qrdx 0.0.54 → 0.0.55

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 (113) hide show
  1. package/README.md +1 -1
  2. package/dist/core.js +7 -7
  3. package/dist/core.js.map +1 -1
  4. package/dist/core.mjs +7 -7
  5. package/dist/core.mjs.map +1 -1
  6. package/dist/element.browser.mjs +6 -67
  7. package/dist/element.browser.mjs.map +1 -1
  8. package/dist/index.js +7 -7
  9. package/dist/index.js.map +1 -1
  10. package/dist/index.mjs +7 -7
  11. package/dist/index.mjs.map +1 -1
  12. package/dist/qr-code-canvas.js +1 -1
  13. package/dist/qr-code-canvas.js.map +1 -1
  14. package/dist/qr-code-canvas.mjs +1 -1
  15. package/dist/qr-code-canvas.mjs.map +1 -1
  16. package/dist/schemas.js +2 -0
  17. package/dist/schemas.js.map +1 -0
  18. package/dist/schemas.mjs +2 -0
  19. package/dist/schemas.mjs.map +1 -0
  20. package/dist/src/art.d.ts +1 -1
  21. package/dist/src/art.d.ts.map +1 -1
  22. package/dist/src/engine.d.ts +2 -1
  23. package/dist/src/engine.d.ts.map +1 -1
  24. package/dist/src/eps.d.ts.map +1 -1
  25. package/dist/src/frame-import.d.ts +1 -1
  26. package/dist/src/frame-import.d.ts.map +1 -1
  27. package/dist/src/frame-spec.d.ts +5 -4
  28. package/dist/src/frame-spec.d.ts.map +1 -1
  29. package/dist/src/frame.d.ts +1 -1
  30. package/dist/src/frame.d.ts.map +1 -1
  31. package/dist/src/frames/builtin.d.ts +1 -1
  32. package/dist/src/frames/builtin.d.ts.map +1 -1
  33. package/dist/src/qr-outline.d.ts +1 -2
  34. package/dist/src/qr-outline.d.ts.map +1 -1
  35. package/dist/src/qr-shape.d.ts +1 -1
  36. package/dist/src/qr-shape.d.ts.map +1 -1
  37. package/dist/src/silhouette.d.ts +1 -2
  38. package/dist/src/silhouette.d.ts.map +1 -1
  39. package/dist/src/template/dot-ring-layout.d.ts +26 -3
  40. package/dist/src/template/dot-ring-layout.d.ts.map +1 -1
  41. package/dist/src/template/dot-ring.d.ts +22 -4
  42. package/dist/src/template/dot-ring.d.ts.map +1 -1
  43. package/dist/src/utils.d.ts +1 -1
  44. package/dist/src/utils.d.ts.map +1 -1
  45. package/dist/types/art.d.ts +1 -18
  46. package/dist/types/art.d.ts.map +1 -1
  47. package/dist/types/color-helpers.d.ts +26 -0
  48. package/dist/types/color-helpers.d.ts.map +1 -0
  49. package/dist/types/color.d.ts +1 -24
  50. package/dist/types/color.d.ts.map +1 -1
  51. package/dist/types/constants.d.ts +97 -0
  52. package/dist/types/constants.d.ts.map +1 -0
  53. package/dist/types/corner-dot.d.ts +2 -12
  54. package/dist/types/corner-dot.d.ts.map +1 -1
  55. package/dist/types/corner-eye.d.ts +2 -11
  56. package/dist/types/corner-eye.d.ts.map +1 -1
  57. package/dist/types/frame-spec-parse.d.ts +21 -0
  58. package/dist/types/frame-spec-parse.d.ts.map +1 -0
  59. package/dist/types/frame-spec-rules.d.ts +95 -0
  60. package/dist/types/frame-spec-rules.d.ts.map +1 -0
  61. package/dist/types/frame-spec.d.ts +2 -83
  62. package/dist/types/frame-spec.d.ts.map +1 -1
  63. package/dist/types/frame.d.ts +1 -8
  64. package/dist/types/frame.d.ts.map +1 -1
  65. package/dist/types/image-pattern.d.ts +1 -1
  66. package/dist/types/image-pattern.d.ts.map +1 -1
  67. package/dist/types/index.d.ts +3 -22
  68. package/dist/types/index.d.ts.map +1 -1
  69. package/dist/types/index.js +2 -2
  70. package/dist/types/index.js.map +1 -1
  71. package/dist/types/index.mjs +2 -2
  72. package/dist/types/index.mjs.map +1 -1
  73. package/dist/types/plain.d.ts +17 -0
  74. package/dist/types/plain.d.ts.map +1 -0
  75. package/dist/types/qr.d.ts +2 -46
  76. package/dist/types/qr.d.ts.map +1 -1
  77. package/dist/types/schemas.d.ts +12 -0
  78. package/dist/types/schemas.d.ts.map +1 -0
  79. package/dist/vanilla.browser.mjs +28 -28
  80. package/dist/vanilla.browser.mjs.map +1 -1
  81. package/package.json +1 -1
  82. package/src/art.tsx +3 -6
  83. package/src/body-patterns.tsx +1 -1
  84. package/src/engine.ts +53 -1
  85. package/src/eps.ts +6 -1
  86. package/src/frame-import.ts +7 -6
  87. package/src/frame-spec.ts +17 -23
  88. package/src/frame.tsx +3 -2
  89. package/src/frames/builtin.ts +2 -5
  90. package/src/helpers.ts +1 -1
  91. package/src/qr-outline.ts +2 -2
  92. package/src/qr-shape.ts +2 -5
  93. package/src/scan-score.ts +2 -2
  94. package/src/silhouette.ts +2 -2
  95. package/src/template/dot-ring-layout.ts +281 -15
  96. package/src/template/dot-ring.tsx +27 -8
  97. package/src/utils/print-shared.ts +1 -1
  98. package/src/utils.tsx +6 -5
  99. package/types/art.ts +10 -20
  100. package/types/color-helpers.ts +132 -0
  101. package/types/color.ts +9 -122
  102. package/types/constants.ts +222 -0
  103. package/types/corner-dot.ts +8 -40
  104. package/types/corner-eye.ts +2 -31
  105. package/types/frame-spec-parse.ts +683 -0
  106. package/types/frame-spec-rules.ts +645 -0
  107. package/types/frame-spec.ts +38 -635
  108. package/types/frame.ts +14 -34
  109. package/types/image-pattern.ts +2 -26
  110. package/types/index.ts +6 -162
  111. package/types/plain.ts +117 -0
  112. package/types/qr.ts +29 -51
  113. package/types/schemas.ts +62 -0
@@ -0,0 +1,683 @@
1
+ /** biome-ignore-all lint/style/noMagicNumbers: spec limits */
2
+ // The engine's frame spec parser: frameSpecSchema (frame-spec.ts) without
3
+ // zod, so drawing a frame, custom ones included, never loads zod. It accepts
4
+ // and rejects exactly what frameSpecSchema does, with the same messages and
5
+ // paths in the same order, and returns a copy with the keys in the schema's
6
+ // order, as zod does. It follows zod 4's rules for the few kinds of schema a
7
+ // spec uses: which checks still run after an issue, which union option
8
+ // reports, an oversized array failing before its items are read.
9
+ // tests/frame-spec-parse.test.ts compares the two on every official frame
10
+ // and thousands of broken specs. Change one, change the other.
11
+
12
+ import { FRAME_TEXT_MAX_LENGTH } from "./constants";
13
+ import type { FrameSpec } from "./frame-spec";
14
+ import {
15
+ checkFrameSpec,
16
+ FRAME_COLOR_TOKENS,
17
+ FRAME_ICONS,
18
+ FRAME_SPEC_KIND,
19
+ FRAME_SPEC_LIMITS,
20
+ FRAME_SPEC_VERSION,
21
+ hasPrecision,
22
+ } from "./frame-spec-rules";
23
+
24
+ /** One problem with a spec: where it is, and what's wrong. */
25
+ export interface FrameSpecIssue {
26
+ path: (string | number)[];
27
+ message: string;
28
+ }
29
+
30
+ // ── A small schema kit with zod's semantics ───────────────────────────────
31
+
32
+ interface Issue extends FrameSpecIssue {
33
+ /**
34
+ * zod's `continue`: true lets the schema's later checks run, undefined
35
+ * stops them (except length checks), false stops every one.
36
+ */
37
+ continue?: boolean;
38
+ }
39
+
40
+ interface Payload {
41
+ value: unknown;
42
+ issues: Issue[];
43
+ }
44
+
45
+ interface Check {
46
+ /** Length checks run on any value with a length, even after an issue. */
47
+ hasLength?: true;
48
+ run(payload: Payload): void;
49
+ }
50
+
51
+ interface Schema {
52
+ run(value: unknown): Payload;
53
+ optional?: true;
54
+ /** What a literal accepts (a discriminated union's keys). */
55
+ values?: readonly unknown[];
56
+ shape?: Record<string, Schema>;
57
+ }
58
+
59
+ const stops = (issues: Issue[], from = 0) => {
60
+ for (let i = from; i < issues.length; i++) {
61
+ if (issues[i]?.continue !== true) {
62
+ return true;
63
+ }
64
+ }
65
+ return false;
66
+ };
67
+
68
+ /** Runs `parse`, then the checks that may still run (zod's runChecks). */
69
+ function schema(
70
+ parse: (payload: Payload) => Payload,
71
+ checks: Check[] = [],
72
+ extra: Omit<Schema, "run"> = {}
73
+ ): Schema {
74
+ return {
75
+ ...extra,
76
+ run(value) {
77
+ const payload = parse({ value, issues: [] });
78
+ let stopped = stops(payload.issues);
79
+ for (const check of checks) {
80
+ if (check.hasLength) {
81
+ const input = payload.value as { length?: unknown } | null;
82
+ if (
83
+ payload.issues.some((issue) => issue.continue === false) ||
84
+ input === null ||
85
+ input === undefined ||
86
+ input.length === undefined
87
+ ) {
88
+ continue;
89
+ }
90
+ } else if (stopped) {
91
+ continue;
92
+ }
93
+ const start = payload.issues.length;
94
+ check.run(payload);
95
+ if (!stopped && payload.issues.length > start) {
96
+ stopped = stops(payload.issues, start);
97
+ }
98
+ }
99
+ return payload;
100
+ },
101
+ };
102
+ }
103
+
104
+ // zod's English messages
105
+ function typeName(input: unknown): string {
106
+ if (typeof input === "number") {
107
+ return Number.isNaN(input)
108
+ ? "NaN"
109
+ : Number.isFinite(input)
110
+ ? "number"
111
+ : String(input);
112
+ }
113
+ if (input === null) {
114
+ return "null";
115
+ }
116
+ if (Array.isArray(input)) {
117
+ return "array";
118
+ }
119
+ if (typeof input === "object") {
120
+ const maker = (input as { constructor?: { name: string } }).constructor;
121
+ if (
122
+ Object.getPrototypeOf(input) !== Object.prototype &&
123
+ "constructor" in input &&
124
+ maker
125
+ ) {
126
+ return maker.name;
127
+ }
128
+ }
129
+ return typeof input;
130
+ }
131
+
132
+ const typeIssue = (expected: string, input: unknown): Issue => ({
133
+ path: [],
134
+ message: `Invalid input: expected ${expected}, received ${typeName(input)}`,
135
+ });
136
+
137
+ const UNITS: Record<string, string> = { string: "characters", array: "items" };
138
+
139
+ /** too_big or too_small; `more` is the issue's `continue` (see Issue). */
140
+ function sizeIssue(
141
+ big: boolean,
142
+ origin: string,
143
+ bound: number,
144
+ more: boolean | undefined
145
+ ): Issue {
146
+ const unit = UNITS[origin];
147
+ const word = big ? "Too big" : "Too small";
148
+ const limit = `${big ? "<=" : ">="}${bound}`;
149
+ return {
150
+ path: [],
151
+ message: unit
152
+ ? `${word}: expected ${origin} to have ${limit} ${unit}`
153
+ : `${word}: expected ${origin} to be ${limit}`,
154
+ continue: more,
155
+ };
156
+ }
157
+
158
+ const quote = (value: unknown) =>
159
+ typeof value === "string" ? `"${value}"` : `${value}`;
160
+
161
+ const isObject = (value: unknown): value is Record<string, unknown> =>
162
+ typeof value === "object" && value !== null && !Array.isArray(value);
163
+
164
+ function prefix(target: Issue[], key: string | number, issues: Issue[]) {
165
+ for (const issue of issues) {
166
+ issue.path.unshift(key);
167
+ target.push(issue);
168
+ }
169
+ }
170
+
171
+ const isHigh = (code: number) => code >= 0xd8_00 && code <= 0xdb_ff;
172
+ const isLow = (code: number) => code >= 0xdc_00 && code <= 0xdf_ff;
173
+
174
+ // Code points: a surrogate pair counts once, a lone surrogate as itself
175
+ function codePoints(text: string): number {
176
+ let count = text.length;
177
+ for (let i = 0; i < text.length - 1; i++) {
178
+ if (isHigh(text.charCodeAt(i)) && isLow(text.charCodeAt(i + 1))) {
179
+ count--;
180
+ i++;
181
+ }
182
+ }
183
+ return count;
184
+ }
185
+
186
+ const lengthOrigin = (input: unknown) =>
187
+ Array.isArray(input)
188
+ ? "array"
189
+ : typeof input === "string"
190
+ ? "string"
191
+ : "unknown";
192
+
193
+ // ── Checks ────────────────────────────────────────────────────────────────
194
+
195
+ const gte = (minimum: number): Check => ({
196
+ run(payload) {
197
+ if ((payload.value as number) < minimum) {
198
+ payload.issues.push(sizeIssue(false, "number", minimum, true));
199
+ }
200
+ },
201
+ });
202
+
203
+ const lte = (maximum: number): Check => ({
204
+ run(payload) {
205
+ if ((payload.value as number) > maximum) {
206
+ payload.issues.push(sizeIssue(true, "number", maximum, true));
207
+ }
208
+ },
209
+ });
210
+
211
+ const refine = (
212
+ test: (value: number) => boolean,
213
+ message = "Invalid input"
214
+ ): Check => ({
215
+ run(payload) {
216
+ if (!test(payload.value as number)) {
217
+ payload.issues.push({ path: [], message, continue: true });
218
+ }
219
+ },
220
+ });
221
+
222
+ // A string's length counts code points
223
+ const lengthOf = (input: string | unknown[]) =>
224
+ typeof input === "string" ? codePoints(input) : input.length;
225
+
226
+ const minLength = (minimum: number): Check => ({
227
+ hasLength: true,
228
+ run(payload) {
229
+ const input = payload.value as string | unknown[];
230
+ if (lengthOf(input) < minimum) {
231
+ payload.issues.push(sizeIssue(false, lengthOrigin(input), minimum, true));
232
+ }
233
+ },
234
+ });
235
+
236
+ const maxLength = (maximum: number): Check => ({
237
+ hasLength: true,
238
+ run(payload) {
239
+ const input = payload.value as string | unknown[];
240
+ if (lengthOf(input) > maximum) {
241
+ payload.issues.push(sizeIssue(true, lengthOrigin(input), maximum, true));
242
+ }
243
+ },
244
+ });
245
+
246
+ const regex = (pattern: RegExp, message?: string): Check => ({
247
+ run(payload) {
248
+ pattern.lastIndex = 0;
249
+ if (!pattern.test(payload.value as string)) {
250
+ payload.issues.push({
251
+ path: [],
252
+ message: message ?? `Invalid string: must match pattern ${pattern}`,
253
+ continue: true,
254
+ });
255
+ }
256
+ },
257
+ });
258
+
259
+ // z.int(): a whole number within the safe range, checked before the rest
260
+ const integer: Check = {
261
+ run(payload) {
262
+ const input = payload.value as number;
263
+ if (!Number.isInteger(input)) {
264
+ payload.issues.push({ ...typeIssue("int", input), continue: false });
265
+ } else if (!Number.isSafeInteger(input)) {
266
+ payload.issues.push(
267
+ input > 0
268
+ ? sizeIssue(true, "int", Number.MAX_SAFE_INTEGER, true)
269
+ : sizeIssue(false, "int", Number.MIN_SAFE_INTEGER, true)
270
+ );
271
+ }
272
+ },
273
+ };
274
+
275
+ // ── Schemas ───────────────────────────────────────────────────────────────
276
+
277
+ const number = (...checks: Check[]) =>
278
+ schema((payload) => {
279
+ const input = payload.value;
280
+ if (!(typeof input === "number" && Number.isFinite(input))) {
281
+ payload.issues.push(typeIssue("number", input));
282
+ }
283
+ return payload;
284
+ }, checks);
285
+
286
+ const int = (...checks: Check[]) => number(integer, ...checks);
287
+
288
+ const string = (...checks: Check[]) =>
289
+ schema((payload) => {
290
+ if (typeof payload.value !== "string") {
291
+ payload.issues.push(typeIssue("string", payload.value));
292
+ }
293
+ return payload;
294
+ }, checks);
295
+
296
+ function oneOf(values: readonly unknown[]): Schema {
297
+ const message =
298
+ values.length === 1
299
+ ? `Invalid input: expected ${quote(values[0])}`
300
+ : `Invalid option: expected one of ${values.map(quote).join("|")}`;
301
+ return schema(
302
+ (payload) => {
303
+ if (!values.includes(payload.value)) {
304
+ payload.issues.push({ path: [], message });
305
+ }
306
+ return payload;
307
+ },
308
+ [],
309
+ { values }
310
+ );
311
+ }
312
+
313
+ const literal = (value: string | number) => oneOf([value]);
314
+
315
+ const optional = (inner: Schema): Schema => ({
316
+ optional: true,
317
+ run: (value) =>
318
+ value === undefined ? { value, issues: [] } : inner.run(value),
319
+ });
320
+
321
+ /** An object with exactly these keys (z.object(shape).strict()). */
322
+ function strict(shape: Record<string, Schema>, checks: Check[] = []): Schema {
323
+ const keys = Object.keys(shape);
324
+ const known = new Set(keys);
325
+ return schema(
326
+ (payload) => {
327
+ const input = payload.value;
328
+ if (!isObject(input)) {
329
+ payload.issues.push(typeIssue("object", input));
330
+ return payload;
331
+ }
332
+ const output: Record<string, unknown> = {};
333
+ for (const key of keys) {
334
+ const field = shape[key] as Schema;
335
+ const result = field.run(input[key]);
336
+ const present = key in input;
337
+ // (An absent optional field never has issues: it's undefined.)
338
+ prefix(payload.issues, key, result.issues);
339
+ if (!(present || field.optional || result.issues.length > 0)) {
340
+ payload.issues.push({
341
+ path: [key],
342
+ message: "Invalid input: expected nonoptional, received undefined",
343
+ });
344
+ }
345
+ if (present) {
346
+ output[key] = result.value;
347
+ }
348
+ }
349
+ payload.value = output;
350
+ const unknown: string[] = [];
351
+ // biome-ignore lint/suspicious/noForIn: zod lists inherited enumerable keys too
352
+ for (const key in input) {
353
+ if (!known.has(key)) {
354
+ unknown.push(key);
355
+ }
356
+ }
357
+ if (unknown.length > 0) {
358
+ payload.issues.push({
359
+ path: [],
360
+ message: `Unrecognized key${unknown.length > 1 ? "s" : ""}: ${unknown.map(quote).join(", ")}`,
361
+ continue: true,
362
+ });
363
+ }
364
+ return payload;
365
+ },
366
+ checks,
367
+ { shape }
368
+ );
369
+ }
370
+
371
+ function array(item: Schema, minimum?: number, maximum?: number): Schema {
372
+ const checks: Check[] = [];
373
+ if (minimum !== undefined) {
374
+ checks.push(minLength(minimum));
375
+ }
376
+ if (maximum !== undefined) {
377
+ checks.push(maxLength(maximum));
378
+ }
379
+ return schema((payload) => {
380
+ const input = payload.value;
381
+ // An oversized array fails before any item is read
382
+ if (
383
+ Array.isArray(input) &&
384
+ maximum !== undefined &&
385
+ input.length > maximum
386
+ ) {
387
+ payload.issues.push(sizeIssue(true, "array", maximum, false));
388
+ return payload;
389
+ }
390
+ if (!Array.isArray(input)) {
391
+ payload.issues.push(typeIssue("array", input));
392
+ return payload;
393
+ }
394
+ const output: unknown[] = new Array(input.length);
395
+ for (let i = 0; i < input.length; i++) {
396
+ const result = item.run(input[i]);
397
+ prefix(payload.issues, i, result.issues);
398
+ output[i] = result.value;
399
+ }
400
+ payload.value = output;
401
+ return payload;
402
+ }, checks);
403
+ }
404
+
405
+ function tuple(items: Schema[]): Schema {
406
+ return schema((payload) => {
407
+ const input = payload.value;
408
+ if (!Array.isArray(input)) {
409
+ payload.issues.push(typeIssue("tuple", input));
410
+ return payload;
411
+ }
412
+ if (input.length < items.length) {
413
+ payload.issues.push(sizeIssue(false, "array", items.length, undefined));
414
+ return payload;
415
+ }
416
+ if (input.length > items.length) {
417
+ payload.issues.push(sizeIssue(true, "array", items.length, undefined));
418
+ }
419
+ const output: unknown[] = [];
420
+ items.forEach((item, i) => {
421
+ const result = item.run(input[i]);
422
+ prefix(payload.issues, i, result.issues);
423
+ output[i] = result.value;
424
+ });
425
+ payload.value = output;
426
+ return payload;
427
+ });
428
+ }
429
+
430
+ /** The first option that passes; else the one that failed softly; else one issue. */
431
+ function union(options: Schema[]): Schema {
432
+ return schema((payload) => {
433
+ const results: Payload[] = [];
434
+ for (const option of options) {
435
+ const result = option.run(payload.value);
436
+ if (result.issues.length === 0) {
437
+ return result;
438
+ }
439
+ results.push(result);
440
+ }
441
+ const soft = results.filter((result) => !stops(result.issues));
442
+ if (soft.length === 1) {
443
+ return soft[0] as Payload;
444
+ }
445
+ payload.issues.push({ path: [], message: "Invalid input" });
446
+ return payload;
447
+ });
448
+ }
449
+
450
+ /** The option whose `key` literal matches (z.discriminatedUnion). */
451
+ function discriminated(key: string, options: Schema[]): Schema {
452
+ const byValue = new Map<unknown, Schema>();
453
+ for (const option of options) {
454
+ for (const value of option.shape?.[key]?.values ?? []) {
455
+ byValue.set(value, option);
456
+ }
457
+ }
458
+ const message = `Invalid discriminator value. Expected ${[...byValue.keys()]
459
+ .map((value) => `'${value}'`)
460
+ .join(" | ")}`;
461
+ return schema((payload) => {
462
+ const input = payload.value;
463
+ if (!isObject(input)) {
464
+ payload.issues.push(typeIssue("object", input));
465
+ return payload;
466
+ }
467
+ const option = byValue.get(input[key]);
468
+ if (option) {
469
+ return option.run(input);
470
+ }
471
+ payload.issues.push({ path: [key], message });
472
+ return payload;
473
+ });
474
+ }
475
+
476
+ // ── The spec (in step with frame-spec.ts) ─────────────────────────────────
477
+
478
+ const precise = refine(
479
+ hasPrecision,
480
+ `Numbers may have at most ${FRAME_SPEC_LIMITS.maxDecimals} decimals`
481
+ );
482
+ const coordinate = [
483
+ gte(-FRAME_SPEC_LIMITS.maxCoordinate),
484
+ lte(FRAME_SPEC_LIMITS.maxCoordinate),
485
+ precise,
486
+ ];
487
+ const num = number(...coordinate);
488
+ const positive = number(
489
+ ...coordinate,
490
+ refine((value) => value > 0, "Must be greater than 0")
491
+ );
492
+ const nonNegative = number(
493
+ ...coordinate,
494
+ refine((value) => value >= 0, "Must not be negative")
495
+ );
496
+
497
+ const hexColor = string(
498
+ regex(/^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/, "Use a #rgb or #rrggbb color")
499
+ );
500
+ const baseColor = union([oneOf(FRAME_COLOR_TOKENS), hexColor]);
501
+ const mix = (base: Schema) =>
502
+ strict({
503
+ mix: tuple([base, base]),
504
+ amount: number(gte(0), lte(1), refine(hasPrecision)),
505
+ });
506
+ const color = union([baseColor, mix(baseColor)]);
507
+ const defaultTextColor = union([
508
+ hexColor,
509
+ mix(union([oneOf(["frame", "accent", "background"]), hexColor])),
510
+ ]);
511
+ const paint = union([
512
+ color,
513
+ strict({
514
+ gradient: strict({
515
+ from: color,
516
+ to: color,
517
+ direction: optional(oneOf(["horizontal", "vertical"])),
518
+ steps: optional(int(gte(2), lte(FRAME_SPEC_LIMITS.maxGradientSteps))),
519
+ }),
520
+ }),
521
+ ]);
522
+
523
+ const box = () => ({ x: num, y: num, width: positive, height: positive });
524
+ const stroke = strict({ color, width: positive });
525
+
526
+ const shape = discriminated("type", [
527
+ strict({
528
+ type: literal("rect"),
529
+ ...box(),
530
+ radius: optional(nonNegative),
531
+ fill: paint,
532
+ hole: optional(strict({ ...box(), radius: optional(nonNegative) })),
533
+ stroke: optional(stroke),
534
+ }),
535
+ strict({
536
+ type: literal("circle"),
537
+ cx: num,
538
+ cy: num,
539
+ r: positive,
540
+ hole: optional(positive),
541
+ fill: paint,
542
+ stroke: optional(stroke),
543
+ }),
544
+ strict({
545
+ type: literal("ellipse"),
546
+ cx: num,
547
+ cy: num,
548
+ rx: positive,
549
+ ry: positive,
550
+ fill: paint,
551
+ stroke: optional(stroke),
552
+ }),
553
+ strict({
554
+ type: literal("polygon"),
555
+ points: array(tuple([num, num]), 3, FRAME_SPEC_LIMITS.maxPolygonPoints),
556
+ fill: paint,
557
+ stroke: optional(stroke),
558
+ }),
559
+ strict({
560
+ type: literal("path"),
561
+ d: string(minLength(2), maxLength(FRAME_SPEC_LIMITS.maxPathLength)),
562
+ fill: paint,
563
+ fillRule: optional(oneOf(["nonzero", "evenodd"])),
564
+ stroke: optional(stroke),
565
+ }),
566
+ strict({
567
+ type: literal("line"),
568
+ x1: num,
569
+ y1: num,
570
+ x2: num,
571
+ y2: num,
572
+ width: positive,
573
+ cap: optional(oneOf(["butt", "round"])),
574
+ dash: optional(tuple([positive, positive])),
575
+ fill: paint,
576
+ }),
577
+ strict({
578
+ type: literal("icon"),
579
+ icon: oneOf(FRAME_ICONS),
580
+ x: num,
581
+ y: num,
582
+ size: positive,
583
+ fill: paint,
584
+ }),
585
+ ]);
586
+
587
+ const labelFields = () => ({
588
+ id: string(regex(/^[a-z][a-z0-9-]{0,31}$/)),
589
+ slot: oneOf(["primary", "secondary", "fixed"]),
590
+ text: string(maxLength(200)),
591
+ maxLength: optional(int(gte(1), lte(FRAME_TEXT_MAX_LENGTH))),
592
+ color,
593
+ weight: optional(oneOf(["bold", "regular"])),
594
+ collapse: optional(strict({ y: num, height: positive })),
595
+ });
596
+
597
+ const label = discriminated("type", [
598
+ strict({
599
+ type: literal("text"),
600
+ ...labelFields(),
601
+ box: strict(box()),
602
+ align: optional(oneOf(["start", "middle", "end"])),
603
+ fontSize: optional(positive),
604
+ }),
605
+ strict({
606
+ type: literal("curved"),
607
+ ...labelFields(),
608
+ curve: strict({
609
+ cx: num,
610
+ cy: num,
611
+ radius: positive,
612
+ side: oneOf(["top", "bottom"]),
613
+ spread: optional(number(gte(20), lte(300), refine(hasPrecision))),
614
+ }),
615
+ fontSize: positive,
616
+ }),
617
+ ]);
618
+
619
+ const artboardSide = number(
620
+ ...coordinate,
621
+ refine(
622
+ (value) =>
623
+ value >= FRAME_SPEC_LIMITS.minArtboard &&
624
+ value <= FRAME_SPEC_LIMITS.maxArtboard,
625
+ `Artboard sides must be ${FRAME_SPEC_LIMITS.minArtboard} to ${FRAME_SPEC_LIMITS.maxArtboard} units`
626
+ )
627
+ );
628
+
629
+ const frameSpec = strict(
630
+ {
631
+ kind: literal(FRAME_SPEC_KIND),
632
+ version: literal(FRAME_SPEC_VERSION),
633
+ artboard: strict({ width: artboardSide, height: artboardSide }),
634
+ qr: strict({
635
+ x: num,
636
+ y: num,
637
+ size: positive,
638
+ padding: optional(nonNegative),
639
+ radius: optional(nonNegative),
640
+ plate: optional(oneOf(["opaque", "background", "none"])),
641
+ }),
642
+ colors: strict({
643
+ frame: hexColor,
644
+ text: optional(defaultTextColor),
645
+ accent: optional(hexColor),
646
+ }),
647
+ shapes: array(shape, undefined, FRAME_SPEC_LIMITS.maxShapes),
648
+ labels: array(label, undefined, FRAME_SPEC_LIMITS.maxLabels),
649
+ bleed: optional(union([literal("none"), color])),
650
+ },
651
+ [
652
+ {
653
+ run(payload) {
654
+ checkFrameSpec(payload.value as FrameSpec, (message, path = []) => {
655
+ payload.issues.push({ path: [...path], message, continue: true });
656
+ });
657
+ },
658
+ },
659
+ ]
660
+ );
661
+
662
+ /**
663
+ * Parses `input` as a frame spec with every limit and check: a copy of it,
664
+ * or the problems. What `frameSpecSchema.safeParse` gives, without zod.
665
+ */
666
+ export function parseFrameSpec(
667
+ input: unknown
668
+ ):
669
+ | { success: true; data: FrameSpec }
670
+ | { success: false; issues: FrameSpecIssue[] } {
671
+ const result = frameSpec.run(input);
672
+ if (result.issues.length === 0) {
673
+ return { success: true, data: result.value as FrameSpec };
674
+ }
675
+ return {
676
+ success: false,
677
+ issues: result.issues.map(({ path, message }) => ({ path, message })),
678
+ };
679
+ }
680
+
681
+ /** An issue as one line: `shapes.0.fill: Invalid input`. */
682
+ export const frameSpecIssueText = ({ path, message }: FrameSpecIssue) =>
683
+ path.length > 0 ? `${path.join(".")}: ${message}` : message;