@alpha2-sh/editor 0.5.2 → 0.6.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 +60 -3
  2. package/dist/browser/bridge.d.ts +5 -4
  3. package/dist/browser/bridge.js +390 -67
  4. package/dist/browser/extensions-worker.d.ts +4 -3
  5. package/dist/browser/extensions-worker.js +13 -6
  6. package/dist/browser/jobs.d.ts +17 -0
  7. package/dist/browser/jobs.js +40 -0
  8. package/dist/browser/resources.d.ts +9 -4
  9. package/dist/browser/resources.js +17 -5
  10. package/dist/browser/runtime/assets.d.ts +14 -2
  11. package/dist/browser/runtime/assets.js +37 -27
  12. package/dist/browser/runtime/audio.d.ts +12 -2
  13. package/dist/browser/runtime/audio.js +124 -14
  14. package/dist/browser/runtime/engine.js +8 -1
  15. package/dist/browser/runtime/exporter.d.ts +2 -1
  16. package/dist/browser/runtime/exporter.js +15 -4
  17. package/dist/browser/runtime/extension-import.d.ts +30 -10
  18. package/dist/browser/runtime/extension-import.js +52 -9
  19. package/dist/browser/runtime/preview-utils.d.ts +12 -0
  20. package/dist/browser/runtime/preview-utils.js +45 -0
  21. package/dist/browser/runtime/sources.d.ts +2 -2
  22. package/dist/browser/runtime/sources.js +23 -40
  23. package/dist/browser/runtime/wasm.d.ts +5 -5
  24. package/dist/browser/runtime/wasm.js +6 -13
  25. package/dist/browser/types.d.ts +138 -26
  26. package/dist/browser/worker.d.ts +4 -2
  27. package/dist/browser/worker.js +75 -25
  28. package/dist/core/commands.d.ts +46 -3
  29. package/dist/core/commands.js +212 -40
  30. package/dist/core/compositions.d.ts +27 -0
  31. package/dist/core/compositions.js +43 -0
  32. package/dist/core/data.d.ts +34 -0
  33. package/dist/core/data.js +69 -0
  34. package/dist/core/document.d.ts +20 -1
  35. package/dist/core/document.js +138 -8
  36. package/dist/core/keyframes.d.ts +3 -2
  37. package/dist/core/keyframes.js +6 -2
  38. package/dist/core/sameness.d.ts +6 -0
  39. package/dist/core/sameness.js +42 -0
  40. package/dist/core/session.d.ts +85 -7
  41. package/dist/core/session.js +124 -13
  42. package/dist/index.d.ts +1 -0
  43. package/dist/index.js +1 -0
  44. package/dist/native-client/index.d.ts +2 -2
  45. package/dist/native-client/index.js +2 -2
  46. package/dist/ports/index.d.ts +5 -4
  47. package/package.json +3 -3
@@ -5,10 +5,9 @@
5
5
  // never evicted, even past the budget. Decoder cursors are scoped per clip consumer so overlapping
6
6
  // uses of one source cannot seek each other. An `HTMLVideoElement` seek is the fallback for codecs
7
7
  // WebCodecs cannot open or frames that keep failing.
8
- import { activeTimeout } from "alpha2/active-clock";
9
8
  import { decoderCursorKey } from "alpha2/frame-supply";
10
9
  import { MediabunnyVideoDecoder } from "alpha2/mediabunny";
11
- import { containRect, seekVideoFrame } from "./preview-utils.js";
10
+ import { containRect, loadedOrFailed, seekVideoFrame, unloadVideo, } from "./preview-utils.js";
12
11
  import { decodeStill, stillRaster } from "./still.js";
13
12
  const TICKS_PER_SECOND = 120_000;
14
13
  /** Failed frames in a row, each retried with a reopened decoder, before element seeks take over. */
@@ -50,7 +49,7 @@ export class SourcePixels {
50
49
  #fonts = [];
51
50
  /** Each SVG's content identity with the fonts it was drawn with, for `contentOf`. */
52
51
  #fontContents = new WeakMap();
53
- constructor(library, { decoderLimit = 32, rasterBudgetBytes = DEFAULT_RASTER_BUDGET_BYTES, providerSourceBytes = DEFAULT_PROVIDER_SOURCE_BYTES, extensionsWasmUrl, videoDecode = "auto", } = {}) {
52
+ constructor(library, { decoderLimit = 32, rasterBudgetBytes = DEFAULT_RASTER_BUDGET_BYTES, providerSourceBytes = DEFAULT_PROVIDER_SOURCE_BYTES, extensionWasmUrls, videoDecode = "auto", } = {}) {
54
53
  if (videoDecode !== "auto" && videoDecode !== "software")
55
54
  throw new RangeError('videoDecode must be "auto" or "software"');
56
55
  if (!Number.isSafeInteger(rasterBudgetBytes) || rasterBudgetBytes <= 0)
@@ -61,7 +60,7 @@ export class SourcePixels {
61
60
  this.rasterBudgetBytes = rasterBudgetBytes;
62
61
  this.providerSourceBytes = providerSourceBytes;
63
62
  this.library = library;
64
- this.extensionsWasmUrl = extensionsWasmUrl;
63
+ this.extensionWasmUrls = extensionWasmUrls;
65
64
  /**
66
65
  * `"auto"` lets the browser pick, hardware where available; `"software"` decodes on the CPU so
67
66
  * no frame needs a GPU readback. Sources without a software decoder decode as `"auto"` and are
@@ -160,7 +159,7 @@ export class SourcePixels {
160
159
  fonts,
161
160
  source: provider.format === "animated_image"
162
161
  ? this.#openReader(asset)
163
- : openProvider(asset, this.extensionsWasmUrl, fonts),
162
+ : openProvider(asset, this.extensionWasmUrls, fonts),
164
163
  };
165
164
  // Keep provider reports, but retry load or read failures next frame.
166
165
  opening.source.catch((error) => {
@@ -195,9 +194,13 @@ export class SourcePixels {
195
194
  frame = await extensions.withResources(read, () => source.needs(ticks), () => source.render(ticks, fit));
196
195
  }
197
196
  catch (error) {
198
- // The provider module restarted after another source stopped it, so reopen this one.
199
- if (error?.name !== "StaleExtensionSourceError" || reopened)
197
+ // The provider module restarted, or is restarting, after another source stopped it, so
198
+ // reopen this one once it is ready.
199
+ if ((error?.name !== "ExtensionModuleRestartingError" &&
200
+ error?.name !== "StaleExtensionSourceError") ||
201
+ reopened)
200
202
  throw error;
203
+ await extensions.ready();
201
204
  if (this.#providers.get(key) === opened)
202
205
  this.#providers.delete(key);
203
206
  return this.#providerPixels(asset, key, seconds, true);
@@ -248,7 +251,7 @@ export class SourcePixels {
248
251
  }
249
252
  else if (made)
250
253
  this.#dropReaderMaker(asset.id);
251
- const opening = openProvider(asset, this.extensionsWasmUrl, null);
254
+ const opening = openProvider(asset, this.extensionWasmUrls, null);
252
255
  const entry = {
253
256
  asset,
254
257
  provider,
@@ -693,7 +696,16 @@ export class SourcePixels {
693
696
  });
694
697
  fallback = { sourceId, asset, consumerId, video };
695
698
  this.#seekVideos.set(cursor, fallback);
696
- await waitForLoad(video);
699
+ try {
700
+ await loadedOrFailed(video);
701
+ }
702
+ catch (error) {
703
+ // A broken element would cost every later frame the seek timeout; the next one tries anew.
704
+ if (this.#seekVideos.get(cursor) === fallback)
705
+ this.#seekVideos.delete(cursor);
706
+ unloadVideo(video);
707
+ throw error;
708
+ }
697
709
  }
698
710
  const { video } = fallback;
699
711
  const duration = Number.isFinite(video.duration)
@@ -777,11 +789,6 @@ function closeOpened(decoder) {
777
789
  decoder.video = null;
778
790
  decoder.opening = null;
779
791
  }
780
- /** Releases a fallback seek element's media. */
781
- function unloadVideo(video) {
782
- video.removeAttribute("src");
783
- video.load();
784
- }
785
792
  function premultiplyInPlace(pixels) {
786
793
  for (let index = 0; index < pixels.length; index += 4) {
787
794
  const alpha = pixels[index + 3];
@@ -792,32 +799,6 @@ function premultiplyInPlace(pixels) {
792
799
  pixels[index + 2] = Math.round((pixels[index + 2] * alpha) / 255);
793
800
  }
794
801
  }
795
- function waitForLoad(video) {
796
- return new Promise((resolve, reject) => {
797
- const timer = new AbortController();
798
- const cleanup = () => {
799
- timer.abort();
800
- video.removeEventListener("loadeddata", ready);
801
- video.removeEventListener("error", failed);
802
- };
803
- const ready = () => {
804
- cleanup();
805
- resolve();
806
- };
807
- const failed = () => {
808
- cleanup();
809
- reject(video.error ?? new Error("video load failed"));
810
- };
811
- // Active time, so a page frozen while the element loads does not time out.
812
- void activeTimeout(10_000, timer.signal).then(() => {
813
- cleanup();
814
- reject(new Error("video load timed out"));
815
- });
816
- video.addEventListener("loadeddata", ready, { once: true });
817
- video.addEventListener("error", failed, { once: true });
818
- video.load();
819
- });
820
- }
821
802
  /**
822
803
  * Which open extension source answers `consumerId`'s read of `asset`. Animated images decode in
823
804
  * order and keep only a window of frames, so each reader gets its own; other providers share one
@@ -899,6 +880,8 @@ async function openProvider(asset, wasmUrl, fonts) {
899
880
  try {
900
881
  const { loadExtensions } = await import("alpha2/extensions");
901
882
  extensions = await loadExtensions(wasmUrl);
883
+ await extensions.ready();
884
+ await extensions.prepare(asset.provider);
902
885
  own = asset.file
903
886
  ? new Uint8Array(await asset.file.arrayBuffer())
904
887
  : undefined;
@@ -1,8 +1,8 @@
1
1
  /**
2
- * Instantiates `alpha2/wasm` once per realm and resolves to its exports. wasm-bindgen's init only
3
- * reuses a finished instance, so two concurrent calls would instantiate twice and the second would
4
- * replace the module's memory under objects made from the first. Every caller goes through here; a
5
- * failed load is retried by the next call.
2
+ * Instantiates `alpha2/wasm` once per realm and resolves to its exports. Every caller goes through
3
+ * here, since two concurrent wasm-bindgen inits would replace the module's memory under objects
4
+ * made from the first; a failed load is retried by the next call.
6
5
  * @param {string | URL | undefined} wasmUrl
7
6
  */
8
- export function loadEngineWasm(wasmUrl: string | URL | undefined): any;
7
+ export function loadEngineWasm(wasmUrl: string | URL | undefined): Promise<typeof binding>;
8
+ import * as binding from "alpha2/wasm";
@@ -1,19 +1,12 @@
1
- import init from "alpha2/wasm";
2
1
  import * as binding from "alpha2/wasm";
3
- let loading = null;
2
+ import { WasmModule } from "alpha2/wasm-module";
3
+ const engine = new WasmModule(() => import("alpha2/wasm"));
4
4
  /**
5
- * Instantiates `alpha2/wasm` once per realm and resolves to its exports. wasm-bindgen's init only
6
- * reuses a finished instance, so two concurrent calls would instantiate twice and the second would
7
- * replace the module's memory under objects made from the first. Every caller goes through here; a
8
- * failed load is retried by the next call.
5
+ * Instantiates `alpha2/wasm` once per realm and resolves to its exports. Every caller goes through
6
+ * here, since two concurrent wasm-bindgen inits would replace the module's memory under objects
7
+ * made from the first; a failed load is retried by the next call.
9
8
  * @param {string | URL | undefined} wasmUrl
10
9
  */
11
10
  export function loadEngineWasm(wasmUrl) {
12
- loading ??= init(wasmUrl ? { module_or_path: wasmUrl } : undefined)
13
- .then(() => binding)
14
- .catch((error) => {
15
- loading = null;
16
- throw error;
17
- });
18
- return loading;
11
+ return engine.load(wasmUrl).then(() => binding);
19
12
  }
@@ -7,6 +7,7 @@ import type { EditorSession } from "../core/session.js";
7
7
  import type { CapabilityReport, PlaybackPolicy } from "alpha2";
8
8
  import type { Capability } from "../ports/index.js";
9
9
  import type { Json } from "../core/document.js";
10
+ import type { ExtensionWasmUrls } from "alpha2/extensions";
10
11
  import type { ExportJob } from "./jobs.js";
11
12
  /** Bundled locations of the runtime's code and data. Each URL defaults to the packaged one. */
12
13
  export interface RuntimeAssets {
@@ -30,8 +31,16 @@ export interface RuntimeAssets {
30
31
  readonly extensionsWorkerFactory?: () => Worker;
31
32
  /** The engine's wasm binary (`alpha2/wasm`). */
32
33
  readonly wasmUrl?: string | URL;
33
- /** `alpha2_extensions_bg.wasm`, loaded when an SVG, animated image or image sequence opens. */
34
+ /**
35
+ * `alpha2_extensions_bg.wasm`, the core provider module, loaded when an SVG, animated image,
36
+ * Lottie, OpenEXR, image sequence or LaTeX source opens.
37
+ */
34
38
  readonly extensionsWasmUrl?: string | URL;
39
+ /**
40
+ * Other provider modules' `.wasm` files by module name, such as `pdf` for
41
+ * `alpha2_extensions_pdf_bg.wasm`, each loaded when a file it reads is probed or opened.
42
+ */
43
+ readonly extensionModuleUrls?: ExtensionWasmUrls;
35
44
  /** The audio worklet's wasm binary, loaded on the first Play. */
36
45
  readonly audioWasmUrl?: string | URL;
37
46
  /** The audio worklet processor module. */
@@ -76,8 +85,10 @@ export interface RuntimeAsset {
76
85
  readonly hasAudio?: boolean;
77
86
  /**
78
87
  * `false` when this browser cannot decode the file's audio (Safari before 26 has no
79
- * `AudioDecoder`). It then plays and exports silent in this session, while the document still
80
- * records the audio for native hosts and other browsers.
88
+ * `AudioDecoder`). It then plays silent in this session, and an export that would write its
89
+ * sound is refused unless `BrowserExportOptions.undecodableAudio` is `silence`; the document
90
+ * still records the audio for native hosts and other browsers. `conform` for an export purpose
91
+ * decodes a trial again and updates it.
81
92
  */
82
93
  readonly audioDecodable?: boolean;
83
94
  /** When `audioDecodable` is `false`, what the trial decode at import found. */
@@ -113,10 +124,12 @@ export interface BrowserMediaAdapter {
113
124
  /**
114
125
  * Stages one file. The bridge stages at most four files of one import at once.
115
126
  *
116
- * Rejects with an `EditorError` coded `unsupported_media` for a file the adapter does not import,
117
- * `unreadable_media` when this browser or an extension provider cannot read it (the reason is the
118
- * message and `cause`), `too_large` for Lottie, dotLottie or SVG past the engine's parse limits
119
- * (`MAX_LOTTIE_DOCUMENT_BYTES`, `MAX_PROVIDER_DOCUMENT_BYTES`, `MAX_SVG_DOCUMENT_BYTES`),
127
+ * Rejects with an `EditorError` coded `unsupported_media` for a file the adapter does not import
128
+ * or a video this browser decodes none of (its `cause` a `DecodeUnavailableError` with the
129
+ * track's `facts`), `unreadable_media` when this browser or an extension provider cannot read it
130
+ * (the reason is the message and `cause`), `too_large` for Lottie, dotLottie or SVG past the
131
+ * engine's parse limits (`MAX_LOTTIE_DOCUMENT_BYTES`, `MAX_PROVIDER_DOCUMENT_BYTES`,
132
+ * `MAX_SVG_DOCUMENT_BYTES`),
120
133
  * `provider_stalled` past `EXTENSIONS_CALL_TIMEOUT_MS`, and when `signal` aborts.
121
134
  */
122
135
  stage(file: File, signal: AbortSignal, options?: {
@@ -149,12 +162,20 @@ export interface BrowserBridgeOptions {
149
162
  /** Defaults to `createMediaAdapter(runtimeAssets)`. */
150
163
  readonly mediaAdapter?: BrowserMediaAdapter;
151
164
  /**
152
- * The most runtime resources (imported media, rasterized text, proxies) held at once,
153
- * default 128. An import past it is refused with `EditorError` `resource_budget`.
165
+ * The most imported media files (videos, images, audio, fonts, LUTs) this session holds at
166
+ * once, default 128. Media removed from the document still counts while undo or redo can bring
167
+ * it back. Rasterized text and adopted proxies are not counted. An import past the limit is
168
+ * refused with `EditorError` `resource_budget` and changes nothing.
154
169
  */
155
170
  readonly resourceLimit?: number;
156
171
  /** `false` renders picture only: no AudioContext opens and playback runs on the wall clock. */
157
172
  readonly audio?: boolean;
173
+ /**
174
+ * Overrides the preview worker's request deadlines (`WorkerPreviewOptions.requestTimeoutMs`).
175
+ * A request past it gives the worker up: the main-thread renderer takes over the surface and
176
+ * `onError` receives one `preview_worker_failed`.
177
+ */
178
+ readonly workerRequestTimeoutMs?: number;
158
179
  /**
159
180
  * Receives errors no caller awaits, such as a failed preview render or audio that did not start.
160
181
  * The bridge keeps running after each.
@@ -278,6 +299,13 @@ export interface BrowserExportOptions {
278
299
  * an `EditorError` `invalid_video_conversion`.
279
300
  */
280
301
  readonly videoConversion?: "engine" | "browser";
302
+ /**
303
+ * What an export does with audible sources whose audio this browser cannot decode
304
+ * (`RuntimeAsset.audioDecodable` `false`): `refuse` (the default) refuses the export before it
305
+ * renders; `silence` writes them silent. The result's `report.silentAudioSources` lists the
306
+ * sources written silent either way (empty when none).
307
+ */
308
+ readonly undecodableAudio?: "refuse" | "silence";
281
309
  }
282
310
  /** Where a browser export writes its file. */
283
311
  export type ExportOutputTarget = {
@@ -376,7 +404,9 @@ export interface BrowserBridge {
376
404
  /** The playhead, in ticks. */
377
405
  readonly tick: number;
378
406
  readonly playing: boolean;
379
- /** Runtime resources currently held (see `BrowserBridgeOptions.resourceLimit`). */
407
+ /**
408
+ * Runtime resources currently held, counted or not (see `BrowserBridgeOptions.resourceLimit`).
409
+ */
380
410
  readonly resourceCount: number;
381
411
  /**
382
412
  * Preview output volume from 0 to 1, a monitor control outside the project and exports. Kept by
@@ -427,9 +457,8 @@ export interface BrowserBridge {
427
457
  readonly catalog: BuiltinEffectCatalog | null;
428
458
  /**
429
459
  * Adds runtime effects and transitions beyond the built-in catalog, addressable by `id@version`.
430
- * They belong to the bridge, not the document: every renderer the bridge makes registers them
431
- * (preview, a preview remade after GPU loss, each export attempt), and loading another project
432
- * keeps them.
460
+ * They belong to the bridge, not the document, so they outlast loading another project. Each
461
+ * renderer the bridge makes registers them, including a preview remade after GPU loss.
433
462
  *
434
463
  * With a preview bound, the definitions compile on its device all or none, and the call rejects
435
464
  * with `invalid_effect` naming the first one the engine refuses. Without one they are kept
@@ -527,8 +556,11 @@ export interface BrowserBridge {
527
556
  * Plays from the playhead at `rate` (negative plays backwards) under a playback `policy`
528
557
  * (default `drop_video_keep_audio`), stopping at the end of the export range (else of the
529
558
  * content), or looping with `loop`. Sound plays only at rate 1 under a policy that allows it;
530
- * when it cannot start within 3 s the picture plays silently and `onError` hears why. Rejects
531
- * for a zero or non-finite rate (`invalid_rate`) and an unknown policy (`invalid_policy`).
559
+ * when it fails to start or cannot start within 3 s the picture plays silently and `onError`
560
+ * hears why (`audio_unavailable`). A source whose stream this browser cannot decode, or which
561
+ * the file it reads (a proxy, say) does not have, plays silent and is reported once; so is a
562
+ * source whose sound does not arrive for a few mixes in a row, until playback starts again.
563
+ * Rejects a zero or non-finite rate (`invalid_rate`) and an unknown policy (`invalid_policy`).
532
564
  */
533
565
  play(rate?: number, options?: {
534
566
  loop?: boolean;
@@ -537,9 +569,9 @@ export interface BrowserBridge {
537
569
  /** Stops playback and audio; the playhead stays where it was. */
538
570
  pause(): void;
539
571
  /**
540
- * Reads a subtitle file (`.srt`, or `.vtt` for WebVTT) into a captions asset in the bin;
541
- * `skipped` counts blocks that were not cues. Nothing reaches the timeline until the asset is
542
- * inserted (`captionTrackCommands`).
572
+ * Reads a subtitle file (`.srt`, or `.vtt` for WebVTT) into a captions asset in the bin, and
573
+ * `skipped` counts blocks that were not cues. Nothing reaches the timeline until
574
+ * `captionTrackCommands` inserts the asset.
543
575
  *
544
576
  * Rejects with an `EditorError` `invalid_captions` for a file larger than
545
577
  * `MAX_CAPTION_FILE_BYTES` (not read), a WebVTT file without its header, more than
@@ -585,9 +617,55 @@ export interface BrowserBridge {
585
617
  * ready (`ConformError`) or the document does not compile.
586
618
  */
587
619
  nativeAssets(document?: import("../core/document.js").EditorDocument, options?: Pick<BrowserExportOptions, "media">): Promise<import("../native-client/index.js").NativeAsset[]>;
620
+ /**
621
+ * Runs an engine edit operation (`remove_ranges`, `split_at`, `bake`) on the committed document
622
+ * with this runtime's engine and commits it as one undo step (`EditorSession.applyEdit`), with
623
+ * `then` in the same step. Waits for the engine to load, so it can be called right away.
624
+ *
625
+ * Rejects with the engine's refusal (an `Alpha2Error` whose `details.refusal` names it), with
626
+ * `stale_edit` when the document changed while the engine loaded, with what
627
+ * `EditorSession.applyEdit` refuses, when `signal` aborts before the edit runs, and after the
628
+ * bridge is disposed (`disposed`).
629
+ */
630
+ applyEdit(request: import("alpha2/apply-edit").EditRequest, options?: {
631
+ readonly then?: readonly import("../core/commands.js").Command[];
632
+ readonly label?: string;
633
+ readonly signal?: AbortSignal;
634
+ }): Promise<{
635
+ readonly document: import("../core/document.js").EditorDocument;
636
+ readonly report: import("alpha2/apply-edit").EditReport;
637
+ }>;
638
+ /**
639
+ * Runs an extractor over a source's original media on this page (`runExtractor` from
640
+ * `alpha2/extract`), with an app's `extractor` or a `plugin` it loads (`loadPlugin` from
641
+ * `alpha2/plugins`, manifest and SHA-256 pinned). Resolves with the result and the read taken
642
+ * when the run started; commit them with `EditorSession.applyExtraction(result, { read })`.
643
+ *
644
+ * Rejects without exactly one of `plugin` and `extractor` (`invalid_command`), for a timeline
645
+ * input (`unsupported_media`), without the source's original in this session (`missing_asset`),
646
+ * with the plugin loader's and the extractor's errors (`PLUGIN_*`, `INVALID_INPUT`,
647
+ * `INVALID_EMIT`, `EXTRACTOR_FAILED`, `DECODE_UNAVAILABLE`), with `cancelled` when `signal`
648
+ * aborts or the bridge is disposed, and after disposal (`disposed`).
649
+ */
650
+ extract(run: import("alpha2/extractor").ExtractRun, options: {
651
+ readonly plugin?: {
652
+ readonly manifest: string | URL;
653
+ readonly sha256: string;
654
+ /** The most linear memory the module may have; the loader's default when left out. */
655
+ readonly memoryBytes?: number;
656
+ };
657
+ readonly extractor?: import("alpha2/extractor").Extractor;
658
+ readonly signal?: AbortSignal;
659
+ readonly onProgress?: (progress: import("alpha2/extractor").ExtractProgress) => void;
660
+ }): Promise<{
661
+ readonly result: import("alpha2/extractor").ExtractResult;
662
+ readonly read: import("../core/session.js").ExtractionRead;
663
+ }>;
588
664
  /**
589
665
  * Whether the document's media is ready for `purpose`, as the engine decides from this session's
590
- * originals and kept proxies.
666
+ * originals and kept proxies. Its `stale_data` lists the data sets whose `made_from` no longer
667
+ * matches their source's original (`data`, `source` and the differing `fields`); the set's own
668
+ * `made_by` in the project says how to run its extractor again. Nothing is fixed automatically.
591
669
  */
592
670
  conform(purpose: MediaPurpose, document?: import("../core/document.js").EditorDocument): Promise<ConformReport>;
593
671
  /**
@@ -596,8 +674,10 @@ export interface BrowserBridge {
596
674
  * export that starts restarts the conversion from 0 once it ends. Rejects for a source without a
597
675
  * single video file (`unsupported_media`, including HDR video), without its original in this
598
676
  * session (`missing_asset`), with a proxy already being made (`proxy_busy`), when the conversion
599
- * makes no progress for 30 s (`proxy_stalled`; preview keeps reading the original), or when
600
- * `signal` aborts.
677
+ * makes no progress for 30 s (`proxy_stalled`; preview keeps reading the original), when
678
+ * `signal` aborts, or when the bridge is disposed (`disposed`). Opening another project does not
679
+ * stop it: the proxy is kept in origin storage and used only while a document this session can
680
+ * show has that media.
601
681
  */
602
682
  generateProxy(id: string, options?: {
603
683
  signal?: AbortSignal;
@@ -641,11 +721,31 @@ export interface BrowserBridge {
641
721
  /**
642
722
  * Makes preview read a fresh proxy wherever a source has one (`proxies`), or the original
643
723
  * wherever it is online (`original`, the default). Preview only: an export reads what its own
644
- * `media` says. {@link BrowserBridge.proxyStatus} reports what each source reads.
724
+ * `media` says. {@link BrowserBridge.proxyStatus} reports what each source reads. A kept proxy
725
+ * that cannot be staged or held goes to `onError` once (`EditorError` `proxy_unavailable`), and
726
+ * its source reads the original.
645
727
  */
646
728
  setPreviewMedia(media: "original" | "proxies"): void;
647
729
  /** What {@link BrowserBridge.setPreviewMedia} last set. */
648
730
  readonly previewMedia: "original" | "proxies";
731
+ /**
732
+ * Adds or replaces a source whose provider reads no file, such as `{ format: "latex", ... }`,
733
+ * in one undoable `asset.put`. With an existing `id` its clips keep showing it with the new
734
+ * settings. The source is opened first, so its bin thumbnail and size are known.
735
+ *
736
+ * Rejects with `EditorError` `unsupported_media` for a provider that reads a file (use
737
+ * {@link BrowserBridge.importFiles}), `unreadable_media` when the source does not open, and
738
+ * `stale_import` when the session loads another project meanwhile.
739
+ */
740
+ putProviderSource(source: {
741
+ readonly id?: string;
742
+ readonly name?: string;
743
+ readonly provider: import("alpha2/project").ProviderSource;
744
+ }, options?: {
745
+ signal?: AbortSignal;
746
+ }): Promise<{
747
+ assetId: string;
748
+ }>;
649
749
  /**
650
750
  * Shows another animation of a dotLottie source, keeping its clips. Throws `EditorError`
651
751
  * `unsupported_media` for another kind of source or an animation the package lacks.
@@ -665,10 +765,13 @@ export interface BrowserBridge {
665
765
  * (`export_busy`), `frameRate` is not one the engine reads (`invalid_frame_rate`), `videoDecode`
666
766
  * is not `auto` or `software` (`invalid_video_decode`), `videoConversion` is not `engine` or
667
767
  * `browser` (`invalid_video_conversion`), the asset decisions are not loaded (`conform_pending`),
668
- * the media is not ready (`ConformError`), the document does not compile, or it shows an HDR
768
+ * the media is not ready (`ConformError`), the document does not compile, it shows an HDR
669
769
  * source this browser previews only degraded (`unsupported_media`, its `cause` a
670
- * `PlanarDecodeUnavailableError` naming the sources). Later failures arrive through the job's
671
- * `result`.
770
+ * `PlanarDecodeUnavailableError` naming the sources), `undecodableAudio` is not `refuse` or
771
+ * `silence` (`invalid_undecodable_audio`), or it would write audio this browser cannot decode
772
+ * (`unsupported_media`, its `cause` a `DecodeUnavailableError` and `details.sources` each
773
+ * source's `id`, `name` and import-time `facts`). `conform` for an export purpose decodes a trial
774
+ * of such audio again first. Later failures arrive through the job's `result`.
672
775
  */
673
776
  startExport(options?: BrowserExportOptions): ExportJob;
674
777
  /**
@@ -698,6 +801,12 @@ export interface WorkerPreviewOptions {
698
801
  readonly opaqueEngineFrames?: "refuse" | "present-degraded";
699
802
  /** `"auto"` (the default: a hardware GPU, else the CPU renderer), `"gpu"` or `"cpu"`. */
700
803
  readonly renderer?: "auto" | "gpu" | "cpu";
804
+ /**
805
+ * Milliseconds of active time (a hidden or frozen page does not count) any request waits for
806
+ * its reply. Default 60000 for `init` and `replaceProject`, 30000 for every other call. Past it
807
+ * the call and every later one reject with a fatal `worker_timeout`.
808
+ */
809
+ readonly requestTimeoutMs?: number;
701
810
  }
702
811
  /** The main-thread side of a preview renderer running in a worker. */
703
812
  export interface WorkerPreview {
@@ -750,6 +859,9 @@ export interface WorkerPreview {
750
859
  mix(startSample: number, frames: number): Promise<Float32Array[]>;
751
860
  /** Drops the render in flight; its `seek` resolves with `rendered: false`. */
752
861
  cancel(): Promise<void>;
753
- /** Releases the worker's engine and terminates the worker. Idempotent. */
862
+ /**
863
+ * Asks the worker to release its engine, waits at most one second for its reply, then terminates
864
+ * it and rejects every pending call. Idempotent.
865
+ */
754
866
  dispose(): Promise<void>;
755
867
  }
@@ -16,9 +16,11 @@ export function installEditorWorker(scope: import("./types.js").EditorWorkerScop
16
16
  * worker; `dispose()` terminates it. This port renders picture and mixes audio blocks only, apart
17
17
  * from a bridge's main-thread audio output. Every call waits for `ready`, which rejects if the
18
18
  * worker cannot start its engine; a disposed preview rejects new calls, and a worker error rejects
19
- * every pending one.
19
+ * every pending and later call. A request unanswered past its deadline (active time, see
20
+ * `WorkerPreviewOptions.requestTimeoutMs`) fails the worker the same way, with a fatal
21
+ * `worker_timeout`. `dispose()` waits at most a second for the worker's reply.
20
22
  * @param {Worker} worker
21
23
  * @param {import("./types.js").WorkerPreviewOptions} [options]
22
24
  * @returns {import("./types.js").WorkerPreview}
23
25
  */
24
- export function createWorkerPreview(worker: Worker, { sessionId, runtimeAssets, canvas, bitmapOutput, width, height, videoConversion, opaqueEngineFrames, renderer, }?: import("./types.js").WorkerPreviewOptions): import("./types.js").WorkerPreview;
26
+ export function createWorkerPreview(worker: Worker, { sessionId, runtimeAssets, canvas, bitmapOutput, width, height, videoConversion, opaqueEngineFrames, renderer, requestTimeoutMs, }?: import("./types.js").WorkerPreviewOptions): import("./types.js").WorkerPreview;
@@ -1,7 +1,17 @@
1
1
  import { Alpha2WasmError, serializeError } from "alpha2/worker-error";
2
+ import { withinActiveTime } from "alpha2/active-clock";
2
3
  import { SourcePixels } from "./runtime/sources.js";
4
+ import { extensionWasmUrls } from "./runtime/extension-import.js";
3
5
  import { AudioWindowSupplier, mixBlock } from "./runtime/audio.js";
4
6
  const INSTALLED = Symbol.for("alpha2.editorWorker");
7
+ /** How long `WorkerPreview.dispose()` waits for the worker's reply before terminating it. */
8
+ const DISPOSE_REPLY_MS = 1000;
9
+ /** Active milliseconds a request may wait for its reply, by type; others take the default. */
10
+ const REQUEST_TIMEOUT_MS = Object.freeze({
11
+ init: 60_000,
12
+ "replace-project": 60_000,
13
+ });
14
+ const DEFAULT_REQUEST_TIMEOUT_MS = 30_000;
5
15
  /**
6
16
  * Serves the editor's preview protocol (`createWorkerPreview`) on `scope`, a dedicated worker's
7
17
  * global. Requests run one at a time in arrival order. A `cancel` or `replace-project` stops the
@@ -69,7 +79,7 @@ function serveEditorWorker(scope) {
69
79
  sessionId = request.sessionId;
70
80
  bitmapOutput = request.bitmapOutput === true;
71
81
  pixels = new SourcePixels(library, {
72
- extensionsWasmUrl: request.runtimeAssets?.extensionsWasmUrl,
82
+ extensionWasmUrls: extensionWasmUrls(request.runtimeAssets),
73
83
  });
74
84
  const { Engine } = await import("./runtime/engine.js");
75
85
  engine = new Engine(request.canvas ??
@@ -189,17 +199,34 @@ function serveEditorWorker(scope) {
189
199
  catch {
190
200
  lossReport = undefined;
191
201
  }
192
- scope.postMessage({
193
- ...response,
194
- ok: false,
195
- error: {
196
- ...serializeError(error, false, "worker_error"),
197
- ...(typeof causeCode === "string" ? { causeCode } : {}),
198
- ...(lossReport === undefined ? {} : { lossReport }),
199
- },
200
- });
202
+ const serialized = serializeError(error, false, "worker_error");
203
+ try {
204
+ scope.postMessage({
205
+ ...response,
206
+ ok: false,
207
+ error: {
208
+ ...serialized,
209
+ ...(typeof causeCode === "string" ? { causeCode } : {}),
210
+ ...(lossReport === undefined ? {} : { lossReport }),
211
+ },
212
+ });
213
+ }
214
+ catch {
215
+ // A field that cannot be cloned must not leave the request unanswered.
216
+ scope.postMessage({
217
+ ...response,
218
+ ok: false,
219
+ error: {
220
+ code: "worker_error",
221
+ message: String(serialized.message),
222
+ fatal: serialized.fatal === true,
223
+ },
224
+ });
225
+ }
201
226
  }
202
227
  });
228
+ // One request that fails outside its handler must not stop the ones after it.
229
+ tail = tail.catch(() => { });
203
230
  };
204
231
  return {
205
232
  async dispose() {
@@ -218,13 +245,17 @@ function serveEditorWorker(scope) {
218
245
  * worker; `dispose()` terminates it. This port renders picture and mixes audio blocks only, apart
219
246
  * from a bridge's main-thread audio output. Every call waits for `ready`, which rejects if the
220
247
  * worker cannot start its engine; a disposed preview rejects new calls, and a worker error rejects
221
- * every pending one.
248
+ * every pending and later call. A request unanswered past its deadline (active time, see
249
+ * `WorkerPreviewOptions.requestTimeoutMs`) fails the worker the same way, with a fatal
250
+ * `worker_timeout`. `dispose()` waits at most a second for the worker's reply.
222
251
  * @param {Worker} worker
223
252
  * @param {import("./types.js").WorkerPreviewOptions} [options]
224
253
  * @returns {import("./types.js").WorkerPreview}
225
254
  */
226
- export function createWorkerPreview(worker, { sessionId = crypto.randomUUID(), runtimeAssets = {}, canvas, bitmapOutput = false, width = 16, height = 16, videoConversion, opaqueEngineFrames, renderer, } = {}) {
227
- let nextId = 0, revision = 0, disposed = false;
255
+ export function createWorkerPreview(worker, { sessionId = crypto.randomUUID(), runtimeAssets = {}, canvas, bitmapOutput = false, width = 16, height = 16, videoConversion, opaqueEngineFrames, renderer, requestTimeoutMs, } = {}) {
256
+ let nextId = 0, revision = 0, disposed = false,
257
+ // Set once the worker failed as a whole; every later call rejects with it at once.
258
+ failure = null;
228
259
  const pending = new Map();
229
260
  const rejectAll = (error) => {
230
261
  for (const waiter of pending.values())
@@ -259,10 +290,14 @@ export function createWorkerPreview(worker, { sessionId = crypto.randomUUID(), r
259
290
  waiter.reject(error);
260
291
  }
261
292
  };
262
- worker.onerror = (event) => rejectAll(new Error(event.message));
263
- const call = (type, body = {}, transfer = []) => {
264
- if (disposed)
265
- return Promise.reject(new Error("Worker preview disposed"));
293
+ const fail = (message, code = "worker_error") => {
294
+ failure ??= new Alpha2WasmError({ code, message, fatal: true });
295
+ rejectAll(failure);
296
+ return failure;
297
+ };
298
+ worker.onerror = (event) => fail(event?.message || "The preview worker failed");
299
+ worker.onmessageerror = () => fail("A preview worker reply could not be read");
300
+ const send = (type, body = {}, transfer = []) => {
266
301
  const requestId = ++nextId;
267
302
  return new Promise((resolve, reject) => {
268
303
  pending.set(requestId, { resolve, reject });
@@ -275,6 +310,16 @@ export function createWorkerPreview(worker, { sessionId = crypto.randomUUID(), r
275
310
  }
276
311
  });
277
312
  };
313
+ const call = (type, body, transfer) => {
314
+ if (disposed)
315
+ return Promise.reject(new Error("Worker preview disposed"));
316
+ if (failure)
317
+ return Promise.reject(failure);
318
+ const limit = requestTimeoutMs ??
319
+ REQUEST_TIMEOUT_MS[type] ??
320
+ DEFAULT_REQUEST_TIMEOUT_MS;
321
+ return withinActiveTime(send(type, body, transfer), limit, () => fail(`The preview worker did not answer ${type} within ${limit / 1000} s of active time`, "worker_timeout"));
322
+ };
278
323
  const ready = call("init", {
279
324
  runtimeAssets,
280
325
  bitmapOutput,
@@ -316,15 +361,20 @@ export function createWorkerPreview(worker, { sessionId = crypto.randomUUID(), r
316
361
  async dispose() {
317
362
  if (disposed)
318
363
  return;
319
- try {
320
- await ready;
321
- await call("dispose");
322
- }
323
- finally {
324
- disposed = true;
325
- worker.terminate();
326
- rejectAll(new Error("Worker disposed"));
364
+ disposed = true;
365
+ // The worker releases its engine if it answers in time; terminating frees it either way.
366
+ if (!failure) {
367
+ let timer = 0;
368
+ await Promise.race([
369
+ send("dispose").catch(() => { }),
370
+ new Promise((resolve) => {
371
+ timer = setTimeout(resolve, DISPOSE_REPLY_MS);
372
+ }),
373
+ ]);
374
+ clearTimeout(timer);
327
375
  }
376
+ worker.terminate();
377
+ rejectAll(new Error("Worker disposed"));
328
378
  },
329
379
  };
330
380
  }