@stagepass/loader 1.0.1 → 1.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
@@ -3,35 +3,45 @@ var Stagepass = (() => {
3
3
  (function() {
4
4
  const K = "stagepass_domain";
5
5
  const P = "stagepass";
6
+ const isValidDomain = (d) => d === "debug" || d.endsWith(".sp") || d === "localhost" || d.startsWith("localhost:");
6
7
  const p = new URLSearchParams(window.location.search);
7
- const svCheck = localStorage.getItem(K);
8
- if (!svCheck && !p.has(P)) {
9
- const noop = () => {
10
- };
11
- console.log = noop;
12
- console.warn = noop;
13
- console.error = noop;
14
- console.info = noop;
15
- console.debug = noop;
8
+ const loaderScript = document.querySelector('script[src*="loader"]');
9
+ let modulesParam = null;
10
+ let silentParam = null;
11
+ if (loaderScript && loaderScript.src) {
12
+ try {
13
+ const scriptUrl = new URL(loaderScript.src);
14
+ modulesParam = scriptUrl.searchParams.get("modules");
15
+ silentParam = scriptUrl.searchParams.get("silent");
16
+ } catch (e) {
17
+ const modulesMatch = loaderScript.src.match(/[?&]modules(=([^&]*))?/);
18
+ if (modulesMatch) {
19
+ modulesParam = modulesMatch[2] !== void 0 ? modulesMatch[2] : "";
20
+ }
21
+ const silentMatch = loaderScript.src.match(/[?&]silent/);
22
+ if (silentMatch) {
23
+ silentParam = "";
24
+ }
25
+ }
16
26
  }
17
27
  function log(level, ...args) {
18
28
  var _a;
19
29
  const v = localStorage.getItem(K);
20
- if (!v || v !== "debug" && !v) return;
30
+ if (!v) return;
21
31
  const t = (/* @__PURE__ */ new Date()).toTimeString().split(" ")[0];
22
- let c = "unknown";
32
+ let c = "";
23
33
  try {
24
34
  const s = (_a = new Error().stack) == null ? void 0 : _a.split("\n");
25
35
  if (s) {
26
36
  const l = s.find((x, i) => i > 2 && !x.includes("log"));
27
37
  if (l) {
28
- const m = l.match(/(\/?([^\/\?:]+))(\?[^\s)]*)?:([0-9]+):[0-9]+/);
29
- if (m) c = `${m[2]}:${m[4]}`;
38
+ const m = l.match(/:([0-9]+):/);
39
+ if (m) c = `:${m[1]}`;
30
40
  }
31
41
  }
32
42
  } catch (e) {
33
43
  }
34
- const pre = `[\u{1F3AB} ${t} \u{1F4CD} ${c}]`;
44
+ const pre = `[\u{1F3AB} ${t}${c ? " \u{1F4CD}" + c : ""}]`;
35
45
  if (level === "error") {
36
46
  console.log(`%c${pre}`, "color: red; font-weight: bold;", ...args);
37
47
  } else if (console[level]) {
@@ -46,25 +56,23 @@ var Stagepass = (() => {
46
56
  window.splog = splog;
47
57
  window.spwarn = spwarn;
48
58
  window.sperror = sperror;
49
- function clean(d) {
50
- return d ? d.replace(/^https?:\/\//, "").replace(/\/$/, "") : null;
51
- }
52
- function isValidDomain(d) {
53
- return d === "debug" || d.endsWith(".sp") || d === "localhost" || d.startsWith("localhost:");
54
- }
59
+ const clean = (d) => d ? d.replace(/^https?:\/\//, "").replace(/\/$/, "") : null;
55
60
  let paramProcessed = false;
61
+ let sv = localStorage.getItem(K);
56
62
  if (p.has(P)) {
57
63
  const v = p.get(P);
58
64
  if (v === "off" || v === "0" || v === "false") {
59
65
  localStorage.removeItem(K);
66
+ sv = null;
60
67
  splog("\u{1F50C} Stagepass disconnected.");
61
68
  } else if (v) {
62
69
  const c = v === "debug" ? "debug" : clean(v);
63
70
  if (c && isValidDomain(c)) {
64
71
  localStorage.setItem(K, c);
72
+ sv = c;
65
73
  splog(c === "debug" ? "\u{1F50D} Stagepass debug mode enabled." : `\u{1F50C} Stagepass connected to: ${c}`);
66
74
  paramProcessed = true;
67
- } else if (c && !isValidDomain(c)) {
75
+ } else if (c) {
68
76
  spwarn(`Invalid domain: ${c}. Only .sp domains are allowed.`);
69
77
  }
70
78
  }
@@ -72,7 +80,6 @@ var Stagepass = (() => {
72
80
  const s = p.toString();
73
81
  window.history.replaceState({}, "", window.location.pathname + (s ? `?${s}` : "") + window.location.hash);
74
82
  }
75
- let sv = localStorage.getItem(K);
76
83
  if (sv && !isValidDomain(sv)) {
77
84
  localStorage.removeItem(K);
78
85
  sv = null;
@@ -83,9 +90,32 @@ var Stagepass = (() => {
83
90
  const dev = !!sv;
84
91
  const swap = !!sv && sv !== "debug";
85
92
  const dom = swap ? clean(sv) : null;
93
+ const now = swap ? Date.now() : 0;
94
+ const cacheBust = now;
95
+ const sessionStartTime = now;
96
+ const hostname = window.location.hostname;
97
+ const isLocalhost = hostname === "localhost" || hostname === "127.0.0.1" || hostname.startsWith("localhost:") || hostname.startsWith("127.0.0.1:");
98
+ const isLocal = swap || isLocalhost;
99
+ const env = isLocal ? "local" : hostname.endsWith(".webflow.io") ? "staging" : "production";
100
+ const hasValidSession = sv && isValidDomain(sv);
101
+ const shouldSuppress = !hasValidSession && !p.has(P);
102
+ if (shouldSuppress && (env === "production" || env === "staging" && silentParam !== null)) {
103
+ const noop = () => {
104
+ };
105
+ console.log = console.warn = console.error = console.info = console.debug = noop;
106
+ }
107
+ const stagepassObj = window.stagepass || {};
108
+ stagepassObj.vars = Object.freeze({
109
+ isLocal,
110
+ env,
111
+ domain: dom || hostname,
112
+ timestamp: sessionStartTime,
113
+ version: "1.1.0"
114
+ });
115
+ window.stagepass = stagepassObj;
116
+ globalThis.stagepass = stagepassObj;
86
117
  function swapEl(sel, pathAttr, srcAttr, type, skipAttrs) {
87
- const els = document.querySelectorAll(`${sel}:not([data-stagepass-processed])`);
88
- els.forEach((el) => {
118
+ document.querySelectorAll(`${sel}:not([data-stagepass-processed])`).forEach((el) => {
89
119
  el.setAttribute("data-stagepass-processed", "true");
90
120
  let lp = el.getAttribute(pathAttr);
91
121
  const ps = el.getAttribute(srcAttr);
@@ -100,45 +130,63 @@ var Stagepass = (() => {
100
130
  if (match) lp = match[1];
101
131
  }
102
132
  }
103
- let url = "";
104
- if (swap && lp && dom) {
105
- const cp = lp.startsWith("/") ? lp.substring(1) : lp;
106
- url = `https://${dom}/${cp}`;
107
- } else if (ps) {
108
- url = ps;
133
+ const url = swap && lp && dom ? `https://${dom}/${lp.startsWith("/") ? lp.substring(1) : lp}?_cb=${cacheBust}` : ps;
134
+ if (!url) return;
135
+ const n = document.createElement(type);
136
+ if (type === "script") {
137
+ n.src = url;
138
+ Array.from(el.attributes).forEach((a) => {
139
+ const attr = a;
140
+ if (!skipAttrs.includes(attr.name)) n.setAttribute(attr.name, attr.value);
141
+ });
142
+ if (!el.hasAttribute("async") && !el.hasAttribute("defer")) n.setAttribute("defer", "");
143
+ } else {
144
+ n.rel = "stylesheet";
145
+ n.href = url;
146
+ Array.from(el.attributes).forEach((a) => {
147
+ const attr = a;
148
+ if (!skipAttrs.includes(attr.name)) n.setAttribute(attr.name, attr.value);
149
+ });
109
150
  }
110
- if (url) {
111
- const n = document.createElement(type);
112
- if (type === "script") {
113
- n.src = url;
114
- Array.from(el.attributes).forEach((a) => {
115
- const attr = a;
116
- if (!skipAttrs.includes(attr.name)) n.setAttribute(attr.name, attr.value);
117
- });
118
- if (!el.hasAttribute("async") && !el.hasAttribute("defer")) {
119
- n.setAttribute("defer", "");
120
- }
121
- } else {
122
- n.rel = "stylesheet";
123
- n.href = url;
124
- Array.from(el.attributes).forEach((a) => {
125
- const attr = a;
126
- if (!skipAttrs.includes(attr.name)) n.setAttribute(attr.name, attr.value);
127
- });
128
- }
129
- if (el.parentNode) {
130
- el.parentNode.insertBefore(n, el);
131
- el.remove();
132
- } else {
133
- sperror(`${type} injection failed: No parent node`);
134
- }
151
+ if (el.parentNode) {
152
+ el.parentNode.insertBefore(n, el);
153
+ el.remove();
154
+ } else {
155
+ sperror(`${type} injection failed: No parent node`);
135
156
  }
136
157
  });
137
158
  }
138
- function process() {
159
+ function loadModules() {
160
+ if (modulesParam === null) return;
161
+ const modulesToLoad = modulesParam === "" ? ["all"] : modulesParam.split(",").map((m) => m.trim()).filter(Boolean);
162
+ if (modulesToLoad.length === 0) return;
163
+ let baseUrl = window.location.origin;
164
+ if (loaderScript && loaderScript.src) {
165
+ try {
166
+ const scriptUrl = new URL(loaderScript.src);
167
+ const pathParts = scriptUrl.pathname.split("/");
168
+ pathParts.pop();
169
+ baseUrl = `${scriptUrl.origin}${pathParts.join("/")}`;
170
+ } catch (e) {
171
+ baseUrl = loaderScript.src.replace(/\/[^\/\?]+(\?.*)?$/, "");
172
+ }
173
+ }
174
+ modulesToLoad.forEach((moduleName) => {
175
+ const moduleUrl = `${baseUrl}/${moduleName}.min.js`;
176
+ const script = document.createElement("script");
177
+ script.src = moduleUrl;
178
+ script.async = true;
179
+ document.head.appendChild(script);
180
+ if (env !== "production") {
181
+ splog(`\u{1F4E6} Loading module: ${moduleName}`);
182
+ }
183
+ });
184
+ }
185
+ const process = () => {
139
186
  swapEl("script[data-stagepass]", "data-stagepass-path", "data-src", "script", ["data-src", "data-stagepass", "data-stagepass-path"]);
140
187
  swapEl('link[rel="stylesheet"][data-stagepass]', "data-stagepass-path", "data-href", "link", ["href", "data-href", "data-stagepass", "data-stagepass-path"]);
141
- }
188
+ };
189
+ loadModules();
142
190
  process();
143
191
  if (document.readyState === "loading") {
144
192
  document.addEventListener("DOMContentLoaded", process);
@@ -148,7 +196,7 @@ var Stagepass = (() => {
148
196
  const f = document.createElement("div");
149
197
  f.id = "stagepass-flag";
150
198
  f.textContent = sv === "debug" ? "STAGEPASS DEBUG" : "STAGEPASS ACTIVE";
151
- f.style.cssText = `font-size: 12px; line-height: 1; font-weight: bold; color: #fff; background-color: #D92662; padding: 4px 6px; z-index: 9999999999; position: fixed; top: 0; right: 0; cursor: pointer; border-radius: 0 0 0 4px; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; user-select: none;`;
199
+ 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;';
152
200
  f.addEventListener("click", () => {
153
201
  localStorage.removeItem(K);
154
202
  splog("\u{1F50C} Stagepass disconnected.");
@@ -1,2 +1,2 @@
1
- var Stagepass=(()=>{(function(){let d="stagepass_domain",h="stagepass",f=new URLSearchParams(window.location.search);if(!localStorage.getItem(d)&&!f.has(h)){let t=()=>{};console.log=t,console.warn=t,console.error=t,console.info=t,console.debug=t}function w(t,...l){var s;let e=localStorage.getItem(d);if(!e||e!=="debug"&&!e)return;let u=new Date().toTimeString().split(" ")[0],m="unknown";try{let a=(s=new Error().stack)==null?void 0:s.split(`
2
- `);if(a){let i=a.find((r,n)=>n>2&&!r.includes("log"));if(i){let r=i.match(/(\/?([^\/\?:]+))(\?[^\s)]*)?:([0-9]+):[0-9]+/);r&&(m=`${r[2]}:${r[4]}`)}}}catch{}let b=`[\u{1F3AB} ${u} \u{1F4CD} ${m}]`;t==="error"?console.log(`%c${b}`,"color: red; font-weight: bold;",...l):console[t]?console[t](b,...l):console.log(b,t,...l)}let g=(...t)=>w("log",...t),A=(...t)=>w("warn",...t),v=(...t)=>w("error",...t);window.splog=g,window.spwarn=A,window.sperror=v;function $(t){return t?t.replace(/^https?:\/\//,"").replace(/\/$/,""):null}function y(t){return t==="debug"||t.endsWith(".sp")||t==="localhost"||t.startsWith("localhost:")}let L=!1;if(f.has(h)){let t=f.get(h);if(t==="off"||t==="0"||t==="false")localStorage.removeItem(d),g("\u{1F50C} Stagepass disconnected.");else if(t){let e=t==="debug"?"debug":$(t);e&&y(e)?(localStorage.setItem(d,e),g(e==="debug"?"\u{1F50D} Stagepass debug mode enabled.":`\u{1F50C} Stagepass connected to: ${e}`),L=!0):e&&!y(e)&&A(`Invalid domain: ${e}. Only .sp domains are allowed.`)}f.delete(h);let l=f.toString();window.history.replaceState({},"",window.location.pathname+(l?`?${l}`:"")+window.location.hash)}let o=localStorage.getItem(d);o&&!y(o)&&(localStorage.removeItem(d),o=null),o&&!L&&o!=="debug"&&g(`\u{1F50C} Stagepass connected to: ${o}`);let x=!!o,S=!!o&&o!=="debug",E=S?$(o):null;function k(t,l,e,u,m){document.querySelectorAll(`${t}:not([data-stagepass-processed])`).forEach(s=>{s.setAttribute("data-stagepass-processed","true");let a=s.getAttribute(l),i=s.getAttribute(e);if(!i)return;if(!a&&i&&S&&E)try{let c=new URL(i).pathname.split("/");a=c[c.length-1]||c[c.length-2]}catch{let c=i.match(/\/([^\/\?#]+)(?:\?|#|$)/);c&&(a=c[1])}let r="";if(S&&a&&E){let n=a.startsWith("/")?a.substring(1):a;r=`https://${E}/${n}`}else i&&(r=i);if(r){let n=document.createElement(u);u==="script"?(n.src=r,Array.from(s.attributes).forEach(c=>{let p=c;m.includes(p.name)||n.setAttribute(p.name,p.value)}),!s.hasAttribute("async")&&!s.hasAttribute("defer")&&n.setAttribute("defer","")):(n.rel="stylesheet",n.href=r,Array.from(s.attributes).forEach(c=>{let p=c;m.includes(p.name)||n.setAttribute(p.name,p.value)})),s.parentNode?(s.parentNode.insertBefore(n,s),s.remove()):v(`${u} injection failed: No parent node`)}})}function C(){k("script[data-stagepass]","data-stagepass-path","data-src","script",["data-src","data-stagepass","data-stagepass-path"]),k('link[rel="stylesheet"][data-stagepass]',"data-stagepass-path","data-href","link",["href","data-href","data-stagepass","data-stagepass-path"])}C(),document.readyState==="loading"&&document.addEventListener("DOMContentLoaded",C);function I(){if(!x)return;let t=document.createElement("div");t.id="stagepass-flag",t.textContent=o==="debug"?"STAGEPASS DEBUG":"STAGEPASS ACTIVE",t.style.cssText='font-size: 12px; line-height: 1; font-weight: bold; color: #fff; background-color: #D92662; padding: 4px 6px; z-index: 9999999999; position: fixed; top: 0; right: 0; cursor: pointer; border-radius: 0 0 0 4px; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; user-select: none;',t.addEventListener("click",()=>{localStorage.removeItem(d),g("\u{1F50C} Stagepass disconnected."),window.location.reload()}),document.body?document.body.appendChild(t):document.addEventListener("DOMContentLoaded",()=>{document.body&&document.body.appendChild(t)})}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",I):I()})();})();
1
+ var Stagepass=(()=>{(function(){let g="stagepass_domain",y="stagepass",$=t=>t==="debug"||t.endsWith(".sp")||t==="localhost"||t.startsWith("localhost:"),w=new URLSearchParams(window.location.search),d=document.querySelector('script[src*="loader"]'),b=null,v=null;if(d&&d.src)try{let t=new URL(d.src);b=t.searchParams.get("modules"),v=t.searchParams.get("silent")}catch{let s=d.src.match(/[?&]modules(=([^&]*))?/);s&&(b=s[2]!==void 0?s[2]:""),d.src.match(/[?&]silent/)&&(v="")}function A(t,...s){var l;if(!localStorage.getItem(g))return;let c=new Date().toTimeString().split(" ")[0],i="";try{let p=(l=new Error().stack)==null?void 0:l.split(`
2
+ `);if(p){let h=p.find((r,u)=>u>2&&!r.includes("log"));if(h){let r=h.match(/:([0-9]+):/);r&&(i=`:${r[1]}`)}}}catch{}let o=`[\u{1F3AB} ${c}${i?" \u{1F4CD}"+i:""}]`;t==="error"?console.log(`%c${o}`,"color: red; font-weight: bold;",...s):console[t]?console[t](o,...s):console.log(o,t,...s)}let f=(...t)=>A("log",...t),T=(...t)=>A("warn",...t),P=(...t)=>A("error",...t);window.splog=f,window.spwarn=T,window.sperror=P;let k=t=>t?t.replace(/^https?:\/\//,"").replace(/\/$/,""):null,C=!1,n=localStorage.getItem(g);if(w.has(y)){let t=w.get(y);if(t==="off"||t==="0"||t==="false")localStorage.removeItem(g),n=null,f("\u{1F50C} Stagepass disconnected.");else if(t){let e=t==="debug"?"debug":k(t);e&&$(e)?(localStorage.setItem(g,e),n=e,f(e==="debug"?"\u{1F50D} Stagepass debug mode enabled.":`\u{1F50C} Stagepass connected to: ${e}`),C=!0):e&&T(`Invalid domain: ${e}. Only .sp domains are allowed.`)}w.delete(y);let s=w.toString();window.history.replaceState({},"",window.location.pathname+(s?`?${s}`:"")+window.location.hash)}n&&!$(n)&&(localStorage.removeItem(g),n=null),n&&!C&&n!=="debug"&&f(`\u{1F50C} Stagepass connected to: ${n}`);let j=!!n,S=!!n&&n!=="debug",E=S?k(n):null,U=S?Date.now():0,W=U,B=U,m=window.location.hostname,R=m==="localhost"||m==="127.0.0.1"||m.startsWith("localhost:")||m.startsWith("127.0.0.1:"),I=S||R,L=I?"local":m.endsWith(".webflow.io")?"staging":"production";!(n&&$(n))&&!w.has(y)&&(L==="production"||L==="staging"&&v!==null)&&(console.log=console.warn=console.error=console.info=console.debug=()=>{});let M=window.stagepass||{};M.vars=Object.freeze({isLocal:I,env:L,domain:E||m,timestamp:B,version:"1.1.0"}),window.stagepass=M,globalThis.stagepass=M;function x(t,s,e,c,i){document.querySelectorAll(`${t}:not([data-stagepass-processed])`).forEach(o=>{o.setAttribute("data-stagepass-processed","true");let l=o.getAttribute(s),p=o.getAttribute(e);if(!p)return;if(!l&&p&&S&&E)try{let a=new URL(p).pathname.split("/");l=a[a.length-1]||a[a.length-2]}catch{let a=p.match(/\/([^\/\?#]+)(?:\?|#|$)/);a&&(l=a[1])}let h=S&&l&&E?`https://${E}/${l.startsWith("/")?l.substring(1):l}?_cb=${W}`:p;if(!h)return;let r=document.createElement(c);c==="script"?(r.src=h,Array.from(o.attributes).forEach(u=>{let a=u;i.includes(a.name)||r.setAttribute(a.name,a.value)}),!o.hasAttribute("async")&&!o.hasAttribute("defer")&&r.setAttribute("defer","")):(r.rel="stylesheet",r.href=h,Array.from(o.attributes).forEach(u=>{let a=u;i.includes(a.name)||r.setAttribute(a.name,a.value)})),o.parentNode?(o.parentNode.insertBefore(r,o),o.remove()):P(`${c} injection failed: No parent node`)})}function H(){if(b===null)return;let t=b===""?["all"]:b.split(",").map(e=>e.trim()).filter(Boolean);if(t.length===0)return;let s=window.location.origin;if(d&&d.src)try{let e=new URL(d.src),c=e.pathname.split("/");c.pop(),s=`${e.origin}${c.join("/")}`}catch{s=d.src.replace(/\/[^\/\?]+(\?.*)?$/,"")}t.forEach(e=>{let c=`${s}/${e}.min.js`,i=document.createElement("script");i.src=c,i.async=!0,document.head.appendChild(i),L!=="production"&&f(`\u{1F4E6} Loading module: ${e}`)})}let D=()=>{x("script[data-stagepass]","data-stagepass-path","data-src","script",["data-src","data-stagepass","data-stagepass-path"]),x('link[rel="stylesheet"][data-stagepass]',"data-stagepass-path","data-href","link",["href","data-href","data-stagepass","data-stagepass-path"])};H(),D(),document.readyState==="loading"&&document.addEventListener("DOMContentLoaded",D);function O(){if(!j)return;let t=document.createElement("div");t.id="stagepass-flag",t.textContent=n==="debug"?"STAGEPASS DEBUG":"STAGEPASS ACTIVE",t.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;',t.addEventListener("click",()=>{localStorage.removeItem(g),f("\u{1F50C} Stagepass disconnected."),window.location.reload()}),document.body?document.body.appendChild(t):document.addEventListener("DOMContentLoaded",()=>{document.body&&document.body.appendChild(t)})}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",O):O()})();})();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stagepass/loader",
3
- "version": "1.0.1",
3
+ "version": "1.1.0",
4
4
  "description": "Universal loader for Stagepass - injects local files into Webflow projects",
5
5
  "main": "dist/loader.min.js",
6
6
  "type": "module",
@@ -9,7 +9,9 @@
9
9
  ],
10
10
  "scripts": {
11
11
  "build": "tsup",
12
- "dev": "tsup --watch"
12
+ "dev": "tsup --watch",
13
+ "test": "vitest run",
14
+ "test:watch": "vitest"
13
15
  },
14
16
  "keywords": [
15
17
  "webflow",
@@ -26,6 +28,9 @@
26
28
  "license": "MIT",
27
29
  "devDependencies": {
28
30
  "tsup": "^8.0.1",
29
- "typescript": "^5.3.3"
31
+ "typescript": "^5.3.3",
32
+ "vitest": "^2.1.0",
33
+ "jsdom": "^24.0.0",
34
+ "@vitest/ui": "^2.1.0"
30
35
  }
31
36
  }