@openbone/player 0.0.0-stage → 0.4.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/dist/audio.js ADDED
@@ -0,0 +1,439 @@
1
+ import { busGain } from "@openbone/core";
2
+ const isAbsolute = (src) => /^(data:|https?:|blob:|\/)/.test(src);
3
+ /**
4
+ * Plays the runtime's AudioCommands with the Web Audio API: resolves and decodes assets (cached per URL),
5
+ * routes each sound through its bus into the master, applies fades, and follows the document's mix
6
+ * (call `syncMix()` after changing bus/master values). Browsers block audio until a user gesture, so the
7
+ * context is resumed by the first pointer/key event (see `unlock`); one-shots requested before that are skipped.
8
+ */
9
+ export class WebAudioBackend {
10
+ doc;
11
+ opts;
12
+ ctx;
13
+ master = null;
14
+ buses = new Map();
15
+ buffers = new Map();
16
+ voices = new Map();
17
+ hostMuted = false;
18
+ unbind = null;
19
+ /** Looping sounds requested before audio was unlocked, by voice id; they start when the context runs. */
20
+ pending = new Map();
21
+ offline = null;
22
+ constructor(doc, opts = {}) {
23
+ this.doc = doc;
24
+ this.opts = opts;
25
+ this.ctx = opts.context ?? null;
26
+ if (this.ctx)
27
+ this.watch(this.ctx);
28
+ }
29
+ /** True once the browser lets the context play. */
30
+ get unlocked() {
31
+ return this.ctx?.state === "running";
32
+ }
33
+ get muted() {
34
+ return this.hostMuted;
35
+ }
36
+ /** Mute everything (independent of the document's own mute). */
37
+ setMuted(m) {
38
+ this.hostMuted = m;
39
+ this.syncMix();
40
+ }
41
+ setDocument(doc) {
42
+ this.doc = doc;
43
+ this.syncMix();
44
+ }
45
+ setBaseUrl(url) {
46
+ this.opts.baseUrl = url;
47
+ }
48
+ /** Create (if needed) and resume the context now. Call it from a user gesture (a click) so the browser allows sound. */
49
+ activate() {
50
+ const ctx = this.context();
51
+ if (ctx && ctx.state !== "running")
52
+ void ctx.resume();
53
+ return ctx;
54
+ }
55
+ context() {
56
+ if (this.ctx)
57
+ return this.ctx;
58
+ const Ctor = globalThis.AudioContext ?? globalThis.webkitAudioContext;
59
+ if (!Ctor)
60
+ return null;
61
+ this.ctx = new Ctor();
62
+ this.watch(this.ctx);
63
+ return this.ctx;
64
+ }
65
+ /** Start the loops that were waiting for audio once the context runs (whoever resumed it). */
66
+ watch(ctx) {
67
+ ctx.addEventListener?.("statechange", () => this.flushPending());
68
+ }
69
+ flushPending() {
70
+ if (this.ctx?.state !== "running" || !this.pending.size)
71
+ return;
72
+ const cmds = [...this.pending.values()];
73
+ this.pending.clear();
74
+ for (const cmd of cmds)
75
+ this.play(cmd);
76
+ }
77
+ /**
78
+ * Where sounds are decoded: the live context once it exists, else an OfflineAudioContext, which the browser allows
79
+ * without a user gesture (decoded buffers play in any context).
80
+ */
81
+ decoder() {
82
+ if (this.ctx)
83
+ return this.ctx;
84
+ if (!this.offline) {
85
+ const Offline = globalThis.OfflineAudioContext ?? globalThis.webkitOfflineAudioContext;
86
+ if (!Offline)
87
+ return this.context();
88
+ this.offline = new Offline(2, 1, 48000);
89
+ }
90
+ return this.offline;
91
+ }
92
+ masterNode(ctx) {
93
+ if (!this.master) {
94
+ this.master = ctx.createGain();
95
+ this.master.connect(ctx.destination);
96
+ this.syncMix();
97
+ }
98
+ return this.master;
99
+ }
100
+ busNode(ctx, busId) {
101
+ const master = this.masterNode(ctx);
102
+ if (!busId || !this.doc.audio?.buses.some((b) => b.id === busId))
103
+ return master;
104
+ let g = this.buses.get(busId);
105
+ if (!g) {
106
+ g = ctx.createGain();
107
+ g.connect(master);
108
+ this.buses.set(busId, g);
109
+ this.syncMix();
110
+ }
111
+ return g;
112
+ }
113
+ /** Mutes set while playing by "mix" commands (mute buttons): bus id, "" = master. They win over the document. */
114
+ mixMutes = new Map();
115
+ isMuted(busId) {
116
+ const key = busId ?? "";
117
+ if (this.mixMutes.has(key))
118
+ return this.mixMutes.get(key);
119
+ const a = this.doc.audio;
120
+ return busId === null ? !!a?.muted : !!a?.buses.find((b) => b.id === busId)?.muted;
121
+ }
122
+ /** Apply the document's master/bus volumes and mutes (and the host mute, and mute buttons) to the graph. */
123
+ syncMix() {
124
+ const ctx = this.ctx;
125
+ if (!ctx)
126
+ return;
127
+ const a = this.doc.audio;
128
+ const t = ctx.currentTime;
129
+ if (this.master)
130
+ this.master.gain.setTargetAtTime(this.hostMuted || this.isMuted(null) ? 0 : (a?.master ?? 1), t, 0.015);
131
+ for (const [id, g] of this.buses) {
132
+ const bus = a?.buses.find((b) => b.id === id);
133
+ g.gain.setTargetAtTime(bus ? (this.isMuted(id) ? 0 : bus.volume) : 1, t, 0.015);
134
+ }
135
+ }
136
+ /** Effective gain a sound on `busId` gets from the mix right now (master x bus, 0 when muted). */
137
+ busGain(busId) {
138
+ if (this.hostMuted || this.isMuted(null) || (busId !== null && this.isMuted(busId)))
139
+ return 0;
140
+ return busGain(this.doc, busId);
141
+ }
142
+ url(asset) {
143
+ if (this.opts.resolveUrl)
144
+ return this.opts.resolveUrl(asset);
145
+ return isAbsolute(asset.src) ? asset.src : (this.opts.baseUrl ?? "") + asset.src;
146
+ }
147
+ /** Fetch and decode an asset (cached by URL). */
148
+ load(asset) {
149
+ const url = this.url(asset);
150
+ let p = this.buffers.get(url);
151
+ if (!p) {
152
+ const ctx = this.decoder();
153
+ if (!ctx)
154
+ return Promise.resolve(null);
155
+ p = fetch(url)
156
+ .then((r) => {
157
+ if (!r.ok)
158
+ throw new Error(`${r.status}`);
159
+ return r.arrayBuffer();
160
+ })
161
+ .then((buf) => ctx.decodeAudioData(buf))
162
+ .catch((e) => {
163
+ this.opts.onLog?.(`could not load audio "${asset.name}": ${e.message}`);
164
+ this.buffers.delete(url);
165
+ return null;
166
+ });
167
+ this.buffers.set(url, p);
168
+ }
169
+ return p;
170
+ }
171
+ /** Start decoding every asset in the document. */
172
+ preload() {
173
+ return Promise.all((this.doc.audio?.assets ?? []).map((a) => this.load(a)));
174
+ }
175
+ /** Resume the context on the first user gesture on `target` (default: window). Safe to call more than once. */
176
+ unlock(target = globalThis) {
177
+ if (this.unbind || !target?.addEventListener)
178
+ return;
179
+ const evs = ["pointerdown", "keydown", "touchend"];
180
+ const go = () => {
181
+ const ctx = this.context();
182
+ if (!ctx)
183
+ return;
184
+ void ctx.resume().then(() => {
185
+ if (ctx.state === "running") {
186
+ this.opts.onLog?.("audio unlocked");
187
+ this.unbind?.();
188
+ }
189
+ });
190
+ };
191
+ for (const e of evs)
192
+ target.addEventListener(e, go, { capture: true });
193
+ this.unbind = () => {
194
+ for (const e of evs)
195
+ target.removeEventListener(e, go, { capture: true });
196
+ this.unbind = () => { };
197
+ };
198
+ }
199
+ /** Handle one runtime command. Pass this to `instance.on("audio", ...)`. */
200
+ handle = (cmd) => {
201
+ switch (cmd.type) {
202
+ case "play":
203
+ return this.play(cmd);
204
+ case "stop":
205
+ return this.stop(cmd.id, cmd.fade, cmd);
206
+ case "fade": {
207
+ const v = this.voices.get(cmd.id);
208
+ if (!v || !this.ctx)
209
+ return;
210
+ const t = this.ctx.currentTime;
211
+ v.gain.gain.cancelScheduledValues(t);
212
+ v.gain.gain.setValueAtTime(v.gain.gain.value, t);
213
+ v.gain.gain.linearRampToValueAtTime(cmd.volume, t + Math.max(0.005, cmd.duration));
214
+ this.opts.onLog?.(`fade ${cmd.id} → ${cmd.volume} over ${cmd.duration}s`, cmd);
215
+ return;
216
+ }
217
+ case "mix": {
218
+ this.mixMutes.set(cmd.bus ?? "", cmd.muted);
219
+ // Make sure the bus node exists so the mute applies to sounds started later too.
220
+ const ctx = this.ctx;
221
+ if (ctx && cmd.bus)
222
+ this.busNode(ctx, cmd.bus);
223
+ this.syncMix();
224
+ const name = cmd.bus === null ? "master" : (this.doc.audio?.buses.find((b) => b.id === cmd.bus)?.name ?? cmd.bus);
225
+ this.opts.onLog?.(`${cmd.muted ? "mute" : "unmute"} ${name}`, cmd);
226
+ return;
227
+ }
228
+ }
229
+ };
230
+ play(cmd) {
231
+ const asset = this.doc.audio?.assets.find((a) => a.id === cmd.asset);
232
+ // Never create the context here: before a user gesture the browser refuses it ("The AudioContext was not allowed
233
+ // to start"). It is created by unlock() / activate(), from a click or key press.
234
+ const ctx = this.ctx;
235
+ const name = this.doc.audio?.sounds.find((s) => s.id === cmd.sound)?.name ?? asset?.name ?? cmd.sound;
236
+ if (!asset) {
237
+ this.opts.onLog?.(`play ${name} skipped (asset missing)`, cmd);
238
+ return;
239
+ }
240
+ if (!ctx || ctx.state !== "running") {
241
+ // One-shots before the first gesture would all burst out at unlock time: drop them. Loops (music, ambience)
242
+ // wait and start when audio unlocks.
243
+ if (!cmd.loop) {
244
+ this.opts.onLog?.(`play ${name} skipped (audio locked until a click or key press)`, cmd);
245
+ return;
246
+ }
247
+ this.pending.set(cmd.id, cmd);
248
+ this.opts.onLog?.(`play ${name} [${cmd.id}] loop waits for audio to unlock`, cmd);
249
+ void this.load(asset);
250
+ return;
251
+ }
252
+ const gain = ctx.createGain();
253
+ gain.connect(this.busNode(ctx, cmd.bus));
254
+ const voice = { gain, source: null, stopped: false, rate: cmd.rate, loop: cmd.loop, startedAt: 0, offset: 0, paused: this.pausedAll ? 0 : null };
255
+ this.voices.set(cmd.id, voice);
256
+ this.opts.onLog?.(`play ${name} [${cmd.id}]${cmd.loop ? " loop" : ""} vol ${round(cmd.volume)} × bus ${round(this.busGain(cmd.bus))} rate ${cmd.rate} (${cmd.source})`, cmd);
257
+ void this.load(asset).then((buffer) => {
258
+ if (!buffer || voice.stopped) {
259
+ this.voices.delete(cmd.id);
260
+ gain.disconnect();
261
+ return;
262
+ }
263
+ voice.buffer = buffer;
264
+ const t = ctx.currentTime;
265
+ if (cmd.fadeIn > 0) {
266
+ gain.gain.setValueAtTime(0, t);
267
+ gain.gain.linearRampToValueAtTime(cmd.volume, t + cmd.fadeIn);
268
+ }
269
+ else
270
+ gain.gain.setValueAtTime(cmd.volume, t);
271
+ // Started while everything is paused: it waits at the beginning for resumeAll().
272
+ if (voice.paused === null)
273
+ this.startSource(cmd.id, voice, 0);
274
+ });
275
+ }
276
+ /** (Re)start a voice's buffer from `offset` seconds into the file, at the sound's rate × the backend's speed. */
277
+ startSource(id, voice, offset) {
278
+ const ctx = this.ctx;
279
+ if (!ctx || !voice.buffer)
280
+ return;
281
+ const src = ctx.createBufferSource();
282
+ src.buffer = voice.buffer;
283
+ src.loop = voice.loop;
284
+ src.playbackRate.value = voice.rate * this.speed;
285
+ src.connect(voice.gain);
286
+ src.onended = () => {
287
+ if (voice.source !== src)
288
+ return;
289
+ if (this.voices.get(id) === voice)
290
+ this.voices.delete(id);
291
+ voice.gain.disconnect();
292
+ };
293
+ voice.source = src;
294
+ voice.startedAt = ctx.currentTime;
295
+ voice.offset = offset;
296
+ voice.paused = null;
297
+ src.start(ctx.currentTime, Math.max(0, offset));
298
+ }
299
+ /** Where a voice is in its file now (seconds). */
300
+ position(v) {
301
+ if (v.paused !== null)
302
+ return v.paused;
303
+ const ctx = this.ctx;
304
+ if (!ctx || !v.buffer)
305
+ return 0;
306
+ const p = v.offset + (ctx.currentTime - v.startedAt) * v.rate * this.speed;
307
+ return v.loop ? p % v.buffer.duration : p;
308
+ }
309
+ speed = 1;
310
+ pausedAll = false;
311
+ /**
312
+ * Playback speed for everything this backend plays (sounds already playing change too), like a player's speed
313
+ * control: 2 plays twice as fast and an octave higher.
314
+ */
315
+ setSpeed(speed) {
316
+ const ctx = this.ctx;
317
+ for (const v of this.voices.values()) {
318
+ if (!v.source || !ctx)
319
+ continue;
320
+ // Keep the position continuous: restart the clock from here at the new rate.
321
+ v.offset = this.position(v);
322
+ v.startedAt = ctx.currentTime;
323
+ v.source.playbackRate.value = v.rate * speed;
324
+ }
325
+ this.speed = Math.max(0.05, speed);
326
+ }
327
+ /** Pause every voice where it is (resumeAll continues them from there). */
328
+ pauseAll() {
329
+ this.pausedAll = true;
330
+ for (const v of this.voices.values()) {
331
+ if (!v.source)
332
+ continue;
333
+ v.paused = this.position(v);
334
+ const src = v.source;
335
+ v.source = null;
336
+ try {
337
+ src.stop();
338
+ }
339
+ catch {
340
+ /* already stopped */
341
+ }
342
+ src.disconnect();
343
+ }
344
+ }
345
+ /** Continue every paused voice from where it was paused. */
346
+ resumeAll() {
347
+ this.pausedAll = false;
348
+ for (const [id, v] of [...this.voices]) {
349
+ if (v.paused === null || v.source)
350
+ continue;
351
+ if (!v.buffer) {
352
+ v.paused = null; // still loading: it starts when it arrives
353
+ continue;
354
+ }
355
+ if (!v.loop && v.paused >= v.buffer.duration - 0.005) {
356
+ this.voices.delete(id);
357
+ v.gain.disconnect();
358
+ continue;
359
+ }
360
+ this.startSource(id, v, v.paused);
361
+ }
362
+ }
363
+ /**
364
+ * A short grain of a sound at `offset` seconds into its file, for scrubbing a timeline: fades in and out over a few
365
+ * milliseconds so dragging sounds like a tape head rather than clicks.
366
+ */
367
+ scrub(assetId, offset, o = {}) {
368
+ const asset = this.doc.audio?.assets.find((a) => a.id === assetId);
369
+ const ctx = this.context();
370
+ if (!asset || !ctx || ctx.state !== "running")
371
+ return;
372
+ void this.load(asset).then((buffer) => {
373
+ if (!buffer || offset < 0 || offset >= buffer.duration)
374
+ return;
375
+ const dur = Math.min(o.duration ?? 0.09, buffer.duration - offset);
376
+ const g = ctx.createGain();
377
+ g.connect(this.busNode(ctx, o.bus ?? null));
378
+ const src = ctx.createBufferSource();
379
+ src.buffer = buffer;
380
+ src.playbackRate.value = (o.rate ?? 1) * this.speed;
381
+ src.connect(g);
382
+ const t = ctx.currentTime;
383
+ const v = o.volume ?? 1;
384
+ g.gain.setValueAtTime(0, t);
385
+ g.gain.linearRampToValueAtTime(v, t + 0.006);
386
+ g.gain.setValueAtTime(v, t + Math.max(0.007, dur - 0.012));
387
+ g.gain.linearRampToValueAtTime(0, t + dur);
388
+ src.onended = () => g.disconnect();
389
+ src.start(t, offset, dur + 0.01);
390
+ });
391
+ }
392
+ stop(id, fade, cmd) {
393
+ if (this.pending.delete(id))
394
+ this.opts.onLog?.(`stop [${id}] (had not started)`, cmd);
395
+ const v = this.voices.get(id);
396
+ if (!v)
397
+ return;
398
+ v.stopped = true;
399
+ this.voices.delete(id);
400
+ this.opts.onLog?.(`stop [${id}]${fade > 0 ? ` fade ${fade}s` : ""}`, cmd);
401
+ const ctx = this.ctx;
402
+ if (!ctx || !v.source) {
403
+ v.gain.disconnect();
404
+ return;
405
+ }
406
+ const t = ctx.currentTime;
407
+ v.gain.gain.cancelScheduledValues(t);
408
+ v.gain.gain.setValueAtTime(v.gain.gain.value, t);
409
+ if (fade > 0)
410
+ v.gain.gain.linearRampToValueAtTime(0, t + fade);
411
+ try {
412
+ v.source.stop(t + Math.max(0, fade));
413
+ }
414
+ catch {
415
+ /* already stopped */
416
+ }
417
+ }
418
+ /** Stop every voice (optionally fading). */
419
+ stopAll(fade = 0) {
420
+ this.pending.clear();
421
+ for (const id of [...this.voices.keys()])
422
+ this.stop(id, fade);
423
+ }
424
+ /** Number of voices currently playing or loading. */
425
+ get activeVoices() {
426
+ return this.voices.size;
427
+ }
428
+ dispose() {
429
+ this.stopAll();
430
+ this.unbind?.();
431
+ if (!this.opts.context)
432
+ void this.ctx?.close();
433
+ this.ctx = null;
434
+ this.master = null;
435
+ this.buses.clear();
436
+ this.buffers.clear();
437
+ }
438
+ }
439
+ const round = (n) => Math.round(n * 100) / 100;
@@ -0,0 +1,115 @@
1
+ /**
2
+ * Host bridge for embedding the player in a native WebView (Flutter, Android, iOS) or an iframe.
3
+ *
4
+ * Host → page: call `OpenBone.receive(json)` (or `OpenBone.setInput(...)` etc. directly) with a {@link BridgeCommand}.
5
+ * Page → host: JSON strings of {@link BridgeMessage}, posted to whichever channel exists:
6
+ * - `window.OpenBoneHost.postMessage(str)` Flutter `JavaScriptChannel` / Android `addJavascriptInterface`
7
+ * - `window.webkit.messageHandlers.openbone.postMessage(str)` iOS WKWebView
8
+ * - `window.parent.postMessage(obj, "*")` iframes (object, not string), when embedded
9
+ * - a `openbone-message` DOM event on `window` (detail = object), always
10
+ */
11
+ export declare const BRIDGE_VERSION = 1;
12
+ export type BridgeCommand = {
13
+ type: "setInput";
14
+ name: string;
15
+ value: boolean | number | string;
16
+ } | {
17
+ type: "fire";
18
+ name: string;
19
+ } | {
20
+ type: "play";
21
+ animation?: string;
22
+ loop?: boolean;
23
+ } | {
24
+ type: "pause";
25
+ } | {
26
+ type: "setSkin";
27
+ name: string | null;
28
+ } | {
29
+ type: "useStateMachine";
30
+ name?: string;
31
+ } | {
32
+ type: "getInputs";
33
+ } | {
34
+ type: "setMuted";
35
+ muted: boolean;
36
+ } | {
37
+ type: "setBusMuted";
38
+ bus: string | null;
39
+ muted: boolean | "toggle";
40
+ };
41
+ export interface BridgeInputInfo {
42
+ name: string;
43
+ type: "bool" | "number" | "trigger" | "string";
44
+ value: boolean | number | string | null;
45
+ }
46
+ export type BridgeMessage = {
47
+ type: "ready";
48
+ animations: string[];
49
+ stateMachines: string[];
50
+ inputs: BridgeInputInfo[];
51
+ skins: string[];
52
+ width: number;
53
+ height: number;
54
+ } | {
55
+ type: "event";
56
+ name: string;
57
+ int?: number;
58
+ float?: number;
59
+ string?: string;
60
+ time?: number;
61
+ } | {
62
+ type: "stateChange";
63
+ layer: string;
64
+ from: string | null;
65
+ to: string;
66
+ } | {
67
+ type: "inputs";
68
+ inputs: BridgeInputInfo[];
69
+ } | {
70
+ type: "error";
71
+ message: string;
72
+ };
73
+ /** Wire format of a page → host message: the message plus a source tag and protocol version. */
74
+ export type BridgeEnvelope = BridgeMessage & {
75
+ source: "openbone";
76
+ v: number;
77
+ };
78
+ export declare function encodeMessage(m: BridgeMessage): string;
79
+ /** Parse a host message string (for hosts written in JS, and tests). Returns null for anything that is not ours. */
80
+ export declare function decodeMessage(s: string): BridgeEnvelope | null;
81
+ /** Validate a command from the host (a JSON string or an object). Throws with a readable message when it is wrong. */
82
+ export declare function parseCommand(input: string | unknown): BridgeCommand;
83
+ /** What the bridge needs from a player (structural, so tests can pass a fake). */
84
+ export interface BridgePlayer {
85
+ setInput(name: string, value: boolean | number | string): void;
86
+ fire(name: string): void;
87
+ play(): void;
88
+ pause(): void;
89
+ playAnimation(name: string, loop?: boolean): void;
90
+ setSkin(name: string | null): void;
91
+ useStateMachine?(name?: string): void;
92
+ setMuted?(muted: boolean): void;
93
+ setBusMuted?(bus: string | null, muted: boolean | "toggle"): unknown;
94
+ inputs(): BridgeInputInfo[];
95
+ }
96
+ /** Run a validated command against a player. Returns a reply message for queries. */
97
+ export declare function applyCommand(p: BridgePlayer, c: BridgeCommand): BridgeMessage | null;
98
+ type PostTarget = {
99
+ postMessage(s: string): void;
100
+ };
101
+ interface HostWindow {
102
+ OpenBoneHost?: PostTarget;
103
+ webkit?: {
104
+ messageHandlers?: {
105
+ openbone?: PostTarget;
106
+ };
107
+ };
108
+ parent?: {
109
+ postMessage(m: unknown, origin: string): void;
110
+ } | null;
111
+ dispatchEvent?(e: Event): boolean;
112
+ }
113
+ /** Send a message to every host channel present on `w` (see the module comment). */
114
+ export declare function postToHost(m: BridgeMessage, w?: HostWindow): string;
115
+ export {};
package/dist/bridge.js ADDED
@@ -0,0 +1,126 @@
1
+ /**
2
+ * Host bridge for embedding the player in a native WebView (Flutter, Android, iOS) or an iframe.
3
+ *
4
+ * Host → page: call `OpenBone.receive(json)` (or `OpenBone.setInput(...)` etc. directly) with a {@link BridgeCommand}.
5
+ * Page → host: JSON strings of {@link BridgeMessage}, posted to whichever channel exists:
6
+ * - `window.OpenBoneHost.postMessage(str)` Flutter `JavaScriptChannel` / Android `addJavascriptInterface`
7
+ * - `window.webkit.messageHandlers.openbone.postMessage(str)` iOS WKWebView
8
+ * - `window.parent.postMessage(obj, "*")` iframes (object, not string), when embedded
9
+ * - a `openbone-message` DOM event on `window` (detail = object), always
10
+ */
11
+ export const BRIDGE_VERSION = 1;
12
+ export function encodeMessage(m) {
13
+ return JSON.stringify({ source: "openbone", v: BRIDGE_VERSION, ...m });
14
+ }
15
+ /** Parse a host message string (for hosts written in JS, and tests). Returns null for anything that is not ours. */
16
+ export function decodeMessage(s) {
17
+ try {
18
+ const m = JSON.parse(s);
19
+ return m && m.source === "openbone" && typeof m.type === "string" ? m : null;
20
+ }
21
+ catch {
22
+ return null;
23
+ }
24
+ }
25
+ /** Validate a command from the host (a JSON string or an object). Throws with a readable message when it is wrong. */
26
+ export function parseCommand(input) {
27
+ const c = (typeof input === "string" ? JSON.parse(input) : input);
28
+ if (!c || typeof c !== "object" || typeof c.type !== "string")
29
+ throw new Error("OpenBone bridge: a command needs a string `type`");
30
+ const str = (k) => {
31
+ if (typeof c[k] !== "string" || !c[k])
32
+ throw new Error(`OpenBone bridge: "${c.type}" needs a string \`${k}\``);
33
+ return c[k];
34
+ };
35
+ switch (c.type) {
36
+ case "setInput": {
37
+ const v = c.value;
38
+ if (typeof v !== "boolean" && typeof v !== "string" && !(typeof v === "number" && Number.isFinite(v)))
39
+ throw new Error('OpenBone bridge: "setInput" needs a boolean, number or string `value`');
40
+ return { type: "setInput", name: str("name"), value: v };
41
+ }
42
+ case "fire":
43
+ return { type: "fire", name: str("name") };
44
+ case "play":
45
+ return {
46
+ type: "play",
47
+ ...(typeof c.animation === "string" ? { animation: c.animation } : {}),
48
+ ...(typeof c.loop === "boolean" ? { loop: c.loop } : {}),
49
+ };
50
+ case "pause":
51
+ case "getInputs":
52
+ return { type: c.type };
53
+ case "setSkin":
54
+ return { type: "setSkin", name: typeof c.name === "string" && c.name ? c.name : null };
55
+ case "useStateMachine":
56
+ return { type: "useStateMachine", ...(typeof c.name === "string" ? { name: c.name } : {}) };
57
+ case "setMuted":
58
+ if (typeof c.muted !== "boolean")
59
+ throw new Error('OpenBone bridge: "setMuted" needs a boolean `muted`');
60
+ return { type: "setMuted", muted: c.muted };
61
+ case "setBusMuted": {
62
+ const m = c.muted ?? true;
63
+ if (typeof m !== "boolean" && m !== "toggle")
64
+ throw new Error('OpenBone bridge: "setBusMuted" needs `muted`: true, false or "toggle"');
65
+ if (c.bus !== null && c.bus !== undefined && typeof c.bus !== "string")
66
+ throw new Error('OpenBone bridge: "setBusMuted" needs a string `bus` (or null for the master)');
67
+ return { type: "setBusMuted", bus: c.bus ?? null, muted: m };
68
+ }
69
+ default:
70
+ throw new Error(`OpenBone bridge: unknown command "${String(c.type)}"`);
71
+ }
72
+ }
73
+ /** Run a validated command against a player. Returns a reply message for queries. */
74
+ export function applyCommand(p, c) {
75
+ switch (c.type) {
76
+ case "setInput":
77
+ p.setInput(c.name, c.value);
78
+ return null;
79
+ case "fire":
80
+ p.fire(c.name);
81
+ return null;
82
+ case "play":
83
+ if (c.animation)
84
+ p.playAnimation(c.animation, c.loop ?? true);
85
+ p.play();
86
+ return null;
87
+ case "pause":
88
+ p.pause();
89
+ return null;
90
+ case "setSkin":
91
+ p.setSkin(c.name);
92
+ return null;
93
+ case "useStateMachine":
94
+ p.useStateMachine?.(c.name);
95
+ return null;
96
+ case "getInputs":
97
+ return { type: "inputs", inputs: p.inputs() };
98
+ case "setMuted":
99
+ p.setMuted?.(c.muted);
100
+ return null;
101
+ case "setBusMuted":
102
+ p.setBusMuted?.(c.bus, c.muted);
103
+ return null;
104
+ }
105
+ }
106
+ /** Send a message to every host channel present on `w` (see the module comment). */
107
+ export function postToHost(m, w = globalThis) {
108
+ const s = encodeMessage(m);
109
+ try {
110
+ w.OpenBoneHost?.postMessage(s);
111
+ }
112
+ catch {
113
+ /* host channel gone */
114
+ }
115
+ try {
116
+ w.webkit?.messageHandlers?.openbone?.postMessage(s);
117
+ }
118
+ catch {
119
+ /* host channel gone */
120
+ }
121
+ if (w.parent && w.parent !== w)
122
+ w.parent.postMessage(JSON.parse(s), "*");
123
+ if (w.dispatchEvent && typeof CustomEvent !== "undefined")
124
+ w.dispatchEvent(new CustomEvent("openbone-message", { detail: JSON.parse(s) }));
125
+ return s;
126
+ }