loader.spec.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  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 { afterEach, describe, expect, it, vi } from 'vitest'
  11. import {
  12. ClientModuleSystem,
  13. type BootModuleRow, type ClientModuleLoader, type ClientPluginHandoff, type DshWindow,
  14. } from '../src/client/index.ts'
  15. const win = globalThis as DshWindow
  16. type Factory = ClientPluginHandoff['factory']
  17. afterEach(() => {
  18. vi.unstubAllGlobals()
  19. delete win.__ModuleLoader__
  20. for (const el of document.querySelectorAll('style, script')) el.remove()
  21. })
  22. const row = (id: string): BootModuleRow => ({ id, url: `/plugins/${id}/client.js?rev=0`, rev: '0' })
  23. interface Bench {
  24. loader: ClientModuleLoader
  25. fetched: string[]
  26. gates: Map<string, () => void>
  27. }
  28. /**
  29. * Loader over scripted bundles: load records the row URL, optionally waits on
  30. * a release callback, then registers the scripted factory through the window
  31. * sink (`null` scripts a bundle that never calls load).
  32. */
  33. function bench(
  34. entries: BootModuleRow[],
  35. bundles: Record<string, Factory | null> = {},
  36. opts: { seed?: Record<string, unknown>; gated?: string[] } = {},
  37. ): Bench {
  38. const fetched: string[] = []
  39. const gates = new Map<string, () => void>()
  40. const loader = new ClientModuleSystem({
  41. modules: entries,
  42. staticModules: opts.seed ?? {},
  43. loadBundle: async (url) => {
  44. fetched.push(url)
  45. if (opts.gated?.includes(url) === true) {
  46. await new Promise<void>((resolve) => { gates.set(url, resolve) })
  47. }
  48. const id = /\/plugins\/(.+)\/client\.js/.exec(url)?.[1]
  49. const factory = id === undefined ? undefined : bundles[id]
  50. if (factory == null || id === undefined) return
  51. win.__ModuleLoader__?.load({ id, factory })
  52. },
  53. })
  54. return { loader, fetched, gates }
  55. }
  56. describe('lazy CJS arrival', () => {
  57. it('prefetch loads and registers but does not run the factory', async () => {
  58. const ran: string[] = []
  59. const b = bench([row('a')], { a: () => { ran.push('a'); return {} } })
  60. await b.loader.prefetch('a')
  61. expect(b.fetched).toEqual(['/plugins/a/client.js?rev=0'])
  62. expect(ran).toEqual([])
  63. expect(b.loader.loadCache.size).toBe(0)
  64. })
  65. it('import materializes once and memoizes the exports', async () => {
  66. const ran: string[] = []
  67. const b = bench([row('a')], { a: () => { ran.push('a'); return { marker: 'a' } } })
  68. const first = await b.loader.import('a', '', {})
  69. const second = await b.loader.import('a', '', {})
  70. expect(first).toBe(second)
  71. expect((first as { marker: string }).marker).toBe('a')
  72. expect(ran).toEqual(['a'])
  73. expect(b.loader.loadCache.get('a')?.id).toBe('a')
  74. })
  75. it('import without prefetch loads, registers, and materializes in one call', async () => {
  76. const b = bench([row('a')], { a: () => ({ marker: 'direct' }) })
  77. const exports = await b.loader.import('a', '', {})
  78. expect((exports as { marker: string }).marker).toBe('direct')
  79. expect(b.fetched).toHaveLength(1)
  80. })
  81. it('concurrent callers share one in-flight arrival and materialize once', async () => {
  82. const ran: string[] = []
  83. const url = '/plugins/a/client.js?rev=0'
  84. const b = bench([row('a')], { a: () => { ran.push('a'); return { marker: 'a' } } }, { gated: [url] })
  85. const first = b.loader.import('a', '', {})
  86. const second = b.loader.import('a', '', {})
  87. const third = b.loader.prefetch('a')
  88. b.gates.get(url)?.()
  89. const [s1, s2] = await Promise.all([first, second, third])
  90. expect(s1).toBe(s2)
  91. expect(b.fetched).toEqual([url])
  92. expect(ran).toEqual(['a'])
  93. })
  94. it('prefetch after registration is a no-op without invalidate', async () => {
  95. const b = bench([row('a')], { a: () => ({}) })
  96. await b.loader.prefetch('a')
  97. await b.loader.prefetch('a')
  98. expect(b.fetched).toHaveLength(1)
  99. })
  100. })
  101. describe('require resolution', () => {
  102. it('a factory requiring a registered-but-unmaterialized module materializes it recursively', async () => {
  103. const order: string[] = []
  104. const b = bench([row('a'), row('b')], {
  105. a: (req) => {
  106. order.push('a')
  107. const dep = req('b/client') as { helper: string }
  108. return { got: dep.helper }
  109. },
  110. b: () => { order.push('b'); return { helper: 'from-b' } },
  111. })
  112. await b.loader.prefetch('a')
  113. await b.loader.prefetch('b')
  114. const exports = await b.loader.import('a', '', {})
  115. expect((exports as { got: string }).got).toBe('from-b')
  116. expect(order).toEqual(['a', 'b'])
  117. expect(b.loader.loadCache.get('a')?.edges.has('b/client')).toBe(true)
  118. expect(b.loader.loadCache.has('b')).toBe(true)
  119. })
  120. it('require prefers the platform seed word over the module table', async () => {
  121. const react = { marker: 'react' }
  122. const b = bench([row('a')], {
  123. a: req => ({ dep: req('react') }),
  124. }, { seed: { react } })
  125. const exports = await b.loader.import('a', '', {})
  126. expect((exports as { dep: unknown }).dep).toBe(react)
  127. expect(await b.loader.import('react', '', {})).toBe(react)
  128. expect(b.loader.loadCache.has('react')).toBe(false)
  129. })
  130. it('require answers an already-materialized module from the cache', async () => {
  131. let built = 0
  132. const b = bench([row('a'), row('c')], {
  133. a: req => ({ dep: req('c') }),
  134. c: () => { built += 1; return { marker: 'c' } },
  135. })
  136. const c = await b.loader.import('c', '', {})
  137. const a = await b.loader.import('a', '', {})
  138. expect((a as { dep: unknown }).dep).toBe(c)
  139. expect(built).toBe(1)
  140. })
  141. it('a require that misses the module table is loud', async () => {
  142. const b = bench([row('a')], { a: req => ({ dep: req('ghost') }) })
  143. await expect(b.loader.import('a', '', {})).rejects.toThrow('require("ghost") missed the module table')
  144. })
  145. it('a require cycle is fatal', async () => {
  146. const b = bench([row('a'), row('b')], {
  147. a: req => ({ dep: req('b') }),
  148. b: req => ({ dep: req('a') }),
  149. })
  150. await b.loader.prefetch('b')
  151. await expect(b.loader.import('a', '', {})).rejects.toThrow('require cycle through "a"')
  152. })
  153. })
  154. describe('static registry', () => {
  155. it('serves shell-own modules to import and require without any fetch', async () => {
  156. const shell = { marker: 'app-shell' }
  157. const b = bench([row('a')], {
  158. a: req => ({ dep: req('app-shell') }),
  159. })
  160. b.loader.registerStatic('app-shell', shell)
  161. await b.loader.prefetch('app-shell')
  162. expect(await b.loader.import('app-shell', '', {})).toBe(shell)
  163. expect(b.loader.loadCache.get('app-shell')?.styles).toEqual([])
  164. expect((await b.loader.import('a', '', {}) as { dep: unknown }).dep).toBe(shell)
  165. expect(b.fetched).toEqual(['/plugins/a/client.js?rev=0'])
  166. })
  167. it('duplicate static registration is loud', () => {
  168. const b = bench([])
  169. b.loader.registerStatic('app-shell', {})
  170. expect(() => { b.loader.registerStatic('app-shell', {}) }).toThrow('registered twice')
  171. })
  172. })
  173. describe('failure modes', () => {
  174. it('duplicate factory registration is loud', () => {
  175. bench([])
  176. win.__ModuleLoader__?.load({ id: 'x', factory: () => ({}) })
  177. expect(() => win.__ModuleLoader__?.load({ id: 'x', factory: () => ({}) }))
  178. .toThrow('duplicate factory registration for "x"')
  179. })
  180. it('a bundle that never registers its id is loud', async () => {
  181. const b = bench([row('a')], { a: null })
  182. await expect(b.loader.import('a', '', {})).rejects.toThrow('without registering "a"')
  183. })
  184. it('an unknown import specifier is loud', async () => {
  185. const b = bench([])
  186. await expect(b.loader.import('nope', '', {})).rejects.toThrow('cannot resolve "nope"')
  187. })
  188. it('an unknown prefetch id is loud', async () => {
  189. const b = bench([])
  190. await expect(b.loader.prefetch('nope')).rejects.toThrow('prefetch("nope") — not a graph entry')
  191. })
  192. it('a duplicate graph entry is loud at construction', () => {
  193. expect(() => bench([row('a'), row('a')])).toThrow('duplicate graph entry "a"')
  194. })
  195. it('double boot is loud', () => {
  196. bench([])
  197. expect(() => new ClientModuleSystem({ modules: [], staticModules: {} }))
  198. .toThrow('already installed (double boot?)')
  199. })
  200. })
  201. describe('HMR reset', () => {
  202. it('invalidate drops the factory and record so the module reloads and re-registers', async () => {
  203. let generation = 0
  204. const b = bench([row('a')], { a: () => ({ generation: ++generation }) })
  205. const first = await b.loader.import('a', '', {})
  206. b.loader.invalidate('a')
  207. expect(b.loader.loadCache.has('a')).toBe(false)
  208. await b.loader.prefetch('a')
  209. const second = await b.loader.import('a', '', {})
  210. expect(b.fetched).toHaveLength(2)
  211. expect((first as { generation: number }).generation).toBe(1)
  212. expect((second as { generation: number }).generation).toBe(2)
  213. })
  214. })
  215. describe('style claiming', () => {
  216. it('claims untagged style tags for the materializing plugin and inventories owned css ids', async () => {
  217. const foreign = document.createElement('style')
  218. foreign.setAttribute('data-plugin', 'other')
  219. document.head.appendChild(foreign)
  220. const b = bench([row('a')], {
  221. a: () => {
  222. document.head.appendChild(document.createElement('style'))
  223. const tagged = document.createElement('style')
  224. tagged.setAttribute('data-plugin', 'a')
  225. tagged.setAttribute('data-plugin-css', 'sheet-1')
  226. document.head.appendChild(tagged)
  227. return {}
  228. },
  229. })
  230. await b.loader.import('a', '', {})
  231. expect(b.loader.loadCache.get('a')?.styles).toEqual(['a', 'sheet-1'])
  232. expect(document.querySelectorAll('style[data-plugin="a"]')).toHaveLength(2)
  233. expect(foreign.getAttribute('data-plugin')).toBe('other')
  234. })
  235. it('materialization without a document skips the style inventory', async () => {
  236. const b = bench([row('a')], { a: () => ({}) })
  237. vi.stubGlobal('document', undefined)
  238. try {
  239. await b.loader.import('a', '', {})
  240. } finally {
  241. vi.unstubAllGlobals()
  242. }
  243. expect(b.loader.loadCache.get('a')?.styles).toEqual([])
  244. })
  245. })
  246. describe('default transport seam', () => {
  247. it('loads through an external classic script and removes the settled node', async () => {
  248. const append = vi.spyOn(document.head, 'append').mockImplementation((...nodes) => {
  249. const script = nodes[0]
  250. if (!(script instanceof HTMLScriptElement)) throw new Error('expected script node')
  251. expect(script.async).toBe(true)
  252. expect(script.getAttribute('src')).toBe('/plugins/dee/client.js?rev=0')
  253. queueMicrotask(() => {
  254. win.__ModuleLoader__?.load({ id: 'dee', factory: () => ({ marker: 'via-script' }) })
  255. script.dispatchEvent(new Event('load'))
  256. })
  257. })
  258. const loader: ClientModuleLoader = new ClientModuleSystem({ modules: [row('dee')], staticModules: {} })
  259. const exports = await loader.import('dee', '', {})
  260. expect((exports as { marker: string }).marker).toBe('via-script')
  261. expect(append).toHaveBeenCalledOnce()
  262. expect([...document.querySelectorAll('script')]).toEqual([])
  263. })
  264. it('a script load failure is loud and removes the node', async () => {
  265. vi.spyOn(document.head, 'append').mockImplementation((...nodes) => {
  266. const script = nodes[0]
  267. if (!(script instanceof HTMLScriptElement)) throw new Error('expected script node')
  268. queueMicrotask(() => { script.dispatchEvent(new Event('error')) })
  269. })
  270. const loader = new ClientModuleSystem({ modules: [row('dee')], staticModules: {} })
  271. await expect(loader.prefetch('dee')).rejects.toThrow(
  272. 'bundle script /plugins/dee/client.js?rev=0 failed to load',
  273. )
  274. expect([...document.querySelectorAll('script')]).toEqual([])
  275. })
  276. })