@enhance-eng/enhance 0.1.33 → 0.1.38

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/main.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
- import { $t as createOrganisationOutputSchema, At as PartialBatchError, Ct as canvasEditsSchema, Dt as fromCanvasReference, Et as canvasReferenceRenderTarget, Ft as createScreenOutputSchema, Gn as getCanvasDocumentOutputSchema, It as appendRecordingChunkOutputSchema, Kn as saveCanvasDocumentOutputSchema, Lt as completeRecordingOutputSchema, Mn as beginCanvasActivityOutputSchema, Nn as canvasAgentActivityPhaseSchema, Nt as appErrorSchema, Ot as hasCanvasReferenceScope, Pt as completeScreenOutputSchema, _ as PROCEDURE_DESCRIPTIONS, a as toFailurePayload, ar as canvasReadableSceneDocumentSchema, cr as canvasAuthoredStyleDeclarations, d as ProcessExitError, dr as canvasLayoutPriorityDeclarations, er as canvasWorldBoundsSchema, et as canvasRenderScopedInputSchema, f as createCapabilityCatalogAdapter, g as OPTION_DESCRIPTIONS, gt as canvasFindInputSchema, i as toExitCode, it as canvasRemoveCapabilityInputSchema, jt as CliError, k as operationStatusInputSchema, kt as parseCanvasReference, l as toSharedCapabilities, lr as canvasAxisStyleProperties, lt as canvasUpdateHtmlCapabilityInputSchema, m as createCapabilityPolicyAdapter, n as withCommandName, nn as withFixtureScreen, p as createRouterShapeAdapter, qn as canvasOperationSchema, r as toCanvasAuthoringResult, sr as canvasAuthoredLayoutValueOf, st as canvasReadInputSchema, t as withCommandInFailure, tn as emptyFixtureDocument, u as createMcpCapabilityDiscoveryAdapter, ur as canvasLayoutMainAxisOf, wn as canvasTextRunsOf, wt as assertCanvasReferenceNodes, yr as canvasSchema, zt as startRecordingOutputSchema } from "./cli-output-identity.lib-CWNAXho4.mjs";
3
- import { S as createAuthUseCase, _ as assertCanvasReferenceOperations, b as createCanvasActivityComposite, d as createRenderFileAdapter, f as readCanvasReferenceScene, g as createEditCanvasComposite, h as fromCapabilityReference, n as createHttpRemoteAdapter, o as createOauthLoopbackAdapter, p as createWriteHtmlCanvasComposite, r as readCliEnvironment, s as createCapabilityInvocationAdapter, t as createMutationKeyAdapter, v as sceneAtVersion, x as createRenderCanvasComposite, y as createApplyCanvasComposite } from "./mutation-key.adapter-A1d27TVY.mjs";
2
+ import { $t as createOrganisationOutputSchema, At as PartialBatchError, Ct as canvasEditsSchema, Dt as fromCanvasReference, Et as canvasReferenceRenderTarget, Ft as createScreenOutputSchema, It as appendRecordingChunkOutputSchema, Lt as completeRecordingOutputSchema, Mn as beginCanvasActivityOutputSchema, Mr as canvasSchema, Nn as canvasAgentActivityPhaseSchema, Nt as appErrorSchema, Ot as hasCanvasReferenceScope, Pt as completeScreenOutputSchema, Qn as canvasOperationSchema, Xn as getCanvasDocumentOutputSchema, Zn as saveCanvasDocumentOutputSchema, _ as PROCEDURE_DESCRIPTIONS, a as toFailurePayload, ar as canvasWorldBoundsSchema, d as ProcessExitError, et as canvasRenderScopedInputSchema, f as createCapabilityCatalogAdapter, fr as canvasAuthoredLayoutValueOf, g as OPTION_DESCRIPTIONS, gr as canvasLayoutPriorityDeclarations, gt as canvasFindInputSchema, hr as canvasLayoutMainAxisOf, i as toExitCode, it as canvasRemoveCapabilityInputSchema, jt as CliError, k as operationStatusInputSchema, kt as parseCanvasReference, l as toSharedCapabilities, lt as canvasUpdateHtmlCapabilityInputSchema, m as createCapabilityPolicyAdapter, mr as canvasAxisStyleProperties, n as withCommandName, nn as withFixtureScreen, p as createRouterShapeAdapter, pr as canvasAuthoredStyleDeclarations, r as toCanvasAuthoringResult, st as canvasReadInputSchema, t as withCommandInFailure, tn as emptyFixtureDocument, u as createMcpCapabilityDiscoveryAdapter, ur as canvasReadableSceneDocumentSchema, wn as canvasTextRunsOf, wt as assertCanvasReferenceNodes, zt as startRecordingOutputSchema } from "./cli-output-identity.lib-C3i0q8cd.mjs";
3
+ import { C as canvasRadialGradientSvg, D as canvasAngularGradientSvg, E as canvasDiamondGradientSvg, O as canvasColorCss, S as createAuthUseCase, T as canvasFilterListCss, _ as assertCanvasReferenceOperations, b as createCanvasActivityComposite, d as createRenderFileAdapter, f as readCanvasReferenceScene, g as createEditCanvasComposite, h as fromCapabilityReference, k as compareCanvasSortKeys, n as createHttpRemoteAdapter, o as createOauthLoopbackAdapter, p as createWriteHtmlCanvasComposite, r as readCliEnvironment, s as createCapabilityInvocationAdapter, t as createMutationKeyAdapter, v as sceneAtVersion, w as canvasLinearGradientSvg, x as createRenderCanvasComposite, y as createApplyCanvasComposite } from "./mutation-key.adapter-BVKXAugo.mjs";
4
4
  import { t as toCapabilityInventory } from "./capability-inventory.mapper-DyYXyVBJ.mjs";
5
5
  import { t as createFileCredentialAdapter } from "./file-credential.adapter-C78gc9OK.mjs";
6
6
  import process from "node:process";
@@ -17,22 +17,43 @@ import { mkdir, readFile, rename, stat, writeFile } from "node:fs/promises";
17
17
  import { channel } from "node:diagnostics_channel";
18
18
  import { proxify } from "trpc-cli/dist/proxify.js";
19
19
 
20
- //#region ../../packages/contract/src/canvas/canvas-color-css.lib.ts
21
- const BYTE_MAX = 255;
22
- const CHANNEL_PRECISION = 1e6;
23
- const roundedChannel = (value) => Math.round(value * BYTE_MAX * CHANNEL_PRECISION) / CHANNEL_PRECISION;
24
- const canvasColorCss = (color, opacity = 1) => {
25
- const alpha = color.alpha * opacity;
26
- if (color.space === "srgb") {
27
- const channels = [
28
- color.red,
29
- color.green,
30
- color.blue
31
- ].map((channel) => String(roundedChannel(channel))).join(" ");
32
- return alpha === 1 ? `rgb(${channels})` : `rgb(${channels} / ${String(alpha)})`;
33
- }
34
- const channels = `${String(color.red)} ${String(color.green)} ${String(color.blue)}`;
35
- return `color(${color.space} ${channels} / ${String(alpha)})`;
20
+ //#region ../../packages/contract/src/canvas/canvas-font-family.lib.ts
21
+ const GENERIC_FAMILIES = /* @__PURE__ */ new Set([
22
+ "cursive",
23
+ "emoji",
24
+ "fantasy",
25
+ "fangsong",
26
+ "math",
27
+ "monospace",
28
+ "sans-serif",
29
+ "serif",
30
+ "system-ui",
31
+ "ui-monospace",
32
+ "ui-rounded",
33
+ "ui-sans-serif",
34
+ "ui-serif"
35
+ ]);
36
+ const CSS_IDENTIFIER = /^-?[_a-z][-\w]*$/iu;
37
+ const CSS_VARIABLE = /^var\(--[-\w]+\)$/iu;
38
+ const MAX_UNICODE = 1114111;
39
+ const SURROGATE_START = 55296;
40
+ const SURROGATE_END = 57343;
41
+ const REPLACEMENT_CHARACTER = 65533;
42
+ const isCanvasGenericFontFamily = (family) => GENERIC_FAMILIES.has(family.toLowerCase());
43
+ const decodedCss = (value) => value.replaceAll(/\\(?:([\da-f]{1,6})(?:\r\n|[\t\n\f\r ])?|(\r\n|[\n\r\f])|([^\da-f]))/giu, (_match, hex, newline, literal) => {
44
+ if (newline !== void 0) return "";
45
+ if (hex === void 0) return literal ?? "";
46
+ const point = Number.parseInt(hex, 16);
47
+ return String.fromCodePoint(point === 0 || point > MAX_UNICODE || point >= SURROGATE_START && point <= SURROGATE_END ? REPLACEMENT_CHARACTER : point);
48
+ });
49
+ const canvasFontFamilyName = (token) => {
50
+ const value = token.trim();
51
+ const isQuoted = value.startsWith("\"") && value.endsWith("\"") || value.startsWith("'") && value.endsWith("'");
52
+ return decodedCss(isQuoted ? value.slice(1, -1) : value);
53
+ };
54
+ const canvasFontFamilyCss = (family) => {
55
+ if (family.startsWith("\"") && isCanvasGenericFontFamily(canvasFontFamilyName(family))) return JSON.stringify(canvasFontFamilyName(family));
56
+ return CSS_IDENTIFIER.test(family) || CSS_VARIABLE.test(family) ? family : JSON.stringify(family);
36
57
  };
37
58
 
38
59
  //#endregion
@@ -43,15 +64,12 @@ const canvasTextDirectionDeclarations = (direction) => direction === void 0 ? {}
43
64
  ...direction !== "auto" && { direction },
44
65
  "unicode-bidi": direction === "auto" ? "plaintext" : "isolate"
45
66
  };
46
- const CSS_IDENTIFIER = /^-?[_a-z][-\w]*$/iu;
47
- const CSS_VARIABLE = /^var\(--[-\w]+\)$/iu;
48
- const fontFamilyName = (family) => CSS_IDENTIFIER.test(family) || CSS_VARIABLE.test(family) ? family : JSON.stringify(family);
49
67
  const canvasTypographyFontFamily = (typography) => [.../* @__PURE__ */ new Set([
50
68
  typography.family,
51
69
  ...typography.family === "Inter" ? ["Inter Variable"] : [],
52
70
  ...typography.family === "JetBrains Mono" ? ["JetBrains Mono Variable"] : [],
53
71
  ...typography.fallbackFamilies
54
- ])].map((family) => fontFamilyName(family)).join(", ");
72
+ ])].map((family) => canvasFontFamilyCss(family)).join(", ");
55
73
  /** Weight is the sole wght owner; the remaining axes never shadow the visible weight field. */
56
74
  const canvasFontVariationSettings = (typography) => Object.entries({
57
75
  ...typography.variations,
@@ -89,7 +107,7 @@ const canvasTextDecorationDeclarations = (decoration) => ({
89
107
  //#endregion
90
108
  //#region ../../packages/contract/src/recording/event-stream.lib.ts
91
109
  /**
92
- * @justified docs/comments.md#intent
110
+ * @justified intent
93
111
  * The recording wire format, in one place, because the recorder, the seed and the player all
94
112
  * speak it.
95
113
  *
@@ -98,7 +116,7 @@ const canvasTextDecorationDeclarations = (decoration) => ({
98
116
  *
99
117
  * It has to work that way. rrweb emits the full snapshot as a *single event*, and with fonts and
100
118
  * images inlined that runs to megabytes; whole-event chunks would put that event's size under
101
- * the request ceiling, making the ceiling one on fidelity. docs/features/recorder.md#dom.
119
+ * the request ceiling, making the ceiling one on fidelity.
102
120
  *
103
121
  * A raw newline only ever separates records: `JSON.stringify` writes one inside a string as the
104
122
  * two characters `\` and `n`.
@@ -106,7 +124,7 @@ const canvasTextDecorationDeclarations = (decoration) => ({
106
124
  /** One event's line, terminator included. Every line ends in one, including the last. */
107
125
  const lineFor = (event) => `${JSON.stringify(event)}\n`;
108
126
  /**
109
- * @justified docs/comments.md#clarification
127
+ * @justified clarification
110
128
  * A recording being written, cut into ranges of at most `limit` units as it goes.
111
129
  *
112
130
  * A range comes out the moment it is full, because the point of streaming is that stopping is a
@@ -233,6 +251,7 @@ const createScreenFixtureComposite = (remote) => async (input) => {
233
251
  }));
234
252
  return {
235
253
  screenId: completed.screenId,
254
+ clientToken: input.clientToken,
236
255
  route: input.route,
237
256
  title: input.pageTitle,
238
257
  viewport: input.viewport,
@@ -837,27 +856,33 @@ const cssPaint = (paint) => {
837
856
  if (!paint.visible) return null;
838
857
  if (paint.kind === "solid") return cssColour(paint.color);
839
858
  if (paint.kind === "image") return `url(${JSON.stringify(paint.assetId)})`;
859
+ if (paint.kind === "angular-gradient" || paint.kind === "diamond-gradient") {
860
+ const svg = paint.kind === "angular-gradient" ? canvasAngularGradientSvg(paint) : canvasDiamondGradientSvg(paint);
861
+ return `url("data:image/svg+xml,${encodeURIComponent(svg)}") 0 0 / 100% 100% no-repeat`;
862
+ }
840
863
  const stops = paint.stops.map((stop) => `${cssColour(stop.color)} ${String(stop.position * PERCENT)}%`).join(", ");
841
- if (paint.kind === "linear-gradient") return `linear-gradient(${String(paint.angle)}deg, ${stops})`;
864
+ if (paint.kind === "linear-gradient") {
865
+ if (paint.transform !== void 0) return `url("data:image/svg+xml,${encodeURIComponent(canvasLinearGradientSvg({
866
+ ...paint,
867
+ transform: paint.transform
868
+ }))}") 0 0 / 100% 100% no-repeat`;
869
+ return `linear-gradient(${String(paint.angle)}deg, ${stops})`;
870
+ }
871
+ if (paint.transform !== void 0) return `url("data:image/svg+xml,${encodeURIComponent(canvasRadialGradientSvg(paint))}") 0 0 / 100% 100% no-repeat`;
842
872
  return `radial-gradient(at ${String(paint.center.x * PERCENT)}% ${String(paint.center.y * PERCENT)}%, ${stops})`;
843
873
  };
844
- const cssFilter = (filter) => {
845
- if (filter.kind === "blur") return `blur(${String(filter.value)}px)`;
846
- if (filter.kind === "hue-rotate") return `hue-rotate(${String(filter.value)}deg)`;
847
- const value = [
848
- "grayscale",
849
- "invert",
850
- "sepia"
851
- ].includes(filter.kind) ? `${String(filter.value * PERCENT)}%` : String(filter.value);
852
- return `${filter.kind}(${value})`;
853
- };
854
874
  const visiblePaints = (paints) => paints?.flatMap((paint) => {
855
875
  const value = cssPaint(paint);
856
876
  return value === null ? [] : [value];
857
877
  }) ?? [];
878
+ /** A CSS border or outline draws one colour, so only a single visible paint gives one. */
879
+ const strokePaint = (paints) => {
880
+ const visible = paints.filter((paint) => paint.visible);
881
+ return visible.length === 1 && visible[0] !== void 0 ? cssPaint(visible[0]) : null;
882
+ };
858
883
  const borderCss = (border) => {
859
884
  if (border?.visible !== true) return {};
860
- const paint = cssPaint(border.paint);
885
+ const paint = strokePaint(border.paints);
861
886
  return {
862
887
  "border-width": [
863
888
  border.width.top,
@@ -871,7 +896,7 @@ const borderCss = (border) => {
871
896
  };
872
897
  const outlineCss = (outline) => {
873
898
  if (outline?.visible !== true) return {};
874
- const paint = cssPaint(outline.paint);
899
+ const paint = strokePaint(outline.paints);
875
900
  return {
876
901
  "outline-width": `${String(outline.width)}px`,
877
902
  "outline-offset": `${String(outline.offset)}px`,
@@ -881,12 +906,12 @@ const outlineCss = (outline) => {
881
906
  };
882
907
  const effectCss = (appearance) => {
883
908
  const shadows = appearance.shadows?.filter((shadow) => shadow.visible).map((shadow) => `${shadow.kind === "inner" ? "inset " : ""}${String(shadow.offsetX)}px ${String(shadow.offsetY)}px ${String(shadow.blur)}px ${String(shadow.spread)}px ${cssColour(shadow.color)}`);
884
- const filters = appearance.filters?.filter((filter) => filter.visible).map(cssFilter);
885
- const backdrop = appearance.backdropFilters?.filter((filter) => filter.visible).map(cssFilter);
909
+ const filters = canvasFilterListCss(appearance.filters ?? []);
910
+ const backdrop = canvasFilterListCss(appearance.backdropFilters ?? []);
886
911
  return {
887
912
  ...shadows !== void 0 && shadows.length > 0 && { "box-shadow": shadows.join(", ") },
888
- ...filters !== void 0 && filters.length > 0 && { filter: filters.join(" ") },
889
- ...backdrop !== void 0 && backdrop.length > 0 && { "backdrop-filter": backdrop.join(" ") }
913
+ ...filters !== "" && { filter: filters },
914
+ ...backdrop !== "" && { "backdrop-filter": backdrop }
890
915
  };
891
916
  };
892
917
  const appearanceCss = (appearance) => {
@@ -989,7 +1014,7 @@ const computedCanvasNodeCss = (node, document) => ({
989
1014
 
990
1015
  //#endregion
991
1016
  //#region src/application/canvas-source-projection.use-case.ts
992
- const childrenOf = (document, parentId) => Object.entries(document.relationships).filter(([, relationship]) => relationship.parentId === parentId).toSorted(([leftId, left], [rightId, right]) => left.sortKey === right.sortKey ? leftId.localeCompare(rightId) : left.sortKey.localeCompare(right.sortKey)).map(([nodeId]) => nodeId);
1017
+ const childrenOf = (document, parentId) => Object.entries(document.relationships).filter(([, relationship]) => relationship.parentId === parentId).toSorted(([leftId, left], [rightId, right]) => left.sortKey === right.sortKey ? leftId.localeCompare(rightId) : compareCanvasSortKeys(left.sortKey, right.sortKey)).map(([nodeId]) => nodeId);
993
1018
  const requireNode = (document, nodeId) => {
994
1019
  const node = document.nodes[nodeId];
995
1020
  if (node === void 0) throw new CliError("NOT_FOUND", `Canvas node ${nodeId} does not exist.`, "Run canvas tree and use a current stable node id.");
@@ -1594,13 +1619,12 @@ const registerCanvasProgram = (program, input) => {
1594
1619
  };
1595
1620
 
1596
1621
  //#endregion
1597
- //#region ../../packages/sdk/dist/capture-files.lib-DmLQGNWF.mjs
1598
- const CAPTURE_KEY_LENGTH = 160;
1622
+ //#region ../../packages/sdk/dist/capture-files.lib-DbjZ8kU9.mjs
1599
1623
  const CAPTURE_METADATA_LENGTH = 200;
1600
1624
  const CAPTURE_ISSUE_LENGTH = 500;
1601
1625
  const CAPTURE_FAILURE_LENGTH = 1e3;
1602
1626
  const CAPTURE_UPLOAD_BATCH_SIZE = 400;
1603
- const key = z.string().trim().min(1).max(CAPTURE_KEY_LENGTH);
1627
+ const key = z.string().trim().min(1).max(160);
1604
1628
  const digest = z.string().regex(/^[a-f0-9]{64}$/u);
1605
1629
  const dimension = z.number().int().positive();
1606
1630
  const captureKeySchema = z.strictObject({
@@ -1614,6 +1638,30 @@ const captureBlobSchema = z.strictObject({
1614
1638
  bytes: z.number().int().positive(),
1615
1639
  mediaType: z.string().min(1).max(CAPTURE_METADATA_LENGTH)
1616
1640
  });
1641
+ const captureDestinationSchema = z.strictObject({ organisationId: z.uuid().optional() });
1642
+ const captureContextSchema = z.strictObject({
1643
+ key: z.string().min(1),
1644
+ label: z.string().min(1),
1645
+ url: z.url().optional(),
1646
+ sequence: z.number().int().nonnegative(),
1647
+ attempt: z.number().int().nonnegative().default(0)
1648
+ });
1649
+ const captureBaselineSelectionSchema = z.union([z.strictObject({ runId: z.uuid() }), z.strictObject({
1650
+ reference: z.string().min(1),
1651
+ revision: z.string().min(1).optional()
1652
+ })]);
1653
+ const captureReviewMetadataSchema = z.strictObject({
1654
+ destination: captureDestinationSchema,
1655
+ context: captureContextSchema.optional(),
1656
+ revision: z.string().min(1).optional(),
1657
+ baselineRunId: z.uuid().nullable(),
1658
+ compareTo: captureBaselineSelectionSchema.optional()
1659
+ });
1660
+ const captureVerdictSchema = z.enum([
1661
+ "awaiting-review",
1662
+ "approved",
1663
+ "changes-requested"
1664
+ ]);
1617
1665
  const captureArtifactSchema = z.strictObject({
1618
1666
  format: z.literal("enhance-capture"),
1619
1667
  version: z.literal(1),
@@ -1621,6 +1669,7 @@ const captureArtifactSchema = z.strictObject({
1621
1669
  label: key,
1622
1670
  journeyLabel: key,
1623
1671
  order: z.number().int().nonnegative(),
1672
+ page: z.string().min(1).optional(),
1624
1673
  viewport: z.strictObject({
1625
1674
  width: dimension,
1626
1675
  height: dimension,
@@ -1693,7 +1742,8 @@ const captureRunDescriptorSchema = z.strictObject({
1693
1742
  generation: z.number().int().nonnegative(),
1694
1743
  participants: z.array(key).min(1),
1695
1744
  expiresAt: z.iso.datetime(),
1696
- formatVersion: z.literal(1)
1745
+ formatVersion: z.literal(1),
1746
+ review: captureReviewMetadataSchema.optional()
1697
1747
  });
1698
1748
  const captureAttemptSchema = z.strictObject({
1699
1749
  participant: key,
@@ -1707,6 +1757,11 @@ const captureAttemptSchema = z.strictObject({
1707
1757
  "interrupted",
1708
1758
  "timedOut"
1709
1759
  ]),
1760
+ title: z.string().min(1).optional(),
1761
+ location: z.strictObject({
1762
+ file: z.string().min(1),
1763
+ line: z.number().int()
1764
+ }).optional(),
1710
1765
  captures: z.array(captureArtifactSchema)
1711
1766
  });
1712
1767
  const captureManifestSchema = z.strictObject({
@@ -1741,11 +1796,25 @@ const captureReceiptSchema = z.strictObject({
1741
1796
  }))
1742
1797
  });
1743
1798
  const beginCaptureRunInputSchema = z.strictObject({
1744
- canvasId: z.uuid(),
1799
+ canvasId: z.uuid().optional(),
1800
+ destination: captureDestinationSchema.optional(),
1801
+ title: z.string().trim().min(1).optional(),
1802
+ context: captureContextSchema.optional(),
1803
+ revision: z.string().min(1).optional(),
1804
+ compareTo: captureBaselineSelectionSchema.optional(),
1745
1805
  source: key.default("default"),
1746
1806
  runKey: key,
1747
1807
  participants: z.array(key).min(1).default(["local"]),
1748
1808
  formatVersion: z.literal(1).default(1)
1809
+ }).superRefine((input, ctx) => {
1810
+ if (input.canvasId === void 0 === (input.destination === void 0)) ctx.addIssue({
1811
+ code: "custom",
1812
+ message: "Choose either a canvas or a destination for this run."
1813
+ });
1814
+ if (input.canvasId !== void 0 && (input.context !== void 0 || input.compareTo !== void 0)) ctx.addIssue({
1815
+ code: "custom",
1816
+ message: "Run review requires a destination."
1817
+ });
1749
1818
  });
1750
1819
  const beginCaptureRunOutputSchema = z.strictObject({ run: captureRunDescriptorSchema });
1751
1820
  z.strictObject({ runId: z.uuid() });
@@ -1761,6 +1830,7 @@ const getCaptureRunOutputSchema = z.strictObject({
1761
1830
  run: captureRunDescriptorSchema,
1762
1831
  state: captureRunStateSchema,
1763
1832
  receipt: captureReceiptSchema.nullable(),
1833
+ verdict: captureVerdictSchema.optional(),
1764
1834
  failure: z.strictObject({
1765
1835
  code: key,
1766
1836
  message: z.string().max(CAPTURE_FAILURE_LENGTH)
@@ -1778,7 +1848,6 @@ const reserveCaptureBlobsOutputSchema = z.strictObject({ uploads: z.array(z.stri
1778
1848
  expiresAt: z.iso.datetime()
1779
1849
  }).nullable()
1780
1850
  })).max(CAPTURE_UPLOAD_BATCH_SIZE) });
1781
- z.strictObject({ manifest: captureManifestSchema });
1782
1851
  const COMMIT_LENGTH = 200;
1783
1852
  z.strictObject({
1784
1853
  canvasId: z.uuid(),
@@ -1799,6 +1868,28 @@ z.strictObject({
1799
1868
  before: preview,
1800
1869
  after: preview
1801
1870
  });
1871
+ const CODE_LENGTH = 8;
1872
+ const FNV_OFFSET = 2166136261;
1873
+ const FNV_PRIME = 16777619;
1874
+ const HEX = 16;
1875
+ /** FNV-1a: a short code that is the same for the same text on every run and every platform. */
1876
+ const shortCode = (text) => {
1877
+ let hash = FNV_OFFSET;
1878
+ for (const character of text) {
1879
+ hash ^= character.codePointAt(0) ?? 0;
1880
+ hash = Math.imul(hash, FNV_PRIME) >>> 0;
1881
+ }
1882
+ return hash.toString(HEX).padStart(CODE_LENGTH, "0");
1883
+ };
1884
+ /**
1885
+ * A name within the key limit. A longer one keeps its start and gains a code made from the whole
1886
+ * name, so two long names that share a start stay apart and the same name always shortens the same way.
1887
+ */
1888
+ const fitCaptureName = (name) => {
1889
+ const trimmed = name.trim();
1890
+ if (trimmed.length <= 160) return trimmed;
1891
+ return `${trimmed.slice(0, 160 - CODE_LENGTH - 1).trimEnd()} ${shortCode(trimmed)}`;
1892
+ };
1802
1893
  const captureKeyString = (key) => JSON.stringify([
1803
1894
  key.source,
1804
1895
  key.journey,
@@ -1852,95 +1943,222 @@ const canonicalCaptureJson = (value) => {
1852
1943
  }
1853
1944
  return state.output.join("");
1854
1945
  };
1946
+ /** Each file once, described as its first capture described it. */
1855
1947
  const captureBlobs = (artifacts) => {
1856
- const blobs = /* @__PURE__ */ new Map();
1948
+ const seen = /* @__PURE__ */ new Set();
1857
1949
  const unique = [];
1858
- for (const artifact of artifacts) {
1859
- const references = [
1860
- artifact.source.blob,
1861
- artifact.preview.blob,
1862
- ...artifact.assets.map((asset) => asset.blob)
1863
- ];
1864
- for (const blob of references) {
1865
- const previous = blobs.get(blob.sha256);
1866
- if (previous !== void 0 && canonicalCaptureJson(previous) !== canonicalCaptureJson(blob)) return "The same capture digest has conflicting blob metadata.";
1867
- if (previous === void 0) {
1868
- unique.push(blob);
1869
- blobs.set(blob.sha256, blob);
1870
- }
1871
- }
1950
+ for (const artifact of artifacts) for (const blob of [
1951
+ artifact.source.blob,
1952
+ artifact.preview.blob,
1953
+ ...artifact.assets.map((asset) => asset.blob)
1954
+ ]) if (!seen.has(blob.sha256)) {
1955
+ seen.add(blob.sha256);
1956
+ unique.push(blob);
1872
1957
  }
1873
1958
  return unique.toSorted((a, b) => compare(a.sha256, b.sha256));
1874
1959
  };
1960
+ const testIdentity = (attempt) => JSON.stringify([
1961
+ attempt.participant,
1962
+ attempt.project,
1963
+ attempt.testId
1964
+ ]);
1965
+ /**
1966
+ * Each test's last attempt that captured anything, whatever its result. Attempts from an
1967
+ * unreserved participant are left out; of two records of one attempt, the first is kept.
1968
+ */
1875
1969
  const finalAttempts = (manifest) => {
1876
- const expected = new Set(manifest.run.participants);
1877
- if (expected.size !== manifest.run.participants.length || manifest.participants.length !== expected.size || new Set(manifest.participants.map((part) => part.id)).size !== expected.size || manifest.participants.some((part) => !expected.has(part.id) || part.status !== "passed")) return "Every reserved participant must finish successfully exactly once.";
1878
- const attempts = /* @__PURE__ */ new Map();
1879
- const terminal = /* @__PURE__ */ new Map();
1970
+ const reserved = new Set(manifest.run.participants);
1971
+ const recorded = /* @__PURE__ */ new Set();
1972
+ const selected = /* @__PURE__ */ new Map();
1880
1973
  for (const attempt of manifest.attempts) {
1881
- if (!expected.has(attempt.participant)) return "Capture attempt belongs to an unreserved participant.";
1882
- const identity = JSON.stringify([
1883
- attempt.participant,
1884
- attempt.project,
1885
- attempt.testId
1886
- ]);
1887
- const attemptKey = JSON.stringify([identity, attempt.retry]);
1888
- const content = canonicalCaptureJson(attempt);
1889
- if (content === null) return "Capture attempts must contain finite JSON values.";
1890
- const previous = terminal.get(attemptKey);
1891
- if (previous !== void 0 && previous !== content) return "Conflicting terminal records for the same test attempt.";
1892
- terminal.set(attemptKey, content);
1893
- const selected = attempts.get(identity);
1894
- if (selected === void 0 || selected.retry < attempt.retry) attempts.set(identity, attempt);
1895
- }
1896
- return manifest.attempts.filter((attempt) => attempts.get(JSON.stringify([
1897
- attempt.participant,
1898
- attempt.project,
1899
- attempt.testId
1900
- ])) === attempt);
1901
- };
1902
- const uniqueCaptures = (source, artifacts) => {
1903
- const keys = /* @__PURE__ */ new Set();
1904
- const orders = /* @__PURE__ */ new Set();
1905
- for (const artifact of artifacts) {
1906
- if (artifact.key.source !== source) return "Capture source differs from its reserved run.";
1907
- const identity = captureKeyString(artifact.key);
1908
- if (keys.has(identity)) return `Duplicate capture key: ${identity}`;
1909
- const order = JSON.stringify([
1910
- artifact.key.journey,
1911
- artifact.key.variant,
1912
- artifact.order
1913
- ]);
1914
- if (orders.has(order)) return `Duplicate step order in journey ${artifact.key.journey}.`;
1915
- keys.add(identity);
1916
- orders.add(order);
1974
+ const record = JSON.stringify([testIdentity(attempt), attempt.retry]);
1975
+ if (!reserved.has(attempt.participant) || recorded.has(record)) continue;
1976
+ recorded.add(record);
1977
+ if (attempt.captures.length === 0) continue;
1978
+ const previous = selected.get(testIdentity(attempt));
1979
+ if (previous === void 0 || previous.retry < attempt.retry) selected.set(testIdentity(attempt), attempt);
1917
1980
  }
1918
- return null;
1981
+ return manifest.attempts.filter((attempt) => selected.get(testIdentity(attempt)) === attempt);
1919
1982
  };
1920
- const compareCaptureArtifacts = (left, right) => {
1921
- const journey = compare(left.key.journey, right.key.journey);
1922
- if (journey !== 0) return journey;
1923
- const variant = compare(left.key.variant, right.key.variant);
1924
- return variant === 0 ? left.order - right.order : variant;
1983
+ const rowOf = (artifact) => JSON.stringify([artifact.key.journey, artifact.key.variant]);
1984
+ /** Journey, variant and position first; then test file, line and call order, which never depend on timing. */
1985
+ const firstDifference = (...differences) => differences.find((difference) => difference !== 0) ?? 0;
1986
+ const compareEntries = (left, right) => firstDifference(compare(left.artifact.key.journey, right.artifact.key.journey), compare(left.artifact.key.variant, right.artifact.key.variant), left.artifact.order - right.artifact.order, compare(left.attempt.location?.file ?? "", right.attempt.location?.file ?? ""), (left.attempt.location?.line ?? 0) - (right.attempt.location?.line ?? 0), compare(testIdentity(left.attempt), testIdentity(right.attempt)), left.index - right.index);
1987
+ /**
1988
+ * What tells repeated captures of one step apart: repeats within one attempt are numbered, and a
1989
+ * step several tests captured is named after each test.
1990
+ */
1991
+ const stepSuffixes = (entries) => {
1992
+ const groups = Map.groupBy(entries, (entry) => captureKeyString(entry.artifact.key));
1993
+ const suffixes = /* @__PURE__ */ new Map();
1994
+ for (const group of groups.values()) {
1995
+ const tests = Map.groupBy(group, (entry) => testIdentity(entry.attempt));
1996
+ for (const repeats of tests.values()) for (const [repeat, entry] of repeats.entries()) {
1997
+ const test = tests.size > 1 ? ` · ${entry.attempt.title ?? entry.attempt.testId}` : "";
1998
+ const count = repeat > 0 ? ` (${String(repeat + 1)})` : "";
1999
+ suffixes.set(entry, `${test}${count}`);
2000
+ }
2001
+ }
2002
+ return suffixes;
1925
2003
  };
1926
- /** All publishers select whole terminal attempts with the same completeness rules. */
2004
+ /** All publishers select captures with the same rules, so the SDK and the API agree on every frame. */
1927
2005
  const selectedCaptures = (input) => {
1928
2006
  const parsed = captureManifestSchema.safeParse(input);
1929
2007
  if (!parsed.success) return "Invalid capture manifest.";
1930
2008
  const manifest = parsed.data;
1931
- const attempts = finalAttempts(manifest);
1932
- if (typeof attempts === "string") return attempts;
1933
- const artifacts = attempts.flatMap((attempt) => attempt.status === "passed" ? attempt.captures : []);
1934
- if (artifacts.length === 0) return "A run must contain at least one successful capture.";
1935
- const conflict = uniqueCaptures(manifest.run.source, artifacts);
1936
- if (conflict !== null) return conflict;
1937
- const blobs = captureBlobs(artifacts);
1938
- return typeof blobs === "string" ? blobs : artifacts.toSorted(compareCaptureArtifacts);
2009
+ const entries = finalAttempts(manifest).flatMap((attempt) => attempt.captures.map((artifact, index) => ({
2010
+ artifact,
2011
+ attempt,
2012
+ index
2013
+ }))).filter((entry) => entry.artifact.key.source === manifest.run.source).toSorted(compareEntries);
2014
+ if (entries.length === 0) return "A run must contain at least one capture.";
2015
+ const suffixes = stepSuffixes(entries);
2016
+ const descriptions = new Map(captureBlobs(entries.map((entry) => entry.artifact)).map((blob) => [blob.sha256, blob]));
2017
+ const described = (blob) => descriptions.get(blob.sha256) ?? blob;
2018
+ const pages = /* @__PURE__ */ new Map();
2019
+ const positions = /* @__PURE__ */ new Map();
2020
+ return entries.map((entry) => {
2021
+ const { artifact } = entry;
2022
+ const row = rowOf(artifact);
2023
+ if (!pages.has(row)) pages.set(row, artifact.page);
2024
+ const order = positions.get(row) ?? 0;
2025
+ positions.set(row, order + 1);
2026
+ const suffix = suffixes.get(entry) ?? "";
2027
+ const page = pages.get(row);
2028
+ const placed = { ...artifact };
2029
+ delete placed.page;
2030
+ return {
2031
+ ...placed,
2032
+ ...page !== void 0 && { page },
2033
+ key: {
2034
+ ...artifact.key,
2035
+ step: fitCaptureName(`${artifact.key.step}${suffix}`)
2036
+ },
2037
+ label: fitCaptureName(`${artifact.label}${suffix}`),
2038
+ order,
2039
+ source: {
2040
+ ...artifact.source,
2041
+ blob: described(artifact.source.blob)
2042
+ },
2043
+ preview: {
2044
+ ...artifact.preview,
2045
+ blob: described(artifact.preview.blob)
2046
+ },
2047
+ assets: artifact.assets.map((asset) => ({
2048
+ ...asset,
2049
+ blob: described(asset.blob)
2050
+ }))
2051
+ };
2052
+ });
1939
2053
  };
2054
+ /** The same reserved run. Its expiry moves with each upload and seal, so it is not part of its identity. */
2055
+ const isSameCaptureRun = (left, right) => canonicalCaptureJson({
2056
+ ...left,
2057
+ expiresAt: ""
2058
+ }) === canonicalCaptureJson({
2059
+ ...right,
2060
+ expiresAt: ""
2061
+ });
1940
2062
  const captureManifestContent = (manifest) => {
1941
2063
  const serialized = canonicalCaptureJson(manifest);
1942
2064
  return serialized === null ? null : `enhance-capture-run:v1\0${serialized}`;
1943
2065
  };
2066
+ const mergeCaptureManifests = (parts) => {
2067
+ const first = parts[0];
2068
+ if (first === void 0) return "At least one participant manifest is required.";
2069
+ const participants = /* @__PURE__ */ new Map();
2070
+ const attempts = [];
2071
+ for (const part of parts) {
2072
+ if (!isSameCaptureRun(part.run, first.run) || part.ordering !== first.ordering) return "Participant manifests must belong to the same reserved run and ordering.";
2073
+ if (part.participants.some((participant) => participants.has(participant.id))) continue;
2074
+ for (const participant of part.participants) participants.set(participant.id, participant);
2075
+ attempts.push(...part.attempts.filter((attempt) => part.participants.some((participant) => participant.id === attempt.participant)));
2076
+ }
2077
+ const manifest = {
2078
+ ...first,
2079
+ participants: Array.from(participants, ([, participant]) => participant).toSorted((a, b) => compare(a.id, b.id)),
2080
+ attempts: attempts.toSorted((a, b) => {
2081
+ const participant = compare(a.participant, b.participant);
2082
+ if (participant !== 0) return participant;
2083
+ const project = compare(a.project, b.project);
2084
+ if (project !== 0) return project;
2085
+ const test = compare(a.testId, b.testId);
2086
+ return test === 0 ? a.retry - b.retry : test;
2087
+ })
2088
+ };
2089
+ const selected = selectedCaptures(manifest);
2090
+ return typeof selected === "string" ? selected : manifest;
2091
+ };
2092
+ const NAMED_KEY_FIELDS = [
2093
+ "journey",
2094
+ "step",
2095
+ "variant"
2096
+ ];
2097
+ const NAMED_FIELDS = ["label", "journeyLabel"];
2098
+ const fitted = (value) => typeof value === "string" ? fitCaptureName(value) : value;
2099
+ /** A capture whose names a test author wrote too long is shortened, never refused. */
2100
+ const fitCaptureNames = (raw) => {
2101
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return raw;
2102
+ const capture = { ...raw };
2103
+ for (const field of NAMED_FIELDS) capture[field] = fitted(capture[field]);
2104
+ const captureKey = capture["key"];
2105
+ if (typeof captureKey === "object" && captureKey !== null && !Array.isArray(captureKey)) {
2106
+ const named = { ...captureKey };
2107
+ for (const field of NAMED_KEY_FIELDS) named[field] = fitted(named[field]);
2108
+ capture["key"] = named;
2109
+ }
2110
+ return capture;
2111
+ };
2112
+ /**
2113
+ * A manifest checked in outline, then capture by capture: one capture that fails its own checks
2114
+ * is left out, and the rest of the run still publishes.
2115
+ */
2116
+ const lenientCaptureManifestSchema = captureManifestSchema.extend({ attempts: z.array(captureAttemptSchema.extend({ captures: z.array(z.unknown()) })) }).transform((manifest) => ({
2117
+ ...manifest,
2118
+ attempts: manifest.attempts.map((attempt) => ({
2119
+ ...attempt,
2120
+ captures: attempt.captures.flatMap((capture) => {
2121
+ const parsed = captureArtifactSchema.safeParse(fitCaptureNames(capture));
2122
+ return parsed.success ? [parsed.data] : [];
2123
+ })
2124
+ }))
2125
+ }));
2126
+ z.strictObject({ manifest: lenientCaptureManifestSchema });
2127
+ z.strictObject({ canvasId: z.uuid() }).extend({ verdict: captureVerdictSchema });
2128
+ const captureReferenceInputSchema = z.strictObject({
2129
+ canvasId: z.uuid(),
2130
+ name: z.string().min(1)
2131
+ });
2132
+ const captureReferenceSchema = z.strictObject({
2133
+ runId: z.uuid(),
2134
+ revision: z.string(),
2135
+ version: z.number().int().positive()
2136
+ });
2137
+ const updateCaptureReferenceInputSchema = captureReferenceInputSchema.extend({
2138
+ expectedVersion: z.number().int().nonnegative(),
2139
+ revision: z.string().min(1)
2140
+ });
2141
+ const captureReviewSchema = z.strictObject({
2142
+ current: getCaptureRunOutputSchema,
2143
+ latest: captureRunDescriptorSchema,
2144
+ related: z.array(z.strictObject({
2145
+ run: captureRunDescriptorSchema,
2146
+ verdict: captureVerdictSchema
2147
+ })),
2148
+ changes: z.array(z.strictObject({
2149
+ key: captureKeySchema,
2150
+ frameId: z.string(),
2151
+ label: z.string(),
2152
+ journeyLabel: z.string(),
2153
+ page: z.string().optional(),
2154
+ change: z.enum([
2155
+ "new",
2156
+ "changed",
2157
+ "unchanged",
2158
+ "uncompared"
2159
+ ])
2160
+ }))
2161
+ });
1944
2162
  const captureError = (code, message, runId) => Object.assign(new Error(message), {
1945
2163
  code,
1946
2164
  ...runId !== void 0 && { runId }
@@ -1997,108 +2215,13 @@ const writeCaptureJson = async (path, value) => {
1997
2215
  };
1998
2216
  const readCaptureManifest = async (path) => {
1999
2217
  const raw = JSON.parse(await readFile(path, "utf8"));
2000
- return captureManifestSchema.parse(raw);
2218
+ return lenientCaptureManifestSchema.parse(raw);
2001
2219
  };
2002
2220
 
2003
2221
  //#endregion
2004
- //#region ../../packages/sdk/dist/capture-client.client-D7YPcnYK.mjs
2005
- const UPLOAD_BATCH_SIZE = 400;
2006
- const POLL_INTERVAL_MS = 250;
2007
- const uploadBlob = async (input) => {
2008
- if (input.held === void 0) throw captureError("transport", "Enhance omitted a requested blob reservation.", input.runId);
2009
- const upload = input.held.upload;
2010
- if (upload === null) return;
2011
- const bytes = await readCaptureBlob(input.directory, input.blob);
2012
- try {
2013
- if (!(await fetch(upload.url, {
2014
- method: "PUT",
2015
- headers: upload.headers,
2016
- body: new Blob([Uint8Array.from(bytes)]),
2017
- signal: AbortSignal.timeout(input.transport.timeoutMs),
2018
- redirect: "error"
2019
- })).ok) throw captureError("transport", "Upload refused.", input.runId);
2020
- } catch {
2021
- throw captureError("transport", "Capture upload was not confirmed. Resume the same manifest.", input.runId);
2022
- }
2023
- };
2024
- const uploadBlobs = async (transport, manifest, directory, blobs) => {
2025
- let unavailable = 0;
2026
- const available = [];
2027
- for (const blob of blobs) try {
2028
- await readCaptureBlob(directory, blob);
2029
- available.push(blob);
2030
- } catch {
2031
- unavailable++;
2032
- }
2033
- for (let start = 0; start < available.length; start += UPLOAD_BATCH_SIZE) {
2034
- const batch = available.slice(start, start + UPLOAD_BATCH_SIZE);
2035
- const reserved = await transport.request("captureRun.reserveAssets", {
2036
- runId: manifest.run.id,
2037
- blobs: batch
2038
- }, reserveCaptureBlobsOutputSchema);
2039
- const uploads = new Map(reserved.uploads.map((item) => [item.sha256, item]));
2040
- for (const blob of batch) try {
2041
- await uploadBlob({
2042
- transport,
2043
- runId: manifest.run.id,
2044
- directory,
2045
- blob,
2046
- held: uploads.get(blob.sha256)
2047
- });
2048
- } catch {
2049
- unavailable++;
2050
- }
2051
- }
2052
- if (unavailable > 0) channel("enhance.capture.resources").publish({
2053
- stage: "upload",
2054
- runId: manifest.run.id,
2055
- unavailable
2056
- });
2057
- };
2058
- const committedRun = async (transport, runId) => {
2059
- let status = await transport.request("captureRun.publish", { runId }, getCaptureRunOutputSchema);
2060
- const deadline = Date.now() + transport.publicationTimeoutMs;
2061
- while (status.receipt === null && status.failure === null && !["cancelled", "failed"].includes(status.state)) {
2062
- if (Date.now() >= deadline) throw captureError("transport", `Capture run ${runId} is still processing. Resume the same manifest.`, runId);
2063
- await new Promise((resolve) => {
2064
- setTimeout(resolve, POLL_INTERVAL_MS);
2065
- });
2066
- status = await transport.request("captureRun.publish", { runId }, getCaptureRunOutputSchema);
2067
- }
2068
- if (status.receipt === null) throw captureError(status.failure?.code === "conflict" ? "conflict" : "conversion", status.failure?.message ?? "The capture run was cancelled.", runId);
2069
- return status.receipt;
2070
- };
2071
- const checkedReceipt = (receipt, manifest) => {
2072
- if (receipt.runId !== manifest.run.id || receipt.canvasId !== manifest.run.canvasId || receipt.manifestDigest !== captureManifestDigest(manifest)) throw captureError("conflict", "This run committed a different manifest.", manifest.run.id);
2073
- return receipt;
2074
- };
2075
- const publishManifest = async (transport, manifest, directory) => {
2076
- const artifacts = selectedCaptures(manifest);
2077
- if (typeof artifacts === "string") throw captureError("artifact", artifacts);
2078
- const blobs = captureBlobs(artifacts);
2079
- if (typeof blobs === "string") throw captureError("artifact", blobs);
2080
- const current = await transport.request("captureRun.get", { runId: manifest.run.id }, getCaptureRunOutputSchema, true);
2081
- if (current.receipt !== null) {
2082
- const receipt = checkedReceipt(current.receipt, manifest);
2083
- await writeCaptureJson(path.join(directory, "receipt.json"), receipt);
2084
- return receipt;
2085
- }
2086
- if (current.state === "collecting") await uploadBlobs(transport, manifest, directory, blobs);
2087
- await transport.request("captureRun.seal", { manifest }, getCaptureRunOutputSchema);
2088
- const receipt = checkedReceipt(await committedRun(transport, manifest.run.id), manifest);
2089
- await writeCaptureJson(path.join(directory, "receipt.json"), receipt);
2090
- return receipt;
2091
- };
2092
- const publishCaptureManifest = async (transport, manifest, directory) => {
2093
- try {
2094
- return await publishManifest(transport, manifest, directory);
2095
- } catch (error) {
2096
- if (error instanceof Error) throw Object.assign(error, { runId: manifest.run.id });
2097
- throw captureError("transport", "Capture publication was not confirmed. Resume the same manifest.", manifest.run.id);
2098
- }
2099
- };
2222
+ //#region ../../packages/sdk/dist/capture-client.client-C38aUbFr.mjs
2100
2223
  const RATE_LIMIT_STATUS = 429;
2101
- const MILLISECONDS_PER_SECOND = 1e3;
2224
+ const MILLISECONDS_PER_SECOND$1 = 1e3;
2102
2225
  const MAX_ERROR_LENGTH = 1e3;
2103
2226
  const DEFAULT_TIMEOUT_MS = 3e4;
2104
2227
  const DEFAULT_PUBLICATION_TIMEOUT_MS = 6e5;
@@ -2109,22 +2232,50 @@ const HTTP_ERRORS = /* @__PURE__ */ new Map([
2109
2232
  [409, "conflict"],
2110
2233
  [400, "artifact"]
2111
2234
  ]);
2235
+ const SERVER_ERROR_STATUS = 500;
2236
+ const MOST_ATTEMPTS = 3;
2237
+ const BACKOFF_MS = [1e3, 2e3];
2238
+ const JITTER_SPREAD = .5;
2239
+ const isRetryable = (response) => response.status === RATE_LIMIT_STATUS || response.status >= SERVER_ERROR_STATUS;
2240
+ /** The server's own wait when it names one, otherwise a growing wait with random jitter. */
2241
+ const waitBefore = (response, attempt) => {
2242
+ const header = response?.headers.get("retry-after") ?? null;
2243
+ if (header !== null) {
2244
+ const seconds = Number(header);
2245
+ const named = Number.isFinite(seconds) ? seconds * MILLISECONDS_PER_SECOND$1 : Date.parse(header) - Date.now();
2246
+ if (Number.isFinite(named) && named >= 0) return named;
2247
+ }
2248
+ return (BACKOFF_MS[Math.min(attempt, BACKOFF_MS.length - 1)] ?? 0) * (1 - JITTER_SPREAD / 2 + Math.random() * JITTER_SPREAD);
2249
+ };
2250
+ /**
2251
+ * One retry rule for every request the SDK makes: a dropped connection, a timeout, a server error
2252
+ * or "too many requests" is tried again, up to three attempts in all, while the wait fits the
2253
+ * deadline. Any other answer is returned at once.
2254
+ */
2255
+ const sendWithRetry = async (send, timing) => {
2256
+ for (let attempt = 0;; attempt++) {
2257
+ let response = null;
2258
+ try {
2259
+ response = await send(AbortSignal.timeout(timing.timeoutMs));
2260
+ if (!isRetryable(response)) return response;
2261
+ } catch (error) {
2262
+ if (attempt + 1 >= MOST_ATTEMPTS) throw error;
2263
+ }
2264
+ const wait = waitBefore(response, attempt);
2265
+ if ((attempt + 1 >= MOST_ATTEMPTS || Date.now() + wait >= timing.retryDeadline) && response !== null) return response;
2266
+ await response?.body?.cancel();
2267
+ await setTimeout$1(wait);
2268
+ }
2269
+ };
2112
2270
  const requestResponse = async (url, options, timeoutMs, retryDeadline) => {
2113
2271
  try {
2114
- for (;;) {
2115
- const response = await fetch(url, {
2116
- ...options,
2117
- signal: AbortSignal.timeout(timeoutMs)
2118
- });
2119
- if (response.status !== RATE_LIMIT_STATUS) return response;
2120
- const header = response.headers.get("retry-after");
2121
- if (header === null) return response;
2122
- const seconds = Number(header);
2123
- const wait = Number.isFinite(seconds) ? seconds * MILLISECONDS_PER_SECOND : Date.parse(header) - Date.now();
2124
- if (!Number.isFinite(wait) || wait < 0 || Date.now() + wait >= retryDeadline) return response;
2125
- await response.body?.cancel();
2126
- await setTimeout$1(wait);
2127
- }
2272
+ return await sendWithRetry(async (signal) => fetch(url, {
2273
+ ...options,
2274
+ signal
2275
+ }), {
2276
+ timeoutMs,
2277
+ retryDeadline
2278
+ });
2128
2279
  } catch {
2129
2280
  throw captureError("transport", "Enhance did not confirm the request. Resume the same run to recover its result.");
2130
2281
  }
@@ -2180,6 +2331,119 @@ const captureTransport = (options) => {
2180
2331
  }
2181
2332
  };
2182
2333
  };
2334
+ const UPLOAD_BATCH_SIZE = 400;
2335
+ const POLL_INTERVAL_MS = 250;
2336
+ const HTTP_FORBIDDEN = 403;
2337
+ const BYTES_PER_EXTRA_SECOND = 102400;
2338
+ const MILLISECONDS_PER_SECOND = 1e3;
2339
+ /** S3 answers an upload to an expired signed address with this message. */
2340
+ const EXPIRED_ADDRESS = "Request has expired";
2341
+ const readFromDirectories = async (directories, blob) => {
2342
+ for (const directory of directories) try {
2343
+ return await readCaptureBlob(directory, blob);
2344
+ } catch {}
2345
+ throw captureError("artifact", `Capture blob is unavailable: ${blob.sha256}.`);
2346
+ };
2347
+ /** Each upload may take its base time plus a second for every 100 KB, so a large file is not cut off on every try. */
2348
+ const uploadTimeLimit = (transport, blob) => transport.timeoutMs + Math.ceil(blob.bytes / BYTES_PER_EXTRA_SECOND) * MILLISECONDS_PER_SECOND;
2349
+ const uploadBlob = async (input) => {
2350
+ const upload = input.held?.upload;
2351
+ if (upload === null) return "stored";
2352
+ if (upload === void 0) return "failed";
2353
+ try {
2354
+ const bytes = await readFromDirectories(input.directories, input.blob);
2355
+ const response = await sendWithRetry(async (signal) => fetch(upload.url, {
2356
+ method: "PUT",
2357
+ headers: upload.headers,
2358
+ body: new Blob([Uint8Array.from(bytes)]),
2359
+ signal,
2360
+ redirect: "error"
2361
+ }), {
2362
+ timeoutMs: uploadTimeLimit(input.transport, input.blob),
2363
+ retryDeadline: Date.now() + input.transport.publicationTimeoutMs
2364
+ });
2365
+ if (response.ok) return "stored";
2366
+ const answer = await response.text();
2367
+ return response.status === HTTP_FORBIDDEN && answer.includes(EXPIRED_ADDRESS) ? "expired" : "failed";
2368
+ } catch {
2369
+ return "failed";
2370
+ }
2371
+ };
2372
+ const reserve = async (transport, runId, blobs) => {
2373
+ const reserved = await transport.request("captureRun.reserveAssets", {
2374
+ runId,
2375
+ blobs
2376
+ }, reserveCaptureBlobsOutputSchema);
2377
+ return new Map(reserved.uploads.map((item) => [item.sha256, item]));
2378
+ };
2379
+ /** A file that will not upload is left out; the API publishes its screen without it. */
2380
+ const uploadBlobs = async (transport, manifest, directories, blobs) => {
2381
+ const runId = manifest.run.id;
2382
+ const available = [];
2383
+ for (const blob of blobs) try {
2384
+ await readFromDirectories(directories, blob);
2385
+ available.push(blob);
2386
+ } catch {}
2387
+ for (let start = 0; start < available.length; start += UPLOAD_BATCH_SIZE) {
2388
+ const batch = available.slice(start, start + UPLOAD_BATCH_SIZE);
2389
+ const uploads = await reserve(transport, runId, batch);
2390
+ for (const blob of batch) if (await uploadBlob({
2391
+ transport,
2392
+ directories,
2393
+ blob,
2394
+ held: uploads.get(blob.sha256)
2395
+ }) === "expired") {
2396
+ const renewed = await reserve(transport, runId, [blob]);
2397
+ await uploadBlob({
2398
+ transport,
2399
+ directories,
2400
+ blob,
2401
+ held: renewed.get(blob.sha256)
2402
+ });
2403
+ }
2404
+ }
2405
+ };
2406
+ const committedRun = async (transport, runId) => {
2407
+ let status = await transport.request("captureRun.publish", { runId }, getCaptureRunOutputSchema);
2408
+ const deadline = Date.now() + transport.publicationTimeoutMs;
2409
+ while (status.receipt === null && status.failure === null && !["cancelled", "failed"].includes(status.state)) {
2410
+ if (Date.now() >= deadline) throw captureError("pending", `Capture run ${runId} is still publishing to canvas ${status.run.canvasId}. It appears there when done.`, runId);
2411
+ await new Promise((resolve) => {
2412
+ setTimeout(resolve, POLL_INTERVAL_MS);
2413
+ });
2414
+ status = await transport.request("captureRun.publish", { runId }, getCaptureRunOutputSchema);
2415
+ }
2416
+ if (status.receipt === null) throw captureError(status.failure?.code === "conflict" ? "conflict" : "conversion", status.failure?.message ?? "The capture run was cancelled.", runId);
2417
+ return status.receipt;
2418
+ };
2419
+ const checkedReceipt = (receipt, manifest) => {
2420
+ if (receipt.runId !== manifest.run.id || receipt.canvasId !== manifest.run.canvasId || receipt.manifestDigest !== captureManifestDigest(manifest)) throw captureError("conflict", "This run committed a different manifest.", manifest.run.id);
2421
+ return receipt;
2422
+ };
2423
+ const publishManifest = async (transport, manifest, directory, blobDirectories = [directory]) => {
2424
+ const artifacts = selectedCaptures(manifest);
2425
+ if (typeof artifacts === "string") throw captureError("artifact", artifacts);
2426
+ const blobs = captureBlobs(artifacts);
2427
+ const current = await transport.request("captureRun.get", { runId: manifest.run.id }, getCaptureRunOutputSchema, true);
2428
+ if (current.receipt !== null) {
2429
+ const receipt = checkedReceipt(current.receipt, manifest);
2430
+ await writeCaptureJson(path.join(directory, "receipt.json"), receipt);
2431
+ return receipt;
2432
+ }
2433
+ if (current.state === "collecting") await uploadBlobs(transport, manifest, blobDirectories, blobs);
2434
+ await transport.request("captureRun.seal", { manifest }, getCaptureRunOutputSchema);
2435
+ const receipt = checkedReceipt(await committedRun(transport, manifest.run.id), manifest);
2436
+ await writeCaptureJson(path.join(directory, "receipt.json"), receipt);
2437
+ return receipt;
2438
+ };
2439
+ const publishCaptureManifest = async (transport, manifest, directory, blobDirectories = [directory]) => {
2440
+ try {
2441
+ return await publishManifest(transport, manifest, directory, blobDirectories);
2442
+ } catch (error) {
2443
+ if (error instanceof Error) throw Object.assign(error, { runId: manifest.run.id });
2444
+ throw captureError("transport", "Capture publication was not confirmed. Resume the same manifest.", manifest.run.id);
2445
+ }
2446
+ };
2183
2447
  const nodeManifest = (descriptor, captured) => {
2184
2448
  const participant = descriptor.participants[0];
2185
2449
  if (participant === void 0) throw captureError("configuration", "No capture participant was reserved.");
@@ -2232,24 +2496,49 @@ const createRun = (transport, input, directory) => {
2232
2496
  }
2233
2497
  };
2234
2498
  };
2499
+ const beginCaptureRun = async (transport, input) => {
2500
+ const request = beginCaptureRunInputSchema.parse({
2501
+ canvasId: input.canvas,
2502
+ destination: input.destination,
2503
+ title: input.title,
2504
+ context: input.context,
2505
+ revision: input.revision,
2506
+ compareTo: input.compareTo,
2507
+ source: input.source,
2508
+ runKey: input.runKey,
2509
+ participants: input.participants
2510
+ });
2511
+ const { run } = await transport.request("captureRun.begin", request, beginCaptureRunOutputSchema);
2512
+ const directory = input.directory ?? path.join(".enhance", "captures", run.id);
2513
+ await mkdir(directory, { recursive: true });
2514
+ await writeCaptureJson(path.join(directory, "run.json"), run);
2515
+ return createRun(transport, run, directory);
2516
+ };
2235
2517
  const createEnhance = (options) => {
2236
2518
  const transport = captureTransport(options);
2237
2519
  const get = async (runId) => transport.request("captureRun.get", { runId }, getCaptureRunOutputSchema, true);
2238
2520
  return { captures: {
2239
- begin: async (input) => {
2240
- const request = beginCaptureRunInputSchema.parse({
2241
- canvasId: input.canvas,
2242
- source: input.source,
2243
- runKey: input.runKey,
2244
- participants: input.participants
2245
- });
2246
- const { run } = await transport.request("captureRun.begin", request, beginCaptureRunOutputSchema);
2247
- const directory = input.directory ?? path.join(".enhance", "captures", run.id);
2248
- await mkdir(directory, { recursive: true });
2249
- await writeCaptureJson(path.join(directory, "run.json"), run);
2250
- return createRun(transport, run, directory);
2521
+ review: async (canvasId) => transport.request("captureRun.review", { canvasId }, captureReviewSchema.nullable(), true),
2522
+ decide: async (canvasId, verdict) => {
2523
+ await transport.request("captureRun.decide", {
2524
+ canvasId,
2525
+ verdict
2526
+ }, z.object({ accepted: z.literal(true) }));
2527
+ },
2528
+ reference: async (canvasId, name) => transport.request("captureRun.reference", {
2529
+ canvasId,
2530
+ name
2531
+ }, captureReferenceSchema.nullable(), true),
2532
+ promote: async (input) => transport.request("captureRun.promote", updateCaptureReferenceInputSchema.parse(input), captureReferenceSchema),
2533
+ publishManifests: async (paths) => {
2534
+ const manifest = mergeCaptureManifests(await Promise.all(paths.map(async (path) => readCaptureManifest(path))));
2535
+ if (typeof manifest === "string") throw captureError("artifact", manifest);
2536
+ const directory = path.dirname(paths[0] ?? ".");
2537
+ await writeCaptureJson(path.join(directory, "merged-manifest.json"), manifest);
2538
+ return publishCaptureManifest(transport, manifest, directory, paths.map((path$1) => path.dirname(path$1)));
2251
2539
  },
2252
- publishManifest: async (path$1) => publishCaptureManifest(transport, await readCaptureManifest(path$1), path.dirname(path$1)),
2540
+ begin: async (input) => beginCaptureRun(transport, input),
2541
+ publishManifest: async (path$2) => publishCaptureManifest(transport, await readCaptureManifest(path$2), path.dirname(path$2)),
2253
2542
  get
2254
2543
  } };
2255
2544
  };
@@ -2279,12 +2568,12 @@ const registerCapturesProgram = (program, dependencies) => {
2279
2568
  //#endregion
2280
2569
  //#region src/infrastructure/command-summaries.consts.ts
2281
2570
  const COMMAND_SUMMARIES = {
2571
+ "captureRun.review": "Read product review for a run canvas.",
2282
2572
  "canvas chats": "Chat history.",
2283
2573
  "canvas.createEditableFrame": "Make a screen editable.",
2284
2574
  "canvas.create": "Create a canvas.",
2285
2575
  "canvas.get": "Read a canvas and access.",
2286
2576
  "canvas.setAccess": "Change canvas link access.",
2287
- "canvas.markViewed": "Mark a canvas as viewed.",
2288
2577
  "canvas.list": "List canvases.",
2289
2578
  "canvas.rename": "Rename a canvas.",
2290
2579
  "canvas.setReviewState": "Set review state.",
@@ -3135,7 +3424,7 @@ const main = async () => {
3135
3424
  const remote = createHttpRemoteAdapter(config.apiUrl, credentials, mutationKey);
3136
3425
  const cli = createCliProgram({
3137
3426
  apiUrl: config.apiUrl,
3138
- version: "0.1.33",
3427
+ version: "0.1.38",
3139
3428
  credentials,
3140
3429
  remote,
3141
3430
  mutationKey,