alpha2 0.6.1 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/README.md +3 -3
  2. package/dist/effects.d.ts +3 -2
  3. package/dist/export-failure.d.ts +6 -0
  4. package/dist/export-failure.js +18 -1
  5. package/dist/export-retry.d.ts +2 -1
  6. package/dist/export-retry.js +12 -5
  7. package/dist/extract.d.ts +0 -5
  8. package/dist/extract.js +5 -12
  9. package/dist/extractor.d.ts +16 -3
  10. package/dist/extractor.js +2 -1
  11. package/dist/generated/project-schema.d.ts +31 -1
  12. package/dist/generated/project-schema.js +5 -0
  13. package/dist/generated/project-shape.js +14 -1
  14. package/dist/gpu-recovery.d.ts +13 -5
  15. package/dist/gpu-recovery.js +19 -8
  16. package/dist/hdr-frames.js +2 -0
  17. package/dist/media-source.d.ts +3 -0
  18. package/dist/media-source.js +13 -0
  19. package/dist/media.d.ts +12 -1
  20. package/dist/media.js +15 -1
  21. package/dist/mediabunny.d.ts +4 -1
  22. package/dist/mediabunny.js +22 -23
  23. package/dist/player.js +2 -0
  24. package/dist/plugin-manifest.d.ts +119 -0
  25. package/dist/plugin-manifest.js +583 -0
  26. package/dist/plugin-supplied.d.ts +55 -0
  27. package/dist/plugin-supplied.js +221 -0
  28. package/dist/plugins.d.ts +87 -9
  29. package/dist/plugins.js +196 -47
  30. package/dist/project-data.d.ts +19 -0
  31. package/dist/project-data.js +210 -7
  32. package/dist/project.d.ts +1 -1
  33. package/dist/project.js +1 -1
  34. package/dist/sha256.d.ts +1 -1
  35. package/package.json +1 -1
  36. package/wasm/alpha2_compose_bg.wasm +0 -0
  37. package/wasm/alpha2_extensions_bg.wasm +0 -0
  38. package/wasm/alpha2_extensions_pdf_bg.wasm +0 -0
  39. package/wasm/alpha2_wasm.d.ts +14 -12
  40. package/wasm/alpha2_wasm.js +48 -46
  41. package/wasm/alpha2_wasm_bg.wasm +0 -0
  42. package/wasm/alpha2_wasm_bg.wasm.d.ts +6 -6
  43. /package/wasm/snippets/{alpha2-wasm-6749ed8b34a74067/inline4.js → alpha2-wasm-7cccf477e10e3d0d/inline0.js} +0 -0
  44. /package/wasm/snippets/{alpha2-wasm-6749ed8b34a74067/inline0.js → alpha2-wasm-7cccf477e10e3d0d/inline1.js} +0 -0
  45. /package/wasm/snippets/{alpha2-wasm-6749ed8b34a74067/inline1.js → alpha2-wasm-7cccf477e10e3d0d/inline2.js} +0 -0
  46. /package/wasm/snippets/{alpha2-wasm-6749ed8b34a74067/inline2.js → alpha2-wasm-7cccf477e10e3d0d/inline3.js} +0 -0
  47. /package/wasm/snippets/{alpha2-wasm-6749ed8b34a74067/inline3.js → alpha2-wasm-7cccf477e10e3d0d/inline4.js} +0 -0
package/dist/plugins.js CHANGED
@@ -1,41 +1,104 @@
1
1
  // Runs a plugin's wasm artifact in the browser, checked against its pinned hashes, through the
2
2
  // `alpha2-plugin/1` ABI as an extractor for `runExtractor`. Native artifacts never run here.
3
- /** The ABI this loader implements. */
4
- export const PLUGIN_ABI = "alpha2-plugin/1";
3
+ import { resolveSupplied, SuppliedReader, } from "./plugin-supplied.js";
4
+ import { MAX_MANIFEST_BYTES, PluginError, parsePluginManifest, readPluginDescriptor, } from "./plugin-manifest.js";
5
+ export { MAX_ABOUT_AUTHOR_CHARS, MAX_ABOUT_HOMEPAGE_CHARS, MAX_ABOUT_LICENSE_CHARS, MAX_ABOUT_NAME_CHARS, MAX_ABOUT_SUMMARY_CHARS, MAX_EXTRACTOR_OUTPUTS, MAX_MANIFEST_BYTES, MAX_OUTPUT_DESCRIPTION_CHARS, MAX_OUTPUT_LABEL_CHARS, MAX_PLUGIN_ARTIFACT_BYTES, MAX_PLUGIN_ARTIFACTS, MAX_PLUGIN_RESOURCE_BYTES, MAX_PLUGIN_RESOURCES, MAX_PLUGIN_RESOURCES_TOTAL_BYTES, MAX_PLUGIN_SLOTS, MAX_SLOT_ACCEPT, MAX_SLOT_ACCEPT_BYTES, MAX_SLOT_NAME_BYTES, PLUGIN_ABI, PluginError, parsePluginManifest, } from "./plugin-manifest.js";
6
+ export { MAX_SLOT_DEPTH } from "./plugin-supplied.js";
7
+ /** Why `manifest`'s plugin cannot run where `capabilities` say, or `undefined` when it can. */
8
+ export function pluginProblem(manifest, capabilities) {
9
+ const runs = manifest.artifacts.some((artifact) => capabilities.artifacts.includes(artifact.type === "wasm" ? "wasm" : "native"));
10
+ if (!runs)
11
+ return {
12
+ reason: "artifact",
13
+ message: `${manifest.id} has no artifact of a kind that runs here (${capabilities.artifacts.join(", ") || "none"})`,
14
+ };
15
+ const required = (manifest.resources ?? []).find((resource) => resource.supplied !== undefined && resource.supplied.required !== false);
16
+ if (required !== undefined && !capabilities.slots)
17
+ return {
18
+ reason: "slots",
19
+ message: `${manifest.id} needs a file for its resource slot ${required.name}, and no slot is filled here`,
20
+ };
21
+ const { media, from } = manifest.descriptor.input;
22
+ const read = capabilities.inputs[media];
23
+ if (!from.some((clock) => read.includes(clock)))
24
+ return {
25
+ reason: "input",
26
+ message: `${manifest.id} reads ${media} from the ${from.join(" or the ")}, which is not read here`,
27
+ };
28
+ return undefined;
29
+ }
5
30
  /** Linear memory a plugin may grow to when the caller sets no cap. */
6
31
  export const DEFAULT_PLUGIN_MEMORY_BYTES = 1024 * 1024 * 1024;
7
32
  /** The memory a module's `i32` offsets address; a larger cap is taken as this. */
8
33
  const MAX_PLUGIN_MEMORY_BYTES = 2 ** 31;
9
- /** A plugin that was refused, did not load or failed, with the code every surface uses. */
10
- export class PluginError extends Error {
11
- code;
12
- constructor(code, message, options) {
13
- super(message, options);
14
- this.name = "PluginError";
15
- this.code = code;
16
- }
17
- }
18
34
  async function sha256Hex(bytes) {
19
35
  const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", bytes));
20
36
  return [...digest].map((byte) => byte.toString(16).padStart(2, "0")).join("");
21
37
  }
22
- async function fetchBytes(fetcher, url, signal) {
38
+ /**
39
+ * The body at `url`, read in chunks so that one longer than `limit` is refused as it arrives,
40
+ * with `refuse` the error for that.
41
+ */
42
+ async function fetchBytes(fetcher, url, limit, refuse, signal, onChunk) {
43
+ const failed = (cause) => new PluginError("PLUGIN_FETCH_FAILED", `${url.href}: ${String(cause)}`, {
44
+ cause,
45
+ });
23
46
  let response;
24
47
  try {
25
48
  response = await fetcher(url, { signal });
26
49
  }
27
50
  catch (cause) {
28
- throw new PluginError("PLUGIN_FETCH_FAILED", `${url.href}: ${String(cause)}`, {
29
- cause,
30
- });
51
+ throw failed(cause);
31
52
  }
32
53
  if (!response.ok)
33
54
  throw new PluginError("PLUGIN_FETCH_FAILED", `${url.href}: HTTP ${response.status}`);
34
- return new Uint8Array(await response.arrayBuffer());
55
+ const reader = response.body?.getReader();
56
+ if (reader === undefined) {
57
+ const whole = new Uint8Array(await response.arrayBuffer());
58
+ if (whole.byteLength > limit)
59
+ throw refuse(whole.byteLength);
60
+ onChunk?.(whole.byteLength);
61
+ return whole;
62
+ }
63
+ const chunks = [];
64
+ let loaded = 0;
65
+ for (;;) {
66
+ let read;
67
+ try {
68
+ read = await reader.read();
69
+ }
70
+ catch (cause) {
71
+ throw failed(cause);
72
+ }
73
+ if (read.done)
74
+ break;
75
+ loaded += read.value.byteLength;
76
+ if (loaded > limit) {
77
+ await reader.cancel().catch(() => { });
78
+ throw refuse(loaded);
79
+ }
80
+ chunks.push(read.value);
81
+ onChunk?.(loaded);
82
+ }
83
+ const bytes = new Uint8Array(loaded);
84
+ let at = 0;
85
+ for (const chunk of chunks) {
86
+ bytes.set(chunk, at);
87
+ at += chunk.byteLength;
88
+ }
89
+ return bytes;
35
90
  }
36
- async function verified(fetcher, base, file, signal) {
91
+ async function verified(fetcher, base, file, options) {
37
92
  const url = new URL(file.url, base);
38
- const bytes = await fetchBytes(fetcher, url, signal);
93
+ const longer = (length) => new PluginError("PLUGIN_HASH_MISMATCH", `${file.url} is ${length} bytes or more; the manifest pins ${file.bytes}`);
94
+ const { onProgress } = options;
95
+ const bytes = await fetchBytes(fetcher, url, file.bytes, longer, options.signal, onProgress &&
96
+ ((loaded) => onProgress({
97
+ phase: "load",
98
+ file: file.url,
99
+ loaded,
100
+ total: file.bytes,
101
+ })));
39
102
  if (bytes.byteLength !== file.bytes)
40
103
  throw new PluginError("PLUGIN_HASH_MISMATCH", `${file.url} is ${bytes.byteLength} bytes; the manifest pins ${file.bytes}`);
41
104
  const found = await sha256Hex(bytes);
@@ -234,19 +297,21 @@ class Run {
234
297
  #failure;
235
298
  #logLeft = LOG_BUDGET_BYTES;
236
299
  #logExhausted = false;
300
+ /** A failed read of a resource, which ends the call it happened in whatever it returns. */
301
+ #readFailure;
237
302
  constructor(descriptor, memoryBytes) {
238
303
  this.#descriptor = descriptor;
239
304
  this.#memoryBytes = memoryBytes;
240
305
  }
241
- static async start(module, descriptor, resources, memoryBytes) {
242
- const run = new Run(descriptor, memoryBytes);
243
- const instance = await WebAssembly.instantiate(module, run.#imports(resources));
306
+ static async start(parts, supplied) {
307
+ const run = new Run(parts.descriptor, parts.memoryBytes);
308
+ const instance = await WebAssembly.instantiate(parts.module, run.#imports(parts.resources, supplied));
244
309
  run.#exports = instance.exports;
245
310
  if (run.#exports.alpha2_abi() !== 1)
246
311
  throw new PluginError("PLUGIN_ABI_UNSUPPORTED", `the module implements alpha2-plugin/${run.#exports.alpha2_abi()}`);
247
312
  return run;
248
313
  }
249
- #imports(resources) {
314
+ #imports(resources, supplied) {
250
315
  const bytes = (ptr, len) => new Uint8Array(this.#exports.memory.buffer, ptr, len);
251
316
  const utf8 = (ptr, len) => new TextDecoder().decode(bytes(ptr, len));
252
317
  // Mirrors host-core: at most `max` bytes are decoded, one more read to see a split sequence.
@@ -272,15 +337,34 @@ class Run {
272
337
  }
273
338
  },
274
339
  resource_size: (name, nameLength) => {
275
- const found = resources.get(utf8(name, nameLength));
276
- return found === undefined ? -1n : BigInt(found.byteLength);
340
+ const named = utf8(name, nameLength);
341
+ const size = resources.get(named)?.byteLength ?? supplied?.size(named);
342
+ return size === undefined ? -1n : BigInt(size);
277
343
  },
278
344
  resource_read: (name, nameLength, dst, dstLength) => {
279
- const found = resources.get(utf8(name, nameLength));
280
- if (found === undefined || found.byteLength !== dstLength)
345
+ if (this.#readFailure !== undefined)
281
346
  return 1;
282
- bytes(dst, dstLength).set(found);
283
- return 0;
347
+ const named = utf8(name, nameLength);
348
+ const found = resources.get(named);
349
+ if (found !== undefined) {
350
+ if (found.byteLength !== dstLength)
351
+ return 1;
352
+ bytes(dst, dstLength).set(found);
353
+ return 0;
354
+ }
355
+ if (supplied?.size(named) !== dstLength)
356
+ return 1;
357
+ try {
358
+ supplied.read(named, bytes(dst, dstLength));
359
+ return 0;
360
+ }
361
+ catch (error) {
362
+ this.#readFailure =
363
+ error instanceof PluginError
364
+ ? error
365
+ : new PluginError("PLUGIN_FETCH_FAILED", String(error));
366
+ return 1;
367
+ }
284
368
  },
285
369
  fail: (ptr, len) => {
286
370
  this.#failure = new TextDecoder().decode(bounded(ptr, len, MAX_FAIL_BYTES));
@@ -334,6 +418,10 @@ class Run {
334
418
  throw new PluginError("PLUGIN_LIMIT", `the plugin needed more than ${this.#memoryBytes} bytes of memory`);
335
419
  const records = this.#records;
336
420
  this.#records = [];
421
+ const readFailure = this.#readFailure;
422
+ this.#readFailure = undefined;
423
+ if (readFailure !== undefined)
424
+ throw readFailure;
337
425
  if (status === 0)
338
426
  return records;
339
427
  if (status === 1) {
@@ -378,7 +466,7 @@ function nothingEmitted(records, step) {
378
466
  throw new PluginError("INVALID_EMIT", `the plugin emitted during ${step}, which takes no emits`);
379
467
  }
380
468
  /** The run context as the ABI's `begin` takes it. */
381
- function abiContext(context, params) {
469
+ function abiContext(context, params, supplied) {
382
470
  const raw = context;
383
471
  return JSON.stringify({
384
472
  range: context.range,
@@ -394,6 +482,7 @@ function abiContext(context, params) {
394
482
  },
395
483
  frame_rate: raw.frameRate ?? null,
396
484
  params,
485
+ supplied: supplied.context,
397
486
  });
398
487
  }
399
488
  /**
@@ -401,37 +490,49 @@ function abiContext(context, params) {
401
490
  * whose bytes have SHA-256 `sha256`, with its wasm artifact and resources, each checked against
402
491
  * the hash and length the manifest pins.
403
492
  *
493
+ * `supplied` fills the manifest's resource slots as `docs/plugin-abi.md` describes, with the
494
+ * limits and refusals of the native loaders: a `File` for a `file` slot, a directory handle or a
495
+ * directory picker's `File`s for a `directory` slot. They are resolved before any file is fetched
496
+ * and read when the plugin asks for one, in a worker; on a page, where browsers read files only
497
+ * asynchronously, every file of the filled slots is read into memory as a run begins. A run records
498
+ * the files it read in `made_by.plugin.supplied`.
499
+ *
500
+ * The manifest is checked as {@link parsePluginManifest} checks it before any other file is
501
+ * fetched; a file is refused as soon as more bytes arrive than the manifest pins. `onProgress`
502
+ * reports each pinned file as it arrives.
503
+ *
404
504
  * Rejects with a {@link PluginError} whose code is `PLUGIN_FETCH_FAILED`, `PLUGIN_HASH_MISMATCH`,
405
505
  * `PLUGIN_ABI_UNSUPPORTED`, `PLUGIN_NO_ARTIFACT` (no wasm artifact), `PLUGIN_UNSUPPORTED_FEATURE`,
406
- * `PLUGIN_LOAD_FAILED` or `PLUGIN_DESCRIPTOR_MISMATCH`.
506
+ * `PLUGIN_LOAD_FAILED`, `PLUGIN_DESCRIPTOR_MISMATCH` or `PLUGIN_RESOURCE_INVALID` (a slot
507
+ * `supplied` does not fill as the manifest asks, `details` `{ slot, reason }`).
407
508
  */
408
509
  export async function loadPlugin(manifest, sha256, options = {}) {
409
510
  const fetcher = options.fetch ?? globalThis.fetch.bind(globalThis);
410
511
  const base = new URL(manifest, globalThis.location?.href);
411
- const text = await fetchBytes(fetcher, base, options.signal);
512
+ const text = await fetchBytes(fetcher, base, MAX_MANIFEST_BYTES, () => new PluginError("PLUGIN_LOAD_FAILED", `invalid plugin manifest: longer than ${MAX_MANIFEST_BYTES} bytes`), options.signal);
412
513
  const found = await sha256Hex(text);
413
514
  if (found !== sha256.toLowerCase())
414
515
  throw new PluginError("PLUGIN_HASH_MISMATCH", `the manifest has SHA-256 ${found}; the caller pins ${sha256}`);
415
- let parsed;
516
+ let decoded;
416
517
  try {
417
- parsed = JSON.parse(new TextDecoder().decode(text));
518
+ // WHATWG Encoding: `ignoreBOM` keeps a byte order mark, which `JSON.parse` refuses.
519
+ decoded = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(text);
418
520
  }
419
521
  catch (cause) {
420
- throw new PluginError("PLUGIN_LOAD_FAILED", "the manifest is not JSON", {
522
+ throw new PluginError("PLUGIN_LOAD_FAILED", "the manifest is not UTF-8", {
421
523
  cause,
422
524
  });
423
525
  }
424
- if (parsed.abi !== PLUGIN_ABI)
425
- throw new PluginError("PLUGIN_ABI_UNSUPPORTED", `the plugin needs ABI ${String(parsed.abi)}; this build implements ${PLUGIN_ABI}`);
426
- if (parsed.kind !== "extractor" || parsed.id !== parsed.descriptor?.id)
427
- throw new PluginError("PLUGIN_LOAD_FAILED", "the manifest is not an extractor whose id is its descriptor's");
526
+ const parsed = parsePluginManifest(decoded);
428
527
  const artifact = parsed.artifacts.find((entry) => entry.target === "wasm32" && entry.type === "wasm");
429
528
  if (artifact === undefined)
430
529
  throw new PluginError("PLUGIN_NO_ARTIFACT", `${parsed.id} has no wasm artifact; it offers ${parsed.artifacts.map((entry) => `${entry.target} (${entry.type})`).join(", ")}`);
431
- const bytes = await verified(fetcher, base, artifact, options.signal);
530
+ const supplied = await resolveSupplied(parsed, options.supplied ?? {});
531
+ const bytes = await verified(fetcher, base, artifact, options);
432
532
  const resources = new Map();
433
533
  for (const resource of parsed.resources ?? [])
434
- resources.set(resource.name, await verified(fetcher, base, resource, options.signal));
534
+ if (resource.supplied === undefined)
535
+ resources.set(resource.name, await verified(fetcher, base, resource, options));
435
536
  let module;
436
537
  try {
437
538
  module = await WebAssembly.compile(bytes);
@@ -441,17 +542,54 @@ export async function loadPlugin(manifest, sha256, options = {}) {
441
542
  }
442
543
  checkModule(module, bytes);
443
544
  const memoryBytes = Math.min(options.memoryBytes ?? DEFAULT_PLUGIN_MEMORY_BYTES, MAX_PLUGIN_MEMORY_BYTES);
444
- const described = (await Run.start(module, parsed.descriptor, resources, memoryBytes)).describe();
445
- if (!sameJson(JSON.parse(described), parsed.descriptor))
446
- throw new PluginError("PLUGIN_DESCRIPTOR_MISMATCH", `the artifact ${artifact.url} describes another extractor than the manifest`);
447
- const descriptor = parsed.descriptor;
448
- return {
545
+ const parts = {
449
546
  id: parsed.id,
450
547
  version: parsed.version,
451
548
  artifactSha256: artifact.sha256,
549
+ manifestSha256: found,
550
+ ...(parsed.about === undefined ? {} : { about: parsed.about }),
551
+ descriptor: parsed.descriptor,
552
+ module,
553
+ resources,
554
+ supplied,
555
+ memoryBytes,
556
+ };
557
+ const described = (await Run.start(parts, undefined)).describe();
558
+ let own;
559
+ try {
560
+ own = readPluginDescriptor(JSON.parse(described));
561
+ }
562
+ catch (cause) {
563
+ throw new PluginError("PLUGIN_DESCRIPTOR_MISMATCH", `the artifact ${artifact.url} describes no extractor: ${String(cause)}`, { cause });
564
+ }
565
+ if (!sameJson(own, parsed.descriptor))
566
+ throw new PluginError("PLUGIN_DESCRIPTOR_MISMATCH", `the artifact ${artifact.url} describes another extractor than the manifest`);
567
+ return pluginOf(parts);
568
+ }
569
+ const partsOf = new WeakMap();
570
+ /** `plugin` as a value a worker can be posted; `plugin` is one {@link loadPlugin} gave. */
571
+ export function transferablePlugin(plugin) {
572
+ const parts = partsOf.get(plugin);
573
+ if (parts === undefined)
574
+ throw new TypeError("the plugin was not loaded by loadPlugin");
575
+ return { alpha2Plugin: parts };
576
+ }
577
+ /** The plugin {@link transferablePlugin} made `transferred` of, as it was loaded. */
578
+ export function restorePlugin(transferred) {
579
+ return pluginOf(transferred.alpha2Plugin);
580
+ }
581
+ function pluginOf(parts) {
582
+ const { descriptor } = parts;
583
+ const plugin = {
584
+ id: parts.id,
585
+ version: parts.version,
586
+ artifactSha256: parts.artifactSha256,
587
+ manifestSha256: parts.manifestSha256,
588
+ ...(parts.about === undefined ? {} : { about: parts.about }),
452
589
  descriptor,
453
590
  extractor(params = {}) {
454
591
  let run;
592
+ const reader = new SuppliedReader(parts.supplied);
455
593
  const current = () => {
456
594
  if (run === undefined)
457
595
  throw new PluginError("PLUGIN_LOAD_FAILED", "the run has not begun");
@@ -459,10 +597,19 @@ export async function loadPlugin(manifest, sha256, options = {}) {
459
597
  };
460
598
  return {
461
599
  describe: () => descriptor,
600
+ madeByPlugin: () => ({
601
+ version: parts.version,
602
+ artifact_sha256: parts.artifactSha256,
603
+ manifest_sha256: parts.manifestSha256,
604
+ ...(parts.supplied.files.size === 0
605
+ ? {}
606
+ : { supplied: reader.supplied() }),
607
+ }),
462
608
  async begin(context) {
463
- run = await Run.start(module, descriptor, resources, memoryBytes);
609
+ await reader.prepare();
610
+ run = await Run.start(parts, reader);
464
611
  const live = run;
465
- const json = new TextEncoder().encode(abiContext(context, params));
612
+ const json = new TextEncoder().encode(abiContext(context, params, parts.supplied));
466
613
  const records = live.withBytes(json, 1, (ptr) => live.exports.alpha2_begin(ptr, json.byteLength));
467
614
  nothingEmitted(records, "begin");
468
615
  },
@@ -487,6 +634,8 @@ export async function loadPlugin(manifest, sha256, options = {}) {
487
634
  };
488
635
  },
489
636
  };
637
+ partsOf.set(plugin, parts);
638
+ return plugin;
490
639
  }
491
640
  function sameJson(a, b) {
492
641
  if (Array.isArray(a) && Array.isArray(b))
@@ -53,4 +53,23 @@ export declare function dataReferences(project: object): DataReference[];
53
53
  * as unchangeable skips its own checks once it has passed them with the same source duration.
54
54
  */
55
55
  export declare function dataProblems(project: Json, paramType: ParamType, validFingerprint: (fingerprint: unknown) => boolean, sealed?: (value: unknown) => boolean): string[];
56
+ /** A property a data set can be bound to, by {@link bindableProperties}. */
57
+ export interface BindableProperty {
58
+ /** The property path in the syntax of {@link DataReference.property}. */
59
+ readonly property: string;
60
+ /**
61
+ * The data kinds it reads: `points` and `scalars` for a binding (`{ mode: "data" }`, a point
62
+ * or two-component value following `points`, or one channel per component of `scalars`),
63
+ * `similarity` for `visual.correction`, `words` for a caption track's `captions`.
64
+ */
65
+ readonly accepts: readonly ("points" | "scalars" | "similarity" | "words")[];
66
+ }
67
+ /**
68
+ * The properties of `owner` in `project` a data set can be bound to, in the order
69
+ * {@link dataReferences} lists references: each with the kinds it reads, by the rules project
70
+ * validation applies to a binding there. Masks, merge layers and the parameters of a host effect
71
+ * are those `project` has; a built-in effect lists every parameter that reads data. Values drawn
72
+ * on a picture clock (generators, caption styles) and an owner `project` lacks give none.
73
+ */
74
+ export declare function bindableProperties(project: object, owner: DataOwner): BindableProperty[];
56
75
  export {};
@@ -1,5 +1,7 @@
1
1
  // Data sets and the places that bind to them, mirroring `alpha2-model`'s `data` and `data_places`.
2
- import { MAX_DATA_CHANNELS, MAX_DATA_COORDINATE, MAX_DATA_ID_BYTES, MAX_DATA_INTERVALS, MAX_DATA_LABEL_BYTES, MAX_DATA_ROTATION_DEGREES, MAX_DATA_SCALAR, MAX_DATA_SCALE, MAX_DATA_SETS, MAX_DATA_VALUES, MAX_DATA_WORDS, MAX_FOLLOW_DEPTH, } from "./generated/project-schema.js";
2
+ import { MAX_DATA_CHANNELS, MAX_DATA_COORDINATE, MAX_DATA_ID_BYTES, MAX_DATA_INTERVALS, MAX_DATA_LABEL_BYTES, MAX_DATA_ROTATION_DEGREES, MAX_DATA_SCALAR, MAX_DATA_SCALE, MAX_DATA_SETS, MAX_DATA_VALUES, MAX_DATA_WORDS, MAX_FOLLOW_DEPTH, MAX_SUPPLIED_FILES, MAX_SUPPLIED_NAME_BYTES, } from "./generated/project-schema.js";
3
+ import { BUILTIN_EFFECT_RULES } from "./generated/builtin-effects.js";
4
+ import { PROJECT_SHAPE } from "./generated/project-shape.js";
3
5
  const encoder = new TextEncoder();
4
6
  function isRecord(value) {
5
7
  return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -7,6 +9,15 @@ function isRecord(value) {
7
9
  function bytes(text) {
8
10
  return encoder.encode(text).length;
9
11
  }
12
+ /** Whether `a` sorts before `b` by UTF-8 bytes, as Rust compares strings. */
13
+ function bytesBefore(a, b) {
14
+ const left = encoder.encode(a);
15
+ const right = encoder.encode(b);
16
+ for (let index = 0; index < Math.min(left.length, right.length); index++)
17
+ if (left[index] !== right[index])
18
+ return left[index] < right[index];
19
+ return left.length < right.length;
20
+ }
10
21
  function finite(value) {
11
22
  return typeof value === "number" && Number.isFinite(value);
12
23
  }
@@ -41,6 +52,31 @@ function inBounds(kind, component, value) {
41
52
  function label(text) {
42
53
  return typeof text === "string" && bytes(text) <= MAX_DATA_LABEL_BYTES;
43
54
  }
55
+ const isSha256 = (value) => typeof value === "string" && /^[0-9a-f]{64}$/.test(value);
56
+ /** Mirrors `MadeByPlugin::is_valid`. */
57
+ function validMadeByPlugin(plugin) {
58
+ if (!isRecord(plugin) ||
59
+ typeof plugin.version !== "string" ||
60
+ plugin.version.length === 0 ||
61
+ !isSha256(plugin.artifact_sha256) ||
62
+ !isSha256(plugin.manifest_sha256))
63
+ return false;
64
+ const supplied = plugin.supplied ?? [];
65
+ if (!Array.isArray(supplied) || supplied.length > MAX_SUPPLIED_FILES)
66
+ return false;
67
+ let previous;
68
+ for (const file of supplied) {
69
+ if (!isRecord(file) ||
70
+ typeof file.name !== "string" ||
71
+ file.name.length === 0 ||
72
+ bytes(file.name) > MAX_SUPPLIED_NAME_BYTES ||
73
+ !isSha256(file.sha256) ||
74
+ (previous !== undefined && !bytesBefore(previous, file.name)))
75
+ return false;
76
+ previous = file.name;
77
+ }
78
+ return true;
79
+ }
44
80
  /** Mirrors `DataSet::check`. */
45
81
  function setProblem(set, validFingerprint) {
46
82
  const id = String(set.id);
@@ -49,12 +85,7 @@ function setProblem(set, validFingerprint) {
49
85
  const madeBy = set.made_by;
50
86
  if (isRecord(madeBy)) {
51
87
  const plugin = madeBy.plugin;
52
- const pluginOk = plugin == null ||
53
- (isRecord(plugin) &&
54
- typeof plugin.version === "string" &&
55
- plugin.version.length > 0 &&
56
- typeof plugin.artifact_sha256 === "string" &&
57
- /^[0-9a-f]{64}$/.test(plugin.artifact_sha256));
88
+ const pluginOk = plugin == null || validMadeByPlugin(plugin);
58
89
  if (madeBy.extractor === "" || !pluginOk)
59
90
  return "has an invalid made_by";
60
91
  }
@@ -763,3 +794,175 @@ function followProblem(follows) {
763
794
  };
764
795
  return undefined;
765
796
  }
797
+ const TWO = ["points", "scalars"];
798
+ const ONE = ["scalars"];
799
+ /** What a binding on a value of `slot` reads, as `Places::check` decides it; none for others. */
800
+ function acceptsSlot(slot) {
801
+ if (slot.kind === "point" ||
802
+ slot.kind === "vec2" ||
803
+ (slot.kind === "param" && (slot.type === "vec2" || slot.type === undefined)))
804
+ return TWO;
805
+ if (slot.kind === "scalar" ||
806
+ (slot.kind === "param" && slot.type === "float"))
807
+ return ONE;
808
+ return undefined;
809
+ }
810
+ const SHAPE_DEFS = PROJECT_SHAPE.$defs;
811
+ function maskShapeFields(type) {
812
+ const variants = (SHAPE_DEFS.ShapeGeometry?.oneOf ?? []);
813
+ const variant = variants.find((candidate) => candidate.properties?.type
814
+ ?.const === type);
815
+ return Object.entries((variant?.properties ?? {}))
816
+ .filter(([, field]) => typeof field.$ref === "string" &&
817
+ field.$ref.startsWith("#/$defs/Animated"))
818
+ .map(([field]) => [
819
+ field,
820
+ slotOf(field === "center" ? "point" : field === "size" ? "vec2" : "scalar"),
821
+ ]);
822
+ }
823
+ function effectParams(effect, prefix) {
824
+ if (!isRecord(effect))
825
+ return [];
826
+ const rules = BUILTIN_EFFECT_RULES[String(effect.id)];
827
+ const names = rules === undefined
828
+ ? Object.keys(isRecord(effect.params) ? effect.params : {})
829
+ : Object.keys(rules.params);
830
+ return names.flatMap((name) => {
831
+ const accepts = acceptsSlot({
832
+ kind: "param",
833
+ type: rules?.params[name]?.type,
834
+ });
835
+ return accepts === undefined
836
+ ? []
837
+ : [{ property: `${prefix}${name}`, accepts }];
838
+ });
839
+ }
840
+ function maskProperties(masks) {
841
+ return (Array.isArray(masks) ? masks : []).flatMap((mask, index) => {
842
+ if (!isRecord(mask) || !isRecord(mask.shape))
843
+ return [];
844
+ const at = `masks[${index}]`;
845
+ return [
846
+ ...maskShapeFields(mask.shape.type).flatMap(([field, slot]) => {
847
+ const accepts = acceptsSlot(slot);
848
+ return accepts === undefined
849
+ ? []
850
+ : [{ property: `${at}.shape.${field}`, accepts }];
851
+ }),
852
+ { property: `${at}.feather`, accepts: ONE },
853
+ ];
854
+ });
855
+ }
856
+ const visualProperties = (prefix) => [
857
+ { property: `${prefix}.position`, accepts: TWO },
858
+ { property: `${prefix}.scale`, accepts: TWO },
859
+ { property: `${prefix}.rotation_degrees`, accepts: ONE },
860
+ { property: `${prefix}.opacity`, accepts: ONE },
861
+ ];
862
+ const audioProperties = [
863
+ { property: "audio.gain", accepts: ONE },
864
+ { property: "audio.pan", accepts: ONE },
865
+ ];
866
+ /**
867
+ * The properties of `owner` in `project` a data set can be bound to, in the order
868
+ * {@link dataReferences} lists references: each with the kinds it reads, by the rules project
869
+ * validation applies to a binding there. Masks, merge layers and the parameters of a host effect
870
+ * are those `project` has; a built-in effect lists every parameter that reads data. Values drawn
871
+ * on a picture clock (generators, caption styles) and an owner `project` lacks give none.
872
+ */
873
+ export function bindableProperties(project, owner) {
874
+ const root = project;
875
+ const timeline = isRecord(root.timeline) ? root.timeline : {};
876
+ const tracks = (Array.isArray(timeline.tracks) ? timeline.tracks : []).filter(isRecord);
877
+ const sources = (Array.isArray(root.sources) ? root.sources : []).filter(isRecord);
878
+ switch (owner.kind) {
879
+ case "clip": {
880
+ for (const track of tracks)
881
+ for (const clip of Array.isArray(track.clips) ? track.clips : []) {
882
+ if (!isRecord(clip) || clip.id !== owner.clip)
883
+ continue;
884
+ if (track.kind !== "video")
885
+ return [...audioProperties];
886
+ const source = sources.find((entry) => entry.id === clip.source_id);
887
+ const pictured = source?.kind === "video" || source?.kind === "image";
888
+ return [
889
+ ...visualProperties("visual"),
890
+ ...maskProperties(clip.masks),
891
+ ...audioProperties,
892
+ ...(pictured
893
+ ? [
894
+ {
895
+ property: "visual.correction",
896
+ accepts: ["similarity"],
897
+ },
898
+ ]
899
+ : []),
900
+ ];
901
+ }
902
+ return [];
903
+ }
904
+ case "transition": {
905
+ const track = tracks.find((entry) => entry.id === owner.track);
906
+ const transition = (Array.isArray(track?.transitions) ? track.transitions : []).find((entry) => isRecord(entry) &&
907
+ entry.from_clip === owner.from &&
908
+ entry.to_clip === owner.to);
909
+ return effectParams(transition?.effect, "effect.params.");
910
+ }
911
+ case "track": {
912
+ const track = tracks.find((entry) => entry.id === owner.track);
913
+ if (track === undefined)
914
+ return [];
915
+ return track.kind === "caption"
916
+ ? [{ property: "captions", accepts: ["words"] }]
917
+ : [...audioProperties];
918
+ }
919
+ case "master":
920
+ return [{ property: "audio.gain", accepts: ONE }];
921
+ case "source":
922
+ return [];
923
+ case "node": {
924
+ const compositions = (Array.isArray(root.compositions) ? root.compositions : []).filter(isRecord);
925
+ const composition = compositions.find((entry) => entry.id === owner.composition);
926
+ const node = (Array.isArray(composition?.nodes) ? composition.nodes : []).find((entry) => isRecord(entry) && entry.id === owner.node);
927
+ const op = isRecord(node?.op) ? node.op : {};
928
+ switch (op.type) {
929
+ case "effect":
930
+ return effectParams(op.effect, "effect.params.");
931
+ case "transition":
932
+ return [
933
+ ...effectParams(op.effect, "effect.params."),
934
+ { property: "progress", accepts: ONE },
935
+ ];
936
+ case "transform":
937
+ return visualProperties("transform");
938
+ case "merge":
939
+ return (Array.isArray(op.layers) ? op.layers : []).map((_, index) => ({
940
+ property: `layers[${index}].opacity`,
941
+ accepts: ONE,
942
+ }));
943
+ case "shape_mask":
944
+ return maskProperties(op.masks);
945
+ case "group": {
946
+ const group = compositions.find((entry) => entry.id === op.composition);
947
+ return (Array.isArray(group?.controls) ? group.controls : []).flatMap((control) => {
948
+ if (!isRecord(control))
949
+ return [];
950
+ const target = (Array.isArray(group?.nodes) ? group.nodes : []).find((entry) => isRecord(entry) && entry.id === control.node);
951
+ const targetOp = isRecord(target?.op) ? target.op : undefined;
952
+ const type = (targetOp?.type === "effect" ||
953
+ targetOp?.type === "transition") &&
954
+ isRecord(targetOp.effect)
955
+ ? BUILTIN_EFFECT_RULES[String(targetOp.effect.id)]?.params[String(control.param)]?.type
956
+ : undefined;
957
+ const accepts = acceptsSlot({ kind: "param", type });
958
+ return accepts === undefined
959
+ ? []
960
+ : [{ property: `controls.${String(control.name)}`, accepts }];
961
+ });
962
+ }
963
+ default:
964
+ return [];
965
+ }
966
+ }
967
+ }
968
+ }
package/dist/project.d.ts CHANGED
@@ -8,7 +8,7 @@
8
8
  * Timeline values are integer ticks at {@link TICKS_PER_SECOND}. Ranges are half-open.
9
9
  */
10
10
  import type { Animated, Easing, FrameRate, Insets, Interpolation, LayoutOffset, LayoutSize, MediaTime, Paint, Project, Rgba, TextContent, VisualProperties } from "./generated/project-schema.js";
11
- export { dataReferences, describeDataReference, type DataOwner, type DataReference, } from "./project-data.js";
11
+ export { bindableProperties, dataReferences, describeDataReference, type BindableProperty, type DataOwner, type DataReference, } from "./project-data.js";
12
12
  import { MAX_JSON_DEPTH } from "./json-text.js";
13
13
  export * from "./generated/project-schema.js";
14
14
  /** The deepest nesting of arrays and objects the engine reads in a project (serde_json's limit). */
package/dist/project.js CHANGED
@@ -10,7 +10,7 @@
10
10
  import { BUILTIN_EFFECT_RULES } from "./generated/builtin-effects.js";
11
11
  import { dataProblems } from "./project-data.js";
12
12
  import { shortestFloat32 } from "./float32.js";
13
- export { dataReferences, describeDataReference, } from "./project-data.js";
13
+ export { bindableProperties, dataReferences, describeDataReference, } from "./project-data.js";
14
14
  import { parseHex, parseInsets, parseLength, parseOffset, parsePlacement, parseSize, parseTrackList, } from "./layout-values.js";
15
15
  import { AUDIO_EFFECT_STATE_MARGIN_MS, MAX_CANVAS_DIMENSION, MAX_CANVAS_PIXELS, MAX_TEXT_CONTENT_BYTES, MAX_FONT_FAMILY_BYTES, MAX_COMPOSITIONS, MAX_COMPOSITION_NODES, MAX_COMPOSITION_CONTROLS, MAX_COMPOSITION_DEPTH, MAX_GROUP_INPUTS, MAX_EFFECT_INPUTS, MAX_FRAME_INLINED_NODES, MAX_INLINED_NODES, MAX_MERGE_LAYERS, MAX_CLIP_MASKS, MAX_DASH_ENTRIES, MAX_GRADIENT_STOPS, MAX_PATH_SUBPATHS, MAX_PATH_VERTICES, MAX_POLYSTAR_POINTS, MAX_SHAPE_DEPTH, MAX_SHAPE_ITEMS, MAX_LAYOUT_DEPTH, MAX_LAYOUT_FONT_SIZE, MAX_LAYOUT_ISOLATED, MAX_LAYOUT_NODES, MAX_LAYOUT_TEXTS, MAX_GRID_TRACKS, MIN_POLYSTAR_POINTS, MAX_CLIPS, MAX_CLIPS_PER_TRACK, MAX_AUDIO_DELAY_MS, MAX_AUDIO_EFFECTS, MAX_CAPTION_FONT_SIZE, MAX_CAPTION_NAME_BYTES, MAX_CAPTION_STYLES, MAX_TEXT_GENERATOR_FONT_SIZE, MAX_FONT_WEIGHT, MAX_LETTER_SPACING, MAX_LINE_HEIGHT, MAX_TEXT_PADDING, MAX_ANIMATOR_SCALE, MAX_CLASS_NAME_BYTES, MAX_RANGE_INDEX, MAX_RANGE_PERCENT, MAX_RUN_CLASSES, MAX_TEXT_ANIMATORS, MAX_TEXT_RUNS, MAX_LOOP_PASSES, MAX_ANIMATOR_OFFSET, MAX_ASPECT_RATIO, MAX_FLEX_FACTOR, MAX_LAYOUT_FRACTION, MAX_LAYOUT_PERCENT, MAX_LAYOUT_PX, MAX_TEXT_POSITION, MIN_ASPECT_RATIO, MIN_RANGE_PERCENT, MAX_TEXT_SHADOW_BLUR, MAX_TEXT_SHADOW_OFFSET, MAX_TEXT_SHADOWS, MAX_TEXT_STROKE_EXTENT, MAX_TEXT_STROKES, MAX_CHAIN_EFFECTS, MAX_COMPRESSOR_RATIO, MAX_ENVELOPE_MS, MAX_EQ_BANDS, MAX_LOOKAHEAD_MS, MIN_FONT_WEIGHT, MIN_LETTER_SPACING, MIN_LINE_HEIGHT, MIN_LEVEL_DB, MAX_EQ_FREQUENCY_HZ, MAX_EQ_GAIN_DB, MAX_EQ_Q, MAX_GAIN, MAX_PROJECT_JSON_BYTES, MAX_SAMPLE_RATE, MAX_TRACKS, MAX_TRANSITIONS_PER_TRACK, MIN_EQ_FREQUENCY_HZ, MIN_EQ_Q, MIN_SAMPLE_RATE, MIN_HDR_PEAK_NITS, MAX_HDR_PEAK_NITS, MAX_SEQUENCE_FRAMES, MAX_SELECTED_CHANNELS, MAX_AUDIO_CHANNELS, MAX_LATEX_BYTES, MAX_LATEX_FONT_SIZE, MAX_PDF_PAGES, REVERB_DELAY_MS, TICKS_PER_SECOND, } from "./generated/project-schema.js";
16
16
  import { PROJECT_SHAPE } from "./generated/project-shape.js";