tsdown.client.ts 32 KB

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