qwen-code/scripts/tests/export-transcript-document-template.test.js
易良 11e629b3a1
perf(export): split the transcript renderer's embedded CSS into a versioned asset (#11485)
* perf(export): split the transcript renderer's embedded CSS into a versioned asset

The export renderer carried the web-shell component stylesheet as a ~2.3 MB
string literal, so every reader parsed and compiled 4.1 MB of JS (56% of it dead
CSS) before a transcript could render. Lift that literal out at export build
time into a version-pinned, SRI-protected export-transcript-document.css served
from unpkg and loaded via a nonce-bearing <link>, dropping the renderer JS to
~1.83 MB.

The transform is an esbuild onLoad plugin in the web-templates export build that
strips the injected CSS constant from web-shell's dist/transcript.js; web-shell
source and runtime behavior are untouched. The document's fail-closed load-error
path is extended to the stylesheet so a missing CSS asset fails the same way as
a missing renderer.

* fix(export): match the transcript CSS entry on Windows paths too

esbuild hands plugin callbacks the platform-native absolute path, so the
extract-transcript-css `onLoad` filter never matched on Windows: the callback
did not run, `extractedTranscriptCss.css` stayed undefined, and the mandatory
extraction guard below aborted the build. That build is not platform-gated —
`scripts/prepare.js` runs it from `prepare`, so `npm ci` itself would fail on
every Windows contributor and on the windows-latest legs of test_windows and
desktop-release.

Widen the separator to `[\\/]`, keeping the `transcript\.js$` tail so the
barred `web-shell/dist/index.js` package root still does not match. The filter
moves to transcript-css-entry.mjs because build.mjs is a top-level-await script
with no harness — the same reason scripts/sdk-node-exporter-stub.js exists — so
scripts/tests/transcript-css-entry-filter.test.js can pin both separators.

Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
Patrol-Run: qwen-pr-closeout/jmtufhms2u4

* fix(export): latch a stylesheet failure ahead of the parser block

The `<link id="transcript-stylesheet">` sits in `<head>` while the `window`
error listener that catches its failure is registered by an inline script in
`<body>`. Chromium parser-blocks that script on the pending stylesheet, so when
the CSS failure settles first the error event is dispatched with no listener to
receive it: nothing marks the render as failed, both renderComplete guards in
document-main.tsx pass, React mounts the transcript without any of the
component CSS, and the requestAnimationFrame stamps
`data-render-complete="true"`. The reviewer measured this fail-open above
roughly 2.1 MB of document HTML (272 of the 1,000 permitted blocks) for a 404,
an SRI rejection, a truncated body and a destroyed socket alike, and fail-closed
for a *late* failure — so size, not failure kind, decides it.

Latch the failure in `<head>` before the `<link>` is parsed and act on the latch
from the existing body IIFE. The head script only records: `showLoadError()`
writes `document.body.dataset` and `#app`, neither of which exists while the
parser is still in `<head>`. It carries `nonce="__EXPORT_NONCE__"` because the
document CSP allows no inline script, which is safe — `formatters/html.ts:53`
replaces every occurrence. The listener is capture-phase because resource error
events do not bubble.

Not the `link.sheet === null` variant: the reviewer measured `sheet` non-null
for a 404, a truncated body and a destroyed socket, so it only detects SRI
rejection.

scripts/tests/export-transcript-document-template.test.js pins the position,
the nonce, the capture phase and the record-only shape; all five cases go red
against the unpatched template. The behavioural witness (real Chromium, large
document, instant CSS abort) belongs to the playwright transcript gate, which
is out of budget on this host.

Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
Patrol-Run: qwen-pr-closeout/jmtufhms2u4

* fix(scripts): name the missing export renderer assets, pin the CSS gate

The bundle copy became all-or-nothing over two artifacts but its `else` warning
still named only the renderer, so the one new way to reach that branch — a tree
built before the split, then `npm run bundle`d without rebuilding web-templates,
which has the JS and no CSS — told the operator to go looking for a
`export-transcript-document.js` that was sitting right there, and silently
discarded it. List the paths that are actually absent, matching the sibling Web
Shell warning twenty lines above. Stays warn-and-skip: prepare-package.js is the
release gate.

Also pin that release gate. Every fixture that reached `preparePackage` staged
`dist/export-transcript-document.css` unconditionally, so deleting the new
required-path entry left the whole test:scripts lane green; a release built with
`npm ci --ignore-scripts` would then publish documents whose stylesheet 404s on
unpkg for that version. `verifyBundleArtifacts` reports through console.error +
process.exit(1) rather than a throw, so the new case stubs exit instead of
copying the audio-capture sibling's `toThrow` idiom.

Both cases were flip-checked: restoring the old warning text, and deleting the
CSS line from prepare-package.js, each turn their case red.

Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
Patrol-Run: qwen-pr-closeout/jmtufhms2u4

* fix(export): pin the stylesheet-failure id contract and sync the design docs

The <head> latch, the body listener and the <link> each spell
'transcript-stylesheet' independently and nothing compared them, so renaming
either listener's id left the whole suite green while the latch recorded
nothing - reinstating the fail-open the latch was added to close. Derive the id
from the <link> and assert both listeners compare against it. Verified red under
both mutations: latch id -> 'transcript-renderer' (1 failed | 5 passed), and the
mirror with the body listener's id wrong and the latch intact (same).

Both design docs still specified the two shapes the previous round replaced: the
forward-slash-only onLoad filter that never matches on Windows, and the
body-listener-only fail-closed extension. Section 1 now quotes the shipped
TRANSCRIPT_CSS_ENTRY_FILTER and names transcript-css-entry.mjs, section 2
describes the <head> latch (position, nonce, capture phase, record-only),
section 3 names the module-level render guard, and "Files affected" lists the
three omitted files. EN and zh-CN are updated in the same commit.

Also correct the shape-guard comment in build.mjs: the document nonces every
<style> created through document.createElement, so the CSP would not block an
un-stripped duplicate, and a 367-byte regrowth stays inside both byte budgets.
That throw is the only guard on the duplicate-injection path.

Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
Patrol-Run: qwen-pr-closeout/jmtuo29vduf

* fix(export): close out transcript CSS review comments

* fix(export): tighten transcript CSS closeout

Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>

---------

Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
2026-09-10 07:15:32 +00:00

117 lines
4.6 KiB
JavaScript

/**
* @license
* Copyright 2026 Qwen Team
* SPDX-License-Identifier: Apache-2.0
*/
import { readFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { describe, expect, it } from 'vitest';
const root = join(dirname(fileURLToPath(import.meta.url)), '../..');
const template = readFileSync(
join(
root,
'packages',
'web-templates',
'src',
'export-html',
'src',
'document-index.html',
),
'utf8',
);
const STYLESHEET_ID = 'id="transcript-stylesheet"';
/**
* The id the `<link>` actually carries, read back out of the template rather
* than hard-coded. The same literal is spelled in three places — declared on
* the `<link>`, compared by the `<head>` latch, compared by the body listener
* — so deriving it here is what lets one test pin all three against each other.
*/
const STYLESHEET_LINK_ID = /<link[^>]*\bid="([^"]+)"/.exec(template)?.[1];
/** The <head> script that records a stylesheet failure before the <link>. */
function latchScript() {
const latch = template.indexOf('window.__transcriptStyleFailed = true');
expect(latch).toBeGreaterThan(-1);
const start = template.lastIndexOf('<script', latch);
const end = template.indexOf('</script>', latch);
expect(start).toBeGreaterThan(-1);
expect(end).toBeGreaterThan(latch);
return template.slice(start, end);
}
// The split stylesheet fails closed through a `window` error listener that the
// body script registers. Chromium parser-blocks that script on the pending
// stylesheet, so on a large document a CSS failure that settles first is
// dispatched while no listener exists yet: nothing marks the render as failed,
// both document-main.tsx guards pass, and the transcript renders completely
// unstyled while stamping data-render-complete="true". The head latch is what
// closes that window, and its *position* is the whole fix — these assertions
// pin the position, the CSP nonce and the record-only shape.
describe('export transcript document template', () => {
it('latches stylesheet failures in <head>, ahead of the <link>', () => {
const stylesheet = template.indexOf(STYLESHEET_ID);
const bodyStart = template.indexOf('<body>');
const latchStart = template.indexOf(
'window.__transcriptStyleFailed = true',
);
expect(stylesheet).toBeGreaterThan(-1);
expect(bodyStart).toBeGreaterThan(-1);
expect(latchStart).toBeGreaterThan(-1);
expect(template.lastIndexOf('<script', latchStart)).toBeLessThan(
stylesheet,
);
expect(latchStart).toBeLessThan(bodyStart);
});
it('nonces the latch script, because the CSP allows no inline script', () => {
expect(latchScript()).toContain('nonce="__EXPORT_NONCE__"');
expect(template).toMatch(/script-src 'nonce-__EXPORT_NONCE__'/);
expect(template).not.toMatch(/script-src[^;]*'unsafe-inline'/);
expect(template).not.toMatch(/script-src[^;]*'unsafe-hashes'/);
});
it('listens for error in the capture phase, which <link> failures need', () => {
// Resource error events do not bubble, so a bubble-phase listener on window
// never sees the stylesheet failure.
expect(latchScript()).toMatch(
/window\.addEventListener\(\s*'error',[\s\S]*?\n\s*true,?\s*\);/,
);
});
it('only records the failure while the parser is still in <head>', () => {
// showLoadError() writes document.body.dataset and #app; neither exists
// before the parser leaves <head>, so the latch must not call it.
const script = latchScript();
expect(script).not.toContain('document.body');
expect(script).not.toContain('showLoadError');
});
it('acts on the latch from the body script', () => {
const consumed = template.indexOf('if (window.__transcriptStyleFailed)');
expect(consumed).toBeGreaterThan(template.indexOf('<body>'));
expect(consumed).toBeGreaterThan(template.indexOf(STYLESHEET_ID));
expect(template.slice(consumed, consumed + 120)).toContain(
'showLoadError();',
);
});
it('compares the failing element id both listeners agree on', () => {
// Without this, one character of drift is invisible: the position, nonce,
// capture-phase and record-only assertions above all still pass if either
// listener compares against a different id, and the latch then records
// nothing — which is R1-2 reinstated with a green suite.
expect(STYLESHEET_LINK_ID).toBe('transcript-stylesheet');
expect(latchScript()).toContain(
`event.target.id === '${STYLESHEET_LINK_ID}'`,
);
const bodyListener = template.slice(template.indexOf('<body>'));
expect(bodyListener).toContain(
`event.target.id === '${STYLESHEET_LINK_ID}'`,
);
});
});