skia-motion-runtime 3.0.0 → 3.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.
package/runtime/asset.ts CHANGED
@@ -6,6 +6,7 @@ import { imageSize } from './asset-image';
6
6
  import type { MeshNode, MeshVertex } from './asset-mesh';
7
7
 
8
8
  export const ASSET_SCHEMA = 'skac.asset/1';
9
+ export const ASSET_BUNDLE_SCHEMA = 'skac.bundle/1';
9
10
  export const MAX_ASSET_BYTES = 1024 * 1024;
10
11
  export const MAX_FEATHER = 64;
11
12
 
@@ -18,7 +19,14 @@ export type PathCommand =
18
19
  | readonly [op: 'Q', controlX: Scalar, controlY: Scalar, x: Scalar, y: Scalar]
19
20
  | readonly [op: 'C', control1X: Scalar, control1Y: Scalar, control2X: Scalar, control2Y: Scalar, x: Scalar, y: Scalar]
20
21
  | readonly [op: 'Z'];
21
- type Shade = string | { kind: 'radial'; x: Scalar; y: Scalar; radius: Scalar; colors: readonly [string, string] };
22
+ export type AssetColor = string | { palette: string };
23
+ type Shade = AssetColor | { kind: 'radial'; x: Scalar; y: Scalar; radius: Scalar; colors: readonly [string, string] };
24
+ export type AssetStroke = {
25
+ color: AssetColor; width: Scalar;
26
+ cap?: 'butt' | 'round' | 'square'; join?: 'miter' | 'round' | 'bevel';
27
+ trim?: { start?: Scalar; end?: Scalar };
28
+ dash?: { intervals: readonly number[]; phase?: Scalar };
29
+ };
22
30
 
23
31
  type Group = {
24
32
  kind: 'group'; x?: Scalar; y?: Scalar; scaleX?: Scalar; scaleY?: Scalar; rotation?: Scalar;
@@ -27,10 +35,10 @@ type Group = {
27
35
  points?: Readonly<Record<string, { x: Scalar; y: Scalar }>>;
28
36
  children: readonly AssetNode[];
29
37
  };
30
- type Shape = { fill: Shade; opacity?: Scalar; feather?: Scalar } & (
31
- | { kind: 'ellipse'; x: Scalar; y: Scalar; width: Scalar; height: Scalar }
32
- | { kind: 'roundRect'; x: Scalar; y: Scalar; width: Scalar; height: Scalar; radius: Scalar }
33
- | { kind: 'path'; commands: readonly PathCommand[] }
38
+ type Shape = { opacity?: Scalar; feather?: Scalar } & (
39
+ | { kind: 'ellipse'; x: Scalar; y: Scalar; width: Scalar; height: Scalar; fill: Shade }
40
+ | { kind: 'roundRect'; x: Scalar; y: Scalar; width: Scalar; height: Scalar; radius: Scalar; fill: Shade }
41
+ | { kind: 'path'; commands: readonly PathCommand[]; fill?: Shade; stroke?: AssetStroke }
34
42
  );
35
43
 
36
44
  type ImageNode = {
@@ -38,8 +46,19 @@ type ImageNode = {
38
46
  x: Scalar; y: Scalar; width: Scalar; height: Scalar;
39
47
  };
40
48
 
41
- export type AssetNode = Group | Shape | ImageNode | MeshNode;
42
- export type AssetMarker = { name: string; layer: string; state: string };
49
+ export type BoundText = string | { value: string };
50
+ export type AssetTextNode = {
51
+ kind: 'text'; text: BoundText; x: Scalar; y: Scalar; width: number; fontSize: number; fill: string;
52
+ fonts?: readonly string[]; direction?: 'ltr' | 'rtl'; align?: 'start' | 'center' | 'end'; maxLines?: number;
53
+ };
54
+ export type AssetSemantic = {
55
+ name: string; label: BoundText; role: 'button' | 'image' | 'text' | 'header';
56
+ bounds: readonly [x: number, y: number, width: number, height: number];
57
+ trigger?: string;
58
+ };
59
+
60
+ export type AssetNode = Group | Shape | ImageNode | MeshNode | AssetTextNode;
61
+ export type AssetMarker = { name: string; layer: string; state: string; audio?: string };
43
62
  export type AssetMarkerEvent = AssetMarker & { at: number };
44
63
  export type AssetAttachment = { from: string; to: string; maxDistance: number };
45
64
  export type MotionAsset<M extends Machine = Machine> = {
@@ -48,14 +67,31 @@ export type MotionAsset<M extends Machine = Machine> = {
48
67
  artboard: { width: number; height: number; nodes: readonly AssetNode[] };
49
68
  channels: Readonly<Record<string, number>>;
50
69
  images?: Readonly<Record<string, string>>;
70
+ imageSlots?: Readonly<Record<string, string>>;
71
+ palette?: Readonly<Record<string, string>>;
72
+ fonts?: Readonly<Record<string, string>>;
73
+ fontLicenses?: Readonly<Record<string, string>>;
74
+ audio?: Readonly<Record<string, string>>;
75
+ semantics?: readonly AssetSemantic[];
51
76
  clips: Readonly<Record<string, { ms: number; reducedAt?: number; tracks: Readonly<Record<string, Track>> }>>;
52
77
  machine: M;
53
78
  markers?: readonly AssetMarker[];
54
79
  attachments?: readonly AssetAttachment[];
55
80
  };
81
+ export type MotionAssetFile = MotionAsset | {
82
+ schema: typeof ASSET_BUNDLE_SCHEMA;
83
+ name: string;
84
+ defaultArtboard: string;
85
+ artboards: Readonly<Record<string, MotionAsset>>;
86
+ fonts?: MotionAsset['fonts'];
87
+ fontLicenses?: MotionAsset['fontLicenses'];
88
+ audio?: MotionAsset['audio'];
89
+ };
56
90
 
57
91
  const IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_-]{0,63}$/;
58
92
  const HEX_COLOR = /^#[0-9a-fA-F]{6}([0-9a-fA-F]{2})?$/;
93
+ const FONT_URI = /^data:font\/(ttf|otf);base64,([A-Za-z0-9+/]+={0,2})$/;
94
+ const AUDIO_URI = /^data:audio\/(mpeg|wav|mp4|aac);base64,([A-Za-z0-9+/]+={0,2})$/;
59
95
  const PATH_ARGUMENTS: Record<string, number> = { M: 2, L: 2, Q: 4, C: 6, Z: 0 };
60
96
  const EASES = ['linear', 'in', 'out', 'inOut', 'hold'];
61
97
  const RESERVED_KEYS = new Set([...Object.getOwnPropertyNames(Object.prototype), 'prototype']);
@@ -114,9 +150,71 @@ function checkPath(value: unknown, at: string, channels: Record<string, unknown>
114
150
  type NodeValidation = {
115
151
  channels: Record<string, unknown>;
116
152
  images: Record<string, unknown>;
153
+ imageSlots: Record<string, unknown>;
117
154
  points: Set<string>;
155
+ fonts: Record<string, unknown>;
156
+ values: Record<string, unknown>;
157
+ palette: Record<string, unknown>;
118
158
  };
119
159
 
160
+ function checkColor(value: unknown, at: string, palette: Record<string, unknown>): void {
161
+ if (typeof value === 'string') return color(value, at);
162
+ const name = identifier(record(value, at, ['palette']).palette, `${at}.palette`);
163
+ if (!Object.hasOwn(palette, name)) invalid(at, `unknown palette entry "${name}"`);
164
+ }
165
+
166
+ function checkStroke(value: unknown, at: string, { channels, palette }: NodeValidation): void {
167
+ const stroke = record(value, at, ['color', 'width', 'cap', 'join', 'trim', 'dash']);
168
+ checkColor(stroke.color, `${at}.color`, palette);
169
+ scalar(stroke.width, `${at}.width`, channels, 0, 4096);
170
+ if (stroke.cap !== undefined && !['butt', 'round', 'square'].includes(stroke.cap as string)) invalid(`${at}.cap`, 'expected butt, round or square');
171
+ if (stroke.join !== undefined && !['miter', 'round', 'bevel'].includes(stroke.join as string)) invalid(`${at}.join`, 'expected miter, round or bevel');
172
+ if (stroke.trim !== undefined) {
173
+ const trim = record(stroke.trim, `${at}.trim`, ['start', 'end']);
174
+ for (const key of ['start', 'end']) if (trim[key] !== undefined) scalar(trim[key], `${at}.trim.${key}`, channels, 0, 1);
175
+ }
176
+ if (stroke.dash !== undefined) {
177
+ const dash = record(stroke.dash, `${at}.dash`, ['intervals', 'phase']);
178
+ const intervals = list(dash.intervals, `${at}.dash.intervals`, 32);
179
+ if (intervals.length < 2 || intervals.length % 2) invalid(`${at}.dash.intervals`, 'expected an even number of intervals');
180
+ intervals.forEach((interval, i) => number(interval, `${at}.dash.intervals[${i}]`, 0.001, 4096));
181
+ if (dash.phase !== undefined) scalar(dash.phase, `${at}.dash.phase`, channels);
182
+ }
183
+ }
184
+
185
+ function checkText(value: unknown, at: string, values: Record<string, unknown>): void {
186
+ if (typeof value === 'string') {
187
+ if (value.length > 4096) invalid(at, 'expected at most 4096 characters');
188
+ return;
189
+ }
190
+ const input = identifier(record(value, at, ['value']).value, `${at}.value`);
191
+ if ((values[input] as { type?: string } | undefined)?.type !== 'string') {
192
+ invalid(`${at}.value`, 'expected a string value from machine.values');
193
+ }
194
+ }
195
+
196
+ function resourceMap(value: unknown, at: string, pattern: RegExp) {
197
+ if (value === undefined) return {};
198
+ const resources = record(value, at);
199
+ if (Object.keys(resources).length > 32) invalid(at, 'expected at most 32 resources');
200
+ for (const [name, uri] of Object.entries(resources)) {
201
+ const key = `${at}.${name}`;
202
+ identifier(name, key);
203
+ const match = typeof uri === 'string' ? pattern.exec(uri) : null;
204
+ if (!match || match[0] !== uri || match[2]!.length % 4 !== 0) invalid(key, 'expected an embedded base64 data URI');
205
+ }
206
+ return resources;
207
+ }
208
+
209
+ function checkFontLicenses(value: unknown, fonts: Record<string, unknown>, at: string): void {
210
+ if (value === undefined) return;
211
+ for (const [name, license] of Object.entries(record(value, at))) {
212
+ if (!Object.hasOwn(fonts, name) || typeof license !== 'string' || license.length > 16_384) {
213
+ invalid(`${at}.${name}`, 'expected a license of up to 16384 characters for a declared font');
214
+ }
215
+ }
216
+ }
217
+
120
218
  function registerPoint(name: string, at: string, points: Set<string>): void {
121
219
  identifier(name, at);
122
220
  if (points.has(name)) invalid(at, 'duplicate point name');
@@ -171,8 +269,26 @@ function checkMesh(node: Record<string, unknown>, at: string, context: NodeValid
171
269
  }
172
270
 
173
271
  function checkNode(value: unknown, at: string, context: NodeValidation, depth: number): void {
174
- const { channels, images, points } = context;
272
+ const { channels, images, imageSlots, points } = context;
175
273
  const node = record(value, at);
274
+ if (node.kind === 'text') {
275
+ record(node, at, ['kind', 'text', 'x', 'y', 'width', 'fontSize', 'fill', 'fonts', 'direction', 'align', 'maxLines']);
276
+ checkText(node.text, `${at}.text`, context.values);
277
+ scalar(node.x, `${at}.x`, channels);
278
+ scalar(node.y, `${at}.y`, channels);
279
+ number(node.width, `${at}.width`, 1, 4096);
280
+ number(node.fontSize, `${at}.fontSize`, 1, 512);
281
+ color(node.fill, `${at}.fill`);
282
+ if (node.fonts !== undefined) list(node.fonts, `${at}.fonts`, 8).forEach((name, i) => {
283
+ if (typeof name !== 'string' || !Object.hasOwn(context.fonts, name)) invalid(`${at}.fonts[${i}]`, 'unknown embedded font');
284
+ });
285
+ if (node.direction !== undefined && node.direction !== 'ltr' && node.direction !== 'rtl') invalid(`${at}.direction`, 'expected ltr or rtl');
286
+ if (node.align !== undefined && !['start', 'center', 'end'].includes(node.align as string)) invalid(`${at}.align`, 'expected start, center or end');
287
+ if (node.maxLines !== undefined && !Number.isInteger(number(node.maxLines, `${at}.maxLines`, 1, 16))) {
288
+ invalid(`${at}.maxLines`, 'expected an integer');
289
+ }
290
+ return;
291
+ }
176
292
  if (node.kind === 'group') {
177
293
  record(node, at, ['kind', 'children', 'x', 'y', 'scaleX', 'scaleY', 'rotation', 'anchor', 'clip', 'points']);
178
294
  for (const key of ['x', 'y', 'scaleX', 'scaleY', 'rotation']) {
@@ -203,7 +319,9 @@ function checkNode(value: unknown, at: string, context: NodeValidation, depth: n
203
319
  return;
204
320
  }
205
321
  if (node.kind === 'image' || node.kind === 'mesh') {
206
- if (typeof node.image !== 'string' || !Object.hasOwn(images, node.image)) invalid(`${at}.image`, 'expected a name from images');
322
+ if (typeof node.image !== 'string' || (!Object.hasOwn(images, node.image) && !Object.hasOwn(imageSlots, node.image))) {
323
+ invalid(`${at}.image`, 'expected a name from images or imageSlots');
324
+ }
207
325
  if (node.opacity !== undefined) scalar(node.opacity, `${at}.opacity`, channels, 0, 1);
208
326
  if (node.kind === 'mesh') {
209
327
  checkMesh(node, at, context, depth);
@@ -215,8 +333,9 @@ function checkNode(value: unknown, at: string, context: NodeValidation, depth: n
215
333
  return;
216
334
  }
217
335
  if (node.kind === 'path') {
218
- record(node, at, ['kind', 'fill', 'opacity', 'feather', 'commands']);
336
+ record(node, at, ['kind', 'fill', 'opacity', 'feather', 'commands', 'stroke']);
219
337
  checkPath(node.commands, `${at}.commands`, channels);
338
+ if (node.stroke !== undefined) checkStroke(node.stroke, `${at}.stroke`, context);
220
339
  } else if (node.kind === 'ellipse' || node.kind === 'roundRect') {
221
340
  const keys = ['kind', 'fill', 'opacity', 'feather', 'x', 'y', 'width', 'height'];
222
341
  if (node.kind === 'roundRect') keys.push('radius');
@@ -224,14 +343,19 @@ function checkNode(value: unknown, at: string, context: NodeValidation, depth: n
224
343
  for (const key of ['x', 'y', 'width', 'height']) scalar(node[key], `${at}.${key}`, channels, key === 'x' || key === 'y' ? undefined : 0);
225
344
  if (node.kind === 'roundRect') scalar(node.radius, `${at}.radius`, channels, 0);
226
345
  } else {
227
- invalid(`${at}.kind`, 'expected ellipse, roundRect, path, image, mesh or group');
346
+ invalid(`${at}.kind`, 'expected ellipse, roundRect, path, image, mesh, text or group');
228
347
  }
229
348
  if (node.opacity !== undefined) scalar(node.opacity, `${at}.opacity`, channels, 0, 1);
230
349
  if (node.feather !== undefined) scalar(node.feather, `${at}.feather`, channels, 0, MAX_FEATHER);
350
+ if (node.kind === 'path' && node.fill === undefined && node.stroke !== undefined) return;
231
351
  if (typeof node.fill === 'string') {
232
352
  color(node.fill, `${at}.fill`);
233
353
  return;
234
354
  }
355
+ if (node.fill && typeof node.fill === 'object' && Object.hasOwn(node.fill, 'palette')) {
356
+ checkColor(node.fill, `${at}.fill`, context.palette);
357
+ return;
358
+ }
235
359
  const fill = record(node.fill, `${at}.fill`, ['kind', 'x', 'y', 'radius', 'colors']);
236
360
  if (fill.kind !== 'radial') invalid(`${at}.fill.kind`, 'expected radial');
237
361
  scalar(fill.x, `${at}.fill.x`, channels);
@@ -243,15 +367,34 @@ function checkNode(value: unknown, at: string, context: NodeValidation, depth: n
243
367
  }
244
368
 
245
369
  function validateAsset(value: unknown): MotionAsset {
246
- const data = record(value, 'asset', ['schema', 'name', 'artboard', 'channels', 'clips', 'machine', 'markers', 'images', 'attachments']);
370
+ const data = record(value, 'asset', [
371
+ 'schema', 'name', 'artboard', 'channels', 'clips', 'machine', 'markers', 'images', 'imageSlots', 'palette', 'attachments', 'fonts', 'fontLicenses', 'audio', 'semantics',
372
+ ]);
247
373
  if (data.schema !== ASSET_SCHEMA) invalid('asset.schema', `this player reads ${ASSET_SCHEMA}`);
248
374
  identifier(data.name, 'asset.name');
375
+ const machine = record(data.machine, 'machine');
376
+ const values = machine.values === undefined ? {} : record(machine.values, 'machine.values');
377
+ const fonts = resourceMap(data.fonts, 'fonts', FONT_URI);
378
+ checkFontLicenses(data.fontLicenses, fonts, 'fontLicenses');
379
+ const audio = resourceMap(data.audio, 'audio', AUDIO_URI);
380
+ const palette = data.palette === undefined ? {} : record(data.palette, 'palette');
381
+ for (const [name, value] of Object.entries(palette)) {
382
+ identifier(name, `palette.${name}`);
383
+ color(value, `palette.${name}`);
384
+ }
249
385
  const channels = record(data.channels, 'channels');
250
386
  for (const [name, value] of Object.entries(channels)) {
251
387
  identifier(name, `channels.${name}`);
252
388
  number(value, `channels.${name}`);
253
389
  }
254
390
  const images = data.images === undefined ? {} : record(data.images, 'images');
391
+ const imageSlots = data.imageSlots === undefined ? {} : record(data.imageSlots, 'imageSlots');
392
+ for (const [name, fallback] of Object.entries(imageSlots)) {
393
+ const at = `imageSlots.${name}`;
394
+ identifier(name, at);
395
+ if (Object.hasOwn(images, name)) invalid(at, 'the slot name must be distinct from its embedded fallback');
396
+ if (typeof fallback !== 'string' || !Object.hasOwn(images, fallback)) invalid(at, 'expected an embedded fallback from images');
397
+ }
255
398
  let pixels = 0;
256
399
  for (const [name, uri] of Object.entries(images)) {
257
400
  const at = `images.${name}`;
@@ -268,8 +411,30 @@ function validateAsset(value: unknown): MotionAsset {
268
411
  number(artboard.height, 'artboard.height', 1, 4096);
269
412
  const nodes = list(artboard.nodes, 'artboard.nodes', 256);
270
413
  if (!nodes.length) invalid('artboard.nodes', 'add at least one shape');
271
- const context = { channels, images, points: new Set<string>() };
414
+ const context = { channels, images, imageSlots, fonts, values, palette, points: new Set<string>() };
272
415
  nodes.forEach((node, i) => checkNode(node, `artboard.nodes[${i}]`, context, 0));
416
+ if (data.semantics !== undefined) {
417
+ const names = new Set<string>();
418
+ list(data.semantics, 'semantics', 64).forEach((item, i) => {
419
+ const at = `semantics[${i}]`;
420
+ const entry = record(item, at, ['name', 'role', 'label', 'bounds', 'trigger']);
421
+ const name = identifier(entry.name, `${at}.name`);
422
+ if (names.has(name)) invalid(`${at}.name`, 'duplicate semantic name');
423
+ names.add(name);
424
+ if (!['button', 'image', 'text', 'header'].includes(entry.role as string)) invalid(`${at}.role`, 'unknown role');
425
+ checkText(entry.label, `${at}.label`, values);
426
+ const bounds = list(entry.bounds, `${at}.bounds`, 4);
427
+ if (bounds.length !== 4) invalid(`${at}.bounds`, 'expected x, y, width and height');
428
+ bounds.forEach((side, index) => number(side, `${at}.bounds[${index}]`, index < 2 ? -4096 : 1, 4096));
429
+ if (entry.trigger !== undefined) {
430
+ const trigger = identifier(entry.trigger, `${at}.trigger`);
431
+ const property = values[trigger] as { type?: string; bind?: string } | undefined;
432
+ if (entry.role !== 'button' || property?.type !== 'trigger' || property.bind === 'out') {
433
+ invalid(`${at}.trigger`, 'expected a writable trigger on a button');
434
+ }
435
+ }
436
+ });
437
+ }
273
438
  if (data.attachments !== undefined) {
274
439
  list(data.attachments, 'attachments', 256).forEach((item, i) => {
275
440
  const at = `attachments[${i}]`;
@@ -308,8 +473,7 @@ function validateAsset(value: unknown): MotionAsset {
308
473
  });
309
474
  }
310
475
  }
311
- const machine = record(data.machine, 'machine');
312
- if (machine.clocks !== undefined || machine.hits !== undefined) invalid('machine', 'this asset version uses frame clocks and host input');
476
+ if (machine.hits !== undefined) invalid('machine.hits', 'packed scenes use host input and semantic regions');
313
477
  list(machine.layers, 'machine.layers', 32).forEach((value, i) => {
314
478
  const at = `machine.layers[${i}]`;
315
479
  const layer = record(value, at);
@@ -326,20 +490,23 @@ function validateAsset(value: unknown): MotionAsset {
326
490
  if (data.markers !== undefined) {
327
491
  list(data.markers, 'markers', 256).forEach((item, i) => {
328
492
  const at = `markers[${i}]`;
329
- const marker = record(item, at, ['name', 'layer', 'state']);
493
+ const marker = record(item, at, ['name', 'layer', 'state', 'audio']);
330
494
  const name = identifier(marker.name, `${at}.name`);
331
495
  if (names.has(name)) invalid(`${at}.name`, 'duplicate marker name');
332
496
  names.add(name);
333
497
  const layer = typed.machine.layers.find((layer) => layer.name === marker.layer);
334
498
  const state = identifier(marker.state, `${at}.state`);
335
499
  if (!layer || !Object.hasOwn(layer.states, state)) invalid(at, 'unknown layer or state');
500
+ if (marker.audio !== undefined && (typeof marker.audio !== 'string' || !Object.hasOwn(audio, marker.audio))) {
501
+ invalid(`${at}.audio`, 'unknown embedded audio cue');
502
+ }
336
503
  });
337
504
  }
338
505
  return typed;
339
506
  }
340
507
 
341
508
  /** Decode the same data file on a React Native JS thread and in the CLI. */
342
- export function parseAsset(text: string): MotionAsset {
509
+ export function parseAssetFile(text: string): MotionAssetFile {
343
510
  if (typeof text !== 'string' || text.length > MAX_ASSET_BYTES) invalid('asset', 'expected a JSON asset of at most 1 MiB');
344
511
  const bytes = encodeURI(text).replace(/%[0-9A-F]{2}/g, 'x').length;
345
512
  if (bytes > MAX_ASSET_BYTES) invalid('asset', 'expected a JSON asset of at most 1 MiB');
@@ -348,7 +515,77 @@ export function parseAsset(text: string): MotionAsset {
348
515
  if (typeof value === 'number' && !Number.isFinite(value)) invalid(key, 'expected a finite number');
349
516
  return value;
350
517
  });
351
- return validateAsset(decoded);
518
+ const file = record(decoded, 'asset');
519
+ if (file.schema !== ASSET_BUNDLE_SCHEMA) return validateAsset(file);
520
+ record(file, 'bundle', ['schema', 'name', 'defaultArtboard', 'artboards', 'fonts', 'fontLicenses', 'audio']);
521
+ const name = identifier(file.name, 'bundle.name');
522
+ const defaultArtboard = identifier(file.defaultArtboard, 'bundle.defaultArtboard');
523
+ const artboards = record(file.artboards, 'bundle.artboards');
524
+ const fonts = resourceMap(file.fonts, 'bundle.fonts', FONT_URI) as NonNullable<MotionAsset['fonts']>;
525
+ checkFontLicenses(file.fontLicenses, fonts, 'bundle.fontLicenses');
526
+ const fontLicenses = file.fontLicenses as MotionAsset['fontLicenses'];
527
+ const audio = resourceMap(file.audio, 'bundle.audio', AUDIO_URI) as NonNullable<MotionAsset['audio']>;
528
+ const entries = Object.entries(artboards);
529
+ if (entries.length < 1 || entries.length > 16) invalid('bundle.artboards', 'expected one to sixteen artboards');
530
+ if (!Object.hasOwn(artboards, defaultArtboard)) invalid('bundle.defaultArtboard', 'unknown artboard');
531
+ return {
532
+ schema: ASSET_BUNDLE_SCHEMA, name, defaultArtboard,
533
+ ...(Object.keys(fonts).length && { fonts }),
534
+ ...(fontLicenses && { fontLicenses }),
535
+ ...(Object.keys(audio).length && { audio }),
536
+ artboards: Object.fromEntries(entries.map(([key, value]) => {
537
+ identifier(key, `bundle.artboards.${key}`);
538
+ try {
539
+ const board = record(value, `bundle.artboards.${key}`);
540
+ const localFonts = board.fonts === undefined ? {} : record(board.fonts, 'fonts');
541
+ const localAudio = board.audio === undefined ? {} : record(board.audio, 'audio');
542
+ const localLicenses = board.fontLicenses === undefined ? {} : record(board.fontLicenses, 'fontLicenses');
543
+ validateAsset({
544
+ ...board, fonts: { ...fonts, ...localFonts },
545
+ fontLicenses: { ...fontLicenses, ...localLicenses }, audio: { ...audio, ...localAudio },
546
+ });
547
+ return [key, board as MotionAsset];
548
+ } catch (error) {
549
+ invalid(`bundle.artboards.${key}`, (error as Error).message);
550
+ }
551
+ })),
552
+ };
553
+ }
554
+
555
+ export function selectArtboard(file: MotionAssetFile, artboard?: string): MotionAsset {
556
+ if (file.schema === ASSET_SCHEMA) {
557
+ if (artboard === undefined || artboard === file.name) return file;
558
+ invalid('artboard', `unknown artboard "${artboard}". Available: ${file.name}`);
559
+ }
560
+ const name = artboard ?? file.defaultArtboard;
561
+ if (!Object.hasOwn(file.artboards, name)) {
562
+ invalid('artboard', `unknown artboard "${name}". Available: ${Object.keys(file.artboards).join(', ')}`);
563
+ }
564
+ const selected = file.artboards[name]!;
565
+ return {
566
+ ...selected,
567
+ ...(file.fonts && { fonts: { ...file.fonts, ...selected.fonts } }),
568
+ ...(file.fontLicenses && { fontLicenses: { ...file.fontLicenses, ...selected.fontLicenses } }),
569
+ ...(file.audio && { audio: { ...file.audio, ...selected.audio } }),
570
+ };
571
+ }
572
+
573
+ export function parseAsset(text: string, artboard?: string): MotionAsset {
574
+ return selectArtboard(parseAssetFile(text), artboard);
575
+ }
576
+
577
+ export function resolveAssetColor(value: AssetColor, palette: Readonly<Record<string, string>>): string {
578
+ 'worklet';
579
+ return typeof value === 'string' ? value : palette[value.palette]!;
580
+ }
581
+
582
+ export function bindAssetPalette(asset: MotionAsset, overrides?: Readonly<Record<string, string>>): MotionAsset {
583
+ if (!overrides) return asset;
584
+ for (const [name, value] of Object.entries(overrides)) {
585
+ if (!asset.palette || !Object.hasOwn(asset.palette, name)) invalid(`palette.${name}`, 'unknown palette entry');
586
+ color(value, `palette.${name}`);
587
+ }
588
+ return { ...asset, palette: { ...asset.palette, ...overrides } };
352
589
  }
353
590
 
354
591
  /** Image names used by the drawing. Unreferenced library entries can be omitted from playback. */
@@ -0,0 +1,19 @@
1
+ const ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
2
+
3
+ /** Decode a validated base64 string on Node, Hermes, or the web. */
4
+ export function decodeBase64(encoded: string): Uint8Array {
5
+ const bytes = new Uint8Array(encoded.length * 3 / 4);
6
+ let length = 0;
7
+ let bits = 0;
8
+ let value = 0;
9
+ for (const char of encoded) {
10
+ if (char === '=') break;
11
+ value = (value << 6) | ALPHABET.indexOf(char);
12
+ bits += 6;
13
+ if (bits >= 8) {
14
+ bits -= 8;
15
+ bytes[length++] = (value >>> bits) & 255;
16
+ }
17
+ }
18
+ return bytes.subarray(0, length);
19
+ }
@@ -0,0 +1,72 @@
1
+ import { useCallback, useEffect, useRef } from 'react';
2
+ import { createAudioPlayer, type AudioPlayer } from 'expo-audio';
3
+ import { File, Paths } from 'expo-file-system';
4
+ import type { LoadedMotionAsset } from './asset-load';
5
+ import { decodeBase64 } from './base64';
6
+ import type { MotionAudioCue } from './mobile';
7
+
8
+ const extensions: Record<string, string> = { mpeg: 'mp3', wav: 'wav', mp4: 'm4a', aac: 'aac' };
9
+ let sequence = 0;
10
+
11
+ type Prepared = {
12
+ file: File;
13
+ source: string;
14
+ ready: Promise<AudioPlayer | undefined>;
15
+ active: boolean;
16
+ revision: number;
17
+ };
18
+
19
+ /** Prepare embedded cues and return the callback for MotionPlayer's onAudio prop. */
20
+ export function useExpoMotionAudio(
21
+ asset: LoadedMotionAsset | null | undefined,
22
+ { enabled = true, onError }: { enabled?: boolean; onError?: (error: unknown) => void } = {},
23
+ ) {
24
+ const sounds = useRef(new Map<string, Prepared>());
25
+ const onErrorRef = useRef(onError);
26
+ useEffect(() => { onErrorRef.current = onError; }, [onError]);
27
+
28
+ useEffect(() => {
29
+ if (!enabled || !asset?.audio) return;
30
+ const loaded = new Map<string, Prepared>();
31
+ sounds.current = loaded;
32
+ const id = `${Date.now()}-${sequence++}`;
33
+ for (const [name, source] of Object.entries(asset.audio)) {
34
+ const header = /^data:audio\/(mpeg|wav|mp4|aac);base64,/.exec(source);
35
+ if (!header) continue;
36
+ const file = new File(Paths.cache, `skac-${id}-${name}.${extensions[header[1]!]}`);
37
+ const entry: Prepared = {
38
+ file, source, active: true, revision: 0,
39
+ ready: Promise.resolve().then(async () => {
40
+ if (!entry.active) return undefined;
41
+ await file.write(decodeBase64(source.slice(header[0].length)));
42
+ return entry.active ? createAudioPlayer({ uri: file.uri }) : undefined;
43
+ }).catch((error: unknown) => {
44
+ if (entry.active) onErrorRef.current?.(error);
45
+ return undefined;
46
+ }),
47
+ };
48
+ loaded.set(name, entry);
49
+ }
50
+ return () => {
51
+ sounds.current = new Map();
52
+ for (const entry of loaded.values()) {
53
+ entry.active = false;
54
+ void entry.ready.then(async (player) => {
55
+ player?.remove();
56
+ if (entry.file.exists) await entry.file.delete();
57
+ }).catch((error: unknown) => onErrorRef.current?.(error));
58
+ }
59
+ };
60
+ }, [asset, enabled]);
61
+
62
+ return useCallback(({ name, source }: MotionAudioCue) => {
63
+ const entry = sounds.current.get(name);
64
+ if (!entry || entry.source !== source) return;
65
+ const revision = ++entry.revision;
66
+ void entry.ready.then(async (player) => {
67
+ if (!player || !entry.active || revision !== entry.revision) return;
68
+ await player.seekTo(0);
69
+ if (entry.active && revision === entry.revision) player.play();
70
+ }).catch((error: unknown) => { if (entry.active) onErrorRef.current?.(error); });
71
+ }, []);
72
+ }
@@ -0,0 +1,16 @@
1
+ import { Asset } from 'expo-asset';
2
+ import { File } from 'expo-file-system';
3
+ import { useMotionAsset, type MotionAssetOptions } from './useMotionAsset';
4
+
5
+ /** Read a .skmotion from Expo's Metro asset registry in a development or release build. */
6
+ export function useExpoMotionAsset(moduleId: number | null | undefined, options?: MotionAssetOptions) {
7
+ return useMotionAsset(moduleId == null ? null : {
8
+ key: `expo-module:${moduleId}`,
9
+ async read(signal) {
10
+ const asset = await Asset.fromModule(moduleId).downloadAsync();
11
+ if (signal.aborted) throw new Error('Motion asset load cancelled');
12
+ if (!asset.localUri) throw new Error('Expo did not produce a local motion file');
13
+ return new File(asset.localUri).text();
14
+ },
15
+ }, options);
16
+ }
@@ -1,6 +1,6 @@
1
1
  // The schema and graph validator are shared by the CLI and the mobile asset loader.
2
2
  export const SCHEMA = 'skac.machine/1';
3
- export const VALUE_TYPES = ['boolean', 'number', 'enum', 'trigger'];
3
+ export const VALUE_TYPES = ['boolean', 'number', 'enum', 'trigger', 'string'];
4
4
  export const BINDS = ['in', 'out', 'both'];
5
5
  export const LOOPS = ['once', 'loop', 'pingpong'];
6
6
  export const EASES = ['linear', 'out', 'inOut', 'in'];
@@ -58,7 +58,7 @@ export const validateMachine = (m, { clips, clipNames = clips && Object.keys(cli
58
58
  const where = `values.${name}`;
59
59
  if (!isObj(v)) { bad(where, 'a value is not an object', 'like {"type": "boolean", "default": false}'); continue; }
60
60
  unknownKeys(v, KEYS.value, where);
61
- if (!VALUE_TYPES.includes(v.type)) { bad(where, `type ${JSON.stringify(v.type)} is not one of ${VALUE_TYPES.join(', ')}`, 'string, colour, image and list values are not in skac.machine/1'); continue; }
61
+ if (!VALUE_TYPES.includes(v.type)) { bad(where, `type ${JSON.stringify(v.type)} is not one of ${VALUE_TYPES.join(', ')}`, 'choose a supported value type'); continue; }
62
62
  if (v.bind !== undefined && !BINDS.includes(v.bind)) bad(where, `bind ${JSON.stringify(v.bind)} is not one of ${BINDS.join(', ')}`, '"in": the app writes it; "out": the machine writes it and the app reads it; "both"');
63
63
  if (v.type === 'enum') {
64
64
  if (!Array.isArray(v.options) || v.options.length < 2 || !v.options.every((o) => typeof o === 'string')) {
@@ -89,7 +89,7 @@ export const validateMachine = (m, { clips, clipNames = clips && Object.keys(cli
89
89
  // A literal or a value name on the right of a condition or action, checked against the type it must have.
90
90
  const operand = (rhs, type, where, options, assignment = false) => {
91
91
  const enumOptions = type === 'enum' && Array.isArray(options) ? options : undefined;
92
- if (typeof rhs === 'string' && values[rhs] !== undefined && !enumOptions?.includes(rhs)) {
92
+ if (typeof rhs === 'string' && Object.hasOwn(values, rhs) && !enumOptions?.includes(rhs)) {
93
93
  if (valueType(rhs) !== type) bad(where, `"${rhs}" is a ${valueType(rhs)}, compared with a ${type}`, 'compare values of one type');
94
94
  else if (assignment && enumOptions && Array.isArray(values[rhs].options)) {
95
95
  const missing = values[rhs].options.filter((option) => !enumOptions.includes(option));