@agentic-canvas/media 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/NOTICE +10 -0
- package/README.md +20 -2
- package/dist/index.d.ts +162 -0
- package/dist/index.js +942 -0
- package/dist/index.js.map +1 -0
- package/package.json +26 -3
package/dist/index.js
ADDED
|
@@ -0,0 +1,942 @@
|
|
|
1
|
+
// packages/media/src/assets.ts
|
|
2
|
+
import { isAssetPurpose } from "@agentic-canvas/core";
|
|
3
|
+
var messages = {
|
|
4
|
+
INVALID_REQUEST: "Invalid asset request.",
|
|
5
|
+
INVALID_URI: "Asset source is not an allowed HTTP(S) or opted-in blob URI.",
|
|
6
|
+
ORIGIN_DENIED: "Asset origin is not allowed by the host.",
|
|
7
|
+
RESOLUTION_FAILED: "Asset resolution failed.",
|
|
8
|
+
ABORTED: "Asset resolution was cancelled."
|
|
9
|
+
};
|
|
10
|
+
var AssetLoadError = class extends Error {
|
|
11
|
+
code;
|
|
12
|
+
constructor(code) {
|
|
13
|
+
super(messages[code]);
|
|
14
|
+
this.name = "AssetLoadError";
|
|
15
|
+
this.code = code;
|
|
16
|
+
}
|
|
17
|
+
};
|
|
18
|
+
var unsafeCharacters = /[\u0000-\u001f\u007f\\]/u;
|
|
19
|
+
var isHttp = (url) => url.protocol === "http:" || url.protocol === "https:";
|
|
20
|
+
function baseUrl(value) {
|
|
21
|
+
try {
|
|
22
|
+
const source = value ?? globalThis.location?.href ?? "https://acc.invalid/";
|
|
23
|
+
if (unsafeCharacters.test(source)) throw new Error();
|
|
24
|
+
const url = new URL(source);
|
|
25
|
+
if (!isHttp(url) || url.username || url.password) throw new Error();
|
|
26
|
+
return url;
|
|
27
|
+
} catch {
|
|
28
|
+
throw new TypeError("Asset loader requires an HTTP(S) base URL without credentials.");
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
function allowedOrigins(values) {
|
|
32
|
+
if (values === void 0) return void 0;
|
|
33
|
+
if (!Array.isArray(values)) throw new TypeError("Asset origins must be an array of exact HTTP(S) origins.");
|
|
34
|
+
const result = /* @__PURE__ */ new Set();
|
|
35
|
+
for (const value of values) {
|
|
36
|
+
try {
|
|
37
|
+
if (typeof value !== "string" || !value.trim() || unsafeCharacters.test(value) || value.includes("*")) throw new Error();
|
|
38
|
+
const url = new URL(value);
|
|
39
|
+
if (!isHttp(url) || url.username || url.password || url.pathname !== "/" || url.search || url.hash) throw new Error();
|
|
40
|
+
result.add(url.origin);
|
|
41
|
+
} catch {
|
|
42
|
+
throw new TypeError("Asset origins must be exact HTTP(S) origins without paths or credentials.");
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
return result;
|
|
46
|
+
}
|
|
47
|
+
function cloneReference(value) {
|
|
48
|
+
if (value === void 0) return void 0;
|
|
49
|
+
if (!value || typeof value !== "object" || typeof value.assetId !== "string" || !value.assetId.trim() || value.versionId !== void 0 && typeof value.versionId !== "string" || value.uri !== void 0 && typeof value.uri !== "string") throw new AssetLoadError("INVALID_REQUEST");
|
|
50
|
+
return { assetId: value.assetId, ...value.versionId === void 0 ? {} : { versionId: value.versionId }, ...value.uri === void 0 ? {} : { uri: value.uri } };
|
|
51
|
+
}
|
|
52
|
+
function releaseOnce(value) {
|
|
53
|
+
let released = false;
|
|
54
|
+
let release;
|
|
55
|
+
try {
|
|
56
|
+
if (value && typeof value === "object" && "release" in value) {
|
|
57
|
+
const cleanup = value.release;
|
|
58
|
+
if (typeof cleanup === "function") release = cleanup.bind(value);
|
|
59
|
+
}
|
|
60
|
+
} catch {
|
|
61
|
+
}
|
|
62
|
+
return () => {
|
|
63
|
+
if (released) return;
|
|
64
|
+
released = true;
|
|
65
|
+
try {
|
|
66
|
+
const result = release?.();
|
|
67
|
+
if (result && typeof result.then === "function") void Promise.resolve(result).catch(() => {
|
|
68
|
+
});
|
|
69
|
+
} catch {
|
|
70
|
+
}
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
function createAssetLoader(options = {}) {
|
|
74
|
+
const base = baseUrl(options.baseUrl);
|
|
75
|
+
const origins = allowedOrigins(options.allowedOrigins);
|
|
76
|
+
const { resolver, allowBlob = false } = options;
|
|
77
|
+
function resolveUri(source) {
|
|
78
|
+
if (typeof source !== "string" || !source.trim() || unsafeCharacters.test(source)) throw new AssetLoadError("INVALID_URI");
|
|
79
|
+
let url;
|
|
80
|
+
try {
|
|
81
|
+
url = new URL(source, base);
|
|
82
|
+
} catch {
|
|
83
|
+
throw new AssetLoadError("INVALID_URI");
|
|
84
|
+
}
|
|
85
|
+
if (url.username || url.password) throw new AssetLoadError("INVALID_URI");
|
|
86
|
+
if (url.protocol === "blob:" && allowBlob) {
|
|
87
|
+
let embedded;
|
|
88
|
+
try {
|
|
89
|
+
embedded = new URL(url.pathname);
|
|
90
|
+
} catch {
|
|
91
|
+
throw new AssetLoadError("INVALID_URI");
|
|
92
|
+
}
|
|
93
|
+
if (!isHttp(embedded) || embedded.username || embedded.password || url.origin === "null") throw new AssetLoadError("INVALID_URI");
|
|
94
|
+
} else if (!isHttp(url)) throw new AssetLoadError("INVALID_URI");
|
|
95
|
+
if (origins && !origins.has(url.origin)) throw new AssetLoadError("ORIGIN_DENIED");
|
|
96
|
+
return url.href;
|
|
97
|
+
}
|
|
98
|
+
return {
|
|
99
|
+
resolve(request) {
|
|
100
|
+
return new Promise((resolve, reject) => {
|
|
101
|
+
const controller = new AbortController();
|
|
102
|
+
let settled = false;
|
|
103
|
+
const signal = request?.signal;
|
|
104
|
+
const removeListener = () => signal?.removeEventListener("abort", cancel);
|
|
105
|
+
const fail = (error) => {
|
|
106
|
+
if (settled) return;
|
|
107
|
+
settled = true;
|
|
108
|
+
removeListener();
|
|
109
|
+
reject(error);
|
|
110
|
+
};
|
|
111
|
+
const cancel = () => {
|
|
112
|
+
controller.abort();
|
|
113
|
+
fail(new AssetLoadError("ABORTED"));
|
|
114
|
+
};
|
|
115
|
+
if (signal?.aborted) {
|
|
116
|
+
cancel();
|
|
117
|
+
return;
|
|
118
|
+
}
|
|
119
|
+
signal?.addEventListener("abort", cancel, { once: true });
|
|
120
|
+
let reference;
|
|
121
|
+
let purpose;
|
|
122
|
+
let src;
|
|
123
|
+
try {
|
|
124
|
+
if (!request || !isAssetPurpose(request.purpose) || request.src !== void 0 && typeof request.src !== "string") throw new AssetLoadError("INVALID_REQUEST");
|
|
125
|
+
reference = cloneReference(request.assetRef);
|
|
126
|
+
purpose = request.purpose;
|
|
127
|
+
src = request.src;
|
|
128
|
+
} catch {
|
|
129
|
+
fail(new AssetLoadError("INVALID_REQUEST"));
|
|
130
|
+
return;
|
|
131
|
+
}
|
|
132
|
+
void Promise.resolve().then(() => {
|
|
133
|
+
if (controller.signal.aborted) throw new AssetLoadError("ABORTED");
|
|
134
|
+
if (reference && resolver) return resolver.resolve(reference, { purpose, signal: controller.signal });
|
|
135
|
+
return { uri: src !== void 0 ? src : reference?.uri ?? "" };
|
|
136
|
+
}).then((result) => {
|
|
137
|
+
const release = releaseOnce(result);
|
|
138
|
+
if (settled || controller.signal.aborted) {
|
|
139
|
+
release();
|
|
140
|
+
return;
|
|
141
|
+
}
|
|
142
|
+
try {
|
|
143
|
+
const uri = resolveUri(result?.uri);
|
|
144
|
+
const mimeType = result?.mimeType;
|
|
145
|
+
if (mimeType !== void 0 && (typeof mimeType !== "string" || !mimeType.trim() || unsafeCharacters.test(mimeType))) throw new AssetLoadError("INVALID_URI");
|
|
146
|
+
const lease = Object.freeze({ uri, ...mimeType === void 0 ? {} : { mimeType }, dispose: release });
|
|
147
|
+
settled = true;
|
|
148
|
+
removeListener();
|
|
149
|
+
resolve(lease);
|
|
150
|
+
} catch (error) {
|
|
151
|
+
release();
|
|
152
|
+
fail(error instanceof AssetLoadError ? error : new AssetLoadError("INVALID_URI"));
|
|
153
|
+
}
|
|
154
|
+
}, () => fail(new AssetLoadError(controller.signal.aborted ? "ABORTED" : "RESOLUTION_FAILED")));
|
|
155
|
+
});
|
|
156
|
+
}
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
// packages/media/src/scheduler.ts
|
|
161
|
+
import { isActiveResourceKind } from "@agentic-canvas/core";
|
|
162
|
+
function budget(value) {
|
|
163
|
+
if (!Number.isSafeInteger(value) || value < 0) throw new TypeError("Activation budgets must be nonnegative safe integers.");
|
|
164
|
+
return value;
|
|
165
|
+
}
|
|
166
|
+
function createActivationScheduler(options = {}) {
|
|
167
|
+
const maxActive = budget(options.maxActive ?? 1);
|
|
168
|
+
const perKind = /* @__PURE__ */ new Map();
|
|
169
|
+
for (const [kind, value] of Object.entries(options.perKind ?? {})) {
|
|
170
|
+
if (!isActiveResourceKind(kind)) throw new TypeError("Unknown activation resource kind.");
|
|
171
|
+
if (value !== void 0) perKind.set(kind, budget(value));
|
|
172
|
+
}
|
|
173
|
+
const entries = /* @__PURE__ */ new Map();
|
|
174
|
+
let disposed = false;
|
|
175
|
+
let busy = false;
|
|
176
|
+
let generation = 0;
|
|
177
|
+
function cleanup(entry) {
|
|
178
|
+
try {
|
|
179
|
+
const result = entry.onEvict();
|
|
180
|
+
if (result && typeof result.then === "function") void Promise.resolve(result).catch(() => {
|
|
181
|
+
});
|
|
182
|
+
} catch {
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
function evict(entry) {
|
|
186
|
+
if (!entry.active) return;
|
|
187
|
+
if (entries.get(entry.id) === entry) entries.delete(entry.id);
|
|
188
|
+
entry.active = false;
|
|
189
|
+
cleanup(entry);
|
|
190
|
+
}
|
|
191
|
+
function clear() {
|
|
192
|
+
generation++;
|
|
193
|
+
const wasBusy = busy;
|
|
194
|
+
busy = true;
|
|
195
|
+
const pending = [...entries.values()];
|
|
196
|
+
entries.clear();
|
|
197
|
+
for (const entry of pending) entry.active = false;
|
|
198
|
+
try {
|
|
199
|
+
for (const entry of pending) cleanup(entry);
|
|
200
|
+
} finally {
|
|
201
|
+
busy = wasBusy;
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
return {
|
|
205
|
+
request(input) {
|
|
206
|
+
if (disposed || busy) return null;
|
|
207
|
+
if (!input) throw new TypeError("Invalid activation request.");
|
|
208
|
+
const { id, kind, onEvict } = input;
|
|
209
|
+
if (typeof id !== "string" || !id.trim() || !isActiveResourceKind(kind) || typeof onEvict !== "function") throw new TypeError("Invalid activation request.");
|
|
210
|
+
const kindBudget = perKind.get(kind) ?? Infinity;
|
|
211
|
+
if (!maxActive || !kindBudget) return null;
|
|
212
|
+
busy = true;
|
|
213
|
+
const started = generation;
|
|
214
|
+
const cancelled = () => disposed || generation !== started;
|
|
215
|
+
try {
|
|
216
|
+
const sameId = entries.get(id);
|
|
217
|
+
if (sameId) evict(sameId);
|
|
218
|
+
if (cancelled()) return null;
|
|
219
|
+
while ([...entries.values()].filter((entry2) => entry2.kind === kind).length >= kindBudget) {
|
|
220
|
+
const oldest = [...entries.values()].find((entry2) => entry2.kind === kind);
|
|
221
|
+
evict(oldest);
|
|
222
|
+
if (cancelled()) return null;
|
|
223
|
+
}
|
|
224
|
+
while (entries.size >= maxActive) {
|
|
225
|
+
evict(entries.values().next().value);
|
|
226
|
+
if (cancelled()) return null;
|
|
227
|
+
}
|
|
228
|
+
const entry = { id, kind, active: true, onEvict };
|
|
229
|
+
entries.set(entry.id, entry);
|
|
230
|
+
return Object.freeze({
|
|
231
|
+
get active() {
|
|
232
|
+
return entry.active;
|
|
233
|
+
},
|
|
234
|
+
release() {
|
|
235
|
+
if (entries.get(entry.id) === entry) entries.delete(entry.id);
|
|
236
|
+
entry.active = false;
|
|
237
|
+
}
|
|
238
|
+
});
|
|
239
|
+
} finally {
|
|
240
|
+
busy = false;
|
|
241
|
+
}
|
|
242
|
+
},
|
|
243
|
+
getSnapshot() {
|
|
244
|
+
return [...entries.values()].map(({ id, kind }) => ({ id, kind }));
|
|
245
|
+
},
|
|
246
|
+
clear,
|
|
247
|
+
dispose() {
|
|
248
|
+
if (disposed) return;
|
|
249
|
+
disposed = true;
|
|
250
|
+
clear();
|
|
251
|
+
}
|
|
252
|
+
};
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
// packages/media/src/video.ts
|
|
256
|
+
function createVideoSession(video, options) {
|
|
257
|
+
let state = { phase: "preview" };
|
|
258
|
+
let current = null, owner = null;
|
|
259
|
+
let visible = true, disposed = false, generation = 0, notifying = 0, transitioning = 0;
|
|
260
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
261
|
+
const copy = () => ({ ...state, ...state.error ? { error: { ...state.error } } : {} });
|
|
262
|
+
const safely = (action) => {
|
|
263
|
+
try {
|
|
264
|
+
action();
|
|
265
|
+
} catch {
|
|
266
|
+
}
|
|
267
|
+
};
|
|
268
|
+
function release(action) {
|
|
269
|
+
transitioning++;
|
|
270
|
+
try {
|
|
271
|
+
safely(action);
|
|
272
|
+
} finally {
|
|
273
|
+
transitioning--;
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
function publish(next) {
|
|
277
|
+
if (JSON.stringify(state) === JSON.stringify(next)) return;
|
|
278
|
+
state = next;
|
|
279
|
+
const version = state;
|
|
280
|
+
notifying++;
|
|
281
|
+
try {
|
|
282
|
+
for (const listener of [...listeners]) {
|
|
283
|
+
if (state !== version) break;
|
|
284
|
+
safely(() => listener(copy()));
|
|
285
|
+
}
|
|
286
|
+
} finally {
|
|
287
|
+
notifying--;
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
function clearElement() {
|
|
291
|
+
safely(() => video.pause());
|
|
292
|
+
video.removeAttribute("src");
|
|
293
|
+
for (const source of video.querySelectorAll("source")) source.removeAttribute("src");
|
|
294
|
+
safely(() => {
|
|
295
|
+
video.srcObject = null;
|
|
296
|
+
});
|
|
297
|
+
safely(() => video.load());
|
|
298
|
+
}
|
|
299
|
+
function cleanup(operation) {
|
|
300
|
+
transitioning++;
|
|
301
|
+
try {
|
|
302
|
+
operation.detachAbort?.();
|
|
303
|
+
operation.detachAbort = void 0;
|
|
304
|
+
operation.detachError?.();
|
|
305
|
+
operation.detachError = void 0;
|
|
306
|
+
safely(() => operation.controller.abort());
|
|
307
|
+
if (owner === operation) {
|
|
308
|
+
owner = null;
|
|
309
|
+
clearElement();
|
|
310
|
+
}
|
|
311
|
+
const asset = operation.asset, activation = operation.activation;
|
|
312
|
+
operation.asset = void 0;
|
|
313
|
+
operation.activation = void 0;
|
|
314
|
+
operation.settle(false);
|
|
315
|
+
if (asset) safely(() => asset.dispose());
|
|
316
|
+
if (activation) safely(() => activation.release());
|
|
317
|
+
} finally {
|
|
318
|
+
transitioning--;
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
function cancel(next) {
|
|
322
|
+
const version = ++generation, previous = current;
|
|
323
|
+
current = null;
|
|
324
|
+
if (previous) cleanup(previous);
|
|
325
|
+
if (generation === version) publish(next);
|
|
326
|
+
}
|
|
327
|
+
function live(operation) {
|
|
328
|
+
return !disposed && visible && current === operation && !operation.controller.signal.aborted;
|
|
329
|
+
}
|
|
330
|
+
function fail(operation, code) {
|
|
331
|
+
if (!live(operation)) return;
|
|
332
|
+
const messages2 = {
|
|
333
|
+
ASSET_ERROR: "\u89C6\u9891\u7D20\u6750\u65E0\u6CD5\u89E3\u6790\u3002",
|
|
334
|
+
BUDGET_EXCEEDED: "\u6D3B\u52A8\u5A92\u4F53\u8D44\u6E90\u9884\u7B97\u4E0D\u53EF\u7528\u3002",
|
|
335
|
+
LOAD_FAILED: "\u89C6\u9891\u52A0\u8F7D\u5931\u8D25\u3002",
|
|
336
|
+
PLAYBACK_FAILED: "\u89C6\u9891\u65E0\u6CD5\u64AD\u653E\u3002"
|
|
337
|
+
};
|
|
338
|
+
cancel({ phase: "failed", id: operation.id, error: { code, message: messages2[code] } });
|
|
339
|
+
}
|
|
340
|
+
function start(operation, request) {
|
|
341
|
+
void Promise.resolve().then(() => {
|
|
342
|
+
if (!live(operation)) return null;
|
|
343
|
+
return options.assets.resolve({ purpose: "video", assetRef: request.assetRef ? { ...request.assetRef } : void 0, src: request.src, signal: operation.controller.signal });
|
|
344
|
+
}).then((asset) => {
|
|
345
|
+
if (!asset) return;
|
|
346
|
+
if (!live(operation)) {
|
|
347
|
+
release(() => asset.dispose());
|
|
348
|
+
return;
|
|
349
|
+
}
|
|
350
|
+
operation.asset = asset;
|
|
351
|
+
if (typeof asset.uri !== "string" || asset.uri.trim() === "") {
|
|
352
|
+
fail(operation, "ASSET_ERROR");
|
|
353
|
+
return;
|
|
354
|
+
}
|
|
355
|
+
const failed = () => fail(operation, "LOAD_FAILED");
|
|
356
|
+
video.addEventListener("error", failed);
|
|
357
|
+
operation.detachError = () => video.removeEventListener("error", failed);
|
|
358
|
+
owner = operation;
|
|
359
|
+
try {
|
|
360
|
+
video.muted = options.muted ?? true;
|
|
361
|
+
video.loop = options.loop ?? false;
|
|
362
|
+
video.srcObject = null;
|
|
363
|
+
video.setAttribute("src", asset.uri);
|
|
364
|
+
video.load();
|
|
365
|
+
} catch {
|
|
366
|
+
fail(operation, "LOAD_FAILED");
|
|
367
|
+
return;
|
|
368
|
+
}
|
|
369
|
+
if (!live(operation)) return;
|
|
370
|
+
let playback;
|
|
371
|
+
try {
|
|
372
|
+
playback = Promise.resolve(video.play());
|
|
373
|
+
} catch {
|
|
374
|
+
fail(operation, "PLAYBACK_FAILED");
|
|
375
|
+
return;
|
|
376
|
+
}
|
|
377
|
+
void playback.then(() => {
|
|
378
|
+
if (!live(operation)) return;
|
|
379
|
+
publish({ phase: "active", id: operation.id });
|
|
380
|
+
if (live(operation)) operation.settle(true);
|
|
381
|
+
}, () => fail(operation, "PLAYBACK_FAILED"));
|
|
382
|
+
}, () => fail(operation, "ASSET_ERROR"));
|
|
383
|
+
}
|
|
384
|
+
return {
|
|
385
|
+
activate(request) {
|
|
386
|
+
if (disposed || notifying || transitioning) return Promise.resolve(false);
|
|
387
|
+
const input = { id: request.id, src: request.src, signal: request.signal, assetRef: request.assetRef ? { ...request.assetRef } : void 0 };
|
|
388
|
+
const version = ++generation, previous = current;
|
|
389
|
+
current = null;
|
|
390
|
+
if (previous) cleanup(previous);
|
|
391
|
+
if (version !== generation || disposed || !visible || input.signal?.aborted) {
|
|
392
|
+
if (version === generation && !disposed) publish({ phase: "preview" });
|
|
393
|
+
return Promise.resolve(false);
|
|
394
|
+
}
|
|
395
|
+
let settled = false, resolve;
|
|
396
|
+
const promise = new Promise((accept) => {
|
|
397
|
+
resolve = accept;
|
|
398
|
+
});
|
|
399
|
+
const operation = {
|
|
400
|
+
id: input.id,
|
|
401
|
+
controller: new AbortController(),
|
|
402
|
+
promise,
|
|
403
|
+
settle(value) {
|
|
404
|
+
if (!settled) {
|
|
405
|
+
settled = true;
|
|
406
|
+
resolve(value);
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
};
|
|
410
|
+
current = operation;
|
|
411
|
+
if (input.signal) {
|
|
412
|
+
const abort = () => {
|
|
413
|
+
if (current === operation) cancel({ phase: "preview" });
|
|
414
|
+
};
|
|
415
|
+
input.signal.addEventListener("abort", abort, { once: true });
|
|
416
|
+
operation.detachAbort = () => input.signal.removeEventListener("abort", abort);
|
|
417
|
+
}
|
|
418
|
+
let activation;
|
|
419
|
+
try {
|
|
420
|
+
activation = options.scheduler.request({ id: input.id, kind: "video", onEvict: () => {
|
|
421
|
+
if (current === operation) cancel({ phase: "preview" });
|
|
422
|
+
} });
|
|
423
|
+
} catch {
|
|
424
|
+
activation = null;
|
|
425
|
+
}
|
|
426
|
+
if (!live(operation)) {
|
|
427
|
+
if (activation) release(() => activation.release());
|
|
428
|
+
operation.settle(false);
|
|
429
|
+
return promise;
|
|
430
|
+
}
|
|
431
|
+
operation.activation = activation ?? void 0;
|
|
432
|
+
if (!activation || !activation.active) {
|
|
433
|
+
fail(operation, "BUDGET_EXCEEDED");
|
|
434
|
+
return promise;
|
|
435
|
+
}
|
|
436
|
+
publish({ phase: "loading", id: input.id });
|
|
437
|
+
if (live(operation)) start(operation, input);
|
|
438
|
+
return promise;
|
|
439
|
+
},
|
|
440
|
+
deactivate() {
|
|
441
|
+
if (!disposed) cancel({ phase: "preview" });
|
|
442
|
+
},
|
|
443
|
+
setVisible(value) {
|
|
444
|
+
if (disposed || visible === value) return;
|
|
445
|
+
visible = value;
|
|
446
|
+
cancel({ phase: "preview" });
|
|
447
|
+
},
|
|
448
|
+
getState: copy,
|
|
449
|
+
subscribe(listener) {
|
|
450
|
+
if (disposed) return () => {
|
|
451
|
+
};
|
|
452
|
+
listeners.add(listener);
|
|
453
|
+
return () => {
|
|
454
|
+
listeners.delete(listener);
|
|
455
|
+
};
|
|
456
|
+
},
|
|
457
|
+
dispose() {
|
|
458
|
+
if (disposed) return;
|
|
459
|
+
disposed = true;
|
|
460
|
+
cancel({ phase: "disposed" });
|
|
461
|
+
listeners.clear();
|
|
462
|
+
}
|
|
463
|
+
};
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
// packages/media/src/audio.ts
|
|
467
|
+
var AUDIO_TYPE = "audio";
|
|
468
|
+
var AUDIO_VERSION = 1;
|
|
469
|
+
var AUDIO_PEAKS = 96;
|
|
470
|
+
var PROP_KEYS = ["title", "duration", "peaks", "loop", "src"];
|
|
471
|
+
function validateAudio(object) {
|
|
472
|
+
const errors = [];
|
|
473
|
+
const issue = (path, message) => {
|
|
474
|
+
errors.push({ path, message });
|
|
475
|
+
};
|
|
476
|
+
const props2 = object.props;
|
|
477
|
+
if (object.typeVersion !== AUDIO_VERSION) issue("typeVersion", `audio v${AUDIO_VERSION} is required`);
|
|
478
|
+
for (const key of Object.keys(props2)) if (!PROP_KEYS.includes(key)) issue(`props.${key}`, "Unknown audio property");
|
|
479
|
+
if (!object.assetRef && typeof props2.src !== "string") issue("assetRef", "An audio object needs an asset or a src");
|
|
480
|
+
if (props2.src !== void 0 && (typeof props2.src !== "string" || !props2.src)) issue("props.src", "src is a URL");
|
|
481
|
+
if (typeof props2.title !== "string" || props2.title.length > 200) issue("props.title", "A title of at most 200 characters is required");
|
|
482
|
+
if (typeof props2.duration !== "number" || !Number.isFinite(props2.duration) || props2.duration < 0 || props2.duration > 86400) issue("props.duration", "Duration is 0\u201386400 seconds");
|
|
483
|
+
if (!Array.isArray(props2.peaks) || props2.peaks.length > AUDIO_PEAKS * 4 || !props2.peaks.every((value) => typeof value === "number" && Number.isFinite(value) && value >= 0 && value <= 1)) issue("props.peaks", `Up to ${AUDIO_PEAKS * 4} peaks in 0\u20131`);
|
|
484
|
+
if (props2.loop !== void 0 && typeof props2.loop !== "boolean") issue("props.loop", "loop is a boolean");
|
|
485
|
+
return errors.length ? { valid: false, errors } : { valid: true };
|
|
486
|
+
}
|
|
487
|
+
var audioDefinition = Object.freeze({
|
|
488
|
+
type: AUDIO_TYPE,
|
|
489
|
+
version: AUDIO_VERSION,
|
|
490
|
+
capabilities: Object.freeze({ create: true, update: true, delete: true, transform: true }),
|
|
491
|
+
validate: validateAudio
|
|
492
|
+
});
|
|
493
|
+
var escape = (text) => text.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
|
|
494
|
+
var props = (object) => object.props;
|
|
495
|
+
function formatAudioTime(seconds) {
|
|
496
|
+
const s = Math.max(0, Math.floor(seconds)), h = Math.floor(s / 3600), m = Math.floor(s / 60) % 60, rest = String(s % 60).padStart(2, "0");
|
|
497
|
+
return h ? `${h}:${String(m).padStart(2, "0")}:${rest}` : `${m}:${rest}`;
|
|
498
|
+
}
|
|
499
|
+
function audioLayout(width, height) {
|
|
500
|
+
const pad = Math.max(8, Math.min(20, height * 0.14)), icon = Math.max(16, Math.min(56, height - pad * 2, width * 0.25));
|
|
501
|
+
const left = pad * 2 + icon, font = Math.max(9, Math.min(16, height * 0.13));
|
|
502
|
+
const wave = { x: left, y: pad + font * 1.8, width: Math.max(1, width - left - pad), height: Math.max(1, height - pad * 2 - font * 1.8) };
|
|
503
|
+
return { pad, icon, left, font, wave };
|
|
504
|
+
}
|
|
505
|
+
function audioSvg(audio, width, height, options = {}) {
|
|
506
|
+
const { pad, icon, left, font, wave } = audioLayout(width, height);
|
|
507
|
+
const peaks = audio.peaks.length ? audio.peaks : new Array(AUDIO_PEAKS).fill(0.04);
|
|
508
|
+
const step = wave.width / peaks.length, mid = wave.y + wave.height / 2, played = (options.progress ?? 0) * peaks.length;
|
|
509
|
+
const bars = peaks.map((peak, i) => {
|
|
510
|
+
const h = Math.max(1.5, peak * wave.height);
|
|
511
|
+
return `<rect x="${(wave.x + i * step + step * 0.2).toFixed(2)}" y="${(mid - h / 2).toFixed(2)}" width="${Math.max(0.5, step * 0.6).toFixed(2)}" height="${h.toFixed(2)}" rx="${Math.min(1.5, step * 0.3).toFixed(2)}" fill="${i < played ? "#5b5bd6" : "#c9c6e0"}"/>`;
|
|
512
|
+
}).join("");
|
|
513
|
+
const cx = pad + icon / 2, cy = height / 2, r = icon / 2;
|
|
514
|
+
const glyph = options.playing ? `<rect x="${cx - r * 0.32}" y="${cy - r * 0.36}" width="${r * 0.22}" height="${r * 0.72}" rx="1" fill="#fff"/><rect x="${cx + r * 0.1}" y="${cy - r * 0.36}" width="${r * 0.22}" height="${r * 0.72}" rx="1" fill="#fff"/>` : `<path d="M${cx - r * 0.26} ${cy - r * 0.4} L${cx + r * 0.42} ${cy} L${cx - r * 0.26} ${cy + r * 0.4} Z" fill="#fff"/>`;
|
|
515
|
+
const maxChars = Math.max(4, Math.floor((width - left - pad - font * (options.elapsed !== void 0 ? 7 : 4)) / (font * 0.9)));
|
|
516
|
+
const title = [...audio.title].length > maxChars ? `${[...audio.title].slice(0, maxChars - 1).join("")}\u2026` : audio.title;
|
|
517
|
+
return `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}" font-family="Inter, system-ui, sans-serif"><rect width="${width}" height="${height}" rx="${Math.min(12, height / 6)}" fill="#f4f3fa" stroke="#dedbeb"/><circle cx="${cx}" cy="${cy}" r="${r}" fill="#5b5bd6"/>${glyph}<text x="${left}" y="${pad + font}" font-size="${font}" font-weight="600" fill="#282538">${escape(title)}</text><text x="${width - pad}" y="${pad + font}" font-size="${font * 0.85}" text-anchor="end" fill="#7a738c">${options.elapsed !== void 0 ? `${formatAudioTime(options.elapsed)} / ` : ""}${formatAudioTime(audio.duration)}</text>` + bars + `</svg>`;
|
|
518
|
+
}
|
|
519
|
+
async function mountAudio(element, object, context) {
|
|
520
|
+
const source = props(object).src;
|
|
521
|
+
const lease = await context.assets.resolve({ purpose: AUDIO_TYPE, ...object.assetRef ? { assetRef: object.assetRef } : {}, ...source ? { src: source } : {}, signal: context.signal });
|
|
522
|
+
const doc = element.ownerDocument, root = doc.createElement("div"), audio = doc.createElement("audio");
|
|
523
|
+
root.className = "acc-audio-live";
|
|
524
|
+
root.style.cssText = "position:absolute;inset:0;cursor:pointer;user-select:none";
|
|
525
|
+
root.setAttribute("role", "group");
|
|
526
|
+
audio.preload = "auto";
|
|
527
|
+
audio.src = lease.uri;
|
|
528
|
+
let current = object, frame = 0;
|
|
529
|
+
audio.loop = props(current).loop === true;
|
|
530
|
+
root.append(audio);
|
|
531
|
+
element.append(root);
|
|
532
|
+
const draw = () => {
|
|
533
|
+
const width = Math.max(1, root.clientWidth), height = Math.max(1, root.clientHeight);
|
|
534
|
+
const duration = Number.isFinite(audio.duration) && audio.duration > 0 ? audio.duration : props(current).duration;
|
|
535
|
+
const svg = audioSvg(props(current), width, height, { progress: duration ? audio.currentTime / duration : 0, playing: !audio.paused, elapsed: audio.currentTime });
|
|
536
|
+
const holder = root.querySelector("svg");
|
|
537
|
+
if (holder) holder.outerHTML = svg;
|
|
538
|
+
else root.insertAdjacentHTML("afterbegin", svg);
|
|
539
|
+
root.setAttribute("aria-label", `${props(current).title} ${formatAudioTime(audio.currentTime)} / ${formatAudioTime(duration)}`);
|
|
540
|
+
};
|
|
541
|
+
const tick = () => {
|
|
542
|
+
draw();
|
|
543
|
+
frame = audio.paused ? 0 : requestAnimationFrame(tick);
|
|
544
|
+
};
|
|
545
|
+
const start = () => {
|
|
546
|
+
if (!frame) frame = requestAnimationFrame(tick);
|
|
547
|
+
};
|
|
548
|
+
audio.addEventListener("play", start);
|
|
549
|
+
audio.addEventListener("pause", draw);
|
|
550
|
+
audio.addEventListener("ended", draw);
|
|
551
|
+
audio.addEventListener("loadedmetadata", draw);
|
|
552
|
+
root.addEventListener("pointerdown", (event) => event.stopPropagation());
|
|
553
|
+
root.addEventListener("click", (event) => {
|
|
554
|
+
const rect = root.getBoundingClientRect(), { left, wave } = audioLayout(root.clientWidth, root.clientHeight);
|
|
555
|
+
const scale = rect.width / Math.max(1, root.clientWidth), x = (event.clientX - rect.left) / scale;
|
|
556
|
+
if (x >= left && Number.isFinite(audio.duration) && audio.duration > 0) {
|
|
557
|
+
audio.currentTime = Math.min(audio.duration, Math.max(0, (x - wave.x) / wave.width * audio.duration));
|
|
558
|
+
draw();
|
|
559
|
+
if (audio.paused) void audio.play().catch(() => {
|
|
560
|
+
});
|
|
561
|
+
} else if (audio.paused) void audio.play().catch(() => {
|
|
562
|
+
});
|
|
563
|
+
else audio.pause();
|
|
564
|
+
});
|
|
565
|
+
const view = doc.defaultView;
|
|
566
|
+
const observer = view && "ResizeObserver" in view ? new view.ResizeObserver(() => draw()) : void 0;
|
|
567
|
+
observer?.observe(root);
|
|
568
|
+
draw();
|
|
569
|
+
await audio.play().catch(() => {
|
|
570
|
+
});
|
|
571
|
+
return {
|
|
572
|
+
update(next) {
|
|
573
|
+
current = next;
|
|
574
|
+
audio.loop = props(next).loop === true;
|
|
575
|
+
draw();
|
|
576
|
+
},
|
|
577
|
+
resize() {
|
|
578
|
+
draw();
|
|
579
|
+
},
|
|
580
|
+
dispose() {
|
|
581
|
+
cancelAnimationFrame(frame);
|
|
582
|
+
observer?.disconnect();
|
|
583
|
+
audio.pause();
|
|
584
|
+
audio.removeAttribute("src");
|
|
585
|
+
audio.load();
|
|
586
|
+
root.remove();
|
|
587
|
+
lease.dispose();
|
|
588
|
+
}
|
|
589
|
+
};
|
|
590
|
+
}
|
|
591
|
+
var audioAdapter = Object.freeze({
|
|
592
|
+
definition: audioDefinition,
|
|
593
|
+
label: "\u97F3\u9891",
|
|
594
|
+
activateText: "\u64AD\u653E",
|
|
595
|
+
poster: async (object, context) => ({ kind: "svg", markup: audioSvg(props(object), context.width, context.height) }),
|
|
596
|
+
mount: mountAudio
|
|
597
|
+
});
|
|
598
|
+
function audioPeaks(channels, count = AUDIO_PEAKS) {
|
|
599
|
+
const length = Math.max(0, ...channels.map((channel) => channel.length));
|
|
600
|
+
if (!length) return new Array(count).fill(0);
|
|
601
|
+
const peaks = Array.from({ length: count }, (_, i) => {
|
|
602
|
+
const from = Math.floor(i * length / count), to = Math.max(from + 1, Math.floor((i + 1) * length / count));
|
|
603
|
+
let peak = 0;
|
|
604
|
+
for (const channel of channels) for (let k = from; k < to && k < channel.length; k++) {
|
|
605
|
+
const v = Math.abs(channel[k]);
|
|
606
|
+
if (v > peak) peak = v;
|
|
607
|
+
}
|
|
608
|
+
return peak;
|
|
609
|
+
});
|
|
610
|
+
const max = Math.max(...peaks);
|
|
611
|
+
return peaks.map((peak) => max > 0 ? Math.round(peak / max * 1e3) / 1e3 : 0);
|
|
612
|
+
}
|
|
613
|
+
|
|
614
|
+
// packages/media/src/image.ts
|
|
615
|
+
function createImageSession(image, options) {
|
|
616
|
+
let state = { phase: "preview" };
|
|
617
|
+
let current = null, owner = null;
|
|
618
|
+
let visible = true, disposed = false, generation = 0, notifying = 0, transitioning = 0;
|
|
619
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
620
|
+
const copy = () => ({ ...state, ...state.error ? { error: { ...state.error } } : {} });
|
|
621
|
+
const safely = (action) => {
|
|
622
|
+
try {
|
|
623
|
+
action();
|
|
624
|
+
} catch {
|
|
625
|
+
}
|
|
626
|
+
};
|
|
627
|
+
function release(action) {
|
|
628
|
+
transitioning++;
|
|
629
|
+
try {
|
|
630
|
+
safely(action);
|
|
631
|
+
} finally {
|
|
632
|
+
transitioning--;
|
|
633
|
+
}
|
|
634
|
+
}
|
|
635
|
+
function publish(next) {
|
|
636
|
+
if (JSON.stringify(state) === JSON.stringify(next)) return;
|
|
637
|
+
state = next;
|
|
638
|
+
const version = state;
|
|
639
|
+
notifying++;
|
|
640
|
+
try {
|
|
641
|
+
for (const listener of [...listeners]) {
|
|
642
|
+
if (state !== version) break;
|
|
643
|
+
safely(() => listener(copy()));
|
|
644
|
+
}
|
|
645
|
+
} finally {
|
|
646
|
+
notifying--;
|
|
647
|
+
}
|
|
648
|
+
}
|
|
649
|
+
function cleanup(operation) {
|
|
650
|
+
transitioning++;
|
|
651
|
+
try {
|
|
652
|
+
operation.detachAbort?.();
|
|
653
|
+
operation.detachAbort = void 0;
|
|
654
|
+
operation.detachEvents?.();
|
|
655
|
+
operation.detachEvents = void 0;
|
|
656
|
+
safely(() => operation.controller.abort());
|
|
657
|
+
if (owner === operation) {
|
|
658
|
+
owner = null;
|
|
659
|
+
image.removeAttribute("src");
|
|
660
|
+
image.removeAttribute("srcset");
|
|
661
|
+
}
|
|
662
|
+
const asset = operation.asset;
|
|
663
|
+
operation.asset = void 0;
|
|
664
|
+
operation.settle(false);
|
|
665
|
+
if (asset) safely(() => asset.dispose());
|
|
666
|
+
} finally {
|
|
667
|
+
transitioning--;
|
|
668
|
+
}
|
|
669
|
+
}
|
|
670
|
+
function cancel(next) {
|
|
671
|
+
const version = ++generation, previous = current;
|
|
672
|
+
current = null;
|
|
673
|
+
if (previous) cleanup(previous);
|
|
674
|
+
if (generation === version) publish(next);
|
|
675
|
+
}
|
|
676
|
+
function live(operation) {
|
|
677
|
+
return !disposed && visible && current === operation && !operation.controller.signal.aborted;
|
|
678
|
+
}
|
|
679
|
+
function fail(operation, code) {
|
|
680
|
+
if (live(operation)) cancel({ phase: "failed", id: operation.id, error: { code, message: code === "ASSET_ERROR" ? "\u56FE\u7247\u7D20\u6750\u65E0\u6CD5\u89E3\u6790\u3002" : "\u56FE\u7247\u52A0\u8F7D\u5931\u8D25\u3002" } });
|
|
681
|
+
}
|
|
682
|
+
function ready(operation) {
|
|
683
|
+
if (!live(operation)) return;
|
|
684
|
+
publish({ phase: "active", id: operation.id });
|
|
685
|
+
if (live(operation)) operation.settle(true);
|
|
686
|
+
}
|
|
687
|
+
function start(operation, request) {
|
|
688
|
+
void Promise.resolve().then(() => {
|
|
689
|
+
if (!live(operation)) return null;
|
|
690
|
+
return options.assets.resolve({ purpose: "image", assetRef: request.assetRef ? { ...request.assetRef } : void 0, src: request.src, signal: operation.controller.signal });
|
|
691
|
+
}).then((asset) => {
|
|
692
|
+
if (!asset) return;
|
|
693
|
+
if (!live(operation)) {
|
|
694
|
+
release(() => asset.dispose());
|
|
695
|
+
return;
|
|
696
|
+
}
|
|
697
|
+
operation.asset = asset;
|
|
698
|
+
if (typeof asset.uri !== "string" || asset.uri.trim() === "") {
|
|
699
|
+
fail(operation, "ASSET_ERROR");
|
|
700
|
+
return;
|
|
701
|
+
}
|
|
702
|
+
const supportsDecode = typeof image.decode === "function";
|
|
703
|
+
const loaded = () => {
|
|
704
|
+
if (!supportsDecode) ready(operation);
|
|
705
|
+
};
|
|
706
|
+
const failed = () => fail(operation, "LOAD_FAILED");
|
|
707
|
+
image.addEventListener("load", loaded);
|
|
708
|
+
image.addEventListener("error", failed);
|
|
709
|
+
operation.detachEvents = () => {
|
|
710
|
+
image.removeEventListener("load", loaded);
|
|
711
|
+
image.removeEventListener("error", failed);
|
|
712
|
+
};
|
|
713
|
+
owner = operation;
|
|
714
|
+
try {
|
|
715
|
+
image.removeAttribute("srcset");
|
|
716
|
+
image.setAttribute("src", asset.uri);
|
|
717
|
+
if (supportsDecode) {
|
|
718
|
+
void Promise.resolve(image.decode()).then(() => ready(operation), () => fail(operation, "LOAD_FAILED"));
|
|
719
|
+
} else if (image.complete && image.naturalWidth > 0) ready(operation);
|
|
720
|
+
} catch {
|
|
721
|
+
fail(operation, "LOAD_FAILED");
|
|
722
|
+
}
|
|
723
|
+
}, () => fail(operation, "ASSET_ERROR"));
|
|
724
|
+
}
|
|
725
|
+
return {
|
|
726
|
+
activate(request) {
|
|
727
|
+
if (disposed || notifying || transitioning) return Promise.resolve(false);
|
|
728
|
+
const input = { id: request.id, src: request.src, signal: request.signal, assetRef: request.assetRef ? { ...request.assetRef } : void 0 };
|
|
729
|
+
const version = ++generation, previous = current;
|
|
730
|
+
current = null;
|
|
731
|
+
if (previous) cleanup(previous);
|
|
732
|
+
if (version !== generation || disposed || !visible || input.signal?.aborted) {
|
|
733
|
+
if (version === generation && !disposed) publish({ phase: "preview" });
|
|
734
|
+
return Promise.resolve(false);
|
|
735
|
+
}
|
|
736
|
+
let settled = false, resolve;
|
|
737
|
+
const promise = new Promise((accept) => {
|
|
738
|
+
resolve = accept;
|
|
739
|
+
});
|
|
740
|
+
const operation = {
|
|
741
|
+
id: input.id,
|
|
742
|
+
controller: new AbortController(),
|
|
743
|
+
promise,
|
|
744
|
+
settle(value) {
|
|
745
|
+
if (!settled) {
|
|
746
|
+
settled = true;
|
|
747
|
+
resolve(value);
|
|
748
|
+
}
|
|
749
|
+
}
|
|
750
|
+
};
|
|
751
|
+
current = operation;
|
|
752
|
+
if (input.signal) {
|
|
753
|
+
const abort = () => {
|
|
754
|
+
if (current === operation) cancel({ phase: "preview" });
|
|
755
|
+
};
|
|
756
|
+
input.signal.addEventListener("abort", abort, { once: true });
|
|
757
|
+
operation.detachAbort = () => input.signal.removeEventListener("abort", abort);
|
|
758
|
+
}
|
|
759
|
+
publish({ phase: "loading", id: input.id });
|
|
760
|
+
if (live(operation)) start(operation, input);
|
|
761
|
+
return promise;
|
|
762
|
+
},
|
|
763
|
+
deactivate() {
|
|
764
|
+
if (!disposed) cancel({ phase: "preview" });
|
|
765
|
+
},
|
|
766
|
+
setVisible(value) {
|
|
767
|
+
if (disposed || visible === value) return;
|
|
768
|
+
visible = value;
|
|
769
|
+
cancel({ phase: "preview" });
|
|
770
|
+
},
|
|
771
|
+
getState: copy,
|
|
772
|
+
subscribe(listener) {
|
|
773
|
+
if (disposed) return () => {
|
|
774
|
+
};
|
|
775
|
+
listeners.add(listener);
|
|
776
|
+
return () => {
|
|
777
|
+
listeners.delete(listener);
|
|
778
|
+
};
|
|
779
|
+
},
|
|
780
|
+
dispose() {
|
|
781
|
+
if (disposed) return;
|
|
782
|
+
disposed = true;
|
|
783
|
+
cancel({ phase: "disposed" });
|
|
784
|
+
listeners.clear();
|
|
785
|
+
}
|
|
786
|
+
};
|
|
787
|
+
}
|
|
788
|
+
|
|
789
|
+
// packages/media/src/studio.ts
|
|
790
|
+
import {
|
|
791
|
+
checkStudioResult,
|
|
792
|
+
parseStudioMessage,
|
|
793
|
+
STUDIO_PROTOCOL,
|
|
794
|
+
studioFields
|
|
795
|
+
} from "@agentic-canvas/core";
|
|
796
|
+
function createWindowStudioChannel(target, origin, host = globalThis) {
|
|
797
|
+
return {
|
|
798
|
+
// An opaque-origin (sandboxed) frame can only be addressed with "*"; the message still goes to that one window.
|
|
799
|
+
post: (message) => target()?.postMessage(message, origin === "null" ? "*" : origin),
|
|
800
|
+
listen(handler) {
|
|
801
|
+
const listener = (event) => {
|
|
802
|
+
const studio = target();
|
|
803
|
+
handler({ origin: event.origin, fromStudio: !!studio && event.source === studio, data: event.data });
|
|
804
|
+
};
|
|
805
|
+
host.addEventListener("message", listener);
|
|
806
|
+
return () => host.removeEventListener("message", listener);
|
|
807
|
+
}
|
|
808
|
+
};
|
|
809
|
+
}
|
|
810
|
+
var terminal = (state) => ["committed", "cancelled", "removed", "failed"].includes(state.phase);
|
|
811
|
+
function openStudioSession(options) {
|
|
812
|
+
const { studio, channel, object } = options;
|
|
813
|
+
const id = options.sessionId ?? crypto.randomUUID().replace(/-/g, "");
|
|
814
|
+
const base = studioFields(studio, object);
|
|
815
|
+
let state = { phase: "opening" }, pending;
|
|
816
|
+
let ignored = 0, late = 0;
|
|
817
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
818
|
+
const set = (next) => {
|
|
819
|
+
state = next;
|
|
820
|
+
for (const listener of [...listeners]) listener(next);
|
|
821
|
+
};
|
|
822
|
+
const close = (reason) => {
|
|
823
|
+
try {
|
|
824
|
+
channel.post({ protocol: STUDIO_PROTOCOL, type: "close", sessionId: id, reason });
|
|
825
|
+
} catch {
|
|
826
|
+
}
|
|
827
|
+
};
|
|
828
|
+
const end = (next, reason) => {
|
|
829
|
+
clearTimeout(timer);
|
|
830
|
+
pending = void 0;
|
|
831
|
+
set(next);
|
|
832
|
+
close(reason);
|
|
833
|
+
};
|
|
834
|
+
const open = () => channel.post({ protocol: STUDIO_PROTOCOL, type: "open", sessionId: id, baseRevision: options.revision, object: structuredClone(object), ...options.media ? { media: options.media } : {} });
|
|
835
|
+
const apply = async (result, checkFields) => {
|
|
836
|
+
const before = options.current(object.id);
|
|
837
|
+
if (!before) return end({ phase: "removed" }, "removed");
|
|
838
|
+
if (checkFields && studioFields(studio, before) !== base) {
|
|
839
|
+
pending = result;
|
|
840
|
+
set({ phase: "conflict" });
|
|
841
|
+
return;
|
|
842
|
+
}
|
|
843
|
+
set({ phase: "committing" });
|
|
844
|
+
const refs = {};
|
|
845
|
+
try {
|
|
846
|
+
for (const asset of result.assets) refs[studio.assets[asset.slot].prop] = await options.storeAsset({ objectId: object.id, slot: asset.slot, mimeType: asset.mimeType, bytes: asset.bytes });
|
|
847
|
+
} catch (error) {
|
|
848
|
+
if (state.phase === "committing") end({ phase: "failed", code: "ASSET_STORE_FAILED", message: error instanceof Error ? error.message : String(error) }, "failed");
|
|
849
|
+
return;
|
|
850
|
+
}
|
|
851
|
+
if (state.phase !== "committing") return;
|
|
852
|
+
const now = options.current(object.id);
|
|
853
|
+
if (!now) return end({ phase: "removed" }, "removed");
|
|
854
|
+
if (checkFields && studioFields(studio, now) !== base) {
|
|
855
|
+
pending = result;
|
|
856
|
+
set({ phase: "conflict" });
|
|
857
|
+
return;
|
|
858
|
+
}
|
|
859
|
+
const committed = options.commit(object.id, { props: { ...result.props, ...refs } });
|
|
860
|
+
if (committed.ok) end({ phase: "committed", revision: committed.revision }, "committed");
|
|
861
|
+
else end({ phase: "failed", code: "COMMIT_REJECTED", message: committed.error.message }, "failed");
|
|
862
|
+
};
|
|
863
|
+
const unsubscribe = channel.listen((event) => {
|
|
864
|
+
const message = event.origin === studio.origin && event.fromStudio ? parseStudioMessage(event.data) : void 0;
|
|
865
|
+
if (!message || message.sessionId !== id) {
|
|
866
|
+
ignored++;
|
|
867
|
+
return;
|
|
868
|
+
}
|
|
869
|
+
if (terminal(state)) {
|
|
870
|
+
late++;
|
|
871
|
+
return;
|
|
872
|
+
}
|
|
873
|
+
if (message.type === "ready") {
|
|
874
|
+
if (state.phase === "opening") {
|
|
875
|
+
clearTimeout(timer);
|
|
876
|
+
set({ phase: "editing" });
|
|
877
|
+
}
|
|
878
|
+
open();
|
|
879
|
+
return;
|
|
880
|
+
}
|
|
881
|
+
if (message.type === "cancel") {
|
|
882
|
+
end({ phase: "cancelled", by: "studio" }, "cancelled");
|
|
883
|
+
return;
|
|
884
|
+
}
|
|
885
|
+
if (state.phase !== "editing") {
|
|
886
|
+
late++;
|
|
887
|
+
return;
|
|
888
|
+
}
|
|
889
|
+
if (message.baseRevision !== options.revision) return end({ phase: "failed", code: "STALE_SESSION", message: "The result is for another opening of this object" }, "failed");
|
|
890
|
+
const issues = checkStudioResult(studio, message);
|
|
891
|
+
if (issues.length) return end({ phase: "failed", code: "INVALID_RESULT", message: issues.map((issue) => `${issue.path}: ${issue.message}`).join("; "), issues }, "failed");
|
|
892
|
+
void apply(message, true);
|
|
893
|
+
});
|
|
894
|
+
const timer = setTimeout(() => {
|
|
895
|
+
if (state.phase === "opening") end({ phase: "failed", code: "STUDIO_TIMEOUT", message: `${studio.label} did not respond` }, "failed");
|
|
896
|
+
}, options.readyTimeoutMs ?? 15e3);
|
|
897
|
+
return {
|
|
898
|
+
id,
|
|
899
|
+
state: () => state,
|
|
900
|
+
subscribe(listener) {
|
|
901
|
+
listeners.add(listener);
|
|
902
|
+
return () => {
|
|
903
|
+
listeners.delete(listener);
|
|
904
|
+
};
|
|
905
|
+
},
|
|
906
|
+
cancel() {
|
|
907
|
+
if (!terminal(state)) end({ phase: "cancelled", by: "host" }, "cancelled");
|
|
908
|
+
},
|
|
909
|
+
resolveConflict(choice) {
|
|
910
|
+
if (state.phase !== "conflict" || !pending) return;
|
|
911
|
+
const result = pending;
|
|
912
|
+
pending = void 0;
|
|
913
|
+
if (choice === "discard") end({ phase: "cancelled", by: "host" }, "conflict");
|
|
914
|
+
else void apply(result, false);
|
|
915
|
+
},
|
|
916
|
+
stats: () => ({ ignored, late }),
|
|
917
|
+
dispose() {
|
|
918
|
+
if (!terminal(state)) end({ phase: "cancelled", by: "host" }, "cancelled");
|
|
919
|
+
clearTimeout(timer);
|
|
920
|
+
unsubscribe();
|
|
921
|
+
listeners.clear();
|
|
922
|
+
}
|
|
923
|
+
};
|
|
924
|
+
}
|
|
925
|
+
export {
|
|
926
|
+
AUDIO_PEAKS,
|
|
927
|
+
AUDIO_TYPE,
|
|
928
|
+
AUDIO_VERSION,
|
|
929
|
+
AssetLoadError,
|
|
930
|
+
audioAdapter,
|
|
931
|
+
audioDefinition,
|
|
932
|
+
audioPeaks,
|
|
933
|
+
audioSvg,
|
|
934
|
+
createActivationScheduler,
|
|
935
|
+
createAssetLoader,
|
|
936
|
+
createImageSession,
|
|
937
|
+
createVideoSession,
|
|
938
|
+
createWindowStudioChannel,
|
|
939
|
+
formatAudioTime,
|
|
940
|
+
openStudioSession
|
|
941
|
+
};
|
|
942
|
+
//# sourceMappingURL=index.js.map
|