loader.client.spec.ts 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603
  1. // @vitest-environment jsdom
  2. import { removeOwnedStyles } from '../src/client/entry-lifecycle.ts'
  3. import { Context } from '@deepseek-ai/cordis'
  4. import { afterEach, describe, expect, it, vi } from 'vitest'
  5. import {
  6. apply, createClientModuleSystem, parseBootManifest,
  7. type BootModuleRow, type ClientBundleRegistration, type ClientModuleCreateOptions,
  8. type ClientModuleLoader, type ClientModuleLoaderTarget, type DshWindow,
  9. } from '../src/client/index.ts'
  10. const MODULES_ID = '@deepseek-ai/dsh-client-modules'
  11. const comboUrl = (ids: readonly string[], rev: string): string =>
  12. `/plugins/??${ids.map(id => `${id}/client.js`).join(',')}&rev=${rev}`
  13. const BOOTSTRAP_URL = comboUrl([MODULES_ID], 'bootstrap')
  14. const APPLICATION_URL = comboUrl(['a', 'b'], 'application')
  15. const win = globalThis as DshWindow
  16. const bootstrapExports = { apply, createClientModuleSystem }
  17. type Factory = ClientBundleRegistration['factory']
  18. afterEach(() => {
  19. vi.unstubAllGlobals()
  20. delete win.__ModuleLoader__
  21. for (const el of document.querySelectorAll('style, script')) el.remove()
  22. })
  23. const row = (id: string, fields: Partial<BootModuleRow> = {}): BootModuleRow =>
  24. ({
  25. id,
  26. url: comboUrl([id], '0'),
  27. initialUrl: id === MODULES_ID ? BOOTSTRAP_URL : APPLICATION_URL,
  28. rev: '0',
  29. inject: [],
  30. external: [],
  31. ...fields,
  32. })
  33. interface Bench {
  34. loader: ClientModuleLoader
  35. target: ClientModuleLoaderTarget
  36. fetched: string[]
  37. gates: Map<string, () => void>
  38. }
  39. /** Build the page-global facade shape consumed by the module system. */
  40. function registrationTarget(pending: ClientBundleRegistration[] = []): ClientModuleLoaderTarget {
  41. const pendingQueue = [...pending]
  42. const target: ClientModuleLoaderTarget = {
  43. mode: 'queue',
  44. pendingQueue,
  45. load: (registration) => { pendingQueue.push(registration) },
  46. create: options => createClientModuleSystem(target, {
  47. id: MODULES_ID,
  48. exports: bootstrapExports,
  49. }, options),
  50. }
  51. return target
  52. }
  53. /**
  54. * Loader over scripted bundles: load records the row URL, optionally waits on
  55. * a release callback, then registers the scripted factory through the window
  56. * sink (`null` scripts a bundle that never calls load).
  57. */
  58. function bench(
  59. entries: BootModuleRow[],
  60. bundles: Record<string, Factory | null> = {},
  61. opts: {
  62. seed?: Record<string, unknown>
  63. gated?: string[]
  64. pending?: ClientBundleRegistration[]
  65. defaultTransport?: boolean
  66. } = {},
  67. ): Bench {
  68. const fetched: string[] = []
  69. const gates = new Map<string, () => void>()
  70. const target = registrationTarget(opts.pending)
  71. win.__ModuleLoader__ = target
  72. const loadBundle = async (url: string): Promise<void> => {
  73. fetched.push(url)
  74. if (opts.gated?.includes(url) === true) {
  75. await new Promise<void>((resolve) => { gates.set(url, resolve) })
  76. }
  77. const batchIds = url === BOOTSTRAP_URL
  78. ? entries.filter(entry => entry.initialUrl === BOOTSTRAP_URL).map(entry => entry.id)
  79. : url === APPLICATION_URL
  80. ? entries.filter(entry => entry.initialUrl === APPLICATION_URL).map(entry => entry.id)
  81. : undefined
  82. const parsed = new URL(url, 'http://dsh.invalid')
  83. const combo = parsed.search.startsWith('??') ? parsed.search.slice(2).split('&', 1)[0] : undefined
  84. const singleId = combo?.split(',').length === 1 && combo.endsWith('/client.js')
  85. ? combo.slice(0, -'/client.js'.length)
  86. : undefined
  87. for (const id of batchIds ?? (singleId === undefined ? [] : [singleId])) {
  88. const factory = bundles[id]
  89. if (factory != null) win.__ModuleLoader__?.load({ id, factory })
  90. }
  91. }
  92. const bootstrapEntries = entries.filter(entry => entry.initialUrl === BOOTSTRAP_URL).map(entry => entry.id)
  93. const applicationEntries = entries.filter(entry => entry.initialUrl === APPLICATION_URL).map(entry => entry.id)
  94. const batches = [
  95. ...(bootstrapEntries.length === 0 ? [] : [{
  96. phase: 'bootstrap' as const, url: BOOTSTRAP_URL, rev: 'bootstrap', entries: bootstrapEntries,
  97. }]),
  98. ...(applicationEntries.length === 0 ? [] : [{
  99. phase: 'application' as const, url: APPLICATION_URL, rev: 'application', entries: applicationEntries,
  100. }]),
  101. ]
  102. const loader = target.create({
  103. boot: {
  104. rev: 'graph',
  105. entries: entries.map(({ initialUrl: _initialUrl, inject, external, ...entry }) => ({
  106. ...entry,
  107. ...(inject.length === 0 ? {} : { inject }),
  108. ...(external.length === 0 ? {} : { external }),
  109. })),
  110. batches,
  111. },
  112. staticModules: opts.seed ?? {},
  113. ...(opts.defaultTransport === true ? {} : { loadBundle }),
  114. })
  115. return { loader, target, fetched, gates }
  116. }
  117. describe('Cordis plugin face', () => {
  118. it('rejects a Loader whose internal is absent or not a client module system', () => {
  119. for (const internal of [undefined, { version: 'worker' }]) {
  120. const ctx = new Context()
  121. ctx.provide('loader', { internal } as never)
  122. expect(() => { apply(ctx) }).toThrow('the Loader has no client module system')
  123. }
  124. })
  125. })
  126. describe('lazy CJS arrival', () => {
  127. it('drains registrations queued by parser-blocking preload scripts into the same live facade', async () => {
  128. const b = bench([row('runtime')], {}, {
  129. pending: [{ id: 'runtime', factory: () => ({ marker: 'preloaded' }) }],
  130. })
  131. const exports = await b.loader.import('runtime', '', {})
  132. expect((exports as { marker: string }).marker).toBe('preloaded')
  133. expect(b.target.pendingQueue).toEqual([])
  134. expect(b.fetched).toEqual([])
  135. expect(win.__ModuleLoader__).toBe(b.target)
  136. expect(b.target.mode).toBe('live')
  137. })
  138. it('prefetch loads and registers but does not run the factory', async () => {
  139. const ran: string[] = []
  140. const b = bench([row('a')], { a: () => { ran.push('a'); return {} } })
  141. await b.loader.prefetch('a')
  142. expect(b.fetched).toEqual([APPLICATION_URL])
  143. expect(ran).toEqual([])
  144. expect(b.loader.loadCache.has('a')).toBe(false)
  145. })
  146. it('import materializes once and memoizes the exports', async () => {
  147. const ran: string[] = []
  148. const b = bench([row('a')], { a: () => { ran.push('a'); return { marker: 'a' } } })
  149. const first = await b.loader.import('a', '', {})
  150. const second = await b.loader.import('a', '', {})
  151. expect(first).toBe(second)
  152. expect((first as { marker: string }).marker).toBe('a')
  153. expect(ran).toEqual(['a'])
  154. expect(b.loader.loadCache.get('a')?.id).toBe('a')
  155. })
  156. it('import without prefetch loads, registers, and materializes in one call', async () => {
  157. const b = bench([row('a')], { a: () => ({ marker: 'direct' }) })
  158. const exports = await b.loader.import('a', '', {})
  159. expect((exports as { marker: string }).marker).toBe('direct')
  160. expect(b.fetched).toHaveLength(1)
  161. })
  162. it('registers declared dynamic requests before materializing their consumer', async () => {
  163. const b = bench([
  164. row('consumer', { external: ['provider/client', 'react'] }),
  165. row('provider'),
  166. ], {
  167. consumer: req => ({ provider: req('provider/client'), react: req('react') }),
  168. provider: () => ({ marker: 'provider' }),
  169. }, { seed: { react: { marker: 'react' } } })
  170. const exports = await b.loader.import('consumer', '', {}) as {
  171. provider: { marker: string }
  172. react: { marker: string }
  173. }
  174. expect(b.fetched).toEqual([APPLICATION_URL])
  175. expect(exports.provider.marker).toBe('provider')
  176. expect(exports.react.marker).toBe('react')
  177. })
  178. it('registers injected package factories before materializing a consumer', async () => {
  179. const b = bench([
  180. row('consumer', { inject: ['provider'] }),
  181. row('provider', { inject: ['consumer'] }),
  182. ], {
  183. consumer: req => ({ provider: req('provider/client') }),
  184. provider: () => ({ marker: 'provider' }),
  185. })
  186. const exports = await b.loader.import('consumer', '', {}) as { provider: { marker: string } }
  187. expect(b.fetched).toEqual([APPLICATION_URL])
  188. expect(exports.provider.marker).toBe('provider')
  189. })
  190. it('concurrent callers share one in-flight arrival and materialize once', async () => {
  191. const ran: string[] = []
  192. const url = APPLICATION_URL
  193. const b = bench([row('a')], { a: () => { ran.push('a'); return { marker: 'a' } } }, { gated: [url] })
  194. const first = b.loader.import('a', '', {})
  195. const second = b.loader.import('a', '', {})
  196. const third = b.loader.prefetch('a')
  197. b.gates.get(url)?.()
  198. const [s1, s2] = await Promise.all([first, second, third])
  199. expect(s1).toBe(s2)
  200. expect(b.fetched).toEqual([url])
  201. expect(ran).toEqual(['a'])
  202. })
  203. it('prefetch after registration is a no-op without invalidate', async () => {
  204. const b = bench([row('a')], { a: () => ({}) })
  205. await b.loader.prefetch('a')
  206. await b.loader.prefetch('a')
  207. expect(b.fetched).toHaveLength(1)
  208. })
  209. })
  210. describe('require resolution', () => {
  211. it('a factory requiring a registered-but-unmaterialized module materializes it recursively', async () => {
  212. const order: string[] = []
  213. const b = bench([row('a'), row('b')], {
  214. a: (req) => {
  215. order.push('a')
  216. const dep = req('b/client') as { helper: string }
  217. return { got: dep.helper }
  218. },
  219. b: () => { order.push('b'); return { helper: 'from-b' } },
  220. })
  221. await b.loader.prefetch('a')
  222. await b.loader.prefetch('b')
  223. const exports = await b.loader.import('a', '', {})
  224. expect((exports as { got: string }).got).toBe('from-b')
  225. expect(order).toEqual(['a', 'b'])
  226. expect(b.loader.loadCache.get('a')?.edges.has('b/client')).toBe(true)
  227. expect(b.loader.loadCache.has('b')).toBe(true)
  228. })
  229. it('require prefers the platform seed word over the module table', async () => {
  230. const react = { marker: 'react' }
  231. const b = bench([row('a')], {
  232. a: req => ({ dep: req('react') }),
  233. }, { seed: { react } })
  234. const exports = await b.loader.import('a', '', {})
  235. expect((exports as { dep: unknown }).dep).toBe(react)
  236. expect(await b.loader.import('react', '', {})).toBe(react)
  237. expect(b.loader.loadCache.has('react')).toBe(false)
  238. })
  239. it('require answers an already-materialized module from the cache', async () => {
  240. let built = 0
  241. const b = bench([row('a'), row('c')], {
  242. a: req => ({ dep: req('c') }),
  243. c: () => { built += 1; return { marker: 'c' } },
  244. })
  245. const c = await b.loader.import('c', '', {})
  246. const a = await b.loader.import('a', '', {})
  247. expect((a as { dep: unknown }).dep).toBe(c)
  248. expect(built).toBe(1)
  249. })
  250. it('a require that misses the module table is loud', async () => {
  251. const b = bench([row('a')], { a: req => ({ dep: req('ghost') }) })
  252. await expect(b.loader.import('a', '', {})).rejects.toThrow('require("ghost") missed the module table')
  253. })
  254. it('a require cycle is fatal', async () => {
  255. const b = bench([row('a'), row('b')], {
  256. a: req => ({ dep: req('b') }),
  257. b: req => ({ dep: req('a') }),
  258. })
  259. await b.loader.prefetch('b')
  260. await expect(b.loader.import('a', '', {})).rejects.toThrow('require cycle through "a"')
  261. })
  262. })
  263. describe('bootstrap module', () => {
  264. it('caches the materialized modules exports under the package id and /client alias', async () => {
  265. const b = bench([
  266. row('consumer', { external: [`${MODULES_ID}/client`] }),
  267. row(MODULES_ID),
  268. ], {
  269. consumer: req => ({ dep: req(`${MODULES_ID}/client`) }),
  270. })
  271. await b.loader.prefetch(MODULES_ID)
  272. const exports = await b.loader.import('consumer', '', {}) as { dep: unknown }
  273. expect(exports.dep).toBe(bootstrapExports)
  274. expect(await b.loader.import(`${MODULES_ID}/client`, '', {})).toBe(bootstrapExports)
  275. expect(b.fetched).toEqual([APPLICATION_URL])
  276. })
  277. it('publishes the module system attached to its own Loader', () => {
  278. const a = bench([])
  279. const b = bench([])
  280. const ctxA = new Context()
  281. const ctxB = new Context()
  282. ctxA.reflect.provide('loader', { internal: a.loader })
  283. ctxB.reflect.provide('loader', { internal: b.loader })
  284. apply(ctxA)
  285. apply(ctxB)
  286. expect(ctxA.modules).toBe(a.loader)
  287. expect(ctxB.modules).toBe(b.loader)
  288. })
  289. it('rejects a second queued registration for the bootstrap id', () => {
  290. expect(() => bench([], {}, {
  291. pending: [{ id: `${MODULES_ID}/client`, factory: () => ({}) }],
  292. })).toThrow(`duplicate factory registration for "${MODULES_ID}/client"`)
  293. })
  294. })
  295. describe('failure modes', () => {
  296. it('duplicate factory registration is loud', () => {
  297. bench([])
  298. win.__ModuleLoader__?.load({ id: 'x', factory: () => ({}) })
  299. expect(() => win.__ModuleLoader__?.load({ id: 'x', factory: () => ({}) }))
  300. .toThrow('duplicate factory registration for "x"')
  301. })
  302. it('a bundle that never registers its id is loud', async () => {
  303. const b = bench([row('a')], { a: null })
  304. await expect(b.loader.import('a', '', {})).rejects.toThrow('without registering "a"')
  305. })
  306. it('an unknown import specifier is loud', async () => {
  307. const b = bench([])
  308. await expect(b.loader.import('nope', '', {})).rejects.toThrow('cannot resolve "nope"')
  309. })
  310. it('an unknown prefetch id is loud', async () => {
  311. const b = bench([])
  312. await expect(b.loader.prefetch('nope')).rejects.toThrow('prefetch("nope") — not a graph entry')
  313. })
  314. it('a duplicate graph entry is loud at construction', () => {
  315. expect(() => bench([row('a'), row('a')])).toThrow('duplicate graph entry "a"')
  316. })
  317. it('a module arrival cycle is loud even if a malformed host graph reaches the browser', async () => {
  318. const b = bench([
  319. row('a', { external: ['b'] }),
  320. row('b', { external: ['a'] }),
  321. ])
  322. await expect(b.loader.prefetch('a')).rejects.toThrow('module arrival cycle a -> b -> a')
  323. })
  324. it('double boot is loud', () => {
  325. const b = bench([])
  326. const options: ClientModuleCreateOptions = {
  327. boot: { rev: 'graph', entries: [], batches: [] },
  328. staticModules: {},
  329. }
  330. expect(() => b.target.create(options)).toThrow('create called after module-system boot')
  331. })
  332. })
  333. describe('boot manifest wire', () => {
  334. it('normalizes absent shared-module fields and carries the declared ones', () => {
  335. const manifest = parseBootManifest({
  336. rev: 'graph',
  337. entries: [
  338. { id: 'a', url: '/plugins/a/client.js', rev: '1', inject: ['b'] },
  339. { id: 'b', url: '/plugins/b/client.js', rev: '2', external: ['react'] },
  340. ],
  341. batches: [{ phase: 'application', url: '/batch.js', rev: 'batch', entries: ['a', 'b'] }],
  342. })
  343. expect(manifest.modules).toEqual([
  344. { id: 'a', url: '/plugins/a/client.js', initialUrl: '/batch.js', rev: '1', inject: ['b'], external: [] },
  345. { id: 'b', url: '/plugins/b/client.js', initialUrl: '/batch.js', rev: '2', inject: [], external: ['react'] },
  346. ])
  347. })
  348. it('rejects a non-array external', () => {
  349. expect(() => parseBootManifest({
  350. rev: 'graph',
  351. entries: [{ id: 'a', url: '/a', rev: '1', external: 'react' }],
  352. batches: [{ phase: 'application', url: '/batch.js', rev: 'batch', entries: ['a'] }],
  353. })).toThrow('client-modules: boot manifest entry "a" external must be a string array')
  354. })
  355. it('requires the batch table', () => {
  356. expect(() => parseBootManifest({ rev: 'graph', entries: [] }))
  357. .toThrow('client-modules: boot manifest batches must be an array')
  358. })
  359. it('rejects malformed batch phases', () => {
  360. const entry = { id: 'a', url: '/a.js', rev: '1' }
  361. expect(() => parseBootManifest({ rev: 'graph', entries: [entry], batches: [null] }))
  362. .toThrow('client-modules: boot manifest batch is not an object')
  363. expect(() => parseBootManifest({
  364. rev: 'graph', entries: [entry], batches: [{ phase: 'idle', url: '/b.js', rev: 'b', entries: ['a'] }],
  365. })).toThrow('boot manifest batch phase must be "bootstrap" or "application"')
  366. })
  367. it('rejects duplicate batch URLs', () => {
  368. expect(() => parseBootManifest({
  369. rev: 'graph',
  370. entries: [
  371. { id: 'a', url: '/a.js', rev: '1' },
  372. { id: 'b', url: '/b.js', rev: '2' },
  373. ],
  374. batches: [
  375. { phase: 'application', url: '/combo.js', rev: '1', entries: ['a'] },
  376. { phase: 'application', url: '/combo.js', rev: '2', entries: ['b'] },
  377. ],
  378. })).toThrow('boot manifest carries duplicate batch URL "/combo.js"')
  379. })
  380. it('allows several batches in one scheduling phase', () => {
  381. const manifest = parseBootManifest({
  382. rev: 'graph',
  383. entries: [
  384. { id: 'a', url: '/a.js', rev: '1' },
  385. { id: 'b', url: '/b.js', rev: '2' },
  386. ],
  387. batches: [
  388. { phase: 'application', url: '/b.js', rev: '1', entries: ['a'] },
  389. { phase: 'application', url: '/c.js', rev: '2', entries: ['b'] },
  390. ],
  391. })
  392. expect(manifest.modules.map(row => row.initialUrl)).toEqual(['/b.js', '/c.js'])
  393. })
  394. it('requires complete batch fields and non-empty entries', () => {
  395. const entry = { id: 'a', url: '/a.js', rev: '1' }
  396. expect(() => parseBootManifest({
  397. rev: 'graph', entries: [entry], batches: [{ phase: 'application', entries: ['a'] }],
  398. })).toThrow('boot manifest application batch must carry string url/rev')
  399. expect(() => parseBootManifest({
  400. rev: 'graph', entries: [entry], batches: [{ phase: 'application', url: '/b.js', rev: 'b', entries: [] }],
  401. })).toThrow('boot manifest application batch entries must be a non-empty string array')
  402. })
  403. it('requires a one-to-one batch assignment over graph entries', () => {
  404. const entries = [
  405. { id: 'a', url: '/a.js', rev: '1' },
  406. { id: 'b', url: '/b.js', rev: '2' },
  407. ]
  408. expect(() => parseBootManifest({
  409. rev: 'graph',
  410. entries,
  411. batches: [{ phase: 'application', url: '/batch.js', rev: 'b', entries: ['ghost'] }],
  412. })).toThrow('boot manifest application batch names unknown entry "ghost"')
  413. expect(() => parseBootManifest({
  414. rev: 'graph',
  415. entries,
  416. batches: [
  417. { phase: 'bootstrap', url: '/boot.js', rev: 'boot', entries: ['a'] },
  418. { phase: 'application', url: '/batch.js', rev: 'app', entries: ['a', 'b'] },
  419. ],
  420. })).toThrow('boot manifest entry "a" belongs to more than one batch')
  421. expect(() => parseBootManifest({
  422. rev: 'graph',
  423. entries,
  424. batches: [{ phase: 'application', url: '/batch.js', rev: 'b', entries: ['a'] }],
  425. })).toThrow('boot manifest entry "b" belongs to no initial-load batch')
  426. })
  427. })
  428. describe('HMR reset', () => {
  429. it('invalidate drops the factory and record so the module reloads and re-registers', async () => {
  430. let generation = 0
  431. const b = bench([row('a')], { a: () => ({ generation: ++generation }) })
  432. const first = await b.loader.import('a', '', {})
  433. b.loader.invalidate('a', '1')
  434. expect(b.loader.loadCache.has('a')).toBe(false)
  435. await b.loader.prefetch('a')
  436. const second = await b.loader.import('a', '', {})
  437. expect(b.fetched).toEqual([APPLICATION_URL, comboUrl(['a'], '1')])
  438. expect((first as { generation: number }).generation).toBe(1)
  439. expect((second as { generation: number }).generation).toBe(2)
  440. })
  441. it('preserves an absolute combo endpoint when applying the rebuilt revision', async () => {
  442. const b = bench([
  443. row('a', { url: 'https://plugins.example.test/plugins/??a/client.js&rev=0' }),
  444. ], { a: () => ({}) })
  445. await b.loader.import('a', '', {})
  446. b.loader.invalidate('a', 'next')
  447. await b.loader.prefetch('a')
  448. expect(b.fetched.at(-1)).toBe('https://plugins.example.test/plugins/??a/client.js&rev=next')
  449. })
  450. it('preserves a protocol-relative combo endpoint when applying the rebuilt revision', async () => {
  451. const b = bench([
  452. row('a', { url: '//plugins.example.test/plugins/??a/client.js&rev=0' }),
  453. ], { a: () => ({}) })
  454. await b.loader.import('a', '', {})
  455. b.loader.invalidate('a', 'next')
  456. await b.loader.prefetch('a')
  457. expect(b.fetched.at(-1)).toBe('//plugins.example.test/plugins/??a/client.js&rev=next')
  458. })
  459. it('uses the current plugin revision when a graph-row invalidation omits an override', async () => {
  460. const b = bench([row('a')], { a: () => ({}) })
  461. await b.loader.import('a', '', {})
  462. b.loader.invalidate('a')
  463. await b.loader.prefetch('a')
  464. expect(b.fetched).toEqual([APPLICATION_URL, comboUrl(['a'], '0')])
  465. })
  466. })
  467. describe('style claiming', () => {
  468. it('claims untagged style tags for the materializing plugin and inventories owned css ids', async () => {
  469. const foreign = document.createElement('style')
  470. foreign.setAttribute('data-plugin', 'other')
  471. document.head.appendChild(foreign)
  472. const b = bench([row('a')], {
  473. a: () => {
  474. document.head.appendChild(document.createElement('style'))
  475. const tagged = document.createElement('style')
  476. tagged.setAttribute('data-plugin', 'a')
  477. tagged.setAttribute('data-plugin-css', 'sheet-1')
  478. document.head.appendChild(tagged)
  479. return {}
  480. },
  481. })
  482. await b.loader.import('a', '', {})
  483. expect(b.loader.loadCache.get('a')?.styles).toEqual(['a', 'sheet-1'])
  484. expect(document.querySelectorAll('style[data-plugin="a"]')).toHaveLength(2)
  485. expect(foreign.getAttribute('data-plugin')).toBe('other')
  486. })
  487. it('materialization without a document skips the style inventory', async () => {
  488. const b = bench([row('a')], { a: () => ({}) })
  489. vi.stubGlobal('document', undefined)
  490. try {
  491. await b.loader.import('a', '', {})
  492. removeOwnedStyles('a')
  493. } finally {
  494. vi.unstubAllGlobals()
  495. }
  496. expect(b.loader.loadCache.get('a')?.styles).toEqual([])
  497. })
  498. })
  499. describe('default transport seam', () => {
  500. it('loads through an external classic script and removes the settled node', async () => {
  501. const append = vi.spyOn(document.head, 'append').mockImplementation((...nodes) => {
  502. const script = nodes[0]
  503. if (!(script instanceof HTMLScriptElement)) throw new Error('expected script node')
  504. expect(script.async).toBe(true)
  505. expect(script.getAttribute('src')).toBe(APPLICATION_URL)
  506. queueMicrotask(() => {
  507. win.__ModuleLoader__?.load({ id: 'dee', factory: () => ({ marker: 'via-script' }) })
  508. script.dispatchEvent(new Event('load'))
  509. })
  510. })
  511. const b = bench([row('dee')], {}, { defaultTransport: true })
  512. const exports = await b.loader.import('dee', '', {})
  513. expect((exports as { marker: string }).marker).toBe('via-script')
  514. expect(append).toHaveBeenCalledOnce()
  515. expect([...document.querySelectorAll('script')]).toEqual([])
  516. })
  517. it('a script load failure is loud and removes the node', async () => {
  518. vi.spyOn(document.head, 'append').mockImplementation((...nodes) => {
  519. const script = nodes[0]
  520. if (!(script instanceof HTMLScriptElement)) throw new Error('expected script node')
  521. queueMicrotask(() => { script.dispatchEvent(new Event('error')) })
  522. })
  523. const b = bench([row('dee')], {}, { defaultTransport: true })
  524. await expect(b.loader.prefetch('dee')).rejects.toThrow(
  525. `bundle script ${APPLICATION_URL} failed to load`,
  526. )
  527. expect([...document.querySelectorAll('script')]).toEqual([])
  528. })
  529. })
  530. it('rejects invalid revision URLs and keeps bootstrap exports pinned under invalidation', () => {
  531. const b = bench([row(MODULES_ID), row('a', { url: '/unrevisioned' })])
  532. b.loader.invalidate(MODULES_ID)
  533. expect(b.loader.loadCache.get(MODULES_ID)?.exports).toBe(bootstrapExports)
  534. expect(() =>{ b.loader.invalidate('a', 'next') }).toThrow('has no revision')
  535. })
  536. it('prefetch skips platform requests, cached dependencies and absent optional inject rows', async () => {
  537. const b = bench([
  538. row('a'),
  539. row('b', { external: ['platform', 'a/client'], inject: ['missing'] }),
  540. ], { a: () => ({}), b: () => ({}) }, { seed: { platform: {} } })
  541. await b.loader.import('a', '', {})
  542. await b.loader.import('b', '', {})
  543. expect(b.fetched).toEqual([APPLICATION_URL])
  544. })
  545. it('rejects a wire request with no dynamic row or platform supplier at materialization', async () => {
  546. const b = bench([row('a', { external: ['missing'] })], { a: require => ({ value: require('missing') }) })
  547. await expect(b.loader.import('a', '', {})).rejects.toThrow('missed the module table')
  548. })