@enhance-eng/enhance 0.1.14 → 0.1.15

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 { $ as canvasLayoutWithoutCssProperties, A as startRecordingOutputSchema, C as CliError, D as createScreenOutputSchema, E as completeScreenOutputSchema, G as emptyFixtureDocument, J as canvasAgentActivityPhaseSchema, K as withFixtureScreen, O as appendRecordingChunkOutputSchema, Q as canvasNodeStylePatchSchema, S as PartialBatchError, T as appErrorSchema, W as createOrganisationOutputSchema, Y as MAX_CANVAS_OPERATIONS, Z as canvasOperationSchema, _t as canvasSchema, at as canvasWorldBoundsSchema, c as ProcessExitError, d as createCapabilityPolicyAdapter, dt as canvasAdditionalStyleSchema, et as getCanvasDocumentOutputSchema, ft as canvasAuthoredLayoutValueOf, gt as canvasLayoutPriorityDeclarations, ht as canvasLayoutMainAxisOf, i as toFailurePayload, it as RENDER_MIN_SCALE, k as completeRecordingOutputSchema, l as createCapabilityCatalogAdapter, m as PROCEDURE_DESCRIPTIONS, mt as canvasAxisStyleProperties, n as withCommandName, o as toSharedCapabilities, p as OPTION_DESCRIPTIONS, pt as canvasAuthoredStyleDeclarations, q as beginCanvasActivityOutputSchema, r as toExitCode, s as createMcpCapabilityDiscoveryAdapter, t as withCommandInFailure, tt as saveCanvasDocumentOutputSchema, u as createRouterShapeAdapter, ut as canvasReadableSceneDocumentSchema } from "./cli-output-identity.lib-bX6NwZjd.mjs";
3
- import { a as createOauthLoopbackAdapter, c as createWriteHtmlCanvasComposite, d as createRenderCanvasComposite, f as createAuthUseCase, l as createApplyCanvasComposite, n as createHttpRemoteAdapter, o as createCapabilityInvocationAdapter, r as CLI_CONFIG, s as createRenderFileAdapter, t as createMutationKeyAdapter, u as createCanvasActivityComposite } from "./mutation-key.adapter-p1odGHfg.mjs";
2
+ import { $ as createOrganisationOutputSchema, A as parseCanvasReference, At as canvasSchema, D as assertCanvasReferenceOperations, Dt as canvasAxisStyleProperties, E as assertCanvasReferenceNodes, Et as canvasAuthoredStyleDeclarations, F as completeScreenOutputSchema, I as createScreenOutputSchema, L as appendRecordingChunkOutputSchema, M as CliError, O as canvasReferenceNodeIds, Ot as canvasLayoutMainAxisOf, P as appErrorSchema, R as completeRecordingOutputSchema, St as canvasReadableSceneDocumentSchema, T as canvasEditsSchema, Tt as canvasAuthoredLayoutValueOf, _t as canvasWorldBoundsSchema, a as toExitCode, c as toSharedCapabilities, d as createCapabilityCatalogAdapter, dt as saveCanvasDocumentOutputSchema, et as emptyFixtureDocument, f as createRouterShapeAdapter, g as PROCEDURE_DESCRIPTIONS, h as OPTION_DESCRIPTIONS, i as toCanvasAuthoringResult, it as MAX_CANVAS_OPERATIONS, j as PartialBatchError, k as fromCanvasReference, kt as canvasLayoutPriorityDeclarations, l as createMcpCapabilityDiscoveryAdapter, mt as RENDER_MIN_SCALE, n as withCommandName, nt as beginCanvasActivityOutputSchema, o as toFailurePayload, p as createCapabilityPolicyAdapter, rt as canvasAgentActivityPhaseSchema, st as canvasOperationSchema, t as withCommandInFailure, tt as withFixtureScreen, u as ProcessExitError, ut as getCanvasDocumentOutputSchema, z as startRecordingOutputSchema } from "./cli-output-identity.lib-F9-nlguI.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-Bc4p5ff4.mjs";
4
4
  import { t as toCapabilityInventory } from "./capability-inventory.mapper-DyYXyVBJ.mjs";
5
5
  import { t as createFileCredentialAdapter } from "./file-credential.adapter-rI5HpMEo.mjs";
6
6
  import { Command } from "commander";
@@ -345,129 +345,6 @@ const moveInputsSchema = z.array(z.union([
345
345
  const nodeIdsSchema = z.array(z.string().min(1).max(NODE_ID_LENGTH)).min(1).max(MAX_NODE_IDS);
346
346
  const sourceDepthSchema = z.coerce.number().int().min(0).max(MAX_DEPTH);
347
347
 
348
- //#endregion
349
- //#region src/infrastructure/canvas-reference.lib.ts
350
- const canvasIdSchema = z.uuid();
351
- const selectedIdsSchema = z.array(z.string().min(1).max(200)).min(1);
352
- const CANVAS_PATH = /^\/c\/([^/]+)\/?$/u;
353
- const urlFrom = (candidate) => {
354
- try {
355
- return new URL(candidate);
356
- } catch {
357
- return null;
358
- }
359
- };
360
- const parseCanvasReference = (reference) => {
361
- const candidate = reference.trim();
362
- const direct = canvasIdSchema.safeParse(candidate);
363
- if (direct.success) return {
364
- canvasId: direct.data,
365
- nodeIds: []
366
- };
367
- const url = urlFrom(candidate);
368
- if (url !== null && (url.protocol === "http:" || url.protocol === "https:")) {
369
- const id = canvasIdSchema.safeParse(CANVAS_PATH.exec(url.pathname.toLowerCase())?.[1]);
370
- if (id.success) {
371
- const selection = new URLSearchParams(url.hash.slice(1)).getAll("selection");
372
- if (selection.length === 0) return {
373
- canvasId: id.data,
374
- nodeIds: []
375
- };
376
- const parsed = selectedIdsSchema.safeParse(selection);
377
- if (!parsed.success) throw new CliError("BAD_REQUEST", "The link contains an invalid selection.", "Copy the selection link again from the canvas.");
378
- return {
379
- canvasId: id.data,
380
- nodeIds: [...new Set(parsed.data)]
381
- };
382
- }
383
- }
384
- throw new CliError("BAD_REQUEST", "The canvas reference is neither a canvas URL nor a UUID.", "Paste an HTTP(S) URL shaped https://app.example/c/<UUID>, or pass the bare canvas UUID.");
385
- };
386
- const fromCanvasReference = (reference) => {
387
- const parsed = parseCanvasReference(reference);
388
- if (parsed.nodeIds.length > 0) throw new CliError("BAD_REQUEST", `This command cannot discard the link selection: ${parsed.nodeIds.join(", ")}.`, "Inspect the selection with canvas tree and use a targeted edit. Use a canvas URL without a selection only when the request covers the whole canvas.");
389
- return parsed.canvasId;
390
- };
391
- const canvasReferenceNodeIds = (reference, document) => {
392
- const missing = reference.nodeIds.filter((id) => document.nodes[id] === void 0);
393
- if (missing.length > 0) throw new CliError("NOT_FOUND", `The link selection no longer exists: ${missing.join(", ")}.`, "Copy a current selection link; do not substitute other canvas content.");
394
- const selected = new Set(reference.nodeIds);
395
- const descendants = (parentId) => {
396
- for (const [id, relationship] of Object.entries(document.relationships)) {
397
- if (relationship.parentId !== parentId || selected.has(id)) continue;
398
- selected.add(id);
399
- descendants(id);
400
- }
401
- };
402
- for (const id of reference.nodeIds) descendants(id);
403
- return selected;
404
- };
405
- const assertCanvasReferenceNodes = (reference, document, nodeIds) => {
406
- if (reference.nodeIds.length === 0) return;
407
- const scope = canvasReferenceNodeIds(reference, document);
408
- assertNodesInScope(scope, nodeIds);
409
- };
410
- const assertNodesInScope = (scope, nodeIds) => {
411
- const outside = nodeIds.filter((id) => !scope.has(id));
412
- if (outside.length > 0) throw new CliError("BAD_REQUEST", `These nodes are outside the link selection: ${outside.join(", ")}.`, "Limit the edit to the selected nodes and their descendants. Request a wider selection only when the person wants a wider change.");
413
- };
414
- const conversionScope = (operation) => {
415
- if (operation.destination.kind === "adjacent") throw new CliError("BAD_REQUEST", "Adjacent conversion would insert outside the link selection.", "Use insert-children or replace with a selected target.");
416
- return {
417
- required: [operation.destination.targetNodeId],
418
- inserted: Object.keys(operation.nodes)
419
- };
420
- };
421
- const operationScope = (operation, document) => {
422
- switch (operation.op) {
423
- case "insertNode": return {
424
- required: [operation.parentage.parentId],
425
- inserted: [operation.node.id]
426
- };
427
- case "insertText":
428
- case "insertPrototype": return {
429
- required: [operation.parentId, ...operation.afterId === void 0 ? [] : [operation.afterId]],
430
- inserted: [operation.nodeId]
431
- };
432
- case "insertConvertedSubtree": return conversionScope(operation);
433
- case "move":
434
- case "setParentage": {
435
- const parentId = operation.op === "move" ? operation.parentId : operation.parentage.parentId;
436
- return {
437
- required: [operation.nodeId, ...parentId === document.relationships[operation.nodeId]?.parentId ? [] : [parentId]],
438
- inserted: []
439
- };
440
- }
441
- case "setPrototypeDeployment":
442
- case "setText":
443
- case "setBox":
444
- case "setLabel":
445
- case "setContainerKind":
446
- case "setVisibility":
447
- case "setLocked":
448
- case "setConstraints":
449
- case "setStyles":
450
- case "setAppearance":
451
- case "setLayout":
452
- case "setTypography":
453
- case "setAdditionalStyles":
454
- case "setProps":
455
- case "remove": return {
456
- required: [operation.nodeId],
457
- inserted: []
458
- };
459
- }
460
- };
461
- const assertCanvasReferenceOperations = (reference, document, operations) => {
462
- if (reference.nodeIds.length === 0) return;
463
- const scope = new Set(canvasReferenceNodeIds(reference, document));
464
- for (const operation of operations) {
465
- const { required, inserted } = operationScope(operation, document);
466
- assertNodesInScope(scope, [...required, ...inserted.filter((id) => document.nodes[id] !== void 0)]);
467
- for (const id of inserted) scope.add(id);
468
- }
469
- };
470
-
471
348
  //#endregion
472
349
  //#region src/infrastructure/canvas-authoring-command.lib.ts
473
350
  const uuidNullableSchema = z.uuid().nullable();
@@ -483,14 +360,6 @@ const selectAuthoringToken = (input, value, isComposite) => {
483
360
  input.mutationKey.select(parsed.data, isComposite);
484
361
  };
485
362
  const authoringMutationId = (input, purpose) => input.mutationKey.current("canvas.applyOperations", { purpose });
486
- const sceneAtVersion = async (input, canvasId, expectedVersion) => {
487
- const held = getCanvasDocumentOutputSchema.safeParse(await input.remote.query("canvas.document.get", { canvasId }));
488
- if (!held.success) throw new CliError("INTERNAL", "The API returned an invalid canvas document.", "Run `enhance doctor` and report incompatible API and CLI versions.");
489
- if (held.data.version !== expectedVersion) throw new CliError("CONFLICT", `Canvas version ${String(held.data.version)} no longer matches --base-version ${String(expectedVersion)}.`, `Run 'enhance canvas tree --canvas ${canvasId}' and recompute against version ${String(held.data.version)}.`);
490
- const scene = canvasReadableSceneDocumentSchema.safeParse(held.data.document);
491
- if (scene.success) return scene.data;
492
- throw new CliError("INTERNAL", "The stored canvas is not an editable scene.", "Open the canvas in the editor and repair or recreate the invalid document.");
493
- };
494
363
  const applyAuthoringOperations = async (input, options, purpose, operations) => {
495
364
  selectAuthoringToken(input, options.clientToken, false);
496
365
  const reference = parseCanvasReference(options.canvas);
@@ -503,6 +372,17 @@ const applyAuthoringOperations = async (input, options, purpose, operations) =>
503
372
  operations: [...operations]
504
373
  });
505
374
  };
375
+ const applyAuthoringEdits = async (input, options, edits, idPrefix) => {
376
+ selectAuthoringToken(input, options.clientToken, false);
377
+ const reference = parseCanvasReference(options.canvas);
378
+ return createEditCanvasComposite(input.remote).execute({
379
+ ...reference,
380
+ baseVersion: authoringBaseVersion(options.baseVersion),
381
+ mutationId: authoringMutationId(input, "canvas.edit"),
382
+ edits,
383
+ ...idPrefix !== void 0 && { idPrefix }
384
+ });
385
+ };
506
386
 
507
387
  //#endregion
508
388
  //#region src/infrastructure/canvas-operation-input.adapter.ts
@@ -647,108 +527,6 @@ const configureCanvasAuthoringActivity = (canvas, input) => {
647
527
  configureFinish(canvas, input);
648
528
  };
649
529
 
650
- //#endregion
651
- //#region src/application/canvas-style-operations.use-case.ts
652
- const ADDITIONAL_STYLE_ID_LENGTH = 200;
653
- const camelToKebab = (property) => property.startsWith("--") ? property : property.replace(/^Webkit/u, "-webkit-").replace(/^Moz/u, "-moz-").replaceAll(/([a-z\d])([A-Z])/gu, "$1-$2").toLowerCase();
654
- const additionalOperation = (node, styles) => {
655
- const held = new Map((node.additionalStyles?.declarations ?? []).map((declaration) => [declaration.property, declaration]));
656
- for (const [property, value] of Object.entries(styles)) {
657
- if (value === null || canvasNodeStylePatchSchema.safeParse({ [property]: value }).success) {
658
- held.delete(property);
659
- continue;
660
- }
661
- const result = canvasAdditionalStyleSchema.safeParse({
662
- id: held.get(property)?.id ?? `css-${property}`.slice(0, ADDITIONAL_STYLE_ID_LENGTH),
663
- property,
664
- value: String(value),
665
- enabled: true
666
- });
667
- if (!result.success) throw new CliError("BAD_REQUEST", `Style ${property} is not safe CSS.`, "Use a valid CSS property without imports, expressions, or executable URLs.");
668
- held.set(property, result.data);
669
- }
670
- const declarations = [];
671
- for (const declaration of held.values()) {
672
- if (declarations.length === 128) throw new CliError("BAD_REQUEST", "Too many additional CSS declarations.", "Remove unused declarations before adding more; no styles were changed.");
673
- declarations.push(declaration);
674
- }
675
- return JSON.stringify(declarations) === JSON.stringify(node.additionalStyles?.declarations ?? []) ? null : {
676
- op: "setAdditionalStyles",
677
- nodeId: node.id,
678
- additionalStyles: { declarations }
679
- };
680
- };
681
- const layoutOperation = (document, node, next, styles) => {
682
- const changed = new Set(Object.keys(styles));
683
- const properties = (axis) => [...canvasAxisStyleProperties(node, axis, document), ...canvasAxisStyleProperties(next, axis, document)];
684
- const layout = canvasLayoutWithoutCssProperties(node.layout ?? {}, changed, {
685
- horizontal: properties("horizontal"),
686
- vertical: properties("vertical")
687
- });
688
- for (const [property, axis] of [["width", "horizontal"], ["height", "vertical"]]) {
689
- const value = styles[property];
690
- if (value === "fill" || value === "hug") layout[axis] = { mode: value };
691
- }
692
- return JSON.stringify(layout) === JSON.stringify(node.layout ?? {}) ? null : {
693
- op: "setLayout",
694
- nodeId: node.id,
695
- layout: Object.keys(layout).length === 0 ? "default" : layout
696
- };
697
- };
698
- const cssValues = (document, node, styles) => {
699
- const result = { ...styles };
700
- for (const [property, axis] of [["width", "horizontal"], ["height", "vertical"]]) {
701
- if (styles[property] !== "fill" && styles[property] !== "hug") continue;
702
- result[property] = null;
703
- for (const related of canvasAxisStyleProperties(node, axis, document)) if (node.styles[related] !== void 0 || node.additionalStyles?.declarations.some((declaration) => declaration.property === related) === true) result[related] = null;
704
- }
705
- return result;
706
- };
707
- const operationsForNode = (document, node, source) => {
708
- const styles = cssValues(document, node, source);
709
- const additional = additionalOperation(node, styles);
710
- const stylePatch = Object.fromEntries(Object.entries(styles).filter(([property, value]) => canvasNodeStylePatchSchema.safeParse({ [property]: value }).success));
711
- const next = {
712
- ...node,
713
- styles: { ...node.styles },
714
- ...additional !== null && additional.additionalStyles !== "default" && { additionalStyles: additional.additionalStyles }
715
- };
716
- for (const [property, value] of Object.entries(stylePatch)) if (value === null) Reflect.deleteProperty(next.styles, property);
717
- else next.styles[property] = value;
718
- const layout = layoutOperation(document, node, next, source);
719
- return [
720
- ...Object.keys(stylePatch).length > 0 ? [{
721
- op: "setStyles",
722
- nodeId: node.id,
723
- styles: canvasNodeStylePatchSchema.parse(stylePatch)
724
- }] : [],
725
- ...layout === null ? [] : [layout],
726
- ...additional === null ? [] : [additional]
727
- ];
728
- };
729
- const mergedUpdates = (updates) => {
730
- const merged = /* @__PURE__ */ new Map();
731
- for (const update of updates) for (const nodeId of update.nodeIds) {
732
- const styles = merged.get(nodeId) ?? {};
733
- for (const [property, value] of Object.entries(update.styles)) {
734
- const normalized = camelToKebab(property);
735
- Reflect.deleteProperty(styles, normalized);
736
- styles[normalized] = value;
737
- }
738
- merged.set(nodeId, styles);
739
- }
740
- return merged;
741
- };
742
- const canvasStyleOperations = (document, updates) => {
743
- const operations = [...mergedUpdates(updates)].flatMap(([nodeId, styles]) => {
744
- const node = document.nodes[nodeId];
745
- if (node === void 0) throw new CliError("NOT_FOUND", `Canvas node ${nodeId} does not exist.`, "Run canvas tree and use current stable node ids.");
746
- return operationsForNode(document, node, styles);
747
- });
748
- if (operations.length === 0) throw new CliError("BAD_REQUEST", "No style changes were provided.", "Pass at least one changed CSS property.");
749
- return operations;
750
- };
751
-
752
530
  //#endregion
753
531
  //#region src/infrastructure/canvas-authoring-bounded-input.lib.ts
754
532
  const boundedCanvasAuthoringInput = (value, bytes, option) => {
@@ -788,22 +566,21 @@ const createCanvasJsonInputAdapter = (value, schema, option) => {
788
566
  const configureText = (canvas, input) => {
789
567
  canvas.command("set-text-content").description("Set Text node values.").requiredOption("--canvas <url-or-id>", "Canvas URL or UUID to edit.").requiredOption("--base-version <integer>", "Exact current canvas version.").requiredOption("--updates <json-or-@path>", "Array of {nodeId,textContent} updates.").option("--client-token <uuid>", "Stable UUID for retrying this exact batch.").action(async (options) => {
790
568
  const operations = createCanvasJsonInputAdapter(options.updates, textUpdatesSchema, "--updates").map((update) => ({
791
- op: "setText",
569
+ kind: "set_text",
792
570
  nodeId: update.nodeId,
793
571
  text: update.textContent
794
572
  }));
795
- input.output.result(await applyAuthoringOperations(input, options, "set-text-content", operations));
573
+ input.output.result(await applyAuthoringEdits(input, options, operations));
796
574
  });
797
575
  };
798
576
  const configureRename = (canvas, input) => {
799
577
  canvas.command("rename-nodes").description("Rename layers.").requiredOption("--canvas <url-or-id>", "Canvas URL or UUID to edit.").requiredOption("--base-version <integer>", "Exact current canvas version.").requiredOption("--updates <json-or-@path>", "Array of {nodeId,name} updates.").option("--client-token <uuid>", "Stable UUID for retrying this exact batch.").action(async (options) => {
800
578
  const operations = createCanvasJsonInputAdapter(options.updates, renameUpdatesSchema, "--updates").map((update) => ({
801
- op: "setLabel",
579
+ kind: "rename",
802
580
  nodeId: update.nodeId,
803
- label: update.name,
804
- labelOrigin: "user"
581
+ name: update.name
805
582
  }));
806
- input.output.result(await applyAuthoringOperations(input, options, "rename-nodes", operations));
583
+ input.output.result(await applyAuthoringEdits(input, options, operations));
807
584
  });
808
585
  };
809
586
  const configureDelete = (canvas, input) => {
@@ -817,13 +594,30 @@ const configureDelete = (canvas, input) => {
817
594
  };
818
595
  const configureStyles = (canvas, input) => {
819
596
  canvas.command("update-styles").description("Update visual and layout styles.").requiredOption("--canvas <url-or-id>", "Canvas URL or UUID to edit.").requiredOption("--base-version <integer>", "Exact current canvas version.").requiredOption("--updates <json-or-@path>", "Array of {nodeIds,styles} updates.").option("--client-token <uuid>", "Stable UUID for retrying this exact batch.").action(async (options) => {
820
- const canvasId = parseCanvasReference(options.canvas).canvasId;
821
- const scene = await sceneAtVersion(input, canvasId, authoringBaseVersion(options.baseVersion));
822
597
  const updates = createCanvasJsonInputAdapter(options.updates, styleUpdatesSchema, "--updates");
823
- input.output.result(await applyAuthoringOperations(input, options, "update-styles", canvasStyleOperations(scene, updates)));
598
+ input.output.result(await applyAuthoringEdits(input, options, updates.map((update) => ({
599
+ kind: "set_styles",
600
+ ...update
601
+ }))));
602
+ });
603
+ };
604
+ const configureBatch = (canvas, input) => {
605
+ canvas.command("edit").description("Apply an atomic canvas edit batch.").requiredOption("--canvas <url-or-id>", "Canvas or selection URL, or canvas UUID.").requiredOption("--base-version <integer>", "Canvas version to edit; use the previous write result to continue.").requiredOption("--edits <json-or-@path>", "Array of edits with kind set_text, set_styles, rename, duplicate or move.").option("--client-token <uuid>", "Stable UUID for retrying this exact batch.").addHelpText("after", `
606
+ Edit shapes (combine related edits in one array):
607
+ {"kind":"set_text","nodeId":"title","text":"Your day"}
608
+ {"kind":"set_styles","nodeIds":["button"],"styles":{"background":"#0f766e"}}
609
+ {"kind":"rename","nodeId":"card","name":"Task"}
610
+ {"kind":"duplicate","nodeIds":["card"],"parentId":"screen"}
611
+ {"kind":"move","nodeId":"card","destination":{"kind":"before","nodeId":"other"}}
612
+ Move destinations also accept {"kind":"after","nodeId":"other"} or {"kind":"parent","parentId":"screen","index":0}.
613
+ Use input-version IDs. Duplicate mappings are returned for a subsequent call.
614
+ `).action(async (options) => {
615
+ const edits = createCanvasJsonInputAdapter(options.edits, canvasEditsSchema, "--edits");
616
+ input.output.result(await applyAuthoringEdits(input, options, edits));
824
617
  });
825
618
  };
826
619
  const configureCanvasAuthoringEdits = (canvas, input) => {
620
+ configureBatch(canvas, input);
827
621
  configureText(canvas, input);
828
622
  configureRename(canvas, input);
829
623
  configureDelete(canvas, input);
@@ -1152,30 +946,28 @@ const canvasComputedStyleRecords = (document, nodeIds) => nodeIds.map((nodeId) =
1152
946
  const GUIDE = {
1153
947
  topic: "canvas-agent-authoring",
1154
948
  workflow: [
1155
- "Run canvas inspect, then canvas tree, before editing. Keep a pasted selection link intact as --canvas on every read and edit; it limits the request to those nodes and their descendants.",
1156
- "Render the target before changing it and inspect the PNG.",
1157
- "Write small visual groups incrementally with write-html.",
1158
- "Use duplicate-nodes, set-text-content, update-styles, and move-nodes instead of rewriting existing structure.",
1159
- "Use flex, padding, and gap as the primary layout tools. Avoid margin, grid, tables, and inline layout.",
1160
- "Every write requires the exact version returned by the latest read.",
1161
- "Inspect the review PNG returned by write-html and correct visual discrepancies.",
1162
- "Automatic commands show and clear their work indicator. Finish a manual work lease explicitly."
949
+ "Keep the complete selection link as --canvas; only selected nodes and descendants are in scope.",
950
+ "Unknown state: canvas inspect. When nodeCount=0, use target root and its version to create a populated screen using write-html --review none. No blank pre-render or empty shell.",
951
+ "Existing content: read only missing subtree structure or ids. Reuse useful context and product styles.",
952
+ "Batch related text, style, rename, duplicate and move changes with canvas edit --edits. Existing focused commands also work.",
953
+ "Use the version from the latest successful read or write as --base-version. After a conflict, reread and recompute the requested edit.",
954
+ "Render the affected screen when ready for review and inspect the PNG. Repeat after changes or a concrete discrepancy."
1163
955
  ],
1164
956
  html: {
1165
957
  modes: ["insert-children", "replace"],
1166
958
  rules: [
1167
- "Use inline styles and concrete CSS values.",
1168
- "Use layer-name for meaningful hierarchy names.",
1169
- "One call should add roughly one visual group.",
1170
- "Styled text controls become a frame plus an editable text child.",
1171
- "Scripts, event handlers, embedded documents, executable URLs, and CSS imports are rejected."
959
+ "Use inline concrete CSS; flex, padding and gap. Avoid margin, grid, tables and inline layout.",
960
+ "Give screen rows, cards and buttons explicit dimensions; avoid relying on implicit stretch. Use block frames for colored badges.",
961
+ "Name meaningful groups with layer-name; include content and structure together.",
962
+ "Styled text controls become frames with editable text children.",
963
+ "Scripts, event handlers, embedded documents, executable URLs and CSS imports are rejected."
1172
964
  ]
1173
965
  },
1174
966
  completion: [
1175
- "The hierarchy is natural and uses the fewest useful editable primitives.",
1176
- "The affected version and node ids match the intended change.",
1177
- "The post-write PNG has been inspected.",
1178
- "Text, layout, paint, effects, and additional CSS remain editable in the ordinary inspector."
967
+ "Natural hierarchy with the fewest useful editable primitives.",
968
+ "The committed version and affected ids match the request.",
969
+ "Inspect the final PNG for hierarchy, alignment, clipping and overflow.",
970
+ "Keep text, layout and appearance editable in the ordinary inspector."
1179
971
  ]
1180
972
  };
1181
973
  const canvasScene = async (input, canvasId) => {
@@ -1217,243 +1009,45 @@ const configureCanvasAuthoringSource = (canvas, input) => {
1217
1009
  });
1218
1010
  };
1219
1011
 
1220
- //#endregion
1221
- //#region src/application/canvas-structure-document.use-case.ts
1222
- const ROOT_CANVAS_NODE_ID = "root";
1223
- const canvasChildIds = (document, parentId) => Object.entries(document.relationships).filter(([, relationship]) => relationship.parentId === parentId).toSorted(([leftId, left], [rightId, right]) => left.sortKey === right.sortKey ? leftId.localeCompare(rightId) : left.sortKey.localeCompare(right.sortKey)).map(([nodeId]) => nodeId);
1224
- const canCanvasNodeContainChildren = (node) => node !== void 0 && [
1225
- "root",
1226
- "frame",
1227
- "group"
1228
- ].includes(node.component);
1229
- const requireCanvasNode = (document, nodeId) => {
1230
- const node = document.nodes[nodeId];
1231
- if (node !== void 0) return node;
1232
- throw new CliError("NOT_FOUND", `Canvas node ${nodeId} does not exist.`, "Run canvas tree and use a current stable node id.");
1233
- };
1234
- const canvasDescendantIds = (document, nodeId) => {
1235
- const found = /* @__PURE__ */ new Set();
1236
- const visit = (parentId) => {
1237
- for (const childId of canvasChildIds(document, parentId)) {
1238
- found.add(childId);
1239
- visit(childId);
1240
- }
1241
- };
1242
- visit(nodeId);
1243
- return found;
1244
- };
1245
-
1246
- //#endregion
1247
- //#region src/application/canvas-duplicate-operations.use-case.ts
1248
- const SLUG_LENGTH = 60;
1249
- const ID_LENGTH = 200;
1250
- const ID_SEQUENCE_LENGTH = 4;
1251
- const SORT_KEY_LENGTH = 500;
1252
- const FALLBACK_SORT_SEQUENCE_LENGTH = 6;
1253
- const slug = (source) => {
1254
- const held = source.normalize("NFKD").toLowerCase().replaceAll(/[^a-z0-9_-]+/gu, "-").replaceAll(/^-+|-+$/gu, "").slice(0, SLUG_LENGTH);
1255
- return held === "" ? "copy" : held;
1256
- };
1257
- const createDuplicateId = (prefix) => {
1258
- let sequence = 0;
1259
- return (label) => {
1260
- sequence += 1;
1261
- return `${slug(prefix)}_${slug(label)}_${String(sequence).padStart(ID_SEQUENCE_LENGTH, "0")}`.slice(0, ID_LENGTH);
1262
- };
1263
- };
1264
- const subtreeIds = (document, rootId) => {
1265
- const ordered = [];
1266
- const visit = (nodeId) => {
1267
- ordered.push(nodeId);
1268
- for (const childId of canvasChildIds(document, nodeId)) visit(childId);
1269
- };
1270
- visit(rootId);
1271
- return ordered;
1272
- };
1273
- const duplicateMap = (document, rootId, nextId) => Object.fromEntries(subtreeIds(document, rootId).map((nodeId) => [nodeId, nextId(requireCanvasNode(document, nodeId).label)]));
1274
- const duplicateInsertOperation = (context, oldId) => {
1275
- const { document, rootId, parentId, inputIndex, sourceSortKey, map } = context;
1276
- const node = requireCanvasNode(document, oldId);
1277
- const newId = map[oldId];
1278
- if (newId === void 0) throw new Error(`Missing duplicate id for ${oldId}`);
1279
- const oldParentage = document.relationships[oldId];
1280
- const isRoot = oldId === rootId;
1281
- const clonedParentId = isRoot ? parentId : map[oldParentage?.parentId ?? ""];
1282
- if (clonedParentId === void 0) throw new Error(`Missing duplicate parent for ${oldId}`);
1283
- const fallbackSort = `agent:${String(inputIndex + 1).padStart(FALLBACK_SORT_SEQUENCE_LENGTH, "0")}`;
1284
- return {
1285
- op: "insertNode",
1286
- node: {
1287
- ...structuredClone(node),
1288
- id: newId
1289
- },
1290
- parentage: {
1291
- parentId: clonedParentId,
1292
- sortKey: isRoot ? `${sourceSortKey}~agent-copy-${String(inputIndex + 1).padStart(ID_SEQUENCE_LENGTH, "0")}`.slice(0, SORT_KEY_LENGTH) : oldParentage?.sortKey ?? fallbackSort
1293
- }
1294
- };
1295
- };
1296
- const duplicateOne = (context) => {
1297
- const { document, input, inputIndex, nextId } = context;
1298
- const source = requireCanvasNode(document, input.id);
1299
- if (input.id === "root") throw new CliError("BAD_REQUEST", "The canvas root cannot be duplicated.", "Duplicate one or more root children instead.");
1300
- const sourceParentage = document.relationships[input.id];
1301
- if (sourceParentage === void 0) throw new CliError("BAD_REQUEST", `Canvas node ${input.id} is detached.`, "Choose a reachable node from canvas tree.");
1302
- const parentId = input.parentId ?? sourceParentage.parentId;
1303
- if (!canCanvasNodeContainChildren(document.nodes[parentId])) throw new CliError("BAD_REQUEST", `Canvas node ${parentId} cannot contain duplicates.`, "Choose a frame, group, or root as the destination.");
1304
- const map = duplicateMap(document, input.id, nextId);
1305
- const treeContext = {
1306
- document,
1307
- rootId: input.id,
1308
- parentId,
1309
- inputIndex,
1310
- sourceSortKey: sourceParentage.sortKey,
1311
- map
1312
- };
1313
- const operations = subtreeIds(document, input.id).map((oldId) => duplicateInsertOperation(treeContext, oldId));
1314
- const newId = map[input.id];
1315
- if (newId === void 0) throw new Error(`Missing duplicate root id for ${input.id}`);
1316
- return {
1317
- operations,
1318
- summary: {
1319
- sourceId: input.id,
1320
- newId,
1321
- name: source.label,
1322
- component: source.component,
1323
- descendantIdMap: Object.fromEntries(Object.entries(map).filter(([oldId]) => oldId !== input.id))
1324
- }
1325
- };
1326
- };
1327
- const duplicateCanvasNodeOperations = (document, inputs, idPrefix) => {
1328
- if (inputs.length === 0) throw new CliError("BAD_REQUEST", "No nodes were provided to duplicate.", "Pass at least one stable node id.");
1329
- const nextId = createDuplicateId(idPrefix);
1330
- const duplicates = inputs.map((input, inputIndex) => duplicateOne({
1331
- document,
1332
- input,
1333
- inputIndex,
1334
- nextId
1335
- }));
1336
- return {
1337
- operations: duplicates.flatMap((duplicate) => duplicate.operations),
1338
- duplicatedNodes: duplicates.map((duplicate) => duplicate.summary)
1339
- };
1340
- };
1341
-
1342
- //#endregion
1343
- //#region src/application/canvas-move-operations.use-case.ts
1344
- const moveState = (document) => ({
1345
- document,
1346
- children: new Map(Object.keys(document.nodes).map((nodeId) => [nodeId, canvasChildIds(document, nodeId)])),
1347
- parentOf: new Map(Object.entries(document.relationships).map(([nodeId, relationship]) => [nodeId, relationship.parentId])),
1348
- affected: /* @__PURE__ */ new Set()
1349
- });
1350
- const directDestination = (input, state) => {
1351
- const destination = (state.children.get(input.parentId) ?? []).filter((nodeId) => nodeId !== input.nodeId);
1352
- return {
1353
- parentId: input.parentId,
1354
- index: Math.max(0, Math.min(input.index ?? destination.length, destination.length))
1355
- };
1356
- };
1357
- const siblingDestination = (input, state) => {
1358
- const siblingId = "before" in input ? input.before : input.after;
1359
- if (siblingId === input.nodeId || state.document.nodes[siblingId] === void 0) throw new CliError("BAD_REQUEST", `Sibling ${siblingId} is not a valid move target.`, "Choose another current sibling node.");
1360
- const parentId = state.parentOf.get(siblingId);
1361
- if (parentId === void 0) throw new CliError("BAD_REQUEST", `Sibling ${siblingId} is detached.`, "Choose a reachable sibling from canvas tree.");
1362
- const siblingIndex = (state.children.get(parentId) ?? []).filter((nodeId) => nodeId !== input.nodeId).indexOf(siblingId);
1363
- return {
1364
- parentId,
1365
- index: "before" in input ? siblingIndex : siblingIndex + 1
1366
- };
1367
- };
1368
- const destinationFor = (input, state) => "parentId" in input ? directDestination(input, state) : siblingDestination(input, state);
1369
- const validateMove = (input, destination, state) => {
1370
- if (input.nodeId === "root" || state.document.nodes[input.nodeId] === void 0) throw new CliError("BAD_REQUEST", `Canvas node ${input.nodeId} cannot be moved.`, "Choose a current non-root node.");
1371
- if (canvasDescendantIds(state.document, input.nodeId).has(destination.parentId) || !canCanvasNodeContainChildren(state.document.nodes[destination.parentId])) throw new CliError("BAD_REQUEST", `Canvas node ${destination.parentId} is not a valid parent for ${input.nodeId}.`, "Choose a frame, group, or root outside the moving subtree.");
1372
- };
1373
- const applyMove = (input, destination, state) => {
1374
- const oldParentId = state.parentOf.get(input.nodeId);
1375
- if (oldParentId !== void 0) {
1376
- state.children.set(oldParentId, (state.children.get(oldParentId) ?? []).filter((nodeId) => nodeId !== input.nodeId));
1377
- state.affected.add(oldParentId);
1378
- }
1379
- const children = [...state.children.get(destination.parentId) ?? []];
1380
- children.splice(destination.index, 0, input.nodeId);
1381
- state.children.set(destination.parentId, children);
1382
- state.parentOf.set(input.nodeId, destination.parentId);
1383
- state.affected.add(destination.parentId);
1384
- const afterId = children[destination.index - 1];
1385
- return {
1386
- op: "move",
1387
- nodeId: input.nodeId,
1388
- parentId: destination.parentId,
1389
- ...afterId !== void 0 && { afterId }
1390
- };
1391
- };
1392
- const moveCanvasNodeOperations = (document, inputs) => {
1393
- if (inputs.length === 0) throw new CliError("BAD_REQUEST", "No moves were provided.", "Pass at least one move operation.");
1394
- const state = moveState(document);
1395
- const moves = [];
1396
- return {
1397
- operations: inputs.map((input) => {
1398
- const destination = destinationFor(input, state);
1399
- validateMove(input, destination, state);
1400
- moves.push({
1401
- nodeId: input.nodeId,
1402
- ...destination
1403
- });
1404
- return applyMove(input, destination, state);
1405
- }),
1406
- moves,
1407
- affectedParents: Array.from(state.affected, (parentId) => ({
1408
- parentId,
1409
- children: [...state.children.get(parentId) ?? []]
1410
- }))
1411
- };
1412
- };
1413
-
1414
1012
  //#endregion
1415
1013
  //#region src/infrastructure/canvas-authoring-structure.program.ts
1416
1014
  const configureDuplicate = (canvas, input) => {
1417
1015
  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) => {
1418
- selectAuthoringToken(input, options.clientToken, false);
1419
- const reference = parseCanvasReference(options.canvas);
1420
- const canvasId = reference.canvasId;
1421
- const baseVersion = authoringBaseVersion(options.baseVersion);
1422
- const scene = await sceneAtVersion(input, canvasId, baseVersion);
1423
- const mutationId = authoringMutationId(input, "duplicate-nodes");
1424
- const nodes = createCanvasJsonInputAdapter(options.nodes, duplicateInputsSchema, "--nodes");
1425
- assertCanvasReferenceNodes(reference, scene, nodes.flatMap((node) => [node.id, ...node.parentId === void 0 || node.parentId === scene.relationships[node.id]?.parentId ? [] : [node.parentId]]));
1426
- const plan = duplicateCanvasNodeOperations(scene, nodes, options.idPrefix ?? `copy_${mutationId.replaceAll("-", "")}`);
1427
- const apply = await createApplyCanvasComposite(input.remote).execute({
1428
- canvasId,
1429
- mutationId,
1430
- baseVersion,
1431
- operations: [...plan.operations]
1432
- });
1016
+ const result = await applyAuthoringEdits(input, options, createCanvasJsonInputAdapter(options.nodes, duplicateInputsSchema, "--nodes").map((node) => ({
1017
+ kind: "duplicate",
1018
+ nodeIds: [node.id],
1019
+ ...node.parentId !== void 0 && { parentId: node.parentId }
1020
+ })), options.idPrefix);
1021
+ const { duplicatedNodes, ...apply } = result;
1433
1022
  input.output.result({
1434
- duplicatedNodes: plan.duplicatedNodes,
1023
+ ...result,
1024
+ duplicatedNodes,
1435
1025
  apply
1436
1026
  });
1437
1027
  });
1438
1028
  };
1439
1029
  const configureMove = (canvas, input) => {
1440
1030
  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) => {
1441
- selectAuthoringToken(input, options.clientToken, false);
1442
- const reference = parseCanvasReference(options.canvas);
1443
- const canvasId = reference.canvasId;
1444
- const baseVersion = authoringBaseVersion(options.baseVersion);
1445
- const scene = await sceneAtVersion(input, canvasId, baseVersion);
1446
- const plan = moveCanvasNodeOperations(scene, createCanvasJsonInputAdapter(options.moves, moveInputsSchema, "--moves"));
1447
- assertCanvasReferenceOperations(reference, scene, plan.operations);
1448
- const apply = await createApplyCanvasComposite(input.remote).execute({
1449
- canvasId,
1450
- mutationId: authoringMutationId(input, "move-nodes"),
1451
- baseVersion,
1452
- operations: [...plan.operations]
1453
- });
1031
+ const result = await applyAuthoringEdits(input, options, createCanvasJsonInputAdapter(options.moves, moveInputsSchema, "--moves").map((move) => ({
1032
+ kind: "move",
1033
+ nodeId: move.nodeId,
1034
+ destination: "before" in move ? {
1035
+ kind: "before",
1036
+ nodeId: move.before
1037
+ } : "after" in move ? {
1038
+ kind: "after",
1039
+ nodeId: move.after
1040
+ } : {
1041
+ kind: "parent",
1042
+ parentId: move.parentId,
1043
+ ...move.index !== void 0 && { index: move.index }
1044
+ }
1045
+ })));
1046
+ const { moves: appliedMoves, affectedParents, ...apply } = result;
1454
1047
  input.output.result({
1455
- moves: plan.moves,
1456
- affectedParents: plan.affectedParents,
1048
+ ...result,
1049
+ moves: appliedMoves,
1050
+ affectedParents,
1457
1051
  apply
1458
1052
  });
1459
1053
  });
@@ -1484,31 +1078,34 @@ const UNITLESS_CSS_PROPERTIES = /* @__PURE__ */ new Set([
1484
1078
  "order",
1485
1079
  "z-index"
1486
1080
  ]);
1081
+ const writeHtml = async (input, options) => {
1082
+ if (!["insert-children", "replace"].includes(options.mode)) throw new CliError("BAD_REQUEST", "--mode must be insert-children or replace.", "Choose one of the two documented modes.");
1083
+ if (!["none", "render"].includes(options.review)) throw new CliError("BAD_REQUEST", "--review must be none or render.", "Choose one of the documented review modes.");
1084
+ selectAuthoringToken(input, options.clientToken, true);
1085
+ const mode = options.mode === "replace" ? "replace" : "insert-children";
1086
+ const reference = parseCanvasReference(options.canvas);
1087
+ const baseVersion = authoringBaseVersion(options.baseVersion);
1088
+ input.output.result(await input.invocation.invoke({
1089
+ capability: fromCapabilityReference(input.catalog(), "canvas.writeHtml"),
1090
+ arguments: {
1091
+ canvasId: reference.canvasId,
1092
+ ...reference.nodeIds.length > 0 && { selectionNodeIds: [...reference.nodeIds] },
1093
+ targetNodeId: options.targetNodeId,
1094
+ mode,
1095
+ html: createCanvasHtmlInputAdapter(options.html),
1096
+ ...options.idPrefix !== void 0 && { idPrefix: options.idPrefix },
1097
+ baseVersion,
1098
+ review: options.review,
1099
+ renderOutputPath: options.output ?? null,
1100
+ overwriteRender: options.force === true,
1101
+ renderScale: authoringNumberFrom(renderScaleSchema, options.scale, "--scale"),
1102
+ renderTimeoutMs: authoringNumberFrom(positiveIntegerSchema, options.timeoutMs, "--timeout-ms")
1103
+ },
1104
+ clientToken: options.clientToken ?? null
1105
+ }));
1106
+ };
1487
1107
  const configureWriteHtml = (canvas, input) => {
1488
- canvas.command("write-html").description("Compile HTML/CSS primitives.").requiredOption("--canvas <url-or-id>", "Canvas URL or UUID to edit.").requiredOption("--base-version <integer>", "Exact current canvas version.").requiredOption("--target-node-id <id>", "Container receiving children, or node to replace.").requiredOption("--html <html-or-@path>", "Inline HTML fragment or @path to a UTF-8 file.").option("--mode <mode>", "insert-children or replace.", "insert-children").option("--id-prefix <prefix>", "Stable namespace for generated node ids.").option("--client-token <uuid>", "Stable UUID for retrying this exact write and review.").option("--output <path>", "Write the review PNG to this path.").option("--force", "Replace an existing --output file deliberately.", false).option("--scale <number>", "Review pixels per canvas unit, from 0.1 to 4.", "1").option("--timeout-ms <integer>", "Review render polling deadline.", "120000").addHelpText("after", "\nWrite one visual group at a time. Use flex, padding and gap; use targeted commands for later edits. Inspect the returned PNG.\n").action(async (options) => {
1489
- if (!["insert-children", "replace"].includes(options.mode)) throw new CliError("BAD_REQUEST", "--mode must be insert-children or replace.", "Choose one of the two documented modes.");
1490
- selectAuthoringToken(input, options.clientToken, true);
1491
- const mode = options.mode === "replace" ? "replace" : "insert-children";
1492
- const reference = parseCanvasReference(options.canvas);
1493
- const baseVersion = authoringBaseVersion(options.baseVersion);
1494
- if (reference.nodeIds.length > 0) assertCanvasReferenceNodes(reference, await sceneAtVersion(input, reference.canvasId, baseVersion), [options.targetNodeId]);
1495
- input.output.result(await input.invocation.invoke({
1496
- capability: fromCapabilityReference(input.catalog(), "canvas.writeHtml"),
1497
- arguments: {
1498
- canvasId: reference.canvasId,
1499
- targetNodeId: options.targetNodeId,
1500
- mode,
1501
- html: createCanvasHtmlInputAdapter(options.html),
1502
- ...options.idPrefix !== void 0 && { idPrefix: options.idPrefix },
1503
- baseVersion,
1504
- renderOutputPath: options.output ?? null,
1505
- overwriteRender: options.force === true,
1506
- renderScale: authoringNumberFrom(renderScaleSchema, options.scale, "--scale"),
1507
- renderTimeoutMs: authoringNumberFrom(positiveIntegerSchema, options.timeoutMs, "--timeout-ms")
1508
- },
1509
- clientToken: options.clientToken ?? null
1510
- }));
1511
- });
1108
+ canvas.command("write-html").description("Compile HTML/CSS primitives.").requiredOption("--canvas <url-or-id>", "Canvas URL or UUID to edit.").requiredOption("--base-version <integer>", "Exact current canvas version.").requiredOption("--target-node-id <id>", "Container receiving children, or node to replace.").requiredOption("--html <html-or-@path>", "Inline HTML fragment or @path to a UTF-8 file.").option("--mode <mode>", "insert-children or replace.", "insert-children").option("--review <mode>", "none to return after commitment; render to include review pixels.", "render").option("--id-prefix <prefix>", "Fresh namespace for a new import/replacement; reuse only for an identical retry.").option("--client-token <uuid>", "Stable UUID for retrying this exact write and review.").option("--output <path>", "Write the review PNG to this path.").option("--force", "Replace an existing --output file deliberately.", false).option("--scale <number>", "Review pixels per canvas unit, from 0.1 to 4.", "1").option("--timeout-ms <integer>", "Review render polling deadline.", "120000").addHelpText("after", "\nWrite one visual group at a time. Use --review none for a committed receipt, then render its version and inspect the PNG. Use flex, padding and gap; use targeted commands for later edits.\n").action(async (options) => writeHtml(input, options));
1512
1109
  };
1513
1110
  const cssProperty = (property) => property.replaceAll(/([a-z\d])([A-Z])/gu, "$1-$2").toLowerCase();
1514
1111
  const cssValue = (property, value) => typeof value === "number" && !UNITLESS_CSS_PROPERTIES.has(property) ? `${String(value)}px` : String(value);
@@ -1532,9 +1129,9 @@ const configureCreateArtboard = (canvas, input) => {
1532
1129
  const positioned = {
1533
1130
  display: "flex",
1534
1131
  flexDirection: "column",
1535
- ...styles,
1536
1132
  left: rightEdge(rootBoxes),
1537
1133
  top: 0,
1134
+ ...styles,
1538
1135
  position: "absolute"
1539
1136
  };
1540
1137
  const escapedName = options.name.replaceAll("&", "&amp;").replaceAll("\"", "&quot;");
@@ -2486,6 +2083,29 @@ const writeResult = (value, sensitiveDirectory) => {
2486
2083
  writeSignedUrlResult(value, sensitiveDirectory);
2487
2084
  return;
2488
2085
  }
2086
+ const authoring = toCanvasAuthoringResult(value);
2087
+ if (authoring !== null) {
2088
+ let detail = null;
2089
+ if (authoring.detail !== null) {
2090
+ prepareSensitiveDirectory(sensitiveDirectory);
2091
+ const outputPath = path.join(sensitiveDirectory, `result-${randomUUID()}.ndjson`);
2092
+ const body = `${JSON.stringify(authoring.detail)}\n`;
2093
+ writeFileSync(outputPath, body, {
2094
+ mode: FILE_MODE,
2095
+ flag: "wx"
2096
+ });
2097
+ detail = sensitiveReference({
2098
+ path: outputPath,
2099
+ characters: body.length,
2100
+ records: 1
2101
+ });
2102
+ }
2103
+ process.stdout.write(`${JSON.stringify({
2104
+ ...authoring.value,
2105
+ ...detail !== null && { detail }
2106
+ })}\n`);
2107
+ return;
2108
+ }
2489
2109
  writeLines(linesFor(value));
2490
2110
  };
2491
2111
  const writeFailure = (value) => {
@@ -2527,7 +2147,7 @@ const main = async () => {
2527
2147
  const credentials = createFileCredentialAdapter(CLI_CONFIG.configDirectory);
2528
2148
  const mutationKey = createMutationKeyAdapter();
2529
2149
  const cli = createCliProgram({
2530
- version: "0.1.14",
2150
+ version: "0.1.15",
2531
2151
  credentials,
2532
2152
  remote: createHttpRemoteAdapter(CLI_CONFIG.apiUrl, credentials, mutationKey),
2533
2153
  mutationKey,