@ovineko/spa-guard-node 0.0.2-alpha-0 → 0.0.3-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.
package/dist-inline/index.js
CHANGED
|
@@ -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 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
|
+
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"),g=(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 m=globalThis.window?.[a]??new Set,f=globalThis.window?.[o]??{defaultRetryEnabled:!0,initialized:!1},p=()=>globalThis.window?.[l],y=(e,r)=>{r?.silent||p()?.logEvent(e),m.forEach(r=>{try{r(e)}catch{}})};function h(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")}function b(){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}}((r,t)=>{for(var a in t)e(r,a,{get:t[a],enumerable:!0})})({},{getOptions:()=>v,optionsWindowKey:()=>t});var w={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}.spa-guard-fallback-root{display:flex;align-items:center;justify-content:center;min-height:100vh;padding:2rem;font-family:system-ui,sans-serif;background:#fff;color:#1a1a1a;color-scheme:light dark}.spa-guard-fallback-icon{stroke:#b0b0b0}.spa-guard-fallback-message{color:#666}.spa-guard-fallback-muted{color:#999}.spa-guard-btn-secondary{border:1px solid #d0d0d0;background:#fff;color:#333}.spa-guard-btn-primary{border:1px solid transparent;background:#111;color:#fff}@media (prefers-color-scheme:dark){.spa-guard-fallback-root{background:#111318;color:#e7eaf0}.spa-guard-fallback-icon{stroke:#8b95a7}.spa-guard-fallback-message{color:#b8bfca}.spa-guard-fallback-muted{color:#8b95a7}.spa-guard-btn-secondary{border-color:#3b4351;background:#1a1f28;color:#d8deea}.spa-guard-btn-primary{background:#e7eaf0;color:#151922}}</style><div class="spa-guard-fallback-root"><div style="text-align:center;max-width:480px"><div style="margin-bottom:1.5rem"><svg class="spa-guard-fallback-icon" xmlns="http://www.w3.org/2000/svg" width="48" height="48" fill="none" viewBox="0 0 24 24" 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;line-height:1.3">Something went wrong</h1><p data-spa-guard-content="message" class="spa-guard-fallback-message" style="max-width:600px;margin:0 auto 1.5rem;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" class="spa-guard-btn-secondary" style="display:none;padding:.5rem 1.25rem;font-size:.875rem;font-family:inherit;border-radius:6px;cursor:pointer;line-height:1.5">Try again</button> <button data-spa-guard-action="reload" type="button" class="spa-guard-btn-primary" style="padding:.5rem 1.25rem;font-size:.875rem;font-family:inherit;border-radius:6px;cursor:pointer;line-height:1.5">Reload page</button></div><p class="spa-guard-error-id spa-guard-fallback-muted" style="margin-top:1.5rem;font-size:.6875rem">Error ID: <span class="spa-guard-retry-id"></span></p></div></div>',selector:"body"},loading:{content:'<style>.spa-guard-loading-root{display:flex;align-items:center;justify-content:center;min-height:100vh;padding:2rem;font-family:system-ui,sans-serif;background:#fff;color:#1a1a1a;color-scheme:light dark}.spa-guard-loading-muted{color:#999}@media (prefers-color-scheme:dark){.spa-guard-loading-root{background:#111318;color:#e7eaf0}.spa-guard-loading-muted{color:#8b95a7}}</style><div class="spa-guard-loading-root"><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">Loading...</h2><p data-spa-guard-section="retrying" class="spa-guard-loading-muted" style="display:none;font-size:.8125rem;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?.[t];return{...w,...e,checkVersion:{...w.checkVersion,...e?.checkVersion},errors:{...w.errors,...e?.errors},handleUnhandledRejections:{...w.handleUnhandledRejections,...e?.handleUnhandledRejections},html:{fallback:{...w.html?.fallback,...e?.html?.fallback},loading:{...w.html?.loading,...e?.html?.loading},spinner:{...w.html?.spinner,...e?.html?.spinner}},lazyRetry:{...w.lazyRetry,...e?.lazyRetry},reportBeacon:{...w.reportBeacon,...e?.reportBeacon},staticAssets:{...w.staticAssets,...e?.staticAssets}}},T="__SPA_GUARD_FORCE_RETRY__",S=()=>{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)}`},R=()=>{let e=S();return e?{retryAttempt:e.retryAttempt,retryId:e.retryId}:{}},I="__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(I);if(e)return JSON.parse(e)}catch{try{sessionStorage.removeItem(I)}catch{}return E().storage}return E().storage},x=e=>{let r=(v().errors?.ignore??[]).filter(e=>""!==e);return 0!==r.length&&e.filter(e=>"string"==typeof e).some(e=>r.some(r=>e.includes(r)))},D=e=>{let r=[...v().errors?.forceRetry??[],T].filter(e=>""!==e);return e.filter(e=>"string"==typeof e).some(e=>r.some(r=>e.includes(r)))},L=e=>{if((e=>x([e.errorMessage,e.eventMessage]))(e))return;let r=v();if(!r.reportBeacon?.endpoint)return void p()?.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=>{p()?.beaconSendFailed(e)})},z=Symbol.for(r+":retry-orchestrator"),U=e=>{if(void 0===globalThis.window)return;let r=globalThis.window;r[z]||(r[z]={attempt:0,lastSource:void 0,lastTriggerTime:void 0,phase:"idle",retryId:null,timer:null}),Object.assign(r[z],e)},M=()=>{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)}},j=(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[z]||(e[z]={attempt:0,lastSource:void 0,lastTriggerTime:void 0,phase:"idle",retryId:null,timer:null}),e[z]})();if("fallback"===r.phase||void 0!==globalThis.window&&!0===globalThis.window[g])return p()?.fallbackAlreadyShown(e.error),{status:"fallback"};if("scheduled"===r.phase)return p()?.reloadAlreadyScheduled(e.error),{reason:"already-scheduled",status:"deduped"};if(!f.defaultRetryEnabled)return{status:"retry-disabled"};U({lastSource:e.source,lastTriggerTime:Date.now(),phase:"scheduled"});try{let r=v(),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,m=a&&c?c:k();if(p()?.retryCycleStarting(m,u),o&&c&&null!==l&&l>0&&((e,r,t=5e3)=>{if(0===e.retryAttempt)return!1;let a=N();if(!a||a.retryId!==e.retryId)return!1;let o=(()=>{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!(o&&Date.now()-o.timestamp<t)&&Date.now()-a.timestamp>(r[a.attemptNumber-1]??1e3)+3e4})({retryAttempt:l,retryId:c},t,n)){let r=N(),t=r?Date.now()-r.timestamp:0;M(),(()=>{if(_())try{sessionStorage.removeItem(I)}catch{}E().storage=null})(),(e=>{let r={previousRetryId:e,timestamp:Date.now()};if(_())try{sessionStorage.setItem(A,JSON.stringify(r))}catch{E().resetInfo=r}else E().resetInfo=r})(c);let a=e.error+"";y({name:"retry-reset",previousAttempt:l,previousRetryId:c,timeSinceReload:t},{silent:x([a])}),u=0,m=k()}if(y({error:e.error,isRetrying:u<t.length,name:"chunk-error"}),u>=t.length){let r=e.error+"";return y({finalAttempt:u,name:"retry-exhausted",retryId:m},{silent:x([r])}),L({errorMessage:"Exceeded maximum reload attempts",eventName:"chunk_error_max_reloads",retryAttempt:u,retryId:m,serialized:JSON.stringify({error:e.error+"",retryAttempt:u,retryId:m})}),U({attempt:u,phase:"fallback",retryId:m}),void 0!==globalThis.window&&(globalThis.window[g]=!0),M(),(e=>{let r=v(),t=r.html?.fallback?.content,a=r.html?.fallback?.selector??"body";if(!t)return p()?.noFallbackConfigured(),void y({name:"fallback-ui-not-rendered",reason:"no-html-configured"});try{let r=document.querySelector(a);if(!r)return p()?.fallbackTargetNotFound(a),void y({name:"fallback-ui-not-rendered",reason:"target-not-found",selector:a});let o=document.createElement("div");o.innerHTML=t;let n=b();n&&h(o,n),r.innerHTML=o.innerHTML;let l=r.querySelector('[data-spa-guard-action="reload"]');l&&l.addEventListener("click",()=>globalThis.window.location.reload());let i=e?.retryId??S()?.retryId;if(i){let e=document.getElementsByClassName("spa-guard-retry-id");for(let r of e)r.textContent=i}y({name:"fallback-ui-shown"})}catch(e){p()?.fallbackInjectFailed(e)}})({retryId:m}),{status:"fallback"}}let f=u+1,w=t[u]??1e3,T=e.error+"";y({attempt:f,delay:w,name:"retry-attempt",retryId:m},{silent:x([T])}),p()?.retrySchedulingReload(m,f,w),U({attempt:f,retryId:m}),(e=>{let r=v(),t=r.html?.loading?.content;if(!t)return;let a=r.html?.fallback?.selector??"body";try{let o=document.querySelector(a);if(!o)return;let n=document.createElement("div");n.innerHTML=t;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 r of s)r.textContent=e+"";let d=o.querySelector("[data-spa-guard-spinner]");if(d){let e=r.html?.spinner;e?.disabled?d.style.display="none":e?.content&&(d.innerHTML=e.content)}}catch{}})(f);let R=setTimeout(()=>{try{a&&o&&((e,r)=>{let t={attemptNumber:r,retryId:e,timestamp:Date.now()};if(_())try{sessionStorage.setItem(I,JSON.stringify(t))}catch{E().storage=t}else E().storage=t})(m,f);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()})(m,f,e.cacheBust,a);globalThis.window.location.href=r}catch(e){p()?.error("triggerRetry navigation failed",e),U({phase:"idle",timer:null})}},w);return U({timer:R}),{status:"accepted"}}catch(e){return p()?.error("triggerRetry internal error",e),U({lastSource:void 0,lastTriggerTime:void 0,phase:"idle"}),{status:"internal-error"}}},B=e=>{let r=O(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))},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 r=new URL(e).pathname;return P.test(r)}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||f.initialized)return;f.initialized=!0,void 0!==globalThis.window&&(globalThis.window[n]=!0);let e=globalThis.window.addEventListener.bind(globalThis.window);e("error",e=>{let r=(e=>{let r=e.target;return r instanceof HTMLScriptElement?r.src:r instanceof HTMLLinkElement?r.href:""})(e);if((e=>{let r=e.target;return r instanceof HTMLScriptElement?C(r.src):r instanceof HTMLLinkElement&&C(r.href)})(e)&&(void 0!==(t=r)?(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})(t):(typeof performance>"u"?0:performance.now())>3e4)){if(x([r,e.message]))return;return e.preventDefault(),y({name:"static-asset-load-failed",url:r}),void(!1!==v().staticAssets?.autoRecover&&(e=>{if(void 0===globalThis.window)return;let r=H();if(r.failedAssets.add(e),null!==r.recoveryTimer)return;let t=v().staticAssets?.recoveryDelay??500;r.recoveryTimer=setTimeout(()=>{let e=H();e.recoveryTimer=null;let r=[...e.failedAssets];e.failedAssets=new Set;let t=Error("Static asset load failed: "+r.join(", "));j({cacheBust:!0,error:t,source:"static-asset-error"})},t)})(r))}var t;if(!x([e.message]))return p()?.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:"",...R()})},!0),e("unhandledrejection",e=>{let r=e.reason+"";if(x([r]))return;if(p()?.capturedError("unhandledrejection",e),B(e.reason))return e.preventDefault(),void j({error:e.reason,source:"chunk-error"});if(D([r]))return e.preventDefault(),void j({error:e.reason,source:"force-retry"});let t=v().handleUnhandledRejections;!1!==t?.sendBeacon&&L({errorMessage:r,eventName:"unhandledrejection",serialized:"",...R()}),!1!==t?.retry&&(e.preventDefault(),j({error:e.reason,source:"unhandled-rejection"}))}),e("securitypolicyviolation",e=>{let r=`${e.violatedDirective}: ${e.blockedURI}`;x([r])||(p()?.capturedError("csp",e.blockedURI,e.violatedDirective),L({eventMessage:r,eventName:"securitypolicyviolation",serialized:"",...R()}))}),e("vite:preloadError",e=>{let r=e?.payload;x([r?.message||e?.message])||(p()?.capturedError("vite:preloadError",e),e.preventDefault(),j({error:r??e,source:"vite:preloadError"}))})})();
|
|
@@ -1 +1 @@
|
|
|
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)}});
|
|
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"),s="spaGuardRetryId",i="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{}})};function h(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")}function b(){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}}((r,t)=>{for(var a in t)e(r,a,{get:t[a],enumerable:!0})})({},{getOptions:()=>w,optionsWindowKey:()=>t});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}.spa-guard-fallback-root{display:flex;align-items:center;justify-content:center;min-height:100vh;padding:2rem;font-family:system-ui,sans-serif;background:#fff;color:#1a1a1a;color-scheme:light dark}.spa-guard-fallback-icon{stroke:#b0b0b0}.spa-guard-fallback-message{color:#666}.spa-guard-fallback-muted{color:#999}.spa-guard-btn-secondary{border:1px solid #d0d0d0;background:#fff;color:#333}.spa-guard-btn-primary{border:1px solid transparent;background:#111;color:#fff}@media (prefers-color-scheme:dark){.spa-guard-fallback-root{background:#111318;color:#e7eaf0}.spa-guard-fallback-icon{stroke:#8b95a7}.spa-guard-fallback-message{color:#b8bfca}.spa-guard-fallback-muted{color:#8b95a7}.spa-guard-btn-secondary{border-color:#3b4351;background:#1a1f28;color:#d8deea}.spa-guard-btn-primary{background:#e7eaf0;color:#151922}}</style><div class="spa-guard-fallback-root"><div style="text-align:center;max-width:480px"><div style="margin-bottom:1.5rem"><svg class="spa-guard-fallback-icon" xmlns="http://www.w3.org/2000/svg" width="48" height="48" fill="none" viewBox="0 0 24 24" 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;line-height:1.3">Something went wrong</h1><p data-spa-guard-content="message" class="spa-guard-fallback-message" style="max-width:600px;margin:0 auto 1.5rem;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" class="spa-guard-btn-secondary" style="display:none;padding:.5rem 1.25rem;font-size:.875rem;font-family:inherit;border-radius:6px;cursor:pointer;line-height:1.5">Try again</button> <button data-spa-guard-action="reload" type="button" class="spa-guard-btn-primary" style="padding:.5rem 1.25rem;font-size:.875rem;font-family:inherit;border-radius:6px;cursor:pointer;line-height:1.5">Reload page</button></div><p class="spa-guard-error-id spa-guard-fallback-muted" style="margin-top:1.5rem;font-size:.6875rem">Error ID: <span class="spa-guard-retry-id"></span></p></div></div>',selector:"body"},loading:{content:'<style>.spa-guard-loading-root{display:flex;align-items:center;justify-content:center;min-height:100vh;padding:2rem;font-family:system-ui,sans-serif;background:#fff;color:#1a1a1a;color-scheme:light dark}.spa-guard-loading-muted{color:#999}@media (prefers-color-scheme:dark){.spa-guard-loading-root{background:#111318;color:#e7eaf0}.spa-guard-loading-muted{color:#8b95a7}}</style><div class="spa-guard-loading-root"><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">Loading...</h2><p data-spa-guard-section="retrying" class="spa-guard-loading-muted" style="display:none;font-size:.8125rem;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?.[t];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),r=e.get(s),t=e.get(i);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}},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 r=(w().errors?.ignore??[]).filter(e=>""!==e);return 0!==r.length&&e.filter(e=>"string"==typeof e).some(e=>r.some(r=>e.includes(r)))},j=e=>{let r=[...w().errors?.forceRetry??[],k].filter(e=>""!==e);return e.filter(e=>"string"==typeof e).some(e=>r.some(r=>e.includes(r)))},D=e=>{if((e=>x([e.errorMessage,e.eventMessage]))(e))return;let r=w();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)})},z=Symbol.for(r+":retry-orchestrator"),L=e=>{if(void 0===globalThis.window)return;let r=globalThis.window;r[z]||(r[z]={attempt:0,lastSource:void 0,lastTriggerTime:void 0,phase:"idle",retryId:null,timer:null}),Object.assign(r[z],e)},U=()=>{try{let e=new URL(globalThis.window.location.href);e.searchParams.delete(s),e.searchParams.delete(i),e.searchParams.delete(d),globalThis.window.history.replaceState(null,"",e.toString())}catch(e){f()?.error("clearRetryFromUrl failed",e)}},_=(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[z]||(e[z]={attempt:0,lastSource:void 0,lastTriggerTime:void 0,phase:"idle",retryId:null,timer:null}),e[z]})();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"};L({lastSource:e.source,lastTriggerTime:Date.now(),phase:"scheduled"});try{let r=w(),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(i);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(s)}catch{return null}})(),u=l??0,y=a&&c?c:S();if(f()?.retryCycleStarting(y,u),o&&c&&null!==l&&l>0&&((e,r,t=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<t)&&Date.now()-a.timestamp>(r[a.attemptNumber-1]??1e3)+3e4})({retryAttempt:l,retryId:c},t,n)){let r=N(),t=r?Date.now()-r.timestamp:0;U(),(()=>{if(A())try{sessionStorage.removeItem(I)}catch{}E().storage=null})(),(e=>{let r={previousRetryId:e,timestamp:Date.now()};if(A())try{sessionStorage.setItem($,JSON.stringify(r))}catch{E().resetInfo=r}else E().resetInfo=r})(c);let a=e.error+"";p({name:"retry-reset",previousAttempt:l,previousRetryId:c,timeSinceReload:t},{silent:x([a])}),u=0,y=S()}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:x([r])}),D({errorMessage:"Exceeded maximum reload attempts",eventName:"chunk_error_max_reloads",retryAttempt:u,retryId:y,serialized:JSON.stringify({error:e.error+"",retryAttempt:u,retryId:y})}),L({attempt:u,phase:"fallback",retryId:y}),void 0!==globalThis.window&&(globalThis.window[m]=!0),U(),(e=>{let r=w(),t=r.html?.fallback?.content,a=r.html?.fallback?.selector??"body";if(!t)return f()?.noFallbackConfigured(),void p({name:"fallback-ui-not-rendered",reason:"no-html-configured"});try{let r=document.querySelector(a);if(!r)return f()?.fallbackTargetNotFound(a),void p({name:"fallback-ui-not-rendered",reason:"target-not-found",selector:a});let o=document.createElement("div");o.innerHTML=t;let n=b();n&&h(o,n),r.innerHTML=o.innerHTML;let l=r.querySelector('[data-spa-guard-action="reload"]');l&&l.addEventListener("click",()=>globalThis.window.location.reload());let s=e?.retryId??T()?.retryId;if(s){let e=document.getElementsByClassName("spa-guard-retry-id");for(let r of e)r.textContent=s}p({name:"fallback-ui-shown"})}catch(e){f()?.fallbackInjectFailed(e)}})({retryId:y}),{status:"fallback"}}let g=u+1,v=t[u]??1e3,k=e.error+"";p({attempt:g,delay:v,name:"retry-attempt",retryId:y},{silent:x([k])}),f()?.retrySchedulingReload(y,g,v),L({attempt:g,retryId:y}),(e=>{let r=w(),t=r.html?.loading?.content;if(!t)return;let a=r.html?.fallback?.selector??"body";try{let o=document.querySelector(a);if(!o)return;let n=document.createElement("div");n.innerHTML=t;let l=b();l&&h(n,l),o.innerHTML=n.innerHTML;let s=o.querySelector('[data-spa-guard-section="retrying"]');if(s){let e=s;e.style.display="",e.style.visibility="visible"}let i=o.querySelectorAll('[data-spa-guard-content="attempt"]');for(let r of i)r.textContent=e+"";let d=o.querySelector("[data-spa-guard-spinner]");if(d){let e=r.html?.spinner;e?.disabled?d.style.display="none":e?.content&&(d.innerHTML=e.content)}}catch{}})(g);let R=setTimeout(()=>{try{a&&o&&((e,r)=>{let t={attemptNumber:r,retryId:e,timestamp:Date.now()};if(A())try{sessionStorage.setItem(I,JSON.stringify(t))}catch{E().storage=t}else E().storage=t})(y,g);let r=((e,r,t,a=!0)=>{let o=new URL(globalThis.window.location.href);return a&&o.searchParams.set(s,e),o.searchParams.set(i,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),L({phase:"idle",timer:null})}},v);return L({timer:R}),{status:"accepted"}}catch(e){return f()?.error("triggerRetry internal error",e),L({lastSource:void 0,lastTriggerTime:void 0,phase:"idle"}),{status:"internal-error"}}},C=e=>{let r=M(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))},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 r=e,t=r.reason,a=typeof window<"u"&&"string"==typeof window.location?.href?window.location.href:void 0;return{constructorName:t?.constructor?.name,isTrusted:r.isTrusted,pageUrl:a,reason:F(t,new WeakSet,0),timeStamp:r.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 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:V(r.target),timeStamp:r.timeStamp,type:"Event"}}return{type:"object",value:J(e)}},F=(e,r,t)=>{if(null==e)return{type:"null",value:e};if("object"!=typeof e)return{type:typeof e,value:"string"==typeof e?O(e):e};if(r.has(e))return{type:"circular"};if(r.add(e),typeof AggregateError<"u"&&e instanceof AggregateError)return{errors:e.errors.slice(0,3).map(e=>B(e,r,t+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"};let a=e;if(null!=a.response){let e=a.response,r={type:"HttpError"};void 0!==e.status&&(r.status=e.status),void 0!==e.statusText&&(r.statusText="string"==typeof e.statusText?O(e.statusText):e.statusText),void 0!==e.url&&(r.url="string"==typeof e.url?O(e.url):e.url),void 0!==e.method&&(r.method=e.method),void 0!==e.type&&(r.responseType=e.type);try{let t=e.headers;if(t){let e;"function"==typeof t.get?e=t.get("X-Request-ID")??t.get("x-request-id"):"object"==typeof t&&(e=t["X-Request-ID"]??t["x-request-id"]),e&&(r.xRequestId=O(e+""))}}catch{}let t=a.config??a.request;if(null!=t){let e={};void 0!==t.method&&(e.method=t.method),void 0!==t.url&&(e.url="string"==typeof t.url?O(t.url):t.url),void 0!==t.baseURL&&(e.baseURL="string"==typeof t.baseURL?O(t.baseURL):t.baseURL),r.request=e}return r}return e instanceof Error?B(e,r,t):{type:"object",value:q(a,r,t)}},B=(e,r,t)=>{if(!(e instanceof Error))return F(e,r,t+1);let a={message:O(e.message),name:e.name,stack:e.stack?O(e.stack):void 0,type:"Error"};if(t<4&&void 0!==e.cause){let o=e.cause;"object"==typeof o&&null!==o?r.has(o)||(a.cause=F(o,r,t+1)):a.cause=o}return a},q=(e,r,t)=>{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:t<4&&!r.has(o)?(r.add(o),a[n]=q(o,r,t+1)):a[n]="[object]"}catch{}o++}return a},H=e=>{let r={},t=0;for(let a of Object.getOwnPropertyNames(e)){if(t>=20)break;if(!["message","name","stack"].includes(a)){try{let t=e[a];r[a]=null==t||"object"!=typeof t?"string"==typeof t?O(t):t:"[object]"}catch{}t++}}return r},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 r={},t=0;for(let a of Object.keys(e)){if(t>=20)break;try{let t=e[a];r[a]=null==t||"object"!=typeof t?"string"==typeof t?O(t):t:"[object]"}catch{}t++}return r},G=/[-._][a-zA-Z0-9]{6,}\.(js|mjs|css)$/i,W=e=>{try{let r=new URL(e).pathname;return G.test(r)}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,r)=>{if(void 0===globalThis.window||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=globalThis.window.addEventListener.bind(globalThis.window);t("error",r=>{let t=(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?W(r.src):r instanceof HTMLLinkElement&&W(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)(t)){if(x([t,r.message]))return;return r.preventDefault(),p({name:"static-asset-load-failed",url:t}),void(!1!==w().staticAssets?.autoRecover&&(e=>{if(void 0===globalThis.window)return;let r=X();if(r.failedAssets.add(e),null!==r.recoveryTimer)return;let t=w().staticAssets?.recoveryDelay??500;r.recoveryTimer=setTimeout(()=>{let e=X();e.recoveryTimer=null;let r=[...e.failedAssets];e.failedAssets=new Set;let t=Error("Static asset load failed: "+r.join(", "));_({cacheBust:!0,error:t,source:"static-asset-error"})},t)})(t))}if(x([r.message]))return;if(f()?.capturedError("error",r),C(r))return r.preventDefault(),void _({error:r.error??r,source:"chunk-error"});if(j([r.message]))return r.preventDefault(),void _({error:r.error??r,source:"force-retry"});let a=e(r);D({errorMessage:r.message,eventName:"error",serialized:a,...R()})},!0),t("unhandledrejection",r=>{let t=r.reason+"";if(x([t]))return;if(f()?.capturedError("unhandledrejection",r),C(r.reason))return r.preventDefault(),void _({error:r.reason,source:"chunk-error"});if(j([t]))return r.preventDefault(),void _({error:r.reason,source:"force-retry"});let a=w().handleUnhandledRejections;if(!1!==a?.sendBeacon){let a=e(r);D({errorMessage:t,eventName:"unhandledrejection",serialized:a,...R()})}!1!==a?.retry&&(r.preventDefault(),_({error:r.reason,source:"unhandled-rejection"}))}),t("securitypolicyviolation",r=>{let t=`${r.violatedDirective}: ${r.blockedURI}`;if(x([t]))return;f()?.capturedError("csp",r.blockedURI,r.violatedDirective);let a=e(r);D({eventMessage:t,eventName:"securitypolicyviolation",serialized:a,...R()})}),t("vite:preloadError",e=>{let r=e?.payload;x([r?.message||e?.message])||(f()?.capturedError("vite:preloadError",e),e.preventDefault(),_({error:r??e,source:"vite:preloadError"}))})})(e=>{try{let r=P(e);return JSON.stringify(r,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,...r){console.error(`${Y} ${e}:capture:`,...r)},error(e,...r){console.error(`${Y} ${e}`,...r)},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,...r){console.log(`${Y} ${e}`,...r)},logEvent(e){let r=K[e.name],t=(e=>{switch(e.name){case"chunk-error":return`${Y} chunk-error: isRetrying=${e.isRetrying}`;case"fallback-ui-not-rendered":{let r=e.selector?" selector="+e.selector:"";return`${Y} fallback-ui-not-rendered: reason=${e.reason}${r}`}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 r=void 0===e.totalTime?"":`, totalTime=${e.totalTime}ms`;return`${Y} lazy-retry-success: succeeded on attempt ${e.attempt}${r}`}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[r](t,e.error):console[r](t)},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,r){console.log(`${Y} Retry cycle starting: retryId=${e}, fromAttempt=${r}`)},retrySchedulingReload(e,r,t){console.log(`${Y} Scheduling reload: retryId=${e}, attempt=${r}, delay=${t}ms`)},versionChangeDetected(e,r){console.warn(`${Y} New version available (${e??"unknown"} → ${r}). 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,r,t){console.log(`${Y} Starting version check (mode: ${e}, interval: ${r}ms, current: ${t})`)},versionCheckStopped(){console.log(Y+" Version check stopped")},warn(e,...r){console.warn(`${Y} ${e}`,...r)}});
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ovineko/spa-guard-node",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.3-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.
|
|
50
|
+
"@ovineko/spa-guard": "0.0.3-alpha-0"
|
|
51
51
|
},
|
|
52
52
|
"engines": {
|
|
53
53
|
"node": ">=22.15.0"
|