frontend-static.spec.ts 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133
  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 '@deepseek-ai/cordis'
  14. import Loader from '@deepseek-ai/cordis-plugin-loader'
  15. import Include from '@deepseek-ai/cordis-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. await writeFile(join(dist, 'manifest.webmanifest'), '{}')
  36. const configPath = join(root, 'cordis.yml')
  37. await writeFile(configPath, [
  38. "- name: '@deepseek-ai/dsh-host-webserver'",
  39. ' config:',
  40. " host: '127.0.0.1'",
  41. ' port: 0',
  42. '- id: frontend',
  43. " name: '@deepseek-ai/dsh-frontend-static'",
  44. ' config:',
  45. ` distIndex: '${distIndex}'`,
  46. '',
  47. ].join('\n'))
  48. context = new Context()
  49. context.baseUrl = pathToFileURL(root).href + '/'
  50. await context.plugin(Loader)
  51. context.loader.builtins.include = Include
  52. const modules = new Map<string, unknown>([
  53. ['@deepseek-ai/dsh-host-webserver', HttpServer],
  54. ['@deepseek-ai/dsh-frontend-static', FrontendStatic],
  55. ])
  56. context.loader.internal = {
  57. version: 'v2',
  58. async import(specifier: string) {
  59. if (!modules.has(specifier)) throw new Error(`unexpected Loader import: ${specifier}`)
  60. return modules.get(specifier)
  61. },
  62. } as unknown as NonNullable<typeof context.loader.internal>
  63. await context.loader.create({
  64. name: 'cordis:include',
  65. config: { path: pathToFileURL(configPath).href },
  66. })
  67. await context.loader.await()
  68. return context
  69. }
  70. /** GET (by default) one path against the running server; returns status, content-type, and a body prefix. */
  71. async function request(port: number, path: string, init?: RequestInit): Promise<{ status: number; type: string | null; body: string }> {
  72. const response = await fetch(`http://127.0.0.1:${String(port)}${path}`, init)
  73. return {
  74. status: response.status,
  75. type: response.headers.get('content-type'),
  76. body: (await response.text()).slice(0, 80),
  77. }
  78. }
  79. describe('real Loader composition', () => {
  80. it('serves the dist with SPA fallback, taps, traversal rejection, and method gating', { timeout: 60_000 }, async () => {
  81. const loaded = await loadComposition()
  82. const unloaded = [...loaded.loader.entries()]
  83. .filter(entry => entry.fiber === undefined && !entry.disabled)
  84. .map(entry => entry.options.name)
  85. expect(unloaded).toEqual([])
  86. const server = loaded.httpServer
  87. const port = server.port
  88. // Real assets with their MIME types; a live rebuild is served on the next read.
  89. expect(await request(port, '/app.js')).toMatchObject({ status: 200, type: 'text/javascript; charset=utf-8', body: 'export {}' })
  90. expect(await request(port, '/manifest.webmanifest')).toMatchObject({
  91. status: 200,
  92. type: 'application/manifest+json',
  93. body: '{}',
  94. })
  95. await writeFile(join(root!, 'dist', 'app.js'), 'export const rebuilt = true')
  96. expect(await request(port, '/app.js')).toMatchObject({ status: 200, body: 'export const rebuilt = true' })
  97. // Unknown extension ships as octet-stream.
  98. expect(await request(port, '/blob.bin')).toMatchObject({ status: 200, type: 'application/octet-stream', body: 'BLOB' })
  99. // `/`, the index path, and any miss all render index.html (SPA routing)
  100. // through the registered index taps.
  101. const untap = server.tapIndex(html => html.replace('<head>', '<head><script>window.__T__=1</script>'))
  102. for (const path of ['/', '/index.html', '/no/such/route']) {
  103. const got = await request(port, path)
  104. expect(got.status).toBe(200)
  105. expect(got.body).toContain('__T__')
  106. expect(got.body).toContain('shell')
  107. }
  108. untap()
  109. expect((await request(port, '/')).body).not.toContain('__T__')
  110. // Traversal outside the dist root is 403; non-GET/HEAD is 405.
  111. expect((await request(port, '/..%2f..%2fetc%2fpasswd')).status).toBe(403)
  112. expect((await request(port, '/nowhere', { method: 'POST' })).status).toBe(405)
  113. // HMR safety: disposing the frontend row releases the fallback seat (the
  114. // unclaimed webserver answers 404) and the seat is claimable again.
  115. const frontendEntry = [...loaded.loader.entries()].find(e => e.options.id === 'frontend')
  116. expect(frontendEntry).toBeDefined()
  117. await frontendEntry!.fiber?.dispose()
  118. expect((await request(port, '/no/such/route')).status).toBe(404)
  119. expect(() => server.registerFallback(() => {})).not.toThrow()
  120. })
  121. })