@stagepass/loader 2.3.0 → 2.3.1

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/README.md CHANGED
@@ -48,6 +48,7 @@ See [MIGRATION.md](../../MIGRATION.md) for breaking changes from 1.x.
48
48
  | `data-stagepass-mute-console="true"` | Opt-in legacy mute of `console.log/warn/error/info/debug` in production when no session. |
49
49
  | `data-stagepass-staging-hosts` | Comma-separated hostnames treated as staging (in addition to `*.webflow.io`). |
50
50
  | `data-stagepass-alias` | Optional custom global name (valid JS identifier). Assigned only when that global is free. |
51
+ | `data-stagepass-flag-base` | Folder for `flag.min.js` / `flag-card.min.js` when the loader is inlined or bundled (2.3.1+). `http(s)` or relative only; also `window.stagepassFlagBase`. Read only during a session. |
51
52
 
52
53
  ## Asset attributes
53
54
 
@@ -90,7 +91,7 @@ Shown only while a session is active (including debug).
90
91
  - Errors: `sp.error`, `sp.log('error', …)`, `console.error`, uncaught errors (with stack), failed resource loads, unhandled rejections (with stack). Local files report "Local file not found (404)" or "Local server not reachable … Run stagepass doctor". Sanitized errors from other origins show as "Error in a cross-origin script (details only in DevTools console)".
91
92
  - Accessibility: the pill is a button with `aria-expanded`, the card a `role="dialog"`; focus moves into the card and back to the pill; reduced motion makes all changes instant.
92
93
  - Rendered in an open Shadow DOM (`#stagepass-flag`) with DOM APIs only (no `innerHTML`, no `eval`, constructable stylesheet with a `<style>` fallback). No shadows, glow or filters.
93
- - The UI lives in `dist/flag.min.js` (about 2.7 KB gzip) and `dist/flag-card.min.js` (about 4.8 KB gzip, fetched on first expand). Both are fetched only during a session, next to the loader URL (or from jsDelivr at the same version when the loader is served under another file name). Allow that origin in `script-src` if the site uses a strict CSP.
94
+ - The UI lives in `dist/flag.min.js` (about 2.7 KB gzip) and `dist/flag-card.min.js` (about 4.8 KB gzip, fetched on first expand). Both are fetched only during a session, from the folder of the loader's script URL under any file name (self-hosted or copied from `node_modules`: keep the three files together). Inlined or bundled: set `data-stagepass-flag-base`; without a script URL and without the option they come from jsDelivr at the same version (debug sessions warn). Allow that origin in `script-src` if the site uses a strict CSP.
94
95
 
95
96
  ## Runtime API
96
97
 
package/dist/loader.js CHANGED
@@ -288,8 +288,19 @@ var Stagepass = (() => {
288
288
  const W = window;
289
289
  const d = document;
290
290
  const loc = location;
291
- const PKG_VERSION = true ? "2.3.0" : "0.0.0";
291
+ const PKG_VERSION = true ? "2.3.1" : "0.0.0";
292
292
  const LOADER_RE = /loader(?:\.min)?\.js/i;
293
+ function flagBase(v, file) {
294
+ if (typeof v !== "string" || !(v = v.trim())) return null;
295
+ try {
296
+ const u = new URL(v, d.baseURI);
297
+ if (!/^https?:$/.test(u.protocol) || u.username || u.password) return null;
298
+ u.search = u.hash = "";
299
+ return file ? new URL("./", u).href : u.href.replace(/\/?$/, "/");
300
+ } catch (_) {
301
+ return null;
302
+ }
303
+ }
293
304
  function getLoaderScript() {
294
305
  try {
295
306
  if (d.currentScript instanceof HTMLScriptElement) return d.currentScript;
@@ -545,8 +556,14 @@ var Stagepass = (() => {
545
556
  if (dev) {
546
557
  try {
547
558
  const FLAG = /* @__PURE__ */ Symbol.for("stagepass.flag.v2");
548
- const src = loaderScript && loaderScript.src || "";
549
- const base = /\/loader(?:\.min)?\.js$/i.test(src.split(/[?#]/)[0]) ? new URL("./", src).href : `https://cdn.jsdelivr.net/npm/@stagepass/loader@${PKG_VERSION}/dist/`;
559
+ const opt = attr("flag-base") ?? W.stagepassFlagBase;
560
+ let base = flagBase(opt, false);
561
+ if (opt != null && !base) spWarn("Ignored flag base (http(s) or relative only): " + cut(String(opt), 99));
562
+ base = base || flagBase(loaderScript && loaderScript.src || "", true);
563
+ if (!base) {
564
+ base = `https://cdn.jsdelivr.net/npm/@stagepass/loader@${PKG_VERSION}/dist/`;
565
+ if (debug) spWarn("Loader URL unknown, flag loads from " + base + ". Set data-stagepass-flag-base");
566
+ }
550
567
  Object.assign(flagState, {
551
568
  debug,
552
569
  domain: dom,
@@ -1,2 +1,2 @@
1
- var Stagepass=(()=>{function P(t){if(typeof t!="string"||!t)return!1;if(t==="debug"||t==="localhost")return!0;if(t.startsWith("localhost:")){let s=t.slice(10);return/^[0-9]{1,5}$/.test(s)&&Number(s)<=65535}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(t)}function Y(t){return t?t.replace(/^https?:\/\//i,"").replace(/\/$/,""):null}var Se="stagepass_domain",U=12;function ye(t,s=Date.now()){if(!t||!t.startsWith("{"))return null;try{let r=JSON.parse(t);return typeof r.domain!="string"||typeof r.expires!="number"||!Number.isFinite(r.expires)||!P(r.domain)||r.expires<=s?null:{domain:r.domain,expires:r.expires}}catch{return null}}function be(t,s=U,r=Date.now()){let c=Number.isFinite(s)&&s>0?s:U;return{domain:t,expires:r+c*60*60*1e3}}function we(t){return JSON.stringify(t)}function ke(t){if(t==null||t==="")return U;let s=Number(t);return!Number.isFinite(s)||s<=0?U:s}function ve(t,s,r){if(!t||typeof t!="string")return t;let c=encodeURIComponent(r),f=t.indexOf("#"),h=f>=0?t.slice(f):"",E=f>=0?t.slice(0,f):t,N=E.includes("?")?"&":"?";return`${E}${N}${encodeURIComponent(s)}=${c}${h}`}function X(t,s,r){let c=s.startsWith("/")?s.substring(1):s;return`https://${t}/${c}?_cb=${encodeURIComponent(String(r))}`}async function Ee(){let t=typeof navigator<"u"?navigator.permissions:void 0;if(!t||typeof t.query!="function")return"unknown";let s=["loopback-network","local-network-access"];for(let r of s)try{let c=await t.query({name:r}),f=c&&c.state;if(f==="granted"||f==="prompt"||f==="denied")return f}catch{}return"unknown"}function ee(t){return t==="prompt"?"Local network access is required. Allow local/loopback network access when Chrome prompts, then reload.":t==="denied"?"Local network access is blocked. Enable loopback/local network access for this site in Chrome settings, then reload.":null}function xe(t,s){let r=s.hasAttribute("async"),c=s.hasAttribute("defer");r?t.async=!0:(t.async=!1,c||(t.defer=!0))}function _e(t){return!t||typeof t!="string"?[]:t.split(",").map(s=>s.trim().toLowerCase()).filter(Boolean)}function Le(t,s,r=[]){if(s&&s.endsWith(".sp"))return"local";let c=(t||"").toLowerCase();return c.endsWith(".webflow.io")||r.some(f=>f===c)?"staging":"production"}function $e(t){return!t||typeof t!="string"?!1:/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)}function Ae(t,s){try{return typeof t[s]>"u"}catch{return!1}}var Ke=[["edge",/Edg\/(\d+)/],["opera",/OPR\/(\d+)/],["firefox",/Firefox\/(\d+)/],["chrome",/Chrome\/(\d+)/],["safari",/Version\/(\d+).+Safari\//]],Ze=[["android",/Android/i],["ios",/iPhone|iPad|iPod/i],["macos",/Mac OS X|Macintosh/i],["windows",/Windows NT/i],["linux",/Linux/i]];function Qe(t){for(let[s,r]of Ke){let c=t.match(r);if(c)return{family:s,major:Number(c[1]),userAgent:t}}return{family:"unknown",major:null,userAgent:t}}function Ye(t){let s=Ze.find(([,r])=>r.test(t));return{family:s?s[0]:"unknown"}}function Xe(t){let s="ontouchstart"in window||(navigator.maxTouchPoints||0)>0,r="desktop";return/iPad|Tablet/i.test(t)?r="tablet":/Mobi|Android.+Mobile|iPhone/i.test(t)?r="mobile":/Android/i.test(t)&&s&&(r="tablet"),{type:r,touch:s}}function te(){let t=null;try{let s=r=>matchMedia(`(prefers-color-scheme: ${r})`).matches;t=s("dark")?"dark":s("light")?"light":null}catch{}return{preferred:t||"no-preference",current:t||"unknown"}}function Ie(t){try{let s=window[t],r="__stagepass_test__";return s.setItem(r,"1"),s.removeItem(r),!0}catch{return!1}}function et(){try{return typeof navigator<"u"&&"serviceWorker"in navigator}catch{return!1}}function Oe(){let t=navigator.userAgent||"",s=null;try{s=Intl.DateTimeFormat().resolvedOptions().timeZone||null}catch{}return{theme:te(),browser:Qe(t),os:Ye(t),device:Xe(t),viewport:{width:window.innerWidth||0,height:window.innerHeight||0,dpr:window.devicePixelRatio||1},locale:{language:navigator.language||"unknown",timezone:s},capabilities:{cookiesEnabled:navigator.cookieEnabled===!0,localStorage:Ie("localStorage"),sessionStorage:Ie("sessionStorage")}}}function Re(t,s){let r=t.capabilities;switch(s){case"localStorage":return r.localStorage===!0;case"sessionStorage":return r.sessionStorage===!0;case"cookies":return r.cookiesEnabled===!0;case"serviceWorker":return et();default:return!1}}function Ne(t){if(!t||typeof t!="string")return null;let s=t.trim().match(/^(\d+)/);if(!s)return null;let r=Number(s[1]);return Number.isFinite(r)?r:null}function Ce(t,s){let r=Ne(t),c=new Map;function f(h,E,N,$){if(!h||typeof h!="string")return s("stagepass.use: invalid module name"),!1;let k=Ne(E);if(r==null||k==null)return s(`stagepass.use: cannot parse version for module "${h}"`),!1;if(k!==r)return s(`Module "${h}" major ${k} does not match loader major ${r}. Skipping.`),!1;try{return N($),c.set(h,E),!0}catch(V){return s(`Module "${h}" failed to register:`,V),!1}}return{use:f,registered:c}}(function(){let t=Se,s="stagepass",r=window,c=document,f=location,h="2.3.0",E=/loader(?:\.min)?\.js/i;function N(){try{if(c.currentScript instanceof HTMLScriptElement)return c.currentScript}catch{}try{let e=c.querySelectorAll('script[src*="loader"]');for(let n=e.length-1;n>=0;n--)if(E.test(e[n].src||""))return e[n]}catch{}return null}let $=N(),k=e=>$?$.getAttribute("data-stagepass-"+e):null,V=k("mute-console")==="true",je=ke(k("session-hours")),Fe=k("version"),ne=_e(k("staging-hosts")),A=k("alias"),T=new URLSearchParams(f.search),v=!1,x={n:[0,0],m:[],f:[],swapped:0,v:h},C=null,se=()=>C&&C(),re=()=>new Date().toTimeString().slice(0,8),D=e=>(e||"").split(/[?#]/)[0].split("/").pop()||"",q=(e,n)=>e.length>n?e.slice(0,n)+"\u2026":e,oe=(e,n=0)=>{try{if(typeof e=="string")return n?JSON.stringify(e):e;if(e instanceof Error)return e.name+": "+e.message;if(!e||typeof e!="object")return String(e);if(e instanceof Node)return"<"+e.nodeName.toLowerCase()+">";let o=Array.isArray(e);if(n>2)return o?"[\u2026]":"{\u2026}";let u=Object.keys(e),i=u.slice(0,20).map(a=>(o?"":a+": ")+oe(e[a],n+1));return u.length>20&&i.push("\u2026"),q(o?"["+i.join(", ")+"]":"{"+i.join(", ")+"}",1e3)}catch{return"[unserializable]"}},G=(e,n=0)=>{let o=(e||"").split(`
2
- `);for(let u=n;u<o.length;u++){let i=o[u].match(/([a-z][\w+.-]*:\/\/[^\s()]+?):(\d+):(\d+)/i);if(i&&!E.test(D(i[1])))return[i[1],i[2],i[3]]}return null},y=null,Me=e=>e?y&&!e.indexOf(`https://${y}/`)?"local":"live":"external",I=(e,n,o="",u="",i="",a="",d)=>{x.n[e]++;let l=x.m,m={type:e?"error":"warn",time:re(),src:d||(o?Me(o):""),file:D(o),url:o.split(/[?#]/)[0],line:u?String(u):"",col:i?String(i):"",text:q(n,500),stack:q(a,2e3),c:1},S=p=>p.type+p.text+p.url+p.line+p.col;for(let p=l.length-1;p>=0;p--)if(S(l[p])===S(m)){m.c=l[p].c+1,l.splice(p,1);break}l.push(m),l.length>50&&l.shift(),se()},B=(e,n,o,u)=>{let i=o.find(l=>l instanceof Error),a=i&&i.stack||"",d=G(a)||u;I(e,n+o.map(l=>oe(l)).join(" "),d?d[0]:"",d?d[1]:"",d?d[2]:"",a)},j=!1,Pe=e=>{j=!0;try{e()}catch{}j=!1};function O(e,...n){if(!v)return;let o=G(new Error().stack||"",3);(e==="warn"||e==="error")&&B(e==="warn"?0:1,"",n,o),Pe(()=>{let u=`[\u{1F3AB} ${re()}${o?" | "+D(o[0])+":"+o[1]:""}]`,i=console;e==="error"?i.log(`%c${u}`,"color:red;font-weight:bold",...n):i[e]?i[e](u,...n):i.log(u,e,...n)})}function Te(...e){let n=e[0]==="warn"||e[0]==="error"?e.shift():"log";O(n,...e)}let W=(...e)=>O("warn",...e),ie=(...e)=>O("error",...e),J=(e,n)=>{let o=v;v=!0,O(e,n),v=o};function De(){try{let e=localStorage.getItem(t),n=ye(e);return!n&&e&&localStorage.removeItem(t),n?n.domain:null}catch{return null}}function K(){try{localStorage.removeItem(t)}catch{}}let ae=!1,b=De();if(T.has(s)){let e=T.get(s);if(e==="off"||e==="0"||e==="false")K(),b=null,J("log","\u{1F50C} Stagepass disconnected.");else if(e){let n=e==="debug"?"debug":Y(e);if(n&&P(n)){try{localStorage.setItem(t,we(be(n,je)))}catch{}b=n,ae=!0,J("log",n==="debug"?"\u{1F50D} Stagepass debug mode enabled.":`\u{1F50C} Stagepass connected to: ${n}`)}else n&&J("warn",`Invalid domain: ${n}. Only .sp domains are allowed.`)}try{T.delete(s);let n=T.toString();history.replaceState({},"",f.pathname+(n?`?${n}`:"")+f.hash)}catch{}}b&&!P(b)&&(K(),b=null);let H=b==="debug";v=!!b,b&&!ae&&!H&&O("log",`\u{1F50C} Stagepass connected to: ${b}`);let ce=!!b,w=ce&&!H;y=w?Y(b):null;let le=w?Date.now():0,_=f.hostname,We=_==="localhost"||_==="127.0.0.1"||_.startsWith("localhost:")||_.startsWith("127.0.0.1:"),ue=w||We,de=ue?"local":_.endsWith(".webflow.io")||ne.includes(_.toLowerCase())?"staging":"production";if(V&&de==="production"&&!v)try{console.log=console.warn=console.error=console.info=console.debug=()=>{}}catch{}let fe={theme:new Set,session:new Set},Z=(e,n)=>fe[e].forEach(o=>{try{o(n)}catch{}}),R=Oe();try{let e=()=>Z("theme",{...Object.assign(R.theme,te())});["dark","light"].forEach(n=>{let o=matchMedia(`(prefers-color-scheme: ${n})`);o.addEventListener?o.addEventListener("change",e):o.addListener&&o.addListener(e)})}catch{}r.addEventListener("resize",()=>{let e=R.viewport;e.width=r.innerWidth||0,e.height=r.innerHeight||0,e.dpr=r.devicePixelRatio||1});let g=r.stagepass||{},He=Ce(h,W);if(g.vars=Object.freeze({isLocal:ue,env:de,domain:y||_,timestamp:le,version:h,client:R}),g.log=Te,g.warn=W,g.error=ie,g.resolveLocalUrl=e=>w&&y&&e?X(y,e,g.vars.timestamp||Date.now()):"",g.env=()=>Le(_,y,ne),g.is=e=>g.env()===e,g.can=e=>Re(R,e),g.client=e=>e==null||e===""?R:R[e],g.on=(e,n)=>{let o=fe[e];return!o||e!=="theme"&&e!=="session"?()=>{}:(o.add(n),()=>{o.delete(n)})},g.use=(e,n,o)=>He.use(e,n,o,g),r.stagepass=r.sp=g,globalThis.stagepass=globalThis.sp=g,A&&$e(A)&&A!=="sp"&&A!=="stagepass"&&[r,globalThis].forEach(e=>{Ae(e,A)&&(e[A]=g)}),ce)try{let e=Symbol.for("stagepass.flag.v2"),n=$&&$.src||"",o=/\/loader(?:\.min)?\.js$/i.test(n.split(/[?#]/)[0])?new URL("./",n).href:`https://cdn.jsdelivr.net/npm/@stagepass/loader@${h}/dist/`;Object.assign(x,{debug:H,domain:y,card:o+"flag-card.min.js",end:()=>{K(),v=!0,O("log","\u{1F50C} Stagepass disconnected."),Z("session",{active:!1,domain:null,swap:!1,debug:!1}),f.reload()}}),Object.defineProperty(g,e,{configurable:!0,value:a=>{delete g[e];try{C=a(x)}catch{}}}),r.addEventListener("error",a=>{let d=a.target,l=d&&d!==r&&(d.src||d.href);typeof l=="string"?ge.has(d)||I(1,"Failed to load "+l.split(/[?#]/)[0],l):/^Script error\.?$/.test(a.message||"")&&!a.filename?I(1,"Error in a cross-origin script (details only in DevTools console)","","","","","external"):I(1,a.message||"Script error",a.filename||"",a.lineno,a.colno,a.error&&a.error.stack||"")},!0),r.addEventListener("unhandledrejection",a=>B(1,"Unhandled rejection: ",[a.reason],null));let u=console;["warn","error"].forEach((a,d)=>{let l=u[a];typeof l=="function"&&(u[a]=function(...m){if(!j){j=!0;try{B(d,"",m,G(new Error().stack||"",2))}catch{}j=!1}return l.apply(this,m)})});let i=c.createElement("script");i.src=o+"flag.min.js",i.async=!0,i.onerror=()=>W("Stagepass flag could not be loaded: "+i.src),(c.head||c.documentElement).appendChild(i)}catch{}Z("session",{active:v,domain:b,swap:w,debug:H});function ze(e,n,o){if(w&&o&&y)return X(y,o,le);let u=e.getAttribute("data-stagepass-v")||Fe;return u?ve(n,"v",u):n}function Ue(e){try{let n=new URL(e).pathname.split("/");return n[n.length-1]||n[n.length-2]||null}catch{let o=e.match(/\/([^\/\?#]+)(?:\?|#|$)/);return o?o[1]:null}}let ge=new WeakSet,Q="";function Ve(e,n,o,u,i){let a={live:n,local:o,type:u?"js":"css",st:""},d=D(o);ge.add(e),x.f.push(a),e.addEventListener("load",()=>{a.st="ok",x.swapped++,se()}),e.addEventListener("error",()=>{let l=(S,p,z)=>{a.st=S,I(p,z,o)},m=r.fetch;if(typeof m!="function")return l("failed",1,`Failed to load ${d}`);m(o,{method:"HEAD",cache:"no-store"}).then(S=>l(S.ok?"failed":String(S.status),1,S.ok?`Failed to load ${d}`:`Local file not found (${S.status}): ${d}`),()=>m(o,{method:"HEAD",mode:"no-cors",cache:"no-store"}).then(()=>{if(!i)return l("failed",1,`Failed to load ${d}`);x.f.splice(x.f.indexOf(a),1),e.replaceWith(i(!1)),I(0,`Local server sends no CORS header for ${d}. Loaded without crossorigin, error details are limited`,o)},()=>l("failed",1,`Local server not reachable: ${d}. Run stagepass doctor`+(ee(Q)?". "+ee(Q):""))))})}let qe=["data-stagepass","data-stagepass-path","data-stagepass-cachebust","data-stagepass-v"];function pe(e,n,o,u){c.querySelectorAll(`${e}:not([data-stagepass-processed])`).forEach(i=>{try{i.setAttribute("data-stagepass-processed","true");let a=i.getAttribute("data-stagepass-path"),d=!!a,l=i.getAttribute(n);if(!l)return;if(!a&&w&&y&&(a=Ue(l)),w&&a&&!d&&v){let F=(u.get(a)||0)+1;u.set(a,F),F===2&&W(`Multiple assets resolve to local file "${a}" without data-stagepass-path. Set unique paths to avoid collisions.`)}let m=ze(i,l,a);if(!m)return;let S=w&&a&&y,p=o==="script",z=F=>{let L=c.createElement(o);F&&(L.crossOrigin="anonymous"),p?L.src=m:(L.rel="stylesheet",L.href=m);for(let M of Array.from(i.attributes))M.name!==n&&!qe.includes(M.name)&&(p||M.name!=="href")&&L.setAttribute(M.name,M.value);return p&&xe(L,i),S&&Ve(L,l,m,p,F?z:null),L},Je=z(!!S&&!i.hasAttribute("crossorigin"));i.parentNode?(i.parentNode.insertBefore(Je,i),i.remove()):ie(`${o} injection failed: No parent node`)}catch{}})}let Ge=()=>{try{let e=new Map;pe("script[data-stagepass]","data-src","script",e),pe('link[rel="stylesheet"][data-stagepass]',"data-href","link",e),C&&C()}catch{}},me=null,Be=()=>me=me||(w?Ee().then(e=>{Q=e}).catch(()=>{}):Promise.resolve()),he=()=>{Be().then(Ge)};he(),c.readyState==="loading"&&c.addEventListener("DOMContentLoaded",he)})();})();
1
+ var Stagepass=(()=>{function D(t){if(typeof t!="string"||!t)return!1;if(t==="debug"||t==="localhost")return!0;if(t.startsWith("localhost:")){let r=t.slice(10);return/^[0-9]{1,5}$/.test(r)&&Number(r)<=65535}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(t)}function Y(t){return t?t.replace(/^https?:\/\//i,"").replace(/\/$/,""):null}var Se="stagepass_domain",V=12;function ye(t,r=Date.now()){if(!t||!t.startsWith("{"))return null;try{let o=JSON.parse(t);return typeof o.domain!="string"||typeof o.expires!="number"||!Number.isFinite(o.expires)||!D(o.domain)||o.expires<=r?null:{domain:o.domain,expires:o.expires}}catch{return null}}function be(t,r=V,o=Date.now()){let c=Number.isFinite(r)&&r>0?r:V;return{domain:t,expires:o+c*60*60*1e3}}function we(t){return JSON.stringify(t)}function ke(t){if(t==null||t==="")return V;let r=Number(t);return!Number.isFinite(r)||r<=0?V:r}function ve(t,r,o){if(!t||typeof t!="string")return t;let c=encodeURIComponent(o),f=t.indexOf("#"),h=f>=0?t.slice(f):"",v=f>=0?t.slice(0,f):t,I=v.includes("?")?"&":"?";return`${v}${I}${encodeURIComponent(r)}=${c}${h}`}function X(t,r,o){let c=r.startsWith("/")?r.substring(1):r;return`https://${t}/${c}?_cb=${encodeURIComponent(String(o))}`}async function Ee(){let t=typeof navigator<"u"?navigator.permissions:void 0;if(!t||typeof t.query!="function")return"unknown";let r=["loopback-network","local-network-access"];for(let o of r)try{let c=await t.query({name:o}),f=c&&c.state;if(f==="granted"||f==="prompt"||f==="denied")return f}catch{}return"unknown"}function ee(t){return t==="prompt"?"Local network access is required. Allow local/loopback network access when Chrome prompts, then reload.":t==="denied"?"Local network access is blocked. Enable loopback/local network access for this site in Chrome settings, then reload.":null}function xe(t,r){let o=r.hasAttribute("async"),c=r.hasAttribute("defer");o?t.async=!0:(t.async=!1,c||(t.defer=!0))}function _e(t){return!t||typeof t!="string"?[]:t.split(",").map(r=>r.trim().toLowerCase()).filter(Boolean)}function Le(t,r,o=[]){if(r&&r.endsWith(".sp"))return"local";let c=(t||"").toLowerCase();return c.endsWith(".webflow.io")||o.some(f=>f===c)?"staging":"production"}function $e(t){return!t||typeof t!="string"?!1:/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)}function Ie(t,r){try{return typeof t[r]>"u"}catch{return!1}}var Ze=[["edge",/Edg\/(\d+)/],["opera",/OPR\/(\d+)/],["firefox",/Firefox\/(\d+)/],["chrome",/Chrome\/(\d+)/],["safari",/Version\/(\d+).+Safari\//]],Qe=[["android",/Android/i],["ios",/iPhone|iPad|iPod/i],["macos",/Mac OS X|Macintosh/i],["windows",/Windows NT/i],["linux",/Linux/i]];function Ye(t){for(let[r,o]of Ze){let c=t.match(o);if(c)return{family:r,major:Number(c[1]),userAgent:t}}return{family:"unknown",major:null,userAgent:t}}function Xe(t){let r=Qe.find(([,o])=>o.test(t));return{family:r?r[0]:"unknown"}}function et(t){let r="ontouchstart"in window||(navigator.maxTouchPoints||0)>0,o="desktop";return/iPad|Tablet/i.test(t)?o="tablet":/Mobi|Android.+Mobile|iPhone/i.test(t)?o="mobile":/Android/i.test(t)&&r&&(o="tablet"),{type:o,touch:r}}function te(){let t=null;try{let r=o=>matchMedia(`(prefers-color-scheme: ${o})`).matches;t=r("dark")?"dark":r("light")?"light":null}catch{}return{preferred:t||"no-preference",current:t||"unknown"}}function Ae(t){try{let r=window[t],o="__stagepass_test__";return r.setItem(o,"1"),r.removeItem(o),!0}catch{return!1}}function tt(){try{return typeof navigator<"u"&&"serviceWorker"in navigator}catch{return!1}}function Re(){let t=navigator.userAgent||"",r=null;try{r=Intl.DateTimeFormat().resolvedOptions().timeZone||null}catch{}return{theme:te(),browser:Ye(t),os:Xe(t),device:et(t),viewport:{width:window.innerWidth||0,height:window.innerHeight||0,dpr:window.devicePixelRatio||1},locale:{language:navigator.language||"unknown",timezone:r},capabilities:{cookiesEnabled:navigator.cookieEnabled===!0,localStorage:Ae("localStorage"),sessionStorage:Ae("sessionStorage")}}}function Oe(t,r){let o=t.capabilities;switch(r){case"localStorage":return o.localStorage===!0;case"sessionStorage":return o.sessionStorage===!0;case"cookies":return o.cookiesEnabled===!0;case"serviceWorker":return tt();default:return!1}}function Ne(t){if(!t||typeof t!="string")return null;let r=t.trim().match(/^(\d+)/);if(!r)return null;let o=Number(r[1]);return Number.isFinite(o)?o:null}function Ce(t,r){let o=Ne(t),c=new Map;function f(h,v,I,q){if(!h||typeof h!="string")return r("stagepass.use: invalid module name"),!1;let E=Ne(v);if(o==null||E==null)return r(`stagepass.use: cannot parse version for module "${h}"`),!1;if(E!==o)return r(`Module "${h}" major ${E} does not match loader major ${o}. Skipping.`),!1;try{return I(q),c.set(h,v),!0}catch(x){return r(`Module "${h}" failed to register:`,x),!1}}return{use:f,registered:c}}(function(){let t=Se,r="stagepass",o=window,c=document,f=location,h="2.3.1",v=/loader(?:\.min)?\.js/i;function I(e,n){if(typeof e!="string"||!(e=e.trim()))return null;try{let s=new URL(e,c.baseURI);return!/^https?:$/.test(s.protocol)||s.username||s.password?null:(s.search=s.hash="",n?new URL("./",s).href:s.href.replace(/\/?$/,"/"))}catch{return null}}function q(){try{if(c.currentScript instanceof HTMLScriptElement)return c.currentScript}catch{}try{let e=c.querySelectorAll('script[src*="loader"]');for(let n=e.length-1;n>=0;n--)if(v.test(e[n].src||""))return e[n]}catch{}return null}let E=q(),x=e=>E?E.getAttribute("data-stagepass-"+e):null,je=x("mute-console")==="true",Fe=ke(x("session-hours")),Me=x("version"),ne=_e(x("staging-hosts")),A=x("alias"),W=new URLSearchParams(f.search),k=!1,_={n:[0,0],m:[],f:[],swapped:0,v:h},j=null,se=()=>j&&j(),re=()=>new Date().toTimeString().slice(0,8),H=e=>(e||"").split(/[?#]/)[0].split("/").pop()||"",z=(e,n)=>e.length>n?e.slice(0,n)+"\u2026":e,oe=(e,n=0)=>{try{if(typeof e=="string")return n?JSON.stringify(e):e;if(e instanceof Error)return e.name+": "+e.message;if(!e||typeof e!="object")return String(e);if(e instanceof Node)return"<"+e.nodeName.toLowerCase()+">";let s=Array.isArray(e);if(n>2)return s?"[\u2026]":"{\u2026}";let u=Object.keys(e),i=u.slice(0,20).map(a=>(s?"":a+": ")+oe(e[a],n+1));return u.length>20&&i.push("\u2026"),z(s?"["+i.join(", ")+"]":"{"+i.join(", ")+"}",1e3)}catch{return"[unserializable]"}},B=(e,n=0)=>{let s=(e||"").split(`
2
+ `);for(let u=n;u<s.length;u++){let i=s[u].match(/([a-z][\w+.-]*:\/\/[^\s()]+?):(\d+):(\d+)/i);if(i&&!v.test(H(i[1])))return[i[1],i[2],i[3]]}return null},y=null,Pe=e=>e?y&&!e.indexOf(`https://${y}/`)?"local":"live":"external",R=(e,n,s="",u="",i="",a="",d)=>{_.n[e]++;let l=_.m,m={type:e?"error":"warn",time:re(),src:d||(s?Pe(s):""),file:H(s),url:s.split(/[?#]/)[0],line:u?String(u):"",col:i?String(i):"",text:z(n,500),stack:z(a,2e3),c:1},S=p=>p.type+p.text+p.url+p.line+p.col;for(let p=l.length-1;p>=0;p--)if(S(l[p])===S(m)){m.c=l[p].c+1,l.splice(p,1);break}l.push(m),l.length>50&&l.shift(),se()},G=(e,n,s,u)=>{let i=s.find(l=>l instanceof Error),a=i&&i.stack||"",d=B(a)||u;R(e,n+s.map(l=>oe(l)).join(" "),d?d[0]:"",d?d[1]:"",d?d[2]:"",a)},F=!1,Te=e=>{F=!0;try{e()}catch{}F=!1};function O(e,...n){if(!k)return;let s=B(new Error().stack||"",3);(e==="warn"||e==="error")&&G(e==="warn"?0:1,"",n,s),Te(()=>{let u=`[\u{1F3AB} ${re()}${s?" | "+H(s[0])+":"+s[1]:""}]`,i=console;e==="error"?i.log(`%c${u}`,"color:red;font-weight:bold",...n):i[e]?i[e](u,...n):i.log(u,e,...n)})}function De(...e){let n=e[0]==="warn"||e[0]==="error"?e.shift():"log";O(n,...e)}let N=(...e)=>O("warn",...e),ie=(...e)=>O("error",...e),J=(e,n)=>{let s=k;k=!0,O(e,n),k=s};function We(){try{let e=localStorage.getItem(t),n=ye(e);return!n&&e&&localStorage.removeItem(t),n?n.domain:null}catch{return null}}function K(){try{localStorage.removeItem(t)}catch{}}let ae=!1,b=We();if(W.has(r)){let e=W.get(r);if(e==="off"||e==="0"||e==="false")K(),b=null,J("log","\u{1F50C} Stagepass disconnected.");else if(e){let n=e==="debug"?"debug":Y(e);if(n&&D(n)){try{localStorage.setItem(t,we(be(n,Fe)))}catch{}b=n,ae=!0,J("log",n==="debug"?"\u{1F50D} Stagepass debug mode enabled.":`\u{1F50C} Stagepass connected to: ${n}`)}else n&&J("warn",`Invalid domain: ${n}. Only .sp domains are allowed.`)}try{W.delete(r);let n=W.toString();history.replaceState({},"",f.pathname+(n?`?${n}`:"")+f.hash)}catch{}}b&&!D(b)&&(K(),b=null);let M=b==="debug";k=!!b,b&&!ae&&!M&&O("log",`\u{1F50C} Stagepass connected to: ${b}`);let ce=!!b,w=ce&&!M;y=w?Y(b):null;let le=w?Date.now():0,L=f.hostname,He=L==="localhost"||L==="127.0.0.1"||L.startsWith("localhost:")||L.startsWith("127.0.0.1:"),ue=w||He,de=ue?"local":L.endsWith(".webflow.io")||ne.includes(L.toLowerCase())?"staging":"production";if(je&&de==="production"&&!k)try{console.log=console.warn=console.error=console.info=console.debug=()=>{}}catch{}let fe={theme:new Set,session:new Set},Z=(e,n)=>fe[e].forEach(s=>{try{s(n)}catch{}}),C=Re();try{let e=()=>Z("theme",{...Object.assign(C.theme,te())});["dark","light"].forEach(n=>{let s=matchMedia(`(prefers-color-scheme: ${n})`);s.addEventListener?s.addEventListener("change",e):s.addListener&&s.addListener(e)})}catch{}o.addEventListener("resize",()=>{let e=C.viewport;e.width=o.innerWidth||0,e.height=o.innerHeight||0,e.dpr=o.devicePixelRatio||1});let g=o.stagepass||{},ze=Ce(h,N);if(g.vars=Object.freeze({isLocal:ue,env:de,domain:y||L,timestamp:le,version:h,client:C}),g.log=De,g.warn=N,g.error=ie,g.resolveLocalUrl=e=>w&&y&&e?X(y,e,g.vars.timestamp||Date.now()):"",g.env=()=>Le(L,y,ne),g.is=e=>g.env()===e,g.can=e=>Oe(C,e),g.client=e=>e==null||e===""?C:C[e],g.on=(e,n)=>{let s=fe[e];return!s||e!=="theme"&&e!=="session"?()=>{}:(s.add(n),()=>{s.delete(n)})},g.use=(e,n,s)=>ze.use(e,n,s,g),o.stagepass=o.sp=g,globalThis.stagepass=globalThis.sp=g,A&&$e(A)&&A!=="sp"&&A!=="stagepass"&&[o,globalThis].forEach(e=>{Ie(e,A)&&(e[A]=g)}),ce)try{let e=Symbol.for("stagepass.flag.v2"),n=x("flag-base")??o.stagepassFlagBase,s=I(n,!1);n!=null&&!s&&N("Ignored flag base (http(s) or relative only): "+z(String(n),99)),s=s||I(E&&E.src||"",!0),s||(s=`https://cdn.jsdelivr.net/npm/@stagepass/loader@${h}/dist/`,M&&N("Loader URL unknown, flag loads from "+s+". Set data-stagepass-flag-base")),Object.assign(_,{debug:M,domain:y,card:s+"flag-card.min.js",end:()=>{K(),k=!0,O("log","\u{1F50C} Stagepass disconnected."),Z("session",{active:!1,domain:null,swap:!1,debug:!1}),f.reload()}}),Object.defineProperty(g,e,{configurable:!0,value:a=>{delete g[e];try{j=a(_)}catch{}}}),o.addEventListener("error",a=>{let d=a.target,l=d&&d!==o&&(d.src||d.href);typeof l=="string"?ge.has(d)||R(1,"Failed to load "+l.split(/[?#]/)[0],l):/^Script error\.?$/.test(a.message||"")&&!a.filename?R(1,"Error in a cross-origin script (details only in DevTools console)","","","","","external"):R(1,a.message||"Script error",a.filename||"",a.lineno,a.colno,a.error&&a.error.stack||"")},!0),o.addEventListener("unhandledrejection",a=>G(1,"Unhandled rejection: ",[a.reason],null));let u=console;["warn","error"].forEach((a,d)=>{let l=u[a];typeof l=="function"&&(u[a]=function(...m){if(!F){F=!0;try{G(d,"",m,B(new Error().stack||"",2))}catch{}F=!1}return l.apply(this,m)})});let i=c.createElement("script");i.src=s+"flag.min.js",i.async=!0,i.onerror=()=>N("Stagepass flag could not be loaded: "+i.src),(c.head||c.documentElement).appendChild(i)}catch{}Z("session",{active:k,domain:b,swap:w,debug:M});function Ue(e,n,s){if(w&&s&&y)return X(y,s,le);let u=e.getAttribute("data-stagepass-v")||Me;return u?ve(n,"v",u):n}function Ve(e){try{let n=new URL(e).pathname.split("/");return n[n.length-1]||n[n.length-2]||null}catch{let s=e.match(/\/([^\/\?#]+)(?:\?|#|$)/);return s?s[1]:null}}let ge=new WeakSet,Q="";function qe(e,n,s,u,i){let a={live:n,local:s,type:u?"js":"css",st:""},d=H(s);ge.add(e),_.f.push(a),e.addEventListener("load",()=>{a.st="ok",_.swapped++,se()}),e.addEventListener("error",()=>{let l=(S,p,U)=>{a.st=S,R(p,U,s)},m=o.fetch;if(typeof m!="function")return l("failed",1,`Failed to load ${d}`);m(s,{method:"HEAD",cache:"no-store"}).then(S=>l(S.ok?"failed":String(S.status),1,S.ok?`Failed to load ${d}`:`Local file not found (${S.status}): ${d}`),()=>m(s,{method:"HEAD",mode:"no-cors",cache:"no-store"}).then(()=>{if(!i)return l("failed",1,`Failed to load ${d}`);_.f.splice(_.f.indexOf(a),1),e.replaceWith(i(!1)),R(0,`Local server sends no CORS header for ${d}. Loaded without crossorigin, error details are limited`,s)},()=>l("failed",1,`Local server not reachable: ${d}. Run stagepass doctor`+(ee(Q)?". "+ee(Q):""))))})}let Be=["data-stagepass","data-stagepass-path","data-stagepass-cachebust","data-stagepass-v"];function pe(e,n,s,u){c.querySelectorAll(`${e}:not([data-stagepass-processed])`).forEach(i=>{try{i.setAttribute("data-stagepass-processed","true");let a=i.getAttribute("data-stagepass-path"),d=!!a,l=i.getAttribute(n);if(!l)return;if(!a&&w&&y&&(a=Ve(l)),w&&a&&!d&&k){let P=(u.get(a)||0)+1;u.set(a,P),P===2&&N(`Multiple assets resolve to local file "${a}" without data-stagepass-path. Set unique paths to avoid collisions.`)}let m=Ue(i,l,a);if(!m)return;let S=w&&a&&y,p=s==="script",U=P=>{let $=c.createElement(s);P&&($.crossOrigin="anonymous"),p?$.src=m:($.rel="stylesheet",$.href=m);for(let T of Array.from(i.attributes))T.name!==n&&!Be.includes(T.name)&&(p||T.name!=="href")&&$.setAttribute(T.name,T.value);return p&&xe($,i),S&&qe($,l,m,p,P?U:null),$},Ke=U(!!S&&!i.hasAttribute("crossorigin"));i.parentNode?(i.parentNode.insertBefore(Ke,i),i.remove()):ie(`${s} injection failed: No parent node`)}catch{}})}let Ge=()=>{try{let e=new Map;pe("script[data-stagepass]","data-src","script",e),pe('link[rel="stylesheet"][data-stagepass]',"data-href","link",e),j&&j()}catch{}},me=null,Je=()=>me=me||(w?Ee().then(e=>{Q=e}).catch(()=>{}):Promise.resolve()),he=()=>{Je().then(Ge)};he(),c.readyState==="loading"&&c.addEventListener("DOMContentLoaded",he)})();})();
package/global.d.ts CHANGED
@@ -161,6 +161,8 @@ declare global {
161
161
  interface Window {
162
162
  stagepass: StagepassAPI;
163
163
  sp: StagepassAPI;
164
+ /** Optional folder for flag.min.js / flag-card.min.js when the loader is inlined or bundled (2.3.1+). http(s) or relative only. */
165
+ stagepassFlagBase?: string;
164
166
  }
165
167
 
166
168
  // Global aliases (same object as window.stagepass)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stagepass/loader",
3
- "version": "2.3.0",
3
+ "version": "2.3.1",
4
4
  "description": "Universal loader for Stagepass - injects local files into Webflow projects",
5
5
  "main": "dist/loader.min.js",
6
6
  "types": "global.d.ts",