index.ts 16 KB

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