index.ts 16 KB

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