diff --git a/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.i18n.yaml b/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.i18n.yaml index 7f34aedf3f..7730aa86e7 100644 --- a/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.i18n.yaml @@ -15,8 +15,8 @@ en: 6af228b03e5e533f zh: 276a522af6be5d7a /agent-note-client-plugin-loading-lazy-factories-cordis-lifecycle-and-hot-reload/decision/one-module-system-one-plugin-governor: - en: 5f5daec51b20db77 - zh: e4d6f78fc1b4b835 + en: 51df5a30c9337f22 + zh: f4533cd731c86890 /agent-note-client-plugin-loading-lazy-factories-cordis-lifecycle-and-hot-reload/decision/combo-external-script-arrival-and-source-maps: en: 04b9f0138b5d2288 zh: 2a749db57f6e7a10 diff --git a/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.md b/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.md index 6de1fd1ab8..643a0909e0 100644 --- a/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.md +++ b/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.md @@ -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. 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. +`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. A factory may also synchronously require a chunk of its own package that is already registered; the chunk registration and request rules are in [package-local chunk dependencies](2026-11-26-package-local-chunk-dependencies.md). 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`. diff --git a/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.zh.md b/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.zh.md index 7e1e7d1d40..3542910eb2 100644 --- a/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.zh.md +++ b/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.zh.md @@ -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 还会提供其生成文件名——此外什么都不发生。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 请求不能填充新代次。 +`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()` 表达式编译到这个独立操作。factory 也可以同步 require 本包已登记的 chunk;chunk 登记与请求的规则见[包内分片之间的依赖](2026-11-26-package-local-chunk-dependencies.zh.md)。模块表按固定分支顺序解析: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`。 diff --git a/.agents/notes/implemented/architecture/2026-10-14-webworker-preview-profile-parity.i18n.yaml b/.agents/notes/implemented/architecture/2026-10-14-webworker-preview-profile-parity.i18n.yaml index a475a53ae5..336bd67da2 100644 --- a/.agents/notes/implemented/architecture/2026-10-14-webworker-preview-profile-parity.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-10-14-webworker-preview-profile-parity.i18n.yaml @@ -21,8 +21,8 @@ en: 608b24ca97ab5bca zh: 94bb28377c856b2e /agent-note-boot-the-preview-worker-from-the-shipped-profile-and-fetch-lazy-chunks-on-demand/decision/separate-archives-for-lazily-loaded-chunks: - en: 428699f74f19e998 - zh: 2e8fcdbc9616f70b + en: bb3f7f2737dddec6 + zh: c514e53f6a4837ff /agent-note-boot-the-preview-worker-from-the-shipped-profile-and-fetch-lazy-chunks-on-demand/decision/watching-and-client-plugin-delivery: en: 814c344e891f7f91 zh: a024d5e30607968b diff --git a/.agents/notes/implemented/architecture/2026-10-14-webworker-preview-profile-parity.md b/.agents/notes/implemented/architecture/2026-10-14-webworker-preview-profile-parity.md index 97af566106..6bcbb60874 100644 --- a/.agents/notes/implemented/architecture/2026-10-14-webworker-preview-profile-parity.md +++ b/.agents/notes/implemented/architecture/2026-10-14-webworker-preview-profile-parity.md @@ -52,7 +52,7 @@ The Worker's structural stubs throw errors carrying `ERR_FEATURE_UNAVAILABLE_ON_ ### Separate archives for lazily loaded chunks -- **Classification**: the client build preset emits package-local chunk requests only as `require.async("./client..js")`, and `verify-client-packages` forbids synchronous chunk requires. The packer's `lazyChunksOf` scans every page asset in the swept image (each package's `lib/client.js` and `lib/client.*.js`) for these literals, so a chunk that another chunk requests is found without following requests from the `./client` entry. A target that a package's `./client` export names under any condition (such as `client.browser.js`) loads eagerly and stays in the base image; every other target leaves it. A request for a chunk the package does not publish fails the pack. +- **Classification**: the client build preset emits asynchronous package-local chunk requests only as `require.async("./client..js")`, optionally with a `{ deps: [...] }` prefetch hint that names every other chunk the request needs ([chunk dependencies](2026-11-26-package-local-chunk-dependencies.md)). The packer's `lazyChunksOf` scans every page asset in the swept image (each package's `lib/client.js` and `lib/client.*.js`) for these literals, hint entries included, so a chunk that another chunk requests is found without following requests from the `./client` entry. A target that a package's `./client` export names under any condition (such as `client.browser.js`) loads eagerly and stays in the base image; every other target leaves it. A request for a chunk the package does not publish fails the pack. - **Archives**: each chunk gets one deterministic tar.gz named `lazy/.tar.gz` after the SHA-256 of the compressed archive. The base manifest's `lazy` list records each archive as `{ archive, files: [{ path, size }] }`, with no file mode. There is no size threshold. - **Registration**: the Worker registers each listed file with `MemoryVfs.deferArchive`, which creates its parent directories and gives it the VFS default file mode; an image that lists lazy archives must be fetched from a URL, against which the archive names resolve. `exists`, `stat`, and `readdir` answer synchronously from the registration. - **Fetch**: the asynchronous faces of the Worker's `node:fs` and `node:fs/promises` that read a registered file wait for its archive: `fs.promises.readFile`, `fs.promises.open` (so every FileHandle opens after arrival), `fs.promises.cp`, and `fs.createReadStream`. The first of them fetches the archive, inflates it, checks that it carries exactly the registered paths at the registered sizes, and materializes the files; concurrent readers share one fetch. The digest in the archive name is not verified. A failed fetch fails only the reads waiting on it; the files stay registered and the next asynchronous read fetches again. diff --git a/.agents/notes/implemented/architecture/2026-10-14-webworker-preview-profile-parity.zh.md b/.agents/notes/implemented/architecture/2026-10-14-webworker-preview-profile-parity.zh.md index c2fbd3262c..598977551e 100644 --- a/.agents/notes/implemented/architecture/2026-10-14-webworker-preview-profile-parity.zh.md +++ b/.agents/notes/implemented/architecture/2026-10-14-webworker-preview-profile-parity.zh.md @@ -52,7 +52,7 @@ Worker 的结构化 stub 抛出带 `ERR_FEATURE_UNAVAILABLE_ON_PLATFORM` 的错 ### 懒加载 chunk 独立归档 -- **分类**:client 构建预设只以 `require.async("./client..js")` 的形式产出包内 chunk 请求,`verify-client-packages` 禁止同步 require chunk。packer 的 `lazyChunksOf` 扫描清扫后镜像里的每个页面资源(各包的 `lib/client.js` 和 `lib/client.*.js`)中的这些字面量,因此 chunk 引用的 chunk 不必从 `./client` 入口沿请求追踪也能找到。在任一条件下被某个包的 `./client` 导出指向的目标(如 `client.browser.js`)会被立即加载,留在基础镜像;其余目标移出基础镜像。请求包未发布的 chunk 会让打包失败。 +- **分类**:client 构建预设只以 `require.async("./client..js")` 的形式产出异步的包内 chunk 请求,可选带上 `{ deps: [...] }` 预取提示,列出该请求需要的其他所有 chunk([分片依赖](2026-11-26-package-local-chunk-dependencies.zh.md))。packer 的 `lazyChunksOf` 扫描清扫后镜像里的每个页面资源(各包的 `lib/client.js` 和 `lib/client.*.js`)中的这些字面量,包括提示中的项,因此 chunk 引用的 chunk 不必从 `./client` 入口沿请求追踪也能找到。在任一条件下被某个包的 `./client` 导出指向的目标(如 `client.browser.js`)会被立即加载,留在基础镜像;其余目标移出基础镜像。请求包未发布的 chunk 会让打包失败。 - **归档**:每个 chunk 一个确定性 tar.gz,按压缩后归档的 SHA-256 命名为 `lazy/.tar.gz`。基础 manifest 的 `lazy` 列表把每个 archive 记录为 `{ archive, files: [{ path, size }] }`,不记录文件 mode。不设大小阈值。 - **登记**:Worker 用 `MemoryVfs.deferArchive` 登记列出的每个文件,同时创建其父目录,并赋予 VFS 默认文件 mode;列出懒加载 archive 的镜像必须从 URL 拉取,archive 名相对这个 URL 解析。`exists`、`stat`、`readdir` 依据登记同步作答。 - **拉取**:Worker 的 `node:fs` 和 `node:fs/promises` 中读取已登记文件的异步接口会等待其 archive:`fs.promises.readFile`、`fs.promises.open`(因此每个 FileHandle 都在到达后才打开)、`fs.promises.cp` 和 `fs.createReadStream`。其中第一个调用拉取 archive、解压,校验其中恰好是登记的路径和登记的大小,再物化文件;并发读取方共用一次拉取。archive 名里的摘要不做校验。拉取失败只让等待它的读取失败;文件保持登记,下一次异步读取再次拉取。 diff --git a/.agents/notes/implemented/architecture/2026-11-05-client-module-metadata.i18n.yaml b/.agents/notes/implemented/architecture/2026-11-05-client-module-metadata.i18n.yaml index dae69e3b7b..e21c652156 100644 --- a/.agents/notes/implemented/architecture/2026-11-05-client-module-metadata.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-11-05-client-module-metadata.i18n.yaml @@ -9,8 +9,8 @@ en: 590dbd303b44e903 zh: b536f88e6fcdbce2 /agent-note-client-metadata-and-renderer-owned-stylesheet-installation/decision: - en: 93d58b7585af3f6c - zh: a91c4717778dd5eb + en: 87e7d3b714915271 + zh: b527931e3eac73b9 /agent-note-client-metadata-and-renderer-owned-stylesheet-installation/alternatives-considered: en: 70adfc415b3a5328 zh: 16599d6feb06cae8 diff --git a/.agents/notes/implemented/architecture/2026-11-05-client-module-metadata.md b/.agents/notes/implemented/architecture/2026-11-05-client-module-metadata.md index e280866b88..2d19e0efa9 100644 --- a/.agents/notes/implemented/architecture/2026-11-05-client-module-metadata.md +++ b/.agents/notes/implemented/architecture/2026-11-05-client-module-metadata.md @@ -10,7 +10,7 @@ A script's execution environment need not be its presentation document. CSS inje ## 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. +Client artifacts contain `id` and `factory`, with optional `meta`, a `chunk` name for dynamic package-local chunks, and [`deps`](2026-11-26-package-local-chunk-dependencies.md) naming the chunks a factory requires synchronously. `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. diff --git a/.agents/notes/implemented/architecture/2026-11-05-client-module-metadata.zh.md b/.agents/notes/implemented/architecture/2026-11-05-client-module-metadata.zh.md index 688207c5ab..f4160811ed 100644 --- a/.agents/notes/implemented/architecture/2026-11-05-client-module-metadata.zh.md +++ b/.agents/notes/implemented/architecture/2026-11-05-client-module-metadata.zh.md @@ -10,7 +10,7 @@ Status: implemented ## Decision -Client 产物包含 `id` 和 `factory`,可选带有 `meta`,动态包内 chunk 另带 `chunk` 名称。`meta()` 返回资源描述;可选的 `stylesheets` 是以路径为键的字典,每个值提供独立求值的 `text(context)` 函数。资源路径标识样式表,而不是组件。当前没有样式表依赖字段。 +Client 产物包含 `id` 和 `factory`,可选带有 `meta`,动态包内 chunk 另带 `chunk` 名称,factory 同步 require 的 chunk 列在 [`deps`](2026-11-26-package-local-chunk-dependencies.zh.md) 中。`meta()` 返回资源描述;可选的 `stylesheets` 是以路径为键的字典,每个值提供独立求值的 `text(context)` 函数。资源路径标识样式表,而不是组件。当前没有样式表依赖字段。 Modules 拥有 JavaScript 导出、模块身份、owner id 和观察到的依赖边。它保存元信息函数而不求值,发布通用的模块记录变化。Renderer 拥有元信息/文本缓存、依赖有序的样式集合、路径去重与主文档节点。它在 React 挂载前显式安装已有资源,随模块变化更新,并在根卸载后释放样式。组件生命周期不拥有样式。 diff --git a/.agents/notes/implemented/architecture/2026-11-26-package-local-chunk-dependencies.i18n.yaml b/.agents/notes/implemented/architecture/2026-11-26-package-local-chunk-dependencies.i18n.yaml new file mode 100644 index 0000000000..92f5c53877 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-26-package-local-chunk-dependencies.i18n.yaml @@ -0,0 +1,22 @@ +# Bilingual-pair consistency record for 2026-11-26-package-local-chunk-dependencies.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-26-package-local-chunk-dependencies.md +/agent-note-package-local-chunk-dependencies: + en: be8e63e6d765fd9b + zh: 2301e5754a32f288 +/agent-note-package-local-chunk-dependencies/problem: + en: 3a5fb76c845f5938 + zh: 8da1557121ec5503 +/agent-note-package-local-chunk-dependencies/decision: + en: dd2c654e49bbc659 + zh: 2a461be554571a86 +/agent-note-package-local-chunk-dependencies/alternatives-considered: + en: fa1b734a16a83dad + zh: c0f51477e123a8f9 +/agent-note-package-local-chunk-dependencies/consequences: + en: 90a70c4127a31e0a + zh: 7874aabdd89159b2 +/agent-note-package-local-chunk-dependencies/testing: + en: 5efdb48c7772afa9 + zh: f81468f7d27cac8d diff --git a/.agents/notes/implemented/architecture/2026-11-26-package-local-chunk-dependencies.md b/.agents/notes/implemented/architecture/2026-11-26-package-local-chunk-dependencies.md new file mode 100644 index 0000000000..e9d8ae9f0a --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-26-package-local-chunk-dependencies.md @@ -0,0 +1,49 @@ +# Agent Note: Package-local chunk dependencies + +Status: implemented + +English | [中文](2026-11-26-package-local-chunk-dependencies.zh.md) + +## Problem + +The dynamic Client preset builds a package's browser half with Rolldown, which splits every source `import()` into a `client..js` chunk. Rolldown also moves code that several chunks share, including its CommonJS helper `\0rolldown/runtime.js`, into common chunks, and every chunk that uses them requires those chunks synchronously. The [loading model](2026-07-23-client-plugin-loading-model.md) required self-contained output: a factory's `require` answered only module-table requests, and `require.async` loaded exactly one chunk. A package whose lazy modules import each other, such as syntax grammars that embed other grammars, could not split by `import()`, and an entry that shared one module with a lazy chunk failed at runtime on its synchronous `require("./client..js")`. + +## Decision + +Chunks of one package may require each other synchronously. Two `deps` lists carry the chunk graph to the [module system](../../../../packages/client/modules/README.md), each with its own obligation: + +- **Registration `deps`** in `__ModuleLoader__.load({ id, chunk, deps, factory })` is a precondition: the chunks of the same package (`./client..js`) that the factory requires synchronously. The module system downloads and registers each of them, and transitively their own `deps`, before the factory runs. The [preset](../../../../packages/client/tsdown.client.ts) writes the chunk's direct chunk imports from Rolldown's `RenderedChunk.imports` and omits the field when there are none. +- **`require.async(spec, { deps })`** is a prefetch hint: further chunks of the same package to download in parallel with the requested chunk. The preset writes the requested chunk's transitive synchronous closure, computed from the `meta.chunks` graph of `renderChunk`, minus the chunks the entry file carries, and keeps the one-argument call when nothing remains. A missing hint costs round trips only, because registration `deps` still load the group one level per round. A request for another package ignores the option. + +The preset moves every chunk the entry requires synchronously, transitively and dependencies first, into the entry file ahead of the entry's own registration, and deletes their files and maps. One script may already register several factories, as combo batches do, so the entry needs no request beyond its own script. The move runs in `generateBundle` after input isolation has checked each chunk, and the entry map gains one empty line per inserted line, in both the emitted map asset and the in-memory chunk map. A chunk that imports the package entry, statically or dynamically, fails the build: the module system keys the entry by package id, so no relative specifier reaches it. A dynamic import of a chunk the entry file carries keeps Rolldown's synchronous `require` inside a resolved promise, because the entry file registers that chunk before any code of the package runs and no file is left to download. + +In the module system, a synchronous `require("./client..js")` materializes a registered chunk of the same package and throws for an unregistered one. Arriving a graph row registers its entry script, then the entry's registration `deps`; a batch script can register the entry without the row's own download, so the dependency step also runs for an entry that was already registered, and an owner invalidation while those chunks download restarts the arrival from the entry script. A package-local `require.async` downloads the hinted chunks in parallel with the requested chunk and waits for those downloads to end before the chunk runs or the request retries, so a hinted download of a dropped generation cannot discard what the retry registers; the chunk itself needs only its registration `deps`, transitively and in parallel, and a hinted chunk that fails to download fails the request only through a registration that requires it. A failed dependency rejects with the chain of registrations that required it, with or without a hint, once every sibling arrival has ended; an owner invalidation during arrival restarts the request under the new revision; a cycle downloads once and fails when the factories run, as module-table cycles do. A `deps` entry that names no package-local chunk is rejected at registration and at the request. + +[`src/chunks.ts`](../../../../packages/client/modules/src/chunks.ts) owns the chunk file-name pattern that the preset, the Host chunk route, the module system, and the WebWorker packer read. The publication closure check in [`publint-all`](../../../../scripts/publint-all.ts) accepts a `require("./client..js")` inside a registered module factory whose file is not published when a script in the same directory registers the package entry and that chunk, because the moved chunks no longer have files; an ESM `import` or any other relative request still needs its published file. The WebWorker packer treats hinted chunks as requested ones, so they leave the base image as well. Values of another package remain module-table requests composed by the Host graph; `deps` never names another package. + +## Alternatives considered + +**Self-contained chunks through Rolldown's chunking options.** Forcing shared modules into each importing chunk gives every chunk a private copy of each module it reaches. Grammar modules form a graph, so the copies multiply, and modules with state would exist once per chunk. + +**Rolldown groups that keep the entry's shared modules in the entry chunk.** Lazy chunks would then require `./client.js`, which the module system does not address, and the group rule would duplicate Rolldown's reachability analysis. Concatenating the rendered chunks keeps Rolldown's chunk graph and every registration unchanged and costs one source-map offset. + +**Separate files for the entry's chunks, loaded through registration `deps`.** Every package with shared code would add at least one request round before its entry can run during boot. + +**One `deps` list with both meanings.** A hint that the loader trusted would turn a builder's closure mistake into a missing chunk at runtime, and a precondition that the loader treated as a hint would run a factory whose dependencies never arrived when no hint accompanies the request, as when one chunk requests another. + +**Waiting for dependencies inside `require`.** A factory's `require` is synchronous; factory-form CommonJS cannot wait, so every chunk a factory requires must be registered before it runs. + +## Consequences + +- A hinted lazy group downloads in one round; registration `deps` alone take one round per dependency level. +- The entry file grows by the moved chunks. Boot only registers them; their factories still run at the first `require`. +- The moved chunks have no source mapping in the entry map, so browser tools show their generated code. +- During HMR replacement, old code that requests a chunk after its package was invalidated loads the new revision's chunk. If that chunk requires a chunk the new entry file carries, the request fails until the new entry has registered; the loader does not handle chunks specially for HMR. +- A package built outside this repository must write registration `deps` for every synchronous chunk require; the hint is optional. + +## Testing + +- [chunk-deps.client.spec.ts](../../../../packages/client/modules/tests/chunk-deps.client.spec.ts) covers level-by-level arrival, one-round hinted downloads, entry dependencies registered by the same script or completed after a preloaded registration, an entry arrival restarted by an invalidation during its chunk downloads, shared and cyclic dependencies, the failure chain with and without a hint, a failed hinted chunk that no registration requires, restart after invalidation, a retry that waits for the hinted downloads of the dropped generation and for every sibling of a failed dependency, re-execution of an entry script after invalidation, rejected `deps` entries, and synchronous requests of unregistered chunks. +- [client-bundle-chunk-deps.client.spec.ts](../../../../scripts/client-bundle-chunk-deps.client.spec.ts) builds a fixture whose entry and lazy chunks share modules and CommonJS packages, asserts the moved registrations, deleted files, registration `deps`, hints, the synchronous form of a dynamic import of an entry-carried chunk, and the shifted map, rejects a chunk that imports the entry statically or dynamically, and runs the written artifacts through the real module system. +- [lazy-chunks.spec.ts](../../../../packages/experimental/webworker-packer/tests/lazy-chunks.spec.ts) moves hinted chunks out of the WebWorker base image. +- [publint-all.spec.ts](../../../../scripts/publint-all.spec.ts) accepts a factory's chunk request that the entry file registers and rejects one that only a chunk file registers, that nothing provides, or that an ESM import or code outside a factory makes. diff --git a/.agents/notes/implemented/architecture/2026-11-26-package-local-chunk-dependencies.zh.md b/.agents/notes/implemented/architecture/2026-11-26-package-local-chunk-dependencies.zh.md new file mode 100644 index 0000000000..132689092f --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-26-package-local-chunk-dependencies.zh.md @@ -0,0 +1,49 @@ +# Agent Note: 包内分片之间的依赖 + +Status: implemented + +[English](2026-11-26-package-local-chunk-dependencies.md) | 中文 + +## Problem + +动态 Client 预设用 Rolldown 构建包的浏览器半侧,每个源码 `import()` 都会拆成一个 `client..js` 分片。Rolldown 还会把多个分片共用的代码,包括它的 CommonJS 辅助模块 `\0rolldown/runtime.js`,移进公共分片,用到这些代码的分片会同步 require 这些公共分片。[加载模型](2026-07-23-client-plugin-loading-model.zh.md)原先要求产物自包含:factory 的 `require` 只解析模块表请求,`require.async` 只加载一个分片。懒加载模块互相导入的包,例如嵌入其他语法的语法高亮模块,因此无法按 `import()` 拆分;入口只要和某个懒加载分片共用一个模块,运行时就会在同步的 `require("./client..js")` 上失败。 + +## Decision + +同一个包的分片之间可以同步 require。分片依赖图通过两个 `deps` 列表交给[模块系统](../../../../packages/client/modules/README.zh.md),两者承担的义务不同: + +- **登记信息里的 `deps`**(`__ModuleLoader__.load({ id, chunk, deps, factory })`)是前提条件:列出 factory 同步 require 的同包分片(`./client..js`)。模块系统先下载并登记其中每个分片,以及它们各自 `deps` 的传递闭包,再运行这个 factory。[预设](../../../../packages/client/tsdown.client.ts)从 Rolldown 的 `RenderedChunk.imports` 写入该分片直接导入的分片,没有时省略该字段。 +- **`require.async(spec, { deps })`** 是预取提示:列出与所请求分片并行下载的其他同包分片。预设按 `renderChunk` 的 `meta.chunks` 分片图算出所请求分片的同步传递闭包,去掉入口文件已携带的分片后写入;结果为空时保留单参数调用。缺少提示只会多花请求轮次,因为登记信息里的 `deps` 仍会逐层加载整组分片。请求其他包时忽略该选项。 + +预设把入口同步 require 的所有分片(传递闭包,依赖在前)移进入口文件,放在入口自己的登记之前,并删除它们各自的文件和 map。一个脚本本来就可以登记多个 factory,combo 批次就是这样,因此入口除了自己的脚本不需要别的请求。移动发生在 `generateBundle` 阶段、输入隔离检查完每个分片之后;入口 map 按插入的行数补上同样数量的空行,输出的 map 资源和内存中的分片 map 都会更新。静态或动态导入包入口的分片会让构建失败:模块系统以包 id 作为入口的键,没有相对路径能指向它。对入口文件携带的分片的动态导入保留 Rolldown 生成的、包在已完成 Promise 里的同步 `require`,因为入口文件在该包任何代码运行之前就登记了这个分片,也没有文件可下载。 + +在模块系统里,同步的 `require("./client..js")` 会物化已登记的同包分片,对未登记的分片抛错。图行到达时先登记入口脚本,再处理入口登记信息里的 `deps`;批次脚本可能在这一行自己的下载之前就登记了入口,所以已经登记过的入口也会执行这一步;这些分片下载期间所属包被失效时,到达过程从入口脚本重新开始。包内 `require.async` 会把提示中的分片与分片本身并行下载,并等这些下载结束后才运行分片或重试请求,因此旧代次的提示下载不会删掉重试登记的分片;分片本身只需要自己登记信息里的 `deps`(递归、并行),提示中的分片下载失败,只有被某个登记信息依赖时才会让请求失败。依赖失败时,要等同一批的其余到达全部结束才拒绝,无论是否带提示,拒绝信息都会带出要求该分片的登记链;到达过程中所属包被失效时,请求在新 revision 下重新开始;有环时每个分片只下载一次,在 factory 运行时失败,与模块表的环相同。不指向包内分片的 `deps` 项在登记和请求时都会被拒绝。 + +[`src/chunks.ts`](../../../../packages/client/modules/src/chunks.ts) 持有分片文件名规则,预设、Host 分片路由、模块系统和 WebWorker 打包器都从这里读取。[`publint-all`](../../../../scripts/publint-all.ts) 的发布闭包检查遇到已登记模块 factory 里文件未发布的 `require("./client..js")` 时,若同一目录下有脚本登记了包入口和该分片,就视为满足,因为被移入的分片已经没有单独文件;ESM `import` 等其他相对请求仍要求对应文件已发布。WebWorker 打包器把提示中的分片当作被请求的分片,它们同样移出基础镜像。其他包的值仍是由 Host 图组合的模块表请求;`deps` 从不指向其他包。 + +## Alternatives considered + +**用 Rolldown 的拆分选项保持分片自包含。** 把共用模块强行放进每个导入它的分片,会让每个分片都带上它能到达的每个模块的私有副本。语法模块之间是图结构,副本会成倍增加,有状态的模块也会在每个分片里各有一份。 + +**用 Rolldown 分组把入口共用的模块留在入口分片里。** 懒加载分片随后会 require `./client.js`,而模块系统无法定位它;分组规则还要重复 Rolldown 的可达性分析。把已渲染的分片拼接起来,Rolldown 的分片图和每个登记都保持不变,只需一次 source map 偏移。 + +**入口的分片保留为单独文件,靠登记信息里的 `deps` 加载。** 每个有共用代码的包都会在启动时、入口运行之前至少多一轮请求。 + +**一个 `deps` 列表兼具两种含义。** 加载器若信任提示,构建端算错闭包就会变成运行时缺分片;加载器若把前提条件当作提示,请求不带提示时(例如一个分片请求另一个分片)factory 就会在依赖未到达时运行。 + +**在 `require` 内部等待依赖。** factory 的 `require` 是同步的;factory 形式的 CommonJS 无法等待,所以 factory 会 require 的每个分片都必须在它运行前登记。 + +## Consequences + +- 带提示的懒加载分组一轮下载完;只靠登记信息里的 `deps` 时,每层依赖一轮。 +- 入口文件会增加被移入的分片。启动时只登记它们;它们的 factory 仍在首次 `require` 时运行。 +- 被移入的分片在入口 map 中没有源码映射,浏览器工具只显示其生成代码。 +- HMR 替换期间,包失效后旧代码请求分片时会加载新 revision 的分片。如果该分片 require 的分片由新的入口文件携带,在新入口登记之前该请求会失败;加载器不针对 HMR 特别处理分片。 +- 在本仓库之外构建的包必须为每个同步分片 require 写出登记信息里的 `deps`;提示是可选的。 + +## Testing + +- [chunk-deps.client.spec.ts](../../../../packages/client/modules/tests/chunk-deps.client.spec.ts) 覆盖逐层到达、带提示时一轮下载、由同一脚本登记或在预加载登记后补齐的入口依赖、分片下载期间失效导致的入口到达重启、共用与成环的依赖、带或不带提示时的失败链、提示中无登记依赖的分片下载失败、失效后重新开始、重试前等待旧代次的提示下载及失败依赖的同批到达全部结束、失效后重新执行入口脚本、被拒绝的 `deps` 项,以及同步请求未登记分片。 +- [client-bundle-chunk-deps.client.spec.ts](../../../../scripts/client-bundle-chunk-deps.client.spec.ts) 构建一个入口与懒加载分片共用模块和 CommonJS 包的夹具,断言被移入的登记、被删除的文件、登记信息里的 `deps`、提示、对入口携带分片的动态导入保持同步形式以及偏移后的 map,拒绝静态或动态导入入口的分片,并用真实模块系统运行写出的产物。 +- [lazy-chunks.spec.ts](../../../../packages/experimental/webworker-packer/tests/lazy-chunks.spec.ts) 把带提示的分片移出 WebWorker 基础镜像。 +- [publint-all.spec.ts](../../../../scripts/publint-all.spec.ts) 接受 factory 中由入口文件登记过的分片请求,拒绝只有分片文件登记、无处提供、或来自 ESM import 及 factory 之外代码的请求。 diff --git a/packages/client/AGENTS.md b/packages/client/AGENTS.md index 802ecf01ab..d2ab9fa667 100644 --- a/packages/client/AGENTS.md +++ b/packages/client/AGENTS.md @@ -85,7 +85,7 @@ A dynamic browser half either carries a module privately or requests the shared 3. **Silence means a private copy.** Third-party implementation libraries outside the baseline may be bundled independently. A value reached only through `import type` is erased and creates no request. 4. **A request has two possible suppliers.** A dynamic package supplies its own row; `PLATFORM_MODULES` supplies an exact static-table key. There is no `dsh.client.provide` alias protocol. 5. **Validate both sides.** The dynamic build preset externalizes the baseline and rejects undeclared workspace value imports; [`verify-client-packages`](../../scripts/verify-client-packages.ts) rejects malformed or redundant requests, missing suppliers, and synchronous request cycles. -6. **Package-local dynamic chunks are self-contained.** Source uses `import()` and the shared preset emits `require.async("./client..js")`; an entry or chunk must not retain a synchronous relative `require("./client*.js")`. Keep every static relative dependency inside its owning output chunk rather than relying on a sibling-chunk graph the runtime does not support. +6. **Package-local chunks may require each other synchronously.** Source uses `import()`. The shared preset writes each chunk's synchronous chunk requires as its registration `deps`, which Modules registers before the factory runs, emits `require.async("./client..js", { deps })` with a prefetch hint for the rest of the target's chunk group, and moves the chunks the entry requires into the entry file. A chunk must not import the package entry, and `deps` never crosses packages ([decision](../../.agents/notes/implemented/architecture/2026-11-26-package-local-chunk-dependencies.md)). ### The module graph sits below cordis DI diff --git a/packages/client/modules/README.i18n.yaml b/packages/client/modules/README.i18n.yaml index 53a0eea4d1..a2c2c834bd 100644 --- a/packages/client/modules/README.i18n.yaml +++ b/packages/client/modules/README.i18n.yaml @@ -24,8 +24,8 @@ en: bc77e9c5d74134b0 zh: cd99a246d43472ea /deepseek-ai-dsh-client-modules/use-this-package/what-the-browser-loads: - en: fabb527083efdf4b - zh: a110a9471e494f5e + en: 3402ce993a0f4a1d + zh: 683a4f16b64210b6 /deepseek-ai-dsh-client-modules/use-this-package/live-plugin-composition: en: 09ed5277078f44ee zh: 3643210476149b2a @@ -48,8 +48,8 @@ en: 49dcadc166c2d06e zh: bbf67c6dc47f4ead /deepseek-ai-dsh-client-modules/understand-the-implementation/lazy-cjs-model: - en: c87fb35ad5800144 - zh: b5dd02f4d5e9821e + en: 7685cf8d45d4e223 + zh: 58cebfaaa6125151 /deepseek-ai-dsh-client-modules/understand-the-implementation/main-execution-environment: en: 3b2d663c0304e78a zh: 32aa738248e6080b @@ -66,8 +66,8 @@ en: a0d8dbb15e079ec0 zh: 7d215cb85fa8b2c7 /deepseek-ai-dsh-client-modules/understand-the-implementation/source-map: - en: 232120cddca73330 - zh: bd100d2e3e7094bc + en: cd4eb82cb19f94b4 + zh: 1dac9abb0dbb334e /deepseek-ai-dsh-client-modules/further-exploration: en: 7e5b283efe4f1d16 zh: 79472b64a0d759fe @@ -78,8 +78,8 @@ en: ca75c51c89c2c9b0 zh: de54f3467ef3b9be /deepseek-ai-dsh-client-modules/known-limitations-and-deferred-work: - en: 1b71a96e072e5d08 - zh: 4f08ae822bb91192 + en: 8ba377999c1cd27e + zh: 6e04e6dcb6704539 /deepseek-ai-dsh-client-modules/known-limitations-and-deferred-work/dev-note: en: e67f633dc6fe7773 zh: 3bb0c20c93f16f98 diff --git a/packages/client/modules/README.md b/packages/client/modules/README.md index 6264a06dfd..773ba63afc 100644 --- a/packages/client/modules/README.md +++ b/packages/client/modules/README.md @@ -40,7 +40,7 @@ The same `/plugins` route serves the images a client package publishes through i ### What the browser loads -The application combo scripts carry only each plugin's `client.js` entry and register those factories once during boot; module bodies remain lazy and run only at first import or materialization. A source `import()` split by tsdown compiles to `require.async("./client..js")`; its versioned sibling script arrives only when that expression runs. Rows that share a combo URL share one in-flight script task. A combo whose `