svg-path-interpolator 0.2.5 → 1.0.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.
@@ -0,0 +1,597 @@
1
+ import { SaxEventType } from 'sax-wasm';
2
+ import { calculators } from './math/calculators.js';
3
+ import { SVGTransform } from './math/SVGTransform.js';
4
+ const commandRegEx = /([mlcqzavhst])\s*([-+\d.eE,\s]*)/ig;
5
+ const argumentsRegEx = /[-+]?(?:\d+\.?\d*|\.\d+)(?:[eE][-+]?\d+)?/g;
6
+ const minimumSampleFrequency = 0.000001;
7
+ const numberRegEx = /[-+]?(?:\d+\.?\d*|\.\d+)(?:[eE][-+]?\d+)?/y;
8
+ const transformNames = new Set(['matrix', 'translate', 'scale', 'rotate', 'skewX', 'skewY']);
9
+ const pathArgumentCounts = {
10
+ M: 2, L: 2, H: 1, V: 1, C: 6, S: 4, Q: 4, T: 2, A: 7
11
+ };
12
+ /**
13
+ * Turns SVG path data into sampled x/y coordinate pairs.
14
+ *
15
+ * Create this class directly when you only need `interpolatePath`. Use
16
+ * `createInterpolator` when you also need to read complete SVG documents.
17
+ */
18
+ export class SVGPathInterpolator {
19
+ /**
20
+ * When trim is true, paths that were translated
21
+ * are normalized and will begin at 0,0.
22
+ *
23
+ * @var {boolean} trim
24
+ * @memberOf SVGPathInterpolator#
25
+ * @default false
26
+ */
27
+ trim = false;
28
+ /**
29
+ * minDistance is the minimum distance between the
30
+ * current and previous points when sampling.
31
+ * If a sample results in a distance less than the
32
+ * specified value, the point is discarded.
33
+ *
34
+ * @var {number} minDistance
35
+ * @memberOf SVGPathInterpolator#
36
+ * @default 0.5
37
+ */
38
+ minDistance = 0.5;
39
+ /**
40
+ * roundToNearest is useful when snapping to fractional
41
+ * pixel values. For example, if roundToNearest is .25,
42
+ * a sample resulting in the point 2.343200092,4.6100923
43
+ * will round to 2.25,4.5.
44
+ *
45
+ * @var {number} roundToNearest
46
+ * @memberOf SVGPathInterpolator#
47
+ * @default 0.25
48
+ */
49
+ roundToNearest = 0.25;
50
+ /**
51
+ * sampleFrequency determines the increment of t when sampling.
52
+ * Values must be between 0.000001 and 1, inclusive, to bound
53
+ * the amount of sampling work performed for each command.
54
+ * If sampleFrequency is set to .001 , since t iterates from
55
+ * 0 to 1, there will be 1000 points sampled per command
56
+ * but only points that are greater than minDistance are captured.
57
+ *
58
+ * @var {number} sampleFrequency
59
+ * @memberOf SVGPathInterpolator#
60
+ * @default 0.001
61
+ */
62
+ sampleFrequency = 0.001;
63
+ /**
64
+ * Maximum sample attempts for one interpolation operation.
65
+ *
66
+ * This limit includes attempts that do not produce a saved point.
67
+ */
68
+ maxSamples;
69
+ /**
70
+ * Maximum emitted coordinate pairs for one interpolation operation.
71
+ *
72
+ * This limit is shared by every path in a processed SVG document.
73
+ */
74
+ maxOutputPoints;
75
+ /**
76
+ * When true, pretty creates formatted json output.
77
+ *
78
+ * @var {boolean} pretty
79
+ * @memberOf SVGPathInterpolator#
80
+ * @default false
81
+ */
82
+ pretty = false;
83
+ /**
84
+ * Then number of spaces to indent when pretty is true.
85
+ *
86
+ * @var {int} prettyIndent
87
+ * @memberOf SVGPathInterpolator#
88
+ * @default 0
89
+ */
90
+ prettyIndent = 0;
91
+ /**
92
+ * Whether to join path data into a single flat array.
93
+ *
94
+ * @var {boolean} joinPathData
95
+ * @memberOf SVGPathInterpolator#
96
+ * @default false
97
+ */
98
+ joinPathData = false;
99
+ /**
100
+ * The SaxWasm parser instance;
101
+ * @var { SAXParser } parser
102
+ * @memberOf SVGPathInterpolator#
103
+ * @default null
104
+ */
105
+ parser;
106
+ constructor(config = {}) {
107
+ Object.assign(this, config);
108
+ this.validateNumericOptions();
109
+ }
110
+ validateNumericOptions() {
111
+ this.validateNumericOption('minDistance', this.minDistance, value => value >= 0, 'greater than or equal to 0');
112
+ this.validateNumericOption('roundToNearest', this.roundToNearest, value => value > 0, 'greater than 0');
113
+ this.validateNumericOption('sampleFrequency', this.sampleFrequency, value => value >= minimumSampleFrequency && value <= 1, `between ${minimumSampleFrequency} and 1, inclusive`);
114
+ this.validateLimit('maxSamples', this.maxSamples);
115
+ this.validateLimit('maxOutputPoints', this.maxOutputPoints);
116
+ }
117
+ validateLimit(name, value) {
118
+ if (value !== undefined && (!Number.isFinite(value) || !Number.isInteger(value) || value <= 0)) {
119
+ throw new RangeError(`${name} must be a finite positive integer`);
120
+ }
121
+ }
122
+ createSamplingBudget() {
123
+ return {
124
+ maxSamples: this.maxSamples,
125
+ maxOutputPoints: this.maxOutputPoints,
126
+ samples: 0,
127
+ outputPoints: 0
128
+ };
129
+ }
130
+ validateNumericOption(name, value, isValid, requirement) {
131
+ if (!Number.isFinite(value) || !isValid(value)) {
132
+ throw new RangeError(`${name} must be a finite number ${requirement}`);
133
+ }
134
+ }
135
+ /** Read the numeric values from one SVG path or transform argument string. */
136
+ parseArguments(source) {
137
+ const args = [];
138
+ let arg;
139
+ while (arg = argumentsRegEx.exec(source)) {
140
+ args.push(+arg[0]);
141
+ }
142
+ return args;
143
+ }
144
+ /**
145
+ * Read every path in an SVG document and return its sampled points.
146
+ *
147
+ * Paths are keyed by `id` unless `joinPathData` is enabled. The configured
148
+ * sample and output limits apply to the whole document, not one path at a time.
149
+ */
150
+ processSVG(data) {
151
+ if (!this.parser) {
152
+ throw new Error('A prepared SAX parser is required to process SVG');
153
+ }
154
+ this.validateNumericOptions();
155
+ const budget = this.createSamplingBudget();
156
+ const transformStack = [];
157
+ let interpolatedPaths = this.joinPathData ? [] : {};
158
+ let i = Date.now();
159
+ this.parser.eventHandler = (event, detail) => {
160
+ const node = detail;
161
+ if (event === SaxEventType.OpenTag) {
162
+ const inheritedTransform = transformStack[transformStack.length - 1];
163
+ const cumulativeTransform = inheritedTransform
164
+ ? new SVGTransform().multiply(inheritedTransform)
165
+ : new SVGTransform();
166
+ const transform = node.attributes.find(attr => attr.name.value === 'transform');
167
+ if (transform) {
168
+ cumulativeTransform.multiply(this.parseTransform(transform.value.value));
169
+ }
170
+ transformStack.push(cumulativeTransform);
171
+ if (node.name === 'path') {
172
+ const p = node.attributes.find(attr => attr.name.value === 'd');
173
+ if (!p) {
174
+ return;
175
+ }
176
+ const points = this.interpolatePathWithBudget(p.value.value, budget);
177
+ this.applyTransforms(cumulativeTransform, points);
178
+ if (!this.joinPathData) {
179
+ const id = node.attributes.find(attr => attr.name.value === 'id');
180
+ const key = id ? id.value.value : `path_${i++}`;
181
+ interpolatedPaths[key] = points;
182
+ }
183
+ else {
184
+ interpolatedPaths = interpolatedPaths.concat(points);
185
+ }
186
+ }
187
+ }
188
+ else {
189
+ transformStack.pop();
190
+ }
191
+ };
192
+ this.parser.write(data);
193
+ this.parser.end();
194
+ return interpolatedPaths;
195
+ }
196
+ parseTransform(rawTransform) {
197
+ const svgTransform = new SVGTransform();
198
+ let index = 0;
199
+ let count = 0;
200
+ while (index < rawTransform.length) {
201
+ index = this.skipSeparators(rawTransform, index);
202
+ if (index === rawTransform.length) {
203
+ break;
204
+ }
205
+ const nameMatch = /^[A-Za-z]+/.exec(rawTransform.slice(index));
206
+ if (!nameMatch || !transformNames.has(nameMatch[0])) {
207
+ throw new Error('Invalid SVG transform: unsupported transform function');
208
+ }
209
+ const type = nameMatch[0];
210
+ index += type.length;
211
+ index = this.skipWhitespace(rawTransform, index);
212
+ if (rawTransform[index] !== '(') {
213
+ throw new Error(`Invalid SVG transform: expected "(" after ${type}`);
214
+ }
215
+ const closingIndex = rawTransform.indexOf(')', index + 1);
216
+ if (closingIndex === -1) {
217
+ throw new Error(`Invalid SVG transform: missing closing ")" for ${type}`);
218
+ }
219
+ const args = this.parseStrictNumbers(rawTransform.slice(index + 1, closingIndex), `SVG transform ${type}`);
220
+ this.validateTransformArity(type, args.length);
221
+ if (type === 'matrix') {
222
+ svgTransform.multiply(new SVGTransform(args[0], args[1], args[2], args[3], args[4], args[5]));
223
+ }
224
+ else if (type === 'translate') {
225
+ if (args.length === 1) {
226
+ args.push(0);
227
+ }
228
+ svgTransform.translate(args[0], args[1]);
229
+ }
230
+ else if (type === 'scale') {
231
+ svgTransform.scale(args[0], args[1]);
232
+ }
233
+ else if (type === 'rotate') {
234
+ svgTransform.rotate(args[0], args[1], args[2]);
235
+ }
236
+ else if (type === 'skewX') {
237
+ svgTransform.skewX(args[0]);
238
+ }
239
+ else {
240
+ svgTransform.skewY(args[0]);
241
+ }
242
+ if (!this.isFiniteTransform(svgTransform)) {
243
+ throw new RangeError('Invalid SVG transform: matrix values must be finite');
244
+ }
245
+ index = closingIndex + 1;
246
+ count++;
247
+ }
248
+ if (count === 0) {
249
+ throw new Error('Invalid SVG transform: expected at least one transform function');
250
+ }
251
+ return svgTransform;
252
+ }
253
+ validateTransformArity(type, length) {
254
+ const valid = (type === 'matrix' && length === 6)
255
+ || ((type === 'translate' || type === 'scale') && (length === 1 || length === 2))
256
+ || (type === 'rotate' && (length === 1 || length === 3))
257
+ || ((type === 'skewX' || type === 'skewY') && length === 1);
258
+ if (!valid) {
259
+ throw new Error(`Invalid SVG transform: ${type} has an invalid argument count`);
260
+ }
261
+ }
262
+ isFiniteTransform(transform) {
263
+ const points = [transform.map(0, 0), transform.map(1, 0), transform.map(0, 1)];
264
+ return points.every(point => Number.isFinite(point.x) && Number.isFinite(point.y));
265
+ }
266
+ skipWhitespace(source, index) {
267
+ while (index < source.length && /\s/.test(source[index])) {
268
+ index++;
269
+ }
270
+ return index;
271
+ }
272
+ skipSeparators(source, index) {
273
+ while (index < source.length && (source[index] === ',' || /\s/.test(source[index]))) {
274
+ index++;
275
+ }
276
+ return index;
277
+ }
278
+ parseStrictNumbers(source, context) {
279
+ const values = [];
280
+ let index = 0;
281
+ while (index < source.length) {
282
+ const separatorStart = index;
283
+ index = this.skipSeparators(source, index);
284
+ if (index === source.length) {
285
+ if (source.slice(separatorStart, index).includes(',')) {
286
+ throw new Error(`Invalid ${context}: trailing separator`);
287
+ }
288
+ break;
289
+ }
290
+ numberRegEx.lastIndex = index;
291
+ const match = numberRegEx.exec(source);
292
+ if (!match) {
293
+ throw new Error(`Invalid ${context}: malformed number`);
294
+ }
295
+ const value = Number(match[0]);
296
+ if (!Number.isFinite(value)) {
297
+ throw new RangeError(`Invalid ${context}: numbers must be finite`);
298
+ }
299
+ values.push(value);
300
+ index = numberRegEx.lastIndex;
301
+ }
302
+ return values;
303
+ }
304
+ parseArcArguments(source) {
305
+ const values = [];
306
+ let index = 0;
307
+ while (index < source.length) {
308
+ const group = [];
309
+ for (let argument = 0; argument < 3; argument++) {
310
+ const parsed = this.readStrictNumber(source, index, 'SVG path data');
311
+ group.push(parsed.value);
312
+ index = parsed.index;
313
+ }
314
+ for (let flag = 0; flag < 2; flag++) {
315
+ index = this.skipSeparators(source, index);
316
+ if (source[index] !== '0' && source[index] !== '1') {
317
+ throw new Error('Invalid SVG path data: arc flags must be 0 or 1');
318
+ }
319
+ group.push(Number(source[index++]));
320
+ }
321
+ for (let argument = 0; argument < 2; argument++) {
322
+ const parsed = this.readStrictNumber(source, index, 'SVG path data');
323
+ group.push(parsed.value);
324
+ index = parsed.index;
325
+ }
326
+ values.push(...group);
327
+ const separatorStart = index;
328
+ index = this.skipSeparators(source, index);
329
+ if (index === source.length && source.slice(separatorStart, index).includes(',')) {
330
+ throw new Error('Invalid SVG path data: trailing separator');
331
+ }
332
+ }
333
+ return values;
334
+ }
335
+ readStrictNumber(source, index, context) {
336
+ index = this.skipSeparators(source, index);
337
+ numberRegEx.lastIndex = index;
338
+ const match = numberRegEx.exec(source);
339
+ if (!match) {
340
+ throw new Error(`Invalid ${context}: malformed number`);
341
+ }
342
+ const value = Number(match[0]);
343
+ if (!Number.isFinite(value)) {
344
+ throw new RangeError(`Invalid ${context}: numbers must be finite`);
345
+ }
346
+ return { value, index: numberRegEx.lastIndex };
347
+ }
348
+ validatePath(path) {
349
+ let index = 0;
350
+ let command;
351
+ let firstCommand = true;
352
+ while (index < path.length) {
353
+ index = this.skipSeparators(path, index);
354
+ if (index === path.length) {
355
+ break;
356
+ }
357
+ const token = path[index];
358
+ if (!/[A-Za-z]/.test(token)) {
359
+ throw new Error('Invalid SVG path data: expected a command');
360
+ }
361
+ if (!'MmLlHhVvCcSsQqTtAaZz'.includes(token)) {
362
+ throw new Error(`Invalid SVG path data: unsupported command ${token}`);
363
+ }
364
+ command = token;
365
+ index++;
366
+ if (firstCommand && command.toLowerCase() !== 'm') {
367
+ throw new Error('Invalid SVG path data: the first command must be moveto');
368
+ }
369
+ firstCommand = false;
370
+ const start = index;
371
+ while (index < path.length) {
372
+ const beforeSeparator = index;
373
+ index = this.skipSeparators(path, index);
374
+ if (index === path.length || /[A-Za-z]/.test(path[index])) {
375
+ if (index === path.length && index !== beforeSeparator && path.slice(beforeSeparator, index).includes(',')) {
376
+ throw new Error('Invalid SVG path data: trailing separator');
377
+ }
378
+ break;
379
+ }
380
+ numberRegEx.lastIndex = index;
381
+ const match = numberRegEx.exec(path);
382
+ if (!match) {
383
+ throw new Error('Invalid SVG path data: malformed number');
384
+ }
385
+ const value = Number(match[0]);
386
+ if (!Number.isFinite(value)) {
387
+ throw new RangeError('Invalid SVG path data: numbers must be finite');
388
+ }
389
+ index = numberRegEx.lastIndex;
390
+ }
391
+ const rawArguments = path.slice(start, index);
392
+ const values = command.toLowerCase() === 'a'
393
+ ? this.parseArcArguments(rawArguments)
394
+ : this.parseStrictNumbers(rawArguments, 'SVG path data');
395
+ if (command.toLowerCase() === 'z') {
396
+ if (values.length) {
397
+ throw new Error('Invalid SVG path data: closepath cannot have arguments');
398
+ }
399
+ continue;
400
+ }
401
+ const argumentCount = pathArgumentCounts[command.toUpperCase()];
402
+ if (!values.length || values.length % argumentCount !== 0) {
403
+ throw new Error(`Invalid SVG path data: ${command} has an incomplete argument group`);
404
+ }
405
+ }
406
+ if (firstCommand) {
407
+ throw new Error('Invalid SVG path data: expected a moveto command');
408
+ }
409
+ }
410
+ applyTransforms(transformOrTransforms, points) {
411
+ const transform = transformOrTransforms instanceof SVGTransform
412
+ ? transformOrTransforms
413
+ : Object.values(transformOrTransforms).reduce((combined, rawTransform) => combined.multiply(this.parseTransform(rawTransform)), new SVGTransform());
414
+ if (transform.isIdentity()) {
415
+ return;
416
+ }
417
+ const len = points.length;
418
+ for (let i = 0; i < len; i += 2) {
419
+ const { x, y } = transform.map(points[i], points[i + 1]);
420
+ points[i] = x - (x % this.roundToNearest);
421
+ points[i + 1] = y - (y % this.roundToNearest);
422
+ }
423
+ }
424
+ /**
425
+ * Sample one SVG path-data string and return a flat x/y coordinate array.
426
+ *
427
+ * Invalid path data and exhausted limits throw a descriptive error.
428
+ */
429
+ interpolatePath(path) {
430
+ this.validateNumericOptions();
431
+ return this.interpolatePathWithBudget(path, this.createSamplingBudget());
432
+ }
433
+ interpolatePathWithBudget(path, budget) {
434
+ if (path.trim() === '' || path.trim().toLowerCase() === 'none') {
435
+ return [];
436
+ }
437
+ this.validatePath(path);
438
+ commandRegEx.lastIndex = 0;
439
+ const data = [];
440
+ let subPathStartX = 0;
441
+ let subPathStartY = 0;
442
+ let offsetX = 0;
443
+ let offsetY = 0;
444
+ let match;
445
+ let lastCommand = { command: '' };
446
+ let lastQuadraticControlX = 0;
447
+ let lastQuadraticControlY = 0;
448
+ while (match = commandRegEx.exec(path)) {
449
+ const [, command, rawArguments] = match;
450
+ let points = command.toLowerCase() === 'a'
451
+ ? this.parseArcArguments(rawArguments)
452
+ : this.parseArguments(rawArguments);
453
+ let args;
454
+ switch (command) {
455
+ case 'A':
456
+ case 'C':
457
+ case 'L':
458
+ case 'Q':
459
+ points.unshift(offsetX, offsetY);
460
+ args = [points];
461
+ break;
462
+ case 'S':
463
+ case 's':
464
+ let lastCtrlX = offsetX;
465
+ let lastCtrlY = offsetY;
466
+ const { command: lastC, points: lastP } = lastCommand;
467
+ const reg = command.toLowerCase() === 's' ? /^[cs]$/ : /^[qt]$/;
468
+ if (reg.test(lastC.toLowerCase()) && lastP) {
469
+ const { length } = lastP;
470
+ lastCtrlY = lastP[length - 3];
471
+ lastCtrlX = lastP[length - 4];
472
+ }
473
+ if (/^[st]$/.test(command)) {
474
+ this.applyOffset(offsetX, offsetY, points, 4);
475
+ }
476
+ points.unshift(offsetX, offsetY, lastCtrlX, lastCtrlY);
477
+ args = [points];
478
+ break;
479
+ case 'T':
480
+ case 't':
481
+ for (let i = 0; i < points.length; i += 2) {
482
+ const reflect = /^[qt]$/i.test(lastCommand.command);
483
+ const controlX = reflect ? 2 * offsetX - lastQuadraticControlX : offsetX;
484
+ const controlY = reflect ? 2 * offsetY - lastQuadraticControlY : offsetY;
485
+ const endX = command === 't' ? offsetX + points[i] : points[i];
486
+ const endY = command === 't' ? offsetY + points[i + 1] : points[i + 1];
487
+ data.push(...calculators.q([offsetX, offsetY, controlX, controlY, endX, endY], this.minDistance, this.roundToNearest, this.sampleFrequency, budget));
488
+ offsetX = endX;
489
+ offsetY = endY;
490
+ lastQuadraticControlX = controlX;
491
+ lastQuadraticControlY = controlY;
492
+ lastCommand.command = command;
493
+ }
494
+ continue;
495
+ case 'a':
496
+ points.unshift(0, 0);
497
+ args = [this.applyOffset(offsetX, offsetY, points, 7)];
498
+ break;
499
+ case 'c':
500
+ this.applyOffset(offsetX, offsetY, points, 6);
501
+ points.unshift(offsetX, offsetY);
502
+ args = [points];
503
+ break;
504
+ case 'l':
505
+ points.unshift(0, 0);
506
+ args = [this.applyOffset(offsetX, offsetY, points, 2)];
507
+ break;
508
+ case 'q':
509
+ points.unshift(0, 0);
510
+ args = [this.applyOffset(offsetX, offsetY, points, 4)];
511
+ break;
512
+ case 'H':
513
+ points.unshift(offsetX, offsetY);
514
+ points.push(offsetY);
515
+ args = [points];
516
+ break;
517
+ case 'h':
518
+ this.applyOffset(offsetX, offsetX, points, 2); // offsetX, offsetX is intentional
519
+ points.unshift(offsetX, offsetY);
520
+ points.push(offsetY);
521
+ args = [points];
522
+ break;
523
+ case 'm':
524
+ subPathStartX = points[0] + offsetX;
525
+ subPathStartY = points[1] + offsetY;
526
+ args = [this.applyOffset(offsetX, offsetY, points.slice(2), 2)];
527
+ break;
528
+ case 'M':
529
+ subPathStartX = points[0];
530
+ subPathStartY = points[1];
531
+ args = [points.slice(2)];
532
+ break;
533
+ case 'V':
534
+ points.unshift(offsetX, offsetY, offsetX);
535
+ args = [points];
536
+ break;
537
+ case 'v':
538
+ this.applyOffset(offsetY, offsetY, points, 2); // offsetY, offsetY is intentional
539
+ points.unshift(offsetX, offsetY, offsetX);
540
+ args = [points];
541
+ break;
542
+ case 'z':
543
+ case 'Z':
544
+ points = [offsetX, offsetY, subPathStartX, subPathStartY];
545
+ args = [points];
546
+ break;
547
+ }
548
+ const calculator = calculators[command.toLowerCase()];
549
+ const offsets = { offsetX, offsetY };
550
+ if (calculator && args) {
551
+ const pts = calculator(args[0], this.minDistance, this.roundToNearest, this.sampleFrequency, budget);
552
+ data.push(...pts);
553
+ const len = ~~points.length;
554
+ offsetY = points[len - 1];
555
+ offsetX = points[len - 2];
556
+ if (command.toLowerCase() === 'q') {
557
+ lastQuadraticControlX = points[len - 4];
558
+ lastQuadraticControlY = points[len - 3];
559
+ }
560
+ }
561
+ lastCommand = { command, points, offsets };
562
+ }
563
+ if (this.trim) {
564
+ this.trimPathOffsets(data);
565
+ }
566
+ return data;
567
+ }
568
+ trimPathOffsets(paths) {
569
+ let minX = Number.POSITIVE_INFINITY;
570
+ let minY = Number.POSITIVE_INFINITY;
571
+ if (!paths.length) {
572
+ return;
573
+ }
574
+ for (let i = 0; i < paths.length; i += 2) {
575
+ if (paths[i] < minX) {
576
+ minX = paths[i];
577
+ }
578
+ if (paths[i + 1] < minY) {
579
+ minY = paths[i + 1];
580
+ }
581
+ }
582
+ for (let i = 0; i < paths.length; i += 2) {
583
+ paths[i] -= minX;
584
+ paths[i + 1] -= minY;
585
+ }
586
+ }
587
+ applyOffset(offsetX, offsetY, coords = [], setLength = 2) {
588
+ for (let i = 0; i < coords.length; i++) {
589
+ if (i && i % +setLength === 0) {
590
+ offsetX = coords[i - 2];
591
+ offsetY = coords[i - 1];
592
+ }
593
+ coords[i] += (i % 2 ? +offsetY : +offsetX);
594
+ }
595
+ return coords;
596
+ }
597
+ }
package/lib/cli.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/lib/cli.js ADDED
@@ -0,0 +1,27 @@
1
+ #!/usr/bin/env node
2
+ import { mkdir, readFile, writeFile } from 'node:fs/promises';
3
+ import { dirname } from 'node:path';
4
+ import { createInterpolator } from './index.js';
5
+ async function main() {
6
+ const [configPath, svgPath, outputPath] = process.argv.slice(2);
7
+ if (!configPath || !svgPath) {
8
+ throw new Error('Usage: svgpi <config.json> <input.svg> [output.json]');
9
+ }
10
+ const config = JSON.parse(await readFile(configPath, 'utf8'));
11
+ const svg = await readFile(svgPath);
12
+ const wasm = await readFile(new URL(import.meta.resolve('sax-wasm/lib/sax-wasm.wasm')));
13
+ const interpolator = await createInterpolator(config, new Uint8Array(wasm));
14
+ const result = interpolator.processSVG(new Uint8Array(svg));
15
+ const json = JSON.stringify(result, null, config.pretty ? config.prettyIndent : 0);
16
+ if (outputPath) {
17
+ await mkdir(dirname(outputPath), { recursive: true });
18
+ await writeFile(outputPath, json);
19
+ }
20
+ else {
21
+ console.log(json);
22
+ }
23
+ }
24
+ main().catch((error) => {
25
+ console.error(error instanceof Error ? error.message : String(error));
26
+ process.exitCode = 1;
27
+ });
package/lib/index.d.ts ADDED
@@ -0,0 +1,13 @@
1
+ import { SVGPathInterpolator } from './SVGPathInterpolator.js';
2
+ import type { SVGInterpolatorConfig } from './SVGPathInterpolator.js';
3
+ export { SVGPathInterpolator } from './SVGPathInterpolator.js';
4
+ export type { SVGInterpolatorConfig } from './SVGPathInterpolator.js';
5
+ /** A source for the WebAssembly parser required to process complete SVG documents. */
6
+ export type SaxWasmSource = string | URL | Uint8Array | Response;
7
+ /**
8
+ * Create an interpolator that can process complete SVG documents.
9
+ *
10
+ * Provide the SAX WebAssembly bytes, a URL, or a fetch `Response`. The package
11
+ * does not bundle that binary, so callers choose how it is loaded.
12
+ */
13
+ export declare function createInterpolator(config: Omit<SVGInterpolatorConfig, 'parser'>, saxWasmSource: SaxWasmSource): Promise<SVGPathInterpolator>;
package/lib/index.js ADDED
@@ -0,0 +1,27 @@
1
+ import { SaxEventType, SAXParser } from 'sax-wasm';
2
+ import { SVGPathInterpolator } from './SVGPathInterpolator.js';
3
+ export { SVGPathInterpolator } from './SVGPathInterpolator.js';
4
+ async function getParser(saxWasmSource) {
5
+ const parser = new SAXParser(SaxEventType.OpenTag | SaxEventType.CloseTag);
6
+ const response = typeof saxWasmSource === 'string' || saxWasmSource instanceof URL
7
+ ? await fetch(saxWasmSource)
8
+ : saxWasmSource;
9
+ if (response instanceof Response && !response.ok) {
10
+ throw new Error('Cannot load the SAX parser WASM');
11
+ }
12
+ const ready = await parser.prepareWasm(response);
13
+ if (!ready) {
14
+ throw new Error('Could not initialize the SAX parser');
15
+ }
16
+ return parser;
17
+ }
18
+ /**
19
+ * Create an interpolator that can process complete SVG documents.
20
+ *
21
+ * Provide the SAX WebAssembly bytes, a URL, or a fetch `Response`. The package
22
+ * does not bundle that binary, so callers choose how it is loaded.
23
+ */
24
+ export async function createInterpolator(config, saxWasmSource) {
25
+ const parser = await getParser(saxWasmSource);
26
+ return new SVGPathInterpolator({ ...config, parser });
27
+ }