node-half.client.spec.ts 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995
  1. /** Node-half composition diagnostics for package metadata and built client bundles. */
  2. import { mkdirSync, mkdtempSync, realpathSync, rmSync, statSync, writeFileSync } from 'node:fs'
  3. import type { IncomingMessage, ServerResponse } from 'node:http'
  4. import { SourceMap } from 'node:module'
  5. import { tmpdir } from 'node:os'
  6. import { dirname, join } from 'node:path'
  7. import { pathToFileURL } from 'node:url'
  8. import { runInNewContext } from 'node:vm'
  9. import { Context, FiberState, type Fiber } from '@deepseek-ai/cordis'
  10. import { afterEach, describe, expect, it, vi } from 'vitest'
  11. import { renderIndexInjections, type WebServer, type WebRoute } from '@deepseek-ai/dsh-host-webserver'
  12. import * as modulesClient from '../src/client/index.ts'
  13. import { ClientModuleRegistry, bootInjections, orderByModuleGraph } from '../src/index.ts'
  14. import type { ClientModuleLoaderTarget, WebBootEntry, WebBootGraph } from '../src/client/index.ts'
  15. const MODULES_ID = '@deepseek-ai/dsh-client-modules'
  16. const UI_RENDERER_ID = '@deepseek-ai/dsh-client-ui-renderer'
  17. const comboUrl = (ids: readonly string[], rev: string): string =>
  18. `/plugins/??${ids.map(id => `${id}/client.js`).join(',')}&rev=${rev}`
  19. const mapUrl = (url: string): string => url.replace(/\/client\.js(?=,|&rev=)/g, '/client.js.map')
  20. const chunkUrl = (id: string, fileName: string, rev: string): string => `/plugins/${id}/${fileName}?rev=${rev}`
  21. const BOOTSTRAP_URL = comboUrl([MODULES_ID], 'boot')
  22. const APPLICATION_URL = comboUrl([UI_RENDERER_ID], 'app')
  23. let root: string | undefined
  24. const contexts: { ctx: Context; ready?: Promise<WebRoute> }[] = []
  25. afterEach(async () => {
  26. await Promise.all(contexts.splice(0).map(async ({ ctx, ready }) => {
  27. await ready
  28. await ctx.fiber.dispose()
  29. }))
  30. if (root !== undefined) rmSync(root, { recursive: true, force: true })
  31. root = undefined
  32. })
  33. it.each([false, true])('tracks the Web carrier lifetime when server-first is %s', async (serverFirst) => {
  34. const ctx = new Context()
  35. contexts.push({ ctx })
  36. ctx.provide('loader', { entries: () => [] })
  37. const routes = new Set<WebRoute>()
  38. const mountServer = () => ctx.plugin((serverCtx) => {
  39. serverCtx.provide('webServer', {
  40. register: (route: WebRoute) => {
  41. routes.add(route)
  42. return () => { routes.delete(route) }
  43. },
  44. } as WebServer)
  45. })
  46. let server = serverFirst ? await mountServer() : undefined
  47. const modules = await ctx.plugin(ClientModuleRegistry)
  48. const service = ctx.get('clientModules')!
  49. expect(service.graph().entries).toEqual([])
  50. expect((await service.fetchBundle(new Request('http://localhost/plugins/missing'))).status).toBe(404)
  51. if (!serverFirst) {
  52. expect(routes.size).toBe(0)
  53. server = await mountServer()
  54. }
  55. await expect.poll(() => routes.size).toBe(1)
  56. await server!.dispose()
  57. await expect.poll(() => routes.size).toBe(0)
  58. expect(modules.state).toBe(FiberState.ACTIVE)
  59. expect((await service.fetchBundle(new Request('http://localhost/plugins/missing'))).status).toBe(404)
  60. await mountServer()
  61. await expect.poll(() => routes.size).toBe(1)
  62. await modules.dispose()
  63. expect(routes.size).toBe(0)
  64. })
  65. /** Create a resolvable package whose client export points at the returned path. */
  66. function writePackage(
  67. packageName: string,
  68. metadata: Record<string, unknown> = { dsh: { client: { platform: 'web' } } },
  69. ): string {
  70. root ??= realpathSync(mkdtempSync(join(tmpdir(), 'dsh-client-modules-')))
  71. const pkgRoot = join(root, 'node_modules', ...packageName.split('/'))
  72. const clientPath = join(pkgRoot, 'lib', 'client.js')
  73. mkdirSync(pkgRoot, { recursive: true })
  74. writeFileSync(join(pkgRoot, 'package.json'), JSON.stringify({
  75. name: packageName,
  76. exports: {
  77. './client': './lib/client.js',
  78. './package.json': './package.json',
  79. },
  80. ...metadata,
  81. }))
  82. return clientPath
  83. }
  84. /** Create a built package with the supplied client declaration. */
  85. function writeBuiltPackage(packageName: string, client: Record<string, unknown>): void {
  86. const clientPath = writePackage(packageName, { dsh: { client: { platform: 'web', ...client } } })
  87. mkdirSync(dirname(clientPath), { recursive: true })
  88. writeFileSync(clientPath, 'module.exports = {}\n')
  89. }
  90. /** Construct the node-half service and capture its plugin-bundle route. */
  91. function constructWithRoute(
  92. packageNames: string[],
  93. options: {
  94. contextBaseUrl?: string
  95. entryBaseUrl?: string
  96. internal?: NonNullable<Context['loader']['internal']>
  97. } = {},
  98. ): { context: Context; service: ClientModuleRegistry; route: Promise<WebRoute> } {
  99. const ctx = new Context()
  100. const owned: typeof contexts[number] = { ctx }
  101. contexts.push(owned)
  102. ctx.baseUrl = options.contextBaseUrl ?? pathToFileURL(root!).href + '/'
  103. ctx.provide('loader', {
  104. internal: options.internal,
  105. *entries() {
  106. for (const packageName of packageNames) {
  107. yield {
  108. options: { name: packageName },
  109. fiber: {},
  110. disabled: false,
  111. parent: { tree: { ctx: { baseUrl: options.entryBaseUrl ?? ctx.baseUrl } } },
  112. }
  113. }
  114. },
  115. })
  116. const route = Promise.withResolvers<WebRoute>()
  117. const webServer: Pick<WebServer, 'port' | 'register' | 'tapIndex'> = {
  118. port: 0,
  119. register: (candidate) => {
  120. if (candidate.path === '/plugins') route.resolve(candidate)
  121. return () => {}
  122. },
  123. tapIndex: () => () => {},
  124. }
  125. ctx.provide('webServer', webServer as WebServer)
  126. const service = new ClientModuleRegistry(ctx)
  127. owned.ready = route.promise
  128. return { context: ctx, service, route: route.promise }
  129. }
  130. /** Construct the node-half service over the enabled fixture entries. */
  131. function construct(packageNames: string[]): ClientModuleRegistry {
  132. return constructWithRoute(packageNames).service
  133. }
  134. /** Invoke the registered plugin route and capture status, headers, and bytes. */
  135. async function routeRequest(route: Promise<WebRoute>, url: string, method = 'GET'): Promise<{
  136. status: number
  137. headers: Record<string, string> | undefined
  138. body: Buffer
  139. }> {
  140. let status = 0
  141. let headers: Record<string, string> | undefined
  142. let body = Buffer.alloc(0)
  143. const response = {
  144. writeHead(nextStatus: number, nextHeaders?: Record<string, string>) {
  145. status = nextStatus
  146. headers = nextHeaders
  147. return response
  148. },
  149. end(chunk?: Uint8Array) {
  150. body = chunk === undefined ? Buffer.alloc(0) : Buffer.from(chunk)
  151. return response
  152. },
  153. } as unknown as ServerResponse
  154. await (await route).handler({ method, url } as IncomingMessage, response)
  155. return { status, headers, body }
  156. }
  157. /** Execute the exact first inline script emitted by the Host boot rows. */
  158. function injectedFacade(graph: WebBootGraph): { html: string; target: ClientModuleLoaderTarget } {
  159. const html = renderIndexInjections(
  160. '<html><head></head><body><script type="module" src="/index.js"></script></body></html>',
  161. bootInjections(graph),
  162. )
  163. const source = /<head><script>([\s\S]*?)<\/script>/.exec(html)?.[1]
  164. if (source === undefined) throw new Error('missing injected ModuleLoader facade script')
  165. const window: { __ModuleLoader__?: ClientModuleLoaderTarget } = {}
  166. runInNewContext(source, { window })
  167. if (window.__ModuleLoader__ === undefined) throw new Error('facade script did not install __ModuleLoader__')
  168. return { html, target: window.__ModuleLoader__ }
  169. }
  170. const bootGraph = (): WebBootGraph => ({
  171. rev: 'graph',
  172. entries: [
  173. { id: MODULES_ID, url: comboUrl([MODULES_ID], 'm'), rev: 'm' },
  174. { id: UI_RENDERER_ID, url: comboUrl([UI_RENDERER_ID], 'r'), rev: 'r' },
  175. ],
  176. batches: [
  177. {
  178. phase: 'bootstrap',
  179. url: BOOTSTRAP_URL,
  180. rev: 'boot',
  181. entries: [MODULES_ID],
  182. },
  183. {
  184. phase: 'application',
  185. url: APPLICATION_URL,
  186. rev: 'app',
  187. entries: [UI_RENDERER_ID],
  188. },
  189. ],
  190. })
  191. describe('HTML bootstrap facade', () => {
  192. it('precedes blocking preloads and the boot graph, then becomes the live registration target', async () => {
  193. const graph = bootGraph()
  194. const { html, target } = injectedFacade(graph)
  195. const facadeAt = html.indexOf('window.__ModuleLoader__=')
  196. const applicationAt = html.indexOf(
  197. `<link rel="preload" as="script" href="${APPLICATION_URL.replaceAll('&', '&amp;')}">`,
  198. )
  199. const bootstrapAt = html.indexOf(`<script src="${BOOTSTRAP_URL.replaceAll('&', '&amp;')}"></script>`)
  200. const graphAt = html.indexOf('globalThis["__DSH_BOOT__"] = ')
  201. const entryAt = html.indexOf('<script type="module" src="/index.js"></script>')
  202. expect([facadeAt, applicationAt, bootstrapAt, graphAt, entryAt]).toEqual([...new Set([
  203. facadeAt, applicationAt, bootstrapAt, graphAt, entryAt,
  204. ])].sort((a, b) => a - b))
  205. target.load({ id: MODULES_ID, factory: () => modulesClient })
  206. const system = target.create({
  207. boot: graph,
  208. staticModules: {},
  209. loadBundle: async (url) => {
  210. expect(url).toBe(APPLICATION_URL)
  211. target.load({ id: UI_RENDERER_ID, factory: () => ({ marker: 'ui-renderer' }) })
  212. },
  213. })
  214. expect(target.mode).toBe('live')
  215. expect(target.pendingQueue).toEqual([])
  216. expect(system.manifest.rev).toBe('graph')
  217. expect(await system.import(MODULES_ID)).toBe(modulesClient)
  218. expect(await system.import(`${UI_RENDERER_ID}/client`)).toEqual({ marker: 'ui-renderer' })
  219. expect(() => target.create({ boot: graph, staticModules: {} }))
  220. .toThrow('create called after module-system boot')
  221. })
  222. it('preloads every application combo', () => {
  223. const graph = bootGraph()
  224. const secondId = '@fixture/second-application-combo'
  225. const secondUrl = comboUrl([secondId], 'app-2')
  226. graph.entries.push({ id: secondId, url: comboUrl([secondId], 'row-2'), rev: 'row-2' })
  227. graph.batches.push({ phase: 'application', url: secondUrl, rev: 'app-2', entries: [secondId] })
  228. expect(bootInjections(graph).flatMap(row => row.kind === 'script-preload' ? [row.src] : []))
  229. .toEqual([APPLICATION_URL, secondUrl])
  230. })
  231. it('rejects a page that did not preload the modules bundle', () => {
  232. const graph = bootGraph()
  233. const { target } = injectedFacade(graph)
  234. expect(() => target.create({ boot: graph, staticModules: {} }))
  235. .toThrow(`HTML did not preload ${MODULES_ID}/client.js`)
  236. })
  237. it('rejects a bootstrap bundle with a runtime external', () => {
  238. const graph = bootGraph()
  239. const { target } = injectedFacade(graph)
  240. target.load({
  241. id: MODULES_ID,
  242. factory: (require) => {
  243. require('react')
  244. return modulesClient
  245. },
  246. })
  247. expect(() => target.create({ boot: graph, staticModules: {} }))
  248. .toThrow(`${MODULES_ID}/client.js requested external "react"`)
  249. })
  250. it.each([
  251. null,
  252. { ...modulesClient, createClientModuleSystem: undefined },
  253. { ...modulesClient, apply: undefined },
  254. ])('rejects a bootstrap bundle without the complete module face', (exports) => {
  255. const graph = bootGraph()
  256. const { target } = injectedFacade(graph)
  257. target.load({ id: MODULES_ID, factory: () => exports as unknown as Record<string, unknown> })
  258. expect(() => target.create({ boot: graph, staticModules: {} }))
  259. .toThrow(`${MODULES_ID}/client.js did not export the bootstrap module face`)
  260. })
  261. })
  262. describe('client bundle activation', () => {
  263. it.each(['v1', 'v2'] as const)(
  264. 'resolves %s package metadata from the owning entry tree',
  265. (version) => {
  266. const packageName = `@fixture/entry-base-${version}`
  267. const clientPath = writePackage(packageName)
  268. const hostPath = join(dirname(clientPath), 'index.js')
  269. mkdirSync(dirname(hostPath), { recursive: true })
  270. writeFileSync(hostPath, 'export default {}\n')
  271. writeFileSync(clientPath, 'module.exports = {}\n')
  272. const contextBaseUrl = pathToFileURL(join(root!, 'profile')).href + '/'
  273. const entryBaseUrl = pathToFileURL(join(root!, 'overlay')).href + '/'
  274. const calls: unknown[][] = []
  275. const resolveSync = (...args: unknown[]) => {
  276. calls.push(args)
  277. return { format: 'module' as const, url: pathToFileURL(hostPath).href }
  278. }
  279. const internal = { version, resolveSync }
  280. const { service } = constructWithRoute([packageName], {
  281. contextBaseUrl,
  282. entryBaseUrl,
  283. internal: internal as NonNullable<Context['loader']['internal']>,
  284. })
  285. expect(calls).toEqual(version === 'v2'
  286. ? [[entryBaseUrl, { specifier: packageName, attributes: {} }]]
  287. : [[packageName, entryBaseUrl, {}]])
  288. expect(service.clientPath(packageName)).toBe(clientPath)
  289. expect(service.graph().entries.map(entry => entry.id)).toEqual([packageName])
  290. },
  291. )
  292. it('derives the browser module id from a file entry owning manifest', () => {
  293. const packageName = '@fixture/file-entry'
  294. const clientPath = writePackage(packageName)
  295. const hostPath = join(dirname(clientPath), 'index.js')
  296. mkdirSync(dirname(hostPath), { recursive: true })
  297. writeFileSync(hostPath, 'export default {}\n')
  298. writeFileSync(clientPath, 'module.exports = {}\n')
  299. const service = construct([pathToFileURL(hostPath).href])
  300. expect(service.clientPath(packageName)).toBe(clientPath)
  301. expect(service.graph().entries.map(entry => entry.id)).toEqual([packageName])
  302. })
  303. it.each(['relative', 'absolute'] as const)(
  304. 'finds the owning manifest through the %s-path fallback without Node loader internals',
  305. (kind) => {
  306. const packageName = `@fixture/${kind}-fallback-entry`
  307. const clientPath = writePackage(packageName)
  308. const packageRoot = dirname(dirname(clientPath))
  309. const hostPath = join(packageRoot, 'index.js')
  310. mkdirSync(dirname(clientPath), { recursive: true })
  311. writeFileSync(hostPath, 'export default {}\n')
  312. writeFileSync(clientPath, 'module.exports = {}\n')
  313. const loaderName = kind === 'relative' ? './index.js' : hostPath
  314. const { service } = constructWithRoute([loaderName], {
  315. entryBaseUrl: pathToFileURL(packageRoot).href + '/',
  316. })
  317. expect(service.clientPath(packageName)).toBe(clientPath)
  318. expect(service.graph().entries.map(entry => entry.id)).toEqual([packageName])
  319. },
  320. )
  321. it.each(['v1', 'v2', 'worker'] as const)(
  322. 'derives a file entry package id through the %s Loader resolver',
  323. (version) => {
  324. const packageName = `@fixture/file-entry-${version}`
  325. const clientPath = writePackage(packageName)
  326. const hostPath = join(dirname(clientPath), 'index.js')
  327. mkdirSync(dirname(hostPath), { recursive: true })
  328. writeFileSync(hostPath, 'export default {}\n')
  329. writeFileSync(clientPath, 'module.exports = {}\n')
  330. const loaderName = pathToFileURL(hostPath).href
  331. const entryBaseUrl = pathToFileURL(join(root!, 'overlay')).href + '/'
  332. const calls: unknown[][] = []
  333. const resolveSync = (...args: unknown[]) => {
  334. calls.push(args)
  335. return { format: 'module' as const, url: loaderName }
  336. }
  337. const internal = { version, resolveSync }
  338. const { service } = constructWithRoute([loaderName], {
  339. entryBaseUrl,
  340. internal: internal as NonNullable<Context['loader']['internal']>,
  341. })
  342. expect(calls).toEqual(version === 'v2'
  343. ? [[entryBaseUrl, { specifier: loaderName, attributes: {} }]]
  344. : [[loaderName, entryBaseUrl, {}]])
  345. expect(service.graph().entries.map(entry => entry.id)).toEqual([packageName])
  346. },
  347. )
  348. it('rejects distinct active Loader sources for one browser package', () => {
  349. const packageName = '@fixture/duplicate-source'
  350. const clientPath = writePackage(packageName)
  351. const hostPath = join(dirname(clientPath), 'index.js')
  352. mkdirSync(dirname(hostPath), { recursive: true })
  353. writeFileSync(hostPath, 'export default {}\n')
  354. writeFileSync(clientPath, 'module.exports = {}\n')
  355. const alias = './duplicate-source.js'
  356. const internal = {
  357. version: 'v2' as const,
  358. resolveSync: () => ({ format: 'module' as const, url: pathToFileURL(hostPath).href }),
  359. }
  360. expect(() => constructWithRoute([packageName, alias], {
  361. internal: internal as unknown as NonNullable<Context['loader']['internal']>,
  362. })).toThrow(
  363. `client-modules: package ${packageName} resolves from multiple active Loader sources:`,
  364. )
  365. })
  366. it('promotes the remaining Loader source after the selected alias unloads', async () => {
  367. const packageName = '@fixture/duplicate-source-recovery'
  368. const clientPath = writePackage(packageName)
  369. const hostPath = join(dirname(clientPath), 'index.js')
  370. mkdirSync(dirname(hostPath), { recursive: true })
  371. writeFileSync(hostPath, 'export default {}\n')
  372. writeFileSync(clientPath, 'module.exports = {}\n')
  373. const alias = './duplicate-source-recovery.js'
  374. const entries = [packageName]
  375. const internal = {
  376. version: 'v2' as const,
  377. resolveSync: () => ({ format: 'module' as const, url: pathToFileURL(hostPath).href }),
  378. }
  379. const { context, service } = constructWithRoute(entries, {
  380. internal: internal as unknown as NonNullable<Context['loader']['internal']>,
  381. })
  382. const firstRevision = service.graph().entries[0]!.rev
  383. const warning = vi.spyOn(context.logger, 'warn').mockImplementation(() => undefined)
  384. entries.push(alias)
  385. emitLoaderEntryChange(context, alias)
  386. await Promise.resolve()
  387. expect(warning).toHaveBeenCalledWith(expect.objectContaining({
  388. message: expect.stringContaining(`package ${packageName} resolves from multiple active Loader sources`) as string,
  389. }))
  390. expect(service.graph().entries[0]!.rev).toBe(firstRevision)
  391. entries.splice(entries.indexOf(packageName), 1)
  392. emitLoaderEntryChange(context, packageName)
  393. await Promise.resolve()
  394. expect(service.graph().entries.map(entry => entry.id)).toEqual([packageName])
  395. expect(service.graph().entries[0]!.rev).not.toBe(firstRevision)
  396. expect(service.clientPath(packageName)).toBe(clientPath)
  397. })
  398. it('uses owning-tree package resolution for an import-only Worker module loader', () => {
  399. const packageName = '@fixture/worker-loader'
  400. writeBuiltPackage(packageName, {})
  401. const internal = {
  402. version: 'worker',
  403. import: async () => ({}),
  404. } as unknown as NonNullable<Context['loader']['internal']>
  405. const { service } = constructWithRoute([packageName], { internal })
  406. expect(service.graph().entries.map(entry => entry.id)).toEqual([packageName])
  407. })
  408. it('allows sibling dsh roles', () => {
  409. const currentName = '@fixture/current-client-field'
  410. const clientPath = writePackage(currentName, {
  411. dsh: {
  412. bundle: { patch: './cordis.patch.yml' },
  413. client: { platform: 'web' },
  414. profile: { bundles: [] },
  415. },
  416. })
  417. mkdirSync(dirname(clientPath), { recursive: true })
  418. writeFileSync(clientPath, 'module.exports = {}\n')
  419. expect(construct([currentName]).graph().entries.map(entry => entry.id)).toEqual([currentName])
  420. })
  421. it('groups missing bundles under one source-build instruction with a package/path list', () => {
  422. const firstName = '@fixture/missing-first'
  423. const secondName = '@fixture/missing-second'
  424. const firstPath = writePackage(firstName)
  425. const secondPath = writePackage(secondName)
  426. expect(() => construct([firstName, secondName])).toThrow([
  427. 'client-modules: 2 client packages failed to compose:',
  428. ' client bundles not found; run `pnpm run build` before launch:',
  429. ` - package: ${firstName}`,
  430. ` path: ${firstPath}`,
  431. ` - package: ${secondName}`,
  432. ` path: ${secondPath}`,
  433. ].join('\n'))
  434. })
  435. it('does not report other bundle read failures as missing builds', () => {
  436. const packageName = '@fixture/unreadable-client'
  437. const clientPath = writePackage(packageName)
  438. mkdirSync(clientPath, { recursive: true })
  439. let thrown: unknown
  440. try {
  441. construct([packageName])
  442. } catch (error) {
  443. thrown = error
  444. }
  445. expect(String(thrown)).toContain('client-modules: 1 client package failed to compose:')
  446. expect(String(thrown)).toContain(' other failures:')
  447. expect(String(thrown)).toContain('EISDIR')
  448. expect(String(thrown)).not.toContain('pnpm run build')
  449. })
  450. it('falls back to a generated-file map when an authored map is malformed', async () => {
  451. const packageName = '@fixture/malformed-source-map'
  452. const clientPath = writePackage(packageName)
  453. mkdirSync(dirname(clientPath), { recursive: true })
  454. writeFileSync(clientPath, 'module.exports = {}\n')
  455. writeFileSync(`${clientPath}.map`, '{')
  456. const torn = constructWithRoute([packageName])
  457. const tornRow = torn.service.graph().entries[0]!
  458. expect((await routeRequest(torn.route, tornRow.url)).body.toString('utf8'))
  459. .toContain(`sourceMappingURL=${mapUrl(tornRow.url)}`)
  460. const fallback = await routeRequest(torn.route, mapUrl(torn.service.graph().batches[0]!.url))
  461. expect(JSON.parse(fallback.body.toString('utf8'))).toMatchObject({
  462. sections: [{ map: { sources: [`/plugins/${packageName}/client.js`] } }],
  463. })
  464. writeFileSync(`${clientPath}.map`, '{"version":3,"sources":[null]}\n')
  465. expect(() => construct([packageName])).not.toThrow()
  466. writeFileSync(`${clientPath}.map`, JSON.stringify({
  467. version: 3,
  468. names: [],
  469. mappings: 'AAAA',
  470. sourceRoot: 'http://[',
  471. sources: ['src/index.ts'],
  472. }))
  473. const invalidUrl = constructWithRoute([packageName])
  474. const invalidMapUrl = mapUrl(invalidUrl.service.graph().batches[0]!.url)
  475. expect(JSON.parse((await routeRequest(invalidUrl.route, invalidMapUrl)).body.toString('utf8'))).toMatchObject({
  476. sections: [{ map: { sources: [`/plugins/${packageName}/client.js`] } }],
  477. })
  478. })
  479. it('reads a source map only on its first map GET', async () => {
  480. const packageName = '@fixture/lazy-source-map'
  481. const clientPath = writePackage(packageName)
  482. mkdirSync(dirname(clientPath), { recursive: true })
  483. writeFileSync(clientPath, 'module.exports = {}\n//# sourceMappingURL=client.js.map')
  484. writeFileSync(`${clientPath}.map`, '{')
  485. const { service, route } = constructWithRoute([packageName])
  486. const batch = service.graph().batches[0]!
  487. const sourceMapUrl = mapUrl(batch.url)
  488. const script = await routeRequest(route, batch.url)
  489. expect(script.status).toBe(200)
  490. expect((await routeRequest(route, sourceMapUrl, 'HEAD')).body).toHaveLength(0)
  491. writeFileSync(`${clientPath}.map`, JSON.stringify({
  492. version: 3,
  493. names: [],
  494. mappings: 'AAAA',
  495. sources: ['src/first.ts'],
  496. }))
  497. const first = await routeRequest(route, sourceMapUrl)
  498. expect(JSON.parse(first.body.toString('utf8'))).toMatchObject({
  499. sections: [{ map: { sources: [`/plugins/${packageName}/src/first.ts`] } }],
  500. })
  501. writeFileSync(`${clientPath}.map`, JSON.stringify({
  502. version: 3,
  503. names: [],
  504. mappings: 'AAAA',
  505. sources: ['src/second.ts'],
  506. }))
  507. expect((await routeRequest(route, sourceMapUrl)).body).toEqual(first.body)
  508. expect((await routeRequest(route, batch.url)).body).toEqual(script.body)
  509. })
  510. it('retains a materialized resource when an unrelated row recomposes the graph', async () => {
  511. const stablePackage = '@fixture/stable-source-map'
  512. const rebuiltPackage = '@fixture/rebuilt-neighbor'
  513. const stablePath = writePackage(stablePackage)
  514. const rebuiltPath = writePackage(rebuiltPackage)
  515. for (const clientPath of [stablePath, rebuiltPath]) {
  516. mkdirSync(dirname(clientPath), { recursive: true })
  517. writeFileSync(clientPath, 'module.exports = {}\n//# sourceMappingURL=client.js.map')
  518. writeFileSync(`${clientPath}.map`, JSON.stringify({
  519. version: 3,
  520. names: [],
  521. mappings: 'AAAA',
  522. sources: ['src/first.ts'],
  523. }))
  524. }
  525. const { service, route } = constructWithRoute([stablePackage, rebuiltPackage])
  526. const stableUrl = service.graph().entries.find(entry => entry.id === stablePackage)!.url
  527. const stableMapUrl = mapUrl(stableUrl)
  528. const first = await routeRequest(route, stableMapUrl)
  529. writeFileSync(`${stablePath}.map`, JSON.stringify({
  530. version: 3,
  531. names: [],
  532. mappings: 'AAAA',
  533. sources: ['src/second.ts'],
  534. }))
  535. writeFileSync(rebuiltPath, 'module.exports = { rebuilt: true }\n')
  536. service.rebuilt(rebuiltPackage)
  537. expect((await routeRequest(route, stableMapUrl)).body).toEqual(first.body)
  538. })
  539. it('maps packed combo sections back to each generated client bundle', async () => {
  540. const names = ['@fixture/generated-first', '@fixture/generated-second']
  541. for (const [index, packageName] of names.entries()) {
  542. const clientPath = writePackage(packageName)
  543. mkdirSync(dirname(clientPath), { recursive: true })
  544. writeFileSync(
  545. clientPath,
  546. `window.generation = ${String(index)}\n//# sourceURL=packages/client/generated-${String(index)}/lib/client.js`,
  547. )
  548. }
  549. const { service, route } = constructWithRoute(names)
  550. const batch = service.graph().batches[0]!
  551. const script = (await routeRequest(route, batch.url)).body.toString('utf8')
  552. expect(script).not.toContain('//# sourceURL=')
  553. expect(script).toContain(`//# sourceMappingURL=${mapUrl(batch.url)}`)
  554. const payload = JSON.parse((await routeRequest(route, mapUrl(batch.url))).body.toString('utf8')) as {
  555. sections: { map: { mappings: string; sources: string[]; sourcesContent: string[] } }[]
  556. }
  557. expect(payload.sections.map(section => section.map)).toEqual([
  558. {
  559. version: 3,
  560. names: [],
  561. mappings: 'AAAA',
  562. sources: ['/packages/client/generated-0/lib/client.js'],
  563. sourcesContent: ['window.generation = 0\n'],
  564. },
  565. {
  566. version: 3,
  567. names: [],
  568. mappings: 'AAAA',
  569. sources: ['/packages/client/generated-1/lib/client.js'],
  570. sourcesContent: ['window.generation = 1\n'],
  571. },
  572. ])
  573. const consumer = new SourceMap(payload as unknown as ConstructorParameters<typeof SourceMap>[0])
  574. expect(consumer.findEntry(0, 0)).toMatchObject({
  575. originalSource: '/packages/client/generated-0/lib/client.js',
  576. })
  577. expect(consumer.findEntry(2, 0)).toMatchObject({
  578. originalSource: '/packages/client/generated-1/lib/client.js',
  579. })
  580. })
  581. it('retains one prior immutable batch generation across rebuild recomposition', async () => {
  582. const packageName = '@fixture/batch-rebuild-race'
  583. const clientPath = writePackage(packageName)
  584. mkdirSync(dirname(clientPath), { recursive: true })
  585. writeFileSync(clientPath, 'module.exports = { generation: 1 }\n')
  586. const { service, route } = constructWithRoute([packageName])
  587. const first = service.graph().batches[0]!.url
  588. const firstSize = service.artifactBaseline(packageName)!.size
  589. writeFileSync(clientPath, 'module.exports = { generation: 200 }\n')
  590. service.rebuilt(packageName)
  591. const second = service.graph().batches[0]!.url
  592. expect(second).not.toBe(first)
  593. expect(service.artifactBaseline(packageName)!.size).toBeGreaterThan(firstSize)
  594. expect((await routeRequest(route, first)).status).toBe(200)
  595. expect((await routeRequest(route, second)).status).toBe(200)
  596. writeFileSync(clientPath, 'module.exports = { generation: 3 }\n')
  597. service.rebuilt(packageName)
  598. const third = service.graph().batches[0]!.url
  599. expect((await routeRequest(route, first)).status).toBe(404)
  600. expect((await routeRequest(route, second)).status).toBe(200)
  601. expect((await routeRequest(route, third)).status).toBe(200)
  602. })
  603. it('assigns opaque startup revisions instead of deriving them from artifact content', () => {
  604. const firstName = '@fixture/startup-revision-first'
  605. const secondName = '@fixture/startup-revision-second'
  606. writeBuiltPackage(firstName, {})
  607. writeBuiltPackage(secondName, {})
  608. const service = construct([firstName, secondName])
  609. const [first, second] = service.graph().entries
  610. const firstMatch = /^(?<nonce>[a-f\d]{16})-(?<sequence>\d+)$/.exec(first!.rev)
  611. const secondMatch = /^(?<nonce>[a-f\d]{16})-(?<sequence>\d+)$/.exec(second!.rev)
  612. expect(firstMatch?.groups).toMatchObject({ sequence: '0' })
  613. expect(secondMatch?.groups).toMatchObject({ nonce: firstMatch?.groups?.nonce, sequence: '1' })
  614. const firstPath = service.clientPath(firstName)!
  615. const firstStat = statSync(firstPath)
  616. expect(service.artifactBaseline(firstName)).toEqual({
  617. path: firstPath,
  618. mtimeMs: firstStat.mtimeMs,
  619. size: firstStat.size,
  620. })
  621. expect(service.artifactBaseline('@fixture/unknown')).toBeUndefined()
  622. })
  623. it('splits startup combos before the map-form URL exceeds 3 KiB', async () => {
  624. const packageNames = Array.from({ length: 48 }, (_, index) => (
  625. `@fixture/combo-url-${String(index).padStart(3, '0')}-${'x'.repeat(40)}`
  626. ))
  627. const sourceMap = JSON.stringify({
  628. version: 3,
  629. names: [],
  630. mappings: 'AAAA',
  631. sources: ['src/index.ts'],
  632. })
  633. for (const packageName of packageNames) {
  634. const clientPath = writePackage(packageName)
  635. mkdirSync(dirname(clientPath), { recursive: true })
  636. writeFileSync(clientPath, 'module.exports = {}\n')
  637. writeFileSync(`${clientPath}.map`, sourceMap)
  638. }
  639. const { service, route } = constructWithRoute(packageNames)
  640. const batches = service.graph().batches.filter(batch => batch.phase === 'application')
  641. expect(batches.length).toBeGreaterThan(1)
  642. expect(batches.flatMap(batch => batch.entries)).toEqual(packageNames)
  643. for (const batch of batches) {
  644. expect(Buffer.byteLength(batch.url)).toBeLessThanOrEqual(3 * 1024)
  645. expect(Buffer.byteLength(mapUrl(batch.url))).toBeLessThanOrEqual(3 * 1024)
  646. expect((await routeRequest(route, batch.url)).status).toBe(200)
  647. expect((await routeRequest(route, mapUrl(batch.url))).status).toBe(200)
  648. }
  649. for (let index = 0; index < batches.length - 1; index += 1) {
  650. const entries = [...batches[index]!.entries, batches[index + 1]!.entries[0]!]
  651. expect(Buffer.byteLength(mapUrl(comboUrl(entries, '0'.repeat(12))))).toBeGreaterThan(3 * 1024)
  652. }
  653. })
  654. it('serves the source map beside a registered client bundle', async () => {
  655. const packageName = '@fixture/source-map'
  656. const clientPath = writePackage(packageName)
  657. mkdirSync(dirname(clientPath), { recursive: true })
  658. writeFileSync(clientPath, 'module.exports = {}\n//# sourceMappingURL=client.js.map')
  659. const map = '{"version":3,"names":[],"mappings":"AAAA","sources":["../../../packages/client/demo/src/index.tsx","https://cdn.example.test/library.js"]}\n'
  660. writeFileSync(`${clientPath}.map`, map)
  661. const { service, route } = constructWithRoute([packageName])
  662. const row = service.graph().entries[0]!
  663. const singleScript = await routeRequest(route, row.url)
  664. expect(singleScript.body.toString('utf8')).toContain(`sourceMappingURL=${mapUrl(row.url)}`)
  665. const singleMap = await routeRequest(route, mapUrl(row.url))
  666. expect(singleMap.status).toBe(200)
  667. expect(singleMap.headers).toEqual({
  668. 'content-type': 'application/json; charset=utf-8',
  669. 'cache-control': 'public, max-age=31536000, immutable',
  670. })
  671. expect(JSON.parse(singleMap.body.toString('utf8'))).toMatchObject({
  672. version: 3,
  673. file: 'client.js',
  674. sections: [{
  675. offset: { line: 0, column: 0 },
  676. map: {
  677. ...(JSON.parse(map) as Record<string, unknown>),
  678. sources: ['/packages/client/demo/src/index.tsx', 'https://cdn.example.test/library.js'],
  679. },
  680. }],
  681. })
  682. const batch = service.graph().batches[0]!
  683. expect(batch).toMatchObject({ phase: 'application', entries: [packageName] })
  684. const batchScript = await routeRequest(route, batch.url)
  685. expect(batchScript.status).toBe(200)
  686. expect(batchScript.headers?.['cache-control']).toBe('public, max-age=31536000, immutable')
  687. expect(batchScript.body.toString('utf8')).toContain(`//# sourceMappingURL=${mapUrl(batch.url)}`)
  688. const shellResponse = await service.fetchBundle(new Request(`dsh-app://app${batch.url}`))
  689. expect(shellResponse.status).toBe(200)
  690. expect(shellResponse.headers.get('cache-control')).toBe('public, max-age=31536000, immutable')
  691. expect(await shellResponse.text()).toBe(batchScript.body.toString('utf8'))
  692. expect((await routeRequest(route, batch.url, 'HEAD')).body).toHaveLength(0)
  693. expect((await routeRequest(route, batch.url, 'POST')).status).toBe(405)
  694. const batchMap = await routeRequest(route, mapUrl(batch.url))
  695. const parsedBatchMap = JSON.parse(batchMap.body.toString('utf8')) as unknown
  696. const parsedPluginMap = JSON.parse(map) as Record<string, unknown>
  697. expect(parsedBatchMap).toMatchObject({
  698. version: 3,
  699. file: 'client.js',
  700. sections: [{
  701. offset: { line: 0, column: 0 },
  702. map: {
  703. ...parsedPluginMap,
  704. sources: ['/packages/client/demo/src/index.tsx', 'https://cdn.example.test/library.js'],
  705. },
  706. }],
  707. })
  708. expect((await routeRequest(route, `${row.url}&stale=1`.replace(`rev=${row.rev}`, 'rev=stale'))).status).toBe(404)
  709. writeFileSync(`${clientPath}.map`, '{"version":3,"names":[],"mappings":"AAAA","sources":["src/changed.tsx"]}\n')
  710. const nextRev = service.rebuilt(packageName)
  711. expect(nextRev).not.toBe(row.rev)
  712. const nextRow = service.graph().entries[0]!
  713. expect(nextRow.rev).toBe(nextRev)
  714. const nextMap = await routeRequest(route, mapUrl(nextRow.url))
  715. expect(JSON.parse(nextMap.body.toString('utf8'))).toMatchObject({
  716. sections: [{ map: { sources: ['/plugins/@fixture/source-map/src/changed.tsx'] } }],
  717. })
  718. })
  719. it('snapshots and serves package-local chunks under the entry revision', async () => {
  720. const packageName = '@fixture/chunked'
  721. const clientPath = writePackage(packageName)
  722. const chunkPath = join(dirname(clientPath), 'client.pdf.js')
  723. mkdirSync(dirname(clientPath), { recursive: true })
  724. writeFileSync(clientPath, 'module.exports = require("./client.pdf.js")\n')
  725. writeFileSync(chunkPath, 'module.exports = { version: 1 }\n//# sourceMappingURL=client.pdf.js.map')
  726. writeFileSync(`${chunkPath}.map`, JSON.stringify({
  727. version: 3,
  728. names: [],
  729. mappings: 'AAAA',
  730. sources: ['../../../packages/client/demo/src/pdf.tsx'],
  731. }))
  732. const { service, route } = constructWithRoute([packageName])
  733. const firstRev = service.graph().entries[0]!.rev
  734. const firstUrl = chunkUrl(packageName, 'client.pdf.js', firstRev)
  735. const script = await routeRequest(route, firstUrl)
  736. expect(script.status).toBe(200)
  737. expect(script.body.toString('utf8')).toContain('module.exports = { version: 1 }')
  738. expect(script.body.toString('utf8')).toContain(`sourceMappingURL=${firstUrl.replace('.js?', '.js.map?')}`)
  739. expect((await routeRequest(route, firstUrl.replace('.js?', '.js.map?'))).status).toBe(200)
  740. writeFileSync(chunkPath, 'module.exports = { version: 2 }\n')
  741. const secondRev = service.rebuilt(packageName)!
  742. expect(secondRev).not.toBe(firstRev)
  743. const second = await routeRequest(route, chunkUrl(packageName, 'client.pdf.js', secondRev))
  744. expect(second.body.toString('utf8')).toContain('module.exports = { version: 2 }')
  745. })
  746. it('applies sourceRoot before relocating absolute-looking section sources', async () => {
  747. const packageName = '@fixture/source-root'
  748. const clientPath = writePackage(packageName)
  749. mkdirSync(dirname(clientPath), { recursive: true })
  750. writeFileSync(clientPath, 'module.exports = {}\n')
  751. writeFileSync(`${clientPath}.map`, JSON.stringify({
  752. version: 3,
  753. names: [],
  754. mappings: 'AAAA',
  755. sourceRoot: '../root',
  756. sources: ['/absolute.ts'],
  757. }))
  758. const { service, route } = constructWithRoute([packageName])
  759. const response = await routeRequest(route, mapUrl(service.graph().batches[0]!.url))
  760. const map = JSON.parse(response.body.toString('utf8')) as {
  761. sections: { map: { sourceRoot?: string; sources: string[] } }[]
  762. }
  763. expect(map.sections[0]?.map).toMatchObject({
  764. sources: ['/plugins/@fixture/root/absolute.ts'],
  765. })
  766. expect(map.sections[0]?.map).not.toHaveProperty('sourceRoot')
  767. })
  768. it('maps a non-zero second batch section through a standard source-map consumer', async () => {
  769. const firstName = '@fixture/offset-first'
  770. const secondName = '@fixture/offset-second'
  771. const firstPath = writePackage(firstName)
  772. const secondPath = writePackage(secondName)
  773. for (const [path, source] of [
  774. [firstPath, '../../../packages/demo/first.ts'],
  775. [secondPath, '../../../packages/demo/second.ts'],
  776. ] as const) {
  777. mkdirSync(dirname(path), { recursive: true })
  778. writeFileSync(path, 'window.first = true\nwindow.second = true\n')
  779. writeFileSync(`${path}.map`, JSON.stringify({
  780. version: 3,
  781. names: [],
  782. mappings: 'AAAA',
  783. sources: [source],
  784. sourcesContent: ['export {}\n'],
  785. }))
  786. }
  787. const { service, route } = constructWithRoute([firstName, secondName])
  788. const response = await routeRequest(route, mapUrl(service.graph().batches[0]!.url))
  789. const payload = JSON.parse(response.body.toString('utf8')) as ConstructorParameters<typeof SourceMap>[0]
  790. const sections = (payload as unknown as {
  791. sections: { offset: { line: number; column: number } }[]
  792. }).sections
  793. expect(sections.map(section => section.offset)).toEqual([
  794. { line: 0, column: 0 },
  795. { line: 3, column: 0 },
  796. ])
  797. const consumer = new SourceMap(payload)
  798. expect(consumer.findEntry(0, 0)).toMatchObject({ originalSource: '/packages/demo/first.ts' })
  799. expect(consumer.findEntry(3, 0)).toMatchObject({ originalSource: '/packages/demo/second.ts' })
  800. })
  801. it('combines a generated-file fallback with a later authored map', async () => {
  802. const unmappedName = '@fixture/unmapped-first'
  803. const mappedName = '@fixture/mapped-second'
  804. const unmappedPath = writePackage(unmappedName)
  805. const mappedPath = writePackage(mappedName)
  806. mkdirSync(dirname(unmappedPath), { recursive: true })
  807. mkdirSync(dirname(mappedPath), { recursive: true })
  808. writeFileSync(unmappedPath, 'window.unmapped = true\n')
  809. writeFileSync(mappedPath, 'window.mapped = true\n')
  810. writeFileSync(`${mappedPath}.map`, JSON.stringify({
  811. version: 3,
  812. names: [],
  813. mappings: 'AAAA',
  814. sources: ['../../../packages/demo/mapped.ts'],
  815. sourcesContent: ['export {}\n'],
  816. }))
  817. const { service, route } = constructWithRoute([unmappedName, mappedName])
  818. const response = await routeRequest(route, mapUrl(service.graph().batches[0]!.url))
  819. const payload = JSON.parse(response.body.toString('utf8')) as ConstructorParameters<typeof SourceMap>[0]
  820. const consumer = new SourceMap(payload)
  821. expect(consumer.findEntry(0, 0)).toMatchObject({
  822. originalSource: `/plugins/${unmappedName}/client.js`,
  823. })
  824. expect(consumer.findEntry(2, 0)).toMatchObject({ originalSource: '/packages/demo/mapped.ts' })
  825. })
  826. })
  827. function emitLoaderEntryChange(context: Context, name: string): void {
  828. context.emit('internal/plugin', {
  829. entry: { options: { name } },
  830. } as unknown as Fiber)
  831. }
  832. describe('shared module declarations', () => {
  833. it('accepts external requests and carries them onto the graph row', () => {
  834. const packageName = '@fixture/shared-declared'
  835. writeBuiltPackage(packageName, { external: ['react'] })
  836. expect(construct([packageName]).graph().entries).toEqual([{
  837. id: packageName,
  838. url: expect.stringContaining(`/plugins/??${packageName}/client.js&rev=`) as unknown as string,
  839. rev: expect.any(String) as unknown as string,
  840. external: ['react'],
  841. }])
  842. })
  843. it('omits external when the package declares no requests', () => {
  844. const packageName = '@fixture/shared-absent'
  845. writeBuiltPackage(packageName, {})
  846. const [row] = construct([packageName]).graph().entries
  847. expect(row).not.toHaveProperty('external')
  848. })
  849. it('rejects a non-array external', () => {
  850. const packageName = '@fixture/external-not-array'
  851. writeBuiltPackage(packageName, { external: 'react' })
  852. expect(() => construct([packageName]))
  853. .toThrow(`client-modules: ${packageName} dsh.client.external must be a string array`)
  854. })
  855. })
  856. describe('module graph order', () => {
  857. const entry = (id: string, fields: Partial<WebBootEntry> = {}): WebBootEntry =>
  858. ({ id, url: comboUrl([id], '0'), rev: '0', ...fields })
  859. const ids = (entries: readonly WebBootEntry[]): string[] => entries.map(row => row.id)
  860. it('places every requested package row before its consumers along a chain', () => {
  861. expect(ids(orderByModuleGraph([
  862. entry('ui', { external: ['slots'] }),
  863. entry('slots', { external: ['render'] }),
  864. entry('render'),
  865. ]))).toEqual(['render', 'slots', 'ui'])
  866. })
  867. it('places a shared package row before both arms of a diamond', () => {
  868. expect(ids(orderByModuleGraph([
  869. entry('app', { external: ['left', 'right'] }),
  870. entry('left', { external: ['vendor'] }),
  871. entry('right', { external: ['vendor'] }),
  872. entry('vendor'),
  873. ]))).toEqual(['vendor', 'left', 'right', 'app'])
  874. })
  875. it('resolves a /client request onto the requested package row', () => {
  876. expect(ids(orderByModuleGraph([
  877. entry('ui', { external: ['runtime/client'] }),
  878. entry('runtime'),
  879. ]))).toEqual(['runtime', 'ui'])
  880. })
  881. it('leaves a request no row answers to the static assembly channel', () => {
  882. expect(ids(orderByModuleGraph([
  883. entry('consumer', { external: ['@deepseek-ai/cordis'] }),
  884. entry('other'),
  885. ]))).toEqual(['consumer', 'other'])
  886. })
  887. it('rejects a cycle and names the packages on it', () => {
  888. expect(() => orderByModuleGraph([
  889. entry('a', { external: ['b'] }),
  890. entry('b', { external: ['a'] }),
  891. ])).toThrow('client-modules: module graph cycle a -> b -> a')
  892. })
  893. it('rejects a row requesting its own package name', () => {
  894. expect(() => orderByModuleGraph([entry('solo', { external: ['solo'] })]))
  895. .toThrow('client-modules: "solo" requests module "solo" that it answers itself')
  896. })
  897. it('composes the served graph in module-graph order', () => {
  898. const consumerName = '@fixture/order-consumer'
  899. const dependencyName = '@fixture/order-dependency'
  900. writeBuiltPackage(consumerName, { external: [dependencyName] })
  901. writeBuiltPackage(dependencyName, {})
  902. expect(ids(construct([consumerName, dependencyName]).graph().entries))
  903. .toEqual([dependencyName, consumerName])
  904. })
  905. it('fails activation loud when scanned packages form a module cycle', () => {
  906. writeBuiltPackage('@fixture/cycle-a', { external: ['@fixture/cycle-b'] })
  907. writeBuiltPackage('@fixture/cycle-b', { external: ['@fixture/cycle-a'] })
  908. expect(() => construct(['@fixture/cycle-a', '@fixture/cycle-b']))
  909. .toThrow('module graph cycle @fixture/cycle-a -> @fixture/cycle-b -> @fixture/cycle-a')
  910. })
  911. })