@stagepass/loader 1.2.0 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/loader.js CHANGED
@@ -1,9 +1,332 @@
1
1
  var Stagepass = (() => {
2
+ // src/domain.ts
3
+ function isValidDomain(d) {
4
+ if (typeof d !== "string" || !d) return false;
5
+ if (d === "debug" || d === "localhost") return true;
6
+ if (d.startsWith("localhost:")) {
7
+ const port = d.slice("localhost:".length);
8
+ return /^[0-9]{1,5}$/.test(port) && Number(port) <= 65535;
9
+ }
10
+ return /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*\.sp$/i.test(
11
+ d
12
+ );
13
+ }
14
+ function cleanDomain(d) {
15
+ if (!d) return null;
16
+ return d.replace(/^https?:\/\//i, "").replace(/\/$/, "");
17
+ }
18
+
19
+ // src/session.ts
20
+ var SESSION_KEY = "stagepass_domain";
21
+ var DEFAULT_SESSION_HOURS = 12;
22
+ function parseSession(raw, now = Date.now()) {
23
+ if (!raw) return null;
24
+ if (!raw.startsWith("{")) {
25
+ return null;
26
+ }
27
+ try {
28
+ const parsed = JSON.parse(raw);
29
+ if (typeof parsed.domain !== "string" || typeof parsed.expires !== "number" || !Number.isFinite(parsed.expires)) {
30
+ return null;
31
+ }
32
+ if (!isValidDomain(parsed.domain)) return null;
33
+ if (parsed.expires <= now) return null;
34
+ return { domain: parsed.domain, expires: parsed.expires };
35
+ } catch {
36
+ return null;
37
+ }
38
+ }
39
+ function createSession(domain, hours = DEFAULT_SESSION_HOURS, now = Date.now()) {
40
+ const safeHours = Number.isFinite(hours) && hours > 0 ? hours : DEFAULT_SESSION_HOURS;
41
+ return {
42
+ domain,
43
+ expires: now + safeHours * 60 * 60 * 1e3
44
+ };
45
+ }
46
+ function serializeSession(record) {
47
+ return JSON.stringify(record);
48
+ }
49
+ function parseSessionHours(value) {
50
+ if (value == null || value === "") return DEFAULT_SESSION_HOURS;
51
+ const n = Number(value);
52
+ if (!Number.isFinite(n) || n <= 0) return DEFAULT_SESSION_HOURS;
53
+ return n;
54
+ }
55
+
56
+ // src/url.ts
57
+ function appendQueryParam(url, key, value) {
58
+ if (!url || typeof url !== "string") return url;
59
+ const encoded = encodeURIComponent(value);
60
+ const hashIdx = url.indexOf("#");
61
+ const hash = hashIdx >= 0 ? url.slice(hashIdx) : "";
62
+ const base = hashIdx >= 0 ? url.slice(0, hashIdx) : url;
63
+ const sep = base.includes("?") ? "&" : "?";
64
+ return `${base}${sep}${encodeURIComponent(key)}=${encoded}${hash}`;
65
+ }
66
+ function buildLocalAssetUrl(domain, relativePath, cacheBust) {
67
+ const clean = relativePath.startsWith("/") ? relativePath.substring(1) : relativePath;
68
+ return `https://${domain}/${clean}?_cb=${encodeURIComponent(String(cacheBust))}`;
69
+ }
70
+
71
+ // src/lna.ts
72
+ async function queryLoopbackPermission() {
73
+ const perms = typeof navigator !== "undefined" ? navigator.permissions : void 0;
74
+ if (!perms || typeof perms.query !== "function") {
75
+ return "unknown";
76
+ }
77
+ const names = ["loopback-network", "local-network-access"];
78
+ for (const name of names) {
79
+ try {
80
+ const status = await perms.query({ name });
81
+ const state = status && status.state;
82
+ if (state === "granted" || state === "prompt" || state === "denied") {
83
+ return state;
84
+ }
85
+ } catch {
86
+ }
87
+ }
88
+ return "unknown";
89
+ }
90
+ function lnaHintMessage(state) {
91
+ if (state === "prompt") {
92
+ return "Local network access is required. Allow local/loopback network access when Chrome prompts, then reload.";
93
+ }
94
+ if (state === "denied") {
95
+ return "Local network access is blocked. Enable loopback/local network access for this site in Chrome settings, then reload.";
96
+ }
97
+ return null;
98
+ }
99
+
100
+ // src/script-attrs.ts
101
+ function applyScriptLoadOrder(script, source) {
102
+ const hadAsync = source.hasAttribute("async");
103
+ const hadDefer = source.hasAttribute("defer");
104
+ if (hadAsync) {
105
+ script.async = true;
106
+ } else {
107
+ script.async = false;
108
+ if (!hadDefer) {
109
+ script.defer = true;
110
+ }
111
+ }
112
+ }
113
+
114
+ // src/env.ts
115
+ function parseStagingHosts(value) {
116
+ if (!value || typeof value !== "string") return [];
117
+ return value.split(",").map((h) => h.trim().toLowerCase()).filter(Boolean);
118
+ }
119
+ function detectRuntimeEnv(hostname, swapDomain, stagingHosts = []) {
120
+ if (swapDomain && swapDomain.endsWith(".sp")) return "local";
121
+ const host = (hostname || "").toLowerCase();
122
+ if (host.endsWith(".webflow.io")) return "staging";
123
+ if (stagingHosts.some((h) => h === host)) return "staging";
124
+ return "production";
125
+ }
126
+
127
+ // src/alias.ts
128
+ function isValidJsIdentifier(name) {
129
+ if (!name || typeof name !== "string") return false;
130
+ return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name);
131
+ }
132
+ function isGlobalFree(target, name) {
133
+ try {
134
+ return typeof target[name] === "undefined";
135
+ } catch (_) {
136
+ return false;
137
+ }
138
+ }
139
+
140
+ // src/client.ts
141
+ function getBrowserInfo(ua) {
142
+ let family = "unknown";
143
+ let major = null;
144
+ let m = null;
145
+ if (/Edg\/(\d+)/.test(ua)) {
146
+ family = "edge";
147
+ m = ua.match(/Edg\/(\d+)/);
148
+ } else if (/OPR\/(\d+)/.test(ua)) {
149
+ family = "opera";
150
+ m = ua.match(/OPR\/(\d+)/);
151
+ } else if (/Firefox\/(\d+)/.test(ua)) {
152
+ family = "firefox";
153
+ m = ua.match(/Firefox\/(\d+)/);
154
+ } else if (/Chrome\/(\d+)/.test(ua)) {
155
+ family = "chrome";
156
+ m = ua.match(/Chrome\/(\d+)/);
157
+ } else if (/Version\/(\d+).+Safari\//.test(ua)) {
158
+ family = "safari";
159
+ m = ua.match(/Version\/(\d+)/);
160
+ }
161
+ if (m && m[1]) major = Number(m[1]);
162
+ return { family, major: Number.isFinite(major) ? major : null, userAgent: ua };
163
+ }
164
+ function getOsInfo(ua) {
165
+ if (/Android/i.test(ua)) return { family: "android" };
166
+ if (/iPhone|iPad|iPod/i.test(ua)) return { family: "ios" };
167
+ if (/Mac OS X|Macintosh/i.test(ua)) return { family: "macos" };
168
+ if (/Windows NT/i.test(ua)) return { family: "windows" };
169
+ if (/Linux/i.test(ua)) return { family: "linux" };
170
+ return { family: "unknown" };
171
+ }
172
+ function getDeviceInfo(ua) {
173
+ const touch = "ontouchstart" in window || (navigator.maxTouchPoints || 0) > 0;
174
+ let type = "desktop";
175
+ if (/iPad|Tablet/i.test(ua)) type = "tablet";
176
+ else if (/Mobi|Android.+Mobile|iPhone/i.test(ua)) type = "mobile";
177
+ else if (/Android/i.test(ua) && touch) type = "tablet";
178
+ return { type, touch };
179
+ }
180
+ function getThemeInfo() {
181
+ let preferred = "no-preference";
182
+ let current = "unknown";
183
+ try {
184
+ if (window.matchMedia) {
185
+ if (window.matchMedia("(prefers-color-scheme: dark)").matches) {
186
+ preferred = "dark";
187
+ current = "dark";
188
+ } else if (window.matchMedia("(prefers-color-scheme: light)").matches) {
189
+ preferred = "light";
190
+ current = "light";
191
+ }
192
+ }
193
+ } catch (_) {
194
+ }
195
+ return { preferred, current };
196
+ }
197
+ function hasStorage(type) {
198
+ try {
199
+ const storage = window[type];
200
+ const key = "__stagepass_test__";
201
+ storage.setItem(key, "1");
202
+ storage.removeItem(key);
203
+ return true;
204
+ } catch (_) {
205
+ return false;
206
+ }
207
+ }
208
+ function hasServiceWorker() {
209
+ try {
210
+ return typeof navigator !== "undefined" && "serviceWorker" in navigator;
211
+ } catch (_) {
212
+ return false;
213
+ }
214
+ }
215
+ function getClientInfo() {
216
+ const ua = navigator.userAgent || "";
217
+ let timezone = null;
218
+ try {
219
+ timezone = Intl.DateTimeFormat().resolvedOptions().timeZone || null;
220
+ } catch (_) {
221
+ }
222
+ return {
223
+ theme: getThemeInfo(),
224
+ browser: getBrowserInfo(ua),
225
+ os: getOsInfo(ua),
226
+ device: getDeviceInfo(ua),
227
+ viewport: {
228
+ width: window.innerWidth || 0,
229
+ height: window.innerHeight || 0,
230
+ dpr: window.devicePixelRatio || 1
231
+ },
232
+ locale: {
233
+ language: navigator.language || "unknown",
234
+ timezone
235
+ },
236
+ capabilities: {
237
+ cookiesEnabled: navigator.cookieEnabled === true,
238
+ localStorage: hasStorage("localStorage"),
239
+ sessionStorage: hasStorage("sessionStorage")
240
+ }
241
+ };
242
+ }
243
+ function canCapability(client, capability) {
244
+ const caps = client.capabilities;
245
+ switch (capability) {
246
+ case "localStorage":
247
+ return caps.localStorage === true;
248
+ case "sessionStorage":
249
+ return caps.sessionStorage === true;
250
+ case "cookies":
251
+ return caps.cookiesEnabled === true;
252
+ case "serviceWorker":
253
+ return hasServiceWorker();
254
+ default:
255
+ return false;
256
+ }
257
+ }
258
+
259
+ // src/registry.ts
260
+ function majorFromVersion(version) {
261
+ if (!version || typeof version !== "string") return null;
262
+ const m = version.trim().match(/^(\d+)/);
263
+ if (!m) return null;
264
+ const n = Number(m[1]);
265
+ return Number.isFinite(n) ? n : null;
266
+ }
267
+ function createModuleRegistry(loaderVersion, warn) {
268
+ const loaderMajor = majorFromVersion(loaderVersion);
269
+ const registered = /* @__PURE__ */ new Map();
270
+ function use(name, version, factory, api) {
271
+ if (!name || typeof name !== "string") {
272
+ warn("stagepass.use: invalid module name");
273
+ return false;
274
+ }
275
+ const modMajor = majorFromVersion(version);
276
+ if (loaderMajor == null || modMajor == null) {
277
+ warn(`stagepass.use: cannot parse version for module "${name}"`);
278
+ return false;
279
+ }
280
+ if (modMajor !== loaderMajor) {
281
+ warn(
282
+ `Module "${name}" major ${modMajor} does not match loader major ${loaderMajor}. Skipping.`
283
+ );
284
+ return false;
285
+ }
286
+ try {
287
+ factory(api);
288
+ registered.set(name, version);
289
+ return true;
290
+ } catch (err) {
291
+ warn(`Module "${name}" failed to register:`, err);
292
+ return false;
293
+ }
294
+ }
295
+ return { use, registered };
296
+ }
297
+
2
298
  // src/index.ts
3
299
  (function() {
4
- const K = "stagepass_domain";
300
+ const K = SESSION_KEY;
5
301
  const P = "stagepass";
6
- const isValidDomain = (d) => d === "debug" || d.endsWith(".sp") || d === "localhost" || d.startsWith("localhost:");
302
+ const PKG_VERSION = true ? "2.1.0" : "0.0.0";
303
+ function getLoaderScript() {
304
+ try {
305
+ if (document.currentScript instanceof HTMLScriptElement) {
306
+ return document.currentScript;
307
+ }
308
+ } catch (_) {
309
+ }
310
+ try {
311
+ const scripts = document.querySelectorAll('script[src*="loader"]');
312
+ for (let i = scripts.length - 1; i >= 0; i--) {
313
+ const s = scripts[i];
314
+ if (/loader(?:\.min)?\.js/i.test(s.src || "")) return s;
315
+ }
316
+ } catch (_) {
317
+ }
318
+ return null;
319
+ }
320
+ const loaderScript = getLoaderScript();
321
+ const muteConsole = (loaderScript == null ? void 0 : loaderScript.getAttribute("data-stagepass-mute-console")) === "true";
322
+ const sessionHours = parseSessionHours(
323
+ loaderScript == null ? void 0 : loaderScript.getAttribute("data-stagepass-session-hours")
324
+ );
325
+ const loaderVersionAttr = loaderScript == null ? void 0 : loaderScript.getAttribute("data-stagepass-version");
326
+ const stagingHosts = parseStagingHosts(
327
+ loaderScript == null ? void 0 : loaderScript.getAttribute("data-stagepass-staging-hosts")
328
+ );
329
+ const aliasName = loaderScript == null ? void 0 : loaderScript.getAttribute("data-stagepass-alias");
7
330
  const p = new URLSearchParams(window.location.search);
8
331
  function getCallerLocation() {
9
332
  var _a;
@@ -23,26 +346,23 @@ var Stagepass = (() => {
23
346
  }
24
347
  return "";
25
348
  }
349
+ let hasActiveSession = false;
26
350
  function log(level, ...args) {
27
- const v = localStorage.getItem(K);
28
- if (!v) return;
29
- const t = (/* @__PURE__ */ new Date()).toTimeString().split(" ")[0];
30
- const loc = getCallerLocation();
31
- const pre = `[\u{1F3AB} ${t}${loc ? " |" + loc : ""}]`;
32
- if (level === "error") {
33
- console.log(`%c${pre}`, "color: red; font-weight: bold;", ...args);
34
- } else if (console[level]) {
35
- console[level](pre, ...args);
36
- } else {
37
- console.log(pre, level, ...args);
38
- }
39
- }
40
- const splog = (...args) => log("log", ...args);
41
- const spwarn = (...args) => log("warn", ...args);
42
- const sperror = (...args) => log("error", ...args);
43
- window.splog = splog;
44
- window.spwarn = spwarn;
45
- window.sperror = sperror;
351
+ if (!hasActiveSession) return;
352
+ try {
353
+ const t = (/* @__PURE__ */ new Date()).toTimeString().split(" ")[0];
354
+ const loc = getCallerLocation();
355
+ const pre = `[\u{1F3AB} ${t}${loc ? " |" + loc : ""}]`;
356
+ if (level === "error") {
357
+ console.log(`%c${pre}`, "color: red; font-weight: bold;", ...args);
358
+ } else if (console[level]) {
359
+ console[level](pre, ...args);
360
+ } else {
361
+ console.log(pre, level, ...args);
362
+ }
363
+ } catch (_) {
364
+ }
365
+ }
46
366
  function spLog(...args) {
47
367
  let level = "log";
48
368
  if (args.length > 0 && (args[0] === "warn" || args[0] === "error")) {
@@ -53,189 +373,130 @@ var Stagepass = (() => {
53
373
  }
54
374
  const spWarn = (...args) => log("warn", ...args);
55
375
  const spError = (...args) => log("error", ...args);
56
- const clean = (d) => d ? d.replace(/^https?:\/\//, "").replace(/\/$/, "") : null;
376
+ function readSessionDomain() {
377
+ try {
378
+ const raw = localStorage.getItem(K);
379
+ const record = parseSession(raw);
380
+ if (!record) {
381
+ if (raw) localStorage.removeItem(K);
382
+ return null;
383
+ }
384
+ return record.domain;
385
+ } catch (_) {
386
+ return null;
387
+ }
388
+ }
389
+ function writeSession(domain) {
390
+ try {
391
+ const record = createSession(domain, sessionHours);
392
+ localStorage.setItem(K, serializeSession(record));
393
+ } catch (_) {
394
+ }
395
+ }
396
+ function clearSession() {
397
+ try {
398
+ localStorage.removeItem(K);
399
+ } catch (_) {
400
+ }
401
+ }
57
402
  let paramProcessed = false;
58
- let sv = localStorage.getItem(K);
403
+ let sv = readSessionDomain();
59
404
  if (p.has(P)) {
60
405
  const v = p.get(P);
61
406
  if (v === "off" || v === "0" || v === "false") {
62
- localStorage.removeItem(K);
407
+ clearSession();
63
408
  sv = null;
64
- splog("\u{1F50C} Stagepass disconnected.");
409
+ hasActiveSession = true;
410
+ log("log", "\u{1F50C} Stagepass disconnected.");
411
+ hasActiveSession = false;
65
412
  } else if (v) {
66
- const c = v === "debug" ? "debug" : clean(v);
413
+ const c = v === "debug" ? "debug" : cleanDomain(v);
67
414
  if (c && isValidDomain(c)) {
68
- localStorage.setItem(K, c);
415
+ writeSession(c);
69
416
  sv = c;
70
- splog(c === "debug" ? "\u{1F50D} Stagepass debug mode enabled." : `\u{1F50C} Stagepass connected to: ${c}`);
417
+ hasActiveSession = true;
418
+ log(
419
+ "log",
420
+ c === "debug" ? "\u{1F50D} Stagepass debug mode enabled." : `\u{1F50C} Stagepass connected to: ${c}`
421
+ );
71
422
  paramProcessed = true;
72
423
  } else if (c) {
73
- spwarn(`Invalid domain: ${c}. Only .sp domains are allowed.`);
424
+ hasActiveSession = true;
425
+ spWarn(`Invalid domain: ${c}. Only .sp domains are allowed.`);
426
+ hasActiveSession = false;
74
427
  }
75
428
  }
76
- p.delete(P);
77
- const s = p.toString();
78
- window.history.replaceState({}, "", window.location.pathname + (s ? `?${s}` : "") + window.location.hash);
429
+ try {
430
+ p.delete(P);
431
+ const s = p.toString();
432
+ window.history.replaceState(
433
+ {},
434
+ "",
435
+ window.location.pathname + (s ? `?${s}` : "") + window.location.hash
436
+ );
437
+ } catch (_) {
438
+ }
79
439
  }
80
440
  if (sv && !isValidDomain(sv)) {
81
- localStorage.removeItem(K);
441
+ clearSession();
82
442
  sv = null;
83
443
  }
84
- if (sv && !paramProcessed && sv !== "debug") {
85
- splog(`\u{1F50C} Stagepass connected to: ${sv}`);
444
+ hasActiveSession = !!(sv && isValidDomain(sv));
445
+ if (sv && !paramProcessed && sv !== "debug" && hasActiveSession) {
446
+ log("log", `\u{1F50C} Stagepass connected to: ${sv}`);
86
447
  }
87
448
  const dev = !!sv;
88
449
  const swap = !!sv && sv !== "debug";
89
- const dom = swap ? clean(sv) : null;
450
+ const dom = swap ? cleanDomain(sv) : null;
90
451
  const now = swap ? Date.now() : 0;
91
452
  const cacheBust = now;
92
453
  const sessionStartTime = now;
93
454
  const hostname = window.location.hostname;
94
455
  const isLocalhost = hostname === "localhost" || hostname === "127.0.0.1" || hostname.startsWith("localhost:") || hostname.startsWith("127.0.0.1:");
95
456
  const isLocal = swap || isLocalhost;
96
- const env = isLocal ? "local" : hostname.endsWith(".webflow.io") ? "staging" : "production";
97
- const hasValidSession = sv && isValidDomain(sv);
98
- const shouldSuppress = !hasValidSession && !p.has(P);
99
- if (shouldSuppress && env === "production") {
100
- const noop = () => {
101
- };
102
- console.log = console.warn = console.error = console.info = console.debug = noop;
103
- }
104
- function getBrowserInfo(ua) {
105
- let family = "unknown";
106
- let major = null;
107
- let m = null;
108
- if (/Edg\/(\d+)/.test(ua)) {
109
- family = "edge";
110
- m = ua.match(/Edg\/(\d+)/);
111
- } else if (/OPR\/(\d+)/.test(ua)) {
112
- family = "opera";
113
- m = ua.match(/OPR\/(\d+)/);
114
- } else if (/Firefox\/(\d+)/.test(ua)) {
115
- family = "firefox";
116
- m = ua.match(/Firefox\/(\d+)/);
117
- } else if (/Chrome\/(\d+)/.test(ua)) {
118
- family = "chrome";
119
- m = ua.match(/Chrome\/(\d+)/);
120
- } else if (/Version\/(\d+).+Safari\//.test(ua)) {
121
- family = "safari";
122
- m = ua.match(/Version\/(\d+)/);
123
- }
124
- if (m && m[1]) major = Number(m[1]);
125
- return { family, major: Number.isFinite(major) ? major : null, userAgent: ua };
126
- }
127
- function getOsInfo(ua) {
128
- if (/Android/i.test(ua)) return { family: "android" };
129
- if (/iPhone|iPad|iPod/i.test(ua)) return { family: "ios" };
130
- if (/Mac OS X|Macintosh/i.test(ua)) return { family: "macos" };
131
- if (/Windows NT/i.test(ua)) return { family: "windows" };
132
- if (/Linux/i.test(ua)) return { family: "linux" };
133
- return { family: "unknown" };
134
- }
135
- function getDeviceInfo(ua) {
136
- const touch = "ontouchstart" in window || (navigator.maxTouchPoints || 0) > 0;
137
- let type = "desktop";
138
- if (/iPad|Tablet/i.test(ua)) type = "tablet";
139
- else if (/Mobi|Android.+Mobile|iPhone/i.test(ua)) type = "mobile";
140
- else if (/Android/i.test(ua) && touch) type = "tablet";
141
- return { type, touch };
142
- }
143
- function getThemeInfo() {
144
- let preferred = "no-preference";
145
- let current = "unknown";
457
+ const env = isLocal ? "local" : hostname.endsWith(".webflow.io") || stagingHosts.includes(hostname.toLowerCase()) ? "staging" : "production";
458
+ if (muteConsole && env === "production" && !hasActiveSession) {
146
459
  try {
147
- if (window.matchMedia) {
148
- if (window.matchMedia("(prefers-color-scheme: dark)").matches) {
149
- preferred = "dark";
150
- current = "dark";
151
- } else if (window.matchMedia("(prefers-color-scheme: light)").matches) {
152
- preferred = "light";
153
- current = "light";
154
- }
155
- }
156
- } catch (_) {
157
- }
158
- return { preferred, current };
159
- }
160
- function hasStorage(type) {
161
- try {
162
- const storage = window[type];
163
- const key = "__stagepass_test__";
164
- storage.setItem(key, "1");
165
- storage.removeItem(key);
166
- return true;
460
+ const noop = () => {
461
+ };
462
+ console.log = console.warn = console.error = console.info = console.debug = noop;
167
463
  } catch (_) {
168
- return false;
169
464
  }
170
465
  }
171
- function getClientInfo() {
172
- const ua = navigator.userAgent || "";
173
- let timezone = null;
174
- try {
175
- timezone = Intl.DateTimeFormat().resolvedOptions().timeZone || null;
176
- } catch (_) {
177
- }
178
- return {
179
- theme: getThemeInfo(),
180
- browser: getBrowserInfo(ua),
181
- os: getOsInfo(ua),
182
- device: getDeviceInfo(ua),
183
- viewport: {
184
- width: window.innerWidth || 0,
185
- height: window.innerHeight || 0,
186
- dpr: window.devicePixelRatio || 1
187
- },
188
- locale: {
189
- language: navigator.language || "unknown",
190
- timezone
191
- },
192
- capabilities: {
193
- cookiesEnabled: navigator.cookieEnabled === true,
194
- localStorage: hasStorage("localStorage"),
195
- sessionStorage: hasStorage("sessionStorage")
466
+ const listeners = {
467
+ theme: /* @__PURE__ */ new Set(),
468
+ session: /* @__PURE__ */ new Set()
469
+ };
470
+ function emit(event, payload) {
471
+ listeners[event].forEach((fn) => {
472
+ try {
473
+ fn(payload);
474
+ } catch (_) {
196
475
  }
197
- };
476
+ });
477
+ }
478
+ let clientInfo = getClientInfo();
479
+ function ensureClient() {
480
+ return clientInfo;
198
481
  }
199
- const stagepassObj = window.stagepass || {};
200
- const clientInfo = getClientInfo();
201
- stagepassObj.vars = Object.freeze({
202
- isLocal,
203
- env,
204
- domain: dom || hostname,
205
- timestamp: sessionStartTime,
206
- version: "1.2.0",
207
- client: clientInfo
208
- });
209
- stagepassObj.log = spLog;
210
- stagepassObj.warn = spWarn;
211
- stagepassObj.error = spError;
212
- stagepassObj.resolveLocalUrl = (relativePath) => {
213
- const v = stagepassObj.vars;
214
- if (!v.isLocal || !v.domain) return "";
215
- const clean2 = relativePath.startsWith("/") ? relativePath.substring(1) : relativePath;
216
- return clean2 ? `https://${v.domain}/${clean2}?_cb=${v.timestamp}` : "";
217
- };
218
- window.stagepass = stagepassObj;
219
- globalThis.stagepass = stagepassObj;
220
- window.sp = stagepassObj;
221
- globalThis.sp = stagepassObj;
222
482
  try {
223
483
  if (window.matchMedia) {
224
484
  const darkMq = window.matchMedia("(prefers-color-scheme: dark)");
225
485
  const lightMq = window.matchMedia("(prefers-color-scheme: light)");
226
486
  const updateTheme = () => {
227
- var _a, _b;
228
- if (!((_b = (_a = stagepassObj.vars) == null ? void 0 : _a.client) == null ? void 0 : _b.theme)) return;
487
+ const c = clientInfo;
488
+ if (!(c == null ? void 0 : c.theme)) return;
229
489
  if (darkMq.matches) {
230
- stagepassObj.vars.client.theme.current = "dark";
231
- stagepassObj.vars.client.theme.preferred = "dark";
490
+ c.theme.current = "dark";
491
+ c.theme.preferred = "dark";
232
492
  } else if (lightMq.matches) {
233
- stagepassObj.vars.client.theme.current = "light";
234
- stagepassObj.vars.client.theme.preferred = "light";
493
+ c.theme.current = "light";
494
+ c.theme.preferred = "light";
235
495
  } else {
236
- stagepassObj.vars.client.theme.current = "unknown";
237
- stagepassObj.vars.client.theme.preferred = "no-preference";
496
+ c.theme.current = "unknown";
497
+ c.theme.preferred = "no-preference";
238
498
  }
499
+ emit("theme", { ...c.theme });
239
500
  };
240
501
  if (typeof darkMq.addEventListener === "function") {
241
502
  darkMq.addEventListener("change", updateTheme);
@@ -248,89 +509,232 @@ var Stagepass = (() => {
248
509
  } catch (_) {
249
510
  }
250
511
  const updateViewport = () => {
251
- var _a, _b;
252
- if (!((_b = (_a = stagepassObj.vars) == null ? void 0 : _a.client) == null ? void 0 : _b.viewport)) return;
253
- stagepassObj.vars.client.viewport.width = window.innerWidth || 0;
254
- stagepassObj.vars.client.viewport.height = window.innerHeight || 0;
255
- stagepassObj.vars.client.viewport.dpr = window.devicePixelRatio || 1;
512
+ const c = clientInfo;
513
+ if (!(c == null ? void 0 : c.viewport)) return;
514
+ c.viewport.width = window.innerWidth || 0;
515
+ c.viewport.height = window.innerHeight || 0;
516
+ c.viewport.dpr = window.devicePixelRatio || 1;
256
517
  };
257
518
  window.addEventListener("resize", updateViewport);
258
- function swapEl(sel, pathAttr, srcAttr, type, skipAttrs) {
519
+ const stagepassObj = window.stagepass || {};
520
+ const registry = createModuleRegistry(PKG_VERSION, spWarn);
521
+ stagepassObj.vars = Object.freeze({
522
+ isLocal,
523
+ env,
524
+ domain: dom || hostname,
525
+ timestamp: sessionStartTime,
526
+ version: PKG_VERSION,
527
+ client: clientInfo
528
+ });
529
+ stagepassObj.log = spLog;
530
+ stagepassObj.warn = spWarn;
531
+ stagepassObj.error = spError;
532
+ stagepassObj.resolveLocalUrl = (relativePath) => {
533
+ const v = stagepassObj.vars;
534
+ if (!swap || !dom || !relativePath) return "";
535
+ return buildLocalAssetUrl(dom, relativePath, v.timestamp || Date.now());
536
+ };
537
+ stagepassObj.env = () => detectRuntimeEnv(hostname, dom, stagingHosts);
538
+ stagepassObj.is = (name) => stagepassObj.env() === name;
539
+ stagepassObj.can = (capability) => canCapability(ensureClient(), capability);
540
+ stagepassObj.client = (key) => {
541
+ const c = ensureClient();
542
+ if (key == null || key === "") return c;
543
+ return c[key];
544
+ };
545
+ stagepassObj.on = (event, fn) => {
546
+ if (event !== "theme" && event !== "session") {
547
+ return () => {
548
+ };
549
+ }
550
+ const set = listeners[event];
551
+ set.add(fn);
552
+ return () => {
553
+ set.delete(fn);
554
+ };
555
+ };
556
+ stagepassObj.use = (name, version, factory) => registry.use(name, version, factory, stagepassObj);
557
+ window.stagepass = stagepassObj;
558
+ globalThis.stagepass = stagepassObj;
559
+ window.sp = stagepassObj;
560
+ globalThis.sp = stagepassObj;
561
+ if (aliasName && isValidJsIdentifier(aliasName) && aliasName !== "sp" && aliasName !== "stagepass") {
562
+ if (isGlobalFree(window, aliasName)) {
563
+ window[aliasName] = stagepassObj;
564
+ }
565
+ if (isGlobalFree(globalThis, aliasName)) {
566
+ globalThis[aliasName] = stagepassObj;
567
+ }
568
+ }
569
+ emit("session", {
570
+ active: hasActiveSession,
571
+ domain: sv,
572
+ swap,
573
+ debug: sv === "debug"
574
+ });
575
+ let lnaState = "unknown";
576
+ let lnaHint = null;
577
+ function resolveAssetUrl(el, productionSrc, localPath) {
578
+ if (swap && localPath && dom) {
579
+ return buildLocalAssetUrl(dom, localPath, cacheBust);
580
+ }
581
+ const perAssetVersion = el.getAttribute("data-stagepass-v");
582
+ const version = perAssetVersion || loaderVersionAttr;
583
+ if (version) {
584
+ return appendQueryParam(productionSrc, "v", version);
585
+ }
586
+ return productionSrc;
587
+ }
588
+ function extractLocalFilename(ps) {
589
+ try {
590
+ const urlObj = new URL(ps);
591
+ const pathParts = urlObj.pathname.split("/");
592
+ return pathParts[pathParts.length - 1] || pathParts[pathParts.length - 2] || null;
593
+ } catch (e) {
594
+ const match = ps.match(/\/([^\/\?#]+)(?:\?|#|$)/);
595
+ return match ? match[1] : null;
596
+ }
597
+ }
598
+ function swapEl(sel, pathAttr, srcAttr, type, skipAttrs, seenLocalNames) {
259
599
  document.querySelectorAll(`${sel}:not([data-stagepass-processed])`).forEach((el) => {
260
- el.setAttribute("data-stagepass-processed", "true");
261
- let lp = el.getAttribute(pathAttr);
262
- const ps = el.getAttribute(srcAttr);
263
- if (!ps) return;
264
- if (!lp && ps && swap && dom) {
265
- try {
266
- const urlObj = new URL(ps);
267
- const pathParts = urlObj.pathname.split("/");
268
- lp = pathParts[pathParts.length - 1] || pathParts[pathParts.length - 2];
269
- } catch (e) {
270
- const match = ps.match(/\/([^\/\?#]+)(?:\?|#|$)/);
271
- if (match) lp = match[1];
600
+ try {
601
+ el.setAttribute("data-stagepass-processed", "true");
602
+ let lp = el.getAttribute(pathAttr);
603
+ const hadExplicitPath = !!lp;
604
+ const ps = el.getAttribute(srcAttr);
605
+ if (!ps) return;
606
+ if (!lp && ps && swap && dom) {
607
+ lp = extractLocalFilename(ps);
272
608
  }
273
- }
274
- let url;
275
- if (swap && lp && dom) {
276
- url = `https://${dom}/${lp.startsWith("/") ? lp.substring(1) : lp}?_cb=${cacheBust}`;
277
- } else if (el.getAttribute("data-stagepass-cachebust") === "true") {
278
- url = ps + (ps.includes("?") ? "&" : "?") + "_cb=" + Date.now();
279
- } else {
280
- url = ps;
281
- }
282
- if (!url) return;
283
- const n = document.createElement(type);
284
- if (type === "script") {
285
- n.src = url;
286
- Array.from(el.attributes).forEach((a) => {
287
- const attr = a;
288
- if (!skipAttrs.includes(attr.name)) n.setAttribute(attr.name, attr.value);
289
- });
290
- if (!el.hasAttribute("async") && !el.hasAttribute("defer")) n.setAttribute("defer", "");
291
- } else {
292
- n.rel = "stylesheet";
293
- n.href = url;
294
- Array.from(el.attributes).forEach((a) => {
295
- const attr = a;
296
- if (!skipAttrs.includes(attr.name)) n.setAttribute(attr.name, attr.value);
297
- });
298
- }
299
- if (el.parentNode) {
300
- el.parentNode.insertBefore(n, el);
301
- el.remove();
302
- } else {
303
- sperror(`${type} injection failed: No parent node`);
609
+ if (swap && lp && !hadExplicitPath && hasActiveSession) {
610
+ const key = lp;
611
+ const count = (seenLocalNames.get(key) || 0) + 1;
612
+ seenLocalNames.set(key, count);
613
+ if (count === 2) {
614
+ spWarn(
615
+ `Multiple assets resolve to local file "${key}" without data-stagepass-path. Set unique paths to avoid collisions.`
616
+ );
617
+ }
618
+ }
619
+ const url = resolveAssetUrl(el, ps, lp);
620
+ if (!url) return;
621
+ const n = document.createElement(type);
622
+ if (type === "script") {
623
+ n.src = url;
624
+ Array.from(el.attributes).forEach((a) => {
625
+ const attr = a;
626
+ if (!skipAttrs.includes(attr.name)) n.setAttribute(attr.name, attr.value);
627
+ });
628
+ applyScriptLoadOrder(n, el);
629
+ } else {
630
+ n.rel = "stylesheet";
631
+ n.href = url;
632
+ Array.from(el.attributes).forEach((a) => {
633
+ const attr = a;
634
+ if (!skipAttrs.includes(attr.name)) n.setAttribute(attr.name, attr.value);
635
+ });
636
+ }
637
+ if (el.parentNode) {
638
+ el.parentNode.insertBefore(n, el);
639
+ el.remove();
640
+ } else {
641
+ spError(`${type} injection failed: No parent node`);
642
+ }
643
+ } catch (_) {
304
644
  }
305
645
  });
306
646
  }
307
647
  const process = () => {
308
- swapEl("script[data-stagepass]", "data-stagepass-path", "data-src", "script", ["data-src", "data-stagepass", "data-stagepass-path", "data-stagepass-cachebust"]);
309
- swapEl('link[rel="stylesheet"][data-stagepass]', "data-stagepass-path", "data-href", "link", ["href", "data-href", "data-stagepass", "data-stagepass-path", "data-stagepass-cachebust"]);
648
+ try {
649
+ const seenLocalNames = /* @__PURE__ */ new Map();
650
+ swapEl(
651
+ "script[data-stagepass]",
652
+ "data-stagepass-path",
653
+ "data-src",
654
+ "script",
655
+ [
656
+ "data-src",
657
+ "data-stagepass",
658
+ "data-stagepass-path",
659
+ "data-stagepass-cachebust",
660
+ "data-stagepass-v"
661
+ ],
662
+ seenLocalNames
663
+ );
664
+ swapEl(
665
+ 'link[rel="stylesheet"][data-stagepass]',
666
+ "data-stagepass-path",
667
+ "data-href",
668
+ "link",
669
+ [
670
+ "href",
671
+ "data-href",
672
+ "data-stagepass",
673
+ "data-stagepass-path",
674
+ "data-stagepass-cachebust",
675
+ "data-stagepass-v"
676
+ ],
677
+ seenLocalNames
678
+ );
679
+ } catch (_) {
680
+ }
310
681
  };
311
- process();
312
- if (document.readyState === "loading") {
313
- document.addEventListener("DOMContentLoaded", process);
682
+ function updateFlagText(flag2) {
683
+ let text = sv === "debug" ? "STAGEPASS DEBUG" : "STAGEPASS ACTIVE";
684
+ if (lnaHint) {
685
+ text = sv === "debug" ? "STAGEPASS DEBUG \xB7 LNA" : "STAGEPASS \xB7 ALLOW LOCAL NETWORK";
686
+ }
687
+ flag2.textContent = text;
688
+ if (lnaHint) {
689
+ flag2.title = lnaHint;
690
+ }
314
691
  }
315
692
  function flag() {
316
693
  if (!dev) return;
317
- const f = document.createElement("div");
318
- f.id = "stagepass-flag";
319
- f.textContent = sv === "debug" ? "STAGEPASS DEBUG" : "STAGEPASS ACTIVE";
320
- f.style.cssText = 'font:12px/1 -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif;font-weight:bold;color:#fff;background:#D92662;padding:4px 6px;z-index:9999999999;position:fixed;top:0;right:0;cursor:pointer;border-radius:0 0 0 4px;user-select:none;';
321
- f.addEventListener("click", () => {
322
- localStorage.removeItem(K);
323
- splog("\u{1F50C} Stagepass disconnected.");
324
- window.location.reload();
325
- });
326
- if (document.body) {
327
- document.body.appendChild(f);
328
- } else {
329
- document.addEventListener("DOMContentLoaded", () => {
330
- if (document.body) document.body.appendChild(f);
694
+ try {
695
+ const f = document.createElement("div");
696
+ f.id = "stagepass-flag";
697
+ updateFlagText(f);
698
+ f.style.cssText = 'font:12px/1 -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif;font-weight:bold;color:#fff;background:#D92662;padding:4px 6px;z-index:9999999999;position:fixed;top:0;right:0;cursor:pointer;border-radius:0 0 0 4px;user-select:none;';
699
+ f.addEventListener("click", () => {
700
+ clearSession();
701
+ hasActiveSession = true;
702
+ log("log", "\u{1F50C} Stagepass disconnected.");
703
+ emit("session", { active: false, domain: null, swap: false, debug: false });
704
+ window.location.reload();
331
705
  });
706
+ const mount = () => {
707
+ if (document.body) document.body.appendChild(f);
708
+ };
709
+ if (document.body) mount();
710
+ else document.addEventListener("DOMContentLoaded", mount);
711
+ stagepassObj.__flagEl = f;
712
+ } catch (_) {
332
713
  }
333
714
  }
715
+ async function maybeCheckLnaAndProcess() {
716
+ if (swap) {
717
+ try {
718
+ lnaState = await queryLoopbackPermission();
719
+ lnaHint = lnaHintMessage(lnaState);
720
+ if (lnaHint) {
721
+ spWarn(lnaHint);
722
+ const flagEl = stagepassObj.__flagEl;
723
+ if (flagEl) updateFlagText(flagEl);
724
+ }
725
+ } catch (_) {
726
+ lnaState = "unknown";
727
+ lnaHint = null;
728
+ }
729
+ }
730
+ process();
731
+ }
732
+ void maybeCheckLnaAndProcess();
733
+ if (document.readyState === "loading") {
734
+ document.addEventListener("DOMContentLoaded", () => {
735
+ void maybeCheckLnaAndProcess();
736
+ });
737
+ }
334
738
  if (document.readyState === "loading") {
335
739
  document.addEventListener("DOMContentLoaded", flag);
336
740
  } else {