tsdown.client.ts 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  1. /**
  2. * Shared tsdown preset for UI plugin client bundles. Emits a closure-factory
  3. * artifact: the bundle calls window.__ModuleLoader__.load({id, factory})
  4. * and resolves externals through the injected require (loader module table —
  5. * cordis DI entities, no globals, no import map). CSS Modules are compiled by
  6. * lightningcss inside the bundle: importing `x.module.css` yields the
  7. * hashed class map, and the css text auto-injects a <style data-plugin="<id>">
  8. * tag at factory execution (the loader removes plugin-owned tags on unload).
  9. * The virtual loader registers each real stylesheet as a watch dependency.
  10. */
  11. import { readFile } from 'node:fs/promises'
  12. import { basename, dirname, relative, resolve as resolvePath, sep } from 'node:path'
  13. import { fileURLToPath } from 'node:url'
  14. import type { UserConfig } from 'tsdown'
  15. import { transform } from 'lightningcss'
  16. import { PLATFORM_MODULES } from './web/src/platform.ts'
  17. /**
  18. * Virtual-id wrapper keeping module CSS away from tsdown's own css pipeline
  19. * (which requires @tsdown/css). The suffix matters: tsdown's guard matches ids
  20. * ending in `.css`, so the virtual id must not.
  21. */
  22. const CSS_VIRTUAL_PREFIX = '\0dsh-css:'
  23. const CSS_VIRTUAL_SUFFIX = '.mjs'
  24. /**
  25. * Wire/type layers a client bundle may inline: browser-safe contract surfaces
  26. * with no runtime identity to share (no Symbol/instanceof/singleton state).
  27. * Everything else under @deepseek-ai/* is either a module-table entry
  28. * (external) or a leak the purity gate rejects.
  29. */
  30. export const INLINE_SAFE = /^@deepseek-ai\/dsh-(host-apiproxy|session|llm|tools|brand)(\/|$)/
  31. /**
  32. * Documented TEMPORARY exemption, not a platform module (hence not in
  33. * platform.ts): the snapshot-store engine (createSnapshotStore/defineStore/
  34. * shallowEqual) lives in runtime pending its promotion-time rehoming, and
  35. * five importers (locale, ui-layout, ui-conversation ×3) ride this single
  36. * exemption. At runtime the lazy CJS table answers the require natively:
  37. * runtime is an immediately-tier row, its factory is registered before any
  38. * dependent bundle materializes. TODO(webload/store-rehome): remove with the
  39. * store-engine relocation follow-up.
  40. */
  41. const RUNTIME_STORE_EXEMPTION = '@deepseek-ai/dsh-client-runtime/client'
  42. /** Externals resolved from the loader module table: the platform seed entries plus the documented runtime exemption. */
  43. export const CLIENT_EXTERNALS: readonly string[] = [...PLATFORM_MODULES, RUNTIME_STORE_EXEMPTION]
  44. const REPOSITORY_ROOT = fileURLToPath(new URL('../..', import.meta.url))
  45. /** Rebase a physical lib-relative source onto the browser's repository-shaped URL tree. */
  46. function browserSourcePath(source: string, sourcemapPath: string): string {
  47. if (!source.startsWith('.')) return source
  48. const physicalSource = resolvePath(dirname(sourcemapPath), source)
  49. const repositoryPath = relative(REPOSITORY_ROOT, physicalSource).split(sep).join('/')
  50. return repositoryPath.startsWith('packages/') ? `../../../${repositoryPath}` : source
  51. }
  52. /**
  53. * Build the tsdown config for one UI plugin package: the node-half lib build
  54. * plus the browser client bundle. A package-level tsdown.config.ts REPLACES
  55. * the root workspace shape, so the lib half must be restated here — dropping
  56. * it leaves the package without lib/index.js and the host Loader cannot
  57. * import its node half.
  58. * @param id - plugin id (package name), stamped into the __ModuleLoader__.load
  59. * handoff and onto the injected style tags.
  60. * @param libEntry - node-half entries, spelled at the call site so the
  61. * package-invariants gate can see `lib/types/invariant.js` in each package's
  62. * own tsdown.config.ts (a preset-side glob hides it from the mechanical check).
  63. * @returns tsdown user configs emitting lib/*.js and lib/client.js.
  64. */
  65. export function clientBundle(id: string, libEntry: readonly string[]): [UserConfig, UserConfig] {
  66. return [{
  67. entry: [...libEntry],
  68. outDir: 'lib',
  69. format: ['esm'],
  70. platform: 'node',
  71. target: 'es2024',
  72. fixedExtension: false,
  73. dts: false,
  74. clean: false,
  75. }, {
  76. entry: { client: 'src/client/index.ts' },
  77. // Browser bundle lands next to the node half (single lib/ artifact dir;
  78. // the entryFileNames pin keeps it exactly lib/client.js). clean must stay
  79. // off — a default clean would wipe the node-half output emitted above.
  80. outDir: 'lib',
  81. format: 'cjs',
  82. platform: 'browser',
  83. // Types ship from lib/types (tsc); dts here would wrap the banner/footer into .d.cts and break parsing.
  84. dts: false,
  85. // Plugin code is fetched outside Vite's module graph, so its own bundle
  86. // must carry the TS/TSX mapping consumed by browser profiling tools.
  87. sourcemap: true,
  88. clean: false,
  89. external: [...CLIENT_EXTERNALS],
  90. // Browser bundles inline node-idiom deps (zustand/immer read
  91. // process.env.NODE_ENV; zustand's esm build also probes
  92. // import.meta.env.MODE, which a CJS output cannot carry — rolldown flags
  93. // EMPTY_IMPORT_META). vite defined both on the seed path; tsdown inlining
  94. // needs the substitutions here or the factory throws ReferenceError at
  95. // boot / the build gate reds. Both keys honor the build's NODE_ENV so a
  96. // dev build keeps the dev-branch semantics; artifacts default to production.
  97. // The bare `import.meta.env` key is required alongside the precise MODE
  98. // key: zustand probes `import.meta.env ? import.meta.env.MODE : ...`, and
  99. // the truthiness probe would otherwise survive as an empty import.meta.
  100. define: {
  101. 'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV ?? 'production'),
  102. 'import.meta.env.MODE': JSON.stringify(process.env.NODE_ENV ?? 'production'),
  103. 'import.meta.env': JSON.stringify({ MODE: process.env.NODE_ENV ?? 'production' }),
  104. },
  105. // tsdown auto-externalizes package dependencies; anything NOT in the
  106. // loader module table must inline instead (wire/type layers, zod, clsx —
  107. // every non-shared dep). A require() the table cannot answer is a
  108. // guaranteed runtime throw, so the rule is the table list itself: no
  109. // opinion for table entries (external above wins), bundle everything else.
  110. noExternal: (id: string) => (CLIENT_EXTERNALS.includes(id) ? undefined : true),
  111. plugins: [{
  112. // Bundle purity gate (build-time mirror of the module-edge rules):
  113. // platform seed entries stay external, inline-safe wire layers inline,
  114. // and every other @deepseek-ai value import is a build error — a
  115. // cross-plugin value import either inlines a duplicate runtime instance
  116. // or requires a specifier the frozen module table cannot answer.
  117. // Cross-plugin collaboration goes through cordis services instead.
  118. name: 'dsh-client-bundle-purity',
  119. resolveId(source: string) {
  120. if (!source.startsWith('@deepseek-ai/')) return null
  121. if (CLIENT_EXTERNALS.includes(source)) return null // platform module: external wins
  122. if (INLINE_SAFE.test(source)) return null // wire/type layer: inline is the point
  123. throw new Error(
  124. `client bundle purity: "${source}" is not a platform module (CLIENT_EXTERNALS) and not an inline-safe wire layer — `
  125. + 'cross-plugin value imports are forbidden; collaborate through cordis services (type-only imports are erased and never reach this gate)',
  126. )
  127. },
  128. }, {
  129. name: 'dsh-css-modules-inline',
  130. resolveId(source: string, importer: string | undefined) {
  131. if (!source.endsWith('.module.css')) return null
  132. const abs = importer !== undefined ? resolvePath(dirname(importer), source) : source
  133. return CSS_VIRTUAL_PREFIX + abs + CSS_VIRTUAL_SUFFIX
  134. },
  135. async load(virtualId: string) {
  136. if (!virtualId.startsWith(CSS_VIRTUAL_PREFIX)) return null
  137. const fileId = virtualId.slice(CSS_VIRTUAL_PREFIX.length, -CSS_VIRTUAL_SUFFIX.length)
  138. // The virtual id otherwise hides the physical stylesheet from Rolldown's watch graph.
  139. this.addWatchFile(fileId)
  140. const source = await readFile(fileId)
  141. const { code, exports: cssExports } = transform({
  142. filename: fileId,
  143. code: source,
  144. cssModules: { pattern: `[hash]_[local]` },
  145. minify: true,
  146. })
  147. const classMap: Record<string, string> = {}
  148. for (const [local, exp] of Object.entries(cssExports ?? {})) classMap[local] = exp.name
  149. // One <style data-plugin> per module file; idempotent under re-evaluation.
  150. return [
  151. `const css = ${JSON.stringify(code.toString())};`,
  152. `const tagId = ${JSON.stringify(`${id}/${basename(fileId)}`)};`,
  153. `if (typeof document !== 'undefined' && document.querySelector('style[data-plugin-css=' + JSON.stringify(tagId) + ']') === null) {`,
  154. ` const tag = document.createElement('style');`,
  155. ` tag.dataset.plugin = ${JSON.stringify(id)};`,
  156. ` tag.dataset.pluginCss = tagId;`,
  157. ` tag.textContent = css;`,
  158. ` document.head.appendChild(tag);`,
  159. `}`,
  160. `export default ${JSON.stringify(classMap)};`,
  161. ].join('\n')
  162. },
  163. }],
  164. outputOptions: {
  165. entryFileNames: 'client.js',
  166. // The map is served from /plugins/<scoped-package>/client.js.map. The
  167. // browser resolves its local sources back into the repository-shaped
  168. // /packages/<group>/<package>/src tree; sourcesContent keeps them usable
  169. // without exposing that tree as an HTTP route.
  170. sourcemapPathTransform: browserSourcePath,
  171. banner: `window.__ModuleLoader__.load({ id: ${JSON.stringify(id)}, factory: (require) => {`,
  172. footer: `return module.exports; } });`,
  173. intro: 'var module = { exports: {} }; var exports = module.exports;',
  174. },
  175. }]
  176. }