upnext-adapter-browser 0.1.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 ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,152 @@
1
+ # upnext-adapter-browser
2
+
3
+ [![npm](https://img.shields.io/npm/v/upnext-adapter-browser)](https://www.npmjs.com/package/upnext-adapter-browser)
4
+ [![license](https://img.shields.io/badge/license-Apache--2.0-blue)](https://github.com/tothienbao6a0/upnext/blob/main/LICENSE)
5
+
6
+ Plays audio through a media element you control, for
7
+ [**upnext-core**](https://www.npmjs.com/package/upnext-core) — in a browser, an
8
+ Electron renderer, or a webview.
9
+
10
+ `upnext-core` has always claimed it runs anywhere JavaScript does. Until this
11
+ package, the only adapter that could make a sound shelled out to `ffplay`, so a
12
+ browser had a queue and no way to play it. This closes that.
13
+
14
+ ## Install
15
+
16
+ ```bash
17
+ npm i upnext-core upnext-adapter-browser
18
+ ```
19
+
20
+ ```ts
21
+ import { Runtime } from 'upnext-core';
22
+ import { MediaElementAdapter } from 'upnext-adapter-browser';
23
+
24
+ const runtime = new Runtime({
25
+ adapters: [new MediaElementAdapter({ element: document.querySelector('audio')! })],
26
+ });
27
+
28
+ runtime.enqueue('https://traffic.megaphone.fm/episode.mp3');
29
+ runtime.enqueue('https://example.com/track.m4a');
30
+ await runtime.play();
31
+ ```
32
+
33
+ The element can be a function, so a host can build its queue before it has a
34
+ document:
35
+
36
+ ```ts
37
+ new MediaElementAdapter({ element: () => new Audio() });
38
+ ```
39
+
40
+ ## What it plays — and what it refuses
41
+
42
+ An `<audio>` element plays a **media stream**. It does not play a **page**. That
43
+ distinction is the whole design of this adapter, because "the browser can play
44
+ anything" is the intuition and it is wrong.
45
+
46
+ | | score | |
47
+ |---|:---:|---|
48
+ | `https://…/episode.mp3` | **1** | a direct stream |
49
+ | `https://…/ABC.mp3?updated=1712` | **1** | query strings don't hide the format |
50
+ | `blob:` / `data:audio/…` | **1** | already bytes |
51
+ | `file:///music/song.mp3` | 0.8 | Electron and webviews yes, plain web no |
52
+ | `https://…/download/12345` | 0.2 | no extension — podcast enclosures look like this, so it's tried last |
53
+ | `https://…/article.html` | **0** | names a format we can't decode |
54
+ | **`youtube.com/watch?v=…`** | **0** | **a page, not a stream** |
55
+ | `open.spotify.com/track/…` | **0** | a page — use `upnext-adapter-spotify` |
56
+ | `soundcloud.com`, `bandcamp.com`, `vimeo.com`, … | **0** | pages |
57
+
58
+ Those refusals are deliberate and explicit. Handing an element a YouTube watch
59
+ URL gets you a lump of HTML and a decode error — and a queue full of things that
60
+ fail at the last moment is worse than one that admitted up front it couldn't
61
+ take them. Scoring zero sends the entry to another adapter, or fails it
62
+ honestly.
63
+
64
+ Making those work needs a page-level integration — YouTube's IFrame player, a
65
+ SoundCloud widget, a stream extractor — which is a different adapter with
66
+ different terms of service, not a cleverer regex here.
67
+
68
+ If your element has been taught extra formats (hls.js, a custom source
69
+ extension), say so:
70
+
71
+ ```ts
72
+ new MediaElementAdapter({ element, extraExtensions: ['.dsf'] });
73
+ ```
74
+
75
+ ## It does not touch tabs you already have open
76
+
77
+ This adapter **owns a player**. It does not reach into pages the user has open.
78
+
79
+ Commandeering somebody's YouTube tab needs a browser extension, and it's a
80
+ different feature with a different risk profile — *pausing whatever is playing*
81
+ is a control feature, where *queueing* needs a player you can hand things to.
82
+ You cannot queue into a stranger's tab.
83
+
84
+ ## Capabilities
85
+
86
+ ```ts
87
+ {
88
+ endOfTrack: 'event', // the element's `ended` — no polling, no timers
89
+ position: 'authoritative', // currentTime, not a guess
90
+ seek: true, pause: true, volume: true,
91
+ search: false, // it plays a URL it is handed
92
+ externalControl: false, // nobody else has a handle on this element
93
+ }
94
+ ```
95
+
96
+ This is the fully-controlled end of the capability spectrum — the opposite of
97
+ `upnext-adapter-spotify`, where a human can hit next on their phone.
98
+
99
+ Blocked autoplay is reported as a failure rather than swallowed, so the runtime
100
+ falls through to a source that can actually make sound.
101
+
102
+ ## Across a process boundary
103
+
104
+ In Electron the queue usually lives in the main process, and only a renderer can
105
+ hold an `<audio>`. The adapter splits in two, over any transport you like:
106
+
107
+ ```ts
108
+ // main process — where the Runtime is
109
+ import { RemoteMediaAdapter } from 'upnext-adapter-browser';
110
+
111
+ const runtime = new Runtime({
112
+ adapters: [new RemoteMediaAdapter({
113
+ channel: {
114
+ send: (m) => win.webContents.send('upnext', m),
115
+ subscribe: (fn) => {
116
+ const h = (_e, m) => fn(m);
117
+ ipcMain.on('upnext', h);
118
+ return () => ipcMain.off('upnext', h);
119
+ },
120
+ },
121
+ })],
122
+ });
123
+ ```
124
+
125
+ ```ts
126
+ // renderer — where the element is
127
+ import { serveMediaElement } from 'upnext-adapter-browser';
128
+
129
+ serveMediaElement(document.querySelector('audio')!, {
130
+ send: (m) => ipcRenderer.send('upnext', m),
131
+ subscribe: (fn) => {
132
+ const h = (_e, m) => fn(m);
133
+ ipcRenderer.on('upnext', h);
134
+ return () => ipcRenderer.off('upnext', h);
135
+ },
136
+ });
137
+ ```
138
+
139
+ The transport is deliberately unnamed — `ipcMain`/`ipcRenderer`, `postMessage`,
140
+ a WebSocket, or two functions in a test. This package takes a `Channel` and asks
141
+ no further questions.
142
+
143
+ `serveMediaElement` drives a real `MediaElementAdapter`, so behaviour on the far
144
+ side is the same class as the in-process case and cannot drift from it. `match`
145
+ is evaluated locally and never crosses the wire — it's synchronous by contract,
146
+ and what an element accepts is knowable from the URL. Requests are bounded by
147
+ `requestTimeoutMs` (5s default), and a malformed command becomes an error reply
148
+ rather than an exception thrown inside a renderer where nothing is listening.
149
+
150
+ ---
151
+
152
+ Full docs: **https://github.com/tothienbao6a0/upnext** · Apache-2.0
@@ -0,0 +1,64 @@
1
+ import type { Adapter, AdapterEvent, Binding, Capabilities, MediaRef } from 'upnext-core';
2
+ /**
3
+ * The part of `HTMLMediaElement` this adapter actually uses.
4
+ *
5
+ * Deliberately tiny. A real `<audio>` satisfies it, so does a `<video>`, so
6
+ * does a webview's element behind a proxy — and so does a fake in a test, which
7
+ * is the point: none of this needs a browser to be exercised.
8
+ */
9
+ export interface MediaElementLike {
10
+ src: string;
11
+ currentTime: number;
12
+ readonly duration: number;
13
+ volume: number;
14
+ readonly paused: boolean;
15
+ play(): Promise<void> | void;
16
+ pause(): void;
17
+ load?(): void;
18
+ addEventListener(type: string, listener: () => void): void;
19
+ removeEventListener(type: string, listener: () => void): void;
20
+ }
21
+ export interface MediaElementAdapterOptions {
22
+ id?: string;
23
+ /**
24
+ * The element to drive. A function is allowed so the element can be created
25
+ * lazily — browsers refuse to construct audio contexts before a user
26
+ * gesture, and a host may not have a document yet when it builds its queue.
27
+ */
28
+ element: MediaElementLike | (() => MediaElementLike);
29
+ /** Extra media types this element is known to handle, e.g. `['audio/flac']`. */
30
+ extraExtensions?: string[];
31
+ }
32
+ /**
33
+ * Plays audio through a media element you own.
34
+ *
35
+ * This sits at the fully-controlled end of the capability spectrum, and it is
36
+ * the adapter that makes the core's claim true: `upnext-core` has always said
37
+ * it runs anywhere JavaScript does, but until now the only thing that could
38
+ * make a sound shelled out to `ffplay`, so a browser or an Electron renderer
39
+ * had a queue and no way to play it.
40
+ *
41
+ * What it deliberately does **not** do is reach into pages the user already has
42
+ * open. Commandeering somebody's YouTube tab needs a browser extension and is a
43
+ * different feature with a different risk profile — this owns a player, which
44
+ * is what a *queue* needs. See the README for where that line is.
45
+ */
46
+ export declare class MediaElementAdapter implements Adapter {
47
+ #private;
48
+ readonly id: string;
49
+ readonly capabilities: Capabilities;
50
+ constructor(options: MediaElementAdapterOptions);
51
+ match(ref: MediaRef): number;
52
+ resolve(ref: MediaRef): Promise<Binding | null>;
53
+ load(binding: Binding, opts?: {
54
+ startAtMs?: number;
55
+ }): Promise<void>;
56
+ play(): Promise<void>;
57
+ pause(): Promise<void>;
58
+ stop(): Promise<void>;
59
+ seek(positionMs: number): Promise<void>;
60
+ setVolume(volume: number): Promise<void>;
61
+ subscribe(listener: (event: AdapterEvent) => void): () => void;
62
+ dispose(): Promise<void>;
63
+ }
64
+ //# sourceMappingURL=element.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"element.d.ts","sourceRoot":"","sources":["../../src/element.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACV,OAAO,EACP,YAAY,EACZ,OAAO,EACP,YAAY,EACZ,QAAQ,EACT,MAAM,aAAa,CAAC;AAGrB;;;;;;GAMG;AACH,MAAM,WAAW,gBAAgB;IAC/B,GAAG,EAAE,MAAM,CAAC;IACZ,WAAW,EAAE,MAAM,CAAC;IACpB,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,CAAC,MAAM,EAAE,OAAO,CAAC;IACzB,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC;IAC7B,KAAK,IAAI,IAAI,CAAC;IACd,IAAI,CAAC,IAAI,IAAI,CAAC;IACd,gBAAgB,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,IAAI,GAAG,IAAI,CAAC;IAC3D,mBAAmB,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,IAAI,GAAG,IAAI,CAAC;CAC/D;AAED,MAAM,WAAW,0BAA0B;IACzC,EAAE,CAAC,EAAE,MAAM,CAAC;IACZ;;;;OAIG;IACH,OAAO,EAAE,gBAAgB,GAAG,CAAC,MAAM,gBAAgB,CAAC,CAAC;IACrD,gFAAgF;IAChF,eAAe,CAAC,EAAE,MAAM,EAAE,CAAC;CAC5B;AAED;;;;;;;;;;;;;GAaG;AACH,qBAAa,mBAAoB,YAAW,OAAO;;IACjD,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IAEpB,QAAQ,CAAC,YAAY,EAAE,YAAY,CAajC;gBAUU,OAAO,EAAE,0BAA0B;IAK/C,KAAK,CAAC,GAAG,EAAE,QAAQ,GAAG,MAAM;IAItB,OAAO,CAAC,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,OAAO,GAAG,IAAI,CAAC;IAS/C,IAAI,CAAC,OAAO,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE;QAAE,SAAS,CAAC,EAAE,MAAM,CAAA;KAAE,GAAG,OAAO,CAAC,IAAI,CAAC;IASpE,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC;IAQrB,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAItB,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC;IAgBrB,IAAI,CAAC,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAIvC,SAAS,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAI9C,SAAS,CAAC,QAAQ,EAAE,CAAC,KAAK,EAAE,YAAY,KAAK,IAAI,GAAG,MAAM,IAAI;IAWxD,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;CAqE/B"}
@@ -0,0 +1,176 @@
1
+ import { defaultCapabilities } from 'upnext-core';
2
+ import { canPlay, describeSource, score } from './sources.js';
3
+ /**
4
+ * Plays audio through a media element you own.
5
+ *
6
+ * This sits at the fully-controlled end of the capability spectrum, and it is
7
+ * the adapter that makes the core's claim true: `upnext-core` has always said
8
+ * it runs anywhere JavaScript does, but until now the only thing that could
9
+ * make a sound shelled out to `ffplay`, so a browser or an Electron renderer
10
+ * had a queue and no way to play it.
11
+ *
12
+ * What it deliberately does **not** do is reach into pages the user already has
13
+ * open. Commandeering somebody's YouTube tab needs a browser extension and is a
14
+ * different feature with a different risk profile — this owns a player, which
15
+ * is what a *queue* needs. See the README for where that line is.
16
+ */
17
+ export class MediaElementAdapter {
18
+ id;
19
+ capabilities = {
20
+ ...defaultCapabilities,
21
+ // The element tells us. No polling, no duration timer, no guessing.
22
+ endOfTrack: 'event',
23
+ position: 'authoritative',
24
+ seek: true,
25
+ pause: true,
26
+ volume: true,
27
+ // Nothing to search — this plays a URL it is handed.
28
+ search: false,
29
+ // Nobody else has a handle on this element. If something else could pause
30
+ // it, that would be the host's own UI, and the host already knows.
31
+ externalControl: false,
32
+ };
33
+ #options;
34
+ #element = null;
35
+ #listeners = new Set();
36
+ #detach = [];
37
+ #binding = null;
38
+ /** Set while we are tearing down, so our own `pause` is not reported. */
39
+ #closing = false;
40
+ constructor(options) {
41
+ this.id = options.id ?? 'browser';
42
+ this.#options = options;
43
+ }
44
+ match(ref) {
45
+ return score(ref, this.#options.extraExtensions);
46
+ }
47
+ async resolve(ref) {
48
+ if (!ref.uri || !canPlay(ref.uri, this.#options.extraExtensions))
49
+ return null;
50
+ return {
51
+ adapterId: this.id,
52
+ nativeUri: ref.uri,
53
+ ref: { ...ref, title: ref.title ?? describeSource(ref.uri) },
54
+ };
55
+ }
56
+ async load(binding, opts) {
57
+ const element = this.#ensure();
58
+ this.#binding = binding;
59
+ element.src = binding.nativeUri;
60
+ element.load?.();
61
+ if (opts?.startAtMs)
62
+ element.currentTime = opts.startAtMs / 1000;
63
+ }
64
+ async play() {
65
+ const element = this.#ensure();
66
+ // `play()` rejects when a browser blocks autoplay. That is a real failure
67
+ // the runtime should hear about, not a warning to swallow — it falls
68
+ // through to the next source, which may well be one that can make sound.
69
+ await element.play();
70
+ }
71
+ async pause() {
72
+ this.#ensure().pause();
73
+ }
74
+ async stop() {
75
+ const element = this.#element;
76
+ if (!element)
77
+ return;
78
+ this.#closing = true;
79
+ try {
80
+ element.pause();
81
+ // Releases the network connection and stops buffering. Without it a long
82
+ // podcast keeps downloading behind whatever plays next.
83
+ element.src = '';
84
+ element.load?.();
85
+ }
86
+ finally {
87
+ this.#closing = false;
88
+ this.#binding = null;
89
+ }
90
+ }
91
+ async seek(positionMs) {
92
+ this.#ensure().currentTime = Math.max(0, positionMs) / 1000;
93
+ }
94
+ async setVolume(volume) {
95
+ this.#ensure().volume = Math.min(1, Math.max(0, volume));
96
+ }
97
+ subscribe(listener) {
98
+ this.#listeners.add(listener);
99
+ // Wiring is deferred until someone is listening, so constructing an adapter
100
+ // never touches the DOM — a host can build its queue before it has one.
101
+ if (this.#listeners.size === 1)
102
+ this.#wire();
103
+ return () => {
104
+ this.#listeners.delete(listener);
105
+ if (this.#listeners.size === 0)
106
+ this.#unwire();
107
+ };
108
+ }
109
+ async dispose() {
110
+ await this.stop();
111
+ this.#unwire();
112
+ this.#listeners.clear();
113
+ this.#element = null;
114
+ }
115
+ // -- internals ------------------------------------------------------------
116
+ #ensure() {
117
+ if (!this.#element) {
118
+ const source = this.#options.element;
119
+ this.#element = typeof source === 'function' ? source() : source;
120
+ }
121
+ return this.#element;
122
+ }
123
+ #wire() {
124
+ const element = this.#ensure();
125
+ const on = (type, handler) => {
126
+ element.addEventListener(type, handler);
127
+ this.#detach.push(() => element.removeEventListener(type, handler));
128
+ };
129
+ on('ended', () => this.#emit({ type: 'ended' }));
130
+ on('timeupdate', () => {
131
+ const durationMs = toMs(element.duration);
132
+ this.#emit({
133
+ type: 'position',
134
+ positionMs: Math.round(element.currentTime * 1000),
135
+ ...(durationMs ? { durationMs } : {}),
136
+ });
137
+ });
138
+ on('loadedmetadata', () => {
139
+ const durationMs = toMs(element.duration);
140
+ if (durationMs) {
141
+ this.#emit({ type: 'position', positionMs: 0, durationMs });
142
+ }
143
+ });
144
+ on('play', () => this.#emit({ type: 'status', status: 'playing' }));
145
+ on('pause', () => {
146
+ // Our own teardown pauses the element; reporting that would tell the
147
+ // runtime the listener paused when in fact the track was being replaced.
148
+ if (this.#closing)
149
+ return;
150
+ this.#emit({ type: 'status', status: 'paused' });
151
+ });
152
+ on('error', () => {
153
+ this.#emit({
154
+ type: 'error',
155
+ code: 'media_error',
156
+ message: `could not play ${this.#binding?.nativeUri ?? 'the loaded source'}`,
157
+ });
158
+ });
159
+ }
160
+ #unwire() {
161
+ for (const off of this.#detach)
162
+ off();
163
+ this.#detach = [];
164
+ }
165
+ #emit(event) {
166
+ for (const listener of [...this.#listeners])
167
+ listener(event);
168
+ }
169
+ }
170
+ /** A media element reports `NaN` before metadata and `Infinity` for streams. */
171
+ function toMs(seconds) {
172
+ if (!Number.isFinite(seconds) || seconds <= 0)
173
+ return undefined;
174
+ return Math.round(seconds * 1000);
175
+ }
176
+ //# sourceMappingURL=element.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"element.js","sourceRoot":"","sources":["../../src/element.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,MAAM,aAAa,CAAC;AAQlD,OAAO,EAAE,OAAO,EAAE,cAAc,EAAE,KAAK,EAAE,MAAM,cAAc,CAAC;AAkC9D;;;;;;;;;;;;;GAaG;AACH,MAAM,OAAO,mBAAmB;IACrB,EAAE,CAAS;IAEX,YAAY,GAAiB;QACpC,GAAG,mBAAmB;QACtB,oEAAoE;QACpE,UAAU,EAAE,OAAO;QACnB,QAAQ,EAAE,eAAe;QACzB,IAAI,EAAE,IAAI;QACV,KAAK,EAAE,IAAI;QACX,MAAM,EAAE,IAAI;QACZ,qDAAqD;QACrD,MAAM,EAAE,KAAK;QACb,0EAA0E;QAC1E,mEAAmE;QACnE,eAAe,EAAE,KAAK;KACvB,CAAC;IAEF,QAAQ,CAA6B;IACrC,QAAQ,GAA4B,IAAI,CAAC;IACzC,UAAU,GAAG,IAAI,GAAG,EAAiC,CAAC;IACtD,OAAO,GAAsB,EAAE,CAAC;IAChC,QAAQ,GAAmB,IAAI,CAAC;IAChC,yEAAyE;IACzE,QAAQ,GAAG,KAAK,CAAC;IAEjB,YAAY,OAAmC;QAC7C,IAAI,CAAC,EAAE,GAAG,OAAO,CAAC,EAAE,IAAI,SAAS,CAAC;QAClC,IAAI,CAAC,QAAQ,GAAG,OAAO,CAAC;IAC1B,CAAC;IAED,KAAK,CAAC,GAAa;QACjB,OAAO,KAAK,CAAC,GAAG,EAAE,IAAI,CAAC,QAAQ,CAAC,eAAe,CAAC,CAAC;IACnD,CAAC;IAED,KAAK,CAAC,OAAO,CA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,OAAO,IAAI,CAAC,KAAK,CAAC,OAAO,GAAG,IAAI,CAAC,CAAC;AACpC,CAAC"}
@@ -0,0 +1,6 @@
1
+ export { MediaElementAdapter } from './element.js';
2
+ export type { MediaElementLike, MediaElementAdapterOptions } from './element.js';
3
+ export { RemoteMediaAdapter, serveMediaElement } from './remote.js';
4
+ export type { Channel, RemoteMediaAdapterOptions } from './remote.js';
5
+ export { canPlay, score as scoreSource, describeSource } from './sources.js';
6
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,MAAM,cAAc,CAAC;AACnD,YAAY,EAAE,gBAAgB,EAAE,0BAA0B,EAAE,MAAM,cAAc,CAAC;AAEjF,OAAO,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AACpE,YAAY,EAAE,OAAO,EAAE,yBAAyB,EAAE,MAAM,aAAa,CAAC;AAEtE,OAAO,EAAE,OAAO,EAAE,KAAK,IAAI,WAAW,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC"}
@@ -0,0 +1,4 @@
1
+ export { MediaElementAdapter } from './element.js';
2
+ export { RemoteMediaAdapter, serveMediaElement } from './remote.js';
3
+ export { canPlay, score as scoreSource, describeSource } from './sources.js';
4
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,MAAM,cAAc,CAAC;AAGnD,OAAO,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAGpE,OAAO,EAAE,OAAO,EAAE,KAAK,IAAI,WAAW,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC"}