@polotno/schema 0.2.0 → 0.4.0

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 (55) hide show
  1. package/README.md +2 -2
  2. package/lib/bleed.d.ts +0 -1
  3. package/lib/bleed.js +0 -1
  4. package/lib/defaults.d.ts +44 -434
  5. package/lib/defaults.js +92 -243
  6. package/lib/design.schema.json +5 -0
  7. package/lib/errors.d.ts +23 -6
  8. package/lib/errors.js +5 -1
  9. package/lib/index.d.ts +3 -1
  10. package/lib/index.js +3 -1
  11. package/lib/migrate.d.ts +18 -3
  12. package/lib/migrate.js +120 -45
  13. package/lib/normalize.d.ts +20 -3
  14. package/lib/normalize.js +196 -50
  15. package/lib/schema.d.ts +14 -1
  16. package/lib/schema.js +537 -134
  17. package/lib/types-parity.d.ts +0 -1
  18. package/lib/types-parity.js +0 -1
  19. package/lib/types.d.ts +2 -1
  20. package/lib/types.js +0 -1
  21. package/package.json +8 -8
  22. package/lib/bleed.d.ts.map +0 -1
  23. package/lib/bleed.js.map +0 -1
  24. package/lib/constants.d.ts +0 -6
  25. package/lib/constants.d.ts.map +0 -1
  26. package/lib/constants.js +0 -61
  27. package/lib/constants.js.map +0 -1
  28. package/lib/defaults.d.ts.map +0 -1
  29. package/lib/defaults.js.map +0 -1
  30. package/lib/errors.d.ts.map +0 -1
  31. package/lib/errors.js.map +0 -1
  32. package/lib/index.d.ts.map +0 -1
  33. package/lib/index.js.map +0 -1
  34. package/lib/migrate.d.ts.map +0 -1
  35. package/lib/migrate.js.map +0 -1
  36. package/lib/normalize.d.ts.map +0 -1
  37. package/lib/normalize.js.map +0 -1
  38. package/lib/processors.d.ts +0 -13
  39. package/lib/processors.d.ts.map +0 -1
  40. package/lib/processors.js +0 -170
  41. package/lib/processors.js.map +0 -1
  42. package/lib/schema.d.ts.map +0 -1
  43. package/lib/schema.js.map +0 -1
  44. package/lib/traverse.d.ts +0 -3
  45. package/lib/traverse.d.ts.map +0 -1
  46. package/lib/traverse.js +0 -32
  47. package/lib/traverse.js.map +0 -1
  48. package/lib/types-parity.d.ts.map +0 -1
  49. package/lib/types-parity.js.map +0 -1
  50. package/lib/types.d.ts.map +0 -1
  51. package/lib/types.js.map +0 -1
  52. package/lib/validate.d.ts +0 -19
  53. package/lib/validate.d.ts.map +0 -1
  54. package/lib/validate.js +0 -383
  55. package/lib/validate.js.map +0 -1
@@ -12,10 +12,28 @@ export interface ParseOptions extends ValidateOptions {
12
12
  * Assign a synthetic `id` to any page/element/cell that lacks one before
13
13
  * validating. `id` is otherwise required, but it's identity metadata the
14
14
  * renderer doesn't draw, so consumers that accept hand-built JSON (the export
15
- * converters) stay tolerant. Real `store.toJSON()` output always has ids, so
16
- * this is a no-op there. Does not touch the caller's input (works on a copy).
15
+ * converters) stay tolerant. Ids are DETERMINISTIC (structural index paths
16
+ * like `el-0-2`) so identical input yields identical output. Real
17
+ * `store.toJSON()` output always has ids, so this is a no-op there. Does not
18
+ * touch the caller's input (works on a copy).
17
19
  */
18
20
  fillMissingIds?: boolean;
21
+ /**
22
+ * Editor-export compatibility: preserve client-owned content the way the
23
+ * editor's own SVG/HTML export historically did (it rendered raw JSON).
24
+ * - Elements whose type is outside the schema union (the editor's
25
+ * `registerShapeModel` extensions) skip validation and stay in place —
26
+ * handed through as shallow copies of the CALLER's objects (`id` filled
27
+ * when `fillMissingIds` is set), so they survive to element hooks.
28
+ * Renderers fall back to a placeholder for them.
29
+ * - Unrecognized ad-hoc keys the zod pass strips are copied back onto
30
+ * parsed elements/pages/cells/audios from the caller's input.
31
+ * Schema-recognized keys keep their validated values; `null` stays
32
+ * "unset".
33
+ * - `custom` needs no special handling: it is JSON-like data by contract
34
+ * and the schema keeps it everywhere, so it survives parsing as-is.
35
+ */
36
+ preserveClientData?: boolean;
19
37
  }
20
38
  /**
21
39
  * The one entry a consumer should use to accept design JSON: validate, then
@@ -24,4 +42,3 @@ export interface ParseOptions extends ValidateOptions {
24
42
  * with `assertValidDesign`.
25
43
  */
26
44
  export declare function parseDesign(input: unknown, opts?: ParseOptions): Design;
27
- //# sourceMappingURL=normalize.d.ts.map
package/lib/normalize.js CHANGED
@@ -1,54 +1,179 @@
1
- // normalizeDesign = drop nulls -> zod parse (fills defaults, strips unknown
2
- // keys). "Fill defaults + validate-shape", exact for clean modern input.
3
- //
4
- // No schemaVersion migration: this package assumes current-format input. A
5
- // missing schemaVersion defaults to the current version; old documents that
6
- // need migrating should round-trip through the core `polotno` store.
7
- import { designSchemaLenient, assertValidDesign, cloneDropNulls, } from './schema.js';
1
+ // normalizeDesign = migrate -> drop nulls -> zod parse (fills defaults, strips
2
+ // unknown keys). The migration step is what makes a design mean the same thing
3
+ // in every package; migrate.ts explains why it lives here and why a missing
4
+ // `schemaVersion` counts as 0.
5
+ import { designSchemaLenient, parseValidDesign, cloneDropNulls, ELEMENT_TYPES, } from './schema.js';
8
6
  import { polotnoError } from './errors.js';
7
+ import { migrateDesign } from './migrate.js';
9
8
  export function normalizeDesign(json) {
10
- return designSchemaLenient.parse(cloneDropNulls(json));
9
+ return designSchemaLenient.parse(cloneDropNulls(migrateDesign(json)));
11
10
  }
12
- const ID_ALPHABET = 'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict';
13
- // URL-safe id matching core's `nanoid(10)` (group-model.ts / page-model.ts) — 10
14
- // chars from a 64-char alphabet. Inlined (no dependency) so schema bundles under
15
- // any platform/bundler; prefers Web Crypto where present (browser + modern Node),
16
- // falls back to Math.random so it never throws.
17
- function randomId(size = 10) {
18
- const c = globalThis.crypto;
19
- let id = '';
20
- if (c && typeof c.getRandomValues === 'function') {
21
- const bytes = c.getRandomValues(new Uint8Array(size));
22
- for (let i = 0; i < size; i++)
23
- id += ID_ALPHABET[bytes[i] & 63];
24
- }
25
- else {
26
- for (let i = 0; i < size; i++)
27
- id += ID_ALPHABET[(Math.random() * 64) | 0];
28
- }
29
- return id;
30
- }
31
- // Return a deep copy with a fresh `id` on any page/element/cell missing one.
32
- // Recurses children (groups) + cells (tables) so ids stay collision-safe even if
33
- // designs are later merged. Other required fields (`type`, font `fontFamily`) are
34
- // left alone — their absence is genuinely malformed.
35
- function withFilledIds(input) {
36
- if (!input || typeof input !== 'object')
37
- return input;
38
- const clone = JSON.parse(JSON.stringify(input));
39
- const ensure = (node) => {
11
+ // Fill missing `id`s with DETERMINISTIC structural ids — the index path from
12
+ // the document root (`page-0`, `el-0-2`, nested `el-0-2-1`, `cell-0-2-3`).
13
+ // Ids are emitted into exported HTML/SVG, so a random id would make the same
14
+ // input produce different output on every call (breaking snapshots, hashing,
15
+ // cache keys). Uniqueness is guaranteed within THIS design (an authored id
16
+ // that collides gets a `_2` suffix); real `store.toJSON()` output always has
17
+ // ids, so this never runs on it. Other required fields (`type`, font
18
+ // `fontFamily`) are left alone — their absence is genuinely malformed.
19
+ // Mutates in place — runs only on parseDesign's private working copy.
20
+ function fillIds(clone) {
21
+ if (!Array.isArray(clone.pages))
22
+ return;
23
+ const taken = new Set();
24
+ const collect = (node) => {
40
25
  if (node && typeof node === 'object') {
41
- if (node.id == null || node.id === '')
42
- node.id = randomId(10);
26
+ if (typeof node.id === 'string' && node.id !== '')
27
+ taken.add(node.id);
43
28
  if (Array.isArray(node.children))
44
- node.children.forEach(ensure);
29
+ node.children.forEach(collect);
45
30
  if (Array.isArray(node.cells))
46
- node.cells.forEach(ensure);
31
+ node.cells.forEach(collect);
32
+ }
33
+ };
34
+ clone.pages.forEach(collect);
35
+ const claim = (base) => {
36
+ let id = base;
37
+ for (let n = 2; taken.has(id); n++)
38
+ id = `${base}_${n}`;
39
+ taken.add(id);
40
+ return id;
41
+ };
42
+ const ensure = (node, kind, path) => {
43
+ if (!node || typeof node !== 'object')
44
+ return;
45
+ if (node.id == null || node.id === '') {
46
+ node.id = claim(`${kind}-${path.join('-')}`);
47
+ }
48
+ if (Array.isArray(node.children)) {
49
+ node.children.forEach((child, i) => ensure(child, 'el', [...path, i]));
50
+ }
51
+ if (Array.isArray(node.cells)) {
52
+ node.cells.forEach((cell, i) => ensure(cell, 'cell', [...path, i]));
53
+ }
54
+ };
55
+ clone.pages.forEach((page, i) => ensure(page, 'page', [i]));
56
+ }
57
+ const KNOWN_ELEMENT_TYPES = new Set(ELEMENT_TYPES);
58
+ // Pull unknown-type elements out of the working copy before validation (they
59
+ // would fail the element union), remembering their original index path so
60
+ // they can be spliced back verbatim after the parse. Scans in document order
61
+ // — the splice replay depends on it (restoring earlier siblings first keeps
62
+ // later recorded paths valid). Nullish children are dropped, matching what
63
+ // cloneDropNulls does inside the parse, so the trees stay index-aligned.
64
+ function extractUnknownElements(clone) {
65
+ const out = [];
66
+ const scan = (node, path) => {
67
+ if (!node || !Array.isArray(node.children))
68
+ return;
69
+ const kept = [];
70
+ // Index in the null-free (reconstructed) array — recorded paths must not
71
+ // count dropped nullish slots.
72
+ let outIdx = 0;
73
+ for (const child of node.children) {
74
+ if (child == null)
75
+ continue;
76
+ if (typeof child === 'object' && KNOWN_ELEMENT_TYPES.has(child.type)) {
77
+ kept.push(child);
78
+ scan(child, [...path, outIdx]);
79
+ }
80
+ else if (typeof child === 'object' && typeof child.type === 'string') {
81
+ out.push({ path: [...path, outIdx], element: child });
82
+ }
83
+ else {
84
+ // Not an extension element (extension types always carry a string
85
+ // `type`): strings, numbers, type-less objects stay in place so the
86
+ // schema pass rejects them as DESIGN_INVALID — the editor's model
87
+ // would reject them too.
88
+ kept.push(child);
89
+ }
90
+ outIdx++;
91
+ }
92
+ node.children = kept;
93
+ };
94
+ if (Array.isArray(clone.pages)) {
95
+ clone.pages.forEach((page, i) => scan(page, [i]));
96
+ }
97
+ return out;
98
+ }
99
+ // Re-insert the extracted unknown elements at their original positions, in
100
+ // extraction (document) order so every path's ancestor indices are already
101
+ // restored by the time it is replayed.
102
+ function spliceUnknownElements(design, extracted) {
103
+ for (const { path, element } of extracted) {
104
+ let arr = design.pages[path[0]].children;
105
+ for (const idx of path.slice(1, -1))
106
+ arr = arr[idx].children;
107
+ arr.splice(path[path.length - 1], 0, element);
108
+ }
109
+ }
110
+ // Restore client-owned content from the CALLER's original input: keys the
111
+ // schema stripped as unrecognized come back (ad-hoc extension fields), and
112
+ // kept unknown-type elements become shallow copies of the caller's objects
113
+ // (keeping the working copy's filled `id`). `custom` needs no special path —
114
+ // it is JSON-like data by contract and the schema keeps it everywhere
115
+ // (z.unknown()), so it survives the round-trip + validation on its own.
116
+ // Runs AFTER unknown elements are spliced back: the parsed arrays then equal
117
+ // the original minus nullish entries, which the walk skips.
118
+ function restoreClientData(original, design) {
119
+ const restoreKeys = (orig, parsed) => {
120
+ for (const key of Object.keys(orig)) {
121
+ if (orig[key] != null && !(key in parsed))
122
+ parsed[key] = orig[key];
47
123
  }
48
124
  };
49
- if (Array.isArray(clone.pages))
50
- clone.pages.forEach(ensure);
51
- return clone;
125
+ // Flat record lists (table cells, audio tracks): restore keys per entry.
126
+ const walkRecords = (origList, parsedList) => {
127
+ let j = 0;
128
+ for (const orig of origList) {
129
+ if (orig == null)
130
+ continue;
131
+ const parsed = parsedList[j++];
132
+ if (typeof orig === 'object' && parsed)
133
+ restoreKeys(orig, parsed);
134
+ }
135
+ };
136
+ const walkElements = (origList, parsedList) => {
137
+ let j = 0;
138
+ for (const orig of origList) {
139
+ if (orig == null)
140
+ continue;
141
+ const parsed = parsedList[j++];
142
+ if (typeof orig !== 'object' || !parsed)
143
+ continue;
144
+ if (!KNOWN_ELEMENT_TYPES.has(orig.type)) {
145
+ // Unknown type: hand the caller's element through (shallow copy so
146
+ // the filled `id` never mutates the caller's input).
147
+ parsedList[j - 1] = { ...orig, id: parsed.id ?? orig.id };
148
+ continue;
149
+ }
150
+ restoreKeys(orig, parsed);
151
+ if (Array.isArray(orig.children) && Array.isArray(parsed.children)) {
152
+ walkElements(orig.children, parsed.children);
153
+ }
154
+ if (Array.isArray(orig.cells) && Array.isArray(parsed.cells)) {
155
+ walkRecords(orig.cells, parsed.cells);
156
+ }
157
+ }
158
+ };
159
+ restoreKeys(original, design);
160
+ if (Array.isArray(original.audios) && Array.isArray(design.audios)) {
161
+ walkRecords(original.audios, design.audios);
162
+ }
163
+ if (!Array.isArray(original.pages))
164
+ return;
165
+ let p = 0;
166
+ for (const origPage of original.pages) {
167
+ if (origPage == null)
168
+ continue;
169
+ const page = design.pages[p++];
170
+ if (typeof origPage !== 'object' || !page)
171
+ continue;
172
+ restoreKeys(origPage, page);
173
+ if (Array.isArray(origPage.children) && Array.isArray(page.children)) {
174
+ walkElements(origPage.children, page.children);
175
+ }
176
+ }
52
177
  }
53
178
  /**
54
179
  * The one entry a consumer should use to accept design JSON: validate, then
@@ -57,15 +182,36 @@ function withFilledIds(input) {
57
182
  * with `assertValidDesign`.
58
183
  */
59
184
  export function parseDesign(input, opts = {}) {
60
- if (opts.fillMissingIds)
61
- input = withFilledIds(input);
62
- // Both `assertValidDesign` and the schema's parse drop null-valued fields
63
- // (treating them as "unset", e.g. `dpi: null`) so they agree on what's valid.
64
- assertValidDesign(input, opts);
65
- const design = designSchemaLenient.parse(cloneDropNulls(input));
185
+ const original = input;
186
+ // Migrate first, so the pre-transforms and the validation below see the
187
+ // current format. The result is ALSO the working copy they mutate in place:
188
+ // migrateDesign deep-clones via a JSON round-trip, which is not just a copy —
189
+ // it coerces NaN/Infinity to null exactly like real store serialization, and
190
+ // exporter tolerance tests pin that (pdf dpi.test.js). So the caller's input
191
+ // is never touched and nothing needs cloning again below.
192
+ const migrated = migrateDesign(input);
193
+ const pre = (opts.preserveClientData || opts.fillMissingIds) &&
194
+ migrated &&
195
+ typeof migrated === 'object';
196
+ let extracted = [];
197
+ if (pre) {
198
+ // fillIds first so unknown elements get ids too, numbered off the full
199
+ // tree (extraction would hide them from the structural paths).
200
+ if (opts.fillMissingIds)
201
+ fillIds(migrated);
202
+ if (opts.preserveClientData)
203
+ extracted = extractUnknownElements(migrated);
204
+ }
205
+ // Single schema pass: validates (drops null-valued fields, so it agrees
206
+ // with the core store on what's valid) and fills defaults in one parse.
207
+ const design = parseValidDesign(migrated, opts);
208
+ if (pre && opts.preserveClientData) {
209
+ if (extracted.length)
210
+ spliceUnknownElements(design, extracted);
211
+ restoreClientData(original, design);
212
+ }
66
213
  if (opts.requirePages && design.pages.length === 0) {
67
214
  throw polotnoError('DESIGN_INVALID', 'Invalid Polotno design: no pages — did you pass `store.toJSON()`?', { errors: [{ path: 'pages', message: 'no pages' }] });
68
215
  }
69
216
  return design;
70
217
  }
71
- //# sourceMappingURL=normalize.js.map
package/lib/schema.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { z } from 'zod';
2
2
  export declare const CURRENT_SCHEMA_VERSION = 4;
3
+ export declare const ELEMENT_TYPES: readonly ["text", "image", "svg", "line", "figure", "gif", "video", "table", "group"];
3
4
  /** Non-strict: strips unknown keys, fills defaults. `normalizeDesign` uses this. */
4
5
  export declare const designSchemaLenient: z.ZodObject<{
5
6
  schemaVersion: z.ZodDefault<z.ZodNumber>;
@@ -39,6 +40,7 @@ export declare const designSchemaLenient: z.ZodObject<{
39
40
  }, z.core.$strip>>>;
40
41
  audios: z.ZodDefault<z.ZodArray<z.ZodObject<{
41
42
  id: z.ZodString;
43
+ name: z.ZodDefault<z.ZodString>;
42
44
  src: z.ZodDefault<z.ZodString>;
43
45
  duration: z.ZodDefault<z.ZodNumber>;
44
46
  startTime: z.ZodDefault<z.ZodNumber>;
@@ -98,6 +100,7 @@ export declare const designSchemaCanonical: z.ZodObject<{
98
100
  }, z.core.$strip>>>;
99
101
  audios: z.ZodDefault<z.ZodArray<z.ZodObject<{
100
102
  id: z.ZodString;
103
+ name: z.ZodDefault<z.ZodString>;
101
104
  src: z.ZodDefault<z.ZodString>;
102
105
  duration: z.ZodDefault<z.ZodNumber>;
103
106
  startTime: z.ZodDefault<z.ZodNumber>;
@@ -682,6 +685,7 @@ export declare const leafSchemas: {
682
685
  }, z.core.$strip>;
683
686
  audio: z.ZodObject<{
684
687
  id: z.ZodString;
688
+ name: z.ZodDefault<z.ZodString>;
685
689
  src: z.ZodDefault<z.ZodString>;
686
690
  duration: z.ZodDefault<z.ZodNumber>;
687
691
  startTime: z.ZodDefault<z.ZodNumber>;
@@ -706,4 +710,13 @@ export interface ValidateOptions {
706
710
  export declare function cloneDropNulls(value: any): any;
707
711
  export declare function validateDesign(input: unknown, opts?: ValidateOptions): ValidationResult;
708
712
  export declare function assertValidDesign(input: unknown, opts?: ValidateOptions): void;
709
- //# sourceMappingURL=schema.d.ts.map
713
+ /**
714
+ * Validate AND normalize in a single schema pass (safeParse both raises the
715
+ * same DESIGN_INVALID as `assertValidDesign` and returns the defaults-filled
716
+ * result). The only other copy on this path is the one `migrateDesign` makes,
717
+ * which parseDesign reuses as its working copy rather than cloning again.
718
+ * For canonical mode the single pass is equally faithful: input that passes
719
+ * the strict schema has no unknown keys, so its parse result equals the
720
+ * lenient one.
721
+ */
722
+ export declare function parseValidDesign(input: unknown, opts?: ValidateOptions): unknown;