@capybara-hq/plugin-sdk 0.1.0-rc.5 → 0.1.0-rc.51

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 (134) hide show
  1. package/README.md +1 -1
  2. package/agent-docs/agent-templates.md +14 -2
  3. package/agent-docs/concepts.md +14 -5
  4. package/agent-docs/connector-templates.md +4 -1
  5. package/agent-docs/extension-points/channel.md +1 -1
  6. package/agent-docs/extension-points/context.md +15 -0
  7. package/agent-docs/extension-points/device-provider.md +15 -0
  8. package/agent-docs/extension-points/file-preview.md +2 -0
  9. package/agent-docs/extension-points/model-provider.md +3 -1
  10. package/agent-docs/extension-points/object-store.md +2 -0
  11. package/agent-docs/extension-points/push-provider.md +17 -0
  12. package/agent-docs/extensions.md +29 -3
  13. package/agent-docs/plugin-format.md +53 -2
  14. package/agent-docs/setup.md +54 -0
  15. package/dist/agent-template.d.ts +15 -6
  16. package/dist/agent-template.js +32 -13
  17. package/dist/avatar-presets.d.ts +8 -0
  18. package/dist/avatar-presets.js +17 -0
  19. package/dist/bootstrap.d.ts +86 -1
  20. package/dist/bootstrap.js +161 -2
  21. package/dist/cards.d.ts +67 -13
  22. package/dist/cards.js +91 -21
  23. package/dist/channel.d.ts +148 -48
  24. package/dist/channel.js +10 -5
  25. package/dist/client-css.d.ts +36 -0
  26. package/dist/client-css.js +326 -0
  27. package/dist/client-section.d.ts +35 -0
  28. package/dist/client-section.js +133 -0
  29. package/dist/config-ui.d.ts +22 -0
  30. package/dist/config-ui.js +64 -4
  31. package/dist/connector-auth.d.ts +7 -2
  32. package/dist/connector-auth.js +29 -8
  33. package/dist/connector.d.ts +74 -32
  34. package/dist/context.d.ts +40 -0
  35. package/dist/context.js +2 -0
  36. package/dist/ctx.d.ts +120 -29
  37. package/dist/define-extension.d.ts +26 -12
  38. package/dist/define-extension.js +11 -4
  39. package/dist/device-denied-paths.d.ts +14 -0
  40. package/dist/device-denied-paths.js +41 -0
  41. package/dist/device-operation.d.ts +302 -0
  42. package/dist/device-operation.js +292 -0
  43. package/dist/device-protocol.d.ts +490 -0
  44. package/dist/device-protocol.js +1117 -0
  45. package/dist/device-provider.d.ts +472 -0
  46. package/dist/device-provider.js +283 -0
  47. package/dist/extension-point.d.ts +2 -0
  48. package/dist/extension-point.js +6 -2
  49. package/dist/file-preview.d.ts +23 -6
  50. package/dist/git-hosts.d.ts +53 -0
  51. package/dist/git-hosts.js +98 -0
  52. package/dist/hooks.d.ts +125 -20
  53. package/dist/hooks.js +5 -0
  54. package/dist/http-access.d.ts +62 -0
  55. package/dist/http-access.js +12 -0
  56. package/dist/identity.d.ts +38 -9
  57. package/dist/identity.js +21 -1
  58. package/dist/index.d.ts +29 -2
  59. package/dist/index.js +29 -2
  60. package/dist/marketplace.d.ts +26 -0
  61. package/dist/marketplace.js +43 -1
  62. package/dist/model-params.d.ts +41 -22
  63. package/dist/model-params.js +28 -15
  64. package/dist/model.d.ts +206 -71
  65. package/dist/model.js +152 -19
  66. package/dist/net.d.ts +52 -0
  67. package/dist/net.js +34 -0
  68. package/dist/network-classes.d.ts +98 -0
  69. package/dist/network-classes.js +291 -0
  70. package/dist/permissions.d.ts +41 -21
  71. package/dist/permissions.js +101 -42
  72. package/dist/plugin-manifest.d.ts +45 -5
  73. package/dist/plugin-manifest.js +169 -6
  74. package/dist/plugin-package.d.ts +82 -38
  75. package/dist/plugin-package.js +61 -29
  76. package/dist/push.d.ts +75 -0
  77. package/dist/push.js +87 -0
  78. package/dist/sandbox-linux-runtime-source.d.ts +1 -0
  79. package/dist/sandbox-linux-runtime-source.js +2318 -0
  80. package/dist/sandbox-native-runtime-source.d.ts +10 -0
  81. package/dist/sandbox-native-runtime-source.js +476 -0
  82. package/dist/sandbox-runtime-source.d.ts +19 -0
  83. package/dist/sandbox-runtime-source.js +28 -0
  84. package/dist/sandbox-write-denies.d.ts +139 -0
  85. package/dist/sandbox-write-denies.js +869 -0
  86. package/dist/secret.d.ts +4 -1
  87. package/dist/secret.js +4 -1
  88. package/dist/setup-check.d.ts +128 -0
  89. package/dist/setup-check.js +142 -0
  90. package/dist/setup-guide-parse.d.ts +135 -0
  91. package/dist/setup-guide-parse.js +413 -0
  92. package/dist/setup-guide-render.d.ts +50 -0
  93. package/dist/setup-guide-render.js +367 -0
  94. package/dist/setup-guide.d.ts +109 -0
  95. package/dist/setup-guide.js +377 -0
  96. package/dist/shell-capabilities.d.ts +231 -0
  97. package/dist/shell-capabilities.js +37 -0
  98. package/dist/shell-environment.d.ts +57 -0
  99. package/dist/shell-environment.js +22 -0
  100. package/dist/skill-invocation.d.ts +4 -3
  101. package/dist/skill-invocation.js +5 -4
  102. package/dist/skill.d.ts +34 -21
  103. package/dist/skill.js +49 -32
  104. package/dist/storage.d.ts +52 -25
  105. package/dist/theme-assets.d.ts +55 -0
  106. package/dist/theme-assets.js +507 -0
  107. package/dist/theme-readability.d.ts +37 -0
  108. package/dist/theme-readability.js +145 -0
  109. package/dist/theme-tokens.generated.d.ts +299 -0
  110. package/dist/theme-tokens.generated.js +184 -0
  111. package/dist/theme.d.ts +190 -0
  112. package/dist/theme.js +471 -0
  113. package/dist/tool.d.ts +69 -26
  114. package/dist/tool.js +29 -9
  115. package/dist/ui-parts.d.ts +23 -0
  116. package/dist/ui-parts.js +348 -0
  117. package/dist/ui-resolve.d.ts +35 -0
  118. package/dist/ui-resolve.js +42 -0
  119. package/dist/ui-slots.d.ts +65 -0
  120. package/dist/ui-slots.js +261 -0
  121. package/dist/ui.d.ts +212 -76
  122. package/dist/ui.js +101 -27
  123. package/dist/url.d.ts +4 -1
  124. package/dist/url.js +4 -1
  125. package/package.json +8 -1
  126. package/schemas/bootstrap-extra.v1.schema.json +172 -0
  127. package/schemas/bootstrap.v1.schema.json +6 -0
  128. package/schemas/connector-template.v1.schema.json +35 -0
  129. package/schemas/marketplace.v1.schema.json +14 -0
  130. package/schemas/plugin.v1.schema.json +117 -3
  131. package/schemas/theme.v1.schema.json +302 -0
  132. package/agent-docs/extension-points/sandbox.md +0 -15
  133. package/dist/sandbox.d.ts +0 -232
  134. package/dist/sandbox.js +0 -120
@@ -0,0 +1,507 @@
1
+ import { SaxesParser } from "saxes";
2
+ import { isSafePackagePath } from "./plugin-package.js";
3
+ import { THEME_LIMITS } from "./theme.js";
4
+ /**
5
+ * Checks of a theme's asset files (themes spec §4.2-§4.4, theme brand coverage spec §1): woff2
6
+ * fonts, PNG logos, app icons and avatars, and the SVG sanitizer. The sanitized SVG is served to
7
+ * every browser, so {@link sanitizeThemeSvg} is a trust boundary: the output is re-serialized from
8
+ * the parsed tree (never the input bytes), elements are allowlisted, every attribute value and text
9
+ * node is escaped on output.
10
+ */
11
+ const SVG_NS = "http://www.w3.org/2000/svg";
12
+ const XLINK_NS = "http://www.w3.org/1999/xlink";
13
+ const XML_NS = "http://www.w3.org/XML/1998/namespace";
14
+ const XMLNS_NS = "http://www.w3.org/2000/xmlns/";
15
+ const XHTML_NS = "http://www.w3.org/1999/xhtml";
16
+ /** SVG elements a logo may use: shapes, structure, paint servers, filters and animation. */
17
+ const SVG_ELEMENTS = new Set([
18
+ "svg",
19
+ "g",
20
+ "defs",
21
+ "symbol",
22
+ "use",
23
+ "title",
24
+ "desc",
25
+ "metadata",
26
+ "a",
27
+ "switch",
28
+ "view",
29
+ "path",
30
+ "rect",
31
+ "circle",
32
+ "ellipse",
33
+ "line",
34
+ "polyline",
35
+ "polygon",
36
+ "text",
37
+ "tspan",
38
+ "textPath",
39
+ "image",
40
+ "marker",
41
+ "linearGradient",
42
+ "radialGradient",
43
+ "stop",
44
+ "pattern",
45
+ "clipPath",
46
+ "mask",
47
+ "filter",
48
+ "feBlend",
49
+ "feColorMatrix",
50
+ "feComponentTransfer",
51
+ "feComposite",
52
+ "feConvolveMatrix",
53
+ "feDiffuseLighting",
54
+ "feDisplacementMap",
55
+ "feDistantLight",
56
+ "feDropShadow",
57
+ "feFlood",
58
+ "feFuncA",
59
+ "feFuncB",
60
+ "feFuncG",
61
+ "feFuncR",
62
+ "feGaussianBlur",
63
+ "feImage",
64
+ "feMerge",
65
+ "feMergeNode",
66
+ "feMorphology",
67
+ "feOffset",
68
+ "fePointLight",
69
+ "feSpecularLighting",
70
+ "feSpotLight",
71
+ "feTile",
72
+ "feTurbulence",
73
+ "animate",
74
+ "animateMotion",
75
+ "animateTransform",
76
+ "set",
77
+ "mpath",
78
+ ]);
79
+ /** `xml:` attributes kept; `xml:base` and the rest are dropped. */
80
+ const XML_ATTRS = new Set(["space", "lang"]);
81
+ /** Root attributes dropped: the design system sizes the logo to its slot. */
82
+ const ROOT_DROPPED = new Set(["width", "height", "class"]);
83
+ /** Characters of a viewBox value; longer values are refused before they are split. */
84
+ const VIEWBOX_MAX_CHARS = 128;
85
+ /** Characters a viewBox number may use (checked per character class, no backtracking). */
86
+ const VIEWBOX_NUMBER_RE = /^[-+.0-9eE]+$/;
87
+ /**
88
+ * The only functions an attribute value may call: colors and transforms. `url` is allowed only as
89
+ * `url(#id)` (checked separately); everything else (`image-set`, `cross-fade`, `element`,
90
+ * `src`, `var`, ...) is refused, since some of them load resources from quoted strings.
91
+ */
92
+ const ALLOWED_FUNCTIONS = new Set([
93
+ "url",
94
+ "rgb",
95
+ "rgba",
96
+ "hsl",
97
+ "hsla",
98
+ "translate",
99
+ "rotate",
100
+ "scale",
101
+ "matrix",
102
+ "skewx",
103
+ "skewy",
104
+ ]);
105
+ const isIdentChar = (c) => /[A-Za-z0-9_-]/.test(c);
106
+ const isSpace = (c) => c === " " || c === "\t" || c === "\n" || c === "\r" || c === "\f";
107
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: whitespace and control characters are stripped before matching schemes
108
+ const IGNORED_IN_SCHEME_RE = /[\u0000- \u007f]/g;
109
+ class SvgRejected extends Error {
110
+ }
111
+ const reject = (message) => {
112
+ throw new SvgRejected(message);
113
+ };
114
+ const escapeText = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
115
+ const escapeAttr = (s) => escapeText(s)
116
+ .replace(/"/g, "&quot;")
117
+ .replace(/\t/g, "&#9;")
118
+ .replace(/\n/g, "&#10;")
119
+ .replace(/\r/g, "&#13;");
120
+ /** Rejects an attribute value that could run script or load a resource outside the document. */
121
+ function checkValue(el, attr, value) {
122
+ const squeezed = value.replace(IGNORED_IN_SCHEME_RE, "").toLowerCase();
123
+ if (squeezed.includes("javascript:") || squeezed.includes("vbscript:")) {
124
+ reject(`attribute ${attr} on <${el}> must not contain javascript: or vbscript: URLs`);
125
+ }
126
+ // CSS escapes could spell a function name; quoted strings are how CSS functions take URLs.
127
+ if (value.includes("\\"))
128
+ reject(`attribute ${attr} on <${el}> must not contain "\\"`);
129
+ if (value.includes("'") || value.includes('"')) {
130
+ reject(`attribute ${attr} on <${el}> must not contain quotes`);
131
+ }
132
+ // Linear scan: at every "(", walk back over spaces and the function name.
133
+ for (let i = value.indexOf("("); i !== -1; i = value.indexOf("(", i + 1)) {
134
+ let end = i;
135
+ while (end > 0 && isSpace(value.charAt(end - 1)))
136
+ end -= 1;
137
+ let start = end;
138
+ while (start > 0 && isIdentChar(value.charAt(start - 1)))
139
+ start -= 1;
140
+ const fn = value.slice(start, end).toLowerCase();
141
+ if (!ALLOWED_FUNCTIONS.has(fn)) {
142
+ reject(`attribute ${attr} on <${el}> must not call ${fn === "" ? "a bare (" : `${fn}()`}; only url(#id), colors and transforms are allowed`);
143
+ }
144
+ if (fn === "url") {
145
+ let j = i + 1;
146
+ while (j < value.length && isSpace(value.charAt(j)))
147
+ j += 1;
148
+ if (value.charAt(j) !== "#") {
149
+ reject(`attribute ${attr} on <${el}> may only reference url(#id) inside the document`);
150
+ }
151
+ }
152
+ }
153
+ }
154
+ /** `min-x min-y width height`, width and height > 0; undefined when malformed. */
155
+ function parseViewBox(v) {
156
+ if (v.length > VIEWBOX_MAX_CHARS)
157
+ return undefined;
158
+ const parts = v
159
+ .trim()
160
+ .split(/[\s,]+/)
161
+ .filter((p) => p !== "");
162
+ if (parts.length !== 4 || !parts.every((p) => VIEWBOX_NUMBER_RE.test(p)))
163
+ return undefined;
164
+ const n = parts.map(Number);
165
+ if (!n.every(Number.isFinite) || n[2] <= 0 || n[3] <= 0)
166
+ return undefined;
167
+ return n;
168
+ }
169
+ /** The serialized attributes of an allowed SVG element; rejects the forbidden ones. */
170
+ function attributesOf(tag, isRoot, usesXlink) {
171
+ const el = tag.local;
172
+ let out = "";
173
+ for (const a of Object.values(tag.attributes)) {
174
+ const lower = a.local.toLowerCase();
175
+ if (a.uri === XMLNS_NS || a.name === "xmlns")
176
+ continue;
177
+ let name;
178
+ if (a.uri === "") {
179
+ if (lower === "style")
180
+ reject(`attribute style on <${el}> is not allowed`);
181
+ if (lower.startsWith("on"))
182
+ reject(`event handler attribute ${a.name} on <${el}> is not allowed`);
183
+ if (isRoot && ROOT_DROPPED.has(a.local))
184
+ continue;
185
+ name = a.local;
186
+ }
187
+ else if (a.uri === XLINK_NS) {
188
+ usesXlink.value = true;
189
+ name = `xlink:${a.local}`;
190
+ }
191
+ else if (a.uri === XML_NS) {
192
+ if (!XML_ATTRS.has(a.local))
193
+ continue;
194
+ name = `xml:${a.local}`;
195
+ }
196
+ else {
197
+ // Editor metadata (inkscape:*, sodipodi:*, …) in foreign namespaces is dropped.
198
+ continue;
199
+ }
200
+ if (lower === "href" && !a.value.startsWith("#")) {
201
+ reject(`attribute ${name} on <${el}> must reference an element of the document (#id)`);
202
+ }
203
+ if (lower === "attributename") {
204
+ const target = (a.value.split(":").pop() ?? "").trim().toLowerCase();
205
+ if (target === "href" || target === "style" || target.startsWith("on")) {
206
+ reject(`<${el}> must not animate ${a.value}`);
207
+ }
208
+ }
209
+ checkValue(el, name, a.value);
210
+ out += ` ${name}="${escapeAttr(a.value)}"`;
211
+ }
212
+ return out;
213
+ }
214
+ /**
215
+ * Parses a logo SVG (UTF-8, ≤ {@link THEME_LIMITS}`.svgBytes`) with a strict, namespace-aware
216
+ * XML parser and re-serializes it. The root must be an `svg` element in the SVG namespace with a
217
+ * numeric `viewBox`; its `width`, `height` and `class` are dropped. Rejected: a DOCTYPE (and so
218
+ * any entity declaration), processing instructions, a non-UTF-8 encoding, elements outside the
219
+ * SVG allowlist (`script`, `foreignObject`, `style`, …) or in the XHTML namespace, `style` and
220
+ * `on*` attributes, `href` / `xlink:href` not starting with `#`, `javascript:` / `vbscript:` in
221
+ * any value, quotes or a backslash in attribute values, any function other than `url(#id)`, colors
222
+ * (`rgb`, `rgba`, `hsl`, `hsla`) and transforms (`translate`, `rotate`, `scale`, `matrix`,
223
+ * `skewX`, `skewY`), a viewBox longer than 128 characters, and animation of `href`, `style` or event
224
+ * handlers. Comments, the XML declaration and elements / attributes in other namespaces (editor
225
+ * metadata) are dropped; CDATA becomes escaped text. Never throws.
226
+ */
227
+ export function sanitizeThemeSvg(bytes) {
228
+ const r = sanitize(bytes);
229
+ return "error" in r ? r : { svg: r.svg };
230
+ }
231
+ /** {@link sanitizeThemeSvg} plus the root viewBox (for the favicon's squareness). */
232
+ function sanitize(bytes) {
233
+ if (bytes.length > THEME_LIMITS.svgBytes) {
234
+ return { error: `SVG is larger than ${THEME_LIMITS.svgBytes} bytes` };
235
+ }
236
+ let source;
237
+ try {
238
+ source = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
239
+ }
240
+ catch {
241
+ return { error: "SVG is not valid UTF-8" };
242
+ }
243
+ const parts = [];
244
+ const usesXlink = { value: false };
245
+ let xlinkAt = -1;
246
+ let depth = 0;
247
+ /** Depth at which a dropped foreign element started; 0 when not inside one. */
248
+ let skipFrom = 0;
249
+ /** The last emitted start tag still lacks its `>`. */
250
+ let openPending = false;
251
+ let sawRoot = false;
252
+ let rootBox = [0, 0, 0, 0];
253
+ const closePending = () => {
254
+ if (openPending)
255
+ parts.push(">");
256
+ openPending = false;
257
+ };
258
+ const parser = new SaxesParser({ xmlns: true, position: true });
259
+ parser.on("error", (e) => reject(`SVG is not valid XML: ${e.message}`));
260
+ parser.on("doctype", () => reject("SVG must not contain a DOCTYPE or entity declarations"));
261
+ parser.on("processinginstruction", () => reject("SVG must not contain processing instructions"));
262
+ parser.on("xmldecl", (d) => {
263
+ if (d.encoding !== undefined && !/^utf-?8$/i.test(d.encoding)) {
264
+ reject(`SVG must be encoded as UTF-8, not ${d.encoding}`);
265
+ }
266
+ });
267
+ parser.on("opentag", (tag) => {
268
+ depth += 1;
269
+ if (skipFrom > 0)
270
+ return;
271
+ const isRoot = !sawRoot;
272
+ sawRoot = true;
273
+ if (tag.uri === XHTML_NS)
274
+ reject(`XHTML element <${tag.name}> is not allowed`);
275
+ if (isRoot) {
276
+ if (tag.local !== "svg")
277
+ reject("the root element must be <svg>");
278
+ if (tag.uri !== SVG_NS)
279
+ reject(`the root <svg> must be in the SVG namespace (${SVG_NS})`);
280
+ const viewBox = Object.values(tag.attributes).find((a) => a.uri === "" && a.local === "viewBox");
281
+ if (viewBox === undefined)
282
+ reject("the root <svg> must have a viewBox");
283
+ else {
284
+ const box = parseViewBox(viewBox.value);
285
+ if (box === undefined) {
286
+ reject("the root <svg> viewBox must be four numbers with a positive width and height");
287
+ }
288
+ else
289
+ rootBox = box;
290
+ }
291
+ }
292
+ if (tag.uri !== SVG_NS) {
293
+ skipFrom = depth;
294
+ return;
295
+ }
296
+ if (!SVG_ELEMENTS.has(tag.local))
297
+ reject(`element <${tag.local}> is not allowed`);
298
+ closePending();
299
+ parts.push(`<${tag.local}`);
300
+ if (isRoot) {
301
+ parts.push(` xmlns="${SVG_NS}"`);
302
+ xlinkAt = parts.length;
303
+ parts.push("");
304
+ }
305
+ parts.push(attributesOf(tag, isRoot, usesXlink));
306
+ openPending = true;
307
+ });
308
+ parser.on("closetag", (tag) => {
309
+ depth -= 1;
310
+ if (skipFrom > 0) {
311
+ if (depth < skipFrom)
312
+ skipFrom = 0;
313
+ return;
314
+ }
315
+ if (openPending) {
316
+ parts.push("/>");
317
+ openPending = false;
318
+ }
319
+ else {
320
+ parts.push(`</${tag.local}>`);
321
+ }
322
+ });
323
+ const onText = (t) => {
324
+ if (depth === 0 || skipFrom > 0 || t === "")
325
+ return;
326
+ closePending();
327
+ parts.push(escapeText(t));
328
+ };
329
+ parser.on("text", onText);
330
+ parser.on("cdata", onText);
331
+ try {
332
+ parser.write(source).close();
333
+ }
334
+ catch (e) {
335
+ if (e instanceof SvgRejected)
336
+ return { error: e.message };
337
+ return { error: `SVG is not valid XML: ${e instanceof Error ? e.message : String(e)}` };
338
+ }
339
+ if (!sawRoot)
340
+ return { error: "the root element must be <svg>" };
341
+ if (usesXlink.value)
342
+ parts[xlinkAt] = ` xmlns:xlink="${XLINK_NS}"`;
343
+ return { svg: parts.join(""), viewBox: rootBox };
344
+ }
345
+ const startsWith = (bytes, sig) => bytes.length >= sig.length && sig.every((b, i) => bytes[i] === b);
346
+ const WOFF2_SIG = [0x77, 0x4f, 0x46, 0x32]; // "wOF2"
347
+ const PNG_SIG = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a];
348
+ const IHDR = [0x49, 0x48, 0x44, 0x52];
349
+ /** A woff2 font: the `wOF2` signature and at most {@link THEME_LIMITS}`.fontBytes`. */
350
+ export function checkWoff2(bytes) {
351
+ if (bytes.length > THEME_LIMITS.fontBytes) {
352
+ return `font is larger than ${THEME_LIMITS.fontBytes} bytes`;
353
+ }
354
+ if (!startsWith(bytes, WOFF2_SIG))
355
+ return "font is not a woff2 file (no wOF2 signature)";
356
+ return undefined;
357
+ }
358
+ /**
359
+ * A PNG logo: the PNG signature, an `IHDR` first chunk with a height of at least
360
+ * {@link THEME_LIMITS}`.pngMinHeight` pixels, and at most `maxBytes` (default
361
+ * {@link THEME_LIMITS}`.pngBytes`; an app icon allows {@link THEME_LIMITS}`.appIconBytes`).
362
+ */
363
+ export function checkPng(bytes, maxBytes = THEME_LIMITS.pngBytes) {
364
+ const r = readPng(bytes, maxBytes);
365
+ return typeof r === "string" ? r : undefined;
366
+ }
367
+ /** {@link checkPng}, returning the IHDR size when the PNG passes. */
368
+ function readPng(bytes, maxBytes) {
369
+ if (bytes.length > maxBytes) {
370
+ return `PNG is larger than ${maxBytes} bytes`;
371
+ }
372
+ if (!startsWith(bytes, PNG_SIG))
373
+ return "image is not a PNG file (no PNG signature)";
374
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
375
+ if (bytes.length < 24 || view.getUint32(8) !== 13 || !IHDR.every((b, i) => bytes[12 + i] === b)) {
376
+ return "PNG has no valid IHDR header";
377
+ }
378
+ const width = view.getUint32(16);
379
+ const height = view.getUint32(20);
380
+ if (width === 0)
381
+ return "PNG has a width of 0";
382
+ if (height < THEME_LIMITS.pngMinHeight) {
383
+ return `PNG must be at least ${THEME_LIMITS.pngMinHeight} px high, not ${height}`;
384
+ }
385
+ return { width, height };
386
+ }
387
+ /**
388
+ * Every asset a parsed theme names, in order: `fonts.<i>.file`, `logo.mark`, `logo.favicon`,
389
+ * `logo.illustration`, `logo.appIcon`, `logo.appIconMaskable`, `avatars.<i>.file`. `ref` is the
390
+ * path as written (an optional leading `./`). The one list every reader of theme assets uses (the
391
+ * checks, packing, the catalog and delivery), so a file the theme does not name is never read or
392
+ * served.
393
+ */
394
+ export function themeAssetRefs(theme) {
395
+ return refsWithKind(theme).map(({ field, ref }) => ({ field, ref }));
396
+ }
397
+ /** The kind each logo field is checked as, in {@link themeAssetRefs} order. */
398
+ const LOGO_ASSETS = [
399
+ ["mark", "image"],
400
+ ["favicon", "favicon"],
401
+ ["illustration", "image"],
402
+ ["appIcon", "appIcon"],
403
+ ["appIconMaskable", "appIcon"],
404
+ ];
405
+ /** {@link themeAssetRefs} with the kind each file is checked as. */
406
+ function refsWithKind(theme) {
407
+ const refs = [];
408
+ theme.fonts?.forEach((f, i) => {
409
+ refs.push({ field: `fonts.${i}.file`, ref: f.file, kind: "font" });
410
+ });
411
+ for (const [key, kind] of LOGO_ASSETS) {
412
+ const ref = theme.logo?.[key];
413
+ if (ref !== undefined)
414
+ refs.push({ field: `logo.${key}`, ref, kind });
415
+ }
416
+ theme.avatars?.forEach((a, i) => {
417
+ refs.push({ field: `avatars.${i}.file`, ref: a.file, kind: "avatar" });
418
+ });
419
+ return refs;
420
+ }
421
+ /**
422
+ * Resolves and checks the asset files of a parsed theme ({@link themeAssetRefs}), each by its
423
+ * kind: `fonts[].file` ({@link checkWoff2}); `logo.mark` and `logo.illustration` (`.svg` through
424
+ * {@link sanitizeThemeSvg}, `.png` through {@link checkPng}); `logo.favicon` and `avatars[].file`
425
+ * likewise and square (SVG viewBox or PNG width = height); `logo.appIcon` and
426
+ * `logo.appIconMaskable` PNG only, square, at least {@link THEME_LIMITS}`.appIconMinSize` px and at
427
+ * most {@link THEME_LIMITS}`.appIconBytes`. `files` holds the plugin's files keyed by their path
428
+ * without a leading `./`; the returned `assets` (the sanitized SVG bytes, the other files
429
+ * unchanged) use the same keys. Errors are `<field>: <reason>`, English; the total input size of
430
+ * the theme's distinct assets must stay within {@link THEME_LIMITS}`.assetsBytes`. That limit is
431
+ * per plugin, so a caller reading several themes also checks the sum over all of them (distinct
432
+ * paths).
433
+ */
434
+ export function validateThemeAssets(theme, files) {
435
+ const assets = new Map();
436
+ const errors = [];
437
+ const sizes = new Map();
438
+ const resolve = (field, ref, check) => {
439
+ const path = ref.replace(/^\.\//, "");
440
+ if (!isSafePackagePath(path)) {
441
+ errors.push(`${field}: ${ref} must be a relative path inside the plugin`);
442
+ return;
443
+ }
444
+ const bytes = files.get(path);
445
+ if (bytes === undefined) {
446
+ errors.push(`${field}: ${ref} not found in the plugin`);
447
+ return;
448
+ }
449
+ const r = check(bytes);
450
+ if (typeof r === "string") {
451
+ errors.push(`${field}: ${ref}: ${r}`);
452
+ return;
453
+ }
454
+ sizes.set(path, bytes.length);
455
+ assets.set(path, r);
456
+ };
457
+ const font = (b) => checkWoff2(b) ?? b;
458
+ const notSquare = (what, w, h) => `${what} must be square, not ${w} x ${h}`;
459
+ /** A logo image (`mark` rules); `square` names what must be square, or is undefined. */
460
+ const image = (ref, square) => (b) => {
461
+ if (/\.png$/i.test(ref)) {
462
+ const r = readPng(b, THEME_LIMITS.pngBytes);
463
+ if (typeof r === "string")
464
+ return r;
465
+ return square !== undefined && r.width !== r.height
466
+ ? notSquare(square, r.width, r.height)
467
+ : b;
468
+ }
469
+ if (!/\.svg$/i.test(ref))
470
+ return "must be a .svg or .png file";
471
+ const r = sanitize(b);
472
+ if ("error" in r)
473
+ return r.error;
474
+ const [, , w, h] = r.viewBox;
475
+ return square !== undefined && w !== h
476
+ ? notSquare(square, w, h)
477
+ : new TextEncoder().encode(r.svg);
478
+ };
479
+ const appIcon = (ref) => (b) => {
480
+ if (!/\.png$/i.test(ref))
481
+ return "must be a .png file";
482
+ const r = readPng(b, THEME_LIMITS.appIconBytes);
483
+ if (typeof r === "string")
484
+ return r;
485
+ if (r.width !== r.height)
486
+ return notSquare("app icon", r.width, r.height);
487
+ if (r.width < THEME_LIMITS.appIconMinSize) {
488
+ return `app icon must be at least ${THEME_LIMITS.appIconMinSize} px, not ${r.width}`;
489
+ }
490
+ return b;
491
+ };
492
+ for (const { field, ref, kind } of refsWithKind(theme)) {
493
+ const check = kind === "font"
494
+ ? font
495
+ : kind === "appIcon"
496
+ ? appIcon(ref)
497
+ : image(ref, kind === "favicon" ? "favicon" : kind === "avatar" ? "avatar" : undefined);
498
+ resolve(field, ref, check);
499
+ }
500
+ let total = 0;
501
+ for (const n of sizes.values())
502
+ total += n;
503
+ if (total > THEME_LIMITS.assetsBytes) {
504
+ errors.push(`theme assets are larger than ${THEME_LIMITS.assetsBytes} bytes in total (${total})`);
505
+ }
506
+ return { assets, errors };
507
+ }
@@ -0,0 +1,37 @@
1
+ export type ThemeScheme = "dark" | "light";
2
+ /** A theme scheme after merging its overrides onto the built-in values. */
3
+ export type MergedScheme = {
4
+ color: Record<string, string>;
5
+ shadow: Record<string, string>;
6
+ radius: Record<string, number>;
7
+ };
8
+ export type ReadabilityIssue = {
9
+ kind: "contrast" | "separation" | "separation-order" | "unevaluable";
10
+ /** `<fg> on <bg>` (with ` over <surface>` for a surface pair) or `<ground> on <surface>`. */
11
+ pair: string;
12
+ /** The measured value: contrast ratio, or OKLab lightness difference x100. */
13
+ ratio: number;
14
+ /** The floor it had to reach (for `separation-order`: the hover difference selected must beat). */
15
+ floor: number;
16
+ /** The composited colors compared, or for `unevaluable` the offending value. */
17
+ detail?: string;
18
+ };
19
+ /** WCAG 2 contrast ratio of two #RRGGBB colors. */
20
+ export declare function contrastRatio(fg: string, bg: string): number;
21
+ /** OKLab lightness (x100) of a #RRGGBB color. */
22
+ export declare function oklabL(hex: string): number;
23
+ /**
24
+ * The opaque #RRGGBB of `color` drawn over the opaque `ground`: a hex color passes through, an
25
+ * rgba(...) color is alpha-blended (per channel, rounded), anything else (color-mix) is undefined.
26
+ */
27
+ export declare function compositeOver(color: string, ground: string): string | undefined;
28
+ /**
29
+ * Evaluates the readability rules (every contrast pair and separation entry of the design tokens)
30
+ * on one merged scheme. An rgba(...) value is composited over the scheme's `bg` first, or over a
31
+ * pair's surface token; pairs with a color-mix value are skipped. `selected` must stand further
32
+ * from a surface than `hover` on the same surface. `rules` defaults to the built-in lists.
33
+ */
34
+ export declare function checkThemeReadability(_scheme: ThemeScheme, merged: MergedScheme, rules?: {
35
+ contrast: readonly (readonly [string, string, number, string?])[];
36
+ separation: readonly (readonly [string, string, number])[];
37
+ }): ReadabilityIssue[];
@@ -0,0 +1,145 @@
1
+ import { THEME_CONTRAST, THEME_SEPARATION } from "./theme-tokens.generated.js";
2
+ const HEX_RE = /^#[0-9A-F]{6}$/;
3
+ const LOOSE_HEX_RE = /^#[0-9A-Fa-f]{6}$/;
4
+ const RGBA_PARTS_RE = /^rgba\((\d{1,3}),(\d{1,3}),(\d{1,3}),(0|1|0?\.\d+)\)$/;
5
+ function luminance(hex) {
6
+ const ch = [1, 3, 5].map((i) => {
7
+ const c = Number.parseInt(hex.slice(i, i + 2), 16) / 255;
8
+ return c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;
9
+ });
10
+ return 0.2126 * ch[0] + 0.7152 * ch[1] + 0.0722 * ch[2];
11
+ }
12
+ /** WCAG 2 contrast ratio of two #RRGGBB colors. */
13
+ export function contrastRatio(fg, bg) {
14
+ const [hi, lo] = [luminance(fg), luminance(bg)].sort((x, y) => y - x);
15
+ return (hi + 0.05) / (lo + 0.05);
16
+ }
17
+ /** OKLab lightness (x100) of a #RRGGBB color. */
18
+ export function oklabL(hex) {
19
+ const [r, g, b] = [1, 3, 5].map((i) => {
20
+ const c = Number.parseInt(hex.slice(i, i + 2), 16) / 255;
21
+ return c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;
22
+ });
23
+ const l = Math.cbrt(0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b);
24
+ const m = Math.cbrt(0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b);
25
+ const s = Math.cbrt(0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b);
26
+ return (0.2104542553 * l + 0.793617785 * m - 0.0040720958 * s) * 100;
27
+ }
28
+ /**
29
+ * The opaque #RRGGBB of `color` drawn over the opaque `ground`: a hex color passes through, an
30
+ * rgba(...) color is alpha-blended (per channel, rounded), anything else (color-mix) is undefined.
31
+ */
32
+ export function compositeOver(color, ground) {
33
+ if (HEX_RE.test(color))
34
+ return color;
35
+ const m = RGBA_PARTS_RE.exec(color);
36
+ if (!m || !HEX_RE.test(ground))
37
+ return undefined;
38
+ const a = Number(m[4]);
39
+ const hex = [1, 2, 3]
40
+ .map((i) => {
41
+ const fg = Number(m[i]);
42
+ const bg = Number.parseInt(ground.slice(2 * i - 1, 2 * i + 1), 16);
43
+ return Math.round(fg * a + bg * (1 - a))
44
+ .toString(16)
45
+ .padStart(2, "0");
46
+ })
47
+ .join("");
48
+ return `#${hex.toUpperCase()}`;
49
+ }
50
+ /**
51
+ * Evaluates the readability rules (every contrast pair and separation entry of the design tokens)
52
+ * on one merged scheme. An rgba(...) value is composited over the scheme's `bg` first, or over a
53
+ * pair's surface token; pairs with a color-mix value are skipped. `selected` must stand further
54
+ * from a surface than `hover` on the same surface. `rules` defaults to the built-in lists.
55
+ */
56
+ export function checkThemeReadability(_scheme, merged, rules = { contrast: THEME_CONTRAST, separation: THEME_SEPARATION }) {
57
+ const issues = [];
58
+ // Hex case is not significant in CSS: evaluate `#rrggbb` like `#RRGGBB`.
59
+ const color = Object.fromEntries(Object.entries(merged.color).map(([n, v]) => [n, LOOSE_HEX_RE.test(v) ? v.toUpperCase() : v]));
60
+ const bg = color.bg ?? "";
61
+ // A value the rules read that cannot be evaluated is reported, never silently skipped. A
62
+ // color-mix value is legitimate (it derives) and is skipped; `bg` must be a plain hex ground.
63
+ const used = new Set(["bg"]);
64
+ for (const [fg, back, , surface] of rules.contrast) {
65
+ for (const n of [fg, back, surface])
66
+ if (n !== undefined)
67
+ used.add(n);
68
+ }
69
+ for (const [ground, surface] of rules.separation) {
70
+ used.add(ground);
71
+ used.add(surface);
72
+ }
73
+ for (const name of used) {
74
+ const v = color[name];
75
+ if (v === undefined || v.startsWith("color-mix("))
76
+ continue;
77
+ const ok = name === "bg" ? HEX_RE.test(v) : HEX_RE.test(v) || RGBA_PARTS_RE.test(v);
78
+ if (!ok) {
79
+ issues.push({ kind: "unevaluable", pair: name, ratio: Number.NaN, floor: 0, detail: v });
80
+ }
81
+ }
82
+ /** The opaque value of a surface token: an rgba surface is composited over `bg`. */
83
+ const surfaceOf = (name) => {
84
+ const raw = color[name];
85
+ return raw === undefined ? undefined : compositeOver(raw, bg);
86
+ };
87
+ for (const [fg, back, floor, surface] of rules.contrast) {
88
+ const ground = surfaceOf(surface ?? "bg");
89
+ if (ground === undefined)
90
+ continue;
91
+ const rawA = color[fg];
92
+ const rawB = color[back];
93
+ if (rawA === undefined || rawB === undefined)
94
+ continue;
95
+ const a = compositeOver(rawA, ground);
96
+ const b = compositeOver(rawB, ground);
97
+ if (a === undefined || b === undefined)
98
+ continue;
99
+ const ratio = contrastRatio(a, b);
100
+ if (ratio + 1e-9 < floor) {
101
+ const composited = a !== rawA || b !== rawB ? ` (rgba composited over ${surface ?? "bg"})` : "";
102
+ issues.push({
103
+ kind: "contrast",
104
+ pair: `${fg} on ${back}${surface === undefined ? "" : ` over ${surface}`}`,
105
+ ratio,
106
+ floor,
107
+ detail: `${a} on ${b}${composited}`,
108
+ });
109
+ }
110
+ }
111
+ const delta = new Map();
112
+ for (const [ground, surface, floor] of rules.separation) {
113
+ const s = surfaceOf(surface);
114
+ const raw = color[ground];
115
+ const g = s === undefined || raw === undefined ? undefined : compositeOver(raw, s);
116
+ if (s === undefined || g === undefined)
117
+ continue;
118
+ const d = Math.abs(oklabL(g) - oklabL(s));
119
+ delta.set(`${ground}@${surface}`, d);
120
+ if (d + 1e-9 < floor) {
121
+ issues.push({
122
+ kind: "separation",
123
+ pair: `${ground} on ${surface}`,
124
+ ratio: d,
125
+ floor,
126
+ detail: `${g} on ${s}`,
127
+ });
128
+ }
129
+ }
130
+ for (const [k, hover] of delta) {
131
+ if (!k.startsWith("hover@"))
132
+ continue;
133
+ const surface = k.slice("hover@".length);
134
+ const selected = delta.get(`selected@${surface}`);
135
+ if (selected !== undefined && selected <= hover) {
136
+ issues.push({
137
+ kind: "separation-order",
138
+ pair: `selected on ${surface}`,
139
+ ratio: selected,
140
+ floor: hover,
141
+ });
142
+ }
143
+ }
144
+ return issues;
145
+ }