@enhance-eng/enhance 0.1.25 → 0.1.37

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 { At as fromCanvasReference, Bt as completeRecordingOutputSchema, Dn as canvasTextRunsOf, Dt as assertCanvasReferenceNodes, Et as canvasEditsSchema, Fn as beginCanvasActivityOutputSchema, Gn as getCanvasDocumentOutputSchema, Ht as startRecordingOutputSchema, In as canvasAgentActivityPhaseSchema, It as appErrorSchema, Jn as canvasOperationSchema, Kn as saveCanvasDocumentOutputSchema, Lt as completeScreenOutputSchema, Mt as parseCanvasReference, Nt as PartialBatchError, Pt as CliError, Rt as createScreenOutputSchema, _ as PROCEDURE_DESCRIPTIONS, a as toFailurePayload, an as withFixtureScreen, d as ProcessExitError, dr as canvasAuthoredLayoutValueOf, et as canvasRenderScopedInputSchema, f as createCapabilityCatalogAdapter, fr as canvasAuthoredStyleDeclarations, g as OPTION_DESCRIPTIONS, gt as canvasFindInputSchema, hr as canvasLayoutPriorityDeclarations, i as toExitCode, in as emptyFixtureDocument, it as canvasRemoveCapabilityInputSchema, jt as hasCanvasReferenceScope, k as operationStatusInputSchema, kt as canvasReferenceRenderTarget, l as toSharedCapabilities, lr as canvasReadableSceneDocumentSchema, lt as canvasUpdateHtmlCapabilityInputSchema, m as createCapabilityPolicyAdapter, mr as canvasLayoutMainAxisOf, n as withCommandName, nn as createOrganisationOutputSchema, p as createRouterShapeAdapter, pr as canvasAxisStyleProperties, qn as MAX_CANVAS_OPERATIONS, r as toCanvasAuthoringResult, sr as RENDER_MIN_SCALE, st as canvasReadInputSchema, t as withCommandInFailure, tr as canvasWorldBoundsSchema, u as createMcpCapabilityDiscoveryAdapter, wr as canvasSchema, zt as appendRecordingChunkOutputSchema } from "./cli-output-identity.lib-DpON8As5.mjs";
3
- import { _ as sceneAtVersion, b as createRenderCanvasComposite, d as createRenderFileAdapter, f as readCanvasReferenceScene, g as assertCanvasReferenceOperations, h as createEditCanvasComposite, m as fromCapabilityReference, n as createHttpRemoteAdapter, o as createOauthLoopbackAdapter, p as createWriteHtmlCanvasComposite, r as readCliEnvironment, s as createCapabilityInvocationAdapter, t as createMutationKeyAdapter, v as createApplyCanvasComposite, x as createAuthUseCase, y as createCanvasActivityComposite } from "./mutation-key.adapter-CXQ08HQY.mjs";
2
+ import { $t as createOrganisationOutputSchema, An as canvasAgentActivityPhaseSchema, 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, 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, kn as beginCanvasActivityOutputSchema, 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-i4KnVAYs.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-Ck8nOqke.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";
@@ -12,7 +12,9 @@ import { createInterface } from "node:readline";
12
12
  import { chmodSync, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, statSync, unlinkSync, writeFileSync } from "node:fs";
13
13
  import path from "node:path";
14
14
  import { createHash, randomUUID } from "node:crypto";
15
- import { readFile } from "node:fs/promises";
15
+ import { setTimeout as setTimeout$1 } from "node:timers/promises";
16
+ import { mkdir, readFile, rename, stat, writeFile } from "node:fs/promises";
17
+ import { channel } from "node:diagnostics_channel";
16
18
  import { proxify } from "trpc-cli/dist/proxify.js";
17
19
 
18
20
  //#region ../../packages/contract/src/canvas/canvas-color-css.lib.ts
@@ -33,6 +35,173 @@ const canvasColorCss = (color, opacity = 1) => {
33
35
  return `color(${color.space} ${channels} / ${String(alpha)})`;
34
36
  };
35
37
 
38
+ //#endregion
39
+ //#region ../../packages/contract/src/canvas/canvas-gradient-field.lib.ts
40
+ const UNIT_BOUNDS = {
41
+ x: 0,
42
+ y: 0,
43
+ width: 1,
44
+ height: 1
45
+ };
46
+ const fieldPoint = (paint, point) => {
47
+ const [a, b, c, d, e, f] = paint.transform;
48
+ const determinant = a * d - b * c;
49
+ const x = point.x - e, y = point.y - f;
50
+ return {
51
+ x: (d * x - c * y) / determinant,
52
+ y: (a * y - b * x) / determinant
53
+ };
54
+ };
55
+ const canvasGradientFieldCoordinates = (paint, bounds = UNIT_BOUNDS) => [
56
+ {
57
+ x: bounds.x,
58
+ y: bounds.y
59
+ },
60
+ {
61
+ x: bounds.x + bounds.width,
62
+ y: bounds.y
63
+ },
64
+ {
65
+ x: bounds.x,
66
+ y: bounds.y + bounds.height
67
+ },
68
+ {
69
+ x: bounds.x + bounds.width,
70
+ y: bounds.y + bounds.height
71
+ }
72
+ ].flatMap((point) => {
73
+ const local = fieldPoint(paint, point);
74
+ return [local.x, local.y];
75
+ });
76
+
77
+ //#endregion
78
+ //#region ../../packages/contract/src/canvas/canvas-angular-gradient.lib.ts
79
+ const HALF$1 = .5;
80
+ const FULL_TURN = 360;
81
+ const PERCENT$4 = 100;
82
+ const FIELD_UNIT = 1024;
83
+ const LINEAR_COEFFICIENTS = 4;
84
+ const gradient = (paint, center, isAlpha) => {
85
+ const stops = paint.stops.map((stop) => {
86
+ return `${isAlpha ? `rgb(255 255 255 / ${String(stop.color.alpha * paint.opacity)})` : canvasColorCss({
87
+ ...stop.color,
88
+ alpha: 1
89
+ })} ${String(stop.position * FULL_TURN)}deg`;
90
+ });
91
+ return `conic-gradient(from 90deg at ${String(center)}% ${String(center)}% in srgb, ${stops.join(", ")})`;
92
+ };
93
+ /** Separate alpha from color so translucent stops interpolate straight sRGB, as copied by Figma. */
94
+ const canvasAngularGradientField = (paint, bounds) => {
95
+ const coordinates = canvasGradientFieldCoordinates(paint, bounds);
96
+ const low = Math.min(0, ...coordinates);
97
+ const span = Math.max(1, ...coordinates) - low;
98
+ const center = (HALF$1 - low) / span * PERCENT$4;
99
+ const matrix = paint.transform.map((value, index) => index < LINEAR_COEFFICIENTS ? value / FIELD_UNIT : value);
100
+ const style = `width:100%;height:100%;background-image:${gradient(paint, center, false)};mask-image:${gradient(paint, center, true)};`;
101
+ return `<g transform="matrix(${matrix.map(String).join(" ")})"><foreignObject x="${String(low * FIELD_UNIT)}" y="${String(low * FIELD_UNIT)}" width="${String(span * FIELD_UNIT)}" height="${String(span * FIELD_UNIT)}" overflow="visible"><div xmlns="http://www.w3.org/1999/xhtml" style="${style}"></div></foreignObject></g>`;
102
+ };
103
+ const canvasAngularGradientSvg = (paint) => `<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewBox="0 0 1 1" preserveAspectRatio="none">${canvasAngularGradientField(paint)}</svg>`;
104
+
105
+ //#endregion
106
+ //#region ../../packages/contract/src/canvas/canvas-diamond-gradient.lib.ts
107
+ const HALF = .5;
108
+ const QUARTER = .25;
109
+ /** Each quadrant is a linear field with slope 2*(abs(x-.5)+abs(y-.5)). */
110
+ const canvasDiamondGradientField = (paint, id = "field", bounds) => {
111
+ const coordinates = canvasGradientFieldCoordinates(paint, bounds);
112
+ const extent = Math.max(HALF, ...coordinates.map((value) => Math.abs(value - HALF))) + 1;
113
+ const low = HALF - extent, high = HALF + extent;
114
+ const quadrants = [
115
+ {
116
+ x: .75,
117
+ y: .75,
118
+ points: `.5,.5 ${String(high)},.5 ${String(high)},${String(high)} .5,${String(high)}`
119
+ },
120
+ {
121
+ x: QUARTER,
122
+ y: .75,
123
+ points: `.5,.5 .5,${String(high)} ${String(low)},${String(high)} ${String(low)},.5`
124
+ },
125
+ {
126
+ x: QUARTER,
127
+ y: QUARTER,
128
+ points: `.5,.5 ${String(low)},.5 ${String(low)},${String(low)} .5,${String(low)}`
129
+ },
130
+ {
131
+ x: .75,
132
+ y: QUARTER,
133
+ points: `.5,.5 .5,${String(low)} ${String(high)},${String(low)} ${String(high)},.5`
134
+ }
135
+ ];
136
+ const stops = paint.stops.map((stop) => `<stop offset="${String(stop.position)}" stop-color="${canvasColorCss({
137
+ ...stop.color,
138
+ alpha: 1
139
+ })}" stop-opacity="${String(stop.color.alpha * paint.opacity)}" />`).join("");
140
+ const definitions = quadrants.map((quadrant, index) => `<linearGradient id="${id}-${String(index)}" gradientUnits="userSpaceOnUse" x1=".5" y1=".5" x2="${String(quadrant.x)}" y2="${String(quadrant.y)}" color-interpolation="sRGB">${stops}</linearGradient>`).join("");
141
+ const fields = quadrants.map((quadrant, index) => `<polygon points="${quadrant.points}" fill="url(#${id}-${String(index)})" shape-rendering="crispEdges" />`).join("");
142
+ return `<defs>${definitions}</defs><g transform="matrix(${paint.transform.map(String).join(" ")})">${fields}</g>`;
143
+ };
144
+ const canvasDiamondGradientSvg = (paint) => `<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewBox="0 0 1 1" preserveAspectRatio="none">${canvasDiamondGradientField(paint)}</svg>`;
145
+
146
+ //#endregion
147
+ //#region ../../packages/contract/src/canvas/canvas-filter.lib.ts
148
+ const PERCENT$3 = 100;
149
+ /** Radius/2 preserves the existing Gaussian approximation, not native sampling parity. */
150
+ const canvasBlurStandardDeviation = (filter) => filter.parameter === "radius" ? filter.value / 2 : filter.value;
151
+ const filterCss = (filter) => {
152
+ switch (filter.kind) {
153
+ case "blur": return `blur(${String(canvasBlurStandardDeviation(filter))}px)`;
154
+ case "brightness":
155
+ case "contrast":
156
+ case "saturate": return `${filter.kind}(${String(filter.value)})`;
157
+ case "grayscale":
158
+ case "invert":
159
+ case "sepia": return `${filter.kind}(${String(filter.value * PERCENT$3)}%)`;
160
+ case "hue-rotate": return `hue-rotate(${String(filter.value)}deg)`;
161
+ }
162
+ };
163
+ const canvasFilterListCss = (filters) => filters.filter((filter) => filter.visible).map((filter) => filterCss(filter)).join(" ");
164
+
165
+ //#endregion
166
+ //#region ../../packages/contract/src/canvas/canvas-font-family.lib.ts
167
+ const GENERIC_FAMILIES = /* @__PURE__ */ new Set([
168
+ "cursive",
169
+ "emoji",
170
+ "fantasy",
171
+ "fangsong",
172
+ "math",
173
+ "monospace",
174
+ "sans-serif",
175
+ "serif",
176
+ "system-ui",
177
+ "ui-monospace",
178
+ "ui-rounded",
179
+ "ui-sans-serif",
180
+ "ui-serif"
181
+ ]);
182
+ const CSS_IDENTIFIER = /^-?[_a-z][-\w]*$/iu;
183
+ const CSS_VARIABLE = /^var\(--[-\w]+\)$/iu;
184
+ const MAX_UNICODE = 1114111;
185
+ const SURROGATE_START = 55296;
186
+ const SURROGATE_END = 57343;
187
+ const REPLACEMENT_CHARACTER = 65533;
188
+ const isCanvasGenericFontFamily = (family) => GENERIC_FAMILIES.has(family.toLowerCase());
189
+ 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) => {
190
+ if (newline !== void 0) return "";
191
+ if (hex === void 0) return literal ?? "";
192
+ const point = Number.parseInt(hex, 16);
193
+ return String.fromCodePoint(point === 0 || point > MAX_UNICODE || point >= SURROGATE_START && point <= SURROGATE_END ? REPLACEMENT_CHARACTER : point);
194
+ });
195
+ const canvasFontFamilyName = (token) => {
196
+ const value = token.trim();
197
+ const isQuoted = value.startsWith("\"") && value.endsWith("\"") || value.startsWith("'") && value.endsWith("'");
198
+ return decodedCss(isQuoted ? value.slice(1, -1) : value);
199
+ };
200
+ const canvasFontFamilyCss = (family) => {
201
+ if (family.startsWith("\"") && isCanvasGenericFontFamily(canvasFontFamilyName(family))) return JSON.stringify(canvasFontFamilyName(family));
202
+ return CSS_IDENTIFIER.test(family) || CSS_VARIABLE.test(family) ? family : JSON.stringify(family);
203
+ };
204
+
36
205
  //#endregion
37
206
  //#region ../../packages/contract/src/canvas/canvas-typography-css.lib.ts
38
207
  const PERCENT$2 = 100;
@@ -41,15 +210,12 @@ const canvasTextDirectionDeclarations = (direction) => direction === void 0 ? {}
41
210
  ...direction !== "auto" && { direction },
42
211
  "unicode-bidi": direction === "auto" ? "plaintext" : "isolate"
43
212
  };
44
- const CSS_IDENTIFIER = /^-?[_a-z][-\w]*$/iu;
45
- const CSS_VARIABLE = /^var\(--[-\w]+\)$/iu;
46
- const fontFamilyName = (family) => CSS_IDENTIFIER.test(family) || CSS_VARIABLE.test(family) ? family : JSON.stringify(family);
47
213
  const canvasTypographyFontFamily = (typography) => [.../* @__PURE__ */ new Set([
48
214
  typography.family,
49
215
  ...typography.family === "Inter" ? ["Inter Variable"] : [],
50
216
  ...typography.family === "JetBrains Mono" ? ["JetBrains Mono Variable"] : [],
51
217
  ...typography.fallbackFamilies
52
- ])].map((family) => fontFamilyName(family)).join(", ");
218
+ ])].map((family) => canvasFontFamilyCss(family)).join(", ");
53
219
  /** Weight is the sole wght owner; the remaining axes never shadow the visible weight field. */
54
220
  const canvasFontVariationSettings = (typography) => Object.entries({
55
221
  ...typography.variations,
@@ -84,10 +250,45 @@ const canvasTextDecorationDeclarations = (decoration) => ({
84
250
  "text-decoration-skip-ink": decoration.skipInk ?? "auto"
85
251
  });
86
252
 
253
+ //#endregion
254
+ //#region ../../packages/contract/src/canvas/canvas-linear-gradient.lib.ts
255
+ const canvasLinearGradientDefinition = (paint, id, units = "userSpaceOnUse") => {
256
+ const stops = paint.stops.map((stop) => `<stop offset="${String(stop.position)}" stop-color="${canvasColorCss({
257
+ ...stop.color,
258
+ alpha: 1
259
+ })}" stop-opacity="${String(stop.color.alpha * paint.opacity)}" />`).join("");
260
+ return `<linearGradient id="${id}" gradientUnits="${units}" x1="0" y1=".5" x2="1" y2=".5" gradientTransform="matrix(${paint.transform.map(String).join(" ")})" color-interpolation="sRGB">${stops}</linearGradient>`;
261
+ };
262
+ const canvasLinearGradientSvg = (paint) => {
263
+ return `<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewBox="0 0 1 1" preserveAspectRatio="none"><defs>${canvasLinearGradientDefinition(paint, "field")}</defs><path d="M0 0H1V1H0Z" fill="url(#field)" /></svg>`;
264
+ };
265
+
266
+ //#endregion
267
+ //#region ../../packages/contract/src/canvas/canvas-radial-gradient.lib.ts
268
+ const DIAMETER = 2;
269
+ const transformFor = (paint) => paint.transform ?? [
270
+ paint.radius.x * DIAMETER,
271
+ 0,
272
+ 0,
273
+ paint.radius.y * DIAMETER,
274
+ paint.center.x - paint.radius.x,
275
+ paint.center.y - paint.radius.y
276
+ ];
277
+ const canvasRadialGradientDefinition = (paint, id, units = "userSpaceOnUse") => {
278
+ const stops = paint.stops.map((stop) => `<stop offset="${String(stop.position)}" stop-color="${canvasColorCss({
279
+ ...stop.color,
280
+ alpha: 1
281
+ })}" stop-opacity="${String(stop.color.alpha * paint.opacity)}" />`).join("");
282
+ return `<radialGradient id="${id}" gradientUnits="${units}" cx=".5" cy=".5" r=".5" gradientTransform="matrix(${transformFor(paint).map(String).join(" ")})" color-interpolation="sRGB">${stops}</radialGradient>`;
283
+ };
284
+ const canvasRadialGradientSvg = (paint) => {
285
+ return `<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewBox="0 0 1 1" preserveAspectRatio="none"><defs>${canvasRadialGradientDefinition(paint, "field")}</defs><path d="M0 0H1V1H0Z" fill="url(#field)" /></svg>`;
286
+ };
287
+
87
288
  //#endregion
88
289
  //#region ../../packages/contract/src/recording/event-stream.lib.ts
89
290
  /**
90
- * @justified docs/comments.md#intent
291
+ * @justified intent
91
292
  * The recording wire format, in one place, because the recorder, the seed and the player all
92
293
  * speak it.
93
294
  *
@@ -96,7 +297,7 @@ const canvasTextDecorationDeclarations = (decoration) => ({
96
297
  *
97
298
  * It has to work that way. rrweb emits the full snapshot as a *single event*, and with fonts and
98
299
  * images inlined that runs to megabytes; whole-event chunks would put that event's size under
99
- * the request ceiling, making the ceiling one on fidelity. docs/features/recorder.md#dom.
300
+ * the request ceiling, making the ceiling one on fidelity.
100
301
  *
101
302
  * A raw newline only ever separates records: `JSON.stringify` writes one inside a string as the
102
303
  * two characters `\` and `n`.
@@ -104,7 +305,7 @@ const canvasTextDecorationDeclarations = (decoration) => ({
104
305
  /** One event's line, terminator included. Every line ends in one, including the last. */
105
306
  const lineFor = (event) => `${JSON.stringify(event)}\n`;
106
307
  /**
107
- * @justified docs/comments.md#clarification
308
+ * @justified clarification
108
309
  * A recording being written, cut into ranges of at most `limit` units as it goes.
109
310
  *
110
311
  * A range comes out the moment it is full, because the point of streaming is that stopping is a
@@ -365,15 +566,8 @@ const registerAuthProgram = (program, auth, output) => {
365
566
  //#endregion
366
567
  //#region src/infrastructure/canvas-authoring-input.schema.ts
367
568
  const NODE_ID_LENGTH = 200;
368
- const NODE_NAME_LENGTH = 500;
369
- const TEXT_LENGTH = 1e5;
370
- const MAX_NODE_IDS = 1e3;
371
- const MAX_BATCHES = 100;
372
- const MAX_DEPTH = 20;
373
- const MIN_RENDER_SCALE = .1;
374
- const MAX_RENDER_SCALE = 4;
375
569
  const positiveIntegerSchema = z.coerce.number().int().positive();
376
- const renderScaleSchema = z.coerce.number().min(MIN_RENDER_SCALE).max(MAX_RENDER_SCALE);
570
+ const renderScaleSchema = z.coerce.number().positive();
377
571
  const authoringUuidSchema = z.uuid();
378
572
  const styleValueSchema = z.union([
379
573
  z.string(),
@@ -383,20 +577,20 @@ const styleValueSchema = z.union([
383
577
  const styleObjectSchema = z.record(z.string(), styleValueSchema);
384
578
  const textUpdatesSchema = z.array(z.object({
385
579
  nodeId: z.string().min(1).max(NODE_ID_LENGTH),
386
- textContent: z.string().max(TEXT_LENGTH)
387
- })).min(1).max(MAX_NODE_IDS);
580
+ textContent: z.string()
581
+ })).min(1);
388
582
  const renameUpdatesSchema = z.array(z.object({
389
583
  nodeId: z.string().min(1).max(NODE_ID_LENGTH),
390
- name: z.string().max(NODE_NAME_LENGTH)
391
- })).min(1).max(MAX_NODE_IDS);
584
+ name: z.string()
585
+ })).min(1);
392
586
  const styleUpdatesSchema = z.array(z.object({
393
- nodeIds: z.array(z.string().min(1).max(NODE_ID_LENGTH)).min(1).max(MAX_BATCHES),
587
+ nodeIds: z.array(z.string().min(1).max(NODE_ID_LENGTH)).min(1),
394
588
  styles: styleObjectSchema
395
- })).min(1).max(MAX_BATCHES);
589
+ })).min(1);
396
590
  const duplicateInputsSchema = z.array(z.object({
397
591
  id: z.string().min(1).max(NODE_ID_LENGTH),
398
592
  parentId: z.string().min(1).max(NODE_ID_LENGTH).optional()
399
- })).min(1).max(MAX_BATCHES);
593
+ })).min(1);
400
594
  const moveInputsSchema = z.array(z.union([
401
595
  z.object({
402
596
  nodeId: z.string().min(1).max(NODE_ID_LENGTH),
@@ -411,9 +605,9 @@ const moveInputsSchema = z.array(z.union([
411
605
  parentId: z.string().min(1).max(NODE_ID_LENGTH),
412
606
  index: z.number().int().nonnegative().optional()
413
607
  })
414
- ])).min(1).max(MAX_BATCHES);
415
- const nodeIdsSchema = z.array(z.string().min(1).max(NODE_ID_LENGTH)).min(1).max(MAX_NODE_IDS);
416
- const sourceDepthSchema = z.coerce.number().int().min(0).max(MAX_DEPTH);
608
+ ])).min(1);
609
+ const nodeIdsSchema = z.array(z.string().min(1).max(NODE_ID_LENGTH)).min(1);
610
+ const sourceDepthSchema = z.coerce.number().int().min(0);
417
611
 
418
612
  //#endregion
419
613
  //#region src/infrastructure/canvas-authoring-command.lib.ts
@@ -455,25 +649,26 @@ const applyAuthoringEdits = async (input, options, edits, idPrefix) => {
455
649
  };
456
650
 
457
651
  //#endregion
458
- //#region src/infrastructure/canvas-operation-input.adapter.ts
459
- const MAX_OPERATION_FILE_BYTES = 1048576;
460
- const operationBatchSchema = z.array(canvasOperationSchema).min(1).max(MAX_CANVAS_OPERATIONS);
461
- const textFrom = (value) => {
652
+ //#region src/infrastructure/canvas-authoring-input.lib.ts
653
+ const canvasAuthoringInput = (value, option) => {
462
654
  if (!value.startsWith("@")) return value;
463
655
  const selected = value.slice(1);
464
- if (selected === "") throw new CliError("BAD_REQUEST", "--operations @ must name a JSON file.", "Pass --operations @/absolute/path/layout.json or an inline JSON array.");
656
+ if (selected === "") throw new CliError("BAD_REQUEST", `${option} @ must name a file.`, `Pass ${option} @/absolute/path/to/file or an inline value.`);
465
657
  const filePath = path.resolve(selected);
466
658
  try {
467
- const stats = statSync(filePath);
468
- if (!stats.isFile() || stats.size > MAX_OPERATION_FILE_BYTES) throw new Error("invalid size");
659
+ if (!statSync(filePath).isFile()) throw new Error("not a regular file");
469
660
  return readFileSync(filePath, "utf8");
470
661
  } catch {
471
- throw new CliError("BAD_REQUEST", `Could not read a bounded operations file at ${filePath}.`, "Use a regular JSON file no larger than 1 MiB.");
662
+ throw new CliError("BAD_REQUEST", `Could not read the file at ${filePath}.`, "Use a readable regular UTF-8 file.");
472
663
  }
473
664
  };
665
+
666
+ //#endregion
667
+ //#region src/infrastructure/canvas-operation-input.adapter.ts
668
+ const operationBatchSchema = z.array(canvasOperationSchema).min(1);
474
669
  const decodedFrom = (value) => {
475
670
  try {
476
- return JSON.parse(textFrom(value));
671
+ return JSON.parse(canvasAuthoringInput(value, "--operations"));
477
672
  } catch (error) {
478
673
  if (error instanceof CliError) throw error;
479
674
  throw new CliError("BAD_REQUEST", "--operations must be one valid JSON array.", "Pass inline JSON or @/absolute/path/layout.json; run 'enhance canvas apply --help' for examples.");
@@ -590,29 +785,12 @@ const configureCanvasAuthoringActivity = (canvas, input) => {
590
785
  configureFinish(canvas, input);
591
786
  };
592
787
 
593
- //#endregion
594
- //#region src/infrastructure/canvas-authoring-bounded-input.lib.ts
595
- const boundedCanvasAuthoringInput = (value, bytes, option) => {
596
- if (!value.startsWith("@")) return value;
597
- const selected = value.slice(1);
598
- if (selected === "") throw new CliError("BAD_REQUEST", `${option} @ must name a file.`, `Pass ${option} @/absolute/path/to/file or an inline value.`);
599
- const filePath = path.resolve(selected);
600
- try {
601
- const stats = statSync(filePath);
602
- if (!stats.isFile() || stats.size > bytes) throw new Error("invalid size");
603
- return readFileSync(filePath, "utf8");
604
- } catch {
605
- throw new CliError("BAD_REQUEST", `Could not read a bounded file at ${filePath}.`, `Use a regular UTF-8 file no larger than ${String(bytes)} bytes.`);
606
- }
607
- };
608
-
609
788
  //#endregion
610
789
  //#region src/infrastructure/canvas-json-input.adapter.ts
611
- const MAX_JSON_BYTES = 1048576;
612
790
  const createCanvasJsonInputAdapter = (value, schema, option) => {
613
791
  const decoded = (() => {
614
792
  try {
615
- return JSON.parse(boundedCanvasAuthoringInput(value, MAX_JSON_BYTES, option));
793
+ return JSON.parse(canvasAuthoringInput(value, option));
616
794
  } catch (error) {
617
795
  if (error instanceof CliError) throw error;
618
796
  throw new CliError("BAD_REQUEST", `${option} must be valid JSON.`, `Pass inline JSON or @/absolute/path/to/input.json; run the command with --help.`);
@@ -858,20 +1036,21 @@ const cssPaint = (paint) => {
858
1036
  if (!paint.visible) return null;
859
1037
  if (paint.kind === "solid") return cssColour(paint.color);
860
1038
  if (paint.kind === "image") return `url(${JSON.stringify(paint.assetId)})`;
1039
+ if (paint.kind === "angular-gradient" || paint.kind === "diamond-gradient") {
1040
+ const svg = paint.kind === "angular-gradient" ? canvasAngularGradientSvg(paint) : canvasDiamondGradientSvg(paint);
1041
+ return `url("data:image/svg+xml,${encodeURIComponent(svg)}") 0 0 / 100% 100% no-repeat`;
1042
+ }
861
1043
  const stops = paint.stops.map((stop) => `${cssColour(stop.color)} ${String(stop.position * PERCENT)}%`).join(", ");
862
- if (paint.kind === "linear-gradient") return `linear-gradient(${String(paint.angle)}deg, ${stops})`;
1044
+ if (paint.kind === "linear-gradient") {
1045
+ if (paint.transform !== void 0) return `url("data:image/svg+xml,${encodeURIComponent(canvasLinearGradientSvg({
1046
+ ...paint,
1047
+ transform: paint.transform
1048
+ }))}") 0 0 / 100% 100% no-repeat`;
1049
+ return `linear-gradient(${String(paint.angle)}deg, ${stops})`;
1050
+ }
1051
+ if (paint.transform !== void 0) return `url("data:image/svg+xml,${encodeURIComponent(canvasRadialGradientSvg(paint))}") 0 0 / 100% 100% no-repeat`;
863
1052
  return `radial-gradient(at ${String(paint.center.x * PERCENT)}% ${String(paint.center.y * PERCENT)}%, ${stops})`;
864
1053
  };
865
- const cssFilter = (filter) => {
866
- if (filter.kind === "blur") return `blur(${String(filter.value)}px)`;
867
- if (filter.kind === "hue-rotate") return `hue-rotate(${String(filter.value)}deg)`;
868
- const value = [
869
- "grayscale",
870
- "invert",
871
- "sepia"
872
- ].includes(filter.kind) ? `${String(filter.value * PERCENT)}%` : String(filter.value);
873
- return `${filter.kind}(${value})`;
874
- };
875
1054
  const visiblePaints = (paints) => paints?.flatMap((paint) => {
876
1055
  const value = cssPaint(paint);
877
1056
  return value === null ? [] : [value];
@@ -902,12 +1081,12 @@ const outlineCss = (outline) => {
902
1081
  };
903
1082
  const effectCss = (appearance) => {
904
1083
  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)}`);
905
- const filters = appearance.filters?.filter((filter) => filter.visible).map(cssFilter);
906
- const backdrop = appearance.backdropFilters?.filter((filter) => filter.visible).map(cssFilter);
1084
+ const filters = canvasFilterListCss(appearance.filters ?? []);
1085
+ const backdrop = canvasFilterListCss(appearance.backdropFilters ?? []);
907
1086
  return {
908
1087
  ...shadows !== void 0 && shadows.length > 0 && { "box-shadow": shadows.join(", ") },
909
- ...filters !== void 0 && filters.length > 0 && { filter: filters.join(" ") },
910
- ...backdrop !== void 0 && backdrop.length > 0 && { "backdrop-filter": backdrop.join(" ") }
1088
+ ...filters !== "" && { filter: filters },
1089
+ ...backdrop !== "" && { "backdrop-filter": backdrop }
911
1090
  };
912
1091
  };
913
1092
  const appearanceCss = (appearance) => {
@@ -1241,12 +1420,7 @@ const configureCanvasAuthoringStructure = (canvas, input) => {
1241
1420
 
1242
1421
  //#endregion
1243
1422
  //#region src/infrastructure/canvas-html-input.adapter.ts
1244
- const MAX_HTML_BYTES = 262144;
1245
- const createCanvasHtmlInputAdapter = (value) => {
1246
- const html = boundedCanvasAuthoringInput(value, MAX_HTML_BYTES, "--html");
1247
- if (Buffer.byteLength(html, "utf8") > MAX_HTML_BYTES) throw new CliError("BAD_REQUEST", `--html exceeds ${String(MAX_HTML_BYTES)} bytes.`, "Write one visual group at a time, as taught by canvas guide.");
1248
- return html;
1249
- };
1423
+ const createCanvasHtmlInputAdapter = (value) => canvasAuthoringInput(value, "--html");
1250
1424
 
1251
1425
  //#endregion
1252
1426
  //#region src/infrastructure/canvas-authoring-write.program.ts
@@ -1514,7 +1688,7 @@ const createCanvasRenderInputAdapter = (options) => {
1514
1688
  //#region src/infrastructure/canvas.program.ts
1515
1689
  const positiveInteger$2 = z.coerce.number().int().positive();
1516
1690
  const nonnegativeInteger = z.coerce.number().int().nonnegative();
1517
- const renderScale = z.coerce.number().min(RENDER_MIN_SCALE).max(4);
1691
+ const renderScale = z.coerce.number().positive();
1518
1692
  const RECORDING_NODE_PREFIX = "rec_";
1519
1693
  const numberFrom = (schema, value, option, command = "canvas render") => {
1520
1694
  const parsed = schema.safeParse(value);
@@ -1619,9 +1793,834 @@ const registerCanvasProgram = (program, input) => {
1619
1793
  configureRender(render, input);
1620
1794
  };
1621
1795
 
1796
+ //#endregion
1797
+ //#region ../../packages/sdk/dist/capture-files.lib-Gy817Cvp.mjs
1798
+ const CAPTURE_KEY_LENGTH = 160;
1799
+ const CAPTURE_METADATA_LENGTH = 200;
1800
+ const CAPTURE_ISSUE_LENGTH = 500;
1801
+ const CAPTURE_FAILURE_LENGTH = 1e3;
1802
+ const CAPTURE_UPLOAD_BATCH_SIZE = 400;
1803
+ const key = z.string().trim().min(1).max(CAPTURE_KEY_LENGTH);
1804
+ const digest = z.string().regex(/^[a-f0-9]{64}$/u);
1805
+ const dimension = z.number().int().positive();
1806
+ const captureKeySchema = z.strictObject({
1807
+ source: key,
1808
+ journey: key,
1809
+ step: key,
1810
+ variant: key
1811
+ });
1812
+ const captureBlobSchema = z.strictObject({
1813
+ sha256: digest,
1814
+ bytes: z.number().int().positive(),
1815
+ mediaType: z.string().min(1).max(CAPTURE_METADATA_LENGTH)
1816
+ });
1817
+ const captureDestinationSchema = z.strictObject({ organisationId: z.uuid().optional() });
1818
+ const captureContextSchema = z.strictObject({
1819
+ key: z.string().min(1),
1820
+ label: z.string().min(1),
1821
+ url: z.url().optional(),
1822
+ sequence: z.number().int().nonnegative(),
1823
+ attempt: z.number().int().nonnegative().default(0)
1824
+ });
1825
+ const captureBaselineSelectionSchema = z.union([z.strictObject({ runId: z.uuid() }), z.strictObject({
1826
+ reference: z.string().min(1),
1827
+ revision: z.string().min(1).optional()
1828
+ })]);
1829
+ const captureReviewMetadataSchema = z.strictObject({
1830
+ destination: captureDestinationSchema,
1831
+ context: captureContextSchema.optional(),
1832
+ revision: z.string().min(1).optional(),
1833
+ baselineRunId: z.uuid().nullable(),
1834
+ compareTo: captureBaselineSelectionSchema.optional()
1835
+ });
1836
+ const captureVerdictSchema = z.enum([
1837
+ "awaiting-review",
1838
+ "approved",
1839
+ "changes-requested"
1840
+ ]);
1841
+ const captureArtifactSchema = z.strictObject({
1842
+ format: z.literal("enhance-capture"),
1843
+ version: z.literal(1),
1844
+ key: captureKeySchema,
1845
+ label: key,
1846
+ journeyLabel: key,
1847
+ order: z.number().int().nonnegative(),
1848
+ page: z.string().min(1).optional(),
1849
+ viewport: z.strictObject({
1850
+ width: dimension,
1851
+ height: dimension,
1852
+ deviceScaleFactor: z.number().positive()
1853
+ }),
1854
+ extent: z.enum(["viewport", "full-page"]),
1855
+ source: z.strictObject({
1856
+ format: z.literal("rrweb-screen"),
1857
+ version: z.literal(1),
1858
+ blob: captureBlobSchema
1859
+ }),
1860
+ preview: z.strictObject({
1861
+ blob: captureBlobSchema,
1862
+ width: dimension,
1863
+ height: dimension,
1864
+ pixelRatio: z.number().positive()
1865
+ }),
1866
+ assets: z.array(z.strictObject({
1867
+ url: z.url(),
1868
+ blob: captureBlobSchema
1869
+ })),
1870
+ provenance: z.strictObject({
1871
+ adapter: key,
1872
+ sdkVersion: key,
1873
+ kernelVersion: key,
1874
+ browser: key,
1875
+ capturedAt: z.iso.datetime(),
1876
+ sourceUrl: z.url().optional(),
1877
+ commit: z.string().min(1).max(CAPTURE_METADATA_LENGTH).optional()
1878
+ }),
1879
+ issues: z.array(z.strictObject({
1880
+ code: key,
1881
+ message: z.string().min(1).max(CAPTURE_ISSUE_LENGTH)
1882
+ }))
1883
+ }).superRefine((artifact, ctx) => {
1884
+ if (artifact.preview.width / artifact.preview.pixelRatio !== artifact.viewport.width || artifact.preview.height / artifact.preview.pixelRatio !== artifact.viewport.height) ctx.addIssue({
1885
+ code: "custom",
1886
+ path: ["preview"],
1887
+ message: "The preview and captured CSS extent must match."
1888
+ });
1889
+ if (artifact.source.blob.mediaType !== "application/json") ctx.addIssue({
1890
+ code: "custom",
1891
+ path: [
1892
+ "source",
1893
+ "blob",
1894
+ "mediaType"
1895
+ ],
1896
+ message: "Capture sources must be frozen JSON."
1897
+ });
1898
+ if (artifact.preview.blob.mediaType !== "image/png") ctx.addIssue({
1899
+ code: "custom",
1900
+ path: [
1901
+ "preview",
1902
+ "blob",
1903
+ "mediaType"
1904
+ ],
1905
+ message: "Capture previews must be PNG."
1906
+ });
1907
+ if (new Set(artifact.assets.map((asset) => asset.url)).size !== artifact.assets.length) ctx.addIssue({
1908
+ code: "custom",
1909
+ path: ["assets"],
1910
+ message: "Capture resource URLs must be unique."
1911
+ });
1912
+ });
1913
+ const captureRunDescriptorSchema = z.strictObject({
1914
+ id: z.uuid(),
1915
+ canvasId: z.uuid(),
1916
+ source: key,
1917
+ runKey: key,
1918
+ generation: z.number().int().nonnegative(),
1919
+ participants: z.array(key).min(1),
1920
+ expiresAt: z.iso.datetime(),
1921
+ formatVersion: z.literal(1),
1922
+ review: captureReviewMetadataSchema.optional()
1923
+ });
1924
+ const captureAttemptSchema = z.strictObject({
1925
+ participant: key,
1926
+ testId: key,
1927
+ project: key,
1928
+ retry: z.number().int().nonnegative(),
1929
+ status: z.enum([
1930
+ "passed",
1931
+ "failed",
1932
+ "skipped",
1933
+ "interrupted",
1934
+ "timedOut"
1935
+ ]),
1936
+ captures: z.array(captureArtifactSchema)
1937
+ });
1938
+ const captureManifestSchema = z.strictObject({
1939
+ format: z.literal("enhance-capture-run"),
1940
+ version: z.literal(1),
1941
+ run: captureRunDescriptorSchema,
1942
+ participants: z.array(z.strictObject({
1943
+ id: key,
1944
+ status: z.enum([
1945
+ "passed",
1946
+ "failed",
1947
+ "interrupted"
1948
+ ])
1949
+ })).min(1),
1950
+ attempts: z.array(captureAttemptSchema),
1951
+ ordering: z.enum(["partial", "complete"])
1952
+ });
1953
+ const captureReceiptSchema = z.strictObject({
1954
+ runId: z.uuid(),
1955
+ canvasId: z.uuid(),
1956
+ canvasUrl: z.url(),
1957
+ version: z.number().int().positive(),
1958
+ manifestDigest: digest,
1959
+ frames: z.array(z.strictObject({
1960
+ key: captureKeySchema,
1961
+ frameId: key,
1962
+ captureId: z.uuid()
1963
+ })),
1964
+ issues: z.array(z.strictObject({
1965
+ code: key,
1966
+ message: z.string().max(CAPTURE_ISSUE_LENGTH)
1967
+ }))
1968
+ });
1969
+ const beginCaptureRunInputSchema = z.strictObject({
1970
+ canvasId: z.uuid().optional(),
1971
+ destination: captureDestinationSchema.optional(),
1972
+ title: z.string().trim().min(1).optional(),
1973
+ context: captureContextSchema.optional(),
1974
+ revision: z.string().min(1).optional(),
1975
+ compareTo: captureBaselineSelectionSchema.optional(),
1976
+ source: key.default("default"),
1977
+ runKey: key,
1978
+ participants: z.array(key).min(1).default(["local"]),
1979
+ formatVersion: z.literal(1).default(1)
1980
+ }).superRefine((input, ctx) => {
1981
+ if (input.canvasId === void 0 === (input.destination === void 0)) ctx.addIssue({
1982
+ code: "custom",
1983
+ message: "Choose either a canvas or a destination for this run."
1984
+ });
1985
+ if (input.canvasId !== void 0 && (input.context !== void 0 || input.compareTo !== void 0)) ctx.addIssue({
1986
+ code: "custom",
1987
+ message: "Run review requires a destination."
1988
+ });
1989
+ });
1990
+ const beginCaptureRunOutputSchema = z.strictObject({ run: captureRunDescriptorSchema });
1991
+ z.strictObject({ runId: z.uuid() });
1992
+ const captureRunStateSchema = z.enum([
1993
+ "collecting",
1994
+ "sealed",
1995
+ "converting",
1996
+ "committed",
1997
+ "failed",
1998
+ "cancelled"
1999
+ ]);
2000
+ const getCaptureRunOutputSchema = z.strictObject({
2001
+ run: captureRunDescriptorSchema,
2002
+ state: captureRunStateSchema,
2003
+ receipt: captureReceiptSchema.nullable(),
2004
+ verdict: captureVerdictSchema.optional(),
2005
+ failure: z.strictObject({
2006
+ code: key,
2007
+ message: z.string().max(CAPTURE_FAILURE_LENGTH)
2008
+ }).nullable()
2009
+ });
2010
+ z.strictObject({
2011
+ runId: z.uuid(),
2012
+ blobs: z.array(captureBlobSchema).min(1).max(CAPTURE_UPLOAD_BATCH_SIZE)
2013
+ });
2014
+ const reserveCaptureBlobsOutputSchema = z.strictObject({ uploads: z.array(z.strictObject({
2015
+ sha256: digest,
2016
+ upload: z.strictObject({
2017
+ url: z.url(),
2018
+ headers: z.record(z.string(), z.string()),
2019
+ expiresAt: z.iso.datetime()
2020
+ }).nullable()
2021
+ })).max(CAPTURE_UPLOAD_BATCH_SIZE) });
2022
+ z.strictObject({ manifest: captureManifestSchema });
2023
+ const COMMIT_LENGTH = 200;
2024
+ z.strictObject({
2025
+ canvasId: z.uuid(),
2026
+ frameId: z.string().min(1),
2027
+ captureId: z.uuid()
2028
+ });
2029
+ const preview = z.strictObject({
2030
+ captureId: z.uuid(),
2031
+ capturedAt: z.iso.datetime(),
2032
+ commit: z.string().max(COMMIT_LENGTH).optional(),
2033
+ url: z.string().min(1),
2034
+ width: z.number().positive(),
2035
+ height: z.number().positive(),
2036
+ pixelRatio: z.number().positive()
2037
+ });
2038
+ z.strictObject({
2039
+ frameId: z.string(),
2040
+ before: preview,
2041
+ after: preview
2042
+ });
2043
+ const captureKeyString = (key) => JSON.stringify([
2044
+ key.source,
2045
+ key.journey,
2046
+ key.step,
2047
+ key.variant
2048
+ ]);
2049
+ const compare = (left, right) => left < right ? -1 : left === right ? 0 : 1;
2050
+ const enqueueJsonObject = (item, state) => {
2051
+ const keys = Object.keys(item).toSorted(compare);
2052
+ state.output.push("{");
2053
+ state.pending.push({ text: "}" });
2054
+ for (let index = keys.length - 1; index >= 0; index--) {
2055
+ const key = keys[index];
2056
+ if (key === void 0) continue;
2057
+ state.pending.push({ value: Reflect.get(item, key) }, { text: `${JSON.stringify(key)}:` });
2058
+ if (index > 0) state.pending.push({ text: "," });
2059
+ }
2060
+ };
2061
+ const canAppendJsonValue = (item, state) => {
2062
+ if (item === null || typeof item === "boolean" || typeof item === "string" || typeof item === "number" && Number.isFinite(item)) {
2063
+ state.output.push(JSON.stringify(item));
2064
+ return true;
2065
+ }
2066
+ if (typeof item !== "object" || state.active.has(item)) return false;
2067
+ if (!Array.isArray(item) && Object.getPrototypeOf(item) !== Object.prototype) return false;
2068
+ state.active.add(item);
2069
+ state.pending.push({ leave: item });
2070
+ if (Array.isArray(item)) {
2071
+ state.output.push("[");
2072
+ state.pending.push({ text: "]" });
2073
+ for (let index = item.length - 1; index >= 0; index--) {
2074
+ state.pending.push({ value: item[index] });
2075
+ if (index > 0) state.pending.push({ text: "," });
2076
+ }
2077
+ } else enqueueJsonObject(item, state);
2078
+ return true;
2079
+ };
2080
+ /** Null means a value would be lost or coerced by JSON; it must never be hashed. */
2081
+ const canonicalCaptureJson = (value) => {
2082
+ const state = {
2083
+ pending: [{ value }],
2084
+ active: /* @__PURE__ */ new Set(),
2085
+ output: []
2086
+ };
2087
+ while (state.pending.length > 0) {
2088
+ const task = state.pending.pop();
2089
+ if (task === void 0) break;
2090
+ if ("text" in task) state.output.push(task.text);
2091
+ else if ("leave" in task) state.active.delete(task.leave);
2092
+ else if (!canAppendJsonValue(task.value, state)) return null;
2093
+ }
2094
+ return state.output.join("");
2095
+ };
2096
+ const captureBlobs = (artifacts) => {
2097
+ const blobs = /* @__PURE__ */ new Map();
2098
+ const unique = [];
2099
+ for (const artifact of artifacts) {
2100
+ const references = [
2101
+ artifact.source.blob,
2102
+ artifact.preview.blob,
2103
+ ...artifact.assets.map((asset) => asset.blob)
2104
+ ];
2105
+ for (const blob of references) {
2106
+ const previous = blobs.get(blob.sha256);
2107
+ if (previous !== void 0 && canonicalCaptureJson(previous) !== canonicalCaptureJson(blob)) return "The same capture digest has conflicting blob metadata.";
2108
+ if (previous === void 0) {
2109
+ unique.push(blob);
2110
+ blobs.set(blob.sha256, blob);
2111
+ }
2112
+ }
2113
+ }
2114
+ return unique.toSorted((a, b) => compare(a.sha256, b.sha256));
2115
+ };
2116
+ const finalAttempts = (manifest) => {
2117
+ const expected = new Set(manifest.run.participants);
2118
+ 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.";
2119
+ const attempts = /* @__PURE__ */ new Map();
2120
+ const terminal = /* @__PURE__ */ new Map();
2121
+ for (const attempt of manifest.attempts) {
2122
+ if (!expected.has(attempt.participant)) return "Capture attempt belongs to an unreserved participant.";
2123
+ const identity = JSON.stringify([
2124
+ attempt.participant,
2125
+ attempt.project,
2126
+ attempt.testId
2127
+ ]);
2128
+ const attemptKey = JSON.stringify([identity, attempt.retry]);
2129
+ const content = canonicalCaptureJson(attempt);
2130
+ if (content === null) return "Capture attempts must contain finite JSON values.";
2131
+ const previous = terminal.get(attemptKey);
2132
+ if (previous !== void 0 && previous !== content) return "Conflicting terminal records for the same test attempt.";
2133
+ terminal.set(attemptKey, content);
2134
+ const selected = attempts.get(identity);
2135
+ if (selected === void 0 || selected.retry < attempt.retry) attempts.set(identity, attempt);
2136
+ }
2137
+ return manifest.attempts.filter((attempt) => attempts.get(JSON.stringify([
2138
+ attempt.participant,
2139
+ attempt.project,
2140
+ attempt.testId
2141
+ ])) === attempt);
2142
+ };
2143
+ const uniqueCaptures = (source, artifacts) => {
2144
+ const keys = /* @__PURE__ */ new Set();
2145
+ const orders = /* @__PURE__ */ new Set();
2146
+ const pages = /* @__PURE__ */ new Map();
2147
+ for (const artifact of artifacts) {
2148
+ if (artifact.key.source !== source) return "Capture source differs from its reserved run.";
2149
+ const identity = captureKeyString(artifact.key);
2150
+ if (keys.has(identity)) return `Duplicate capture key: ${identity}`;
2151
+ const order = JSON.stringify([
2152
+ artifact.key.journey,
2153
+ artifact.key.variant,
2154
+ artifact.order
2155
+ ]);
2156
+ if (orders.has(order)) return `Duplicate step order in journey ${artifact.key.journey}.`;
2157
+ const journey = JSON.stringify([artifact.key.journey, artifact.key.variant]);
2158
+ if (pages.has(journey) && pages.get(journey) !== artifact.page) return `Every step in journey ${artifact.key.journey} must use the same page.`;
2159
+ pages.set(journey, artifact.page);
2160
+ keys.add(identity);
2161
+ orders.add(order);
2162
+ }
2163
+ return null;
2164
+ };
2165
+ const compareCaptureArtifacts = (left, right) => {
2166
+ const journey = compare(left.key.journey, right.key.journey);
2167
+ if (journey !== 0) return journey;
2168
+ const variant = compare(left.key.variant, right.key.variant);
2169
+ return variant === 0 ? left.order - right.order : variant;
2170
+ };
2171
+ /** All publishers select whole terminal attempts with the same completeness rules. */
2172
+ const selectedCaptures = (input) => {
2173
+ const parsed = captureManifestSchema.safeParse(input);
2174
+ if (!parsed.success) return "Invalid capture manifest.";
2175
+ const manifest = parsed.data;
2176
+ const attempts = finalAttempts(manifest);
2177
+ if (typeof attempts === "string") return attempts;
2178
+ const artifacts = attempts.flatMap((attempt) => attempt.status === "passed" ? attempt.captures : []);
2179
+ if (artifacts.length === 0) return "A run must contain at least one successful capture.";
2180
+ const conflict = uniqueCaptures(manifest.run.source, artifacts);
2181
+ if (conflict !== null) return conflict;
2182
+ const blobs = captureBlobs(artifacts);
2183
+ return typeof blobs === "string" ? blobs : artifacts.toSorted(compareCaptureArtifacts);
2184
+ };
2185
+ const captureManifestContent = (manifest) => {
2186
+ const serialized = canonicalCaptureJson(manifest);
2187
+ return serialized === null ? null : `enhance-capture-run:v1\0${serialized}`;
2188
+ };
2189
+ const mergeCaptureManifests = (parts) => {
2190
+ const first = parts[0];
2191
+ if (first === void 0) return "At least one participant manifest is required.";
2192
+ const descriptor = canonicalCaptureJson(first.run);
2193
+ const participants = /* @__PURE__ */ new Map();
2194
+ const attempts = [];
2195
+ for (const part of parts) {
2196
+ if (canonicalCaptureJson(part.run) !== descriptor || part.ordering !== first.ordering) return "Participant manifests must belong to the same reserved run and ordering.";
2197
+ for (const participant of part.participants) {
2198
+ if (participants.has(participant.id)) return "A participant manifest was supplied more than once.";
2199
+ participants.set(participant.id, participant);
2200
+ }
2201
+ if (part.attempts.some((attempt) => part.participants.every((participant) => participant.id !== attempt.participant))) return "A participant manifest contains another participant’s attempt.";
2202
+ attempts.push(...part.attempts);
2203
+ }
2204
+ const manifest = {
2205
+ ...first,
2206
+ participants: Array.from(participants, ([, participant]) => participant).toSorted((a, b) => compare(a.id, b.id)),
2207
+ attempts: attempts.toSorted((a, b) => {
2208
+ const participant = compare(a.participant, b.participant);
2209
+ if (participant !== 0) return participant;
2210
+ const project = compare(a.project, b.project);
2211
+ if (project !== 0) return project;
2212
+ const test = compare(a.testId, b.testId);
2213
+ return test === 0 ? a.retry - b.retry : test;
2214
+ })
2215
+ };
2216
+ const selected = selectedCaptures(manifest);
2217
+ return typeof selected === "string" ? selected : manifest;
2218
+ };
2219
+ z.strictObject({ canvasId: z.uuid() }).extend({ verdict: captureVerdictSchema });
2220
+ const captureReferenceInputSchema = z.strictObject({
2221
+ canvasId: z.uuid(),
2222
+ name: z.string().min(1)
2223
+ });
2224
+ const captureReferenceSchema = z.strictObject({
2225
+ runId: z.uuid(),
2226
+ revision: z.string(),
2227
+ version: z.number().int().positive()
2228
+ });
2229
+ const updateCaptureReferenceInputSchema = captureReferenceInputSchema.extend({
2230
+ expectedVersion: z.number().int().nonnegative(),
2231
+ revision: z.string().min(1)
2232
+ });
2233
+ const captureReviewSchema = z.strictObject({
2234
+ current: getCaptureRunOutputSchema,
2235
+ latest: captureRunDescriptorSchema,
2236
+ related: z.array(z.strictObject({
2237
+ run: captureRunDescriptorSchema,
2238
+ verdict: captureVerdictSchema
2239
+ })),
2240
+ changes: z.array(z.strictObject({
2241
+ key: captureKeySchema,
2242
+ frameId: z.string(),
2243
+ label: z.string(),
2244
+ journeyLabel: z.string(),
2245
+ page: z.string().optional(),
2246
+ change: z.enum([
2247
+ "new",
2248
+ "changed",
2249
+ "unchanged",
2250
+ "uncompared"
2251
+ ])
2252
+ }))
2253
+ });
2254
+ const captureError = (code, message, runId) => Object.assign(new Error(message), {
2255
+ code,
2256
+ ...runId !== void 0 && { runId }
2257
+ });
2258
+ const captureBlobDigest = (bytes) => createHash("sha256").update(bytes).digest("hex");
2259
+ const captureManifestDigest = (manifest) => {
2260
+ const canonical = captureManifestContent(manifest);
2261
+ if (canonical === null) throw new Error("A capture manifest must contain only finite JSON values.");
2262
+ return createHash("sha256").update(canonical).digest("hex");
2263
+ };
2264
+ const captureBlobPath = (directory, digest) => {
2265
+ if (!/^[a-f0-9]{64}$/u.test(digest)) throw captureError("artifact", "Invalid capture blob digest.");
2266
+ return path.join(path.resolve(directory), "blobs", digest);
2267
+ };
2268
+ const readCaptureBlob = async (directory, description) => {
2269
+ const path = captureBlobPath(directory, description.sha256);
2270
+ const info = await stat(path);
2271
+ if (!info.isFile() || info.size !== description.bytes) throw captureError("artifact", `Capture blob size does not match ${description.sha256}.`);
2272
+ const bytes = await readFile(path);
2273
+ if (captureBlobDigest(bytes) !== description.sha256) throw captureError("artifact", `Capture blob checksum does not match ${description.sha256}.`);
2274
+ return bytes;
2275
+ };
2276
+ const writeCapturePayload = async (directory, payload) => {
2277
+ const artifact = captureArtifactSchema.parse(payload.artifact);
2278
+ await mkdir(path.join(directory, "blobs"), { recursive: true });
2279
+ let unavailable = 0;
2280
+ for (const blob of payload.blobs) try {
2281
+ if (blob.description.bytes !== blob.bytes.byteLength || captureBlobDigest(blob.bytes) !== blob.description.sha256) throw captureError("artifact", "Capture blob bytes do not match their descriptor.");
2282
+ const path = captureBlobPath(directory, blob.description.sha256);
2283
+ const temporary = `${path}.${globalThis.crypto.randomUUID()}.tmp`;
2284
+ await writeFile(temporary, blob.bytes, {
2285
+ flag: "wx",
2286
+ mode: 384
2287
+ });
2288
+ await rename(temporary, path);
2289
+ } catch {
2290
+ unavailable++;
2291
+ }
2292
+ try {
2293
+ await readCaptureBlob(directory, artifact.source.blob);
2294
+ } catch {
2295
+ await readCaptureBlob(directory, artifact.preview.blob);
2296
+ }
2297
+ if (unavailable > 0) channel("enhance.capture.resources").publish({
2298
+ stage: "local-write",
2299
+ unavailable
2300
+ });
2301
+ return artifact;
2302
+ };
2303
+ const writeCaptureJson = async (path, value) => {
2304
+ const temporary = `${path}.${globalThis.crypto.randomUUID()}.tmp`;
2305
+ await writeFile(temporary, JSON.stringify(value), { mode: 384 });
2306
+ await rename(temporary, path);
2307
+ };
2308
+ const readCaptureManifest = async (path) => {
2309
+ const raw = JSON.parse(await readFile(path, "utf8"));
2310
+ return captureManifestSchema.parse(raw);
2311
+ };
2312
+
2313
+ //#endregion
2314
+ //#region ../../packages/sdk/dist/capture-client.client-wrAGDHxW.mjs
2315
+ const UPLOAD_BATCH_SIZE = 400;
2316
+ const POLL_INTERVAL_MS = 250;
2317
+ const readFromDirectories = async (directories, blob) => {
2318
+ for (const directory of directories) try {
2319
+ return await readCaptureBlob(directory, blob);
2320
+ } catch {}
2321
+ throw captureError("artifact", `Capture blob is unavailable: ${blob.sha256}.`);
2322
+ };
2323
+ const uploadBlob = async (input) => {
2324
+ if (input.held === void 0) throw captureError("transport", "Enhance omitted a requested blob reservation.", input.runId);
2325
+ const upload = input.held.upload;
2326
+ if (upload === null) return;
2327
+ const bytes = await readFromDirectories(input.directories, input.blob);
2328
+ try {
2329
+ if (!(await fetch(upload.url, {
2330
+ method: "PUT",
2331
+ headers: upload.headers,
2332
+ body: new Blob([Uint8Array.from(bytes)]),
2333
+ signal: AbortSignal.timeout(input.transport.timeoutMs),
2334
+ redirect: "error"
2335
+ })).ok) throw captureError("transport", "Upload refused.", input.runId);
2336
+ } catch {
2337
+ throw captureError("transport", "Capture upload was not confirmed. Resume the same manifest.", input.runId);
2338
+ }
2339
+ };
2340
+ const uploadBlobs = async (transport, manifest, directories, blobs) => {
2341
+ let unavailable = 0;
2342
+ const available = [];
2343
+ for (const blob of blobs) try {
2344
+ await readFromDirectories(directories, blob);
2345
+ available.push(blob);
2346
+ } catch {
2347
+ unavailable++;
2348
+ }
2349
+ for (let start = 0; start < available.length; start += UPLOAD_BATCH_SIZE) {
2350
+ const batch = available.slice(start, start + UPLOAD_BATCH_SIZE);
2351
+ const reserved = await transport.request("captureRun.reserveAssets", {
2352
+ runId: manifest.run.id,
2353
+ blobs: batch
2354
+ }, reserveCaptureBlobsOutputSchema);
2355
+ const uploads = new Map(reserved.uploads.map((item) => [item.sha256, item]));
2356
+ for (const blob of batch) try {
2357
+ await uploadBlob({
2358
+ transport,
2359
+ runId: manifest.run.id,
2360
+ directories,
2361
+ blob,
2362
+ held: uploads.get(blob.sha256)
2363
+ });
2364
+ } catch {
2365
+ unavailable++;
2366
+ }
2367
+ }
2368
+ if (unavailable > 0) channel("enhance.capture.resources").publish({
2369
+ stage: "upload",
2370
+ runId: manifest.run.id,
2371
+ unavailable
2372
+ });
2373
+ };
2374
+ const committedRun = async (transport, runId) => {
2375
+ let status = await transport.request("captureRun.publish", { runId }, getCaptureRunOutputSchema);
2376
+ const deadline = Date.now() + transport.publicationTimeoutMs;
2377
+ while (status.receipt === null && status.failure === null && !["cancelled", "failed"].includes(status.state)) {
2378
+ if (Date.now() >= deadline) throw captureError("transport", `Capture run ${runId} is still processing. Resume the same manifest.`, runId);
2379
+ await new Promise((resolve) => {
2380
+ setTimeout(resolve, POLL_INTERVAL_MS);
2381
+ });
2382
+ status = await transport.request("captureRun.publish", { runId }, getCaptureRunOutputSchema);
2383
+ }
2384
+ if (status.receipt === null) throw captureError(status.failure?.code === "conflict" ? "conflict" : "conversion", status.failure?.message ?? "The capture run was cancelled.", runId);
2385
+ return status.receipt;
2386
+ };
2387
+ const checkedReceipt = (receipt, manifest) => {
2388
+ 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);
2389
+ return receipt;
2390
+ };
2391
+ const publishManifest = async (transport, manifest, directory, blobDirectories = [directory]) => {
2392
+ const artifacts = selectedCaptures(manifest);
2393
+ if (typeof artifacts === "string") throw captureError("artifact", artifacts);
2394
+ const blobs = captureBlobs(artifacts);
2395
+ if (typeof blobs === "string") throw captureError("artifact", blobs);
2396
+ const current = await transport.request("captureRun.get", { runId: manifest.run.id }, getCaptureRunOutputSchema, true);
2397
+ if (current.receipt !== null) {
2398
+ const receipt = checkedReceipt(current.receipt, manifest);
2399
+ await writeCaptureJson(path.join(directory, "receipt.json"), receipt);
2400
+ return receipt;
2401
+ }
2402
+ if (current.state === "collecting") await uploadBlobs(transport, manifest, blobDirectories, blobs);
2403
+ await transport.request("captureRun.seal", { manifest }, getCaptureRunOutputSchema);
2404
+ const receipt = checkedReceipt(await committedRun(transport, manifest.run.id), manifest);
2405
+ await writeCaptureJson(path.join(directory, "receipt.json"), receipt);
2406
+ return receipt;
2407
+ };
2408
+ const publishCaptureManifest = async (transport, manifest, directory, blobDirectories = [directory]) => {
2409
+ try {
2410
+ return await publishManifest(transport, manifest, directory, blobDirectories);
2411
+ } catch (error) {
2412
+ if (error instanceof Error) throw Object.assign(error, { runId: manifest.run.id });
2413
+ throw captureError("transport", "Capture publication was not confirmed. Resume the same manifest.", manifest.run.id);
2414
+ }
2415
+ };
2416
+ const RATE_LIMIT_STATUS = 429;
2417
+ const MILLISECONDS_PER_SECOND = 1e3;
2418
+ const MAX_ERROR_LENGTH = 1e3;
2419
+ const DEFAULT_TIMEOUT_MS = 3e4;
2420
+ const DEFAULT_PUBLICATION_TIMEOUT_MS = 6e5;
2421
+ const NODE_TIMER_MAX_MS = 2147483647;
2422
+ const HTTP_ERRORS = /* @__PURE__ */ new Map([
2423
+ [401, "authorization"],
2424
+ [403, "authorization"],
2425
+ [409, "conflict"],
2426
+ [400, "artifact"]
2427
+ ]);
2428
+ const requestResponse = async (url, options, timeoutMs, retryDeadline) => {
2429
+ try {
2430
+ for (;;) {
2431
+ const response = await fetch(url, {
2432
+ ...options,
2433
+ signal: AbortSignal.timeout(timeoutMs)
2434
+ });
2435
+ if (response.status !== RATE_LIMIT_STATUS) return response;
2436
+ const header = response.headers.get("retry-after");
2437
+ if (header === null) return response;
2438
+ const seconds = Number(header);
2439
+ const wait = Number.isFinite(seconds) ? seconds * MILLISECONDS_PER_SECOND : Date.parse(header) - Date.now();
2440
+ if (!Number.isFinite(wait) || wait < 0 || Date.now() + wait >= retryDeadline) return response;
2441
+ await response.body?.cancel();
2442
+ await setTimeout$1(wait);
2443
+ }
2444
+ } catch {
2445
+ throw captureError("transport", "Enhance did not confirm the request. Resume the same run to recover its result.");
2446
+ }
2447
+ };
2448
+ const responseBody = async (response) => {
2449
+ try {
2450
+ return await response.json();
2451
+ } catch {
2452
+ return null;
2453
+ }
2454
+ };
2455
+ const call = async (url, options, schema, request) => {
2456
+ const { procedure, timeoutMs, publicationTimeoutMs } = request;
2457
+ const response = await requestResponse(url, options, timeoutMs, Date.now() + publicationTimeoutMs);
2458
+ const body = await responseBody(response);
2459
+ if (!response.ok) {
2460
+ const error = typeof body === "object" && body !== null ? Reflect.get(body, "error") : null;
2461
+ const message = typeof error === "object" && error !== null ? Reflect.get(error, "message") : null;
2462
+ throw captureError(HTTP_ERRORS.get(response.status) ?? "transport", typeof message === "string" ? message.slice(0, MAX_ERROR_LENGTH) : `Enhance rejected ${procedure} (HTTP ${String(response.status)}).`);
2463
+ }
2464
+ const result = typeof body === "object" && body !== null ? Reflect.get(body, "result") : null;
2465
+ const data = typeof result === "object" && result !== null ? Reflect.get(result, "data") : void 0;
2466
+ const parsed = schema.safeParse(data);
2467
+ if (!parsed.success) throw captureError("transport", `Enhance returned an incompatible ${procedure} response.`);
2468
+ return parsed.data;
2469
+ };
2470
+ const captureTransport = (options) => {
2471
+ const base = URL.parse(options.apiUrl);
2472
+ if (base === null || !["http:", "https:"].includes(base.protocol) || base.username !== "" || base.password !== "" || options.token.trim() === "") throw captureError("configuration", "Enhance needs an HTTP API URL and an explicit token.");
2473
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
2474
+ const publicationTimeoutMs = options.publicationTimeoutMs ?? DEFAULT_PUBLICATION_TIMEOUT_MS;
2475
+ if (!Number.isSafeInteger(publicationTimeoutMs) || publicationTimeoutMs < 1) throw captureError("configuration", "Enhance publication timeout must be a positive integer in milliseconds.");
2476
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > NODE_TIMER_MAX_MS) throw captureError("configuration", `Enhance timeout must fit the Node timer range of 1 to ${String(NODE_TIMER_MAX_MS)} milliseconds.`);
2477
+ return {
2478
+ timeoutMs,
2479
+ publicationTimeoutMs,
2480
+ request: async (procedure, input, schema, isQuery = false) => {
2481
+ const url = new URL(`${base.pathname.replace(/\/$/u, "")}/trpc/${procedure}`, base.origin);
2482
+ if (isQuery) url.searchParams.set("input", JSON.stringify(input));
2483
+ return call(url, {
2484
+ method: isQuery ? "GET" : "POST",
2485
+ headers: {
2486
+ authorization: `Bearer ${options.token}`,
2487
+ "content-type": "application/json"
2488
+ },
2489
+ ...!isQuery && { body: JSON.stringify(input) },
2490
+ redirect: "error"
2491
+ }, schema, {
2492
+ procedure,
2493
+ timeoutMs,
2494
+ publicationTimeoutMs
2495
+ });
2496
+ }
2497
+ };
2498
+ };
2499
+ const nodeManifest = (descriptor, captured) => {
2500
+ const participant = descriptor.participants[0];
2501
+ if (participant === void 0) throw captureError("configuration", "No capture participant was reserved.");
2502
+ return {
2503
+ format: "enhance-capture-run",
2504
+ version: 1,
2505
+ run: descriptor,
2506
+ ordering: "partial",
2507
+ participants: [{
2508
+ id: participant,
2509
+ status: "passed"
2510
+ }],
2511
+ attempts: [{
2512
+ participant,
2513
+ testId: "node",
2514
+ project: "node",
2515
+ retry: 0,
2516
+ status: "passed",
2517
+ captures: captured
2518
+ }]
2519
+ };
2520
+ };
2521
+ const createRun = (transport, input, directory) => {
2522
+ const descriptor = captureRunDescriptorSchema.parse(input);
2523
+ const artifacts = [];
2524
+ let isClosed = false;
2525
+ return {
2526
+ descriptor,
2527
+ directory,
2528
+ add: async (payload) => {
2529
+ if (isClosed) throw captureError("configuration", "This run no longer accepts captures.");
2530
+ const written = writeCapturePayload(directory, payload);
2531
+ artifacts.push(written);
2532
+ await written;
2533
+ },
2534
+ publish: async () => {
2535
+ isClosed = true;
2536
+ const captured = await Promise.all(artifacts);
2537
+ if (descriptor.participants.length !== 1) throw captureError("configuration", "Multi-participant runs must publish a complete merged manifest.");
2538
+ const manifest = nodeManifest(descriptor, captured);
2539
+ const selected = selectedCaptures(manifest);
2540
+ if (typeof selected === "string") throw captureError("artifact", selected);
2541
+ await mkdir(directory, { recursive: true });
2542
+ await writeCaptureJson(path.join(directory, "manifest.json"), manifest);
2543
+ return publishCaptureManifest(transport, manifest, directory);
2544
+ },
2545
+ cancel: async () => {
2546
+ isClosed = true;
2547
+ return (await transport.request("captureRun.cancel", { runId: descriptor.id }, getCaptureRunOutputSchema)).receipt;
2548
+ }
2549
+ };
2550
+ };
2551
+ const beginCaptureRun = async (transport, input) => {
2552
+ const request = beginCaptureRunInputSchema.parse({
2553
+ canvasId: input.canvas,
2554
+ destination: input.destination,
2555
+ title: input.title,
2556
+ context: input.context,
2557
+ revision: input.revision,
2558
+ compareTo: input.compareTo,
2559
+ source: input.source,
2560
+ runKey: input.runKey,
2561
+ participants: input.participants
2562
+ });
2563
+ const { run } = await transport.request("captureRun.begin", request, beginCaptureRunOutputSchema);
2564
+ const directory = input.directory ?? path.join(".enhance", "captures", run.id);
2565
+ await mkdir(directory, { recursive: true });
2566
+ await writeCaptureJson(path.join(directory, "run.json"), run);
2567
+ return createRun(transport, run, directory);
2568
+ };
2569
+ const createEnhance = (options) => {
2570
+ const transport = captureTransport(options);
2571
+ const get = async (runId) => transport.request("captureRun.get", { runId }, getCaptureRunOutputSchema, true);
2572
+ return { captures: {
2573
+ review: async (canvasId) => transport.request("captureRun.review", { canvasId }, captureReviewSchema.nullable(), true),
2574
+ decide: async (canvasId, verdict) => {
2575
+ await transport.request("captureRun.decide", {
2576
+ canvasId,
2577
+ verdict
2578
+ }, z.object({ accepted: z.literal(true) }));
2579
+ },
2580
+ reference: async (canvasId, name) => transport.request("captureRun.reference", {
2581
+ canvasId,
2582
+ name
2583
+ }, captureReferenceSchema.nullable(), true),
2584
+ promote: async (input) => transport.request("captureRun.promote", updateCaptureReferenceInputSchema.parse(input), captureReferenceSchema),
2585
+ publishManifests: async (paths) => {
2586
+ const manifest = mergeCaptureManifests(await Promise.all(paths.map(async (path) => readCaptureManifest(path))));
2587
+ if (typeof manifest === "string") throw captureError("artifact", manifest);
2588
+ const directory = path.dirname(paths[0] ?? ".");
2589
+ await writeCaptureJson(path.join(directory, "merged-manifest.json"), manifest);
2590
+ return publishCaptureManifest(transport, manifest, directory, paths.map((path$1) => path.dirname(path$1)));
2591
+ },
2592
+ begin: async (input) => beginCaptureRun(transport, input),
2593
+ publishManifest: async (path$2) => publishCaptureManifest(transport, await readCaptureManifest(path$2), path.dirname(path$2)),
2594
+ get
2595
+ } };
2596
+ };
2597
+
2598
+ //#endregion
2599
+ //#region src/infrastructure/captures.program.ts
2600
+ const publicationError = (error, manifest) => {
2601
+ const code = error instanceof Error ? Reflect.get(error, "code") : void 0;
2602
+ return new CliError(code === "authorization" ? "UNAUTHORIZED" : code === "conflict" ? "CONFLICT" : ["configuration", "artifact"].includes(String(code)) ? "BAD_REQUEST" : "INTERNAL", error instanceof Error ? error.message : "Capture publication was not confirmed.", `Retry enhance captures publish with the same manifest: ${manifest}`);
2603
+ };
2604
+ const registerCapturesProgram = (program, dependencies) => {
2605
+ program.command("captures").description("Publish SDK captures as editable canvas journeys.").command("publish <manifest>").description("Publish or resume a reserved capture manifest and print its durable receipt.").action(async (manifest) => {
2606
+ const token = await dependencies.credentials.read();
2607
+ if (token === null) throw new CliError("UNAUTHORIZED", "Capture publication requires an agent token.", "Run enhance auth login, then retry the same manifest.");
2608
+ const enhance = createEnhance({
2609
+ apiUrl: dependencies.apiUrl,
2610
+ token
2611
+ });
2612
+ try {
2613
+ dependencies.output.result(await enhance.captures.publishManifest(manifest));
2614
+ } catch (error) {
2615
+ throw publicationError(error, manifest);
2616
+ }
2617
+ });
2618
+ };
2619
+
1622
2620
  //#endregion
1623
2621
  //#region src/infrastructure/command-summaries.consts.ts
1624
2622
  const COMMAND_SUMMARIES = {
2623
+ "captureRun.review": "Read product review for a run canvas.",
1625
2624
  "canvas chats": "Chat history.",
1626
2625
  "canvas.createEditableFrame": "Make a screen editable.",
1627
2626
  "canvas.create": "Create a canvas.",
@@ -2027,13 +3026,14 @@ const DEFAULT_POSITION = 48;
2027
3026
  const DEFAULT_WIDTH = 1440;
2028
3027
  const DEFAULT_HEIGHT = 900;
2029
3028
  const registerPrototypeProgram = (program, invocation, catalog, output) => {
2030
- (program.commands.find((command) => command.name() === "prototype") ?? program.command("prototype").description("Publish static frontend prototypes.")).command("publish").description("Package and publish an unpacked static build directory. The CLI creates the upload artifact.").requiredOption("--canvas-id <uuid>", "Canvas that receives the prototype.").requiredOption("--directory <path>", "Unpacked static build directory; do not pass a ZIP file.").requiredOption("--title <title>", "Label above the prototype frame.").requiredOption("--base-version <number>", "Current canvas document version.", positiveInteger).option("--prototype-id <uuid>", "Existing prototype identity to publish a new deployment.").option("--client-token <uuid>", "Stable retry token for this exact build.").option("--node-id <id>", "Stable canvas node id for a new prototype.").option("--entry <path>", "HTML entry relative to the uploaded directory.", "index.html").option("--x <pixels>", "Canvas x coordinate.", finiteNumber, DEFAULT_POSITION).option("--y <pixels>", "Canvas y coordinate.", finiteNumber, DEFAULT_POSITION).option("--width <pixels>", "Prototype viewport width.", positiveNumber, DEFAULT_WIDTH).option("--height <pixels>", "Prototype viewport height.", positiveNumber, DEFAULT_HEIGHT).action(async (options) => {
3029
+ (program.commands.find((command) => command.name() === "prototype") ?? program.command("prototype").description("Publish static frontend prototypes.")).command("publish").description("Package and publish an unpacked static build directory. The CLI creates the upload artifact.").requiredOption("--canvas-id <uuid>", "Canvas that receives the prototype.").requiredOption("--directory <path>", "Unpacked static build directory; do not pass a ZIP file.").requiredOption("--title <title>", "Label above the prototype frame.").requiredOption("--base-version <number>", "Current canvas document version.", positiveInteger).option("--prototype-id <uuid>", "Existing prototype identity to publish a new deployment.").option("--client-token <uuid>", "Stable retry token for this exact build.").option("--node-id <id>", "Exact canvas node to create, update, or fork when it is a copy.").option("--entry <path>", "HTML entry relative to the uploaded directory.", "index.html").option("--x <pixels>", "Canvas x coordinate.", finiteNumber, DEFAULT_POSITION).option("--y <pixels>", "Canvas y coordinate.", finiteNumber, DEFAULT_POSITION).option("--width <pixels>", "Prototype viewport width.", positiveNumber, DEFAULT_WIDTH).option("--height <pixels>", "Prototype viewport height.", positiveNumber, DEFAULT_HEIGHT).action(async (options) => {
2031
3030
  const clientToken = options.clientToken ?? randomUUID();
2032
3031
  output.result(await invocation.invoke({
2033
3032
  capability: fromCapabilityReference(catalog(), "prototype.publish"),
2034
3033
  arguments: {
2035
3034
  canvasId: options.canvasId,
2036
3035
  prototypeId: options.prototypeId ?? null,
3036
+ targetMode: options.prototypeId !== void 0 && options.nodeId === void 0 ? "prototype" : "node",
2037
3037
  nodeId: options.nodeId ?? `proto_${clientToken.replaceAll("-", "")}`,
2038
3038
  title: options.title,
2039
3039
  directory: options.directory,
@@ -2163,6 +3163,7 @@ const registerUtilityPrograms = (program, input, catalog) => {
2163
3163
  });
2164
3164
  registerAuthProgram(program, createAuthUseCase(input.credentials, input.remote, createOauthLoopbackAdapter(input.remote)), input.output);
2165
3165
  registerCommentProgram(program, invocation, catalog, input.output);
3166
+ registerCapturesProgram(program, input);
2166
3167
  registerOperationProgram(program, {
2167
3168
  invocation,
2168
3169
  catalog,
@@ -2473,10 +3474,12 @@ const main = async () => {
2473
3474
  const output = createNdjsonLoggerAdapter(state, config.configDirectory, config.commandName);
2474
3475
  const credentials = createFileCredentialAdapter(config.configDirectory);
2475
3476
  const mutationKey = createMutationKeyAdapter();
3477
+ const remote = createHttpRemoteAdapter(config.apiUrl, credentials, mutationKey);
2476
3478
  const cli = createCliProgram({
2477
- version: "0.1.25",
3479
+ apiUrl: config.apiUrl,
3480
+ version: "0.1.37",
2478
3481
  credentials,
2479
- remote: createHttpRemoteAdapter(config.apiUrl, credentials, mutationKey),
3482
+ remote,
2480
3483
  mutationKey,
2481
3484
  output,
2482
3485
  state,