test-invariants.ts 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. /**
  2. * Vitest-wide invariant host. Ordinary Cordis roots receive the invariant
  3. * service with global enablement plus the current test package's companion.
  4. * One topology test mounts every companion; focused invariant tests own their
  5. * service topology explicitly.
  6. */
  7. import { expect } from 'vitest'
  8. import { RegistryService } from 'cordis'
  9. import type { Context, Plugin } from 'cordis'
  10. import { AttachmentStore } from '@deepseek-ai/dsh-attachment'
  11. import type {
  12. ImageAttachmentLimits,
  13. ImageAttachmentRef,
  14. SaveImageAttachment,
  15. StoredImageAttachment,
  16. } from '@deepseek-ai/dsh-attachment'
  17. import InvariantService from '@deepseek-ai/dsh-invariants'
  18. declare global {
  19. interface ImportMeta {
  20. /** Eager Vite module-glob expansion used by the Vitest setup file. */
  21. glob<TModule>(pattern: string, options: { eager: true }): Record<string, TModule>
  22. }
  23. }
  24. /** Loader-safe shape shared by every package invariant companion. */
  25. export interface TestInvariantCompanion {
  26. readonly name: string
  27. readonly inject: readonly string[]
  28. readonly default?: unknown
  29. apply(ctx: Context): Promise<() => void>
  30. }
  31. /** Every package companion, discovered eagerly so coverage observes each registration. */
  32. export const testInvariantCompanions: Readonly<Record<string, TestInvariantCompanion>> =
  33. import.meta.glob<TestInvariantCompanion>('../packages/*/*/src/invariant.ts', { eager: true })
  34. /** Manual-topology suites whose names cannot follow the focused invariant convention. */
  35. const MANUAL_INVARIANT_TEST_EXCEPTIONS = [
  36. '/packages/support/invariants/tests/service.spec.ts',
  37. '/packages/examples/agent-spine-demo/tests/agent-core.spec.ts',
  38. ] as const
  39. interface InvariantHost {
  40. readonly fibers: readonly PluginFiber[]
  41. readonly byCallback: ReadonlyMap<unknown, PluginFiber>
  42. readonly ready: Promise<void>
  43. }
  44. type PluginFiber = ReturnType<RegistryService['plugin']>
  45. const hosts = new WeakMap<Context, InvariantHost>()
  46. // eslint-disable-next-line @typescript-eslint/unbound-method -- every call below supplies its RegistryService receiver explicitly.
  47. const originalPlugin = RegistryService.prototype.plugin
  48. RegistryService.prototype.plugin = function(plugin: Plugin, config?: unknown, getOuterStack?: () => string[]) {
  49. const testPath = expect.getState().testPath ?? ''
  50. if (usesManualInvariantTree(testPath)) return originalPlugin.call(this, plugin, config, getOuterStack)
  51. const root = this.ctx.root
  52. const host = hosts.get(root) ?? startInvariantHost(root)
  53. const callback = this.resolve(plugin)
  54. const existing = callback === undefined ? undefined : host.byCallback.get(callback)
  55. if (existing !== undefined) {
  56. return this.ctx === root ? joinInvariantStartup(existing, host.ready) : existing
  57. }
  58. const fiber = originalPlugin.call(this, plugin, config, getOuterStack)
  59. // A root-level await is the test's composition boundary. Nested plugin
  60. // fibers must not await their own companion parent through the global host.
  61. if (this.ctx !== root) return fiber
  62. return joinInvariantStartup(fiber, host.ready)
  63. }
  64. /**
  65. * Detect focused suites that construct service selection or companion lifecycle explicitly.
  66. * @param testPath - absolute or repo-relative Vitest file path.
  67. * @returns whether the global invariant host must leave the root untouched.
  68. */
  69. export function usesManualInvariantTree(testPath: string): boolean {
  70. const normalized = testPath.replaceAll('\\', '/')
  71. if (/\/packages\/[^/]+\/[^/]+\/tests\/[^/]*invariant[^/]*\.spec\.ts$/.test(normalized)) return true
  72. return MANUAL_INVARIANT_TEST_EXCEPTIONS.some(path => normalized.endsWith(path))
  73. }
  74. const ALL_COMPANION_TESTS = ['/scripts/test-invariants.spec.ts'] as const
  75. const ATTACHMENT_COMPANION = '../packages/attachment/attachment-local/src/invariant.ts'
  76. class TestAttachmentStore extends AttachmentStore {
  77. readonly imageLimits: ImageAttachmentLimits = {
  78. maxImageBytes: 1,
  79. maxImagesPerMessage: 1,
  80. maxMessageImageBytes: 1,
  81. maxImagePixels: 1,
  82. mediaTypes: ['image/png'],
  83. }
  84. saveImage(_input: SaveImageAttachment): Promise<ImageAttachmentRef> {
  85. return Promise.reject(new Error('test invariant attachment store does not save images'))
  86. }
  87. readImage(_ref: ImageAttachmentRef): Promise<StoredImageAttachment> {
  88. return Promise.reject(new Error('test invariant attachment store does not read images'))
  89. }
  90. }
  91. /**
  92. * Select the package companions that an ordinary test root must register.
  93. * Package tests receive their owner's checks; the dedicated topology test
  94. * receives every owner so coverage and exhaustive runtime registration remain
  95. * independently enforced.
  96. * @param testPath - absolute or repo-relative normalized Vitest file path.
  97. * @returns sorted `import.meta.glob` keys for companions to mount.
  98. */
  99. export function testInvariantCompanionPaths(testPath: string): string[] {
  100. const normalized = testPath.replaceAll('\\', '/')
  101. const allPaths = Object.keys(testInvariantCompanions).sort()
  102. if (ALL_COMPANION_TESTS.some(path => normalized.endsWith(path))) return allPaths
  103. const owner = normalized.match(/\/packages\/([^/]+)\/([^/]+)\/tests\//)
  104. if (owner === null) return []
  105. const companionPath = `../packages/${owner[1]}/${owner[2]}/src/invariant.ts`
  106. if (testInvariantCompanions[companionPath] === undefined) {
  107. throw new Error(`test invariants: package test has no companion at ${companionPath}`)
  108. }
  109. return [companionPath]
  110. }
  111. function startInvariantHost(root: Context): InvariantHost {
  112. const fibers: PluginFiber[] = []
  113. const byCallback = new Map<unknown, PluginFiber>()
  114. const mount = (plugin: Plugin, config?: unknown): void => {
  115. const fiber = originalPlugin.call(root.registry, plugin, config)
  116. const callback = root.registry.resolve(plugin)
  117. if (callback === undefined) throw new Error('test invariants: companion is not a valid Cordis plugin')
  118. fibers.push(fiber)
  119. byCallback.set(callback, fiber)
  120. }
  121. mount(InvariantService, { enabled: true })
  122. const testPath = expect.getState().testPath ?? ''
  123. const companionPaths = testInvariantCompanionPaths(testPath)
  124. if (companionPaths.includes(ATTACHMENT_COMPANION)) mount(TestAttachmentStore)
  125. for (const path of companionPaths) {
  126. const companion = testInvariantCompanions[path]
  127. if (companion === undefined) {
  128. throw new Error(`test invariants: selected companion vanished at ${path}`)
  129. }
  130. if (!companion.inject.includes('invariants')) {
  131. throw new Error(`test invariants: ${path} must inject the invariant service`)
  132. }
  133. mount(companion)
  134. }
  135. const [serviceFiber, ...companionFibers] = fibers
  136. if (serviceFiber === undefined) throw new Error('test invariants: service fiber was not mounted')
  137. // A companion is initially PENDING on the invariant service, and Cordis
  138. // Fiber.await() only joins work already in flight. Wait for the service to
  139. // activate its dependants before joining their startup and failures.
  140. const ready = serviceFiber.await()
  141. .then(() => Promise.all(companionFibers.map(fiber => fiber.await())))
  142. .then(() => undefined)
  143. const host = { fibers, byCallback, ready }
  144. hosts.set(root, host)
  145. return host
  146. }
  147. function joinInvariantStartup(fiber: PluginFiber, invariantReady: Promise<void>): PluginFiber {
  148. const readiness = fiber.await().then(async (loaded) => {
  149. await invariantReady
  150. return loaded
  151. })
  152. const joined = Object.create(fiber) as PluginFiber
  153. joined.then = readiness.then.bind(readiness)
  154. return joined
  155. }