@ovineko/spa-guard-node 0.0.1-alpha-30 → 0.0.2-alpha-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.
@@ -1 +1 @@
1
- var e=Object.defineProperty,t="@ovineko/spa-guard",r="__SPA_GUARD_OPTIONS__",a=Symbol.for(t+":event-subscribers"),n=Symbol.for(t+":internal-config"),o=Symbol.for(t+":initialized"),i=Symbol.for(t+":logger"),l="spaGuardRetryId",s="spaGuardRetryAttempt",d="spaGuardCacheBust",c=(Symbol.for(t+":version-check-state"),Symbol.for(t+":in-memory-last-reload")),u=Symbol.for(t+":static-asset-recovery"),m=(Symbol.for(t+":spinner-state"),Symbol.for(t+":fallback-mode"));globalThis.window&&!globalThis.window[a]&&(globalThis.window[a]=new Set),globalThis.window&&!globalThis.window[n]&&(globalThis.window[n]={defaultRetryEnabled:!0,initialized:!1});var g=globalThis.window?.[a]??new Set,y=globalThis.window?.[n]??{defaultRetryEnabled:!0,initialized:!1},f=()=>globalThis.window?.[i],p=(e,t)=>{t?.silent||f()?.logEvent(e),g.forEach(t=>{try{t(e)}catch{}})};((t,r)=>{for(var a in r)e(t,a,{get:r[a],enumerable:!0})})({},{getOptions:()=>w,optionsWindowKey:()=>r});var h={checkVersion:{cache:"no-store",interval:3e5,mode:"html",onUpdate:"reload"},enableRetryReset:!0,errors:{forceRetry:[],ignore:[]},handleUnhandledRejections:{retry:!0,sendBeacon:!0},html:{fallback:{content:'<style>.spa-guard-error-id:has(.spa-guard-retry-id:empty){display:none}.spa-guard-error-id{font-family:ui-monospace,SFMono-Regular,Consolas,"Liberation Mono",Menlo,monospace}</style><div style="display:flex;align-items:center;justify-content:center;min-height:100vh;padding:2rem;font-family:system-ui,sans-serif"><div style="text-align:center;max-width:480px"><div style="margin-bottom:1.5rem"><svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" fill="none" viewBox="0 0 24 24" stroke="#b0b0b0" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg></div><h1 data-spa-guard-content="heading" style="font-size:1.375rem;font-weight:600;margin:0 0 .5rem;color:#1a1a1a;line-height:1.3">Something went wrong</h1><p data-spa-guard-content="message" style="max-width:600px;margin:0 auto 1.5rem;color:#666;font-size:.9375rem;line-height:1.5">Please refresh the page to continue.</p><div style="display:flex;gap:.5rem;justify-content:center;flex-wrap:wrap"><button data-spa-guard-action="try-again" type="button" style="display:none;padding:.5rem 1.25rem;font-size:.875rem;font-family:inherit;border-radius:6px;border:1px solid #d0d0d0;background:#fff;color:#333;cursor:pointer;line-height:1.5">Try again</button> <button data-spa-guard-action="reload" type="button" style="padding:.5rem 1.25rem;font-size:.875rem;font-family:inherit;border-radius:6px;border:1px solid transparent;background:#111;color:#fff;cursor:pointer;line-height:1.5">Reload page</button></div><p class="spa-guard-error-id" style="margin-top:1.5rem;font-size:.6875rem;color:#999">Error ID: <span class="spa-guard-retry-id"></span></p></div></div>',selector:"body"},loading:{content:'<div style="display:flex;align-items:center;justify-content:center;min-height:100vh;padding:2rem;font-family:system-ui,sans-serif"><div style="text-align:center"><div data-spa-guard-spinner style="margin-bottom:1.25rem"></div><h2 data-spa-guard-content="loading" style="font-size:1.125rem;font-weight:600;margin:0 0 .25rem;color:#1a1a1a">Loading...</h2><p data-spa-guard-section="retrying" style="display:none;font-size:.8125rem;color:#999;margin:.5rem 0 0"><span data-spa-guard-content="retrying">Retry attempt</span> <span data-spa-guard-content="attempt"></span></p></div></div>'},spinner:{background:"#fff",disabled:!1}},lazyRetry:{callReloadOnFailure:!0,retryDelays:[1e3,2e3]},minTimeBetweenResets:5e3,reloadDelays:[1e3,2e3,5e3],staticAssets:{autoRecover:!0,recoveryDelay:500},useRetryId:!0},w=()=>{let e=globalThis.window?.[r];return{...h,...e,checkVersion:{...h.checkVersion,...e?.checkVersion},errors:{...h.errors,...e?.errors},handleUnhandledRejections:{...h.handleUnhandledRejections,...e?.handleUnhandledRejections},html:{fallback:{...h.html?.fallback,...e?.html?.fallback},loading:{...h.html?.loading,...e?.html?.loading},spinner:{...h.html?.spinner,...e?.html?.spinner}},lazyRetry:{...h.lazyRetry,...e?.lazyRetry},reportBeacon:{...h.reportBeacon,...e?.reportBeacon},staticAssets:{...h.staticAssets,...e?.staticAssets}}},b="__SPA_GUARD_FORCE_RETRY__",v=()=>{try{let e=new URLSearchParams(globalThis.window.location.search),t=e.get(l),r=e.get(s);if(t&&r){if(!/^\d+$/.test(r))return null;let e=parseInt(r,10);return Number.isNaN(e)||!Number.isFinite(e)||e<0?null:{retryAttempt:e,retryId:t}}return null}catch{return null}},T=()=>{if(typeof crypto<"u"&&crypto.randomUUID)return crypto.randomUUID();if(typeof crypto<"u"&&crypto.getRandomValues){let e=new Uint32Array(2);return crypto.getRandomValues(e),`${Date.now()}-${e[0].toString(36)}-${e[1].toString(36)}`}return`${Date.now()}-${Math.random().toString(36).slice(2,15)}`},S=()=>{let e=v();return e?{retryAttempt:e.retryAttempt,retryId:e.retryId}:{}},R="__spa_guard_last_reload_timestamp__",I="__spa_guard_last_retry_reset__";globalThis.window&&!globalThis.window[c]&&(globalThis.window[c]={resetInfo:null,storage:null});var k=()=>{let e=globalThis.window;return e?e[c]??(e[c]={resetInfo:null,storage:null}):{resetInfo:null,storage:null}},A=()=>{try{return void 0!==globalThis.window&&typeof sessionStorage<"u"}catch{return!1}},_=()=>{if(A())try{let e=sessionStorage.getItem(R);if(e)return JSON.parse(e)}catch{try{sessionStorage.removeItem(R)}catch{}return k().storage}return k().storage},E=e=>{let t=(w().errors?.ignore??[]).filter(e=>""!==e);return 0!==t.length&&e.filter(e=>"string"==typeof e).some(e=>t.some(t=>e.includes(t)))},N=e=>{let t=[...w().errors?.forceRetry??[],b].filter(e=>""!==e);return e.filter(e=>"string"==typeof e).some(e=>t.some(t=>e.includes(t)))},x=e=>{if((e=>E([e.errorMessage,e.eventMessage]))(e))return;let t=w();if(!t.reportBeacon?.endpoint)return void f()?.noBeaconEndpoint();let r=t.appName?{...e,appName:t.appName}:e,a=JSON.stringify(r);("function"!=typeof globalThis.window?.navigator?.sendBeacon||!globalThis.window.navigator.sendBeacon(t.reportBeacon.endpoint,a))&&"function"==typeof fetch&&fetch(t.reportBeacon.endpoint,{body:a,keepalive:!0,method:"POST"}).catch(e=>{f()?.beaconSendFailed(e)})},D=Symbol.for(t+":retry-orchestrator"),L=e=>{if(void 0===globalThis.window)return;let t=globalThis.window;t[D]||(t[D]={attempt:0,lastSource:void 0,lastTriggerTime:void 0,phase:"idle",retryId:null,timer:null}),Object.assign(t[D],e)},z=(e={})=>{let t=(()=>{if(void 0===globalThis.window)return{attempt:0,lastSource:void 0,lastTriggerTime:void 0,phase:"idle",retryId:null,timer:null};let e=globalThis.window;return e[D]||(e[D]={attempt:0,lastSource:void 0,lastTriggerTime:void 0,phase:"idle",retryId:null,timer:null}),e[D]})();if("fallback"===t.phase||void 0!==globalThis.window&&!0===globalThis.window[m])return f()?.fallbackAlreadyShown(e.error),{status:"fallback"};if("scheduled"===t.phase)return f()?.reloadAlreadyScheduled(e.error),{reason:"already-scheduled",status:"deduped"};if(!y.defaultRetryEnabled)return{status:"retry-disabled"};L({lastSource:e.source,lastTriggerTime:Date.now(),phase:"scheduled"});try{let t=w(),r=t.reloadDelays??[1e3,2e3,5e3],a=t.useRetryId??!0,n=t.enableRetryReset??!0,o=t.minTimeBetweenResets??5e3,i=(()=>{try{let e=new URLSearchParams(globalThis.window.location.search).get(s);if(!e||!/^\d+$/.test(e))return null;let t=parseInt(e,10);return Number.isNaN(t)||!Number.isFinite(t)||t<0?null:t}catch{return null}})(),c=(()=>{try{return new URLSearchParams(globalThis.window.location.search).get(l)}catch{return null}})(),u=i??0,g=a&&c?c:T();if(f()?.retryCycleStarting(g,u),n&&c&&null!==i&&i>0&&((e,t,r=5e3)=>{if(0===e.retryAttempt)return!1;let a=_();if(!a||a.retryId!==e.retryId)return!1;let n=(()=>{if(A())try{let e=sessionStorage.getItem(I);if(e)return JSON.parse(e)}catch{try{sessionStorage.removeItem(I)}catch{}return k().resetInfo}return k().resetInfo})();return!(n&&Date.now()-n.timestamp<r)&&Date.now()-a.timestamp>(t[a.attemptNumber-1]??1e3)+3e4})({retryAttempt:i,retryId:c},r,o)){let t=_(),r=t?Date.now()-t.timestamp:0;(()=>{try{let e=new URL(globalThis.window.location.href);e.searchParams.delete(l),e.searchParams.delete(s),e.searchParams.delete(d),globalThis.window.history.replaceState(null,"",e.toString())}catch(e){f()?.error("clearRetryFromUrl failed",e)}})(),(()=>{if(A())try{sessionStorage.removeItem(R)}catch{}k().storage=null})(),(e=>{let t={previousRetryId:e,timestamp:Date.now()};if(A())try{sessionStorage.setItem(I,JSON.stringify(t))}catch{k().resetInfo=t}else k().resetInfo=t})(c);let a=e.error+"";p({name:"retry-reset",previousAttempt:i,previousRetryId:c,timeSinceReload:r},{silent:E([a])}),u=0,g=T()}if(p({error:e.error,isRetrying:u<r.length,name:"chunk-error"}),u>=r.length){let t=e.error+"";return p({finalAttempt:u,name:"retry-exhausted",retryId:g},{silent:E([t])}),x({errorMessage:"Exceeded maximum reload attempts",eventName:"chunk_error_max_reloads",retryAttempt:u,retryId:g,serialized:JSON.stringify({error:e.error+"",retryAttempt:u,retryId:g})}),L({attempt:u,phase:"fallback",retryId:g}),void 0!==globalThis.window&&(globalThis.window[m]=!0),(()=>{let e=w(),t=e.html?.fallback?.content,r=e.html?.fallback?.selector??"body";if(!t)return f()?.noFallbackConfigured(),void p({name:"fallback-ui-not-rendered",reason:"no-html-configured"});try{let e=document.querySelector(r);if(!e)return f()?.fallbackTargetNotFound(r),void p({name:"fallback-ui-not-rendered",reason:"target-not-found",selector:r});let a=document.createElement("div");a.innerHTML=t;let n=function(){try{let e=document.querySelector('meta[name="spa-guard-i18n"]');if(!e)return null;let t=e.getAttribute("content");return t?JSON.parse(t):null}catch{return null}}();n&&function(e,t){let r=e.querySelectorAll("[data-spa-guard-content]");for(let e of r){let r=e.dataset.spaGuardContent;if(r&&r in t){let a=t[r];"string"==typeof a&&(e.textContent=a)}}let a=e.querySelectorAll("[data-spa-guard-action]");for(let e of a){let r=e.dataset.spaGuardAction,a="try-again"===r?"tryAgain":r;if(a&&a in t){let r=t[a];"string"==typeof r&&(e.textContent=r)}}if(t.rtl)for(let t of e.children)t instanceof HTMLElement&&"STYLE"!==t.tagName&&(t.style.direction="rtl")}(a,n),e.innerHTML=a.innerHTML;let o=e.querySelector('[data-spa-guard-action="reload"]');o&&o.addEventListener("click",()=>globalThis.window.location.reload());let i=v();if(i){let e=document.getElementsByClassName("spa-guard-retry-id");for(let t of e)t.textContent=i.retryId}p({name:"fallback-ui-shown"})}catch(e){f()?.fallbackInjectFailed(e)}})(),{status:"fallback"}}let y=u+1,h=r[u]??1e3,b=e.error+"";p({attempt:y,delay:h,name:"retry-attempt",retryId:g},{silent:E([b])}),f()?.retrySchedulingReload(g,y,h),L({attempt:y,retryId:g});let S=setTimeout(()=>{try{a&&n&&((e,t)=>{let r={attemptNumber:t,retryId:e,timestamp:Date.now()};if(A())try{sessionStorage.setItem(R,JSON.stringify(r))}catch{k().storage=r}else k().storage=r})(g,y);let t=((e,t,r,a=!0)=>{let n=new URL(globalThis.window.location.href);return a&&n.searchParams.set(l,e),n.searchParams.set(s,t+""),r&&n.searchParams.set(d,Date.now()+""),n.toString()})(g,y,e.cacheBust,a);globalThis.window.location.href=t}catch(e){f()?.error("triggerRetry navigation failed",e),L({phase:"idle"})}},h);return L({timer:S}),{status:"accepted"}}catch(e){return f()?.error("triggerRetry internal error",e),L({lastSource:void 0,lastTriggerTime:void 0,phase:"idle"}),{reason:"internal-error",status:"deduped"}}},U=e=>{let t=j(e);return!!t&&[/Failed to fetch dynamically imported module/i,/Importing a module script failed/i,/error loading dynamically imported module/i,/Unable to preload CSS/i,/Loading chunk \d+ failed/i,/Loading CSS chunk \d+ failed/i,/ChunkLoadError/i].some(e=>e.test(t))},j=e=>e instanceof Error?e.message:"string"==typeof e?e:e&&"object"==typeof e&&"message"in e?e.message+"":e&&"object"==typeof e&&"reason"in e?j(e.reason):null,B=/[-._][a-zA-Z0-9]{6,}\.(js|mjs|css)$/i,M=e=>{try{let t=new URL(e).pathname;return B.test(t)}catch{return B.test(e)}},O=()=>void 0===globalThis.window?{failedAssets:new Set,recoveryTimer:null}:(globalThis.window[u]||(globalThis.window[u]={failedAssets:new Set,recoveryTimer:null}),globalThis.window[u]);(()=>{if(y.initialized)return;y.initialized=!0,void 0!==globalThis.window&&(globalThis.window[o]=!0);let e=w(),t=globalThis.window.addEventListener.bind(globalThis.window);t("error",t=>{let r=(e=>{let t=e.target;return t instanceof HTMLScriptElement?t.src:t instanceof HTMLLinkElement?t.href:""})(t);if((e=>{let t=e.target;return t instanceof HTMLScriptElement?M(t.src):t instanceof HTMLLinkElement&&M(t.href)})(t)&&(void 0!==(a=r)?(e=>{if(typeof performance>"u"||"function"!=typeof performance.getEntriesByName)return!0;let t=performance.getEntriesByName(e,"resource");if(0===t.length)return!0;let r=t.at(-1);return r.responseStatus>=400||0===r.transferSize&&0===r.decodedBodySize})(a):(typeof performance>"u"?0:performance.now())>3e4)){if(E([r,t.message]))return;return t.preventDefault(),p({name:"static-asset-load-failed",url:r}),void(!1!==e.staticAssets?.autoRecover&&(e=>{if(void 0===globalThis.window)return;let t=O();if(t.failedAssets.add(e),null!==t.recoveryTimer)return;let r=w().staticAssets?.recoveryDelay??500;t.recoveryTimer=setTimeout(()=>{let e=O();e.recoveryTimer=null;let t=[...e.failedAssets];e.failedAssets=new Set;let r=Error("Static asset load failed: "+t.join(", "));z({cacheBust:!0,error:r,source:"static-asset-error"})},r)})(r))}var a;if(!E([t.message]))return f()?.capturedError("error",t),U(t)?(t.preventDefault(),void z({error:t.error??t,source:"chunk-error"})):N([t.message])?(t.preventDefault(),void z({error:t.error??t,source:"force-retry"})):void x({errorMessage:t.message,eventName:"error",serialized:"",...S()})},!0),t("unhandledrejection",t=>{let r=t.reason+"";if(E([r]))return;if(f()?.capturedError("unhandledrejection",t),U(t.reason))return t.preventDefault(),void z({error:t.reason,source:"chunk-error"});if(N([r]))return t.preventDefault(),void z({error:t.reason,source:"force-retry"});let a=e.handleUnhandledRejections;!1!==a?.sendBeacon&&x({errorMessage:r,eventName:"unhandledrejection",serialized:"",...S()}),!1!==a?.retry&&(t.preventDefault(),z({error:t.reason,source:"unhandled-rejection"}))}),t("securitypolicyviolation",e=>{let t=`${e.violatedDirective}: ${e.blockedURI}`;E([t])||(f()?.capturedError("csp",e.blockedURI,e.violatedDirective),x({eventMessage:t,eventName:"securitypolicyviolation",serialized:"",...S()}))}),t("vite:preloadError",e=>{let t=e?.payload;E([t?.message||e?.message])||(f()?.capturedError("vite:preloadError",e),e.preventDefault(),z({error:t??e,source:"vite:preloadError"}))})})();
1
+ var e=Object.defineProperty,t="@ovineko/spa-guard",r="__SPA_GUARD_OPTIONS__",a=Symbol.for(t+":event-subscribers"),n=Symbol.for(t+":internal-config"),o=Symbol.for(t+":initialized"),i=Symbol.for(t+":logger"),l="spaGuardRetryId",s="spaGuardRetryAttempt",d="spaGuardCacheBust",c=(Symbol.for(t+":version-check-state"),Symbol.for(t+":in-memory-last-reload")),u=Symbol.for(t+":static-asset-recovery"),m=(Symbol.for(t+":spinner-state"),Symbol.for(t+":fallback-mode"));globalThis.window&&!globalThis.window[a]&&(globalThis.window[a]=new Set),globalThis.window&&!globalThis.window[n]&&(globalThis.window[n]={defaultRetryEnabled:!0,initialized:!1});var y=globalThis.window?.[a]??new Set,g=globalThis.window?.[n]??{defaultRetryEnabled:!0,initialized:!1},f=()=>globalThis.window?.[i],p=(e,t)=>{t?.silent||f()?.logEvent(e),y.forEach(t=>{try{t(e)}catch{}})};function h(e,t){let r=e.querySelectorAll("[data-spa-guard-content]");for(let e of r){let r=e.dataset.spaGuardContent;if(r&&r in t){let a=t[r];"string"==typeof a&&(e.textContent=a)}}let a=e.querySelectorAll("[data-spa-guard-action]");for(let e of a){let r=e.dataset.spaGuardAction,a="try-again"===r?"tryAgain":r;if(a&&a in t){let r=t[a];"string"==typeof r&&(e.textContent=r)}}if(t.rtl)for(let t of e.children)t instanceof HTMLElement&&"STYLE"!==t.tagName&&(t.style.direction="rtl")}function w(){try{let e=document.querySelector('meta[name="spa-guard-i18n"]');if(!e)return null;let t=e.getAttribute("content");return t?JSON.parse(t):null}catch{return null}}((t,r)=>{for(var a in r)e(t,a,{get:r[a],enumerable:!0})})({},{getOptions:()=>v,optionsWindowKey:()=>r});var b={checkVersion:{cache:"no-store",interval:3e5,mode:"html",onUpdate:"reload"},enableRetryReset:!0,errors:{forceRetry:[],ignore:[]},handleUnhandledRejections:{retry:!0,sendBeacon:!0},html:{fallback:{content:'<style>.spa-guard-error-id:has(.spa-guard-retry-id:empty){display:none}.spa-guard-error-id{font-family:ui-monospace,SFMono-Regular,Consolas,"Liberation Mono",Menlo,monospace}</style><div style="display:flex;align-items:center;justify-content:center;min-height:100vh;padding:2rem;font-family:system-ui,sans-serif"><div style="text-align:center;max-width:480px"><div style="margin-bottom:1.5rem"><svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" fill="none" viewBox="0 0 24 24" stroke="#b0b0b0" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg></div><h1 data-spa-guard-content="heading" style="font-size:1.375rem;font-weight:600;margin:0 0 .5rem;color:#1a1a1a;line-height:1.3">Something went wrong</h1><p data-spa-guard-content="message" style="max-width:600px;margin:0 auto 1.5rem;color:#666;font-size:.9375rem;line-height:1.5">Please refresh the page to continue.</p><div style="display:flex;gap:.5rem;justify-content:center;flex-wrap:wrap"><button data-spa-guard-action="try-again" type="button" style="display:none;padding:.5rem 1.25rem;font-size:.875rem;font-family:inherit;border-radius:6px;border:1px solid #d0d0d0;background:#fff;color:#333;cursor:pointer;line-height:1.5">Try again</button> <button data-spa-guard-action="reload" type="button" style="padding:.5rem 1.25rem;font-size:.875rem;font-family:inherit;border-radius:6px;border:1px solid transparent;background:#111;color:#fff;cursor:pointer;line-height:1.5">Reload page</button></div><p class="spa-guard-error-id" style="margin-top:1.5rem;font-size:.6875rem;color:#999">Error ID: <span class="spa-guard-retry-id"></span></p></div></div>',selector:"body"},loading:{content:'<div style="display:flex;align-items:center;justify-content:center;min-height:100vh;padding:2rem;font-family:system-ui,sans-serif"><div style="text-align:center"><div data-spa-guard-spinner style="margin-bottom:1.25rem"></div><h2 data-spa-guard-content="loading" style="font-size:1.125rem;font-weight:600;margin:0 0 .25rem;color:#1a1a1a">Loading...</h2><p data-spa-guard-section="retrying" style="display:none;font-size:.8125rem;color:#999;margin:.5rem 0 0"><span data-spa-guard-content="retrying">Retry attempt</span> <span data-spa-guard-content="attempt"></span></p></div></div>'},spinner:{background:"#fff",disabled:!1}},lazyRetry:{callReloadOnFailure:!0,retryDelays:[1e3,2e3]},minTimeBetweenResets:5e3,reloadDelays:[1e3,2e3,5e3],staticAssets:{autoRecover:!0,recoveryDelay:500},useRetryId:!0},v=()=>{let e=globalThis.window?.[r];return{...b,...e,checkVersion:{...b.checkVersion,...e?.checkVersion},errors:{...b.errors,...e?.errors},handleUnhandledRejections:{...b.handleUnhandledRejections,...e?.handleUnhandledRejections},html:{fallback:{...b.html?.fallback,...e?.html?.fallback},loading:{...b.html?.loading,...e?.html?.loading},spinner:{...b.html?.spinner,...e?.html?.spinner}},lazyRetry:{...b.lazyRetry,...e?.lazyRetry},reportBeacon:{...b.reportBeacon,...e?.reportBeacon},staticAssets:{...b.staticAssets,...e?.staticAssets}}},T="__SPA_GUARD_FORCE_RETRY__",S=()=>{try{let e=new URLSearchParams(globalThis.window.location.search),t=e.get(l),r=e.get(s);if(t&&r){if(!/^\d+$/.test(r))return null;let e=parseInt(r,10);return Number.isNaN(e)||!Number.isFinite(e)||e<0?null:{retryAttempt:e,retryId:t}}return null}catch{return null}},R=()=>{if(typeof crypto<"u"&&crypto.randomUUID)return crypto.randomUUID();if(typeof crypto<"u"&&crypto.getRandomValues){let e=new Uint32Array(2);return crypto.getRandomValues(e),`${Date.now()}-${e[0].toString(36)}-${e[1].toString(36)}`}return`${Date.now()}-${Math.random().toString(36).slice(2,15)}`},I=()=>{let e=S();return e?{retryAttempt:e.retryAttempt,retryId:e.retryId}:{}},k="__spa_guard_last_reload_timestamp__",A="__spa_guard_last_retry_reset__";globalThis.window&&!globalThis.window[c]&&(globalThis.window[c]={resetInfo:null,storage:null});var E=()=>{let e=globalThis.window;return e?e[c]??(e[c]={resetInfo:null,storage:null}):{resetInfo:null,storage:null}},_=()=>{try{return void 0!==globalThis.window&&typeof sessionStorage<"u"}catch{return!1}},N=()=>{if(_())try{let e=sessionStorage.getItem(k);if(e)return JSON.parse(e)}catch{try{sessionStorage.removeItem(k)}catch{}return E().storage}return E().storage},x=e=>{let t=(v().errors?.ignore??[]).filter(e=>""!==e);return 0!==t.length&&e.filter(e=>"string"==typeof e).some(e=>t.some(t=>e.includes(t)))},D=e=>{let t=[...v().errors?.forceRetry??[],T].filter(e=>""!==e);return e.filter(e=>"string"==typeof e).some(e=>t.some(t=>e.includes(t)))},L=e=>{if((e=>x([e.errorMessage,e.eventMessage]))(e))return;let t=v();if(!t.reportBeacon?.endpoint)return void f()?.noBeaconEndpoint();let r=t.appName?{...e,appName:t.appName}:e,a=JSON.stringify(r);("function"!=typeof globalThis.window?.navigator?.sendBeacon||!globalThis.window.navigator.sendBeacon(t.reportBeacon.endpoint,a))&&"function"==typeof fetch&&fetch(t.reportBeacon.endpoint,{body:a,keepalive:!0,method:"POST"}).catch(e=>{f()?.beaconSendFailed(e)})},z=Symbol.for(t+":retry-orchestrator"),U=e=>{if(void 0===globalThis.window)return;let t=globalThis.window;t[z]||(t[z]={attempt:0,lastSource:void 0,lastTriggerTime:void 0,phase:"idle",retryId:null,timer:null}),Object.assign(t[z],e)},M=()=>{try{let e=new URL(globalThis.window.location.href);e.searchParams.delete(l),e.searchParams.delete(s),e.searchParams.delete(d),globalThis.window.history.replaceState(null,"",e.toString())}catch(e){f()?.error("clearRetryFromUrl failed",e)}},j=(e={})=>{let t=(()=>{if(void 0===globalThis.window)return{attempt:0,lastSource:void 0,lastTriggerTime:void 0,phase:"idle",retryId:null,timer:null};let e=globalThis.window;return e[z]||(e[z]={attempt:0,lastSource:void 0,lastTriggerTime:void 0,phase:"idle",retryId:null,timer:null}),e[z]})();if("fallback"===t.phase||void 0!==globalThis.window&&!0===globalThis.window[m])return f()?.fallbackAlreadyShown(e.error),{status:"fallback"};if("scheduled"===t.phase)return f()?.reloadAlreadyScheduled(e.error),{reason:"already-scheduled",status:"deduped"};if(!g.defaultRetryEnabled)return{status:"retry-disabled"};U({lastSource:e.source,lastTriggerTime:Date.now(),phase:"scheduled"});try{let t=v(),r=t.reloadDelays??[1e3,2e3,5e3],a=t.useRetryId??!0,n=t.enableRetryReset??!0,o=t.minTimeBetweenResets??5e3,i=(()=>{try{let e=new URLSearchParams(globalThis.window.location.search).get(s);if(!e||!/^\d+$/.test(e))return null;let t=parseInt(e,10);return Number.isNaN(t)||!Number.isFinite(t)||t<0?null:t}catch{return null}})(),c=(()=>{try{return new URLSearchParams(globalThis.window.location.search).get(l)}catch{return null}})(),u=i??0,y=a&&c?c:R();if(f()?.retryCycleStarting(y,u),n&&c&&null!==i&&i>0&&((e,t,r=5e3)=>{if(0===e.retryAttempt)return!1;let a=N();if(!a||a.retryId!==e.retryId)return!1;let n=(()=>{if(_())try{let e=sessionStorage.getItem(A);if(e)return JSON.parse(e)}catch{try{sessionStorage.removeItem(A)}catch{}return E().resetInfo}return E().resetInfo})();return!(n&&Date.now()-n.timestamp<r)&&Date.now()-a.timestamp>(t[a.attemptNumber-1]??1e3)+3e4})({retryAttempt:i,retryId:c},r,o)){let t=N(),r=t?Date.now()-t.timestamp:0;M(),(()=>{if(_())try{sessionStorage.removeItem(k)}catch{}E().storage=null})(),(e=>{let t={previousRetryId:e,timestamp:Date.now()};if(_())try{sessionStorage.setItem(A,JSON.stringify(t))}catch{E().resetInfo=t}else E().resetInfo=t})(c);let a=e.error+"";p({name:"retry-reset",previousAttempt:i,previousRetryId:c,timeSinceReload:r},{silent:x([a])}),u=0,y=R()}if(p({error:e.error,isRetrying:u<r.length,name:"chunk-error"}),u>=r.length){let t=e.error+"";return p({finalAttempt:u,name:"retry-exhausted",retryId:y},{silent:x([t])}),L({errorMessage:"Exceeded maximum reload attempts",eventName:"chunk_error_max_reloads",retryAttempt:u,retryId:y,serialized:JSON.stringify({error:e.error+"",retryAttempt:u,retryId:y})}),U({attempt:u,phase:"fallback",retryId:y}),void 0!==globalThis.window&&(globalThis.window[m]=!0),M(),(e=>{let t=v(),r=t.html?.fallback?.content,a=t.html?.fallback?.selector??"body";if(!r)return f()?.noFallbackConfigured(),void p({name:"fallback-ui-not-rendered",reason:"no-html-configured"});try{let t=document.querySelector(a);if(!t)return f()?.fallbackTargetNotFound(a),void p({name:"fallback-ui-not-rendered",reason:"target-not-found",selector:a});let n=document.createElement("div");n.innerHTML=r;let o=w();o&&h(n,o),t.innerHTML=n.innerHTML;let i=t.querySelector('[data-spa-guard-action="reload"]');i&&i.addEventListener("click",()=>globalThis.window.location.reload());let l=e?.retryId??S()?.retryId;if(l){let e=document.getElementsByClassName("spa-guard-retry-id");for(let t of e)t.textContent=l}p({name:"fallback-ui-shown"})}catch(e){f()?.fallbackInjectFailed(e)}})({retryId:y}),{status:"fallback"}}let g=u+1,b=r[u]??1e3,T=e.error+"";p({attempt:g,delay:b,name:"retry-attempt",retryId:y},{silent:x([T])}),f()?.retrySchedulingReload(y,g,b),U({attempt:g,retryId:y}),(e=>{let t=v(),r=t.html?.loading?.content;if(!r)return;let a=t.html?.fallback?.selector??"body";try{let n=document.querySelector(a);if(!n)return;let o=document.createElement("div");o.innerHTML=r;let i=w();i&&h(o,i),n.innerHTML=o.innerHTML;let l=n.querySelector('[data-spa-guard-section="retrying"]');if(l){let e=l;e.style.display="",e.style.visibility="visible"}let s=n.querySelectorAll('[data-spa-guard-content="attempt"]');for(let t of s)t.textContent=e+"";let d=n.querySelector("[data-spa-guard-spinner]");if(d){let e=t.html?.spinner;e?.disabled?d.style.display="none":e?.content&&(d.innerHTML=e.content)}}catch{}})(g);let I=setTimeout(()=>{try{a&&n&&((e,t)=>{let r={attemptNumber:t,retryId:e,timestamp:Date.now()};if(_())try{sessionStorage.setItem(k,JSON.stringify(r))}catch{E().storage=r}else E().storage=r})(y,g);let t=((e,t,r,a=!0)=>{let n=new URL(globalThis.window.location.href);return a&&n.searchParams.set(l,e),n.searchParams.set(s,t+""),r&&n.searchParams.set(d,Date.now()+""),n.toString()})(y,g,e.cacheBust,a);globalThis.window.location.href=t}catch(e){f()?.error("triggerRetry navigation failed",e),U({phase:"idle",timer:null})}},b);return U({timer:I}),{status:"accepted"}}catch(e){return f()?.error("triggerRetry internal error",e),U({lastSource:void 0,lastTriggerTime:void 0,phase:"idle"}),{status:"internal-error"}}},B=e=>{let t=O(e);return!!t&&[/Failed to fetch dynamically imported module/i,/Importing a module script failed/i,/error loading dynamically imported module/i,/Unable to preload CSS/i,/Loading chunk \d+ failed/i,/Loading CSS chunk \d+ failed/i,/ChunkLoadError/i].some(e=>e.test(t))},O=e=>e instanceof Error?e.message:"string"==typeof e?e:e&&"object"==typeof e&&"message"in e?e.message+"":e&&"object"==typeof e&&"reason"in e?O(e.reason):null,P=/[-._][a-zA-Z0-9]{6,}\.(js|mjs|css)$/i,C=e=>{try{let t=new URL(e).pathname;return P.test(t)}catch{return P.test(e)}},H=()=>void 0===globalThis.window?{failedAssets:new Set,recoveryTimer:null}:(globalThis.window[u]||(globalThis.window[u]={failedAssets:new Set,recoveryTimer:null}),globalThis.window[u]);(()=>{if(void 0===globalThis.window||g.initialized)return;g.initialized=!0,void 0!==globalThis.window&&(globalThis.window[o]=!0);let e=globalThis.window.addEventListener.bind(globalThis.window);e("error",e=>{let t=(e=>{let t=e.target;return t instanceof HTMLScriptElement?t.src:t instanceof HTMLLinkElement?t.href:""})(e);if((e=>{let t=e.target;return t instanceof HTMLScriptElement?C(t.src):t instanceof HTMLLinkElement&&C(t.href)})(e)&&(void 0!==(r=t)?(e=>{if(typeof performance>"u"||"function"!=typeof performance.getEntriesByName)return!0;let t=performance.getEntriesByName(e,"resource");if(0===t.length)return!0;let r=t.at(-1);return r.responseStatus>=400||0===r.transferSize&&0===r.decodedBodySize})(r):(typeof performance>"u"?0:performance.now())>3e4)){if(x([t,e.message]))return;return e.preventDefault(),p({name:"static-asset-load-failed",url:t}),void(!1!==v().staticAssets?.autoRecover&&(e=>{if(void 0===globalThis.window)return;let t=H();if(t.failedAssets.add(e),null!==t.recoveryTimer)return;let r=v().staticAssets?.recoveryDelay??500;t.recoveryTimer=setTimeout(()=>{let e=H();e.recoveryTimer=null;let t=[...e.failedAssets];e.failedAssets=new Set;let r=Error("Static asset load failed: "+t.join(", "));j({cacheBust:!0,error:r,source:"static-asset-error"})},r)})(t))}var r;if(!x([e.message]))return f()?.capturedError("error",e),B(e)?(e.preventDefault(),void j({error:e.error??e,source:"chunk-error"})):D([e.message])?(e.preventDefault(),void j({error:e.error??e,source:"force-retry"})):void L({errorMessage:e.message,eventName:"error",serialized:"",...I()})},!0),e("unhandledrejection",e=>{let t=e.reason+"";if(x([t]))return;if(f()?.capturedError("unhandledrejection",e),B(e.reason))return e.preventDefault(),void j({error:e.reason,source:"chunk-error"});if(D([t]))return e.preventDefault(),void j({error:e.reason,source:"force-retry"});let r=v().handleUnhandledRejections;!1!==r?.sendBeacon&&L({errorMessage:t,eventName:"unhandledrejection",serialized:"",...I()}),!1!==r?.retry&&(e.preventDefault(),j({error:e.reason,source:"unhandled-rejection"}))}),e("securitypolicyviolation",e=>{let t=`${e.violatedDirective}: ${e.blockedURI}`;x([t])||(f()?.capturedError("csp",e.blockedURI,e.violatedDirective),L({eventMessage:t,eventName:"securitypolicyviolation",serialized:"",...I()}))}),e("vite:preloadError",e=>{let t=e?.payload;x([t?.message||e?.message])||(f()?.capturedError("vite:preloadError",e),e.preventDefault(),j({error:t??e,source:"vite:preloadError"}))})})();
@@ -1 +1 @@
1
- var e=Object.defineProperty,r="@ovineko/spa-guard",t="__SPA_GUARD_OPTIONS__",a=Symbol.for(r+":event-subscribers"),o=Symbol.for(r+":internal-config"),n=Symbol.for(r+":initialized"),l=Symbol.for(r+":logger"),i="spaGuardRetryId",s="spaGuardRetryAttempt",d="spaGuardCacheBust",c=(Symbol.for(r+":version-check-state"),Symbol.for(r+":in-memory-last-reload")),u=Symbol.for(r+":static-asset-recovery"),m=(Symbol.for(r+":spinner-state"),Symbol.for(r+":fallback-mode"));globalThis.window&&!globalThis.window[a]&&(globalThis.window[a]=new Set),globalThis.window&&!globalThis.window[o]&&(globalThis.window[o]={defaultRetryEnabled:!0,initialized:!1});var y=globalThis.window?.[a]??new Set,g=globalThis.window?.[o]??{defaultRetryEnabled:!0,initialized:!1},f=()=>globalThis.window?.[l],p=(e,r)=>{r?.silent||f()?.logEvent(e),y.forEach(r=>{try{r(e)}catch{}})};((r,t)=>{for(var a in t)e(r,a,{get:t[a],enumerable:!0})})({},{getOptions:()=>b,optionsWindowKey:()=>t});var h={checkVersion:{cache:"no-store",interval:3e5,mode:"html",onUpdate:"reload"},enableRetryReset:!0,errors:{forceRetry:[],ignore:[]},handleUnhandledRejections:{retry:!0,sendBeacon:!0},html:{fallback:{content:'<style>.spa-guard-error-id:has(.spa-guard-retry-id:empty){display:none}.spa-guard-error-id{font-family:ui-monospace,SFMono-Regular,Consolas,"Liberation Mono",Menlo,monospace}</style><div style="display:flex;align-items:center;justify-content:center;min-height:100vh;padding:2rem;font-family:system-ui,sans-serif"><div style="text-align:center;max-width:480px"><div style="margin-bottom:1.5rem"><svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" fill="none" viewBox="0 0 24 24" stroke="#b0b0b0" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg></div><h1 data-spa-guard-content="heading" style="font-size:1.375rem;font-weight:600;margin:0 0 .5rem;color:#1a1a1a;line-height:1.3">Something went wrong</h1><p data-spa-guard-content="message" style="max-width:600px;margin:0 auto 1.5rem;color:#666;font-size:.9375rem;line-height:1.5">Please refresh the page to continue.</p><div style="display:flex;gap:.5rem;justify-content:center;flex-wrap:wrap"><button data-spa-guard-action="try-again" type="button" style="display:none;padding:.5rem 1.25rem;font-size:.875rem;font-family:inherit;border-radius:6px;border:1px solid #d0d0d0;background:#fff;color:#333;cursor:pointer;line-height:1.5">Try again</button> <button data-spa-guard-action="reload" type="button" style="padding:.5rem 1.25rem;font-size:.875rem;font-family:inherit;border-radius:6px;border:1px solid transparent;background:#111;color:#fff;cursor:pointer;line-height:1.5">Reload page</button></div><p class="spa-guard-error-id" style="margin-top:1.5rem;font-size:.6875rem;color:#999">Error ID: <span class="spa-guard-retry-id"></span></p></div></div>',selector:"body"},loading:{content:'<div style="display:flex;align-items:center;justify-content:center;min-height:100vh;padding:2rem;font-family:system-ui,sans-serif"><div style="text-align:center"><div data-spa-guard-spinner style="margin-bottom:1.25rem"></div><h2 data-spa-guard-content="loading" style="font-size:1.125rem;font-weight:600;margin:0 0 .25rem;color:#1a1a1a">Loading...</h2><p data-spa-guard-section="retrying" style="display:none;font-size:.8125rem;color:#999;margin:.5rem 0 0"><span data-spa-guard-content="retrying">Retry attempt</span> <span data-spa-guard-content="attempt"></span></p></div></div>'},spinner:{background:"#fff",disabled:!1}},lazyRetry:{callReloadOnFailure:!0,retryDelays:[1e3,2e3]},minTimeBetweenResets:5e3,reloadDelays:[1e3,2e3,5e3],staticAssets:{autoRecover:!0,recoveryDelay:500},useRetryId:!0},b=()=>{let e=globalThis.window?.[t];return{...h,...e,checkVersion:{...h.checkVersion,...e?.checkVersion},errors:{...h.errors,...e?.errors},handleUnhandledRejections:{...h.handleUnhandledRejections,...e?.handleUnhandledRejections},html:{fallback:{...h.html?.fallback,...e?.html?.fallback},loading:{...h.html?.loading,...e?.html?.loading},spinner:{...h.html?.spinner,...e?.html?.spinner}},lazyRetry:{...h.lazyRetry,...e?.lazyRetry},reportBeacon:{...h.reportBeacon,...e?.reportBeacon},staticAssets:{...h.staticAssets,...e?.staticAssets}}},w="__SPA_GUARD_FORCE_RETRY__",v=()=>{try{let e=new URLSearchParams(globalThis.window.location.search),r=e.get(i),t=e.get(s);if(r&&t){if(!/^\d+$/.test(t))return null;let e=parseInt(t,10);return Number.isNaN(e)||!Number.isFinite(e)||e<0?null:{retryAttempt:e,retryId:r}}return null}catch{return null}},k=()=>{if(typeof crypto<"u"&&crypto.randomUUID)return crypto.randomUUID();if(typeof crypto<"u"&&crypto.getRandomValues){let e=new Uint32Array(2);return crypto.getRandomValues(e),`${Date.now()}-${e[0].toString(36)}-${e[1].toString(36)}`}return`${Date.now()}-${Math.random().toString(36).slice(2,15)}`},S=()=>{let e=v();return e?{retryAttempt:e.retryAttempt,retryId:e.retryId}:{}},T="__spa_guard_last_reload_timestamp__",R="__spa_guard_last_retry_reset__";globalThis.window&&!globalThis.window[c]&&(globalThis.window[c]={resetInfo:null,storage:null});var $=()=>{let e=globalThis.window;return e?e[c]??(e[c]={resetInfo:null,storage:null}):{resetInfo:null,storage:null}},I=()=>{try{return void 0!==globalThis.window&&typeof sessionStorage<"u"}catch{return!1}},E=()=>{if(I())try{let e=sessionStorage.getItem(T);if(e)return JSON.parse(e)}catch{try{sessionStorage.removeItem(T)}catch{}return $().storage}return $().storage},N=e=>{let r=(b().errors?.ignore??[]).filter(e=>""!==e);return 0!==r.length&&e.filter(e=>"string"==typeof e).some(e=>r.some(r=>e.includes(r)))},A=e=>{let r=[...b().errors?.forceRetry??[],w].filter(e=>""!==e);return e.filter(e=>"string"==typeof e).some(e=>r.some(r=>e.includes(r)))},z=e=>{if((e=>N([e.errorMessage,e.eventMessage]))(e))return;let r=b();if(!r.reportBeacon?.endpoint)return void f()?.noBeaconEndpoint();let t=r.appName?{...e,appName:r.appName}:e,a=JSON.stringify(t);("function"!=typeof globalThis.window?.navigator?.sendBeacon||!globalThis.window.navigator.sendBeacon(r.reportBeacon.endpoint,a))&&"function"==typeof fetch&&fetch(r.reportBeacon.endpoint,{body:a,keepalive:!0,method:"POST"}).catch(e=>{f()?.beaconSendFailed(e)})},x=Symbol.for(r+":retry-orchestrator"),D=e=>{if(void 0===globalThis.window)return;let r=globalThis.window;r[x]||(r[x]={attempt:0,lastSource:void 0,lastTriggerTime:void 0,phase:"idle",retryId:null,timer:null}),Object.assign(r[x],e)},U=(e={})=>{let r=(()=>{if(void 0===globalThis.window)return{attempt:0,lastSource:void 0,lastTriggerTime:void 0,phase:"idle",retryId:null,timer:null};let e=globalThis.window;return e[x]||(e[x]={attempt:0,lastSource:void 0,lastTriggerTime:void 0,phase:"idle",retryId:null,timer:null}),e[x]})();if("fallback"===r.phase||void 0!==globalThis.window&&!0===globalThis.window[m])return f()?.fallbackAlreadyShown(e.error),{status:"fallback"};if("scheduled"===r.phase)return f()?.reloadAlreadyScheduled(e.error),{reason:"already-scheduled",status:"deduped"};if(!g.defaultRetryEnabled)return{status:"retry-disabled"};D({lastSource:e.source,lastTriggerTime:Date.now(),phase:"scheduled"});try{let r=b(),t=r.reloadDelays??[1e3,2e3,5e3],a=r.useRetryId??!0,o=r.enableRetryReset??!0,n=r.minTimeBetweenResets??5e3,l=(()=>{try{let e=new URLSearchParams(globalThis.window.location.search).get(s);if(!e||!/^\d+$/.test(e))return null;let r=parseInt(e,10);return Number.isNaN(r)||!Number.isFinite(r)||r<0?null:r}catch{return null}})(),c=(()=>{try{return new URLSearchParams(globalThis.window.location.search).get(i)}catch{return null}})(),u=l??0,y=a&&c?c:k();if(f()?.retryCycleStarting(y,u),o&&c&&null!==l&&l>0&&((e,r,t=5e3)=>{if(0===e.retryAttempt)return!1;let a=E();if(!a||a.retryId!==e.retryId)return!1;let o=(()=>{if(I())try{let e=sessionStorage.getItem(R);if(e)return JSON.parse(e)}catch{try{sessionStorage.removeItem(R)}catch{}return $().resetInfo}return $().resetInfo})();return!(o&&Date.now()-o.timestamp<t)&&Date.now()-a.timestamp>(r[a.attemptNumber-1]??1e3)+3e4})({retryAttempt:l,retryId:c},t,n)){let r=E(),t=r?Date.now()-r.timestamp:0;(()=>{try{let e=new URL(globalThis.window.location.href);e.searchParams.delete(i),e.searchParams.delete(s),e.searchParams.delete(d),globalThis.window.history.replaceState(null,"",e.toString())}catch(e){f()?.error("clearRetryFromUrl failed",e)}})(),(()=>{if(I())try{sessionStorage.removeItem(T)}catch{}$().storage=null})(),(e=>{let r={previousRetryId:e,timestamp:Date.now()};if(I())try{sessionStorage.setItem(R,JSON.stringify(r))}catch{$().resetInfo=r}else $().resetInfo=r})(c);let a=e.error+"";p({name:"retry-reset",previousAttempt:l,previousRetryId:c,timeSinceReload:t},{silent:N([a])}),u=0,y=k()}if(p({error:e.error,isRetrying:u<t.length,name:"chunk-error"}),u>=t.length){let r=e.error+"";return p({finalAttempt:u,name:"retry-exhausted",retryId:y},{silent:N([r])}),z({errorMessage:"Exceeded maximum reload attempts",eventName:"chunk_error_max_reloads",retryAttempt:u,retryId:y,serialized:JSON.stringify({error:e.error+"",retryAttempt:u,retryId:y})}),D({attempt:u,phase:"fallback",retryId:y}),void 0!==globalThis.window&&(globalThis.window[m]=!0),(()=>{let e=b(),r=e.html?.fallback?.content,t=e.html?.fallback?.selector??"body";if(!r)return f()?.noFallbackConfigured(),void p({name:"fallback-ui-not-rendered",reason:"no-html-configured"});try{let e=document.querySelector(t);if(!e)return f()?.fallbackTargetNotFound(t),void p({name:"fallback-ui-not-rendered",reason:"target-not-found",selector:t});let a=document.createElement("div");a.innerHTML=r;let o=function(){try{let e=document.querySelector('meta[name="spa-guard-i18n"]');if(!e)return null;let r=e.getAttribute("content");return r?JSON.parse(r):null}catch{return null}}();o&&function(e,r){let t=e.querySelectorAll("[data-spa-guard-content]");for(let e of t){let t=e.dataset.spaGuardContent;if(t&&t in r){let a=r[t];"string"==typeof a&&(e.textContent=a)}}let a=e.querySelectorAll("[data-spa-guard-action]");for(let e of a){let t=e.dataset.spaGuardAction,a="try-again"===t?"tryAgain":t;if(a&&a in r){let t=r[a];"string"==typeof t&&(e.textContent=t)}}if(r.rtl)for(let r of e.children)r instanceof HTMLElement&&"STYLE"!==r.tagName&&(r.style.direction="rtl")}(a,o),e.innerHTML=a.innerHTML;let n=e.querySelector('[data-spa-guard-action="reload"]');n&&n.addEventListener("click",()=>globalThis.window.location.reload());let l=v();if(l){let e=document.getElementsByClassName("spa-guard-retry-id");for(let r of e)r.textContent=l.retryId}p({name:"fallback-ui-shown"})}catch(e){f()?.fallbackInjectFailed(e)}})(),{status:"fallback"}}let g=u+1,h=t[u]??1e3,w=e.error+"";p({attempt:g,delay:h,name:"retry-attempt",retryId:y},{silent:N([w])}),f()?.retrySchedulingReload(y,g,h),D({attempt:g,retryId:y});let S=setTimeout(()=>{try{a&&o&&((e,r)=>{let t={attemptNumber:r,retryId:e,timestamp:Date.now()};if(I())try{sessionStorage.setItem(T,JSON.stringify(t))}catch{$().storage=t}else $().storage=t})(y,g);let r=((e,r,t,a=!0)=>{let o=new URL(globalThis.window.location.href);return a&&o.searchParams.set(i,e),o.searchParams.set(s,r+""),t&&o.searchParams.set(d,Date.now()+""),o.toString()})(y,g,e.cacheBust,a);globalThis.window.location.href=r}catch(e){f()?.error("triggerRetry navigation failed",e),D({phase:"idle"})}},h);return D({timer:S}),{status:"accepted"}}catch(e){return f()?.error("triggerRetry internal error",e),D({lastSource:void 0,lastTriggerTime:void 0,phase:"idle"}),{reason:"internal-error",status:"deduped"}}},_=e=>{let r=j(e);return!!r&&[/Failed to fetch dynamically imported module/i,/Importing a module script failed/i,/error loading dynamically imported module/i,/Unable to preload CSS/i,/Loading chunk \d+ failed/i,/Loading CSS chunk \d+ failed/i,/ChunkLoadError/i].some(e=>e.test(r))},j=e=>e instanceof Error?e.message:"string"==typeof e?e:e&&"object"==typeof e&&"message"in e?e.message+"":e&&"object"==typeof e&&"reason"in e?j(e.reason):null,L=e=>{if(null==e)return{type:"null",value:e};if("object"!=typeof e)return{type:typeof e,value:e};if(e instanceof Error)return{message:e.message,name:e.name,stack:e.stack,type:"Error",...C(e)};if("reason"in e&&"promise"in e)return{reason:L(e.reason),type:"PromiseRejectionEvent"};if("error"in e&&"message"in e&&"filename"in e)return{colno:e.colno,error:L(e.error),filename:e.filename,lineno:e.lineno,message:e.message,type:"ErrorEvent"};if("violatedDirective"in e&&"blockedURI"in e){let r=e;return{blockedURI:r.blockedURI,columnNumber:r.columnNumber,effectiveDirective:r.effectiveDirective,lineNumber:r.lineNumber,originalPolicy:r.originalPolicy,sourceFile:r.sourceFile,type:"SecurityPolicyViolationEvent",violatedDirective:r.violatedDirective}}if("type"in e&&"target"in e){let r=e;return{eventType:r.type,target:P(r.target),timeStamp:r.timeStamp,type:"Event"}}return{type:"object",value:F(e)}},C=e=>{let r={};for(let t of Object.getOwnPropertyNames(e))if(!["message","name","stack"].includes(t))try{r[t]=e[t]}catch{}return r},P=e=>e?e instanceof HTMLElement?{className:e.className,href:e.href,id:e.id,src:e.src,tagName:e.tagName}:{type:e+""}:null,F=e=>{let r={};for(let t of Object.keys(e))try{let a=e[t];r[t]="object"==typeof a?a+"":a}catch{}return r},B=/[-._][a-zA-Z0-9]{6,}\.(js|mjs|css)$/i,O=e=>{try{let r=new URL(e).pathname;return B.test(r)}catch{return B.test(e)}},M=()=>void 0===globalThis.window?{failedAssets:new Set,recoveryTimer:null}:(globalThis.window[u]||(globalThis.window[u]={failedAssets:new Set,recoveryTimer:null}),globalThis.window[u]),V="[spa-guard]",H={"chunk-error":"error","fallback-ui-not-rendered":"error","fallback-ui-shown":"warn","lazy-retry-attempt":"warn","lazy-retry-exhausted":"error","lazy-retry-start":"log","lazy-retry-success":"log","retry-attempt":"warn","retry-exhausted":"error","retry-reset":"log","static-asset-load-failed":"error"};((e,r)=>{if(g.initialized)return;r&&(e=>{void 0!==globalThis.window&&(globalThis.window[l]=e)})(r),g.initialized=!0,void 0!==globalThis.window&&(globalThis.window[n]=!0);let t=b(),a=globalThis.window.addEventListener.bind(globalThis.window);a("error",r=>{let a=(e=>{let r=e.target;return r instanceof HTMLScriptElement?r.src:r instanceof HTMLLinkElement?r.href:""})(r);if((e=>{let r=e.target;return r instanceof HTMLScriptElement?O(r.src):r instanceof HTMLLinkElement&&O(r.href)})(r)&&(e=>void 0!==e?(e=>{if(typeof performance>"u"||"function"!=typeof performance.getEntriesByName)return!0;let r=performance.getEntriesByName(e,"resource");if(0===r.length)return!0;let t=r.at(-1);return t.responseStatus>=400||0===t.transferSize&&0===t.decodedBodySize})(e):(typeof performance>"u"?0:performance.now())>3e4)(a)){if(N([a,r.message]))return;return r.preventDefault(),p({name:"static-asset-load-failed",url:a}),void(!1!==t.staticAssets?.autoRecover&&(e=>{if(void 0===globalThis.window)return;let r=M();if(r.failedAssets.add(e),null!==r.recoveryTimer)return;let t=b().staticAssets?.recoveryDelay??500;r.recoveryTimer=setTimeout(()=>{let e=M();e.recoveryTimer=null;let r=[...e.failedAssets];e.failedAssets=new Set;let t=Error("Static asset load failed: "+r.join(", "));U({cacheBust:!0,error:t,source:"static-asset-error"})},t)})(a))}if(N([r.message]))return;if(f()?.capturedError("error",r),_(r))return r.preventDefault(),void U({error:r.error??r,source:"chunk-error"});if(A([r.message]))return r.preventDefault(),void U({error:r.error??r,source:"force-retry"});let o=e(r);z({errorMessage:r.message,eventName:"error",serialized:o,...S()})},!0),a("unhandledrejection",r=>{let a=r.reason+"";if(N([a]))return;if(f()?.capturedError("unhandledrejection",r),_(r.reason))return r.preventDefault(),void U({error:r.reason,source:"chunk-error"});if(A([a]))return r.preventDefault(),void U({error:r.reason,source:"force-retry"});let o=t.handleUnhandledRejections;if(!1!==o?.sendBeacon){let t=e(r);z({errorMessage:a,eventName:"unhandledrejection",serialized:t,...S()})}!1!==o?.retry&&(r.preventDefault(),U({error:r.reason,source:"unhandled-rejection"}))}),a("securitypolicyviolation",r=>{let t=`${r.violatedDirective}: ${r.blockedURI}`;if(N([t]))return;f()?.capturedError("csp",r.blockedURI,r.violatedDirective);let a=e(r);z({eventMessage:t,eventName:"securitypolicyviolation",serialized:a,...S()})}),a("vite:preloadError",e=>{let r=e?.payload;N([r?.message||e?.message])||(f()?.capturedError("vite:preloadError",e),e.preventDefault(),U({error:r??e,source:"vite:preloadError"}))})})(e=>{try{let r=L(e);return JSON.stringify(r,null,2)}catch{return JSON.stringify({error:"Failed to serialize error",fallback:e+""})}},{beaconSendFailed(e){console.error(V+" Failed to send beacon:",e)},capturedError(e,...r){console.error(`${V} ${e}:capture:`,...r)},clearingRetryState(){console.log(V+" Clearing retry state from URL to allow clean reload attempt")},error(e,...r){console.error(`${V} ${e}`,...r)},fallbackAlreadyShown(e){console.error(V+" Fallback UI was already shown. Not retrying to prevent infinite loop.",e)},fallbackInjectFailed(e){console.error(V+" Failed to inject fallback UI",e)},fallbackTargetNotFound(e){console.error(`${V} Target element not found for selector: ${e}`)},log(e,...r){console.log(`${V} ${e}`,...r)},logEvent(e){let r=H[e.name],t=(e=>{switch(e.name){case"chunk-error":return`${V} chunk-error: isRetrying=${e.isRetrying}`;case"fallback-ui-not-rendered":{let r=e.selector?" selector="+e.selector:"";return`${V} fallback-ui-not-rendered: reason=${e.reason}${r}`}case"fallback-ui-shown":return V+" fallback-ui-shown";case"lazy-retry-attempt":return`${V} lazy-retry-attempt: attempt ${e.attempt}/${e.totalAttempts}, delay ${e.delay}ms`;case"lazy-retry-exhausted":return`${V} lazy-retry-exhausted: ${e.totalAttempts} attempts, willReload=${e.willReload}`;case"lazy-retry-start":return`${V} lazy-retry-start: totalAttempts=${e.totalAttempts}`;case"lazy-retry-success":{let r=void 0===e.totalTime?"":`, totalTime=${e.totalTime}ms`;return`${V} lazy-retry-success: succeeded on attempt ${e.attempt}${r}`}case"retry-attempt":return`${V} retry-attempt: attempt ${e.attempt} in ${e.delay}ms (retryId: ${e.retryId})`;case"retry-exhausted":return`${V} retry-exhausted: finalAttempt=${e.finalAttempt} (retryId: ${e.retryId})`;case"retry-reset":return`${V} retry-reset: ${e.timeSinceReload}ms since last reload (retryId: ${e.previousRetryId})`;case"static-asset-load-failed":return`${V} static-asset-load-failed: ${e.url}`}})(e);"chunk-error"===e.name||"lazy-retry-attempt"===e.name||"lazy-retry-exhausted"===e.name?console[r](t,e.error):console[r](t)},noBeaconEndpoint(){console.warn(V+" Report endpoint is not configured")},noFallbackConfigured(){console.error(V+" No fallback UI configured")},reloadAlreadyScheduled(e){console.log(V+" Reload already scheduled, ignoring duplicate chunk error:",e)},retryCycleStarting(e,r){console.log(`${V} Retry cycle starting: retryId=${e}, fromAttempt=${r}`)},retryLimitExceeded(e,r){console.log(`${V} Retry limit exceeded (${e}/${r}), marking as fallback shown`)},retrySchedulingReload(e,r,t){console.log(`${V} Scheduling reload: retryId=${e}, attempt=${r}, delay=${t}ms`)},updatedRetryAttempt(e){console.log(`${V} Updated retry attempt to ${e} in URL for fallback UI`)},versionChangeDetected(e,r){console.warn(`${V} New version available (${e??"unknown"} → ${r}). Please refresh to get the latest version.`)},versionCheckAlreadyRunning(){console.warn(V+" Version check already running")},versionCheckDisabled(){console.warn(V+" Version checking disabled: no version configured")},versionCheckFailed(e){console.error(V+" Version check failed",e)},versionCheckHttpError(e){console.warn(`${V} Version check HTTP error: ${e}`)},versionCheckParseError(){console.warn(V+" Failed to parse version from HTML")},versionCheckPaused(){console.log(V+" Version check paused (tab hidden)")},versionCheckRequiresEndpoint(){console.warn(V+" JSON version check mode requires endpoint")},versionCheckResumed(){console.log(V+" Version check resumed (tab visible)")},versionCheckResumedImmediate(){console.log(V+" Version check resumed with immediate check (tab visible, interval elapsed)")},versionCheckStarted(e,r,t){console.log(`${V} Starting version check (mode: ${e}, interval: ${r}ms, current: ${t})`)},versionCheckStopped(){console.log(V+" Version check stopped")},warn(e,...r){console.warn(`${V} ${e}`,...r)}});
1
+ var e=Object.defineProperty,t="@ovineko/spa-guard",r="__SPA_GUARD_OPTIONS__",a=Symbol.for(t+":event-subscribers"),o=Symbol.for(t+":internal-config"),n=Symbol.for(t+":initialized"),l=Symbol.for(t+":logger"),i="spaGuardRetryId",s="spaGuardRetryAttempt",d="spaGuardCacheBust",c=(Symbol.for(t+":version-check-state"),Symbol.for(t+":in-memory-last-reload")),u=Symbol.for(t+":static-asset-recovery"),y=(Symbol.for(t+":spinner-state"),Symbol.for(t+":fallback-mode"));globalThis.window&&!globalThis.window[a]&&(globalThis.window[a]=new Set),globalThis.window&&!globalThis.window[o]&&(globalThis.window[o]={defaultRetryEnabled:!0,initialized:!1});var m=globalThis.window?.[a]??new Set,f=globalThis.window?.[o]??{defaultRetryEnabled:!0,initialized:!1},p=()=>globalThis.window?.[l],g=(e,t)=>{t?.silent||p()?.logEvent(e),m.forEach(t=>{try{t(e)}catch{}})};function h(e,t){let r=e.querySelectorAll("[data-spa-guard-content]");for(let e of r){let r=e.dataset.spaGuardContent;if(r&&r in t){let a=t[r];"string"==typeof a&&(e.textContent=a)}}let a=e.querySelectorAll("[data-spa-guard-action]");for(let e of a){let r=e.dataset.spaGuardAction,a="try-again"===r?"tryAgain":r;if(a&&a in t){let r=t[a];"string"==typeof r&&(e.textContent=r)}}if(t.rtl)for(let t of e.children)t instanceof HTMLElement&&"STYLE"!==t.tagName&&(t.style.direction="rtl")}function b(){try{let e=document.querySelector('meta[name="spa-guard-i18n"]');if(!e)return null;let t=e.getAttribute("content");return t?JSON.parse(t):null}catch{return null}}((t,r)=>{for(var a in r)e(t,a,{get:r[a],enumerable:!0})})({},{getOptions:()=>w,optionsWindowKey:()=>r});var v={checkVersion:{cache:"no-store",interval:3e5,mode:"html",onUpdate:"reload"},enableRetryReset:!0,errors:{forceRetry:[],ignore:[]},handleUnhandledRejections:{retry:!0,sendBeacon:!0},html:{fallback:{content:'<style>.spa-guard-error-id:has(.spa-guard-retry-id:empty){display:none}.spa-guard-error-id{font-family:ui-monospace,SFMono-Regular,Consolas,"Liberation Mono",Menlo,monospace}</style><div style="display:flex;align-items:center;justify-content:center;min-height:100vh;padding:2rem;font-family:system-ui,sans-serif"><div style="text-align:center;max-width:480px"><div style="margin-bottom:1.5rem"><svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" fill="none" viewBox="0 0 24 24" stroke="#b0b0b0" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg></div><h1 data-spa-guard-content="heading" style="font-size:1.375rem;font-weight:600;margin:0 0 .5rem;color:#1a1a1a;line-height:1.3">Something went wrong</h1><p data-spa-guard-content="message" style="max-width:600px;margin:0 auto 1.5rem;color:#666;font-size:.9375rem;line-height:1.5">Please refresh the page to continue.</p><div style="display:flex;gap:.5rem;justify-content:center;flex-wrap:wrap"><button data-spa-guard-action="try-again" type="button" style="display:none;padding:.5rem 1.25rem;font-size:.875rem;font-family:inherit;border-radius:6px;border:1px solid #d0d0d0;background:#fff;color:#333;cursor:pointer;line-height:1.5">Try again</button> <button data-spa-guard-action="reload" type="button" style="padding:.5rem 1.25rem;font-size:.875rem;font-family:inherit;border-radius:6px;border:1px solid transparent;background:#111;color:#fff;cursor:pointer;line-height:1.5">Reload page</button></div><p class="spa-guard-error-id" style="margin-top:1.5rem;font-size:.6875rem;color:#999">Error ID: <span class="spa-guard-retry-id"></span></p></div></div>',selector:"body"},loading:{content:'<div style="display:flex;align-items:center;justify-content:center;min-height:100vh;padding:2rem;font-family:system-ui,sans-serif"><div style="text-align:center"><div data-spa-guard-spinner style="margin-bottom:1.25rem"></div><h2 data-spa-guard-content="loading" style="font-size:1.125rem;font-weight:600;margin:0 0 .25rem;color:#1a1a1a">Loading...</h2><p data-spa-guard-section="retrying" style="display:none;font-size:.8125rem;color:#999;margin:.5rem 0 0"><span data-spa-guard-content="retrying">Retry attempt</span> <span data-spa-guard-content="attempt"></span></p></div></div>'},spinner:{background:"#fff",disabled:!1}},lazyRetry:{callReloadOnFailure:!0,retryDelays:[1e3,2e3]},minTimeBetweenResets:5e3,reloadDelays:[1e3,2e3,5e3],staticAssets:{autoRecover:!0,recoveryDelay:500},useRetryId:!0},w=()=>{let e=globalThis.window?.[r];return{...v,...e,checkVersion:{...v.checkVersion,...e?.checkVersion},errors:{...v.errors,...e?.errors},handleUnhandledRejections:{...v.handleUnhandledRejections,...e?.handleUnhandledRejections},html:{fallback:{...v.html?.fallback,...e?.html?.fallback},loading:{...v.html?.loading,...e?.html?.loading},spinner:{...v.html?.spinner,...e?.html?.spinner}},lazyRetry:{...v.lazyRetry,...e?.lazyRetry},reportBeacon:{...v.reportBeacon,...e?.reportBeacon},staticAssets:{...v.staticAssets,...e?.staticAssets}}},k="__SPA_GUARD_FORCE_RETRY__",T=()=>{try{let e=new URLSearchParams(globalThis.window.location.search),t=e.get(i),r=e.get(s);if(t&&r){if(!/^\d+$/.test(r))return null;let e=parseInt(r,10);return Number.isNaN(e)||!Number.isFinite(e)||e<0?null:{retryAttempt:e,retryId:t}}return null}catch{return null}},S=()=>{if(typeof crypto<"u"&&crypto.randomUUID)return crypto.randomUUID();if(typeof crypto<"u"&&crypto.getRandomValues){let e=new Uint32Array(2);return crypto.getRandomValues(e),`${Date.now()}-${e[0].toString(36)}-${e[1].toString(36)}`}return`${Date.now()}-${Math.random().toString(36).slice(2,15)}`},R=()=>{let e=T();return e?{retryAttempt:e.retryAttempt,retryId:e.retryId}:{}},I="__spa_guard_last_reload_timestamp__",$="__spa_guard_last_retry_reset__";globalThis.window&&!globalThis.window[c]&&(globalThis.window[c]={resetInfo:null,storage:null});var E=()=>{let e=globalThis.window;return e?e[c]??(e[c]={resetInfo:null,storage:null}):{resetInfo:null,storage:null}},A=()=>{try{return void 0!==globalThis.window&&typeof sessionStorage<"u"}catch{return!1}},N=()=>{if(A())try{let e=sessionStorage.getItem(I);if(e)return JSON.parse(e)}catch{try{sessionStorage.removeItem(I)}catch{}return E().storage}return E().storage},x=e=>{let t=(w().errors?.ignore??[]).filter(e=>""!==e);return 0!==t.length&&e.filter(e=>"string"==typeof e).some(e=>t.some(t=>e.includes(t)))},j=e=>{let t=[...w().errors?.forceRetry??[],k].filter(e=>""!==e);return e.filter(e=>"string"==typeof e).some(e=>t.some(t=>e.includes(t)))},D=e=>{if((e=>x([e.errorMessage,e.eventMessage]))(e))return;let t=w();if(!t.reportBeacon?.endpoint)return void p()?.noBeaconEndpoint();let r=t.appName?{...e,appName:t.appName}:e,a=JSON.stringify(r);("function"!=typeof globalThis.window?.navigator?.sendBeacon||!globalThis.window.navigator.sendBeacon(t.reportBeacon.endpoint,a))&&"function"==typeof fetch&&fetch(t.reportBeacon.endpoint,{body:a,keepalive:!0,method:"POST"}).catch(e=>{p()?.beaconSendFailed(e)})},z=Symbol.for(t+":retry-orchestrator"),L=e=>{if(void 0===globalThis.window)return;let t=globalThis.window;t[z]||(t[z]={attempt:0,lastSource:void 0,lastTriggerTime:void 0,phase:"idle",retryId:null,timer:null}),Object.assign(t[z],e)},U=()=>{try{let e=new URL(globalThis.window.location.href);e.searchParams.delete(i),e.searchParams.delete(s),e.searchParams.delete(d),globalThis.window.history.replaceState(null,"",e.toString())}catch(e){p()?.error("clearRetryFromUrl failed",e)}},_=(e={})=>{let t=(()=>{if(void 0===globalThis.window)return{attempt:0,lastSource:void 0,lastTriggerTime:void 0,phase:"idle",retryId:null,timer:null};let e=globalThis.window;return e[z]||(e[z]={attempt:0,lastSource:void 0,lastTriggerTime:void 0,phase:"idle",retryId:null,timer:null}),e[z]})();if("fallback"===t.phase||void 0!==globalThis.window&&!0===globalThis.window[y])return p()?.fallbackAlreadyShown(e.error),{status:"fallback"};if("scheduled"===t.phase)return p()?.reloadAlreadyScheduled(e.error),{reason:"already-scheduled",status:"deduped"};if(!f.defaultRetryEnabled)return{status:"retry-disabled"};L({lastSource:e.source,lastTriggerTime:Date.now(),phase:"scheduled"});try{let t=w(),r=t.reloadDelays??[1e3,2e3,5e3],a=t.useRetryId??!0,o=t.enableRetryReset??!0,n=t.minTimeBetweenResets??5e3,l=(()=>{try{let e=new URLSearchParams(globalThis.window.location.search).get(s);if(!e||!/^\d+$/.test(e))return null;let t=parseInt(e,10);return Number.isNaN(t)||!Number.isFinite(t)||t<0?null:t}catch{return null}})(),c=(()=>{try{return new URLSearchParams(globalThis.window.location.search).get(i)}catch{return null}})(),u=l??0,m=a&&c?c:S();if(p()?.retryCycleStarting(m,u),o&&c&&null!==l&&l>0&&((e,t,r=5e3)=>{if(0===e.retryAttempt)return!1;let a=N();if(!a||a.retryId!==e.retryId)return!1;let o=(()=>{if(A())try{let e=sessionStorage.getItem($);if(e)return JSON.parse(e)}catch{try{sessionStorage.removeItem($)}catch{}return E().resetInfo}return E().resetInfo})();return!(o&&Date.now()-o.timestamp<r)&&Date.now()-a.timestamp>(t[a.attemptNumber-1]??1e3)+3e4})({retryAttempt:l,retryId:c},r,n)){let t=N(),r=t?Date.now()-t.timestamp:0;U(),(()=>{if(A())try{sessionStorage.removeItem(I)}catch{}E().storage=null})(),(e=>{let t={previousRetryId:e,timestamp:Date.now()};if(A())try{sessionStorage.setItem($,JSON.stringify(t))}catch{E().resetInfo=t}else E().resetInfo=t})(c);let a=e.error+"";g({name:"retry-reset",previousAttempt:l,previousRetryId:c,timeSinceReload:r},{silent:x([a])}),u=0,m=S()}if(g({error:e.error,isRetrying:u<r.length,name:"chunk-error"}),u>=r.length){let t=e.error+"";return g({finalAttempt:u,name:"retry-exhausted",retryId:m},{silent:x([t])}),D({errorMessage:"Exceeded maximum reload attempts",eventName:"chunk_error_max_reloads",retryAttempt:u,retryId:m,serialized:JSON.stringify({error:e.error+"",retryAttempt:u,retryId:m})}),L({attempt:u,phase:"fallback",retryId:m}),void 0!==globalThis.window&&(globalThis.window[y]=!0),U(),(e=>{let t=w(),r=t.html?.fallback?.content,a=t.html?.fallback?.selector??"body";if(!r)return p()?.noFallbackConfigured(),void g({name:"fallback-ui-not-rendered",reason:"no-html-configured"});try{let t=document.querySelector(a);if(!t)return p()?.fallbackTargetNotFound(a),void g({name:"fallback-ui-not-rendered",reason:"target-not-found",selector:a});let o=document.createElement("div");o.innerHTML=r;let n=b();n&&h(o,n),t.innerHTML=o.innerHTML;let l=t.querySelector('[data-spa-guard-action="reload"]');l&&l.addEventListener("click",()=>globalThis.window.location.reload());let i=e?.retryId??T()?.retryId;if(i){let e=document.getElementsByClassName("spa-guard-retry-id");for(let t of e)t.textContent=i}g({name:"fallback-ui-shown"})}catch(e){p()?.fallbackInjectFailed(e)}})({retryId:m}),{status:"fallback"}}let f=u+1,v=r[u]??1e3,k=e.error+"";g({attempt:f,delay:v,name:"retry-attempt",retryId:m},{silent:x([k])}),p()?.retrySchedulingReload(m,f,v),L({attempt:f,retryId:m}),(e=>{let t=w(),r=t.html?.loading?.content;if(!r)return;let a=t.html?.fallback?.selector??"body";try{let o=document.querySelector(a);if(!o)return;let n=document.createElement("div");n.innerHTML=r;let l=b();l&&h(n,l),o.innerHTML=n.innerHTML;let i=o.querySelector('[data-spa-guard-section="retrying"]');if(i){let e=i;e.style.display="",e.style.visibility="visible"}let s=o.querySelectorAll('[data-spa-guard-content="attempt"]');for(let t of s)t.textContent=e+"";let d=o.querySelector("[data-spa-guard-spinner]");if(d){let e=t.html?.spinner;e?.disabled?d.style.display="none":e?.content&&(d.innerHTML=e.content)}}catch{}})(f);let R=setTimeout(()=>{try{a&&o&&((e,t)=>{let r={attemptNumber:t,retryId:e,timestamp:Date.now()};if(A())try{sessionStorage.setItem(I,JSON.stringify(r))}catch{E().storage=r}else E().storage=r})(m,f);let t=((e,t,r,a=!0)=>{let o=new URL(globalThis.window.location.href);return a&&o.searchParams.set(i,e),o.searchParams.set(s,t+""),r&&o.searchParams.set(d,Date.now()+""),o.toString()})(m,f,e.cacheBust,a);globalThis.window.location.href=t}catch(e){p()?.error("triggerRetry navigation failed",e),L({phase:"idle",timer:null})}},v);return L({timer:R}),{status:"accepted"}}catch(e){return p()?.error("triggerRetry internal error",e),L({lastSource:void 0,lastTriggerTime:void 0,phase:"idle"}),{status:"internal-error"}}},C=e=>{let t=M(e);return!!t&&[/Failed to fetch dynamically imported module/i,/Importing a module script failed/i,/error loading dynamically imported module/i,/Unable to preload CSS/i,/Loading chunk \d+ failed/i,/Loading CSS chunk \d+ failed/i,/ChunkLoadError/i].some(e=>e.test(t))},M=e=>e instanceof Error?e.message:"string"==typeof e?e:e&&"object"==typeof e&&"message"in e?e.message+"":e&&"object"==typeof e&&"reason"in e?M(e.reason):null,O=e=>e.length>500?e.slice(0,500)+"…":e,P=e=>{if(null==e)return{type:"null",value:e};if("object"!=typeof e)return{type:typeof e,value:e};if(e instanceof Error)return{message:e.message,name:e.name,stack:e.stack?O(e.stack):void 0,type:"Error",...H(e)};if("reason"in e&&"promise"in e){let t=e,r=t.reason,a=typeof window<"u"&&"string"==typeof window.location?.href?window.location.href:void 0;return{constructorName:r?.constructor?.name,isTrusted:t.isTrusted,pageUrl:a,reason:F(r,new WeakSet,0),timeStamp:t.timeStamp,type:"PromiseRejectionEvent"}}if("error"in e&&"message"in e&&"filename"in e)return{colno:e.colno,error:P(e.error),filename:e.filename,lineno:e.lineno,message:e.message,type:"ErrorEvent"};if("violatedDirective"in e&&"blockedURI"in e){let t=e;return{blockedURI:t.blockedURI,columnNumber:t.columnNumber,effectiveDirective:t.effectiveDirective,lineNumber:t.lineNumber,originalPolicy:t.originalPolicy,sourceFile:t.sourceFile,type:"SecurityPolicyViolationEvent",violatedDirective:t.violatedDirective}}if("type"in e&&"target"in e){let t=e;return{eventType:t.type,target:V(t.target),timeStamp:t.timeStamp,type:"Event"}}return{type:"object",value:J(e)}},F=(e,t,r)=>{if(null==e)return{type:"null",value:e};if("object"!=typeof e)return{type:typeof e,value:"string"==typeof e?O(e):e};if(t.has(e))return{type:"circular"};if(t.add(e),typeof AggregateError<"u"&&e instanceof AggregateError)return{errors:e.errors.slice(0,3).map(e=>B(e,t,r+1)),message:O(e.message),name:e.name,stack:e.stack?O(e.stack):void 0,type:"Error"};if(typeof DOMException<"u"&&e instanceof DOMException)return{code:e.code,message:O(e.message),name:e.name,type:"Error"};if(e instanceof Error)return B(e,t,r);let a=e;if(null!=a.response){let e=a.response,t={type:"HttpError"};void 0!==e.status&&(t.status=e.status),void 0!==e.statusText&&(t.statusText="string"==typeof e.statusText?O(e.statusText):e.statusText),void 0!==e.url&&(t.url="string"==typeof e.url?O(e.url):e.url),void 0!==e.method&&(t.method=e.method),void 0!==e.type&&(t.responseType=e.type);try{let r=e.headers;if(r){let e;"function"==typeof r.get?e=r.get("X-Request-ID")??r.get("x-request-id"):"object"==typeof r&&(e=r["X-Request-ID"]??r["x-request-id"]),e&&(t.xRequestId=O(e+""))}}catch{}let r=a.config??a.request;if(null!=r){let e={};void 0!==r.method&&(e.method=r.method),void 0!==r.url&&(e.url="string"==typeof r.url?O(r.url):r.url),void 0!==r.baseURL&&(e.baseURL="string"==typeof r.baseURL?O(r.baseURL):r.baseURL),t.request=e}return t}return{type:"object",value:q(a,t,r)}},B=(e,t,r)=>{if(!(e instanceof Error))return F(e,t,r+1);let a={message:O(e.message),name:e.name,stack:e.stack?O(e.stack):void 0,type:"Error"};if(r<4&&void 0!==e.cause){let o=e.cause;"object"==typeof o&&null!==o?t.has(o)||(a.cause=F(o,t,r+1)):a.cause=o}return a},q=(e,t,r)=>{let a={},o=0;for(let n of Object.keys(e)){if(o>=20)break;try{let o=e[n];null==o||"object"!=typeof o?a[n]="string"==typeof o?O(o):o:r<4&&!t.has(o)?(t.add(o),a[n]=q(o,t,r+1)):a[n]="[object]"}catch{}o++}return a},H=e=>{let t={},r=0;for(let a of Object.getOwnPropertyNames(e)){if(r>=20)break;if(!["message","name","stack"].includes(a)){try{let r=e[a];t[a]=null==r||"object"!=typeof r?"string"==typeof r?O(r):r:"[object]"}catch{}r++}}return t},V=e=>e?e instanceof HTMLElement?{className:e.className,href:e.href,id:e.id,src:e.src,tagName:e.tagName}:{type:e+""}:null,J=e=>{let t={},r=0;for(let a of Object.keys(e)){if(r>=20)break;try{let r=e[a];t[a]=null==r||"object"!=typeof r?"string"==typeof r?O(r):r:"[object]"}catch{}r++}return t},G=/[-._][a-zA-Z0-9]{6,}\.(js|mjs|css)$/i,W=e=>{try{let t=new URL(e).pathname;return G.test(t)}catch{return G.test(e)}},X=()=>void 0===globalThis.window?{failedAssets:new Set,recoveryTimer:null}:(globalThis.window[u]||(globalThis.window[u]={failedAssets:new Set,recoveryTimer:null}),globalThis.window[u]),Y="[spa-guard]",K={"chunk-error":"error","fallback-ui-not-rendered":"error","fallback-ui-shown":"warn","lazy-retry-attempt":"warn","lazy-retry-exhausted":"error","lazy-retry-start":"log","lazy-retry-success":"log","retry-attempt":"warn","retry-exhausted":"error","retry-reset":"log","static-asset-load-failed":"error"};((e,t)=>{if(void 0===globalThis.window||f.initialized)return;t&&(e=>{void 0!==globalThis.window&&(globalThis.window[l]=e)})(t),f.initialized=!0,void 0!==globalThis.window&&(globalThis.window[n]=!0);let r=globalThis.window.addEventListener.bind(globalThis.window);r("error",t=>{let r=(e=>{let t=e.target;return t instanceof HTMLScriptElement?t.src:t instanceof HTMLLinkElement?t.href:""})(t);if((e=>{let t=e.target;return t instanceof HTMLScriptElement?W(t.src):t instanceof HTMLLinkElement&&W(t.href)})(t)&&(e=>void 0!==e?(e=>{if(typeof performance>"u"||"function"!=typeof performance.getEntriesByName)return!0;let t=performance.getEntriesByName(e,"resource");if(0===t.length)return!0;let r=t.at(-1);return r.responseStatus>=400||0===r.transferSize&&0===r.decodedBodySize})(e):(typeof performance>"u"?0:performance.now())>3e4)(r)){if(x([r,t.message]))return;return t.preventDefault(),g({name:"static-asset-load-failed",url:r}),void(!1!==w().staticAssets?.autoRecover&&(e=>{if(void 0===globalThis.window)return;let t=X();if(t.failedAssets.add(e),null!==t.recoveryTimer)return;let r=w().staticAssets?.recoveryDelay??500;t.recoveryTimer=setTimeout(()=>{let e=X();e.recoveryTimer=null;let t=[...e.failedAssets];e.failedAssets=new Set;let r=Error("Static asset load failed: "+t.join(", "));_({cacheBust:!0,error:r,source:"static-asset-error"})},r)})(r))}if(x([t.message]))return;if(p()?.capturedError("error",t),C(t))return t.preventDefault(),void _({error:t.error??t,source:"chunk-error"});if(j([t.message]))return t.preventDefault(),void _({error:t.error??t,source:"force-retry"});let a=e(t);D({errorMessage:t.message,eventName:"error",serialized:a,...R()})},!0),r("unhandledrejection",t=>{let r=t.reason+"";if(x([r]))return;if(p()?.capturedError("unhandledrejection",t),C(t.reason))return t.preventDefault(),void _({error:t.reason,source:"chunk-error"});if(j([r]))return t.preventDefault(),void _({error:t.reason,source:"force-retry"});let a=w().handleUnhandledRejections;if(!1!==a?.sendBeacon){let a=e(t);D({errorMessage:r,eventName:"unhandledrejection",serialized:a,...R()})}!1!==a?.retry&&(t.preventDefault(),_({error:t.reason,source:"unhandled-rejection"}))}),r("securitypolicyviolation",t=>{let r=`${t.violatedDirective}: ${t.blockedURI}`;if(x([r]))return;p()?.capturedError("csp",t.blockedURI,t.violatedDirective);let a=e(t);D({eventMessage:r,eventName:"securitypolicyviolation",serialized:a,...R()})}),r("vite:preloadError",e=>{let t=e?.payload;x([t?.message||e?.message])||(p()?.capturedError("vite:preloadError",e),e.preventDefault(),_({error:t??e,source:"vite:preloadError"}))})})(e=>{try{let t=P(e);return JSON.stringify(t,null,2)}catch{return JSON.stringify({error:"Failed to serialize error",fallback:e+""})}},{beaconSendFailed(e){console.error(Y+" Failed to send beacon:",e)},capturedError(e,...t){console.error(`${Y} ${e}:capture:`,...t)},error(e,...t){console.error(`${Y} ${e}`,...t)},fallbackAlreadyShown(e){console.error(Y+" Fallback UI was already shown. Not retrying to prevent infinite loop.",e)},fallbackInjectFailed(e){console.error(Y+" Failed to inject fallback UI",e)},fallbackTargetNotFound(e){console.error(`${Y} Target element not found for selector: ${e}`)},log(e,...t){console.log(`${Y} ${e}`,...t)},logEvent(e){let t=K[e.name],r=(e=>{switch(e.name){case"chunk-error":return`${Y} chunk-error: isRetrying=${e.isRetrying}`;case"fallback-ui-not-rendered":{let t=e.selector?" selector="+e.selector:"";return`${Y} fallback-ui-not-rendered: reason=${e.reason}${t}`}case"fallback-ui-shown":return Y+" fallback-ui-shown";case"lazy-retry-attempt":return`${Y} lazy-retry-attempt: attempt ${e.attempt}/${e.totalAttempts}, delay ${e.delay}ms`;case"lazy-retry-exhausted":return`${Y} lazy-retry-exhausted: ${e.totalAttempts} attempts, willReload=${e.willReload}`;case"lazy-retry-start":return`${Y} lazy-retry-start: totalAttempts=${e.totalAttempts}`;case"lazy-retry-success":{let t=void 0===e.totalTime?"":`, totalTime=${e.totalTime}ms`;return`${Y} lazy-retry-success: succeeded on attempt ${e.attempt}${t}`}case"retry-attempt":return`${Y} retry-attempt: attempt ${e.attempt} in ${e.delay}ms (retryId: ${e.retryId})`;case"retry-exhausted":return`${Y} retry-exhausted: finalAttempt=${e.finalAttempt} (retryId: ${e.retryId})`;case"retry-reset":return`${Y} retry-reset: ${e.timeSinceReload}ms since last reload (retryId: ${e.previousRetryId})`;case"static-asset-load-failed":return`${Y} static-asset-load-failed: ${e.url}`}})(e);"chunk-error"===e.name||"lazy-retry-attempt"===e.name||"lazy-retry-exhausted"===e.name?console[t](r,e.error):console[t](r)},noBeaconEndpoint(){console.warn(Y+" Report endpoint is not configured")},noFallbackConfigured(){console.error(Y+" No fallback UI configured")},reloadAlreadyScheduled(e){console.log(Y+" Reload already scheduled, ignoring duplicate chunk error:",e)},retryCycleStarting(e,t){console.log(`${Y} Retry cycle starting: retryId=${e}, fromAttempt=${t}`)},retrySchedulingReload(e,t,r){console.log(`${Y} Scheduling reload: retryId=${e}, attempt=${t}, delay=${r}ms`)},versionChangeDetected(e,t){console.warn(`${Y} New version available (${e??"unknown"} → ${t}). Please refresh to get the latest version.`)},versionCheckAlreadyRunning(){console.warn(Y+" Version check already running")},versionCheckDisabled(){console.warn(Y+" Version checking disabled: no version configured")},versionCheckFailed(e){console.error(Y+" Version check failed",e)},versionCheckHttpError(e){console.warn(`${Y} Version check HTTP error: ${e}`)},versionCheckParseError(){console.warn(Y+" Failed to parse version from HTML")},versionCheckPaused(){console.log(Y+" Version check paused (tab hidden)")},versionCheckRequiresEndpoint(){console.warn(Y+" JSON version check mode requires endpoint")},versionCheckResumed(){console.log(Y+" Version check resumed (tab visible)")},versionCheckResumedImmediate(){console.log(Y+" Version check resumed with immediate check (tab visible, interval elapsed)")},versionCheckStarted(e,t,r){console.log(`${Y} Starting version check (mode: ${e}, interval: ${t}ms, current: ${r})`)},versionCheckStopped(){console.log(Y+" Version check stopped")},warn(e,...t){console.warn(`${Y} ${e}`,...t)}});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ovineko/spa-guard-node",
3
- "version": "0.0.1-alpha-30",
3
+ "version": "0.0.2-alpha-0",
4
4
  "description": "Server-side HTML cache with ETag/304, pre-compression, and i18n for spa-guard",
5
5
  "keywords": [
6
6
  "spa",
@@ -47,7 +47,7 @@
47
47
  },
48
48
  "peerDependencies": {
49
49
  "parse5": "^8",
50
- "@ovineko/spa-guard": "0.0.1-alpha-30"
50
+ "@ovineko/spa-guard": "0.0.2-alpha-0"
51
51
  },
52
52
  "engines": {
53
53
  "node": ">=22.15.0"