tsdown.client.ts 27 KB

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