@enhance-eng/enhance 0.1.22 → 0.1.33

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,18 +1,20 @@
1
1
  #!/usr/bin/env node
2
- import { $ as createOrganisationOutputSchema, A as parseCanvasReference, At as canvasLayoutPriorityDeclarations, D as assertCanvasReferenceOperations, Dt as canvasAuthoredStyleDeclarations, E as assertCanvasReferenceNodes, Et as canvasAuthoredLayoutValueOf, F as completeScreenOutputSchema, I as createScreenOutputSchema, L as appendRecordingChunkOutputSchema, M as CliError, Mt as canvasSchema, O as canvasReferenceNodeIds, Ot as canvasAxisStyleProperties, P as appErrorSchema, R as completeRecordingOutputSchema, T as canvasEditsSchema, Tt as canvasReadableSceneDocumentSchema, _t as RENDER_MIN_SCALE, a as toExitCode, at as beginCanvasActivityOutputSchema, bt as canvasWorldBoundsSchema, c as toSharedCapabilities, ct as getCanvasDocumentOutputSchema, d as createCapabilityCatalogAdapter, et as emptyFixtureDocument, f as createRouterShapeAdapter, g as PROCEDURE_DESCRIPTIONS, h as OPTION_DESCRIPTIONS, i as toCanvasAuthoringResult, it as canvasTextRunsOf, j as PartialBatchError, k as fromCanvasReference, kt as canvasLayoutMainAxisOf, l as createMcpCapabilityDiscoveryAdapter, lt as saveCanvasDocumentOutputSchema, n as withCommandName, o as toFailurePayload, ot as canvasAgentActivityPhaseSchema, p as createCapabilityPolicyAdapter, pt as canvasOperationSchema, t as withCommandInFailure, tt as withFixtureScreen, u as ProcessExitError, ut as MAX_CANVAS_OPERATIONS, z as startRecordingOutputSchema } from "./cli-output-identity.lib-a1wTreJ6.mjs";
3
- import { a as createOauthLoopbackAdapter, c as createWriteHtmlCanvasComposite, d as createApplyCanvasComposite, f as createCanvasActivityComposite, l as createEditCanvasComposite, m as createAuthUseCase, n as createHttpRemoteAdapter, o as createCapabilityInvocationAdapter, p as createRenderCanvasComposite, r as CLI_CONFIG, s as createRenderFileAdapter, t as createMutationKeyAdapter, u as sceneAtVersion } from "./mutation-key.adapter-B3ugNA3r.mjs";
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";
4
4
  import { t as toCapabilityInventory } from "./capability-inventory.mapper-DyYXyVBJ.mjs";
5
- import { t as createFileCredentialAdapter } from "./file-credential.adapter-rI5HpMEo.mjs";
5
+ import { t as createFileCredentialAdapter } from "./file-credential.adapter-C78gc9OK.mjs";
6
+ import process from "node:process";
6
7
  import { Command } from "commander";
7
8
  import { createCli, parseRouter } from "trpc-cli";
8
9
  import { z } from "zod";
9
10
  import { hostname, tmpdir } from "node:os";
10
- import process from "node:process";
11
11
  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
@@ -365,15 +367,8 @@ const registerAuthProgram = (program, auth, output) => {
365
367
  //#endregion
366
368
  //#region src/infrastructure/canvas-authoring-input.schema.ts
367
369
  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
370
  const positiveIntegerSchema = z.coerce.number().int().positive();
376
- const renderScaleSchema = z.coerce.number().min(MIN_RENDER_SCALE).max(MAX_RENDER_SCALE);
371
+ const renderScaleSchema = z.coerce.number().positive();
377
372
  const authoringUuidSchema = z.uuid();
378
373
  const styleValueSchema = z.union([
379
374
  z.string(),
@@ -383,20 +378,20 @@ const styleValueSchema = z.union([
383
378
  const styleObjectSchema = z.record(z.string(), styleValueSchema);
384
379
  const textUpdatesSchema = z.array(z.object({
385
380
  nodeId: z.string().min(1).max(NODE_ID_LENGTH),
386
- textContent: z.string().max(TEXT_LENGTH)
387
- })).min(1).max(MAX_NODE_IDS);
381
+ textContent: z.string()
382
+ })).min(1);
388
383
  const renameUpdatesSchema = z.array(z.object({
389
384
  nodeId: z.string().min(1).max(NODE_ID_LENGTH),
390
- name: z.string().max(NODE_NAME_LENGTH)
391
- })).min(1).max(MAX_NODE_IDS);
385
+ name: z.string()
386
+ })).min(1);
392
387
  const styleUpdatesSchema = z.array(z.object({
393
- nodeIds: z.array(z.string().min(1).max(NODE_ID_LENGTH)).min(1).max(MAX_BATCHES),
388
+ nodeIds: z.array(z.string().min(1).max(NODE_ID_LENGTH)).min(1),
394
389
  styles: styleObjectSchema
395
- })).min(1).max(MAX_BATCHES);
390
+ })).min(1);
396
391
  const duplicateInputsSchema = z.array(z.object({
397
392
  id: z.string().min(1).max(NODE_ID_LENGTH),
398
393
  parentId: z.string().min(1).max(NODE_ID_LENGTH).optional()
399
- })).min(1).max(MAX_BATCHES);
394
+ })).min(1);
400
395
  const moveInputsSchema = z.array(z.union([
401
396
  z.object({
402
397
  nodeId: z.string().min(1).max(NODE_ID_LENGTH),
@@ -411,9 +406,9 @@ const moveInputsSchema = z.array(z.union([
411
406
  parentId: z.string().min(1).max(NODE_ID_LENGTH),
412
407
  index: z.number().int().nonnegative().optional()
413
408
  })
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);
409
+ ])).min(1);
410
+ const nodeIdsSchema = z.array(z.string().min(1).max(NODE_ID_LENGTH)).min(1);
411
+ const sourceDepthSchema = z.coerce.number().int().min(0);
417
412
 
418
413
  //#endregion
419
414
  //#region src/infrastructure/canvas-authoring-command.lib.ts
@@ -434,7 +429,7 @@ const applyAuthoringOperations = async (input, options, purpose, operations) =>
434
429
  selectAuthoringToken(input, options.clientToken, false);
435
430
  const reference = parseCanvasReference(options.canvas);
436
431
  const baseVersion = authoringBaseVersion(options.baseVersion);
437
- if (reference.nodeIds.length > 0) assertCanvasReferenceOperations(reference, await sceneAtVersion(input, reference.canvasId, baseVersion), operations);
432
+ if (hasCanvasReferenceScope(reference)) assertCanvasReferenceOperations(reference, await sceneAtVersion(input, reference.canvasId, baseVersion), operations);
438
433
  return createApplyCanvasComposite(input.remote).execute({
439
434
  canvasId: reference.canvasId,
440
435
  mutationId: authoringMutationId(input, purpose),
@@ -455,25 +450,26 @@ const applyAuthoringEdits = async (input, options, edits, idPrefix) => {
455
450
  };
456
451
 
457
452
  //#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) => {
453
+ //#region src/infrastructure/canvas-authoring-input.lib.ts
454
+ const canvasAuthoringInput = (value, option) => {
462
455
  if (!value.startsWith("@")) return value;
463
456
  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.");
457
+ if (selected === "") throw new CliError("BAD_REQUEST", `${option} @ must name a file.`, `Pass ${option} @/absolute/path/to/file or an inline value.`);
465
458
  const filePath = path.resolve(selected);
466
459
  try {
467
- const stats = statSync(filePath);
468
- if (!stats.isFile() || stats.size > MAX_OPERATION_FILE_BYTES) throw new Error("invalid size");
460
+ if (!statSync(filePath).isFile()) throw new Error("not a regular file");
469
461
  return readFileSync(filePath, "utf8");
470
462
  } 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.");
463
+ throw new CliError("BAD_REQUEST", `Could not read the file at ${filePath}.`, "Use a readable regular UTF-8 file.");
472
464
  }
473
465
  };
466
+
467
+ //#endregion
468
+ //#region src/infrastructure/canvas-operation-input.adapter.ts
469
+ const operationBatchSchema = z.array(canvasOperationSchema).min(1);
474
470
  const decodedFrom = (value) => {
475
471
  try {
476
- return JSON.parse(textFrom(value));
472
+ return JSON.parse(canvasAuthoringInput(value, "--operations"));
477
473
  } catch (error) {
478
474
  if (error instanceof CliError) throw error;
479
475
  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.");
@@ -489,14 +485,6 @@ const createCanvasOperationInputAdapter = (value) => {
489
485
  return parsed.data;
490
486
  };
491
487
 
492
- //#endregion
493
- //#region src/infrastructure/capability-reference.mapper.ts
494
- const fromCapabilityReference = (catalog, id) => {
495
- const capability = catalog.find((candidate) => candidate.id === id);
496
- if (capability === void 0) throw new TypeError(`${id} is missing from the capability catalogue`);
497
- return capability;
498
- };
499
-
500
488
  //#endregion
501
489
  //#region src/infrastructure/canvas-apply.program.ts
502
490
  const positiveInteger$3 = z.coerce.number().int().positive();
@@ -512,7 +500,7 @@ const selectMutationToken = (input, value) => {
512
500
  return input.mutationKey.current("canvas.applyOperations", {});
513
501
  };
514
502
  const configureCanvasApply = (canvas, input) => {
515
- canvas.command("apply").description("Apply an atomic canvas edit batch and return its affected bounds.").requiredOption("--canvas <url-or-id>", "Canvas URL or UUID to edit.").requiredOption("--base-version <integer>", "Exact version returned by canvas inspect or tree.").requiredOption("--operations <json-or-@path>", "JSON operation array inline, or @path to a JSON file.").option("--client-token <uuid>", "Stable UUID to reuse only when retrying this exact batch.").addHelpText("after", [
503
+ canvas.command("apply").description("Apply an atomic canvas edit batch and return its affected bounds.").summary("Apply edits and return affected bounds.").requiredOption("--canvas <url-or-id>", "Canvas URL or UUID to edit.").requiredOption("--base-version <integer>", "Exact version returned by canvas inspect or tree.").requiredOption("--operations <json-or-@path>", "JSON operation array inline, or @path to a JSON file.").option("--client-token <uuid>", "Stable UUID to reuse only when retrying this exact batch.").addHelpText("after", [
516
504
  "",
517
505
  "Supported operations: insertNode, insertText, insertPrototype, setText, editText, setBox, setLabel, setVisibility, setLocked, setConstraints, setStyles, setAppearance, setLayout, patchTypography, setTypography, patchAdditionalStyles, setAdditionalStyles, setProps, setParentage, move, remove.",
518
506
  "Use editText for revision-aware character or range changes. setText replaces the whole text and is rejected if it conflicts with a newer text edit.",
@@ -523,7 +511,7 @@ const configureCanvasApply = (canvas, input) => {
523
511
  const reference = parseCanvasReference(options.canvas);
524
512
  const baseVersion = baseVersionFrom(options.baseVersion);
525
513
  const operations = createCanvasOperationInputAdapter(options.operations);
526
- if (reference.nodeIds.length > 0) assertCanvasReferenceOperations(reference, await sceneAtVersion(input, reference.canvasId, baseVersion), operations);
514
+ if (hasCanvasReferenceScope(reference)) assertCanvasReferenceOperations(reference, await sceneAtVersion(input, reference.canvasId, baseVersion), operations);
527
515
  const result = await input.invocation.invoke({
528
516
  capability: fromCapabilityReference(input.catalog(), "canvas.apply"),
529
517
  arguments: {
@@ -598,29 +586,12 @@ const configureCanvasAuthoringActivity = (canvas, input) => {
598
586
  configureFinish(canvas, input);
599
587
  };
600
588
 
601
- //#endregion
602
- //#region src/infrastructure/canvas-authoring-bounded-input.lib.ts
603
- const boundedCanvasAuthoringInput = (value, bytes, option) => {
604
- if (!value.startsWith("@")) return value;
605
- const selected = value.slice(1);
606
- if (selected === "") throw new CliError("BAD_REQUEST", `${option} @ must name a file.`, `Pass ${option} @/absolute/path/to/file or an inline value.`);
607
- const filePath = path.resolve(selected);
608
- try {
609
- const stats = statSync(filePath);
610
- if (!stats.isFile() || stats.size > bytes) throw new Error("invalid size");
611
- return readFileSync(filePath, "utf8");
612
- } catch {
613
- 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.`);
614
- }
615
- };
616
-
617
589
  //#endregion
618
590
  //#region src/infrastructure/canvas-json-input.adapter.ts
619
- const MAX_JSON_BYTES = 1048576;
620
591
  const createCanvasJsonInputAdapter = (value, schema, option) => {
621
592
  const decoded = (() => {
622
593
  try {
623
- return JSON.parse(boundedCanvasAuthoringInput(value, MAX_JSON_BYTES, option));
594
+ return JSON.parse(canvasAuthoringInput(value, option));
624
595
  } catch (error) {
625
596
  if (error instanceof CliError) throw error;
626
597
  throw new CliError("BAD_REQUEST", `${option} must be valid JSON.`, `Pass inline JSON or @/absolute/path/to/input.json; run the command with --help.`);
@@ -1179,21 +1150,43 @@ const configureCanvasAuthoringSource = (canvas, input) => {
1179
1150
 
1180
1151
  //#endregion
1181
1152
  //#region src/infrastructure/canvas-authoring-structure.program.ts
1182
- const configureDuplicate = (canvas, input) => {
1183
- canvas.command("duplicate-nodes").description("Deep-clone node subtrees.").requiredOption("--canvas <url-or-id>", "Canvas URL or UUID to edit.").requiredOption("--base-version <integer>", "Exact current canvas version.").requiredOption("--nodes <json-or-@path>", "Array of {id,parentId?} requests.").option("--id-prefix <prefix>", "Stable namespace for cloned ids.").option("--client-token <uuid>", "Stable UUID for retrying this exact batch.").action(async (options) => {
1184
- const result = await applyAuthoringEdits(input, options, createCanvasJsonInputAdapter(options.nodes, duplicateInputsSchema, "--nodes").map((node) => ({
1185
- kind: "duplicate",
1186
- nodeIds: [node.id],
1187
- ...node.parentId !== void 0 && { parentId: node.parentId }
1188
- })), options.idPrefix);
1189
- const { duplicatedNodes, ...apply } = result;
1190
- input.output.result({
1191
- ...result,
1192
- duplicatedNodes,
1193
- apply
1194
- });
1153
+ const executeDuplicate = async (input, options) => {
1154
+ if (options.input !== void 0) {
1155
+ if ([
1156
+ options.canvas,
1157
+ options.baseVersion,
1158
+ options.nodes,
1159
+ options.idPrefix
1160
+ ].some((value) => value !== void 0)) throw new CliError("BAD_REQUEST", "Choose --input or the individual duplicate options.", "Use --input with --client-token for native measured duplication.");
1161
+ const capability = fromCapabilityReference(input.catalog(), "canvas.duplicateNodes");
1162
+ input.output.result(await input.invocation.invoke({
1163
+ capability,
1164
+ arguments: createCanvasJsonInputAdapter(options.input, capability.inputSchema, "--input"),
1165
+ clientToken: z.uuid().parse(options.clientToken)
1166
+ }));
1167
+ return;
1168
+ }
1169
+ if (options.canvas === void 0 || options.baseVersion === void 0 || options.nodes === void 0) throw new CliError("BAD_REQUEST", "Duplicate needs --canvas, --base-version and --nodes, or --input.", "Run duplicate-nodes --help.");
1170
+ const edits = createCanvasJsonInputAdapter(options.nodes, duplicateInputsSchema, "--nodes").map((node) => ({
1171
+ kind: "duplicate",
1172
+ nodeIds: [node.id],
1173
+ ...node.parentId !== void 0 && { parentId: node.parentId }
1174
+ }));
1175
+ const result = await applyAuthoringEdits(input, {
1176
+ canvas: options.canvas,
1177
+ baseVersion: options.baseVersion,
1178
+ ...options.clientToken !== void 0 && { clientToken: options.clientToken }
1179
+ }, edits, options.idPrefix);
1180
+ const { duplicatedNodes, ...apply } = result;
1181
+ input.output.result({
1182
+ ...result,
1183
+ duplicatedNodes,
1184
+ apply
1195
1185
  });
1196
1186
  };
1187
+ const configureDuplicate = (canvas, input) => {
1188
+ canvas.command("duplicate-nodes").description("Deep-clone node subtrees; --input uses native measured layout and durable copy receipts.").option("--input <json-or-@path>", "Scoped native duplication request; requires --client-token.").option("--canvas <url-or-id>", "Canvas URL or UUID to edit.").option("--base-version <integer>", "Exact current canvas version.").option("--nodes <json-or-@path>", "Array of {id,parentId?} requests.").option("--id-prefix <prefix>", "Stable namespace for cloned ids.").option("--client-token <uuid>", "Stable UUID for retrying this exact batch.").action(async (options) => executeDuplicate(input, options));
1189
+ };
1197
1190
  const configureMove = (canvas, input) => {
1198
1191
  canvas.command("move-nodes").description("Reorder or reparent nodes.").requiredOption("--canvas <url-or-id>", "Canvas URL or UUID to edit.").requiredOption("--base-version <integer>", "Exact current canvas version.").requiredOption("--moves <json-or-@path>", "Sequential before, after, or parent/index moves.").option("--client-token <uuid>", "Stable UUID for retrying this exact batch.").action(async (options) => {
1199
1192
  const result = await applyAuthoringEdits(input, options, createCanvasJsonInputAdapter(options.moves, moveInputsSchema, "--moves").map((move) => ({
@@ -1227,12 +1220,7 @@ const configureCanvasAuthoringStructure = (canvas, input) => {
1227
1220
 
1228
1221
  //#endregion
1229
1222
  //#region src/infrastructure/canvas-html-input.adapter.ts
1230
- const MAX_HTML_BYTES = 262144;
1231
- const createCanvasHtmlInputAdapter = (value) => {
1232
- const html = boundedCanvasAuthoringInput(value, MAX_HTML_BYTES, "--html");
1233
- 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.");
1234
- return html;
1235
- };
1223
+ const createCanvasHtmlInputAdapter = (value) => canvasAuthoringInput(value, "--html");
1236
1224
 
1237
1225
  //#endregion
1238
1226
  //#region src/infrastructure/canvas-authoring-write.program.ts
@@ -1257,6 +1245,7 @@ const writeHtml = async (input, options) => {
1257
1245
  capability: fromCapabilityReference(input.catalog(), "canvas.writeHtml"),
1258
1246
  arguments: {
1259
1247
  canvasId: reference.canvasId,
1248
+ ...reference.pageId !== void 0 && { pageId: reference.pageId },
1260
1249
  ...reference.nodeIds.length > 0 && { selectionNodeIds: [...reference.nodeIds] },
1261
1250
  targetNodeId: options.targetNodeId,
1262
1251
  mode,
@@ -1323,9 +1312,105 @@ const configureCanvasAuthoringWrites = (canvas, input) => {
1323
1312
  configureCreateArtboard(canvas, input);
1324
1313
  };
1325
1314
 
1315
+ //#endregion
1316
+ //#region src/infrastructure/canvas-conversion.program.ts
1317
+ const configureCanvasConversions = (canvas, input) => {
1318
+ for (const id of [
1319
+ "canvas.insertHtml",
1320
+ "canvas.makeEditable",
1321
+ "canvas.capture",
1322
+ "canvas.arrange"
1323
+ ]) {
1324
+ const capability = fromCapabilityReference(input.catalog(), id);
1325
+ const name = id === "canvas.insertHtml" ? "insert-html" : id === "canvas.makeEditable" ? "make-editable" : id.slice(7);
1326
+ canvas.command(name).description(capability.guide.summary).requiredOption("--input <json-or-@path>", "Canvas reference, base version and explicit native authoring request.").requiredOption("--client-token <uuid>", "Stable intent ID; reuse unchanged after an uncertain outcome.").action(async (options) => {
1327
+ input.output.result(await input.invocation.invoke({
1328
+ capability,
1329
+ arguments: createCanvasJsonInputAdapter(options.input, capability.inputSchema, "--input"),
1330
+ clientToken: z.uuid().parse(options.clientToken)
1331
+ }));
1332
+ });
1333
+ }
1334
+ };
1335
+
1336
+ //#endregion
1337
+ //#region src/infrastructure/canvas-exchange.program.ts
1338
+ const configureRemove = (canvas, input) => {
1339
+ canvas.command("remove").description("Remove explicitly named canvas subtrees with scope, lock and revision checks.").requiredOption("--input <json-or-@path>", "Request containing canvasRef, baseVersion and rootNodeIds.").requiredOption("--client-token <uuid>", "Stable intent ID; reuse unchanged after an uncertain outcome.").action(async (options) => {
1340
+ input.output.result(await input.invocation.invoke({
1341
+ capability: fromCapabilityReference(input.catalog(), "canvas.remove"),
1342
+ arguments: createCanvasJsonInputAdapter(options.input, canvasRemoveCapabilityInputSchema, "--input"),
1343
+ clientToken: z.uuid().parse(options.clientToken)
1344
+ }));
1345
+ });
1346
+ };
1347
+ const configureRead = (canvas, input) => {
1348
+ canvas.command("read").description("Read complete editable content, bounded evidence, or the supplied reference.").summary("Read linked canvas content.").option("--input <json-or-@path>", "Bounded read request containing canvasRef, view and target options.").option("--canvas <url-or-id>", "Complete canvas, page or selection URL for comprehensive reads.").option("--node-id <id>", "Subtree within --canvas; unavailable with --input.").action(async (options) => {
1349
+ if (options.input === void 0 === (options.canvas === void 0) || options.input !== void 0 && options.nodeId !== void 0) throw new CliError("BAD_REQUEST", "Choose exactly one of --input or --canvas; --node-id requires --canvas.", "Use --input for bounded views, or --canvas with an optional --node-id for comprehensive reads.");
1350
+ const request = options.input === void 0 ? {
1351
+ canvas: options.canvas,
1352
+ ...options.nodeId !== void 0 && { nodeId: options.nodeId }
1353
+ } : createCanvasJsonInputAdapter(options.input, canvasReadInputSchema, "--input");
1354
+ input.output.result(await input.invocation.invoke({
1355
+ capability: fromCapabilityReference(input.catalog(), "canvas.read"),
1356
+ arguments: request,
1357
+ clientToken: null
1358
+ }));
1359
+ });
1360
+ };
1361
+ const configureCanvasExchange = (canvas, input) => {
1362
+ canvas.command("find").description("Find accessible canvases and existing creation destinations with bounded results.").option("--input <json-or-@path>", "Search title, collection, limit and continuation cursor.", "{}").action(async (options) => {
1363
+ input.output.result(await input.invocation.invoke({
1364
+ capability: fromCapabilityReference(input.catalog(), "canvas.find"),
1365
+ arguments: createCanvasJsonInputAdapter(options.input, canvasFindInputSchema, "--input"),
1366
+ clientToken: null
1367
+ }));
1368
+ });
1369
+ configureRemove(canvas, input);
1370
+ configureRead(canvas, input);
1371
+ canvas.command("update-html").description("Apply an identity-preserving edit from a complete HTML snapshot.").requiredOption("--input <json-or-@path>", "Request containing canvasRef, snapshotToken, html and removeNodeIds.").requiredOption("--client-token <uuid>", "Stable intent ID; reuse unchanged after an uncertain outcome.").action(async (options) => {
1372
+ const request = createCanvasJsonInputAdapter(options.input, canvasUpdateHtmlCapabilityInputSchema, "--input");
1373
+ input.output.result(await input.invocation.invoke({
1374
+ capability: fromCapabilityReference(input.catalog(), "canvas.updateHtml"),
1375
+ arguments: request,
1376
+ clientToken: z.uuid().parse(options.clientToken)
1377
+ }));
1378
+ });
1379
+ };
1380
+
1381
+ //#endregion
1382
+ //#region src/infrastructure/canvas-prototype.program.ts
1383
+ const configureCanvasPrototype = (canvas, input) => {
1384
+ const capability = fromCapabilityReference(input.catalog(), "prototype.publishCanvas");
1385
+ canvas.command("publish-prototype").description(capability.guide.summary).requiredOption("--input <json-or-@path>", "Complete canvas reference, baseVersion, unpacked build directory or existing deployment, and bounded waitMs.").requiredOption("--client-token <uuid>", "Stable attachment intent; reuse the same arguments after uncertainty, use a new token after replanning.").action(async (options) => {
1386
+ input.output.result(await input.invocation.invoke({
1387
+ capability,
1388
+ arguments: createCanvasJsonInputAdapter(options.input, capability.inputSchema, "--input"),
1389
+ clientToken: z.uuid().parse(options.clientToken)
1390
+ }));
1391
+ });
1392
+ };
1393
+
1394
+ //#endregion
1395
+ //#region src/infrastructure/canvas-asset.program.ts
1396
+ const configureCanvasAsset = (canvas, input) => {
1397
+ const capability = fromCapabilityReference(input.catalog(), "canvas.importAsset");
1398
+ canvas.command("import-asset").description(capability.guide.summary).requiredOption("--input <json-or-@path>", "Canvas reference and selected local file source.").requiredOption("--client-token <uuid>", "Stable import intent; reuse after uncertainty.").action(async (options) => {
1399
+ input.output.result(await input.invocation.invoke({
1400
+ capability,
1401
+ arguments: createCanvasJsonInputAdapter(options.input, capability.inputSchema, "--input"),
1402
+ clientToken: z.uuid().parse(options.clientToken)
1403
+ }));
1404
+ });
1405
+ };
1406
+
1326
1407
  //#endregion
1327
1408
  //#region src/infrastructure/canvas-authoring.program.ts
1328
1409
  const configureCanvasAuthoring = (canvas, input) => {
1410
+ configureCanvasExchange(canvas, input);
1411
+ configureCanvasPrototype(canvas, input);
1412
+ configureCanvasAsset(canvas, input);
1413
+ configureCanvasConversions(canvas, input);
1329
1414
  configureCanvasAuthoringSource(canvas, input);
1330
1415
  configureCanvasAuthoringWrites(canvas, input);
1331
1416
  configureCanvasAuthoringEdits(canvas, input);
@@ -1352,33 +1437,16 @@ const nodeIdFor = (command, reference) => {
1352
1437
  return nodeId;
1353
1438
  };
1354
1439
  const readLinkedSelection = async (command, input, reference, url) => {
1355
- const held = getCanvasDocumentOutputSchema.parse(await input.remote.query("canvas.document.get", { canvasId: reference.canvasId }));
1356
- const document = canvasReadableSceneDocumentSchema.parse(held.document);
1357
- const scope = canvasReferenceNodeIds(reference, document);
1358
- const nodes = Object.values(document.nodes).filter((node) => scope.has(node.id)).map((node) => ({
1359
- ...node,
1360
- kind: node.component,
1361
- parentId: document.relationships[node.id]?.parentId ?? null,
1362
- children: Object.entries(document.relationships).filter(([, relation]) => relation.parentId === node.id).map(([id]) => id)
1363
- }));
1364
- const context = {
1365
- canvasId: reference.canvasId,
1366
- version: held.version,
1367
- source: "selection-link",
1368
- selectedNodeIds: reference.nodeIds,
1369
- next: [`Keep this selection link as --canvas for every edit: ${url}`, "Edit only these nodes or their descendants; other canvas content is outside the request."]
1370
- };
1371
- if (command.name() === "node") {
1372
- const nodeId = nodeIdFor(command, reference);
1373
- assertCanvasReferenceNodes(reference, document, [nodeId]);
1374
- return {
1375
- ...context,
1376
- node: nodes.find((node) => node.id === nodeId)
1377
- };
1378
- }
1440
+ const nodeId = command.name() === "node" ? nodeIdFor(command, reference) : void 0;
1441
+ const context = await readCanvasReferenceScene(input.remote, {
1442
+ canvas: url,
1443
+ ...nodeId !== void 0 && { nodeId }
1444
+ });
1445
+ if (nodeId === void 0) return context;
1446
+ const { nodes, ...metadata } = context;
1379
1447
  return {
1380
- ...context,
1381
- nodes
1448
+ ...metadata,
1449
+ node: nodes.find((node) => node.id === nodeId)
1382
1450
  };
1383
1451
  };
1384
1452
  const configureCanvasInspection = (canvas, input) => {
@@ -1396,7 +1464,7 @@ const configureCanvasInspection = (canvas, input) => {
1396
1464
  command.option("--canvas <url-or-id>", "Pasted canvas URL or UUID. Selection links limit reads and edits to the linked subtree.");
1397
1465
  command.action(async () => {
1398
1466
  const { reference, url } = referenceFor(command);
1399
- const result = reference.nodeIds.length > 0 ? await readLinkedSelection(command, input, reference, url) : await input.remote.query(`canvas.${name}`, {
1467
+ const result = hasCanvasReferenceScope(reference) ? await readLinkedSelection(command, input, reference, url) : await input.remote.query(`canvas.${name}`, {
1400
1468
  canvasId: reference.canvasId,
1401
1469
  ...name === "node" && { nodeId: nodeIdFor(command, reference) }
1402
1470
  });
@@ -1405,11 +1473,22 @@ const configureCanvasInspection = (canvas, input) => {
1405
1473
  }
1406
1474
  };
1407
1475
 
1476
+ //#endregion
1477
+ //#region src/infrastructure/canvas-render-input.adapter.ts
1478
+ const createCanvasRenderInputAdapter = (options) => {
1479
+ if (options.input === void 0) return null;
1480
+ if (options.canvas !== void 0 || options.nodeId !== void 0 || options.bounds !== void 0 || options.expectedVersion !== void 0 || options.atMs !== void 0 || options.output !== void 0 || options.force === true || options.scale !== "1" || options.timeoutMs !== "120000") throw new CliError("BAD_REQUEST", "The bounded --input request cannot be combined with individual render options.", "Put the entire scoped render request in --input.");
1481
+ return {
1482
+ arguments: createCanvasJsonInputAdapter(options.input, canvasRenderScopedInputSchema, "--input"),
1483
+ clientToken: z.uuid().parse(options.clientToken)
1484
+ };
1485
+ };
1486
+
1408
1487
  //#endregion
1409
1488
  //#region src/infrastructure/canvas.program.ts
1410
1489
  const positiveInteger$2 = z.coerce.number().int().positive();
1411
1490
  const nonnegativeInteger = z.coerce.number().int().nonnegative();
1412
- const renderScale = z.coerce.number().min(RENDER_MIN_SCALE).max(4);
1491
+ const renderScale = z.coerce.number().positive();
1413
1492
  const RECORDING_NODE_PREFIX = "rec_";
1414
1493
  const numberFrom = (schema, value, option, command = "canvas render") => {
1415
1494
  const parsed = schema.safeParse(value);
@@ -1445,19 +1524,26 @@ const selectClientToken = (input, value) => {
1445
1524
  input.mutationKey.select(clientToken.data, false);
1446
1525
  return input.mutationKey.current("canvas.render.create", {});
1447
1526
  };
1448
- const selectedRenderNode = async (options, input) => {
1527
+ const selectedRenderTarget = async (options, input) => {
1449
1528
  const reference = parseCanvasReference(options.canvas ?? "");
1450
- if (reference.nodeIds.length === 0) return options.nodeId;
1451
- const nodeId = options.nodeId ?? (reference.nodeIds.length === 1 ? reference.nodeIds[0] : void 0);
1452
- if (nodeId === void 0 || options.bounds !== void 0) throw new CliError("BAD_REQUEST", "A selection link requires one selected node to render.", "Pass --node-id for one node in the selection; bounds and whole-canvas renders would include unrelated content.");
1529
+ const target = targetFrom(options.nodeId, boundsFrom(options.bounds));
1530
+ const expectedVersion = options.expectedVersion === void 0 ? null : numberFrom(positiveInteger$2, options.expectedVersion, "--expected-version");
1531
+ if (!hasCanvasReferenceScope(reference)) return {
1532
+ target,
1533
+ expectedVersion
1534
+ };
1453
1535
  const held = getCanvasDocumentOutputSchema.parse(await input.remote.query("canvas.document.get", { canvasId: reference.canvasId }));
1454
- assertCanvasReferenceNodes(reference, canvasReadableSceneDocumentSchema.parse(held.document), [nodeId]);
1455
- return nodeId;
1536
+ if (expectedVersion !== null && expectedVersion !== held.version) throw new CliError("CONFLICT", "The canvas changed before rendering.", "Read the linked page or selection and render its current version.");
1537
+ return {
1538
+ target: canvasReferenceRenderTarget(reference, canvasReadableSceneDocumentSchema.parse(held.document), target),
1539
+ expectedVersion: held.version
1540
+ };
1456
1541
  };
1457
1542
  const executeRender = async (options, input) => {
1458
1543
  if (options.canvas === void 0) throw new CliError("BAD_REQUEST", "--canvas is required.", "Pass a pasted Enhance canvas URL or bare UUID through --canvas.");
1459
1544
  if (options.nodeId !== void 0 && options.bounds !== void 0) throw new CliError("BAD_REQUEST", "--node-id and --bounds cannot be combined.", "Choose one focused target, or omit both to render all authored content.");
1460
- const nodeId = await selectedRenderNode(options, input);
1545
+ const resolved = await selectedRenderTarget(options, input);
1546
+ const nodeId = resolved.target.kind === "node" ? resolved.target.nodeId : void 0;
1461
1547
  if (nodeId === void 0 && options.atMs !== void 0) throw new CliError("BAD_REQUEST", "--at-ms requires --node-id.", "Render the stable recording node returned by `enhance canvas tree`.");
1462
1548
  const recordingId = options.atMs === void 0 ? null : recordingIdFrom(nodeId);
1463
1549
  if (recordingId === void 0 && options.atMs !== void 0) throw new CliError("BAD_REQUEST", "--at-ms requires a stable recording node id such as rec_<recording-uuid>.", "Run `enhance canvas tree --canvas <url-or-id>` and choose a recording node.");
@@ -1466,8 +1552,7 @@ const executeRender = async (options, input) => {
1466
1552
  capability: fromCapabilityReference(input.catalog(), "canvas.render"),
1467
1553
  arguments: {
1468
1554
  canvasId: parseCanvasReference(options.canvas).canvasId,
1469
- expectedVersion: options.expectedVersion === void 0 ? null : numberFrom(positiveInteger$2, options.expectedVersion, "--expected-version"),
1470
- target: targetFrom(nodeId, boundsFrom(options.bounds)),
1555
+ ...resolved,
1471
1556
  sourceState: recordingId === null || recordingId === void 0 ? null : {
1472
1557
  kind: "recording",
1473
1558
  recordingId,
@@ -1483,11 +1568,19 @@ const executeRender = async (options, input) => {
1483
1568
  input.output.result(result);
1484
1569
  };
1485
1570
  const configureRender = (render, input) => {
1486
- render.option("--canvas <url-or-id>", "Canvas URL or UUID to render.").option("--node-id <id>", "Render one stable canvas node instead of all authored content.").option("--bounds <json>", "Render an explicit rectangle in canvas world coordinates.").option("--expected-version <integer>", "Refuse pixels from any other document version.").option("--at-ms <integer>", "Pause a recording node at this millisecond; inspect the PNG before snapshotting it.").option("--scale <number>", "Output pixels per canvas unit, from 0.1 to 4.", "1").option("--output <path>", "Write the PNG to this path instead of a protected temporary file.").option("--force", "Replace an existing --output file deliberately.", false).option("--timeout-ms <integer>", "Local polling deadline in milliseconds.", "120000").option("--client-token <uuid>", "Stable UUID to reuse only when retrying this render request.").addHelpText("after", "\nFor transcript-led selection, inspect nearby --at-ms renders and reject transitions or duplicate states before running recording snapshot.\n").action(async (options) => executeRender(options, input));
1571
+ render.option("--input <json-or-@path>", "Bounded scoped render request; requires --client-token.").option("--canvas <url-or-id>", "Canvas URL or UUID to render.").option("--node-id <id>", "Render one stable canvas node instead of all authored content.").option("--bounds <json>", "Render an explicit rectangle in canvas world coordinates.").option("--expected-version <integer>", "Refuse pixels from any other document version.").option("--at-ms <integer>", "Pause a recording node at this millisecond; inspect the PNG before snapshotting it.").option("--scale <number>", "Output pixels per canvas unit, from 0.1 to 4.", "1").option("--output <path>", "Write the PNG to this path instead of a protected temporary file.").option("--force", "Replace an existing --output file deliberately.", false).option("--timeout-ms <integer>", "Local polling deadline in milliseconds.", "120000").option("--client-token <uuid>", "Stable UUID to reuse only when retrying this render request.").addHelpText("after", "\nFor transcript-led selection, inspect nearby --at-ms renders and reject transitions or duplicate states before running recording snapshot.\n").action(async (options) => {
1572
+ const bounded = createCanvasRenderInputAdapter(options);
1573
+ if (bounded === null) return executeRender(options, input);
1574
+ input.output.result(await input.invocation.invoke({
1575
+ capability: fromCapabilityReference(input.catalog(), "canvas.render"),
1576
+ ...bounded
1577
+ }));
1578
+ });
1487
1579
  };
1488
1580
  const registerCanvasProgram = (program, input) => {
1489
1581
  const canvas = program.commands.find((command) => command.name() === "canvas");
1490
1582
  if (canvas === void 0) throw new TypeError("the API router did not supply canvas commands");
1583
+ canvas.configureHelp({ subcommandTerm: (command) => command.name() });
1491
1584
  const render = canvas.commands.find((command) => command.name() === "render");
1492
1585
  if (render === void 0) throw new TypeError("the API router did not supply canvas render");
1493
1586
  const composite = createRenderCanvasComposite(input.remote, createRenderFileAdapter(input.configDirectory), input.now, input.output.result);
@@ -1500,32 +1593,730 @@ const registerCanvasProgram = (program, input) => {
1500
1593
  configureRender(render, input);
1501
1594
  };
1502
1595
 
1596
+ //#endregion
1597
+ //#region ../../packages/sdk/dist/capture-files.lib-DmLQGNWF.mjs
1598
+ const CAPTURE_KEY_LENGTH = 160;
1599
+ const CAPTURE_METADATA_LENGTH = 200;
1600
+ const CAPTURE_ISSUE_LENGTH = 500;
1601
+ const CAPTURE_FAILURE_LENGTH = 1e3;
1602
+ const CAPTURE_UPLOAD_BATCH_SIZE = 400;
1603
+ const key = z.string().trim().min(1).max(CAPTURE_KEY_LENGTH);
1604
+ const digest = z.string().regex(/^[a-f0-9]{64}$/u);
1605
+ const dimension = z.number().int().positive();
1606
+ const captureKeySchema = z.strictObject({
1607
+ source: key,
1608
+ journey: key,
1609
+ step: key,
1610
+ variant: key
1611
+ });
1612
+ const captureBlobSchema = z.strictObject({
1613
+ sha256: digest,
1614
+ bytes: z.number().int().positive(),
1615
+ mediaType: z.string().min(1).max(CAPTURE_METADATA_LENGTH)
1616
+ });
1617
+ const captureArtifactSchema = z.strictObject({
1618
+ format: z.literal("enhance-capture"),
1619
+ version: z.literal(1),
1620
+ key: captureKeySchema,
1621
+ label: key,
1622
+ journeyLabel: key,
1623
+ order: z.number().int().nonnegative(),
1624
+ viewport: z.strictObject({
1625
+ width: dimension,
1626
+ height: dimension,
1627
+ deviceScaleFactor: z.number().positive()
1628
+ }),
1629
+ extent: z.enum(["viewport", "full-page"]),
1630
+ source: z.strictObject({
1631
+ format: z.literal("rrweb-screen"),
1632
+ version: z.literal(1),
1633
+ blob: captureBlobSchema
1634
+ }),
1635
+ preview: z.strictObject({
1636
+ blob: captureBlobSchema,
1637
+ width: dimension,
1638
+ height: dimension,
1639
+ pixelRatio: z.number().positive()
1640
+ }),
1641
+ assets: z.array(z.strictObject({
1642
+ url: z.url(),
1643
+ blob: captureBlobSchema
1644
+ })),
1645
+ provenance: z.strictObject({
1646
+ adapter: key,
1647
+ sdkVersion: key,
1648
+ kernelVersion: key,
1649
+ browser: key,
1650
+ capturedAt: z.iso.datetime(),
1651
+ sourceUrl: z.url().optional(),
1652
+ commit: z.string().min(1).max(CAPTURE_METADATA_LENGTH).optional()
1653
+ }),
1654
+ issues: z.array(z.strictObject({
1655
+ code: key,
1656
+ message: z.string().min(1).max(CAPTURE_ISSUE_LENGTH)
1657
+ }))
1658
+ }).superRefine((artifact, ctx) => {
1659
+ if (artifact.preview.width / artifact.preview.pixelRatio !== artifact.viewport.width || artifact.preview.height / artifact.preview.pixelRatio !== artifact.viewport.height) ctx.addIssue({
1660
+ code: "custom",
1661
+ path: ["preview"],
1662
+ message: "The preview and captured CSS extent must match."
1663
+ });
1664
+ if (artifact.source.blob.mediaType !== "application/json") ctx.addIssue({
1665
+ code: "custom",
1666
+ path: [
1667
+ "source",
1668
+ "blob",
1669
+ "mediaType"
1670
+ ],
1671
+ message: "Capture sources must be frozen JSON."
1672
+ });
1673
+ if (artifact.preview.blob.mediaType !== "image/png") ctx.addIssue({
1674
+ code: "custom",
1675
+ path: [
1676
+ "preview",
1677
+ "blob",
1678
+ "mediaType"
1679
+ ],
1680
+ message: "Capture previews must be PNG."
1681
+ });
1682
+ if (new Set(artifact.assets.map((asset) => asset.url)).size !== artifact.assets.length) ctx.addIssue({
1683
+ code: "custom",
1684
+ path: ["assets"],
1685
+ message: "Capture resource URLs must be unique."
1686
+ });
1687
+ });
1688
+ const captureRunDescriptorSchema = z.strictObject({
1689
+ id: z.uuid(),
1690
+ canvasId: z.uuid(),
1691
+ source: key,
1692
+ runKey: key,
1693
+ generation: z.number().int().nonnegative(),
1694
+ participants: z.array(key).min(1),
1695
+ expiresAt: z.iso.datetime(),
1696
+ formatVersion: z.literal(1)
1697
+ });
1698
+ const captureAttemptSchema = z.strictObject({
1699
+ participant: key,
1700
+ testId: key,
1701
+ project: key,
1702
+ retry: z.number().int().nonnegative(),
1703
+ status: z.enum([
1704
+ "passed",
1705
+ "failed",
1706
+ "skipped",
1707
+ "interrupted",
1708
+ "timedOut"
1709
+ ]),
1710
+ captures: z.array(captureArtifactSchema)
1711
+ });
1712
+ const captureManifestSchema = z.strictObject({
1713
+ format: z.literal("enhance-capture-run"),
1714
+ version: z.literal(1),
1715
+ run: captureRunDescriptorSchema,
1716
+ participants: z.array(z.strictObject({
1717
+ id: key,
1718
+ status: z.enum([
1719
+ "passed",
1720
+ "failed",
1721
+ "interrupted"
1722
+ ])
1723
+ })).min(1),
1724
+ attempts: z.array(captureAttemptSchema),
1725
+ ordering: z.enum(["partial", "complete"])
1726
+ });
1727
+ const captureReceiptSchema = z.strictObject({
1728
+ runId: z.uuid(),
1729
+ canvasId: z.uuid(),
1730
+ canvasUrl: z.url(),
1731
+ version: z.number().int().positive(),
1732
+ manifestDigest: digest,
1733
+ frames: z.array(z.strictObject({
1734
+ key: captureKeySchema,
1735
+ frameId: key,
1736
+ captureId: z.uuid()
1737
+ })),
1738
+ issues: z.array(z.strictObject({
1739
+ code: key,
1740
+ message: z.string().max(CAPTURE_ISSUE_LENGTH)
1741
+ }))
1742
+ });
1743
+ const beginCaptureRunInputSchema = z.strictObject({
1744
+ canvasId: z.uuid(),
1745
+ source: key.default("default"),
1746
+ runKey: key,
1747
+ participants: z.array(key).min(1).default(["local"]),
1748
+ formatVersion: z.literal(1).default(1)
1749
+ });
1750
+ const beginCaptureRunOutputSchema = z.strictObject({ run: captureRunDescriptorSchema });
1751
+ z.strictObject({ runId: z.uuid() });
1752
+ const captureRunStateSchema = z.enum([
1753
+ "collecting",
1754
+ "sealed",
1755
+ "converting",
1756
+ "committed",
1757
+ "failed",
1758
+ "cancelled"
1759
+ ]);
1760
+ const getCaptureRunOutputSchema = z.strictObject({
1761
+ run: captureRunDescriptorSchema,
1762
+ state: captureRunStateSchema,
1763
+ receipt: captureReceiptSchema.nullable(),
1764
+ failure: z.strictObject({
1765
+ code: key,
1766
+ message: z.string().max(CAPTURE_FAILURE_LENGTH)
1767
+ }).nullable()
1768
+ });
1769
+ z.strictObject({
1770
+ runId: z.uuid(),
1771
+ blobs: z.array(captureBlobSchema).min(1).max(CAPTURE_UPLOAD_BATCH_SIZE)
1772
+ });
1773
+ const reserveCaptureBlobsOutputSchema = z.strictObject({ uploads: z.array(z.strictObject({
1774
+ sha256: digest,
1775
+ upload: z.strictObject({
1776
+ url: z.url(),
1777
+ headers: z.record(z.string(), z.string()),
1778
+ expiresAt: z.iso.datetime()
1779
+ }).nullable()
1780
+ })).max(CAPTURE_UPLOAD_BATCH_SIZE) });
1781
+ z.strictObject({ manifest: captureManifestSchema });
1782
+ const COMMIT_LENGTH = 200;
1783
+ z.strictObject({
1784
+ canvasId: z.uuid(),
1785
+ frameId: z.string().min(1),
1786
+ captureId: z.uuid()
1787
+ });
1788
+ const preview = z.strictObject({
1789
+ captureId: z.uuid(),
1790
+ capturedAt: z.iso.datetime(),
1791
+ commit: z.string().max(COMMIT_LENGTH).optional(),
1792
+ url: z.string().min(1),
1793
+ width: z.number().positive(),
1794
+ height: z.number().positive(),
1795
+ pixelRatio: z.number().positive()
1796
+ });
1797
+ z.strictObject({
1798
+ frameId: z.string(),
1799
+ before: preview,
1800
+ after: preview
1801
+ });
1802
+ const captureKeyString = (key) => JSON.stringify([
1803
+ key.source,
1804
+ key.journey,
1805
+ key.step,
1806
+ key.variant
1807
+ ]);
1808
+ const compare = (left, right) => left < right ? -1 : left === right ? 0 : 1;
1809
+ const enqueueJsonObject = (item, state) => {
1810
+ const keys = Object.keys(item).toSorted(compare);
1811
+ state.output.push("{");
1812
+ state.pending.push({ text: "}" });
1813
+ for (let index = keys.length - 1; index >= 0; index--) {
1814
+ const key = keys[index];
1815
+ if (key === void 0) continue;
1816
+ state.pending.push({ value: Reflect.get(item, key) }, { text: `${JSON.stringify(key)}:` });
1817
+ if (index > 0) state.pending.push({ text: "," });
1818
+ }
1819
+ };
1820
+ const canAppendJsonValue = (item, state) => {
1821
+ if (item === null || typeof item === "boolean" || typeof item === "string" || typeof item === "number" && Number.isFinite(item)) {
1822
+ state.output.push(JSON.stringify(item));
1823
+ return true;
1824
+ }
1825
+ if (typeof item !== "object" || state.active.has(item)) return false;
1826
+ if (!Array.isArray(item) && Object.getPrototypeOf(item) !== Object.prototype) return false;
1827
+ state.active.add(item);
1828
+ state.pending.push({ leave: item });
1829
+ if (Array.isArray(item)) {
1830
+ state.output.push("[");
1831
+ state.pending.push({ text: "]" });
1832
+ for (let index = item.length - 1; index >= 0; index--) {
1833
+ state.pending.push({ value: item[index] });
1834
+ if (index > 0) state.pending.push({ text: "," });
1835
+ }
1836
+ } else enqueueJsonObject(item, state);
1837
+ return true;
1838
+ };
1839
+ /** Null means a value would be lost or coerced by JSON; it must never be hashed. */
1840
+ const canonicalCaptureJson = (value) => {
1841
+ const state = {
1842
+ pending: [{ value }],
1843
+ active: /* @__PURE__ */ new Set(),
1844
+ output: []
1845
+ };
1846
+ while (state.pending.length > 0) {
1847
+ const task = state.pending.pop();
1848
+ if (task === void 0) break;
1849
+ if ("text" in task) state.output.push(task.text);
1850
+ else if ("leave" in task) state.active.delete(task.leave);
1851
+ else if (!canAppendJsonValue(task.value, state)) return null;
1852
+ }
1853
+ return state.output.join("");
1854
+ };
1855
+ const captureBlobs = (artifacts) => {
1856
+ const blobs = /* @__PURE__ */ new Map();
1857
+ 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
+ }
1872
+ }
1873
+ return unique.toSorted((a, b) => compare(a.sha256, b.sha256));
1874
+ };
1875
+ 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();
1880
+ 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);
1917
+ }
1918
+ return null;
1919
+ };
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;
1925
+ };
1926
+ /** All publishers select whole terminal attempts with the same completeness rules. */
1927
+ const selectedCaptures = (input) => {
1928
+ const parsed = captureManifestSchema.safeParse(input);
1929
+ if (!parsed.success) return "Invalid capture manifest.";
1930
+ 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);
1939
+ };
1940
+ const captureManifestContent = (manifest) => {
1941
+ const serialized = canonicalCaptureJson(manifest);
1942
+ return serialized === null ? null : `enhance-capture-run:v1\0${serialized}`;
1943
+ };
1944
+ const captureError = (code, message, runId) => Object.assign(new Error(message), {
1945
+ code,
1946
+ ...runId !== void 0 && { runId }
1947
+ });
1948
+ const captureBlobDigest = (bytes) => createHash("sha256").update(bytes).digest("hex");
1949
+ const captureManifestDigest = (manifest) => {
1950
+ const canonical = captureManifestContent(manifest);
1951
+ if (canonical === null) throw new Error("A capture manifest must contain only finite JSON values.");
1952
+ return createHash("sha256").update(canonical).digest("hex");
1953
+ };
1954
+ const captureBlobPath = (directory, digest) => {
1955
+ if (!/^[a-f0-9]{64}$/u.test(digest)) throw captureError("artifact", "Invalid capture blob digest.");
1956
+ return path.join(path.resolve(directory), "blobs", digest);
1957
+ };
1958
+ const readCaptureBlob = async (directory, description) => {
1959
+ const path = captureBlobPath(directory, description.sha256);
1960
+ const info = await stat(path);
1961
+ if (!info.isFile() || info.size !== description.bytes) throw captureError("artifact", `Capture blob size does not match ${description.sha256}.`);
1962
+ const bytes = await readFile(path);
1963
+ if (captureBlobDigest(bytes) !== description.sha256) throw captureError("artifact", `Capture blob checksum does not match ${description.sha256}.`);
1964
+ return bytes;
1965
+ };
1966
+ const writeCapturePayload = async (directory, payload) => {
1967
+ const artifact = captureArtifactSchema.parse(payload.artifact);
1968
+ await mkdir(path.join(directory, "blobs"), { recursive: true });
1969
+ let unavailable = 0;
1970
+ for (const blob of payload.blobs) try {
1971
+ if (blob.description.bytes !== blob.bytes.byteLength || captureBlobDigest(blob.bytes) !== blob.description.sha256) throw captureError("artifact", "Capture blob bytes do not match their descriptor.");
1972
+ const path = captureBlobPath(directory, blob.description.sha256);
1973
+ const temporary = `${path}.${globalThis.crypto.randomUUID()}.tmp`;
1974
+ await writeFile(temporary, blob.bytes, {
1975
+ flag: "wx",
1976
+ mode: 384
1977
+ });
1978
+ await rename(temporary, path);
1979
+ } catch {
1980
+ unavailable++;
1981
+ }
1982
+ try {
1983
+ await readCaptureBlob(directory, artifact.source.blob);
1984
+ } catch {
1985
+ await readCaptureBlob(directory, artifact.preview.blob);
1986
+ }
1987
+ if (unavailable > 0) channel("enhance.capture.resources").publish({
1988
+ stage: "local-write",
1989
+ unavailable
1990
+ });
1991
+ return artifact;
1992
+ };
1993
+ const writeCaptureJson = async (path, value) => {
1994
+ const temporary = `${path}.${globalThis.crypto.randomUUID()}.tmp`;
1995
+ await writeFile(temporary, JSON.stringify(value), { mode: 384 });
1996
+ await rename(temporary, path);
1997
+ };
1998
+ const readCaptureManifest = async (path) => {
1999
+ const raw = JSON.parse(await readFile(path, "utf8"));
2000
+ return captureManifestSchema.parse(raw);
2001
+ };
2002
+
2003
+ //#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
+ };
2100
+ const RATE_LIMIT_STATUS = 429;
2101
+ const MILLISECONDS_PER_SECOND = 1e3;
2102
+ const MAX_ERROR_LENGTH = 1e3;
2103
+ const DEFAULT_TIMEOUT_MS = 3e4;
2104
+ const DEFAULT_PUBLICATION_TIMEOUT_MS = 6e5;
2105
+ const NODE_TIMER_MAX_MS = 2147483647;
2106
+ const HTTP_ERRORS = /* @__PURE__ */ new Map([
2107
+ [401, "authorization"],
2108
+ [403, "authorization"],
2109
+ [409, "conflict"],
2110
+ [400, "artifact"]
2111
+ ]);
2112
+ const requestResponse = async (url, options, timeoutMs, retryDeadline) => {
2113
+ 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
+ }
2128
+ } catch {
2129
+ throw captureError("transport", "Enhance did not confirm the request. Resume the same run to recover its result.");
2130
+ }
2131
+ };
2132
+ const responseBody = async (response) => {
2133
+ try {
2134
+ return await response.json();
2135
+ } catch {
2136
+ return null;
2137
+ }
2138
+ };
2139
+ const call = async (url, options, schema, request) => {
2140
+ const { procedure, timeoutMs, publicationTimeoutMs } = request;
2141
+ const response = await requestResponse(url, options, timeoutMs, Date.now() + publicationTimeoutMs);
2142
+ const body = await responseBody(response);
2143
+ if (!response.ok) {
2144
+ const error = typeof body === "object" && body !== null ? Reflect.get(body, "error") : null;
2145
+ const message = typeof error === "object" && error !== null ? Reflect.get(error, "message") : null;
2146
+ throw captureError(HTTP_ERRORS.get(response.status) ?? "transport", typeof message === "string" ? message.slice(0, MAX_ERROR_LENGTH) : `Enhance rejected ${procedure} (HTTP ${String(response.status)}).`);
2147
+ }
2148
+ const result = typeof body === "object" && body !== null ? Reflect.get(body, "result") : null;
2149
+ const data = typeof result === "object" && result !== null ? Reflect.get(result, "data") : void 0;
2150
+ const parsed = schema.safeParse(data);
2151
+ if (!parsed.success) throw captureError("transport", `Enhance returned an incompatible ${procedure} response.`);
2152
+ return parsed.data;
2153
+ };
2154
+ const captureTransport = (options) => {
2155
+ const base = URL.parse(options.apiUrl);
2156
+ 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.");
2157
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
2158
+ const publicationTimeoutMs = options.publicationTimeoutMs ?? DEFAULT_PUBLICATION_TIMEOUT_MS;
2159
+ if (!Number.isSafeInteger(publicationTimeoutMs) || publicationTimeoutMs < 1) throw captureError("configuration", "Enhance publication timeout must be a positive integer in milliseconds.");
2160
+ 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.`);
2161
+ return {
2162
+ timeoutMs,
2163
+ publicationTimeoutMs,
2164
+ request: async (procedure, input, schema, isQuery = false) => {
2165
+ const url = new URL(`${base.pathname.replace(/\/$/u, "")}/trpc/${procedure}`, base.origin);
2166
+ if (isQuery) url.searchParams.set("input", JSON.stringify(input));
2167
+ return call(url, {
2168
+ method: isQuery ? "GET" : "POST",
2169
+ headers: {
2170
+ authorization: `Bearer ${options.token}`,
2171
+ "content-type": "application/json"
2172
+ },
2173
+ ...!isQuery && { body: JSON.stringify(input) },
2174
+ redirect: "error"
2175
+ }, schema, {
2176
+ procedure,
2177
+ timeoutMs,
2178
+ publicationTimeoutMs
2179
+ });
2180
+ }
2181
+ };
2182
+ };
2183
+ const nodeManifest = (descriptor, captured) => {
2184
+ const participant = descriptor.participants[0];
2185
+ if (participant === void 0) throw captureError("configuration", "No capture participant was reserved.");
2186
+ return {
2187
+ format: "enhance-capture-run",
2188
+ version: 1,
2189
+ run: descriptor,
2190
+ ordering: "partial",
2191
+ participants: [{
2192
+ id: participant,
2193
+ status: "passed"
2194
+ }],
2195
+ attempts: [{
2196
+ participant,
2197
+ testId: "node",
2198
+ project: "node",
2199
+ retry: 0,
2200
+ status: "passed",
2201
+ captures: captured
2202
+ }]
2203
+ };
2204
+ };
2205
+ const createRun = (transport, input, directory) => {
2206
+ const descriptor = captureRunDescriptorSchema.parse(input);
2207
+ const artifacts = [];
2208
+ let isClosed = false;
2209
+ return {
2210
+ descriptor,
2211
+ directory,
2212
+ add: async (payload) => {
2213
+ if (isClosed) throw captureError("configuration", "This run no longer accepts captures.");
2214
+ const written = writeCapturePayload(directory, payload);
2215
+ artifacts.push(written);
2216
+ await written;
2217
+ },
2218
+ publish: async () => {
2219
+ isClosed = true;
2220
+ const captured = await Promise.all(artifacts);
2221
+ if (descriptor.participants.length !== 1) throw captureError("configuration", "Multi-participant runs must publish a complete merged manifest.");
2222
+ const manifest = nodeManifest(descriptor, captured);
2223
+ const selected = selectedCaptures(manifest);
2224
+ if (typeof selected === "string") throw captureError("artifact", selected);
2225
+ await mkdir(directory, { recursive: true });
2226
+ await writeCaptureJson(path.join(directory, "manifest.json"), manifest);
2227
+ return publishCaptureManifest(transport, manifest, directory);
2228
+ },
2229
+ cancel: async () => {
2230
+ isClosed = true;
2231
+ return (await transport.request("captureRun.cancel", { runId: descriptor.id }, getCaptureRunOutputSchema)).receipt;
2232
+ }
2233
+ };
2234
+ };
2235
+ const createEnhance = (options) => {
2236
+ const transport = captureTransport(options);
2237
+ const get = async (runId) => transport.request("captureRun.get", { runId }, getCaptureRunOutputSchema, true);
2238
+ 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);
2251
+ },
2252
+ publishManifest: async (path$1) => publishCaptureManifest(transport, await readCaptureManifest(path$1), path.dirname(path$1)),
2253
+ get
2254
+ } };
2255
+ };
2256
+
2257
+ //#endregion
2258
+ //#region src/infrastructure/captures.program.ts
2259
+ const publicationError = (error, manifest) => {
2260
+ const code = error instanceof Error ? Reflect.get(error, "code") : void 0;
2261
+ 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}`);
2262
+ };
2263
+ const registerCapturesProgram = (program, dependencies) => {
2264
+ 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) => {
2265
+ const token = await dependencies.credentials.read();
2266
+ if (token === null) throw new CliError("UNAUTHORIZED", "Capture publication requires an agent token.", "Run enhance auth login, then retry the same manifest.");
2267
+ const enhance = createEnhance({
2268
+ apiUrl: dependencies.apiUrl,
2269
+ token
2270
+ });
2271
+ try {
2272
+ dependencies.output.result(await enhance.captures.publishManifest(manifest));
2273
+ } catch (error) {
2274
+ throw publicationError(error, manifest);
2275
+ }
2276
+ });
2277
+ };
2278
+
1503
2279
  //#endregion
1504
2280
  //#region src/infrastructure/command-summaries.consts.ts
1505
2281
  const COMMAND_SUMMARIES = {
1506
- "canvas.createEditableFrame": "Insert editable primitives beside a source screen.",
1507
- "canvas.create": "Create a canvas and return its id.",
1508
- "canvas.get": "Read one canvas and viewer access.",
2282
+ "canvas chats": "Chat history.",
2283
+ "canvas.createEditableFrame": "Make a screen editable.",
2284
+ "canvas.create": "Create a canvas.",
2285
+ "canvas.get": "Read a canvas and access.",
1509
2286
  "canvas.setAccess": "Change canvas link access.",
1510
2287
  "canvas.markViewed": "Mark a canvas as viewed.",
1511
- "canvas.list": "Find canvases by shelf, title, access, or state.",
2288
+ "canvas.list": "List canvases.",
1512
2289
  "canvas.rename": "Rename a canvas.",
1513
- "canvas.setReviewState": "Change your canvas review state.",
1514
- "canvas.delete": "Move a canvas to its recoverable bin.",
1515
- "canvas.move": "Move a canvas between shelves.",
1516
- "canvas.duplicate": "Copy a canvas into a shelf.",
1517
- "canvas.deletePermanently": "Permanently delete a binned canvas.",
2290
+ "canvas.setReviewState": "Set review state.",
2291
+ "canvas.delete": "Bin a canvas.",
2292
+ "canvas.move": "Move between shelves.",
2293
+ "canvas.duplicate": "Copy a canvas.",
2294
+ "canvas.deletePermanently": "Permanently delete a canvas.",
1518
2295
  "canvas.restore": "Restore a binned canvas.",
1519
- "canvas.inspect": "Read canvas URL, structure, and next steps.",
1520
- "canvas.tree": "List canvas node ids, hierarchy, kinds, and boxes.",
1521
- "canvas.node": "Read one canvas node and its children.",
1522
- "canvas.selection": "Read the person’s current live browser selection.",
1523
- "canvas text-style-library": "Discover and publish text styles.",
2296
+ "canvas.inspect": "Inspect a canvas.",
2297
+ "canvas.tree": "Read the node hierarchy.",
2298
+ "canvas.node": "Read a node and children.",
2299
+ "canvas.selection": "Read the live selection.",
2300
+ "canvas asset": "Manage uploaded assets.",
2301
+ "canvas mutation": "Read mutation receipts.",
2302
+ "canvas apply": "Apply canvas operations.",
2303
+ "canvas find": "Find accessible canvases.",
2304
+ "canvas remove": "Remove scoped subtrees.",
2305
+ "canvas read": "Read linked content.",
2306
+ "canvas update-html": "Update an HTML snapshot.",
2307
+ "canvas publish-prototype": "Publish a static build.",
2308
+ "canvas import-asset": "Import an image or font.",
2309
+ "canvas insert-html": "Insert compiled HTML.",
2310
+ "canvas make-editable": "Convert a captured screen.",
2311
+ "canvas capture": "Capture a recording moment.",
2312
+ "canvas arrange": "Arrange canvas objects.",
2313
+ "canvas duplicate-nodes": "Duplicate node subtrees.",
2314
+ "canvas text-style-library": "Manage text styles.",
1524
2315
  "canvas realtime": "Canvas presence and activity.",
1525
- "canvas document": "Read or replace a canvas document.",
2316
+ "canvas document": "Read or replace documents.",
1526
2317
  "canvas version": "Retained canvas history.",
1527
- "canvas render": "Create and inspect faithful canvas renders.",
1528
- "canvas participants": "List and change canvas participants.",
2318
+ "canvas render": "Render canvas pixels.",
2319
+ "canvas participants": "Manage participants.",
1529
2320
  "canvas invites": "Invite people to a canvas."
1530
2321
  };
1531
2322
 
@@ -1560,7 +2351,8 @@ const createProcessAdapter = () => ({ exit: (code) => {
1560
2351
  //#region src/infrastructure/cli-polish.lib.ts
1561
2352
  const NAMESPACES = {
1562
2353
  "canvas text-style-library": "Find, read, and publish reusable text styles across canvases.",
1563
- canvas: "Canvases: create, find, share, and manage review surfaces.",
2354
+ "canvas chats": "Inspect and manage authorized canvas chat history.",
2355
+ canvas: "Create, find, share and manage canvases.",
1564
2356
  "canvas render": "Render production-faithful canvas pixels after inspecting exact structure and geometry.",
1565
2357
  "canvas version": "Inspect and name retained canvas history.",
1566
2358
  "canvas document": "Read or replace the opaque document stored on a canvas.",
@@ -1871,6 +2663,18 @@ const registerFixtureProgram = (program, composites, output) => {
1871
2663
  registerWorldFixture(fixture, composites.world, output);
1872
2664
  };
1873
2665
 
2666
+ //#endregion
2667
+ //#region src/infrastructure/operation.program.ts
2668
+ const registerOperationProgram = (program, input) => {
2669
+ program.command("operation").description("Read existing domain-owned operation outcomes.").command("status").description("Recover an existing outcome without creating or resuming work.").requiredOption("--input <json-or-@path>", "Operation reference and optional detail offset/limit.").action(async (options) => {
2670
+ input.output.result(await input.invocation.invoke({
2671
+ capability: fromCapabilityReference(input.catalog(), "operation.status"),
2672
+ arguments: createCanvasJsonInputAdapter(options.input, operationStatusInputSchema, "--input"),
2673
+ clientToken: null
2674
+ }));
2675
+ });
2676
+ };
2677
+
1874
2678
  //#endregion
1875
2679
  //#region src/infrastructure/prototype.program.ts
1876
2680
  const finiteNumber = (value) => z.coerce.number().parse(value);
@@ -1880,13 +2684,14 @@ const DEFAULT_POSITION = 48;
1880
2684
  const DEFAULT_WIDTH = 1440;
1881
2685
  const DEFAULT_HEIGHT = 900;
1882
2686
  const registerPrototypeProgram = (program, invocation, catalog, output) => {
1883
- (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) => {
2687
+ (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) => {
1884
2688
  const clientToken = options.clientToken ?? randomUUID();
1885
2689
  output.result(await invocation.invoke({
1886
2690
  capability: fromCapabilityReference(catalog(), "prototype.publish"),
1887
2691
  arguments: {
1888
2692
  canvasId: options.canvasId,
1889
2693
  prototypeId: options.prototypeId ?? null,
2694
+ targetMode: options.prototypeId !== void 0 && options.nodeId === void 0 ? "prototype" : "node",
1890
2695
  nodeId: options.nodeId ?? `proto_${clientToken.replaceAll("-", "")}`,
1891
2696
  title: options.title,
1892
2697
  directory: options.directory,
@@ -1989,8 +2794,7 @@ const descriptionFrom = (meta) => {
1989
2794
  const description = record === null ? void 0 : record["description"];
1990
2795
  return typeof description === "string" && description !== "" ? description : null;
1991
2796
  };
1992
- const cliMetadataFrom = (source) => {
1993
- const procedures = parseRouter({ router: source });
2797
+ const cliMetadataFrom = (procedures) => {
1994
2798
  return {
1995
2799
  descriptions: new Map(procedures.flatMap(([path, info]) => {
1996
2800
  const description = descriptionFrom(info.meta);
@@ -2017,6 +2821,12 @@ const registerUtilityPrograms = (program, input, catalog) => {
2017
2821
  });
2018
2822
  registerAuthProgram(program, createAuthUseCase(input.credentials, input.remote, createOauthLoopbackAdapter(input.remote)), input.output);
2019
2823
  registerCommentProgram(program, invocation, catalog, input.output);
2824
+ registerCapturesProgram(program, input);
2825
+ registerOperationProgram(program, {
2826
+ invocation,
2827
+ catalog,
2828
+ output: input.output
2829
+ });
2020
2830
  registerDoctorProgram(program, {
2021
2831
  version: input.version,
2022
2832
  credentials: input.credentials,
@@ -2051,11 +2861,11 @@ const registerUtilityPrograms = (program, input, catalog) => {
2051
2861
  });
2052
2862
  };
2053
2863
  const createCliProgram = (input) => {
2054
- const source = createRouterShapeAdapter();
2864
+ const procedures = parseRouter({ router: createRouterShapeAdapter() });
2055
2865
  const catalog = createLazyCapabilityCatalog();
2056
- const { descriptions, mutationPaths } = cliMetadataFrom(source);
2866
+ const { descriptions, mutationPaths } = cliMetadataFrom(procedures);
2057
2867
  const cli = createCli({
2058
- router: createRemoteRouterAdapter(source, input.remote),
2868
+ router: createRemoteRouterAdapter(procedures, input.remote),
2059
2869
  name: input.commandName,
2060
2870
  version: input.version,
2061
2871
  description: "Operate Enhance as the authenticated person.",
@@ -2109,6 +2919,7 @@ const isObject = (value) => typeof value === "object" && value !== null && !Arra
2109
2919
  const linesFor = (value) => {
2110
2920
  if (Array.isArray(value)) return value.map((entry) => JSON.stringify(entry));
2111
2921
  if (!isObject(value) || !Array.isArray(value["items"])) return [JSON.stringify(value)];
2922
+ if ("nextCursor" in value) return [JSON.stringify(value)];
2112
2923
  const items = value["items"];
2113
2924
  if (items.length === 0) return [JSON.stringify(value)];
2114
2925
  const isTruncated = value["truncated"] === true;
@@ -2313,22 +3124,25 @@ const createNdjsonLoggerAdapter = (state, configDirectory, commandName = "enhanc
2313
3124
  //#endregion
2314
3125
  //#region src/main.ts
2315
3126
  const main = async () => {
3127
+ const config = readCliEnvironment();
2316
3128
  const state = {
2317
3129
  exitCode: 1,
2318
3130
  pendingParserMessage: null
2319
3131
  };
2320
- const output = createNdjsonLoggerAdapter(state, CLI_CONFIG.configDirectory, CLI_CONFIG.commandName);
2321
- const credentials = createFileCredentialAdapter(CLI_CONFIG.configDirectory);
3132
+ const output = createNdjsonLoggerAdapter(state, config.configDirectory, config.commandName);
3133
+ const credentials = createFileCredentialAdapter(config.configDirectory);
2322
3134
  const mutationKey = createMutationKeyAdapter();
3135
+ const remote = createHttpRemoteAdapter(config.apiUrl, credentials, mutationKey);
2323
3136
  const cli = createCliProgram({
2324
- version: "0.1.22",
3137
+ apiUrl: config.apiUrl,
3138
+ version: "0.1.33",
2325
3139
  credentials,
2326
- remote: createHttpRemoteAdapter(CLI_CONFIG.apiUrl, credentials, mutationKey),
3140
+ remote,
2327
3141
  mutationKey,
2328
3142
  output,
2329
3143
  state,
2330
- configDirectory: CLI_CONFIG.configDirectory,
2331
- commandName: CLI_CONFIG.commandName
3144
+ configDirectory: config.configDirectory,
3145
+ commandName: config.commandName
2332
3146
  });
2333
3147
  try {
2334
3148
  await cli.run();
@@ -2338,7 +3152,10 @@ const main = async () => {
2338
3152
  exitProcess(1);
2339
3153
  }
2340
3154
  };
2341
- main();
3155
+ main().catch((error) => {
3156
+ process.stderr.write(`${error instanceof Error ? error.message : "CLI startup failed."}\n`);
3157
+ process.exitCode = 1;
3158
+ });
2342
3159
 
2343
3160
  //#endregion
2344
3161
  export { };