@enhance-eng/enhance 0.1.25 → 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/{cli-output-identity.lib-DpON8As5.mjs → cli-output-identity.lib-CWNAXho4.mjs} +2402 -1306
- package/dist/main.mjs +719 -58
- package/dist/{mcp-invocation.adapter-FuxI6KsE.mjs → mcp-invocation.adapter-DHdF8-MP.mjs} +115 -69
- package/dist/mcp-main.mjs +12 -7
- package/dist/{mcp-server.adapter-D7XwVD-o.mjs → mcp-server.adapter-B0Kn0e7m.mjs} +109 -35
- package/dist/mcp.mjs +2 -2
- package/dist/{mutation-key.adapter-CXQ08HQY.mjs → mutation-key.adapter-A1d27TVY.mjs} +333 -176
- package/dist/remote-mcp-main.mjs +28 -45
- package/package.json +4 -3
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { $ as canvasRenderPendingSchema,
|
|
2
|
+
import { $ as canvasRenderPendingSchema, An as canvasReferencePageOf, At as PartialBatchError, B as canvasCaptureCapabilityInputSchema, Bn as applyCanvasOperationsOutputSchema, Bt as PROTOTYPE_ARTIFACT_MANIFEST_PATH, C as canvasSnapshotToken, Cn as canvasTextPropsWithContent, Dn as canvasPrototypePropsSchema, E as resolveCanvasSnapshot, En as canvasConversionMetadataSchema, G as canvasRenderCapabilityInputSchema, Gn as getCanvasDocumentOutputSchema, Gt as getPrototypePublishStatusOutputSchema, Hn as canvasLayoutWithoutCssProperties, Ht as createPrototypeArtifactOutputSchema, I as canvasDuplicateCapabilityInputSchema, In as createCanvasPreparationOutputSchema, J as prototypePublishCapabilityInputSchema, Jn as canvasNodeStylePatchSchema, Jt as submitPrototypeArtifactOutputSchema, K as canvasWriteHtmlCapabilityInputSchema, Kt as prototypeArtifactManifestSchema, Ln as getCanvasPreparationOutputSchema, Mn as beginCanvasActivityOutputSchema, Mt as transcriptOutputSchema, N as canvasAssetImportOutputSchema, On as canvasRecordingPropsSchema, Ot as hasCanvasReferenceScope, P as canvasArrangeCapabilityInputSchema, Pn as AGENT_CLIENT_HEADER, Qn as canvasRenderStateSchema, Qt as createAgentTokenOutputSchema, Rn as PAGE_KIND, Rt as getRecordingOutputSchema, S as canvasExchangeDigest, Sn as canvasTextChangeBetween, St as canvasEditCapabilityInputSchema, T as encodeCanvasExchangeToken, Tn as canvasCaptureSchema, Tt as canvasReferenceNodeIds, U as canvasApplyCapabilityInputSchema, Un as textOf, Ut as foldPrototypeArtifactPath, Vn as getCanvasMutationOutputSchema, Vt as attachPrototypeArtifactOutputSchema, W as canvasReadCapabilityInputSchema, Wn as mapCanvasFontSources, Wt as getPrototypeArtifactCapabilitiesOutputSchema, X as transcriptReadCapabilityInputSchema, Xn as getCanvasConversionOutputSchema, Y as recordingSnapshotCapabilityInputSchema, Yn as createCanvasConversionOutputSchema, Yt as getMeOutputSchema, Z as canvasRenderBatchRequestSchema, Zt as cliAuthConfigurationSchema, _r as canvasImageAssetIdentityFromPath, ar as canvasReadableSceneDocumentSchema, bn as applyCanvasTypographyPatch, bt as canvasMakeEditableCapabilityInputSchema, cr as canvasAuthoredStyleDeclarations, dt as canvasTranscriptCursorSchema, en as listOrganisationsOutputSchema, fr as canvasCssValue, ft as canvasResourcesCursorSchema, gr as canvasFontAssetIdentityFromPath, gt as canvasFindInputSchema, hr as reserveCanvasAssetOutputSchema, ht as canvasFindCursorSchema, ir as getCanvasRenderOutputSchema, it as canvasRemoveCapabilityInputSchema, j as canvasAssetImportCapabilityInputSchema, jn as resolveCanvasReference, jt as CliError, k as operationStatusInputSchema, kn as DEFAULT_CANVAS_REFERENCE_PAGE_ID, kt as parseCanvasReference, lr as canvasAxisStyleProperties, lt as canvasUpdateHtmlCapabilityInputSchema, mr as reserveCanvasAssetInputSchema, nr as createRecordingSnapshotOutputSchema, nt as canvasRenderRequestSchema, or as canvasSceneDocumentSchema, ot as canvasOutlineCursorSchema, pr as canvasAssetUploadOutputSchema, q as commentAttentionCapabilityInputSchema, qt as prototypeArtifactPathSchema, rr as downloadCanvasRenderOutputSchema, rt as canvasRenderFileSchema, s as toRemoteError, st as canvasReadInputSchema, tr as createCanvasRenderOutputSchema, ut as canvasUpdateHtmlInputSchema, v as canvasPrototypeCapabilityInputSchema, vr as canvasAdditionalStyleSchema, vt as canvasInsertHtmlCapabilityInputSchema, w as decodeCanvasExchangeToken, wt as assertCanvasReferenceNodes, xn as canvasCssTypographyOwners, xr as listCanvasesOutputSchema, zn as applyCanvasOperationsInputSchema } from "./cli-output-identity.lib-CWNAXho4.mjs";
|
|
3
3
|
import process from "node:process";
|
|
4
4
|
import { z } from "zod";
|
|
5
5
|
import { homedir, tmpdir } from "node:os";
|
|
@@ -8,10 +8,11 @@ import { chmodSync, constants, createReadStream, createWriteStream, mkdirSync, w
|
|
|
8
8
|
import path from "node:path";
|
|
9
9
|
import { createHash, randomBytes, randomUUID } from "node:crypto";
|
|
10
10
|
import { setTimeout as setTimeout$1 } from "node:timers/promises";
|
|
11
|
-
import { mkdtemp, open, readFile, realpath, rm, stat } from "node:fs/promises";
|
|
11
|
+
import { access, mkdtemp, open, readFile, realpath, rm, stat } from "node:fs/promises";
|
|
12
12
|
import { isDeepStrictEqual } from "node:util";
|
|
13
13
|
import { generate, parse } from "css-tree";
|
|
14
14
|
import { parseFragment, serialize, serializeOuter } from "parse5";
|
|
15
|
+
import { performance as performance$1 } from "node:perf_hooks";
|
|
15
16
|
import { Readable, Transform } from "node:stream";
|
|
16
17
|
import { pipeline } from "node:stream/promises";
|
|
17
18
|
import { ZipFile } from "yazl";
|
|
@@ -68,6 +69,34 @@ const canvasAdditionalStylePatchBetween = (before, after) => {
|
|
|
68
69
|
};
|
|
69
70
|
};
|
|
70
71
|
|
|
72
|
+
//#endregion
|
|
73
|
+
//#region ../../packages/contract/src/canvas/canvas-html-source.lib.ts
|
|
74
|
+
const OMITTED_ELEMENTS = /* @__PURE__ */ new Set([
|
|
75
|
+
"base",
|
|
76
|
+
"embed",
|
|
77
|
+
"iframe",
|
|
78
|
+
"link",
|
|
79
|
+
"meta",
|
|
80
|
+
"object",
|
|
81
|
+
"script"
|
|
82
|
+
]);
|
|
83
|
+
const EXECUTABLE_URL = /^(?:(?:javascript|vbscript):|data:text\/html(?:[;,]|$))/iu;
|
|
84
|
+
const UNSAFE_STYLE = /javascript|vbscript|data\s*:\s*text\/html|expression\s*\(|@import/iu;
|
|
85
|
+
const canRetainCanvasHtmlElement = (tag) => !OMITTED_ELEMENTS.has(tag.toLowerCase());
|
|
86
|
+
const canRetainCanvasHtmlStyle = (style) => !UNSAFE_STYLE.test(style);
|
|
87
|
+
const canRetainCanvasHtmlAttribute = (name, value) => {
|
|
88
|
+
const property = name.toLowerCase();
|
|
89
|
+
if (property === "srcdoc" || /^on/iu.test(property)) return false;
|
|
90
|
+
if (property === "style") return canRetainCanvasHtmlStyle(value);
|
|
91
|
+
return ![
|
|
92
|
+
"href",
|
|
93
|
+
"src",
|
|
94
|
+
"action",
|
|
95
|
+
"formaction",
|
|
96
|
+
"xlink:href"
|
|
97
|
+
].includes(property) || !EXECUTABLE_URL.test(value.replaceAll(/[\p{Control}\s]/gu, ""));
|
|
98
|
+
};
|
|
99
|
+
|
|
71
100
|
//#endregion
|
|
72
101
|
//#region ../../packages/contract/src/canvas/canvas-image-resources.lib.ts
|
|
73
102
|
const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
@@ -167,9 +196,9 @@ const createAuthUseCase = (credentials, remote, browser) => ({
|
|
|
167
196
|
await credentials.write(created.token);
|
|
168
197
|
return status;
|
|
169
198
|
},
|
|
170
|
-
status: async () => {
|
|
199
|
+
status: async (requestRemote = remote) => {
|
|
171
200
|
if (await credentials.read() === null) throw new CliError("UNAUTHORIZED", `No credential exists at ${credentials.path}.`, "A human must run 'enhance auth login'.");
|
|
172
|
-
return authenticated(await
|
|
201
|
+
return authenticated(await requestRemote.query("person.me", {}));
|
|
173
202
|
},
|
|
174
203
|
logout: async () => ({ loggedOut: await credentials.remove() })
|
|
175
204
|
});
|
|
@@ -190,7 +219,7 @@ const pngDimensions = (body) => {
|
|
|
190
219
|
};
|
|
191
220
|
const downloadVerifiedRenderPng = async (remote, job) => {
|
|
192
221
|
if (job.result.canvasId !== job.canvasId || job.result.requestedVersion !== job.requestedVersion || job.result.loadedVersion !== job.requestedVersion || JSON.stringify(job.result.target) !== JSON.stringify(job.target)) throw new CliError("INTERNAL", "The completed render evidence does not match its requested canvas, revision or target.", `Do not use the image. Report render job ${job.id}.`);
|
|
193
|
-
if (job.result.width * job.result.height >
|
|
222
|
+
if (job.maxOutputPixels !== void 0 && job.result.width * job.result.height > job.maxOutputPixels) throw new CliError("INTERNAL", "The completed render exceeds its authorised output pixel limit.", `Do not use the image. Report render job ${job.id}.`, { reason: "RENDER_BUDGET_UNSUPPORTED" });
|
|
194
223
|
const signed = downloadCanvasRenderOutputSchema.safeParse(await remote.query("canvas.render.download", { jobId: job.id }));
|
|
195
224
|
if (!signed.success || signed.data.jobId !== job.id || signed.data.download.bytes !== job.result.bytes) throw new CliError("INTERNAL", "The API returned an invalid render download response.", "Run `enhance doctor`; report the API and CLI versions if they differ.");
|
|
196
225
|
const body = await remote.download(signed.data.download.url);
|
|
@@ -296,7 +325,7 @@ const awaitJob = async (remote, input) => {
|
|
|
296
325
|
});
|
|
297
326
|
}
|
|
298
327
|
await wait$2(POLL_MS$3);
|
|
299
|
-
job = await readJob(remote, job.id);
|
|
328
|
+
job = job.purpose === "inspection" && job.state === "queued" && job.attempt > 0 ? await input.resume() : await readJob(remote, job.id);
|
|
300
329
|
}
|
|
301
330
|
if (job.state !== "succeeded") throw terminalFailure$1(job);
|
|
302
331
|
return job;
|
|
@@ -325,6 +354,7 @@ const executeRender = async (dependencies, input) => {
|
|
|
325
354
|
requireRenderBudget(initial, input);
|
|
326
355
|
const job = await awaitJob(dependencies.remote, {
|
|
327
356
|
initial,
|
|
357
|
+
resume: async () => requestRenderJob(dependencies.remote, input),
|
|
328
358
|
deadline: Date.now() + input.timeoutMs,
|
|
329
359
|
timeoutMs: input.timeoutMs,
|
|
330
360
|
retryClientToken: input.retryClientToken,
|
|
@@ -344,7 +374,7 @@ const executeRender = async (dependencies, input) => {
|
|
|
344
374
|
jobId: job.id
|
|
345
375
|
},
|
|
346
376
|
pixelsDelivered: false,
|
|
347
|
-
next: ["Read operation_status with includeImage true. Do not create another render."]
|
|
377
|
+
next: ["Read operation_status with includeImage true. Do not create another render.", "If it stays queued with attempt above 0, an attempt failed: repeat this exact request with the same clientToken to retry it."]
|
|
348
378
|
};
|
|
349
379
|
return await writeRenderArtifact(dependencies.remote, dependencies.files, job, {
|
|
350
380
|
outputPath: input.outputPath,
|
|
@@ -494,7 +524,7 @@ const union = (boxes) => {
|
|
|
494
524
|
const apply = async (remote, input) => {
|
|
495
525
|
const response = await remote.mutate(APPLY_PROCEDURE, {
|
|
496
526
|
...input,
|
|
497
|
-
documentFormatVersion:
|
|
527
|
+
documentFormatVersion: 7
|
|
498
528
|
});
|
|
499
529
|
const parsed = applyCanvasOperationsOutputSchema.safeParse(response);
|
|
500
530
|
if (!parsed.success) throw new CliError("INTERNAL", "The API returned an invalid canvas apply response.", "Run `enhance doctor`; report the API and CLI versions if they differ.");
|
|
@@ -829,11 +859,7 @@ const additionalOperation = (node, styles) => {
|
|
|
829
859
|
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.");
|
|
830
860
|
held.set(id, result.data);
|
|
831
861
|
}
|
|
832
|
-
const declarations =
|
|
833
|
-
for (const declaration of held.values()) {
|
|
834
|
-
if (declarations.length === 128) throw new CliError("BAD_REQUEST", "Too many additional CSS declarations.", "Remove unused declarations before adding more; no styles were changed.");
|
|
835
|
-
declarations.push(declaration);
|
|
836
|
-
}
|
|
862
|
+
const declarations = held.values().toArray();
|
|
837
863
|
const requested = declarations.length === 0 && node.additionalStyles === void 0 ? void 0 : { declarations };
|
|
838
864
|
const patch = canvasAdditionalStylePatchBetween(node.additionalStyles, requested);
|
|
839
865
|
return patch === null ? null : {
|
|
@@ -1242,7 +1268,6 @@ const assertCanvasReferenceOperations = (reference, document, operations) => {
|
|
|
1242
1268
|
|
|
1243
1269
|
//#endregion
|
|
1244
1270
|
//#region src/application/edit-canvas.composite.ts
|
|
1245
|
-
const MAX_EDIT_TARGETS = 1e3;
|
|
1246
1271
|
const targetIds = (edit) => {
|
|
1247
1272
|
switch (edit.kind) {
|
|
1248
1273
|
case "set_text":
|
|
@@ -1258,9 +1283,7 @@ const scopeIds = (edit, scene) => {
|
|
|
1258
1283
|
return targetIds(edit);
|
|
1259
1284
|
};
|
|
1260
1285
|
const validateTargets = (input, scene) => {
|
|
1261
|
-
if (input.edits.length === 0 || input.edits.length > 1e3) throw new CliError("BAD_REQUEST", "The edit batch exceeds the canonical operation limit.", "Split larger changes into bounded batches.");
|
|
1262
1286
|
const ids = new Set(input.edits.flatMap((edit) => targetIds(edit)));
|
|
1263
|
-
if (ids.size > MAX_EDIT_TARGETS) throw new CliError("BAD_REQUEST", "A batch may target at most 1,000 nodes.", "Split the edit into smaller batches.");
|
|
1264
1287
|
for (const id of ids) requireCanvasNode(scene, id);
|
|
1265
1288
|
const reference = {
|
|
1266
1289
|
canvasId: input.canvasId,
|
|
@@ -1281,11 +1304,11 @@ const createEditCanvasComposite = (remote) => ({ execute: async (input) => {
|
|
|
1281
1304
|
const parsed = applyCanvasOperationsInputSchema.safeParse({
|
|
1282
1305
|
canvasId: input.canvasId,
|
|
1283
1306
|
mutationId: input.mutationId,
|
|
1284
|
-
documentFormatVersion:
|
|
1307
|
+
documentFormatVersion: 7,
|
|
1285
1308
|
baseVersion: input.baseVersion,
|
|
1286
1309
|
operations: plan.operations
|
|
1287
1310
|
});
|
|
1288
|
-
if (!parsed.success) throw new CliError("BAD_REQUEST", "The edit
|
|
1311
|
+
if (!parsed.success) throw new CliError("BAD_REQUEST", "The edit contains an invalid canvas operation.", parsed.error.issues[0]?.message ?? "Check the edit’s node references and values.");
|
|
1289
1312
|
const result = applyCanvasOperationsOutputSchema.parse(await createApplyCanvasComposite(remote).execute(parsed.data));
|
|
1290
1313
|
return {
|
|
1291
1314
|
...result,
|
|
@@ -1307,20 +1330,19 @@ const fromCapabilityReference = (catalog, id) => {
|
|
|
1307
1330
|
};
|
|
1308
1331
|
|
|
1309
1332
|
//#endregion
|
|
1310
|
-
//#region src/application/
|
|
1311
|
-
const
|
|
1312
|
-
const
|
|
1313
|
-
if (offset > entries.length) throw new CliError("BAD_REQUEST", "The
|
|
1333
|
+
//#region src/application/result-page.use-case.ts
|
|
1334
|
+
const TARGET_PAGE_BYTES = 48e3;
|
|
1335
|
+
const boundedResultPage = (entries, offset, limit, maxBytes = TARGET_PAGE_BYTES) => {
|
|
1336
|
+
if (offset > entries.length) throw new CliError("BAD_REQUEST", "The result page offset is out of range.", "Restart pagination at offset 0.");
|
|
1314
1337
|
const selected = [];
|
|
1315
1338
|
let bytes = 2;
|
|
1316
1339
|
const offered = entries.slice(offset, offset + limit);
|
|
1317
1340
|
for (const entry of offered) {
|
|
1318
1341
|
const size = Buffer.byteLength(JSON.stringify(entry)) + 1;
|
|
1319
|
-
if (bytes + size >
|
|
1342
|
+
if (selected.length > 0 && bytes + size > maxBytes) break;
|
|
1320
1343
|
selected.push(entry);
|
|
1321
1344
|
bytes += size;
|
|
1322
1345
|
}
|
|
1323
|
-
if (selected.length === 0 && offset < entries.length) throw new CliError("BAD_REQUEST", "One operation detail exceeds the inline result budget.", "Read the full operation through its comprehensive CLI command.");
|
|
1324
1346
|
const nextOffset = offset + selected.length;
|
|
1325
1347
|
return {
|
|
1326
1348
|
entries: selected,
|
|
@@ -1382,7 +1404,7 @@ const canvasConversionStatus = (job, page) => ({
|
|
|
1382
1404
|
destination: job.destination,
|
|
1383
1405
|
result: conversionSummary(job),
|
|
1384
1406
|
failure: job.failure,
|
|
1385
|
-
details:
|
|
1407
|
+
details: boundedResultPage(conversionEntries(job), page.offset, page.limit),
|
|
1386
1408
|
warnings: job.state === "succeeded" ? ["This receipt does not verify visual fidelity. Render the committed root to inspect it."] : []
|
|
1387
1409
|
});
|
|
1388
1410
|
|
|
@@ -1747,6 +1769,8 @@ const createImportCanvasAssetComposite = (remote, files) => ({ execute: async (i
|
|
|
1747
1769
|
|
|
1748
1770
|
//#endregion
|
|
1749
1771
|
//#region src/application/prototype-publication.use-case.ts
|
|
1772
|
+
const STATUS_TIMEOUT_MS = 15e3;
|
|
1773
|
+
const delay = async (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
1750
1774
|
const INITIAL_POLL_MS = 50;
|
|
1751
1775
|
const MAX_POLL_MS = 1e3;
|
|
1752
1776
|
const TERMINAL_STATES = /* @__PURE__ */ new Set([
|
|
@@ -1767,6 +1791,8 @@ const reserveAndUpload = async (remote, input, artifact, reserved) => {
|
|
|
1767
1791
|
...input.prototypeId !== null && { prototypeId: input.prototypeId },
|
|
1768
1792
|
clientToken: input.clientToken,
|
|
1769
1793
|
nodeId: input.nodeId,
|
|
1794
|
+
...input.targetMode !== void 0 && { targetMode: input.targetMode },
|
|
1795
|
+
...input.canvasPageId !== void 0 && { canvasPageId: input.canvasPageId },
|
|
1770
1796
|
title: input.title,
|
|
1771
1797
|
entryPath: artifact.manifest.entryPath,
|
|
1772
1798
|
artifact: artifact.identity,
|
|
@@ -1801,25 +1827,79 @@ const preparePrototypePublication = async (remote, artifacts, input, reserved) =
|
|
|
1801
1827
|
await artifact.dispose();
|
|
1802
1828
|
}
|
|
1803
1829
|
};
|
|
1804
|
-
const readPublication = async (remote, input) => {
|
|
1805
|
-
const
|
|
1806
|
-
|
|
1807
|
-
|
|
1830
|
+
const readPublication = async (remote, input, timeoutMs) => {
|
|
1831
|
+
const abort = new AbortController();
|
|
1832
|
+
const expired = Promise.withResolvers();
|
|
1833
|
+
const timer = setTimeout(() => {
|
|
1834
|
+
abort.abort();
|
|
1835
|
+
expired.reject(new CliError("INTERNAL", "The prototype status request timed out.", "Check this deployment again; keep its existing client token.", {
|
|
1836
|
+
reason: "STATUS_TIMEOUT",
|
|
1837
|
+
deploymentId: input.deploymentId
|
|
1838
|
+
}));
|
|
1839
|
+
}, timeoutMs);
|
|
1840
|
+
try {
|
|
1841
|
+
const response = await Promise.race([remote.query(PUBLICATION_PROCEDURES[3], input, { signal: abort.signal }), expired.promise]);
|
|
1842
|
+
const parsed = getPrototypePublishStatusOutputSchema.safeParse(response);
|
|
1843
|
+
if (!parsed.success || parsed.data.deploymentId !== input.deploymentId) throw invalidResponse$1("status");
|
|
1844
|
+
return parsed.data;
|
|
1845
|
+
} finally {
|
|
1846
|
+
clearTimeout(timer);
|
|
1847
|
+
}
|
|
1808
1848
|
};
|
|
1809
1849
|
const waitForPrototypePublication = async (remote, input, waitMs) => {
|
|
1810
|
-
const deadline =
|
|
1850
|
+
const deadline = performance.now() + waitMs;
|
|
1811
1851
|
let pollMs = INITIAL_POLL_MS;
|
|
1812
|
-
let status = await readPublication(remote, input);
|
|
1852
|
+
let status = await readPublication(remote, input, waitMs > 0 ? Math.min(STATUS_TIMEOUT_MS, waitMs) : STATUS_TIMEOUT_MS);
|
|
1813
1853
|
while (!TERMINAL_STATES.has(status.state)) {
|
|
1814
|
-
const remainingMs = deadline -
|
|
1854
|
+
const remainingMs = deadline - performance.now();
|
|
1815
1855
|
if (remainingMs <= 0) return status;
|
|
1816
|
-
await
|
|
1856
|
+
await delay(Math.min(pollMs, remainingMs));
|
|
1817
1857
|
pollMs = Math.min(pollMs * 2, MAX_POLL_MS);
|
|
1818
|
-
|
|
1858
|
+
const timeLeft = deadline - performance.now();
|
|
1859
|
+
if (timeLeft <= 0) return status;
|
|
1860
|
+
try {
|
|
1861
|
+
status = await readPublication(remote, input, Math.min(STATUS_TIMEOUT_MS, timeLeft));
|
|
1862
|
+
} catch (error) {
|
|
1863
|
+
if (error instanceof CliError && error.fields?.["reason"] === "STATUS_TIMEOUT") return status;
|
|
1864
|
+
throw error;
|
|
1865
|
+
}
|
|
1819
1866
|
}
|
|
1820
1867
|
return status;
|
|
1821
1868
|
};
|
|
1822
1869
|
|
|
1870
|
+
//#endregion
|
|
1871
|
+
//#region src/application/prototype-publication-outcome.use-case.ts
|
|
1872
|
+
const SOURCE_FAILURES = [
|
|
1873
|
+
"BAD_ARTIFACT",
|
|
1874
|
+
"ARTIFACT_INTEGRITY",
|
|
1875
|
+
"FILE_INTEGRITY",
|
|
1876
|
+
"FILE_TOO_LARGE",
|
|
1877
|
+
"FILE_COUNT_",
|
|
1878
|
+
"MANIFEST_",
|
|
1879
|
+
"PATH_",
|
|
1880
|
+
"ENTRY_",
|
|
1881
|
+
"EXPANDED_",
|
|
1882
|
+
"ZIP_INVALID",
|
|
1883
|
+
"ZIP_ENCRYPTED",
|
|
1884
|
+
"ZIP_PATH_ENCODING",
|
|
1885
|
+
"ZIP_COMPRESSION",
|
|
1886
|
+
"ZIP_ENTRY_TYPE"
|
|
1887
|
+
];
|
|
1888
|
+
const toPrototypePublicationFailure = (publication) => {
|
|
1889
|
+
const failure = publication.failure;
|
|
1890
|
+
const isBuildFailure = SOURCE_FAILURES.some((prefix) => failure.code.startsWith(prefix));
|
|
1891
|
+
return {
|
|
1892
|
+
isBuildFailure,
|
|
1893
|
+
nextAction: isBuildFailure ? "fix_build" : "retry_new_publication",
|
|
1894
|
+
failure: {
|
|
1895
|
+
code: failure.code,
|
|
1896
|
+
message: failure.message,
|
|
1897
|
+
remediation: isBuildFailure ? "Correct the named build problem and publish a new artifact with a new clientToken." : "This ingestion attempt is terminal. Restore storage or service access, then explicitly publish the same valid build with a new clientToken. Do not change the source to repair a service failure."
|
|
1898
|
+
}
|
|
1899
|
+
};
|
|
1900
|
+
};
|
|
1901
|
+
const prototypePublicationWarnings = (publication) => publication.unavailableFiles?.map((file) => `Unavailable published file: ${file.path} (${file.code}).`) ?? [];
|
|
1902
|
+
|
|
1823
1903
|
//#endregion
|
|
1824
1904
|
//#region src/application/publish-canvas-prototype.composite.ts
|
|
1825
1905
|
const PROCEDURES = ["prototype.getArtifactCapabilities", "prototype.attach"];
|
|
@@ -1860,7 +1940,7 @@ const attach = async (remote, input, publication) => {
|
|
|
1860
1940
|
if (!parsed.success) throw new Error("Invalid prototype attachment response");
|
|
1861
1941
|
const result = parsed.data;
|
|
1862
1942
|
const receipt = result.attachment;
|
|
1863
|
-
if (receipt === void 0 || result.canvasId !== reference.canvasId || result.deploymentId !== publication.deploymentId || result.prototypeId !== publication.prototypeId || result.nodeId !== publication.nodeId || result.version !== receipt.version || receipt.outcome === "committed" && (receipt.mutationId !== input.clientToken || receipt.
|
|
1943
|
+
if (receipt === void 0 || result.canvasId !== reference.canvasId || result.deploymentId !== publication.deploymentId || result.prototypeId !== publication.prototypeId || result.nodeId !== publication.nodeId || result.version !== receipt.version || receipt.outcome === "committed" && (receipt.mutationId !== input.clientToken || receipt.version !== receipt.previousVersion + 1) || receipt.outcome === "no_op" && receipt.version !== input.baseVersion) throw new Error("Unconfirmed prototype attachment receipt");
|
|
1864
1944
|
return {
|
|
1865
1945
|
...result,
|
|
1866
1946
|
attachment: receipt
|
|
@@ -1883,8 +1963,8 @@ const attachReady = async (remote, input, base, publication) => {
|
|
|
1883
1963
|
...base,
|
|
1884
1964
|
attachmentStatus: isConflict ? "conflict" : isRejected ? "not_attempted" : "not_confirmed",
|
|
1885
1965
|
failure,
|
|
1886
|
-
nextAction: isConflict || isRejected ? "replan_attachment" : "retry_same_request",
|
|
1887
|
-
warnings: ["The ready deployment is reusable. A status read never attaches it. Retry uncertainty with the original attachment intent;
|
|
1966
|
+
nextAction: failure.code === "UNAUTHORIZED" || failure.code === "FORBIDDEN" ? "restore_access" : isConflict || isRejected ? "replan_attachment" : "retry_same_request",
|
|
1967
|
+
warnings: [...base.warnings, "The ready deployment is reusable. A status read never attaches it. Retry uncertainty with the original attachment intent; refresh baseVersion after an unrelated canvas edit and keep the same clientToken. A changed scope or destination requires a new attachment intent."]
|
|
1888
1968
|
};
|
|
1889
1969
|
}
|
|
1890
1970
|
};
|
|
@@ -1901,16 +1981,25 @@ const finishPublication = async (remote, input, canvasId, publication) => {
|
|
|
1901
1981
|
attachment: null,
|
|
1902
1982
|
failure: null,
|
|
1903
1983
|
nextAction: "check_status",
|
|
1904
|
-
warnings:
|
|
1984
|
+
warnings: prototypePublicationWarnings(publication)
|
|
1905
1985
|
};
|
|
1906
|
-
if (publication.state === "failed"
|
|
1986
|
+
if (publication.state === "failed") {
|
|
1987
|
+
const { nextAction, failure } = toPrototypePublicationFailure(publication);
|
|
1988
|
+
return {
|
|
1989
|
+
...base,
|
|
1990
|
+
attachmentStatus: "not_attempted",
|
|
1991
|
+
nextAction,
|
|
1992
|
+
failure
|
|
1993
|
+
};
|
|
1994
|
+
}
|
|
1995
|
+
if (publication.state === "abandoned") return {
|
|
1907
1996
|
...base,
|
|
1908
1997
|
attachmentStatus: "not_attempted",
|
|
1909
|
-
nextAction: "
|
|
1998
|
+
nextAction: "retry_new_publication",
|
|
1910
1999
|
failure: {
|
|
1911
|
-
code:
|
|
1912
|
-
message:
|
|
1913
|
-
remediation: "
|
|
2000
|
+
code: "NOT_FOUND",
|
|
2001
|
+
message: "The deployment was abandoned.",
|
|
2002
|
+
remediation: "Publish the same build explicitly with a new clientToken if it is still needed."
|
|
1914
2003
|
}
|
|
1915
2004
|
};
|
|
1916
2005
|
if (publication.state !== "ready") return base;
|
|
@@ -1924,6 +2013,7 @@ const createPublishCanvasPrototypeComposite = (remote, artifacts) => ({ execute:
|
|
|
1924
2013
|
if (input.source.kind === "build") deploymentId = (await preparePrototypePublication(remote, artifacts, {
|
|
1925
2014
|
...input.source,
|
|
1926
2015
|
canvasId: reference.canvasId,
|
|
2016
|
+
...reference.pageId !== void 0 && { canvasPageId: reference.pageId },
|
|
1927
2017
|
clientToken: input.clientToken
|
|
1928
2018
|
}, (reservedId) => {
|
|
1929
2019
|
deploymentId = reservedId;
|
|
@@ -1947,7 +2037,7 @@ const createPublishCanvasPrototypeComposite = (remote, artifacts) => ({ execute:
|
|
|
1947
2037
|
attachmentStatus: "not_attempted",
|
|
1948
2038
|
attachment: null,
|
|
1949
2039
|
failure: failureOf$1(error),
|
|
1950
|
-
nextAction: "retry_same_request",
|
|
2040
|
+
nextAction: error instanceof CliError && (error.code === "UNAUTHORIZED" || error.code === "FORBIDDEN") ? "restore_access" : "retry_same_request",
|
|
1951
2041
|
warnings: ["An existing deployment may still be processing. Retry the same source and clientToken to recover or finish upload; do not reserve a new publication."]
|
|
1952
2042
|
};
|
|
1953
2043
|
}
|
|
@@ -1958,10 +2048,23 @@ const createPublishCanvasPrototypeComposite = (remote, artifacts) => ({ execute:
|
|
|
1958
2048
|
const PUBLISH_WAIT_MS = 3e5;
|
|
1959
2049
|
const PUBLISH_PROTOTYPE_PROCEDURES = ["prototype.attach"];
|
|
1960
2050
|
const invalidResponse = (operation) => new CliError("INTERNAL", `The API returned an invalid prototype ${operation} response.`, "Run `enhance doctor`; report the API and CLI versions if they differ.");
|
|
1961
|
-
const
|
|
1962
|
-
if (status.state
|
|
1963
|
-
|
|
1964
|
-
|
|
2051
|
+
const requireReadyPublication = (status) => {
|
|
2052
|
+
if (status.state === "failed") {
|
|
2053
|
+
const failure = toPrototypePublicationFailure(status);
|
|
2054
|
+
throw new CliError(failure.isBuildFailure ? "BAD_REQUEST" : "INTERNAL", failure.failure.message, failure.failure.remediation, {
|
|
2055
|
+
reason: failure.failure.code,
|
|
2056
|
+
deploymentId: status.deploymentId,
|
|
2057
|
+
nextAction: failure.nextAction,
|
|
2058
|
+
...status.failure.path !== void 0 && { path: status.failure.path }
|
|
2059
|
+
});
|
|
2060
|
+
}
|
|
2061
|
+
if (status.state === "abandoned") throw new CliError("NOT_FOUND", `Prototype deployment ${status.deploymentId} was abandoned.`, "Publish the directory again with a new client token.");
|
|
2062
|
+
if (status.state !== "ready") throw new CliError("INTERNAL", "Prototype ingestion is still processing.", "Check this deployment status, then resume the same source and client token; do not reserve a second publication.", {
|
|
2063
|
+
reason: "INGESTION_PENDING",
|
|
2064
|
+
state: status.state,
|
|
2065
|
+
processedFiles: String(status.processedFiles),
|
|
2066
|
+
deploymentId: status.deploymentId
|
|
2067
|
+
});
|
|
1965
2068
|
};
|
|
1966
2069
|
const executePublish = async (remote, artifacts, input) => {
|
|
1967
2070
|
const progress = { deploymentId: null };
|
|
@@ -1973,9 +2076,7 @@ const executePublish = async (remote, artifacts, input) => {
|
|
|
1973
2076
|
canvasId: input.canvasId,
|
|
1974
2077
|
deploymentId: created.deploymentId
|
|
1975
2078
|
}, PUBLISH_WAIT_MS);
|
|
1976
|
-
|
|
1977
|
-
if (status.state === "abandoned") throw new CliError("NOT_FOUND", `Prototype deployment ${created.deploymentId} was abandoned.`, "Publish the directory again with a new client token.");
|
|
1978
|
-
if (status.state !== "ready") throw new Error("prototype ingestion is still running");
|
|
2079
|
+
requireReadyPublication(status);
|
|
1979
2080
|
const attached = attachPrototypeArtifactOutputSchema.safeParse(await remote.mutate(PUBLISH_PROTOTYPE_PROCEDURES[0], {
|
|
1980
2081
|
canvasId: input.canvasId,
|
|
1981
2082
|
deploymentId: created.deploymentId,
|
|
@@ -1987,12 +2088,21 @@ const executePublish = async (remote, artifacts, input) => {
|
|
|
1987
2088
|
fileCount: status.fileCount,
|
|
1988
2089
|
totalBytes: status.totalBytes,
|
|
1989
2090
|
alreadyExists: created.alreadyExists,
|
|
1990
|
-
|
|
2091
|
+
warnings: prototypePublicationWarnings(status),
|
|
2092
|
+
next: [attached.data.canvasUrl ?? attached.data.openUrl, `enhance canvas render --canvas ${input.canvasId} --node-id ${attached.data.nodeId} --expected-version ${String(attached.data.version)}`]
|
|
1991
2093
|
};
|
|
1992
2094
|
} catch (error) {
|
|
1993
2095
|
if (error instanceof CliError && (error.code === "BAD_REQUEST" || error.code === "NOT_FOUND")) throw error;
|
|
1994
2096
|
if (progress.deploymentId === null) throw error;
|
|
1995
|
-
throw new PartialBatchError(`Prototype deployment ${progress.deploymentId}
|
|
2097
|
+
throw new PartialBatchError(error instanceof CliError ? error.message : `Prototype deployment ${progress.deploymentId} has no confirmed completion.`, `${error instanceof CliError ? `${error.remediation} ` : ""}Retry 'enhance prototype publish' with the same --client-token ${input.clientToken}.`, {
|
|
2098
|
+
code: error instanceof CliError ? error.code : "INTERNAL",
|
|
2099
|
+
fields: {
|
|
2100
|
+
...error instanceof CliError && error.fields,
|
|
2101
|
+
canvasId: input.canvasId,
|
|
2102
|
+
deploymentId: progress.deploymentId,
|
|
2103
|
+
clientToken: input.clientToken
|
|
2104
|
+
}
|
|
2105
|
+
});
|
|
1996
2106
|
}
|
|
1997
2107
|
};
|
|
1998
2108
|
const createPublishPrototypeComposite = (remote, artifacts) => ({ execute: async (input) => executePublish(remote, artifacts, input) });
|
|
@@ -2138,7 +2248,7 @@ const mutationStatus = async (remote, input) => {
|
|
|
2138
2248
|
kind: "canvas-mutation",
|
|
2139
2249
|
state: "committed",
|
|
2140
2250
|
receipt: canvasWriteReceipt(found.result, operation.fingerprint),
|
|
2141
|
-
affected:
|
|
2251
|
+
affected: boundedResultPage(affectedEntries(found.result), offset, limit)
|
|
2142
2252
|
};
|
|
2143
2253
|
};
|
|
2144
2254
|
const renderStatus = async (remote, input) => {
|
|
@@ -2152,10 +2262,11 @@ const renderStatus = async (remote, input) => {
|
|
|
2152
2262
|
state: job.state,
|
|
2153
2263
|
phase: job.phase,
|
|
2154
2264
|
requestedVersion: job.requestedVersion,
|
|
2265
|
+
attempt: job.attempt,
|
|
2155
2266
|
target: job.target,
|
|
2156
2267
|
sourceState: job.sourceState ?? null,
|
|
2157
2268
|
evidence,
|
|
2158
|
-
details:
|
|
2269
|
+
details: boundedResultPage(renderEntries(job), offset, limit),
|
|
2159
2270
|
failure: job.failure,
|
|
2160
2271
|
pixelsDelivered: false,
|
|
2161
2272
|
warnings: ["Status reports stored render evidence. It does not deliver or inspect the image."]
|
|
@@ -2194,7 +2305,7 @@ const readStatus = async (remote, input) => {
|
|
|
2194
2305
|
const { operation, offset, limit } = input;
|
|
2195
2306
|
switch (operation.kind) {
|
|
2196
2307
|
case "canvas-asset":
|
|
2197
|
-
|
|
2308
|
+
boundedResultPage([], offset, limit);
|
|
2198
2309
|
return assetStatus(remote, operation);
|
|
2199
2310
|
case "canvas-mutation": return mutationStatus(remote, {
|
|
2200
2311
|
...input,
|
|
@@ -2225,7 +2336,7 @@ const readStatus = async (remote, input) => {
|
|
|
2225
2336
|
});
|
|
2226
2337
|
}
|
|
2227
2338
|
case "prototype-deployment":
|
|
2228
|
-
|
|
2339
|
+
boundedResultPage([], offset, limit);
|
|
2229
2340
|
return {
|
|
2230
2341
|
kind: "prototype-deployment",
|
|
2231
2342
|
operation,
|
|
@@ -2408,14 +2519,14 @@ const CONTENT_TYPES$1 = {
|
|
|
2408
2519
|
".woff": "font/woff",
|
|
2409
2520
|
".woff2": "font/woff2"
|
|
2410
2521
|
};
|
|
2411
|
-
const badFile = () => new CliError("BAD_REQUEST", "Choose one supported regular image or font file
|
|
2522
|
+
const badFile = () => new CliError("BAD_REQUEST", "Choose one supported regular image or font file.", "Use an explicit local PNG, JPEG, GIF, WebP, AVIF, TTF, OTF, WOFF or WOFF2 file.");
|
|
2412
2523
|
const readFile$1 = async (filePath) => {
|
|
2413
2524
|
const contentType = CONTENT_TYPES$1[path.extname(filePath).toLowerCase()];
|
|
2414
2525
|
if (contentType === void 0) throw badFile();
|
|
2415
2526
|
const file = await open(filePath, constants.O_RDONLY | constants.O_NONBLOCK);
|
|
2416
2527
|
try {
|
|
2417
2528
|
const stats = await file.stat();
|
|
2418
|
-
if (!stats.isFile() || stats.size === 0
|
|
2529
|
+
if (!stats.isFile() || stats.size === 0) throw badFile();
|
|
2419
2530
|
const buffer = Buffer.alloc(stats.size + 1);
|
|
2420
2531
|
let bytes = 0;
|
|
2421
2532
|
while (bytes < buffer.byteLength) {
|
|
@@ -2447,7 +2558,7 @@ const createCanvasAssetFileAdapter = (filePath) => ({ read: async () => {
|
|
|
2447
2558
|
|
|
2448
2559
|
//#endregion
|
|
2449
2560
|
//#region src/application/find-canvas.composite.ts
|
|
2450
|
-
const MAX_PAGE_BYTES
|
|
2561
|
+
const MAX_PAGE_BYTES = 48e3;
|
|
2451
2562
|
const DISCOVERY_PROCEDURES = ["canvas.list", "organisation.list"];
|
|
2452
2563
|
const readItems = async (remote, input) => {
|
|
2453
2564
|
const [canvasValue, teamValue] = await Promise.all([remote.query(DISCOVERY_PROCEDURES[0], {
|
|
@@ -2496,7 +2607,7 @@ const boundedItems = (items) => {
|
|
|
2496
2607
|
let bytes = 2;
|
|
2497
2608
|
for (const entry of items) {
|
|
2498
2609
|
const size = Buffer.byteLength(JSON.stringify(entry)) + 1;
|
|
2499
|
-
if (bytes + size > MAX_PAGE_BYTES
|
|
2610
|
+
if (bytes + size > MAX_PAGE_BYTES) break;
|
|
2500
2611
|
selected.push(entry);
|
|
2501
2612
|
bytes += size;
|
|
2502
2613
|
}
|
|
@@ -2538,6 +2649,14 @@ const createFindCanvasComposite = (remote) => ({ execute: async (input) => {
|
|
|
2538
2649
|
//#endregion
|
|
2539
2650
|
//#region src/application/canvas-preparation.use-case.ts
|
|
2540
2651
|
const POLL_MS = 250;
|
|
2652
|
+
const readPreparation = async (remote, jobId) => {
|
|
2653
|
+
try {
|
|
2654
|
+
return { value: await remote.query("canvas.render.preparation.get", { jobId }) };
|
|
2655
|
+
} catch (error) {
|
|
2656
|
+
if (error instanceof CliError && !["INTERNAL", "RATE_LIMITED"].includes(error.code)) throw error;
|
|
2657
|
+
return null;
|
|
2658
|
+
}
|
|
2659
|
+
};
|
|
2541
2660
|
const waitForPreparation = async (remote, initial, waitMs) => {
|
|
2542
2661
|
const deadline = Date.now() + waitMs;
|
|
2543
2662
|
let job = initial;
|
|
@@ -2545,7 +2664,9 @@ const waitForPreparation = async (remote, initial, waitMs) => {
|
|
|
2545
2664
|
const remaining = deadline - Date.now();
|
|
2546
2665
|
if (remaining <= 0) break;
|
|
2547
2666
|
await setTimeout$1(Math.min(POLL_MS, remaining));
|
|
2548
|
-
|
|
2667
|
+
const status = await readPreparation(remote, initial.id);
|
|
2668
|
+
if (status === null) return job;
|
|
2669
|
+
job = getCanvasPreparationOutputSchema.parse(status.value).job;
|
|
2549
2670
|
if (job.id !== initial.id) throw new CliError("INTERNAL", "Preparation identity changed.", "Retry the original request.");
|
|
2550
2671
|
}
|
|
2551
2672
|
return job;
|
|
@@ -2589,7 +2710,7 @@ const commitPreparation = async (remote, input, job, fingerprint) => {
|
|
|
2589
2710
|
const request = applyCanvasOperationsInputSchema.parse({
|
|
2590
2711
|
canvasId: job.canvasId,
|
|
2591
2712
|
mutationId: input.clientToken,
|
|
2592
|
-
documentFormatVersion:
|
|
2713
|
+
documentFormatVersion: 7,
|
|
2593
2714
|
baseVersion: input.baseVersion,
|
|
2594
2715
|
operations: job.result.operations,
|
|
2595
2716
|
requestContext: {
|
|
@@ -2681,8 +2802,7 @@ const projectCanvasEditableHtml = (document, rootNodeId) => {
|
|
|
2681
2802
|
const seen = /* @__PURE__ */ new Set();
|
|
2682
2803
|
const opaqueNodeIds = [];
|
|
2683
2804
|
const childrenByParent = canvasChildrenByParent(document);
|
|
2684
|
-
const visit = (nodeId
|
|
2685
|
-
if (depth > CANVAS_HTML_LIMITS.depth || seen.size >= CANVAS_HTML_LIMITS.nodes) return fail("This editable subtree exceeds the depth or node budget. Read a smaller root.");
|
|
2805
|
+
const visit = (nodeId) => {
|
|
2686
2806
|
if (seen.has(nodeId)) return fail("The document contains repeated node identity.");
|
|
2687
2807
|
seen.add(nodeId);
|
|
2688
2808
|
const node = requireCanvasNode(document, nodeId);
|
|
@@ -2702,16 +2822,14 @@ const projectCanvasEditableHtml = (document, rootNodeId) => {
|
|
|
2702
2822
|
opaque: isOpaque,
|
|
2703
2823
|
styles,
|
|
2704
2824
|
text: isOpaque || node.component !== "text" ? "" : textOf(node) ?? "",
|
|
2705
|
-
children: isOpaque ? [] : children.map((id) => visit(id
|
|
2825
|
+
children: isOpaque ? [] : children.map((id) => visit(id))
|
|
2706
2826
|
};
|
|
2707
2827
|
};
|
|
2708
|
-
const root = visit(rootNodeId
|
|
2709
|
-
const html = serialize$1(root);
|
|
2710
|
-
if (html.length > CANVAS_HTML_LIMITS.characters) return fail("This editable subtree exceeds the inline HTML budget. Read a smaller root.");
|
|
2828
|
+
const root = visit(rootNodeId);
|
|
2711
2829
|
return {
|
|
2712
2830
|
projectionVersion: 1,
|
|
2713
2831
|
root,
|
|
2714
|
-
html,
|
|
2832
|
+
html: serialize$1(root),
|
|
2715
2833
|
opaqueNodeIds
|
|
2716
2834
|
};
|
|
2717
2835
|
};
|
|
@@ -2721,17 +2839,27 @@ const elements = (children) => children.flatMap((child) => {
|
|
|
2721
2839
|
return fail("Container content must contain identified elements; text belongs inside its retained span.");
|
|
2722
2840
|
});
|
|
2723
2841
|
const canvasEditableHtmlFragment = (html) => {
|
|
2724
|
-
|
|
2725
|
-
return parseFragment(html, {
|
|
2842
|
+
const fragment = parseFragment(html, {
|
|
2726
2843
|
sourceCodeLocationInfo: true,
|
|
2727
2844
|
onParseError: (error) => fail(`Invalid HTML at line ${String(error.startLine)}: ${error.code}.`)
|
|
2728
2845
|
});
|
|
2846
|
+
const pending = [fragment];
|
|
2847
|
+
while (pending.length > 0) {
|
|
2848
|
+
const parent = pending.pop();
|
|
2849
|
+
if (parent === void 0) break;
|
|
2850
|
+
parent.childNodes = parent.childNodes.filter((child) => !("tagName" in child) || canRetainCanvasHtmlElement(child.tagName));
|
|
2851
|
+
const children = parent.childNodes.filter((child) => "tagName" in child);
|
|
2852
|
+
for (const child of children) {
|
|
2853
|
+
child.attrs = child.attrs.filter((attribute) => canRetainCanvasHtmlAttribute(attribute.name, attribute.value));
|
|
2854
|
+
pending.push(child);
|
|
2855
|
+
}
|
|
2856
|
+
}
|
|
2857
|
+
return fragment;
|
|
2729
2858
|
};
|
|
2730
2859
|
const parseCanvasEditableHtml = (html) => {
|
|
2731
2860
|
const fragment = canvasEditableHtmlFragment(html);
|
|
2732
2861
|
const seen = /* @__PURE__ */ new Set();
|
|
2733
|
-
const visit = (element
|
|
2734
|
-
if (depth > CANVAS_HTML_LIMITS.depth || seen.size >= CANVAS_HTML_LIMITS.nodes) return fail("The submitted HTML exceeds the depth or node budget.");
|
|
2862
|
+
const visit = (element) => {
|
|
2735
2863
|
if (element.tagName !== "div" && element.tagName !== "span") return fail(`Unsupported retained element: ${element.tagName}.`);
|
|
2736
2864
|
const attrs = Object.fromEntries(element.attrs.map((attr) => {
|
|
2737
2865
|
if (!ATTRIBUTES.has(attr.name) || attr.namespace !== void 0) return fail(`Unsupported attribute: ${attr.name}.`);
|
|
@@ -2755,13 +2883,13 @@ const parseCanvasEditableHtml = (html) => {
|
|
|
2755
2883
|
opaque: marker === "true",
|
|
2756
2884
|
text,
|
|
2757
2885
|
styles: styleValues(attrs["style"] ?? ""),
|
|
2758
|
-
children: element.tagName === "span" ? [] : elements(element.childNodes).map((child) => visit(child
|
|
2886
|
+
children: element.tagName === "span" ? [] : elements(element.childNodes).map((child) => visit(child))
|
|
2759
2887
|
};
|
|
2760
2888
|
};
|
|
2761
2889
|
const roots = elements(fragment.childNodes);
|
|
2762
2890
|
const root = roots[0];
|
|
2763
2891
|
if (root === void 0 || roots.length !== 1) return fail("An editable update must contain exactly its original root.");
|
|
2764
|
-
return visit(root
|
|
2892
|
+
return visit(root);
|
|
2765
2893
|
};
|
|
2766
2894
|
|
|
2767
2895
|
//#endregion
|
|
@@ -2937,18 +3065,6 @@ const offsetOf = (input, snapshot, digest) => {
|
|
|
2937
3065
|
if (cursor.version !== snapshot.version) throw new CliError("CONFLICT", "The canvas changed between resource pages.", "Restart the read at the current revision.");
|
|
2938
3066
|
return cursor.offset;
|
|
2939
3067
|
};
|
|
2940
|
-
const boundedPage = (envelope, all, offset, limit) => {
|
|
2941
|
-
const resources = [];
|
|
2942
|
-
const candidates = all.slice(offset, offset + limit);
|
|
2943
|
-
for (const entry of candidates) {
|
|
2944
|
-
const candidate = envelope([...resources, entry]);
|
|
2945
|
-
if (Buffer.byteLength(JSON.stringify(candidate)) > MAX_RESULT_BYTES) break;
|
|
2946
|
-
resources.push(entry);
|
|
2947
|
-
}
|
|
2948
|
-
const result = envelope(resources);
|
|
2949
|
-
if (resources.length === 0 && offset < all.length || Buffer.byteLength(JSON.stringify(result)) > MAX_RESULT_BYTES) throw new CliError("BAD_REQUEST", "One resource or scope exceeds the bounded read budget.", "Choose a smaller selection or inspect the resource in the editor.");
|
|
2950
|
-
return result;
|
|
2951
|
-
};
|
|
2952
3068
|
const readCanvasResources = (input, snapshot) => {
|
|
2953
3069
|
const scope = resolveCanvasReference(snapshot.reference, snapshot.scene);
|
|
2954
3070
|
if (!scope.ok) throw new CliError("NOT_FOUND", "The requested canvas scope is unavailable.", "Copy a current page or selection link; do not broaden the request.");
|
|
@@ -2985,18 +3101,12 @@ const readCanvasResources = (input, snapshot) => {
|
|
|
2985
3101
|
]
|
|
2986
3102
|
};
|
|
2987
3103
|
};
|
|
2988
|
-
|
|
3104
|
+
const budget = MAX_RESULT_BYTES - Buffer.byteLength(JSON.stringify(envelope([])));
|
|
3105
|
+
return envelope(boundedResultPage(all, offset, input.limit, budget).entries);
|
|
2989
3106
|
};
|
|
2990
3107
|
|
|
2991
3108
|
//#endregion
|
|
2992
3109
|
//#region src/application/canvas-transcript-page.use-case.ts
|
|
2993
|
-
const MAX_PAGE_BYTES = 48e3;
|
|
2994
|
-
const boundedCues = (offered) => {
|
|
2995
|
-
const cues = [...offered];
|
|
2996
|
-
while (Buffer.byteLength(JSON.stringify(cues), "utf8") > MAX_PAGE_BYTES) cues.pop();
|
|
2997
|
-
if (cues.length === 0 && offered.length > 0) throw new CliError("BAD_REQUEST", "One transcript cue exceeds the inline evidence budget.", "Read this source through the comprehensive transcript CLI; no partial cue was returned.");
|
|
2998
|
-
return cues;
|
|
2999
|
-
};
|
|
3000
3110
|
const canvasTranscriptPage = (transcript, request, scope) => {
|
|
3001
3111
|
if (transcript.state !== "ready") {
|
|
3002
3112
|
if (request.cursor !== void 0) throw new CliError("CONFLICT", "The transcript changed during pagination.", "Restart the read.");
|
|
@@ -3013,7 +3123,7 @@ const canvasTranscriptPage = (transcript, request, scope) => {
|
|
|
3013
3123
|
const matching = transcript.cues.filter((cue) => cue.endMs >= request.startMs && (request.endMs === void 0 || cue.startMs < request.endMs));
|
|
3014
3124
|
const offset = held?.offset ?? 0;
|
|
3015
3125
|
if (offset > matching.length) throw new CliError("BAD_REQUEST", "Transcript cursor offset is out of range.", "Restart the read.");
|
|
3016
|
-
const cues =
|
|
3126
|
+
const cues = boundedResultPage(matching, offset, request.limit).entries;
|
|
3017
3127
|
const nextOffset = offset + cues.length;
|
|
3018
3128
|
return {
|
|
3019
3129
|
state: "ready",
|
|
@@ -3233,7 +3343,7 @@ const createRevisionedCanvasCommandComposite = (remote) => ({ execute: async (in
|
|
|
3233
3343
|
};
|
|
3234
3344
|
const request = applyCanvasOperationsInputSchema.safeParse({
|
|
3235
3345
|
canvasId,
|
|
3236
|
-
documentFormatVersion:
|
|
3346
|
+
documentFormatVersion: 7,
|
|
3237
3347
|
mutationId: input.clientToken,
|
|
3238
3348
|
baseVersion: input.baseVersion,
|
|
3239
3349
|
operations,
|
|
@@ -3371,30 +3481,25 @@ const EMPTY_COMPILATION = {
|
|
|
3371
3481
|
const finishCanvasHtmlReconciliation = (document, prepared, compiled = EMPTY_COMPILATION) => {
|
|
3372
3482
|
const staged = stagedInsertions(document, compiled, prepared);
|
|
3373
3483
|
const root = boundRoot(prepared.root, compiled.idMap);
|
|
3374
|
-
|
|
3484
|
+
return [
|
|
3375
3485
|
...prepared.operations,
|
|
3376
3486
|
...compiled.operations,
|
|
3377
3487
|
...canvasHtmlStructureOperations(staged, root, prepared.removed)
|
|
3378
3488
|
];
|
|
3379
|
-
if (operations.length > 1e3) return invalid$2("The complete edit exceeds the canonical operation budget.");
|
|
3380
|
-
return operations;
|
|
3381
3489
|
};
|
|
3382
3490
|
|
|
3383
3491
|
//#endregion
|
|
3384
3492
|
//#region src/application/canvas-html-update-source.use-case.ts
|
|
3385
|
-
const MAX_NODES = CANVAS_HTML_LIMITS.nodes;
|
|
3386
3493
|
const identity = (element) => element.attrs.find((attribute) => attribute.name === "data-enhance-id")?.value;
|
|
3387
3494
|
const invalid$1 = (message) => {
|
|
3388
3495
|
throw new CliError("BAD_REQUEST", message, "Preserve retained identities and opaque placeholders. Add new populated subtrees without identity markers. No canvas changes were committed.");
|
|
3389
3496
|
};
|
|
3390
|
-
const collectElements = (children
|
|
3391
|
-
|
|
3392
|
-
return children.flatMap((child) => "tagName" in child ? [child, ...collectElements(child.childNodes, depth + 1)] : []);
|
|
3497
|
+
const collectElements = (children) => {
|
|
3498
|
+
return children.flatMap((child) => "tagName" in child ? [child, ...collectElements(child.childNodes)] : []);
|
|
3393
3499
|
};
|
|
3394
3500
|
const parseCanvasHtmlUpdate = (html) => {
|
|
3395
3501
|
const fragment = canvasEditableHtmlFragment(html);
|
|
3396
3502
|
const elements = collectElements(fragment.childNodes);
|
|
3397
|
-
if (elements.length > MAX_NODES) return invalid$1("The HTML exceeds the node budget.");
|
|
3398
3503
|
const reservedIds = new Set(elements.map((element) => identity(element)));
|
|
3399
3504
|
const fragments = [];
|
|
3400
3505
|
const visit = (element, parentId) => {
|
|
@@ -3405,7 +3510,6 @@ const parseCanvasHtmlUpdate = (html) => {
|
|
|
3405
3510
|
};
|
|
3406
3511
|
if (parentId === void 0) return invalid$1("The submitted HTML must retain its original root identity.");
|
|
3407
3512
|
if ([element, ...collectElements(element.childNodes)].some((node) => node.attrs.some((attribute) => ["data-enhance-id", "data-enhance-opaque"].includes(attribute.name)))) return invalid$1("A new HTML subtree cannot wrap retained identities or opaque placeholders. Insert the container and use canvas_arrange to move retained content into it.");
|
|
3408
|
-
if (fragments.length >= CANVAS_HTML_LIMITS.newSubtrees) return invalid$1("One update can compile at most 32 new subtrees.");
|
|
3409
3513
|
let key = `new_${String(fragments.length)}`;
|
|
3410
3514
|
while (reservedIds.has(key)) key = `_${key}`;
|
|
3411
3515
|
reservedIds.add(key);
|
|
@@ -3705,15 +3809,12 @@ const targetFailure = (error, target) => {
|
|
|
3705
3809
|
};
|
|
3706
3810
|
};
|
|
3707
3811
|
const plannedTargets = (request, clientTokens) => {
|
|
3708
|
-
const unassigned = request.targets.filter((target) => target.maxOutputPixels === void 0).length;
|
|
3709
|
-
const assignedPixels = request.targets.reduce((sum, target) => sum + (target.maxOutputPixels ?? 0), 0);
|
|
3710
|
-
const sharedLimit = Math.floor((RENDER_MAX_OUTPUT_PIXELS - assignedPixels) / Math.max(unassigned, 1));
|
|
3711
3812
|
return request.targets.map(({ id, maxOutputPixels, ...target }) => {
|
|
3712
3813
|
const retryClientToken = clientTokens.get(id);
|
|
3713
3814
|
if (retryClientToken === void 0) throw new TypeError("A batch target has no native render request key.");
|
|
3714
3815
|
return {
|
|
3715
3816
|
id,
|
|
3716
|
-
maxOutputPixels
|
|
3817
|
+
maxOutputPixels,
|
|
3717
3818
|
input: canvasRenderRequest({
|
|
3718
3819
|
...request,
|
|
3719
3820
|
...target
|
|
@@ -3730,34 +3831,24 @@ const renderTarget = async (render, target) => {
|
|
|
3730
3831
|
const file = canvasRenderFileSchema.safeParse(returned);
|
|
3731
3832
|
if (!file.success) return canvasRenderPendingSchema.parse(returned);
|
|
3732
3833
|
const pixels = file.data.width * file.data.height;
|
|
3733
|
-
if (!Number.isSafeInteger(pixels) || pixels <= 0 || pixels > target.maxOutputPixels) throw new CliError("INTERNAL", "The render exceeded its allocated pixel budget.", "Update the API and renderer together, then retry.", { reason: "RENDER_BUDGET_UNSUPPORTED" });
|
|
3834
|
+
if (!Number.isSafeInteger(pixels) || pixels <= 0 || target.maxOutputPixels !== void 0 && pixels > target.maxOutputPixels) throw new CliError("INTERNAL", "The render exceeded its allocated pixel budget.", "Update the API and renderer together, then retry.", { reason: "RENDER_BUDGET_UNSUPPORTED" });
|
|
3734
3835
|
return file.data;
|
|
3735
3836
|
} catch (error) {
|
|
3736
3837
|
return targetFailure(error, target);
|
|
3737
3838
|
}
|
|
3738
3839
|
};
|
|
3739
|
-
const NOT_STARTED = {
|
|
3740
|
-
state: "not_started",
|
|
3741
|
-
error: {
|
|
3742
|
-
code: "INTERNAL",
|
|
3743
|
-
message: "Earlier work could not enforce the render budget.",
|
|
3744
|
-
remediation: "Update the API and renderer together before retrying this batch."
|
|
3745
|
-
}
|
|
3746
|
-
};
|
|
3747
3840
|
const createRenderCanvasBatchComposite = (render) => ({ execute: async (offered, clientTokens) => {
|
|
3748
3841
|
const request = canvasRenderBatchRequestSchema.parse(offered);
|
|
3749
3842
|
const targets = plannedTargets(request, clientTokens);
|
|
3750
3843
|
const results = [];
|
|
3751
3844
|
let renderedPixels = 0;
|
|
3752
|
-
let isIncompatible = false;
|
|
3753
3845
|
for (const target of targets) {
|
|
3754
|
-
const outcome =
|
|
3846
|
+
const outcome = await renderTarget(render, target);
|
|
3755
3847
|
if ("jobId" in outcome) renderedPixels += outcome.width * outcome.height;
|
|
3756
|
-
if ("error" in outcome && outcome.error.fields?.["reason"] === "RENDER_BUDGET_UNSUPPORTED") isIncompatible = true;
|
|
3757
3848
|
results.push({
|
|
3758
3849
|
id: target.id,
|
|
3759
3850
|
target: target.input.target,
|
|
3760
|
-
maxOutputPixels: target.maxOutputPixels,
|
|
3851
|
+
...target.maxOutputPixels !== void 0 && { maxOutputPixels: target.maxOutputPixels },
|
|
3761
3852
|
outcome
|
|
3762
3853
|
});
|
|
3763
3854
|
}
|
|
@@ -3768,7 +3859,6 @@ const createRenderCanvasBatchComposite = (render) => ({ execute: async (offered,
|
|
|
3768
3859
|
canvasId: first.input.canvasId,
|
|
3769
3860
|
requestedVersion: request.expectedVersion,
|
|
3770
3861
|
complete: results.every((result) => "jobId" in result.outcome),
|
|
3771
|
-
maxOutputPixels: RENDER_MAX_OUTPUT_PIXELS,
|
|
3772
3862
|
renderedPixels,
|
|
3773
3863
|
results,
|
|
3774
3864
|
next: ["Inspect each delivered image alongside its target id. Collect pending images with operation_status and includeImage true. Retry uncertain outcomes with the identical batch and clientToken."]
|
|
@@ -3831,13 +3921,17 @@ const hashingTransform = (source, completed) => {
|
|
|
3831
3921
|
callback(/* @__PURE__ */ new Error(`prototype file ${source.path} changed while it was packaged`));
|
|
3832
3922
|
return;
|
|
3833
3923
|
}
|
|
3834
|
-
|
|
3835
|
-
|
|
3836
|
-
|
|
3837
|
-
|
|
3838
|
-
|
|
3839
|
-
|
|
3840
|
-
|
|
3924
|
+
try {
|
|
3925
|
+
completed({
|
|
3926
|
+
path: source.path,
|
|
3927
|
+
contentType: source.contentType,
|
|
3928
|
+
bytes,
|
|
3929
|
+
sha256: hash.digest("hex")
|
|
3930
|
+
});
|
|
3931
|
+
callback();
|
|
3932
|
+
} catch (error) {
|
|
3933
|
+
callback(error instanceof Error ? error : /* @__PURE__ */ new Error("prototype manifest failed"));
|
|
3934
|
+
}
|
|
3841
3935
|
}
|
|
3842
3936
|
});
|
|
3843
3937
|
};
|
|
@@ -3848,7 +3942,7 @@ const addManifest = (input) => {
|
|
|
3848
3942
|
files: input.files.map((file) => input.completed.get(file.path))
|
|
3849
3943
|
});
|
|
3850
3944
|
const body = Buffer.from(JSON.stringify(manifest), "utf8");
|
|
3851
|
-
if (body.byteLength > input.limits.manifestBytes) throw badRequest$1("The prototype manifest is too large.", `Shorten paths or reduce metadata below ${String(input.limits.manifestBytes)} bytes.`);
|
|
3945
|
+
if (input.limits.manifestBytes !== void 0 && body.byteLength > input.limits.manifestBytes) throw badRequest$1("The prototype manifest is too large.", `Shorten paths or reduce metadata below ${String(input.limits.manifestBytes)} bytes.`);
|
|
3852
3946
|
input.zip.addBuffer(body, PROTOTYPE_ARTIFACT_MANIFEST_PATH, {
|
|
3853
3947
|
mtime: NORMALIZED_MTIME,
|
|
3854
3948
|
mode: REGULAR_FILE_MODE,
|
|
@@ -3874,7 +3968,12 @@ const addPrototypeFile = (zip, input, complete) => {
|
|
|
3874
3968
|
...options,
|
|
3875
3969
|
size: source.bytes
|
|
3876
3970
|
}, (callback) => {
|
|
3877
|
-
|
|
3971
|
+
const stream = createReadStream(source.absolutePath);
|
|
3972
|
+
const hashing = hashingTransform(source, complete);
|
|
3973
|
+
stream.on("error", (error) => hashing.destroy(error));
|
|
3974
|
+
hashing.on("error", (error) => zip.emit("error", error));
|
|
3975
|
+
hashing.on("close", () => stream.destroy());
|
|
3976
|
+
callback(null, stream.pipe(hashing));
|
|
3878
3977
|
});
|
|
3879
3978
|
return;
|
|
3880
3979
|
}
|
|
@@ -3887,14 +3986,35 @@ const addPrototypeFile = (zip, input, complete) => {
|
|
|
3887
3986
|
sha256: createHash("sha256").update(content).digest("hex")
|
|
3888
3987
|
});
|
|
3889
3988
|
};
|
|
3890
|
-
const
|
|
3891
|
-
|
|
3892
|
-
|
|
3893
|
-
|
|
3894
|
-
|
|
3895
|
-
|
|
3896
|
-
for (const input of batch) addPrototypeFile(zip, input, complete);
|
|
3989
|
+
const addAvailableFiles = (zip, batch, complete) => {
|
|
3990
|
+
const included = [];
|
|
3991
|
+
for (const available of batch) {
|
|
3992
|
+
if (available === null) continue;
|
|
3993
|
+
addPrototypeFile(zip, available, complete);
|
|
3994
|
+
included.push(available.source);
|
|
3897
3995
|
}
|
|
3996
|
+
return included;
|
|
3997
|
+
};
|
|
3998
|
+
const addPrototypeFiles = async (zip, input, complete) => {
|
|
3999
|
+
const included = [];
|
|
4000
|
+
for (let offset = 0; offset < input.files.length; offset += READ_BATCH_SIZE) {
|
|
4001
|
+
const batch = await Promise.all(input.files.slice(offset, offset + READ_BATCH_SIZE).map(async (source) => {
|
|
4002
|
+
try {
|
|
4003
|
+
const content = source.bytes <= SMALL_FILE_BYTES ? await readFile(source.absolutePath) : null;
|
|
4004
|
+
if (content === null) await access(source.absolutePath, constants.R_OK);
|
|
4005
|
+
if (content !== null && content.byteLength !== source.bytes) throw new Error(`prototype file ${source.path} changed while it was packaged`);
|
|
4006
|
+
return {
|
|
4007
|
+
source,
|
|
4008
|
+
content
|
|
4009
|
+
};
|
|
4010
|
+
} catch (error) {
|
|
4011
|
+
if (source.path === input.entryPath) throw error;
|
|
4012
|
+
return null;
|
|
4013
|
+
}
|
|
4014
|
+
}));
|
|
4015
|
+
included.push(...addAvailableFiles(zip, batch, complete));
|
|
4016
|
+
}
|
|
4017
|
+
return included;
|
|
3898
4018
|
};
|
|
3899
4019
|
const createPrototypeZipAdapter = async (input) => {
|
|
3900
4020
|
const zip = new ZipFile();
|
|
@@ -3907,16 +4027,22 @@ const createPrototypeZipAdapter = async (input) => {
|
|
|
3907
4027
|
const packaged = { manifest: null };
|
|
3908
4028
|
const output = pipeline(zip.outputStream, hashing, createWriteStream(input.artifactPath));
|
|
3909
4029
|
zip.on("error", (error) => hashing.destroy(error instanceof Error ? error : /* @__PURE__ */ new Error("prototype ZIP failed")));
|
|
3910
|
-
|
|
3911
|
-
|
|
3912
|
-
if (packaged.manifest === null && completed.size ===
|
|
4030
|
+
let included = null;
|
|
4031
|
+
const finish = () => {
|
|
4032
|
+
if (included !== null && packaged.manifest === null && completed.size === included.length) packaged.manifest = addManifest({
|
|
3913
4033
|
zip,
|
|
3914
4034
|
completed,
|
|
3915
|
-
...input
|
|
4035
|
+
...input,
|
|
4036
|
+
files: included
|
|
3916
4037
|
});
|
|
3917
4038
|
};
|
|
4039
|
+
const complete = (file) => {
|
|
4040
|
+
completed.set(file.path, file);
|
|
4041
|
+
finish();
|
|
4042
|
+
};
|
|
3918
4043
|
try {
|
|
3919
|
-
await addPrototypeFiles(zip, input
|
|
4044
|
+
included = await addPrototypeFiles(zip, input, complete);
|
|
4045
|
+
finish();
|
|
3920
4046
|
} catch (error) {
|
|
3921
4047
|
hashing.destroy(error instanceof Error ? error : /* @__PURE__ */ new Error("prototype ZIP failed"));
|
|
3922
4048
|
await output;
|
|
@@ -3928,7 +4054,8 @@ const createPrototypeZipAdapter = async (input) => {
|
|
|
3928
4054
|
return {
|
|
3929
4055
|
manifest: packaged.manifest,
|
|
3930
4056
|
bytes: artifactStats.size,
|
|
3931
|
-
sha256: hash.digest("hex")
|
|
4057
|
+
sha256: hash.digest("hex"),
|
|
4058
|
+
unavailableFileCount: input.files.length - completed.size
|
|
3932
4059
|
};
|
|
3933
4060
|
};
|
|
3934
4061
|
|
|
@@ -3975,9 +4102,13 @@ const validatePath = (relativePath, limits) => {
|
|
|
3975
4102
|
if (!prototypeArtifactPathSchema.safeParse(relativePath).success) throw badRequest(`Cannot package the prototype path ${relativePath}.`, "Use portable relative NFC paths outside the reserved __enhance directory.");
|
|
3976
4103
|
if (byteLength(relativePath) > limits.pathBytes) throw badRequest(`The prototype path ${relativePath} is too long.`, `Shorten it to at most ${String(limits.pathBytes)} UTF-8 bytes.`);
|
|
3977
4104
|
};
|
|
3978
|
-
const walk = async (root, directory, ancestors,
|
|
4105
|
+
const walk = async (root, directory, ancestors, options) => {
|
|
4106
|
+
const { limits, unavailable } = options;
|
|
3979
4107
|
const resolvedDirectory = await realpath(directory);
|
|
3980
|
-
if (ancestors.has(resolvedDirectory))
|
|
4108
|
+
if (ancestors.has(resolvedDirectory)) {
|
|
4109
|
+
unavailable();
|
|
4110
|
+
return [];
|
|
4111
|
+
}
|
|
3981
4112
|
const nextAncestors = new Set(ancestors).add(resolvedDirectory);
|
|
3982
4113
|
const { readdir } = await import("node:fs/promises");
|
|
3983
4114
|
const entries = await readdir(directory, { withFileTypes: true });
|
|
@@ -3987,10 +4118,17 @@ const walk = async (root, directory, ancestors, limits) => {
|
|
|
3987
4118
|
const absolutePath = path.join(directory, entry.name);
|
|
3988
4119
|
const stats = await statsFor(absolutePath);
|
|
3989
4120
|
if (stats?.isDirectory() === true) {
|
|
3990
|
-
|
|
4121
|
+
try {
|
|
4122
|
+
files.push(...await walk(root, absolutePath, nextAncestors, options));
|
|
4123
|
+
} catch {
|
|
4124
|
+
unavailable();
|
|
4125
|
+
}
|
|
4126
|
+
continue;
|
|
4127
|
+
}
|
|
4128
|
+
if (stats?.isFile() !== true) {
|
|
4129
|
+
unavailable();
|
|
3991
4130
|
continue;
|
|
3992
4131
|
}
|
|
3993
|
-
if (stats?.isFile() !== true) throw badRequest(`Cannot read ${absolutePath} as a prototype file.`, "Pass a directory containing only regular files and directory links.");
|
|
3994
4132
|
const relativePath = path.relative(root, absolutePath).split(path.sep).join("/").normalize("NFC");
|
|
3995
4133
|
validatePath(relativePath, limits);
|
|
3996
4134
|
files.push({
|
|
@@ -4004,7 +4142,7 @@ const walk = async (root, directory, ancestors, limits) => {
|
|
|
4004
4142
|
};
|
|
4005
4143
|
const validateSources = (files, entryPath, limits) => {
|
|
4006
4144
|
if (files.length === 0) throw badRequest("The prototype build is empty.", "Build the app before publishing it.");
|
|
4007
|
-
if (files.length > limits.fileCount) throw badRequest(`The prototype has ${String(files.length)} files.`, `This environment currently accepts ${String(limits.fileCount)} files per deployment.`);
|
|
4145
|
+
if (limits.fileCount !== void 0 && files.length > limits.fileCount) throw badRequest(`The prototype has ${String(files.length)} files.`, `This environment currently accepts ${String(limits.fileCount)} files per deployment.`);
|
|
4008
4146
|
const folded = /* @__PURE__ */ new Set();
|
|
4009
4147
|
let totalBytes = 0;
|
|
4010
4148
|
for (const file of files) {
|
|
@@ -4013,12 +4151,20 @@ const validateSources = (files, entryPath, limits) => {
|
|
|
4013
4151
|
folded.add(key);
|
|
4014
4152
|
if (file.bytes > limits.fileBytes) throw badRequest(`The prototype file ${file.path} is too large.`, `This environment accepts ${String(limits.fileBytes)} bytes in one runtime file.`);
|
|
4015
4153
|
totalBytes += file.bytes;
|
|
4016
|
-
if (totalBytes > limits.expandedBytes) throw badRequest("The prototype build is too large.", `This environment accepts ${String(limits.expandedBytes)} expanded bytes.`);
|
|
4154
|
+
if (limits.expandedBytes !== void 0 && totalBytes > limits.expandedBytes) throw badRequest("The prototype build is too large.", `This environment accepts ${String(limits.expandedBytes)} expanded bytes.`);
|
|
4017
4155
|
}
|
|
4018
4156
|
const entry = files.find((file) => file.path === entryPath);
|
|
4019
4157
|
if (entry === void 0) throw badRequest(`The prototype entry ${entryPath} is missing.`, "Pass --entry with an HTML file inside the build directory.");
|
|
4020
4158
|
if (!entry.contentType.startsWith("text/html")) throw badRequest(`The prototype entry ${entryPath} is not HTML.`, "Pass an HTML entry file such as index.html.");
|
|
4021
4159
|
};
|
|
4160
|
+
const reportPackaging = (fileCount, unavailableFileCount) => {
|
|
4161
|
+
try {
|
|
4162
|
+
performance$1.mark("enhance.prototype.packaging", { detail: {
|
|
4163
|
+
fileCount,
|
|
4164
|
+
unavailableFileCount
|
|
4165
|
+
} });
|
|
4166
|
+
} catch {}
|
|
4167
|
+
};
|
|
4022
4168
|
const packageArtifact = async (input) => {
|
|
4023
4169
|
const root = path.resolve(input.directory);
|
|
4024
4170
|
const rootStats = await statsFor(root);
|
|
@@ -4026,7 +4172,13 @@ const packageArtifact = async (input) => {
|
|
|
4026
4172
|
if (!rootStats.isDirectory()) throw badRequest(`${root} is not an unpacked build directory.`, "Pass the build directory; the CLI creates the ZIP artifact automatically.");
|
|
4027
4173
|
const entryPath = input.entryPath.split(path.sep).join("/").normalize("NFC");
|
|
4028
4174
|
validatePath(entryPath, input.limits);
|
|
4029
|
-
|
|
4175
|
+
let unavailableFileCount = 0;
|
|
4176
|
+
const files = await walk(root, root, /* @__PURE__ */ new Set(), {
|
|
4177
|
+
limits: input.limits,
|
|
4178
|
+
unavailable: () => {
|
|
4179
|
+
unavailableFileCount += 1;
|
|
4180
|
+
}
|
|
4181
|
+
});
|
|
4030
4182
|
validateSources(files, entryPath, input.limits);
|
|
4031
4183
|
const tempDirectory = await mkdtemp(path.join(tmpdir(), "enhance-prototype-artifact-"));
|
|
4032
4184
|
const artifactPath = path.join(tempDirectory, "artifact.zip");
|
|
@@ -4037,6 +4189,8 @@ const packageArtifact = async (input) => {
|
|
|
4037
4189
|
entryPath,
|
|
4038
4190
|
limits: input.limits
|
|
4039
4191
|
});
|
|
4192
|
+
unavailableFileCount += packaged.unavailableFileCount;
|
|
4193
|
+
reportPackaging(packaged.manifest.files.length, unavailableFileCount);
|
|
4040
4194
|
return {
|
|
4041
4195
|
identity: {
|
|
4042
4196
|
protocolVersion: 1,
|
|
@@ -4379,6 +4533,7 @@ const readLocalMcpEnvironment = () => {
|
|
|
4379
4533
|
|
|
4380
4534
|
//#endregion
|
|
4381
4535
|
//#region src/infrastructure/http-remote.adapter.ts
|
|
4536
|
+
const DIRECT_CLIENT = { path: "direct_cli" };
|
|
4382
4537
|
const HEALTH_TIMEOUT_MS = 4e3;
|
|
4383
4538
|
const NOT_FOUND_STATUS = 404;
|
|
4384
4539
|
const FORBIDDEN_STATUS = 403;
|
|
@@ -4405,13 +4560,14 @@ const fetchApi = async (input, init) => {
|
|
|
4405
4560
|
if (!response.ok && response.headers.get("content-type")?.includes("application/json") !== true) throw httpFailure(input, response.status);
|
|
4406
4561
|
return response;
|
|
4407
4562
|
};
|
|
4408
|
-
const clientFor = (apiUrl, token, idempotencyKey = null) => createTRPCUntypedClient({ links: [httpLink({
|
|
4563
|
+
const clientFor = (apiUrl, token, idempotencyKey = null, clientMetadata = DIRECT_CLIENT) => createTRPCUntypedClient({ links: [httpLink({
|
|
4409
4564
|
url: `${apiUrl}/trpc`,
|
|
4410
4565
|
fetch: async (input, init) => fetchApi(input, {
|
|
4411
4566
|
...init,
|
|
4412
4567
|
signal: init?.signal ?? null
|
|
4413
4568
|
}),
|
|
4414
4569
|
headers: {
|
|
4570
|
+
[AGENT_CLIENT_HEADER]: JSON.stringify(clientMetadata),
|
|
4415
4571
|
...token !== null && { authorization: `Bearer ${token}` },
|
|
4416
4572
|
...idempotencyKey !== null && { "x-enhance-idempotency-key": idempotencyKey }
|
|
4417
4573
|
}
|
|
@@ -4475,32 +4631,33 @@ const health = async (apiUrl) => {
|
|
|
4475
4631
|
};
|
|
4476
4632
|
}
|
|
4477
4633
|
};
|
|
4478
|
-
const
|
|
4634
|
+
const upload = async (input) => {
|
|
4635
|
+
const isStreaming = !(input.body instanceof Uint8Array);
|
|
4636
|
+
const body = isStreaming ? Readable.toWeb(input.body) : input.body;
|
|
4637
|
+
const request = {
|
|
4638
|
+
method: "PUT",
|
|
4639
|
+
headers: input.headers,
|
|
4640
|
+
body,
|
|
4641
|
+
...isStreaming && { duplex: "half" }
|
|
4642
|
+
};
|
|
4643
|
+
const response = await fetch(input.url, request);
|
|
4644
|
+
if (!response.ok) throw new CliError("INTERNAL", `Signed upload answered HTTP ${String(response.status)}.`, "Retry the fixture command with the same source file.");
|
|
4645
|
+
const etag = response.headers.get("etag");
|
|
4646
|
+
if (etag === null || etag === "") throw new CliError("INTERNAL", "Signed upload returned no ETag.", "Report the storage response and stop.");
|
|
4647
|
+
return etag.replaceAll("\"", "");
|
|
4648
|
+
};
|
|
4649
|
+
const createHttpRemoteAdapter = (apiUrl, credentials, mutationKey, clientMetadata = DIRECT_CLIENT) => {
|
|
4479
4650
|
const normalized = apiUrl.replace(/\/$/, "");
|
|
4480
4651
|
return {
|
|
4481
4652
|
authenticationConfig: async () => authenticationConfig(normalized),
|
|
4482
4653
|
oauthMetadata,
|
|
4483
4654
|
exchangeOauthCode,
|
|
4484
|
-
query: async (path, input) => remoteRequest(async () => clientFor(normalized, await credentials.read()).query(path, input)),
|
|
4485
|
-
queryWithToken: async (path, input, token) => remoteRequest(async () => clientFor(normalized, token).query(path, input)),
|
|
4486
|
-
mutate: async (procedure, input) => remoteRequest(async () => clientFor(normalized, await credentials.read(), mutationKey.current(procedure, input)).mutation(procedure, input)),
|
|
4487
|
-
mutateWithToken: async (procedure, input, token) => remoteRequest(async () => clientFor(normalized, token).mutation(procedure, input)),
|
|
4655
|
+
query: async (path, input, options) => remoteRequest(async () => clientFor(normalized, await credentials.read(), null, clientMetadata).query(path, input, options)),
|
|
4656
|
+
queryWithToken: async (path, input, token) => remoteRequest(async () => clientFor(normalized, token, null, clientMetadata).query(path, input)),
|
|
4657
|
+
mutate: async (procedure, input) => remoteRequest(async () => clientFor(normalized, await credentials.read(), mutationKey.current(procedure, input), clientMetadata).mutation(procedure, input)),
|
|
4658
|
+
mutateWithToken: async (procedure, input, token) => remoteRequest(async () => clientFor(normalized, token, null, clientMetadata).mutation(procedure, input)),
|
|
4488
4659
|
download,
|
|
4489
|
-
upload
|
|
4490
|
-
const isStreaming = !(input.body instanceof Uint8Array);
|
|
4491
|
-
const body = isStreaming ? Readable.toWeb(input.body) : input.body;
|
|
4492
|
-
const request = {
|
|
4493
|
-
method: "PUT",
|
|
4494
|
-
headers: input.headers,
|
|
4495
|
-
body,
|
|
4496
|
-
...isStreaming && { duplex: "half" }
|
|
4497
|
-
};
|
|
4498
|
-
const response = await fetch(input.url, request);
|
|
4499
|
-
if (!response.ok) throw new CliError("INTERNAL", `Signed upload answered HTTP ${String(response.status)}.`, "Retry the fixture command with the same source file.");
|
|
4500
|
-
const etag = response.headers.get("etag");
|
|
4501
|
-
if (etag === null || etag === "") throw new CliError("INTERNAL", "Signed upload returned no ETag.", "Report the storage response and stop.");
|
|
4502
|
-
return etag.replaceAll("\"", "");
|
|
4503
|
-
},
|
|
4660
|
+
upload,
|
|
4504
4661
|
health: async () => health(normalized)
|
|
4505
4662
|
};
|
|
4506
4663
|
};
|
|
@@ -4528,4 +4685,4 @@ const createMutationKeyAdapter = () => {
|
|
|
4528
4685
|
};
|
|
4529
4686
|
|
|
4530
4687
|
//#endregion
|
|
4531
|
-
export {
|
|
4688
|
+
export { createAuthUseCase as S, assertCanvasReferenceOperations as _, readRemoteMcpEnvironment as a, createCanvasActivityComposite as b, createPrototypeArtifactAdapter as c, createRenderFileAdapter as d, readCanvasReferenceScene as f, createEditCanvasComposite as g, fromCapabilityReference as h, readLocalMcpEnvironment as i, createPublishCanvasPrototypeComposite as l, boundedResultPage as m, createHttpRemoteAdapter as n, createOauthLoopbackAdapter as o, createWriteHtmlCanvasComposite as p, readCliEnvironment as r, createCapabilityInvocationAdapter as s, createMutationKeyAdapter as t, createImportCanvasAssetComposite as u, sceneAtVersion as v, createRenderCanvasComposite as x, createApplyCanvasComposite as y };
|