@drupflare/spool 0.2.0 → 0.4.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/README.md +499 -43
- package/dist/cdn/client.js +1 -1
- package/dist/cdn/manifest.json +7 -7
- package/dist/cdn/spool-sw.js +1 -1
- package/dist/client/activity.d.ts +37 -0
- package/dist/client/activity.js +114 -0
- package/dist/client/entry.js +34 -1
- package/dist/client/index.d.ts +1 -0
- package/dist/client/index.js +1 -0
- package/dist/client/register.d.ts +23 -1
- package/dist/client/register.js +53 -7
- package/dist/media/embeds.d.ts +3 -2
- package/dist/media/embeds.js +16 -1
- package/dist/protocol/config.d.ts +16 -1
- package/dist/protocol/config.js +3 -1
- package/dist/protocol/dataset.d.ts +183 -0
- package/dist/protocol/dataset.js +206 -0
- package/dist/protocol/envelope.d.ts +3 -0
- package/dist/protocol/envelope.js +14 -3
- package/dist/protocol/errors.d.ts +1 -1
- package/dist/protocol/graph.d.ts +23 -4
- package/dist/protocol/graph.js +34 -3
- package/dist/protocol/hash.d.ts +2 -0
- package/dist/protocol/hash.js +8 -0
- package/dist/protocol/index.d.ts +7 -0
- package/dist/protocol/index.js +7 -0
- package/dist/protocol/inline.d.ts +14 -0
- package/dist/protocol/inline.js +43 -0
- package/dist/protocol/navigation.d.ts +81 -0
- package/dist/protocol/navigation.js +249 -0
- package/dist/protocol/normalise.d.ts +4 -3
- package/dist/protocol/normalise.js +6 -4
- package/dist/protocol/plan.d.ts +100 -0
- package/dist/protocol/plan.js +661 -0
- package/dist/protocol/provision.d.ts +52 -1
- package/dist/protocol/provision.js +53 -5
- package/dist/protocol/query.d.ts +141 -0
- package/dist/protocol/query.js +252 -0
- package/dist/protocol/route.d.ts +85 -5
- package/dist/protocol/route.js +91 -0
- package/dist/protocol/write.d.ts +146 -0
- package/dist/protocol/write.js +101 -0
- package/dist/proxy/bases.d.ts +53 -0
- package/dist/proxy/bases.js +76 -0
- package/dist/proxy/index.d.ts +1 -0
- package/dist/proxy/index.js +1 -0
- package/dist/proxy/proxy.js +8 -2
- package/dist/report/capacity.d.ts +59 -0
- package/dist/report/capacity.js +76 -0
- package/dist/report/channels.d.ts +60 -0
- package/dist/report/channels.js +65 -0
- package/dist/report/dataset.d.ts +48 -0
- package/dist/report/dataset.js +93 -0
- package/dist/report/derive.d.ts +285 -0
- package/dist/report/derive.js +676 -1
- package/dist/report/economics.d.ts +11 -1
- package/dist/report/economics.js +19 -1
- package/dist/report/index.d.ts +5 -0
- package/dist/report/index.js +5 -0
- package/dist/report/inputs.d.ts +97 -0
- package/dist/report/inputs.js +133 -0
- package/dist/report/institution.d.ts +284 -0
- package/dist/report/institution.js +225 -0
- package/dist/report/ledger.d.ts +28 -0
- package/dist/report/ledger.js +30 -0
- package/dist/report/loops.d.ts +73 -0
- package/dist/report/loops.js +101 -0
- package/dist/report/measurement.d.ts +1 -1
- package/dist/report/measurement.js +6 -1
- package/dist/report/model.d.ts +2 -0
- package/dist/report/model.js +4 -0
- package/dist/report/thirdparty.d.ts +57 -0
- package/dist/report/thirdparty.js +111 -0
- package/dist/report/traffic.d.ts +11 -2
- package/dist/report/traffic.js +13 -3
- package/dist/report/trim.d.ts +56 -0
- package/dist/report/trim.js +83 -1
- package/dist/server/dataset.d.ts +48 -0
- package/dist/server/dataset.js +308 -0
- package/dist/server/embedded.d.ts +3 -3
- package/dist/server/embedded.js +3 -3
- package/dist/server/index.d.ts +3 -0
- package/dist/server/index.js +3 -0
- package/dist/server/spool.d.ts +40 -0
- package/dist/server/spool.js +184 -23
- package/dist/server/write.d.ts +27 -0
- package/dist/server/write.js +127 -0
- package/dist/sw/analytics.d.ts +6 -0
- package/dist/sw/analytics.js +14 -0
- package/dist/sw/dataset-sync.d.ts +76 -0
- package/dist/sw/dataset-sync.js +149 -0
- package/dist/sw/dataset.d.ts +91 -0
- package/dist/sw/dataset.js +318 -0
- package/dist/sw/graph/index.d.ts +31 -1
- package/dist/sw/graph/index.js +57 -5
- package/dist/sw/graph/invalidate.d.ts +15 -3
- package/dist/sw/graph/invalidate.js +42 -4
- package/dist/sw/idb.js +78 -9
- package/dist/sw/partition.d.ts +6 -1
- package/dist/sw/partition.js +21 -2
- package/dist/sw/principal-dataset.d.ts +64 -0
- package/dist/sw/principal-dataset.js +254 -0
- package/dist/sw/render.d.ts +8 -1
- package/dist/sw/render.js +28 -1
- package/dist/sw/replica.d.ts +14 -3
- package/dist/sw/replica.js +46 -5
- package/dist/sw/router.js +2 -2
- package/dist/sw/runtime.d.ts +43 -2
- package/dist/sw/runtime.js +440 -29
- package/dist/sw/seal.d.ts +13 -0
- package/dist/sw/seal.js +13 -4
- package/dist/sw/static.d.ts +18 -0
- package/dist/sw/static.js +84 -1
- package/dist/sw/storage.d.ts +51 -1
- package/dist/sw/storage.js +33 -1
- package/dist/sw/write.d.ts +107 -0
- package/dist/sw/write.js +442 -0
- package/package.json +5 -2
package/dist/cdn/client.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
(()=>{var
|
|
1
|
+
(()=>{var R="data-spool-client";function v(e=k()){return{register(t,r={}){let i=r.hiddenAfterMs??1e4,n=!0,o=!1,a=!1,u=!1,d=!1,p=null,f=(g)=>{try{t[g]()}catch(L){if(!d)d=!0,console.warn("spool.activity",L)}},s=()=>{if(u)return;let g=!n||o;if(g===a)return;a=g,f(g?"pause":"resume")},c=()=>{if(p===null)return;e.clearTimeout(p),p=null},l=()=>{if(u)return;if(!e.hidden()){c(),o=!1,s();return}if(o||p!==null)return;if(i<=0){o=!0,s();return}p=e.setTimeout(()=>{if(p=null,e.hidden())o=!0,s()},i)},m=e.onVisibilityChange(l),h=r.target?e.observe(r.target,(g)=>{n=g,s()}):()=>{return};return l(),()=>{if(u)return;if(u=!0,c(),m(),h(),a)a=!1,f("resume")}}}}function k(){return{hidden:()=>document.hidden,onVisibilityChange(e){return document.addEventListener("visibilitychange",e),()=>document.removeEventListener("visibilitychange",e)},observe(e,t){if(typeof IntersectionObserver>"u")return t(!0),()=>{return};let r=new IntersectionObserver((i)=>{let n=i.at(-1);if(n)t(n.isIntersecting||n.intersectionRatio>0)},{threshold:0});return r.observe(e),()=>r.disconnect()},setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:(e)=>clearTimeout(e)}}function x(e,t,r=[]){let i=0;for(let{name:n}of e){if(r.includes(n))continue;try{if(new URL(n).origin!==t)i+=1}catch{continue}}return i}function S(e,t,r=[],i=32){let n=new Map;for(let{name:o}of e){if(r.includes(o))continue;try{let a=new URL(o).origin;if(a!==t&&a!=="null")n.set(a,(n.get(a)??0)+1)}catch{continue}}return Object.fromEntries([...n].sort((o,a)=>a[1]-o[1]||(o[0]<a[0]?-1:1)).slice(0,i))}var F=1n<<256n,D="0".repeat(64);var P=1;var j={sync:"/.spool/sync",artifact:"/.spool/artifact",dataset:"/.spool/dataset",beacon:"/.spool/beacon",write:"/.spool/write",worker:"/spool-sw.js"};function E(e,t=window){let r=()=>e.close();return t.addEventListener("pagehide",r),()=>t.removeEventListener("pagehide",r)}var A=30000;function w(e,t,r){return new Promise((i,n)=>{let o=new MessageChannel,a=setTimeout(()=>{o.port1.close(),n(Error("the worker did not answer"))},r);o.port1.onmessage=(u)=>{clearTimeout(a),o.port1.close(),i(u.data)},e.postMessage(t,[o.port2])})}async function T(e={}){let t=e.container??navigator.serviceWorker;if(!t)return null;let r=e.helloTimeoutMs??5000,i=null,n=!1,o,a=async()=>{if(n)return;n=!0;let s=e.storage??navigator.storage;try{i=await s?.persisted?.()===!0||await s?.persist?.()===!0}catch{i=!1}(e.target??window).dispatchEvent(new CustomEvent("spool:persisted",{detail:{granted:i}})),(o??t.controller)?.postMessage({type:"spool:persisted",granted:i})};t.addEventListener?.("message",(s)=>{let c=s.data;if(c?.type==="spool:persist")a();if(c?.type==="spool:written"){let{queued:l,flushed:m,conflicted:h}=c;(e.target??window).dispatchEvent(new CustomEvent("spool:written",{detail:{queued:l,flushed:m,conflicted:h}}))}if(c?.type!=="spool:cleared")return;(e.target??window).dispatchEvent(new CustomEvent("spool:cleared",{detail:{reason:c.reason}}))}),await t.register(e.workerUrl??j.worker,{scope:e.scope,updateViaCache:"all"});let u=await t.ready,d=u.active;if(!d)throw Error("the worker is not active");o=d;let p=await w(d,{type:"spool:hello",protocol:P},r),f=async(s,c=r)=>{try{let l=await w(u.active??d,s,c);if(l?.type===s.type)return l.result}catch{}return{ok:!1,code:"unavailable",message:"the worker did not answer"}};return{registration:u,hello:p,status:()=>w(u.active??d,{type:"spool:status"},r),view:async(s=location.pathname)=>(await w(u.active??d,{type:"spool:view",path:s},r)).id,reportLoads:(s,c,l)=>(u.active??d).postMessage({type:"spool:loads",view:s,count:c,origins:l}),persisted:()=>i,track:(s)=>E(s),write:(s,c,l,m)=>f({type:"spool:write",name:s,key:c,value:l,version:m}),flush:()=>f({type:"spool:flush"},Math.max(r,A)),writes:()=>f({type:"spool:writes"}),resolve:(s,c,l)=>f({type:"spool:resolve",name:s,key:c,use:l},Math.max(r,A))}}var y=T().catch(()=>null),b={ok:!1,code:"unavailable",message:"there is no worker on this page"},C=!1,M={write:async(...e)=>{let t=await y.then((r)=>r?.write(...e)??b);if(t.ok)C=!0;return t},flush:()=>y.then((e)=>e?.flush()??b),writes:()=>y.then((e)=>e?.writes()??b),resolve:(...e)=>y.then((t)=>t?.resolve(...e)??b)};globalThis.spool={ready:y,activity:v(k()),...M};var O=()=>{if(C)M.flush()};y.then((e)=>{if(!e)return;addEventListener("pagehide",O),document.addEventListener("visibilitychange",()=>{if(document.visibilityState==="hidden")O()})});y.then(async(e)=>{let t=await e?.view().catch(()=>null);if(!e||!t)return;let r=-1,i=()=>{let n=document.querySelector(`script[${R}]`)?.src,o=performance.getEntriesByType("resource"),a=x(o,location.origin,n?[n]:[]);if(a===r)return;r=a,e.reportLoads(t,a,S(o,location.origin,n?[n]:[]))};addEventListener("pagehide",i),document.addEventListener("visibilitychange",()=>{if(document.visibilityState==="hidden")i()})});})();
|
package/dist/cdn/manifest.json
CHANGED
|
@@ -1,16 +1,16 @@
|
|
|
1
1
|
{
|
|
2
2
|
"schema": 2,
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0",
|
|
4
4
|
"files": {
|
|
5
5
|
"client.js": {
|
|
6
|
-
"bytes":
|
|
7
|
-
"sha384": "
|
|
8
|
-
"integrity": "sha384-
|
|
6
|
+
"bytes": 4769,
|
|
7
|
+
"sha384": "1e5b2f9377a9b6a2aae6419e69bc67878fd9c4c0a5568c05c7340c7aaa9a0fc866d5e4f29b9130da711a218c5563240e",
|
|
8
|
+
"integrity": "sha384-Hlsvk3eptqKq5kGeabxnh4/ZxMClVowFxzQMeqqaD8hm1eTym5Ew2nEaIYxVYyQO"
|
|
9
9
|
},
|
|
10
10
|
"spool-sw.js": {
|
|
11
|
-
"bytes":
|
|
12
|
-
"sha384": "
|
|
13
|
-
"integrity": "sha384-
|
|
11
|
+
"bytes": 104735,
|
|
12
|
+
"sha384": "9a9a89745420549f1421d1201ab60bb4a723cfe6c3afad048a342d293082321f81716dd5dc44090c62801214a8d16a05",
|
|
13
|
+
"integrity": "sha384-mpqJdFQgVJ8UIdEgGrYLtKcjz+bDr60EijQtKTCCMh+BcW3V3EQJDGKAEhSo0WoF"
|
|
14
14
|
}
|
|
15
15
|
}
|
|
16
16
|
}
|
package/dist/cdn/spool-sw.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
(()=>{class A extends Error{code;constructor(e,t){super(t);this.name="ProtocolError",this.code=e}}function oe(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function ue(e){if(!oe(e))return!1;let t=Object.keys(e);if(t.length!==1)return!1;let r=t[0];return(r==="$record"||r==="$projection")&&typeof e[r]==="string"}function Y(e){let t=new Set,r=new Set,n=(o)=>{if(Array.isArray(o))return o.forEach(n);if(!oe(o))return;if(ue(o)){if("$record"in o)t.add(o.$record);else r.add(o.$projection);return}Object.values(o).forEach(n)};return n(e),{records:[...t].sort(),projections:[...r].sort()}}function Te(e,t){let r=(n,o)=>{if(Array.isArray(n))return n.map((s)=>r(s,o));if(!oe(n))return n;if(ue(n)){if("$record"in n){let u=t.record(n.$record);if(!u)throw Error(`record ${n.$record} is not stored`);return u.data}let s=n.$projection;if(o.includes(s))throw Error(`projection ${s} reaches itself`);let a=t.projection(s);if(!a)throw Error(`projection ${s} is not stored`);return r(a.data,[...o,s])}return Object.fromEntries(Object.entries(n).map(([s,a])=>[s,r(a,o)]))};try{return{ok:!0,value:r(e,[])}}catch(n){return{ok:!1,reason:n instanceof Error?n.message:"unresolved reference"}}}function G(e){throw new A("bad-artifact",e)}function Tt(e,t){if(typeof e!=="number"||!Number.isSafeInteger(e)||e<0)return G(`${t} version must be a non-negative integer`);return e}function Ot(e){if(!oe(e))return G("record must be an object");if(typeof e.id!=="string"||e.id==="")return G("record id");if(!("data"in e))return G(`record ${e.id} needs data`);return{id:e.id,version:Tt(e.version,"record"),data:e.data}}function jt(e){if(!oe(e))return G("projection must be an object");let{id:t,deps:r}=e;if(typeof t!=="string"||t==="")return G("projection id");if(!Array.isArray(r)||r.some((n)=>typeof n!=="string"))return G(`projection ${t} deps must be a list of strings`);if(!("data"in e))return G(`projection ${t} needs data`);return{id:t,version:Tt(e.version,"projection"),deps:r,data:e.data}}var P=1;function _(e){throw new A("bad-artifact",e)}function Oe(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function Ct(e,t){if(e===void 0)return;if(!Oe(e))return _(`${t} must be an object`);for(let r of Object.values(e))if(typeof r!=="string"&&!ue(r))return _(`${t} values must be strings or references`);return e}function Bt(e,t,r){if(e===void 0)return;if(!Array.isArray(e))return _(`${t} must be a list`);return e.map(r)}function de(e){if(!Oe(e))return _("artifact must be an object");if(e.protocol!==P)return _("unsupported protocol version");let{id:t,scope:r,deps:n,vector:o,strategy:s,body:a}=e;if(typeof t!=="string"||!t.startsWith("/"))return _("id must be a path");if(r!=="public"&&r!=="principal")return _("scope must be public or principal");if(!Array.isArray(n)||n.some((p)=>typeof p!=="string"))return _("deps must be a list of strings");if(typeof o!=="number"||!Number.isSafeInteger(o)||o<0)return _("vector must be a non-negative integer");if(!Oe(a))return _("body must be an object");let u={protocol:P,id:t,scope:r,deps:n,vector:o},l=Bt(e.records,"records",Ot),f=Bt(e.projections,"projections",jt);if(l)u.records=l;if(f)u.projections=f;if(s==="template"||s==="projection"||s==="data"){if(!("data"in a))return _(`${s} body needs data`);return{...u,strategy:s,body:{data:a.data}}}if(s==="assembly"){if(typeof a.shell!=="string")return _("assembly body needs a shell string");let p={shell:a.shell},h=Ct(a.fragments,"fragments"),R=Ct(a.slots,"slots");if(h)p.fragments=h;if(R)p.slots=R;return{...u,strategy:s,body:p}}return _(`unknown strategy ${String(s)}`)}function k(e){return new Promise((t,r)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>r(e.error)})}function dn(e){return new Promise((t,r)=>{e.oncomplete=()=>t(),e.onerror=()=>r(e.error),e.onabort=()=>r(e.error)})}function pe(e=indexedDB,t="spool"){let r,n=()=>r??=new Promise((s,a)=>{let u=e.open(t,2);u.onupgradeneeded=()=>{let l=u.result,f=(p)=>!l.objectStoreNames.contains(p);if(f("artifacts"))l.createObjectStore("artifacts",{keyPath:"artifact.id"});if(f("meta"))l.createObjectStore("meta");if(f("beacons"))l.createObjectStore("beacons",{autoIncrement:!0});if(f("records"))l.createObjectStore("records",{keyPath:"id"});if(f("projections"))l.createObjectStore("projections",{keyPath:"id"})},u.onsuccess=()=>{let l=u.result;l.onversionchange=()=>{l.close(),r=void 0},s(l)},u.onerror=()=>a(u.error)});async function o(s,a,u){let f=(await n()).transaction(s,a),p=dn(f),h=await u(f.objectStore(s));return await p,h}return{destroy:async()=>{(await r?.catch(()=>{return}))?.close(),r=void 0,await new Promise((a)=>{let u=e.deleteDatabase(t);u.onsuccess=()=>a(),u.onerror=()=>a()})},getArtifact:(s)=>o("artifacts","readonly",(a)=>k(a.get(s))),putArtifact:(s)=>o("artifacts","readwrite",async(a)=>void await k(a.put(s))),deleteArtifacts:(s)=>o("artifacts","readwrite",async(a)=>{await Promise.all(s.map((u)=>k(a.delete(u))))}),allArtifacts:()=>o("artifacts","readonly",(s)=>k(s.getAll())),clearArtifacts:()=>o("artifacts","readwrite",async(s)=>void await k(s.clear())),getMeta:()=>o("meta","readonly",(s)=>k(s.get("replica"))),setMeta:(s)=>o("meta","readwrite",async(a)=>void await k(a.put(s,"replica"))),addBeacon:(s)=>o("beacons","readwrite",async(a)=>void await k(a.add(s))),readBeacons:()=>o("beacons","readonly",async(s)=>{let[a,u]=await Promise.all([k(s.getAllKeys()),k(s.getAll())]);return a.map((l,f)=>({key:l,event:u[f]}))}),removeBeacons:(s)=>o("beacons","readwrite",async(a)=>{await Promise.all(s.map((u)=>k(a.delete(u))))}),getFlush:()=>o("meta","readonly",(s)=>k(s.get("flush"))),setFlush:(s)=>o("meta","readwrite",async(a)=>void await k(a.put(s,"flush"))),putRecords:(s)=>o("records","readwrite",async(a)=>{await Promise.all(s.map((u)=>k(a.put(u))))}),allRecords:()=>o("records","readonly",(s)=>k(s.getAll())),deleteRecords:(s)=>o("records","readwrite",async(a)=>{await Promise.all(s.map((u)=>k(a.delete(u))))}),putProjections:(s)=>o("projections","readwrite",async(a)=>{await Promise.all(s.map((u)=>k(a.put(u))))}),allProjections:()=>o("projections","readonly",(s)=>k(s.getAll())),deleteProjections:(s)=>o("projections","readwrite",async(a)=>{await Promise.all(s.map((u)=>k(a.delete(u))))}),clearGraph:async()=>{await o("records","readwrite",async(s)=>void await k(s.clear())),await o("projections","readwrite",async(s)=>void await k(s.clear()))}}}var je=new TextEncoder,pn=new TextDecoder;async function fn(e,t,r,n){let o=crypto.getRandomValues(new Uint8Array(12)),s=await crypto.subtle.encrypt({name:"AES-GCM",iv:o,additionalData:je.encode(t)},e,je.encode(JSON.stringify(r)));return{sealed:{iv:o,data:s,at:n}}}async function mn(e,t,r,n){let o=n?.sealed;if(!o)return;let s=await e.get(t,o.at,!1);if(!s)return;try{let a=await crypto.subtle.decrypt({name:"AES-GCM",iv:o.iv,additionalData:je.encode(r)},s,o.data);return JSON.parse(pn.decode(a))}catch{return}}function Mt(e,t){let{partition:r,vault:n}=t,o=!1,s=(l,f)=>`${r}\x00${l}\x00${f}`;async function a(l,f,p,h){let R=await n.get(r,l,!0);if(!R)throw Error("no key");return fn(R,s(f,p),h,l)}let u=(l,f,p)=>mn(n,r,s(l,f),p);return{kill:()=>void(o=!0),async getArtifact(l){if(o)return;let f=await e.getArtifact(l);if(!f)return;let p=await u("artifact",l,f);if(!p)await e.deleteArtifacts([l]);return p},async putArtifact(l){if(o)return;let f=l.artifact.id,p=await a(t.retentionOf(f),"artifact",f,l);if(o)return;await e.putArtifact({artifact:{id:f},...p})},deleteArtifacts:(l)=>o?Promise.resolve():e.deleteArtifacts(l),async allArtifacts(){if(o)return[];let l=[],f=[];for(let p of await e.allArtifacts()){let h=p.artifact.id,R=await u("artifact",h,p);if(R)l.push(R);else f.push(h)}if(f.length>0)await e.deleteArtifacts(f);return l},clearArtifacts:()=>o?Promise.resolve():e.clearArtifacts(),async getMeta(){if(o)return;return u("meta","replica",await e.getMeta())},async setMeta(l){if(o)return;let f=await a(t.shared,"meta","replica",l);if(!o)await e.setMeta(f)},addBeacon:(l)=>e.addBeacon(l),readBeacons:()=>e.readBeacons(),removeBeacons:(l)=>e.removeBeacons(l),getFlush:()=>e.getFlush(),setFlush:(l)=>e.setFlush(l),async putRecords(l){if(o)return;let f=await Promise.all(l.map(async(p)=>({id:p.id,version:p.version,...await a(t.shared,"record",p.id,p)})));if(!o)await e.putRecords(f)},async allRecords(){if(o)return[];let l=[];for(let f of await e.allRecords()){let p=await u("record",f.id,f);if(p)l.push(p)}return l},deleteRecords:(l)=>o?Promise.resolve():e.deleteRecords(l),async putProjections(l){if(o)return;let f=await Promise.all(l.map(async(p)=>({id:p.id,version:p.version,...await a(t.shared,"projection",p.id,p)})));if(!o)await e.putProjections(f)},async allProjections(){if(o)return[];let l=[];for(let f of await e.allProjections()){let p=await u("projection",f.id,f);if(p)l.push(p)}return l},deleteProjections:(l)=>o?Promise.resolve():e.deleteProjections(l),clearGraph:()=>o?Promise.resolve():e.clearGraph()}}var gn="spool-keys",Be="keys",Me="meta",Ce="partition";function Z(e){return new Promise((t,r)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>r(e.error)})}function _t(e){return new Promise((t,r)=>{let n=e.open(gn,1);n.onupgradeneeded=()=>{n.result.createObjectStore(Be),n.result.createObjectStore(Me)},n.onsuccess=()=>{let o=n.result;o.onversionchange=()=>o.close(),t(o)},n.onerror=()=>r(n.error)})}function yn(e=indexedDB){let t=new Map,r=Promise.resolve(),n=(a)=>{let u=r.then(a,a);return r=u.catch(()=>{return}),u},o=()=>crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);async function s(a,u){let l=await _t(e);try{let f=l.transaction(Be,a),p=new Promise((R,T)=>{f.oncomplete=()=>R(),f.onerror=()=>T(f.error),f.onabort=()=>T(f.error)}),h=await u(f.objectStore(Be));return await p,h}finally{l.close()}}return{get:(a,u,l)=>n(async()=>{if(u==="session"){let h=t.get(a);if(!h&&l)h=await o(),t.set(a,h);return h}let f=await s("readonly",(h)=>Z(h.get(a)));if(f||!l)return f;let p=await o();return await s("readwrite",async(h)=>void await Z(h.put(p,a))),p}),shred:(a)=>n(async()=>{t.delete(a),await s("readwrite",async(u)=>void await Z(u.delete(a)))})}}function It(e=indexedDB,t=yn(e)){let r=new Map,n=(s)=>`spool-p-${s}`;async function o(s,a){let u=await _t(e);try{let l=u.transaction(Me,s),f=new Promise((h,R)=>{l.oncomplete=()=>h(),l.onerror=()=>R(l.error),l.onabort=()=>R(l.error)}),p=await a(l.objectStore(Me));return await f,p}finally{u.close()}}return{current:async()=>await o("readonly",(s)=>Z(s.get(Ce)))??null,setCurrent:(s)=>o("readwrite",async(a)=>{if(s===null)await Z(a.delete(Ce));else await Z(a.put(s,Ce))}),open(s,a,u){let l=r.get(s);if(l)return l.sealed;let f=pe(e,n(s)),p=Mt(f,{partition:s,vault:t,retentionOf:a,shared:u});return r.set(s,{sealed:p,destroy:f.destroy}),p},async destroy(s){let a=r.get(s);if(a?.sealed.kill(),r.delete(s),await t.shred(s),a)await a.destroy();else await new Promise((u)=>{let l=e.deleteDatabase(n(s));l.onsuccess=()=>u(),l.onerror=()=>u()})}}}var _e="/.spool/dropped",$t="/.spool/",Nt=65536;var Lt=8;var Dt=3600000,xo=48*Dt,Eo=72*Dt;function Ht(e,t){if(!e||e.length===0)return;let r;try{r=new URL(t)}catch{return}return e.find((n)=>{let o=new URL(n.match);return r.origin===o.origin&&r.pathname.startsWith(o.pathname)})}function hn(e,t,r){if(e==="age-ms")return String(Math.max(0,Math.round(r-t)));if(e==="epoch-ms")return String(Math.round(t));if(e==="epoch-s")return String(Math.floor(t/1000));return new Date(t).toISOString().slice(0,19).replace("T"," ")}function Ft(e,t,r,n){let o=new URLSearchParams(e);o.set(t.param,hn(t.kind,r,n));let s=o.toString();return s===""?"":`?${s}`}var fe={sync:"/.spool/sync",artifact:"/.spool/artifact",beacon:"/.spool/beacon",worker:"/spool-sw.js"};var B={protocol:"spool-protocol",artifact:"spool-artifact",invalidate:"spool-invalidate",clear:"spool-clear",vector:"spool-vector",partition:"spool-partition",vectorSeen:"spool-vector-seen",provision:"spool-provision"},Ie="*",wn=/^[A-Za-z0-9_-]{1,128}$/;function W(e){throw new A("bad-header",e)}function se(e,t){if(!/^\d{1,15}$/.test(e.trim()))return W(`${t} must be a non-negative integer`);return Number(e)}function ie(e,t){try{return decodeURIComponent(e)}catch{return W(`${t} has a bad escape`)}}function me(e){return e.split(",").map((t)=>t.trim()).filter((t)=>t!=="")}function $e(e){try{return Ne(e)}catch{let t=e.get(B.protocol)?.trim();if(t&&/^\d{1,15}$/.test(t)&&Number(t)!==P)return;let r=e.get(B.clear);if(r===null)return;try{return{protocol:P,clear:me(r).map((n)=>ie(n,"Spool-Clear"))}}catch{return{protocol:P,clear:[Ie]}}}}function Ne(e){let t={},r=e.get(B.protocol);if(r!==null)t.protocol=se(r,"Spool-Protocol");let n=e.get(B.artifact);if(n!==null){let f=new Map;for(let T of n.split(";")){let L=T.indexOf("=");if(L<1)return W("Spool-Artifact has a field without a name");f.set(T.slice(0,L).trim(),T.slice(L+1).trim())}let p=f.get("id"),h=f.get("scope"),R=f.get("v");if(p===void 0||R===void 0)return W("Spool-Artifact needs id and v");if(h!=="public"&&h!=="principal")return W("Spool-Artifact scope is unknown");t.artifact={id:ie(p,"Spool-Artifact id"),scope:h,deps:me(f.get("deps")??"").map((T)=>ie(T,"Spool-Artifact deps")),version:se(R,"Spool-Artifact v")}}let o=e.get(B.invalidate);if(o!==null)t.invalidate=Object.fromEntries(me(o).map((f)=>{let p=f.lastIndexOf("=");if(p<1)return W("Spool-Invalidate entries are tag=version");return[ie(f.slice(0,p),"Spool-Invalidate tag"),se(f.slice(p+1),"Spool-Invalidate version")]}));let s=e.get(B.clear);if(s!==null)t.clear=me(s).map((f)=>ie(f,"Spool-Clear"));let a=e.get(B.vector);if(a!==null)t.vector=se(a,"Spool-Vector");let u=e.get(B.vectorSeen);if(u!==null)t.seen=se(u,"Spool-Vector-Seen");let l=e.get(B.partition);if(l!==null){if(!wn.test(l))return W("Spool-Partition must be a base64url token");t.partition=l}return t}var bn=/^[A-Za-z_][A-Za-z0-9_]*$/;function Le(e){let t=e.length>1&&e.endsWith("/")?e.slice(0,-1):e;return t==="/"?[]:t.slice(1).split("/")}function De(e){if(!e.startsWith("/"))throw new A("bad-pattern",`pattern must start with "/": ${e}`);let t=new Set,r=Le(e);for(let[n,o]of r.entries()){if(o==="")throw new A("bad-pattern",`empty segment in ${e}`);if(o==="**"){if(n!==r.length-1)throw new A("bad-pattern",`"**" must be the last segment in ${e}`);continue}if(!o.startsWith(":"))continue;let s=o.slice(1);if(!bn.test(s))throw new A("bad-pattern",`bad parameter name "${s}" in ${e}`);if(t.has(s))throw new A("bad-pattern",`duplicate parameter "${s}" in ${e}`);t.add(s)}}function ge(e,t){let r=Le(e),n=Le(t),o=r[r.length-1]==="**";if(o)r.pop();if(o?n.length<r.length:r.length!==n.length)return null;let s={};for(let a=0;a<r.length;a++){let u=r[a],l=n[a];if(u.startsWith(":")){if(l==="")return null;try{s[u.slice(1)]=decodeURIComponent(l)}catch{return null}}else if(u!==l)return null}return s}var Vt={public:{maxStale:900,mode:"soft"},principal:{maxStale:300,mode:"hard"}};function N(e,t){for(let r of e){let n=ge(r.pattern,t);if(n)return{route:r,params:n}}return null}var Ut=1,Gt=256;function M(e){throw new A("bad-manifest",e)}function He(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function Rn(e,t){let r=`routes[${t}]`;if(!He(e))return M(`${r} must be an object`);let{pattern:n,strategy:o,version:s,freshness:a,offline:u,sync:l}=e;if(typeof n!=="string")return M(`${r}.pattern must be a string`);try{De(n)}catch(p){return M(`${r}: ${p instanceof Error?p.message:"bad pattern"}`)}if(o!=="static")return M(`${n}: strategy must be "static"`);if(typeof s!=="string"||s===""||s.length>Gt)return M(`${n}: version must be a string of 1 to ${Gt} characters`);let f={pattern:n,strategy:o,version:s};if(a!==void 0){if(!He(a))return M(`${n}: freshness must be an object`);let{maxStale:p,mode:h}=a;if(p!==void 0){if(typeof p!=="number"||!Number.isFinite(p)||p<=0)return M(`${n}: freshness.maxStale must be a positive number of seconds`)}if(h!==void 0&&h!=="hard"&&h!=="soft")return M(`${n}: freshness.mode must be "hard" or "soft"`);f.freshness={...p===void 0?{}:{maxStale:p},...h===void 0?{}:{mode:h}}}if(u!==void 0){if(u!=="serve"&&u!=="refuse")return M(`${n}: offline must be "serve" or "refuse"`);f.offline=u}if(l!==void 0){if(l!=="background"&&l!=="deferred")return M(`${n}: sync must be "background" or "deferred"`);f.sync=l}return f}function Fe(e){if(!He(e))return M("manifest must be an object");if(e.schema!==Ut)return M("unsupported manifest schema");let{routes:t}=e;if(!Array.isArray(t))return M("routes must be a list");let r=t.map(Rn),n=new Set;for(let o of r){if(n.has(o.pattern))return M(`${o.pattern}: declared twice`);n.add(o.pattern)}return{schema:Ut,routes:r}}function Ve(e){return e.routes.map((t)=>({pattern:t.pattern,strategy:"static",scope:"public",freshness:{...Vt.public,...t.freshness},persist:!0,offline:t.offline??"serve",sync:t.sync??"background",version:t.version}))}var ae="spool:artifact:",Ue=64,zt=256;function Ge(e){return`${ae}${e}`}function z(e){throw new A("bad-sync",e)}function ze(e){return Object.entries(e).map(([t,r])=>`${encodeURIComponent(t)}@${r}`).join(",")}function qt(e){if(typeof e!=="object"||e===null)return z("sync response must be an object");let t=e;if(t.protocol!==P)return z("unsupported protocol version");let{cursor:r,changed:n,dropped:o,reset:s,partial:a}=t;if(typeof r!=="number"||!Number.isSafeInteger(r)||r<0)return z("cursor must be a non-negative integer");if(typeof n!=="object"||n===null||Array.isArray(n))return z("changed must be an object");for(let l of Object.values(n))if(typeof l!=="number"||!Number.isSafeInteger(l))return z("changed versions must be integers");if(!Array.isArray(o)||o.some((l)=>typeof l!=="string"))return z("dropped must be a list of strings");if(typeof s!=="boolean")return z("reset must be a boolean");if(a!==void 0&&typeof a!=="boolean")return z("partial must be a boolean");let u={protocol:P,cursor:r,changed:n,dropped:o,reset:s};if(a)u.partial=!0;return u}var qe={cold:"network",principal:"network",fresh:"local",catalogue:"local","soft-deferred":"local","soft-sync":"local-revalidate","hard-sync":"local-revalidate","offline-stale":"local-revalidate",invalidated:"fallback","stale-after-sync":"fallback","hard-refused":"fallback",refused:"fallback"};var Wt="external",We="/.spool/view",Kt="/.spool/loads";function Xt(e,t,r,n){return{path:"/.spool/loads",body:JSON.stringify(n&&Object.keys(n).length>0?{view:e,count:t,origins:n}:{view:e,count:t}),contentType:"application/json",at:r}}function Jt(e,t){return{path:"/.spool/view",body:JSON.stringify(e),contentType:"application/json",at:t}}function Yt(e){if(/\b(?:CriOS|FxiOS|EdgiOS|OPiOS)\//.test(e))return"webkit";if(/\bFirefox\//.test(e))return"firefox";if(/\b(?:Chrome|Chromium)\//.test(e))return"chromium";if(/\bSafari\//.test(e))return"webkit";return"other"}var Zt=86400000,Sn=3600000,vn=20,An=3600000,Pn=86400000,xn=256,Qt=100,er=3000,En="same-origin";function kn(e,t){let r,n=new Promise((o,s)=>{r=setTimeout(()=>s(Error("timed out")),t)});return Promise.race([e,n]).finally(()=>clearTimeout(r))}var Tn=new TextEncoder,Ke=(e)=>e.path.startsWith($t)||e.deliver==="sink";class Xe{#e;#t=null;#s;dropped=new Map;constructor(e){this.#e=e}async record(e){await this.#e.storage.addBeacon(e)}async enqueue(e,t){let r=e.method==="GET",n=r?"":e.headers.get("content-type")??"text/plain";if(/octet-stream|multipart|image\//i.test(n))return!1;let o=r?"":await e.clone().text();if(Tn.encode(o).length>Nt)return!1;let s=new URL(e.url),a=this.#e.now(),u={path:s.pathname,body:o,contentType:n,at:a};if(s.search!=="")u.search=s.search;if(r)u.method="GET";if(t){if(u.origin=s.origin,u.vendor=t.vendor,u.until=a+t.maxAgeMs,t.delivery==="sink")u.deliver="sink"}return await this.#e.storage.addBeacon(u),!0}flush(){return this.#t??=this.#c().finally(()=>{this.#t=null}),this.#t}async flushAtMoment(){await this.#n();let e=await this.#e.storage.readBeacons();if(e.length===0)return!1;let t=(l)=>l===We||l===Kt||l===_e,r=e.some((l)=>!t(l.event.path)),n=e.filter((l)=>l.event.path===We).length,o=(await this.#e.want?.()??[]).length>0,s=await this.#i(this.#e.catalogue?.())!==void 0,a=Math.min(...e.map((l)=>l.event.at)),u=this.#e.now()-a>=An;if(r||o||s||u||n>=vn)return this.flush();return!1}async flushIfDue(){let e=this.#e.now(),t=await this.#r(),r=t.checkedAt>e?-1/0:t.checkedAt;if(e-r<Sn)return!1;t.checkedAt=e,await this.#o(t),await this.#n();let n=await this.#e.storage.readBeacons(),o=Math.min(...n.map((a)=>a.event.at));if(n.length===0||e-o<Zt)return!1;let s=t.lastStandalone>e?-1/0:t.lastStandalone;if(e-s<Zt)return!1;return t.lastStandalone=e,await this.#o(t),this.flush()}async#r(){return this.#s??=await this.#e.storage.getFlush()??{lastStandalone:-1/0,checkedAt:-1/0},this.#s}async#o(e){await this.#e.storage.setFlush(e)}async#n(){let{storage:e,now:t}=this.#e,r=t(),o=(await e.readBeacons()).filter((s)=>s.event.until!==void 0&&s.event.until<r);if(o.length===0)return;await e.removeBeacons(o.map((s)=>s.key)),await this.#a(o.map(({event:s})=>s.vendor??"unknown"))}async#a(e){let t=new Map;for(let r of e)t.set(r,(t.get(r)??0)+1);for(let[r,n]of t)this.dropped.set(r,(this.dropped.get(r)??0)+n),await this.#e.storage.addBeacon({path:_e,body:JSON.stringify({vendor:r,count:n}),contentType:"application/json",at:this.#e.now()})}async sendSameOrigin(e){if(this.#t)await this.#t.catch(()=>!1);let{storage:t,replay:r}=this.#e,n=(await t.readBeacons()).filter(({event:a})=>!Ke(a)&&a.origin===void 0);if(n.length===0)return;await t.removeBeacons(n.map((a)=>a.key));let o=!1,s=[];for(let{event:a}of n){let u=!1;if(!o)try{u=await kn(r(a),e)}catch{o=!0}if(!u)s.push(En)}await this.#a(s)}async#c(){let{storage:e,send:t,replay:r,want:n,catalogue:o}=this.#e;await this.#n();let s=await e.readBeacons();if(s.length===0)return!1;let a=!0;for(let h of s.filter((R)=>!Ke(R.event))){let R;try{R=await r(h.event)}catch{R=!1}if(R)await e.removeBeacons([h.key]);else a=!1}let u=s.filter((h)=>Ke(h.event)),l=await n?.()??[],f=await this.#i(o?.());if(u.length===0&&l.length===0)return a;let p=!0;for(let h=0;h<Math.max(u.length,1);h+=Qt){let R=u.slice(h,h+Qt),T={protocol:P,events:R.map(({event:{until:L,...te}})=>te)};if(l.length>0)T.want=l;if(f)T.catalogue=f;l=[],f=void 0;try{p=await t(T)}catch{p=!1}if(!p)return!1;if(await e.removeBeacons(R.map((L)=>L.key)),T.catalogue)await this.#u(T.catalogue.path)}return a&&p}async#i(e){if(!e)return;let t=(await this.#r()).catalogue?.[e.path],r=this.#e.now();return t===void 0||t>r||r-t>=Pn?e:void 0}async#u(e){let t=await this.#r(),r={...t.catalogue};delete r[e],r[e]=this.#e.now();let n=Object.keys(r);for(let o of n.slice(0,n.length-xn))delete r[o];t.catalogue=r,await this.#o(t)}}function On(e){try{return new URL(e).origin}catch{return null}}var jn=Uint8Array.from(atob("R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"),(e)=>e.charCodeAt(0));function tr(e){let t=new Headers;if(e.mode==="cors"){let r=e.headers.get("origin")??On(e.referrer);if(e.credentials==="include"&&r)t.set("access-control-allow-origin",r),t.set("access-control-allow-credentials","true");else t.set("access-control-allow-origin","*")}if(e.method==="GET")return t.set("content-type","image/gif"),t.set("cache-control","no-store"),new Response(jn,{status:200,headers:t});return new Response(null,{status:204,headers:t})}function rr(e,t,r){if((r>=t?(r-t)/1000:1/0)<=e.maxStale)return"serve";return e.mode==="hard"?"sync-first":"serve-then-sync"}function nr(e,t){return Math.max(e,t)}function or(e,t){return e.deps.every((r)=>t(r)<=e.vector)}var Cn=["content-security-policy","content-security-policy-report-only","x-frame-options","x-content-type-options","referrer-policy","permissions-policy","cross-origin-opener-policy","cross-origin-embedder-policy","cross-origin-resource-policy"],sr=128;function ir(e){let t=[];for(let r of Cn){let n=e.get(r);if(n!==null)t.push([r,n])}return t}var K={reuse:0.5,futureViews:2,requestBytes:2000,artifactBytes:20000,avoidedBytes:17054,changesPerDay:1};function cr(e){let{hot:t,...r}=e??{};return{...K,...r}}function Bn(e,t){return e.bytes+e.requests*t}var Mn={bytes:0,requests:0};function _n(e,t=K){let r=e.reuse??t.reuse,n=e.futureViews??t.futureViews,o=(s)=>Bn(s,t.requestBytes);return r*n*o(e.avoided)-o(e.provision)-o(e.maintain??Mn)}var ar={layout:0,template:0,asset:0,route:1,expansion:2};function lr(e,t=K){return e.map((r)=>({...r,benefit:_n(r,t)})).filter((r)=>r.benefit>0).sort((r,n)=>ar[r.kind]-ar[n.kind]||n.benefit-r.benefit||(r.id<n.id?-1:r.id>n.id?1:0))}class Je{#e=new Map;#t(e){let t=this.#e.get(e)??{id:e,bytes:0,requests:0,views:0,catalogueBytes:0,catalogueViews:0};return this.#e.set(e,t),t}spend(e,t,r=!1){let n=this.#t(e);if(n.bytes+=t.bytes,n.requests+=t.requests,r)n.catalogueBytes+=t.bytes}serve(e,t=!1){let r=this.#t(e);if(r.views+=1,t)r.catalogueViews+=1}entries(){return[...this.#e.values()].map((e)=>({...e})).sort((e,t)=>e.id<t.id?-1:1)}totals(){let e=[...this.#e.values()],t=(o)=>e.reduce((s,a)=>s+o(a),0),r=t((o)=>o.views),n=t((o)=>o.bytes);return{bytes:n,requests:t((o)=>o.requests),views:r,bytesPerView:r===0?null:n/r,catalogueBytes:t((o)=>o.catalogueBytes),catalogueViews:t((o)=>o.catalogueViews)}}meanFetchBytes(){let e=[...this.#e.values()].filter((t)=>t.bytes>t.catalogueBytes);return e.length===0?null:e.reduce((t,r)=>t+r.bytes-r.catalogueBytes,0)/e.length}}var In=/<span data-spool-placeholder="([^"]*)"><\/span>/g,$n=/\{\{spool-slot:([A-Za-z0-9_.-]+)\}\}/g;function ur(e,t,r){let n=[],o=[],s=new Set,a=e.replace(t,(l,f)=>{s.add(f);let p=Object.hasOwn(r,f)?r[f]:void 0;if(p===void 0)return o.push(f),l;return n.push(f),p}),u=Object.keys(r).filter((l)=>!s.has(l));return{html:a,filled:n,unfilled:o,unmatched:u}}function Nn(e,t){return ur(e,In,t)}function Ln(e,t){return ur(e,$n,t)}function dr(e){let t=(a)=>{let u={};for(let[l,f]of Object.entries(a??{})){if(typeof f!=="string")return null;u[l]=f}return u},r=t(e.fragments),n=t(e.slots);if(!r||!n)return{ok:!1,reason:"unresolved reference"};let o=Nn(e.shell,r);if(o.unfilled.length>0)return{ok:!1,reason:`unfilled placeholders: ${o.unfilled.join(", ")}`};let s=Ln(o.html,n);if(s.unfilled.length>0)return{ok:!1,reason:`unfilled slots: ${s.unfilled.join(", ")}`};return{ok:!0,html:s.html}}function pr(e,t){if(e.includes("data-spool-client"))return e;for(let r of[/<\/head\s*>/i,/<\/body\s*>/i]){let n=e.search(r);if(n>=0)return e.slice(0,n)+t+e.slice(n)}return e+t}var Dn={"&":"&","<":"<",">":">",'"':""","'":"'"};function Hn(e){return e.replace(/[&<>"']/g,(t)=>Dn[t])}function fr(e,t){if(e===null||typeof e!=="object")return;return Object.hasOwn(e,t)?e[t]:void 0}function Ye(e,t){let r=t[t.length-1];if(e.length===0)return r.value;if(e[0]==="@index")return r.index;for(let n=t.length-1;n>=0;n--){let o=t[n];if(fr(o.value,e[0])===void 0)continue;return e.reduce((s,a)=>fr(s,a),o.value)}return}function Fn(e){if(Array.isArray(e))return e.length>0;return!(e===void 0||e===null||e===!1||e===""||e===0)}function Vn(e){return typeof e==="string"||typeof e==="number"?String(e):""}function Ze(e,t,r){let n="";for(let o of e)if(o.t==="text")n+=o.v;else if(o.t==="var"){let s=Vn(Ye(o.p,t));if(!o.raw)n+=Hn(s);else if(r.has(o.p.join(".")))n+=s;else throw new A("bad-template",`{{{${o.p.join(".")}}}} is not trusted`)}else if(o.t==="if")n+=Ze(Fn(Ye(o.p,t))?o.then:o.else,t,r);else{let s=Ye(o.p,t);if(!Array.isArray(s))continue;s.forEach((a,u)=>{n+=Ze(o.body,[...t,{value:a,index:u}],r)})}return n}function mr(e,t){if(e.v!==1)throw new A("bad-template",`unknown template version ${String(e.v)}`);return Ze(e.nodes,[{value:t,index:0}],new Set(e.trusted))}async function gr(e,t,r,n={}){try{let o=Object.hasOwn(n,t.pattern)?n[t.pattern]:void 0,s;if(o)s=await o(r);else if(r.strategy==="data"&&t.strategy==="data")return{ok:!0,html:JSON.stringify(r.body.data)};else if(r.strategy==="projection"&&t.strategy==="projection")return{ok:!1,reason:`no renderer for ${t.pattern}`};else if(r.strategy==="static"||r.strategy!==t.strategy)return{ok:!1,reason:`artifact is ${r.strategy}, route is ${t.strategy}`};else if(r.strategy==="assembly"){let a=dr(r.body);if(!a.ok)return a;s=a.html}else if(r.strategy!=="template")return{ok:!1,reason:`${r.strategy} has no built-in render`};else{let a=Object.hasOwn(e.templates,t.pattern)?e.templates[t.pattern]:void 0;if(!a)return{ok:!1,reason:`no template for ${t.pattern}`};s=mr(a,r.body.data)}if(t.strategy==="data")return{ok:!0,html:s};return{ok:!0,html:pr(s,e.clientTag)}}catch(o){return{ok:!1,reason:o instanceof Error?o.message:"render failed"}}}function ye(e,t,r){let n=e.get(t)??new Set;n.add(r),e.set(t,n)}function he(e,t,r){let n=e.get(t);if(!n)return;if(n.delete(r),n.size===0)e.delete(t)}class we{#e=new Map;#t=new Map;#s=new Map;#r=new Map;#o=new Map;#n=new Map;addProjection(e,t,r){this.removeProjections([e]),this.#n.set(e,{deps:[...t],children:[...r]});for(let n of t)ye(this.#e,n,e);for(let n of r)ye(this.#t,n,e)}removeProjections(e){for(let t of e){let r=this.#n.get(t);if(!r)continue;for(let n of r.deps)he(this.#e,n,t);for(let n of r.children)he(this.#t,n,t);this.#n.delete(t)}}addArtifact(e,t){this.removeArtifacts([e]),this.#o.set(e,t);for(let r of t.records)ye(this.#s,r,e);for(let r of t.projections)ye(this.#r,r,e)}removeArtifacts(e){for(let t of e){let r=this.#o.get(t);if(!r)continue;for(let n of r.records)he(this.#s,n,t);for(let n of r.projections)he(this.#r,n,t);this.#o.delete(t)}}clear(){this.#e.clear(),this.#t.clear(),this.#s.clear(),this.#r.clear(),this.#o.clear(),this.#n.clear()}projectionsReading(e){let t=new Set;for(let r of e)for(let n of this.#e.get(r)??[])t.add(n);return[...t].sort()}withParents(e){let t=new Set,r=[...e];for(let n=r.pop();n!==void 0;n=r.pop()){if(t.has(n))continue;t.add(n),r.push(...this.#t.get(n)??[])}return[...t].sort()}artifactsUsing(e,t){let r=new Set;for(let n of e)for(let o of this.#s.get(n)??[])r.add(o);for(let n of t)for(let o of this.#r.get(n)??[])r.add(o);return[...r].sort()}}class Q{#e;#t=new Map;constructor(e){this.#e=e}async load(){for(let e of await this.#e.all())this.#t.set(e.id,e)}get(e){return this.#t.get(e)}all(){return[...this.#t.values()]}ids(){return[...this.#t.keys()].sort()}async put(e,t){let r=e.filter((n)=>(this.#t.get(n.id)?.version??-1)<n.version);for(let n of r)this.#t.set(n.id,n);if(r.length>0)if(t)await this.#e.put(r);else await this.#e.delete(r.map((n)=>n.id));return r.map((n)=>n.id)}async drop(e){let t=e.filter((r)=>this.#t.delete(r));if(t.length>0)await this.#e.delete(t)}forget(){this.#t.clear()}}function Qe(e){return new Q({all:()=>e.allProjections(),put:(t)=>e.putProjections(t),delete:(t)=>e.deleteProjections(t)})}function et(e){return new Q({all:()=>e.allRecords(),put:(t)=>e.putRecords(t),delete:(t)=>e.deleteRecords(t)})}function Re(e){return e.records!==void 0||e.projections!==void 0||be(Y(e.body))}var be=(e)=>e.records.length+e.projections.length>0;function yr(e){return Y(e.data).projections}class tt{records;projections;index=new we;#e;#t;constructor(e){this.#e=e,this.records=et(e.storage),this.projections=Qe(e.storage)}get loaded(){return this.#t!==void 0}ensure(){let e=this.#t===void 0;return this.#t??=this.#s(),e?this.#t:this.#t.then(()=>[])}async#s(){await Promise.all([this.records.load(),this.projections.load()]);for(let t of this.projections.all())this.index.addProjection(t.id,t.deps,yr(t));for(let{artifact:t}of await this.#e.artifacts()){let r=Y(t.body);if(be(r))this.index.addArtifact(t.id,r)}let e={};for(let t of this.records.all()){let r=this.#e.tagVersion(t.id);if(r>t.version)e[t.id]=r}for(let t of this.projections.all())for(let r of t.deps){let n=this.#e.tagVersion(r);if(n>t.version)e[r]=n}return(await this.invalidate(e)).artifacts}async put(e,t){await this.records.put(e.records??[],t);let r=await this.projections.put(e.projections??[],t);for(let o of r){let s=this.projections.get(o);this.index.addProjection(o,s.deps,yr(s))}let n=Y(e.body);if(be(n))this.index.addArtifact(e.id,n)}forgetArtifacts(e){this.index.removeArtifacts(e)}held(e){let t={};for(let r of[...this.records.all(),...this.projections.all()].slice(0,e))t[r.id]=r.version;return t}async invalidate(e){let t=Object.keys(e),r=(u,l)=>(e[u]??0)>l,n=t.filter((u)=>{let l=this.records.get(u);return l!==void 0&&r(u,l.version)}),o=this.index.projectionsReading(t).filter((u)=>{let l=this.projections.get(u);return l!==void 0&&l.deps.some((f)=>r(f,l.version))}),s=this.index.withParents(o).filter((u)=>this.projections.get(u)),a=this.index.artifactsUsing(n,s);return await this.records.drop(n),await this.projections.drop(s),this.index.removeProjections(s),{records:n.sort(),projections:s,artifacts:a}}async clear(){this.records.forget(),this.projections.forget(),this.index.clear(),await this.#e.storage.clearGraph()}async materialize(e){if(e.strategy==="static"||!be(Y(e.body)))return{ok:!0,artifact:e};await this.ensure();let t={record:(a)=>this.records.get(a),projection:(a)=>this.projections.get(a)};if(e.strategy!=="assembly"){let a=Te(e.body.data,t);if(!a.ok)return a;return{ok:!0,artifact:{...e,body:{data:a.value}}}}let r=(a)=>{let u={};for(let[l,f]of Object.entries(a??{})){let p=Te(f,t);if(!p.ok)return p;if(typeof p.value!=="string")return{ok:!1,reason:`${l} did not resolve to text`};u[l]=p.value}return{ok:!0,value:u}},n=r(e.body.fragments);if(!n.ok)return n;let o=r(e.body.slots);if(!o.ok)return o;let s={shell:e.body.shell};if(e.body.fragments)s.fragments=n.value;if(e.body.slots)s.slots=o.value;return{ok:!0,artifact:{...e,body:s}}}}class Se{#e;#t;#s;#r=new Map;#o=new Map;#n=null;#a=0;#c;#i=new Map;graph;constructor(e,t,r=Date.now){this.#e=e,this.#t=t,this.#s=r,this.graph=new tt({storage:e,tagVersion:(n)=>this.#o.get(n)??0,artifacts:()=>this.#d()})}async load(){let e=await this.#e.getMeta();if(e&&e.version===this.#t){this.#n=e.cursor,this.#a=e.syncedAt,this.#o=new Map(e.tags),this.#c=e.policy?.site,this.#i=new Map(e.policy?.paths);return}await this.#e.clearArtifacts(),await this.graph.clear(),await this.#l()}get cursor(){return this.#n}get syncedAt(){return this.#a}get sitePolicy(){return this.#c}policyOf(e){return this.#i.get(e)}async keepPolicy(e,t){let r=(n)=>JSON.stringify(n)===JSON.stringify(t);if(e===null){if(r(this.#c))return;this.#c=t}else{if(r(this.#i.get(e)))return;if(this.#i.delete(e),this.#i.set(e,t),this.#i.size>sr)this.#i.delete(this.#i.keys().next().value)}await this.#l()}async get(e){return this.#r.get(e)??await this.#e.getArtifact(e)}async ids(){return(await this.#d()).map((e)=>e.artifact.id)}isCurrent(e){return or(e,(t)=>this.#o.get(t)??0)}validatedAt(e){return Math.max(nr(e.fetchedAt,this.#a),e.validatedAt??0)}async validate(e){let t=await this.get(e);if(!t||!this.isCurrent(t.artifact))return;let r={...t,validatedAt:this.#s()};if(this.#r.has(e))this.#r.set(e,r);else await this.#e.putArtifact(r)}needFor(e,t=!1){if(!t&&!Re(e))return null;let r=[...new Set([...e.deps,Ge(e.id)])];if(r.length>Ue)return null;return Object.fromEntries(r.map((n)=>[n,e.vector]))}async held(){return await this.#u(),this.graph.held(zt)}async materialize(e){if(Re(e))await this.#u();return this.graph.materialize(e)}async#u(){let e=await this.graph.ensure();if(e.length>0)await this.drop(e)}async put(e,t,r=!1){if(!this.isCurrent(e))return!1;if(Re(e))await this.#u(),await this.graph.put(e,t);let{records:n,projections:o,...s}=e,a={artifact:s,fetchedAt:this.#s(),...r?{catalogue:!0}:{}};if(t)this.#r.delete(e.id),await this.#e.putArtifact(a);else await this.#e.deleteArtifacts([e.id]),this.#r.set(e.id,a);if(this.#n===null)this.#n=e.vector,await this.#l();return!0}async open(e){let t=await this.get(e);if(!t?.catalogue)return;let{catalogue:r,...n}=t;if(this.#r.has(e))this.#r.set(e,n);else await this.#e.putArtifact(n)}async sweep(e){let t={...e};for(let{artifact:r,catalogue:n}of await this.#d()){if(!n)continue;for(let o of[...r.deps,Ge(r.id)])t[o]=Math.min(t[o]??1/0,r.vector)}return Object.keys(t).length>Ue?null:t}async drop(e){for(let t of e)this.#r.delete(t);if(await this.#e.deleteArtifacts(e),this.graph.loaded)this.graph.forgetArtifacts(e)}async wipe(e=null){this.#r.clear(),await this.#e.clearArtifacts(),await this.graph.clear(),this.#o=new Map,this.#c=void 0,this.#i=new Map,this.#n=e,await this.#l()}async applySync(e){if(e.reset){let r=await this.ids();return await this.wipe(e.cursor),this.#a=this.#s(),await this.#l(),r}let t=await this.#p(e.changed);if(await this.drop(e.dropped),!e.partial)this.#n=Math.max(this.#n??0,e.cursor),this.#a=this.#s();return await this.#l(),[...new Set([...t,...e.dropped])]}async applyEnvelope(e,t,r){let n=[];if(e.clear?.includes(Ie))n=await this.ids(),await this.wipe(e.vector??this.#n);else if(e.invalidate)n=await this.#p(e.invalidate);if(t!==null&&e.seen===t&&e.vector!==void 0&&!r)this.#n=Math.max(this.#n??0,e.vector),this.#a=this.#s();return await this.#l(),n}async#d(){return[...this.#r.values(),...await this.#e.allArtifacts()]}async#p(e){let t=new Map;for(let[o,s]of Object.entries(e))if(o.startsWith(ae))t.set(o.slice(ae.length),s);else if(s>(this.#o.get(o)??0))this.#o.set(o,s);let r=this.graph.loaded?(await this.graph.invalidate(Object.fromEntries(this.#f(e)))).artifacts:[],n=(await this.#d()).filter(({artifact:o})=>{let s=t.get(o.id);return s!==void 0&&o.vector<s||!this.isCurrent(o)||r.includes(o.id)}).map(({artifact:o})=>o.id);return await this.drop(n),n}#f(e){return Object.entries(e).filter(([t])=>!t.startsWith(ae))}async#l(){await this.#e.setMeta({version:this.#t,cursor:this.#n,tags:[...this.#o],syncedAt:this.#a,policy:{...this.#c?{site:this.#c}:{},paths:[...this.#i]}})}}function Un(e,t){return e.thirdParty?.allow.includes(t.origin)===!0}function rt(e,t,r){let n=new URL(t.url);if(n.origin!==r){let a=Ht(e.collectors,t.url);if(a&&(t.method==="POST"||t.method==="GET"))return{kind:"collector",collector:a};if(t.method==="GET"&&Un(e,n))return{kind:"thirdparty"};return{kind:"ignore"}}if(e.logout?.some((a)=>ge(a,n.pathname)))return{kind:"logout"};if(t.method==="POST"&&e.beacons.includes(n.pathname))return{kind:"beacon"};if(t.method!=="GET")return{kind:"pass"};let o=N(e.routes,n.pathname),s=n.search!=="";if(t.mode!=="navigate"){if(o?.route.strategy==="static"&&!t.headers.has("range"))return{kind:"static",route:o.route,path:n.pathname+n.search};if(o?.route.strategy==="data"&&!t.headers.has("range")&&!s)return{kind:"data",route:o.route,path:n.pathname};return{kind:"asset"}}if(!o||o.route.strategy==="data"||s)return{kind:"pass"};return{kind:"navigation",route:o.route,params:o.params,path:n.pathname}}function Gn(e,t){let r=(o)=>`${t}${o}`,n=[{condition:{requestMode:"navigate"},source:"fetch-event"}];for(let o of e.beacons)n.push({condition:{urlPattern:r(o),requestMethod:"POST"},source:"fetch-event"});for(let o of e.logout??[])n.push({condition:{urlPattern:r(o)},source:"fetch-event"});for(let o of e.routes)if(o.strategy==="static"||o.strategy==="data")n.push({condition:{urlPattern:r(o.pattern)},source:"fetch-event"});if((e.collectors?.length??0)>0||e.thirdParty)n.push({condition:{not:{urlPattern:r("/*")}},source:"fetch-event"});return n.push({condition:{urlPattern:r("/*")},source:"network"}),n}async function hr(e,t,r){if(typeof e.addRoutes!=="function")return!1;try{return await e.addRoutes(Gn(t,r)),!0}catch{return!1}}var zn=86400,qn={changesPerDay:K.changesPerDay,staleBytes:K.avoidedBytes,syncBytes:K.requestBytes};class wr{#e;#t;constructor(e){this.#e=1,this.#t=zn/e}observe(e,t,r){this.#e+=r,this.#t+=e*t}perSecond(){return this.#e/this.#t}}function Wn(e){return(1-Math.exp(-e.perSecond*e.tags*Math.max(0,e.ageSec)))*e.policy.staleBytes-e.policy.syncBytes}var Kn=(e)=>e?Object.entries(e).sort().join("|"):"*";class nt{#e;#t=new Map;#s;#r={};#o=0;rate;constructor(e){this.#e=e,this.#s=e.policy??qn,this.rate=new wr(this.#s.changesPerDay)}sync(e,t){let r=this.#t.get("*");if(r)return r;let n=Kn(e),o=this.#t.get(n);if(o)return o;let s=[...this.#t.values()],a=Promise.allSettled(s).then(()=>this.#n(e,t)).finally(()=>{if(this.#t.get(n)===a)this.#t.delete(n)});return this.#t.set(n,a),a}background(e,t){return this.sync(e,t).then(()=>{return},()=>{return})}defer(e,t){let r=Object.keys(e).length;if(r===0)return!1;if(Wn({ageSec:t,perSecond:this.rate.perSecond(),tags:r,policy:this.#s})<=0)return!1;for(let[o,s]of Object.entries(e))this.#r[o]=Math.min(s,this.#r[o]??1/0);return this.#o=Math.max(this.#o,t),!0}get pending(){return Object.keys(this.#r).sort()}drain(){let e=this.#r;if(Object.keys(e).length===0)return Promise.resolve(!0);let t=this.#o;return this.#r={},this.#o=0,this.sync(e,t)}async#n(e,t){let{replica:r,fetchSync:n,onNetwork:o}=this.#e,s=r.cursor;if(s===null&&!e)return!0;try{let a=await n(s??0,e);if(e&&t!==void 0&&!a.reset){let u=Object.keys(e),l=u.filter((f)=>Object.hasOwn(a.changed,f)).length;this.rate.observe(u.length,t,l)}return await r.applySync(a),!0}catch{return!1}finally{o?.()}}}function br(e,t={}){let r=e.replace(/<!--[\s\S]*?-->/g,"");for(let n of t.ignore??[]){let o=n.flags.includes("g")?n.flags:`${n.flags}g`;r=r.replace(new RegExp(n.source,o),"\x00")}return r.replace(/\s+/g," ").replace(/>\s+</g,"><").trim()}function Rr(e,t,r={}){let n=br(e,r),o=br(t,r);if(n===o)return{equal:!0};let s=0;while(s<n.length&&n[s]===o[s])s++;return{at:s,equal:!1,reason:`diverges at ${s}: ${JSON.stringify(n.slice(s,s+80))} vs ${JSON.stringify(o.slice(s,s+80))}`}}function ot(e,t){return t.mode??e.mode??"serve"}function Sr(e,t,r){if(t.strategy==="static")return!1;if(ot(e,t)==="shadow")return!0;let n=e.shadowSample??0;return n>0&&r()<n}async function vr(e,t){if(t.status!==200)return!0;return!Rr(e,await t.text()).equal}var st="spool-static-",Pr=4194304,Xn=["content-encoding","content-length","transfer-encoding","connection","keep-alive","set-cookie","age","date","vary"];function xr(e){let t=new Headers(e);for(let r of Xn)t.delete(r);return t}async function Er(e,t){if(Number(e.headers.get("content-length"))>t)return null;let r=e.body?.getReader();if(!r)return new Uint8Array;let n=[],o=0;for(;;){let{done:u,value:l}=await r.read();if(u)break;if(o+=l.byteLength,o>t)return r.cancel().catch(()=>{return}),null;n.push(l)}let s=new Uint8Array(o),a=0;for(let u of n)s.set(u,a),a+=u.byteLength;return s}var Jn=/^sha(256|384|512)-([A-Za-z0-9+/]+={0,2})$/,Yn=/^(?:W\/)?"/;function Zn(e){let t="";for(let r of e)t+=String.fromCharCode(r);return btoa(t)}var Ar=(e)=>e.replace(/^W\//,"");async function kr(e,t,r){let n=Jn.exec(e);if(n){let o=await crypto.subtle.digest(`SHA-${n[1]}`,t);return Zn(new Uint8Array(o))===n[2]}if(Yn.test(e)){let o=r.get("etag");return o!==null&&Ar(o)===Ar(e)}return!0}var ce="spool-third",ee={class:"x-spool-class",fetched:"x-spool-fetched"};var Qn=[/[._-][0-9a-f]{8,}(?=[._-]|$)/i,/[@/_-]v?\d+\.\d+\.\d+/,/\/v\d+(?:\/|$)/],eo=/[?&](?:v|ver|version|hash|h|rev)=[^&]+/i;function Tr(e,t,r=[]){if(Qn.some((s)=>s.test(e.pathname)))return"immutable";let n=t.get("cache-control")??"";if(/(?:^|,)\s*immutable\b/i.test(n))return"immutable";let o=/max-age=(\d+)/i.exec(n);if(o!==null&&Number(o[1])>=31536000)return"immutable";if(eo.test(e.search))return"revalidate";for(let s of r)try{if(new RegExp(s).test(e.href))return"revalidate"}catch{continue}return null}var to=["template","projection","data"],jr="spool-assets-",ro=[jr,st],no=31536000,oo=86400000,it=new TextEncoder,Or=(e)=>e.split("?",1)[0];function so(e){let t=e.headers.get("cache-control")??"";if(/(?:^|,)\s*immutable\b/i.test(t))return!0;let r=/max-age=(\d+)/i.exec(t);return r!==null&&Number(r[1])>=no}function Cr(e){let{config:t,storage:r,origin:n,renderers:o}=e,s=e.partitions,a=e.now??Date.now,u=e.random??Math.random,l=Yt(e.userAgent??(typeof navigator>"u"?"":navigator.userAgent)),f=cr(t.provision),p=new Se(r,t.version,a),h=new Je,R=new Set,T=new Map,L=new Set,te=new Set,at=new Set,ve=null,X=new Map,ct=`${jr}${t.version}`,re=`${st}${t.version}`,lt=(i)=>new Request(`${n}${i}`),Ir=a(),Ae=t.assets??"cache",ut=!1,Pe=null,$r,dt,Nr,O=null,pt=Promise.resolve(),Lr=t.mode==="shadow",ft=()=>t.manifest!==void 0&&t.routes.length===0,xe=new Map,D=(i)=>{let c=xe.get(i);if(!c)c=e.caches.open(i),xe.set(i,c),c.catch(()=>xe.delete(i));return c},I=async()=>{if(await($r??=p.load()),ft())await(dt??=sn());if(s)await(Nr??=Xr())},F=(i)=>{let c=i.then(()=>{return},()=>{return});R.add(c),c.then(()=>R.delete(c))},Dr=async()=>{while(R.size>0)await Promise.allSettled([...R])},mt=(i)=>{let c=pt.then(i,i);return pt=c.catch(()=>{return}),c};async function Hr(i,c){if(t.manifest)return vt();let d=c?`need=${encodeURIComponent(ze(c))}`:`from=${i}`,m=await e.fetch(`${n}${fe.sync}?${d}`,{cache:"no-store",credentials:"same-origin"});if(!m.ok)throw Error(`sync answered ${m.status}`);return await ht($e(m.headers),!0),qt(await m.json())}let Fr={changesPerDay:f.changesPerDay,staleBytes:f.avoidedBytes,syncBytes:f.requestBytes};async function Vr(){let i=[];for(let d of te)if(!await p.get(d))i.push(d);let c=[];for(let d of t.provision?.hot??[]){if(at.has(d)||i.includes(d)||await p.get(d))continue;let m=N(t.routes,d);if(!m||m.route.scope!=="public"||m.route.strategy==="static")continue;c.push({id:d,kind:"route",provision:{bytes:h.meanFetchBytes()??f.artifactBytes,requests:0},avoided:{bytes:f.avoidedBytes,requests:1}})}return[...i,...lr(c,f).map((d)=>d.id)].slice(0,Lt)}async function Ur(i,c,d){let m=N(t.routes,i.id);if(!m||i.scope!=="public"||i.strategy!==m.route.strategy)return;if(await p.put(i,m.route.persist))h.spend(i.id,{bytes:c,requests:d})}let Gr=()=>ve!==null?{path:ve,sweep:!0}:void 0;async function zr(i,c){if(!Array.isArray(i))return;for(let d of i){let m;try{m=de(d)}catch{continue}h.spend(m.id,{bytes:it.encode(JSON.stringify(d)).length,requests:0},!0);let g=N(t.routes,m.id);if(!g||!to.includes(m.strategy))continue;if(m.strategy!==g.route.strategy||m.scope!==g.route.scope)continue;let w=q;if(m.scope==="principal"){if(w=await J(),!w||w.id!==c)continue}if(await w.replica.get(m.id))continue;await w.replica.put(m,g.route.persist,!0)}}async function qr(i){let c=t.collectors?.find((y)=>y.vendor===i.vendor),d=i.search??"";if(c?.stamp)d=Ft(d,c.stamp,i.at,a());let m=i.method??"POST",g={method:m,credentials:i.origin?"omit":"same-origin"};if(m==="POST"){if(g.body=i.body,i.contentType)g.headers={"content-type":i.contentType}}if(i.origin){let y=i.contentType.split(";")[0]?.trim().toLowerCase()??"",S=["","text/plain","application/x-www-form-urlencoded"].includes(y);g.mode=S?"no-cors":"cors"}let w=await e.fetch(`${i.origin??n}${i.path}${d}`,g);return w.type==="opaque"||w.ok||w.status>=400&&w.status<500}let H=new Xe({storage:r,now:a,want:Vr,catalogue:Gr,replay:qr,async send(i){let c=await e.fetch(`${n}${fe.beacon}`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(i),credentials:"same-origin"});if(c.status===200&&(i.want||i.catalogue)){let d=await c.json();if(i.want){let m=Array.isArray(d.artifacts)?d.artifacts:[];for(let g of m){let w=de(g);await Ur(w,it.encode(JSON.stringify(g)).length,0)}for(let g of i.want)te.delete(g),at.add(g)}if(i.catalogue)await zr(d.catalogue,c.headers.get(B.partition))}return c.ok||c.status>=400&&c.status<500}}),gt=(i)=>new nt({replica:i,fetchSync:Hr,onNetwork:()=>F(H.flushAtMoment()),policy:Fr}),q={id:null,replica:p,scheduler:gt(p),deferred:new Set,loaded:Promise.resolve()},co=q.scheduler,Wr=(i)=>N(t.routes,i)?.route.retention??"session",Kr=()=>t.routes.some((i)=>i.scope==="principal"&&i.retention==="persistent")?"persistent":"session";function yt(i){let c=s.open(i,Wr,Kr()),d=new Se(c,t.version,a);return{id:i,replica:d,scheduler:gt(d),deferred:new Set,loaded:d.load()}}async function Xr(){let i=await s.current();if(i&&!O)O=yt(i)}async function J(){await I();let i=O;if(!i)return null;return await i.loaded,i}function Ee(i){return mt(async()=>{await I();let c=O;if(O=null,!c||!s)return!1;return await s.setCurrent(null),await s.destroy(c.id),e.broadcast?.({type:"spool:cleared",reason:i}),!0})}function Jr(i){return mt(async()=>{await I();let c=O;if(c?.id===i)return;if(O=yt(i),await s.setCurrent(i),c)await s.destroy(c.id),e.broadcast?.({type:"spool:cleared",reason:"partition"})})}async function ht(i,c,d=!1){if(!s||!i||i.protocol!==P)return;await I();let m=i.clear??[];if(m.includes("*")||O&&m.includes(O.id)){await Ee("clear");return}if(d)return;if(i.partition!==void 0){if(O?.id!==i.partition)await Jr(i.partition)}else if(c&&O)await Ee("session-ended")}async function Yr(i,c,d){let m=c.scope==="principal"?await J():q;if(!m||c.scope==="principal"&&m.id!==d)return;let g=await m.replica.held(),w=Object.keys(g).length>0?`&have=${encodeURIComponent(ze(g))}`:"",y=await e.fetch(`${n}${fe.artifact}?path=${encodeURIComponent(i)}${w}`,{cache:"no-store",credentials:"same-origin"});if(y.status===204&&y.headers.get(B.provision)==="declined"){L.add(i);return}if(!y.ok){if(c.scope==="principal"&&[401,403,404].includes(y.status))await m.replica.drop([i]);return}let S=await y.text(),b=de(JSON.parse(S));if(b.scope!==c.scope||b.id!==i)return;if(b.strategy!==c.strategy)return;if(c.scope==="principal"){if(y.headers.get(B.partition)!==d)return;if(O!==m)return}if(await m.replica.put(b,c.persist))h.spend(i,{bytes:it.encode(S).length,requests:1})}async function wt(i){let c=[...i.deferred];if(i.deferred.clear(),await i.scheduler.drain())for(let d of c)await i.replica.validate(d)}async function Zr(i,c,d,m,g,w,y){if(await y(),c&&c.protocol===P){await p.applyEnvelope(c,d,i.has("age"));let S=O;if(S)await S.loaded,await S.replica.applyEnvelope(c,null,!0);let b=c.artifact;if(w&&b){let v=N(t.routes,b.id),x=b.scope==="principal"?await J():q,U=v&&v.route.strategy!=="static"&&v.route.scope===b.scope&&!L.has(b.id)&&x&&(b.scope==="public"||x.id===c.partition);if(v&&x&&U&&!await x.replica.get(b.id))if(b.scope==="public"&&ot(t,v.route)==="shadow")te.add(b.id);else{let E=`${b.scope}:${b.id}`,j=T.get(E)??Yr(b.id,v.route,c.partition);T.set(E,j);try{await j}catch{}finally{T.delete(E)}}}}if(g){if(await wt(q),O)await wt(O);await H.flushAtMoment(),await ln()}}async function Qr(i,c,d,m,g){if(i.method!=="GET"||c.status!==200||c.redirected)return;if(g?.signedOut)return;if(m&&!/text\/html/i.test(c.headers.get("content-type")??""))return;let w=ir(c.headers);if(m)await p.keepPolicy(null,w);let y=g?.route,S=new URL(i.url);if(!y||y.strategy==="static"||S.search!=="")return;let b=y.scope==="principal"?O?.id===d?.partition?O:null:q;if(!b)return;await b.loaded,await b.replica.keepPolicy(S.pathname,w)}async function V(i,c,d){let m=i,g=null;if(!t.manifest&&!c&&i.method==="GET"&&p.cursor!==null)try{let v=new Headers(i.headers);v.set(B.vectorSeen,String(p.cursor)),m=new Request(i,{headers:v}),g=p.cursor}catch{m=i}let w=await e.fetch(m),y=$e(w.headers);await ht(y,c,d?.signedOut);let S=c||i.method!=="GET",b=d?.clone?w.clone():null;return F((async()=>{try{await d?.run(b)}catch{}await Zr(w.headers,y,g,c,S,d?.provision??c,()=>Qr(i,w,y,c,d))})()),w}async function ke(i,c,d){let m=q;if(c.scope==="principal"){if(!s)return{reason:"principal",staleSec:null};let C=await J();if(!C)return{reason:"cold",staleSec:null};m=C}let{replica:g,scheduler:w}=m,y=await g.get(i);if(!y)return{reason:"cold",staleSec:null};let S=()=>y?Math.max(0,Math.floor((a()-g.validatedAt(y))/1000)):null;if(!g.isCurrent(y.artifact)){let C=S();return await g.drop([i]),{reason:"invalidated",staleSec:C}}if(c.version!==void 0&&y.artifact.strategy==="static"&&y.artifact.body.version!==c.version){let C=S();return await g.drop([i]),{reason:"invalidated",staleSec:C}}let b=y.catalogue===!0,v=rr(c.freshness,g.validatedAt(y),a()),x=S(),U=g.needFor(y.artifact,c.sync==="deferred"||c.scope==="principal"),E=(c.scope==="principal"&&U?await g.sweep(U):U)??void 0,j="fresh";if(v==="sync-first"){if(j="hard-sync",!d){let C=await w.sync(E,x);if(!C&&c.offline==="refuse")return{reason:"hard-refused",staleSec:x};if(C){if(E)await g.validate(i);if(y=await g.get(i),!y||!g.isCurrent(y.artifact))return{reason:"stale-after-sync",staleSec:x}}else j="offline-stale"}}else if(v==="serve-then-sync"){if(c.sync==="deferred"){if(j="soft-deferred",!d&&E&&w.defer(E,x))m.deferred.add(i)}else if(j="soft-sync",!d)F(w.sync(E,x).then(async(C)=>{if(C&&E)await g.validate(i)}))}if(c.strategy==="static"){let C=await nn(i);if(!C)return await g.drop([i]),{reason:"refused",staleSec:x};return{reason:j,response:C,staleSec:x}}let le=g.policyOf(i)??p.sitePolicy;if(!le&&!d)return{reason:"refused",staleSec:x};let Et=await g.materialize(y.artifact);if(!Et.ok)return await g.drop([i]),{reason:"refused",staleSec:x};let kt=await gr(t,c,Et.artifact,o);if(!kt.ok)return{reason:"refused",staleSec:x};if(b){if(await g.open(i),qe[j]==="local")j="catalogue"}return{reason:j,html:kt.html,headers:le,staleSec:x}}function en(i){let c;try{c=new URL(i)}catch{return}if(c.protocol!=="http:"&&c.protocol!=="https:")return;if(c.origin!==n)return Wt;return N(t.routes,c.pathname)?.route.pattern}async function tn(i,c,d){let m=Sr(t,c,u),g=a(),w=Pe===null?null:g-Pe;Pe=g,ve=c.catalogue?i:null;let y=await ke(i,c,m),S=en(d.referrer),b=crypto.randomUUID();if(X.delete(i),X.set(i,b),X.size>64)X.delete(X.keys().next().value);let v=(E)=>({id:b,crossOriginLoads:null,tier:m?"shadow":qe[y.reason],reason:y.reason,staleSec:y.staleSec,engine:l,scope:c.scope,strategy:c.strategy,route:c.pattern,mismatch:E,swAgeMs:g-Ir,gapMs:w,...S?{from:S}:{}}),x=async(E)=>{if(t.views!==!1)await H.record(Jt(v(E),g))};if(m){let E=y.html;return V(d,!0,{clone:E!==void 0,route:c,run:async(j)=>{await x(E===void 0||!j?null:await vr(E,j))}})}if(y.response)return h.serve(i),F(x(null)),y.response;if(y.html===void 0){let E=c.strategy==="static",j=await V(d,!0,{clone:E,route:c,run:async(le)=>{if(E)await St(i,c,le);await x(null)}});if(c.scope==="principal"&&bt(j))await Rt(i);return j}h.serve(i,y.reason==="catalogue"),F(x(null));let U=new Headers(y.headers);return U.set("content-type","text/html; charset=utf-8"),new Response(y.html,{headers:U})}function bt(i){return i.status===401||i.status===403||i.type==="opaqueredirect"||i.status>=300&&i.status<400}async function Rt(i){let c=await J();if(c)await c.replica.drop([i])}async function rn(i,c,d){let m=await ke(c,d,!1);if(m.html!==void 0){h.serve(c,m.reason==="catalogue");let w=new Headers(m.headers);return w.set("content-type",d.type??"application/json"),new Response(m.html,{headers:w})}let g=await V(i,!1,{provision:!0,route:d,run:async()=>{return}});if(d.scope==="principal"&&bt(g))await Rt(c);return g}async function nn(i){return(await D(re)).match(lt(i))}async function St(i,c,d){if(!d||d.status!==200||d.redirected)return;let m=t.manifest?N(t.routes,Or(i))?.route:c;if(m?.strategy!=="static")return;let g=await Er(d,Pr);if(!g)return;let w=d.headers.get("content-type")??"application/octet-stream",y;if(t.manifest){let b=m.version;if(b===void 0||!await kr(b,g,d.headers))return;y={protocol:P,id:i,scope:"public",strategy:"static",deps:[],vector:0,body:{type:w,bytes:g.byteLength,version:b}}}else{let b;try{b=Ne(d.headers)}catch{return}let v=b.artifact;if(b.protocol!==P||!v)return;if(v.id!==i||v.scope!=="public")return;y={protocol:P,id:i,scope:"public",strategy:"static",deps:v.deps,vector:v.version,body:{type:w,bytes:g.byteLength}}}if(await(await D(re)).put(lt(i),new Response(g,{headers:xr(d.headers)})),await p.put(y,!0))h.spend(i,{bytes:g.byteLength,requests:0})}async function on(i,c,d){let m=await ke(c,d,!1);if(m.response)return h.serve(c),m.response;return V(i,!1,{clone:!0,run:(g)=>St(c,d,g)})}async function sn(){try{let c=await(await D(re)).match(new Request(t.manifest));if(c){t.routes=Ve(Fe(JSON.parse(await c.text())));return}await vt()}catch{dt=void 0}}async function vt(){let i=t.manifest,c=await e.fetch(i,{cache:"no-store",credentials:"same-origin"});if(!c.ok)throw Error(`manifest answered ${c.status}`);let d=await c.text(),m=Ve(Fe(JSON.parse(d)));t.routes=m,await(await D(re)).put(new Request(i),new Response(d,{headers:{"content-type":"application/json"}}));let w=[];for(let y of await p.ids()){let S=await p.get(y);if(S?.artifact.strategy!=="static")continue;let b=N(m,Or(y));if(!b||S.artifact.body.version!==b.route.version)w.push(y)}return{protocol:P,cursor:p.cursor??0,changed:{},dropped:w,reset:!1}}async function At(i){let c=await D(ct),d=!i.headers.has("range");if(d){let g=await c.match(i);if(g)return g}await I();let m=await V(i,!1);if(d&&m.status===200&&so(m))F(c.put(i,m.clone()));return m}async function an(i,c){if(await I(),!await H.enqueue(i,c))return e.fetch(i);return tr(i)}let ne=t.thirdParty,Pt=(i)=>new Request(i.url);async function cn(i){let d=await(await D(ce)).match(Pt(i));if(d)return d;let m=await e.fetch(i);if(m.status===200&&(m.type!=="opaque"||ne?.allowOpaque)){let g=m.type==="opaque"?"immutable":Tr(new URL(i.url),m.headers,ne?.versioned);if(g)F(xt(i,m.clone(),g))}return m}async function xt(i,c,d){let m=await D(ce),g=c;if(c.type!=="opaque"){let b=new Headers(c.headers);b.set(ee.class,d),b.set(ee.fetched,String(a())),g=new Response(await c.arrayBuffer(),{status:200,headers:b})}await m.put(Pt(i),g);let w=await m.keys(),y=ne?.maxEntries??64;if(w.length<=y)return;let S=[];for(let b of w){let v=await m.match(b);S.push({key:b,at:Number(v?.headers.get(ee.fetched)??0)})}S.sort((b,v)=>b.at-v.at);for(let{key:b}of S.slice(0,w.length-y))await m.delete(b)}async function ln(){if(!ne)return;let i=await D(ce),c=ne.revalidateAfterMs??oo;for(let d of await i.keys()){let m=await i.match(d);if(!m||m.headers.get(ee.class)!=="revalidate")continue;let g=Number(m.headers.get(ee.fetched)??0);if(a()-g<c)continue;try{let w=await e.fetch(new Request(d.url,{cache:"no-cache",mode:"cors",credentials:"omit"}));if(w.status===200&&w.type!=="opaque")await xt(d,w,"revalidate")}catch{}}}async function un(i){await I();let c=rt(t,i,n);if(F(H.flushIfDue()),c.kind==="logout")return await H.sendSameOrigin(er).catch(()=>{return}),await Ee("logout"),V(i,i.mode==="navigate",{signedOut:!0,run:async()=>{return}});if(c.kind==="collector")return an(i,c.collector);if(c.kind==="thirdparty")return cn(i);if(c.kind==="beacon"){if(await H.enqueue(i))return new Response(null,{status:204});return V(i,!1)}if(c.kind==="navigation")return tn(c.path,c.route,i);if(c.kind==="static")return on(i,c.path,c.route);if(c.kind==="data")return rn(i,c.path,c.route);if(c.kind==="asset")return At(i);return V(i,i.mode==="navigate")}return{replica:p,ledger:h,handle(i,c){let d=rt(t,i,n).kind;if(d==="ignore")return;if(d==="asset"&&Ae!=="cache")return;if(Lr&&d!=="navigation"&&d!=="static"&&i.mode!=="navigate")return;return(d==="asset"&&!ft()?At(i):un(i)).catch(()=>e.fetch(i)).finally(()=>c(Dr()))},async install(i){if(Ae==="static-routing")ut=await hr(i,t,n)},async activate(){await I();for(let i of await e.caches.keys())if(ro.some((d)=>i.startsWith(d))&&i!==ct&&i!==re)await e.caches.delete(i)},async message(i){let c=i??{};if(c.type==="spool:hello")return{type:"spool:hello",protocol:P,version:t.version,compatible:c.protocol===P};if(c.type==="spool:status")return await I(),{type:"spool:status",cursor:p.cursor,syncedAt:p.syncedAt,artifacts:await p.ids(),beacons:(await r.readBeacons()).length};if(c.type==="spool:view"){let d=c.path;return{type:"spool:view",id:typeof d==="string"&&X.get(d)||null}}if(c.type==="spool:loads"){let{view:d,count:m,origins:g}=c;if(typeof d==="string"&&typeof m==="number"&&t.views!==!1){await I();let w=typeof g==="object"&&g!==null&&!Array.isArray(g)?g:void 0;await H.record(Xt(d,m,a(),w))}return}if(c.type==="spool:graph")return await I(),await p.held(),{type:"spool:graph",records:p.graph.records.ids(),projections:p.graph.projections.ids()};if(c.type==="spool:ledger")return{type:"spool:ledger",entries:h.entries(),totals:h.totals()};if(c.type==="spool:partition"){let d=await J();if(!d)return{type:"spool:partition",partition:null,artifacts:[],records:[],projections:[]};return await d.replica.held(),{type:"spool:partition",partition:d.id,artifacts:await d.replica.ids(),records:d.replica.graph.records.ids(),projections:d.replica.graph.projections.ids()}}if(c.type==="spool:assets")return{type:"spool:assets",mode:Ae,routed:ut};if(c.type==="spool:held"){let d=await D(ce);return{type:"spool:held",dropped:Object.fromEntries(H.dropped),third:(await d.keys()).map((m)=>m.url).sort()}}return}}}var io="static-1",ao="spool.json";function Br(e){return{protocol:P,version:io,routes:[],templates:{},beacons:[],clientTag:"",views:!1,manifest:new URL(ao,e).href}}function Mr(e,t){let r=self,n=Cr({config:e,storage:pe(),fetch:(o,s)=>fetch(o,s),caches,origin:r.location.origin,renderers:t,partitions:typeof indexedDB>"u"?void 0:It(),broadcast:(o)=>void r.clients.matchAll({type:"window",includeUncontrolled:!0}).then((s)=>s.forEach((a)=>a.postMessage(o)))});r.addEventListener("install",(o)=>o.waitUntil(Promise.all([r.skipWaiting(),n.install(o)]))),r.addEventListener("activate",(o)=>o.waitUntil(Promise.all([n.activate(),r.clients.claim()]))),r.addEventListener("fetch",(o)=>{let s=n.handle(o.request,(a)=>o.waitUntil(a));if(s)o.respondWith(s)}),r.addEventListener("message",(o)=>{o.waitUntil(n.message(o.data).then((s)=>{if(!s)return;let a=o.ports[0];if(a)a.postMessage(s);else o.source?.postMessage(s)}))})}var _r=self;Mr(_r.__SPOOL_CONFIG__??Br(_r.location.href));})();
|
|
1
|
+
(()=>{class D extends Error{code;constructor(e,t){super(t);this.name="ProtocolError",this.code=e}}async function Ae(e){let t=new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(e))),n="";for(let r of t)n+=String.fromCharCode(r);return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}var Bt="dataset proof does not match its items",be=(e)=>typeof e==="object"&&e!==null&&!Array.isArray(e),fe=(e,t)=>Object.hasOwn(e,t)?e[t]:void 0;function rt(e){let t=e?.toJSON;if(typeof e==="object"&&typeof t==="function")return rt(t.call(e));if(Array.isArray(e))return`[${e.map((n)=>rt(n)??"null").join(",")}]`;if(be(e)){let n=[];for(let r of Object.keys(e).sort()){let s=rt(e[r]);if(s!==void 0)n.push(`${JSON.stringify(r)}:${s}`)}return`{${n.join(",")}}`}return JSON.stringify(e)}function nr(e){return rt(e)??"null"}var $t=1n<<256n,We="0".repeat(64),rr=/^[0-9a-f]{64}$/;function Nt(e,t){return Ae(`${e}\x00${nr(t)}`)}function _t(e){if(!/^[A-Za-z0-9_-]{43}$/.test(e))throw RangeError("not a row hash");let t=atob(e.replace(/-/g,"+").replace(/_/g,"/")+"="),n="";for(let r=0;r<t.length;r++)n+=t.charCodeAt(r).toString(16).padStart(2,"0");return BigInt(`0x${n}`)}function sr(e){if(!rr.test(e))throw RangeError("not a set digest");return BigInt(`0x${e}`)}var Wt=(e)=>((e%$t+$t)%$t).toString(16).padStart(64,"0");function st(e,t){return Wt(sr(e)+_t(t))}function or(e,t){return Wt(sr(e)-_t(t))}async function qt(e){let t=await Promise.all([...e].map(([r,s])=>Nt(r,s))),n=0n;for(let r of t)n+=_t(r);return{kind:"set",count:e.size,digest:Wt(n)}}function Lt(e){return be(e)&&e.kind==="set"&&typeof e.count==="number"&&Number.isSafeInteger(e.count)&&e.count>=0&&typeof e.digest==="string"&&rr.test(e.digest)}function ir(e){let t=e.key;if(t===void 0)return;return(n)=>{let r=fe(n,t);if(typeof r!=="string")throw TypeError(`${t} is not a string key`);return r}}async function Oo(e,t,n){if(t.count!==e.length)return!1;let r=new Map;for(let s of e){if(!be(s))return!1;let o;try{o=n(s)}catch{return!1}if(typeof o!=="string"||r.has(o))return!1;r.set(o,s)}return(await qt(r)).digest===t.digest}async function Do(e,t,n){if(!be(t))return!1;let r=fe(t,e.list),s=fe(t,"proof");if(!Array.isArray(r)||!be(s))return!1;let o=s.kind;if(o==="set")return n!==void 0&&Lt(s)&&await Oo(r,s,n);if(o!==void 0&&o!=="ordered")return!1;if(s.count!==r.length||typeof s.digest!=="string")return!1;return await Ae(nr(r))===s.digest}var jo=(e)=>e.trim()!==""&&Number.isFinite(Number(e))?Number(e):null,tr=(e)=>typeof e==="number"?0:typeof e==="string"?1:2;function Co(e,t){let[n,r]=[tr(e),tr(t)];if(n!==r)return n-r;if(n===2)return 0;return e<t?-1:e>t?1:0}function Mo(e,t,n){let r=be(t)?fe(t,e.list):void 0;if(!Array.isArray(r)||!r.every(be))return null;let s=new URLSearchParams(n),o=e.filter??{};for(let y of new Set(s.keys()))if(y!=="sort"&&y!=="page"&&!Object.hasOwn(o,y))return null;let i=r;for(let[y,S]of Object.entries(o)){let x=s.getAll(y);if(x.length===0)continue;if(S==="number"){let T=x.map(jo);if(T.includes(null))return null;i=i.filter((N)=>{let C=fe(N,y);return typeof C==="number"&&T.includes(C)})}else i=i.filter((T)=>{let N=fe(T,y),C=typeof N==="string"||typeof N==="number"||typeof N==="boolean"?String(N):void 0;return C!==void 0&&x.includes(C)})}let a=s.getAll("sort");if(a.length>1)return null;if(i=[...i],a.length===1){let y=a[0],S=e.sort??[],x=!S.includes(y)&&y.startsWith("-"),T=x?y.slice(1):y;if(!S.includes(T))return null;i.sort((N,C)=>{let q=Co(fe(N,T),fe(C,T));return x?-q:q})}let c=s.getAll("page");if(c.length>1)return null;let l=1;if(c.length===1){if(!/^[1-9]\d{0,14}$/.test(c[0]))return null;l=Number(c[0])}let d=i.length,p=e.pageSize,h=p===void 0?1:Math.max(1,Math.ceil(d/p));if(l>h)return null;return{items:p===void 0?i:i.slice((l-1)*p,l*p),total:d,page:l,pages:h}}async function ar(e,t,n,r){if(!await Do(e,t,r))return{ok:!1,reason:Bt};return Ft(e,t,n)}function Ft(e,t,n){let r=Mo(e,t,n);if(!r)return{ok:!1,reason:"query is not one the route declares"};let{items:s,total:o,page:i,pages:a}=r,c={total:o,page:i,pages:a};return{ok:!0,data:{...t,[e.list]:s,query:c}}}function Vt(e){let t=e.indexOf("/");if(t<1||t===e.length-1)return null;return{dataset:e.slice(0,t),key:e.slice(t+1)}}function qe(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function ot(e){if(!qe(e))return!1;let t=Object.keys(e);if(t.length!==1)return!1;let n=t[0];return(n==="$record"||n==="$projection"||n==="$row")&&typeof e[n]==="string"}function ge(e){let t=new Set,n=new Set,r=new Set,s=(o)=>{if(Array.isArray(o))return o.forEach(s);if(!qe(o))return;if(ot(o)){if("$record"in o)t.add(o.$record);else if("$row"in o)r.add(o.$row);else n.add(o.$projection);return}Object.values(o).forEach(s)};return s(e),{records:[...t].sort(),projections:[...n].sort(),...r.size>0?{rows:[...r].sort()}:{}}}function Ut(e,t){let n=(r,s)=>{if(Array.isArray(r))return r.map((o)=>n(o,s));if(!qe(r))return r;if(ot(r)){if("$record"in r){let a=t.record(r.$record);if(!a)throw Error(`record ${r.$record} is not stored`);return a.data}if("$row"in r){let a=Vt(r.$row),c=a?t.row?.(a.dataset,a.key):void 0;if(c===void 0)throw Error(`row ${r.$row} is not held`);return c}let o=r.$projection;if(s.includes(o))throw Error(`projection ${o} reaches itself`);let i=t.projection(o);if(!i)throw Error(`projection ${o} is not stored`);return n(i.data,[...s,o])}return Object.fromEntries(Object.entries(r).map(([o,i])=>[o,n(i,s)]))};try{return{ok:!0,value:n(e,[])}}catch(r){return{ok:!1,reason:r instanceof Error?r.message:"unresolved reference"}}}function pe(e){throw new D("bad-artifact",e)}function cr(e,t){if(typeof e!=="number"||!Number.isSafeInteger(e)||e<0)return pe(`${t} version must be a non-negative integer`);return e}function ur(e){if(!qe(e))return pe("record must be an object");if(typeof e.id!=="string"||e.id==="")return pe("record id");if(!("data"in e))return pe(`record ${e.id} needs data`);return{id:e.id,version:cr(e.version,"record"),data:e.data}}function lr(e){if(!qe(e))return pe("projection must be an object");let{id:t,deps:n}=e;if(typeof t!=="string"||t==="")return pe("projection id");if(!Array.isArray(n)||n.some((r)=>typeof r!=="string"))return pe(`projection ${t} deps must be a list of strings`);if(!("data"in e))return pe(`projection ${t} needs data`);return{id:t,version:cr(e.version,"projection"),deps:n,data:e.data}}var j=1;function J(e){throw new D("bad-artifact",e)}function zt(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function dr(e,t){if(e===void 0)return;if(!zt(e))return J(`${t} must be an object`);for(let n of Object.values(e))if(typeof n!=="string"&&!ot(n))return J(`${t} values must be strings or references`);return e}function fr(e,t,n){if(e===void 0)return;if(!Array.isArray(e))return J(`${t} must be a list`);return e.map(n)}function Le(e){if(!zt(e))return J("artifact must be an object");if(e.protocol!==j)return J("unsupported protocol version");let{id:t,scope:n,deps:r,vector:s,strategy:o,body:i}=e;if(typeof t!=="string"||!t.startsWith("/"))return J("id must be a path");if(n!=="public"&&n!=="principal")return J("scope must be public or principal");if(!Array.isArray(r)||r.some((d)=>typeof d!=="string"))return J("deps must be a list of strings");if(typeof s!=="number"||!Number.isSafeInteger(s)||s<0)return J("vector must be a non-negative integer");if(!zt(i))return J("body must be an object");let a={protocol:j,id:t,scope:n,deps:r,vector:s},c=fr(e.records,"records",ur),l=fr(e.projections,"projections",lr);if(c)a.records=c;if(l)a.projections=l;if(o==="template"||o==="projection"||o==="data"){if(!("data"in i))return J(`${o} body needs data`);return{...a,strategy:o,body:{data:i.data}}}if(o==="assembly"){if(typeof i.shell!=="string")return J("assembly body needs a shell string");let d={shell:i.shell},p=dr(i.fragments,"fragments"),h=dr(i.slots,"slots");if(p)d.fragments=p;if(h)d.slots=h;return{...a,strategy:o,body:d}}return J(`unknown strategy ${String(o)}`)}function I(e){return new Promise((t,n)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>n(e.error)})}function Gt(e){return new Promise((t,n)=>{e.oncomplete=()=>t(),e.onerror=()=>n(e.error),e.onabort=()=>n(e.error)})}function it(e=indexedDB,t="spool"){let n,r,s=()=>n??=new Promise((a,c)=>{let l=e.open(t,2);l.onupgradeneeded=()=>{let d=l.result,p=(h)=>!d.objectStoreNames.contains(h);if(p("artifacts"))d.createObjectStore("artifacts",{keyPath:"artifact.id"});if(p("meta"))d.createObjectStore("meta");if(p("beacons"))d.createObjectStore("beacons",{autoIncrement:!0});if(p("records"))d.createObjectStore("records",{keyPath:"id"});if(p("projections"))d.createObjectStore("projections",{keyPath:"id"})},l.onsuccess=()=>{let d=l.result;d.onversionchange=()=>{d.close(),n=void 0},a(d)},l.onerror=()=>c(l.error)}),o=()=>r??=new Promise((a,c)=>{let l=e.open(`${t}-datasets`,1);l.onupgradeneeded=()=>{let d=l.result;d.createObjectStore("datasetRows",{keyPath:["name","key"]}),d.createObjectStore("datasetMeta",{keyPath:"name"})},l.onsuccess=()=>{let d=l.result;d.onversionchange=()=>{d.close(),r=void 0},a(d)},l.onerror=()=>c(l.error)});async function i(a,c,l,d=s){let h=(await d()).transaction(a,c),y=Gt(h),S=await l(h.objectStore(a));return await y,S}return{destroy:async()=>{let a=await Promise.all([n,r].map((c)=>c?.catch(()=>{return})));for(let c of a)c?.close();n=void 0,r=void 0;for(let c of[t,`${t}-datasets`])await new Promise((l)=>{let d=e.deleteDatabase(c);d.onsuccess=()=>l(),d.onerror=()=>l()})},getArtifact:(a)=>i("artifacts","readonly",(c)=>I(c.get(a))),putArtifact:(a)=>i("artifacts","readwrite",async(c)=>void await I(c.put(a))),deleteArtifacts:(a)=>i("artifacts","readwrite",async(c)=>{await Promise.all(a.map((l)=>I(c.delete(l))))}),allArtifacts:()=>i("artifacts","readonly",(a)=>I(a.getAll())),clearArtifacts:()=>i("artifacts","readwrite",async(a)=>void await I(a.clear())),getMeta:()=>i("meta","readonly",(a)=>I(a.get("replica"))),setMeta:(a)=>i("meta","readwrite",async(c)=>void await I(c.put(a,"replica"))),addBeacon:(a)=>i("beacons","readwrite",async(c)=>void await I(c.add(a))),readBeacons:()=>i("beacons","readonly",async(a)=>{let[c,l]=await Promise.all([I(a.getAllKeys()),I(a.getAll())]);return c.map((d,p)=>({key:d,event:l[p]}))}),removeBeacons:(a)=>i("beacons","readwrite",async(c)=>{await Promise.all(a.map((l)=>I(c.delete(l))))}),getFlush:()=>i("meta","readonly",(a)=>I(a.get("flush"))),setFlush:(a)=>i("meta","readwrite",async(c)=>void await I(c.put(a,"flush"))),putRecords:(a)=>i("records","readwrite",async(c)=>{await Promise.all(a.map((l)=>I(c.put(l))))}),allRecords:()=>i("records","readonly",(a)=>I(a.getAll())),deleteRecords:(a)=>i("records","readwrite",async(c)=>{await Promise.all(a.map((l)=>I(c.delete(l))))}),putProjections:(a)=>i("projections","readwrite",async(c)=>{await Promise.all(a.map((l)=>I(c.put(l))))}),allProjections:()=>i("projections","readonly",(a)=>I(a.getAll())),deleteProjections:(a)=>i("projections","readwrite",async(c)=>{await Promise.all(a.map((l)=>I(c.delete(l))))}),clearGraph:async()=>{await i("records","readwrite",async(a)=>void await I(a.clear())),await i("projections","readwrite",async(a)=>void await I(a.clear()))},getDatasets:()=>i("datasetMeta","readonly",(a)=>I(a.getAll()),o),readDataset:(a)=>i("datasetRows","readonly",(c)=>I(c.getAll(IDBKeyRange.bound([a],[a,[]]))),o),commitDataset:async(a)=>{let l=(await o()).transaction(["datasetRows","datasetMeta"],"readwrite",{durability:"strict"}),d=Gt(l);d.catch(()=>{return});try{let p=l.objectStore("datasetRows"),h=l.objectStore("datasetMeta");if(a.clear)p.delete(IDBKeyRange.bound([a.name],[a.name,[]]));for(let y of a.deletes)p.delete([a.name,y]);for(let y of a.puts)p.put(y);if(a.meta)h.put(a.meta);else h.delete(a.name)}catch(p){try{l.abort()}catch{}throw p}await d},clearDatasets:async()=>{let c=(await o()).transaction(["datasetRows","datasetMeta"],"readwrite"),l=Gt(c);c.objectStore("datasetRows").clear(),c.objectStore("datasetMeta").clear(),await l}}}var Qt=new TextEncoder,Io=new TextDecoder;async function Fe(e,t,n,r){let s=crypto.getRandomValues(new Uint8Array(12)),o=await crypto.subtle.encrypt({name:"AES-GCM",iv:s,additionalData:Qt.encode(t)},e,Qt.encode(JSON.stringify(n)));return{sealed:{iv:s,data:o,at:r}}}async function Ee(e,t,n,r){let s=r?.sealed;if(!s)return;let o=await e.get(t,s.at,!1);if(!o)return;try{let i=await crypto.subtle.decrypt({name:"AES-GCM",iv:s.iv,additionalData:Qt.encode(n)},o,s.data);return JSON.parse(Io.decode(i))}catch{return}}function pr(e,t){let{partition:n,vault:r}=t,s=!1,o=(c,l)=>`${n}\x00${c}\x00${l}`;async function i(c,l,d,p){let h=await r.get(n,c,!0);if(!h)throw Error("no key");return Fe(h,o(l,d),p,c)}let a=(c,l,d)=>Ee(r,n,o(c,l),d);return{kill:()=>{s=!0,t.datasets?.kill()},async getArtifact(c){if(s)return;let l=await e.getArtifact(c);if(!l)return;let d=await a("artifact",c,l);if(!d)await e.deleteArtifacts([c]);return d},async putArtifact(c){if(s)return;let l=c.artifact.id,d=await i(t.retentionOf(l),"artifact",l,c);if(s)return;await e.putArtifact({artifact:{id:l},...d})},deleteArtifacts:(c)=>s?Promise.resolve():e.deleteArtifacts(c),async allArtifacts(){if(s)return[];let c=[],l=[];for(let d of await e.allArtifacts()){let p=d.artifact.id,h=await a("artifact",p,d);if(h)c.push(h);else l.push(p)}if(l.length>0)await e.deleteArtifacts(l);return c},clearArtifacts:()=>s?Promise.resolve():e.clearArtifacts(),async getMeta(){if(s)return;return a("meta","replica",await e.getMeta())},async setMeta(c){if(s)return;let l=await i(t.shared,"meta","replica",c);if(!s)await e.setMeta(l)},addBeacon:(c)=>e.addBeacon(c),readBeacons:()=>e.readBeacons(),removeBeacons:(c)=>e.removeBeacons(c),getFlush:()=>e.getFlush(),setFlush:(c)=>e.setFlush(c),async putRecords(c){if(s)return;let l=await Promise.all(c.map(async(d)=>({id:d.id,version:d.version,...await i(t.shared,"record",d.id,d)})));if(!s)await e.putRecords(l)},async allRecords(){if(s)return[];let c=[];for(let l of await e.allRecords()){let d=await a("record",l.id,l);if(d)c.push(d)}return c},deleteRecords:(c)=>s?Promise.resolve():e.deleteRecords(c),async putProjections(c){if(s)return;let l=await Promise.all(c.map(async(d)=>({id:d.id,version:d.version,...await i(t.shared,"projection",d.id,d)})));if(!s)await e.putProjections(l)},async allProjections(){if(s)return[];let c=[];for(let l of await e.allProjections()){let d=await a("projection",l.id,l);if(d)c.push(d)}return c},deleteProjections:(c)=>s?Promise.resolve():e.deleteProjections(c),clearGraph:()=>s?Promise.resolve():e.clearGraph(),getDatasets:t.datasets?.getDatasets??(async()=>[]),readDataset:t.datasets?.readDataset??(async()=>[]),commitDataset:t.datasets?.commitDataset??(()=>Promise.reject(Error("a principal partition holds no dataset"))),clearDatasets:t.datasets?.clearDatasets??(async()=>{return})}}var yr="spool-principal-datasets",ue="rows",oe="meta",$o=new TextEncoder;function Bo(e){return new Promise((t,n)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>n(e.error)})}function at(e){return new Promise((t,n)=>{e.oncomplete=()=>t(),e.onerror=()=>n(e.error),e.onabort=()=>n(e.error)})}var He=(e)=>IDBKeyRange.bound([e],[e,[]]),gr=(e,t)=>IDBKeyRange.bound([e,t],[e,t,[]]);function hr(e,t){let n,r=()=>n??=new Promise((i,a)=>{let c=e.open(yr,1);c.onupgradeneeded=()=>{let l=c.result;l.createObjectStore(ue,{keyPath:["partition","name","slot"]}),l.createObjectStore(oe,{keyPath:["partition","name"]})},c.onsuccess=()=>{let l=c.result;l.onversionchange=()=>{l.close(),n=void 0},i(l)},c.onerror=()=>a(c.error)}),s=(i)=>{let{partition:a,...c}=i;return c};async function o(i,a){let l=(await r()).transaction(i,"readonly"),d=at(l),p=await Bo(a(l.objectStore(i)));return await d,p}return{metas:async()=>(await o(oe,(i)=>i.getAll(He(t)))).map((i)=>s(i)),meta:async(i)=>{let a=await o(oe,(c)=>c.get([t,i]));return a?s(a):void 0},rows:async(i)=>(await o(ue,(a)=>a.getAll(gr(t,i)))).map((a)=>s(a)),commit:async(i)=>{let c=(await r()).transaction([ue,oe],"readwrite",{durability:"strict"}),l=at(c);l.catch(()=>{return});try{let d=c.objectStore(ue),p=c.objectStore(oe);if(i.clear)d.delete(gr(t,i.name));for(let h of i.deletes)d.delete([t,i.name,h]);for(let h of i.puts)d.put({partition:t,...h});if(i.meta)p.put({partition:t,...i.meta});else p.delete([t,i.name])}catch(d){try{c.abort()}catch{}throw d}await l},clear:async()=>{let a=(await r()).transaction([ue,oe],"readwrite"),c=at(a);a.objectStore(ue).delete(He(t)),a.objectStore(oe).delete(He(t)),await c}}}async function wr(e,t){let n=await new Promise((r)=>{let s=e.open(yr);s.onupgradeneeded=()=>{try{s.transaction?.abort()}catch{}},s.onsuccess=()=>r(s.result),s.onerror=()=>r(null),s.onblocked=()=>r(null)});if(!n)return;try{if(!n.objectStoreNames.contains(ue)||!n.objectStoreNames.contains(oe))return;let r=n.transaction([ue,oe],"readwrite"),s=at(r);r.objectStore(ue).delete(He(t)),r.objectStore(oe).delete(He(t)),await s}catch{}finally{n.close()}}function mr(e){let t="";for(let n of e)t+=String.fromCharCode(n);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function br(e,t){let{partition:n,vault:r,retention:s}=t,o=!1,i=new Map,a=(y)=>`${n}\x00dataset-meta\x00${y}`,c=(y,S)=>`${n}\x00dataset-row\x00${y}\x00${S}`;async function l(y,S){let x=await r.get(n,s,!0);if(!x)throw Error("no key");return Fe(x,y,S,s)}async function d(y,S,x){let T=$o.encode(`${x}\x00${y}\x00${S}`);return mr(new Uint8Array(await crypto.subtle.digest("SHA-256",T)))}async function p(y){let S=await Ee(r,n,a(y.name),y);if(S)return i.set(y.name,S.salt),S;i.delete(y.name),await e.commit({name:y.name,meta:null,clear:!0,puts:[],deletes:[]});return}async function h(y){let S=i.get(y);if(S!==void 0)return S;let x=await e.meta(y);return x?(await p(x))?.salt:void 0}return{kill:()=>void(o=!0),async getDatasets(){if(o)return[];let y=[];for(let S of await e.metas()){let x=await p(S);if(x)y.push(x.meta)}return y},async readDataset(y){if(o||await h(y)===void 0)return[];let S=[];for(let x of await e.rows(y)){let T=await Ee(r,n,c(y,x.slot),x);if(T&&T.name===y)S.push(T)}return S.sort((x,T)=>x.key<T.key?-1:x.key>T.key?1:0)},async commitDataset(y){if(o)return;let{name:S}=y;if(y.meta===null){await e.commit({name:S,meta:null,clear:!0,puts:[],deletes:[]}),i.delete(S);return}let x=y.clear?void 0:await h(S),T=x===void 0;x??=mr(crypto.getRandomValues(new Uint8Array(16)));let N=[];for(let H of y.puts){let ae=await d(S,H.key,x);N.push({name:S,slot:ae,...await l(c(S,ae),H)})}let C=await Promise.all(y.deletes.map((H)=>d(S,H,x))),q=await l(a(S),{meta:y.meta,salt:x});if(o)return;await e.commit({name:S,meta:{name:S,...q},clear:y.clear||T,puts:N,deletes:C}),i.set(S,x)},async clearDatasets(){if(o)return;await e.clear(),i.clear()}}}var No=/^[A-Za-z_][A-Za-z0-9_]*$/;function Jt(e){let t=e.length>1&&e.endsWith("/")?e.slice(0,-1):e;return t==="/"?[]:t.slice(1).split("/")}function ct(e){if(!e.startsWith("/"))throw new D("bad-pattern",`pattern must start with "/": ${e}`);let t=new Set,n=Jt(e);for(let[r,s]of n.entries()){if(s==="")throw new D("bad-pattern",`empty segment in ${e}`);if(s==="**"){if(r!==n.length-1)throw new D("bad-pattern",`"**" must be the last segment in ${e}`);continue}if(!s.startsWith(":"))continue;let o=s.slice(1);if(!No.test(o))throw new D("bad-pattern",`bad parameter name "${o}" in ${e}`);if(t.has(o))throw new D("bad-pattern",`duplicate parameter "${o}" in ${e}`);t.add(o)}}function ut(e,t){let n=Jt(e),r=Jt(t),s=n[n.length-1]==="**";if(s)n.pop();if(s?r.length<n.length:n.length!==r.length)return null;let o={};for(let i=0;i<n.length;i++){let a=n[i],c=r[i];if(a.startsWith(":")){if(c==="")return null;try{o[a.slice(1)]=decodeURIComponent(c)}catch{return null}}else if(a!==c)return null}return o}var Rr={id:"spool-write-id"};var _o=/^[A-Za-z0-9._:~-]{1,128}$/;var Wo=256;var Sr={"writes-off":403,"unknown-write":404,"bad-method":405,"bad-key":400,"missing-version":428,"bad-version":400,"bad-id":400,"bad-body":400,"too-large":413,"too-many":429,"id-reused":422,forbidden:403,"sign-in":401,"no-partition":409,"no-record":404,"not-conflicted":409,unavailable:503};function Pr(e){return typeof e==="string"&&e.length>0&&e.length<=Wo&&!e.includes("\x00")}var lt=(e)=>typeof e==="string"&&_o.test(e);var vr=(e)=>`"${e}"`;function dt(){let e=crypto.getRandomValues(new Uint8Array(16)),t="";for(let n of e)t+=String.fromCharCode(n);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}var xr="spool-writes",Te="queue",qo=new TextEncoder;function Ve(e){return new Promise((t,n)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>n(e.error)})}function kr(e){return new Promise((t,n)=>{e.oncomplete=()=>t(),e.onerror=()=>n(e.error),e.onabort=()=>n(e.error)})}var Ar=(e)=>IDBKeyRange.bound([e],[e,[]]);function Er(e,t,n){let r,s=()=>r??=new Promise((c,l)=>{let d=e.open(xr,1);d.onupgradeneeded=()=>{d.result.createObjectStore(Te,{keyPath:["partition","name","key"]})},d.onsuccess=()=>{let p=d.result;p.onversionchange=()=>{p.close(),r=void 0},c(p)},d.onerror=()=>l(d.error)}),o=(c,l)=>`${t}\x00write\x00${c}\x00${l}`;async function i(c,l){let p=(await s()).transaction(Te,c),h=kr(p),y=await l(p.objectStore(Te));return await h,y}let a=async(c)=>c&&await Ee(n,t,o(c.name,c.key),c);return{get:async(c,l)=>a(await i("readonly",(d)=>Ve(d.get([t,c,l])))),put:async(c)=>{let l=await n.get(t,"persistent",!0);if(!l)throw Error("no key");let d=await Fe(l,o(c.name,c.key),c,"persistent");await i("readwrite",async(p)=>{await Ve(p.put({partition:t,name:c.name,key:c.key,...d}))})},delete:(c,l)=>i("readwrite",async(d)=>void await Ve(d.delete([t,c,l]))),all:async()=>{let c=await i("readonly",(d)=>Ve(d.getAll(Ar(t)))),l=[];for(let d of c){let p=await a(d);if(p)l.push(p);else await i("readwrite",async(h)=>void await Ve(h.delete([t,d.name,d.key])))}return l}}}async function Tr(e,t){let n=await new Promise((r)=>{let s=e.open(xr);s.onupgradeneeded=()=>{try{s.transaction?.abort()}catch{}},s.onsuccess=()=>r(s.result),s.onerror=()=>r(null),s.onblocked=()=>r(null)});if(!n)return;try{if(!n.objectStoreNames.contains(Te))return;let r=n.transaction(Te,"readwrite"),s=kr(r);r.objectStore(Te).delete(Ar(t)),await s}catch{}finally{n.close()}}var G=(e,t)=>({ok:!1,code:e,message:t}),Lo=new Set(Object.keys(Sr)),Fo=(e)=>{let t=e?.code;return typeof t==="string"&&Lo.has(t)?t:void 0};function Ho(e){let t=e?.conflict;if(!t||!lt(t.version))return;return"value"in t?{version:t.version,value:t.value}:{version:t.version}}class Re{#e;#t=Promise.resolve();#n=null;#r=!1;constructor(e){this.#e=e}kill(){this.#r=!0}#s(e){let t=this.#t.then(e,e);return this.#t=t.catch(()=>{return}),t}write(e,t,n,r){if(this.#r)return Promise.resolve(G("no-partition","the queue was wiped"));let s=this.#e.classes().find((i)=>i.name===e);if(!s)return Promise.resolve(G("unknown-write",`no write class "${e}"`));if(!Pr(t))return Promise.resolve(G("bad-key","the key is malformed"));if(r===void 0||r===null)return Promise.resolve(G("missing-version","say which version the edit started from"));if(!lt(r))return Promise.resolve(G("bad-version","the version is malformed"));let o;try{let i=JSON.stringify({value:n});if(n===void 0)throw Error("no value");o=qo.encode(i).length}catch{return Promise.resolve(G("bad-body","the value is not JSON"))}if(o>s.maxBytes)return Promise.resolve(G("too-large",`the value is over ${s.maxBytes} bytes`));return this.#s(async()=>{if(this.#r)return G("no-partition","the queue was wiped");let i=this.#e.now(),a=await this.#e.store.get(e,t);if(!a){if((await this.#e.store.all()).filter((h)=>h.name===e).length>=s.maxPending)return G("too-many",`${s.maxPending} keys of "${e}" are already queued`);let p={name:e,key:t,value:n,base:r,id:dt(),state:"pending",queuedAt:i,updatedAt:i,bytes:o,edits:1,attempts:0};return await this.#e.store.put(p),{ok:!0,state:p.state,edits:1}}let c=a.state==="flushing"||a.attempts>0,l={...a,updatedAt:i,edits:a.edits+1,...c&&a.state!=="conflicted"?{next:{value:n,bytes:o}}:{value:n,bytes:o}};return await this.#e.store.put(l),{ok:!0,state:l.state,edits:l.edits}})}list(){return this.#s(async()=>{if(this.#r)return[];return(await this.#e.store.all()).sort((t,n)=>t.queuedAt-n.queuedAt||(t.key<n.key?-1:1)).map((t)=>({name:t.name,key:t.key,state:t.state,base:t.base,queuedAt:t.queuedAt,updatedAt:t.updatedAt,bytes:t.bytes,attempts:t.attempts,...t.conflict?{conflict:t.conflict}:{},...t.refusal?{refusal:t.refusal}:{}}))})}flush(e){if(this.#n&&!e)return this.#n;let t=this.#o(e);if(!e)return this.#n=t.finally(()=>{this.#n=null}),this.#n;return t}async#o(e){let t={queued:0,flushed:0,conflicted:0};if(this.#r)return t;let n=await this.#s(async()=>this.#r?[]:(await this.#e.store.all()).filter((r)=>r.state!=="conflicted"));for(let r of n){if(e&&(r.name!==e.name||r.key!==e.key))continue;let s=await this.#s(async()=>{if(this.#r)return;let a=await this.#e.store.get(r.name,r.key);if(!a||a.state==="conflicted")return;let c={...a,state:"flushing"};return await this.#e.store.put(c),c});if(!s)continue;t.queued+=1;let o;try{o=await this.#e.send(s)}catch{o=void 0}if(await this.#s(()=>this.#i(s,o,t)).catch(()=>!0))break}if(t.queued>0&&!this.#r)this.#e.onFlush?.(t);return t}async#i(e,t,n){if(this.#r)return!0;let{store:r}=this.#e,s=this.#e.now(),o=await r.get(e.name,e.key);if(!o)return!1;let i=async(d)=>(await r.put({...o,state:"pending",updatedAt:s,attempts:o.attempts+(d?1:0)}),!0);if(!t)return i(!0);let{status:a,body:c}=t;if(a===200){let d=c?.version;if(!lt(d))return i(!0);if(n.flushed+=1,!o.next)return await r.delete(o.name,o.key),!1;let{value:p,bytes:h}=o.next;return await r.put({name:o.name,key:o.key,value:p,bytes:h,base:d,id:dt(),state:"pending",queuedAt:o.queuedAt,updatedAt:s,edits:1,attempts:0}),!1}let l=Fo(c);if(a===412){let d=Ho(c);if(d)return n.conflicted+=1,await r.put(this.#a(o,s,{conflict:d})),!1;return n.conflicted+=1,await r.put(this.#a(o,s,{refusal:"unavailable"})),!1}if(a===401||a===429||l==="writes-off"||l==="sign-in")return i(!1);if(a>=500||a===408)return i(!0);return n.conflicted+=1,await r.put(this.#a(o,s,{refusal:l??"unavailable"})),!1}#a(e,t,n){let{next:r,conflict:s,refusal:o,...i}=e;return{...i,...r?{value:r.value,bytes:r.bytes}:{},state:"conflicted",updatedAt:t,...n}}async resolve(e,t,n){if(this.#r)return G("no-partition","the queue was wiped");if(n!=="local"&&n!=="server")return G("bad-body",'resolve with "local" or "server"');let r=await this.#s(async()=>{if(this.#r)return G("no-partition","the queue was wiped");let s=await this.#e.store.get(e,t);if(!s)return G("no-record","nothing is queued for that key");if(s.state!=="conflicted")return G("not-conflicted","that record has no conflict to resolve");if(n==="server")return await this.#e.store.delete(e,t),{ok:!0,...s.conflict?{server:s.conflict}:{}};let{conflict:o,refusal:i,...a}=s;return await this.#e.store.put({...a,base:o?.version??s.base,id:dt(),state:"pending",updatedAt:this.#e.now(),edits:1,attempts:0}),{ok:!0}});if(!r.ok||n==="server")return r;return{ok:!0,flush:await this.flush({name:e,key:t})}}}var Vo="spool-keys",Xt="keys",Yt="meta",Kt="partition";function Oe(e){return new Promise((t,n)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>n(e.error)})}function Or(e){return new Promise((t,n)=>{let r=e.open(Vo,1);r.onupgradeneeded=()=>{r.result.createObjectStore(Xt),r.result.createObjectStore(Yt)},r.onsuccess=()=>{let s=r.result;s.onversionchange=()=>s.close(),t(s)},r.onerror=()=>n(r.error)})}function Uo(e=indexedDB){let t=new Map,n=Promise.resolve(),r=(i)=>{let a=n.then(i,i);return n=a.catch(()=>{return}),a},s=()=>crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);async function o(i,a){let c=await Or(e);try{let l=c.transaction(Xt,i),d=new Promise((h,y)=>{l.oncomplete=()=>h(),l.onerror=()=>y(l.error),l.onabort=()=>y(l.error)}),p=await a(l.objectStore(Xt));return await d,p}finally{c.close()}}return{get:(i,a,c)=>r(async()=>{if(a==="session"){let p=t.get(i);if(!p&&c)p=await s(),t.set(i,p);return p}let l=await o("readonly",(p)=>Oe(p.get(i)));if(l||!c)return l;let d=await s();return await o("readwrite",async(p)=>void await Oe(p.put(d,i))),d}),shred:(i)=>r(async()=>{t.delete(i),await o("readwrite",async(a)=>void await Oe(a.delete(i)))})}}function Dr(e=indexedDB,t=Uo(e)){let n=new Map,r=(o)=>`spool-p-${o}`;async function s(o,i){let a=await Or(e);try{let c=a.transaction(Yt,o),l=new Promise((p,h)=>{c.oncomplete=()=>p(),c.onerror=()=>h(c.error),c.onabort=()=>h(c.error)}),d=await i(c.objectStore(Yt));return await l,d}finally{a.close()}}return{current:async()=>await s("readonly",(o)=>Oe(o.get(Kt)))??null,setCurrent:(o)=>s("readwrite",async(i)=>{if(o===null)await Oe(i.delete(Kt));else await Oe(i.put(o,Kt))}),open(o,i,a,c=!1){let l=n.get(o);if(l)return l.sealed;let d=it(e,r(o)),p=pr(d,{partition:o,vault:t,retentionOf:i,shared:a,...c?{datasets:br(hr(e,o),{partition:o,vault:t,retention:a})}:{}});return n.set(o,{sealed:p,destroy:d.destroy}),p},openWrites:(o)=>Er(e,o,t),async destroy(o){let i=n.get(o);if(i?.sealed.kill(),n.delete(o),await t.shred(o),await Tr(e,o),await wr(e,o),i)await i.destroy();else await new Promise((a)=>{let c=e.deleteDatabase(r(o));c.onsuccess=()=>a(),c.onerror=()=>a()})}}}var Zt="/.spool/dropped",jr="/.spool/",Cr=65536;var Mr=8;var Ir=3600000,Ma=48*Ir,Ia=72*Ir;function $r(e,t){if(!e||e.length===0)return;let n;try{n=new URL(t)}catch{return}return e.find((r)=>{let s=new URL(r.match);return n.origin===s.origin&&n.pathname.startsWith(s.pathname)})}function zo(e,t,n){if(e==="age-ms")return String(Math.max(0,Math.round(n-t)));if(e==="epoch-ms")return String(Math.round(t));if(e==="epoch-s")return String(Math.floor(t/1000));return new Date(t).toISOString().slice(0,19).replace("T"," ")}function Br(e,t,n,r){let s=new URLSearchParams(e);s.set(t.param,zo(t.kind,n,r));let o=s.toString();return o===""?"":`?${o}`}var Se={sync:"/.spool/sync",artifact:"/.spool/artifact",dataset:"/.spool/dataset",beacon:"/.spool/beacon",write:"/.spool/write",worker:"/spool-sw.js"};var W={protocol:"spool-protocol",artifact:"spool-artifact",invalidate:"spool-invalidate",clear:"spool-clear",vector:"spool-vector",partition:"spool-partition",vectorSeen:"spool-vector-seen",provision:"spool-provision",provisionReason:"spool-provision-reason"},en="*",Go=/^[A-Za-z0-9_-]{1,128}$/,Qo=/^[A-Za-z0-9_-]{43}$/;function Pe(e){throw new D("bad-header",e)}function Ue(e,t){if(!/^\d{1,15}$/.test(e.trim()))return Pe(`${t} must be a non-negative integer`);return Number(e)}function ze(e,t){try{return decodeURIComponent(e)}catch{return Pe(`${t} has a bad escape`)}}function ft(e){return e.split(",").map((t)=>t.trim()).filter((t)=>t!=="")}function pt(e){try{return tn(e)}catch{let t=e.get(W.protocol)?.trim();if(t&&/^\d{1,15}$/.test(t)&&Number(t)!==j)return;let n=e.get(W.clear);if(n===null)return;try{return{protocol:j,clear:ft(n).map((r)=>ze(r,"Spool-Clear"))}}catch{return{protocol:j,clear:[en]}}}}function tn(e){let t={},n=e.get(W.protocol);if(n!==null)t.protocol=Ue(n,"Spool-Protocol");let r=e.get(W.artifact);if(r!==null){let l=new Map;for(let S of r.split(";")){let x=S.indexOf("=");if(x<1)return Pe("Spool-Artifact has a field without a name");l.set(S.slice(0,x).trim(),S.slice(x+1).trim())}let d=l.get("id"),p=l.get("scope"),h=l.get("v");if(d===void 0||h===void 0)return Pe("Spool-Artifact needs id and v");if(p!=="public"&&p!=="principal")return Pe("Spool-Artifact scope is unknown");t.artifact={id:ze(d,"Spool-Artifact id"),scope:p,deps:ft(l.get("deps")??"").map((S)=>ze(S,"Spool-Artifact deps")),version:Ue(h,"Spool-Artifact v")};let y=l.get("h");if(y!==void 0&&Qo.test(y))t.artifact.hash=y}let s=e.get(W.invalidate);if(s!==null)t.invalidate=Object.fromEntries(ft(s).map((l)=>{let d=l.lastIndexOf("=");if(d<1)return Pe("Spool-Invalidate entries are tag=version");return[ze(l.slice(0,d),"Spool-Invalidate tag"),Ue(l.slice(d+1),"Spool-Invalidate version")]}));let o=e.get(W.clear);if(o!==null)t.clear=ft(o).map((l)=>ze(l,"Spool-Clear"));let i=e.get(W.vector);if(i!==null)t.vector=Ue(i,"Spool-Vector");let a=e.get(W.vectorSeen);if(a!==null)t.seen=Ue(a,"Spool-Vector-Seen");let c=e.get(W.partition);if(c!==null){if(!Go.test(c))return Pe("Spool-Partition must be a base64url token");t.partition=c}return t}var qa=new RegExp(`[<>&${String.fromCharCode(8232,8233)}]`,"g");function Nr(e){let t=e.lastIndexOf('<script type="application/spool+json" data-spool-artifact>');if(t<0)return null;let n=t+58,r=e.indexOf("</script>",n);return r<0?null:e.slice(n,r)}function _r(e){let t="",n=0;for(;;){let r=e.indexOf('<script type="application/spool+json" data-spool-artifact>',n),s=r<0?-1:e.indexOf("</script>",r+58);if(s<0)return t+e.slice(n);t+=e.slice(n,r),n=s+9}}var qr=200,Jo=/^[1-9]\d{0,14}$/,Ko=/^[+-]?(\d+\.?\d*|\.\d+)(e[+-]?\d+)?$/i,Xo=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/;class gt extends Error{}var ie=(e,t)=>Object.hasOwn(e,t)?e[t]??null:null,Yo=(e)=>typeof e==="object"&&e!==null&&!Array.isArray(e),F=(e)=>typeof e==="number"?1:typeof e==="string"?2:0,mt=(e)=>e.replace(/[A-Z]+/g,(t)=>t.toLowerCase());function Lr(e){if(e===null||e===void 0)return!0;if(typeof e==="number")return Number.isFinite(e);if(typeof e==="string")return!Xo.test(e)&&!e.includes("\x00");return!1}function Qe(e,t){let n=Math.min(e.length,t.length);for(let r=0;r<n;r++){let s=e.charCodeAt(r),o=t.charCodeAt(r);if(s===o)continue;let i=s>=55296&&s<=57343,a=o>=55296&&o<=57343;if(i!==a)return i?1:-1;return s-o}return e.length-t.length}function me(e,t){let n=F(e),r=F(t);if(n!==r)return n-r;if(n===0)return 0;if(n===1)return e<t?-1:e>t?1:0;return Qe(e,t)}function Zo(e,t){for(let n=0;n<e.length;n++){let r=me(e[n],t[n]);if(r!==0)return r}return 0}var Fr=(e,t)=>F(e)!==0&&F(e)===F(t)&&e===t,nn=(e)=>e.sort(Qe);function Ge(e,t){let n=0,r=e.length;while(n<r){let s=n+r>>>1;if(t(e[s]))r=s;else n=s+1}return n}class sn{#e;#t;#n=new Map;#r=new Map;#s=new Map;#o=0;#i=0;constructor(e,t){this.#e=e,this.#t=t}get built(){return this.#o}get entries(){return this.#i}clean(e){let t=this.#n.get(e);if(t===void 0)t=this.#e.every((n)=>Lr(ie(this.#t.get(n),e))),this.#n.set(e,t);return t}equal(e,t){let n=this.#a(e),r=t.length===1?n.get(`${F(t[0])}${String(t[0])}`):void 0;if(r)return[...r];let s=new Set;for(let o of t)for(let i of n.get(`${F(o)}${String(o)}`)??[])s.add(i);return nn([...s])}range(e,t,n){let r=this.#c(`r\x00${e}`,e,(l)=>F(l)===0?void 0:l),s=F(n),o=Ge(r,(l)=>F(l[0])>=s),i=Ge(r,(l)=>F(l[0])>s),[a,c]=t==="gte"?[Ge(r,(l)=>me(l[0],n)>=0),i]:[o,Ge(r,(l)=>me(l[0],n)>0)];return nn(r.slice(Math.max(a,o),c).map((l)=>l[1]))}prefix(e,t,n){let r=this.#c(`p\x00${t??""}\x00${e}`,e,(i)=>typeof i==="string"?t==="ascii"?mt(i):i:void 0),s=t==="ascii"?mt(n):n,o=[];for(let i=Ge(r,(a)=>me(a[0],s)>=0);i<r.length;i++){let[a,c]=r[i];if(!a.startsWith(s))break;o.push(c)}return nn(o)}#a(e){let t=this.#r.get(e);if(!t){t=new Map;for(let n of this.#e){let r=ie(this.#t.get(n),e);if(F(r)===0)continue;let s=`${F(r)}${String(r)}`,o=t.get(s);if(o)o.push(n);else t.set(s,[n]);this.#i+=1}this.#r.set(e,t),this.#o+=1}return t}#c(e,t,n){let r=this.#s.get(e);if(!r){r=[];for(let s of this.#e){let o=n(ie(this.#t.get(s),t));if(o!==void 0)r.push([o,s])}r.sort((s,o)=>me(s[0],o[0])||Qe(s[1],o[1])),this.#s.set(e,r),this.#o+=1,this.#i+=r.length}return r}}function Wr(e,t){if(e.index)return e.index.clean(t);return e.keys.every((n)=>Lr(ie(e.rows.get(n),t)))}function yt(e,t){if(e.from.includes(t))return{join:-1,field:t};let n=t.indexOf(".");if(n<0)return;let r=t.slice(0,n),s=t.slice(n+1),o=(e.join??[]).findIndex((i)=>i.as===r);if(o<0||!(e.join?.[o]?.fields??[]).includes(s))return;return{join:o,field:s}}function ht(e,t){if(t.join<0)return ie(e.base,t.field);let n=e.joined[t.join];return n?ie(n,t.field):null}function ei(e,t){if(e.op!=="in"&&t.length!==1)return null;let n=[];for(let r of t)if(e.type==="number"){if(!Ko.test(r))return null;let s=Number(r);if(!Number.isFinite(s))return null;n.push(s)}else{if(r.includes("\x00"))return null;n.push(r)}return n}function ti(e,t){let{cond:n,values:r}=e;if(n.op==="eq"||n.op==="in")return r.some((o)=>Fr(t,o));if(n.op==="gte"||n.op==="lte"){let o=r[0];if(F(t)===0||F(t)!==F(o))return!1;let i=me(t,o);return n.op==="gte"?i>=0:i<=0}if(typeof t!=="string")return!1;let s=r[0];return n.fold==="ascii"?mt(t).startsWith(mt(s)):t.startsWith(s)}function ni(e,t,n){let r=ie(n,e.on[0]);if(e.on[1]===null)return typeof r==="string"&&t.rows.has(r)?[r]:[];if(F(r)===0)return[];let s=e.on[1];if(t.index&&t.keys.length>=qr)return t.index.equal(s,[r]);return t.keys.filter((o)=>Fr(ie(t.rows.get(o),s),r))}function rn(e,t,n,r,s){if(r===e.length){s.push(n);return}let o=e[r],i=t[r],a=ni(o,i,n.base);if(a.length===0){if(o.type==="left")rn(e,t,{...n,keys:[...n.keys,null],joined:[...n.joined,null]},r+1,s);return}for(let c of a){let l=i.rows.get(c);rn(e,t,{base:n.base,keys:[...n.keys,c],joined:[...n.joined,l]},r+1,s)}}function ri(e,t,n){if(t==="count")return n.length;let[r,s]=Object.entries(t)[0],o=yt(e,s),i=n.map((c)=>ht(c,o)).filter((c)=>c!==null);if(r==="count")return i.length;if(r==="min"||r==="max"){if(i.length===0)return null;return i.reduce((c,l)=>{let d=me(l,c);return r==="min"?d<0?l:c:d>0?l:c})}if(i.length===0)return null;let a=0;for(let c of i){if(typeof c!=="number"||!Number.isSafeInteger(c))throw new gt;if(a+=c,!Number.isSafeInteger(a))throw new gt}return r==="sum"?a:a/i.length}function si(e,t){let n=e.from.map((s)=>[s,ie(t.base,s)]),r=(e.join??[]).map((s,o)=>{let i=t.joined[o],a=s.fields.map((c)=>[c,i?ie(i,c):null]);return[s.as,Object.fromEntries(a)]});return Object.fromEntries([...n,...r])}function oi(e,t,n,r){let s=t.by.map((a)=>yt(e,a)),o=new Map;if(t.by.length===0)o.set("[]",{by:[],members:[]});for(let a of n){let c=s.map((p)=>ht(a,p)),l=JSON.stringify(c.map((p)=>p===null?"0":`${F(p)}${String(p)}`)),d=o.get(l)??{by:c,members:[]};d.members.push(a),o.set(l,d)}let i=Object.entries(t.aggregates);return[...o.values()].map(({by:a,members:c})=>{let l=Object.fromEntries([...t.by.map((d,p)=>[d,a[p]??null]),...i.map(([d,p])=>[d,ri(e,p,c)])]);return{row:l,sort:r.map((d)=>l[d]),tie:a}})}function ii(e,t,n){let r=new URLSearchParams(t),s=e.where??[],o=e.join??[];for(let k of new Set(r.keys()))if(k!=="sort"&&k!=="page"&&!s.some((E)=>E.param===k))return null;let i=[];for(let k of s){let E=r.getAll(k.param);if(E.length===0)continue;let M=ei(k,E);if(!M)return null;i.push({cond:k,ref:yt(e,k.field),values:M})}let a=r.getAll("sort");if(a.length>1)return null;let c=[];if(a.length===1){let k=a[0],E=k.startsWith("-"),M=E?k.slice(1):k;if(!(e.sort??[]).includes(M))return null;c.push({name:M,desc:E})}let l=r.getAll("page");if(l.length>1)return null;let d=1;if(l.length===1){if(!Jo.test(l[0]))return null;d=Number(l[0])}let p=n.base,h=[];for(let k of o){let E=n.joined(k.dataset);if(!E)return null;h.push(E)}for(let k of e.from)if(!Wr(p,k))return null;for(let k=0;k<o.length;k++){let E=o[k],M=E.on[1]===null?E.fields:[...E.fields,E.on[1]];for(let he of M)if(!Wr(h[k],he))return null}let y=p.keys,S=i.find((k)=>k.ref.join<0);if(S&&p.index&&p.keys.length>=qr){let{cond:k,ref:E,values:M}=S;y=k.op==="gte"||k.op==="lte"?p.index.range(E.field,k.op,M[0]):k.op==="prefix"?p.index.prefix(E.field,k.fold,M[0]):p.index.equal(E.field,M)}let x=[];for(let k of y){let E=p.rows.get(k);rn(o,h,{base:E,keys:[k],joined:[]},0,x)}let T=x.filter((k)=>i.every((E)=>ti(E,ht(k,E.ref)))),N=e.group,C=c.map((k)=>k.name),q;if(N)q=oi(e,N,T,C);else{if(T.length>e.limit)return null;let k=C.map((E)=>yt(e,E));q=T.map((E)=>({row:si(e,E),sort:k.map((M)=>ht(E,M)),tie:E.keys}))}if(q.length>e.limit)return null;q.sort((k,E)=>{for(let M=0;M<c.length;M++){let he=me(k.sort[M],E.sort[M]);if(he!==0)return c[M]?.desc?-he:he}return Zo(k.tie,E.tie)});let H=q.length,ae=e.pageSize,Ye=Math.max(1,Math.ceil(H/ae));if(d>Ye)return null;return{items:q.slice((d-1)*ae,d*ae).map((k)=>k.row),total:H,page:d,pages:Ye}}function ai(e,t,n){try{return ii(e,t,n)}catch(r){if(r instanceof gt)return null;throw r}}function Hr(e,t,n,r,s){if(!s)return{ok:!1,reason:"plan needs its datasets"};let o=ai(t,r,s);if(!o)return{ok:!1,reason:"query is not one the route declares"};let{items:i,total:a,page:c,pages:l}=o;return{ok:!0,data:{...Yo(n)?n:{},[e]:i,query:{total:a,page:c,pages:l}}}}var Vr={public:{maxStale:900,mode:"soft"},principal:{maxStale:300,mode:"hard"}};function ne(e,t){for(let n of e){let r=ut(n.pattern,t);if(r)return{route:n,params:r}}return null}var Ur=1,zr=256;function Q(e){throw new D("bad-manifest",e)}function on(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function ci(e,t){let n=`routes[${t}]`;if(!on(e))return Q(`${n} must be an object`);let{pattern:r,strategy:s,version:o,freshness:i,offline:a,sync:c}=e;if(typeof r!=="string")return Q(`${n}.pattern must be a string`);try{ct(r)}catch(d){return Q(`${n}: ${d instanceof Error?d.message:"bad pattern"}`)}if(s!=="static")return Q(`${r}: strategy must be "static"`);if(typeof o!=="string"||o===""||o.length>zr)return Q(`${r}: version must be a string of 1 to ${zr} characters`);let l={pattern:r,strategy:s,version:o};if(i!==void 0){if(!on(i))return Q(`${r}: freshness must be an object`);let{maxStale:d,mode:p}=i;if(d!==void 0){if(typeof d!=="number"||!Number.isFinite(d)||d<=0)return Q(`${r}: freshness.maxStale must be a positive number of seconds`)}if(p!==void 0&&p!=="hard"&&p!=="soft")return Q(`${r}: freshness.mode must be "hard" or "soft"`);l.freshness={...d===void 0?{}:{maxStale:d},...p===void 0?{}:{mode:p}}}if(a!==void 0){if(a!=="serve"&&a!=="refuse")return Q(`${r}: offline must be "serve" or "refuse"`);l.offline=a}if(c!==void 0){if(c!=="background"&&c!=="deferred")return Q(`${r}: sync must be "background" or "deferred"`);l.sync=c}return l}function an(e){if(!on(e))return Q("manifest must be an object");if(e.schema!==Ur)return Q("unsupported manifest schema");let{routes:t}=e;if(!Array.isArray(t))return Q("routes must be a list");let n=t.map(ci),r=new Set;for(let s of n){if(r.has(s.pattern))return Q(`${s.pattern}: declared twice`);r.add(s.pattern)}return{schema:Ur,routes:n}}function cn(e){return e.routes.map((t)=>({pattern:t.pattern,strategy:"static",scope:"public",freshness:{...Vr.public,...t.freshness},persist:!0,offline:t.offline??"serve",sync:t.sync??"background",version:t.version}))}var Je="spool:artifact:",un=64,Gr=256;function ln(e){return`${Je}${e}`}function ye(e){throw new D("bad-sync",e)}function dn(e){return Object.entries(e).map(([t,n])=>`${encodeURIComponent(t)}@${n}`).join(",")}function Qr(e){if(typeof e!=="object"||e===null)return ye("sync response must be an object");let t=e;if(t.protocol!==j)return ye("unsupported protocol version");let{cursor:n,changed:r,dropped:s,reset:o,partial:i}=t;if(typeof n!=="number"||!Number.isSafeInteger(n)||n<0)return ye("cursor must be a non-negative integer");if(typeof r!=="object"||r===null||Array.isArray(r))return ye("changed must be an object");for(let c of Object.values(r))if(typeof c!=="number"||!Number.isSafeInteger(c))return ye("changed versions must be integers");if(!Array.isArray(s)||s.some((c)=>typeof c!=="string"))return ye("dropped must be a list of strings");if(typeof o!=="boolean")return ye("reset must be a boolean");if(i!==void 0&&typeof i!=="boolean")return ye("partial must be a boolean");let a={protocol:j,cursor:n,changed:r,dropped:s,reset:o};if(i)a.partial=!0;return a}var fn={cold:"network",principal:"network",fresh:"local",catalogue:"local","soft-deferred":"local","soft-sync":"local-revalidate","hard-sync":"local-revalidate","offline-stale":"local-revalidate",invalidated:"fallback","stale-after-sync":"fallback","hard-refused":"fallback",refused:"fallback"};var Jr="external",pn="/.spool/view",Kr="/.spool/loads";function Xr(e,t,n,r){return{path:"/.spool/loads",body:JSON.stringify(r&&Object.keys(r).length>0?{view:e,count:t,origins:r}:{view:e,count:t}),contentType:"application/json",at:n}}function Yr(e,t){return{path:"/.spool/view",body:JSON.stringify(e),contentType:"application/json",at:t}}function Zr(e){if(/\b(?:CriOS|FxiOS|EdgiOS|OPiOS)\//.test(e))return"webkit";if(/\bFirefox\//.test(e))return"firefox";if(/\b(?:Chrome|Chromium)\//.test(e))return"chromium";if(/\bSafari\//.test(e))return"webkit";return"other"}var es=86400000,ui=3600000,li=20,di=3600000,fi=86400000,pi=256,ts=100,rs=3000,ns="same-origin";function gi(e,t){let n,r=new Promise((s,o)=>{n=setTimeout(()=>o(Error("timed out")),t)});return Promise.race([e,r]).finally(()=>clearTimeout(n))}var mi=new TextEncoder,wt=(e)=>e.path.startsWith(jr)||e.deliver==="sink";class gn{#e;#t=null;#n;dropped=new Map;constructor(e){this.#e=e}async record(e){await this.#e.storage.addBeacon(e)}async enqueue(e,t){let n=e.method==="GET",r=n?"":e.headers.get("content-type")??"text/plain";if(/octet-stream|multipart|image\//i.test(r))return!1;let s=n?"":await e.clone().text();if(mi.encode(s).length>Cr)return!1;let o=new URL(e.url),i=this.#e.now(),a={path:o.pathname,body:s,contentType:r,at:i};if(o.search!=="")a.search=o.search;if(n)a.method="GET";if(t){if(a.origin=o.origin,a.vendor=t.vendor,a.until=i+t.maxAgeMs,t.delivery==="sink")a.deliver="sink"}return await this.#e.storage.addBeacon(a),!0}flush(){return this.#t??=this.#a().finally(()=>{this.#t=null}),this.#t}async flushAtMoment(){await this.#o();let e=await this.#e.storage.readBeacons();if(e.length===0)return!1;let t=(c)=>c===pn||c===Kr||c===Zt,n=e.some((c)=>!t(c.event.path)),r=e.filter((c)=>c.event.path===pn).length,s=(await this.#e.want?.()??[]).length>0,o=await this.#c(this.#e.catalogue?.())!==void 0,i=Math.min(...e.map((c)=>c.event.at)),a=this.#e.now()-i>=di;if(n||s||o||a||r>=li)return this.flush();return!1}async flushIfDue(){let e=this.#e.now(),t=await this.#r(),n=t.checkedAt>e?-1/0:t.checkedAt;if(e-n<ui)return!1;t.checkedAt=e,await this.#s(t),await this.#o();let r=await this.#e.storage.readBeacons(),s=Math.min(...r.map((i)=>i.event.at));if(r.length===0||e-s<es)return!1;let o=t.lastStandalone>e?-1/0:t.lastStandalone;if(e-o<es)return!1;return t.lastStandalone=e,await this.#s(t),this.flush()}async#r(){return this.#n??=await this.#e.storage.getFlush()??{lastStandalone:-1/0,checkedAt:-1/0},this.#n}async#s(e){await this.#e.storage.setFlush(e)}async#o(){let{storage:e,now:t}=this.#e,n=t(),s=(await e.readBeacons()).filter((o)=>o.event.until!==void 0&&o.event.until<n);if(s.length===0)return;await e.removeBeacons(s.map((o)=>o.key)),await this.#i(s.map(({event:o})=>o.vendor??"unknown"))}async#i(e){let t=new Map;for(let n of e)t.set(n,(t.get(n)??0)+1);for(let[n,r]of t)this.dropped.set(n,(this.dropped.get(n)??0)+r),await this.#e.storage.addBeacon({path:Zt,body:JSON.stringify({vendor:n,count:r}),contentType:"application/json",at:this.#e.now()})}async sendSameOrigin(e){if(this.#t)await this.#t.catch(()=>!1);let{storage:t,replay:n}=this.#e,r=(await t.readBeacons()).filter(({event:i})=>!wt(i)&&i.origin===void 0);if(r.length===0)return;await t.removeBeacons(r.map((i)=>i.key));let s=!1,o=[];for(let{event:i}of r){let a=!1;if(!s)try{a=await gi(n(i),e)}catch{s=!0}if(!a)o.push(ns)}await this.#i(o)}async dropSameOrigin(){if(this.#t)await this.#t.catch(()=>!1);let e=(await this.#e.storage.readBeacons()).filter(({event:t})=>!wt(t)&&t.origin===void 0);if(e.length===0)return;await this.#e.storage.removeBeacons(e.map((t)=>t.key)),await this.#i(e.map(()=>ns))}async#a(){let{storage:e,send:t,replay:n,want:r,catalogue:s}=this.#e;await this.#o();let o=await e.readBeacons();if(o.length===0)return!1;let i=!0;for(let p of o.filter((h)=>!wt(h.event))){let h;try{h=await n(p.event)}catch{h=!1}if(h)await e.removeBeacons([p.key]);else i=!1}let a=o.filter((p)=>wt(p.event)),c=await r?.()??[],l=await this.#c(s?.());if(a.length===0&&c.length===0)return i;let d=!0;for(let p=0;p<Math.max(a.length,1);p+=ts){let h=a.slice(p,p+ts),y={protocol:j,events:h.map(({event:{until:S,...x}})=>x)};if(c.length>0)y.want=c;if(l)y.catalogue=l;c=[],l=void 0;try{d=await t(y)}catch{d=!1}if(!d)return!1;if(await e.removeBeacons(h.map((S)=>S.key)),y.catalogue)await this.#u(y.catalogue.path)}return i&&d}async#c(e){if(!e)return;let t=(await this.#r()).catalogue?.[e.path],n=this.#e.now();return t===void 0||t>n||n-t>=fi?e:void 0}async#u(e){let t=await this.#r(),n={...t.catalogue};delete n[e],n[e]=this.#e.now();let r=Object.keys(n);for(let s of r.slice(0,r.length-pi))delete n[s];t.catalogue=n,await this.#s(t)}}function yi(e){try{return new URL(e).origin}catch{return null}}var hi=Uint8Array.from(atob("R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"),(e)=>e.charCodeAt(0));function ss(e){let t=new Headers;if(e.mode==="cors"){let n=e.headers.get("origin")??yi(e.referrer);if(e.credentials==="include"&&n)t.set("access-control-allow-origin",n),t.set("access-control-allow-credentials","true");else t.set("access-control-allow-origin","*")}if(e.method==="GET")return t.set("content-type","image/gif"),t.set("cache-control","no-store"),new Response(hi,{status:200,headers:t});return new Response(null,{status:204,headers:t})}function K(e){throw new D("bad-dataset",e)}function is(e){let t=new URLSearchParams({name:e.name});if(e.since!==void 0)t.set("since",String(e.since));if(e.schema!==void 0)t.set("schema",e.schema);if(e.after!==void 0)t.set("after",e.after);if(e.limit!==void 0)t.set("limit",String(e.limit));return t.toString()}var bt=(e)=>typeof e==="object"&&e!==null&&!Array.isArray(e),os=(e)=>typeof e==="number"&&Number.isSafeInteger(e)&&e>=0;function as(e){if(!bt(e))return K("dataset response must be an object");if(e.protocol!==j)return K("unsupported protocol version");let{name:t,schema:n,cursor:r,reset:s,puts:o,deletes:i,after:a,next:c,proof:l}=e;if(typeof t!=="string"||typeof n!=="string")return K("name and schema must be strings");if(!os(r))return K("cursor must be a non-negative integer");if(typeof s!=="boolean")return K("reset must be a boolean");if(!Array.isArray(o))return K("puts must be a list");let d=o.map((y)=>{if(!bt(y)||typeof y.key!=="string"||!bt(y.row))return K("a put is { key, row }");return{key:y.key,row:y.row}});if(!Array.isArray(i))return K("deletes must be a list");let p=i.map((y)=>{if(!bt(y)||typeof y.key!=="string"||!os(y.cursor))return K("a delete is { key, cursor }");return{key:y.key,cursor:y.cursor}}),h={protocol:j,name:t,schema:n,cursor:r,reset:s,puts:d,deletes:p};if(a!==void 0){if(typeof a!=="string")return K("after must be a string");h.after=a}if(c!==void 0){if(typeof c!=="string")return K("next must be a string");h.next=c}if(l!==void 0){if(!Lt(l))return K("proof must be a set proof");h.proof={kind:"set",count:l.count,digest:l.digest}}if(h.next===void 0&&h.proof===void 0)return K("a response without next carries a proof");return h}async function cs(e,t,n,r={}){let s=r.hash??Nt,o=t.reset&&t.after===void 0,i=new Map(o?[]:e),a=r.hashes?new Map(o?[]:r.hashes):void 0,c=o?We:n??(await qt(e)).digest,l=async(p)=>{let h=i.get(p);if(h===void 0)return;c=or(c,a?.get(p)??await s(p,h)),i.delete(p),a?.delete(p)};for(let{key:p}of t.deletes)await l(p);for(let{key:p,row:h}of t.puts){await l(p),i.set(p,h);let y=await s(p,h);a?.set(p,y),c=st(c,y)}let d=t.proof;return{rows:i,digest:c,matches:d===void 0?null:d.count===i.size&&d.digest===c,...a?{hashes:a}:{}}}function us(e){return(t)=>{if(t.status===401)return"ended";if(t.status===403)return"revoked";if(t.ok&&t.headers.get(W.partition)!==e)return"partition";return"ok"}}var wi=1000;class z extends Error{reason;by;constructor(e,t){super(e);this.reason=e;this.by=t}}async function ls(e,t){let{store:n,origin:r}=e,s=e.epoch(),o=0,i=async(l)=>{o+=1;let d=await e.fetch(`${r}${Se.dataset}?${is(l)}`,{cache:"no-store",credentials:"same-origin"}),p=e.guard?.(d)??"ok";if(p!=="ok")throw new z(p);if(d.status===409)throw new z("declined",d.headers.get(W.provisionReason));if(d.status===400||d.status===404)throw new z("unavailable");if(!d.ok)throw TypeError(`dataset answered ${d.status}`);let h=as(await d.json());if(h.name!==t)throw new z("bad-response");return h},a=async(l,d,p)=>{try{if(e.epoch()!==s)throw new z("epoch");if(!await n.commit(l,d,s))throw new z("epoch")}catch(h){if(h instanceof z)throw h;throw new z("storage")}return{name:t,requests:o,status:p,cursor:d.cursor,rows:l.rows.size}},c=async(l,d,p)=>{let h=l??await i({name:t}),{cursor:y,schema:S}=h,x=await e.budget(),T=n.stage(t),N,C;for(let H=1;;H+=1){if(e.epoch()!==s)throw new z("epoch");if(N=await T.add(h),x!==void 0&&T.bytes>x)throw new z("budget");if(h.next===void 0)break;if(H>=wi||C!==void 0&&h.next<=C)throw new z("bad-response");C=h.next,h=await i({name:t,after:C})}if(N===!0)return a(T,{cursor:y,schema:S},d);let q=await i({name:t,since:y,schema:S});if(!q.reset&&await T.add(q)===!0)return a(T,{cursor:q.cursor,schema:S},d);if(p)return c(void 0,"reseeded",!1);throw new z("proof")};try{let l=await n.get(t);if(!l)return await c(void 0,"seeded",!0);let{cursor:d,schema:p,digest:h,count:y}=l.meta,S=await i({name:t,since:d,schema:p});if(S.reset)return await c(S,"reseeded",!0);if(S.cursor<d)return{name:t,requests:o,status:"current",cursor:d,rows:y};let x=S.proof;if(S.cursor===d){if(x&&(x.count!==y||x.digest!==h))return await n.drop(t),await c(void 0,"reseeded",!1);if(!await n.touch(t,s))throw new z("epoch");return{name:t,requests:o,status:"current",cursor:d,rows:y}}let T=n.stage(t,l);if(await T.add(S)===!0)return await a(T,{cursor:S.cursor,schema:p},"patched");return await n.drop(t),await c(void 0,"reseeded",!1)}catch(l){if(l instanceof z){if(l.reason==="revoked"&&e.epoch()===s)await n.drop(t).catch(()=>{return});return{name:t,requests:o,status:"refused",reason:l.reason,by:l.by}}if(l instanceof D)return{name:t,requests:o,status:"refused",reason:"bad-response"};return{name:t,requests:o,status:"offline"}}}function ds(e,t,n){if((n>=t?(n-t)/1000:1/0)<=e.maxStale)return"serve";return e.mode==="hard"?"sync-first":"serve-then-sync"}function fs(e,t){return Math.max(e,t)}function ps(e,t){return e.deps.every((n)=>t(n)<=e.vector)}var bi=["content-security-policy","content-security-policy-report-only","x-frame-options","x-content-type-options","referrer-policy","permissions-policy","cross-origin-opener-policy","cross-origin-embedder-policy","cross-origin-resource-policy"],gs=128;function ms(e){let t=[];for(let n of bi){let r=e.get(n);if(r!==null)t.push([n,r])}return t}var ve={reuse:0.5,futureViews:2,requestBytes:2000,artifactBytes:20000,avoidedBytes:17054,changesPerDay:1};function hs(e){let{hot:t,...n}=e??{};return{...ve,...n}}function Ri(e,t){return e.bytes+e.requests*t}var Si={bytes:0,requests:0};function Pi(e,t=ve){let n=e.reuse??t.reuse,r=e.futureViews??t.futureViews,s=(o)=>Ri(o,t.requestBytes);return n*r*s(e.avoided)-s(e.provision)-s(e.maintain??Si)}var ys={layout:0,template:0,asset:0,route:1,expansion:2};function ws(e,t=ve){return e.map((n)=>({...n,benefit:Pi(n,t)})).filter((n)=>n.benefit>0).sort((n,r)=>ys[n.kind]-ys[r.kind]||r.benefit-n.benefit||(n.id<r.id?-1:n.id>r.id?1:0))}class mn{#e=new Map;#t(e){let t=this.#e.get(e)??{id:e,bytes:0,requests:0,views:0,catalogueBytes:0,catalogueViews:0};return this.#e.set(e,t),t}spend(e,t,n=!1){let r=this.#t(e);if(r.bytes+=t.bytes,r.requests+=t.requests,n)r.catalogueBytes+=t.bytes}serve(e,t=!1){let n=this.#t(e);if(n.views+=1,t)n.catalogueViews+=1}entries(){return[...this.#e.values()].map((e)=>({...e})).sort((e,t)=>e.id<t.id?-1:1)}totals(){let e=[...this.#e.values()],t=(s)=>e.reduce((o,i)=>o+s(i),0),n=t((s)=>s.views),r=t((s)=>s.bytes);return{bytes:r,requests:t((s)=>s.requests),views:n,bytesPerView:n===0?null:r/n,catalogueBytes:t((s)=>s.catalogueBytes),catalogueViews:t((s)=>s.catalogueViews)}}meanFetchBytes(){let e=[...this.#e.values()].filter((t)=>t.bytes>t.catalogueBytes);return e.length===0?null:e.reduce((t,n)=>t+n.bytes-n.catalogueBytes,0)/e.length}}var vi=/<span data-spool-placeholder="([^"]*)"><\/span>/g,xi=/\{\{spool-slot:([A-Za-z0-9_.-]+)\}\}/g;function bs(e,t,n){let r=[],s=[],o=new Set,i=e.replace(t,(c,l)=>{o.add(l);let d=Object.hasOwn(n,l)?n[l]:void 0;if(d===void 0)return s.push(l),c;return r.push(l),d}),a=Object.keys(n).filter((c)=>!o.has(c));return{html:i,filled:r,unfilled:s,unmatched:a}}function ki(e,t){return bs(e,vi,t)}function Ai(e,t){return bs(e,xi,t)}function Rs(e){let t=(i)=>{let a={};for(let[c,l]of Object.entries(i??{})){if(typeof l!=="string")return null;a[c]=l}return a},n=t(e.fragments),r=t(e.slots);if(!n||!r)return{ok:!1,reason:"unresolved reference"};let s=ki(e.shell,n);if(s.unfilled.length>0)return{ok:!1,reason:`unfilled placeholders: ${s.unfilled.join(", ")}`};let o=Ai(s.html,r);if(o.unfilled.length>0)return{ok:!1,reason:`unfilled slots: ${o.unfilled.join(", ")}`};return{ok:!0,html:o.html}}function Ss(e,t){if(e.includes("data-spool-client"))return e;for(let n of[/<\/head\s*>/i,/<\/body\s*>/i]){let r=e.search(n);if(r>=0)return e.slice(0,r)+t+e.slice(r)}return e+t}var Ei={"&":"&","<":"<",">":">",'"':""","'":"'"};function Ti(e){return e.replace(/[&<>"']/g,(t)=>Ei[t])}function Ps(e,t){if(e===null||typeof e!=="object")return;return Object.hasOwn(e,t)?e[t]:void 0}function yn(e,t){let n=t[t.length-1];if(e.length===0)return n.value;if(e[0]==="@index")return n.index;for(let r=t.length-1;r>=0;r--){let s=t[r];if(Ps(s.value,e[0])===void 0)continue;return e.reduce((o,i)=>Ps(o,i),s.value)}return}function Oi(e){if(Array.isArray(e))return e.length>0;return!(e===void 0||e===null||e===!1||e===""||e===0)}function Di(e){return typeof e==="string"||typeof e==="number"?String(e):""}function hn(e,t,n){let r="";for(let s of e)if(s.t==="text")r+=s.v;else if(s.t==="var"){let o=Di(yn(s.p,t));if(!s.raw)r+=Ti(o);else if(n.has(s.p.join(".")))r+=o;else throw new D("bad-template",`{{{${s.p.join(".")}}}} is not trusted`)}else if(s.t==="if")r+=hn(Oi(yn(s.p,t))?s.then:s.else,t,n);else{let o=yn(s.p,t);if(!Array.isArray(o))continue;o.forEach((i,a)=>{r+=hn(s.body,[...t,{value:i,index:a}],n)})}return r}function vs(e,t){if(e.v!==1)throw new D("bad-template",`unknown template version ${String(e.v)}`);return hn(e.nodes,[{value:t,index:0}],new Set(e.trusted))}var ji=(e)=>typeof e==="object"&&e!==null&&!Array.isArray(e);async function xs(e,t,n,r={},s,o,i){try{let a=n,c=t.query;if(c&&(c.plan!==void 0||o!==void 0||s!==void 0&&s!=="")){if(n.strategy==="assembly"||n.strategy==="static")return{ok:!1,reason:`${n.strategy} artifact cannot answer a query`};let p=n.body.data,h=c.plan?Hr(c.list,c.plan,p,s??"",i):o===void 0?await ar(c,p,s??"",ir(c)):Ft(c,{...ji(p)?p:{},[c.list]:o},s??"");if(!h.ok)return h;a={...n,body:{data:h.data}}}let l=Object.hasOwn(r,t.pattern)?r[t.pattern]:void 0,d;if(l)d=await l(a);else if(a.strategy==="data"&&t.strategy==="data")return{ok:!0,html:JSON.stringify(a.body.data)};else if(a.strategy==="projection"&&t.strategy==="projection")return{ok:!1,reason:`no renderer for ${t.pattern}`};else if(a.strategy==="static"||a.strategy!==t.strategy)return{ok:!1,reason:`artifact is ${a.strategy}, route is ${t.strategy}`};else if(a.strategy==="assembly"){let p=Rs(a.body);if(!p.ok)return p;d=p.html}else if(a.strategy!=="template")return{ok:!1,reason:`${a.strategy} has no built-in render`};else{let p=Object.hasOwn(e.templates,t.pattern)?e.templates[t.pattern]:void 0;if(!p)return{ok:!1,reason:`no template for ${t.pattern}`};d=vs(p,a.body.data)}if(t.strategy==="data")return{ok:!0,html:d};return{ok:!0,html:Ss(d,e.clientTag)}}catch(a){return{ok:!1,reason:a instanceof Error?a.message:"render failed"}}}var Ci=new TextEncoder,wn=(e)=>Ci.encode(JSON.stringify(e)).length;class ks{name;clear;rows;hashes;digest;bytes;#e;#t=new Set;#n=new Set;constructor(e,t,n){this.#e=e,this.name=t,this.clear=n===void 0,this.rows=n?.rows??new Map,this.hashes=n?.hashes??new Map,this.digest=n?.meta.digest??We,this.bytes=n?.meta.bytes??0}async add(e){let t=e.reset&&e.after===void 0;if(t)this.clear=!0,this.bytes=0,this.#t.clear(),this.#n.clear();let n=new Map,r=(i)=>n.has(i)?n.get(i):t?void 0:this.rows.get(i);for(let{key:i}of e.deletes){let a=r(i);if(a!==void 0)this.bytes-=wn(a);n.set(i,void 0)}for(let{key:i,row:a}of e.puts){let c=r(i);if(c!==void 0)this.bytes-=wn(c);this.bytes+=wn(a),n.set(i,a)}let s={hashes:this.hashes,...this.#e.hash?{hash:this.#e.hash}:{}},o=await cs(this.rows,e,this.digest,s);this.rows=o.rows,this.hashes=o.hashes,this.digest=o.digest;for(let{key:i}of e.deletes)this.#n.add(i),this.#t.delete(i);for(let{key:i}of e.puts)this.#t.add(i),this.#n.delete(i);return o.matches}writes(){return{puts:(this.clear?[...this.rows.keys()]:[...this.#t]).map((t)=>({name:this.name,key:t,row:this.rows.get(t),hash:this.hashes.get(t)})),deletes:this.clear?[]:[...this.#n]}}}class bn{#e;#t=new Map;#n=new Map;#r;#s=Promise.resolve();#o=new Map;#i=new Map;evicted=0;constructor(e){this.#e=e}#a(e){let t=this.#s.then(e,e);return this.#s=t.catch(()=>{return}),t}#c(){return this.#r??=this.#e.storage.getDatasets().then((e)=>new Map(e.map((t)=>[t.name,t]))),this.#r}async list(){return[...(await this.#c()).values()].sort((e,t)=>e.name<t.name?-1:1)}get(e){let t=this.#t.get(e);if(!t)t=this.#u(e),this.#t.set(e,t);return t}async#u(e){let t=(await this.#c()).get(e);if(!t)return;let n=await this.#e.storage.readDataset(e),r=We,s=n.length===t.count;try{for(let i of n)r=st(r,i.hash)}catch{s=!1}if(!s||r!==t.digest){this.evicted+=1,await this.drop(e);return}let o={meta:t,rows:new Map(n.map((i)=>[i.key,i.row])),hashes:new Map(n.map((i)=>[i.key,i.hash]))};return this.#n.set(e,o),o}async rows(e){let t=await this.get(e);if(!t)return;let n=this.#o.get(e);if(!n)n=[...t.rows.keys()].sort().map((r)=>t.rows.get(r)),this.#o.set(e,n);return n}async tables(e,t){let n=await this.#f(e);if(!n)return;let r=new Map;for(let s of t){let o=await this.#f(s);if(!o)return;r.set(s,o)}return{base:n,joined:(s)=>r.get(s)}}async#f(e){let t=await this.get(e);if(!t)return;let n=this.#i.get(e);if(!n){let r=[...t.rows.keys()].sort(Qe);n={keys:r,rows:t.rows,index:new sn(r,t.rows)},this.#i.set(e,n)}return n}loaded(e){return this.#n.has(e)}row(e,t){return this.#n.get(e)?.rows.get(t)}stage(e,t){return new ks(this.#e,e,t)}commit(e,t,n){return this.#a(async()=>{if(this.#e.epoch()!==n)return!1;let r=this.#n.get(e.name),s={name:e.name,schema:t.schema,cursor:t.cursor,count:e.rows.size,digest:e.digest,bytes:e.bytes,appliedAt:this.#e.now()},{puts:o,deletes:i}=e.writes();await this.#e.storage.commitDataset({name:e.name,meta:s,clear:e.clear,puts:o,deletes:i});let a={meta:s,rows:e.rows,hashes:e.hashes};return this.#i.delete(e.name),await this.#l(e.name,a),await this.#e.onChange?.(e.name,...Mi(r,a)),!0})}touch(e,t){return this.#a(async()=>{let n=this.#n.get(e);if(!n||this.#e.epoch()!==t)return!1;let r={...n.meta,appliedAt:this.#e.now()};return await this.#e.storage.commitDataset({name:e,meta:r,clear:!1,puts:[],deletes:[]}),await this.#l(e,{...n,meta:r}),!0})}drop(e){return this.#a(async()=>{let t=this.#n.get(e);if(await this.#e.storage.commitDataset({name:e,meta:null,clear:!0,puts:[],deletes:[]}),this.#i.delete(e),await this.#l(e,void 0),t)await this.#e.onChange?.(e,[],[...t.rows.keys()])})}clear(){return this.#a(async()=>{await this.#e.storage.clearDatasets(),this.#t.clear(),this.#n.clear(),this.#o.clear(),this.#i.clear(),this.#r=Promise.resolve(new Map)})}async#l(e,t){let n=await this.#c();if(this.#o.delete(e),t)n.set(e,t.meta),this.#n.set(e,t),this.#t.set(e,Promise.resolve(t));else n.delete(e),this.#n.delete(e),this.#t.delete(e)}}function Mi(e,t){let n=[];for(let[s,o]of t.hashes)if(e?.hashes.get(s)!==o)n.push(s);let r=[...e?.hashes.keys()??[]].filter((s)=>!t.hashes.has(s));return[n,r]}function De(e,t,n){let r=e.get(t)??new Set;r.add(n),e.set(t,r)}function je(e,t,n){let r=e.get(t);if(!r)return;if(r.delete(n),r.size===0)e.delete(t)}class Rt{#e=new Map;#t=new Map;#n=new Map;#r=new Map;#s=new Map;#o=new Map;#i=new Map;#a=new Map;addProjection(e,t,n,r=[]){this.removeProjections([e]),this.#a.set(e,{deps:[...t],children:[...n],rows:[...r]});for(let s of t)De(this.#e,s,e);for(let s of n)De(this.#t,s,e);for(let s of r)De(this.#s,s,e)}removeProjections(e){for(let t of e){let n=this.#a.get(t);if(!n)continue;for(let r of n.deps)je(this.#e,r,t);for(let r of n.children)je(this.#t,r,t);for(let r of n.rows)je(this.#s,r,t);this.#a.delete(t)}}addArtifact(e,t){this.removeArtifacts([e]),this.#i.set(e,t);for(let n of t.records)De(this.#n,n,e);for(let n of t.projections)De(this.#r,n,e);for(let n of t.rows??[])De(this.#o,n,e)}removeArtifacts(e){for(let t of e){let n=this.#i.get(t);if(!n)continue;for(let r of n.records)je(this.#n,r,t);for(let r of n.projections)je(this.#r,r,t);for(let r of n.rows??[])je(this.#o,r,t);this.#i.delete(t)}}clear(){this.#e.clear(),this.#t.clear(),this.#n.clear(),this.#r.clear(),this.#s.clear(),this.#o.clear(),this.#i.clear(),this.#a.clear()}rowsReaching(e){let t=new Set,n=new Set;for(let s of e){for(let o of this.#s.get(s)??[])t.add(o);for(let o of this.#o.get(s)??[])n.add(o)}let r=this.withParents(t);for(let s of this.artifactsUsing([],r))n.add(s);return{projections:r,artifacts:[...n].sort()}}projectionsReading(e){let t=new Set;for(let n of e)for(let r of this.#e.get(n)??[])t.add(r);return[...t].sort()}withParents(e){let t=new Set,n=[...e];for(let r=n.pop();r!==void 0;r=n.pop()){if(t.has(r))continue;t.add(r),n.push(...this.#t.get(r)??[])}return[...t].sort()}artifactsUsing(e,t){let n=new Set;for(let r of e)for(let s of this.#n.get(r)??[])n.add(s);for(let r of t)for(let s of this.#r.get(r)??[])n.add(s);return[...n].sort()}}class Ce{#e;#t=new Map;constructor(e){this.#e=e}async load(){for(let e of await this.#e.all())this.#t.set(e.id,e)}get(e){return this.#t.get(e)}all(){return[...this.#t.values()]}ids(){return[...this.#t.keys()].sort()}async put(e,t){let n=e.filter((r)=>(this.#t.get(r.id)?.version??-1)<r.version);for(let r of n)this.#t.set(r.id,r);if(n.length>0)if(t)await this.#e.put(n);else await this.#e.delete(n.map((r)=>r.id));return n.map((r)=>r.id)}async drop(e){let t=e.filter((n)=>this.#t.delete(n));if(t.length>0)await this.#e.delete(t)}forget(){this.#t.clear()}}function Rn(e){return new Ce({all:()=>e.allProjections(),put:(t)=>e.putProjections(t),delete:(t)=>e.deleteProjections(t)})}function Sn(e){return new Ce({all:()=>e.allRecords(),put:(t)=>e.putRecords(t),delete:(t)=>e.deleteRecords(t)})}function Ke(e){return e.records!==void 0||e.projections!==void 0||St(ge(e.body))}var St=(e)=>e.records.length+e.projections.length+(e.rows?.length??0)>0;function As(e){return ge(e.data).projections}var Es=(e)=>ge(e.data).rows??[];class Pn{records;projections;index=new Rt;#e;#t;constructor(e){this.#e=e,this.records=Sn(e.storage),this.projections=Rn(e.storage)}get loaded(){return this.#t!==void 0}ensure(){let e=this.#t===void 0;return this.#t??=this.#n(),e?this.#t:this.#t.then(()=>[])}async#n(){await Promise.all([this.records.load(),this.projections.load()]);for(let t of this.projections.all())this.index.addProjection(t.id,t.deps,As(t),Es(t));for(let{artifact:t}of await this.#e.artifacts()){let n=ge(t.body);if(St(n))this.index.addArtifact(t.id,n)}let e={};for(let t of this.records.all()){let n=this.#e.tagVersion(t.id);if(n>t.version)e[t.id]=n}for(let t of this.projections.all())for(let n of t.deps){let r=this.#e.tagVersion(n);if(r>t.version)e[n]=r}return(await this.invalidate(e)).artifacts}async put(e,t){await this.records.put(e.records??[],t);let n=await this.projections.put(e.projections??[],t);for(let s of n){let o=this.projections.get(s);this.index.addProjection(s,o.deps,As(o),Es(o))}let r=ge(e.body);if(St(r))this.index.addArtifact(e.id,r)}forgetArtifacts(e){this.index.removeArtifacts(e)}held(e){let t={};for(let n of[...this.records.all(),...this.projections.all()].slice(0,e))t[n.id]=n.version;return t}async invalidate(e){let t=Object.keys(e),n=(a,c)=>(e[a]??0)>c,r=t.filter((a)=>{let c=this.records.get(a);return c!==void 0&&n(a,c.version)}),s=this.index.projectionsReading(t).filter((a)=>{let c=this.projections.get(a);return c!==void 0&&c.deps.some((l)=>n(l,c.version))}),o=this.index.withParents(s).filter((a)=>this.projections.get(a)),i=this.index.artifactsUsing(r,o);return await this.records.drop(r),await this.projections.drop(o),this.index.removeProjections(o),{records:r.sort(),projections:o,artifacts:i}}async rowsChanged(e,t,n){let r=(i)=>`${e}/${i}`,s=this.index.rowsReaching([...t,...n].map(r)),o=this.index.rowsReaching(n.map(r));return await this.projections.drop(o.projections),this.index.removeProjections(o.projections),{touched:s,dropped:{records:[],projections:o.projections,artifacts:o.artifacts}}}async clear(){this.records.forget(),this.projections.forget(),this.index.clear(),await this.#e.storage.clearGraph()}datasetsOf(e){let t=new Set,n=new Set,r=[e.body];for(let s=r.pop();s!==void 0;s=r.pop()){let o=ge(s);for(let i of o.rows??[])t.add(Vt(i)?.dataset??i);for(let i of o.projections){if(n.has(i))continue;n.add(i);let a=this.projections.get(i);if(a)r.push(a.data)}}return[...t]}async materialize(e){if(e.strategy==="static"||!St(ge(e.body)))return{ok:!0,artifact:e};await this.ensure();let t=this.datasetsOf(e);if(t.length>0){await this.#e.loadDatasets?.(t);let a=t.filter((c)=>!this.#e.held?.(c));if(a.length>0)return{ok:!1,reason:`dataset ${a[0]} is not held`,datasets:a}}let n={record:(a)=>this.records.get(a),projection:(a)=>this.projections.get(a),...this.#e.row?{row:this.#e.row}:{}};if(e.strategy!=="assembly"){let a=Ut(e.body.data,n);if(!a.ok)return a;return{ok:!0,artifact:{...e,body:{data:a.value}}}}let r=(a)=>{let c={};for(let[l,d]of Object.entries(a??{})){let p=Ut(d,n);if(!p.ok)return p;if(typeof p.value!=="string")return{ok:!1,reason:`${l} did not resolve to text`};c[l]=p.value}return{ok:!0,value:c}},s=r(e.body.fragments);if(!s.ok)return s;let o=r(e.body.slots);if(!o.ok)return o;let i={shell:e.body.shell};if(e.body.fragments)i.fragments=s.value;if(e.body.slots)i.slots=o.value;return{ok:!0,artifact:{...e,body:i}}}}class Pt{#e;#t;#n;#r=new Map;#s=new Map;#o=null;#i=0;#a=0;#c;#u=new Map;graph;datasets;constructor(e,t,n=Date.now,r){this.#e=e,this.#t=t,this.#n=n,this.datasets=new bn({storage:e,now:n,epoch:()=>this.#a,...r?{hash:r}:{},onChange:(s,o,i)=>this.#f(s,o,i)}),this.graph=new Pn({storage:e,tagVersion:(s)=>this.#s.get(s)??0,artifacts:()=>this.#p(),row:(s,o)=>this.datasets.row(s,o),held:(s)=>this.datasets.loaded(s),loadDatasets:async(s)=>void await Promise.all(s.map((o)=>this.datasets.get(o)))})}async#f(e,t,n){if(!this.graph.loaded)return;let r=await this.graph.rowsChanged(e,t,n);if(r.dropped.artifacts.length>0)await this.drop(r.dropped.artifacts)}async load(){let e=await this.#e.getMeta();if(e&&e.version===this.#t){this.#o=e.cursor,this.#i=e.syncedAt,this.#s=new Map(e.tags),this.#c=e.policy?.site,this.#u=new Map(e.policy?.paths);return}await this.#e.clearArtifacts(),await this.graph.clear(),await this.datasets.clear(),await this.#d()}get cursor(){return this.#o}get syncedAt(){return this.#i}get sitePolicy(){return this.#c}policyOf(e){return this.#u.get(e)}async keepPolicy(e,t){let n=(r)=>JSON.stringify(r)===JSON.stringify(t);if(e===null){if(n(this.#c))return;this.#c=t}else{if(n(this.#u.get(e)))return;if(this.#u.delete(e),this.#u.set(e,t),this.#u.size>gs)this.#u.delete(this.#u.keys().next().value)}await this.#d()}async get(e){return this.#r.get(e)??await this.#e.getArtifact(e)}async ids(){return(await this.#p()).map((e)=>e.artifact.id)}get epoch(){return this.#a}isCurrent(e){return ps(e,(t)=>this.#s.get(t)??0)}validatedAt(e){return Math.max(fs(e.fetchedAt,this.#i),e.validatedAt??0)}async validate(e){let t=await this.get(e);if(!t||!this.isCurrent(t.artifact))return;let n={...t,validatedAt:this.#n()};if(this.#r.has(e))this.#r.set(e,n);else await this.#e.putArtifact(n)}needFor(e,t=!1){if(!t&&!Ke(e))return null;let n=[...new Set([...e.deps,ln(e.id)])];if(n.length>un)return null;return Object.fromEntries(n.map((r)=>[r,e.vector]))}async held(){return await this.#l(),this.graph.held(Gr)}async datasetsOf(e){if(!Ke(e))return[];return await this.#l(),this.graph.datasetsOf(e)}async materialize(e){if(Ke(e))await this.#l();return this.graph.materialize(e)}async#l(){let e=await this.graph.ensure();if(e.length>0)await this.drop(e)}async put(e,t,n=!1){if(!this.isCurrent(e))return!1;if(Ke(e))await this.#l(),await this.graph.put(e,t);let{records:r,projections:s,...o}=e,i={artifact:o,fetchedAt:this.#n(),...n?{catalogue:!0}:{}};if(t)this.#r.delete(e.id),await this.#e.putArtifact(i);else await this.#e.deleteArtifacts([e.id]),this.#r.set(e.id,i);if(this.#o===null)this.#o=e.vector,await this.#d();return!0}async open(e){let t=await this.get(e);if(!t?.catalogue)return;let{catalogue:n,...r}=t;if(this.#r.has(e))this.#r.set(e,r);else await this.#e.putArtifact(r)}async sweep(e){let t={...e};for(let{artifact:n,catalogue:r}of await this.#p()){if(!r)continue;for(let s of[...n.deps,ln(n.id)])t[s]=Math.min(t[s]??1/0,n.vector)}return Object.keys(t).length>un?null:t}async drop(e){for(let t of e)this.#r.delete(t);if(await this.#e.deleteArtifacts(e),this.graph.loaded)this.graph.forgetArtifacts(e)}async wipe(e=null,t=!1){if(this.#a+=1,this.#r.clear(),await this.#e.clearArtifacts(),await this.graph.clear(),!t)await this.datasets.clear();this.#s=new Map,this.#c=void 0,this.#u=new Map,this.#o=e,await this.#d()}async applySync(e){if(e.reset){let n=await this.ids();return await this.wipe(e.cursor,!0),this.#i=this.#n(),await this.#d(),n}let t=await this.#g(e.changed);if(await this.drop(e.dropped),!e.partial)this.#o=Math.max(this.#o??0,e.cursor),this.#i=this.#n();return await this.#d(),[...new Set([...t,...e.dropped])]}async applyEnvelope(e,t,n){let r=[];if(e.clear?.includes(en))r=await this.ids(),await this.wipe(e.vector??this.#o);else if(e.invalidate)r=await this.#g(e.invalidate);if(t!==null&&e.seen===t&&e.vector!==void 0&&!n)this.#o=Math.max(this.#o??0,e.vector),this.#i=this.#n();return await this.#d(),r}async#p(){return[...this.#r.values(),...await this.#e.allArtifacts()]}async#g(e){let t=new Map;for(let[s,o]of Object.entries(e))if(s.startsWith(Je))t.set(s.slice(Je.length),o);else if(o>(this.#s.get(s)??0))this.#s.set(s,o);let n=this.graph.loaded?(await this.graph.invalidate(Object.fromEntries(this.#m(e)))).artifacts:[],r=(await this.#p()).filter(({artifact:s})=>{let o=t.get(s.id);return o!==void 0&&s.vector<o||!this.isCurrent(s)||n.includes(s.id)}).map(({artifact:s})=>s.id);return await this.drop(r),r}#m(e){return Object.entries(e).filter(([t])=>!t.startsWith(Je))}async#d(){await this.#e.setMeta({version:this.#t,cursor:this.#o,tags:[...this.#s],syncedAt:this.#i,policy:{...this.#c?{site:this.#c}:{},paths:[...this.#u]}})}}function Ii(e,t){return e.thirdParty?.allow.includes(t.origin)===!0}function vn(e,t,n){let r=new URL(t.url);if(r.origin!==n){let i=$r(e.collectors,t.url);if(i&&(t.method==="POST"||t.method==="GET"))return{kind:"collector",collector:i};if(t.method==="GET"&&Ii(e,r))return{kind:"thirdparty"};return{kind:"ignore"}}if(e.logout?.some((i)=>ut(i,r.pathname)))return{kind:"logout"};if(t.method==="POST"&&e.beacons.includes(r.pathname))return{kind:"beacon"};if(t.method!=="GET")return{kind:"pass"};let s=ne(e.routes,r.pathname),o=r.search!==""&&!s?.route.query;if(t.mode!=="navigate"){if(s?.route.strategy==="static"&&!t.headers.has("range"))return{kind:"static",route:s.route,path:r.pathname+r.search};if(s?.route.strategy==="data"&&!t.headers.has("range")&&!o)return{kind:"data",route:s.route,path:r.pathname};return{kind:"asset"}}if(!s||s.route.strategy==="data"||o)return{kind:"pass"};return{kind:"navigation",route:s.route,params:s.params,path:r.pathname}}function $i(e,t){let n=(s)=>`${t}${s}`,r=[{condition:{requestMode:"navigate"},source:"fetch-event"}];for(let s of e.beacons)r.push({condition:{urlPattern:n(s),requestMethod:"POST"},source:"fetch-event"});for(let s of e.logout??[])r.push({condition:{urlPattern:n(s)},source:"fetch-event"});for(let s of e.routes)if(s.strategy==="static"||s.strategy==="data")r.push({condition:{urlPattern:n(s.pattern)},source:"fetch-event"});if((e.collectors?.length??0)>0||e.thirdParty)r.push({condition:{not:{urlPattern:n("/*")}},source:"fetch-event"});return r.push({condition:{urlPattern:n("/*")},source:"network"}),r}async function Ts(e,t,n){if(typeof e.addRoutes!=="function")return!1;try{return await e.addRoutes($i(t,n)),!0}catch{return!1}}var Bi=86400,Ni={changesPerDay:ve.changesPerDay,staleBytes:ve.avoidedBytes,syncBytes:ve.requestBytes};class Os{#e;#t;constructor(e){this.#e=1,this.#t=Bi/e}observe(e,t,n){this.#e+=n,this.#t+=e*t}perSecond(){return this.#e/this.#t}}function _i(e){return(1-Math.exp(-e.perSecond*e.tags*Math.max(0,e.ageSec)))*e.policy.staleBytes-e.policy.syncBytes}var Wi=(e)=>e?Object.entries(e).sort().join("|"):"*";class xn{#e;#t=new Map;#n;#r={};#s=0;rate;constructor(e){this.#e=e,this.#n=e.policy??Ni,this.rate=new Os(this.#n.changesPerDay)}sync(e,t){let n=this.#t.get("*");if(n)return n;let r=Wi(e),s=this.#t.get(r);if(s)return s;let o=[...this.#t.values()],i=Promise.allSettled(o).then(()=>this.#o(e,t)).finally(()=>{if(this.#t.get(r)===i)this.#t.delete(r)});return this.#t.set(r,i),i}background(e,t){return this.sync(e,t).then(()=>{return},()=>{return})}defer(e,t){let n=Object.keys(e).length;if(n===0)return!1;if(_i({ageSec:t,perSecond:this.rate.perSecond(),tags:n,policy:this.#n})<=0)return!1;for(let[s,o]of Object.entries(e))this.#r[s]=Math.min(o,this.#r[s]??1/0);return this.#s=Math.max(this.#s,t),!0}get pending(){return Object.keys(this.#r).sort()}drain(){let e=this.#r;if(Object.keys(e).length===0)return Promise.resolve(!0);let t=this.#s;return this.#r={},this.#s=0,this.sync(e,t)}async#o(e,t){let{replica:n,fetchSync:r,onNetwork:s}=this.#e,o=n.cursor;if(o===null&&!e)return!0;try{let i=await r(o??0,e);if(e&&t!==void 0&&!i.reset){let a=Object.keys(e),c=a.filter((l)=>Object.hasOwn(i.changed,l)).length;this.rate.observe(a.length,t,c)}return await n.applySync(i),!0}catch{return!1}finally{s?.()}}}var qi="\x00";function Ds(e,t={}){let n=_r(e).replace(/<!--[\s\S]*?-->/g,"");for(let r of t.ignore??[]){let s=r.flags.includes("g")?r.flags:`${r.flags}g`;n=n.replace(new RegExp(r.source,s),qi)}return n.replace(/\s+/g," ").replace(/>\s+</g,"><").trim()}function js(e,t,n={}){let r=Ds(e,n),s=Ds(t,n);if(r===s)return{equal:!0};let o=0;while(o<r.length&&r[o]===s[o])o++;return{at:o,equal:!1,reason:`diverges at ${o}: ${JSON.stringify(r.slice(o,o+80))} vs ${JSON.stringify(s.slice(o,o+80))}`}}function vt(e,t){return t.mode??e.mode??"serve"}function Cs(e,t,n){if(t.strategy==="static")return!1;if(vt(e,t)==="shadow")return!0;let r=e.shadowSample??0;return r>0&&n()<r}async function Ms(e,t){if(t.status!==200)return!0;return!js(e,await t.text()).equal}var kn="spool-static-",An=4194304,Li=["content-encoding","content-length","transfer-encoding","connection","keep-alive","set-cookie","age","date","vary"];function $s(e){let t=new Headers(e);for(let n of Li)t.delete(n);return t}async function En(e,t){if(Number(e.headers.get("content-length"))>t)return e.body?.cancel().catch(()=>{return}),null;let n=e.body?.getReader();if(!n)return new Uint8Array;let r=[],s=0;for(;;){let{done:a,value:c}=await n.read();if(a)break;if(s+=c.byteLength,s>t)return n.cancel().catch(()=>{return}),null;r.push(c)}let o=new Uint8Array(s),i=0;for(let a of r)o.set(a,i),i+=a.byteLength;return o}function Fi(e){let t=e.getReader(),n=[],r=null,s=()=>{},o=!0,i,a=new ReadableStream({start(d){i=d},cancel(){o=!1}}),c=(d)=>{r=d,s()};return(async()=>{for(;;){let d;try{d=await t.read()}catch(p){if(o)i.error(p);return c({failed:!0,reason:p})}if(d.done){if(o)i.close();return c({failed:!1})}if(n.push(d.value),s(),o)i.enqueue(d.value)}})(),{visitor:new ReadableStream({async pull(d){for(;;){let p=n.shift();if(p)return d.enqueue(p);if(r?.failed)return d.error(r.reason);if(r)return d.close();await new Promise((h)=>s=h)}},cancel:(d)=>t.cancel(d)},{highWaterMark:0}),capture:a}}function Bs(e){if(e.redirected||!e.body)return{visitor:e,copy:e.clone()};let{visitor:t,capture:n}=Fi(e.body),r={status:e.status,statusText:e.statusText,headers:e.headers};return{visitor:new Response(t,r),copy:new Response(n,r)}}var Hi=/^sha(256|384|512)-([A-Za-z0-9+/]+={0,2})$/,Vi=/^(?:W\/)?"/;function Ui(e){let t="";for(let n of e)t+=String.fromCharCode(n);return btoa(t)}var Is=(e)=>e.replace(/^W\//,"");async function Ns(e,t,n){let r=Hi.exec(e);if(r){let s=await crypto.subtle.digest(`SHA-${r[1]}`,t);return Ui(new Uint8Array(s))===r[2]}if(Vi.test(e)){let s=n.get("etag");return s!==null&&Is(s)===Is(e)}return!0}var Xe="spool-third",Me={class:"x-spool-class",fetched:"x-spool-fetched"};var zi=[/[._-][0-9a-f]{8,}(?=[._-]|$)/i,/[@/_-]v?\d+\.\d+\.\d+/,/\/v\d+(?:\/|$)/],Gi=/[?&](?:v|ver|version|hash|h|rev)=[^&]+/i;function _s(e,t,n=[]){if(zi.some((o)=>o.test(e.pathname)))return"immutable";let r=t.get("cache-control")??"";if(/(?:^|,)\s*immutable\b/i.test(r))return"immutable";let s=/max-age=(\d+)/i.exec(r);if(s!==null&&Number(s[1])>=31536000)return"immutable";if(Gi.test(e.search))return"revalidate";for(let o of n)try{if(new RegExp(o).test(e.href))return"revalidate"}catch{continue}return null}var Qi=["template","projection","data"],qs="spool-assets-",Ji=[qs,kn],Ki=31536000,Xi=86400000,xt=new TextEncoder,Ws=(e)=>e.split("?",1)[0];function Yi(e){let t=e.headers.get("cache-control")??"";if(/(?:^|,)\s*immutable\b/i.test(t))return!0;let n=/max-age=(\d+)/i.exec(t);return n!==null&&Number(n[1])>=Ki}function Ls(e){let{config:t,storage:n,origin:r,renderers:s}=e,o=e.partitions,i=e.now??Date.now,a=e.random??Math.random,c=Zr(e.userAgent??(typeof navigator>"u"?"":navigator.userAgent)),l=hs(t.provision),d=new Pt(n,t.version,i),p=new mn,h=new Set,y=new Map,S=new Map,x=new Set,T=new Set,N=null,C=new Map,q=`${qs}${t.version}`,H=`${kn}${t.version}`,ae=(u)=>new Request(`${r}${u}`),Ye=i(),k=t.assets??"cache",E=!1,M=null,he,Tn,Us,_=null,On=Promise.resolve(),zs=t.mode==="shadow",Dn=()=>t.manifest!==void 0&&t.routes.length===0,kt=new Map,ce=(u)=>{let f=kt.get(u);if(!f)f=e.caches.open(u),kt.set(u,f),f.catch(()=>kt.delete(u));return f},X=async()=>{if(await(he??=d.load()),Dn())await(Tn??=vo());if(o)await(Us??=co())},re=(u)=>{let f=u.then(()=>{return},()=>{return});h.add(f),f.then(()=>h.delete(f))},Gs=async(u)=>{let f=()=>[...h].filter((g)=>!u.has(g));while(f().length>0)await Promise.allSettled(f())},jn=(u)=>{let f=On.then(u,u);return On=f.catch(()=>{return}),f};async function Qs(u,f){if(t.manifest)return Un();let g=f?`need=${encodeURIComponent(dn(f))}`:`from=${u}`,m=await e.fetch(`${r}${Se.sync}?${g}`,{cache:"no-store",credentials:"same-origin"});if(!m.ok)throw Error(`sync answered ${m.status}`);return await Ot(pt(m.headers),!0),Qr(await m.json())}let Js={changesPerDay:l.changesPerDay,staleBytes:l.avoidedBytes,syncBytes:l.requestBytes};async function Ks(){let u=[];for(let g of x)if(!await d.get(g))u.push(g);let f=[];for(let g of t.provision?.hot??[]){if(T.has(g)||u.includes(g)||await d.get(g))continue;let m=ne(t.routes,g);if(!m||m.route.scope!=="public"||m.route.strategy==="static")continue;f.push({id:g,kind:"route",provision:{bytes:p.meanFetchBytes()??l.artifactBytes,requests:0},avoided:{bytes:l.avoidedBytes,requests:1}})}return[...u,...ws(f,l).map((g)=>g.id)].slice(0,Mr)}async function Xs(u,f,g){let m=ne(t.routes,u.id);if(!m||u.scope!=="public"||u.strategy!==m.route.strategy)return;if(await d.put(u,m.route.persist))p.spend(u.id,{bytes:f,requests:g})}let Ys=()=>N!==null?{path:N,sweep:!0}:void 0;async function Zs(u,f){if(!Array.isArray(u))return;for(let g of u){let m;try{m=Le(g)}catch{continue}p.spend(m.id,{bytes:xt.encode(JSON.stringify(g)).length,requests:0},!0);let w=ne(t.routes,m.id);if(!w||!Qi.includes(m.strategy))continue;if(m.strategy!==w.route.strategy||m.scope!==w.route.scope)continue;let b=Z;if(m.scope==="principal"){if(b=await we(),!b||b.id!==f)continue}if(await b.replica.get(m.id))continue;await b.replica.put(m,w.route.persist,!0)}}async function eo(u){let f=t.collectors?.find((R)=>R.vendor===u.vendor),g=u.search??"";if(f?.stamp)g=Br(g,f.stamp,u.at,i());let m=u.method??"POST",w={method:m,credentials:u.origin?"omit":"same-origin"};if(m==="POST"){if(w.body=u.body,u.contentType)w.headers={"content-type":u.contentType}}if(u.origin){let R=u.contentType.split(";")[0]?.trim().toLowerCase()??"",v=["","text/plain","application/x-www-form-urlencoded"].includes(R);w.mode=v?"no-cors":"cors"}let b=await e.fetch(`${u.origin??r}${u.path}${g}`,w);return b.type==="opaque"||b.ok||b.status>=400&&b.status<500}let Y=new gn({storage:n,now:i,want:Ks,catalogue:Ys,replay:eo,async send(u){let f=await e.fetch(`${r}${Se.beacon}`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(u),credentials:"same-origin"});if(f.status===200&&(u.want||u.catalogue)){let g=await f.json();if(u.want){let m=Array.isArray(g.artifacts)?g.artifacts:[];for(let w of m){let b=Le(w);await Xs(b,xt.encode(JSON.stringify(w)).length,0)}for(let w of u.want)x.delete(w),T.add(w)}if(u.catalogue)await Zs(g.catalogue,f.headers.get(W.partition))}return f.ok||f.status>=400&&f.status<500}}),Cn=(u)=>new xn({replica:u,fetchSync:Qs,onNetwork:()=>re(Y.flushAtMoment()),policy:Js}),Z={id:null,replica:d,scheduler:Cn(d),deferred:new Set,loaded:Promise.resolve(),dead:!1},ta=Z.scheduler,Ze=new Map,At={},Ie=new Map,Et=new Set,$e=new Set,Mn=!1,In=null,to=async()=>{if(e.estimate)return e.estimate();return(typeof navigator>"u"?void 0:await navigator.storage?.estimate?.())??{}},no=async()=>{try{let{quota:u,usage:f}=await to();if(u===void 0||f===void 0)return;return Math.max(0,(u-f)*(t.datasetShare??1))}catch{return}},ro=(u)=>{let f=u.status==="refused"?`${u.name}:refused:${u.reason}`:`${u.name}:${u.status}`;if(At[f]=(At[f]??0)+1,u.status==="refused"){if(Ie.set(u.name,u.reason),u.reason==="declined")S.set(u.name,u.by??null)}else if(u.status!=="offline")Ie.delete(u.name);if(u.status!=="offline"&&u.status!=="refused"&&!Mn)Mn=!0,e.broadcast?.({type:"spool:persist"})},Tt=()=>new Map((t.principalDatasets??[]).map((u)=>[u.name,u.maxStaleMs]));async function so(u,f,g){let m=await e.fetch(f,g);if(u.dead||_!==u)return m;if(m.status===401)await Ne("session-ended");else if(m.ok)if(m.headers.has(W.partition))await Ot(pt(m.headers),!0);else await Ne("session-ended");return m}function Be(u,f=Z){let g=`${f.id??""}\x00${u}`,m=Ze.get(g);if(m)return m;let w=f.id,b=ls({store:f.replica.datasets,fetch:w===null?(R,v)=>e.fetch(R,v):(R,v)=>so(f,R,v),origin:r,epoch:()=>f.dead?-1:f.replica.epoch,budget:no,...w===null?{}:{guard:us(w)}},u).then((R)=>(ro(R),R)).finally(()=>Ze.delete(g));return Ze.set(g,b),b}let oo=(u)=>u.status!=="offline"&&u.status!=="refused";function $n(u,f=Z){if(f!==Z&&!Tt().has(u))return;let g=`${f.id??""}\x00${u}`;if(!Ie.has(u)&&!Ze.has(g))re(Be(u,f))}let io=(u)=>ne(t.routes,u)?.route.retention??"session",ao=()=>t.routes.some((u)=>u.scope==="principal"&&u.retention==="persistent")?"persistent":"session";function Bn(u){let f=o.open(u,io,ao(),t.principalDatasets!==void 0),g=new Pt(f,t.version,i);return{id:u,replica:g,scheduler:Cn(g),deferred:new Set,loaded:g.load(),dead:!1}}async function co(){let u=await o.current();if(u&&!_)_=Bn(u)}async function we(){await X();let u=_;if(!u)return null;return await u.loaded,u}function Nn(u){u.dead=!0,$e.clear();for(let f of Tt().keys())Ie.delete(f)}function Ne(u){return jn(async()=>{await X();let f=_;if(_=null,f?.writes?.kill(),f)Nn(f);if(!f||!o)return!1;return await o.setCurrent(null),await o.destroy(f.id),e.broadcast?.({type:"spool:cleared",reason:u}),!0})}function uo(u){return jn(async()=>{await X();let f=_;if(f?.id===u)return;if(_=Bn(u),f?.writes?.kill(),f)Nn(f);if(await o.setCurrent(u),f)await o.destroy(f.id),e.broadcast?.({type:"spool:cleared",reason:"partition"})})}async function Ot(u,f,g=!1){if(!o||!u||u.protocol!==j)return;await X();let m=u.clear??[];if(m.includes("*")||_&&m.includes(_.id)){await Y.dropSameOrigin(),await Ne("clear");return}if(g)return;if(u.partition!==void 0){if(_?.id!==u.partition)await Y.dropSameOrigin(),await uo(u.partition)}else if(f&&_)await Y.dropSameOrigin(),await Ne("session-ended")}let _n=()=>t.writes!==void 0&&t.mode!=="shadow",Dt=(u,f)=>({ok:!1,code:u,message:f});async function lo(u){let f=`name=${encodeURIComponent(u.name)}&key=${encodeURIComponent(u.key)}`,g=await e.fetch(`${r}${Se.write}?${f}`,{method:"PUT",headers:{"content-type":"application/json","if-match":vr(u.base),[Rr.id]:u.id},body:JSON.stringify({value:u.value}),cache:"no-store",credentials:"same-origin"}),m=await g.json().catch(()=>{return});return{status:g.status,body:m}}function Wn(u){if(!_n()||!o?.openWrites)return null;return u.writes??=new Re({store:o.openWrites(u.id),classes:()=>t.writes??[],now:i,send:lo,onFlush:(f)=>e.broadcast?.({type:"spool:written",...f})}),u.writes}async function et(){if(!_n())return Dt("writes-off","declared writes are off");let u=await we();if(!u)return Dt("no-partition","no signed-in principal is held");return Wn(u)??Dt("unavailable","this worker has no partition storage")}async function fo(){let u=_?Wn(_):null;if(u)await u.flush()}async function po(u,f,g){let m=f.scope==="principal"?await we():Z;if(!m||f.scope==="principal"&&m.id!==g)return;let w=await m.replica.held(),b=Object.keys(w).length>0?`&have=${encodeURIComponent(dn(w))}`:"",R=await e.fetch(`${r}${Se.artifact}?path=${encodeURIComponent(u)}${b}`,{cache:"no-store",credentials:"same-origin"});if(R.status===204&&R.headers.get(W.provision)==="declined"){S.set(u,R.headers.get(W.provisionReason));return}if(!R.ok){if(f.scope==="principal"&&[401,403,404].includes(R.status))await m.replica.drop([u]);return}let v=await R.text(),P=Le(JSON.parse(v));if(P.scope!==f.scope||P.id!==u)return;if(P.strategy!==f.strategy)return;if(f.scope==="principal"){if(R.headers.get(W.partition)!==g)return;if(_!==m)return}if(await m.replica.put(P,f.persist))p.spend(u,{bytes:xt.encode(v).length,requests:1})}async function qn(u){let f=[...u.deferred];if(u.deferred.clear(),await u.scheduler.drain())for(let g of f)await u.replica.validate(g)}async function go(u,f,g,m,w,b,R){if(await R(),f&&f.protocol===j){await d.applyEnvelope(f,g,u.has("age"));let v=_;if(v)await v.loaded,await v.replica.applyEnvelope(f,null,!0);let P=f.artifact;if(b&&P){let O=ne(t.routes,P.id),L=P.scope==="principal"?await we():Z,V=O&&O.route.strategy!=="static"&&O.route.scope===P.scope&&!S.has(P.id)&&L&&(P.scope==="public"||L.id===f.partition);if(O&&L&&V&&!await L.replica.get(P.id))if(P.scope==="public"&&vt(t,O.route)==="shadow")x.add(P.id);else{let B=`${P.scope}:${P.id}`,ee=y.get(B)??po(P.id,O.route,f.partition);y.set(B,ee);try{await ee}catch{}finally{y.delete(B)}}}}if(w){if(await qn(Z),_)await qn(_);let v=[...Et];Et.clear();for(let L of v)await Be(L);let P=[...$e];$e.clear();let O=_;if(O)for(let L of P)await Be(L,O);await Y.flushAtMoment(),await fo(),await Ao()}}async function mo(u,f,g,m,w){if(u.method!=="GET"||f.status!==200||f.redirected)return;if(w?.signedOut)return;if(m&&!/text\/html/i.test(f.headers.get("content-type")??""))return;let b=ms(f.headers);if(m)await d.keepPolicy(null,b);let R=w?.route,v=new URL(u.url);if(!R||R.strategy==="static"||v.search!=="")return;let P=R.scope==="principal"?_?.id===g?.partition?_:null:Z;if(!P)return;await P.loaded,await P.replica.keepPolicy(v.pathname,b)}async function le(u,f,g){let m=u,w=null;if(!t.manifest&&!f&&u.method==="GET"&&d.cursor!==null)try{let B=new Headers(u.headers);B.set(W.vectorSeen,String(d.cursor)),m=new Request(u,{headers:B}),w=d.cursor}catch{m=u}let b=await e.fetch(m),R=pt(b.headers);await Ot(R,f,g?.signedOut);let v=f||u.method!=="GET",P=g?.clone,O=typeof P==="function"?P(b,R):P,{visitor:L,copy:V}=O?Bs(b):{visitor:b,copy:null};return re((async()=>{try{await g?.run(V,R)}catch{}await go(b.headers,R,w,f,v,g?.provision??f,()=>mo(u,b,R,f,g))})()),L}async function jt(u,f,g,m=""){let w=Z;if(f.scope==="principal"){if(!o)return{reason:"principal",staleSec:null};let A=await we();if(!A)return{reason:"cold",staleSec:null};w=A}let{replica:b,scheduler:R}=w,v=await b.get(u);if(!v)return{reason:"cold",staleSec:null};let P=()=>v?Math.max(0,Math.floor((i()-b.validatedAt(v))/1000)):null;if(!b.isCurrent(v.artifact)){let A=P();return await b.drop([u]),{reason:"invalidated",staleSec:A}}if(f.version!==void 0&&v.artifact.strategy==="static"&&v.artifact.body.version!==f.version){let A=P();return await b.drop([u]),{reason:"invalidated",staleSec:A}}let O=f.query?.dataset,L=(f.query?.plan?.join??[]).map((A)=>A.dataset),V=[...new Set([...O?[O]:[],...L,...await b.datasetsOf(v.artifact)])],B=w===Z?void 0:Tt();if(B&&V.some((A)=>!B.has(A)))return{reason:"refused",staleSec:P()};let ee=async()=>Promise.all(V.map(async(A)=>(await b.datasets.get(A))?.meta.appliedAt)),te=await ee(),xe=V.filter((A,se)=>te[se]===void 0);if(xe.length>0){if(!g)for(let A of xe)$n(A,w);return{reason:"refused",staleSec:P()}}if(B){let A=V.filter((se,It)=>{let er=i()-te[It];return!(er>=0&&er<B.get(se))});if(A.length>0){if(!g)for(let se of A)$e.add(se);return{reason:"refused",staleSec:P()}}}let Jn=(A)=>A.filter((se)=>se!==void 0),To=v.catalogue===!0,Kn=ds(f.freshness,Math.min(b.validatedAt(v),...Jn(te)),i()),U=Math.max(P(),...Jn(te).map((A)=>Math.floor((i()-A)/1000))),Ct=b.needFor(v.artifact,f.sync==="deferred"||f.scope==="principal"),ke=(f.scope==="principal"&&Ct?await b.sweep(Ct):Ct)??void 0,de="fresh";if(Kn==="sync-first"){if(de="hard-sync",!g){let A=await R.sync(ke,U),se=(await Promise.all(V.map((It)=>Be(It,w)))).every(oo);if(!(A&&se)&&f.offline==="refuse")return{reason:"hard-refused",staleSec:U};if(V.length>0){if(te=await ee(),te.includes(void 0))return{reason:"refused",staleSec:U}}if(A){if(ke)await b.validate(u);if(v=await b.get(u),!v||!b.isCurrent(v.artifact))return{reason:"stale-after-sync",staleSec:U}}if(!(A&&se))de="offline-stale"}}else if(Kn==="serve-then-sync"){if(f.sync==="deferred"){if(de="soft-deferred",!g&&ke&&R.defer(ke,U))w.deferred.add(u);if(!g)for(let A of V)(w===Z?Et:$e).add(A)}else if(de="soft-sync",!g){re(R.sync(ke,U).then(async(A)=>{if(A&&ke)await b.validate(u)}));for(let A of V)re(Be(A,w))}}if(f.strategy==="static"){let A=await bo(u);if(!A)return await b.drop([u]),{reason:"refused",staleSec:U};return{reason:de,response:A,staleSec:U}}let Xn=b.policyOf(u)??d.sitePolicy;if(!Xn&&!g)return{reason:"refused",staleSec:U};let tt=await b.materialize(v.artifact);if(!tt.ok){if(tt.datasets){if(!g)for(let A of tt.datasets)$n(A,w);return{reason:"refused",staleSec:U}}return await b.drop([u]),{reason:"refused",staleSec:U}}let nt=f.query?.plan!==void 0,Yn=O===void 0||nt?void 0:await b.datasets.rows(O);if(O!==void 0&&!nt&&!Yn)return{reason:"refused",staleSec:U};let Zn=O!==void 0&&nt?await b.datasets.tables(O,L):void 0;if(O!==void 0&&nt&&!Zn)return{reason:"refused",staleSec:U};let Mt=await xs(t,f,tt.artifact,s,m,Yn,Zn);if(!Mt.ok){if(Mt.reason===Bt)await b.drop([u]);return{reason:"refused",staleSec:U}}if(To){if(await b.open(u),fn[de]==="local")de="catalogue"}return{reason:de,html:Mt.html,headers:Xn,staleSec:U}}function yo(u){let f;try{f=new URL(u)}catch{return}if(f.protocol!=="http:"&&f.protocol!=="https:")return;if(f.origin!==r)return Jr;return ne(t.routes,f.pathname)?.route.pattern}async function ho(u,f,g){let m=Cs(t,f,a),w=i(),b=M===null?null:w-M;M=w,N=f.catalogue?u:null;let R=await jt(u,f,m,new URL(g.url).search),v=yo(g.referrer),P=crypto.randomUUID();if(C.delete(u),C.set(u,P),C.size>64)C.delete(C.keys().next().value);let O=(B)=>({id:P,crossOriginLoads:null,tier:m?"shadow":fn[R.reason],reason:R.reason,staleSec:R.staleSec,engine:c,scope:f.scope,strategy:f.strategy,route:f.pattern,mismatch:B,swAgeMs:w-Ye,gapMs:b,...v?{from:v}:{}}),L=async(B)=>{if(t.views!==!1)await Y.record(Yr(O(B),w))};if(m){let B=R.html;return le(g,!0,{clone:B!==void 0,route:f,run:async(ee)=>{await L(B===void 0||!ee?null:await Ms(B,ee))}})}if(R.response)return p.serve(u),re(L(null)),R.response;if(R.html===void 0){let B=f.strategy==="static",ee=await le(g,!0,{clone:B||((te,xe)=>Vn(u,f,te,xe)),route:f,run:async(te,xe)=>{if(B)await Hn(u,f,te);else await So(u,f,te,xe);await L(null)}});if(f.scope==="principal"&&Ln(ee))await Fn(u);return ee}p.serve(u,R.reason==="catalogue"),re(L(null));let V=new Headers(R.headers);return V.set("content-type","text/html; charset=utf-8"),new Response(R.html,{headers:V})}function Ln(u){return u.status===401||u.status===403||u.type==="opaqueredirect"||u.status>=300&&u.status<400}async function Fn(u){let f=await we();if(f)await f.replica.drop([u])}async function wo(u,f,g){let m=await jt(f,g,!1,new URL(u.url).search);if(m.html!==void 0){p.serve(f,m.reason==="catalogue");let b=new Headers(m.headers);return b.set("content-type",g.type??"application/json"),new Response(m.html,{headers:b})}let w=await le(u,!1,{provision:!0,route:g,run:async()=>{return}});if(g.scope==="principal"&&Ln(w))await Fn(f);return w}async function bo(u){return(await ce(H)).match(ae(u))}async function Hn(u,f,g){if(!g||g.status!==200||g.redirected){g?.body?.cancel().catch(()=>{return});return}let m=t.manifest?ne(t.routes,Ws(u))?.route:f;if(m?.strategy!=="static")return;let w=await En(g,An);if(!w)return;let b=g.headers.get("content-type")??"application/octet-stream",R;if(t.manifest){let P=m.version;if(P===void 0||!await Ns(P,w,g.headers))return;R={protocol:j,id:u,scope:"public",strategy:"static",deps:[],vector:0,body:{type:b,bytes:w.byteLength,version:P}}}else{let P;try{P=tn(g.headers)}catch{return}let O=P.artifact;if(P.protocol!==j||!O)return;if(O.id!==u||O.scope!=="public")return;R={protocol:j,id:u,scope:"public",strategy:"static",deps:O.deps,vector:O.version,body:{type:b,bytes:w.byteLength}}}if(await(await ce(H)).put(ae(u),new Response(w,{headers:$s(g.headers)})),await d.put(R,!0))p.spend(u,{bytes:w.byteLength,requests:0})}function Vn(u,f,g,m){let w=m?.artifact;return(f.strategy==="assembly"||f.strategy==="template")&&f.scope==="public"&&m?.protocol===j&&w?.hash!==void 0&&w.id===u&&w.scope==="public"&&vt(t,f)!=="shadow"&&!S.has(u)&&g.status===200&&!g.redirected&&/text\/html/i.test(g.headers.get("content-type")??"")}async function Ro(u,f,g,m){if(f.strategy==="template"){let R=Nr(g);if(R===null||await Ae(R)!==m.hash)return null;let v=Le(JSON.parse(R));if(v.id!==u||v.scope!=="public")return null;if(v.strategy!=="template")return null;return{artifact:v,bytes:xt.encode(R).length}}let w=g.indexOf(t.clientTag),b=w<0?[g]:[g.slice(0,w)+g.slice(w+t.clientTag.length),g];for(let R of b){if(await Ae(R)!==m.hash)continue;return{artifact:{protocol:j,id:u,scope:"public",strategy:"assembly",deps:[...new Set(m.deps)],vector:m.version,body:{shell:R}},bytes:0}}return null}async function So(u,f,g,m){let w=m?.artifact;if(!g||!w?.hash||!Vn(u,f,g,m))return;let b=d.epoch;try{let R=await En(g,An);if(!R)return;let v=new TextDecoder("utf-8",{fatal:!0}).decode(R),P=await Ro(u,f,v,{...w,hash:w.hash});if(!P||await d.get(u)||d.epoch!==b)return;if(await d.put(P.artifact,f.persist))p.spend(u,{bytes:P.bytes,requests:0})}catch{}}async function Po(u,f,g){let m=await jt(f,g,!1);if(m.response)return p.serve(f),m.response;return le(u,!1,{clone:!0,run:(w)=>Hn(f,g,w)})}async function vo(){try{let f=await(await ce(H)).match(new Request(t.manifest));if(f){t.routes=cn(an(JSON.parse(await f.text())));return}await Un()}catch{Tn=void 0}}async function Un(){let u=t.manifest,f=await e.fetch(u,{cache:"no-store",credentials:"same-origin"});if(!f.ok)throw Error(`manifest answered ${f.status}`);let g=await f.text(),m=cn(an(JSON.parse(g)));t.routes=m,await(await ce(H)).put(new Request(u),new Response(g,{headers:{"content-type":"application/json"}}));let b=[];for(let R of await d.ids()){let v=await d.get(R);if(v?.artifact.strategy!=="static")continue;let P=ne(m,Ws(R));if(!P||v.artifact.body.version!==P.route.version)b.push(R)}return{protocol:j,cursor:d.cursor??0,changed:{},dropped:b,reset:!1}}async function zn(u){let f=await ce(q),g=!u.headers.has("range");if(g){let w=await f.match(u);if(w)return w}await X();let m=await le(u,!1);if(g&&m.status===200&&Yi(m))re(f.put(u,m.clone()));return m}async function xo(u,f){if(await X(),!await Y.enqueue(u,f))return e.fetch(u);return ss(u)}let _e=t.thirdParty,Gn=(u)=>new Request(u.url);async function ko(u){let g=await(await ce(Xe)).match(Gn(u));if(g)return g;let m=await e.fetch(u);if(m.status===200&&(m.type!=="opaque"||_e?.allowOpaque)){let w=m.type==="opaque"?"immutable":_s(new URL(u.url),m.headers,_e?.versioned);if(w)re(Qn(u,m.clone(),w))}return m}async function Qn(u,f,g){let m=await ce(Xe),w=f;if(f.type!=="opaque"){let P=new Headers(f.headers);P.set(Me.class,g),P.set(Me.fetched,String(i())),w=new Response(await f.arrayBuffer(),{status:200,headers:P})}await m.put(Gn(u),w);let b=await m.keys(),R=_e?.maxEntries??64;if(b.length<=R)return;let v=[];for(let P of b){let O=await m.match(P);v.push({key:P,at:Number(O?.headers.get(Me.fetched)??0)})}v.sort((P,O)=>P.at-O.at);for(let{key:P}of v.slice(0,b.length-R))await m.delete(P)}async function Ao(){if(!_e)return;let u=await ce(Xe),f=_e.revalidateAfterMs??Xi;for(let g of await u.keys()){let m=await u.match(g);if(!m||m.headers.get(Me.class)!=="revalidate")continue;let w=Number(m.headers.get(Me.fetched)??0);if(i()-w<f)continue;try{let b=await e.fetch(new Request(g.url,{cache:"no-cache",mode:"cors",credentials:"omit"}));if(b.status===200&&b.type!=="opaque")await Qn(g,b,"revalidate")}catch{}}}async function Eo(u){await X();let f=vn(t,u,r);if(re(Y.flushIfDue()),f.kind==="logout")return await Y.sendSameOrigin(rs).catch(()=>{return}),await Ne("logout"),le(u,u.mode==="navigate",{signedOut:!0,run:async()=>{return}});if(f.kind==="collector")return xo(u,f.collector);if(f.kind==="thirdparty")return ko(u);if(f.kind==="beacon"){if(await Y.enqueue(u))return new Response(null,{status:204});return le(u,!1)}if(f.kind==="navigation")return ho(f.path,f.route,u);if(f.kind==="static")return Po(u,f.path,f.route);if(f.kind==="data")return wo(u,f.path,f.route);if(f.kind==="asset")return zn(u);return le(u,u.mode==="navigate")}return{replica:d,ledger:p,handle(u,f){let g=vn(t,u,r).kind;if(g==="ignore")return;if(g==="asset"&&k!=="cache")return;if(zs&&g!=="navigation"&&g!=="static"&&u.mode!=="navigate")return;let m=new Set(h);return(g==="asset"&&!Dn()?zn(u):Eo(u)).catch(()=>e.fetch(u)).finally(()=>f(Gs(m)))},async install(u){if(k==="static-routing")E=await Ts(u,t,r)},async activate(){await X();for(let u of await e.caches.keys())if(Ji.some((g)=>u.startsWith(g))&&u!==q&&u!==H)await e.caches.delete(u)},async message(u){let f=u??{};if(f.type==="spool:hello")return{type:"spool:hello",protocol:j,version:t.version,compatible:f.protocol===j};if(f.type==="spool:status")return await X(),{type:"spool:status",cursor:d.cursor,syncedAt:d.syncedAt,artifacts:await d.ids(),beacons:(await n.readBeacons()).length};if(f.type==="spool:view"){let g=f.path;return{type:"spool:view",id:typeof g==="string"&&C.get(g)||null}}if(f.type==="spool:loads"){let{view:g,count:m,origins:w}=f;if(typeof g==="string"&&typeof m==="number"&&t.views!==!1){await X();let b=typeof w==="object"&&w!==null&&!Array.isArray(w)?w:void 0;await Y.record(Xr(g,m,i(),b))}return}if(f.type==="spool:graph")return await X(),await d.held(),{type:"spool:graph",records:d.graph.records.ids(),projections:d.graph.projections.ids()};if(f.type==="spool:ledger")return{type:"spool:ledger",entries:p.entries(),totals:p.totals()};if(f.type==="spool:partition"){let g=await we();if(!g)return{type:"spool:partition",partition:null,artifacts:[],records:[],projections:[],datasets:[]};return await g.replica.held(),{type:"spool:partition",partition:g.id,artifacts:await g.replica.ids(),records:g.replica.graph.records.ids(),projections:g.replica.graph.projections.ids(),datasets:await g.replica.datasets.list()}}if(f.type==="spool:assets")return{type:"spool:assets",mode:k,routed:E};if(f.type==="spool:datasets")return await X(),{type:"spool:datasets",datasets:await d.datasets.list(),outcomes:{...At},refused:Object.fromEntries(Ie),declined:Object.fromEntries(S),evicted:d.datasets.evicted,persisted:In};if(f.type==="spool:persisted"){In=f.granted===!0;return}if(f.type==="spool:write"){let{name:g,key:m,value:w,version:b}=f,R=await et();return{type:"spool:write",result:R instanceof Re?await R.write(typeof g==="string"?g:"",typeof m==="string"?m:"",w,b):R}}if(f.type==="spool:flush"){let g=await et();return{type:"spool:flush",result:g instanceof Re?{ok:!0,...await g.flush()}:g}}if(f.type==="spool:writes"){let g=await et();return{type:"spool:writes",result:g instanceof Re?{ok:!0,writes:await g.list()}:g}}if(f.type==="spool:resolve"){let{name:g,key:m,use:w}=f,b=await et();return{type:"spool:resolve",result:b instanceof Re?await b.resolve(typeof g==="string"?g:"",typeof m==="string"?m:"",w):b}}if(f.type==="spool:held"){let g=await ce(Xe);return{type:"spool:held",dropped:Object.fromEntries(Y.dropped),third:(await g.keys()).map((m)=>m.url).sort()}}return}}}var Zi="static-1",ea="spool.json";function Fs(e){return{protocol:j,version:Zi,routes:[],templates:{},beacons:[],clientTag:"",views:!1,manifest:new URL(ea,e).href}}function Hs(e,t){let n=self,r=Ls({config:e,storage:it(),fetch:(s,o)=>fetch(s,o),caches,origin:n.location.origin,renderers:t,partitions:typeof indexedDB>"u"?void 0:Dr(),broadcast:(s)=>void n.clients.matchAll({type:"window",includeUncontrolled:!0}).then((o)=>o.forEach((i)=>i.postMessage(s)))});n.addEventListener("install",(s)=>s.waitUntil(Promise.all([n.skipWaiting(),r.install(s)]))),n.addEventListener("activate",(s)=>s.waitUntil(Promise.all([r.activate(),n.clients.claim()]))),n.addEventListener("fetch",(s)=>{let o=r.handle(s.request,(i)=>s.waitUntil(i));if(o)s.respondWith(o)}),n.addEventListener("message",(s)=>{s.waitUntil(r.message(s.data).then((o)=>{if(!o)return;let i=s.ports[0];if(i)i.postMessage(o);else s.source?.postMessage(o)}))})}var Vs=self;Hs(Vs.__SPOOL_CONFIG__??Fs(Vs.location.href));})();
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/** what a site gives spool for one loop of its own */
|
|
2
|
+
export type ActivityControls = {
|
|
3
|
+
/** stops the loop; called while the target is off screen or the page is hidden */
|
|
4
|
+
pause(): void;
|
|
5
|
+
/** restarts the loop once neither condition holds */
|
|
6
|
+
resume(): void;
|
|
7
|
+
};
|
|
8
|
+
export type ActivityOptions = {
|
|
9
|
+
/** the element the loop draws; the loop pauses while none of it is on screen */
|
|
10
|
+
target?: Element;
|
|
11
|
+
/** how long the page may stay hidden before the loop pauses; default 10000 ms, 0 pauses at once */
|
|
12
|
+
hiddenAfterMs?: number;
|
|
13
|
+
};
|
|
14
|
+
/** everything the hook needs from the page, injected so node can drive it */
|
|
15
|
+
export type ActivityHost = {
|
|
16
|
+
/** whether the page is hidden now */
|
|
17
|
+
hidden(): boolean;
|
|
18
|
+
/** calls listener on each visibility change; returns the function that stops it */
|
|
19
|
+
onVisibilityChange(listener: () => void): () => void;
|
|
20
|
+
/** calls listener with whether the target is on screen; returns the function that stops it */
|
|
21
|
+
observe(target: Element, listener: (onScreen: boolean) => void): () => void;
|
|
22
|
+
/** runs callback after ms milliseconds; returns a handle for clearTimeout */
|
|
23
|
+
setTimeout(callback: () => void, ms: number): unknown;
|
|
24
|
+
/** cancels a timer from setTimeout */
|
|
25
|
+
clearTimeout(handle: unknown): void;
|
|
26
|
+
};
|
|
27
|
+
/**
|
|
28
|
+
* Lets a site say which of its own loops spool may pause: a loop pauses while its target is off
|
|
29
|
+
* screen, and while the page has been hidden for `hiddenAfterMs`. The hook never touches
|
|
30
|
+
* `setInterval`, `requestAnimationFrame`, `fetch`, audio, WebRTC or any element the site did not
|
|
31
|
+
* hand over.
|
|
32
|
+
*/
|
|
33
|
+
export declare function createActivity(host?: ActivityHost): {
|
|
34
|
+
/** pauses the loop while its target is off screen or the page is hidden */
|
|
35
|
+
register(controls: ActivityControls, options?: ActivityOptions): () => void;
|
|
36
|
+
};
|
|
37
|
+
export declare function browserActivityHost(): ActivityHost;
|