diff --git a/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.i18n.yaml b/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.i18n.yaml index f85c64d77c..c42ed69bb7 100644 --- a/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.md -2026-07-23-client-plugin-loading-model.md: 02dadf6e1dc1f2c4fd99907446bc6d07b35ba471 -2026-07-23-client-plugin-loading-model.zh.md: eaf10d32a6b51189867d2a52f76dc190380cbca0 +2026-07-23-client-plugin-loading-model.md: dfa9f34276f20ffa99541db1544539d693313a2f +2026-07-23-client-plugin-loading-model.zh.md: 68fe9b912c60aceb2ecea315ed0121f9f96c1ecf diff --git a/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.md b/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.md index 02dadf6e1d..dfa9f34276 100644 --- a/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.md +++ b/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.md @@ -14,7 +14,7 @@ The browser client runs the same cordis plugin mechanism, so it needs the same s Conventional frontend engineering digests all dependencies at build time: one bundle, externals resolved by the bundler, nothing left to manage at runtime. Runtime module management on top of that is the unusual requirement here. The client therefore splits into two layers: the upper layer is cordis plugin loading through the same vendored Loader, and the lower layer is module-granular dependency management — `dsh-client-modules`. -The lower layer supplies four capabilities: externals (the platform list), remote arrival (same-origin external classic scripts plus lazy factory registration), versioning (content-hash revs), and hot update (invalidate/prefetch). +The lower layer supplies four capabilities: externals (the platform list), remote arrival (same-origin external classic scripts plus lazy factory registration), immutable revisioned delivery, and hot update (invalidate/prefetch). Plugin bundles are built independently outside Vite's module graph. Feeding response text into an inline script leaves the browser with a dynamic source execution: no standard source-map chain connects the network resource, generated bundle, and TypeScript/TSX source, so performance profiles and stacks stop at generated `client.js`; the module system must also buffer the complete source and split one arrival responsibility across fetch and execute transport boundaries. @@ -28,7 +28,7 @@ The first-generation client loader (`createClientLoader`) hand-wrote both layers The [client shell layering note](2026-08-15-client-shells-and-dynamic-packages.md) defines the current static and dynamic package sets and the import rules between them. The loading machinery treats every `dsh.client` package as a host-graph row with one ordinary `lib/client.js` factory bundle. Its declaration carries Cordis `inject` edges, synchronous module-table `external` requests, and the optional `immediately` prefetch mark; the composing app owns only the mounted roster. -The web kernel remains framework-free and imports no dynamic package value. Modules is itself a dynamic row, but the host parser delivers its ordinary factory before the Vite main module. The HTML-installed `__ModuleLoader__` facade uses that factory to construct the module system when the kernel calls `create()`. Runtime arrives through the same pending queue; static React, Cordis, and UI library identities come from the shell seed. +The web kernel remains framework-free and imports no dynamic package value. Modules is itself a dynamic row, but the host parser delivers its factory before the Vite main module. The HTML-installed `__ModuleLoader__` facade uses that factory to construct the module system when the kernel calls `create()`. Every other dynamic row arrives through the application batch; static React, Cordis, and UI library identities come from the shell seed. ### One module system, one plugin governor @@ -38,13 +38,13 @@ The browser mirrors the host's division of labor. `dsh-client-modules` (`ClientM The vendored Loader consumes the module system through its `internal` contract — the only call site is `tree.import` — and owns everything entry-shaped: entry creation, fiber activation through cordis service waiting (PENDING until injected services exist, cascading when a service is provided), update/refresh, teardown. The governance code is byte-identical to the host side, per vendor policy. Browserization is compile-time mapping in the shell's vite config: a `node:module` stub alias plus `process.*` defines make `ModuleLoader.fromInternal()` return undefined — exactly the empty slot the shell fills. The module system mounts as `ctx.modules`. -### External-script arrival and source maps +### Batched external-script arrival and source maps -Each graph row's `url` goes to a same-origin external classic `') + const applicationAt = html.indexOf( + ``, + ) + const bootstrapAt = html.indexOf(``) const graphAt = html.indexOf('globalThis["__DSH_BOOT__"] = ') const entryAt = html.indexOf('') - expect(html).not.toContain('') - expect([facadeAt, modulesAt, graphAt, entryAt]).toEqual([...new Set([ - facadeAt, modulesAt, graphAt, entryAt, + expect([facadeAt, applicationAt, bootstrapAt, graphAt, entryAt]).toEqual([...new Set([ + facadeAt, applicationAt, bootstrapAt, graphAt, entryAt, ])].sort((a, b) => a - b)) target.load({ id: MODULES_ID, factory: () => modulesClient }) - target.load({ id: UI_RENDERER_ID, factory: () => ({ marker: 'ui-renderer' }) }) - const system = target.create({ boot: graph, staticModules: {} }) + const system = target.create({ + boot: graph, + staticModules: {}, + loadBundle: async (url) => { + expect(url).toBe(APPLICATION_URL) + target.load({ id: UI_RENDERER_ID, factory: () => ({ marker: 'ui-renderer' }) }) + }, + }) expect(target.mode).toBe('live') expect(target.pendingQueue).toEqual([]) @@ -209,40 +258,201 @@ describe('client bundle activation', () => { expect(String(thrown)).not.toContain('pnpm run build') }) + it('omits a torn or malformed source map without blocking composition', async () => { + const packageName = '@fixture/malformed-source-map' + const clientPath = writePackage(packageName) + mkdirSync(dirname(clientPath), { recursive: true }) + writeFileSync(clientPath, 'module.exports = {}\n') + writeFileSync(`${clientPath}.map`, '{') + const torn = constructWithRoute([packageName]) + const tornRow = torn.service.graph().entries[0]! + expect((await routeRequest(torn.route, tornRow.url)).body.toString('utf8')) + .not.toContain('sourceMappingURL') + expect((await routeRequest(torn.route, `${torn.service.graph().batches[0]!.url}.map`)).status).toBe(404) + + writeFileSync(`${clientPath}.map`, '{"version":3,"sources":[null]}\n') + expect(() => construct([packageName])).not.toThrow() + }) + + it('retains one prior immutable batch generation across rebuild recomposition', async () => { + const packageName = '@fixture/batch-rebuild-race' + const clientPath = writePackage(packageName) + mkdirSync(dirname(clientPath), { recursive: true }) + writeFileSync(clientPath, 'module.exports = { generation: 1 }\n') + const { service, route } = constructWithRoute([packageName]) + const first = service.graph().batches[0]!.url + const firstSize = service.artifactBaseline(packageName)!.size + + writeFileSync(clientPath, 'module.exports = { generation: 200 }\n') + service.rebuilt(packageName) + const second = service.graph().batches[0]!.url + expect(second).not.toBe(first) + expect(service.artifactBaseline(packageName)!.size).toBeGreaterThan(firstSize) + expect((await routeRequest(route, first)).status).toBe(200) + expect((await routeRequest(route, second)).status).toBe(200) + + writeFileSync(clientPath, 'module.exports = { generation: 3 }\n') + service.rebuilt(packageName) + const third = service.graph().batches[0]!.url + expect((await routeRequest(route, first)).status).toBe(404) + expect((await routeRequest(route, second)).status).toBe(200) + expect((await routeRequest(route, third)).status).toBe(200) + }) + + it('assigns opaque startup revisions instead of deriving them from artifact content', () => { + const firstName = '@fixture/startup-revision-first' + const secondName = '@fixture/startup-revision-second' + writeBuiltPackage(firstName, {}) + writeBuiltPackage(secondName, {}) + + const service = construct([firstName, secondName]) + const [first, second] = service.graph().entries + const firstMatch = /^(?[a-f\d]{16})-(?\d+)$/.exec(first!.rev) + const secondMatch = /^(?[a-f\d]{16})-(?\d+)$/.exec(second!.rev) + expect(firstMatch?.groups).toMatchObject({ sequence: '0' }) + expect(secondMatch?.groups).toMatchObject({ nonce: firstMatch?.groups?.nonce, sequence: '1' }) + const firstPath = service.clientPath(firstName)! + const firstStat = statSync(firstPath) + expect(service.artifactBaseline(firstName)).toEqual({ + path: firstPath, + mtimeMs: firstStat.mtimeMs, + size: firstStat.size, + mapMtimeMs: null, + mapSize: null, + }) + expect(service.artifactBaseline('@fixture/unknown')).toBeUndefined() + }) + it('serves the source map beside a registered client bundle', async () => { const packageName = '@fixture/source-map' const clientPath = writePackage(packageName) mkdirSync(dirname(clientPath), { recursive: true }) - writeFileSync(clientPath, 'module.exports = {}\n') - const map = '{"version":3,"sources":["src/client/index.tsx"]}\n' + writeFileSync(clientPath, 'module.exports = {}\n//# sourceMappingURL=client.js.map') + const map = '{"version":3,"names":[],"mappings":"AAAA","sources":["../../../packages/client/demo/src/index.tsx","https://cdn.example.test/library.js"]}\n' writeFileSync(`${clientPath}.map`, map) - const { route } = constructWithRoute([packageName]) - let status = 0 - let headers: Record | undefined - let body = '' - const response = { - writeHead(nextStatus: number, nextHeaders?: Record) { - status = nextStatus - headers = nextHeaders - return response - }, - end(chunk?: Uint8Array) { - body = chunk === undefined ? '' : Buffer.from(chunk).toString('utf8') - return response - }, - } as unknown as ServerResponse - - await route.handler({ - method: 'GET', - url: `/plugins/${packageName}/client.js.map`, - } as IncomingMessage, response) - - expect(status).toBe(200) - expect(headers).toEqual({ + const { service, route } = constructWithRoute([packageName]) + const row = service.graph().entries[0]! + const individualScript = await routeRequest(route, row.url) + expect(individualScript.body.toString('utf8')).toContain(`sourceMappingURL=client.js.map?rev=${row.rev}`) + const individual = await routeRequest(route, row.url.replace('/client.js?', '/client.js.map?')) + expect(individual.status).toBe(200) + expect(individual.headers).toEqual({ 'content-type': 'application/json; charset=utf-8', - 'cache-control': 'no-cache', + 'cache-control': 'public, max-age=31536000, immutable', }) - expect(body).toBe(map) + expect(individual.body.toString('utf8')).toBe(map) + + const batch = service.graph().batches[0]! + expect(batch).toMatchObject({ phase: 'application', entries: [packageName] }) + const batchScript = await routeRequest(route, batch.url) + expect(batchScript.status).toBe(200) + expect(batchScript.headers?.['cache-control']).toBe('public, max-age=31536000, immutable') + expect(batchScript.body.toString('utf8')).toContain('//# sourceMappingURL=client.js.map') + expect(batchScript.body.toString('utf8')).not.toContain('sourceMappingURL=client.js.map?rev=') + expect((await routeRequest(route, batch.url, 'HEAD')).body).toHaveLength(0) + expect((await routeRequest(route, batch.url, 'POST')).status).toBe(405) + const batchMap = await routeRequest(route, `${batch.url}.map`) + const parsedBatchMap = JSON.parse(batchMap.body.toString('utf8')) as unknown + const parsedIndividualMap = JSON.parse(map) as Record + expect(parsedBatchMap).toMatchObject({ + version: 3, + file: 'client.js', + sections: [{ + offset: { line: 0, column: 0 }, + map: { + ...parsedIndividualMap, + sources: ['/packages/client/demo/src/index.tsx', 'https://cdn.example.test/library.js'], + }, + }], + }) + expect((await routeRequest(route, `${row.url}&stale=1`.replace(`rev=${row.rev}`, 'rev=stale'))).status).toBe(404) + + writeFileSync(`${clientPath}.map`, '{"version":3,"names":[],"mappings":"AAAA","sources":["src/changed.tsx"]}\n') + const nextRev = service.rebuilt(packageName) + expect(nextRev).not.toBe(row.rev) + const nextMap = await routeRequest(route, `/plugins/${packageName}/client.js.map?rev=${String(nextRev)}`) + expect(JSON.parse(nextMap.body.toString('utf8'))).toMatchObject({ sources: ['src/changed.tsx'] }) + }) + + it('applies sourceRoot before relocating absolute-looking section sources', async () => { + const packageName = '@fixture/source-root' + const clientPath = writePackage(packageName) + mkdirSync(dirname(clientPath), { recursive: true }) + writeFileSync(clientPath, 'module.exports = {}\n') + writeFileSync(`${clientPath}.map`, JSON.stringify({ + version: 3, + names: [], + mappings: 'AAAA', + sourceRoot: '../root', + sources: ['/absolute.ts'], + })) + const { service, route } = constructWithRoute([packageName]) + const response = await routeRequest(route, `${service.graph().batches[0]!.url}.map`) + const map = JSON.parse(response.body.toString('utf8')) as { + sections: { map: { sourceRoot?: string; sources: string[] } }[] + } + expect(map.sections[0]?.map).toMatchObject({ + sources: ['/plugins/@fixture/root/absolute.ts'], + }) + expect(map.sections[0]?.map).not.toHaveProperty('sourceRoot') + }) + + it('maps a non-zero second batch section through a standard source-map consumer', async () => { + const firstName = '@fixture/offset-first' + const secondName = '@fixture/offset-second' + const firstPath = writePackage(firstName) + const secondPath = writePackage(secondName) + for (const [path, source] of [ + [firstPath, '../../../packages/demo/first.ts'], + [secondPath, '../../../packages/demo/second.ts'], + ] as const) { + mkdirSync(dirname(path), { recursive: true }) + writeFileSync(path, 'window.first = true\nwindow.second = true\n') + writeFileSync(`${path}.map`, JSON.stringify({ + version: 3, + names: [], + mappings: 'AAAA', + sources: [source], + sourcesContent: ['export {}\n'], + })) + } + const { service, route } = constructWithRoute([firstName, secondName]) + const response = await routeRequest(route, `${service.graph().batches[0]!.url}.map`) + const payload = JSON.parse(response.body.toString('utf8')) as ConstructorParameters[0] + const sections = (payload as unknown as { + sections: { offset: { line: number; column: number } }[] + }).sections + expect(sections.map(section => section.offset)).toEqual([ + { line: 0, column: 0 }, + { line: 3, column: 0 }, + ]) + const consumer = new SourceMap(payload) + expect(consumer.findEntry(0, 0)).toMatchObject({ originalSource: '/packages/demo/first.ts' }) + expect(consumer.findEntry(3, 0)).toMatchObject({ originalSource: '/packages/demo/second.ts' }) + }) + + it('keeps a later source-map section usable when an earlier bundle has no map', async () => { + const unmappedName = '@fixture/unmapped-first' + const mappedName = '@fixture/mapped-second' + const unmappedPath = writePackage(unmappedName) + const mappedPath = writePackage(mappedName) + mkdirSync(dirname(unmappedPath), { recursive: true }) + mkdirSync(dirname(mappedPath), { recursive: true }) + writeFileSync(unmappedPath, 'window.unmapped = true\n') + writeFileSync(mappedPath, 'window.mapped = true\n') + writeFileSync(`${mappedPath}.map`, JSON.stringify({ + version: 3, + names: [], + mappings: 'AAAA', + sources: ['../../../packages/demo/mapped.ts'], + sourcesContent: ['export {}\n'], + })) + + const { service, route } = constructWithRoute([unmappedName, mappedName]) + const response = await routeRequest(route, `${service.graph().batches[0]!.url}.map`) + const payload = JSON.parse(response.body.toString('utf8')) as ConstructorParameters[0] + const consumer = new SourceMap(payload) + expect(consumer.findEntry(2, 0)).toMatchObject({ originalSource: '/packages/demo/mapped.ts' }) }) }) diff --git a/packages/client/tsdown.client.ts b/packages/client/tsdown.client.ts index c21885f78e..5728d345da 100644 --- a/packages/client/tsdown.client.ts +++ b/packages/client/tsdown.client.ts @@ -94,7 +94,8 @@ function browserSourcePath(source: string, sourcemapPath: string): string { * earlier Host pass. A package-level tsdown.config.ts REPLACES the root * workspace layout, so the lib half must be restated here — dropping it leaves * the package without lib/index.js and the host Loader cannot import its node - * half. + * half. The Client build consumes `lib/types` and chains those tsc maps, with + * original source content, into the standalone plugin map. * @param id - plugin id (package name), stamped into the __ModuleLoader__.load * handoff and onto the injected style tags. * @param libEntry - node-half entries, spelled at the call site so the @@ -267,6 +268,7 @@ function staticLinkedConfig(id: string, entry: string, outputName = basename(ent // The shell compiles this artifact, so its map is the only path from a // browser stack frame back to the TSX (tsc emits the lib/types half). sourcemap: true, + outputOptions: { sourcemapExcludeSources: false }, plugins: [{ // Contract 1. `pre` because tsdown's own deps plugin would otherwise // resolve and inline every specifier missing from the npm production @@ -281,18 +283,7 @@ function staticLinkedConfig(id: string, entry: string, outputName = basename(ent return isBareSpecifier(source) ? { id: source, external: true } : null }, }, - }, { - // Contract 3. Rolldown does not read the `//# sourceMappingURL` of its - // inputs, so each tsc map is handed over as that module's map and - // composed into the bundle map; without it frames stop at the emitted - // lib/types JavaScript instead of reaching the TSX. - name: 'dsh-tsc-sourcemap', - async load(id: string) { - if (!id.includes(TYPES_MARKER) || !id.endsWith('.js') || !existsSync(`${id}.map`)) return null - const code = await readFile(id, 'utf8') - return { code: code.replace(SOURCEMAP_COMMENT, ''), map: await readFile(`${id}.map`, 'utf8') } - }, - }, { + }, tscSourceMapPlugin(), { // Contract 4. The import survives verbatim and the sheet lands beside the // JavaScript, so the shell's CSS Modules pipeline sees a real stylesheet. name: 'dsh-css-asset', @@ -495,7 +486,7 @@ function clientConfig(id: string, entry: string): UserConfig { + '(type-only imports are erased and never reach this gate)', ) }, - }, { + }, tscSourceMapPlugin(), { name: 'dsh-css-modules-inline', resolveId(source: string, importer: string | undefined) { if (!source.endsWith('.module.css')) return null @@ -554,6 +545,7 @@ function clientConfig(id: string, entry: string): UserConfig { }], outputOptions: { entryFileNames: 'client.js', + sourcemapExcludeSources: false, // The map is served from /plugins//client.js.map. The // browser resolves its local sources back into URLs that mirror the // /packages///src directories; sourcesContent keeps them usable @@ -566,6 +558,38 @@ function clientConfig(id: string, entry: string): UserConfig { } } +/** Chain tsc's emitted maps into any Client bundle that consumes `lib/types`. */ +function tscSourceMapPlugin() { + return { + name: 'dsh-tsc-sourcemap', + async load(id: string) { + if (!id.includes(TYPES_MARKER) || !id.endsWith('.js') || !existsSync(`${id}.map`)) return null + const code = await readFile(id, 'utf8') + const mapPath = `${id}.map` + const map = JSON.parse(await readFile(mapPath, 'utf8')) as { + sourceRoot?: unknown + sources?: unknown + sourcesContent?: unknown + [key: string]: unknown + } + if (!Array.isArray(map.sources) || map.sources.some(source => typeof source !== 'string')) { + throw new Error(`client sourcemap: ${mapPath} has invalid sources`) + } + const sources = map.sources as string[] + if ( + !Array.isArray(map.sourcesContent) + || map.sourcesContent.length !== sources.length + || map.sourcesContent.some(source => typeof source !== 'string') + ) { + const sourceRoot = typeof map.sourceRoot === 'string' ? map.sourceRoot : '' + map.sourcesContent = await Promise.all(sources.map(async source => + await readFile(resolvePath(dirname(mapPath), sourceRoot, source), 'utf8'))) + } + return { code: code.replace(SOURCEMAP_COMMENT, ''), map } + }, + } +} + /** Path segment separating a package's tsc output from the sources it was emitted from. */ const TYPES_MARKER = `${sep}lib${sep}types${sep}` diff --git a/packages/client/web/README.i18n.yaml b/packages/client/web/README.i18n.yaml index e63b485800..855acd9bc7 100644 --- a/packages/client/web/README.i18n.yaml +++ b/packages/client/web/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/client/web/README.md -README.md: 3208cb202dd9c101f1ab5f3936aac50fae35ab1c -README.zh.md: c6be7daf8a86660627095063590b063b80e14839 +README.md: c95c5601b6e61d434e585bbf1887135fe177efb6 +README.zh.md: 5335760011f2e801503011d49240e08a7638981e diff --git a/packages/client/web/README.md b/packages/client/web/README.md index 3208cb202d..c95c5601b6 100644 --- a/packages/client/web/README.md +++ b/packages/client/web/README.md @@ -2,7 +2,7 @@ English | [中文](README.zh.md) -Web boot kernel: `new AppWebEntry(el, seams?).run()` mounts the client through two stages. The module stage calls the Host-installed `window.__ModuleLoader__.create()` with `window.__DSH_BOOT__`, the shell's static modules, and any test transport override; the facade returns the constructed module system and parsed manifest after adopting parser-preloaded registrations. This package then prefetches the `immediately` tier. The plugin stage mounts the vendored Cordis Loader, injects that module system through the Loader's `internal` interface, creates every graph entry uniformly, and waits for every fiber to become ACTIVE. It then hands the marked boot DOM to the dynamic UI renderer's `ctx.uiRenderer.mount(el)` operation; the renderer hydrates that DOM before switching to the complete UI. The Host owns the graph, parser preloads, and facade; AppWebEntry does not know the bootstrap package id or parse the wire format. +Web boot kernel: `new AppWebEntry(el, seams?).run()` mounts the client through two stages. The module stage calls the Host-installed `window.__ModuleLoader__.create()` with `window.__DSH_BOOT__`, the shell's static modules, and any test transport override; the facade returns the constructed module system and parsed manifest after adopting the parser-loaded bootstrap batch. This package then prefetches the `immediately` tier, whose shared application-batch URL executes once. The plugin stage mounts the vendored Cordis Loader, injects that module system through the Loader's `internal` interface, creates every graph entry uniformly, and waits for every fiber to become ACTIVE. It then hands the marked boot DOM to the dynamic UI renderer's `ctx.uiRenderer.mount(el)` operation; the renderer hydrates that DOM before switching to the complete UI. The Host owns the graph, batch preload, and facade; AppWebEntry does not know the bootstrap package id or parse the wire format. The boot page uses plain DOM and local CSS, so client-bundle and plugin-activation failures remain visible. Its fallback fonts and colors match the theme tokens that arrive during loading. Fiber updates retain one spinner node and grow its CSS arc as entries first become active; hydration preserves that node and its animation phase until the application commit. React mounting, slot rendering, and application assembly live in [`ui-renderer`](../ui-renderer/README.md); [`ui-layout`](../ui-layout/README.md) owns the assembled browser-title projection. The modules bundle caches its own materialized exports and provides the closed-over system when its ordinary graph entry activates; Cordis service waiting makes graph-row creation order independent from that activation. diff --git a/packages/client/web/README.zh.md b/packages/client/web/README.zh.md index c6be7daf8a..5335760011 100644 --- a/packages/client/web/README.zh.md +++ b/packages/client/web/README.zh.md @@ -2,7 +2,7 @@ [English](README.md) | 中文 -Web 启动内核:`new AppWebEntry(el, seams?).run()` 分两个阶段挂载客户端。模块阶段调用 Host 安装的 `window.__ModuleLoader__.create()`,传入 `window.__DSH_BOOT__`、外壳静态模块以及可选测试传输覆盖;facade 接纳 parser 预载的 registration 后返回构造好的模块系统与已解析 manifest。本包随后预取 `immediately` 层级。插件阶段挂载仓库内置的 Cordis Loader,通过 Loader 的 `internal` 接口注入该模块系统,统一创建全部图 entry,并等待每个 fiber 进入 ACTIVE。随后它把带标记的启动 DOM 交给动态 UI 渲染器的 `ctx.uiRenderer.mount(el)` 操作;渲染器先 hydrate 该 DOM,再切换到完整 UI。Graph、parser preload 与 facade 归 Host 所有;AppWebEntry 不感知 bootstrap package id,也不解析 wire 格式。 +Web 启动内核:`new AppWebEntry(el, seams?).run()` 分两个阶段挂载客户端。模块阶段调用 Host 安装的 `window.__ModuleLoader__.create()`,传入 `window.__DSH_BOOT__`、外壳静态模块以及可选测试传输覆盖;facade 接纳 parser 已加载的 bootstrap 批次后返回构造好的模块系统与已解析 manifest。本包随后预取 `immediately` 层级,其共享的 application 批次 URL 只执行一次。插件阶段挂载仓库内置的 Cordis Loader,通过 Loader 的 `internal` 接口注入该模块系统,统一创建全部图 entry,并等待每个 fiber 进入 ACTIVE。随后它把带标记的启动 DOM 交给动态 UI 渲染器的 `ctx.uiRenderer.mount(el)` 操作;渲染器先 hydrate 该 DOM,再切换到完整 UI。Graph、批次 preload 与 facade 归 Host 所有;AppWebEntry 不感知 bootstrap package id,也不解析 wire 格式。 启动页只使用原生 DOM 与本地 CSS,因此客户端 bundle 或插件激活失败时仍能显示。其回退字体和颜色与加载期间到达的主题 token 一致。fiber 更新会保留同一个 spinner 节点,并在 entry 首次进入 active 时增长其 CSS 圆弧;hydrate 会继续保留该节点及其动画相位,直到应用提交。React 挂载、slot 渲染和应用组装位于 [`ui-renderer`](../ui-renderer/README.zh.md);[`ui-layout`](../ui-layout/README.zh.md) 拥有组装后的浏览器标题投影。Modules bundle 会缓存自身已物化导出,并在其普通图 entry 激活时提供闭包中的系统;Cordis service 等待使图 row 创建顺序不依赖该激活时点。 diff --git a/packages/client/web/tests/boot.client.spec.ts b/packages/client/web/tests/boot.client.spec.ts index def708d2c5..34b13d40ad 100644 --- a/packages/client/web/tests/boot.client.spec.ts +++ b/packages/client/web/tests/boot.client.spec.ts @@ -80,7 +80,11 @@ describe('bootstrap failure rendering', () => { await expectBootFailure(() => { installFacade() const duplicate = { id: 'duplicate', url: '/duplicate/client.js', rev: '1' } - win.__DSH_BOOT__ = { rev: 'graph', entries: [duplicate, duplicate] } + win.__DSH_BOOT__ = { + rev: 'graph', + entries: [duplicate, duplicate], + batches: [{ phase: 'application', url: '/batch.js', rev: 'batch', entries: ['duplicate'] }], + } }, 'duplicate graph entry "duplicate"') }) }) @@ -102,50 +106,54 @@ describe('plugin activation', () => { { id: 'provider', url: '/provider.js', rev: '1' }, { id: 'renderer', url: '/renderer.js', rev: '1' }, ] - win.__DSH_BOOT__ = { rev: 'graph', entries } - target.load({ - id: 'runtime', - factory: require => ({ - apply: () => {}, - marker: (require(PROVIDER_CLIENT_ID) as { marker: string }).marker, - }), - }) + const applicationUrl = '/application.js' + win.__DSH_BOOT__ = { + rev: 'graph', + entries, + batches: [{ phase: 'application', url: applicationUrl, rev: 'batch', entries: entries.map(row => row.id) }], + } const loaded: string[] = [] - const registrations = new Map([ - ['/consumer.js', { + const registrations: ClientBundleRegistration[] = [ + { id: 'consumer', factory: require => ({ apply: () => { expect((require(RUNTIME_CLIENT_ID) as { marker: string }).marker).toBe('provider') }, }), - }], - ['/provider.js', { + }, + { id: 'provider', factory: () => ({ apply: () => {}, marker: 'provider' }), - }], - ['/renderer.js', { + }, + { + id: 'runtime', + factory: require => ({ + apply: () => {}, + marker: (require(PROVIDER_CLIENT_ID) as { marker: string }).marker, + }), + }, + { id: 'renderer', factory: () => ({ apply: (ctx: Context) => { ctx.reflect.provide('uiRenderer', { mount: () => () => {} }) }, }), - }], - ]) + }, + ] transportGlobal.__DSH_TRANSPORT__ = { loadBundle: async (url) => { loaded.push(url) - const registration = registrations.get(url) - if (registration === undefined) throw new Error(`missing fixture registration ${url}`) - target.load(registration) + if (url !== applicationUrl) throw new Error(`missing fixture batch ${url}`) + for (const registration of registrations) target.load(registration) }, } const entry = new AppWebEntry(container) await entry.run() - expect(loaded).toEqual(['/provider.js', '/consumer.js', '/renderer.js']) + expect(loaded).toEqual([applicationUrl]) await entry.dispose() }) @@ -159,7 +167,16 @@ describe('plugin activation', () => { { id: MODULES_ID, url: '/modules.js', rev: '1' }, { id: 'renderer', url: '/renderer.js', rev: '1' }, ] - win.__DSH_BOOT__ = { rev: 'graph', entries } + win.__DSH_BOOT__ = { + rev: 'graph', + entries, + batches: [{ + phase: 'application', + url: '/application.js', + rev: 'batch', + entries: entries.map(row => row.id), + }], + } const registrations = new Map([ ['/consumer.js', { id: 'consumer', @@ -188,9 +205,8 @@ describe('plugin activation', () => { ]) const entry = new AppWebEntry(container, { loadBundle: async (url) => { - const registration = registrations.get(url) - if (registration === undefined) throw new Error(`missing fixture registration ${url}`) - target.load(registration) + if (url !== '/application.js') throw new Error(`missing fixture batch ${url}`) + for (const registration of registrations.values()) target.load(registration) }, }) diff --git a/packages/experimental/webworker-runtime/README.i18n.yaml b/packages/experimental/webworker-runtime/README.i18n.yaml index d0d0d13a6e..2da19ae9e3 100644 --- a/packages/experimental/webworker-runtime/README.i18n.yaml +++ b/packages/experimental/webworker-runtime/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/experimental/webworker-runtime/README.md -README.md: 3e9b4fffe0b97a97adf218aa12fd1f4342d3bc6c -README.zh.md: 2552c659d1b735b0cf28b9b0d0808276d31d0a2a +README.md: f8789f8e82005c15cd38cbe77832e486d4a44b9b +README.zh.md: e89ae7fd1e6b5d9ad9aa68edecfd92a81dcaf9b9 diff --git a/packages/experimental/webworker-runtime/README.md b/packages/experimental/webworker-runtime/README.md index 3e9b4fffe0..f8789f8e82 100644 --- a/packages/experimental/webworker-runtime/README.md +++ b/packages/experimental/webworker-runtime/README.md @@ -9,7 +9,7 @@ Three artifacts from one tsdown pipeline: - **`lib/index.js` (assembly library)** — `createWorkerHost`/`startWorkerHost` mount the base image and any ordered data overlays (`storage/`), install the module loader (`module-system/`) and the `process` shim, boot the tree through the image's own `dsh-app-boot`, and hand the tunnel its serving seams. Overlays may replace files only under `home/` and `workspace/`; they cannot replace the base manifest, configuration, or modules. The image layout contract (`image-layout.ts`: virtual root, config/manifest paths, empty directories, the `lowered` wrapper-contract gate) is shared with the packer. Boot patches force the deployment-shaped rows: frontend serving off, JSONL session logs on the plaintext path, preset roots onto the image's `config/agent-presets`. - **`lib/worker.js` (worker bundle)** — the assembly plus this package's Node-compatibility layer as one self-contained ES module. The module proxy table (`module-proxies.ts`) is the only platform fork: `node:*` builtins over VFS/tunnel/browser primitives, structural stubs that fail loud on the console for what a browser cannot do, and native/binary package replacements. `node:module` supplies `createRequire().resolve` and `.resolve.paths()` over the image package root, so unchanged packages can discover manifests without evaluating their modules. VFS mutations drive `node:fs` callback, polling, and promise watchers; open descriptors retain file identity and access mode across rename, replacement, and unlink; `readable-stream` supplies the stream state machine used by file streams and unchanged image packages such as Chokidar and readdirp. AsyncLocalStorage carries sync-stack causality across `await` through the snapshot/restore faces the pack-time lowering injects. The worker holds no compiler: an image the packer did not lower is refused at mount ([note](../../../.agents/notes/implemented/architecture/2026-08-20-webworker-pack-lowering-and-preview.md)). - **`src/shell/` (the worker's own process layer)** — a browser worker cannot fork, so `node:child_process` is not a stub but an implementation: `spawn` starts the command in its own Web Worker — this same bundle, told by its first frame to be a shell process — and reports it through the `ChildProcess` surface the subprocess service consumes. The command runs off the host's thread, `SIGKILL` terminates it whatever it is doing, and it reaches the VFS only by message (the host serves those frames). Worker platform executables preserve native-package protocols such as Landlock without replacing their JavaScript packages or coupling their implementations to `node:child_process`; ordinary commands use the package's evaluator and coreutils command table. The grammar is `@yarnpkg/parsers`' `parseShell`, while `execSync`/`fork` still refuse because they need a real process. -- **`lib/client.js` (page half)** — startup has two independent stages. `chooseWorkerHostSource({ image?, fixtureManifest? })` optionally owns the boot barrier and fixture manifest: without `preview-fixture` it waits at the source chooser, while a valid query selects directly; either path returns ordered overlays. `connectWorkerHost(worker, { image?, overlays? })` remains the public base-runtime connector; callers that skip the chooser get an empty overlay list. `apps/web` invokes both and supplies its statically bundled Worker. The opening `init` frame carries the base and ordered overlay URLs, the boot payload delivers the structured index-injection table, and `applyIndexInjections` executes it before the shell entry runs. The tunnel exposes fetch-shaped transport, the API client, and `loadBundle` for the shell's boot seam. +- **`lib/client.js` (page half)** — startup has two independent stages. `chooseWorkerHostSource({ image?, fixtureManifest? })` optionally owns the boot barrier and fixture manifest: without `preview-fixture` it waits at the source chooser, while a valid query selects directly; either path returns ordered overlays. `connectWorkerHost(worker, { image?, overlays? })` remains the public base-runtime connector; callers that skip the chooser get an empty overlay list. `apps/web` invokes both and supplies its statically bundled Worker. The opening `init` frame carries the base and ordered overlay URLs, the boot payload delivers the structured index-injection table, and `applyIndexInjections` executes it before the shell entry runs. Script preload rows are advisory and skipped because `/plugins` resources resolve only through the tunnel; `loadBundle` performs the actual fetch and execution on first demand. The tunnel also exposes fetch-shaped transport and the API client. Acceptance lives in `apps/web/tests/preview-boot.e2e.ts`, which serves the real built pages and drives the pre-boot chooser plus Worker activation in headless Chromium. The empty selection exercises first-run startup. The `vfs-example` overlay supplies ordinary workspace files and plaintext persistence artifacts for cold Workspace/Session discovery, tool presentation, subagent navigation, and history paging without a model request. The chooser reserves WebFS as a separate user-authorized source; that provider does not read the built-in fixture. diff --git a/packages/experimental/webworker-runtime/README.zh.md b/packages/experimental/webworker-runtime/README.zh.md index 2552c659d1..e89ae7fd1e 100644 --- a/packages/experimental/webworker-runtime/README.zh.md +++ b/packages/experimental/webworker-runtime/README.zh.md @@ -9,7 +9,7 @@ - **`lib/index.js`(装配库)**——`createWorkerHost`/`startWorkerHost` 挂载基础镜像和按序排列的数据 overlays(`storage/`)、安装模块加载器(`module-system/`)与 `process` shim、经镜像自带的 `dsh-app-boot` 启动插件树,并把服务缝隙交给隧道。Overlay 只能替换 `home/` 与 `workspace/` 下的文件,不能替换基础 manifest、配置或模块。镜像布局契约(`image-layout.ts`:虚拟根、config/manifest 路径、空目录、`lowered` 包装契约门)与 packer 共享。boot patch 强制部署形态行:关前端静态服务、JSONL 会话日志走明文、preset 根指向镜像内 `config/agent-presets`。 - **`lib/worker.js`(worker 束)**——装配库加本包的 Node 兼容层,合成一个自含 ES module。模块代理表(`module-proxies.ts`)是唯一平台叉口:`node:*` 内建走 VFS、隧道和浏览器原语,浏览器做不到的走结构化 stub(调用即在 console 报错并抛出),native/binary 包则替换执行后端。`node:module` 在镜像 package 根之上提供 `createRequire().resolve` 与 `.resolve.paths()`,使未修改的包无需执行目标模块即可发现 manifest。VFS mutation 驱动 `node:fs` 的 callback、polling 和 promise watcher;打开的 descriptor 在 rename、replacement 和 unlink 后仍保留文件身份与访问模式;`readable-stream` 提供文件流以及 Chokidar、readdirp 等未修改镜像包所用的流状态机。AsyncLocalStorage 经 pack 时降低注入的 snapshot/restore 面在 `await` 间携带同步栈因果。worker 不带编译器:packer 未降低的镜像在挂载时被拒([note](../../../.agents/notes/implemented/architecture/2026-08-20-webworker-pack-lowering-and-preview.zh.md))。 - **`src/shell/`(worker 自己的进程层)**——浏览器 worker 无法 fork,所以 `node:child_process` 不是 stub 而是实现:`spawn` 把命令放进它自己的 Web Worker——就是这同一个束,由首帧告诉它「你是 shell 进程」——并以 subprocess 服务消费的 `ChildProcess` 面报告结果。命令不占宿主线程,`SIGKILL` 不管它在干什么都能终止它,而它只能靠消息触达 VFS(由宿主应答这些帧)。Worker 平台 executable 在不替换 JavaScript 包、也不把具体实现耦合进 `node:child_process` 的情况下保持 Landlock 等 native 包协议;普通命令使用本包的求值器与 coreutils 命令表。语法来自 `@yarnpkg/parsers` 的 `parseShell`,而 `execSync`/`fork` 依然拒绝,因为它们需要真进程。 -- **`lib/client.js`(页面半)**——启动分为相互独立的两段。`chooseWorkerHostSource({ image?, fixtureManifest? })` 可选地拥有 boot barrier 与 fixture manifest:没有 `preview-fixture` 时停在来源选择面板,合法 query 则直接选择;两条路径都返回按序排列的 overlays。`connectWorkerHost(worker, { image?, overlays? })` 仍是公开的基础运行态连接器;调用方跳过选择器时 overlay 列表为空。`apps/web` 调用这两段并提供静态打包的 Worker。开局 `init` 帧携带基础镜像与按序排列的 overlay URL,boot 载荷送达结构化 index 注入表,`applyIndexInjections` 在壳入口运行前逐行执行。隧道暴露 fetch 形传输、API 客户端与壳启动缝隙用的 `loadBundle`。 +- **`lib/client.js`(页面半)**——启动分为相互独立的两段。`chooseWorkerHostSource({ image?, fixtureManifest? })` 可选地拥有 boot barrier 与 fixture manifest:没有 `preview-fixture` 时停在来源选择面板,合法 query 则直接选择;两条路径都返回按序排列的 overlays。`connectWorkerHost(worker, { image?, overlays? })` 仍是公开的基础运行态连接器;调用方跳过选择器时 overlay 列表为空。`apps/web` 调用这两段并提供静态打包的 Worker。开局 `init` 帧携带基础镜像与按序排列的 overlay URL,boot 载荷送达结构化 index 注入表,`applyIndexInjections` 在壳入口运行前逐行执行。脚本 preload 行只是提示,因此会被跳过:`/plugins` 资源只能经 tunnel 解析,`loadBundle` 会在首次需要时完成实际获取与执行。Tunnel 还暴露 fetch 形传输与 API 客户端。 验收在 `apps/web/tests/preview-boot.e2e.ts`:静态服务真实构建页面,在 headless Chromium 里驱动 pre-boot 选择面板与 Worker 激活。空白选择验证首次启动;`vfs-example` overlay 提供普通 workspace 文件与明文 persistence 产物,无需模型请求即可验证 Workspace/Session 冷发现、工具呈现、subagent 导航和历史分页。选择面板为 WebFS 保留独立的用户授权来源;该 provider 不读取内置 fixture。 diff --git a/packages/experimental/webworker-runtime/src/client/apply-injections.ts b/packages/experimental/webworker-runtime/src/client/apply-injections.ts index 163729a6aa..76e094cd60 100644 --- a/packages/experimental/webworker-runtime/src/client/apply-injections.ts +++ b/packages/experimental/webworker-runtime/src/client/apply-injections.ts @@ -34,6 +34,10 @@ export async function applyIndexInjections( case 'script-src': await loadScript(row.src) break + case 'script-preload': + // The worker tunnel has no browser URL to warm without also executing + // the script; loadScript handles the real request when the row arrives. + break case 'style': { const el = document.createElement('style') el.textContent = row.text diff --git a/packages/experimental/webworker-runtime/tests/client/apply-injections.spec.ts b/packages/experimental/webworker-runtime/tests/client/apply-injections.spec.ts new file mode 100644 index 0000000000..60a764e5e0 --- /dev/null +++ b/packages/experimental/webworker-runtime/tests/client/apply-injections.spec.ts @@ -0,0 +1,21 @@ +// @vitest-environment jsdom +import { afterEach, expect, it, vi } from 'vitest' +import { applyIndexInjections } from '../../src/client/apply-injections.ts' + +afterEach(() => { + document.head.innerHTML = '' + document.body.innerHTML = '' +}) + +it('ignores script preload hints and executes script sources through the worker loader', async () => { + const loadScript = vi.fn(async () => {}) + + await applyIndexInjections([ + { kind: 'script-preload', src: '/plugins/preload.js' }, + { kind: 'script-src', placement: 'head', src: '/plugins/execute.js' }, + ], loadScript) + + expect(loadScript).toHaveBeenCalledOnce() + expect(loadScript).toHaveBeenCalledWith('/plugins/execute.js') + expect(document.querySelector('link[rel="preload"]')).toBeNull() +}) diff --git a/packages/extensions/tool-cordis/src/api-catalog.ts b/packages/extensions/tool-cordis/src/api-catalog.ts index 320c44b9aa..3d5d495cc0 100644 --- a/packages/extensions/tool-cordis/src/api-catalog.ts +++ b/packages/extensions/tool-cordis/src/api-catalog.ts @@ -519,6 +519,12 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ parameters: [{ name: 'id', description: 'entry id (package name).' }], returns: 'the path, or undefined for an unknown id.', }, + { + signature: 'artifactBaseline(id: string): ClientArtifactBaseline | undefined', + description: 'Filesystem baseline captured before an entry\'s current bytes were read. HMR compares it with the live files when installing a watch, so a write between startup composition and watch installation cannot disappear into the watcher\'s initial state.', + parameters: [{ name: 'id', description: 'entry id (package name).' }], + returns: 'the path and baseline, or undefined for an unknown id.', + }, { signature: 'rebuilt(id: string): string | undefined', description: 'Re-hash one bundle (the HMR watch\'s registration hook — the only entry point through which bundle content changes reach the graph).', @@ -3303,6 +3309,10 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'Branded', declaration: 'export type Branded = string & {\n readonly [BRAND]: B;\n};', }, + { + name: 'ClientArtifactBaseline', + declaration: 'export interface ClientArtifactBaseline {\n readonly path: string;\n readonly mtimeMs: number;\n readonly size: number;\n readonly mapMtimeMs: number | null;\n readonly mapSize: number | null;\n}', + }, { name: 'CodeBindingErrorClass', declaration: 'export interface CodeBindingErrorClass {\n name: string;\n memberNameProperty: string;\n}', @@ -3765,7 +3775,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'IndexInjection', - declaration: 'export type IndexInjection = {\n kind: \'global\';\n name: string;\n value: unknown;\n} | {\n kind: \'script\';\n placement: IndexInjectionPlacement;\n text: string;\n} | {\n kind: \'script-src\';\n placement: IndexInjectionPlacement;\n src: string;\n} | {\n kind: \'style\';\n text: string;\n} | {\n kind: \'html\';\n placement: IndexInjectionPlacement;\n html: string;\n};', + declaration: 'export type IndexInjection = {\n kind: \'global\';\n name: string;\n value: unknown;\n} | {\n kind: \'script\';\n placement: IndexInjectionPlacement;\n text: string;\n} | {\n kind: \'script-src\';\n placement: IndexInjectionPlacement;\n src: string;\n} | {\n kind: \'script-preload\';\n src: string;\n} | {\n kind: \'style\';\n text: string;\n} | {\n kind: \'html\';\n placement: IndexInjectionPlacement;\n html: string;\n};', }, { name: 'IndexInjectionPlacement', @@ -5443,13 +5453,21 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'VerifiedWebhookDelivery', declaration: 'export interface VerifiedWebhookDelivery {\n readonly kind: K;\n readonly source: WebhookSourceId;\n readonly deliveryId: WebhookDeliveryId;\n readonly event: WebhookEventOf;\n readonly receivedAt: number;\n}', }, + { + name: 'WebBootBatch', + declaration: 'export interface WebBootBatch {\n phase: WebBootBatchPhase;\n url: string;\n rev: string;\n entries: string[];\n}', + }, + { + name: 'WebBootBatchPhase', + declaration: 'export type WebBootBatchPhase = \'bootstrap\' | \'application\';', + }, { name: 'WebBootEntry', declaration: 'export interface WebBootEntry {\n id: string;\n url: string;\n rev: string;\n inject?: string[];\n immediately?: boolean;\n external?: string[];\n}', }, { name: 'WebBootGraph', - declaration: 'export interface WebBootGraph {\n rev: string;\n entries: WebBootEntry[];\n}', + declaration: 'export interface WebBootGraph {\n rev: string;\n entries: WebBootEntry[];\n batches: WebBootBatch[];\n}', }, { name: 'WebFetchBody', diff --git a/packages/host/webserver/README.i18n.yaml b/packages/host/webserver/README.i18n.yaml index aae84858b2..8a6b93bb12 100644 --- a/packages/host/webserver/README.i18n.yaml +++ b/packages/host/webserver/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/host/webserver/README.md -README.md: 0dc8f197f923c2dc4cb2d72ccb5b3a31f5384503 -README.zh.md: d19e4a6be1df0c464d7ac61726e6bfb45a92c8a1 +README.md: c6abc503222fc8bf60d4b6c940eeb1f7910cc9aa +README.zh.md: 430488869c98a86ff669e12acfaee86bae7aa8a3 diff --git a/packages/host/webserver/README.md b/packages/host/webserver/README.md index 0dc8f197f9..c6abc50322 100644 --- a/packages/host/webserver/README.md +++ b/packages/host/webserver/README.md @@ -2,7 +2,7 @@ English | [中文](README.zh.md) -Web HTTP and upgrade-route registration plugin (default-exported `WebServer`, config `{host, port}`): a `node:http` server that listens on activation and provides `ctx.webServer`. `register(route)` adds a named `exact`/`prefix` HTTP route; `registerUpgrade(route)` adds an upgrade route for an exact pathname. A duplicate path within either table throws because route patterns are a composition-level contract and a collision is a misconfiguration; both methods return a disposer that removes the registration. `registerFallback(handler)` registers the one handler for requests that match no named route. A second registration throws; the SPA dist server [`dsh-host-frontend-static`](../frontend-static/README.md) is the shipped owner, and the server returns 404 while none is registered. Index startup inputs are structured rows: `collectIndexInjections()` gathers a fresh `IndexInjection` table over one `webserver/index-inject` emit per call, and `renderIndex(html)` renders the rows into an index.html body before applying the raw `tapIndex(transform)` transforms in registration order (`applyIndexTaps(html)`, the escape hatch for markup no row expresses); the fallback handler calls `renderIndex` on every index response, and a static deployment ships the same rows over its boot payload, rendering with the exported `renderIndexInjections`. `port` reads the listening port (the OS-assigned value when `port` is 0), and `host` reads the configured bind host (composition-time facts other plugins adapt to, e.g. the directory-picker chooser). HTTP match order is fixed: exact over the whole table, then longest prefix, then the fallback handler. Upgrades match exactly and unmatched connections are closed; registration order carries no request-facing semantics. +Web HTTP and upgrade-route registration plugin (default-exported `WebServer`, config `{host, port}`): a `node:http` server that listens on activation and provides `ctx.webServer`. `register(route)` adds a named `exact`/`prefix` HTTP route; `registerUpgrade(route)` adds an upgrade route for an exact pathname. A duplicate path within either table throws because route patterns are a composition-level contract and a collision is a misconfiguration; both methods return a disposer that removes the registration. `registerFallback(handler)` registers the one handler for requests that match no named route. A second registration throws; the SPA dist server [`dsh-host-frontend-static`](../frontend-static/README.md) is the shipped owner, and the server returns 404 while none is registered. Index startup inputs are structured rows: `collectIndexInjections()` gathers a fresh `IndexInjection` table over one `webserver/index-inject` emit per call, and `renderIndex(html)` renders the rows into an index.html body before applying the raw `tapIndex(transform)` transforms in registration order (`applyIndexTaps(html)`, the escape hatch for markup no row expresses); `script-preload` rows render advisory classic-script preload links. The fallback handler calls `renderIndex` on every index response, and a static deployment ships the same rows over its boot payload. `port` reads the listening port (the OS-assigned value when `port` is 0), and `host` reads the configured bind host (composition-time facts other plugins adapt to, e.g. the directory-picker chooser). HTTP match order is fixed: exact over the whole table, then longest prefix, then the fallback handler. Upgrades match exactly and unmatched connections are closed; registration order carries no request-facing semantics. The package knows no harness concepts and serves no files: the `/api` HTTP bridge and downlink WebSockets are routes owned by the connection plugin, plugin bundles and the HMR event stream are routes owned by the modules/hmr plugins, and dist serving belongs to the fallback owner. The upgrade handler owns the protocol handshake and connection contents; the webserver only delivers the raw socket and request. `host` accepts only `127.0.0.1` (default posture) and `0.0.0.0` (deliberate network exposure). This server serves browsers only; Electron loads dist over `file://` and carries fetch over an IPC bridge. This package never prints; the URL line belongs to the shell. diff --git a/packages/host/webserver/README.zh.md b/packages/host/webserver/README.zh.md index d19e4a6be1..430488869c 100644 --- a/packages/host/webserver/README.zh.md +++ b/packages/host/webserver/README.zh.md @@ -2,7 +2,7 @@ [English](README.md) | 中文 -Web HTTP 与 upgrade route 注册插件(默认导出 `WebServer`,配置为 `{host, port}`):一个在激活时开始监听的 `node:http` 服务器,提供 `ctx.webServer`。`register(route)` 添加具名的 `exact`/`prefix` HTTP route;`registerUpgrade(route)` 添加精确 pathname 的 upgrade route;同一张表内的重复路径会抛错,因为 route 模式是组合层约定,冲突即配置错误;两者返回的 disposer 都会移除注册。`registerFallback(handler)` 注册一个 handler,处理所有未被具名 route 命中的请求。第二次注册会抛错;随附的 SPA dist 服务器 [`dsh-host-frontend-static`](../frontend-static/README.zh.md) 是该 handler 的所有者,没有注册 handler 时服务器返回 404。index 的启动输入是结构化行:`collectIndexInjections()` 每次调用经一次 `webserver/index-inject` emit 现收一张全新的 `IndexInjection` 表,`renderIndex(html)` 先把行渲染进 index.html 响应体,再按注册顺序应用原始的 `tapIndex(transform)` 转换(`applyIndexTaps(html)`,行无法表达的标记的逃生口);fallback handler 在每次 index 响应时调用 `renderIndex`,静态部署则把同一批行经 boot 载荷下发,用导出的 `renderIndexInjections` 渲染。`port` 读取正在监听的端口(当 `port` 为 0 时读取 OS 分配的值),`host` 读取配置的绑定宿主(这些是其他插件据以自适应的组合期事实,例如 directory-picker 选择器)。HTTP 匹配顺序固定不变:先在整张表中匹配精确 route,再匹配最长前缀,最后交给 fallback handler。upgrade 只做精确匹配,未命中连接直接关闭;注册顺序不影响请求处理。 +Web HTTP 与 upgrade route 注册插件(默认导出 `WebServer`,配置为 `{host, port}`):一个在激活时开始监听的 `node:http` 服务器,提供 `ctx.webServer`。`register(route)` 添加具名的 `exact`/`prefix` HTTP route;`registerUpgrade(route)` 添加精确 pathname 的 upgrade route;同一张表内的重复路径会抛错,因为 route 模式是组合层约定,冲突即配置错误;两者返回的 disposer 都会移除注册。`registerFallback(handler)` 注册一个 handler,处理所有未被具名 route 命中的请求。第二次注册会抛错;随附的 SPA dist 服务器 [`dsh-host-frontend-static`](../frontend-static/README.zh.md) 是该 handler 的所有者,没有注册 handler 时服务器返回 404。index 的启动输入是结构化行:`collectIndexInjections()` 每次调用经一次 `webserver/index-inject` emit 现收一张全新的 `IndexInjection` 表,`renderIndex(html)` 先把行渲染进 index.html 响应体,再按注册顺序应用原始的 `tapIndex(transform)` 转换(`applyIndexTaps(html)`,行无法表达的标记的逃生口);`script-preload` 行渲染为 classic script 的提示性预加载链接。fallback handler 在每次 index 响应时调用 `renderIndex`,静态部署则把同一批行经 boot 载荷下发。`port` 读取正在监听的端口(当 `port` 为 0 时读取 OS 分配的值),`host` 读取配置的绑定宿主(这些是其他插件据以自适应的组合期事实,例如 directory-picker 选择器)。HTTP 匹配顺序固定不变:先在整张表中匹配精确 route,再匹配最长前缀,最后交给 fallback handler。upgrade 只做精确匹配,未命中连接直接关闭;注册顺序不影响请求处理。 该包不了解任何 harness 概念,也不提供任何文件服务:`/api` HTTP 桥接与下行 WebSocket 是 connection 插件的 route,插件 bundle 与 HMR(热模块替换)事件流是 modules/hmr 插件的 route,dist 服务则属于 fallback 持有者。upgrade handler 拥有协议握手与连接内容;webserver 只交付原始 socket 与 request。`host` 只接受 `127.0.0.1`(默认安全姿态)和 `0.0.0.0`(有意向网络开放)。该服务器只服务浏览器;Electron 通过 `file://` 加载 dist,并经 IPC 桥接承载 fetch。该包从不打印内容;URL 行属于 shell。 diff --git a/packages/host/webserver/src/injections.ts b/packages/host/webserver/src/injections.ts index 7a61ae0510..5b431918f5 100644 --- a/packages/host/webserver/src/injections.ts +++ b/packages/host/webserver/src/injections.ts @@ -23,6 +23,8 @@ export type IndexInjection = * loader resolves worker-only URLs such as `/plugins/...`). */ | { kind: 'script-src'; placement: IndexInjectionPlacement; src: string } + /** Advisory preload for an external classic script; static workers may ignore it. */ + | { kind: 'script-preload'; src: string } /** A `` } case 'html': diff --git a/packages/host/webserver/tests/webserver.spec.ts b/packages/host/webserver/tests/webserver.spec.ts index e8fa315ecc..198716d778 100644 --- a/packages/host/webserver/tests/webserver.spec.ts +++ b/packages/host/webserver/tests/webserver.spec.ts @@ -208,6 +208,7 @@ describe('real Loader composition', () => { table.push( { kind: 'script', placement: 'head', text: 'window.__Q__=1' }, { kind: 'script-src', placement: 'head', src: '/plugins/a.js?rev="1"&x=' }, + { kind: 'script-preload', src: '/plugins/b.js?rev="2"&x=' }, { kind: 'global', name: '__DSH_BOOT__', value: { rev: '' } }, { kind: 'style', text: 'body{margin:0}' }, { kind: 'html', placement: 'head', html: '' }, @@ -222,6 +223,7 @@ describe('real Loader composition', () => { '', '', '', + '', 'globalThis["__DSH_BOOT__"] = {"rev":"\\u003c/script>\\u003cb>"}', '', '', diff --git a/scripts/client-bundle-purity.spec.ts b/scripts/client-bundle-purity.spec.ts index d9222f617b..ce17d3247e 100644 --- a/scripts/client-bundle-purity.spec.ts +++ b/scripts/client-bundle-purity.spec.ts @@ -1,7 +1,10 @@ /** - * Pins shared client-bundle preset rules: the module-edge purity gate and - * the physical watch dependencies hidden behind virtual CSS Modules. + * Pins shared client-bundle preset rules: module-edge purity, source-map + * chaining, and physical watch dependencies hidden behind virtual CSS Modules. */ +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' import { fileURLToPath } from 'node:url' import { describe, expect, it, vi } from 'vitest' import { clientBundle, requestedExternals } from '../packages/client/tsdown.client.ts' @@ -14,6 +17,11 @@ interface CssModulePlugin { load?: (this: { addWatchFile: (id: string) => void }, id: string) => Promise } +interface SourceMapPlugin { + name: string + load?: (id: string) => Promise +} + /** A representative dynamic bundle using the shared client baseline. */ const REQUESTING_PACKAGE = '@deepseek-ai/dsh-client-ui-conversation' @@ -59,6 +67,14 @@ function cssModulePlugin(): CssModulePlugin { return plugin } +function sourceMapPlugin(): SourceMapPlugin { + const configs = clientConfigs() + const plugins = (configs[0] as { plugins: SourceMapPlugin[] }).plugins + const plugin = plugins.find(candidate => candidate.name === 'dsh-tsc-sourcemap') + if (plugin?.load === undefined) throw new Error('tsc sourcemap plugin missing from client config') + return plugin +} + describe('client bundle purity gate', () => { const resolveId = purityResolveId() @@ -143,6 +159,28 @@ describe('client bundle debug artifacts', () => { it('emits source maps for plugin TS and TSX outside the Vite module graph', () => { const configs = clientConfigs() expect(configs[0]?.sourcemap).toBe(true) + expect(configs[0]?.outputOptions).toMatchObject({ sourcemapExcludeSources: false }) + }) + + it('chains emitted tsc maps when the production Client build consumes lib/types', async () => { + const root = mkdtempSync(join(tmpdir(), 'dsh-client-sourcemap-')) + try { + const entry = join(root, 'lib', 'types', 'client', 'index.js') + const source = join(root, 'src', 'client', 'index.ts') + const map = { version: 3, names: [], mappings: 'AAAA', sources: ['../../../src/client/index.ts'] } + mkdirSync(join(root, 'lib', 'types', 'client'), { recursive: true }) + mkdirSync(join(root, 'src', 'client'), { recursive: true }) + writeFileSync(entry, 'export const marker = true\n//# sourceMappingURL=index.js.map\n') + writeFileSync(`${entry}.map`, JSON.stringify(map)) + writeFileSync(source, 'export const marker: true = true\n') + + await expect(sourceMapPlugin().load!(entry)).resolves.toEqual({ + code: 'export const marker = true', + map: { ...map, sourcesContent: ['export const marker: true = true\n'] }, + }) + } finally { + rmSync(root, { recursive: true, force: true }) + } }) it('maps first-party sources to their repository package paths', () => { diff --git a/scripts/gen-cordis-catalog.ts b/scripts/gen-cordis-catalog.ts index 05a4c8947c..4acfd5b694 100644 --- a/scripts/gen-cordis-catalog.ts +++ b/scripts/gen-cordis-catalog.ts @@ -573,6 +573,7 @@ export const LINK_MAP: Readonly> = { WorkspaceOrderValue: 'workspace.md', WorkspaceRenameRequest: 'workspace.md', WorkspaceValue: 'workspace.md', + ClientArtifactBaseline: 'client-modules.md', WebBootGraph: 'client-modules.md', SessionTelemetryRecord: 'session-telemetry.md', WorkflowRunInfo: 'workflow.md', diff --git a/scripts/type-equiv.manifest.json b/scripts/type-equiv.manifest.json index 3bedaa9804..81a3e124a1 100644 --- a/scripts/type-equiv.manifest.json +++ b/scripts/type-equiv.manifest.json @@ -1761,11 +1761,26 @@ "symbol": "WebBootEntry", "source": "packages/client/modules/src/client/manifest.ts" }, + { + "doc": "docs/subsystems/client-modules.md", + "symbol": "WebBootBatchPhase", + "source": "packages/client/modules/src/client/manifest.ts" + }, + { + "doc": "docs/subsystems/client-modules.md", + "symbol": "WebBootBatch", + "source": "packages/client/modules/src/client/manifest.ts" + }, { "doc": "docs/subsystems/client-modules.md", "symbol": "WebBootGraph", "source": "packages/client/modules/src/client/manifest.ts" }, + { + "doc": "docs/subsystems/client-modules.md", + "symbol": "ClientArtifactBaseline", + "source": "packages/client/modules/src/index.ts" + }, { "doc": "docs/subsystems/session-telemetry.md", "symbol": "SessionTelemetrySharingStatus",