frontend-static.spec.ts 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127
  1. /**
  2. * REAL-composition coverage: a test-only cordis.yml booted through the
  3. * vendored Loader mounts the webserver and frontend-static rows, and every
  4. * assertion observes the served HTTP surface — asset serving, MIME fallback,
  5. * SPA index fallback with index taps, traversal rejection, 405 on non-GET/
  6. * HEAD, and seat release on fiber disposal (HMR safety).
  7. */
  8. import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'
  9. import { tmpdir } from 'node:os'
  10. import { join } from 'node:path'
  11. import { pathToFileURL } from 'node:url'
  12. import { afterEach, describe, expect, it } from 'vitest'
  13. import { Context } from 'cordis'
  14. import Loader from '@cordisjs/plugin-loader'
  15. import Include from '@cordisjs/plugin-include'
  16. import HttpServer from '@deepseek-ai/dsh-host-webserver'
  17. import * as FrontendStatic from '../src/index.ts'
  18. let root: string | undefined
  19. let context: Context | undefined
  20. afterEach(async () => {
  21. await context?.fiber.dispose()
  22. context = undefined
  23. if (root !== undefined) await rm(root, { recursive: true, force: true })
  24. root = undefined
  25. })
  26. /** Write a dist fixture and a two-row cordis.yml, then boot it through the real Loader. */
  27. async function loadComposition(): Promise<Context> {
  28. root = await mkdtemp(join(tmpdir(), 'dsh-frontend-static-'))
  29. const dist = join(root, 'dist')
  30. await mkdir(dist)
  31. const distIndex = join(dist, 'index.html')
  32. await writeFile(distIndex, '<head></head><body>shell</body>')
  33. await writeFile(join(dist, 'app.js'), 'export {}')
  34. await writeFile(join(dist, 'blob.bin'), 'BLOB')
  35. const configPath = join(root, 'cordis.yml')
  36. await writeFile(configPath, [
  37. "- name: '@deepseek-ai/dsh-host-webserver'",
  38. ' config:',
  39. " host: '127.0.0.1'",
  40. ' port: 0',
  41. '- id: frontend',
  42. " name: '@deepseek-ai/dsh-frontend-static'",
  43. ' config:',
  44. ` distIndex: '${distIndex}'`,
  45. '',
  46. ].join('\n'))
  47. context = new Context()
  48. context.baseUrl = pathToFileURL(root).href + '/'
  49. await context.plugin(Loader)
  50. context.loader.builtins.include = Include
  51. const modules = new Map<string, unknown>([
  52. ['@deepseek-ai/dsh-host-webserver', HttpServer],
  53. ['@deepseek-ai/dsh-frontend-static', FrontendStatic],
  54. ])
  55. context.loader.internal = {
  56. version: 'v2',
  57. async import(specifier: string) {
  58. if (!modules.has(specifier)) throw new Error(`unexpected Loader import: ${specifier}`)
  59. return modules.get(specifier)
  60. },
  61. } as unknown as NonNullable<typeof context.loader.internal>
  62. await context.loader.create({
  63. name: 'cordis:include',
  64. config: { path: pathToFileURL(configPath).href },
  65. })
  66. await context.loader.await()
  67. return context
  68. }
  69. /** GET (by default) one path against the running server; returns status, content-type, and a body prefix. */
  70. async function request(port: number, path: string, init?: RequestInit): Promise<{ status: number; type: string | null; body: string }> {
  71. const response = await fetch(`http://127.0.0.1:${String(port)}${path}`, init)
  72. return {
  73. status: response.status,
  74. type: response.headers.get('content-type'),
  75. body: (await response.text()).slice(0, 80),
  76. }
  77. }
  78. describe('real Loader composition', () => {
  79. it('serves the dist with SPA fallback, taps, traversal rejection, and method gating', { timeout: 60_000 }, async () => {
  80. const loaded = await loadComposition()
  81. const unloaded = [...loaded.loader.entries()]
  82. .filter(entry => entry.fiber === undefined && !entry.disabled)
  83. .map(entry => entry.options.name)
  84. expect(unloaded).toEqual([])
  85. const server = loaded.httpServer
  86. const port = server.port
  87. // Real asset with its MIME type; a live rebuild is served on the next read.
  88. expect(await request(port, '/app.js')).toMatchObject({ status: 200, type: 'text/javascript; charset=utf-8', body: 'export {}' })
  89. await writeFile(join(root!, 'dist', 'app.js'), 'export const rebuilt = true')
  90. expect(await request(port, '/app.js')).toMatchObject({ status: 200, body: 'export const rebuilt = true' })
  91. // Unknown extension ships as octet-stream.
  92. expect(await request(port, '/blob.bin')).toMatchObject({ status: 200, type: 'application/octet-stream', body: 'BLOB' })
  93. // `/`, the index path, and any miss all render index.html (SPA routing)
  94. // through the registered index taps.
  95. const untap = server.tapIndex(html => html.replace('<head>', '<head><script>window.__T__=1</script>'))
  96. for (const path of ['/', '/index.html', '/no/such/route']) {
  97. const got = await request(port, path)
  98. expect(got.status).toBe(200)
  99. expect(got.body).toContain('__T__')
  100. expect(got.body).toContain('shell')
  101. }
  102. untap()
  103. expect((await request(port, '/')).body).not.toContain('__T__')
  104. // Traversal outside the dist root is 403; non-GET/HEAD is 405.
  105. expect((await request(port, '/..%2f..%2fetc%2fpasswd')).status).toBe(403)
  106. expect((await request(port, '/nowhere', { method: 'POST' })).status).toBe(405)
  107. // HMR safety: disposing the frontend row releases the fallback seat (the
  108. // unclaimed webserver answers 404) and the seat is claimable again.
  109. const frontendEntry = [...loaded.loader.entries()].find(e => e.options.id === 'frontend')
  110. expect(frontendEntry).toBeDefined()
  111. await frontendEntry!.fiber?.dispose()
  112. expect((await request(port, '/no/such/route')).status).toBe(404)
  113. expect(() => server.registerFallback(() => {})).not.toThrow()
  114. })
  115. })