// Real Docs app, controlled Google responses. This is not a live Google test. import assert from 'node:assert/strict' import { pathToFileURL } from 'node:url' const playwright = process.env.DOCS_IMPORT_PLAYWRIGHT ? await import(pathToFileURL(process.env.DOCS_IMPORT_PLAYWRIGHT + '/index.mjs')) : await import('playwright') const config = JSON.parse(process.env.DOCS_GOOGLE_IMPORT_TEST) const fixture = Buffer.from(config.fixture, 'base64') const gis = `window.google={accounts:{oauth2:{initTokenClient(c){return{requestAccessToken(){c.callback({access_token:'controlled-google-bearer',scope:'https://www.googleapis.com/auth/drive.file'})}}},hasGrantedAllScopes(r,s){return r.scope===s}}}};` const gapi = `window.gapi={load(name,c){google.picker={Action:{PICKED:'picked',CANCEL:'cancel'},DocsView:class{setMimeTypes(){return this}},PickerBuilder:class{setDeveloperKey(){return this}setAppId(){return this}setOAuthToken(){return this}setOrigin(){return this}addView(){return this}setCallback(fn){this.cb=fn;return this}build(){const cb=this.cb;let el;return{setVisible(){el=document.createElement('button');el.textContent='Select import fixture';el.onclick=()=>cb({action:'picked',docs:[{id:'controlled_file',name:'Import fixture',mimeType:'application/vnd.google-apps.document'}]});document.body.append(el)},dispose(){el?.remove()}}}}};c.callback()}};` const expected = ['Import fixture', 'linked words', 'bold text', 'plain text', 'Table cell'] for (const engine of ['chromium', 'webkit']) { const browser = await playwright[engine].launch() try { const context = await browser.newContext({ viewport: { width: 900, height: 850 } }) const cookies = config.cookies.map(c => ({ name: c.Name, value: c.Value, url: config.origin, httpOnly: c.HttpOnly, sameSite: 'Lax' })) await context.addCookies(cookies) const page = await context.newPage() const violations = [], failures = [] let exports = 0, leaked = false, externalRelationship = false page.on('pageerror', e => failures.push(e.message)) await page.addInitScript(() => document.addEventListener('securitypolicyviolation', e => console.log('IMPORT-CSP:' + e.violatedDirective))) page.on('console', message => { if (message.text().startsWith('IMPORT-CSP:')) violations.push(message.text()) }) page.on('request', request => { if (request.url().startsWith(config.origin) && ((request.postData() || '').includes('controlled-google-bearer') || JSON.stringify(request.headers()).includes('controlled-google-bearer'))) leaked = true if (request.url().startsWith('https://fixture.invalid/')) externalRelationship = true }) await context.route('https://accounts.google.com/gsi/client', r => r.fulfill({ contentType: 'text/javascript', body: gis })) await context.route('https://apis.google.com/js/api.js', r => r.fulfill({ contentType: 'text/javascript', body: gapi })) await context.route('https://www.googleapis.com/drive/v3/files/**', async r => { exports++ assert.equal(r.request().headers().authorization, 'Bearer controlled-google-bearer') await r.fulfill({ headers: { 'Access-Control-Allow-Origin': '*' }, contentType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', body: fixture }) }) await page.goto(config.origin + '/import') await page.waitForFunction(() => !document.querySelector('[data-google-choose]')?.disabled) await page.locator('[data-google-choose]').click() await page.getByRole('button', { name: 'Select import fixture', exact: true }).click() await page.waitForURL(url => url.pathname !== '/import') const editorPath = new URL(page.url()).pathname assert.match(editorPath, /^\/d\/[^/]+$/) const reportURL = config.origin + editorPath + '/import-report' assert.match(await page.locator('body').innerText(), /import/i) assert.match(await page.locator('body').innerText(), /table/i) assert.match(await page.locator('body').innerText(), /link/i) assert.equal(await page.locator('[docs-import-report]').count(), 1) await page.goto(config.origin + editorPath) const editor = page.locator('[docs-text][contenteditable="true"]') try { await editor.waitFor({ state: 'visible', timeout: 30000 }) } catch (cause) { throw new Error(engine + ': editor unavailable; errors=' + JSON.stringify(failures) + '; page=' + (await page.locator('body').innerText()).slice(0, 1500), { cause }) } for (const text of expected) assert((await editor.innerText()).includes(text), 'missing ' + text) assert.match(await editor.locator('strong').innerText(), /bold text/) assert(!(await editor.locator('strong').innerText()).includes('plain text')) assert.equal(await editor.locator('a').count(), 0) const saved = page.waitForResponse(r => r.request().method() === 'POST' && r.url().endsWith('/updates') && r.ok()) await editor.click() await page.keyboard.press('End') await page.keyboard.insertText(' Edited after import.') await saved await page.reload() await page.waitForFunction(() => document.querySelector('[docs-text]')?.textContent.includes('Edited after import.')) await page.goto(reportURL) assert.match(await page.locator('body').innerText(), /table/i) assert.equal(exports, 1) assert.equal(leaked, false) assert.equal(externalRelationship, false) assert.deepEqual(violations, []) assert.deepEqual(failures, []) const plainContext = await browser.newContext({ javaScriptEnabled: false }) await plainContext.addCookies(cookies) const plain = await plainContext.newPage() await plain.goto(config.origin + '/import') assert.equal(await plain.locator('[data-google-choose]').isVisible(), false) await plain.locator('input[type="file"]').setInputFiles({ name: 'scriptless.docx', mimeType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', buffer: fixture }) await plain.locator('form:has(input[type="file"]) button[type="submit"]').click() await plain.waitForURL(url => url.pathname !== '/import') assert.match(await plain.locator('body').innerText(), /table/i) await plainContext.close() await context.close() console.log(engine + ': actual import route, nested text, marks, editable persistence, report reopening and scriptless upload passed') } finally { await browser.close() } }