@orkestrel/capture 0.0.8 → 0.0.10

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.
@@ -1,4 +1,4 @@
1
- import { INTRINSICS, arrayOf, holds, isError, isFiniteNumber, isFunction, isObject, isRecord, isString } from "@orkestrel/contract";
1
+ import { INTRINSICS, arrayOf, holds, isError, isFiniteNumber, isFunction, isObject, isRecord, isString, preview } from "@orkestrel/contract";
2
2
  // src/core/constants.ts
3
3
  /**
4
4
  * Lists the condition axes a capture failure carries, in the order the executable reports them.
@@ -7,7 +7,9 @@ import { INTRINSICS, arrayOf, holds, isError, isFiniteNumber, isFunction, isObje
7
7
  * `USAGE` is a refused command line and exits 64; every other condition exits 1. `SELECTION`
8
8
  * names a selector, variant, case, state, or portfolio the host does not declare. `HOST` names a
9
9
  * wrapper, configuration, or declaration fault. `STAGE` names a runner stage that did not
10
- * complete. `EVIDENCE` names a record, report, registry, or manifest that fails its protocol.
10
+ * complete. `EVIDENCE` names a record, report, journal, or manifest that fails its protocol, and a
11
+ * document of another version. `REGISTRY` names an accepted registry that is absent, fails
12
+ * authentication, or lags the declarations. `LOOKUP` names a state lookup that is absent or stale.
11
13
  * `CONTAINMENT` names a path that leaves the authorized roots.
12
14
  *
13
15
  * @example
@@ -21,6 +23,8 @@ var CAPTURE_ERROR_CODES = Object.freeze([
21
23
  "HOST",
22
24
  "STAGE",
23
25
  "EVIDENCE",
26
+ "REGISTRY",
27
+ "LOOKUP",
24
28
  "CONTAINMENT"
25
29
  ]);
26
30
  /**
@@ -70,10 +74,10 @@ var CAPTURE_REQUEST_PREFIX = "journey-selection";
70
74
  *
71
75
  * @example
72
76
  * ```ts
73
- * CAPTURE_VERSION // 1
77
+ * CAPTURE_VERSION // 2
74
78
  * ```
75
79
  */
76
- var CAPTURE_VERSION = 1;
80
+ var CAPTURE_VERSION = 2;
77
81
  /**
78
82
  * Holds the eight bytes every PNG file opens with.
79
83
  *
@@ -119,6 +123,31 @@ var CAPTURE_MANIFEST_FILE = "manifest.json";
119
123
  * ```
120
124
  */
121
125
  var CAPTURE_LOOKUPS_FILE = "lookups.json";
126
+ /**
127
+ * Names the tag prefix that marks a case's owner path and each ancestor of it.
128
+ *
129
+ * @example
130
+ * ```ts
131
+ * `${CAPTURE_OWNER_PREFIX}pages:mail` // 'owner:pages:mail'
132
+ * ```
133
+ */
134
+ var CAPTURE_OWNER_PREFIX = "owner:";
135
+ /**
136
+ * Names the journey artifact line prefixes that bind a run record and each case that ran.
137
+ *
138
+ * @remarks
139
+ * The preflight reader requires the line `record=<record path>` and one `case-ran=<full name>`
140
+ * line for each stamping case.
141
+ *
142
+ * @example
143
+ * ```ts
144
+ * `${CAPTURE_ARTIFACT_PREFIXES.case}mail opens the inbox` // 'case-ran=mail opens the inbox'
145
+ * ```
146
+ */
147
+ var CAPTURE_ARTIFACT_PREFIXES = Object.freeze({
148
+ record: "record=",
149
+ case: "case-ran="
150
+ });
122
151
  // src/core/errors.ts
123
152
  /**
124
153
  * Reports one capture failure under a stable condition axis.
@@ -313,11 +342,11 @@ function isCaptureIdentity(value) {
313
342
  * @example
314
343
  * ```ts
315
344
  * isCaptureRequest(JSON.parse(text)) // true for a well-formed runner request
316
- * isCaptureRequest({ version: 2 }) // false
345
+ * isCaptureRequest({ version: 1 }) // false
317
346
  * ```
318
347
  */
319
348
  function isCaptureRequest(value) {
320
- return holds(() => isRecord(value) && isCaptureIdentity(value) && value.version === 1 && (value.command === "journey" || value.command === "capture") && (value.mode === void 0 || typeof value.mode === "string" && value.mode.trim() !== "") && isCaptureSelector(value.selector) && arrayOf(isCaptureSegment)(value.variants) && value.variants.length > 0 && arrayOf(isString)(value.args) && (value.case === void 0 || typeof value.case === "string" && value.case.trim() !== "") && (value.state === void 0 || value.command === "capture" && isCaptureSegment(value.state)));
349
+ return holds(() => isRecord(value) && isCaptureIdentity(value) && value.version === 2 && (value.command === "journey" || value.command === "capture") && (value.mode === void 0 || typeof value.mode === "string" && value.mode.trim() !== "") && isCaptureSelector(value.selector) && arrayOf(isCaptureSegment)(value.variants) && value.variants.length > 0 && arrayOf(isString)(value.args) && (value.case === void 0 || typeof value.case === "string" && value.case.trim() !== "") && (value.state === void 0 || value.command === "capture" && isCaptureSegment(value.state)));
321
350
  }
322
351
  /**
323
352
  * Checks whether a collected declaration preserves its full owner and state population.
@@ -397,7 +426,7 @@ function isCaptureArtifact(value) {
397
426
  * ```
398
427
  */
399
428
  function isCaptureRun(value) {
400
- return holds(() => isRecord(value) && value.version === 1 && isCaptureSegment(value.variant) && typeof value.time === "string" && Number.isFinite(Date.parse(value.time)) && typeof value.complete === "boolean" && typeof value.reference === "boolean" && arrayOf(isCaptureDeclaration)(value.declarations) && arrayOf(isCaptureDestination)(value.registry) && arrayOf(isString)(value.passed) && arrayOf(isCaptureSegment)(value.observed) && arrayOf(isCaptureEntry)(value.entries) && (value.artifact === void 0 || isCaptureArtifact(value.artifact)) && (value.identity === void 0 && value.request === void 0 || isCaptureIdentity(value.identity) && isCaptureRequest(value.request)));
429
+ return holds(() => isRecord(value) && value.version === 2 && isCaptureSegment(value.variant) && typeof value.time === "string" && Number.isFinite(Date.parse(value.time)) && typeof value.complete === "boolean" && typeof value.reference === "boolean" && arrayOf(isCaptureDeclaration)(value.declarations) && arrayOf(isCaptureDestination)(value.registry) && arrayOf(isString)(value.passed) && arrayOf(isCaptureSegment)(value.observed) && arrayOf(isCaptureEntry)(value.entries) && (value.artifact === void 0 || isCaptureArtifact(value.artifact)) && (value.identity === void 0 && value.request === void 0 || isCaptureIdentity(value.identity) && isCaptureRequest(value.request)));
401
430
  }
402
431
  /**
403
432
  * Checks whether a shared-source digest retains both patterns and expanded file hashes.
@@ -427,7 +456,7 @@ function isCaptureDigest(value) {
427
456
  * ```
428
457
  */
429
458
  function isCaptureReceipt(value) {
430
- return holds(() => isRecord(value) && value.version === 1 && isCaptureSegment(value.variant) && typeof value.time === "string" && Number.isFinite(Date.parse(value.time)) && isRecord(value.report) && isCapturePath(value.report.file) && isCaptureHash(value.report.digest) && isCaptureHashes(value.inputs) && arrayOf(isCaptureDeclaration)(value.declarations) && arrayOf(isCaptureDestination)(value.registry) && typeof value.complete === "boolean");
459
+ return holds(() => isRecord(value) && value.version === 2 && isCaptureSegment(value.variant) && typeof value.time === "string" && Number.isFinite(Date.parse(value.time)) && isRecord(value.report) && isCapturePath(value.report.file) && isCaptureHash(value.report.digest) && isCaptureHashes(value.inputs) && arrayOf(isCaptureDeclaration)(value.declarations) && arrayOf(isCaptureDestination)(value.registry) && typeof value.complete === "boolean");
431
460
  }
432
461
  /**
433
462
  * Checks whether a registry document retains its receipts and required output pairs.
@@ -442,7 +471,7 @@ function isCaptureReceipt(value) {
442
471
  * ```
443
472
  */
444
473
  function isCaptureRegistry(value) {
445
- return holds(() => isRecord(value) && value.version === 1 && arrayOf(isCaptureReceipt)(value.receipts) && arrayOf(isCaptureDestination)(value.entries) && isCaptureHash(value.digest));
474
+ return holds(() => isRecord(value) && value.version === 2 && arrayOf(isCaptureReceipt)(value.receipts) && arrayOf(isCaptureDestination)(value.entries) && isCaptureHash(value.digest));
446
475
  }
447
476
  /**
448
477
  * Checks whether a lookup binds a passing case to its full run record and input hashes.
@@ -468,12 +497,12 @@ function isCaptureLookup(value) {
468
497
  *
469
498
  * @example
470
499
  * ```ts
471
- * isCaptureLookupJournal({ version: 1, inputs: {}, lookups: [] }) // true
472
- * isCaptureLookupJournal({ version: 2, inputs: {}, lookups: [] }) // false
500
+ * isCaptureLookupJournal({ version: 2, populations: {}, lookups: [] }) // true
501
+ * isCaptureLookupJournal({ version: 1, populations: {}, lookups: [] }) // false
473
502
  * ```
474
503
  */
475
504
  function isCaptureLookupJournal(value) {
476
- return holds(() => isRecord(value) && (value.collections === void 0 || arrayOf(isCaptureCollection)(value.collections)) && value.version === 1 && (value.manifest === void 0 || isCaptureHash(value.manifest)) && isRecord(value.inputs) && Object.entries(value.inputs).every(([digest, inputs]) => isCaptureHash(digest) && isCaptureHashes(inputs)) && arrayOf((entry) => isRecord(entry) && isCaptureHash(entry.inputs) && isCaptureLookup({
505
+ return holds(() => isRecord(value) && (value.collections === void 0 || arrayOf(isCaptureCollection)(value.collections)) && value.version === 2 && (value.manifest === void 0 || isCaptureHash(value.manifest)) && isRecord(value.populations) && Object.entries(value.populations).every(([digest, inputs]) => isCaptureHash(digest) && isCaptureHashes(inputs)) && arrayOf((entry) => isRecord(entry) && isCaptureHash(entry.inputs) && isCaptureLookup({
477
506
  ...entry,
478
507
  inputs: {}
479
508
  }))(value.lookups));
@@ -494,19 +523,19 @@ function isCaptureStamp(value) {
494
523
  return holds(() => isRecord(value) && isCaptureEntry(value) && isCaptureIdentity(value.identity) && typeof value.time === "string" && Number.isFinite(Date.parse(value.time)) && typeof value.commit === "string" && /^[a-f0-9]{40,64}$/u.test(value.commit) && arrayOf(isCapturePath)(value.dirty) && isCaptureHashes(value.own) && isCaptureDigest(value.shared) && isCaptureHashes(value.tests) && isCaptureHash(value.registry) && isRecord(value.image) && isCaptureHash(value.image.digest) && isFiniteNumber(value.image.size) && Number.isSafeInteger(value.image.size) && value.image.size > 0 && isFiniteNumber(value.image.modified) && value.image.modified >= 0);
495
524
  }
496
525
  /**
497
- * Checks whether an inherited manifest has the supported schema without discarding malformed rows.
526
+ * Checks whether an expanded manifest has the supported schema without discarding malformed rows.
498
527
  *
499
528
  * @param value - The manifest
500
529
  * @returns True if every inherited member validates; false otherwise
501
530
  *
502
531
  * @example
503
532
  * ```ts
504
- * isCaptureManifest(JSON.parse(text)) // true for a published manifest.json
533
+ * isCaptureManifest(readCaptureManifest(JSON.parse(text), file)) // true for an expanded manifest.json
505
534
  * isCaptureManifest('manifest') // false
506
535
  * ```
507
536
  */
508
537
  function isCaptureManifest(value) {
509
- return holds(() => isRecord(value) && value.version === 1 && isCaptureRegistry(value.registry) && isRecord(value.entries) && Object.entries(value.entries).every(([key, stamp]) => isCapturePath(key) && isCaptureStamp(stamp)) && arrayOf(isCaptureLookup)(value.lookups));
538
+ return holds(() => isRecord(value) && value.version === 2 && isCaptureRegistry(value.registry) && isRecord(value.entries) && Object.entries(value.entries).every(([key, stamp]) => isCapturePath(key) && isCaptureStamp(stamp)) && arrayOf(isCaptureLookup)(value.lookups));
510
539
  }
511
540
  /**
512
541
  * Checks whether collection evidence pins complete input membership and both external artifacts.
@@ -524,21 +553,68 @@ function isCaptureCollection(value) {
524
553
  return holds(() => isRecord(value) && isCaptureHash(value.registry) && isCaptureSegment(value.variant) && typeof value.project === "string" && value.project.trim() !== "" && isCaptureDigest(value.inputs) && isRecord(value.run) && isCapturePath(value.run.file) && isCaptureHash(value.run.digest) && isRecord(value.report) && isCapturePath(value.report.file) && isCaptureHash(value.report.digest));
525
554
  }
526
555
  /**
527
- * Checks optional collection metadata without upgrading historical image evidence.
556
+ * Checks whether an expanded manifest and its optional collection receipts have the supported schema.
528
557
  *
529
- * @param value - The inherited image transaction
530
- * @returns True if its existing manifest and any collection receipts are valid; false otherwise
558
+ * @param value - The expanded manifest
559
+ * @returns True if the manifest and any collection receipts are valid; false otherwise
531
560
  *
532
561
  * @example
533
562
  * ```ts
534
- * isCaptureStoredManifest(JSON.parse(text)) // true for a manifest with or without collections
535
- * isCaptureStoredManifest(null) // false
563
+ * isCaptureExpandedManifest(readCaptureManifest(JSON.parse(text), file)) // true with or without collections
564
+ * isCaptureExpandedManifest(null) // false
536
565
  * ```
537
566
  */
538
- function isCaptureStoredManifest(value) {
567
+ function isCaptureExpandedManifest(value) {
539
568
  return holds(() => isCaptureManifest(value) && isRecord(value) && (value.collections === void 0 || arrayOf(isCaptureCollection)(value.collections)));
540
569
  }
541
570
  /**
571
+ * Checks whether a digest names its file map by a table key beside its patterns and combined digest.
572
+ *
573
+ * @param value - The stored digest reference
574
+ * @returns True if the patterns are valid and both digests are SHA-256 hexadecimal; false otherwise
575
+ *
576
+ * @example
577
+ * ```ts
578
+ * isCaptureDigestReference({ patterns: ['src/**'], files: 'a'.repeat(64), digest: 'b'.repeat(64) }) // true
579
+ * isCaptureDigestReference({ patterns: ['src/**'], files: {}, digest: 'b'.repeat(64) }) // false
580
+ * ```
581
+ */
582
+ function isCaptureDigestReference(value) {
583
+ return holds(() => isRecord(value) && arrayOf(isCapturePattern)(value.patterns) && isCaptureHash(value.files) && isCaptureHash(value.digest));
584
+ }
585
+ /**
586
+ * Checks whether a stored manifest holds its population table and every member that names a table key.
587
+ *
588
+ * @param value - The decoded manifest file
589
+ * @returns True if the version, table, registry, stamps, lookups, and collections are valid; false otherwise
590
+ * @remarks Table digests and reference existence are verified when the document is read.
591
+ *
592
+ * @example
593
+ * ```ts
594
+ * isCaptureManifestDocument(JSON.parse(text)) // true for a written manifest.json
595
+ * isCaptureManifestDocument({ version: 1, populations: {}, entries: {}, lookups: [] }) // false
596
+ * ```
597
+ */
598
+ function isCaptureManifestDocument(value) {
599
+ return holds(() => isRecord(value) && isCaptureLookupJournal({
600
+ version: value.version,
601
+ populations: value.populations,
602
+ lookups: value.lookups
603
+ }) && isCaptureRegistry(value.registry) && isRecord(value.entries) && Object.entries(value.entries).every(([key, stamp]) => isCapturePath(key) && isRecord(stamp) && isCaptureDigestReference(stamp.shared) && isCaptureStamp({
604
+ ...stamp,
605
+ shared: {
606
+ ...stamp.shared,
607
+ files: {}
608
+ }
609
+ })) && (value.collections === void 0 || arrayOf((entry) => isRecord(entry) && isCaptureDigestReference(entry.inputs) && isCaptureCollection({
610
+ ...entry,
611
+ inputs: {
612
+ ...entry.inputs,
613
+ files: {}
614
+ }
615
+ }))(value.collections)));
616
+ }
617
+ /**
542
618
  * Checks the host's declared viewport without deriving geometry from an output name.
543
619
  *
544
620
  * @param value - The published viewport data
@@ -870,8 +946,8 @@ function readCaptureReport(value) {
870
946
  }));
871
947
  requireCaptureUnique(assertions.map(resolveLookupKey), "reporter case identities");
872
948
  return {
873
- start: Math.min(value.startTime, ...files.map((file) => file.start)),
874
- end: Math.max(...files.map((file) => file.end)),
949
+ start: files.reduce((start, file) => Math.min(start, file.start), value.startTime),
950
+ end: files.reduce((end, file) => Math.max(end, file.end), -Infinity),
875
951
  assertions
876
952
  };
877
953
  }
@@ -985,6 +1061,353 @@ function validateCaptureReceipt(receipt, report) {
985
1061
  }
986
1062
  if (receipt.registry.some((entry) => !eligible.some((declaration) => declaration.case === entry.case)) || new Set(receipt.registry.map((entry) => entry.project)).size > 1) throw new CaptureError("Registry receipt contains an undeclared output or mixes producing projects", { code: "EVIDENCE" });
987
1063
  }
988
- export { CAPTURE_ERROR_BRAND, CAPTURE_ERROR_CODES, CAPTURE_LOOKUPS_FILE, CAPTURE_MANIFEST_FILE, CAPTURE_PNG_SIGNATURE, CAPTURE_REGISTRY_FILE, CAPTURE_REQUEST_PREFIX, CAPTURE_STATUS_PRECEDENCE, CAPTURE_VERSION, CaptureError, collectCaptureChanges, collectCaptureDuplicates, describeCaptureDeclaration, describeCaptureDestination, describeCaptureError, describeCaptureIdentity, describeCaptureRequest, isCaptureArtifact, isCaptureBox, isCaptureCollection, isCaptureDeclaration, isCaptureDestination, isCaptureDigest, isCaptureEntry, isCaptureError, isCaptureGeometry, isCaptureHash, isCaptureHashes, isCaptureIdentity, isCaptureLookup, isCaptureLookupJournal, isCaptureManifest, isCapturePath, isCapturePattern, isCaptureReceipt, isCaptureRegistry, isCaptureRequest, isCaptureRun, isCaptureSegment, isCaptureSelector, isCaptureSources, isCaptureStamp, isCaptureStoredManifest, matchesCaptureMembers, matchesCaptureSelector, readCaptureDirty, readCaptureReport, requireCaptureUnique, resolveCaptureKey, resolveCaptureOwner, resolveCaptureStatus, resolveLookupKey, validateCaptureReceipt, validateCaptureRun };
1064
+ /**
1065
+ * Expands an owner path into its prefixes, from its scope through the owner itself.
1066
+ *
1067
+ * @param owner - A canonical owner path
1068
+ * @returns Each colon-bounded prefix, shortest first
1069
+ *
1070
+ * @example
1071
+ * ```ts
1072
+ * collectCaptureAncestors('pages:mail:inbox') // ['pages', 'pages:mail', 'pages:mail:inbox']
1073
+ * ```
1074
+ */
1075
+ function collectCaptureAncestors(owner) {
1076
+ return owner.split(":").map((_part, index, parts) => parts.slice(0, index + 1).join(":"));
1077
+ }
1078
+ /**
1079
+ * Builds the owner and capture tags a wrapper declares for its owner population.
1080
+ *
1081
+ * @param owners - Every canonical owner path the host declares
1082
+ * @returns The unique `owner:` tag of each owner and ancestor, and each owner's scope and part tags
1083
+ * @throws Thrown as a `HOST` capture error naming each owner that is not a canonical selector.
1084
+ *
1085
+ * @example
1086
+ * ```ts
1087
+ * buildCaptureTags(['pages:mail'])
1088
+ * // ['owner:pages', 'owner:pages:mail', 'pages', 'pages:mail']
1089
+ * ```
1090
+ */
1091
+ function buildCaptureTags(owners) {
1092
+ const invalid = owners.filter((owner) => !isCaptureSelector(owner));
1093
+ if (invalid.length > 0) throw new CaptureError(`Invalid capture owners: ${invalid.map((owner) => preview(owner)).join(", ")}; expected colon-separated portable segments such as "pages:mail"`, {
1094
+ code: "HOST",
1095
+ context: { owners: invalid }
1096
+ });
1097
+ return [...new Set(owners.flatMap((owner) => [...collectCaptureAncestors(owner).map((path) => `${CAPTURE_OWNER_PREFIX}${path}`), ...collectCaptureAncestors(owner).slice(0, 2)]))];
1098
+ }
1099
+ /**
1100
+ * Builds the Vitest test options of one capture case from its declaration.
1101
+ *
1102
+ * @param input - The case's owner, states, producing variant, and harness values
1103
+ * @param rules - The host's owners and part resolver
1104
+ * @returns The derived tags, the capture metadata, and the optional timeout
1105
+ * @throws Thrown as a `HOST` capture error for an undeclared owner or tag, tags beside an owner, capture tags with no states, or a state whose part is undeclared or outside the owner.
1106
+ *
1107
+ * @example
1108
+ * ```ts
1109
+ * buildCaptureTest({ owner: 'pages:mail', states: ['inbox'], variant: 'light-390' }, rules).tags
1110
+ * // ['owner:pages', 'owner:pages:mail', 'pages', 'pages:mail']
1111
+ * ```
1112
+ */
1113
+ function buildCaptureTest(input, rules) {
1114
+ const declared = buildCaptureTags(rules.owners);
1115
+ const owner = input.owner;
1116
+ if (owner !== void 0 && !declared.includes(`owner:${owner}`)) throw new CaptureError(`Unknown capture owner: ${preview(owner)}; expected a declared owner path or one of its ancestors`, {
1117
+ code: "HOST",
1118
+ context: { owner }
1119
+ });
1120
+ if (owner !== void 0 && input.tags !== void 0) throw new CaptureError(`Capture case owned by ${owner} derives its tags from its owner and states; remove its tags`, {
1121
+ code: "HOST",
1122
+ context: { owner }
1123
+ });
1124
+ const unknown = (input.tags ?? []).filter((tag) => !declared.includes(tag));
1125
+ if (unknown.length > 0) throw new CaptureError(`Unknown capture tags: ${unknown.map((tag) => preview(tag)).join(", ")}; expected tags the owners declare`, {
1126
+ code: "HOST",
1127
+ context: { tags: unknown }
1128
+ });
1129
+ if (input.states === void 0 && (input.tags ?? []).some((tag) => !tag.startsWith("owner:"))) throw new CaptureError("Capture case names capture tags but declares no states; declare its states, an empty list included", { code: "HOST" });
1130
+ const parts = (input.states ?? []).map((state) => {
1131
+ const part = rules.part(state);
1132
+ if (!declared.includes(`owner:${part}`)) throw new CaptureError(`Capture state ${state} resolves to an undeclared owner: ${preview(part)}`, {
1133
+ code: "HOST",
1134
+ context: {
1135
+ state,
1136
+ part
1137
+ }
1138
+ });
1139
+ if (owner !== void 0 && !matchesCaptureSelector(part, owner)) throw new CaptureError(`Capture state ${state} belongs to ${part}, outside owner ${owner}; split the case by owner`, {
1140
+ code: "HOST",
1141
+ context: {
1142
+ state,
1143
+ part,
1144
+ owner
1145
+ }
1146
+ });
1147
+ return part;
1148
+ });
1149
+ return {
1150
+ tags: [.../* @__PURE__ */ new Set([...input.owner === void 0 ? input.tags ?? [] : collectCaptureAncestors(input.owner).map((path) => `${CAPTURE_OWNER_PREFIX}${path}`), ...parts.flatMap((part) => collectCaptureAncestors(part).slice(0, 2))])],
1151
+ meta: {
1152
+ ...input.owner === void 0 ? {} : { owner: input.owner },
1153
+ ...input.states === void 0 ? {} : { states: [...input.states] },
1154
+ variant: input.variant,
1155
+ ...input.eligible === void 0 ? {} : { eligible: input.eligible }
1156
+ },
1157
+ ...input.timeout === void 0 ? {} : { timeout: input.timeout }
1158
+ };
1159
+ }
1160
+ /**
1161
+ * Collects every leaf case under a task, keeping cases a runner filter excluded and their results.
1162
+ *
1163
+ * @param task - A Vitest file, suite, or test task
1164
+ * @param ancestors - The titles of the suites that enclose the task, excluding the file name. Default: none
1165
+ * @returns Each case with its suite titles and own title joined by spaces, as the Vitest JSON reporter names it
1166
+ *
1167
+ * @example
1168
+ * ```ts
1169
+ * collectCaptureCases({ name: 'mail', mode: 'run', meta: {}, tasks: [inbox] })[0]?.name
1170
+ * // 'mail opens the inbox'
1171
+ * ```
1172
+ */
1173
+ function collectCaptureCases(task, ancestors = []) {
1174
+ const names = task.filepath === void 0 ? [...ancestors, task.name] : ancestors;
1175
+ if (task.tasks !== void 0) return task.tasks.flatMap((child) => collectCaptureCases(child, names));
1176
+ return [{
1177
+ name: names.join(" "),
1178
+ mode: task.mode,
1179
+ tags: [...task.tags ?? []],
1180
+ meta: {
1181
+ ...task.meta.owner === void 0 ? {} : { owner: task.meta.owner },
1182
+ ...task.meta.states === void 0 ? {} : { states: [...task.meta.states] },
1183
+ ...task.meta.variant === void 0 ? {} : { variant: task.meta.variant },
1184
+ ...task.meta.eligible === void 0 ? {} : { eligible: task.meta.eligible }
1185
+ },
1186
+ ...task.result === void 0 ? {} : { result: {
1187
+ state: task.result.state,
1188
+ ...task.result.duration === void 0 ? {} : { duration: task.result.duration }
1189
+ } }
1190
+ }];
1191
+ }
1192
+ /**
1193
+ * Refuses a selection whose cases place states owned outside the selected owner.
1194
+ *
1195
+ * @param cases - Every collected case, including cases a runner filter excluded
1196
+ * @param rules - The host's owners and part resolver
1197
+ * @param selection - The runner's selection, absent when no runner is the parent
1198
+ * @throws Thrown as a `SELECTION` capture error for an undeclared selector, and as a `HOST` capture error naming each case that places a selected state from outside the selected owner.
1199
+ *
1200
+ * @example
1201
+ * ```ts
1202
+ * requireCaptureCases(cases, rules, { selector: 'pages:mail' }) // returns when no case is parked
1203
+ * ```
1204
+ */
1205
+ function requireCaptureCases(cases, rules, selection) {
1206
+ if (selection === void 0 || selection.selector === "all") return;
1207
+ const { selector } = selection;
1208
+ if (!buildCaptureTags(rules.owners).includes(`owner:${selector}`)) throw new CaptureError(`Unknown capture selector: ${preview(selector)}; expected all or a declared owner path`, {
1209
+ code: "SELECTION",
1210
+ context: { selector }
1211
+ });
1212
+ const parked = cases.filter((entry) => selection.case === void 0 || entry.name === selection.case).flatMap((entry) => {
1213
+ const owner = entry.meta.owner;
1214
+ if (owner === void 0 || matchesCaptureSelector(owner, selector)) return [];
1215
+ const states = (entry.meta.states ?? []).filter((state) => matchesCaptureSelector(rules.part(state), selector));
1216
+ return states.length > 0 ? [`${entry.name}: owner ${owner}; foreign states ${states.join(", ")}`] : [];
1217
+ });
1218
+ if (parked.length > 0) throw new CaptureError(`Capture selection ${selector} is parked; split each case so its states stay inside its owner:\n${parked.join("\n")}`, {
1219
+ code: "HOST",
1220
+ context: {
1221
+ selector,
1222
+ parked
1223
+ }
1224
+ });
1225
+ }
1226
+ /**
1227
+ * Builds the required output pair of each state an eligible owner-bearing case declares.
1228
+ *
1229
+ * @param cases - Every collected case, including cases a runner filter excluded
1230
+ * @param rules - The host's part and source resolvers
1231
+ * @param options - The producing project and the portfolio mapping of each state
1232
+ * @returns One destination per declared state, in case and state order
1233
+ * @throws Thrown as a `HOST` capture error when a state has no single mapping or resolves outside its case's owner or the scope, part, and optional section form.
1234
+ *
1235
+ * @example
1236
+ * ```ts
1237
+ * buildCaptureDestinations(cases, rules, { project: 'journey:light-390', portfolios })[0]?.file
1238
+ * // 'tmp/captures/states/pages/inbox--light-390.png'
1239
+ * ```
1240
+ */
1241
+ function buildCaptureDestinations(cases, rules, options) {
1242
+ return cases.flatMap((entry) => {
1243
+ const declared = entry.meta.owner;
1244
+ if (declared === void 0 || entry.meta.eligible === false) return [];
1245
+ return (entry.meta.states ?? []).map((state) => {
1246
+ const mappings = options.portfolios.filter((portfolio) => portfolio.states.includes(state));
1247
+ const [mapping] = mappings;
1248
+ if (mapping === void 0 || mappings.length > 1) throw new CaptureError(`Capture state ${state} needs exactly one portfolio mapping; mapped by: ${mappings.map((candidate) => preview(candidate.portfolio)).join(", ") || "none"}`, {
1249
+ code: "HOST",
1250
+ context: { state }
1251
+ });
1252
+ const owner = rules.part(state);
1253
+ if (!matchesCaptureSelector(owner, declared)) throw new CaptureError(`Capture state ${state} belongs to ${owner}, outside owner ${declared} of ${entry.name}`, {
1254
+ code: "HOST",
1255
+ context: {
1256
+ state,
1257
+ owner,
1258
+ declared
1259
+ }
1260
+ });
1261
+ const [scope, part, section, ...rest] = owner.split(":");
1262
+ if (scope === void 0 || part === void 0 || rest.length > 0) throw new CaptureError(`Capture state ${state} resolves to ${preview(owner)}; expected scope:part or scope:part:section`, {
1263
+ code: "HOST",
1264
+ context: {
1265
+ state,
1266
+ owner
1267
+ }
1268
+ });
1269
+ return {
1270
+ portfolio: mapping.portfolio,
1271
+ state,
1272
+ scope,
1273
+ part,
1274
+ ...section === void 0 ? {} : { section },
1275
+ variant: mapping.variant,
1276
+ project: options.project,
1277
+ file: `${mapping.directory}/${mapping.scoped ? `${scope}/` : ""}${state}--${mapping.variant}.png`,
1278
+ case: entry.name,
1279
+ sources: rules.sources(owner)
1280
+ };
1281
+ });
1282
+ });
1283
+ }
1284
+ /**
1285
+ * Builds a run record from collected cases, the run's destinations, and its observed and emitted states.
1286
+ *
1287
+ * @param options - The cases, registry, observed states, emitted state-to-path pairs, and execution context
1288
+ * @returns The final record, without the journey artifact the caller binds after rendering it
1289
+ * @throws Thrown as a `HOST` capture error for an owner-bearing case with no variant, and as an `EVIDENCE` capture error for an emitted state with no destination, a path other than its destination's file, or a producing case with no measured duration.
1290
+ *
1291
+ * @example
1292
+ * ```ts
1293
+ * const run = buildCaptureRun({ cases, registry, observed, emitted, variant: 'light-390', time })
1294
+ * validateCaptureRun(run, readCaptureReport(parseJSON(text)), 'journey:light-390')
1295
+ * ```
1296
+ */
1297
+ function buildCaptureRun(options) {
1298
+ const declarations = options.cases.flatMap((entry) => {
1299
+ const { owner, variant } = entry.meta;
1300
+ if (owner === void 0) return [];
1301
+ if (variant === void 0) throw new CaptureError(`Owner-bearing case declares no variant: ${entry.name}`, { code: "HOST" });
1302
+ return [{
1303
+ case: entry.name,
1304
+ owner,
1305
+ variant,
1306
+ eligible: entry.meta.eligible !== false,
1307
+ states: [...entry.meta.states ?? []]
1308
+ }];
1309
+ });
1310
+ const passed = declarations.filter((declaration) => declaration.eligible && options.cases.some((entry) => entry.name === declaration.case && entry.result?.state === "pass")).map((declaration) => declaration.case);
1311
+ const entries = options.emitted.map(([state, path]) => {
1312
+ const destination = options.registry.find((entry) => entry.state === state);
1313
+ if (destination === void 0) throw new CaptureError(`Emitted state has no registry destination: ${preview(state)}`, {
1314
+ code: "EVIDENCE",
1315
+ context: { state }
1316
+ });
1317
+ const written = path.replaceAll("\\", "/");
1318
+ if (written !== destination.file && !written.endsWith(`/${destination.file}`)) throw new CaptureError(`Emitted state ${state} was written at ${preview(path)}, not at its destination ${destination.file}`, {
1319
+ code: "EVIDENCE",
1320
+ context: {
1321
+ state,
1322
+ path,
1323
+ file: destination.file
1324
+ }
1325
+ });
1326
+ const duration = options.cases.find((entry) => entry.name === destination.case)?.result?.duration;
1327
+ if (duration === void 0) throw new CaptureError(`Emitting case has no measured duration: ${destination.case}`, {
1328
+ code: "EVIDENCE",
1329
+ context: {
1330
+ state,
1331
+ case: destination.case
1332
+ }
1333
+ });
1334
+ return {
1335
+ ...destination,
1336
+ duration
1337
+ };
1338
+ });
1339
+ const eligible = declarations.filter((declaration) => declaration.eligible);
1340
+ const reference = options.registry.filter((entry) => entry.section === entry.state);
1341
+ const request = options.request;
1342
+ return {
1343
+ version: 2,
1344
+ ...request === void 0 ? {} : {
1345
+ identity: {
1346
+ id: request.id,
1347
+ stage: request.stage,
1348
+ pid: request.pid,
1349
+ config: request.config
1350
+ },
1351
+ request
1352
+ },
1353
+ variant: options.variant,
1354
+ time: options.time,
1355
+ complete: eligible.length > 0 && eligible.every((entry) => passed.includes(entry.case)),
1356
+ reference: reference.length > 0 && reference.every((entry) => passed.includes(entry.case)),
1357
+ declarations,
1358
+ registry: [...options.registry],
1359
+ passed,
1360
+ observed: [...options.observed],
1361
+ entries
1362
+ };
1363
+ }
1364
+ /**
1365
+ * Renders the journey artifact lines that bind a run record and each case that passed in it.
1366
+ *
1367
+ * @param record - The run record's portable path
1368
+ * @param run - The run whose passed cases the artifact names
1369
+ * @returns The `record=` line, then one `case-ran=` line per passed case, without line endings
1370
+ * @throws Thrown as an `EVIDENCE` capture error for a record path that is not portable or a case name that holds a line break.
1371
+ *
1372
+ * @example
1373
+ * ```ts
1374
+ * renderCaptureArtifact('tmp/captures/states/runs/run-1/selected/light-390.json', {
1375
+ * passed: ['mail opens the inbox'],
1376
+ * })
1377
+ * // ['record=tmp/captures/states/runs/run-1/selected/light-390.json', 'case-ran=mail opens the inbox']
1378
+ * ```
1379
+ */
1380
+ function renderCaptureArtifact(record, run) {
1381
+ if (!isCapturePath(record)) throw new CaptureError(`Artifact record path is not a portable relative path: ${preview(record)}`, {
1382
+ code: "EVIDENCE",
1383
+ context: { record }
1384
+ });
1385
+ const broken = run.passed.filter((name) => /[\r\n]/u.test(name));
1386
+ if (broken.length > 0) throw new CaptureError(`Artifact cannot carry case names with line breaks: ${broken.map((name) => preview(name)).join(", ")}`, {
1387
+ code: "EVIDENCE",
1388
+ context: { cases: broken }
1389
+ });
1390
+ return [`${CAPTURE_ARTIFACT_PREFIXES.record}${record}`, ...run.passed.map((name) => `${CAPTURE_ARTIFACT_PREFIXES.case}${name}`)];
1391
+ }
1392
+ /**
1393
+ * Reads the record bindings and the ran cases from a journey artifact's text.
1394
+ *
1395
+ * @param text - The artifact text, with LF or CRLF line endings
1396
+ * @returns The path of each `record=` line and the full name of each `case-ran=` line, in text order
1397
+ *
1398
+ * @example
1399
+ * ```ts
1400
+ * readCaptureArtifact('# light-390\r\nrecord=tmp/run.json\r\ncase-ran=mail opens the inbox\r\n')
1401
+ * // { records: ['tmp/run.json'], cases: ['mail opens the inbox'] }
1402
+ * ```
1403
+ */
1404
+ function readCaptureArtifact(text) {
1405
+ const lines = text.split(/\r\n|\n/u);
1406
+ return {
1407
+ records: lines.filter((line) => line.startsWith(CAPTURE_ARTIFACT_PREFIXES.record)).map((line) => line.slice(CAPTURE_ARTIFACT_PREFIXES.record.length)),
1408
+ cases: lines.filter((line) => line.startsWith(CAPTURE_ARTIFACT_PREFIXES.case)).map((line) => line.slice(CAPTURE_ARTIFACT_PREFIXES.case.length))
1409
+ };
1410
+ }
1411
+ export { CAPTURE_ARTIFACT_PREFIXES, CAPTURE_ERROR_BRAND, CAPTURE_ERROR_CODES, CAPTURE_LOOKUPS_FILE, CAPTURE_MANIFEST_FILE, CAPTURE_OWNER_PREFIX, CAPTURE_PNG_SIGNATURE, CAPTURE_REGISTRY_FILE, CAPTURE_REQUEST_PREFIX, CAPTURE_STATUS_PRECEDENCE, CAPTURE_VERSION, CaptureError, buildCaptureDestinations, buildCaptureRun, buildCaptureTags, buildCaptureTest, collectCaptureAncestors, collectCaptureCases, collectCaptureChanges, collectCaptureDuplicates, describeCaptureDeclaration, describeCaptureDestination, describeCaptureError, describeCaptureIdentity, describeCaptureRequest, isCaptureArtifact, isCaptureBox, isCaptureCollection, isCaptureDeclaration, isCaptureDestination, isCaptureDigest, isCaptureDigestReference, isCaptureEntry, isCaptureError, isCaptureExpandedManifest, isCaptureGeometry, isCaptureHash, isCaptureHashes, isCaptureIdentity, isCaptureLookup, isCaptureLookupJournal, isCaptureManifest, isCaptureManifestDocument, isCapturePath, isCapturePattern, isCaptureReceipt, isCaptureRegistry, isCaptureRequest, isCaptureRun, isCaptureSegment, isCaptureSelector, isCaptureSources, isCaptureStamp, matchesCaptureMembers, matchesCaptureSelector, readCaptureArtifact, readCaptureDirty, readCaptureReport, renderCaptureArtifact, requireCaptureCases, requireCaptureUnique, resolveCaptureKey, resolveCaptureOwner, resolveCaptureStatus, resolveLookupKey, validateCaptureReceipt, validateCaptureRun };
989
1412
 
990
1413
  //# sourceMappingURL=index.js.map