loader.client.spec.ts 15 KB

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