mirror of
https://ghproxy.cflmy.top/https://github.com/deepseek-ai/deepseek-harness.git
synced 2026-11-29 16:49:35 +08:00
* feat(ui-renderer): scope opted-in package styles on existing slot roots Share the package style policy between slot dispatch and stylesheet installation. Preserve global themes, root identity and component state through style-only toggles, including nested Factory, HOC and list output. * fix(dev-web): keep launcher validation independent of package sources * refactor(ui-renderer): identify generated scope CSS as stylesheet content * fix(client): keep panel indicators visible under style isolation Position a shared indicator area on the Session panel toggle. Jobs, Subagents, and Forge paint their own marks without crossing package scopes. * refactor(ui-renderer): fix each package style scope for the page Stamp the content supplier on existing slot roots. Read its page-owned mode when registering content and writing stylesheets instead of subscribing the render tree to live policy changes. * fix(ui-renderer): keep scoped styles with their actual package Resolve Loader aliases against the page module table and stamp contributions from the renderer’s own module source. Let a valid package stylesheet take over a path rejected during scope preflight or by the destination. * fix(client-modules): declare the row callback receiver-free * refactor(ui-renderer): scope styles from their module records * test(ui-renderer): verify module-record style scoping * chore(ui-renderer): restore scoped slots to the PR base * fix(ui-renderer): mark slot roots with their supplying module * refactor(ui-renderer): bind Factory child slots once per supplier An outlet belongs to whoever called renderSlot for it, wherever it later renders. A Factory's child-slot methods are now kept per Factory and per supplier: the Factory itself for its own Component and fallback locals, the occurrence's caller for a local it selected. One caller mounting its local in several places shares one method, and no per-mount binding or extra occurrence context field remains. * refactor(ui-renderer): scan a Factory's chain children once Whether a Factory declares a chain child is recorded once per Factory beside its per-supplier child-slot methods, instead of once per supplier. The Factory kit assigns `renderSlot` and `renderSlotChain` by name rather than copying whichever keys the methods object holds. * test(client-runtime): expect data-plugin on the mounted slot root The slot outlet names its supplier on the existing root; the test runtime registers without a package, so the two DOM snapshots gain data-plugin="". * test(web): launch the panel indicator scenario per isolation mode The Host reads an entry's client isolation when its plugin starts, so updating that field on a running entry never reached the boot graph and the scenario waited forever. Each mode now starts its own Host: the shipped composition, and one whose overlay declares style isolation for the panel and the two packages drawing on its toggle. Both check the boot graph first, then run the same interaction and indicator assertions.
1062 lines
46 KiB
TypeScript
1062 lines
46 KiB
TypeScript
// @vitest-environment jsdom
|
|
import { readRelease } from '../src/client/manifest.ts'
|
|
import { Context } from '@deepseek-ai/cordis'
|
|
import { afterEach, describe, expect, it, vi } from 'vitest'
|
|
import {
|
|
apply, createClientModuleSystem, parseBootManifest,
|
|
type BootModuleRow, type ClientBundleRegistration, type ClientModuleCreateOptions,
|
|
type ClientModuleLoader, type ClientModuleLoaderTarget, type DshWindow,
|
|
} from '../src/client/index.ts'
|
|
|
|
const MODULES_ID = '@deepseek-ai/dsh-client-modules'
|
|
|
|
// The host composes graph rows and batch descriptors as app-directory-relative
|
|
// browser references, so these fixtures carry the same form.
|
|
const comboReference = (ids: readonly string[], rev: string): string =>
|
|
`plugins/??${ids.map(id => `${id}/client.js`).join(',')}&rev=${rev}`
|
|
const chunkReference = (id: string, fileName: string, rev = '0'): string =>
|
|
`plugins/${id}/${fileName}?rev=${rev}`
|
|
const BOOTSTRAP_URL = comboReference([MODULES_ID], 'bootstrap')
|
|
const APPLICATION_URL = comboReference(['a', 'b'], 'application')
|
|
const win = globalThis as DshWindow
|
|
const bootstrapExports = { apply, createClientModuleSystem }
|
|
|
|
type Factory = ClientBundleRegistration['factory']
|
|
type Meta = NonNullable<ClientBundleRegistration['meta']>
|
|
const stylesheet = (path: string, css: string): Meta => () => ({ stylesheets: { [path]: { text: () => css } } })
|
|
|
|
afterEach(() => {
|
|
vi.unstubAllGlobals()
|
|
delete win.__ModuleLoader__
|
|
for (const el of document.querySelectorAll('style, script')) el.remove()
|
|
})
|
|
|
|
type FixtureRow = Omit<BootModuleRow, 'isolation'>
|
|
|
|
const row = (id: string, fields: Partial<FixtureRow> = {}): FixtureRow =>
|
|
({
|
|
id,
|
|
url: comboReference([id], '0'),
|
|
initialUrl: id === MODULES_ID ? BOOTSTRAP_URL : APPLICATION_URL,
|
|
rev: '0',
|
|
inject: [],
|
|
external: [],
|
|
...fields,
|
|
})
|
|
|
|
interface Bench {
|
|
loader: ClientModuleLoader
|
|
target: ClientModuleLoaderTarget
|
|
fetched: string[]
|
|
gates: Map<string, () => void>
|
|
}
|
|
|
|
/** Build the page-global facade shape consumed by the module system. */
|
|
function registrationTarget(pending: ClientBundleRegistration[] = []): ClientModuleLoaderTarget {
|
|
const pendingQueue = [...pending]
|
|
const target: ClientModuleLoaderTarget = {
|
|
mode: 'queue',
|
|
pendingQueue,
|
|
load: (registration) => { pendingQueue.push(registration) },
|
|
create: options => createClientModuleSystem(target, {
|
|
id: MODULES_ID,
|
|
exports: bootstrapExports,
|
|
}, options),
|
|
}
|
|
return target
|
|
}
|
|
|
|
/**
|
|
* Loader over scripted bundles: load records the row URL, optionally waits on
|
|
* a release callback, then registers the scripted factory through the window
|
|
* sink (`null` scripts a bundle that never calls load).
|
|
*/
|
|
function bench(
|
|
entries: FixtureRow[],
|
|
bundles: Record<string, Factory | null> = {},
|
|
opts: {
|
|
seed?: readonly ClientBundleRegistration[]
|
|
metadata?: Record<string, Meta>
|
|
gated?: string[]
|
|
pending?: ClientBundleRegistration[]
|
|
defaultTransport?: boolean
|
|
chunks?: Record<string, Factory | null>
|
|
/** Remaining transport rejections per URL (the `<script>` error event). */
|
|
transportFailures?: Record<string, number>
|
|
/** URLs whose script loads but registers only the listed ids (a runtime throw after those registrations). */
|
|
registerOnly?: Record<string, string[]>
|
|
resolveAsset?: (reference: string) => string
|
|
} = {},
|
|
): Bench {
|
|
const fetched: string[] = []
|
|
const gates = new Map<string, () => void>()
|
|
const target = registrationTarget(opts.pending)
|
|
win.__ModuleLoader__ = target
|
|
const transportFailures = { ...opts.transportFailures }
|
|
const loadBundle = async (url: string): Promise<void> => {
|
|
fetched.push(url)
|
|
if (opts.gated?.includes(url) === true) {
|
|
await new Promise<void>((resolve) => { gates.set(url, resolve) })
|
|
}
|
|
if ((transportFailures[url] ?? 0) > 0) {
|
|
transportFailures[url] = (transportFailures[url] as number) - 1
|
|
throw new Error(`client-modules: bundle script ${url} failed to load`)
|
|
}
|
|
const sibling = /^plugins\/(.+)\/(client\.[A-Za-z0-9][A-Za-z0-9._-]*\.js)\?rev=[^&]+$/.exec(url)
|
|
if (sibling !== null) {
|
|
const id = sibling[1] as string
|
|
const chunk = sibling[2] as string
|
|
const factory = opts.chunks?.[`${id}/${chunk}`]
|
|
const meta = opts.metadata?.[`${id}/${chunk}`]
|
|
if (factory != null) win.__ModuleLoader__?.load({ id, chunk, factory, ...(meta === undefined ? {} : { meta }) })
|
|
return
|
|
}
|
|
const batchIds = url === BOOTSTRAP_URL
|
|
? entries.filter(entry => entry.initialUrl === BOOTSTRAP_URL).map(entry => entry.id)
|
|
: url === APPLICATION_URL
|
|
? entries.filter(entry => entry.initialUrl === APPLICATION_URL).map(entry => entry.id)
|
|
: undefined
|
|
const parsed = new URL(url, 'http://dsh.invalid')
|
|
const combo = parsed.search.startsWith('??') ? parsed.search.slice(2).split('&', 1)[0] : undefined
|
|
const singleId = combo?.split(',').length === 1 && combo.endsWith('/client.js')
|
|
? combo.slice(0, -'/client.js'.length)
|
|
: undefined
|
|
const only = opts.registerOnly?.[url]
|
|
for (const id of batchIds ?? (singleId === undefined ? [] : [singleId])) {
|
|
if (only !== undefined && !only.includes(id)) continue
|
|
const factory = bundles[id]
|
|
const meta = opts.metadata?.[id]
|
|
if (factory != null) win.__ModuleLoader__?.load({ id, factory, ...(meta === undefined ? {} : { meta }) })
|
|
}
|
|
}
|
|
const bootstrapEntries = entries.filter(entry => entry.initialUrl === BOOTSTRAP_URL).map(entry => entry.id)
|
|
const applicationEntries = entries.filter(entry => entry.initialUrl === APPLICATION_URL).map(entry => entry.id)
|
|
const batches = [
|
|
...(bootstrapEntries.length === 0 ? [] : [{
|
|
phase: 'bootstrap' as const, url: BOOTSTRAP_URL, rev: 'bootstrap', entries: bootstrapEntries,
|
|
}]),
|
|
...(applicationEntries.length === 0 ? [] : [{
|
|
phase: 'application' as const, url: APPLICATION_URL, rev: 'application', entries: applicationEntries,
|
|
}]),
|
|
]
|
|
const loader = target.create({
|
|
boot: {
|
|
rev: 'graph',
|
|
entries: entries.map(({ initialUrl: _initialUrl, inject, external, ...entry }) => ({
|
|
...entry,
|
|
...(inject.length === 0 ? {} : { inject }),
|
|
...(external.length === 0 ? {} : { external }),
|
|
})),
|
|
batches,
|
|
},
|
|
staticModules: opts.seed ?? [],
|
|
...(opts.defaultTransport === true ? {} : { loadBundle }),
|
|
...(opts.resolveAsset === undefined ? {} : { resolveAsset: opts.resolveAsset }),
|
|
})
|
|
return { loader, target, fetched, gates }
|
|
}
|
|
|
|
describe('materialized module inventory', () => {
|
|
it('retains only successful records and reports chunk ownership without loading lazy code', async () => {
|
|
let loadChunk!: () => Promise<unknown>
|
|
const b = bench([row('a'), row('b'), row('broken')], {
|
|
a: (require) => { loadChunk = () => require.async('./client.details.js'); return {} },
|
|
b: () => ({}),
|
|
broken: () => { throw new Error('factory failed') },
|
|
}, {
|
|
seed: [{ id: 'platform', factory: () => ({}) }],
|
|
chunks: { 'a/client.details.js': () => ({}) },
|
|
})
|
|
const ids = () => [...b.loader.loadCache.keys()].sort()
|
|
const changed = vi.fn()
|
|
const off = b.loader.subscribeModules(changed)
|
|
expect(ids()).toEqual([MODULES_ID])
|
|
await b.loader.import('platform', '', {})
|
|
expect(ids()).toEqual([MODULES_ID, 'platform'])
|
|
expect(changed).toHaveBeenCalledTimes(1)
|
|
expect(b.fetched).toEqual([])
|
|
await b.loader.prefetch('a')
|
|
expect(ids()).toEqual([MODULES_ID, 'platform'])
|
|
expect(changed).toHaveBeenCalledTimes(1)
|
|
await b.loader.import('a', '', {})
|
|
expect(ids()).toEqual([MODULES_ID, 'a', 'platform'])
|
|
expect(b.fetched).not.toContain(chunkReference('a', 'client.details.js'))
|
|
await loadChunk()
|
|
expect(ids()).toEqual([MODULES_ID, 'a', 'a/client.details.js', 'platform'])
|
|
expect(b.loader.loadCache.get('a/client.details.js')?.ownerId).toBe('a')
|
|
await expect(b.loader.import('broken', '', {})).rejects.toThrow('factory failed')
|
|
expect(b.loader.loadCache.has('broken')).toBe(false)
|
|
await b.loader.import('b', '', {})
|
|
expect(ids()).toEqual([MODULES_ID, 'a', 'a/client.details.js', 'b', 'platform'])
|
|
b.loader.invalidate('a')
|
|
expect(ids()).toEqual([MODULES_ID, 'b', 'platform'])
|
|
off()
|
|
})
|
|
|
|
it('retains the owner identity of an already-materialized standalone chunk', async () => {
|
|
const b = bench([], {}, { pending: [{ id: 'owner', chunk: 'client.details.js', factory: () => ({}) }] })
|
|
await b.loader.import('owner/client.details.js', '', {})
|
|
expect([...b.loader.loadCache.keys()]).toEqual([MODULES_ID, 'owner/client.details.js'])
|
|
expect(b.loader.loadCache.get('owner/client.details.js')?.ownerId).toBe('owner')
|
|
expect(b.fetched).toEqual([])
|
|
})
|
|
|
|
it('records loaded dynamic and static dependency edges without further transport', async () => {
|
|
const b = bench([row('a'), row('b')], {
|
|
a: (require) => { require('b'); return {} },
|
|
b: (require) => { require('shared'); return {} },
|
|
}, {
|
|
seed: [
|
|
{ id: 'shared', factory: (require) => { require('base'); return {} } },
|
|
{ id: 'base', factory: () => ({}) },
|
|
],
|
|
})
|
|
await b.loader.import('a', '', {})
|
|
const fetched = [...b.fetched]
|
|
expect(b.loader.loadCache.get('a')?.edges).toEqual(new Set(['b']))
|
|
expect(b.loader.loadCache.get('b')?.edges).toEqual(new Set(['shared']))
|
|
expect(b.loader.loadCache.get('shared')?.edges).toEqual(new Set(['base']))
|
|
expect(b.fetched).toEqual(fetched)
|
|
})
|
|
|
|
it('records lazy chunk dependencies only after its factory materializes', async () => {
|
|
let loadChunk!: () => Promise<unknown>
|
|
const b = bench([row('a'), row('b')], {
|
|
a: (require) => { loadChunk = () => require.async('./client.details.js'); return {} },
|
|
b: () => ({}),
|
|
}, { chunks: { 'a/client.details.js': (require) => { require('b'); return {} } } })
|
|
await b.loader.import('a', '', {})
|
|
expect(b.loader.loadCache.get('a')?.edges).toEqual(new Set())
|
|
expect(b.loader.loadCache.has('a/client.details.js')).toBe(false)
|
|
expect(b.fetched).not.toContain(chunkReference('a', 'client.details.js'))
|
|
await loadChunk()
|
|
expect(b.loader.loadCache.get('a')?.edges).toEqual(new Set(['./client.details.js']))
|
|
expect(b.loader.loadCache.get('a/client.details.js')?.edges).toEqual(new Set(['b']))
|
|
})
|
|
})
|
|
|
|
describe('Cordis plugin face', () => {
|
|
it('rejects a Loader whose internal is absent or not a client module system', () => {
|
|
for (const internal of [undefined, { version: 'worker' }]) {
|
|
const ctx = new Context()
|
|
ctx.provide('loader', { internal } as never)
|
|
expect(() => { apply(ctx) }).toThrow('the Loader has no client module system')
|
|
}
|
|
})
|
|
})
|
|
|
|
describe('lazy CJS arrival', () => {
|
|
it('drains registrations queued by parser-blocking preload scripts into the same live facade', async () => {
|
|
const b = bench([row('runtime')], {}, {
|
|
pending: [{ id: 'runtime', factory: () => ({ marker: 'preloaded' }) }],
|
|
})
|
|
const exports = await b.loader.import('runtime', '', {})
|
|
expect((exports as { marker: string }).marker).toBe('preloaded')
|
|
expect(b.target.pendingQueue).toEqual([])
|
|
expect(b.fetched).toEqual([])
|
|
expect(win.__ModuleLoader__).toBe(b.target)
|
|
expect(b.target.mode).toBe('live')
|
|
})
|
|
|
|
it('prefetch loads and registers but does not run the factory', async () => {
|
|
const ran: string[] = []
|
|
const b = bench([row('a')], { a: () => { ran.push('a'); return {} } })
|
|
await b.loader.prefetch('a')
|
|
expect(b.fetched).toEqual([APPLICATION_URL])
|
|
expect(ran).toEqual([])
|
|
expect(b.loader.loadCache.has('a')).toBe(false)
|
|
})
|
|
|
|
it('import materializes once and memoizes the exports', async () => {
|
|
const ran: string[] = []
|
|
const b = bench([row('a')], { a: () => { ran.push('a'); return { marker: 'a' } } })
|
|
const first = await b.loader.import('a', '', {})
|
|
const second = await b.loader.import('a', '', {})
|
|
expect(first).toBe(second)
|
|
expect((first as { marker: string }).marker).toBe('a')
|
|
expect(ran).toEqual(['a'])
|
|
expect(b.loader.loadCache.get('a')?.id).toBe('a')
|
|
})
|
|
|
|
it('import without prefetch loads, registers, and materializes in one call', async () => {
|
|
const b = bench([row('a')], { a: () => ({ marker: 'direct' }) })
|
|
const exports = await b.loader.import('a', '', {})
|
|
expect((exports as { marker: string }).marker).toBe('direct')
|
|
expect(b.fetched).toHaveLength(1)
|
|
})
|
|
|
|
it('registers declared dynamic requests before materializing their consumer', async () => {
|
|
const b = bench([
|
|
row('consumer', { external: ['provider/client', 'react'] }),
|
|
row('provider'),
|
|
], {
|
|
consumer: req => ({ provider: req('provider/client'), react: req('react') }),
|
|
provider: () => ({ marker: 'provider' }),
|
|
}, { seed: [{ id: 'react', factory: () => ({ marker: 'react' }) }] })
|
|
const exports = await b.loader.import('consumer', '', {}) as {
|
|
provider: { marker: string }
|
|
react: { marker: string }
|
|
}
|
|
expect(b.fetched).toEqual([APPLICATION_URL])
|
|
expect(exports.provider.marker).toBe('provider')
|
|
expect(exports.react.marker).toBe('react')
|
|
})
|
|
|
|
it('registers injected package factories before materializing a consumer', async () => {
|
|
const b = bench([
|
|
row('consumer', { inject: ['provider'] }),
|
|
row('provider', { inject: ['consumer'] }),
|
|
], {
|
|
consumer: req => ({ provider: req('provider/client') }),
|
|
provider: () => ({ marker: 'provider' }),
|
|
})
|
|
const exports = await b.loader.import('consumer', '', {}) as { provider: { marker: string } }
|
|
expect(b.fetched).toEqual([APPLICATION_URL])
|
|
expect(exports.provider.marker).toBe('provider')
|
|
})
|
|
|
|
it('concurrent callers share one in-flight arrival and materialize once', async () => {
|
|
const ran: string[] = []
|
|
const url = APPLICATION_URL
|
|
const b = bench([row('a')], { a: () => { ran.push('a'); return { marker: 'a' } } }, { gated: [url] })
|
|
const first = b.loader.import('a', '', {})
|
|
const second = b.loader.import('a', '', {})
|
|
const third = b.loader.prefetch('a')
|
|
b.gates.get(url)?.()
|
|
const [s1, s2] = await Promise.all([first, second, third])
|
|
expect(s1).toBe(s2)
|
|
expect(b.fetched).toEqual([url])
|
|
expect(ran).toEqual(['a'])
|
|
})
|
|
|
|
it('prefetch after registration is a no-op without invalidate', async () => {
|
|
const b = bench([row('a')], { a: () => ({}) })
|
|
await b.loader.prefetch('a')
|
|
await b.loader.prefetch('a')
|
|
expect(b.fetched).toHaveLength(1)
|
|
})
|
|
|
|
it('resolves a package-asset reference through the carrier, or returns it unchanged without one', async () => {
|
|
const reference = 'plugins/a/assets/mark-0123456789ab.svg'
|
|
const factory: Factory = req => ({ url: req.asset(reference) })
|
|
const served = bench([row('a')], { a: factory })
|
|
expect(await served.loader.import('a', '', {})).toEqual({ url: reference })
|
|
expect(served.loader.resolveAsset(reference)).toBe(reference)
|
|
|
|
const mapped = bench([row('a')], { a: factory }, { resolveAsset: asset => `blob:${asset}` })
|
|
expect(await mapped.loader.import('a', '', {})).toEqual({ url: `blob:${reference}` })
|
|
const resolveAsset = mapped.loader.resolveAsset
|
|
expect(resolveAsset(reference)).toBe(`blob:${reference}`)
|
|
})
|
|
|
|
it('loads a package-local dynamic chunk only when its factory requests it', async () => {
|
|
const b = bench([row('a')], {
|
|
a: req => ({ load: () => req.async('./client.terminal.js') }),
|
|
}, {
|
|
chunks: { 'a/client.terminal.js': () => ({ marker: 'terminal' }) },
|
|
})
|
|
const entry = await b.loader.import('a', '', {}) as { load: () => Promise<{ marker: string }> }
|
|
expect(b.fetched).toEqual([APPLICATION_URL])
|
|
|
|
const first = await entry.load()
|
|
const second = await entry.load()
|
|
expect(first).toBe(second)
|
|
expect(first).toEqual({ marker: 'terminal' })
|
|
expect(b.fetched).toEqual([APPLICATION_URL, chunkReference('a', 'client.terminal.js')])
|
|
})
|
|
|
|
it('loads a package-local chunk with the revision that invalidated its entry', async () => {
|
|
const b = bench([row('a')], {
|
|
a: req => ({ load: () => req.async('./client.terminal.js') }),
|
|
}, {
|
|
chunks: { 'a/client.terminal.js': () => ({ marker: 'terminal' }) },
|
|
})
|
|
const first = await b.loader.import('a', '', {}) as { load: () => Promise<unknown> }
|
|
await first.load()
|
|
|
|
b.loader.invalidate('a', 'rebuilt')
|
|
const second = await b.loader.import('a', '', {}) as { load: () => Promise<unknown> }
|
|
await second.load()
|
|
expect(b.fetched).toEqual([
|
|
APPLICATION_URL,
|
|
chunkReference('a', 'client.terminal.js'),
|
|
comboReference(['a'], 'rebuilt'),
|
|
chunkReference('a', 'client.terminal.js', 'rebuilt'),
|
|
])
|
|
})
|
|
|
|
it('answers a bare asynchronous request through the ordinary module import path', async () => {
|
|
const b = bench([row('a'), row('b')], {
|
|
a: req => ({ load: () => req.async('b') }),
|
|
b: () => ({ marker: 'b' }),
|
|
})
|
|
const entry = await b.loader.import('a', '', {}) as { load: () => Promise<unknown> }
|
|
await expect(entry.load()).resolves.toEqual({ marker: 'b' })
|
|
})
|
|
|
|
it('materializes a parser-preloaded chunk without another transport', async () => {
|
|
const b = bench([row('a')], {
|
|
a: req => ({ load: () => req.async('./client.preloaded.js') }),
|
|
}, {
|
|
pending: [{ id: 'a', chunk: 'client.preloaded.js', factory: () => ({ marker: 'preloaded' }) }],
|
|
})
|
|
const entry = await b.loader.import('a', '', {}) as { load: () => Promise<unknown> }
|
|
await expect(entry.load()).resolves.toEqual({ marker: 'preloaded' })
|
|
expect(b.fetched).toEqual([APPLICATION_URL])
|
|
})
|
|
|
|
it('shares one in-flight package-local chunk transport', async () => {
|
|
const url = chunkReference('a', 'client.terminal.js')
|
|
const b = bench([row('a')], {
|
|
a: req => ({ load: () => req.async('./client.terminal.js') }),
|
|
}, {
|
|
gated: [url],
|
|
chunks: { 'a/client.terminal.js': () => ({ marker: 'terminal' }) },
|
|
})
|
|
const entry = await b.loader.import('a', '', {}) as { load: () => Promise<unknown> }
|
|
const first = entry.load()
|
|
const second = entry.load()
|
|
expect(b.gates.has(url)).toBe(true)
|
|
b.gates.get(url)?.()
|
|
const [left, right] = await Promise.all([first, second])
|
|
expect(left).toBe(right)
|
|
expect(b.fetched.filter(fetched => fetched === url)).toHaveLength(1)
|
|
})
|
|
|
|
it('uses a pending replacement revision for a stale entry closure', async () => {
|
|
const b = bench([row('a')], {
|
|
a: req => ({ load: () => req.async('./client.terminal.js') }),
|
|
}, {
|
|
chunks: { 'a/client.terminal.js': () => ({ marker: 'terminal' }) },
|
|
})
|
|
const stale = await b.loader.import('a', '', {}) as { load: () => Promise<unknown> }
|
|
b.loader.invalidate('a', 'rebuilt')
|
|
await stale.load()
|
|
expect(b.fetched.at(-1)).toBe(chunkReference('a', 'client.terminal.js', 'rebuilt'))
|
|
})
|
|
|
|
it('discards a chunk that arrives after its owner generation was invalidated', async () => {
|
|
const staleUrl = chunkReference('a', 'client.terminal.js')
|
|
const b = bench([row('a')], {
|
|
a: req => ({ load: () => req.async('./client.terminal.js') }),
|
|
}, {
|
|
gated: [staleUrl],
|
|
chunks: { 'a/client.terminal.js': () => ({ marker: 'terminal' }) },
|
|
})
|
|
const staleEntry = await b.loader.import('a', '', {}) as { load: () => Promise<unknown> }
|
|
const staleLoad = staleEntry.load()
|
|
expect(b.gates.has(staleUrl)).toBe(true)
|
|
b.loader.invalidate('a', 'rebuilt')
|
|
await b.loader.import('a', '', {})
|
|
b.gates.get(staleUrl)?.()
|
|
|
|
await expect(staleLoad).resolves.toEqual({ marker: 'terminal' })
|
|
expect(b.fetched).toContain(chunkReference('a', 'client.terminal.js', 'rebuilt'))
|
|
})
|
|
})
|
|
|
|
describe('bundle arrival recovery', () => {
|
|
const single = (id: string): string => comboReference([id], '0')
|
|
|
|
it('retries a batch once after a transport failure and shares the retry across its rows', async () => {
|
|
const b = bench([row('a'), row('b')], { a: () => ({ a: 1 }), b: () => ({ b: 2 }) }, {
|
|
transportFailures: { [APPLICATION_URL]: 1 },
|
|
})
|
|
const [a, c] = await Promise.all([b.loader.import('a', '', {}), b.loader.import('b', '', {})])
|
|
expect(a).toEqual({ a: 1 })
|
|
expect(c).toEqual({ b: 2 })
|
|
expect(b.fetched).toEqual([APPLICATION_URL, APPLICATION_URL])
|
|
})
|
|
|
|
it('falls back to each missing row\'s one-resource URL when the batch keeps failing, without re-fetching the batch per row', async () => {
|
|
const b = bench([row('a'), row('b')], { a: () => ({ a: 1 }), b: () => ({ b: 2 }) }, {
|
|
transportFailures: { [APPLICATION_URL]: 5 },
|
|
})
|
|
const [a, c] = await Promise.all([b.loader.import('a', '', {}), b.loader.import('b', '', {})])
|
|
expect(a).toEqual({ a: 1 })
|
|
expect(c).toEqual({ b: 2 })
|
|
expect(b.fetched.filter(url => url === APPLICATION_URL)).toHaveLength(2)
|
|
expect(b.fetched.slice(2).sort()).toEqual([single('a'), single('b')].sort())
|
|
expect(b.loader.importError('a')).toBeUndefined()
|
|
})
|
|
|
|
it('does not re-execute a batch that loaded without registering; the missing row loads alone', async () => {
|
|
const b = bench([row('a')], { a: () => ({ a: 1 }) }, { registerOnly: { [APPLICATION_URL]: [] } })
|
|
expect(await b.loader.import('a', '', {})).toEqual({ a: 1 })
|
|
expect(b.fetched).toEqual([APPLICATION_URL, single('a')])
|
|
})
|
|
|
|
it('after a partially registering batch, loads only the missing row and never duplicates the registered one', async () => {
|
|
const b = bench([row('a'), row('b')], { a: () => ({ a: 1 }), b: () => ({ b: 2 }) }, {
|
|
registerOnly: { [APPLICATION_URL]: ['a'] },
|
|
})
|
|
expect(await b.loader.import('b', '', {})).toEqual({ b: 2 })
|
|
expect(b.fetched).toEqual([APPLICATION_URL, single('b')])
|
|
expect(await b.loader.import('a', '', {})).toEqual({ a: 1 })
|
|
expect(b.fetched).toHaveLength(2)
|
|
})
|
|
|
|
it('never re-executes a batch that already ran, even when its first importer was one of the rows it did register', async () => {
|
|
const b = bench([row('a'), row('b')], { a: () => ({ a: 1 }), b: () => ({ b: 2 }) }, {
|
|
registerOnly: { [APPLICATION_URL]: ['a'] },
|
|
})
|
|
expect(await b.loader.import('a', '', {})).toEqual({ a: 1 })
|
|
expect(b.fetched).toEqual([APPLICATION_URL])
|
|
expect(await b.loader.import('b', '', {})).toEqual({ b: 2 })
|
|
expect(b.fetched).toEqual([APPLICATION_URL, single('b')])
|
|
})
|
|
|
|
it('reports every attempt when the one-resource fallback fails too', async () => {
|
|
const b = bench([row('a')], { a: () => ({ a: 1 }) }, {
|
|
transportFailures: { [APPLICATION_URL]: 2, [single('a')]: 1 },
|
|
})
|
|
const failure: unknown = await b.loader.import('a', '', {}).then(() => undefined, (error: unknown) => error)
|
|
if (!(failure instanceof Error)) throw new Error('import resolved')
|
|
expect(failure.message).toContain('could not load "a"')
|
|
const batchAttempts = failure.message.split(`${APPLICATION_URL}: client-modules: bundle script`).length - 1
|
|
expect(batchAttempts).toBe(2)
|
|
expect(failure.message).toContain(`${single('a')}: client-modules: bundle script`)
|
|
expect(b.fetched).toEqual([APPLICATION_URL, APPLICATION_URL, single('a')])
|
|
})
|
|
|
|
it('a one-resource URL that fails stays retryable on the next import instead of being remembered as a failed batch', async () => {
|
|
const reloadUrl = comboReference(['a'], '1')
|
|
const b = bench([row('a')], { a: () => ({ a: 1 }) }, { transportFailures: { [reloadUrl]: 2 } })
|
|
expect(await b.loader.import('a', '', {})).toEqual({ a: 1 })
|
|
b.loader.invalidate('a', '1')
|
|
await expect(b.loader.import('a', '', {})).rejects.toThrow('could not load "a"')
|
|
expect(await b.loader.import('a', '', {})).toEqual({ a: 1 })
|
|
expect(b.fetched).toEqual([APPLICATION_URL, reloadUrl, reloadUrl, reloadUrl])
|
|
})
|
|
})
|
|
|
|
describe('import error record', () => {
|
|
it('records the transport failure of a row and clears it once the row imports', async () => {
|
|
const b = bench([row('a')], { a: () => ({ a: 1 }) }, {
|
|
transportFailures: { [APPLICATION_URL]: 2, [comboReference(['a'], '0')]: 1 },
|
|
})
|
|
await expect(b.loader.import('a', '', {})).rejects.toThrow()
|
|
expect(b.loader.importError('a')?.message).toContain('could not load "a"')
|
|
expect(b.loader.importError('a/client')).toBe(b.loader.importError('a'))
|
|
expect(await b.loader.import('a', '', {})).toEqual({ a: 1 })
|
|
expect(b.loader.importError('a')).toBeUndefined()
|
|
})
|
|
|
|
it('records a factory that throws during materialization, which no arrival record could see', async () => {
|
|
const b = bench([row('a')], { a: () => { throw new Error('factory exploded') } })
|
|
await expect(b.loader.import('a', '', {})).rejects.toThrow('factory exploded')
|
|
expect(b.loader.importError('a')?.message).toBe('factory exploded')
|
|
})
|
|
|
|
it('names the failed dependency in the consumer\'s record so a cascade reads as a chain', async () => {
|
|
const b = bench([row('dep'), row('consumer', { inject: ['dep'] })], { dep: () => ({}), consumer: () => ({}) }, {
|
|
registerOnly: { [APPLICATION_URL]: ['consumer'] },
|
|
transportFailures: { [comboReference(['dep'], '0')]: 1 },
|
|
})
|
|
await expect(b.loader.import('consumer', '', {})).rejects.toThrow(
|
|
'"consumer" not loaded because dependency "dep" failed: client-modules: could not load "dep"',
|
|
)
|
|
expect(b.loader.importError('consumer')?.message).toContain('dependency "dep" failed')
|
|
expect(b.loader.importError('dep')).toBeUndefined()
|
|
expect(b.loader.importError('consumer')?.cause).toBeInstanceOf(Error)
|
|
})
|
|
|
|
it('records a non-Error thrown by a factory as an Error carrying its text', async () => {
|
|
const b = bench([row('a')], { a: () => { throw 'factory rejected a string' } })
|
|
await expect(b.loader.import('a', '', {})).rejects.toBe('factory rejected a string')
|
|
expect(b.loader.importError('a')).toBeInstanceOf(Error)
|
|
expect(b.loader.importError('a')?.message).toBe('factory rejected a string')
|
|
})
|
|
|
|
it('records a prefetch failure and invalidate clears the record', async () => {
|
|
const b = bench([row('a')], { a: null })
|
|
await expect(b.loader.prefetch('a')).rejects.toThrow('without registering "a"')
|
|
expect(b.loader.importError('a')).toBeDefined()
|
|
b.loader.invalidate('a')
|
|
expect(b.loader.importError('a')).toBeUndefined()
|
|
})
|
|
|
|
it('has no record for a row that never failed or is unknown', () => {
|
|
const b = bench([row('a')], { a: () => ({}) })
|
|
expect(b.loader.importError('a')).toBeUndefined()
|
|
expect(b.loader.importError('nope')).toBeUndefined()
|
|
})
|
|
})
|
|
|
|
describe('require resolution', () => {
|
|
it('a factory requiring a registered-but-unmaterialized module materializes it recursively', async () => {
|
|
const order: string[] = []
|
|
const b = bench([row('a'), row('b')], {
|
|
a: (req) => {
|
|
order.push('a')
|
|
const dep = req('b/client') as { helper: string }
|
|
return { got: dep.helper }
|
|
},
|
|
b: () => { order.push('b'); return { helper: 'from-b' } },
|
|
})
|
|
await b.loader.prefetch('a')
|
|
await b.loader.prefetch('b')
|
|
const exports = await b.loader.import('a', '', {})
|
|
expect((exports as { got: string }).got).toBe('from-b')
|
|
expect(order).toEqual(['a', 'b'])
|
|
expect(b.loader.loadCache.get('a')?.edges.has('b/client')).toBe(true)
|
|
expect(b.loader.loadCache.has('b')).toBe(true)
|
|
})
|
|
|
|
it('require and import share one materialized platform instance', async () => {
|
|
const react = { marker: 'react' }
|
|
const b = bench([row('a')], {
|
|
a: req => ({ dep: req('react') }),
|
|
}, { seed: [{ id: 'react', factory: () => react }] })
|
|
const exports = await b.loader.import('a', '', {})
|
|
expect((exports as { dep: unknown }).dep).toBe(react)
|
|
expect(await b.loader.import('react', '', {})).toBe(react)
|
|
expect(b.loader.loadCache.get('react')?.exports).toBe(react)
|
|
})
|
|
|
|
it('require answers an already-materialized module from the cache', async () => {
|
|
let built = 0
|
|
const b = bench([row('a'), row('c')], {
|
|
a: req => ({ dep: req('c') }),
|
|
c: () => { built += 1; return { marker: 'c' } },
|
|
})
|
|
const c = await b.loader.import('c', '', {})
|
|
const a = await b.loader.import('a', '', {})
|
|
expect((a as { dep: unknown }).dep).toBe(c)
|
|
expect(built).toBe(1)
|
|
})
|
|
|
|
it('a require that misses the module table is loud', async () => {
|
|
const b = bench([row('a')], { a: req => ({ dep: req('ghost') }) })
|
|
await expect(b.loader.import('a', '', {})).rejects.toThrow('require("ghost") missed the module table')
|
|
})
|
|
|
|
it('a require cycle is fatal', async () => {
|
|
const b = bench([row('a'), row('b')], {
|
|
a: req => ({ dep: req('b') }),
|
|
b: req => ({ dep: req('a') }),
|
|
})
|
|
await b.loader.prefetch('b')
|
|
await expect(b.loader.import('a', '', {})).rejects.toThrow('require cycle through "a"')
|
|
})
|
|
})
|
|
|
|
describe('bootstrap module', () => {
|
|
it('caches the materialized modules exports under the package id and /client alias', async () => {
|
|
const b = bench([
|
|
row('consumer', { external: [`${MODULES_ID}/client`] }),
|
|
row(MODULES_ID),
|
|
], {
|
|
consumer: req => ({ dep: req(`${MODULES_ID}/client`) }),
|
|
})
|
|
await b.loader.prefetch(MODULES_ID)
|
|
const exports = await b.loader.import('consumer', '', {}) as { dep: unknown }
|
|
expect(exports.dep).toBe(bootstrapExports)
|
|
expect(await b.loader.import(`${MODULES_ID}/client`, '', {})).toBe(bootstrapExports)
|
|
expect(b.fetched).toEqual([APPLICATION_URL])
|
|
})
|
|
|
|
it('publishes the module system attached to its own Loader', () => {
|
|
const a = bench([], {})
|
|
const b = bench([], {})
|
|
const ctxA = new Context()
|
|
const ctxB = new Context()
|
|
ctxA.reflect.provide('loader', { internal: a.loader })
|
|
ctxB.reflect.provide('loader', { internal: b.loader })
|
|
|
|
apply(ctxA)
|
|
apply(ctxB)
|
|
|
|
expect(ctxA.modules).toBe(a.loader)
|
|
expect(ctxB.modules).toBe(b.loader)
|
|
})
|
|
|
|
it('rejects a second queued registration for the bootstrap id', () => {
|
|
expect(() => bench([], {}, {
|
|
pending: [{ id: MODULES_ID, factory: () => ({}) }],
|
|
})).toThrow(`duplicate factory registration for "${MODULES_ID}"`)
|
|
})
|
|
})
|
|
|
|
describe('failure modes', () => {
|
|
it('duplicate factory registration is loud, including reuse of the same manifest object', () => {
|
|
bench([])
|
|
const registration = { id: 'x', factory: () => ({}) }
|
|
win.__ModuleLoader__?.load(registration)
|
|
expect(() => win.__ModuleLoader__?.load(registration))
|
|
.toThrow('duplicate factory registration for "x"')
|
|
expect(() => win.__ModuleLoader__?.load({ id: 'x', factory: () => ({}) }))
|
|
.toThrow('duplicate factory registration for "x"')
|
|
})
|
|
|
|
it('rejects malformed and duplicate chunk registrations', () => {
|
|
const b = bench([])
|
|
expect(() => { b.target.load({ id: 'a', chunk: '../bad.js', factory: () => ({}) }) })
|
|
.toThrow('invalid package-local chunk "../bad.js"')
|
|
b.target.load({ id: 'a', chunk: 'client.terminal.js', factory: () => ({}) })
|
|
expect(() => { b.target.load({ id: 'a', chunk: 'client.terminal.js', factory: () => ({}) }) })
|
|
.toThrow('duplicate factory registration for "a/client.terminal.js"')
|
|
})
|
|
|
|
it('rejects malformed relative chunk requests', async () => {
|
|
const b = bench([row('a')], {
|
|
a: req => ({ load: () => req.async('./terminal.js') }),
|
|
})
|
|
const entry = await b.loader.import('a', '', {}) as { load: () => Promise<unknown> }
|
|
await expect(entry.load()).rejects.toThrow('invalid relative chunk request "./terminal.js"')
|
|
})
|
|
|
|
it('rejects a chunk request from a manually registered owner outside the boot graph', async () => {
|
|
const b = bench([])
|
|
b.target.load({
|
|
id: 'orphan',
|
|
factory: req => ({ load: () => req.async('./client.terminal.js') }),
|
|
})
|
|
const entry = await b.loader.import('orphan', '', {}) as { load: () => Promise<unknown> }
|
|
await expect(entry.load()).rejects.toThrow('chunk owner "orphan" is not a boot graph entry')
|
|
})
|
|
|
|
it('rejects a graph row whose one-resource URL cannot address sibling chunks', async () => {
|
|
const b = bench([row('a', { url: 'plugins/a/client.js?rev=0' })], {
|
|
a: req => ({ load: () => req.async('./client.terminal.js') }),
|
|
})
|
|
const entry = await b.loader.import('a', '', {}) as { load: () => Promise<unknown> }
|
|
await expect(entry.load()).rejects.toThrow('cannot resolve chunk "client.terminal.js"')
|
|
})
|
|
|
|
it('rejects a chunk script that does not register its generated id', async () => {
|
|
const b = bench([row('a')], {
|
|
a: req => ({ load: () => req.async('./client.missing.js') }),
|
|
})
|
|
const entry = await b.loader.import('a', '', {}) as { load: () => Promise<unknown> }
|
|
await expect(entry.load()).rejects.toThrow('loaded without registering "a/client.missing.js"')
|
|
})
|
|
|
|
it('a bundle that never registers its id is loud', async () => {
|
|
const b = bench([row('a')], { a: null })
|
|
await expect(b.loader.import('a', '', {})).rejects.toThrow('without registering "a"')
|
|
})
|
|
|
|
it('an unknown import specifier is loud', async () => {
|
|
const b = bench([])
|
|
await expect(b.loader.import('nope', '', {})).rejects.toThrow('cannot resolve "nope"')
|
|
})
|
|
|
|
it('an unknown prefetch id is loud', async () => {
|
|
const b = bench([])
|
|
await expect(b.loader.prefetch('nope')).rejects.toThrow('prefetch("nope") — not a graph entry')
|
|
})
|
|
|
|
it('a duplicate graph entry is loud at construction', () => {
|
|
expect(() => bench([row('a'), row('a')])).toThrow('duplicate graph entry "a"')
|
|
})
|
|
|
|
it('a module arrival cycle is loud even if a malformed host graph reaches the browser', async () => {
|
|
const b = bench([
|
|
row('a', { external: ['b'] }),
|
|
row('b', { external: ['a'] }),
|
|
])
|
|
await expect(b.loader.prefetch('a')).rejects.toThrow('module arrival cycle a -> b -> a')
|
|
})
|
|
|
|
it('double boot is loud', () => {
|
|
const b = bench([])
|
|
const options: ClientModuleCreateOptions = {
|
|
boot: { rev: 'graph', entries: [], batches: [] },
|
|
staticModules: [],
|
|
}
|
|
expect(() => b.target.create(options)).toThrow('create called after module-system boot')
|
|
})
|
|
})
|
|
|
|
describe('boot manifest wire', () => {
|
|
it('normalizes absent shared-module fields and carries the declared ones', () => {
|
|
const manifest = parseBootManifest({
|
|
rev: 'graph',
|
|
entries: [
|
|
{ id: 'a', url: 'plugins/a/client.js', rev: '1', inject: ['b'] },
|
|
{ id: 'b', url: 'plugins/b/client.js', rev: '2', external: ['react'] },
|
|
],
|
|
batches: [{ phase: 'application', url: 'batch.js', rev: 'batch', entries: ['a', 'b'] }],
|
|
})
|
|
const isolation = { script: false, style: false }
|
|
expect(manifest.modules).toEqual([
|
|
{ id: 'a', url: 'plugins/a/client.js', initialUrl: 'batch.js', rev: '1', inject: ['b'], external: [], isolation },
|
|
{ id: 'b', url: 'plugins/b/client.js', initialUrl: 'batch.js', rev: '2', inject: [], external: ['react'], isolation },
|
|
])
|
|
})
|
|
|
|
it('rejects a non-array external', () => {
|
|
expect(() => parseBootManifest({
|
|
rev: 'graph',
|
|
entries: [{ id: 'a', url: '/a', rev: '1', external: 'react' }],
|
|
batches: [{ phase: 'application', url: '/batch.js', rev: 'batch', entries: ['a'] }],
|
|
})).toThrow('client-modules: boot manifest entry "a" external must be a string array')
|
|
})
|
|
|
|
it('requires the batch table', () => {
|
|
expect(() => parseBootManifest({ rev: 'graph', entries: [] }))
|
|
.toThrow('client-modules: boot manifest batches must be an array')
|
|
})
|
|
|
|
it('carries an optional Host release and rejects a malformed one', () => {
|
|
const wire = { rev: 'graph', entries: [], batches: [] }
|
|
expect(parseBootManifest(wire)).not.toHaveProperty('release')
|
|
expect(parseBootManifest({ ...wire, release: { version: '1.0.0' } }).release).toEqual({ version: '1.0.0' })
|
|
// Members outside the identity are dropped so equality compares only version and commit.
|
|
expect(parseBootManifest({ ...wire, release: { version: '1.0.0', commit: 'abc1234', label: 'x' } }).release)
|
|
.toEqual({ version: '1.0.0', commit: 'abc1234' })
|
|
for (const release of ['1.0.0', null, {}, { version: 1 }, { version: '1.0.0', commit: 7 }]) {
|
|
expect(() => parseBootManifest({ ...wire, release }))
|
|
.toThrow('client-modules: boot manifest release must carry a string version and an optional string commit')
|
|
// Release comparison reads no further than the release and reports an unreadable one as absent.
|
|
expect(readRelease({ release })).toBeUndefined()
|
|
}
|
|
expect(readRelease({ release: { version: '1.0.0', commit: 'abc1234', label: 'x' }, entries: 'another format' }))
|
|
.toEqual({ version: '1.0.0', commit: 'abc1234' })
|
|
expect(readRelease(null)).toBeUndefined()
|
|
})
|
|
|
|
it('rejects malformed batch phases', () => {
|
|
const entry = { id: 'a', url: '/a.js', rev: '1' }
|
|
expect(() => parseBootManifest({ rev: 'graph', entries: [entry], batches: [null] }))
|
|
.toThrow('client-modules: boot manifest batch is not an object')
|
|
expect(() => parseBootManifest({
|
|
rev: 'graph', entries: [entry], batches: [{ phase: 'idle', url: '/b.js', rev: 'b', entries: ['a'] }],
|
|
})).toThrow('boot manifest batch phase must be "bootstrap" or "application"')
|
|
})
|
|
|
|
it('rejects duplicate batch URLs', () => {
|
|
expect(() => parseBootManifest({
|
|
rev: 'graph',
|
|
entries: [
|
|
{ id: 'a', url: '/a.js', rev: '1' },
|
|
{ id: 'b', url: '/b.js', rev: '2' },
|
|
],
|
|
batches: [
|
|
{ phase: 'application', url: '/combo.js', rev: '1', entries: ['a'] },
|
|
{ phase: 'application', url: '/combo.js', rev: '2', entries: ['b'] },
|
|
],
|
|
})).toThrow('boot manifest carries duplicate batch URL "/combo.js"')
|
|
})
|
|
|
|
it('allows several batches in one scheduling phase', () => {
|
|
const manifest = parseBootManifest({
|
|
rev: 'graph',
|
|
entries: [
|
|
{ id: 'a', url: '/a.js', rev: '1' },
|
|
{ id: 'b', url: '/b.js', rev: '2' },
|
|
],
|
|
batches: [
|
|
{ phase: 'application', url: '/b.js', rev: '1', entries: ['a'] },
|
|
{ phase: 'application', url: '/c.js', rev: '2', entries: ['b'] },
|
|
],
|
|
})
|
|
expect(manifest.modules.map(row => row.initialUrl)).toEqual(['/b.js', '/c.js'])
|
|
})
|
|
|
|
it('requires complete batch fields and non-empty entries', () => {
|
|
const entry = { id: 'a', url: '/a.js', rev: '1' }
|
|
expect(() => parseBootManifest({
|
|
rev: 'graph', entries: [entry], batches: [{ phase: 'application', entries: ['a'] }],
|
|
})).toThrow('boot manifest application batch must carry string url/rev')
|
|
expect(() => parseBootManifest({
|
|
rev: 'graph', entries: [entry], batches: [{ phase: 'application', url: '/b.js', rev: 'b', entries: [] }],
|
|
})).toThrow('boot manifest application batch entries must be a non-empty string array')
|
|
})
|
|
|
|
it('requires a one-to-one batch assignment over graph entries', () => {
|
|
const entries = [
|
|
{ id: 'a', url: '/a.js', rev: '1' },
|
|
{ id: 'b', url: '/b.js', rev: '2' },
|
|
]
|
|
expect(() => parseBootManifest({
|
|
rev: 'graph',
|
|
entries,
|
|
batches: [{ phase: 'application', url: '/batch.js', rev: 'b', entries: ['ghost'] }],
|
|
})).toThrow('boot manifest application batch names unknown entry "ghost"')
|
|
expect(() => parseBootManifest({
|
|
rev: 'graph',
|
|
entries,
|
|
batches: [
|
|
{ phase: 'bootstrap', url: '/boot.js', rev: 'boot', entries: ['a'] },
|
|
{ phase: 'application', url: '/batch.js', rev: 'app', entries: ['a', 'b'] },
|
|
],
|
|
})).toThrow('boot manifest entry "a" belongs to more than one batch')
|
|
expect(() => parseBootManifest({
|
|
rev: 'graph',
|
|
entries,
|
|
batches: [{ phase: 'application', url: '/batch.js', rev: 'b', entries: ['a'] }],
|
|
})).toThrow('boot manifest entry "b" belongs to no initial-load batch')
|
|
})
|
|
})
|
|
|
|
describe('HMR reset', () => {
|
|
it('invalidate drops the factory and record so the module reloads and re-registers', async () => {
|
|
let generation = 0
|
|
const b = bench([row('a')], { a: () => ({ generation: ++generation }) })
|
|
const first = await b.loader.import('a', '', {})
|
|
b.loader.invalidate('a', '1')
|
|
expect(b.loader.loadCache.has('a')).toBe(false)
|
|
await b.loader.prefetch('a')
|
|
const second = await b.loader.import('a', '', {})
|
|
expect(b.fetched).toEqual([APPLICATION_URL, comboReference(['a'], '1')])
|
|
expect((first as { generation: number }).generation).toBe(1)
|
|
expect((second as { generation: number }).generation).toBe(2)
|
|
})
|
|
|
|
it('preserves an absolute combo endpoint when applying the rebuilt revision', async () => {
|
|
const b = bench([
|
|
row('a', { url: 'https://plugins.example.test/plugins/??a/client.js&rev=0' }),
|
|
], { a: () => ({}) })
|
|
await b.loader.import('a', '', {})
|
|
b.loader.invalidate('a', 'next')
|
|
await b.loader.prefetch('a')
|
|
expect(b.fetched.at(-1)).toBe('https://plugins.example.test/plugins/??a/client.js&rev=next')
|
|
})
|
|
|
|
it('preserves a protocol-relative combo endpoint when applying the rebuilt revision', async () => {
|
|
const b = bench([
|
|
row('a', { url: '//plugins.example.test/plugins/??a/client.js&rev=0' }),
|
|
], { a: () => ({}) })
|
|
await b.loader.import('a', '', {})
|
|
b.loader.invalidate('a', 'next')
|
|
await b.loader.prefetch('a')
|
|
expect(b.fetched.at(-1)).toBe('//plugins.example.test/plugins/??a/client.js&rev=next')
|
|
})
|
|
|
|
it('uses the current plugin revision when a graph-row invalidation omits an override', async () => {
|
|
const b = bench([row('a')], { a: () => ({}) })
|
|
await b.loader.import('a', '', {})
|
|
b.loader.invalidate('a')
|
|
await b.loader.prefetch('a')
|
|
expect(b.fetched).toEqual([APPLICATION_URL, comboReference(['a'], '0')])
|
|
})
|
|
})
|
|
|
|
describe('opaque module metadata', () => {
|
|
it('retains metadata producers for external consumers without claiming document nodes', async () => {
|
|
const earlier = document.createElement('style')
|
|
earlier.textContent = '.earlier {}'
|
|
document.head.appendChild(earlier)
|
|
const text = vi.fn(() => '.a {}')
|
|
const meta = vi.fn(() => ({ stylesheets: { 'a.css': { text } } }))
|
|
const b = bench([row('a')], { a: () => ({}) }, { metadata: { a: meta } })
|
|
await b.loader.prefetch('a')
|
|
expect(meta).not.toHaveBeenCalled()
|
|
await b.loader.import('a', '', {})
|
|
expect(meta).not.toHaveBeenCalled()
|
|
expect(text).not.toHaveBeenCalled()
|
|
expect(b.loader.loadCache.get('a')?.meta).toBe(meta)
|
|
expect(meta).not.toHaveBeenCalled()
|
|
expect(text).not.toHaveBeenCalled()
|
|
expect([...document.querySelectorAll('style')]).toEqual([earlier])
|
|
expect(earlier.getAttributeNames()).toEqual([])
|
|
b.loader.invalidate('a')
|
|
expect(b.loader.loadCache.has('a')).toBe(false)
|
|
expect(earlier.isConnected).toBe(true)
|
|
})
|
|
|
|
it('does not claim style nodes inserted by plugin code before a nested require', async () => {
|
|
const inserted = document.createElement('style')
|
|
const b = bench([row('b'), row('a', { external: ['b'] })], {
|
|
a: (require) => { document.head.appendChild(inserted); require('b'); return {} },
|
|
b: () => ({}),
|
|
}, { metadata: { a: stylesheet('a.css', '.a {}'), b: stylesheet('b.css', '.b {}') } })
|
|
await b.loader.import('a', '', {})
|
|
expect(inserted.getAttributeNames()).toEqual([])
|
|
expect([...document.querySelectorAll('style')]).toEqual([inserted])
|
|
expect(b.loader.loadCache.get('a')?.edges).toEqual(new Set(['b']))
|
|
})
|
|
|
|
it('does not evaluate failed factory metadata or remove document nodes', async () => {
|
|
const existing = document.createElement('style')
|
|
existing.dataset.plugin = 'a'
|
|
document.head.appendChild(existing)
|
|
const inserted = document.createElement('style')
|
|
const meta = vi.fn(stylesheet('a.css', '.a {}'))
|
|
const b = bench([row('a')], { a: () => {
|
|
document.head.appendChild(inserted)
|
|
throw new Error('factory exploded')
|
|
} }, { metadata: { a: meta } })
|
|
const changed = vi.fn()
|
|
const off = b.loader.subscribeModules(changed)
|
|
await expect(b.loader.import('a', '', {})).rejects.toThrow('factory exploded')
|
|
expect(b.loader.loadCache.has('a')).toBe(false)
|
|
expect(meta).not.toHaveBeenCalled()
|
|
expect(b.loader.loadCache.has('a')).toBe(false)
|
|
expect(changed).not.toHaveBeenCalled()
|
|
off()
|
|
expect([...document.querySelectorAll('style')]).toEqual([existing, inserted])
|
|
expect(inserted.getAttributeNames()).toEqual([])
|
|
})
|
|
|
|
it('retains opaque metadata without a document', async () => {
|
|
const b = bench([row('a')], { a: () => ({}) }, { metadata: { a: stylesheet('a.css', '.a {}') } })
|
|
vi.stubGlobal('document', undefined)
|
|
try {
|
|
await b.loader.import('a', '', {})
|
|
expect(typeof b.loader.loadCache.get('a')?.meta).toBe('function')
|
|
} finally {
|
|
vi.unstubAllGlobals()
|
|
}
|
|
})
|
|
})
|
|
|
|
describe('default transport seam', () => {
|
|
it('loads through an external classic script and removes the settled node', async () => {
|
|
const append = vi.spyOn(document.head, 'append').mockImplementation((...nodes) => {
|
|
const script = nodes[0]
|
|
if (!(script instanceof HTMLScriptElement)) throw new Error('expected script node')
|
|
expect(script.async).toBe(true)
|
|
expect(script.getAttribute('src')).toBe(APPLICATION_URL)
|
|
queueMicrotask(() => {
|
|
win.__ModuleLoader__?.load({ id: 'dee', factory: () => ({ marker: 'via-script' }) })
|
|
script.dispatchEvent(new Event('load'))
|
|
})
|
|
})
|
|
const b = bench([row('dee')], {}, { defaultTransport: true })
|
|
const exports = await b.loader.import('dee', '', {})
|
|
expect((exports as { marker: string }).marker).toBe('via-script')
|
|
expect(append).toHaveBeenCalledOnce()
|
|
expect([...document.querySelectorAll('script')]).toEqual([])
|
|
})
|
|
|
|
it('a script load failure is loud and removes the node', async () => {
|
|
vi.spyOn(document.head, 'append').mockImplementation((...nodes) => {
|
|
const script = nodes[0]
|
|
if (!(script instanceof HTMLScriptElement)) throw new Error('expected script node')
|
|
queueMicrotask(() => { script.dispatchEvent(new Event('error')) })
|
|
})
|
|
const b = bench([row('dee')], {}, { defaultTransport: true })
|
|
await expect(b.loader.prefetch('dee')).rejects.toThrow(
|
|
`bundle script ${APPLICATION_URL} failed to load`,
|
|
)
|
|
expect([...document.querySelectorAll('script')]).toEqual([])
|
|
})
|
|
})
|
|
|
|
|
|
it('rejects invalid revision URLs and keeps bootstrap exports pinned under invalidation', () => {
|
|
const b = bench([row(MODULES_ID), row('a', { url: '/unrevisioned' })])
|
|
expect(() =>{ b.loader.invalidate(MODULES_ID) }).toThrow(/requires a page reload/)
|
|
expect(b.loader.loadCache.get(MODULES_ID)?.exports).toBe(bootstrapExports)
|
|
expect(() =>{ b.loader.invalidate('a', 'next') }).toThrow('has no revision')
|
|
})
|
|
|
|
it('prefetch skips platform requests, cached dependencies and absent optional inject rows', async () => {
|
|
const b = bench([
|
|
row('a'),
|
|
row('b', { external: ['platform', 'a/client'], inject: ['missing'] }),
|
|
], { a: () => ({}), b: () => ({}) }, { seed: [{ id: 'platform', factory: () => ({}) }] })
|
|
await b.loader.import('a', '', {})
|
|
await b.loader.import('b', '', {})
|
|
expect(b.fetched).toEqual([APPLICATION_URL])
|
|
})
|
|
|
|
|
|
it('rejects a wire request with no dynamic row or platform supplier at materialization', async () => {
|
|
const b = bench([row('a', { external: ['missing'] })], { a: require => ({ value: require('missing') }) })
|
|
await expect(b.loader.import('a', '', {})).rejects.toThrow('missed the module table')
|
|
})
|