@drupflare/spool 0.2.0 → 0.3.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 +256 -22
- 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 +2 -1
- package/dist/client/index.d.ts +1 -0
- package/dist/client/index.js +1 -0
- package/dist/media/embeds.d.ts +3 -2
- package/dist/media/embeds.js +16 -1
- package/dist/protocol/envelope.d.ts +2 -0
- package/dist/protocol/envelope.js +12 -2
- package/dist/protocol/errors.d.ts +1 -1
- package/dist/protocol/hash.d.ts +2 -0
- package/dist/protocol/hash.js +8 -0
- package/dist/protocol/index.d.ts +4 -0
- package/dist/protocol/index.js +4 -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/provision.d.ts +6 -1
- package/dist/protocol/provision.js +15 -5
- package/dist/protocol/query.d.ts +80 -0
- package/dist/protocol/query.js +153 -0
- package/dist/protocol/route.d.ts +80 -4
- package/dist/protocol/route.js +63 -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/index.d.ts +3 -0
- package/dist/report/index.js +3 -0
- package/dist/report/institution.d.ts +97 -0
- package/dist/report/institution.js +79 -0
- package/dist/report/ledger.d.ts +28 -0
- package/dist/report/ledger.js +30 -0
- package/dist/report/measurement.d.ts +1 -1
- package/dist/report/measurement.js +4 -1
- package/dist/report/traffic.d.ts +11 -2
- package/dist/report/traffic.js +13 -3
- package/dist/server/embedded.d.ts +3 -3
- package/dist/server/embedded.js +3 -3
- package/dist/server/index.d.ts +1 -0
- package/dist/server/index.js +1 -0
- package/dist/server/spool.d.ts +20 -0
- package/dist/server/spool.js +62 -9
- package/dist/sw/render.d.ts +3 -1
- package/dist/sw/render.js +14 -1
- package/dist/sw/replica.d.ts +2 -0
- package/dist/sw/replica.js +6 -0
- package/dist/sw/router.js +2 -2
- package/dist/sw/runtime.js +104 -9
- package/package.json +4 -2
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 A extends Error{code;constructor(e,t){super(t);this.name="ProtocolError",this.code=e}}function le(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function we(e){if(!le(e))return!1;let t=Object.keys(e);if(t.length!==1)return!1;let n=t[0];return(n==="$record"||n==="$projection")&&typeof e[n]==="string"}function re(e){let t=new Set,n=new Set,r=(o)=>{if(Array.isArray(o))return o.forEach(r);if(!le(o))return;if(we(o)){if("$record"in o)t.add(o.$record);else n.add(o.$projection);return}Object.values(o).forEach(r)};return r(e),{records:[...t].sort(),projections:[...n].sort()}}function Le(e,t){let n=(r,o)=>{if(Array.isArray(r))return r.map((s)=>n(s,o));if(!le(r))return r;if(we(r)){if("$record"in r){let l=t.record(r.$record);if(!l)throw Error(`record ${r.$record} is not stored`);return l.data}let s=r.$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 n(a.data,[...o,s])}return Object.fromEntries(Object.entries(r).map(([s,a])=>[s,n(a,o)]))};try{return{ok:!0,value:n(e,[])}}catch(r){return{ok:!1,reason:r instanceof Error?r.message:"unresolved reference"}}}function K(e){throw new A("bad-artifact",e)}function $t(e,t){if(typeof e!=="number"||!Number.isSafeInteger(e)||e<0)return K(`${t} version must be a non-negative integer`);return e}function Lt(e){if(!le(e))return K("record must be an object");if(typeof e.id!=="string"||e.id==="")return K("record id");if(!("data"in e))return K(`record ${e.id} needs data`);return{id:e.id,version:$t(e.version,"record"),data:e.data}}function Dt(e){if(!le(e))return K("projection must be an object");let{id:t,deps:n}=e;if(typeof t!=="string"||t==="")return K("projection id");if(!Array.isArray(n)||n.some((r)=>typeof r!=="string"))return K(`projection ${t} deps must be a list of strings`);if(!("data"in e))return K(`projection ${t} needs data`);return{id:t,version:$t(e.version,"projection"),deps:n,data:e.data}}var x=1;function H(e){throw new A("bad-artifact",e)}function De(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function Ht(e,t){if(e===void 0)return;if(!De(e))return H(`${t} must be an object`);for(let n of Object.values(e))if(typeof n!=="string"&&!we(n))return H(`${t} values must be strings or references`);return e}function Ft(e,t,n){if(e===void 0)return;if(!Array.isArray(e))return H(`${t} must be a list`);return e.map(n)}function de(e){if(!De(e))return H("artifact must be an object");if(e.protocol!==x)return H("unsupported protocol version");let{id:t,scope:n,deps:r,vector:o,strategy:s,body:a}=e;if(typeof t!=="string"||!t.startsWith("/"))return H("id must be a path");if(n!=="public"&&n!=="principal")return H("scope must be public or principal");if(!Array.isArray(r)||r.some((f)=>typeof f!=="string"))return H("deps must be a list of strings");if(typeof o!=="number"||!Number.isSafeInteger(o)||o<0)return H("vector must be a non-negative integer");if(!De(a))return H("body must be an object");let l={protocol:x,id:t,scope:n,deps:r,vector:o},u=Ft(e.records,"records",Lt),p=Ft(e.projections,"projections",Dt);if(u)l.records=u;if(p)l.projections=p;if(s==="template"||s==="projection"||s==="data"){if(!("data"in a))return H(`${s} body needs data`);return{...l,strategy:s,body:{data:a.data}}}if(s==="assembly"){if(typeof a.shell!=="string")return H("assembly body needs a shell string");let f={shell:a.shell},h=Ht(a.fragments,"fragments"),S=Ht(a.slots,"slots");if(h)f.fragments=h;if(S)f.slots=S;return{...l,strategy:s,body:f}}return H(`unknown strategy ${String(s)}`)}function E(e){return new Promise((t,n)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>n(e.error)})}function xr(e){return new Promise((t,n)=>{e.oncomplete=()=>t(),e.onerror=()=>n(e.error),e.onabort=()=>n(e.error)})}function be(e=indexedDB,t="spool"){let n,r=()=>n??=new Promise((s,a)=>{let l=e.open(t,2);l.onupgradeneeded=()=>{let u=l.result,p=(f)=>!u.objectStoreNames.contains(f);if(p("artifacts"))u.createObjectStore("artifacts",{keyPath:"artifact.id"});if(p("meta"))u.createObjectStore("meta");if(p("beacons"))u.createObjectStore("beacons",{autoIncrement:!0});if(p("records"))u.createObjectStore("records",{keyPath:"id"});if(p("projections"))u.createObjectStore("projections",{keyPath:"id"})},l.onsuccess=()=>{let u=l.result;u.onversionchange=()=>{u.close(),n=void 0},s(u)},l.onerror=()=>a(l.error)});async function o(s,a,l){let p=(await r()).transaction(s,a),f=xr(p),h=await l(p.objectStore(s));return await f,h}return{destroy:async()=>{(await n?.catch(()=>{return}))?.close(),n=void 0,await new Promise((a)=>{let l=e.deleteDatabase(t);l.onsuccess=()=>a(),l.onerror=()=>a()})},getArtifact:(s)=>o("artifacts","readonly",(a)=>E(a.get(s))),putArtifact:(s)=>o("artifacts","readwrite",async(a)=>void await E(a.put(s))),deleteArtifacts:(s)=>o("artifacts","readwrite",async(a)=>{await Promise.all(s.map((l)=>E(a.delete(l))))}),allArtifacts:()=>o("artifacts","readonly",(s)=>E(s.getAll())),clearArtifacts:()=>o("artifacts","readwrite",async(s)=>void await E(s.clear())),getMeta:()=>o("meta","readonly",(s)=>E(s.get("replica"))),setMeta:(s)=>o("meta","readwrite",async(a)=>void await E(a.put(s,"replica"))),addBeacon:(s)=>o("beacons","readwrite",async(a)=>void await E(a.add(s))),readBeacons:()=>o("beacons","readonly",async(s)=>{let[a,l]=await Promise.all([E(s.getAllKeys()),E(s.getAll())]);return a.map((u,p)=>({key:u,event:l[p]}))}),removeBeacons:(s)=>o("beacons","readwrite",async(a)=>{await Promise.all(s.map((l)=>E(a.delete(l))))}),getFlush:()=>o("meta","readonly",(s)=>E(s.get("flush"))),setFlush:(s)=>o("meta","readwrite",async(a)=>void await E(a.put(s,"flush"))),putRecords:(s)=>o("records","readwrite",async(a)=>{await Promise.all(s.map((l)=>E(a.put(l))))}),allRecords:()=>o("records","readonly",(s)=>E(s.getAll())),deleteRecords:(s)=>o("records","readwrite",async(a)=>{await Promise.all(s.map((l)=>E(a.delete(l))))}),putProjections:(s)=>o("projections","readwrite",async(a)=>{await Promise.all(s.map((l)=>E(a.put(l))))}),allProjections:()=>o("projections","readonly",(s)=>E(s.getAll())),deleteProjections:(s)=>o("projections","readwrite",async(a)=>{await Promise.all(s.map((l)=>E(a.delete(l))))}),clearGraph:async()=>{await o("records","readwrite",async(s)=>void await E(s.clear())),await o("projections","readwrite",async(s)=>void await E(s.clear()))}}}var He=new TextEncoder,Pr=new TextDecoder;async function Er(e,t,n,r){let o=crypto.getRandomValues(new Uint8Array(12)),s=await crypto.subtle.encrypt({name:"AES-GCM",iv:o,additionalData:He.encode(t)},e,He.encode(JSON.stringify(n)));return{sealed:{iv:o,data:s,at:r}}}async function kr(e,t,n,r){let o=r?.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:He.encode(n)},s,o.data);return JSON.parse(Pr.decode(a))}catch{return}}function Vt(e,t){let{partition:n,vault:r}=t,o=!1,s=(u,p)=>`${n}\x00${u}\x00${p}`;async function a(u,p,f,h){let S=await r.get(n,u,!0);if(!S)throw Error("no key");return Er(S,s(p,f),h,u)}let l=(u,p,f)=>kr(r,n,s(u,p),f);return{kill:()=>void(o=!0),async getArtifact(u){if(o)return;let p=await e.getArtifact(u);if(!p)return;let f=await l("artifact",u,p);if(!f)await e.deleteArtifacts([u]);return f},async putArtifact(u){if(o)return;let p=u.artifact.id,f=await a(t.retentionOf(p),"artifact",p,u);if(o)return;await e.putArtifact({artifact:{id:p},...f})},deleteArtifacts:(u)=>o?Promise.resolve():e.deleteArtifacts(u),async allArtifacts(){if(o)return[];let u=[],p=[];for(let f of await e.allArtifacts()){let h=f.artifact.id,S=await l("artifact",h,f);if(S)u.push(S);else p.push(h)}if(p.length>0)await e.deleteArtifacts(p);return u},clearArtifacts:()=>o?Promise.resolve():e.clearArtifacts(),async getMeta(){if(o)return;return l("meta","replica",await e.getMeta())},async setMeta(u){if(o)return;let p=await a(t.shared,"meta","replica",u);if(!o)await e.setMeta(p)},addBeacon:(u)=>e.addBeacon(u),readBeacons:()=>e.readBeacons(),removeBeacons:(u)=>e.removeBeacons(u),getFlush:()=>e.getFlush(),setFlush:(u)=>e.setFlush(u),async putRecords(u){if(o)return;let p=await Promise.all(u.map(async(f)=>({id:f.id,version:f.version,...await a(t.shared,"record",f.id,f)})));if(!o)await e.putRecords(p)},async allRecords(){if(o)return[];let u=[];for(let p of await e.allRecords()){let f=await l("record",p.id,p);if(f)u.push(f)}return u},deleteRecords:(u)=>o?Promise.resolve():e.deleteRecords(u),async putProjections(u){if(o)return;let p=await Promise.all(u.map(async(f)=>({id:f.id,version:f.version,...await a(t.shared,"projection",f.id,f)})));if(!o)await e.putProjections(p)},async allProjections(){if(o)return[];let u=[];for(let p of await e.allProjections()){let f=await l("projection",p.id,p);if(f)u.push(f)}return u},deleteProjections:(u)=>o?Promise.resolve():e.deleteProjections(u),clearGraph:()=>o?Promise.resolve():e.clearGraph()}}var Or="spool-keys",Ve="keys",Ue="meta",Fe="partition";function oe(e){return new Promise((t,n)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>n(e.error)})}function Ut(e){return new Promise((t,n)=>{let r=e.open(Or,1);r.onupgradeneeded=()=>{r.result.createObjectStore(Ve),r.result.createObjectStore(Ue)},r.onsuccess=()=>{let o=r.result;o.onversionchange=()=>o.close(),t(o)},r.onerror=()=>n(r.error)})}function Tr(e=indexedDB){let t=new Map,n=Promise.resolve(),r=(a)=>{let l=n.then(a,a);return n=l.catch(()=>{return}),l},o=()=>crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);async function s(a,l){let u=await Ut(e);try{let p=u.transaction(Ve,a),f=new Promise((S,v)=>{p.oncomplete=()=>S(),p.onerror=()=>v(p.error),p.onabort=()=>v(p.error)}),h=await l(p.objectStore(Ve));return await f,h}finally{u.close()}}return{get:(a,l,u)=>r(async()=>{if(l==="session"){let h=t.get(a);if(!h&&u)h=await o(),t.set(a,h);return h}let p=await s("readonly",(h)=>oe(h.get(a)));if(p||!u)return p;let f=await o();return await s("readwrite",async(h)=>void await oe(h.put(f,a))),f}),shred:(a)=>r(async()=>{t.delete(a),await s("readwrite",async(l)=>void await oe(l.delete(a)))})}}function qt(e=indexedDB,t=Tr(e)){let n=new Map,r=(s)=>`spool-p-${s}`;async function o(s,a){let l=await Ut(e);try{let u=l.transaction(Ue,s),p=new Promise((h,S)=>{u.oncomplete=()=>h(),u.onerror=()=>S(u.error),u.onabort=()=>S(u.error)}),f=await a(u.objectStore(Ue));return await p,f}finally{l.close()}}return{current:async()=>await o("readonly",(s)=>oe(s.get(Fe)))??null,setCurrent:(s)=>o("readwrite",async(a)=>{if(s===null)await oe(a.delete(Fe));else await oe(a.put(s,Fe))}),open(s,a,l){let u=n.get(s);if(u)return u.sealed;let p=be(e,r(s)),f=Vt(p,{partition:s,vault:t,retentionOf:a,shared:l});return n.set(s,{sealed:f,destroy:p.destroy}),f},async destroy(s){let a=n.get(s);if(a?.sealed.kill(),n.delete(s),await t.shred(s),a)await a.destroy();else await new Promise((l)=>{let u=e.deleteDatabase(r(s));u.onsuccess=()=>l(),u.onerror=()=>l()})}}}var qe="/.spool/dropped",Gt="/.spool/",zt=65536;var Wt=8;var Jt=3600000,Go=48*Jt,zo=72*Jt;function Kt(e,t){if(!e||e.length===0)return;let n;try{n=new URL(t)}catch{return}return e.find((r)=>{let o=new URL(r.match);return n.origin===o.origin&&n.pathname.startsWith(o.pathname)})}function jr(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 Qt(e,t,n,r){let o=new URLSearchParams(e);o.set(t.param,jr(t.kind,n,r));let s=o.toString();return s===""?"":`?${s}`}var Re={sync:"/.spool/sync",artifact:"/.spool/artifact",beacon:"/.spool/beacon",worker:"/spool-sw.js"};var _={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"},Ge="*",Cr=/^[A-Za-z0-9_-]{1,128}$/,Nr=/^[A-Za-z0-9_-]{43}$/;function Y(e){throw new A("bad-header",e)}function fe(e,t){if(!/^\d{1,15}$/.test(e.trim()))return Y(`${t} must be a non-negative integer`);return Number(e)}function pe(e,t){try{return decodeURIComponent(e)}catch{return Y(`${t} has a bad escape`)}}function Se(e){return e.split(",").map((t)=>t.trim()).filter((t)=>t!=="")}function ze(e){try{return We(e)}catch{let t=e.get(_.protocol)?.trim();if(t&&/^\d{1,15}$/.test(t)&&Number(t)!==x)return;let n=e.get(_.clear);if(n===null)return;try{return{protocol:x,clear:Se(n).map((r)=>pe(r,"Spool-Clear"))}}catch{return{protocol:x,clear:[Ge]}}}}function We(e){let t={},n=e.get(_.protocol);if(n!==null)t.protocol=fe(n,"Spool-Protocol");let r=e.get(_.artifact);if(r!==null){let p=new Map;for(let O of r.split(";")){let j=O.indexOf("=");if(j<1)return Y("Spool-Artifact has a field without a name");p.set(O.slice(0,j).trim(),O.slice(j+1).trim())}let f=p.get("id"),h=p.get("scope"),S=p.get("v");if(f===void 0||S===void 0)return Y("Spool-Artifact needs id and v");if(h!=="public"&&h!=="principal")return Y("Spool-Artifact scope is unknown");t.artifact={id:pe(f,"Spool-Artifact id"),scope:h,deps:Se(p.get("deps")??"").map((O)=>pe(O,"Spool-Artifact deps")),version:fe(S,"Spool-Artifact v")};let v=p.get("h");if(v!==void 0&&Nr.test(v))t.artifact.hash=v}let o=e.get(_.invalidate);if(o!==null)t.invalidate=Object.fromEntries(Se(o).map((p)=>{let f=p.lastIndexOf("=");if(f<1)return Y("Spool-Invalidate entries are tag=version");return[pe(p.slice(0,f),"Spool-Invalidate tag"),fe(p.slice(f+1),"Spool-Invalidate version")]}));let s=e.get(_.clear);if(s!==null)t.clear=Se(s).map((p)=>pe(p,"Spool-Clear"));let a=e.get(_.vector);if(a!==null)t.vector=fe(a,"Spool-Vector");let l=e.get(_.vectorSeen);if(l!==null)t.seen=fe(l,"Spool-Vector-Seen");let u=e.get(_.partition);if(u!==null){if(!Cr.test(u))return Y("Spool-Partition must be a base64url token");t.partition=u}return t}async function me(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 Zo=new RegExp(`[<>&${String.fromCharCode(8232,8233)}]`,"g");function Xt(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 Yt(e){let t="",n=0;for(;;){let r=e.indexOf('<script type="application/spool+json" data-spool-artifact>',n),o=r<0?-1:e.indexOf("</script>",r+58);if(o<0)return t+e.slice(n);t+=e.slice(n,r),n=o+9}}var Mr=/^[A-Za-z_][A-Za-z0-9_]*$/;function Je(e){let t=e.length>1&&e.endsWith("/")?e.slice(0,-1):e;return t==="/"?[]:t.slice(1).split("/")}function Ke(e){if(!e.startsWith("/"))throw new A("bad-pattern",`pattern must start with "/": ${e}`);let t=new Set,n=Je(e);for(let[r,o]of n.entries()){if(o==="")throw new A("bad-pattern",`empty segment in ${e}`);if(o==="**"){if(r!==n.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(!Mr.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 ve(e,t){let n=Je(e),r=Je(t),o=n[n.length-1]==="**";if(o)n.pop();if(o?r.length<n.length:n.length!==r.length)return null;let s={};for(let a=0;a<n.length;a++){let l=n[a],u=r[a];if(l.startsWith(":")){if(u==="")return null;try{s[l.slice(1)]=decodeURIComponent(u)}catch{return null}}else if(l!==u)return null}return s}var Zt={public:{maxStale:900,mode:"soft"},principal:{maxStale:300,mode:"hard"}};function q(e,t){for(let n of e){let r=ve(n.pattern,t);if(r)return{route:n,params:r}}return null}var en=1,tn=256;function L(e){throw new A("bad-manifest",e)}function Qe(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function Ir(e,t){let n=`routes[${t}]`;if(!Qe(e))return L(`${n} must be an object`);let{pattern:r,strategy:o,version:s,freshness:a,offline:l,sync:u}=e;if(typeof r!=="string")return L(`${n}.pattern must be a string`);try{Ke(r)}catch(f){return L(`${n}: ${f instanceof Error?f.message:"bad pattern"}`)}if(o!=="static")return L(`${r}: strategy must be "static"`);if(typeof s!=="string"||s===""||s.length>tn)return L(`${r}: version must be a string of 1 to ${tn} characters`);let p={pattern:r,strategy:o,version:s};if(a!==void 0){if(!Qe(a))return L(`${r}: freshness must be an object`);let{maxStale:f,mode:h}=a;if(f!==void 0){if(typeof f!=="number"||!Number.isFinite(f)||f<=0)return L(`${r}: freshness.maxStale must be a positive number of seconds`)}if(h!==void 0&&h!=="hard"&&h!=="soft")return L(`${r}: freshness.mode must be "hard" or "soft"`);p.freshness={...f===void 0?{}:{maxStale:f},...h===void 0?{}:{mode:h}}}if(l!==void 0){if(l!=="serve"&&l!=="refuse")return L(`${r}: offline must be "serve" or "refuse"`);p.offline=l}if(u!==void 0){if(u!=="background"&&u!=="deferred")return L(`${r}: sync must be "background" or "deferred"`);p.sync=u}return p}function Xe(e){if(!Qe(e))return L("manifest must be an object");if(e.schema!==en)return L("unsupported manifest schema");let{routes:t}=e;if(!Array.isArray(t))return L("routes must be a list");let n=t.map(Ir),r=new Set;for(let o of n){if(r.has(o.pattern))return L(`${o.pattern}: declared twice`);r.add(o.pattern)}return{schema:en,routes:n}}function Ye(e){return e.routes.map((t)=>({pattern:t.pattern,strategy:"static",scope:"public",freshness:{...Zt.public,...t.freshness},persist:!0,offline:t.offline??"serve",sync:t.sync??"background",version:t.version}))}var Ze="dataset proof does not match its items",ge=(e)=>typeof e==="object"&&e!==null&&!Array.isArray(e),Z=(e,t)=>Object.hasOwn(e,t)?e[t]:void 0;function Ae(e){let t=e?.toJSON;if(typeof e==="object"&&typeof t==="function")return Ae(t.call(e));if(Array.isArray(e))return`[${e.map((n)=>Ae(n)??"null").join(",")}]`;if(ge(e)){let n=[];for(let r of Object.keys(e).sort()){let o=Ae(e[r]);if(o!==void 0)n.push(`${JSON.stringify(r)}:${o}`)}return`{${n.join(",")}}`}return JSON.stringify(e)}function Br(e){return Ae(e)??"null"}async function _r(e,t){if(!ge(t))return!1;let n=Z(t,e.list),r=Z(t,"proof");if(!Array.isArray(n)||!ge(r))return!1;if(r.count!==n.length||typeof r.digest!=="string")return!1;return await me(Br(n))===r.digest}var $r=(e)=>e.trim()!==""&&Number.isFinite(Number(e))?Number(e):null,nn=(e)=>typeof e==="number"?0:typeof e==="string"?1:2;function Lr(e,t){let[n,r]=[nn(e),nn(t)];if(n!==r)return n-r;if(n===2)return 0;return e<t?-1:e>t?1:0}function Dr(e,t,n){let r=ge(t)?Z(t,e.list):void 0;if(!Array.isArray(r)||!r.every(ge))return null;let o=new URLSearchParams(n),s=e.filter??{};for(let v of new Set(o.keys()))if(v!=="sort"&&v!=="page"&&!Object.hasOwn(s,v))return null;let a=r;for(let[v,O]of Object.entries(s)){let j=o.getAll(v);if(j.length===0)continue;if(O==="number"){let V=j.map($r);if(V.includes(null))return null;a=a.filter((F)=>{let I=Z(F,v);return typeof I==="number"&&V.includes(I)})}else a=a.filter((V)=>{let F=Z(V,v),I=typeof F==="string"||typeof F==="number"||typeof F==="boolean"?String(F):void 0;return I!==void 0&&j.includes(I)})}let l=o.getAll("sort");if(l.length>1)return null;if(a=[...a],l.length===1){let v=l[0],O=e.sort??[],j=!O.includes(v)&&v.startsWith("-"),V=j?v.slice(1):v;if(!O.includes(V))return null;a.sort((F,I)=>{let ae=Lr(Z(F,V),Z(I,V));return j?-ae:ae})}let u=o.getAll("page");if(u.length>1)return null;let p=1;if(u.length===1){if(!/^[1-9]\d{0,14}$/.test(u[0]))return null;p=Number(u[0])}let f=a.length,h=e.pageSize,S=h===void 0?1:Math.max(1,Math.ceil(f/h));if(p>S)return null;return{items:h===void 0?a:a.slice((p-1)*h,p*h),total:f,page:p,pages:S}}async function rn(e,t,n){if(!await _r(e,t))return{ok:!1,reason:Ze};let r=Dr(e,t,n);if(!r)return{ok:!1,reason:"query is not one the route declares"};let{items:o,total:s,page:a,pages:l}=r,u={total:s,page:a,pages:l};return{ok:!0,data:{...t,[e.list]:o,query:u}}}var ye="spool:artifact:",et=64,on=256;function tt(e){return`${ye}${e}`}function Q(e){throw new A("bad-sync",e)}function nt(e){return Object.entries(e).map(([t,n])=>`${encodeURIComponent(t)}@${n}`).join(",")}function sn(e){if(typeof e!=="object"||e===null)return Q("sync response must be an object");let t=e;if(t.protocol!==x)return Q("unsupported protocol version");let{cursor:n,changed:r,dropped:o,reset:s,partial:a}=t;if(typeof n!=="number"||!Number.isSafeInteger(n)||n<0)return Q("cursor must be a non-negative integer");if(typeof r!=="object"||r===null||Array.isArray(r))return Q("changed must be an object");for(let u of Object.values(r))if(typeof u!=="number"||!Number.isSafeInteger(u))return Q("changed versions must be integers");if(!Array.isArray(o)||o.some((u)=>typeof u!=="string"))return Q("dropped must be a list of strings");if(typeof s!=="boolean")return Q("reset must be a boolean");if(a!==void 0&&typeof a!=="boolean")return Q("partial must be a boolean");let l={protocol:x,cursor:n,changed:r,dropped:o,reset:s};if(a)l.partial=!0;return l}var rt={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 an="external",ot="/.spool/view",cn="/.spool/loads";function un(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 ln(e,t){return{path:"/.spool/view",body:JSON.stringify(e),contentType:"application/json",at:t}}function dn(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 fn=86400000,Hr=3600000,Fr=20,Vr=3600000,Ur=86400000,qr=256,pn=100,mn=3000,Gr="same-origin";function zr(e,t){let n,r=new Promise((o,s)=>{n=setTimeout(()=>s(Error("timed out")),t)});return Promise.race([e,r]).finally(()=>clearTimeout(n))}var Wr=new TextEncoder,st=(e)=>e.path.startsWith(Gt)||e.deliver==="sink";class it{#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 n=e.method==="GET",r=n?"":e.headers.get("content-type")??"text/plain";if(/octet-stream|multipart|image\//i.test(r))return!1;let o=n?"":await e.clone().text();if(Wr.encode(o).length>zt)return!1;let s=new URL(e.url),a=this.#e.now(),l={path:s.pathname,body:o,contentType:r,at:a};if(s.search!=="")l.search=s.search;if(n)l.method="GET";if(t){if(l.origin=s.origin,l.vendor=t.vendor,l.until=a+t.maxAgeMs,t.delivery==="sink")l.deliver="sink"}return await this.#e.storage.addBeacon(l),!0}flush(){return this.#t??=this.#l().finally(()=>{this.#t=null}),this.#t}async flushAtMoment(){await this.#r();let e=await this.#e.storage.readBeacons();if(e.length===0)return!1;let t=(u)=>u===ot||u===cn||u===qe,n=e.some((u)=>!t(u.event.path)),r=e.filter((u)=>u.event.path===ot).length,o=(await this.#e.want?.()??[]).length>0,s=await this.#c(this.#e.catalogue?.())!==void 0,a=Math.min(...e.map((u)=>u.event.at)),l=this.#e.now()-a>=Vr;if(n||o||s||l||r>=Fr)return this.flush();return!1}async flushIfDue(){let e=this.#e.now(),t=await this.#n(),n=t.checkedAt>e?-1/0:t.checkedAt;if(e-n<Hr)return!1;t.checkedAt=e,await this.#o(t),await this.#r();let r=await this.#e.storage.readBeacons(),o=Math.min(...r.map((a)=>a.event.at));if(r.length===0||e-o<fn)return!1;let s=t.lastStandalone>e?-1/0:t.lastStandalone;if(e-s<fn)return!1;return t.lastStandalone=e,await this.#o(t),this.flush()}async#n(){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#r(){let{storage:e,now:t}=this.#e,n=t(),o=(await e.readBeacons()).filter((s)=>s.event.until!==void 0&&s.event.until<n);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 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:qe,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:a})=>!st(a)&&a.origin===void 0);if(r.length===0)return;await t.removeBeacons(r.map((a)=>a.key));let o=!1,s=[];for(let{event:a}of r){let l=!1;if(!o)try{l=await zr(n(a),e)}catch{o=!0}if(!l)s.push(Gr)}await this.#a(s)}async#l(){let{storage:e,send:t,replay:n,want:r,catalogue:o}=this.#e;await this.#r();let s=await e.readBeacons();if(s.length===0)return!1;let a=!0;for(let h of s.filter((S)=>!st(S.event))){let S;try{S=await n(h.event)}catch{S=!1}if(S)await e.removeBeacons([h.key]);else a=!1}let l=s.filter((h)=>st(h.event)),u=await r?.()??[],p=await this.#c(o?.());if(l.length===0&&u.length===0)return a;let f=!0;for(let h=0;h<Math.max(l.length,1);h+=pn){let S=l.slice(h,h+pn),v={protocol:x,events:S.map(({event:{until:O,...j}})=>j)};if(u.length>0)v.want=u;if(p)v.catalogue=p;u=[],p=void 0;try{f=await t(v)}catch{f=!1}if(!f)return!1;if(await e.removeBeacons(S.map((O)=>O.key)),v.catalogue)await this.#i(v.catalogue.path)}return a&&f}async#c(e){if(!e)return;let t=(await this.#n()).catalogue?.[e.path],n=this.#e.now();return t===void 0||t>n||n-t>=Ur?e:void 0}async#i(e){let t=await this.#n(),n={...t.catalogue};delete n[e],n[e]=this.#e.now();let r=Object.keys(n);for(let o of r.slice(0,r.length-qr))delete n[o];t.catalogue=n,await this.#o(t)}}function Jr(e){try{return new URL(e).origin}catch{return null}}var Kr=Uint8Array.from(atob("R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"),(e)=>e.charCodeAt(0));function gn(e){let t=new Headers;if(e.mode==="cors"){let n=e.headers.get("origin")??Jr(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(Kr,{status:200,headers:t});return new Response(null,{status:204,headers:t})}function yn(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 hn(e,t){return Math.max(e,t)}function wn(e,t){return e.deps.every((n)=>t(n)<=e.vector)}var Qr=["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"],bn=128;function Rn(e){let t=[];for(let n of Qr){let r=e.get(n);if(r!==null)t.push([n,r])}return t}var ee={reuse:0.5,futureViews:2,requestBytes:2000,artifactBytes:20000,avoidedBytes:17054,changesPerDay:1};function vn(e){let{hot:t,...n}=e??{};return{...ee,...n}}function Xr(e,t){return e.bytes+e.requests*t}var Yr={bytes:0,requests:0};function Zr(e,t=ee){let n=e.reuse??t.reuse,r=e.futureViews??t.futureViews,o=(s)=>Xr(s,t.requestBytes);return n*r*o(e.avoided)-o(e.provision)-o(e.maintain??Yr)}var Sn={layout:0,template:0,asset:0,route:1,expansion:2};function An(e,t=ee){return e.map((n)=>({...n,benefit:Zr(n,t)})).filter((n)=>n.benefit>0).sort((n,r)=>Sn[n.kind]-Sn[r.kind]||r.benefit-n.benefit||(n.id<r.id?-1:n.id>r.id?1:0))}class at{#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=(o)=>e.reduce((s,a)=>s+o(a),0),n=t((o)=>o.views),r=t((o)=>o.bytes);return{bytes:r,requests:t((o)=>o.requests),views:n,bytesPerView:n===0?null:r/n,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,n)=>t+n.bytes-n.catalogueBytes,0)/e.length}}var eo=/<span data-spool-placeholder="([^"]*)"><\/span>/g,to=/\{\{spool-slot:([A-Za-z0-9_.-]+)\}\}/g;function xn(e,t,n){let r=[],o=[],s=new Set,a=e.replace(t,(u,p)=>{s.add(p);let f=Object.hasOwn(n,p)?n[p]:void 0;if(f===void 0)return o.push(p),u;return r.push(p),f}),l=Object.keys(n).filter((u)=>!s.has(u));return{html:a,filled:r,unfilled:o,unmatched:l}}function no(e,t){return xn(e,eo,t)}function ro(e,t){return xn(e,to,t)}function Pn(e){let t=(a)=>{let l={};for(let[u,p]of Object.entries(a??{})){if(typeof p!=="string")return null;l[u]=p}return l},n=t(e.fragments),r=t(e.slots);if(!n||!r)return{ok:!1,reason:"unresolved reference"};let o=no(e.shell,n);if(o.unfilled.length>0)return{ok:!1,reason:`unfilled placeholders: ${o.unfilled.join(", ")}`};let s=ro(o.html,r);if(s.unfilled.length>0)return{ok:!1,reason:`unfilled slots: ${s.unfilled.join(", ")}`};return{ok:!0,html:s.html}}function En(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 oo={"&":"&","<":"<",">":">",'"':""","'":"'"};function so(e){return e.replace(/[&<>"']/g,(t)=>oo[t])}function kn(e,t){if(e===null||typeof e!=="object")return;return Object.hasOwn(e,t)?e[t]:void 0}function ct(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 o=t[r];if(kn(o.value,e[0])===void 0)continue;return e.reduce((s,a)=>kn(s,a),o.value)}return}function io(e){if(Array.isArray(e))return e.length>0;return!(e===void 0||e===null||e===!1||e===""||e===0)}function ao(e){return typeof e==="string"||typeof e==="number"?String(e):""}function ut(e,t,n){let r="";for(let o of e)if(o.t==="text")r+=o.v;else if(o.t==="var"){let s=ao(ct(o.p,t));if(!o.raw)r+=so(s);else if(n.has(o.p.join(".")))r+=s;else throw new A("bad-template",`{{{${o.p.join(".")}}}} is not trusted`)}else if(o.t==="if")r+=ut(io(ct(o.p,t))?o.then:o.else,t,n);else{let s=ct(o.p,t);if(!Array.isArray(s))continue;s.forEach((a,l)=>{r+=ut(o.body,[...t,{value:a,index:l}],n)})}return r}function On(e,t){if(e.v!==1)throw new A("bad-template",`unknown template version ${String(e.v)}`);return ut(e.nodes,[{value:t,index:0}],new Set(e.trusted))}async function Tn(e,t,n,r={},o){try{let s=n;if(o!==void 0&&o!==""&&t.query){if(n.strategy==="assembly"||n.strategy==="static")return{ok:!1,reason:`${n.strategy} artifact cannot answer a query`};let u=await rn(t.query,n.body.data,o);if(!u.ok)return u;s={...n,body:{data:u.data}}}let a=Object.hasOwn(r,t.pattern)?r[t.pattern]:void 0,l;if(a)l=await a(s);else if(s.strategy==="data"&&t.strategy==="data")return{ok:!0,html:JSON.stringify(s.body.data)};else if(s.strategy==="projection"&&t.strategy==="projection")return{ok:!1,reason:`no renderer for ${t.pattern}`};else if(s.strategy==="static"||s.strategy!==t.strategy)return{ok:!1,reason:`artifact is ${s.strategy}, route is ${t.strategy}`};else if(s.strategy==="assembly"){let u=Pn(s.body);if(!u.ok)return u;l=u.html}else if(s.strategy!=="template")return{ok:!1,reason:`${s.strategy} has no built-in render`};else{let u=Object.hasOwn(e.templates,t.pattern)?e.templates[t.pattern]:void 0;if(!u)return{ok:!1,reason:`no template for ${t.pattern}`};l=On(u,s.body.data)}if(t.strategy==="data")return{ok:!0,html:l};return{ok:!0,html:En(l,e.clientTag)}}catch(s){return{ok:!1,reason:s instanceof Error?s.message:"render failed"}}}function xe(e,t,n){let r=e.get(t)??new Set;r.add(n),e.set(t,r)}function Pe(e,t,n){let r=e.get(t);if(!r)return;if(r.delete(n),r.size===0)e.delete(t)}class Ee{#e=new Map;#t=new Map;#s=new Map;#n=new Map;#o=new Map;#r=new Map;addProjection(e,t,n){this.removeProjections([e]),this.#r.set(e,{deps:[...t],children:[...n]});for(let r of t)xe(this.#e,r,e);for(let r of n)xe(this.#t,r,e)}removeProjections(e){for(let t of e){let n=this.#r.get(t);if(!n)continue;for(let r of n.deps)Pe(this.#e,r,t);for(let r of n.children)Pe(this.#t,r,t);this.#r.delete(t)}}addArtifact(e,t){this.removeArtifacts([e]),this.#o.set(e,t);for(let n of t.records)xe(this.#s,n,e);for(let n of t.projections)xe(this.#n,n,e)}removeArtifacts(e){for(let t of e){let n=this.#o.get(t);if(!n)continue;for(let r of n.records)Pe(this.#s,r,t);for(let r of n.projections)Pe(this.#n,r,t);this.#o.delete(t)}}clear(){this.#e.clear(),this.#t.clear(),this.#s.clear(),this.#n.clear(),this.#o.clear(),this.#r.clear()}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 o of this.#s.get(r)??[])n.add(o);for(let r of t)for(let o of this.#n.get(r)??[])n.add(o);return[...n].sort()}}class se{#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 lt(e){return new se({all:()=>e.allProjections(),put:(t)=>e.putProjections(t),delete:(t)=>e.deleteProjections(t)})}function dt(e){return new se({all:()=>e.allRecords(),put:(t)=>e.putRecords(t),delete:(t)=>e.deleteRecords(t)})}function Oe(e){return e.records!==void 0||e.projections!==void 0||ke(re(e.body))}var ke=(e)=>e.records.length+e.projections.length>0;function jn(e){return re(e.data).projections}class ft{records;projections;index=new Ee;#e;#t;constructor(e){this.#e=e,this.records=dt(e.storage),this.projections=lt(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,jn(t));for(let{artifact:t}of await this.#e.artifacts()){let n=re(t.body);if(ke(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 o of n){let s=this.projections.get(o);this.index.addProjection(o,s.deps,jn(s))}let r=re(e.body);if(ke(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=(l,u)=>(e[l]??0)>u,r=t.filter((l)=>{let u=this.records.get(l);return u!==void 0&&n(l,u.version)}),o=this.index.projectionsReading(t).filter((l)=>{let u=this.projections.get(l);return u!==void 0&&u.deps.some((p)=>n(p,u.version))}),s=this.index.withParents(o).filter((l)=>this.projections.get(l)),a=this.index.artifactsUsing(r,s);return await this.records.drop(r),await this.projections.drop(s),this.index.removeProjections(s),{records:r.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"||!ke(re(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=Le(e.body.data,t);if(!a.ok)return a;return{ok:!0,artifact:{...e,body:{data:a.value}}}}let n=(a)=>{let l={};for(let[u,p]of Object.entries(a??{})){let f=Le(p,t);if(!f.ok)return f;if(typeof f.value!=="string")return{ok:!1,reason:`${u} did not resolve to text`};l[u]=f.value}return{ok:!0,value:l}},r=n(e.body.fragments);if(!r.ok)return r;let o=n(e.body.slots);if(!o.ok)return o;let s={shell:e.body.shell};if(e.body.fragments)s.fragments=r.value;if(e.body.slots)s.slots=o.value;return{ok:!0,artifact:{...e,body:s}}}}class Te{#e;#t;#s;#n=new Map;#o=new Map;#r=null;#a=0;#l=0;#c;#i=new Map;graph;constructor(e,t,n=Date.now){this.#e=e,this.#t=t,this.#s=n,this.graph=new ft({storage:e,tagVersion:(r)=>this.#o.get(r)??0,artifacts:()=>this.#d()})}async load(){let e=await this.#e.getMeta();if(e&&e.version===this.#t){this.#r=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.#u()}get cursor(){return this.#r}get syncedAt(){return this.#a}get sitePolicy(){return this.#c}policyOf(e){return this.#i.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.#i.get(e)))return;if(this.#i.delete(e),this.#i.set(e,t),this.#i.size>bn)this.#i.delete(this.#i.keys().next().value)}await this.#u()}async get(e){return this.#n.get(e)??await this.#e.getArtifact(e)}async ids(){return(await this.#d()).map((e)=>e.artifact.id)}get epoch(){return this.#l}isCurrent(e){return wn(e,(t)=>this.#o.get(t)??0)}validatedAt(e){return Math.max(hn(e.fetchedAt,this.#a),e.validatedAt??0)}async validate(e){let t=await this.get(e);if(!t||!this.isCurrent(t.artifact))return;let n={...t,validatedAt:this.#s()};if(this.#n.has(e))this.#n.set(e,n);else await this.#e.putArtifact(n)}needFor(e,t=!1){if(!t&&!Oe(e))return null;let n=[...new Set([...e.deps,tt(e.id)])];if(n.length>et)return null;return Object.fromEntries(n.map((r)=>[r,e.vector]))}async held(){return await this.#f(),this.graph.held(on)}async materialize(e){if(Oe(e))await this.#f();return this.graph.materialize(e)}async#f(){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(Oe(e))await this.#f(),await this.graph.put(e,t);let{records:r,projections:o,...s}=e,a={artifact:s,fetchedAt:this.#s(),...n?{catalogue:!0}:{}};if(t)this.#n.delete(e.id),await this.#e.putArtifact(a);else await this.#e.deleteArtifacts([e.id]),this.#n.set(e.id,a);if(this.#r===null)this.#r=e.vector,await this.#u();return!0}async open(e){let t=await this.get(e);if(!t?.catalogue)return;let{catalogue:n,...r}=t;if(this.#n.has(e))this.#n.set(e,r);else await this.#e.putArtifact(r)}async sweep(e){let t={...e};for(let{artifact:n,catalogue:r}of await this.#d()){if(!r)continue;for(let o of[...n.deps,tt(n.id)])t[o]=Math.min(t[o]??1/0,n.vector)}return Object.keys(t).length>et?null:t}async drop(e){for(let t of e)this.#n.delete(t);if(await this.#e.deleteArtifacts(e),this.graph.loaded)this.graph.forgetArtifacts(e)}async wipe(e=null){this.#l+=1,this.#n.clear(),await this.#e.clearArtifacts(),await this.graph.clear(),this.#o=new Map,this.#c=void 0,this.#i=new Map,this.#r=e,await this.#u()}async applySync(e){if(e.reset){let n=await this.ids();return await this.wipe(e.cursor),this.#a=this.#s(),await this.#u(),n}let t=await this.#p(e.changed);if(await this.drop(e.dropped),!e.partial)this.#r=Math.max(this.#r??0,e.cursor),this.#a=this.#s();return await this.#u(),[...new Set([...t,...e.dropped])]}async applyEnvelope(e,t,n){let r=[];if(e.clear?.includes(Ge))r=await this.ids(),await this.wipe(e.vector??this.#r);else if(e.invalidate)r=await this.#p(e.invalidate);if(t!==null&&e.seen===t&&e.vector!==void 0&&!n)this.#r=Math.max(this.#r??0,e.vector),this.#a=this.#s();return await this.#u(),r}async#d(){return[...this.#n.values(),...await this.#e.allArtifacts()]}async#p(e){let t=new Map;for(let[o,s]of Object.entries(e))if(o.startsWith(ye))t.set(o.slice(ye.length),s);else if(s>(this.#o.get(o)??0))this.#o.set(o,s);let n=this.graph.loaded?(await this.graph.invalidate(Object.fromEntries(this.#m(e)))).artifacts:[],r=(await this.#d()).filter(({artifact:o})=>{let s=t.get(o.id);return s!==void 0&&o.vector<s||!this.isCurrent(o)||n.includes(o.id)}).map(({artifact:o})=>o.id);return await this.drop(r),r}#m(e){return Object.entries(e).filter(([t])=>!t.startsWith(ye))}async#u(){await this.#e.setMeta({version:this.#t,cursor:this.#r,tags:[...this.#o],syncedAt:this.#a,policy:{...this.#c?{site:this.#c}:{},paths:[...this.#i]}})}}function co(e,t){return e.thirdParty?.allow.includes(t.origin)===!0}function pt(e,t,n){let r=new URL(t.url);if(r.origin!==n){let a=Kt(e.collectors,t.url);if(a&&(t.method==="POST"||t.method==="GET"))return{kind:"collector",collector:a};if(t.method==="GET"&&co(e,r))return{kind:"thirdparty"};return{kind:"ignore"}}if(e.logout?.some((a)=>ve(a,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 o=q(e.routes,r.pathname),s=r.search!==""&&!o?.route.query;if(t.mode!=="navigate"){if(o?.route.strategy==="static"&&!t.headers.has("range"))return{kind:"static",route:o.route,path:r.pathname+r.search};if(o?.route.strategy==="data"&&!t.headers.has("range")&&!s)return{kind:"data",route:o.route,path:r.pathname};return{kind:"asset"}}if(!o||o.route.strategy==="data"||s)return{kind:"pass"};return{kind:"navigation",route:o.route,params:o.params,path:r.pathname}}function uo(e,t){let n=(o)=>`${t}${o}`,r=[{condition:{requestMode:"navigate"},source:"fetch-event"}];for(let o of e.beacons)r.push({condition:{urlPattern:n(o),requestMethod:"POST"},source:"fetch-event"});for(let o of e.logout??[])r.push({condition:{urlPattern:n(o)},source:"fetch-event"});for(let o of e.routes)if(o.strategy==="static"||o.strategy==="data")r.push({condition:{urlPattern:n(o.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 Cn(e,t,n){if(typeof e.addRoutes!=="function")return!1;try{return await e.addRoutes(uo(t,n)),!0}catch{return!1}}var lo=86400,fo={changesPerDay:ee.changesPerDay,staleBytes:ee.avoidedBytes,syncBytes:ee.requestBytes};class Nn{#e;#t;constructor(e){this.#e=1,this.#t=lo/e}observe(e,t,n){this.#e+=n,this.#t+=e*t}perSecond(){return this.#e/this.#t}}function po(e){return(1-Math.exp(-e.perSecond*e.tags*Math.max(0,e.ageSec)))*e.policy.staleBytes-e.policy.syncBytes}var mo=(e)=>e?Object.entries(e).sort().join("|"):"*";class mt{#e;#t=new Map;#s;#n={};#o=0;rate;constructor(e){this.#e=e,this.#s=e.policy??fo,this.rate=new Nn(this.#s.changesPerDay)}sync(e,t){let n=this.#t.get("*");if(n)return n;let r=mo(e),o=this.#t.get(r);if(o)return o;let s=[...this.#t.values()],a=Promise.allSettled(s).then(()=>this.#r(e,t)).finally(()=>{if(this.#t.get(r)===a)this.#t.delete(r)});return this.#t.set(r,a),a}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(po({ageSec:t,perSecond:this.rate.perSecond(),tags:n,policy:this.#s})<=0)return!1;for(let[o,s]of Object.entries(e))this.#n[o]=Math.min(s,this.#n[o]??1/0);return this.#o=Math.max(this.#o,t),!0}get pending(){return Object.keys(this.#n).sort()}drain(){let e=this.#n;if(Object.keys(e).length===0)return Promise.resolve(!0);let t=this.#o;return this.#n={},this.#o=0,this.sync(e,t)}async#r(e,t){let{replica:n,fetchSync:r,onNetwork:o}=this.#e,s=n.cursor;if(s===null&&!e)return!0;try{let a=await r(s??0,e);if(e&&t!==void 0&&!a.reset){let l=Object.keys(e),u=l.filter((p)=>Object.hasOwn(a.changed,p)).length;this.rate.observe(l.length,t,u)}return await n.applySync(a),!0}catch{return!1}finally{o?.()}}}var go="\x00";function Mn(e,t={}){let n=Yt(e).replace(/<!--[\s\S]*?-->/g,"");for(let r of t.ignore??[]){let o=r.flags.includes("g")?r.flags:`${r.flags}g`;n=n.replace(new RegExp(r.source,o),go)}return n.replace(/\s+/g," ").replace(/>\s+</g,"><").trim()}function In(e,t,n={}){let r=Mn(e,n),o=Mn(t,n);if(r===o)return{equal:!0};let s=0;while(s<r.length&&r[s]===o[s])s++;return{at:s,equal:!1,reason:`diverges at ${s}: ${JSON.stringify(r.slice(s,s+80))} vs ${JSON.stringify(o.slice(s,s+80))}`}}function je(e,t){return t.mode??e.mode??"serve"}function Bn(e,t,n){if(t.strategy==="static")return!1;if(je(e,t)==="shadow")return!0;let r=e.shadowSample??0;return r>0&&n()<r}async function _n(e,t){if(t.status!==200)return!0;return!In(e,await t.text()).equal}var gt="spool-static-",yt=4194304,yo=["content-encoding","content-length","transfer-encoding","connection","keep-alive","set-cookie","age","date","vary"];function Ln(e){let t=new Headers(e);for(let n of yo)t.delete(n);return t}async function ht(e,t){if(Number(e.headers.get("content-length"))>t)return null;let n=e.body?.getReader();if(!n)return new Uint8Array;let r=[],o=0;for(;;){let{done:l,value:u}=await n.read();if(l)break;if(o+=u.byteLength,o>t)return n.cancel().catch(()=>{return}),null;r.push(u)}let s=new Uint8Array(o),a=0;for(let l of r)s.set(l,a),a+=l.byteLength;return s}var ho=/^sha(256|384|512)-([A-Za-z0-9+/]+={0,2})$/,wo=/^(?:W\/)?"/;function bo(e){let t="";for(let n of e)t+=String.fromCharCode(n);return btoa(t)}var $n=(e)=>e.replace(/^W\//,"");async function Dn(e,t,n){let r=ho.exec(e);if(r){let o=await crypto.subtle.digest(`SHA-${r[1]}`,t);return bo(new Uint8Array(o))===r[2]}if(wo.test(e)){let o=n.get("etag");return o!==null&&$n(o)===$n(e)}return!0}var he="spool-third",ie={class:"x-spool-class",fetched:"x-spool-fetched"};var Ro=[/[._-][0-9a-f]{8,}(?=[._-]|$)/i,/[@/_-]v?\d+\.\d+\.\d+/,/\/v\d+(?:\/|$)/],So=/[?&](?:v|ver|version|hash|h|rev)=[^&]+/i;function Hn(e,t,n=[]){if(Ro.some((s)=>s.test(e.pathname)))return"immutable";let r=t.get("cache-control")??"";if(/(?:^|,)\s*immutable\b/i.test(r))return"immutable";let o=/max-age=(\d+)/i.exec(r);if(o!==null&&Number(o[1])>=31536000)return"immutable";if(So.test(e.search))return"revalidate";for(let s of n)try{if(new RegExp(s).test(e.href))return"revalidate"}catch{continue}return null}var vo=["template","projection","data"],Vn="spool-assets-",Ao=[Vn,gt],xo=31536000,Po=86400000,Ce=new TextEncoder,Fn=(e)=>e.split("?",1)[0];function Eo(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])>=xo}function Un(e){let{config:t,storage:n,origin:r,renderers:o}=e,s=e.partitions,a=e.now??Date.now,l=e.random??Math.random,u=dn(e.userAgent??(typeof navigator>"u"?"":navigator.userAgent)),p=vn(t.provision),f=new Te(n,t.version,a),h=new at,S=new Set,v=new Map,O=new Set,j=new Set,V=new Set,F=null,I=new Map,ae=`${Vn}${t.version}`,ce=`${gt}${t.version}`,wt=(i)=>new Request(`${r}${i}`),Wn=a(),Ne=t.assets??"cache",bt=!1,Me=null,Jn,Rt,Kn,T=null,St=Promise.resolve(),Qn=t.mode==="shadow",vt=()=>t.manifest!==void 0&&t.routes.length===0,Ie=new Map,G=(i)=>{let c=Ie.get(i);if(!c)c=e.caches.open(i),Ie.set(i,c),c.catch(()=>Ie.delete(i));return c},U=async()=>{if(await(Jn??=f.load()),vt())await(Rt??=br());if(s)await(Kn??=ar())},W=(i)=>{let c=i.then(()=>{return},()=>{return});S.add(c),c.then(()=>S.delete(c))},Xn=async()=>{while(S.size>0)await Promise.allSettled([...S])},At=(i)=>{let c=St.then(i,i);return St=c.catch(()=>{return}),c};async function Yn(i,c){if(t.manifest)return Nt();let d=c?`need=${encodeURIComponent(nt(c))}`:`from=${i}`,m=await e.fetch(`${r}${Re.sync}?${d}`,{cache:"no-store",credentials:"same-origin"});if(!m.ok)throw Error(`sync answered ${m.status}`);return await Et(ze(m.headers),!0),sn(await m.json())}let Zn={changesPerDay:p.changesPerDay,staleBytes:p.avoidedBytes,syncBytes:p.requestBytes};async function er(){let i=[];for(let d of j)if(!await f.get(d))i.push(d);let c=[];for(let d of t.provision?.hot??[]){if(V.has(d)||i.includes(d)||await f.get(d))continue;let m=q(t.routes,d);if(!m||m.route.scope!=="public"||m.route.strategy==="static")continue;c.push({id:d,kind:"route",provision:{bytes:h.meanFetchBytes()??p.artifactBytes,requests:0},avoided:{bytes:p.avoidedBytes,requests:1}})}return[...i,...An(c,p).map((d)=>d.id)].slice(0,Wt)}async function tr(i,c,d){let m=q(t.routes,i.id);if(!m||i.scope!=="public"||i.strategy!==m.route.strategy)return;if(await f.put(i,m.route.persist))h.spend(i.id,{bytes:c,requests:d})}let nr=()=>F!==null?{path:F,sweep:!0}:void 0;async function rr(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:Ce.encode(JSON.stringify(d)).length,requests:0},!0);let g=q(t.routes,m.id);if(!g||!vo.includes(m.strategy))continue;if(m.strategy!==g.route.strategy||m.scope!==g.route.scope)continue;let y=X;if(m.scope==="principal"){if(y=await te(),!y||y.id!==c)continue}if(await y.replica.get(m.id))continue;await y.replica.put(m,g.route.persist,!0)}}async function or(i){let c=t.collectors?.find((w)=>w.vendor===i.vendor),d=i.search??"";if(c?.stamp)d=Qt(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 w=i.contentType.split(";")[0]?.trim().toLowerCase()??"",R=["","text/plain","application/x-www-form-urlencoded"].includes(w);g.mode=R?"no-cors":"cors"}let y=await e.fetch(`${i.origin??r}${i.path}${d}`,g);return y.type==="opaque"||y.ok||y.status>=400&&y.status<500}let z=new it({storage:n,now:a,want:er,catalogue:nr,replay:or,async send(i){let c=await e.fetch(`${r}${Re.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 y=de(g);await tr(y,Ce.encode(JSON.stringify(g)).length,0)}for(let g of i.want)j.delete(g),V.add(g)}if(i.catalogue)await rr(d.catalogue,c.headers.get(_.partition))}return c.ok||c.status>=400&&c.status<500}}),xt=(i)=>new mt({replica:i,fetchSync:Yn,onNetwork:()=>W(z.flushAtMoment()),policy:Zn}),X={id:null,replica:f,scheduler:xt(f),deferred:new Set,loaded:Promise.resolve()},To=X.scheduler,sr=(i)=>q(t.routes,i)?.route.retention??"session",ir=()=>t.routes.some((i)=>i.scope==="principal"&&i.retention==="persistent")?"persistent":"session";function Pt(i){let c=s.open(i,sr,ir()),d=new Te(c,t.version,a);return{id:i,replica:d,scheduler:xt(d),deferred:new Set,loaded:d.load()}}async function ar(){let i=await s.current();if(i&&!T)T=Pt(i)}async function te(){await U();let i=T;if(!i)return null;return await i.loaded,i}function Be(i){return At(async()=>{await U();let c=T;if(T=null,!c||!s)return!1;return await s.setCurrent(null),await s.destroy(c.id),e.broadcast?.({type:"spool:cleared",reason:i}),!0})}function cr(i){return At(async()=>{await U();let c=T;if(c?.id===i)return;if(T=Pt(i),await s.setCurrent(i),c)await s.destroy(c.id),e.broadcast?.({type:"spool:cleared",reason:"partition"})})}async function Et(i,c,d=!1){if(!s||!i||i.protocol!==x)return;await U();let m=i.clear??[];if(m.includes("*")||T&&m.includes(T.id)){await Be("clear");return}if(d)return;if(i.partition!==void 0){if(T?.id!==i.partition)await cr(i.partition)}else if(c&&T)await Be("session-ended")}async function ur(i,c,d){let m=c.scope==="principal"?await te():X;if(!m||c.scope==="principal"&&m.id!==d)return;let g=await m.replica.held(),y=Object.keys(g).length>0?`&have=${encodeURIComponent(nt(g))}`:"",w=await e.fetch(`${r}${Re.artifact}?path=${encodeURIComponent(i)}${y}`,{cache:"no-store",credentials:"same-origin"});if(w.status===204&&w.headers.get(_.provision)==="declined"){O.add(i);return}if(!w.ok){if(c.scope==="principal"&&[401,403,404].includes(w.status))await m.replica.drop([i]);return}let R=await w.text(),b=de(JSON.parse(R));if(b.scope!==c.scope||b.id!==i)return;if(b.strategy!==c.strategy)return;if(c.scope==="principal"){if(w.headers.get(_.partition)!==d)return;if(T!==m)return}if(await m.replica.put(b,c.persist))h.spend(i,{bytes:Ce.encode(R).length,requests:1})}async function kt(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 lr(i,c,d,m,g,y,w){if(await w(),c&&c.protocol===x){await f.applyEnvelope(c,d,i.has("age"));let R=T;if(R)await R.loaded,await R.replica.applyEnvelope(c,null,!0);let b=c.artifact;if(y&&b){let P=q(t.routes,b.id),N=b.scope==="principal"?await te():X,C=P&&P.route.strategy!=="static"&&P.route.scope===b.scope&&!O.has(b.id)&&N&&(b.scope==="public"||N.id===c.partition);if(P&&N&&C&&!await N.replica.get(b.id))if(b.scope==="public"&&je(t,P.route)==="shadow")j.add(b.id);else{let k=`${b.scope}:${b.id}`,M=v.get(k)??ur(b.id,P.route,c.partition);v.set(k,M);try{await M}catch{}finally{v.delete(k)}}}}if(g){if(await kt(X),T)await kt(T);await z.flushAtMoment(),await vr()}}async function dr(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 y=Rn(c.headers);if(m)await f.keepPolicy(null,y);let w=g?.route,R=new URL(i.url);if(!w||w.strategy==="static"||R.search!=="")return;let b=w.scope==="principal"?T?.id===d?.partition?T:null:X;if(!b)return;await b.loaded,await b.replica.keepPolicy(R.pathname,y)}async function J(i,c,d){let m=i,g=null;if(!t.manifest&&!c&&i.method==="GET"&&f.cursor!==null)try{let N=new Headers(i.headers);N.set(_.vectorSeen,String(f.cursor)),m=new Request(i,{headers:N}),g=f.cursor}catch{m=i}let y=await e.fetch(m),w=ze(y.headers);await Et(w,c,d?.signedOut);let R=c||i.method!=="GET",b=d?.clone,P=(typeof b==="function"?b(y,w):b)?y.clone():null;return W((async()=>{try{await d?.run(P,w)}catch{}await lr(y.headers,w,g,c,R,d?.provision??c,()=>dr(i,y,w,c,d))})()),y}async function _e(i,c,d,m=""){let g=X;if(c.scope==="principal"){if(!s)return{reason:"principal",staleSec:null};let B=await te();if(!B)return{reason:"cold",staleSec:null};g=B}let{replica:y,scheduler:w}=g,R=await y.get(i);if(!R)return{reason:"cold",staleSec:null};let b=()=>R?Math.max(0,Math.floor((a()-y.validatedAt(R))/1000)):null;if(!y.isCurrent(R.artifact)){let B=b();return await y.drop([i]),{reason:"invalidated",staleSec:B}}if(c.version!==void 0&&R.artifact.strategy==="static"&&R.artifact.body.version!==c.version){let B=b();return await y.drop([i]),{reason:"invalidated",staleSec:B}}let P=R.catalogue===!0,N=yn(c.freshness,y.validatedAt(R),a()),C=b(),k=y.needFor(R.artifact,c.sync==="deferred"||c.scope==="principal"),M=(c.scope==="principal"&&k?await y.sweep(k):k)??void 0,D="fresh";if(N==="sync-first"){if(D="hard-sync",!d){let B=await w.sync(M,C);if(!B&&c.offline==="refuse")return{reason:"hard-refused",staleSec:C};if(B){if(M)await y.validate(i);if(R=await y.get(i),!R||!y.isCurrent(R.artifact))return{reason:"stale-after-sync",staleSec:C}}else D="offline-stale"}}else if(N==="serve-then-sync"){if(c.sync==="deferred"){if(D="soft-deferred",!d&&M&&w.defer(M,C))g.deferred.add(i)}else if(D="soft-sync",!d)W(w.sync(M,C).then(async(B)=>{if(B&&M)await y.validate(i)}))}if(c.strategy==="static"){let B=await gr(i);if(!B)return await y.drop([i]),{reason:"refused",staleSec:C};return{reason:D,response:B,staleSec:C}}let ne=y.policyOf(i)??f.sitePolicy;if(!ne&&!d)return{reason:"refused",staleSec:C};let _t=await y.materialize(R.artifact);if(!_t.ok)return await y.drop([i]),{reason:"refused",staleSec:C};let $e=await Tn(t,c,_t.artifact,o,m);if(!$e.ok){if($e.reason===Ze)await y.drop([i]);return{reason:"refused",staleSec:C}}if(P){if(await y.open(i),rt[D]==="local")D="catalogue"}return{reason:D,html:$e.html,headers:ne,staleSec:C}}function fr(i){let c;try{c=new URL(i)}catch{return}if(c.protocol!=="http:"&&c.protocol!=="https:")return;if(c.origin!==r)return an;return q(t.routes,c.pathname)?.route.pattern}async function pr(i,c,d){let m=Bn(t,c,l),g=a(),y=Me===null?null:g-Me;Me=g,F=c.catalogue?i:null;let w=await _e(i,c,m,new URL(d.url).search),R=fr(d.referrer),b=crypto.randomUUID();if(I.delete(i),I.set(i,b),I.size>64)I.delete(I.keys().next().value);let P=(k)=>({id:b,crossOriginLoads:null,tier:m?"shadow":rt[w.reason],reason:w.reason,staleSec:w.staleSec,engine:u,scope:c.scope,strategy:c.strategy,route:c.pattern,mismatch:k,swAgeMs:g-Wn,gapMs:y,...R?{from:R}:{}}),N=async(k)=>{if(t.views!==!1)await z.record(ln(P(k),g))};if(m){let k=w.html;return J(d,!0,{clone:k!==void 0,route:c,run:async(M)=>{await N(k===void 0||!M?null:await _n(k,M))}})}if(w.response)return h.serve(i),W(N(null)),w.response;if(w.html===void 0){let k=c.strategy==="static",M=await J(d,!0,{clone:k||((D,ne)=>Ct(i,c,D,ne)),route:c,run:async(D,ne)=>{if(k)await jt(i,c,D);else await hr(i,c,D,ne);await N(null)}});if(c.scope==="principal"&&Ot(M))await Tt(i);return M}h.serve(i,w.reason==="catalogue"),W(N(null));let C=new Headers(w.headers);return C.set("content-type","text/html; charset=utf-8"),new Response(w.html,{headers:C})}function Ot(i){return i.status===401||i.status===403||i.type==="opaqueredirect"||i.status>=300&&i.status<400}async function Tt(i){let c=await te();if(c)await c.replica.drop([i])}async function mr(i,c,d){let m=await _e(c,d,!1,new URL(i.url).search);if(m.html!==void 0){h.serve(c,m.reason==="catalogue");let y=new Headers(m.headers);return y.set("content-type",d.type??"application/json"),new Response(m.html,{headers:y})}let g=await J(i,!1,{provision:!0,route:d,run:async()=>{return}});if(d.scope==="principal"&&Ot(g))await Tt(c);return g}async function gr(i){return(await G(ce)).match(wt(i))}async function jt(i,c,d){if(!d||d.status!==200||d.redirected)return;let m=t.manifest?q(t.routes,Fn(i))?.route:c;if(m?.strategy!=="static")return;let g=await ht(d,yt);if(!g)return;let y=d.headers.get("content-type")??"application/octet-stream",w;if(t.manifest){let b=m.version;if(b===void 0||!await Dn(b,g,d.headers))return;w={protocol:x,id:i,scope:"public",strategy:"static",deps:[],vector:0,body:{type:y,bytes:g.byteLength,version:b}}}else{let b;try{b=We(d.headers)}catch{return}let P=b.artifact;if(b.protocol!==x||!P)return;if(P.id!==i||P.scope!=="public")return;w={protocol:x,id:i,scope:"public",strategy:"static",deps:P.deps,vector:P.version,body:{type:y,bytes:g.byteLength}}}if(await(await G(ce)).put(wt(i),new Response(g,{headers:Ln(d.headers)})),await f.put(w,!0))h.spend(i,{bytes:g.byteLength,requests:0})}function Ct(i,c,d,m){let g=m?.artifact;return(c.strategy==="assembly"||c.strategy==="template")&&c.scope==="public"&&m?.protocol===x&&g?.hash!==void 0&&g.id===i&&g.scope==="public"&&je(t,c)!=="shadow"&&!O.has(i)&&d.status===200&&!d.redirected&&/text\/html/i.test(d.headers.get("content-type")??"")}async function yr(i,c,d,m){if(c.strategy==="template"){let w=Xt(d);if(w===null||await me(w)!==m.hash)return null;let R=de(JSON.parse(w));if(R.id!==i||R.scope!=="public")return null;if(R.strategy!=="template")return null;return{artifact:R,bytes:Ce.encode(w).length}}let g=d.indexOf(t.clientTag),y=g<0?[d]:[d.slice(0,g)+d.slice(g+t.clientTag.length),d];for(let w of y){if(await me(w)!==m.hash)continue;return{artifact:{protocol:x,id:i,scope:"public",strategy:"assembly",deps:[...new Set(m.deps)],vector:m.version,body:{shell:w}},bytes:0}}return null}async function hr(i,c,d,m){let g=m?.artifact;if(!d||!g?.hash||!Ct(i,c,d,m))return;let y=f.epoch;try{let w=await ht(d,yt);if(!w)return;let R=new TextDecoder("utf-8",{fatal:!0}).decode(w),b=await yr(i,c,R,{...g,hash:g.hash});if(!b||await f.get(i)||f.epoch!==y)return;if(await f.put(b.artifact,c.persist))h.spend(i,{bytes:b.bytes,requests:0})}catch{}}async function wr(i,c,d){let m=await _e(c,d,!1);if(m.response)return h.serve(c),m.response;return J(i,!1,{clone:!0,run:(g)=>jt(c,d,g)})}async function br(){try{let c=await(await G(ce)).match(new Request(t.manifest));if(c){t.routes=Ye(Xe(JSON.parse(await c.text())));return}await Nt()}catch{Rt=void 0}}async function Nt(){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=Ye(Xe(JSON.parse(d)));t.routes=m,await(await G(ce)).put(new Request(i),new Response(d,{headers:{"content-type":"application/json"}}));let y=[];for(let w of await f.ids()){let R=await f.get(w);if(R?.artifact.strategy!=="static")continue;let b=q(m,Fn(w));if(!b||R.artifact.body.version!==b.route.version)y.push(w)}return{protocol:x,cursor:f.cursor??0,changed:{},dropped:y,reset:!1}}async function Mt(i){let c=await G(ae),d=!i.headers.has("range");if(d){let g=await c.match(i);if(g)return g}await U();let m=await J(i,!1);if(d&&m.status===200&&Eo(m))W(c.put(i,m.clone()));return m}async function Rr(i,c){if(await U(),!await z.enqueue(i,c))return e.fetch(i);return gn(i)}let ue=t.thirdParty,It=(i)=>new Request(i.url);async function Sr(i){let d=await(await G(he)).match(It(i));if(d)return d;let m=await e.fetch(i);if(m.status===200&&(m.type!=="opaque"||ue?.allowOpaque)){let g=m.type==="opaque"?"immutable":Hn(new URL(i.url),m.headers,ue?.versioned);if(g)W(Bt(i,m.clone(),g))}return m}async function Bt(i,c,d){let m=await G(he),g=c;if(c.type!=="opaque"){let b=new Headers(c.headers);b.set(ie.class,d),b.set(ie.fetched,String(a())),g=new Response(await c.arrayBuffer(),{status:200,headers:b})}await m.put(It(i),g);let y=await m.keys(),w=ue?.maxEntries??64;if(y.length<=w)return;let R=[];for(let b of y){let P=await m.match(b);R.push({key:b,at:Number(P?.headers.get(ie.fetched)??0)})}R.sort((b,P)=>b.at-P.at);for(let{key:b}of R.slice(0,y.length-w))await m.delete(b)}async function vr(){if(!ue)return;let i=await G(he),c=ue.revalidateAfterMs??Po;for(let d of await i.keys()){let m=await i.match(d);if(!m||m.headers.get(ie.class)!=="revalidate")continue;let g=Number(m.headers.get(ie.fetched)??0);if(a()-g<c)continue;try{let y=await e.fetch(new Request(d.url,{cache:"no-cache",mode:"cors",credentials:"omit"}));if(y.status===200&&y.type!=="opaque")await Bt(d,y,"revalidate")}catch{}}}async function Ar(i){await U();let c=pt(t,i,r);if(W(z.flushIfDue()),c.kind==="logout")return await z.sendSameOrigin(mn).catch(()=>{return}),await Be("logout"),J(i,i.mode==="navigate",{signedOut:!0,run:async()=>{return}});if(c.kind==="collector")return Rr(i,c.collector);if(c.kind==="thirdparty")return Sr(i);if(c.kind==="beacon"){if(await z.enqueue(i))return new Response(null,{status:204});return J(i,!1)}if(c.kind==="navigation")return pr(c.path,c.route,i);if(c.kind==="static")return wr(i,c.path,c.route);if(c.kind==="data")return mr(i,c.path,c.route);if(c.kind==="asset")return Mt(i);return J(i,i.mode==="navigate")}return{replica:f,ledger:h,handle(i,c){let d=pt(t,i,r).kind;if(d==="ignore")return;if(d==="asset"&&Ne!=="cache")return;if(Qn&&d!=="navigation"&&d!=="static"&&i.mode!=="navigate")return;return(d==="asset"&&!vt()?Mt(i):Ar(i)).catch(()=>e.fetch(i)).finally(()=>c(Xn()))},async install(i){if(Ne==="static-routing")bt=await Cn(i,t,r)},async activate(){await U();for(let i of await e.caches.keys())if(Ao.some((d)=>i.startsWith(d))&&i!==ae&&i!==ce)await e.caches.delete(i)},async message(i){let c=i??{};if(c.type==="spool:hello")return{type:"spool:hello",protocol:x,version:t.version,compatible:c.protocol===x};if(c.type==="spool:status")return await U(),{type:"spool:status",cursor:f.cursor,syncedAt:f.syncedAt,artifacts:await f.ids(),beacons:(await n.readBeacons()).length};if(c.type==="spool:view"){let d=c.path;return{type:"spool:view",id:typeof d==="string"&&I.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 U();let y=typeof g==="object"&&g!==null&&!Array.isArray(g)?g:void 0;await z.record(un(d,m,a(),y))}return}if(c.type==="spool:graph")return await U(),await f.held(),{type:"spool:graph",records:f.graph.records.ids(),projections:f.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 te();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:Ne,routed:bt};if(c.type==="spool:held"){let d=await G(he);return{type:"spool:held",dropped:Object.fromEntries(z.dropped),third:(await d.keys()).map((m)=>m.url).sort()}}return}}}var ko="static-1",Oo="spool.json";function qn(e){return{protocol:x,version:ko,routes:[],templates:{},beacons:[],clientTag:"",views:!1,manifest:new URL(Oo,e).href}}function Gn(e,t){let n=self,r=Un({config:e,storage:be(),fetch:(o,s)=>fetch(o,s),caches,origin:n.location.origin,renderers:t,partitions:typeof indexedDB>"u"?void 0:qt(),broadcast:(o)=>void n.clients.matchAll({type:"window",includeUncontrolled:!0}).then((s)=>s.forEach((a)=>a.postMessage(o)))});n.addEventListener("install",(o)=>o.waitUntil(Promise.all([n.skipWaiting(),r.install(o)]))),n.addEventListener("activate",(o)=>o.waitUntil(Promise.all([r.activate(),n.clients.claim()]))),n.addEventListener("fetch",(o)=>{let s=r.handle(o.request,(a)=>o.waitUntil(a));if(s)o.respondWith(s)}),n.addEventListener("message",(o)=>{o.waitUntil(r.message(o.data).then((s)=>{if(!s)return;let a=o.ports[0];if(a)a.postMessage(s);else o.source?.postMessage(s)}))})}var zn=self;Gn(zn.__SPOOL_CONFIG__??qn(zn.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;
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Lets a site say which of its own loops spool may pause: a loop pauses while its target is off
|
|
3
|
+
* screen, and while the page has been hidden for `hiddenAfterMs`. The hook never touches
|
|
4
|
+
* `setInterval`, `requestAnimationFrame`, `fetch`, audio, WebRTC or any element the site did not
|
|
5
|
+
* hand over.
|
|
6
|
+
*/
|
|
7
|
+
export function createActivity(host = browserActivityHost()) {
|
|
8
|
+
return {
|
|
9
|
+
/** pauses the loop while its target is off screen or the page is hidden */
|
|
10
|
+
register(controls, options = {}) {
|
|
11
|
+
const hiddenAfterMs = options.hiddenAfterMs ?? 10_000;
|
|
12
|
+
let onScreen = true;
|
|
13
|
+
let hiddenFor = false;
|
|
14
|
+
let paused = false;
|
|
15
|
+
let done = false;
|
|
16
|
+
let warned = false;
|
|
17
|
+
let timer = null;
|
|
18
|
+
const call = (method) => {
|
|
19
|
+
try {
|
|
20
|
+
controls[method]();
|
|
21
|
+
}
|
|
22
|
+
catch (error) {
|
|
23
|
+
if (!warned) {
|
|
24
|
+
warned = true;
|
|
25
|
+
console.warn('spool.activity', error);
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
};
|
|
29
|
+
const sync = () => {
|
|
30
|
+
if (done)
|
|
31
|
+
return;
|
|
32
|
+
const want = !onScreen || hiddenFor;
|
|
33
|
+
if (want === paused)
|
|
34
|
+
return;
|
|
35
|
+
paused = want;
|
|
36
|
+
call(want ? 'pause' : 'resume');
|
|
37
|
+
};
|
|
38
|
+
const clear = () => {
|
|
39
|
+
if (timer === null)
|
|
40
|
+
return;
|
|
41
|
+
host.clearTimeout(timer);
|
|
42
|
+
timer = null;
|
|
43
|
+
};
|
|
44
|
+
const hiddenChanged = () => {
|
|
45
|
+
if (done)
|
|
46
|
+
return;
|
|
47
|
+
if (!host.hidden()) {
|
|
48
|
+
clear();
|
|
49
|
+
hiddenFor = false;
|
|
50
|
+
sync();
|
|
51
|
+
return;
|
|
52
|
+
}
|
|
53
|
+
if (hiddenFor || timer !== null)
|
|
54
|
+
return;
|
|
55
|
+
if (hiddenAfterMs <= 0) {
|
|
56
|
+
hiddenFor = true;
|
|
57
|
+
sync();
|
|
58
|
+
return;
|
|
59
|
+
}
|
|
60
|
+
timer = host.setTimeout(() => {
|
|
61
|
+
timer = null;
|
|
62
|
+
if (host.hidden()) {
|
|
63
|
+
hiddenFor = true;
|
|
64
|
+
sync();
|
|
65
|
+
}
|
|
66
|
+
}, hiddenAfterMs);
|
|
67
|
+
};
|
|
68
|
+
const stopVisibility = host.onVisibilityChange(hiddenChanged);
|
|
69
|
+
const stopObserving = options.target
|
|
70
|
+
? host.observe(options.target, (next) => {
|
|
71
|
+
onScreen = next;
|
|
72
|
+
sync();
|
|
73
|
+
})
|
|
74
|
+
: () => undefined;
|
|
75
|
+
hiddenChanged();
|
|
76
|
+
return () => {
|
|
77
|
+
if (done)
|
|
78
|
+
return;
|
|
79
|
+
done = true;
|
|
80
|
+
clear();
|
|
81
|
+
stopVisibility();
|
|
82
|
+
stopObserving();
|
|
83
|
+
if (paused) {
|
|
84
|
+
paused = false;
|
|
85
|
+
call('resume');
|
|
86
|
+
}
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
export function browserActivityHost() {
|
|
92
|
+
return {
|
|
93
|
+
hidden: () => document.hidden,
|
|
94
|
+
onVisibilityChange(listener) {
|
|
95
|
+
document.addEventListener('visibilitychange', listener);
|
|
96
|
+
return () => document.removeEventListener('visibilitychange', listener);
|
|
97
|
+
},
|
|
98
|
+
observe(target, listener) {
|
|
99
|
+
if (typeof IntersectionObserver === 'undefined') {
|
|
100
|
+
listener(true);
|
|
101
|
+
return () => undefined;
|
|
102
|
+
}
|
|
103
|
+
const observer = new IntersectionObserver((entries) => {
|
|
104
|
+
const entry = entries.at(-1);
|
|
105
|
+
if (entry)
|
|
106
|
+
listener(entry.isIntersecting || entry.intersectionRatio > 0);
|
|
107
|
+
}, { threshold: 0 });
|
|
108
|
+
observer.observe(target);
|
|
109
|
+
return () => observer.disconnect();
|
|
110
|
+
},
|
|
111
|
+
setTimeout: (callback, ms) => setTimeout(callback, ms),
|
|
112
|
+
clearTimeout: (handle) => clearTimeout(handle)
|
|
113
|
+
};
|
|
114
|
+
}
|
package/dist/client/entry.js
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import { CLIENT_TAG_ATTR } from '../protocol/tag.js';
|
|
2
|
+
import { browserActivityHost, createActivity } from './activity.js';
|
|
2
3
|
import { crossOriginLoads, crossOriginOrigins } from './loads.js';
|
|
3
4
|
import { register } from './register.js';
|
|
4
5
|
const ready = register().catch(() => null);
|
|
5
|
-
globalThis.spool = { ready };
|
|
6
|
+
globalThis.spool = { ready, activity: createActivity(browserActivityHost()) };
|
|
6
7
|
void ready.then(async (client) => {
|
|
7
8
|
const id = await client?.view().catch(() => null);
|
|
8
9
|
if (!client || !id)
|
package/dist/client/index.d.ts
CHANGED
package/dist/client/index.js
CHANGED
package/dist/media/embeds.d.ts
CHANGED
|
@@ -19,7 +19,7 @@ export type ResolvedEmbedOptions = {
|
|
|
19
19
|
thumbnail: boolean;
|
|
20
20
|
ignoreCsp: boolean;
|
|
21
21
|
};
|
|
22
|
-
/** what the proxy counted for `embeds`: pages with a rewritten embed, the embeds, and the ones left alone by reason (`csp`, `jsapi`) */
|
|
22
|
+
/** what the proxy counted for `embeds`: pages with a rewritten embed, the embeds, and the ones left alone by reason (`csp`, `jsapi`, `ambient`) */
|
|
23
23
|
export type EmbedStats = {
|
|
24
24
|
pages: number;
|
|
25
25
|
rewritten: number;
|
|
@@ -45,7 +45,8 @@ export declare function facadeDocument(embed: {
|
|
|
45
45
|
* `http` or protocol-relative `src` on a known embed host and path, with an id of 6 to 64 letters,
|
|
46
46
|
* digits, `-` and `_`, is touched. An iframe inside an HTML comment or `<noscript>`, one that has
|
|
47
47
|
* `srcdoc`, and one whose URL sets `enablejsapi=1` (the page's script expects the real player) stay
|
|
48
|
-
* as they are; the last is counted as `jsapi`.
|
|
48
|
+
* as they are; the last is counted as `jsapi`. An embed that plays on its own by design (see
|
|
49
|
+
* `ambient`) stays too and is counted as `ambient`. With `page.csp` set, and no `ignoreCsp`, every
|
|
49
50
|
* matching iframe is left alone and counted as `csp`. The facade keeps `width`, `height`, `title`,
|
|
50
51
|
* `class`, `style`, `allow`, `allowfullscreen`, `loading`, `id`, `sandbox` and `referrerpolicy`.
|
|
51
52
|
* Everything outside the replaced start tags stays byte for byte.
|
package/dist/media/embeds.js
CHANGED
|
@@ -75,13 +75,24 @@ function facadeTag(html, tag, embed, o) {
|
|
|
75
75
|
const doc = escape(facadeDocument(embed, title, o.thumbnail));
|
|
76
76
|
return `<iframe ${[...kept, `srcdoc="${doc}"`].join(' ')}>`;
|
|
77
77
|
}
|
|
78
|
+
const AMBIENT_NAME = /(?:^|[^a-z0-9])(?:hero|ambient|background|banner)(?:[^a-z0-9]|$)/i;
|
|
79
|
+
/** a muted loop or a hero background plays on its own by design, so a click-to-load link would change the page */
|
|
80
|
+
function ambient(tag, url) {
|
|
81
|
+
const on = (name) => url.searchParams.get(name) === '1';
|
|
82
|
+
if (on('background'))
|
|
83
|
+
return true;
|
|
84
|
+
if (on('autoplay') && (on('mute') || on('muted') || on('loop')))
|
|
85
|
+
return true;
|
|
86
|
+
return AMBIENT_NAME.test(`${find(tag, 'class')?.value ?? ''} ${find(tag, 'id')?.value ?? ''}`);
|
|
87
|
+
}
|
|
78
88
|
/**
|
|
79
89
|
* Replaces each server-rendered YouTube or Vimeo `<iframe src>` in `html` with a facade, as
|
|
80
90
|
* `options` allow, and says how many it replaced and how many it left alone. Only an `https`,
|
|
81
91
|
* `http` or protocol-relative `src` on a known embed host and path, with an id of 6 to 64 letters,
|
|
82
92
|
* digits, `-` and `_`, is touched. An iframe inside an HTML comment or `<noscript>`, one that has
|
|
83
93
|
* `srcdoc`, and one whose URL sets `enablejsapi=1` (the page's script expects the real player) stay
|
|
84
|
-
* as they are; the last is counted as `jsapi`.
|
|
94
|
+
* as they are; the last is counted as `jsapi`. An embed that plays on its own by design (see
|
|
95
|
+
* `ambient`) stays too and is counted as `ambient`. With `page.csp` set, and no `ignoreCsp`, every
|
|
85
96
|
* matching iframe is left alone and counted as `csp`. The facade keeps `width`, `height`, `title`,
|
|
86
97
|
* `class`, `style`, `allow`, `allowfullscreen`, `loading`, `id`, `sandbox` and `referrerpolicy`.
|
|
87
98
|
* Everything outside the replaced start tags stays byte for byte.
|
|
@@ -110,6 +121,10 @@ export function rewriteEmbeds(html, options = {}, page = { csp: false }) {
|
|
|
110
121
|
skipped.jsapi = (skipped.jsapi ?? 0) + 1;
|
|
111
122
|
continue;
|
|
112
123
|
}
|
|
124
|
+
if (ambient(tag, embed.url)) {
|
|
125
|
+
skipped.ambient = (skipped.ambient ?? 0) + 1;
|
|
126
|
+
continue;
|
|
127
|
+
}
|
|
113
128
|
if (page.csp && !resolved.ignoreCsp) {
|
|
114
129
|
skipped.csp = (skipped.csp ?? 0) + 1;
|
|
115
130
|
continue;
|
|
@@ -19,6 +19,8 @@ export type EnvelopeArtifact = {
|
|
|
19
19
|
deps: string[];
|
|
20
20
|
/** the vector cursor the artifact reflects */
|
|
21
21
|
version: number;
|
|
22
|
+
/** base64url SHA-256 of the artifact's shell as the page body carries it, minus the client tag */
|
|
23
|
+
hash?: string;
|
|
22
24
|
};
|
|
23
25
|
/** every spool header of a response, decoded; an absent header is an absent field */
|
|
24
26
|
export type Envelope = {
|
|
@@ -14,6 +14,7 @@ export const HEADERS = {
|
|
|
14
14
|
/** `Spool-Clear` token that wipes everything the worker holds */
|
|
15
15
|
export const CLEAR_ALL = '*';
|
|
16
16
|
const PARTITION = /^[A-Za-z0-9_-]{1,128}$/;
|
|
17
|
+
const HASH = /^[A-Za-z0-9_-]{43}$/;
|
|
17
18
|
function bad(message) {
|
|
18
19
|
throw new ProtocolError('bad-header', message);
|
|
19
20
|
}
|
|
@@ -43,12 +44,18 @@ export function encodeEnvelope(envelope) {
|
|
|
43
44
|
};
|
|
44
45
|
const { artifact, invalidate, clear, vector, seen, partition } = envelope;
|
|
45
46
|
if (artifact) {
|
|
46
|
-
|
|
47
|
+
const fields = [
|
|
47
48
|
`id=${encodeURIComponent(artifact.id)}`,
|
|
48
49
|
`scope=${artifact.scope}`,
|
|
49
50
|
`deps=${artifact.deps.map(encodeURIComponent).join(',')}`,
|
|
50
51
|
`v=${artifact.version}`
|
|
51
|
-
]
|
|
52
|
+
];
|
|
53
|
+
if (artifact.hash !== undefined) {
|
|
54
|
+
if (!HASH.test(artifact.hash))
|
|
55
|
+
return bad('hash must be a base64url token');
|
|
56
|
+
fields.push(`h=${artifact.hash}`);
|
|
57
|
+
}
|
|
58
|
+
out[HEADERS.artifact] = fields.join('; ');
|
|
52
59
|
}
|
|
53
60
|
const changed = Object.entries(invalidate ?? {});
|
|
54
61
|
if (changed.length > 0) {
|
|
@@ -130,6 +137,9 @@ export function decodeEnvelope(headers) {
|
|
|
130
137
|
deps: list(fields.get('deps') ?? '').map((d) => decode(d, 'Spool-Artifact deps')),
|
|
131
138
|
version: integer(version, 'Spool-Artifact v')
|
|
132
139
|
};
|
|
140
|
+
const hash = fields.get('h');
|
|
141
|
+
if (hash !== undefined && HASH.test(hash))
|
|
142
|
+
out.artifact.hash = hash;
|
|
133
143
|
}
|
|
134
144
|
const invalidate = headers.get(HEADERS.invalidate);
|
|
135
145
|
if (invalidate !== null) {
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/** why a protocol value was refused */
|
|
2
|
-
export type ProtocolErrorCode = 'bad-pattern' | 'bad-route' | 'bad-header' | 'bad-artifact' | 'bad-sync' | 'bad-beacon' | 'bad-template' | 'bad-manifest';
|
|
2
|
+
export type ProtocolErrorCode = 'bad-pattern' | 'bad-route' | 'bad-header' | 'bad-artifact' | 'bad-sync' | 'bad-beacon' | 'bad-template' | 'bad-manifest' | 'bad-nav';
|
|
3
3
|
/** thrown for malformed protocol input; `code` names the family so callers can map it to a status */
|
|
4
4
|
export declare class ProtocolError extends Error {
|
|
5
5
|
readonly code: ProtocolErrorCode;
|