ngx-json-render 0.4.0 → 0.5.0

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.
package/README.md CHANGED
@@ -473,6 +473,40 @@ the harness: `text` / `texts` / `find` / `findAll` for the DOM, `click` /
473
473
  Options mirror the renderer's inputs, plus `providers` for anything the
474
474
  components under test inject.
475
475
 
476
+ ### Mounting one component
477
+
478
+ `renderComponent` mounts a catalog component with no renderer and no spec. You
479
+ give it props and read back what it emitted and what it wrote to bound props.
480
+ It tests the component as a presentational one — what it draws, and what it
481
+ says when used — and leaves what the spec does with that to `renderSpec`:
482
+
483
+ ```ts
484
+ import { renderComponent } from 'ngx-json-render/testing';
485
+
486
+ it('emits press, and stays quiet once disabled', async () => {
487
+ const button = await renderComponent(MyButton, { props: { label: 'Save' } });
488
+
489
+ expect(button.text('button')).toBe('Save');
490
+ await button.click('button');
491
+ expect(button.emitted).toEqual(['press']);
492
+
493
+ await button.patchProps({ disabled: true });
494
+ expect(button.find<HTMLButtonElement>('button').disabled).toBe(true);
495
+ });
496
+ ```
497
+
498
+ `bindings` says which props are two-way bound (`{ checked: '/dark' }`): a
499
+ `setBound` on one of them is recorded in `writes` and lands back in the props,
500
+ and on any other prop it is the same no-op it is under the renderer. `on` lists
501
+ the events the spec would bind, for components that read `ctx.on(event).bound`;
502
+ `key`, `type` and `loading` fill in the rest of the context, and `setProps` /
503
+ `patchProps` / `setLoading` change it between frames. The DOM helpers are the
504
+ same as `renderSpec`'s.
505
+
506
+ A component that renders `<jr-children>`, registers field validation or
507
+ dispatches actions itself needs the renderer's own services, and there is no
508
+ honest fake for a subtree — it fails with a message pointing at `renderSpec`.
509
+
476
510
  ### Replaying a generation
477
511
 
478
512
  `recordedTransport` is a `fetch` that answers from a recording, so a test runs
@@ -731,7 +765,7 @@ is how you tell the two apart.
731
765
 
732
766
  Registry & schema: `defineRegistry`, `createStoreSetState`, `schema`.
733
767
 
734
- Testing (`ngx-json-render/testing`): `renderSpec`, `recordedTransport`, `specStream`, `usageLine`.
768
+ Testing (`ngx-json-render/testing`): `renderSpec`, `renderComponent`, `recordedTransport`, `specStream`, `usageLine`.
735
769
 
736
770
  Everything from `@json-render/core` (types, `createStateStore`, `nestedToFlat`, prompt builders, spec validators, SpecStream compiler) composes with this package; the most common symbols are re-exported.
737
771
 
@@ -1,7 +1,8 @@
1
+ import { NgComponentOutlet } from '@angular/common';
1
2
  import * as i0 from '@angular/core';
2
- import { signal, ChangeDetectionStrategy, Component, provideZonelessChangeDetection } from '@angular/core';
3
+ import { provideZonelessChangeDetection, inject, Injector, signal, ChangeDetectionStrategy, Component, computed, isDevMode } from '@angular/core';
3
4
  import { TestBed } from '@angular/core/testing';
4
- import { JsonRenderer, JsonRenderValidationService } from 'ngx-json-render';
5
+ import { RENDER_CONTEXT, ELEMENT_KEY, JsonRenderer, JsonRenderValidationService } from 'ngx-json-render';
5
6
 
6
7
  /** The rejection `fetch` raises when its signal fires. */
7
8
  function abortError() {
@@ -163,6 +164,230 @@ function usageLine(usage) {
163
164
  });
164
165
  }
165
166
 
167
+ /**
168
+ * What `renderSpec` and `renderComponent` share: the TestBed setup, the settle
169
+ * loop, and the handful of DOM queries a test runs against what rendered.
170
+ *
171
+ * @internal Not exported from the entry point.
172
+ */
173
+ /**
174
+ * Configure the TestBed, unless the test already did.
175
+ *
176
+ * A test that called `TestBed.runInInjectionContext` first — or that renders
177
+ * a second time — has an instantiated module, and configuring it again
178
+ * throws. Its own module stands; the only thing that cannot be salvaged is
179
+ * this call's `providers`, so that is the one case worth failing over.
180
+ */
181
+ function configureTestBed(caller, providers) {
182
+ try {
183
+ TestBed.configureTestingModule({
184
+ providers: [provideZonelessChangeDetection(), ...providers],
185
+ });
186
+ }
187
+ catch {
188
+ if (providers.length > 0) {
189
+ throw new Error(`${caller}: the TestBed was already instantiated, so \`providers\` cannot be applied. Pass them to your own TestBed.configureTestingModule() call instead.`);
190
+ }
191
+ }
192
+ }
193
+ /** Let effects, promises and change detection finish. */
194
+ function settler(fixture) {
195
+ return async () => {
196
+ // Twice: the first pass runs the effects that a render schedules, the
197
+ // second renders what those effects changed. One pass leaves a test
198
+ // asserting against a frame that no browser would ever show.
199
+ await fixture.whenStable();
200
+ fixture.detectChanges();
201
+ await fixture.whenStable();
202
+ };
203
+ }
204
+ function domQueries(caller, element, settle) {
205
+ const resolve = (target) => {
206
+ if (typeof target !== 'string')
207
+ return target;
208
+ const found = element.querySelector(target);
209
+ if (!found) {
210
+ throw new Error(`${caller}: nothing matches ${JSON.stringify(target)}. Rendered HTML:\n${element.innerHTML}`);
211
+ }
212
+ return found;
213
+ };
214
+ return {
215
+ text: (selector) => ((selector ? resolve(selector) : element).textContent ?? '').trim(),
216
+ texts: (selector) => Array.from(element.querySelectorAll(selector)).map((el) => (el.textContent ?? '').trim()),
217
+ find: (selector) => resolve(selector),
218
+ findAll: (selector) => Array.from(element.querySelectorAll(selector)),
219
+ async click(target) {
220
+ resolve(target).click();
221
+ await settle();
222
+ },
223
+ async fill(target, value) {
224
+ const input = resolve(target);
225
+ input.value = value;
226
+ input.dispatchEvent(new Event('input', { bubbles: true }));
227
+ await settle();
228
+ },
229
+ };
230
+ }
231
+
232
+ /**
233
+ * Mounted through `NgComponentOutlet` with an element injector, the way
234
+ * `<jr-element>` mounts a catalog component — so the context is the
235
+ * component's own, not the TestBed module's, and a test can mount twice.
236
+ */
237
+ class JrComponentTestHost {
238
+ parent = inject(Injector);
239
+ component = signal(null, ...(ngDevMode ? [{ debugName: "component" }] : /* istanbul ignore next */ []));
240
+ injector = signal(this.parent, ...(ngDevMode ? [{ debugName: "injector" }] : /* istanbul ignore next */ []));
241
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.22", ngImport: i0, type: JrComponentTestHost, deps: [], target: i0.ɵɵFactoryTarget.Component });
242
+ static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "21.2.22", type: JrComponentTestHost, isStandalone: true, selector: "jr-component-test-host", ngImport: i0, template: `
243
+ @if (component(); as type) {
244
+ <ng-container *ngComponentOutlet="type; injector: injector()" />
245
+ }
246
+ `, isInline: true, dependencies: [{ kind: "directive", type: NgComponentOutlet, selector: "[ngComponentOutlet]", inputs: ["ngComponentOutlet", "ngComponentOutletInputs", "ngComponentOutletInjector", "ngComponentOutletEnvironmentInjector", "ngComponentOutletContent", "ngComponentOutletNgModule"], exportAs: ["ngComponentOutlet"] }], changeDetection: i0.ChangeDetectionStrategy.OnPush });
247
+ }
248
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.22", ngImport: i0, type: JrComponentTestHost, decorators: [{
249
+ type: Component,
250
+ args: [{
251
+ selector: 'jr-component-test-host',
252
+ changeDetection: ChangeDetectionStrategy.OnPush,
253
+ imports: [NgComponentOutlet],
254
+ template: `
255
+ @if (component(); as type) {
256
+ <ng-container *ngComponentOutlet="type; injector: injector()" />
257
+ }
258
+ `,
259
+ }]
260
+ }] });
261
+ /** The renderer-owned services a component can only have from a renderer. */
262
+ const RENDERER_ONLY = /JsonRender(RootContext|StateService|ValidationService|ActionsService)/;
263
+ /**
264
+ * Turn "no provider for the renderer's services" into what to do about it.
265
+ * `<jr-children>`, `injectFieldValidation` and `injectActions` all need a
266
+ * real renderer behind them; there is no honest fake for a subtree.
267
+ */
268
+ function explainMissingRenderer(error) {
269
+ const message = error instanceof Error ? error.message : String(error);
270
+ if (RENDERER_ONLY.test(message)) {
271
+ throw new Error(`renderComponent: this component needs a real <json-render> — it renders <jr-children>, validates a field or dispatches actions itself. Test it with renderSpec instead.\n\n${message}`);
272
+ }
273
+ throw error;
274
+ }
275
+ /**
276
+ * Mount a catalog component with no renderer and no spec: hand it props, and
277
+ * read back the events it emitted and the values it wrote to bound props.
278
+ *
279
+ * This is the test of a component as a presentational one — what it draws
280
+ * for these props, and what it says when used. What the spec then does with
281
+ * that is the renderer's business, and `renderSpec` is where to test it.
282
+ *
283
+ * `props` is not inferred from the first value, so a later `patchProps` can
284
+ * set a prop the first render left out. Pass `P` to have the props typed.
285
+ *
286
+ * A component that renders `<jr-children>`, registers field validation or
287
+ * dispatches actions directly needs the renderer's services and fails with a
288
+ * message pointing at `renderSpec`.
289
+ *
290
+ * @example
291
+ * ```ts
292
+ * const button = await renderComponent(MyButton, { props: { label: 'Save' } });
293
+ *
294
+ * expect(button.text('button')).toBe('Save');
295
+ * await button.click('button');
296
+ * expect(button.emitted).toEqual(['press']);
297
+ *
298
+ * await button.patchProps({ disabled: true });
299
+ * expect(button.find<HTMLButtonElement>('button').disabled).toBe(true);
300
+ * ```
301
+ */
302
+ async function renderComponent(component, options = {}) {
303
+ const emitted = [];
304
+ const writes = [];
305
+ const props = signal(options.props ?? {}, ...(ngDevMode ? [{ debugName: "props" }] : /* istanbul ignore next */ []));
306
+ const loading = signal(options.loading ?? false, ...(ngDevMode ? [{ debugName: "loading" }] : /* istanbul ignore next */ []));
307
+ const bindings = options.bindings;
308
+ const boundEvents = new Set(options.on ?? []);
309
+ const key = signal(options.key ?? 'element', ...(ngDevMode ? [{ debugName: "key" }] : /* istanbul ignore next */ []));
310
+ const element = computed(() => ({
311
+ type: options.type ?? component.name,
312
+ props: props(),
313
+ children: [],
314
+ }), ...(ngDevMode ? [{ debugName: "element" }] : /* istanbul ignore next */ []));
315
+ const emit = (event) => {
316
+ emitted.push(event);
317
+ };
318
+ const context = {
319
+ element,
320
+ props: props.asReadonly(),
321
+ emit,
322
+ on: (event) => ({
323
+ emit: () => emit(event),
324
+ shouldPreventDefault: false,
325
+ bound: boundEvents.has(event),
326
+ }),
327
+ bindings: signal(bindings).asReadonly(),
328
+ loading: loading.asReadonly(),
329
+ setBound: (prop, value) => {
330
+ if (!bindings?.[prop]) {
331
+ if (isDevMode()) {
332
+ console.warn(`[ngx-json-render] setBound("${prop}"): prop has no $bindState/$bindItem binding`);
333
+ }
334
+ return;
335
+ }
336
+ writes.push({ prop, value });
337
+ // What the renderer's round trip amounts to: the write lands in state,
338
+ // and the bound prop resolves to it on the next read.
339
+ props.update((current) => ({ ...current, [prop]: value }));
340
+ },
341
+ };
342
+ configureTestBed('renderComponent', options.providers ?? []);
343
+ const fixture = TestBed.createComponent(JrComponentTestHost);
344
+ const host = fixture.componentInstance;
345
+ host.injector.set(Injector.create({
346
+ providers: [
347
+ { provide: RENDER_CONTEXT, useValue: context },
348
+ { provide: ELEMENT_KEY, useValue: key.asReadonly() },
349
+ ],
350
+ parent: host.parent,
351
+ }));
352
+ host.component.set(component);
353
+ const settle = settler(fixture);
354
+ try {
355
+ await settle();
356
+ }
357
+ catch (error) {
358
+ explainMissingRenderer(error);
359
+ }
360
+ const mounted = fixture.debugElement.query((candidate) => candidate.componentInstance instanceof component);
361
+ if (!mounted) {
362
+ throw new Error(`renderComponent: ${component.name} did not mount. Is it a component?`);
363
+ }
364
+ const root = fixture.nativeElement;
365
+ return {
366
+ fixture,
367
+ element: root,
368
+ component: mounted.componentInstance,
369
+ context,
370
+ emitted,
371
+ writes,
372
+ props: () => props(),
373
+ async setProps(next) {
374
+ props.set(next);
375
+ await settle();
376
+ },
377
+ async patchProps(patch) {
378
+ props.update((current) => ({ ...current, ...patch }));
379
+ await settle();
380
+ },
381
+ async setLoading(next) {
382
+ loading.set(next);
383
+ await settle();
384
+ },
385
+ settle,
386
+ ...domQueries('renderComponent', root, settle),
387
+ destroy: () => fixture.destroy(),
388
+ };
389
+ }
390
+
166
391
  class JrTestHost {
167
392
  spec = signal(null, ...(ngDevMode ? [{ debugName: "spec" }] : /* istanbul ignore next */ []));
168
393
  registry = signal({}, ...(ngDevMode ? [{ debugName: "registry" }] : /* istanbul ignore next */ []));
@@ -238,26 +463,6 @@ function recordingHandlers(handlers, dispatched) {
238
463
  }
239
464
  return wrapped;
240
465
  }
241
- /**
242
- * Configure the TestBed, unless the test already did.
243
- *
244
- * A test that called `TestBed.runInInjectionContext` first — or that renders
245
- * a second spec — has an instantiated module, and configuring it again
246
- * throws. Its own module stands; the only thing that cannot be salvaged is
247
- * this call's `providers`, so that is the one case worth failing over.
248
- */
249
- function configureTestBed(providers) {
250
- try {
251
- TestBed.configureTestingModule({
252
- providers: [provideZonelessChangeDetection(), ...providers],
253
- });
254
- }
255
- catch {
256
- if (providers.length > 0) {
257
- throw new Error('renderSpec: the TestBed was already instantiated, so `providers` cannot be applied. Pass them to your own TestBed.configureTestingModule() call instead.');
258
- }
259
- }
260
- }
261
466
  /**
262
467
  * Render a spec against a registry and hand back the few things a test does
263
468
  * to it.
@@ -287,7 +492,7 @@ function configureTestBed(providers) {
287
492
  async function renderSpec(spec, options) {
288
493
  const dispatched = [];
289
494
  const changes = [];
290
- configureTestBed(options.providers ?? []);
495
+ configureTestBed('renderSpec', options.providers ?? []);
291
496
  const fixture = TestBed.createComponent(JrTestHost);
292
497
  const host = fixture.componentInstance;
293
498
  host.registry.set(options.registry);
@@ -306,14 +511,7 @@ async function renderSpec(spec, options) {
306
511
  host.directives.set(options.directives);
307
512
  host.record = (batch) => changes.push(...batch);
308
513
  host.spec.set(spec);
309
- const settle = async () => {
310
- // Twice: the first pass runs the effects that a render schedules, the
311
- // second renders what those effects changed. One pass leaves a test
312
- // asserting against a frame that no browser would ever show.
313
- await fixture.whenStable();
314
- fixture.detectChanges();
315
- await fixture.whenStable();
316
- };
514
+ const settle = settler(fixture);
317
515
  await settle();
318
516
  const element = fixture.nativeElement;
319
517
  // Found by predicate rather than with `By.directive`, which would make
@@ -324,15 +522,6 @@ async function renderSpec(spec, options) {
324
522
  // From the renderer's own injector: these services are provided by the
325
523
  // component, so the root TestBed injector has never heard of them.
326
524
  const validation = rendererElement.injector.get(JsonRenderValidationService);
327
- const resolve = (target) => {
328
- if (typeof target !== 'string')
329
- return target;
330
- const found = element.querySelector(target);
331
- if (!found) {
332
- throw new Error(`renderSpec: nothing matches ${JSON.stringify(target)}. Rendered HTML:\n${element.innerHTML}`);
333
- }
334
- return found;
335
- };
336
525
  return {
337
526
  fixture,
338
527
  element,
@@ -356,20 +545,7 @@ async function renderSpec(spec, options) {
356
545
  await settle();
357
546
  },
358
547
  state: () => store.state(),
359
- text: (selector) => ((selector ? resolve(selector) : element).textContent ?? '').trim(),
360
- texts: (selector) => Array.from(element.querySelectorAll(selector)).map((el) => (el.textContent ?? '').trim()),
361
- find: (selector) => resolve(selector),
362
- findAll: (selector) => Array.from(element.querySelectorAll(selector)),
363
- async click(target) {
364
- resolve(target).click();
365
- await settle();
366
- },
367
- async fill(target, value) {
368
- const input = resolve(target);
369
- input.value = value;
370
- input.dispatchEvent(new Event('input', { bubbles: true }));
371
- await settle();
372
- },
548
+ ...domQueries('renderSpec', element, settle),
373
549
  destroy: () => fixture.destroy(),
374
550
  };
375
551
  }
@@ -385,5 +561,5 @@ async function renderSpec(spec, options) {
385
561
  * Generated bundle index. Do not edit.
386
562
  */
387
563
 
388
- export { recordedTransport, renderSpec, specStream, usageLine };
564
+ export { recordedTransport, renderComponent, renderSpec, specStream, usageLine };
389
565
  //# sourceMappingURL=ngx-json-render-testing.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"ngx-json-render-testing.mjs","sources":["../../../projects/ngx-json-render/testing/src/recorded-transport.ts","../../../projects/ngx-json-render/testing/src/render-spec.ts","../../../projects/ngx-json-render/testing/src/public-api.ts","../../../projects/ngx-json-render/testing/src/ngx-json-render-testing.ts"],"sourcesContent":["import type { Spec } from '@json-render/core';\n\n/**\n * The lines of one recorded response body, in the order the server sent them,\n * without their trailing newlines.\n */\nexport type Recording = readonly string[];\n\n/**\n * What to replay for a request. Either one recording for every request, a\n * lookup by prompt, or a function for anything more involved.\n */\nexport type Recordings =\n | Recording\n | Readonly<Record<string, Recording>>\n | ((\n prompt: string,\n body: Readonly<Record<string, unknown>>,\n ) => Recording | undefined);\n\n/** An error the recorded server answers with instead of a stream. */\nexport interface RecordedFailure {\n /** HTTP status. Defaults to 500. */\n status?: number;\n /** The `message` field of the JSON error body. */\n message?: string;\n}\n\n/** Options for {@link recordedTransport}. */\nexport interface RecordedTransportOptions {\n /**\n * Milliseconds between lines — the pace a model would emit them at.\n * Defaults to 0, which still yields to the event loop between lines, so a\n * test can observe the stream in flight.\n */\n delayMs?: number;\n /**\n * Answer with an error instead of a stream. A function is called per\n * request, so a test can turn the failure on and off between sends.\n */\n fail?: RecordedFailure | (() => RecordedFailure | null | undefined);\n /**\n * Pull the prompt out of the request body. The default reads `prompt`\n * (what `injectUIStream` sends) and falls back to the last message's\n * content (what `injectChatUI` sends).\n */\n promptOf?: (body: Readonly<Record<string, unknown>>) => string;\n}\n\n/** The rejection `fetch` raises when its signal fires. */\nfunction abortError(): Error {\n const error = new Error('The operation was aborted.');\n error.name = 'AbortError';\n return error;\n}\n\n/** A JSON error body, shaped the way the streaming hooks read it. */\nfunction errorResponse(status: number, message: string): Response {\n return new Response(JSON.stringify({ message }), {\n status,\n headers: { 'Content-Type': 'application/json' },\n });\n}\n\nfunction parseBody(body: BodyInit | null | undefined): Record<string, unknown> {\n try {\n const parsed: unknown = JSON.parse(String(body ?? '{}'));\n return parsed && typeof parsed === 'object'\n ? (parsed as Record<string, unknown>)\n : {};\n } catch {\n return {};\n }\n}\n\n/**\n * The prompt of a request, from either hook's body shape. Both are the\n * package's own, so the default knows them and a test does not have to.\n */\nfunction defaultPromptOf(body: Readonly<Record<string, unknown>>): string {\n const prompt = body['prompt'];\n if (typeof prompt === 'string') return prompt;\n\n const messages = body['messages'];\n if (!Array.isArray(messages) || messages.length === 0) return '';\n const last: unknown = messages[messages.length - 1];\n const content = (last as { content?: unknown } | null)?.content;\n return typeof content === 'string' ? content : '';\n}\n\nfunction toFinder(\n recordings: Recordings,\n): (prompt: string, body: Record<string, unknown>) => Recording | undefined {\n if (typeof recordings === 'function') return recordings;\n if (Array.isArray(recordings)) return () => recordings as Recording;\n const byPrompt = recordings as Readonly<Record<string, Recording>>;\n return (prompt) => byPrompt[prompt];\n}\n\nfunction replay(\n lines: Recording,\n delayMs: number,\n signal: AbortSignal | null,\n): ReadableStream<Uint8Array> {\n const encoder = new TextEncoder();\n return new ReadableStream<Uint8Array>({\n start(controller) {\n let index = 0;\n let timer: ReturnType<typeof setTimeout> | null = null;\n\n // A superseded or stopped generation has to die mid-flight the way a\n // real request does, or a test of that behaviour proves nothing.\n const onAbort = () => {\n if (timer) clearTimeout(timer);\n controller.error(abortError());\n };\n signal?.addEventListener('abort', onAbort, { once: true });\n\n const push = () => {\n if (index >= lines.length) {\n signal?.removeEventListener('abort', onAbort);\n controller.close();\n return;\n }\n controller.enqueue(encoder.encode(`${lines[index++]}\\n`));\n timer = setTimeout(push, delayMs);\n };\n timer = setTimeout(push, delayMs);\n },\n });\n}\n\n/**\n * A `fetch` that answers the streaming hooks from a recording instead of a\n * server.\n *\n * Both {@link injectUIStream} and {@link injectChatUI} take any function with\n * fetch's shape, so a test runs the real client — request body, streamed\n * lines, usage metadata, abort on supersede — with no server, no API key and\n * no global patched behind the test's back. Only the transport is recorded.\n *\n * @example\n * ```ts\n * const ui = injectUIStream({\n * api: '/api/generate',\n * fetch: recordedTransport(specStream(spec)),\n * });\n * ```\n *\n * @example Different answers per prompt, at a visible pace:\n * ```ts\n * recordedTransport(\n * { 'a dashboard': specStream(dashboard), 'a form': specStream(form) },\n * { delayMs: 20 },\n * );\n * ```\n */\nexport function recordedTransport(\n recordings: Recordings,\n options: RecordedTransportOptions = {},\n): typeof globalThis.fetch {\n const { delayMs = 0, promptOf = defaultPromptOf } = options;\n const find = toFinder(recordings);\n\n return async (_input, init) => {\n const failure =\n typeof options.fail === 'function' ? options.fail() : options.fail;\n if (failure) {\n return errorResponse(\n failure.status ?? 500,\n failure.message ?? 'The recorded server failed this request.',\n );\n }\n\n const body = parseBody(init?.body);\n const prompt = promptOf(body);\n const lines = find(prompt, body);\n if (!lines) {\n return errorResponse(404, `No recording for ${JSON.stringify(prompt)}.`);\n }\n\n const signal = init?.signal ?? null;\n if (signal?.aborted) throw abortError();\n\n return new Response(replay(lines, delayMs, signal), { status: 200 });\n };\n}\n\n/** Escape a JSON Pointer segment (RFC 6901). */\nfunction pointer(segment: string): string {\n return segment.replace(/~/g, '~0').replace(/\\//g, '~1');\n}\n\n/**\n * The JSONL patch lines a model would emit to build `spec`: the root, then\n * the state, then one line per element in declaration order.\n *\n * Recording a stream by hand means writing patches by hand; this writes them\n * from the spec a test already has, so the test says what it renders rather\n * than how the wire spells it.\n */\nexport function specStream(spec: Spec): string[] {\n const lines = [\n JSON.stringify({ op: 'add', path: '/root', value: spec.root }),\n ];\n if (spec.state) {\n lines.push(\n JSON.stringify({ op: 'add', path: '/state', value: spec.state }),\n );\n }\n for (const [key, element] of Object.entries(spec.elements ?? {})) {\n lines.push(\n JSON.stringify({\n op: 'add',\n path: `/elements/${pointer(key)}`,\n value: element,\n }),\n );\n }\n return lines;\n}\n\n/**\n * The usage metadata line `injectUIStream` reads into its `usage` signal.\n * Append it to a recording to exercise that path.\n */\nexport function usageLine(usage: {\n promptTokens?: number;\n completionTokens?: number;\n totalTokens?: number;\n}): string {\n return JSON.stringify({\n __meta: 'usage',\n promptTokens: usage.promptTokens ?? 0,\n completionTokens: usage.completionTokens ?? 0,\n totalTokens: usage.totalTokens ?? 0,\n });\n}\n","import {\n ChangeDetectionStrategy,\n Component,\n type Provider,\n type Type,\n provideZonelessChangeDetection,\n signal,\n} from '@angular/core';\nimport { type ComponentFixture, TestBed } from '@angular/core/testing';\nimport type {\n ActionHandler,\n ComputedFunction,\n DirectiveDefinition,\n Spec,\n StateStore,\n ValidationFunction,\n} from '@json-render/core';\nimport {\n type ComponentRegistry,\n JsonRenderStateService,\n JsonRenderValidationService,\n JsonRenderer,\n type RegistryEntry,\n type StateChange,\n type StateModel,\n} from 'ngx-json-render';\n\n/** One action the spec asked for, in the order it was dispatched. */\nexport interface DispatchedAction {\n name: string;\n params?: Record<string, unknown>;\n}\n\n/** Options for {@link renderSpec}. Everything but `registry` is optional. */\nexport interface RenderSpecOptions {\n /** Catalog type name → Angular component. The one required option. */\n registry: ComponentRegistry;\n /** Initial state model. Defaults to the spec's own `state`. */\n state?: StateModel;\n /** External store, for controlled mode. */\n store?: StateStore | null;\n /** Action handlers by name. Dispatches are recorded either way. */\n handlers?: Record<string, ActionHandler>;\n /** Catch-all handler for actions with no dedicated handler. */\n onAction?: (name: string, params?: Record<string, unknown>) => unknown;\n /** Navigation function for `onSuccess: { navigate }`. */\n navigate?: (path: string) => void;\n /** Fallback component for unknown types. */\n fallback?: Type<unknown> | RegistryEntry | null;\n /** Named functions for `$computed` props. */\n functions?: Record<string, ComputedFunction>;\n /** Custom validation functions. */\n validationFunctions?: Record<string, ValidationFunction>;\n /** Custom directives for `$`-prefixed values. */\n directives?: DirectiveDefinition[];\n /** Render as if the spec were still streaming. */\n loading?: boolean;\n /** Extra TestBed providers, e.g. a `JR_CONFIRM_DIALOG` replacement. */\n providers?: Provider[];\n}\n\n/**\n * A rendered spec, and the handful of things a test does to one.\n *\n * `fixture` and `element` are there for everything this does not cover — the\n * harness is a shortcut, not a wall.\n */\nexport interface SpecHarness {\n /** The fixture of the host that owns the `<json-render>`. */\n readonly fixture: ComponentFixture<unknown>;\n /** The host element, the root of the rendered DOM. */\n readonly element: HTMLElement;\n /** The renderer instance. */\n readonly renderer: JsonRenderer;\n /** The renderer's state store. */\n readonly store: JsonRenderStateService;\n /** The renderer's validation service. */\n readonly validation: JsonRenderValidationService;\n /** Every action the spec dispatched, handled or not, in order. */\n readonly dispatched: readonly DispatchedAction[];\n /** Every state change the renderer emitted, flattened, in order. */\n readonly changes: readonly StateChange[];\n\n /** Render a different spec (a later streaming frame, say). */\n setSpec(spec: Spec | null): Promise<void>;\n /** Flip the loading flag catalog components see. */\n setLoading(loading: boolean): Promise<void>;\n /** Let effects, promises and change detection finish. */\n settle(): Promise<void>;\n\n /** Read a state path, e.g. `/form/email`. */\n read(path: string): unknown;\n /** Write a state path and settle. */\n write(path: string, value: unknown): Promise<void>;\n /** The whole state model. */\n state(): StateModel;\n\n /** Trimmed text of the first match, or of everything when given nothing. */\n text(selector?: string): string;\n /** Trimmed text of every match. */\n texts(selector: string): string[];\n /** The first match. Throws when there is none. */\n find<T extends HTMLElement>(selector: string): T;\n /** Every match, possibly none. */\n findAll<T extends HTMLElement>(selector: string): T[];\n /** Click an element (or the first match of a selector) and settle. */\n click(target: string | Element): Promise<void>;\n /** Set an input's value, fire `input`, and settle. */\n fill(target: string | Element, value: string): Promise<void>;\n\n /** Destroy the fixture. Rarely needed — TestBed resets between tests. */\n destroy(): void;\n}\n\n@Component({\n selector: 'jr-test-host',\n changeDetection: ChangeDetectionStrategy.OnPush,\n imports: [JsonRenderer],\n template: `\n <json-render\n [spec]=\"spec()\"\n [registry]=\"registry()\"\n [loading]=\"loading()\"\n [state]=\"state()\"\n [store]=\"store()\"\n [handlers]=\"handlers()\"\n [onAction]=\"onAction()\"\n [navigate]=\"navigate()\"\n [fallback]=\"fallback()\"\n [functions]=\"functions()\"\n [validationFunctions]=\"validationFunctions()\"\n [directives]=\"directives()\"\n (stateChange)=\"record($event)\"\n />\n `,\n})\nclass JrTestHost {\n readonly spec = signal<Spec | null>(null);\n readonly registry = signal<ComponentRegistry>({});\n readonly loading = signal(false);\n readonly state = signal<StateModel | undefined>(undefined);\n readonly store = signal<StateStore | null>(null);\n readonly handlers = signal<Record<string, ActionHandler> | undefined>(\n undefined,\n );\n readonly onAction = signal<\n ((name: string, params?: Record<string, unknown>) => unknown) | null\n >(null);\n readonly navigate = signal<((path: string) => void) | null>(null);\n readonly fallback = signal<Type<unknown> | RegistryEntry | null>(null);\n readonly functions = signal<Record<string, ComputedFunction> | undefined>(\n undefined,\n );\n readonly validationFunctions = signal<\n Record<string, ValidationFunction> | undefined\n >(undefined);\n readonly directives = signal<DirectiveDefinition[] | undefined>(undefined);\n\n record: (changes: StateChange[]) => void = () => {};\n}\n\n/**\n * Wrap every handler so a dispatch is recorded whether or not the action is\n * handled. Without this, `dispatched` would silently omit exactly the actions\n * a test bothered to wire up.\n */\nfunction recordingHandlers(\n handlers: Record<string, ActionHandler> | undefined,\n dispatched: DispatchedAction[],\n): Record<string, ActionHandler> | undefined {\n if (!handlers) return undefined;\n const wrapped: Record<string, ActionHandler> = {};\n for (const [name, handler] of Object.entries(handlers)) {\n wrapped[name] = (params: Record<string, unknown>) => {\n dispatched.push({ name, params });\n return handler(params);\n };\n }\n return wrapped;\n}\n\n/**\n * Configure the TestBed, unless the test already did.\n *\n * A test that called `TestBed.runInInjectionContext` first — or that renders\n * a second spec — has an instantiated module, and configuring it again\n * throws. Its own module stands; the only thing that cannot be salvaged is\n * this call's `providers`, so that is the one case worth failing over.\n */\nfunction configureTestBed(providers: Provider[]): void {\n try {\n TestBed.configureTestingModule({\n providers: [provideZonelessChangeDetection(), ...providers],\n });\n } catch {\n if (providers.length > 0) {\n throw new Error(\n 'renderSpec: the TestBed was already instantiated, so `providers` cannot be applied. Pass them to your own TestBed.configureTestingModule() call instead.',\n );\n }\n }\n}\n\n/**\n * Render a spec against a registry and hand back the few things a test does\n * to it.\n *\n * Testing a catalog component otherwise means a host component, a TestBed\n * module, a zoneless provider, two settle passes and a `querySelector` — the\n * same twenty lines in every project that adopts this package, none of them\n * about the component under test.\n *\n * @example\n * ```ts\n * const ui = await renderSpec(\n * {\n * root: 'save',\n * elements: {\n * save: { type: 'Button', props: { label: 'Save' }, on: { press: { action: 'save' } } },\n * },\n * },\n * { registry: { Button: MyButton } },\n * );\n *\n * expect(ui.text('button')).toBe('Save');\n * await ui.click('button');\n * expect(ui.dispatched).toEqual([{ name: 'save', params: {} }]);\n * ```\n */\nexport async function renderSpec(\n spec: Spec | null,\n options: RenderSpecOptions,\n): Promise<SpecHarness> {\n const dispatched: DispatchedAction[] = [];\n const changes: StateChange[] = [];\n\n configureTestBed(options.providers ?? []);\n\n const fixture = TestBed.createComponent(JrTestHost);\n const host = fixture.componentInstance;\n\n host.registry.set(options.registry);\n host.loading.set(options.loading ?? false);\n host.state.set(options.state);\n host.store.set(options.store ?? null);\n host.handlers.set(recordingHandlers(options.handlers, dispatched));\n host.onAction.set((name, params) => {\n dispatched.push({ name, params });\n return options.onAction?.(name, params);\n });\n host.navigate.set(options.navigate ?? null);\n host.fallback.set(options.fallback ?? null);\n host.functions.set(options.functions);\n host.validationFunctions.set(options.validationFunctions);\n host.directives.set(options.directives);\n host.record = (batch) => changes.push(...batch);\n host.spec.set(spec);\n\n const settle = async () => {\n // Twice: the first pass runs the effects that a render schedules, the\n // second renders what those effects changed. One pass leaves a test\n // asserting against a frame that no browser would ever show.\n await fixture.whenStable();\n fixture.detectChanges();\n await fixture.whenStable();\n };\n await settle();\n\n const element = fixture.nativeElement as HTMLElement;\n // Found by predicate rather than with `By.directive`, which would make\n // @angular/platform-browser a dependency of this entry point for one line.\n const rendererElement = fixture.debugElement.query(\n (candidate) => candidate.componentInstance instanceof JsonRenderer,\n );\n const renderer = rendererElement.componentInstance as JsonRenderer;\n const store = renderer.stateStore;\n // From the renderer's own injector: these services are provided by the\n // component, so the root TestBed injector has never heard of them.\n const validation = rendererElement.injector.get(JsonRenderValidationService);\n\n const resolve = (target: string | Element): HTMLElement => {\n if (typeof target !== 'string') return target as HTMLElement;\n const found = element.querySelector<HTMLElement>(target);\n if (!found) {\n throw new Error(\n `renderSpec: nothing matches ${JSON.stringify(target)}. Rendered HTML:\\n${element.innerHTML}`,\n );\n }\n return found;\n };\n\n return {\n fixture,\n element,\n renderer,\n store,\n validation,\n dispatched,\n changes,\n\n async setSpec(next) {\n host.spec.set(next);\n await settle();\n },\n async setLoading(loading) {\n host.loading.set(loading);\n await settle();\n },\n settle,\n\n read: (path) => store.get(path),\n async write(path, value) {\n store.set(path, value);\n await settle();\n },\n state: () => store.state(),\n\n text: (selector) =>\n ((selector ? resolve(selector) : element).textContent ?? '').trim(),\n texts: (selector) =>\n Array.from(element.querySelectorAll(selector)).map((el) =>\n (el.textContent ?? '').trim(),\n ),\n find: <T extends HTMLElement>(selector: string) => resolve(selector) as T,\n findAll: <T extends HTMLElement>(selector: string) =>\n Array.from(element.querySelectorAll<T>(selector)),\n async click(target) {\n resolve(target).click();\n await settle();\n },\n async fill(target, value) {\n const input = resolve(target) as HTMLInputElement;\n input.value = value;\n input.dispatchEvent(new Event('input', { bubbles: true }));\n await settle();\n },\n\n destroy: () => fixture.destroy(),\n };\n}\n","/*\n * Public API Surface of ngx-json-render/testing\n *\n * Test utilities, shipped as a separate entry point so nothing here can be\n * pulled into an application bundle by accident.\n */\n\nexport {\n recordedTransport,\n specStream,\n usageLine,\n type Recording,\n type Recordings,\n type RecordedFailure,\n type RecordedTransportOptions,\n} from './recorded-transport';\nexport {\n renderSpec,\n type DispatchedAction,\n type RenderSpecOptions,\n type SpecHarness,\n} from './render-spec';\n","/**\n * Generated bundle index. Do not edit.\n */\n\nexport * from './public-api';\n"],"names":[],"mappings":";;;;;AAiDA;AACA,SAAS,UAAU,GAAA;AACjB,IAAA,MAAM,KAAK,GAAG,IAAI,KAAK,CAAC,4BAA4B,CAAC;AACrD,IAAA,KAAK,CAAC,IAAI,GAAG,YAAY;AACzB,IAAA,OAAO,KAAK;AACd;AAEA;AACA,SAAS,aAAa,CAAC,MAAc,EAAE,OAAe,EAAA;IACpD,OAAO,IAAI,QAAQ,CAAC,IAAI,CAAC,SAAS,CAAC,EAAE,OAAO,EAAE,CAAC,EAAE;QAC/C,MAAM;AACN,QAAA,OAAO,EAAE,EAAE,cAAc,EAAE,kBAAkB,EAAE;AAChD,KAAA,CAAC;AACJ;AAEA,SAAS,SAAS,CAAC,IAAiC,EAAA;AAClD,IAAA,IAAI;AACF,QAAA,MAAM,MAAM,GAAY,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,IAAI,IAAI,IAAI,CAAC,CAAC;AACxD,QAAA,OAAO,MAAM,IAAI,OAAO,MAAM,KAAK;AACjC,cAAG;cACD,EAAE;IACR;AAAE,IAAA,MAAM;AACN,QAAA,OAAO,EAAE;IACX;AACF;AAEA;;;AAGG;AACH,SAAS,eAAe,CAAC,IAAuC,EAAA;AAC9D,IAAA,MAAM,MAAM,GAAG,IAAI,CAAC,QAAQ,CAAC;IAC7B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E,EAAE,IAAI,EAAE;AACrE,QAAA,KAAK,EAAE,CAAC,QAAQ,KACd,KAAK,CAAC,IAAI,CAAC,OAAO,CAAC,gBAAgB,CAAC,QAAQ,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,EAAE,KACpD,CAAC,EAAE,CAAC,WAAW,IAAI,EAAE,EAAE,IAAI,EAAE,CAC9B;QACH,IAAI,EAAE,CAAwB,QAAgB,KAAK,OAAO,CAAC,QAAQ,CAAM;AACzE,QAAA,OAAO,EAAE,CAAwB,QAAgB,KAC/C,KAAK,CAAC,IAAI,CAAC,OAAO,CAAC,gBAAgB,CAAI,QAAQ,CAAC,CAAC;QACnD,MAAM,KAAK,CAAC,MAAM,EAAA;AAChB,YAAA,OAAO,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE;YACvB,MAAM,MAAM,EAAE;QAChB,CAAC;AACD,QAAA,MAAM,IAAI,CAAC,MAAM,EAAE,KAAK,EAAA;AACtB,YAAA,MAAM,KAAK,GAAG,OAAO,CAAC,MAAM,CAAqB;AACjD,YAAA,KAAK,CAAC,KAAK,GAAG,KAAK;AACnB,YAAA,KAAK,CAAC,aAAa,CAAC,IAAI,KAAK,CAAC,OAAO,EAAE,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC,CAAC;YAC1D,MAAM,MAAM,EAAE;QAChB,CAAC;AAED,QAAA,OAAO,EAAE,MAAM,OAAO,CAAC,OAAO,EAAE;KACjC;AACH;;ACnVA;;;;;AAKG;;ACLH;;AAEG;;"}
1
+ {"version":3,"file":"ngx-json-render-testing.mjs","sources":["../../../projects/ngx-json-render/testing/src/recorded-transport.ts","../../../projects/ngx-json-render/testing/src/fixture-helpers.ts","../../../projects/ngx-json-render/testing/src/render-component.ts","../../../projects/ngx-json-render/testing/src/render-spec.ts","../../../projects/ngx-json-render/testing/src/public-api.ts","../../../projects/ngx-json-render/testing/src/ngx-json-render-testing.ts"],"sourcesContent":["import type { Spec } from '@json-render/core';\n\n/**\n * The lines of one recorded response body, in the order the server sent them,\n * without their trailing newlines.\n */\nexport type Recording = readonly string[];\n\n/**\n * What to replay for a request. Either one recording for every request, a\n * lookup by prompt, or a function for anything more involved.\n */\nexport type Recordings =\n | Recording\n | Readonly<Record<string, Recording>>\n | ((\n prompt: string,\n body: Readonly<Record<string, unknown>>,\n ) => Recording | undefined);\n\n/** An error the recorded server answers with instead of a stream. */\nexport interface RecordedFailure {\n /** HTTP status. Defaults to 500. */\n status?: number;\n /** The `message` field of the JSON error body. */\n message?: string;\n}\n\n/** Options for {@link recordedTransport}. */\nexport interface RecordedTransportOptions {\n /**\n * Milliseconds between lines — the pace a model would emit them at.\n * Defaults to 0, which still yields to the event loop between lines, so a\n * test can observe the stream in flight.\n */\n delayMs?: number;\n /**\n * Answer with an error instead of a stream. A function is called per\n * request, so a test can turn the failure on and off between sends.\n */\n fail?: RecordedFailure | (() => RecordedFailure | null | undefined);\n /**\n * Pull the prompt out of the request body. The default reads `prompt`\n * (what `injectUIStream` sends) and falls back to the last message's\n * content (what `injectChatUI` sends).\n */\n promptOf?: (body: Readonly<Record<string, unknown>>) => string;\n}\n\n/** The rejection `fetch` raises when its signal fires. */\nfunction abortError(): Error {\n const error = new Error('The operation was aborted.');\n error.name = 'AbortError';\n return error;\n}\n\n/** A JSON error body, shaped the way the streaming hooks read it. */\nfunction errorResponse(status: number, message: string): Response {\n return new Response(JSON.stringify({ message }), {\n status,\n headers: { 'Content-Type': 'application/json' },\n });\n}\n\nfunction parseBody(body: BodyInit | null | undefined): Record<string, unknown> {\n try {\n const parsed: unknown = JSON.parse(String(body ?? '{}'));\n return parsed && typeof parsed === 'object'\n ? (parsed as Record<string, unknown>)\n : {};\n } catch {\n return {};\n }\n}\n\n/**\n * The prompt of a request, from either hook's body shape. Both are the\n * package's own, so the default knows them and a test does not have to.\n */\nfunction defaultPromptOf(body: Readonly<Record<string, unknown>>): string {\n const prompt = body['prompt'];\n if (typeof prompt === 'string') return prompt;\n\n const messages = body['messages'];\n if (!Array.isArray(messages) || messages.length === 0) return '';\n const last: unknown = messages[messages.length - 1];\n const content = (last as { content?: unknown } | null)?.content;\n return typeof content === 'string' ? content : '';\n}\n\nfunction toFinder(\n recordings: Recordings,\n): (prompt: string, body: Record<string, unknown>) => Recording | undefined {\n if (typeof recordings === 'function') return recordings;\n if (Array.isArray(recordings)) return () => recordings as Recording;\n const byPrompt = recordings as Readonly<Record<string, Recording>>;\n return (prompt) => byPrompt[prompt];\n}\n\nfunction replay(\n lines: Recording,\n delayMs: number,\n signal: AbortSignal | null,\n): ReadableStream<Uint8Array> {\n const encoder = new TextEncoder();\n return new ReadableStream<Uint8Array>({\n start(controller) {\n let index = 0;\n let timer: ReturnType<typeof setTimeout> | null = null;\n\n // A superseded or stopped generation has to die mid-flight the way a\n // real request does, or a test of that behaviour proves nothing.\n const onAbort = () => {\n if (timer) clearTimeout(timer);\n controller.error(abortError());\n };\n signal?.addEventListener('abort', onAbort, { once: true });\n\n const push = () => {\n if (index >= lines.length) {\n signal?.removeEventListener('abort', onAbort);\n controller.close();\n return;\n }\n controller.enqueue(encoder.encode(`${lines[index++]}\\n`));\n timer = setTimeout(push, delayMs);\n };\n timer = setTimeout(push, delayMs);\n },\n });\n}\n\n/**\n * A `fetch` that answers the streaming hooks from a recording instead of a\n * server.\n *\n * Both {@link injectUIStream} and {@link injectChatUI} take any function with\n * fetch's shape, so a test runs the real client — request body, streamed\n * lines, usage metadata, abort on supersede — with no server, no API key and\n * no global patched behind the test's back. Only the transport is recorded.\n *\n * @example\n * ```ts\n * const ui = injectUIStream({\n * api: '/api/generate',\n * fetch: recordedTransport(specStream(spec)),\n * });\n * ```\n *\n * @example Different answers per prompt, at a visible pace:\n * ```ts\n * recordedTransport(\n * { 'a dashboard': specStream(dashboard), 'a form': specStream(form) },\n * { delayMs: 20 },\n * );\n * ```\n */\nexport function recordedTransport(\n recordings: Recordings,\n options: RecordedTransportOptions = {},\n): typeof globalThis.fetch {\n const { delayMs = 0, promptOf = defaultPromptOf } = options;\n const find = toFinder(recordings);\n\n return async (_input, init) => {\n const failure =\n typeof options.fail === 'function' ? options.fail() : options.fail;\n if (failure) {\n return errorResponse(\n failure.status ?? 500,\n failure.message ?? 'The recorded server failed this request.',\n );\n }\n\n const body = parseBody(init?.body);\n const prompt = promptOf(body);\n const lines = find(prompt, body);\n if (!lines) {\n return errorResponse(404, `No recording for ${JSON.stringify(prompt)}.`);\n }\n\n const signal = init?.signal ?? null;\n if (signal?.aborted) throw abortError();\n\n return new Response(replay(lines, delayMs, signal), { status: 200 });\n };\n}\n\n/** Escape a JSON Pointer segment (RFC 6901). */\nfunction pointer(segment: string): string {\n return segment.replace(/~/g, '~0').replace(/\\//g, '~1');\n}\n\n/**\n * The JSONL patch lines a model would emit to build `spec`: the root, then\n * the state, then one line per element in declaration order.\n *\n * Recording a stream by hand means writing patches by hand; this writes them\n * from the spec a test already has, so the test says what it renders rather\n * than how the wire spells it.\n */\nexport function specStream(spec: Spec): string[] {\n const lines = [\n JSON.stringify({ op: 'add', path: '/root', value: spec.root }),\n ];\n if (spec.state) {\n lines.push(\n JSON.stringify({ op: 'add', path: '/state', value: spec.state }),\n );\n }\n for (const [key, element] of Object.entries(spec.elements ?? {})) {\n lines.push(\n JSON.stringify({\n op: 'add',\n path: `/elements/${pointer(key)}`,\n value: element,\n }),\n );\n }\n return lines;\n}\n\n/**\n * The usage metadata line `injectUIStream` reads into its `usage` signal.\n * Append it to a recording to exercise that path.\n */\nexport function usageLine(usage: {\n promptTokens?: number;\n completionTokens?: number;\n totalTokens?: number;\n}): string {\n return JSON.stringify({\n __meta: 'usage',\n promptTokens: usage.promptTokens ?? 0,\n completionTokens: usage.completionTokens ?? 0,\n totalTokens: usage.totalTokens ?? 0,\n });\n}\n","import { type Provider, provideZonelessChangeDetection } from '@angular/core';\nimport { type ComponentFixture, TestBed } from '@angular/core/testing';\n\n/**\n * What `renderSpec` and `renderComponent` share: the TestBed setup, the settle\n * loop, and the handful of DOM queries a test runs against what rendered.\n *\n * @internal Not exported from the entry point.\n */\n\n/**\n * Configure the TestBed, unless the test already did.\n *\n * A test that called `TestBed.runInInjectionContext` first — or that renders\n * a second time — has an instantiated module, and configuring it again\n * throws. Its own module stands; the only thing that cannot be salvaged is\n * this call's `providers`, so that is the one case worth failing over.\n */\nexport function configureTestBed(caller: string, providers: Provider[]): void {\n try {\n TestBed.configureTestingModule({\n providers: [provideZonelessChangeDetection(), ...providers],\n });\n } catch {\n if (providers.length > 0) {\n throw new Error(\n `${caller}: the TestBed was already instantiated, so \\`providers\\` cannot be applied. Pass them to your own TestBed.configureTestingModule() call instead.`,\n );\n }\n }\n}\n\n/** Let effects, promises and change detection finish. */\nexport function settler(\n fixture: ComponentFixture<unknown>,\n): () => Promise<void> {\n return async () => {\n // Twice: the first pass runs the effects that a render schedules, the\n // second renders what those effects changed. One pass leaves a test\n // asserting against a frame that no browser would ever show.\n await fixture.whenStable();\n fixture.detectChanges();\n await fixture.whenStable();\n };\n}\n\n/** The DOM half of a harness. */\nexport interface DomQueries {\n /** Trimmed text of the first match, or of everything when given nothing. */\n text(selector?: string): string;\n /** Trimmed text of every match. */\n texts(selector: string): string[];\n /** The first match. Throws when there is none. */\n find<T extends HTMLElement>(selector: string): T;\n /** Every match, possibly none. */\n findAll<T extends HTMLElement>(selector: string): T[];\n /** Click an element (or the first match of a selector) and settle. */\n click(target: string | Element): Promise<void>;\n /** Set an input's value, fire `input`, and settle. */\n fill(target: string | Element, value: string): Promise<void>;\n}\n\nexport function domQueries(\n caller: string,\n element: HTMLElement,\n settle: () => Promise<void>,\n): DomQueries {\n const resolve = (target: string | Element): HTMLElement => {\n if (typeof target !== 'string') return target as HTMLElement;\n const found = element.querySelector<HTMLElement>(target);\n if (!found) {\n throw new Error(\n `${caller}: nothing matches ${JSON.stringify(target)}. Rendered HTML:\\n${element.innerHTML}`,\n );\n }\n return found;\n };\n\n return {\n text: (selector) =>\n ((selector ? resolve(selector) : element).textContent ?? '').trim(),\n texts: (selector) =>\n Array.from(element.querySelectorAll(selector)).map((el) =>\n (el.textContent ?? '').trim(),\n ),\n find: <T extends HTMLElement>(selector: string) => resolve(selector) as T,\n findAll: <T extends HTMLElement>(selector: string) =>\n Array.from(element.querySelectorAll<T>(selector)),\n async click(target) {\n resolve(target).click();\n await settle();\n },\n async fill(target, value) {\n const input = resolve(target) as HTMLInputElement;\n input.value = value;\n input.dispatchEvent(new Event('input', { bubbles: true }));\n await settle();\n },\n };\n}\n","import { NgComponentOutlet } from '@angular/common';\nimport {\n ChangeDetectionStrategy,\n Component,\n Injector,\n type Provider,\n type Type,\n computed,\n inject,\n isDevMode,\n signal,\n} from '@angular/core';\nimport { type ComponentFixture, TestBed } from '@angular/core/testing';\nimport type { UIElement } from '@json-render/core';\nimport {\n ELEMENT_KEY,\n type EventHandle,\n RENDER_CONTEXT,\n type RenderContext,\n} from 'ngx-json-render';\nimport {\n type DomQueries,\n configureTestBed,\n domQueries,\n settler,\n} from './fixture-helpers';\n\n/** One `setBound` call that reached a bound prop, in order. */\nexport interface BoundWrite {\n prop: string;\n value: unknown;\n}\n\n/** Options for {@link renderComponent}. Everything is optional. */\nexport interface RenderComponentOptions<P extends object> {\n /** The resolved props the component sees. Defaults to `{}`. */\n props?: P;\n /**\n * Which props are two-way bound, as `prop → state path` — what\n * `$bindState` / `$bindItem` would have resolved to. A `setBound` on a prop\n * listed here is recorded and written back into `props`; on any other prop\n * it is a no-op, exactly as under the renderer.\n */\n bindings?: Record<string, string>;\n /**\n * The events the spec would bind in `on`. Only affects what `ctx.on(event)`\n * reports as `bound` — `emitted` records every event regardless.\n */\n on?: readonly string[];\n /** The loading flag the component sees. */\n loading?: boolean;\n /** The spec key, for components that `injectElementKey()`. */\n key?: string;\n /** The element's catalog type name. */\n type?: string;\n /** Extra TestBed providers for anything else the component injects. */\n providers?: Provider[];\n}\n\n/**\n * A catalog component mounted on its own, and what it said to the renderer\n * it thinks it is inside.\n */\nexport interface ComponentHarness<T, P extends object> extends DomQueries {\n /** The fixture of the host the component is mounted in. */\n readonly fixture: ComponentFixture<unknown>;\n /** The host element, the root of the rendered DOM. */\n readonly element: HTMLElement;\n /** The component instance. */\n readonly component: T;\n /** The render context the component injected. */\n readonly context: RenderContext<P>;\n /** Every event the component emitted, bound or not, in order. */\n readonly emitted: readonly string[];\n /** Every `setBound` that reached a bound prop, in order. */\n readonly writes: readonly BoundWrite[];\n\n /** The props as the component currently sees them. */\n props(): P;\n /** Replace the props and settle. */\n setProps(props: P): Promise<void>;\n /** Merge into the props and settle. */\n patchProps(patch: Partial<P>): Promise<void>;\n /** Flip the loading flag and settle. */\n setLoading(loading: boolean): Promise<void>;\n /** Let effects, promises and change detection finish. */\n settle(): Promise<void>;\n /** Destroy the fixture. Rarely needed — TestBed resets between tests. */\n destroy(): void;\n}\n\n/**\n * Mounted through `NgComponentOutlet` with an element injector, the way\n * `<jr-element>` mounts a catalog component — so the context is the\n * component's own, not the TestBed module's, and a test can mount twice.\n */\n@Component({\n selector: 'jr-component-test-host',\n changeDetection: ChangeDetectionStrategy.OnPush,\n imports: [NgComponentOutlet],\n template: `\n @if (component(); as type) {\n <ng-container *ngComponentOutlet=\"type; injector: injector()\" />\n }\n `,\n})\nclass JrComponentTestHost {\n readonly parent = inject(Injector);\n readonly component = signal<Type<unknown> | null>(null);\n readonly injector = signal<Injector>(this.parent);\n}\n\n/** The renderer-owned services a component can only have from a renderer. */\nconst RENDERER_ONLY =\n /JsonRender(RootContext|StateService|ValidationService|ActionsService)/;\n\n/**\n * Turn \"no provider for the renderer's services\" into what to do about it.\n * `<jr-children>`, `injectFieldValidation` and `injectActions` all need a\n * real renderer behind them; there is no honest fake for a subtree.\n */\nfunction explainMissingRenderer(error: unknown): never {\n const message = error instanceof Error ? error.message : String(error);\n if (RENDERER_ONLY.test(message)) {\n throw new Error(\n `renderComponent: this component needs a real <json-render> — it renders <jr-children>, validates a field or dispatches actions itself. Test it with renderSpec instead.\\n\\n${message}`,\n );\n }\n throw error;\n}\n\n/**\n * Mount a catalog component with no renderer and no spec: hand it props, and\n * read back the events it emitted and the values it wrote to bound props.\n *\n * This is the test of a component as a presentational one — what it draws\n * for these props, and what it says when used. What the spec then does with\n * that is the renderer's business, and `renderSpec` is where to test it.\n *\n * `props` is not inferred from the first value, so a later `patchProps` can\n * set a prop the first render left out. Pass `P` to have the props typed.\n *\n * A component that renders `<jr-children>`, registers field validation or\n * dispatches actions directly needs the renderer's services and fails with a\n * message pointing at `renderSpec`.\n *\n * @example\n * ```ts\n * const button = await renderComponent(MyButton, { props: { label: 'Save' } });\n *\n * expect(button.text('button')).toBe('Save');\n * await button.click('button');\n * expect(button.emitted).toEqual(['press']);\n *\n * await button.patchProps({ disabled: true });\n * expect(button.find<HTMLButtonElement>('button').disabled).toBe(true);\n * ```\n */\nexport async function renderComponent<\n T,\n P extends object = Record<string, unknown>,\n>(\n component: Type<T>,\n options: RenderComponentOptions<NoInfer<P>> = {},\n): Promise<ComponentHarness<T, P>> {\n const emitted: string[] = [];\n const writes: BoundWrite[] = [];\n\n const props = signal<P>(options.props ?? ({} as P));\n const loading = signal(options.loading ?? false);\n const bindings = options.bindings;\n const boundEvents = new Set(options.on ?? []);\n const key = signal(options.key ?? 'element');\n\n const element = computed(\n () =>\n ({\n type: options.type ?? component.name,\n props: props(),\n children: [],\n }) as UIElement<string, P>,\n );\n\n const emit = (event: string) => {\n emitted.push(event);\n };\n\n const context: RenderContext<P> = {\n element,\n props: props.asReadonly(),\n emit,\n on: (event): EventHandle => ({\n emit: () => emit(event),\n shouldPreventDefault: false,\n bound: boundEvents.has(event),\n }),\n bindings: signal(bindings).asReadonly(),\n loading: loading.asReadonly(),\n setBound: (prop, value) => {\n if (!bindings?.[prop]) {\n if (isDevMode()) {\n console.warn(\n `[ngx-json-render] setBound(\"${prop}\"): prop has no $bindState/$bindItem binding`,\n );\n }\n return;\n }\n writes.push({ prop, value });\n // What the renderer's round trip amounts to: the write lands in state,\n // and the bound prop resolves to it on the next read.\n props.update((current) => ({ ...current, [prop]: value }));\n },\n };\n\n configureTestBed('renderComponent', options.providers ?? []);\n\n const fixture = TestBed.createComponent(JrComponentTestHost);\n const host = fixture.componentInstance;\n host.injector.set(\n Injector.create({\n providers: [\n { provide: RENDER_CONTEXT, useValue: context },\n { provide: ELEMENT_KEY, useValue: key.asReadonly() },\n ],\n parent: host.parent,\n }),\n );\n host.component.set(component);\n\n const settle = settler(fixture);\n try {\n await settle();\n } catch (error) {\n explainMissingRenderer(error);\n }\n\n const mounted = fixture.debugElement.query(\n (candidate) => candidate.componentInstance instanceof component,\n );\n if (!mounted) {\n throw new Error(\n `renderComponent: ${component.name} did not mount. Is it a component?`,\n );\n }\n\n const root = fixture.nativeElement as HTMLElement;\n\n return {\n fixture,\n element: root,\n component: mounted.componentInstance as T,\n context,\n emitted,\n writes,\n\n props: () => props(),\n async setProps(next) {\n props.set(next);\n await settle();\n },\n async patchProps(patch) {\n props.update((current) => ({ ...current, ...patch }));\n await settle();\n },\n async setLoading(next) {\n loading.set(next);\n await settle();\n },\n settle,\n\n ...domQueries('renderComponent', root, settle),\n\n destroy: () => fixture.destroy(),\n };\n}\n","import {\n ChangeDetectionStrategy,\n Component,\n type Provider,\n type Type,\n signal,\n} from '@angular/core';\nimport { type ComponentFixture, TestBed } from '@angular/core/testing';\nimport type {\n ActionHandler,\n ComputedFunction,\n DirectiveDefinition,\n Spec,\n StateStore,\n ValidationFunction,\n} from '@json-render/core';\nimport {\n type ComponentRegistry,\n JsonRenderStateService,\n JsonRenderValidationService,\n JsonRenderer,\n type RegistryEntry,\n type StateChange,\n type StateModel,\n} from 'ngx-json-render';\nimport {\n type DomQueries,\n configureTestBed,\n domQueries,\n settler,\n} from './fixture-helpers';\n\n/** One action the spec asked for, in the order it was dispatched. */\nexport interface DispatchedAction {\n name: string;\n params?: Record<string, unknown>;\n}\n\n/** Options for {@link renderSpec}. Everything but `registry` is optional. */\nexport interface RenderSpecOptions {\n /** Catalog type name → Angular component. The one required option. */\n registry: ComponentRegistry;\n /** Initial state model. Defaults to the spec's own `state`. */\n state?: StateModel;\n /** External store, for controlled mode. */\n store?: StateStore | null;\n /** Action handlers by name. Dispatches are recorded either way. */\n handlers?: Record<string, ActionHandler>;\n /** Catch-all handler for actions with no dedicated handler. */\n onAction?: (name: string, params?: Record<string, unknown>) => unknown;\n /** Navigation function for `onSuccess: { navigate }`. */\n navigate?: (path: string) => void;\n /** Fallback component for unknown types. */\n fallback?: Type<unknown> | RegistryEntry | null;\n /** Named functions for `$computed` props. */\n functions?: Record<string, ComputedFunction>;\n /** Custom validation functions. */\n validationFunctions?: Record<string, ValidationFunction>;\n /** Custom directives for `$`-prefixed values. */\n directives?: DirectiveDefinition[];\n /** Render as if the spec were still streaming. */\n loading?: boolean;\n /** Extra TestBed providers, e.g. a `JR_CONFIRM_DIALOG` replacement. */\n providers?: Provider[];\n}\n\n/**\n * A rendered spec, and the handful of things a test does to one.\n *\n * `fixture` and `element` are there for everything this does not cover — the\n * harness is a shortcut, not a wall.\n */\nexport interface SpecHarness extends DomQueries {\n /** The fixture of the host that owns the `<json-render>`. */\n readonly fixture: ComponentFixture<unknown>;\n /** The host element, the root of the rendered DOM. */\n readonly element: HTMLElement;\n /** The renderer instance. */\n readonly renderer: JsonRenderer;\n /** The renderer's state store. */\n readonly store: JsonRenderStateService;\n /** The renderer's validation service. */\n readonly validation: JsonRenderValidationService;\n /** Every action the spec dispatched, handled or not, in order. */\n readonly dispatched: readonly DispatchedAction[];\n /** Every state change the renderer emitted, flattened, in order. */\n readonly changes: readonly StateChange[];\n\n /** Render a different spec (a later streaming frame, say). */\n setSpec(spec: Spec | null): Promise<void>;\n /** Flip the loading flag catalog components see. */\n setLoading(loading: boolean): Promise<void>;\n /** Let effects, promises and change detection finish. */\n settle(): Promise<void>;\n\n /** Read a state path, e.g. `/form/email`. */\n read(path: string): unknown;\n /** Write a state path and settle. */\n write(path: string, value: unknown): Promise<void>;\n /** The whole state model. */\n state(): StateModel;\n\n /** Destroy the fixture. Rarely needed — TestBed resets between tests. */\n destroy(): void;\n}\n\n@Component({\n selector: 'jr-test-host',\n changeDetection: ChangeDetectionStrategy.OnPush,\n imports: [JsonRenderer],\n template: `\n <json-render\n [spec]=\"spec()\"\n [registry]=\"registry()\"\n [loading]=\"loading()\"\n [state]=\"state()\"\n [store]=\"store()\"\n [handlers]=\"handlers()\"\n [onAction]=\"onAction()\"\n [navigate]=\"navigate()\"\n [fallback]=\"fallback()\"\n [functions]=\"functions()\"\n [validationFunctions]=\"validationFunctions()\"\n [directives]=\"directives()\"\n (stateChange)=\"record($event)\"\n />\n `,\n})\nclass JrTestHost {\n readonly spec = signal<Spec | null>(null);\n readonly registry = signal<ComponentRegistry>({});\n readonly loading = signal(false);\n readonly state = signal<StateModel | undefined>(undefined);\n readonly store = signal<StateStore | null>(null);\n readonly handlers = signal<Record<string, ActionHandler> | undefined>(\n undefined,\n );\n readonly onAction = signal<\n ((name: string, params?: Record<string, unknown>) => unknown) | null\n >(null);\n readonly navigate = signal<((path: string) => void) | null>(null);\n readonly fallback = signal<Type<unknown> | RegistryEntry | null>(null);\n readonly functions = signal<Record<string, ComputedFunction> | undefined>(\n undefined,\n );\n readonly validationFunctions = signal<\n Record<string, ValidationFunction> | undefined\n >(undefined);\n readonly directives = signal<DirectiveDefinition[] | undefined>(undefined);\n\n record: (changes: StateChange[]) => void = () => {};\n}\n\n/**\n * Wrap every handler so a dispatch is recorded whether or not the action is\n * handled. Without this, `dispatched` would silently omit exactly the actions\n * a test bothered to wire up.\n */\nfunction recordingHandlers(\n handlers: Record<string, ActionHandler> | undefined,\n dispatched: DispatchedAction[],\n): Record<string, ActionHandler> | undefined {\n if (!handlers) return undefined;\n const wrapped: Record<string, ActionHandler> = {};\n for (const [name, handler] of Object.entries(handlers)) {\n wrapped[name] = (params: Record<string, unknown>) => {\n dispatched.push({ name, params });\n return handler(params);\n };\n }\n return wrapped;\n}\n\n/**\n * Render a spec against a registry and hand back the few things a test does\n * to it.\n *\n * Testing a catalog component otherwise means a host component, a TestBed\n * module, a zoneless provider, two settle passes and a `querySelector` — the\n * same twenty lines in every project that adopts this package, none of them\n * about the component under test.\n *\n * @example\n * ```ts\n * const ui = await renderSpec(\n * {\n * root: 'save',\n * elements: {\n * save: { type: 'Button', props: { label: 'Save' }, on: { press: { action: 'save' } } },\n * },\n * },\n * { registry: { Button: MyButton } },\n * );\n *\n * expect(ui.text('button')).toBe('Save');\n * await ui.click('button');\n * expect(ui.dispatched).toEqual([{ name: 'save', params: {} }]);\n * ```\n */\nexport async function renderSpec(\n spec: Spec | null,\n options: RenderSpecOptions,\n): Promise<SpecHarness> {\n const dispatched: DispatchedAction[] = [];\n const changes: StateChange[] = [];\n\n configureTestBed('renderSpec', options.providers ?? []);\n\n const fixture = TestBed.createComponent(JrTestHost);\n const host = fixture.componentInstance;\n\n host.registry.set(options.registry);\n host.loading.set(options.loading ?? false);\n host.state.set(options.state);\n host.store.set(options.store ?? null);\n host.handlers.set(recordingHandlers(options.handlers, dispatched));\n host.onAction.set((name, params) => {\n dispatched.push({ name, params });\n return options.onAction?.(name, params);\n });\n host.navigate.set(options.navigate ?? null);\n host.fallback.set(options.fallback ?? null);\n host.functions.set(options.functions);\n host.validationFunctions.set(options.validationFunctions);\n host.directives.set(options.directives);\n host.record = (batch) => changes.push(...batch);\n host.spec.set(spec);\n\n const settle = settler(fixture);\n await settle();\n\n const element = fixture.nativeElement as HTMLElement;\n // Found by predicate rather than with `By.directive`, which would make\n // @angular/platform-browser a dependency of this entry point for one line.\n const rendererElement = fixture.debugElement.query(\n (candidate) => candidate.componentInstance instanceof JsonRenderer,\n );\n const renderer = rendererElement.componentInstance as JsonRenderer;\n const store = renderer.stateStore;\n // From the renderer's own injector: these services are provided by the\n // component, so the root TestBed injector has never heard of them.\n const validation = rendererElement.injector.get(JsonRenderValidationService);\n\n return {\n fixture,\n element,\n renderer,\n store,\n validation,\n dispatched,\n changes,\n\n async setSpec(next) {\n host.spec.set(next);\n await settle();\n },\n async setLoading(loading) {\n host.loading.set(loading);\n await settle();\n },\n settle,\n\n read: (path) => store.get(path),\n async write(path, value) {\n store.set(path, value);\n await settle();\n },\n state: () => store.state(),\n\n ...domQueries('renderSpec', element, settle),\n\n destroy: () => fixture.destroy(),\n };\n}\n","/*\n * Public API Surface of ngx-json-render/testing\n *\n * Test utilities, shipped as a separate entry point so nothing here can be\n * pulled into an application bundle by accident.\n */\n\nexport {\n recordedTransport,\n specStream,\n usageLine,\n type Recording,\n type Recordings,\n type RecordedFailure,\n type RecordedTransportOptions,\n} from './recorded-transport';\nexport {\n renderComponent,\n type BoundWrite,\n type ComponentHarness,\n type RenderComponentOptions,\n} from './render-component';\nexport {\n renderSpec,\n type DispatchedAction,\n type RenderSpecOptions,\n type SpecHarness,\n} from './render-spec';\n","/**\n * Generated bundle index. Do not edit.\n */\n\nexport * from './public-api';\n"],"names":[],"mappings":";;;;;;AAiDA;AACA,SAAS,UAAU,GAAA;AACjB,IAAA,MAAM,KAAK,GAAG,IAAI,KAAK,CAAC,4BAA4B,CAAC;AACrD,IAAA,KAAK,CAAC,IAAI,GAAG,YAAY;AACzB,IAAA,OAAO,KAAK;AACd;AAEA;AACA,SAAS,aAAa,CAAC,MAAc,EAAE,OAAe,EAAA;IACpD,OAAO,IAAI,QAAQ,CAAC,IAAI,CAAC,SAAS,CAAC,EAAE,OAAO,EAAE,CAAC,EAAE;QAC/C,MAAM;AACN,QAAA,OAAO,EAAE,EAAE,cAAc,EAAE,kBAAkB,EAAE;AAChD,KAAA,CAAC;AACJ;AAEA,SAAS,SAAS,CAAC,IAAiC,EAAA;AAClD,IAAA,IAAI;AACF,QAAA,MAAM,MAAM,GAAY,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,IAAI,IAAI,IAAI,CAAC,CAAC;AACxD,QAAA,OAAO,MAAM,IAAI,OAAO,MAAM,KAAK;AACjC,cAAG;cACD,EAAE;IACR;AAAE,IAAA,MAAM;AACN,QAAA,OAAO,EAAE;IACX;AACF;AAEA;;;AAGG;AACH,SAAS,eAAe,CAAC,IAAu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AAK,CAAC,IAAI,EAAE,KAAK,EAAA;AACrB,YAAA,KAAK,CAAC,GAAG,CAAC,IAAI,EAAE,KAAK,CAAC;YACtB,MAAM,MAAM,EAAE;QAChB,CAAC;AACD,QAAA,KAAK,EAAE,MAAM,KAAK,CAAC,KAAK,EAAE;AAE1B,QAAA,GAAG,UAAU,CAAC,YAAY,EAAE,OAAO,EAAE,MAAM,CAAC;AAE5C,QAAA,OAAO,EAAE,MAAM,OAAO,CAAC,OAAO,EAAE;KACjC;AACH;;ACjRA;;;;;AAKG;;ACLH;;AAEG;;"}
@@ -1290,21 +1290,8 @@ class JrElement {
1290
1290
  if (!changedPaths.has(path))
1291
1291
  continue;
1292
1292
  const binding = watchConfig[path];
1293
- if (!binding)
1294
- continue;
1295
- const bindings = Array.isArray(binding) ? binding : [binding];
1296
- for (const b of bindings) {
1297
- if (!b.params) {
1298
- await this.actions.execute(b);
1299
- continue;
1300
- }
1301
- const liveCtx = this.liveResolutionCtx();
1302
- const resolved = {};
1303
- for (const [key, val] of Object.entries(b.params)) {
1304
- resolved[key] = resolveActionParam(val, liveCtx);
1305
- }
1306
- await this.actions.execute({ ...b, params: resolved });
1307
- }
1293
+ if (binding)
1294
+ await this.dispatch(binding);
1308
1295
  }
1309
1296
  })().catch(reportActionError);
1310
1297
  });
@@ -1330,12 +1317,17 @@ class JrElement {
1330
1317
  this.emitEvent(eventName).catch(reportActionError);
1331
1318
  }
1332
1319
  async emitEvent(eventName) {
1333
- const el = untracked(this.rawElement);
1334
- const binding = el?.on?.[eventName];
1335
- if (!binding)
1336
- return;
1337
- const actionBindings = Array.isArray(binding) ? binding : [binding];
1338
- for (const b of actionBindings) {
1320
+ const binding = untracked(this.rawElement)?.on?.[eventName];
1321
+ if (binding)
1322
+ await this.dispatch(binding);
1323
+ }
1324
+ /**
1325
+ * Run an `on` or `watch` binding's actions in order. Params are resolved
1326
+ * per action, just before it runs, so a `$state` read in a later action of
1327
+ * the chain sees what an earlier one wrote.
1328
+ */
1329
+ async dispatch(binding) {
1330
+ for (const b of Array.isArray(binding) ? binding : [binding]) {
1339
1331
  if (!b.params) {
1340
1332
  await this.actions.execute(b);
1341
1333
  continue;