tsdown.client.ts 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588
  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 is compiled by
  6. * lightningcss inside the bundle: `x.module.css` yields its hashed class map
  7. * and injects a tagged style at factory execution, while `x.css?inline`
  8. * exports compiled text for a plugin-owned lifecycle effect. The virtual
  9. * loaders register each real stylesheet as a watch dependency.
  10. */
  11. import { readFile } from 'node:fs/promises'
  12. import { existsSync, globSync, readFileSync } from 'node:fs'
  13. import { isBuiltin } from 'node:module'
  14. import { basename, dirname, isAbsolute, relative, resolve as resolvePath, sep } from 'node:path'
  15. import { fileURLToPath } from 'node:url'
  16. import type { UserConfig } from 'tsdown'
  17. import { transform } from 'lightningcss'
  18. import { optionalStringArray } from './modules/src/client/manifest.ts'
  19. import { PLATFORM_MODULES, PRELOADED_CLIENT_EXTERNALS } from './web/src/platform.ts'
  20. import { clientBuildEnvironmentDefines } from '../../scripts/client-build-environment.ts'
  21. /**
  22. * Virtual-id wrapper keeping module CSS away from tsdown's own css pipeline
  23. * (which requires @tsdown/css). The suffix matters: tsdown's guard matches ids
  24. * ending in `.css`, so the virtual id must not.
  25. */
  26. const CSS_VIRTUAL_PREFIX = '\0dsh-css:'
  27. const GLOBAL_CSS_VIRTUAL_PREFIX = '\0dsh-global-css:'
  28. const INLINE_CSS_VIRTUAL_PREFIX = '\0dsh-inline-css:'
  29. const CSS_VIRTUAL_SUFFIX = '.mjs'
  30. const INLINE_CSS_QUERY = '?inline'
  31. /** Emit one plugin-owned style injector and an optional CSS Modules export. */
  32. function styleInjectionModule(
  33. id: string,
  34. fileId: string,
  35. css: string,
  36. classMap?: Readonly<Record<string, string>>,
  37. ): string {
  38. const source = [
  39. `const css = ${JSON.stringify(css)};`,
  40. `const tagId = ${JSON.stringify(`${id}/${basename(fileId)}`)};`,
  41. 'if (typeof document !== \'undefined\' && document.querySelector(\'style[data-plugin-css=\' + JSON.stringify(tagId) + \']\') === null) {',
  42. ' const tag = document.createElement(\'style\');',
  43. ` tag.dataset.plugin = ${JSON.stringify(id)};`,
  44. ' tag.dataset.pluginCss = tagId;',
  45. ' tag.textContent = css;',
  46. ' document.head.appendChild(tag);',
  47. '}',
  48. ]
  49. source.push(classMap === undefined ? 'export {};' : `export default ${JSON.stringify(classMap)};`)
  50. return source.join('\n')
  51. }
  52. /**
  53. * Wire/type layers a client bundle may inline: browser-safe contracts
  54. * with no runtime identity to share (no Symbol/instanceof/singleton state).
  55. * Everything else under @deepseek-ai/* is either a module-table entry
  56. * (external) or a leak the purity gate rejects.
  57. */
  58. export const INLINE_SAFE = /^@deepseek-ai\/dsh-(?:host-apiproxy|file-reference|session|llm|tools|brand|util-crypto|util-workspace-path)(?:\/|$)/
  59. /**
  60. * Vendored framework libraries: rescoped into @deepseek-ai, so the gate below
  61. * would read them as plugin packages. They carry no cross-plugin runtime
  62. * identity to share — the framework itself is a requested module-table row
  63. * (external), while these are ordinary libraries a browser bundle inlines.
  64. */
  65. const VENDORED_LIBRARY = /^@deepseek-ai\/(cosmokit|schemastery)(\/|$)/
  66. /** Generated descriptor/codec contribution with no shared runtime identity. */
  67. const GENERATED_REMOTE = /^@deepseek-ai\/dsh-[a-z0-9]+(?:-[a-z0-9]+)*\/remote$/
  68. /**
  69. * Workspace mode replaces an empty config array with the root defaults. A
  70. * falsey entry instead removes this package before entry resolution.
  71. */
  72. const SKIP_WORKSPACE_BUILD: UserConfig = { entry: '' }
  73. const REPOSITORY_ROOT = fileURLToPath(new URL('../..', import.meta.url))
  74. /** Rebase a physical lib-relative source onto a browser URL that mirrors the repository directories. */
  75. function browserSourcePath(source: string, sourcemapPath: string): string {
  76. if (!source.startsWith('.')) return source
  77. const physicalSource = resolvePath(dirname(sourcemapPath), source)
  78. const repositoryPath = relative(REPOSITORY_ROOT, physicalSource).split(sep).join('/')
  79. return repositoryPath.startsWith('packages/') ? `../../../${repositoryPath}` : source
  80. }
  81. /**
  82. * Build the tsdown config for one UI plugin package: the node-half lib build
  83. * plus the browser client bundle. Client packages emit both halves during the
  84. * Client pass by default; packages needed for Host reflection may opt into the
  85. * earlier Host pass. A package-level tsdown.config.ts REPLACES the root
  86. * workspace layout, so the lib half must be restated here — dropping it leaves
  87. * the package without lib/index.js and the host Loader cannot import its node
  88. * half.
  89. * @param id - plugin id (package name), stamped into the __ModuleLoader__.load
  90. * handoff and onto the injected style tags.
  91. * @param libEntry - node-half entries, spelled at the call site so the
  92. * package-invariants gate can see `lib/types/invariant.js` in each package's
  93. * own tsdown.config.ts (a preset-side glob hides it from the mechanical check).
  94. * @param options - phase placement, lib overrides, and companion Node configs.
  95. * @returns ENV-selected tsdown config for the current build face.
  96. */
  97. export function clientBundle(
  98. id: string,
  99. libEntry: readonly string[],
  100. options: ClientBundleOptions = {},
  101. ): BuildFaceConfig {
  102. const lib = clientLibraryConfig(id, libEntry, options.lib)
  103. return ({ env }) => {
  104. const face = buildFace(env?.DSH_BUILD_FACE)
  105. const clientEntry = face === undefined ? 'src/client/index.ts' : 'lib/types/client/index.js'
  106. const client = clientConfig(id, clientEntry)
  107. const node = [lib, ...(options.companions ?? [])]
  108. if (face === 'host') return options.hostPhase === true ? node : [SKIP_WORKSPACE_BUILD]
  109. if (face === 'client') {
  110. return options.hostPhase === true ? [client] : [...node, client]
  111. }
  112. return [...node, client]
  113. }
  114. }
  115. /**
  116. * Build the tsdown config for a client library the compile shell links
  117. * statically (the static assembly channel: `apps/web` resolves the package
  118. * name, bundles the artifact, and owns the chunk layout and the CSS pipeline).
  119. *
  120. * Calling this preset is what puts a package in the static assembly channel,
  121. * so the call sites are the roster: gates read it through
  122. * {@link isStaticLinkedConfig} rather than a second hand-kept list. A package on
  123. * this roster must not be a module-table row as well — the browser would take
  124. * the statically linked copy and a provider's bytes would sit unused in its
  125. * bundle.
  126. *
  127. * Four artifact contracts:
  128. * 1. every bare specifier stays an import. The shell attributes chunk bytes by
  129. * `node_modules/<pkg>`, so a dependency inlined into a workspace file is
  130. * attributed to no npm package and its bytes fall into the index chunk,
  131. * which collapses the vendor/index cache split.
  132. * 2. `esm` on `platform: 'browser'` — the shell is the only consumer.
  133. * 3. sourcemaps, chained through the tsc maps under `lib/types` to the sources.
  134. * 4. stylesheets ship with the package: a relative `.css` import survives as a
  135. * relative external and the sheet is emitted under `lib/` at its
  136. * `src`-relative path, so vite stays the only owner of class hashing.
  137. * @param id - package name, used in tsdown diagnostics.
  138. * @param libEntry - emitted JavaScript entries consumed from `lib/types`, one
  139. * bundle each: a multi-entry build would emit a hash-named shared chunk that
  140. * the exact `files` list cannot publish.
  141. * @returns ENV-selected tsdown config for the Client build face.
  142. */
  143. export function staticLinked(id: string, libEntry: readonly string[]): BuildFaceConfig {
  144. // Each entry names its own output file, so two entries with the same basename
  145. // would overwrite one artifact instead of emitting two.
  146. const names = new Set(libEntry.map(entry => basename(entry, '.js')))
  147. if (names.size !== libEntry.length) {
  148. throw new Error(`tsdown: ${id} entries collide on an output name: ${libEntry.join(', ')}`)
  149. }
  150. return clientOnly(libEntry.map(entry => staticLinkedConfig(id, entry)))
  151. }
  152. /**
  153. * Whether a package's tsdown configs put it in the static assembly channel.
  154. * The roster has no separate list: gates load each package's own
  155. * `tsdown.config.ts`, call it for the Client face, and ask this.
  156. * @param configs - configs a package's build-face function returned.
  157. * @returns true when at least one config was built by {@link staticLinked}.
  158. */
  159. export function isStaticLinkedConfig(configs: readonly UserConfig[]): boolean {
  160. return configs.some(config => (config.plugins as readonly { name?: string }[] | undefined ?? [])
  161. .some(plugin => plugin.name === STATIC_LINKED_PLUGIN))
  162. }
  163. /**
  164. * Build a Client-only Node library during the Client pass.
  165. * @param id - Package name used in tsdown diagnostics.
  166. * @param libEntry - Emitted JavaScript entries consumed from `lib/types`.
  167. * @returns ENV-selected tsdown config for the Client build face.
  168. */
  169. export function clientLibrary(id: string, libEntry: readonly string[]): BuildFaceConfig {
  170. const lib = clientLibraryConfig(id, libEntry)
  171. return clientOnly([lib])
  172. }
  173. /**
  174. * Select arbitrary package-local configs only during the Client pass.
  175. * @param configs - Node-side configs emitted after Client tsc.
  176. * @returns ENV-selected tsdown config for the Client build face.
  177. */
  178. export function clientOnly(configs: readonly UserConfig[]): BuildFaceConfig {
  179. return ({ env }) => buildFace(env?.DSH_BUILD_FACE) === 'host'
  180. ? [SKIP_WORKSPACE_BUILD]
  181. : [...configs]
  182. }
  183. interface ClientBundleOptions {
  184. /** Emit the Node-side artifacts during the Host pass instead of the Client pass. */
  185. readonly hostPhase?: boolean
  186. /** Additional Node-side configs emitted alongside the package library. */
  187. readonly companions?: readonly UserConfig[]
  188. /** Overrides for the package's primary Node-side library config. */
  189. readonly lib?: UserConfig
  190. }
  191. type BuildFace = 'host' | 'client' | undefined
  192. type BuildFaceConfig = (inlineConfig: Pick<UserConfig, 'env'>) => UserConfig[]
  193. function buildFace(value: unknown): BuildFace {
  194. if (value === undefined || value === 'host' || value === 'client') return value
  195. throw new Error(`tsdown: --env.DSH_BUILD_FACE must be host or client, received ${String(value)}`)
  196. }
  197. function clientLibraryConfig(
  198. id: string,
  199. libEntry: readonly string[],
  200. overrides: UserConfig = {},
  201. ): UserConfig {
  202. const isProductionDependency = (specifier: string): boolean =>
  203. matchesSpecifier(productionExternals(id), specifier)
  204. return {
  205. name: id,
  206. entry: [...libEntry],
  207. outDir: 'lib',
  208. format: ['esm'],
  209. platform: 'node',
  210. target: 'es2024',
  211. fixedExtension: false,
  212. dts: false,
  213. clean: false,
  214. deps: {
  215. // The Node half runs from a real install: a production dependency is on
  216. // disk there and stays an import, everything else inlines. Stating both
  217. // halves takes the artifact off tsdown's getProductionDeps fallback, where
  218. // moving a dependency between npm sections silently re-bundles it.
  219. // Builtins keep tsdown's own handling (neither side claims them).
  220. neverBundle: isProductionDependency,
  221. alwaysBundle: (specifier: string) => !isBuiltin(specifier) && !isProductionDependency(specifier),
  222. },
  223. ...overrides,
  224. }
  225. }
  226. /** The slice of the rolldown plugin context the stylesheet plugin uses. */
  227. interface AssetEmitter {
  228. emitFile(file: {
  229. type: 'asset'
  230. fileName: string
  231. source: Uint8Array
  232. originalFileName: string
  233. }): string
  234. }
  235. function staticLinkedConfig(id: string, entry: string, outputName = basename(entry, '.js')): UserConfig {
  236. const emitted = new Set<string>()
  237. return {
  238. name: id,
  239. entry: { [outputName]: entry },
  240. outDir: 'lib',
  241. format: ['esm'],
  242. platform: 'browser',
  243. target: 'es2024',
  244. fixedExtension: false,
  245. dts: false,
  246. clean: false,
  247. // The shell compiles this artifact, so its map is the only path from a
  248. // browser stack frame back to the TSX (tsc emits the lib/types half).
  249. sourcemap: true,
  250. plugins: [{
  251. // Contract 1. `pre` because tsdown's own deps plugin would otherwise
  252. // resolve and inline every specifier missing from the npm production
  253. // sections, which is the coupling this preset exists to remove. The name
  254. // is also the roster marker {@link isStaticLinkedConfig} reads.
  255. name: STATIC_LINKED_PLUGIN,
  256. resolveId: {
  257. order: 'pre' as const,
  258. handler(source: string, importer: string | undefined) {
  259. // An entry arrives without an importer and must stay internal.
  260. if (importer === undefined) return null
  261. return isBareSpecifier(source) ? { id: source, external: true } : null
  262. },
  263. },
  264. }, {
  265. // Contract 3. Rolldown does not read the `//# sourceMappingURL` of its
  266. // inputs, so each tsc map is handed over as that module's map and
  267. // composed into the bundle map; without it frames stop at the emitted
  268. // lib/types JavaScript instead of reaching the TSX.
  269. name: 'dsh-tsc-sourcemap',
  270. async load(id: string) {
  271. if (!id.includes(TYPES_MARKER) || !id.endsWith('.js') || !existsSync(`${id}.map`)) return null
  272. const code = await readFile(id, 'utf8')
  273. return { code: code.replace(SOURCEMAP_COMMENT, ''), map: await readFile(`${id}.map`, 'utf8') }
  274. },
  275. }, {
  276. // Contract 4. The import survives verbatim and the sheet lands beside the
  277. // JavaScript, so the shell's CSS Modules pipeline sees a real stylesheet.
  278. name: 'dsh-css-asset',
  279. async resolveId(this: AssetEmitter, source: string, importer: string | undefined) {
  280. if (!source.endsWith('.css') || importer === undefined) return null
  281. const { file, fileName } = stylesheetAsset(source, importer)
  282. if (!emitted.has(fileName)) {
  283. emitted.add(fileName)
  284. // originalFileName also puts the physical sheet in the watch graph.
  285. this.emitFile({ type: 'asset', fileName, source: await readFile(file), originalFileName: file })
  286. }
  287. // Every emitted chunk sits at the lib/ root, so the src-relative name
  288. // is what resolves from there. Rolldown keeps relative externals as
  289. // written instead of re-normalizing them.
  290. return { id: `./${fileName}`, external: true }
  291. },
  292. }],
  293. }
  294. }
  295. /** Whether a specifier names a package rather than a file next to its importer. */
  296. function isBareSpecifier(specifier: string): boolean {
  297. return !specifier.startsWith('.') && !specifier.startsWith('\0') && !isAbsolute(specifier)
  298. }
  299. /**
  300. * Locate a stylesheet import against the package sources and name its emitted position.
  301. * @param source - relative import specifier as written in the source.
  302. * @param importer - absolute path of the importing module, emitted or source.
  303. * @returns the stylesheet on disk plus its `src`-relative name under `lib/`.
  304. */
  305. function stylesheetAsset(source: string, importer: string): { readonly file: string, readonly fileName: string } {
  306. const file = sourceAssetPath(source, importer)
  307. const boundary = file.lastIndexOf(SOURCE_MARKER)
  308. if (boundary < 0) throw new Error(`tsdown: stylesheet ${file} is outside the package sources`)
  309. return { file, fileName: file.slice(boundary + SOURCE_MARKER.length).split(sep).join('/') }
  310. }
  311. /** The manifest fields the build faces read to state their own module edges. */
  312. interface WorkspaceManifest {
  313. readonly name?: string
  314. /** Sections a real install materializes on disk next to the built package. */
  315. readonly dependencies?: Record<string, string>
  316. readonly peerDependencies?: Record<string, string>
  317. readonly optionalDependencies?: Record<string, string>
  318. readonly dsh?: { readonly client?: { readonly external?: unknown } }
  319. }
  320. const manifestCache = new Map<string, WorkspaceManifest>()
  321. const productionExternalCache = new Map<string, readonly RegExp[]>()
  322. const clientExternalCache = new Map<string, ReadonlySet<string>>()
  323. /**
  324. * Read one workspace package's manifest. Located by package name rather than by
  325. * cwd, because tsdown evaluates every package config with the repository root as
  326. * `process.cwd()` during a workspace build. Callers read it on the first
  327. * resolveId of a build, not while a config is built, so selecting a build face
  328. * never touches a manifest.
  329. * @param id - package name, as spelled at the preset call site.
  330. * @returns the parsed manifest.
  331. * @throws {Error} when no workspace package declares that name.
  332. */
  333. function workspaceManifest(id: string): WorkspaceManifest {
  334. const cached = manifestCache.get(id)
  335. if (cached !== undefined) return cached
  336. for (const manifestPath of globSync('packages/*/*/package.json', { cwd: REPOSITORY_ROOT })) {
  337. const manifest = JSON.parse(
  338. readFileSync(resolvePath(REPOSITORY_ROOT, manifestPath), 'utf8'),
  339. ) as WorkspaceManifest
  340. if (manifest.name !== id) continue
  341. manifestCache.set(id, manifest)
  342. return manifest
  343. }
  344. throw new Error(`tsdown: no packages/*/*/package.json declares the name ${id}`)
  345. }
  346. /**
  347. * External patterns for one package's Node half: its own production sections,
  348. * subpaths included.
  349. * @param id - package name, as spelled at the preset call site.
  350. * @returns one `^name(/|$)` pattern per production dependency, name-sorted.
  351. */
  352. function productionExternals(id: string): readonly RegExp[] {
  353. const cached = productionExternalCache.get(id)
  354. if (cached !== undefined) return cached
  355. const manifest = workspaceManifest(id)
  356. const names = new Set([
  357. ...Object.keys(manifest.dependencies ?? {}),
  358. ...Object.keys(manifest.peerDependencies ?? {}),
  359. ...Object.keys(manifest.optionalDependencies ?? {}),
  360. ])
  361. const patterns = [...names].sort().map(name => new RegExp(`^${escapeSpecifier(name)}(/|$)`))
  362. productionExternalCache.set(id, patterns)
  363. return patterns
  364. }
  365. /**
  366. * Module-table specifiers one `dsh.client` declaration requests. Matching is
  367. * exact, never normalized: a package declares the specifier its own code
  368. * imports, and the loader keys static entries the same way.
  369. * @param subject - package name, used in diagnostics.
  370. * @param declaration - the package's `dsh.client` object.
  371. * @returns the requested specifiers, empty when the package declares none.
  372. * @throws {Error} when `external` is not a string array.
  373. */
  374. export function requestedExternals(
  375. subject: string,
  376. declaration: { readonly external?: unknown },
  377. ): ReadonlySet<string> {
  378. return new Set(optionalStringArray(subject, 'dsh.client.external', declaration.external) ?? [])
  379. }
  380. /**
  381. * Module-table specifiers one package requests. The shell baseline is implicit
  382. * for every dynamic bundle; `dsh.client.external` only adds package-specific
  383. * dynamic rows or subpaths.
  384. * @param id - package name, as spelled at the preset call site.
  385. * @returns the baseline plus the package's explicit requests.
  386. */
  387. function clientExternals(id: string): ReadonlySet<string> {
  388. const cached = clientExternalCache.get(id)
  389. if (cached !== undefined) return cached
  390. const externals = new Set([
  391. ...PLATFORM_MODULES,
  392. ...PRELOADED_CLIENT_EXTERNALS,
  393. ...requestedExternals(id, workspaceManifest(id).dsh?.client ?? {}),
  394. ])
  395. clientExternalCache.set(id, externals)
  396. return externals
  397. }
  398. /** Escape a package name for literal use inside a RegExp source. */
  399. function escapeSpecifier(name: string): string {
  400. return name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
  401. }
  402. /** Whether an import specifier is the package a pattern names, or one of its subpaths. */
  403. function matchesSpecifier(patterns: readonly RegExp[], specifier: string): boolean {
  404. return patterns.some(pattern => pattern.test(specifier))
  405. }
  406. function clientConfig(id: string, entry: string): UserConfig {
  407. const isRequested = (specifier: string): boolean => clientExternals(id).has(specifier)
  408. return {
  409. name: `${id}/client`,
  410. entry: { client: entry },
  411. // Browser bundle lands next to the node half (single lib/ artifact dir;
  412. // the entryFileNames pin keeps it exactly lib/client.js). clean must stay
  413. // off — a default clean would wipe the node-half output emitted above.
  414. outDir: 'lib',
  415. format: 'cjs',
  416. platform: 'browser',
  417. // Types ship from lib/types (tsc); dts here would wrap the banner/footer into .d.cts and break parsing.
  418. dts: false,
  419. // Plugin code is fetched outside Vite's module graph, so its own bundle
  420. // must carry the TS/TSX mapping consumed by browser profiling tools.
  421. sourcemap: true,
  422. clean: false,
  423. deps: {
  424. neverBundle: isRequested,
  425. // Anything NOT requested from the loader module table must inline
  426. // (wire/type layers, zod, clsx — every non-shared dep). A require() the
  427. // table cannot answer is a guaranteed runtime throw, so the rule is the
  428. // package's own request list: requested specifiers stay imports,
  429. // everything else is bundled.
  430. alwaysBundle: (specifier: string) => !isRequested(specifier),
  431. },
  432. // Browser bundles inline node-idiom deps (zustand/immer read
  433. // process.env.NODE_ENV; zustand's esm build also probes
  434. // import.meta.env.MODE, which a CJS output cannot carry — rolldown flags
  435. // EMPTY_IMPORT_META). vite defined both on the seed path; tsdown inlining
  436. // needs the substitutions here or the factory throws ReferenceError at
  437. // boot / the build gate reds. Both keys honor the build's NODE_ENV so a
  438. // dev build keeps the dev-branch semantics; artifacts default to production.
  439. // The bare `import.meta.env` key is required alongside the precise MODE
  440. // key: zustand probes `import.meta.env ? import.meta.env.MODE : ...`, and
  441. // the truthiness probe would otherwise survive as an empty import.meta.
  442. define: {
  443. ...clientBuildEnvironmentDefines(process.env),
  444. 'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV ?? 'production'),
  445. 'import.meta.env.MODE': JSON.stringify(process.env.NODE_ENV ?? 'production'),
  446. 'import.meta.env': JSON.stringify({ MODE: process.env.NODE_ENV ?? 'production' }),
  447. },
  448. plugins: [{
  449. // Bundle purity gate (build-time mirror of the module-edge rules): the
  450. // baseline and package-specific requests stay external, inline-safe wire layers
  451. // inline, and every other @deepseek-ai value import is a build error — a
  452. // cross-plugin value import either inlines a duplicate runtime instance
  453. // or requires a specifier the module table cannot answer for this package.
  454. // Cross-plugin collaboration goes through cordis services instead.
  455. name: 'dsh-client-bundle-purity',
  456. resolveId(source: string) {
  457. if (!source.startsWith('@deepseek-ai/')) return null
  458. if (isRequested(source)) return null // requested module-table row: external wins
  459. if (VENDORED_LIBRARY.test(source)) return null // vendored library: inline, no shared identity
  460. if (INLINE_SAFE.test(source) || GENERATED_REMOTE.test(source)) return null // wire contribution: inline is the point
  461. throw new Error(
  462. `client bundle purity: "${source}" is not in the default client externals or ${id}'s dsh.client.external, an inline-safe wire layer, or a generated /remote contribution — `
  463. + 'cross-plugin value imports are forbidden; declare a non-default module request or collaborate through cordis services '
  464. + '(type-only imports are erased and never reach this gate)',
  465. )
  466. },
  467. }, {
  468. name: 'dsh-css-modules-inline',
  469. resolveId(source: string, importer: string | undefined) {
  470. if (!source.endsWith('.module.css')) return null
  471. const abs = importer !== undefined ? sourceAssetPath(source, importer) : source
  472. return CSS_VIRTUAL_PREFIX + abs + CSS_VIRTUAL_SUFFIX
  473. },
  474. async load(virtualId: string) {
  475. if (!virtualId.startsWith(CSS_VIRTUAL_PREFIX)) return null
  476. const fileId = virtualId.slice(CSS_VIRTUAL_PREFIX.length, -CSS_VIRTUAL_SUFFIX.length)
  477. // The virtual id otherwise hides the physical stylesheet from Rolldown's watch graph.
  478. this.addWatchFile(fileId)
  479. const source = await readFile(fileId)
  480. const { code, exports: cssExports } = transform({
  481. filename: fileId,
  482. code: source,
  483. cssModules: { pattern: '[hash]_[local]' },
  484. minify: true,
  485. })
  486. const classMap: Record<string, string> = {}
  487. const exportEntries = Object.entries(cssExports ?? {})
  488. .sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))
  489. for (const [local, exp] of exportEntries) classMap[local] = exp.name
  490. return styleInjectionModule(id, fileId, code.toString(), classMap)
  491. },
  492. }, {
  493. name: 'dsh-css-text-inline',
  494. resolveId(source: string, importer: string | undefined) {
  495. if (!source.endsWith(`.css${INLINE_CSS_QUERY}`)) return null
  496. const stylesheet = source.slice(0, -INLINE_CSS_QUERY.length)
  497. const abs = importer !== undefined ? sourceAssetPath(stylesheet, importer) : stylesheet
  498. return INLINE_CSS_VIRTUAL_PREFIX + abs + CSS_VIRTUAL_SUFFIX
  499. },
  500. async load(virtualId: string) {
  501. if (!virtualId.startsWith(INLINE_CSS_VIRTUAL_PREFIX)) return null
  502. const fileId = virtualId.slice(INLINE_CSS_VIRTUAL_PREFIX.length, -CSS_VIRTUAL_SUFFIX.length)
  503. this.addWatchFile(fileId)
  504. const source = await readFile(fileId)
  505. const { code } = transform({ filename: fileId, code: source, minify: true })
  506. return `export default ${JSON.stringify(code.toString())};`
  507. },
  508. }, {
  509. name: 'dsh-css-global-inline',
  510. resolveId(source: string, importer: string | undefined) {
  511. if (!source.endsWith('.css') || source.endsWith('.module.css')) return null
  512. const abs = importer !== undefined ? sourceAssetPath(source, importer) : source
  513. return GLOBAL_CSS_VIRTUAL_PREFIX + abs + CSS_VIRTUAL_SUFFIX
  514. },
  515. async load(virtualId: string) {
  516. if (!virtualId.startsWith(GLOBAL_CSS_VIRTUAL_PREFIX)) return null
  517. const fileId = virtualId.slice(GLOBAL_CSS_VIRTUAL_PREFIX.length, -CSS_VIRTUAL_SUFFIX.length)
  518. this.addWatchFile(fileId)
  519. const source = await readFile(fileId)
  520. const { code } = transform({ filename: fileId, code: source, minify: true })
  521. return styleInjectionModule(id, fileId, code.toString())
  522. },
  523. }],
  524. outputOptions: {
  525. entryFileNames: 'client.js',
  526. // The map is served from /plugins/<scoped-package>/client.js.map. The
  527. // browser resolves its local sources back into URLs that mirror the
  528. // /packages/<group>/<package>/src directories; sourcesContent keeps them usable
  529. // without exposing that tree as an HTTP route.
  530. sourcemapPathTransform: browserSourcePath,
  531. banner: `window.__ModuleLoader__.load({ id: ${JSON.stringify(id)}, factory: (require) => {`,
  532. footer: 'return module.exports; } });',
  533. intro: 'var module = { exports: {} }; var exports = module.exports;',
  534. },
  535. }
  536. }
  537. /** Path segment separating a package's tsc output from the sources it was emitted from. */
  538. const TYPES_MARKER = `${sep}lib${sep}types${sep}`
  539. /** Plugin name carrying contract 1, and the marker that identifies a statically linked config. */
  540. const STATIC_LINKED_PLUGIN = 'dsh-static-linked-external'
  541. /** Path segment a package's sources hang under, and the root emitted assets mirror. */
  542. const SOURCE_MARKER = `${sep}src${sep}`
  543. /** Trailing sourcemap reference tsc appends to every emitted module. */
  544. const SOURCEMAP_COMMENT = /\n\/\/# sourceMappingURL=.*\s*$/
  545. /** Resolve an emitted JS asset import against its source-tree counterpart. */
  546. function sourceAssetPath(source: string, importer: string): string {
  547. const emitted = resolvePath(dirname(importer), source)
  548. if (existsSync(emitted)) return emitted
  549. const boundary = emitted.indexOf(TYPES_MARKER)
  550. if (boundary < 0) return emitted
  551. return resolvePath(emitted.slice(0, boundary), 'src', emitted.slice(boundary + TYPES_MARKER.length))
  552. }