orkestrator 2.36.6-beta → 2.37.1-beta
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/artifact-runtime/THIRD_PARTY_NOTICES.txt +1038 -0
- package/dist/artifact-runtime/chart.umd.min.js +14 -0
- package/dist/artifact-runtime/d3.min.js +2 -0
- package/dist/artifact-runtime/licenses/chart.js@4.5.1/@kurkle/color/LICENSE.md +9 -0
- package/dist/artifact-runtime/licenses/chart.js@4.5.1/LICENSE.md +9 -0
- package/dist/artifact-runtime/licenses/d3@7.9.0/LICENSE +13 -0
- package/dist/artifact-runtime/licenses/dompurify@3.4.17/LICENSE +202 -0
- package/dist/artifact-runtime/licenses/dompurify@3.4.17/LICENSE-MPL +373 -0
- package/dist/artifact-runtime/licenses/mermaid@12.2.0/LICENSE +21 -0
- package/dist/artifact-runtime/licenses/pdfjs-dist-worker@6.4.299/LICENSE +177 -0
- package/dist/artifact-runtime/licenses/pdfjs-dist@6.4.299/LICENSE +177 -0
- package/dist/artifact-runtime/mermaid.min.js +4330 -0
- package/dist/artifact-runtime/pdf.min.mjs +28 -0
- package/dist/artifact-runtime/pdf.worker.min.mjs +28 -0
- package/dist/artifact-runtime/preview-worker.js +2043 -0
- package/dist/artifact-runtime/purify.min.js +7 -0
- package/dist/artifact-runtime/seccomp_profile.json +701 -0
- package/dist/artifact-runtime/worker-context/Dockerfile +41 -0
- package/dist/artifact-runtime/worker-context/THIRD_PARTY_NOTICES.txt +1038 -0
- package/dist/artifact-runtime/worker-context/chart.umd.min.js +14 -0
- package/dist/artifact-runtime/worker-context/d3.min.js +2 -0
- package/dist/artifact-runtime/worker-context/licenses/chart.js@4.5.1/@kurkle/color/LICENSE.md +9 -0
- package/dist/artifact-runtime/worker-context/licenses/chart.js@4.5.1/LICENSE.md +9 -0
- package/dist/artifact-runtime/worker-context/licenses/d3@7.9.0/LICENSE +13 -0
- package/dist/artifact-runtime/worker-context/licenses/dompurify@3.4.17/LICENSE +202 -0
- package/dist/artifact-runtime/worker-context/licenses/dompurify@3.4.17/LICENSE-MPL +373 -0
- package/dist/artifact-runtime/worker-context/licenses/mermaid@12.2.0/LICENSE +21 -0
- package/dist/artifact-runtime/worker-context/licenses/pdfjs-dist-worker@6.4.299/LICENSE +177 -0
- package/dist/artifact-runtime/worker-context/licenses/pdfjs-dist@6.4.299/LICENSE +177 -0
- package/dist/artifact-runtime/worker-context/mermaid.min.js +4330 -0
- package/dist/artifact-runtime/worker-context/package-lock.json +25 -0
- package/dist/artifact-runtime/worker-context/package.json +8 -0
- package/dist/artifact-runtime/worker-context/pdf.min.mjs +28 -0
- package/dist/artifact-runtime/worker-context/pdf.worker.min.mjs +28 -0
- package/dist/artifact-runtime/worker-context/preview-worker.mjs +2042 -0
- package/dist/artifact-runtime/worker-context/purify.min.js +7 -0
- package/dist/artifact-runtime/worker-context/seccomp_profile.json +701 -0
- package/dist/client.js +6132 -294
- package/dist/main.js +103177 -64996
- package/package.json +4 -4
- package/resources/acp-bridge/dist/index.js +253 -36
- package/resources/claude-bridge/dist/index.js +2705 -2320
- package/resources/codex-bridge/dist/index.js +332 -34
- package/resources/cursor-bridge/dist/index.js +160 -11
- package/resources/cursor-bridge/runtime/bun.lock +8 -8
- package/resources/cursor-bridge/runtime/install.json +1 -1
- package/resources/cursor-bridge/runtime/package.json +2 -2
- package/resources/cursor-bridge/runtime/patches/@cursor%2Fsdk@1.3.1.patch +19 -0
- package/resources/pi-bridge/dist/index.js +622 -86
- package/resources/pi-bridge/runtime/bun.lock +36 -32
- package/resources/pi-bridge/runtime/install.json +1 -1
- package/resources/pi-bridge/runtime/package.json +3 -3
- package/resources/release-runtime/bun.lock +13 -13
- package/resources/release-runtime/package.json +1 -1
- package/resources/cursor-bridge/runtime/patches/@cursor%2Fsdk@1.2.0.patch +0 -19
|
@@ -0,0 +1,2043 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
// ../../apps/backend/src/core/transcript-artifacts/preview-worker-protocol.ts
|
|
3
|
+
var PREVIEW_WORKER_PROTOCOL = 1;
|
|
4
|
+
|
|
5
|
+
// ../../apps/backend/src/core/transcript-artifacts/preview-jobs.ts
|
|
6
|
+
import { randomUUID as randomUUID2 } from "crypto";
|
|
7
|
+
import { chromium } from "playwright-core";
|
|
8
|
+
|
|
9
|
+
// ../protocol/src/keyboard-shortcuts.ts
|
|
10
|
+
var APP_SHORTCUTS = [
|
|
11
|
+
{
|
|
12
|
+
id: "show-shortcuts",
|
|
13
|
+
key: "/",
|
|
14
|
+
shift: true,
|
|
15
|
+
owner: "document",
|
|
16
|
+
fromPreviews: true,
|
|
17
|
+
ctrlEditsText: false
|
|
18
|
+
},
|
|
19
|
+
{
|
|
20
|
+
id: "search-projects",
|
|
21
|
+
key: "k",
|
|
22
|
+
shift: false,
|
|
23
|
+
owner: "window",
|
|
24
|
+
fromPreviews: false,
|
|
25
|
+
ctrlEditsText: true
|
|
26
|
+
},
|
|
27
|
+
{
|
|
28
|
+
id: "open-settings",
|
|
29
|
+
key: ",",
|
|
30
|
+
shift: false,
|
|
31
|
+
owner: "window",
|
|
32
|
+
fromPreviews: true,
|
|
33
|
+
ctrlEditsText: false
|
|
34
|
+
},
|
|
35
|
+
{
|
|
36
|
+
id: "new-agent-tab",
|
|
37
|
+
key: "t",
|
|
38
|
+
shift: false,
|
|
39
|
+
owner: "workspace",
|
|
40
|
+
fromPreviews: true,
|
|
41
|
+
ctrlEditsText: true
|
|
42
|
+
},
|
|
43
|
+
{
|
|
44
|
+
id: "rotate-sidebar-grouping",
|
|
45
|
+
key: "d",
|
|
46
|
+
shift: true,
|
|
47
|
+
owner: "window",
|
|
48
|
+
fromPreviews: false,
|
|
49
|
+
ctrlEditsText: false
|
|
50
|
+
}
|
|
51
|
+
];
|
|
52
|
+
function matchAppShortcut(chord, shortcuts = APP_SHORTCUTS) {
|
|
53
|
+
if (chord.metaKey === chord.ctrlKey || chord.altKey)
|
|
54
|
+
return null;
|
|
55
|
+
const key = chord.key;
|
|
56
|
+
const code = chord.code;
|
|
57
|
+
const pressed = typeof key === "string" && /^[\x21-\x7e]$/.test(key) ? key.toLowerCase() : typeof code === "string" && /^Key[A-Z]$/.test(code) ? code.slice(3).toLowerCase() : code === "Comma" ? "," : code === "Slash" ? "/" : null;
|
|
58
|
+
if (!pressed)
|
|
59
|
+
return null;
|
|
60
|
+
const typed = pressed === "?" ? "/" : pressed;
|
|
61
|
+
for (const shortcut of shortcuts) {
|
|
62
|
+
if (shortcut.key === typed && shortcut.shift === chord.shiftKey)
|
|
63
|
+
return shortcut.id;
|
|
64
|
+
}
|
|
65
|
+
return null;
|
|
66
|
+
}
|
|
67
|
+
function appClaimsShortcut(shortcut, chord, platform, focus) {
|
|
68
|
+
if (!shortcut.ctrlEditsText || chord.metaKey || !chord.ctrlKey)
|
|
69
|
+
return true;
|
|
70
|
+
if (focus === "terminal")
|
|
71
|
+
return false;
|
|
72
|
+
return !(focus === "text" && platform === "mac");
|
|
73
|
+
}
|
|
74
|
+
function shortcutFocus(target) {
|
|
75
|
+
if (!(target instanceof Element))
|
|
76
|
+
return "page";
|
|
77
|
+
if (target.closest(".xterm"))
|
|
78
|
+
return "terminal";
|
|
79
|
+
if (target.closest(".monaco-editor"))
|
|
80
|
+
return "text";
|
|
81
|
+
if (target instanceof HTMLElement && target.isContentEditable)
|
|
82
|
+
return "text";
|
|
83
|
+
if (target instanceof HTMLInputElement)
|
|
84
|
+
return [
|
|
85
|
+
"button",
|
|
86
|
+
"checkbox",
|
|
87
|
+
"color",
|
|
88
|
+
"file",
|
|
89
|
+
"image",
|
|
90
|
+
"radio",
|
|
91
|
+
"range",
|
|
92
|
+
"reset",
|
|
93
|
+
"submit"
|
|
94
|
+
].includes(target.type) ? "page" : "text";
|
|
95
|
+
return target instanceof HTMLTextAreaElement || target instanceof HTMLSelectElement ? "text" : "page";
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
// ../protocol/src/design-runtime.ts
|
|
99
|
+
function installDesignRuntime(matchesShortcut, shortcuts, claimsShortcut, focusedSurface) {
|
|
100
|
+
const MAX_HTML_BYTES = 256 * 1024;
|
|
101
|
+
const MAX_ELEMENTS = 5000;
|
|
102
|
+
const forbidden = "script,iframe,frame,object,embed,base,meta,link,portal,applet";
|
|
103
|
+
const externalUrl = /^\s*(?:https?:)?\/\//i;
|
|
104
|
+
const cssExternal = /url\(\s*['"]?\s*(?:https?:)?\/\//gi;
|
|
105
|
+
const cssImport = /@import\s/gi;
|
|
106
|
+
let mode = "inspect";
|
|
107
|
+
const emptyCounts = () => ({
|
|
108
|
+
scripts: 0,
|
|
109
|
+
handlers: 0,
|
|
110
|
+
externalReferences: 0,
|
|
111
|
+
forbiddenElements: 0,
|
|
112
|
+
executableUrls: 0
|
|
113
|
+
});
|
|
114
|
+
function countCss(text, counts) {
|
|
115
|
+
if (!text)
|
|
116
|
+
return;
|
|
117
|
+
counts.externalReferences += (text.match(cssExternal) ?? []).length;
|
|
118
|
+
counts.externalReferences += (text.match(cssImport) ?? []).length;
|
|
119
|
+
}
|
|
120
|
+
function clean(doc, counts) {
|
|
121
|
+
doc.querySelectorAll(forbidden).forEach((node) => {
|
|
122
|
+
if (node.tagName.toLowerCase() === "script")
|
|
123
|
+
counts.scripts++;
|
|
124
|
+
else
|
|
125
|
+
counts.forbiddenElements++;
|
|
126
|
+
node.remove();
|
|
127
|
+
});
|
|
128
|
+
for (const node of Array.from(doc.querySelectorAll("*"))) {
|
|
129
|
+
if (node.tagName.toLowerCase() === "style")
|
|
130
|
+
countCss(node.textContent, counts);
|
|
131
|
+
for (const attr of Array.from(node.attributes)) {
|
|
132
|
+
const lower = attr.name.toLowerCase();
|
|
133
|
+
if (/^on/i.test(attr.name)) {
|
|
134
|
+
counts.handlers++;
|
|
135
|
+
node.removeAttribute(attr.name);
|
|
136
|
+
} else if (["srcdoc", "nonce", "http-equiv", "action", "formaction"].includes(lower)) {
|
|
137
|
+
counts.forbiddenElements++;
|
|
138
|
+
node.removeAttribute(attr.name);
|
|
139
|
+
} else if (["href", "src", "xlink:href", "srcset", "poster"].includes(lower)) {
|
|
140
|
+
if (/^(?:javascript|vbscript):/i.test(attr.value.trim())) {
|
|
141
|
+
counts.executableUrls++;
|
|
142
|
+
node.removeAttribute(attr.name);
|
|
143
|
+
} else if (externalUrl.test(attr.value) && lower !== "href") {
|
|
144
|
+
counts.externalReferences++;
|
|
145
|
+
}
|
|
146
|
+
} else if (lower === "style") {
|
|
147
|
+
countCss(attr.value, counts);
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
if (node instanceof HTMLTemplateElement)
|
|
151
|
+
clean(node.content, counts);
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
function elementCount(root) {
|
|
155
|
+
let total = 0;
|
|
156
|
+
for (const node of Array.from(root.querySelectorAll("*"))) {
|
|
157
|
+
total++;
|
|
158
|
+
if (node instanceof HTMLTemplateElement)
|
|
159
|
+
total += elementCount(node.content);
|
|
160
|
+
}
|
|
161
|
+
return total;
|
|
162
|
+
}
|
|
163
|
+
function depthOf(root) {
|
|
164
|
+
if (!root)
|
|
165
|
+
return 0;
|
|
166
|
+
let deepest = 0;
|
|
167
|
+
const stack = [[root, 1]];
|
|
168
|
+
while (stack.length) {
|
|
169
|
+
const [el, depth] = stack.pop();
|
|
170
|
+
if (depth > deepest)
|
|
171
|
+
deepest = depth;
|
|
172
|
+
for (const child of Array.from(el.children))
|
|
173
|
+
stack.push([child, depth + 1]);
|
|
174
|
+
}
|
|
175
|
+
return deepest;
|
|
176
|
+
}
|
|
177
|
+
function byteLength(value) {
|
|
178
|
+
return new TextEncoder().encode(value).length;
|
|
179
|
+
}
|
|
180
|
+
function parse(html, counts = emptyCounts()) {
|
|
181
|
+
if (typeof html !== "string")
|
|
182
|
+
throw new Error("Invalid HTML");
|
|
183
|
+
if (byteLength(html) > MAX_HTML_BYTES)
|
|
184
|
+
throw new Error("HTML exceeds 256 KiB");
|
|
185
|
+
const doc = new DOMParser().parseFromString(html, "text/html");
|
|
186
|
+
clean(doc, counts);
|
|
187
|
+
if (elementCount(doc) > MAX_ELEMENTS)
|
|
188
|
+
throw new Error("Frame exceeds 5000 elements");
|
|
189
|
+
return doc;
|
|
190
|
+
}
|
|
191
|
+
function selector(el) {
|
|
192
|
+
if (el === document.documentElement)
|
|
193
|
+
return "html";
|
|
194
|
+
if (el === document.body)
|
|
195
|
+
return "body";
|
|
196
|
+
if (el === document.head)
|
|
197
|
+
return "head";
|
|
198
|
+
const path = [];
|
|
199
|
+
let current = el;
|
|
200
|
+
while (current && current !== document.body && current !== document.documentElement) {
|
|
201
|
+
const parent = current.parentElement;
|
|
202
|
+
if (!parent)
|
|
203
|
+
break;
|
|
204
|
+
path.unshift(`:nth-child(${Array.from(parent.children).indexOf(current) + 1})`);
|
|
205
|
+
current = parent;
|
|
206
|
+
}
|
|
207
|
+
return `${current === document.body ? "body" : "html"} > ${path.join(" > ")}`;
|
|
208
|
+
}
|
|
209
|
+
function find(value) {
|
|
210
|
+
if (typeof value !== "string" || value.length > 2048)
|
|
211
|
+
throw new Error("Invalid selector");
|
|
212
|
+
let nodes;
|
|
213
|
+
try {
|
|
214
|
+
nodes = document.querySelectorAll(value);
|
|
215
|
+
} catch {
|
|
216
|
+
throw new Error("Invalid selector");
|
|
217
|
+
}
|
|
218
|
+
if (nodes.length !== 1 || !(nodes[0] instanceof HTMLElement || nodes[0] instanceof SVGElement)) {
|
|
219
|
+
throw new Error("Selector must match exactly one element");
|
|
220
|
+
}
|
|
221
|
+
return nodes[0];
|
|
222
|
+
}
|
|
223
|
+
const inspected = [
|
|
224
|
+
"display",
|
|
225
|
+
"position",
|
|
226
|
+
"width",
|
|
227
|
+
"height",
|
|
228
|
+
"min-width",
|
|
229
|
+
"min-height",
|
|
230
|
+
"max-width",
|
|
231
|
+
"max-height",
|
|
232
|
+
"box-sizing",
|
|
233
|
+
"color",
|
|
234
|
+
"background-color",
|
|
235
|
+
"font-size",
|
|
236
|
+
"font-family",
|
|
237
|
+
"font-weight",
|
|
238
|
+
"line-height",
|
|
239
|
+
"letter-spacing",
|
|
240
|
+
"text-align",
|
|
241
|
+
"padding",
|
|
242
|
+
"margin",
|
|
243
|
+
"gap",
|
|
244
|
+
"border-radius",
|
|
245
|
+
"border",
|
|
246
|
+
"border-color",
|
|
247
|
+
"border-width",
|
|
248
|
+
"border-style",
|
|
249
|
+
"opacity",
|
|
250
|
+
"visibility",
|
|
251
|
+
"flex-direction",
|
|
252
|
+
"flex-wrap",
|
|
253
|
+
"align-items",
|
|
254
|
+
"justify-content",
|
|
255
|
+
"top",
|
|
256
|
+
"left",
|
|
257
|
+
"bottom",
|
|
258
|
+
"right"
|
|
259
|
+
];
|
|
260
|
+
function inspect(el) {
|
|
261
|
+
const rect = el.getBoundingClientRect();
|
|
262
|
+
const computed = getComputedStyle(el);
|
|
263
|
+
const styles = {};
|
|
264
|
+
for (const name of inspected)
|
|
265
|
+
styles[name] = computed.getPropertyValue(name);
|
|
266
|
+
const inline = {};
|
|
267
|
+
const inlinePriority = {};
|
|
268
|
+
const style = el.style;
|
|
269
|
+
if (style) {
|
|
270
|
+
for (let index = 0;index < style.length && index < 128; index++) {
|
|
271
|
+
const name = style.item(index);
|
|
272
|
+
inline[name] = style.getPropertyValue(name).slice(0, 2048);
|
|
273
|
+
if (style.getPropertyPriority(name) === "important")
|
|
274
|
+
inlinePriority[name] = "important";
|
|
275
|
+
if (!(name in styles) && Object.keys(styles).length < 160)
|
|
276
|
+
styles[name] = computed.getPropertyValue(name);
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
const allAttributes = Array.from(el.attributes);
|
|
280
|
+
const text = el.textContent ?? "";
|
|
281
|
+
const path = selector(el);
|
|
282
|
+
return {
|
|
283
|
+
selector: path,
|
|
284
|
+
key: path,
|
|
285
|
+
tag: el.tagName.toLowerCase(),
|
|
286
|
+
text: text.slice(0, 200),
|
|
287
|
+
textTruncated: text.length > 200,
|
|
288
|
+
attributes: Object.fromEntries(allAttributes.slice(0, 64).map((a) => [a.name, a.value.slice(0, 1024)])),
|
|
289
|
+
attributesTruncated: allAttributes.length > 64,
|
|
290
|
+
styles,
|
|
291
|
+
inline,
|
|
292
|
+
inlinePriority,
|
|
293
|
+
svg: el instanceof SVGElement,
|
|
294
|
+
rect: { x: rect.x, y: rect.y, width: rect.width, height: rect.height },
|
|
295
|
+
scroll: { x: window.scrollX, y: window.scrollY }
|
|
296
|
+
};
|
|
297
|
+
}
|
|
298
|
+
function serialize() {
|
|
299
|
+
if (elementCount(document) > MAX_ELEMENTS)
|
|
300
|
+
throw new Error("Frame exceeds 5000 elements");
|
|
301
|
+
const html = `<!doctype html>
|
|
302
|
+
` + document.documentElement.outerHTML;
|
|
303
|
+
if (byteLength(html) > MAX_HTML_BYTES)
|
|
304
|
+
throw new Error("HTML exceeds 256 KiB");
|
|
305
|
+
return html;
|
|
306
|
+
}
|
|
307
|
+
function splitPriority(value) {
|
|
308
|
+
const match = /^(.*?)\s*!\s*important\s*$/i.exec(value);
|
|
309
|
+
return match ? { value: match[1], priority: "important" } : { value, priority: "" };
|
|
310
|
+
}
|
|
311
|
+
function applyStyles(target, styles, commit) {
|
|
312
|
+
const entries = Object.entries(styles ?? {});
|
|
313
|
+
if (entries.length > 64)
|
|
314
|
+
throw new Error("Too many styles");
|
|
315
|
+
const invalid = [];
|
|
316
|
+
const unchanged = [];
|
|
317
|
+
const probe = document.createElement("div");
|
|
318
|
+
const planned = [];
|
|
319
|
+
for (const [rawKey, rawValue] of entries) {
|
|
320
|
+
const key = rawKey.trim();
|
|
321
|
+
if (!/^(--[a-zA-Z0-9_-]+|[a-z-]+)$/.test(key) || key.length > 100 || rawValue !== null && (typeof rawValue !== "string" || rawValue.length > 2048)) {
|
|
322
|
+
invalid.push(rawKey.slice(0, 100));
|
|
323
|
+
continue;
|
|
324
|
+
}
|
|
325
|
+
const current = target.style.getPropertyValue(key);
|
|
326
|
+
const currentPriority = target.style.getPropertyPriority(key);
|
|
327
|
+
if (rawValue === null || rawValue.trim() === "") {
|
|
328
|
+
if (!current)
|
|
329
|
+
unchanged.push(key);
|
|
330
|
+
planned.push([key, null, ""]);
|
|
331
|
+
continue;
|
|
332
|
+
}
|
|
333
|
+
const { value, priority } = splitPriority(rawValue.trim());
|
|
334
|
+
probe.style.cssText = "";
|
|
335
|
+
probe.style.setProperty(key, value, priority);
|
|
336
|
+
const accepted = probe.style.getPropertyValue(key);
|
|
337
|
+
if (!accepted && !key.startsWith("--")) {
|
|
338
|
+
invalid.push(key);
|
|
339
|
+
continue;
|
|
340
|
+
}
|
|
341
|
+
if (accepted === current && priority === currentPriority)
|
|
342
|
+
unchanged.push(key);
|
|
343
|
+
planned.push([key, value, priority]);
|
|
344
|
+
}
|
|
345
|
+
if (invalid.length > 0)
|
|
346
|
+
return { html: "", invalid, unchanged };
|
|
347
|
+
if (!commit) {
|
|
348
|
+
for (const [key, value, priority] of planned) {
|
|
349
|
+
if (value === null)
|
|
350
|
+
target.style.removeProperty(key);
|
|
351
|
+
else
|
|
352
|
+
target.style.setProperty(key, value, priority);
|
|
353
|
+
}
|
|
354
|
+
return { html: "", invalid, unchanged };
|
|
355
|
+
}
|
|
356
|
+
if (unchanged.length === planned.length)
|
|
357
|
+
return { html: "", invalid, unchanged };
|
|
358
|
+
for (const [key, value, priority] of planned) {
|
|
359
|
+
if (value === null)
|
|
360
|
+
target.style.removeProperty(key);
|
|
361
|
+
else
|
|
362
|
+
target.style.setProperty(key, value, priority);
|
|
363
|
+
}
|
|
364
|
+
if (target.getAttribute("style") === "")
|
|
365
|
+
target.removeAttribute("style");
|
|
366
|
+
return { html: serialize(), invalid, unchanged };
|
|
367
|
+
}
|
|
368
|
+
function structureFingerprint(root) {
|
|
369
|
+
let hash = 2166136261;
|
|
370
|
+
let count = 0;
|
|
371
|
+
const walk = (el) => {
|
|
372
|
+
count++;
|
|
373
|
+
const tag = el.tagName;
|
|
374
|
+
for (let i = 0;i < tag.length; i++) {
|
|
375
|
+
hash ^= tag.charCodeAt(i);
|
|
376
|
+
hash = Math.imul(hash, 16777619);
|
|
377
|
+
}
|
|
378
|
+
hash ^= el.children.length;
|
|
379
|
+
hash = Math.imul(hash, 16777619);
|
|
380
|
+
for (const child of Array.from(el.children))
|
|
381
|
+
walk(child);
|
|
382
|
+
};
|
|
383
|
+
walk(root);
|
|
384
|
+
return `${(hash >>> 0).toString(36)}.${count}`;
|
|
385
|
+
}
|
|
386
|
+
function label(el) {
|
|
387
|
+
return (el.id || el.getAttribute("aria-label") || el.tagName.toLowerCase()).slice(0, 100);
|
|
388
|
+
}
|
|
389
|
+
function hierarchyPage(input) {
|
|
390
|
+
const root = input.rootSelector ? find(input.rootSelector) : document.body;
|
|
391
|
+
const maxNodes = Math.max(1, Math.min(200, Math.floor(input.maxNodes ?? 200)));
|
|
392
|
+
const maxBytes = Math.max(1024, Math.min(128 * 1024, Math.floor(input.maxBytes ?? 128 * 1024)));
|
|
393
|
+
const maxDepth = Math.max(1, Math.min(32, Math.floor(input.maxDepth ?? 1)));
|
|
394
|
+
const fingerprint = structureFingerprint(document.body);
|
|
395
|
+
let offset = 0;
|
|
396
|
+
if (input.cursor) {
|
|
397
|
+
const [expected, value] = String(input.cursor).split(":");
|
|
398
|
+
if (expected !== fingerprint)
|
|
399
|
+
throw new Error("Hierarchy changed; reload this branch");
|
|
400
|
+
offset = Math.max(0, Number.parseInt(value ?? "0", 10) || 0);
|
|
401
|
+
}
|
|
402
|
+
const flat = [];
|
|
403
|
+
const walk = (el, depth) => {
|
|
404
|
+
for (const child of Array.from(el.children)) {
|
|
405
|
+
if (child.tagName === "HEAD")
|
|
406
|
+
continue;
|
|
407
|
+
flat.push([child, depth]);
|
|
408
|
+
if (depth < maxDepth)
|
|
409
|
+
walk(child, depth + 1);
|
|
410
|
+
}
|
|
411
|
+
};
|
|
412
|
+
walk(root, 1);
|
|
413
|
+
const layers = [];
|
|
414
|
+
let bytes = 0;
|
|
415
|
+
let index = offset;
|
|
416
|
+
for (;index < flat.length && layers.length < maxNodes; index++) {
|
|
417
|
+
const [el, depth] = flat[index];
|
|
418
|
+
const layer = {
|
|
419
|
+
selector: selector(el),
|
|
420
|
+
tag: el.tagName.toLowerCase(),
|
|
421
|
+
label: label(el),
|
|
422
|
+
depth,
|
|
423
|
+
childCount: el.children.length
|
|
424
|
+
};
|
|
425
|
+
const size = layer.selector.length + layer.label.length + 48;
|
|
426
|
+
if (bytes + size > maxBytes && layers.length > 0)
|
|
427
|
+
break;
|
|
428
|
+
bytes += size;
|
|
429
|
+
layers.push(layer);
|
|
430
|
+
}
|
|
431
|
+
return {
|
|
432
|
+
layers,
|
|
433
|
+
total: flat.length,
|
|
434
|
+
truncated: index < flat.length,
|
|
435
|
+
bytes,
|
|
436
|
+
...index < flat.length ? { nextCursor: `${fingerprint}:${index}` } : {}
|
|
437
|
+
};
|
|
438
|
+
}
|
|
439
|
+
function validate(html) {
|
|
440
|
+
if (typeof html !== "string")
|
|
441
|
+
throw new Error("Invalid HTML");
|
|
442
|
+
if (byteLength(html) > MAX_HTML_BYTES)
|
|
443
|
+
throw new Error("HTML exceeds 256 KiB");
|
|
444
|
+
const counts = emptyCounts();
|
|
445
|
+
const doc = new DOMParser().parseFromString(html, "text/html");
|
|
446
|
+
clean(doc, counts);
|
|
447
|
+
const total = elementCount(doc);
|
|
448
|
+
return {
|
|
449
|
+
elementCount: total,
|
|
450
|
+
maxDepth: depthOf(doc.documentElement),
|
|
451
|
+
removed: counts,
|
|
452
|
+
overElementLimit: total > MAX_ELEMENTS
|
|
453
|
+
};
|
|
454
|
+
}
|
|
455
|
+
function run(input) {
|
|
456
|
+
switch (input.op) {
|
|
457
|
+
case "render": {
|
|
458
|
+
const doc = parse(input.html);
|
|
459
|
+
document.documentElement.replaceChildren(...Array.from(doc.documentElement.childNodes).map((node) => document.importNode(node, true)));
|
|
460
|
+
for (const attr of Array.from(document.documentElement.attributes))
|
|
461
|
+
document.documentElement.removeAttribute(attr.name);
|
|
462
|
+
for (const attr of Array.from(doc.documentElement.attributes))
|
|
463
|
+
document.documentElement.setAttribute(attr.name, attr.value);
|
|
464
|
+
return true;
|
|
465
|
+
}
|
|
466
|
+
case "validate":
|
|
467
|
+
return validate(input.html);
|
|
468
|
+
case "hitTest": {
|
|
469
|
+
const el = document.elementFromPoint(input.x, input.y);
|
|
470
|
+
return el ? inspect(el) : null;
|
|
471
|
+
}
|
|
472
|
+
case "inspectElement":
|
|
473
|
+
return inspect(find(input.selector));
|
|
474
|
+
case "setStyles": {
|
|
475
|
+
const result = applyStyles(find(input.selector), input.styles, true);
|
|
476
|
+
if (result.invalid.length)
|
|
477
|
+
throw new Error(`Invalid style: ${result.invalid.join(", ")}`);
|
|
478
|
+
return result.html || serialize();
|
|
479
|
+
}
|
|
480
|
+
case "applyStyles":
|
|
481
|
+
return applyStyles(find(input.selector), input.styles, true);
|
|
482
|
+
case "previewStyles":
|
|
483
|
+
return applyStyles(find(input.selector), input.styles, false);
|
|
484
|
+
case "replaceElementHtml": {
|
|
485
|
+
const el = find(input.selector);
|
|
486
|
+
if (el === document.body || el === document.documentElement || !document.body.contains(el))
|
|
487
|
+
throw new Error("Select an element inside the body");
|
|
488
|
+
el.replaceWith(...Array.from(parse(input.html).body.childNodes));
|
|
489
|
+
return serialize();
|
|
490
|
+
}
|
|
491
|
+
case "appendHtml": {
|
|
492
|
+
const doc = parse(input.html);
|
|
493
|
+
document.head.append(...Array.from(doc.head.childNodes));
|
|
494
|
+
document.body.append(...Array.from(doc.body.childNodes));
|
|
495
|
+
return serialize();
|
|
496
|
+
}
|
|
497
|
+
case "moveElement": {
|
|
498
|
+
const el = find(input.selector), parent = find(input.parentSelector);
|
|
499
|
+
const before = input.beforeSelector ? find(input.beforeSelector) : null;
|
|
500
|
+
const unsafeParents = new Set([
|
|
501
|
+
"AREA",
|
|
502
|
+
"BASE",
|
|
503
|
+
"BR",
|
|
504
|
+
"COL",
|
|
505
|
+
"EMBED",
|
|
506
|
+
"HR",
|
|
507
|
+
"IMG",
|
|
508
|
+
"INPUT",
|
|
509
|
+
"LINK",
|
|
510
|
+
"META",
|
|
511
|
+
"PARAM",
|
|
512
|
+
"SOURCE",
|
|
513
|
+
"TRACK",
|
|
514
|
+
"WBR",
|
|
515
|
+
"TEMPLATE",
|
|
516
|
+
"SCRIPT",
|
|
517
|
+
"STYLE",
|
|
518
|
+
"TEXTAREA",
|
|
519
|
+
"TITLE",
|
|
520
|
+
"XMP",
|
|
521
|
+
"NOSCRIPT",
|
|
522
|
+
"IFRAME",
|
|
523
|
+
"OBJECT",
|
|
524
|
+
"SELECT",
|
|
525
|
+
"OPTION",
|
|
526
|
+
"OPTGROUP"
|
|
527
|
+
]);
|
|
528
|
+
if (!document.body.contains(el) || el === document.body || !document.body.contains(parent) || el.contains(parent) || unsafeParents.has(parent.tagName) || before && before.parentElement !== parent)
|
|
529
|
+
throw new Error("Invalid element move");
|
|
530
|
+
parent.insertBefore(el, before);
|
|
531
|
+
return serialize();
|
|
532
|
+
}
|
|
533
|
+
case "serialize":
|
|
534
|
+
return serialize();
|
|
535
|
+
case "hierarchy": {
|
|
536
|
+
const result = [];
|
|
537
|
+
const walk = (el, depth) => {
|
|
538
|
+
if (result.length >= 1000 || depth > 32)
|
|
539
|
+
return;
|
|
540
|
+
result.push({
|
|
541
|
+
selector: selector(el),
|
|
542
|
+
tag: el.tagName.toLowerCase(),
|
|
543
|
+
label: label(el),
|
|
544
|
+
depth
|
|
545
|
+
});
|
|
546
|
+
for (const child of Array.from(el.children))
|
|
547
|
+
walk(child, depth + 1);
|
|
548
|
+
};
|
|
549
|
+
walk(document.body, 0);
|
|
550
|
+
return result;
|
|
551
|
+
}
|
|
552
|
+
case "hierarchyPage":
|
|
553
|
+
return hierarchyPage(input);
|
|
554
|
+
case "setMode":
|
|
555
|
+
mode = input.mode === "preview" ? "preview" : "inspect";
|
|
556
|
+
document.documentElement.toggleAttribute("data-ork-preview", mode === "preview");
|
|
557
|
+
if (mode === "inspect")
|
|
558
|
+
window.scrollTo(0, 0);
|
|
559
|
+
return mode;
|
|
560
|
+
case "scrollOffset":
|
|
561
|
+
return { x: window.scrollX, y: window.scrollY };
|
|
562
|
+
}
|
|
563
|
+
}
|
|
564
|
+
window.orkDesign = run;
|
|
565
|
+
window.addEventListener("message", (event) => {
|
|
566
|
+
if (event.source !== window.parent || !event.data || event.data.channel !== "orkestrator-design" || typeof event.data.requestId !== "string")
|
|
567
|
+
return;
|
|
568
|
+
const { requestId, operation } = event.data;
|
|
569
|
+
try {
|
|
570
|
+
window.parent.postMessage({ channel: "orkestrator-design", requestId, result: run(operation) }, "*");
|
|
571
|
+
} catch (error) {
|
|
572
|
+
window.parent.postMessage({
|
|
573
|
+
channel: "orkestrator-design",
|
|
574
|
+
requestId,
|
|
575
|
+
error: error instanceof Error ? error.message : "Runtime failed"
|
|
576
|
+
}, "*");
|
|
577
|
+
}
|
|
578
|
+
});
|
|
579
|
+
document.addEventListener("click", (event) => event.preventDefault(), true);
|
|
580
|
+
document.addEventListener("auxclick", (event) => event.preventDefault(), true);
|
|
581
|
+
document.addEventListener("submit", (event) => event.preventDefault(), true);
|
|
582
|
+
document.addEventListener("keydown", (event) => {
|
|
583
|
+
const shortcut = matchesShortcut && shortcuts ? matchesShortcut(event, shortcuts) : null;
|
|
584
|
+
const definition = shortcuts?.find((entry) => entry.id === shortcut);
|
|
585
|
+
if (definition && claimsShortcut && focusedSurface && claimsShortcut(definition, event, /Mac|iPhone|iPad|iPod/i.test(navigator.platform || navigator.userAgent) ? "mac" : "other", focusedSurface(event.target))) {
|
|
586
|
+
event.preventDefault();
|
|
587
|
+
event.stopPropagation();
|
|
588
|
+
if (!event.repeat)
|
|
589
|
+
window.parent.postMessage({ channel: "orkestrator-design-shortcuts", shortcut }, "*");
|
|
590
|
+
return;
|
|
591
|
+
}
|
|
592
|
+
if (event.key === "Escape")
|
|
593
|
+
window.parent.postMessage({ channel: "orkestrator-design-escape" }, "*");
|
|
594
|
+
}, true);
|
|
595
|
+
}
|
|
596
|
+
function designDocument(scriptSource, scriptAttributes, script) {
|
|
597
|
+
return `<!doctype html><html><head><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src ${scriptSource}; style-src 'unsafe-inline'; img-src data:; font-src data:; connect-src 'none'; frame-src 'none'; object-src 'none'; base-uri 'none'; form-action 'none'"></head><body><script${scriptAttributes}>${script}</script></body></html>`;
|
|
598
|
+
}
|
|
599
|
+
function designRuntimeScript() {
|
|
600
|
+
return `(${installDesignRuntime.toString()})(${matchAppShortcut.toString()}, ${JSON.stringify(APP_SHORTCUTS)}, ${appClaimsShortcut.toString()}, ${shortcutFocus.toString()});`;
|
|
601
|
+
}
|
|
602
|
+
function designBootstrap(nonce) {
|
|
603
|
+
if (!/^[a-zA-Z0-9-]{16,80}$/.test(nonce))
|
|
604
|
+
throw new Error("Invalid runtime nonce");
|
|
605
|
+
return designDocument(`'nonce-${nonce}'`, ` nonce="${nonce}"`, designRuntimeScript());
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
// ../protocol/src/rich-content-policy.ts
|
|
609
|
+
var KIB = 1024;
|
|
610
|
+
var MIB = 1024 * KIB;
|
|
611
|
+
var CODE_BLOCK_POLICY = {
|
|
612
|
+
maxHighlightBytes: 32 * KIB,
|
|
613
|
+
maxHighlightLines: 2000,
|
|
614
|
+
initialVisualLines: 24
|
|
615
|
+
};
|
|
616
|
+
var MERMAID_POLICY = {
|
|
617
|
+
maxSourceBytes: 32 * KIB,
|
|
618
|
+
maxEdges: 250,
|
|
619
|
+
maxSvgBytes: 1 * MIB,
|
|
620
|
+
maxSvgElements: 5000,
|
|
621
|
+
renderTimeoutMs: 5000
|
|
622
|
+
};
|
|
623
|
+
var CHART_POLICY = {
|
|
624
|
+
maxPayloadBytes: 256 * KIB,
|
|
625
|
+
maxSeries: 6,
|
|
626
|
+
maxBarCategories: 100,
|
|
627
|
+
maxCartesianPoints: 2000,
|
|
628
|
+
maxDonutSlices: 24,
|
|
629
|
+
maxTitleCharacters: 200,
|
|
630
|
+
maxLabelCharacters: 200,
|
|
631
|
+
maxDescriptionCharacters: 2000,
|
|
632
|
+
maxSourceNotes: 8,
|
|
633
|
+
maxSourceNoteCharacters: 500,
|
|
634
|
+
maxIdCharacters: 64,
|
|
635
|
+
maxUnitCharacters: 32,
|
|
636
|
+
maxAbsoluteValue: 1000000000000000,
|
|
637
|
+
maxJsonDepth: 16
|
|
638
|
+
};
|
|
639
|
+
var WORKFLOW_SNAPSHOT_POLICY = {
|
|
640
|
+
maxNormalizedBytes: 256 * KIB,
|
|
641
|
+
maxNodes: 200,
|
|
642
|
+
maxEdges: 400,
|
|
643
|
+
maxIdCharacters: 128,
|
|
644
|
+
maxLabelCharacters: 200,
|
|
645
|
+
maxDescriptionCharacters: 2000,
|
|
646
|
+
maxRawStatusCharacters: 100,
|
|
647
|
+
maxLinksPerNode: 8
|
|
648
|
+
};
|
|
649
|
+
var STATIC_HTML_POLICY = {
|
|
650
|
+
maxSourceBytes: 256 * KIB,
|
|
651
|
+
maxPreparedBytes: 16 * MIB,
|
|
652
|
+
maxElements: 5000
|
|
653
|
+
};
|
|
654
|
+
var STATIC_PRESENTATION_POLICY = {
|
|
655
|
+
maxDocumentBytes: STATIC_HTML_POLICY.maxSourceBytes,
|
|
656
|
+
maxElements: STATIC_HTML_POLICY.maxElements,
|
|
657
|
+
maxFramesPerWindow: 4,
|
|
658
|
+
renderTimeoutMs: 15000,
|
|
659
|
+
maxSizeChangesPerWindow: 16,
|
|
660
|
+
sizeChangeWindowMs: 5000,
|
|
661
|
+
maxRefusedMessages: 100,
|
|
662
|
+
maxSearchTextCharacters: 64 * KIB,
|
|
663
|
+
searchTextChunkCharacters: 2 * KIB
|
|
664
|
+
};
|
|
665
|
+
var INTERACTIVE_HTML_POLICY = {
|
|
666
|
+
maxAuthoredBytes: 512 * KIB,
|
|
667
|
+
maxAssets: 32,
|
|
668
|
+
maxAssetBytesTotal: 10 * MIB,
|
|
669
|
+
maxDependencies: 4,
|
|
670
|
+
maxPreparedBytes: 16 * MIB,
|
|
671
|
+
maxRuntimeElements: 1e4,
|
|
672
|
+
maxProbeSteps: 20,
|
|
673
|
+
maxProbeStepMs: 2000,
|
|
674
|
+
defaultWaitVisibleMs: 1000,
|
|
675
|
+
maxProbeTextCharacters: 1024,
|
|
676
|
+
probeTargetPattern: /^[A-Za-z][A-Za-z0-9_-]{0,63}$/
|
|
677
|
+
};
|
|
678
|
+
var PREVIEW_CAPTURE_POLICY = {
|
|
679
|
+
maxPngBytes: 8 * MIB,
|
|
680
|
+
maxPixels: 12000000,
|
|
681
|
+
maxDimension: 4096,
|
|
682
|
+
minDimension: 240,
|
|
683
|
+
maxCapturesPerReceipt: 3,
|
|
684
|
+
defaultViewport: { width: 960, height: 640, deviceScaleFactor: 1 }
|
|
685
|
+
};
|
|
686
|
+
var PREVIEW_ADMISSION_POLICY = {
|
|
687
|
+
runningPerEnvironment: 1,
|
|
688
|
+
runningGlobal: 2,
|
|
689
|
+
queuedPerEnvironment: 8,
|
|
690
|
+
queuedGlobal: 16,
|
|
691
|
+
nonterminalPerConversation: 2,
|
|
692
|
+
queuedMetadataBytesGlobal: 8 * MIB,
|
|
693
|
+
queueWaitMs: 15000,
|
|
694
|
+
workerWallMs: 30000,
|
|
695
|
+
readinessMs: 5000,
|
|
696
|
+
operationDeadlineMs: 45000,
|
|
697
|
+
cleanupGraceMs: 2000,
|
|
698
|
+
workerMemoryBytes: 1024 * MIB,
|
|
699
|
+
workerCpus: 2,
|
|
700
|
+
workerPids: 128
|
|
701
|
+
};
|
|
702
|
+
var FRONTEND_RENDER_POLICY = {
|
|
703
|
+
highlightConcurrency: 2,
|
|
704
|
+
diagramConcurrency: 1,
|
|
705
|
+
maxQueuedJobs: 32,
|
|
706
|
+
maxQueuedSourceBytes: 2 * MIB,
|
|
707
|
+
maxSettledCacheEntries: 128,
|
|
708
|
+
maxSettledCacheBytes: 16 * MIB,
|
|
709
|
+
maxInactiveViewStateEntries: 500,
|
|
710
|
+
maxActiveViewStateEntries: 200,
|
|
711
|
+
maxPinnedViewStateEntries: 50,
|
|
712
|
+
liveExecutableHostsPerWindow: 1,
|
|
713
|
+
imageDecodeMaxPixels: 40000000,
|
|
714
|
+
pdfPreviewMaxPages: 100,
|
|
715
|
+
pdfPreviewMaxBytes: 20 * MIB
|
|
716
|
+
};
|
|
717
|
+
var PDF_POLICY = {
|
|
718
|
+
maxPages: 100,
|
|
719
|
+
maxBytes: 20 * MIB,
|
|
720
|
+
thumbnailMaxDimension: 1024,
|
|
721
|
+
thumbnailMaxPngBytes: 4 * MIB,
|
|
722
|
+
imageDecodeMaxPixels: 40000000,
|
|
723
|
+
printMarginMm: 10,
|
|
724
|
+
previewCacheEntries: 32,
|
|
725
|
+
previewCacheBytes: 16 * MIB
|
|
726
|
+
};
|
|
727
|
+
var DIAGNOSTIC_POLICY = {
|
|
728
|
+
maxPersistedEntries: 50,
|
|
729
|
+
maxEntryBytes: 2 * KIB,
|
|
730
|
+
maxPersistedBytes: 32 * KIB,
|
|
731
|
+
maxToolFieldErrors: 20,
|
|
732
|
+
maxToolDiagnosticBytes: 8 * KIB
|
|
733
|
+
};
|
|
734
|
+
var ARTIFACT_TOOL_POLICY = {
|
|
735
|
+
maxResultBytes: 16 * KIB,
|
|
736
|
+
maxSourceSliceBytes: 8 * KIB,
|
|
737
|
+
maxTitleCharacters: 120,
|
|
738
|
+
maxSummaryCharacters: 400,
|
|
739
|
+
maxRequestKeyCharacters: 128,
|
|
740
|
+
maxRepairRevisions: 2,
|
|
741
|
+
maxTransientRetries: 2,
|
|
742
|
+
maxUnpublishedArtifactsPerConversation: 100,
|
|
743
|
+
maxRevisionsPerArtifact: 100,
|
|
744
|
+
assetStoreBytesPerEnvironment: 1024 * MIB,
|
|
745
|
+
scopeCapabilityTtlMs: 24 * 60 * 60 * 1000
|
|
746
|
+
};
|
|
747
|
+
var ARTIFACT_RETENTION_POLICY = {
|
|
748
|
+
cleanupIntervalMs: 60 * 60 * 1000,
|
|
749
|
+
abandonedStagingMs: 60 * 60 * 1000,
|
|
750
|
+
unpublishedDraftMs: 7 * 24 * 60 * 60 * 1000,
|
|
751
|
+
unreferencedPreviewAssetMs: 24 * 60 * 60 * 1000
|
|
752
|
+
};
|
|
753
|
+
var FRAME_CHANNEL_POLICY = {
|
|
754
|
+
maxMessageBytes: 8 * KIB,
|
|
755
|
+
messagesPerSecond: 20,
|
|
756
|
+
burst: 40,
|
|
757
|
+
sizeUpdatesPerSecond: 4,
|
|
758
|
+
minInlineHeight: 120,
|
|
759
|
+
maxInlineHeight: 1600,
|
|
760
|
+
maxLinkCharacters: 2048,
|
|
761
|
+
maxLinkLabelCharacters: 200
|
|
762
|
+
};
|
|
763
|
+
|
|
764
|
+
// ../protocol/src/artifact-frame-channel.ts
|
|
765
|
+
var ARTIFACT_FRAME_CHANNEL = "orkestrator-artifact";
|
|
766
|
+
var UNSAFE_LINK_CHARACTERS = new RegExp("[\\u0000-\\u001f\\u007f-\\u009f\\u200e\\u200f\\u202a-\\u202e\\u2066-\\u2069]");
|
|
767
|
+
|
|
768
|
+
// ../../apps/backend/src/core/transcript-artifacts/dependency-manifest.ts
|
|
769
|
+
import { createHash } from "crypto";
|
|
770
|
+
import { existsSync } from "fs";
|
|
771
|
+
import { mkdir, readFile, realpath, writeFile } from "fs/promises";
|
|
772
|
+
import path from "path";
|
|
773
|
+
import { fileURLToPath } from "url";
|
|
774
|
+
var ARTIFACT_DEPENDENCY_MANIFEST = Object.freeze([
|
|
775
|
+
{
|
|
776
|
+
id: "d3@7.9.0",
|
|
777
|
+
packageName: "d3",
|
|
778
|
+
version: "7.9.0",
|
|
779
|
+
packageFile: "dist/d3.min.js",
|
|
780
|
+
distName: "d3.min.js",
|
|
781
|
+
sha256: "f2094bbf6141b359722c4fe454eb6c4b0f0e42cc10cc7af921fc158fceb86539",
|
|
782
|
+
license: "ISC",
|
|
783
|
+
notice: "d3 7.9.0 https://d3js.org Copyright 2010-2023 Mike Bostock (ISC License)",
|
|
784
|
+
licenseFiles: ["LICENSE"],
|
|
785
|
+
global: "d3",
|
|
786
|
+
moduleSpecifiers: ["d3"],
|
|
787
|
+
moduleShim: `module.exports = globalThis.d3;
|
|
788
|
+
`
|
|
789
|
+
},
|
|
790
|
+
{
|
|
791
|
+
id: "chart.js@4.5.1",
|
|
792
|
+
packageName: "chart.js",
|
|
793
|
+
version: "4.5.1",
|
|
794
|
+
packageFile: "dist/chart.umd.min.js",
|
|
795
|
+
distName: "chart.umd.min.js",
|
|
796
|
+
sha256: "48444a82d4edcb5bec0f1965faacdde18d9c17db3063d042abada2f705c9f54a",
|
|
797
|
+
license: "MIT",
|
|
798
|
+
notice: "Chart.js 4.5.1 https://www.chartjs.org (c) 2025 Chart.js Contributors (MIT License); embeds @kurkle/color v0.3.2 (c) 2023 Jukka Kurkela (MIT License)",
|
|
799
|
+
licenseFiles: ["LICENSE.md", "../@kurkle/color/LICENSE.md"],
|
|
800
|
+
global: "Chart",
|
|
801
|
+
moduleSpecifiers: ["chart.js", "chart.js/auto"],
|
|
802
|
+
moduleShim: [
|
|
803
|
+
"var Chart = globalThis.Chart;",
|
|
804
|
+
"module.exports = Object.assign(Object.create(null), Chart, {",
|
|
805
|
+
" __esModule: true,",
|
|
806
|
+
" default: Chart,",
|
|
807
|
+
" Chart: Chart,",
|
|
808
|
+
" registerables: [],",
|
|
809
|
+
"});",
|
|
810
|
+
""
|
|
811
|
+
].join(`
|
|
812
|
+
`)
|
|
813
|
+
}
|
|
814
|
+
]);
|
|
815
|
+
var RENDERER_BUNDLES = Object.freeze({
|
|
816
|
+
mermaid: {
|
|
817
|
+
id: "mermaid@12.2.0",
|
|
818
|
+
packageName: "mermaid",
|
|
819
|
+
version: "12.2.0",
|
|
820
|
+
packageFile: "dist/mermaid.min.js",
|
|
821
|
+
distName: "mermaid.min.js",
|
|
822
|
+
sha256: "a8a6a6f805b074a8261a2825c86f99c8054acb3b35f50bb7e24a4f9f2c3c3b9f",
|
|
823
|
+
license: "MIT",
|
|
824
|
+
notice: "mermaid 12.2.0 https://mermaid.js.org (MIT License)",
|
|
825
|
+
licenseFiles: ["LICENSE"]
|
|
826
|
+
},
|
|
827
|
+
dompurify: {
|
|
828
|
+
id: "dompurify@3.4.17",
|
|
829
|
+
packageName: "dompurify",
|
|
830
|
+
version: "3.4.17",
|
|
831
|
+
packageFile: "dist/purify.min.js",
|
|
832
|
+
distName: "purify.min.js",
|
|
833
|
+
sha256: "cd37898f9782adf54820c413191b5691803f0f137c799d6edcfd38523b4c2c31",
|
|
834
|
+
license: "(MPL-2.0 OR Apache-2.0)",
|
|
835
|
+
notice: "DOMPurify 3.4.17 https://github.com/cure53/DOMPurify (MPL-2.0 OR Apache-2.0)",
|
|
836
|
+
licenseFiles: ["LICENSE", "LICENSE-MPL"]
|
|
837
|
+
},
|
|
838
|
+
pdfjs: {
|
|
839
|
+
id: "pdfjs-dist@6.4.299",
|
|
840
|
+
packageName: "pdfjs-dist",
|
|
841
|
+
version: "6.4.299",
|
|
842
|
+
packageFile: "build/pdf.min.mjs",
|
|
843
|
+
distName: "pdf.min.mjs",
|
|
844
|
+
sha256: "57456c8e0c81e46be31174b499ef77f2b9f5ee46d04412ba627320a36755d4c2",
|
|
845
|
+
license: "Apache-2.0",
|
|
846
|
+
notice: "PDF.js (pdfjs-dist) 6.4.299 https://mozilla.github.io/pdf.js/ Copyright 2024 Mozilla Foundation (Apache License 2.0)",
|
|
847
|
+
licenseFiles: ["LICENSE"]
|
|
848
|
+
},
|
|
849
|
+
pdfjsWorker: {
|
|
850
|
+
id: "pdfjs-dist-worker@6.4.299",
|
|
851
|
+
packageName: "pdfjs-dist",
|
|
852
|
+
version: "6.4.299",
|
|
853
|
+
packageFile: "build/pdf.worker.min.mjs",
|
|
854
|
+
distName: "pdf.worker.min.mjs",
|
|
855
|
+
sha256: "9536359f1b8367850d485731ca1d5e45c159a7b7a0912325e539937aa21ceb18",
|
|
856
|
+
license: "Apache-2.0",
|
|
857
|
+
notice: "PDF.js worker (pdfjs-dist) 6.4.299 https://mozilla.github.io/pdf.js/ Copyright 2024 Mozilla Foundation (Apache License 2.0)",
|
|
858
|
+
licenseFiles: ["LICENSE"]
|
|
859
|
+
}
|
|
860
|
+
});
|
|
861
|
+
var ALL_PINNED_BUNDLES = Object.freeze([
|
|
862
|
+
...ARTIFACT_DEPENDENCY_MANIFEST,
|
|
863
|
+
RENDERER_BUNDLES.mermaid,
|
|
864
|
+
RENDERER_BUNDLES.dompurify,
|
|
865
|
+
RENDERER_BUNDLES.pdfjs,
|
|
866
|
+
RENDERER_BUNDLES.pdfjsWorker
|
|
867
|
+
]);
|
|
868
|
+
|
|
869
|
+
class PinnedBundleError extends Error {
|
|
870
|
+
reason;
|
|
871
|
+
bundleId;
|
|
872
|
+
constructor(reason, bundleId) {
|
|
873
|
+
super(reason === "missing" ? `Pinned bundle ${bundleId} is not installed with this backend` : `Pinned bundle ${bundleId} does not match its recorded SHA-256`);
|
|
874
|
+
this.reason = reason;
|
|
875
|
+
this.bundleId = bundleId;
|
|
876
|
+
this.name = "PinnedBundleError";
|
|
877
|
+
}
|
|
878
|
+
}
|
|
879
|
+
function sha256Hex(bytes) {
|
|
880
|
+
return createHash("sha256").update(bytes).digest("hex");
|
|
881
|
+
}
|
|
882
|
+
function moduleDirectory() {
|
|
883
|
+
return path.dirname(fileURLToPath(import.meta.url));
|
|
884
|
+
}
|
|
885
|
+
function pinnedBundleCandidates(bundle, baseDir = moduleDirectory()) {
|
|
886
|
+
return [
|
|
887
|
+
path.join(baseDir, "artifact-runtime", bundle.distName),
|
|
888
|
+
path.join(baseDir, bundle.distName),
|
|
889
|
+
path.resolve(baseDir, "../../../node_modules", bundle.packageName, bundle.packageFile)
|
|
890
|
+
];
|
|
891
|
+
}
|
|
892
|
+
var cache = new Map;
|
|
893
|
+
function loadPinnedBundle(bundle, baseDir) {
|
|
894
|
+
const key = `${bundle.id}\x00${baseDir ?? ""}`;
|
|
895
|
+
let pending = cache.get(key);
|
|
896
|
+
if (!pending) {
|
|
897
|
+
pending = (async () => {
|
|
898
|
+
const file = pinnedBundleCandidates(bundle, baseDir).find((candidate) => existsSync(candidate));
|
|
899
|
+
if (!file)
|
|
900
|
+
throw new PinnedBundleError("missing", bundle.id);
|
|
901
|
+
const bytes = new Uint8Array(await readFile(file));
|
|
902
|
+
if (sha256Hex(bytes) !== bundle.sha256)
|
|
903
|
+
throw new PinnedBundleError("integrity", bundle.id);
|
|
904
|
+
return bytes;
|
|
905
|
+
})();
|
|
906
|
+
pending.catch(() => cache.delete(key));
|
|
907
|
+
cache.set(key, pending);
|
|
908
|
+
}
|
|
909
|
+
return pending;
|
|
910
|
+
}
|
|
911
|
+
|
|
912
|
+
// ../../apps/backend/src/core/transcript-artifacts/preview-probes.ts
|
|
913
|
+
var OBSERVED_TEXT_LIMIT = 200;
|
|
914
|
+
|
|
915
|
+
class ProbeFailure extends Error {
|
|
916
|
+
code;
|
|
917
|
+
observed;
|
|
918
|
+
constructor(code, message, observed) {
|
|
919
|
+
super(message);
|
|
920
|
+
this.code = code;
|
|
921
|
+
this.observed = observed;
|
|
922
|
+
}
|
|
923
|
+
}
|
|
924
|
+
function describe(probe) {
|
|
925
|
+
return `${probe.op} on "${probe.target}"`;
|
|
926
|
+
}
|
|
927
|
+
function boundedText(value) {
|
|
928
|
+
return value.length > OBSERVED_TEXT_LIMIT ? `${value.slice(0, OBSERVED_TEXT_LIMIT)}\u2026` : value;
|
|
929
|
+
}
|
|
930
|
+
function parseVisibleNumber(text) {
|
|
931
|
+
const match = /[-+]?(?:\d{1,3}(?:,\d{3})+|\d+)(?:\.\d+)?(?:[eE][-+]?\d+)?|[-+]?\.\d+/.exec(text);
|
|
932
|
+
if (!match)
|
|
933
|
+
return null;
|
|
934
|
+
const value = Number(match[0].replace(/,/g, ""));
|
|
935
|
+
return Number.isFinite(value) ? value : null;
|
|
936
|
+
}
|
|
937
|
+
async function readValue(page, target, timeoutMs) {
|
|
938
|
+
const locator = page.locator(`[data-artifact-test="${target}"]`);
|
|
939
|
+
return locator.evaluate((element) => {
|
|
940
|
+
if (element instanceof HTMLInputElement || element instanceof HTMLTextAreaElement || element instanceof HTMLSelectElement) {
|
|
941
|
+
return element.value;
|
|
942
|
+
}
|
|
943
|
+
if (element instanceof HTMLOutputElement)
|
|
944
|
+
return element.value || (element.textContent ?? "");
|
|
945
|
+
return element instanceof HTMLElement ? element.innerText : element.textContent ?? "";
|
|
946
|
+
}, undefined, { timeout: timeoutMs });
|
|
947
|
+
}
|
|
948
|
+
async function uniqueTarget(page, target) {
|
|
949
|
+
if (!INTERACTIVE_HTML_POLICY.probeTargetPattern.test(target)) {
|
|
950
|
+
throw new ProbeFailure("invalid_target", `Target "${target.slice(0, 64)}" is not a valid data-artifact-test id`);
|
|
951
|
+
}
|
|
952
|
+
const locator = page.locator(`[data-artifact-test="${target}"]`);
|
|
953
|
+
const count = await locator.count();
|
|
954
|
+
if (count === 0)
|
|
955
|
+
throw new ProbeFailure("target_not_found", `No element has data-artifact-test="${target}"`);
|
|
956
|
+
if (count > 1)
|
|
957
|
+
throw new ProbeFailure("target_not_unique", `${count} elements have data-artifact-test="${target}"`);
|
|
958
|
+
return locator;
|
|
959
|
+
}
|
|
960
|
+
async function runStep(page, probe, stepMs) {
|
|
961
|
+
switch (probe.op) {
|
|
962
|
+
case "wait-visible": {
|
|
963
|
+
const timeout = Math.min(stepMs, Math.max(0, probe.timeoutMs ?? INTERACTIVE_HTML_POLICY.defaultWaitVisibleMs));
|
|
964
|
+
const locator = page.locator(`[data-artifact-test="${probe.target}"]`);
|
|
965
|
+
if (!INTERACTIVE_HTML_POLICY.probeTargetPattern.test(probe.target)) {
|
|
966
|
+
throw new ProbeFailure("invalid_target", "Invalid target");
|
|
967
|
+
}
|
|
968
|
+
try {
|
|
969
|
+
await locator.first().waitFor({ state: "visible", timeout });
|
|
970
|
+
} catch {
|
|
971
|
+
throw new ProbeFailure("not_visible", `data-artifact-test="${probe.target}" was not visible within ${timeout} ms`);
|
|
972
|
+
}
|
|
973
|
+
const count = await locator.count();
|
|
974
|
+
if (count > 1)
|
|
975
|
+
throw new ProbeFailure("target_not_unique", `${count} elements have data-artifact-test="${probe.target}"`);
|
|
976
|
+
return;
|
|
977
|
+
}
|
|
978
|
+
case "click": {
|
|
979
|
+
const locator = await uniqueTarget(page, probe.target);
|
|
980
|
+
await locator.click({ timeout: stepMs, noWaitAfter: true });
|
|
981
|
+
return;
|
|
982
|
+
}
|
|
983
|
+
case "fill": {
|
|
984
|
+
const locator = await uniqueTarget(page, probe.target);
|
|
985
|
+
const text = probe.text.slice(0, INTERACTIVE_HTML_POLICY.maxProbeTextCharacters);
|
|
986
|
+
await locator.fill(text, { timeout: stepMs, noWaitAfter: true });
|
|
987
|
+
return boundedText(await readValue(page, probe.target, stepMs));
|
|
988
|
+
}
|
|
989
|
+
case "set-number": {
|
|
990
|
+
if (!Number.isFinite(probe.value))
|
|
991
|
+
throw new ProbeFailure("invalid_value", "set-number requires a finite value");
|
|
992
|
+
const locator = await uniqueTarget(page, probe.target);
|
|
993
|
+
const type = await locator.evaluate((element) => element instanceof HTMLInputElement ? element.type : element.tagName.toLowerCase(), undefined, { timeout: stepMs });
|
|
994
|
+
if (type !== "number" && type !== "range") {
|
|
995
|
+
throw new ProbeFailure("not_numeric_control", `data-artifact-test="${probe.target}" is a ${type}, not a number or range input`);
|
|
996
|
+
}
|
|
997
|
+
await locator.fill(String(probe.value), { timeout: stepMs, noWaitAfter: true });
|
|
998
|
+
const observed = await readValue(page, probe.target, stepMs);
|
|
999
|
+
const value = Number(observed);
|
|
1000
|
+
if (!Number.isFinite(value) || value !== probe.value) {
|
|
1001
|
+
throw new ProbeFailure("value_rejected", `The control kept ${boundedText(observed)} instead of ${probe.value}`, boundedText(observed));
|
|
1002
|
+
}
|
|
1003
|
+
return value;
|
|
1004
|
+
}
|
|
1005
|
+
case "expect-text": {
|
|
1006
|
+
await uniqueTarget(page, probe.target);
|
|
1007
|
+
const observed = (await readValue(page, probe.target, stepMs)).trim();
|
|
1008
|
+
if (observed !== probe.equals.trim()) {
|
|
1009
|
+
throw new ProbeFailure("expectation_failed", `Expected text ${JSON.stringify(boundedText(probe.equals))}, observed ${JSON.stringify(boundedText(observed))}`, boundedText(observed));
|
|
1010
|
+
}
|
|
1011
|
+
return boundedText(observed);
|
|
1012
|
+
}
|
|
1013
|
+
case "expect-number": {
|
|
1014
|
+
await uniqueTarget(page, probe.target);
|
|
1015
|
+
const text = await readValue(page, probe.target, stepMs);
|
|
1016
|
+
const observed = parseVisibleNumber(text);
|
|
1017
|
+
if (observed === null) {
|
|
1018
|
+
throw new ProbeFailure("not_a_number", `Expected a number, observed ${JSON.stringify(boundedText(text.trim()))}`, boundedText(text.trim()));
|
|
1019
|
+
}
|
|
1020
|
+
const tolerance = probe.tolerance ?? 0;
|
|
1021
|
+
if (!(Math.abs(observed - probe.equals) <= tolerance)) {
|
|
1022
|
+
throw new ProbeFailure("expectation_failed", `Expected ${probe.equals}${tolerance ? ` \xB1 ${tolerance}` : ""}, observed ${observed}`, observed);
|
|
1023
|
+
}
|
|
1024
|
+
return observed;
|
|
1025
|
+
}
|
|
1026
|
+
}
|
|
1027
|
+
}
|
|
1028
|
+
async function runProbes(page, probes, options) {
|
|
1029
|
+
const results = [];
|
|
1030
|
+
const diagnostics = [];
|
|
1031
|
+
const steps = probes.slice(0, INTERACTIVE_HTML_POLICY.maxProbeSteps);
|
|
1032
|
+
let failed = false;
|
|
1033
|
+
for (const [index, probe] of steps.entries()) {
|
|
1034
|
+
const base = { index, op: probe.op, target: String(probe.target).slice(0, 64) };
|
|
1035
|
+
if (failed) {
|
|
1036
|
+
results.push({ ...base, status: "skipped" });
|
|
1037
|
+
continue;
|
|
1038
|
+
}
|
|
1039
|
+
const stepMs = Math.min(options.stepMs, INTERACTIVE_HTML_POLICY.maxProbeStepMs);
|
|
1040
|
+
try {
|
|
1041
|
+
const observed = await withDeadline(runStep(page, probe, stepMs), stepMs + 250);
|
|
1042
|
+
await options.onStep?.();
|
|
1043
|
+
results.push({ ...base, status: "passed", ...observed === undefined ? {} : { observed } });
|
|
1044
|
+
} catch (error) {
|
|
1045
|
+
failed = true;
|
|
1046
|
+
const failure = error instanceof ProbeFailure ? error : new ProbeFailure(error instanceof StepTimeout ? "step_timeout" : "action_failed", error instanceof StepTimeout ? `The step did not finish within ${stepMs} ms` : `The ${probe.op} action could not be performed (${firstLine(error)})`);
|
|
1047
|
+
results.push({
|
|
1048
|
+
...base,
|
|
1049
|
+
status: "failed",
|
|
1050
|
+
errorCode: failure.code,
|
|
1051
|
+
...failure.observed === undefined ? {} : { observed: failure.observed }
|
|
1052
|
+
});
|
|
1053
|
+
diagnostics.push({
|
|
1054
|
+
severity: "error",
|
|
1055
|
+
code: `probe_${failure.code}`,
|
|
1056
|
+
message: `Probe ${index} (${describe(probe)}): ${failure.message}`.slice(0, 1000),
|
|
1057
|
+
location: `probes[${index}]`
|
|
1058
|
+
});
|
|
1059
|
+
}
|
|
1060
|
+
}
|
|
1061
|
+
return { results, diagnostics, passed: !failed };
|
|
1062
|
+
}
|
|
1063
|
+
|
|
1064
|
+
class StepTimeout extends Error {
|
|
1065
|
+
}
|
|
1066
|
+
function firstLine(error) {
|
|
1067
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
1068
|
+
return (message.split(`
|
|
1069
|
+
`)[0] ?? "").replace(/\s+/g, " ").slice(0, 200);
|
|
1070
|
+
}
|
|
1071
|
+
function withDeadline(promise, ms) {
|
|
1072
|
+
return new Promise((resolve, reject) => {
|
|
1073
|
+
const timer = setTimeout(() => reject(new StepTimeout), ms);
|
|
1074
|
+
promise.then((value) => {
|
|
1075
|
+
clearTimeout(timer);
|
|
1076
|
+
resolve(value);
|
|
1077
|
+
}, (error) => {
|
|
1078
|
+
clearTimeout(timer);
|
|
1079
|
+
reject(error);
|
|
1080
|
+
});
|
|
1081
|
+
});
|
|
1082
|
+
}
|
|
1083
|
+
|
|
1084
|
+
// ../../apps/backend/src/core/transcript-artifacts/preview-worker-browser.ts
|
|
1085
|
+
var PREVIEW_DOCUMENT_URL = "https://artifact-preview.invalid/document";
|
|
1086
|
+
var PREVIEW_ORIGIN = "https://artifact-preview.invalid";
|
|
1087
|
+
|
|
1088
|
+
class JobFailure extends Error {
|
|
1089
|
+
code;
|
|
1090
|
+
resource;
|
|
1091
|
+
constructor(code, message, resource) {
|
|
1092
|
+
super(message);
|
|
1093
|
+
this.code = code;
|
|
1094
|
+
this.resource = resource;
|
|
1095
|
+
}
|
|
1096
|
+
}
|
|
1097
|
+
function deadline(promise, ms, onTimeout) {
|
|
1098
|
+
return new Promise((resolve, reject) => {
|
|
1099
|
+
const timer = setTimeout(() => reject(onTimeout()), Math.max(1, ms));
|
|
1100
|
+
promise.then((value) => {
|
|
1101
|
+
clearTimeout(timer);
|
|
1102
|
+
resolve(value);
|
|
1103
|
+
}, (error) => {
|
|
1104
|
+
clearTimeout(timer);
|
|
1105
|
+
reject(error);
|
|
1106
|
+
});
|
|
1107
|
+
});
|
|
1108
|
+
}
|
|
1109
|
+
function increment(record, key) {
|
|
1110
|
+
record[key] = (record[key] ?? 0) + 1;
|
|
1111
|
+
}
|
|
1112
|
+
function checkProfile(profile) {
|
|
1113
|
+
const { width, height } = profile.viewport;
|
|
1114
|
+
const p = PREVIEW_CAPTURE_POLICY;
|
|
1115
|
+
if (!Number.isInteger(width) || !Number.isInteger(height) || width < p.minDimension || height < p.minDimension || width > p.maxDimension || height > p.maxDimension || width * height > p.maxPixels) {
|
|
1116
|
+
throw new JobFailure("invalid_input", "Preview viewport is outside the capture limits", "viewport");
|
|
1117
|
+
}
|
|
1118
|
+
}
|
|
1119
|
+
async function capture(page, profile, label, timeoutMs) {
|
|
1120
|
+
const png = await page.screenshot({
|
|
1121
|
+
type: "png",
|
|
1122
|
+
animations: "disabled",
|
|
1123
|
+
timeout: Math.max(1, timeoutMs),
|
|
1124
|
+
fullPage: false
|
|
1125
|
+
});
|
|
1126
|
+
if (png.byteLength > PREVIEW_CAPTURE_POLICY.maxPngBytes) {
|
|
1127
|
+
throw new JobFailure("package_size_exceeded", `Capture is ${png.byteLength} bytes; the limit is ${PREVIEW_CAPTURE_POLICY.maxPngBytes}`, "capture-bytes");
|
|
1128
|
+
}
|
|
1129
|
+
return {
|
|
1130
|
+
pngBase64: png.toString("base64"),
|
|
1131
|
+
width: profile.viewport.width,
|
|
1132
|
+
height: profile.viewport.height,
|
|
1133
|
+
label
|
|
1134
|
+
};
|
|
1135
|
+
}
|
|
1136
|
+
async function settleAssets(maxMs) {
|
|
1137
|
+
const images = Array.from(document.images).map((image) => image.complete ? undefined : image.decode().catch(() => {
|
|
1138
|
+
return;
|
|
1139
|
+
}));
|
|
1140
|
+
await Promise.race([
|
|
1141
|
+
Promise.all([document.fonts?.ready, ...images]).then(() => new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve)))),
|
|
1142
|
+
new Promise((resolve) => setTimeout(resolve, maxMs))
|
|
1143
|
+
]);
|
|
1144
|
+
}
|
|
1145
|
+
async function isolatedContext(browser, profile, blocked, allow) {
|
|
1146
|
+
const context = await browser.newContext({
|
|
1147
|
+
viewport: { width: profile.viewport.width, height: profile.viewport.height },
|
|
1148
|
+
deviceScaleFactor: 1,
|
|
1149
|
+
colorScheme: profile.theme,
|
|
1150
|
+
reducedMotion: "reduce",
|
|
1151
|
+
forcedColors: "none",
|
|
1152
|
+
serviceWorkers: "block",
|
|
1153
|
+
acceptDownloads: false,
|
|
1154
|
+
permissions: [],
|
|
1155
|
+
locale: "en-US",
|
|
1156
|
+
timezoneId: "UTC",
|
|
1157
|
+
javaScriptEnabled: true,
|
|
1158
|
+
bypassCSP: false,
|
|
1159
|
+
ignoreHTTPSErrors: false
|
|
1160
|
+
});
|
|
1161
|
+
await context.route("**/*", async (route) => {
|
|
1162
|
+
if (await allow(route))
|
|
1163
|
+
return;
|
|
1164
|
+
const request = route.request();
|
|
1165
|
+
if (request.isNavigationRequest()) {
|
|
1166
|
+
increment(blocked, "navigation");
|
|
1167
|
+
await route.fulfill({ status: 204, body: "" }).catch(() => {
|
|
1168
|
+
return;
|
|
1169
|
+
});
|
|
1170
|
+
return;
|
|
1171
|
+
}
|
|
1172
|
+
increment(blocked, request.resourceType());
|
|
1173
|
+
await route.abort("blockedbyclient").catch(() => {
|
|
1174
|
+
return;
|
|
1175
|
+
});
|
|
1176
|
+
});
|
|
1177
|
+
await context.routeWebSocket(/.*/, (socket) => {
|
|
1178
|
+
increment(blocked, "websocket");
|
|
1179
|
+
socket.close({ code: 1008, reason: "blocked" }).catch(() => {
|
|
1180
|
+
return;
|
|
1181
|
+
});
|
|
1182
|
+
});
|
|
1183
|
+
context.on("page", (page) => {
|
|
1184
|
+
page.on("dialog", (dialog) => {
|
|
1185
|
+
increment(blocked, "dialog");
|
|
1186
|
+
dialog.dismiss().catch(() => {
|
|
1187
|
+
return;
|
|
1188
|
+
});
|
|
1189
|
+
});
|
|
1190
|
+
});
|
|
1191
|
+
return context;
|
|
1192
|
+
}
|
|
1193
|
+
function readinessListener(expectedNonce) {
|
|
1194
|
+
const channel = "orkestrator-artifact";
|
|
1195
|
+
window.addEventListener("message", (event) => {
|
|
1196
|
+
const data = event.data;
|
|
1197
|
+
if (!data || data.channel !== channel || data.type !== "ready")
|
|
1198
|
+
return;
|
|
1199
|
+
if (expectedNonce !== null && data.nonce !== expectedNonce)
|
|
1200
|
+
return;
|
|
1201
|
+
window.__orkPreviewReady = true;
|
|
1202
|
+
});
|
|
1203
|
+
}
|
|
1204
|
+
|
|
1205
|
+
// ../../apps/backend/src/core/transcript-artifacts/preview-worker-print.ts
|
|
1206
|
+
import { createHash as createHash2, randomUUID } from "crypto";
|
|
1207
|
+
|
|
1208
|
+
// ../../apps/backend/src/core/transcript-artifacts/print-profile.ts
|
|
1209
|
+
var PRINT_PAPER_FORMAT = {
|
|
1210
|
+
a4: "A4",
|
|
1211
|
+
letter: "Letter"
|
|
1212
|
+
};
|
|
1213
|
+
function countPrintedPdfPages(pdf) {
|
|
1214
|
+
const text = Buffer.from(pdf.buffer, pdf.byteOffset, pdf.byteLength).toString("latin1");
|
|
1215
|
+
return (text.match(/\/Type\s*\/Page(?![A-Za-z])/g) ?? []).length;
|
|
1216
|
+
}
|
|
1217
|
+
function looksLikePdf(bytes) {
|
|
1218
|
+
const head = Buffer.from(bytes.buffer, bytes.byteOffset, Math.min(bytes.byteLength, 1024));
|
|
1219
|
+
return head.includes("%PDF-", 0, "latin1");
|
|
1220
|
+
}
|
|
1221
|
+
|
|
1222
|
+
// ../../apps/backend/src/core/transcript-artifacts/preview-worker-print.ts
|
|
1223
|
+
function neutralizePrint() {
|
|
1224
|
+
const counter = window;
|
|
1225
|
+
counter.__orkPrintCalls = 0;
|
|
1226
|
+
const print = () => {
|
|
1227
|
+
counter.__orkPrintCalls = (counter.__orkPrintCalls ?? 0) + 1;
|
|
1228
|
+
};
|
|
1229
|
+
try {
|
|
1230
|
+
Object.defineProperty(window, "print", {
|
|
1231
|
+
value: print,
|
|
1232
|
+
writable: false,
|
|
1233
|
+
configurable: false
|
|
1234
|
+
});
|
|
1235
|
+
} catch {
|
|
1236
|
+
window.print = print;
|
|
1237
|
+
}
|
|
1238
|
+
}
|
|
1239
|
+
var stopped = () => new JobFailure("render_timeout", "The page stopped responding", "runtime");
|
|
1240
|
+
async function printStatic(context, job, result, remaining) {
|
|
1241
|
+
const page = await context.newPage();
|
|
1242
|
+
page.setDefaultTimeout(remaining());
|
|
1243
|
+
await page.setContent(designBootstrap(randomUUID()), { waitUntil: "load" });
|
|
1244
|
+
const outcome = await page.evaluate(async (html) => {
|
|
1245
|
+
const run = window.orkDesign;
|
|
1246
|
+
try {
|
|
1247
|
+
run({ op: "validate", html });
|
|
1248
|
+
run({ op: "render", html });
|
|
1249
|
+
return { ok: true };
|
|
1250
|
+
} catch (error) {
|
|
1251
|
+
return {
|
|
1252
|
+
ok: false,
|
|
1253
|
+
message: error instanceof Error ? error.message : "Runtime failed"
|
|
1254
|
+
};
|
|
1255
|
+
}
|
|
1256
|
+
}, job.document.html);
|
|
1257
|
+
if (!outcome.ok)
|
|
1258
|
+
throw new JobFailure("validation_failed", outcome.message.slice(0, 300));
|
|
1259
|
+
await page.evaluate(settleAssets, Math.min(5000, Math.floor(remaining() / 3)));
|
|
1260
|
+
const effective = await page.evaluate(() => window.orkDesign({
|
|
1261
|
+
op: "serialize"
|
|
1262
|
+
}));
|
|
1263
|
+
result.effectiveHtmlSha256 = createHash2("sha256").update(effective, "utf8").digest("hex");
|
|
1264
|
+
return page;
|
|
1265
|
+
}
|
|
1266
|
+
async function printInteractive(browser, job, pkg, result, emit) {
|
|
1267
|
+
const prepared = job.document;
|
|
1268
|
+
let served = 0;
|
|
1269
|
+
let mainPage;
|
|
1270
|
+
const context = await isolatedContext(browser, job.profile, result.blockedRequests, async (route) => {
|
|
1271
|
+
const request = route.request();
|
|
1272
|
+
if (served === 0 && request.url() === PREVIEW_DOCUMENT_URL && request.method() === "GET" && request.isNavigationRequest() && mainPage !== undefined && request.frame() === mainPage.mainFrame()) {
|
|
1273
|
+
served++;
|
|
1274
|
+
await route.fulfill({
|
|
1275
|
+
status: 200,
|
|
1276
|
+
headers: {
|
|
1277
|
+
"content-type": "text/html; charset=utf-8",
|
|
1278
|
+
"content-security-policy": prepared.contentSecurityPolicy,
|
|
1279
|
+
"x-content-type-options": "nosniff",
|
|
1280
|
+
"cache-control": "no-store",
|
|
1281
|
+
"referrer-policy": "no-referrer"
|
|
1282
|
+
},
|
|
1283
|
+
body: prepared.preparedDocument
|
|
1284
|
+
});
|
|
1285
|
+
return true;
|
|
1286
|
+
}
|
|
1287
|
+
if (request.url() === `${PREVIEW_ORIGIN}/favicon.ico`) {
|
|
1288
|
+
await route.abort("blockedbyclient").catch(() => {
|
|
1289
|
+
return;
|
|
1290
|
+
});
|
|
1291
|
+
return true;
|
|
1292
|
+
}
|
|
1293
|
+
return false;
|
|
1294
|
+
});
|
|
1295
|
+
await context.addInitScript(neutralizePrint);
|
|
1296
|
+
await context.addInitScript(readinessListener, prepared.readinessNonce ?? null);
|
|
1297
|
+
const page = await context.newPage();
|
|
1298
|
+
mainPage = page;
|
|
1299
|
+
page.on("popup", (popup) => {
|
|
1300
|
+
increment(result.blockedRequests, "popup");
|
|
1301
|
+
popup.close().catch(() => {
|
|
1302
|
+
return;
|
|
1303
|
+
});
|
|
1304
|
+
});
|
|
1305
|
+
emit({ t: "phase", phase: "navigating" });
|
|
1306
|
+
const readinessDeadline = Date.now() + pkg.limits.readinessMs;
|
|
1307
|
+
try {
|
|
1308
|
+
await page.goto(PREVIEW_DOCUMENT_URL, {
|
|
1309
|
+
waitUntil: "load",
|
|
1310
|
+
timeout: pkg.limits.readinessMs
|
|
1311
|
+
});
|
|
1312
|
+
await page.waitForFunction(() => window.__orkPreviewReady === true, undefined, { timeout: Math.max(1, readinessDeadline - Date.now()), polling: 50 });
|
|
1313
|
+
} catch {
|
|
1314
|
+
throw new JobFailure("render_timeout", "The interactive document did not become ready in time", "readiness");
|
|
1315
|
+
}
|
|
1316
|
+
emit({ t: "phase", phase: "ready" });
|
|
1317
|
+
if (prepared.identity) {
|
|
1318
|
+
await deadline(page.evaluate((message) => window.postMessage(message, "*"), {
|
|
1319
|
+
channel: ARTIFACT_FRAME_CHANNEL,
|
|
1320
|
+
v: 1,
|
|
1321
|
+
type: "theme",
|
|
1322
|
+
artifactId: prepared.identity.artifactId,
|
|
1323
|
+
revision: prepared.identity.revision,
|
|
1324
|
+
generation: "print",
|
|
1325
|
+
appearance: job.profile.theme,
|
|
1326
|
+
reducedMotion: true,
|
|
1327
|
+
viewport: {
|
|
1328
|
+
width: job.profile.viewport.width,
|
|
1329
|
+
height: job.profile.viewport.height
|
|
1330
|
+
},
|
|
1331
|
+
tokens: {}
|
|
1332
|
+
}), 2000, stopped);
|
|
1333
|
+
}
|
|
1334
|
+
await deadline(page.evaluate(settleAssets, 1000), 3000, stopped);
|
|
1335
|
+
const elements = await deadline(page.evaluate(() => document.getElementsByTagName("*").length), 2000, stopped);
|
|
1336
|
+
if (elements > INTERACTIVE_HTML_POLICY.maxRuntimeElements)
|
|
1337
|
+
throw new JobFailure("validation_failed", "The document exceeded its element budget", "dom-elements");
|
|
1338
|
+
return { context, page };
|
|
1339
|
+
}
|
|
1340
|
+
async function runHtmlPrint(browser, job, pkg, result, remaining, emit) {
|
|
1341
|
+
checkProfile(job.profile);
|
|
1342
|
+
const { print } = job;
|
|
1343
|
+
if (print.paper !== "a4" && print.paper !== "letter")
|
|
1344
|
+
throw new JobFailure("invalid_input", "Unknown print paper", "print-profile");
|
|
1345
|
+
const maxPages = Math.min(print.maxPages, PDF_POLICY.maxPages);
|
|
1346
|
+
const maxBytes = Math.min(print.maxBytes, PDF_POLICY.maxBytes);
|
|
1347
|
+
let page;
|
|
1348
|
+
if (job.document.type === "static") {
|
|
1349
|
+
const context = await isolatedContext(browser, job.profile, result.blockedRequests, async () => false);
|
|
1350
|
+
await context.addInitScript(neutralizePrint);
|
|
1351
|
+
page = await printStatic(context, job, result, remaining);
|
|
1352
|
+
} else {
|
|
1353
|
+
page = (await printInteractive(browser, job, pkg, result, emit)).page;
|
|
1354
|
+
}
|
|
1355
|
+
emit({ t: "phase", phase: "capturing" });
|
|
1356
|
+
const margin = `${print.marginMm}mm`;
|
|
1357
|
+
const pdf = await deadline(page.pdf({
|
|
1358
|
+
format: PRINT_PAPER_FORMAT[print.paper],
|
|
1359
|
+
printBackground: true,
|
|
1360
|
+
scale: 1,
|
|
1361
|
+
margin: { top: margin, right: margin, bottom: margin, left: margin },
|
|
1362
|
+
pageRanges: `1-${maxPages + 1}`,
|
|
1363
|
+
displayHeaderFooter: false,
|
|
1364
|
+
preferCSSPageSize: false,
|
|
1365
|
+
outline: false,
|
|
1366
|
+
tagged: false
|
|
1367
|
+
}), Math.max(1, remaining()), () => new JobFailure("render_timeout", "Printing exceeded its time budget", "print"));
|
|
1368
|
+
if (pdf.byteLength > maxBytes)
|
|
1369
|
+
throw new JobFailure("package_size_exceeded", `The PDF is ${pdf.byteLength} bytes; the limit is ${maxBytes}`, "pdf-bytes");
|
|
1370
|
+
if (!looksLikePdf(pdf))
|
|
1371
|
+
throw new JobFailure("renderer_unavailable", "The browser did not produce a PDF", "print");
|
|
1372
|
+
const pages = countPrintedPdfPages(pdf);
|
|
1373
|
+
if (pages < 1)
|
|
1374
|
+
throw new JobFailure("renderer_unavailable", "The printed PDF has no pages", "print");
|
|
1375
|
+
if (pages > maxPages)
|
|
1376
|
+
throw new JobFailure("package_size_exceeded", `The document prints to more than ${maxPages} pages`, "pdf-pages");
|
|
1377
|
+
result.pdfBase64 = pdf.toString("base64");
|
|
1378
|
+
result.pageCount = pages;
|
|
1379
|
+
result.ok = true;
|
|
1380
|
+
}
|
|
1381
|
+
async function renderFirstPage(input) {
|
|
1382
|
+
const moduleUrl = (source) => URL.createObjectURL(new Blob([source], { type: "text/javascript" }));
|
|
1383
|
+
globalThis.pdfjsWorker = await import(moduleUrl(input.worker));
|
|
1384
|
+
const pdfjs = await import(moduleUrl(input.library));
|
|
1385
|
+
const binary = atob(input.pdfBase64);
|
|
1386
|
+
const data = new Uint8Array(binary.length);
|
|
1387
|
+
for (let index = 0;index < binary.length; index++)
|
|
1388
|
+
data[index] = binary.charCodeAt(index);
|
|
1389
|
+
let pdfDocument;
|
|
1390
|
+
const task = pdfjs.getDocument({
|
|
1391
|
+
data,
|
|
1392
|
+
isEvalSupported: false,
|
|
1393
|
+
enableXfa: false,
|
|
1394
|
+
disableFontFace: true,
|
|
1395
|
+
useSystemFonts: false,
|
|
1396
|
+
useWasm: false,
|
|
1397
|
+
useWorkerFetch: false,
|
|
1398
|
+
disableRange: true,
|
|
1399
|
+
disableStream: true,
|
|
1400
|
+
disableAutoFetch: true,
|
|
1401
|
+
isOffscreenCanvasSupported: false,
|
|
1402
|
+
isImageDecoderSupported: false,
|
|
1403
|
+
enableHWA: false,
|
|
1404
|
+
stopAtErrors: false,
|
|
1405
|
+
maxImageSize: input.maxImagePixels,
|
|
1406
|
+
verbosity: 0
|
|
1407
|
+
});
|
|
1408
|
+
try {
|
|
1409
|
+
pdfDocument = await task.promise;
|
|
1410
|
+
} catch (error) {
|
|
1411
|
+
await Promise.resolve(task.destroy()).catch(() => {
|
|
1412
|
+
return;
|
|
1413
|
+
});
|
|
1414
|
+
const name = error.name ?? "";
|
|
1415
|
+
return {
|
|
1416
|
+
ok: false,
|
|
1417
|
+
reason: name === "PasswordException" ? "encrypted" : "invalid-pdf"
|
|
1418
|
+
};
|
|
1419
|
+
}
|
|
1420
|
+
try {
|
|
1421
|
+
const pages = pdfDocument.numPages;
|
|
1422
|
+
if (pages > input.maxPages)
|
|
1423
|
+
return { ok: false, reason: "page-limit", pages };
|
|
1424
|
+
const page = await pdfDocument.getPage(1);
|
|
1425
|
+
const natural = page.getViewport({ scale: 1 });
|
|
1426
|
+
const scale = Math.min(2, input.maxDimension / Math.max(1, natural.width), input.maxDimension / Math.max(1, natural.height));
|
|
1427
|
+
const viewport = page.getViewport({ scale });
|
|
1428
|
+
const canvas = window.document.createElement("canvas");
|
|
1429
|
+
canvas.width = Math.max(1, Math.min(input.maxDimension, Math.floor(viewport.width)));
|
|
1430
|
+
canvas.height = Math.max(1, Math.min(input.maxDimension, Math.floor(viewport.height)));
|
|
1431
|
+
const canvasContext = canvas.getContext("2d");
|
|
1432
|
+
if (!canvasContext)
|
|
1433
|
+
return { ok: false, reason: "invalid-pdf", pages };
|
|
1434
|
+
canvasContext.fillStyle = "#ffffff";
|
|
1435
|
+
canvasContext.fillRect(0, 0, canvas.width, canvas.height);
|
|
1436
|
+
await page.render({ canvas, canvasContext, viewport, annotationMode: 1 }).promise;
|
|
1437
|
+
const dataUrl = canvas.toDataURL("image/png");
|
|
1438
|
+
return {
|
|
1439
|
+
ok: true,
|
|
1440
|
+
pages,
|
|
1441
|
+
width: canvas.width,
|
|
1442
|
+
height: canvas.height,
|
|
1443
|
+
pngBase64: dataUrl.slice(dataUrl.indexOf(",") + 1)
|
|
1444
|
+
};
|
|
1445
|
+
} finally {
|
|
1446
|
+
await Promise.resolve(task.destroy()).catch(() => {
|
|
1447
|
+
return;
|
|
1448
|
+
});
|
|
1449
|
+
}
|
|
1450
|
+
}
|
|
1451
|
+
async function runPdfThumbnail(browser, job, result, remaining, emit) {
|
|
1452
|
+
const decodedBytes = Math.floor(job.pdfBase64.length * 3 / 4);
|
|
1453
|
+
if (decodedBytes > PDF_POLICY.maxBytes + 3)
|
|
1454
|
+
throw new JobFailure("package_size_exceeded", "The PDF exceeds its preview limit", "pdf-bytes");
|
|
1455
|
+
const maxDimension = Math.max(64, Math.min(job.maxDimension, PDF_POLICY.thumbnailMaxDimension, PREVIEW_CAPTURE_POLICY.maxDimension));
|
|
1456
|
+
const [library, worker] = await Promise.all([
|
|
1457
|
+
loadPinnedBundle(RENDERER_BUNDLES.pdfjs),
|
|
1458
|
+
loadPinnedBundle(RENDERER_BUNDLES.pdfjsWorker)
|
|
1459
|
+
]).catch(() => {
|
|
1460
|
+
throw new JobFailure("renderer_unavailable", "The pinned PDF renderer bundle is unavailable", "pdf-bundle");
|
|
1461
|
+
});
|
|
1462
|
+
const context = await isolatedContext(browser, { theme: "light", viewport: { width: maxDimension, height: maxDimension } }, result.blockedRequests, async () => false);
|
|
1463
|
+
const page = await context.newPage();
|
|
1464
|
+
page.setDefaultTimeout(Math.max(1, remaining()));
|
|
1465
|
+
await page.setContent('<!doctype html><html><head><meta charset="utf-8"></head><body></body></html>');
|
|
1466
|
+
emit({ t: "phase", phase: "capturing" });
|
|
1467
|
+
const decoder = new TextDecoder;
|
|
1468
|
+
const output = await deadline(page.evaluate(renderFirstPage, {
|
|
1469
|
+
library: decoder.decode(library),
|
|
1470
|
+
worker: decoder.decode(worker),
|
|
1471
|
+
pdfBase64: job.pdfBase64,
|
|
1472
|
+
maxDimension,
|
|
1473
|
+
maxPages: Math.min(job.maxPages, PDF_POLICY.maxPages),
|
|
1474
|
+
maxImagePixels: PDF_POLICY.imageDecodeMaxPixels
|
|
1475
|
+
}), Math.max(1, remaining()), () => new JobFailure("render_timeout", "Rendering the PDF exceeded its time budget", "pdf"));
|
|
1476
|
+
if (!output.ok) {
|
|
1477
|
+
result.pdfRefusal = output.reason;
|
|
1478
|
+
if ("pages" in output && typeof output.pages === "number")
|
|
1479
|
+
result.pageCount = output.pages;
|
|
1480
|
+
result.ok = true;
|
|
1481
|
+
return;
|
|
1482
|
+
}
|
|
1483
|
+
const png = Buffer.from(output.pngBase64, "base64");
|
|
1484
|
+
if (png.byteLength > PDF_POLICY.thumbnailMaxPngBytes)
|
|
1485
|
+
throw new JobFailure("package_size_exceeded", "The page preview is too large", "thumbnail");
|
|
1486
|
+
result.pageCount = output.pages;
|
|
1487
|
+
result.captures.push({
|
|
1488
|
+
pngBase64: output.pngBase64,
|
|
1489
|
+
width: output.width,
|
|
1490
|
+
height: output.height,
|
|
1491
|
+
label: "initial"
|
|
1492
|
+
});
|
|
1493
|
+
result.ok = true;
|
|
1494
|
+
}
|
|
1495
|
+
|
|
1496
|
+
// ../../apps/backend/src/core/transcript-artifacts/preview-jobs.ts
|
|
1497
|
+
var NETWORK_DENIAL_ARGS = [
|
|
1498
|
+
"--host-resolver-rules=MAP * ~NOTFOUND",
|
|
1499
|
+
"--force-webrtc-ip-handling-policy=disable_non_proxied_udp",
|
|
1500
|
+
"--webrtc-ip-handling-policy=disable_non_proxied_udp",
|
|
1501
|
+
"--disable-background-networking",
|
|
1502
|
+
"--disable-component-update",
|
|
1503
|
+
"--disable-domain-reliability",
|
|
1504
|
+
"--disable-sync",
|
|
1505
|
+
"--no-pings",
|
|
1506
|
+
"--dns-prefetch-disable",
|
|
1507
|
+
"--disable-features=NetworkPrediction,InterestFeedContentSuggestions,OptimizationHints,MediaRouter,DialMediaRouteProvider",
|
|
1508
|
+
"--metrics-recording-only",
|
|
1509
|
+
"--no-first-run",
|
|
1510
|
+
"--disable-default-apps",
|
|
1511
|
+
"--mute-audio"
|
|
1512
|
+
];
|
|
1513
|
+
var DEAD_PROXY = { server: "http://127.0.0.1:9", bypass: "<-loopback>" };
|
|
1514
|
+
function emptyResult(kind, browserBuild) {
|
|
1515
|
+
return { ok: false, kind, browserBuild, diagnostics: [], blockedRequests: {}, captures: [] };
|
|
1516
|
+
}
|
|
1517
|
+
async function elementCount(page, timeoutMs) {
|
|
1518
|
+
return deadline(page.evaluate(() => document.getElementsByTagName("*").length), timeoutMs, () => new JobFailure("render_timeout", "The page stopped responding"));
|
|
1519
|
+
}
|
|
1520
|
+
async function launch(pkg, emit) {
|
|
1521
|
+
let server;
|
|
1522
|
+
try {
|
|
1523
|
+
server = await chromium.launchServer({
|
|
1524
|
+
headless: true,
|
|
1525
|
+
chromiumSandbox: true,
|
|
1526
|
+
...pkg.executablePath ? { executablePath: pkg.executablePath } : {},
|
|
1527
|
+
args: NETWORK_DENIAL_ARGS,
|
|
1528
|
+
proxy: DEAD_PROXY,
|
|
1529
|
+
timeout: Math.max(1000, Math.min(15000, pkg.limits.workerWallMs)),
|
|
1530
|
+
handleSIGINT: false,
|
|
1531
|
+
handleSIGTERM: true,
|
|
1532
|
+
handleSIGHUP: false,
|
|
1533
|
+
host: "127.0.0.1"
|
|
1534
|
+
});
|
|
1535
|
+
} catch (error) {
|
|
1536
|
+
const socketPathTooLong = /Socket path too long/.test(String(error?.message));
|
|
1537
|
+
throw new JobFailure("renderer_unavailable", socketPathTooLong ? "Chromium could not start in the preview worker: its temporary directory path is too long for Chromium's socket" : "Chromium could not start with its sandbox enabled in the preview worker", "browser-launch");
|
|
1538
|
+
}
|
|
1539
|
+
const pid = server.process()?.pid ?? null;
|
|
1540
|
+
const browser = await chromium.connect(server.wsEndpoint(), { timeout: 1e4 });
|
|
1541
|
+
const build = `chromium/${browser.version()}`;
|
|
1542
|
+
emit({ t: "launched", browserPid: pid, browserBuild: build });
|
|
1543
|
+
return { server, browser, build };
|
|
1544
|
+
}
|
|
1545
|
+
async function closeQuietly(launched) {
|
|
1546
|
+
if (!launched)
|
|
1547
|
+
return;
|
|
1548
|
+
await deadline(launched.browser.close(), 1000, () => new Error("close")).catch(() => {
|
|
1549
|
+
return;
|
|
1550
|
+
});
|
|
1551
|
+
await deadline(launched.server.kill(), 1000, () => new Error("kill")).catch(() => {
|
|
1552
|
+
return;
|
|
1553
|
+
});
|
|
1554
|
+
}
|
|
1555
|
+
async function runWorkerJob(pkg, emit) {
|
|
1556
|
+
const { job } = pkg;
|
|
1557
|
+
const started = Date.now();
|
|
1558
|
+
const remaining = () => Math.max(1, pkg.limits.workerWallMs - (Date.now() - started) - 500);
|
|
1559
|
+
let launched;
|
|
1560
|
+
const result = emptyResult(job.kind, "unknown");
|
|
1561
|
+
try {
|
|
1562
|
+
launched = await launch(pkg, emit);
|
|
1563
|
+
result.browserBuild = launched.build;
|
|
1564
|
+
switch (job.kind) {
|
|
1565
|
+
case "probe":
|
|
1566
|
+
result.ok = true;
|
|
1567
|
+
return result;
|
|
1568
|
+
case "html-static":
|
|
1569
|
+
await runStatic(launched.browser, job, result, remaining);
|
|
1570
|
+
return result;
|
|
1571
|
+
case "html-interactive":
|
|
1572
|
+
await runInteractive(launched.browser, job, pkg, result, remaining, emit);
|
|
1573
|
+
return result;
|
|
1574
|
+
case "mermaid":
|
|
1575
|
+
await runMermaid(launched.browser, job, pkg, result, emit);
|
|
1576
|
+
return result;
|
|
1577
|
+
case "html-print":
|
|
1578
|
+
await runHtmlPrint(launched.browser, job, pkg, result, remaining, emit);
|
|
1579
|
+
return result;
|
|
1580
|
+
case "pdf-thumbnail":
|
|
1581
|
+
await runPdfThumbnail(launched.browser, job, result, remaining, emit);
|
|
1582
|
+
return result;
|
|
1583
|
+
}
|
|
1584
|
+
} catch (error) {
|
|
1585
|
+
result.ok = false;
|
|
1586
|
+
if (error instanceof JobFailure) {
|
|
1587
|
+
result.failure = {
|
|
1588
|
+
code: error.code,
|
|
1589
|
+
message: error.message,
|
|
1590
|
+
...error.resource ? { resource: error.resource } : {}
|
|
1591
|
+
};
|
|
1592
|
+
} else if (error instanceof Error && error.name === "TimeoutError") {
|
|
1593
|
+
result.failure = {
|
|
1594
|
+
code: "render_timeout",
|
|
1595
|
+
message: "The page stopped responding within its time budget",
|
|
1596
|
+
resource: "runtime"
|
|
1597
|
+
};
|
|
1598
|
+
} else {
|
|
1599
|
+
result.failure = {
|
|
1600
|
+
code: "renderer_unavailable",
|
|
1601
|
+
message: "The preview worker failed unexpectedly"
|
|
1602
|
+
};
|
|
1603
|
+
}
|
|
1604
|
+
return result;
|
|
1605
|
+
} finally {
|
|
1606
|
+
await closeQuietly(launched);
|
|
1607
|
+
}
|
|
1608
|
+
}
|
|
1609
|
+
async function runStatic(browser, job, result, remaining) {
|
|
1610
|
+
checkProfile(job.profile);
|
|
1611
|
+
const context = await isolatedContext(browser, job.profile, result.blockedRequests, async () => false);
|
|
1612
|
+
const page = await context.newPage();
|
|
1613
|
+
page.setDefaultTimeout(remaining());
|
|
1614
|
+
await page.setContent(designBootstrap(randomUUID2()), { waitUntil: "load" });
|
|
1615
|
+
const outcome = await page.evaluate(async (html) => {
|
|
1616
|
+
const run = window.orkDesign;
|
|
1617
|
+
try {
|
|
1618
|
+
const report = run({ op: "validate", html });
|
|
1619
|
+
run({ op: "render", html });
|
|
1620
|
+
return { ok: true, report };
|
|
1621
|
+
} catch (error) {
|
|
1622
|
+
return {
|
|
1623
|
+
ok: false,
|
|
1624
|
+
message: error instanceof Error ? error.message : "Runtime failed"
|
|
1625
|
+
};
|
|
1626
|
+
}
|
|
1627
|
+
}, job.html);
|
|
1628
|
+
if (!outcome.ok) {
|
|
1629
|
+
result.diagnostics.push({
|
|
1630
|
+
severity: "error",
|
|
1631
|
+
code: "static_render_failed",
|
|
1632
|
+
message: outcome.message.slice(0, 300)
|
|
1633
|
+
});
|
|
1634
|
+
throw new JobFailure("validation_failed", outcome.message.slice(0, 300));
|
|
1635
|
+
}
|
|
1636
|
+
await page.evaluate(settleAssets, Math.min(5000, Math.floor(remaining() / 3)));
|
|
1637
|
+
result.captures.push(await capture(page, job.profile, "initial", remaining()));
|
|
1638
|
+
result.effectiveHtml = await page.evaluate(() => window.orkDesign({
|
|
1639
|
+
op: "serialize"
|
|
1640
|
+
}));
|
|
1641
|
+
result.sanitizer = outcome.report.removed;
|
|
1642
|
+
result.elementCount = outcome.report.elementCount;
|
|
1643
|
+
result.ok = true;
|
|
1644
|
+
}
|
|
1645
|
+
async function runInteractive(browser, job, pkg, result, remaining, emit) {
|
|
1646
|
+
const state = { crashed: false };
|
|
1647
|
+
try {
|
|
1648
|
+
await runInteractivePage(browser, job, pkg, result, remaining, emit, state);
|
|
1649
|
+
} catch (error) {
|
|
1650
|
+
if (!state.crashed)
|
|
1651
|
+
throw error;
|
|
1652
|
+
result.diagnostics.push({
|
|
1653
|
+
severity: "error",
|
|
1654
|
+
code: "renderer_crashed",
|
|
1655
|
+
message: "The page's renderer process crashed, usually because the document exhausted its memory limit"
|
|
1656
|
+
});
|
|
1657
|
+
throw new JobFailure("validation_failed", "The document crashed its renderer (memory or resource limit)", "renderer-crash");
|
|
1658
|
+
}
|
|
1659
|
+
}
|
|
1660
|
+
async function runInteractivePage(browser, job, pkg, result, remaining, emit, state) {
|
|
1661
|
+
checkProfile(job.profile);
|
|
1662
|
+
let served = 0;
|
|
1663
|
+
let mainPage;
|
|
1664
|
+
const context = await isolatedContext(browser, job.profile, result.blockedRequests, async (route) => {
|
|
1665
|
+
const request = route.request();
|
|
1666
|
+
if (served === 0 && request.url() === PREVIEW_DOCUMENT_URL && request.method() === "GET" && request.isNavigationRequest() && mainPage !== undefined && request.frame() === mainPage.mainFrame()) {
|
|
1667
|
+
served++;
|
|
1668
|
+
await route.fulfill({
|
|
1669
|
+
status: 200,
|
|
1670
|
+
headers: {
|
|
1671
|
+
"content-type": "text/html; charset=utf-8",
|
|
1672
|
+
"content-security-policy": job.contentSecurityPolicy,
|
|
1673
|
+
"x-content-type-options": "nosniff",
|
|
1674
|
+
"cache-control": "no-store",
|
|
1675
|
+
"referrer-policy": "no-referrer"
|
|
1676
|
+
},
|
|
1677
|
+
body: job.preparedDocument
|
|
1678
|
+
});
|
|
1679
|
+
return true;
|
|
1680
|
+
}
|
|
1681
|
+
if (request.url() === `${PREVIEW_ORIGIN}/favicon.ico`) {
|
|
1682
|
+
await route.abort("blockedbyclient").catch(() => {
|
|
1683
|
+
return;
|
|
1684
|
+
});
|
|
1685
|
+
return true;
|
|
1686
|
+
}
|
|
1687
|
+
return false;
|
|
1688
|
+
});
|
|
1689
|
+
let runtimeErrors = 0;
|
|
1690
|
+
let consoleErrors = 0;
|
|
1691
|
+
let unexpectedNavigations = 0;
|
|
1692
|
+
await context.addInitScript(readinessListener, job.readinessNonce ?? null);
|
|
1693
|
+
const page = await context.newPage();
|
|
1694
|
+
mainPage = page;
|
|
1695
|
+
page.on("crash", () => {
|
|
1696
|
+
state.crashed = true;
|
|
1697
|
+
});
|
|
1698
|
+
page.on("pageerror", () => runtimeErrors++);
|
|
1699
|
+
page.on("console", (message) => {
|
|
1700
|
+
if (message.type() !== "error")
|
|
1701
|
+
return;
|
|
1702
|
+
if (/content security policy/i.test(message.text()))
|
|
1703
|
+
increment(result.blockedRequests, "csp");
|
|
1704
|
+
else
|
|
1705
|
+
consoleErrors++;
|
|
1706
|
+
});
|
|
1707
|
+
page.on("popup", (popup) => {
|
|
1708
|
+
increment(result.blockedRequests, "popup");
|
|
1709
|
+
popup.close().catch(() => {
|
|
1710
|
+
return;
|
|
1711
|
+
});
|
|
1712
|
+
});
|
|
1713
|
+
let loaded = false;
|
|
1714
|
+
page.on("framenavigated", (frame) => {
|
|
1715
|
+
if (frame === page.mainFrame() && loaded)
|
|
1716
|
+
unexpectedNavigations++;
|
|
1717
|
+
});
|
|
1718
|
+
emit({ t: "phase", phase: "navigating" });
|
|
1719
|
+
const readinessDeadline = Date.now() + pkg.limits.readinessMs;
|
|
1720
|
+
try {
|
|
1721
|
+
await page.goto(PREVIEW_DOCUMENT_URL, { waitUntil: "load", timeout: pkg.limits.readinessMs });
|
|
1722
|
+
loaded = true;
|
|
1723
|
+
await page.waitForFunction(() => window.__orkPreviewReady === true, undefined, { timeout: Math.max(1, readinessDeadline - Date.now()), polling: 50 });
|
|
1724
|
+
} catch (error) {
|
|
1725
|
+
if (state.crashed)
|
|
1726
|
+
throw error;
|
|
1727
|
+
result.diagnostics.push({
|
|
1728
|
+
severity: "error",
|
|
1729
|
+
code: "readiness_timeout",
|
|
1730
|
+
message: `The document did not load and report readiness within ${pkg.limits.readinessMs} ms`
|
|
1731
|
+
});
|
|
1732
|
+
throw new JobFailure("render_timeout", "The interactive document did not become ready in time", "readiness");
|
|
1733
|
+
}
|
|
1734
|
+
emit({ t: "phase", phase: "ready" });
|
|
1735
|
+
if (job.identity) {
|
|
1736
|
+
await deadline(page.evaluate((message) => window.postMessage(message, "*"), {
|
|
1737
|
+
channel: ARTIFACT_FRAME_CHANNEL,
|
|
1738
|
+
v: 1,
|
|
1739
|
+
type: "theme",
|
|
1740
|
+
artifactId: job.identity.artifactId,
|
|
1741
|
+
revision: job.identity.revision,
|
|
1742
|
+
generation: "preview",
|
|
1743
|
+
appearance: job.profile.theme,
|
|
1744
|
+
reducedMotion: true,
|
|
1745
|
+
viewport: { width: job.profile.viewport.width, height: job.profile.viewport.height },
|
|
1746
|
+
tokens: {}
|
|
1747
|
+
}), 2000, () => new JobFailure("render_timeout", "The page stopped responding", "runtime"));
|
|
1748
|
+
}
|
|
1749
|
+
await deadline(page.evaluate(settleAssets, 1000), 3000, () => new JobFailure("render_timeout", "The page stopped responding", "runtime"));
|
|
1750
|
+
const checkDom = async (when) => {
|
|
1751
|
+
const count = await elementCount(page, Math.min(2000, remaining()));
|
|
1752
|
+
result.elementCount = Math.max(result.elementCount ?? 0, count);
|
|
1753
|
+
if (count > INTERACTIVE_HTML_POLICY.maxRuntimeElements) {
|
|
1754
|
+
result.diagnostics.push({
|
|
1755
|
+
severity: "error",
|
|
1756
|
+
code: "dom_limit",
|
|
1757
|
+
message: `The document grew to ${count} elements ${when}; at most ${INTERACTIVE_HTML_POLICY.maxRuntimeElements} are allowed`
|
|
1758
|
+
});
|
|
1759
|
+
throw new JobFailure("validation_failed", "The document exceeded its element budget", "dom-elements");
|
|
1760
|
+
}
|
|
1761
|
+
};
|
|
1762
|
+
await checkDom("after loading");
|
|
1763
|
+
emit({ t: "phase", phase: "capturing" });
|
|
1764
|
+
result.captures.push(await capture(page, job.profile, "initial", remaining()));
|
|
1765
|
+
let probesPassed = true;
|
|
1766
|
+
if (job.probes.length) {
|
|
1767
|
+
const outcome = await runProbes(page, job.probes, {
|
|
1768
|
+
stepMs: Math.min(pkg.limits.probeStepMs, INTERACTIVE_HTML_POLICY.maxProbeStepMs),
|
|
1769
|
+
onStep: () => checkDom("during probes")
|
|
1770
|
+
});
|
|
1771
|
+
result.probeResults = outcome.results;
|
|
1772
|
+
result.diagnostics.push(...outcome.diagnostics);
|
|
1773
|
+
probesPassed = outcome.passed;
|
|
1774
|
+
await deadline(page.evaluate(settleAssets, 500), 2000, () => new JobFailure("render_timeout", "The page stopped responding")).catch(() => {
|
|
1775
|
+
return;
|
|
1776
|
+
});
|
|
1777
|
+
if (!probesPassed) {
|
|
1778
|
+
await checkDom("after probes");
|
|
1779
|
+
}
|
|
1780
|
+
result.captures.push(await capture(page, job.profile, probesPassed ? "final" : "diagnostic", probesPassed ? remaining() : Math.min(3000, remaining())));
|
|
1781
|
+
}
|
|
1782
|
+
await checkDom("after probes");
|
|
1783
|
+
result.runtimeErrors = runtimeErrors + consoleErrors;
|
|
1784
|
+
if (unexpectedNavigations > 0)
|
|
1785
|
+
increment(result.blockedRequests, "navigation");
|
|
1786
|
+
const prohibited = Object.values(result.blockedRequests).reduce((sum, value) => sum + value, 0);
|
|
1787
|
+
if (runtimeErrors > 0) {
|
|
1788
|
+
result.diagnostics.push({
|
|
1789
|
+
severity: "error",
|
|
1790
|
+
code: "runtime_error",
|
|
1791
|
+
message: `${runtimeErrors} uncaught JavaScript error${runtimeErrors === 1 ? "" : "s"} during the preview`
|
|
1792
|
+
});
|
|
1793
|
+
}
|
|
1794
|
+
if (prohibited > 0) {
|
|
1795
|
+
result.diagnostics.push({
|
|
1796
|
+
severity: "error",
|
|
1797
|
+
code: "prohibited_resource",
|
|
1798
|
+
message: `Blocked ${prohibited} prohibited resource, navigation or dialog attempt${prohibited === 1 ? "" : "s"} (${Object.entries(result.blockedRequests).map(([key, value]) => `${key}: ${value}`).join(", ")})`
|
|
1799
|
+
});
|
|
1800
|
+
}
|
|
1801
|
+
if (!probesPassed)
|
|
1802
|
+
throw new JobFailure("validation_failed", "A declared interaction probe failed", "probes");
|
|
1803
|
+
if (runtimeErrors > 0)
|
|
1804
|
+
throw new JobFailure("validation_failed", "The document raised uncaught JavaScript errors", "runtime");
|
|
1805
|
+
if (prohibited > 0)
|
|
1806
|
+
throw new JobFailure("policy_denied", "The document attempted prohibited network, navigation or dialog access", "network");
|
|
1807
|
+
result.ok = true;
|
|
1808
|
+
}
|
|
1809
|
+
async function renderMermaidInPage(input) {
|
|
1810
|
+
const globals = globalThis;
|
|
1811
|
+
const { mermaid, DOMPurify } = globals;
|
|
1812
|
+
const secure = [
|
|
1813
|
+
"secure",
|
|
1814
|
+
"securityLevel",
|
|
1815
|
+
"startOnLoad",
|
|
1816
|
+
"maxTextSize",
|
|
1817
|
+
"maxEdges",
|
|
1818
|
+
"htmlLabels",
|
|
1819
|
+
"flowchart",
|
|
1820
|
+
"theme",
|
|
1821
|
+
"themeCSS",
|
|
1822
|
+
"themeVariables",
|
|
1823
|
+
"fontFamily",
|
|
1824
|
+
"altFontFamily",
|
|
1825
|
+
"dompurifyConfig",
|
|
1826
|
+
"arrowMarkerAbsolute",
|
|
1827
|
+
"deterministicIds",
|
|
1828
|
+
"deterministicIDSeed",
|
|
1829
|
+
"suppressErrorRendering",
|
|
1830
|
+
"legacyMathML",
|
|
1831
|
+
"forceLegacyMathML",
|
|
1832
|
+
"elk",
|
|
1833
|
+
"layout",
|
|
1834
|
+
"look",
|
|
1835
|
+
"handDrawnSeed",
|
|
1836
|
+
"fontSize",
|
|
1837
|
+
"markdownAutoWrap",
|
|
1838
|
+
"wrap"
|
|
1839
|
+
];
|
|
1840
|
+
mermaid.initialize({
|
|
1841
|
+
startOnLoad: false,
|
|
1842
|
+
securityLevel: "strict",
|
|
1843
|
+
htmlLabels: false,
|
|
1844
|
+
flowchart: { htmlLabels: false },
|
|
1845
|
+
maxTextSize: input.maxTextSize,
|
|
1846
|
+
maxEdges: input.maxEdges,
|
|
1847
|
+
secure,
|
|
1848
|
+
theme: input.theme === "dark" ? "dark" : "default",
|
|
1849
|
+
deterministicIds: true,
|
|
1850
|
+
deterministicIDSeed: "orkestrator",
|
|
1851
|
+
suppressErrorRendering: true,
|
|
1852
|
+
arrowMarkerAbsolute: false,
|
|
1853
|
+
logLevel: 5
|
|
1854
|
+
});
|
|
1855
|
+
let parsedType;
|
|
1856
|
+
try {
|
|
1857
|
+
const parsed = await mermaid.parse(input.source);
|
|
1858
|
+
parsedType = parsed ? parsed.diagramType : undefined;
|
|
1859
|
+
} catch (error) {
|
|
1860
|
+
const err = error;
|
|
1861
|
+
const line = typeof err.hash?.line === "number" ? err.hash.line + 1 : err.hash?.loc?.first_line;
|
|
1862
|
+
const column = err.hash?.loc && err.hash.loc.first_line === line ? err.hash.loc.first_column : undefined;
|
|
1863
|
+
const message = String(err.message ?? "Syntax error").split(`
|
|
1864
|
+
`).filter(Boolean).slice(0, 4).join(" ").slice(0, 400);
|
|
1865
|
+
if (/edge limit exceeded|maximum text size/i.test(message))
|
|
1866
|
+
return { ok: false, kind: "limit", message };
|
|
1867
|
+
return { ok: false, kind: "syntax", message, line, column };
|
|
1868
|
+
}
|
|
1869
|
+
if (input.block) {
|
|
1870
|
+
for (;; ) {}
|
|
1871
|
+
}
|
|
1872
|
+
let rendered;
|
|
1873
|
+
try {
|
|
1874
|
+
rendered = await mermaid.render("ork-mermaid", input.source);
|
|
1875
|
+
} catch (error) {
|
|
1876
|
+
const message = String(error.message ?? "Render failed").slice(0, 400);
|
|
1877
|
+
return {
|
|
1878
|
+
ok: false,
|
|
1879
|
+
kind: /edge limit/i.test(message) ? "limit" : "render",
|
|
1880
|
+
message
|
|
1881
|
+
};
|
|
1882
|
+
}
|
|
1883
|
+
document.querySelectorAll("[id^='dork-mermaid'], #ork-mermaid").forEach((node) => node.remove());
|
|
1884
|
+
const countElements = (svg) => {
|
|
1885
|
+
const doc = new DOMParser().parseFromString(svg, "image/svg+xml");
|
|
1886
|
+
return doc.getElementsByTagName("*").length;
|
|
1887
|
+
};
|
|
1888
|
+
const rawBytes = new TextEncoder().encode(rendered.svg).length;
|
|
1889
|
+
const rawElements = countElements(rendered.svg);
|
|
1890
|
+
const preSanitize = { bytes: rawBytes, elements: rawElements };
|
|
1891
|
+
if (rawBytes > input.maxSvgBytes || rawElements > input.maxSvgElements) {
|
|
1892
|
+
return {
|
|
1893
|
+
ok: false,
|
|
1894
|
+
kind: "limit",
|
|
1895
|
+
message: `Generated SVG is ${rawBytes} bytes with ${rawElements} elements; limits are ${input.maxSvgBytes} bytes and ${input.maxSvgElements} elements`,
|
|
1896
|
+
preSanitize
|
|
1897
|
+
};
|
|
1898
|
+
}
|
|
1899
|
+
DOMPurify.addHook("uponSanitizeAttribute", (_node, data) => {
|
|
1900
|
+
const name = data.attrName.toLowerCase();
|
|
1901
|
+
const value = data.attrValue.trim();
|
|
1902
|
+
if (name === "href" || name === "xlink:href") {
|
|
1903
|
+
if (!value.startsWith("#"))
|
|
1904
|
+
data.keepAttr = false;
|
|
1905
|
+
return;
|
|
1906
|
+
}
|
|
1907
|
+
if (/url\s*\(/i.test(value) && !/^url\(\s*['"]?#[^)'"]*['"]?\s*\)$/i.test(value) && name !== "style")
|
|
1908
|
+
data.keepAttr = false;
|
|
1909
|
+
});
|
|
1910
|
+
const clean = DOMPurify.sanitize(rendered.svg, {
|
|
1911
|
+
USE_PROFILES: { svg: true, svgFilters: true },
|
|
1912
|
+
FORBID_TAGS: [
|
|
1913
|
+
"script",
|
|
1914
|
+
"foreignObject",
|
|
1915
|
+
"iframe",
|
|
1916
|
+
"image",
|
|
1917
|
+
"feImage",
|
|
1918
|
+
"use",
|
|
1919
|
+
"animate",
|
|
1920
|
+
"set",
|
|
1921
|
+
"animateMotion",
|
|
1922
|
+
"animateTransform",
|
|
1923
|
+
"a"
|
|
1924
|
+
],
|
|
1925
|
+
FORBID_ATTR: ["target", "ping", "src", "action", "formaction"],
|
|
1926
|
+
KEEP_CONTENT: true,
|
|
1927
|
+
ALLOW_DATA_ATTR: false
|
|
1928
|
+
});
|
|
1929
|
+
const removed = DOMPurify.removed.length;
|
|
1930
|
+
const finalBytes = new TextEncoder().encode(clean).length;
|
|
1931
|
+
const finalElements = countElements(clean);
|
|
1932
|
+
const doc = new DOMParser().parseFromString(clean, "image/svg+xml");
|
|
1933
|
+
const edges = doc.querySelectorAll(".flowchart-link, .edgePath, .relation, .transition, .messageLine0, .messageLine1, .relationshipLine").length;
|
|
1934
|
+
return {
|
|
1935
|
+
ok: true,
|
|
1936
|
+
svg: clean,
|
|
1937
|
+
diagramType: rendered.diagramType ?? parsedType ?? "unknown",
|
|
1938
|
+
preSanitize,
|
|
1939
|
+
finalBytes,
|
|
1940
|
+
finalElements,
|
|
1941
|
+
removed,
|
|
1942
|
+
edges
|
|
1943
|
+
};
|
|
1944
|
+
}
|
|
1945
|
+
async function runMermaid(browser, job, pkg, result, emit) {
|
|
1946
|
+
const sourceBytes = new TextEncoder().encode(job.source).length;
|
|
1947
|
+
if (sourceBytes > MERMAID_POLICY.maxSourceBytes) {
|
|
1948
|
+
throw new JobFailure("package_size_exceeded", `Diagram source is ${sourceBytes} bytes; the limit is ${MERMAID_POLICY.maxSourceBytes}`, "source-bytes");
|
|
1949
|
+
}
|
|
1950
|
+
const [mermaid, purify] = await Promise.all([
|
|
1951
|
+
loadPinnedBundle(RENDERER_BUNDLES.mermaid),
|
|
1952
|
+
loadPinnedBundle(RENDERER_BUNDLES.dompurify)
|
|
1953
|
+
]).catch(() => {
|
|
1954
|
+
throw new JobFailure("renderer_unavailable", "The pinned Mermaid renderer bundle is unavailable", "mermaid-bundle");
|
|
1955
|
+
});
|
|
1956
|
+
const context = await isolatedContext(browser, { theme: job.theme, viewport: { width: 1200, height: 800 } }, result.blockedRequests, async () => false);
|
|
1957
|
+
const page = await context.newPage();
|
|
1958
|
+
await page.setContent('<!doctype html><html><head><meta charset="utf-8"></head><body></body></html>');
|
|
1959
|
+
await page.addScriptTag({ content: new TextDecoder().decode(purify) });
|
|
1960
|
+
await page.addScriptTag({ content: new TextDecoder().decode(mermaid) });
|
|
1961
|
+
emit({ t: "phase", phase: "render-start" });
|
|
1962
|
+
const output = await deadline(page.evaluate(renderMermaidInPage, {
|
|
1963
|
+
source: job.source,
|
|
1964
|
+
theme: job.theme,
|
|
1965
|
+
maxTextSize: MERMAID_POLICY.maxSourceBytes,
|
|
1966
|
+
maxEdges: MERMAID_POLICY.maxEdges,
|
|
1967
|
+
maxSvgBytes: MERMAID_POLICY.maxSvgBytes,
|
|
1968
|
+
maxSvgElements: MERMAID_POLICY.maxSvgElements,
|
|
1969
|
+
block: pkg.testing?.blockMermaidRender === true
|
|
1970
|
+
}), pkg.limits.mermaidRenderMs + 2000, () => new JobFailure("render_timeout", `Diagram parse/layout exceeded ${pkg.limits.mermaidRenderMs} ms`, "mermaid-render"));
|
|
1971
|
+
emit({ t: "phase", phase: "render-done" });
|
|
1972
|
+
if (!output.ok) {
|
|
1973
|
+
if (output.kind === "syntax") {
|
|
1974
|
+
const location = output.line !== undefined ? `line ${output.line}${output.column !== undefined ? `:${output.column + 1}` : ""}` : undefined;
|
|
1975
|
+
const diagnostic = {
|
|
1976
|
+
severity: "error",
|
|
1977
|
+
code: "mermaid_syntax",
|
|
1978
|
+
message: output.message,
|
|
1979
|
+
...location ? { location } : {}
|
|
1980
|
+
};
|
|
1981
|
+
result.diagnostics.push(diagnostic);
|
|
1982
|
+
throw new JobFailure("validation_failed", `Mermaid syntax error${location ? ` at ${location}` : ""}: ${output.message}`.slice(0, 450));
|
|
1983
|
+
}
|
|
1984
|
+
result.diagnostics.push({
|
|
1985
|
+
severity: "error",
|
|
1986
|
+
code: output.kind === "limit" ? "mermaid_limit" : "mermaid_render",
|
|
1987
|
+
message: output.message
|
|
1988
|
+
});
|
|
1989
|
+
if ("preSanitize" in output && output.preSanitize)
|
|
1990
|
+
result.preSanitize = output.preSanitize;
|
|
1991
|
+
const resource = output.kind !== "limit" ? undefined : /edge limit/i.test(output.message) ? "edges" : /text size/i.test(output.message) ? "source-bytes" : "svg";
|
|
1992
|
+
throw new JobFailure(output.kind === "limit" ? "package_size_exceeded" : "validation_failed", output.message, resource);
|
|
1993
|
+
}
|
|
1994
|
+
if (output.removed > 0) {
|
|
1995
|
+
result.diagnostics.push({
|
|
1996
|
+
severity: "info",
|
|
1997
|
+
code: "mermaid_sanitized",
|
|
1998
|
+
message: `The SVG sanitizer removed ${output.removed} node(s) or attribute(s)`
|
|
1999
|
+
});
|
|
2000
|
+
}
|
|
2001
|
+
result.svg = output.svg;
|
|
2002
|
+
result.diagramType = output.diagramType;
|
|
2003
|
+
result.preSanitize = output.preSanitize;
|
|
2004
|
+
result.svgElements = output.finalElements;
|
|
2005
|
+
result.edges = output.edges;
|
|
2006
|
+
result.ok = true;
|
|
2007
|
+
}
|
|
2008
|
+
|
|
2009
|
+
// ../../apps/backend/src/core/transcript-artifacts/preview-worker-entry.ts
|
|
2010
|
+
var MAX_INPUT_BYTES = 40 * 1024 * 1024;
|
|
2011
|
+
function write(event) {
|
|
2012
|
+
return new Promise((resolve) => {
|
|
2013
|
+
process.stdout.write(`${JSON.stringify(event)}
|
|
2014
|
+
`, () => resolve());
|
|
2015
|
+
});
|
|
2016
|
+
}
|
|
2017
|
+
async function readInput() {
|
|
2018
|
+
const chunks = [];
|
|
2019
|
+
let total = 0;
|
|
2020
|
+
for await (const chunk of process.stdin) {
|
|
2021
|
+
total += chunk.byteLength;
|
|
2022
|
+
if (total > MAX_INPUT_BYTES)
|
|
2023
|
+
throw new Error("input too large");
|
|
2024
|
+
chunks.push(chunk);
|
|
2025
|
+
}
|
|
2026
|
+
return Buffer.concat(chunks).toString("utf8");
|
|
2027
|
+
}
|
|
2028
|
+
async function main() {
|
|
2029
|
+
const pkg = JSON.parse(await readInput());
|
|
2030
|
+
if (pkg?.v !== PREVIEW_WORKER_PROTOCOL || !pkg.job || !pkg.limits)
|
|
2031
|
+
throw new Error("bad package");
|
|
2032
|
+
const pending = [];
|
|
2033
|
+
const result = await runWorkerJob(pkg, (event) => {
|
|
2034
|
+
pending.push(write(event));
|
|
2035
|
+
});
|
|
2036
|
+
await Promise.all(pending);
|
|
2037
|
+
await write({ t: "result", result });
|
|
2038
|
+
}
|
|
2039
|
+
main().then(() => process.exit(0), () => {
|
|
2040
|
+
process.stderr.write(`[artifact-preview-worker] job failed
|
|
2041
|
+
`);
|
|
2042
|
+
process.exit(1);
|
|
2043
|
+
});
|