@es3d/es3d 1.0.0 → 1.0.2

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 (80) hide show
  1. package/LICENSE +201 -201
  2. package/README.md +95 -86
  3. package/docs/SPEC.md +426 -417
  4. package/package.json +1 -1
  5. package/scripts/es3d-cli.mjs +390 -377
  6. package/src/cache/geometry-store.js +392 -392
  7. package/src/cache/mesh-bundle.js +123 -123
  8. package/src/cache/sha256.js +73 -73
  9. package/src/format/ast.js +238 -238
  10. package/src/format/colors.js +93 -93
  11. package/src/format/compact-parser.js +171 -171
  12. package/src/format/compact-tokenizer.js +165 -165
  13. package/src/format/errors.js +247 -247
  14. package/src/format/json.js +55 -55
  15. package/src/format/limits.js +14 -14
  16. package/src/format/parse.js +132 -92
  17. package/src/format/schema.js +617 -617
  18. package/src/format/serializer.js +333 -333
  19. package/src/format/validator.js +330 -330
  20. package/src/format/value-error.js +12 -12
  21. package/src/format/value-format.js +314 -314
  22. package/src/format/values.js +459 -459
  23. package/src/format/xml-parser.js +136 -136
  24. package/src/format/xml-tokenizer.js +237 -237
  25. package/src/geometry/contour.js +86 -86
  26. package/src/geometry/extrude.js +175 -175
  27. package/src/geometry/gear.js +85 -85
  28. package/src/geometry/geometry-cache.js +159 -159
  29. package/src/geometry/lod-error.js +178 -178
  30. package/src/geometry/mesh.js +458 -458
  31. package/src/geometry/primitives.js +299 -299
  32. package/src/geometry/registry.js +645 -645
  33. package/src/geometry/revolve.js +136 -136
  34. package/src/geometry/sweep.js +441 -441
  35. package/src/index.js +47 -47
  36. package/src/io/compression.js +67 -67
  37. package/src/io/convert.js +236 -236
  38. package/src/io/download.js +13 -13
  39. package/src/io/external-scene.js +127 -127
  40. package/src/io/file-loader.js +28 -28
  41. package/src/io/gltf-pack.js +1461 -0
  42. package/src/io/gltf.js +630 -630
  43. package/src/io/mesh-import.js +104 -104
  44. package/src/io/obj.js +352 -352
  45. package/src/io/step-brep.js +439 -439
  46. package/src/io/step-exact.js +1149 -1149
  47. package/src/io/step.js +1418 -1418
  48. package/src/io/stl.js +193 -193
  49. package/src/io/svg-import.js +787 -787
  50. package/src/material/materials.js +154 -154
  51. package/src/math/mat4.js +475 -475
  52. package/src/math/random.js +30 -30
  53. package/src/math/trig.js +65 -65
  54. package/src/math/vec3.js +81 -81
  55. package/src/optimize/optimizer.js +604 -579
  56. package/src/path/path-flatten.js +322 -322
  57. package/src/path/path-parser.js +332 -332
  58. package/src/path/shapes.js +129 -129
  59. package/src/path/triangulate.js +517 -517
  60. package/src/pipeline.js +74 -74
  61. package/src/render/camera.js +168 -168
  62. package/src/render/frame-builder.js +362 -362
  63. package/src/render/geometry-pool.js +149 -149
  64. package/src/render/lighting.js +149 -149
  65. package/src/render/orbit-controls.js +237 -237
  66. package/src/render/renderer.js +258 -249
  67. package/src/render/scroll-timeline.js +104 -104
  68. package/src/render/shaders/glsl.js +285 -285
  69. package/src/render/shaders/wgsl.js +252 -252
  70. package/src/render/stage.js +365 -352
  71. package/src/render/texture-cache.js +40 -40
  72. package/src/render/textures.js +223 -223
  73. package/src/render/webgl2/webgl2-backend.js +586 -532
  74. package/src/render/webgpu/webgpu-backend.js +482 -480
  75. package/src/scene/flatten.js +754 -754
  76. package/src/scene/picking.js +161 -161
  77. package/src/scene/scene-graph.js +320 -320
  78. package/src/transform/transform.js +211 -211
  79. package/src/wasm/kernels-binary.js +3 -3
  80. package/src/wasm/kernels.js +385 -385
@@ -1,333 +1,333 @@
1
- // Serialization of the ES3D AST to text.
2
- //
3
- // serialize(doc, { syntax: 'xml' | 'compact' | 'json', pretty, aliases, precision, comments })
4
- //
5
- // pretty : indentation, one element per line, comments kept (default true)
6
- // aliases : use the short attribute aliases (p, r, s, m, ...) (default !pretty)
7
- // precision: quantize numbers to this many decimals (null = keep source values)
8
- // normalize: re-format typed values canonically (implied by precision / !pretty)
9
- //
10
- // Without precision/normalize the original attribute strings are written
11
- // unchanged, so load -> save is lossless.
12
-
13
- import { elementSpec, attrSpec } from './schema.js';
14
- import { formatNumber, formatNumberList, formatColor, formatTransformOps, formatPathData } from './value-format.js';
15
- import { toJsonTree } from './json.js';
16
-
17
- const PRESETS = {
18
- pretty: { pretty: true, aliases: false, precision: null, normalize: false, comments: true },
19
- minified: { pretty: false, aliases: true, precision: null, normalize: true, comments: false },
20
- };
21
-
22
- function resolveOptions(opts = {}) {
23
- const base = opts.pretty === false ? PRESETS.minified : PRESETS.pretty;
24
- const o = { syntax: 'xml', indent: ' ', wrap: 100, ...base, ...opts };
25
- if (o.precision !== null && o.precision !== undefined) o.normalize = true;
26
- return o;
27
- }
28
-
29
- /** Canonical (or aliased) attribute name for output. */
30
- function outName(elName, canonical, opts) {
31
- if (!opts.aliases) return canonical;
32
- const spec = attrSpec(elName, canonical);
33
- return spec && spec.alias ? spec.alias : canonical;
34
- }
35
-
36
- function canonicalName(el, a) {
37
- if (el.attrIndex) {
38
- for (const [k, v] of Object.entries(el.attrIndex)) if (v === a) return k;
39
- }
40
- const spec = elementSpec(el.name);
41
- if (!spec) return a.name;
42
- if (spec.attrs[a.name]) return a.name;
43
- for (const [k, s] of Object.entries(spec.attrs)) if (s.alias === a.name) return k;
44
- return a.name;
45
- }
46
-
47
- const allEqual = (v) => v.every((x) => x === v[0]);
48
-
49
- /** Format an attribute value, re-encoding typed values when normalizing. */
50
- export function formatAttrValue(el, canonical, raw, opts) {
51
- if (!opts.normalize) return raw;
52
- const spec = attrSpec(el.name, canonical);
53
- const v = el.values ? el.values[canonical] : undefined;
54
- if (!spec || v === undefined) return raw.trim();
55
- const p = opts.precision;
56
- const c = !opts.pretty;
57
- switch (spec.type) {
58
- case 'number':
59
- case 'angle':
60
- return formatNumber(v, p, c);
61
- case 'int':
62
- return String(v);
63
- case 'vec2':
64
- case 'vec3':
65
- case 'vec4':
66
- case 'numbers':
67
- case 'animValue':
68
- return formatNumberList(v, { sep: ',', precision: p, compact: c });
69
- case 'keyframes':
70
- return v.map((k) => formatNumberList(k, { sep: ',', precision: p, compact: c })).join(c ? ';' : '; ');
71
- case 'size2':
72
- case 'size3':
73
- case 'scale3':
74
- return allEqual(v) ? formatNumber(v[0], p, c) : formatNumberList(v, { sep: ',', precision: p, compact: c });
75
- case 'count2':
76
- return v.join(',');
77
- case 'points2':
78
- return formatNumberList(v, { group: 2, precision: p, compact: c });
79
- case 'points3':
80
- return formatNumberList(v, { group: 3, precision: p, compact: c });
81
- case 'floats':
82
- return formatNumberList(v, { sep: ' ', precision: p, compact: c });
83
- case 'indices':
84
- return Array.from(v).join(' ');
85
- case 'color': {
86
- const hex = formatColor(v);
87
- const r = raw.trim();
88
- return r.length < hex.length ? r : hex;
89
- }
90
- case 'ref':
91
- case 'id':
92
- case 'enum':
93
- case 'string':
94
- return String(v);
95
- case 'bool':
96
- return v ? 'true' : 'false';
97
- case 'transform':
98
- return formatTransformOps(v.ops, p, c);
99
- case 'path2d':
100
- return formatPathData(v.segments, { precision: p, minify: c, dim: 2 });
101
- case 'spine':
102
- if (v.kind === 'path') return formatPathData(v.segments, { precision: p, minify: c, dim: 3 });
103
- if (v.kind === 'points') return formatNumberList(v.points, { group: 3, precision: p, compact: c });
104
- return `helix(${[v.radius, v.pitch, v.turns, ...(v.segmentsPerTurn ? [v.segmentsPerTurn] : [])].map((x) => formatNumber(x, p, c)).join(',')})`;
105
- case 'range': {
106
- const [a, b] = v;
107
- return a === b ? formatNumber(a, p, c) : `${formatNumber(a, p, c)}..${formatNumber(b, p, c)}`;
108
- }
109
- case 'range3': {
110
- const f = ([a, b]) => (a === b ? formatNumber(a, p, c) : `${formatNumber(a, p, c)}..${formatNumber(b, p, c)}`);
111
- return v.ranges.map(f).join(',');
112
- }
113
- case 'idlist':
114
- return v.join(',');
115
- case 'duration':
116
- return formatNumber(v, p, c) + 's';
117
- case 'repeatCount':
118
- return v === Infinity ? 'indefinite' : formatNumber(v, p, c);
119
- default:
120
- return raw.trim();
121
- }
122
- }
123
-
124
- // ---------------------------------------------------------------------------
125
- // markup syntax
126
-
127
- function escAttr(s) {
128
- return s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/"/g, '&quot;');
129
- }
130
- function escText(s) {
131
- return s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
132
- }
133
- function xmlComment(text) {
134
- return `<!--${text.replace(/--/g, '- -').replace(/-$/, '- ')}-->`;
135
- }
136
-
137
- function attrPairs(el, opts) {
138
- const out = [];
139
- for (const a of el.attrs) {
140
- const canonical = canonicalName(el, a);
141
- out.push([outName(el.name, canonical, opts), formatAttrValue(el, canonical, a.value, opts), canonical]);
142
- }
143
- return out;
144
- }
145
-
146
- function serializeXml(doc, opts) {
147
- const lines = [];
148
- const ind = (d) => opts.indent.repeat(d);
149
- if (opts.pretty) {
150
- if (opts.comments) for (const c of doc.leading) lines.push(xmlComment(c.text));
151
- const emit = (el, depth) => {
152
- const pairs = attrPairs(el, opts);
153
- const attrsInline = pairs.map(([k, v]) => ` ${k}="${escAttr(v)}"`).join('');
154
- const kids = el.children.filter((c) => c.type === 'element' || opts.comments);
155
- const hasText = el.text !== null && el.text !== undefined && el.text.trim() !== '';
156
- let open = `${ind(depth)}<${el.name}${attrsInline}`;
157
- if (open.length + 2 > opts.wrap && pairs.length > 1) {
158
- open = `${ind(depth)}<${el.name}` + pairs.map(([k, v]) => `\n${ind(depth + 2)}${k}="${escAttr(v)}"`).join('');
159
- }
160
- if (!kids.length && !hasText) {
161
- lines.push(open + '/>');
162
- return;
163
- }
164
- if (hasText && !kids.length) {
165
- lines.push(`${open}>${escText(el.text.trim())}</${el.name}>`);
166
- return;
167
- }
168
- lines.push(open + '>');
169
- if (hasText) lines.push(ind(depth + 1) + escText(el.text.trim()));
170
- for (const c of kids) {
171
- if (c.type === 'comment') lines.push(ind(depth + 1) + xmlComment(c.text));
172
- else emit(c, depth + 1);
173
- }
174
- lines.push(`${ind(depth)}</${el.name}>`);
175
- };
176
- emit(doc.root, 0);
177
- if (opts.comments) for (const c of doc.trailing) lines.push(xmlComment(c.text));
178
- return lines.join('\n') + '\n';
179
- }
180
- // minified
181
- let out = '';
182
- const emit = (el) => {
183
- out += '<' + el.name;
184
- for (const [k, v] of attrPairs(el, opts)) out += ` ${k}="${escAttr(v)}"`;
185
- const kids = el.children.filter((c) => c.type === 'element' || opts.comments);
186
- const hasText = el.text !== null && el.text !== undefined && el.text.trim() !== '';
187
- if (!kids.length && !hasText) {
188
- out += '/>';
189
- return;
190
- }
191
- out += '>';
192
- if (hasText) out += escText(el.text.trim());
193
- for (const c of kids) {
194
- if (c.type === 'comment') out += xmlComment(c.text);
195
- else emit(c);
196
- }
197
- out += `</${el.name}>`;
198
- };
199
- emit(doc.root);
200
- return out;
201
- }
202
-
203
- // ---------------------------------------------------------------------------
204
- // compact syntax
205
-
206
- const NAME_RE = /^[A-Za-z_][A-Za-z0-9_.:-]*$/;
207
-
208
- function quoteCompact(v) {
209
- if (v !== '' && !/[\s{};"\\]/.test(v)) return v;
210
- return '"' + v.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\n/g, '\\n').replace(/\t/g, '\\t') + '"';
211
- }
212
-
213
- function compactComment(text, pretty) {
214
- if (pretty && !text.includes('\n')) return '//' + (text.startsWith(' ') ? '' : ' ') + text.replace(/\s+$/, '');
215
- return '/*' + text.replace(/\*\//g, '* /') + '*/';
216
- }
217
-
218
- function compactHeader(el, opts) {
219
- let s = el.name;
220
- const rest = [];
221
- for (const [k, v, canonical] of attrPairs(el, opts)) {
222
- if (canonical === 'id' && NAME_RE.test(v)) s += '#' + v;
223
- else if (canonical === 'ref' && NAME_RE.test(v)) rest.unshift('@' + v);
224
- else rest.push(`${k}=${quoteCompact(v)}`);
225
- }
226
- const hasText = el.text !== null && el.text !== undefined && el.text.trim() !== '';
227
- if (hasText) {
228
- const t = el.text.trim();
229
- rest.unshift('"' + t.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\n/g, '\\n').replace(/\t/g, '\\t') + '"');
230
- }
231
- return rest.length ? s + ' ' + rest.join(' ') : s;
232
- }
233
-
234
- function serializeCompact(doc, opts) {
235
- if (opts.pretty) {
236
- const lines = [];
237
- const ind = (d) => opts.indent.repeat(d);
238
- if (opts.comments) for (const c of doc.leading) lines.push(compactComment(c.text, true));
239
- const emitChildren = (el, depth) => {
240
- for (const c of el.children) {
241
- if (c.type === 'comment') {
242
- if (opts.comments) lines.push(ind(depth) + compactComment(c.text, true));
243
- continue;
244
- }
245
- const kids = c.children.filter((k) => k.type === 'element' || opts.comments);
246
- const head = ind(depth) + compactHeader(c, opts);
247
- if (!kids.length) lines.push(head);
248
- else {
249
- lines.push(head + ' {');
250
- emitChildren(c, depth + 1);
251
- lines.push(ind(depth) + '}');
252
- }
253
- }
254
- };
255
- lines.push(compactHeader(doc.root, opts));
256
- emitChildren(doc.root, 0);
257
- if (opts.comments) for (const c of doc.trailing) lines.push(compactComment(c.text, true));
258
- return lines.join('\n') + '\n';
259
- }
260
- const parts = [];
261
- const emit = (el) => {
262
- let s = compactHeader(el, opts);
263
- const kids = el.children.filter((k) => k.type === 'element' || opts.comments);
264
- if (kids.length) {
265
- const inner = [];
266
- for (const c of kids) inner.push(c.type === 'comment' ? compactComment(c.text, false) : emit(c));
267
- s += '{' + joinStatements(inner) + '}';
268
- }
269
- return s;
270
- };
271
- parts.push(compactHeader(doc.root, opts));
272
- for (const c of doc.root.children) {
273
- if (c.type === 'comment') {
274
- if (opts.comments) parts.push(compactComment(c.text, false));
275
- } else parts.push(emit(c));
276
- }
277
- return joinStatements(parts);
278
- }
279
-
280
- /** Join compact statements; a separator is needed only between two plain headers. */
281
- function joinStatements(items) {
282
- let out = '';
283
- for (let i = 0; i < items.length; i++) {
284
- const s = items[i];
285
- if (i > 0) {
286
- const prev = items[i - 1];
287
- if (!prev.endsWith('}') && !prev.endsWith('*/')) out += ';';
288
- }
289
- out += s;
290
- }
291
- return out;
292
- }
293
-
294
- // ---------------------------------------------------------------------------
295
-
296
- /**
297
- * Serialize a document.
298
- * @param {import('./ast.js').Document} doc
299
- * @param {object} [options]
300
- * @returns {string}
301
- */
302
- export function serialize(doc, options = {}) {
303
- const opts = resolveOptions(options);
304
- if (!doc.root) throw new Error('Cannot serialize a document without a root element.');
305
- if (opts.syntax === 'compact') return serializeCompact(doc, opts);
306
- if (opts.syntax === 'json') {
307
- const workDoc = opts.normalize ? normalizedCopy(doc, opts) : doc;
308
- const tree = toJsonTree(workDoc, { comments: opts.comments });
309
- return opts.pretty ? JSON.stringify(tree, null, 1) + '\n' : JSON.stringify(tree);
310
- }
311
- return serializeXml(doc, opts);
312
- }
313
-
314
- /** Copy of the AST where attribute values are already formatted per opts. */
315
- function normalizedCopy(doc, opts) {
316
- const clone = (el) => {
317
- const pairs = attrPairs(el, opts);
318
- return {
319
- ...el,
320
- attrs: pairs.map(([k, v]) => ({ name: k, value: v })),
321
- children: el.children.map((c) => (c.type === 'element' ? clone(c) : c)),
322
- };
323
- };
324
- return { ...doc, root: clone(doc.root) };
325
- }
326
-
327
- export const SERIALIZE_PRESETS = {
328
- 'xml-pretty': { syntax: 'xml', pretty: true },
329
- 'xml-min': { syntax: 'xml', pretty: false },
330
- 'compact-pretty': { syntax: 'compact', pretty: true },
331
- 'compact-min': { syntax: 'compact', pretty: false },
332
- 'json-min': { syntax: 'json', pretty: false },
333
- };
1
+ // Serialization of the ES3D AST to text.
2
+ //
3
+ // serialize(doc, { syntax: 'xml' | 'compact' | 'json', pretty, aliases, precision, comments })
4
+ //
5
+ // pretty : indentation, one element per line, comments kept (default true)
6
+ // aliases : use the short attribute aliases (p, r, s, m, ...) (default !pretty)
7
+ // precision: quantize numbers to this many decimals (null = keep source values)
8
+ // normalize: re-format typed values canonically (implied by precision / !pretty)
9
+ //
10
+ // Without precision/normalize the original attribute strings are written
11
+ // unchanged, so load -> save is lossless.
12
+
13
+ import { elementSpec, attrSpec } from './schema.js';
14
+ import { formatNumber, formatNumberList, formatColor, formatTransformOps, formatPathData } from './value-format.js';
15
+ import { toJsonTree } from './json.js';
16
+
17
+ const PRESETS = {
18
+ pretty: { pretty: true, aliases: false, precision: null, normalize: false, comments: true },
19
+ minified: { pretty: false, aliases: true, precision: null, normalize: true, comments: false },
20
+ };
21
+
22
+ function resolveOptions(opts = {}) {
23
+ const base = opts.pretty === false ? PRESETS.minified : PRESETS.pretty;
24
+ const o = { syntax: 'xml', indent: ' ', wrap: 100, ...base, ...opts };
25
+ if (o.precision !== null && o.precision !== undefined) o.normalize = true;
26
+ return o;
27
+ }
28
+
29
+ /** Canonical (or aliased) attribute name for output. */
30
+ function outName(elName, canonical, opts) {
31
+ if (!opts.aliases) return canonical;
32
+ const spec = attrSpec(elName, canonical);
33
+ return spec && spec.alias ? spec.alias : canonical;
34
+ }
35
+
36
+ function canonicalName(el, a) {
37
+ if (el.attrIndex) {
38
+ for (const [k, v] of Object.entries(el.attrIndex)) if (v === a) return k;
39
+ }
40
+ const spec = elementSpec(el.name);
41
+ if (!spec) return a.name;
42
+ if (spec.attrs[a.name]) return a.name;
43
+ for (const [k, s] of Object.entries(spec.attrs)) if (s.alias === a.name) return k;
44
+ return a.name;
45
+ }
46
+
47
+ const allEqual = (v) => v.every((x) => x === v[0]);
48
+
49
+ /** Format an attribute value, re-encoding typed values when normalizing. */
50
+ export function formatAttrValue(el, canonical, raw, opts) {
51
+ if (!opts.normalize) return raw;
52
+ const spec = attrSpec(el.name, canonical);
53
+ const v = el.values ? el.values[canonical] : undefined;
54
+ if (!spec || v === undefined) return raw.trim();
55
+ const p = opts.precision;
56
+ const c = !opts.pretty;
57
+ switch (spec.type) {
58
+ case 'number':
59
+ case 'angle':
60
+ return formatNumber(v, p, c);
61
+ case 'int':
62
+ return String(v);
63
+ case 'vec2':
64
+ case 'vec3':
65
+ case 'vec4':
66
+ case 'numbers':
67
+ case 'animValue':
68
+ return formatNumberList(v, { sep: ',', precision: p, compact: c });
69
+ case 'keyframes':
70
+ return v.map((k) => formatNumberList(k, { sep: ',', precision: p, compact: c })).join(c ? ';' : '; ');
71
+ case 'size2':
72
+ case 'size3':
73
+ case 'scale3':
74
+ return allEqual(v) ? formatNumber(v[0], p, c) : formatNumberList(v, { sep: ',', precision: p, compact: c });
75
+ case 'count2':
76
+ return v.join(',');
77
+ case 'points2':
78
+ return formatNumberList(v, { group: 2, precision: p, compact: c });
79
+ case 'points3':
80
+ return formatNumberList(v, { group: 3, precision: p, compact: c });
81
+ case 'floats':
82
+ return formatNumberList(v, { sep: ' ', precision: p, compact: c });
83
+ case 'indices':
84
+ return Array.from(v).join(' ');
85
+ case 'color': {
86
+ const hex = formatColor(v);
87
+ const r = raw.trim();
88
+ return r.length < hex.length ? r : hex;
89
+ }
90
+ case 'ref':
91
+ case 'id':
92
+ case 'enum':
93
+ case 'string':
94
+ return String(v);
95
+ case 'bool':
96
+ return v ? 'true' : 'false';
97
+ case 'transform':
98
+ return formatTransformOps(v.ops, p, c);
99
+ case 'path2d':
100
+ return formatPathData(v.segments, { precision: p, minify: c, dim: 2 });
101
+ case 'spine':
102
+ if (v.kind === 'path') return formatPathData(v.segments, { precision: p, minify: c, dim: 3 });
103
+ if (v.kind === 'points') return formatNumberList(v.points, { group: 3, precision: p, compact: c });
104
+ return `helix(${[v.radius, v.pitch, v.turns, ...(v.segmentsPerTurn ? [v.segmentsPerTurn] : [])].map((x) => formatNumber(x, p, c)).join(',')})`;
105
+ case 'range': {
106
+ const [a, b] = v;
107
+ return a === b ? formatNumber(a, p, c) : `${formatNumber(a, p, c)}..${formatNumber(b, p, c)}`;
108
+ }
109
+ case 'range3': {
110
+ const f = ([a, b]) => (a === b ? formatNumber(a, p, c) : `${formatNumber(a, p, c)}..${formatNumber(b, p, c)}`);
111
+ return v.ranges.map(f).join(',');
112
+ }
113
+ case 'idlist':
114
+ return v.join(',');
115
+ case 'duration':
116
+ return formatNumber(v, p, c) + 's';
117
+ case 'repeatCount':
118
+ return v === Infinity ? 'indefinite' : formatNumber(v, p, c);
119
+ default:
120
+ return raw.trim();
121
+ }
122
+ }
123
+
124
+ // ---------------------------------------------------------------------------
125
+ // markup syntax
126
+
127
+ function escAttr(s) {
128
+ return s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/"/g, '&quot;');
129
+ }
130
+ function escText(s) {
131
+ return s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
132
+ }
133
+ function xmlComment(text) {
134
+ return `<!--${text.replace(/--/g, '- -').replace(/-$/, '- ')}-->`;
135
+ }
136
+
137
+ function attrPairs(el, opts) {
138
+ const out = [];
139
+ for (const a of el.attrs) {
140
+ const canonical = canonicalName(el, a);
141
+ out.push([outName(el.name, canonical, opts), formatAttrValue(el, canonical, a.value, opts), canonical]);
142
+ }
143
+ return out;
144
+ }
145
+
146
+ function serializeXml(doc, opts) {
147
+ const lines = [];
148
+ const ind = (d) => opts.indent.repeat(d);
149
+ if (opts.pretty) {
150
+ if (opts.comments) for (const c of doc.leading) lines.push(xmlComment(c.text));
151
+ const emit = (el, depth) => {
152
+ const pairs = attrPairs(el, opts);
153
+ const attrsInline = pairs.map(([k, v]) => ` ${k}="${escAttr(v)}"`).join('');
154
+ const kids = el.children.filter((c) => c.type === 'element' || opts.comments);
155
+ const hasText = el.text !== null && el.text !== undefined && el.text.trim() !== '';
156
+ let open = `${ind(depth)}<${el.name}${attrsInline}`;
157
+ if (open.length + 2 > opts.wrap && pairs.length > 1) {
158
+ open = `${ind(depth)}<${el.name}` + pairs.map(([k, v]) => `\n${ind(depth + 2)}${k}="${escAttr(v)}"`).join('');
159
+ }
160
+ if (!kids.length && !hasText) {
161
+ lines.push(open + '/>');
162
+ return;
163
+ }
164
+ if (hasText && !kids.length) {
165
+ lines.push(`${open}>${escText(el.text.trim())}</${el.name}>`);
166
+ return;
167
+ }
168
+ lines.push(open + '>');
169
+ if (hasText) lines.push(ind(depth + 1) + escText(el.text.trim()));
170
+ for (const c of kids) {
171
+ if (c.type === 'comment') lines.push(ind(depth + 1) + xmlComment(c.text));
172
+ else emit(c, depth + 1);
173
+ }
174
+ lines.push(`${ind(depth)}</${el.name}>`);
175
+ };
176
+ emit(doc.root, 0);
177
+ if (opts.comments) for (const c of doc.trailing) lines.push(xmlComment(c.text));
178
+ return lines.join('\n') + '\n';
179
+ }
180
+ // minified
181
+ let out = '';
182
+ const emit = (el) => {
183
+ out += '<' + el.name;
184
+ for (const [k, v] of attrPairs(el, opts)) out += ` ${k}="${escAttr(v)}"`;
185
+ const kids = el.children.filter((c) => c.type === 'element' || opts.comments);
186
+ const hasText = el.text !== null && el.text !== undefined && el.text.trim() !== '';
187
+ if (!kids.length && !hasText) {
188
+ out += '/>';
189
+ return;
190
+ }
191
+ out += '>';
192
+ if (hasText) out += escText(el.text.trim());
193
+ for (const c of kids) {
194
+ if (c.type === 'comment') out += xmlComment(c.text);
195
+ else emit(c);
196
+ }
197
+ out += `</${el.name}>`;
198
+ };
199
+ emit(doc.root);
200
+ return out;
201
+ }
202
+
203
+ // ---------------------------------------------------------------------------
204
+ // compact syntax
205
+
206
+ const NAME_RE = /^[A-Za-z_][A-Za-z0-9_.:-]*$/;
207
+
208
+ function quoteCompact(v) {
209
+ if (v !== '' && !/[\s{};"\\]/.test(v)) return v;
210
+ return '"' + v.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\n/g, '\\n').replace(/\t/g, '\\t') + '"';
211
+ }
212
+
213
+ function compactComment(text, pretty) {
214
+ if (pretty && !text.includes('\n')) return '//' + (text.startsWith(' ') ? '' : ' ') + text.replace(/\s+$/, '');
215
+ return '/*' + text.replace(/\*\//g, '* /') + '*/';
216
+ }
217
+
218
+ function compactHeader(el, opts) {
219
+ let s = el.name;
220
+ const rest = [];
221
+ for (const [k, v, canonical] of attrPairs(el, opts)) {
222
+ if (canonical === 'id' && NAME_RE.test(v)) s += '#' + v;
223
+ else if (canonical === 'ref' && NAME_RE.test(v)) rest.unshift('@' + v);
224
+ else rest.push(`${k}=${quoteCompact(v)}`);
225
+ }
226
+ const hasText = el.text !== null && el.text !== undefined && el.text.trim() !== '';
227
+ if (hasText) {
228
+ const t = el.text.trim();
229
+ rest.unshift('"' + t.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\n/g, '\\n').replace(/\t/g, '\\t') + '"');
230
+ }
231
+ return rest.length ? s + ' ' + rest.join(' ') : s;
232
+ }
233
+
234
+ function serializeCompact(doc, opts) {
235
+ if (opts.pretty) {
236
+ const lines = [];
237
+ const ind = (d) => opts.indent.repeat(d);
238
+ if (opts.comments) for (const c of doc.leading) lines.push(compactComment(c.text, true));
239
+ const emitChildren = (el, depth) => {
240
+ for (const c of el.children) {
241
+ if (c.type === 'comment') {
242
+ if (opts.comments) lines.push(ind(depth) + compactComment(c.text, true));
243
+ continue;
244
+ }
245
+ const kids = c.children.filter((k) => k.type === 'element' || opts.comments);
246
+ const head = ind(depth) + compactHeader(c, opts);
247
+ if (!kids.length) lines.push(head);
248
+ else {
249
+ lines.push(head + ' {');
250
+ emitChildren(c, depth + 1);
251
+ lines.push(ind(depth) + '}');
252
+ }
253
+ }
254
+ };
255
+ lines.push(compactHeader(doc.root, opts));
256
+ emitChildren(doc.root, 0);
257
+ if (opts.comments) for (const c of doc.trailing) lines.push(compactComment(c.text, true));
258
+ return lines.join('\n') + '\n';
259
+ }
260
+ const parts = [];
261
+ const emit = (el) => {
262
+ let s = compactHeader(el, opts);
263
+ const kids = el.children.filter((k) => k.type === 'element' || opts.comments);
264
+ if (kids.length) {
265
+ const inner = [];
266
+ for (const c of kids) inner.push(c.type === 'comment' ? compactComment(c.text, false) : emit(c));
267
+ s += '{' + joinStatements(inner) + '}';
268
+ }
269
+ return s;
270
+ };
271
+ parts.push(compactHeader(doc.root, opts));
272
+ for (const c of doc.root.children) {
273
+ if (c.type === 'comment') {
274
+ if (opts.comments) parts.push(compactComment(c.text, false));
275
+ } else parts.push(emit(c));
276
+ }
277
+ return joinStatements(parts);
278
+ }
279
+
280
+ /** Join compact statements; a separator is needed only between two plain headers. */
281
+ function joinStatements(items) {
282
+ let out = '';
283
+ for (let i = 0; i < items.length; i++) {
284
+ const s = items[i];
285
+ if (i > 0) {
286
+ const prev = items[i - 1];
287
+ if (!prev.endsWith('}') && !prev.endsWith('*/')) out += ';';
288
+ }
289
+ out += s;
290
+ }
291
+ return out;
292
+ }
293
+
294
+ // ---------------------------------------------------------------------------
295
+
296
+ /**
297
+ * Serialize a document.
298
+ * @param {import('./ast.js').Document} doc
299
+ * @param {object} [options]
300
+ * @returns {string}
301
+ */
302
+ export function serialize(doc, options = {}) {
303
+ const opts = resolveOptions(options);
304
+ if (!doc.root) throw new Error('Cannot serialize a document without a root element.');
305
+ if (opts.syntax === 'compact') return serializeCompact(doc, opts);
306
+ if (opts.syntax === 'json') {
307
+ const workDoc = opts.normalize ? normalizedCopy(doc, opts) : doc;
308
+ const tree = toJsonTree(workDoc, { comments: opts.comments });
309
+ return opts.pretty ? JSON.stringify(tree, null, 1) + '\n' : JSON.stringify(tree);
310
+ }
311
+ return serializeXml(doc, opts);
312
+ }
313
+
314
+ /** Copy of the AST where attribute values are already formatted per opts. */
315
+ function normalizedCopy(doc, opts) {
316
+ const clone = (el) => {
317
+ const pairs = attrPairs(el, opts);
318
+ return {
319
+ ...el,
320
+ attrs: pairs.map(([k, v]) => ({ name: k, value: v })),
321
+ children: el.children.map((c) => (c.type === 'element' ? clone(c) : c)),
322
+ };
323
+ };
324
+ return { ...doc, root: clone(doc.root) };
325
+ }
326
+
327
+ export const SERIALIZE_PRESETS = {
328
+ 'xml-pretty': { syntax: 'xml', pretty: true },
329
+ 'xml-min': { syntax: 'xml', pretty: false },
330
+ 'compact-pretty': { syntax: 'compact', pretty: true },
331
+ 'compact-min': { syntax: 'compact', pretty: false },
332
+ 'json-min': { syntax: 'json', pretty: false },
333
+ };