@enhance-eng/enhance 0.1.37 → 0.1.39
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-i4KnVAYs.mjs → cli-output-identity.lib-DgHRuXTI.mjs} +1325 -393
- package/dist/main.mjs +335 -388
- package/dist/{mcp-invocation.adapter-CBnzmPZl.mjs → mcp-invocation.adapter-CjZnnMCd.mjs} +18 -13
- package/dist/mcp-main.mjs +7 -7
- package/dist/{mcp-server.adapter-DC9gAePw.mjs → mcp-server.adapter-DOHJxL6l.mjs} +1 -1
- package/dist/mcp.mjs +2 -2
- package/dist/{mutation-key.adapter-Ck8nOqke.mjs → mutation-key.adapter-BWkNj5jp.mjs} +4060 -134
- package/dist/remote-mcp-main.mjs +5 -5
- package/package.json +5 -1
package/dist/main.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { $t as createOrganisationOutputSchema,
|
|
3
|
-
import { S as createAuthUseCase, _ as assertCanvasReferenceOperations, b as createCanvasActivityComposite, d as createRenderFileAdapter, f as readCanvasReferenceScene, g as createEditCanvasComposite, h as fromCapabilityReference, n as createHttpRemoteAdapter, o as createOauthLoopbackAdapter, p as createWriteHtmlCanvasComposite, r as readCliEnvironment, s as createCapabilityInvocationAdapter, t as createMutationKeyAdapter, v as sceneAtVersion, x as createRenderCanvasComposite, y as createApplyCanvasComposite } from "./mutation-key.adapter-
|
|
2
|
+
import { $t as createOrganisationOutputSchema, At as PartialBatchError, Ct as canvasEditsSchema, Dt as fromCanvasReference, Et as canvasReferenceRenderTarget, Ft as createScreenOutputSchema, It as appendRecordingChunkOutputSchema, Lt as completeRecordingOutputSchema, Mn as beginCanvasActivityOutputSchema, Mr as canvasSchema, Nn as canvasAgentActivityPhaseSchema, Nt as appErrorSchema, Ot as hasCanvasReferenceScope, Pt as completeScreenOutputSchema, Qn as canvasOperationSchema, Xn as getCanvasDocumentOutputSchema, Zn as saveCanvasDocumentOutputSchema, _ as PROCEDURE_DESCRIPTIONS, a as toFailurePayload, ar as canvasWorldBoundsSchema, d as ProcessExitError, et as canvasRenderScopedInputSchema, f as createCapabilityCatalogAdapter, fr as canvasAuthoredLayoutValueOf, g as OPTION_DESCRIPTIONS, gr as canvasLayoutPriorityDeclarations, gt as canvasFindInputSchema, hr as canvasLayoutMainAxisOf, i as toExitCode, it as canvasRemoveCapabilityInputSchema, jt as CliError, k as operationStatusInputSchema, kt as parseCanvasReference, l as toSharedCapabilities, lt as canvasUpdateHtmlCapabilityInputSchema, m as createCapabilityPolicyAdapter, mr as canvasAxisStyleProperties, n as withCommandName, nn as withFixtureScreen, p as createRouterShapeAdapter, pr as canvasAuthoredStyleDeclarations, r as toCanvasAuthoringResult, st as canvasReadInputSchema, t as withCommandInFailure, tn as emptyFixtureDocument, u as createMcpCapabilityDiscoveryAdapter, ur as canvasReadableSceneDocumentSchema, wn as canvasTextRunsOf, wt as assertCanvasReferenceNodes, zt as startRecordingOutputSchema } from "./cli-output-identity.lib-DgHRuXTI.mjs";
|
|
3
|
+
import { C as canvasRadialGradientSvg, D as canvasAngularGradientSvg, E as canvasDiamondGradientSvg, O as canvasColorCss, S as createAuthUseCase, T as canvasFilterListCss, _ as assertCanvasReferenceOperations, b as createCanvasActivityComposite, d as createRenderFileAdapter, f as readCanvasReferenceScene, g as createEditCanvasComposite, h as fromCapabilityReference, k as compareCanvasSortKeys, n as createHttpRemoteAdapter, o as createOauthLoopbackAdapter, p as createWriteHtmlCanvasComposite, r as readCliEnvironment, s as createCapabilityInvocationAdapter, t as createMutationKeyAdapter, v as sceneAtVersion, w as canvasLinearGradientSvg, x as createRenderCanvasComposite, y as createApplyCanvasComposite } from "./mutation-key.adapter-BWkNj5jp.mjs";
|
|
4
4
|
import { t as toCapabilityInventory } from "./capability-inventory.mapper-DyYXyVBJ.mjs";
|
|
5
5
|
import { t as createFileCredentialAdapter } from "./file-credential.adapter-C78gc9OK.mjs";
|
|
6
6
|
import process from "node:process";
|
|
@@ -17,152 +17,6 @@ import { mkdir, readFile, rename, stat, writeFile } from "node:fs/promises";
|
|
|
17
17
|
import { channel } from "node:diagnostics_channel";
|
|
18
18
|
import { proxify } from "trpc-cli/dist/proxify.js";
|
|
19
19
|
|
|
20
|
-
//#region ../../packages/contract/src/canvas/canvas-color-css.lib.ts
|
|
21
|
-
const BYTE_MAX = 255;
|
|
22
|
-
const CHANNEL_PRECISION = 1e6;
|
|
23
|
-
const roundedChannel = (value) => Math.round(value * BYTE_MAX * CHANNEL_PRECISION) / CHANNEL_PRECISION;
|
|
24
|
-
const canvasColorCss = (color, opacity = 1) => {
|
|
25
|
-
const alpha = color.alpha * opacity;
|
|
26
|
-
if (color.space === "srgb") {
|
|
27
|
-
const channels = [
|
|
28
|
-
color.red,
|
|
29
|
-
color.green,
|
|
30
|
-
color.blue
|
|
31
|
-
].map((channel) => String(roundedChannel(channel))).join(" ");
|
|
32
|
-
return alpha === 1 ? `rgb(${channels})` : `rgb(${channels} / ${String(alpha)})`;
|
|
33
|
-
}
|
|
34
|
-
const channels = `${String(color.red)} ${String(color.green)} ${String(color.blue)}`;
|
|
35
|
-
return `color(${color.space} ${channels} / ${String(alpha)})`;
|
|
36
|
-
};
|
|
37
|
-
|
|
38
|
-
//#endregion
|
|
39
|
-
//#region ../../packages/contract/src/canvas/canvas-gradient-field.lib.ts
|
|
40
|
-
const UNIT_BOUNDS = {
|
|
41
|
-
x: 0,
|
|
42
|
-
y: 0,
|
|
43
|
-
width: 1,
|
|
44
|
-
height: 1
|
|
45
|
-
};
|
|
46
|
-
const fieldPoint = (paint, point) => {
|
|
47
|
-
const [a, b, c, d, e, f] = paint.transform;
|
|
48
|
-
const determinant = a * d - b * c;
|
|
49
|
-
const x = point.x - e, y = point.y - f;
|
|
50
|
-
return {
|
|
51
|
-
x: (d * x - c * y) / determinant,
|
|
52
|
-
y: (a * y - b * x) / determinant
|
|
53
|
-
};
|
|
54
|
-
};
|
|
55
|
-
const canvasGradientFieldCoordinates = (paint, bounds = UNIT_BOUNDS) => [
|
|
56
|
-
{
|
|
57
|
-
x: bounds.x,
|
|
58
|
-
y: bounds.y
|
|
59
|
-
},
|
|
60
|
-
{
|
|
61
|
-
x: bounds.x + bounds.width,
|
|
62
|
-
y: bounds.y
|
|
63
|
-
},
|
|
64
|
-
{
|
|
65
|
-
x: bounds.x,
|
|
66
|
-
y: bounds.y + bounds.height
|
|
67
|
-
},
|
|
68
|
-
{
|
|
69
|
-
x: bounds.x + bounds.width,
|
|
70
|
-
y: bounds.y + bounds.height
|
|
71
|
-
}
|
|
72
|
-
].flatMap((point) => {
|
|
73
|
-
const local = fieldPoint(paint, point);
|
|
74
|
-
return [local.x, local.y];
|
|
75
|
-
});
|
|
76
|
-
|
|
77
|
-
//#endregion
|
|
78
|
-
//#region ../../packages/contract/src/canvas/canvas-angular-gradient.lib.ts
|
|
79
|
-
const HALF$1 = .5;
|
|
80
|
-
const FULL_TURN = 360;
|
|
81
|
-
const PERCENT$4 = 100;
|
|
82
|
-
const FIELD_UNIT = 1024;
|
|
83
|
-
const LINEAR_COEFFICIENTS = 4;
|
|
84
|
-
const gradient = (paint, center, isAlpha) => {
|
|
85
|
-
const stops = paint.stops.map((stop) => {
|
|
86
|
-
return `${isAlpha ? `rgb(255 255 255 / ${String(stop.color.alpha * paint.opacity)})` : canvasColorCss({
|
|
87
|
-
...stop.color,
|
|
88
|
-
alpha: 1
|
|
89
|
-
})} ${String(stop.position * FULL_TURN)}deg`;
|
|
90
|
-
});
|
|
91
|
-
return `conic-gradient(from 90deg at ${String(center)}% ${String(center)}% in srgb, ${stops.join(", ")})`;
|
|
92
|
-
};
|
|
93
|
-
/** Separate alpha from color so translucent stops interpolate straight sRGB, as copied by Figma. */
|
|
94
|
-
const canvasAngularGradientField = (paint, bounds) => {
|
|
95
|
-
const coordinates = canvasGradientFieldCoordinates(paint, bounds);
|
|
96
|
-
const low = Math.min(0, ...coordinates);
|
|
97
|
-
const span = Math.max(1, ...coordinates) - low;
|
|
98
|
-
const center = (HALF$1 - low) / span * PERCENT$4;
|
|
99
|
-
const matrix = paint.transform.map((value, index) => index < LINEAR_COEFFICIENTS ? value / FIELD_UNIT : value);
|
|
100
|
-
const style = `width:100%;height:100%;background-image:${gradient(paint, center, false)};mask-image:${gradient(paint, center, true)};`;
|
|
101
|
-
return `<g transform="matrix(${matrix.map(String).join(" ")})"><foreignObject x="${String(low * FIELD_UNIT)}" y="${String(low * FIELD_UNIT)}" width="${String(span * FIELD_UNIT)}" height="${String(span * FIELD_UNIT)}" overflow="visible"><div xmlns="http://www.w3.org/1999/xhtml" style="${style}"></div></foreignObject></g>`;
|
|
102
|
-
};
|
|
103
|
-
const canvasAngularGradientSvg = (paint) => `<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewBox="0 0 1 1" preserveAspectRatio="none">${canvasAngularGradientField(paint)}</svg>`;
|
|
104
|
-
|
|
105
|
-
//#endregion
|
|
106
|
-
//#region ../../packages/contract/src/canvas/canvas-diamond-gradient.lib.ts
|
|
107
|
-
const HALF = .5;
|
|
108
|
-
const QUARTER = .25;
|
|
109
|
-
/** Each quadrant is a linear field with slope 2*(abs(x-.5)+abs(y-.5)). */
|
|
110
|
-
const canvasDiamondGradientField = (paint, id = "field", bounds) => {
|
|
111
|
-
const coordinates = canvasGradientFieldCoordinates(paint, bounds);
|
|
112
|
-
const extent = Math.max(HALF, ...coordinates.map((value) => Math.abs(value - HALF))) + 1;
|
|
113
|
-
const low = HALF - extent, high = HALF + extent;
|
|
114
|
-
const quadrants = [
|
|
115
|
-
{
|
|
116
|
-
x: .75,
|
|
117
|
-
y: .75,
|
|
118
|
-
points: `.5,.5 ${String(high)},.5 ${String(high)},${String(high)} .5,${String(high)}`
|
|
119
|
-
},
|
|
120
|
-
{
|
|
121
|
-
x: QUARTER,
|
|
122
|
-
y: .75,
|
|
123
|
-
points: `.5,.5 .5,${String(high)} ${String(low)},${String(high)} ${String(low)},.5`
|
|
124
|
-
},
|
|
125
|
-
{
|
|
126
|
-
x: QUARTER,
|
|
127
|
-
y: QUARTER,
|
|
128
|
-
points: `.5,.5 ${String(low)},.5 ${String(low)},${String(low)} .5,${String(low)}`
|
|
129
|
-
},
|
|
130
|
-
{
|
|
131
|
-
x: .75,
|
|
132
|
-
y: QUARTER,
|
|
133
|
-
points: `.5,.5 .5,${String(low)} ${String(high)},${String(low)} ${String(high)},.5`
|
|
134
|
-
}
|
|
135
|
-
];
|
|
136
|
-
const stops = paint.stops.map((stop) => `<stop offset="${String(stop.position)}" stop-color="${canvasColorCss({
|
|
137
|
-
...stop.color,
|
|
138
|
-
alpha: 1
|
|
139
|
-
})}" stop-opacity="${String(stop.color.alpha * paint.opacity)}" />`).join("");
|
|
140
|
-
const definitions = quadrants.map((quadrant, index) => `<linearGradient id="${id}-${String(index)}" gradientUnits="userSpaceOnUse" x1=".5" y1=".5" x2="${String(quadrant.x)}" y2="${String(quadrant.y)}" color-interpolation="sRGB">${stops}</linearGradient>`).join("");
|
|
141
|
-
const fields = quadrants.map((quadrant, index) => `<polygon points="${quadrant.points}" fill="url(#${id}-${String(index)})" shape-rendering="crispEdges" />`).join("");
|
|
142
|
-
return `<defs>${definitions}</defs><g transform="matrix(${paint.transform.map(String).join(" ")})">${fields}</g>`;
|
|
143
|
-
};
|
|
144
|
-
const canvasDiamondGradientSvg = (paint) => `<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewBox="0 0 1 1" preserveAspectRatio="none">${canvasDiamondGradientField(paint)}</svg>`;
|
|
145
|
-
|
|
146
|
-
//#endregion
|
|
147
|
-
//#region ../../packages/contract/src/canvas/canvas-filter.lib.ts
|
|
148
|
-
const PERCENT$3 = 100;
|
|
149
|
-
/** Radius/2 preserves the existing Gaussian approximation, not native sampling parity. */
|
|
150
|
-
const canvasBlurStandardDeviation = (filter) => filter.parameter === "radius" ? filter.value / 2 : filter.value;
|
|
151
|
-
const filterCss = (filter) => {
|
|
152
|
-
switch (filter.kind) {
|
|
153
|
-
case "blur": return `blur(${String(canvasBlurStandardDeviation(filter))}px)`;
|
|
154
|
-
case "brightness":
|
|
155
|
-
case "contrast":
|
|
156
|
-
case "saturate": return `${filter.kind}(${String(filter.value)})`;
|
|
157
|
-
case "grayscale":
|
|
158
|
-
case "invert":
|
|
159
|
-
case "sepia": return `${filter.kind}(${String(filter.value * PERCENT$3)}%)`;
|
|
160
|
-
case "hue-rotate": return `hue-rotate(${String(filter.value)}deg)`;
|
|
161
|
-
}
|
|
162
|
-
};
|
|
163
|
-
const canvasFilterListCss = (filters) => filters.filter((filter) => filter.visible).map((filter) => filterCss(filter)).join(" ");
|
|
164
|
-
|
|
165
|
-
//#endregion
|
|
166
20
|
//#region ../../packages/contract/src/canvas/canvas-font-family.lib.ts
|
|
167
21
|
const GENERIC_FAMILIES = /* @__PURE__ */ new Set([
|
|
168
22
|
"cursive",
|
|
@@ -250,41 +104,6 @@ const canvasTextDecorationDeclarations = (decoration) => ({
|
|
|
250
104
|
"text-decoration-skip-ink": decoration.skipInk ?? "auto"
|
|
251
105
|
});
|
|
252
106
|
|
|
253
|
-
//#endregion
|
|
254
|
-
//#region ../../packages/contract/src/canvas/canvas-linear-gradient.lib.ts
|
|
255
|
-
const canvasLinearGradientDefinition = (paint, id, units = "userSpaceOnUse") => {
|
|
256
|
-
const stops = paint.stops.map((stop) => `<stop offset="${String(stop.position)}" stop-color="${canvasColorCss({
|
|
257
|
-
...stop.color,
|
|
258
|
-
alpha: 1
|
|
259
|
-
})}" stop-opacity="${String(stop.color.alpha * paint.opacity)}" />`).join("");
|
|
260
|
-
return `<linearGradient id="${id}" gradientUnits="${units}" x1="0" y1=".5" x2="1" y2=".5" gradientTransform="matrix(${paint.transform.map(String).join(" ")})" color-interpolation="sRGB">${stops}</linearGradient>`;
|
|
261
|
-
};
|
|
262
|
-
const canvasLinearGradientSvg = (paint) => {
|
|
263
|
-
return `<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewBox="0 0 1 1" preserveAspectRatio="none"><defs>${canvasLinearGradientDefinition(paint, "field")}</defs><path d="M0 0H1V1H0Z" fill="url(#field)" /></svg>`;
|
|
264
|
-
};
|
|
265
|
-
|
|
266
|
-
//#endregion
|
|
267
|
-
//#region ../../packages/contract/src/canvas/canvas-radial-gradient.lib.ts
|
|
268
|
-
const DIAMETER = 2;
|
|
269
|
-
const transformFor = (paint) => paint.transform ?? [
|
|
270
|
-
paint.radius.x * DIAMETER,
|
|
271
|
-
0,
|
|
272
|
-
0,
|
|
273
|
-
paint.radius.y * DIAMETER,
|
|
274
|
-
paint.center.x - paint.radius.x,
|
|
275
|
-
paint.center.y - paint.radius.y
|
|
276
|
-
];
|
|
277
|
-
const canvasRadialGradientDefinition = (paint, id, units = "userSpaceOnUse") => {
|
|
278
|
-
const stops = paint.stops.map((stop) => `<stop offset="${String(stop.position)}" stop-color="${canvasColorCss({
|
|
279
|
-
...stop.color,
|
|
280
|
-
alpha: 1
|
|
281
|
-
})}" stop-opacity="${String(stop.color.alpha * paint.opacity)}" />`).join("");
|
|
282
|
-
return `<radialGradient id="${id}" gradientUnits="${units}" cx=".5" cy=".5" r=".5" gradientTransform="matrix(${transformFor(paint).map(String).join(" ")})" color-interpolation="sRGB">${stops}</radialGradient>`;
|
|
283
|
-
};
|
|
284
|
-
const canvasRadialGradientSvg = (paint) => {
|
|
285
|
-
return `<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewBox="0 0 1 1" preserveAspectRatio="none"><defs>${canvasRadialGradientDefinition(paint, "field")}</defs><path d="M0 0H1V1H0Z" fill="url(#field)" /></svg>`;
|
|
286
|
-
};
|
|
287
|
-
|
|
288
107
|
//#endregion
|
|
289
108
|
//#region ../../packages/contract/src/recording/event-stream.lib.ts
|
|
290
109
|
/**
|
|
@@ -432,6 +251,7 @@ const createScreenFixtureComposite = (remote) => async (input) => {
|
|
|
432
251
|
}));
|
|
433
252
|
return {
|
|
434
253
|
screenId: completed.screenId,
|
|
254
|
+
clientToken: input.clientToken,
|
|
435
255
|
route: input.route,
|
|
436
256
|
title: input.pageTitle,
|
|
437
257
|
viewport: input.viewport,
|
|
@@ -1055,9 +875,14 @@ const visiblePaints = (paints) => paints?.flatMap((paint) => {
|
|
|
1055
875
|
const value = cssPaint(paint);
|
|
1056
876
|
return value === null ? [] : [value];
|
|
1057
877
|
}) ?? [];
|
|
878
|
+
/** A CSS border or outline draws one colour, so only a single visible paint gives one. */
|
|
879
|
+
const strokePaint = (paints) => {
|
|
880
|
+
const visible = paints.filter((paint) => paint.visible);
|
|
881
|
+
return visible.length === 1 && visible[0] !== void 0 ? cssPaint(visible[0]) : null;
|
|
882
|
+
};
|
|
1058
883
|
const borderCss = (border) => {
|
|
1059
884
|
if (border?.visible !== true) return {};
|
|
1060
|
-
const paint =
|
|
885
|
+
const paint = strokePaint(border.paints);
|
|
1061
886
|
return {
|
|
1062
887
|
"border-width": [
|
|
1063
888
|
border.width.top,
|
|
@@ -1071,7 +896,7 @@ const borderCss = (border) => {
|
|
|
1071
896
|
};
|
|
1072
897
|
const outlineCss = (outline) => {
|
|
1073
898
|
if (outline?.visible !== true) return {};
|
|
1074
|
-
const paint =
|
|
899
|
+
const paint = strokePaint(outline.paints);
|
|
1075
900
|
return {
|
|
1076
901
|
"outline-width": `${String(outline.width)}px`,
|
|
1077
902
|
"outline-offset": `${String(outline.offset)}px`,
|
|
@@ -1189,7 +1014,7 @@ const computedCanvasNodeCss = (node, document) => ({
|
|
|
1189
1014
|
|
|
1190
1015
|
//#endregion
|
|
1191
1016
|
//#region src/application/canvas-source-projection.use-case.ts
|
|
1192
|
-
const childrenOf = (document, parentId) => Object.entries(document.relationships).filter(([, relationship]) => relationship.parentId === parentId).toSorted(([leftId, left], [rightId, right]) => left.sortKey === right.sortKey ? leftId.localeCompare(rightId) : left.sortKey
|
|
1017
|
+
const childrenOf = (document, parentId) => Object.entries(document.relationships).filter(([, relationship]) => relationship.parentId === parentId).toSorted(([leftId, left], [rightId, right]) => left.sortKey === right.sortKey ? leftId.localeCompare(rightId) : compareCanvasSortKeys(left.sortKey, right.sortKey)).map(([nodeId]) => nodeId);
|
|
1193
1018
|
const requireNode = (document, nodeId) => {
|
|
1194
1019
|
const node = document.nodes[nodeId];
|
|
1195
1020
|
if (node === void 0) throw new CliError("NOT_FOUND", `Canvas node ${nodeId} does not exist.`, "Run canvas tree and use a current stable node id.");
|
|
@@ -1794,13 +1619,12 @@ const registerCanvasProgram = (program, input) => {
|
|
|
1794
1619
|
};
|
|
1795
1620
|
|
|
1796
1621
|
//#endregion
|
|
1797
|
-
//#region ../../packages/sdk/dist/capture-files.lib-
|
|
1798
|
-
const CAPTURE_KEY_LENGTH = 160;
|
|
1622
|
+
//#region ../../packages/sdk/dist/capture-files.lib-DbjZ8kU9.mjs
|
|
1799
1623
|
const CAPTURE_METADATA_LENGTH = 200;
|
|
1800
1624
|
const CAPTURE_ISSUE_LENGTH = 500;
|
|
1801
1625
|
const CAPTURE_FAILURE_LENGTH = 1e3;
|
|
1802
1626
|
const CAPTURE_UPLOAD_BATCH_SIZE = 400;
|
|
1803
|
-
const key = z.string().trim().min(1).max(
|
|
1627
|
+
const key = z.string().trim().min(1).max(160);
|
|
1804
1628
|
const digest = z.string().regex(/^[a-f0-9]{64}$/u);
|
|
1805
1629
|
const dimension = z.number().int().positive();
|
|
1806
1630
|
const captureKeySchema = z.strictObject({
|
|
@@ -1933,6 +1757,11 @@ const captureAttemptSchema = z.strictObject({
|
|
|
1933
1757
|
"interrupted",
|
|
1934
1758
|
"timedOut"
|
|
1935
1759
|
]),
|
|
1760
|
+
title: z.string().min(1).optional(),
|
|
1761
|
+
location: z.strictObject({
|
|
1762
|
+
file: z.string().min(1),
|
|
1763
|
+
line: z.number().int()
|
|
1764
|
+
}).optional(),
|
|
1936
1765
|
captures: z.array(captureArtifactSchema)
|
|
1937
1766
|
});
|
|
1938
1767
|
const captureManifestSchema = z.strictObject({
|
|
@@ -2019,7 +1848,6 @@ const reserveCaptureBlobsOutputSchema = z.strictObject({ uploads: z.array(z.stri
|
|
|
2019
1848
|
expiresAt: z.iso.datetime()
|
|
2020
1849
|
}).nullable()
|
|
2021
1850
|
})).max(CAPTURE_UPLOAD_BATCH_SIZE) });
|
|
2022
|
-
z.strictObject({ manifest: captureManifestSchema });
|
|
2023
1851
|
const COMMIT_LENGTH = 200;
|
|
2024
1852
|
z.strictObject({
|
|
2025
1853
|
canvasId: z.uuid(),
|
|
@@ -2040,6 +1868,28 @@ z.strictObject({
|
|
|
2040
1868
|
before: preview,
|
|
2041
1869
|
after: preview
|
|
2042
1870
|
});
|
|
1871
|
+
const CODE_LENGTH = 8;
|
|
1872
|
+
const FNV_OFFSET = 2166136261;
|
|
1873
|
+
const FNV_PRIME = 16777619;
|
|
1874
|
+
const HEX = 16;
|
|
1875
|
+
/** FNV-1a: a short code that is the same for the same text on every run and every platform. */
|
|
1876
|
+
const shortCode = (text) => {
|
|
1877
|
+
let hash = FNV_OFFSET;
|
|
1878
|
+
for (const character of text) {
|
|
1879
|
+
hash ^= character.codePointAt(0) ?? 0;
|
|
1880
|
+
hash = Math.imul(hash, FNV_PRIME) >>> 0;
|
|
1881
|
+
}
|
|
1882
|
+
return hash.toString(HEX).padStart(CODE_LENGTH, "0");
|
|
1883
|
+
};
|
|
1884
|
+
/**
|
|
1885
|
+
* A name within the key limit. A longer one keeps its start and gains a code made from the whole
|
|
1886
|
+
* name, so two long names that share a start stay apart and the same name always shortens the same way.
|
|
1887
|
+
*/
|
|
1888
|
+
const fitCaptureName = (name) => {
|
|
1889
|
+
const trimmed = name.trim();
|
|
1890
|
+
if (trimmed.length <= 160) return trimmed;
|
|
1891
|
+
return `${trimmed.slice(0, 160 - CODE_LENGTH - 1).trimEnd()} ${shortCode(trimmed)}`;
|
|
1892
|
+
};
|
|
2043
1893
|
const captureKeyString = (key) => JSON.stringify([
|
|
2044
1894
|
key.source,
|
|
2045
1895
|
key.journey,
|
|
@@ -2093,95 +1943,122 @@ const canonicalCaptureJson = (value) => {
|
|
|
2093
1943
|
}
|
|
2094
1944
|
return state.output.join("");
|
|
2095
1945
|
};
|
|
1946
|
+
/** Each file once, described as its first capture described it. */
|
|
2096
1947
|
const captureBlobs = (artifacts) => {
|
|
2097
|
-
const
|
|
1948
|
+
const seen = /* @__PURE__ */ new Set();
|
|
2098
1949
|
const unique = [];
|
|
2099
|
-
for (const artifact of artifacts)
|
|
2100
|
-
|
|
2101
|
-
|
|
2102
|
-
|
|
2103
|
-
|
|
2104
|
-
|
|
2105
|
-
|
|
2106
|
-
const previous = blobs.get(blob.sha256);
|
|
2107
|
-
if (previous !== void 0 && canonicalCaptureJson(previous) !== canonicalCaptureJson(blob)) return "The same capture digest has conflicting blob metadata.";
|
|
2108
|
-
if (previous === void 0) {
|
|
2109
|
-
unique.push(blob);
|
|
2110
|
-
blobs.set(blob.sha256, blob);
|
|
2111
|
-
}
|
|
2112
|
-
}
|
|
1950
|
+
for (const artifact of artifacts) for (const blob of [
|
|
1951
|
+
artifact.source.blob,
|
|
1952
|
+
artifact.preview.blob,
|
|
1953
|
+
...artifact.assets.map((asset) => asset.blob)
|
|
1954
|
+
]) if (!seen.has(blob.sha256)) {
|
|
1955
|
+
seen.add(blob.sha256);
|
|
1956
|
+
unique.push(blob);
|
|
2113
1957
|
}
|
|
2114
1958
|
return unique.toSorted((a, b) => compare(a.sha256, b.sha256));
|
|
2115
1959
|
};
|
|
1960
|
+
const testIdentity = (attempt) => JSON.stringify([
|
|
1961
|
+
attempt.participant,
|
|
1962
|
+
attempt.project,
|
|
1963
|
+
attempt.testId
|
|
1964
|
+
]);
|
|
1965
|
+
/**
|
|
1966
|
+
* Each test's last attempt that captured anything, whatever its result. Attempts from an
|
|
1967
|
+
* unreserved participant are left out; of two records of one attempt, the first is kept.
|
|
1968
|
+
*/
|
|
2116
1969
|
const finalAttempts = (manifest) => {
|
|
2117
|
-
const
|
|
2118
|
-
|
|
2119
|
-
const
|
|
2120
|
-
const terminal = /* @__PURE__ */ new Map();
|
|
1970
|
+
const reserved = new Set(manifest.run.participants);
|
|
1971
|
+
const recorded = /* @__PURE__ */ new Set();
|
|
1972
|
+
const selected = /* @__PURE__ */ new Map();
|
|
2121
1973
|
for (const attempt of manifest.attempts) {
|
|
2122
|
-
|
|
2123
|
-
|
|
2124
|
-
|
|
2125
|
-
|
|
2126
|
-
|
|
2127
|
-
|
|
2128
|
-
const attemptKey = JSON.stringify([identity, attempt.retry]);
|
|
2129
|
-
const content = canonicalCaptureJson(attempt);
|
|
2130
|
-
if (content === null) return "Capture attempts must contain finite JSON values.";
|
|
2131
|
-
const previous = terminal.get(attemptKey);
|
|
2132
|
-
if (previous !== void 0 && previous !== content) return "Conflicting terminal records for the same test attempt.";
|
|
2133
|
-
terminal.set(attemptKey, content);
|
|
2134
|
-
const selected = attempts.get(identity);
|
|
2135
|
-
if (selected === void 0 || selected.retry < attempt.retry) attempts.set(identity, attempt);
|
|
1974
|
+
const record = JSON.stringify([testIdentity(attempt), attempt.retry]);
|
|
1975
|
+
if (!reserved.has(attempt.participant) || recorded.has(record)) continue;
|
|
1976
|
+
recorded.add(record);
|
|
1977
|
+
if (attempt.captures.length === 0) continue;
|
|
1978
|
+
const previous = selected.get(testIdentity(attempt));
|
|
1979
|
+
if (previous === void 0 || previous.retry < attempt.retry) selected.set(testIdentity(attempt), attempt);
|
|
2136
1980
|
}
|
|
2137
|
-
return manifest.attempts.filter((attempt) =>
|
|
2138
|
-
attempt.participant,
|
|
2139
|
-
attempt.project,
|
|
2140
|
-
attempt.testId
|
|
2141
|
-
])) === attempt);
|
|
2142
|
-
};
|
|
2143
|
-
const uniqueCaptures = (source, artifacts) => {
|
|
2144
|
-
const keys = /* @__PURE__ */ new Set();
|
|
2145
|
-
const orders = /* @__PURE__ */ new Set();
|
|
2146
|
-
const pages = /* @__PURE__ */ new Map();
|
|
2147
|
-
for (const artifact of artifacts) {
|
|
2148
|
-
if (artifact.key.source !== source) return "Capture source differs from its reserved run.";
|
|
2149
|
-
const identity = captureKeyString(artifact.key);
|
|
2150
|
-
if (keys.has(identity)) return `Duplicate capture key: ${identity}`;
|
|
2151
|
-
const order = JSON.stringify([
|
|
2152
|
-
artifact.key.journey,
|
|
2153
|
-
artifact.key.variant,
|
|
2154
|
-
artifact.order
|
|
2155
|
-
]);
|
|
2156
|
-
if (orders.has(order)) return `Duplicate step order in journey ${artifact.key.journey}.`;
|
|
2157
|
-
const journey = JSON.stringify([artifact.key.journey, artifact.key.variant]);
|
|
2158
|
-
if (pages.has(journey) && pages.get(journey) !== artifact.page) return `Every step in journey ${artifact.key.journey} must use the same page.`;
|
|
2159
|
-
pages.set(journey, artifact.page);
|
|
2160
|
-
keys.add(identity);
|
|
2161
|
-
orders.add(order);
|
|
2162
|
-
}
|
|
2163
|
-
return null;
|
|
1981
|
+
return manifest.attempts.filter((attempt) => selected.get(testIdentity(attempt)) === attempt);
|
|
2164
1982
|
};
|
|
2165
|
-
const
|
|
2166
|
-
|
|
2167
|
-
|
|
2168
|
-
|
|
2169
|
-
|
|
1983
|
+
const rowOf = (artifact) => JSON.stringify([artifact.key.journey, artifact.key.variant]);
|
|
1984
|
+
/** Journey, variant and position first; then test file, line and call order, which never depend on timing. */
|
|
1985
|
+
const firstDifference = (...differences) => differences.find((difference) => difference !== 0) ?? 0;
|
|
1986
|
+
const compareEntries = (left, right) => firstDifference(compare(left.artifact.key.journey, right.artifact.key.journey), compare(left.artifact.key.variant, right.artifact.key.variant), left.artifact.order - right.artifact.order, compare(left.attempt.location?.file ?? "", right.attempt.location?.file ?? ""), (left.attempt.location?.line ?? 0) - (right.attempt.location?.line ?? 0), compare(testIdentity(left.attempt), testIdentity(right.attempt)), left.index - right.index);
|
|
1987
|
+
/**
|
|
1988
|
+
* What tells repeated captures of one step apart: repeats within one attempt are numbered, and a
|
|
1989
|
+
* step several tests captured is named after each test.
|
|
1990
|
+
*/
|
|
1991
|
+
const stepSuffixes = (entries) => {
|
|
1992
|
+
const groups = Map.groupBy(entries, (entry) => captureKeyString(entry.artifact.key));
|
|
1993
|
+
const suffixes = /* @__PURE__ */ new Map();
|
|
1994
|
+
for (const group of groups.values()) {
|
|
1995
|
+
const tests = Map.groupBy(group, (entry) => testIdentity(entry.attempt));
|
|
1996
|
+
for (const repeats of tests.values()) for (const [repeat, entry] of repeats.entries()) {
|
|
1997
|
+
const test = tests.size > 1 ? ` · ${entry.attempt.title ?? entry.attempt.testId}` : "";
|
|
1998
|
+
const count = repeat > 0 ? ` (${String(repeat + 1)})` : "";
|
|
1999
|
+
suffixes.set(entry, `${test}${count}`);
|
|
2000
|
+
}
|
|
2001
|
+
}
|
|
2002
|
+
return suffixes;
|
|
2170
2003
|
};
|
|
2171
|
-
/** All publishers select
|
|
2004
|
+
/** All publishers select captures with the same rules, so the SDK and the API agree on every frame. */
|
|
2172
2005
|
const selectedCaptures = (input) => {
|
|
2173
2006
|
const parsed = captureManifestSchema.safeParse(input);
|
|
2174
2007
|
if (!parsed.success) return "Invalid capture manifest.";
|
|
2175
2008
|
const manifest = parsed.data;
|
|
2176
|
-
const
|
|
2177
|
-
|
|
2178
|
-
|
|
2179
|
-
|
|
2180
|
-
|
|
2181
|
-
if (
|
|
2182
|
-
const
|
|
2183
|
-
|
|
2009
|
+
const entries = finalAttempts(manifest).flatMap((attempt) => attempt.captures.map((artifact, index) => ({
|
|
2010
|
+
artifact,
|
|
2011
|
+
attempt,
|
|
2012
|
+
index
|
|
2013
|
+
}))).filter((entry) => entry.artifact.key.source === manifest.run.source).toSorted(compareEntries);
|
|
2014
|
+
if (entries.length === 0) return "A run must contain at least one capture.";
|
|
2015
|
+
const suffixes = stepSuffixes(entries);
|
|
2016
|
+
const descriptions = new Map(captureBlobs(entries.map((entry) => entry.artifact)).map((blob) => [blob.sha256, blob]));
|
|
2017
|
+
const described = (blob) => descriptions.get(blob.sha256) ?? blob;
|
|
2018
|
+
const pages = /* @__PURE__ */ new Map();
|
|
2019
|
+
const positions = /* @__PURE__ */ new Map();
|
|
2020
|
+
return entries.map((entry) => {
|
|
2021
|
+
const { artifact } = entry;
|
|
2022
|
+
const row = rowOf(artifact);
|
|
2023
|
+
if (!pages.has(row)) pages.set(row, artifact.page);
|
|
2024
|
+
const order = positions.get(row) ?? 0;
|
|
2025
|
+
positions.set(row, order + 1);
|
|
2026
|
+
const suffix = suffixes.get(entry) ?? "";
|
|
2027
|
+
const page = pages.get(row);
|
|
2028
|
+
const placed = { ...artifact };
|
|
2029
|
+
delete placed.page;
|
|
2030
|
+
return {
|
|
2031
|
+
...placed,
|
|
2032
|
+
...page !== void 0 && { page },
|
|
2033
|
+
key: {
|
|
2034
|
+
...artifact.key,
|
|
2035
|
+
step: fitCaptureName(`${artifact.key.step}${suffix}`)
|
|
2036
|
+
},
|
|
2037
|
+
label: fitCaptureName(`${artifact.label}${suffix}`),
|
|
2038
|
+
order,
|
|
2039
|
+
source: {
|
|
2040
|
+
...artifact.source,
|
|
2041
|
+
blob: described(artifact.source.blob)
|
|
2042
|
+
},
|
|
2043
|
+
preview: {
|
|
2044
|
+
...artifact.preview,
|
|
2045
|
+
blob: described(artifact.preview.blob)
|
|
2046
|
+
},
|
|
2047
|
+
assets: artifact.assets.map((asset) => ({
|
|
2048
|
+
...asset,
|
|
2049
|
+
blob: described(asset.blob)
|
|
2050
|
+
}))
|
|
2051
|
+
};
|
|
2052
|
+
});
|
|
2184
2053
|
};
|
|
2054
|
+
/** The same reserved run. Its expiry moves with each upload and seal, so it is not part of its identity. */
|
|
2055
|
+
const isSameCaptureRun = (left, right) => canonicalCaptureJson({
|
|
2056
|
+
...left,
|
|
2057
|
+
expiresAt: ""
|
|
2058
|
+
}) === canonicalCaptureJson({
|
|
2059
|
+
...right,
|
|
2060
|
+
expiresAt: ""
|
|
2061
|
+
});
|
|
2185
2062
|
const captureManifestContent = (manifest) => {
|
|
2186
2063
|
const serialized = canonicalCaptureJson(manifest);
|
|
2187
2064
|
return serialized === null ? null : `enhance-capture-run:v1\0${serialized}`;
|
|
@@ -2189,17 +2066,13 @@ const captureManifestContent = (manifest) => {
|
|
|
2189
2066
|
const mergeCaptureManifests = (parts) => {
|
|
2190
2067
|
const first = parts[0];
|
|
2191
2068
|
if (first === void 0) return "At least one participant manifest is required.";
|
|
2192
|
-
const descriptor = canonicalCaptureJson(first.run);
|
|
2193
2069
|
const participants = /* @__PURE__ */ new Map();
|
|
2194
2070
|
const attempts = [];
|
|
2195
2071
|
for (const part of parts) {
|
|
2196
|
-
if (
|
|
2197
|
-
|
|
2198
|
-
|
|
2199
|
-
|
|
2200
|
-
}
|
|
2201
|
-
if (part.attempts.some((attempt) => part.participants.every((participant) => participant.id !== attempt.participant))) return "A participant manifest contains another participant’s attempt.";
|
|
2202
|
-
attempts.push(...part.attempts);
|
|
2072
|
+
if (!isSameCaptureRun(part.run, first.run) || part.ordering !== first.ordering) return "Participant manifests must belong to the same reserved run and ordering.";
|
|
2073
|
+
if (part.participants.some((participant) => participants.has(participant.id))) continue;
|
|
2074
|
+
for (const participant of part.participants) participants.set(participant.id, participant);
|
|
2075
|
+
attempts.push(...part.attempts.filter((attempt) => part.participants.some((participant) => participant.id === attempt.participant)));
|
|
2203
2076
|
}
|
|
2204
2077
|
const manifest = {
|
|
2205
2078
|
...first,
|
|
@@ -2216,6 +2089,41 @@ const mergeCaptureManifests = (parts) => {
|
|
|
2216
2089
|
const selected = selectedCaptures(manifest);
|
|
2217
2090
|
return typeof selected === "string" ? selected : manifest;
|
|
2218
2091
|
};
|
|
2092
|
+
const NAMED_KEY_FIELDS = [
|
|
2093
|
+
"journey",
|
|
2094
|
+
"step",
|
|
2095
|
+
"variant"
|
|
2096
|
+
];
|
|
2097
|
+
const NAMED_FIELDS = ["label", "journeyLabel"];
|
|
2098
|
+
const fitted = (value) => typeof value === "string" ? fitCaptureName(value) : value;
|
|
2099
|
+
/** A capture whose names a test author wrote too long is shortened, never refused. */
|
|
2100
|
+
const fitCaptureNames = (raw) => {
|
|
2101
|
+
if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return raw;
|
|
2102
|
+
const capture = { ...raw };
|
|
2103
|
+
for (const field of NAMED_FIELDS) capture[field] = fitted(capture[field]);
|
|
2104
|
+
const captureKey = capture["key"];
|
|
2105
|
+
if (typeof captureKey === "object" && captureKey !== null && !Array.isArray(captureKey)) {
|
|
2106
|
+
const named = { ...captureKey };
|
|
2107
|
+
for (const field of NAMED_KEY_FIELDS) named[field] = fitted(named[field]);
|
|
2108
|
+
capture["key"] = named;
|
|
2109
|
+
}
|
|
2110
|
+
return capture;
|
|
2111
|
+
};
|
|
2112
|
+
/**
|
|
2113
|
+
* A manifest checked in outline, then capture by capture: one capture that fails its own checks
|
|
2114
|
+
* is left out, and the rest of the run still publishes.
|
|
2115
|
+
*/
|
|
2116
|
+
const lenientCaptureManifestSchema = captureManifestSchema.extend({ attempts: z.array(captureAttemptSchema.extend({ captures: z.array(z.unknown()) })) }).transform((manifest) => ({
|
|
2117
|
+
...manifest,
|
|
2118
|
+
attempts: manifest.attempts.map((attempt) => ({
|
|
2119
|
+
...attempt,
|
|
2120
|
+
captures: attempt.captures.flatMap((capture) => {
|
|
2121
|
+
const parsed = captureArtifactSchema.safeParse(fitCaptureNames(capture));
|
|
2122
|
+
return parsed.success ? [parsed.data] : [];
|
|
2123
|
+
})
|
|
2124
|
+
}))
|
|
2125
|
+
}));
|
|
2126
|
+
z.strictObject({ manifest: lenientCaptureManifestSchema });
|
|
2219
2127
|
z.strictObject({ canvasId: z.uuid() }).extend({ verdict: captureVerdictSchema });
|
|
2220
2128
|
const captureReferenceInputSchema = z.strictObject({
|
|
2221
2129
|
canvasId: z.uuid(),
|
|
@@ -2307,75 +2215,199 @@ const writeCaptureJson = async (path, value) => {
|
|
|
2307
2215
|
};
|
|
2308
2216
|
const readCaptureManifest = async (path) => {
|
|
2309
2217
|
const raw = JSON.parse(await readFile(path, "utf8"));
|
|
2310
|
-
return
|
|
2218
|
+
return lenientCaptureManifestSchema.parse(raw);
|
|
2311
2219
|
};
|
|
2312
2220
|
|
|
2313
2221
|
//#endregion
|
|
2314
|
-
//#region ../../packages/sdk/dist/capture-client.client-
|
|
2222
|
+
//#region ../../packages/sdk/dist/capture-client.client-C38aUbFr.mjs
|
|
2223
|
+
const RATE_LIMIT_STATUS = 429;
|
|
2224
|
+
const MILLISECONDS_PER_SECOND$1 = 1e3;
|
|
2225
|
+
const MAX_ERROR_LENGTH = 1e3;
|
|
2226
|
+
const DEFAULT_TIMEOUT_MS = 3e4;
|
|
2227
|
+
const DEFAULT_PUBLICATION_TIMEOUT_MS = 6e5;
|
|
2228
|
+
const NODE_TIMER_MAX_MS = 2147483647;
|
|
2229
|
+
const HTTP_ERRORS = /* @__PURE__ */ new Map([
|
|
2230
|
+
[401, "authorization"],
|
|
2231
|
+
[403, "authorization"],
|
|
2232
|
+
[409, "conflict"],
|
|
2233
|
+
[400, "artifact"]
|
|
2234
|
+
]);
|
|
2235
|
+
const SERVER_ERROR_STATUS = 500;
|
|
2236
|
+
const MOST_ATTEMPTS = 3;
|
|
2237
|
+
const BACKOFF_MS = [1e3, 2e3];
|
|
2238
|
+
const JITTER_SPREAD = .5;
|
|
2239
|
+
const isRetryable = (response) => response.status === RATE_LIMIT_STATUS || response.status >= SERVER_ERROR_STATUS;
|
|
2240
|
+
/** The server's own wait when it names one, otherwise a growing wait with random jitter. */
|
|
2241
|
+
const waitBefore = (response, attempt) => {
|
|
2242
|
+
const header = response?.headers.get("retry-after") ?? null;
|
|
2243
|
+
if (header !== null) {
|
|
2244
|
+
const seconds = Number(header);
|
|
2245
|
+
const named = Number.isFinite(seconds) ? seconds * MILLISECONDS_PER_SECOND$1 : Date.parse(header) - Date.now();
|
|
2246
|
+
if (Number.isFinite(named) && named >= 0) return named;
|
|
2247
|
+
}
|
|
2248
|
+
return (BACKOFF_MS[Math.min(attempt, BACKOFF_MS.length - 1)] ?? 0) * (1 - JITTER_SPREAD / 2 + Math.random() * JITTER_SPREAD);
|
|
2249
|
+
};
|
|
2250
|
+
/**
|
|
2251
|
+
* One retry rule for every request the SDK makes: a dropped connection, a timeout, a server error
|
|
2252
|
+
* or "too many requests" is tried again, up to three attempts in all, while the wait fits the
|
|
2253
|
+
* deadline. Any other answer is returned at once.
|
|
2254
|
+
*/
|
|
2255
|
+
const sendWithRetry = async (send, timing) => {
|
|
2256
|
+
for (let attempt = 0;; attempt++) {
|
|
2257
|
+
let response = null;
|
|
2258
|
+
try {
|
|
2259
|
+
response = await send(AbortSignal.timeout(timing.timeoutMs));
|
|
2260
|
+
if (!isRetryable(response)) return response;
|
|
2261
|
+
} catch (error) {
|
|
2262
|
+
if (attempt + 1 >= MOST_ATTEMPTS) throw error;
|
|
2263
|
+
}
|
|
2264
|
+
const wait = waitBefore(response, attempt);
|
|
2265
|
+
if ((attempt + 1 >= MOST_ATTEMPTS || Date.now() + wait >= timing.retryDeadline) && response !== null) return response;
|
|
2266
|
+
await response?.body?.cancel();
|
|
2267
|
+
await setTimeout$1(wait);
|
|
2268
|
+
}
|
|
2269
|
+
};
|
|
2270
|
+
const requestResponse = async (url, options, timeoutMs, retryDeadline) => {
|
|
2271
|
+
try {
|
|
2272
|
+
return await sendWithRetry(async (signal) => fetch(url, {
|
|
2273
|
+
...options,
|
|
2274
|
+
signal
|
|
2275
|
+
}), {
|
|
2276
|
+
timeoutMs,
|
|
2277
|
+
retryDeadline
|
|
2278
|
+
});
|
|
2279
|
+
} catch {
|
|
2280
|
+
throw captureError("transport", "Enhance did not confirm the request. Resume the same run to recover its result.");
|
|
2281
|
+
}
|
|
2282
|
+
};
|
|
2283
|
+
const responseBody = async (response) => {
|
|
2284
|
+
try {
|
|
2285
|
+
return await response.json();
|
|
2286
|
+
} catch {
|
|
2287
|
+
return null;
|
|
2288
|
+
}
|
|
2289
|
+
};
|
|
2290
|
+
const call = async (url, options, schema, request) => {
|
|
2291
|
+
const { procedure, timeoutMs, publicationTimeoutMs } = request;
|
|
2292
|
+
const response = await requestResponse(url, options, timeoutMs, Date.now() + publicationTimeoutMs);
|
|
2293
|
+
const body = await responseBody(response);
|
|
2294
|
+
if (!response.ok) {
|
|
2295
|
+
const error = typeof body === "object" && body !== null ? Reflect.get(body, "error") : null;
|
|
2296
|
+
const message = typeof error === "object" && error !== null ? Reflect.get(error, "message") : null;
|
|
2297
|
+
throw captureError(HTTP_ERRORS.get(response.status) ?? "transport", typeof message === "string" ? message.slice(0, MAX_ERROR_LENGTH) : `Enhance rejected ${procedure} (HTTP ${String(response.status)}).`);
|
|
2298
|
+
}
|
|
2299
|
+
const result = typeof body === "object" && body !== null ? Reflect.get(body, "result") : null;
|
|
2300
|
+
const data = typeof result === "object" && result !== null ? Reflect.get(result, "data") : void 0;
|
|
2301
|
+
const parsed = schema.safeParse(data);
|
|
2302
|
+
if (!parsed.success) throw captureError("transport", `Enhance returned an incompatible ${procedure} response.`);
|
|
2303
|
+
return parsed.data;
|
|
2304
|
+
};
|
|
2305
|
+
const captureTransport = (options) => {
|
|
2306
|
+
const base = URL.parse(options.apiUrl);
|
|
2307
|
+
if (base === null || !["http:", "https:"].includes(base.protocol) || base.username !== "" || base.password !== "" || options.token.trim() === "") throw captureError("configuration", "Enhance needs an HTTP API URL and an explicit token.");
|
|
2308
|
+
const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
2309
|
+
const publicationTimeoutMs = options.publicationTimeoutMs ?? DEFAULT_PUBLICATION_TIMEOUT_MS;
|
|
2310
|
+
if (!Number.isSafeInteger(publicationTimeoutMs) || publicationTimeoutMs < 1) throw captureError("configuration", "Enhance publication timeout must be a positive integer in milliseconds.");
|
|
2311
|
+
if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > NODE_TIMER_MAX_MS) throw captureError("configuration", `Enhance timeout must fit the Node timer range of 1 to ${String(NODE_TIMER_MAX_MS)} milliseconds.`);
|
|
2312
|
+
return {
|
|
2313
|
+
timeoutMs,
|
|
2314
|
+
publicationTimeoutMs,
|
|
2315
|
+
request: async (procedure, input, schema, isQuery = false) => {
|
|
2316
|
+
const url = new URL(`${base.pathname.replace(/\/$/u, "")}/trpc/${procedure}`, base.origin);
|
|
2317
|
+
if (isQuery) url.searchParams.set("input", JSON.stringify(input));
|
|
2318
|
+
return call(url, {
|
|
2319
|
+
method: isQuery ? "GET" : "POST",
|
|
2320
|
+
headers: {
|
|
2321
|
+
authorization: `Bearer ${options.token}`,
|
|
2322
|
+
"content-type": "application/json"
|
|
2323
|
+
},
|
|
2324
|
+
...!isQuery && { body: JSON.stringify(input) },
|
|
2325
|
+
redirect: "error"
|
|
2326
|
+
}, schema, {
|
|
2327
|
+
procedure,
|
|
2328
|
+
timeoutMs,
|
|
2329
|
+
publicationTimeoutMs
|
|
2330
|
+
});
|
|
2331
|
+
}
|
|
2332
|
+
};
|
|
2333
|
+
};
|
|
2315
2334
|
const UPLOAD_BATCH_SIZE = 400;
|
|
2316
2335
|
const POLL_INTERVAL_MS = 250;
|
|
2336
|
+
const HTTP_FORBIDDEN = 403;
|
|
2337
|
+
const BYTES_PER_EXTRA_SECOND = 102400;
|
|
2338
|
+
const MILLISECONDS_PER_SECOND = 1e3;
|
|
2339
|
+
/** S3 answers an upload to an expired signed address with this message. */
|
|
2340
|
+
const EXPIRED_ADDRESS = "Request has expired";
|
|
2317
2341
|
const readFromDirectories = async (directories, blob) => {
|
|
2318
2342
|
for (const directory of directories) try {
|
|
2319
2343
|
return await readCaptureBlob(directory, blob);
|
|
2320
2344
|
} catch {}
|
|
2321
2345
|
throw captureError("artifact", `Capture blob is unavailable: ${blob.sha256}.`);
|
|
2322
2346
|
};
|
|
2347
|
+
/** Each upload may take its base time plus a second for every 100 KB, so a large file is not cut off on every try. */
|
|
2348
|
+
const uploadTimeLimit = (transport, blob) => transport.timeoutMs + Math.ceil(blob.bytes / BYTES_PER_EXTRA_SECOND) * MILLISECONDS_PER_SECOND;
|
|
2323
2349
|
const uploadBlob = async (input) => {
|
|
2324
|
-
|
|
2325
|
-
|
|
2326
|
-
if (upload ===
|
|
2327
|
-
const bytes = await readFromDirectories(input.directories, input.blob);
|
|
2350
|
+
const upload = input.held?.upload;
|
|
2351
|
+
if (upload === null) return "stored";
|
|
2352
|
+
if (upload === void 0) return "failed";
|
|
2328
2353
|
try {
|
|
2329
|
-
|
|
2354
|
+
const bytes = await readFromDirectories(input.directories, input.blob);
|
|
2355
|
+
const response = await sendWithRetry(async (signal) => fetch(upload.url, {
|
|
2330
2356
|
method: "PUT",
|
|
2331
2357
|
headers: upload.headers,
|
|
2332
2358
|
body: new Blob([Uint8Array.from(bytes)]),
|
|
2333
|
-
signal
|
|
2359
|
+
signal,
|
|
2334
2360
|
redirect: "error"
|
|
2335
|
-
})
|
|
2361
|
+
}), {
|
|
2362
|
+
timeoutMs: uploadTimeLimit(input.transport, input.blob),
|
|
2363
|
+
retryDeadline: Date.now() + input.transport.publicationTimeoutMs
|
|
2364
|
+
});
|
|
2365
|
+
if (response.ok) return "stored";
|
|
2366
|
+
const answer = await response.text();
|
|
2367
|
+
return response.status === HTTP_FORBIDDEN && answer.includes(EXPIRED_ADDRESS) ? "expired" : "failed";
|
|
2336
2368
|
} catch {
|
|
2337
|
-
|
|
2369
|
+
return "failed";
|
|
2338
2370
|
}
|
|
2339
2371
|
};
|
|
2372
|
+
const reserve = async (transport, runId, blobs) => {
|
|
2373
|
+
const reserved = await transport.request("captureRun.reserveAssets", {
|
|
2374
|
+
runId,
|
|
2375
|
+
blobs
|
|
2376
|
+
}, reserveCaptureBlobsOutputSchema);
|
|
2377
|
+
return new Map(reserved.uploads.map((item) => [item.sha256, item]));
|
|
2378
|
+
};
|
|
2379
|
+
/** A file that will not upload is left out; the API publishes its screen without it. */
|
|
2340
2380
|
const uploadBlobs = async (transport, manifest, directories, blobs) => {
|
|
2341
|
-
|
|
2381
|
+
const runId = manifest.run.id;
|
|
2342
2382
|
const available = [];
|
|
2343
2383
|
for (const blob of blobs) try {
|
|
2344
2384
|
await readFromDirectories(directories, blob);
|
|
2345
2385
|
available.push(blob);
|
|
2346
|
-
} catch {
|
|
2347
|
-
unavailable++;
|
|
2348
|
-
}
|
|
2386
|
+
} catch {}
|
|
2349
2387
|
for (let start = 0; start < available.length; start += UPLOAD_BATCH_SIZE) {
|
|
2350
2388
|
const batch = available.slice(start, start + UPLOAD_BATCH_SIZE);
|
|
2351
|
-
const
|
|
2352
|
-
|
|
2353
|
-
|
|
2354
|
-
|
|
2355
|
-
|
|
2356
|
-
|
|
2389
|
+
const uploads = await reserve(transport, runId, batch);
|
|
2390
|
+
for (const blob of batch) if (await uploadBlob({
|
|
2391
|
+
transport,
|
|
2392
|
+
directories,
|
|
2393
|
+
blob,
|
|
2394
|
+
held: uploads.get(blob.sha256)
|
|
2395
|
+
}) === "expired") {
|
|
2396
|
+
const renewed = await reserve(transport, runId, [blob]);
|
|
2357
2397
|
await uploadBlob({
|
|
2358
2398
|
transport,
|
|
2359
|
-
runId: manifest.run.id,
|
|
2360
2399
|
directories,
|
|
2361
2400
|
blob,
|
|
2362
|
-
held:
|
|
2401
|
+
held: renewed.get(blob.sha256)
|
|
2363
2402
|
});
|
|
2364
|
-
} catch {
|
|
2365
|
-
unavailable++;
|
|
2366
2403
|
}
|
|
2367
2404
|
}
|
|
2368
|
-
if (unavailable > 0) channel("enhance.capture.resources").publish({
|
|
2369
|
-
stage: "upload",
|
|
2370
|
-
runId: manifest.run.id,
|
|
2371
|
-
unavailable
|
|
2372
|
-
});
|
|
2373
2405
|
};
|
|
2374
2406
|
const committedRun = async (transport, runId) => {
|
|
2375
2407
|
let status = await transport.request("captureRun.publish", { runId }, getCaptureRunOutputSchema);
|
|
2376
2408
|
const deadline = Date.now() + transport.publicationTimeoutMs;
|
|
2377
2409
|
while (status.receipt === null && status.failure === null && !["cancelled", "failed"].includes(status.state)) {
|
|
2378
|
-
if (Date.now() >= deadline) throw captureError("
|
|
2410
|
+
if (Date.now() >= deadline) throw captureError("pending", `Capture run ${runId} is still publishing to canvas ${status.run.canvasId}. It appears there when done.`, runId);
|
|
2379
2411
|
await new Promise((resolve) => {
|
|
2380
2412
|
setTimeout(resolve, POLL_INTERVAL_MS);
|
|
2381
2413
|
});
|
|
@@ -2392,7 +2424,6 @@ const publishManifest = async (transport, manifest, directory, blobDirectories =
|
|
|
2392
2424
|
const artifacts = selectedCaptures(manifest);
|
|
2393
2425
|
if (typeof artifacts === "string") throw captureError("artifact", artifacts);
|
|
2394
2426
|
const blobs = captureBlobs(artifacts);
|
|
2395
|
-
if (typeof blobs === "string") throw captureError("artifact", blobs);
|
|
2396
2427
|
const current = await transport.request("captureRun.get", { runId: manifest.run.id }, getCaptureRunOutputSchema, true);
|
|
2397
2428
|
if (current.receipt !== null) {
|
|
2398
2429
|
const receipt = checkedReceipt(current.receipt, manifest);
|
|
@@ -2413,89 +2444,6 @@ const publishCaptureManifest = async (transport, manifest, directory, blobDirect
|
|
|
2413
2444
|
throw captureError("transport", "Capture publication was not confirmed. Resume the same manifest.", manifest.run.id);
|
|
2414
2445
|
}
|
|
2415
2446
|
};
|
|
2416
|
-
const RATE_LIMIT_STATUS = 429;
|
|
2417
|
-
const MILLISECONDS_PER_SECOND = 1e3;
|
|
2418
|
-
const MAX_ERROR_LENGTH = 1e3;
|
|
2419
|
-
const DEFAULT_TIMEOUT_MS = 3e4;
|
|
2420
|
-
const DEFAULT_PUBLICATION_TIMEOUT_MS = 6e5;
|
|
2421
|
-
const NODE_TIMER_MAX_MS = 2147483647;
|
|
2422
|
-
const HTTP_ERRORS = /* @__PURE__ */ new Map([
|
|
2423
|
-
[401, "authorization"],
|
|
2424
|
-
[403, "authorization"],
|
|
2425
|
-
[409, "conflict"],
|
|
2426
|
-
[400, "artifact"]
|
|
2427
|
-
]);
|
|
2428
|
-
const requestResponse = async (url, options, timeoutMs, retryDeadline) => {
|
|
2429
|
-
try {
|
|
2430
|
-
for (;;) {
|
|
2431
|
-
const response = await fetch(url, {
|
|
2432
|
-
...options,
|
|
2433
|
-
signal: AbortSignal.timeout(timeoutMs)
|
|
2434
|
-
});
|
|
2435
|
-
if (response.status !== RATE_LIMIT_STATUS) return response;
|
|
2436
|
-
const header = response.headers.get("retry-after");
|
|
2437
|
-
if (header === null) return response;
|
|
2438
|
-
const seconds = Number(header);
|
|
2439
|
-
const wait = Number.isFinite(seconds) ? seconds * MILLISECONDS_PER_SECOND : Date.parse(header) - Date.now();
|
|
2440
|
-
if (!Number.isFinite(wait) || wait < 0 || Date.now() + wait >= retryDeadline) return response;
|
|
2441
|
-
await response.body?.cancel();
|
|
2442
|
-
await setTimeout$1(wait);
|
|
2443
|
-
}
|
|
2444
|
-
} catch {
|
|
2445
|
-
throw captureError("transport", "Enhance did not confirm the request. Resume the same run to recover its result.");
|
|
2446
|
-
}
|
|
2447
|
-
};
|
|
2448
|
-
const responseBody = async (response) => {
|
|
2449
|
-
try {
|
|
2450
|
-
return await response.json();
|
|
2451
|
-
} catch {
|
|
2452
|
-
return null;
|
|
2453
|
-
}
|
|
2454
|
-
};
|
|
2455
|
-
const call = async (url, options, schema, request) => {
|
|
2456
|
-
const { procedure, timeoutMs, publicationTimeoutMs } = request;
|
|
2457
|
-
const response = await requestResponse(url, options, timeoutMs, Date.now() + publicationTimeoutMs);
|
|
2458
|
-
const body = await responseBody(response);
|
|
2459
|
-
if (!response.ok) {
|
|
2460
|
-
const error = typeof body === "object" && body !== null ? Reflect.get(body, "error") : null;
|
|
2461
|
-
const message = typeof error === "object" && error !== null ? Reflect.get(error, "message") : null;
|
|
2462
|
-
throw captureError(HTTP_ERRORS.get(response.status) ?? "transport", typeof message === "string" ? message.slice(0, MAX_ERROR_LENGTH) : `Enhance rejected ${procedure} (HTTP ${String(response.status)}).`);
|
|
2463
|
-
}
|
|
2464
|
-
const result = typeof body === "object" && body !== null ? Reflect.get(body, "result") : null;
|
|
2465
|
-
const data = typeof result === "object" && result !== null ? Reflect.get(result, "data") : void 0;
|
|
2466
|
-
const parsed = schema.safeParse(data);
|
|
2467
|
-
if (!parsed.success) throw captureError("transport", `Enhance returned an incompatible ${procedure} response.`);
|
|
2468
|
-
return parsed.data;
|
|
2469
|
-
};
|
|
2470
|
-
const captureTransport = (options) => {
|
|
2471
|
-
const base = URL.parse(options.apiUrl);
|
|
2472
|
-
if (base === null || !["http:", "https:"].includes(base.protocol) || base.username !== "" || base.password !== "" || options.token.trim() === "") throw captureError("configuration", "Enhance needs an HTTP API URL and an explicit token.");
|
|
2473
|
-
const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
2474
|
-
const publicationTimeoutMs = options.publicationTimeoutMs ?? DEFAULT_PUBLICATION_TIMEOUT_MS;
|
|
2475
|
-
if (!Number.isSafeInteger(publicationTimeoutMs) || publicationTimeoutMs < 1) throw captureError("configuration", "Enhance publication timeout must be a positive integer in milliseconds.");
|
|
2476
|
-
if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > NODE_TIMER_MAX_MS) throw captureError("configuration", `Enhance timeout must fit the Node timer range of 1 to ${String(NODE_TIMER_MAX_MS)} milliseconds.`);
|
|
2477
|
-
return {
|
|
2478
|
-
timeoutMs,
|
|
2479
|
-
publicationTimeoutMs,
|
|
2480
|
-
request: async (procedure, input, schema, isQuery = false) => {
|
|
2481
|
-
const url = new URL(`${base.pathname.replace(/\/$/u, "")}/trpc/${procedure}`, base.origin);
|
|
2482
|
-
if (isQuery) url.searchParams.set("input", JSON.stringify(input));
|
|
2483
|
-
return call(url, {
|
|
2484
|
-
method: isQuery ? "GET" : "POST",
|
|
2485
|
-
headers: {
|
|
2486
|
-
authorization: `Bearer ${options.token}`,
|
|
2487
|
-
"content-type": "application/json"
|
|
2488
|
-
},
|
|
2489
|
-
...!isQuery && { body: JSON.stringify(input) },
|
|
2490
|
-
redirect: "error"
|
|
2491
|
-
}, schema, {
|
|
2492
|
-
procedure,
|
|
2493
|
-
timeoutMs,
|
|
2494
|
-
publicationTimeoutMs
|
|
2495
|
-
});
|
|
2496
|
-
}
|
|
2497
|
-
};
|
|
2498
|
-
};
|
|
2499
2447
|
const nodeManifest = (descriptor, captured) => {
|
|
2500
2448
|
const participant = descriptor.participants[0];
|
|
2501
2449
|
if (participant === void 0) throw captureError("configuration", "No capture participant was reserved.");
|
|
@@ -2626,7 +2574,6 @@ const COMMAND_SUMMARIES = {
|
|
|
2626
2574
|
"canvas.create": "Create a canvas.",
|
|
2627
2575
|
"canvas.get": "Read a canvas and access.",
|
|
2628
2576
|
"canvas.setAccess": "Change canvas link access.",
|
|
2629
|
-
"canvas.markViewed": "Mark a canvas as viewed.",
|
|
2630
2577
|
"canvas.list": "List canvases.",
|
|
2631
2578
|
"canvas.rename": "Rename a canvas.",
|
|
2632
2579
|
"canvas.setReviewState": "Set review state.",
|
|
@@ -3477,7 +3424,7 @@ const main = async () => {
|
|
|
3477
3424
|
const remote = createHttpRemoteAdapter(config.apiUrl, credentials, mutationKey);
|
|
3478
3425
|
const cli = createCliProgram({
|
|
3479
3426
|
apiUrl: config.apiUrl,
|
|
3480
|
-
version: "0.1.
|
|
3427
|
+
version: "0.1.39",
|
|
3481
3428
|
credentials,
|
|
3482
3429
|
remote,
|
|
3483
3430
|
mutationKey,
|