@alpha2-sh/editor 0.5.3 → 0.6.1

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 (39) hide show
  1. package/README.md +58 -1
  2. package/dist/browser/bridge.js +275 -52
  3. package/dist/browser/jobs.d.ts +17 -0
  4. package/dist/browser/jobs.js +40 -0
  5. package/dist/browser/resources.d.ts +9 -4
  6. package/dist/browser/resources.js +17 -5
  7. package/dist/browser/runtime/assets.d.ts +14 -2
  8. package/dist/browser/runtime/assets.js +37 -27
  9. package/dist/browser/runtime/audio.d.ts +12 -2
  10. package/dist/browser/runtime/audio.js +124 -14
  11. package/dist/browser/runtime/engine.js +8 -1
  12. package/dist/browser/runtime/exporter.d.ts +2 -1
  13. package/dist/browser/runtime/exporter.js +15 -4
  14. package/dist/browser/runtime/preview-utils.d.ts +12 -0
  15. package/dist/browser/runtime/preview-utils.js +45 -0
  16. package/dist/browser/runtime/sources.js +11 -34
  17. package/dist/browser/types.d.ts +105 -19
  18. package/dist/browser/worker.d.ts +4 -2
  19. package/dist/browser/worker.js +73 -24
  20. package/dist/core/commands.d.ts +46 -3
  21. package/dist/core/commands.js +212 -40
  22. package/dist/core/compositions.d.ts +27 -0
  23. package/dist/core/compositions.js +43 -0
  24. package/dist/core/data.d.ts +34 -0
  25. package/dist/core/data.js +69 -0
  26. package/dist/core/document.d.ts +10 -1
  27. package/dist/core/document.js +127 -6
  28. package/dist/core/keyframes.d.ts +3 -2
  29. package/dist/core/keyframes.js +6 -2
  30. package/dist/core/sameness.d.ts +6 -0
  31. package/dist/core/sameness.js +42 -0
  32. package/dist/core/session.d.ts +85 -7
  33. package/dist/core/session.js +124 -13
  34. package/dist/index.d.ts +1 -0
  35. package/dist/index.js +1 -0
  36. package/dist/native-client/index.d.ts +2 -2
  37. package/dist/native-client/index.js +2 -2
  38. package/dist/ports/index.d.ts +5 -4
  39. package/package.json +3 -3
@@ -13,6 +13,8 @@ const EDITOR_FAILURE_CODES = Object.freeze({
13
13
  cancelled: "CANCELLED",
14
14
  conform_failed: "INVALID_INPUT",
15
15
  conform_pending: "UNKNOWN",
16
+ data_bound: "INVALID_INPUT",
17
+ data_referenced: "INVALID_INPUT",
16
18
  disposed: "UNKNOWN",
17
19
  duplicate_resource: "INVALID_INPUT",
18
20
  effect_unavailable: "INVALID_INPUT",
@@ -33,9 +35,11 @@ const EDITOR_FAILURE_CODES = Object.freeze({
33
35
  invalid_project: "INVALID_INPUT",
34
36
  invalid_projection: "INVALID_INPUT",
35
37
  invalid_rate: "INVALID_INPUT",
38
+ invalid_result: "UNKNOWN",
36
39
  invalid_text: "INVALID_INPUT",
37
40
  invalid_time: "INVALID_INPUT",
38
41
  invalid_transition: "INVALID_INPUT",
42
+ invalid_undecodable_audio: "INVALID_INPUT",
39
43
  invalid_video_conversion: "INVALID_INPUT",
40
44
  invalid_video_decode: "INVALID_INPUT",
41
45
  locked: "INVALID_INPUT",
@@ -45,11 +49,14 @@ const EDITOR_FAILURE_CODES = Object.freeze({
45
49
  provider_stalled: "RESOURCE_LIMIT",
46
50
  proxy_busy: "UNKNOWN",
47
51
  proxy_stalled: "UNKNOWN",
52
+ proxy_unavailable: "UNKNOWN",
48
53
  relink_conflict: "INVALID_INPUT",
49
54
  resource_budget: "RESOURCE_LIMIT",
50
55
  resource_limit: "RESOURCE_LIMIT",
51
56
  sequence_gap: "INVALID_INPUT",
52
57
  sequence_size: "INVALID_INPUT",
58
+ stale_edit: "UNKNOWN",
59
+ stale_extraction: "UNKNOWN",
53
60
  stale_gesture: "UNKNOWN",
54
61
  stale_import: "UNKNOWN",
55
62
  storage_quota_exceeded: "STORAGE_QUOTA_EXCEEDED",
@@ -66,12 +73,18 @@ export class EditorError extends Error {
66
73
  operation;
67
74
  entityId;
68
75
  recoverable;
76
+ /**
77
+ * Structured facts about the refusal, for codes that define them. A `data_referenced` refusal has
78
+ * the `references` (`DataReference`s from `alpha2/project`) or `dataSets` ids that block it.
79
+ */
80
+ details;
69
81
  /**
70
82
  * @param code What went wrong, such as `invalid_command` or `locked`.
71
83
  * @param message A human-readable description.
72
84
  * @param operation The operation that failed, such as `validate`, `open` or a command name.
73
85
  * @param entityId The track, clip, asset or other entity the error concerns, when there is one.
74
86
  * @param recoverable Whether the editor stays usable after the error. Defaults to `true`.
87
+ * @param options `cause`, and `details` for {@link EditorError.details}.
75
88
  */
76
89
  constructor(code, message, operation, entityId, recoverable = true, options) {
77
90
  super(message, options);
@@ -80,6 +93,8 @@ export class EditorError extends Error {
80
93
  this.entityId = entityId;
81
94
  this.recoverable = recoverable;
82
95
  this.name = "EditorError";
96
+ if (options?.details)
97
+ this.details = options.details;
83
98
  }
84
99
  /**
85
100
  * The export failure class this error implies, read by `classifyBrowserFailure`. `UNKNOWN` for
@@ -124,14 +139,20 @@ export function freeze(value) {
124
139
  * ({@link MAX_JSON_DEPTH}) plus one for the document that holds it.
125
140
  */
126
141
  export const MAX_DOCUMENT_JSON_DEPTH = MAX_JSON_DEPTH + 1;
142
+ /** Nesting height of deep-frozen containers that passed {@link assertJson}. */
143
+ const jsonHeights = new WeakMap();
127
144
  /**
128
145
  * Throws an `EditorError` (`invalid_document`) unless `value` is plain JSON (finite numbers, arrays
129
146
  * and plain objects) nested at most `maxDepth` deep ({@link MAX_DOCUMENT_JSON_DEPTH} by default).
147
+ * Deep-frozen parts that passed before are not walked again.
130
148
  */
131
149
  export function assertJson(value, maxDepth = MAX_DOCUMENT_JSON_DEPTH) {
132
- const pending = [[value, 0]];
150
+ const tooDeep = () => new EditorError("invalid_document", `Document nests deeper than ${maxDepth} levels`, "validate");
151
+ // Children follow their parent here, so a reverse pass totals heights without recursion.
152
+ const containers = [];
153
+ const pending = [[value, 0, -1]];
133
154
  while (pending.length) {
134
- const [next, depth] = pending.pop();
155
+ const [next, depth, parent] = pending.pop();
135
156
  if (next === null || typeof next === "string" || typeof next === "boolean")
136
157
  continue;
137
158
  if (typeof next === "number" && Number.isFinite(next))
@@ -141,10 +162,35 @@ export function assertJson(value, maxDepth = MAX_DOCUMENT_JSON_DEPTH) {
141
162
  Object.getPrototypeOf(next) === Object.prototype);
142
163
  if (!container)
143
164
  throw new EditorError("invalid_document", "Document must contain finite JSON values", "validate");
165
+ const known = jsonHeights.get(next);
166
+ if (known !== undefined) {
167
+ if (depth + known > maxDepth)
168
+ throw tooDeep();
169
+ if (parent >= 0)
170
+ containers[parent].height = Math.max(containers[parent].height, known + 1);
171
+ continue;
172
+ }
144
173
  if (depth >= maxDepth)
145
- throw new EditorError("invalid_document", `Document nests deeper than ${maxDepth} levels`, "validate");
174
+ throw tooDeep();
175
+ const index = containers.length;
176
+ containers.push({
177
+ node: next,
178
+ parent,
179
+ height: 1,
180
+ frozen: Object.isFrozen(next),
181
+ });
146
182
  for (const child of Object.values(next))
147
- pending.push([child, depth + 1]);
183
+ pending.push([child, depth + 1, index]);
184
+ }
185
+ for (let index = containers.length - 1; index >= 0; index--) {
186
+ const entry = containers[index];
187
+ if (entry.frozen)
188
+ jsonHeights.set(entry.node, entry.height);
189
+ if (entry.parent < 0)
190
+ continue;
191
+ const parent = containers[entry.parent];
192
+ parent.height = Math.max(parent.height, entry.height + 1);
193
+ parent.frozen &&= entry.frozen;
148
194
  }
149
195
  }
150
196
  /**
@@ -195,10 +241,85 @@ const optionalBoolean = (value) => value === undefined || typeof value === "bool
195
241
  /** The largest editor file {@link parseDocument} opens; every valid document fits in it. */
196
242
  export const MAX_EDITOR_FILE_BYTES = 128 * 1024 * 1024;
197
243
  const utf8Length = (text) => new TextEncoder().encode(text).length;
244
+ /** {@link jsonLength} of deep-frozen containers. */
245
+ const jsonLengths = new WeakMap();
246
+ /** UTF-8 bytes of `text` as `JSON.stringify` writes it, quotes and escapes included. */
247
+ function stringLength(text) {
248
+ let bytes = 2;
249
+ for (let i = 0; i < text.length; i++) {
250
+ const unit = text.charCodeAt(i);
251
+ if (unit === 0x22 || unit === 0x5c)
252
+ bytes += 2;
253
+ else if (unit < 0x20)
254
+ bytes +=
255
+ unit === 8 || unit === 9 || unit === 10 || unit === 12 || unit === 13
256
+ ? 2
257
+ : 6;
258
+ else if (unit < 0x80)
259
+ bytes += 1;
260
+ else if (unit < 0x800)
261
+ bytes += 2;
262
+ else if (unit >= 0xd800 && unit < 0xdc00) {
263
+ const low = text.charCodeAt(i + 1);
264
+ // A pair is one 4-byte character. A lone surrogate is written as a `\u` escape.
265
+ if (low >= 0xdc00 && low < 0xe000) {
266
+ bytes += 4;
267
+ i++;
268
+ }
269
+ else
270
+ bytes += 6;
271
+ }
272
+ else if (unit >= 0xdc00 && unit < 0xe000)
273
+ bytes += 6;
274
+ else
275
+ bytes += 3;
276
+ }
277
+ return bytes;
278
+ }
279
+ /**
280
+ * UTF-8 bytes of `JSON.stringify(value)` for a value {@link assertJson} accepted, without building
281
+ * the string. Deep-frozen parts are measured once. Returns the length and whether it may be cached.
282
+ */
283
+ function jsonLength(value) {
284
+ if (value === null)
285
+ return [4, true];
286
+ if (typeof value === "string")
287
+ return [stringLength(value), true];
288
+ // `assertJson` leaves only finite numbers and booleans here.
289
+ if (typeof value === "number" || typeof value === "boolean")
290
+ return [String(value).length, true];
291
+ if (typeof value !== "object")
292
+ return [0, true];
293
+ const known = jsonLengths.get(value);
294
+ if (known !== undefined)
295
+ return [known, true];
296
+ let frozen = Object.isFrozen(value);
297
+ let bytes;
298
+ if (Array.isArray(value)) {
299
+ bytes = 1 + Math.max(value.length, 1);
300
+ for (const item of value) {
301
+ const [length, cached] = jsonLength(item);
302
+ bytes += length;
303
+ frozen &&= cached;
304
+ }
305
+ }
306
+ else {
307
+ const entries = Object.entries(value);
308
+ bytes = 1 + Math.max(entries.length, 1);
309
+ for (const [key, field] of entries) {
310
+ const [length, cached] = jsonLength(field);
311
+ bytes += stringLength(key) + 1 + length;
312
+ frozen &&= cached;
313
+ }
314
+ }
315
+ if (frozen)
316
+ jsonLengths.set(value, bytes);
317
+ return [bytes, frozen];
318
+ }
198
319
  function assertDocumentSize(document) {
199
- if (utf8Length(JSON.stringify(document.project)) > MAX_PROJECT_JSON_BYTES)
320
+ if (jsonLength(document.project)[0] > MAX_PROJECT_JSON_BYTES)
200
321
  throw new EditorError("too_large", "Engine JSON exceeds its size limit", "validate");
201
- if (utf8Length(JSON.stringify(document)) > MAX_EDITOR_FILE_BYTES)
322
+ if (jsonLength(document)[0] > MAX_EDITOR_FILE_BYTES)
202
323
  throw new EditorError("too_large", "Editor document exceeds the 128 MiB file limit", "validate");
203
324
  }
204
325
  /**
@@ -33,8 +33,9 @@ export declare const EASINGS: {
33
33
  * The keyframe at `from` moved to `to`, clamped a tick inside its neighbours so keyframe order
34
34
  * never changes. Returns the value and where the keyframe landed.
35
35
  *
36
- * Throws when `value` is not keyframed or has no keyframe at `from`; the other keyframe-editing
37
- * functions below throw in the same cases.
36
+ * Throws when `value` is not keyframed or has no keyframe at `from`, an `EditorError`
37
+ * (`data_bound`) when it follows a data set; the other keyframe-editing functions below throw in
38
+ * the same cases.
38
39
  */
39
40
  export declare function moveKeyframe<T>(value: Animated<T>, from: number, to: number): {
40
41
  readonly value: Animated<T>;
@@ -1,3 +1,4 @@
1
+ import { EditorError } from "./document.js";
1
2
  /** Common easing curves, as CSS names them. */
2
3
  export const EASINGS = {
3
4
  ease_in: { type: "cubic_bezier", x1: 0.42, y1: 0, x2: 1, y2: 1 },
@@ -5,6 +6,8 @@ export const EASINGS = {
5
6
  ease_in_out: { type: "cubic_bezier", x1: 0.42, y1: 0, x2: 0.58, y2: 1 },
6
7
  };
7
8
  function keyframesOf(value) {
9
+ if (value.mode === "data")
10
+ throw new EditorError("data_bound", `The value follows data set ${value.data}; bake it to edit its keyframes`, "keyframes", value.data);
8
11
  if (value.mode !== "keyframes")
9
12
  throw new Error("the value has no keyframes");
10
13
  return [...value.keyframes];
@@ -19,8 +22,9 @@ function indexAt(keys, time) {
19
22
  * The keyframe at `from` moved to `to`, clamped a tick inside its neighbours so keyframe order
20
23
  * never changes. Returns the value and where the keyframe landed.
21
24
  *
22
- * Throws when `value` is not keyframed or has no keyframe at `from`; the other keyframe-editing
23
- * functions below throw in the same cases.
25
+ * Throws when `value` is not keyframed or has no keyframe at `from`, an `EditorError`
26
+ * (`data_bound`) when it follows a data set; the other keyframe-editing functions below throw in
27
+ * the same cases.
24
28
  */
25
29
  export function moveKeyframe(value, from, to) {
26
30
  const keys = keyframesOf(value);
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Whether `a` and `b` serialize to the same JSON text: arrays item by item, objects key by key in
3
+ * order. Shared parts compare by identity, so the cost is the unshared part up to the first
4
+ * difference.
5
+ */
6
+ export declare function sameJson(a: unknown, b: unknown): boolean;
@@ -0,0 +1,42 @@
1
+ /** Keys `JSON.stringify` writes for `value`, in order. */
2
+ function serializedKeys(value) {
3
+ return Object.keys(value).filter((key) => {
4
+ const field = value[key];
5
+ return field !== undefined && typeof field !== "function";
6
+ });
7
+ }
8
+ /**
9
+ * Whether `a` and `b` serialize to the same JSON text: arrays item by item, objects key by key in
10
+ * order. Shared parts compare by identity, so the cost is the unshared part up to the first
11
+ * difference.
12
+ */
13
+ export function sameJson(a, b) {
14
+ if (a === b)
15
+ return true;
16
+ if (a === null ||
17
+ b === null ||
18
+ typeof a !== "object" ||
19
+ typeof b !== "object")
20
+ return (a ?? null) === (b ?? null);
21
+ if (Array.isArray(a)) {
22
+ if (!Array.isArray(b) || a.length !== b.length)
23
+ return false;
24
+ for (let index = 0; index < a.length; index++)
25
+ if (!sameJson(a[index] ?? null, b[index] ?? null))
26
+ return false;
27
+ return true;
28
+ }
29
+ if (Array.isArray(b))
30
+ return false;
31
+ const keys = serializedKeys(a);
32
+ const other = serializedKeys(b);
33
+ if (keys.length !== other.length)
34
+ return false;
35
+ for (let index = 0; index < keys.length; index++) {
36
+ const key = keys[index];
37
+ if (key !== other[index] ||
38
+ !sameJson(a[key], b[key]))
39
+ return false;
40
+ }
41
+ return true;
42
+ }
@@ -1,4 +1,6 @@
1
- import type { Clip } from "alpha2/project";
1
+ import type { Clip, Project } from "alpha2/project";
2
+ import type { AppliedEdit, EditReport, EditRequest } from "alpha2/apply-edit";
3
+ import type { ExtractResult } from "alpha2/extractor";
2
4
  import type { EditorDocument, Result } from "./document.js";
3
5
  import type { Command } from "./commands.js";
4
6
  /** An immutable view of an {@link EditorSession}; a new object after every change. */
@@ -18,6 +20,35 @@ export interface EditorSnapshot {
18
20
  readonly generation: number;
19
21
  readonly canUndo: boolean;
20
22
  readonly canRedo: boolean;
23
+ /** The label of the step `undo` would take back, when it was applied with one. */
24
+ readonly undoLabel: string | undefined;
25
+ /** The label of the step `redo` would apply again, when it was applied with one. */
26
+ readonly redoLabel: string | undefined;
27
+ }
28
+ /**
29
+ * Which committed document an edit operation was computed from ({@link EditorSession.editProject}).
30
+ * It pins that document object, so any later commit, data included, makes it stale.
31
+ */
32
+ export interface EditRead {
33
+ readonly document: EditorDocument;
34
+ }
35
+ /**
36
+ * The timeline an extraction read ({@link EditorSession.extractionProject}). It holds the
37
+ * projection's JSON without data sets, so data applied in between does not make it stale.
38
+ */
39
+ export interface ExtractionRead {
40
+ readonly timeline: string;
41
+ }
42
+ /** How {@link EditorSession.applyEdit} applies a result. */
43
+ export interface ApplyEditOptions {
44
+ /** From the `editProject()` the result was computed from. */
45
+ readonly read: EditRead;
46
+ /** The operation that made the result; its `op` is the default history label. */
47
+ readonly request: EditRequest;
48
+ /** Commands run on the edited document in the same undo step, such as a `data.remove`. */
49
+ readonly then?: readonly Command[];
50
+ /** The history label of the step. */
51
+ readonly label?: string;
21
52
  }
22
53
  /**
23
54
  * Holds an editor document with undo history, selection, clipboard and pointer gestures. Every
@@ -62,9 +93,55 @@ export declare class EditorSession {
62
93
  /**
63
94
  * Runs `command` on the committed document and commits the result as one undo step, cancelling an
64
95
  * active gesture first. A refusal is returned, not thrown, and leaves the session unchanged. A
65
- * command that changes nothing also leaves it unchanged and keeps the redo history.
96
+ * command whose result serializes like the committed document leaves it unchanged too (history,
97
+ * redo and `revision` included) and returns the committed document.
66
98
  */
67
99
  dispatch(command: Command): Result<EditorDocument>;
100
+ /**
101
+ * The committed project, for the runtime to compute an edit operation from (`client.edit` in
102
+ * `@alpha2-sh/node`, `applyEdit` from `alpha2/apply-edit`), and the read that pins it for
103
+ * {@link applyEdit}. The project is the stored one, disabled tracks included.
104
+ */
105
+ editProject(): {
106
+ readonly project: Project;
107
+ readonly read: EditRead;
108
+ };
109
+ /**
110
+ * Commits an edit operation's result (`AppliedEdit`) as one undo step, with `then` run on the
111
+ * edited document in the same step, cancelling an active gesture first. Returns the document and
112
+ * the operation's report.
113
+ *
114
+ * Refusals leave the session unchanged. They are `invalid_command` without `read`, `stale_edit`
115
+ * when the committed document is no longer the one `read` pinned (compute again from a new
116
+ * `editProject()`), and those of `executeEditResult` (`locked`, `invalid_result`, a refused
117
+ * `then` command).
118
+ */
119
+ applyEdit(applied: AppliedEdit, options: ApplyEditOptions): Result<{
120
+ readonly document: EditorDocument;
121
+ readonly report: EditReport;
122
+ }>;
123
+ /**
124
+ * The project an extraction reads (what the engine renders of the committed document) and the
125
+ * read {@link applyExtraction} checks a timeline-anchored result against.
126
+ */
127
+ extractionProject(): {
128
+ readonly project: Project;
129
+ readonly read: ExtractionRead;
130
+ };
131
+ /**
132
+ * Puts an extraction's data sets in the document as one undo step (a `data.put` for each,
133
+ * replacing sets with their ids), cancelling an active gesture first. Returns the document,
134
+ * unchanged (and no step added) for a result without sets or with sets equal to the ones held.
135
+ *
136
+ * Refusals leave the session unchanged. They are `missing_asset` for a source-anchored set
137
+ * whose source is gone, `invalid_command` for a timeline-anchored set without `read`,
138
+ * `stale_extraction` when the timeline changed since the read (data put in between does not
139
+ * count), and those of `data.put`.
140
+ */
141
+ applyExtraction(result: ExtractResult, options?: {
142
+ readonly read?: ExtractionRead;
143
+ readonly label?: string;
144
+ }): Result<EditorDocument>;
68
145
  /**
69
146
  * Replaces the document, clearing history, selection and clipboard and increasing `generation`.
70
147
  * Throws an `EditorError` when `document` does not validate, leaving the session unchanged.
@@ -102,8 +179,9 @@ export declare class EditorSession {
102
179
  copy(ids?: readonly string[]): void;
103
180
  /**
104
181
  * Inserts the clipboard's clips on their original tracks as one undo step, the earliest at tick
105
- * `at` and the rest at their offsets from it. New clip ids come from `idFactory`. With nothing
106
- * copied it returns the document unchanged.
182
+ * `at` and the rest at their offsets from it. New clip ids come from `idFactory`; a pasted clip's
183
+ * bindings that read through itself read through its new id (`withClipId`). With nothing copied
184
+ * it returns the document unchanged.
107
185
  */
108
186
  paste(at: number, idFactory?: () => string): Result<EditorDocument>;
109
187
  /**
@@ -115,9 +193,9 @@ export declare class EditorSession {
115
193
  * Starts a pointer gesture, cancelling an active one. Each `update` runs a command on the
116
194
  * gesture's starting document and, when valid, shows the result as the snapshot's `draft` without
117
195
  * touching history. `commit` validates the last candidate fully and commits it as one undo step,
118
- * returning whether anything was committed; `cancel` discards it. A commit, cancel, dispatch,
119
- * undo, redo, open, dispose or new `beginGesture` ends the gesture, after which `update` returns
120
- * `stale_gesture`.
196
+ * returning whether anything was committed (nothing is when the candidate serializes like the
197
+ * starting document); `cancel` discards it. A commit, cancel, dispatch, undo, redo, open, dispose
198
+ * or new `beginGesture` ends the gesture, after which `update` returns `stale_gesture`.
121
199
  */
122
200
  beginGesture(): {
123
201
  readonly candidate: EditorDocument;
@@ -1,7 +1,9 @@
1
+ import { withClipId } from "alpha2/edit";
1
2
  import { compositionTree } from "./compositions.js";
2
- import { createEmptyDocument, validateDocument, withInstanceIds, canonicalDocument, indexDocument, inheritDocumentIndex, EditorError, } from "./document.js";
3
- import { executeCommand } from "./commands.js";
3
+ import { compileEditorDocument, createEmptyDocument, validateDocument, withInstanceIds, canonicalDocument, indexDocument, inheritDocumentIndex, EditorError, } from "./document.js";
4
+ import { executeCommand, executeEditResult } from "./commands.js";
4
5
  import { frozenValid, owned } from "./validated.js";
6
+ import { sameJson } from "./sameness.js";
5
7
  /**
6
8
  * Holds an editor document with undo history, selection, clipboard and pointer gestures. Every
7
9
  * document it holds is frozen; edits produce new documents through {@link Command}s. Methods other
@@ -102,6 +104,12 @@ export class EditorSession {
102
104
  generation: this.#generation,
103
105
  canUndo: this.#undo.length > 0,
104
106
  canRedo: this.#redo.length > 0,
107
+ undoLabel: this.#undo.length
108
+ ? this.#labels.get(this.#document)
109
+ : undefined,
110
+ redoLabel: this.#redo.length
111
+ ? this.#labels.get(this.#redo[this.#redo.length - 1])
112
+ : undefined,
105
113
  });
106
114
  }
107
115
  #emit() {
@@ -136,7 +144,11 @@ export class EditorSession {
136
144
  this.#undo.shift();
137
145
  }
138
146
  }
139
- #commit(document) {
147
+ /** History labels, by the document the labelled step made. */
148
+ #labels = new WeakMap();
149
+ #commit(document, label) {
150
+ if (label !== undefined)
151
+ this.#labels.set(document, label);
140
152
  inheritDocumentIndex(this.#document, document);
141
153
  this.#undo.push(this.#document);
142
154
  this.#trimHistory(document);
@@ -161,16 +173,103 @@ export class EditorSession {
161
173
  /**
162
174
  * Runs `command` on the committed document and commits the result as one undo step, cancelling an
163
175
  * active gesture first. A refusal is returned, not thrown, and leaves the session unchanged. A
164
- * command that changes nothing also leaves it unchanged and keeps the redo history.
176
+ * command whose result serializes like the committed document leaves it unchanged too (history,
177
+ * redo and `revision` included) and returns the committed document.
165
178
  */
166
179
  dispatch(command) {
167
180
  this.#active();
168
181
  this.#cancelGesture?.();
169
182
  const result = this.canExecute(command);
170
- if (result.ok && result.value !== this.#document)
171
- this.#commit(result.value);
183
+ if (!result.ok)
184
+ return result;
185
+ if (sameJson(result.value, this.#document))
186
+ return { ok: true, value: this.#document };
187
+ this.#commit(result.value);
172
188
  return result;
173
189
  }
190
+ /**
191
+ * The committed project, for the runtime to compute an edit operation from (`client.edit` in
192
+ * `@alpha2-sh/node`, `applyEdit` from `alpha2/apply-edit`), and the read that pins it for
193
+ * {@link applyEdit}. The project is the stored one, disabled tracks included.
194
+ */
195
+ editProject() {
196
+ this.#active();
197
+ const document = this.#document;
198
+ return { project: document.project, read: Object.freeze({ document }) };
199
+ }
200
+ /**
201
+ * Commits an edit operation's result (`AppliedEdit`) as one undo step, with `then` run on the
202
+ * edited document in the same step, cancelling an active gesture first. Returns the document and
203
+ * the operation's report.
204
+ *
205
+ * Refusals leave the session unchanged. They are `invalid_command` without `read`, `stale_edit`
206
+ * when the committed document is no longer the one `read` pinned (compute again from a new
207
+ * `editProject()`), and those of `executeEditResult` (`locked`, `invalid_result`, a refused
208
+ * `then` command).
209
+ */
210
+ applyEdit(applied, options) {
211
+ this.#active();
212
+ this.#cancelGesture?.();
213
+ if (!options?.read)
214
+ return refused("invalid_command", "applyEdit needs the read of the editProject() the result was computed from");
215
+ if (options.read.document !== this.#document)
216
+ return refused("stale_edit", "The document changed after the edit was computed; compute it again");
217
+ const result = executeEditResult(this.#document, applied, options.then);
218
+ if (!result.ok)
219
+ return result;
220
+ this.#commit(result.value, options.label ?? options.request.op);
221
+ return {
222
+ ok: true,
223
+ value: { document: result.value, report: applied.report },
224
+ };
225
+ }
226
+ /**
227
+ * The project an extraction reads (what the engine renders of the committed document) and the
228
+ * read {@link applyExtraction} checks a timeline-anchored result against.
229
+ */
230
+ extractionProject() {
231
+ this.#active();
232
+ const { project } = compileEditorDocument(this.#document);
233
+ return { project, read: Object.freeze({ timeline: withoutData(project) }) };
234
+ }
235
+ /**
236
+ * Puts an extraction's data sets in the document as one undo step (a `data.put` for each,
237
+ * replacing sets with their ids), cancelling an active gesture first. Returns the document,
238
+ * unchanged (and no step added) for a result without sets or with sets equal to the ones held.
239
+ *
240
+ * Refusals leave the session unchanged. They are `missing_asset` for a source-anchored set
241
+ * whose source is gone, `invalid_command` for a timeline-anchored set without `read`,
242
+ * `stale_extraction` when the timeline changed since the read (data put in between does not
243
+ * count), and those of `data.put`.
244
+ */
245
+ applyExtraction(result, options = {}) {
246
+ this.#active();
247
+ this.#cancelGesture?.();
248
+ const sets = result.dataSets;
249
+ if (!sets.length)
250
+ return { ok: true, value: this.#document };
251
+ const sources = new Set(this.#document.project.sources.map((s) => s.id));
252
+ const lost = sets.find((set) => set.anchor.type === "source" && !sources.has(set.anchor.source_id));
253
+ if (lost?.anchor.type === "source")
254
+ return refused("missing_asset", `Source ${lost.anchor.source_id} was removed after the extraction read it`, "extract", lost.anchor.source_id);
255
+ if (sets.some((set) => set.anchor.type === "timeline")) {
256
+ if (!options.read)
257
+ return refused("invalid_command", "A timeline-anchored result needs the read of the extractionProject() it came from", "extract");
258
+ const now = withoutData(compileEditorDocument(this.#document).project);
259
+ if (now !== options.read.timeline)
260
+ return refused("stale_extraction", "The timeline changed after the extraction read it; run it again", "extract");
261
+ }
262
+ const applied = executeCommand(this.#document, {
263
+ type: "transaction",
264
+ commands: sets.map((dataSet) => ({ type: "data.put", dataSet })),
265
+ });
266
+ if (!applied.ok)
267
+ return applied;
268
+ if (sameJson(applied.value, this.#document))
269
+ return { ok: true, value: this.#document };
270
+ this.#commit(applied.value, options.label ?? "extract");
271
+ return applied;
272
+ }
174
273
  /**
175
274
  * Replaces the document, clearing history, selection and clipboard and increasing `generation`.
176
275
  * Throws an `EditorError` when `document` does not validate, leaving the session unchanged.
@@ -270,8 +369,9 @@ export class EditorSession {
270
369
  }
271
370
  /**
272
371
  * Inserts the clipboard's clips on their original tracks as one undo step, the earliest at tick
273
- * `at` and the rest at their offsets from it. New clip ids come from `idFactory`. With nothing
274
- * copied it returns the document unchanged.
372
+ * `at` and the rest at their offsets from it. New clip ids come from `idFactory`; a pasted clip's
373
+ * bindings that read through itself read through its new id (`withClipId`). With nothing copied
374
+ * it returns the document unchanged.
275
375
  */
276
376
  paste(at, idFactory = () => crypto.randomUUID()) {
277
377
  this.#active();
@@ -285,7 +385,7 @@ export class EditorSession {
285
385
  commands.push({
286
386
  type: "clip.insert",
287
387
  trackId,
288
- clip: { ...clip, id },
388
+ clip: withClipId(clip, id),
289
389
  ...(name ? { name } : {}),
290
390
  ...(compositions.length ? { compositions } : {}),
291
391
  });
@@ -309,9 +409,9 @@ export class EditorSession {
309
409
  * Starts a pointer gesture, cancelling an active one. Each `update` runs a command on the
310
410
  * gesture's starting document and, when valid, shows the result as the snapshot's `draft` without
311
411
  * touching history. `commit` validates the last candidate fully and commits it as one undo step,
312
- * returning whether anything was committed; `cancel` discards it. A commit, cancel, dispatch,
313
- * undo, redo, open, dispose or new `beginGesture` ends the gesture, after which `update` returns
314
- * `stale_gesture`.
412
+ * returning whether anything was committed (nothing is when the candidate serializes like the
413
+ * starting document); `cancel` discards it. A commit, cancel, dispatch, undo, redo, open, dispose
414
+ * or new `beginGesture` ends the gesture, after which `update` returns `stale_gesture`.
315
415
  */
316
416
  beginGesture() {
317
417
  this.#active();
@@ -357,7 +457,7 @@ export class EditorSession {
357
457
  return false;
358
458
  const value = candidate;
359
459
  const hadDraft = end();
360
- if (value === base) {
460
+ if (sameJson(value, base)) {
361
461
  if (hadDraft)
362
462
  this.#emit();
363
463
  return false;
@@ -414,6 +514,17 @@ export class EditorSession {
414
514
  return this.#disposal;
415
515
  }
416
516
  }
517
+ function refused(code, message, operation = "edit", entityId) {
518
+ return {
519
+ ok: false,
520
+ error: new EditorError(code, message, operation, entityId),
521
+ };
522
+ }
523
+ /** `project` as JSON without its data sets. */
524
+ function withoutData(project) {
525
+ const { data: _data, ...rest } = project;
526
+ return JSON.stringify(rest);
527
+ }
417
528
  /** Creates an {@link EditorSession}; see its constructor for the options and their defaults. */
418
529
  export function createEditor(options = {}) {
419
530
  return new EditorSession(options.document, options.historyLimit, options.historyByteLimit);
package/dist/index.d.ts CHANGED
@@ -6,6 +6,7 @@ export * from "./core/clip-time.js";
6
6
  export * from "./core/session.js";
7
7
  export * from "./core/timeline-index.js";
8
8
  export * from "./core/keyframes.js";
9
+ export { dataValue, isDataBound, type DataBoundValue, type DataValueOptions, } from "./core/data.js";
9
10
  export * from "./core/presets.js";
10
11
  export * from "./core/captions.js";
11
12
  export * from "./core/text.js";
package/dist/index.js CHANGED
@@ -6,6 +6,7 @@ export * from "./core/clip-time.js";
6
6
  export * from "./core/session.js";
7
7
  export * from "./core/timeline-index.js";
8
8
  export * from "./core/keyframes.js";
9
+ export { dataValue, isDataBound, } from "./core/data.js";
9
10
  export * from "./core/presets.js";
10
11
  export * from "./core/captions.js";
11
12
  export * from "./core/text.js";
@@ -91,8 +91,8 @@ export interface NativeClientOptions {
91
91
  readonly fetch?: typeof fetch;
92
92
  }
93
93
  /**
94
- * A client for the native export service (`@alpha2-sh/node`'s HTTP host). Exports run with the
95
- * editor's retry policy; each job uploads its assets once and reuses them across attempts.
94
+ * A client for an HTTP export service the application runs. Exports run with the editor's retry
95
+ * policy; each job uploads its assets once and reuses them across attempts.
96
96
  */
97
97
  export declare function createNativeClient(options: NativeClientOptions): {
98
98
  /** The service's `/health` report. Rejects when the service answers with an error status. */