node-half.client.spec.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. /** Node-half composition diagnostics for package metadata and built client bundles. */
  2. import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs'
  3. import type { IncomingMessage, ServerResponse } from 'node:http'
  4. import { tmpdir } from 'node:os'
  5. import { dirname, join } from 'node:path'
  6. import { pathToFileURL } from 'node:url'
  7. import { runInNewContext } from 'node:vm'
  8. import { Context } from '@deepseek-ai/cordis'
  9. import { afterEach, describe, expect, it } from 'vitest'
  10. import { renderIndexInjections, type WebServer, type WebRoute } from '@deepseek-ai/dsh-host-webserver'
  11. import * as modulesClient from '../src/client/index.ts'
  12. import { ClientModuleRegistry, bootInjections, orderByModuleGraph } from '../src/index.ts'
  13. import type { ClientModuleLoaderTarget, WebBootEntry, WebBootGraph } from '../src/client/index.ts'
  14. const MODULES_ID = '@deepseek-ai/dsh-client-modules'
  15. const UI_RENDERER_ID = '@deepseek-ai/dsh-client-ui-renderer'
  16. let root: string | undefined
  17. afterEach(() => {
  18. if (root !== undefined) rmSync(root, { recursive: true, force: true })
  19. root = undefined
  20. })
  21. /** Create a resolvable package whose client export points at the returned path. */
  22. function writePackage(
  23. packageName: string,
  24. metadata: Record<string, unknown> = { dsh: { client: { platform: 'web' } } },
  25. ): string {
  26. root ??= realpathSync(mkdtempSync(join(tmpdir(), 'dsh-client-modules-')))
  27. const pkgRoot = join(root, 'node_modules', ...packageName.split('/'))
  28. const clientPath = join(pkgRoot, 'lib', 'client.js')
  29. mkdirSync(pkgRoot, { recursive: true })
  30. writeFileSync(join(pkgRoot, 'package.json'), JSON.stringify({
  31. name: packageName,
  32. exports: {
  33. './client': './lib/client.js',
  34. './package.json': './package.json',
  35. },
  36. ...metadata,
  37. }))
  38. return clientPath
  39. }
  40. /** Create a built package with the supplied client declaration. */
  41. function writeBuiltPackage(packageName: string, client: Record<string, unknown>): void {
  42. const clientPath = writePackage(packageName, { dsh: { client: { platform: 'web', ...client } } })
  43. mkdirSync(dirname(clientPath), { recursive: true })
  44. writeFileSync(clientPath, 'module.exports = {}\n')
  45. }
  46. /** Construct the node-half service and capture its plugin-bundle route. */
  47. function constructWithRoute(packageNames: string[]): { service: ClientModuleRegistry; route: WebRoute } {
  48. const ctx = new Context()
  49. ctx.baseUrl = pathToFileURL(root!).href + '/'
  50. ctx.provide('loader', {
  51. *entries() {
  52. for (const packageName of packageNames) {
  53. yield { options: { name: packageName }, fiber: {}, disabled: false }
  54. }
  55. },
  56. })
  57. let route: WebRoute | undefined
  58. const webServer: Pick<WebServer, 'port' | 'register' | 'tapIndex'> = {
  59. port: 0,
  60. register: (candidate) => {
  61. if (candidate.path === '/plugins') route = candidate
  62. return () => {}
  63. },
  64. tapIndex: () => () => {},
  65. }
  66. ctx.provide('webServer', webServer as WebServer)
  67. const service = new ClientModuleRegistry(ctx)
  68. if (route === undefined) throw new Error('client bundle route was not registered')
  69. return { service, route }
  70. }
  71. /** Construct the node-half service over the enabled fixture entries. */
  72. function construct(packageNames: string[]): ClientModuleRegistry {
  73. return constructWithRoute(packageNames).service
  74. }
  75. /** Execute the exact first inline script emitted by the Host boot rows. */
  76. function injectedFacade(graph: WebBootGraph): { html: string; target: ClientModuleLoaderTarget } {
  77. const html = renderIndexInjections(
  78. '<html><head></head><body><script type="module" src="/index.js"></script></body></html>',
  79. bootInjections(graph),
  80. )
  81. const source = /<head><script>([\s\S]*?)<\/script>/.exec(html)?.[1]
  82. if (source === undefined) throw new Error('missing injected ModuleLoader facade script')
  83. const window: { __ModuleLoader__?: ClientModuleLoaderTarget } = {}
  84. runInNewContext(source, { window })
  85. if (window.__ModuleLoader__ === undefined) throw new Error('facade script did not install __ModuleLoader__')
  86. return { html, target: window.__ModuleLoader__ }
  87. }
  88. const bootGraph = (): WebBootGraph => ({
  89. rev: 'graph',
  90. entries: [
  91. { id: MODULES_ID, url: '/plugins/modules.js?rev=m', rev: 'm' },
  92. { id: UI_RENDERER_ID, url: '/plugins/ui-renderer.js?rev=r', rev: 'r' },
  93. ],
  94. })
  95. describe('HTML bootstrap facade', () => {
  96. it('precedes blocking preloads and the boot graph, then becomes the live registration target', async () => {
  97. const graph = bootGraph()
  98. const { html, target } = injectedFacade(graph)
  99. const facadeAt = html.indexOf('window.__ModuleLoader__=')
  100. const modulesAt = html.indexOf('<script src="/plugins/modules.js?rev=m"></script>')
  101. const graphAt = html.indexOf('globalThis["__DSH_BOOT__"] = ')
  102. const entryAt = html.indexOf('<script type="module" src="/index.js"></script>')
  103. expect(html).not.toContain('<script src="/plugins/ui-renderer.js?rev=r"></script>')
  104. expect([facadeAt, modulesAt, graphAt, entryAt]).toEqual([...new Set([
  105. facadeAt, modulesAt, graphAt, entryAt,
  106. ])].sort((a, b) => a - b))
  107. target.load({ id: MODULES_ID, factory: () => modulesClient })
  108. target.load({ id: UI_RENDERER_ID, factory: () => ({ marker: 'ui-renderer' }) })
  109. const system = target.create({ boot: graph, staticModules: {} })
  110. expect(target.mode).toBe('live')
  111. expect(target.pendingQueue).toEqual([])
  112. expect(system.manifest.rev).toBe('graph')
  113. expect(await system.import(MODULES_ID)).toBe(modulesClient)
  114. expect(await system.import(`${UI_RENDERER_ID}/client`)).toEqual({ marker: 'ui-renderer' })
  115. expect(() => target.create({ boot: graph, staticModules: {} }))
  116. .toThrow('create called after module-system boot')
  117. })
  118. it('rejects a page that did not preload the modules bundle', () => {
  119. const graph = bootGraph()
  120. const { target } = injectedFacade(graph)
  121. expect(() => target.create({ boot: graph, staticModules: {} }))
  122. .toThrow(`HTML did not preload ${MODULES_ID}/client.js`)
  123. })
  124. it('rejects a bootstrap bundle with a runtime external', () => {
  125. const graph = bootGraph()
  126. const { target } = injectedFacade(graph)
  127. target.load({
  128. id: MODULES_ID,
  129. factory: (require) => {
  130. require('react')
  131. return modulesClient
  132. },
  133. })
  134. expect(() => target.create({ boot: graph, staticModules: {} }))
  135. .toThrow(`${MODULES_ID}/client.js requested external "react"`)
  136. })
  137. it.each([
  138. null,
  139. { ...modulesClient, createClientModuleSystem: undefined },
  140. { ...modulesClient, apply: undefined },
  141. ])('rejects a bootstrap bundle without the complete module face', (exports) => {
  142. const graph = bootGraph()
  143. const { target } = injectedFacade(graph)
  144. target.load({ id: MODULES_ID, factory: () => exports as unknown as Record<string, unknown> })
  145. expect(() => target.create({ boot: graph, staticModules: {} }))
  146. .toThrow(`${MODULES_ID}/client.js did not export the bootstrap module face`)
  147. })
  148. })
  149. describe('client bundle activation', () => {
  150. it('allows sibling dsh roles', () => {
  151. const currentName = '@fixture/current-client-field'
  152. const clientPath = writePackage(currentName, {
  153. dsh: {
  154. bundle: { patch: './cordis.patch.yml' },
  155. client: { platform: 'web' },
  156. profile: { bundles: [] },
  157. },
  158. })
  159. mkdirSync(dirname(clientPath), { recursive: true })
  160. writeFileSync(clientPath, 'module.exports = {}\n')
  161. expect(construct([currentName]).graph().entries.map(entry => entry.id)).toEqual([currentName])
  162. })
  163. it('groups missing bundles under one source-build instruction with a package/path list', () => {
  164. const firstName = '@fixture/missing-first'
  165. const secondName = '@fixture/missing-second'
  166. const firstPath = writePackage(firstName)
  167. const secondPath = writePackage(secondName)
  168. expect(() => construct([firstName, secondName])).toThrow([
  169. 'client-modules: 2 client packages failed to compose:',
  170. ' client bundles not found; run `pnpm run build` before launch:',
  171. ` - package: ${firstName}`,
  172. ` path: ${firstPath}`,
  173. ` - package: ${secondName}`,
  174. ` path: ${secondPath}`,
  175. ].join('\n'))
  176. })
  177. it('does not report other bundle read failures as missing builds', () => {
  178. const packageName = '@fixture/unreadable-client'
  179. const clientPath = writePackage(packageName)
  180. mkdirSync(clientPath, { recursive: true })
  181. let thrown: unknown
  182. try {
  183. construct([packageName])
  184. } catch (error) {
  185. thrown = error
  186. }
  187. expect(String(thrown)).toContain('client-modules: 1 client package failed to compose:')
  188. expect(String(thrown)).toContain(' other failures:')
  189. expect(String(thrown)).toContain('EISDIR')
  190. expect(String(thrown)).not.toContain('pnpm run build')
  191. })
  192. it('serves the source map beside a registered client bundle', async () => {
  193. const packageName = '@fixture/source-map'
  194. const clientPath = writePackage(packageName)
  195. mkdirSync(dirname(clientPath), { recursive: true })
  196. writeFileSync(clientPath, 'module.exports = {}\n')
  197. const map = '{"version":3,"sources":["src/client/index.tsx"]}\n'
  198. writeFileSync(`${clientPath}.map`, map)
  199. const { route } = constructWithRoute([packageName])
  200. let status = 0
  201. let headers: Record<string, string> | undefined
  202. let body = ''
  203. const response = {
  204. writeHead(nextStatus: number, nextHeaders?: Record<string, string>) {
  205. status = nextStatus
  206. headers = nextHeaders
  207. return response
  208. },
  209. end(chunk?: Uint8Array) {
  210. body = chunk === undefined ? '' : Buffer.from(chunk).toString('utf8')
  211. return response
  212. },
  213. } as unknown as ServerResponse
  214. await route.handler({
  215. method: 'GET',
  216. url: `/plugins/${packageName}/client.js.map`,
  217. } as IncomingMessage, response)
  218. expect(status).toBe(200)
  219. expect(headers).toEqual({
  220. 'content-type': 'application/json; charset=utf-8',
  221. 'cache-control': 'no-cache',
  222. })
  223. expect(body).toBe(map)
  224. })
  225. })
  226. describe('shared module declarations', () => {
  227. it('accepts external requests and carries them onto the graph row', () => {
  228. const packageName = '@fixture/shared-declared'
  229. writeBuiltPackage(packageName, { external: ['react'] })
  230. expect(construct([packageName]).graph().entries).toEqual([{
  231. id: packageName,
  232. url: expect.stringContaining(`/plugins/${packageName}/client.js?rev=`) as unknown as string,
  233. rev: expect.any(String) as unknown as string,
  234. external: ['react'],
  235. }])
  236. })
  237. it('omits external when the package declares no requests', () => {
  238. const packageName = '@fixture/shared-absent'
  239. writeBuiltPackage(packageName, {})
  240. const [row] = construct([packageName]).graph().entries
  241. expect(row).not.toHaveProperty('external')
  242. })
  243. it('rejects a non-array external', () => {
  244. const packageName = '@fixture/external-not-array'
  245. writeBuiltPackage(packageName, { external: 'react' })
  246. expect(() => construct([packageName]))
  247. .toThrow(`client-modules: ${packageName} dsh.client.external must be a string array`)
  248. })
  249. })
  250. describe('module graph order', () => {
  251. const entry = (id: string, fields: Partial<WebBootEntry> = {}): WebBootEntry =>
  252. ({ id, url: `/plugins/${id}/client.js?rev=0`, rev: '0', ...fields })
  253. const ids = (entries: readonly WebBootEntry[]): string[] => entries.map(row => row.id)
  254. it('places every requested package row before its consumers along a chain', () => {
  255. expect(ids(orderByModuleGraph([
  256. entry('ui', { external: ['slots'] }),
  257. entry('slots', { external: ['render'] }),
  258. entry('render'),
  259. ]))).toEqual(['render', 'slots', 'ui'])
  260. })
  261. it('places a shared package row before both arms of a diamond', () => {
  262. expect(ids(orderByModuleGraph([
  263. entry('app', { external: ['left', 'right'] }),
  264. entry('left', { external: ['vendor'] }),
  265. entry('right', { external: ['vendor'] }),
  266. entry('vendor'),
  267. ]))).toEqual(['vendor', 'left', 'right', 'app'])
  268. })
  269. it('resolves a /client request onto the requested package row', () => {
  270. expect(ids(orderByModuleGraph([
  271. entry('ui', { external: ['runtime/client'] }),
  272. entry('runtime'),
  273. ]))).toEqual(['runtime', 'ui'])
  274. })
  275. it('leaves a request no row answers to the static assembly channel', () => {
  276. expect(ids(orderByModuleGraph([
  277. entry('consumer', { external: ['@deepseek-ai/cordis'] }),
  278. entry('other'),
  279. ]))).toEqual(['consumer', 'other'])
  280. })
  281. it('rejects a cycle and names the packages on it', () => {
  282. expect(() => orderByModuleGraph([
  283. entry('a', { external: ['b'] }),
  284. entry('b', { external: ['a'] }),
  285. ])).toThrow('client-modules: module graph cycle a -> b -> a')
  286. })
  287. it('rejects a row requesting its own package name', () => {
  288. expect(() => orderByModuleGraph([entry('solo', { external: ['solo'] })]))
  289. .toThrow('client-modules: "solo" requests module "solo" that it answers itself')
  290. })
  291. it('composes the served graph in module-graph order', () => {
  292. const consumerName = '@fixture/order-consumer'
  293. const dependencyName = '@fixture/order-dependency'
  294. writeBuiltPackage(consumerName, { external: [dependencyName] })
  295. writeBuiltPackage(dependencyName, {})
  296. expect(ids(construct([consumerName, dependencyName]).graph().entries))
  297. .toEqual([dependencyName, consumerName])
  298. })
  299. it('fails activation loud when scanned packages form a module cycle', () => {
  300. writeBuiltPackage('@fixture/cycle-a', { external: ['@fixture/cycle-b'] })
  301. writeBuiltPackage('@fixture/cycle-b', { external: ['@fixture/cycle-a'] })
  302. expect(() => construct(['@fixture/cycle-a', '@fixture/cycle-b']))
  303. .toThrow('module graph cycle @fixture/cycle-a -> @fixture/cycle-b -> @fixture/cycle-a')
  304. })
  305. })