tiny-essentials 1.19.3 → 1.20.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.
@@ -0,0 +1,486 @@
1
+ 'use strict';
2
+
3
+ var TinyEvents = require('./TinyEvents.cjs');
4
+
5
+ /**
6
+ * Stores polling intervals associated with window references.
7
+ * Used to detect when the window is closed.
8
+ *
9
+ * @type {WeakMap<Window, NodeJS.Timeout>}
10
+ */
11
+ const pollClosedInterval = new WeakMap();
12
+
13
+ /**
14
+ * @callback handler
15
+ * A function to handle incoming event payloads.
16
+ * @param {any} payload - The data sent by the emitter.
17
+ * @param {MessageEvent<any>} event - Metadata about the message.
18
+ */
19
+
20
+ /**
21
+ * TinyNewWinEvents provides structured communication between a main window
22
+ * and a child window (created using window.open) using postMessage.
23
+ *
24
+ * It supports routing, queuing messages until handshake is ready,
25
+ * connection status checks, and close detection.
26
+ *
27
+ * @class
28
+ */
29
+ class TinyNewWinEvents {
30
+ #events = new TinyEvents();
31
+
32
+ /**
33
+ * Enables or disables throwing an error when the maximum number of listeners is exceeded.
34
+ *
35
+ * @param {boolean} shouldThrow - If true, an error will be thrown when the max is exceeded.
36
+ */
37
+ setThrowOnMaxListeners(shouldThrow) {
38
+ return this.#events.setThrowOnMaxListeners(shouldThrow);
39
+ }
40
+
41
+ /**
42
+ * Checks whether an error will be thrown when the max listener limit is exceeded.
43
+ *
44
+ * @returns {boolean} True if an error will be thrown, false if only a warning is shown.
45
+ */
46
+ getThrowOnMaxListeners() {
47
+ return this.#events.getThrowOnMaxListeners();
48
+ }
49
+
50
+ /////////////////////////////////////////////////////////////
51
+
52
+ /**
53
+ * Adds a listener to the beginning of the listeners array for the specified event.
54
+ *
55
+ * @param {string} event - Event name.
56
+ * @param {handler} handler - The callback function.
57
+ */
58
+ prependListener(event, handler) {
59
+ return this.#events.prependListener(event, handler);
60
+ }
61
+
62
+ /**
63
+ * Adds a one-time listener to the beginning of the listeners array for the specified event.
64
+ *
65
+ * @param {string} event - Event name.
66
+ * @param {handler} handler - The callback function.
67
+ * @returns {handler} - The wrapped handler used internally.
68
+ */
69
+ prependListenerOnce(event, handler) {
70
+ return this.#events.prependListenerOnce(event, handler);
71
+ }
72
+
73
+ //////////////////////////////////////////////////////////////////////
74
+
75
+ /**
76
+ * Adds a event listener.
77
+ *
78
+ * @param {string} event - Event name, such as 'onScrollBoundary' or 'onAutoScroll'.
79
+ * @param {handler} handler - Callback function to be called when event fires.
80
+ */
81
+ appendListener(event, handler) {
82
+ return this.#events.appendListener(event, handler);
83
+ }
84
+
85
+ /**
86
+ * Registers an event listener that runs only once, then is removed.
87
+ *
88
+ * @param {string} event - Event name, such as 'onScrollBoundary' or 'onAutoScroll'.
89
+ * @param {handler} handler - The callback function to run on event.
90
+ * @returns {handler} - The wrapped version of the handler.
91
+ */
92
+ appendListenerOnce(event, handler) {
93
+ return this.#events.appendListenerOnce(event, handler);
94
+ }
95
+
96
+ /**
97
+ * Adds a event listener.
98
+ *
99
+ * @param {string} event - Event name, such as 'onScrollBoundary' or 'onAutoScroll'.
100
+ * @param {handler} handler - Callback function to be called when event fires.
101
+ */
102
+ on(event, handler) {
103
+ return this.#events.on(event, handler);
104
+ }
105
+
106
+ /**
107
+ * Registers an event listener that runs only once, then is removed.
108
+ *
109
+ * @param {string} event - Event name, such as 'onScrollBoundary' or 'onAutoScroll'.
110
+ * @param {handler} handler - The callback function to run on event.
111
+ * @returns {handler} - The wrapped version of the handler.
112
+ */
113
+ once(event, handler) {
114
+ return this.#events.once(event, handler);
115
+ }
116
+
117
+ ////////////////////////////////////////////////////////////////////
118
+
119
+ /**
120
+ * Removes a previously registered event listener.
121
+ *
122
+ * @param {string} event - The name of the event to remove the handler from.
123
+ * @param {handler} handler - The specific callback function to remove.
124
+ */
125
+ off(event, handler) {
126
+ return this.#events.off(event, handler);
127
+ }
128
+
129
+ /**
130
+ * Removes all event listeners of a specific type from the element.
131
+ *
132
+ * @param {string} event - The event type to remove (e.g. 'onScrollBoundary').
133
+ */
134
+ offAll(event) {
135
+ return this.#events.offAll(event);
136
+ }
137
+
138
+ /**
139
+ * Removes all event listeners of all types from the element.
140
+ */
141
+ offAllTypes() {
142
+ return this.#events.offAllTypes();
143
+ }
144
+
145
+ ////////////////////////////////////////////////////////////
146
+
147
+ /**
148
+ * Returns the number of listeners for a given event.
149
+ *
150
+ * @param {string} event - The name of the event.
151
+ * @returns {number} Number of listeners for the event.
152
+ */
153
+ listenerCount(event) {
154
+ return this.#events.listenerCount(event);
155
+ }
156
+
157
+ /**
158
+ * Returns a copy of the array of listeners for the specified event.
159
+ *
160
+ * @param {string} event - The name of the event.
161
+ * @returns {handler[]} Array of listener functions.
162
+ */
163
+ listeners(event) {
164
+ return this.#events.listeners(event);
165
+ }
166
+
167
+ /**
168
+ * Returns a copy of the array of listeners for the specified event.
169
+ *
170
+ * @param {string} event - The name of the event.
171
+ * @returns {handler[]} Array of listener functions.
172
+ */
173
+ onceListeners(event) {
174
+ return this.#events.onceListeners(event);
175
+ }
176
+
177
+ /**
178
+ * Returns a copy of the internal listeners array for the specified event,
179
+ * including wrapper functions like those used by `.once()`.
180
+ * @param {string | symbol} event - The event name.
181
+ * @returns {handler[]} An array of raw listener functions.
182
+ */
183
+ allListeners(event) {
184
+ return this.#events.allListeners(event);
185
+ }
186
+
187
+ /**
188
+ * Returns an array of event names for which there are registered listeners.
189
+ *
190
+ * @returns {string[]} Array of registered event names.
191
+ */
192
+ eventNames() {
193
+ return this.#events.eventNames();
194
+ }
195
+
196
+ //////////////////////////////////////////////////////
197
+
198
+ /**
199
+ * Sets the maximum number of listeners per event before a warning is shown.
200
+ *
201
+ * @param {number} n - The maximum number of listeners.
202
+ */
203
+ setMaxListeners(n) {
204
+ return this.#events.setMaxListeners(n);
205
+ }
206
+
207
+ /**
208
+ * Gets the maximum number of listeners allowed per event.
209
+ *
210
+ * @returns {number} The maximum number of listeners.
211
+ */
212
+ getMaxListeners() {
213
+ return this.#events.getMaxListeners();
214
+ }
215
+
216
+ ///////////////////////////////////////////////////
217
+
218
+ /** @type {Window|null} Reference to the opened or parent window */
219
+ #windowRef;
220
+
221
+ /** @type {string} Expected origin for postMessage communication */
222
+ #targetOrigin;
223
+
224
+ /** @type {{ route: string, payload: any }[]} Queue of messages emitted before connection is ready */
225
+ #pendingQueue = [];
226
+
227
+ /** @type {boolean} True if handshake between windows is complete */
228
+ #ready = false;
229
+
230
+ /** @type {boolean} True if this instance is the main window (host) */
231
+ #isHost = false;
232
+
233
+ /** @type {NodeJS.Timeout|null} Interval for polling child window closure */
234
+ #pollClosedInterval = null;
235
+
236
+ /** @type {string} Internal message type for handshake */
237
+ #readyEventName = '__TNE_READY__';
238
+
239
+ /** @type {string} Internal message type for routed communication */
240
+ #routeEventName = '__TNE_ROUTE__';
241
+
242
+ /**
243
+ * Gets the internal handshake event name.
244
+ * @returns {string}
245
+ */
246
+ get readyEventName() {
247
+ return this.#readyEventName;
248
+ }
249
+
250
+ /**
251
+ * Sets the internal handshake event name.
252
+ * @param {string} name
253
+ * @throws {TypeError} If the value is not a string.
254
+ */
255
+ set readyEventName(name) {
256
+ if (typeof name !== 'string') throw new TypeError('TinyNewWinEvents: readyEventName must be a string.');
257
+ this.#readyEventName = name;
258
+ }
259
+
260
+ /**
261
+ * Gets the internal route event name.
262
+ * @returns {string}
263
+ */
264
+ get routeEventName() {
265
+ return this.#routeEventName;
266
+ }
267
+
268
+ /**
269
+ * Sets the internal route event name.
270
+ * @param {string} name
271
+ * @throws {TypeError} If the value is not a string.
272
+ */
273
+ set routeEventName(name) {
274
+ if (typeof name !== 'string') throw new TypeError('TinyNewWinEvents: routeEventName must be a string.');
275
+ this.#routeEventName = name;
276
+ }
277
+
278
+ /**
279
+ * Initializes a TinyNewWinEvents instance for communication.
280
+ *
281
+ * @param {Object} [settings={}] Configuration object.
282
+ * @param {string} [settings.targetOrigin] Origin to enforce in postMessage.
283
+ * @param {string} [settings.url] URL string to open.
284
+ * @param {string} [settings.name] Window name (required if opening a new window).
285
+ * @param {string} [settings.features] Features string for `window.open`.
286
+ *
287
+ * @throws {Error} If `name` is "_blank", which is not allowed.
288
+ * @throws {TypeError} If `targetOrigin`, `url`, or `features` are not strings (when provided).
289
+ * @throws {Error} If the window reference is invalid or already being tracked.
290
+ */
291
+ constructor({ targetOrigin, url, name, features } = {}) {
292
+ if (typeof name === 'string' && name === '_blank')
293
+ throw new Error(
294
+ 'TinyNewWinEvents: The window name "_blank" is not supported. Please use a custom name to allow tracking.',
295
+ );
296
+ if (typeof targetOrigin !== 'undefined' && typeof targetOrigin !== 'string')
297
+ throw new TypeError('TinyNewWinEvents: The "targetOrigin" option must be a string.');
298
+ if (typeof url !== 'undefined' && typeof url !== 'string')
299
+ throw new TypeError('TinyNewWinEvents: The "url" option must be a string.');
300
+ if (typeof features !== 'undefined' && typeof features !== 'string')
301
+ throw new TypeError('TinyNewWinEvents: The "features" option must be a string if provided.');
302
+
303
+ // Open Page
304
+ if (typeof url === 'undefined') this.#windowRef = window.opener;
305
+ // Main Page
306
+ else {
307
+ this.#windowRef = typeof url === 'string' ? window.open(url, name, features) : url;
308
+ this.#isHost = true;
309
+ }
310
+
311
+ if (!this.#windowRef || pollClosedInterval.has(this.#windowRef))
312
+ throw new Error('Invalid or duplicate window reference.');
313
+ this.#targetOrigin = targetOrigin ?? window.location.origin;
314
+ this._handleMessage = this.#handleMessage.bind(this);
315
+ window.addEventListener('message', this._handleMessage, false);
316
+
317
+ // Sends handshake if it is host (main window)
318
+ if (!this.#isHost) {
319
+ this.#postRaw(this.#readyEventName, null);
320
+ this.#startCloseWatcher();
321
+ }
322
+ }
323
+
324
+ /**
325
+ * Returns the internal window reference.
326
+ *
327
+ * @returns {Window|null}
328
+ */
329
+ getWin() {
330
+ return this.#windowRef;
331
+ }
332
+
333
+ /**
334
+ * Internal message handler.
335
+ *
336
+ * @param {MessageEvent} event
337
+ * @returns {void}
338
+ */
339
+ #handleMessage(event) {
340
+ if (!event.source || (this.#windowRef && event.source !== this.#windowRef)) return;
341
+ const { type, route, payload } = event.data || {};
342
+
343
+ if (type === this.#readyEventName) {
344
+ this.#ready = true;
345
+ this.#flushQueue();
346
+ this.#startCloseWatcher(); // start watcher after handshake (for child window)
347
+ if (this.#isHost) this.#postRaw(this.#readyEventName, null);
348
+ return;
349
+ }
350
+
351
+ if (type === this.#routeEventName) this.#events.emit(route, payload, event);
352
+ }
353
+
354
+ /**
355
+ * Sends all pending messages queued before handshake completion.
356
+ *
357
+ * @returns {void}
358
+ */
359
+ #flushQueue() {
360
+ while (this.#pendingQueue.length) {
361
+ const data = this.#pendingQueue.shift();
362
+ if (data) {
363
+ const { route, payload } = data;
364
+ this.emit(route, payload);
365
+ }
366
+ }
367
+ }
368
+
369
+ /**
370
+ * Sends a raw postMessage with given type and payload.
371
+ *
372
+ * @param {string} type Internal message type
373
+ * @param {any} payload Data to send
374
+ * @param {string} [route=''] Optional route name
375
+ * @returns {void}
376
+ */
377
+ #postRaw(type, payload, route = '') {
378
+ if (this.#windowRef && this.#windowRef.closed) return;
379
+ this.#windowRef?.postMessage({ type, route, payload }, this.#targetOrigin);
380
+ }
381
+
382
+ /**
383
+ * Closes the child window (only allowed from the host).
384
+ *
385
+ * @returns {void}
386
+ */
387
+ close() {
388
+ if (!this.#isHost) throw new Error('Only host can close the window.');
389
+ if (this.#windowRef && !this.#windowRef.closed) this.#windowRef.close();
390
+ }
391
+
392
+ /**
393
+ * Emits a message to the other window on a specific route.
394
+ * If the handshake is not yet complete, the message is queued.
395
+ * Throws an error if the instance has already been destroyed.
396
+ *
397
+ * @param {string} route - Route name used to identify the message handler.
398
+ * @param {any} payload - Data to send along with the message.
399
+ * @throws {Error} If the instance is already destroyed.
400
+ * @returns {void}
401
+ */
402
+ emit(route, payload) {
403
+ if (typeof route !== 'string') throw new TypeError('Event name must be a string.');
404
+ if (this.isDestroyed()) throw new Error('Cannot emit: instance has been destroyed.');
405
+ if (!this.#ready) {
406
+ this.#pendingQueue.push({ route, payload });
407
+ return;
408
+ }
409
+ this.#postRaw(this.#routeEventName, payload, route);
410
+ }
411
+
412
+ /**
413
+ * Checks if the connection is active and the window is still open.
414
+ *
415
+ * @returns {boolean}
416
+ */
417
+ isConnected() {
418
+ return this.#ready && this.#windowRef && !this.#windowRef.closed ? true : false;
419
+ }
420
+
421
+ /**
422
+ * Starts polling to detect when the window is closed.
423
+ *
424
+ * @returns {void}
425
+ */
426
+ #startCloseWatcher() {
427
+ if (!this.#windowRef || this.#pollClosedInterval) return;
428
+ this.#pollClosedInterval = setInterval(() => {
429
+ if (this.#windowRef?.closed) {
430
+ this.#events.emit('WINDOW_REF_CLOSED');
431
+ this.destroy();
432
+ }
433
+ }, 500);
434
+ pollClosedInterval.set(this.#windowRef, this.#pollClosedInterval);
435
+ }
436
+
437
+ /**
438
+ * Registers a callback for when the window is closed.
439
+ *
440
+ * @param {handler} callback Callback to run on close
441
+ * @returns {void}
442
+ */
443
+ onClose(callback) {
444
+ return this.#events.on('WINDOW_REF_CLOSED', callback);
445
+ }
446
+
447
+ /**
448
+ * Unregisters a previously registered close callback.
449
+ *
450
+ * @param {handler} callback Callback to remove
451
+ * @returns {void}
452
+ */
453
+ offClose(callback) {
454
+ return this.#events.off('WINDOW_REF_CLOSED', callback);
455
+ }
456
+
457
+ /**
458
+ * Checks if the communication instance has been destroyed.
459
+ *
460
+ * @returns {boolean}
461
+ */
462
+ isDestroyed() {
463
+ return !this.#windowRef;
464
+ }
465
+
466
+ /**
467
+ * Destroys the communication instance, cleaning up all resources and listeners.
468
+ *
469
+ * @returns {void}
470
+ */
471
+ destroy() {
472
+ if (!this.#windowRef) return;
473
+ if (this.#pollClosedInterval) {
474
+ clearInterval(this.#pollClosedInterval);
475
+ this.#pollClosedInterval = null;
476
+ pollClosedInterval.delete(this.#windowRef);
477
+ }
478
+ window.removeEventListener('message', this._handleMessage);
479
+ this.#pendingQueue = [];
480
+ this.#ready = false;
481
+ this.#windowRef = null;
482
+ this.#events.offAllTypes();
483
+ }
484
+ }
485
+
486
+ module.exports = TinyNewWinEvents;