qrdx 0.0.46 → 0.0.47

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 (206) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +353 -300
  3. package/dist/index.js +27 -7
  4. package/dist/index.js.map +1 -1
  5. package/dist/index.mjs +27 -7
  6. package/dist/index.mjs.map +1 -1
  7. package/dist/qr-code-canvas.js +12 -0
  8. package/dist/qr-code-canvas.js.map +1 -0
  9. package/dist/qr-code-canvas.mjs +12 -0
  10. package/dist/qr-code-canvas.mjs.map +1 -0
  11. package/dist/src/api.d.ts.map +1 -1
  12. package/dist/src/art-trace.d.ts +46 -0
  13. package/dist/src/art-trace.d.ts.map +1 -0
  14. package/dist/src/art.d.ts +138 -0
  15. package/dist/src/art.d.ts.map +1 -0
  16. package/dist/src/body-patterns.d.ts +34 -0
  17. package/dist/src/body-patterns.d.ts.map +1 -0
  18. package/dist/src/codegen.d.ts +5 -5
  19. package/dist/src/codegen.d.ts.map +1 -1
  20. package/dist/src/codeword-map.d.ts +40 -0
  21. package/dist/src/codeword-map.d.ts.map +1 -0
  22. package/dist/src/constants.d.ts +4 -7
  23. package/dist/src/constants.d.ts.map +1 -1
  24. package/dist/src/corner-dot.d.ts +3 -1
  25. package/dist/src/corner-dot.d.ts.map +1 -1
  26. package/dist/src/corner-eye.d.ts +5 -2
  27. package/dist/src/corner-eye.d.ts.map +1 -1
  28. package/dist/src/detection.d.ts.map +1 -1
  29. package/dist/src/download.d.ts +22 -5
  30. package/dist/src/download.d.ts.map +1 -1
  31. package/dist/src/eps.d.ts +62 -0
  32. package/dist/src/eps.d.ts.map +1 -0
  33. package/dist/src/frame-icons.d.ts +11 -0
  34. package/dist/src/frame-icons.d.ts.map +1 -0
  35. package/dist/src/frame-import.d.ts +61 -0
  36. package/dist/src/frame-import.d.ts.map +1 -0
  37. package/dist/src/frame-spec.d.ts +24 -0
  38. package/dist/src/frame-spec.d.ts.map +1 -0
  39. package/dist/src/frame-styles.d.ts +50 -0
  40. package/dist/src/frame-styles.d.ts.map +1 -0
  41. package/dist/src/frame.d.ts +126 -0
  42. package/dist/src/frame.d.ts.map +1 -0
  43. package/dist/src/frames/builtin.d.ts +8 -0
  44. package/dist/src/frames/builtin.d.ts.map +1 -0
  45. package/dist/src/frames/official.d.ts +18 -0
  46. package/dist/src/frames/official.d.ts.map +1 -0
  47. package/dist/src/helpers.d.ts +15 -2
  48. package/dist/src/helpers.d.ts.map +1 -1
  49. package/dist/src/index.d.ts +24 -13
  50. package/dist/src/index.d.ts.map +1 -1
  51. package/dist/src/logo-budget.d.ts +54 -0
  52. package/dist/src/logo-budget.d.ts.map +1 -0
  53. package/dist/src/logo-cleanup.d.ts +25 -0
  54. package/dist/src/logo-cleanup.d.ts.map +1 -0
  55. package/dist/src/logo.d.ts +28 -0
  56. package/dist/src/logo.d.ts.map +1 -0
  57. package/dist/src/print.d.ts +73 -0
  58. package/dist/src/print.d.ts.map +1 -0
  59. package/dist/src/qr-code-canvas.d.ts +13 -0
  60. package/dist/src/qr-code-canvas.d.ts.map +1 -0
  61. package/dist/src/qr-code.d.ts +4 -2
  62. package/dist/src/qr-code.d.ts.map +1 -1
  63. package/dist/src/qr-outline.d.ts +41 -0
  64. package/dist/src/qr-outline.d.ts.map +1 -0
  65. package/dist/src/qr-shape.d.ts +72 -0
  66. package/dist/src/qr-shape.d.ts.map +1 -0
  67. package/dist/src/scan-risk.d.ts +40 -0
  68. package/dist/src/scan-risk.d.ts.map +1 -0
  69. package/dist/src/scan-score.d.ts +154 -0
  70. package/dist/src/scan-score.d.ts.map +1 -0
  71. package/dist/src/shapes.d.ts +36 -0
  72. package/dist/src/shapes.d.ts.map +1 -0
  73. package/dist/src/silhouette.d.ts +28 -0
  74. package/dist/src/silhouette.d.ts.map +1 -0
  75. package/dist/src/utils/color.d.ts.map +1 -1
  76. package/dist/src/utils/fmt.d.ts +24 -0
  77. package/dist/src/utils/fmt.d.ts.map +1 -0
  78. package/dist/src/utils/paint.d.ts +80 -0
  79. package/dist/src/utils/paint.d.ts.map +1 -0
  80. package/dist/src/utils/parse-color.d.ts +21 -0
  81. package/dist/src/utils/parse-color.d.ts.map +1 -0
  82. package/dist/src/utils/path-data.d.ts +24 -0
  83. package/dist/src/utils/path-data.d.ts.map +1 -0
  84. package/dist/src/utils/png.d.ts +16 -0
  85. package/dist/src/utils/png.d.ts.map +1 -0
  86. package/dist/src/utils/polygon-clip.d.ts +26 -0
  87. package/dist/src/utils/polygon-clip.d.ts.map +1 -0
  88. package/dist/src/utils/print-shared.d.ts +20 -0
  89. package/dist/src/utils/print-shared.d.ts.map +1 -0
  90. package/dist/src/utils/svg-geometry.d.ts +49 -0
  91. package/dist/src/utils/svg-geometry.d.ts.map +1 -0
  92. package/dist/src/utils/svg-gradient.d.ts +59 -0
  93. package/dist/src/utils/svg-gradient.d.ts.map +1 -0
  94. package/dist/src/utils/svg-painter.d.ts +152 -0
  95. package/dist/src/utils/svg-painter.d.ts.map +1 -0
  96. package/dist/src/utils.d.ts +18 -2
  97. package/dist/src/utils.d.ts.map +1 -1
  98. package/dist/types/art.d.ts +64 -0
  99. package/dist/types/art.d.ts.map +1 -0
  100. package/dist/types/color.d.ts +125 -7
  101. package/dist/types/color.d.ts.map +1 -1
  102. package/dist/types/corner-dot.d.ts +52 -2
  103. package/dist/types/corner-dot.d.ts.map +1 -1
  104. package/dist/types/corner-eye.d.ts +43 -2
  105. package/dist/types/corner-eye.d.ts.map +1 -1
  106. package/dist/types/frame-spec.d.ts +3509 -0
  107. package/dist/types/frame-spec.d.ts.map +1 -0
  108. package/dist/types/frame.d.ts +68 -0
  109. package/dist/types/frame.d.ts.map +1 -0
  110. package/dist/types/image-pattern.d.ts +15 -1
  111. package/dist/types/image-pattern.d.ts.map +1 -1
  112. package/dist/types/index.d.ts +15 -9
  113. package/dist/types/index.d.ts.map +1 -1
  114. package/dist/types/index.js +6 -0
  115. package/dist/types/index.js.map +1 -0
  116. package/dist/types/index.mjs +6 -0
  117. package/dist/types/index.mjs.map +1 -0
  118. package/dist/types/qr.d.ts +1684 -4
  119. package/dist/types/qr.d.ts.map +1 -1
  120. package/dist/types/template.d.ts +2 -2
  121. package/dist/types/template.d.ts.map +1 -1
  122. package/package.json +68 -25
  123. package/src/api.tsx +67 -17
  124. package/src/art-trace.ts +554 -0
  125. package/src/art.tsx +2226 -0
  126. package/src/body-patterns.tsx +389 -0
  127. package/src/codegen.ts +10 -5
  128. package/src/codeword-map.ts +265 -0
  129. package/src/constants.ts +4 -8
  130. package/src/corner-dot.tsx +209 -33
  131. package/src/corner-eye.ts +328 -60
  132. package/src/detection.ts +5 -11
  133. package/src/download.tsx +123 -52
  134. package/src/eps.ts +701 -0
  135. package/src/frame-icons.ts +325 -0
  136. package/src/frame-import.ts +1198 -0
  137. package/src/frame-spec.ts +518 -0
  138. package/src/frame-styles.ts +1095 -0
  139. package/src/frame.tsx +630 -0
  140. package/src/frames/builtin/banner-bottom.json +58 -0
  141. package/src/frames/builtin/circle.json +81 -0
  142. package/src/frames/builtin/rounded-border.json +60 -0
  143. package/src/frames/builtin/ticket.json +51 -0
  144. package/src/frames/builtin.ts +20 -0
  145. package/src/frames/official/attendance.json +110 -0
  146. package/src/frames/official/audio-guide.json +95 -0
  147. package/src/frames/official/book-now.json +103 -0
  148. package/src/frames/official/check-in.json +110 -0
  149. package/src/frames/official/christmas.json +131 -0
  150. package/src/frames/official/donate.json +77 -0
  151. package/src/frames/official/event-ticket.json +77 -0
  152. package/src/frames/official/feedback-bubble.json +73 -0
  153. package/src/frames/official/follow-us.json +83 -0
  154. package/src/frames/official/get-the-app.json +107 -0
  155. package/src/frames/official/halloween.json +80 -0
  156. package/src/frames/official/new-year.json +94 -0
  157. package/src/frames/official/order-at-table.json +86 -0
  158. package/src/frames/official/product-info.json +119 -0
  159. package/src/frames/official/register-product.json +77 -0
  160. package/src/frames/official/review-us.json +127 -0
  161. package/src/frames/official/rsvp-card.json +112 -0
  162. package/src/frames/official/save-contact.json +117 -0
  163. package/src/frames/official/scan-to-pay.json +94 -0
  164. package/src/frames/official/shop-window.json +81 -0
  165. package/src/frames/official/sign-rider.json +81 -0
  166. package/src/frames/official/table-tent.json +75 -0
  167. package/src/frames/official/wifi-card.json +89 -0
  168. package/src/frames/official/winter.json +142 -0
  169. package/src/frames/official.ts +77 -0
  170. package/src/helpers.ts +168 -11
  171. package/src/index.tsx +141 -172
  172. package/src/logo-budget.ts +226 -0
  173. package/src/logo-cleanup.ts +146 -0
  174. package/src/logo.tsx +137 -0
  175. package/src/print.ts +794 -0
  176. package/src/qr-code-canvas.tsx +241 -0
  177. package/src/qr-code.tsx +51 -16
  178. package/src/qr-outline.ts +511 -0
  179. package/src/qr-shape.ts +255 -0
  180. package/src/scan-risk.ts +197 -0
  181. package/src/scan-score.ts +1629 -0
  182. package/src/shapes.ts +169 -0
  183. package/src/silhouette.ts +334 -0
  184. package/src/utils/color.ts +10 -1
  185. package/src/utils/fmt.ts +59 -0
  186. package/src/utils/paint.ts +317 -0
  187. package/src/utils/parse-color.ts +135 -0
  188. package/src/utils/path-data.ts +182 -0
  189. package/src/utils/png.ts +175 -0
  190. package/src/utils/polygon-clip.ts +163 -0
  191. package/src/utils/print-shared.ts +74 -0
  192. package/src/utils/svg-geometry.ts +838 -0
  193. package/src/utils/svg-gradient.ts +407 -0
  194. package/src/utils/svg-painter.ts +946 -0
  195. package/src/utils.tsx +794 -385
  196. package/types/art.ts +74 -0
  197. package/types/color.ts +132 -12
  198. package/types/corner-dot.ts +41 -4
  199. package/types/corner-eye.ts +31 -4
  200. package/types/frame-spec.ts +748 -0
  201. package/types/frame.ts +67 -0
  202. package/types/image-pattern.ts +15 -0
  203. package/types/index.ts +106 -4
  204. package/types/qr.ts +180 -2
  205. package/types/template.ts +2 -2
  206. package/dist/cli.js +0 -4319
@@ -0,0 +1,1198 @@
1
+ /** biome-ignore-all lint/style/noMagicNumbers: import limits */
2
+ // Converts an uploaded SVG into a frame spec (types/frame-spec.ts), for a
3
+ // server to call. The SVG itself is never kept: only plain filled shapes
4
+ // survive, as path data re-written from parsed numbers, with colors as hex.
5
+ //
6
+ // Defences, in order:
7
+ // - size cap, and no DOCTYPE, entity, or processing instruction other than
8
+ // the XML declaration (no entity expansion, no external DTD);
9
+ // - a linear well-formedness scan before the engine's SVG reader runs, so
10
+ // hostile markup can't make its regular expressions backtrack; it also
11
+ // caps the element count and nesting depth;
12
+ // - an allow-list walk: svg, g, path, rect, circle, ellipse, polygon,
13
+ // polyline and line are read for geometry and fill/stroke color only.
14
+ // script, style, foreignObject, image, use, text, filters, masks, clip
15
+ // paths, patterns, animation and unknown elements are dropped; no
16
+ // attribute is ever copied, so on* handlers, href / xlink:href and
17
+ // url(...) references go with them (internal gradients are flattened to
18
+ // their first color);
19
+ // - segment, shape and color caps, and the result must pass frameSpecSchema.
20
+ // Everything dropped is reported as a warning.
21
+ import {
22
+ FRAME_SPEC_KIND,
23
+ FRAME_SPEC_LIMITS,
24
+ FRAME_SPEC_VERSION,
25
+ type FrameSpec,
26
+ frameSpecSchema,
27
+ } from "../types/frame-spec";
28
+ import { fmt } from "./utils/fmt";
29
+ import { parseColor } from "./utils/parse-color";
30
+ import {
31
+ type ClipBox,
32
+ clipPolygon,
33
+ flattenSegments,
34
+ segmentsBounds,
35
+ } from "./utils/polygon-clip";
36
+ import {
37
+ applyMatrix,
38
+ ellipseSegments,
39
+ type Matrix,
40
+ multiply,
41
+ parseNumbers,
42
+ parsePathData,
43
+ parseSvgMarkup,
44
+ parseTransform,
45
+ rectSegments,
46
+ type Segment,
47
+ type SvgNode,
48
+ } from "./utils/svg-geometry";
49
+ import { readStyle } from "./utils/svg-painter";
50
+
51
+ export const FRAME_IMPORT_LIMITS = {
52
+ /** Largest SVG accepted, in UTF-8 bytes */
53
+ maxBytes: 200_000,
54
+ maxElements: 500,
55
+ maxDepth: 16,
56
+ /** Segments read from the SVG, before simplifying */
57
+ maxInputSegments: 4000,
58
+ /** Distinct fill colors kept (closer ones are merged) */
59
+ maxColors: 8,
60
+ /** The artboard's longer side, in spec units */
61
+ artboardSide: 1000,
62
+ /** Decimals kept in the spec's path data */
63
+ decimals: 1,
64
+ /** Default light padding around the code, as a share of its size */
65
+ padding: 0.06,
66
+ } as const;
67
+
68
+ export interface FrameImportWarning {
69
+ code: string;
70
+ message: string;
71
+ count: number;
72
+ }
73
+
74
+ export interface FrameImportColor {
75
+ color: string;
76
+ /** What the color became: a theme token or a fixed color */
77
+ ref: "frame" | "accent" | "fixed";
78
+ /** Shapes painted with it */
79
+ shapes: number;
80
+ }
81
+
82
+ export interface FrameImportOptions {
83
+ /**
84
+ * Where the code goes, in the SVG's own units (its viewBox). By default a
85
+ * rect with the id "qr" (or "qr-code", "qrdx-qr") marks it and isn't
86
+ * drawn; without one, the code is centered at 60% of the shorter side.
87
+ */
88
+ qr?: { x: number; y: number; size: number };
89
+ /** Light padding around the code, as a share of its size (default 0.06) */
90
+ padding?: number;
91
+ }
92
+
93
+ export type FrameImportResult =
94
+ | {
95
+ ok: true;
96
+ spec: FrameSpec;
97
+ warnings: FrameImportWarning[];
98
+ palette: FrameImportColor[];
99
+ }
100
+ | { ok: false; error: string; warnings: FrameImportWarning[] };
101
+
102
+ class ImportError extends Error {}
103
+
104
+ // ── Warnings ───────────────────────────────────────────────────────────────
105
+
106
+ const WARNINGS: Record<string, (count: number) => string> = {
107
+ script: (n) => `Removed ${plural(n, "script")}`,
108
+ style: (n) =>
109
+ `Removed ${plural(n, "style sheet")}: colors set with CSS classes are lost. Export with presentation attributes (Illustrator: Styling → Presentation Attributes)`,
110
+ "foreign-object": (n) => `Removed ${plural(n, "foreignObject element")}`,
111
+ image: (n) => `Removed ${plural(n, "image")}: frames are vector shapes only`,
112
+ use: (n) =>
113
+ `Removed ${plural(n, "<use> reference")}: ungroup or detach symbols before exporting`,
114
+ text: (n) =>
115
+ `Removed ${plural(n, "text element")}: add text as labels in the frame editor`,
116
+ effects: (n) => `Removed ${plural(n, "filter, mask, clip path or pattern")}`,
117
+ animation: (n) => `Removed ${plural(n, "animation")}`,
118
+ unknown: (n) => `Removed ${plural(n, "unsupported element")}`,
119
+ "nested-svg": (n) => `Removed ${plural(n, "nested <svg>")}: flatten it first`,
120
+ handlers: (n) => `Removed ${plural(n, "event handler attribute")}`,
121
+ links: (n) => `Removed ${plural(n, "link")} (href)`,
122
+ "external-paint": (n) =>
123
+ `Removed ${plural(n, "fill or stroke")} that referenced something outside the file`,
124
+ gradient: (n) =>
125
+ `Flattened ${plural(n, "gradient")} to its first color: add gradients in the frame editor`,
126
+ opacity: (n) =>
127
+ `Made ${plural(n, "semi-transparent shape")} opaque (print files have no transparency)`,
128
+ "invalid-paint": (n) =>
129
+ `${plural(n, "color")} couldn't be read and fell back to the parent color`,
130
+ stroke: (n) =>
131
+ `Removed ${plural(n, "stroke")} on paths, polygons or polylines: outline strokes before exporting (Figma: Outline stroke)`,
132
+ dash: (n) => `Drew ${plural(n, "dashed stroke")} as solid`,
133
+ clipped: (n) => `Cut ${plural(n, "shape")} at the edge of the artboard`,
134
+ outside: (n) => `Removed ${plural(n, "shape")} outside the artboard`,
135
+ colors: (n) =>
136
+ `Merged ${plural(n, "color")} with similar ones (${FRAME_IMPORT_LIMITS.maxColors} at most)`,
137
+ "qr-placed": () =>
138
+ 'No QR placeholder found (a rect with id "qr"): the code was centered; place it in the frame editor',
139
+ };
140
+
141
+ function plural(count: number, noun: string): string {
142
+ return `${count} ${noun}${count === 1 ? "" : "s"}`;
143
+ }
144
+
145
+ class Warnings {
146
+ private readonly counts = new Map<string, number>();
147
+
148
+ add(code: keyof typeof WARNINGS, count = 1) {
149
+ this.counts.set(code, (this.counts.get(code) ?? 0) + count);
150
+ }
151
+
152
+ list(): FrameImportWarning[] {
153
+ return [...this.counts].map(([code, count]) => ({
154
+ code,
155
+ count,
156
+ message: (WARNINGS[code] as (count: number) => string)(count),
157
+ }));
158
+ }
159
+ }
160
+
161
+ // ── Markup checks ──────────────────────────────────────────────────────────
162
+
163
+ const XML_DECLARATION = /^\s*<\?xml\s[^?>]*\?>/;
164
+ const TAG_NAME = /[A-Za-z_][\w:.-]*/y;
165
+ const CLOSE_TAG = /<\/([A-Za-z_][\w:.-]*)\s*>/y;
166
+
167
+ // Attributes and tag ends are read one character class at a time, so no
168
+ // pattern can backtrack. The steps accept exactly what
169
+ // /\s+[A-Za-z_:][\w:.-]*\s*=\s*(?:"[^"<]*"|'[^'<]*')/y and /\s*(\/?)>/y did.
170
+ const SPACES = /\s*/y;
171
+ const ATTRIBUTE_NAME = /[A-Za-z_:][\w:.-]*/y;
172
+ const DOUBLE_QUOTED = /[^"<]*/y;
173
+ const SINGLE_QUOTED = /[^'<]*/y;
174
+
175
+ /** Where sticky `pattern` stops matching at `from` (`from` when it doesn't). */
176
+ function skip(pattern: RegExp, markup: string, from: number): number {
177
+ pattern.lastIndex = from;
178
+ return pattern.test(markup) ? pattern.lastIndex : from;
179
+ }
180
+
181
+ /** The end of the ` name="value"` attribute at `from`, or -1. */
182
+ function attributeEnd(markup: string, from: number): number {
183
+ const nameStart = skip(SPACES, markup, from);
184
+ const nameEnd = skip(ATTRIBUTE_NAME, markup, nameStart);
185
+ if (nameStart === from || nameEnd === nameStart) {
186
+ return -1;
187
+ }
188
+ const equals = skip(SPACES, markup, nameEnd);
189
+ if (markup[equals] !== "=") {
190
+ return -1;
191
+ }
192
+ const open = skip(SPACES, markup, equals + 1);
193
+ const quote = markup[open];
194
+ if (quote !== '"' && quote !== "'") {
195
+ return -1;
196
+ }
197
+ const value = quote === '"' ? DOUBLE_QUOTED : SINGLE_QUOTED;
198
+ const close = skip(value, markup, open + 1);
199
+ return markup[close] === quote ? close + 1 : -1;
200
+ }
201
+
202
+ /** The end of the ">" or "/>" after optional whitespace at `from`. */
203
+ function tagEnd(
204
+ markup: string,
205
+ from: number
206
+ ): { end: number; selfClosing: boolean } | null {
207
+ const at = skip(SPACES, markup, from);
208
+ if (markup[at] === ">") {
209
+ return { end: at + 1, selfClosing: false };
210
+ }
211
+ return markup.startsWith("/>", at)
212
+ ? { end: at + 2, selfClosing: true }
213
+ : null;
214
+ }
215
+
216
+ /**
217
+ * Linear well-formedness scan: tags, attributes (quoted values without
218
+ * "<"), comments and CDATA must be complete, closing tags must match, and
219
+ * the element count and depth stay within the limits. Returns the first
220
+ * element's name.
221
+ */
222
+ function scanMarkup(markup: string): string {
223
+ const stack: string[] = [];
224
+ let elements = 0;
225
+ let first = "";
226
+ let index = 0;
227
+ while (index < markup.length) {
228
+ const open = markup.indexOf("<", index);
229
+ if (open < 0) {
230
+ break;
231
+ }
232
+ index = open;
233
+ if (markup.startsWith("<!--", index)) {
234
+ const end = markup.indexOf("-->", index + 4);
235
+ if (end < 0) {
236
+ throw new ImportError("The SVG has an unclosed comment");
237
+ }
238
+ index = end + 3;
239
+ continue;
240
+ }
241
+ if (markup.startsWith("<![CDATA[", index)) {
242
+ const end = markup.indexOf("]]>", index + 9);
243
+ if (end < 0) {
244
+ throw new ImportError("The SVG has an unclosed CDATA section");
245
+ }
246
+ index = end + 3;
247
+ continue;
248
+ }
249
+ if (markup.startsWith("<?", index)) {
250
+ const end = markup.indexOf("?>", index + 2);
251
+ if (end < 0) {
252
+ throw new ImportError("The SVG has an unclosed declaration");
253
+ }
254
+ index = end + 2;
255
+ continue;
256
+ }
257
+ if (markup.startsWith("<!", index)) {
258
+ throw new ImportError("DOCTYPE and other declarations are not allowed");
259
+ }
260
+ if (markup[index + 1] === "/") {
261
+ CLOSE_TAG.lastIndex = index;
262
+ const close = CLOSE_TAG.exec(markup);
263
+ if (!close) {
264
+ throw new ImportError("The SVG has a malformed closing tag");
265
+ }
266
+ if (stack.pop() !== close[1]) {
267
+ throw new ImportError(`The SVG closes <${close[1]}> out of order`);
268
+ }
269
+ index = CLOSE_TAG.lastIndex;
270
+ continue;
271
+ }
272
+ TAG_NAME.lastIndex = index + 1;
273
+ const name = TAG_NAME.exec(markup);
274
+ if (!name) {
275
+ throw new ImportError("The SVG has a malformed tag");
276
+ }
277
+ let position = TAG_NAME.lastIndex;
278
+ for (
279
+ let next = attributeEnd(markup, position);
280
+ next >= 0;
281
+ next = attributeEnd(markup, position)
282
+ ) {
283
+ position = next;
284
+ }
285
+ const end = tagEnd(markup, position);
286
+ if (!end) {
287
+ throw new ImportError(
288
+ `The SVG has a malformed <${name[0]}> tag (attributes must be quoted and may not contain "<")`
289
+ );
290
+ }
291
+ elements++;
292
+ if (elements > FRAME_IMPORT_LIMITS.maxElements) {
293
+ throw new ImportError(
294
+ `The SVG has more than ${FRAME_IMPORT_LIMITS.maxElements} elements`
295
+ );
296
+ }
297
+ if (!first) {
298
+ first = name[0];
299
+ }
300
+ if (!end.selfClosing) {
301
+ stack.push(name[0]);
302
+ if (stack.length > FRAME_IMPORT_LIMITS.maxDepth) {
303
+ throw new ImportError(
304
+ `The SVG nests elements more than ${FRAME_IMPORT_LIMITS.maxDepth} deep`
305
+ );
306
+ }
307
+ }
308
+ index = end.end;
309
+ }
310
+ if (stack.length > 0) {
311
+ throw new ImportError(`The SVG doesn't close <${stack.at(-1)}>`);
312
+ }
313
+ return first;
314
+ }
315
+
316
+ function checkMarkup(svg: unknown): string {
317
+ if (typeof svg !== "string") {
318
+ throw new ImportError("Expected SVG markup as a string");
319
+ }
320
+ const bytes = new TextEncoder().encode(svg).length;
321
+ if (bytes > FRAME_IMPORT_LIMITS.maxBytes) {
322
+ throw new ImportError(
323
+ `The SVG is ${Math.ceil(bytes / 1000)} KB; the limit is ${FRAME_IMPORT_LIMITS.maxBytes / 1000} KB`
324
+ );
325
+ }
326
+ if (/<!(?:DOCTYPE|ENTITY|ATTLIST|ELEMENT|NOTATION)/i.test(svg)) {
327
+ throw new ImportError("DOCTYPE and entity declarations are not allowed");
328
+ }
329
+ const body = svg.replace(XML_DECLARATION, "");
330
+ if (body.includes("<?")) {
331
+ throw new ImportError(
332
+ "Processing instructions (such as xml-stylesheet) are not allowed"
333
+ );
334
+ }
335
+ if (scanMarkup(body) !== "svg") {
336
+ throw new ImportError("The file must start with an <svg> element");
337
+ }
338
+ return body;
339
+ }
340
+
341
+ // ── Paint ──────────────────────────────────────────────────────────────────
342
+
343
+ interface State {
344
+ matrix: Matrix;
345
+ fill: string;
346
+ fillRule: "nonzero" | "evenodd";
347
+ stroke: string;
348
+ strokeWidth: number;
349
+ color: string;
350
+ opacity: number;
351
+ }
352
+
353
+ const toHex = (value: number) =>
354
+ Math.round(Math.min(255, Math.max(0, value)))
355
+ .toString(16)
356
+ .padStart(2, "0");
357
+
358
+ function cleanValue(value: string | undefined): string | undefined {
359
+ const clean = value?.replace(/!important/i, "").trim();
360
+ return clean === "" || clean === "inherit" ? undefined : clean;
361
+ }
362
+
363
+ /** A fill or stroke as an opaque hex color, or null for none. */
364
+ function resolvePaint(
365
+ value: string,
366
+ state: State,
367
+ gradients: Map<string, string>,
368
+ warnings: Warnings
369
+ ): string | null {
370
+ const paint = value.trim();
371
+ if (paint === "none" || paint === "transparent") {
372
+ return null;
373
+ }
374
+ if (/^url\(/i.test(paint)) {
375
+ const id = /^url\(\s*['"]?#([^)'"\s]+)['"]?\s*\)/i.exec(paint)?.[1];
376
+ const first = id ? gradients.get(id) : undefined;
377
+ if (!first) {
378
+ warnings.add("external-paint");
379
+ return null;
380
+ }
381
+ warnings.add("gradient");
382
+ return resolvePaint(first, state, gradients, warnings);
383
+ }
384
+ const color = parseColor(paint === "currentColor" ? state.color : paint);
385
+ if (!color) {
386
+ warnings.add("invalid-paint");
387
+ return null;
388
+ }
389
+ if (color.a <= 0) {
390
+ return null;
391
+ }
392
+ return `#${toHex(color.r)}${toHex(color.g)}${toHex(color.b)}`;
393
+ }
394
+
395
+ /** First stop color of every gradient with an id (following href once). */
396
+ function collectGradients(root: SvgNode): Map<string, string> {
397
+ const nodes = new Map<string, SvgNode>();
398
+ const visit = (node: SvgNode) => {
399
+ if (
400
+ (node.name === "linearGradient" || node.name === "radialGradient") &&
401
+ node.attrs.id
402
+ ) {
403
+ nodes.set(node.attrs.id, node);
404
+ }
405
+ for (const child of node.children) {
406
+ visit(child);
407
+ }
408
+ };
409
+ visit(root);
410
+ const out = new Map<string, string>();
411
+ for (const [id, node] of nodes) {
412
+ let stop = node.children.find((child) => child.name === "stop");
413
+ if (!stop) {
414
+ const ref = (node.attrs.href ?? node.attrs["xlink:href"])?.match(
415
+ /^#(.+)$/
416
+ )?.[1];
417
+ stop = ref
418
+ ? nodes.get(ref)?.children.find((child) => child.name === "stop")
419
+ : undefined;
420
+ }
421
+ const color = stop && cleanValue(readStyle(stop, "stop-color"));
422
+ if (color) {
423
+ out.set(id, color);
424
+ }
425
+ }
426
+ return out;
427
+ }
428
+
429
+ // ── Geometry ───────────────────────────────────────────────────────────────
430
+
431
+ interface Shape {
432
+ segments: Segment[];
433
+ fill: string;
434
+ fillRule: "nonzero" | "evenodd";
435
+ }
436
+
437
+ function transformSegments(segments: Segment[], m: Matrix): Segment[] {
438
+ return segments.map((segment) => {
439
+ if (segment.op === "Z") {
440
+ return segment;
441
+ }
442
+ if (segment.op === "C") {
443
+ const [x1, y1] = applyMatrix(m, segment.x1, segment.y1);
444
+ const [x2, y2] = applyMatrix(m, segment.x2, segment.y2);
445
+ const [x, y] = applyMatrix(m, segment.x, segment.y);
446
+ return { op: "C", x1, y1, x2, y2, x, y };
447
+ }
448
+ const [x, y] = applyMatrix(m, segment.x, segment.y);
449
+ return { op: segment.op, x, y };
450
+ });
451
+ }
452
+
453
+ function signedArea(points: [number, number][]): number {
454
+ let sum = 0;
455
+ points.forEach(([x, y], i) => {
456
+ const [nx, ny] = points[(i + 1) % points.length] as [number, number];
457
+ sum += x * ny - nx * y;
458
+ });
459
+ return sum / 2;
460
+ }
461
+
462
+ function polygonSegments(points: [number, number][]): Segment[] {
463
+ if (points.length < 3) {
464
+ return [];
465
+ }
466
+ return [
467
+ ...points.map(([x, y], i): Segment => ({ op: i === 0 ? "M" : "L", x, y })),
468
+ { op: "Z" },
469
+ ];
470
+ }
471
+
472
+ const isNumber = (value: number) => Number.isFinite(value);
473
+
474
+ function num(node: SvgNode, name: string, fallback = 0): number {
475
+ const value = Number.parseFloat(node.attrs[name] ?? "");
476
+ return isNumber(value) ? value : fallback;
477
+ }
478
+
479
+ /** Fill outline of a shape element, in its own coordinates. */
480
+ function fillGeometry(node: SvgNode): Segment[] {
481
+ switch (node.name) {
482
+ case "path":
483
+ return parsePathData(node.attrs.d ?? "");
484
+ case "rect": {
485
+ const rx = node.attrs.rx ?? node.attrs.ry;
486
+ const ry = node.attrs.ry ?? node.attrs.rx;
487
+ return rectSegments(
488
+ num(node, "x"),
489
+ num(node, "y"),
490
+ num(node, "width"),
491
+ num(node, "height"),
492
+ Number.parseFloat(rx ?? "0") || 0,
493
+ Number.parseFloat(ry ?? "0") || 0
494
+ );
495
+ }
496
+ case "circle": {
497
+ const r = num(node, "r");
498
+ return ellipseSegments(num(node, "cx"), num(node, "cy"), r, r);
499
+ }
500
+ case "ellipse":
501
+ return ellipseSegments(
502
+ num(node, "cx"),
503
+ num(node, "cy"),
504
+ num(node, "rx"),
505
+ num(node, "ry")
506
+ );
507
+ case "polygon":
508
+ case "polyline": {
509
+ const values = parseNumbers(node.attrs.points);
510
+ const points: [number, number][] = [];
511
+ for (let i = 0; i + 1 < values.length; i += 2) {
512
+ points.push([values[i] as number, values[i + 1] as number]);
513
+ }
514
+ return polygonSegments(points);
515
+ }
516
+ default:
517
+ return [];
518
+ }
519
+ }
520
+
521
+ /**
522
+ * Stroke outline (even-odd) for the elements whose stroke has a simple
523
+ * outline: rects, circles, ellipses and lines. Null for the rest.
524
+ */
525
+ function strokeGeometry(node: SvgNode, width: number): Segment[] | null {
526
+ const half = width / 2;
527
+ switch (node.name) {
528
+ case "rect": {
529
+ const x = num(node, "x");
530
+ const y = num(node, "y");
531
+ const w = num(node, "width");
532
+ const h = num(node, "height");
533
+ const r = Number.parseFloat(node.attrs.rx ?? node.attrs.ry ?? "0") || 0;
534
+ const outer = rectSegments(
535
+ x - half,
536
+ y - half,
537
+ w + width,
538
+ h + width,
539
+ r > 0 ? r + half : 0,
540
+ r > 0 ? r + half : 0
541
+ );
542
+ if (w <= width || h <= width) {
543
+ return outer;
544
+ }
545
+ const innerRadius = Math.max(r - half, 0);
546
+ return [
547
+ ...outer,
548
+ ...rectSegments(
549
+ x + half,
550
+ y + half,
551
+ w - width,
552
+ h - width,
553
+ innerRadius,
554
+ innerRadius
555
+ ),
556
+ ];
557
+ }
558
+ case "circle":
559
+ case "ellipse": {
560
+ const cx = num(node, "cx");
561
+ const cy = num(node, "cy");
562
+ const rx = node.name === "circle" ? num(node, "r") : num(node, "rx");
563
+ const ry = node.name === "circle" ? num(node, "r") : num(node, "ry");
564
+ const outer = ellipseSegments(cx, cy, rx + half, ry + half);
565
+ if (rx <= half || ry <= half) {
566
+ return outer;
567
+ }
568
+ return [...outer, ...ellipseSegments(cx, cy, rx - half, ry - half)];
569
+ }
570
+ case "line": {
571
+ const [x1, y1, x2, y2] = ["x1", "y1", "x2", "y2"].map((name) =>
572
+ num(node, name)
573
+ ) as [number, number, number, number];
574
+ const length = Math.hypot(x2 - x1, y2 - y1);
575
+ if (length === 0) {
576
+ return [];
577
+ }
578
+ const nx = (-(y2 - y1) / length) * half;
579
+ const ny = ((x2 - x1) / length) * half;
580
+ const quad: [number, number][] = [
581
+ [x1 + nx, y1 + ny],
582
+ [x2 + nx, y2 + ny],
583
+ [x2 - nx, y2 - ny],
584
+ [x1 - nx, y1 - ny],
585
+ ];
586
+ return polygonSegments(signedArea(quad) < 0 ? quad.reverse() : quad);
587
+ }
588
+ default:
589
+ return null;
590
+ }
591
+ }
592
+
593
+ // ── Walk ───────────────────────────────────────────────────────────────────
594
+
595
+ const SHAPES = new Set([
596
+ "path",
597
+ "rect",
598
+ "circle",
599
+ "ellipse",
600
+ "polygon",
601
+ "polyline",
602
+ "line",
603
+ ]);
604
+ const SILENT = new Set([
605
+ "defs",
606
+ "linearGradient",
607
+ "radialGradient",
608
+ "stop",
609
+ "title",
610
+ "desc",
611
+ "metadata",
612
+ ]);
613
+ const DROPPED: Record<string, keyof typeof WARNINGS> = {
614
+ script: "script",
615
+ style: "style",
616
+ foreignObject: "foreign-object",
617
+ image: "image",
618
+ feImage: "image",
619
+ use: "use",
620
+ text: "text",
621
+ tspan: "text",
622
+ textPath: "text",
623
+ filter: "effects",
624
+ mask: "effects",
625
+ clipPath: "effects",
626
+ pattern: "effects",
627
+ marker: "effects",
628
+ symbol: "effects",
629
+ animate: "animation",
630
+ animateMotion: "animation",
631
+ animateTransform: "animation",
632
+ set: "animation",
633
+ };
634
+
635
+ const QR_PLACEHOLDER = /^(?:qrdx[-_ ]?)?qr(?:[-_ ]?code)?$/i;
636
+
637
+ interface Collected {
638
+ shapes: Shape[];
639
+ qrBox: ClipBox | null;
640
+ segments: number;
641
+ }
642
+
643
+ function checkAttributes(node: SvgNode, warnings: Warnings) {
644
+ for (const name of Object.keys(node.attrs)) {
645
+ const lower = name.toLowerCase();
646
+ if (lower.startsWith("on")) {
647
+ warnings.add("handlers");
648
+ } else if (lower === "href" || lower === "xlink:href") {
649
+ if (node.name !== "linearGradient" && node.name !== "radialGradient") {
650
+ warnings.add("links");
651
+ }
652
+ } else if (
653
+ lower === "filter" ||
654
+ lower === "mask" ||
655
+ lower === "clip-path"
656
+ ) {
657
+ warnings.add("effects");
658
+ }
659
+ }
660
+ }
661
+
662
+ function walk(
663
+ node: SvgNode,
664
+ parent: State,
665
+ gradients: Map<string, string>,
666
+ warnings: Warnings,
667
+ out: Collected
668
+ ) {
669
+ checkAttributes(node, warnings);
670
+ if (
671
+ cleanValue(readStyle(node, "display")) === "none" ||
672
+ cleanValue(readStyle(node, "visibility")) === "hidden"
673
+ ) {
674
+ return;
675
+ }
676
+ const opacity = Number.parseFloat(readStyle(node, "opacity") ?? "1");
677
+ const fillRule = cleanValue(readStyle(node, "fill-rule"));
678
+ const strokeWidth = Number.parseFloat(
679
+ cleanValue(readStyle(node, "stroke-width")) ?? ""
680
+ );
681
+ const state: State = {
682
+ matrix: multiply(parent.matrix, parseTransform(node.attrs.transform)),
683
+ fill: cleanValue(readStyle(node, "fill")) ?? parent.fill,
684
+ fillRule:
685
+ fillRule === "evenodd" || fillRule === "nonzero"
686
+ ? fillRule
687
+ : parent.fillRule,
688
+ stroke: cleanValue(readStyle(node, "stroke")) ?? parent.stroke,
689
+ strokeWidth:
690
+ isNumber(strokeWidth) && strokeWidth >= 0
691
+ ? strokeWidth
692
+ : parent.strokeWidth,
693
+ color: cleanValue(readStyle(node, "color")) ?? parent.color,
694
+ opacity: parent.opacity * (isNumber(opacity) ? opacity : 1),
695
+ };
696
+ for (const child of node.children) {
697
+ if (SILENT.has(child.name)) {
698
+ continue;
699
+ }
700
+ const dropped = DROPPED[child.name];
701
+ if (dropped) {
702
+ warnings.add(dropped);
703
+ continue;
704
+ }
705
+ if (child.name === "svg") {
706
+ warnings.add("nested-svg");
707
+ continue;
708
+ }
709
+ if (child.name === "g" || child.name === "a") {
710
+ walk(child, state, gradients, warnings, out);
711
+ continue;
712
+ }
713
+ if (!SHAPES.has(child.name)) {
714
+ warnings.add("unknown");
715
+ continue;
716
+ }
717
+ shapeElement(child, state, gradients, warnings, out);
718
+ }
719
+ }
720
+
721
+ function shapeElement(
722
+ node: SvgNode,
723
+ parent: State,
724
+ gradients: Map<string, string>,
725
+ warnings: Warnings,
726
+ out: Collected
727
+ ) {
728
+ checkAttributes(node, warnings);
729
+ if (
730
+ cleanValue(readStyle(node, "display")) === "none" ||
731
+ cleanValue(readStyle(node, "visibility")) === "hidden"
732
+ ) {
733
+ return;
734
+ }
735
+ const matrix = multiply(parent.matrix, parseTransform(node.attrs.transform));
736
+
737
+ if (
738
+ node.name === "rect" &&
739
+ QR_PLACEHOLDER.test(node.attrs.id ?? "") &&
740
+ !out.qrBox
741
+ ) {
742
+ out.qrBox = segmentsBounds(transformSegments(fillGeometry(node), matrix));
743
+ return;
744
+ }
745
+
746
+ const read = (name: string) => cleanValue(readStyle(node, name));
747
+ const opacity = parent.opacity * Number.parseFloat(read("opacity") ?? "1");
748
+ const fillOpacity = Number.parseFloat(read("fill-opacity") ?? "1");
749
+ const strokeOpacity = Number.parseFloat(read("stroke-opacity") ?? "1");
750
+ const fillRule = read("fill-rule");
751
+ const state: State = {
752
+ ...parent,
753
+ matrix,
754
+ fill: read("fill") ?? parent.fill,
755
+ fillRule:
756
+ fillRule === "evenodd" || fillRule === "nonzero"
757
+ ? fillRule
758
+ : parent.fillRule,
759
+ stroke: read("stroke") ?? parent.stroke,
760
+ color: read("color") ?? parent.color,
761
+ };
762
+ const strokeWidthValue = Number.parseFloat(read("stroke-width") ?? "");
763
+ const strokeWidth =
764
+ isNumber(strokeWidthValue) && strokeWidthValue >= 0
765
+ ? strokeWidthValue
766
+ : parent.strokeWidth;
767
+
768
+ const add = (segments: Segment[], fill: string, rule: Shape["fillRule"]) => {
769
+ if (segments.length === 0) {
770
+ return;
771
+ }
772
+ out.segments += segments.length;
773
+ if (out.segments > FRAME_IMPORT_LIMITS.maxInputSegments) {
774
+ throw new ImportError(
775
+ `The SVG has more than ${FRAME_IMPORT_LIMITS.maxInputSegments} path segments; simplify it`
776
+ );
777
+ }
778
+ out.shapes.push({
779
+ segments: transformSegments(segments, matrix),
780
+ fill,
781
+ fillRule: rule,
782
+ });
783
+ };
784
+
785
+ const visible = (alpha: number) => {
786
+ const value =
787
+ (isNumber(opacity) ? opacity : 1) * (isNumber(alpha) ? alpha : 1);
788
+ if (value <= 0) {
789
+ return false;
790
+ }
791
+ if (value < 1) {
792
+ warnings.add("opacity");
793
+ }
794
+ return true;
795
+ };
796
+
797
+ if (node.name !== "line") {
798
+ const fill = resolvePaint(state.fill, state, gradients, warnings);
799
+ if (fill && visible(fillOpacity)) {
800
+ add(fillGeometry(node), fill, state.fillRule);
801
+ }
802
+ }
803
+ if (strokeWidth > 0 && state.stroke !== "none") {
804
+ const stroke = resolvePaint(state.stroke, state, gradients, warnings);
805
+ if (stroke && visible(strokeOpacity)) {
806
+ const outline = strokeGeometry(node, strokeWidth);
807
+ if (outline) {
808
+ if ((read("stroke-dasharray") ?? "none") !== "none") {
809
+ warnings.add("dash");
810
+ }
811
+ add(outline, stroke, node.name === "line" ? "nonzero" : "evenodd");
812
+ } else {
813
+ warnings.add("stroke");
814
+ }
815
+ }
816
+ }
817
+ }
818
+
819
+ // ── Output ─────────────────────────────────────────────────────────────────
820
+
821
+ /** Path data with relative commands, rounded to `decimals`. */
822
+ function writeSegments(segments: Segment[], decimals: number): string {
823
+ const round = (value: number) => {
824
+ const scale = 10 ** decimals;
825
+ return Math.round(value * scale) / scale + 0;
826
+ };
827
+ const n = (value: number) => fmt(value, decimals);
828
+ let out = "";
829
+ let x = 0;
830
+ let y = 0;
831
+ let startX = 0;
832
+ let startY = 0;
833
+ for (const segment of segments) {
834
+ if (segment.op === "Z") {
835
+ out += "z";
836
+ x = startX;
837
+ y = startY;
838
+ continue;
839
+ }
840
+ const ex = round(segment.x);
841
+ const ey = round(segment.y);
842
+ if (segment.op === "M") {
843
+ out += `m${n(ex - x)} ${n(ey - y)}`;
844
+ startX = ex;
845
+ startY = ey;
846
+ } else if (segment.op === "L") {
847
+ if (ex === x && ey === y) {
848
+ continue;
849
+ }
850
+ out +=
851
+ ey === y
852
+ ? `h${n(ex - x)}`
853
+ : ex === x
854
+ ? `v${n(ey - y)}`
855
+ : `l${n(ex - x)} ${n(ey - y)}`;
856
+ } else {
857
+ out += `c${n(round(segment.x1) - x)} ${n(round(segment.y1) - y)} ${n(round(segment.x2) - x)} ${n(round(segment.y2) - y)} ${n(ex - x)} ${n(ey - y)}`;
858
+ }
859
+ x = ex;
860
+ y = ey;
861
+ }
862
+ return out;
863
+ }
864
+
865
+ const overlaps = (a: ClipBox, b: ClipBox) =>
866
+ a.x0 < b.x1 && b.x0 < a.x1 && a.y0 < b.y1 && b.y0 < a.y1;
867
+
868
+ /** Joins neighbours in paint order with the same paint that don't touch. */
869
+ function mergeShapes(shapes: Shape[]): Shape[] {
870
+ const merged: { shape: Shape; boxes: ClipBox[] }[] = [];
871
+ for (const shape of shapes) {
872
+ const box = segmentsBounds(shape.segments);
873
+ if (!box) {
874
+ continue;
875
+ }
876
+ const last = merged.at(-1);
877
+ if (
878
+ last &&
879
+ last.shape.fill === shape.fill &&
880
+ last.shape.fillRule === shape.fillRule &&
881
+ !last.boxes.some((other) => overlaps(other, box))
882
+ ) {
883
+ last.shape = {
884
+ ...last.shape,
885
+ segments: [...last.shape.segments, ...shape.segments],
886
+ };
887
+ last.boxes.push(box);
888
+ } else {
889
+ merged.push({ shape, boxes: [box] });
890
+ }
891
+ }
892
+ return merged.map((entry) => entry.shape);
893
+ }
894
+
895
+ const rgbOf = (hex: string) => [
896
+ Number.parseInt(hex.slice(1, 3), 16),
897
+ Number.parseInt(hex.slice(3, 5), 16),
898
+ Number.parseInt(hex.slice(5, 7), 16),
899
+ ];
900
+
901
+ /** Merges the closest colors until at most `limit` remain. */
902
+ function limitColors(
903
+ shapes: Shape[],
904
+ limit: number,
905
+ warnings: Warnings
906
+ ): Map<string, string> {
907
+ const weight = new Map<string, number>();
908
+ for (const shape of shapes) {
909
+ weight.set(shape.fill, (weight.get(shape.fill) ?? 0) + 1);
910
+ }
911
+ const mapping = new Map<string, string>(
912
+ [...weight.keys()].map((color) => [color, color])
913
+ );
914
+ let merges = 0;
915
+ while (weight.size > limit) {
916
+ const colors = [...weight.keys()];
917
+ let best: [string, string] = [colors[0] as string, colors[1] as string];
918
+ let bestDistance = Number.POSITIVE_INFINITY;
919
+ for (let i = 0; i < colors.length; i++) {
920
+ for (let j = i + 1; j < colors.length; j++) {
921
+ const a = rgbOf(colors[i] as string);
922
+ const b = rgbOf(colors[j] as string);
923
+ const d = Math.hypot(
924
+ (a[0] as number) - (b[0] as number),
925
+ (a[1] as number) - (b[1] as number),
926
+ (a[2] as number) - (b[2] as number)
927
+ );
928
+ if (d < bestDistance) {
929
+ bestDistance = d;
930
+ best = [colors[i] as string, colors[j] as string];
931
+ }
932
+ }
933
+ }
934
+ const [a, b] = best;
935
+ const [keep, drop] =
936
+ (weight.get(a) ?? 0) >= (weight.get(b) ?? 0) ? [a, b] : [b, a];
937
+ weight.set(keep, (weight.get(keep) ?? 0) + (weight.get(drop) ?? 0));
938
+ weight.delete(drop);
939
+ for (const [color, target] of mapping) {
940
+ if (target === drop) {
941
+ mapping.set(color, keep);
942
+ }
943
+ }
944
+ merges++;
945
+ }
946
+ if (merges > 0) {
947
+ warnings.add("colors", merges);
948
+ }
949
+ return mapping;
950
+ }
951
+
952
+ const isNearWhite = (hex: string) => {
953
+ const [r, g, b] = rgbOf(hex) as [number, number, number];
954
+ return 0.2126 * r + 0.7152 * g + 0.0722 * b > 235;
955
+ };
956
+
957
+ /**
958
+ * Converts SVG markup into a frame spec. Never throws: problems come back
959
+ * as `{ ok: false, error }`, and everything that was dropped or changed is
960
+ * listed in `warnings`.
961
+ */
962
+ export function importFrameSvg(
963
+ svg: string,
964
+ options: FrameImportOptions = {}
965
+ ): FrameImportResult {
966
+ const warnings = new Warnings();
967
+ try {
968
+ const body = checkMarkup(svg);
969
+ const root = parseSvgMarkup(body);
970
+ if (!root) {
971
+ throw new ImportError("No <svg> element found");
972
+ }
973
+
974
+ // Artboard: the viewBox, else width × height
975
+ const viewBox = parseNumbers(root.attrs.viewBox);
976
+ let [vx, vy, vw, vh] = [0, 0, 0, 0];
977
+ if (
978
+ viewBox.length === 4 &&
979
+ (viewBox[2] as number) > 0 &&
980
+ (viewBox[3] as number) > 0
981
+ ) {
982
+ [vx, vy, vw, vh] = viewBox as [number, number, number, number];
983
+ } else {
984
+ vw = num(root, "width");
985
+ vh = num(root, "height");
986
+ }
987
+ if (!(isNumber(vw) && isNumber(vh) && vw > 0 && vh > 0)) {
988
+ throw new ImportError("The SVG needs a viewBox (or a width and height)");
989
+ }
990
+ const side = FRAME_IMPORT_LIMITS.artboardSide;
991
+ const k = side / Math.max(vw, vh);
992
+ const width = Math.round(vw * k * 10) / 10;
993
+ const height = Math.round(vh * k * 10) / 10;
994
+ if (Math.min(width, height) < FRAME_SPEC_LIMITS.minArtboard) {
995
+ throw new ImportError(
996
+ "The artboard is too narrow: its sides may differ by 20 times at most"
997
+ );
998
+ }
999
+ const toArtboard: Matrix = [k, 0, 0, k, -vx * k, -vy * k];
1000
+
1001
+ const collected: Collected = { shapes: [], qrBox: null, segments: 0 };
1002
+ walk(
1003
+ root,
1004
+ {
1005
+ matrix: toArtboard,
1006
+ fill: "#000000",
1007
+ fillRule: "nonzero",
1008
+ stroke: "none",
1009
+ strokeWidth: 1,
1010
+ color: "#000000",
1011
+ opacity: 1,
1012
+ },
1013
+ collectGradients(root),
1014
+ warnings,
1015
+ collected
1016
+ );
1017
+
1018
+ // Keep what lies on the artboard; cut what crosses its edge
1019
+ const artboard: ClipBox = { x0: 0, y0: 0, x1: width, y1: height };
1020
+ const tolerance = Math.max(width, height) * 0.004;
1021
+ const shapes: Shape[] = [];
1022
+ let outside = 0;
1023
+ let clipped = 0;
1024
+ for (const shape of collected.shapes) {
1025
+ const box = segmentsBounds(shape.segments);
1026
+ if (
1027
+ !box ||
1028
+ box.x1 <= 0 ||
1029
+ box.y1 <= 0 ||
1030
+ box.x0 >= width ||
1031
+ box.y0 >= height
1032
+ ) {
1033
+ outside++;
1034
+ continue;
1035
+ }
1036
+ if (
1037
+ box.x0 < -tolerance ||
1038
+ box.y0 < -tolerance ||
1039
+ box.x1 > width + tolerance ||
1040
+ box.y1 > height + tolerance
1041
+ ) {
1042
+ const pieces = flattenSegments(shape.segments, 0.25)
1043
+ .map((polygon) => clipPolygon(polygon, artboard))
1044
+ .filter((polygon) => polygon.length > 2);
1045
+ if (pieces.length === 0) {
1046
+ outside++;
1047
+ continue;
1048
+ }
1049
+ clipped++;
1050
+ shapes.push({
1051
+ ...shape,
1052
+ segments: pieces.flatMap((polygon) => polygonSegments(polygon)),
1053
+ });
1054
+ } else {
1055
+ shapes.push(shape);
1056
+ }
1057
+ }
1058
+ if (outside > 0) {
1059
+ warnings.add("outside", outside);
1060
+ }
1061
+ if (clipped > 0) {
1062
+ warnings.add("clipped", clipped);
1063
+ }
1064
+ if (shapes.length === 0) {
1065
+ throw new ImportError("The SVG has no filled shapes to use");
1066
+ }
1067
+
1068
+ // Colors: the most used become the frame and accent tokens
1069
+ const mapping = limitColors(
1070
+ shapes,
1071
+ FRAME_IMPORT_LIMITS.maxColors,
1072
+ warnings
1073
+ );
1074
+ for (const shape of shapes) {
1075
+ shape.fill = mapping.get(shape.fill) ?? shape.fill;
1076
+ }
1077
+ const area = new Map<string, number>();
1078
+ const count = new Map<string, number>();
1079
+ for (const shape of shapes) {
1080
+ const box = segmentsBounds(shape.segments) as ClipBox;
1081
+ area.set(
1082
+ shape.fill,
1083
+ (area.get(shape.fill) ?? 0) + (box.x1 - box.x0) * (box.y1 - box.y0)
1084
+ );
1085
+ count.set(shape.fill, (count.get(shape.fill) ?? 0) + 1);
1086
+ }
1087
+ const ranked = [...area.keys()].sort(
1088
+ (a, b) =>
1089
+ Number(isNearWhite(a)) - Number(isNearWhite(b)) ||
1090
+ (area.get(b) as number) - (area.get(a) as number)
1091
+ );
1092
+ const frameColor = ranked[0] as string;
1093
+ const accentColor = ranked[1];
1094
+ const refOf = (color: string) =>
1095
+ color === frameColor ? "frame" : color === accentColor ? "accent" : color;
1096
+
1097
+ // The code
1098
+ let qrBox: ClipBox | null = collected.qrBox;
1099
+ if (!qrBox && options.qr) {
1100
+ const [x0, y0] = applyMatrix(toArtboard, options.qr.x, options.qr.y);
1101
+ qrBox = {
1102
+ x0,
1103
+ y0,
1104
+ x1: x0 + options.qr.size * k,
1105
+ y1: y0 + options.qr.size * k,
1106
+ };
1107
+ }
1108
+ let size: number;
1109
+ let qrX: number;
1110
+ let qrY: number;
1111
+ if (qrBox) {
1112
+ size = Math.min(qrBox.x1 - qrBox.x0, qrBox.y1 - qrBox.y0);
1113
+ qrX = (qrBox.x0 + qrBox.x1 - size) / 2;
1114
+ qrY = (qrBox.y0 + qrBox.y1 - size) / 2;
1115
+ } else {
1116
+ warnings.add("qr-placed");
1117
+ size = Math.min(width, height) * 0.6;
1118
+ qrX = (width - size) / 2;
1119
+ qrY = (height - size) / 2;
1120
+ }
1121
+ const r1 = (value: number) => Math.round(value * 10) / 10 + 0;
1122
+ size = Math.floor(size * 10) / 10;
1123
+ qrX = r1(qrX);
1124
+ qrY = r1(qrY);
1125
+ if (size < Math.min(width, height) * FRAME_SPEC_LIMITS.minQrShare) {
1126
+ throw new ImportError(
1127
+ "The QR area must be at least half the frame's shorter side"
1128
+ );
1129
+ }
1130
+ const room = Math.min(qrX, qrY, width - qrX - size, height - qrY - size);
1131
+ if (room < size * FRAME_SPEC_LIMITS.minPadding - 1e-9) {
1132
+ throw new ImportError(
1133
+ "Leave room around the QR area: at least 4% of its size on every side, inside the artboard"
1134
+ );
1135
+ }
1136
+ const share = Math.min(
1137
+ Math.max(
1138
+ options.padding ?? FRAME_IMPORT_LIMITS.padding,
1139
+ FRAME_SPEC_LIMITS.minPadding
1140
+ ),
1141
+ 0.2
1142
+ );
1143
+ const padding = Math.floor(Math.min(size * share, room) * 10) / 10;
1144
+
1145
+ const merged = mergeShapes(shapes);
1146
+ if (merged.length > FRAME_SPEC_LIMITS.maxShapes) {
1147
+ throw new ImportError(
1148
+ `The artwork has ${merged.length} separate shapes; the limit is ${FRAME_SPEC_LIMITS.maxShapes}. Combine shapes of the same color first`
1149
+ );
1150
+ }
1151
+
1152
+ const spec = {
1153
+ kind: FRAME_SPEC_KIND,
1154
+ version: FRAME_SPEC_VERSION,
1155
+ artboard: { width, height },
1156
+ qr: { x: qrX, y: qrY, size, padding },
1157
+ colors: {
1158
+ frame: frameColor,
1159
+ ...(accentColor && { accent: accentColor }),
1160
+ },
1161
+ shapes: merged.map((shape) => ({
1162
+ type: "path" as const,
1163
+ d: writeSegments(shape.segments, FRAME_IMPORT_LIMITS.decimals),
1164
+ fill: refOf(shape.fill),
1165
+ ...(shape.fillRule === "evenodd" && { fillRule: "evenodd" as const }),
1166
+ })),
1167
+ labels: [],
1168
+ };
1169
+
1170
+ const result = frameSpecSchema.safeParse(spec);
1171
+ if (!result.success) {
1172
+ const issue = result.error.issues[0];
1173
+ throw new ImportError(
1174
+ `The converted frame doesn't fit the frame format: ${issue?.message ?? "invalid"}`
1175
+ );
1176
+ }
1177
+ const palette: FrameImportColor[] = ranked.map((color) => ({
1178
+ color,
1179
+ ref:
1180
+ color === frameColor
1181
+ ? "frame"
1182
+ : color === accentColor
1183
+ ? "accent"
1184
+ : "fixed",
1185
+ shapes: count.get(color) ?? 0,
1186
+ }));
1187
+ return { ok: true, spec: result.data, warnings: warnings.list(), palette };
1188
+ } catch (error) {
1189
+ return {
1190
+ ok: false,
1191
+ error:
1192
+ error instanceof ImportError
1193
+ ? error.message
1194
+ : `Could not read the SVG (${error instanceof Error ? error.name : "error"})`,
1195
+ warnings: warnings.list(),
1196
+ };
1197
+ }
1198
+ }