@engenty/wizards-runtime 0.9.1 → 0.9.3

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.
Files changed (91) hide show
  1. package/README.md +24 -13
  2. package/apps/runtime/dist/docs/dev/integration/openui.md +6 -2
  3. package/apps/runtime/dist/docs/dev/plugins/runners.md +1 -1
  4. package/apps/runtime/dist/docs/dev/wizard-format/index.md +4 -53
  5. package/apps/runtime/dist/docs/dev/wizard-format/meta.json +1 -0
  6. package/apps/runtime/dist/docs/dev/wizard-format/pages-and-fields.md +17 -0
  7. package/apps/runtime/dist/docs/dev/wizard-format/themes.md +220 -0
  8. package/apps/runtime/dist/docs/dev/wizard-format/wizard-file.md +2 -0
  9. package/apps/runtime/dist/docs/user/build-a-wizard.md +25 -19
  10. package/apps/runtime/dist/docs/user/run.md +15 -1
  11. package/apps/runtime/dist/docs/user/space.md +4 -0
  12. package/apps/runtime/dist/docs/user/test-and-share.md +9 -7
  13. package/apps/runtime/dist/engine/runner.js +7 -4
  14. package/apps/runtime/dist/files/upload-check.js +622 -0
  15. package/apps/runtime/dist/harness/terminal.js +14 -7
  16. package/apps/runtime/dist/index.js +2 -0
  17. package/apps/runtime/dist/no-webstorage.js +6 -0
  18. package/apps/runtime/dist/plugins/runs.js +8 -5
  19. package/apps/runtime/dist/routes/runs.js +48 -6
  20. package/apps/runtime/dist/routes/studio.js +11 -4
  21. package/apps/runtime/dist/services/brand.js +20 -0
  22. package/apps/runtime/dist/services/project-files.js +14 -6
  23. package/apps/runtime/dist/services/runners.js +12 -2
  24. package/apps/runtime/dist/services/runs.js +73 -1
  25. package/apps/runtime/dist/services/shipped-fonts.js +33 -0
  26. package/apps/web/dist/assets/AboutDialog-DsGqq2Es.js +1 -0
  27. package/apps/web/dist/assets/{ChangelogDialog-BsM9zGdh.js → ChangelogDialog-Hn7oDuyx.js} +1 -1
  28. package/apps/web/dist/assets/EditorPage-DsJqhoXy.js +4 -0
  29. package/apps/web/dist/assets/{FlowPreview-szPmsT2-.js → FlowPreview-DZ1XL_o1.js} +1 -1
  30. package/apps/web/dist/assets/{Harness-CXx-Js4U.js → Harness-BBpl_EUW.js} +2 -2
  31. package/apps/web/dist/assets/Marketplace-BF0Rx0VR.js +2 -0
  32. package/apps/web/dist/assets/NewWizardChannels-WaAOvmzw.js +1 -0
  33. package/apps/web/dist/assets/NewWizardPage-kpm-UyQC.js +7 -0
  34. package/apps/web/dist/assets/OnboardingPage-Birm-hM5.js +1 -0
  35. package/apps/web/dist/assets/ProjectPage-CqtpxOq5.js +1 -0
  36. package/apps/web/dist/assets/PublicRunner-CXTHGYHv.js +1 -0
  37. package/apps/web/dist/assets/{ReadOnly-BUyOPou5.js → ReadOnly-CcW91P4l.js} +1 -1
  38. package/apps/web/dist/assets/RunDrawer-ByvmBv6e.js +4 -0
  39. package/apps/web/dist/assets/{RunnerView-CufG6xDP.js → RunnerView-DcduYZly.js} +1 -1
  40. package/apps/web/dist/assets/SettingsPage-Q2CUb7kK.js +2 -0
  41. package/apps/web/dist/assets/SetupPage-C7mzUoiR.js +1 -0
  42. package/apps/web/dist/assets/SharePage-CC7V2TYJ.js +1 -0
  43. package/apps/web/dist/assets/changelog-7DN_qWR2.js +1 -0
  44. package/apps/web/dist/assets/coins-RUupcqZx.js +1 -0
  45. package/apps/web/dist/assets/esm-BdxDT9Km.js +7 -0
  46. package/apps/web/dist/assets/index-myC3mJie.css +1 -0
  47. package/apps/web/dist/assets/index-qnpoZzuw.js +14 -0
  48. package/apps/web/dist/assets/logo-CGNoptDg.js +1 -0
  49. package/apps/web/dist/assets/media-Cej-H610.js +1 -0
  50. package/apps/web/dist/assets/oss-credits-D7izqI_0.js +1 -0
  51. package/apps/web/dist/assets/{phone-CJVAobUx.js → phone-ChnpShTU.js} +1 -1
  52. package/apps/web/dist/assets/react-dom-hf6EcyAr.js +1 -0
  53. package/apps/web/dist/assets/session-DekDyd9S.js +2 -0
  54. package/apps/web/dist/assets/settings-menu-CLw_oucZ.js +1 -0
  55. package/apps/web/dist/assets/theme-DjpqxoRe.js +11 -0
  56. package/apps/web/dist/assets/ui-DRYauuxF.js +137 -0
  57. package/apps/web/dist/assets/{upload-Dz86uI5u.js → upload-0sFU9K8-.js} +1 -1
  58. package/apps/web/dist/assets/useMutation-1jFwXbI6.js +1 -0
  59. package/apps/web/dist/assets/volume-2-C51sO2X0.js +1 -0
  60. package/apps/web/dist/assets/{wrench-Dr5LakQv.js → wrench-DdT-nErU.js} +1 -1
  61. package/apps/web/dist/index.html +11 -3
  62. package/apps/web/dist/install.sh +43 -3
  63. package/apps/web/dist/mcp/flow.html +54 -54
  64. package/node_modules/@engenty/wizards-shared/dist/feature-flags.d.ts +12 -0
  65. package/node_modules/@engenty/wizards-shared/dist/feature-flags.js +12 -0
  66. package/node_modules/@engenty/wizards-shared/dist/run.d.ts +4 -0
  67. package/node_modules/@engenty/wizards-shared/dist/run.js +8 -0
  68. package/node_modules/@engenty/wizards-shared/dist/theme.d.ts +7 -0
  69. package/node_modules/@engenty/wizards-shared/dist/theme.js +11 -0
  70. package/package.json +17 -6
  71. package/plugin/.claude-plugin/plugin.json +1 -1
  72. package/plugin/plugin.json +1 -1
  73. package/apps/web/dist/assets/AboutDialog-DKfHXQUv.js +0 -1
  74. package/apps/web/dist/assets/EditorPage-CRcgupmQ.js +0 -4
  75. package/apps/web/dist/assets/NewWizardChannels-C6R1HV0I.js +0 -1
  76. package/apps/web/dist/assets/NewWizardPage-D6Z6DYeT.js +0 -7
  77. package/apps/web/dist/assets/OnboardingPage-DrN26Afr.js +0 -1
  78. package/apps/web/dist/assets/ProjectPage-CNyhwfgz.js +0 -1
  79. package/apps/web/dist/assets/PublicRunner-CREvMYW_.js +0 -1
  80. package/apps/web/dist/assets/RunDrawer-8iWXyXjL.js +0 -4
  81. package/apps/web/dist/assets/SettingsPage-B4M4DrMS.js +0 -2
  82. package/apps/web/dist/assets/SetupPage-D-Op38jE.js +0 -1
  83. package/apps/web/dist/assets/SharePage-BXYVZ3Fa.js +0 -1
  84. package/apps/web/dist/assets/changelog-KvwOYLcI.js +0 -1
  85. package/apps/web/dist/assets/esm-CetquljB.js +0 -7
  86. package/apps/web/dist/assets/index-C5Qmfm_0.css +0 -1
  87. package/apps/web/dist/assets/index-TJhB4-x8.js +0 -14
  88. package/apps/web/dist/assets/oss-credits-BvQGQEzd.js +0 -1
  89. package/apps/web/dist/assets/settings-menu-DjgZMuyV.js +0 -1
  90. package/apps/web/dist/assets/theme-BucH2rUv.js +0 -11
  91. package/apps/web/dist/assets/ui-LJgQlXbd.js +0 -137
@@ -1,13 +1,14 @@
1
1
  ---
2
2
  title: Test and share
3
3
  description: Try the wizard, publish it, and hand out its link or put it on a website.
4
- version: 0.9.0
4
+ version: 0.9.2
5
5
  ---
6
6
 
7
7
  ## Test
8
8
 
9
- “Test” in the editor starts a run of the draft, just as a person would see it. Test runs are
10
- listed under “Runs”. A test spends what a real run spends: your model’s usage, or credits. A test
9
+ “Test” in the preview’s bar starts a run of the draft, just as a person would see it, in the
10
+ preview. “Test run” at the start of the row of steps comes back to it after you looked at a step.
11
+ Test runs are listed under “Runs”. A test spends what a real run spends: your model’s usage, or credits. A test
11
12
  run reads the wizard’s memory, but it writes into a copy of its own, which goes with the run.
12
13
 
13
14
  Where runs spend credits, each AI step shows an estimate. At first it is a formula. After five
@@ -67,10 +68,11 @@ One visitor can start 6 runs an hour.
67
68
 
68
69
  ### Channels
69
70
 
70
- A wizard can run page by page, as a chat, as a live conversation on top of the chat, or as a
71
- video call on a stage with the chat beside it. In a conversation or a call, the person talks,
72
- and the wizard talks back and sees the camera. For now, both need an OpenAI API key under
73
- Models. A plugin can add further ways, such as a kiosk page or a messenger.
71
+ A wizard can run page by page or as a chat. Where this studio offers them, it can also run as a
72
+ live conversation on top of the chat, or as a video call on a stage with the chat beside it. In
73
+ a conversation or a call, the person talks, and the wizard talks back and sees the camera. For
74
+ now, both need an OpenAI API key under Models. A plugin can add further ways, such as a kiosk
75
+ page or a messenger.
74
76
 
75
77
  A wizard you start on the “New wizard” page runs step by step unless you choose more under “How
76
78
  should it run?”. A wizard without its own choice, such as one from a template or an import, has
@@ -19,6 +19,7 @@ import { conversationAvailable, freeTierRefusal, freeTierText, ModelUnavailableE
19
19
  import { runEnded } from "../plugins/events.js";
20
20
  import { projectFiles } from "../services/project-files.js";
21
21
  import { projectProfile } from "../services/projects.js";
22
+ import { switchedOffRunners } from "../services/runners.js";
22
23
  import { storedTranslation } from "../services/translations.js";
23
24
  import { latestShareJob } from "../sharing/state.js";
24
25
  import { listRows, listSecrets, scopeOf } from "../store/index.js";
@@ -864,11 +865,13 @@ function prefillOf(step, run, closed) {
864
865
  return out;
865
866
  }
866
867
  /**
867
- * Whether a run may hold a live conversation: a speech model is set up, and the wizard has live
868
- * voice or video switched on. Its owner's test run always may.
868
+ * Whether a run may hold a live conversation: live voice or video call is switched on for the
869
+ * tenant, a speech model is set up, and the wizard has one of them on. Its owner's test run
870
+ * always may, where one of them is switched on.
869
871
  */
870
872
  export async function talkAllowed(run) {
871
- if (!(await conversationAvailable())) {
873
+ const off = await switchedOffRunners();
874
+ if (CONVERSATION_RUNNERS.every((id) => off.has(id)) || !(await conversationAvailable())) {
872
875
  return false;
873
876
  }
874
877
  if (run.mode === "test") {
@@ -876,7 +879,7 @@ export async function talkAllowed(run) {
876
879
  }
877
880
  const w = await db.query.wizard.findFirst({ where: eq(schema.wizard.id, run.wizardId) });
878
881
  const { enabled } = w?.runners ?? DEFAULT_RUNNER_SETTINGS;
879
- return enabled.some((id) => CONVERSATION_RUNNERS.includes(id));
882
+ return enabled.some((id) => CONVERSATION_RUNNERS.includes(id) && !off.has(id));
880
883
  }
881
884
  export async function runView(run, brand) {
882
885
  // In the viewer's language every text of the view is the translation; ids and values stay.
@@ -0,0 +1,622 @@
1
+ import { spawn } from "node:child_process";
2
+ import { note } from "@engenty/wizards-shared/run";
3
+ import { XMLBuilder, XMLParser } from "fast-xml-parser";
4
+ import { bareMime } from "../routes/delivery.js";
5
+ import { ServiceError } from "../services/errors.js";
6
+ /**
7
+ * What a file that someone uploads goes through before it is kept: its name, its type read from
8
+ * its bytes, a picture's size, a picture drawn again without its metadata, an SVG written again
9
+ * from an allowlist (docs/plans/upload-checks.md).
10
+ */
11
+ /** A picture larger than this is refused before anything decodes it. */
12
+ export const MAX_PIXELS = 50_000_000;
13
+ export const MAX_SIDE = 16_384;
14
+ const MAX_NAME = 120;
15
+ // --- name ---------------------------------------------------------------------------
16
+ /**
17
+ * A file's name as it is kept and shown: no control characters, no bidirectional overrides that
18
+ * make `photo` + U+202E + `gpj.exe` read as `photoexe.jpg`, no folders.
19
+ */
20
+ export function cleanName(name, fallback) {
21
+ const base = name.split(/[/\\]/).pop() ?? "";
22
+ const clean = base
23
+ .replace(/[\p{Cc}\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/gu, "")
24
+ .trim()
25
+ .slice(0, MAX_NAME);
26
+ return clean && clean !== "." && clean !== ".." ? clean : fallback;
27
+ }
28
+ // --- type from the bytes --------------------------------------------------------------
29
+ const has = (d, at, bytes) => d.length >= at + bytes.length && bytes.every((b, i) => d[at + i] === b);
30
+ const text = (d, at, s) => d.length >= at + s.length && [...s].every((ch, i) => d[at + i] === ch.charCodeAt(0));
31
+ const u16be = (d, at) => (d[at] << 8) | d[at + 1];
32
+ const u16le = (d, at) => d[at] | (d[at + 1] << 8);
33
+ const u24le = (d, at) => d[at] | (d[at + 1] << 8) | (d[at + 2] << 16);
34
+ const u32be = (d, at) => ((d[at] << 24) >>> 0) + ((d[at + 1] << 16) | (d[at + 2] << 8) | d[at + 3]);
35
+ const i32le = (d, at) => d[at] | (d[at + 1] << 8) | (d[at + 2] << 16) | (d[at + 3] << 24);
36
+ /** The brands of an ISO media file (MP4, QuickTime, HEIC, AVIF): its `ftyp` box. */
37
+ function ftypBrands(d) {
38
+ if (!text(d, 4, "ftyp")) {
39
+ return null;
40
+ }
41
+ const size = Math.min(u32be(d, 0), d.length, 256);
42
+ const brands = [];
43
+ for (let at = 8; at + 4 <= size; at += at === 8 ? 8 : 4) {
44
+ brands.push(String.fromCharCode(d[at], d[at + 1], d[at + 2], d[at + 3]));
45
+ }
46
+ return brands;
47
+ }
48
+ const HEIF_BRANDS = new Set(["heic", "heix", "hevc", "hevx", "heim", "heis", "mif1", "msf1"]);
49
+ function isoType(brands) {
50
+ if (brands.includes("avif") || brands.includes("avis")) {
51
+ return "image/avif";
52
+ }
53
+ if (HEIF_BRANDS.has(brands[0])) {
54
+ return "image/heic";
55
+ }
56
+ if (brands[0] === "qt ") {
57
+ return "video/quicktime";
58
+ }
59
+ if (brands[0] === "M4A " || brands[0] === "M4B ") {
60
+ return "audio/mp4";
61
+ }
62
+ return "video/mp4";
63
+ }
64
+ /** No NUL in the first 64 KB: what a text, CSV, JSON or mail file holds. */
65
+ function looksLikeText(d) {
66
+ return !d.subarray(0, 65_536).includes(0);
67
+ }
68
+ /** A drawing: text that starts with markup and has `<svg` near the top. */
69
+ function looksLikeSvg(d) {
70
+ if (!looksLikeText(d)) {
71
+ return false;
72
+ }
73
+ const head = new TextDecoder().decode(d.subarray(0, 4096)).replace(/^/, "");
74
+ return /^\s*</.test(head) && /<svg[\s/>]/i.test(head);
75
+ }
76
+ function isBmp(d) {
77
+ return text(d, 0, "BM") && d.length > 26 && [12, 40, 52, 56, 108, 124].includes(i32le(d, 14));
78
+ }
79
+ /** What a file is, from its first bytes; null when none of the types below. */
80
+ export function sniffType(d) {
81
+ if (has(d, 0, [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])) {
82
+ return "image/png";
83
+ }
84
+ if (has(d, 0, [0xff, 0xd8, 0xff])) {
85
+ return "image/jpeg";
86
+ }
87
+ if (text(d, 0, "GIF87a") || text(d, 0, "GIF89a")) {
88
+ return "image/gif";
89
+ }
90
+ if (text(d, 0, "RIFF")) {
91
+ if (text(d, 8, "WEBP")) {
92
+ return "image/webp";
93
+ }
94
+ if (text(d, 8, "WAVE")) {
95
+ return "audio/wav";
96
+ }
97
+ if (text(d, 8, "AVI ")) {
98
+ return "video/x-msvideo";
99
+ }
100
+ }
101
+ const brands = ftypBrands(d);
102
+ if (brands) {
103
+ return isoType(brands);
104
+ }
105
+ if (isBmp(d)) {
106
+ return "image/bmp";
107
+ }
108
+ if (has(d, 0, [0x00, 0x00, 0x01, 0x00]) && d.length > 6 && u16le(d, 4) > 0) {
109
+ return "image/x-icon";
110
+ }
111
+ if (has(d, 0, [0x1a, 0x45, 0xdf, 0xa3])) {
112
+ return new TextDecoder("latin1").decode(d.subarray(0, 64)).includes("webm")
113
+ ? "video/webm"
114
+ : "video/x-matroska";
115
+ }
116
+ if (text(d, 0, "OggS")) {
117
+ return "audio/ogg";
118
+ }
119
+ if (text(d, 0, "fLaC")) {
120
+ return "audio/flac";
121
+ }
122
+ if (text(d, 0, "ID3") || (d[0] === 0xff && d.length > 1 && (d[1] & 0xe0) === 0xe0)) {
123
+ return "audio/mpeg";
124
+ }
125
+ if (new TextDecoder("latin1").decode(d.subarray(0, 1024)).includes("%PDF-")) {
126
+ return "application/pdf";
127
+ }
128
+ if (has(d, 0, [0x50, 0x4b, 0x03, 0x04]) || has(d, 0, [0x50, 0x4b, 0x05, 0x06])) {
129
+ return "application/zip";
130
+ }
131
+ if (has(d, 0, [0xd0, 0xcf, 0x11, 0xe0, 0xa1, 0xb1, 0x1a, 0xe1])) {
132
+ return "application/x-ole-storage";
133
+ }
134
+ if (text(d, 0, "{\\rtf")) {
135
+ return "application/rtf";
136
+ }
137
+ if (text(d, 0, "wOFF")) {
138
+ return "font/woff";
139
+ }
140
+ if (text(d, 0, "wOF2")) {
141
+ return "font/woff2";
142
+ }
143
+ if (has(d, 0, [0x00, 0x01, 0x00, 0x00]) || text(d, 0, "true")) {
144
+ return "font/ttf";
145
+ }
146
+ if (text(d, 0, "OTTO")) {
147
+ return "font/otf";
148
+ }
149
+ if (text(d, 0, "ttcf")) {
150
+ return "font/collection";
151
+ }
152
+ if (text(d, 0, "glTF")) {
153
+ return "model/gltf-binary";
154
+ }
155
+ if (looksLikeSvg(d)) {
156
+ return "image/svg+xml";
157
+ }
158
+ return null;
159
+ }
160
+ const OFFICE = /^application\/(msword|vnd\.ms-[a-z.-]+|vnd\.openxmlformats-officedocument\.[a-z.-]+|vnd\.oasis\.opendocument\.[a-z.-]+)$/;
161
+ const FONT = /^(font\/|application\/(font-|x-font-|vnd\.ms-fontobject))/;
162
+ function declaredKind(mime) {
163
+ if (mime.startsWith("image/")) {
164
+ return "image";
165
+ }
166
+ if (/^(audio|video)\//.test(mime)) {
167
+ return "media";
168
+ }
169
+ if (mime === "application/pdf") {
170
+ return "pdf";
171
+ }
172
+ if (OFFICE.test(mime)) {
173
+ return "office";
174
+ }
175
+ if (mime === "application/zip" || mime === "application/x-zip-compressed") {
176
+ return "zip";
177
+ }
178
+ if (mime === "application/rtf" || mime === "text/rtf") {
179
+ return "rtf";
180
+ }
181
+ if (FONT.test(mime)) {
182
+ return "font";
183
+ }
184
+ if (mime === "model/gltf-binary") {
185
+ return "glb";
186
+ }
187
+ if (mime.startsWith("text/") ||
188
+ mime === "application/json" ||
189
+ mime === "message/rfc822" ||
190
+ mime === "model/gltf+json") {
191
+ return "text";
192
+ }
193
+ return null;
194
+ }
195
+ function bytesFit(kind, sniffed, d) {
196
+ switch (kind) {
197
+ case "image":
198
+ return sniffed?.startsWith("image/") ?? false;
199
+ case "media":
200
+ return /^(audio|video)\//.test(sniffed ?? "");
201
+ case "pdf":
202
+ return sniffed === "application/pdf";
203
+ case "office":
204
+ return sniffed === "application/zip" || sniffed === "application/x-ole-storage";
205
+ case "zip":
206
+ return sniffed === "application/zip";
207
+ case "rtf":
208
+ return sniffed === "application/rtf";
209
+ case "font":
210
+ return sniffed?.startsWith("font/") ?? false;
211
+ case "glb":
212
+ return sniffed === "model/gltf-binary";
213
+ case "text":
214
+ return looksLikeText(d);
215
+ }
216
+ }
217
+ // --- pictures -------------------------------------------------------------------------
218
+ /** A JPEG's size from its frame header. */
219
+ function jpegSize(d) {
220
+ let at = 2;
221
+ while (at + 9 < d.length) {
222
+ if (d[at] !== 0xff) {
223
+ return null;
224
+ }
225
+ const marker = d[at + 1];
226
+ if (marker === 0xff) {
227
+ at += 1;
228
+ continue;
229
+ }
230
+ if (marker === 0xd8 || marker === 0x01 || (marker >= 0xd0 && marker <= 0xd7)) {
231
+ at += 2;
232
+ continue;
233
+ }
234
+ const isFrame = marker >= 0xc0 && marker <= 0xcf && marker !== 0xc4 && marker !== 0xc8 && marker !== 0xcc;
235
+ if (isFrame) {
236
+ return { height: u16be(d, at + 5), width: u16be(d, at + 7) };
237
+ }
238
+ at += 2 + u16be(d, at + 2);
239
+ }
240
+ return null;
241
+ }
242
+ function webpSize(d) {
243
+ if (text(d, 12, "VP8 ") && d.length >= 30) {
244
+ return { width: u16le(d, 26) & 0x3fff, height: u16le(d, 28) & 0x3fff };
245
+ }
246
+ if (text(d, 12, "VP8L") && d.length >= 25) {
247
+ const [b0, b1, b2, b3] = [d[21], d[22], d[23], d[24]];
248
+ return {
249
+ width: 1 + (((b1 & 0x3f) << 8) | b0),
250
+ height: 1 + (((b3 & 0x0f) << 10) | (b2 << 2) | ((b1 & 0xc0) >> 6)),
251
+ };
252
+ }
253
+ if (text(d, 12, "VP8X") && d.length >= 30) {
254
+ return { width: 1 + u24le(d, 24), height: 1 + u24le(d, 27) };
255
+ }
256
+ return null;
257
+ }
258
+ /** HEIC and AVIF name each image's size in an `ispe` box; a grid's whole is the largest. */
259
+ function ispeSize(d) {
260
+ let found = null;
261
+ const end = Math.min(d.length, 2_000_000) - 16;
262
+ for (let at = 0; at < end; at++) {
263
+ if (d[at] === 0x69 && text(d, at, "ispe")) {
264
+ const width = u32be(d, at + 8);
265
+ const height = u32be(d, at + 12);
266
+ if (!found || width * height > found.width * found.height) {
267
+ found = { width, height };
268
+ }
269
+ }
270
+ }
271
+ return found;
272
+ }
273
+ /** A picture's size in pixels, read from its header without decoding it. */
274
+ export function pictureSize(d, mime) {
275
+ switch (mime) {
276
+ case "image/png":
277
+ return d.length >= 24 && text(d, 12, "IHDR")
278
+ ? { width: u32be(d, 16), height: u32be(d, 20) }
279
+ : null;
280
+ case "image/gif":
281
+ return d.length >= 10 ? { width: u16le(d, 6), height: u16le(d, 8) } : null;
282
+ case "image/jpeg":
283
+ return jpegSize(d);
284
+ case "image/webp":
285
+ return webpSize(d);
286
+ case "image/avif":
287
+ case "image/heic":
288
+ return ispeSize(d);
289
+ case "image/bmp":
290
+ return i32le(d, 14) === 12
291
+ ? { width: u16le(d, 18), height: u16le(d, 20) }
292
+ : { width: Math.abs(i32le(d, 18)), height: Math.abs(i32le(d, 22)) };
293
+ default:
294
+ return null;
295
+ }
296
+ }
297
+ /** Whether a picture moves: drawing it again would keep one frame. */
298
+ function animated(d, mime) {
299
+ if (mime === "image/gif") {
300
+ return true;
301
+ }
302
+ if (mime === "image/webp") {
303
+ return text(d, 12, "VP8X") && (d[20] & 0x02) !== 0;
304
+ }
305
+ if (mime === "image/avif") {
306
+ return ftypBrands(d)?.includes("avis") ?? false;
307
+ }
308
+ if (mime === "image/png") {
309
+ for (let at = 8; at + 8 <= d.length;) {
310
+ const type = String.fromCharCode(d[at + 4], d[at + 5], d[at + 6], d[at + 7]);
311
+ if (type === "acTL") {
312
+ return true;
313
+ }
314
+ if (type === "IDAT") {
315
+ return false;
316
+ }
317
+ at += 12 + u32be(d, at);
318
+ }
319
+ }
320
+ return false;
321
+ }
322
+ /** The formats drawn again, each in itself: PNG lossless, the others at a quality a photo keeps. */
323
+ const REDRAWN = new Set(["image/png", "image/jpeg", "image/webp", "image/avif"]);
324
+ /**
325
+ * What draws a picture again, in a process of its own: a broken PNG, JPEG or WebP can crash the
326
+ * image library, and that must not take the runtime down. It reads the bytes on stdin, writes the
327
+ * new ones on stdout, and ends with 3 when the picture doesn't decode.
328
+ */
329
+ const REDRAW = `
330
+ const [url, mime] = process.argv.slice(1);
331
+ const { createCanvas, loadImage } = await import(url);
332
+ const chunks = [];
333
+ for await (const chunk of process.stdin) chunks.push(chunk);
334
+ let image;
335
+ try { image = await loadImage(Buffer.concat(chunks)); } catch { process.exit(3); }
336
+ if (!image.width || !image.height) process.exit(3);
337
+ const canvas = createCanvas(image.width, image.height);
338
+ canvas.getContext("2d").drawImage(image, 0, 0);
339
+ const out =
340
+ mime === "image/jpeg" ? await canvas.encode("jpeg", 92)
341
+ : mime === "image/webp" ? await canvas.encode("webp", 92)
342
+ : mime === "image/avif" ? await canvas.encode("avif", { quality: 80, speed: 8 })
343
+ : await canvas.encode("png");
344
+ process.stdout.write(out, () => process.exit(0));
345
+ `;
346
+ const REDRAW_TIMEOUT_MS = 30_000;
347
+ /** Two pictures are drawn at a time; each process holds a decoded picture in memory. */
348
+ let drawing = 0;
349
+ const waiting = [];
350
+ async function inTurn(work) {
351
+ if (drawing >= 2) {
352
+ await new Promise((resolve) => waiting.push(resolve));
353
+ }
354
+ drawing++;
355
+ try {
356
+ return await work();
357
+ }
358
+ finally {
359
+ drawing--;
360
+ waiting.shift()?.();
361
+ }
362
+ }
363
+ /** The bytes the child wrote, or null when it couldn't draw the picture, crashed or took too long. */
364
+ function drawInChild(d, mime) {
365
+ return new Promise((resolve) => {
366
+ const child = spawn(process.execPath, ["--input-type=module", "-e", REDRAW, import.meta.resolve("@napi-rs/canvas"), mime], { env: {}, stdio: ["pipe", "pipe", "ignore"], timeout: REDRAW_TIMEOUT_MS });
367
+ const out = [];
368
+ child.stdout.on("data", (chunk) => out.push(chunk));
369
+ child.on("error", () => resolve(null));
370
+ child.on("close", (code) => resolve(code === 0 ? Buffer.concat(out) : null));
371
+ child.stdin.on("error", () => undefined);
372
+ child.stdin.end(Buffer.from(d));
373
+ });
374
+ }
375
+ /**
376
+ * A picture decoded and encoded again in its own format: upright as its EXIF orientation said,
377
+ * without EXIF, XMP, comments or anything after its end. Refuses one that doesn't decode.
378
+ */
379
+ async function redraw(d, mime) {
380
+ const out = await inTurn(() => drawInChild(d, mime));
381
+ if (!out?.byteLength) {
382
+ throw new ServiceError("invalid", note("uploadNotPicture"));
383
+ }
384
+ return new Uint8Array(out);
385
+ }
386
+ async function checkPicture(d, mime) {
387
+ if (mime === "image/svg+xml") {
388
+ return new TextEncoder().encode(cleanSvg(new TextDecoder().decode(d)));
389
+ }
390
+ if (mime === "image/x-icon") {
391
+ return d;
392
+ }
393
+ const size = pictureSize(d, mime);
394
+ if (!size?.width || !size.height) {
395
+ throw new ServiceError("invalid", note("uploadNotPicture"));
396
+ }
397
+ if (size.width > MAX_SIDE || size.height > MAX_SIDE || size.width * size.height > MAX_PIXELS) {
398
+ throw new ServiceError("invalid", note("uploadPictureTooLarge", { mp: Math.round(MAX_PIXELS / 1_000_000) }));
399
+ }
400
+ return REDRAWN.has(mime) && !animated(d, mime) ? redraw(d, mime) : d;
401
+ }
402
+ // --- SVG ------------------------------------------------------------------------------
403
+ const SVG_ELEMENTS = new Set([
404
+ "svg",
405
+ "g",
406
+ "defs",
407
+ "symbol",
408
+ "use",
409
+ "path",
410
+ "rect",
411
+ "circle",
412
+ "ellipse",
413
+ "line",
414
+ "polyline",
415
+ "polygon",
416
+ "text",
417
+ "tspan",
418
+ "textPath",
419
+ "title",
420
+ "desc",
421
+ "linearGradient",
422
+ "radialGradient",
423
+ "stop",
424
+ "clipPath",
425
+ "mask",
426
+ "pattern",
427
+ "marker",
428
+ "image",
429
+ "style",
430
+ "filter",
431
+ "feBlend",
432
+ "feColorMatrix",
433
+ "feComponentTransfer",
434
+ "feComposite",
435
+ "feConvolveMatrix",
436
+ "feDiffuseLighting",
437
+ "feDisplacementMap",
438
+ "feDistantLight",
439
+ "feDropShadow",
440
+ "feFlood",
441
+ "feFuncA",
442
+ "feFuncB",
443
+ "feFuncG",
444
+ "feFuncR",
445
+ "feGaussianBlur",
446
+ "feMerge",
447
+ "feMergeNode",
448
+ "feMorphology",
449
+ "feOffset",
450
+ "fePointLight",
451
+ "feSpecularLighting",
452
+ "feSpotLight",
453
+ "feTile",
454
+ "feTurbulence",
455
+ ].map((n) => n.toLowerCase()));
456
+ /** Elements whose content stays where they go: a link's text, a switch's choices. */
457
+ const SVG_UNWRAPPED = new Set(["a", "switch"]);
458
+ const NAMESPACES = new Set(["http://www.w3.org/2000/svg", "http://www.w3.org/1999/xlink"]);
459
+ const DATA_PICTURE = /^data:image\/(png|jpeg|gif|webp);base64,[a-z0-9+/=\s]*$/i;
460
+ /** Text as a browser reads it after XML: character references and the five named entities resolved. */
461
+ function decodeEntities(v) {
462
+ return v
463
+ .replace(/&#x([0-9a-f]+);?/gi, (_, hex) => String.fromCodePoint(Number.parseInt(hex, 16)))
464
+ .replace(/&#(\d+);?/g, (_, dec) => String.fromCodePoint(Number(dec)))
465
+ .replace(/&(lt|gt|quot|apos|amp);/g, (_, n) => ({ lt: "<", gt: ">", quot: '"', apos: "'", amp: "&" })[n] ?? "");
466
+ }
467
+ /**
468
+ * CSS that reaches nothing outside the drawing: only `url(#…)`, no imports, no expressions, and
469
+ * no escapes that could spell any of them.
470
+ */
471
+ export function cssStaysInside(css) {
472
+ const flat = decodeEntities(css).toLowerCase();
473
+ if (/\\|@import|expression\s*\(|javascript:|behavior\s*:|-moz-binding/.test(flat)) {
474
+ return false;
475
+ }
476
+ return [...flat.matchAll(/url\s*\(\s*(['"]?)\s*([^)'"]*)/g)].every((m) => m[2].startsWith("#"));
477
+ }
478
+ const escapeAttr = (v) => v
479
+ .replace(/&(?!(?:[a-z][a-z0-9]*|#\d+|#x[0-9a-f]+);)/gi, "&amp;")
480
+ .replace(/"/g, "&quot;")
481
+ .replace(/</g, "&lt;");
482
+ const escapeText = (v) => v.replace(/&(?!(?:[a-z][a-z0-9]*|#\d+|#x[0-9a-f]+);)/gi, "&amp;").replace(/</g, "&lt;");
483
+ function nodeName(node) {
484
+ return Object.keys(node).find((k) => k !== ":@") ?? "";
485
+ }
486
+ function cleanAttrs(element, attrs) {
487
+ const kept = {};
488
+ for (const [key, raw] of Object.entries(attrs ?? {})) {
489
+ const name = key.slice(2);
490
+ const lower = name.toLowerCase();
491
+ const value = String(raw);
492
+ if (lower.startsWith("on")) {
493
+ continue;
494
+ }
495
+ if (lower === "xmlns" || lower === "xmlns:xlink") {
496
+ if (NAMESPACES.has(value)) {
497
+ kept[key] = escapeAttr(value);
498
+ }
499
+ continue;
500
+ }
501
+ if (lower.includes(":") && lower !== "xlink:href" && lower !== "xml:space") {
502
+ continue;
503
+ }
504
+ if (lower === "href" || lower === "xlink:href") {
505
+ const target = value.trim();
506
+ if (target.startsWith("#") || (element === "image" && DATA_PICTURE.test(target))) {
507
+ kept[key] = escapeAttr(target);
508
+ }
509
+ continue;
510
+ }
511
+ if (!cssStaysInside(value)) {
512
+ continue;
513
+ }
514
+ kept[key] = escapeAttr(value);
515
+ }
516
+ return kept;
517
+ }
518
+ function cleanNodes(nodes, inStyle = false) {
519
+ const out = [];
520
+ for (const node of nodes) {
521
+ const name = nodeName(node);
522
+ if (name === "#text" || name === "#cdata") {
523
+ const value = name === "#cdata" ? node[name] : String(node[name] ?? "");
524
+ if (name === "#text") {
525
+ out.push({ "#text": inStyle ? String(value) : escapeText(String(value)) });
526
+ }
527
+ else {
528
+ out.push({ "#cdata": value });
529
+ }
530
+ continue;
531
+ }
532
+ const lower = name.toLowerCase();
533
+ const children = node[name] ?? [];
534
+ if (SVG_UNWRAPPED.has(lower)) {
535
+ out.push(...cleanNodes(children));
536
+ continue;
537
+ }
538
+ if (!SVG_ELEMENTS.has(lower)) {
539
+ continue;
540
+ }
541
+ if (lower === "style") {
542
+ const css = children
543
+ .map((c) => {
544
+ const v = c["#text"] ?? c["#cdata"];
545
+ return Array.isArray(v) ? v.map((x) => x["#text"] ?? "").join("") : v;
546
+ })
547
+ .join("");
548
+ if (!cssStaysInside(String(css))) {
549
+ continue;
550
+ }
551
+ }
552
+ const attrs = cleanAttrs(lower, node[":@"]);
553
+ out.push({
554
+ [name]: cleanNodes(children, lower === "style"),
555
+ ...(Object.keys(attrs).length ? { ":@": attrs } : {}),
556
+ });
557
+ }
558
+ return out;
559
+ }
560
+ /** An SVG written again from the allowlist above. Refuses declarations and a root that isn't `<svg>`. */
561
+ export function cleanSvg(source) {
562
+ if (/<!DOCTYPE|<!ENTITY|<\?xml-stylesheet/i.test(source)) {
563
+ throw new ServiceError("invalid", note("uploadSvgNotUsable"));
564
+ }
565
+ let tree;
566
+ try {
567
+ tree = new XMLParser({
568
+ preserveOrder: true,
569
+ ignoreAttributes: false,
570
+ attributeNamePrefix: "@_",
571
+ parseAttributeValue: false,
572
+ parseTagValue: false,
573
+ processEntities: false,
574
+ htmlEntities: false,
575
+ trimValues: false,
576
+ cdataPropName: "#cdata",
577
+ }).parse(source);
578
+ }
579
+ catch {
580
+ throw new ServiceError("invalid", note("uploadSvgNotUsable"));
581
+ }
582
+ const roots = tree.filter((n) => {
583
+ const name = nodeName(n);
584
+ return !name.startsWith("?") && !name.startsWith("!") && name !== "#text";
585
+ });
586
+ if (roots.length !== 1 || nodeName(roots[0]) !== "svg") {
587
+ throw new ServiceError("invalid", note("uploadSvgNotUsable"));
588
+ }
589
+ const clean = cleanNodes(roots);
590
+ const xml = new XMLBuilder({
591
+ preserveOrder: true,
592
+ ignoreAttributes: false,
593
+ attributeNamePrefix: "@_",
594
+ processEntities: false,
595
+ suppressEmptyNode: true,
596
+ cdataPropName: "#cdata",
597
+ }).build(clean);
598
+ return xml;
599
+ }
600
+ // --- the whole check --------------------------------------------------------------------
601
+ /**
602
+ * A file as it is kept: its clean name, the type its bytes show (a picture by its bytes, the
603
+ * rest as declared once the bytes agree), and a picture drawn again. Refuses a file whose bytes
604
+ * aren't what its type says, a picture too large to decode, and an SVG that can't be cleaned.
605
+ * A type not checked here is kept as declared: it is served as a download.
606
+ */
607
+ export async function checkUpload(input) {
608
+ const name = cleanName(input.name, input.fallbackName ?? "file");
609
+ const declared = bareMime(input.mime) ?? "application/octet-stream";
610
+ const kind = declaredKind(declared);
611
+ if (!kind) {
612
+ return { name, mime: declared, data: input.data };
613
+ }
614
+ const sniffed = sniffType(input.data);
615
+ if (!bytesFit(kind, sniffed, input.data)) {
616
+ throw new ServiceError("invalid", kind === "image" ? note("uploadNotPicture") : note("uploadNotItsType"));
617
+ }
618
+ if (kind !== "image" || !sniffed) {
619
+ return { name, mime: declared, data: input.data };
620
+ }
621
+ return { name, mime: sniffed, data: await checkPicture(input.data, sniffed) };
622
+ }