@deepseek-ai/dsh-client-test-runtime 0.2.2-rc.1 → 0.2.2-rc.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/README.i18n.yaml +2 -2
  2. package/README.md +1 -1
  3. package/README.zh.md +1 -1
  4. package/lib/index.js +9 -0
  5. package/lib/types/access.d.ts.map +1 -0
  6. package/lib/types/access.js.map +1 -0
  7. package/lib/types/assembly/bundle-roster.d.ts.map +1 -0
  8. package/lib/types/assembly/bundle-roster.js.map +1 -0
  9. package/lib/types/assembly/index.d.ts.map +1 -0
  10. package/lib/types/assembly/index.js.map +1 -0
  11. package/lib/types/assembly/modules.d.ts.map +1 -0
  12. package/lib/types/assembly/modules.js.map +1 -0
  13. package/lib/types/assembly/remote-default-responses.d.ts.map +1 -0
  14. package/lib/types/assembly/remote-default-responses.js.map +1 -0
  15. package/lib/types/assembly/remote-proxies.d.ts.map +1 -0
  16. package/lib/types/assembly/remote-proxies.js.map +1 -0
  17. package/lib/types/assembly/roster.d.ts.map +1 -0
  18. package/lib/types/assembly/roster.js.map +1 -0
  19. package/lib/types/assembly/test-client.d.ts +10 -2
  20. package/lib/types/assembly/test-client.d.ts.map +1 -0
  21. package/lib/types/assembly/test-client.js.map +1 -0
  22. package/lib/types/assembly/vitest.d.ts +1 -1
  23. package/lib/types/assembly/vitest.d.ts.map +1 -0
  24. package/lib/types/assembly/vitest.js.map +1 -0
  25. package/lib/types/config-form.d.ts.map +1 -0
  26. package/lib/types/config-form.js.map +1 -0
  27. package/lib/types/context-menu.d.ts.map +1 -0
  28. package/lib/types/context-menu.js.map +1 -0
  29. package/lib/types/fixtures.d.ts.map +1 -0
  30. package/lib/types/fixtures.js.map +1 -0
  31. package/lib/types/index.d.ts.map +1 -0
  32. package/lib/types/index.js.map +1 -0
  33. package/lib/types/locale-env.d.ts.map +1 -0
  34. package/lib/types/locale-env.js.map +1 -0
  35. package/lib/types/remote.d.ts.map +1 -0
  36. package/lib/types/remote.js.map +1 -0
  37. package/lib/types/sessions.d.ts +5 -0
  38. package/lib/types/sessions.d.ts.map +1 -0
  39. package/lib/types/sessions.js.map +1 -0
  40. package/lib/types/snapshot.d.ts.map +1 -0
  41. package/lib/types/snapshot.js.map +1 -0
  42. package/lib/types/translate.d.ts.map +1 -0
  43. package/lib/types/translate.js.map +1 -0
  44. package/lib/types/workspaces.d.ts.map +1 -0
  45. package/lib/types/workspaces.js.map +1 -0
  46. package/package.json +53 -50
  47. package/src/access.ts +95 -0
  48. package/src/assembly/bundle-roster.ts +167 -0
  49. package/src/assembly/index.ts +14 -0
  50. package/src/assembly/modules.ts +80 -0
  51. package/src/assembly/remote-default-responses.ts +64 -0
  52. package/src/assembly/remote-proxies.ts +87 -0
  53. package/src/assembly/roster.ts +163 -0
  54. package/src/assembly/test-client.ts +388 -0
  55. package/src/assembly/vitest.ts +60 -0
  56. package/src/config-form.ts +61 -0
  57. package/src/context-menu.ts +17 -0
  58. package/src/fixtures.ts +119 -0
  59. package/src/index.ts +490 -0
  60. package/src/locale-env.ts +29 -0
  61. package/src/remote.ts +103 -0
  62. package/src/sessions.ts +844 -0
  63. package/src/snapshot.ts +89 -0
  64. package/src/translate.ts +32 -0
  65. package/src/workspaces.ts +210 -0
@@ -0,0 +1,163 @@
1
+ /**
2
+ * Client roster: the ordered package-name rows a whole-client test boots, and
3
+ * the plan that annotates one with the rows the test provides itself. `webApp`
4
+ * and `bundleRoster` (`./bundle-roster.ts`) read rosters from the bundle patch
5
+ * files; a spec may also build one inline with {@link ClientRoster.of}.
6
+ * @module @deepseek-ai/dsh-client-test-runtime/src/assembly/roster
7
+ */
8
+ import type { Context } from '@deepseek-ai/cordis'
9
+ import type { WebBootEntry, WebBootGraph } from '@deepseek-ai/dsh-client-modules/client'
10
+ import { PLATFORM_MODULES } from '@deepseek-ai/dsh-client-web/src/platform.ts'
11
+
12
+ /** One browser plugin row as `dsh.client` declares it, keyed by package name. */
13
+ export interface ClientRosterRow {
14
+ /** Package name (== manifest entry id == Loader entry name). */
15
+ readonly name: string
16
+ /** Package-name dependency edges from `dsh.client.inject` ([] when absent). */
17
+ readonly inject: readonly string[]
18
+ /** Stage-one prefetch mark from `dsh.client.immediately` (false when absent). */
19
+ readonly immediately: boolean
20
+ }
21
+
22
+ /** Revision stamped on every synthesized row and batch; nothing is fetched by it. */
23
+ const LOCAL_REV = 'local'
24
+
25
+ /**
26
+ * Synthesize the raw `WebBootGraph` for `rows`: one `application` batch
27
+ * holding every row, `rev: 'local'`, placeholder `plugins/<name>/client.js`
28
+ * references, since every module is seeded in process and never fetched.
29
+ * Validation stays with the production `parseBootManifest` inside the module
30
+ * system: duplicate names and an empty roster are rejected there, not here.
31
+ * @param rows - roster rows in composition order.
32
+ * @returns the unparsed graph, as `createClientModuleSystem` consumes it.
33
+ */
34
+ export function graphFromRoster(rows: readonly ClientRosterRow[]): WebBootGraph {
35
+ const entries: WebBootEntry[] = rows.map(row => ({
36
+ id: row.name,
37
+ url: `plugins/${row.name}/client.js`,
38
+ rev: LOCAL_REV,
39
+ ...(row.inject.length > 0 ? { inject: [...row.inject] } : {}),
40
+ ...(row.immediately ? { immediately: true } : {}),
41
+ }))
42
+ return {
43
+ rev: LOCAL_REV,
44
+ entries,
45
+ batches: [{
46
+ phase: 'application',
47
+ url: 'plugins/local.js',
48
+ rev: LOCAL_REV,
49
+ entries: entries.map(entry => entry.id),
50
+ }],
51
+ }
52
+ }
53
+
54
+ /** Module names the shell seeds before any row loads; an inject edge to one of them is satisfied without a row. */
55
+ const PLATFORM_SEED: ReadonlySet<string> = new Set(PLATFORM_MODULES)
56
+
57
+ /** Immutable, name-addressable roster. */
58
+ export class ClientRoster {
59
+ /**
60
+ * Build a roster from rows; duplicate names throw.
61
+ * @param rows - roster rows in composition order.
62
+ * @returns roster.
63
+ */
64
+ static of(rows: readonly ClientRosterRow[]): ClientRoster {
65
+ const seen = new Set<string>()
66
+ const duplicates = new Set<string>()
67
+ for (const { name } of rows) {
68
+ if (seen.has(name)) duplicates.add(name)
69
+ seen.add(name)
70
+ }
71
+ if (duplicates.size > 0) {
72
+ throw new Error(`client-test-runtime: duplicate roster rows: ${[...duplicates].join(', ')}`)
73
+ }
74
+ return new ClientRoster(Object.freeze([...rows]))
75
+ }
76
+
77
+ private constructor(readonly rows: readonly ClientRosterRow[]) {}
78
+
79
+ /**
80
+ * Keep only `names`, preserving roster order; an unknown name throws with the roster listed.
81
+ * @param names - package names to keep.
82
+ * @returns sub-roster.
83
+ */
84
+ pick(names: readonly string[]): ClientRoster {
85
+ const keep = this.known(names, 'pick')
86
+ return new ClientRoster(Object.freeze(this.rows.filter(row => keep.has(row.name))))
87
+ }
88
+
89
+ /**
90
+ * The named rows plus every row they inject, transitively, in roster order: the rows a spec needs to boot the
91
+ * named plugins as the bundle composes them. The shell's platform modules (`PLATFORM_MODULES`, seeded statically
92
+ * rather than loaded as rows) end the walk. An unknown name throws with the roster listed; a row injecting any
93
+ * other package outside the roster throws, since the bundle itself would not boot.
94
+ * @param names - package names whose dependency cone to keep.
95
+ * @returns sub-roster.
96
+ */
97
+ closure(names: readonly string[]): ClientRoster {
98
+ this.known(names, 'closure')
99
+ const byName = new Map(this.rows.map(row => [row.name, row]))
100
+ const keep = new Set<string>()
101
+ const visit = (name: string, from: string | undefined): void => {
102
+ if (keep.has(name) || PLATFORM_SEED.has(name)) return
103
+ const row = byName.get(name)
104
+ if (row === undefined) {
105
+ throw new Error(`client-test-runtime: ${String(from)} injects ${name}, which is outside the roster`)
106
+ }
107
+ keep.add(name)
108
+ for (const dependency of row.inject) visit(dependency, name)
109
+ }
110
+ for (const name of names) visit(name, undefined)
111
+ return new ClientRoster(Object.freeze(this.rows.filter(row => keep.has(row.name))))
112
+ }
113
+
114
+ /**
115
+ * Drop `names`; an unknown name throws with the roster listed.
116
+ * @param names - package names to drop.
117
+ * @returns sub-roster.
118
+ */
119
+ without(names: readonly string[]): ClientRoster {
120
+ const drop = this.known(names, 'without')
121
+ return new ClientRoster(Object.freeze(this.rows.filter(row => !drop.has(row.name))))
122
+ }
123
+
124
+ private known(names: readonly string[], operation: string): ReadonlySet<string> {
125
+ const rostered = this.rows.map(row => row.name)
126
+ const unknown = names.filter(name => !rostered.includes(name))
127
+ if (unknown.length > 0) {
128
+ throw new Error(
129
+ `client-test-runtime: ${operation}() names outside the roster: ${unknown.join(', ')}; roster: ${rostered.join(', ')}`,
130
+ )
131
+ }
132
+ return new Set(names)
133
+ }
134
+ }
135
+
136
+ /** The module face the Loader materializes for one client plugin row. */
137
+ export interface ClientPluginModule {
138
+ apply(ctx: Context, config?: unknown): unknown
139
+ readonly inject?: readonly string[] | Readonly<Record<string, unknown>>
140
+ readonly Config?: unknown
141
+ }
142
+
143
+ /** What to boot and what the test supplies itself. */
144
+ export interface AssemblyPlan {
145
+ readonly roster: ClientRoster
146
+ /** Row replacements by package name (the test's own implementation of that row). Names outside the roster throw. */
147
+ readonly provide?: Readonly<Record<string, ClientPluginModule>>
148
+ }
149
+
150
+ /**
151
+ * Validate a plan against its roster.
152
+ * @param plan - plan to check.
153
+ * @throws {Error} naming any `provide` key outside the roster.
154
+ */
155
+ export function assertPlan(plan: AssemblyPlan): void {
156
+ const rostered = plan.roster.rows.map(row => row.name)
157
+ const unknown = Object.keys(plan.provide ?? {}).filter(name => !rostered.includes(name))
158
+ if (unknown.length > 0) {
159
+ throw new Error(
160
+ `client-test-runtime: provide names rows outside the roster: ${unknown.join(', ')}; roster: ${rostered.join(', ')}`,
161
+ )
162
+ }
163
+ }
@@ -0,0 +1,388 @@
1
+ /**
2
+ * Whole-client test carrier: boots an {@link AssemblyPlan} through the
3
+ * production `bootClient` over an in-process module table, with a
4
+ * `RemoteMock` bound to that client's Connection plugin instance.
5
+ * @module @deepseek-ai/dsh-client-test-runtime/src/assembly/test-client
6
+ */
7
+ import { Context, type Plugin } from '@deepseek-ai/cordis'
8
+ import type { Entry } from '@deepseek-ai/cordis-plugin-loader'
9
+ import { tearDownEntryFiber } from '@deepseek-ai/dsh-client-modules/client'
10
+ import {
11
+ installConnection,
12
+ type ConnectionHandle,
13
+ } from '@deepseek-ai/dsh-client-connection/client'
14
+ import { assertEntriesActive, bootClient } from '@deepseek-ai/dsh-client-web/src/boot-client.ts'
15
+ import { mountClient } from '@deepseek-ai/dsh-client-web/src/mount.ts'
16
+ import type { RemoteMock } from '@deepseek-ai/dsh-remote-mock'
17
+ import { act } from '@testing-library/react'
18
+ import { createInProcessModules, loadPluginModules } from './modules.ts'
19
+ import { assertPlan, graphFromRoster, type AssemblyPlan } from './roster.ts'
20
+ import { REMOTES_PACKAGE, remoteNamespacesOf, remoteProxiesPlugin } from './remote-proxies.ts'
21
+ import { allowAllAccessPlugin, staticAccessPlugin } from '../access.ts'
22
+
23
+ /** The remote-access row: it mounts its own generated Remote contribution and publishes the access Hooks. */
24
+ const REMOTE_ACCESS_PACKAGE = '@deepseek-ai/dsh-api-remote-access'
25
+
26
+ /**
27
+ * Rows whose generated Remote contributions exist only in built `lib/`. The
28
+ * tier drops them: `remote.<ns>` proxies stand in for the namespaces and
29
+ * allow-all access Hooks stand in for remote-access.
30
+ */
31
+ const GENERATED_REMOTE_PACKAGES: readonly string[] = [REMOTES_PACKAGE, REMOTE_ACCESS_PACKAGE]
32
+
33
+ /** Carrier options. */
34
+ export interface TestClientOptions {
35
+ /**
36
+ * Mount `uiRenderer` into an element (a fresh `document.body` child when `true`); requires jsdom and a roster
37
+ * that provides `uiRenderer`. Default false.
38
+ */
39
+ readonly mount?: boolean | HTMLElement
40
+ /** Wait for `ctx.connection.state === 'connected'` before returning. Default true. */
41
+ readonly awaitConnected?: boolean
42
+ /** Readiness budget in milliseconds before `start` rejects with the mock log summary. Default 5000. */
43
+ readonly connectTimeoutMs?: number
44
+ /** The fixed access answer for each action on every resource. Default: every action is allowed. */
45
+ readonly access?: (action: string) => boolean
46
+ /**
47
+ * Tolerate inactive roster entries outside the Web client's required list, as the product boot does. Default
48
+ * false: every roster entry must activate, so a plugin that fails to import or activate, or waits on a missing
49
+ * service, rejects `start` with its audit reason.
50
+ */
51
+ readonly allowInactiveEntries?: boolean
52
+ }
53
+
54
+ /**
55
+ * jsdom shims shared by every live client in this worker. The first holder
56
+ * installs missing shims and the last release removes exactly those shims.
57
+ */
58
+ class SharedJsdomShims {
59
+ private holders = 0
60
+ private removeShims: (() => void) | undefined
61
+
62
+ /**
63
+ * Hold the shims for one client.
64
+ * @returns the release for this holder.
65
+ */
66
+ acquire(): () => void {
67
+ if (this.holders === 0) {
68
+ this.removeShims = installJsdomShims()
69
+ }
70
+ this.holders += 1
71
+ return () => {
72
+ this.holders -= 1
73
+ if (this.holders > 0) return
74
+ this.removeShims?.()
75
+ this.removeShims = undefined
76
+ }
77
+ }
78
+ }
79
+
80
+ const sharedJsdomShims = new SharedJsdomShims()
81
+
82
+ const CONNECTION_PACKAGE = '@deepseek-ai/dsh-client-connection'
83
+
84
+ /** Default readiness budget; the mock answers `$events` immediately, so a miss means a boot-time fixture is absent. */
85
+ const DEFAULT_CONNECT_TIMEOUT_MS = 5_000
86
+
87
+ /**
88
+ * Browser globals jsdom lacks that roster plugins touch at apply or mount:
89
+ * client-hmr opens an `EventSource`; layout components observe size, media queries, and font loading.
90
+ * Inert stand-ins, installed only where the global is absent.
91
+ */
92
+ const JSDOM_SHIMS: Readonly<Record<string, unknown>> = {
93
+ matchMedia: (media: string): MediaQueryList => Object.assign(new EventTarget(), {
94
+ media, matches: false, onchange: null,
95
+ addListener() {},
96
+ removeListener() {},
97
+ }),
98
+ EventSource: class {
99
+ addEventListener(): void {}
100
+ close(): void {}
101
+ },
102
+ ResizeObserver: class {
103
+ observe(): void {}
104
+ disconnect(): void {}
105
+ },
106
+ }
107
+
108
+ /** Install a shim for each absent global; the disposer deletes exactly those. */
109
+ function installJsdomShims(): () => void {
110
+ const globals = globalThis as Record<string, unknown>
111
+ const installed = Object.keys(JSDOM_SHIMS).filter(name => globals[name] === undefined)
112
+ for (const name of installed) globals[name] = JSDOM_SHIMS[name]
113
+ const fontDocument: { readonly fonts?: EventTarget } | undefined =
114
+ typeof document === 'undefined' ? undefined : document
115
+ const shimFonts = fontDocument !== undefined && fontDocument.fonts === undefined
116
+ const fontsDescriptor = fontDocument === undefined ? undefined : Object.getOwnPropertyDescriptor(fontDocument, 'fonts')
117
+ if (shimFonts) Object.defineProperty(fontDocument, 'fonts', { configurable: true, value: new EventTarget() })
118
+ return () => {
119
+ for (const name of installed) Reflect.deleteProperty(globals, name)
120
+ if (shimFonts) {
121
+ if (fontsDescriptor === undefined) Reflect.deleteProperty(fontDocument, 'fonts')
122
+ else Object.defineProperty(fontDocument, 'fonts', fontsDescriptor)
123
+ }
124
+ }
125
+ }
126
+
127
+ /** The Error a thrown value stands for: itself, or a new Error carrying its string form. */
128
+ function toError(error: unknown): Error {
129
+ return error instanceof Error ? error : new Error(String(error))
130
+ }
131
+
132
+ function messageOf(error: unknown): string {
133
+ return toError(error).message
134
+ }
135
+
136
+ function connectionOf(ctx: Context): ConnectionHandle {
137
+ const connection = ctx.get('connection') as ConnectionHandle | undefined
138
+ if (connection === undefined) {
139
+ throw new Error('client-test-runtime: the roster provides no `connection` service')
140
+ }
141
+ return connection
142
+ }
143
+
144
+ /** Mount point plus whether `start` created it (and so removes it on dispose). */
145
+ interface MountPoint {
146
+ readonly element: HTMLElement | undefined
147
+ readonly owned: boolean
148
+ }
149
+
150
+ function resolveMountPoint(mount: boolean | HTMLElement | undefined): MountPoint {
151
+ if (mount === undefined || mount === false) return { element: undefined, owned: false }
152
+ if (typeof document === 'undefined') {
153
+ throw new Error('client-test-runtime: mount requires a DOM; add `// @vitest-environment jsdom` to the spec')
154
+ }
155
+ if (mount === true) {
156
+ const element = document.createElement('div')
157
+ document.body.appendChild(element)
158
+ return { element, owned: true }
159
+ }
160
+ return { element: mount, owned: false }
161
+ }
162
+
163
+ /** Run `fn` inside React `act` when a DOM exists; plain await otherwise. */
164
+ async function settle(fn: () => Promise<void>): Promise<void> {
165
+ if (typeof document === 'undefined') {
166
+ await fn()
167
+ return
168
+ }
169
+ await act(async () => { await fn() })
170
+ }
171
+
172
+ async function awaitConnected(ctx: Context, mock: RemoteMock, timeoutMs: number): Promise<void> {
173
+ const { state } = connectionOf(ctx)
174
+ if (state.getSnapshot() === 'connected') return
175
+ await new Promise<void>((resolve, reject) => {
176
+ const timer = setTimeout(() => {
177
+ unsubscribe()
178
+ const unmatched = mock.log.unmatched().map(row => `${row.mode} ${row.endpoint}`)
179
+ const streams = mock.log.streams().map(row => `${row.endpoint} (${row.state})`)
180
+ reject(new Error(
181
+ `client-test-runtime: connection state is ${String(state.getSnapshot())} after ${timeoutMs}ms; `
182
+ + `unmatched: [${unmatched.join(', ')}]; streams: [${streams.join(', ')}]`,
183
+ ))
184
+ }, timeoutMs)
185
+ const unsubscribe = state.subscribe(() => {
186
+ if (state.getSnapshot() !== 'connected') return
187
+ clearTimeout(timer)
188
+ unsubscribe()
189
+ resolve()
190
+ })
191
+ })
192
+ }
193
+
194
+ /** A booted client under test. */
195
+ export class TestClient {
196
+ /**
197
+ * Load the roster's modules, bind this client's mock to its Connection row,
198
+ * hold the jsdom shims, and boot through `bootClient` over the synthesized
199
+ * boot graph; afterwards optionally mount and wait for the connection. The
200
+ * bound row replaces only the page-global input adapter: both paths call
201
+ * `installConnection`, while this path supplies the mock carrier, uses
202
+ * default recovery timings, and captures the current page hostname once for
203
+ * later reloads. A caller-provided Connection row remains unchanged and owns
204
+ * its readiness behavior. The `@deepseek-ai/dsh-api-remotes` row is
205
+ * dropped from the roster: its generated Remote clients exist only in built
206
+ * `lib/`, and the `remote.<ns>` services the roster injects (plus the
207
+ * namespaces the mock has rules for at this point) are provided as
208
+ * contract-free proxies over the same Connection instead. The
209
+ * `@deepseek-ai/dsh-api-remote-access` row, which mounts its own generated
210
+ * contribution, is dropped too, and allow-all access Hooks replace it. A
211
+ * `provide` entry for either row is refused. Unless `allowInactiveEntries` is set, every roster entry must
212
+ * activate, stricter than the product boot, which only warns about entries outside its required list. On any
213
+ * failure the context is disposed, an owned
214
+ * mount removed, and this client's hold on the shims released before the
215
+ * original error is rethrown.
216
+ * @param plan - roster and annotations.
217
+ * @param mock - Remote mock answering every Gateway call.
218
+ * @param options - mount, readiness, and strictness options.
219
+ * @returns the booted client.
220
+ */
221
+ static async start(
222
+ plan: AssemblyPlan,
223
+ mock: RemoteMock,
224
+ options: TestClientOptions = {},
225
+ ): Promise<TestClient> {
226
+ assertPlan(plan)
227
+ for (const name of GENERATED_REMOTE_PACKAGES) {
228
+ if (plan.provide?.[name] !== undefined) {
229
+ throw new Error(`client-test-runtime: ${name} cannot be provided; the tier replaces its generated Remote mount`)
230
+ }
231
+ }
232
+ const generated = GENERATED_REMOTE_PACKAGES.filter(name => plan.roster.rows.some(row => row.name === name))
233
+ const roster = generated.length > 0 ? plan.roster.without(generated) : plan.roster
234
+ const ctx = new Context()
235
+ const pageLocation = typeof location === 'undefined'
236
+ ? undefined
237
+ : { hostname: location.hostname }
238
+ let mountPoint: MountPoint = { element: undefined, owned: false }
239
+ let release: (() => void) | undefined
240
+ const restore = (): void => {
241
+ if (mountPoint.owned) mountPoint.element?.remove()
242
+ release?.()
243
+ }
244
+ try {
245
+ const modules = new Map(await loadPluginModules({ ...plan, roster }))
246
+ const connection = modules.get(CONNECTION_PACKAGE)
247
+ if (connection !== undefined && plan.provide?.[CONNECTION_PACKAGE] === undefined) {
248
+ modules.set(CONNECTION_PACKAGE, {
249
+ ...connection,
250
+ apply: (connectionCtx) => {
251
+ installConnection(connectionCtx, {
252
+ interactions: 'answer',
253
+ transport: { rpc: mock.rpc },
254
+ ...(pageLocation === undefined ? {} : { location: pageLocation }),
255
+ })
256
+ },
257
+ })
258
+ }
259
+ mountPoint = resolveMountPoint(options.mount)
260
+ release = sharedJsdomShims.acquire()
261
+ const system = createInProcessModules(graphFromRoster(roster.rows), modules)
262
+ ctx.plugin(remoteProxiesPlugin(remoteNamespacesOf(modules.values(), mock), mock) as Plugin)
263
+ // The dropped remote-access row's Hooks: every action is allowed on every resource unless the spec fixes the answers.
264
+ if (generated.includes(REMOTE_ACCESS_PACKAGE)) {
265
+ ctx.plugin(options.access === undefined ? allowAllAccessPlugin : staticAccessPlugin(options.access))
266
+ }
267
+ await bootClient({ ctx, modules: system, manifest: system.manifest })
268
+ if (options.allowInactiveEntries !== true) {
269
+ await assertEntriesActive(ctx, system, (report) => {
270
+ throw new Error(`client-test-runtime: every roster entry must activate; pass allowInactiveEntries to tolerate it\n${report}`)
271
+ })
272
+ }
273
+ if (mountPoint.element !== undefined) {
274
+ if (ctx.get('uiRenderer') === undefined) {
275
+ throw new Error('client-test-runtime: mount requested, but the roster provides no `uiRenderer`')
276
+ }
277
+ await mountClient(ctx, mountPoint.element)
278
+ }
279
+ if (options.awaitConnected !== false) {
280
+ await awaitConnected(ctx, mock, options.connectTimeoutMs ?? DEFAULT_CONNECT_TIMEOUT_MS)
281
+ }
282
+ } catch (error) {
283
+ try {
284
+ await settle(() => ctx.fiber.dispose())
285
+ } catch {
286
+ // The boot failure is the error to report; a half-built tree failing to dispose adds nothing to it.
287
+ } finally {
288
+ restore()
289
+ }
290
+ throw error
291
+ }
292
+ return new TestClient(ctx, mock, mountPoint.element, restore)
293
+ }
294
+
295
+ private disposing: Promise<void> | undefined
296
+
297
+ private constructor(
298
+ readonly ctx: Context,
299
+ readonly mock: RemoteMock,
300
+ readonly container: HTMLElement | undefined,
301
+ private readonly restore: () => void,
302
+ ) {}
303
+
304
+ /** The roster's Connection service (no `Context` augmentation declares it); throws when the roster provides none. */
305
+ get connection(): ConnectionHandle {
306
+ return connectionOf(this.ctx)
307
+ }
308
+
309
+ /** Flush pending React work and microtasks inside `act` (plain microtask flush without a DOM). */
310
+ async flush(): Promise<void> {
311
+ await settle(() => Promise.resolve())
312
+ }
313
+
314
+ /**
315
+ * Rebuild one Loader entry: Client Modules' registry-first fiber teardown, then
316
+ * `entry.refresh()`. Each client's module table retains its own instance-bound
317
+ * Connection plugin, so reloads do not coordinate through process globals.
318
+ * Requires a live client: after `dispose()` the Loader holds no entries and
319
+ * the lookup throws before teardown.
320
+ * @param name - package name of the row.
321
+ */
322
+ async reload(name: string): Promise<void> {
323
+ const entry = this.entryOf(name)
324
+ await tearDownEntryFiber(entry)
325
+ await entry.refresh()
326
+ await this.ctx.loader.await()
327
+ }
328
+
329
+ /**
330
+ * Remove one Loader entry and wait for its plugin cleanup.
331
+ * @param name - package name of the row.
332
+ */
333
+ async unload(name: string): Promise<void> {
334
+ const entry = this.entryOf(name)
335
+ const disposal = entry.fiber?.dispose()
336
+ this.ctx.loader.remove(entry.id)
337
+ await disposal
338
+ }
339
+
340
+ /**
341
+ * Dispose the plugin tree, then drop an owned mount and release this
342
+ * client's hold on the shared jsdom shims even when the tree fails to dispose,
343
+ * then `mock.assertNoUnmatched()` last so its failure is the test's reason
344
+ * without skipping the cleanup; when both the tree and the check fail, one
345
+ * error carries both messages. The first call owns the teardown and reports
346
+ * its failure; every later call waits for that teardown and resolves.
347
+ */
348
+ async dispose(): Promise<void> {
349
+ if (this.disposing !== undefined) {
350
+ await this.disposing.catch(() => undefined)
351
+ return
352
+ }
353
+ this.disposing = this.teardown()
354
+ await this.disposing
355
+ }
356
+
357
+ private async teardown(): Promise<void> {
358
+ let failure: Error | undefined
359
+ try {
360
+ await settle(() => this.ctx.fiber.dispose())
361
+ } catch (error) {
362
+ failure = toError(error)
363
+ } finally {
364
+ this.restore()
365
+ }
366
+ if (failure === undefined) {
367
+ this.mock.assertNoUnmatched()
368
+ return
369
+ }
370
+ try {
371
+ this.mock.assertNoUnmatched()
372
+ } catch (unmatched) {
373
+ throw new Error(`${messageOf(unmatched)}\nclient-test-runtime: the plugin tree also failed to dispose: ${failure.message}`, { cause: failure })
374
+ }
375
+ throw failure
376
+ }
377
+
378
+ private entryOf(name: string): Entry {
379
+ const entries = [...this.ctx.loader.entries()]
380
+ const entry = entries.find(candidate => candidate.options.name === name)
381
+ if (entry === undefined) {
382
+ throw new Error(
383
+ `client-test-runtime: no Loader entry named ${name}; entries: ${entries.map(row => row.options.name).join(', ')}`,
384
+ )
385
+ }
386
+ return entry
387
+ }
388
+ }
@@ -0,0 +1,60 @@
1
+ /** Test-scoped Remote mock and lazy client boot, owned by native Vitest fixtures. */
2
+ import { test, type TestAPI } from 'vitest'
3
+ import { RemoteMock, type MockedRemote } from '@deepseek-ai/dsh-remote-mock'
4
+ import type { AssemblyPlan } from './roster.ts'
5
+ import { remoteDefaultResponses } from './remote-default-responses.ts'
6
+ import { TestClient, type TestClientOptions } from './test-client.ts'
7
+
8
+ /** Per-test controls; configure the mock before awaiting `start()`. */
9
+ export interface ClientTestFixtures {
10
+ /** Fresh mock with the assembly's default responses already loaded. */
11
+ mock: RemoteMock
12
+ /** Namespace proxy backed by the same native mocks used by the Connection carrier. */
13
+ remote: MockedRemote
14
+ /** Await the one client owned by this test; rejects after the fixture closes. */
15
+ start: () => Promise<TestClient>
16
+ }
17
+
18
+ /**
19
+ * Extend Vitest with a fresh mock and a lazy, automatically disposed client. Repeated `start()` calls share one
20
+ * promise. Await it to observe startup failures; cleanup waits for startup but does not rethrow its rejection.
21
+ * Missing mock responses still fail teardown even when no client was started. Page globals remain environment-owned.
22
+ * @param plan - roster and replacement modules, shared as configuration rather than as a running client.
23
+ * @param options - mount, readiness, and strictness settings passed to `TestClient.start`.
24
+ * @returns Vitest's test function with test-scoped `mock` and `start` fixtures.
25
+ */
26
+ export function createClientTest(plan: AssemblyPlan, options: TestClientOptions = {}): TestAPI<ClientTestFixtures> {
27
+ return test.extend<ClientTestFixtures>({
28
+ remote: async ({ mock }, use) => {
29
+ await use(mock.remote)
30
+ },
31
+ mock: async ({}, use) => {
32
+ const mock = RemoteMock.create().load(remoteDefaultResponses)
33
+ try {
34
+ await use(mock)
35
+ } finally {
36
+ mock.assertNoUnmatched()
37
+ }
38
+ },
39
+ start: async ({ mock }, use) => {
40
+ let pending: Promise<TestClient> | undefined
41
+ let closed = false
42
+ const start = (): Promise<TestClient> => {
43
+ if (closed) return Promise.reject(new Error('client-test-runtime: start() called after its test fixture closed'))
44
+ if (pending === undefined) {
45
+ pending = TestClient.start(plan, mock, options)
46
+ // Startup belongs to the caller; keep a rejection handler attached until teardown can await it.
47
+ void pending.catch(() => undefined)
48
+ }
49
+ return pending
50
+ }
51
+ try {
52
+ await use(start)
53
+ } finally {
54
+ closed = true
55
+ const client = await pending?.catch(() => undefined)
56
+ await client?.dispose()
57
+ }
58
+ },
59
+ })
60
+ }
@@ -0,0 +1,61 @@
1
+ /** Test doubles for settings transport. */
2
+ import { vi } from 'vitest'
3
+ import type {
4
+ ConfigForm, ConfigFormSnapshot,
5
+ } from '@deepseek-ai/dsh-client-ui-settings/client'
6
+
7
+ /** Handle over one stubbed scope: the scope, its write spy, and publication controls. */
8
+ export interface StubConfigForm<T> {
9
+ /** The scope face handed to the service under test. */
10
+ scope: ConfigForm<T>
11
+ /** Spy behind `scope.set`; resolves immediately. */
12
+ set: ReturnType<typeof vi.fn>
13
+ /** Spy behind `scope.mutate`; resolves immediately. */
14
+ mutate: ReturnType<typeof vi.fn<ConfigForm<T>['mutate']>>
15
+ /** Spy behind `scope.unset`; resolves immediately. */
16
+ unset: ReturnType<typeof vi.fn>
17
+ /** @returns how many listeners are currently subscribed (disposal assertions). */
18
+ listenerCount(): number
19
+ /**
20
+ * Replace part of the snapshot and notify subscribers, as a Host
21
+ * acceptance would.
22
+ * @param next - snapshot fields to replace.
23
+ */
24
+ publish(next: Partial<ConfigFormSnapshot<T>>): void
25
+ }
26
+
27
+ /**
28
+ * Build an in-memory settings scope for service specs: starts in the loading
29
+ * state, records writes, and lets the test publish Host acceptances.
30
+ * @returns the stub handle.
31
+ */
32
+ export function stubConfigForm<T>(): StubConfigForm<T> {
33
+ let snapshot: ConfigFormSnapshot<T> = {
34
+ status: 'loading', value: undefined, base: undefined, user: undefined,
35
+ revision: undefined, writable: false,
36
+ }
37
+ const listeners = new Set<() => void>()
38
+ const set = vi.fn(() => Promise.resolve(true))
39
+ const mutate = vi.fn<ConfigForm<T>['mutate']>(() => Promise.resolve(true))
40
+ const unset = vi.fn(() => Promise.resolve(true))
41
+ return {
42
+ scope: {
43
+ getSnapshot: () => snapshot,
44
+ subscribe: (listener) => {
45
+ listeners.add(listener)
46
+ return () => { listeners.delete(listener) }
47
+ },
48
+ mutate,
49
+ set,
50
+ unset,
51
+ },
52
+ set,
53
+ mutate,
54
+ unset,
55
+ listenerCount: () => listeners.size,
56
+ publish: (next) => {
57
+ snapshot = { ...snapshot, ...next }
58
+ for (const listener of [...listeners]) listener()
59
+ },
60
+ }
61
+ }
@@ -0,0 +1,17 @@
1
+ /** Gesture bindings for direct component fixtures, using the production adapter. */
2
+ import type { ContextMenuTriggerProps, MenuPoint, ContextMenuTarget } from '@deepseek-ai/dsh-client-ui-context-menu/client'
3
+ import { createContextMenuBindings } from '@deepseek-ai/dsh-client-ui-context-menu/src/client/trigger.ts'
4
+
5
+ /**
6
+ * Supply the global hook to a component mounted outside the Slot renderer.
7
+ * @param open - Observe captured targets; an unstubbed activation throws.
8
+ * @returns Stable hook using the production pointer and keyboard handlers.
9
+ */
10
+ export function contextMenuHook<Target extends object = ContextMenuTarget>(
11
+ open: (target: Target, point: MenuPoint) => void = () => { throw new Error('Unexpected context menu') },
12
+ ): () => {
13
+ getTriggerProps: (target: Target | (() => Target) | undefined, handlers?: ContextMenuTriggerProps) => ContextMenuTriggerProps
14
+ } {
15
+ const bindings = createContextMenuBindings(open, () => true)
16
+ return () => bindings
17
+ }