@haiyue/animation-spec 0.1.0 → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/README.md +40 -6
  2. package/SPECIFICATION.md +12 -2
  3. package/bin/hya-live2d-convert.mjs +76 -0
  4. package/bin/{hya-convert.mjs → hya-lottie-convert.mjs} +1 -1
  5. package/dist/chunks/binary-DvuTJ_hy.js +1 -0
  6. package/dist/chunks/clip-baked-Dv-wjX9d.js +1 -0
  7. package/dist/chunks/errors-Bzs3GOD9.js +1 -0
  8. package/dist/chunks/expression-D1cKtNwM.js +1 -0
  9. package/dist/chunks/extensions-DxL4AxOC.js +1 -0
  10. package/dist/conversion.d.ts +1 -0
  11. package/dist/conversion.js +1 -0
  12. package/dist/cubism.d.ts +1 -0
  13. package/dist/cubism.js +1 -0
  14. package/dist/deformable2d.d.ts +1 -0
  15. package/dist/deformable2d.js +1 -0
  16. package/dist/hya-production.d.ts +1 -0
  17. package/dist/hya-production.js +1 -0
  18. package/dist/index.d.ts +1 -10
  19. package/dist/index.js +1 -2927
  20. package/dist/live2d/clip-baked.d.ts +1 -0
  21. package/dist/live2d/clip-baked.js +1 -0
  22. package/dist/live2d.d.ts +1 -0
  23. package/dist/live2d.js +1 -0
  24. package/dist/lottie.d.ts +1 -62
  25. package/dist/lottie.js +1 -2642
  26. package/dist/native3d.d.ts +1 -2
  27. package/dist/native3d.js +1 -907
  28. package/dist/shared.d.ts +2791 -0
  29. package/package.json +93 -69
  30. package/schema/animation.schema.json +104 -12
  31. package/schema/deformable-mesh-2d-extension.schema.json +18 -0
  32. package/schema/deformable-mesh-2d.contract.json +58 -0
  33. package/schema/hya-composition.schema.json +41 -0
  34. package/schema/parameterized-rig-2d.contract.json +63 -0
  35. package/schema/parameterized-rig-2d.schema.json +57 -0
  36. package/schema/parameterized-rig-census-map.json +128 -0
  37. package/schema/responsive-layout-2d-census-map.json +49 -0
  38. package/schema/responsive-layout-2d.contract.json +58 -0
  39. package/schema/responsive-layout-2d.schema.json +34 -0
  40. package/schema/state-machine-v2-census-map.json +1 -0
  41. package/schema/state-machine-v2.contract.json +66 -0
  42. package/schema/state-machine-v2.schema.json +55 -0
  43. package/schema/vector-visual-census-map.json +120 -0
  44. package/schema/vector-visual.contract.json +47 -0
  45. package/schema/vector-visual.schema.json +72 -0
  46. package/dist/binary.d.ts +0 -7
  47. package/dist/chunks/types-l6nBVYwx.js +0 -8
  48. package/dist/chunks/types-l6nBVYwx.js.map +0 -1
  49. package/dist/errors.d.ts +0 -7
  50. package/dist/extensions.d.ts +0 -19
  51. package/dist/index.js.map +0 -1
  52. package/dist/lottie-merge-path.d.ts +0 -11
  53. package/dist/lottie.js.map +0 -1
  54. package/dist/native3d/Animation3DError.d.ts +0 -8
  55. package/dist/native3d/Animation3DParser.d.ts +0 -7
  56. package/dist/native3d/Animation3DTypes.d.ts +0 -285
  57. package/dist/native3d/index.d.ts +0 -5
  58. package/dist/native3d.js.map +0 -1
  59. package/dist/parser.d.ts +0 -2
  60. package/dist/state-machine.d.ts +0 -130
  61. package/dist/text-selector.d.ts +0 -2
  62. package/dist/types.d.ts +0 -419
  63. package/dist/validation.d.ts +0 -32
  64. package/src/binary.ts +0 -1441
  65. package/src/errors.ts +0 -18
  66. package/src/extensions.ts +0 -55
  67. package/src/index.ts +0 -90
  68. package/src/lottie-merge-path.ts +0 -204
  69. package/src/lottie.ts +0 -3073
  70. package/src/native3d/Animation3DError.ts +0 -20
  71. package/src/native3d/Animation3DParser.ts +0 -964
  72. package/src/native3d/Animation3DTypes.ts +0 -322
  73. package/src/native3d/index.ts +0 -14
  74. package/src/native3d.ts +0 -2
  75. package/src/parser.ts +0 -41
  76. package/src/state-machine.ts +0 -645
  77. package/src/text-selector.ts +0 -7
  78. package/src/types.ts +0 -483
  79. package/src/validation.ts +0 -1286
  80. package/test/fixtures/basic-lottie.json +0 -31
package/src/validation.ts DELETED
@@ -1,1286 +0,0 @@
1
- import { AnimationFormatError } from './errors';
2
- import { extensionIdFromComponentType, validateExtensionId } from './extensions';
3
- import {
4
- ANIMATION_FORMAT,
5
- ANIMATION_VERSION,
6
- ANIMATION_VECTOR_SHAPE_EXTENSION_ID,
7
- type AnimationComponent,
8
- type AnimationCompositeLayer,
9
- type AnimationDocument,
10
- type AnimationEndBehavior,
11
- type AnimationLayerEffect,
12
- type AnimationNode,
13
- type AnimationParseOptions,
14
- type AnimationResource,
15
- type AnimationSprite2DComponent,
16
- type AnimationTrackProperty,
17
- type AnimationText2DComponent,
18
- type AnimationVectorShapeComponent,
19
- type AnimationVectorValueTrack,
20
- type ParsedAnimation,
21
- type ParsedAnimationTrack,
22
- } from './types';
23
- import {
24
- HYA_STATE_MACHINE_EXTENSION_ID,
25
- } from './state-machine';
26
- import { TEXT_SELECTOR_BASES, TEXT_SELECTOR_SHAPES } from './text-selector';
27
-
28
- const DEFAULT_LIMITS = Object.freeze({
29
- maxInputBytes: 64 * 1024 * 1024,
30
- maxMetadataBytes: 8 * 1024 * 1024,
31
- maxNodes: 100_000,
32
- maxComponents: 200_000,
33
- maxTracks: 200_000,
34
- maxKeyframes: 5_000_000,
35
- maxResources: 10_000,
36
- maxPathValues: 10_000_000,
37
- maxTextCharacters: 5_000_000,
38
- maxParticleCapacity: 2_000_000,
39
- });
40
-
41
- export function resolveAnimationParseLimits(options: AnimationParseOptions): Required<Omit<AnimationParseOptions, 'extensions' | 'copyFloatData'>> {
42
- if (
43
- options.maxInputBytes === undefined
44
- && options.maxMetadataBytes === undefined
45
- && options.maxNodes === undefined
46
- && options.maxComponents === undefined
47
- && options.maxTracks === undefined
48
- && options.maxKeyframes === undefined
49
- && options.maxResources === undefined
50
- && options.maxPathValues === undefined
51
- && options.maxTextCharacters === undefined
52
- && options.maxParticleCapacity === undefined
53
- ) {
54
- return DEFAULT_LIMITS;
55
- }
56
- return {
57
- maxInputBytes: positiveLimit(options.maxInputBytes, DEFAULT_LIMITS.maxInputBytes, 'maxInputBytes'),
58
- maxMetadataBytes: positiveLimit(options.maxMetadataBytes, DEFAULT_LIMITS.maxMetadataBytes, 'maxMetadataBytes'),
59
- maxNodes: positiveLimit(options.maxNodes, DEFAULT_LIMITS.maxNodes, 'maxNodes'),
60
- maxComponents: positiveLimit(options.maxComponents, DEFAULT_LIMITS.maxComponents, 'maxComponents'),
61
- maxTracks: positiveLimit(options.maxTracks, DEFAULT_LIMITS.maxTracks, 'maxTracks'),
62
- maxKeyframes: positiveLimit(options.maxKeyframes, DEFAULT_LIMITS.maxKeyframes, 'maxKeyframes'),
63
- maxResources: positiveLimit(options.maxResources, DEFAULT_LIMITS.maxResources, 'maxResources'),
64
- maxPathValues: positiveLimit(options.maxPathValues, DEFAULT_LIMITS.maxPathValues, 'maxPathValues'),
65
- maxTextCharacters: positiveLimit(options.maxTextCharacters, DEFAULT_LIMITS.maxTextCharacters, 'maxTextCharacters'),
66
- maxParticleCapacity: positiveLimit(options.maxParticleCapacity, DEFAULT_LIMITS.maxParticleCapacity, 'maxParticleCapacity'),
67
- };
68
- }
69
-
70
- export function parseAnimationValue(
71
- input: unknown,
72
- options: AnimationParseOptions,
73
- source: 'json' | 'binary',
74
- backingBuffer?: ArrayBuffer,
75
- ): ParsedAnimation {
76
- const limits = resolveAnimationParseLimits(options);
77
- const root = record(input, '$');
78
- if (root.format !== ANIMATION_FORMAT) fail(`format must be "${ANIMATION_FORMAT}".`, '$.format');
79
- if (root.version !== ANIMATION_VERSION) {
80
- throw new AnimationFormatError('E_ANIMATION_UNSUPPORTED_VERSION', `Unsupported animation version "${String(root.version)}".`, '$.version');
81
- }
82
-
83
- const canvasValue = record(root.canvas, '$.canvas');
84
- const canvas = Object.freeze({
85
- width: positiveNumber(canvasValue.width, '$.canvas.width'),
86
- height: positiveNumber(canvasValue.height, '$.canvas.height'),
87
- coordinateSystem: literal(canvasValue.coordinateSystem, ['screen-y-down'] as const, '$.canvas.coordinateSystem'),
88
- });
89
- const duration = positiveNumber(root.duration, '$.duration');
90
- const frameRate = root.frameRate === undefined ? undefined : positiveNumber(root.frameRate, '$.frameRate');
91
- const endBehavior = root.endBehavior === undefined
92
- ? 'loop'
93
- : literal(root.endBehavior, ['hold', 'loop', 'destroy'] as const, '$.endBehavior');
94
-
95
- const resourcesInput = array(root.resources ?? [], '$.resources');
96
- limit(resourcesInput.length, limits.maxResources, 'resources', '$.resources');
97
- const resourceIds = new Set<string>();
98
- const resources = resourcesInput.map((value, index) => parseBinaryResourceValue(value, index, resourceIds));
99
-
100
- const nodesInput = array(root.nodes, '$.nodes');
101
- limit(nodesInput.length, limits.maxNodes, 'nodes', '$.nodes');
102
- const nodeIds = new Set<string>();
103
- let componentCount = 0;
104
- let pathValueCount = 0;
105
- let textCharacterCount = 0;
106
- let particleCapacity = 0;
107
- const nodes = nodesInput.map((value, index) => {
108
- const node = parseBinaryNodeValue(value, index, nodeIds, options, (kind, count) => {
109
- if (kind === 'path') {
110
- pathValueCount += count;
111
- limit(pathValueCount, limits.maxPathValues, 'path values', `$.nodes[${index}].components`);
112
- } else if (kind === 'text') {
113
- textCharacterCount += count;
114
- limit(textCharacterCount, limits.maxTextCharacters, 'text characters', `$.nodes[${index}].components`);
115
- } else {
116
- particleCapacity += count;
117
- limit(particleCapacity, limits.maxParticleCapacity, 'particle capacity', `$.nodes[${index}].components`);
118
- }
119
- });
120
- componentCount += node.components?.length ?? 0;
121
- limit(componentCount, limits.maxComponents, 'components', `$.nodes[${index}].components`);
122
- return node;
123
- });
124
- const tracksInput = array(root.tracks ?? [], '$.tracks');
125
- limit(tracksInput.length, limits.maxTracks, 'tracks', '$.tracks');
126
- let keyframeCount = 0;
127
- const tracks = tracksInput.map((value, index) => {
128
- const track = parseBinaryTrackValue(value, index, nodeIds, duration, options.copyFloatData === true);
129
- keyframeCount += track.times.length;
130
- limit(keyframeCount, limits.maxKeyframes, 'keyframes', `$.tracks[${index}].times`);
131
- return track;
132
- });
133
-
134
- const extensionsUsed = stringList(root.extensionsUsed ?? [], '$.extensionsUsed');
135
- const extensionsRequired = stringList(root.extensionsRequired ?? [], '$.extensionsRequired');
136
- const extensionData = root.extensions === undefined ? {} : record(root.extensions, '$.extensions');
137
- return finalizeParsedAnimation({
138
- ...(typeof root.name === 'string' ? { name: root.name } : {}),
139
- canvas,
140
- duration,
141
- ...(frameRate !== undefined ? { frameRate } : {}),
142
- endBehavior,
143
- resources,
144
- nodes,
145
- tracks,
146
- extensionsUsed,
147
- extensionsRequired,
148
- extensions: extensionData,
149
- }, options, source, backingBuffer);
150
- }
151
-
152
- /** Canonical fields used internally after JSON or compact-binary structural validation. */
153
- export interface ParsedAnimationFields {
154
- readonly name?: string;
155
- readonly canvas: ParsedAnimation['canvas'];
156
- readonly duration: number;
157
- readonly frameRate?: number;
158
- readonly endBehavior: AnimationEndBehavior;
159
- readonly resources: readonly Readonly<AnimationResource>[];
160
- readonly nodes: readonly Readonly<AnimationNode>[];
161
- readonly tracks: readonly ParsedAnimationTrack[];
162
- readonly extensionsUsed: readonly string[];
163
- readonly extensionsRequired: readonly string[];
164
- readonly extensions: Readonly<Record<string, unknown>>;
165
- }
166
-
167
- /** @internal Shared semantic validation after a decoder has canonicalized every field exactly once. */
168
- export function finalizeParsedAnimation(
169
- fields: ParsedAnimationFields,
170
- options: AnimationParseOptions,
171
- source: 'json' | 'binary',
172
- backingBuffer?: ArrayBuffer,
173
- graphValidated = false,
174
- ): ParsedAnimation {
175
- if (fields.extensionsUsed.includes(HYA_STATE_MACHINE_EXTENSION_ID)
176
- && !(HYA_STATE_MACHINE_EXTENSION_ID in fields.extensions)) {
177
- fail(
178
- `Built-in extension "${HYA_STATE_MACHINE_EXTENSION_ID}" requires document data.`,
179
- `$.extensions.${HYA_STATE_MACHINE_EXTENSION_ID}`,
180
- );
181
- }
182
- const hasHierarchy = !graphValidated && fields.nodes.some(node => node.parent !== undefined);
183
- const hasComposites = !graphValidated && fields.nodes.some(node => node.composite !== undefined);
184
- if (!graphValidated && (hasHierarchy || hasComposites)) {
185
- const nodeIds = new Set(fields.nodes.map(node => node.id));
186
- if (hasHierarchy) validateHierarchy(fields.nodes, nodeIds);
187
- if (hasComposites) validateComposites(fields.nodes, nodeIds);
188
- }
189
- const hasResourceReferences = fields.nodes.some(node => node.components?.some(component => (
190
- component.type === 'sprite2d' || component.type === 'particle2d' || component.type === 'audio'
191
- || (component.type === 'text2d' && component.fontResource !== undefined)
192
- )));
193
- const resourceIds = hasResourceReferences ? new Set(fields.resources.map(resource => resource.id)) : undefined;
194
- const resourcesById = hasResourceReferences ? new Map(fields.resources.map(resource => [resource.id, resource])) : undefined;
195
- for (let index = 0; index < fields.nodes.length; index++) {
196
- const node = fields.nodes[index]!;
197
- const start = node.start ?? 0;
198
- if (start > fields.duration || start + (node.duration ?? fields.duration - start) > fields.duration + 1e-6) {
199
- fail('Node time range must fit inside the composition duration.', `$.nodes[${index}]`);
200
- }
201
- const nodeCompositeLayers = compositeLayers(node.composite);
202
- for (let layerIndex = 0; layerIndex < nodeCompositeLayers.length; layerIndex++) {
203
- const track = nodeCompositeLayers[layerIndex]!.expansionTrack;
204
- if (track) validateTrackDuration(
205
- track.times,
206
- `$.nodes[${index}].composite${'layers' in node.composite! ? `.layers[${layerIndex}]` : ''}.expansionTrack.times`,
207
- fields.duration,
208
- );
209
- }
210
- for (let componentIndex = 0; componentIndex < (node.components?.length ?? 0); componentIndex++) {
211
- const component = node.components![componentIndex]!;
212
- if (component.type === ANIMATION_VECTOR_SHAPE_EXTENSION_ID) {
213
- validateVectorTrackDurations(
214
- component as AnimationVectorShapeComponent,
215
- `$.nodes[${index}].components[${componentIndex}]`,
216
- fields.duration,
217
- );
218
- } else if (component.type === 'org.haiyue.vector-path-morph@1') {
219
- validateTrackDuration(
220
- (component as unknown as { times: readonly number[] | Float32Array }).times,
221
- `$.nodes[${index}].components[${componentIndex}].times`,
222
- fields.duration,
223
- );
224
- }
225
- const sprite = component.type === 'sprite2d' ? component as AnimationSprite2DComponent : undefined;
226
- if (sprite?.uvRectTrack) {
227
- validateTrackDuration(
228
- sprite.uvRectTrack.times,
229
- `$.nodes[${index}].components[${componentIndex}].uvRectTrack.times`,
230
- fields.duration,
231
- );
232
- }
233
- if (component.type === 'text2d') {
234
- const text = component as AnimationText2DComponent;
235
- validateTextTrackDurations(text, `$.nodes[${index}].components[${componentIndex}]`, fields.duration);
236
- const fontResources = [text.fontResource, ...(text.documents?.map(document => document.fontResource) ?? [])]
237
- .filter((resource): resource is string => resource !== undefined);
238
- for (const fontResource of fontResources) {
239
- if (!resourceIds!.has(fontResource)) {
240
- fail(`Text component references missing font resource "${fontResource}".`, `$.nodes[${index}].components[${componentIndex}].fontResource`);
241
- }
242
- if (resourcesById!.get(fontResource)?.type !== 'binary') {
243
- fail(`Text font resource "${fontResource}" must have type "binary".`, `$.nodes[${index}].components[${componentIndex}].fontResource`);
244
- }
245
- }
246
- }
247
- const imageResource = component.type === 'sprite2d' || component.type === 'particle2d' ? component.resource : undefined;
248
- if (typeof imageResource === 'string' && !resourceIds!.has(imageResource)) {
249
- fail(`Component references missing resource "${imageResource}".`, `$.nodes[${index}].components[${componentIndex}].resource`);
250
- }
251
- if (typeof imageResource === 'string' && resourcesById!.get(imageResource)?.type !== 'image') {
252
- fail(`Component resource "${imageResource}" must have type "image".`, `$.nodes[${index}].components[${componentIndex}].resource`);
253
- }
254
- const audioResource = component.type === 'audio' ? component.resource : undefined;
255
- if (typeof audioResource === 'string' && resourcesById!.get(audioResource)?.type !== 'audio') {
256
- fail(`Audio resource "${audioResource}" must have type "audio".`, `$.nodes[${index}].components[${componentIndex}].resource`);
257
- }
258
- }
259
- for (let effectIndex = 0; effectIndex < (node.effects?.length ?? 0); effectIndex++) {
260
- validateEffectTrackDurations(node.effects![effectIndex]!, `$.nodes[${index}].effects[${effectIndex}]`, fields.duration);
261
- }
262
- }
263
-
264
- if (fields.extensionsUsed.length > 0 || fields.extensionsRequired.length > 0) {
265
- const used = new Set(fields.extensionsUsed);
266
- for (const id of fields.extensionsUsed) validateExtensionId(id);
267
- for (const id of fields.extensionsRequired) {
268
- validateExtensionId(id);
269
- if (!used.has(id)) fail(`Required extension "${id}" must also appear in extensionsUsed.`, '$.extensionsRequired');
270
- if (id !== HYA_STATE_MACHINE_EXTENSION_ID && !options.extensions?.has(id)) {
271
- throw new AnimationFormatError('E_ANIMATION_MISSING_EXTENSION', `Required extension "${id}" is not registered.`, '$.extensionsRequired');
272
- }
273
- }
274
- for (let nodeIndex = 0; nodeIndex < fields.nodes.length; nodeIndex++) {
275
- const components = fields.nodes[nodeIndex]!.components ?? [];
276
- for (let componentIndex = 0; componentIndex < components.length; componentIndex++) {
277
- const extension = extensionIdFromComponentType(components[componentIndex]!.type);
278
- if (extension && !used.has(extension)) {
279
- fail(`Extension component "${extension}" must be declared in extensionsUsed.`, `$.nodes[${nodeIndex}].components[${componentIndex}].type`);
280
- }
281
- }
282
- }
283
- for (const id of fields.extensionsUsed) {
284
- const handler = id === HYA_STATE_MACHINE_EXTENSION_ID ? undefined : options.extensions?.get(id);
285
- if (!handler?.validateDocument || !(id in fields.extensions)) continue;
286
- handler.validateDocument(fields.extensions[id], extensionContext(id, `$.extensions.${id}`));
287
- }
288
- } else {
289
- for (let nodeIndex = 0; nodeIndex < fields.nodes.length; nodeIndex++) {
290
- const components = fields.nodes[nodeIndex]!.components ?? [];
291
- for (let componentIndex = 0; componentIndex < components.length; componentIndex++) {
292
- const extension = extensionIdFromComponentType(components[componentIndex]!.type);
293
- if (extension) {
294
- fail(`Extension component "${extension}" must be declared in extensionsUsed.`, `$.nodes[${nodeIndex}].components[${componentIndex}].type`);
295
- }
296
- }
297
- }
298
- }
299
-
300
- return Object.freeze({
301
- format: ANIMATION_FORMAT,
302
- version: ANIMATION_VERSION,
303
- ...fields,
304
- resources: Object.freeze(fields.resources),
305
- nodes: Object.freeze(fields.nodes),
306
- tracks: Object.freeze(fields.tracks),
307
- extensionsUsed: Object.freeze(fields.extensionsUsed),
308
- extensionsRequired: Object.freeze(fields.extensionsRequired),
309
- extensions: Object.freeze({ ...fields.extensions }),
310
- source,
311
- ...(backingBuffer ? { backingBuffer } : {}),
312
- });
313
- }
314
-
315
- function validateVectorTrackDurations(component: AnimationVectorShapeComponent, path: string, duration: number): void {
316
- const check = (owner: object | undefined, prefix: string, keys: readonly string[]): void => {
317
- if (!owner) return;
318
- for (const key of keys) {
319
- const track = (owner as Record<string, AnimationVectorValueTrack | undefined>)[key];
320
- if (track) validateTrackDuration(track.times, `${path}.${prefix}${key}.times`, duration);
321
- }
322
- };
323
- check(component, '', ['morph']);
324
- check(component.fill, 'fill.', component.fill?.kind === 'solid'
325
- ? ['colorTrack', 'opacityTrack']
326
- : ['startTrack', 'endTrack', 'stopsTrack', 'opacityTrack']);
327
- check(component.stroke, 'stroke.', ['colorTrack', 'opacityTrack', 'widthTrack', 'dashOffsetTrack']);
328
- check(component.stroke?.gradient, 'stroke.gradient.', ['startTrack', 'endTrack', 'stopsTrack', 'opacityTrack']);
329
- for (let index = 0; index < (component.modifiers?.length ?? 0); index++) {
330
- const modifier = component.modifiers![index]!;
331
- check(modifier, `modifiers[${index}].`, modifier.kind === 'trim-path'
332
- ? ['startTrack', 'endTrack', 'offsetTrack']
333
- : ['radiusTrack']);
334
- }
335
- }
336
-
337
- function validateTextTrackDurations(
338
- component: AnimationText2DComponent,
339
- path: string,
340
- duration: number,
341
- ): void {
342
- const documents = component.documents ?? [];
343
- const lastDocument = documents[documents.length - 1];
344
- if (lastDocument && lastDocument.time > Math.max(duration, Math.fround(duration))) {
345
- fail('Text document time exceeds the composition duration.', `${path}.documents[${documents.length - 1}].time`);
346
- }
347
- for (let index = 0; index < (component.animators?.length ?? 0); index++) {
348
- const animator = component.animators![index]!;
349
- checkOwnerTrackDurations(
350
- animator.selector,
351
- `${path}.animators[${index}].selector`,
352
- ['startTrack', 'endTrack', 'offsetTrack', 'amountTrack'],
353
- duration,
354
- );
355
- checkOwnerTrackDurations(
356
- animator,
357
- `${path}.animators[${index}]`,
358
- ['positionTrack', 'scaleTrack', 'rotationTrack', 'opacityTrack', 'fillColorTrack', 'trackingTrack'],
359
- duration,
360
- );
361
- }
362
- }
363
-
364
- function validateEffectTrackDurations(effect: AnimationLayerEffect, path: string, duration: number): void {
365
- const keys = effect.kind === 'tint' ? ['blackTrack', 'whiteTrack', 'amountTrack']
366
- : effect.kind === 'fill' ? ['colorTrack', 'opacityTrack']
367
- : effect.kind === 'opacity' ? ['opacityTrack']
368
- : effect.kind === 'color-matrix' ? ['matrixTrack']
369
- : effect.kind === 'blur' ? ['radiusTrack']
370
- : ['colorTrack', 'opacityTrack', 'offsetTrack', 'blurTrack'];
371
- checkOwnerTrackDurations(effect, path, keys, duration);
372
- }
373
-
374
- function checkOwnerTrackDurations(
375
- owner: object,
376
- path: string,
377
- keys: readonly string[],
378
- duration: number,
379
- ): void {
380
- for (const key of keys) {
381
- const track = (owner as Record<string, AnimationVectorValueTrack | undefined>)[key];
382
- if (track) validateTrackDuration(track.times, `${path}.${key}.times`, duration);
383
- }
384
- }
385
-
386
- function validateTrackDuration(times: readonly number[] | Float32Array, path: string, duration: number): void {
387
- const last = times[times.length - 1];
388
- if (last !== undefined && last > Math.max(duration, Math.fround(duration))) {
389
- fail('Vector track time exceeds the composition duration.', `${path}[${times.length - 1}]`);
390
- }
391
- }
392
-
393
- export function parsedAnimationToDocument(parsed: ParsedAnimation): AnimationDocument {
394
- return {
395
- format: parsed.format,
396
- version: parsed.version,
397
- canvas: parsed.canvas,
398
- duration: parsed.duration,
399
- endBehavior: parsed.endBehavior,
400
- nodes: parsed.nodes,
401
- tracks: parsed.tracks,
402
- resources: parsed.resources,
403
- extensionsUsed: parsed.extensionsUsed,
404
- extensionsRequired: parsed.extensionsRequired,
405
- extensions: parsed.extensions,
406
- ...(parsed.name !== undefined ? { name: parsed.name } : {}),
407
- ...(parsed.frameRate !== undefined ? { frameRate: parsed.frameRate } : {}),
408
- };
409
- }
410
-
411
- /** @internal Compact-binary structural decoder entry point. */
412
- export function parseBinaryNodeValue(
413
- value: unknown,
414
- index: number,
415
- ids: Set<string>,
416
- options: AnimationParseOptions,
417
- countBudget: (kind: 'path' | 'text' | 'particle', count: number) => void,
418
- ): Readonly<AnimationNode> {
419
- const path = `$.nodes[${index}]`;
420
- const node = record(value, path);
421
- const id = nonEmptyString(node.id, `${path}.id`);
422
- if (ids.has(id)) fail(`Duplicate node id "${id}".`, `${path}.id`);
423
- ids.add(id);
424
- const start = node.start === undefined ? 0 : nonNegativeNumber(node.start, `${path}.start`);
425
- const duration = node.duration === undefined ? undefined : positiveNumber(node.duration, `${path}.duration`);
426
- const transform = node.transform === undefined ? undefined : parseTransform(node.transform, `${path}.transform`);
427
- const components = node.components === undefined
428
- ? undefined
429
- : array(node.components, `${path}.components`).map((component, componentIndex) => (
430
- parseComponent(component, `${path}.components[${componentIndex}]`, options, countBudget)
431
- ));
432
- const effects = node.effects === undefined
433
- ? undefined
434
- : parseLayerEffects(node.effects, `${path}.effects`, options.copyFloatData === true);
435
- return Object.freeze({
436
- id,
437
- ...(typeof node.name === 'string' ? { name: node.name } : {}),
438
- ...(node.parent !== undefined ? { parent: nonEmptyString(node.parent, `${path}.parent`) } : {}),
439
- ...(start !== 0 ? { start } : {}),
440
- ...(duration !== undefined ? { duration } : {}),
441
- ...(transform ? { transform } : {}),
442
- ...(node.composite !== undefined ? {
443
- composite: parseComposite(node.composite, `${path}.composite`, options.copyFloatData === true),
444
- } : {}),
445
- ...(effects ? { effects } : {}),
446
- ...(components ? { components: Object.freeze(components) } : {}),
447
- ...(node.extensions !== undefined ? { extensions: Object.freeze({ ...record(node.extensions, `${path}.extensions`) }) } : {}),
448
- });
449
- }
450
-
451
- function parseTransform(value: unknown, path: string) {
452
- const transform = record(value, path);
453
- const opacity = transform.opacity === undefined ? undefined : unitNumber(transform.opacity, `${path}.opacity`);
454
- return Object.freeze({
455
- ...(transform.position !== undefined ? { position: vec2(transform.position, `${path}.position`) } : {}),
456
- ...(transform.rotation !== undefined ? { rotation: finiteNumber(transform.rotation, `${path}.rotation`) } : {}),
457
- ...(transform.scale !== undefined ? { scale: vec2(transform.scale, `${path}.scale`) } : {}),
458
- ...(transform.anchor !== undefined ? { anchor: vec2(transform.anchor, `${path}.anchor`) } : {}),
459
- ...(opacity !== undefined ? { opacity } : {}),
460
- });
461
- }
462
-
463
- /** @internal Compact-binary transform decoder entry point. */
464
- export function parseBinaryTransformValue(value: unknown, path: string): Readonly<NonNullable<AnimationNode['transform']>> {
465
- return parseTransform(value, path);
466
- }
467
-
468
- function parseComponent(
469
- value: unknown,
470
- path: string,
471
- options: AnimationParseOptions,
472
- countBudget: (kind: 'path' | 'text' | 'particle', count: number) => void,
473
- ): AnimationComponent {
474
- const component = record(value, path);
475
- const type = nonEmptyString(component.type, `${path}.type`);
476
- if (type === 'shape2d') {
477
- return Object.freeze({
478
- type,
479
- shape: literal(component.shape, ['rect', 'ellipse'] as const, `${path}.shape`),
480
- size: positiveVec2(component.size, `${path}.size`),
481
- fill: color(component.fill, `${path}.fill`),
482
- ...(component.position !== undefined ? { position: vec2(component.position, `${path}.position`) } : {}),
483
- });
484
- }
485
- if (type === 'path2d') {
486
- const commands = nonEmptyString(component.commands, `${path}.commands`).toUpperCase();
487
- if (!/^[MLQCZ]+$/.test(commands) || commands[0] !== 'M') fail('Path commands must start with M and contain only M, L, Q, C, Z.', `${path}.commands`);
488
- validatePathTopology(commands, `${path}.commands`);
489
- const values = floatArray(component.values, `${path}.values`, options.copyFloatData === true);
490
- const expected = pathValueCount(commands);
491
- if (values.length !== expected) fail(`Path values length must be ${expected} for command stream "${commands}".`, `${path}.values`);
492
- if (!commands.includes('Z')) fail('Filled path must contain at least one closed contour (Z).', `${path}.commands`);
493
- countBudget('path', values.length);
494
- return Object.freeze({
495
- type,
496
- commands,
497
- values,
498
- fill: color(component.fill, `${path}.fill`),
499
- fillRule: component.fillRule === undefined ? 'nonzero' : literal(component.fillRule, ['nonzero', 'evenodd'] as const, `${path}.fillRule`),
500
- tolerance: component.tolerance === undefined ? 0.35 : positiveNumber(component.tolerance, `${path}.tolerance`),
501
- });
502
- }
503
- if (type === 'sprite2d') {
504
- const uvRectTrack = component.uvRectTrack === undefined
505
- ? undefined
506
- : parseVectorValueTrack(component.uvRectTrack, `${path}.uvRectTrack`, 4, options.copyFloatData === true);
507
- if (uvRectTrack && uvRectTrack.interpolation !== 'step') {
508
- fail('Sprite uvRectTrack requires step interpolation.', `${path}.uvRectTrack.interpolation`);
509
- }
510
- if (uvRectTrack) validateUvRectTrack(uvRectTrack, `${path}.uvRectTrack`);
511
- return Object.freeze({
512
- type,
513
- resource: nonEmptyString(component.resource, `${path}.resource`),
514
- size: positiveVec2(component.size, `${path}.size`),
515
- ...(component.position !== undefined ? { position: vec2(component.position, `${path}.position`) } : {}),
516
- ...(component.tint !== undefined ? { tint: color(component.tint, `${path}.tint`) } : {}),
517
- ...(component.uvRect !== undefined ? { uvRect: uvRect(component.uvRect, `${path}.uvRect`) } : {}),
518
- ...(uvRectTrack ? { uvRectTrack } : {}),
519
- });
520
- }
521
- if (type === 'text2d') {
522
- if (typeof component.text !== 'string') fail('Expected text to be a string.', `${path}.text`);
523
- countBudget('text', component.text.length);
524
- const resolutionScale = component.resolutionScale === undefined ? undefined : positiveNumber(component.resolutionScale, `${path}.resolutionScale`);
525
- if (resolutionScale !== undefined && resolutionScale > 4) fail('resolutionScale must be at most 4.', `${path}.resolutionScale`);
526
- const documents = component.documents === undefined ? undefined : parseTextDocuments(component.documents, `${path}.documents`);
527
- const animators = component.animators === undefined ? undefined : parseTextAnimators(component.animators, `${path}.animators`, options.copyFloatData === true);
528
- if (documents) for (const document of documents) countBudget('text', document.text.length);
529
- return Object.freeze({
530
- type,
531
- text: component.text,
532
- size: positiveVec2(component.size, `${path}.size`),
533
- color: color(component.color, `${path}.color`),
534
- ...(component.position !== undefined ? { position: vec2(component.position, `${path}.position`) } : {}),
535
- ...(component.fontFamily !== undefined ? { fontFamily: nonEmptyString(component.fontFamily, `${path}.fontFamily`) } : {}),
536
- ...(component.fontSize !== undefined ? { fontSize: positiveNumber(component.fontSize, `${path}.fontSize`) } : {}),
537
- ...(component.fontWeight !== undefined ? { fontWeight: fontWeight(component.fontWeight, `${path}.fontWeight`) } : {}),
538
- ...(component.fontStyle !== undefined ? { fontStyle: literal(component.fontStyle, ['normal', 'italic'] as const, `${path}.fontStyle`) } : {}),
539
- ...(component.fontResource !== undefined ? { fontResource: nonEmptyString(component.fontResource, `${path}.fontResource`) } : {}),
540
- ...(component.lineHeight !== undefined ? { lineHeight: positiveNumber(component.lineHeight, `${path}.lineHeight`) } : {}),
541
- ...(component.tracking !== undefined ? { tracking: finiteNumber(component.tracking, `${path}.tracking`) } : {}),
542
- ...(component.textAlign !== undefined ? { textAlign: literal(component.textAlign, ['left', 'center', 'right'] as const, `${path}.textAlign`) } : {}),
543
- ...(component.verticalAlign !== undefined ? { verticalAlign: literal(component.verticalAlign, ['top', 'middle', 'bottom'] as const, `${path}.verticalAlign`) } : {}),
544
- ...(component.backgroundColor !== undefined ? { backgroundColor: color(component.backgroundColor, `${path}.backgroundColor`) } : {}),
545
- ...(component.padding !== undefined ? { padding: nonNegativeNumber(component.padding, `${path}.padding`) } : {}),
546
- ...(resolutionScale !== undefined ? { resolutionScale } : {}),
547
- ...(documents ? { documents } : {}),
548
- ...(animators ? { animators } : {}),
549
- });
550
- }
551
- if (type === 'particle2d') {
552
- const maxParticles = boundedInteger(component.maxParticles, 1, 1_000_000, `${path}.maxParticles`);
553
- countBudget('particle', maxParticles);
554
- return Object.freeze({
555
- type,
556
- maxParticles,
557
- emissionRate: nonNegativeNumber(component.emissionRate, `${path}.emissionRate`),
558
- lifetime: numericRange(component.lifetime, `${path}.lifetime`, 1e-4),
559
- speed: numericRange(component.speed, `${path}.speed`, 0),
560
- angle: numericRange(component.angle, `${path}.angle`),
561
- startSize: numericRange(component.startSize, `${path}.startSize`, 0),
562
- endSize: numericRange(component.endSize, `${path}.endSize`, 0),
563
- startColor: color(component.startColor, `${path}.startColor`),
564
- endColor: color(component.endColor, `${path}.endColor`),
565
- ...(component.burst !== undefined ? { burst: boundedInteger(component.burst, 0, maxParticles, `${path}.burst`) } : {}),
566
- ...(component.duration !== undefined ? { duration: positiveNumber(component.duration, `${path}.duration`) } : {}),
567
- ...(component.loop !== undefined ? { loop: booleanValue(component.loop, `${path}.loop`) } : {}),
568
- ...(component.seed !== undefined ? { seed: safeInteger(component.seed, `${path}.seed`) } : {}),
569
- ...(component.gravity !== undefined ? { gravity: vec2(component.gravity, `${path}.gravity`) } : {}),
570
- ...(component.shape !== undefined ? { shape: literal(component.shape, ['point', 'box', 'circle'] as const, `${path}.shape`) } : {}),
571
- ...(component.shapeSize !== undefined ? { shapeSize: nonNegativeVec2(component.shapeSize, `${path}.shapeSize`) } : {}),
572
- ...(component.shapeRadius !== undefined ? { shapeRadius: nonNegativeNumber(component.shapeRadius, `${path}.shapeRadius`) } : {}),
573
- ...(component.blendMode !== undefined ? { blendMode: literal(component.blendMode, ['normal', 'additive'] as const, `${path}.blendMode`) } : {}),
574
- ...(component.resource !== undefined ? { resource: nonEmptyString(component.resource, `${path}.resource`) } : {}),
575
- ...(component.radial !== undefined ? { radial: booleanValue(component.radial, `${path}.radial`) } : {}),
576
- });
577
- }
578
- if (type === 'audio') {
579
- return Object.freeze({
580
- type,
581
- resource: nonEmptyString(component.resource, `${path}.resource`),
582
- ...(component.volume !== undefined ? { volume: unitNumber(component.volume, `${path}.volume`) } : {}),
583
- ...(component.loop !== undefined ? { loop: booleanValue(component.loop, `${path}.loop`) } : {}),
584
- ...(component.startOffset !== undefined ? { startOffset: nonNegativeNumber(component.startOffset, `${path}.startOffset`) } : {}),
585
- ...(component.playbackRate !== undefined ? { playbackRate: positiveNumber(component.playbackRate, `${path}.playbackRate`) } : {}),
586
- });
587
- }
588
- if (type === 'org.haiyue.vector-path-morph@1') {
589
- const commands = nonEmptyString(component.commands, `${path}.commands`).toUpperCase();
590
- if (!/^[MLQCZ]+$/.test(commands) || commands[0] !== 'M') fail('Path morph commands must start with M and contain only M, L, Q, C, Z.', `${path}.commands`);
591
- validatePathTopology(commands, `${path}.commands`);
592
- if (!commands.includes('Z')) fail('Filled path morph must contain at least one closed contour (Z).', `${path}.commands`);
593
- const times = floatArray(component.times, `${path}.times`, options.copyFloatData === true);
594
- const values = floatArray(component.values, `${path}.values`, options.copyFloatData === true);
595
- const valueSize = safeInteger(component.valueSize, `${path}.valueSize`);
596
- if (valueSize !== pathValueCount(commands)) fail(`Path morph valueSize must be ${pathValueCount(commands)} for command stream "${commands}".`, `${path}.valueSize`);
597
- if (times.length === 0 || values.length !== times.length * valueSize) fail('Path morph values must contain valueSize numbers for every keyframe.', `${path}.values`);
598
- for (let index = 0; index < times.length; index++) {
599
- if (times[index]! < 0 || (index > 0 && times[index]! <= times[index - 1]!)) fail('Path morph times must be non-negative and strictly increasing.', `${path}.times`);
600
- }
601
- const interpolation = literal(component.interpolation, ['step', 'linear', 'cubic-bezier'] as const, `${path}.interpolation`);
602
- const easings = component.easings === undefined ? undefined : floatArray(component.easings, `${path}.easings`, options.copyFloatData === true);
603
- if (interpolation === 'cubic-bezier' && easings?.length !== Math.max(0, times.length - 1) * 4) fail('Cubic path morph easing data must contain four numbers per segment.', `${path}.easings`);
604
- countBudget('path', values.length);
605
- return Object.freeze({
606
- type,
607
- commands,
608
- times,
609
- values,
610
- valueSize,
611
- interpolation,
612
- ...(easings === undefined ? {} : { easings }),
613
- fill: color(component.fill, `${path}.fill`),
614
- fillRule: component.fillRule === undefined ? 'nonzero' : literal(component.fillRule, ['nonzero', 'evenodd'] as const, `${path}.fillRule`),
615
- tolerance: component.tolerance === undefined ? 0.35 : positiveNumber(component.tolerance, `${path}.tolerance`),
616
- });
617
- }
618
- if (type === ANIMATION_VECTOR_SHAPE_EXTENSION_ID) {
619
- const commands = nonEmptyString(component.commands, `${path}.commands`).toUpperCase();
620
- if (!/^[MLQCZ]+$/.test(commands) || commands[0] !== 'M') fail('Vector shape commands must start with M and contain only M, L, Q, C, Z.', `${path}.commands`);
621
- validatePathTopology(commands, `${path}.commands`, component.fill !== undefined);
622
- const values = floatArray(component.values, `${path}.values`, options.copyFloatData === true);
623
- const valueSize = pathValueCount(commands);
624
- if (values.length !== valueSize) fail(`Vector shape values length must be ${valueSize}.`, `${path}.values`);
625
- const morph = component.morph === undefined ? undefined : parseVectorValueTrack(component.morph, `${path}.morph`, valueSize, options.copyFloatData === true);
626
- const fill = component.fill === undefined ? undefined : parseVectorFill(component.fill, `${path}.fill`, options.copyFloatData === true);
627
- const stroke = component.stroke === undefined ? undefined : parseVectorStroke(component.stroke, `${path}.stroke`, options.copyFloatData === true);
628
- const modifiers = component.modifiers === undefined
629
- ? undefined
630
- : array(component.modifiers, `${path}.modifiers`).map((modifier, index) => (
631
- parseVectorModifier(modifier, `${path}.modifiers[${index}]`, options.copyFloatData === true)
632
- ));
633
- if (modifiers && (modifiers.length < 1 || modifiers.length > 8)) fail('Vector shape modifiers must contain 1–8 entries.', `${path}.modifiers`);
634
- if (!fill && !stroke) fail('Vector shape requires a fill or stroke paint.', path);
635
- countBudget('path', values.length + (morph?.values.length ?? 0));
636
- return Object.freeze({
637
- type,
638
- commands,
639
- values,
640
- ...(morph ? { morph } : {}),
641
- ...(component.morphRelative === true ? { morphRelative: true } : {}),
642
- ...(fill ? { fill } : {}),
643
- ...(stroke ? { stroke } : {}),
644
- ...(modifiers ? { modifiers: Object.freeze(modifiers) } : {}),
645
- fillRule: component.fillRule === undefined ? 'nonzero' : literal(component.fillRule, ['nonzero', 'evenodd'] as const, `${path}.fillRule`),
646
- tolerance: component.tolerance === undefined ? 0.35 : positiveNumber(component.tolerance, `${path}.tolerance`),
647
- });
648
- }
649
- validateExtensionId(type);
650
- const handler = options.extensions?.get(extensionIdFromComponentType(type)!);
651
- handler?.validateComponent?.(component, extensionContext(type, path));
652
- return Object.freeze({ ...component, type });
653
- }
654
-
655
- function parseTextDocuments(value: unknown, path: string) {
656
- const documents = array(value, path);
657
- if (documents.length < 1 || documents.length > 128) fail('Text documents must contain 1–128 keyframes.', path);
658
- let previousTime = -1;
659
- return Object.freeze(documents.map((value, index) => {
660
- const documentPath = `${path}[${index}]`;
661
- const document = record(value, documentPath);
662
- const time = nonNegativeNumber(document.time, `${documentPath}.time`);
663
- if (time <= previousTime) fail('Text document times must be strictly increasing.', `${documentPath}.time`);
664
- previousTime = time;
665
- if (typeof document.text !== 'string') fail('Expected text to be a string.', `${documentPath}.text`);
666
- return Object.freeze({
667
- time,
668
- text: document.text,
669
- ...(document.fontFamily === undefined ? {} : { fontFamily: nonEmptyString(document.fontFamily, `${documentPath}.fontFamily`) }),
670
- ...(document.fontSize === undefined ? {} : { fontSize: positiveNumber(document.fontSize, `${documentPath}.fontSize`) }),
671
- ...(document.fontWeight === undefined ? {} : { fontWeight: fontWeight(document.fontWeight, `${documentPath}.fontWeight`) }),
672
- ...(document.fontStyle === undefined ? {} : { fontStyle: literal(document.fontStyle, ['normal', 'italic'] as const, `${documentPath}.fontStyle`) }),
673
- ...(document.fontResource === undefined ? {} : { fontResource: nonEmptyString(document.fontResource, `${documentPath}.fontResource`) }),
674
- ...(document.lineHeight === undefined ? {} : { lineHeight: positiveNumber(document.lineHeight, `${documentPath}.lineHeight`) }),
675
- ...(document.tracking === undefined ? {} : { tracking: finiteNumber(document.tracking, `${documentPath}.tracking`) }),
676
- ...(document.textAlign === undefined ? {} : { textAlign: literal(document.textAlign, ['left', 'center', 'right'] as const, `${documentPath}.textAlign`) }),
677
- ...(document.color === undefined ? {} : { color: color(document.color, `${documentPath}.color`) }),
678
- });
679
- }));
680
- }
681
-
682
- function parseTextAnimators(value: unknown, path: string, copy: boolean) {
683
- const animators = array(value, path);
684
- if (animators.length < 1 || animators.length > 16) fail('Text animators must contain 1–16 entries.', path);
685
- return Object.freeze(animators.map((value, index) => {
686
- const animatorPath = `${path}[${index}]`;
687
- const animator = record(value, animatorPath);
688
- const selectorPath = `${animatorPath}.selector`;
689
- const selector = record(animator.selector, selectorPath);
690
- const amount = selector.amount === undefined ? undefined : finiteNumber(selector.amount, `${selectorPath}.amount`);
691
- if (amount !== undefined && (amount < -1 || amount > 1)) fail('Text selector amount must be in [-1, 1].', `${selectorPath}.amount`);
692
- return Object.freeze({
693
- selector: Object.freeze({
694
- start: finiteNumber(selector.start, `${selectorPath}.start`),
695
- end: finiteNumber(selector.end, `${selectorPath}.end`),
696
- ...(selector.offset === undefined ? {} : { offset: finiteNumber(selector.offset, `${selectorPath}.offset`) }),
697
- ...(selector.units === undefined ? {} : { units: literal(selector.units, ['percent', 'index'] as const, `${selectorPath}.units`) }),
698
- ...(amount === undefined ? {} : { amount }),
699
- ...(selector.shape === undefined ? {} : { shape: literal(selector.shape, TEXT_SELECTOR_SHAPES, `${selectorPath}.shape`) }),
700
- ...(selector.basedOn === undefined ? {} : { basedOn: literal(selector.basedOn, TEXT_SELECTOR_BASES, `${selectorPath}.basedOn`) }),
701
- ...(selector.easing === undefined ? {} : { easing: color(selector.easing, `${selectorPath}.easing`) }),
702
- ...(selector.smoothness === undefined ? {} : { smoothness: unitNumber(selector.smoothness, `${selectorPath}.smoothness`) }),
703
- ...(selector.randomSeed === undefined ? {} : { randomSeed: boundedInteger(selector.randomSeed, 0, 0xffffffff, `${selectorPath}.randomSeed`) }),
704
- ...parseVectorTrackField(selector, 'startTrack', selectorPath, 1, copy),
705
- ...parseVectorTrackField(selector, 'endTrack', selectorPath, 1, copy),
706
- ...parseVectorTrackField(selector, 'offsetTrack', selectorPath, 1, copy),
707
- ...parseVectorTrackField(selector, 'amountTrack', selectorPath, 1, copy),
708
- }),
709
- ...(animator.position === undefined ? {} : { position: vec2(animator.position, `${animatorPath}.position`) }),
710
- ...(animator.scale === undefined ? {} : { scale: vec2(animator.scale, `${animatorPath}.scale`) }),
711
- ...(animator.rotation === undefined ? {} : { rotation: finiteNumber(animator.rotation, `${animatorPath}.rotation`) }),
712
- ...(animator.opacity === undefined ? {} : { opacity: unitNumber(animator.opacity, `${animatorPath}.opacity`) }),
713
- ...(animator.fillColor === undefined ? {} : { fillColor: color(animator.fillColor, `${animatorPath}.fillColor`) }),
714
- ...(animator.tracking === undefined ? {} : { tracking: finiteNumber(animator.tracking, `${animatorPath}.tracking`) }),
715
- ...parseVectorTrackField(animator, 'positionTrack', animatorPath, 2, copy),
716
- ...parseVectorTrackField(animator, 'scaleTrack', animatorPath, 2, copy),
717
- ...parseVectorTrackField(animator, 'rotationTrack', animatorPath, 1, copy),
718
- ...parseVectorTrackField(animator, 'opacityTrack', animatorPath, 1, copy),
719
- ...parseVectorTrackField(animator, 'fillColorTrack', animatorPath, 4, copy),
720
- ...parseVectorTrackField(animator, 'trackingTrack', animatorPath, 1, copy),
721
- });
722
- }));
723
- }
724
-
725
- function parseLayerEffects(value: unknown, path: string, copy: boolean): readonly AnimationLayerEffect[] {
726
- const effects = array(value, path);
727
- if (effects.length < 1 || effects.length > 8) fail('Layer effects must contain 1–8 ordered entries.', path);
728
- return Object.freeze(effects.map((value, index) => {
729
- const effectPath = `${path}[${index}]`;
730
- const effect = record(value, effectPath);
731
- const kind = literal(effect.kind, ['tint', 'fill', 'opacity', 'color-matrix', 'blur', 'drop-shadow'] as const, `${effectPath}.kind`);
732
- if (kind === 'tint') return Object.freeze({
733
- kind,
734
- black: unitVec3(effect.black, `${effectPath}.black`),
735
- white: unitVec3(effect.white, `${effectPath}.white`),
736
- amount: unitNumber(effect.amount, `${effectPath}.amount`),
737
- ...parseVectorTrackField(effect, 'blackTrack', effectPath, 3, copy),
738
- ...parseVectorTrackField(effect, 'whiteTrack', effectPath, 3, copy),
739
- ...parseVectorTrackField(effect, 'amountTrack', effectPath, 1, copy),
740
- });
741
- if (kind === 'fill') return Object.freeze({
742
- kind,
743
- color: color(effect.color, `${effectPath}.color`),
744
- ...(effect.opacity === undefined ? {} : { opacity: unitNumber(effect.opacity, `${effectPath}.opacity`) }),
745
- ...parseVectorTrackField(effect, 'colorTrack', effectPath, 4, copy),
746
- ...parseVectorTrackField(effect, 'opacityTrack', effectPath, 1, copy),
747
- });
748
- if (kind === 'opacity') return Object.freeze({
749
- kind,
750
- opacity: unitNumber(effect.opacity, `${effectPath}.opacity`),
751
- ...parseVectorTrackField(effect, 'opacityTrack', effectPath, 1, copy),
752
- });
753
- if (kind === 'color-matrix') {
754
- const matrix = floatArray(effect.matrix, `${effectPath}.matrix`, copy);
755
- if (matrix.length !== 20) fail('Color matrix must contain exactly 20 values.', `${effectPath}.matrix`);
756
- return Object.freeze({
757
- kind, matrix,
758
- ...parseVectorTrackField(effect, 'matrixTrack', effectPath, 20, copy),
759
- });
760
- }
761
- if (kind === 'blur') return Object.freeze({
762
- kind,
763
- radius: nonNegativeVec2(effect.radius, `${effectPath}.radius`),
764
- ...parseVectorTrackField(effect, 'radiusTrack', effectPath, 2, copy),
765
- });
766
- return Object.freeze({
767
- kind,
768
- color: color(effect.color, `${effectPath}.color`),
769
- opacity: unitNumber(effect.opacity, `${effectPath}.opacity`),
770
- offset: vec2(effect.offset, `${effectPath}.offset`),
771
- blur: nonNegativeNumber(effect.blur, `${effectPath}.blur`),
772
- ...parseVectorTrackField(effect, 'colorTrack', effectPath, 4, copy),
773
- ...parseVectorTrackField(effect, 'opacityTrack', effectPath, 1, copy),
774
- ...parseVectorTrackField(effect, 'offsetTrack', effectPath, 2, copy),
775
- ...parseVectorTrackField(effect, 'blurTrack', effectPath, 1, copy),
776
- });
777
- }));
778
- }
779
-
780
- /** @internal Compact-binary effect decoder entry point. */
781
- export function parseBinaryEffectsValue(
782
- value: unknown,
783
- path: string,
784
- copy: boolean,
785
- ): readonly AnimationLayerEffect[] {
786
- return parseLayerEffects(value, path, copy);
787
- }
788
-
789
- function parseVectorModifier(value: unknown, path: string, copy: boolean) {
790
- const modifier = record(value, path);
791
- const kind = literal(modifier.kind, ['trim-path', 'round-corners'] as const, `${path}.kind`);
792
- if (kind === 'round-corners') return Object.freeze({
793
- kind,
794
- radius: nonNegativeNumber(modifier.radius, `${path}.radius`),
795
- ...parseVectorTrackField(modifier, 'radiusTrack', path, 1, copy),
796
- });
797
- return Object.freeze({
798
- kind,
799
- start: finiteNumber(modifier.start, `${path}.start`),
800
- end: finiteNumber(modifier.end, `${path}.end`),
801
- offset: finiteNumber(modifier.offset, `${path}.offset`),
802
- mode: literal(modifier.mode, ['simultaneous', 'individual'] as const, `${path}.mode`),
803
- ...parseVectorTrackField(modifier, 'startTrack', path, 1, copy),
804
- ...parseVectorTrackField(modifier, 'endTrack', path, 1, copy),
805
- ...parseVectorTrackField(modifier, 'offsetTrack', path, 1, copy),
806
- });
807
- }
808
-
809
- function parseVectorTrackField(
810
- owner: Record<string, unknown>,
811
- key: string,
812
- path: string,
813
- valueSize: number,
814
- copy: boolean,
815
- ): Record<string, AnimationVectorValueTrack> {
816
- const value = owner[key];
817
- return value === undefined ? {} : { [key]: parseVectorValueTrack(value, `${path}.${key}`, valueSize, copy) };
818
- }
819
-
820
- function parseVectorValueTrack(
821
- value: unknown,
822
- path: string,
823
- expectedValueSize: number | undefined,
824
- copy: boolean,
825
- ): AnimationVectorValueTrack {
826
- const track = record(value, path);
827
- const valueSize = safeInteger(track.valueSize, `${path}.valueSize`);
828
- if (valueSize < 1 || valueSize > 4096 || (expectedValueSize !== undefined && valueSize !== expectedValueSize)) {
829
- fail(`Vector track valueSize must be ${expectedValueSize ?? 'between 1 and 4096'}.`, `${path}.valueSize`);
830
- }
831
- const times = floatArray(track.times, `${path}.times`, copy);
832
- const values = floatArray(track.values, `${path}.values`, copy);
833
- if (times.length < 1 || values.length !== times.length * valueSize) fail('Vector track values must contain valueSize numbers for every keyframe.', `${path}.values`);
834
- for (let index = 0; index < times.length; index++) {
835
- if (times[index]! < 0 || (index > 0 && times[index]! <= times[index - 1]!)) fail('Vector track times must be non-negative and strictly increasing.', `${path}.times`);
836
- }
837
- const interpolation = literal(track.interpolation, ['step', 'linear', 'cubic-bezier'] as const, `${path}.interpolation`);
838
- const easings = track.easings === undefined ? undefined : floatArray(track.easings, `${path}.easings`, copy);
839
- if (interpolation === 'cubic-bezier' && easings?.length !== Math.max(0, times.length - 1) * 4) fail('Cubic vector track easing data must contain four numbers per segment.', `${path}.easings`);
840
- if (interpolation !== 'cubic-bezier' && easings !== undefined) fail('Vector track easings require cubic-bezier interpolation.', `${path}.easings`);
841
- return Object.freeze({ times, values, valueSize, interpolation, ...(easings ? { easings } : {}) });
842
- }
843
-
844
- function parseVectorFill(value: unknown, path: string, copy: boolean) {
845
- const fill = record(value, path);
846
- const kind = literal(fill.kind, ['solid', 'linear-gradient', 'radial-gradient'] as const, `${path}.kind`);
847
- const opacityTrack = fill.opacityTrack === undefined ? undefined : parseVectorValueTrack(fill.opacityTrack, `${path}.opacityTrack`, 1, copy);
848
- if (kind === 'solid') {
849
- return Object.freeze({
850
- kind,
851
- color: color(fill.color, `${path}.color`),
852
- ...(fill.opacity === undefined ? {} : { opacity: unitNumber(fill.opacity, `${path}.opacity`) }),
853
- ...parseVectorTrackField(fill, 'colorTrack', path, 4, copy),
854
- ...(opacityTrack ? { opacityTrack } : {}),
855
- });
856
- }
857
- const stops = floatArray(fill.stops, `${path}.stops`, copy);
858
- if (stops.length < 10 || stops.length > 40 || stops.length % 5 !== 0) fail('Gradient stops must contain 2–8 offset,r,g,b,a tuples.', `${path}.stops`);
859
- let previousOffset = -Infinity;
860
- for (let offset = 0; offset < stops.length; offset += 5) {
861
- if (stops[offset]! < previousOffset || stops[offset]! < 0 || stops[offset]! > 1) fail('Gradient stop offsets must be ordered in [0, 1].', `${path}.stops[${offset}]`);
862
- previousOffset = stops[offset]!;
863
- for (let channel = 1; channel < 5; channel++) if (stops[offset + channel]! < 0 || stops[offset + channel]! > 1) fail('Gradient stop channels must be in [0, 1].', `${path}.stops[${offset + channel}]`);
864
- }
865
- return Object.freeze({
866
- kind,
867
- start: vec2(fill.start, `${path}.start`),
868
- end: vec2(fill.end, `${path}.end`),
869
- stops,
870
- ...(fill.opacity === undefined ? {} : { opacity: unitNumber(fill.opacity, `${path}.opacity`) }),
871
- ...parseVectorTrackField(fill, 'startTrack', path, 2, copy),
872
- ...parseVectorTrackField(fill, 'endTrack', path, 2, copy),
873
- ...parseVectorTrackField(fill, 'stopsTrack', path, stops.length, copy),
874
- ...(opacityTrack ? { opacityTrack } : {}),
875
- });
876
- }
877
-
878
- function parseVectorStroke(value: unknown, path: string, copy: boolean) {
879
- const stroke = record(value, path);
880
- const dash = stroke.dash === undefined ? undefined : floatArray(stroke.dash, `${path}.dash`, copy);
881
- if (dash && (dash.length < 1 || dash.length > 32 || Array.from(dash).some(value => value < 0))) fail('Stroke dash values must contain 1–32 non-negative numbers.', `${path}.dash`);
882
- const gradient = stroke.gradient === undefined ? undefined : parseVectorFill(stroke.gradient, `${path}.gradient`, copy);
883
- if (gradient?.kind === 'solid') fail('Stroke gradient must be linear-gradient or radial-gradient.', `${path}.gradient.kind`);
884
- return Object.freeze({
885
- color: color(stroke.color, `${path}.color`),
886
- width: positiveNumber(stroke.width, `${path}.width`),
887
- ...(stroke.opacity === undefined ? {} : { opacity: unitNumber(stroke.opacity, `${path}.opacity`) }),
888
- lineCap: literal(stroke.lineCap, ['butt', 'round', 'square'] as const, `${path}.lineCap`),
889
- lineJoin: literal(stroke.lineJoin, ['miter', 'round', 'bevel'] as const, `${path}.lineJoin`),
890
- miterLimit: positiveNumber(stroke.miterLimit, `${path}.miterLimit`),
891
- ...(gradient ? { gradient } : {}),
892
- ...(dash ? { dash } : {}),
893
- ...(stroke.dashOffset === undefined ? {} : { dashOffset: finiteNumber(stroke.dashOffset, `${path}.dashOffset`) }),
894
- ...parseVectorTrackField(stroke, 'colorTrack', path, 4, copy),
895
- ...parseVectorTrackField(stroke, 'opacityTrack', path, 1, copy),
896
- ...parseVectorTrackField(stroke, 'widthTrack', path, 1, copy),
897
- ...parseVectorTrackField(stroke, 'dashOffsetTrack', path, 1, copy),
898
- });
899
- }
900
-
901
- /** @internal Compact-binary component decoder entry point. */
902
- export function parseBinaryComponentValue(
903
- value: unknown,
904
- path: string,
905
- options: AnimationParseOptions,
906
- countBudget: (kind: 'path' | 'text' | 'particle', count: number) => void,
907
- ): AnimationComponent {
908
- return parseComponent(value, path, options, countBudget);
909
- }
910
-
911
- function parseComposite(value: unknown, path: string, copy: boolean) {
912
- const composite = record(value, path);
913
- if (composite.layers !== undefined) {
914
- const values = array(composite.layers, `${path}.layers`);
915
- if (values.length < 1 || values.length > 8) fail('Composite stacks must contain between 1 and 8 layers.', `${path}.layers`);
916
- return Object.freeze({
917
- layers: Object.freeze(values.map((layer, index) => parseCompositeLayer(layer, `${path}.layers[${index}]`, copy))),
918
- });
919
- }
920
- return parseCompositeLayer(composite, path, copy);
921
- }
922
-
923
- function parseCompositeLayer(value: unknown, path: string, copy: boolean) {
924
- const composite = record(value, path);
925
- return Object.freeze({
926
- kind: literal(composite.kind, ['mask', 'matte'] as const, `${path}.kind`),
927
- source: nonEmptyString(composite.source, `${path}.source`),
928
- mode: literal(composite.mode, ['alpha', 'alpha-inverted', 'luma', 'luma-inverted'] as const, `${path}.mode`),
929
- ...(composite.operation === undefined ? {} : {
930
- operation: literal(composite.operation, ['add', 'subtract', 'intersect', 'difference'] as const, `${path}.operation`),
931
- }),
932
- ...(composite.feather === undefined ? {} : { feather: nonNegativeVec2(composite.feather, `${path}.feather`) }),
933
- ...(composite.expansion === undefined ? {} : { expansion: finiteNumber(composite.expansion, `${path}.expansion`) }),
934
- ...parseVectorTrackField(composite, 'expansionTrack', path, 1, copy),
935
- });
936
- }
937
-
938
- /** @internal Compact-binary structural decoder entry point. */
939
- export function parseBinaryTrackValue(value: unknown, index: number, nodeIds: Set<string>, duration: number, copy: boolean): ParsedAnimationTrack {
940
- const path = `$.tracks[${index}]`;
941
- const track = record(value, path);
942
- const node = nonEmptyString(track.node, `${path}.node`);
943
- if (!nodeIds.has(node)) fail(`Track references missing node "${node}".`, `${path}.node`);
944
- const property = literal(track.property, ['position', 'rotation', 'scale', 'opacity'] as const, `${path}.property`);
945
- const interpolation = literal(track.interpolation, ['step', 'linear', 'cubic-bezier'] as const, `${path}.interpolation`);
946
- const times = floatArray(track.times, `${path}.times`, copy);
947
- if (times.length < 1) fail('Track must contain at least one keyframe.', `${path}.times`);
948
- let previous = -Infinity;
949
- // Track pools are Float32-backed. A source key exactly at a non-representable
950
- // composition duration may round above the Float64 duration, but no later
951
- // representable Float32 value is part of that boundary.
952
- const maximumTrackTime = Math.max(duration, Math.fround(duration));
953
- for (let i = 0; i < times.length; i++) {
954
- const current = requiredFloat(times, i, `${path}.times`);
955
- if (current < 0 || current <= previous) fail('Track times must be finite, non-negative and strictly increasing.', `${path}.times[${i}]`);
956
- if (current > maximumTrackTime) fail('Track time exceeds the composition duration.', `${path}.times[${i}]`);
957
- previous = current;
958
- }
959
- const valueSize = trackValueSize(property);
960
- const values = floatArray(track.values, `${path}.values`, copy);
961
- if (values.length !== times.length * valueSize) {
962
- fail(`Track values length must equal keyframe count × ${valueSize}.`, `${path}.values`);
963
- }
964
- const easings = track.easings === undefined ? undefined : floatArray(track.easings, `${path}.easings`, copy);
965
- if (interpolation === 'cubic-bezier') {
966
- const expected = Math.max(0, times.length - 1) * 4;
967
- if (!easings || easings.length !== expected) fail(`Cubic track easings length must be ${expected}.`, `${path}.easings`);
968
- for (let i = 0; i < easings.length; i += 4) {
969
- if (requiredFloat(easings, i, `${path}.easings`) < 0 || requiredFloat(easings, i, `${path}.easings`) > 1
970
- || requiredFloat(easings, i + 2, `${path}.easings`) < 0 || requiredFloat(easings, i + 2, `${path}.easings`) > 1) {
971
- fail('Cubic easing x control points must be in [0, 1].', `${path}.easings[${i}]`);
972
- }
973
- }
974
- } else if (easings) {
975
- fail('easings are only valid for cubic-bezier tracks.', `${path}.easings`);
976
- }
977
- const spatialTangents = track.spatialTangents === undefined
978
- ? undefined
979
- : floatArray(track.spatialTangents, `${path}.spatialTangents`, copy);
980
- if (spatialTangents) {
981
- const expected = Math.max(0, times.length - 1) * 4;
982
- if (property !== 'position' || interpolation === 'step' || spatialTangents.length !== expected) {
983
- fail(`spatialTangents require position, non-step and ${expected} values.`, `${path}.spatialTangents`);
984
- }
985
- }
986
- return Object.freeze({
987
- node, property, interpolation, times, values, valueSize,
988
- ...(easings ? { easings } : {}),
989
- ...(spatialTangents ? { spatialTangents } : {}),
990
- });
991
- }
992
-
993
- /** @internal Compact-binary structural decoder entry point. */
994
- export function parseBinaryResourceValue(value: unknown, index: number, ids: Set<string>): Readonly<AnimationResource> {
995
- const path = `$.resources[${index}]`;
996
- const resource = record(value, path);
997
- const id = nonEmptyString(resource.id, `${path}.id`);
998
- if (ids.has(id)) fail(`Duplicate resource id "${id}".`, `${path}.id`);
999
- ids.add(id);
1000
- const type = literal(resource.type, ['image', 'audio', 'binary'] as const, `${path}.type`);
1001
- return Object.freeze({
1002
- id,
1003
- type,
1004
- uri: nonEmptyString(resource.uri, `${path}.uri`),
1005
- ...(resource.mimeType !== undefined ? { mimeType: nonEmptyString(resource.mimeType, `${path}.mimeType`) } : {}),
1006
- ...(resource.integrity !== undefined ? { integrity: nonEmptyString(resource.integrity, `${path}.integrity`) } : {}),
1007
- ...(type === 'image' && resource.width !== undefined ? { width: positiveNumber(resource.width, `${path}.width`) } : {}),
1008
- ...(type === 'image' && resource.height !== undefined ? { height: positiveNumber(resource.height, `${path}.height`) } : {}),
1009
- ...(type === 'image' && resource.colorSpace !== undefined
1010
- ? { colorSpace: literal(resource.colorSpace, ['srgb', 'linear'] as const, `${path}.colorSpace`) }
1011
- : {}),
1012
- });
1013
- }
1014
-
1015
- function validateHierarchy(nodes: readonly Readonly<AnimationNode>[], ids: Set<string>): void {
1016
- const indexById = new Map(nodes.map((node, index) => [node.id, index]));
1017
- const states = new Uint8Array(nodes.length);
1018
- for (let index = 0; index < nodes.length; index++) {
1019
- const node = nodes[index]!;
1020
- if (node.parent && !ids.has(node.parent)) fail(`Node references missing parent "${node.parent}".`, `$.nodes[${index}].parent`);
1021
- if (states[index] !== 0) continue;
1022
- let cursor: number | undefined = index;
1023
- while (cursor !== undefined && states[cursor] === 0) {
1024
- states[cursor] = 1;
1025
- const parentId: string | undefined = nodes[cursor]!.parent;
1026
- cursor = parentId === undefined ? undefined : indexById.get(parentId);
1027
- }
1028
- if (cursor !== undefined && states[cursor] === 1) {
1029
- fail('Node hierarchy contains a cycle.', `$.nodes[${index}].parent`);
1030
- }
1031
- cursor = index;
1032
- while (cursor !== undefined && states[cursor] === 1) {
1033
- states[cursor] = 2;
1034
- const parentId: string | undefined = nodes[cursor]!.parent;
1035
- cursor = parentId === undefined ? undefined : indexById.get(parentId);
1036
- }
1037
- }
1038
- }
1039
-
1040
- function validateComposites(nodes: readonly Readonly<AnimationNode>[], ids: Set<string>): void {
1041
- const indexById = new Map(nodes.map((node, index) => [node.id, index]));
1042
- for (let index = 0; index < nodes.length; index++) {
1043
- const node = nodes[index]!;
1044
- const layers = compositeLayers(node.composite);
1045
- for (let layerIndex = 0; layerIndex < layers.length; layerIndex++) {
1046
- const source = layers[layerIndex]!.source;
1047
- const sourcePath = compositeSourcePath(index, node.composite!, layerIndex);
1048
- if (!ids.has(source)) fail(`Composite references missing source node "${source}".`, sourcePath);
1049
- if (source === node.id) fail('Composite source cannot reference its own node.', sourcePath);
1050
- }
1051
- }
1052
- const states = new Uint8Array(nodes.length);
1053
- const visit = (index: number): void => {
1054
- if (states[index] === 2) return;
1055
- if (states[index] === 1) fail('Composite graph contains a cycle.', `$.nodes[${index}].composite`);
1056
- states[index] = 1;
1057
- for (const layer of compositeLayers(nodes[index]!.composite)) visit(indexById.get(layer.source)!);
1058
- states[index] = 2;
1059
- };
1060
- for (let index = 0; index < nodes.length; index++) visit(index);
1061
- }
1062
-
1063
- function compositeLayers(composite: Readonly<AnimationNode>['composite']): readonly AnimationCompositeLayer[] {
1064
- if (!composite) return [];
1065
- return 'layers' in composite ? composite.layers : [composite];
1066
- }
1067
-
1068
- function compositeSourcePath(index: number, composite: NonNullable<Readonly<AnimationNode>['composite']>, layerIndex: number): string {
1069
- return 'layers' in composite
1070
- ? `$.nodes[${index}].composite.layers[${layerIndex}].source`
1071
- : `$.nodes[${index}].composite.source`;
1072
- }
1073
-
1074
- function extensionContext(extension: string, path: string) {
1075
- return {
1076
- extension,
1077
- path,
1078
- fail(message: string, overridePath = path): never { return fail(message, overridePath); },
1079
- };
1080
- }
1081
-
1082
- function trackValueSize(property: AnimationTrackProperty): 1 | 2 {
1083
- return property === 'position' || property === 'scale' ? 2 : 1;
1084
- }
1085
-
1086
- function floatArray(value: unknown, path: string, copy: boolean): Float32Array {
1087
- if (value instanceof Float32Array) {
1088
- for (let i = 0; i < value.length; i++) requiredFloat(value, i, path);
1089
- return copy ? new Float32Array(value) : value;
1090
- }
1091
- const values = array(value, path);
1092
- const result = new Float32Array(values.length);
1093
- for (let i = 0; i < values.length; i++) result[i] = finiteNumber(values[i], `${path}[${i}]`);
1094
- return result;
1095
- }
1096
-
1097
- function pathValueCount(commands: string): number {
1098
- let count = 0;
1099
- for (const command of commands) count += command === 'M' || command === 'L' ? 2 : command === 'Q' ? 4 : command === 'C' ? 6 : 0;
1100
- return count;
1101
- }
1102
-
1103
- function validatePathTopology(commands: string, path: string, requireClosed = true): void {
1104
- let open = false;
1105
- let pointCount = 0;
1106
- for (let index = 0; index < commands.length; index++) {
1107
- const command = commands[index]!;
1108
- if (command === 'M') {
1109
- if (open && requireClosed) fail('Each filled subpath must be closed with Z before the next M.', `${path}[${index}]`);
1110
- open = true;
1111
- pointCount = 1;
1112
- } else if (command === 'Z') {
1113
- if (!open || pointCount < (requireClosed ? 3 : 2)) fail(`Each ${requireClosed ? 'filled ' : ''}subpath must contain at least ${requireClosed ? 'three' : 'two'} points before Z.`, `${path}[${index}]`);
1114
- open = false;
1115
- pointCount = 0;
1116
- } else {
1117
- if (!open) fail('L, Q and C commands must follow M inside a subpath.', `${path}[${index}]`);
1118
- pointCount++;
1119
- }
1120
- }
1121
- if (open && requireClosed) fail('Each filled subpath must end with Z.', path);
1122
- }
1123
-
1124
- function stringList(value: unknown, path: string): string[] {
1125
- const values = array(value, path);
1126
- const result: string[] = [];
1127
- const seen = new Set<string>();
1128
- for (let i = 0; i < values.length; i++) {
1129
- const item = nonEmptyString(values[i], `${path}[${i}]`);
1130
- if (seen.has(item)) fail(`Duplicate value "${item}".`, `${path}[${i}]`);
1131
- seen.add(item);
1132
- result.push(item);
1133
- }
1134
- return result;
1135
- }
1136
-
1137
- function record(value: unknown, path: string): Record<string, unknown> {
1138
- if (!value || typeof value !== 'object' || Array.isArray(value) || ArrayBuffer.isView(value)) fail('Expected an object.', path);
1139
- return value as Record<string, unknown>;
1140
- }
1141
-
1142
- function array(value: unknown, path: string): unknown[] {
1143
- if (!Array.isArray(value)) fail('Expected an array.', path);
1144
- return value;
1145
- }
1146
-
1147
- function vec2(value: unknown, path: string): readonly [number, number] {
1148
- const values = array(value, path);
1149
- if (values.length !== 2) fail('Expected exactly two numbers.', path);
1150
- return Object.freeze([finiteNumber(values[0], `${path}[0]`), finiteNumber(values[1], `${path}[1]`)] as [number, number]);
1151
- }
1152
-
1153
- function positiveVec2(value: unknown, path: string): readonly [number, number] {
1154
- const values = vec2(value, path);
1155
- if (values[0] <= 0 || values[1] <= 0) fail('Expected two positive numbers.', path);
1156
- return values;
1157
- }
1158
-
1159
- function nonNegativeVec2(value: unknown, path: string): readonly [number, number] {
1160
- const values = vec2(value, path);
1161
- if (values[0] < 0 || values[1] < 0) fail('Expected two non-negative numbers.', path);
1162
- return values;
1163
- }
1164
-
1165
- function numericRange(value: unknown, path: string, minimum = -Infinity): readonly [number, number] {
1166
- const values = vec2(value, path);
1167
- if (values[0] < minimum || values[1] < values[0]) fail(`Expected an ascending numeric range above ${minimum}.`, path);
1168
- return values;
1169
- }
1170
-
1171
- function color(value: unknown, path: string): readonly [number, number, number, number] {
1172
- const values = array(value, path);
1173
- if (values.length !== 4) fail('Expected RGBA with four numbers.', path);
1174
- return Object.freeze([
1175
- unitNumber(values[0], `${path}[0]`), unitNumber(values[1], `${path}[1]`),
1176
- unitNumber(values[2], `${path}[2]`), unitNumber(values[3], `${path}[3]`),
1177
- ] as [number, number, number, number]);
1178
- }
1179
-
1180
- function unitVec3(value: unknown, path: string): readonly [number, number, number] {
1181
- const values = array(value, path);
1182
- if (values.length !== 3) fail('Expected RGB with three numbers.', path);
1183
- return Object.freeze([
1184
- unitNumber(values[0], `${path}[0]`),
1185
- unitNumber(values[1], `${path}[1]`),
1186
- unitNumber(values[2], `${path}[2]`),
1187
- ] as [number, number, number]);
1188
- }
1189
-
1190
- function uvRect(value: unknown, path: string): readonly [number, number, number, number] {
1191
- const values = array(value, path);
1192
- if (values.length !== 4) fail('Expected normalized UV rectangle with four numbers.', path);
1193
- const x = unitNumber(values[0], `${path}[0]`);
1194
- const y = unitNumber(values[1], `${path}[1]`);
1195
- const width = positiveNumber(values[2], `${path}[2]`);
1196
- const height = positiveNumber(values[3], `${path}[3]`);
1197
- if (x + width > 1 + 1e-6 || y + height > 1 + 1e-6) fail('UV rectangle must fit inside [0, 1].', path);
1198
- return Object.freeze([x, y, width, height] as [number, number, number, number]);
1199
- }
1200
-
1201
- function validateUvRectTrack(track: AnimationVectorValueTrack, path: string): void {
1202
- for (let frame = 0; frame < track.times.length; frame++) {
1203
- const offset = frame * 4;
1204
- uvRect([
1205
- track.values[offset],
1206
- track.values[offset + 1],
1207
- track.values[offset + 2],
1208
- track.values[offset + 3],
1209
- ], `${path}.values[${offset}..${offset + 3}]`);
1210
- }
1211
- }
1212
-
1213
- function finiteNumber(value: unknown, path: string): number {
1214
- if (typeof value !== 'number' || !Number.isFinite(value)) fail('Expected a finite number.', path);
1215
- return value;
1216
- }
1217
-
1218
- function positiveNumber(value: unknown, path: string): number {
1219
- const result = finiteNumber(value, path);
1220
- if (result <= 0) fail('Expected a positive number.', path);
1221
- return result;
1222
- }
1223
-
1224
- function nonNegativeNumber(value: unknown, path: string): number {
1225
- const result = finiteNumber(value, path);
1226
- if (result < 0) fail('Expected a non-negative number.', path);
1227
- return result;
1228
- }
1229
-
1230
- function unitNumber(value: unknown, path: string): number {
1231
- const result = finiteNumber(value, path);
1232
- if (result < 0 || result > 1) fail('Expected a number in [0, 1].', path);
1233
- return result;
1234
- }
1235
-
1236
- function nonEmptyString(value: unknown, path: string): string {
1237
- if (typeof value !== 'string' || !value.trim()) fail('Expected a non-empty string.', path);
1238
- return value;
1239
- }
1240
-
1241
- function fontWeight(value: unknown, path: string): string | number {
1242
- if (typeof value === 'string' && value.trim()) return value;
1243
- if (typeof value === 'number' && Number.isFinite(value) && value >= 1 && value <= 1000) return value;
1244
- fail('Expected a non-empty font weight string or a number in [1, 1000].', path);
1245
- }
1246
-
1247
- function booleanValue(value: unknown, path: string): boolean {
1248
- if (typeof value !== 'boolean') fail('Expected a boolean.', path);
1249
- return value;
1250
- }
1251
-
1252
- function safeInteger(value: unknown, path: string): number {
1253
- if (typeof value !== 'number' || !Number.isSafeInteger(value)) fail('Expected a safe integer.', path);
1254
- return value;
1255
- }
1256
-
1257
- function boundedInteger(value: unknown, minimum: number, maximum: number, path: string): number {
1258
- const result = safeInteger(value, path);
1259
- if (result < minimum || result > maximum) fail(`Expected an integer in [${minimum}, ${maximum}].`, path);
1260
- return result;
1261
- }
1262
-
1263
- function literal<const T extends readonly string[]>(value: unknown, values: T, path: string): T[number] {
1264
- if (typeof value !== 'string' || !values.includes(value)) fail(`Expected one of: ${values.join(', ')}.`, path);
1265
- return value as T[number];
1266
- }
1267
-
1268
- function requiredFloat(values: Float32Array, index: number, path: string): number {
1269
- const value = values[index];
1270
- if (value === undefined || !Number.isFinite(value)) fail('Expected finite Float32 values.', `${path}[${index}]`);
1271
- return value;
1272
- }
1273
-
1274
- function positiveLimit(value: number | undefined, fallback: number, name: string): number {
1275
- if (value === undefined) return fallback;
1276
- if (!Number.isSafeInteger(value) || value < 1) fail(`${name} must be a positive safe integer.`, '$options');
1277
- return value;
1278
- }
1279
-
1280
- function limit(actual: number, maximum: number, label: string, path: string): void {
1281
- if (actual > maximum) throw new AnimationFormatError('E_ANIMATION_LIMIT_EXCEEDED', `${label} count ${actual} exceeds limit ${maximum}.`, path);
1282
- }
1283
-
1284
- function fail(message: string, path: string): never {
1285
- throw new AnimationFormatError('E_ANIMATION_INVALID_FORMAT', message, path);
1286
- }