1
0

index.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  1. /**
  2. * jsdom slot test runtime: a real small runtime — Cordis `Context`, the
  3. * runtime `SlotsService`, and the web-react renderer — assembled around
  4. * test-owned session/workspace doubles, so feature specs exercise
  5. * declaration, registration, scope, store, inject, rendering, updates, and
  6. * disposal without hand-building the machinery per suite.
  7. *
  8. * Not part of the product plugin graph (no `dshClient`); feature packages
  9. * depend on it in devDependencies only. It copies no SlotCore/renderer/store
  10. * machinery — everything mounts the production implementations.
  11. * @module @deepseek-ai/dsh-client-test-runtime
  12. */
  13. /* oxlint-disable typescript/no-redundant-type-constituents --
  14. * `keyof SlotMap & string` is the declare-merge key pattern (see ui-slots):
  15. * this compilation unit sees only the runtime's 'root' row, but consumer
  16. * programs merge their own keys in; the rule fires on the narrow-map view. */
  17. import { Context, Inject } from 'cordis'
  18. import type { Fiber, Plugin } from 'cordis'
  19. import { createElement, Fragment, useSyncExternalStore } from 'react'
  20. import type { ReactNode } from 'react'
  21. import { act, render, within } from '@testing-library/react'
  22. import type { RenderResult } from '@testing-library/react'
  23. import type { queries } from '@testing-library/dom'
  24. import type { BoundFunctions } from '@testing-library/dom'
  25. import { SlotsService } from '@deepseek-ai/dsh-client-runtime/client'
  26. import { createSlotRenderer } from '@deepseek-ai/dsh-client-web-react'
  27. import type {
  28. ChildrenDecl, ComposedProps, OwnerOf, SlotComponent, SlotMap, SlotRendererHost, StoreInstanceLike,
  29. } from '@deepseek-ai/dsh-client-ui-slots'
  30. import { registerDomSnapshotSerializer } from './snapshot.ts'
  31. import { TestSessions } from './sessions.ts'
  32. import { TestWorkspaces } from './workspaces.ts'
  33. import type { Stabilizer } from './fixtures.ts'
  34. export { domSnapshotSerializer, registerDomSnapshotSerializer } from './snapshot.ts'
  35. export { FixtureSession, TestSessions } from './sessions.ts'
  36. export { TestWorkspaces } from './workspaces.ts'
  37. export { conversationSnapshot, workspaceListState } from './fixtures.ts'
  38. export type { SessionBehaviorOverrides, SessionFixture, Stabilizer } from './fixtures.ts'
  39. /** Erased register face for the internal root call (the public declare seam holds the typing). */
  40. type ErasedRegister = (options: object, component: unknown) => () => void
  41. /**
  42. * One rendered slot's local view, from {@link SlotTestRuntime.renderSlot}:
  43. * the `data-slot` wrapper is the snapshot root (`expect(view.container)
  44. * .toMatchSnapshot()` captures exactly this slot's output), Testing Library
  45. * queries are bound inside it, and `update` re-renders with new owner props.
  46. */
  47. export interface SlotView<K extends keyof SlotMap & string> {
  48. /** The `<div data-slot="<key>">` wrapper around the slot's rendered output. */
  49. readonly container: HTMLElement
  50. /** Testing Library queries scoped to {@link SlotView.container}. */
  51. readonly view: BoundFunctions<typeof queries>
  52. /**
  53. * Replace the owner props and flush the re-render (the render-site update:
  54. * in production the owner recomputes the share and React re-renders).
  55. * @param owner - the next owner props share.
  56. */
  57. update(owner: OwnerOf<K>): void
  58. }
  59. /**
  60. * Mounted feature plugin handle: the live fiber plus an act-wrapped,
  61. * idempotent dispose (unload cascade: entries, declared child slots, store
  62. * instances, and provided services all fall together).
  63. */
  64. export interface FeatureHandle {
  65. /** The plugin's live Cordis fiber (state assertions, escape hatch). */
  66. readonly fiber: Fiber
  67. /**
  68. * Dispose the plugin fiber inside React act; repeated calls no-op.
  69. * @returns completion of the unload cascade.
  70. */
  71. dispose(): Promise<void>
  72. }
  73. /**
  74. * Owner-props cell behind the auto frame: one external store the frame
  75. * subscribes to, so {@link SlotTestRuntime.renderSlot} and
  76. * {@link SlotView.update} drive React through the standard uSES seam.
  77. */
  78. class OwnerPropsCell {
  79. private readonly owners = new Map<string, object>()
  80. private readonly listeners = new Set<() => void>()
  81. private version = 0
  82. /** Snapshot version for uSES pairing (bumped on every set). */
  83. readonly getVersion = (): number => this.version
  84. /**
  85. * Subscribe to owner-props changes.
  86. * @param fn - change callback.
  87. * @returns unsubscribe.
  88. */
  89. readonly subscribe = (fn: () => void): (() => void) => {
  90. this.listeners.add(fn)
  91. return () => { this.listeners.delete(fn) }
  92. }
  93. /**
  94. * Install or replace one key's owner props and notify (synchronous; the
  95. * caller wraps in act).
  96. * @param key - slot key.
  97. * @param owner - owner props share.
  98. */
  99. set(key: string, owner: object): void {
  100. this.owners.set(key, owner)
  101. this.version += 1
  102. for (const fn of [...this.listeners]) fn()
  103. }
  104. /** Keys with supplied owner props, in first-supply order. */
  105. entries(): readonly (readonly [string, object])[] {
  106. return [...this.owners.entries()]
  107. }
  108. }
  109. /**
  110. * The test-owned 'root' occupant: declares the child slots a suite needs
  111. * through the REAL `slots.register`, with a caller-supplied minimal frame —
  112. * the runtime never guesses a feature's page structure.
  113. */
  114. export class TestRoot {
  115. private disposeEntry: (() => void) | undefined
  116. /**
  117. * @param slots - the runtime SlotsService.
  118. * @param stabilize - the owning runtime's act wrapper.
  119. */
  120. constructor(private readonly slots: SlotsService, private readonly stabilize: Stabilizer) {}
  121. /**
  122. * Register the root frame, declaring (and thereby claiming) the child
  123. * slots. One declaration per runtime — a second call fails loud in the
  124. * core ('root' is a single slot).
  125. * @param children - child-slot declaration table (declaration + render authorization + runtime spec).
  126. * @param frame - minimal frame component; its props derive from the declared keys (composed-props contract).
  127. * @returns completion of the act-wrapped registration.
  128. */
  129. async declare<const D extends ChildrenDecl>(
  130. children: D,
  131. frame: SlotComponent<ComposedProps<'root', keyof NoInfer<D> & keyof SlotMap & string, undefined, object>>,
  132. ): Promise<void> {
  133. await this.stabilize(() => {
  134. // Erased hop (same pattern as SlotsService's own implementation arm);
  135. // the declare signature above is the typed seam.
  136. this.disposeEntry = (this.slots.register as unknown as ErasedRegister)({ name: 'root', children }, frame)
  137. })
  138. }
  139. /** Remove the root registration and collapse its declarations (runtime dispose path). */
  140. release(): void {
  141. this.disposeEntry?.()
  142. this.disposeEntry = undefined
  143. }
  144. }
  145. /**
  146. * The assembled test runtime. Obtain via {@link SlotTestRuntime.create};
  147. * dispose with {@link SlotTestRuntime.dispose} (afterEach). Public mutators
  148. * are act-wrapped throughout — tests never handle SlotCore microtask
  149. * batching or React act themselves.
  150. */
  151. export class SlotTestRuntime {
  152. /** The runtime's Cordis root (escape hatch: extra services via `ctx.provide`, raw `ctx.plugin` mounts). */
  153. readonly ctx: Context
  154. /** The production SlotsService mounted on {@link SlotTestRuntime.ctx}. */
  155. readonly slots: SlotsService
  156. /** The test-owned 'root' occupant. */
  157. readonly root: TestRoot
  158. /** Sessions double (list/current observable, cells, scopes, behavior faces). */
  159. readonly sessions: TestSessions
  160. /** Workspaces double (list observable, recorded intent actions). */
  161. readonly workspaces: TestWorkspaces
  162. private readonly stabilizer: Stabilizer = async (fn) => {
  163. await act(async () => { await fn() })
  164. }
  165. private host: SlotRendererHost | undefined
  166. private readonly views: RenderResult[] = []
  167. private readonly handles: FeatureHandle[] = []
  168. private disposed = false
  169. /** Auto-frame state ({@link SlotTestRuntime.declare} / {@link SlotTestRuntime.renderSlot}). */
  170. private readonly ownerCell = new OwnerPropsCell()
  171. private readonly autoDeclared = new Set<string>()
  172. private autoRootView: RenderResult | undefined
  173. private constructor(ctx: Context, slots: SlotsService) {
  174. this.ctx = ctx
  175. this.slots = slots
  176. this.root = new TestRoot(slots, this.stabilizer)
  177. this.sessions = new TestSessions(this.stabilizer, ctx)
  178. this.workspaces = new TestWorkspaces(this.stabilizer)
  179. ctx.provide('sessions', this.sessions)
  180. ctx.provide('workspaces', this.workspaces)
  181. // Capturing install: the production renderer does the rendering; the
  182. // wrapper only takes the host face for storeOf (no machinery copied).
  183. const renderer = createSlotRenderer()
  184. slots.install({
  185. renderRoot: (host, ownerProps) => {
  186. this.host = host
  187. return renderer.renderRoot(host, ownerProps)
  188. },
  189. })
  190. }
  191. /**
  192. * Assemble a runtime: real Context, mounted SlotsService, installed
  193. * renderer, and the session/workspace doubles provided as services.
  194. * @returns the ready runtime.
  195. */
  196. static async create(): Promise<SlotTestRuntime> {
  197. registerDomSnapshotSerializer()
  198. const ctx = new Context()
  199. const fiber = ctx.plugin(SlotsService)
  200. await fiber.await()
  201. return new SlotTestRuntime(ctx, ctx.get('slots') as SlotsService)
  202. }
  203. /**
  204. * Provide an extra service the feature under test injects (e.g. a layout
  205. * fake). Sugar over `ctx.provide`, typed against the Context declaration
  206. * merge: for a declared service name the fake must be a subset of that
  207. * service's outward face (Partial — supply only what the feature calls),
  208. * so a production face change breaks the fake at compile time. Undeclared
  209. * names stay unchecked (ad-hoc test services).
  210. * @param name - service name.
  211. * @param value - service implementation (test double).
  212. */
  213. provide<K extends string>(name: K, value: K extends keyof Context ? Partial<Context[K]> : unknown): void {
  214. this.ctx.provide(name, value)
  215. }
  216. /**
  217. * Mount a feature plugin on a real fiber. Required services are prechecked
  218. * so a missing provider fails loud instead of suspending the fiber forever
  219. * (deliberate load-order suspension tests use `ctx.plugin` directly).
  220. * @param plugin - plugin value (function, class, or `{ inject, apply }` object).
  221. * @returns handle owning the fiber's explicit disposal.
  222. */
  223. async mount(plugin: Plugin): Promise<FeatureHandle> {
  224. const required = Object.keys(Inject.resolve((plugin as { inject?: Inject }).inject))
  225. const missing = required.filter(name => this.ctx.get(name) === undefined)
  226. if (missing.length > 0) {
  227. throw new Error(`mount would suspend: missing service(s) ${missing.join(', ')} — provide() them first`)
  228. }
  229. const fiber = this.ctx.plugin(plugin)
  230. await this.stabilizer(async () => {
  231. await fiber.await()
  232. })
  233. let disposed = false
  234. const handle: FeatureHandle = {
  235. fiber,
  236. dispose: async () => {
  237. if (disposed) return
  238. disposed = true
  239. await this.stabilizer(() => fiber.dispose())
  240. },
  241. }
  242. this.handles.push(handle)
  243. return handle
  244. }
  245. /**
  246. * Render the root slot tree through the ctx-level entry (the shell's own
  247. * seam): `ctx.slots.renderSlot('root', {})` under Testing Library.
  248. * @returns the Testing Library view.
  249. */
  250. renderRoot(): RenderResult {
  251. const view = render(createElement(Fragment, null, this.slots.renderSlot('root', {})))
  252. this.views.push(view)
  253. return view
  254. }
  255. /**
  256. * Declare child slots under an auto-generated root frame — the single-slot
  257. * mounting path for local DOM snapshots. Each key later supplied through
  258. * {@link SlotTestRuntime.renderSlot} renders inside its own
  259. * `<div data-slot="<key>">` wrapper (the snapshot root). Mutually exclusive
  260. * with {@link TestRoot.declare} ('root' is a single slot); one call per
  261. * runtime.
  262. * @param children - child-slot declaration table (same contract as TestRoot.declare).
  263. * @returns completion of the act-wrapped registration.
  264. */
  265. async declare(children: ChildrenDecl): Promise<void> {
  266. for (const key of Object.keys(children)) this.autoDeclared.add(key)
  267. const cell = this.ownerCell
  268. const AutoFrame = (props: { renderSlot: (key: string, owner: object) => ReactNode }) => {
  269. useSyncExternalStore(cell.subscribe, cell.getVersion)
  270. return createElement(Fragment, null, cell.entries().map(([key, owner]) =>
  271. createElement('div', { 'data-slot': key, key }, props.renderSlot(key, owner))))
  272. }
  273. await this.root.declare(children as never, AutoFrame as never)
  274. }
  275. /**
  276. * Render one declared slot with its owner props and return the local view.
  277. * The whole root tree mounts through the production assembly path
  278. * (renderer, scope providers, store axis); only this key's output lands in
  279. * the returned container. Call again with another key to view a sibling
  280. * slot of the same tree.
  281. * @param key - a key declared through {@link SlotTestRuntime.declare}.
  282. * @param owner - owner props share for the render site.
  283. * @returns the slot-local view (snapshot container, scoped queries, owner updates).
  284. */
  285. renderSlot<K extends keyof SlotMap & string>(key: K, owner: OwnerOf<K>): SlotView<K> {
  286. if (!this.autoDeclared.has(key)) {
  287. throw new Error(`renderSlot('${key}') without declare() — declare the key first (or use root.declare for a custom frame)`)
  288. }
  289. const install = (next: object): void => {
  290. // Synchronous cell write inside act: the frame re-renders through uSES.
  291. act(() => {
  292. this.ownerCell.set(key, next)
  293. })
  294. }
  295. install(owner)
  296. this.autoRootView ??= this.renderRoot()
  297. const container = this.autoRootView.container.querySelector(`[data-slot="${key}"]`)
  298. if (!(container instanceof HTMLElement)) {
  299. throw new Error(`renderSlot('${key}'): the auto frame rendered no wrapper — was the runtime already disposed?`)
  300. }
  301. return { container, view: within(container), update: install }
  302. }
  303. /**
  304. * Resolve the store instance the renderer would hand a slot's component
  305. * (identity assertions, action-driven writes). Requires a prior
  306. * {@link SlotTestRuntime.renderRoot} — the host face exists only inside the
  307. * installed renderer, exactly as in production.
  308. * @param key - slot key whose first entry declares the store.
  309. * @param scopeKey - session id for session-scope slots; omit for root scope.
  310. * @returns the live store instance.
  311. */
  312. storeOf(key: keyof SlotMap & string, scopeKey?: string): StoreInstanceLike {
  313. if (this.host === undefined) {
  314. throw new Error('storeOf before renderRoot() — the host face exists only inside the installed renderer')
  315. }
  316. const entry = this.host.entriesOf(key)[0]
  317. if (entry === undefined) throw new Error(`storeOf('${key}'): no registration on the ledger`)
  318. const instance = this.host.storeOf(entry, scopeKey)
  319. if (instance === undefined) throw new Error(`storeOf('${key}'): the entry declares no store`)
  320. return instance
  321. }
  322. /**
  323. * Flush pending ledger/store notifications inside act — for mutations made
  324. * outside the runtime's own methods (e.g. a direct `slots.register`).
  325. * @returns completion of the act pass.
  326. */
  327. async flush(): Promise<void> {
  328. await this.stabilizer(() => {})
  329. }
  330. /**
  331. * Tear down: unmount React trees first, then dispose feature fibers, the
  332. * root registration, minted session scopes, and persisted test state.
  333. * Idempotent.
  334. * @returns completion of the teardown.
  335. */
  336. async dispose(): Promise<void> {
  337. if (this.disposed) return
  338. this.disposed = true
  339. this.autoRootView = undefined
  340. for (const view of this.views.splice(0)) view.unmount()
  341. for (const handle of this.handles.splice(0)) await handle.dispose()
  342. this.root.release()
  343. await this.sessions.disposeScopes()
  344. localStorage.clear()
  345. }
  346. }