@haiyue/animation-spec 0.1.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 (52) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +190 -0
  3. package/SPECIFICATION.md +108 -0
  4. package/bin/hya-convert.mjs +31 -0
  5. package/dist/binary.d.ts +7 -0
  6. package/dist/chunks/types-l6nBVYwx.js +8 -0
  7. package/dist/chunks/types-l6nBVYwx.js.map +1 -0
  8. package/dist/errors.d.ts +7 -0
  9. package/dist/extensions.d.ts +19 -0
  10. package/dist/index.d.ts +10 -0
  11. package/dist/index.js +2927 -0
  12. package/dist/index.js.map +1 -0
  13. package/dist/lottie-merge-path.d.ts +11 -0
  14. package/dist/lottie.d.ts +62 -0
  15. package/dist/lottie.js +2642 -0
  16. package/dist/lottie.js.map +1 -0
  17. package/dist/native3d/Animation3DError.d.ts +8 -0
  18. package/dist/native3d/Animation3DParser.d.ts +7 -0
  19. package/dist/native3d/Animation3DTypes.d.ts +285 -0
  20. package/dist/native3d/index.d.ts +5 -0
  21. package/dist/native3d.d.ts +2 -0
  22. package/dist/native3d.js +907 -0
  23. package/dist/native3d.js.map +1 -0
  24. package/dist/parser.d.ts +2 -0
  25. package/dist/state-machine.d.ts +130 -0
  26. package/dist/text-selector.d.ts +2 -0
  27. package/dist/types.d.ts +419 -0
  28. package/dist/validation.d.ts +32 -0
  29. package/package.json +69 -0
  30. package/schema/animation-3d-carrier.schema.json +73 -0
  31. package/schema/animation-3d-extension.schema.json +573 -0
  32. package/schema/animation-3d.contract.json +130 -0
  33. package/schema/animation.schema.json +611 -0
  34. package/schema/fixtures/native-3d-mixed-invalid.hya.json +50 -0
  35. package/schema/fixtures/native-3d-valid.hya.json +284 -0
  36. package/src/binary.ts +1441 -0
  37. package/src/errors.ts +18 -0
  38. package/src/extensions.ts +55 -0
  39. package/src/index.ts +90 -0
  40. package/src/lottie-merge-path.ts +204 -0
  41. package/src/lottie.ts +3073 -0
  42. package/src/native3d/Animation3DError.ts +20 -0
  43. package/src/native3d/Animation3DParser.ts +964 -0
  44. package/src/native3d/Animation3DTypes.ts +322 -0
  45. package/src/native3d/index.ts +14 -0
  46. package/src/native3d.ts +2 -0
  47. package/src/parser.ts +41 -0
  48. package/src/state-machine.ts +645 -0
  49. package/src/text-selector.ts +7 -0
  50. package/src/types.ts +483 -0
  51. package/src/validation.ts +1286 -0
  52. package/test/fixtures/basic-lottie.json +31 -0
package/dist/index.js ADDED
@@ -0,0 +1,2927 @@
1
+ import { a as ANIMATION_FORMAT, A as ANIMATION_VERSION, b as ANIMATION_VECTOR_SHAPE_EXTENSION_ID } from './chunks/types-l6nBVYwx.js';
2
+ export { c as ANIMATION_FILE_EXTENSION, d as ANIMATION_MIME_TYPE } from './chunks/types-l6nBVYwx.js';
3
+
4
+ class AnimationFormatError extends Error {
5
+ code;
6
+ path;
7
+ name = 'AnimationFormatError';
8
+ constructor(code, message, path = '$') {
9
+ super(`${message} (${path})`);
10
+ this.code = code;
11
+ this.path = path;
12
+ }
13
+ }
14
+
15
+ class AnimationExtensionRegistry {
16
+ _handlers = new Map();
17
+ register(handler) {
18
+ validateExtensionId(handler.id);
19
+ if (this._handlers.has(handler.id)) {
20
+ throw new AnimationFormatError('E_ANIMATION_INVALID_FORMAT', `Extension "${handler.id}" is already registered.`, '$.extensions');
21
+ }
22
+ this._handlers.set(handler.id, handler);
23
+ let active = true;
24
+ return () => {
25
+ if (!active)
26
+ return;
27
+ active = false;
28
+ if (this._handlers.get(handler.id) === handler)
29
+ this._handlers.delete(handler.id);
30
+ };
31
+ }
32
+ get(id) {
33
+ return this._handlers.get(id);
34
+ }
35
+ has(id) {
36
+ return this._handlers.has(id);
37
+ }
38
+ }
39
+ function extensionIdFromComponentType(type) {
40
+ return type === 'shape2d' || type === 'path2d' || type === 'sprite2d'
41
+ || type === 'text2d' || type === 'particle2d' || type === 'audio' ? null : type;
42
+ }
43
+ function validateExtensionId(value) {
44
+ if (!/^[a-z0-9]+(?:[.-][a-z0-9]+)+@[1-9][0-9]*$/i.test(value)) {
45
+ throw new AnimationFormatError('E_ANIMATION_INVALID_FORMAT', `Extension id "${value}" must be a namespaced id with a major version suffix.`, '$.extensionsUsed');
46
+ }
47
+ }
48
+
49
+ const TEXT_SELECTOR_SHAPES = [
50
+ 'square', 'ramp-up', 'ramp-down', 'triangle', 'round', 'smooth',
51
+ ];
52
+ const TEXT_SELECTOR_BASES = [
53
+ 'characters', 'characters-excluding-spaces', 'words', 'lines',
54
+ ];
55
+
56
+ const HYA_STATE_MACHINE_EXTENSION_ID = 'org.haiyue.animation-state-machine@1';
57
+ const STATE_MACHINE_CHANNEL_CAPABILITIES = Object.freeze([
58
+ channel('core-transform', 'continuous-number', 'full', 'numeric-track', 'override-additive-layer-mask', 'pose-buffer', 'cross-fade'),
59
+ channel('sprite-uv', 'discrete-step', 'full', 'step-track', 'dominant-weight-then-action-order', 'shared-visual', 'switch-at-dominant-weight'),
60
+ channel('vector-morph', 'shape-morph', 'full', 'numeric-track', 'override-additive-layer-mask', 'shared-visual', 'cross-fade'),
61
+ channel('vector-paint', 'continuous-number', 'unsupported', 'numeric-track', 'override-additive-layer-mask', 'shared-visual', 'rejected', 'E_STATE_MACHINE_CHANNEL_ADVANCED_INLINE_UNSUPPORTED'),
62
+ channel('text-animator', 'continuous-number', 'unsupported', 'numeric-track', 'override-additive-layer-mask', 'shared-visual', 'rejected', 'E_STATE_MACHINE_CHANNEL_ADVANCED_INLINE_UNSUPPORTED'),
63
+ channel('visual-effect', 'continuous-number', 'unsupported', 'numeric-track', 'override-additive-layer-mask', 'shared-visual', 'rejected', 'E_STATE_MACHINE_CHANNEL_ADVANCED_INLINE_UNSUPPORTED'),
64
+ channel('composite-expansion', 'continuous-number', 'unsupported', 'numeric-track', 'override-additive-layer-mask', 'shared-visual', 'rejected', 'E_STATE_MACHINE_CHANNEL_ADVANCED_INLINE_UNSUPPORTED'),
65
+ channel('resource-switch', 'resource-switch', 'degraded', 'step-track', 'dominant-weight-then-action-order', 'shared-visual', 'switch-at-dominant-weight', 'E_STATE_MACHINE_CHANNEL_RESOURCE_SWITCH_OVERLAP'),
66
+ channel('particle-2d', 'particle-side-effect', 'full', 'effect-cue', 'shared-instance-lifecycle', 'shared-side-effect', 'destination-takeover'),
67
+ channel('particle-3d', 'particle-side-effect', 'full', 'effect-cue', 'shared-instance-lifecycle', 'shared-side-effect', 'destination-takeover'),
68
+ channel('audio', 'audio-side-effect', 'degraded', 'effect-cue', 'reject-overlap', 'shared-side-effect', 'immediate-only', 'E_STATE_MACHINE_CHANNEL_AUDIO_UNMIXABLE_RANGE'),
69
+ channel('pose-3d', 'pose-3d', 'full', 'pose-buffer', 'override-additive-layer-mask', 'pose-buffer', 'cross-fade'),
70
+ ]);
71
+ /** Canonical immutable channel registry for the built-in state machine. */
72
+ const HYA_STATE_MACHINE_CHANNEL_REGISTRY = immutableReadonlyMap(STATE_MACHINE_CHANNEL_CAPABILITIES.map(capability => [capability.id, capability]));
73
+ function hyaStateMachineChannelCapability(id) {
74
+ return HYA_STATE_MACHINE_CHANNEL_REGISTRY.get(id);
75
+ }
76
+ function immutableReadonlyMap(entries) {
77
+ const source = new Map(entries);
78
+ let view;
79
+ view = Object.freeze({
80
+ get size() { return source.size; },
81
+ get: (key) => source.get(key),
82
+ has: (key) => source.has(key),
83
+ entries: () => source.entries(),
84
+ keys: () => source.keys(),
85
+ values: () => source.values(),
86
+ forEach: (callbackfn, thisArg) => source.forEach((value, key) => callbackfn.call(thisArg, value, key, view)),
87
+ [Symbol.iterator]: () => source[Symbol.iterator](),
88
+ });
89
+ return view;
90
+ }
91
+ const MAX_CLIPS = 10_000;
92
+ const MAX_PARAMETERS = 1_000;
93
+ const MAX_LAYERS = 128;
94
+ const MAX_STATES = 100_000;
95
+ const MAX_TRANSITIONS = 200_000;
96
+ const MAX_BLEND_DEPTH = 32;
97
+ const MAX_BLEND_CHILDREN = 4_096;
98
+ function channel(id, kind, support, sampling, mixing, ownership, transition, diagnosticCode) {
99
+ return Object.freeze({
100
+ id,
101
+ kind,
102
+ support,
103
+ sampling,
104
+ mixing,
105
+ ownership,
106
+ transition,
107
+ ...(diagnosticCode === undefined ? {} : { diagnosticCode }),
108
+ });
109
+ }
110
+ /** Strictly validates and freezes the built-in HYA state-machine extension. */
111
+ function parseHyaStateMachineExtension(value, compositionDuration, path = `$.extensions.${HYA_STATE_MACHINE_EXTENSION_ID}`) {
112
+ positive(compositionDuration, '$.duration');
113
+ const root = record$1(value, path);
114
+ knownKeys(root, ['clips', 'stateMachine'], path);
115
+ const clipValues = array$1(root.clips, `${path}.clips`);
116
+ bounded(clipValues.length, 1, MAX_CLIPS, 'clips', `${path}.clips`);
117
+ const clipIds = new Set();
118
+ const clips = clipValues.map((entry, index) => {
119
+ const clipPath = `${path}.clips[${index}]`;
120
+ const clip = record$1(entry, clipPath);
121
+ knownKeys(clip, ['id', 'name', 'start', 'duration'], clipPath);
122
+ const id = identifier(clip.id, `${clipPath}.id`);
123
+ unique(clipIds, id, `${clipPath}.id`, 'clip');
124
+ const start = nonNegative(clip.start, `${clipPath}.start`);
125
+ const duration = positive(clip.duration, `${clipPath}.duration`);
126
+ if (start + duration > compositionDuration + 1e-6) {
127
+ invalid('Clip range must fit inside the HYA composition duration.', clipPath);
128
+ }
129
+ return Object.freeze({
130
+ id,
131
+ ...(clip.name === undefined ? {} : { name: text(clip.name, `${clipPath}.name`) }),
132
+ start,
133
+ duration,
134
+ });
135
+ });
136
+ const stateMachine = parseStateMachine(root.stateMachine, clipIds, `${path}.stateMachine`);
137
+ return Object.freeze({ clips: Object.freeze(clips), stateMachine });
138
+ }
139
+ function parseStateMachine(value, clipIds, path) {
140
+ const root = record$1(value, path);
141
+ knownKeys(root, ['format', 'id', 'name', 'parameters', 'layers'], path);
142
+ if (root.format !== 'haiyue-animation-state-machine@1') {
143
+ invalid('State machine format must be "haiyue-animation-state-machine@1".', `${path}.format`);
144
+ }
145
+ const parametersInput = array$1(root.parameters, `${path}.parameters`);
146
+ bounded(parametersInput.length, 0, MAX_PARAMETERS, 'parameters', `${path}.parameters`);
147
+ const parameterNames = new Set();
148
+ const parameterTypes = new Map();
149
+ const parameters = parametersInput.map((entry, index) => {
150
+ const parameterPath = `${path}.parameters[${index}]`;
151
+ const parameter = record$1(entry, parameterPath);
152
+ knownKeys(parameter, ['name', 'type', 'defaultValue'], parameterPath);
153
+ const name = identifier(parameter.name, `${parameterPath}.name`);
154
+ unique(parameterNames, name, `${parameterPath}.name`, 'parameter');
155
+ const type = oneOf(parameter.type, ['float', 'integer', 'boolean', 'trigger'], `${parameterPath}.type`);
156
+ parameterTypes.set(name, type);
157
+ if (type === 'float')
158
+ return Object.freeze({ name, type, defaultValue: finite(parameter.defaultValue, `${parameterPath}.defaultValue`) });
159
+ if (type === 'integer')
160
+ return Object.freeze({ name, type, defaultValue: safeInteger$1(parameter.defaultValue, `${parameterPath}.defaultValue`) });
161
+ if (type === 'boolean')
162
+ return Object.freeze({ name, type, defaultValue: booleanValue$1(parameter.defaultValue, `${parameterPath}.defaultValue`) });
163
+ if (parameter.defaultValue !== undefined)
164
+ invalid('Trigger parameters do not have a defaultValue.', `${parameterPath}.defaultValue`);
165
+ return Object.freeze({ name, type });
166
+ });
167
+ const layersInput = array$1(root.layers, `${path}.layers`);
168
+ bounded(layersInput.length, 1, MAX_LAYERS, 'layers', `${path}.layers`);
169
+ const layerIds = new Set();
170
+ let stateCount = 0;
171
+ let transitionCount = 0;
172
+ const layers = layersInput.map((entry, layerIndex) => {
173
+ const layerPath = `${path}.layers[${layerIndex}]`;
174
+ const layer = record$1(entry, layerPath);
175
+ knownKeys(layer, [
176
+ 'id', 'name', 'initialStateId', 'states', 'transitions', 'blendMode', 'weight', 'mask',
177
+ ], layerPath);
178
+ const id = identifier(layer.id, `${layerPath}.id`);
179
+ unique(layerIds, id, `${layerPath}.id`, 'layer');
180
+ const stateInputs = array$1(layer.states, `${layerPath}.states`);
181
+ bounded(stateInputs.length, 1, MAX_STATES, 'states', `${layerPath}.states`);
182
+ stateCount += stateInputs.length;
183
+ bounded(stateCount, 1, MAX_STATES, 'total states', `${layerPath}.states`);
184
+ const stateIds = new Set();
185
+ const states = stateInputs.map((stateEntry, stateIndex) => {
186
+ const statePath = `${layerPath}.states[${stateIndex}]`;
187
+ const state = record$1(stateEntry, statePath);
188
+ knownKeys(state, ['id', 'name', 'motion', 'speed', 'speedParameter', 'loop'], statePath);
189
+ const stateId = identifier(state.id, `${statePath}.id`);
190
+ unique(stateIds, stateId, `${statePath}.id`, 'state');
191
+ const speed = state.speed === undefined ? undefined : finite(state.speed, `${statePath}.speed`);
192
+ const speedParameter = state.speedParameter === undefined
193
+ ? undefined
194
+ : numericParameterReference(state.speedParameter, parameterTypes, `${statePath}.speedParameter`);
195
+ return Object.freeze({
196
+ id: stateId,
197
+ name: text(state.name, `${statePath}.name`),
198
+ motion: parseMotion(state.motion, clipIds, parameterTypes, `${statePath}.motion`, 0),
199
+ ...(speed === undefined ? {} : { speed }),
200
+ ...(speedParameter === undefined ? {} : { speedParameter }),
201
+ ...(state.loop === undefined ? {} : { loop: oneOf(state.loop, ['once', 'repeat', 'ping-pong'], `${statePath}.loop`) }),
202
+ });
203
+ });
204
+ const initialStateId = identifier(layer.initialStateId, `${layerPath}.initialStateId`);
205
+ if (!stateIds.has(initialStateId))
206
+ invalid(`Unknown initial state "${initialStateId}".`, `${layerPath}.initialStateId`);
207
+ const transitionInputs = array$1(layer.transitions, `${layerPath}.transitions`);
208
+ transitionCount += transitionInputs.length;
209
+ bounded(transitionCount, 0, MAX_TRANSITIONS, 'total transitions', `${layerPath}.transitions`);
210
+ const transitionIds = new Set();
211
+ const transitions = transitionInputs.map((transitionEntry, transitionIndex) => {
212
+ const transitionPath = `${layerPath}.transitions[${transitionIndex}]`;
213
+ const transition = record$1(transitionEntry, transitionPath);
214
+ knownKeys(transition, [
215
+ 'id', 'from', 'to', 'conditions', 'duration', 'hasExitTime', 'exitTime',
216
+ 'destinationOffset', 'interruption',
217
+ ], transitionPath);
218
+ const transitionId = identifier(transition.id, `${transitionPath}.id`);
219
+ unique(transitionIds, transitionId, `${transitionPath}.id`, 'transition');
220
+ const from = transition.from === '*' ? '*' : identifier(transition.from, `${transitionPath}.from`);
221
+ const to = identifier(transition.to, `${transitionPath}.to`);
222
+ if (from !== '*' && !stateIds.has(from))
223
+ invalid(`Unknown source state "${from}".`, `${transitionPath}.from`);
224
+ if (!stateIds.has(to))
225
+ invalid(`Unknown destination state "${to}".`, `${transitionPath}.to`);
226
+ const conditions = array$1(transition.conditions, `${transitionPath}.conditions`).map((condition, conditionIndex) => (parseCondition(condition, parameterTypes, `${transitionPath}.conditions[${conditionIndex}]`)));
227
+ if (transition.hasExitTime === true && transition.exitTime === undefined) {
228
+ invalid('exitTime is required when hasExitTime is true.', `${transitionPath}.exitTime`);
229
+ }
230
+ const exitTime = transition.exitTime === undefined ? undefined : nonNegative(transition.exitTime, `${transitionPath}.exitTime`);
231
+ const destinationOffset = transition.destinationOffset === undefined
232
+ ? undefined
233
+ : nonNegative(transition.destinationOffset, `${transitionPath}.destinationOffset`);
234
+ return Object.freeze({
235
+ id: transitionId,
236
+ from,
237
+ to,
238
+ conditions: Object.freeze(conditions),
239
+ duration: nonNegative(transition.duration, `${transitionPath}.duration`),
240
+ ...(transition.hasExitTime === undefined ? {} : { hasExitTime: booleanValue$1(transition.hasExitTime, `${transitionPath}.hasExitTime`) }),
241
+ ...(exitTime === undefined ? {} : { exitTime }),
242
+ ...(destinationOffset === undefined ? {} : { destinationOffset }),
243
+ ...(transition.interruption === undefined ? {} : {
244
+ interruption: oneOf(transition.interruption, [
245
+ 'none', 'source', 'destination', 'source-then-destination', 'destination-then-source',
246
+ ], `${transitionPath}.interruption`),
247
+ }),
248
+ });
249
+ });
250
+ const mask = layer.mask === undefined ? undefined : parseMask(layer.mask, `${layerPath}.mask`);
251
+ return Object.freeze({
252
+ id,
253
+ name: text(layer.name, `${layerPath}.name`),
254
+ initialStateId,
255
+ states: Object.freeze(states),
256
+ transitions: Object.freeze(transitions),
257
+ ...(layer.blendMode === undefined ? {} : { blendMode: oneOf(layer.blendMode, ['override', 'additive'], `${layerPath}.blendMode`) }),
258
+ ...(layer.weight === undefined ? {} : { weight: unit(layer.weight, `${layerPath}.weight`) }),
259
+ ...(mask === undefined ? {} : { mask }),
260
+ });
261
+ });
262
+ return Object.freeze({
263
+ format: 'haiyue-animation-state-machine@1',
264
+ id: identifier(root.id, `${path}.id`),
265
+ name: text(root.name, `${path}.name`),
266
+ parameters: Object.freeze(parameters),
267
+ layers: Object.freeze(layers),
268
+ });
269
+ }
270
+ function parseMotion(value, clipIds, parameterTypes, path, depth) {
271
+ if (depth > MAX_BLEND_DEPTH)
272
+ invalid(`Blend Tree depth exceeds ${MAX_BLEND_DEPTH}.`, path);
273
+ const motion = record$1(value, path);
274
+ const kind = oneOf(motion.kind, ['clip', 'blend-1d', 'blend-2d'], `${path}.kind`);
275
+ if (kind === 'clip') {
276
+ knownKeys(motion, ['kind', 'clipId'], path);
277
+ const clipId = identifier(motion.clipId, `${path}.clipId`);
278
+ if (!clipIds.has(clipId))
279
+ invalid(`Unknown HYA clip "${clipId}".`, `${path}.clipId`);
280
+ return Object.freeze({ kind, clipId });
281
+ }
282
+ const childInputs = array$1(motion.children, `${path}.children`);
283
+ bounded(childInputs.length, 1, MAX_BLEND_CHILDREN, 'Blend Tree children', `${path}.children`);
284
+ if (kind === 'blend-1d') {
285
+ knownKeys(motion, ['kind', 'parameter', 'children'], path);
286
+ const parameter = numericParameterReference(motion.parameter, parameterTypes, `${path}.parameter`);
287
+ let previous = -Infinity;
288
+ const children = childInputs.map((entry, index) => {
289
+ const childPath = `${path}.children[${index}]`;
290
+ const child = record$1(entry, childPath);
291
+ knownKeys(child, ['threshold', 'motion'], childPath);
292
+ const threshold = finite(child.threshold, `${childPath}.threshold`);
293
+ if (threshold <= previous)
294
+ invalid('Blend-1D thresholds must be strictly increasing.', `${childPath}.threshold`);
295
+ previous = threshold;
296
+ return Object.freeze({ threshold, motion: parseMotion(child.motion, clipIds, parameterTypes, `${childPath}.motion`, depth + 1) });
297
+ });
298
+ return Object.freeze({ kind, parameter, children: Object.freeze(children) });
299
+ }
300
+ const parameterX = numericParameterReference(motion.parameterX, parameterTypes, `${path}.parameterX`);
301
+ const parameterY = numericParameterReference(motion.parameterY, parameterTypes, `${path}.parameterY`);
302
+ knownKeys(motion, ['kind', 'algorithm', 'parameterX', 'parameterY', 'children'], path);
303
+ const children = childInputs.map((entry, index) => {
304
+ const childPath = `${path}.children[${index}]`;
305
+ const child = record$1(entry, childPath);
306
+ knownKeys(child, ['position', 'motion'], childPath);
307
+ return Object.freeze({
308
+ position: pair(child.position, `${childPath}.position`),
309
+ motion: parseMotion(child.motion, clipIds, parameterTypes, `${childPath}.motion`, depth + 1),
310
+ });
311
+ });
312
+ return Object.freeze({
313
+ kind,
314
+ algorithm: oneOf(motion.algorithm, ['cartesian', 'directional'], `${path}.algorithm`),
315
+ parameterX,
316
+ parameterY,
317
+ children: Object.freeze(children),
318
+ });
319
+ }
320
+ function parseCondition(value, parameterTypes, path) {
321
+ const condition = record$1(value, path);
322
+ knownKeys(condition, ['parameter', 'operator', 'value'], path);
323
+ const parameter = parameterReference(condition.parameter, parameterTypes, `${path}.parameter`);
324
+ const parameterType = parameterTypes.get(parameter);
325
+ const operator = oneOf(condition.operator, [
326
+ 'greater', 'greater-or-equal', 'less', 'less-or-equal',
327
+ 'equal', 'not-equal', 'is-true', 'is-false', 'triggered',
328
+ ], `${path}.operator`);
329
+ const numericOperator = operator === 'greater' || operator === 'greater-or-equal'
330
+ || operator === 'less' || operator === 'less-or-equal';
331
+ if ((parameterType === 'float' || parameterType === 'integer')
332
+ && (numericOperator || operator === 'equal' || operator === 'not-equal')) {
333
+ const value = finite(condition.value, `${path}.value`);
334
+ if (parameterType === 'integer' && !Number.isSafeInteger(value)) {
335
+ invalid('Integer conditions require a safe integer value.', `${path}.value`);
336
+ }
337
+ return Object.freeze({ parameter, operator, value });
338
+ }
339
+ if (parameterType === 'boolean'
340
+ && (operator === 'is-true' || operator === 'is-false')) {
341
+ if (condition.value !== undefined)
342
+ invalid(`Operator "${operator}" does not accept a value.`, `${path}.value`);
343
+ return Object.freeze({ parameter, operator });
344
+ }
345
+ if (parameterType === 'boolean' && (operator === 'equal' || operator === 'not-equal')) {
346
+ return Object.freeze({ parameter, operator, value: booleanValue$1(condition.value, `${path}.value`) });
347
+ }
348
+ if (parameterType === 'trigger' && operator === 'triggered') {
349
+ if (condition.value !== undefined)
350
+ invalid('Operator "triggered" does not accept a value.', `${path}.value`);
351
+ return Object.freeze({ parameter, operator });
352
+ }
353
+ invalid(`Operator "${operator}" is invalid for ${parameterType} parameters.`, `${path}.operator`);
354
+ }
355
+ function parseMask(value, path) {
356
+ const mask = record$1(value, path);
357
+ knownKeys(mask, ['include', 'exclude'], path);
358
+ const include = mask.include === undefined ? undefined : stringList$1(mask.include, `${path}.include`);
359
+ const exclude = mask.exclude === undefined ? undefined : stringList$1(mask.exclude, `${path}.exclude`);
360
+ return Object.freeze({
361
+ ...(include === undefined ? {} : { include }),
362
+ ...(exclude === undefined ? {} : { exclude }),
363
+ });
364
+ }
365
+ function record$1(value, path) {
366
+ if (!value || typeof value !== 'object' || Array.isArray(value))
367
+ invalid('Expected an object.', path);
368
+ return value;
369
+ }
370
+ function array$1(value, path) {
371
+ if (!Array.isArray(value))
372
+ invalid('Expected an array.', path);
373
+ return value;
374
+ }
375
+ function identifier(value, path) {
376
+ const result = text(value, path);
377
+ if (!result.trim())
378
+ invalid('Expected a non-empty identifier.', path);
379
+ return result;
380
+ }
381
+ function text(value, path) {
382
+ if (typeof value !== 'string')
383
+ invalid('Expected a string.', path);
384
+ return value;
385
+ }
386
+ function finite(value, path) {
387
+ if (typeof value !== 'number' || !Number.isFinite(value))
388
+ invalid('Expected a finite number.', path);
389
+ return value;
390
+ }
391
+ function safeInteger$1(value, path) {
392
+ const result = finite(value, path);
393
+ if (!Number.isSafeInteger(result))
394
+ invalid('Expected a safe integer.', path);
395
+ return result;
396
+ }
397
+ function nonNegative(value, path) {
398
+ const result = finite(value, path);
399
+ if (result < 0)
400
+ invalid('Expected a non-negative number.', path);
401
+ return result;
402
+ }
403
+ function positive(value, path) {
404
+ const result = finite(value, path);
405
+ if (result <= 0)
406
+ invalid('Expected a positive number.', path);
407
+ return result;
408
+ }
409
+ function unit(value, path) {
410
+ const result = finite(value, path);
411
+ if (result < 0 || result > 1)
412
+ invalid('Expected a number in [0, 1].', path);
413
+ return result;
414
+ }
415
+ function booleanValue$1(value, path) {
416
+ if (typeof value !== 'boolean')
417
+ invalid('Expected a boolean.', path);
418
+ return value;
419
+ }
420
+ function pair(value, path) {
421
+ const values = array$1(value, path);
422
+ if (values.length !== 2)
423
+ invalid('Expected two numbers.', path);
424
+ return Object.freeze([finite(values[0], `${path}[0]`), finite(values[1], `${path}[1]`)]);
425
+ }
426
+ function stringList$1(value, path) {
427
+ const values = array$1(value, path);
428
+ const seen = new Set();
429
+ return Object.freeze(values.map((entry, index) => {
430
+ const result = identifier(entry, `${path}[${index}]`);
431
+ unique(seen, result, `${path}[${index}]`, 'mask binding');
432
+ return result;
433
+ }));
434
+ }
435
+ function parameterReference(value, parameters, path) {
436
+ const result = identifier(value, path);
437
+ if (!parameters.has(result))
438
+ invalid(`Unknown state-machine parameter "${result}".`, path);
439
+ return result;
440
+ }
441
+ function numericParameterReference(value, parameters, path) {
442
+ const result = parameterReference(value, parameters, path);
443
+ const type = parameters.get(result);
444
+ if (type !== 'float' && type !== 'integer') {
445
+ invalid(`State-machine parameter "${result}" must be float or integer.`, path);
446
+ }
447
+ return result;
448
+ }
449
+ function unique(values, value, path, kind) {
450
+ if (values.has(value))
451
+ invalid(`Duplicate ${kind} id "${value}".`, path);
452
+ values.add(value);
453
+ }
454
+ function knownKeys(value, allowed, path) {
455
+ const allowedKeys = new Set(allowed);
456
+ for (const key of Object.keys(value)) {
457
+ if (!allowedKeys.has(key))
458
+ invalid(`Unknown state-machine property "${key}".`, `${path}.${key}`);
459
+ }
460
+ }
461
+ function bounded(value, minimum, maximum, label, path) {
462
+ if (value < minimum || value > maximum)
463
+ invalid(`${label} count must be in [${minimum}, ${maximum}].`, path);
464
+ }
465
+ function oneOf(value, allowed, path) {
466
+ if (typeof value !== 'string' || !allowed.includes(value))
467
+ invalid(`Expected one of ${allowed.join(', ')}.`, path);
468
+ return value;
469
+ }
470
+ function invalid(message, path) {
471
+ throw new AnimationFormatError('E_ANIMATION_INVALID_FORMAT', message, path);
472
+ }
473
+
474
+ const DEFAULT_LIMITS = Object.freeze({
475
+ maxInputBytes: 64 * 1024 * 1024,
476
+ maxMetadataBytes: 8 * 1024 * 1024,
477
+ maxNodes: 100_000,
478
+ maxComponents: 200_000,
479
+ maxTracks: 200_000,
480
+ maxKeyframes: 5_000_000,
481
+ maxResources: 10_000,
482
+ maxPathValues: 10_000_000,
483
+ maxTextCharacters: 5_000_000,
484
+ maxParticleCapacity: 2_000_000,
485
+ });
486
+ function resolveAnimationParseLimits(options) {
487
+ if (options.maxInputBytes === undefined
488
+ && options.maxMetadataBytes === undefined
489
+ && options.maxNodes === undefined
490
+ && options.maxComponents === undefined
491
+ && options.maxTracks === undefined
492
+ && options.maxKeyframes === undefined
493
+ && options.maxResources === undefined
494
+ && options.maxPathValues === undefined
495
+ && options.maxTextCharacters === undefined
496
+ && options.maxParticleCapacity === undefined) {
497
+ return DEFAULT_LIMITS;
498
+ }
499
+ return {
500
+ maxInputBytes: positiveLimit(options.maxInputBytes, DEFAULT_LIMITS.maxInputBytes, 'maxInputBytes'),
501
+ maxMetadataBytes: positiveLimit(options.maxMetadataBytes, DEFAULT_LIMITS.maxMetadataBytes, 'maxMetadataBytes'),
502
+ maxNodes: positiveLimit(options.maxNodes, DEFAULT_LIMITS.maxNodes, 'maxNodes'),
503
+ maxComponents: positiveLimit(options.maxComponents, DEFAULT_LIMITS.maxComponents, 'maxComponents'),
504
+ maxTracks: positiveLimit(options.maxTracks, DEFAULT_LIMITS.maxTracks, 'maxTracks'),
505
+ maxKeyframes: positiveLimit(options.maxKeyframes, DEFAULT_LIMITS.maxKeyframes, 'maxKeyframes'),
506
+ maxResources: positiveLimit(options.maxResources, DEFAULT_LIMITS.maxResources, 'maxResources'),
507
+ maxPathValues: positiveLimit(options.maxPathValues, DEFAULT_LIMITS.maxPathValues, 'maxPathValues'),
508
+ maxTextCharacters: positiveLimit(options.maxTextCharacters, DEFAULT_LIMITS.maxTextCharacters, 'maxTextCharacters'),
509
+ maxParticleCapacity: positiveLimit(options.maxParticleCapacity, DEFAULT_LIMITS.maxParticleCapacity, 'maxParticleCapacity'),
510
+ };
511
+ }
512
+ function parseAnimationValue(input, options, source, backingBuffer) {
513
+ const limits = resolveAnimationParseLimits(options);
514
+ const root = record(input, '$');
515
+ if (root.format !== ANIMATION_FORMAT)
516
+ fail(`format must be "${ANIMATION_FORMAT}".`, '$.format');
517
+ if (root.version !== ANIMATION_VERSION) {
518
+ throw new AnimationFormatError('E_ANIMATION_UNSUPPORTED_VERSION', `Unsupported animation version "${String(root.version)}".`, '$.version');
519
+ }
520
+ const canvasValue = record(root.canvas, '$.canvas');
521
+ const canvas = Object.freeze({
522
+ width: positiveNumber(canvasValue.width, '$.canvas.width'),
523
+ height: positiveNumber(canvasValue.height, '$.canvas.height'),
524
+ coordinateSystem: literal(canvasValue.coordinateSystem, ['screen-y-down'], '$.canvas.coordinateSystem'),
525
+ });
526
+ const duration = positiveNumber(root.duration, '$.duration');
527
+ const frameRate = root.frameRate === undefined ? undefined : positiveNumber(root.frameRate, '$.frameRate');
528
+ const endBehavior = root.endBehavior === undefined
529
+ ? 'loop'
530
+ : literal(root.endBehavior, ['hold', 'loop', 'destroy'], '$.endBehavior');
531
+ const resourcesInput = array(root.resources ?? [], '$.resources');
532
+ limit(resourcesInput.length, limits.maxResources, 'resources', '$.resources');
533
+ const resourceIds = new Set();
534
+ const resources = resourcesInput.map((value, index) => parseBinaryResourceValue(value, index, resourceIds));
535
+ const nodesInput = array(root.nodes, '$.nodes');
536
+ limit(nodesInput.length, limits.maxNodes, 'nodes', '$.nodes');
537
+ const nodeIds = new Set();
538
+ let componentCount = 0;
539
+ let pathValueCount = 0;
540
+ let textCharacterCount = 0;
541
+ let particleCapacity = 0;
542
+ const nodes = nodesInput.map((value, index) => {
543
+ const node = parseBinaryNodeValue(value, index, nodeIds, options, (kind, count) => {
544
+ if (kind === 'path') {
545
+ pathValueCount += count;
546
+ limit(pathValueCount, limits.maxPathValues, 'path values', `$.nodes[${index}].components`);
547
+ }
548
+ else if (kind === 'text') {
549
+ textCharacterCount += count;
550
+ limit(textCharacterCount, limits.maxTextCharacters, 'text characters', `$.nodes[${index}].components`);
551
+ }
552
+ else {
553
+ particleCapacity += count;
554
+ limit(particleCapacity, limits.maxParticleCapacity, 'particle capacity', `$.nodes[${index}].components`);
555
+ }
556
+ });
557
+ componentCount += node.components?.length ?? 0;
558
+ limit(componentCount, limits.maxComponents, 'components', `$.nodes[${index}].components`);
559
+ return node;
560
+ });
561
+ const tracksInput = array(root.tracks ?? [], '$.tracks');
562
+ limit(tracksInput.length, limits.maxTracks, 'tracks', '$.tracks');
563
+ let keyframeCount = 0;
564
+ const tracks = tracksInput.map((value, index) => {
565
+ const track = parseBinaryTrackValue(value, index, nodeIds, duration, options.copyFloatData === true);
566
+ keyframeCount += track.times.length;
567
+ limit(keyframeCount, limits.maxKeyframes, 'keyframes', `$.tracks[${index}].times`);
568
+ return track;
569
+ });
570
+ const extensionsUsed = stringList(root.extensionsUsed ?? [], '$.extensionsUsed');
571
+ const extensionsRequired = stringList(root.extensionsRequired ?? [], '$.extensionsRequired');
572
+ const extensionData = root.extensions === undefined ? {} : record(root.extensions, '$.extensions');
573
+ return finalizeParsedAnimation({
574
+ ...(typeof root.name === 'string' ? { name: root.name } : {}),
575
+ canvas,
576
+ duration,
577
+ ...(frameRate !== undefined ? { frameRate } : {}),
578
+ endBehavior,
579
+ resources,
580
+ nodes,
581
+ tracks,
582
+ extensionsUsed,
583
+ extensionsRequired,
584
+ extensions: extensionData,
585
+ }, options, source, backingBuffer);
586
+ }
587
+ /** @internal Shared semantic validation after a decoder has canonicalized every field exactly once. */
588
+ function finalizeParsedAnimation(fields, options, source, backingBuffer, graphValidated = false) {
589
+ if (fields.extensionsUsed.includes(HYA_STATE_MACHINE_EXTENSION_ID)
590
+ && !(HYA_STATE_MACHINE_EXTENSION_ID in fields.extensions)) {
591
+ fail(`Built-in extension "${HYA_STATE_MACHINE_EXTENSION_ID}" requires document data.`, `$.extensions.${HYA_STATE_MACHINE_EXTENSION_ID}`);
592
+ }
593
+ const hasHierarchy = !graphValidated && fields.nodes.some(node => node.parent !== undefined);
594
+ const hasComposites = !graphValidated && fields.nodes.some(node => node.composite !== undefined);
595
+ if (!graphValidated && (hasHierarchy || hasComposites)) {
596
+ const nodeIds = new Set(fields.nodes.map(node => node.id));
597
+ if (hasHierarchy)
598
+ validateHierarchy(fields.nodes, nodeIds);
599
+ if (hasComposites)
600
+ validateComposites(fields.nodes, nodeIds);
601
+ }
602
+ const hasResourceReferences = fields.nodes.some(node => node.components?.some(component => (component.type === 'sprite2d' || component.type === 'particle2d' || component.type === 'audio'
603
+ || (component.type === 'text2d' && component.fontResource !== undefined))));
604
+ const resourceIds = hasResourceReferences ? new Set(fields.resources.map(resource => resource.id)) : undefined;
605
+ const resourcesById = hasResourceReferences ? new Map(fields.resources.map(resource => [resource.id, resource])) : undefined;
606
+ for (let index = 0; index < fields.nodes.length; index++) {
607
+ const node = fields.nodes[index];
608
+ const start = node.start ?? 0;
609
+ if (start > fields.duration || start + (node.duration ?? fields.duration - start) > fields.duration + 1e-6) {
610
+ fail('Node time range must fit inside the composition duration.', `$.nodes[${index}]`);
611
+ }
612
+ const nodeCompositeLayers = compositeLayers(node.composite);
613
+ for (let layerIndex = 0; layerIndex < nodeCompositeLayers.length; layerIndex++) {
614
+ const track = nodeCompositeLayers[layerIndex].expansionTrack;
615
+ if (track)
616
+ validateTrackDuration(track.times, `$.nodes[${index}].composite${'layers' in node.composite ? `.layers[${layerIndex}]` : ''}.expansionTrack.times`, fields.duration);
617
+ }
618
+ for (let componentIndex = 0; componentIndex < (node.components?.length ?? 0); componentIndex++) {
619
+ const component = node.components[componentIndex];
620
+ if (component.type === ANIMATION_VECTOR_SHAPE_EXTENSION_ID) {
621
+ validateVectorTrackDurations(component, `$.nodes[${index}].components[${componentIndex}]`, fields.duration);
622
+ }
623
+ else if (component.type === 'org.haiyue.vector-path-morph@1') {
624
+ validateTrackDuration(component.times, `$.nodes[${index}].components[${componentIndex}].times`, fields.duration);
625
+ }
626
+ const sprite = component.type === 'sprite2d' ? component : undefined;
627
+ if (sprite?.uvRectTrack) {
628
+ validateTrackDuration(sprite.uvRectTrack.times, `$.nodes[${index}].components[${componentIndex}].uvRectTrack.times`, fields.duration);
629
+ }
630
+ if (component.type === 'text2d') {
631
+ const text = component;
632
+ validateTextTrackDurations(text, `$.nodes[${index}].components[${componentIndex}]`, fields.duration);
633
+ const fontResources = [text.fontResource, ...(text.documents?.map(document => document.fontResource) ?? [])]
634
+ .filter((resource) => resource !== undefined);
635
+ for (const fontResource of fontResources) {
636
+ if (!resourceIds.has(fontResource)) {
637
+ fail(`Text component references missing font resource "${fontResource}".`, `$.nodes[${index}].components[${componentIndex}].fontResource`);
638
+ }
639
+ if (resourcesById.get(fontResource)?.type !== 'binary') {
640
+ fail(`Text font resource "${fontResource}" must have type "binary".`, `$.nodes[${index}].components[${componentIndex}].fontResource`);
641
+ }
642
+ }
643
+ }
644
+ const imageResource = component.type === 'sprite2d' || component.type === 'particle2d' ? component.resource : undefined;
645
+ if (typeof imageResource === 'string' && !resourceIds.has(imageResource)) {
646
+ fail(`Component references missing resource "${imageResource}".`, `$.nodes[${index}].components[${componentIndex}].resource`);
647
+ }
648
+ if (typeof imageResource === 'string' && resourcesById.get(imageResource)?.type !== 'image') {
649
+ fail(`Component resource "${imageResource}" must have type "image".`, `$.nodes[${index}].components[${componentIndex}].resource`);
650
+ }
651
+ const audioResource = component.type === 'audio' ? component.resource : undefined;
652
+ if (typeof audioResource === 'string' && resourcesById.get(audioResource)?.type !== 'audio') {
653
+ fail(`Audio resource "${audioResource}" must have type "audio".`, `$.nodes[${index}].components[${componentIndex}].resource`);
654
+ }
655
+ }
656
+ for (let effectIndex = 0; effectIndex < (node.effects?.length ?? 0); effectIndex++) {
657
+ validateEffectTrackDurations(node.effects[effectIndex], `$.nodes[${index}].effects[${effectIndex}]`, fields.duration);
658
+ }
659
+ }
660
+ if (fields.extensionsUsed.length > 0 || fields.extensionsRequired.length > 0) {
661
+ const used = new Set(fields.extensionsUsed);
662
+ for (const id of fields.extensionsUsed)
663
+ validateExtensionId(id);
664
+ for (const id of fields.extensionsRequired) {
665
+ validateExtensionId(id);
666
+ if (!used.has(id))
667
+ fail(`Required extension "${id}" must also appear in extensionsUsed.`, '$.extensionsRequired');
668
+ if (id !== HYA_STATE_MACHINE_EXTENSION_ID && !options.extensions?.has(id)) {
669
+ throw new AnimationFormatError('E_ANIMATION_MISSING_EXTENSION', `Required extension "${id}" is not registered.`, '$.extensionsRequired');
670
+ }
671
+ }
672
+ for (let nodeIndex = 0; nodeIndex < fields.nodes.length; nodeIndex++) {
673
+ const components = fields.nodes[nodeIndex].components ?? [];
674
+ for (let componentIndex = 0; componentIndex < components.length; componentIndex++) {
675
+ const extension = extensionIdFromComponentType(components[componentIndex].type);
676
+ if (extension && !used.has(extension)) {
677
+ fail(`Extension component "${extension}" must be declared in extensionsUsed.`, `$.nodes[${nodeIndex}].components[${componentIndex}].type`);
678
+ }
679
+ }
680
+ }
681
+ for (const id of fields.extensionsUsed) {
682
+ const handler = id === HYA_STATE_MACHINE_EXTENSION_ID ? undefined : options.extensions?.get(id);
683
+ if (!handler?.validateDocument || !(id in fields.extensions))
684
+ continue;
685
+ handler.validateDocument(fields.extensions[id], extensionContext(id, `$.extensions.${id}`));
686
+ }
687
+ }
688
+ else {
689
+ for (let nodeIndex = 0; nodeIndex < fields.nodes.length; nodeIndex++) {
690
+ const components = fields.nodes[nodeIndex].components ?? [];
691
+ for (let componentIndex = 0; componentIndex < components.length; componentIndex++) {
692
+ const extension = extensionIdFromComponentType(components[componentIndex].type);
693
+ if (extension) {
694
+ fail(`Extension component "${extension}" must be declared in extensionsUsed.`, `$.nodes[${nodeIndex}].components[${componentIndex}].type`);
695
+ }
696
+ }
697
+ }
698
+ }
699
+ return Object.freeze({
700
+ format: ANIMATION_FORMAT,
701
+ version: ANIMATION_VERSION,
702
+ ...fields,
703
+ resources: Object.freeze(fields.resources),
704
+ nodes: Object.freeze(fields.nodes),
705
+ tracks: Object.freeze(fields.tracks),
706
+ extensionsUsed: Object.freeze(fields.extensionsUsed),
707
+ extensionsRequired: Object.freeze(fields.extensionsRequired),
708
+ extensions: Object.freeze({ ...fields.extensions }),
709
+ source,
710
+ ...(backingBuffer ? { backingBuffer } : {}),
711
+ });
712
+ }
713
+ function validateVectorTrackDurations(component, path, duration) {
714
+ const check = (owner, prefix, keys) => {
715
+ if (!owner)
716
+ return;
717
+ for (const key of keys) {
718
+ const track = owner[key];
719
+ if (track)
720
+ validateTrackDuration(track.times, `${path}.${prefix}${key}.times`, duration);
721
+ }
722
+ };
723
+ check(component, '', ['morph']);
724
+ check(component.fill, 'fill.', component.fill?.kind === 'solid'
725
+ ? ['colorTrack', 'opacityTrack']
726
+ : ['startTrack', 'endTrack', 'stopsTrack', 'opacityTrack']);
727
+ check(component.stroke, 'stroke.', ['colorTrack', 'opacityTrack', 'widthTrack', 'dashOffsetTrack']);
728
+ check(component.stroke?.gradient, 'stroke.gradient.', ['startTrack', 'endTrack', 'stopsTrack', 'opacityTrack']);
729
+ for (let index = 0; index < (component.modifiers?.length ?? 0); index++) {
730
+ const modifier = component.modifiers[index];
731
+ check(modifier, `modifiers[${index}].`, modifier.kind === 'trim-path'
732
+ ? ['startTrack', 'endTrack', 'offsetTrack']
733
+ : ['radiusTrack']);
734
+ }
735
+ }
736
+ function validateTextTrackDurations(component, path, duration) {
737
+ const documents = component.documents ?? [];
738
+ const lastDocument = documents[documents.length - 1];
739
+ if (lastDocument && lastDocument.time > Math.max(duration, Math.fround(duration))) {
740
+ fail('Text document time exceeds the composition duration.', `${path}.documents[${documents.length - 1}].time`);
741
+ }
742
+ for (let index = 0; index < (component.animators?.length ?? 0); index++) {
743
+ const animator = component.animators[index];
744
+ checkOwnerTrackDurations(animator.selector, `${path}.animators[${index}].selector`, ['startTrack', 'endTrack', 'offsetTrack', 'amountTrack'], duration);
745
+ checkOwnerTrackDurations(animator, `${path}.animators[${index}]`, ['positionTrack', 'scaleTrack', 'rotationTrack', 'opacityTrack', 'fillColorTrack', 'trackingTrack'], duration);
746
+ }
747
+ }
748
+ function validateEffectTrackDurations(effect, path, duration) {
749
+ const keys = effect.kind === 'tint' ? ['blackTrack', 'whiteTrack', 'amountTrack']
750
+ : effect.kind === 'fill' ? ['colorTrack', 'opacityTrack']
751
+ : effect.kind === 'opacity' ? ['opacityTrack']
752
+ : effect.kind === 'color-matrix' ? ['matrixTrack']
753
+ : effect.kind === 'blur' ? ['radiusTrack']
754
+ : ['colorTrack', 'opacityTrack', 'offsetTrack', 'blurTrack'];
755
+ checkOwnerTrackDurations(effect, path, keys, duration);
756
+ }
757
+ function checkOwnerTrackDurations(owner, path, keys, duration) {
758
+ for (const key of keys) {
759
+ const track = owner[key];
760
+ if (track)
761
+ validateTrackDuration(track.times, `${path}.${key}.times`, duration);
762
+ }
763
+ }
764
+ function validateTrackDuration(times, path, duration) {
765
+ const last = times[times.length - 1];
766
+ if (last !== undefined && last > Math.max(duration, Math.fround(duration))) {
767
+ fail('Vector track time exceeds the composition duration.', `${path}[${times.length - 1}]`);
768
+ }
769
+ }
770
+ /** @internal Compact-binary structural decoder entry point. */
771
+ function parseBinaryNodeValue(value, index, ids, options, countBudget) {
772
+ const path = `$.nodes[${index}]`;
773
+ const node = record(value, path);
774
+ const id = nonEmptyString(node.id, `${path}.id`);
775
+ if (ids.has(id))
776
+ fail(`Duplicate node id "${id}".`, `${path}.id`);
777
+ ids.add(id);
778
+ const start = node.start === undefined ? 0 : nonNegativeNumber(node.start, `${path}.start`);
779
+ const duration = node.duration === undefined ? undefined : positiveNumber(node.duration, `${path}.duration`);
780
+ const transform = node.transform === undefined ? undefined : parseTransform(node.transform, `${path}.transform`);
781
+ const components = node.components === undefined
782
+ ? undefined
783
+ : array(node.components, `${path}.components`).map((component, componentIndex) => (parseComponent(component, `${path}.components[${componentIndex}]`, options, countBudget)));
784
+ const effects = node.effects === undefined
785
+ ? undefined
786
+ : parseLayerEffects(node.effects, `${path}.effects`, options.copyFloatData === true);
787
+ return Object.freeze({
788
+ id,
789
+ ...(typeof node.name === 'string' ? { name: node.name } : {}),
790
+ ...(node.parent !== undefined ? { parent: nonEmptyString(node.parent, `${path}.parent`) } : {}),
791
+ ...(start !== 0 ? { start } : {}),
792
+ ...(duration !== undefined ? { duration } : {}),
793
+ ...(transform ? { transform } : {}),
794
+ ...(node.composite !== undefined ? {
795
+ composite: parseComposite(node.composite, `${path}.composite`, options.copyFloatData === true),
796
+ } : {}),
797
+ ...(effects ? { effects } : {}),
798
+ ...(components ? { components: Object.freeze(components) } : {}),
799
+ ...(node.extensions !== undefined ? { extensions: Object.freeze({ ...record(node.extensions, `${path}.extensions`) }) } : {}),
800
+ });
801
+ }
802
+ function parseTransform(value, path) {
803
+ const transform = record(value, path);
804
+ const opacity = transform.opacity === undefined ? undefined : unitNumber(transform.opacity, `${path}.opacity`);
805
+ return Object.freeze({
806
+ ...(transform.position !== undefined ? { position: vec2(transform.position, `${path}.position`) } : {}),
807
+ ...(transform.rotation !== undefined ? { rotation: finiteNumber$1(transform.rotation, `${path}.rotation`) } : {}),
808
+ ...(transform.scale !== undefined ? { scale: vec2(transform.scale, `${path}.scale`) } : {}),
809
+ ...(transform.anchor !== undefined ? { anchor: vec2(transform.anchor, `${path}.anchor`) } : {}),
810
+ ...(opacity !== undefined ? { opacity } : {}),
811
+ });
812
+ }
813
+ /** @internal Compact-binary transform decoder entry point. */
814
+ function parseBinaryTransformValue(value, path) {
815
+ return parseTransform(value, path);
816
+ }
817
+ function parseComponent(value, path, options, countBudget) {
818
+ const component = record(value, path);
819
+ const type = nonEmptyString(component.type, `${path}.type`);
820
+ if (type === 'shape2d') {
821
+ return Object.freeze({
822
+ type,
823
+ shape: literal(component.shape, ['rect', 'ellipse'], `${path}.shape`),
824
+ size: positiveVec2(component.size, `${path}.size`),
825
+ fill: color(component.fill, `${path}.fill`),
826
+ ...(component.position !== undefined ? { position: vec2(component.position, `${path}.position`) } : {}),
827
+ });
828
+ }
829
+ if (type === 'path2d') {
830
+ const commands = nonEmptyString(component.commands, `${path}.commands`).toUpperCase();
831
+ if (!/^[MLQCZ]+$/.test(commands) || commands[0] !== 'M')
832
+ fail('Path commands must start with M and contain only M, L, Q, C, Z.', `${path}.commands`);
833
+ validatePathTopology(commands, `${path}.commands`);
834
+ const values = floatArray(component.values, `${path}.values`, options.copyFloatData === true);
835
+ const expected = pathValueCount(commands);
836
+ if (values.length !== expected)
837
+ fail(`Path values length must be ${expected} for command stream "${commands}".`, `${path}.values`);
838
+ if (!commands.includes('Z'))
839
+ fail('Filled path must contain at least one closed contour (Z).', `${path}.commands`);
840
+ countBudget('path', values.length);
841
+ return Object.freeze({
842
+ type,
843
+ commands,
844
+ values,
845
+ fill: color(component.fill, `${path}.fill`),
846
+ fillRule: component.fillRule === undefined ? 'nonzero' : literal(component.fillRule, ['nonzero', 'evenodd'], `${path}.fillRule`),
847
+ tolerance: component.tolerance === undefined ? 0.35 : positiveNumber(component.tolerance, `${path}.tolerance`),
848
+ });
849
+ }
850
+ if (type === 'sprite2d') {
851
+ const uvRectTrack = component.uvRectTrack === undefined
852
+ ? undefined
853
+ : parseVectorValueTrack(component.uvRectTrack, `${path}.uvRectTrack`, 4, options.copyFloatData === true);
854
+ if (uvRectTrack && uvRectTrack.interpolation !== 'step') {
855
+ fail('Sprite uvRectTrack requires step interpolation.', `${path}.uvRectTrack.interpolation`);
856
+ }
857
+ if (uvRectTrack)
858
+ validateUvRectTrack(uvRectTrack, `${path}.uvRectTrack`);
859
+ return Object.freeze({
860
+ type,
861
+ resource: nonEmptyString(component.resource, `${path}.resource`),
862
+ size: positiveVec2(component.size, `${path}.size`),
863
+ ...(component.position !== undefined ? { position: vec2(component.position, `${path}.position`) } : {}),
864
+ ...(component.tint !== undefined ? { tint: color(component.tint, `${path}.tint`) } : {}),
865
+ ...(component.uvRect !== undefined ? { uvRect: uvRect(component.uvRect, `${path}.uvRect`) } : {}),
866
+ ...(uvRectTrack ? { uvRectTrack } : {}),
867
+ });
868
+ }
869
+ if (type === 'text2d') {
870
+ if (typeof component.text !== 'string')
871
+ fail('Expected text to be a string.', `${path}.text`);
872
+ countBudget('text', component.text.length);
873
+ const resolutionScale = component.resolutionScale === undefined ? undefined : positiveNumber(component.resolutionScale, `${path}.resolutionScale`);
874
+ if (resolutionScale !== undefined && resolutionScale > 4)
875
+ fail('resolutionScale must be at most 4.', `${path}.resolutionScale`);
876
+ const documents = component.documents === undefined ? undefined : parseTextDocuments(component.documents, `${path}.documents`);
877
+ const animators = component.animators === undefined ? undefined : parseTextAnimators(component.animators, `${path}.animators`, options.copyFloatData === true);
878
+ if (documents)
879
+ for (const document of documents)
880
+ countBudget('text', document.text.length);
881
+ return Object.freeze({
882
+ type,
883
+ text: component.text,
884
+ size: positiveVec2(component.size, `${path}.size`),
885
+ color: color(component.color, `${path}.color`),
886
+ ...(component.position !== undefined ? { position: vec2(component.position, `${path}.position`) } : {}),
887
+ ...(component.fontFamily !== undefined ? { fontFamily: nonEmptyString(component.fontFamily, `${path}.fontFamily`) } : {}),
888
+ ...(component.fontSize !== undefined ? { fontSize: positiveNumber(component.fontSize, `${path}.fontSize`) } : {}),
889
+ ...(component.fontWeight !== undefined ? { fontWeight: fontWeight(component.fontWeight, `${path}.fontWeight`) } : {}),
890
+ ...(component.fontStyle !== undefined ? { fontStyle: literal(component.fontStyle, ['normal', 'italic'], `${path}.fontStyle`) } : {}),
891
+ ...(component.fontResource !== undefined ? { fontResource: nonEmptyString(component.fontResource, `${path}.fontResource`) } : {}),
892
+ ...(component.lineHeight !== undefined ? { lineHeight: positiveNumber(component.lineHeight, `${path}.lineHeight`) } : {}),
893
+ ...(component.tracking !== undefined ? { tracking: finiteNumber$1(component.tracking, `${path}.tracking`) } : {}),
894
+ ...(component.textAlign !== undefined ? { textAlign: literal(component.textAlign, ['left', 'center', 'right'], `${path}.textAlign`) } : {}),
895
+ ...(component.verticalAlign !== undefined ? { verticalAlign: literal(component.verticalAlign, ['top', 'middle', 'bottom'], `${path}.verticalAlign`) } : {}),
896
+ ...(component.backgroundColor !== undefined ? { backgroundColor: color(component.backgroundColor, `${path}.backgroundColor`) } : {}),
897
+ ...(component.padding !== undefined ? { padding: nonNegativeNumber(component.padding, `${path}.padding`) } : {}),
898
+ ...(resolutionScale !== undefined ? { resolutionScale } : {}),
899
+ ...(documents ? { documents } : {}),
900
+ ...(animators ? { animators } : {}),
901
+ });
902
+ }
903
+ if (type === 'particle2d') {
904
+ const maxParticles = boundedInteger(component.maxParticles, 1, 1_000_000, `${path}.maxParticles`);
905
+ countBudget('particle', maxParticles);
906
+ return Object.freeze({
907
+ type,
908
+ maxParticles,
909
+ emissionRate: nonNegativeNumber(component.emissionRate, `${path}.emissionRate`),
910
+ lifetime: numericRange(component.lifetime, `${path}.lifetime`, 1e-4),
911
+ speed: numericRange(component.speed, `${path}.speed`, 0),
912
+ angle: numericRange(component.angle, `${path}.angle`),
913
+ startSize: numericRange(component.startSize, `${path}.startSize`, 0),
914
+ endSize: numericRange(component.endSize, `${path}.endSize`, 0),
915
+ startColor: color(component.startColor, `${path}.startColor`),
916
+ endColor: color(component.endColor, `${path}.endColor`),
917
+ ...(component.burst !== undefined ? { burst: boundedInteger(component.burst, 0, maxParticles, `${path}.burst`) } : {}),
918
+ ...(component.duration !== undefined ? { duration: positiveNumber(component.duration, `${path}.duration`) } : {}),
919
+ ...(component.loop !== undefined ? { loop: booleanValue(component.loop, `${path}.loop`) } : {}),
920
+ ...(component.seed !== undefined ? { seed: safeInteger(component.seed, `${path}.seed`) } : {}),
921
+ ...(component.gravity !== undefined ? { gravity: vec2(component.gravity, `${path}.gravity`) } : {}),
922
+ ...(component.shape !== undefined ? { shape: literal(component.shape, ['point', 'box', 'circle'], `${path}.shape`) } : {}),
923
+ ...(component.shapeSize !== undefined ? { shapeSize: nonNegativeVec2(component.shapeSize, `${path}.shapeSize`) } : {}),
924
+ ...(component.shapeRadius !== undefined ? { shapeRadius: nonNegativeNumber(component.shapeRadius, `${path}.shapeRadius`) } : {}),
925
+ ...(component.blendMode !== undefined ? { blendMode: literal(component.blendMode, ['normal', 'additive'], `${path}.blendMode`) } : {}),
926
+ ...(component.resource !== undefined ? { resource: nonEmptyString(component.resource, `${path}.resource`) } : {}),
927
+ ...(component.radial !== undefined ? { radial: booleanValue(component.radial, `${path}.radial`) } : {}),
928
+ });
929
+ }
930
+ if (type === 'audio') {
931
+ return Object.freeze({
932
+ type,
933
+ resource: nonEmptyString(component.resource, `${path}.resource`),
934
+ ...(component.volume !== undefined ? { volume: unitNumber(component.volume, `${path}.volume`) } : {}),
935
+ ...(component.loop !== undefined ? { loop: booleanValue(component.loop, `${path}.loop`) } : {}),
936
+ ...(component.startOffset !== undefined ? { startOffset: nonNegativeNumber(component.startOffset, `${path}.startOffset`) } : {}),
937
+ ...(component.playbackRate !== undefined ? { playbackRate: positiveNumber(component.playbackRate, `${path}.playbackRate`) } : {}),
938
+ });
939
+ }
940
+ if (type === 'org.haiyue.vector-path-morph@1') {
941
+ const commands = nonEmptyString(component.commands, `${path}.commands`).toUpperCase();
942
+ if (!/^[MLQCZ]+$/.test(commands) || commands[0] !== 'M')
943
+ fail('Path morph commands must start with M and contain only M, L, Q, C, Z.', `${path}.commands`);
944
+ validatePathTopology(commands, `${path}.commands`);
945
+ if (!commands.includes('Z'))
946
+ fail('Filled path morph must contain at least one closed contour (Z).', `${path}.commands`);
947
+ const times = floatArray(component.times, `${path}.times`, options.copyFloatData === true);
948
+ const values = floatArray(component.values, `${path}.values`, options.copyFloatData === true);
949
+ const valueSize = safeInteger(component.valueSize, `${path}.valueSize`);
950
+ if (valueSize !== pathValueCount(commands))
951
+ fail(`Path morph valueSize must be ${pathValueCount(commands)} for command stream "${commands}".`, `${path}.valueSize`);
952
+ if (times.length === 0 || values.length !== times.length * valueSize)
953
+ fail('Path morph values must contain valueSize numbers for every keyframe.', `${path}.values`);
954
+ for (let index = 0; index < times.length; index++) {
955
+ if (times[index] < 0 || (index > 0 && times[index] <= times[index - 1]))
956
+ fail('Path morph times must be non-negative and strictly increasing.', `${path}.times`);
957
+ }
958
+ const interpolation = literal(component.interpolation, ['step', 'linear', 'cubic-bezier'], `${path}.interpolation`);
959
+ const easings = component.easings === undefined ? undefined : floatArray(component.easings, `${path}.easings`, options.copyFloatData === true);
960
+ if (interpolation === 'cubic-bezier' && easings?.length !== Math.max(0, times.length - 1) * 4)
961
+ fail('Cubic path morph easing data must contain four numbers per segment.', `${path}.easings`);
962
+ countBudget('path', values.length);
963
+ return Object.freeze({
964
+ type,
965
+ commands,
966
+ times,
967
+ values,
968
+ valueSize,
969
+ interpolation,
970
+ ...(easings === undefined ? {} : { easings }),
971
+ fill: color(component.fill, `${path}.fill`),
972
+ fillRule: component.fillRule === undefined ? 'nonzero' : literal(component.fillRule, ['nonzero', 'evenodd'], `${path}.fillRule`),
973
+ tolerance: component.tolerance === undefined ? 0.35 : positiveNumber(component.tolerance, `${path}.tolerance`),
974
+ });
975
+ }
976
+ if (type === ANIMATION_VECTOR_SHAPE_EXTENSION_ID) {
977
+ const commands = nonEmptyString(component.commands, `${path}.commands`).toUpperCase();
978
+ if (!/^[MLQCZ]+$/.test(commands) || commands[0] !== 'M')
979
+ fail('Vector shape commands must start with M and contain only M, L, Q, C, Z.', `${path}.commands`);
980
+ validatePathTopology(commands, `${path}.commands`, component.fill !== undefined);
981
+ const values = floatArray(component.values, `${path}.values`, options.copyFloatData === true);
982
+ const valueSize = pathValueCount(commands);
983
+ if (values.length !== valueSize)
984
+ fail(`Vector shape values length must be ${valueSize}.`, `${path}.values`);
985
+ const morph = component.morph === undefined ? undefined : parseVectorValueTrack(component.morph, `${path}.morph`, valueSize, options.copyFloatData === true);
986
+ const fill = component.fill === undefined ? undefined : parseVectorFill(component.fill, `${path}.fill`, options.copyFloatData === true);
987
+ const stroke = component.stroke === undefined ? undefined : parseVectorStroke(component.stroke, `${path}.stroke`, options.copyFloatData === true);
988
+ const modifiers = component.modifiers === undefined
989
+ ? undefined
990
+ : array(component.modifiers, `${path}.modifiers`).map((modifier, index) => (parseVectorModifier(modifier, `${path}.modifiers[${index}]`, options.copyFloatData === true)));
991
+ if (modifiers && (modifiers.length < 1 || modifiers.length > 8))
992
+ fail('Vector shape modifiers must contain 1–8 entries.', `${path}.modifiers`);
993
+ if (!fill && !stroke)
994
+ fail('Vector shape requires a fill or stroke paint.', path);
995
+ countBudget('path', values.length + (morph?.values.length ?? 0));
996
+ return Object.freeze({
997
+ type,
998
+ commands,
999
+ values,
1000
+ ...(morph ? { morph } : {}),
1001
+ ...(component.morphRelative === true ? { morphRelative: true } : {}),
1002
+ ...(fill ? { fill } : {}),
1003
+ ...(stroke ? { stroke } : {}),
1004
+ ...(modifiers ? { modifiers: Object.freeze(modifiers) } : {}),
1005
+ fillRule: component.fillRule === undefined ? 'nonzero' : literal(component.fillRule, ['nonzero', 'evenodd'], `${path}.fillRule`),
1006
+ tolerance: component.tolerance === undefined ? 0.35 : positiveNumber(component.tolerance, `${path}.tolerance`),
1007
+ });
1008
+ }
1009
+ validateExtensionId(type);
1010
+ const handler = options.extensions?.get(extensionIdFromComponentType(type));
1011
+ handler?.validateComponent?.(component, extensionContext(type, path));
1012
+ return Object.freeze({ ...component, type });
1013
+ }
1014
+ function parseTextDocuments(value, path) {
1015
+ const documents = array(value, path);
1016
+ if (documents.length < 1 || documents.length > 128)
1017
+ fail('Text documents must contain 1–128 keyframes.', path);
1018
+ let previousTime = -1;
1019
+ return Object.freeze(documents.map((value, index) => {
1020
+ const documentPath = `${path}[${index}]`;
1021
+ const document = record(value, documentPath);
1022
+ const time = nonNegativeNumber(document.time, `${documentPath}.time`);
1023
+ if (time <= previousTime)
1024
+ fail('Text document times must be strictly increasing.', `${documentPath}.time`);
1025
+ previousTime = time;
1026
+ if (typeof document.text !== 'string')
1027
+ fail('Expected text to be a string.', `${documentPath}.text`);
1028
+ return Object.freeze({
1029
+ time,
1030
+ text: document.text,
1031
+ ...(document.fontFamily === undefined ? {} : { fontFamily: nonEmptyString(document.fontFamily, `${documentPath}.fontFamily`) }),
1032
+ ...(document.fontSize === undefined ? {} : { fontSize: positiveNumber(document.fontSize, `${documentPath}.fontSize`) }),
1033
+ ...(document.fontWeight === undefined ? {} : { fontWeight: fontWeight(document.fontWeight, `${documentPath}.fontWeight`) }),
1034
+ ...(document.fontStyle === undefined ? {} : { fontStyle: literal(document.fontStyle, ['normal', 'italic'], `${documentPath}.fontStyle`) }),
1035
+ ...(document.fontResource === undefined ? {} : { fontResource: nonEmptyString(document.fontResource, `${documentPath}.fontResource`) }),
1036
+ ...(document.lineHeight === undefined ? {} : { lineHeight: positiveNumber(document.lineHeight, `${documentPath}.lineHeight`) }),
1037
+ ...(document.tracking === undefined ? {} : { tracking: finiteNumber$1(document.tracking, `${documentPath}.tracking`) }),
1038
+ ...(document.textAlign === undefined ? {} : { textAlign: literal(document.textAlign, ['left', 'center', 'right'], `${documentPath}.textAlign`) }),
1039
+ ...(document.color === undefined ? {} : { color: color(document.color, `${documentPath}.color`) }),
1040
+ });
1041
+ }));
1042
+ }
1043
+ function parseTextAnimators(value, path, copy) {
1044
+ const animators = array(value, path);
1045
+ if (animators.length < 1 || animators.length > 16)
1046
+ fail('Text animators must contain 1–16 entries.', path);
1047
+ return Object.freeze(animators.map((value, index) => {
1048
+ const animatorPath = `${path}[${index}]`;
1049
+ const animator = record(value, animatorPath);
1050
+ const selectorPath = `${animatorPath}.selector`;
1051
+ const selector = record(animator.selector, selectorPath);
1052
+ const amount = selector.amount === undefined ? undefined : finiteNumber$1(selector.amount, `${selectorPath}.amount`);
1053
+ if (amount !== undefined && (amount < -1 || amount > 1))
1054
+ fail('Text selector amount must be in [-1, 1].', `${selectorPath}.amount`);
1055
+ return Object.freeze({
1056
+ selector: Object.freeze({
1057
+ start: finiteNumber$1(selector.start, `${selectorPath}.start`),
1058
+ end: finiteNumber$1(selector.end, `${selectorPath}.end`),
1059
+ ...(selector.offset === undefined ? {} : { offset: finiteNumber$1(selector.offset, `${selectorPath}.offset`) }),
1060
+ ...(selector.units === undefined ? {} : { units: literal(selector.units, ['percent', 'index'], `${selectorPath}.units`) }),
1061
+ ...(amount === undefined ? {} : { amount }),
1062
+ ...(selector.shape === undefined ? {} : { shape: literal(selector.shape, TEXT_SELECTOR_SHAPES, `${selectorPath}.shape`) }),
1063
+ ...(selector.basedOn === undefined ? {} : { basedOn: literal(selector.basedOn, TEXT_SELECTOR_BASES, `${selectorPath}.basedOn`) }),
1064
+ ...(selector.easing === undefined ? {} : { easing: color(selector.easing, `${selectorPath}.easing`) }),
1065
+ ...(selector.smoothness === undefined ? {} : { smoothness: unitNumber(selector.smoothness, `${selectorPath}.smoothness`) }),
1066
+ ...(selector.randomSeed === undefined ? {} : { randomSeed: boundedInteger(selector.randomSeed, 0, 0xffffffff, `${selectorPath}.randomSeed`) }),
1067
+ ...parseVectorTrackField(selector, 'startTrack', selectorPath, 1, copy),
1068
+ ...parseVectorTrackField(selector, 'endTrack', selectorPath, 1, copy),
1069
+ ...parseVectorTrackField(selector, 'offsetTrack', selectorPath, 1, copy),
1070
+ ...parseVectorTrackField(selector, 'amountTrack', selectorPath, 1, copy),
1071
+ }),
1072
+ ...(animator.position === undefined ? {} : { position: vec2(animator.position, `${animatorPath}.position`) }),
1073
+ ...(animator.scale === undefined ? {} : { scale: vec2(animator.scale, `${animatorPath}.scale`) }),
1074
+ ...(animator.rotation === undefined ? {} : { rotation: finiteNumber$1(animator.rotation, `${animatorPath}.rotation`) }),
1075
+ ...(animator.opacity === undefined ? {} : { opacity: unitNumber(animator.opacity, `${animatorPath}.opacity`) }),
1076
+ ...(animator.fillColor === undefined ? {} : { fillColor: color(animator.fillColor, `${animatorPath}.fillColor`) }),
1077
+ ...(animator.tracking === undefined ? {} : { tracking: finiteNumber$1(animator.tracking, `${animatorPath}.tracking`) }),
1078
+ ...parseVectorTrackField(animator, 'positionTrack', animatorPath, 2, copy),
1079
+ ...parseVectorTrackField(animator, 'scaleTrack', animatorPath, 2, copy),
1080
+ ...parseVectorTrackField(animator, 'rotationTrack', animatorPath, 1, copy),
1081
+ ...parseVectorTrackField(animator, 'opacityTrack', animatorPath, 1, copy),
1082
+ ...parseVectorTrackField(animator, 'fillColorTrack', animatorPath, 4, copy),
1083
+ ...parseVectorTrackField(animator, 'trackingTrack', animatorPath, 1, copy),
1084
+ });
1085
+ }));
1086
+ }
1087
+ function parseLayerEffects(value, path, copy) {
1088
+ const effects = array(value, path);
1089
+ if (effects.length < 1 || effects.length > 8)
1090
+ fail('Layer effects must contain 1–8 ordered entries.', path);
1091
+ return Object.freeze(effects.map((value, index) => {
1092
+ const effectPath = `${path}[${index}]`;
1093
+ const effect = record(value, effectPath);
1094
+ const kind = literal(effect.kind, ['tint', 'fill', 'opacity', 'color-matrix', 'blur', 'drop-shadow'], `${effectPath}.kind`);
1095
+ if (kind === 'tint')
1096
+ return Object.freeze({
1097
+ kind,
1098
+ black: unitVec3(effect.black, `${effectPath}.black`),
1099
+ white: unitVec3(effect.white, `${effectPath}.white`),
1100
+ amount: unitNumber(effect.amount, `${effectPath}.amount`),
1101
+ ...parseVectorTrackField(effect, 'blackTrack', effectPath, 3, copy),
1102
+ ...parseVectorTrackField(effect, 'whiteTrack', effectPath, 3, copy),
1103
+ ...parseVectorTrackField(effect, 'amountTrack', effectPath, 1, copy),
1104
+ });
1105
+ if (kind === 'fill')
1106
+ return Object.freeze({
1107
+ kind,
1108
+ color: color(effect.color, `${effectPath}.color`),
1109
+ ...(effect.opacity === undefined ? {} : { opacity: unitNumber(effect.opacity, `${effectPath}.opacity`) }),
1110
+ ...parseVectorTrackField(effect, 'colorTrack', effectPath, 4, copy),
1111
+ ...parseVectorTrackField(effect, 'opacityTrack', effectPath, 1, copy),
1112
+ });
1113
+ if (kind === 'opacity')
1114
+ return Object.freeze({
1115
+ kind,
1116
+ opacity: unitNumber(effect.opacity, `${effectPath}.opacity`),
1117
+ ...parseVectorTrackField(effect, 'opacityTrack', effectPath, 1, copy),
1118
+ });
1119
+ if (kind === 'color-matrix') {
1120
+ const matrix = floatArray(effect.matrix, `${effectPath}.matrix`, copy);
1121
+ if (matrix.length !== 20)
1122
+ fail('Color matrix must contain exactly 20 values.', `${effectPath}.matrix`);
1123
+ return Object.freeze({
1124
+ kind, matrix,
1125
+ ...parseVectorTrackField(effect, 'matrixTrack', effectPath, 20, copy),
1126
+ });
1127
+ }
1128
+ if (kind === 'blur')
1129
+ return Object.freeze({
1130
+ kind,
1131
+ radius: nonNegativeVec2(effect.radius, `${effectPath}.radius`),
1132
+ ...parseVectorTrackField(effect, 'radiusTrack', effectPath, 2, copy),
1133
+ });
1134
+ return Object.freeze({
1135
+ kind,
1136
+ color: color(effect.color, `${effectPath}.color`),
1137
+ opacity: unitNumber(effect.opacity, `${effectPath}.opacity`),
1138
+ offset: vec2(effect.offset, `${effectPath}.offset`),
1139
+ blur: nonNegativeNumber(effect.blur, `${effectPath}.blur`),
1140
+ ...parseVectorTrackField(effect, 'colorTrack', effectPath, 4, copy),
1141
+ ...parseVectorTrackField(effect, 'opacityTrack', effectPath, 1, copy),
1142
+ ...parseVectorTrackField(effect, 'offsetTrack', effectPath, 2, copy),
1143
+ ...parseVectorTrackField(effect, 'blurTrack', effectPath, 1, copy),
1144
+ });
1145
+ }));
1146
+ }
1147
+ /** @internal Compact-binary effect decoder entry point. */
1148
+ function parseBinaryEffectsValue(value, path, copy) {
1149
+ return parseLayerEffects(value, path, copy);
1150
+ }
1151
+ function parseVectorModifier(value, path, copy) {
1152
+ const modifier = record(value, path);
1153
+ const kind = literal(modifier.kind, ['trim-path', 'round-corners'], `${path}.kind`);
1154
+ if (kind === 'round-corners')
1155
+ return Object.freeze({
1156
+ kind,
1157
+ radius: nonNegativeNumber(modifier.radius, `${path}.radius`),
1158
+ ...parseVectorTrackField(modifier, 'radiusTrack', path, 1, copy),
1159
+ });
1160
+ return Object.freeze({
1161
+ kind,
1162
+ start: finiteNumber$1(modifier.start, `${path}.start`),
1163
+ end: finiteNumber$1(modifier.end, `${path}.end`),
1164
+ offset: finiteNumber$1(modifier.offset, `${path}.offset`),
1165
+ mode: literal(modifier.mode, ['simultaneous', 'individual'], `${path}.mode`),
1166
+ ...parseVectorTrackField(modifier, 'startTrack', path, 1, copy),
1167
+ ...parseVectorTrackField(modifier, 'endTrack', path, 1, copy),
1168
+ ...parseVectorTrackField(modifier, 'offsetTrack', path, 1, copy),
1169
+ });
1170
+ }
1171
+ function parseVectorTrackField(owner, key, path, valueSize, copy) {
1172
+ const value = owner[key];
1173
+ return value === undefined ? {} : { [key]: parseVectorValueTrack(value, `${path}.${key}`, valueSize, copy) };
1174
+ }
1175
+ function parseVectorValueTrack(value, path, expectedValueSize, copy) {
1176
+ const track = record(value, path);
1177
+ const valueSize = safeInteger(track.valueSize, `${path}.valueSize`);
1178
+ if (valueSize < 1 || valueSize > 4096 || (expectedValueSize !== undefined && valueSize !== expectedValueSize)) {
1179
+ fail(`Vector track valueSize must be ${expectedValueSize ?? 'between 1 and 4096'}.`, `${path}.valueSize`);
1180
+ }
1181
+ const times = floatArray(track.times, `${path}.times`, copy);
1182
+ const values = floatArray(track.values, `${path}.values`, copy);
1183
+ if (times.length < 1 || values.length !== times.length * valueSize)
1184
+ fail('Vector track values must contain valueSize numbers for every keyframe.', `${path}.values`);
1185
+ for (let index = 0; index < times.length; index++) {
1186
+ if (times[index] < 0 || (index > 0 && times[index] <= times[index - 1]))
1187
+ fail('Vector track times must be non-negative and strictly increasing.', `${path}.times`);
1188
+ }
1189
+ const interpolation = literal(track.interpolation, ['step', 'linear', 'cubic-bezier'], `${path}.interpolation`);
1190
+ const easings = track.easings === undefined ? undefined : floatArray(track.easings, `${path}.easings`, copy);
1191
+ if (interpolation === 'cubic-bezier' && easings?.length !== Math.max(0, times.length - 1) * 4)
1192
+ fail('Cubic vector track easing data must contain four numbers per segment.', `${path}.easings`);
1193
+ if (interpolation !== 'cubic-bezier' && easings !== undefined)
1194
+ fail('Vector track easings require cubic-bezier interpolation.', `${path}.easings`);
1195
+ return Object.freeze({ times, values, valueSize, interpolation, ...(easings ? { easings } : {}) });
1196
+ }
1197
+ function parseVectorFill(value, path, copy) {
1198
+ const fill = record(value, path);
1199
+ const kind = literal(fill.kind, ['solid', 'linear-gradient', 'radial-gradient'], `${path}.kind`);
1200
+ const opacityTrack = fill.opacityTrack === undefined ? undefined : parseVectorValueTrack(fill.opacityTrack, `${path}.opacityTrack`, 1, copy);
1201
+ if (kind === 'solid') {
1202
+ return Object.freeze({
1203
+ kind,
1204
+ color: color(fill.color, `${path}.color`),
1205
+ ...(fill.opacity === undefined ? {} : { opacity: unitNumber(fill.opacity, `${path}.opacity`) }),
1206
+ ...parseVectorTrackField(fill, 'colorTrack', path, 4, copy),
1207
+ ...(opacityTrack ? { opacityTrack } : {}),
1208
+ });
1209
+ }
1210
+ const stops = floatArray(fill.stops, `${path}.stops`, copy);
1211
+ if (stops.length < 10 || stops.length > 40 || stops.length % 5 !== 0)
1212
+ fail('Gradient stops must contain 2–8 offset,r,g,b,a tuples.', `${path}.stops`);
1213
+ let previousOffset = -Infinity;
1214
+ for (let offset = 0; offset < stops.length; offset += 5) {
1215
+ if (stops[offset] < previousOffset || stops[offset] < 0 || stops[offset] > 1)
1216
+ fail('Gradient stop offsets must be ordered in [0, 1].', `${path}.stops[${offset}]`);
1217
+ previousOffset = stops[offset];
1218
+ for (let channel = 1; channel < 5; channel++)
1219
+ if (stops[offset + channel] < 0 || stops[offset + channel] > 1)
1220
+ fail('Gradient stop channels must be in [0, 1].', `${path}.stops[${offset + channel}]`);
1221
+ }
1222
+ return Object.freeze({
1223
+ kind,
1224
+ start: vec2(fill.start, `${path}.start`),
1225
+ end: vec2(fill.end, `${path}.end`),
1226
+ stops,
1227
+ ...(fill.opacity === undefined ? {} : { opacity: unitNumber(fill.opacity, `${path}.opacity`) }),
1228
+ ...parseVectorTrackField(fill, 'startTrack', path, 2, copy),
1229
+ ...parseVectorTrackField(fill, 'endTrack', path, 2, copy),
1230
+ ...parseVectorTrackField(fill, 'stopsTrack', path, stops.length, copy),
1231
+ ...(opacityTrack ? { opacityTrack } : {}),
1232
+ });
1233
+ }
1234
+ function parseVectorStroke(value, path, copy) {
1235
+ const stroke = record(value, path);
1236
+ const dash = stroke.dash === undefined ? undefined : floatArray(stroke.dash, `${path}.dash`, copy);
1237
+ if (dash && (dash.length < 1 || dash.length > 32 || Array.from(dash).some(value => value < 0)))
1238
+ fail('Stroke dash values must contain 1–32 non-negative numbers.', `${path}.dash`);
1239
+ const gradient = stroke.gradient === undefined ? undefined : parseVectorFill(stroke.gradient, `${path}.gradient`, copy);
1240
+ if (gradient?.kind === 'solid')
1241
+ fail('Stroke gradient must be linear-gradient or radial-gradient.', `${path}.gradient.kind`);
1242
+ return Object.freeze({
1243
+ color: color(stroke.color, `${path}.color`),
1244
+ width: positiveNumber(stroke.width, `${path}.width`),
1245
+ ...(stroke.opacity === undefined ? {} : { opacity: unitNumber(stroke.opacity, `${path}.opacity`) }),
1246
+ lineCap: literal(stroke.lineCap, ['butt', 'round', 'square'], `${path}.lineCap`),
1247
+ lineJoin: literal(stroke.lineJoin, ['miter', 'round', 'bevel'], `${path}.lineJoin`),
1248
+ miterLimit: positiveNumber(stroke.miterLimit, `${path}.miterLimit`),
1249
+ ...(gradient ? { gradient } : {}),
1250
+ ...(dash ? { dash } : {}),
1251
+ ...(stroke.dashOffset === undefined ? {} : { dashOffset: finiteNumber$1(stroke.dashOffset, `${path}.dashOffset`) }),
1252
+ ...parseVectorTrackField(stroke, 'colorTrack', path, 4, copy),
1253
+ ...parseVectorTrackField(stroke, 'opacityTrack', path, 1, copy),
1254
+ ...parseVectorTrackField(stroke, 'widthTrack', path, 1, copy),
1255
+ ...parseVectorTrackField(stroke, 'dashOffsetTrack', path, 1, copy),
1256
+ });
1257
+ }
1258
+ /** @internal Compact-binary component decoder entry point. */
1259
+ function parseBinaryComponentValue(value, path, options, countBudget) {
1260
+ return parseComponent(value, path, options, countBudget);
1261
+ }
1262
+ function parseComposite(value, path, copy) {
1263
+ const composite = record(value, path);
1264
+ if (composite.layers !== undefined) {
1265
+ const values = array(composite.layers, `${path}.layers`);
1266
+ if (values.length < 1 || values.length > 8)
1267
+ fail('Composite stacks must contain between 1 and 8 layers.', `${path}.layers`);
1268
+ return Object.freeze({
1269
+ layers: Object.freeze(values.map((layer, index) => parseCompositeLayer(layer, `${path}.layers[${index}]`, copy))),
1270
+ });
1271
+ }
1272
+ return parseCompositeLayer(composite, path, copy);
1273
+ }
1274
+ function parseCompositeLayer(value, path, copy) {
1275
+ const composite = record(value, path);
1276
+ return Object.freeze({
1277
+ kind: literal(composite.kind, ['mask', 'matte'], `${path}.kind`),
1278
+ source: nonEmptyString(composite.source, `${path}.source`),
1279
+ mode: literal(composite.mode, ['alpha', 'alpha-inverted', 'luma', 'luma-inverted'], `${path}.mode`),
1280
+ ...(composite.operation === undefined ? {} : {
1281
+ operation: literal(composite.operation, ['add', 'subtract', 'intersect', 'difference'], `${path}.operation`),
1282
+ }),
1283
+ ...(composite.feather === undefined ? {} : { feather: nonNegativeVec2(composite.feather, `${path}.feather`) }),
1284
+ ...(composite.expansion === undefined ? {} : { expansion: finiteNumber$1(composite.expansion, `${path}.expansion`) }),
1285
+ ...parseVectorTrackField(composite, 'expansionTrack', path, 1, copy),
1286
+ });
1287
+ }
1288
+ /** @internal Compact-binary structural decoder entry point. */
1289
+ function parseBinaryTrackValue(value, index, nodeIds, duration, copy) {
1290
+ const path = `$.tracks[${index}]`;
1291
+ const track = record(value, path);
1292
+ const node = nonEmptyString(track.node, `${path}.node`);
1293
+ if (!nodeIds.has(node))
1294
+ fail(`Track references missing node "${node}".`, `${path}.node`);
1295
+ const property = literal(track.property, ['position', 'rotation', 'scale', 'opacity'], `${path}.property`);
1296
+ const interpolation = literal(track.interpolation, ['step', 'linear', 'cubic-bezier'], `${path}.interpolation`);
1297
+ const times = floatArray(track.times, `${path}.times`, copy);
1298
+ if (times.length < 1)
1299
+ fail('Track must contain at least one keyframe.', `${path}.times`);
1300
+ let previous = -Infinity;
1301
+ // Track pools are Float32-backed. A source key exactly at a non-representable
1302
+ // composition duration may round above the Float64 duration, but no later
1303
+ // representable Float32 value is part of that boundary.
1304
+ const maximumTrackTime = Math.max(duration, Math.fround(duration));
1305
+ for (let i = 0; i < times.length; i++) {
1306
+ const current = requiredFloat(times, i, `${path}.times`);
1307
+ if (current < 0 || current <= previous)
1308
+ fail('Track times must be finite, non-negative and strictly increasing.', `${path}.times[${i}]`);
1309
+ if (current > maximumTrackTime)
1310
+ fail('Track time exceeds the composition duration.', `${path}.times[${i}]`);
1311
+ previous = current;
1312
+ }
1313
+ const valueSize = trackValueSize(property);
1314
+ const values = floatArray(track.values, `${path}.values`, copy);
1315
+ if (values.length !== times.length * valueSize) {
1316
+ fail(`Track values length must equal keyframe count × ${valueSize}.`, `${path}.values`);
1317
+ }
1318
+ const easings = track.easings === undefined ? undefined : floatArray(track.easings, `${path}.easings`, copy);
1319
+ if (interpolation === 'cubic-bezier') {
1320
+ const expected = Math.max(0, times.length - 1) * 4;
1321
+ if (!easings || easings.length !== expected)
1322
+ fail(`Cubic track easings length must be ${expected}.`, `${path}.easings`);
1323
+ for (let i = 0; i < easings.length; i += 4) {
1324
+ if (requiredFloat(easings, i, `${path}.easings`) < 0 || requiredFloat(easings, i, `${path}.easings`) > 1
1325
+ || requiredFloat(easings, i + 2, `${path}.easings`) < 0 || requiredFloat(easings, i + 2, `${path}.easings`) > 1) {
1326
+ fail('Cubic easing x control points must be in [0, 1].', `${path}.easings[${i}]`);
1327
+ }
1328
+ }
1329
+ }
1330
+ else if (easings) {
1331
+ fail('easings are only valid for cubic-bezier tracks.', `${path}.easings`);
1332
+ }
1333
+ const spatialTangents = track.spatialTangents === undefined
1334
+ ? undefined
1335
+ : floatArray(track.spatialTangents, `${path}.spatialTangents`, copy);
1336
+ if (spatialTangents) {
1337
+ const expected = Math.max(0, times.length - 1) * 4;
1338
+ if (property !== 'position' || interpolation === 'step' || spatialTangents.length !== expected) {
1339
+ fail(`spatialTangents require position, non-step and ${expected} values.`, `${path}.spatialTangents`);
1340
+ }
1341
+ }
1342
+ return Object.freeze({
1343
+ node, property, interpolation, times, values, valueSize,
1344
+ ...(easings ? { easings } : {}),
1345
+ ...(spatialTangents ? { spatialTangents } : {}),
1346
+ });
1347
+ }
1348
+ /** @internal Compact-binary structural decoder entry point. */
1349
+ function parseBinaryResourceValue(value, index, ids) {
1350
+ const path = `$.resources[${index}]`;
1351
+ const resource = record(value, path);
1352
+ const id = nonEmptyString(resource.id, `${path}.id`);
1353
+ if (ids.has(id))
1354
+ fail(`Duplicate resource id "${id}".`, `${path}.id`);
1355
+ ids.add(id);
1356
+ const type = literal(resource.type, ['image', 'audio', 'binary'], `${path}.type`);
1357
+ return Object.freeze({
1358
+ id,
1359
+ type,
1360
+ uri: nonEmptyString(resource.uri, `${path}.uri`),
1361
+ ...(resource.mimeType !== undefined ? { mimeType: nonEmptyString(resource.mimeType, `${path}.mimeType`) } : {}),
1362
+ ...(resource.integrity !== undefined ? { integrity: nonEmptyString(resource.integrity, `${path}.integrity`) } : {}),
1363
+ ...(type === 'image' && resource.width !== undefined ? { width: positiveNumber(resource.width, `${path}.width`) } : {}),
1364
+ ...(type === 'image' && resource.height !== undefined ? { height: positiveNumber(resource.height, `${path}.height`) } : {}),
1365
+ ...(type === 'image' && resource.colorSpace !== undefined
1366
+ ? { colorSpace: literal(resource.colorSpace, ['srgb', 'linear'], `${path}.colorSpace`) }
1367
+ : {}),
1368
+ });
1369
+ }
1370
+ function validateHierarchy(nodes, ids) {
1371
+ const indexById = new Map(nodes.map((node, index) => [node.id, index]));
1372
+ const states = new Uint8Array(nodes.length);
1373
+ for (let index = 0; index < nodes.length; index++) {
1374
+ const node = nodes[index];
1375
+ if (node.parent && !ids.has(node.parent))
1376
+ fail(`Node references missing parent "${node.parent}".`, `$.nodes[${index}].parent`);
1377
+ if (states[index] !== 0)
1378
+ continue;
1379
+ let cursor = index;
1380
+ while (cursor !== undefined && states[cursor] === 0) {
1381
+ states[cursor] = 1;
1382
+ const parentId = nodes[cursor].parent;
1383
+ cursor = parentId === undefined ? undefined : indexById.get(parentId);
1384
+ }
1385
+ if (cursor !== undefined && states[cursor] === 1) {
1386
+ fail('Node hierarchy contains a cycle.', `$.nodes[${index}].parent`);
1387
+ }
1388
+ cursor = index;
1389
+ while (cursor !== undefined && states[cursor] === 1) {
1390
+ states[cursor] = 2;
1391
+ const parentId = nodes[cursor].parent;
1392
+ cursor = parentId === undefined ? undefined : indexById.get(parentId);
1393
+ }
1394
+ }
1395
+ }
1396
+ function validateComposites(nodes, ids) {
1397
+ const indexById = new Map(nodes.map((node, index) => [node.id, index]));
1398
+ for (let index = 0; index < nodes.length; index++) {
1399
+ const node = nodes[index];
1400
+ const layers = compositeLayers(node.composite);
1401
+ for (let layerIndex = 0; layerIndex < layers.length; layerIndex++) {
1402
+ const source = layers[layerIndex].source;
1403
+ const sourcePath = compositeSourcePath(index, node.composite, layerIndex);
1404
+ if (!ids.has(source))
1405
+ fail(`Composite references missing source node "${source}".`, sourcePath);
1406
+ if (source === node.id)
1407
+ fail('Composite source cannot reference its own node.', sourcePath);
1408
+ }
1409
+ }
1410
+ const states = new Uint8Array(nodes.length);
1411
+ const visit = (index) => {
1412
+ if (states[index] === 2)
1413
+ return;
1414
+ if (states[index] === 1)
1415
+ fail('Composite graph contains a cycle.', `$.nodes[${index}].composite`);
1416
+ states[index] = 1;
1417
+ for (const layer of compositeLayers(nodes[index].composite))
1418
+ visit(indexById.get(layer.source));
1419
+ states[index] = 2;
1420
+ };
1421
+ for (let index = 0; index < nodes.length; index++)
1422
+ visit(index);
1423
+ }
1424
+ function compositeLayers(composite) {
1425
+ if (!composite)
1426
+ return [];
1427
+ return 'layers' in composite ? composite.layers : [composite];
1428
+ }
1429
+ function compositeSourcePath(index, composite, layerIndex) {
1430
+ return 'layers' in composite
1431
+ ? `$.nodes[${index}].composite.layers[${layerIndex}].source`
1432
+ : `$.nodes[${index}].composite.source`;
1433
+ }
1434
+ function extensionContext(extension, path) {
1435
+ return {
1436
+ extension,
1437
+ path,
1438
+ fail(message, overridePath = path) { return fail(message, overridePath); },
1439
+ };
1440
+ }
1441
+ function trackValueSize(property) {
1442
+ return property === 'position' || property === 'scale' ? 2 : 1;
1443
+ }
1444
+ function floatArray(value, path, copy) {
1445
+ if (value instanceof Float32Array) {
1446
+ for (let i = 0; i < value.length; i++)
1447
+ requiredFloat(value, i, path);
1448
+ return copy ? new Float32Array(value) : value;
1449
+ }
1450
+ const values = array(value, path);
1451
+ const result = new Float32Array(values.length);
1452
+ for (let i = 0; i < values.length; i++)
1453
+ result[i] = finiteNumber$1(values[i], `${path}[${i}]`);
1454
+ return result;
1455
+ }
1456
+ function pathValueCount(commands) {
1457
+ let count = 0;
1458
+ for (const command of commands)
1459
+ count += command === 'M' || command === 'L' ? 2 : command === 'Q' ? 4 : command === 'C' ? 6 : 0;
1460
+ return count;
1461
+ }
1462
+ function validatePathTopology(commands, path, requireClosed = true) {
1463
+ let open = false;
1464
+ let pointCount = 0;
1465
+ for (let index = 0; index < commands.length; index++) {
1466
+ const command = commands[index];
1467
+ if (command === 'M') {
1468
+ if (open && requireClosed)
1469
+ fail('Each filled subpath must be closed with Z before the next M.', `${path}[${index}]`);
1470
+ open = true;
1471
+ pointCount = 1;
1472
+ }
1473
+ else if (command === 'Z') {
1474
+ if (!open || pointCount < (requireClosed ? 3 : 2))
1475
+ fail(`Each ${requireClosed ? 'filled ' : ''}subpath must contain at least ${requireClosed ? 'three' : 'two'} points before Z.`, `${path}[${index}]`);
1476
+ open = false;
1477
+ pointCount = 0;
1478
+ }
1479
+ else {
1480
+ if (!open)
1481
+ fail('L, Q and C commands must follow M inside a subpath.', `${path}[${index}]`);
1482
+ pointCount++;
1483
+ }
1484
+ }
1485
+ if (open && requireClosed)
1486
+ fail('Each filled subpath must end with Z.', path);
1487
+ }
1488
+ function stringList(value, path) {
1489
+ const values = array(value, path);
1490
+ const result = [];
1491
+ const seen = new Set();
1492
+ for (let i = 0; i < values.length; i++) {
1493
+ const item = nonEmptyString(values[i], `${path}[${i}]`);
1494
+ if (seen.has(item))
1495
+ fail(`Duplicate value "${item}".`, `${path}[${i}]`);
1496
+ seen.add(item);
1497
+ result.push(item);
1498
+ }
1499
+ return result;
1500
+ }
1501
+ function record(value, path) {
1502
+ if (!value || typeof value !== 'object' || Array.isArray(value) || ArrayBuffer.isView(value))
1503
+ fail('Expected an object.', path);
1504
+ return value;
1505
+ }
1506
+ function array(value, path) {
1507
+ if (!Array.isArray(value))
1508
+ fail('Expected an array.', path);
1509
+ return value;
1510
+ }
1511
+ function vec2(value, path) {
1512
+ const values = array(value, path);
1513
+ if (values.length !== 2)
1514
+ fail('Expected exactly two numbers.', path);
1515
+ return Object.freeze([finiteNumber$1(values[0], `${path}[0]`), finiteNumber$1(values[1], `${path}[1]`)]);
1516
+ }
1517
+ function positiveVec2(value, path) {
1518
+ const values = vec2(value, path);
1519
+ if (values[0] <= 0 || values[1] <= 0)
1520
+ fail('Expected two positive numbers.', path);
1521
+ return values;
1522
+ }
1523
+ function nonNegativeVec2(value, path) {
1524
+ const values = vec2(value, path);
1525
+ if (values[0] < 0 || values[1] < 0)
1526
+ fail('Expected two non-negative numbers.', path);
1527
+ return values;
1528
+ }
1529
+ function numericRange(value, path, minimum = -Infinity) {
1530
+ const values = vec2(value, path);
1531
+ if (values[0] < minimum || values[1] < values[0])
1532
+ fail(`Expected an ascending numeric range above ${minimum}.`, path);
1533
+ return values;
1534
+ }
1535
+ function color(value, path) {
1536
+ const values = array(value, path);
1537
+ if (values.length !== 4)
1538
+ fail('Expected RGBA with four numbers.', path);
1539
+ return Object.freeze([
1540
+ unitNumber(values[0], `${path}[0]`), unitNumber(values[1], `${path}[1]`),
1541
+ unitNumber(values[2], `${path}[2]`), unitNumber(values[3], `${path}[3]`),
1542
+ ]);
1543
+ }
1544
+ function unitVec3(value, path) {
1545
+ const values = array(value, path);
1546
+ if (values.length !== 3)
1547
+ fail('Expected RGB with three numbers.', path);
1548
+ return Object.freeze([
1549
+ unitNumber(values[0], `${path}[0]`),
1550
+ unitNumber(values[1], `${path}[1]`),
1551
+ unitNumber(values[2], `${path}[2]`),
1552
+ ]);
1553
+ }
1554
+ function uvRect(value, path) {
1555
+ const values = array(value, path);
1556
+ if (values.length !== 4)
1557
+ fail('Expected normalized UV rectangle with four numbers.', path);
1558
+ const x = unitNumber(values[0], `${path}[0]`);
1559
+ const y = unitNumber(values[1], `${path}[1]`);
1560
+ const width = positiveNumber(values[2], `${path}[2]`);
1561
+ const height = positiveNumber(values[3], `${path}[3]`);
1562
+ if (x + width > 1 + 1e-6 || y + height > 1 + 1e-6)
1563
+ fail('UV rectangle must fit inside [0, 1].', path);
1564
+ return Object.freeze([x, y, width, height]);
1565
+ }
1566
+ function validateUvRectTrack(track, path) {
1567
+ for (let frame = 0; frame < track.times.length; frame++) {
1568
+ const offset = frame * 4;
1569
+ uvRect([
1570
+ track.values[offset],
1571
+ track.values[offset + 1],
1572
+ track.values[offset + 2],
1573
+ track.values[offset + 3],
1574
+ ], `${path}.values[${offset}..${offset + 3}]`);
1575
+ }
1576
+ }
1577
+ function finiteNumber$1(value, path) {
1578
+ if (typeof value !== 'number' || !Number.isFinite(value))
1579
+ fail('Expected a finite number.', path);
1580
+ return value;
1581
+ }
1582
+ function positiveNumber(value, path) {
1583
+ const result = finiteNumber$1(value, path);
1584
+ if (result <= 0)
1585
+ fail('Expected a positive number.', path);
1586
+ return result;
1587
+ }
1588
+ function nonNegativeNumber(value, path) {
1589
+ const result = finiteNumber$1(value, path);
1590
+ if (result < 0)
1591
+ fail('Expected a non-negative number.', path);
1592
+ return result;
1593
+ }
1594
+ function unitNumber(value, path) {
1595
+ const result = finiteNumber$1(value, path);
1596
+ if (result < 0 || result > 1)
1597
+ fail('Expected a number in [0, 1].', path);
1598
+ return result;
1599
+ }
1600
+ function nonEmptyString(value, path) {
1601
+ if (typeof value !== 'string' || !value.trim())
1602
+ fail('Expected a non-empty string.', path);
1603
+ return value;
1604
+ }
1605
+ function fontWeight(value, path) {
1606
+ if (typeof value === 'string' && value.trim())
1607
+ return value;
1608
+ if (typeof value === 'number' && Number.isFinite(value) && value >= 1 && value <= 1000)
1609
+ return value;
1610
+ fail('Expected a non-empty font weight string or a number in [1, 1000].', path);
1611
+ }
1612
+ function booleanValue(value, path) {
1613
+ if (typeof value !== 'boolean')
1614
+ fail('Expected a boolean.', path);
1615
+ return value;
1616
+ }
1617
+ function safeInteger(value, path) {
1618
+ if (typeof value !== 'number' || !Number.isSafeInteger(value))
1619
+ fail('Expected a safe integer.', path);
1620
+ return value;
1621
+ }
1622
+ function boundedInteger(value, minimum, maximum, path) {
1623
+ const result = safeInteger(value, path);
1624
+ if (result < minimum || result > maximum)
1625
+ fail(`Expected an integer in [${minimum}, ${maximum}].`, path);
1626
+ return result;
1627
+ }
1628
+ function literal(value, values, path) {
1629
+ if (typeof value !== 'string' || !values.includes(value))
1630
+ fail(`Expected one of: ${values.join(', ')}.`, path);
1631
+ return value;
1632
+ }
1633
+ function requiredFloat(values, index, path) {
1634
+ const value = values[index];
1635
+ if (value === undefined || !Number.isFinite(value))
1636
+ fail('Expected finite Float32 values.', `${path}[${index}]`);
1637
+ return value;
1638
+ }
1639
+ function positiveLimit(value, fallback, name) {
1640
+ if (value === undefined)
1641
+ return fallback;
1642
+ if (!Number.isSafeInteger(value) || value < 1)
1643
+ fail(`${name} must be a positive safe integer.`, '$options');
1644
+ return value;
1645
+ }
1646
+ function limit(actual, maximum, label, path) {
1647
+ if (actual > maximum)
1648
+ throw new AnimationFormatError('E_ANIMATION_LIMIT_EXCEEDED', `${label} count ${actual} exceeds limit ${maximum}.`, path);
1649
+ }
1650
+ function fail(message, path) {
1651
+ throw new AnimationFormatError('E_ANIMATION_INVALID_FORMAT', message, path);
1652
+ }
1653
+
1654
+ const HEADER_BYTES = 24;
1655
+ const MAGIC = 0x31415948;
1656
+ const CONTAINER_MAJOR = 2;
1657
+ const CONTAINER_MINOR = 0;
1658
+ const LEGACY_CONTAINER_MAJOR = 1;
1659
+ const DEFAULT_PARSE_OPTIONS$1 = Object.freeze({});
1660
+ const UTF8_DECODER$1 = new TextDecoder();
1661
+ const UTF8_ENCODER$1 = new TextEncoder();
1662
+ const TRACK_PROPERTIES = ['position', 'rotation', 'scale', 'opacity'];
1663
+ const INTERPOLATIONS = ['step', 'linear', 'cubic-bezier'];
1664
+ const END_BEHAVIORS = ['loop', 'hold', 'destroy'];
1665
+ const COMPOSITE_KINDS = ['mask', 'matte'];
1666
+ const COMPOSITE_MODES = ['alpha', 'alpha-inverted', 'luma', 'luma-inverted'];
1667
+ const COMPOSITE_OPERATIONS = ['add', 'subtract', 'intersect', 'difference'];
1668
+ const VECTOR_STROKE_EXTENSION = 'org.haiyue.vector-stroke@1';
1669
+ const VECTOR_PATH_MORPH_EXTENSION = 'org.haiyue.vector-path-morph@1';
1670
+ const VECTOR_STROKE_KEYS = new Set([
1671
+ 'type', 'commands', 'values', 'sourceComponent', 'color', 'width',
1672
+ 'lineCap', 'lineJoin', 'miterLimit', 'tolerance',
1673
+ ]);
1674
+ const VECTOR_PATH_MORPH_KEYS = new Set([
1675
+ 'type', 'commands', 'times', 'values', 'valueSize', 'interpolation',
1676
+ 'easings', 'fill', 'fillRule', 'tolerance',
1677
+ ]);
1678
+ class BinaryFloatPoolBuilder {
1679
+ blocks = [];
1680
+ _deduplicated = new Map();
1681
+ count = 0;
1682
+ add(values, deduplicate = false) {
1683
+ const floats = values instanceof Float32Array ? values : new Float32Array(values);
1684
+ if (deduplicate) {
1685
+ const key = floatBlockKey(floats);
1686
+ const existing = this._deduplicated.get(key);
1687
+ if (existing)
1688
+ return existing;
1689
+ const range = this._append(floats);
1690
+ this._deduplicated.set(key, range);
1691
+ return range;
1692
+ }
1693
+ return this._append(floats);
1694
+ }
1695
+ _append(values) {
1696
+ const result = [this.count, values.length];
1697
+ this.count += values.length;
1698
+ this.blocks.push({ range: result, values });
1699
+ return result;
1700
+ }
1701
+ }
1702
+ class BinaryStringTableBuilder {
1703
+ values = [];
1704
+ _indices = new Map();
1705
+ add(value) {
1706
+ if (value === undefined)
1707
+ return -1;
1708
+ const existing = this._indices.get(value);
1709
+ if (existing !== undefined)
1710
+ return existing;
1711
+ const index = this.values.length;
1712
+ this.values.push(value);
1713
+ this._indices.set(value, index);
1714
+ return index;
1715
+ }
1716
+ }
1717
+ function isAnimationBinary(buffer) {
1718
+ return buffer.byteLength >= 4 && new DataView(buffer).getUint32(0, true) === MAGIC;
1719
+ }
1720
+ /** Encodes compact indexed metadata plus one contiguous zero-copy Float32 track/path pool. */
1721
+ function encodeAnimationBinary(document, options = DEFAULT_PARSE_OPTIONS$1) {
1722
+ const parsed = isParsedAnimation(document)
1723
+ ? document
1724
+ : parseAnimationValue(document, options, 'json');
1725
+ const strings = new BinaryStringTableBuilder();
1726
+ const floats = new BinaryFloatPoolBuilder();
1727
+ const nodeIndices = new Map(parsed.nodes.map((node, index) => [node.id, index]));
1728
+ const resources = parsed.resources.map(resource => encodeResource(resource, strings));
1729
+ const nodes = parsed.nodes.map(node => [
1730
+ strings.add(node.id),
1731
+ strings.add(node.name),
1732
+ node.parent === undefined ? -1 : requiredMapIndex(nodeIndices, node.parent, 'node parent'),
1733
+ node.start ?? -1,
1734
+ node.duration ?? -1,
1735
+ node.transform ? encodeTransform(node.transform) : 0,
1736
+ node.composite ? encodeComposite(node.composite, nodeIndices, floats) : 0,
1737
+ node.components ? node.components.map(component => encodeComponent(component, floats, strings)) : 0,
1738
+ node.extensions ?? 0,
1739
+ node.effects ? encodeLayerEffects(node.effects, floats) : 0,
1740
+ ]);
1741
+ const tracks = parsed.tracks.map(track => [
1742
+ requiredMapIndex(nodeIndices, track.node, 'track node'),
1743
+ TRACK_PROPERTIES.indexOf(track.property),
1744
+ INTERPOLATIONS.indexOf(track.interpolation),
1745
+ floats.add(track.times, true),
1746
+ floats.add(track.values),
1747
+ track.easings ? floats.add(track.easings, true) : 0,
1748
+ track.spatialTangents ? floats.add(track.spatialTangents) : 0,
1749
+ ]);
1750
+ const metadata = [
1751
+ strings.add(parsed.name),
1752
+ parsed.canvas.width,
1753
+ parsed.canvas.height,
1754
+ parsed.duration,
1755
+ parsed.frameRate ?? 0,
1756
+ END_BEHAVIORS.indexOf(parsed.endBehavior),
1757
+ strings.values,
1758
+ resources,
1759
+ nodes,
1760
+ tracks,
1761
+ parsed.extensionsUsed.map(value => strings.add(value)),
1762
+ parsed.extensionsRequired.map(value => strings.add(value)),
1763
+ Object.keys(parsed.extensions).length === 0 ? 0 : parsed.extensions,
1764
+ ];
1765
+ return writeBinary(JSON.stringify(metadata), floats, options);
1766
+ }
1767
+ function decodeAnimationBinary(buffer, options = DEFAULT_PARSE_OPTIONS$1) {
1768
+ if (buffer.byteLength < 4)
1769
+ invalidBinary('Header is truncated.');
1770
+ const header = new DataView(buffer);
1771
+ if (header.getUint32(0, true) !== MAGIC)
1772
+ invalidBinary('Magic must be HYA1.');
1773
+ return decodeAnimationBinaryHeader(buffer, header, options);
1774
+ }
1775
+ /** @internal Parser entry point that checks and consumes the magic with one DataView. */
1776
+ function tryDecodeAnimationBinary(buffer, options) {
1777
+ if (buffer.byteLength < 4)
1778
+ return undefined;
1779
+ const header = new DataView(buffer);
1780
+ if (header.getUint32(0, true) !== MAGIC)
1781
+ return undefined;
1782
+ return decodeAnimationBinaryHeader(buffer, header, options);
1783
+ }
1784
+ function decodeAnimationBinaryHeader(buffer, header, options) {
1785
+ const limits = resolveAnimationParseLimits(options);
1786
+ if (buffer.byteLength > limits.maxInputBytes) {
1787
+ throw new AnimationFormatError('E_ANIMATION_LIMIT_EXCEEDED', `Binary input exceeds ${limits.maxInputBytes} bytes.`, '$binary');
1788
+ }
1789
+ if (buffer.byteLength < HEADER_BYTES)
1790
+ invalidBinary('Header is truncated.');
1791
+ const major = header.getUint16(4, true);
1792
+ const minor = header.getUint16(6, true);
1793
+ if (major !== LEGACY_CONTAINER_MAJOR && major !== CONTAINER_MAJOR) {
1794
+ invalidBinary(`Unsupported container version ${major}.${minor}.`);
1795
+ }
1796
+ if (minor !== 0)
1797
+ invalidBinary(`Unsupported container version ${major}.${minor}.`);
1798
+ const metadataOffset = header.getUint32(8, true);
1799
+ const metadataLength = header.getUint32(12, true);
1800
+ const floatOffset = header.getUint32(16, true);
1801
+ const floatCount = header.getUint32(20, true);
1802
+ if (metadataLength > limits.maxMetadataBytes) {
1803
+ throw new AnimationFormatError('E_ANIMATION_LIMIT_EXCEEDED', `Binary metadata exceeds ${limits.maxMetadataBytes} bytes.`, '$binary.metadata');
1804
+ }
1805
+ if (metadataOffset < HEADER_BYTES || metadataOffset + metadataLength > buffer.byteLength)
1806
+ invalidBinary('Metadata range is outside the buffer.');
1807
+ if ((floatOffset & 3) !== 0 || floatOffset < metadataOffset + metadataLength || floatOffset + floatCount * 4 > buffer.byteLength) {
1808
+ invalidBinary('Float pool range is invalid or unaligned.');
1809
+ }
1810
+ let metadata;
1811
+ try {
1812
+ metadata = JSON.parse(UTF8_DECODER$1.decode(new Uint8Array(buffer, metadataOffset, metadataLength)));
1813
+ }
1814
+ catch (error) {
1815
+ invalidBinary(`Metadata JSON cannot be decoded: ${error instanceof Error ? error.message : String(error)}.`);
1816
+ }
1817
+ const floatPool = new Float32Array(buffer, floatOffset, floatCount);
1818
+ return major === LEGACY_CONTAINER_MAJOR
1819
+ ? decodeLegacyMetadata(metadata, floatPool, buffer, options)
1820
+ : decodeCompactMetadata(metadata, floatPool, buffer, options, limits);
1821
+ }
1822
+ function writeBinary(metadata, floatPool, options) {
1823
+ const metadataBytes = UTF8_ENCODER$1.encode(metadata);
1824
+ const metadataOffset = HEADER_BYTES;
1825
+ const floatOffset = align4(metadataOffset + metadataBytes.byteLength);
1826
+ const totalBytes = floatOffset + floatPool.count * 4;
1827
+ const limits = resolveAnimationParseLimits(options);
1828
+ if (metadataBytes.byteLength > limits.maxMetadataBytes) {
1829
+ throw new AnimationFormatError('E_ANIMATION_LIMIT_EXCEEDED', `Binary metadata exceeds ${limits.maxMetadataBytes} bytes.`, '$binary.metadata');
1830
+ }
1831
+ if (totalBytes > limits.maxInputBytes) {
1832
+ throw new AnimationFormatError('E_ANIMATION_LIMIT_EXCEEDED', `Binary output exceeds ${limits.maxInputBytes} bytes.`, '$binary');
1833
+ }
1834
+ const buffer = new ArrayBuffer(totalBytes);
1835
+ const header = new DataView(buffer);
1836
+ header.setUint32(0, MAGIC, true);
1837
+ header.setUint16(4, CONTAINER_MAJOR, true);
1838
+ header.setUint16(6, CONTAINER_MINOR, true);
1839
+ header.setUint32(8, metadataOffset, true);
1840
+ header.setUint32(12, metadataBytes.byteLength, true);
1841
+ header.setUint32(16, floatOffset, true);
1842
+ header.setUint32(20, floatPool.count, true);
1843
+ new Uint8Array(buffer, metadataOffset, metadataBytes.byteLength).set(metadataBytes);
1844
+ const output = new Float32Array(buffer, floatOffset, floatPool.count);
1845
+ for (const block of floatPool.blocks)
1846
+ output.set(block.values, block.range[0]);
1847
+ return buffer;
1848
+ }
1849
+ function encodeResource(resource, strings) {
1850
+ return [
1851
+ resource.type === 'image' ? 0 : resource.type === 'audio' ? 1 : 2,
1852
+ strings.add(resource.id),
1853
+ strings.add(resource.uri),
1854
+ resource.type === 'image' ? resource.width ?? 0 : 0,
1855
+ resource.type === 'image' ? resource.height ?? 0 : 0,
1856
+ strings.add(resource.mimeType),
1857
+ strings.add(resource.integrity),
1858
+ resource.type === 'image' ? resource.colorSpace === undefined ? -1 : resource.colorSpace === 'srgb' ? 0 : 1 : -1,
1859
+ ];
1860
+ }
1861
+ function encodeTransform(transform) {
1862
+ return [
1863
+ transform.position ?? 0,
1864
+ transform.rotation ?? null,
1865
+ transform.scale ?? 0,
1866
+ transform.anchor ?? 0,
1867
+ transform.opacity ?? -1,
1868
+ ];
1869
+ }
1870
+ function encodeComposite(composite, nodeIndices, floats) {
1871
+ const layers = 'layers' in composite ? composite.layers : [composite];
1872
+ // Keep the original three-field encoding for the common legacy-compatible case.
1873
+ if (layers.length === 1 && layers[0].operation === undefined
1874
+ && layers[0].feather === undefined && layers[0].expansion === undefined
1875
+ && layers[0].expansionTrack === undefined
1876
+ && (layers[0].mode === 'alpha' || layers[0].mode === 'alpha-inverted')) {
1877
+ const layer = layers[0];
1878
+ return [
1879
+ COMPOSITE_KINDS.indexOf(layer.kind),
1880
+ requiredMapIndex(nodeIndices, layer.source, 'composite source'),
1881
+ COMPOSITE_MODES.indexOf(layer.mode),
1882
+ ];
1883
+ }
1884
+ return layers.map(layer => [
1885
+ COMPOSITE_KINDS.indexOf(layer.kind),
1886
+ requiredMapIndex(nodeIndices, layer.source, 'composite source'),
1887
+ COMPOSITE_MODES.indexOf(layer.mode),
1888
+ COMPOSITE_OPERATIONS.indexOf(layer.operation ?? 'add'),
1889
+ layer.feather ?? 0,
1890
+ layer.expansion ?? 0,
1891
+ encodeOptionalVectorTrack(layer.expansionTrack, floats),
1892
+ ]);
1893
+ }
1894
+ function encodeComponent(component, floats, strings) {
1895
+ if (component.type === 'shape2d') {
1896
+ return [
1897
+ 0,
1898
+ component.shape === 'rect' ? 0 : 1,
1899
+ component.size,
1900
+ component.position ?? 0,
1901
+ component.fill,
1902
+ ];
1903
+ }
1904
+ if (isPath2DComponent(component)) {
1905
+ return [
1906
+ 1,
1907
+ strings.add(component.commands),
1908
+ floats.add(component.values, true),
1909
+ component.fill,
1910
+ component.fillRule === 'evenodd' ? 1 : 0,
1911
+ component.tolerance ?? -1,
1912
+ ];
1913
+ }
1914
+ if (isCompactVectorStrokeComponent(component)) {
1915
+ return [
1916
+ 3,
1917
+ strings.add(component.commands),
1918
+ component.values === undefined ? 0 : floats.add(component.values, true),
1919
+ component.sourceComponent ?? -1,
1920
+ component.color,
1921
+ component.width,
1922
+ component.lineCap === 'butt' ? 0 : component.lineCap === 'round' ? 1 : 2,
1923
+ component.lineJoin === 'miter' ? 0 : component.lineJoin === 'round' ? 1 : 2,
1924
+ component.miterLimit,
1925
+ component.tolerance ?? -1,
1926
+ ];
1927
+ }
1928
+ if (isCompactVectorPathMorphComponent(component)) {
1929
+ return [
1930
+ 4,
1931
+ strings.add(component.commands),
1932
+ floats.add(component.times),
1933
+ floats.add(component.values, true),
1934
+ component.valueSize,
1935
+ component.interpolation === 'step' ? 0 : component.interpolation === 'linear' ? 1 : 2,
1936
+ component.easings === undefined ? 0 : floats.add(component.easings),
1937
+ component.fill,
1938
+ component.fillRule === 'evenodd' ? 1 : 0,
1939
+ component.tolerance ?? -1,
1940
+ ];
1941
+ }
1942
+ if (isAnimationVectorShapeComponent(component)) {
1943
+ return [
1944
+ 5,
1945
+ strings.add(component.commands),
1946
+ floats.add(component.values, true),
1947
+ encodeOptionalVectorTrack(component.morph, floats, true),
1948
+ component.fill ? encodeVectorFill(component.fill, floats) : 0,
1949
+ component.stroke ? encodeVectorStroke(component.stroke, floats) : 0,
1950
+ component.fillRule === 'evenodd' ? 1 : 0,
1951
+ component.tolerance ?? -1,
1952
+ component.modifiers ? component.modifiers.map(modifier => encodeVectorModifier(modifier, floats)) : 0,
1953
+ component.morphRelative === true ? 1 : 0,
1954
+ ];
1955
+ }
1956
+ if (component.type === 'sprite2d')
1957
+ return encodeSpriteComponent(component, floats, strings);
1958
+ if (component.type === 'text2d')
1959
+ return encodeTextComponent(component, floats, strings);
1960
+ return [2, component];
1961
+ }
1962
+ function encodeSpriteComponent(component, floats, strings) {
1963
+ return [
1964
+ 7,
1965
+ strings.add(component.resource),
1966
+ component.size,
1967
+ component.position ?? 0,
1968
+ component.tint ?? 0,
1969
+ component.uvRect ?? 0,
1970
+ encodeOptionalVectorTrack(component.uvRectTrack, floats),
1971
+ ];
1972
+ }
1973
+ function encodeTextComponent(component, floats, strings) {
1974
+ return [
1975
+ 6,
1976
+ strings.add(component.text), component.size, component.position ?? 0,
1977
+ strings.add(component.fontFamily), component.fontSize ?? 0,
1978
+ encodeFontWeight(component.fontWeight, strings),
1979
+ component.fontStyle === undefined ? -1 : component.fontStyle === 'normal' ? 0 : 1,
1980
+ strings.add(component.fontResource), component.lineHeight ?? 0, component.tracking ?? null,
1981
+ component.textAlign === undefined ? -1 : ['left', 'center', 'right'].indexOf(component.textAlign),
1982
+ component.verticalAlign === undefined ? -1 : ['top', 'middle', 'bottom'].indexOf(component.verticalAlign),
1983
+ component.color, component.backgroundColor ?? 0, component.padding ?? -1,
1984
+ component.resolutionScale ?? 0,
1985
+ component.documents?.map(document => [
1986
+ document.time, strings.add(document.text), strings.add(document.fontFamily), document.fontSize ?? 0,
1987
+ encodeFontWeight(document.fontWeight, strings),
1988
+ document.fontStyle === undefined ? -1 : document.fontStyle === 'normal' ? 0 : 1,
1989
+ strings.add(document.fontResource), document.lineHeight ?? 0, document.tracking ?? null,
1990
+ document.textAlign === undefined ? -1 : ['left', 'center', 'right'].indexOf(document.textAlign),
1991
+ document.color ?? 0,
1992
+ ]) ?? 0,
1993
+ component.animators?.map(animator => encodeTextAnimator(animator, floats)) ?? 0,
1994
+ ];
1995
+ }
1996
+ function encodeFontWeight(value, strings) {
1997
+ if (value === undefined)
1998
+ return null;
1999
+ return typeof value === 'number' ? value : [-1, strings.add(value)];
2000
+ }
2001
+ function encodeTextAnimator(animator, floats) {
2002
+ const selector = animator.selector;
2003
+ return [[
2004
+ selector.start, selector.end, selector.offset ?? 0,
2005
+ selector.units === 'index' ? 1 : 0, selector.amount ?? 1,
2006
+ TEXT_SELECTOR_SHAPES.indexOf(selector.shape ?? 'square'),
2007
+ encodeOptionalVectorTrack(selector.startTrack, floats),
2008
+ encodeOptionalVectorTrack(selector.endTrack, floats),
2009
+ encodeOptionalVectorTrack(selector.offsetTrack, floats),
2010
+ encodeOptionalVectorTrack(selector.amountTrack, floats),
2011
+ selector.basedOn === undefined ? -1 : TEXT_SELECTOR_BASES.indexOf(selector.basedOn),
2012
+ selector.easing ?? 0,
2013
+ selector.smoothness ?? -1,
2014
+ selector.randomSeed ?? null,
2015
+ ],
2016
+ animator.position ?? 0, animator.scale ?? 0, animator.rotation ?? null,
2017
+ animator.opacity ?? -1, animator.fillColor ?? 0, animator.tracking ?? null,
2018
+ encodeOptionalVectorTrack(animator.positionTrack, floats),
2019
+ encodeOptionalVectorTrack(animator.scaleTrack, floats),
2020
+ encodeOptionalVectorTrack(animator.rotationTrack, floats),
2021
+ encodeOptionalVectorTrack(animator.opacityTrack, floats),
2022
+ encodeOptionalVectorTrack(animator.fillColorTrack, floats),
2023
+ encodeOptionalVectorTrack(animator.trackingTrack, floats)];
2024
+ }
2025
+ function encodeLayerEffects(effects, floats) {
2026
+ return effects.map(effect => {
2027
+ if (effect.kind === 'tint')
2028
+ return [
2029
+ 0, effect.black, effect.white, effect.amount,
2030
+ encodeOptionalVectorTrack(effect.blackTrack, floats),
2031
+ encodeOptionalVectorTrack(effect.whiteTrack, floats),
2032
+ encodeOptionalVectorTrack(effect.amountTrack, floats),
2033
+ ];
2034
+ if (effect.kind === 'fill')
2035
+ return [
2036
+ 1, effect.color, effect.opacity ?? 1,
2037
+ encodeOptionalVectorTrack(effect.colorTrack, floats),
2038
+ encodeOptionalVectorTrack(effect.opacityTrack, floats),
2039
+ ];
2040
+ if (effect.kind === 'opacity')
2041
+ return [2, effect.opacity, encodeOptionalVectorTrack(effect.opacityTrack, floats)];
2042
+ if (effect.kind === 'color-matrix')
2043
+ return [
2044
+ 3, floats.add(effect.matrix), encodeOptionalVectorTrack(effect.matrixTrack, floats),
2045
+ ];
2046
+ if (effect.kind === 'blur')
2047
+ return [4, effect.radius, encodeOptionalVectorTrack(effect.radiusTrack, floats)];
2048
+ return [
2049
+ 5, effect.color, effect.opacity, effect.offset, effect.blur,
2050
+ encodeOptionalVectorTrack(effect.colorTrack, floats),
2051
+ encodeOptionalVectorTrack(effect.opacityTrack, floats),
2052
+ encodeOptionalVectorTrack(effect.offsetTrack, floats),
2053
+ encodeOptionalVectorTrack(effect.blurTrack, floats),
2054
+ ];
2055
+ });
2056
+ }
2057
+ function encodeVectorModifier(modifier, floats) {
2058
+ if (modifier.kind === 'round-corners')
2059
+ return [
2060
+ 1, modifier.radius, encodeOptionalVectorTrack(modifier.radiusTrack, floats),
2061
+ ];
2062
+ return [
2063
+ 0, modifier.start, modifier.end, modifier.offset, modifier.mode === 'individual' ? 1 : 0,
2064
+ encodeOptionalVectorTrack(modifier.startTrack, floats),
2065
+ encodeOptionalVectorTrack(modifier.endTrack, floats),
2066
+ encodeOptionalVectorTrack(modifier.offsetTrack, floats),
2067
+ ];
2068
+ }
2069
+ function isAnimationVectorShapeComponent(component) {
2070
+ return component.type === ANIMATION_VECTOR_SHAPE_EXTENSION_ID
2071
+ && typeof component.commands === 'string'
2072
+ && (Array.isArray(component.values)
2073
+ || component.values instanceof Float32Array);
2074
+ }
2075
+ function encodeVectorTrack(track, floats, deduplicateValues = false) {
2076
+ return [
2077
+ floats.add(track.times, true),
2078
+ floats.add(track.values, deduplicateValues),
2079
+ track.valueSize,
2080
+ INTERPOLATIONS.indexOf(track.interpolation),
2081
+ track.easings ? floats.add(track.easings, true) : 0,
2082
+ ];
2083
+ }
2084
+ function encodeOptionalVectorTrack(track, floats, deduplicateValues = false) {
2085
+ return track ? encodeVectorTrack(track, floats, deduplicateValues) : 0;
2086
+ }
2087
+ function encodeVectorFill(fill, floats) {
2088
+ if (fill.kind === 'solid')
2089
+ return [
2090
+ 0,
2091
+ fill.color,
2092
+ encodeOptionalVectorTrack(fill.colorTrack, floats),
2093
+ encodeOptionalVectorTrack(fill.opacityTrack, floats),
2094
+ fill.opacity ?? 1,
2095
+ ];
2096
+ return [
2097
+ fill.kind === 'linear-gradient' ? 1 : 2,
2098
+ fill.start,
2099
+ fill.end,
2100
+ floats.add(fill.stops),
2101
+ encodeOptionalVectorTrack(fill.startTrack, floats),
2102
+ encodeOptionalVectorTrack(fill.endTrack, floats),
2103
+ encodeOptionalVectorTrack(fill.stopsTrack, floats),
2104
+ encodeOptionalVectorTrack(fill.opacityTrack, floats),
2105
+ fill.opacity ?? 1,
2106
+ ];
2107
+ }
2108
+ function encodeVectorStroke(stroke, floats) {
2109
+ return [
2110
+ stroke.color,
2111
+ stroke.width,
2112
+ ['butt', 'round', 'square'].indexOf(stroke.lineCap),
2113
+ ['miter', 'round', 'bevel'].indexOf(stroke.lineJoin),
2114
+ stroke.miterLimit,
2115
+ stroke.dash ? floats.add(stroke.dash) : 0,
2116
+ stroke.dashOffset ?? 0,
2117
+ encodeOptionalVectorTrack(stroke.colorTrack, floats),
2118
+ encodeOptionalVectorTrack(stroke.opacityTrack, floats),
2119
+ encodeOptionalVectorTrack(stroke.widthTrack, floats),
2120
+ encodeOptionalVectorTrack(stroke.dashOffsetTrack, floats),
2121
+ stroke.gradient ? encodeVectorFill(stroke.gradient, floats) : 0,
2122
+ stroke.opacity ?? 1,
2123
+ ];
2124
+ }
2125
+ function decodeCompactMetadata(value, floatPool, buffer, options, limits) {
2126
+ const root = compactArray(value, '$binary.metadata', 13);
2127
+ const strings = compactArray(root[6], '$binary.metadata[6]').map((item, index) => (requiredString(item, `$binary.metadata[6][${index}]`)));
2128
+ const encodedResources = compactArray(root[7], '$binary.metadata[7]');
2129
+ binaryLimit(encodedResources.length, limits.maxResources, 'resources', '$binary.metadata[7]');
2130
+ const resourceIds = new Set();
2131
+ const resources = encodedResources.map((item, index) => parseBinaryResourceValue(decodeResource(item, strings, `$binary.metadata[7][${index}]`), index, resourceIds));
2132
+ const encodedNodeValues = compactArray(root[8], '$binary.metadata[8]');
2133
+ const encodedNodes = encodedNodeValues.map((item, index) => (compactArray(item, `$binary.metadata[8][${index}]`, 9)));
2134
+ binaryLimit(encodedNodes.length, limits.maxNodes, 'nodes', '$binary.metadata[8]');
2135
+ const nodeIds = encodedNodes.map((node, index) => requiredNonEmptyString(indexedString(strings, node[0], `$binary.metadata[8][${index}][0]`), `$binary.metadata[8][${index}][0]`));
2136
+ const parsedNodeIds = new Set();
2137
+ for (let index = 0; index < nodeIds.length; index++) {
2138
+ const id = nodeIds[index];
2139
+ if (parsedNodeIds.has(id))
2140
+ invalidBinary(`Duplicate node id "${id}" at $binary.metadata[8][${index}][0].`);
2141
+ parsedNodeIds.add(id);
2142
+ }
2143
+ const parentIndices = validateCompactNodeGraph(encodedNodes, nodeIds.length);
2144
+ let componentCount = 0;
2145
+ let pathValueCount = 0;
2146
+ let textCharacterCount = 0;
2147
+ let particleCapacity = 0;
2148
+ const nodes = encodedNodes.map((item, index) => {
2149
+ const node = decodeNode(item, index, strings, nodeIds, parentIndices[index], floatPool, options, (kind, count) => {
2150
+ if (kind === 'path') {
2151
+ pathValueCount += count;
2152
+ binaryLimit(pathValueCount, limits.maxPathValues, 'path values', `$.nodes[${index}].components`);
2153
+ }
2154
+ else if (kind === 'text') {
2155
+ textCharacterCount += count;
2156
+ binaryLimit(textCharacterCount, limits.maxTextCharacters, 'text characters', `$.nodes[${index}].components`);
2157
+ }
2158
+ else {
2159
+ particleCapacity += count;
2160
+ binaryLimit(particleCapacity, limits.maxParticleCapacity, 'particle capacity', `$.nodes[${index}].components`);
2161
+ }
2162
+ });
2163
+ componentCount += node.components?.length ?? 0;
2164
+ binaryLimit(componentCount, limits.maxComponents, 'components', `$.nodes[${index}].components`);
2165
+ return node;
2166
+ });
2167
+ const encodedTracks = compactArray(root[9], '$binary.metadata[9]');
2168
+ binaryLimit(encodedTracks.length, limits.maxTracks, 'tracks', '$binary.metadata[9]');
2169
+ const duration = positiveFiniteNumber(root[3], '$binary.metadata[3]');
2170
+ let keyframeCount = 0;
2171
+ const tracks = encodedTracks.map((item, index) => {
2172
+ const path = `$binary.metadata[9][${index}]`;
2173
+ const track = compactArray(item, path, 6);
2174
+ const nodeIndex = boundedIndex(track[0], nodeIds.length, `${path}[0]`);
2175
+ const parsed = parseBinaryTrackValue({
2176
+ node: nodeIds[nodeIndex],
2177
+ property: indexedLiteral(TRACK_PROPERTIES, track[1], `${path}[1]`),
2178
+ interpolation: indexedLiteral(INTERPOLATIONS, track[2], `${path}[2]`),
2179
+ times: compactFloatView(floatPool, track[3], `${path}[3]`),
2180
+ values: compactFloatView(floatPool, track[4], `${path}[4]`),
2181
+ ...(track[5] === 0 ? {} : { easings: compactFloatView(floatPool, track[5], `${path}[5]`) }),
2182
+ ...(track.length < 7 || track[6] === 0 ? {} : {
2183
+ spatialTangents: compactFloatView(floatPool, track[6], `${path}[6]`),
2184
+ }),
2185
+ }, index, parsedNodeIds, duration, options.copyFloatData === true);
2186
+ keyframeCount += parsed.times.length;
2187
+ binaryLimit(keyframeCount, limits.maxKeyframes, 'keyframes', `$.tracks[${index}].times`);
2188
+ return parsed;
2189
+ });
2190
+ const frameRate = finiteNumber(root[4], '$binary.metadata[4]');
2191
+ if (frameRate < 0)
2192
+ invalidBinary('Frame rate must be positive or zero when omitted.');
2193
+ const extensions = root[12] === 0 ? {} : binaryRecord(root[12], '$binary.metadata[12]');
2194
+ return finalizeParsedAnimation({
2195
+ ...(root[0] === -1 ? {} : { name: indexedString(strings, root[0], '$binary.metadata[0]') }),
2196
+ canvas: Object.freeze({
2197
+ width: positiveFiniteNumber(root[1], '$binary.metadata[1]'),
2198
+ height: positiveFiniteNumber(root[2], '$binary.metadata[2]'),
2199
+ coordinateSystem: 'screen-y-down',
2200
+ }),
2201
+ duration,
2202
+ ...(frameRate === 0 ? {} : { frameRate }),
2203
+ endBehavior: indexedLiteral(END_BEHAVIORS, root[5], '$binary.metadata[5]'),
2204
+ resources,
2205
+ nodes,
2206
+ tracks,
2207
+ extensionsUsed: decodeStringIndices(root[10], strings, '$binary.metadata[10]'),
2208
+ extensionsRequired: decodeStringIndices(root[11], strings, '$binary.metadata[11]'),
2209
+ extensions,
2210
+ }, options, 'binary', buffer, true);
2211
+ }
2212
+ function validateCompactNodeGraph(encodedNodes, nodeCount) {
2213
+ const compositeSources = Array.from({ length: nodeCount }, () => []);
2214
+ const parents = encodedNodes.map((node, index) => {
2215
+ const parent = optionalBoundedIndex(node[2], nodeCount, `$binary.metadata[8][${index}][2]`);
2216
+ if (node[6] !== 0) {
2217
+ const composite = compactArray(node[6], `$binary.metadata[8][${index}][6]`);
2218
+ const layers = typeof composite[0] === 'number' ? [composite] : composite.map((value, layerIndex) => (compactArray(value, `$binary.metadata[8][${index}][6][${layerIndex}]`, 3)));
2219
+ if (layers.length < 1 || layers.length > 8)
2220
+ invalidBinary(`Composite stack must contain between 1 and 8 layers at $binary.metadata[8][${index}][6].`);
2221
+ for (let layerIndex = 0; layerIndex < layers.length; layerIndex++) {
2222
+ const source = boundedIndex(layers[layerIndex][1], nodeCount, `$binary.metadata[8][${index}][6][${layerIndex}][1]`);
2223
+ if (source === index)
2224
+ invalidBinary(`Composite source cannot reference its own node at $binary.metadata[8][${index}][6][${layerIndex}][1].`);
2225
+ compositeSources[index].push(source);
2226
+ }
2227
+ }
2228
+ return parent;
2229
+ });
2230
+ const states = new Uint8Array(nodeCount);
2231
+ for (let index = 0; index < nodeCount; index++) {
2232
+ if (states[index] !== 0)
2233
+ continue;
2234
+ let cursor = index;
2235
+ while (cursor !== undefined && states[cursor] === 0) {
2236
+ states[cursor] = 1;
2237
+ cursor = parents[cursor];
2238
+ }
2239
+ if (cursor !== undefined && states[cursor] === 1) {
2240
+ invalidBinary(`Node hierarchy contains a cycle at $binary.metadata[8][${index}][2].`);
2241
+ }
2242
+ cursor = index;
2243
+ while (cursor !== undefined && states[cursor] === 1) {
2244
+ states[cursor] = 2;
2245
+ cursor = parents[cursor];
2246
+ }
2247
+ }
2248
+ states.fill(0);
2249
+ const visitComposite = (index) => {
2250
+ if (states[index] === 2)
2251
+ return;
2252
+ if (states[index] === 1)
2253
+ invalidBinary(`Composite graph contains a cycle at $binary.metadata[8][${index}][6].`);
2254
+ states[index] = 1;
2255
+ for (const source of compositeSources[index])
2256
+ visitComposite(source);
2257
+ states[index] = 2;
2258
+ };
2259
+ for (let index = 0; index < nodeCount; index++)
2260
+ visitComposite(index);
2261
+ return parents;
2262
+ }
2263
+ function decodeResource(value, strings, path) {
2264
+ const resource = compactArray(value, path, 8);
2265
+ const type = indexedLiteral(['image', 'audio', 'binary'], resource[0], `${path}[0]`);
2266
+ const id = indexedString(strings, resource[1], `${path}[1]`);
2267
+ const uri = indexedString(strings, resource[2], `${path}[2]`);
2268
+ const mimeType = optionalIndexedString(strings, resource[5], `${path}[5]`);
2269
+ const integrity = optionalIndexedString(strings, resource[6], `${path}[6]`);
2270
+ if (type === 'image') {
2271
+ const colorCode = finiteInteger(resource[7], `${path}[7]`);
2272
+ if (colorCode < -1 || colorCode > 1)
2273
+ invalidBinary(`Invalid image color-space code at ${path}[7].`);
2274
+ return {
2275
+ id, type, uri,
2276
+ ...(resource[3] === 0 ? {} : { width: resource[3] }),
2277
+ ...(resource[4] === 0 ? {} : { height: resource[4] }),
2278
+ ...(mimeType === undefined ? {} : { mimeType }),
2279
+ ...(integrity === undefined ? {} : { integrity }),
2280
+ ...(colorCode === -1 ? {} : { colorSpace: colorCode === 0 ? 'srgb' : 'linear' }),
2281
+ };
2282
+ }
2283
+ return {
2284
+ id, type, uri,
2285
+ ...(mimeType === undefined ? {} : { mimeType }),
2286
+ ...(integrity === undefined ? {} : { integrity }),
2287
+ };
2288
+ }
2289
+ function decodeNode(node, index, strings, nodeIds, parentIndex, floatPool, options, countBudget) {
2290
+ const path = `$binary.metadata[8][${index}]`;
2291
+ const name = optionalIndexedString(strings, node[1], `${path}[1]`);
2292
+ const start = node[3] === -1 ? undefined : nonNegativeFiniteNumber(node[3], `${path}[3]`);
2293
+ const duration = node[4] === -1 ? undefined : positiveFiniteNumber(node[4], `${path}[4]`);
2294
+ const composite = node[6] === 0 ? undefined : decodeComposite(node[6], nodeIds, floatPool, `${path}[6]`);
2295
+ const components = node[7] === 0 ? undefined : compactArray(node[7], `${path}[7]`).map((component, componentIndex) => (decodeComponent(component, strings, floatPool, `${path}[7][${componentIndex}]`, `$.nodes[${index}].components[${componentIndex}]`, options, countBudget)));
2296
+ const effects = node.length < 10 || node[9] === 0 ? undefined : parseBinaryEffectsValue(decodeLayerEffects(node[9], floatPool, `${path}[9]`), `$.nodes[${index}].effects`, options.copyFloatData === true);
2297
+ return Object.freeze({
2298
+ id: nodeIds[index],
2299
+ ...(name === undefined ? {} : { name }),
2300
+ ...(parentIndex === undefined ? {} : { parent: nodeIds[parentIndex] }),
2301
+ ...(start === undefined || start === 0 ? {} : { start }),
2302
+ ...(duration === undefined ? {} : { duration }),
2303
+ ...(node[5] === 0 ? {} : { transform: parseBinaryTransformValue(decodeTransform(node[5], `${path}[5]`), `$.nodes[${index}].transform`) }),
2304
+ ...(composite === undefined ? {} : { composite }),
2305
+ ...(effects === undefined ? {} : { effects }),
2306
+ ...(components === undefined ? {} : { components: Object.freeze(components) }),
2307
+ ...(node[8] === 0 ? {} : { extensions: Object.freeze({ ...binaryRecord(node[8], `${path}[8]`) }) }),
2308
+ });
2309
+ }
2310
+ function decodeTransform(value, path) {
2311
+ const transform = compactArray(value, path, 5);
2312
+ return {
2313
+ ...(transform[0] === 0 ? {} : { position: transform[0] }),
2314
+ ...(transform[1] === null ? {} : { rotation: transform[1] }),
2315
+ ...(transform[2] === 0 ? {} : { scale: transform[2] }),
2316
+ ...(transform[3] === 0 ? {} : { anchor: transform[3] }),
2317
+ ...(transform[4] === -1 ? {} : { opacity: transform[4] }),
2318
+ };
2319
+ }
2320
+ function decodeComponent(value, strings, floatPool, path, validationPath, options, countBudget) {
2321
+ const component = compactArray(value, path, 2);
2322
+ const code = finiteInteger(component[0], `${path}[0]`);
2323
+ if (code === 0) {
2324
+ if (component.length < 5)
2325
+ invalidBinary(`Compact shape component is truncated at ${path}.`);
2326
+ return Object.freeze({
2327
+ type: 'shape2d',
2328
+ shape: indexedLiteral(['rect', 'ellipse'], component[1], `${path}[1]`),
2329
+ size: positiveFiniteTuple(component[2], 2, `${path}[2]`),
2330
+ ...(component[3] === 0 ? {} : { position: finiteTuple(component[3], 2, `${path}[3]`) }),
2331
+ fill: unitFiniteTuple(component[4], 4, `${path}[4]`),
2332
+ });
2333
+ }
2334
+ if (code === 1) {
2335
+ if (component.length < 6)
2336
+ invalidBinary(`Compact path component is truncated at ${path}.`);
2337
+ return parseBinaryComponentValue({
2338
+ type: 'path2d',
2339
+ commands: indexedString(strings, component[1], `${path}[1]`),
2340
+ values: compactFloatView(floatPool, component[2], `${path}[2]`),
2341
+ fill: component[3],
2342
+ fillRule: indexedLiteral(['nonzero', 'evenodd'], component[4], `${path}[4]`),
2343
+ ...(component[5] === -1 ? {} : { tolerance: component[5] }),
2344
+ }, validationPath, options, countBudget);
2345
+ }
2346
+ if (code === 2) {
2347
+ return parseBinaryComponentValue(binaryRecord(component[1], `${path}[1]`), validationPath, options, countBudget);
2348
+ }
2349
+ if (code === 3) {
2350
+ if (component.length < 10)
2351
+ invalidBinary(`Compact Lottie stroke component is truncated at ${path}.`);
2352
+ const commands = optionalIndexedString(strings, component[1], `${path}[1]`);
2353
+ const sourceComponent = finiteInteger(component[3], `${path}[3]`);
2354
+ return parseBinaryComponentValue({
2355
+ type: VECTOR_STROKE_EXTENSION,
2356
+ ...(commands === undefined ? {} : { commands }),
2357
+ // The versioned Lottie stroke extension currently defines runtime values as an ordinary
2358
+ // number array; keep the on-disk Float32 packing without changing that extension contract.
2359
+ ...(component[2] === 0 ? {} : { values: Array.from(compactFloatView(floatPool, component[2], `${path}[2]`)) }),
2360
+ ...(sourceComponent === -1 ? {} : { sourceComponent }),
2361
+ color: component[4],
2362
+ width: component[5],
2363
+ lineCap: indexedLiteral(['butt', 'round', 'square'], component[6], `${path}[6]`),
2364
+ lineJoin: indexedLiteral(['miter', 'round', 'bevel'], component[7], `${path}[7]`),
2365
+ miterLimit: component[8],
2366
+ ...(component[9] === -1 ? {} : { tolerance: component[9] }),
2367
+ }, validationPath, options, countBudget);
2368
+ }
2369
+ if (code === 4) {
2370
+ if (component.length < 10)
2371
+ invalidBinary(`Compact Lottie path morph component is truncated at ${path}.`);
2372
+ return parseBinaryComponentValue({
2373
+ type: VECTOR_PATH_MORPH_EXTENSION,
2374
+ commands: indexedString(strings, component[1], `${path}[1]`),
2375
+ times: Array.from(compactFloatView(floatPool, component[2], `${path}[2]`)),
2376
+ values: Array.from(compactFloatView(floatPool, component[3], `${path}[3]`)),
2377
+ valueSize: finiteInteger(component[4], `${path}[4]`),
2378
+ interpolation: indexedLiteral(INTERPOLATIONS, component[5], `${path}[5]`),
2379
+ ...(component[6] === 0 ? {} : { easings: Array.from(compactFloatView(floatPool, component[6], `${path}[6]`)) }),
2380
+ fill: component[7],
2381
+ fillRule: indexedLiteral(['nonzero', 'evenodd'], component[8], `${path}[8]`),
2382
+ ...(component[9] === -1 ? {} : { tolerance: component[9] }),
2383
+ }, validationPath, options, countBudget);
2384
+ }
2385
+ if (code === 5) {
2386
+ if (component.length < 8)
2387
+ invalidBinary(`Compact vector shape component is truncated at ${path}.`);
2388
+ return parseBinaryComponentValue({
2389
+ type: ANIMATION_VECTOR_SHAPE_EXTENSION_ID,
2390
+ commands: indexedString(strings, component[1], `${path}[1]`),
2391
+ values: compactFloatView(floatPool, component[2], `${path}[2]`),
2392
+ ...decodeVectorTrackField(component, 3, 'morph', floatPool, path),
2393
+ ...(component[4] === 0 ? {} : { fill: decodeVectorFill(component[4], floatPool, `${path}[4]`) }),
2394
+ ...(component[5] === 0 ? {} : { stroke: decodeVectorStroke(component[5], floatPool, `${path}[5]`) }),
2395
+ fillRule: indexedLiteral(['nonzero', 'evenodd'], component[6], `${path}[6]`),
2396
+ ...(component[7] === -1 ? {} : { tolerance: component[7] }),
2397
+ ...(component.length < 9 || component[8] === 0 ? {} : {
2398
+ modifiers: compactArray(component[8], `${path}[8]`).map((modifier, index) => (decodeVectorModifier(modifier, floatPool, `${path}[8][${index}]`))),
2399
+ }),
2400
+ ...(component.length < 10 || component[9] !== 1 ? {} : { morphRelative: true }),
2401
+ }, validationPath, options, countBudget);
2402
+ }
2403
+ if (code === 6) {
2404
+ if (component.length < 19)
2405
+ invalidBinary(`Compact text component is truncated at ${path}.`);
2406
+ return parseBinaryComponentValue({
2407
+ type: 'text2d',
2408
+ text: indexedString(strings, component[1], `${path}[1]`),
2409
+ size: component[2],
2410
+ ...(component[3] === 0 ? {} : { position: component[3] }),
2411
+ ...decodeOptionalStringField(component[4], 'fontFamily', strings, `${path}[4]`),
2412
+ ...(component[5] === 0 ? {} : { fontSize: component[5] }),
2413
+ ...decodeFontWeightField(component[6], strings, `${path}[6]`),
2414
+ ...(component[7] === -1 ? {} : { fontStyle: indexedLiteral(['normal', 'italic'], component[7], `${path}[7]`) }),
2415
+ ...decodeOptionalStringField(component[8], 'fontResource', strings, `${path}[8]`),
2416
+ ...(component[9] === 0 ? {} : { lineHeight: component[9] }),
2417
+ ...(component[10] === null ? {} : { tracking: component[10] }),
2418
+ ...(component[11] === -1 ? {} : { textAlign: indexedLiteral(['left', 'center', 'right'], component[11], `${path}[11]`) }),
2419
+ ...(component[12] === -1 ? {} : { verticalAlign: indexedLiteral(['top', 'middle', 'bottom'], component[12], `${path}[12]`) }),
2420
+ color: component[13],
2421
+ ...(component[14] === 0 ? {} : { backgroundColor: component[14] }),
2422
+ ...(component[15] === -1 ? {} : { padding: component[15] }),
2423
+ ...(component[16] === 0 ? {} : { resolutionScale: component[16] }),
2424
+ ...(component[17] === 0 ? {} : {
2425
+ documents: compactArray(component[17], `${path}[17]`).map((document, index) => (decodeTextDocument(document, strings, `${path}[17][${index}]`))),
2426
+ }),
2427
+ ...(component[18] === 0 ? {} : {
2428
+ animators: compactArray(component[18], `${path}[18]`).map((animator, index) => (decodeTextAnimator(animator, floatPool, `${path}[18][${index}]`))),
2429
+ }),
2430
+ }, validationPath, options, countBudget);
2431
+ }
2432
+ if (code === 7) {
2433
+ if (component.length < 7)
2434
+ invalidBinary(`Compact sprite component is truncated at ${path}.`);
2435
+ return parseBinaryComponentValue({
2436
+ type: 'sprite2d',
2437
+ resource: indexedString(strings, component[1], `${path}[1]`),
2438
+ size: component[2],
2439
+ ...(component[3] === 0 ? {} : { position: component[3] }),
2440
+ ...(component[4] === 0 ? {} : { tint: component[4] }),
2441
+ ...(component[5] === 0 ? {} : { uvRect: component[5] }),
2442
+ ...decodeVectorTrackField(component, 6, 'uvRectTrack', floatPool, path),
2443
+ }, validationPath, options, countBudget);
2444
+ }
2445
+ invalidBinary(`Unknown compact component code ${code} at ${path}[0].`);
2446
+ }
2447
+ function decodeOptionalStringField(value, key, strings, path) {
2448
+ const decoded = optionalIndexedString(strings, value, path);
2449
+ return decoded === undefined ? {} : { [key]: decoded };
2450
+ }
2451
+ function decodeFontWeightField(value, strings, path) {
2452
+ if (value === null)
2453
+ return {};
2454
+ if (typeof value === 'number')
2455
+ return { fontWeight: value };
2456
+ const encoded = compactArray(value, path, 2);
2457
+ if (encoded[0] !== -1)
2458
+ invalidBinary(`Invalid compact font weight tag at ${path}[0].`);
2459
+ return { fontWeight: indexedString(strings, encoded[1], `${path}[1]`) };
2460
+ }
2461
+ function decodeTextDocument(value, strings, path) {
2462
+ const document = compactArray(value, path, 11);
2463
+ return {
2464
+ time: document[0], text: indexedString(strings, document[1], `${path}[1]`),
2465
+ ...decodeOptionalStringField(document[2], 'fontFamily', strings, `${path}[2]`),
2466
+ ...(document[3] === 0 ? {} : { fontSize: document[3] }),
2467
+ ...decodeFontWeightField(document[4], strings, `${path}[4]`),
2468
+ ...(document[5] === -1 ? {} : { fontStyle: indexedLiteral(['normal', 'italic'], document[5], `${path}[5]`) }),
2469
+ ...decodeOptionalStringField(document[6], 'fontResource', strings, `${path}[6]`),
2470
+ ...(document[7] === 0 ? {} : { lineHeight: document[7] }),
2471
+ ...(document[8] === null ? {} : { tracking: document[8] }),
2472
+ ...(document[9] === -1 ? {} : { textAlign: indexedLiteral(['left', 'center', 'right'], document[9], `${path}[9]`) }),
2473
+ ...(document[10] === 0 ? {} : { color: document[10] }),
2474
+ };
2475
+ }
2476
+ function decodeTextAnimator(value, floatPool, path) {
2477
+ const animator = compactArray(value, path, 13);
2478
+ const selector = compactArray(animator[0], `${path}[0]`, 10);
2479
+ return {
2480
+ selector: {
2481
+ start: selector[0], end: selector[1], offset: selector[2],
2482
+ units: indexedLiteral(['percent', 'index'], selector[3], `${path}[0][3]`),
2483
+ amount: selector[4],
2484
+ shape: indexedLiteral(TEXT_SELECTOR_SHAPES, selector[5], `${path}[0][5]`),
2485
+ ...decodeVectorTrackField(selector, 6, 'startTrack', floatPool, `${path}[0]`),
2486
+ ...decodeVectorTrackField(selector, 7, 'endTrack', floatPool, `${path}[0]`),
2487
+ ...decodeVectorTrackField(selector, 8, 'offsetTrack', floatPool, `${path}[0]`),
2488
+ ...decodeVectorTrackField(selector, 9, 'amountTrack', floatPool, `${path}[0]`),
2489
+ basedOn: selector.length < 11 || selector[10] === -1
2490
+ ? undefined
2491
+ : indexedLiteral(TEXT_SELECTOR_BASES, selector[10], `${path}[0][10]`),
2492
+ easing: selector[11] === 0 ? undefined : selector[11],
2493
+ smoothness: selector[12] === -1 ? undefined : selector[12],
2494
+ randomSeed: selector[13] === null ? undefined : selector[13],
2495
+ },
2496
+ ...(animator[1] === 0 ? {} : { position: animator[1] }),
2497
+ ...(animator[2] === 0 ? {} : { scale: animator[2] }),
2498
+ ...(animator[3] === null ? {} : { rotation: animator[3] }),
2499
+ ...(animator[4] === -1 ? {} : { opacity: animator[4] }),
2500
+ ...(animator[5] === 0 ? {} : { fillColor: animator[5] }),
2501
+ ...(animator[6] === null ? {} : { tracking: animator[6] }),
2502
+ ...decodeVectorTrackField(animator, 7, 'positionTrack', floatPool, path),
2503
+ ...decodeVectorTrackField(animator, 8, 'scaleTrack', floatPool, path),
2504
+ ...decodeVectorTrackField(animator, 9, 'rotationTrack', floatPool, path),
2505
+ ...decodeVectorTrackField(animator, 10, 'opacityTrack', floatPool, path),
2506
+ ...decodeVectorTrackField(animator, 11, 'fillColorTrack', floatPool, path),
2507
+ ...decodeVectorTrackField(animator, 12, 'trackingTrack', floatPool, path),
2508
+ };
2509
+ }
2510
+ function decodeLayerEffects(value, floatPool, path) {
2511
+ return compactArray(value, path).map((value, index) => {
2512
+ const effectPath = `${path}[${index}]`;
2513
+ const effect = compactArray(value, effectPath, 2);
2514
+ const kind = indexedLiteral(['tint', 'fill', 'opacity', 'color-matrix', 'blur', 'drop-shadow'], effect[0], `${effectPath}[0]`);
2515
+ if (kind === 'tint') {
2516
+ if (effect.length < 7)
2517
+ invalidBinary(`Compact tint effect is truncated at ${effectPath}.`);
2518
+ return {
2519
+ kind, black: effect[1], white: effect[2], amount: effect[3],
2520
+ ...decodeVectorTrackField(effect, 4, 'blackTrack', floatPool, effectPath),
2521
+ ...decodeVectorTrackField(effect, 5, 'whiteTrack', floatPool, effectPath),
2522
+ ...decodeVectorTrackField(effect, 6, 'amountTrack', floatPool, effectPath),
2523
+ };
2524
+ }
2525
+ if (kind === 'fill') {
2526
+ if (effect.length < 5)
2527
+ invalidBinary(`Compact fill effect is truncated at ${effectPath}.`);
2528
+ return {
2529
+ kind, color: effect[1], opacity: effect[2],
2530
+ ...decodeVectorTrackField(effect, 3, 'colorTrack', floatPool, effectPath),
2531
+ ...decodeVectorTrackField(effect, 4, 'opacityTrack', floatPool, effectPath),
2532
+ };
2533
+ }
2534
+ if (kind === 'opacity')
2535
+ return {
2536
+ kind, opacity: effect[1], ...decodeVectorTrackField(effect, 2, 'opacityTrack', floatPool, effectPath),
2537
+ };
2538
+ if (kind === 'color-matrix')
2539
+ return {
2540
+ kind,
2541
+ matrix: compactFloatView(floatPool, effect[1], `${effectPath}[1]`),
2542
+ ...decodeVectorTrackField(effect, 2, 'matrixTrack', floatPool, effectPath),
2543
+ };
2544
+ if (kind === 'blur')
2545
+ return {
2546
+ kind, radius: effect[1], ...decodeVectorTrackField(effect, 2, 'radiusTrack', floatPool, effectPath),
2547
+ };
2548
+ if (effect.length < 9)
2549
+ invalidBinary(`Compact drop-shadow effect is truncated at ${effectPath}.`);
2550
+ return {
2551
+ kind, color: effect[1], opacity: effect[2], offset: effect[3], blur: effect[4],
2552
+ ...decodeVectorTrackField(effect, 5, 'colorTrack', floatPool, effectPath),
2553
+ ...decodeVectorTrackField(effect, 6, 'opacityTrack', floatPool, effectPath),
2554
+ ...decodeVectorTrackField(effect, 7, 'offsetTrack', floatPool, effectPath),
2555
+ ...decodeVectorTrackField(effect, 8, 'blurTrack', floatPool, effectPath),
2556
+ };
2557
+ });
2558
+ }
2559
+ function decodeVectorModifier(value, floatPool, path) {
2560
+ const modifier = compactArray(value, path, 3);
2561
+ const kind = indexedLiteral(['trim-path', 'round-corners'], modifier[0], `${path}[0]`);
2562
+ if (kind === 'round-corners')
2563
+ return {
2564
+ kind,
2565
+ radius: modifier[1],
2566
+ ...decodeVectorTrackField(modifier, 2, 'radiusTrack', floatPool, path),
2567
+ };
2568
+ if (modifier.length < 8)
2569
+ invalidBinary(`Truncated trim-path at ${path}.`);
2570
+ return {
2571
+ kind,
2572
+ start: modifier[1], end: modifier[2], offset: modifier[3],
2573
+ mode: indexedLiteral(['simultaneous', 'individual'], modifier[4], `${path}[4]`),
2574
+ ...decodeVectorTrackField(modifier, 5, 'startTrack', floatPool, path),
2575
+ ...decodeVectorTrackField(modifier, 6, 'endTrack', floatPool, path),
2576
+ ...decodeVectorTrackField(modifier, 7, 'offsetTrack', floatPool, path),
2577
+ };
2578
+ }
2579
+ function decodeVectorTrackField(owner, index, key, floatPool, path) {
2580
+ return owner[index] === 0 ? {} : { [key]: decodeVectorTrack(owner[index], floatPool, `${path}[${index}]`) };
2581
+ }
2582
+ function decodeVectorTrack(value, floatPool, path) {
2583
+ const track = compactArray(value, path, 5);
2584
+ return {
2585
+ times: compactFloatView(floatPool, track[0], `${path}[0]`),
2586
+ values: compactFloatView(floatPool, track[1], `${path}[1]`),
2587
+ valueSize: track[2],
2588
+ interpolation: indexedLiteral(INTERPOLATIONS, track[3], `${path}[3]`),
2589
+ ...(track[4] === 0 ? {} : { easings: compactFloatView(floatPool, track[4], `${path}[4]`) }),
2590
+ };
2591
+ }
2592
+ function decodeVectorFill(value, floatPool, path) {
2593
+ const fill = compactArray(value, path, 4);
2594
+ const kind = indexedLiteral(['solid', 'linear-gradient', 'radial-gradient'], fill[0], `${path}[0]`);
2595
+ if (kind === 'solid')
2596
+ return {
2597
+ kind,
2598
+ color: fill[1],
2599
+ ...decodeVectorTrackField(fill, 2, 'colorTrack', floatPool, path),
2600
+ ...decodeVectorTrackField(fill, 3, 'opacityTrack', floatPool, path),
2601
+ ...(fill.length < 5 || fill[4] === 1 ? {} : { opacity: fill[4] }),
2602
+ };
2603
+ if (fill.length < 8)
2604
+ invalidBinary(`Compact vector gradient is truncated at ${path}.`);
2605
+ return {
2606
+ kind,
2607
+ start: fill[1],
2608
+ end: fill[2],
2609
+ stops: compactFloatView(floatPool, fill[3], `${path}[3]`),
2610
+ ...decodeVectorTrackField(fill, 4, 'startTrack', floatPool, path),
2611
+ ...decodeVectorTrackField(fill, 5, 'endTrack', floatPool, path),
2612
+ ...decodeVectorTrackField(fill, 6, 'stopsTrack', floatPool, path),
2613
+ ...decodeVectorTrackField(fill, 7, 'opacityTrack', floatPool, path),
2614
+ ...(fill.length < 9 || fill[8] === 1 ? {} : { opacity: fill[8] }),
2615
+ };
2616
+ }
2617
+ function decodeVectorStroke(value, floatPool, path) {
2618
+ const stroke = compactArray(value, path, 11);
2619
+ return {
2620
+ color: stroke[0],
2621
+ width: stroke[1],
2622
+ lineCap: indexedLiteral(['butt', 'round', 'square'], stroke[2], `${path}[2]`),
2623
+ lineJoin: indexedLiteral(['miter', 'round', 'bevel'], stroke[3], `${path}[3]`),
2624
+ miterLimit: stroke[4],
2625
+ ...(stroke[5] === 0 ? {} : { dash: compactFloatView(floatPool, stroke[5], `${path}[5]`) }),
2626
+ ...(stroke[6] === 0 ? {} : { dashOffset: stroke[6] }),
2627
+ ...decodeVectorTrackField(stroke, 7, 'colorTrack', floatPool, path),
2628
+ ...decodeVectorTrackField(stroke, 8, 'opacityTrack', floatPool, path),
2629
+ ...decodeVectorTrackField(stroke, 9, 'widthTrack', floatPool, path),
2630
+ ...decodeVectorTrackField(stroke, 10, 'dashOffsetTrack', floatPool, path),
2631
+ ...(stroke.length < 12 || stroke[11] === 0 ? {} : { gradient: decodeVectorFill(stroke[11], floatPool, `${path}[11]`) }),
2632
+ ...(stroke.length < 13 || stroke[12] === 1 ? {} : { opacity: stroke[12] }),
2633
+ };
2634
+ }
2635
+ function decodeComposite(value, nodeIds, floatPool, path) {
2636
+ const composite = compactArray(value, path);
2637
+ if (typeof composite[0] === 'number')
2638
+ return decodeCompositeLayer(composite, nodeIds, floatPool, path);
2639
+ if (composite.length < 1 || composite.length > 8)
2640
+ invalidBinary(`Composite stack must contain between 1 and 8 layers at ${path}.`);
2641
+ return Object.freeze({
2642
+ layers: Object.freeze(composite.map((layer, index) => decodeCompositeLayer(compactArray(layer, `${path}[${index}]`, 3), nodeIds, floatPool, `${path}[${index}]`))),
2643
+ });
2644
+ }
2645
+ function decodeCompositeLayer(composite, nodeIds, floatPool, path) {
2646
+ const source = boundedIndex(composite[1], nodeIds.length, `${path}[1]`);
2647
+ return Object.freeze({
2648
+ kind: indexedLiteral(COMPOSITE_KINDS, composite[0], `${path}[0]`),
2649
+ source: nodeIds[source],
2650
+ mode: indexedLiteral(COMPOSITE_MODES, composite[2], `${path}[2]`),
2651
+ ...(composite.length < 4 ? {} : { operation: indexedLiteral(COMPOSITE_OPERATIONS, composite[3], `${path}[3]`) }),
2652
+ ...(composite.length < 5 || composite[4] === 0 ? {} : {
2653
+ feather: nonNegativeFiniteTuple(composite[4], 2, `${path}[4]`),
2654
+ }),
2655
+ ...(composite.length < 6 || composite[5] === 0 ? {} : { expansion: finiteNumber(composite[5], `${path}[5]`) }),
2656
+ ...(composite.length < 7 ? {} : decodeVectorTrackField(composite, 6, 'expansionTrack', floatPool, path)),
2657
+ });
2658
+ }
2659
+ function decodeLegacyMetadata(metadata, floatPool, buffer, options) {
2660
+ const root = binaryRecord(metadata, '$binary.metadata');
2661
+ const tracks = binaryArray(root.tracks, '$binary.metadata.tracks');
2662
+ const nodes = binaryArray(root.nodes, '$binary.metadata.nodes').map((value, nodeIndex) => {
2663
+ const node = binaryRecord(value, `$.nodes[${nodeIndex}]`);
2664
+ if (node.components === undefined)
2665
+ return node;
2666
+ const components = binaryArray(node.components, `$.nodes[${nodeIndex}].components`).map((componentValue, componentIndex) => {
2667
+ const component = binaryRecord(componentValue, `$.nodes[${nodeIndex}].components[${componentIndex}]`);
2668
+ if (component.type !== 'path2d')
2669
+ return component;
2670
+ return {
2671
+ ...component,
2672
+ values: legacyFloatView(floatPool, component.values, `$.nodes[${nodeIndex}].components[${componentIndex}].values`),
2673
+ };
2674
+ });
2675
+ return { ...node, components };
2676
+ });
2677
+ const hydratedTracks = tracks.map((value, index) => {
2678
+ const track = binaryRecord(value, `$.tracks[${index}]`);
2679
+ return {
2680
+ node: track.node,
2681
+ property: track.property,
2682
+ interpolation: track.interpolation,
2683
+ times: legacyFloatView(floatPool, track.times, `$.tracks[${index}].times`),
2684
+ values: legacyFloatView(floatPool, track.values, `$.tracks[${index}].values`),
2685
+ ...(track.easings === undefined ? {} : { easings: legacyFloatView(floatPool, track.easings, `$.tracks[${index}].easings`) }),
2686
+ };
2687
+ });
2688
+ return parseAnimationValue({ ...root, nodes, tracks: hydratedTracks }, options, 'binary', buffer);
2689
+ }
2690
+ function compactFloatView(pool, value, path) {
2691
+ const descriptor = compactArray(value, path, 2);
2692
+ const offset = safeUint(descriptor[0], `${path}[0]`);
2693
+ const length = safeUint(descriptor[1], `${path}[1]`);
2694
+ if (offset + length > pool.length)
2695
+ invalidBinary(`Float range is outside the pool at ${path}.`);
2696
+ return pool.subarray(offset, offset + length);
2697
+ }
2698
+ function legacyFloatView(pool, value, path) {
2699
+ const descriptor = binaryRecord(value, path);
2700
+ const offset = safeUint(descriptor.offset, `${path}.offset`);
2701
+ const length = safeUint(descriptor.length, `${path}.length`);
2702
+ if (offset + length > pool.length)
2703
+ invalidBinary(`Float range is outside the pool at ${path}.`);
2704
+ return pool.subarray(offset, offset + length);
2705
+ }
2706
+ function floatBlockKey(values) {
2707
+ let result = `${values.length}:`;
2708
+ for (let index = 0; index < values.length; index++)
2709
+ result += `${values[index]},`;
2710
+ return result;
2711
+ }
2712
+ function decodeStringIndices(value, strings, path) {
2713
+ const seen = new Set();
2714
+ return compactArray(value, path).map((item, index) => {
2715
+ const result = indexedString(strings, item, `${path}[${index}]`);
2716
+ if (!result.trim())
2717
+ invalidBinary(`Expected a non-empty string at ${path}[${index}].`);
2718
+ if (seen.has(result))
2719
+ invalidBinary(`Duplicate string-table value at ${path}[${index}].`);
2720
+ seen.add(result);
2721
+ return result;
2722
+ });
2723
+ }
2724
+ function optionalIndexedString(strings, value, path) {
2725
+ const index = finiteInteger(value, path);
2726
+ return index === -1 ? undefined : indexedString(strings, index, path);
2727
+ }
2728
+ function indexedString(strings, value, path) {
2729
+ const index = boundedIndex(value, strings.length, path);
2730
+ return strings[index];
2731
+ }
2732
+ function indexedLiteral(values, value, path) {
2733
+ const index = boundedIndex(value, values.length, path);
2734
+ return values[index];
2735
+ }
2736
+ function optionalBoundedIndex(value, length, path) {
2737
+ const index = finiteInteger(value, path);
2738
+ return index === -1 ? undefined : boundedIndex(index, length, path);
2739
+ }
2740
+ function boundedIndex(value, length, path) {
2741
+ const index = finiteInteger(value, path);
2742
+ if (index < 0 || index >= length)
2743
+ invalidBinary(`Index is outside its table at ${path}.`);
2744
+ return index;
2745
+ }
2746
+ function requiredMapIndex(map, key, label) {
2747
+ const value = map.get(key);
2748
+ if (value === undefined)
2749
+ invalidBinary(`Missing ${label} "${key}" while encoding.`);
2750
+ return value;
2751
+ }
2752
+ function align4(value) {
2753
+ return (value + 3) & -4;
2754
+ }
2755
+ function isParsedAnimation(value) {
2756
+ return 'source' in value && Array.isArray(value.tracks) && value.tracks.every(track => track.times instanceof Float32Array);
2757
+ }
2758
+ function isPath2DComponent(component) {
2759
+ return component.type === 'path2d' && typeof component.commands === 'string';
2760
+ }
2761
+ function isCompactVectorStrokeComponent(component) {
2762
+ if (component.type !== VECTOR_STROKE_EXTENSION || !Object.keys(component).every(key => VECTOR_STROKE_KEYS.has(key)))
2763
+ return false;
2764
+ const candidate = component;
2765
+ const inlinePath = typeof candidate.commands === 'string'
2766
+ && (Array.isArray(candidate.values) || candidate.values instanceof Float32Array)
2767
+ && Array.from(candidate.values).every(Number.isFinite);
2768
+ const sourcePath = Number.isSafeInteger(candidate.sourceComponent) && candidate.sourceComponent >= 0;
2769
+ return (inlinePath || sourcePath)
2770
+ && Array.isArray(candidate.color)
2771
+ && candidate.color.length === 4
2772
+ && candidate.color.every(value => Number.isFinite(value))
2773
+ && typeof candidate.width === 'number' && Number.isFinite(candidate.width)
2774
+ && (candidate.lineCap === 'butt' || candidate.lineCap === 'round' || candidate.lineCap === 'square')
2775
+ && (candidate.lineJoin === 'miter' || candidate.lineJoin === 'round' || candidate.lineJoin === 'bevel')
2776
+ && typeof candidate.miterLimit === 'number' && Number.isFinite(candidate.miterLimit)
2777
+ && (candidate.tolerance === undefined || (typeof candidate.tolerance === 'number' && Number.isFinite(candidate.tolerance)));
2778
+ }
2779
+ function isCompactVectorPathMorphComponent(component) {
2780
+ if (component.type !== VECTOR_PATH_MORPH_EXTENSION || !Object.keys(component).every(key => VECTOR_PATH_MORPH_KEYS.has(key)))
2781
+ return false;
2782
+ const candidate = component;
2783
+ const times = candidate.times;
2784
+ const values = candidate.values;
2785
+ const easings = candidate.easings;
2786
+ return typeof candidate.commands === 'string'
2787
+ && (Array.isArray(times) || times instanceof Float32Array)
2788
+ && Array.from(times).every(Number.isFinite)
2789
+ && (Array.isArray(values) || values instanceof Float32Array)
2790
+ && Array.from(values).every(Number.isFinite)
2791
+ && Number.isSafeInteger(candidate.valueSize) && candidate.valueSize > 0
2792
+ && values.length === times.length * candidate.valueSize
2793
+ && INTERPOLATIONS.includes(candidate.interpolation)
2794
+ && (easings === undefined || Array.isArray(easings) || easings instanceof Float32Array)
2795
+ && Array.isArray(candidate.fill) && candidate.fill.length === 4
2796
+ && (candidate.fillRule === 'nonzero' || candidate.fillRule === 'evenodd')
2797
+ && (candidate.tolerance === undefined || (typeof candidate.tolerance === 'number' && Number.isFinite(candidate.tolerance)));
2798
+ }
2799
+ function safeUint(value, path) {
2800
+ const result = finiteInteger(value, path);
2801
+ if (result < 0 || result > 0xffffffff)
2802
+ invalidBinary(`Expected an unsigned integer at ${path}.`);
2803
+ return result;
2804
+ }
2805
+ function finiteInteger(value, path) {
2806
+ if (typeof value !== 'number' || !Number.isSafeInteger(value))
2807
+ invalidBinary(`Expected an integer at ${path}.`);
2808
+ return value;
2809
+ }
2810
+ function finiteNumber(value, path) {
2811
+ if (typeof value !== 'number' || !Number.isFinite(value))
2812
+ invalidBinary(`Expected a finite number at ${path}.`);
2813
+ return value;
2814
+ }
2815
+ function positiveFiniteNumber(value, path) {
2816
+ const result = finiteNumber(value, path);
2817
+ if (result <= 0)
2818
+ invalidBinary(`Expected a positive number at ${path}.`);
2819
+ return result;
2820
+ }
2821
+ function nonNegativeFiniteNumber(value, path) {
2822
+ const result = finiteNumber(value, path);
2823
+ if (result < 0)
2824
+ invalidBinary(`Expected a non-negative number at ${path}.`);
2825
+ return result;
2826
+ }
2827
+ function finiteTuple(value, length, path) {
2828
+ const tuple = compactArray(value, path, length);
2829
+ if (tuple.length !== length)
2830
+ invalidBinary(`Expected exactly ${length} entries at ${path}.`);
2831
+ return tuple.map((item, index) => finiteNumber(item, `${path}[${index}]`));
2832
+ }
2833
+ function positiveFiniteTuple(value, length, path) {
2834
+ const tuple = finiteTuple(value, length, path);
2835
+ for (let index = 0; index < tuple.length; index++) {
2836
+ if (tuple[index] <= 0)
2837
+ invalidBinary(`Expected positive tuple values at ${path}[${index}].`);
2838
+ }
2839
+ return Object.freeze(tuple);
2840
+ }
2841
+ function nonNegativeFiniteTuple(value, length, path) {
2842
+ const tuple = finiteTuple(value, length, path);
2843
+ for (let index = 0; index < tuple.length; index++) {
2844
+ if (tuple[index] < 0)
2845
+ invalidBinary(`Expected non-negative tuple values at ${path}[${index}].`);
2846
+ }
2847
+ return Object.freeze(tuple);
2848
+ }
2849
+ function unitFiniteTuple(value, length, path) {
2850
+ const tuple = finiteTuple(value, length, path);
2851
+ for (let index = 0; index < tuple.length; index++) {
2852
+ if (tuple[index] < 0 || tuple[index] > 1)
2853
+ invalidBinary(`Expected tuple values in [0, 1] at ${path}[${index}].`);
2854
+ }
2855
+ return Object.freeze(tuple);
2856
+ }
2857
+ function requiredString(value, path) {
2858
+ if (typeof value !== 'string')
2859
+ invalidBinary(`Expected a string at ${path}.`);
2860
+ return value;
2861
+ }
2862
+ function requiredNonEmptyString(value, path) {
2863
+ if (!value.trim())
2864
+ invalidBinary(`Expected a non-empty string at ${path}.`);
2865
+ return value;
2866
+ }
2867
+ function compactArray(value, path, minimumLength = 0) {
2868
+ const result = binaryArray(value, path);
2869
+ if (result.length < minimumLength)
2870
+ invalidBinary(`Expected at least ${minimumLength} entries at ${path}.`);
2871
+ return result;
2872
+ }
2873
+ function binaryRecord(value, path) {
2874
+ if (!value || typeof value !== 'object' || Array.isArray(value))
2875
+ invalidBinary(`Expected an object at ${path}.`);
2876
+ return value;
2877
+ }
2878
+ function binaryArray(value, path) {
2879
+ if (!Array.isArray(value))
2880
+ invalidBinary(`Expected an array at ${path}.`);
2881
+ return value;
2882
+ }
2883
+ function binaryLimit(actual, maximum, label, path) {
2884
+ if (actual > maximum) {
2885
+ throw new AnimationFormatError('E_ANIMATION_LIMIT_EXCEEDED', `${label} count ${actual} exceeds limit ${maximum}.`, path);
2886
+ }
2887
+ }
2888
+ function invalidBinary(message) {
2889
+ throw new AnimationFormatError('E_ANIMATION_INVALID_BINARY', message, '$binary');
2890
+ }
2891
+
2892
+ const DEFAULT_PARSE_OPTIONS = Object.freeze({});
2893
+ const UTF8_DECODER = new TextDecoder();
2894
+ const UTF8_ENCODER = new TextEncoder();
2895
+ function parseAnimation(source, options = DEFAULT_PARSE_OPTIONS) {
2896
+ if (source instanceof ArrayBuffer) {
2897
+ const binary = tryDecodeAnimationBinary(source, options);
2898
+ if (binary)
2899
+ return binary;
2900
+ const limits = resolveAnimationParseLimits(options);
2901
+ if (source.byteLength > limits.maxInputBytes) {
2902
+ throw new AnimationFormatError('E_ANIMATION_LIMIT_EXCEEDED', `Input exceeds ${limits.maxInputBytes} bytes.`, '$');
2903
+ }
2904
+ return parseJsonText(UTF8_DECODER.decode(source), options);
2905
+ }
2906
+ if (typeof source === 'string')
2907
+ return parseJsonText(source, options);
2908
+ return parseAnimationValue(source, options, 'json');
2909
+ }
2910
+ function parseJsonText(source, options) {
2911
+ const limits = resolveAnimationParseLimits(options);
2912
+ const bytes = UTF8_ENCODER.encode(source).byteLength;
2913
+ if (bytes > limits.maxInputBytes) {
2914
+ throw new AnimationFormatError('E_ANIMATION_LIMIT_EXCEEDED', `Input exceeds ${limits.maxInputBytes} bytes.`, '$');
2915
+ }
2916
+ let value;
2917
+ try {
2918
+ value = JSON.parse(source);
2919
+ }
2920
+ catch (error) {
2921
+ throw new AnimationFormatError('E_ANIMATION_INVALID_FORMAT', `Animation JSON cannot be decoded: ${error instanceof Error ? error.message : String(error)}.`, '$');
2922
+ }
2923
+ return parseAnimationValue(value, options, 'json');
2924
+ }
2925
+
2926
+ export { ANIMATION_FORMAT, ANIMATION_VECTOR_SHAPE_EXTENSION_ID, ANIMATION_VERSION, AnimationExtensionRegistry, AnimationFormatError, HYA_STATE_MACHINE_CHANNEL_REGISTRY, HYA_STATE_MACHINE_EXTENSION_ID, decodeAnimationBinary, encodeAnimationBinary, extensionIdFromComponentType, hyaStateMachineChannelCapability, isAnimationBinary, parseAnimation, parseHyaStateMachineExtension, validateExtensionId };
2927
+ //# sourceMappingURL=index.js.map