@drupflare/spool 0.0.0-stage → 0.1.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.
Files changed (182) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1557 -2
  3. package/dist/cdn/client.js +1 -0
  4. package/dist/cdn/location.d.ts +11 -0
  5. package/dist/cdn/location.js +15 -0
  6. package/dist/cdn/manifest.json +16 -0
  7. package/dist/cdn/spool-sw.js +1 -0
  8. package/dist/client/entry.d.ts +1 -0
  9. package/dist/client/entry.js +25 -0
  10. package/dist/client/index.d.ts +3 -0
  11. package/dist/client/index.js +2 -0
  12. package/dist/client/lifecycle.d.ts +10 -0
  13. package/dist/client/lifecycle.js +10 -0
  14. package/dist/client/loads.d.ts +16 -0
  15. package/dist/client/loads.js +41 -0
  16. package/dist/client/register.d.ts +34 -0
  17. package/dist/client/register.js +58 -0
  18. package/dist/index.d.ts +2 -0
  19. package/dist/index.js +2 -0
  20. package/dist/node/listener.d.ts +19 -0
  21. package/dist/node/listener.js +76 -0
  22. package/dist/protocol/artifact.d.ts +54 -0
  23. package/dist/protocol/artifact.js +79 -0
  24. package/dist/protocol/assembly.d.ts +34 -0
  25. package/dist/protocol/assembly.js +72 -0
  26. package/dist/protocol/beacon.d.ts +59 -0
  27. package/dist/protocol/beacon.js +86 -0
  28. package/dist/protocol/collector.d.ts +41 -0
  29. package/dist/protocol/collector.js +84 -0
  30. package/dist/protocol/config.d.ts +89 -0
  31. package/dist/protocol/config.js +13 -0
  32. package/dist/protocol/envelope.d.ts +47 -0
  33. package/dist/protocol/envelope.js +162 -0
  34. package/dist/protocol/errors.d.ts +7 -0
  35. package/dist/protocol/errors.js +9 -0
  36. package/dist/protocol/graph.d.ts +81 -0
  37. package/dist/protocol/graph.js +201 -0
  38. package/dist/protocol/index.d.ts +19 -0
  39. package/dist/protocol/index.js +19 -0
  40. package/dist/protocol/manifest.d.ts +29 -0
  41. package/dist/protocol/manifest.js +94 -0
  42. package/dist/protocol/normalise.d.ts +20 -0
  43. package/dist/protocol/normalise.js +29 -0
  44. package/dist/protocol/pattern.d.ts +12 -0
  45. package/dist/protocol/pattern.js +82 -0
  46. package/dist/protocol/provision.d.ts +100 -0
  47. package/dist/protocol/provision.js +105 -0
  48. package/dist/protocol/route.d.ts +179 -0
  49. package/dist/protocol/route.js +135 -0
  50. package/dist/protocol/sync.d.ts +31 -0
  51. package/dist/protocol/sync.js +87 -0
  52. package/dist/protocol/tag.d.ts +12 -0
  53. package/dist/protocol/tag.js +26 -0
  54. package/dist/protocol/template/compile.d.ts +35 -0
  55. package/dist/protocol/template/compile.js +82 -0
  56. package/dist/protocol/template/interpret.d.ts +9 -0
  57. package/dist/protocol/template/interpret.js +82 -0
  58. package/dist/protocol/vector.d.ts +32 -0
  59. package/dist/protocol/vector.js +56 -0
  60. package/dist/protocol/view.d.ts +110 -0
  61. package/dist/protocol/view.js +201 -0
  62. package/dist/proxy/eligible.d.ts +45 -0
  63. package/dist/proxy/eligible.js +96 -0
  64. package/dist/proxy/index.d.ts +4 -0
  65. package/dist/proxy/index.js +4 -0
  66. package/dist/proxy/proxy.d.ts +86 -0
  67. package/dist/proxy/proxy.js +388 -0
  68. package/dist/proxy/purge.d.ts +10 -0
  69. package/dist/proxy/purge.js +66 -0
  70. package/dist/proxy/tags.d.ts +8 -0
  71. package/dist/proxy/tags.js +36 -0
  72. package/dist/report/derive.d.ts +221 -0
  73. package/dist/report/derive.js +490 -0
  74. package/dist/report/economics.d.ts +14 -0
  75. package/dist/report/economics.js +24 -0
  76. package/dist/report/index.d.ts +8 -0
  77. package/dist/report/index.js +8 -0
  78. package/dist/report/inputs.d.ts +141 -0
  79. package/dist/report/inputs.js +216 -0
  80. package/dist/report/measurement.d.ts +48 -0
  81. package/dist/report/measurement.js +114 -0
  82. package/dist/report/model.d.ts +42 -0
  83. package/dist/report/model.js +74 -0
  84. package/dist/report/thirdparty.d.ts +62 -0
  85. package/dist/report/thirdparty.js +107 -0
  86. package/dist/report/traffic.d.ts +140 -0
  87. package/dist/report/traffic.js +228 -0
  88. package/dist/report/trim.d.ts +81 -0
  89. package/dist/report/trim.js +105 -0
  90. package/dist/server/beacon.d.ts +20 -0
  91. package/dist/server/beacon.js +47 -0
  92. package/dist/server/embedded.d.ts +6 -0
  93. package/dist/server/embedded.js +6 -0
  94. package/dist/server/ga4.d.ts +70 -0
  95. package/dist/server/ga4.js +165 -0
  96. package/dist/server/identity.d.ts +12 -0
  97. package/dist/server/identity.js +17 -0
  98. package/dist/server/index.d.ts +7 -0
  99. package/dist/server/index.js +7 -0
  100. package/dist/server/sink.d.ts +56 -0
  101. package/dist/server/sink.js +133 -0
  102. package/dist/server/size.d.ts +7 -0
  103. package/dist/server/size.js +18 -0
  104. package/dist/server/spool.d.ts +97 -0
  105. package/dist/server/spool.js +463 -0
  106. package/dist/server/stub.d.ts +9 -0
  107. package/dist/server/stub.js +19 -0
  108. package/dist/server/sync.d.ts +12 -0
  109. package/dist/server/sync.js +48 -0
  110. package/dist/server/work.d.ts +22 -0
  111. package/dist/server/work.js +30 -0
  112. package/dist/stores/durable-object.d.ts +19 -0
  113. package/dist/stores/durable-object.js +53 -0
  114. package/dist/stores/index.d.ts +2 -0
  115. package/dist/stores/index.js +2 -0
  116. package/dist/stores/memory.d.ts +4 -0
  117. package/dist/stores/memory.js +10 -0
  118. package/dist/stores/version-store.d.ts +11 -0
  119. package/dist/stores/version-store.js +1 -0
  120. package/dist/sw/analytics.d.ts +81 -0
  121. package/dist/sw/analytics.js +275 -0
  122. package/dist/sw/collect.d.ts +8 -0
  123. package/dist/sw/collect.js +33 -0
  124. package/dist/sw/core.d.ts +1 -0
  125. package/dist/sw/core.js +3 -0
  126. package/dist/sw/freshness.d.ts +15 -0
  127. package/dist/sw/freshness.js +20 -0
  128. package/dist/sw/graph/index.d.ts +67 -0
  129. package/dist/sw/graph/index.js +170 -0
  130. package/dist/sw/graph/invalidate.d.ts +23 -0
  131. package/dist/sw/graph/invalidate.js +109 -0
  132. package/dist/sw/graph/projections.d.ts +7 -0
  133. package/dist/sw/graph/projections.js +9 -0
  134. package/dist/sw/graph/records.d.ts +7 -0
  135. package/dist/sw/graph/records.js +9 -0
  136. package/dist/sw/graph/store.d.ts +32 -0
  137. package/dist/sw/graph/store.js +52 -0
  138. package/dist/sw/idb.d.ts +8 -0
  139. package/dist/sw/idb.js +117 -0
  140. package/dist/sw/index.d.ts +2 -0
  141. package/dist/sw/index.js +1 -0
  142. package/dist/sw/partition.d.ts +21 -0
  143. package/dist/sw/partition.js +137 -0
  144. package/dist/sw/policy.d.ts +8 -0
  145. package/dist/sw/policy.js +24 -0
  146. package/dist/sw/provision.d.ts +39 -0
  147. package/dist/sw/provision.js +61 -0
  148. package/dist/sw/render.d.ts +21 -0
  149. package/dist/sw/render.js +53 -0
  150. package/dist/sw/replica.d.ts +77 -0
  151. package/dist/sw/replica.js +299 -0
  152. package/dist/sw/router.d.ts +42 -0
  153. package/dist/sw/router.js +48 -0
  154. package/dist/sw/routing.d.ts +23 -0
  155. package/dist/sw/routing.js +48 -0
  156. package/dist/sw/runtime.d.ts +112 -0
  157. package/dist/sw/runtime.js +1070 -0
  158. package/dist/sw/scheduler.d.ts +83 -0
  159. package/dist/sw/scheduler.js +149 -0
  160. package/dist/sw/seal.d.ts +37 -0
  161. package/dist/sw/seal.js +183 -0
  162. package/dist/sw/serve.d.ts +15 -0
  163. package/dist/sw/serve.js +63 -0
  164. package/dist/sw/shadow.d.ts +16 -0
  165. package/dist/sw/shadow.js +27 -0
  166. package/dist/sw/static.d.ts +17 -0
  167. package/dist/sw/static.js +81 -0
  168. package/dist/sw/storage.d.ts +64 -0
  169. package/dist/sw/storage.js +34 -0
  170. package/dist/sw/thirdparty.d.ts +17 -0
  171. package/dist/sw/thirdparty.js +36 -0
  172. package/dist/trim/css.d.ts +38 -0
  173. package/dist/trim/css.js +328 -0
  174. package/dist/trim/index.d.ts +3 -0
  175. package/dist/trim/index.js +3 -0
  176. package/dist/trim/manifest.d.ts +67 -0
  177. package/dist/trim/manifest.js +134 -0
  178. package/dist/trim/tokens.d.ts +43 -0
  179. package/dist/trim/tokens.js +142 -0
  180. package/dist/version.d.ts +2 -0
  181. package/dist/version.js +3 -0
  182. package/package.json +146 -5
@@ -0,0 +1 @@
1
+ (()=>{var p="data-spool-client";function d(t,o,n=[]){let s=0;for(let{name:r}of t){if(n.includes(r))continue;try{if(new URL(r).origin!==o)s+=1}catch{continue}}return s}function u(t,o,n=[],s=32){let r=new Map;for(let{name:i}of t){if(n.includes(i))continue;try{let e=new URL(i).origin;if(e!==o&&e!=="null")r.set(e,(r.get(e)??0)+1)}catch{continue}}return Object.fromEntries([...r].sort((i,e)=>e[1]-i[1]||(i[0]<e[0]?-1:1)).slice(0,s))}var f=1;var l={sync:"/.spool/sync",artifact:"/.spool/artifact",beacon:"/.spool/beacon",worker:"/spool-sw.js"};function g(t,o=window){let n=()=>t.close();return o.addEventListener("pagehide",n),()=>o.removeEventListener("pagehide",n)}function a(t,o,n){return new Promise((s,r)=>{let i=new MessageChannel,e=setTimeout(()=>{i.port1.close(),r(Error("the worker did not answer"))},n);i.port1.onmessage=(c)=>{clearTimeout(e),i.port1.close(),s(c.data)},t.postMessage(o,[i.port2])})}async function y(t={}){let o=t.container??navigator.serviceWorker;if(!o)return null;let n=t.helloTimeoutMs??5000;o.addEventListener?.("message",(e)=>{let c=e.data;if(c?.type!=="spool:cleared")return;(t.target??window).dispatchEvent(new CustomEvent("spool:cleared",{detail:{reason:c.reason}}))}),await o.register(t.workerUrl??l.worker,{scope:t.scope,updateViaCache:"all"});let s=await o.ready,r=s.active;if(!r)throw Error("the worker is not active");let i=await a(r,{type:"spool:hello",protocol:f},n);return{registration:s,hello:i,status:()=>a(s.active??r,{type:"spool:status"},n),view:async(e=location.pathname)=>(await a(s.active??r,{type:"spool:view",path:e},n)).id,reportLoads:(e,c,b)=>(s.active??r).postMessage({type:"spool:loads",view:e,count:c,origins:b}),track:(e)=>g(e)}}var m=y().catch(()=>null);globalThis.spool={ready:m};m.then(async(t)=>{let o=await t?.view().catch(()=>null);if(!t||!o)return;let n=-1,s=()=>{let r=document.querySelector(`script[${p}]`)?.src,i=performance.getEntriesByType("resource"),e=d(i,location.origin,r?[r]:[]);if(e===n)return;n=e,t.reportLoads(o,e,u(i,location.origin,r?[r]:[]))};addEventListener("pagehide",s),document.addEventListener("visibilitychange",()=>{if(document.visibilityState==="hidden")s()})});})();
@@ -0,0 +1,11 @@
1
+ /** the host in front of the `drupflare-cdn` bucket */
2
+ export declare const CDN_ORIGIN = "https://cdn.drupflare.com";
3
+ /** the key prefix under which every spool build is published */
4
+ export declare const CDN_PREFIX = "spool";
5
+ /** the bucket prefix of one release; its keys are never overwritten */
6
+ export declare function releasePrefix(version: string): string;
7
+ /**
8
+ * The URL a release's page runtime is served from. `createSpool` puts it in the script tag when
9
+ * `cdn` names only an integrity hash, so the tag, the bucket key and `build:cdn` share one path.
10
+ */
11
+ export declare function cdnClientUrl(version: string): string;
@@ -0,0 +1,15 @@
1
+ /** the host in front of the `drupflare-cdn` bucket */
2
+ export const CDN_ORIGIN = 'https://cdn.drupflare.com';
3
+ /** the key prefix under which every spool build is published */
4
+ export const CDN_PREFIX = 'spool';
5
+ /** the bucket prefix of one release; its keys are never overwritten */
6
+ export function releasePrefix(version) {
7
+ return `${CDN_PREFIX}/${encodeURIComponent(version)}`;
8
+ }
9
+ /**
10
+ * The URL a release's page runtime is served from. `createSpool` puts it in the script tag when
11
+ * `cdn` names only an integrity hash, so the tag, the bucket key and `build:cdn` share one path.
12
+ */
13
+ export function cdnClientUrl(version) {
14
+ return `${CDN_ORIGIN}/${releasePrefix(version)}/client.js`;
15
+ }
@@ -0,0 +1,16 @@
1
+ {
2
+ "schema": 2,
3
+ "version": "0.1.0",
4
+ "files": {
5
+ "client.js": {
6
+ "bytes": 2155,
7
+ "sha384": "0baa3c240fdec865d1b53a00e5db1f7d456ec910f12c11ea9b8ac356df108ca88a77e0bb4eb955a88bbcaa53fd32d04e",
8
+ "integrity": "sha384-C6o8JA/eyGXRtToA5dsffUVuyRDxLBHqm4rDVt8QjKiKd+C7TrlVqIu8qlP9MtBO"
9
+ },
10
+ "spool-sw.js": {
11
+ "bytes": 60560,
12
+ "sha384": "3adadb58e469f2c975ca67c755721d46af092bd9487fe9d673ce7e3a4a083153b955348822ed516c7c047fe80ac85c35",
13
+ "integrity": "sha384-OtrbWORp8sl1ymfHVXIdRq8JK9lIf+nWc85+OkoIMVO5VTSIIu1RbHwEf+gKyFw1"
14
+ }
15
+ }
16
+ }
@@ -0,0 +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={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"};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));})();
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,25 @@
1
+ import { CLIENT_TAG_ATTR } from '../protocol/tag.js';
2
+ import { crossOriginLoads, crossOriginOrigins } from './loads.js';
3
+ import { register } from './register.js';
4
+ const ready = register().catch(() => null);
5
+ globalThis.spool = { ready };
6
+ void ready.then(async (client) => {
7
+ const id = await client?.view().catch(() => null);
8
+ if (!client || !id)
9
+ return;
10
+ let last = -1;
11
+ const report = () => {
12
+ const own = document.querySelector(`script[${CLIENT_TAG_ATTR}]`)?.src;
13
+ const entries = performance.getEntriesByType('resource');
14
+ const count = crossOriginLoads(entries, location.origin, own ? [own] : []);
15
+ if (count === last)
16
+ return;
17
+ last = count;
18
+ client.reportLoads(id, count, crossOriginOrigins(entries, location.origin, own ? [own] : []));
19
+ };
20
+ addEventListener('pagehide', report);
21
+ document.addEventListener('visibilitychange', () => {
22
+ if (document.visibilityState === 'hidden')
23
+ report();
24
+ });
25
+ });
@@ -0,0 +1,3 @@
1
+ export type { Hello, Status } from '../sw/runtime.js';
2
+ export * from './lifecycle.js';
3
+ export * from './register.js';
@@ -0,0 +1,2 @@
1
+ export * from './lifecycle.js';
2
+ export * from './register.js';
@@ -0,0 +1,10 @@
1
+ /** anything with a `close()`, such as an `IDBDatabase` */
2
+ export type Closable = {
3
+ close(): void;
4
+ };
5
+ /**
6
+ * Closes `db` when the page is hidden. An open IndexedDB connection keeps a page out of the
7
+ * back/forward cache, so the page reopens it on the next use. Returns a function that removes
8
+ * the listener.
9
+ */
10
+ export declare function closeOnPageHide(db: Closable, target?: Pick<EventTarget, 'addEventListener' | 'removeEventListener'>): () => void;
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Closes `db` when the page is hidden. An open IndexedDB connection keeps a page out of the
3
+ * back/forward cache, so the page reopens it on the next use. Returns a function that removes
4
+ * the listener.
5
+ */
6
+ export function closeOnPageHide(db, target = window) {
7
+ const close = () => db.close();
8
+ target.addEventListener('pagehide', close);
9
+ return () => target.removeEventListener('pagehide', close);
10
+ }
@@ -0,0 +1,16 @@
1
+ /** the part of a `PerformanceResourceTiming` entry that counting needs */
2
+ export type ResourceEntry = {
3
+ name: string;
4
+ };
5
+ /**
6
+ * How many entries name a resource on another origin than `origin`, leaving out `ignore` (the
7
+ * page runtime's own script, which a CDN may serve). It cannot tell a cache hit from a network
8
+ * request, since a cross-origin entry without `Timing-Allow-Origin` reports no transfer size, so
9
+ * the count is an upper bound on cross-origin network requests. An entry whose name is not a URL is skipped.
10
+ */
11
+ export declare function crossOriginLoads(entries: readonly ResourceEntry[], origin: string, ignore?: readonly string[]): number;
12
+ /**
13
+ * How many entries name a resource on each other origin, busiest first and cut to `limit`, again
14
+ * leaving out `ignore`. Origins only: no path or query string is kept.
15
+ */
16
+ export declare function crossOriginOrigins(entries: readonly ResourceEntry[], origin: string, ignore?: readonly string[], limit?: number): Record<string, number>;
@@ -0,0 +1,41 @@
1
+ /**
2
+ * How many entries name a resource on another origin than `origin`, leaving out `ignore` (the
3
+ * page runtime's own script, which a CDN may serve). It cannot tell a cache hit from a network
4
+ * request, since a cross-origin entry without `Timing-Allow-Origin` reports no transfer size, so
5
+ * the count is an upper bound on cross-origin network requests. An entry whose name is not a URL is skipped.
6
+ */
7
+ export function crossOriginLoads(entries, origin, ignore = []) {
8
+ let count = 0;
9
+ for (const { name } of entries) {
10
+ if (ignore.includes(name))
11
+ continue;
12
+ try {
13
+ if (new URL(name).origin !== origin)
14
+ count += 1;
15
+ }
16
+ catch {
17
+ continue;
18
+ }
19
+ }
20
+ return count;
21
+ }
22
+ /**
23
+ * How many entries name a resource on each other origin, busiest first and cut to `limit`, again
24
+ * leaving out `ignore`. Origins only: no path or query string is kept.
25
+ */
26
+ export function crossOriginOrigins(entries, origin, ignore = [], limit = 32) {
27
+ const counts = new Map();
28
+ for (const { name } of entries) {
29
+ if (ignore.includes(name))
30
+ continue;
31
+ try {
32
+ const other = new URL(name).origin;
33
+ if (other !== origin && other !== 'null')
34
+ counts.set(other, (counts.get(other) ?? 0) + 1);
35
+ }
36
+ catch {
37
+ continue;
38
+ }
39
+ }
40
+ return Object.fromEntries([...counts].sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : 1)).slice(0, limit));
41
+ }
@@ -0,0 +1,34 @@
1
+ import type { Hello, Status } from '../sw/runtime.js';
2
+ import { type Closable } from './lifecycle.js';
3
+ /** what `register` takes */
4
+ export type RegisterOptions = {
5
+ /** the worker script; default `/spool-sw.js` */
6
+ workerUrl?: string;
7
+ scope?: string;
8
+ /** how long to wait for the worker's answer to the handshake; default 5000 */
9
+ helloTimeoutMs?: number;
10
+ /** the container to register on; default `navigator.serviceWorker` */
11
+ container?: ServiceWorkerContainer;
12
+ /** where `spool:cleared` is dispatched; default `window` */
13
+ target?: Pick<EventTarget, 'dispatchEvent'>;
14
+ };
15
+ /** the page's handle on the worker */
16
+ export type SpoolClient = {
17
+ registration: ServiceWorkerRegistration;
18
+ /** the version handshake; `compatible` is false when the worker speaks another protocol */
19
+ hello: Hello;
20
+ /** asks the worker what it holds */
21
+ status(): Promise<Status>;
22
+ /** the id of this page's view, which the worker made when it handled the navigation; null if it made none */
23
+ view(path?: string): Promise<string | null>;
24
+ /** tells the worker how many cross-origin resources the page loaded, for view `id`, and from which origins */
25
+ reportLoads(id: string, count: number, origins?: Record<string, number>): void;
26
+ /** closes `db` when the page is hidden, so the page stays eligible for the back/forward cache */
27
+ track(db: Closable): () => void;
28
+ };
29
+ /**
30
+ * Registers the worker with `updateViaCache: 'all'`, so a controlled navigation skips the script
31
+ * update check inside the script's one-day cache lifetime, then runs the version handshake.
32
+ * Resolves to `null` where service workers do not exist; the page then works as it always did.
33
+ */
34
+ export declare function register(options?: RegisterOptions): Promise<SpoolClient | null>;
@@ -0,0 +1,58 @@
1
+ import { PROTOCOL_VERSION } from '../protocol/artifact.js';
2
+ import { PATHS } from '../protocol/config.js';
3
+ import { closeOnPageHide } from './lifecycle.js';
4
+ function ask(worker, message, timeoutMs) {
5
+ return new Promise((resolve, reject) => {
6
+ const channel = new MessageChannel();
7
+ const timer = setTimeout(() => {
8
+ channel.port1.close();
9
+ reject(new Error('the worker did not answer'));
10
+ }, timeoutMs);
11
+ channel.port1.onmessage = (event) => {
12
+ clearTimeout(timer);
13
+ channel.port1.close();
14
+ resolve(event.data);
15
+ };
16
+ worker.postMessage(message, [channel.port2]);
17
+ });
18
+ }
19
+ /**
20
+ * Registers the worker with `updateViaCache: 'all'`, so a controlled navigation skips the script
21
+ * update check inside the script's one-day cache lifetime, then runs the version handshake.
22
+ * Resolves to `null` where service workers do not exist; the page then works as it always did.
23
+ */
24
+ export async function register(options = {}) {
25
+ const container = options.container ?? navigator.serviceWorker;
26
+ if (!container)
27
+ return null;
28
+ const timeout = options.helloTimeoutMs ?? 5000;
29
+ // the worker tells every page when it wipes the principal store, so a page can blank what it shows
30
+ container.addEventListener?.('message', (event) => {
31
+ const data = event.data;
32
+ if (data?.type !== 'spool:cleared')
33
+ return;
34
+ (options.target ?? window).dispatchEvent(new CustomEvent('spool:cleared', { detail: { reason: data.reason } }));
35
+ });
36
+ await container.register(options.workerUrl ?? PATHS.worker, {
37
+ scope: options.scope,
38
+ updateViaCache: 'all'
39
+ });
40
+ const registration = await container.ready;
41
+ const worker = registration.active;
42
+ if (!worker)
43
+ throw new Error('the worker is not active');
44
+ const hello = await ask(worker, { type: 'spool:hello', protocol: PROTOCOL_VERSION }, timeout);
45
+ return {
46
+ registration,
47
+ hello,
48
+ status: () => ask(registration.active ?? worker, { type: 'spool:status' }, timeout),
49
+ view: async (path = location.pathname) => (await ask(registration.active ?? worker, { type: 'spool:view', path }, timeout)).id,
50
+ reportLoads: (id, count, origins) => (registration.active ?? worker).postMessage({
51
+ type: 'spool:loads',
52
+ view: id,
53
+ count,
54
+ origins
55
+ }),
56
+ track: (db) => closeOnPageHide(db)
57
+ };
58
+ }
@@ -0,0 +1,2 @@
1
+ export * from './protocol/index.js';
2
+ export * from './report/index.js';
package/dist/index.js ADDED
@@ -0,0 +1,2 @@
1
+ export * from './protocol/index.js';
2
+ export * from './report/index.js';
@@ -0,0 +1,19 @@
1
+ import type { IncomingMessage, ServerResponse } from 'node:http';
2
+ /** a Fetch-style handler; return `undefined` to hand the request to the next Node middleware */
3
+ export type FetchHandler = (request: Request) => Response | undefined | Promise<Response | undefined>;
4
+ /** options for {@link toNodeListener} */
5
+ export type NodeListenerOptions = {
6
+ /** the origin to build request URLs from, such as `https://example.edu`; default is the Host header */
7
+ origin?: string;
8
+ };
9
+ /** the Fetch `Request` for a Node request */
10
+ export declare function toRequest(req: IncomingMessage, res: ServerResponse, options?: NodeListenerOptions): Request;
11
+ /** writes a Fetch `Response` to a Node response, streaming the body */
12
+ export declare function writeResponse(res: ServerResponse, response: Response, head?: boolean): Promise<void>;
13
+ /**
14
+ * Bridges `node:http` to a Fetch handler, with no dependency. The result is also an Express
15
+ * middleware: when the handler returns `undefined` and a `next` callback exists it is called,
16
+ * otherwise the reply is a 404. A handler that throws gets a 500 (or the socket is destroyed if
17
+ * headers are already out).
18
+ */
19
+ export declare function toNodeListener(handler: FetchHandler, options?: NodeListenerOptions): (req: IncomingMessage, res: ServerResponse, next?: (error?: unknown) => void) => Promise<void>;
@@ -0,0 +1,76 @@
1
+ import { Readable } from 'node:stream';
2
+ import { pipeline } from 'node:stream/promises';
3
+ /** the Fetch `Request` for a Node request */
4
+ export function toRequest(req, res, options = {}) {
5
+ const encrypted = req.socket.encrypted === true;
6
+ const origin = options.origin ?? `${encrypted ? 'https' : 'http'}://${req.headers.host ?? 'localhost'}`;
7
+ const headers = new Headers();
8
+ for (const [name, value] of Object.entries(req.headers)) {
9
+ if (value === undefined)
10
+ continue;
11
+ for (const v of Array.isArray(value) ? value : [value])
12
+ headers.append(name, v);
13
+ }
14
+ const controller = new AbortController();
15
+ res.once('close', () => {
16
+ if (!res.writableFinished)
17
+ controller.abort();
18
+ });
19
+ const body = req.method === 'GET' || req.method === 'HEAD' ? undefined : Readable.toWeb(req);
20
+ return new Request(new URL(req.url ?? '/', origin), {
21
+ method: req.method,
22
+ headers,
23
+ signal: controller.signal,
24
+ ...(body ? { body: body, duplex: 'half' } : {})
25
+ });
26
+ }
27
+ /** writes a Fetch `Response` to a Node response, streaming the body */
28
+ export async function writeResponse(res, response, head = false) {
29
+ res.statusCode = response.status;
30
+ if (response.statusText)
31
+ res.statusMessage = response.statusText;
32
+ for (const [name, value] of response.headers) {
33
+ if (name !== 'set-cookie')
34
+ res.setHeader(name, value);
35
+ }
36
+ const cookies = response.headers.getSetCookie();
37
+ if (cookies.length > 0)
38
+ res.setHeader('set-cookie', cookies);
39
+ if (head || !response.body) {
40
+ res.end();
41
+ return;
42
+ }
43
+ await pipeline(Readable.fromWeb(response.body), res);
44
+ }
45
+ /**
46
+ * Bridges `node:http` to a Fetch handler, with no dependency. The result is also an Express
47
+ * middleware: when the handler returns `undefined` and a `next` callback exists it is called,
48
+ * otherwise the reply is a 404. A handler that throws gets a 500 (or the socket is destroyed if
49
+ * headers are already out).
50
+ */
51
+ export function toNodeListener(handler, options = {}) {
52
+ return async (req, res, next) => {
53
+ try {
54
+ const response = await handler(toRequest(req, res, options));
55
+ if (!response) {
56
+ if (next)
57
+ return next();
58
+ res.statusCode = 404;
59
+ res.end();
60
+ return;
61
+ }
62
+ await writeResponse(res, response, req.method === 'HEAD');
63
+ }
64
+ catch (error) {
65
+ if (res.headersSent) {
66
+ res.destroy(error instanceof Error ? error : undefined);
67
+ return;
68
+ }
69
+ if (next)
70
+ return next(error);
71
+ res.statusCode = 500;
72
+ res.setHeader('content-type', 'text/plain');
73
+ res.end('internal error');
74
+ }
75
+ };
76
+ }
@@ -0,0 +1,54 @@
1
+ import { type ProjectionEntry, type RecordEntry, type Ref } from './graph.js';
2
+ /** protocol version both halves speak; a response with another value is ignored by the worker */
3
+ export declare const PROTOCOL_VERSION = 1;
4
+ /** markup or a value, or a reference the replica resolves to one when the page renders */
5
+ export type Text = string | Ref;
6
+ /** a shell with named holes, the fragments that fill them and named values for the rest */
7
+ export type AssemblyBody = {
8
+ shell: string;
9
+ fragments?: Record<string, Text>;
10
+ slots?: Record<string, Text>;
11
+ };
12
+ /** the JSON a template renders against; the template itself ships in the worker config */
13
+ export type TemplateBody = {
14
+ data: unknown;
15
+ };
16
+ /**
17
+ * What a stored static file is. The bytes live in the worker's Cache, keyed by the artifact's id;
18
+ * `version` is the manifest's label for them, absent when the server's version vector tracks the file.
19
+ */
20
+ export type StaticBody = {
21
+ type: string;
22
+ bytes: number;
23
+ version?: string;
24
+ };
25
+ /** who may be served an artifact from the replica */
26
+ export type Scope = 'public' | 'principal';
27
+ /** the fields every artifact carries, whatever its body */
28
+ export type ArtifactBase = {
29
+ protocol: typeof PROTOCOL_VERSION;
30
+ /** the request path the artifact answers */
31
+ id: string;
32
+ scope: Scope;
33
+ /** tags the artifact was built from; a change to any of them invalidates it */
34
+ deps: string[];
35
+ /** the version vector cursor read before the artifact was built */
36
+ vector: number;
37
+ /** records this artifact references that the worker did not already hold */
38
+ records?: RecordEntry[];
39
+ /** projections this artifact references that the worker did not already hold */
40
+ projections?: ProjectionEntry[];
41
+ };
42
+ /** one authorised, versioned dependency set and what to render it with */
43
+ export type Artifact = ArtifactBase & ({
44
+ strategy: 'assembly';
45
+ body: AssemblyBody;
46
+ } | {
47
+ strategy: 'template' | 'projection' | 'data';
48
+ body: TemplateBody;
49
+ } | {
50
+ strategy: 'static';
51
+ body: StaticBody;
52
+ });
53
+ /** validates JSON from `/.spool/artifact`; the worker calls this before it stores anything */
54
+ export declare function parseArtifact(value: unknown): Artifact;