tsdown.client.ts 8.3 KB

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