fullscreen-engine 1.0.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/README.md +109 -49
  2. package/bin/fullscreen-engine.js +162 -0
  3. package/dist/adapters/electron.cjs +2 -1
  4. package/dist/adapters/electron.cjs.map +1 -1
  5. package/dist/adapters/electron.esm.js +2 -1
  6. package/dist/adapters/electron.esm.js.map +1 -1
  7. package/dist/adapters/puppeteer.cjs +1 -1
  8. package/dist/adapters/puppeteer.esm.js +1 -1
  9. package/dist/adapters/ssr.cjs +2 -1
  10. package/dist/adapters/ssr.cjs.map +1 -1
  11. package/dist/adapters/ssr.esm.js +2 -1
  12. package/dist/adapters/ssr.esm.js.map +1 -1
  13. package/dist/config.cjs +2282 -0
  14. package/dist/config.cjs.map +1 -0
  15. package/dist/config.esm.js +2276 -0
  16. package/dist/config.esm.js.map +1 -0
  17. package/dist/fullscreen.esm.js +1013 -18
  18. package/dist/fullscreen.esm.js.map +1 -1
  19. package/dist/fullscreen.esm.min.js +2 -2
  20. package/dist/fullscreen.esm.min.js.map +1 -1
  21. package/dist/fullscreen.iife.js +1017 -18
  22. package/dist/fullscreen.iife.js.map +1 -1
  23. package/dist/fullscreen.umd.cjs +1017 -18
  24. package/dist/fullscreen.umd.cjs.map +1 -1
  25. package/dist/fullscreen.umd.min.cjs +2 -2
  26. package/dist/fullscreen.umd.min.cjs.map +1 -1
  27. package/package.json +15 -3
  28. package/src/adapters/electron.js +1 -0
  29. package/src/adapters/ssr.js +1 -0
  30. package/src/config-loader.js +114 -0
  31. package/src/config.js +187 -0
  32. package/src/core.js +201 -5
  33. package/src/fallback.js +22 -8
  34. package/src/guards.js +277 -0
  35. package/src/index.js +2 -1
  36. package/src/vendor.js +1 -0
  37. package/types/config.d.ts +40 -0
  38. package/types/electron.d.ts +4 -0
  39. package/types/index.d.ts +94 -1
  40. package/types/ssr.d.ts +1 -0
@@ -0,0 +1,2276 @@
1
+ /*! fullscreen-engine v1.2.0 | MIT */
2
+ import { existsSync, statSync, readFileSync } from 'node:fs';
3
+ import { createRequire } from 'node:module';
4
+ import { resolve, extname } from 'node:path';
5
+ import { pathToFileURL } from 'node:url';
6
+
7
+ /**
8
+ * Tiny event emitter. No dependencies.
9
+ */
10
+
11
+ class Emitter {
12
+ #listeners = new Map();
13
+
14
+ on(event, cb) {
15
+ if (typeof cb !== 'function') throw new TypeError('listener must be a function');
16
+ if (!this.#listeners.has(event)) this.#listeners.set(event, new Set());
17
+ this.#listeners.get(event).add(cb);
18
+ return () => this.off(event, cb);
19
+ }
20
+
21
+ once(event, cb) {
22
+ if (typeof cb !== 'function') throw new TypeError('listener must be a function');
23
+ const wrapper = (...args) => {
24
+ this.off(event, wrapper);
25
+ cb(...args);
26
+ };
27
+ wrapper._original = cb;
28
+ return this.on(event, wrapper);
29
+ }
30
+
31
+ off(event, cb) {
32
+ const set = this.#listeners.get(event);
33
+ if (!set) return;
34
+ if (set.has(cb)) {
35
+ set.delete(cb);
36
+ } else {
37
+ for (const fn of set) {
38
+ if (fn._original === cb) {
39
+ set.delete(fn);
40
+ break;
41
+ }
42
+ }
43
+ }
44
+ if (set.size === 0) this.#listeners.delete(event);
45
+ }
46
+
47
+ emit(event, ...args) {
48
+ const set = this.#listeners.get(event);
49
+ if (!set) return;
50
+ // copy so listeners can safely remove themselves
51
+ for (const cb of Array.from(set)) {
52
+ try {
53
+ cb(...args);
54
+ } catch (err) {
55
+ // don't break other listeners
56
+ // eslint-disable-next-line no-console
57
+ console.error(`[fullscreen-engine] listener error on "${event}":`, err);
58
+ }
59
+ }
60
+ }
61
+
62
+ clear() {
63
+ this.#listeners.clear();
64
+ }
65
+
66
+ listenerCount(event) {
67
+ return this.#listeners.get(event)?.size ?? 0;
68
+ }
69
+ }
70
+
71
+ /**
72
+ * Small, dependency-free helpers.
73
+ */
74
+
75
+ function isBrowser() {
76
+ return (
77
+ typeof window !== 'undefined' &&
78
+ typeof document !== 'undefined' &&
79
+ typeof document.createElement === 'function'
80
+ );
81
+ }
82
+
83
+ function isNode() {
84
+ return (
85
+ typeof process !== 'undefined' &&
86
+ !!(process.versions && process.versions.node) &&
87
+ !isBrowser()
88
+ );
89
+ }
90
+
91
+ function isElectron() {
92
+ if (!isBrowser()) return false;
93
+ return !!(
94
+ (window.process && window.process.versions && window.process.versions.electron) ||
95
+ typeof window.fsNative !== 'undefined'
96
+ );
97
+ }
98
+
99
+ /**
100
+ * Wrap a function that may or may not return a Promise
101
+ * (older prefixed fullscreen methods don't return one).
102
+ */
103
+ function maybePromise(fn) {
104
+ return new Promise((resolve, reject) => {
105
+ try {
106
+ const result = fn();
107
+ if (result && typeof result.then === 'function') {
108
+ result.then(resolve, reject);
109
+ } else {
110
+ resolve(result);
111
+ }
112
+ } catch (err) {
113
+ reject(err);
114
+ }
115
+ });
116
+ }
117
+
118
+ /**
119
+ * Vendor / prefix detection for fullscreen APIs.
120
+ * Works in browsers; returns null in Node/SSR.
121
+ */
122
+
123
+
124
+ const PREFIXES = ['webkit', 'moz', 'ms'];
125
+
126
+ function deriveVendorPrefix(reqMethod) {
127
+ if (!reqMethod) return '';
128
+ if (reqMethod.startsWith('webkit')) return 'webkit';
129
+ if (reqMethod.startsWith('moz')) return 'moz';
130
+ if (reqMethod.startsWith('ms')) return 'ms';
131
+ return '';
132
+ }
133
+
134
+ function detectEnvironment(root = null) {
135
+ if (!isBrowser()) return null;
136
+
137
+ const el = root || (typeof document !== 'undefined' ? document.documentElement : null);
138
+ if (!el) return null;
139
+
140
+ // request method
141
+ let request = null;
142
+ if (typeof el.requestFullscreen === 'function') request = 'requestFullscreen';
143
+ else {
144
+ for (const p of PREFIXES) {
145
+ const m = `${p}RequestFullscreen`;
146
+ const m2 = `${p}RequestFullScreen`; // Firefox older
147
+ if (typeof el[m] === 'function') { request = m; break; }
148
+ if (typeof el[m2] === 'function') { request = m2; break; }
149
+ }
150
+ }
151
+
152
+ // exit method
153
+ let exit = null;
154
+ if (typeof document.exitFullscreen === 'function') exit = 'exitFullscreen';
155
+ else {
156
+ for (const p of PREFIXES) {
157
+ const m = `${p}ExitFullscreen`;
158
+ const m2 = `${p}CancelFullScreen`;
159
+ if (typeof document[m] === 'function') { exit = m; break; }
160
+ if (typeof document[m2] === 'function') { exit = m2; break; }
161
+ }
162
+ }
163
+
164
+ // element property (who is fullscreen right now)
165
+ let elementProp = null;
166
+ for (const prop of [
167
+ 'fullscreenElement',
168
+ 'webkitFullscreenElement',
169
+ 'mozFullScreenElement',
170
+ 'msFullscreenElement'
171
+ ]) {
172
+ if (prop in document) { elementProp = prop; break; }
173
+ }
174
+
175
+ // enabled property (policy / iframe allowfullscreen check)
176
+ let enabledProp = null;
177
+ for (const prop of [
178
+ 'fullscreenEnabled',
179
+ 'webkitFullscreenEnabled',
180
+ 'mozFullScreenEnabled',
181
+ 'msFullscreenEnabled'
182
+ ]) {
183
+ if (prop in document) { enabledProp = prop; break; }
184
+ }
185
+ const policyAllowed = enabledProp ? Boolean(document[enabledProp]) : true;
186
+
187
+ const vendorPrefix = deriveVendorPrefix(request);
188
+
189
+ // change event name
190
+ let changeEvent = null;
191
+ for (const evt of [
192
+ 'fullscreenchange',
193
+ 'webkitfullscreenchange',
194
+ 'mozfullscreenchange',
195
+ 'MSFullscreenChange',
196
+ 'msfullscreenchange'
197
+ ]) {
198
+ if (`on${evt}` in document) { changeEvent = evt; break; }
199
+ }
200
+ if (!changeEvent) {
201
+ if (vendorPrefix === 'webkit') changeEvent = 'webkitfullscreenchange';
202
+ else if (vendorPrefix === 'moz') changeEvent = 'mozfullscreenchange';
203
+ else if (vendorPrefix === 'ms') changeEvent = 'MSFullscreenChange';
204
+ else changeEvent = 'fullscreenchange';
205
+ }
206
+
207
+ // error event name
208
+ let errorEvent = null;
209
+ for (const evt of [
210
+ 'fullscreenerror',
211
+ 'webkitfullscreenerror',
212
+ 'mozfullscreenerror',
213
+ 'MSFullscreenError',
214
+ 'msfullscreenerror'
215
+ ]) {
216
+ if (`on${evt}` in document) { errorEvent = evt; break; }
217
+ }
218
+ if (!errorEvent) {
219
+ if (vendorPrefix === 'webkit') errorEvent = 'webkitfullscreenerror';
220
+ else if (vendorPrefix === 'moz') errorEvent = 'mozfullscreenerror';
221
+ else if (vendorPrefix === 'ms') errorEvent = 'MSFullscreenError';
222
+ else errorEvent = 'fullscreenerror';
223
+ }
224
+
225
+ return {
226
+ request,
227
+ exit,
228
+ elementProp,
229
+ enabledProp,
230
+ prefix: vendorPrefix,
231
+ changeEvent,
232
+ errorEvent,
233
+ supported: !!(request && exit && elementProp && policyAllowed)
234
+ };
235
+ }
236
+
237
+ /**
238
+ * CSS-based fake fullscreen fallback.
239
+ * Used when native API is unavailable (e.g. iPhone Safari)
240
+ * or when the request is rejected.
241
+ *
242
+ * This does NOT cover browser chrome; it only makes the target
243
+ * element fill the viewport. That's the best a page can do.
244
+ */
245
+
246
+ const styleRefCounts = new Map();
247
+ const lockRefCounts = new Map();
248
+
249
+ function sanitizeClassName(name, fallback) {
250
+ const cleaned = String(name || '').replace(/[^a-zA-Z0-9_-]/g, '_');
251
+ return cleaned || fallback;
252
+ }
253
+
254
+ function sanitizeZIndex(val) {
255
+ if (val === null || val === undefined || val === '' || typeof val === 'boolean') {
256
+ return 2147483647;
257
+ }
258
+ const num = Number(val);
259
+ return Number.isFinite(num) ? Math.trunc(num) : 2147483647;
260
+ }
261
+
262
+ function getStyleId(baseClass, lockClass, zIndex, freezePage = false) {
263
+ return `__fullscreen_engine_style_${baseClass}_${lockClass}_${zIndex}${freezePage ? '_freeze' : ''}__`;
264
+ }
265
+
266
+ function buildCSS(baseClass, lockClass, zIndex, freezePage = false) {
267
+ const freezeTargetCSS = freezePage
268
+ ? `
269
+ overscroll-behavior: none !important;
270
+ touch-action: manipulation !important;
271
+ user-select: none !important;
272
+ -webkit-user-select: none !important;`
273
+ : '';
274
+ const freezeLockCSS = freezePage
275
+ ? `
276
+ overscroll-behavior: none !important;`
277
+ : '';
278
+ return `
279
+ .${baseClass} {
280
+ position: fixed !important;
281
+ top: 0 !important;
282
+ left: 0 !important;
283
+ right: 0 !important;
284
+ bottom: 0 !important;
285
+ width: 100vw !important;
286
+ height: 100vh !important;
287
+ height: 100dvh !important;
288
+ margin: 0 !important;
289
+ padding: 0 !important;
290
+ border: 0 !important;
291
+ z-index: ${zIndex} !important;
292
+ background: #000 !important;
293
+ overflow: auto !important;${freezeTargetCSS}
294
+ }
295
+ html.${lockClass}, body.${lockClass} {
296
+ overflow: hidden !important;
297
+ scrollbar-width: none !important;${freezeLockCSS}
298
+ }
299
+ `;
300
+ }
301
+
302
+ function ensureStyle(styleId, baseClass, lockClass, zIndex, freezePage = false) {
303
+ if (typeof document === 'undefined') return;
304
+ if (document.getElementById(styleId)) return;
305
+ const style = document.createElement('style');
306
+ style.id = styleId;
307
+ style.textContent = buildCSS(baseClass, lockClass, zIndex, freezePage);
308
+ (document.head || document.documentElement).appendChild(style);
309
+ }
310
+
311
+ function removeStyle(styleId) {
312
+ if (typeof document === 'undefined') return;
313
+ const style = document.getElementById(styleId);
314
+ if (style) style.remove();
315
+ }
316
+
317
+ function createFallback(opts) {
318
+ const baseClass = sanitizeClassName(opts.fallbackClass, 'fs-engine-active');
319
+ const lockClass = opts.lockBody === false ? '__no_lock__' : 'fs-engine-scroll-lock';
320
+ const zIndex = sanitizeZIndex(opts.zIndex);
321
+ const freezePage = !!opts.freezePage;
322
+ const styleId = getStyleId(baseClass, lockClass, zIndex, freezePage);
323
+ let active = false;
324
+ let activeTarget = null;
325
+ let styleRegistered = false;
326
+ let lockApplied = false;
327
+
328
+ function enter(target) {
329
+ if (typeof document === 'undefined' || !target || !target.classList) return;
330
+ if (!styleRegistered) {
331
+ styleRefCounts.set(styleId, (styleRefCounts.get(styleId) ?? 0) + 1);
332
+ styleRegistered = true;
333
+ }
334
+ ensureStyle(styleId, baseClass, lockClass, zIndex, freezePage);
335
+ activeTarget = target;
336
+ target.classList.add(baseClass);
337
+ if (opts.lockBody !== false && !lockApplied) {
338
+ lockRefCounts.set(lockClass, (lockRefCounts.get(lockClass) ?? 0) + 1);
339
+ lockApplied = true;
340
+ document.documentElement.classList.add(lockClass);
341
+ document.body && document.body.classList.add(lockClass);
342
+ }
343
+ active = true;
344
+ }
345
+
346
+ function exit() {
347
+ if (typeof document === 'undefined') return;
348
+ if (activeTarget && activeTarget.classList) {
349
+ activeTarget.classList.remove(baseClass);
350
+ }
351
+ if (opts.lockBody !== false && lockApplied) {
352
+ lockApplied = false;
353
+ const nextLockCount = (lockRefCounts.get(lockClass) ?? 1) - 1;
354
+ if (nextLockCount <= 0) {
355
+ lockRefCounts.delete(lockClass);
356
+ document.documentElement.classList.remove(lockClass);
357
+ document.body && document.body.classList.remove(lockClass);
358
+ } else {
359
+ lockRefCounts.set(lockClass, nextLockCount);
360
+ }
361
+ }
362
+ activeTarget = null;
363
+ active = false;
364
+ }
365
+
366
+ function destroy() {
367
+ exit();
368
+ if (styleRegistered) {
369
+ styleRegistered = false;
370
+ const nextCount = (styleRefCounts.get(styleId) ?? 1) - 1;
371
+ if (nextCount <= 0) {
372
+ styleRefCounts.delete(styleId);
373
+ removeStyle(styleId);
374
+ } else {
375
+ styleRefCounts.set(styleId, nextCount);
376
+ }
377
+ }
378
+ }
379
+
380
+ return {
381
+ enter,
382
+ exit,
383
+ destroy,
384
+ get active() { return active; }
385
+ };
386
+ }
387
+
388
+ /**
389
+ * Auto-trigger controller for mouse hover and page scroll fullscreen activation.
390
+ *
391
+ * Pairs with CSS fallback (or Electron IPC bridge) so hover and scroll events
392
+ * can enter fullscreen without triggering browser user-gesture SecurityErrors.
393
+ */
394
+
395
+
396
+ const VALID_TRIGGERS = new Set(['manual', 'hover', 'scroll']);
397
+
398
+ function normalizeThreshold(val) {
399
+ if (val === null || val === '' || typeof val === 'boolean') return 100;
400
+ const num = Number(val);
401
+ return Number.isFinite(num) ? Math.max(0, num) : 100;
402
+ }
403
+
404
+ function normalizeTriggers(triggerOption) {
405
+ const raw = Array.isArray(triggerOption)
406
+ ? triggerOption
407
+ : triggerOption !== undefined && triggerOption !== null
408
+ ? [triggerOption]
409
+ : ['manual'];
410
+
411
+ for (const item of raw) {
412
+ if (!VALID_TRIGGERS.has(item)) {
413
+ throw new TypeError(`[fullscreen-engine] invalid trigger "${String(item)}": expected 'manual', 'hover', or 'scroll'`);
414
+ }
415
+ }
416
+
417
+ const hasHover = raw.includes('hover');
418
+ const hasScroll = raw.includes('scroll');
419
+
420
+ return {
421
+ list: raw,
422
+ hasHover,
423
+ hasScroll,
424
+ isAuto: hasHover || hasScroll
425
+ };
426
+ }
427
+
428
+ function createAutoTriggers({
429
+ triggers,
430
+ resolveHoverTarget,
431
+ resolveScrollTarget,
432
+ hoverDelay = 0,
433
+ scrollThreshold = 100,
434
+ autoExit = true,
435
+ suppressOnManualExit = true,
436
+ isActive,
437
+ onEnter,
438
+ onExit
439
+ }) {
440
+ if (!triggers.isAuto || !isBrowser()) {
441
+ return {
442
+ notifyManualExit() {},
443
+ destroy() {}
444
+ };
445
+ }
446
+
447
+ const threshold = normalizeThreshold(scrollThreshold);
448
+
449
+ let destroyed = false;
450
+ let activeSource = null; // 'hover' | 'scroll' | null
451
+ let isHovered = false;
452
+ let hoverTimer = null;
453
+ let domReadyBound = false;
454
+ let enterSeq = 0;
455
+ let pendingExitSeq = null;
456
+ const suppressed = {
457
+ hover: false,
458
+ scroll: false
459
+ };
460
+
461
+ function clearHoverTimer() {
462
+ if (hoverTimer !== null) {
463
+ clearTimeout(hoverTimer);
464
+ hoverTimer = null;
465
+ }
466
+ }
467
+
468
+ // ---------- Hover & Scroll target state ----------
469
+ let boundHoverEl = null;
470
+ let boundScrollEl = null;
471
+
472
+ function getScrollY() {
473
+ if (boundScrollEl && typeof window !== 'undefined' && boundScrollEl !== window) {
474
+ return boundScrollEl.scrollTop ?? 0;
475
+ }
476
+ if (typeof window === 'undefined') return 0;
477
+ return (
478
+ window.scrollY ??
479
+ window.pageYOffset ??
480
+ (typeof document !== 'undefined' && document.documentElement
481
+ ? document.documentElement.scrollTop
482
+ : 0) ??
483
+ 0
484
+ );
485
+ }
486
+
487
+ function isScrollPastThreshold() {
488
+ return getScrollY() >= threshold;
489
+ }
490
+
491
+ function triggerEnter(source) {
492
+ if (destroyed) return;
493
+ if (suppressed[source]) return;
494
+ if (isActive()) return;
495
+ activeSource = source;
496
+ const seq = ++enterSeq;
497
+ Promise.resolve(onEnter(source))
498
+ .then(() => {
499
+ if (destroyed || seq !== enterSeq) {
500
+ if (pendingExitSeq === seq && isActive()) {
501
+ pendingExitSeq = null;
502
+ Promise.resolve(onExit(source)).catch(() => {});
503
+ }
504
+ return;
505
+ }
506
+ if (!isActive() && activeSource === source) {
507
+ activeSource = null;
508
+ }
509
+ })
510
+ .catch(() => {
511
+ if (seq === enterSeq && activeSource === source) {
512
+ activeSource = null;
513
+ }
514
+ });
515
+ }
516
+
517
+ function triggerExit(source) {
518
+ if (destroyed || !autoExit) return;
519
+ if (activeSource !== source) return;
520
+
521
+ // Transfer ownership if the other trigger condition is still active
522
+ if (source === 'hover' && triggers.hasScroll && isScrollPastThreshold() && !suppressed.scroll) {
523
+ activeSource = 'scroll';
524
+ return;
525
+ }
526
+ if (source === 'scroll' && triggers.hasHover && isHovered && !suppressed.hover) {
527
+ activeSource = 'hover';
528
+ return;
529
+ }
530
+
531
+ if (!isActive()) {
532
+ pendingExitSeq = enterSeq;
533
+ activeSource = null;
534
+ return;
535
+ }
536
+
537
+ activeSource = null;
538
+ onExit(source);
539
+ }
540
+
541
+ // ---------- Hover handlers ----------
542
+ function onMouseEnter() {
543
+ if (destroyed) return;
544
+ isHovered = true;
545
+ if (suppressed.hover) return;
546
+
547
+ clearHoverTimer();
548
+ const delay = Math.max(0, Number(hoverDelay) || 0);
549
+ if (delay > 0) {
550
+ hoverTimer = setTimeout(() => {
551
+ hoverTimer = null;
552
+ if (isHovered && !destroyed) {
553
+ triggerEnter('hover');
554
+ }
555
+ }, delay);
556
+ } else {
557
+ triggerEnter('hover');
558
+ }
559
+ }
560
+
561
+ function onMouseLeave() {
562
+ if (destroyed) return;
563
+ isHovered = false;
564
+ clearHoverTimer();
565
+ suppressed.hover = false;
566
+ triggerExit('hover');
567
+ }
568
+
569
+ function bindHoverTarget() {
570
+ if (destroyed || !triggers.hasHover || boundHoverEl) return;
571
+ const el = typeof resolveHoverTarget === 'function' ? resolveHoverTarget() : null;
572
+ if (el && typeof el.addEventListener === 'function') {
573
+ boundHoverEl = el;
574
+ boundHoverEl.addEventListener('mouseenter', onMouseEnter);
575
+ boundHoverEl.addEventListener('mouseleave', onMouseLeave);
576
+ }
577
+ }
578
+
579
+ // ---------- Scroll handler ----------
580
+ function onScroll() {
581
+ if (destroyed) return;
582
+ if (isScrollPastThreshold()) {
583
+ triggerEnter('scroll');
584
+ } else {
585
+ suppressed.scroll = false;
586
+ triggerExit('scroll');
587
+ }
588
+ }
589
+
590
+ function bindScrollTarget() {
591
+ if (destroyed || !triggers.hasScroll || boundScrollEl) return;
592
+ const target =
593
+ typeof resolveScrollTarget === 'function'
594
+ ? resolveScrollTarget()
595
+ : typeof window !== 'undefined'
596
+ ? window
597
+ : null;
598
+ if (target && typeof target.addEventListener === 'function') {
599
+ boundScrollEl = target;
600
+ boundScrollEl.addEventListener('scroll', onScroll, { passive: true });
601
+ }
602
+ }
603
+
604
+ bindHoverTarget();
605
+ bindScrollTarget();
606
+
607
+ function onDomReady() {
608
+ domReadyBound = false;
609
+ bindHoverTarget();
610
+ bindScrollTarget();
611
+ }
612
+
613
+ const needsDeferredBind =
614
+ (triggers.hasHover && !boundHoverEl) || (triggers.hasScroll && !boundScrollEl);
615
+
616
+ if (
617
+ needsDeferredBind &&
618
+ typeof document !== 'undefined' &&
619
+ document.readyState === 'loading' &&
620
+ typeof document.addEventListener === 'function'
621
+ ) {
622
+ domReadyBound = true;
623
+ document.addEventListener('DOMContentLoaded', onDomReady, { once: true });
624
+ }
625
+
626
+ function notifyManualExit() {
627
+ if (destroyed) return;
628
+ clearHoverTimer();
629
+ enterSeq += 1;
630
+ pendingExitSeq = null;
631
+ if (suppressOnManualExit) {
632
+ if (isHovered) suppressed.hover = true;
633
+ if (isScrollPastThreshold()) suppressed.scroll = true;
634
+ }
635
+ activeSource = null;
636
+ }
637
+
638
+ function destroy() {
639
+ if (destroyed) return;
640
+ destroyed = true;
641
+ clearHoverTimer();
642
+ enterSeq += 1;
643
+ pendingExitSeq = null;
644
+ if (
645
+ domReadyBound &&
646
+ typeof document !== 'undefined' &&
647
+ typeof document.removeEventListener === 'function'
648
+ ) {
649
+ document.removeEventListener('DOMContentLoaded', onDomReady);
650
+ domReadyBound = false;
651
+ }
652
+ if (boundHoverEl && typeof boundHoverEl.removeEventListener === 'function') {
653
+ boundHoverEl.removeEventListener('mouseenter', onMouseEnter);
654
+ boundHoverEl.removeEventListener('mouseleave', onMouseLeave);
655
+ }
656
+ boundHoverEl = null;
657
+ if (boundScrollEl && typeof boundScrollEl.removeEventListener === 'function') {
658
+ boundScrollEl.removeEventListener('scroll', onScroll);
659
+ }
660
+ boundScrollEl = null;
661
+ activeSource = null;
662
+ }
663
+
664
+ return {
665
+ notifyManualExit,
666
+ destroy
667
+ };
668
+ }
669
+
670
+ /**
671
+ * Cross-browser kiosk & exit-key guards (browser-safe, zero Node built-ins).
672
+ *
673
+ * Supports:
674
+ * - keyboardLock: navigator.keyboard?.lock(keys) on native fullscreen
675
+ * - blockShortcuts: keydown guard for F11, Escape (when exitLocked), or custom keys
676
+ * - confirmOnLeave: beforeunload prompt while exitLocked && active
677
+ * - blockContextMenu: contextmenu prevention while active
678
+ */
679
+
680
+ function normalizeKeyboardLock(val) {
681
+ if (val === undefined || val === null || val === false) {
682
+ return { enabled: false, keys: ['Escape', 'F11'] };
683
+ }
684
+ if (val === true) {
685
+ return { enabled: true, keys: ['Escape', 'F11'] };
686
+ }
687
+ if (Array.isArray(val)) {
688
+ const keys = val.map((k) => String(k)).filter(Boolean);
689
+ return { enabled: keys.length > 0, keys };
690
+ }
691
+ throw new TypeError(
692
+ '[fullscreen-engine] invalid keyboardLock option: expected boolean or string[]'
693
+ );
694
+ }
695
+
696
+ const DEFAULT_SHORTCUTS = [
697
+ 'F11',
698
+ 'Escape',
699
+ 'F5',
700
+ 'F12',
701
+ 'Ctrl+R',
702
+ 'Meta+R',
703
+ 'Ctrl+Shift+I',
704
+ 'Meta+Alt+I'
705
+ ];
706
+
707
+ function parseShortcut(raw) {
708
+ const parts = String(raw)
709
+ .split('+')
710
+ .map((p) => p.trim())
711
+ .filter(Boolean);
712
+ if (parts.length === 0) return null;
713
+ const key = parts[parts.length - 1].toLowerCase();
714
+ const mods = parts.slice(0, -1).map((m) => m.toLowerCase());
715
+ const hasModifiers = mods.length > 0;
716
+ return {
717
+ key,
718
+ hasModifiers,
719
+ ctrl: mods.includes('ctrl') || mods.includes('control'),
720
+ meta: mods.includes('meta') || mods.includes('cmd') || mods.includes('command'),
721
+ alt: mods.includes('alt') || mods.includes('option'),
722
+ shift: mods.includes('shift')
723
+ };
724
+ }
725
+
726
+ function matchesShortcut(e, rule) {
727
+ if (!rule || !e || !e.key) return false;
728
+ if (String(e.key).toLowerCase() !== rule.key) return false;
729
+ if (!rule.hasModifiers) return true;
730
+ return (
731
+ !!e.ctrlKey === rule.ctrl &&
732
+ !!e.metaKey === rule.meta &&
733
+ !!e.altKey === rule.alt &&
734
+ !!e.shiftKey === rule.shift
735
+ );
736
+ }
737
+
738
+ function normalizeBlockShortcuts(val) {
739
+ if (val === undefined || val === null || val === false) {
740
+ return { enabled: false, keys: ['F11'], rules: [parseShortcut('F11')] };
741
+ }
742
+ if (val === true) {
743
+ return {
744
+ enabled: true,
745
+ keys: DEFAULT_SHORTCUTS.slice(),
746
+ rules: DEFAULT_SHORTCUTS.map(parseShortcut).filter(Boolean)
747
+ };
748
+ }
749
+ if (Array.isArray(val)) {
750
+ const keys = val.map((k) => String(k).trim()).filter(Boolean);
751
+ const rules = keys.map(parseShortcut).filter(Boolean);
752
+ return { enabled: rules.length > 0, keys, rules };
753
+ }
754
+ throw new TypeError(
755
+ '[fullscreen-engine] invalid blockShortcuts option: expected boolean or string[]'
756
+ );
757
+ }
758
+
759
+ function createGuards({
760
+ keyboardLock,
761
+ blockShortcuts,
762
+ confirmOnLeave,
763
+ blockContextMenu,
764
+ watchFocus = false,
765
+ isExitLocked,
766
+ onExitAttempt,
767
+ onEscapeExit,
768
+ onFocusLost
769
+ }) {
770
+ let keyboardLocked = false;
771
+ let keydownBound = false;
772
+ let beforeUnloadBound = false;
773
+ let contextMenuBound = false;
774
+ let focusBound = false;
775
+
776
+ function releaseKeyboardLock() {
777
+ if (!keyboardLocked) return;
778
+ keyboardLocked = false;
779
+ if (
780
+ typeof navigator !== 'undefined' &&
781
+ navigator.keyboard &&
782
+ typeof navigator.keyboard.unlock === 'function'
783
+ ) {
784
+ try {
785
+ navigator.keyboard.unlock();
786
+ } catch {
787
+ // ignore unsupported unlock errors
788
+ }
789
+ }
790
+ }
791
+
792
+ function onKeyDown(e) {
793
+ if (!e || !e.key) return;
794
+ const rules = blockShortcuts.rules || blockShortcuts.keys.map(parseShortcut).filter(Boolean);
795
+ const matched = rules.some((rule) => matchesShortcut(e, rule));
796
+ if (!matched) return;
797
+ if (e.key === 'Escape' && !isExitLocked()) {
798
+ if (typeof onEscapeExit === 'function') onEscapeExit();
799
+ return;
800
+ }
801
+ if (typeof e.preventDefault === 'function') e.preventDefault();
802
+ if (typeof e.stopPropagation === 'function') e.stopPropagation();
803
+ if (typeof onExitAttempt === 'function') {
804
+ onExitAttempt(e.key === 'Escape' ? 'escape' : 'shortcut');
805
+ }
806
+ }
807
+
808
+ function onVisibilityChange() {
809
+ if (typeof document !== 'undefined' && document.hidden && typeof onFocusLost === 'function') {
810
+ onFocusLost('visibilitychange');
811
+ }
812
+ }
813
+
814
+ function onWindowBlur() {
815
+ if (typeof onFocusLost === 'function') {
816
+ onFocusLost('blur');
817
+ }
818
+ }
819
+
820
+ function onBeforeUnload(e) {
821
+ if (!isExitLocked()) return;
822
+ if (typeof e.preventDefault === 'function') e.preventDefault();
823
+ e.returnValue = '';
824
+ }
825
+
826
+ function onContextMenu(e) {
827
+ if (typeof e.preventDefault === 'function') e.preventDefault();
828
+ }
829
+
830
+ function bindKeydown() {
831
+ if (typeof document === 'undefined' || keydownBound) return;
832
+ document.addEventListener('keydown', onKeyDown, true);
833
+ keydownBound = true;
834
+ }
835
+
836
+ function unbindKeydown() {
837
+ if (typeof document === 'undefined' || !keydownBound) return;
838
+ document.removeEventListener('keydown', onKeyDown, true);
839
+ keydownBound = false;
840
+ }
841
+
842
+ function bindBeforeUnload() {
843
+ if (typeof window === 'undefined' || beforeUnloadBound) return;
844
+ window.addEventListener('beforeunload', onBeforeUnload);
845
+ beforeUnloadBound = true;
846
+ }
847
+
848
+ function unbindBeforeUnload() {
849
+ if (typeof window === 'undefined' || !beforeUnloadBound) return;
850
+ window.removeEventListener('beforeunload', onBeforeUnload);
851
+ beforeUnloadBound = false;
852
+ }
853
+
854
+ function bindContextMenu() {
855
+ if (typeof document === 'undefined' || contextMenuBound) return;
856
+ document.addEventListener('contextmenu', onContextMenu, true);
857
+ contextMenuBound = true;
858
+ }
859
+
860
+ function unbindContextMenu() {
861
+ if (typeof document === 'undefined' || !contextMenuBound) return;
862
+ document.removeEventListener('contextmenu', onContextMenu, true);
863
+ contextMenuBound = false;
864
+ }
865
+
866
+ function bindFocus() {
867
+ if (focusBound) return;
868
+ if (typeof document !== 'undefined') {
869
+ document.addEventListener('visibilitychange', onVisibilityChange);
870
+ }
871
+ if (typeof window !== 'undefined') {
872
+ window.addEventListener('blur', onWindowBlur);
873
+ }
874
+ focusBound = true;
875
+ }
876
+
877
+ function unbindFocus() {
878
+ if (!focusBound) return;
879
+ if (typeof document !== 'undefined') {
880
+ document.removeEventListener('visibilitychange', onVisibilityChange);
881
+ }
882
+ if (typeof window !== 'undefined') {
883
+ window.removeEventListener('blur', onWindowBlur);
884
+ }
885
+ focusBound = false;
886
+ }
887
+
888
+ function sync(active, source) {
889
+ if (!active) {
890
+ releaseKeyboardLock();
891
+ unbindKeydown();
892
+ unbindBeforeUnload();
893
+ unbindContextMenu();
894
+ unbindFocus();
895
+ return;
896
+ }
897
+
898
+ if (
899
+ keyboardLock.enabled &&
900
+ source === 'native' &&
901
+ !keyboardLocked &&
902
+ typeof navigator !== 'undefined' &&
903
+ navigator.keyboard &&
904
+ typeof navigator.keyboard.lock === 'function'
905
+ ) {
906
+ keyboardLocked = true;
907
+ try {
908
+ Promise.resolve(navigator.keyboard.lock(keyboardLock.keys)).catch(() => {
909
+ keyboardLocked = false;
910
+ });
911
+ } catch {
912
+ keyboardLocked = false;
913
+ }
914
+ } else if (source !== 'native') {
915
+ releaseKeyboardLock();
916
+ }
917
+
918
+ if (blockShortcuts.enabled) bindKeydown();
919
+ else unbindKeydown();
920
+
921
+ if (confirmOnLeave && isExitLocked()) bindBeforeUnload();
922
+ else unbindBeforeUnload();
923
+
924
+ if (blockContextMenu) bindContextMenu();
925
+ else unbindContextMenu();
926
+
927
+ if (watchFocus) bindFocus();
928
+ else unbindFocus();
929
+ }
930
+
931
+ function unlock() {
932
+ releaseKeyboardLock();
933
+ unbindBeforeUnload();
934
+ unbindFocus();
935
+ }
936
+
937
+ function destroy() {
938
+ sync(false, 'none');
939
+ }
940
+
941
+ return {
942
+ sync,
943
+ unlock,
944
+ destroy
945
+ };
946
+ }
947
+
948
+ /**
949
+ * Core engine: createFullscreen()
950
+ *
951
+ * Environment-aware. Works in:
952
+ * - Browser (native, with prefixes)
953
+ * - Electron renderer (via window.fsNative bridge)
954
+ * - SSR/Node (import safe; request() rejects gracefully)
955
+ *
956
+ * Fallback: CSS-based fake fullscreen when native is unavailable.
957
+ * Auto-triggers: Opt-in mouse hover and page scroll fullscreen activation.
958
+ */
959
+
960
+
961
+ function isValidElement(el) {
962
+ return (
963
+ typeof el === 'object' &&
964
+ el !== null &&
965
+ el.nodeType === 1 &&
966
+ typeof el.classList === 'object'
967
+ );
968
+ }
969
+
970
+ function normalizeAutoRelock$1(val) {
971
+ if (val === undefined || val === null || val === false) {
972
+ return { enabled: false, delay: 50, maxRetries: 3 };
973
+ }
974
+ if (val === true) {
975
+ return { enabled: true, delay: 50, maxRetries: 3 };
976
+ }
977
+ if (typeof val === 'object') {
978
+ const delayNum = Number(val.delay);
979
+ const retriesNum = Number(val.maxRetries);
980
+ return {
981
+ enabled: val.enabled ?? true,
982
+ delay: Number.isFinite(delayNum) ? Math.max(0, delayNum) : 50,
983
+ maxRetries: Number.isFinite(retriesNum) ? Math.max(1, Math.trunc(retriesNum)) : 3
984
+ };
985
+ }
986
+ throw new TypeError('[fullscreen-engine] invalid autoRelock option: expected boolean or object');
987
+ }
988
+
989
+ function createFullscreen$1(userOptions = {}) {
990
+ const triggers = normalizeTriggers(userOptions.trigger);
991
+ const relockConfig = normalizeAutoRelock$1(userOptions.autoRelock);
992
+
993
+ const fallbackOption = userOptions.fallback ?? 'none';
994
+ if (fallbackOption !== 'css' && fallbackOption !== 'none') {
995
+ throw new TypeError(`[fullscreen-engine] invalid fallback "${String(fallbackOption)}": expected 'css' or 'none'`);
996
+ }
997
+
998
+ if (userOptions.target !== undefined && userOptions.target !== null && !isValidElement(userOptions.target)) {
999
+ throw new TypeError('[fullscreen-engine] target must be a valid DOM Element');
1000
+ }
1001
+
1002
+ const navigationUIOption = userOptions.navigationUI ?? 'hide';
1003
+ if (navigationUIOption !== 'hide' && navigationUIOption !== 'show' && navigationUIOption !== 'auto') {
1004
+ throw new TypeError(
1005
+ `[fullscreen-engine] invalid navigationUI "${String(navigationUIOption)}": expected 'hide', 'show', or 'auto'`
1006
+ );
1007
+ }
1008
+
1009
+ let exitButtons = [];
1010
+ if (userOptions.exitButton !== undefined && userOptions.exitButton !== null) {
1011
+ if (Array.isArray(userOptions.exitButton)) {
1012
+ for (const btn of userOptions.exitButton) {
1013
+ if (!isValidElement(btn)) {
1014
+ throw new TypeError('[fullscreen-engine] exitButton must be a valid DOM Element or Element[]');
1015
+ }
1016
+ }
1017
+ exitButtons = userOptions.exitButton.slice();
1018
+ } else if (isValidElement(userOptions.exitButton)) {
1019
+ exitButtons = [userOptions.exitButton];
1020
+ } else {
1021
+ throw new TypeError('[fullscreen-engine] exitButton must be a valid DOM Element or Element[]');
1022
+ }
1023
+ }
1024
+
1025
+ const freezePageOption = userOptions.freezePage ?? false;
1026
+ if (typeof freezePageOption !== 'boolean') {
1027
+ throw new TypeError('[fullscreen-engine] invalid freezePage option: expected boolean');
1028
+ }
1029
+
1030
+ const gestureUpgradeOption = userOptions.gestureUpgrade ?? false;
1031
+ if (typeof gestureUpgradeOption !== 'boolean') {
1032
+ throw new TypeError('[fullscreen-engine] invalid gestureUpgrade option: expected boolean');
1033
+ }
1034
+
1035
+ const keyboardLockConfig = normalizeKeyboardLock(userOptions.keyboardLock);
1036
+ const blockShortcutsConfig = normalizeBlockShortcuts(userOptions.blockShortcuts);
1037
+
1038
+ const confirmOnLeaveOption = userOptions.confirmOnLeave ?? false;
1039
+ if (typeof confirmOnLeaveOption !== 'boolean') {
1040
+ throw new TypeError('[fullscreen-engine] invalid confirmOnLeave option: expected boolean');
1041
+ }
1042
+
1043
+ const blockContextMenuOption = userOptions.blockContextMenu ?? false;
1044
+ if (typeof blockContextMenuOption !== 'boolean') {
1045
+ throw new TypeError('[fullscreen-engine] invalid blockContextMenu option: expected boolean');
1046
+ }
1047
+
1048
+ const watchFocusOption = userOptions.watchFocus ?? false;
1049
+ if (typeof watchFocusOption !== 'boolean') {
1050
+ throw new TypeError('[fullscreen-engine] invalid watchFocus option: expected boolean');
1051
+ }
1052
+
1053
+ const options = {
1054
+ target: userOptions.target ?? null,
1055
+ fallback: fallbackOption, // 'css' | 'none'
1056
+ fallbackClass: userOptions.fallbackClass ?? 'fs-engine-active',
1057
+ lockBody: userOptions.lockBody ?? true,
1058
+ zIndex: userOptions.zIndex ?? 2147483647,
1059
+ onError: userOptions.onError ?? null,
1060
+ autoDetectElectron: userOptions.autoDetectElectron ?? true,
1061
+ navigationUI: navigationUIOption,
1062
+ exitButton: userOptions.exitButton ?? null,
1063
+ freezePage: freezePageOption,
1064
+ gestureUpgrade: gestureUpgradeOption,
1065
+ keyboardLock: keyboardLockConfig,
1066
+ blockShortcuts: blockShortcutsConfig,
1067
+ confirmOnLeave: confirmOnLeaveOption,
1068
+ blockContextMenu: blockContextMenuOption,
1069
+ watchFocus: watchFocusOption,
1070
+ trigger: triggers.list,
1071
+ hoverTarget: userOptions.hoverTarget ?? null,
1072
+ hoverDelay: userOptions.hoverDelay ?? 0,
1073
+ scrollTarget: userOptions.scrollTarget ?? null,
1074
+ scrollThreshold: userOptions.scrollThreshold ?? 100,
1075
+ autoExit: userOptions.autoExit ?? true,
1076
+ suppressOnManualExit: userOptions.suppressOnManualExit ?? true,
1077
+ autoRelock: relockConfig,
1078
+ preventExit: userOptions.preventExit ?? false
1079
+ };
1080
+
1081
+ const emitter = new Emitter();
1082
+ const env = detectEnvironment();
1083
+
1084
+ function emitError(err) {
1085
+ emitter.emit('error', err);
1086
+ if (typeof options.onError === 'function') options.onError(err);
1087
+ }
1088
+
1089
+ // Resolve target lazily (document may not exist in SSR)
1090
+ function resolveTarget() {
1091
+ if (options.target) return options.target;
1092
+ if (typeof document !== 'undefined') return document.documentElement;
1093
+ return null;
1094
+ }
1095
+
1096
+ function resolveHoverTarget() {
1097
+ if (options.hoverTarget) return options.hoverTarget;
1098
+ return resolveTarget();
1099
+ }
1100
+
1101
+ function resolveScrollTarget() {
1102
+ if (options.scrollTarget) return options.scrollTarget;
1103
+ if (typeof window !== 'undefined') return window;
1104
+ return null;
1105
+ }
1106
+
1107
+ // Electron bridge
1108
+ const electronBridge =
1109
+ options.autoDetectElectron && isElectron() && typeof window !== 'undefined'
1110
+ ? window.fsNative || null
1111
+ : null;
1112
+
1113
+ const hasNative = !!(env && env.supported);
1114
+ const hasElectron = !!(electronBridge && typeof electronBridge.set === 'function');
1115
+ const hasFallback =
1116
+ userOptions.fallback !== undefined
1117
+ ? options.fallback === 'css'
1118
+ : triggers.isAuto || relockConfig.enabled;
1119
+ const effectiveLockBody = triggers.hasScroll && options.autoExit ? false : options.lockBody;
1120
+
1121
+ const fallback = hasFallback
1122
+ ? createFallback({
1123
+ fallbackClass: options.fallbackClass,
1124
+ lockBody: effectiveLockBody,
1125
+ zIndex: options.zIndex,
1126
+ freezePage: options.freezePage
1127
+ })
1128
+ : null;
1129
+
1130
+ let destroyed = false;
1131
+ let electronActive = false;
1132
+ let lastActive = false;
1133
+ let lastSource = 'none';
1134
+ let electronUnsub = null;
1135
+ let escapeBound = false;
1136
+ let gestureUpgradeBound = false;
1137
+ let exitLocked = !!options.preventExit;
1138
+ let manualUnlocking = false;
1139
+ let relockTimer = null;
1140
+ let relockRetries = 0;
1141
+
1142
+ function clearRelockTimer() {
1143
+ if (relockTimer !== null) {
1144
+ clearTimeout(relockTimer);
1145
+ relockTimer = null;
1146
+ }
1147
+ }
1148
+
1149
+ function scheduleRelock() {
1150
+ if (destroyed || !relockConfig.enabled || manualUnlocking) return;
1151
+ if (relockRetries >= relockConfig.maxRetries) {
1152
+ emitError(new Error('[fullscreen-engine] autoRelock failed after maxRetries'));
1153
+ return;
1154
+ }
1155
+ clearRelockTimer();
1156
+ relockTimer = setTimeout(() => {
1157
+ relockTimer = null;
1158
+ if (destroyed || !relockConfig.enabled || manualUnlocking || getState().active) return;
1159
+ relockRetries += 1;
1160
+ requestAuto()
1161
+ .then(() => {
1162
+ if (!destroyed && !getState().active && relockConfig.enabled && !manualUnlocking) {
1163
+ scheduleRelock();
1164
+ }
1165
+ })
1166
+ .catch((err) => {
1167
+ emitError(err);
1168
+ if (!destroyed && relockConfig.enabled && !manualUnlocking) {
1169
+ scheduleRelock();
1170
+ }
1171
+ });
1172
+ }, relockConfig.delay);
1173
+ }
1174
+
1175
+ function onFallbackEscape(e) {
1176
+ if (destroyed || !fallback || !fallback.active) return;
1177
+ if (e && e.key === 'Escape') {
1178
+ if (exitLocked) {
1179
+ if (typeof e.preventDefault === 'function') e.preventDefault();
1180
+ if (typeof e.stopPropagation === 'function') e.stopPropagation();
1181
+ emitter.emit('exitAttempt', { reason: 'escape', state: getState() });
1182
+ emitError(new Error('[fullscreen-engine] Exit blocked: preventExit is active'));
1183
+ return;
1184
+ }
1185
+ exit().catch((err) => emitError(err));
1186
+ }
1187
+ }
1188
+
1189
+ function syncEscapeListener(isFallbackActive) {
1190
+ if (typeof document === 'undefined') return;
1191
+ if (isFallbackActive && !escapeBound) {
1192
+ document.addEventListener('keydown', onFallbackEscape);
1193
+ escapeBound = true;
1194
+ } else if (!isFallbackActive && escapeBound) {
1195
+ document.removeEventListener('keydown', onFallbackEscape);
1196
+ escapeBound = false;
1197
+ }
1198
+ }
1199
+
1200
+ function getState() {
1201
+ let active = false;
1202
+ let source = 'none';
1203
+ let element = null;
1204
+
1205
+ if (hasElectron && electronActive) {
1206
+ active = true;
1207
+ source = 'electron';
1208
+ element = resolveTarget();
1209
+ } else if (hasNative && typeof document !== 'undefined' && env.elementProp) {
1210
+ const fsEl = document[env.elementProp];
1211
+ if (fsEl) {
1212
+ const target = options.target;
1213
+ const matchesTarget =
1214
+ !target ||
1215
+ fsEl === target ||
1216
+ (typeof target.contains === 'function' && target.contains(fsEl));
1217
+ if (matchesTarget) {
1218
+ active = true;
1219
+ source = 'native';
1220
+ element = fsEl;
1221
+ }
1222
+ }
1223
+ }
1224
+
1225
+ if (!active && fallback && fallback.active) {
1226
+ active = true;
1227
+ source = 'fallback';
1228
+ element = resolveTarget();
1229
+ }
1230
+
1231
+ return {
1232
+ active,
1233
+ source,
1234
+ element,
1235
+ supported: hasNative || hasElectron || hasFallback
1236
+ };
1237
+ }
1238
+
1239
+ function notifyChange(force = false) {
1240
+ const state = getState();
1241
+ if (state.active && state.source !== 'fallback' && fallback && fallback.active) {
1242
+ fallback.exit();
1243
+ }
1244
+ const guardsHandlesEscape =
1245
+ blockShortcutsConfig.enabled &&
1246
+ (blockShortcutsConfig.rules || []).some((r) => r.key === 'escape');
1247
+ syncEscapeListener(state.active && state.source === 'fallback' && !guardsHandlesEscape);
1248
+ syncGestureUpgrade(state.active && state.source === 'fallback');
1249
+ guards.sync(state.active, state.source);
1250
+ if (state.active) {
1251
+ relockRetries = 0;
1252
+ clearRelockTimer();
1253
+ }
1254
+ if (!force && state.active === lastActive && state.source === lastSource) return;
1255
+ const wasActive = lastActive;
1256
+ lastActive = state.active;
1257
+ lastSource = state.source;
1258
+ if (wasActive && !state.active) {
1259
+ autoTriggers.notifyManualExit();
1260
+ }
1261
+ emitter.emit('change', state);
1262
+ if (state.active) emitter.emit('enter', state);
1263
+ else {
1264
+ emitter.emit('exit', state);
1265
+ if (wasActive && relockConfig.enabled && !manualUnlocking) {
1266
+ if (options.gestureUpgrade && hasFallback && fallback && !hasElectron) {
1267
+ const target = resolveTarget();
1268
+ if (target) {
1269
+ fallback.enter(target);
1270
+ notifyChange(false);
1271
+ return;
1272
+ }
1273
+ }
1274
+ scheduleRelock();
1275
+ }
1276
+ }
1277
+ }
1278
+
1279
+ // Sync external Electron window state transitions (e.g. F11, Esc, macOS window button)
1280
+ if (hasElectron) {
1281
+ if (typeof electronBridge.onChange === 'function') {
1282
+ electronUnsub = electronBridge.onChange((on) => {
1283
+ if (destroyed) return;
1284
+ const next = !!on;
1285
+ if (electronActive && !next && exitLocked) {
1286
+ emitter.emit('exitAttempt', { reason: 'external', state: getState() });
1287
+ }
1288
+ electronActive = next;
1289
+ notifyChange(false);
1290
+ });
1291
+ }
1292
+ if (typeof electronBridge.get === 'function') {
1293
+ Promise.resolve(electronBridge.get())
1294
+ .then((on) => {
1295
+ if (destroyed) return;
1296
+ const next = !!on;
1297
+ if (next !== electronActive) {
1298
+ electronActive = next;
1299
+ notifyChange(false);
1300
+ }
1301
+ })
1302
+ .catch(() => {});
1303
+ }
1304
+ }
1305
+
1306
+ // ---------- native listener wiring ----------
1307
+ function onNativeChange() {
1308
+ if (destroyed) return;
1309
+ notifyChange();
1310
+ }
1311
+ function onNativeError(e) {
1312
+ if (destroyed) return;
1313
+ const err = (e && (e.error || e)) || new Error('Fullscreen error');
1314
+ emitError(err);
1315
+ }
1316
+
1317
+ let nativeChangeBound = false;
1318
+ function bindNativeListeners() {
1319
+ if (!isBrowser() || !hasNative || nativeChangeBound) return;
1320
+ document.addEventListener(env.changeEvent, onNativeChange);
1321
+ document.addEventListener(env.errorEvent, onNativeError);
1322
+ nativeChangeBound = true;
1323
+ }
1324
+ function unbindNativeListeners() {
1325
+ if (!isBrowser() || !hasNative || !nativeChangeBound) return;
1326
+ document.removeEventListener(env.changeEvent, onNativeChange);
1327
+ document.removeEventListener(env.errorEvent, onNativeError);
1328
+ nativeChangeBound = false;
1329
+ }
1330
+
1331
+ bindNativeListeners();
1332
+
1333
+ // ---------- native request + gestureUpgrade helpers ----------
1334
+ function invokeNativeRequest(target) {
1335
+ return maybePromise(() => {
1336
+ if (env.request === 'requestFullscreen') {
1337
+ try {
1338
+ return target[env.request]({ navigationUI: options.navigationUI });
1339
+ } catch (optErr) {
1340
+ if (optErr instanceof TypeError) {
1341
+ return target[env.request]();
1342
+ }
1343
+ throw optErr;
1344
+ }
1345
+ }
1346
+ return target[env.request]();
1347
+ });
1348
+ }
1349
+
1350
+ function clearGestureUpgrade() {
1351
+ if (typeof document === 'undefined' || !gestureUpgradeBound) return;
1352
+ document.removeEventListener('pointerdown', onGestureUpgrade, true);
1353
+ gestureUpgradeBound = false;
1354
+ }
1355
+
1356
+ function onGestureUpgrade() {
1357
+ gestureUpgradeBound = false;
1358
+ if (destroyed || manualUnlocking || !options.gestureUpgrade || !hasNative || !isBrowser()) return;
1359
+ const st = getState();
1360
+ if (!st.active || st.source !== 'fallback') return;
1361
+ const target = resolveTarget();
1362
+ if (!target) return;
1363
+ invokeNativeRequest(target)
1364
+ .then(() => {
1365
+ if (destroyed) return;
1366
+ if (fallback && fallback.active) {
1367
+ fallback.exit();
1368
+ }
1369
+ notifyChange(false);
1370
+ })
1371
+ .catch((err) => {
1372
+ emitError(err);
1373
+ if (!destroyed && !manualUnlocking && getState().source === 'fallback') {
1374
+ syncGestureUpgrade(true);
1375
+ }
1376
+ });
1377
+ }
1378
+
1379
+ function syncGestureUpgrade(shouldArm) {
1380
+ if (
1381
+ !options.gestureUpgrade ||
1382
+ !hasNative ||
1383
+ hasElectron ||
1384
+ !isBrowser() ||
1385
+ manualUnlocking ||
1386
+ !shouldArm
1387
+ ) {
1388
+ clearGestureUpgrade();
1389
+ return;
1390
+ }
1391
+ if (!gestureUpgradeBound) {
1392
+ document.addEventListener('pointerdown', onGestureUpgrade, { capture: true, once: true });
1393
+ gestureUpgradeBound = true;
1394
+ }
1395
+ }
1396
+
1397
+ // ---------- auto-trigger activation (gesture-safe) ----------
1398
+ async function requestAuto() {
1399
+ if (destroyed) return;
1400
+ if (getState().active) return;
1401
+
1402
+ // 1. Electron native (IPC has no browser user-gesture restriction)
1403
+ if (hasElectron) {
1404
+ try {
1405
+ const res = await Promise.resolve(electronBridge.set(true));
1406
+ if (res === false) {
1407
+ throw new Error('[fullscreen-engine] Electron bridge rejected fullscreen request');
1408
+ }
1409
+ electronActive = true;
1410
+ notifyChange(false);
1411
+ return;
1412
+ } catch (err) {
1413
+ emitError(err);
1414
+ // fall through to CSS fallback
1415
+ }
1416
+ }
1417
+
1418
+ // 2. CSS fallback (avoids browser SecurityError on hover/scroll events)
1419
+ if (hasFallback && fallback) {
1420
+ const target = resolveTarget();
1421
+ if (!target) return;
1422
+ fallback.enter(target);
1423
+ notifyChange(false);
1424
+ }
1425
+ }
1426
+
1427
+ async function exitInternal(fromAutoTrigger = false, reason = 'api') {
1428
+ if (destroyed) {
1429
+ if (!fromAutoTrigger) throw new Error('[fullscreen-engine] instance destroyed');
1430
+ return;
1431
+ }
1432
+ if (exitLocked && !fromAutoTrigger) {
1433
+ emitter.emit('exitAttempt', { reason, state: getState() });
1434
+ const err = new Error('[fullscreen-engine] Exit blocked: preventExit is active');
1435
+ emitError(err);
1436
+ throw err;
1437
+ }
1438
+ if (!getState().active) return;
1439
+ if (!fromAutoTrigger) {
1440
+ autoTriggers.notifyManualExit();
1441
+ }
1442
+
1443
+ if (hasElectron && electronActive) {
1444
+ try {
1445
+ const res = await Promise.resolve(electronBridge.set(false));
1446
+ if (res === true) {
1447
+ throw new Error('[fullscreen-engine] Electron bridge failed to exit fullscreen');
1448
+ }
1449
+ electronActive = false;
1450
+ } catch (err) {
1451
+ emitError(err);
1452
+ }
1453
+ }
1454
+
1455
+ if (
1456
+ hasNative &&
1457
+ isBrowser() &&
1458
+ env.elementProp &&
1459
+ document[env.elementProp] &&
1460
+ typeof document[env.exit] === 'function'
1461
+ ) {
1462
+ try {
1463
+ await maybePromise(() => document[env.exit]());
1464
+ } catch (err) {
1465
+ emitError(err);
1466
+ }
1467
+ }
1468
+
1469
+ if (fallback && fallback.active) {
1470
+ fallback.exit();
1471
+ }
1472
+
1473
+ notifyChange(false);
1474
+ }
1475
+
1476
+ const autoTriggers = createAutoTriggers({
1477
+ triggers,
1478
+ resolveHoverTarget,
1479
+ resolveScrollTarget,
1480
+ hoverDelay: options.hoverDelay,
1481
+ scrollThreshold: options.scrollThreshold,
1482
+ autoExit: options.autoExit,
1483
+ suppressOnManualExit: options.suppressOnManualExit,
1484
+ isActive: () => getState().active,
1485
+ onEnter: () => requestAuto(),
1486
+ onExit: () => exitInternal(true)
1487
+ });
1488
+
1489
+ const guards = createGuards({
1490
+ keyboardLock: keyboardLockConfig,
1491
+ blockShortcuts: blockShortcutsConfig,
1492
+ confirmOnLeave: confirmOnLeaveOption,
1493
+ blockContextMenu: blockContextMenuOption,
1494
+ watchFocus: watchFocusOption,
1495
+ isExitLocked: () => exitLocked,
1496
+ onExitAttempt: (reason) => {
1497
+ emitter.emit('exitAttempt', { reason, state: getState() });
1498
+ },
1499
+ onEscapeExit: () => {
1500
+ if (!destroyed && fallback && fallback.active && !exitLocked) {
1501
+ exit().catch((err) => emitError(err));
1502
+ }
1503
+ },
1504
+ onFocusLost: (reason) => {
1505
+ emitter.emit('focusLost', { reason, state: getState() });
1506
+ }
1507
+ });
1508
+
1509
+ // ---------- public API ----------
1510
+ async function request() {
1511
+ if (destroyed) throw new Error('[fullscreen-engine] instance destroyed');
1512
+ manualUnlocking = false;
1513
+ if (getState().active) return;
1514
+
1515
+ // 1. Electron native (do not fall through to Chromium HTML5 native)
1516
+ if (hasElectron) {
1517
+ try {
1518
+ const res = await Promise.resolve(electronBridge.set(true));
1519
+ if (res === false) {
1520
+ throw new Error('[fullscreen-engine] Electron bridge rejected fullscreen request');
1521
+ }
1522
+ electronActive = true;
1523
+ notifyChange(false);
1524
+ return;
1525
+ } catch (err) {
1526
+ emitError(err);
1527
+ // fall through to CSS fallback
1528
+ }
1529
+ } else if (hasNative) {
1530
+ // 2. Browser native
1531
+ const target = resolveTarget();
1532
+ if (!target) throw new Error('[fullscreen-engine] no target element');
1533
+ try {
1534
+ await invokeNativeRequest(target);
1535
+ // Avoid duplicate emissions if native changeEvent already fired
1536
+ notifyChange(false);
1537
+ return;
1538
+ } catch (err) {
1539
+ emitError(err);
1540
+ // fall through to fallback
1541
+ }
1542
+ }
1543
+
1544
+ // 3. CSS fallback
1545
+ if (hasFallback && fallback) {
1546
+ const target = resolveTarget();
1547
+ if (!target) throw new Error('[fullscreen-engine] no target element for fallback');
1548
+ fallback.enter(target);
1549
+ notifyChange(false);
1550
+ return;
1551
+ }
1552
+
1553
+ throw new Error(
1554
+ '[fullscreen-engine] fullscreen unavailable: no native API, no Electron bridge, fallback disabled'
1555
+ );
1556
+ }
1557
+
1558
+ async function exit() {
1559
+ return exitInternal(false);
1560
+ }
1561
+
1562
+ async function toggle() {
1563
+ if (getState().active) return exit();
1564
+ return request();
1565
+ }
1566
+
1567
+ function unlock() {
1568
+ exitLocked = false;
1569
+ manualUnlocking = true;
1570
+ clearRelockTimer();
1571
+ clearGestureUpgrade();
1572
+ guards.unlock();
1573
+ relockRetries = 0;
1574
+ }
1575
+
1576
+ async function relock() {
1577
+ manualUnlocking = false;
1578
+ return request();
1579
+ }
1580
+
1581
+ function isActive() {
1582
+ return getState().active;
1583
+ }
1584
+
1585
+ function isSupported() {
1586
+ return hasNative || hasElectron || hasFallback;
1587
+ }
1588
+
1589
+ function isFallback() {
1590
+ return getState().source === 'fallback';
1591
+ }
1592
+
1593
+ function on(event, cb) {
1594
+ return emitter.on(event, cb);
1595
+ }
1596
+ function once(event, cb) {
1597
+ return emitter.once(event, cb);
1598
+ }
1599
+ function off(event, cb) {
1600
+ return emitter.off(event, cb);
1601
+ }
1602
+
1603
+ function onExitButtonClick() {
1604
+ if (destroyed) return;
1605
+ exitInternal(false, 'button').catch(() => {});
1606
+ }
1607
+
1608
+ for (const btn of exitButtons) {
1609
+ if (typeof btn.addEventListener === 'function') {
1610
+ btn.addEventListener('click', onExitButtonClick);
1611
+ }
1612
+ }
1613
+
1614
+ function destroy() {
1615
+ if (destroyed) return;
1616
+ destroyed = true;
1617
+ clearRelockTimer();
1618
+ clearGestureUpgrade();
1619
+ guards.destroy();
1620
+ syncEscapeListener(false);
1621
+ unbindNativeListeners();
1622
+ for (const btn of exitButtons) {
1623
+ if (typeof btn.removeEventListener === 'function') {
1624
+ btn.removeEventListener('click', onExitButtonClick);
1625
+ }
1626
+ }
1627
+ if (typeof electronUnsub === 'function') {
1628
+ electronUnsub();
1629
+ electronUnsub = null;
1630
+ }
1631
+ autoTriggers.destroy();
1632
+ if (fallback) fallback.destroy();
1633
+ emitter.clear();
1634
+ }
1635
+
1636
+ // Expose current state snapshots
1637
+ const state = () => getState();
1638
+
1639
+ return {
1640
+ request,
1641
+ exit,
1642
+ toggle,
1643
+ unlock,
1644
+ relock,
1645
+ isActive,
1646
+ isSupported,
1647
+ isFallback,
1648
+ getState: state,
1649
+ on,
1650
+ once,
1651
+ off,
1652
+ destroy,
1653
+ // convenience for debugging
1654
+ _env: env,
1655
+ _options: options
1656
+ };
1657
+ }
1658
+
1659
+ /**
1660
+ * Electron renderer-side adapter.
1661
+ *
1662
+ * Provide this on the renderer via contextBridge (window.fsNative).
1663
+ */
1664
+
1665
+
1666
+ function normalizeAutoRelock(val) {
1667
+ if (val === undefined || val === null || val === false) {
1668
+ return { enabled: false, delay: 50, maxRetries: 3 };
1669
+ }
1670
+ if (val === true) {
1671
+ return { enabled: true, delay: 50, maxRetries: 3 };
1672
+ }
1673
+ if (typeof val === 'object') {
1674
+ const delayNum = Number(val.delay);
1675
+ const retriesNum = Number(val.maxRetries);
1676
+ return {
1677
+ enabled: val.enabled ?? true,
1678
+ delay: Number.isFinite(delayNum) ? Math.max(0, delayNum) : 50,
1679
+ maxRetries: Number.isFinite(retriesNum) ? Math.max(1, Math.trunc(retriesNum)) : 3
1680
+ };
1681
+ }
1682
+ throw new TypeError('[fullscreen-engine/electron] invalid autoRelock option: expected boolean or object');
1683
+ }
1684
+
1685
+ function createElectronFullscreen(bridge, opts = {}) {
1686
+ if (!bridge || typeof bridge.set !== 'function') {
1687
+ throw new Error('[fullscreen-engine/electron] bridge with .set() required');
1688
+ }
1689
+
1690
+ const relockConfig = normalizeAutoRelock(opts.autoRelock);
1691
+ const onError = typeof opts.onError === 'function' ? opts.onError : null;
1692
+ const emitter = new Emitter();
1693
+ let active = false;
1694
+ let destroyed = false;
1695
+ let unsubscribe = null;
1696
+ let exitLocked = !!opts.preventExit;
1697
+ let manualUnlocking = false;
1698
+ let relockTimer = null;
1699
+ let relockRetries = 0;
1700
+
1701
+ function emitError(err) {
1702
+ emitter.emit('error', err);
1703
+ if (onError) onError(err);
1704
+ }
1705
+
1706
+ function clearRelockTimer() {
1707
+ if (relockTimer !== null) {
1708
+ clearTimeout(relockTimer);
1709
+ relockTimer = null;
1710
+ }
1711
+ }
1712
+
1713
+ function getState() {
1714
+ return {
1715
+ active,
1716
+ source: active ? 'electron' : 'none',
1717
+ element: null,
1718
+ supported: true
1719
+ };
1720
+ }
1721
+
1722
+ function scheduleRelock() {
1723
+ if (destroyed || !relockConfig.enabled || manualUnlocking) return;
1724
+ if (relockRetries >= relockConfig.maxRetries) {
1725
+ emitError(new Error('[fullscreen-engine/electron] autoRelock failed after maxRetries'));
1726
+ return;
1727
+ }
1728
+ clearRelockTimer();
1729
+ relockTimer = setTimeout(() => {
1730
+ relockTimer = null;
1731
+ if (destroyed || !relockConfig.enabled || manualUnlocking || active) return;
1732
+ relockRetries += 1;
1733
+ request()
1734
+ .catch((err) => {
1735
+ emitError(err);
1736
+ if (!destroyed && relockConfig.enabled && !manualUnlocking && !active) {
1737
+ scheduleRelock();
1738
+ }
1739
+ });
1740
+ }, relockConfig.delay);
1741
+ }
1742
+
1743
+ function updateActive(next) {
1744
+ const boolNext = !!next;
1745
+ if (boolNext) {
1746
+ relockRetries = 0;
1747
+ clearRelockTimer();
1748
+ }
1749
+ if (boolNext === active) return;
1750
+ const wasActive = active;
1751
+ active = boolNext;
1752
+ const state = getState();
1753
+ emitter.emit('change', state);
1754
+ if (active) emitter.emit('enter', state);
1755
+ else {
1756
+ emitter.emit('exit', state);
1757
+ if (wasActive && relockConfig.enabled && !manualUnlocking) {
1758
+ scheduleRelock();
1759
+ }
1760
+ }
1761
+ }
1762
+
1763
+ if (typeof bridge.onChange === 'function') {
1764
+ unsubscribe = bridge.onChange((on) => {
1765
+ if (!destroyed) updateActive(on);
1766
+ });
1767
+ }
1768
+
1769
+ if (typeof bridge.get === 'function') {
1770
+ Promise.resolve(bridge.get())
1771
+ .then((on) => {
1772
+ if (!destroyed) updateActive(on);
1773
+ })
1774
+ .catch(() => {});
1775
+ }
1776
+
1777
+ async function request() {
1778
+ if (destroyed) throw new Error('[fullscreen-engine/electron] destroyed');
1779
+ manualUnlocking = false;
1780
+ const res = await bridge.set(true);
1781
+ if (res === false) {
1782
+ throw new Error('[fullscreen-engine/electron] bridge.set(true) returned false');
1783
+ }
1784
+ updateActive(true);
1785
+ }
1786
+
1787
+ async function exit() {
1788
+ if (destroyed) throw new Error('[fullscreen-engine/electron] destroyed');
1789
+ if (exitLocked) {
1790
+ emitter.emit('exitAttempt', { reason: 'api', state: getState() });
1791
+ const err = new Error('[fullscreen-engine/electron] Exit blocked: preventExit is active');
1792
+ emitError(err);
1793
+ throw err;
1794
+ }
1795
+ const res = await bridge.set(false);
1796
+ if (res === true) {
1797
+ throw new Error('[fullscreen-engine/electron] bridge.set(false) failed to exit');
1798
+ }
1799
+ updateActive(false);
1800
+ }
1801
+
1802
+ function unlock() {
1803
+ exitLocked = false;
1804
+ manualUnlocking = true;
1805
+ clearRelockTimer();
1806
+ relockRetries = 0;
1807
+ }
1808
+
1809
+ async function relock() {
1810
+ manualUnlocking = false;
1811
+ return request();
1812
+ }
1813
+
1814
+ return {
1815
+ request,
1816
+ exit,
1817
+ async toggle() {
1818
+ return active ? exit() : request();
1819
+ },
1820
+ unlock,
1821
+ relock,
1822
+ isActive() { return active; },
1823
+ isSupported() { return true; },
1824
+ getState,
1825
+ on(event, cb) { return emitter.on(event, cb); },
1826
+ once(event, cb) { return emitter.once(event, cb); },
1827
+ off(event, cb) { return emitter.off(event, cb); },
1828
+ destroy() {
1829
+ if (destroyed) return;
1830
+ destroyed = true;
1831
+ clearRelockTimer();
1832
+ if (typeof unsubscribe === 'function') unsubscribe();
1833
+ unsubscribe = null;
1834
+ active = false;
1835
+ emitter.clear();
1836
+ }
1837
+ };
1838
+ }
1839
+
1840
+ /**
1841
+ * True backend fullscreen control from Node.js.
1842
+ *
1843
+ * Uses Chrome DevTools Protocol (CDP) via Puppeteer to control the
1844
+ * browser window's fullscreen state. This works from a Node.js process.
1845
+ */
1846
+
1847
+ function createPuppeteerFullscreen(page, opts = {}) {
1848
+ if (!page || typeof page.createCDPSession !== 'function') {
1849
+ throw new Error('[fullscreen-engine/puppeteer] page with .createCDPSession() required');
1850
+ }
1851
+
1852
+ let client = null;
1853
+ let windowId = null;
1854
+ let initPromise = null;
1855
+ let active = false;
1856
+ let destroyed = false;
1857
+ let exitLocked = !!opts.preventExit;
1858
+
1859
+ async function ensure() {
1860
+ if (destroyed) throw new Error('[fullscreen-engine/puppeteer] destroyed');
1861
+ if (client && windowId !== null) return;
1862
+ if (!initPromise) {
1863
+ initPromise = (async () => {
1864
+ let session = null;
1865
+ try {
1866
+ session = await page.createCDPSession();
1867
+ const res = await session.send('Browser.getWindowForTarget');
1868
+ if (destroyed) {
1869
+ try { await session.detach(); } catch {}
1870
+ throw new Error('[fullscreen-engine/puppeteer] destroyed');
1871
+ }
1872
+ client = session;
1873
+ windowId = res.windowId;
1874
+ } catch (err) {
1875
+ if (session) {
1876
+ try { await session.detach(); } catch {}
1877
+ }
1878
+ client = null;
1879
+ windowId = null;
1880
+ throw err;
1881
+ } finally {
1882
+ initPromise = null;
1883
+ }
1884
+ })();
1885
+ }
1886
+ return initPromise;
1887
+ }
1888
+
1889
+ async function setState(state) {
1890
+ if (destroyed) throw new Error('[fullscreen-engine/puppeteer] destroyed');
1891
+ await ensure();
1892
+ await client.send('Browser.setWindowBounds', {
1893
+ windowId,
1894
+ bounds: { windowState: state } // 'fullscreen' | 'normal' | 'minimized' | 'maximized'
1895
+ });
1896
+ active = state === 'fullscreen';
1897
+ return active;
1898
+ }
1899
+
1900
+ return {
1901
+ async request() {
1902
+ if (destroyed) throw new Error('[fullscreen-engine/puppeteer] destroyed');
1903
+ if (active) return true;
1904
+ return setState('fullscreen');
1905
+ },
1906
+ async exit() {
1907
+ if (destroyed) throw new Error('[fullscreen-engine/puppeteer] destroyed');
1908
+ if (exitLocked) {
1909
+ throw new Error('[fullscreen-engine/puppeteer] Exit blocked: preventExit is active');
1910
+ }
1911
+ if (!active) {
1912
+ const current = await this.getWindowState();
1913
+ if (current !== 'fullscreen') return false;
1914
+ }
1915
+ return setState(opts.restoreState || 'normal');
1916
+ },
1917
+ async toggle() {
1918
+ if (destroyed) throw new Error('[fullscreen-engine/puppeteer] destroyed');
1919
+ const current = await this.getWindowState();
1920
+ return current === 'fullscreen' ? this.exit() : this.request();
1921
+ },
1922
+ unlock() {
1923
+ exitLocked = false;
1924
+ },
1925
+ async relock() {
1926
+ if (destroyed) throw new Error('[fullscreen-engine/puppeteer] destroyed');
1927
+ const current = await this.getWindowState();
1928
+ if (current === 'fullscreen') return true;
1929
+ return setState('fullscreen');
1930
+ },
1931
+ isActive() {
1932
+ return active;
1933
+ },
1934
+ isSupported() {
1935
+ return true;
1936
+ },
1937
+ async getWindowState() {
1938
+ if (destroyed) throw new Error('[fullscreen-engine/puppeteer] destroyed');
1939
+ await ensure();
1940
+ const res = await client.send('Browser.getWindowBounds', { windowId });
1941
+ const state = res.bounds.windowState;
1942
+ active = state === 'fullscreen';
1943
+ return state;
1944
+ },
1945
+ async destroy() {
1946
+ if (destroyed) return;
1947
+ destroyed = true;
1948
+ if (initPromise) {
1949
+ try { await initPromise; } catch {}
1950
+ }
1951
+ try { if (client) await client.detach(); } catch {}
1952
+ client = null;
1953
+ windowId = null;
1954
+ initPromise = null;
1955
+ active = false;
1956
+ }
1957
+ };
1958
+ }
1959
+
1960
+ /**
1961
+ * SSR / Node.js safe stub.
1962
+ *
1963
+ * Importing the main entry already works in Node (all guards are in place).
1964
+ * But if you explicitly need a no-op controller (e.g. for template
1965
+ * environments that can't tree-shake), use this:
1966
+ *
1967
+ * import { createFullscreen } from 'fullscreen-engine/adapters/ssr';
1968
+ */
1969
+
1970
+ function createFullscreen() {
1971
+ return {
1972
+ async request() { throw new Error('[fullscreen-engine/ssr] fullscreen unavailable in SSR'); },
1973
+ async exit() {},
1974
+ async toggle() { return this.request(); },
1975
+ unlock() {},
1976
+ isActive() { return false; },
1977
+ isSupported() { return false; },
1978
+ isFallback() { return false; },
1979
+ getState() { return { active: false, source: 'none', element: null, supported: false }; },
1980
+ on() { return () => {}; },
1981
+ once() { return () => {}; },
1982
+ off() {},
1983
+ destroy() {}
1984
+ };
1985
+ }
1986
+
1987
+ /**
1988
+ * Global configuration engine for fullscreen-engine.
1989
+ *
1990
+ * Pure isomorphic module (no Node.js built-in imports) safe for Browser,
1991
+ * Electron renderer, Puppeteer/Node, and SSR environments.
1992
+ */
1993
+
1994
+
1995
+ function isPlainObject$1(val) {
1996
+ return typeof val === 'object' && val !== null && !Array.isArray(val);
1997
+ }
1998
+
1999
+ function mergeAutoRelock(baseVal, nextVal) {
2000
+ if (nextVal === undefined) return baseVal;
2001
+ if (isPlainObject$1(baseVal) && isPlainObject$1(nextVal)) {
2002
+ return { ...baseVal, ...nextVal };
2003
+ }
2004
+ return nextVal;
2005
+ }
2006
+
2007
+ function mergeSection(base, ext) {
2008
+ if (!ext) return { ...base };
2009
+ const merged = { ...base, ...ext };
2010
+ if ('autoRelock' in base || 'autoRelock' in ext) {
2011
+ merged.autoRelock = mergeAutoRelock(base.autoRelock, ext.autoRelock);
2012
+ }
2013
+ return merged;
2014
+ }
2015
+
2016
+ function validateConfigShape(cfg, label = 'config') {
2017
+ if (!isPlainObject$1(cfg)) {
2018
+ throw new TypeError(`[fullscreen-engine/config] ${label} must be a plain object`);
2019
+ }
2020
+ if (cfg.mode !== undefined && (typeof cfg.mode !== 'string' || !(cfg.mode in PRESETS))) {
2021
+ throw new TypeError(`[fullscreen-engine/config] unknown mode/preset: ${String(cfg.mode)}`);
2022
+ }
2023
+ if (cfg.core !== undefined && !isPlainObject$1(cfg.core)) {
2024
+ throw new TypeError(`[fullscreen-engine/config] ${label}.core must be a plain object`);
2025
+ }
2026
+ if (cfg.adapters !== undefined) {
2027
+ if (!isPlainObject$1(cfg.adapters)) {
2028
+ throw new TypeError(`[fullscreen-engine/config] ${label}.adapters must be a plain object`);
2029
+ }
2030
+ for (const key of ['electron', 'puppeteer', 'ssr']) {
2031
+ if (cfg.adapters[key] !== undefined && !isPlainObject$1(cfg.adapters[key])) {
2032
+ throw new TypeError(
2033
+ `[fullscreen-engine/config] adapter "${key}" options must be a plain object`
2034
+ );
2035
+ }
2036
+ }
2037
+ }
2038
+ }
2039
+
2040
+ const PRESETS = Object.freeze({
2041
+ default: Object.freeze({
2042
+ core: Object.freeze({}),
2043
+ adapters: Object.freeze({
2044
+ electron: Object.freeze({}),
2045
+ puppeteer: Object.freeze({}),
2046
+ ssr: Object.freeze({ enabled: true })
2047
+ })
2048
+ }),
2049
+ kiosk: Object.freeze({
2050
+ core: Object.freeze({
2051
+ fallback: 'css',
2052
+ lockBody: true,
2053
+ autoRelock: true,
2054
+ preventExit: true,
2055
+ suppressOnManualExit: true
2056
+ }),
2057
+ adapters: Object.freeze({
2058
+ electron: Object.freeze({ autoRelock: true, preventExit: true }),
2059
+ puppeteer: Object.freeze({ preventExit: true }),
2060
+ ssr: Object.freeze({ enabled: true })
2061
+ })
2062
+ }),
2063
+ presentation: Object.freeze({
2064
+ core: Object.freeze({
2065
+ fallback: 'css',
2066
+ lockBody: true,
2067
+ trigger: 'manual',
2068
+ autoExit: false,
2069
+ suppressOnManualExit: true,
2070
+ autoRelock: false,
2071
+ preventExit: false
2072
+ }),
2073
+ adapters: Object.freeze({
2074
+ electron: Object.freeze({ autoRelock: false, preventExit: false }),
2075
+ puppeteer: Object.freeze({ restoreState: 'normal', preventExit: false }),
2076
+ ssr: Object.freeze({ enabled: true })
2077
+ })
2078
+ }),
2079
+ strict: Object.freeze({
2080
+ core: Object.freeze({
2081
+ fallback: 'css',
2082
+ lockBody: true,
2083
+ freezePage: true,
2084
+ autoRelock: Object.freeze({ enabled: true, delay: 50, maxRetries: 5 }),
2085
+ gestureUpgrade: true,
2086
+ keyboardLock: true,
2087
+ blockShortcuts: true,
2088
+ confirmOnLeave: true,
2089
+ blockContextMenu: true,
2090
+ watchFocus: true,
2091
+ preventExit: true,
2092
+ suppressOnManualExit: true
2093
+ }),
2094
+ adapters: Object.freeze({
2095
+ electron: Object.freeze({
2096
+ autoRelock: Object.freeze({ enabled: true, delay: 50, maxRetries: 5 }),
2097
+ preventExit: true
2098
+ }),
2099
+ puppeteer: Object.freeze({ preventExit: true }),
2100
+ ssr: Object.freeze({ enabled: false })
2101
+ })
2102
+ })
2103
+ });
2104
+
2105
+ function resolveConfig(config = {}, overrides = {}) {
2106
+ validateConfigShape(config, 'config');
2107
+ validateConfigShape(overrides, 'overrides');
2108
+
2109
+ const mode = overrides.mode ?? config.mode ?? 'default';
2110
+ const preset = PRESETS[mode];
2111
+
2112
+ const cfgAdapters = config.adapters || {};
2113
+ const ovAdapters = overrides.adapters || {};
2114
+
2115
+ return {
2116
+ mode,
2117
+ core: mergeSection(mergeSection(preset.core, config.core), overrides.core),
2118
+ adapters: {
2119
+ electron: mergeSection(
2120
+ mergeSection(preset.adapters.electron, cfgAdapters.electron),
2121
+ ovAdapters.electron
2122
+ ),
2123
+ puppeteer: mergeSection(
2124
+ mergeSection(preset.adapters.puppeteer, cfgAdapters.puppeteer),
2125
+ ovAdapters.puppeteer
2126
+ ),
2127
+ ssr: mergeSection(
2128
+ mergeSection(preset.adapters.ssr, cfgAdapters.ssr),
2129
+ ovAdapters.ssr
2130
+ )
2131
+ }
2132
+ };
2133
+ }
2134
+
2135
+ function initFullscreen(config = {}, context = {}) {
2136
+ if (!isPlainObject$1(context)) {
2137
+ throw new TypeError('[fullscreen-engine/config] context must be a plain object');
2138
+ }
2139
+
2140
+ const resolved = resolveConfig(config, context.overrides || {});
2141
+ if (context.target !== undefined) {
2142
+ resolved.core.target = context.target;
2143
+ }
2144
+
2145
+ if (context.bridge !== undefined || context.adapter === 'electron') {
2146
+ const bridge =
2147
+ context.bridge ?? (typeof window !== 'undefined' ? window.fsNative : null);
2148
+ return createElectronFullscreen(bridge, resolved.adapters.electron);
2149
+ }
2150
+
2151
+ if (context.page !== undefined || context.adapter === 'puppeteer') {
2152
+ return createPuppeteerFullscreen(context.page, resolved.adapters.puppeteer);
2153
+ }
2154
+
2155
+ if (context.adapter === 'ssr' || (isNode() && !isBrowser() && !isElectron())) {
2156
+ if (resolved.adapters.ssr.enabled === false) {
2157
+ throw new Error('[fullscreen-engine/config] SSR adapter is disabled by config');
2158
+ }
2159
+ return createFullscreen();
2160
+ }
2161
+
2162
+ return createFullscreen$1(resolved.core);
2163
+ }
2164
+
2165
+ /**
2166
+ * Node.js / Electron main-process global config auto-loader.
2167
+ *
2168
+ * Discovers and loads fullscreen.config.{js,mjs,cjs,json} from a project
2169
+ * directory without requiring engine file edits.
2170
+ */
2171
+
2172
+
2173
+ const CONFIG_FILES = Object.freeze([
2174
+ 'fullscreen.config.js',
2175
+ 'fullscreen.config.mjs',
2176
+ 'fullscreen.config.cjs',
2177
+ 'fullscreen.config.json'
2178
+ ]);
2179
+
2180
+ const CONFIG_EXTENSIONS = new Set(['.js', '.mjs', '.cjs', '.json']);
2181
+
2182
+ function isPlainObject(val) {
2183
+ return typeof val === 'object' && val !== null && !Array.isArray(val);
2184
+ }
2185
+
2186
+ function findConfigFile(cwd = process.cwd()) {
2187
+ const baseDir = resolve(cwd);
2188
+ for (const filename of CONFIG_FILES) {
2189
+ const candidate = resolve(baseDir, filename);
2190
+ if (existsSync(candidate) && statSync(candidate).isFile()) {
2191
+ return candidate;
2192
+ }
2193
+ }
2194
+ return null;
2195
+ }
2196
+
2197
+ async function readRawConfigFile(filePath) {
2198
+ const ext = extname(filePath).toLowerCase();
2199
+ try {
2200
+ if (ext === '.json') {
2201
+ const text = readFileSync(filePath, 'utf8');
2202
+ return JSON.parse(text);
2203
+ }
2204
+ if (ext === '.cjs') {
2205
+ const require = createRequire(import.meta.url);
2206
+ const loaded = require(filePath);
2207
+ return loaded && loaded.__esModule ? loaded.default : loaded;
2208
+ }
2209
+ const mod = await import(pathToFileURL(filePath).href);
2210
+ return mod?.default ?? mod;
2211
+ } catch (err) {
2212
+ throw new Error(
2213
+ `[fullscreen-engine/config] failed to load ${filePath}: ${err?.message || String(err)}`,
2214
+ { cause: err }
2215
+ );
2216
+ }
2217
+ }
2218
+
2219
+ async function loadConfig(cwdOrPath = process.cwd(), options = {}) {
2220
+ let target = cwdOrPath;
2221
+ let opts = options;
2222
+
2223
+ if (isPlainObject(cwdOrPath)) {
2224
+ opts = cwdOrPath;
2225
+ target = process.cwd();
2226
+ }
2227
+ if (!isPlainObject(opts)) {
2228
+ throw new TypeError('[fullscreen-engine/config] loadConfig options must be a plain object');
2229
+ }
2230
+
2231
+ const resolvedTarget = resolve(target);
2232
+ const ext = extname(resolvedTarget).toLowerCase();
2233
+ let filePath = null;
2234
+
2235
+ if (CONFIG_EXTENSIONS.has(ext)) {
2236
+ if (!existsSync(resolvedTarget) || !statSync(resolvedTarget).isFile()) {
2237
+ throw new Error(`[fullscreen-engine/config] config file not found: ${resolvedTarget}`);
2238
+ }
2239
+ filePath = resolvedTarget;
2240
+ } else {
2241
+ filePath = findConfigFile(resolvedTarget);
2242
+ }
2243
+
2244
+ if (!filePath) {
2245
+ if (opts.required) {
2246
+ throw new Error(
2247
+ `[fullscreen-engine/config] no fullscreen.config.{js,mjs,cjs,json} found in ${resolvedTarget}`
2248
+ );
2249
+ }
2250
+ return resolveConfig({}, opts.overrides || {});
2251
+ }
2252
+
2253
+ const rawConfig = await readRawConfigFile(filePath);
2254
+ return resolveConfig(rawConfig, opts.overrides || {});
2255
+ }
2256
+
2257
+ async function loadAndInit(cwdOrPath = process.cwd(), context = {}) {
2258
+ let target = cwdOrPath;
2259
+ let ctx = context;
2260
+
2261
+ if (isPlainObject(cwdOrPath)) {
2262
+ ctx = cwdOrPath;
2263
+ target = process.cwd();
2264
+ }
2265
+ if (!isPlainObject(ctx)) {
2266
+ throw new TypeError('[fullscreen-engine/config] context must be a plain object');
2267
+ }
2268
+ const config = await loadConfig(target, {
2269
+ required: ctx.required ?? false,
2270
+ overrides: ctx.overrides || {}
2271
+ });
2272
+ return initFullscreen(config, ctx);
2273
+ }
2274
+
2275
+ export { CONFIG_FILES, findConfigFile, loadAndInit, loadConfig };
2276
+ //# sourceMappingURL=config.esm.js.map