loader.client.spec.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  1. // @vitest-environment jsdom
  2. /**
  3. * ClientModuleSystem behavior: lazy CJS arrival (bundle execution only
  4. * registers the factory), materialization on first import/require with
  5. * memoization and recursive self-sequencing, the resolution branch order,
  6. * shared in-flight arrival, invalidate-refetch (HMR), style claiming, the
  7. * default transport hook, and the loud failure modes (duplicate
  8. * registration, cycles, table misses, double boot).
  9. */
  10. import { Context } from '@deepseek-ai/cordis'
  11. import { afterEach, describe, expect, it, vi } from 'vitest'
  12. import {
  13. apply, createClientModuleSystem, parseBootManifest,
  14. type BootModuleRow, type ClientBundleRegistration, type ClientModuleCreateOptions,
  15. type ClientModuleLoader, type ClientModuleLoaderTarget, type DshWindow,
  16. } from '../src/client/index.ts'
  17. const MODULES_ID = '@deepseek-ai/dsh-client-modules'
  18. const win = globalThis as DshWindow
  19. const bootstrapExports = { apply, createClientModuleSystem }
  20. type Factory = ClientBundleRegistration['factory']
  21. afterEach(() => {
  22. vi.unstubAllGlobals()
  23. delete win.__ModuleLoader__
  24. for (const el of document.querySelectorAll('style, script')) el.remove()
  25. })
  26. const row = (id: string, fields: Partial<BootModuleRow> = {}): BootModuleRow =>
  27. ({ id, url: `/plugins/${id}/client.js?rev=0`, rev: '0', external: [], ...fields })
  28. interface Bench {
  29. loader: ClientModuleLoader
  30. target: ClientModuleLoaderTarget
  31. fetched: string[]
  32. gates: Map<string, () => void>
  33. }
  34. /** Build the page-global facade shape consumed by the module system. */
  35. function registrationTarget(pending: ClientBundleRegistration[] = []): ClientModuleLoaderTarget {
  36. const pendingQueue = [...pending]
  37. const target: ClientModuleLoaderTarget = {
  38. mode: 'queue',
  39. pendingQueue,
  40. load: (registration) => { pendingQueue.push(registration) },
  41. create: options => createClientModuleSystem(target, {
  42. id: MODULES_ID,
  43. exports: bootstrapExports,
  44. }, options),
  45. }
  46. return target
  47. }
  48. /**
  49. * Loader over scripted bundles: load records the row URL, optionally waits on
  50. * a release callback, then registers the scripted factory through the window
  51. * sink (`null` scripts a bundle that never calls load).
  52. */
  53. function bench(
  54. entries: BootModuleRow[],
  55. bundles: Record<string, Factory | null> = {},
  56. opts: {
  57. seed?: Record<string, unknown>
  58. gated?: string[]
  59. pending?: ClientBundleRegistration[]
  60. defaultTransport?: boolean
  61. } = {},
  62. ): Bench {
  63. const fetched: string[] = []
  64. const gates = new Map<string, () => void>()
  65. const target = registrationTarget(opts.pending)
  66. win.__ModuleLoader__ = target
  67. const loadBundle = async (url: string): Promise<void> => {
  68. fetched.push(url)
  69. if (opts.gated?.includes(url) === true) {
  70. await new Promise<void>((resolve) => { gates.set(url, resolve) })
  71. }
  72. const id = /\/plugins\/(.+)\/client\.js/.exec(url)?.[1]
  73. const factory = id === undefined ? undefined : bundles[id]
  74. if (factory == null || id === undefined) return
  75. win.__ModuleLoader__?.load({ id, factory })
  76. }
  77. const loader = target.create({
  78. boot: { rev: 'graph', entries },
  79. staticModules: opts.seed ?? {},
  80. ...(opts.defaultTransport === true ? {} : { loadBundle }),
  81. })
  82. return { loader, target, fetched, gates }
  83. }
  84. describe('Cordis plugin face', () => {
  85. it('rejects activation before the HTML facade creates the module system', () => {
  86. expect(() => { apply(new Context()) }).toThrow('createClientModuleSystem must run before plugin boot')
  87. })
  88. })
  89. describe('lazy CJS arrival', () => {
  90. it('drains registrations queued by parser-blocking preload scripts into the same live facade', async () => {
  91. const b = bench([row('runtime')], {}, {
  92. pending: [{ id: 'runtime', factory: () => ({ marker: 'preloaded' }) }],
  93. })
  94. const exports = await b.loader.import('runtime', '', {})
  95. expect((exports as { marker: string }).marker).toBe('preloaded')
  96. expect(b.target.pendingQueue).toEqual([])
  97. expect(b.fetched).toEqual([])
  98. expect(win.__ModuleLoader__).toBe(b.target)
  99. expect(b.target.mode).toBe('live')
  100. })
  101. it('prefetch loads and registers but does not run the factory', async () => {
  102. const ran: string[] = []
  103. const b = bench([row('a')], { a: () => { ran.push('a'); return {} } })
  104. await b.loader.prefetch('a')
  105. expect(b.fetched).toEqual(['/plugins/a/client.js?rev=0'])
  106. expect(ran).toEqual([])
  107. expect(b.loader.loadCache.has('a')).toBe(false)
  108. })
  109. it('import materializes once and memoizes the exports', async () => {
  110. const ran: string[] = []
  111. const b = bench([row('a')], { a: () => { ran.push('a'); return { marker: 'a' } } })
  112. const first = await b.loader.import('a', '', {})
  113. const second = await b.loader.import('a', '', {})
  114. expect(first).toBe(second)
  115. expect((first as { marker: string }).marker).toBe('a')
  116. expect(ran).toEqual(['a'])
  117. expect(b.loader.loadCache.get('a')?.id).toBe('a')
  118. })
  119. it('import without prefetch loads, registers, and materializes in one call', async () => {
  120. const b = bench([row('a')], { a: () => ({ marker: 'direct' }) })
  121. const exports = await b.loader.import('a', '', {})
  122. expect((exports as { marker: string }).marker).toBe('direct')
  123. expect(b.fetched).toHaveLength(1)
  124. })
  125. it('registers declared dynamic requests before materializing their consumer', async () => {
  126. const b = bench([
  127. row('consumer', { external: ['provider/client', 'react'] }),
  128. row('provider'),
  129. ], {
  130. consumer: req => ({ provider: req('provider/client'), react: req('react') }),
  131. provider: () => ({ marker: 'provider' }),
  132. }, { seed: { react: { marker: 'react' } } })
  133. const exports = await b.loader.import('consumer', '', {}) as {
  134. provider: { marker: string }
  135. react: { marker: string }
  136. }
  137. expect(b.fetched).toEqual([
  138. '/plugins/provider/client.js?rev=0',
  139. '/plugins/consumer/client.js?rev=0',
  140. ])
  141. expect(exports.provider.marker).toBe('provider')
  142. expect(exports.react.marker).toBe('react')
  143. })
  144. it('concurrent callers share one in-flight arrival and materialize once', async () => {
  145. const ran: string[] = []
  146. const url = '/plugins/a/client.js?rev=0'
  147. const b = bench([row('a')], { a: () => { ran.push('a'); return { marker: 'a' } } }, { gated: [url] })
  148. const first = b.loader.import('a', '', {})
  149. const second = b.loader.import('a', '', {})
  150. const third = b.loader.prefetch('a')
  151. b.gates.get(url)?.()
  152. const [s1, s2] = await Promise.all([first, second, third])
  153. expect(s1).toBe(s2)
  154. expect(b.fetched).toEqual([url])
  155. expect(ran).toEqual(['a'])
  156. })
  157. it('prefetch after registration is a no-op without invalidate', async () => {
  158. const b = bench([row('a')], { a: () => ({}) })
  159. await b.loader.prefetch('a')
  160. await b.loader.prefetch('a')
  161. expect(b.fetched).toHaveLength(1)
  162. })
  163. })
  164. describe('require resolution', () => {
  165. it('a factory requiring a registered-but-unmaterialized module materializes it recursively', async () => {
  166. const order: string[] = []
  167. const b = bench([row('a'), row('b')], {
  168. a: (req) => {
  169. order.push('a')
  170. const dep = req('b/client') as { helper: string }
  171. return { got: dep.helper }
  172. },
  173. b: () => { order.push('b'); return { helper: 'from-b' } },
  174. })
  175. await b.loader.prefetch('a')
  176. await b.loader.prefetch('b')
  177. const exports = await b.loader.import('a', '', {})
  178. expect((exports as { got: string }).got).toBe('from-b')
  179. expect(order).toEqual(['a', 'b'])
  180. expect(b.loader.loadCache.get('a')?.edges.has('b/client')).toBe(true)
  181. expect(b.loader.loadCache.has('b')).toBe(true)
  182. })
  183. it('require prefers the platform seed word over the module table', async () => {
  184. const react = { marker: 'react' }
  185. const b = bench([row('a')], {
  186. a: req => ({ dep: req('react') }),
  187. }, { seed: { react } })
  188. const exports = await b.loader.import('a', '', {})
  189. expect((exports as { dep: unknown }).dep).toBe(react)
  190. expect(await b.loader.import('react', '', {})).toBe(react)
  191. expect(b.loader.loadCache.has('react')).toBe(false)
  192. })
  193. it('require answers an already-materialized module from the cache', async () => {
  194. let built = 0
  195. const b = bench([row('a'), row('c')], {
  196. a: req => ({ dep: req('c') }),
  197. c: () => { built += 1; return { marker: 'c' } },
  198. })
  199. const c = await b.loader.import('c', '', {})
  200. const a = await b.loader.import('a', '', {})
  201. expect((a as { dep: unknown }).dep).toBe(c)
  202. expect(built).toBe(1)
  203. })
  204. it('a require that misses the module table is loud', async () => {
  205. const b = bench([row('a')], { a: req => ({ dep: req('ghost') }) })
  206. await expect(b.loader.import('a', '', {})).rejects.toThrow('require("ghost") missed the module table')
  207. })
  208. it('a require cycle is fatal', async () => {
  209. const b = bench([row('a'), row('b')], {
  210. a: req => ({ dep: req('b') }),
  211. b: req => ({ dep: req('a') }),
  212. })
  213. await b.loader.prefetch('b')
  214. await expect(b.loader.import('a', '', {})).rejects.toThrow('require cycle through "a"')
  215. })
  216. })
  217. describe('bootstrap module', () => {
  218. it('caches the materialized modules exports under the package id and /client alias', async () => {
  219. const b = bench([
  220. row('consumer', { external: [`${MODULES_ID}/client`] }),
  221. row(MODULES_ID),
  222. ], {
  223. consumer: req => ({ dep: req(`${MODULES_ID}/client`) }),
  224. })
  225. await b.loader.prefetch(MODULES_ID)
  226. const exports = await b.loader.import('consumer', '', {}) as { dep: unknown }
  227. expect(exports.dep).toBe(bootstrapExports)
  228. expect(await b.loader.import(`${MODULES_ID}/client`, '', {})).toBe(bootstrapExports)
  229. expect(b.fetched).toEqual(['/plugins/consumer/client.js?rev=0'])
  230. })
  231. it('publishes the same closed-over system when the modules Cordis plugin activates', () => {
  232. const b = bench([])
  233. const ctx = new Context()
  234. apply(ctx)
  235. expect(ctx.modules).toBe(b.loader)
  236. })
  237. it('rejects a second queued registration for the bootstrap id', () => {
  238. expect(() => bench([], {}, {
  239. pending: [{ id: `${MODULES_ID}/client`, factory: () => ({}) }],
  240. })).toThrow(`duplicate factory registration for "${MODULES_ID}/client"`)
  241. })
  242. })
  243. describe('failure modes', () => {
  244. it('duplicate factory registration is loud', () => {
  245. bench([])
  246. win.__ModuleLoader__?.load({ id: 'x', factory: () => ({}) })
  247. expect(() => win.__ModuleLoader__?.load({ id: 'x', factory: () => ({}) }))
  248. .toThrow('duplicate factory registration for "x"')
  249. })
  250. it('a bundle that never registers its id is loud', async () => {
  251. const b = bench([row('a')], { a: null })
  252. await expect(b.loader.import('a', '', {})).rejects.toThrow('without registering "a"')
  253. })
  254. it('an unknown import specifier is loud', async () => {
  255. const b = bench([])
  256. await expect(b.loader.import('nope', '', {})).rejects.toThrow('cannot resolve "nope"')
  257. })
  258. it('an unknown prefetch id is loud', async () => {
  259. const b = bench([])
  260. await expect(b.loader.prefetch('nope')).rejects.toThrow('prefetch("nope") — not a graph entry')
  261. })
  262. it('a duplicate graph entry is loud at construction', () => {
  263. expect(() => bench([row('a'), row('a')])).toThrow('duplicate graph entry "a"')
  264. })
  265. it('a module arrival cycle is loud even if a malformed host graph reaches the browser', async () => {
  266. const b = bench([
  267. row('a', { external: ['b'] }),
  268. row('b', { external: ['a'] }),
  269. ])
  270. await expect(b.loader.prefetch('a')).rejects.toThrow('module arrival cycle a -> b -> a')
  271. })
  272. it('double boot is loud', () => {
  273. const b = bench([])
  274. const options: ClientModuleCreateOptions = {
  275. boot: { rev: 'graph', entries: [] },
  276. staticModules: {},
  277. }
  278. expect(() => b.target.create(options)).toThrow('create called after module-system boot')
  279. })
  280. })
  281. describe('boot manifest wire', () => {
  282. it('normalizes absent shared-module fields and carries the declared ones', () => {
  283. const manifest = parseBootManifest({
  284. rev: 'graph',
  285. entries: [
  286. { id: 'a', url: '/plugins/a/client.js', rev: '1' },
  287. { id: 'b', url: '/plugins/b/client.js', rev: '2', external: ['react'] },
  288. ],
  289. })
  290. expect(manifest.modules).toEqual([
  291. { id: 'a', url: '/plugins/a/client.js', rev: '1', external: [] },
  292. { id: 'b', url: '/plugins/b/client.js', rev: '2', external: ['react'] },
  293. ])
  294. })
  295. it('rejects a non-array external', () => {
  296. expect(() => parseBootManifest({
  297. rev: 'graph',
  298. entries: [{ id: 'a', url: '/a', rev: '1', external: 'react' }],
  299. })).toThrow('client-modules: boot manifest entry "a" external must be a string array')
  300. })
  301. })
  302. describe('HMR reset', () => {
  303. it('invalidate drops the factory and record so the module reloads and re-registers', async () => {
  304. let generation = 0
  305. const b = bench([row('a')], { a: () => ({ generation: ++generation }) })
  306. const first = await b.loader.import('a', '', {})
  307. b.loader.invalidate('a')
  308. expect(b.loader.loadCache.has('a')).toBe(false)
  309. await b.loader.prefetch('a')
  310. const second = await b.loader.import('a', '', {})
  311. expect(b.fetched).toHaveLength(2)
  312. expect((first as { generation: number }).generation).toBe(1)
  313. expect((second as { generation: number }).generation).toBe(2)
  314. })
  315. })
  316. describe('style claiming', () => {
  317. it('claims untagged style tags for the materializing plugin and inventories owned css ids', async () => {
  318. const foreign = document.createElement('style')
  319. foreign.setAttribute('data-plugin', 'other')
  320. document.head.appendChild(foreign)
  321. const b = bench([row('a')], {
  322. a: () => {
  323. document.head.appendChild(document.createElement('style'))
  324. const tagged = document.createElement('style')
  325. tagged.setAttribute('data-plugin', 'a')
  326. tagged.setAttribute('data-plugin-css', 'sheet-1')
  327. document.head.appendChild(tagged)
  328. return {}
  329. },
  330. })
  331. await b.loader.import('a', '', {})
  332. expect(b.loader.loadCache.get('a')?.styles).toEqual(['a', 'sheet-1'])
  333. expect(document.querySelectorAll('style[data-plugin="a"]')).toHaveLength(2)
  334. expect(foreign.getAttribute('data-plugin')).toBe('other')
  335. })
  336. it('materialization without a document skips the style inventory', async () => {
  337. const b = bench([row('a')], { a: () => ({}) })
  338. vi.stubGlobal('document', undefined)
  339. try {
  340. await b.loader.import('a', '', {})
  341. } finally {
  342. vi.unstubAllGlobals()
  343. }
  344. expect(b.loader.loadCache.get('a')?.styles).toEqual([])
  345. })
  346. })
  347. describe('default transport seam', () => {
  348. it('loads through an external classic script and removes the settled node', async () => {
  349. const append = vi.spyOn(document.head, 'append').mockImplementation((...nodes) => {
  350. const script = nodes[0]
  351. if (!(script instanceof HTMLScriptElement)) throw new Error('expected script node')
  352. expect(script.async).toBe(true)
  353. expect(script.getAttribute('src')).toBe('/plugins/dee/client.js?rev=0')
  354. queueMicrotask(() => {
  355. win.__ModuleLoader__?.load({ id: 'dee', factory: () => ({ marker: 'via-script' }) })
  356. script.dispatchEvent(new Event('load'))
  357. })
  358. })
  359. const b = bench([row('dee')], {}, { defaultTransport: true })
  360. const exports = await b.loader.import('dee', '', {})
  361. expect((exports as { marker: string }).marker).toBe('via-script')
  362. expect(append).toHaveBeenCalledOnce()
  363. expect([...document.querySelectorAll('script')]).toEqual([])
  364. })
  365. it('a script load failure is loud and removes the node', async () => {
  366. vi.spyOn(document.head, 'append').mockImplementation((...nodes) => {
  367. const script = nodes[0]
  368. if (!(script instanceof HTMLScriptElement)) throw new Error('expected script node')
  369. queueMicrotask(() => { script.dispatchEvent(new Event('error')) })
  370. })
  371. const b = bench([row('dee')], {}, { defaultTransport: true })
  372. await expect(b.loader.prefetch('dee')).rejects.toThrow(
  373. 'bundle script /plugins/dee/client.js?rev=0 failed to load',
  374. )
  375. expect([...document.querySelectorAll('script')]).toEqual([])
  376. })
  377. })