Merge pull request #8133 from deepseek-harness/discuss-client-iframe

refactor(client): add client module js realm (with module manifest and style operation)
This commit is contained in:
imccyu authored and GitHub committed 2026-11-13 10:11:54 +08:00
1 parent 71753fdf91
commit 695f640063
146 files changed
+4410 -628

No files matched your search

@@ -15,20 +15,20 @@
en: 6af228b03e5e533f
zh: 276a522af6be5d7a
/agent-note-client-plugin-loading-lazy-factories-cordis-lifecycle-and-hot-reload/decision/one-module-system-one-plugin-governor:
en: 575aad62490f32e9
zh: a6c18eb63965fc1e
en: 5f5daec51b20db77
zh: e4d6f78fc1b4b835
/agent-note-client-plugin-loading-lazy-factories-cordis-lifecycle-and-hot-reload/decision/combo-external-script-arrival-and-source-maps:
en: 0a4240d88cca240a
zh: 8f5f1527caf571cd
/agent-note-client-plugin-loading-lazy-factories-cordis-lifecycle-and-hot-reload/decision/the-loading-flow-end-to-end:
en: dd05aa1ee608c414
zh: 2863ced0086e3122
en: 1f7db6ecfc0b0831
zh: f6bf37dc921a7d40
/agent-note-client-plugin-loading-lazy-factories-cordis-lifecycle-and-hot-reload/decision/live-graph-reconciliation:
en: 37e2fa1fe5cb2b95
zh: 80e513db87709cb4
en: ab9577214d7b2f2b
zh: fc8f10fd8c90b34b
/agent-note-client-plugin-loading-lazy-factories-cordis-lifecycle-and-hot-reload/decision/hot-reload-one-driver-plugin-self-watched-bundles:
en: c1fdcb3e6f074a7a
zh: b08c7b1ff25acb09
en: e6a0bee3d31cd2c6
zh: 7f7384c5d1a74751
/agent-note-client-plugin-loading-lazy-factories-cordis-lifecycle-and-hot-reload/package-ownership:
en: 94ca0d09e6fd1e3a
zh: d5949a2bdec795ba
@@ -34,7 +34,7 @@ The web kernel remains framework-free and imports no dynamic package value. Modu
The browser mirrors the host's division of labor. `dsh-client-modules` (`ClientModuleSystem`) takes the module-system seat that Node's internal ESM loader holds host-side; the same vendored `@cordisjs/plugin-loader` keeps the governance seat on both sides. The line between them in one sentence: **the module system owns module identity and bytes — how code arrives, registers, and becomes an exports; the Loader owns plugin lifecycle — when a plugin mounts, what it waits for, and how it is torn down.**
`ClientModuleSystem` is a lazy CJS table. Executing a bundle only **registers** its factory — an entry calls `window.__ModuleLoader__.load({ id, factory })`, while a chunk also supplies its generated filename — and nothing else happens. Every module body side effect, CSS injection included, lives inside the factory closure and runs at materialization: the first `require`/import of that id, memoized after that. Import and prefetch recursively register declared dynamic requests before their consumer; a factory then materializes any registered-but-unmaterialized request synchronously. The callable `require` resolves synchronous module-table requests; its `require.async` operation returns a Promise that loads, registers, and materializes one package-local chunk. The shared tsdown preset compiles source `import()` expressions for package-local chunks to that distinct operation. The supported output is self-contained: an entry or chunk cannot synchronously require another relative `client*.js` output. The table resolves through a fixed branch order: seed word → memoized record → graph-row classic-script registration → registered-factory materialization → loud throw. The modules factory is the bootstrap exception: the HTML facade materializes it first, and construction places those same exports directly in the memoized table. That final throw is the runtime mirror of the build-time purity gate. The system also keeps per-module bookkeeping — owned `<style data-plugin>` tag ids, observed require edges — and exposes the two verbs HMR needs: `prefetch(id)` (register the requested dynamic factories and the row's own factory; concurrent arrivals share one task) and `invalidate(id)` (advance the owner generation and drop a non-bootstrap package's entry and chunk factories and records so the next arrival reloads them). A chunk request captured under an older generation cannot populate the new generation.
`ClientModuleSystem` is a lazy CJS table. Executing a bundle only **registers** its factory — an entry calls `window.__ModuleLoader__.load({ id, factory })`, while a chunk also supplies its generated filename — and nothing else happens. JavaScript module body side effects live inside the factory closure and run at materialization: the first `require`/import of that id, memoized after that. Import and prefetch recursively register declared dynamic requests before their consumer; a factory then materializes any registered-but-unmaterialized request synchronously. The callable `require` resolves synchronous module-table requests; its `require.async` operation returns a Promise that loads, registers, and materializes one package-local chunk. The shared tsdown preset compiles source `import()` expressions for package-local chunks to that distinct operation. The supported output is self-contained: an entry or chunk cannot synchronously require another relative `client*.js` output. The table resolves through a fixed branch order: seed word → memoized record → graph-row classic-script registration → registered-factory materialization → loud throw. The modules factory is the bootstrap exception: the HTML facade materializes it first, and construction places those same exports directly in the memoized table. That final throw is the runtime mirror of the build-time purity gate. The system also keeps per-module bookkeeping — owner identity, optional opaque metadata producers, and observed require edges — and exposes the two verbs HMR needs: `prefetch(id)` (register the requested dynamic factories and the row's own factory; concurrent arrivals share one task) and `invalidate(id)` (advance the owner generation and drop a non-bootstrap package's entry and chunk factories and records so the next arrival reloads them). A chunk request captured under an older generation cannot populate the new generation.
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`.
@@ -70,9 +70,11 @@ Why is the roster yml rows and not a scan? Because which plugins compose into a
4. `settled` = every entry created + `loader.await()` quiescent + the boot audit. The audit lists each import-failed, FAILED, or PENDING fiber with its activation error or missing services. It exists because cordis inject waits have no timeout. An inactive entry on the browser required list rejects startup; other inactive entries produce one console warning ([startup policy](2026-09-09-consumer-owned-startup-strictness.md)).
5. The framework-free loading page projects real fiber states via `internal/status`. After the audit accepts the tree, the kernel calls `ctx.uiRenderer.mount(container)` and replaces the page with the real UI in one pass.
Stylesheet metadata and renderer ownership follow the [module metadata decision](2026-11-05-client-module-metadata.md); module loading retains the producer without evaluating it.
### Live graph reconciliation
The modules controller owns exactly the Loader entries created from the boot manifest. Full Host snapshots update its module descriptors and reconcile those entries; other Loader contributors retain ownership. New modules arrive through single-resource URLs because replaying a startup batch could register an existing factory twice. Removal uses Loader deletion, then drains the captured fiber before removing unused modules and styles. Declared and observed transitive requests keep shared modules alive. Factory revision tracking is independent of entry activation because a download or materialization can finish without creating an entry. Graph updates invalidate stale factories and failed arrival targets without managed entries, clearing their styles before any consumer imports its dependencies; rebuilt frames also reconcile entries missing after import failures.
The modules controller owns exactly the Loader entries created from the boot manifest. Full Host snapshots update its module descriptors and reconcile those entries; other Loader contributors retain ownership. New modules arrive through single-resource URLs because replaying a startup batch could register an existing factory twice. Removal uses Loader deletion, then drains the captured fiber before removing unused module records. Declared and observed transitive requests keep shared modules alive. Factory revision tracking is independent of entry activation because a download or materialization can finish without creating an entry. Graph updates invalidate stale factories and failed arrival targets without managed entries, notifying resource consumers before any consumer imports its dependencies; rebuilt frames also reconcile entries missing after import failures.
The Host SSE adapter forwards existing graph-change notifications and sends the current full graph on connection. The graph describes desired browser entries, not Host cleanup completion: Host lifecycle ordering belongs to its Loader, while each browser waits for its own removed fibers. Graph reconciliation and rebuilt code share one page-owned queue. Local generations prevent stale downloads from mounting; opaque revisions are compared only for equality. The settings inventory reports page-local errors and can retry the same graph without changing Host enablement. This preserves unrelated page state and avoids both an application restart and a second plugin executor. Electron's independent installation flow remains outside this mechanism.
@@ -88,8 +90,8 @@ On the browser side, the transport delegates code replacement to the same module
2. `prefetch` — load that one-resource external script and register the fresh factory while the old fiber still serves. The initial multi-resource script never executes again.
3. `registry.delete` — before touching the fiber. A bare fiber dispose trips the vendored Loader's self-dispose branch, which would disable the entry permanently.
4. Drain the old fiber's disposers.
5. Remove owned `<style data-plugin>` tags.
6. Materialize the new exports through the module system, then call `entry.refresh()` to mount them through Loader. CSS re-injects after the old disposers drain; explicit materialization exposes the import error before Loader can reduce it to a console log.
5. Renderer observes module invalidation and removes obsolete stylesheet resources.
6. Materialize the new exports through the module system, then call `entry.refresh()` to mount them through Loader. Renderer installs metadata-provided styles after successful materialization; explicit materialization exposes the import error before Loader can reduce it to a console log.
7. `fiber.await()` — rethrows loud.
Bootstrap replacement is rejected before invalidation or teardown: the module system retains its initial exports, so remounting its old code would reset consumers without applying the requested revision. The page reports the required reload and preserves the bootstrap fiber. Every non-bootstrap plugin shares the replacement semantics; an `immediately` row reloads exactly like a lazy one. Dependency cascade costs zero client code: a fiber's activation epoch strings its service providers' uids, so replacing a foundational provider such as connection re-loads every dependent through cordis itself — correct, if heavy.
@@ -34,7 +34,7 @@ Web 内核保持不依赖框架,也不 import 任何动态包实体。Modules
浏览器复刻 host 侧的分工。`dsh-client-modules`(`ClientModuleSystem`)坐上 host 侧由 Node 内部 ESM loader 占据的模块系统席位;同一份 vendored `@cordisjs/plugin-loader` 在两侧都坐治理席。二者的分界线一句话说尽:**模块系统拥有模块身份与字节——代码怎么到达、怎么登记、怎么变成导出内容;Loader 拥有插件生命周期——插件何时挂载、等待什么、如何拆除。**
`ClientModuleSystem` 是一张 lazy CJS 表。执行 bundle 只**登记**其 factory——入口调用 `window.__ModuleLoader__.load({ id, factory })`,chunk 还会提供其生成文件名——此外什么都不发生。模块体的一切副作用(包括 CSS 注入)都住在 factory 闭包里,在物化时运行:物化即该 id 的首次 `require`/import,此后记忆化。Import 和 prefetch 会先递归登记已声明的动态请求,再登记消费者;随后 factory 会同步物化任何已登记但尚未物化的请求。可调用的 `require` 解析同步模块表请求;其 `require.async` 操作返回 Promise,负责加载、登记并物化一个包内 chunk。共享 tsdown 预设把源码中针对包内 chunk 的 `import()` 表达式编译到这个独立操作。受支持的产物必须自包含:入口或 chunk 不能同步 require 另一个相对 `client*.js` 产物。模块表按固定分支顺序解析:seed word → 记忆化记录 → graph row classic-script 登记 → 已登记 factory 物化 → 大声抛错。Modules factory 是自举例外:HTML facade 先物化它,构造过程再把同一 exports 直接写入记忆化表。最后这一抛是构建期纯度门禁在运行时的镜像。系统还保管逐模块簿记——名下 `<style data-plugin>` 标签 id、观测到的 require 边——并暴露 HMR(热模块替换)需要的两个动词:`prefetch(id)`(登记所请求的动态 factory 和本 row 自身的 factory;并发到达共享一个任务)与 `invalidate(id)`(推进 owner 代次并丢弃非 bootstrap 包的入口和 chunk factory 及记录,让下次到达重新加载它们)。在旧代次捕获的 chunk 请求不能填充新代次。
`ClientModuleSystem` 是一张 lazy CJS 表。执行 bundle 只**登记**其 factory——入口调用 `window.__ModuleLoader__.load({ id, factory })`,chunk 还会提供其生成文件名——此外什么都不发生。JavaScript 模块体副作用位于 factory 闭包里,在物化时运行:物化即该 id 的首次 `require`/import,此后记忆化。Import 和 prefetch 会先递归登记已声明的动态请求,再登记消费者;随后 factory 会同步物化任何已登记但尚未物化的请求。可调用的 `require` 解析同步模块表请求;其 `require.async` 操作返回 Promise,负责加载、登记并物化一个包内 chunk。共享 tsdown 预设把源码中针对包内 chunk 的 `import()` 表达式编译到这个独立操作。受支持的产物必须自包含:入口或 chunk 不能同步 require 另一个相对 `client*.js` 产物。模块表按固定分支顺序解析:seed word → 记忆化记录 → graph row classic-script 登记 → 已登记 factory 物化 → 大声抛错。Modules factory 是自举例外:HTML facade 先物化它,构造过程再把同一 exports 直接写入记忆化表。最后这一抛是构建期纯度门禁在运行时的镜像。系统还保管逐模块簿记——owner 身份、可选且不求值的元信息函数、观测到的 require 边——并暴露 HMR(热模块替换)需要的两个动词:`prefetch(id)`(登记所请求的动态 factory 和本 row 自身的 factory;并发到达共享一个任务)与 `invalidate(id)`(推进 owner 代次并丢弃非 bootstrap 包的入口和 chunk factory 及记录,让下次到达重新加载它们)。在旧代次捕获的 chunk 请求不能填充新代次。
vendored Loader 经其 `internal` 约定消费模块系统——唯一调用点是 `tree.import`——并拥有一切 entry 形状的事务:entry 创建、fiber 经 cordis 服务等待的激活(注入的服务未就位即保持 PENDING,服务 provide 时级联激活)、update/refresh、拆除。治理代码按 vendor 政策与 host 侧逐字节相同。浏览器化是壳 vite 配置里的编译期映射:一个 `node:module` stub 别名加若干 `process.*` define,使 `ModuleLoader.fromInternal()` 返回 undefined——这正是留给壳来填的空槽。模块系统挂载为 `ctx.modules`。
@@ -70,9 +70,11 @@ Host 会快照每个已构建插件入口 bundle,并把每个调度阶段的
4. `settled` = 每个 entry 已创建 + `loader.await()` 完全停稳 + 启动审计。审计列出每个 import 失败、FAILED 或 PENDING 的 fiber 及其激活错误或缺失的服务。它存在的理由:cordis 的 inject 等待没有超时。浏览器必需名单中的 entry 未激活会拒绝启动;其他未激活 entry 输出一条控制台警告([启动策略](2026-09-09-consumer-owned-startup-strictness.zh.md))。
5. 不依赖框架的 loading 页经 `internal/status` 投影真实 fiber 状态。审计接受插件树后,内核调用 `ctx.uiRenderer.mount(container)`,一次切换到真实 UI。
样式元信息及 renderer 所有权遵循[模块元信息决定](2026-11-05-client-module-metadata.zh.md);模块加载保存生产函数而不求值。
### 动态图对账
modules 控制器只持有从启动清单创建的 Loader 条目。Host 的完整快照更新模块描述并对账这些条目;其他 Loader 贡献方保留自身所有权。新增模块通过单资源 URL 到达,因为重放启动 batch 可能重复注册现有 factory。移除使用 Loader 删除语义,随后等待已捕获 fiber 清理完毕,再移除未使用的模块与样式。已声明及已观察到的传递依赖使共享模块保持存活。Factory revision 的跟踪独立于条目激活,因为下载或物化完成后仍可能没有创建条目。图更新会在任何消费者导入依赖前,使未归属受管条目的陈旧 factory 和失败的到达目标失效,并清除其样式;重建帧也会对账因导入失败而缺失的条目。
modules 控制器只持有从启动清单创建的 Loader 条目。Host 的完整快照更新模块描述并对账这些条目;其他 Loader 贡献方保留自身所有权。新增模块通过单资源 URL 到达,因为重放启动 batch 可能重复注册现有 factory。移除使用 Loader 删除语义,随后等待已捕获 fiber 清理完毕,再移除未使用的模块记录。已声明及已观察到的传递依赖使共享模块保持存活。Factory revision 的跟踪独立于条目激活,因为下载或物化完成后仍可能没有创建条目。图更新会在任何消费者导入依赖前,使未归属受管条目的陈旧 factory 和失败的到达目标失效,并通知资源消费者;重建帧也会对账因导入失败而缺失的条目。
Host SSE 适配器转发现有图变化通知,并在连接时发送当前完整图。图描述浏览器的目标条目,不代表 Host 清理完成:Host 生命周期顺序属于其 Loader,每个浏览器则等待自身被移除 fiber 的清理。图对账与代码重建共用一个页面队列。本地代际阻止过期下载挂载;不透明 revision 只比较相等。失败页面报告本地错误,并可重试同一张图而不改变 Host 启用状态。这保留了无关页面状态,也无需重启应用或引入第二套插件执行器。Electron 的独立安装流程不属于此机制。
@@ -88,8 +90,8 @@ Host SSE 适配器转发现有图变化通知,并在连接时发送当前完
2. `prefetch`——加载该单资源外部脚本并登记新 factory,旧 fiber 此刻仍在服役。初始多资源脚本不会再次执行。
3. `registry.delete`——先于任何 fiber 操作。裸做 fiber dispose 会触发 vendored Loader 的自 dispose 分支,把 entry 永久停用。
4. 排空旧 fiber 的各 disposer。
5. 移除名下的 `<style data-plugin>` 标签。
6. 通过模块系统物化新导出,再调用 `entry.refresh()` 由 Loader 挂载。CSS 在旧 disposer 清理完成后重新注入;显式物化使导入错误能够被捕获,而不只留下 Loader 的控制台日志。
5. Renderer 观察模块失效并移除过期样式资源。
6. 通过模块系统物化新导出,再调用 `entry.refresh()` 由 Loader 挂载。成功物化后 Renderer 安装元信息提供的样式;显式物化使导入错误能够被捕获,而不只留下 Loader 的控制台日志。
7. `fiber.await()`——让失败大声重抛。
Bootstrap 替换会在失效或卸载前被拒绝:模块系统保留其初始导出,重新挂载旧代码会重置消费者,却无法应用请求的 revision。页面会报告需要刷新,并保留 bootstrap fiber。所有非 bootstrap 插件都共享同一套替换语义;`immediately` 行的重载与 lazy 行分毫不差。依赖级联不花一行 client 代码:fiber 的激活纪元串接着它各服务提供方的 uid,因此替换 connection 等基础 provider 的 fiber 时,每个依赖方都会经 cordis 本身重新装载——行为正确,但代价较高。
@@ -12,8 +12,8 @@
en: a15c7c13f167e5ac
zh: a15c7c13f167e5ac
/agent-note-client-shell-layering-and-dynamic-package-boundaries/decision/layers-and-build-forms:
en: a1750de2d48551af
zh: ffea0b75c292f186
en: e0d6260cc782acb9
zh: 2ca2418d2b97bc03
/agent-note-client-shell-layering-and-dynamic-package-boundaries/decision/shared-module-requests:
en: 96661da17622132a
zh: dab3424093130c2f
@@ -21,14 +21,14 @@ Shared UI libraries still expose synchronous TypeScript and React values to many
| Layer | Members | Responsibility | Build and load form |
| --- | --- | --- | --- |
| Web compilation shell | `apps/web` | Owns `index.html`, Vite configuration, dist chunks, and static assets | Assembles final browser output from built package exports |
| Startup kernel | `packages/client/web` | Owns the plain-DOM boot page, module-system wiring, Cordis settlement, and renderer handoff | `staticLinked` `lib/index.js`; no `dsh.client` row |
| Static assembly libraries | Cordis, `ui-primitives`, `ui-slots` | Supply shared module identities and direct value APIs | ESM `lib/index.js`, merged and chunked by Vite; not Loader entries |
| Startup kernel | `packages/client/web` | Owns the plain-DOM boot page, module-system wiring, Cordis settlement, and renderer handoff | `clientShell` ESM entries; no `dsh.client` row |
| Static assembly libraries | Cordis, `ui-primitives`, `ui-slots` | Supply shared module identities and direct value APIs | Manifest `lib/index.js`, shared imports assembled by Vite; not Loader entries |
| Module bootstrap | `packages/client/modules` | Supplies the client module table and its Cordis wrapper | Dynamic package with one ordinary `lib/client.js`; the host delivers its factory early |
| Dynamic client packages | connection, `ui-renderer`, theme, and feature plugins | Participate through Cordis services, slots, and effects | Declare `dsh.client`, emit self-registering `lib/client.js`, and remain host-graph entries |
`packages/client/web` keeps Cordis as matching peer and development dependencies and uses modules and static UI packages as development compilation inputs. `apps/web` consumes built package exports rather than aliases into workspace source.
The `staticLinked` preset leaves every bare specifier as an external import in `lib/index.js` and emits relative CSS assets beside it. The Vite host resolves and deduplicates those imports and decides final chunk boundaries. A static library therefore does not copy the host's bundling policy into its own artifact.
The `staticLinked` preset emits `lib/index.js` as ordinary ESM that keeps every bare import and dynamic import for Vite to resolve, deduplicate, and split, and adds one export, `__$dsh_client_module_manifest`, whose factory returns the library's own exports. A factory that runs the library body later would defer nothing useful: the third-party imports already evaluate when the module loads, and the shell registers these libraries at startup. CSS imports become deferred metadata resources. The [module metadata decision](2026-11-05-client-module-metadata.md) defines resource ownership; static libraries do not adopt dynamic plugins' private-dependency bundling policy.
### Shared module requests
@@ -21,14 +21,14 @@ Client npm 依赖区段描述安装和开发关系,但不能可靠描述 bundl
| 层 | 成员 | 职责 | 构建与加载形态 |
| --- | --- | --- | --- |
| Web 编译壳 | `apps/web` | 拥有 `index.html`、Vite 配置、dist chunk 和静态资源 | 从已构建 package export 组装最终浏览器产物 |
| 启动内核 | `packages/client/web` | 拥有纯 DOM 启动页、模块系统接线、Cordis settle 和 renderer handoff | `staticLinked` `lib/index.js`;无 `dsh.client` row |
| 静态装配库 | Cordis、`ui-primitives`、`ui-slots` | 提供共享模块身份和直接实体 API | ESM `lib/index.js`,由 Vite 合并拆分;不是 Loader entry |
| 启动内核 | `packages/client/web` | 拥有纯 DOM 启动页、模块系统接线、Cordis settle 和 renderer handoff | `clientShell` ESM 入口;无 `dsh.client` row |
| 静态装配库 | Cordis、`ui-primitives`、`ui-slots` | 提供共享模块身份和直接实体 API | Manifest `lib/index.js`,共享 import 由 Vite 组装;不是 Loader entry |
| 模块自举包 | `packages/client/modules` | 提供 client 模块表及其 Cordis wrapper | 带一个普通 `lib/client.js` 的动态包;host 提前送达其 factory |
| 动态 client 包 | connection、`ui-renderer`、主题和功能插件 | 通过 Cordis service、slot 和 effect 参与应用 | 声明 `dsh.client`,产出自注册 `lib/client.js`,并保留 host graph entry |
`packages/client/web` 把 Cordis 保持为 matching peer 与开发依赖,并把 modules 和静态 UI 包作为开发期编译输入。`apps/web` 消费已构建 package export,不通过 alias 读取 workspace 源码。
`staticLinked` 预设让 `lib/index.js` 中每个 bare specifier 保持 external import,并在旁边输出相对 CSS 资产。Vite 宿主负责解析和去重这些 import,并决定最终 chunk 边界。静态库不会把宿主打包策略复制进自身产物。
`staticLinked` 预设把 `lib/index.js` 输出为普通 ESM,保留所有裸 import 与动态 import 交给 Vite 解析、去重和拆分,并增加一个导出 `__$dsh_client_module_manifest`,其 factory 返回库自身的导出。让 factory 推迟执行库本体并没有实际收益:第三方 import 在模块加载时已经求值,外壳也在启动时登记这些库。CSS import 成为延迟求值的元信息资源。[模块元信息决定](2026-11-05-client-module-metadata.zh.md)定义资源所有权;静态库不采用动态插件的私有依赖打包策略。
### 共享模块请求
@@ -0,0 +1,19 @@
# Bilingual-pair consistency record for 2026-11-05-client-module-metadata.md (docs/i18n/README.md): per heading
# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
# After editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-11-05-client-module-metadata.md
/agent-note-client-metadata-and-renderer-owned-stylesheet-installation:
en: 4f12a147e4cbe9a6
zh: 8021e4c1c8fd2d4b
/agent-note-client-metadata-and-renderer-owned-stylesheet-installation/problem:
en: 590dbd303b44e903
zh: b536f88e6fcdbce2
/agent-note-client-metadata-and-renderer-owned-stylesheet-installation/decision:
en: a52f47f300542068
zh: 261fdf1cdc37e95d
/agent-note-client-metadata-and-renderer-owned-stylesheet-installation/alternatives-considered:
en: 7e410e5f19c4ded2
zh: f09d8d8ae2e7ac93
/agent-note-client-metadata-and-renderer-owned-stylesheet-installation/consequences:
en: 2db1d05ddc19891c
zh: b5affd079824a7cd
@@ -0,0 +1,33 @@
# Agent Note: Client metadata and renderer-owned stylesheet installation
Status: implemented
English | [中文](2026-11-05-client-module-metadata.zh.md)
## Problem
A script's execution environment need not be its presentation document. CSS injection embedded in JavaScript factories couples those destinations and makes module loading responsible for DOM cleanup. Inferring stylesheet ownership from React components would add component-level tracking without reliable source-file identity.
## Decision
Client artifacts contain `id` and `factory`, with optional `meta` and a `chunk` name for dynamic package-local chunks. `meta()` returns resource descriptions; `stylesheets` is an optional path-keyed record whose values expose independently evaluated `text(context)` functions. Resource paths identify stylesheets, not components. There is no stylesheet dependency field.
Modules owns JavaScript exports, module identity, owner ids, and observed dependency edges. It retains metadata functions without evaluating them and publishes generic module-record changes. Renderer owns metadata/text caches, dependency-ordered stylesheet collection, path deduplication, and main-document nodes. It explicitly installs existing resources before React mounting, updates them on module changes, and releases styles after the root unmounts. Component lifetimes do not own styles.
Static library builds keep their index artifact as ordinary ESM with all imports and dynamic imports for final shell assembly, and add the `__$dsh_client_module_manifest` export carrying the same manifest. The boot shell itself remains ordinary ESM. Modules wraps the existing carrier loading hook in its built-in Main environment; optional Realm providers do not change default startup or select plugin placement.
This decision refines the resource handling in the [loading model](2026-07-23-client-plugin-loading-model.md) and the artifact description in [shell layering](2026-08-15-client-shells-and-dynamic-packages.md). Their module identity, bootstrap, and dependency separation remain active; neither note is fully superseded.
## Alternatives considered
**CSS DOM operations inside each factory.** They target the script's globals and hide presentation effects in module evaluation; metadata separates data production from installation.
**Component analysis, Hooks, or Slot ownership metadata.** The required lifetime is module-level, so precise component tracking adds allocation and cleanup without a required capability.
**Reuse the dynamic plugin's private-dependency bundling for static libraries.** It moves third-party lazy chunking and font delivery into package builds, changing the established shell dependency policy. Static libraries retain that policy instead.
**Document Scope and an early Realm activation phase.** Neither is required when all modules use the existing Main carrier and all styles target the main document. Isolation requests, environment allocation, and multiple presentation destinations remain separate work.
## Consequences
Modules has no stylesheet query or subscription API. A stylesheet failure is reported by the renderer consumer, not a JavaScript factory failure: the renderer leaves out the failing stylesheet, reports it once, and installs the rest, so one module cannot block application mounting or the styles of modules that load later. Live replacement keeps the previous records in `activeRecords()` until the replaced runtime has been torn down, so a running plugin keeps its styles through a pending or failed download. Styles for materialized but currently invisible components remain installed until module invalidation or renderer disposal. Source-level business imports still receive the original exports through factory-backed `require`.
@@ -0,0 +1,33 @@
# Agent Note: Client 元信息与 Renderer 持有的样式安装
Status: implemented
[English](2026-11-05-client-module-metadata.md) | 中文
## Problem
脚本执行环境不一定是其呈现文档。JavaScript factory 内的 CSS 注入把两者耦合,并让模块加载负责 DOM 清理。从 React 组件推断样式归属会增加组件级跟踪,却无法获得可靠的源文件对应关系。
## Decision
Client 产物包含 `id` 和 `factory`,可选带有 `meta`,动态包内 chunk 另带 `chunk` 名称。`meta()` 返回资源描述;可选的 `stylesheets` 是以路径为键的字典,每个值提供独立求值的 `text(context)` 函数。资源路径标识样式表,而不是组件。当前没有样式表依赖字段。
Modules 拥有 JavaScript 导出、模块身份、owner id 和观察到的依赖边。它保存元信息函数而不求值,发布通用的模块记录变化。Renderer 拥有元信息/文本缓存、依赖有序的样式集合、路径去重与主文档节点。它在 React 挂载前显式安装已有资源,随模块变化更新,并在根卸载后释放样式。组件生命周期不拥有样式。
静态库构建把 index 产物保持为普通 ESM,保留所有 import 与动态 import 交给最终外壳组装,并增加携带相同 manifest 的 `__$dsh_client_module_manifest` 导出。启动外壳本身保持普通 ESM。Modules 用内建 Main 环境包装原有载体加载 hook;可选 Realm 提供方不改变默认启动,也不选择插件放置。
本决定细化[加载模型](2026-07-23-client-plugin-loading-model.zh.md)中的资源处理,以及[外壳分层](2026-08-15-client-shells-and-dynamic-packages.zh.md)中的产物描述。两份记录的模块身份、自举和依赖分离仍然有效,没有完全被取代。
## Alternatives considered
**每个 factory 内操作 CSS DOM。** 这会使用脚本的全局对象,并把呈现副作用藏在模块求值中;元信息将数据生成与安装分离。
**组件分析、Hook 或 Slot 来源元信息。** 所需生命周期是模块级,精确组件跟踪会增加分配和清理,却没有对应的必要能力。
**静态库复用动态插件的私有依赖打包。** 这会把第三方惰性拆包和字体交付移到包构建,改变既有外壳依赖策略。静态库因此保留原策略。
**Document Scope 与提前 Realm 激活阶段。** 所有模块使用原 Main 载体、所有样式装到主文档时,不需要这两者。隔离请求、环境分配和多个呈现目的地属于独立工作。
## Consequences
Modules 没有样式查询或订阅 API。样式失败由 renderer 消费方报告,不是 JavaScript factory 失败:renderer 不安装失败的样式,报告一次,并安装其余样式,因此单个模块不会阻止应用挂载,也不会影响之后加载的模块的样式。实时替换期间,旧记录保留在 `activeRecords()` 中,直到被替换的运行时完成卸载,因此下载未完成或失败时,运行中的插件仍保有样式。已物化但当前不可见组件的样式保留到模块失效或 renderer 销毁。源码业务 import 仍通过 factory 支持的 `require` 取得原有导出。
+3
View File
@@ -32,6 +32,9 @@
"license": "MIT",
"devDependencies": {
"@deepseek-ai/dsh-brand": "workspace:*",
"zod": "4.6.6",
"@tanstack/react-virtual": "3.14.10",
"@deepseek-ai/cordis": "workspace:~",
"@deepseek-ai/cordis-plugin-group": "workspace:~",
"@deepseek-ai/dsh-client-modules": "workspace:*",
"@deepseek-ai/dsh-client-store": "workspace:*",
+3
View File
@@ -21,6 +21,9 @@ import {
createAssembledRemote, type AssembledRemote, type AssembledRemoteOptions,
} from './assembled-remote.ts'
// Dynamic plugins use built bundles; this in-process shell shares source platform namespaces.
vi.mock('@deepseek-ai/dsh-client-web/src/seed.ts', () => import('./source-static-modules.client.ts'))
interface AssembledPlugin extends WebBootEntry {
/** Absolute path to the built client artifact declared by this package. */
bundlePath: string
+2 -2
View File
@@ -2,8 +2,8 @@
// The built-bundle boot smoke: the assembled-jsdom test that owns the boot
// graph itself. Other files share the same scaffolding (assembled-boot.ts) to
// reach a surface only the built bundles expose; this one asserts that the
// graph assembles at all — staged activation across the immediately tier and
// the inject layers, per-plugin CSS injection, and a rendered journey reaching
// graph assembles at all — activation across the immediately tier and
// the inject layers, renderer-owned module styles, and a rendered journey reaching
// chat content from the keyless RemoteMock scenario.
//
// Component behavior remains owned by per-package suites (SlotTestRuntime
+6
View File
@@ -42,6 +42,12 @@ it('keeps ordered legacy Session menu rows before Archive and removes them with
await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' })
const row = page.getByRole('treeitem').filter({ has: page.getByText(SESSION_TITLE, { exact: true }) })
await row.waitFor({ timeout: 20_000 })
// Static library styles follow their module dependencies: dockkit imports primitives, so primitives install first.
const styleOwners = await page.evaluate(() => [...document.head.querySelectorAll('style[data-plugin]')].map(style => style.getAttribute('data-plugin')))
const primitives = styleOwners.flatMap((owner, index) => owner === '@deepseek-ai/dsh-client-ui-primitives' ? [index] : [])
const dockkit = styleOwners.indexOf('@deepseek-ai/dsh-client-ui-dockkit')
expect(primitives.length).toBeGreaterThan(0)
expect(dockkit).toBeGreaterThan(Math.max(...primitives))
const trigger = row.getByRole('button', { name: `Session actions for ${SESSION_TITLE}` })
const trailing = row.locator('[data-session-trailing]')
@@ -66,8 +66,18 @@ it('activates the actual default Client registry without experimental packages',
Object.defineProperty(globalThis, '__ModuleLoader__', { configurable: true, writable: true, value: target })
const create = target.create.bind(target)
target.create = function (options) {
const cordis = options.staticModules['@deepseek-ai/cordis'] as { RegistryService: typeof RegistryService }
const prototype = cordis.RegistryService.prototype
const cordis = options.staticModules.find(module => module.id === '@deepseek-ai/cordis')
if (cordis === undefined) throw new Error('Cordis platform module is missing from the static seed')
const forbidRequire = (specifier: string): never => {
throw new Error(`Cordis platform adapter unexpectedly requested ${specifier}`)
}
const require: Parameters<typeof cordis.factory>[0] = Object.assign(forbidRequire, {
async: async (specifier: string): Promise<never> => forbidRequire(specifier),
asset: forbidRequire,
})
const Registry = cordis.factory(require).RegistryService
if (typeof Registry !== 'function') throw new Error('Cordis platform adapter did not export RegistryService')
const prototype = (Registry as typeof RegistryService).prototype
// eslint-disable-next-line @typescript-eslint/unbound-method -- apply() preserves the runtime registry receiver.
const plugin = prototype.plugin
// Capture the first real root and immediately restore the registry method.
@@ -76,9 +86,14 @@ it('activates the actual default Client registry without experimental packages',
observation.ctx = this.ctx.root
return plugin.apply(this, args)
}
const modules = create(options)
observation.modules = modules
return modules
try {
const modules = create(options)
observation.modules = modules
return modules
} catch (error) {
prototype.plugin = plugin
throw error
}
}
},
})
@@ -1,13 +1,18 @@
/** Test package using the published registration protocol, locale and slots. */
window.__ModuleLoader__.load({
id: '@fixture/live-client',
meta() {
return {
stylesheets: {
'style.css': {
text: () => '[data-live-client] { color: rgb(12, 34, 56); position: absolute; bottom: 20px; right: 20px; }',
},
},
}
},
factory(require) {
const React = require('react')
const { IconFolderCloseRegular, IconNewChatOutlineRegular, MenuItemButton } = require('@deepseek-ai/dsh-client-ui-primitives')
const style = document.createElement('style')
style.dataset.plugin = '@fixture/live-client'
style.textContent = '[data-live-client] { color: rgb(12, 34, 56); position: absolute; bottom: 20px; right: 20px; }'
document.head.append(style)
return {
inject: ['slots', 'locale'],
apply(ctx) {
+13 -12
View File
@@ -565,7 +565,7 @@ describe('web e2e: navigation & panes over a rich seeded session', () => {
await expect.poll(() => frame.getAttribute('data-rightbar-collapsed'), { timeout: 5_000 }).toBe('true')
// The card's own controls are outside the summary row and must not expand
// the right column either — the expanded terminal card is read in place.
await page.locator('[data-sample="bash"] ~ div [data-terminal] [class*="_copyButton_"]').first().click()
await page.locator('[data-sample="bash"] ~ div [data-terminal]').first().getByRole('button', { name: 'Copy', exact: true }).click()
await expect.poll(() => frame.getAttribute('data-rightbar-collapsed'), { timeout: 5_000 }).toBe('true')
// Opening a file into the empty column creates only its preview tab.
const fileLink = page.locator('[data-variant="read"] button').first()
@@ -598,9 +598,9 @@ describe('web e2e: navigation & panes over a rich seeded session', () => {
// squeeze the output pane below its content width and the line must keep
// its single row and overflow sideways instead of folding. Soft-wrapping
// here shreds the column alignment this card exists to hold.
const layout = await card.locator('[class*="_output_"]').first().evaluate((node) => {
const layout = await card.locator('[data-terminal-output]').evaluate((node) => {
const pane = node as HTMLElement
const row = pane.querySelector<HTMLElement>('[class*="_line_"]')
const row = pane.querySelector<HTMLElement>(':scope > div')
if (row === null) throw new Error('output pane has no line')
const before = row.offsetHeight
const restore = pane.style.width
@@ -614,7 +614,10 @@ describe('web e2e: navigation & panes over a rich seeded session', () => {
// jsdom cannot report: --dsw-* tokens resolve only against the real theme
// stylesheet. This command settled cleanly, so the dot must be the green
// success token — a red one here would read as a failed command.
const dot = await card.locator('[class*="_runState_"][data-state]').first().evaluate((node) => {
const dot = await card.locator('[data-terminal-banner] [data-state]').evaluate((node) => {
const banner = node.closest('[data-terminal-banner]')
const prompt = banner?.querySelector('[data-terminal-prompt]') ?? null
if (banner === null || prompt === null) throw new Error('terminal status dot has no prompt banner')
// The token lives on body, so the probe must sit in the same cascade.
const probe = document.createElement('span')
probe.style.color = 'var(--dsw-alias-state-success-primary)'
@@ -627,10 +630,10 @@ describe('web e2e: navigation & panes over a rich seeded session', () => {
success,
// One label per card (the state is the call's), so it hangs off the
// prompt column rather than the row the dot sits in.
label: node.closest('[class*="_prompt_"]')?.querySelector('[class*="_runStateLabel_"]')?.textContent ?? null,
label: banner.querySelector('[data-terminal-state-label]')?.textContent ?? null,
// The dot precedes the prompt label in document order, which is what
// puts it to the left of the `$`.
beforePrompt: node.compareDocumentPosition(node.parentElement!.querySelector('[class*="_cwd_"]')!)
beforePrompt: node.compareDocumentPosition(prompt)
=== Node.DOCUMENT_POSITION_FOLLOWING,
// The dot lives in the card's OWN left padding, so it sits inside the
// card box yet left of the prompt text. Owning the reservation as padding
@@ -640,9 +643,7 @@ describe('web e2e: navigation & panes over a rich seeded session', () => {
insideCard: (node as HTMLElement).getBoundingClientRect().left
>= (node.closest('[data-terminal]')?.getBoundingClientRect().left ?? Infinity),
leftOfPrompt: (node as HTMLElement).getBoundingClientRect().right
<= (node.closest('[class*="_promptLine_"]')
?.querySelector('[class*="_cwd_"]')
?.getBoundingClientRect().left ?? -Infinity),
<= prompt.getBoundingClientRect().left,
}
})
expect(dot.state).toBe('done')
@@ -661,9 +662,9 @@ describe('web e2e: navigation & panes over a rich seeded session', () => {
// Copy writes the raw output through the browser's own clipboard, which in
// a real page is the async Clipboard API rather than the jsdom fallback.
await page.context().grantPermissions(['clipboard-read', 'clipboard-write'])
await card.locator('[class*="_copyButton_"]').first().click()
await expect.poll(() => card.locator('[class*="_copyButton_"]').first().textContent(), { timeout: 5_000 })
.toBe('Copied')
await card.getByRole('button', { name: 'Copy', exact: true }).click()
await expect.poll(() => card.getByRole('button', { name: 'Copied', exact: true }).count(), { timeout: 5_000 })
.toBe(1)
expect(await page.evaluate(() => navigator.clipboard.readText())).toContain('NAVIGATION_OK')
}, 60_000)
+2 -1
View File
@@ -514,7 +514,8 @@ async function bootPreview(site: Site, manifest: ImageManifest, browser: Browser
await commands.first().scrollIntoViewIfNeeded()
const geometry = await commands.first().evaluate((element) => {
const prompt = element.parentElement!
const header = element.closest('[class*="_header_"]')!
const header = element.closest('[data-terminal-banner]')
if (header === null) throw new Error('wrapped preview command has no terminal banner')
header.scrollTop = 0
const dot = prompt.querySelector('[data-state="done"]')
if (dot === null) throw new Error('wrapped preview command has no successful status dot')
+2 -2
View File
@@ -91,7 +91,7 @@ it.each([
await input.waitFor()
const background = args.run_in_background
const selectableText = args.command.split('\n')[0]!
const inputSection = card.locator('[data-terminal] [class*="_header_"]')
const inputSection = card.locator('[data-terminal-banner]')
expect(await input.textContent()).toBe(selectableText)
if (background) {
expect(await commands.allTextContents()).toEqual([args.command])
@@ -188,7 +188,7 @@ it.each([
await card.waitFor()
await card.evaluate((element) => { element.style.width = '380px' })
await card.scrollIntoViewIfNeeded()
const header = card.locator('[class*="_header_"]')
const header = card.locator('[data-terminal-banner]')
const mountedCard = await card.elementHandle()
if (mountedCard === null) throw new Error('Running command card is not mounted')
expect(await header.evaluate(element => element.scrollHeight > element.clientHeight)).toBe(true)
@@ -0,0 +1,41 @@
/**
* Source-only platform registrations for in-process browser assembly tests.
*
* `packages/client/web/tests/source-static-modules.client.ts` holds an identical copy:
* a TypeScript test project cannot include a file outside its `rootDir`, so the `apps/web` project and
* the package test projects each need their own. Change both together.
*/
import * as React from 'react'
import * as ReactJsxRuntime from 'react/jsx-runtime'
import * as ReactDom from 'react-dom'
import * as ReactDomClient from 'react-dom/client'
import * as Cordis from '@deepseek-ai/cordis'
import * as Zod from 'zod'
import * as ReactVirtual from '@tanstack/react-virtual'
import * as ClientStore from '@deepseek-ai/dsh-client-store'
import * as UiSlots from '@deepseek-ai/dsh-client-ui-slots'
import * as UiPrimitives from '@deepseek-ai/dsh-client-ui-primitives'
import * as UiDockkit from '@deepseek-ai/dsh-client-ui-dockkit'
import type { ClientModuleCreateOptions } from '@deepseek-ai/dsh-client-modules/client'
import type { PlatformModule } from '@deepseek-ai/dsh-client-web/src/platform.ts'
/**
* Adapt source namespaces to the module registration protocol without compiled metadata.
* @returns Registrations retaining the real source module namespace identities.
*/
export function getStaticModules(): ClientModuleCreateOptions['staticModules'] {
const sources = {
'react': React,
'react/jsx-runtime': ReactJsxRuntime,
'react-dom': ReactDom,
'react-dom/client': ReactDomClient,
'@deepseek-ai/cordis': Cordis,
'zod': Zod,
'@tanstack/react-virtual': ReactVirtual,
'@deepseek-ai/dsh-client-store': ClientStore,
'@deepseek-ai/dsh-client-ui-slots': UiSlots,
'@deepseek-ai/dsh-client-ui-primitives': UiPrimitives,
'@deepseek-ai/dsh-client-ui-dockkit': UiDockkit,
} satisfies Record<PlatformModule, Record<string, unknown>>
return Object.entries(sources).map(([id, exports]) => ({ id, factory: () => exports }))
}
+4 -4
View File
@@ -150,7 +150,7 @@ export async function expectWrappedCommandText(
export async function expectWrappedTerminalCommand(page: Page, card: Locator, expected: string, width: number) {
const originalWidth = await card.evaluate(element => element.style.width)
const command = card.locator('[data-command-text]').first()
const header = card.locator('[class*="_header_"]').first()
const header = card.locator('[data-terminal-banner]')
const observations: ({ colorScheme: 'light' | 'dark' } & Awaited<ReturnType<typeof expectWrappedCommandText>>)[] = []
try {
for (const colorScheme of ['light', 'dark'] as const) {
@@ -177,11 +177,11 @@ export async function expectWrappedTerminalCommand(page: Page, card: Locator, ex
* @returns Resolves after the dot fits inside the banner and aligns with the first line.
*/
export async function expectFirstLineTerminalState(card: Locator, state: 'ongoing' | 'done'): Promise<void> {
const dot = card.locator('[class*="_runState_"][data-state]')
const dot = card.locator('[data-terminal-banner] [data-state]')
await expect.poll(() => dot.getAttribute('data-state')).toBe(state)
const geometry = await dot.evaluate((element) => {
const prompt = element.closest('[class*="_promptLine_"]')
const header = element.closest('[class*="_header_"]')
const prompt = element.parentElement
const header = element.closest('[data-terminal-banner]')
if (prompt === null || header === null) throw new Error('Terminal status has no prompt banner')
const bounds = element.getBoundingClientRect()
const viewport = header.getBoundingClientRect()
+1 -1
View File
@@ -334,7 +334,7 @@ describe('web e2e: macOS window drag coverage', () => {
const panel = page.locator('[data-sidebar-right-panel][data-sidebar-right-open]')
await panel.waitFor()
await settled(page)
const body = panel.locator('[data-dockkit-pane] > [class*="_paneBody_"]').first()
const body = panel.locator('[data-dockkit-pane] > [data-dockkit-pane-body]').first()
await body.waitFor()
// The existing pane supplies the no-drag owner; plain fixture content isolates CSS inheritance from plugin behavior.
await body.evaluate((element) => {
+4 -3
View File
@@ -239,9 +239,10 @@ export default defineConfig({
// no entry: pnpm links each of them to a single directory.
dedupe: ['react', 'react-dom'],
// Workspace packages are consumed as built lib products: each resolves
// through its own package.json exports from the importer's directory, and
// CSS still rides Vite's pipeline because the client build preset emits it
// beside the bundle. Plugin packages never enter this graph; they arrive as
// through its own package.json exports from the importer's directory. A
// static library's own CSS arrives as module metadata for the renderer;
// only the third-party stylesheets it imports, such as KaTeX's, ride Vite's
// pipeline. Plugin packages never enter this graph; they arrive as
// runtime bundles through the client module system. The node:module alias
// supports Loader initialization; its filesystem resolver's other Node
// imports must stay default imports for Vite's browser-external stubs.
+2
View File
@@ -5086,6 +5086,8 @@ These load from a `cordis.yml` entry with no `config:` block; they declare no co
| `@deepseek-ai/dsh-client-locale` | — | [`packages/client/locale/src/index.ts`](../packages/client/locale/src/index.ts) |
| `@deepseek-ai/dsh-client-modules` | `loader` | [`packages/client/modules/src/index.ts`](../packages/client/modules/src/index.ts) |
| `@deepseek-ai/dsh-client-resources` | — | [`packages/client/resources/src/index.ts`](../packages/client/resources/src/index.ts) |
| `@deepseek-ai/dsh-client-script-realm` | — | [`packages/client/script-realm/src/index.ts`](../packages/client/script-realm/src/index.ts) |
| `@deepseek-ai/dsh-client-script-realm-iframe` | — | [`packages/client/script-realm-iframe/src/index.ts`](../packages/client/script-realm-iframe/src/index.ts) |
| `@deepseek-ai/dsh-client-ui-action-cards` | — | [`packages/experimental/client-ui-action-cards/src/index.ts`](../packages/experimental/client-ui-action-cards/src/index.ts) |
| `@deepseek-ai/dsh-client-ui-agent-preset` | — | [`packages/client/ui-agent-preset/src/index.ts`](../packages/client/ui-agent-preset/src/index.ts) |
| `@deepseek-ai/dsh-client-ui-agent-team` | — | [`packages/client/ui-agent-team/src/index.ts`](../packages/client/ui-agent-team/src/index.ts) |
+2
View File
@@ -5088,6 +5088,8 @@ export interface Config {
| `@deepseek-ai/dsh-client-locale` | — | [`packages/client/locale/src/index.ts`](../packages/client/locale/src/index.ts) |
| `@deepseek-ai/dsh-client-modules` | `loader` | [`packages/client/modules/src/index.ts`](../packages/client/modules/src/index.ts) |
| `@deepseek-ai/dsh-client-resources` | — | [`packages/client/resources/src/index.ts`](../packages/client/resources/src/index.ts) |
| `@deepseek-ai/dsh-client-script-realm` | — | [`packages/client/script-realm/src/index.ts`](../packages/client/script-realm/src/index.ts) |
| `@deepseek-ai/dsh-client-script-realm-iframe` | — | [`packages/client/script-realm-iframe/src/index.ts`](../packages/client/script-realm-iframe/src/index.ts) |
| `@deepseek-ai/dsh-client-ui-action-cards` | — | [`packages/experimental/client-ui-action-cards/src/index.ts`](../packages/experimental/client-ui-action-cards/src/index.ts) |
| `@deepseek-ai/dsh-client-ui-agent-preset` | — | [`packages/client/ui-agent-preset/src/index.ts`](../packages/client/ui-agent-preset/src/index.ts) |
| `@deepseek-ai/dsh-client-ui-agent-team` | — | [`packages/client/ui-agent-team/src/index.ts`](../packages/client/ui-agent-team/src/index.ts) |
+4
View File
@@ -157,6 +157,8 @@ flowchart TD
pkg_client_modules["client-modules"]
pkg_client_product_analytics["client-product-analytics"]
pkg_client_resources["client-resources"]
pkg_client_script_realm["client-script-realm"]
pkg_client_script_realm_iframe["client-script-realm-iframe"]
pkg_client_shortcuts["client-shortcuts"]
pkg_client_store["client-store"]
pkg_client_ui_account_notifications["client-ui-account-notifications"]
@@ -1604,6 +1606,8 @@ flowchart TD
| [`client-modules`](../packages/client/modules) | `client` | — |
| [`client-product-analytics`](../packages/client/product-analytics) | `client` | — |
| [`client-resources`](../packages/client/resources) | `client` | — |
| [`client-script-realm`](../packages/client/script-realm) | `client` | — |
| [`client-script-realm-iframe`](../packages/client/script-realm-iframe) | `client` | — |
| [`client-shortcuts`](../packages/client/shortcuts) | `client` | — |
| [`client-store`](../packages/client/store) | `client` | — |
| [`client-ui-account-notifications`](../packages/client/ui-account-notifications) | `client` | — |
+4
View File
@@ -159,6 +159,8 @@ flowchart TD
pkg_client_modules["client-modules"]
pkg_client_product_analytics["client-product-analytics"]
pkg_client_resources["client-resources"]
pkg_client_script_realm["client-script-realm"]
pkg_client_script_realm_iframe["client-script-realm-iframe"]
pkg_client_shortcuts["client-shortcuts"]
pkg_client_store["client-store"]
pkg_client_ui_account_notifications["client-ui-account-notifications"]
@@ -1606,6 +1608,8 @@ flowchart TD
| [`client-modules`](../packages/client/modules) | `client` | — |
| [`client-product-analytics`](../packages/client/product-analytics) | `client` | — |
| [`client-resources`](../packages/client/resources) | `client` | — |
| [`client-script-realm`](../packages/client/script-realm) | `client` | — |
| [`client-script-realm-iframe`](../packages/client/script-realm-iframe) | `client` | — |
| [`client-shortcuts`](../packages/client/shortcuts) | `client` | — |
| [`client-store`](../packages/client/store) | `client` | — |
| [`client-ui-account-notifications`](../packages/client/ui-account-notifications) | `client` | — |
+2 -2
View File
@@ -9,8 +9,8 @@
en: c0454bca818f86ee
zh: 427582150fd3b976
/web-client-architecture/browser-boot:
en: cd68c46a3f365235
zh: 9ac2f7c65cabb144
en: ad100df8a00bd7bd
zh: b160c24ca1d835ab
/web-client-architecture/remote-communication:
en: 426b09164210b77a
zh: ce576099ee668984
+2
View File
@@ -25,6 +25,8 @@ The Host writes the composed `WebBootGraph` to `window.__DSH_BOOT__` and install
The Web boot kernel creates the module system, prefetches `immediately` entries, mounts the vendored Cordis Loader, and creates every graph entry. Cordis service injection determines activation; module graph order determines only whether synchronous imports can be materialized. After the complete roster reaches a settled state and the boot audit accepts it (an inactive entry on the browser required list rejects startup; other inactive entries produce one console warning), `ui-renderer` hydrates the framework-free boot DOM and calls the sole context-level `renderSlot('root')` operation. [Client Modules](client-modules.md) owns the graph, bundle route, cache revision, and loader details.
Module construction binds the startup carrier's existing script loader as its Main environment; optional Realm providers do not add a startup phase. Modules retains optional metadata producers and emits module-record changes; [UI Renderer](../../packages/client/ui-renderer/README.md) evaluates stylesheet descriptors and owns their main-document installation. This resource lifecycle is module-level, not a Slot or component mount protocol.
## Remote communication
Host business services annotate callable methods with Typert Remote decorators. Host generation emits strict descriptors, runtime codecs, declaration merges, and source maps. The Client-side `api-remotes` assembly selects those generated contributions and mounts concrete methods under `ctx.remote.<namespace>` and Session-scoped `agentCtx.remote.<namespace>`. Feature packages depend on the generated service face, not the Gateway implementation or a Host package's runtime entry.
+2
View File
@@ -25,6 +25,8 @@ Host 把组合后的 `WebBootGraph` 写入 `window.__DSH_BOOT__`,并在 parser
Web boot kernel 创建模块系统、预取 `immediately` entry、挂载 vendored Cordis Loader,再创建图中的每个 entry。Cordis service injection 决定激活顺序;module graph 顺序只决定同步 import 能否被 materialize。完整 roster 到达 settled 状态且启动审计通过后(浏览器必需名单中的 entry 未激活会拒绝启动;其他未激活 entry 输出一条控制台警告),`ui-renderer` hydrate 不依赖框架的 boot DOM,并调用唯一一次 context 级 `renderSlot('root')`。[Client Modules](client-modules.zh.md)负责 graph、bundle route、cache revision 与 loader 细节。
模块构造时将启动载体原有的脚本加载器绑定为自身 Main 环境;可选 Realm 提供方不会增加启动阶段。Modules 保存可选的元信息生产函数并发布模块记录变化;[UI Renderer](../../packages/client/ui-renderer/README.zh.md) 求值样式描述并持有其主文档安装。资源生命周期是模块级,而不是 Slot 或组件挂载协议。
## Remote 通信
Host 业务 service 使用 Typert Remote decorator 标记可调用 method。Host generation 产出严格 descriptor、runtime codec、declaration merge 与 source map。Client 侧 `api-remotes` assembly 选择这些生成贡献,并把具体 method 挂到 `ctx.remote.<namespace>` 与 Session scope 的 `agentCtx.remote.<namespace>`。功能包依赖生成的 service face,而不依赖 Gateway 实现或 Host 包的运行时 entry。
@@ -0,0 +1,16 @@
# Bilingual-pair consistency record for guide.md (docs/i18n/README.md): per heading
# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
# After editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.2-rc.2/client-module-metadata/guide.md
/:
en: fb246f910bb01f20
zh: c34361215fc4d61a
/client-module-metadata:
en: 7b3cba91e6f7c512
zh: 84ce9f39b88df70c
/client-module-metadata/change:
en: a6dac8c6027caeb7
zh: 6e54be5e59db6a1e
/client-module-metadata/migration:
en: 068457646208dc0e
zh: a59fb7bb774dc929
@@ -0,0 +1,29 @@
---
kind: upgrade-guide
description: Client artifact metadata and static library manifests require rebuilding custom browser bundles and updating direct static-artifact consumers.
---
# Client module metadata
English | [中文](guide.zh.md)
## Change
Client bundle registrations can carry `meta` beside `id`, `factory`, and optional `chunk`. The factory still returns the plugin or library exports. Metadata optionally contains `stylesheets`, a record keyed by each stylesheet's path within the owning package, such as `src/client/App.module.css`; each descriptor has `text(context)`, with `context.asset()` resolving carrier asset URLs. Compiled stylesheet imports no longer install DOM nodes during JavaScript factory execution.
Static Client library index artifacts keep their named exports and add one more, `__$dsh_client_module_manifest`, carrying the same manifest; its factory returns the library's exports without the manifest. Their ESM imports and dynamic imports remain in the final Web build.
Styles of `staticLinked` libraries, including `dsh-client-ui-primitives` and `dsh-client-ui-dockkit`, leave the Web shell's CSS file: the renderer installs them when the application mounts. Their CSS Modules class names change from `_<local>_<hash>` to `<hash>_<local>`. Generated style elements keep `data-plugin` with the owning package, add `data-path` with the stylesheet's path within that package, and no longer carry `data-plugin-css`.
A bundle built with this preset loads on earlier DSH releases without its styles, because they ignore `meta`. Earlier-preset bundles still inject their own `<style data-plugin>` elements, which Modules no longer removes: disabling or live-replacing such a plugin leaves its styles until reload, and an earlier-preset replacement keeps the old text.
The default startup order is unchanged: Modules constructs its Main environment from the existing loading hook, prefetch runs before Loader activation, and renderer installation adds materialized-module styles before the React root. Realm Registry and iframe providers are optional; there is no Isolation or Shadow DOM configuration in this change.
## Migration
1. Rebuild custom Client bundles with the matching `clientBundle` preset. Custom artifact generators that provide compiled CSS expose its descriptors through `meta`; artifacts without metadata can omit it. Do not add metadata to `factory()`'s returned business exports.
2. Rebuild `staticLinked` libraries and the consuming shell together. Shell assembly reads the `__$dsh_client_module_manifest` export; plugin code keeps its existing package specifiers and obtains exports through the module loader's `require`. Code that enumerates a static library's namespace sees this additional key.
3. Keep carrier asset resolution available through `context.asset()` when generating stylesheet text. Leave DOM installation to the renderer; module factories no longer own generated style tags.
4. Verify that registrations do not evaluate metadata, CSS appears before the application root renders, lazy metadata appears only after its module materializes, and module replacement removes or updates the prior styles. The [module reference](../../../../packages/client/modules/README.md) and [renderer reference](../../../../packages/client/ui-renderer/README.md) define ownership and failure behavior.
5. Replace selectors in custom CSS, user scripts, and tests that match generated class names such as `[class*="_header_"]` with `data-*` attributes or accessible roles, and `style[data-plugin-css]` with `style[data-plugin][data-path]`.
6. Set the rebuilt plugin's `engines.dsh` minimum to the DSH release with this change. Reload the page after disabling or updating an earlier-preset plugin.
@@ -0,0 +1,29 @@
---
kind: upgrade-guide
description: Client 产物元信息和静态库 manifest 要求重新构建自定义浏览器 bundle,并更新直接消费静态产物的代码。
---
# Client 模块元信息
[English](guide.md) | 中文
## 变更
Client bundle 注册可在 `id`、`factory` 和可选 `chunk` 之外携带 `meta`。factory 仍返回插件或库的导出。元信息可包含 `stylesheets`,即以样式在所属包内的路径(如 `src/client/App.module.css`)为键的字典;每份描述具有 `text(context)`,由 `context.asset()` 解析载体资源 URL。编译后的样式 import 不再在 JavaScript factory 执行期间安装 DOM 节点。
静态 Client 库的 index 产物保留原有具名导出,并增加一个携带相同 manifest 的导出 `__$dsh_client_module_manifest`;其 factory 返回不含 manifest 的库导出。ESM import 和动态 import 仍留给最终 Web 构建。
`staticLinked` 库(包括 `dsh-client-ui-primitives` 和 `dsh-client-ui-dockkit`)的样式不再进入 Web 外壳的 CSS 文件,改由 renderer 在应用挂载时安装。它们的 CSS Modules 类名从 `_<local>_<hash>` 变为 `<hash>_<local>`。生成的 style 元素仍以 `data-plugin` 携带所属包名,新增以 `data-path` 携带的包内样式路径,不再带 `data-plugin-css`。
用本预设构建的 bundle 可以在较早的 DSH 版本上加载,但没有样式,因为较早版本会忽略 `meta`。用较早预设构建的 bundle 仍自行插入 `<style data-plugin>` 元素,Modules 不再删除它们:禁用或实时替换这类插件后,其样式保留到页面刷新;替换版本同样由较早预设构建时,页面保留旧样式文本。
默认启动顺序不变:Modules 从原有加载 hook 建立 Main 环境,prefetch 在 Loader 激活前运行,renderer 在 React 根之前安装已物化模块的样式。Realm Registry 与 iframe 提供方是可选的;本次没有 Isolation 或 Shadow DOM 配置。
## 迁移
1. 使用配套版本的 `clientBundle` 预设重新构建自定义 Client bundle。自定义产物生成器通过 `meta` 提供编译 CSS 的描述;没有元信息的产物可省略它。不要把元信息加入 `factory()` 返回的业务导出。
2. 同时重新构建 `staticLinked` 库和消费它的外壳。外壳组装读取 `__$dsh_client_module_manifest` 导出;插件代码保留原有包标识符,通过模块加载器的 `require` 取得导出。枚举静态库命名空间的代码会看到这个新增的键。
3. 生成样式文本时通过 `context.asset()` 保留载体资源解析。DOM 安装交给 renderer,模块 factory 不再拥有生成的 style 标签。
4. 确认登记不会求值元信息、CSS 在应用根渲染前出现、lazy 元信息只在对应模块物化后出现,以及模块替换会移除或更新旧样式。[模块参考](../../../../packages/client/modules/README.zh.md)和 [renderer 参考](../../../../packages/client/ui-renderer/README.zh.md)定义所有权与失败行为。
5. 自定义 CSS、用户脚本和测试中匹配生成类名的选择器(如 `[class*="_header_"]`)改用 `data-*` 属性或无障碍角色,`style[data-plugin-css]` 改用 `style[data-plugin][data-path]`。
6. 把重新构建的插件在 `engines.dsh` 中声明的最低版本设为包含本变更的 DSH 版本。禁用或更新用较早预设构建的插件后,刷新页面。
+1 -1
View File
@@ -66,7 +66,7 @@ Npm sections describe installation and development relationships; each build fac
2. **A package under `packages/client/` is always covered; `dsh.client` marks a Client/Host package outside that directory, in every group including `packages/experimental/`.** Explicit include/exclude entries handle exceptions. Every covered package's Host entries are scanned, including the non-browser entries its `tsdown.config.ts` builds outside `src/client/`, such as Worker and child-process entries, while a `./client` export alone does not select dependency policy.
3. **Browser and type relationships are development-only.** Workspace and third-party Client imports, type-only imports, module augmentations, TypeScript project references, `dsh.client.inject`, and metadata-only peers belong only in `devDependencies`. Configuration-only entries absent from imports are listed in the dependency policy; Node companion value imports follow the Host rules below.
4. **Host value imports require classified exports.** A workspace value reached from the package's Host entry belongs only in `dependencies` when its exact module specifier and runtime export appear in `safeHostDependencyExports`. Exports whose identity or module state must be shared appear in `peerRequiredHostExports` and keep the whole package edge in matching `peerDependencies` and `devDependencies`. The verifier rejects unclassified exports before `--fix` writes manifests.
5. **Only Host runtime libraries require installation dependencies.** Browser-only third-party implementations belong in `devDependencies`, whether inlined into `lib/client.js` or retained as bare imports in a static browser library. Static libraries are Web-shell build inputs; the final Vite build merges their imports and styles. Distributed browser code remains subject to runtime license disclosure ([reference](../../.agents/notes/implemented/process/2026-08-26-published-dependency-faces.md)).
5. **Only Host runtime libraries require installation dependencies.** Browser-only third-party implementations belong in `devDependencies`, whether inlined into `lib/client.js` or retained as bare imports in a static browser library. Static libraries are Web-shell build inputs: the final Vite build merges their imports, and their compiled stylesheets travel in the `__$dsh_client_module_manifest` export for the renderer to install. Distributed browser code remains subject to runtime license disclosure ([reference](../../.agents/notes/implemented/process/2026-08-26-published-dependency-faces.md)).
6. **Browser and Node build faces declare externality independently.** A dynamic browser half uses the baseline plus `dsh.client.external`; a statically linked face externalizes every bare specifier; a Node face externalizes its production dependencies ([`tsdown.client.ts`](tsdown.client.ts)). Moving a name between npm sections must not silently change bundle contents.
7. **Keep the published payload closed.** Every relative runtime import and emitted asset must be covered by `files`; the repository publint pass checks the exact publication view.
8. **Only the root manifest declares React type packages.** `@types/react` and `@types/react-dom` belong only in the root `package.json` `devDependencies`, and `verify-package-dependencies` rejects them in every manifest under `apps/*`, `packages/*/*`, and `vendor/*`; packages still declare the `react` and `react-dom` they import. Each package-local pnpm link is one more location TypeScript scans when it computes module specifiers for every JSX file ([rationale](../../.agents/notes/implemented/process/2026-10-11-lossless-build-speedups.md#1-only-the-root-manifest-declares-react-type-packages)).
+12 -9
View File
@@ -21,13 +21,13 @@
en: cc0eb2c35a7a0998
zh: 0e1df23869410c7a
/deepseek-ai-dsh-client-modules/use-this-package/package-assets:
en: 529af1eb8bf1acf2
zh: 7d891a5dfa90c625
en: bc77e9c5d74134b0
zh: cd99a246d43472ea
/deepseek-ai-dsh-client-modules/use-this-package/what-the-browser-loads:
en: 1383d68472b3c057
zh: 94dd7d9abbdbccf3
/deepseek-ai-dsh-client-modules/use-this-package/live-plugin-composition:
en: 45740a56e931d094
en: 252613c45e5e46f5
zh: fa44cf77c86019af
/deepseek-ai-dsh-client-modules/use-this-package/host-release-changes:
en: 5c0aa6f1d8df8e1c
@@ -45,8 +45,11 @@
en: 49dcadc166c2d06e
zh: bbf67c6dc47f4ead
/deepseek-ai-dsh-client-modules/understand-the-implementation/lazy-cjs-model:
en: 6d16b74acb333e3b
zh: fcb3a20cc8c39e4a
en: 49b1c7274a67945c
zh: 6ec2fdf6f6af7d21
/deepseek-ai-dsh-client-modules/understand-the-implementation/main-execution-environment:
en: bd0b82f672dc99b4
zh: 7d33af671aab0939
/deepseek-ai-dsh-client-modules/understand-the-implementation/incremental-composition:
en: 99483432e6390ca4
zh: f92c018273aa07e4
@@ -54,11 +57,11 @@
en: 253d9f265cd83ed0
zh: 9d0f8df84d9d3ac9
/deepseek-ai-dsh-client-modules/understand-the-implementation/entry-ownership:
en: 608a25c52159629f
zh: c5ef242899cb32c1
en: a0d8dbb15e079ec0
zh: 7d215cb85fa8b2c7
/deepseek-ai-dsh-client-modules/understand-the-implementation/source-map:
en: d8b5407a0279a3f9
zh: 27af3437fad78672
en: ece84808fa9f61f8
zh: 95a65a7adfca9146
/deepseek-ai-dsh-client-modules/further-exploration:
en: 7e5b283efe4f1d16
zh: 79472b64a0d759fe
+9 -4
View File
@@ -36,7 +36,7 @@ A browser plugin package declares `dsh.client` in its `package.json` with `platf
<a id="package-assets"></a>
### Package assets
The same `/plugins` route serves the images a client package publishes through its `"./assets/*": "./lib/assets/*"` export. The build emits each referenced asset with its content revision, the first 12 hexadecimal digits of the SHA-1 digest of its bytes, inserted before the extension, and compiles the import, or the stylesheet `url()`, into a synchronous `require.asset("plugins/<package>/assets/<emitted path>")` call on the bundle's module loader, so one URL always names one content. Each path segment is percent-encoded with `encodeURIComponent` and then `!`, `'`, `(`, `)`, and `*`, so the reference is also a valid unquoted CSS `url()`; a package built outside this repository must emit the same form. The call returns the document-relative reference unless the page's carrier supplies `resolveAsset`: the WebWorker preview, whose page cannot request the reference, maps it to a Blob URL of the bytes its Worker image holds. Any `/plugins/<package>/assets/` path is answered by the asset route alone: for an active client row, the Host percent-decodes the path once and resolves `<package>/assets/<path>` with Node's `require.resolve` from the package's own manifest, so the package's exports decide which files exist. A path that does not resolve, a resolved file whose extension is not `.svg`, `.png`, `.webp`, `.jpg`, or `.jpeg`, a malformed escape, and an inactive package answer 404; the query selects nothing. A served asset streams from disk on every request without caching and carries its media type, the bundle `cache-control: public, max-age=31536000, immutable`, `etag: "<requested path>"`, and `x-content-type-options: nosniff`; an SVG additionally carries `content-security-policy: script-src 'none'`, so an SVG opened directly runs no script. An `If-None-Match` equal to that tag answers 304 without opening the file, and `HEAD` answers without a body. `fetchBundle()` returns the same responses, with a streamed body that closes the file when cancelled.
The same `/plugins` route serves the images a client package publishes through its `"./assets/*": "./lib/assets/*"` export. The build emits each referenced asset with its content revision, the first 12 hexadecimal digits of the SHA-1 digest of its bytes, inserted before the extension, and compiles the import, or the stylesheet `url()`, into a synchronous asset-resolution call (`require.asset` for JavaScript or `context.asset` inside stylesheet `text`) on the bundle's module loader, so one URL always names one content. Each path segment is percent-encoded with `encodeURIComponent` and then `!`, `'`, `(`, `)`, and `*`, so the reference is also a valid unquoted CSS `url()`; a package built outside this repository must emit the same form. The call returns the document-relative reference unless the page's carrier supplies `resolveAsset`: the WebWorker preview, whose page cannot request the reference, maps it to a Blob URL of the bytes its Worker image holds. Any `/plugins/<package>/assets/` path is answered by the asset route alone: for an active client row, the Host percent-decodes the path once and resolves `<package>/assets/<path>` with Node's `require.resolve` from the package's own manifest, so the package's exports decide which files exist. A path that does not resolve, a resolved file whose extension is not `.svg`, `.png`, `.webp`, `.jpg`, or `.jpeg`, a malformed escape, and an inactive package answer 404; the query selects nothing. A served asset streams from disk on every request without caching and carries its media type, the bundle `cache-control: public, max-age=31536000, immutable`, `etag: "<requested path>"`, and `x-content-type-options: nosniff`; an SVG additionally carries `content-security-policy: script-src 'none'`, so an SVG opened directly runs no script. An `If-None-Match` equal to that tag answers 304 without opening the file, and `HEAD` answers without a body. `fetchBundle()` returns the same responses, with a streamed body that closes the file when cancelled.
### What the browser loads
@@ -46,6 +46,7 @@ The application combo scripts carry only each plugin's `client.js` entry and reg
An open Web page follows the Host's complete module graph through the HMR transport. Enabling an ordinary plugin adds its Loader entry; disabling it removes the entry and waits for its asynchronous effects before evicting unused modules and styles. Re-enabling loads one instance with its styles. Other Loader contributors and shared modules still needed by active entries remain loaded. Settings → Plugins → Plugin list shows page-local synchronization failures and offers retry without changing Host enablement.
<a id="host-release-changes"></a>
### Host release changes
Every graph carries the Host release identity as `release`: this package's `version`, which releases share with the CLI, and the source `commit` that the client build fixes into the built Host artifact. Two releases are equal only when both fields are. A page applies graphs and rebuilt frames only while the connected Host serves the release the page booted from, so every module the page runs belongs to that release; when the Host returns to it, the usual revision comparison replaces exactly the changed modules. While the Host serves another release, the page applies nothing from it, keeps its current plugins running, and publishes `ctx.modules.entries.releaseChange` with the page's boot release, the Host's previous release, and its current release; only a page reload loads the other release. `dismissRelease()` withdraws the announcement and keeps the page quiet for that Host release until another one appears; it remembers only the last dismissed release, in page memory. Retrying failed plugins on the Plugins page does not load the other release either: the retry requests the boot release's artifacts, which a Host serving another release no longer has, so it ends in a download failure.
@@ -74,7 +75,11 @@ The package has two sides: the Node half is the composition and serving side (`c
### Lazy-CJS model
Executing a plugin bundle only registers its factory; every module-body side effect (CSS injection included) lives in the factory closure and runs at materialization (`factory(require)` → exports, memoized in `loadCache`). A factory that requires another registered-but-unmaterialized module materializes it recursively; require cycles throw because factory-form CJS cannot deliver partial exports. Resolution checks the platform seed table, memoized records, boot-graph rows, and registered factories in that order; anything else throws. The synchronous `require` uses the same order without asynchronous graph-row loading and records observed edges into the module record. Its `require.async` operation returns a Promise and fetches a compiler-generated package-local chunk before materializing that chunk once. This protocol supports self-contained chunks only: entry and chunk outputs cannot synchronously require another relative `client*.js` output.
Executing a plugin bundle registers its factory and optional `meta` without calling them. First import or synchronous require materializes JavaScript and caches its exports; recursive require cycles reject. The module record retains `ownerId`, observed dependency edges, and `meta` as supplied, without filling in a missing producer. Modules never evaluates stylesheet metadata: it exposes `activeRecords()`, `subscribeModules()` and the carrier asset resolver for consumers. `activeRecords()` lists every materialized record plus the previous records of a package under live replacement, which stay listed until its old runtime has been torn down. The [renderer](../ui-renderer/README.md) owns metadata evaluation and stylesheet installation. Package-local `require.async()` retains its lazy arrival and owner identity.
### Main execution environment
The module system constructs its own Main Realm around `loadBundle`, or the existing page script transport when no carrier hook is supplied. Default boot still prefetches the immediate tier before creating Loader entries; no Realm registry or isolation configuration is required. `dispose()` stops accepting scripts and waits for pending carrier operations without cancelling them. The optional [Realm registry](../script-realm/README.md) and [iframe provider](../script-realm-iframe/README.md) do not participate in this default path.
### Incremental composition
@@ -92,7 +97,7 @@ The host contributes structured index rows that inject, into `<head>`: the `wind
### Entry ownership
`ClientEntries` records the entries created during boot and serializes full-graph updates, retries and code reloads over the same Loader. As the Host Loader group does, a boot entry whose creation rejects, such as a module that exports no plugin, is logged and stays inactive for the boot audit instead of aborting startup. A local generation prevents an older download from mounting after its desired entry or code changes; snapshots of the same targets share the pending load. A graph from another release than the boot release stays outside the queue: retries keep reconciling the last applied graph, and rebuilt frames are ignored while the Host serves that release. New arrivals use single-resource URLs, never startup batches that could register existing factories twice. Factories retain their artifact revision before an entry exists; graph updates discard stale unowned factories, their styles and failed arrival targets before importing consumers. Cleanup retains declared and observed transitive module requests from every remaining Loader entry. Its observable status has no runtime library import because the modules bootstrap materializes before platform seeds are available.
`ClientEntries` records the entries created during boot and serializes full-graph updates, retries and code reloads over the same Loader. As the Host Loader group does, a boot entry whose creation rejects, such as a module that exports no plugin, is logged and stays inactive for the boot audit instead of aborting startup. A local generation prevents an older download from mounting after its desired entry or code changes; snapshots of the same targets share the pending load. A graph from another release than the boot release stays outside the queue: retries keep reconciling the last applied graph, and rebuilt frames are ignored while the Host serves that release. New arrivals use single-resource URLs, never startup batches that could register existing factories twice. Factories retain their artifact revision before an entry exists; graph updates discard stale unowned factories, their materialized records and failed arrival targets before importing consumers. Cleanup retains declared and observed transitive module requests from every remaining Loader entry. Its observable status has no runtime library import because the modules bootstrap materializes before platform seeds are available.
### Source map
@@ -103,7 +108,7 @@ The host contributes structured index rows that inject, into `<head>`: the `wind
| [`src/client/index.ts`](src/client/index.ts) | Browser half: bootstrap export, `ctx.modules` enrollment |
| [`src/client/system.ts`](src/client/system.ts) | `ClientModuleSystem`: load/materialize/invalidate machinery |
| [`src/client/entries.ts`](src/client/entries.ts) | Page entry reconciliation, retries and code replacement |
| [`src/client/entry-lifecycle.ts`](src/client/entry-lifecycle.ts) | Loader fiber teardown through the registry and owned-style cleanup |
| [`src/client/entry-lifecycle.ts`](src/client/entry-lifecycle.ts) | Loader fiber teardown through the registry |
| [`src/client/manifest.ts`](src/client/manifest.ts) | Wire types, boot-manifest parsing, and the `dsh.client` declaration parser |
</details>
+8 -4
View File
@@ -36,7 +36,7 @@ kind: "package-reference"
<a id="package-assets"></a>
### 包资源
同一个 `/plugins` 路由也提供客户端包通过其 `"./assets/*": "./lib/assets/*"` 导出发布的图片。构建会产出每个被引用的资源,在扩展名之前插入其内容 revision(资源字节 SHA-1 摘要的前 12 位十六进制数字),并把 import 或样式表 `url()` 编译成对 bundle 模块加载器的同步调用 `require.asset("plugins/<package>/assets/<emitted path>")`,因此一个 URL 始终对应一份内容。每个路径段先用 `encodeURIComponent` 编码,再编码 `!`、`'`、`(`、`)` 和 `*`,因此引用本身也是合法的无引号 CSS `url()`;仓库外构建的包必须输出同样的形式。除非页面的载体提供了 `resolveAsset`,这个调用都返回文档相对引用;WebWorker 预览的页面无法请求该引用,它把引用映射为 Worker 镜像中对应字节的 Blob URL。任何 `/plugins/<package>/assets/` 路径都只由资源路由响应:对于活动的客户端 row,Host 对路径做一次百分号解码,并从该包自身的 manifest(元数据清单)出发,用 Node 的 `require.resolve` 解析 `<package>/assets/<path>`,因此由包的导出决定哪些文件存在。无法解析的路径、扩展名不是 `.svg`、`.png`、`.webp`、`.jpg` 或 `.jpeg` 的已解析文件、格式错误的转义以及未激活的包都返回 404;查询串不参与选择。提供的资源每次请求都从磁盘流式读取且不缓存,并携带其媒体类型、与 bundle 相同的 `cache-control: public, max-age=31536000, immutable`、`etag: "<requested path>"` 和 `x-content-type-options: nosniff`;SVG 还额外携带 `content-security-policy: script-src 'none'`,因此直接打开的 SVG 不会运行脚本。`If-None-Match` 等于该 etag 时返回 304 且不打开文件,`HEAD` 的响应不带 body。`fetchBundle()` 返回相同的响应,其流式 body 在取消时关闭文件。
同一个 `/plugins` 路由也提供客户端包通过其 `"./assets/*": "./lib/assets/*"` 导出发布的图片。构建会产出每个被引用的资源,在扩展名之前插入其内容 revision(资源字节 SHA-1 摘要的前 12 位十六进制数字),并把 import 或样式表 `url()` 编译成同步资源解析调用(JavaScript 使用 `require.asset`,样式表 `text` 使用 `context.asset`),因此一个 URL 始终对应一份内容。每个路径段先用 `encodeURIComponent` 编码,再编码 `!`、`'`、`(`、`)` 和 `*`,因此引用本身也是合法的无引号 CSS `url()`;仓库外构建的包必须输出同样的形式。除非页面的载体提供了 `resolveAsset`,这个调用都返回文档相对引用;WebWorker 预览的页面无法请求该引用,它把引用映射为 Worker 镜像中对应字节的 Blob URL。任何 `/plugins/<package>/assets/` 路径都只由资源路由响应:对于活动的客户端 row,Host 对路径做一次百分号解码,并从该包自身的 manifest(元数据清单)出发,用 Node 的 `require.resolve` 解析 `<package>/assets/<path>`,因此由包的导出决定哪些文件存在。无法解析的路径、扩展名不是 `.svg`、`.png`、`.webp`、`.jpg` 或 `.jpeg` 的已解析文件、格式错误的转义以及未激活的包都返回 404;查询串不参与选择。提供的资源每次请求都从磁盘流式读取且不缓存,并携带其媒体类型、与 bundle 相同的 `cache-control: public, max-age=31536000, immutable`、`etag: "<requested path>"` 和 `x-content-type-options: nosniff`;SVG 还额外携带 `content-security-policy: script-src 'none'`,因此直接打开的 SVG 不会运行脚本。`If-None-Match` 等于该 etag 时返回 304 且不打开文件,`HEAD` 的响应不带 body。`fetchBundle()` 返回相同的响应,其流式 body 在取消时关闭文件。
### 浏览器加载什么
@@ -75,7 +75,11 @@ application combo 脚本只携带每个插件的 `client.js` 入口,并在启
### 惰性 CJS 模型
执行插件 bundle 只注册其 factory;每个模块主体副作用(包括 CSS 注入)都位于 factory 闭包中,在物化时运行(`factory(require)` → 导出,在 `loadCache` 中记忆化)。factory 依赖另一个已注册但未物化的模块时会递归物化它;require 循环会抛出异常,因为 factory 形式的 CJS 无法提供部分导出。解析会依次检查平台 seed 表、已记忆记录、启动图 row 与已注册 factory;其他情况一律抛错。交给 factory 的同步 `require` 使用相同顺序,但不含异步图 row 加载,并把观察到的边记录到模块记录中。它的 `require.async` 操作返回 Promise,并在一次性物化编译器生成的包内 chunk 前先获取该 chunk。该协议只支持自包含 chunk:入口与 chunk 产物不能同步 require 另一个相对 `client*.js` 产物。
执行插件 bundle 只登记其 factory 和可选的 `meta`,不调用它们。首次 import 或同步 require 会物化 JavaScript 并缓存导出;递归 require 环会被拒绝。模块记录保留 `ownerId`、观察到的依赖边和传入的 `meta`,不会为缺失的生产函数补值。Modules 不求值样式元信息,只向消费者提供 `activeRecords()`、`subscribeModules()` 和载体资源解析器。`activeRecords()` 列出所有已物化记录,以及正在实时替换的包的旧记录;旧记录保留到其旧运行时完成卸载。[Renderer](../ui-renderer/README.zh.md) 负责元信息求值与样式安装。包内 `require.async()` 保持惰性到达及所属模块身份。
### Main 执行环境
模块系统围绕 `loadBundle` 构造自身的 Main Realm;未提供载体 hook 时使用原有页面脚本传输。默认启动仍先预取 immediate 层级,再创建 Loader entries,不要求 Realm 注册表或隔离配置。`dispose()` 停止接受新脚本并等待进行中的载体操作,不取消这些操作。可选的 [Realm 注册表](../script-realm/README.zh.md)和 [iframe 提供方](../script-realm-iframe/README.zh.md)不参与默认路径。
### 增量组合
@@ -93,7 +97,7 @@ bundle 路由随注入的 `webServer` 生命周期注册:服务就绪时注册
### 条目所有权
`ClientEntries` 记录启动时创建的条目,并在同一个 Loader 上串行执行完整图更新、重试和代码重载。与 Host Loader 分组一样,启动时创建失败的条目(例如模块未导出插件)会记录日志并保持未激活,交由启动审计处理,而不会中止启动。本地代际阻止旧下载在目标条目或代码变化后挂载;目标相同的快照共用进行中的加载。来自启动 release 以外 release 的图不进入队列:重试继续调和上次应用的图,Host 提供该 release 期间忽略 rebuilt 帧。新增模块使用单资源 URL,不会重新执行可能重复注册现有 factory 的启动 batch。Factory 在条目创建前就保留产物 revision;图更新会在导入消费者前丢弃未归属条目的陈旧 factory、其样式和失败的到达目标。清理会保留每个剩余 Loader 条目的已声明及已观察到的传递模块依赖。其可观察状态不导入运行时库,因为 modules bootstrap 在平台种子可用之前物化。
`ClientEntries` 记录启动时创建的条目,并在同一个 Loader 上串行执行完整图更新、重试和代码重载。与 Host Loader 分组一样,启动时创建失败的条目(例如模块未导出插件)会记录日志并保持未激活,交由启动审计处理,而不会中止启动。本地代际阻止旧下载在目标条目或代码变化后挂载;目标相同的快照共用进行中的加载。来自启动 release 以外 release 的图不进入队列:重试继续调和上次应用的图,Host 提供该 release 期间忽略 rebuilt 帧。新增模块使用单资源 URL,不会重新执行可能重复注册现有 factory 的启动 batch。Factory 在条目创建前就保留产物 revision;图更新会在导入消费者前丢弃未归属条目的陈旧 factory、其物化记录和失败的到达目标。清理会保留每个剩余 Loader 条目的已声明及已观察到的传递模块依赖。其可观察状态不导入运行时库,因为 modules bootstrap 在平台种子可用之前物化。
### 源码索引
@@ -104,7 +108,7 @@ bundle 路由随注入的 `webServer` 生命周期注册:服务就绪时注册
| [`src/client/index.ts`](src/client/index.ts) | 浏览器半侧:bootstrap 导出、`ctx.modules` 登记 |
| [`src/client/system.ts`](src/client/system.ts) | `ClientModuleSystem`:加载/物化/失效机制 |
| [`src/client/entries.ts`](src/client/entries.ts) | 页面条目对账、重试与代码替换 |
| [`src/client/entry-lifecycle.ts`](src/client/entry-lifecycle.ts) | 通过注册表清理 Loader fiber,回收模块自身样式 |
| [`src/client/entry-lifecycle.ts`](src/client/entry-lifecycle.ts) | 通过注册表清理 Loader fiber |
| [`src/client/manifest.ts`](src/client/manifest.ts) | 协议类型、启动清单解析与 `dsh.client` 声明解析器 |
</details>
+2 -1
View File
@@ -43,7 +43,8 @@
"@deepseek-ai/dsh-host-webserver": "workspace:*",
"@deepseek-ai/cordis": "workspace:~",
"@deepseek-ai/dsh-package-manifest": "workspace:*",
"@deepseek-ai/dsh-client-store": "workspace:*"
"@deepseek-ai/dsh-client-store": "workspace:*",
"@deepseek-ai/dsh-client-script-realm": "workspace:*"
},
"files": [
"locale/*.json",
@@ -6,7 +6,7 @@ import { parseBootManifest, readRelease } from './manifest.ts'
import type { BootManifest, ClientModuleLoader } from './manifest.ts'
import { ReleaseChangeGate, type ClientReleaseChange } from './release-change.ts'
import { notifySubscribers } from './notify.ts'
import { removeOwnedStyles, tearDownEntryFiber } from './entry-lifecycle.ts'
import { tearDownEntryFiber } from './entry-lifecycle.ts'
/** Page-local failures do not change the Host's bundle enablement. */
export interface ClientEntryState {
@@ -19,7 +19,10 @@ export interface ClientEntryState {
/** Module-table capabilities used within serialized entry operations. */
interface ModuleIndex {
update(manifest: BootManifest, managed: Iterable<string>): void
/** Reset a package's code while its previous records stay active for the runtime that is still running. */
invalidateForReplacement(id: string, rev: string): void
/** Release the previous records once the replaced runtime has been torn down. */
releaseReplaced(id: string): void
prune(roots: Iterable<string>): void
}
@@ -146,7 +149,6 @@ export class ClientEntries {
const entry = this.managed.get(id)
if (entry === undefined) {
this.modules.invalidate(id, desired.rev)
removeOwnedStyles(id)
await this.reconcile(this.generation)
return
}
@@ -194,7 +196,7 @@ export class ClientEntries {
await this.modules.prefetch(id)
if (!this.current(generation)) return
await tearDownEntryFiber(entry)
removeOwnedStyles(id)
this.index.releaseReplaced(id)
if (!this.current(generation)) return
await this.modules.import(id, '', {})
if (!this.current(generation)) return
@@ -15,14 +15,3 @@ export async function tearDownEntryFiber(entry: Entry): Promise<void> {
while (fiber.inertia !== undefined) await fiber.inertia
delete entry.fiber
}
/**
* Remove styles after their plugin's effect cleanup has settled.
* @param id - Package whose factory owns the style tags.
*/
export function removeOwnedStyles(id: string): void {
if (typeof document === 'undefined') return
for (const el of document.querySelectorAll('style[data-plugin]')) {
if (el.getAttribute('data-plugin') === id) el.remove()
}
}
+1 -1
View File
@@ -34,7 +34,7 @@ export type {
* Build the live module system from the HTML facade's materialized modules bundle.
* @param target - Stable registration facade whose pending queue becomes the live sink.
* @param bootstrapModule - This bundle's id and already-materialized exports.
* @param options - Raw boot graph, platform seed, and optional bundle transport.
* @param options - Raw boot graph, delivered manifests, and optional bundle transport.
* @returns The created module system.
*/
export function createClientModuleSystem(
@@ -0,0 +1,46 @@
/** Initial execution environment supplied by the module system's startup carrier. */
import type { ScriptRealm } from '@deepseek-ai/dsh-client-script-realm/client'
/** Existing browser transport used when the carrier supplies no load hook. */
const loadPageBundle = (url: string): Promise<void> => new Promise((resolve, reject) => {
const el = document.createElement('script')
el.async = true
el.src = url
el.addEventListener('load', () => {
el.remove()
resolve()
}, { once: true })
el.addEventListener('error', () => {
el.remove()
reject(new Error(`client-modules: bundle script ${url} failed to load`))
}, { once: true })
document.head.append(el)
})
/** Owns execution requests without assuming the carrier has a browser document. */
export class MainScriptRealm implements Pick<ScriptRealm, 'id' | 'execute' | 'dispose'> {
readonly id = 'main' as ScriptRealm['id']
private readonly pending = new Set<Promise<void>>()
private closed = false
private disposal: Promise<void> | undefined
/** @param loadBundle - Carrier execution hook; absent selects the existing page transport. */
constructor(private readonly loadBundle: (url: string) => Promise<void> = loadPageBundle) {}
/** @param script - Script requested by Modules. @returns The carrier's execution completion. */
execute(script: Parameters<ScriptRealm['execute']>[0]): Promise<void> {
if (this.closed) return Promise.reject(new Error('client-modules: Main Realm is disposed'))
const task = this.loadBundle(script.url)
this.pending.add(task)
void task.then(() => { this.pending.delete(task) }, () => { this.pending.delete(task) })
return task
}
/** Stop accepting requests and await existing carrier operations without cancelling them. */
dispose(): Promise<void> {
if (this.disposal !== undefined) return this.disposal
this.closed = true
this.disposal = Promise.allSettled([...this.pending]).then(() => {})
return this.disposal
}
}
+44 -40
View File
@@ -7,15 +7,14 @@
* owns code arrival.
*
* Lazy CJS model: executing a plugin bundle only REGISTERS its
* factory (`window.__ModuleLoader__.load({id, factory})`); every module body
* side effect — including CSS injection — lives inside the factory closure
* and runs at materialization, not at script execution. Materialization
* factory and deferred metadata producer. JavaScript module body side effects
* run at materialization, not registration; metadata remains opaque to the loader. Materialization
* (factory(require) → exports) happens on first import/require and is
* memoized in {@link ClientModuleLoader.loadCache}; a factory that requires
* another registered-but-unmaterialized module materializes it recursively,
* so load order needs no external sequencing.
*
* Resolution branch order (import): seed word → shell instance; memoized
* Resolution branch order (import): memoized
* record → exports; graph row → register its dependency factories and own
* factory; registered factory → materialize; anything else → throw (loud —
* the runtime mirror of the build-time bundle purity gate).
@@ -30,7 +29,12 @@
*/
import type {} from '@deepseek-ai/cordis'
import type { DshClientManifest } from '@deepseek-ai/dsh-package-manifest'
import type {
DshClientManifest, ClientModuleMetaFactory,
DshClientModuleManifest,
} from '@deepseek-ai/dsh-package-manifest'
import type { ScriptRealm } from '@deepseek-ai/dsh-client-script-realm/client'
export type { ClientBundleRequire } from '@deepseek-ai/dsh-package-manifest'
import type { ClientEntries } from './entries.ts'
import type { ClientModuleSystem } from './system.ts'
@@ -345,41 +349,16 @@ export function readRelease(wire: unknown): WebBootRelease | undefined {
return decodeRelease((wire as Record<string, unknown>).release) ?? undefined
}
/** Module resolver passed into a registered Client bundle factory. */
export interface ClientBundleRequire {
/** Resolve a module-table dependency synchronously. */
(specifier: string): unknown
/** Load and resolve a package-local dynamic chunk asynchronously. */
async(specifier: string): Promise<unknown>
/**
* Resolve a package-asset reference (`plugins/<package>/assets/<path>`) the
* build compiled from an asset import or stylesheet `url()` to the URL the
* page loads; the reference itself unless the carrier maps it.
*/
asset(reference: string): string
}
/** One client bundle's factory registration submitted through `window.__ModuleLoader__.load`. */
export interface ClientBundleRegistration {
/** Plugin id (package name) — the registration key; must match the graph row being executed. */
id: string
/** Package-local chunk filename; absent for the package's `client.js` entry. */
chunk?: string
/**
* Closure factory holding the whole bundle body: receives the module-table
* require whose `async` operation loads generated chunks, and returns the
* bundle's exports. The factory runs once, at materialization.
*/
factory: (require: ClientBundleRequire) => Record<string, unknown>
}
/** Registration face of one shared browser artifact manifest. */
export type ClientBundleRegistration = DshClientModuleManifest
/** Inputs passed by the web entry when it creates the client module system. */
export interface ClientModuleCreateOptions {
/** Raw Host-injected boot graph; the modules bundle owns validation and projection. */
boot: unknown
/** Module-table seed: platform-singleton specifier → shell instance. */
staticModules: Record<string, unknown>
/** Bundle-load hook. Defaults to a same-origin classic `<script src>` element. */
/** Initially delivered manifests; registration does not evaluate their JavaScript or metadata. */
staticModules: readonly DshClientModuleManifest[]
/** Execution hook for the module system’s Main Realm; defaults to the page script transport. */
loadBundle?: (url: string) => Promise<void>
/** Package-asset reference hook behind {@link ClientBundleRequire.asset}. Defaults to returning the reference. */
resolveAsset?: (reference: string) => string
@@ -417,10 +396,12 @@ export interface DshWindow {
export interface ClientModuleRecord {
/** Module id (entry name / package name). */
id: string
/** Package identity shared by its entry and package-local chunks. */
readonly ownerId: string
/** Materialized exports (`module.exports` from a factory or bootstrap registration). */
exports: unknown
/** Owned `<style data-plugin>` tag ids (`data-plugin-css` values) injected during materialization. */
styles: string[]
/** Deferred metadata producer; JavaScript materialization does not evaluate it. */
meta?: ClientModuleMetaFactory
/** Observed `require()` edges (module-graph boundary; only table words can appear). */
edges: Set<string>
}
@@ -431,6 +412,25 @@ export interface ClientModuleRecord {
* as `ctx.modules`.
*/
export interface ClientModuleLoader {
/**
* Observe changes to {@link activeRecords} and to their cross-package dependency edges.
* @param listener - Called after a record materializes, records are released, or a record requests another package.
* @returns The subscription disposer.
*/
subscribeModules(listener: () => void): () => void
/**
* Records whose code can still be running: every {@link loadCache} record, plus the previous records of a
* package under live replacement until its old runtime has been torn down.
* @returns Previous records of replaced packages, then materialized records in registry order.
*/
activeRecords(): Iterable<ClientModuleRecord>
/**
* Resolve an asset reference through the startup carrier.
* @param reference - Compiled package-asset reference.
* @returns The carrier's resolved URL.
*/
resolveAsset(this: void, reference: string): string
/** Discriminant against Node's internal loader shapes ('v1'/'v2'). */
version: 'client'
/** Latest parsed Host graph, updated by live entry reconciliation. */
@@ -439,6 +439,10 @@ export interface ClientModuleLoader {
entries: ClientEntries
/** Materialized-module registry: entry or package-local chunk id → record. */
loadCache: Map<string, ClientModuleRecord>
/** Initial execution environment, fixed when the module system is constructed. */
readonly mainRealm: Pick<ScriptRealm, 'id' | 'execute' | 'dispose'>
/** Stop accepting scripts and await pending carrier operations. */
dispose(): Promise<void>
/**
* Internal contract consumed by the vendored Loader's `tree.import`. Resolves
* `specifier` through the branch order documented on the module, fetching
@@ -485,13 +489,13 @@ export interface ClientModuleLoader {
export interface ClientModuleSystemOptions {
/** Boot graph validated by {@link parseBootManifest}, owned by the resulting module system. */
manifest: BootManifest
/** Module-table seed: platform-singleton specifier → shell instance. */
staticModules: Record<string, unknown>
/** Initially delivered manifests; registration does not evaluate their JavaScript or metadata. */
staticModules: readonly DshClientModuleManifest[]
/** Stable HTML-installed registration facade to switch from queue to live mode. */
registrationTarget: ClientModuleLoaderTarget
/** Already-materialized modules bundle consumed while creating the system. */
bootstrapModule: ClientBootstrapModule
/** Bundle-load hook. Defaults to a same-origin classic `<script src>` element. */
/** Execution hook for the module system’s Main Realm; defaults to the page script transport. */
loadBundle?: (url: string) => Promise<void>
/** Package-asset reference hook behind {@link ClientBundleRequire.asset}. Defaults to returning the reference. */
resolveAsset?: (reference: string) => string
+123 -94
View File
@@ -6,28 +6,13 @@
*/
import { stripClientSuffix } from './manifest.ts'
import { ClientEntries } from './entries.ts'
import { removeOwnedStyles } from './entry-lifecycle.ts'
import { MainScriptRealm } from './main-realm.ts'
import { notifySubscribers } from './notify.ts'
import type {
BootManifest, BootModuleRow, ClientBundleRegistration, ClientBundleRequire, ClientModuleLoader, ClientModuleRecord,
ClientModuleSystemOptions,
} from './manifest.ts'
/** Default bundle-load hook: same-origin external classic script. */
const defaultLoadBundle = (url: string): Promise<void> => new Promise((resolve, reject) => {
const el = document.createElement('script')
el.async = true
el.src = url
el.addEventListener('load', () => {
el.remove()
resolve()
}, { once: true })
el.addEventListener('error', () => {
el.remove()
reject(new Error(`client-modules: bundle script ${url} failed to load`))
}, { once: true })
document.head.append(el)
})
/** Replace the rev query while preserving absolute, protocol-relative, or path-relative form. */
function atRevision(url: string, rev: string): string {
if (!/[?&]rev=[^&#]*/.test(url)) {
@@ -63,28 +48,6 @@ function chunkUrl(row: BootModuleRow, fileName: string, rev: string): string {
return `${url.slice(0, resourceStart)}/${row.id}/${fileName}?${url.slice(revisionStart + 1)}`
}
/** Untagged <style> elements present before a factory runs; the factory must not claim them. */
const untaggedStyles = (): ReadonlySet<Element> =>
typeof document === 'undefined' ? new Set() : new Set(document.querySelectorAll('style:not([data-plugin])'))
/**
* Claim and inventory the <style> tags a factory injected during
* materialization: preset-emitted tags arrive pre-tagged with data-plugin;
* an untagged tag that was absent from `before` is claimed for the
* materializing plugin (HMR bookkeeping).
*/
const claimStyles = (id: string, before: ReadonlySet<Element>): string[] => {
if (typeof document === 'undefined') return []
for (const el of untaggedStyles()) {
if (!before.has(el)) el.setAttribute('data-plugin', id)
}
const owned: string[] = []
for (const el of document.querySelectorAll(`style[data-plugin=${JSON.stringify(id)}]`)) {
owned.push(el.getAttribute('data-plugin-css') ?? id)
}
return owned
}
/**
* The client module system: state tables plus the arrival/materialization
* machinery implementing {@link ClientModuleLoader} (whose members carry the
@@ -97,11 +60,14 @@ export class ClientModuleSystem implements ClientModuleLoader {
manifest: BootManifest
readonly entries: ClientEntries
readonly loadCache = new Map<string, ClientModuleRecord>()
private readonly seed: Map<string, unknown>
private readonly factories = new Map<string, { factory: ClientBundleRegistration['factory']; rev: string | undefined }>()
readonly mainRealm: MainScriptRealm
/** Previous records of packages under replacement, by package id, until their old runtime is released. */
private readonly replaced = new Map<string, ClientModuleRecord[]>()
private readonly moduleListeners = new Set<() => void>()
private readonly factories = new Map<string, { manifest: ClientBundleRegistration; factory: ClientBundleRegistration['factory']; rev: string | undefined }>()
private readonly bootstrapIds = new Set<string>()
/** In-flight script transport per URL; every row in one batch shares it. */
private readonly staticIds = new Set<string>()
/** In-flight script transport per URL. */
private readonly pendingArrival = new Map<string, Promise<void>>()
/** Owner generation captured by in-flight chunk requests and advanced on invalidation. */
private readonly generations = new Map<string, number>()
@@ -110,8 +76,7 @@ export class ClientModuleSystem implements ClientModuleLoader {
/** Materialization re-entrancy guard: factory-form CJS cannot deliver partial exports, so a cycle is fatal. */
private readonly materializing = new Set<string>()
private readonly graphRows = new Map<string, BootModuleRow>()
private readonly loadBundle: (url: string) => Promise<void>
private readonly resolveAsset: (reference: string) => string
readonly resolveAsset: (reference: string) => string
/** Last import or prefetch failure per graph row, cleared by a later success or invalidation. */
private readonly importErrors = new Map<string, Error>()
/** Batch URLs whose transport or execution already failed; rows still missing from them go straight to their one-resource URL. */
@@ -121,7 +86,7 @@ export class ClientModuleSystem implements ClientModuleLoader {
/**
* Build the module system over the parsed boot rows.
* @param options - Parsed graph, platform seed, bootstrap module, registration facade, and transport.
* @param options - Parsed graph, delivered manifests, bootstrap module, registration facade, and transport.
*/
constructor(options: ClientModuleSystemOptions) {
this.manifest = options.manifest
@@ -129,12 +94,14 @@ export class ClientModuleSystem implements ClientModuleLoader {
update: (manifest, managed) => { this.updateManifest(manifest, managed) },
invalidateForReplacement: (id, rev) => {
if (this.bootstrapIds.has(id)) throw new Error(`client-modules: replacing bootstrap module ${id} requires a page reload`)
this.invalidate(id, rev)
this.drop(id, rev, true)
},
releaseReplaced: (id) => {
if (this.replaced.delete(this.resolveModuleId(id))) this.publishModules()
},
prune: (roots) => { this.prune(roots) },
})
this.seed = new Map(Object.entries(options.staticModules))
this.loadBundle = options.loadBundle ?? defaultLoadBundle
this.mainRealm = new MainScriptRealm(options.loadBundle)
this.resolveAsset = options.resolveAsset ?? (reference => reference)
for (const row of options.manifest.modules) {
@@ -145,8 +112,8 @@ export class ClientModuleSystem implements ClientModuleLoader {
this.bootstrapIds.add(bootstrapId)
this.loadCache.set(bootstrapId, {
id: bootstrapId,
ownerId: bootstrapId,
exports: options.bootstrapModule.exports,
styles: [],
edges: new Set(),
})
@@ -159,31 +126,61 @@ export class ClientModuleSystem implements ClientModuleLoader {
// must register live rather than append behind the drain.
target.mode = 'live'
target.load = (registration) => { this.register(registration) }
for (const registration of options.staticModules) {
this.staticIds.add(registration.id)
if (registration.id === bootstrapId && registration.chunk === undefined) continue
target.load(registration)
}
for (const registration of pending) target.load(registration)
}
subscribeModules(listener: () => void): () => void {
this.moduleListeners.add(listener)
return () => { this.moduleListeners.delete(listener) }
}
* activeRecords(): Iterable<ClientModuleRecord> {
for (const records of this.replaced.values()) yield * records
yield * this.loadCache.values()
}
private publishModules(): void {
notifySubscribers(this.moduleListeners, 'modules')
}
/** Stop accepting script execution and await the startup carrier's pending operations. */
dispose(): Promise<void> {
return this.mainRealm.dispose()
}
private resolveModuleId(specifier: string): string {
return this.staticIds.has(specifier) || this.factories.has(specifier) || this.loadCache.has(specifier)
? specifier : stripClientSuffix(specifier)
}
/** Register one bundle factory, rejecting a script that executes twice without invalidation. */
private register(registration: ClientBundleRegistration): void {
const ownerId = stripClientSuffix(registration.id)
const ownerId = registration.id
if (registration.chunk !== undefined && !CLIENT_CHUNK.test(registration.chunk)) {
throw new Error(`client-modules: invalid package-local chunk ${JSON.stringify(registration.chunk)}`)
}
const id = registration.chunk === undefined ? ownerId : chunkId(ownerId, registration.chunk)
if (this.bootstrapIds.has(id) || this.factories.has(id)) {
if (this.loadCache.has(id) || this.factories.has(id)) {
const registrationName = registration.chunk === undefined ? registration.id : id
throw new Error(`client-modules: duplicate factory registration for "${registrationName}" (bundle executed twice without invalidate?)`)
}
this.factories.set(id, {
manifest: registration,
factory: registration.factory,
rev: this.reloadTargets.get(ownerId)?.rev ?? this.graphRows.get(ownerId)?.rev,
})
}
/** Run one bundle transport per URL; every row waiting on the same URL shares the in-flight request. */
/** Run one shared script transport per URL. */
private loadShared(url: string): Promise<void> {
let transport = this.pendingArrival.get(url)
if (transport === undefined) {
transport = this.loadBundle(url)
transport = this.mainRealm.execute({ url })
.then(() => { this.executedBundleUrls.add(url) })
.finally(() => { this.pendingArrival.delete(url) })
this.pendingArrival.set(url, transport)
@@ -267,8 +264,8 @@ export class ClientModuleSystem implements ClientModuleLoader {
visited.add(row.id)
const next = [...open, row.id]
for (const request of row.external) {
const id = stripClientSuffix(request)
if (this.seed.has(request) || this.loadCache.has(id)) continue
const id = this.resolveModuleId(request)
if (this.loadCache.has(id) || this.factories.has(id) && !this.graphRows.has(id)) continue
const dependency = this.graphRows.get(id)
if (dependency !== undefined) await this.arriveDependency(row.id, dependency, next, visited)
}
@@ -297,7 +294,7 @@ export class ClientModuleSystem implements ClientModuleLoader {
}
/** Materialize a registered factory (synchronous; memoized in loadCache). */
private materialize(id: string, ownerId = id): ClientModuleRecord {
private materialize(id: string): ClientModuleRecord {
const existing = this.loadCache.get(id)
if (existing !== undefined) return existing
const registered = this.factories.get(id)
@@ -307,45 +304,63 @@ export class ClientModuleSystem implements ClientModuleLoader {
throw new Error(`client-modules: require cycle through "${id}" (factory-form CJS cannot deliver partial exports)`)
}
this.materializing.add(id)
const before = untaggedStyles()
let record: ClientModuleRecord
try {
const edges = new Set<string>()
const exports = registered.factory(this.makeRequire(ownerId, edges))
const record: ClientModuleRecord = { id, exports, styles: claimStyles(ownerId, before), edges }
const exports = registered.factory(this.makeRequire(registered.manifest.id, edges, () => {
if (this.loadCache.get(id)?.edges === edges) this.publishModules()
}))
record = { id, ownerId: registered.manifest.id, exports, edges,
...(registered.manifest.meta === undefined ? {} : { meta: registered.manifest.meta }) }
this.loadCache.set(id, record)
return record
} catch (error) {
claimStyles(ownerId, before)
removeOwnedStyles(ownerId)
throw error
} finally {
this.materializing.delete(id)
}
this.publishModules()
return record
}
/** Build the synchronous module-table require, its asynchronous chunk operation, and its asset resolver. */
private makeRequire(ownerId: string, edges: Set<string>): ClientBundleRequire {
const require = (spec: string): unknown => {
edges.add(spec)
if (this.seed.has(spec)) return this.seed.get(spec)
const id = stripClientSuffix(spec)
private makeRequire(
ownerId: string,
edges: Set<string>,
onEdgesChanged: () => void,
): ClientBundleRequire {
const resolve = (spec: string): unknown => {
const id = this.resolveModuleId(spec)
const record = this.loadCache.get(id)
if (record !== undefined) return record.exports
if (this.factories.has(id)) return this.materialize(id).exports
throw new Error(
`client-modules: require("${spec}") missed the module table — not a platform seed word, not a materialized module, `
`client-modules: require("${spec}") missed the module table — not a materialized module, `
+ 'and no registered package factory (a build-time externals drift, or a dynamic dependency that did not arrive)',
)
}
const recordEdge = (spec: string): void => {
if (edges.has(spec)) return
edges.add(spec)
// A relative chunk request stays inside its package; the chunk's own record is published when it materializes.
if (!spec.startsWith('./')) onEdgesChanged()
}
const require = (spec: string): unknown => {
const exports = resolve(spec)
recordEdge(spec)
return exports
}
require.asset = (reference: string): string => this.resolveAsset(reference)
require.async = async (spec: string): Promise<unknown> => {
edges.add(spec)
if (!spec.startsWith('./')) return await this.import(spec)
if (!spec.startsWith('./')) {
const exports = await this.import(spec)
recordEdge(spec)
return exports
}
const fileName = spec.slice(2)
if (!CLIENT_CHUNK.test(fileName)) {
throw new Error(`client-modules: invalid relative chunk request ${JSON.stringify(spec)}`)
}
return await this.importChunk(ownerId, fileName)
const exports = await this.importChunk(ownerId, fileName)
recordEdge(spec)
return exports
}
return require
}
@@ -362,34 +377,28 @@ export class ClientModuleSystem implements ClientModuleLoader {
/* v8 ignore next -- the final fallback needs an impossible graph-owned factory with no recorded revision. */
const revision = this.factories.get(ownerId)?.rev ?? this.reloadTargets.get(ownerId)?.rev ?? row.rev
const url = chunkUrl(row, fileName, revision)
let transport = this.pendingArrival.get(url)
if (transport === undefined) {
transport = this.loadBundle(url).finally(() => { this.pendingArrival.delete(url) })
this.pendingArrival.set(url, transport)
}
await transport
await this.loadShared(url)
if ((this.generations.get(ownerId) ?? 0) !== generation) {
this.factories.delete(id)
this.loadCache.delete(id)
if (this.loadCache.delete(id)) this.publishModules()
return await this.importChunk(ownerId, fileName)
}
if (!this.factories.has(id)) {
throw new Error(`client-modules: bundle ${url} loaded without registering "${id}" via __ModuleLoader__.load`)
}
}
return this.materialize(id, ownerId).exports
return this.materialize(id).exports
}
async import(specifier: string): Promise<unknown> {
if (this.seed.has(specifier)) return this.seed.get(specifier)
const id = stripClientSuffix(specifier)
const id = this.resolveModuleId(specifier)
const existing = this.loadCache.get(id)
if (existing !== undefined) return existing.exports
const row = this.graphRows.get(id)
if (row === undefined) {
if (this.factories.has(id)) return this.materialize(id).exports
throw new Error(
`client-modules: cannot resolve "${specifier}" — not a seed word, not a materialized module, `
`client-modules: cannot resolve "${specifier}" — not a materialized module, `
+ 'and not a row in the boot graph (the runtime mirror of the bundle purity gate)',
)
}
@@ -400,9 +409,10 @@ export class ClientModuleSystem implements ClientModuleLoader {
}
async prefetch(id: string): Promise<void> {
const normalized = stripClientSuffix(id)
const normalized = this.resolveModuleId(id)
if (this.loadCache.has(normalized)) return
const row = this.graphRows.get(normalized)
if (row === undefined && this.factories.has(normalized)) return
if (row === undefined) throw new Error(`client-modules: prefetch("${id}") — not a graph entry`)
await this.recordingImportError(normalized, () => this.arriveGraphRow(row))
}
@@ -441,7 +451,6 @@ export class ClientModuleSystem implements ClientModuleLoader {
const cachedRevision = this.factories.get(row.id)?.rev ?? this.reloadTargets.get(row.id)?.rev
if (!owned.has(row.id) && cachedRevision !== undefined && cachedRevision !== row.rev) {
this.invalidate(row.id, row.rev)
removeOwnedStyles(row.id)
}
}
this.manifest = manifest
@@ -451,27 +460,38 @@ export class ClientModuleSystem implements ClientModuleLoader {
private prune(roots: Iterable<string>): void {
const retained = new Set<string>(this.bootstrapIds)
const visit = (specifier: string): void => {
const id = stripClientSuffix(specifier)
const id = this.resolveModuleId(specifier)
if (retained.has(id)) return
retained.add(id)
const row = this.graphRows.get(id)
for (const request of [...row?.external ?? [], ...row?.inject ?? [], ...this.loadCache.get(id)?.edges ?? []]) {
// A replaced runtime that is still mounted keeps the modules its previous records requested.
const observed = [this.loadCache.get(id), ...this.replaced.get(id) ?? []].flatMap(record => [...record?.edges ?? []])
for (const request of [...row?.external ?? [], ...row?.inject ?? [], ...observed]) {
visit(request)
}
}
for (const id of this.staticIds) visit(id)
for (const row of this.manifest.modules) visit(row.id)
for (const id of roots) visit(id)
for (const id of this.graphRows.keys()) {
if (retained.has(id)) continue
this.graphRows.delete(id)
this.invalidate(id)
removeOwnedStyles(id)
}
}
invalidate(id: string, rev?: string): void {
const normalized = stripClientSuffix(id)
if (this.bootstrapIds.has(normalized)) return
this.drop(id, rev, false)
}
/**
* Reset one package's code. With `retain`, its materialized records stay in {@link activeRecords}
* until `releaseReplaced`, because the runtime created from them is still running.
*/
private drop(id: string, rev: string | undefined, retain: boolean): void {
const normalized = this.resolveModuleId(id)
if (this.bootstrapIds.has(normalized)) throw new Error(`client-modules: replacing bootstrap module ${normalized} requires a page reload`)
if (this.staticIds.has(normalized)) return
this.importErrors.delete(normalized)
this.generations.set(normalized, (this.generations.get(normalized) ?? 0) + 1)
const row = this.graphRows.get(normalized)
@@ -482,8 +502,17 @@ export class ClientModuleSystem implements ClientModuleLoader {
for (const key of this.factories.keys()) {
if (key === normalized || key.startsWith(`${normalized}/client.`)) this.factories.delete(key)
}
for (const key of this.loadCache.keys()) {
if (key === normalized || key.startsWith(`${normalized}/client.`)) this.loadCache.delete(key)
const removed: ClientModuleRecord[] = []
for (const [key, record] of this.loadCache) {
if (key === normalized || key.startsWith(`${normalized}/client.`)) {
this.loadCache.delete(key)
removed.push(record)
}
}
if (retain) {
if (removed.length > 0) this.replaced.set(normalized, [...this.replaced.get(normalized) ?? [], ...removed])
return
}
if (this.replaced.delete(normalized) || removed.length > 0) this.publishModules()
}
}
@@ -0,0 +1,248 @@
// @vitest-environment jsdom
import { Context } from '@deepseek-ai/cordis'
import Loader from '@deepseek-ai/cordis-plugin-loader'
import { describe, expect, it, vi } from 'vitest'
import type { ClientModuleMeta, DshClientModuleManifest } from '@deepseek-ai/dsh-package-manifest'
import { createClientModuleSystem, type ClientModuleLoaderTarget } from '../src/client/index.ts'
const row = (id: string) => ({ id, url: `/plugins/??${id}/client.js&rev=0`, rev: '0' })
function fixture(
staticModules: readonly DshClientModuleManifest[] = [], ids: readonly string[] = [], loadBundle?: (url: string) => Promise<void>,
) {
const target: ClientModuleLoaderTarget = {
mode: 'queue', pendingQueue: [], load: () => {},
create: options => createClientModuleSystem(target, { id: 'bootstrap', exports: {} }, options),
}
const modules = target.create({ staticModules, boot: { rev: '0', entries: ids.map(row),
batches: ids.length ? [{ phase: 'application', url: '/batch', rev: '0', entries: ids }] : [] },
...(loadBundle === undefined ? {} : { loadBundle }) })
return { modules, target }
}
describe('materialized module records', () => {
it('keeps adopted bootstrap exports when the static table also contains its entry and a chunk', async () => {
const duplicate = vi.fn(() => ({ replaced: true }))
const { modules } = fixture([
{ id: 'bootstrap', factory: duplicate },
{ id: 'bootstrap', chunk: 'client.shared.js', factory: () => ({ shared: true }) },
])
try {
expect(await modules.import('bootstrap')).toEqual({})
expect(await modules.import('bootstrap/client.shared.js')).toEqual({ shared: true })
expect(modules.loadCache.get('bootstrap/client.shared.js')?.ownerId).toBe('bootstrap')
expect(duplicate).not.toHaveBeenCalled()
} finally { await modules.dispose() }
})
it('prefetches an exact static key without fetching or materializing its factory', async () => {
const factory = vi.fn(() => ({ marker: true }))
const transport = vi.fn(async () => {})
const { modules } = fixture([{ id: 'react-dom/client', factory }], [], transport)
const changed = vi.fn()
const off = modules.subscribeModules(changed)
try {
await modules.prefetch('react-dom/client')
expect(transport).not.toHaveBeenCalled()
expect(factory).not.toHaveBeenCalled()
expect(changed).not.toHaveBeenCalled()
expect(modules.loadCache.has('react-dom/client')).toBe(false)
expect(await modules.import('react-dom/client')).toEqual({ marker: true })
expect(factory).toHaveBeenCalledTimes(1)
expect(changed).toHaveBeenCalledTimes(1)
} finally {
off()
await modules.dispose()
}
})
it('evicts and reports a stale chunk materialized before its invalidated transport finishes', async () => {
let arrived!: () => void
let release!: () => void
const started = new Promise<void>((resolve) => { arrived = resolve })
const pending = new Promise<void>((resolve) => { release = resolve })
const stale = { version: 'old' }
const fresh = { version: 'new' }
const load = vi.fn(async (url: string): Promise<void> => {
if (url.endsWith('rev=0')) {
arrived()
await pending
target.load({ id: 'pkg', chunk: 'client.lazy.js', factory: () => stale })
expect(await modules.import('pkg/client.lazy.js')).toBe(stale)
} else {
expect(url).toContain('rev=next')
target.load({ id: 'pkg', chunk: 'client.lazy.js', factory: () => fresh })
}
})
const { modules, target } = fixture([], ['pkg'], load)
target.load({ id: 'pkg', factory: require => ({ open: () => require.async('./client.lazy.js') }) })
const owner = await modules.import('pkg') as { open(): Promise<unknown> }
const snapshots: unknown[] = []
const off = modules.subscribeModules(() => { snapshots.push(modules.loadCache.get('pkg/client.lazy.js')?.exports) })
const opening = owner.open()
try {
await started
modules.invalidate('pkg', 'next')
release()
expect(await opening).toBe(fresh)
expect(load).toHaveBeenCalledTimes(2)
expect(snapshots).toEqual([undefined, stale, undefined, fresh])
expect(modules.loadCache.get('pkg/client.lazy.js')?.exports).toBe(fresh)
} finally {
release()
await opening
off()
await modules.dispose()
}
})
it('materializes modules without metadata and keeps the field absent from their records', async () => {
const factory = vi.fn(() => ({ marker: true }))
const { modules, target } = fixture([{ id: 'static', factory }])
target.load({ id: 'dynamic', factory: require => ({ dependency: require('static') }) })
await expect(modules.import('dynamic')).resolves.toEqual({ dependency: { marker: true } })
expect(factory).toHaveBeenCalledTimes(1)
for (const id of ['bootstrap', 'static', 'dynamic']) {
expect(modules.loadCache.get(id)).toBeDefined()
expect(modules.loadCache.get(id)).not.toHaveProperty('meta')
}
modules.invalidate('dynamic')
target.load({ id: 'dynamic', factory: () => ({ revision: 2 }) })
await expect(modules.import('dynamic')).resolves.toEqual({ revision: 2 })
expect(modules.loadCache.get('dynamic')).not.toHaveProperty('meta')
})
it('retains opaque metadata without evaluating it during registration or materialization', async () => {
const text = vi.fn(() => '.a {}')
const metadata = vi.fn(() => ({ stylesheets: { 'a.css': { text } }, description: 'resource owner' }))
const factory = vi.fn(() => ({ marker: true }))
const { modules } = fixture([{ id: 'a', factory, meta: metadata }])
const changed = vi.fn()
const off = modules.subscribeModules(changed)
expect(modules.loadCache.has('a')).toBe(false)
expect(factory).not.toHaveBeenCalled()
expect(metadata).not.toHaveBeenCalled()
const exports = await modules.import('a')
expect(await modules.import('a')).toBe(exports)
expect(modules.loadCache.get('a')?.meta).toBe(metadata)
expect(metadata).not.toHaveBeenCalled()
expect(text).not.toHaveBeenCalled()
expect(changed).toHaveBeenCalledTimes(1)
const describe = modules.loadCache.get('a')!.meta as typeof metadata
expect(describe().description).toBe('resource owner')
expect(text).not.toHaveBeenCalled()
off()
})
it('retains metadata containing no stylesheets for an external consumer', async () => {
const information: ClientModuleMeta & { description: string } = { description: 'ordinary module information' }
const metadata = vi.fn(() => information)
const { modules } = fixture([{ id: 'a', factory: () => ({}), meta: metadata }])
await modules.import('a')
expect(metadata).not.toHaveBeenCalled()
expect(modules.loadCache.get('a')!.meta!()).toBe(information)
expect(information).not.toHaveProperty('stylesheets')
})
it('leaves metadata failures to the caller that evaluates the stored producer', async () => {
const metadata = vi.fn(() => { throw new Error('metadata unavailable') })
const { modules } = fixture([{ id: 'a', factory: () => ({ marker: true }), meta: metadata }])
await expect(modules.import('a')).resolves.toEqual({ marker: true })
expect(metadata).not.toHaveBeenCalled()
expect(() => modules.loadCache.get('a')!.meta!()).toThrow('metadata unavailable')
expect(await modules.import('a')).toEqual({ marker: true })
})
it('replaces the module record on invalidation without evaluating reused metadata', async () => {
const metadata = vi.fn(() => ({}))
const { modules, target } = fixture()
target.load({ id: 'a', factory: () => ({ version: 1 }), meta: metadata })
await modules.import('a')
const first = modules.loadCache.get('a')!
const snapshots: (typeof first | undefined)[] = []
const off = modules.subscribeModules(() => { snapshots.push(modules.loadCache.get('a')) })
modules.invalidate('a')
target.load({ id: 'a', factory: () => ({ version: 2 }), meta: metadata })
expect(snapshots).toEqual([undefined])
await modules.import('a')
const second = modules.loadCache.get('a')!
expect(second).not.toBe(first)
expect(second.exports).toEqual({ version: 2 })
expect(second.meta).toBe(metadata)
expect(snapshots).toEqual([undefined, second])
expect(metadata).not.toHaveBeenCalled()
off()
})
it('uses the manifest owner when a synchronous shared chunk imports a lazy chunk', async () => {
const load = vi.fn(async (url: string) => {
expect(url).toContain('/pkg/client.lazy.js')
target.load({ id: 'pkg', chunk: 'client.lazy.js', factory: () => ({ lazy: true }) })
})
const { modules, target } = fixture([
{ id: 'pkg', factory: require => require('pkg/client.shared.js') as Record<string, unknown> },
{ id: 'pkg', chunk: 'client.shared.js', factory: require => ({ open: () => require.async('./client.lazy.js') }) },
], ['pkg'], load)
const exports = await modules.import('pkg') as { open(): Promise<unknown> }
expect(await exports.open()).toEqual({ lazy: true })
expect(load).toHaveBeenCalledTimes(1)
expect(modules.loadCache.get('pkg')?.edges).toEqual(new Set(['pkg/client.shared.js']))
expect(modules.loadCache.get('pkg/client.shared.js')?.edges).toEqual(new Set(['./client.lazy.js']))
expect(modules.loadCache.get('pkg/client.lazy.js')?.exports).toEqual({ lazy: true })
expect(modules.loadCache.get('pkg/client.shared.js')?.ownerId).toBe('pkg')
expect(modules.loadCache.get('pkg/client.lazy.js')?.ownerId).toBe('pkg')
})
it('publishes materialized dependencies before their consumer record', async () => {
const { modules } = fixture([
{ id: 'a', factory: (require) => { require('a/client.shared.js'); require('z'); return {} } },
{ id: 'a', chunk: 'client.shared.js', factory: (require) => { require('b'); return {} } },
{ id: 'z', factory: () => ({}) },
{ id: 'b', factory: () => ({}) },
])
const observed: string[][] = []
const off = modules.subscribeModules(() => { observed.push([...modules.loadCache.keys()]) })
await modules.import('a')
expect(observed).toEqual([
['bootstrap', 'b'],
['bootstrap', 'b', 'a/client.shared.js'],
['bootstrap', 'b', 'a/client.shared.js', 'z'],
['bootstrap', 'b', 'a/client.shared.js', 'z', 'a'],
])
expect(modules.loadCache.get('a')?.edges).toEqual(new Set(['a/client.shared.js', 'z']))
expect(modules.loadCache.get('a/client.shared.js')?.edges).toEqual(new Set(['b']))
off()
})
it('publishes later dependency edges after asynchronous imports and supports unsubscription', async () => {
const { modules, target } = fixture()
target.load({ id: 'b', factory: () => ({}) })
target.load({ id: 'a', factory: require => ({ open: () => require.async('b') }) })
const a = await modules.import('a') as { open(): Promise<unknown> }
const snapshots: string[][] = []
const changed = vi.fn(() => { snapshots.push([...modules.loadCache.get('a')!.edges]) })
const off = modules.subscribeModules(changed)
await a.open()
expect(snapshots).toEqual([[], ['b']])
await a.open()
expect(changed).toHaveBeenCalledTimes(2)
off()
modules.invalidate('a')
expect(changed).toHaveBeenCalledTimes(2)
})
it('keeps initial static identities across pruning and ignores invalidation of exact static keys', async () => {
const factory = vi.fn(() => ({ marker: true, apply: () => {} }))
const { modules } = fixture([{ id: 'react-dom/client', factory }], ['react-dom/client'])
const exports = await modules.import('react-dom/client')
const ctx = new Context()
try {
await ctx.plugin(Loader)
ctx.loader.internal = modules as never
await modules.entries.start(ctx.loader, modules.manifest)
await modules.entries.sync({ rev: '1', entries: [], batches: [] })
modules.invalidate('react-dom/client')
expect(await modules.import('react-dom/client')).toBe(exports)
expect(factory).toHaveBeenCalledTimes(1)
} finally { await ctx.fiber.dispose() }
})
})
@@ -2,16 +2,19 @@
import { Context } from '@deepseek-ai/cordis'
import Loader from '@deepseek-ai/cordis-plugin-loader'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { apply as provideModules, createClientModuleSystem } from '../src/client/index.ts'
import { createClientModuleSystem } from '../src/client/index.ts'
import type { ClientBundleRegistration, ClientModuleLoaderTarget, WebBootRelease, WebBootEntry, WebBootGraph } from '../src/client/index.ts'
type Factory = ClientBundleRegistration['factory']
type FixtureModule = Factory | Pick<ClientBundleRegistration, 'factory' | 'meta'>
const stylesheet = (path: string, css: string): NonNullable<ClientBundleRegistration['meta']> => () => ({ stylesheets: { [path]: { text: () => css } } })
const contexts: Context[] = []
afterEach(async () => {
for (const ctx of contexts.splice(0)) {
await ctx.fiber.dispose()
await ctx.fiber.await()
}
document.head.querySelectorAll('style').forEach((el) => { el.remove() })
document.body.replaceChildren()
vi.restoreAllMocks()
})
@@ -29,21 +32,26 @@ const deferred = () => {
return { promise, resolve }
}
async function bench(initial: WebBootGraph, factories: Record<string, ClientBundleRegistration['factory']>, start = true) {
async function bench(initial: WebBootGraph, factories: Record<string, FixtureModule>, start = true) {
const ctx = new Context()
contexts.push(ctx)
const fetched: string[] = []
const target: ClientModuleLoaderTarget = {
mode: 'queue', pendingQueue: [], load: () => {},
create: options => createClientModuleSystem(target, { id: 'bootstrap', exports: { inject: ['loader'], apply: provideModules } }, options),
create: options => createClientModuleSystem(target, { id: 'bootstrap', exports: { inject: ['loader'], apply(ctx: Context) { ctx.reflect.provide('modules', ctx.loader.internal) } } }, options),
}
let arrival: (url: string) => Promise<void> = async () => {}
const modules = target.create({
boot: initial, staticModules: {},
boot: initial, staticModules: [],
loadBundle: async (url) => {
fetched.push(url)
const ids = url === '/batch' ? initial.entries.map(row => row.id).filter(id => id !== 'bootstrap') : [url.split('??')[1]!.split('/client.js')[0]!]
const registrations = ids.map(id => ({ id, factory: factories[id]! }))
const registrations = ids.map((id) => {
const definition = factories[id]!
return typeof definition === 'function'
? { id, factory: definition }
: { id, ...definition }
})
await arrival(url)
for (const registration of registrations) target.load(registration)
},
@@ -54,14 +62,11 @@ async function bench(initial: WebBootGraph, factories: Record<string, ClientBund
return { ctx, modules, fetched, target, arrival: (fn: typeof arrival) => { arrival = fn } }
}
/** A visible plugin whose style and listener are owned by its factory and fiber respectively. */
function visible(id: string, effects: { mounted: number; disposed: number; hits: number }, cleanup?: () => Promise<void>) {
return () => {
const style = document.createElement('style')
style.dataset.plugin = id
style.textContent = `[data-live="${id}"] { color: rgb(12, 34, 56); }`
document.head.append(style)
return { apply(ctx: Context) {
/** A visible plugin with opaque metadata and a listener owned by its fiber. */
function visible(id: string, effects: { mounted: number; disposed: number; hits: number }, cleanup?: () => Promise<void>): Pick<ClientBundleRegistration, 'factory' | 'meta'> {
return {
meta: vi.fn(stylesheet(`${id}.css`, `[data-live="${id}"] { color: rgb(12, 34, 56); }`)),
factory: () => ({ apply(ctx: Context) {
ctx.effect(() => {
effects.mounted++
const el = document.createElement('div')
@@ -76,21 +81,23 @@ function visible(id: string, effects: { mounted: number; disposed: number; hits:
effects.disposed++
}
})
} }
} }),
}
}
describe('client manifest entries', () => {
it('adds, drains removal and re-enables one instance with styles; unrelated entries survive', async () => {
it('adds, drains removal and re-enables one module record; unrelated entries survive', async () => {
const effects = { mounted: 0, disposed: 0, hits: 0 }
const cleanup = deferred()
const b = await bench(graph(), { pet: visible('pet', effects, () => cleanup.promise) })
const plugin = visible('pet', effects, () => cleanup.promise)
const b = await bench(graph(), { pet: plugin })
b.target.load({ id: 'local', factory: () => ({ apply() {} }) })
const localId = await b.ctx.loader.create({ name: 'local' })
await b.modules.entries.sync(graph(row('pet')))
expect(b.fetched).toEqual([row('pet').url])
expect(document.querySelectorAll('[data-live=pet]')).toHaveLength(1)
expect(document.querySelectorAll('style[data-plugin=pet]')).toHaveLength(1)
expect(b.modules.loadCache.get('pet')?.meta).toBe(plugin.meta)
expect(plugin.meta).not.toHaveBeenCalled()
window.dispatchEvent(new Event('live-test'))
expect(effects.hits).toBe(1)
const removing = b.modules.entries.sync(graph())
@@ -101,13 +108,14 @@ describe('client manifest entries', () => {
cleanup.resolve()
await Promise.all([removing, readding])
expect(effects).toEqual({ mounted: 2, disposed: 1, hits: 1 })
expect(document.querySelectorAll('style[data-plugin=pet]')).toHaveLength(1)
expect(b.modules.loadCache.get('pet')?.meta).toBe(plugin.meta)
expect(plugin.meta).not.toHaveBeenCalled()
expect(b.ctx.loader.resolve(localId).fiber?.state).toBe(2)
await b.modules.entries.sync(graph())
window.dispatchEvent(new Event('live-test'))
expect(effects).toEqual({ mounted: 2, disposed: 2, hits: 1 })
expect(document.querySelectorAll('style[data-plugin=pet]')).toHaveLength(0)
expect(b.modules.loadCache.has('pet')).toBe(false)
expect(plugin.meta).not.toHaveBeenCalled()
expect(b.modules.entries.state.getSnapshot()).toEqual({ syncing: false, failures: [] })
})
@@ -176,7 +184,8 @@ describe('client manifest entries', () => {
it('deduplicates rebuilt and graph revisions and retries after failed code arrival', async () => {
const effects = { mounted: 0, disposed: 0, hits: 0 }
const b = await bench(graph(row('pet')), { pet: visible('pet', effects) })
const plugin = visible('pet', effects)
const b = await bench(graph(row('pet')), { pet: plugin })
await b.modules.entries.reload('pet', 'r1')
await b.modules.entries.sync(graph(row('pet', 'r1')))
expect(effects).toEqual({ mounted: 2, disposed: 1, hits: 0 })
@@ -186,7 +195,8 @@ describe('client manifest entries', () => {
b.arrival(async () => {})
await b.modules.entries.retry()
expect(effects).toEqual({ mounted: 3, disposed: 2, hits: 0 })
expect(document.querySelectorAll('style[data-plugin=pet]')).toHaveLength(1)
expect(b.modules.loadCache.get('pet')?.meta).toBe(plugin.meta)
expect(plugin.meta).not.toHaveBeenCalled()
})
it('rejects malformed graphs before mutating active entries', async () => {
@@ -240,18 +250,20 @@ it('reports reconciliation before startup and missing service activation without
expect(b.modules.entries.state.getSnapshot().failures).toEqual([])
})
it('retries a materialization failure with the same graph and cleans its partial styles', async () => {
it('retries a materialization failure without publishing a partial module record', async () => {
let broken = true
const b = await bench(graph(), { a: () => {
const style = document.createElement('style')
style.dataset.plugin = 'a'
document.head.append(style)
if (broken) throw new Error('factory failed')
return { apply() {} }
const meta = vi.fn(stylesheet('a.css', '.a {}'))
const b = await bench(graph(), { a: {
factory: () => {
if (broken) throw new Error('factory failed')
return { apply() {} }
},
meta,
} })
await b.modules.entries.sync(graph(row('a')))
expect(b.modules.entries.state.getSnapshot().failures[0]?.message).toContain('factory failed')
expect(document.querySelectorAll('style[data-plugin=a]')).toHaveLength(0)
expect(b.modules.loadCache.has('a')).toBe(false)
expect(meta).not.toHaveBeenCalled()
await b.modules.entries.retry()
expect(b.modules.entries.state.getSnapshot().failures[0]?.message).toContain('factory failed')
await b.modules.entries.reload('a', 'r1').catch(() => {})
@@ -259,7 +271,8 @@ it('retries a materialization failure with the same graph and cleans its partial
broken = false
await b.modules.entries.retry()
expect(b.modules.entries.state.getSnapshot().failures).toEqual([])
expect(document.querySelectorAll('style[data-plugin=a]')).toHaveLength(1)
expect(b.modules.loadCache.get('a')?.meta).toBe(meta)
expect(meta).not.toHaveBeenCalled()
})
it('does not finish a stale code replacement after download or asynchronous teardown', async () => {
@@ -284,6 +297,95 @@ it('does not finish a stale code replacement after download or asynchronous tear
expect(b.modules.loadCache.has('a')).toBe(false)
})
it('keeps the previous module records active until the replaced runtime has been torn down', async () => {
const effects = { mounted: 0, disposed: 0, hits: 0 }
const cleanup = deferred()
const b = await bench(graph(row('a')), { a: visible('a', effects, () => cleanup.promise) })
const previous = b.modules.loadCache.get('a')!
const active = (): boolean => [...b.modules.activeRecords()].includes(previous)
const published: boolean[] = []
b.modules.subscribeModules(() => { published.push(active()) })
const download = deferred()
const started = deferred()
b.arrival(async () => { started.resolve(); await download.promise })
const replacing = b.modules.entries.reload('a', 'r1')
await started.promise
// The replacement is downloading while the previous runtime is still mounted.
expect(document.querySelectorAll('[data-live=a]')).toHaveLength(1)
expect(b.modules.loadCache.has('a')).toBe(false)
expect(active()).toBe(true)
download.resolve()
await vi.waitFor(() => { expect(document.querySelector('[data-live=a]')).toBeNull() })
// Its asynchronous cleanup has not settled yet.
expect(active()).toBe(true)
expect(published).toEqual([])
cleanup.resolve()
await replacing
expect(published).toEqual([false, false])
expect(b.modules.loadCache.get('a')).not.toBe(previous)
expect([...b.modules.activeRecords()]).toContain(b.modules.loadCache.get('a'))
expect(effects).toEqual({ mounted: 2, disposed: 1, hits: 0 })
})
it('keeps the previous module records active while a failed replacement leaves the old runtime running', async () => {
const effects = { mounted: 0, disposed: 0, hits: 0 }
const b = await bench(graph(row('a')), { a: visible('a', effects) })
const previous = b.modules.loadCache.get('a')!
const published = vi.fn()
b.modules.subscribeModules(published)
b.arrival(async () => { throw new Error('offline') })
await expect(b.modules.entries.reload('a', 'r1')).rejects.toThrow('offline')
expect(document.querySelectorAll('[data-live=a]')).toHaveLength(1)
expect([...b.modules.activeRecords()]).toContain(previous)
expect(published).not.toHaveBeenCalled()
b.arrival(async () => {})
await b.modules.entries.reload('a', 'r2')
expect([...b.modules.activeRecords()]).not.toContain(previous)
expect(effects).toEqual({ mounted: 2, disposed: 1, hits: 0 })
b.arrival(async () => { throw new Error('offline') })
const current = b.modules.loadCache.get('a')!
await expect(b.modules.entries.reload('a', 'r3')).rejects.toThrow('offline')
expect([...b.modules.activeRecords()]).toContain(current)
// Disabling the plugin releases records that a failed replacement left active.
await b.modules.entries.sync(graph())
expect([...b.modules.activeRecords()]).not.toContain(current)
expect(document.querySelector('[data-live=a]')).toBeNull()
})
it('retains a module that only a running replaced runtime requests when the graph drops it', async () => {
const effects = { mounted: 0, disposed: 0, hits: 0 }
const plugin = visible('a', effects)
const b = await bench(graph(row('a'), row('b')), {
a: { ...plugin, factory: (require) => { require('b'); return plugin.factory(require) } },
b: () => ({ apply() {} }),
})
const library = b.modules.loadCache.get('b')!
b.arrival(async () => { throw new Error('offline') })
await expect(b.modules.entries.reload('a', 'r1')).rejects.toThrow('offline')
b.arrival(async () => {})
await b.modules.entries.sync(graph(row('a')))
// The previous runtime of `a` is still mounted and still uses `b`.
expect(document.querySelectorAll('[data-live=a]')).toHaveLength(1)
expect(b.modules.loadCache.get('b')).toBe(library)
expect([...b.modules.activeRecords()]).toContain(library)
})
it('replaces an entry whose previous import left no module record', async () => {
let broken = true
const b = await bench(graph(row('a')), { a: () => {
if (broken) throw new Error('factory failed')
return { apply() {} }
} })
expect(b.modules.loadCache.has('a')).toBe(false)
broken = false
const published: string[][] = []
b.modules.subscribeModules(() => { published.push([...b.modules.activeRecords()].map(record => record.id)) })
await b.modules.entries.reload('a', 'r1')
expect(b.ctx.loader.resolve([...b.ctx.loader.entries()].find(entry => entry.options.name === 'a')!.id).fiber?.state).toBe(2)
// Nothing was retained, so releasing the replaced records publishes nothing before the new record materializes.
expect(published).toEqual([['bootstrap', 'a']])
})
it('stops an obsolete multi-entry application after awaiting removal', async () => {
const cleanup = deferred()
const effects = { mounted: 0, disposed: 0, hits: 0 }
@@ -306,20 +408,27 @@ it('keeps bootstrap ownership explicit and diagnoses removal without changing en
expect(b.modules.entries.state.getSnapshot().failures).toEqual([])
})
it('retains unrelated style tags while reporting a failed replacement', async () => {
it('retains an unrelated module record while reporting a failed replacement', async () => {
let broken = false
const effects = { mounted: 0, disposed: 0, hits: 0 }
const b = await bench(graph(row('a')), { a: () => {
if (broken) throw new Error('changed factory failed')
return visible('a', effects)()
const plugin = visible('a', effects)
const b = await bench(graph(row('a')), { a: {
...plugin,
factory: (require) => {
if (broken) throw new Error('changed factory failed')
return plugin.factory(require)
},
} })
const unrelated = document.createElement('style')
unrelated.dataset.plugin = 'unrelated'
document.head.append(unrelated)
b.target.load({ id: 'unrelated', factory: () => ({ apply() {} }) })
await b.ctx.loader.create({ name: 'unrelated' })
const unrelated = b.modules.loadCache.get('unrelated')
expect(unrelated).toBeDefined()
broken = true
await b.modules.entries.sync(graph(row('a', 'r1')))
expect(b.modules.entries.state.getSnapshot().failures[0]?.message).toContain('changed factory failed')
expect(unrelated.isConnected).toBe(true)
expect(b.modules.loadCache.has('a')).toBe(false)
expect(b.modules.loadCache.get('unrelated')).toBe(unrelated)
expect(plugin.meta).not.toHaveBeenCalled()
})
@@ -426,12 +535,13 @@ it('coalesces an overlapping graph snapshot with the same rebuilt artifact', asy
it.each(['graph', 'rebuilt'])('replaces a failed factory before entry creation on a new %s revision', async (source) => {
const effects = { mounted: 0, disposed: 0, hits: 0 }
const factories: Record<string, ClientBundleRegistration['factory']> = { a: () => { throw new Error('broken r0 factory') } }
const factories: Record<string, FixtureModule> = { a: () => { throw new Error('broken r0 factory') } }
const b = await bench(graph(), factories)
await b.modules.entries.sync(graph(row('a')))
expect([...b.ctx.loader.entries()]).toHaveLength(0)
expect(b.modules.entries.state.getSnapshot().failures[0]?.message).toContain('broken r0 factory')
factories.a = () => ({ ...visible('a', effects)(), revision: 'r1' })
const replacement = visible('a', effects)
factories.a = { ...replacement, factory: require => ({ ...replacement.factory(require), revision: 'r1' }) }
if (source === 'graph') await b.modules.entries.sync(graph(row('a', 'r1')))
else await b.modules.entries.reload('a', 'r1')
await b.modules.entries.retry()
@@ -445,7 +555,7 @@ it.each(['graph', 'rebuilt'])('replaces a failed factory before entry creation o
it('replaces a superseded arrival and its cached dependency before mounting the latest code', async () => {
const dependency = row('dependency')
const consumer = row('consumer', 'r0', { external: ['dependency/client'] })
const factories: Record<string, ClientBundleRegistration['factory']> = {
const factories: Record<string, FixtureModule> = {
dependency: () => ({ apply() {}, revision: 'r0' }),
consumer: require => ({ apply() {}, dependency: require('dependency/client'), revision: 'r0' }),
}
@@ -472,8 +582,9 @@ it('replaces a superseded arrival and its cached dependency before mounting the
it.each(['graph', 'rebuilt'])('preserves bootstrap and dependent fibers when a %s requests new bootstrap code', async (source) => {
const effects = { mounted: 0, disposed: 0, hits: 0 }
const consumer = visible('consumer', effects)
const b = await bench(graph(row('bootstrap'), row('consumer')), {
consumer: () => ({ ...visible('consumer', effects)(), inject: ['modules'] }),
consumer: { ...consumer, factory: require => ({ ...consumer.factory(require), inject: ['modules'] }) },
})
const fibers = [...b.ctx.loader.entries()].map(entry => entry.fiber)
const exports = await b.modules.import('bootstrap')
@@ -513,23 +624,33 @@ it('uses the latest desired revision when a rebuild queues before entry creation
expect([...b.ctx.loader.entries()]).toHaveLength(1)
})
it('cleans styles from a materialized factory superseded before its entry is created', async () => {
it('replaces metadata from a materialized factory superseded before its entry is created', async () => {
const effects = { mounted: 0, disposed: 0, hits: 0 }
let latest: Promise<void> | undefined
const factories: Record<string, ClientBundleRegistration['factory']> = { a: () => {
const old = visible('a', effects)()
queueMicrotask(() => {
factories.a = visible('a', effects)
latest = b.modules.entries.sync(graph(row('a', 'r1')))
})
return old
const replacement = visible('a', effects)
const oldMeta = vi.fn(() => ({ stylesheets: {
'old-a.css': { text: () => '.old {}' },
'a.css': { text: () => '[data-live="a"] { color: rgb(12, 34, 56); }' },
} }))
const factories: Record<string, FixtureModule> = { a: {
meta: oldMeta,
factory: (require) => {
const old = visible('a', effects).factory(require)
queueMicrotask(() => {
factories.a = replacement
latest = b.modules.entries.sync(graph(row('a', 'r1')))
})
return old
},
} }
const b = await bench(graph(), factories)
await b.modules.entries.sync(graph(row('a')))
await latest
expect(b.fetched).toEqual([row('a').url, row('a', 'r1').url])
expect(effects).toEqual({ mounted: 1, disposed: 0, hits: 0 })
expect(document.querySelectorAll('style[data-plugin=a]')).toHaveLength(1)
expect(b.modules.loadCache.get('a')?.meta).toBe(replacement.meta)
expect(oldMeta).not.toHaveBeenCalled()
expect(replacement.meta).not.toHaveBeenCalled()
})
describe('Host release changes', () => {
@@ -1,5 +1,4 @@
// @vitest-environment jsdom
import { removeOwnedStyles } from '../src/client/entry-lifecycle.ts'
import { readRelease } from '../src/client/manifest.ts'
import { Context } from '@deepseek-ai/cordis'
import { afterEach, describe, expect, it, vi } from 'vitest'
@@ -23,6 +22,8 @@ const win = globalThis as DshWindow
const bootstrapExports = { apply, createClientModuleSystem }
type Factory = ClientBundleRegistration['factory']
type Meta = NonNullable<ClientBundleRegistration['meta']>
const stylesheet = (path: string, css: string): Meta => () => ({ stylesheets: { [path]: { text: () => css } } })
afterEach(() => {
vi.unstubAllGlobals()
@@ -72,7 +73,8 @@ function bench(
entries: BootModuleRow[],
bundles: Record<string, Factory | null> = {},
opts: {
seed?: Record<string, unknown>
seed?: readonly ClientBundleRegistration[]
metadata?: Record<string, Meta>
gated?: string[]
pending?: ClientBundleRegistration[]
defaultTransport?: boolean
@@ -103,7 +105,8 @@ function bench(
const id = sibling[1] as string
const chunk = sibling[2] as string
const factory = opts.chunks?.[`${id}/${chunk}`]
if (factory != null) win.__ModuleLoader__?.load({ id, chunk, factory })
const meta = opts.metadata?.[`${id}/${chunk}`]
if (factory != null) win.__ModuleLoader__?.load({ id, chunk, factory, ...(meta === undefined ? {} : { meta }) })
return
}
const batchIds = url === BOOTSTRAP_URL
@@ -120,7 +123,8 @@ function bench(
for (const id of batchIds ?? (singleId === undefined ? [] : [singleId])) {
if (only !== undefined && !only.includes(id)) continue
const factory = bundles[id]
if (factory != null) win.__ModuleLoader__?.load({ id, factory })
const meta = opts.metadata?.[id]
if (factory != null) win.__ModuleLoader__?.load({ id, factory, ...(meta === undefined ? {} : { meta }) })
}
}
const bootstrapEntries = entries.filter(entry => entry.initialUrl === BOOTSTRAP_URL).map(entry => entry.id)
@@ -143,13 +147,92 @@ function bench(
})),
batches,
},
staticModules: opts.seed ?? {},
staticModules: opts.seed ?? [],
...(opts.defaultTransport === true ? {} : { loadBundle }),
...(opts.resolveAsset === undefined ? {} : { resolveAsset: opts.resolveAsset }),
})
return { loader, target, fetched, gates }
}
describe('materialized module inventory', () => {
it('retains only successful records and reports chunk ownership without loading lazy code', async () => {
let loadChunk!: () => Promise<unknown>
const b = bench([row('a'), row('b'), row('broken')], {
a: (require) => { loadChunk = () => require.async('./client.details.js'); return {} },
b: () => ({}),
broken: () => { throw new Error('factory failed') },
}, {
seed: [{ id: 'platform', factory: () => ({}) }],
chunks: { 'a/client.details.js': () => ({}) },
})
const ids = () => [...b.loader.loadCache.keys()].sort()
const changed = vi.fn()
const off = b.loader.subscribeModules(changed)
expect(ids()).toEqual([MODULES_ID])
await b.loader.import('platform', '', {})
expect(ids()).toEqual([MODULES_ID, 'platform'])
expect(changed).toHaveBeenCalledTimes(1)
expect(b.fetched).toEqual([])
await b.loader.prefetch('a')
expect(ids()).toEqual([MODULES_ID, 'platform'])
expect(changed).toHaveBeenCalledTimes(1)
await b.loader.import('a', '', {})
expect(ids()).toEqual([MODULES_ID, 'a', 'platform'])
expect(b.fetched).not.toContain(chunkReference('a', 'client.details.js'))
await loadChunk()
expect(ids()).toEqual([MODULES_ID, 'a', 'a/client.details.js', 'platform'])
expect(b.loader.loadCache.get('a/client.details.js')?.ownerId).toBe('a')
await expect(b.loader.import('broken', '', {})).rejects.toThrow('factory failed')
expect(b.loader.loadCache.has('broken')).toBe(false)
await b.loader.import('b', '', {})
expect(ids()).toEqual([MODULES_ID, 'a', 'a/client.details.js', 'b', 'platform'])
b.loader.invalidate('a')
expect(ids()).toEqual([MODULES_ID, 'b', 'platform'])
off()
})
it('retains the owner identity of an already-materialized standalone chunk', async () => {
const b = bench([], {}, { pending: [{ id: 'owner', chunk: 'client.details.js', factory: () => ({}) }] })
await b.loader.import('owner/client.details.js', '', {})
expect([...b.loader.loadCache.keys()]).toEqual([MODULES_ID, 'owner/client.details.js'])
expect(b.loader.loadCache.get('owner/client.details.js')?.ownerId).toBe('owner')
expect(b.fetched).toEqual([])
})
it('records loaded dynamic and static dependency edges without further transport', async () => {
const b = bench([row('a'), row('b')], {
a: (require) => { require('b'); return {} },
b: (require) => { require('shared'); return {} },
}, {
seed: [
{ id: 'shared', factory: (require) => { require('base'); return {} } },
{ id: 'base', factory: () => ({}) },
],
})
await b.loader.import('a', '', {})
const fetched = [...b.fetched]
expect(b.loader.loadCache.get('a')?.edges).toEqual(new Set(['b']))
expect(b.loader.loadCache.get('b')?.edges).toEqual(new Set(['shared']))
expect(b.loader.loadCache.get('shared')?.edges).toEqual(new Set(['base']))
expect(b.fetched).toEqual(fetched)
})
it('records lazy chunk dependencies only after its factory materializes', async () => {
let loadChunk!: () => Promise<unknown>
const b = bench([row('a'), row('b')], {
a: (require) => { loadChunk = () => require.async('./client.details.js'); return {} },
b: () => ({}),
}, { chunks: { 'a/client.details.js': (require) => { require('b'); return {} } } })
await b.loader.import('a', '', {})
expect(b.loader.loadCache.get('a')?.edges).toEqual(new Set())
expect(b.loader.loadCache.has('a/client.details.js')).toBe(false)
expect(b.fetched).not.toContain(chunkReference('a', 'client.details.js'))
await loadChunk()
expect(b.loader.loadCache.get('a')?.edges).toEqual(new Set(['./client.details.js']))
expect(b.loader.loadCache.get('a/client.details.js')?.edges).toEqual(new Set(['b']))
})
})
describe('Cordis plugin face', () => {
it('rejects a Loader whose internal is absent or not a client module system', () => {
for (const internal of [undefined, { version: 'worker' }]) {
@@ -207,7 +290,7 @@ describe('lazy CJS arrival', () => {
], {
consumer: req => ({ provider: req('provider/client'), react: req('react') }),
provider: () => ({ marker: 'provider' }),
}, { seed: { react: { marker: 'react' } } })
}, { seed: [{ id: 'react', factory: () => ({ marker: 'react' }) }] })
const exports = await b.loader.import('consumer', '', {}) as {
provider: { marker: string }
react: { marker: string }
@@ -256,9 +339,12 @@ describe('lazy CJS arrival', () => {
const factory: Factory = req => ({ url: req.asset(reference) })
const served = bench([row('a')], { a: factory })
expect(await served.loader.import('a', '', {})).toEqual({ url: reference })
expect(served.loader.resolveAsset(reference)).toBe(reference)
const mapped = bench([row('a')], { a: factory }, { resolveAsset: asset => `blob:${asset}` })
expect(await mapped.loader.import('a', '', {})).toEqual({ url: `blob:${reference}` })
const resolveAsset = mapped.loader.resolveAsset
expect(resolveAsset(reference)).toBe(`blob:${reference}`)
})
it('loads a package-local dynamic chunk only when its factory requests it', async () => {
@@ -515,15 +601,15 @@ describe('require resolution', () => {
expect(b.loader.loadCache.has('b')).toBe(true)
})
it('require prefers the platform seed word over the module table', async () => {
it('require and import share one materialized platform instance', async () => {
const react = { marker: 'react' }
const b = bench([row('a')], {
a: req => ({ dep: req('react') }),
}, { seed: { react } })
}, { seed: [{ id: 'react', factory: () => react }] })
const exports = await b.loader.import('a', '', {})
expect((exports as { dep: unknown }).dep).toBe(react)
expect(await b.loader.import('react', '', {})).toBe(react)
expect(b.loader.loadCache.has('react')).toBe(false)
expect(b.loader.loadCache.get('react')?.exports).toBe(react)
})
it('require answers an already-materialized module from the cache', async () => {
@@ -569,8 +655,8 @@ describe('bootstrap module', () => {
})
it('publishes the module system attached to its own Loader', () => {
const a = bench([])
const b = bench([])
const a = bench([], {})
const b = bench([], {})
const ctxA = new Context()
const ctxB = new Context()
ctxA.reflect.provide('loader', { internal: a.loader })
@@ -585,15 +671,18 @@ describe('bootstrap module', () => {
it('rejects a second queued registration for the bootstrap id', () => {
expect(() => bench([], {}, {
pending: [{ id: `${MODULES_ID}/client`, factory: () => ({}) }],
})).toThrow(`duplicate factory registration for "${MODULES_ID}/client"`)
pending: [{ id: MODULES_ID, factory: () => ({}) }],
})).toThrow(`duplicate factory registration for "${MODULES_ID}"`)
})
})
describe('failure modes', () => {
it('duplicate factory registration is loud', () => {
it('duplicate factory registration is loud, including reuse of the same manifest object', () => {
bench([])
win.__ModuleLoader__?.load({ id: 'x', factory: () => ({}) })
const registration = { id: 'x', factory: () => ({}) }
win.__ModuleLoader__?.load(registration)
expect(() => win.__ModuleLoader__?.load(registration))
.toThrow('duplicate factory registration for "x"')
expect(() => win.__ModuleLoader__?.load({ id: 'x', factory: () => ({}) }))
.toThrow('duplicate factory registration for "x"')
})
@@ -672,7 +761,7 @@ describe('failure modes', () => {
const b = bench([])
const options: ClientModuleCreateOptions = {
boot: { rev: 'graph', entries: [], batches: [] },
staticModules: {},
staticModules: [],
}
expect(() => b.target.create(options)).toThrow('create called after module-system boot')
})
@@ -842,68 +931,72 @@ describe('HMR reset', () => {
})
})
describe('style claiming', () => {
it('claims untagged style tags for the materializing plugin and inventories owned css ids', async () => {
const foreign = document.createElement('style')
foreign.setAttribute('data-plugin', 'other')
document.head.appendChild(foreign)
const b = bench([row('a')], {
a: () => {
document.head.appendChild(document.createElement('style'))
const tagged = document.createElement('style')
tagged.setAttribute('data-plugin', 'a')
tagged.setAttribute('data-plugin-css', 'sheet-1')
document.head.appendChild(tagged)
return {}
},
})
await b.loader.import('a', '', {})
expect(b.loader.loadCache.get('a')?.styles).toEqual(['a', 'sheet-1'])
expect(document.querySelectorAll('style[data-plugin="a"]')).toHaveLength(2)
expect(foreign.getAttribute('data-plugin')).toBe('other')
})
it('leaves untagged style tags inserted before materialization unclaimed', async () => {
describe('opaque module metadata', () => {
it('retains metadata producers for external consumers without claiming document nodes', async () => {
const earlier = document.createElement('style')
earlier.textContent = '.earlier {}'
document.head.appendChild(earlier)
const b = bench([row('a')], { a: () => ({}) })
const text = vi.fn(() => '.a {}')
const meta = vi.fn(() => ({ stylesheets: { 'a.css': { text } } }))
const b = bench([row('a')], { a: () => ({}) }, { metadata: { a: meta } })
await b.loader.prefetch('a')
expect(meta).not.toHaveBeenCalled()
await b.loader.import('a', '', {})
removeOwnedStyles('a')
expect(meta).not.toHaveBeenCalled()
expect(text).not.toHaveBeenCalled()
expect(b.loader.loadCache.get('a')?.meta).toBe(meta)
expect(meta).not.toHaveBeenCalled()
expect(text).not.toHaveBeenCalled()
expect([...document.querySelectorAll('style')]).toEqual([earlier])
expect(earlier.getAttributeNames()).toEqual([])
b.loader.invalidate('a')
expect(b.loader.loadCache.has('a')).toBe(false)
expect(earlier.isConnected).toBe(true)
expect(earlier.hasAttribute('data-plugin')).toBe(false)
})
it('assigns an untagged style to the factory that inserted it before a nested require', async () => {
const outer = document.createElement('style')
it('does not claim style nodes inserted by plugin code before a nested require', async () => {
const inserted = document.createElement('style')
const b = bench([row('b'), row('a', { external: ['b'] })], {
a: (require) => {
document.head.appendChild(outer)
require('b')
return {}
},
a: (require) => { document.head.appendChild(inserted); require('b'); return {} },
b: () => ({}),
})
}, { metadata: { a: stylesheet('a.css', '.a {}'), b: stylesheet('b.css', '.b {}') } })
await b.loader.import('a', '', {})
expect(outer.getAttribute('data-plugin')).toBe('a')
expect(inserted.getAttributeNames()).toEqual([])
expect([...document.querySelectorAll('style')]).toEqual([inserted])
expect(b.loader.loadCache.get('a')?.edges).toEqual(new Set(['b']))
})
it('removes untagged styles inserted by a factory that throws', async () => {
const leaked = document.createElement('style')
const b = bench([row('a')], { a: () => { document.head.appendChild(leaked); throw new Error('factory exploded') } })
it('does not evaluate failed factory metadata or remove document nodes', async () => {
const existing = document.createElement('style')
existing.dataset.plugin = 'a'
document.head.appendChild(existing)
const inserted = document.createElement('style')
const meta = vi.fn(stylesheet('a.css', '.a {}'))
const b = bench([row('a')], { a: () => {
document.head.appendChild(inserted)
throw new Error('factory exploded')
} }, { metadata: { a: meta } })
const changed = vi.fn()
const off = b.loader.subscribeModules(changed)
await expect(b.loader.import('a', '', {})).rejects.toThrow('factory exploded')
expect(leaked.isConnected).toBe(false)
expect(b.loader.loadCache.has('a')).toBe(false)
expect(meta).not.toHaveBeenCalled()
expect(b.loader.loadCache.has('a')).toBe(false)
expect(changed).not.toHaveBeenCalled()
off()
expect([...document.querySelectorAll('style')]).toEqual([existing, inserted])
expect(inserted.getAttributeNames()).toEqual([])
})
it('materialization without a document skips the style inventory', async () => {
const b = bench([row('a')], { a: () => ({}) })
it('retains opaque metadata without a document', async () => {
const b = bench([row('a')], { a: () => ({}) }, { metadata: { a: stylesheet('a.css', '.a {}') } })
vi.stubGlobal('document', undefined)
try {
await b.loader.import('a', '', {})
removeOwnedStyles('a')
expect(typeof b.loader.loadCache.get('a')?.meta).toBe('function')
} finally {
vi.unstubAllGlobals()
}
expect(b.loader.loadCache.get('a')?.styles).toEqual([])
})
})
@@ -943,7 +1036,7 @@ describe('default transport seam', () => {
it('rejects invalid revision URLs and keeps bootstrap exports pinned under invalidation', () => {
const b = bench([row(MODULES_ID), row('a', { url: '/unrevisioned' })])
b.loader.invalidate(MODULES_ID)
expect(() =>{ b.loader.invalidate(MODULES_ID) }).toThrow(/requires a page reload/)
expect(b.loader.loadCache.get(MODULES_ID)?.exports).toBe(bootstrapExports)
expect(() =>{ b.loader.invalidate('a', 'next') }).toThrow('has no revision')
})
@@ -952,7 +1045,7 @@ it('prefetch skips platform requests, cached dependencies and absent optional in
const b = bench([
row('a'),
row('b', { external: ['platform', 'a/client'], inject: ['missing'] }),
], { a: () => ({}), b: () => ({}) }, { seed: { platform: {} } })
], { a: () => ({}), b: () => ({}) }, { seed: [{ id: 'platform', factory: () => ({}) }] })
await b.loader.import('a', '', {})
await b.loader.import('b', '', {})
expect(b.fetched).toEqual([APPLICATION_URL])
@@ -0,0 +1,91 @@
// @vitest-environment jsdom
import { describe, expect, it, vi } from 'vitest'
import { MainScriptRealm } from '../src/client/main-realm.ts'
import { createClientModuleSystem, type ClientModuleLoaderTarget } from '../src/client/index.ts'
function fixture(loadBundle?: (url: string) => Promise<void>) {
const target: ClientModuleLoaderTarget = {
mode: 'queue', pendingQueue: [], load: () => {},
create: options => createClientModuleSystem(target, { id: 'bootstrap', exports: {} }, options),
}
const modules = target.create({
boot: { rev: '1', entries: [{ id: 'a', url: '/a.js', rev: '1' }],
batches: [{ phase: 'application', url: '/a.js', rev: '1', entries: ['a'] }] },
staticModules: [], ...(loadBundle === undefined ? {} : { loadBundle }),
})
return { modules, target }
}
const registration = { id: 'a', factory: () => ({ marker: true }) }
describe('module-owned Main Realm', () => {
it('uses the page script transport immediately without a readiness handoff', async () => {
const { modules, target } = fixture()
const append = document.head.append.bind(document.head)
const load = vi.spyOn(document.head, 'append').mockImplementation((...nodes) => {
append(...nodes)
target.load(registration)
const script = nodes[0]
if (typeof script === 'string' || script === undefined) throw new Error('expected a script node')
script.dispatchEvent(new Event('load'))
})
try {
expect(modules.mainRealm.id).toBe('main')
expect(await modules.import('a')).toEqual({ marker: true })
expect(load).toHaveBeenCalledTimes(1)
expect(document.head.querySelector('script')).toBeNull()
} finally {
load.mockRestore()
await modules.dispose()
}
})
it('preserves the configured carrier and shares one transport across concurrent requests', async () => {
const load = vi.fn(async (url: string) => { expect(url).toBe('/a.js'); target.load(registration) })
const { modules, target } = fixture(load)
const realm = modules.mainRealm
await Promise.all([modules.prefetch('a'), modules.prefetch('a')])
expect(load).toHaveBeenCalledTimes(1)
expect(modules.mainRealm).toBe(realm)
expect(await modules.import('a')).toEqual({ marker: true })
await modules.dispose()
})
it('returns the carrier completion and failure without replacing them', async () => {
const failure = new Error('carrier failed')
const task = Promise.reject(failure)
const load = vi.fn(() => task)
const realm = new MainScriptRealm(load)
expect(realm.execute({ url: 'carrier-script' })).toBe(task)
await expect(task).rejects.toBe(failure)
expect(load).toHaveBeenCalledWith('carrier-script')
await realm.dispose()
})
it('waits for existing carrier work and rejects new execution after disposal starts', async () => {
let finish!: () => void
const pending = new Promise<void>((resolve) => { finish = resolve })
const load = vi.fn(() => pending)
const realm = new MainScriptRealm(load)
const execution = realm.execute({ url: 'pending' })
const disposal = realm.dispose()
expect(realm.dispose()).toBe(disposal)
let disposed = false
void disposal.then(() => { disposed = true })
await Promise.resolve()
expect(disposed).toBe(false)
await expect(realm.execute({ url: 'late' })).rejects.toThrow('disposed')
expect(load).toHaveBeenCalledTimes(1)
finish()
await execution
await disposal
expect(disposed).toBe(true)
})
it('keeps synchronous carrier throws synchronous', async () => {
const error = new Error('synchronous carrier failure')
const realm = new MainScriptRealm(() => { throw error })
expect(() => realm.execute({ url: 'invalid' })).toThrow(error)
await realm.dispose()
})
})
@@ -270,7 +270,7 @@ describe('HTML bootstrap facade', () => {
target.load({ id: MODULES_ID, factory: () => modulesClient })
const system = target.create({
boot: graph,
staticModules: {},
staticModules: [],
loadBundle: async (url) => {
expect(url).toBe(APPLICATION_URL)
target.load({ id: UI_RENDERER_ID, factory: () => ({ marker: 'ui-renderer' }) })
@@ -282,7 +282,7 @@ describe('HTML bootstrap facade', () => {
expect(system.manifest.rev).toBe('graph')
expect(await system.import(MODULES_ID)).toBe(modulesClient)
expect(await system.import(`${UI_RENDERER_ID}/client`)).toEqual({ marker: 'ui-renderer' })
expect(() => target.create({ boot: graph, staticModules: {} }))
expect(() => target.create({ boot: graph, staticModules: [] }))
.toThrow('create called after module-system boot')
})
@@ -299,7 +299,7 @@ describe('HTML bootstrap facade', () => {
it('rejects a page that did not preload the modules bundle', () => {
const graph = bootGraph()
const { target } = injectedFacade(graph)
expect(() => target.create({ boot: graph, staticModules: {} }))
expect(() => target.create({ boot: graph, staticModules: [] }))
.toThrow(`HTML did not preload ${MODULES_ID}/client.js`)
})
@@ -313,7 +313,7 @@ describe('HTML bootstrap facade', () => {
return modulesClient
},
})
expect(() => target.create({ boot: graph, staticModules: {} }))
expect(() => target.create({ boot: graph, staticModules: [] }))
.toThrow(`${MODULES_ID}/client.js requested external "react"`)
})
@@ -325,7 +325,7 @@ describe('HTML bootstrap facade', () => {
const graph = bootGraph()
const { target } = injectedFacade(graph)
target.load({ id: MODULES_ID, factory: () => exports as unknown as Record<string, unknown> })
expect(() => target.create({ boot: graph, staticModules: {} }))
expect(() => target.create({ boot: graph, staticModules: [] }))
.toThrow(`${MODULES_ID}/client.js did not export the bootstrap module face`)
})
})
+1
View File
@@ -12,6 +12,7 @@
{"path": "../../../vendor/loader"},
{"path": "../../host/webserver"},
{"path": "../../util/package-manifest"},
{"path": "../script-realm"},
{"path": "../store"}
]
}
@@ -0,0 +1,37 @@
# Bilingual-pair consistency record for README.md (docs/i18n/README.md): per heading
# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
# After editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write packages/client/script-realm-iframe/README.md
/:
en: ab83547c0e26bf9b
zh: 6cadc78b51ddf016
/deepseek-ai-dsh-client-script-realm-iframe:
en: 507d4fed0b68c013
zh: b81e9465ebeb3ec4
/deepseek-ai-dsh-client-script-realm-iframe/summary:
en: f5dbaaa1218e6c58
zh: bbab63fd577892e4
/deepseek-ai-dsh-client-script-realm-iframe/table-of-contents:
en: 23386452a66b2fbd
zh: dc8dd4f5941b9f74
/deepseek-ai-dsh-client-script-realm-iframe/use-this-package:
en: b988139d463e6607
zh: f1736d2b5984ab6c
/deepseek-ai-dsh-client-script-realm-iframe/understand-the-implementation:
en: 4941259f7f948d3e
zh: cbff0fe3744011be
/deepseek-ai-dsh-client-script-realm-iframe/further-exploration:
en: f0659a0a6d6e9876
zh: 66d902d62dd6cd0e
/deepseek-ai-dsh-client-script-realm-iframe/model-experience:
en: 91701b5ed41296fe
zh: caf84df42b9f91a8
/deepseek-ai-dsh-client-script-realm-iframe/model-experience/kv-cache-effect:
en: ca75c51c89c2c9b0
zh: f57cc48a1b5cbfa9
/deepseek-ai-dsh-client-script-realm-iframe/known-limitations-and-deferred-work:
en: c9197ab798546993
zh: a92ce7153db4ab6d
/deepseek-ai-dsh-client-script-realm-iframe/known-limitations-and-deferred-work/dev-note:
en: 0a1253c6f7b5e8b9
zh: 9f56528562c7c914
@@ -0,0 +1,58 @@
---
description: "Provide optional same-origin iframe script environments through the Realm registry."
kind: "package-reference"
---
# @deepseek-ai/dsh-client-script-realm-iframe
English | [中文](README.zh.md)
## Summary
Use this provider when framework code explicitly needs a separate browser global environment with direct object references. Loading the plugin registers the `iframe` factory without allocating a frame. It does not move application plugins or change their default execution environment.
## Table of Contents
- [Use this package](#use-this-package)
- [Understand the implementation](#understand-the-implementation)
- [Further Exploration](#further-exploration)
- [Model Experience](#model-experience)
- [Known Limitations and Deferred Work](#known-limitations-and-deferred-work)
- [Dev Note](#dev-note)
<a id="use-this-package"></a>
## Use this package
The normal Client plugin injects `scriptRealms` and registers its factory. A composition must supply the [registry](../script-realm/README.md); neither package is a default application entry. The provider accepts no configuration.
<a id="understand-the-implementation"></a>
## Understand the implementation
Each request creates a hidden same-origin iframe. `expose()` installs direct references without replacing existing or reserved globals. `execute()` loads an external classic script, resolving relative URLs against the provider page. Cancellation or disposal rejects pending executions and removes the frame. Callers retain responsibility for disposing created instances.
<a id="further-exploration"></a>
## Further Exploration
- [Client modules](../modules/README.md)
- [Web client architecture](../../../docs/subsystems/web-client.md)
- [Client entry](src/client/index.ts)
<a id="model-experience"></a>
## Model Experience
None, as this optional browser infrastructure registers no model-facing tools or prompts.
#### KV Cache effect
None; this package neither assembles nor sends a provider request.
## Known Limitations and Deferred Work
<a id="known-limitations-and-deferred-work"></a>
- Same-origin access is not hostile-code isolation. Native `window`, `document`, viewport, timers, and DOM constructors belong to the iframe; no transparent main-page emulation is provided. Module placement, pooling, and Shadow DOM are deferred.
<a id="dev-note"></a>
### Dev Note
None.
@@ -0,0 +1,58 @@
---
description: "通过 Realm 注册表提供可选的同源 iframe 脚本环境。"
kind: "package-reference"
---
# @deepseek-ai/dsh-client-script-realm-iframe
[English](README.md) | 中文
## 概述
当框架代码明确需要拥有独立浏览器全局对象、同时保留直接对象引用的环境时使用此提供方。加载插件只注册 `iframe` 工厂,不分配 frame。它不会迁移应用插件,也不会改变插件的默认执行环境。
## 目录
- [使用本包](#use-this-package)
- [理解实现](#understand-the-implementation)
- [进一步探索](#further-exploration)
- [模型体验](#model-experience)
- [已知限制与延期工作](#known-limitations-and-deferred-work)
- [开发备注](#dev-note)
<a id="use-this-package"></a>
## 使用本包
普通 Client 插件注入 `scriptRealms` 并注册工厂。组合必须提供[注册表](../script-realm/README.zh.md);两个包都不是默认应用条目。提供方不接受配置。
<a id="understand-the-implementation"></a>
## 理解实现
每次请求创建一个隐藏的同源 iframe。`expose()` 安装直接引用,不替换已有或保留的全局对象。`execute()` 加载外部 classic script,并相对提供方页面解析 URL。取消或销毁会拒绝进行中的执行并移除 frame。调用者负责销毁已创建实例。
<a id="further-exploration"></a>
## 进一步探索
- [Client 模块](../modules/README.zh.md)
- [Web 客户端架构](../../../docs/subsystems/web-client.zh.md)
- [Client 入口](src/client/index.ts)
<a id="model-experience"></a>
## 模型体验
无;本包是可选的浏览器基础设施,不注册面向模型的工具或提示词。
#### KV Cache 影响
无;本包既不组装也不发送提供方请求。
## 已知限制与延期工作
<a id="known-limitations-and-deferred-work"></a>
- 同源访问不提供恶意代码隔离。原生 `window`、`document`、视口、计时器和 DOM 构造器属于 iframe;本包不透明模拟主页面。模块放置、池化和 Shadow DOM 留待后续设计。
<a id="dev-note"></a>
### 开发备注
无。
@@ -0,0 +1,5 @@
{
"meta": {
"title": "Iframe-Umgebung"
}
}
@@ -0,0 +1,5 @@
{
"meta": {
"title": "Iframe realm"
}
}
@@ -0,0 +1,5 @@
{
"meta": {
"title": "Entorno iframe"
}
}
@@ -0,0 +1,5 @@
{
"meta": {
"title": "Environnement iframe"
}
}
@@ -0,0 +1,5 @@
{
"meta": {
"title": "Iframe Realm"
}
}
@@ -0,0 +1,5 @@
{
"meta": {
"title": "Ambiente iframe"
}
}
@@ -0,0 +1,5 @@
{
"meta": {
"title": "Среда iframe"
}
}
@@ -0,0 +1,5 @@
{
"meta": {
"title": "Iframe 运行域"
}
}
@@ -0,0 +1,56 @@
{
"name": "@deepseek-ai/dsh-client-script-realm-iframe",
"description": "Optional iframe ScriptRealm provider",
"version": "0.2.2-rc.2",
"publishConfig": {
"access": "public"
},
"repository": {
"type": "git",
"url": "git+https://github.com/deepseek-ai/deepseek-harness.git",
"directory": "packages/client/script-realm-iframe"
},
"type": "module",
"main": "lib/index.js",
"types": "lib/types/index.d.ts",
"exports": {
".": {
"types": "./lib/types/index.d.ts",
"default": "./lib/index.js"
},
"./client": {
"types": "./lib/types/client/index.d.ts",
"default": "./lib/client.js"
},
"./src/*": "./src/*",
"./package.json": "./package.json",
"./locale/*.json": "./locale/*.json"
},
"license": "MIT",
"peerDependencies": {
"@deepseek-ai/cordis": "workspace:~"
},
"devDependencies": {
"@deepseek-ai/cordis": "workspace:~",
"@deepseek-ai/dsh-client-script-realm": "workspace:*"
},
"files": [
"locale/*.json",
"lib/index.js",
"lib/client.js",
"lib/types/**/*.d.ts",
"lib/types/**/*.d.ts.map",
"lib/**/*.js.map",
"src"
],
"dsh": {
"client": {
"platform": "web",
"external": ["@deepseek-ai/dsh-client-script-realm/client"]
}
},
"scripts": {
"bundle": "tsdown",
"watch": "tsdown --watch"
}
}
@@ -0,0 +1,169 @@
/** Same-origin iframe implementation of the direct-reference ScriptRealm interface. */
import {
ScriptRealmError,
type ScriptRealm, type ScriptRealmCreateOptions, type ScriptRealmFactory, type ScriptRealmId, type ScriptRealmScript,
} from '@deepseek-ai/dsh-client-script-realm/client'
/** Page carrier supplying the iframe mount and script URL base. */
export interface IFrameScriptRealmOptions {
readonly document: Document
}
const RESERVED_BINDINGS = new Set(['window', 'document', 'parent', 'top', 'self', 'globalThis', 'location'])
/** An isolated global environment sharing ordinary references with its owning page. */
export class IFrameScriptRealm implements ScriptRealm {
readonly id: ScriptRealmId
private closed = false
private disposal: Promise<void> | undefined
private readonly pending = new Set<() => void>()
private readonly abort: () => void
constructor(
private readonly frame: HTMLIFrameElement,
readonly window: Window,
readonly document: Document,
private readonly pageDocument: Document,
private readonly options: ScriptRealmCreateOptions,
) {
options.signal.throwIfAborted()
this.id = options.id
this.abort = () => { this.close() }
options.signal.addEventListener('abort', this.abort, { once: true })
}
// oxlint-disable-next-line typescript/require-await -- Preserve the asynchronous API's rejection semantics for validation failures.
async expose(bindings: Readonly<Record<string, unknown>>): Promise<void> {
this.assertLive('expose')
try {
const entries = Object.entries(bindings)
for (const [name] of entries) {
if (RESERVED_BINDINGS.has(name) || name in this.window) {
throw new Error(`binding ${JSON.stringify(name)} is reserved or already exists`)
}
}
if (!Object.isExtensible(this.window)) throw new Error('ScriptRealm globals are not extensible')
const descriptors = Object.fromEntries(entries.map(([name, value]) => [name, {
value, enumerable: true, writable: false, configurable: false,
}]))
Object.defineProperties(this.window, descriptors)
} catch (cause) {
throw new ScriptRealmError({ stage: 'expose', realmId: this.id,
message: `script-realms: could not expose bindings in ${JSON.stringify(this.id)}`, cause })
}
}
async execute(script: ScriptRealmScript): Promise<void> {
this.assertLive('execute', script.url)
let url: string
try {
url = new URL(script.url, this.pageDocument.baseURI).href
} catch (cause) {
throw this.executionError(script.url, cause)
}
return new Promise<void>((resolve, reject) => {
const element = this.document.createElement('script')
element.async = true
element.src = url
let settled = false
const finish = (error?: ScriptRealmError): void => {
if (settled) return
settled = true
this.pending.delete(cancel)
element.removeEventListener('load', onLoad)
element.removeEventListener('error', onError)
this.window.removeEventListener('error', onExecutionError)
element.remove()
if (error === undefined) resolve()
else reject(error)
}
const onLoad = (): void => { finish() }
const onError = (event: Event): void => { finish(this.executionError(url, event)) }
const onExecutionError = (event: ErrorEvent): void => {
if (event.filename === url) finish(this.executionError(url, event.error ?? event.message))
}
const cancel = (): void => {
finish(this.executionError(url, this.options.signal.reason ?? new Error('ScriptRealm disposed')))
}
element.addEventListener('load', onLoad, { once: true })
element.addEventListener('error', onError, { once: true })
this.window.addEventListener('error', onExecutionError)
this.pending.add(cancel)
try {
this.document.head.append(element)
} catch (cause) {
finish(this.executionError(url, cause))
}
})
}
dispose(): Promise<void> {
if (this.disposal !== undefined) return this.disposal
try {
this.close()
this.disposal = Promise.resolve()
} catch (cause) {
this.disposal = Promise.reject(new ScriptRealmError({ stage: 'dispose', realmId: this.id,
message: `script-realms: could not dispose ${JSON.stringify(this.id)}`, cause }))
}
return this.disposal
}
private close(): void {
if (this.closed) return
this.closed = true
this.options.signal.removeEventListener('abort', this.abort)
for (const cancel of [...this.pending]) cancel()
this.frame.remove()
}
private assertLive(stage: 'expose' | 'execute', url?: string): void {
if (!this.closed && !this.options.signal.aborted) return
throw new ScriptRealmError({ stage, realmId: this.id,
message: `script-realms: ${JSON.stringify(this.id)} is disposed`,
...(url === undefined ? {} : { url }), cause: this.options.signal.reason })
}
private executionError(url: string, cause: unknown): ScriptRealmError {
return new ScriptRealmError({ stage: 'execute', realmId: this.id, url,
message: `script-realms: could not execute ${JSON.stringify(url)} in ${JSON.stringify(this.id)}`, cause })
}
}
/**
* Capture the provider page without creating an iframe until requested.
* @param options - Owning page document and script URL base.
* @returns Factory creating a ready, named iframe environment.
*/
export function createIFrameScriptRealmFactory(options: IFrameScriptRealmOptions): ScriptRealmFactory<IFrameScriptRealm> {
const pageDocument = options.document
return {
// oxlint-disable-next-line typescript/require-await -- Provider failures are promise rejections even when creation is synchronous.
async create(createOptions) {
let frame: HTMLIFrameElement | undefined
try {
createOptions.signal.throwIfAborted()
frame = pageDocument.createElement('iframe')
frame.hidden = true
frame.tabIndex = -1
frame.setAttribute('aria-hidden', 'true')
frame.name = `realm-iframe-${createOptions.id}`
frame.title = frame.name
frame.dataset.realm = createOptions.id
pageDocument.body.append(frame)
const window = frame.contentWindow
const document = frame.contentDocument
if (window === null || document === null) {
throw new Error('initial iframe document is unavailable')
}
document.title = frame.name
createOptions.signal.throwIfAborted()
return new IFrameScriptRealm(frame, window, document, pageDocument, createOptions)
} catch (cause) {
frame?.remove()
throw new ScriptRealmError({ stage: 'create', realmId: createOptions.id,
message: `script-realms: could not create iframe ${JSON.stringify(createOptions.id)}`, cause })
}
},
}
}
@@ -0,0 +1,16 @@
/** Optional browser provider; registering it does not allocate an iframe. */
import type { Context } from '@deepseek-ai/cordis'
import { createIFrameScriptRealmFactory } from './iframe.ts'
/** Provider plugin identity. */
export const name = 'script-realm-iframe'
/** Provider registry supplied by the kernel Client plugin. */
export const inject = ['scriptRealms']
/**
* Register the iframe implementation using this provider's page document.
* @param ctx - Registry-bearing provider context.
*/
export function apply(ctx: Context): void {
ctx.scriptRealms.register('iframe', createIFrameScriptRealmFactory({ document }))
}
@@ -0,0 +1,4 @@
/** Host entry for the optional browser iframe ScriptRealm provider. */
/** The iframe implementation has no Host-side behavior. */
export function apply(): void {}
@@ -0,0 +1,204 @@
// @vitest-environment jsdom
import { afterEach, expect, it, vi } from 'vitest'
import type { ScriptRealmId } from '@deepseek-ai/dsh-client-script-realm/client'
import { createIFrameScriptRealmFactory, IFrameScriptRealm } from '../src/client/iframe.ts'
const owned: IFrameScriptRealm[] = []
const frames: HTMLIFrameElement[] = []
const failedDisposals = new Set<IFrameScriptRealm>()
afterEach(async () => {
vi.restoreAllMocks()
try {
for (const realm of owned.splice(0)) {
if (failedDisposals.has(realm)) await expect(realm.dispose()).rejects.toMatchObject({ stage: 'dispose' })
else await realm.dispose()
}
} finally {
failedDisposals.clear()
for (const frame of frames.splice(0)) frame.remove()
}
})
async function fixture() {
const controller = new AbortController()
const realm = await createIFrameScriptRealmFactory({ document }).create({ id: 'execution' as ScriptRealmId, signal: controller.signal })
owned.push(realm)
const frame = document.querySelector<HTMLIFrameElement>('iframe[data-realm="execution"]')!
frames.push(frame)
return { realm, controller, frame }
}
function pendingScript(realm: IFrameScriptRealm): HTMLScriptElement {
const script = realm.document.querySelector('script')
if (script === null) throw new Error('script was not appended')
return script
}
it('creates an independent global environment and preserves exposed reference identity', async () => {
const { realm, frame } = await fixture()
expect(frame.hidden).toBe(true)
expect(frame.tabIndex).toBe(-1)
expect(frame.getAttribute('aria-hidden')).toBe('true')
expect(realm.window).not.toBe(window)
expect(realm.document).not.toBe(document)
expect(Reflect.get(realm.window, 'Array')).not.toBe(Array)
expect(realm.document.title).toBe('realm-iframe-execution')
const shared = { marker: 1 }
await realm.expose({ shared })
expect(Reflect.get(realm.window, 'shared')).toBe(shared)
expect(Object.getOwnPropertyDescriptor(realm.window, 'shared')).toMatchObject({ writable: false, configurable: false })
await expect(realm.expose({ another: 1, shared })).rejects.toMatchObject({ stage: 'expose', realmId: realm.id })
expect(Reflect.has(realm.window, 'another')).toBe(false)
await expect(realm.expose({ document })).rejects.toMatchObject({ stage: 'expose' })
})
it('reports a host that prevents exposing additional globals', async () => {
const { realm } = await fixture()
const isExtensible = Object.isExtensible
vi.spyOn(Object, 'isExtensible').mockImplementation(value => value === realm.window ? false : isExtensible(value))
await expect(realm.expose({ shared: 1 })).rejects.toMatchObject({ stage: 'expose', cause: { message: 'ScriptRealm globals are not extensible' } })
expect(Reflect.has(realm.window, 'shared')).toBe(false)
})
it('settles loading only on its script event and removes the carrier element', async () => {
const { realm } = await fixture()
const task = realm.execute({ url: '/plugin.js' })
const script = pendingScript(realm)
const expected = new URL('/plugin.js', document.baseURI).href
expect(script.src).toBe(expected)
expect(script.async).toBe(true)
let finished = false
void task.then(() => { finished = true })
realm.window.dispatchEvent(new ErrorEvent('error', { filename: 'https://unrelated.invalid/other.js', message: 'unrelated' }))
await Promise.resolve()
expect(finished).toBe(false)
script.dispatchEvent(new Event('load'))
await task
expect(finished).toBe(true)
expect(script.isConnected).toBe(false)
expect(realm.document.querySelector('script')).toBeNull()
})
it('rejects a failed script fetch and removes its load listeners', async () => {
const { realm } = await fixture()
const task = realm.execute({ url: '/missing.js' })
const failure = expect(task).rejects.toMatchObject({ stage: 'execute', url: new URL('/missing.js', document.baseURI).href })
const script = pendingScript(realm)
script.dispatchEvent(new Event('error'))
await failure
expect(script.isConnected).toBe(false)
script.dispatchEvent(new Event('load'))
await realm.dispose()
})
it.each([true, false])('reports matching execution errors with an error object: %s', async (withError) => {
const { realm } = await fixture()
const task = realm.execute({ url: '/throws.js' })
const cause = new Error('script execution failed')
const failure = expect(task).rejects.toMatchObject({ stage: 'execute', cause: withError ? cause : 'script execution failed' })
const script = pendingScript(realm)
realm.window.dispatchEvent(new ErrorEvent('error', { filename: script.src, message: cause.message, ...(withError ? { error: cause } : {}) }))
await failure
expect(script.isConnected).toBe(false)
})
it('reports an invalid script address before creating a carrier element', async () => {
const { realm } = await fixture()
await expect(realm.execute({ url: 'http://[' })).rejects.toMatchObject({ stage: 'execute', url: 'http://[' })
expect(realm.document.querySelector('script')).toBeNull()
})
it('cleans script listeners when the host refuses script insertion', async () => {
const { realm } = await fixture()
const failure = new Error('script insertion refused')
vi.spyOn(realm.document.head, 'append').mockImplementation(() => { throw failure })
await expect(realm.execute({ url: '/blocked.js' })).rejects.toMatchObject({ stage: 'execute', cause: failure })
expect(realm.document.querySelector('script')).toBeNull()
await realm.dispose()
})
it.each(['abort', 'dispose'] as const)('cancels pending execution on %s and does not accept more work', async (action) => {
const { realm, controller, frame } = await fixture()
const first = realm.execute({ url: '/first.js' })
const firstScript = pendingScript(realm)
const second = realm.execute({ url: '/second.js' })
const error = new Error('caller cancelled')
const firstFailure = expect(first).rejects.toMatchObject({ stage: 'execute', cause: action === 'abort' ? error : { message: 'ScriptRealm disposed' } })
const secondFailure = expect(second).rejects.toMatchObject({ stage: 'execute' })
if (action === 'abort') controller.abort(error)
else await realm.dispose()
await Promise.all([firstFailure, secondFailure])
expect(frame.isConnected).toBe(false)
expect(firstScript.isConnected).toBe(false)
firstScript.dispatchEvent(new Event('load'))
await expect(realm.expose({ late: 1 })).rejects.toMatchObject({ stage: 'expose' })
await expect(realm.execute({ url: '/late.js' })).rejects.toMatchObject({ stage: 'execute', url: '/late.js' })
const disposal = realm.dispose()
expect(realm.dispose()).toBe(disposal)
await disposal
})
it('retains a disposal error while stopping pending work', async () => {
const { realm, frame } = await fixture()
const failure = new Error('frame removal refused')
vi.spyOn(frame, 'remove').mockImplementation(() => { throw failure })
failedDisposals.add(realm)
const task = realm.dispose()
await expect(task).rejects.toMatchObject({ stage: 'dispose', cause: failure })
expect(realm.dispose()).toBe(task)
await expect(realm.execute({ url: '/late.js' })).rejects.toMatchObject({ stage: 'execute' })
})
it('does not allocate an iframe for an already-aborted creation', async () => {
const controller = new AbortController()
const failure = new Error('cancel before allocation')
controller.abort(failure)
const create = vi.spyOn(document, 'createElement')
await expect(createIFrameScriptRealmFactory({ document }).create({ id: 'cancelled' as ScriptRealmId, signal: controller.signal })).rejects.toMatchObject({ stage: 'create', cause: failure })
expect(create).not.toHaveBeenCalled()
})
it.each(['window', 'document', 'cancel'] as const)('removes the partially created frame when readiness fails: %s', async (failure) => {
const controller = new AbortController()
const append = document.body.append.bind(document.body)
let created: HTMLIFrameElement | undefined
vi.spyOn(document.body, 'append').mockImplementation((...nodes) => {
append(...nodes)
const frame = nodes[0]
if (!(frame instanceof HTMLIFrameElement)) throw new Error('expected iframe')
created = frame
frames.push(frame)
if (failure === 'cancel') controller.abort(new Error('cancel during readiness'))
else vi.spyOn(frame, failure === 'window' ? 'contentWindow' : 'contentDocument', 'get').mockReturnValue(null)
})
await expect(createIFrameScriptRealmFactory({ document }).create({ id: 'not-ready' as ScriptRealmId, signal: controller.signal })).rejects.toMatchObject({ stage: 'create' })
expect(created).toBeDefined()
expect(created!.isConnected).toBe(false)
})
it('rejects direct construction after caller cancellation', () => {
const controller = new AbortController()
controller.abort(new Error('cancelled'))
const frame = document.createElement('iframe')
frames.push(frame)
document.body.append(frame)
expect(() => new IFrameScriptRealm(frame, frame.contentWindow!, frame.contentDocument!, document,
{ id: 'cancelled' as ScriptRealmId, signal: controller.signal })).toThrow('cancelled')
})
it('retains a completed load if the inserting carrier subsequently throws', async () => {
const { realm } = await fixture()
const append = realm.document.head.append.bind(realm.document.head)
vi.spyOn(realm.document.head, 'append').mockImplementation((...nodes) => {
append(...nodes)
const script = nodes[0]
if (typeof script === 'string' || script === undefined) throw new Error('expected script node')
script.dispatchEvent(new Event('load'))
throw new Error('carrier threw after completing the load')
})
await expect(realm.execute({ url: '/completed.js' })).resolves.toBeUndefined()
expect(realm.document.querySelector('script')).toBeNull()
await realm.dispose()
})
@@ -0,0 +1,33 @@
// @vitest-environment jsdom
import { Context } from '@deepseek-ai/cordis'
import { expect, it } from 'vitest'
import ScriptRealmRegistry, { type ScriptRealmId } from '@deepseek-ai/dsh-client-script-realm/client'
import * as IFrame from '../src/client/index.ts'
import { apply as hostApply } from '../src/index.ts'
it('registers the optional provider without allocating a frame and keeps instances caller-owned', async () => {
expect(() => { hostApply() }).not.toThrow()
const ctx = new Context()
await ctx.plugin(ScriptRealmRegistry).await()
const provider = ctx.plugin(IFrame)
await provider.await()
expect(document.querySelector('iframe[data-realm]')).toBeNull()
const controller = new AbortController()
const realm = await ctx.get('scriptRealms')!.create('iframe', { id: 'optional' as ScriptRealmId, signal: controller.signal })
try {
const frame = document.querySelector<HTMLIFrameElement>('iframe[data-realm="optional"]')!
expect(frame).not.toBeNull()
const shared = { marker: true }
await realm.expose({ __sharedRealmProbe: shared })
expect(Reflect.get(frame.contentWindow!, '__sharedRealmProbe')).toBe(shared)
await provider.dispose()
expect(frame.isConnected).toBe(true)
await expect(ctx.get('scriptRealms')!.create('iframe', { id: realm.id, signal: controller.signal })).rejects.toThrow('not registered')
await realm.dispose()
expect(frame.isConnected).toBe(false)
} finally {
controller.abort()
await realm.dispose()
await ctx.fiber.dispose()
}
})
@@ -0,0 +1,18 @@
{
"extends": "../../../tsconfig.base.client.json",
"compilerOptions": {
"rootDir": "src",
"outDir": "lib/types"
},
"include": [
"src"
],
"references": [
{
"path": "../../../vendor/cordis"
},
{
"path": "../script-realm"
}
]
}
@@ -0,0 +1,3 @@
import { clientBundle } from '../tsdown.client.ts'
export default clientBundle(import.meta.dirname, ['lib/types/index.js'])
@@ -0,0 +1,37 @@
# Bilingual-pair consistency record for README.md (docs/i18n/README.md): per heading
# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
# After editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write packages/client/script-realm/README.md
/:
en: 4eced660e4d69854
zh: cad086b985cadcf9
/deepseek-ai-dsh-client-script-realm:
en: a9339a964382ce06
zh: c6f792d2275c56cb
/deepseek-ai-dsh-client-script-realm/summary:
en: 69e4223146739d2f
zh: 823c8887f603eaca
/deepseek-ai-dsh-client-script-realm/table-of-contents:
en: 23386452a66b2fbd
zh: dc8dd4f5941b9f74
/deepseek-ai-dsh-client-script-realm/use-this-package:
en: 8fca85c2eed966ca
zh: c9c3df51a8d61d29
/deepseek-ai-dsh-client-script-realm/understand-the-implementation:
en: ef5a1eabb8d274e2
zh: 1ef625ab08552773
/deepseek-ai-dsh-client-script-realm/further-exploration:
en: f0659a0a6d6e9876
zh: 66d902d62dd6cd0e
/deepseek-ai-dsh-client-script-realm/model-experience:
en: 91701b5ed41296fe
zh: caf84df42b9f91a8
/deepseek-ai-dsh-client-script-realm/model-experience/kv-cache-effect:
en: ca75c51c89c2c9b0
zh: f57cc48a1b5cbfa9
/deepseek-ai-dsh-client-script-realm/known-limitations-and-deferred-work:
en: 7070fdaeccbc6fcf
zh: 1b18d96a6f426193
/deepseek-ai-dsh-client-script-realm/known-limitations-and-deferred-work/dev-note:
en: 0a1253c6f7b5e8b9
zh: 9f56528562c7c914
+58
View File
@@ -0,0 +1,58 @@
---
description: "Register optional script-environment providers and create caller-owned Realm instances."
kind: "package-reference"
---
# @deepseek-ai/dsh-client-script-realm
English | [中文](README.zh.md)
## Summary
Use this package when an optional Client extension needs a named script-environment provider. Registration does not create an environment; creation returns an instance whose caller owns cleanup. Normal application startup does not wait for this registry. The module loader has its own Main execution environment.
## Table of Contents
- [Use this package](#use-this-package)
- [Understand the implementation](#understand-the-implementation)
- [Further Exploration](#further-exploration)
- [Model Experience](#model-experience)
- [Known Limitations and Deferred Work](#known-limitations-and-deferred-work)
- [Dev Note](#dev-note)
<a id="use-this-package"></a>
## Use this package
The normal Client plugin provides `ctx.scriptRealms`. Provider plugins inject `scriptRealms` and register factories through its effect-owned `register()` operation. The returned disposer is asynchronous; callers that remove a registration early await it, while plugin teardown owns automatic removal. This package declares no configuration and is not included in the default application roster.
<a id="understand-the-implementation"></a>
## Understand the implementation
`create()` resolves a registered provider by name and passes the caller-supplied identity and cancellation signal to it. Removing a provider prevents subsequent creation through that registration; it does not dispose instances already returned. The registry does not assign modules to environments.
<a id="further-exploration"></a>
## Further Exploration
- [Client modules](../modules/README.md)
- [Web client architecture](../../../docs/subsystems/web-client.md)
- [Client entry](src/client/index.ts)
<a id="model-experience"></a>
## Model Experience
None, as this optional browser infrastructure registers no model-facing tools or prompts.
#### KV Cache effect
None; this package neither assembles nor sends a provider request.
## Known Limitations and Deferred Work
<a id="known-limitations-and-deferred-work"></a>
- Isolation requests, capability matching, environment reuse, and plugin placement are not implemented. A Script Realm preserves direct references and is not a security sandbox.
<a id="dev-note"></a>
### Dev Note
None.
+58
View File
@@ -0,0 +1,58 @@
---
description: "注册可选脚本环境提供方,并创建由调用者持有的 Realm 实例。"
kind: "package-reference"
---
# @deepseek-ai/dsh-client-script-realm
[English](README.md) | 中文
## 概述
当可选 Client 扩展需要具名脚本环境提供方时使用本包。注册不会创建环境;创建返回由调用者负责清理的实例。普通应用启动不等待此注册表,模块加载器拥有自己的 Main 执行环境。
## 目录
- [使用本包](#use-this-package)
- [理解实现](#understand-the-implementation)
- [进一步探索](#further-exploration)
- [模型体验](#model-experience)
- [已知限制与延期工作](#known-limitations-and-deferred-work)
- [开发备注](#dev-note)
<a id="use-this-package"></a>
## 使用本包
普通 Client 插件提供 `ctx.scriptRealms`。提供方插件注入 `scriptRealms`,通过绑定 effect 生命周期的 `register()` 操作登记工厂。返回的 disposer 是异步的;提前移除注册的调用者需等待它完成,插件退出则负责自动移除。本包不声明配置,也不加入默认应用名册。
<a id="understand-the-implementation"></a>
## 理解实现
`create()` 按名称解析已注册提供方,并传入调用者提供的身份与取消信号。移除提供方后不能通过该注册继续创建实例,但不会销毁已经返回的实例。注册表不负责给模块分配环境。
<a id="further-exploration"></a>
## 进一步探索
- [Client 模块](../modules/README.zh.md)
- [Web 客户端架构](../../../docs/subsystems/web-client.zh.md)
- [Client 入口](src/client/index.ts)
<a id="model-experience"></a>
## 模型体验
无;本包是可选的浏览器基础设施,不注册面向模型的工具或提示词。
#### KV Cache 影响
无;本包既不组装也不发送提供方请求。
## 已知限制与延期工作
<a id="known-limitations-and-deferred-work"></a>
- 隔离请求、能力匹配、环境复用与插件放置尚未实现。Script Realm 保留直接引用,不是安全沙箱。
<a id="dev-note"></a>
### 开发备注
无。
@@ -0,0 +1,5 @@
{
"meta": {
"title": "Skriptumgebungen"
}
}
@@ -0,0 +1,5 @@
{
"meta": {
"title": "Script realms"
}
}
@@ -0,0 +1,5 @@
{
"meta": {
"title": "Entornos de scripts"
}
}
@@ -0,0 +1,5 @@
{
"meta": {
"title": "Environnements de scripts"
}
}
@@ -0,0 +1,5 @@
{
"meta": {
"title": "スクリプト Realm"
}
}
@@ -0,0 +1,5 @@
{
"meta": {
"title": "Ambientes de scripts"
}
}
@@ -0,0 +1,5 @@
{
"meta": {
"title": "Среды скриптов"
}
}
@@ -0,0 +1,5 @@
{
"meta": {
"title": "脚本运行域"
}
}
+55
View File
@@ -0,0 +1,55 @@
{
"name": "@deepseek-ai/dsh-client-script-realm",
"description": "Direct-reference script environments and Cordis-owned provider registration",
"version": "0.2.2-rc.2",
"publishConfig": {
"access": "public"
},
"repository": {
"type": "git",
"url": "git+https://github.com/deepseek-ai/deepseek-harness.git",
"directory": "packages/client/script-realm"
},
"type": "module",
"main": "lib/index.js",
"types": "lib/types/index.d.ts",
"exports": {
".": {
"types": "./lib/types/index.d.ts",
"default": "./lib/index.js"
},
"./src/*": "./src/*",
"./package.json": "./package.json",
"./locale/*.json": "./locale/*.json",
"./client": {
"types": "./lib/types/client/index.d.ts",
"default": "./lib/client.js"
}
},
"license": "MIT",
"peerDependencies": {
"@deepseek-ai/cordis": "workspace:~"
},
"devDependencies": {
"@deepseek-ai/cordis": "workspace:~",
"@deepseek-ai/dsh-brand": "workspace:*"
},
"files": [
"locale/*.json",
"lib/index.js",
"lib/client.js",
"lib/types/**/*.d.ts",
"lib/types/**/*.d.ts.map",
"lib/**/*.js.map",
"src"
],
"dsh": {
"client": {
"platform": "web"
}
},
"scripts": {
"bundle": "tsdown",
"watch": "tsdown --watch"
}
}
@@ -0,0 +1,80 @@
/** Cordis-owned script-environment providers, independent from module placement. */
import { Service } from '@deepseek-ai/cordis'
import type { Context } from '@deepseek-ai/cordis'
import type { ScriptRealm, ScriptRealmCreateOptions, ScriptRealmFactory, ScriptRealmId } from './types.ts'
export type { ScriptRealm, ScriptRealmCreateOptions, ScriptRealmFactory, ScriptRealmId, ScriptRealmScript } from './types.ts'
/** Failure of one execution-environment operation. */
export class ScriptRealmError extends Error {
/** Realm operation that failed. */
readonly stage: 'create' | 'expose' | 'execute' | 'dispose'
/** Environment in which the operation failed. */
readonly realmId: ScriptRealmId
/** Requested script URL when the failure concerns script execution. */
readonly url?: string
constructor(options: {
readonly stage: ScriptRealmError['stage']
readonly realmId: ScriptRealmId
readonly message: string
readonly url?: string
readonly cause?: unknown
}) {
super(options.message, { cause: options.cause })
this.name = 'ScriptRealmError'
this.stage = options.stage
this.realmId = options.realmId
if (options.url !== undefined) this.url = options.url
}
}
declare module '@deepseek-ai/cordis' {
interface Context {
/** Registered execution-environment providers; instances belong to their creators. */
scriptRealms: ScriptRealmRegistry
}
}
/** Registers provider factories through their calling plugin's effect lifetime. */
export class ScriptRealmRegistry extends Service {
private readonly factories = new Map<string, ScriptRealmFactory>()
constructor(ctx: Context) {
super(ctx, 'scriptRealms')
}
/**
* Register one provider without creating any environment.
* @param name - Exact provider name.
* @param factory - Environment factory retained until the registration is disposed.
* @returns The caller-owned registration disposer; duplicate names reject.
*/
register(name: string, factory: ScriptRealmFactory): () => Promise<void> {
return this.ctx.effect(() => {
if (this.factories.has(name)) throw new Error(`script-realms: provider ${JSON.stringify(name)} is already registered`)
this.factories.set(name, factory)
return () => {
this.factories.delete(name)
}
}, `scriptRealms.register(${JSON.stringify(name)})`)
}
/**
* Create an environment through an already registered provider.
* @param name - Exact provider name.
* @param options - Instance identity and cancellation; the caller owns the returned instance.
* @returns The provider's ready environment; unknown providers reject.
*/
async create(name: string, options: ScriptRealmCreateOptions): Promise<ScriptRealm> {
const factory = this.factories.get(name)
if (factory === undefined) {
throw new ScriptRealmError({ stage: 'create', realmId: options.id,
message: `script-realms: provider ${JSON.stringify(name)} is not registered` })
}
options.signal.throwIfAborted()
return await factory.create(options)
}
}
export default ScriptRealmRegistry
@@ -0,0 +1,48 @@
/** Direct-reference script execution contracts, independent from module loading. */
import type { Branded } from '@deepseek-ai/dsh-brand'
/** Identity assigned by the owner of one execution environment. */
export type ScriptRealmId = Branded<'ScriptRealmId'>
/** External classic script to load in an execution environment. */
export interface ScriptRealmScript {
readonly url: string
}
/** An environment preserving shared object references and synchronous function calls. */
export interface ScriptRealm {
readonly id: ScriptRealmId
/**
* Expose named values without cloning them or replacing different existing bindings.
* @param bindings - Global names and their shared values.
* @returns After the bindings are installed; incompatible names reject before installation.
*/
expose(bindings: Readonly<Record<string, unknown>>): Promise<void>
/**
* Execute an external classic script in this environment.
* @param script - Script URL.
* @returns After script loading; failure or environment disposal rejects.
*/
execute(script: ScriptRealmScript): Promise<void>
/**
* Release environment-owned resources without revoking references already handed out.
* @returns After cleanup; repeated calls share the same result.
*/
dispose(): Promise<void>
}
/** Instance identity and lifetime cancellation supplied by the creating owner. */
export interface ScriptRealmCreateOptions {
readonly id: ScriptRealmId
readonly signal: AbortSignal
}
/** Provider that creates a ready environment and cleans partial creation on failure. */
export interface ScriptRealmFactory<R extends ScriptRealm = ScriptRealm> {
/**
* Create an execution environment; the caller owns its disposal.
* @param options - Instance identity and lifetime cancellation.
* @returns A ready environment.
*/
create(options: ScriptRealmCreateOptions): Promise<R>
}
@@ -0,0 +1,2 @@
/** Host entry; execution environments are provided by the Client plugin. */
export function apply(): void {}
@@ -0,0 +1,80 @@
// @vitest-environment jsdom
import { Context } from '@deepseek-ai/cordis'
import { expect, it, vi } from 'vitest'
import ScriptRealmRegistry, { ScriptRealmError, type ScriptRealm, type ScriptRealmId } from '../src/client/index.ts'
import { apply as hostApply } from '../src/index.ts'
it('keeps the Host entry inert and registers factories for their plugin lifetime', async () => {
expect(() => { hostApply() }).not.toThrow()
const ctx = new Context()
const registry = ctx.plugin(ScriptRealmRegistry)
await registry.await()
const realm: ScriptRealm = { id: 'test' as ScriptRealmId, expose: async () => {}, execute: async () => {}, dispose: async () => {} }
const create = vi.fn(async () => realm)
const provider = ctx.plugin({ inject: ['scriptRealms'], apply(owner: Context) { owner.scriptRealms.register('test', { create }) } })
try {
await provider.await()
expect(create).not.toHaveBeenCalled()
expect(await ctx.get('scriptRealms')!.create('test', { id: realm.id, signal: new AbortController().signal })).toBe(realm)
await provider.dispose()
await expect(ctx.get('scriptRealms')!.create('test', { id: realm.id, signal: new AbortController().signal })).rejects.toThrow('not registered')
} finally {
await ctx.fiber.dispose()
}
})
it('does not call a provider for an already cancelled creation', async () => {
const ctx = new Context()
const registry = ctx.plugin(ScriptRealmRegistry)
await registry.await()
const create = vi.fn()
const off = ctx.get('scriptRealms')!.register('cancelled', { create })
const controller = new AbortController()
controller.abort(new Error('cancelled'))
try {
await expect(ctx.get('scriptRealms')!.create('cancelled', { id: 'test' as ScriptRealmId, signal: controller.signal })).rejects.toThrow('cancelled')
expect(create).not.toHaveBeenCalled()
} finally {
await off()
await ctx.fiber.dispose()
}
})
it('rejects duplicate registrations without replacing the original provider', async () => {
const ctx = new Context()
await ctx.plugin(ScriptRealmRegistry).await()
const registry = ctx.get('scriptRealms')!
const failure = new Error('provider failed')
const first = vi.fn(() => Promise.reject(failure))
const replacement = vi.fn()
const stop = registry.register('unique', { create: first })
try {
expect(() => registry.register('unique', { create: replacement })).toThrow('already registered')
await expect(registry.create('unique', { id: 'failed' as ScriptRealmId, signal: new AbortController().signal })).rejects.toBe(failure)
expect(first).toHaveBeenCalledOnce()
expect(replacement).not.toHaveBeenCalled()
await stop()
await stop()
const absent = registry.create('unique', { id: 'missing' as ScriptRealmId, signal: new AbortController().signal })
await expect(absent).rejects.toMatchObject({ name: 'ScriptRealmError', stage: 'create', realmId: 'missing' })
const realm: ScriptRealm = { id: 'replacement' as ScriptRealmId, expose: async () => {}, execute: async () => {}, dispose: async () => {} }
const next = vi.fn(async () => realm)
registry.register('unique', { create: next })
await stop()
await expect(registry.create('unique', { id: realm.id, signal: new AbortController().signal })).resolves.toBe(realm)
expect(next).toHaveBeenCalledOnce()
} finally {
await ctx.fiber.dispose()
}
})
it('keeps the failed operation and optional script URL on realm errors', () => {
const cause = new Error('network unavailable')
const error = new ScriptRealmError({ stage: 'execute', realmId: 'resource' as ScriptRealmId,
message: 'script failed', url: '/plugin.js', cause })
expect(error).toMatchObject({ name: 'ScriptRealmError', stage: 'execute', realmId: 'resource',
message: 'script failed', url: '/plugin.js', cause })
const create = new ScriptRealmError({ stage: 'create', realmId: 'resource' as ScriptRealmId, message: 'creation failed' })
expect(create.url).toBeUndefined()
})
@@ -0,0 +1,18 @@
{
"extends": "../../../tsconfig.base.client.json",
"compilerOptions": {
"rootDir": "src",
"outDir": "lib/types"
},
"include": [
"src"
],
"references": [
{
"path": "../../../vendor/cordis"
},
{
"path": "../../util/brand"
}
]
}
@@ -0,0 +1,3 @@
import { clientBundle } from '../tsdown.client.ts'
export default clientBundle(import.meta.dirname, ['lib/types/index.js'])
+278 -73
View File
@@ -1,11 +1,11 @@
/**
* Shared tsdown preset for UI plugin client bundles. Emits a closure-factory
* artifact: the bundle calls window.__ModuleLoader__.load({id, factory})
* artifact: the bundle calls window.__ModuleLoader__.load({id, factory, meta})
* and resolves externals through the injected require (loader module table —
* cordis DI entities, no globals, no import map). CSS is compiled by
* lightningcss inside the bundle: `x.module.css` yields its hashed class map
* and injects a tagged style at factory execution, while `x.css?inline`
* exports compiled text for a plugin-owned lifecycle effect. The virtual
* while each output chunk exposes deferred stylesheet text through its metadata
* factory. `x.css?inline` exports compiled text without registering a resource. The virtual
* loaders register each real stylesheet as a watch dependency. Images under
* `src/client/assets/`, imported from Client code or referenced by relative
* `url()` in the package's own stylesheets, are emitted under `lib/assets/`
@@ -35,7 +35,7 @@ import {
packageAssetRevisionedPath,
} from './modules/src/assets.ts'
import { optionalStringArray } from './modules/src/client/manifest.ts'
import { PLATFORM_MODULES, PRELOADED_CLIENT_EXTERNALS } from './web/src/platform.ts'
import { PLATFORM_MODULES, PRELOADED_CLIENT_EXTERNALS, STATIC_MODULE_MANIFEST_EXPORT } from './web/src/platform.ts'
import { clientBuildEnvironmentDefines, clientBuildValueDefines } from '../../scripts/client-build-environment.ts'
import { isExperimentalPackageName } from '../../scripts/experimental-package-policy.ts'
import { BundleInputIsolation, physicalBundleInput } from '../../scripts/bundle-input-isolation.ts'
@@ -51,29 +51,42 @@ const INLINE_CSS_VIRTUAL_PREFIX = '\0dsh-inline-css:'
const CSS_VIRTUAL_SUFFIX = '.mjs'
const INLINE_CSS_QUERY = '?inline'
/** Compiled stylesheet expression retained until its resource's text function runs. */
interface CompiledClientStyle {
/** Stylesheet path within the importing package, the key of its metadata record. */
readonly path: string
readonly expression: string
}
/**
* Emit one plugin-owned style injector and an optional CSS Modules export.
* @param css - JavaScript expression yielding the stylesheet text; see {@link stylesheetSource}.
* Name a compiled stylesheet by its path within the importing package: the package's own files by their
* `src`-relative path, and a dependency's file as `node_modules/<package>/<path>`.
* @param id - Importing package, used in diagnostics.
* @param packageDir - Importing package directory.
* @param fileId - Physical stylesheet path.
* @param expression - Compiled stylesheet text expression.
* @returns The stylesheet's metadata key and expression.
*/
function styleInjectionModule(
function compiledClientStyle(
id: string,
packageDir: string,
fileId: string,
css: string,
classMap?: Readonly<Record<string, string>>,
): string {
const source = [
`const css = ${css};`,
`const tagId = ${JSON.stringify(`${id}/${basename(fileId)}`)};`,
'if (typeof document !== \'undefined\' && document.querySelector(\'style[data-plugin-css=\' + JSON.stringify(tagId) + \']\') === null) {',
' const tag = document.createElement(\'style\');',
` tag.dataset.plugin = ${JSON.stringify(id)};`,
' tag.dataset.pluginCss = tagId;',
' tag.textContent = css;',
' document.head.appendChild(tag);',
'}',
]
source.push(classMap === undefined ? 'export {};' : `export default ${JSON.stringify(classMap)};`)
return source.join('\n')
expression: string,
): CompiledClientStyle {
const path = relative(packageDir, fileId).split(sep).join('/').replace(/^lib\/types\//, 'src/')
if (!path.startsWith('../')) return { path, expression }
let directory = dirname(fileId)
while (dirname(directory) !== directory) {
const manifestPath = join(directory, 'package.json')
if (existsSync(manifestPath)) {
const manifest = JSON.parse(readFileSync(manifestPath, 'utf8')) as { name?: string }
if (typeof manifest.name === 'string') {
return { path: `node_modules/${manifest.name}/${relative(directory, fileId).split(sep).join('/')}`, expression }
}
}
directory = dirname(directory)
}
throw new Error(`tsdown: ${id}: stylesheet ${fileId} has no package owner`)
}
/**
@@ -154,44 +167,37 @@ export function clientBundle(
}
/**
* Build the tsdown config for a client library the compile shell links
* statically (the static assembly channel: `apps/web` resolves the package
* name, bundles the artifact, and owns the chunk layout and the CSS pipeline).
*
* Calling this preset is what puts a package in the static assembly channel,
* so the call sites are the roster: gates read it through
* {@link isStaticLinkedConfig} rather than a second hand-kept list. A package on
* this roster must not be a module-table row as well — the browser would take
* the statically linked copy and a provider's bytes would sit unused in its
* bundle.
*
* Four artifact contracts:
* 1. every bare specifier stays an import. The shell attributes chunk bytes by
* `node_modules/<pkg>`, so a dependency inlined into a workspace file is
* attributed to no npm package and its bytes fall into the index chunk,
* which collapses the vendor/index cache split.
* 2. `esm` on `platform: 'browser'` — the shell is the only consumer.
* 3. sourcemaps, chained through the tsc maps under `lib/types` to the sources.
* 4. stylesheets ship with the package: a relative `.css` import survives as a
* relative external and the sheet is emitted under `lib/` at its
* `src`-relative path, so vite stays the only owner of class hashing.
* @param packageDir - the package's own directory, normally the config's
* `import.meta.dirname`; its `package.json` name is used in tsdown diagnostics.
* @param libEntry - emitted JavaScript entries consumed from `lib/types`, one
* bundle each: a multi-entry build would emit a hash-named shared chunk that
* the exact `files` list cannot publish.
* @returns ENV-selected tsdown config for the Client build face.
* @throws {Error} when `<packageDir>/package.json` is unreadable or declares no name.
* Build one statically delivered Client module as an ESM manifest in `lib/index.js`.
* Shared workspace dependencies resolve through the module loader; third-party
* imports remain ESM dependencies of the final shell build.
* @param packageDir - Package directory containing the module's package.json.
* @param libEntry - Single emitted index entry consumed from `lib/types`.
* @returns ENV-selected config for the Client build face.
* @throws {Error} when the package manifest or index entry is invalid.
*/
export function staticLinked(packageDir: string, libEntry: readonly string[]): BuildFaceConfig {
const id = readPackageManifest(packageDir).name
// Each entry names its own output file, so two entries with the same basename
// would overwrite one artifact instead of emitting two.
const manifest = readPackageManifest(packageDir)
const entry = libEntry[0]
if (libEntry.length !== 1 || entry === undefined || basename(entry, '.js') !== 'index') {
throw new Error(`tsdown: ${manifest.name} staticLinked requires one index entry`)
}
return clientOnly([staticManifestConfig(manifest.name, packageDir, entry)])
}
/**
* Build native ESM bootstrap entries whose CSS loads before the module renderer.
* Bare imports remain available for the final shell bundle to resolve.
* @param packageDir - Package directory containing the shell's package.json.
* @param libEntry - Emitted JavaScript entries, each with a distinct output basename.
* @returns ENV-selected configs for the Client build face.
*/
export function clientShell(packageDir: string, libEntry: readonly string[]): BuildFaceConfig {
const { name } = readPackageManifest(packageDir)
const names = new Set(libEntry.map(entry => basename(entry, '.js')))
if (names.size !== libEntry.length) {
throw new Error(`tsdown: ${id} entries collide on an output name: ${libEntry.join(', ')}`)
throw new Error(`tsdown: ${name} entries collide on an output name: ${libEntry.join(', ')}`)
}
return clientOnly(libEntry.map(entry => staticLinkedConfig(id, entry)))
return clientOnly(libEntry.map(entry => staticLinkedConfig(name, entry)))
}
/**
@@ -199,7 +205,7 @@ export function staticLinked(packageDir: string, libEntry: readonly string[]): B
* The roster has no separate list: gates load each package's own
* `tsdown.config.ts`, call it for the Client face, and ask this.
* @param configs - configs a package's build-face function returned.
* @returns true when at least one config was built by {@link staticLinked}.
* @returns true when at least one config belongs to static module or shell assembly.
*/
export function isStaticLinkedConfig(configs: readonly UserConfig[]): boolean {
return configs.some(config => (config.plugins as readonly { name?: string }[] | undefined ?? [])
@@ -303,7 +309,9 @@ interface AssetContext extends AssetEmitter {
addWatchFile(id: string): void
}
function staticLinkedConfig(id: string, entry: string, outputName = basename(entry, '.js')): UserConfig {
function staticLinkedConfig(
id: string, entry: string, outputName = basename(entry, '.js'),
): UserConfig {
const emitted = new Set<string>()
const isolation = clientInputIsolation(id)
return {
@@ -326,10 +334,9 @@ function staticLinkedConfig(id: string, entry: string, outputName = basename(ent
sourcemapPathTransform: isolation.sourcePath,
},
plugins: [{
// Contract 1. `pre` because tsdown's own deps plugin would otherwise
// resolve and inline every specifier missing from the npm production
// sections, which is the coupling this preset exists to remove. The name
// is also the roster marker {@link isStaticLinkedConfig} reads.
// Resolve before tsdown's dependency plugin so the shell retains bare
// imports independently of npm dependency sections. The name also marks
// this config for the static assembly roster.
name: STATIC_LINKED_PLUGIN,
resolveId: {
order: 'pre' as const,
@@ -340,8 +347,7 @@ function staticLinkedConfig(id: string, entry: string, outputName = basename(ent
},
},
}, tscSourceMapPlugin(), isolation.plugin, {
// Contract 4. The import survives verbatim and the sheet lands beside the
// JavaScript, so the shell's CSS Modules pipeline sees a real stylesheet.
// Preserve stylesheet imports for the shell's final CSS build.
name: 'dsh-css-asset',
async resolveId(this: AssetEmitter, source: string, importer: string | undefined) {
if (!source.endsWith('.css') || importer === undefined) return null
@@ -360,6 +366,169 @@ function staticLinkedConfig(id: string, entry: string, outputName = basename(ent
}
}
/**
* An ordinary ESM library with one more export, the {@link STATIC_MODULE_MANIFEST_EXPORT} manifest. Every import stays
* for the shell build, including third-party stylesheets; one that names a module-table entry also leaves a `require`
* call in the manifest factory, as in a dynamic bundle, so Modules records the dependency. The package's own CSS
* imports become the manifest's deferred stylesheet metadata instead of installing styles.
*/
function staticManifestConfig(id: string, packageDir: string, entry: string): UserConfig {
const config = staticLinkedConfig(id, entry, 'index')
const styles = new Map<string, CompiledClientStyle>()
const imports = new Map<string, string>()
const emitted = new Set<string>()
const sourceRoot = realDirectory(resolvePath(packageDir, 'src'))
const resource = (context: AssetContext, file: string): string => {
const real = realpathSync(file)
context.addWatchFile(real)
const local = pathBelow(sourceRoot, real)
if (local !== undefined) {
const name = local.split(sep).join('/')
if (!emitted.has(name)) {
emitted.add(name)
context.emitFile({ type: 'asset', fileName: name, source: readFileSync(real), originalFileName: real })
}
return `new URL(${JSON.stringify(`./${name}`)}, import.meta.url).href`
}
let directory = dirname(real)
while (dirname(directory) !== directory) {
const manifestPath = join(directory, 'package.json')
if (existsSync(manifestPath)) {
const owner = JSON.parse(readFileSync(manifestPath, 'utf8')) as { name?: string }
if (typeof owner.name === 'string') {
const specifier = `${owner.name}/${relative(directory, real).split(sep).join('/')}?url`
let binding = imports.get(specifier)
if (binding === undefined) {
binding = `__dshStaticAsset${imports.size}`
imports.set(specifier, binding)
}
return binding
}
}
directory = dirname(directory)
}
throw new Error(`tsdown: ${id}: asset ${file} has no package owner`)
}
const css: TsdownPlugin = {
name: 'dsh-static-css-metadata',
buildStart() { styles.clear(); imports.clear(); emitted.clear() },
resolveId: {
order: 'pre',
handler(source, importer) {
if (importer === undefined) return null
const file = source.endsWith(INLINE_CSS_QUERY) ? source.slice(0, -INLINE_CSS_QUERY.length) : source
// A third-party stylesheet stays a bare import, so the shell's Vite build applies its own processing.
if (!file.endsWith('.css') || isBareSpecifier(file)) return null
const resolved = sourceAssetPath(file, importer)
return (source.endsWith(INLINE_CSS_QUERY) ? INLINE_CSS_VIRTUAL_PREFIX : CSS_VIRTUAL_PREFIX) + resolved + CSS_VIRTUAL_SUFFIX
},
},
async load(virtualId) {
const inline = virtualId.startsWith(INLINE_CSS_VIRTUAL_PREFIX)
if (!inline && !virtualId.startsWith(CSS_VIRTUAL_PREFIX)) return null
const file = virtualId.slice((inline ? INLINE_CSS_VIRTUAL_PREFIX : CSS_VIRTUAL_PREFIX).length, -CSS_VIRTUAL_SUFFIX.length)
this.addWatchFile(file)
const references = new Map<string, string>()
const nonce = randomBytes(8).toString('hex')
const rewrite = (url: Url): Url | undefined => {
if (url.url === '' || url.url.startsWith('#') || url.url.startsWith('/') || URL_SCHEME.test(url.url)) return undefined
const parts = /^([^?#]+)(.*)$/.exec(url.url)!
const expression = resource(this, resolvePath(dirname(file), decodeURIComponent(parts[1]!)))
const marker = `__dshStaticCss_${nonce}_${references.size}__`
references.set(marker, parts[2] === '' ? expression : `(${expression} + ${JSON.stringify(parts[2])})`)
return { ...url, url: marker }
}
const result = transform({ filename: file, code: await readFile(file), minify: true,
...(file.endsWith('.module.css') ? { cssModules: { pattern: '[hash]_[local]' } } : {}),
visitor: {
Url: rewrite,
Image(image) {
if (image.type !== 'image-set') return undefined
return { ...image, value: { ...image.value, options: image.value.options.map(option => {
const url = option.image.type === 'url' ? rewrite(option.image.value) : undefined
return url === undefined ? option : { ...option, image: { type: 'url' as const, value: url } }
}) } }
},
},
})
const text = result.code.toString()
const pieces: string[] = []
let last = 0
if (references.size > 0) for (const match of text.matchAll(new RegExp([...references.keys()].join('|'), 'gu'))) {
pieces.push(JSON.stringify(text.slice(last, match.index)), references.get(match[0])!)
last = match.index + match[0].length
}
pieces.push(JSON.stringify(text.slice(last)))
const expression = pieces.join(' + ')
if (inline) return `export default ${expression};`
const classMap = Object.fromEntries(Object.entries(result.exports ?? {}).sort(([a], [b]) => a.localeCompare(b)).map(([key, value]) => [key, value.name]))
styles.set(virtualId, compiledClientStyle(id, packageDir, file, expression))
return { code: `export default ${JSON.stringify(classMap)};`, moduleSideEffects: 'no-treeshake' }
},
}
const envelope: TsdownPlugin = {
name: 'dsh-static-module-manifest',
renderChunk(code, chunk) {
if (!chunk.isEntry) throw new Error(`tsdown: ${id}: static module unexpectedly emitted ${chunk.fileName}`)
const output = new Rolldown.RolldownMagicString(code)
const imported: string[] = []
const getters: string[] = []
const stars: string[] = []
// Each module-table import also leaves a require in the factory, so Modules records the dependency.
const required = new Set<string>()
const table = (specifier: string): void => {
if ((PLATFORM_MODULES as readonly string[]).includes(specifier)) required.add(specifier)
}
let exportObject = '__dshModuleExports'
while (code.includes(exportObject)) exportObject += '_'
const key = (name: { type: string; name?: string; value?: unknown }): string => name.type === 'Identifier' ? name.name! : String(name.value)
const getter = (exported: string, value: string): void => {
if (exported === STATIC_MODULE_MANIFEST_EXPORT) throw new Error(`tsdown: ${id}: ${exported} is reserved for the module manifest`)
getters.push(`${JSON.stringify(exported)}: { enumerable: true, get: () => ${value} }`)
}
// The ordinary exports stay as written; the manifest factory returns live views of the same bindings.
for (const statement of this.parse(code).body) {
if (statement.type === 'ImportDeclaration') {
table(String(statement.source.value))
} else if (statement.type === 'ExportNamedDeclaration') {
if (statement.declaration !== null) throw new Error(`tsdown: ${id}: unsupported generated declaration export`)
let source: string | undefined
if (statement.source !== null) {
table(String(statement.source.value))
source = `__dshReexport${imported.length}`
imported.push(`import * as ${source} from ${JSON.stringify(String(statement.source.value))};`)
}
for (const specifier of statement.specifiers) {
getter(key(specifier.exported), source === undefined ? key(specifier.local) : `${source}[${JSON.stringify(key(specifier.local))}]`)
}
} else if (statement.type === 'ExportAllDeclaration') {
table(String(statement.source.value))
const binding = `__dshReexport${imported.length}`
imported.push(`import * as ${binding} from ${JSON.stringify(String(statement.source.value))};`)
if (statement.exported !== null) getter(key(statement.exported), binding)
else stars.push(binding)
} else if (statement.type === 'ExportDefaultDeclaration') {
throw new Error(`tsdown: ${id}: unsupported generated default declaration`)
}
}
for (const [source, binding] of imports) imported.push(`import ${binding} from ${JSON.stringify(source)};`)
const resources = Object.keys(chunk.modules).flatMap(module => {
const style = styles.get(module)
return style === undefined ? [] : [`${JSON.stringify(style.path)}: { text: (context) => ${style.expression} }`]
})
if (imported.length > 0) output.prepend(`${imported.join('\n')}\n`)
const starExports = stars.map(binding => `for (const key of Object.keys(${binding})) if (key !== 'default' && !Object.hasOwn(${exportObject}, key)) Object.defineProperty(${exportObject}, key, { enumerable: true, get: () => ${binding}[key] });`).join('\n')
const metadata = resources.length === 0 ? '' : `, meta: () => ({ stylesheets: {${resources.join(',')}} })`
const requires = [...required].map(specifier => `require(${JSON.stringify(specifier)});\n`).join('')
output.append(`\nexport const ${STATIC_MODULE_MANIFEST_EXPORT} = { id: ${JSON.stringify(id)}, factory: (require) => {\n${requires}`
+ `const ${exportObject} = Object.defineProperties({}, {${getters.join(',')}});\n${starExports}\nreturn ${exportObject};\n}${metadata} };\n`)
return output
},
}
config.plugins = [css, ...(config.plugins as TsdownPlugin[]).filter(plugin => plugin.name !== 'dsh-css-asset'), envelope]
return config
}
/** Whether a specifier names a package rather than a file next to its importer. */
function isBareSpecifier(specifier: string): boolean {
return !specifier.startsWith('.') && !specifier.startsWith('\0') && !isAbsolute(specifier)
@@ -541,14 +710,16 @@ function packageAssetCall(reference: string): string {
* or drops a declaration.
* @param css - stylesheet text after the rewrite.
* @param references - reference of each placeholder the rewrite inserted into this stylesheet.
* @param resolver - Resolver expression in the generated factory's execution context.
* @returns a string literal, or a concatenation of literals and resolver calls.
*/
function stylesheetSource(css: string, references: ReadonlyMap<string, string>): string {
function stylesheetSource(css: string, references: ReadonlyMap<string, string>, resolver = PACKAGE_ASSET_CALL): string {
if (references.size === 0) return JSON.stringify(css)
const parts: string[] = []
let last = 0
for (const match of css.matchAll(new RegExp([...references.keys()].join('|'), 'gu'))) {
parts.push(JSON.stringify(css.slice(last, match.index)), packageAssetCall(references.get(match[0]) as string))
const reference = JSON.stringify(references.get(match[0]) as string)
parts.push(JSON.stringify(css.slice(last, match.index)), `${resolver}(${reference})`)
last = match.index + match[0].length
}
parts.push(JSON.stringify(css.slice(last)))
@@ -787,6 +958,12 @@ function clientConfig(
const isRequested = (specifier: string): boolean => (requested ??= clientExternals(manifest)).has(specifier)
const isolation = clientInputIsolation(id)
const assets = packageAssets(manifest, packageDir)
const styles = new Map<string, CompiledClientStyle>()
const packageRequire = createRequire(resolvePath(packageDir, 'package.json'))
const resolveStylesheet = (source: string, importer: string | undefined): string => isBareSpecifier(source)
? packageRequire.resolve(source)
: importer === undefined ? source : sourceAssetPath(source, importer)
const styleMarker = `/*__dshChunkStyles_${randomBytes(16).toString('hex')}__*/`
return {
name: `${id}/client`,
entry: { client: entry },
@@ -864,10 +1041,29 @@ function clientConfig(
)
},
}, tscSourceMapPlugin(), asyncChunkRequirePlugin(), isolation.plugin, {
name: 'dsh-client-style-factory',
renderChunk(code, chunk) {
const marker = code.indexOf(styleMarker)
if (marker < 0 || code.indexOf(styleMarker, marker + styleMarker.length) !== -1) {
throw new Error(`tsdown: ${id}: missing or repeated style factory marker in ${chunk.fileName}`)
}
const resources = new Map<string, CompiledClientStyle>()
for (const moduleId of Object.keys(chunk.modules)) {
const style = styles.get(moduleId)
if (style !== undefined) resources.set(style.path, style)
}
const expression = [...resources.values()].map(style =>
`${JSON.stringify(style.path)}: { text: (context) => ${style.expression} }`).join(',')
const output = new Rolldown.RolldownMagicString(code)
output.overwrite(marker, marker + styleMarker.length,
resources.size === 0 ? '' : `, meta: () => ({ stylesheets: {${expression}} })`)
return output
},
}, {
name: 'dsh-css-modules-inline',
resolveId(source: string, importer: string | undefined) {
if (!source.endsWith('.module.css')) return null
const abs = importer !== undefined ? sourceAssetPath(source, importer) : source
const abs = resolveStylesheet(source, importer)
return CSS_VIRTUAL_PREFIX + abs + CSS_VIRTUAL_SUFFIX
},
async load(virtualId: string) {
@@ -888,14 +1084,16 @@ function clientConfig(
const exportEntries = Object.entries(cssExports ?? {})
.sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))
for (const [local, exp] of exportEntries) classMap[local] = exp.name
return styleInjectionModule(id, fileId, stylesheetSource(code.toString(), stylesheetAssets.references), classMap)
styles.set(virtualId, compiledClientStyle(id, packageDir, fileId,
stylesheetSource(code.toString(), stylesheetAssets.references, 'context.asset')))
return { code: `export default ${JSON.stringify(classMap)};`, moduleSideEffects: 'no-treeshake' }
},
}, {
name: 'dsh-css-text-inline',
resolveId(source: string, importer: string | undefined) {
if (!source.endsWith(`.css${INLINE_CSS_QUERY}`)) return null
const stylesheet = source.slice(0, -INLINE_CSS_QUERY.length)
const abs = importer !== undefined ? sourceAssetPath(stylesheet, importer) : stylesheet
const abs = resolveStylesheet(stylesheet, importer)
return INLINE_CSS_VIRTUAL_PREFIX + abs + CSS_VIRTUAL_SUFFIX
},
async load(virtualId: string) {
@@ -904,14 +1102,19 @@ function clientConfig(
this.addWatchFile(fileId)
const source = await readFile(fileId)
const stylesheetAssets = assets.urlRewrite(this, fileId)
const { code } = transform({ filename: fileId, code: source, minify: true, ...stylesheetAssets.options })
const { code } = transform({
filename: fileId,
code: source,
minify: true,
...stylesheetAssets.options,
})
return `export default ${stylesheetSource(code.toString(), stylesheetAssets.references)};`
},
}, {
name: 'dsh-css-global-inline',
resolveId(source: string, importer: string | undefined) {
if (!source.endsWith('.css') || source.endsWith('.module.css')) return null
const abs = importer !== undefined ? sourceAssetPath(source, importer) : source
const abs = resolveStylesheet(source, importer)
return GLOBAL_CSS_VIRTUAL_PREFIX + abs + CSS_VIRTUAL_SUFFIX
},
async load(virtualId: string) {
@@ -921,7 +1124,9 @@ function clientConfig(
const source = await readFile(fileId)
const stylesheetAssets = assets.urlRewrite(this, fileId)
const { code } = transform({ filename: fileId, code: source, minify: true, ...stylesheetAssets.options })
return styleInjectionModule(id, fileId, stylesheetSource(code.toString(), stylesheetAssets.references))
styles.set(virtualId, compiledClientStyle(id, packageDir, fileId,
stylesheetSource(code.toString(), stylesheetAssets.references, 'context.asset')))
return { code: 'export {};', moduleSideEffects: 'no-treeshake' }
},
}, assets.plugin],
outputOptions: {
@@ -943,7 +1148,7 @@ function clientConfig(
const prefix = clientBanner?.(chunk.fileName)
return prefix === undefined ? '' : `${prefix}\n`
},
footer: 'return module.exports; } });',
footer: `return module.exports; }${styleMarker} });`,
intro: 'var module = { exports: {} }; var exports = module.exports;',
},
}
+2 -2
View File
@@ -24,8 +24,8 @@
en: cf2d00ce2b7d5719
zh: 5510420f8872e23a
/deepseek-ai-dsh-client-ui-dockkit/build-shape:
en: 21216ba5798d7f5f
zh: ac505fdcd5c114d4
en: 69f87827f149270f
zh: 65e41db2b2400cd5
/deepseek-ai-dsh-client-ui-dockkit/model-experience:
en: cdebb91645623401
zh: fe262db316714fa8
+1 -1
View File
@@ -88,7 +88,7 @@ These are not stylistic; each one fixes a defect found in a real browser.
<a id="build-shape"></a>
## Build shape
The package is statically linked: tsdown's `staticLinked` preset emits one browser ESM bundle at `lib/index.js` (every bare specifier stays an import, sourcemaps chain to the sources) and ships the stylesheet under `lib/` at its `src`-relative path, and the Web shell resolves the package name and bundles that artifact itself, so vite stays the only owner of class hashing. One consequence is load-bearing — the kit keeps **one** stylesheet, `dockkit.module.css`, because a consumer de-duplicates injected sheets by file name and a collision would drop one silently.
The package is statically linked: tsdown's `staticLinked` preset emits one browser ESM bundle at `lib/index.js` (every bare specifier stays an import, sourcemaps chain to the sources), and the Web shell resolves the package name and bundles that artifact itself. The preset compiles `dockkit.module.css` with class names of the form `<hash>_<local>` and carries its text in the bundle's `__$dsh_client_module_manifest` export; the renderer installs it as one style element with `data-plugin="@deepseek-ai/dsh-client-ui-dockkit"` and `data-path="src/components/dockkit.module.css"`.
<a id="model-experience"></a>
## Model Experience
+1 -1
View File
@@ -88,7 +88,7 @@ Sidebar 使用的 `DockLayout` 在选中项变化、跨格移动与浮动期间
<a id="build-shape"></a>
## 构建形态
本包静态链接:tsdown 的 `staticLinked` 预设在 `lib/index.js` 产出一个浏览器 ESM bundle(所有裸说明符保持为 import,sourcemap 链回源码),并把样式表按其相对 `src` 的路径放到 `lib/` 下;Web 外壳按包名解析并自行打包该产物,因此 vite 仍是 class 哈希的唯一拥有者。有一个后果至关重要——套件只保留**一张**样式表 `dockkit.module.css`,因为消费方按文件名去重注入的样式表,撞名会静默丢掉一张。
本包静态链接:tsdown 的 `staticLinked` 预设在 `lib/index.js` 产出一个浏览器 ESM bundle(所有裸说明符保持为 import,sourcemap 链回源码),Web 外壳按包名解析并自行打包该产物。预设以 `<hash>_<local>` 形式的类名编译 `dockkit.module.css`,其文本随 bundle 的 `__$dsh_client_module_manifest` 导出交付;renderer 将它安装为一个 style 元素,带 `data-plugin="@deepseek-ai/dsh-client-ui-dockkit"` 和 `data-path="src/components/dockkit.module.css"`。
<a id="model-experience"></a>
## 模型体验
@@ -99,7 +99,8 @@ function TabHost({ state, callbacks, intents, tab, pane, column, floats, focusRe
renderTabTitle={callbacks.renderTabTitle} canCloseTab={callbacks.canCloseTab} drag={floats.drag} />
: <TabStrip state={state} pane={pane} callbacks={callbacks} offsets={offsets} />)}
</div>
<div ref={body} className={clsx(css.tabHostBody, floating ? css.floatBody : css.paneBody)}>
<div ref={body} className={clsx(css.tabHostBody, floating ? css.floatBody : css.paneBody)}
data-dockkit-pane-body={floating ? undefined : ''}>
{visited && (retained || (active && selected)) ? <TabBody tab={tab} renderTab={callbacks.renderTab} /> : null}
{!floating && <PaneDropHints pane={pane} callbacks={callbacks} />}
</div>
@@ -493,7 +493,7 @@ export function TabPanel({ state, pane, callbacks }: TabPanelProps): ReactNode {
}}
>
<TabStrip state={state} pane={pane} callbacks={callbacks} />
<div className={css.paneBody}>
<div className={css.paneBody} data-dockkit-pane-body="">
{active === undefined
? <p className={css.empty}>{callbacks.labels.emptyPane}</p>
: <TabBody tab={active} renderTab={callbacks.renderTab} />}
+2 -2
View File
@@ -21,8 +21,8 @@
en: 7eac53b38d0777fe
zh: 7f9422dff671ba50
/deepseek-ai-dsh-client-ui-layout/use-this-package/theme-presentation:
en: 5ac34303ad90b484
zh: abcc4a1dcf28391e
en: f0f27f4819ef4853
zh: 15fced516382b973
/deepseek-ai-dsh-client-ui-layout/understand-the-implementation:
en: e3cb25f05902369a
zh: c1a8f049a7a4effb
+1 -1
View File
@@ -48,7 +48,7 @@ The root publishes `--dsh-frame-top-clearance` for the reserved strip (48px on m
### Theme presentation
The presenter consumes resolved theme snapshots and projects them onto the document: `html { color-scheme }` for native UA chrome, `body[data-ds-dark-theme]` from the active color scheme, the theme's alias tokens, `--dsh-content-font-size`, `--dsh-code-font-size`, `--dsh-terminal-font-size`, and each non-empty `--dsh-font-family-<role>` list as inline variables on body, and one owned `<meta name="theme-color">` whose content follows the computed body background. Disposing the presenter removes its metadata node with its other global writes.
The presenter consumes resolved theme snapshots and projects them onto the document: `html { color-scheme }` for native UA chrome, `body[data-ds-dark-theme]` from the active color scheme, the theme's alias tokens, `--dsh-content-font-size`, `--dsh-code-font-size`, `--dsh-terminal-font-size`, and each non-empty `--dsh-font-family-<role>` list as inline variables on body, and one owned `<meta name="theme-color">` whose content follows the computed body background. It also refreshes that metadata when document-head style elements are installed, edited or removed. Disposing the presenter stops this observation and removes its metadata node with its other global writes.
-----
+1 -1
View File
@@ -48,7 +48,7 @@ Windows Electron 的 `data-windows-titlebar` 标记在所有列上方预留顶
### 主题呈现
呈现器消费解析后的主题快照,并投影到 document:`html { color-scheme }` 驱动原生 UA 控件,依据当前配色方案设置 `body[data-ds-dark-theme]`,把主题的别名 token、`--dsh-content-font-size`、`--dsh-code-font-size`、`--dsh-terminal-font-size` 以及每个非空的 `--dsh-font-family-<role>` 列表设为 body 上的内联变量,并持有一个 `<meta name="theme-color">`,其内容随计算后的 body 背景色更新。对呈现器执行 dispose(资源释放)时,它会连同其他全局写入一起移除自己的元数据节点。
呈现器消费解析后的主题快照,并投影到 document:`html { color-scheme }` 驱动原生 UA 控件,依据当前配色方案设置 `body[data-ds-dark-theme]`,把主题的别名 token、`--dsh-content-font-size`、`--dsh-code-font-size`、`--dsh-terminal-font-size` 以及每个非空的 `--dsh-font-family-<role>` 列表设为 body 上的内联变量,并持有一个 `<meta name="theme-color">`,其内容随计算后的 body 背景色更新。文档 head 中的 style 元素安装、编辑或移除时,它也会刷新该元数据。对呈现器执行 dispose(资源释放)时,它会停止观察,并连同其他全局写入一起移除自己的元数据节点。
-----
@@ -234,6 +234,7 @@ export function apply(ctx: ClientContext): void {
// state through the getter once, then event-driven only; no React path.
ctx.effect(() => {
const presenter = new ThemePresenter()
presenter.start()
presenter.apply(ctx.theme.getTheme())
const off = ctx.on('theme/change', (snapshot) => { presenter.apply(snapshot) })
return () => {
@@ -50,6 +50,7 @@ export class ThemePresenter {
private appliedTokens: string[] = []
/** The single metadata node this presenter inserts and removes. */
private readonly themeColorMeta: HTMLMetaElement
private styleObserver: MutationObserver | undefined
/** Create the presenter-owned metadata node before the first snapshot arrives. */
constructor() {
@@ -57,6 +58,17 @@ export class ThemePresenter {
this.themeColorMeta.name = 'theme-color'
}
/** Observe stylesheet installation and replacement after theme initialization. */
start(): void {
if (this.styleObserver !== undefined) return
this.styleObserver = new MutationObserver((changes) => {
const isStyle = (node: Node): boolean => node.nodeName === 'STYLE'
if (changes.some(change => isStyle(change.target) || change.target.parentNode?.nodeName === 'STYLE'
|| [...change.addedNodes, ...change.removedNodes].some(isStyle))) this.refreshThemeColor()
})
this.styleObserver.observe(document.head, { childList: true, subtree: true, characterData: true })
}
/**
* Project a snapshot onto the document: set root `color-scheme` and the body
* palette attribute from `active.colorScheme` (never the id — `system` is
@@ -88,7 +100,11 @@ export class ThemePresenter {
body.style.setProperty(name, value)
this.appliedTokens.push(name)
}
this.themeColorMeta.content = getComputedStyle(body).backgroundColor
this.refreshThemeColor()
}
private refreshThemeColor(): void {
this.themeColorMeta.content = getComputedStyle(document.body).backgroundColor
if (!this.themeColorMeta.isConnected) document.head.append(this.themeColorMeta)
}
@@ -97,6 +113,8 @@ export class ThemePresenter {
* attribute, token variables, the font sizes, font lists, and the owned metadata node.
*/
dispose(): void {
this.styleObserver?.disconnect()
this.styleObserver = undefined
document.documentElement.style.removeProperty('color-scheme')
document.documentElement.removeAttribute(THEME_SOURCE_ATTRIBUTE)
const body = document.body
@@ -1,6 +1,6 @@
// @vitest-environment jsdom
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { FontFamilies, ThemePreference, ThemeSnapshot } from '@deepseek-ai/dsh-client-ui-theme/client'
import { fontFamilyVariable } from '@deepseek-ai/dsh-client-ui-theme/src/theme-settings.ts'
import { DARK_ATTRIBUTE, THEME_SOURCE_ATTRIBUTE, ThemePresenter } from '@deepseek-ai/dsh-client-ui-layout/src/client/theme-presenter.ts'
@@ -69,6 +69,75 @@ describe('ThemePresenter', () => {
expect(document.head.querySelectorAll('meta[name="theme-color"]')).toHaveLength(1)
})
it('updates theme metadata when styles arrive after the initial snapshot and change later', async () => {
const palette = document.head.querySelector<HTMLStyleElement>('style[data-theme-presenter-test]')!
palette.textContent = `body { background-color: ${LIGHT_THEME_COLOR}; }`
const presenter = new ThemePresenter()
const observe = vi.spyOn(MutationObserver.prototype, 'observe')
try {
presenter.start()
presenter.start()
expect(observe).toHaveBeenCalledTimes(1)
presenter.apply(snapshot('dark'))
expect(themeColorMeta()?.content).toBe(LIGHT_THEME_COLOR)
const installed = document.createElement('style')
installed.dataset.themePresenterTest = ''
installed.textContent = `body[${DARK_ATTRIBUTE}] { background-color: ${DARK_THEME_COLOR}; }`
document.head.append(installed)
await Promise.resolve()
expect(themeColorMeta()?.content).toBe(DARK_THEME_COLOR)
installed.textContent = `body[${DARK_ATTRIBUTE}] { background-color: rgb(40, 41, 42); }`
await Promise.resolve()
expect(themeColorMeta()?.content).toBe('rgb(40, 41, 42)')
const read = vi.spyOn(globalThis, 'getComputedStyle')
try {
installed.firstChild!.textContent = `body[${DARK_ATTRIBUTE}] { background-color: rgb(50, 51, 52); }`
await Promise.resolve()
expect(read).toHaveBeenCalledTimes(1)
} finally {
read.mockRestore()
}
installed.remove()
await Promise.resolve()
expect(themeColorMeta()?.content).toBe(LIGHT_THEME_COLOR)
} finally {
observe.mockRestore()
presenter.dispose()
}
})
it('ignores unrelated head mutations and stops observing when disposed', async () => {
const presenter = new ThemePresenter()
presenter.start()
presenter.apply(snapshot('dark'))
await Promise.resolve()
const read = vi.spyOn(globalThis, 'getComputedStyle')
const foreign = document.createElement('meta')
try {
foreign.name = 'fixture-other'
document.head.append(foreign)
themeColorMeta()!.content = 'rgb(1, 2, 3)'
await Promise.resolve()
expect(read).not.toHaveBeenCalled()
const installed = document.createElement('style')
installed.dataset.themePresenterTest = ''
installed.textContent = 'body { background-color: rgb(4, 5, 6); }'
document.head.append(installed)
presenter.dispose()
await Promise.resolve()
expect(read).not.toHaveBeenCalled()
expect(themeColorMeta()).toBeNull()
} finally {
foreign.remove()
read.mockRestore()
presenter.dispose()
}
})
it('applies tokens as inline variables and clears the previous set on theme change', () => {
const presenter = new ThemePresenter()
presenter.apply(snapshot('dark', { '--dsw-alias-bg': '#111', '--dsw-alias-fg': '#eee' }))
@@ -15,8 +15,8 @@
en: d152484eb41ac6b4
zh: 09388d293f9be9cb
/deepseek-ai-dsh-client-ui-primitives/use-this-package:
en: ead6be55c7c9d7cf
zh: 125ad36db7328551
en: 33a5b39959a595c6
zh: efd1088e9f13ed67
/deepseek-ai-dsh-client-ui-primitives/use-this-package/component-catalog:
en: 11686b52743a702d
zh: d865bb79d8f56ee1
+1 -1
View File
@@ -31,7 +31,7 @@ Use `dsh-client-ui-primitives` to build web-client controls and render agent out
Automatic modal entry and modal/menu return focus, including after Escape and application close shortcuts, use `focusWithoutRing(element, options?)` to suppress the outline until Tab or directional navigation resumes normal focus styling. Dialog containers keep their outline-free styling. Existing borders, shadows, and error states remain intact. Mark a dialog's initial control with `data-modal-autofocus` so the modal captures its invoking control before moving focus. Controls mounted with the dialog must not use React `autoFocus`, which runs before that capture. Tab and Shift+Tab from the dialog container enter its first and last focusable controls.
This package is a Web-shell build input. Its static ESM retains third-party imports and styles for Vite; independent consumers supply its development dependencies ([dependency rules](../AGENTS.md#dependency-declaration)).
This package is a Web-shell build input. Its static ESM retains third-party imports, including third-party stylesheets such as KaTeX's, for Vite; its own stylesheets are compiled into the `__$dsh_client_module_manifest` export for the renderer to install; independent consumers supply its development dependencies ([dependency rules](../AGENTS.md#dependency-declaration)).
Compose feature UI from these atoms whenever the web client needs a standard control or an agent-output renderer. They render through React only and take `--dsw-*` design tokens from the theme, so they fit any plugin without importing the theme or the slot system.
Loaded 100 of 146 files, more files were not shown because too many files have changed in this diff. Show more