index.ts 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883
  1. /**
  2. * Node half of the client module system (`dsh.client` dual-face package): scans
  3. * the host Loader's entries for packages declaring `dsh.client`, composes the
  4. * `window.__DSH_BOOT__` entry graph (wire single source: {@link WebBootEntry}
  5. * in `./client/manifest.ts`) in module-graph order, serves one-or-more-plugin
  6. * combo scripts plus their source maps,
  7. * contributes the registration facade, application preloads, bootstrap scripts,
  8. * and graph to the webserver's index injection table, and provides the
  9. * `clientModuleHost` service (the HMR node half's registration/notification
  10. * face).
  11. *
  12. * Scanning is incremental per package — there is no full-rescan code path.
  13. * Every cordis `internal/plugin` emission (fiber construction/disposal) marks
  14. * the fiber's entry name dirty; a microtask flush reconciles each dirty name
  15. * against the live loader entries. The activation pass seeds the same dirty
  16. * set with all current entries and flushes synchronously, so first scan and
  17. * steady state share one implementation. Package metadata (including the
  18. * negative "not a client package" verdict) is cached per name and never
  19. * expires — plugin-set changes take effect on restart; bundle content
  20. * changes reach the graph only through
  21. * {@link ClientModuleRegistry.rebuilt}.
  22. * @module @deepseek-ai/dsh-client-modules
  23. */
  24. import { createHash, randomBytes } from 'node:crypto'
  25. import { readFileSync, statSync } from 'node:fs'
  26. import type { IncomingMessage, ServerResponse } from 'node:http'
  27. import { createRequire } from 'node:module'
  28. import { dirname, join } from 'node:path'
  29. import { Service } from '@deepseek-ai/cordis'
  30. import type { Context } from '@deepseek-ai/cordis'
  31. import type {} from '@deepseek-ai/cordis-plugin-loader'
  32. import type { IndexInjection } from '@deepseek-ai/dsh-host-webserver'
  33. import { optionalStringArray, stripClientSuffix } from './client/manifest.ts'
  34. import type { WebBootBatch, WebBootBatchPhase, WebBootEntry, WebBootGraph } from './client/manifest.ts'
  35. export { stripClientSuffix } from './client/manifest.ts'
  36. export type {
  37. BootManifest, BootModuleRow, BootPluginRow, WebBootBatch, WebBootBatchPhase, WebBootEntry, WebBootGraph,
  38. } from './client/manifest.ts'
  39. declare module '@deepseek-ai/cordis' {
  40. interface Context {
  41. /** The web plugin table (provided by the client-modules node half). */
  42. clientModules: ClientModuleRegistry
  43. }
  44. }
  45. /** package.json `dsh.client` declaration fields, validated one by one after reading the file. */
  46. interface DshClientDeclaration {
  47. inject?: string[]
  48. platform: string
  49. /** Boot phase-one registration barrier; absent rows still ride the shared application batch. */
  50. immediately?: boolean
  51. /**
  52. * Exact module-table requests beyond the implicit client baseline. Any
  53. * specifier is valid, including subpaths such as `<pkg>/client`; each
  54. * importing package declares its own exceptional requests. A type-only
  55. * import is not a request because the transform erases it before resolution.
  56. * Absent means the package uses only the baseline externals.
  57. */
  58. external?: string[]
  59. }
  60. /** The declared fields a graph row carries, normalized (absent array declarations become empty). */
  61. interface WebBootRowFields {
  62. inject?: string[]
  63. /** Module specifiers the package requests from the module table. */
  64. external: string[]
  65. immediately: boolean
  66. }
  67. /** Filesystem baseline captured before a client artifact snapshot is read. */
  68. export interface ClientArtifactBaseline {
  69. /** Absolute path of the client bundle. */
  70. readonly path: string
  71. /** Bundle modification time in milliseconds. */
  72. readonly mtimeMs: number
  73. /** Bundle size in bytes. */
  74. readonly size: number
  75. }
  76. /** Resolved package metadata for one `dsh.client` package (cached per name, never expires). */
  77. interface PkgMeta extends WebBootRowFields {
  78. clientPath: string
  79. }
  80. /** Recovery instruction shared by grouped startup and steady-state bundle diagnostics. */
  81. const CLIENT_BUNDLE_BUILD_INSTRUCTION = 'run `pnpm run build` before launch'
  82. /** Missing built client export, retained as structured data for activation-error grouping. */
  83. class MissingClientBundleError extends Error {
  84. constructor(
  85. readonly packageName: string,
  86. readonly clientPath: string,
  87. cause: unknown,
  88. ) {
  89. super(
  90. [
  91. `client-modules: client bundle not found; ${CLIENT_BUNDLE_BUILD_INSTRUCTION}:`,
  92. ` package: ${packageName}`,
  93. ` path: ${clientPath}`,
  94. ].join('\n'),
  95. { cause },
  96. )
  97. }
  98. }
  99. /** Activation failures grouped by actionable package-build errors and unrelated failures. */
  100. class ClientPackageCompositionError extends AggregateError {
  101. constructor(failures: Error[]) {
  102. const missingBundles = failures.filter((error): error is MissingClientBundleError => error instanceof MissingClientBundleError)
  103. const otherFailures = failures.filter(error => !(error instanceof MissingClientBundleError))
  104. const packageNoun = failures.length === 1 ? 'package' : 'packages'
  105. const lines = [`client-modules: ${String(failures.length)} client ${packageNoun} failed to compose:`]
  106. if (missingBundles.length > 0) {
  107. lines.push(` client bundles not found; ${CLIENT_BUNDLE_BUILD_INSTRUCTION}:`)
  108. for (const error of missingBundles) {
  109. lines.push(` - package: ${error.packageName}`, ` path: ${error.clientPath}`)
  110. }
  111. }
  112. if (otherFailures.length > 0) {
  113. lines.push(' other failures:', ...otherFailures.map(error => ` - ${error.message}`))
  114. }
  115. super(failures, lines.join('\n'))
  116. }
  117. }
  118. /** One composed table row: the wire entry plus the resolved package metadata behind it. */
  119. interface WebPluginRecord {
  120. entry: WebBootEntry
  121. meta: PkgMeta
  122. /** Exact build artifact included in the startup batches. */
  123. bundle: Buffer
  124. /** Pre-read filesystem baseline handed to the HMR watcher. */
  125. baseline: ClientArtifactBaseline
  126. /** Optional authored source map snapshot; generated-file identity mapping is the fallback. */
  127. sourceMap?: { body: Buffer; parsed: Record<string, unknown> }
  128. }
  129. /** Fields shared by every generated combo response. */
  130. interface ComboArtifactBase {
  131. url: string
  132. rev: string
  133. entries: string[]
  134. script: Buffer
  135. }
  136. /** One generated combo response over an ordered list of plugin resources. */
  137. interface ComboArtifact extends ComboArtifactBase {
  138. sourceMap: Buffer
  139. sourceMapUrl: string
  140. }
  141. /** One generated initial-load response and its wire descriptor. */
  142. type BatchArtifact = ComboArtifact & { descriptor: WebBootBatch }
  143. /** Versioned code is immutable; mismatched revisions are rejected instead of serving newer bytes. */
  144. const IMMUTABLE_CACHE = 'public, max-age=31536000, immutable'
  145. /** Generated request URLs stay below conservative browser and intermediary request-target limits. */
  146. const MAX_COMBO_URL_BYTES = 3 * 1024
  147. const HASH_REVISION_LENGTH = 12
  148. const COMBO_REVISION_PLACEHOLDER = '0'.repeat(HASH_REVISION_LENGTH)
  149. /** Source-map trailer emitted by tsdown at the end of every client bundle. */
  150. const SOURCE_MAP_TRAILER = /(?:\r?\n)?\/\/# sourceMappingURL=[^\r\n]*(?:\r?\n)?$/
  151. /** Debugger source name appended to page bundles in the WebWorker image. */
  152. const SOURCE_URL_TRAILER = /(?:\r?\n)?\/\/# sourceURL=([^\r\n]+)(?:\r?\n)?$/
  153. /** Narrow an unknown parsed JSON value to the `dsh.client` declaration, throwing on malformed fields. */
  154. function parseDshClient(pkgName: string, value: unknown): DshClientDeclaration | undefined {
  155. if (value === undefined) return undefined
  156. if (typeof value !== 'object' || value === null) {
  157. throw new Error(`client-modules: ${pkgName} has a non-object dsh.client declaration`)
  158. }
  159. const decl = value as Record<string, unknown>
  160. if (typeof decl.platform !== 'string') {
  161. throw new Error(`client-modules: ${pkgName} dsh.client.platform must be a string`)
  162. }
  163. const inject = optionalStringArray(pkgName, 'dsh.client.inject', decl.inject)
  164. const external = optionalStringArray(pkgName, 'dsh.client.external', decl.external)
  165. if (decl.immediately !== undefined && typeof decl.immediately !== 'boolean') {
  166. throw new Error(`client-modules: ${pkgName} dsh.client.immediately must be a boolean`)
  167. }
  168. return {
  169. platform: decl.platform,
  170. ...(inject !== undefined ? { inject } : {}),
  171. ...(external !== undefined ? { external } : {}),
  172. ...(decl.immediately !== undefined ? { immediately: decl.immediately } : {}),
  173. }
  174. }
  175. /** Resolve `exports["./client"]` to a relative path, accepting the string and one-level conditional forms. */
  176. function clientExportOf(pkgName: string, exportsField: unknown): string | undefined {
  177. if (typeof exportsField !== 'object' || exportsField === null) return undefined
  178. const client = (exportsField as Record<string, unknown>)['./client']
  179. if (client === undefined) return undefined
  180. if (typeof client === 'string') return client
  181. if (typeof client === 'object' && client !== null) {
  182. const fallback = (client as Record<string, unknown>).default
  183. if (typeof fallback === 'string') return fallback
  184. }
  185. throw new Error(`client-modules: ${pkgName} exports["./client"] must be a string or an object with a string default`)
  186. }
  187. /** sha1 content hash shortened to 12 hex chars (combo / graph / rebuilt-artifact rev). */
  188. function shortHash(input: string | Buffer): string {
  189. return createHash('sha1').update(input).digest('hex').slice(0, HASH_REVISION_LENGTH)
  190. }
  191. /** Hash several response fields without allowing bytes to move across field boundaries. */
  192. function framedHash(domain: string, parts: readonly Buffer[]): string {
  193. const hash = createHash('sha1').update(domain).update('\0')
  194. for (const part of parts) hash.update(`${String(part.byteLength)}:`).update(part)
  195. return hash.digest('hex').slice(0, HASH_REVISION_LENGTH)
  196. }
  197. /** Hash every artifact input served after HMR observes one plugin change. */
  198. function artifactRevision(bundle: Buffer, sourceMap: WebPluginRecord['sourceMap']): string {
  199. return framedHash('plugin-artifact', sourceMap === undefined ? [bundle] : [bundle, sourceMap.body])
  200. }
  201. /** Address one ordered plugin-file list through the shared combo route. */
  202. function comboUrl(ids: readonly string[], rev: string, sourceMap = false): string {
  203. const resources = ids.map(id => `${id}/client.js${sourceMap ? '.map' : ''}`).join(',')
  204. return `/plugins/??${resources}&rev=${rev}`
  205. }
  206. /** Measure the longer map-form URL used to partition a startup resource list. */
  207. function projectedComboUrlBytes(records: readonly WebPluginRecord[]): number {
  208. return Buffer.byteLength(comboUrl(
  209. records.map(record => record.entry.id),
  210. COMBO_REVISION_PLACEHOLDER,
  211. true,
  212. ))
  213. }
  214. /** Partition one phase in graph order without allowing a generated URL above the protocol limit. */
  215. function partitionComboRecords(records: readonly WebPluginRecord[]): WebPluginRecord[][] {
  216. const chunks: WebPluginRecord[][] = []
  217. let current: WebPluginRecord[] = []
  218. for (const record of records) {
  219. const candidate = [...current, record]
  220. if (projectedComboUrlBytes(candidate) <= MAX_COMBO_URL_BYTES) {
  221. current = candidate
  222. continue
  223. }
  224. if (current.length === 0) {
  225. throw new Error(
  226. `client-modules: ${record.entry.id} exceeds the ${String(MAX_COMBO_URL_BYTES)}-byte combo URL limit`,
  227. )
  228. }
  229. chunks.push(current)
  230. current = [record]
  231. if (projectedComboUrlBytes(current) > MAX_COMBO_URL_BYTES) {
  232. throw new Error(
  233. `client-modules: ${record.entry.id} exceeds the ${String(MAX_COMBO_URL_BYTES)}-byte combo URL limit`,
  234. )
  235. }
  236. }
  237. if (current.length > 0) chunks.push(current)
  238. return chunks
  239. }
  240. /** Executable source plus the generated-file name used when no authored map exists. */
  241. interface ComboSource {
  242. source: string
  243. fallbackSource: string
  244. }
  245. /** Remove bundle-local debug directives and retain their stable generated-file name. */
  246. function comboSource(record: WebPluginRecord): ComboSource {
  247. let source = record.bundle.toString('utf8')
  248. const sourceUrl = SOURCE_URL_TRAILER.exec(source)?.[1]
  249. source = source.replace(SOURCE_URL_TRAILER, '').replace(SOURCE_MAP_TRAILER, '')
  250. if (!source.endsWith('\n')) source += '\n'
  251. const fallbackSource = sourceUrl === undefined
  252. ? `/plugins/${record.entry.id}/client.js`
  253. : /^(?:[A-Za-z][A-Za-z\d+.-]*:|\/)/.test(sourceUrl) ? sourceUrl : `/${sourceUrl}`
  254. return { source, fallbackSource }
  255. }
  256. /** Stamp a combo script's absolute indexed-map URL onto its executable bytes. */
  257. function comboScript(input: string, sourceMapUrl?: string): Buffer {
  258. return Buffer.from(sourceMapUrl === undefined ? input : `${input}//# sourceMappingURL=${sourceMapUrl}\n`)
  259. }
  260. /** Parse an optional source-map artifact; missing maps do not prevent plugin execution. */
  261. function sourceMapSnapshot(clientPath: string): WebPluginRecord['sourceMap'] {
  262. let body: Buffer
  263. try {
  264. body = readFileSync(`${clientPath}.map`)
  265. } catch (error) {
  266. if ((error as NodeJS.ErrnoException).code === 'ENOENT') return undefined
  267. throw error
  268. }
  269. const value = JSON.parse(body.toString('utf8')) as unknown
  270. const parsed = typeof value === 'object' && value !== null ? value as Record<string, unknown> : undefined
  271. if (
  272. parsed === undefined
  273. || parsed.version !== 3
  274. || !Array.isArray(parsed.sources)
  275. || parsed.sources.some(source => typeof source !== 'string')
  276. || !Array.isArray(parsed.names)
  277. || parsed.names.some(name => typeof name !== 'string')
  278. || typeof parsed.mappings !== 'string'
  279. ) {
  280. throw new Error(`client-modules: ${clientPath}.map is not a regular Source Map v3 object`)
  281. }
  282. return { body, parsed }
  283. }
  284. /** Count generated lines while assembling indexed-map section offsets. */
  285. function newlineCount(value: string): number {
  286. let count = 0
  287. for (const char of value) if (char === '\n') count += 1
  288. return count
  289. }
  290. /** Resolve section sources against their original per-plugin map URL before combo relocation. */
  291. function comboSectionMap(record: WebPluginRecord): Record<string, unknown> {
  292. const original = record.sourceMap?.parsed
  293. /* v8 ignore next -- callers add sections only for records with a source map. */
  294. if (original === undefined) throw new Error(`client-modules: source map missing for ${record.entry.id}`)
  295. const sourcePaths = original.sources as string[]
  296. const sourceRoot = typeof original.sourceRoot === 'string' ? original.sourceRoot : ''
  297. const base = new URL(`/plugins/${record.entry.id}/client.js.map`, 'http://dsh.invalid')
  298. const relocated = sourcePaths.map((source) => {
  299. const separator = sourceRoot !== '' && !sourceRoot.endsWith('/') && !source.startsWith('/') ? '/' : ''
  300. const resolved = new URL(`${sourceRoot}${separator}${source}`, base)
  301. return resolved.origin === base.origin
  302. ? `${resolved.pathname}${resolved.search}${resolved.hash}`
  303. : resolved.href
  304. })
  305. const section: Record<string, unknown> = { ...original, sources: relocated }
  306. delete section.sourceRoot
  307. return section
  308. }
  309. /** Map each generated line to the same line in a bundled JavaScript source. */
  310. function identitySectionMap(source: string, sourceUrl: string): Record<string, unknown> {
  311. const mappings = Array.from({ length: newlineCount(source) }, (_, index) => index === 0 ? 'AAAA' : 'AACA')
  312. .join(';')
  313. return {
  314. version: 3,
  315. names: [],
  316. sources: [sourceUrl],
  317. sourcesContent: [source],
  318. mappings,
  319. }
  320. }
  321. /** Concatenate one or more factory registrations and compose their maps as indexed sections. */
  322. function buildCombo(records: readonly WebPluginRecord[], revision?: string): ComboArtifact {
  323. let source = ''
  324. const sections: { offset: { line: number; column: 0 }; map: Record<string, unknown> }[] = []
  325. let line = 0
  326. for (const record of records) {
  327. const prepared = comboSource(record)
  328. const section = record.sourceMap === undefined
  329. ? identitySectionMap(prepared.source, prepared.fallbackSource)
  330. : comboSectionMap(record)
  331. sections.push({ offset: { line, column: 0 }, map: section })
  332. const bundle = `${prepared.source};\n`
  333. source += bundle
  334. line += newlineCount(bundle)
  335. }
  336. const sourceMap = Buffer.from(`${JSON.stringify({ version: 3, file: 'client.js', sections })}\n`)
  337. const sourceBytes = Buffer.from(source)
  338. const rev = revision ?? framedHash('combo', [sourceBytes, sourceMap])
  339. const entries = records.map(record => record.entry.id)
  340. const url = comboUrl(entries, rev)
  341. const sourceMapUrl = comboUrl(entries, rev, true)
  342. return { url, rev, entries, script: comboScript(source, sourceMapUrl), sourceMap, sourceMapUrl }
  343. }
  344. /** Add initial-load scheduling metadata to a combo artifact. */
  345. function buildBatch(phase: WebBootBatchPhase, records: readonly WebPluginRecord[]): BatchArtifact {
  346. const artifact = buildCombo(records)
  347. return {
  348. ...artifact,
  349. descriptor: { phase, url: artifact.url, rev: artifact.rev, entries: artifact.entries },
  350. }
  351. }
  352. /** Graph row for one bundle rev (url carries the rev as its cache-busting query). */
  353. function graphRow(id: string, rev: string, fields: WebBootRowFields): WebBootEntry {
  354. return {
  355. id,
  356. url: comboUrl([id], rev),
  357. rev,
  358. ...(fields.inject !== undefined ? { inject: fields.inject } : {}),
  359. ...(fields.immediately ? { immediately: true } : {}),
  360. ...(fields.external.length > 0 ? { external: fields.external } : {}),
  361. }
  362. }
  363. /**
  364. * Order composed rows so every requested dynamic package precedes its
  365. * consumers. An `external` specifier is either the package row it names
  366. * (`<pkg>/client` aliases the bare package) or a static-table name that adds no
  367. * graph edge.
  368. * @param entries - composed rows in scan order.
  369. * @returns the same rows reordered; scan order breaks every tie.
  370. * @throws {Error} when a row requests itself or when the module graph has a
  371. * cycle; the message lists the packages on it.
  372. */
  373. export function orderByModuleGraph(entries: readonly WebBootEntry[]): WebBootEntry[] {
  374. const rowsById = new Map<string, WebBootEntry>()
  375. for (const entry of entries) rowsById.set(entry.id, entry)
  376. const ordered: WebBootEntry[] = []
  377. const placed = new Set<string>()
  378. const open: string[] = []
  379. const visit = (entry: WebBootEntry): void => {
  380. if (placed.has(entry.id)) return
  381. const cycleStart = open.indexOf(entry.id)
  382. if (cycleStart !== -1) {
  383. throw new Error(
  384. `client-modules: module graph cycle ${[...open.slice(cycleStart), entry.id].join(' -> ')} `
  385. + '— a requested package row must precede its consumers, and factory-form CJS cannot deliver partial exports',
  386. )
  387. }
  388. open.push(entry.id)
  389. for (const name of entry.external ?? []) {
  390. const dependency = rowsById.get(name) ?? rowsById.get(stripClientSuffix(name))
  391. if (dependency === entry) {
  392. throw new Error(
  393. `client-modules: "${entry.id}" requests module "${name}" that it answers itself `
  394. + '— a row must not declare its own package in dsh.client.external',
  395. )
  396. }
  397. if (dependency !== undefined) visit(dependency)
  398. }
  399. open.pop()
  400. placed.add(entry.id)
  401. ordered.push(entry)
  402. }
  403. for (const entry of entries) visit(entry)
  404. return ordered
  405. }
  406. /** Bootstrap package whose ordinary client bundle supplies the module-system implementation. */
  407. const CLIENT_MODULES_ID = '@deepseek-ai/dsh-client-modules'
  408. /** Dynamic bundles grouped into the parser bootstrap batch before the Vite shell. */
  409. const PARSER_PRELOAD_IDS = [CLIENT_MODULES_ID] as const
  410. /**
  411. * The boot protocol as index injection rows. The inline registration queue
  412. * precedes the application-batch preload and the blocking bootstrap batch. Its
  413. * `create()` method materializes the modules
  414. * bundle, delegates construction to that bundle, and leaves the same facade
  415. * in live-registration mode. The graph global follows before the shell reads
  416. * it.
  417. * @param graph - the composed entry graph.
  418. * @returns head rows in execution order: queue script, application preloads,
  419. * blocking bootstrap scripts, graph global.
  420. */
  421. export function bootInjections(graph: WebBootGraph): IndexInjection[] {
  422. const bootstrapId = JSON.stringify(CLIENT_MODULES_ID)
  423. const queue = `(()=>{
  424. const pendingQueue=[]
  425. window.__ModuleLoader__={
  426. mode:"queue",
  427. pendingQueue,
  428. load(registration){pendingQueue.push(registration)},
  429. create(options){
  430. if(this.mode!=="queue")throw new Error("client-modules: window.__ModuleLoader__.create called after module-system boot")
  431. const index=pendingQueue.findIndex(registration=>registration.id===${bootstrapId})
  432. const registration=pendingQueue[index]
  433. if(registration===undefined)throw new Error("client-modules: HTML did not preload ${CLIENT_MODULES_ID}/client.js")
  434. pendingQueue.splice(index,1)
  435. const exports=registration.factory(specifier=>{
  436. throw new Error('client-modules: ${CLIENT_MODULES_ID}/client.js requested external "'+specifier+'" before the module system existed')
  437. })
  438. if(typeof exports!=="object"||exports===null||typeof exports.createClientModuleSystem!=="function"||typeof exports.apply!=="function"){
  439. throw new Error("client-modules: ${CLIENT_MODULES_ID}/client.js did not export the bootstrap module face")
  440. }
  441. return exports.createClientModuleSystem(this,{id:registration.id,exports},options)
  442. }
  443. }
  444. })()`
  445. const bootstrap = graph.batches.filter(batch => batch.phase === 'bootstrap')
  446. const application = graph.batches.filter(batch => batch.phase === 'application')
  447. const rows: IndexInjection[] = [{ kind: 'script', placement: 'head', text: queue }]
  448. for (const batch of application) {
  449. rows.push({ kind: 'script-preload', src: batch.url })
  450. }
  451. for (const batch of bootstrap) {
  452. rows.push({ kind: 'script-src', placement: 'head', src: batch.url })
  453. }
  454. rows.push({ kind: 'global', name: '__DSH_BOOT__', value: graph })
  455. return rows
  456. }
  457. /**
  458. * The web plugin table service: incremental `dsh.client` scan + wire composition
  459. * + bundle route + index injection rows. Construction runs the activation scan
  460. * synchronously — a malformed declaration or missing bundle among the
  461. * already-loaded entries aggregates into one loud throw (FAILED fiber; the
  462. * boot activation audit reports it).
  463. */
  464. export class ClientModuleRegistry extends Service {
  465. static inject = ['webServer', 'loader']
  466. private readonly table = new Map<string, WebPluginRecord>()
  467. // Negative verdicts (unresolvable specifier — builtins like cordis:include,
  468. // subpath rows — or a package without a web `dsh.client` declaration) are
  469. // cached as null and never expire: plugin-set changes take effect on restart.
  470. private readonly pkgMeta = new Map<string, PkgMeta | null>()
  471. private readonly rebuildListeners = new Set<(id: string, rev: string) => void>()
  472. private readonly graphListeners = new Set<() => void>()
  473. private readonly dirty = new Set<string>()
  474. private readonly resolvePkgJson: (spec: string) => string
  475. private readonly initialRevisionNonce = randomBytes(8).toString('hex')
  476. private nextInitialRevision = 0
  477. private responses = new Map<string, { body: Buffer; contentType: string }>()
  478. private batchResponses = new Map<string, { body: Buffer; contentType: string }>()
  479. /** One prior graph generation covers a request racing the HMR recomposition that replaced its URL. */
  480. private previousBatchResponses = new Map<string, { body: Buffer; contentType: string }>()
  481. private flushQueued = false
  482. private composed: WebBootGraph
  483. /**
  484. * Build the service: subscribe, seed, and run the activation flush.
  485. * @param ctx - plugin context carrying webServer and loader.
  486. */
  487. constructor(ctx: Context) {
  488. super(ctx, 'clientModules')
  489. // Resolution anchor: the config tree's baseUrl (the cordis.yml directory,
  490. // whose package declares every composed plugin as a dependency). The
  491. // modules package's own URL would miss sibling packages under pnpm's
  492. // isolated node_modules.
  493. if (ctx.baseUrl === undefined) {
  494. throw new Error('client-modules: ctx.baseUrl is unset — the node half needs the config-tree anchor to resolve plugin packages')
  495. }
  496. const require = createRequire(ctx.baseUrl)
  497. this.resolvePkgJson = spec => require.resolve(`${spec}/package.json`)
  498. // Subscribe before seeding so a fiber arriving mid-activation lands in the
  499. // same dirty set (Set idempotence makes the overlap harmless). An entry-less
  500. // fiber is a child plugin or a manual mount — never a loader row; O(1) drop.
  501. ctx.on('internal/plugin', (fiber) => {
  502. const entryName = fiber.entry?.options.name
  503. if (entryName === undefined) return
  504. this.dirty.add(entryName)
  505. if (this.flushQueued) return
  506. this.flushQueued = true
  507. queueMicrotask(() => {
  508. this.flushQueued = false
  509. this.flush((err) => { ctx.logger.warn(err) })
  510. })
  511. })
  512. // Activation pass: the initial scan IS the incremental path over the
  513. // current entries, flushed synchronously (nothing async between subscribe,
  514. // seed, and flush).
  515. for (const entry of ctx.loader.entries()) this.dirty.add(entry.options.name)
  516. this.composed = this.compose()
  517. const failures: Error[] = []
  518. this.flush(err => failures.push(err))
  519. if (failures.length > 0) {
  520. throw new ClientPackageCompositionError(failures)
  521. }
  522. ctx.effect(
  523. () => ctx.webServer.register({ kind: 'prefix', path: '/plugins', handler: this.serveBundle }),
  524. 'client-modules: bundle route',
  525. )
  526. ctx.on('webserver/index-inject', (table) => {
  527. table.push(...bootInjections(this.composed))
  528. })
  529. }
  530. /**
  531. * Current composed entry graph (stable object between changes).
  532. * @returns the graph served as `window.__DSH_BOOT__`.
  533. */
  534. graph(): WebBootGraph {
  535. return this.composed
  536. }
  537. /**
  538. * Absolute path of an entry's client bundle.
  539. * @param id - entry id (package name).
  540. * @returns the path, or undefined for an unknown id.
  541. */
  542. clientPath(id: string): string | undefined {
  543. return this.table.get(id)?.meta.clientPath
  544. }
  545. /**
  546. * Filesystem baseline captured before an entry's current bytes were read.
  547. * HMR compares it with the live files when installing a watch, so a write
  548. * between startup composition and watch installation cannot disappear into
  549. * the watcher's initial state.
  550. * @param id - entry id (package name).
  551. * @returns the path and baseline, or undefined for an unknown id.
  552. */
  553. artifactBaseline(id: string): ClientArtifactBaseline | undefined {
  554. const baseline = this.table.get(id)?.baseline
  555. return baseline === undefined ? undefined : { ...baseline }
  556. }
  557. /**
  558. * Re-hash one bundle (the HMR watch's registration hook — the only entry
  559. * point through which bundle content changes reach the graph).
  560. * @param id - entry id (package name).
  561. * @returns the new rev, or undefined for an unknown id.
  562. */
  563. rebuilt(id: string): string | undefined {
  564. const record = this.table.get(id)
  565. if (record === undefined) return undefined
  566. const baseline = this.captureArtifactBaseline(record.meta.clientPath)
  567. const bundle = readFileSync(record.meta.clientPath)
  568. const sourceMap = this.readSourceMapSnapshot(record.meta.clientPath)
  569. const rev = artifactRevision(bundle, sourceMap)
  570. record.baseline = baseline
  571. if (rev === record.entry.rev) return rev
  572. record.entry = graphRow(id, rev, record.meta)
  573. record.bundle = bundle
  574. if (sourceMap === undefined) delete record.sourceMap
  575. else record.sourceMap = sourceMap
  576. this.composed = this.compose()
  577. for (const notify of this.rebuildListeners) {
  578. // Containment: rebuilt() runs inside the HMR watch callback — a
  579. // throwing subscriber must not kill the poll or skip later subscribers.
  580. try {
  581. notify(id, rev)
  582. } catch (error) {
  583. this.ctx.logger.error(error)
  584. }
  585. }
  586. this.notifyGraphChanged()
  587. return rev
  588. }
  589. /**
  590. * Subscribe to bundle rebuilds; fires only when the re-hash changed the rev.
  591. * @param listener - receives the entry id and its new bundle rev.
  592. * @returns the unsubscriber.
  593. */
  594. onRebuilt(listener: (id: string, rev: string) => void): () => void {
  595. this.rebuildListeners.add(listener)
  596. return () => { this.rebuildListeners.delete(listener) }
  597. }
  598. /**
  599. * Fires after any flush that recomposed the graph (row added/removed, or a
  600. * rebuilt rev change). Pull model: listeners re-read {@link graph}.
  601. * @param listener - notified with no payload.
  602. * @returns the unsubscriber.
  603. */
  604. onGraphChanged(listener: () => void): () => void {
  605. this.graphListeners.add(listener)
  606. return () => { this.graphListeners.delete(listener) }
  607. }
  608. private compose(): WebBootGraph {
  609. const entries = orderByModuleGraph([...this.table.values()].map(record => record.entry))
  610. const bootstrap = PARSER_PRELOAD_IDS
  611. .map(id => this.table.get(id))
  612. .filter((record): record is WebPluginRecord => record !== undefined)
  613. const bootstrapIds = new Set(bootstrap.map(record => record.entry.id))
  614. const application = entries
  615. .filter(entry => !bootstrapIds.has(entry.id))
  616. .map(entry => this.table.get(entry.id))
  617. .filter((record): record is WebPluginRecord => record !== undefined)
  618. const artifacts: BatchArtifact[] = []
  619. for (const records of partitionComboRecords(bootstrap)) {
  620. artifacts.push(buildBatch('bootstrap', records))
  621. }
  622. for (const records of partitionComboRecords(application)) {
  623. artifacts.push(buildBatch('application', records))
  624. }
  625. const batchResponses = new Map<string, { body: Buffer; contentType: string }>()
  626. for (const artifact of artifacts) {
  627. batchResponses.set(artifact.descriptor.url, {
  628. body: artifact.script,
  629. contentType: 'text/javascript; charset=utf-8',
  630. })
  631. batchResponses.set(artifact.sourceMapUrl, {
  632. body: artifact.sourceMap,
  633. contentType: 'application/json; charset=utf-8',
  634. })
  635. }
  636. const responses = new Map(batchResponses)
  637. for (const record of this.table.values()) {
  638. const artifact = buildCombo([record], record.entry.rev)
  639. responses.set(artifact.url, {
  640. body: artifact.script,
  641. contentType: 'text/javascript; charset=utf-8',
  642. })
  643. responses.set(artifact.sourceMapUrl, {
  644. body: artifact.sourceMap,
  645. contentType: 'application/json; charset=utf-8',
  646. })
  647. }
  648. this.previousBatchResponses = this.batchResponses
  649. this.batchResponses = batchResponses
  650. this.responses = responses
  651. const batches = artifacts.map(artifact => artifact.descriptor)
  652. return { rev: shortHash(JSON.stringify({ entries, batches })), entries, batches }
  653. }
  654. private notifyGraphChanged(): void {
  655. for (const listener of this.graphListeners) {
  656. // A throwing subscriber must not skip later subscribers (or escape into
  657. // whatever triggered the flush — possibly an fs.watchFile callback).
  658. try {
  659. listener()
  660. } catch (error) {
  661. this.ctx.logger.error(error)
  662. }
  663. }
  664. }
  665. private resolveMeta(pkgName: string): PkgMeta | null {
  666. const cached = this.pkgMeta.get(pkgName)
  667. if (cached !== undefined) return cached
  668. let pkgPath: string
  669. try {
  670. pkgPath = this.resolvePkgJson(pkgName)
  671. } catch {
  672. // Not a resolvable package root: loader builtins (cordis:include) and
  673. // subpath entries (…/gateway) land here — permanently not a client row.
  674. this.pkgMeta.set(pkgName, null)
  675. return null
  676. }
  677. const pkg = JSON.parse(readFileSync(pkgPath, 'utf8')) as Record<string, unknown>
  678. const dsh = pkg.dsh
  679. const decl = parseDshClient(
  680. pkgName,
  681. dsh !== null && typeof dsh === 'object' ? (dsh as Record<string, unknown>).client : undefined,
  682. )
  683. if (decl === undefined || decl.platform !== 'web') {
  684. this.pkgMeta.set(pkgName, null)
  685. return null
  686. }
  687. const clientRel = clientExportOf(pkgName, pkg.exports)
  688. if (clientRel === undefined) {
  689. throw new Error(`client-modules: ${pkgName} declares dsh.client but exports no "./client" bundle`)
  690. }
  691. const meta: PkgMeta = {
  692. clientPath: join(dirname(pkgPath), clientRel),
  693. ...(decl.inject !== undefined ? { inject: decl.inject } : {}),
  694. external: decl.external ?? [],
  695. immediately: decl.immediately === true,
  696. }
  697. this.pkgMeta.set(pkgName, meta)
  698. return meta
  699. }
  700. /** Capture the bundle stats before reading its bytes. */
  701. private captureArtifactBaseline(clientPath: string): ClientArtifactBaseline {
  702. const bundle = statSync(clientPath)
  703. return {
  704. path: clientPath,
  705. mtimeMs: bundle.mtimeMs,
  706. size: bundle.size,
  707. }
  708. }
  709. /** Allocate an opaque initial row revision without inspecting artifact bytes. */
  710. private allocateInitialRevision(): string {
  711. return `${this.initialRevisionNonce}-${String(this.nextInitialRevision++)}`
  712. }
  713. /**
  714. * Read the activation-time bundle and optional source-map snapshots.
  715. * @param pkgName - package that declares the client bundle.
  716. * @param clientPath - absolute path of the built client artifact.
  717. * @returns the immutable bytes plus the pre-read filesystem baseline.
  718. * @throws {MissingClientBundleError} when the read fails with `ENOENT`; other filesystem errors are rethrown unchanged.
  719. */
  720. private initialBundleSnapshot(pkgName: string, clientPath: string): {
  721. bundle: Buffer
  722. baseline: ClientArtifactBaseline
  723. sourceMap?: WebPluginRecord['sourceMap']
  724. } {
  725. try {
  726. const baseline = this.captureArtifactBaseline(clientPath)
  727. const bundle = readFileSync(clientPath)
  728. const sourceMap = this.readSourceMapSnapshot(clientPath)
  729. return { bundle, baseline, ...(sourceMap === undefined ? {} : { sourceMap }) }
  730. } catch (error) {
  731. if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error
  732. throw new MissingClientBundleError(pkgName, clientPath, error)
  733. }
  734. }
  735. /** Treat a missing, torn, or malformed development map as an identity-mapped artifact revision. */
  736. private readSourceMapSnapshot(clientPath: string): WebPluginRecord['sourceMap'] {
  737. try {
  738. return sourceMapSnapshot(clientPath)
  739. } catch (error) {
  740. this.ctx.logger.warn(error)
  741. return undefined
  742. }
  743. }
  744. /** Reconcile one entry name against the live loader entries. @returns whether the table changed. */
  745. private processOne(entryName: string): boolean {
  746. let qualifies = false
  747. for (const entry of this.ctx.loader.entries()) {
  748. if (entry.options.name === entryName && entry.fiber !== undefined && !entry.disabled) {
  749. qualifies = true
  750. break
  751. }
  752. }
  753. if (!qualifies) return this.table.delete(entryName)
  754. if (this.table.has(entryName)) return false
  755. const meta = this.resolveMeta(entryName)
  756. if (meta === null) return false
  757. // The opaque initial rev rides the row until HMR observes a file change;
  758. // a fiber restart reuses the existing row without inspecting bytes.
  759. const snapshot = this.initialBundleSnapshot(entryName, meta.clientPath)
  760. const rev = this.allocateInitialRevision()
  761. this.table.set(entryName, {
  762. entry: graphRow(entryName, rev, meta),
  763. meta,
  764. bundle: snapshot.bundle,
  765. baseline: snapshot.baseline,
  766. ...(snapshot.sourceMap === undefined ? {} : { sourceMap: snapshot.sourceMap }),
  767. })
  768. return true
  769. }
  770. private flush(onError: (err: Error) => void): void {
  771. let changed = false
  772. for (const entryName of [...this.dirty]) {
  773. this.dirty.delete(entryName)
  774. try {
  775. if (this.processOne(entryName)) changed = true
  776. } catch (error) {
  777. // Steady state: one broken package must not poison the others; the
  778. // activation pass aggregates these into a loud throw instead.
  779. onError(error instanceof Error ? error : new Error(String(error)))
  780. }
  781. }
  782. if (!changed) return
  783. let composed: WebBootGraph
  784. try {
  785. composed = this.compose()
  786. } catch (error) {
  787. // An unorderable module graph is a property of the whole table, not of
  788. // the arriving package, so it surfaces here: aggregated into the
  789. // activation throw, or warned in steady state while the last orderable
  790. // graph stays served.
  791. onError(error as Error)
  792. return
  793. }
  794. this.composed = composed
  795. this.notifyGraphChanged()
  796. }
  797. private readonly serveBundle = (req: IncomingMessage, res: ServerResponse): void => {
  798. if (req.method !== 'GET' && req.method !== 'HEAD') {
  799. res.writeHead(405)
  800. res.end()
  801. return
  802. }
  803. /* v8 ignore next -- `?? '/'` arm: node:http always sets url on server requests. */
  804. const requestUrl = new URL(req.url ?? '/', 'http://x')
  805. const resourceUrl = `${requestUrl.pathname}${requestUrl.search}`
  806. const response = this.responses.get(resourceUrl) ?? this.previousBatchResponses.get(resourceUrl)
  807. if (response !== undefined) {
  808. res.writeHead(200, {
  809. 'content-type': response.contentType,
  810. 'cache-control': IMMUTABLE_CACHE,
  811. })
  812. res.end(req.method === 'HEAD' ? undefined : response.body)
  813. return
  814. }
  815. // Anything else under /plugins (including unadvertised combinations and
  816. // /plugins/events when the HMR row is absent) is an unknown resource.
  817. res.writeHead(404)
  818. res.end()
  819. }
  820. }
  821. export default ClientModuleRegistry