tiny-essentials 1.28.3 → 1.28.5
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/changelog/1/28/4.md +4 -0
- package/changelog/1/28/5.md +31 -0
- package/dist/v1/TinyBasicsEs.min.js +1 -1
- package/dist/v1/TinyEssentials.min.js +1 -1
- package/dist/v1/TinyMediaPlayer.min.js +1 -1
- package/dist/v1/TinyTimeout.min.js +1 -1
- package/dist/v1/TinyUploadClicker.min.js +1 -1
- package/dist/v1/basics/index.cjs +4 -0
- package/dist/v1/basics/index.d.mts +3 -2
- package/dist/v1/basics/index.mjs +3 -2
- package/dist/v1/basics/mediaContent.cjs +1 -0
- package/dist/v1/basics/mediaContent.d.mts +4 -0
- package/dist/v1/basics/mediaContent.mjs +1 -0
- package/dist/v1/basics/objChecker.cjs +16 -0
- package/dist/v1/basics/objChecker.d.mts +12 -0
- package/dist/v1/basics/objChecker.mjs +14 -0
- package/dist/v1/basics/objFilter.cjs +21 -30
- package/dist/v1/basics/objFilter.d.mts +0 -2
- package/dist/v1/basics/objFilter.mjs +21 -30
- package/dist/v1/basics/promiseUtils.cjs +101 -0
- package/dist/v1/basics/promiseUtils.d.mts +31 -0
- package/dist/v1/basics/promiseUtils.mjs +89 -0
- package/dist/v1/index.cjs +4 -0
- package/dist/v1/index.d.mts +3 -2
- package/dist/v1/index.mjs +3 -2
- package/dist/v1/libs/TinyMediaPlayer/HtmlAudio.cjs +268 -0
- package/dist/v1/libs/TinyMediaPlayer/HtmlAudio.d.mts +118 -0
- package/dist/v1/libs/TinyMediaPlayer/HtmlAudio.mjs +237 -0
- package/dist/v1/libs/TinyMediaPlayer/HtmlVideo.cjs +265 -0
- package/dist/v1/libs/TinyMediaPlayer/HtmlVideo.d.mts +118 -0
- package/dist/v1/libs/TinyMediaPlayer/HtmlVideo.mjs +234 -0
- package/dist/v1/libs/TinyMediaPlayer/Youtube.cjs +671 -0
- package/dist/v1/libs/TinyMediaPlayer/Youtube.d.mts +259 -0
- package/dist/v1/libs/TinyMediaPlayer/Youtube.mjs +597 -0
- package/dist/v1/libs/TinyMediaPlayer/docs/YouTubePlayer.cjs +546 -0
- package/dist/v1/libs/TinyMediaPlayer/docs/YouTubePlayer.d.mts +657 -0
- package/dist/v1/libs/TinyMediaPlayer/docs/YouTubePlayer.mjs +480 -0
- package/dist/v1/libs/TinyMediaPlayer/index.cjs +165 -0
- package/dist/v1/libs/TinyMediaPlayer/index.d.mts +102 -0
- package/dist/v1/libs/TinyMediaPlayer/index.mjs +144 -0
- package/dist/v1/libs/TinyMediaPlayer.cjs +589 -103
- package/dist/v1/libs/TinyMediaPlayer.d.mts +150 -65
- package/dist/v1/libs/TinyMediaPlayer.mjs +535 -93
- package/dist/v1/libs/TinyTimeout.cjs +4 -14
- package/dist/v1/libs/TinyTimeout.d.mts +1 -0
- package/dist/v1/libs/TinyTimeout.mjs +4 -13
- package/docs/v1/basics/mediaContent.md +1 -1
- package/docs/v1/basics/objChecker.md +13 -0
- package/docs/v1/basics/promiseUtils.md +32 -0
- package/docs/v1/libs/TinyMediaPlayer.md +239 -32
- package/docs/v1/libs/TinyTimeout.md +1 -14
- package/package.json +21 -1
|
@@ -0,0 +1,671 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var events = require('events');
|
|
4
|
+
var index = require('./index.cjs');
|
|
5
|
+
var utils = require('../utils.cjs');
|
|
6
|
+
var promiseUtils = require('../../basics/promiseUtils.cjs');
|
|
7
|
+
var objChecker = require('../../basics/objChecker.cjs');
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* @typedef {import('../../basics/mediaContent.mjs').PictureDataType} PictureDataType
|
|
11
|
+
* @typedef {import('../../basics/mediaContent.mjs').MediaContent<PictureDataType>} MediaContent
|
|
12
|
+
* @typedef {import('./index.mjs').ContentTimeData} ContentTimeData
|
|
13
|
+
*
|
|
14
|
+
* @typedef {import('./docs/YouTubePlayer.mjs').YTPlayerState} YTPlayerState
|
|
15
|
+
* @typedef {import('./docs/YouTubePlayer.mjs').YTPlayerErrors} YTPlayerErrors
|
|
16
|
+
* @typedef {import('./docs/YouTubePlayer.mjs').YTQuality} YTQuality
|
|
17
|
+
* @typedef {import('./docs/YouTubePlayer.mjs').YTSphericalProperties} YTSphericalProperties
|
|
18
|
+
* @typedef {import('./docs/YouTubePlayer.mjs').YouTubePlayerEventBase} YouTubePlayerEventBase
|
|
19
|
+
* @typedef {import('./docs/YouTubePlayer.mjs').YTPlayerOptionsEvents} YTPlayerOptionsEvents
|
|
20
|
+
* @typedef {import('./docs/YouTubePlayer.mjs').YTPlayerOptionsEvents} YTPlayerOptions
|
|
21
|
+
* @typedef {import('./docs/YouTubePlayer.mjs').EventNames} EventNames
|
|
22
|
+
* @typedef {import('./docs/YouTubePlayer.mjs').YTPlaylistOptions} YTPlaylistOptions
|
|
23
|
+
* @typedef {import('./docs/YouTubePlayer.mjs').VideoByUrlOptions} VideoByUrlOptions
|
|
24
|
+
* @typedef {import('./docs/YouTubePlayer.mjs').VideoByIdOptions} VideoByIdOptions
|
|
25
|
+
*
|
|
26
|
+
* @typedef {import('./docs/YouTubePlayer.mjs').OnReadyEvent} OnReadyEvent
|
|
27
|
+
* @typedef {import('./docs/YouTubePlayer.mjs').OnStateChangeEvent} OnStateChangeEvent
|
|
28
|
+
* @typedef {import('./docs/YouTubePlayer.mjs').OnErrorEvent} OnErrorEvent
|
|
29
|
+
* @typedef {import('./docs/YouTubePlayer.mjs').OnPlaybackQualityChangeEvent} OnPlaybackQualityChangeEvent
|
|
30
|
+
* @typedef {import('./docs/YouTubePlayer.mjs').OnPlaybackRateChangeEvent} OnPlaybackRateChangeEvent
|
|
31
|
+
* @typedef {import('./docs/YouTubePlayer.mjs').OnApiChangeEvent} OnApiChangeEvent
|
|
32
|
+
* @typedef {import('./docs/YouTubePlayer.mjs').OnAutoplayBlockedEvent} OnAutoplayBlockedEvent
|
|
33
|
+
*/
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
const makeLoadYoutubeApi = () => {
|
|
37
|
+
const { callback } = promiseUtils.createSingletonTask(async () => {
|
|
38
|
+
// Use existing API if already loaded
|
|
39
|
+
// @ts-ignore
|
|
40
|
+
if (typeof window !== 'undefined' && window.YT && window.YT.Player) {
|
|
41
|
+
// @ts-ignore
|
|
42
|
+
YoutubeMediaAdapter.PlayerState = window.YT.PlayerState;
|
|
43
|
+
return Promise.resolve(undefined);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
return new Promise((resolve, reject) => {
|
|
47
|
+
let isError = false;
|
|
48
|
+
const tag = document.createElement('script');
|
|
49
|
+
tag.src = 'https://www.youtube.com/iframe_api';
|
|
50
|
+
tag.async = true;
|
|
51
|
+
tag.onerror = () => {
|
|
52
|
+
isError = true;
|
|
53
|
+
reject(new Error('Failed to load YouTube IFrame API.'));
|
|
54
|
+
};
|
|
55
|
+
document.body.appendChild(tag);
|
|
56
|
+
|
|
57
|
+
// Check periodically if YT is ready
|
|
58
|
+
promiseUtils.waitForTrue(
|
|
59
|
+
// @ts-ignore
|
|
60
|
+
() => isError || (typeof window !== 'undefined' && window.YT && window.YT.Player),
|
|
61
|
+
).then(() => {
|
|
62
|
+
if (isError) return;
|
|
63
|
+
// @ts-ignore
|
|
64
|
+
YoutubeMediaAdapter.PlayerState = window.YT.PlayerState;
|
|
65
|
+
resolve(undefined);
|
|
66
|
+
});
|
|
67
|
+
});
|
|
68
|
+
});
|
|
69
|
+
return callback;
|
|
70
|
+
};
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Method to ensure the YouTube IFrame API script is loaded.
|
|
74
|
+
*/
|
|
75
|
+
const loadYoutubeApi = makeLoadYoutubeApi();
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Returns a deep clone of the current YouTube player state values.
|
|
79
|
+
* This ensures the returned object is a copy and does not maintain a reference to the original state.
|
|
80
|
+
* @returns {Record<string, number>} A copy of the PlayerState object.
|
|
81
|
+
*/
|
|
82
|
+
const getPlayerStateValues = () => {
|
|
83
|
+
return structuredClone(YoutubeMediaAdapter.PlayerState);
|
|
84
|
+
};
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Retrieves the YouTube Player constructor from the global window object.
|
|
88
|
+
* @returns {typeof YouTubePlayer} The YouTube Player constructor.
|
|
89
|
+
* @throws {Error} If the YouTube API is not detected in the global scope.
|
|
90
|
+
*/
|
|
91
|
+
const getYtPlayer = () => {
|
|
92
|
+
// @ts-ignore
|
|
93
|
+
if (typeof window === 'undefined' || !window.YT || !window.YT.Player)
|
|
94
|
+
throw new Error('YouTube API not available');
|
|
95
|
+
/** @type {typeof YouTubePlayer} */
|
|
96
|
+
// @ts-ignore
|
|
97
|
+
const Player = window.YT.Player;
|
|
98
|
+
return Player;
|
|
99
|
+
};
|
|
100
|
+
|
|
101
|
+
const checkDestroy = utils.createCheckDestroyed('YoutubeMediaAdapter');
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Implementation of BaseMediaAdapter for the YouTube IFrame Player API.
|
|
105
|
+
* This adapter manages the lifecycle of a YouTube player embedded in a container.
|
|
106
|
+
* @extends BaseMediaAdapter
|
|
107
|
+
*/
|
|
108
|
+
class YoutubeMediaAdapter extends index.BaseMediaAdapter {
|
|
109
|
+
/**
|
|
110
|
+
* Mapping YouTube API events for internal adapter events.
|
|
111
|
+
* Includes semantic events triggered by state changes.
|
|
112
|
+
* @type {Record<string, string>}
|
|
113
|
+
* @private
|
|
114
|
+
*/
|
|
115
|
+
static EVENT_MAPPING = {
|
|
116
|
+
onReady: 'onReady',
|
|
117
|
+
onPlaybackQualityChange: 'onPlaybackQualityChange',
|
|
118
|
+
onPlaybackRateChange: 'onPlaybackRateChange',
|
|
119
|
+
onError: 'onError',
|
|
120
|
+
onApiChange: 'onApiChange',
|
|
121
|
+
onAutoplayBlocked: 'onAutoplayBlocked',
|
|
122
|
+
onStateChange: 'onStateChange',
|
|
123
|
+
timeupdate: 'timeupdate',
|
|
124
|
+
play: 'play',
|
|
125
|
+
pause: 'pause',
|
|
126
|
+
ended: 'ended',
|
|
127
|
+
};
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* Represents the current state of the player.
|
|
131
|
+
* @type {Record<string, number>}
|
|
132
|
+
*/
|
|
133
|
+
static PlayerState = {
|
|
134
|
+
UNSTARTED: -1,
|
|
135
|
+
ENDED: 0,
|
|
136
|
+
PLAYING: 1,
|
|
137
|
+
PAUSED: 2,
|
|
138
|
+
BUFFERING: 3,
|
|
139
|
+
CUED: 5,
|
|
140
|
+
};
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* Safety lock: If true, multiple instances can share the same player/iframe via WeakMap.
|
|
144
|
+
* If false, only one instance can be bound to a specific container at a time.
|
|
145
|
+
* @type {boolean}
|
|
146
|
+
*/
|
|
147
|
+
static allowInstanceSharing = false;
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* The default HTML element where the YouTube iframe will be injected.
|
|
151
|
+
* @type {HTMLIFrameElement|null}
|
|
152
|
+
*/
|
|
153
|
+
static #defaultContainer = null;
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* Registry to reuse players and master emitters per container.
|
|
157
|
+
* @type {WeakMap<HTMLIFrameElement, {player: YouTubePlayer, masterEmitter: EventEmitter, refCount: number}>}
|
|
158
|
+
*/
|
|
159
|
+
static #registry = new WeakMap();
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* Gets the globally configured default container for YouTube players.
|
|
163
|
+
* @returns {HTMLIFrameElement|null}
|
|
164
|
+
*/
|
|
165
|
+
static get defaultContainer() {
|
|
166
|
+
return this.#defaultContainer;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* Sets the globally configured default container for YouTube players.
|
|
171
|
+
* @param {HTMLIFrameElement|null} element - The element to be used as the default container.
|
|
172
|
+
* @throws {TypeError} If the provided element is not an instance of HTMLIFrameElement.
|
|
173
|
+
*/
|
|
174
|
+
static set defaultContainer(element) {
|
|
175
|
+
if (element !== null && !(element instanceof HTMLIFrameElement)) {
|
|
176
|
+
throw new TypeError('The defaultContainer must be an instance of HTMLIFrameElement.');
|
|
177
|
+
}
|
|
178
|
+
this.#defaultContainer = element;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/**
|
|
182
|
+
* Creates a YouTube iframe element.
|
|
183
|
+
* This element can be used as the `defaultContainer` for the adapter.
|
|
184
|
+
*
|
|
185
|
+
* @param {IframeContainerOptions} options - Configuration for the iframe creation.
|
|
186
|
+
* @returns {HTMLIFrameElement} The created iframe element.
|
|
187
|
+
* @throws {TypeError} If the `videoId` is not a valid string.
|
|
188
|
+
*/
|
|
189
|
+
static createIframeContainer(options) {
|
|
190
|
+
const { videoId, width = 640, height = 360, hidden = true, autoplay = false } = options;
|
|
191
|
+
|
|
192
|
+
if (typeof videoId !== 'string' || videoId.trim() === '') {
|
|
193
|
+
throw new TypeError('The "videoId" property is required and must be a valid string.');
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
const iframe = document.createElement('iframe');
|
|
197
|
+
|
|
198
|
+
// enablejsapi=1 is required to allow control via the YouTube API
|
|
199
|
+
iframe.src = `https://www.youtube.com/embed/${videoId}?autoplay=${autoplay ? 1 : 0}&enablejsapi=1`;
|
|
200
|
+
|
|
201
|
+
iframe.style.width = `${width}px`;
|
|
202
|
+
iframe.style.height = `${height}px`;
|
|
203
|
+
iframe.setAttribute('frameborder', '0');
|
|
204
|
+
iframe.setAttribute('allow', 'autoplay; encrypted-media');
|
|
205
|
+
|
|
206
|
+
if (hidden) {
|
|
207
|
+
iframe.style.opacity = '0';
|
|
208
|
+
iframe.style.pointerEvents = 'none';
|
|
209
|
+
// Absolute positioning outside the viewport to prevent layout shifting
|
|
210
|
+
iframe.style.position = 'absolute';
|
|
211
|
+
iframe.style.top = '-9999px';
|
|
212
|
+
iframe.style.left = '-9999px';
|
|
213
|
+
document.body.appendChild(iframe);
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
return iframe;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/**
|
|
220
|
+
* Returns the URL for a YouTube video thumbnail with a specified quality.
|
|
221
|
+
* @param {string} videoId - The YouTube video ID.
|
|
222
|
+
* @param {string} [quality='maxresdefault'] - The thumbnail quality (e.g., 'default', 'mqdefault', 'hqdefault', 'sddefault', 'maxresdefault').
|
|
223
|
+
* @returns {string} The thumbnail URL.
|
|
224
|
+
* @throws {TypeError} If the videoId is not a valid string.
|
|
225
|
+
*/
|
|
226
|
+
static getThumbnailUrl(videoId, quality = 'maxresdefault') {
|
|
227
|
+
if (typeof videoId !== 'string' || videoId.trim() === '') {
|
|
228
|
+
throw new TypeError('The "videoId" must be a non-empty string.');
|
|
229
|
+
}
|
|
230
|
+
if (typeof quality !== 'string' || quality.trim() === '') {
|
|
231
|
+
throw new TypeError('The "quality" must be a non-empty string.');
|
|
232
|
+
}
|
|
233
|
+
return `https://img.youtube.com/vi/${videoId}/${quality}.jpg`;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
get id() {
|
|
237
|
+
return 'youtubeEmbedApi';
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/** @type {YouTubePlayer|null} */
|
|
241
|
+
#player = null;
|
|
242
|
+
|
|
243
|
+
/** @type {HTMLIFrameElement} */
|
|
244
|
+
#container;
|
|
245
|
+
|
|
246
|
+
/** @type {Promise<void>} */
|
|
247
|
+
#apiLoadedPromise;
|
|
248
|
+
|
|
249
|
+
/** @type {number} */
|
|
250
|
+
#currentVolume = 1.0;
|
|
251
|
+
|
|
252
|
+
/** @type {EventEmitter|null} */
|
|
253
|
+
#masterEmitter = null;
|
|
254
|
+
|
|
255
|
+
/** @type {Array<{eventName: string, handler: HandlerFunc}>} */
|
|
256
|
+
#eventHandlers = [];
|
|
257
|
+
|
|
258
|
+
/** @type {boolean} */
|
|
259
|
+
#destroyed = false;
|
|
260
|
+
|
|
261
|
+
/** @type {string|null} */
|
|
262
|
+
#currentContentId = null;
|
|
263
|
+
|
|
264
|
+
get currentContentId() {
|
|
265
|
+
return this.#currentContentId;
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/** @type {ReturnType<typeof setInterval>|null} */
|
|
269
|
+
#timeUpdateInterval = null;
|
|
270
|
+
|
|
271
|
+
/**
|
|
272
|
+
* Gets whether the adapter has been destroyed.
|
|
273
|
+
* @returns {boolean}
|
|
274
|
+
*/
|
|
275
|
+
get destroyed() {
|
|
276
|
+
return this.#destroyed;
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
/**
|
|
280
|
+
* Initializes the YouTube Media Adapter.
|
|
281
|
+
* @throws {Error} If allowInstanceSharing is false and the container is already in use.
|
|
282
|
+
*/
|
|
283
|
+
constructor() {
|
|
284
|
+
const container = YoutubeMediaAdapter.#defaultContainer;
|
|
285
|
+
if (!(container instanceof HTMLIFrameElement)) {
|
|
286
|
+
throw new TypeError(
|
|
287
|
+
'The YoutubeMediaAdapter.defaultContainer must be an instance of HTMLIFrameElement.',
|
|
288
|
+
);
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
// Safety Lock Check
|
|
292
|
+
if (!YoutubeMediaAdapter.allowInstanceSharing && YoutubeMediaAdapter.#registry.has(container)) {
|
|
293
|
+
throw new Error(
|
|
294
|
+
'Security Lock: This container is already bound to another YoutubeMediaAdapter instance.',
|
|
295
|
+
);
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
super();
|
|
299
|
+
this.#container = container;
|
|
300
|
+
this.#apiLoadedPromise = loadYoutubeApi();
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
/**
|
|
304
|
+
* @returns {YouTubePlayer} The current YouTube player instance.
|
|
305
|
+
* @throws {Error} If the player has not been initialized.
|
|
306
|
+
*/
|
|
307
|
+
get player() {
|
|
308
|
+
checkDestroy(this.#destroyed);
|
|
309
|
+
if (!this.#player) {
|
|
310
|
+
throw new Error('YouTube player instance not initialized. Ensure a valid video was played.');
|
|
311
|
+
}
|
|
312
|
+
return this.#player;
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
/**
|
|
316
|
+
* @param {number} value - The volume level from 0.0 to 1.0.
|
|
317
|
+
* @throws {RangeError} If the volume is not between 0.0 and 1.0.
|
|
318
|
+
*/
|
|
319
|
+
set volume(value) {
|
|
320
|
+
checkDestroy(this.#destroyed);
|
|
321
|
+
if (typeof value !== 'number' || value < 0 || value > 1) {
|
|
322
|
+
throw new RangeError('Volume must be a number between 0.0 and 1.0.');
|
|
323
|
+
}
|
|
324
|
+
this.#currentVolume = value;
|
|
325
|
+
if (this.#player && typeof this.#player.setVolume === 'function') {
|
|
326
|
+
this.#player.setVolume(value * 100);
|
|
327
|
+
}
|
|
328
|
+
this.emit('volumeChange', this.#currentVolume);
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
/**
|
|
332
|
+
* @returns {number} The current volume level from 0.0 to 1.0.
|
|
333
|
+
*/
|
|
334
|
+
get volume() {
|
|
335
|
+
checkDestroy(this.#destroyed);
|
|
336
|
+
return this.#currentVolume;
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
/**
|
|
340
|
+
* Retrieves a consolidated object containing all time-related metrics for the current media content.
|
|
341
|
+
* @returns {ContentTimeData} An object containing total, current, remaining time, and playback percentage.
|
|
342
|
+
*/
|
|
343
|
+
getTimeData() {
|
|
344
|
+
const total = this.getTotalDuration();
|
|
345
|
+
const current = this.getCurrentTime();
|
|
346
|
+
const remaining = total > 0 ? total - current : 0;
|
|
347
|
+
const playbackPercentage = total > 0 ? (current / total) * 100 : 0;
|
|
348
|
+
return { total, current, remaining, playbackPercentage };
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
/**
|
|
352
|
+
* Determines if the content is a valid YouTube URL or ID.
|
|
353
|
+
* @param {MediaContent} content - The media content to evaluate.
|
|
354
|
+
* @returns {boolean} True if the content is a YouTube link/ID, false otherwise.
|
|
355
|
+
*/
|
|
356
|
+
canHandle(content) {
|
|
357
|
+
checkDestroy(this.#destroyed);
|
|
358
|
+
if (!objChecker.isValidObj(content)) {
|
|
359
|
+
throw new TypeError('Content must be a valid object.');
|
|
360
|
+
}
|
|
361
|
+
if (typeof content.url !== 'string') return false;
|
|
362
|
+
const youtubeRegex =
|
|
363
|
+
/(?:youtube\.com\/(?:[^\/]+\/.+\/|(?:v|e(?:mbed)?)\/|.*[?&]v=)|youtu\.be\/)([^"&?\/\s]{11})/;
|
|
364
|
+
return youtubeRegex.test(content.url);
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
/**
|
|
368
|
+
* Plays the media content. If the player is already initialized with a different video,
|
|
369
|
+
* it will load the new video automatically.
|
|
370
|
+
* @param {MediaContent} content - The media content to play.
|
|
371
|
+
* @returns {Promise<void>}
|
|
372
|
+
* @throws {TypeError} If the content data is invalid.
|
|
373
|
+
*/
|
|
374
|
+
async play(content) {
|
|
375
|
+
checkDestroy(this.#destroyed);
|
|
376
|
+
await this.#apiLoadedPromise;
|
|
377
|
+
|
|
378
|
+
if (!objChecker.isValidObj(content) || !content.url) {
|
|
379
|
+
throw new TypeError('Invalid media content provided to play().');
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
const videoSource = typeof content.url === 'string' ? content.url : '';
|
|
383
|
+
const targetVideoId = this.#extractVideoId(videoSource);
|
|
384
|
+
|
|
385
|
+
if (!this.#player) {
|
|
386
|
+
await this.#initializePlayer(targetVideoId);
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
if (this.#player && typeof this.#player.setVolume === 'function') {
|
|
390
|
+
this.#player.setVolume(this.#currentVolume * 100);
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
// If the video is different, load the new one
|
|
394
|
+
if (this.#currentContentId !== targetVideoId) {
|
|
395
|
+
this.#currentContentId = targetVideoId;
|
|
396
|
+
this.#player?.loadVideoById(targetVideoId);
|
|
397
|
+
} else {
|
|
398
|
+
this.#player?.playVideo();
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
return Promise.resolve();
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
/**
|
|
405
|
+
* Initializes the YT.Player instance and sets up semantic event bridging.
|
|
406
|
+
* @param {string} videoId - The video ID to load.
|
|
407
|
+
* @returns {Promise<void>}
|
|
408
|
+
*/
|
|
409
|
+
async #initializePlayer(videoId) {
|
|
410
|
+
checkDestroy(this.#destroyed);
|
|
411
|
+
const existing = YoutubeMediaAdapter.#registry.get(this.#container);
|
|
412
|
+
|
|
413
|
+
if (existing) {
|
|
414
|
+
existing.refCount++; // Increment reference count for the shared player
|
|
415
|
+
this.#player = existing.player;
|
|
416
|
+
this.#masterEmitter = existing.masterEmitter;
|
|
417
|
+
this.#currentContentId = this.#player.getVideoData()?.video_id || null;
|
|
418
|
+
this.#attachToMaster();
|
|
419
|
+
return;
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
// Create new master emitter for this specific container
|
|
423
|
+
const masterEmitter = new events.EventEmitter();
|
|
424
|
+
|
|
425
|
+
// Map YouTube API events to the Master Emitter
|
|
426
|
+
/** @type {Record<string, HandlerFunc>} */
|
|
427
|
+
const playerEvents = {};
|
|
428
|
+
Object.entries(YoutubeMediaAdapter.EVENT_MAPPING).forEach(([ytEvent, internalEvent]) => {
|
|
429
|
+
playerEvents[ytEvent] = (...args) => {
|
|
430
|
+
const result = masterEmitter.emit(internalEvent, ...args);
|
|
431
|
+
// Bridge YouTube states to semantic events: play, pause, ended
|
|
432
|
+
if (ytEvent === 'onStateChange') {
|
|
433
|
+
const state = args[0];
|
|
434
|
+
if (objChecker.isValidObj(state)) {
|
|
435
|
+
if (state.data === YoutubeMediaAdapter.PlayerState.PLAYING) masterEmitter.emit('play');
|
|
436
|
+
if (state.data === YoutubeMediaAdapter.PlayerState.PAUSED) masterEmitter.emit('pause');
|
|
437
|
+
if (state.data === YoutubeMediaAdapter.PlayerState.ENDED) masterEmitter.emit('ended');
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
return result;
|
|
441
|
+
};
|
|
442
|
+
});
|
|
443
|
+
|
|
444
|
+
return new Promise((resolve) => {
|
|
445
|
+
const Player = getYtPlayer();
|
|
446
|
+
this.#player = new Player(this.#container, {
|
|
447
|
+
videoId: videoId,
|
|
448
|
+
playerVars: { playsinline: 1 },
|
|
449
|
+
events: playerEvents,
|
|
450
|
+
});
|
|
451
|
+
|
|
452
|
+
// Register this container and its master emitter with initial refCount
|
|
453
|
+
YoutubeMediaAdapter.#registry.set(this.#container, {
|
|
454
|
+
player: this.#player,
|
|
455
|
+
masterEmitter: masterEmitter,
|
|
456
|
+
refCount: 1,
|
|
457
|
+
});
|
|
458
|
+
|
|
459
|
+
this.#masterEmitter = masterEmitter;
|
|
460
|
+
|
|
461
|
+
// Resolve the initialization promise when the player is ready
|
|
462
|
+
this.#masterEmitter?.once('onReady', () => {
|
|
463
|
+
this.#startPollingTimeUpdate();
|
|
464
|
+
resolve();
|
|
465
|
+
});
|
|
466
|
+
|
|
467
|
+
this.#attachToMaster();
|
|
468
|
+
});
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
/**
|
|
472
|
+
* Starts a polling interval to emit 'timeupdate' events, matching the HTML5 Audio interface.
|
|
473
|
+
*/
|
|
474
|
+
#startPollingTimeUpdate() {
|
|
475
|
+
this.#timeUpdateInterval = setInterval(() => {
|
|
476
|
+
if (
|
|
477
|
+
this.#player &&
|
|
478
|
+
this.#player.getPlayerState() === YoutubeMediaAdapter.PlayerState.PLAYING
|
|
479
|
+
) {
|
|
480
|
+
this.#masterEmitter?.emit('timeupdate', this.getTimeData());
|
|
481
|
+
}
|
|
482
|
+
}, 250);
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
/**
|
|
486
|
+
* Connects this instance to the master emitter of the shared player.
|
|
487
|
+
*/
|
|
488
|
+
#attachToMaster() {
|
|
489
|
+
checkDestroy(this.#destroyed);
|
|
490
|
+
if (!this.#masterEmitter) return;
|
|
491
|
+
|
|
492
|
+
for (const eventName of Object.values(YoutubeMediaAdapter.EVENT_MAPPING)) {
|
|
493
|
+
/** @type {HandlerFunc} */
|
|
494
|
+
const handler = (...args) => this.emit(eventName, ...args);
|
|
495
|
+
this.#masterEmitter.on(eventName, handler);
|
|
496
|
+
this.#eventHandlers.push({ eventName, handler });
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
/**
|
|
501
|
+
* Extracts the 11-character video ID from a URL or returns the string if it is already an ID.
|
|
502
|
+
* @param {string} url - The URL or ID.
|
|
503
|
+
* @returns {string} The extracted video ID.
|
|
504
|
+
*/
|
|
505
|
+
#extractVideoId(url) {
|
|
506
|
+
checkDestroy(this.#destroyed);
|
|
507
|
+
const regex =
|
|
508
|
+
/(?:youtube\.com\/(?:[^\/]+\/.+\/|(?:v|e(?:mbed)?)\/|.*[?&]v=)|youtu\.be\/)([^"&?\/\s]{11})/;
|
|
509
|
+
const match = url.match(regex);
|
|
510
|
+
return match ? match[1] : url;
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
/**
|
|
514
|
+
* Pauses the current playback.
|
|
515
|
+
* @returns {Promise<void>}
|
|
516
|
+
*/
|
|
517
|
+
async pause() {
|
|
518
|
+
checkDestroy(this.#destroyed);
|
|
519
|
+
this.#player?.pauseVideo();
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
/**
|
|
523
|
+
* Stops the playback completely.
|
|
524
|
+
* @returns {Promise<void>}
|
|
525
|
+
*/
|
|
526
|
+
async stop() {
|
|
527
|
+
checkDestroy(this.#destroyed);
|
|
528
|
+
this.#player?.stopVideo();
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
/**
|
|
532
|
+
* Seeks to a specific time in the media timeline.
|
|
533
|
+
* @param {number} timeMs - The target time in milliseconds.
|
|
534
|
+
* @returns {Promise<void>}
|
|
535
|
+
* @throws {TypeError} If timeMs is not a number.
|
|
536
|
+
*/
|
|
537
|
+
async seek(timeMs) {
|
|
538
|
+
checkDestroy(this.#destroyed);
|
|
539
|
+
if (typeof timeMs !== 'number') throw new TypeError('Time must be a number.');
|
|
540
|
+
const currentTime = timeMs / 1000;
|
|
541
|
+
this.#player?.seekTo(currentTime, true);
|
|
542
|
+
this.emit('seek', currentTime);
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
/**
|
|
546
|
+
* Retrieves the current playback time.
|
|
547
|
+
* @returns {number} The current time in milliseconds.
|
|
548
|
+
*/
|
|
549
|
+
getCurrentTime() {
|
|
550
|
+
checkDestroy(this.#destroyed);
|
|
551
|
+
return this.#player ? this.#player.getCurrentTime() * 1000 : 0;
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
/**
|
|
555
|
+
* Gets the total duration of the YouTube video.
|
|
556
|
+
* @returns {number} The total duration in milliseconds.
|
|
557
|
+
*/
|
|
558
|
+
getTotalDuration() {
|
|
559
|
+
checkDestroy(this.#destroyed);
|
|
560
|
+
return this.#player ? Math.floor(this.#player.getDuration() * 1000) : 0;
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
/**
|
|
564
|
+
* Gets the remaining time until the YouTube video ends.
|
|
565
|
+
* @returns {number} The remaining time in milliseconds.
|
|
566
|
+
*/
|
|
567
|
+
getRemainingTime() {
|
|
568
|
+
checkDestroy(this.#destroyed);
|
|
569
|
+
const total = this.getTotalDuration();
|
|
570
|
+
const current = this.getCurrentTime();
|
|
571
|
+
return total > 0 ? total - current : 0;
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
/**
|
|
575
|
+
* Gets the percentage of the YouTube video that has been played.
|
|
576
|
+
* @returns {number} The percentage from 0 to 100.
|
|
577
|
+
*/
|
|
578
|
+
getPlaybackPercentage() {
|
|
579
|
+
checkDestroy(this.#destroyed);
|
|
580
|
+
const total = this.getTotalDuration();
|
|
581
|
+
const current = this.getCurrentTime();
|
|
582
|
+
return total > 0 ? (current / total) * 100 : 0;
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
/**
|
|
586
|
+
* Sets the playback volume.
|
|
587
|
+
* @param {number} volume - The volume level from 0.0 to 1.0.
|
|
588
|
+
* @returns {void}
|
|
589
|
+
* @throws {RangeError} If volume is outside [0.0, 1.0].
|
|
590
|
+
*/
|
|
591
|
+
setVolume(volume) {
|
|
592
|
+
this.volume = volume;
|
|
593
|
+
}
|
|
594
|
+
|
|
595
|
+
/**
|
|
596
|
+
* Gets the playback volume.
|
|
597
|
+
* @returns {number}
|
|
598
|
+
* @throws {RangeError} If volume is outside [0.0, 1.0].
|
|
599
|
+
*/
|
|
600
|
+
getVolume() {
|
|
601
|
+
return this.volume;
|
|
602
|
+
}
|
|
603
|
+
|
|
604
|
+
/**
|
|
605
|
+
* Retrieves the thumbnail URL for the currently loaded video with a specified quality.
|
|
606
|
+
* @param {string} [quality='maxresdefault'] - The thumbnail quality.
|
|
607
|
+
* @returns {string|null} The thumbnail URL or null if no video is loaded.
|
|
608
|
+
*/
|
|
609
|
+
getThumbnailUrl(quality = 'maxresdefault') {
|
|
610
|
+
checkDestroy(this.#destroyed);
|
|
611
|
+
return this.#currentContentId
|
|
612
|
+
? YoutubeMediaAdapter.getThumbnailUrl(this.#currentContentId, quality)
|
|
613
|
+
: null;
|
|
614
|
+
}
|
|
615
|
+
|
|
616
|
+
/**
|
|
617
|
+
* Cleans up the instance and disconnects from the shared player.
|
|
618
|
+
*/
|
|
619
|
+
destroy() {
|
|
620
|
+
if (this.#destroyed) return;
|
|
621
|
+
|
|
622
|
+
if (this.#timeUpdateInterval) {
|
|
623
|
+
clearInterval(this.#timeUpdateInterval);
|
|
624
|
+
}
|
|
625
|
+
|
|
626
|
+
// 1. Detach from the master emitter
|
|
627
|
+
if (this.#masterEmitter && this.#eventHandlers.length > 0) {
|
|
628
|
+
for (const { eventName, handler } of this.#eventHandlers) {
|
|
629
|
+
this.#masterEmitter.off(eventName, handler);
|
|
630
|
+
}
|
|
631
|
+
this.#eventHandlers = [];
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
// 2. Handle Registry Cleanup (Reference Counting)
|
|
635
|
+
const existing = YoutubeMediaAdapter.#registry.get(this.#container);
|
|
636
|
+
if (existing) {
|
|
637
|
+
existing.refCount--;
|
|
638
|
+
// If this was the last instance using this player/container, clean up the registry
|
|
639
|
+
if (existing.refCount <= 0) {
|
|
640
|
+
YoutubeMediaAdapter.#registry.delete(this.#container);
|
|
641
|
+
}
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
this.#player = null;
|
|
645
|
+
this.#masterEmitter = null;
|
|
646
|
+
this.#currentContentId = null;
|
|
647
|
+
this.#destroyed = true;
|
|
648
|
+
super.destroy();
|
|
649
|
+
}
|
|
650
|
+
}
|
|
651
|
+
|
|
652
|
+
/**
|
|
653
|
+
* Asynchronously ensures the YouTube IFrame API is loaded and returns
|
|
654
|
+
* the YouTube Player constructor and the current player state mapping.
|
|
655
|
+
*
|
|
656
|
+
* @returns {Promise<{ Player: typeof YouTubePlayer, PlayerState: Record<string, number> }>}
|
|
657
|
+
* An object containing the Player constructor and the current player state mapping.
|
|
658
|
+
*/
|
|
659
|
+
const getYT = async () => {
|
|
660
|
+
await loadYoutubeApi();
|
|
661
|
+
return {
|
|
662
|
+
Player: getYtPlayer(),
|
|
663
|
+
PlayerState: getPlayerStateValues(),
|
|
664
|
+
};
|
|
665
|
+
};
|
|
666
|
+
|
|
667
|
+
exports.YoutubeMediaAdapter = YoutubeMediaAdapter;
|
|
668
|
+
exports.getPlayerStateValues = getPlayerStateValues;
|
|
669
|
+
exports.getYT = getYT;
|
|
670
|
+
exports.getYtPlayer = getYtPlayer;
|
|
671
|
+
exports.loadYoutubeApi = loadYoutubeApi;
|