From 5bbaf168d9759f78884a32c361d970544ba037d4 Mon Sep 17 00:00:00 2001 From: lsdsjy <1356263+lsdsjy@users.noreply.github.com> Date: Tue, 18 Aug 2026 19:25:50 +0800 Subject: [PATCH 1/6] perf(client-modules): batch startup plugin scripts --- ...7-23-client-plugin-loading-model.i18n.yaml | 4 +- .../2026-07-23-client-plugin-loading-model.md | 26 +- ...26-07-23-client-plugin-loading-model.zh.md | 26 +- ...ient-shells-and-dynamic-packages.i18n.yaml | 4 +- ...8-15-client-shells-and-dynamic-packages.md | 10 +- ...5-client-shells-and-dynamic-packages.zh.md | 10 +- apps/web/tests/assembled-boot.ts | 89 ++++-- apps/web/tests/smoke-real.e2e.ts | 28 ++ docs/subsystems/client-modules.i18n.yaml | 4 +- docs/subsystems/client-modules.md | 33 +- docs/subsystems/client-modules.zh.md | 33 +- packages/client/hmr/README.i18n.yaml | 4 +- packages/client/hmr/README.md | 4 +- packages/client/hmr/README.zh.md | 4 +- packages/client/hmr/src/client/index.ts | 26 +- packages/client/hmr/src/events.ts | 28 ++ packages/client/hmr/src/index.ts | 51 ++- .../client/hmr/tests/events.client.spec.ts | 23 ++ .../client/hmr/tests/node-half.client.spec.ts | 6 + packages/client/modules/README.i18n.yaml | 4 +- packages/client/modules/README.md | 8 +- packages/client/modules/README.zh.md | 8 +- .../client/modules/src/client/manifest.ts | 87 +++++- packages/client/modules/src/client/system.ts | 37 ++- packages/client/modules/src/index.ts | 294 +++++++++++++++--- .../modules/tests/loader.client.spec.ts | 153 +++++++-- .../modules/tests/node-half.client.spec.ts | 236 ++++++++++++-- packages/client/web/README.i18n.yaml | 4 +- packages/client/web/README.md | 2 +- packages/client/web/README.zh.md | 2 +- packages/client/web/tests/boot.client.spec.ts | 22 +- .../extensions/tool-cordis/src/api-catalog.ts | 10 +- scripts/type-equiv.manifest.json | 10 + 33 files changed, 1047 insertions(+), 243 deletions(-) create mode 100644 packages/client/hmr/tests/events.client.spec.ts 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..99337fc16f 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: 07c3f2a1f2cb60a6e60e33c81dcf1c9060d7aebb +2026-07-23-client-plugin-loading-model.zh.md: 5d8c553f0d7eda3c05fdaecf1ac2ee6a515b8304 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..07c3f2a1f2 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 @@ -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,161 @@ describe('client bundle activation', () => { expect(String(thrown)).not.toContain('pnpm run build') }) + it('rejects a malformed built source map during composition', () => { + const packageName = '@fixture/malformed-source-map' + const clientPath = writePackage(packageName) + mkdirSync(dirname(clientPath), { recursive: true }) + writeFileSync(clientPath, 'module.exports = {}\n') + writeFileSync(`${clientPath}.map`, '{}\n') + expect(() => construct([packageName])) + .toThrow(`${clientPath}.map is not a regular Source Map v3 object`) + + writeFileSync(`${clientPath}.map`, '{"version":3,"sources":[null]}\n') + expect(() => construct([packageName])) + .toThrow(`${clientPath}.map is not a regular Source Map v3 object`) + }) + + 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 + + writeFileSync(clientPath, 'module.exports = { generation: 2 }\n') + service.rebuilt(packageName) + const second = service.graph().batches[0]!.url + expect(second).not.toBe(first) + 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('frames bundle and map fields before hashing an immutable revision', () => { + const packageName = '@fixture/framed-artifact-hash' + const clientPath = writePackage(packageName) + mkdirSync(dirname(clientPath), { recursive: true }) + const map = '{"version":3,"names":[],"mappings":"AAAA","sources":["src.ts"]}\n' + writeFileSync(clientPath, 'module.exports = {} ') + writeFileSync(`${clientPath}.map`, map) + const first = construct([packageName]).graph().entries[0]!.rev + + writeFileSync(clientPath, 'module.exports = {}') + writeFileSync(`${clientPath}.map`, ` ${map}`) + const second = construct([packageName]).graph().entries[0]!.rev + expect(second).not.toBe(first) + }) + 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') + expect(construct([packageName]).graph().entries[0]?.rev).not.toBe(row.rev) + }) + + 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' }) }) }) 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..8d75949b78 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"') }) }) @@ -159,7 +163,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 +201,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/extensions/tool-cordis/src/api-catalog.ts b/packages/extensions/tool-cordis/src/api-catalog.ts index 320c44b9aa..65f359f42a 100644 --- a/packages/extensions/tool-cordis/src/api-catalog.ts +++ b/packages/extensions/tool-cordis/src/api-catalog.ts @@ -5443,13 +5443,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/scripts/type-equiv.manifest.json b/scripts/type-equiv.manifest.json index 3bedaa9804..a2d0152493 100644 --- a/scripts/type-equiv.manifest.json +++ b/scripts/type-equiv.manifest.json @@ -1761,6 +1761,16 @@ "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", From 9ee9a3270c633603c963141e167aaeb21abbdad3 Mon Sep 17 00:00:00 2001 From: lsdsjy <1356263+lsdsjy@users.noreply.github.com> Date: Tue, 18 Aug 2026 20:18:45 +0800 Subject: [PATCH 2/6] test(web): hold application batch during boot theme check --- apps/web/tests/settings-chrome.e2e.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/apps/web/tests/settings-chrome.e2e.ts b/apps/web/tests/settings-chrome.e2e.ts index d1c6ada8ba..562aff5dad 100644 --- a/apps/web/tests/settings-chrome.e2e.ts +++ b/apps/web/tests/settings-chrome.e2e.ts @@ -192,8 +192,8 @@ describe('web e2e: settings modal and General preferences', () => { .toMatch(/ui-theme:\n\s+preference: dark/) await page.keyboard.press('Escape') - // Hold real plugin bundles so the shell-owned loading page remains observable. - const pluginPattern = /\/plugins\/@deepseek-ai\/dsh-client-ui-theme\/client\.js(?:\?.*)?$/ + // Hold the real application batch so the shell-owned loading page remains observable. + const pluginPattern = /\/plugins\/_batch\/application\/[a-f\d]{12}\/client\.js$/ let releaseBundles = (): void => {} const bundlesReleased = new Promise((resolve) => { releaseBundles = resolve }) await page.route(pluginPattern, async (route) => { From 445de0ab3e5fe1bf5a8695b52e5393ae41f8b631 Mon Sep 17 00:00:00 2001 From: lsdsjy <1356263+lsdsjy@users.noreply.github.com> Date: Wed, 19 Aug 2026 11:28:59 +0800 Subject: [PATCH 3/6] fix(client-modules): tolerate incomplete source maps --- ...7-23-client-plugin-loading-model.i18n.yaml | 4 +-- .../2026-07-23-client-plugin-loading-model.md | 2 +- ...26-07-23-client-plugin-loading-model.zh.md | 2 +- apps/web/tests/smoke-real.e2e.ts | 2 ++ packages/client/modules/README.i18n.yaml | 4 +-- packages/client/modules/README.md | 1 + packages/client/modules/README.zh.md | 1 + packages/client/modules/src/client/system.ts | 7 +++-- packages/client/modules/src/index.ts | 26 ++++++++++--------- .../modules/tests/loader.client.spec.ts | 10 +++++++ .../modules/tests/node-half.client.spec.ts | 14 +++++----- 11 files changed, 47 insertions(+), 26 deletions(-) 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 99337fc16f..63d42117b6 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: 07c3f2a1f2cb60a6e60e33c81dcf1c9060d7aebb -2026-07-23-client-plugin-loading-model.zh.md: 5d8c553f0d7eda3c05fdaecf1ac2ee6a515b8304 +2026-07-23-client-plugin-loading-model.md: a16c022bc2d4f96bd2680a637e02a485ba4f2697 +2026-07-23-client-plugin-loading-model.zh.md: 96c6b85cd6d7bdb0cbfce4479d2cfe5b7e74f2a5 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 07c3f2a1f2..a16c022bc2 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 @@ -96,7 +96,7 @@ The current package inventory and build forms live in the [client shell layering One governance implementation runs on both sides of the wire; the browser-specific layer is one module system plus one reload plugin. Dynamic packages have one artifact form, so the purity check covers them all. Cordis dependencies, module requests, and the boot tier live with their owners — the manifests — while the composing app holds only the roster. Host graph validation and recursive request arrival keep synchronous factory dependencies explicit. Browser-native script loading preserves the standard mapping among plugin network resources, generated bundles, and TypeScript/TSX sources, while the module system keeps only one replaceable `loadBundle` hook. -Costs accepted: the vendored Loader carries idle machinery in the browser (EntryTree persistence is a no-op, groups/isolation unused); every plugin edit in dev pays a bundle rebuild plus fiber remount; graph `inject` rows guide factory arrival but service availability remains the activation authority, so a mismatch appears at the settled sweep; the static UI libraries keep direct value exports; every bundle gains a source-map artifact; and external-script failures provide only coarse URL diagnostics instead of the HTTP status available to an explicit fetch. +Costs accepted: the vendored Loader carries idle machinery in the browser (EntryTree persistence is a no-op, groups/isolation unused); every plugin edit in dev pays a bundle rebuild plus fiber remount; graph `inject` rows guide factory arrival but service availability remains the activation authority, so a mismatch appears at the settled sweep; the static UI libraries keep direct value exports; every bundle gains a source-map artifact; and external-script failures provide only coarse URL diagnostics instead of the HTTP status available to an explicit fetch. The Host retains per-plugin bundle/map snapshots, revision-stamped individual responses, current batches, and one previous batch generation, so memory scales as several copies of the composed client artifacts. This retained state keeps URLs immutable and lets an in-flight request finish across one HMR recomposition. Roster: it lives in the web bundle's config tree (`packages/bundle/web-app/cordis.patch.yml`); `mountWebPlugins` and the `CLIENT_PACKAGES` constant are gone, and recomposing a deployment means swapping the yml/overlay. The graph composer lives in the `dsh-client-modules` node half, while the parser-preloaded client face bootstraps the browser module table. The webserver remains a plain route-registration plugin; `/api/*` binding belongs to the connection node half over `api-gateway` (`dsh-host-apiproxy` providing `ctx.apiProxy`), and the dev bundle watch plus SSE channel belongs to the hmr node half. diff --git a/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.zh.md b/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.zh.md index 5d8c553f0d..96c6b85cd6 100644 --- a/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.zh.md +++ b/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.zh.md @@ -96,7 +96,7 @@ Host 会快照每个已构建插件产物,并把其 factory registration 拼 Wire 两侧运行同一份治理实现;浏览器特有层只包含一套模块系统和一个重载插件。动态包只有一种产物形态,因此纯度检查覆盖全部动态包。Cordis 依赖、模块请求与启动档位都与其所有者——manifest——同住,负责组合的 app 只握名册。Host graph 校验与递归请求到达使同步 factory 依赖保持显式。浏览器原生 script 装载保留插件网络资源、生成 bundle 与 TypeScript/TSX 源码之间的标准映射,模块系统也只保留一个可替换的 `loadBundle` 钩子。 -接受的代价:vendored Loader 在浏览器里背着闲置机件(EntryTree 持久化是 no-op,分组/隔离未用);开发期每次修改插件都要付一次 bundle 重建加 fiber 重挂;graph `inject` row 指导 factory 到达,但服务可用性仍是激活权威,因此不匹配会在 settled 扫描时浮出;静态 UI 库保留直接实体导出;每个 bundle 多出一份 sourcemap 产物,外部 script 失败也只能给出粗粒度 URL 诊断,不能像显式 fetch 那样报告 HTTP 状态。 +接受的代价:vendored Loader 在浏览器里背着闲置机件(EntryTree 持久化是 no-op,分组/隔离未用);开发期每次修改插件都要付一次 bundle 重建加 fiber 重挂;graph `inject` row 指导 factory 到达,但服务可用性仍是激活权威,因此不匹配会在 settled 扫描时浮出;静态 UI 库保留直接实体导出;每个 bundle 多出一份 sourcemap 产物,外部 script 失败也只能给出粗粒度 URL 诊断,不能像显式 fetch 那样报告 HTTP 状态。Host 会保留逐插件 bundle/map 快照、带 revision 的独立响应、当前批次及上一代批次,因此内存会随组合出的客户端产物增长为数份副本。这组保留状态使 URL 保持不可变,并让进行中的请求跨越一次 HMR 重组后仍能完成。 名册位于 web 组合包的配置树(`packages/bundle/web-app/cordis.patch.yml`);`mountWebPlugins` 与 `CLIENT_PACKAGES` 常量已消失,重组一次部署等于替换 yml/overlay。Graph 组合器位于 `dsh-client-modules` node 半,由 parser 预载的 client face 则自举浏览器模块表。Webserver 继续作为朴素路由注册插件;`/api/*` 绑定属于 connection node 半,并经 `api-gateway`(由 `dsh-host-apiproxy` 提供 `ctx.apiProxy`);开发期 bundle 监视与 SSE 通道属于 hmr node 半。 diff --git a/apps/web/tests/smoke-real.e2e.ts b/apps/web/tests/smoke-real.e2e.ts index fcbbd637ac..58facd4b3e 100644 --- a/apps/web/tests/smoke-real.e2e.ts +++ b/apps/web/tests/smoke-real.e2e.ts @@ -265,6 +265,8 @@ describe('dsh web keyless CLI smoke', () => { const page = await newEnglishPage(browser) const pluginScripts: string[] = [] const cacheHeaders = new Map() + // Chromium reports `preload as=script` as Script and reuses that same + // request when the matching script node executes; this count pins both. page.on('request', (request) => { const url = new URL(request.url()) if (request.resourceType() === 'script' && url.pathname.startsWith('/plugins/')) { diff --git a/packages/client/modules/README.i18n.yaml b/packages/client/modules/README.i18n.yaml index b5b5df2c80..162e717aee 100644 --- a/packages/client/modules/README.i18n.yaml +++ b/packages/client/modules/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/modules/README.md -README.md: bd6d53de9d847b02fc7a8b1030efe4f9036e44ab -README.zh.md: d78a2ddc836c1266e92c5ca95b4e54b78bdcbf98 +README.md: 67f6b6216dee90148f78d5b62edbe6009dffb8c9 +README.zh.md: d385b7c3854c9da1c4f22224bc5910ae7cfcdf2f diff --git a/packages/client/modules/README.md b/packages/client/modules/README.md index bd6d53de9d..67f6b6216d 100644 --- a/packages/client/modules/README.md +++ b/packages/client/modules/README.md @@ -26,3 +26,4 @@ None; this package neither assembles nor sends a provider request. - **Flat module graph by design** — every bundle is one module node whose edges point only at table leaves; the interface (`loadCache`/`edges`/`invalidate`) already supports a general module graph, so the externalization granularity can change without an interface change. - **No unload bookkeeping of its own** — style removal and fiber teardown ordering live with the HMR driver (`@deepseek-ai/dsh-client-hmr`); the loader only inventories owned style tag ids per record. +- **Snapshot delivery retains artifact bytes** — the Host holds each bundle, optional source map, revision-stamped individual response, and generated batch in memory; HMR additionally retains one prior batch generation. Memory scales as several copies of the composed client artifacts in exchange for immutable responses and one-generation race tolerance. diff --git a/packages/client/modules/README.zh.md b/packages/client/modules/README.zh.md index d78a2ddc83..d385b7c385 100644 --- a/packages/client/modules/README.zh.md +++ b/packages/client/modules/README.zh.md @@ -26,3 +26,4 @@ Node 侧会扫描已启用的 Loader 配置项以发现 web `dsh.client` 包, - **有意采用扁平模块图**:每个 bundle 是一个模块节点,其边只指向表中的叶节点;接口(`loadCache`/`edges`/`invalidate`)已经支持通用模块图,因此可以改变 externalization 粒度而不更改接口。 - **自身不维护卸载记录**:样式移除与 fiber 拆卸顺序属于 HMR 驱动器(`@deepseek-ai/dsh-client-hmr`);loader 只在每条记录中登记其拥有的样式标签 id。 +- **快照式提供会常驻产物字节**:Host 会在内存中保留每个 bundle、可选 sourcemap、带 revision 的独立响应及生成的批次;HMR 还会保留上一代批次。内存会随组合出的客户端产物增长为数份副本,以换取 immutable 响应和一代竞态容忍。 diff --git a/packages/client/modules/src/client/system.ts b/packages/client/modules/src/client/system.ts index 6e17f83494..be2e998a82 100644 --- a/packages/client/modules/src/client/system.ts +++ b/packages/client/modules/src/client/system.ts @@ -26,12 +26,15 @@ const defaultLoadBundle = (url: string): Promise => new Promise((resolve, document.head.append(el) }) -/** Replace the rev query while preserving same-origin relative URLs. */ +/** Replace the rev query while preserving absolute, protocol-relative, or path-relative form. */ function atRevision(url: string, rev: string): string { const absolute = /^[A-Za-z][A-Za-z\d+.-]*:/.test(url) + const protocolRelative = url.startsWith('//') const parsed = new URL(url, 'http://dsh.invalid') parsed.searchParams.set('rev', rev) - return absolute ? parsed.href : `${parsed.pathname}${parsed.search}${parsed.hash}` + if (absolute) return parsed.href + if (protocolRelative) return `//${parsed.host}${parsed.pathname}${parsed.search}${parsed.hash}` + return `${parsed.pathname}${parsed.search}${parsed.hash}` } /** diff --git a/packages/client/modules/src/index.ts b/packages/client/modules/src/index.ts index cdf24ee1f1..27ce53e35a 100644 --- a/packages/client/modules/src/index.ts +++ b/packages/client/modules/src/index.ts @@ -514,14 +514,7 @@ export class ClientModuleRegistry extends Service { const record = this.table.get(id) if (record === undefined) return undefined const bundle = readFileSync(record.meta.clientPath) - let sourceMap: WebPluginRecord['sourceMap'] - try { - sourceMap = sourceMapSnapshot(record.meta.clientPath) - } catch (error) { - // A client rebuild remains reloadable when its development-only map is - // temporarily incomplete; this revision simply exposes no map. - this.ctx.logger.warn(error) - } + const sourceMap = this.readSourceMapSnapshot(record.meta.clientPath) const rev = artifactRevision(bundle, sourceMap) if (rev === record.entry.rev) return rev record.entry = graphRow(id, rev, record.meta) @@ -566,14 +559,13 @@ export class ClientModuleRegistry extends Service { private compose(): WebBootGraph { const entries = orderByModuleGraph([...this.table.values()].map(record => record.entry)) - const records = new Map([...this.table.entries()]) const bootstrap = PARSER_PRELOAD_IDS - .map(id => records.get(id)) + .map(id => this.table.get(id)) .filter((record): record is WebPluginRecord => record !== undefined) const bootstrapIds = new Set(bootstrap.map(record => record.entry.id)) const application = entries .filter(entry => !bootstrapIds.has(entry.id)) - .map(entry => records.get(entry.id)) + .map(entry => this.table.get(entry.id)) .filter((record): record is WebPluginRecord => record !== undefined) const artifacts: BatchArtifact[] = [] if (bootstrap.length > 0) artifacts.push(buildBatch('bootstrap', bootstrap)) @@ -660,7 +652,7 @@ export class ClientModuleRegistry extends Service { } { try { const bundle = readFileSync(clientPath) - const sourceMap = sourceMapSnapshot(clientPath) + const sourceMap = this.readSourceMapSnapshot(clientPath) return { bundle, rev: artifactRevision(bundle, sourceMap), ...(sourceMap === undefined ? {} : { sourceMap }) } } catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error @@ -668,6 +660,16 @@ export class ClientModuleRegistry extends Service { } } + /** Treat a missing, torn, or malformed development map as an unmapped artifact revision. */ + private readSourceMapSnapshot(clientPath: string): WebPluginRecord['sourceMap'] { + try { + return sourceMapSnapshot(clientPath) + } catch (error) { + this.ctx.logger.warn(error) + return undefined + } + } + /** Reconcile one entry name against the live loader entries. @returns whether the table changed. */ private processOne(entryName: string): boolean { let qualifies = false diff --git a/packages/client/modules/tests/loader.client.spec.ts b/packages/client/modules/tests/loader.client.spec.ts index 4ec0510d59..37813ef6fb 100644 --- a/packages/client/modules/tests/loader.client.spec.ts +++ b/packages/client/modules/tests/loader.client.spec.ts @@ -451,6 +451,16 @@ describe('HMR reset', () => { expect(b.fetched.at(-1)).toBe('https://plugins.example.test/plugins/a/client.js?rev=next') }) + it('preserves a protocol-relative individual endpoint when applying the rebuilt revision', async () => { + const b = bench([ + row('a', { url: '//plugins.example.test/plugins/a/client.js?rev=0' }), + ], { a: () => ({}) }) + await b.loader.import('a', '', {}) + b.loader.invalidate('a', 'next') + await b.loader.prefetch('a') + expect(b.fetched.at(-1)).toBe('//plugins.example.test/plugins/a/client.js?rev=next') + }) + it('uses the current individual revision when a graph-row invalidation omits an override', async () => { const b = bench([row('a')], { a: () => ({}) }) await b.loader.import('a', '', {}) diff --git a/packages/client/modules/tests/node-half.client.spec.ts b/packages/client/modules/tests/node-half.client.spec.ts index 28267e7d81..f22c8e3b18 100644 --- a/packages/client/modules/tests/node-half.client.spec.ts +++ b/packages/client/modules/tests/node-half.client.spec.ts @@ -258,18 +258,20 @@ describe('client bundle activation', () => { expect(String(thrown)).not.toContain('pnpm run build') }) - it('rejects a malformed built source map during composition', () => { + 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`, '{}\n') - expect(() => construct([packageName])) - .toThrow(`${clientPath}.map is not a regular Source Map v3 object`) + 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])) - .toThrow(`${clientPath}.map is not a regular Source Map v3 object`) + expect(() => construct([packageName])).not.toThrow() }) it('retains one prior immutable batch generation across rebuild recomposition', async () => { From 47bf44a5bb7cc3174556f3c4bbd0d28da96bd061 Mon Sep 17 00:00:00 2001 From: lsdsjy <1356263+lsdsjy@users.noreply.github.com> Date: Mon, 24 Aug 2026 12:17:44 +0800 Subject: [PATCH 4/6] fix(client-modules,webserver,webworker-runtime): preserve batched boot across transports --- ...-08-19-web-index-injection-table.i18n.yaml | 4 +- .../2026-08-19-web-index-injection-table.md | 6 +-- ...2026-08-19-web-index-injection-table.zh.md | 6 +-- packages/client/modules/src/index.ts | 15 +------ packages/client/web/tests/boot.client.spec.ts | 44 ++++++++++--------- .../webworker-runtime/README.i18n.yaml | 4 +- .../experimental/webworker-runtime/README.md | 2 +- .../webworker-runtime/README.zh.md | 2 +- .../src/client/apply-injections.ts | 4 ++ .../tests/client/apply-injections.spec.ts | 21 +++++++++ .../extensions/tool-cordis/src/api-catalog.ts | 2 +- packages/host/webserver/README.i18n.yaml | 4 +- packages/host/webserver/README.md | 2 +- packages/host/webserver/README.zh.md | 2 +- packages/host/webserver/src/injections.ts | 4 ++ .../host/webserver/tests/webserver.spec.ts | 2 + 16 files changed, 73 insertions(+), 51 deletions(-) create mode 100644 packages/experimental/webworker-runtime/tests/client/apply-injections.spec.ts diff --git a/.agents/notes/implemented/architecture/2026-08-19-web-index-injection-table.i18n.yaml b/.agents/notes/implemented/architecture/2026-08-19-web-index-injection-table.i18n.yaml index 90d1f96dff..d3fab99c56 100644 --- a/.agents/notes/implemented/architecture/2026-08-19-web-index-injection-table.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-08-19-web-index-injection-table.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-08-19-web-index-injection-table.md -2026-08-19-web-index-injection-table.md: 9ed02aa94cd318d107a32802d8723652e6b10ea2 -2026-08-19-web-index-injection-table.zh.md: 8ad036766faa14071b20da12ef907ab012cae23f +2026-08-19-web-index-injection-table.md: 050690946a73ce453946f6d1152c9e86e1ba3aaf +2026-08-19-web-index-injection-table.zh.md: 27d1cbce1dc39ebe22e0b79e52f9ce935279ee69 diff --git a/.agents/notes/implemented/architecture/2026-08-19-web-index-injection-table.md b/.agents/notes/implemented/architecture/2026-08-19-web-index-injection-table.md index 9ed02aa94c..050690946a 100644 --- a/.agents/notes/implemented/architecture/2026-08-19-web-index-injection-table.md +++ b/.agents/notes/implemented/architecture/2026-08-19-web-index-injection-table.md @@ -10,16 +10,16 @@ The web shell's boot HTML needs three kinds of injection: client-modules' boot p ## Decision -Make the injection surface an event over pure data: the webserver declares the `webserver/index-inject` event and the `IndexInjection` row union (`global`/`script`/`script-src`/`style`/`html`, `head|body` placement). A plugin that wants to inject subscribes and pushes rows; every collection (`collectIndexInjections()`) is a fresh emit, so subscribers read live state at emit time (module graph, theme preference — no re-registration staleness), and a subscription dies with its fiber. +Make the injection surface an event over pure data: the webserver declares the `webserver/index-inject` event and the `IndexInjection` row union (`global`/`script`/`script-src`/`script-preload`/`style`/`html`, with placement where applicable). A plugin that wants to inject subscribes and pushes rows; every collection (`collectIndexInjections()`) is a fresh emit, so subscribers read live state at emit time (module graph, theme preference — no re-registration staleness), and a subscription dies with its fiber. -One table, two renderers: the served form's `webServer.renderIndex(html)` renders rows into index.html deterministically (head rows after the opening head tag, body rows after the opening body tag; `<` JSON-escaped in global values, attribute-escaped `src`); the worker form's `/__boot__` payload is `{ injections }`, executed row by row by a small page-side interpreter (set global / create script element / load external through the tunnel's `loadBundle` / mount style and markup). Rows are pure JSON data — that is the both-ends-equivalent discipline. +One table, two renderers: the served form's `webServer.renderIndex(html)` renders rows into index.html deterministically (head rows after the opening head tag, body rows after the opening body tag; `<` JSON-escaped in global values, attribute-escaped `src`); the worker form's `/__boot__` payload is `{ injections }`, executed row by row by a small page-side interpreter (set global / create script element / load external through the tunnel's `loadBundle` / mount style and markup). A `script-preload` row renders a browser preload hint in served HTML and is ignored by the worker interpreter, whose `/plugins` resources exist only behind the tunnel and load on demand. Rows are pure JSON data — that is the both-ends-equivalent discipline. `tapIndex`/`applyIndexTaps` survive as the raw-HTML escape hatch, applied after row rendering; every internal consumer moved to the event. ## Consequences - client-modules and ui-theme no longer regex-edit HTML; the worker's `readBootPayload` service-poking (`clientModules`, `settings`, theme constants through `loader.load`) is deleted; the page-side `installModuleLoaderFacade`, `applyBootTheme`, and `PARSER_PRELOAD_IDS` re-implementations retire. -- Ordering: across subscribers, subscription order (same as the old tap order); within one subscriber, push order — modules itself guarantees queue → preloads → global. +- Ordering: across subscribers, subscription order (same as the old tap order); within one subscriber, push order — modules itself guarantees queue → application preload → bootstrap script → global. - The served rendering of the manifest global changed from `window.__DSH_BOOT__ =` to `globalThis["__DSH_BOOT__"] =`; no committed snapshot expectation carries that text, so none needed re-recording. - New model-visible or page-visible boot inputs extend the row union; no new tap consumers. diff --git a/.agents/notes/implemented/architecture/2026-08-19-web-index-injection-table.zh.md b/.agents/notes/implemented/architecture/2026-08-19-web-index-injection-table.zh.md index 8ad036766f..27d1cbce1d 100644 --- a/.agents/notes/implemented/architecture/2026-08-19-web-index-injection-table.zh.md +++ b/.agents/notes/implemented/architecture/2026-08-19-web-index-injection-table.zh.md @@ -10,16 +10,16 @@ Web 壳的启动 HTML 需要三类注入:client-modules 的引导协议(`__M ## Decision -注入面事件化、数据化:webserver 声明 `webserver/index-inject` 事件与纯数据行类型 `IndexInjection`(`global`/`script`/`script-src`/`style`/`html`,`head|body` 定位)。想注入的插件订阅事件、往表里 push 行;每次收集(`collectIndexInjections()`)都是一次全新 emit,订阅方现读现填(模块图、主题偏好天然新鲜,无重注册问题),订阅随 fiber 销毁自动摘除。 +注入面事件化、数据化:webserver 声明 `webserver/index-inject` 事件与纯数据行类型 `IndexInjection`(`global`/`script`/`script-src`/`script-preload`/`style`/`html`,在适用的行上携带定位)。想注入的插件订阅事件、往表里 push 行;每次收集(`collectIndexInjections()`)都是一次全新 emit,订阅方现读现填(模块图、主题偏好天然新鲜,无重注册问题),订阅随 fiber 销毁自动摘除。 -一张表两个渲染器:served 形态 `webServer.renderIndex(html)` 确定性把行渲染进 index.html(head 行插 head 首、body 行插 body 首,全局值 JSON `<` 转义、src 属性转义);worker 形态 `/__boot__` 载荷就是 `{ injections }`,页面侧小解释器逐行执行(设全局 / 建脚本元素 / 经 tunnel loadBundle 载外链 / 挂样式与 DOM)。行是纯 JSON 数据,这是双端等价的纪律。 +一张表两个渲染器:served 形态 `webServer.renderIndex(html)` 确定性把行渲染进 index.html(head 行插 head 首、body 行插 body 首,全局值 JSON `<` 转义、src 属性转义);worker 形态 `/__boot__` 载荷就是 `{ injections }`,页面侧小解释器逐行执行(设全局 / 建脚本元素 / 经 tunnel loadBundle 载外链 / 挂样式与 DOM)。`script-preload` 行在 served HTML 中渲染为浏览器预加载提示;worker 解释器忽略它,因为 `/plugins` 资源只存在于 tunnel 后方,并在实际需要时加载。行是纯 JSON 数据,这是双端等价的纪律。 `tapIndex`/`applyIndexTaps` 保留为原始 HTML 变换的逃生口,在行渲染之后执行;内部消费者全部迁走。 ## Consequences - client-modules 与 ui-theme 不再各自正则改 HTML;worker 侧 `readBootPayload` 的 `ctx.get` 手掏(clientModules、settings、theme 常量 loader.load)删除;页面侧 `installModuleLoaderFacade`、`applyBootTheme`、`PARSER_PRELOAD_IDS` 三份重抄退役。 -- 顺序语义:跨订阅方按订阅注册顺序(与旧 tap 顺序一致),单订阅方内按 push 顺序;modules 自己保证 队列→preload→全局 三行有序。 +- 顺序语义:跨订阅方按订阅注册顺序(与旧 tap 顺序一致),单订阅方内按 push 顺序;modules 自己保证队列→application preload→bootstrap script→全局的顺序。 - `__DSH_BOOT__` 的 served 渲染文本从 `window.__DSH_BOOT__ =` 变为 `globalThis["__DSH_BOOT__"] =`;已核实无已提交快照期望含此文本,无需重录。 - 新的模型可见/页面可见注入一律走行类型扩展,不再新增 tap 消费者。 diff --git a/packages/client/modules/src/index.ts b/packages/client/modules/src/index.ts index 27ce53e35a..f8344207e9 100644 --- a/packages/client/modules/src/index.ts +++ b/packages/client/modules/src/index.ts @@ -351,15 +351,6 @@ const CLIENT_MODULES_ID = '@deepseek-ai/dsh-client-modules' /** Dynamic bundles grouped into the parser bootstrap batch before the Vite shell. */ const PARSER_PRELOAD_IDS = [CLIENT_MODULES_ID] as const -/** Escape a graph URL before placing it in a quoted HTML attribute. */ -function escapeHtmlAttribute(value: string): string { - return value - .replaceAll('&', '&') - .replaceAll('"', '"') - .replaceAll('<', '<') - .replaceAll('>', '>') -} - /** * The boot protocol as index injection rows. The inline registration queue * precedes the application-batch preload and the blocking bootstrap batch. Its @@ -398,11 +389,7 @@ window.__ModuleLoader__={ const application = graph.batches.find(batch => batch.phase === 'application') const rows: IndexInjection[] = [{ kind: 'script', placement: 'head', text: queue }] if (application !== undefined) { - rows.push({ - kind: 'html', - placement: 'head', - html: ``, - }) + rows.push({ kind: 'script-preload', src: application.url }) } if (bootstrap !== undefined) { rows.push({ kind: 'script-src', placement: 'head', src: bootstrap.url }) diff --git a/packages/client/web/tests/boot.client.spec.ts b/packages/client/web/tests/boot.client.spec.ts index 8d75949b78..34b13d40ad 100644 --- a/packages/client/web/tests/boot.client.spec.ts +++ b/packages/client/web/tests/boot.client.spec.ts @@ -106,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() }) 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 65f359f42a..5a190d87d1 100644 --- a/packages/extensions/tool-cordis/src/api-catalog.ts +++ b/packages/extensions/tool-cordis/src/api-catalog.ts @@ -3765,7 +3765,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', 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>"}', '', '', From 9c3a0893f622620bd9016bfabb95ddcfd07cf18b Mon Sep 17 00:00:00 2001 From: imccyu <276526105+imccyu@users.noreply.github.com> Date: Mon, 24 Aug 2026 18:15:14 +0800 Subject: [PATCH 5/6] perf(client-modules): defer per-plugin revision hashing Preserve sourcemaps through the production Client build and verify batched loading across Host, HMR, and Web Worker paths. --- ...7-23-client-plugin-loading-model.i18n.yaml | 4 +- .../2026-07-23-client-plugin-loading-model.md | 10 +-- ...26-07-23-client-plugin-loading-model.zh.md | 10 +-- apps/web/tests/smoke-real.e2e.ts | 44 +++++++++- docs/subsystems/client-modules.i18n.yaml | 4 +- docs/subsystems/client-modules.md | 34 +++++++- docs/subsystems/client-modules.zh.md | 34 +++++++- packages/client/hmr/README.i18n.yaml | 4 +- packages/client/hmr/README.md | 2 +- packages/client/hmr/README.zh.md | 2 +- packages/client/hmr/src/index.ts | 47 +++++------ .../client/hmr/tests/node-half.client.spec.ts | 50 ++++++++--- packages/client/modules/README.i18n.yaml | 4 +- packages/client/modules/README.md | 2 +- packages/client/modules/README.zh.md | 2 +- .../client/modules/src/client/manifest.ts | 4 +- packages/client/modules/src/index.ts | 84 ++++++++++++++++--- .../modules/tests/node-half.client.spec.ts | 68 +++++++++++---- packages/client/tsdown.client.ts | 52 ++++++++---- .../extensions/tool-cordis/src/api-catalog.ts | 10 +++ scripts/client-bundle-purity.spec.ts | 42 +++++++++- scripts/gen-cordis-catalog.ts | 1 + scripts/type-equiv.manifest.json | 5 ++ 23 files changed, 402 insertions(+), 117 deletions(-) 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 63d42117b6..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: a16c022bc2d4f96bd2680a637e02a485ba4f2697 -2026-07-23-client-plugin-loading-model.zh.md: 96c6b85cd6d7bdb0cbfce4479d2cfe5b7e74f2a5 +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 a16c022bc2..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. @@ -42,9 +42,9 @@ The vendored Loader consumes the module system through its `internal` contract The Host snapshots every built plugin artifact and concatenates its factory registration into one of two same-origin classic scripts. The parser-blocking `bootstrap` batch contains the modules row; the HTML preloads the `application` batch containing every other graph row while bootstrap executes. The module system keys in-flight transport by batch URL, so concurrent row arrivals execute one application script. Successful settlement still requires each requested row's factory id to exist in the module table, and registration does not run the factory, so the side-effect boundary remains first materialization. -The shared tsdown preset emits `client.js.map` for every plugin and rewrites first-party source paths into the browser-resolvable repository shape `/packages///src/...`. Other workspace sources inlined into a bundle likewise resolve to their `packages/` owner, while dependency paths remain unchanged; `sourcesContent` carries the source. Batch generation strips each local `sourceMappingURL`, records its generated-line offset, resolves every source against the original per-plugin map URL, and emits one indexed Source Map v3 file whose sections embed the available plugin maps. The Vite shell also emits source maps, letting shell code and batched or individually reloaded plugins map stacks and performance profiles back to TypeScript/TSX. +The shared tsdown preset emits `client.js.map` for every plugin and rewrites first-party source paths into the browser-resolvable repository shape `/packages///src/...`. The production Client pass consumes `lib/types`; the preset supplies each tsc map to Rolldown and fills `sourcesContent` from the original files, so the final map reaches TypeScript/TSX instead of stopping at emitted JavaScript. Other workspace sources inlined into a bundle likewise resolve to their `packages/` owner, while dependency paths remain unchanged. Batch generation strips each local `sourceMappingURL`, records its generated-line offset, resolves every source against the original per-plugin map URL, and emits one indexed Source Map v3 file whose sections embed the available plugin maps. The Vite shell also emits source maps, letting shell code and batched or individually reloaded plugins map stacks and performance profiles back to TypeScript/TSX. -The graph retains each row's revisioned individual URL for HMR and adds content-addressed descriptors for the two startup batches. Versioned scripts and maps use immutable caching. The Host serves snapshotted bytes only when the requested revision matches; stale or missing revisions return 404 instead of aliasing newer bytes. An external script's `error` event exposes neither response status nor body, so failure diagnostics name only the URL; the same-origin Host and build-stamped registration id form the identity boundary, while the post-`load` factory-presence check rejects an artifact that did not register the expected id. +The graph retains each row's revisioned individual URL for HMR and adds content-addressed descriptors for the two startup batches. Initial row revisions are opaque process nonces rather than content hashes; they keep an exceptional initial individual request immutable without hashing every plugin at startup. After the watcher observes one artifact change, `rebuilt(id)` hashes only that bundle and map and publishes the resulting revision. Versioned scripts and maps use immutable caching. The Host serves snapshotted bytes only when the requested revision matches; stale or missing revisions return 404 instead of aliasing newer bytes. An external script's `error` event exposes neither response status nor body, so failure diagnostics name only the URL; the same-origin Host and build-stamped registration id form the identity boundary, while the post-`load` factory-presence check rejects an artifact that did not register the expected id. ### The loading flow, end to end @@ -54,7 +54,7 @@ What happens between `dsh web` starting and the UI appearing? Three stages: the 1. The composing app (`apps/cli`) ships the roster as ordinary rows in its `cordis.yml` config tree — client plugin packages are entry rows like every host plugin, including the always-mounted `client-hmr` row. A roster row that fails to import is caught by `assertEntriesLoaded`; a row whose fiber rejects is reported with its original stack by `assertEntriesActivated` ([host boot decision](2026-07-24-web-config-tree-boot-and-transport-layering.md)). 2. The `dsh-client-modules` node half (the package is dual-face: its browser half is the module table) scans loader entries' package.json `dsh.client` declarations and composes `window.__DSH_BOOT__`: `{ rev, entries: [{ id, url, rev, inject?, immediately?, external? }], batches: [{ phase, url, rev, entries }] }`. The row's three optional fields come from manifests, never hand-copied. Composition orders requested dynamic rows before their consumers, rejects synchronous request cycles, and assigns every row to exactly one initial batch. It refuses declared plugins without built `./client` bundles and groups their package/path rows under one required source-build instruction; malformed declaration fields also fail activation, and the Host audit reports either error from the FAILED fiber. -3. Scanning is incremental per package — there is no full-rescan code path. Each cordis `internal/plugin` emission marks the fiber's entry name dirty (entry-less fibers drop O(1)); a microtask flush reconciles each dirty name against live loader entries, with package metadata (including the negative "not a client package" verdict) cached per name forever and bundle re-hashing reachable only through `rebuilt(id)`. The activation pass seeds the same dirty set from current entries and flushes synchronously, so first scan and steady state share one implementation. Each bundle plus its available map hashes into the row `rev`; batch revisions hash their script plus indexed map, and the rows plus batch descriptors hash into `graph.rev`. The graph types are single-sourced in the modules package's `./client` export — the webserver knows nothing about the graph, while modules registers the bundle route and contributes structured index-injection rows. +3. Scanning is incremental per package — there is no full-rescan code path. Each cordis `internal/plugin` emission marks the fiber's entry name dirty (entry-less fibers drop O(1)); a microtask flush reconciles each dirty name against live loader entries, with package metadata (including the negative "not a client package" verdict) cached per name forever and bundle re-hashing reachable only through `rebuilt(id)`. The activation pass seeds the same dirty set from current entries and flushes synchronously, so first scan and steady state share one implementation. Initial rows receive an opaque process nonce plus sequence without hashing their artifacts; batch revisions hash the generated script plus indexed map, and the rows plus batch descriptors hash into `graph.rev`. The graph types are single-sourced in the modules package's `./client` export — the webserver knows nothing about the graph, while modules registers the bundle route and contributes structured index-injection rows. Why is the roster yml rows and not a scan? Because which plugins compose into a deployment is a composition decision, not a package property — a package declaring `dsh.client` in the repo does not mean this deployment mounts it, so discovery-by-scan cannot make that call; the node half scans only what the tree actually mounted. @@ -72,7 +72,7 @@ Why is the roster yml rows and not a scan? Because which plugins compose into a Hot reload is a composition decision: the web bundle mounts the `client-hmr` row (a normal plugin package) unconditionally; its node half brings the bundle watch and the SSE channel, and the chain stays idle until a rebuild watcher rewrites client bundles. A composition that must not expose it disables the row. -How does a rebuilt bundle become a reload signal? The hmr node half observes it itself — no builder tells it. It reads bundle paths from `ctx.clientModules.clientPath(id)`, and one HMR-owned interval stat-polls every current graph row's script and optional map. Adding a row is ordered as synchronous artifact baseline, then immediate `clientModuleHost.rebuilt(id)`: a write after the module host's graph hash but before that baseline is caught by the immediate re-hash, while a write after the baseline leaves a stat delta for the next poll. This avoids `fs.watchFile`, whose asynchronous first baseline can silently absorb a construction-time rebuild. Watch membership follows `onGraphChanged`; vanished rows drop out, and a bundle missing at poll time keeps its row dirty so reappearance forces a re-hash even with identical metadata. On a script/map mtime or size delta, or a dirty row, `clientModuleHost.rebuilt(id)` is the single re-hash entry point; when the `rev` actually changed, the node half broadcasts a `rebuilt` frame on `GET /plugins/events` — a system SSE channel that sends the full graph on connect and `rebuilt` frames on change, presentation-only wire that never enters the session log. Polling is deliberate because inotify does not fire on the weka network mount, the same reason the build-side watcher needs `--poll`; the interval is a validated config field (default 500ms), and disposal clears the one timer. Rebuilding artifacts is any tsdown watch process's business — `scripts/dev-web.ts` remains the watch-build entry point, discovering its package list through `dsh.client` while scanning `packages/*/*/package.json` at startup — and builder and host share zero protocol. A torn read self-heals: stats keep changing while the write completes, so the next poll re-hashes and broadcasts the final rev. +How does a rebuilt bundle become a reload signal? The hmr node half observes it itself — no builder tells it. Before reading each startup snapshot, the module host captures the bundle and optional-map stat baseline and exposes it through `ctx.clientModules.artifactBaseline(id)`. One HMR-owned interval compares every current graph row with that baseline. An unchanged row starts watching without a content read or hash; a write after baseline capture is already a stat delta and only that row enters `rebuilt(id)`. This avoids both an initial all-row re-hash and `fs.watchFile`, whose asynchronous first baseline can silently absorb a construction-time rebuild. Watch membership follows `onGraphChanged`; vanished rows drop out, and a bundle missing at poll time keeps its row dirty so reappearance forces a re-hash even with identical metadata. On a script/map mtime or size delta, or a dirty row, `rebuilt(id)` is the single re-hash entry point; when the `rev` actually changed, the node half broadcasts a `rebuilt` frame on `GET /plugins/events` — a system SSE channel that sends the full graph on connect and `rebuilt` frames on change, presentation-only wire that never enters the session log. Polling is deliberate because inotify does not fire on the weka network mount, the same reason the build-side watcher needs `--poll`; the interval is a validated config field (default 500ms), and disposal clears the one timer. Rebuilding artifacts is any tsdown watch process's business — `scripts/dev-web.ts` remains the watch-build entry point, discovering its package list through `dsh.client` while scanning `packages/*/*/package.json` at startup — and builder and host share zero protocol. A torn read self-heals: stats keep changing while the write completes, so the next poll re-hashes and broadcasts the final rev. On the browser side, the driver reloads one plugin per frame, serialized: diff --git a/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.zh.md b/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.zh.md index 96c6b85cd6..68fe9b912c 100644 --- a/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.zh.md +++ b/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.zh.md @@ -14,7 +14,7 @@ host 侧,cordis 插件装载站在 Node 的模块机制之上——require cac 常规前端工程在构建期消化全部依赖:单一 bundle,external 由打包器解决,运行时无物可管。在此之上再做运行时模块管理,正是这里的特殊需求。client 因此拆成两层:上层是经同一份 vendored Loader 的 cordis 插件装载,下层是模块粒度的依赖管理——`dsh-client-modules`。 -下层供给四项能力:external(平台清单)、远程到达(同源外部 classic script 加惰性工厂登记)、版本化(内容哈希 rev)、热更新(invalidate/prefetch)。 +下层供给四项能力:external(平台清单)、远程到达(同源外部 classic script 加惰性工厂登记)、不可变的版本化交付、热更新(invalidate/prefetch)。 插件 bundle 独立构建在 Vite 模块图之外。若把响应文本塞进内联 script,浏览器只能看到一次动态源码执行:网络资源、生成 bundle、TypeScript/TSX 源码之间没有标准 sourcemap 链,性能 profile 与 stack 只能落到生成后的 `client.js`;模块系统还要持有整份源码文本,并把同一项到达职责拆成 fetch 与 execute 两道传输边界。 @@ -42,9 +42,9 @@ vendored Loader 经其 `internal` 约定消费模块系统——唯一调用点 Host 会快照每个已构建插件产物,并把其 factory registration 拼入两个同源 classic script 之一。阻塞 parser 的 `bootstrap` 批次包含 modules row;HTML 在 bootstrap 执行期间预加载包含其余全部 graph row 的 `application` 批次。模块系统按批次 URL 复用进行中的传输,因此并发 row 到达只执行一次 application 脚本。成功结算仍要求模块表中已经存在被请求 row 的 factory id;登记不会运行 factory,所以副作用边界依然是首次物化。 -共享 tsdown 预设为每个插件产出 `client.js.map`,并把第一方源码路径重写成浏览器可识别的仓库形状 `/packages///src/...`。内联进 bundle 的其他 workspace 源码同样回到其 `packages/` 归属,依赖包路径保持原样;`sourcesContent` 承载源码。批次生成会移除每个局部 `sourceMappingURL`、记录其生成行偏移、以原插件 map URL 解析每个 source,再产出一份以 section 内嵌现有插件 map 的 indexed Source Map v3 文件。Vite 壳也产出 sourcemap,使壳代码以及批量或独立重载的插件都能从 stack 和性能 profile 回到 TypeScript/TSX。 +共享 tsdown 预设为每个插件产出 `client.js.map`,并把第一方源码路径重写成浏览器可识别的仓库形状 `/packages///src/...`。生产 Client 构建会消费 `lib/types`;预设把每份 tsc map 交给 Rolldown,并从原文件补齐 `sourcesContent`,使最终 map 回到 TypeScript/TSX,而不是停在编译后的 JavaScript。内联进 bundle 的其他 workspace 源码同样回到其 `packages/` 归属,依赖包路径保持原样。批次生成会移除每个局部 `sourceMappingURL`、记录其生成行偏移、以原插件 map URL 解析每个 source,再产出一份以 section 内嵌现有插件 map 的 indexed Source Map v3 文件。Vite 壳也产出 sourcemap,使壳代码以及批量或独立重载的插件都能从 stack 和性能 profile 回到 TypeScript/TSX。 -图为 HMR 保留每个 row 带 revision 的独立 URL,并为两个启动批次增加按内容寻址的描述。版本化脚本与 map 使用 immutable 缓存。Host 只在请求 revision 匹配时提供已快照字节;陈旧或缺失 revision 返回 404,不会在旧 URL 下别名到新字节。外部脚本的 `error` 事件不给响应状态与正文,因此失败诊断只报告 URL;同源 Host 与构建期写入的 registration id 是身份边界,`load` 后的 factory 存在性检查负责拒绝未登记预期 id 的产物。 +图为 HMR 保留每个 row 带 revision 的独立 URL,并为两个启动批次增加按内容寻址的描述。初始 row revision 是进程级不透明 nonce,而不是内容哈希;它无需在启动时哈希每个插件,也能保证异常情况下的初始独立请求不可变。watcher 观察到某个产物变化后,`rebuilt(id)` 只哈希该 bundle 与 map,并发布所得 revision。版本化脚本与 map 使用 immutable 缓存。Host 只在请求 revision 匹配时提供已快照字节;陈旧或缺失 revision 返回 404,不会在旧 URL 下别名到新字节。外部脚本的 `error` 事件不给响应状态与正文,因此失败诊断只报告 URL;同源 Host 与构建期写入的 registration id 是身份边界,`load` 后的 factory 存在性检查负责拒绝未登记预期 id 的产物。 ### 装载流程,端到端 @@ -54,7 +54,7 @@ Host 会快照每个已构建插件产物,并把其 factory registration 拼 1. 负责组合的 app(`apps/cli`)把名册作为普通行放进它的 `cordis.yml` 配置树——client 插件包与每个 host 插件一样是 entry 行,包括无条件挂载的 `client-hmr` 行。名册行 import 失败由 `assertEntriesLoaded` 捕获;fiber reject 的行则由 `assertEntriesActivated` 报告原始 stack([host boot 决策](2026-07-24-web-config-tree-boot-and-transport-layering.zh.md))。 2. `dsh-client-modules` 的 node 半(该包是双面的:浏览器半就是模块表)扫描 loader entry 的 package.json `dsh.client` 声明,组合出 `window.__DSH_BOOT__`:`{ rev, entries: [{ id, url, rev, inject?, immediately?, external? }], batches: [{ phase, url, rev, entries }] }`。Row 的三个可选字段都来自 manifest,永不人肉抄写。组合会把被请求的动态图 row 排到消费者之前、拒绝同步请求环,并把每个 row 恰好分配给一个初始批次。它会拒绝没有已构建 `./client` bundle 的已声明插件,并把它们的 package/path 行归到一条源码构建要求下;畸形声明字段同样会让激活失败,Host 检查会从 FAILED fiber 报告这两类错误。 -3. 扫描是单包增量——不存在全量重扫代码路径。每次 cordis `internal/plugin` 发射把该 fiber 的 entry 名标脏(无 entry 的 fiber O(1) 丢弃);微任务 flush 把每个脏名对账 live loader entries,包元数据(含「非 client 包」的否定结论)按名永久缓存,bundle 重哈希只经 `rebuilt(id)` 可达。激活趟从当前 entries 灌同一脏集合并同步 flush,初扫与稳态共享一条实现。每个 bundle 及其可用 map 共同哈希为 row `rev`;批次 revision 对脚本及 indexed map 求哈希,row 与批次描述再共同哈希进 `graph.rev`。图类型单源在 modules 包的 `./client` 出口——webserver 对图一无所知;modules 会注册 bundle 路由并贡献结构化 index 注入行。 +3. 扫描是单包增量——不存在全量重扫代码路径。每次 cordis `internal/plugin` 发射把该 fiber 的 entry 名标脏(无 entry 的 fiber O(1) 丢弃);微任务 flush 把每个脏名对账 live loader entries,包元数据(含「非 client 包」的否定结论)按名永久缓存,bundle 重哈希只经 `rebuilt(id)` 可达。激活趟从当前 entries 灌同一脏集合并同步 flush,初扫与稳态共享一条实现。初始 row 使用不透明的进程 nonce 加序号,不对其产物求哈希;批次 revision 对生成的脚本及 indexed map 求哈希,row 与批次描述再共同哈希进 `graph.rev`。图类型单源在 modules 包的 `./client` 出口——webserver 对图一无所知;modules 会注册 bundle 路由并贡献结构化 index 注入行。 为什么名册是 yml 行而不是扫描?因为哪些插件组合进一次部署是组合决策,不是包属性——一个在仓库中声明了 dsh.client 的包,不代表这次部署要挂载它,扫描发现无从替人做这个决定;node 半只扫描配置树实际挂载了的东西。 @@ -72,7 +72,7 @@ Host 会快照每个已构建插件产物,并把其 factory registration 拼 热重载是一项组合决策:web 组合包无条件挂载 `client-hmr` 行(一个常规的插件包),其 node 半带来 bundle 监视与 SSE(Server-Sent Events)通道;没有重建 watcher 改写客户端 bundle 时链路保持空闲。不应暴露它的组合可以禁用该行。 -重建好的 bundle 怎么变成重载信号?hmr 的 node 半自己观察——没有构建器来通知它。它从 `ctx.clientModules.clientPath(id)` 读取图上各行的 bundle 路径,由 HMR 自持的单个定时器对当前图每一行的脚本及可选 map 做 stat 轮询。新增图行时,顺序固定为先同步取得产物基线,再立即调用 `clientModuleHost.rebuilt(id)`:在模块 host 算出图哈希之后、取得基线之前发生的写入会被这次立即重哈希捕获;取得基线之后发生的写入则会留下 stat 差异,供下一次轮询捕获。这避开了 `fs.watchFile`:它以异步首次 stat 建立基线,可能把构造期间的重建静默吸收进基线。监视集合的成员随 `onGraphChanged` 更新;消失的行撤下监视,轮询时缺失的 bundle 则让对应行保持标脏状态,文件重现时即使元数据相同也强制重哈希。脚本/map 的 mtime 或 size 变化,或行处于标脏状态时,`clientModuleHost.rebuilt(id)` 是重哈希的唯一入口;当 `rev` 真的变了,node 半才在 `GET /plugins/events` 上广播 `rebuilt` 帧——这是一条系统级 SSE 通道,连接即发全量图,变更时发 `rebuilt` 帧,仅供呈现的 wire,永不进会话日志。轮询是刻意选择:inotify 在 weka 网络挂载上不触发,构建侧监视器需要 `--poll` 也是同一原因;轮询间隔是一个经校验的配置字段(默认 500ms),dispose(资源释放)会清掉那一个定时器。重建产物是任意一个 tsdown watch 进程的事——`scripts/dev-web.ts` 仍作为 watch 构建入口保留,其包清单在启动时扫描 `packages/*/*/package.json` 按 dsh.client 发现——构建器与 host 共享零协议。写一半的 bundle 被撕裂读取会自愈:写入完成期间 stat 持续变化,下一个轮询节拍会再次重哈希并广播最终的 rev。 +重建好的 bundle 怎么变成重载信号?hmr 的 node 半自己观察——没有构建器来通知它。模块 host 在读取每份启动快照前捕获 bundle 与可选 map 的 stat 基线,并通过 `ctx.clientModules.artifactBaseline(id)` 暴露它。HMR 自持的单个定时器把当前图的每个 row 与这份基线比较:未变化的 row 直接开始监视,不读取内容也不求哈希;基线捕获后的写入已经形成 stat 差异,只有该 row 会进入 `rebuilt(id)`。这同时消除了启动期的全量重哈希,并避开 `fs.watchFile` 以异步首次 stat 建立基线、可能静默吸收构造期重建的问题。监视集合的成员随 `onGraphChanged` 更新;消失的 row 撤下监视,轮询时缺失的 bundle 则让对应 row 保持标脏状态,文件重现时即使元数据相同也强制重哈希。脚本/map 的 mtime 或 size 变化,或 row 处于标脏状态时,`rebuilt(id)` 是重哈希的唯一入口;当 `rev` 真的变了,node 半才在 `GET /plugins/events` 上广播 `rebuilt` 帧——这是一条系统级 SSE 通道,连接即发全量图,变更时发 `rebuilt` 帧,仅供呈现的 wire,永不进会话日志。轮询是刻意选择:inotify 在 weka 网络挂载上不触发,构建侧监视器需要 `--poll` 也是同一原因;轮询间隔是一个经校验的配置字段(默认 500ms),dispose(资源释放)会清掉那一个定时器。重建产物是任意一个 tsdown watch 进程的事——`scripts/dev-web.ts` 仍作为 watch 构建入口保留,其包清单在启动时扫描 `packages/*/*/package.json` 按 dsh.client 发现——构建器与 host 共享零协议。写一半的 bundle 被撕裂读取会自愈:写入完成期间 stat 持续变化,下一个轮询节拍会再次重哈希并广播最终的 rev。 浏览器侧,驱动插件每帧重载一个插件,串行执行: diff --git a/apps/web/tests/smoke-real.e2e.ts b/apps/web/tests/smoke-real.e2e.ts index 58facd4b3e..ff17f77507 100644 --- a/apps/web/tests/smoke-real.e2e.ts +++ b/apps/web/tests/smoke-real.e2e.ts @@ -19,7 +19,7 @@ import { spawn } from 'node:child_process' import { randomUUID } from 'node:crypto' import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' import { createServer } from 'node:http' -import { createRequire } from 'node:module' +import { createRequire, SourceMap } from 'node:module' import { tmpdir } from 'node:os' import { join } from 'node:path' import { fileURLToPath, pathToFileURL } from 'node:url' @@ -203,6 +203,23 @@ async function waitForAssistantMarker(baseUrl: string, sessionId: string, marker }).toBe(true) } +/** Find one real source location through a served indexed map. */ +function firstMappedSource(script: string, payload: ConstructorParameters[0]): string | undefined { + const consumer = new SourceMap(payload) + const lines = script.split('\n') + for (let line = 0; line < lines.length; line++) { + const lastColumn = Math.min(lines[line]!.length, 512) + for (let column = 0; column <= lastColumn; column++) { + const entry = consumer.findEntry(line, column) + if (!('originalSource' in entry) || typeof entry.originalSource !== 'string') continue + if (entry.originalSource.startsWith('/packages/') && entry.originalSource.includes('/src/')) { + return entry.originalSource + } + } + } + return undefined +} + /** Real-host smoke screenshot: evidence for the figma comparison, not a failure artifact. */ async function screen(page: Page, name: string): Promise { await page.screenshot({ path: join(REPO_ROOT, '.artifacts', `w5-${name}.png`) }) @@ -237,7 +254,7 @@ const notReady = UI_PLUGIN_DIRS.filter((dir) => { if (notReady.length > 0) console.warn(`[smoke-real] skipped — client bundles not ready: ${notReady.join(', ')}`) describe('dsh web keyless CLI smoke', () => { - it('listens on 127.0.0.1 by default', async () => { + it('serves a usable app from two immutable plugin batches', async () => { requireDist() const sessionsDir = mkdtempSync(join(tmpdir(), 'dsh-web-keyless-')) const tsxLoader = pathToFileURL(createRequire(join(REPO_ROOT, 'package.json')).resolve('tsx')).href @@ -281,7 +298,8 @@ describe('dsh web keyless CLI smoke', () => { }) await page.goto(readyUrl) await page.getByRole('button', { name: 'New session', exact: true }).first().waitFor({ timeout: 30_000 }) - expect([...new Set(pluginScripts)].sort()).toEqual([ + const batchPaths = [...new Set(pluginScripts)].sort() + expect(batchPaths).toEqual([ expect.stringMatching(/^\/plugins\/_batch\/application\/[a-f\d]{12}\/client\.js$/), expect.stringMatching(/^\/plugins\/_batch\/bootstrap\/[a-f\d]{12}\/client\.js$/), ]) @@ -289,6 +307,26 @@ describe('dsh web keyless CLI smoke', () => { 'public, max-age=31536000, immutable', 'public, max-age=31536000, immutable', ]) + for (const path of batchPaths) { + const [scriptResponse, mapResponse] = await Promise.all([ + fetch(`${readyUrl}${path}`), + fetch(`${readyUrl}${path}.map`), + ]) + expect(scriptResponse.status).toBe(200) + expect(mapResponse.status).toBe(200) + const script = await scriptResponse.text() + const payload = await mapResponse.json() as ConstructorParameters[0] + const sections = (payload as unknown as { + sections: { map: { sources?: unknown[]; sourcesContent?: unknown[] } }[] + }).sections + expect(sections.every(section => ( + Array.isArray(section.map.sources) + && Array.isArray(section.map.sourcesContent) + && section.map.sourcesContent.length === section.map.sources.length + && section.map.sourcesContent.every(source => typeof source === 'string') + ))).toBe(true) + expect(firstMappedSource(script, payload)).toMatch(/^\/packages\/.+\/src\//) + } } finally { await browser?.close() const closed = child.exitCode === null diff --git a/docs/subsystems/client-modules.i18n.yaml b/docs/subsystems/client-modules.i18n.yaml index 529c670074..756b431f33 100644 --- a/docs/subsystems/client-modules.i18n.yaml +++ b/docs/subsystems/client-modules.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 docs/subsystems/client-modules.md -client-modules.md: b935c7328ff2fc5e8ac5ab427a95fcae01e8df22 -client-modules.zh.md: f65b764a1d66239c40117cabf2b286a3894ce07d +client-modules.md: 8dae05be292d8d5628c59b768d84dfd97dec1ef2 +client-modules.zh.md: 3668a4a3958b3a5957f094c0f925edb120d9b8c6 diff --git a/docs/subsystems/client-modules.md b/docs/subsystems/client-modules.md index b935c7328f..8dae05be29 100644 --- a/docs/subsystems/client-modules.md +++ b/docs/subsystems/client-modules.md @@ -24,7 +24,7 @@ interface WebBootEntry { id: string /** Revisioned individual endpoint used by HMR. */ url: string - /** Hash over the individual bundle and available source map. */ + /** Opaque individual-artifact revision used for HMR cache busting. */ rev: string /** Package-name dependency edges used for factory arrival and plugin composition. */ inject?: string[] @@ -70,7 +70,7 @@ interface WebBootGraph { } ``` -Each row's `rev` hashes the individual bundle and its available source map. The bootstrap batch contains the modules row; the preloaded application batch contains every other row. Batch revisions hash the generated script and indexed source map, and the graph revision hashes both rows and batch descriptors. `immediately` marks the stage-one registration barrier; application rows share one script transport even when only some carry the mark. +Each initial row's `rev` is an opaque process nonce plus sequence, so graph composition does not hash every individual artifact. After HMR observes a change, that row's revision becomes the hash of its new bundle and available source map. The bootstrap batch contains the modules row; the preloaded application batch contains every other row. Batch revisions hash the generated script and indexed source map, and the graph revision hashes both rows and batch descriptors. `immediately` marks the stage-one registration barrier; application rows share one script transport even when only some carry the mark. ## The scan @@ -86,9 +86,25 @@ Package metadata — including the negative "not a client package" verdict — i ## The service -`ClientModuleRegistry` (`ctx.clientModules`, defined in [`packages/client/modules/src/index.ts`](../../packages/client/modules/src/index.ts)) exposes reads and the rebuild face; signatures are in the generated [service catalog](#ctxclientmodules--clientmoduleregistry). `graph()` returns the current composed graph (a stable object between changes) and `clientPath(id)` the bundle's absolute path. `rebuilt(id)` is the only entry point through which bundle content reaches the graph: it re-hashes the file, and only a real rev change recomposes the graph and notifies. `onRebuilt` fires per changed bundle with the new rev; `onGraphChanged` fires after any flush that recomposed the graph (row added or removed, or a rebuilt rev change) and is pull-model — listeners re-read `graph()`. Both notification paths contain listener exceptions so one throwing subscriber cannot skip later subscribers or kill whatever triggered the flush. +```ts type-equiv +/** Filesystem baseline captured before a client artifact snapshot is read. */ +interface ClientArtifactBaseline { + /** Absolute path of the client bundle. */ + readonly path: string + /** Bundle modification time in milliseconds. */ + readonly mtimeMs: number + /** Bundle size in bytes. */ + readonly size: number + /** Source-map modification time, or null when no map was observable. */ + readonly mapMtimeMs: number | null + /** Source-map size in bytes, or null when no map was observable. */ + readonly mapSize: number | null +} +``` -In development, [dsh-client-hmr](../../packages/client/hmr/README.md) is the registry's watch driver: its node half stat-polls every graph row's bundle from a synchronously captured baseline, calls `rebuilt(id)` on change, resyncs its watch set through `onGraphChanged`, and broadcasts rev changes to the browser half over SSE. Production graphs omit the HMR row entirely; the module host itself never watches files. +`ClientModuleRegistry` (`ctx.clientModules`, defined in [`packages/client/modules/src/index.ts`](../../packages/client/modules/src/index.ts)) exposes reads and the rebuild face; signatures are in the generated [service catalog](#ctxclientmodules--clientmoduleregistry). `graph()` returns the current composed graph (a stable object between changes), `clientPath(id)` returns the bundle's absolute path, and `artifactBaseline(id)` returns the bundle/map stat values captured before the current snapshot was read. `rebuilt(id)` is the only entry point through which changed bundle content reaches the graph: it re-hashes that artifact, and only a real rev change recomposes the graph and notifies. `onRebuilt` fires per changed bundle with the new rev; `onGraphChanged` fires after any flush that recomposed the graph (row added or removed, or a rebuilt rev change) and is pull-model — listeners re-read `graph()`. Both notification paths contain listener exceptions so one throwing subscriber cannot skip later subscribers or kill whatever triggered the flush. + +In development, [dsh-client-hmr](../../packages/client/hmr/README.md) is the registry's watch driver: its node half stat-polls every graph row's bundle and optional map from the module host's pre-read baseline, calls `rebuilt(id)` only for a changed or dirty row, resyncs its watch set through `onGraphChanged`, and broadcasts rev changes to the browser half over SSE. Production graphs omit the HMR row entirely; the module host itself never watches files. @@ -118,6 +134,16 @@ graph(): WebBootGraph */ clientPath(id: string): string | undefined +/** + * 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. + * @param id - entry id (package name). + * @returns the path and baseline, or undefined for an unknown id. + */ +artifactBaseline(id: string): ClientArtifactBaseline | undefined + /** * Re-hash one bundle (the HMR watch's registration hook — the only entry * point through which bundle content changes reach the graph). diff --git a/docs/subsystems/client-modules.zh.md b/docs/subsystems/client-modules.zh.md index f65b764a1d..3668a4a395 100644 --- a/docs/subsystems/client-modules.zh.md +++ b/docs/subsystems/client-modules.zh.md @@ -24,7 +24,7 @@ interface WebBootEntry { id: string /** Revisioned individual endpoint used by HMR. */ url: string - /** Hash over the individual bundle and available source map. */ + /** Opaque individual-artifact revision used for HMR cache busting. */ rev: string /** Package-name dependency edges used for factory arrival and plugin composition. */ inject?: string[] @@ -70,7 +70,7 @@ interface WebBootGraph { } ``` -每一行的 `rev` 都对独立 bundle 及其可用 sourcemap 求哈希。Bootstrap 批次包含 modules row;预加载的 application 批次包含其他全部 row。批次 revision 对生成的脚本与 indexed sourcemap 求哈希,图 revision 则对 row 与批次描述一并求哈希。`immediately` 标记第一阶段的 registration barrier;即使只有部分 application row 携带该标记,它们仍共享一次脚本传输。 +每个初始 row 的 `rev` 都是不透明的进程 nonce 加序号,因此组合图时不会哈希每个独立产物。HMR 观察到变化后,该 row 的 revision 才改为新 bundle 及其可用 sourcemap 的哈希。Bootstrap 批次包含 modules row;预加载的 application 批次包含其他全部 row。批次 revision 对生成的脚本与 indexed sourcemap 求哈希,图 revision 则对 row 与批次描述一并求哈希。`immediately` 标记第一阶段的 registration barrier;即使只有部分 application row 携带该标记,它们仍共享一次脚本传输。 ## 扫描 @@ -86,9 +86,25 @@ interface WebBootGraph { ## 服务 -`ClientModuleRegistry`(`ctx.clientModules`,定义于 [`packages/client/modules/src/index.ts`](../../packages/client/modules/src/index.ts))暴露读取面与重建面;签名见生成的[服务目录](#ctxclientmodules--clientmoduleregistry)。`graph()` 返回当前组合出的图(两次变更之间是同一个稳定对象),`clientPath(id)` 返回该 bundle 的绝对路径。`rebuilt(id)` 是 bundle 内容到达图的唯一入口:它对文件重新哈希,只有 rev 真正变化才会重新组合图并发出通知。`onRebuilt` 按发生变化的 bundle 逐个触发并携带新 rev;`onGraphChanged` 在任何一次重新组合了图的 flush 之后触发(行的增删,或 rebuilt 带来的 rev 变化),并采用拉取模型——监听器自行重读 `graph()`。两条通知路径都会兜住监听器异常,因此一个抛错的订阅者既不能让后续订阅者被跳过,也不能杀死触发这次 flush 的一方。 +```ts type-equiv +/** Filesystem baseline captured before a client artifact snapshot is read. */ +interface ClientArtifactBaseline { + /** Absolute path of the client bundle. */ + readonly path: string + /** Bundle modification time in milliseconds. */ + readonly mtimeMs: number + /** Bundle size in bytes. */ + readonly size: number + /** Source-map modification time, or null when no map was observable. */ + readonly mapMtimeMs: number | null + /** Source-map size in bytes, or null when no map was observable. */ + readonly mapSize: number | null +} +``` -开发环境下,[dsh-client-hmr](../../packages/client/hmr/README.zh.md) 是注册表的监视驱动:它的 Node 半从同步取得的基线出发,对图中每一行的 bundle 做 stat 轮询,变化时调用 `rebuilt(id)`,经 `onGraphChanged` 重新同步监视集合,并通过 SSE(Server-Sent Events)把 rev 变化广播给浏览器半。生产环境的图完全不含 HMR(热模块替换)行;模块宿主自身从不监视文件。 +`ClientModuleRegistry`(`ctx.clientModules`,定义于 [`packages/client/modules/src/index.ts`](../../packages/client/modules/src/index.ts))暴露读取面与重建面;签名见生成的[服务目录](#ctxclientmodules--clientmoduleregistry)。`graph()` 返回当前组合出的图(两次变更之间是同一个稳定对象),`clientPath(id)` 返回 bundle 的绝对路径,`artifactBaseline(id)` 返回读取当前快照前捕获的 bundle/map stat 值。`rebuilt(id)` 是变化后的 bundle 内容到达图的唯一入口:它只对该产物重新哈希,只有 rev 真正变化才会重新组合图并发出通知。`onRebuilt` 按发生变化的 bundle 逐个触发并携带新 rev;`onGraphChanged` 在任何一次重新组合了图的 flush 之后触发(行的增删,或 rebuilt 带来的 rev 变化),并采用拉取模型——监听器自行重读 `graph()`。两条通知路径都会兜住监听器异常,因此一个抛错的订阅者既不能让后续订阅者被跳过,也不能杀死触发这次 flush 的一方。 + +开发环境下,[dsh-client-hmr](../../packages/client/hmr/README.zh.md) 是注册表的监视驱动:它的 Node 半从 module host 读文件前记录的基线出发,对图中每一行的 bundle 与可选 map 做 stat 轮询,只为变化或标脏的 row 调用 `rebuilt(id)`,经 `onGraphChanged` 重新同步监视集合,并通过 SSE(Server-Sent Events)把 rev 变化广播给浏览器半。生产环境的图完全不含 HMR(热模块替换)行;module host 自身从不监视文件。 @@ -118,6 +134,16 @@ graph(): WebBootGraph */ clientPath(id: string): string | undefined +/** + * 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. + * @param id - entry id (package name). + * @returns the path and baseline, or undefined for an unknown id. + */ +artifactBaseline(id: string): ClientArtifactBaseline | undefined + /** * Re-hash one bundle (the HMR watch's registration hook — the only entry * point through which bundle content changes reach the graph). diff --git a/packages/client/hmr/README.i18n.yaml b/packages/client/hmr/README.i18n.yaml index f843ddd484..4acf3d1284 100644 --- a/packages/client/hmr/README.i18n.yaml +++ b/packages/client/hmr/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/hmr/README.md -README.md: 5e1d960515094d1c4f18b69ec01d49dd780d0cb5 -README.zh.md: 2c82baac20f2a68b91c25e80ee4714b6ceb2e80c +README.md: 089b3ba35780ccb7a24bc8fed10cc0a5353c9eb9 +README.zh.md: e100dde3ced0f7272e9a75bc4d0a69f6beb4d4ee diff --git a/packages/client/hmr/README.md b/packages/client/hmr/README.md index 5e1d960515..089b3ba357 100644 --- a/packages/client/hmr/README.md +++ b/packages/client/hmr/README.md @@ -4,7 +4,7 @@ English | [中文](README.zh.md) Hot reload for script-loaded client plugins. The web bundle mounts the row unconditionally; without a rebuild watcher (`pnpm run dev:web`) rewriting client bundles, the poll observes no changes and the chain stays idle. -The browser half subscribes to the system SSE channel (`GET /plugins/events`) and reloads one plugin per `rebuilt` frame through a serialized queue. The frame revision makes `invalidate` select that plugin's immutable individual URL instead of its initial batch; `prefetch` loads and registers the new factory while the old fiber still serves. The remaining sequence is `registry.delete` (before the fiber: a bare fiber dispose trips the vendored Loader's self-dispose branch, which would mark the entry disabled), drain the old fiber, delete `entry.fiber`, remove owned `