@jterrazz/test 15.1.0 → 15.2.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.
@@ -0,0 +1,2477 @@
1
+ import { TestRunner, expect, inject, onTestFinished, vi } from "vitest";
2
+ import { commands, page, userEvent } from "vitest/browser";
3
+ import { mockDeep } from "vitest-mock-extended";
4
+ import MockDatePackage from "mockdate";
5
+ //#region src/specification/facets/_common/ground.ts
6
+ /**
7
+ * The GROUND a row of specs stands on — the naming law of a spec tree.
8
+ *
9
+ * In a row of specs, a MEMBER is a spec: `<aspect>.test.ts`, `<case>.spec.yaml`,
10
+ * `<name>.specification.ts`, and the facet/domain folders that hold them.
11
+ * Everything else in that row is what the members STAND ON — inert material the
12
+ * framework resolves BY PATH, never imported, never executed — and it carries a
13
+ * LEADING UNDERSCORE. A spec's own folder never does.
14
+ *
15
+ * Four names, and only four: `_fixtures/` (file state), `_expected/` (goldens),
16
+ * `_requests/` (inputs), `_seeds/` (database state). `contracts/` is NOT ground —
17
+ * a contract is TypeScript a spec imports, behaviour composed with the spec's own,
18
+ * so it stays a member. `docker/` is not ground either: it sits at the PROJECT
19
+ * root beside `package.json`, outside any row of specs.
20
+ *
21
+ * This module is the single home of those names. Every resolver, matcher, lint
22
+ * rule and checker pass reads them from here, so the runtime and the static
23
+ * channels cannot disagree about where a spec's ground lives.
24
+ */
25
+ /** Goldens: every expected fixture, flat, extension included. */
26
+ const GROUND_EXPECTED = "_expected";
27
+ //#endregion
28
+ //#region src/specification/matching/match.ts
29
+ /** Every kind usable as a `{{token}}` in fixture files (all but ref/regex/includes). */
30
+ const TOKEN_KINDS = [
31
+ "any",
32
+ "base64",
33
+ "date",
34
+ "duration",
35
+ "email",
36
+ "float",
37
+ "hex",
38
+ "int",
39
+ "ip",
40
+ "iso8601",
41
+ "number",
42
+ "path",
43
+ "port",
44
+ "semver",
45
+ "sha",
46
+ "string",
47
+ "time",
48
+ "ulid",
49
+ "url",
50
+ "uuid",
51
+ "workdir"
52
+ ];
53
+ /**
54
+ * A dynamic-value matcher. Created via the {@link match} factories — never
55
+ * constructed directly by user code.
56
+ */
57
+ var Matcher = class {
58
+ /** For kind 'includes': the substring the actual value must contain. */
59
+ includes;
60
+ kind;
61
+ /** For kind 'ref': the capture to assert inequality against. */
62
+ notRef;
63
+ /** For kind 'ref': the capture name. */
64
+ refName;
65
+ /** For kind 'regex': the pattern the actual value must match. */
66
+ regex;
67
+ constructor(kind, options = {}) {
68
+ this.includes = options.includes;
69
+ this.kind = kind;
70
+ this.notRef = options.notRef;
71
+ this.refName = options.refName;
72
+ this.regex = options.regex;
73
+ }
74
+ /** Placeholder-style rendering used in failure diffs and serialization. */
75
+ toString() {
76
+ switch (this.kind) {
77
+ case "includes": return `{{includes:${this.includes}}}`;
78
+ case "ref": return this.notRef ? `{{ref#${this.refName}!${this.notRef}}}` : `{{ref#${this.refName}}}`;
79
+ case "regex": return `{{regex:${this.regex?.source}}}`;
80
+ default: return this.refName ? `{{${this.kind}#${this.refName}}}` : `{{${this.kind}}}`;
81
+ }
82
+ }
83
+ toJSON() {
84
+ return this.toString();
85
+ }
86
+ };
87
+ const typed = (kind) => () => new Matcher(kind);
88
+ const match = {
89
+ /** Matches anything. */
90
+ any: typed("any"),
91
+ /** Matches a base64 string. */
92
+ base64: typed("base64"),
93
+ /** Matches a calendar date (`YYYY-MM-DD`). */
94
+ date: typed("date"),
95
+ /** Matches a human duration (`12ms`, `1.5s`, `2m`, `3h`). */
96
+ duration: typed("duration"),
97
+ /** Matches an email address. */
98
+ email: typed("email"),
99
+ /**
100
+ * Matches a float. In JSON contexts any finite number passes (JSON does
101
+ * not distinguish `42` from `42.0`); in text contexts the decimal part
102
+ * is required (`4.2`, never `42`).
103
+ */
104
+ float: typed("float"),
105
+ /** Matches a hexadecimal string. */
106
+ hex: typed("hex"),
107
+ /**
108
+ * Matches a string CONTAINING the given substring. Code-only, like
109
+ * {@link match.regex} — the `{{token}}` fixture vocabulary does not grow.
110
+ * The explicit escape hatch now that contract string filters
111
+ * (`openai.chat({ user })`) mean exact equality.
112
+ */
113
+ includes: (substring) => new Matcher("includes", { includes: substring }),
114
+ /** Matches an integer (or an integer string in text contexts). */
115
+ int: typed("int"),
116
+ /** Matches an IPv4 address. */
117
+ ip: typed("ip"),
118
+ /** Matches an ISO-8601 timestamp string. */
119
+ iso8601: typed("iso8601"),
120
+ /** Matches a number (or a numeric string in text contexts). */
121
+ number: typed("number"),
122
+ /** Matches a filesystem path (`/...` or `./...`). */
123
+ path: typed("path"),
124
+ /** Matches a TCP/UDP port number (0-65535). */
125
+ port: typed("port"),
126
+ /**
127
+ * Capture-and-compare. The first occurrence of `ref(name)` captures the
128
+ * actual value; every later occurrence must strictly equal the capture.
129
+ * `{ not: other }` additionally asserts inequality with the capture named
130
+ * `other`. Scope: the current spec execution (reset per chain).
131
+ */
132
+ ref: (name, options) => new Matcher("ref", {
133
+ notRef: options?.not,
134
+ refName: name
135
+ }),
136
+ /** Matches a string against the given regular expression. */
137
+ regex: (regex) => new Matcher("regex", { regex }),
138
+ /** Matches a semantic version (`1.2.3`, `2.0.0-rc.1`). */
139
+ semver: typed("semver"),
140
+ /** Matches a git SHA (7-64 hex chars). */
141
+ sha: typed("sha"),
142
+ /** Matches any string. */
143
+ string: typed("string"),
144
+ /** Matches a wall-clock time (`HH:MM` or `HH:MM:SS`). */
145
+ time: typed("time"),
146
+ /** Matches a ULID. */
147
+ ulid: typed("ulid"),
148
+ /** Matches an http(s) URL. */
149
+ url: typed("url"),
150
+ /** Matches a UUID string. */
151
+ uuid: typed("uuid"),
152
+ /** Matches the exact working directory of the current spec. */
153
+ workdir: typed("workdir")
154
+ };
155
+ /**
156
+ * Named captures recorded by `match.ref()` / `{{type#ref}}` placeholders.
157
+ * One scope lives on each spec result — every assertion chained off the same
158
+ * result shares it, and a new chain starts fresh.
159
+ */
160
+ var CaptureScope = class {
161
+ values = /* @__PURE__ */ new Map();
162
+ /**
163
+ * The exact working directory of the current spec, when the framework
164
+ * knows it (cli mode). Drives the `{{workdir}}` token / `match.workdir()`.
165
+ */
166
+ workdir;
167
+ constructor(workdir) {
168
+ this.workdir = workdir;
169
+ }
170
+ get(name) {
171
+ return this.values.get(name);
172
+ }
173
+ has(name) {
174
+ return this.values.has(name);
175
+ }
176
+ set(name, value) {
177
+ this.values.set(name, value);
178
+ }
179
+ };
180
+ //#endregion
181
+ //#region src/specification/matching/structural.ts
182
+ /**
183
+ * Structural comparison engine shared by every fixture matcher.
184
+ *
185
+ * Handles three kinds of "expected" values:
186
+ * - plain JSON values → strict deep equality
187
+ * - {@link Matcher} instances (code-side `match.*`)
188
+ * - strings containing `{{placeholder}}` forms (file-side fixtures)
189
+ *
190
+ * One unified `{{token}}` grammar (CONVENTIONS D4) — the same vocabulary
191
+ * works in `_expected/*.http` (body and headers), `_expected/*.json`, and
192
+ * text snapshots (`_expected/*.txt`).
193
+ *
194
+ * Ref captures (`match.ref(name)` / `{{type#name}}`) are recorded in the
195
+ * {@link CaptureScope} supplied by the caller.
196
+ */
197
+ const UUID_SOURCE = "[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}";
198
+ const ULID_SOURCE = "[0-9A-HJKMNP-TV-Z]{26}";
199
+ const ISO8601_SOURCE = String.raw`\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})`;
200
+ const DATE_SOURCE = String.raw`\d{4}-\d{2}-\d{2}`;
201
+ const TIME_SOURCE = String.raw`\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?`;
202
+ const DURATION_SOURCE = String.raw`\d+(?:\.\d+)?(?:ms|s|m|h)`;
203
+ const NUMBER_SOURCE = String.raw`-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?`;
204
+ const INT_SOURCE = String.raw`-?\d+`;
205
+ const FLOAT_SOURCE = String.raw`-?\d+\.\d+`;
206
+ const SEMVER_SOURCE = String.raw`\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?`;
207
+ const SHA_SOURCE = "[0-9a-f]{7,64}";
208
+ const HEX_SOURCE = "[0-9a-fA-F]+";
209
+ const BASE64_SOURCE = "[A-Za-z0-9+/]+={0,2}";
210
+ const PORT_SOURCE = String.raw`(?:6553[0-5]|655[0-2]\d|65[0-4]\d{2}|6[0-4]\d{3}|[1-5]\d{4}|\d{1,4})`;
211
+ const IP_OCTET = String.raw`(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)`;
212
+ const IP_SOURCE = String.raw`(?:${IP_OCTET}\.){3}${IP_OCTET}`;
213
+ const URL_SOURCE = String.raw`https?:\/\/[^\s"'<>]+`;
214
+ const EMBEDDED_SOURCES = {
215
+ base64: BASE64_SOURCE,
216
+ date: DATE_SOURCE,
217
+ duration: DURATION_SOURCE,
218
+ email: String.raw`[^\s@"'<>]+@[^\s@"'<>]+\.[^\s@"'<>]+`,
219
+ float: FLOAT_SOURCE,
220
+ hex: HEX_SOURCE,
221
+ int: INT_SOURCE,
222
+ ip: IP_SOURCE,
223
+ iso8601: ISO8601_SOURCE,
224
+ number: NUMBER_SOURCE,
225
+ path: String.raw`\.{0,2}\/[^\s"'<>]*`,
226
+ port: PORT_SOURCE,
227
+ semver: SEMVER_SOURCE,
228
+ sha: SHA_SOURCE,
229
+ time: TIME_SOURCE,
230
+ ulid: ULID_SOURCE,
231
+ url: URL_SOURCE,
232
+ uuid: UUID_SOURCE
233
+ };
234
+ const wholeRe = (source) => new RegExp(`^(?:${source})$`, "u");
235
+ const WHOLE_RES = Object.fromEntries(Object.entries(EMBEDDED_SOURCES).map(([kind, source]) => [kind, wholeRe(source)]));
236
+ const PLACEHOLDER_RE = new RegExp(String.raw`\{\{(?<kind>${[...TOKEN_KINDS].sort((a, b) => b.length - a.length).join("|")})(?:#(?<ref>[\w.-]+))?\}\}`, "gu");
237
+ /** Whether a fixture string contains at least one `{{placeholder}}`. */
238
+ function hasPlaceholders(value) {
239
+ PLACEHOLDER_RE.lastIndex = 0;
240
+ return PLACEHOLDER_RE.test(value);
241
+ }
242
+ /** Key-order-independent stringification for captured-object comparison. */
243
+ function stableStringify(value) {
244
+ if (Array.isArray(value)) return `[${value.map((item) => stableStringify(item)).join(",")}]`;
245
+ if (value !== null && typeof value === "object") return `{${Object.entries(value).sort(([a], [b]) => a < b ? -1 : 1).map(([key, item]) => `${JSON.stringify(key)}:${stableStringify(item)}`).join(",")}}`;
246
+ return JSON.stringify(value) ?? "undefined";
247
+ }
248
+ function capturedEquals(a, b) {
249
+ if (Object.is(a, b)) return true;
250
+ if (typeof a === "number" && typeof b === "string" || typeof a === "string" && typeof b === "number") return String(a) === String(b);
251
+ if (a !== null && b !== null && typeof a === "object" && typeof b === "object") return stableStringify(a) === stableStringify(b);
252
+ return false;
253
+ }
254
+ function recordRef(name, actual, scope) {
255
+ if (scope.has(name)) return capturedEquals(scope.get(name), actual);
256
+ scope.set(name, actual);
257
+ return true;
258
+ }
259
+ function isPortValue(value) {
260
+ return Number.isInteger(value) && value >= 0 && value <= 65535;
261
+ }
262
+ function kindMatches(kind, actual, scope) {
263
+ switch (kind) {
264
+ case "any": return true;
265
+ case "float":
266
+ if (typeof actual === "number") return Number.isFinite(actual);
267
+ return typeof actual === "string" && WHOLE_RES.float.test(actual);
268
+ case "int":
269
+ if (typeof actual === "number") return Number.isInteger(actual);
270
+ return typeof actual === "string" && WHOLE_RES.int.test(actual);
271
+ case "number":
272
+ if (typeof actual === "number") return Number.isFinite(actual);
273
+ return typeof actual === "string" && WHOLE_RES.number.test(actual);
274
+ case "port":
275
+ if (typeof actual === "number") return isPortValue(actual);
276
+ return typeof actual === "string" && WHOLE_RES.port.test(actual) && isPortValue(Number(actual));
277
+ case "string": return typeof actual === "string";
278
+ case "workdir": return typeof actual === "string" && scope.workdir !== void 0 ? actual === scope.workdir : false;
279
+ default: {
280
+ const re = WHOLE_RES[kind];
281
+ return re !== void 0 && typeof actual === "string" && re.test(actual);
282
+ }
283
+ }
284
+ }
285
+ function matcherMatches(matcher, actual, scope) {
286
+ if (matcher.kind === "includes") return typeof actual === "string" && actual.includes(matcher.includes);
287
+ if (matcher.kind === "regex") return typeof actual === "string" && matcher.regex.test(actual);
288
+ if (matcher.kind === "ref") {
289
+ if (matcher.notRef && scope.has(matcher.notRef) && capturedEquals(scope.get(matcher.notRef), actual)) return false;
290
+ return recordRef(matcher.refName, actual, scope);
291
+ }
292
+ return kindMatches(matcher.kind, actual, scope);
293
+ }
294
+ function placeholderSource(kind, scope) {
295
+ if (kind === "workdir") return scope.workdir === void 0 ? "(?!)" : escapeRegExp(scope.workdir);
296
+ const source = EMBEDDED_SOURCES[kind];
297
+ if (source) return source;
298
+ return kind === "any" ? String.raw`[\s\S]*?` : String.raw`[^\n]*?`;
299
+ }
300
+ function escapeRegExp(text) {
301
+ return text.replaceAll(/[.*+?^${}()|[\]\\]/gu, String.raw`\$&`);
302
+ }
303
+ function parsePlaceholderString(expected, scope) {
304
+ PLACEHOLDER_RE.lastIndex = 0;
305
+ const refs = [];
306
+ let source = "";
307
+ let lastIndex = 0;
308
+ let single = null;
309
+ let count = 0;
310
+ for (const found of expected.matchAll(PLACEHOLDER_RE)) {
311
+ const kind = found.groups.kind;
312
+ const { ref } = found.groups;
313
+ source += escapeRegExp(expected.slice(lastIndex, found.index));
314
+ source += `(${placeholderSource(kind, scope)})`;
315
+ refs.push({
316
+ index: count,
317
+ kind,
318
+ ref
319
+ });
320
+ count++;
321
+ lastIndex = found.index + found[0].length;
322
+ if (found.index === 0 && found[0].length === expected.length) single = {
323
+ kind,
324
+ ref
325
+ };
326
+ }
327
+ source += escapeRegExp(expected.slice(lastIndex));
328
+ return {
329
+ pattern: new RegExp(`^${source}$`, "u"),
330
+ refs,
331
+ single,
332
+ source
333
+ };
334
+ }
335
+ /**
336
+ * Unanchored regex source matching a fixture string — plain text escaped
337
+ * verbatim, each `{{token}}` expanded to its embedded grammar. Used to route
338
+ * declared `.http` intercept paths (`/articles/{{uuid}}`) as URL patterns.
339
+ */
340
+ function placeholderPatternSource(expected) {
341
+ return parsePlaceholderString(expected, new CaptureScope()).source;
342
+ }
343
+ function placeholderStringMatches(expected, actual, scope) {
344
+ const parsed = parsePlaceholderString(expected, scope);
345
+ if (parsed.single) {
346
+ if (!kindMatches(parsed.single.kind, actual, scope)) return false;
347
+ if (parsed.single.ref) return recordRef(parsed.single.ref, actual, scope);
348
+ return true;
349
+ }
350
+ if (typeof actual !== "string" && typeof actual !== "number") return false;
351
+ const text = String(actual);
352
+ const found = parsed.pattern.exec(text);
353
+ if (!found) return false;
354
+ for (const entry of parsed.refs) {
355
+ if (!entry.ref) continue;
356
+ if (!recordRef(entry.ref, found[entry.index + 1], scope)) return false;
357
+ }
358
+ return true;
359
+ }
360
+ function isPlainObject(value) {
361
+ return value !== null && typeof value === "object" && !Array.isArray(value);
362
+ }
363
+ /**
364
+ * Deep structural equality with matcher / placeholder support. Ref captures
365
+ * are recorded in `scope` in traversal order (arrays left-to-right, object
366
+ * keys in expected-key order).
367
+ */
368
+ function structuralEquals(expected, actual, scope) {
369
+ if (expected instanceof Matcher) return matcherMatches(expected, actual, scope);
370
+ if (typeof expected === "string" && hasPlaceholders(expected)) return placeholderStringMatches(expected, actual, scope);
371
+ if (Array.isArray(expected)) {
372
+ if (!Array.isArray(actual) || actual.length !== expected.length) return false;
373
+ return expected.every((item, i) => structuralEquals(item, actual[i], scope));
374
+ }
375
+ if (isPlainObject(expected)) {
376
+ if (!isPlainObject(actual)) return false;
377
+ const expectedKeys = Object.keys(expected);
378
+ const actualKeys = Object.keys(actual);
379
+ if (expectedKeys.length !== actualKeys.length) return false;
380
+ return expectedKeys.every((key) => key in actual && structuralEquals(expected[key], actual[key], scope));
381
+ }
382
+ return Object.is(expected, actual);
383
+ }
384
+ /**
385
+ * Deep structural SUBSET match (toMatchObject-style) with matcher /
386
+ * placeholder support. Plain objects match when every expected key is present
387
+ * and recursively subset-matches — the actual value may carry extra keys.
388
+ * Arrays require equal length with each element subset-matched. Leaves fall
389
+ * back to {@link structuralEquals} semantics (matchers, placeholders, strict
390
+ * equality). Used by request-body filters on intercept triggers.
391
+ */
392
+ function structuralSubset(expected, actual, scope) {
393
+ if (expected instanceof Matcher) return matcherMatches(expected, actual, scope);
394
+ if (typeof expected === "string" && hasPlaceholders(expected)) return placeholderStringMatches(expected, actual, scope);
395
+ if (Array.isArray(expected)) {
396
+ if (!Array.isArray(actual) || actual.length !== expected.length) return false;
397
+ return expected.every((item, i) => structuralSubset(item, actual[i], scope));
398
+ }
399
+ if (isPlainObject(expected)) {
400
+ if (!isPlainObject(actual)) return false;
401
+ return Object.keys(expected).every((key) => key in actual && structuralSubset(expected[key], actual[key], scope));
402
+ }
403
+ return Object.is(expected, actual);
404
+ }
405
+ /**
406
+ * Multi-line text comparison with `{{token}}` support — used by text
407
+ * snapshots (`_expected/*.txt`). Without placeholders this is strict equality.
408
+ */
409
+ function textEquals(expected, actual, scope) {
410
+ if (!hasPlaceholders(expected)) return expected === actual;
411
+ return placeholderStringMatches(expected, actual, scope);
412
+ }
413
+ //#endregion
414
+ //#region src/specification/facets/_common/reporter.ts
415
+ const GREEN = "\x1B[32m";
416
+ const RED = "\x1B[31m";
417
+ const RESET = "\x1B[0m";
418
+ const strictEquals = (expected, actual) => expected === actual;
419
+ function renderLines(expectedLines, actualLines, equals) {
420
+ const rendered = [];
421
+ let marked = 0;
422
+ const maxLines = Math.max(expectedLines.length, actualLines.length);
423
+ for (let i = 0; i < maxLines; i++) {
424
+ const exp = expectedLines[i];
425
+ const act = actualLines[i];
426
+ if (exp !== void 0 && act !== void 0 && equals(exp, act)) {
427
+ rendered.push(` ${exp}`);
428
+ continue;
429
+ }
430
+ marked++;
431
+ if (exp !== void 0) rendered.push(`${GREEN}- ${exp}${RESET}`);
432
+ if (act !== void 0) rendered.push(`${RED}+ ${act}${RESET}`);
433
+ }
434
+ return {
435
+ marked,
436
+ rendered
437
+ };
438
+ }
439
+ /**
440
+ * Render an expected/received diff over two texts.
441
+ *
442
+ * `equals` is how a line is judged EQUAL. Callers that compare through the
443
+ * `{{token}}` grammar pass a token-aware predicate, so a `{{url}}` line that
444
+ * matched is shown as equal — with its token, not as a `-`/`+` pair against
445
+ * the concrete URL. Marking a line the comparison ACCEPTED buries the one it
446
+ * rejected: the reader then has to work out which of the differences is the
447
+ * actual cause.
448
+ *
449
+ * Safety net: if the token-aware pass marks nothing at all, the whole diff
450
+ * would render as a clean block against a failure that really happened (a
451
+ * `#ref` captured inconsistently across lines, say). The strict rendering is
452
+ * used instead, so a diff always shows the reader something.
453
+ */
454
+ function formatStdoutDiff(file, expected, actual, options) {
455
+ const lines = [];
456
+ lines.push(`Output mismatch (${file})`, "", `${GREEN}- Expected${RESET}`, `${RED}+ Received${RESET}`, "");
457
+ const expectedLines = expected.split("\n");
458
+ const actualLines = actual.split("\n");
459
+ const equals = options?.equals ?? strictEquals;
460
+ const first = renderLines(expectedLines, actualLines, equals);
461
+ const rendered = first.marked === 0 && equals !== strictEquals ? renderLines(expectedLines, actualLines, strictEquals).rendered : first.rendered;
462
+ return [...lines, ...rendered].join("\n");
463
+ }
464
+ //#endregion
465
+ //#region src/specification/facets/_common/result/text-assertions.ts
466
+ /** The fixture name carries its extension — the name IS the file. */
467
+ function requireExtension(name, subject) {
468
+ if (!/\.[A-Za-z0-9]+$/u.test(name)) throw new Error(`toMatch("${name}"): the extension is part of the name and is required for ${subject} subjects (e.g. "help.txt").`);
469
+ }
470
+ /**
471
+ * Compare a captured stream against the CONTENT of its golden. Text snapshots
472
+ * share the unified `{{token}}` grammar (CONVENTIONS D4), and the diff judges
473
+ * each line through the SAME grammar the comparison used — so a token line
474
+ * that matched is shown as equal instead of competing with the real mismatch
475
+ * for the reader's attention.
476
+ */
477
+ function compareStreamText(accessor, name, expected) {
478
+ const actual = accessor.comparableText;
479
+ if (textEquals(expected, actual, accessor.captures)) return {
480
+ message: () => `expected ${accessor.streamName} not to match _expected/${name}`,
481
+ pass: true
482
+ };
483
+ return {
484
+ message: () => formatStdoutDiff(name, expected, actual, { equals: (expectedLine, actualLine) => textEquals(expectedLine, actualLine, new CaptureScope(accessor.captures.workdir)) }),
485
+ pass: false
486
+ };
487
+ }
488
+ /** `expect(stream).toBeEmpty()` — the stream you usually want silent. */
489
+ function textIsEmpty(accessor) {
490
+ const content = accessor.comparableText;
491
+ const pass = content === "";
492
+ return {
493
+ message: () => pass ? `expected ${accessor.streamName} not to be empty` : `Expected ${accessor.streamName} to be empty, but it contains:\n${content}`,
494
+ pass
495
+ };
496
+ }
497
+ /** `expect(stream).toContain('…')` — the scalpel, never the default (D11). */
498
+ function textContains(accessor, expected) {
499
+ const actual = accessor.comparableText;
500
+ const pass = actual.includes(expected);
501
+ return {
502
+ message: () => pass ? `expected ${accessor.streamName} not to contain ${JSON.stringify(expected)}` : `${accessor.streamName} does not contain expected substring.\n expected to contain: ${JSON.stringify(expected)}\n actual: ${JSON.stringify(actual.length > 500 ? `${actual.slice(0, 500)}…` : actual)}`,
503
+ pass
504
+ };
505
+ }
506
+ /**
507
+ * `toMatch` and `toContain` on a subject that is NOT an accessor.
508
+ *
509
+ * Both matchers are overridden globally, for every subject in the project, so
510
+ * whatever the framework does not own has to keep meaning what vitest's own
511
+ * matcher meant. Stated once here because the two builds register two different
512
+ * `expect.extend` calls: a copy in the page is how `expect(['ab']).toContain('b')`
513
+ * ends up passing on one side of the seam and failing on the other.
514
+ */
515
+ /** vitest's `toMatch` for a plain string: a substring, or a regular expression. */
516
+ function nativeMatch(received, expected) {
517
+ if (typeof received !== "string") throw new TypeError("toMatch: unsupported subject — expected a stream, json, response, filesystem, or directory accessor, or a string.");
518
+ const pass = expected instanceof RegExp ? expected.test(received) : received.includes(String(expected));
519
+ return {
520
+ message: () => `expected ${JSON.stringify(received)} ${pass ? "not " : ""}to match ${String(expected)}`,
521
+ pass
522
+ };
523
+ }
524
+ /** vitest's `toContain` for a plain string (substring) or an iterable (membership). */
525
+ function nativeContain(received, expected) {
526
+ if (typeof received === "string") {
527
+ const pass = received.includes(String(expected));
528
+ return {
529
+ message: () => `expected ${JSON.stringify(received)} ${pass ? "not " : ""}to contain ${JSON.stringify(expected)}`,
530
+ pass
531
+ };
532
+ }
533
+ if (isIterable(received)) {
534
+ const pass = [...received].includes(expected);
535
+ return {
536
+ message: () => `expected iterable ${pass ? "not " : ""}to contain ${JSON.stringify(expected)}`,
537
+ pass
538
+ };
539
+ }
540
+ throw new TypeError(`toContain: unsupported subject of type ${typeof received} — expected a stream accessor, string, or iterable.`);
541
+ }
542
+ /** Does this value hand out its members? A Set and an array both do; a DOM node does not. */
543
+ function isIterable(value) {
544
+ return value !== null && value !== void 0 && typeof value[Symbol.iterator] === "function";
545
+ }
546
+ //#endregion
547
+ //#region src/specification/facets/_common/result/grep.ts
548
+ /**
549
+ * Extract text blocks from output that contain a pattern.
550
+ * Splits by blank lines (how linter/compiler output is structured),
551
+ * returns only blocks matching the pattern.
552
+ *
553
+ * @example
554
+ * expect(grep(result.stdout, "unused-var.ts")).toContain("no-unused-vars")
555
+ * expect(grep(result.stdout, "valid/sorted.ts")).not.toContain("sort-imports")
556
+ */
557
+ function grep(output, pattern) {
558
+ return output.replaceAll(/\u001B\[[0-9;]*m/gu, "").split(/\n\s*\n/u).filter((block) => block.includes(pattern)).join("\n\n");
559
+ }
560
+ //#endregion
561
+ //#region src/specification/facets/_common/result/text.ts
562
+ const ANSI_RE = /\u001B\[[0-9;]*m/gu;
563
+ /** Strip ANSI escape sequences from a string. */
564
+ function stripAnsiCodes(value) {
565
+ return value.replace(ANSI_RE, "");
566
+ }
567
+ /**
568
+ * Read-only accessor for a captured text handle — THE universal one: stdout,
569
+ * stderr, container logs, and file text all surface as a `TextAccessor`.
570
+ *
571
+ * Backed by a primitive string, exposed via {@link text}, but also provides
572
+ * `toString()` / `valueOf()` for string coercion, so common patterns like
573
+ * `String(result.stdout)` and template-literal interpolation still work.
574
+ *
575
+ * ANSI escape sequences are stripped by default before every comparison
576
+ * (CONVENTIONS D6) — `.text` stays raw. The runner `transform` option remains
577
+ * an escape hatch for application noise not covered by the `{{token}}`
578
+ * grammar.
579
+ *
580
+ * Text operations are **closed** over the type: `.grep(pattern)` returns a
581
+ * `TextAccessor` (not a bare string), preserving the `_expected/`-resolution
582
+ * context and the `transform`, so results are chainable
583
+ * (`result.stdout.grep(a).grep(b)`) and snapshot-able
584
+ * (`expect(result.stdout.grep('users.ts')).toMatch('block.txt')`).
585
+ *
586
+ * Assertions go through `expect()` matchers: `expect(result.stdout).toContain(...)`
587
+ * and `expect(result.stdout).toMatch('name.txt')` (resolved against
588
+ * `_expected/<name>`, flat — with `{{token}}` support, CONVENTIONS D4).
589
+ */
590
+ var TextAccessor = class TextAccessor {
591
+ /** @internal Ref-capture scope shared by the current spec execution. */
592
+ captures;
593
+ /** @internal Stream label used in failure messages ("stdout" / "stderr"). */
594
+ streamName;
595
+ /** @internal Test-file directory — fixture resolution root for matchers. */
596
+ testDir;
597
+ /** The raw captured text (never transformed, ANSI preserved). */
598
+ text;
599
+ /** @internal Normaliser applied before comparisons, never to fixtures. */
600
+ transform;
601
+ constructor(value, streamName, testDir, options = {}) {
602
+ this.text = value;
603
+ this.streamName = streamName;
604
+ this.testDir = testDir;
605
+ this.transform = options.transform;
606
+ this.captures = options.captures ?? new CaptureScope();
607
+ }
608
+ /** @internal The text as compared by matchers — ANSI stripped, transform applied. */
609
+ get comparableText() {
610
+ const stripped = stripAnsiCodes(this.text);
611
+ return this.transform ? this.transform(stripped) : stripped;
612
+ }
613
+ /**
614
+ * Keep only the blank-line-separated blocks of the text that contain
615
+ * `pattern` (how linter/compiler output is structured), returned as a new
616
+ * `TextAccessor` — the same subject type, so the result is chainable and
617
+ * snapshot-able. The scalpel for probing large tool outputs; snapshot the
618
+ * whole surface by default, reach for `.grep()` for targeted checks.
619
+ */
620
+ grep(pattern) {
621
+ return new TextAccessor(grep(this.text, pattern), this.streamName, this.testDir, {
622
+ captures: this.captures,
623
+ transform: this.transform
624
+ });
625
+ }
626
+ toString() {
627
+ return this.text;
628
+ }
629
+ valueOf() {
630
+ return this.text;
631
+ }
632
+ };
633
+ //#endregion
634
+ //#region src/specification/facets/website/ambiguity.ts
635
+ /**
636
+ * The ambiguity refusal — CONVENTIONS W3.
637
+ *
638
+ * A visit descriptor must designate exactly one element. Acting on "the
639
+ * first match" is the failure mode this module exists to prevent: the spec
640
+ * keeps passing while the visitor clicks something else, and nothing ever
641
+ * reports it. So when a descriptor matches several elements the framework
642
+ * refuses, and the refusal has to carry everything needed to fix it without
643
+ * opening a browser — the descriptor in the caller's own vocabulary, every
644
+ * candidate, and the concrete rewrites that would resolve it.
645
+ *
646
+ * Pure string building: it takes captured data and returns a message, so the
647
+ * wording is unit-testable and the browser integration stays a thin adapter.
648
+ */
649
+ /** `kind` → the constructor that builds it, so errors echo the caller's source. */
650
+ const CONSTRUCTORS = {
651
+ banner: "banner",
652
+ button: "button",
653
+ complementary: "complementary",
654
+ contentinfo: "contentinfo",
655
+ dialog: "dialog",
656
+ field: "field",
657
+ form: "form",
658
+ heading: "heading",
659
+ link: "link",
660
+ listitem: "listitem",
661
+ main: "main",
662
+ navigation: "navigation",
663
+ option: "option",
664
+ region: "region",
665
+ row: "row",
666
+ search: "search",
667
+ status: "status",
668
+ table: "table",
669
+ testId: "testId",
670
+ text: "content"
671
+ };
672
+ /** The landmark a context string maps back to, for a copy-pasteable suggestion. */
673
+ const CONTEXT_LANDMARKS = {
674
+ aside: "complementary()",
675
+ banner: "banner()",
676
+ complementary: "complementary()",
677
+ contentinfo: "contentinfo()",
678
+ footer: "contentinfo()",
679
+ form: "form()",
680
+ header: "banner()",
681
+ main: "main()",
682
+ nav: "navigation()",
683
+ navigation: "navigation()",
684
+ search: "search()"
685
+ };
686
+ /**
687
+ * Render a descriptor as the source that would build it — `link('Articles')`,
688
+ * `within(navigation(), link('Articles', { exact: true }))`. The error speaks
689
+ * the vocabulary the author wrote, never playwright's.
690
+ */
691
+ function formatElement(element) {
692
+ const bare = formatBare(element);
693
+ return element.scope ? `within(${formatElement(element.scope)}, ${bare})` : bare;
694
+ }
695
+ function formatBare(element) {
696
+ const args = [];
697
+ if (element.name !== void 0) args.push(JSON.stringify(element.name));
698
+ if (element.exact) args.push("{ exact: true }");
699
+ return `${CONSTRUCTORS[element.kind]}(${args.join(", ")})`;
700
+ }
701
+ /** `1. <a href="/articles">Articles</a> in <nav>` — one evidence line per candidate. */
702
+ function formatMatch(match, index) {
703
+ const attribute = match.detail ? ` ${quoteDetail(match)}` : "";
704
+ const named = match.accessibleName ? ` named ${JSON.stringify(match.accessibleName)}` : "";
705
+ const context = match.context ? ` in <${match.context}>` : "";
706
+ return ` ${index + 1}. <${match.tag}${attribute}>${match.text}</${match.tag}>${named}${context}`;
707
+ }
708
+ function quoteDetail(match) {
709
+ return `${match.tag === "a" ? "href" : "name"}=${JSON.stringify(match.detail)}`;
710
+ }
711
+ /** Each landmark the candidates sit in, and how many of them it holds. */
712
+ function landmarkCounts(matches) {
713
+ const counts = /* @__PURE__ */ new Map();
714
+ for (const match of matches) {
715
+ const landmark = match.context === void 0 ? void 0 : CONTEXT_LANDMARKS[match.context];
716
+ if (landmark !== void 0) counts.set(landmark, (counts.get(landmark) ?? 0) + 1);
717
+ }
718
+ return [...counts].toSorted(([, a], [, b]) => a - b);
719
+ }
720
+ /**
721
+ * The rewrites worth offering, in the order they should be tried. Scoping is
722
+ * always available; `exact` only when it would actually narrow the set, and
723
+ * the count it would leave is stated so a still-ambiguous suggestion never
724
+ * reads as a fix.
725
+ */
726
+ function formatFixes(element, matches) {
727
+ const fixes = [];
728
+ const narrowing = landmarkCounts(matches).filter(([, count]) => count < matches.length);
729
+ if (!element.scope) {
730
+ const [first, ...rest] = narrowing;
731
+ const alsoHere = rest.length > 0 ? ` [also here: ${rest.map(([name]) => name).join(", ")}]` : "";
732
+ fixes.push(first === void 0 ? `scope it within(<a container holding only this one>, ${formatBare(element)})` : `scope it within(${first[0]}, ${formatBare(element)}) [leaves ${first[1]} of ${matches.length}]${alsoHere}`);
733
+ }
734
+ if (!element.exact && element.name !== void 0) {
735
+ const remaining = matches.filter((match) => match.text === element.name).length;
736
+ if (remaining > 0 && remaining < matches.length) fixes.push(`exact name ${formatBare({
737
+ ...element,
738
+ exact: true
739
+ })} [leaves ${remaining} of ${matches.length}]`);
740
+ }
741
+ fixes.push("other element a heading(), button() or field() may name one thing where this does not");
742
+ return fixes;
743
+ }
744
+ /**
745
+ * The W3 refusal. A distinct class so the visit wrapper can recognize an
746
+ * already-complete message and let it through instead of nesting it inside
747
+ * `visit scenario failed: …`, which would print the whole thing twice.
748
+ */
749
+ var AmbiguousElementError = class extends Error {
750
+ name = "AmbiguousElementError";
751
+ };
752
+ /**
753
+ * Build the refusal thrown when a descriptor matches more than one element.
754
+ *
755
+ * @param options.element The descriptor as the caller wrote it.
756
+ * @param options.matches Every candidate, in DOM order (already truncated).
757
+ * @param options.url The page the visitor was on when it happened.
758
+ */
759
+ function describeAmbiguity(options) {
760
+ const { element, matches, url } = options;
761
+ const fixes = formatFixes(element, matches).map((fix) => ` • ${fix}`);
762
+ return [
763
+ `Ambiguous element: ${formatElement(element)} matched ${matches.length} elements on ${url}.`,
764
+ "",
765
+ "A spec must designate exactly one element. Acting on the first match would let",
766
+ "this test keep passing while the visitor interacts with something else.",
767
+ "",
768
+ "Matched:",
769
+ ...matches.map((match, index) => formatMatch(match, index)),
770
+ "",
771
+ "Disambiguate with one of:",
772
+ ...fixes,
773
+ "",
774
+ "Docs: docs/14-website.md#designating-exactly-one-element (CONVENTIONS W3)"
775
+ ].join("\n");
776
+ }
777
+ //#endregion
778
+ //#region src/integrations/vitest-browser/vitest-browser.adapter.ts
779
+ /**
780
+ * The browser-mode adapter — the component facet's half of the one element
781
+ * vocabulary.
782
+ *
783
+ * Its translation table is the playwright adapter's, descriptor for
784
+ * descriptor: a `button('Save')` means `getByRole('button', { name })` whether
785
+ * the surface is a served page or a mounted component, and the W3 refusal
786
+ * enumerates candidates in the same words. Two adapters, one dialect — which
787
+ * is the whole reason a page spec and a component spec read alike.
788
+ *
789
+ * What differs is where the code runs. Playwright drives a page from the
790
+ * outside and reads it through `evaluate`; here the test IS in the page, so a
791
+ * candidate is described from the live element and the ARIA tree is the one
792
+ * thing that has to go back out (`server.commands`, the provider's own frame).
793
+ */
794
+ /** How many candidates the ambiguity error enumerates before truncating. */
795
+ const MAX_REPORTED_MATCHES = 10;
796
+ /** The landmark ancestors the ambiguity evidence names. */
797
+ const LANDMARKS = "nav, header, footer, main, aside, section, form, [role]";
798
+ /**
799
+ * Translate a user-facing descriptor into a Browser Mode locator, resolving
800
+ * `scope` outside-in so `within(navigation(), link('X'))` searches the nav
801
+ * subtree. No `.first()` anywhere: designating exactly one element is
802
+ * CONVENTIONS W3, and taking the first match is the silent wrong-element bug
803
+ * the rule exists to prevent.
804
+ */
805
+ function locate(root, element) {
806
+ const scope = element.scope ? locate(root, element.scope) : root;
807
+ const exact = element.exact ?? false;
808
+ const name = element.name ?? "";
809
+ if (element.kind === "field") return scope.getByLabelText(name, { exact });
810
+ if (element.kind === "testId") return scope.getByTestId(name);
811
+ if (element.kind === "text") return scope.getByText(name, { exact });
812
+ return scope.getByRole(element.kind, element.name === void 0 ? { exact } : {
813
+ exact,
814
+ name: element.name
815
+ });
816
+ }
817
+ /** Describe the live candidates — the evidence the W3 refusal enumerates. */
818
+ function candidates(locator) {
819
+ return locator.elements().slice(0, MAX_REPORTED_MATCHES).map((node) => {
820
+ const landmark = node.parentElement?.closest(LANDMARKS);
821
+ const context = landmark?.getAttribute("role") ?? landmark?.tagName.toLowerCase();
822
+ const detail = node.getAttribute("href") ?? node.getAttribute("name");
823
+ const text = (node.textContent ?? "").replaceAll(/\s+/gu, " ").trim().slice(0, 80);
824
+ const label = node.getAttribute("aria-label")?.trim();
825
+ return {
826
+ accessibleName: label !== void 0 && label !== text ? label : void 0,
827
+ context: context ?? void 0,
828
+ detail: detail ?? void 0,
829
+ tag: node.tagName.toLowerCase(),
830
+ text
831
+ };
832
+ });
833
+ }
834
+ /** Walk the scope chain outside-in; the outermost ambiguous level is the fault. */
835
+ function ambiguousLevel(element) {
836
+ const chain = [];
837
+ for (let current = element; current; current = current.scope) chain.unshift(current);
838
+ for (const level of chain.slice(0, -1)) if (locate(page, level).elements().length > 1) return level;
839
+ return element;
840
+ }
841
+ /**
842
+ * Run one visitor action, turning "more than one match" into the W3 refusal.
843
+ * The ambiguous LEVEL is identified first: a scope matching several landmarks
844
+ * is the real fault, and naming the target would send the author to fix the
845
+ * wrong descriptor.
846
+ */
847
+ async function act(element, action) {
848
+ const locator = locate(page, element);
849
+ try {
850
+ return await action(locator);
851
+ } catch (error) {
852
+ if (locator.elements().length <= 1) throw error;
853
+ const culprit = ambiguousLevel(element);
854
+ const matches = candidates(locate(page, culprit));
855
+ const url = globalThis.location.href;
856
+ throw new AmbiguousElementError(describeAmbiguity({
857
+ element: culprit,
858
+ matches,
859
+ url
860
+ }));
861
+ }
862
+ }
863
+ /**
864
+ * Is this descriptor answered by PRESENCE rather than by visibility?
865
+ *
866
+ * The options of a collapsed `<select>` are in the document and in the
867
+ * accessibility tree, and not one of them has a box on the screen — asking
868
+ * whether an option is visible would answer "no" for every select a visitor
869
+ * never opened.
870
+ */
871
+ function byPresence(element) {
872
+ return element.kind === "option";
873
+ }
874
+ /** A control's live value — the property, never the attribute. */
875
+ function valueOf(node) {
876
+ return node instanceof HTMLInputElement || node instanceof HTMLSelectElement || node instanceof HTMLTextAreaElement ? node.value : void 0;
877
+ }
878
+ /**
879
+ * Is the element gone — or, with a state modifier, no longer in that state? A
880
+ * node that left the document and one that is still there but not rendered are
881
+ * the same answer to a spec.
882
+ */
883
+ function isGone(locator, element) {
884
+ const node = locator.query();
885
+ if (element.focused === true) return node !== document.activeElement;
886
+ if (element.disabled !== void 0) return node === null || node.matches(":disabled") !== element.disabled;
887
+ if (element.selected !== void 0) return node === null || node.matches(":checked") !== element.selected;
888
+ if (element.value !== void 0) return node === null || valueOf(node) !== element.value;
889
+ return node === null || (byPresence(element) ? false : !node.checkVisibility());
890
+ }
891
+ /**
892
+ * How long `gone()` waits — what is LEFT of the running test's budget.
893
+ *
894
+ * Every other verb already gets it: a locator action and `expect.element`
895
+ * default their timeout to the remaining budget, and only a bare
896
+ * `expect.poll` falls back to vitest's one second. That second made `gone()`
897
+ * the one verb that could not outlast a slow answer — a button taken off the
898
+ * screen when a two-second request returns was "still on the screen".
899
+ *
900
+ * The 100ms margin is vitest's own: the poll has to give up just BEFORE the
901
+ * test does, or the failure is a bare timeout naming no element.
902
+ */
903
+ function remainingBudget() {
904
+ const current = TestRunner.getCurrentTest();
905
+ const started = current?.result?.startTime;
906
+ if (current === void 0 || started === void 0) return;
907
+ return Math.max(current.timeout - (Date.now() - started) - 100, 0);
908
+ }
909
+ /** `expect.poll` over that budget — the retry the matchers get for free. */
910
+ function polling(probe, message) {
911
+ const timeout = remainingBudget();
912
+ return expect.poll(probe, {
913
+ message,
914
+ ...timeout === void 0 ? {} : { timeout }
915
+ });
916
+ }
917
+ /** A key name is a key; a single character is typed as itself. */
918
+ function keystroke(key) {
919
+ return key.length > 1 ? `{${key}}` : key;
920
+ }
921
+ /** The verbs a rendered surface shares with a page, plus the two a parent owns. */
922
+ function componentVerbs(surface) {
923
+ return {
924
+ check: async (element) => {
925
+ await act(element, async (locator) => {
926
+ const node = locator.element();
927
+ if (!(node instanceof HTMLInputElement) || !node.checked) await locator.click();
928
+ });
929
+ },
930
+ click: async (element) => {
931
+ await act(element, async (locator) => {
932
+ await locator.click();
933
+ });
934
+ },
935
+ fill: async (element, value) => {
936
+ await act(element, async (locator) => {
937
+ await locator.fill(value);
938
+ });
939
+ },
940
+ gone: async (element) => {
941
+ await act(element, async (locator) => {
942
+ await polling(() => isGone(locator, element), `${formatElement(element)} is still on the screen`).toBeTruthy();
943
+ });
944
+ },
945
+ hover: async (element) => {
946
+ await act(element, async (locator) => {
947
+ await locator.hover();
948
+ });
949
+ },
950
+ press: async (key) => {
951
+ await userEvent.keyboard(keystroke(key));
952
+ },
953
+ rerender: surface.rerender,
954
+ see: async (element) => {
955
+ await act(element, async (locator) => {
956
+ if (element.focused === true) {
957
+ await expect.element(locator).toHaveFocus();
958
+ return;
959
+ }
960
+ if (element.disabled === true) {
961
+ await expect.element(locator).toBeDisabled();
962
+ return;
963
+ }
964
+ if (element.disabled === false) {
965
+ await expect.element(locator).toBeEnabled();
966
+ return;
967
+ }
968
+ if (element.selected !== void 0) {
969
+ await polling(() => locator.query()?.matches(":checked") === true, `${formatElement(element)} is not the selected one`).toBe(element.selected);
970
+ return;
971
+ }
972
+ if (element.value !== void 0) {
973
+ await expect.element(locator).toHaveValue(element.value);
974
+ return;
975
+ }
976
+ if (byPresence(element)) {
977
+ await expect.element(locator).toBeInTheDocument();
978
+ return;
979
+ }
980
+ await expect.element(locator).toBeVisible();
981
+ });
982
+ },
983
+ select: async (element, option) => {
984
+ await act(element, async (locator) => {
985
+ await locator.selectOptions(option);
986
+ });
987
+ },
988
+ unmount: surface.unmount
989
+ };
990
+ }
991
+ /** The ARIA snapshot of the rendered `<body>` — the golden a tree is asserted as. */
992
+ async function ariaTree() {
993
+ return await commands.ariaTree();
994
+ }
995
+ /** A golden's content, read server-side from `_expected/` beside the test. */
996
+ async function readGolden(name) {
997
+ return await commands.goldenRead(name);
998
+ }
999
+ /** Write a golden server-side, and say where — update mode's half. */
1000
+ async function writeGolden(name, content) {
1001
+ return await commands.goldenWrite(name, content);
1002
+ }
1003
+ /** Mount a React subject through the optional `vitest-browser-react` adapter. */
1004
+ async function mountReact(ui) {
1005
+ let render;
1006
+ try {
1007
+ ({render} = await import("vitest-browser-react"));
1008
+ } catch (error) {
1009
+ throw new Error(`component.render(<X />) needs vitest-browser-react and react (optional peers): npm install -D vitest-browser-react react react-dom (${String(error)})`, { cause: error });
1010
+ }
1011
+ const rendered = await render(ui);
1012
+ return {
1013
+ container: rendered.container,
1014
+ rerender: rendered.rerender,
1015
+ unmount: rendered.unmount
1016
+ };
1017
+ }
1018
+ /**
1019
+ * Mount a vanilla DOM subject: the function is handed a fresh container and
1020
+ * may return its own teardown — the shape a DOM library states one in. There
1021
+ * is no react here, and no react is loaded.
1022
+ */
1023
+ function mountDom(mount) {
1024
+ const container = document.createElement("div");
1025
+ document.body.append(container);
1026
+ const teardown = mount(container);
1027
+ return {
1028
+ container,
1029
+ rerender: () => {
1030
+ throw new Error("rerender() replaces a React tree; a DOM function is re-rendered by calling it again in a new render().");
1031
+ },
1032
+ unmount: async () => {
1033
+ teardown?.();
1034
+ container.remove();
1035
+ await Promise.resolve();
1036
+ }
1037
+ };
1038
+ }
1039
+ //#endregion
1040
+ //#region src/integrations/vitest-browser/golden.ts
1041
+ /** Update mode crosses the seam as a provided value, never as an env read. */
1042
+ function updating() {
1043
+ return inject("update") === true;
1044
+ }
1045
+ async function matchGolden(accessor, name, frozen) {
1046
+ requireExtension(name, "stream");
1047
+ const actual = accessor.comparableText;
1048
+ const stored = await readGolden(name);
1049
+ if (stored === null) {
1050
+ if (updating() && !frozen) {
1051
+ const path = await writeGolden(name, actual);
1052
+ return {
1053
+ message: () => `wrote ${path}`,
1054
+ pass: true
1055
+ };
1056
+ }
1057
+ return {
1058
+ message: () => `${accessor.streamName} fixture "${name}" does not exist under ${GROUND_EXPECTED}/ beside this test.\nRun with TEST_UPDATE=1 (or vitest -u) to create it.`,
1059
+ pass: false
1060
+ };
1061
+ }
1062
+ const comparison = compareStreamText(accessor, name, stored);
1063
+ if (!comparison.pass && updating() && !frozen) {
1064
+ await writeGolden(name, actual);
1065
+ return {
1066
+ message: () => `updated ${GROUND_EXPECTED}/${name}`,
1067
+ pass: true
1068
+ };
1069
+ }
1070
+ return comparison;
1071
+ }
1072
+ async function toMatch(received, expected, options) {
1073
+ if (received instanceof TextAccessor) {
1074
+ if (typeof expected !== "string") throw new TypeError("toMatch on accessors takes a fixture name (extension included) — for a regex, assert on the raw text instead: expect(x.text).toMatch(/re/).");
1075
+ return await matchGolden(received, expected, options?.frozen === true);
1076
+ }
1077
+ return nativeMatch(received, expected);
1078
+ }
1079
+ function toContain(received, expected) {
1080
+ if (received instanceof TextAccessor) return textContains(received, String(expected));
1081
+ return nativeContain(received, expected);
1082
+ }
1083
+ function toBeEmpty(received) {
1084
+ if (!(received instanceof TextAccessor)) throw new TypeError("toBeEmpty: unsupported subject — expected a text accessor.");
1085
+ return textIsEmpty(received);
1086
+ }
1087
+ let registered = false;
1088
+ /**
1089
+ * Register the page's matchers with vitest's `expect`. Idempotent, and called
1090
+ * from the browser entry itself: a component test imports `@jterrazz/test` to
1091
+ * get `component`, and that import IS the registration.
1092
+ */
1093
+ function registerBrowserMatchers() {
1094
+ if (registered) return;
1095
+ registered = true;
1096
+ expect.extend({
1097
+ toBeEmpty,
1098
+ toContain,
1099
+ toMatch
1100
+ });
1101
+ }
1102
+ //#endregion
1103
+ //#region src/browser/node-only.ts
1104
+ /**
1105
+ * The refusals the browser build ships in place of what only node can do.
1106
+ *
1107
+ * `@jterrazz/test` has ONE specifier and two runtimes, so the page gets the
1108
+ * same NAMES as the server: a component test that reaches for
1109
+ * `specification.api()` or `postgres()` fails on the line that reached, saying
1110
+ * where that name runs — not on an unresolved import three layers down, and
1111
+ * not silently on `undefined`.
1112
+ */
1113
+ /**
1114
+ * The refusal, in one line, whatever the name. Returns `never`, so a stub is
1115
+ * an ordinary arrow function the page's entry annotates with the node
1116
+ * signature — no cast, and no way for the two surfaces to disagree.
1117
+ */
1118
+ function refuse(name) {
1119
+ throw new Error(`${name} runs under node: a page has no filesystem, no child process and no socket. Specify it from a test collected by a node project (unit/api/jobs/cli/website/mobile); a rendered thing is a \`.test.tsx\` beside its component.`);
1120
+ }
1121
+ /**
1122
+ * A node-only CLASS, present under the same name. A class has a shape a stub
1123
+ * cannot honour — every instance member of the real one — so this is the one
1124
+ * place the page's entry states a type it does not structurally satisfy; what
1125
+ * the value can actually do is throw, which is the whole of the contract.
1126
+ *
1127
+ * The stub is a constructible FUNCTION, never an arrow: `new` on an arrow
1128
+ * throws "is not a constructor" before the refusal can run, so the page would
1129
+ * lose the one thing the stub exists to say — which name it reached for.
1130
+ */
1131
+ const nodeOnlyClass = (name) => function NodeOnly() {
1132
+ return refuse(name);
1133
+ };
1134
+ //#endregion
1135
+ //#region src/specification/contracts/contract.ts
1136
+ /**
1137
+ * Declare one contract. Identity function — its value is the enforced shape
1138
+ * and the naming convention:
1139
+ *
1140
+ * @example
1141
+ * // specs/api/reports/contracts/openai/classify-article.ts
1142
+ * import { defineContract, openai } from '@jterrazz/test';
1143
+ *
1144
+ * export default defineContract({
1145
+ * request: openai.responses({ user: PROMPT, tools: ['classify'] }),
1146
+ * response: openai.reply({ categories: ['TECH'] }),
1147
+ * });
1148
+ *
1149
+ * // Dynamic — the response is computed from the observed request:
1150
+ * export default defineContract({
1151
+ * request: http.post('https://api.example.com/echo'),
1152
+ * response: (request) => http.json({ received: request.body }),
1153
+ * });
1154
+ */
1155
+ function defineContract(contract) {
1156
+ return contract;
1157
+ }
1158
+ /** Is this a {@link Contracts} composite (rather than a contract or a list)? */
1159
+ function isContracts(value) {
1160
+ return typeof value === "object" && value !== null && Array.isArray(value.contracts) && typeof value.with === "function";
1161
+ }
1162
+ /** Is this a single {@link Contract} (rather than a bare request half)? */
1163
+ function isContract(value) {
1164
+ return typeof value === "object" && value !== null && "request" in value && "response" in value;
1165
+ }
1166
+ /**
1167
+ * The route a contract claims — method + the DECLARED url source. Two
1168
+ * contracts share a route when they would be written on the same line of a
1169
+ * declaration: same method, same url pattern (`.source` for a RegExp).
1170
+ */
1171
+ function routeKeyOf(contract) {
1172
+ const { method, url } = contract.request;
1173
+ return url instanceof RegExp ? `${method} re:${url.source}` : `${method} str:${url}`;
1174
+ }
1175
+ /** Human-readable route of a contract — used in every failure message. */
1176
+ function describeRoute(contract) {
1177
+ const { method, url } = contract.request;
1178
+ return `${method === "*" ? "ANY" : method} ${url instanceof RegExp ? String(url) : url}`;
1179
+ }
1180
+ /** Flatten contracts, lists, and composites into one ordered list. */
1181
+ function flatten(items) {
1182
+ const flat = [];
1183
+ for (const item of items) if (Array.isArray(item)) flat.push(...flatten(item));
1184
+ else if (isContracts(item)) flat.push(...item.contracts);
1185
+ else flat.push(item);
1186
+ return flat;
1187
+ }
1188
+ /**
1189
+ * Compose contracts into the artifact a test imports — it's contracts all the
1190
+ * way down: a composite may extend contracts, lists, and other composites,
1191
+ * recursively, order preserved.
1192
+ *
1193
+ * `.with(...)` derives a scenario: contracts whose route the overrides claim
1194
+ * are removed from the base, and the overrides are prepended. Under
1195
+ * first-match selection a more specific override (`/articles/gone-1`) also
1196
+ * wins over a generic base route (`/articles/{{uuid}}`) it does not replace.
1197
+ *
1198
+ * @example
1199
+ * // contracts/newsroom.contracts.ts
1200
+ * export default defineContracts(events, articleById);
1201
+ * export const withArticleGone = (id: string) =>
1202
+ * newsroom.with(articleGone(id));
1203
+ */
1204
+ function defineContracts(...items) {
1205
+ const contracts = Object.freeze(flatten(items));
1206
+ return {
1207
+ contracts,
1208
+ with(...overrides) {
1209
+ const added = flatten(overrides);
1210
+ const claimed = new Set(added.map(routeKeyOf));
1211
+ const kept = contracts.filter((contract) => !claimed.has(routeKeyOf(contract)));
1212
+ return defineContracts([...added, ...kept]);
1213
+ }
1214
+ };
1215
+ }
1216
+ /** Normalize any accepted input into a flat contract list. */
1217
+ function contractsOf(input) {
1218
+ return flatten([input]);
1219
+ }
1220
+ //#endregion
1221
+ //#region src/specification/contracts/queue.ts
1222
+ /**
1223
+ * The ONE contract queue — pure, engine-agnostic (no MSW, no node:http).
1224
+ * Both engines consume it: the MSW integration on api/jobs chains, and the
1225
+ * declared stub backend on website/mobile chains.
1226
+ *
1227
+ * Selection: the FIRST contract in declaration order that matches the observed
1228
+ * request and is not exhausted. A contract with no `times` is unlimited (a
1229
+ * re-render or a retry replays it); `times: n` is spent after n serves, so an
1230
+ * ordered sequence is written as finite contracts before an unlimited tail:
1231
+ * `[error500 ×3, ok]`.
1232
+ *
1233
+ * Strictness (CONVENTIONS D7): when nothing matches — including "everything
1234
+ * that matches is exhausted" — the engine answers 501, records the request,
1235
+ * and the chain fails with {@link ContractQueue.unmatchedError}. A chain that
1236
+ * declared zero contracts is not guarded at all (unchanged boundary).
1237
+ */
1238
+ /** Base used to parse origin-relative observed URLs (`/events?x=1`). */
1239
+ const RELATIVE_BASE = "http://contract.invalid";
1240
+ /** Split a declared url into its base (origin+path, or path) and query halves.
1241
+ * Never through `new URL()`, which would percent-encode `{{token}}` braces. */
1242
+ function splitDeclared(url) {
1243
+ const separator = url.indexOf("?");
1244
+ if (separator === -1) return {
1245
+ base: url,
1246
+ query: new URLSearchParams()
1247
+ };
1248
+ return {
1249
+ base: url.slice(0, separator),
1250
+ query: new URLSearchParams(url.slice(separator + 1))
1251
+ };
1252
+ }
1253
+ /** Decode percent-escapes, falling back to the raw text on malformed input. */
1254
+ function safeDecode(text) {
1255
+ try {
1256
+ return decodeURIComponent(text);
1257
+ } catch {
1258
+ return text;
1259
+ }
1260
+ }
1261
+ /** Token-aware comparison of one declared value against an observed one. */
1262
+ function valueMatches(declared, observed) {
1263
+ return textEquals(declared, observed, new CaptureScope());
1264
+ }
1265
+ /**
1266
+ * Does an observed URL satisfy a declared one? A RegExp tests the full URL; a
1267
+ * PATH FORM (`/articles/{{uuid}}`) ignores the origin; an absolute string
1268
+ * compares origin+pathname. In both string forms `{{token}}` segments compare
1269
+ * structurally and declared query params are a SUBSET of the observed ones.
1270
+ */
1271
+ function urlMatches(declared, observed) {
1272
+ if (declared instanceof RegExp) return declared.test(observed);
1273
+ let url;
1274
+ try {
1275
+ url = new URL(observed, RELATIVE_BASE);
1276
+ } catch {
1277
+ return false;
1278
+ }
1279
+ const { base, query } = splitDeclared(declared);
1280
+ const observedBase = base.startsWith("/") ? url.pathname : `${url.origin}${url.pathname}`;
1281
+ const decodedBase = base.startsWith("/") ? safeDecode(url.pathname) : `${url.origin}${safeDecode(url.pathname)}`;
1282
+ if (!valueMatches(base, observedBase) && !valueMatches(base, decodedBase)) return false;
1283
+ for (const key of new Set(query.keys())) {
1284
+ const observedValues = url.searchParams.getAll(key);
1285
+ if (!query.getAll(key).every((value) => observedValues.some((actual) => valueMatches(value, actual)))) return false;
1286
+ }
1287
+ return true;
1288
+ }
1289
+ /**
1290
+ * Does an observed request satisfy a contract? Method (`*` matches any), URL,
1291
+ * then the contract's own `match` predicate (headers/query/body filters).
1292
+ */
1293
+ function contractMatches(contract, request) {
1294
+ const { match, method, url } = contract.request;
1295
+ if (method !== "*" && method.toUpperCase() !== request.method.toUpperCase()) return false;
1296
+ if (!urlMatches(url, request.url)) return false;
1297
+ return match ? match(request) : true;
1298
+ }
1299
+ /**
1300
+ * The URL pattern an out-of-process router (MSW) must register so the request
1301
+ * REACHES the queue. Deliberately no narrower than {@link contractMatches} —
1302
+ * the predicate above stays the authority on what actually matches.
1303
+ */
1304
+ function routePatternOf(declared) {
1305
+ if (declared instanceof RegExp) return declared;
1306
+ const { base } = splitDeclared(declared);
1307
+ if (base.startsWith("/")) return new RegExp(String.raw`^https?:\/\/[^/?#]+${placeholderPatternSource(base)}(?:\?[^#]*)?(?:#.*)?$`, "u");
1308
+ if (hasPlaceholders(base)) return new RegExp(String.raw`^${placeholderPatternSource(base)}(?:\?[^#]*)?(?:#.*)?$`, "u");
1309
+ return base;
1310
+ }
1311
+ /** How a declared contract reads in a failure message: spent, served, or silent. */
1312
+ function stateOf({ contract, served }) {
1313
+ const { times } = contract;
1314
+ if (times !== void 0 && served >= times) return ` (exhausted after ${times})`;
1315
+ return served === 0 ? "" : ` (served ${served} time(s))`;
1316
+ }
1317
+ var ContractQueue = class {
1318
+ entries;
1319
+ constructor(contracts) {
1320
+ this.entries = contracts.map((contract) => ({
1321
+ contract,
1322
+ served: 0
1323
+ }));
1324
+ }
1325
+ /** How many contracts the chain declared. */
1326
+ get size() {
1327
+ return this.entries.length;
1328
+ }
1329
+ /**
1330
+ * Routes to register with an out-of-process router, deduped by pattern —
1331
+ * two contracts on the same URL share one handler and one queue.
1332
+ */
1333
+ get routes() {
1334
+ const routes = /* @__PURE__ */ new Map();
1335
+ for (const { contract } of this.entries) {
1336
+ const url = routePatternOf(contract.request.url);
1337
+ const key = String(url);
1338
+ const route = routes.get(key) ?? {
1339
+ methods: [],
1340
+ url
1341
+ };
1342
+ if (!route.methods.includes(contract.request.method)) route.methods.push(contract.request.method);
1343
+ routes.set(key, route);
1344
+ }
1345
+ return [...routes.values()];
1346
+ }
1347
+ /** The declared routes, in order — the enumeration a 501 body carries. */
1348
+ declaredRoutes() {
1349
+ return this.entries.map(({ contract }) => describeRoute(contract));
1350
+ }
1351
+ /**
1352
+ * Serve the first contract in declaration order that matches and is not
1353
+ * exhausted, or null when nothing matches (including "everything that
1354
+ * matches is spent") — the strict-violation signal.
1355
+ */
1356
+ take(request) {
1357
+ for (const entry of this.entries) {
1358
+ const { times } = entry.contract;
1359
+ if (times !== void 0 && entry.served >= times) continue;
1360
+ if (!contractMatches(entry.contract, request)) continue;
1361
+ entry.served += 1;
1362
+ return entry.contract;
1363
+ }
1364
+ return null;
1365
+ }
1366
+ /**
1367
+ * The chain-end failure for contracts declared `required: true` that were
1368
+ * never requested (or not exactly `times` times), or null when every
1369
+ * requirement held.
1370
+ */
1371
+ requiredError() {
1372
+ const unmet = [];
1373
+ for (const { contract, served } of this.entries) {
1374
+ if (!contract.required) continue;
1375
+ const { times } = contract;
1376
+ if (times === void 0) {
1377
+ if (served === 0) unmet.push(` - ${describeRoute(contract)} — declared and required but never requested`);
1378
+ } else if (served !== times) unmet.push(` - ${describeRoute(contract)} — declared required with times: ${times} but was requested ${served} time(s)`);
1379
+ }
1380
+ if (unmet.length === 0) return null;
1381
+ return /* @__PURE__ */ new Error(`Required contract(s) never satisfied during the chain:\n${unmet.join("\n")}\nA required contract states the call MUST happen — either the code no longer makes it, or the contract no longer describes it.`);
1382
+ }
1383
+ /**
1384
+ * The strict failure for a request that matched no contract (CONVENTIONS
1385
+ * D7): method + URL of the offending request, plus every declared contract
1386
+ * and how often it was served.
1387
+ */
1388
+ unmatchedError(method, url) {
1389
+ const declared = this.entries.length === 0 ? " (no contracts declared)" : this.entries.map((entry) => ` - ${describeRoute(entry.contract)}${stateOf(entry)}`).join("\n");
1390
+ return /* @__PURE__ */ new Error(`Unmatched outgoing HTTP request during spec: ${method} ${url}\nDeclared contracts:\n${declared}\nEvery outgoing request of a chain that declares contracts must match one — add a contract for it (or raise its \`times\` when it is exhausted).`);
1391
+ }
1392
+ };
1393
+ //#endregion
1394
+ //#region src/integrations/msw/handlers.ts
1395
+ /**
1396
+ * A contract answers the request that was made, never a copy of an earlier one.
1397
+ *
1398
+ * In a page the reply travels through a real service worker and a real HTTP
1399
+ * cache, so a second render of the same component can be served the FIRST
1400
+ * test's answer and never reach the queue at all — a contract that was
1401
+ * exhausted, or replaced, silently keeps answering. Stated as a default, so a
1402
+ * spec whose subject IS caching can still say otherwise.
1403
+ */
1404
+ const NEVER_CACHED = { "cache-control": "no-store" };
1405
+ /** Turn a contract response into the msw reply, body kind by body kind. */
1406
+ function toMswResponse(msw, response) {
1407
+ const { body, headers, status = 200 } = response;
1408
+ if (response.transport === "network-error") return msw.HttpResponse.error();
1409
+ if (body === null || body === void 0) return new msw.HttpResponse(null, {
1410
+ headers: {
1411
+ ...NEVER_CACHED,
1412
+ ...headers
1413
+ },
1414
+ status
1415
+ });
1416
+ if (typeof body === "string") return new msw.HttpResponse(body, {
1417
+ headers: {
1418
+ ...NEVER_CACHED,
1419
+ "content-type": "text/plain; charset=utf-8",
1420
+ ...headers
1421
+ },
1422
+ status
1423
+ });
1424
+ return msw.HttpResponse.json(body, {
1425
+ headers: {
1426
+ ...NEVER_CACHED,
1427
+ ...headers
1428
+ },
1429
+ status
1430
+ });
1431
+ }
1432
+ /**
1433
+ * The handlers one chain's contracts become, plus the trailing catch-all that
1434
+ * records any request no contract accepted (CONVENTIONS D7). The caller decides
1435
+ * what to do with the recorded violation — the api chain rethrows it, the
1436
+ * component chain fails the render. An EMPTY contract list is still a guard:
1437
+ * the catch-all alone says "this subject has no network".
1438
+ *
1439
+ * `bypass` names the traffic that is not the subject's: under node there is
1440
+ * none, in a page it is everything the runner fetches to BE a page.
1441
+ */
1442
+ function buildContractHandlers(msw, contracts, bypass) {
1443
+ const queue = new ContractQueue(contracts);
1444
+ let violation = null;
1445
+ const recordViolation = (method, url) => {
1446
+ violation ??= queue.unmatchedError(method, url);
1447
+ return msw.HttpResponse.json({ error: `@jterrazz/test strict contracts: unmatched request ${method} ${url}` }, {
1448
+ headers: NEVER_CACHED,
1449
+ status: 501
1450
+ });
1451
+ };
1452
+ const handlers = [];
1453
+ for (const route of queue.routes) for (const method of route.methods) {
1454
+ const handlerFn = method === "*" ? msw.http.all : msw.http[method.toLowerCase()];
1455
+ if (!handlerFn) continue;
1456
+ handlers.push(handlerFn(route.url, async ({ request }) => {
1457
+ const observed = await observe(request);
1458
+ const contract = queue.take(observed);
1459
+ if (!contract) return recordViolation(request.method, request.url);
1460
+ const response = typeof contract.response === "function" ? contract.response(observed) : contract.response;
1461
+ if (response.delay) await new Promise((resolve) => setTimeout(resolve, response.delay));
1462
+ return toMswResponse(msw, response);
1463
+ }));
1464
+ }
1465
+ handlers.push(msw.http.all("*", ({ request }) => bypass?.(request.url) === true ? msw.passthrough() : recordViolation(request.method, request.url)));
1466
+ return {
1467
+ handlers,
1468
+ violation: () => violation ?? queue.requiredError()
1469
+ };
1470
+ }
1471
+ /** The request as the queue matches it — body parsed when it is JSON. */
1472
+ async function observe(request) {
1473
+ let body = null;
1474
+ const rawText = await request.clone().text();
1475
+ if (rawText) try {
1476
+ body = JSON.parse(rawText);
1477
+ } catch {
1478
+ body = rawText;
1479
+ }
1480
+ const headers = {};
1481
+ request.headers.forEach((value, key) => {
1482
+ headers[key.toLowerCase()] = value;
1483
+ });
1484
+ return {
1485
+ body,
1486
+ headers,
1487
+ method: request.method.toUpperCase(),
1488
+ url: request.url
1489
+ };
1490
+ }
1491
+ //#endregion
1492
+ //#region src/integrations/msw/worker.ts
1493
+ /**
1494
+ * What the runner itself fetches. Everything else a page asks for is the
1495
+ * subject's own traffic and answers to its contracts (D7).
1496
+ */
1497
+ const RUNNER_PREFIXES = [
1498
+ "/.artifacts/",
1499
+ "/@fs/",
1500
+ "/@id/",
1501
+ "/@vite",
1502
+ "/node_modules/",
1503
+ "/__vitest"
1504
+ ];
1505
+ let workerInstance = null;
1506
+ /**
1507
+ * Is this the runner's own traffic rather than the subject's?
1508
+ *
1509
+ * In a page EVERY module is an HTTP request: the test file, the seam, the
1510
+ * dependency cache Vite optimised, the runner's own channel. None of them is
1511
+ * the component's network, and none of them can be declared by a contract, so
1512
+ * they are recognised by PREFIX — never by extension, because msw bypasses a
1513
+ * "common asset" path before `onUnhandledRequest` ever runs and an extension
1514
+ * test would let a real `/api/posts.json` through on the same ground.
1515
+ */
1516
+ function isRunnerRequest(url) {
1517
+ const { pathname } = new URL(url);
1518
+ return RUNNER_PREFIXES.some((prefix) => pathname.startsWith(prefix));
1519
+ }
1520
+ /**
1521
+ * Start the worker once per page. The script is served at `/mockServiceWorker.js`
1522
+ * by the plugin `component()` registers, out of the package's OWN `msw`
1523
+ * install — so no consumer ever runs `msw init` and no consumer declares `msw`.
1524
+ */
1525
+ async function ensureContractWorker() {
1526
+ if (workerInstance !== null) return;
1527
+ const { setupWorker } = await import("msw/browser");
1528
+ workerInstance = setupWorker();
1529
+ await workerInstance.start({
1530
+ onUnhandledRequest: (request, print) => {
1531
+ if (!isRunnerRequest(request.url)) print.error();
1532
+ },
1533
+ quiet: true,
1534
+ serviceWorker: { url: "/mockServiceWorker.js" }
1535
+ });
1536
+ }
1537
+ /**
1538
+ * Register one render's contracts on the page's worker.
1539
+ *
1540
+ * The worker starts even when the list is empty: on this facet D7 is TOTAL —
1541
+ * a component that was given no contract has no network, and a fetch it makes
1542
+ * anyway is named by {@link ContractRegistration.violation} rather than
1543
+ * answered by whatever the dev server happens to have at that path.
1544
+ */
1545
+ async function registerWorkerContracts(contracts) {
1546
+ await ensureContractWorker();
1547
+ const { handlers, violation } = buildContractHandlers(await import("msw"), contracts, isRunnerRequest);
1548
+ workerInstance.use(...handlers);
1549
+ return {
1550
+ cleanup: () => {
1551
+ workerInstance.resetHandlers();
1552
+ },
1553
+ violation
1554
+ };
1555
+ }
1556
+ /** Drop every handler the page still carries — the per-test reset. */
1557
+ function resetWorkerContracts() {
1558
+ if (workerInstance !== null) workerInstance.resetHandlers();
1559
+ }
1560
+ //#endregion
1561
+ //#region src/integrations/vitest-browser/page-runtime.ts
1562
+ /**
1563
+ * The runner, as the page reaches it.
1564
+ *
1565
+ * `vitest` is the framework's one sanctioned coupling and it lives in the
1566
+ * layers that own a runner — `src/vitest/` for the config side, this seam for
1567
+ * the page's. The component model asks for "after this test", "pin the clock"
1568
+ * and "what did the project provide" and never learns which runner answers.
1569
+ */
1570
+ /** Run `teardown` when the current test ends, however it ends. No hook in the spec. */
1571
+ function afterThisTest(teardown) {
1572
+ onTestFinished(teardown);
1573
+ }
1574
+ /**
1575
+ * Freeze the page's `Date` at `iso`. `Date` ONLY: faking the page's timers
1576
+ * would stop React's scheduler and nothing would ever render.
1577
+ */
1578
+ function pinClock(iso) {
1579
+ vi.useFakeTimers({
1580
+ now: new Date(iso),
1581
+ toFake: ["Date"]
1582
+ });
1583
+ }
1584
+ /** Give the page its real clock back. */
1585
+ function releaseClock() {
1586
+ vi.useRealTimers();
1587
+ }
1588
+ /** The instant `component({ clock })` pinned for every render, if it did. */
1589
+ function providedClock() {
1590
+ return inject("componentClock");
1591
+ }
1592
+ /** The page size the project states — what a per-test `.viewport()` is restored to. */
1593
+ function providedViewport() {
1594
+ return inject("componentViewport");
1595
+ }
1596
+ /** Resize the page the test renders into. */
1597
+ async function setViewport(size) {
1598
+ await page.viewport(size.width, size.height);
1599
+ }
1600
+ /**
1601
+ * The project's `wrap`, left on `globalThis` by the setup module the project
1602
+ * loads. A shared symbol rather than an import: the setup module and this
1603
+ * bundle are two graphs in one page and share no module instance.
1604
+ */
1605
+ function projectWrapper() {
1606
+ const wrap = globalThis[Symbol.for("@jterrazz/test:component-wrap")];
1607
+ return typeof wrap === "function" ? wrap : void 0;
1608
+ }
1609
+ //#endregion
1610
+ //#region src/specification/facets/component/rendered-text.ts
1611
+ /**
1612
+ * A stream captured INSIDE the page.
1613
+ *
1614
+ * Structurally identical to any other {@link TextAccessor} — the same
1615
+ * `{{token}}` grammar, the same ANSI stripping, the same `.grep()` — and
1616
+ * marked so the matcher augmentation can say the one thing that differs: its
1617
+ * golden lives on the server, so `toMatch` is awaited here where it is
1618
+ * synchronous everywhere else.
1619
+ */
1620
+ var RenderedText = class extends TextAccessor {
1621
+ /** The marker the `toMatch` overload reads. Never asserted on directly. */
1622
+ capturedInPage = true;
1623
+ };
1624
+ //#endregion
1625
+ //#region src/specification/facets/component/component.result.ts
1626
+ /**
1627
+ * What a render resolves to — the component as the page saw it, after the
1628
+ * scenario ran.
1629
+ *
1630
+ * Five accessors and no more: the ARIA outline a golden pins, the two
1631
+ * renderings a probe reads, and the two streams a spec wants silent. Nothing
1632
+ * here reaches back into React — a spec that needs the component's internals
1633
+ * is asserting the implementation, not the surface a user meets.
1634
+ */
1635
+ var RenderResult = class {
1636
+ /** The browser console as a stream — one `[type] text` line per message. */
1637
+ console;
1638
+ /** Rendered text of the whole document body (`innerText`). */
1639
+ content;
1640
+ /** Console messages of type `error` only, plus any uncaught page error. */
1641
+ errors;
1642
+ /** The mounted markup, serialised — the escape hatch for a class or an attribute. */
1643
+ html;
1644
+ /** The ARIA snapshot of the rendered body — the outline a golden pins. */
1645
+ tree;
1646
+ constructor(streams) {
1647
+ this.console = new RenderedText(streams.console, "console", "");
1648
+ this.content = new RenderedText(streams.content, "content", "");
1649
+ this.errors = new RenderedText(streams.errors, "errors", "");
1650
+ this.html = new RenderedText(streams.html, "html", "");
1651
+ this.tree = new RenderedText(streams.tree, "tree", "");
1652
+ }
1653
+ };
1654
+ //#endregion
1655
+ //#region src/specification/facets/component/component.chain.ts
1656
+ /** The console methods a render records; everything else is left alone. */
1657
+ const CONSOLE_METHODS = [
1658
+ "debug",
1659
+ "error",
1660
+ "info",
1661
+ "log",
1662
+ "warn"
1663
+ ];
1664
+ const EMPTY = {
1665
+ clock: null,
1666
+ contracts: [],
1667
+ viewport: null,
1668
+ wrap: null
1669
+ };
1670
+ /** Record what the page writes to the console for the length of the render. */
1671
+ function recordConsole() {
1672
+ const entries = [];
1673
+ const originals = /* @__PURE__ */ new Map();
1674
+ for (const method of CONSOLE_METHODS) {
1675
+ const original = console[method];
1676
+ originals.set(method, original);
1677
+ console[method] = (...args) => {
1678
+ entries.push({
1679
+ text: args.map(String).join(" "),
1680
+ type: method
1681
+ });
1682
+ original(...args);
1683
+ };
1684
+ }
1685
+ const onError = (event) => {
1686
+ entries.push({
1687
+ text: event.message,
1688
+ type: "error"
1689
+ });
1690
+ };
1691
+ globalThis.addEventListener("error", onError);
1692
+ let stopped = false;
1693
+ return {
1694
+ entries,
1695
+ stop: () => {
1696
+ if (stopped) return;
1697
+ stopped = true;
1698
+ for (const method of CONSOLE_METHODS) {
1699
+ const original = originals.get(method);
1700
+ if (original !== void 0) console[method] = original;
1701
+ }
1702
+ globalThis.removeEventListener("error", onError);
1703
+ }
1704
+ };
1705
+ }
1706
+ /** Is the subject a function that fills a container, rather than a React tree? */
1707
+ function isDomMount(subject) {
1708
+ return typeof subject === "function";
1709
+ }
1710
+ /** A bare request needs its response — the same refusal every facet gives. */
1711
+ function inlinePair(request, response) {
1712
+ if (response === void 0) throw new Error(".intercept(): a bare request needs its response — pass a contract (defineContract({ request, response })) or the inline pair .intercept(request, response).");
1713
+ return {
1714
+ request,
1715
+ response
1716
+ };
1717
+ }
1718
+ /**
1719
+ * What the page is still holding, and the teardown that lets it go.
1720
+ *
1721
+ * The React adapter's own auto-cleanup is a `beforeEach` registered when its
1722
+ * module loads — and this package loads it lazily, INSIDE the first render, so
1723
+ * that hook never covers the test that triggered it. The seam does the unmount
1724
+ * itself, on the test that rendered: two renders' markup sharing one document
1725
+ * is how a second `button('Open')` appears and a descriptor that named exactly
1726
+ * one element starts refusing.
1727
+ */
1728
+ let mounted = null;
1729
+ /** Everything one test may have left behind, undone — no hook in any spec. */
1730
+ async function resetComponentScope(resized) {
1731
+ await unmountHeld();
1732
+ if (resized) await setViewport(providedViewport());
1733
+ resetWorkerContracts();
1734
+ releaseClock();
1735
+ }
1736
+ /** Take down whatever is still mounted, and hold nothing afterwards. */
1737
+ async function unmountHeld() {
1738
+ const surface = mounted;
1739
+ mounted = null;
1740
+ if (surface !== null) try {
1741
+ await surface.unmount();
1742
+ } catch {}
1743
+ }
1744
+ /** Mount the subject, dressing a React tree in the chain's wrapper and the project's. */
1745
+ async function mount(state, subject) {
1746
+ if (isDomMount(subject)) return mountDom(subject);
1747
+ const outer = projectWrapper();
1748
+ const dress = (ui) => {
1749
+ const inner = state.wrap ? state.wrap(ui) : ui;
1750
+ return outer ? outer(inner) : inner;
1751
+ };
1752
+ const surface = await mountReact(dress(subject));
1753
+ return {
1754
+ ...surface,
1755
+ rerender: async (ui) => {
1756
+ await surface.rerender(dress(ui));
1757
+ }
1758
+ };
1759
+ }
1760
+ /** The terminal action: mount, run the scenario, capture what the page shows. */
1761
+ async function render(state, subject, scenario) {
1762
+ await unmountHeld();
1763
+ const recorder = recordConsole();
1764
+ afterThisTest(async () => {
1765
+ recorder.stop();
1766
+ await resetComponentScope(state.viewport !== null);
1767
+ });
1768
+ if (state.viewport !== null) await setViewport(state.viewport);
1769
+ const instant = state.clock ?? providedClock();
1770
+ if (instant !== void 0) pinClock(instant);
1771
+ const registration = await registerWorkerContracts(state.contracts);
1772
+ const surface = await mount(state, subject);
1773
+ mounted = surface;
1774
+ try {
1775
+ if (scenario) await scenario(componentVerbs(surface));
1776
+ } finally {
1777
+ recorder.stop();
1778
+ }
1779
+ const violation = registration.violation();
1780
+ if (violation !== null) throw violation;
1781
+ const { entries } = recorder;
1782
+ return new RenderResult({
1783
+ console: entries.map((entry) => `[${entry.type}] ${entry.text}`).join("\n"),
1784
+ content: document.body.innerText,
1785
+ errors: entries.filter((entry) => entry.type === "error").map((entry) => entry.text).join("\n"),
1786
+ html: surface.container.innerHTML,
1787
+ tree: await ariaTree()
1788
+ });
1789
+ }
1790
+ /** Every setup forks a chain, so the exported handle never carries a test's state. */
1791
+ function chainOf(state) {
1792
+ return {
1793
+ clock: (iso) => chainOf({
1794
+ ...state,
1795
+ clock: iso
1796
+ }),
1797
+ intercept: (requestOrContracts, maybeResponse) => {
1798
+ const added = Array.isArray(requestOrContracts) || isContracts(requestOrContracts) || isContract(requestOrContracts) ? contractsOf(requestOrContracts) : [inlinePair(requestOrContracts, maybeResponse)];
1799
+ return chainOf({
1800
+ ...state,
1801
+ contracts: [...state.contracts, ...added]
1802
+ });
1803
+ },
1804
+ render: async (subject, scenario) => await render(state, subject, scenario),
1805
+ viewport: (size) => chainOf({
1806
+ ...state,
1807
+ viewport: size
1808
+ }),
1809
+ wrap: (wrapper) => chainOf({
1810
+ ...state,
1811
+ wrap: wrapper
1812
+ })
1813
+ };
1814
+ }
1815
+ /** The handle a component test imports. */
1816
+ const component = chainOf(EMPTY);
1817
+ //#endregion
1818
+ //#region src/specification/facets/_common/result/json.ts
1819
+ /**
1820
+ * Read-only accessor for a JSON payload parsed from a text stream (stdout).
1821
+ *
1822
+ * Lazily parses the JSON on first use; parse errors are deferred until the
1823
+ * value is read so that callers can still read the raw stream text without
1824
+ * triggering a throw.
1825
+ *
1826
+ * ANSI escape sequences are stripped by default before `JSON.parse`
1827
+ * (CONVENTIONS D6). When a `transform` is configured on the spec runner, it
1828
+ * runs on the stripped text — an escape hatch for application noise not
1829
+ * covered by the `{{token}}` grammar.
1830
+ *
1831
+ * Assertions go through `expect()`: `expect(result.json).toMatch('name.json')`
1832
+ * (deep-equal against `_expected/<name>`, with `{{placeholder}}` support).
1833
+ */
1834
+ var JsonAccessor = class {
1835
+ /** @internal Ref-capture scope shared by the current spec execution. */
1836
+ captures;
1837
+ /** @internal */
1838
+ rawText;
1839
+ /** @internal Test-file directory — fixture resolution root for matchers. */
1840
+ testDir;
1841
+ /** @internal */
1842
+ transform;
1843
+ constructor(rawText, testDir, transform, captures) {
1844
+ this.rawText = rawText;
1845
+ this.testDir = testDir;
1846
+ this.transform = transform;
1847
+ this.captures = captures ?? new CaptureScope();
1848
+ }
1849
+ /** The parsed JSON value. Throws if the text is not valid JSON. */
1850
+ get value() {
1851
+ const stripped = stripAnsiCodes(this.rawText);
1852
+ const source = this.transform ? this.transform(stripped) : stripped;
1853
+ try {
1854
+ return JSON.parse(source);
1855
+ } catch {
1856
+ const preview = source.slice(0, 200);
1857
+ throw new Error(`stdout is not valid JSON: ${preview}`);
1858
+ }
1859
+ }
1860
+ };
1861
+ //#endregion
1862
+ //#region src/specification/facets/_common/result/table.ts
1863
+ /**
1864
+ * Read-only accessor for a database table after a specification run.
1865
+ *
1866
+ * Assertions go through `expect()` (async — they query the database):
1867
+ *
1868
+ * await expect(result.table('users', { database: 'db' })).toMatchRows({
1869
+ * columns: ['name'],
1870
+ * rows: [['Alice']],
1871
+ * });
1872
+ * await expect(result.table('users', { database: 'db' })).toBeEmpty();
1873
+ */
1874
+ var TableAccessor = class {
1875
+ /** @internal Ref-capture scope shared by the current spec execution. */
1876
+ captures;
1877
+ /** @internal */
1878
+ db;
1879
+ /** The table name this accessor reads. */
1880
+ name;
1881
+ constructor(name, db, captures) {
1882
+ this.name = name;
1883
+ this.db = db;
1884
+ this.captures = captures ?? new CaptureScope();
1885
+ }
1886
+ /** @internal Query the table — used by the toMatchRows / toBeEmpty matchers. */
1887
+ async query(columns) {
1888
+ return await this.db.query(this.name, columns);
1889
+ }
1890
+ };
1891
+ //#endregion
1892
+ //#region src/specification/facets/website/elements.ts
1893
+ const named = (kind) => (name, options) => ({
1894
+ kind,
1895
+ name,
1896
+ ...options?.exact ? { exact: true } : {}
1897
+ });
1898
+ /** A button (or element with the button role), by accessible name. */
1899
+ const button = named("button");
1900
+ /** A form field, by label. */
1901
+ const field = named("field");
1902
+ /** A heading, by accessible name. */
1903
+ const heading = named("heading");
1904
+ /** A link, by accessible name. */
1905
+ const link = named("link");
1906
+ /** An element containing the given text. */
1907
+ const content = named("text");
1908
+ /** The escape hatch: an element by `data-testid`. Prefer user-facing elements. */
1909
+ const testId = (id) => ({
1910
+ kind: "testId",
1911
+ name: id
1912
+ });
1913
+ const landmark = (kind) => (name, options) => ({
1914
+ kind,
1915
+ ...name === void 0 ? {} : { name },
1916
+ ...options?.exact ? { exact: true } : {}
1917
+ });
1918
+ /** The `banner` landmark — the page header. */
1919
+ const banner = landmark("banner");
1920
+ /** The `complementary` landmark — an `<aside>`, a sidebar. */
1921
+ const complementary = landmark("complementary");
1922
+ /** The `contentinfo` landmark — the page footer. */
1923
+ const contentinfo = landmark("contentinfo");
1924
+ /** The `form` landmark — a form carrying an accessible name. */
1925
+ const form = landmark("form");
1926
+ /** The `main` landmark — the primary content of the document. */
1927
+ const main = landmark("main");
1928
+ /** The `navigation` landmark — a `<nav>`. Name it when a page has several. */
1929
+ const navigation = landmark("navigation");
1930
+ /** The `region` landmark — a `<section>` carrying an accessible name. */
1931
+ const region = landmark("region");
1932
+ /** The `search` landmark. */
1933
+ const search = landmark("search");
1934
+ /**
1935
+ * Restrict a descriptor to the inside of another — the answer to ambiguity,
1936
+ * and the one the framework prefers over a test id.
1937
+ *
1938
+ * click(within(navigation(), link('Articles')))
1939
+ *
1940
+ * Composes outside-in: the scope may itself be scoped, so a deeply nested
1941
+ * target reads `within(main(), within(region('Series'), link('Part 2')))`.
1942
+ * Any descriptor works as a scope, including `testId()` when a container has
1943
+ * no landmark role to stand on.
1944
+ */
1945
+ const within = (scope, target) => ({
1946
+ ...target,
1947
+ scope: target.scope ? {
1948
+ ...target.scope,
1949
+ scope
1950
+ } : scope
1951
+ });
1952
+ /** A modal or non-modal `<dialog>`, by accessible name. A closed one is absent. */
1953
+ const dialog = landmark("dialog");
1954
+ /** A live region announcing a result — `role="status"`, an `<output>`. */
1955
+ const status = landmark("status");
1956
+ /** A table, by its caption or accessible name. */
1957
+ const table = landmark("table");
1958
+ /** A row of a table or grid, by the text of its cells. */
1959
+ const row = landmark("row");
1960
+ /** An item of a list, by its text. Retires the `.first()` of an unnamed `<li>`. */
1961
+ const listitem = landmark("listitem");
1962
+ /**
1963
+ * An option of a select or a listbox, by its label — named inside the field
1964
+ * that holds it: `within(field('Channel'), option('LinkedIn'))`.
1965
+ *
1966
+ * Asserted by PRESENCE, not by visibility: the options of a collapsed
1967
+ * `<select>` are in the document and in the accessibility tree, and none of
1968
+ * them has a box on the screen until it is opened. `see(option('LinkedIn'))`
1969
+ * therefore asks "is it offered", and `see(selected(option('LinkedIn')))`
1970
+ * asks which one the field is on.
1971
+ */
1972
+ const option = named("option");
1973
+ /**
1974
+ * Where the keyboard is: `see(focused(button('Open')))` asserts the element has
1975
+ * focus, `gone(focused(x))` that it does not.
1976
+ *
1977
+ * A modifier rather than a descriptor of its own, because focus is a STATE of
1978
+ * an element the vocabulary can already name. It is a verb's business and never
1979
+ * a golden's: the accessibility tree carries no focus, so a tree snapshot of a
1980
+ * dialog that took the keyboard and one that did not are byte-identical.
1981
+ */
1982
+ const focused = (element) => ({
1983
+ ...element,
1984
+ focused: true
1985
+ });
1986
+ /**
1987
+ * Whether the element accepts input: `see(disabled(button('Delete')))` asserts
1988
+ * it refuses, `see(enabled(button('Delete')))` that it takes it.
1989
+ *
1990
+ * Modifiers rather than descriptors, for the same reason as `focused`: being
1991
+ * disabled is a state of an element the vocabulary already names. Unlike focus,
1992
+ * the ARIA tree carries it, so a golden pins a whole outline's enablement and
1993
+ * these name the ONE control a test is about. They also buy the direction a
1994
+ * behavioural substitute cannot reach — clicking a disabled control is a
1995
+ * timeout, never an assertion.
1996
+ */
1997
+ const disabled = (element) => ({
1998
+ ...element,
1999
+ disabled: true
2000
+ });
2001
+ /** The other direction of {@link disabled} — the element takes input. */
2002
+ const enabled = (element) => ({
2003
+ ...element,
2004
+ disabled: false
2005
+ });
2006
+ /**
2007
+ * Which option the field is on: `see(selected(option('LinkedIn')))`, and
2008
+ * `gone(selected(option('X')))` for the one it left.
2009
+ *
2010
+ * A modifier for the same reason as {@link disabled}: being chosen is a state
2011
+ * of an element the vocabulary already names. No matcher answers for it — a
2012
+ * `<option>` is not a checkbox — so both adapters read the `:checked` the CSS
2013
+ * spec gives a selected option.
2014
+ */
2015
+ const selected = (element) => ({
2016
+ ...element,
2017
+ selected: true
2018
+ });
2019
+ /**
2020
+ * What the field holds: `see(valued(field('Title'), 'Launch teaser'))`, and
2021
+ * `gone(valued(field('Title'), '…'))` for a value it no longer holds.
2022
+ *
2023
+ * A modifier for the same reason as {@link disabled}: what a field holds is a
2024
+ * state of an element the vocabulary already names, and this is how the ONE
2025
+ * field a test is about is waited for — a golden pins a whole outline instead.
2026
+ * Read from the node's live value, never from the `value` ATTRIBUTE, which a
2027
+ * controlled input never moves.
2028
+ */
2029
+ const valued = (element, value) => ({
2030
+ ...element,
2031
+ value
2032
+ });
2033
+ //#endregion
2034
+ //#region src/specification/contracts/filters.ts
2035
+ /** Does an observed text satisfy a declared {@link TextFilter}? */
2036
+ function matchesText(filter, actual) {
2037
+ if (filter === void 0) return true;
2038
+ if (typeof filter === "string") return actual === filter;
2039
+ if (filter instanceof RegExp) return filter.test(actual);
2040
+ return structuralEquals(filter, actual, new CaptureScope());
2041
+ }
2042
+ //#endregion
2043
+ //#region src/integrations/anthropic/anthropic.ts
2044
+ const ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages";
2045
+ function matchesFilter(body, filter) {
2046
+ if (!matchesText(filter.model, body?.model ?? "")) return false;
2047
+ if (!matchesText(filter.system, typeof body?.system === "string" ? body.system : "")) return false;
2048
+ const userMsg = body?.messages?.find((m) => m.role === "user")?.content ?? "";
2049
+ if (!matchesText(filter.user, typeof userMsg === "string" ? userMsg : JSON.stringify(userMsg))) return false;
2050
+ if (filter.tools) {
2051
+ const names = body?.tools?.map((t) => t.name).filter(Boolean) ?? [];
2052
+ if (!filter.tools.every((t) => names.includes(t))) return false;
2053
+ }
2054
+ return true;
2055
+ }
2056
+ function buildReply(data) {
2057
+ return {
2058
+ status: 200,
2059
+ body: {
2060
+ id: "msg-test",
2061
+ type: "message",
2062
+ role: "assistant",
2063
+ content: [{
2064
+ type: "text",
2065
+ text: typeof data === "string" ? data : JSON.stringify(data)
2066
+ }],
2067
+ model: "claude-sonnet-4-20250514",
2068
+ stop_reason: "end_turn",
2069
+ usage: {
2070
+ input_tokens: 10,
2071
+ output_tokens: 10
2072
+ }
2073
+ }
2074
+ };
2075
+ }
2076
+ /**
2077
+ * Anthropic API intercept helpers.
2078
+ */
2079
+ const anthropic = {
2080
+ /**
2081
+ * Request: match Messages API calls, optionally routed through a
2082
+ * custom gateway URL. When used with a JSON fixture file, the data is
2083
+ * returned as-is (no wrapping) because Anthropic fixtures are typically
2084
+ * already in the Messages API response shape.
2085
+ *
2086
+ * @example
2087
+ * anthropic.messages()
2088
+ * anthropic.messages({ system: /classify/ })
2089
+ * anthropic.messages({ user: buildPrompt() }) // string = EXACT equality
2090
+ * anthropic.messages({ user: /classify/ }, GATEWAY)
2091
+ */
2092
+ messages(filter, url) {
2093
+ return {
2094
+ adapter: "anthropic",
2095
+ method: "POST",
2096
+ url: url ?? ANTHROPIC_MESSAGES_URL,
2097
+ match: filter ? ({ body }) => matchesFilter(body, filter) : void 0,
2098
+ wrap(data) {
2099
+ if (data && typeof data === "object" && !Array.isArray(data)) return {
2100
+ status: 200,
2101
+ body: data
2102
+ };
2103
+ return buildReply(data);
2104
+ }
2105
+ };
2106
+ },
2107
+ /** Response: wrap data in Anthropic messages format. */
2108
+ reply(data) {
2109
+ return buildReply(data);
2110
+ },
2111
+ /** Response: return an Anthropic error. */
2112
+ error(status, message) {
2113
+ return {
2114
+ status,
2115
+ body: {
2116
+ type: "error",
2117
+ error: {
2118
+ type: status === 429 ? "rate_limit_error" : "api_error",
2119
+ message: message ?? `Anthropic error (${status})`
2120
+ }
2121
+ }
2122
+ };
2123
+ },
2124
+ /** Response: simulate a timeout. */
2125
+ timeout() {
2126
+ return {
2127
+ status: 200,
2128
+ body: {},
2129
+ delay: 3e4
2130
+ };
2131
+ }
2132
+ };
2133
+ //#endregion
2134
+ //#region src/specification/contracts/http.ts
2135
+ function wrapJson(data) {
2136
+ return {
2137
+ status: 200,
2138
+ body: data
2139
+ };
2140
+ }
2141
+ const TEXT_CONTENT_TYPE = "text/plain; charset=utf-8";
2142
+ function matchesBody(body, expected) {
2143
+ if (typeof expected === "string") return (typeof body === "string" ? body : JSON.stringify(body ?? "")).includes(expected);
2144
+ if (expected instanceof RegExp) {
2145
+ const text = typeof body === "string" ? body : JSON.stringify(body ?? "");
2146
+ return expected.test(text);
2147
+ }
2148
+ return structuralSubset(expected, body, new CaptureScope());
2149
+ }
2150
+ function matchesEntries(expected, lookup) {
2151
+ return Object.entries(expected).every(([key, value]) => {
2152
+ const actual = lookup(key);
2153
+ if (actual === void 0) return false;
2154
+ return value instanceof RegExp ? value.test(actual) : actual === value;
2155
+ });
2156
+ }
2157
+ /**
2158
+ * Build the `match` predicate for an HTTP request filter, or `undefined` when
2159
+ * no filter is supplied (fires on any URL/method match).
2160
+ */
2161
+ function buildMatch(filter) {
2162
+ if (!filter) return;
2163
+ return (request) => {
2164
+ if (filter.body !== void 0 && !matchesBody(request.body, filter.body)) return false;
2165
+ if (filter.headers && !matchesEntries(filter.headers, (key) => request.headers[key.toLowerCase()])) return false;
2166
+ if (filter.query) {
2167
+ let params;
2168
+ try {
2169
+ params = new URL(request.url, "http://contract.invalid").searchParams;
2170
+ } catch {
2171
+ return false;
2172
+ }
2173
+ if (!matchesEntries(filter.query, (key) => params.get(key) ?? void 0)) return false;
2174
+ }
2175
+ return true;
2176
+ };
2177
+ }
2178
+ function declare(method, url, filter) {
2179
+ return {
2180
+ adapter: "http",
2181
+ match: buildMatch(filter),
2182
+ method,
2183
+ url,
2184
+ wrap: wrapJson
2185
+ };
2186
+ }
2187
+ /**
2188
+ * Generic HTTP contract helpers for any URL. The url is absolute (string or
2189
+ * RegExp), or a PATH FORM starting with `/` — `http.get('/articles/{{uuid}}')`
2190
+ * matches that path on ANY origin, which is what an app calling its own
2191
+ * backend needs. An optional {@link HttpContractFilter} narrows matching by
2192
+ * body, headers, or query — a request that hits the URL/method but fails the
2193
+ * filter counts as unmatched (strict contracts, CONVENTIONS D7).
2194
+ *
2195
+ * @example
2196
+ * defineContract({ request: http.get('/articles/{{uuid}}'), response: http.json(article) })
2197
+ * defineContract({ request: http.post(URL, { body: { user: 'alice' } }), response: http.empty() })
2198
+ */
2199
+ const http = {
2200
+ any(url, filter) {
2201
+ return declare("*", url, filter);
2202
+ },
2203
+ delete(url, filter) {
2204
+ return declare("DELETE", url, filter);
2205
+ },
2206
+ get(url, filter) {
2207
+ return declare("GET", url, filter);
2208
+ },
2209
+ patch(url, filter) {
2210
+ return declare("PATCH", url, filter);
2211
+ },
2212
+ post(url, filter) {
2213
+ return declare("POST", url, filter);
2214
+ },
2215
+ put(url, filter) {
2216
+ return declare("PUT", url, filter);
2217
+ },
2218
+ /** Response: a body-less reply (204 by default). */
2219
+ empty(status = 204) {
2220
+ return {
2221
+ status,
2222
+ body: null
2223
+ };
2224
+ },
2225
+ /** Response: an error status. Without a body, `{ error: 'HTTP <status>' }`. */
2226
+ error(status, body) {
2227
+ return {
2228
+ status,
2229
+ body: body === void 0 ? { error: `HTTP ${status}` } : body
2230
+ };
2231
+ },
2232
+ /** Response: a JSON body (200 by default). */
2233
+ json(body, init) {
2234
+ return {
2235
+ status: init?.status ?? 200,
2236
+ body,
2237
+ delay: init?.delay,
2238
+ headers: init?.headers
2239
+ };
2240
+ },
2241
+ /**
2242
+ * Response: no response at all — the request fails in transport, the way a
2243
+ * server that is not running fails it. `fetch` rejects; no status is served.
2244
+ */
2245
+ unreachable() {
2246
+ return {
2247
+ body: null,
2248
+ transport: "network-error"
2249
+ };
2250
+ },
2251
+ /** Response: a text body, served as `text/plain` (200 by default). */
2252
+ text(body, init) {
2253
+ return {
2254
+ status: init?.status ?? 200,
2255
+ body,
2256
+ delay: init?.delay,
2257
+ headers: {
2258
+ "content-type": TEXT_CONTENT_TYPE,
2259
+ ...init?.headers
2260
+ }
2261
+ };
2262
+ }
2263
+ };
2264
+ //#endregion
2265
+ //#region src/integrations/openai/openai.ts
2266
+ const OPENAI_CHAT_URL = "https://api.openai.com/v1/chat/completions";
2267
+ const OPENAI_RESPONSES_URL = "https://api.openai.com/v1/responses";
2268
+ function matchesChatFilter(body, filter) {
2269
+ if (!matchesText(filter.model, body?.model ?? "")) return false;
2270
+ if (!matchesText(filter.system, body?.messages?.find((m) => m.role === "system")?.content ?? "")) return false;
2271
+ if (!matchesText(filter.user, body?.messages?.find((m) => m.role === "user")?.content ?? "")) return false;
2272
+ if (filter.tools) {
2273
+ const names = body?.tools?.map((t) => t.function?.name).filter(Boolean) ?? [];
2274
+ if (!filter.tools.every((t) => names.includes(t))) return false;
2275
+ }
2276
+ if (filter.temperature !== void 0 && body?.temperature !== filter.temperature) return false;
2277
+ return true;
2278
+ }
2279
+ function matchesResponsesFilter(body, filter) {
2280
+ if (!matchesText(filter.model, body?.model ?? "")) return false;
2281
+ const systemInput = body?.input?.find?.((m) => m.role === "system")?.content ?? "";
2282
+ if (!matchesText(filter.system, body?.instructions || systemInput)) return false;
2283
+ const userText = (body?.input ?? []).filter((m) => m.role === "user").map((m) => typeof m.content === "string" ? m.content : JSON.stringify(m.content)).join(" ");
2284
+ if (!matchesText(filter.user, userText)) return false;
2285
+ if (filter.tools) {
2286
+ const names = body?.tools?.map((t) => t.name ?? t.function?.name).filter(Boolean) ?? [];
2287
+ if (!filter.tools.every((t) => names.includes(t))) return false;
2288
+ }
2289
+ return true;
2290
+ }
2291
+ function buildChatReply(data) {
2292
+ const content = typeof data === "string" ? data : JSON.stringify(data);
2293
+ return {
2294
+ status: 200,
2295
+ body: {
2296
+ id: "chatcmpl-test",
2297
+ object: "chat.completion",
2298
+ created: Math.floor(Date.now() / 1e3),
2299
+ model: "gpt-4o-test",
2300
+ choices: [{
2301
+ index: 0,
2302
+ message: {
2303
+ role: "assistant",
2304
+ content
2305
+ },
2306
+ finish_reason: "stop"
2307
+ }],
2308
+ usage: {
2309
+ prompt_tokens: 10,
2310
+ completion_tokens: 10,
2311
+ total_tokens: 20
2312
+ }
2313
+ }
2314
+ };
2315
+ }
2316
+ function buildResponsesReply(data) {
2317
+ const text = typeof data === "string" ? data : JSON.stringify(data);
2318
+ return {
2319
+ status: 200,
2320
+ body: {
2321
+ id: "resp-test",
2322
+ object: "response",
2323
+ created_at: Math.floor(Date.now() / 1e3),
2324
+ model: "gpt-4o-test",
2325
+ output: [{
2326
+ type: "message",
2327
+ id: "msg-test",
2328
+ role: "assistant",
2329
+ content: [{
2330
+ type: "output_text",
2331
+ text,
2332
+ annotations: []
2333
+ }]
2334
+ }],
2335
+ usage: {
2336
+ input_tokens: 10,
2337
+ output_tokens: 10,
2338
+ total_tokens: 20
2339
+ }
2340
+ }
2341
+ };
2342
+ }
2343
+ /**
2344
+ * OpenAI API intercept helpers.
2345
+ */
2346
+ const openai = {
2347
+ /**
2348
+ * Request: match Chat Completions API calls. STRING filters mean EXACT
2349
+ * equality (pass the app's own prompt builder); loosen deliberately with a
2350
+ * RegExp or `match.includes(...)`.
2351
+ *
2352
+ * @example
2353
+ * openai.chat() // any chat call
2354
+ * openai.chat({ model: 'gpt-4o' }) // exact model
2355
+ * openai.chat({ system: buildPrompt() }) // exact system prompt
2356
+ * openai.chat({ system: /classify/ }) // pattern
2357
+ */
2358
+ chat(filter) {
2359
+ return {
2360
+ adapter: "openai",
2361
+ method: "POST",
2362
+ url: OPENAI_CHAT_URL,
2363
+ match: filter ? ({ body }) => matchesChatFilter(body, filter) : void 0,
2364
+ wrap: buildChatReply
2365
+ };
2366
+ },
2367
+ /**
2368
+ * Request: match Responses API calls (AI SDK v5+) with auto-wrapping.
2369
+ * String filters mean EXACT equality (see {@link openai.chat}).
2370
+ * When used with a JSON file, the data is automatically wrapped in the
2371
+ * Responses API envelope.
2372
+ *
2373
+ * @param filter - Optional body filters.
2374
+ * @param url - Custom gateway URL (default: api.openai.com).
2375
+ *
2376
+ * @example
2377
+ * openai.responses({ user: /Report Ingestion/ }, GATEWAY)
2378
+ */
2379
+ responses(filter, url) {
2380
+ return {
2381
+ adapter: "openai",
2382
+ method: "POST",
2383
+ url: url ?? OPENAI_RESPONSES_URL,
2384
+ match: filter ? ({ body }) => matchesResponsesFilter(body, filter) : void 0,
2385
+ wrap: buildResponsesReply
2386
+ };
2387
+ },
2388
+ /**
2389
+ * Response: wrap data in Chat Completions format.
2390
+ *
2391
+ * @example
2392
+ * openai.reply({ categories: ['TECH'] })
2393
+ */
2394
+ reply(data) {
2395
+ return buildChatReply(data);
2396
+ },
2397
+ /** Response: return an OpenAI error. */
2398
+ error(status, message) {
2399
+ return {
2400
+ status,
2401
+ body: { error: {
2402
+ message: message ?? `OpenAI error (${status})`,
2403
+ type: status === 429 ? "rate_limit_error" : "api_error",
2404
+ code: status === 429 ? "rate_limit_exceeded" : null
2405
+ } }
2406
+ };
2407
+ },
2408
+ /** Response: return malformed content. */
2409
+ malformed(content) {
2410
+ return buildChatReply(content);
2411
+ },
2412
+ /** Response: simulate a timeout. */
2413
+ timeout() {
2414
+ return {
2415
+ status: 200,
2416
+ body: {},
2417
+ delay: 3e4
2418
+ };
2419
+ }
2420
+ };
2421
+ //#endregion
2422
+ //#region src/vitest/mock-of.ts
2423
+ /**
2424
+ * Create a deep mock proxy for a given type.
2425
+ * Wraps `vitest-mock-extended`'s `mockDeep` for convenient port mocking.
2426
+ */
2427
+ const mockOf = mockDeep;
2428
+ //#endregion
2429
+ //#region src/vitest/mock-of-date.ts
2430
+ /**
2431
+ * Freeze or reset the global Date for deterministic time-dependent tests.
2432
+ * Wraps the `mockdate` package.
2433
+ */
2434
+ const mockOfDate = MockDatePackage;
2435
+ //#endregion
2436
+ //#region src/browser/index.ts
2437
+ registerBrowserMatchers();
2438
+ /**
2439
+ * The five constructors, present and refusing. A component test never reaches
2440
+ * one: what it renders is a unit, and the assembled product behind an entry is
2441
+ * specified from a node project.
2442
+ */
2443
+ const specification = {
2444
+ api: () => refuse("specification.api()"),
2445
+ cli: () => refuse("specification.cli()"),
2446
+ jobs: () => refuse("specification.jobs()"),
2447
+ mobile: () => refuse("specification.mobile()"),
2448
+ website: () => refuse("specification.website()")
2449
+ };
2450
+ const postgres = () => refuse("postgres()");
2451
+ const redis = () => refuse("redis()");
2452
+ const sqlite = () => refuse("sqlite()");
2453
+ const ContainerAccessor = nodeOnlyClass("ContainerAccessor");
2454
+ const findContainersByLabel = () => refuse("findContainersByLabel()");
2455
+ const inspectContainer = () => refuse("inspectContainer()");
2456
+ const removeContainers = () => refuse("removeContainers()");
2457
+ const Orchestrator = nodeOnlyClass("Orchestrator");
2458
+ const BaseResult = nodeOnlyClass("BaseResult");
2459
+ const CliResult = nodeOnlyClass("CliResult");
2460
+ const DirectoryAccessor = nodeOnlyClass("DirectoryAccessor");
2461
+ const FetchResult = nodeOnlyClass("FetchResult");
2462
+ const FilesystemAccessor = nodeOnlyClass("FilesystemAccessor");
2463
+ const HttpResult = nodeOnlyClass("HttpResult");
2464
+ const PageResult = nodeOnlyClass("PageResult");
2465
+ const ResponseAccessor = nodeOnlyClass("ResponseAccessor");
2466
+ const ScreenResult = nodeOnlyClass("ScreenResult");
2467
+ /**
2468
+ * `text()` is real here: only its anchor differs. Under node the accessor
2469
+ * remembers the caller's directory so a golden resolves against it; in a page
2470
+ * the golden commands read the test's own path server-side, so there is
2471
+ * nothing for the accessor to carry.
2472
+ */
2473
+ function text(value) {
2474
+ return new TextAccessor(value, "text", "");
2475
+ }
2476
+ //#endregion
2477
+ export { BaseResult, CliResult, ContainerAccessor, DirectoryAccessor, FetchResult, FilesystemAccessor, HttpResult, JsonAccessor, Matcher, Orchestrator, PageResult, ResponseAccessor, ScreenResult, TableAccessor, TextAccessor, anthropic, banner, button, complementary, component, content, contentinfo, defineContract, defineContracts, dialog, disabled, enabled, field, findContainersByLabel, focused, form, heading, http, inspectContainer, link, listitem, main, match, mockOf, mockOfDate, navigation, openai, option, postgres, redis, region, removeContainers, row, search, selected, specification, sqlite, status, table, testId, text, valued, within };