gemi 0.234.0 → 0.236.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 (59) hide show
  1. package/dist/ai/Agent.d.ts.map +1 -1
  2. package/dist/ai/AgentProvider.d.ts +33 -0
  3. package/dist/ai/AgentProvider.d.ts.map +1 -1
  4. package/dist/ai/FallbackProvider.d.ts.map +1 -1
  5. package/dist/ai/client/conformance.d.ts +4 -2
  6. package/dist/ai/client/conformance.d.ts.map +1 -1
  7. package/dist/ai/client/index.js +72 -6
  8. package/dist/ai/client/index.js.map +1 -1
  9. package/dist/ai/client/reducer.d.ts.map +1 -1
  10. package/dist/ai/generate.d.ts.map +1 -1
  11. package/dist/ai/index.js +42 -42
  12. package/dist/ai/index.js.map +4 -4
  13. package/dist/ai/providers/anthropicStream.d.ts.map +1 -1
  14. package/dist/ai/providers/call.d.ts +1 -1
  15. package/dist/ai/providers/call.d.ts.map +1 -1
  16. package/dist/ai/testing/index.js +1 -1
  17. package/dist/ai/types.d.ts +5 -0
  18. package/dist/ai/types.d.ts.map +1 -1
  19. package/dist/ai/usageMeter.d.ts +10 -0
  20. package/dist/ai/usageMeter.d.ts.map +1 -1
  21. package/dist/ai/useChat.d.ts +35 -0
  22. package/dist/ai/useChat.d.ts.map +1 -1
  23. package/dist/{chunk-n84v63hn.js → chunk-3nhgh3qx.js} +1 -1
  24. package/dist/{chunk-n84v63hn.js.map → chunk-3nhgh3qx.js.map} +1 -1
  25. package/dist/chunk-4800w7qx.js +12 -0
  26. package/dist/{chunk-w225pkpp.js.map → chunk-4800w7qx.js.map} +6 -6
  27. package/dist/{chunk-t929a66m.js → chunk-7rxj3x6v.js} +2 -2
  28. package/dist/{chunk-t929a66m.js.map → chunk-7rxj3x6v.js.map} +1 -1
  29. package/dist/chunk-dav7mv8t.js +48 -0
  30. package/dist/chunk-dav7mv8t.js.map +26 -0
  31. package/dist/{chunk-69xg5wgz.js → chunk-eca9n9cz.js} +1 -1
  32. package/dist/{chunk-69xg5wgz.js.map → chunk-eca9n9cz.js.map} +1 -1
  33. package/dist/{chunk-m2f4n0mq.js → chunk-vbdtbcrn.js} +1 -1
  34. package/dist/chunks/{RealtimeClient-C5Zh3fD6.js → RealtimeClient-DRVodyn1.js} +2 -2
  35. package/dist/chunks/{RealtimeClient-C5Zh3fD6.js.map → RealtimeClient-DRVodyn1.js.map} +1 -1
  36. package/dist/chunks/{ThemeProvider-bbbE-N3t.js → ThemeProvider-1WtAS7dH.js} +4 -4
  37. package/dist/chunks/{ThemeProvider-bbbE-N3t.js.map → ThemeProvider-1WtAS7dH.js.map} +1 -1
  38. package/dist/chunks/{fetchFileRequest-JXhnEi-R.js → fetchFileRequest-CVCelZqS.js} +2 -2
  39. package/dist/chunks/{fetchFileRequest-JXhnEi-R.js.map → fetchFileRequest-CVCelZqS.js.map} +1 -1
  40. package/dist/chunks/{live-CApTRvmK.js → live-twEh9Qwt.js} +3 -3
  41. package/dist/chunks/{live-CApTRvmK.js.map → live-twEh9Qwt.js.map} +1 -1
  42. package/dist/chunks/{mutationExtras-C2qSSZ2Q.js → mutationExtras-CM77Ur-9.js} +2 -2
  43. package/dist/chunks/{mutationExtras-C2qSSZ2Q.js.map → mutationExtras-CM77Ur-9.js.map} +1 -1
  44. package/dist/chunks/{subscriptionStream-DQLW7dTW.js → subscriptionStream-DQp1Krwi.js} +2 -2
  45. package/dist/chunks/{subscriptionStream-DQLW7dTW.js.map → subscriptionStream-DQp1Krwi.js.map} +1 -1
  46. package/dist/client/chunkLoadRecovery.d.ts +1 -1
  47. package/dist/client/index.js +4 -4
  48. package/dist/client/index.js.map +1 -1
  49. package/dist/kernel/index.js +1 -1
  50. package/dist/orm/index.js.map +1 -1
  51. package/dist/server/index.js +1 -1
  52. package/dist/services/index.js +1 -1
  53. package/dist/services/mcp/http/callers.d.ts +1 -1
  54. package/dist/testing/index.js +2 -2
  55. package/package.json +1 -1
  56. package/dist/chunk-w225pkpp.js +0 -12
  57. package/dist/chunk-xtpx3f5t.js +0 -48
  58. package/dist/chunk-xtpx3f5t.js.map +0 -26
  59. /package/dist/{chunk-m2f4n0mq.js.map → chunk-vbdtbcrn.js.map} +0 -0
@@ -1 +1 @@
1
- {"version":3,"file":"anthropicStream.d.ts","sourceRoot":"","sources":["../../../ai/providers/anthropicStream.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AACtD,OAAO,KAAK,EAAE,UAAU,EAAgB,KAAK,EAAE,MAAM,UAAU,CAAC;AAIhE;;;;;;;;;;;;;;;;;GAiBG;AAEH,KAAK,YAAY,GAAG;IAClB,4EAA4E;IAC5E,gBAAgB,CAAC,EAAE,OAAO,CAAC;IAC3B;;;;OAIG;IACH,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,CAAC;CAClC,CAAC;AAIF,wBAAuB,mBAAmB,CACxC,MAAM,EAAE,aAAa,CAAC,MAAM,CAAC,GAAG,QAAQ,CAAC,MAAM,CAAC,EAChD,OAAO,GAAE,YAAiB,GACzB,cAAc,CAAC,aAAa,CAAC,CA4K/B;AAyCD;;;;;GAKG;AACH,wBAAgB,oBAAoB,CAAC,GAAG,EAAE,GAAG,GAAG,UAAU,CAqBzD;AAED,KAAK,QAAQ,GAAG;IACd,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,2BAA2B,CAAC,EAAE,MAAM,CAAC;IACrC,uBAAuB,CAAC,EAAE,MAAM,CAAC;IACjC,6EAA6E;IAC7E,eAAe,CAAC,EAAE,MAAM,CAAC;CAC1B,CAAC;AAmBF;;;;;;;;;;GAUG;AACH,wBAAgB,gBAAgB,CAAC,GAAG,EAAE,QAAQ,GAAG,SAAS,GAAG,KAAK,CAWjE"}
1
+ {"version":3,"file":"anthropicStream.d.ts","sourceRoot":"","sources":["../../../ai/providers/anthropicStream.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AACtD,OAAO,KAAK,EAAE,UAAU,EAAgB,KAAK,EAAE,MAAM,UAAU,CAAC;AAIhE;;;;;;;;;;;;;;;;;GAiBG;AAEH,KAAK,YAAY,GAAG;IAClB,4EAA4E;IAC5E,gBAAgB,CAAC,EAAE,OAAO,CAAC;IAC3B;;;;OAIG;IACH,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,CAAC;CAClC,CAAC;AAIF,wBAAuB,mBAAmB,CACxC,MAAM,EAAE,aAAa,CAAC,MAAM,CAAC,GAAG,QAAQ,CAAC,MAAM,CAAC,EAChD,OAAO,GAAE,YAAiB,GACzB,cAAc,CAAC,aAAa,CAAC,CA8K/B;AAyCD;;;;;GAKG;AACH,wBAAgB,oBAAoB,CAAC,GAAG,EAAE,GAAG,GAAG,UAAU,CAqBzD;AAED,KAAK,QAAQ,GAAG;IACd,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,2BAA2B,CAAC,EAAE,MAAM,CAAC;IACrC,uBAAuB,CAAC,EAAE,MAAM,CAAC;IACjC,6EAA6E;IAC7E,eAAe,CAAC,EAAE,MAAM,CAAC;CAC1B,CAAC;AAmBF;;;;;;;;;;GAUG;AACH,wBAAgB,gBAAgB,CAAC,GAAG,EAAE,QAAQ,GAAG,SAAS,GAAG,KAAK,CAWjE"}
@@ -61,7 +61,7 @@ export declare function responsesEndpoint(target: ProviderTarget): ResponsesEndp
61
61
  * this covers the one whose response started and then broke while its body was
62
62
  * being read: the socket closed, the stream ended with no terminal frame, or
63
63
  * the provider sent a `response.failed` / `error` frame that reads as
64
- * retryable. Measured in fager: one such drop on the first step lost a whole
64
+ * retryable. Measured in an app: one such drop on the first step lost a whole
65
65
  * build, and the same request a second later worked.
66
66
  *
67
67
  * Nothing the user could have seen is repeated. Until the first content event
@@ -1 +1 @@
1
- {"version":3,"file":"call.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;;;;;;;GAuDG;AACH,wBAAuB,eAAe,CAAC,IAAI,SAAS,MAAM,GAAG,gBAAgB,EAC3E,QAAQ,EAAE,iBAAiB,EAC3B,IAAI,EAAE,IAAI,EACV,MAAM,EAAE;IACN,MAAM,CAAC,EAAE,WAAW,CAAC;IACrB,gBAAgB,EAAE,OAAO,CAAC;IAC1B,4DAA4D;IAC5D,yBAAyB,CAAC,EAAE,OAAO,CAAC;IACpC;;2EAEuE;IACvE,KAAK,CAAC,EAAE,GAAG,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;IAC9B;;;;OAIG;IACH,KAAK,CAAC,EAAE,CACN,MAAM,EAAE,aAAa,CAAC,MAAM,CAAC,EAC7B,OAAO,EAAE;QAAE,gBAAgB,EAAE,OAAO,CAAC;QAAC,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,CAAA;KAAE,KACrE,aAAa,CAAC,aAAa,CAAC,CAAC;CACnC,GACA,cAAc,CAAC,aAAa,CAAC,CAyU/B;AAsED;;;;;;;;;;;;;;;;;GAiBG;AACH,MAAM,MAAM,aAAa,GAAG,WAAW,GAAG,YAAY,CAAC;AAEvD;;;;;GAKG;AACH,wBAAsB,UAAU,CAC9B,QAAQ,EAAE,iBAAiB,EAC3B,IAAI,EAAE,IAAI;AACV,gEAAgE;AAChE,OAAO,GAAE,aAAa,GAAG,IAAkB,GAC1C,OAAO,CAAC,MAAM,CAAC,CAyBjB;AAED;;;;;;;;GAQG;AACH,wBAAsB,UAAU,CAAC,QAAQ,EAAE,iBAAiB,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAqB3F"}
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{la as b}from"../../chunk-w225pkpp.js";import{$d as n}from"../../chunk-gvr7cwxn.js";import{Gj as d,Hj as p}from"../../chunk-t6x1r5n6.js";import"../../chunk-naj8bmj5.js";import"../../chunk-17ewxwga.js";import"../../chunk-sv2mv2q2.js";import"../../chunk-ka8dzc6q.js";import"../../chunk-ts75gcfd.js";import{createHash as QD}from"crypto";import{createHash as x}from"crypto";import{existsSync as o,readdirSync as s,readFileSync as t,statSync as r}from"fs";import{join as E,relative as e,sep as DD}from"path";var M="\u241F",u=6,$D=/\{\{>\s*([^}\s]+)\s*\}\}/g,v=(D)=>D.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");function m(D){let $=D.filter((Q)=>Q.length>=u),z=D.filter((Q)=>Q.length<u);return(Q)=>{let V=Q;for(let X of $)if(V.includes(X))V=V.split(X).join(M);for(let X of z)V=V.replace(new RegExp(`${v(X)}\\s*${M}`,"g"),M).replace(new RegExp(`${M}\\s*${v(X)}`,"g"),M);return V.replace(new RegExp(`\\s*${M}[\\s${M}]*`,"g"),M)}}function g(D,$=[]){for(let z of s(D)){if(z==="node_modules")continue;let Q=E(D,z);if(r(Q).isDirectory())g(Q,$);else if(z.endsWith(".md"))$.push(Q)}return $}class H{data;root;options;constructor(D,$={}){this.data=D;this.options=$,this.root=$.root??process.cwd()}static blob(D){return x("sha1").update(`blob ${Buffer.byteLength(D)}\x00`).update(D).digest("hex")}static pieces(D){return D.split(/\{\{[^}]*\}\}/).map(($)=>$.trim()).filter(($)=>$.length>0)}static tool(D){return x("sha256").update(JSON.stringify({description:D.description,parameters:D.parameters})).digest("hex")}static prompts(D={}){let $=D.root??process.cwd(),z=new Map;for(let Q of D.dirs??["app/agents"]){if(!o(E($,Q)))continue;for(let V of g(E($,Q)).sort())z.set(e($,V).split(DD).join("/"),t(V,"utf8"))}return z}static of(D,$,z={}){let Q=[...D].join(`
2
+ import{la as b}from"../../chunk-4800w7qx.js";import{$d as n}from"../../chunk-gvr7cwxn.js";import{Gj as d,Hj as p}from"../../chunk-t6x1r5n6.js";import"../../chunk-naj8bmj5.js";import"../../chunk-17ewxwga.js";import"../../chunk-sv2mv2q2.js";import"../../chunk-ka8dzc6q.js";import"../../chunk-ts75gcfd.js";import{createHash as QD}from"crypto";import{createHash as x}from"crypto";import{existsSync as o,readdirSync as s,readFileSync as t,statSync as r}from"fs";import{join as E,relative as e,sep as DD}from"path";var M="\u241F",u=6,$D=/\{\{>\s*([^}\s]+)\s*\}\}/g,v=(D)=>D.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");function m(D){let $=D.filter((Q)=>Q.length>=u),z=D.filter((Q)=>Q.length<u);return(Q)=>{let V=Q;for(let X of $)if(V.includes(X))V=V.split(X).join(M);for(let X of z)V=V.replace(new RegExp(`${v(X)}\\s*${M}`,"g"),M).replace(new RegExp(`${M}\\s*${v(X)}`,"g"),M);return V.replace(new RegExp(`\\s*${M}[\\s${M}]*`,"g"),M)}}function g(D,$=[]){for(let z of s(D)){if(z==="node_modules")continue;let Q=E(D,z);if(r(Q).isDirectory())g(Q,$);else if(z.endsWith(".md"))$.push(Q)}return $}class H{data;root;options;constructor(D,$={}){this.data=D;this.options=$,this.root=$.root??process.cwd()}static blob(D){return x("sha1").update(`blob ${Buffer.byteLength(D)}\x00`).update(D).digest("hex")}static pieces(D){return D.split(/\{\{[^}]*\}\}/).map(($)=>$.trim()).filter(($)=>$.length>0)}static tool(D){return x("sha256").update(JSON.stringify({description:D.description,parameters:D.parameters})).digest("hex")}static prompts(D={}){let $=D.root??process.cwd(),z=new Map;for(let Q of D.dirs??["app/agents"]){if(!o(E($,Q)))continue;for(let V of g(E($,Q)).sort())z.set(e($,V).split(DD).join("/"),t(V,"utf8"))}return z}static of(D,$,z={}){let Q=[...D].join(`
3
3
  \x00
4
4
  `),V={};for(let[J,Z]of H.prompts(z))if(H.pieces(Z).filter((j)=>j.length>=12).sort((j,Y)=>Y.length-j.length).slice(0,3).some((j)=>Q.includes(j)))V[J]=H.blob(Z);let X=[...$.keys()].sort(),K=z.inputs?.(new Set(X));return new H({prompts:V,tools:Object.fromEntries(X.map((J)=>[J,[...$.get(J)].sort()])),...K&&Object.keys(K).length>0?{inputs:zD(K)}:{}},z)}same(D){let $=D instanceof H?D.data:D;return JSON.stringify(this.data)===JSON.stringify($)}changed(){let D=this.options.inputs?.(new Set(Object.keys(this.data.tools)))??{};return[...this.changedPrompts().map(([$])=>$),...Object.entries(this.data.inputs??{}).filter(([$,z])=>D[$]!==z).map(([$])=>`input ${$}`)]}cutters(){let D=H.prompts(this.options),$=this.changedPrompts(),z=new Map,Q=new Map;for(let[V,X]of $){let K=this.readBlob(X);if(K===void 0)throw Error(`${V} changed since the recording, and the version it was recorded with (${X}) can't be read back from git`);if(z.set(V,K),D.has(V))Q.set(V,D.get(V))}return{changed:$.map(([V])=>V),recorded:m(this.piecesWithPartials(z,(V)=>{let X=this.data.prompts[V];return X&&this.readBlob(X)||D.get(V)})),sent:m(this.piecesWithPartials(Q,(V)=>D.get(V)))}}changedPrompts(){let D=H.prompts(this.options);return Object.entries(this.data.prompts).filter(([$,z])=>{let Q=D.get($);return Q===void 0||H.blob(Q)!==z})}readBlob(D){if(this.options.readBlob)return this.options.readBlob(D);let $=Bun.spawnSync(["git","cat-file","blob",D],{cwd:this.root});return $.exitCode===0?$.stdout.toString():void 0}piecesWithPartials(D,$){let z=this.options.dirs??["app/agents"],Q=this.options.shared??"prompts",V=[...D];while(V.length>0){let[X,K]=V.pop(),J=z.find((Z)=>X.startsWith(`${Z}/`));if(J===void 0)continue;for(let[,Z]of K.matchAll($D)){let B=`${J}/${Z.includes("/")?Z:`${Q}/${Z}`}.md`,j=D.has(B)?void 0:$(B);if(j===void 0)continue;D.set(B,j),V.push([B,j])}}return[...D.values()].flatMap((X)=>H.pieces(X)).sort((X,K)=>K.length-X.length)}}function zD(D){return Object.fromEntries(Object.entries(D).sort(([$],[z])=>$.localeCompare(z)))}class w extends Error{constructor(D){super(`${D} Record again.`);this.name="RecordingMismatchError"}}var VD=/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/g;function T(D,$){if(typeof D==="string")return $(D);if(Array.isArray(D))return D.map((z)=>T(z,$));if(D&&typeof D==="object")return Object.fromEntries(Object.entries(D).map(([z,Q])=>[z,T(Q,$)]));return D}function h(D){return JSON.parse(JSON.stringify(D,function($,z){if($==="nested")return;if($==="output"&&this.type==="tool-result"&&"modelOutput"in this)return;return z}))}function c(){let D;return{promise:new Promise((z)=>D=z),resolve:D}}var XD=(D)=>QD("sha256").update(D).digest("hex"),k=(D)=>D.flatMap(($)=>("tools"in $)?$.tools:[$]);function l(D){return D.map(({role:$,content:z})=>({role:$,parts:(Array.isArray(z)?z:[]).flatMap((Q)=>{if(Q?.type==="tool-call")return[{call:Q.name,input:Q.input??Q.args}];if(Q?.type==="tool-result")return[{result:Q.name,status:Q.status}];if(Q?.type==="file")return[{file:!0}];return[]})}))}class R extends b{live;model;capabilities;recordedAt;calls;recordedNested;children=new Map;parent;key;sent=[];uploads;uploadCount=0;read;shared;options;texts=new Set;toolHashes=new Map;toolLists=new Set;recorded;cuts;constructor(D,$,z,Q){super();this.live=D;if(this.options={...z,match:z.match??"wording",ids:new RegExp(z.ids??VD,"g"),waitMs:z.waitMs??60000},Q){let{parent:V}=Q;this.parent=V,this.key=Q.key,this.model=V.model,this.capabilities=V.capabilities,this.recordedAt=V.recordedAt,this.calls=Q.calls,this.recordedNested={},this.uploads=V.uploads,this.shared=V.shared;return}if(this.shared={ids:new Map,stale:new Set,staleCalls:0,started:0,moved:c()},this.uploads=new Map,D){this.model=D.model,this.capabilities=D.capabilities,this.recordedAt=new Date,this.calls=[],this.recordedNested={};return}if(!$||$.version!==1||!Array.isArray($.calls))throw Error("RecordingProvider.replay needs a recording made by RecordingProvider.");if(this.model=$.model,this.capabilities=$.capabilities,this.recordedAt=new Date($.recordedAt),this.calls=structuredClone($.calls),this.recordedNested=structuredClone($.nested??{}),$.fingerprints)this.recorded=new H($.fingerprints,z.fingerprints)}static record(D,$={}){return new R(D,void 0,$)}static replay(D,$={}){return new R(void 0,D,$)}get isRecording(){return this.live!==void 0}get stale(){return this.shared.stale}get staleCalls(){return this.shared.staleCalls}nested(D){if(this.parent)return this.parent.nested(D);let $=this.children.get(D);if(!$){let z=this.recordedNested[D];if(!this.live&&!z)throw new w(`The recording has no sub-run "${D}".`);$=new R(this.live,void 0,this.options,{parent:this,key:D,calls:z??[]}),this.children.set(D,$)}return $}recording(){if(this.parent)return this.parent.recording();if(!this.live)throw Error("Only a recording provider (`record`) has a recording to save.");return{version:1,model:this.model,capabilities:this.capabilities,recordedAt:this.recordedAt.toISOString(),calls:structuredClone(this.calls),...this.options.fingerprints?{fingerprints:this.fingerprints().data}:{},...this.children.size>0?{nested:Object.fromEntries([...this.children].map(([D,$])=>[D,structuredClone($.calls)]))}:{}}}fingerprints(){let D=this.parent??this;return H.of(D.texts,D.toolHashes,this.options.fingerprints)}static changedSince(D,$={}){return D.fingerprints?new H(D.fingerprints,$).changed():[]}replayedInFull(){let D=this.parent??this;return D.calls.length===0&&Object.entries(D.recordedNested).every(([$,z])=>(D.children.get($)?.calls??z).length===0)}async pin(D){if(this.live)return this.read=D,D;let $=this.calls[0]?.read;if($===void 0)return D;return await(this.parent??this).reach($,this.where()),$}async upload(D){let $=++this.uploadCount,z=this.key===void 0?`upload_${$}`:`upload_${this.key}_${$}`;if(this.live)this.uploads.set(z,await this.live.upload(D));return z}async deleteFile(D){let $=this.uploads.get(D);if(this.live&&$!==void 0){if(!this.live.deleteFile)throw Error(`${this.live.constructor.name} cannot delete provider files: it does not implement deleteFile().`);await this.live.deleteFile($),this.uploads.delete(D)}}normalizeError(D){return this.live?this.live.normalizeError(D):super.normalizeError(D)}async*stream(D){let $=this.requestOf(D);if(this.live){yield*this.recordCall(D,$);return}yield*this.replayCall(D,$)}async*recordCall(D,$){let z=this.parent??this,Q=z.shared.started++,V=this.read;this.read=void 0;let X=[],K=D.messages.map((Z)=>({...Z,content:Z.content.map((B)=>B.type==="file"&&B.fileId&&this.uploads.has(B.fileId)?{...B,fileId:this.uploads.get(B.fileId)}:B)}));for await(let Z of this.live.stream({...D,messages:K})){let B=X.at(-1);if(Z.type==="tool-call-discard"){let j=new Set(Z.toolCallIds),Y=X.filter((_)=>_.type!=="tool-call-delta"||!j.has(_.toolCallId));X.splice(0,X.length,...Y)}else if(Z.type==="retry");else if(B&&(Z.type==="text-delta"||Z.type==="output-delta")&&B.type===Z.type)B.delta+=Z.delta;else if(B?.type==="tool-call-delta"&&Z.type==="tool-call-delta"&&B.toolCallId===Z.toolCallId)B.argsDelta+=Z.argsDelta;else X.push({...Z});yield Z}let J=this.options.position?await this.options.position():void 0;this.calls.push({request:$,events:X,at:Q,...V!==void 0?{read:V}:{},...J!==void 0?{ended:J}:{}})}async*replayCall(D,$){let z=this.parent??this,Q=this.where(),V=this.calls[0];if(this.options.ordered&&V?.at!==void 0)await z.turn(V.at,Q);let X=this.calls.shift();if(!X)throw new w(`${Q}: call ${this.sentCalls} was not recorded (the recording has no more calls).`);let{promptCacheKey:K,...J}=X.request;if(!z.matches(JSON.stringify(J),$))z.tolerate(Q,{...X,request:J},$,D.tools??[]);if(X.ended!==void 0)await z.reach(X.ended,Q);let Z=z.shared.ids;for(let B of X.events)yield JSON.parse(JSON.stringify(B).replace(this.options.ids,(j)=>Z.get(j)??j))}where(){return this.key===void 0?"the recording":`sub-run "${this.key}"`}sentCalls=0;requestOf(D){this.sentCalls++;let{signal:$,promptCacheKey:z,agent:Q,messages:V,tools:X,...K}=D,J=V.map(({role:_,content:I})=>({role:_,content:h(I)})),Z=this.sent.length>0&&this.sent.length<=J.length&&JSON.stringify(J.slice(0,this.sent.length))===JSON.stringify(this.sent)?this.sent.length:0;this.sent=J;let B=X&&X.length>0?JSON.stringify(X):void 0,j=this.parent??this,Y=(_)=>{return j.texts.add(_),_};if(T([K,J.slice(Z)],Y),B&&!j.toolLists.has(B)){j.toolLists.add(B);for(let _ of k(X)){T(_,Y);let I=j.toolHashes.get(_.name)??new Set;I.add(H.tool(_)),j.toolHashes.set(_.name,I)}}return{...h(K),...B?{tools:`sha256:${XD(B)}`,toolNames:k(X).map((_)=>_.name).sort()}:{},...Z>0?{after:Z}:{},messages:J.slice(Z)}}matches(D,$){let z=this.options.ids,Q=JSON.stringify($),V=D.match(z)??[],X=Q.match(z)??[];if(V.length!==X.length)return!1;let K=new Map(this.shared.ids);for(let[J,Z]of V.entries()){let B=K.get(Z)??X[J];if(B!==X[J])return!1;K.set(Z,B)}if(D.replace(z,(J)=>K.get(J))!==Q)return!1;for(let[J,Z]of K)this.shared.ids.set(J,Z);return!0}tolerate(D,$,z,Q){let V=this.options.ids,X=this.options.match,K=$.request,J=(O,G,W)=>{let U=JSON.stringify(O).replace(V,"<id>"),C=JSON.stringify(G).replace(V,"<id>"),L=0;while(L<U.length&&U[L]===C[L])L++;throw new w(`${D}: the request differs from the recorded one${W}. Recorded: \u2026${U.slice(Math.max(0,L-80),L+120)}\u2026 Sent: \u2026${C.slice(Math.max(0,L-80),L+120)}\u2026`)};if(X==="exact")J(K,z,"");let{tools:Z,toolNames:B,...j}=K,{tools:Y,toolNames:_,...I}=z,P=[];if(!this.matches(JSON.stringify(j),I))if(X==="wording"){if(!this.recorded)J(j,I,", and the recording has no fingerprints to tell a reworded prompt by");try{this.cuts??=this.recorded.cutters()}catch(W){throw new w(`${D}: ${W.message}.`)}let O=T(j,this.cuts.recorded),G=T(I,this.cuts.sent);if(this.cuts.changed.length===0||!this.matches(JSON.stringify(O),G))J(O,G,this.cuts.changed.length>0?", beyond the wording of the prompts changed since":"");P.push(...this.cuts.changed.map((W)=>`${W} changed`))}else{if(!((K.after??0)===(z.after??0)&&this.matches(JSON.stringify(l(K.messages)),l(z.messages))))J(j,I," in the conversation itself");let{messages:G,...W}=j,{messages:U,...C}=I;if(!this.matches(JSON.stringify(G),U))P.push("message text changed");let L=new Set([...Object.keys(W),...Object.keys(C)]);for(let q of[...L].sort()){let A=JSON.stringify(W[q]??null);if(!this.matches(A,C[q]??null))P.push(`${q} changed`)}}if(Z!==Y){let O=k(Q);for(let G of $.events){if(G.type!=="tool-call")continue;let W=O.find((A)=>A.name===G.name);if(!W)throw new w(`${D}: the recorded answer calls ${G.name}, which is not offered any more.`);let U=Object.fromEntries([...JSON.stringify(W.parameters).matchAll(/"format":"([^"]+)"/g)].map(([,A])=>[A,!0])),C;try{C=JSON.parse(G.args||"{}")}catch{C=void 0}let L;try{L=p.fromJSONSchema(W.parameters,{unknownKeys:"error",formats:U})}catch(A){if(!(A instanceof d))throw A}let q=L?.safeParse(C);if(q&&q.ok===!1)throw new w(`${D}: the recorded call of ${G.name} does not fit its schema any more (${q.errors.join("; ")}).`)}if(this.recorded){let G=O.filter((W)=>!this.recorded.data.tools[W.name]?.includes(H.tool(W))).map((W)=>W.name).sort();P.push(G.length>0?`tools changed: ${G.join(", ")}`:"the tools offered changed")}else{let G=new Set(B??[]),W=new Set(_??[]),U=[...W].filter((L)=>!G.has(L)),C=[...G].filter((L)=>!W.has(L));P.push(U.length>0||C.length>0?`tools offered changed (${[...U.map((L)=>`+${L}`),...C.map((L)=>`-${L}`)].join(", ")})`:"the tools offered changed")}}this.shared.staleCalls++;for(let O of P)this.shared.stale.add(O)}async turn(D,$){let z=this.shared;z.pending??=[...this.calls,...Object.values(this.recordedNested).flat()].map((Q)=>Q.at).filter((Q)=>Q!==void 0).sort((Q,V)=>Q-V);while(z.pending[0]!==void 0&&z.pending[0]<D){let Q=z.moved.promise;if(!await Promise.race([Q.then(()=>!0),new Promise((X)=>setTimeout(()=>X(!1),this.options.waitMs))]))throw new w(`${$}: call ${D} waits for call ${z.pending[0]}, which the replay does not make.`)}z.pending=z.pending.filter((Q)=>Q!==D),z.moved.resolve(),z.moved=c()}async reach(D,$){let z=this.options.position;if(!z)return;let Q=await z(),V=0;while(Q<D){await new Promise((K)=>setTimeout(K,25));let X=await z();if(V=X===Q?V+25:0,Q=X,V>=this.options.waitMs)throw new w(`${$}: a call waits for the app to reach ${D}; it stays at ${Q}.`)}}}function ZD(D){let $=globalThis.Date,z=new $(D).getTime()-$.now();if(!Number.isFinite(z))throw Error(`pinClock: ${String(D)} is not a date.`);class Q extends ${constructor(...V){if(V.length===0)super($.now()+z);else super(...V)}static now(){return $.now()+z}}return globalThis.Date=Q,()=>{if(globalThis.Date===Q)globalThis.Date=$}}class N extends Error{error;name="ScriptedProviderError";constructor(D,$){super(D);this.error=$}}var F=Symbol("scriptedProvider.NO_AGENT");function a(D){let z=n(D).at(-1),Q=z?.find((X)=>X.role==="user");if(!z||!Q)return;let V=Q.content.map((X)=>X.type==="text"?X.text:"").join("");return{message:Q,text:V,messages:z}}var S=void 0,i=(D)=>D===S?"the script":D===F?"NO_AGENT":`"${D}"`,BD={reasoning:!0,structuredOutput:!0,fileInput:!0,parallelToolCalls:!0,toolSearch:!0,trailingContext:!0};class f extends b{options;model="scripted";capabilities=BD;calls=[];uploads=[];steps;used=new Map;constructor(D,$={}){super();this.options=$;this.steps=new Map(Array.isArray(D)?[[S,[...D]]]:[...Object.entries(D).map(([z,Q])=>[z,[...Q]]),...D[F]?[[F,[...D[F]]]]:[]])}callsOf(D){return this.calls.filter(($)=>$.agent===D)}assertDone(){let D=[...this.steps].flatMap(([$,z])=>{let Q=z.length-(this.used.get($)??0);return Q>0?[`${i($)}: ${Q} step(s)`]:[]});if(D.length>0)throw new N(`Steps never used: ${D.join(", ")}.`)}stream(D){let $=D.agent?.name,z=this.steps.has(S)?S:$??F,Q=this.used.get(z)??0,V={agent:$,depth:D.agent?.depth??0,index:this.calls.filter((B)=>B.agent===$).length,messages:D.messages,turn:a(D.messages),trailingContext:D.trailingContext,params:D};this.calls.push(V);let X=this.steps.get(z),K=X?.[Q];if(X&&K!==void 0)this.used.set(z,Q+1);let J=()=>{let B=$===void 0?"A call no agent made":`Agent "${$}"`,j=V.turn?` (turn: ${JSON.stringify(V.turn.text.slice(0,80))})`:"";if(!X){let Y=[...this.steps.keys()].map(i).join(", ");return`${B} has no script${j}. The scripts are for ${Y}.${$===void 0?" Script it under [NO_AGENT].":""}`}if(z===S){let Y=$===void 0?"":` (${$}'s call ${V.index+1})`;return`The script ran out at step ${Q+1}${Y}: it has ${X.length} step(s)${j}.`}return`${B} made call ${V.index+1}, and its script has ${X.length} step(s)${j}.`},Z=X?this.options.exhausted??"throw":"throw";return async function*(){if(K===void 0){if(Z==="throw")throw new N(J());yield y("stop");return}yield*jD(await KD(K,V),V)}()}async upload(D){return this.uploads.push(D),`file_${this.uploads.length}`}normalizeError(D){if(D instanceof N&&D.error)return{...D.error};return{code:"provider_error",message:D instanceof Error?D.message:String(D),retryable:!1}}}function JD(D,$){return new f(D,$)}async function KD(D,$){let z=D;while(typeof z==="function")z=await z($);return z}var y=(D,$)=>({type:"finish",reason:D,usage:$??{inputTokens:1,outputTokens:1,totalTokens:2}});function jD(D,$){if(typeof D==="string")return[{type:"text-delta",delta:D},y("stop")];if("events"in D)return D.events;if("error"in D){let{error:Q}=D;if(typeof Q==="string")throw new N(Q);if(Q instanceof Error)throw Q;throw new N(Q.message,Q)}let z=[];if(D.reasoning)z.push({type:"reasoning-delta",delta:D.reasoning});for(let Q of typeof D.text==="string"?[D.text]:D.text??[])if(Q)z.push({type:"text-delta",delta:Q});if(D.output!==void 0)z.push({type:"output-delta",delta:JSON.stringify(D.output)});return(D.toolCalls??[]).forEach((Q,V)=>{z.push({type:"tool-call",toolCallId:Q.id??`call_${$.agent??"any"}_${$.index}_${V}`,name:Q.name,args:JSON.stringify(Q.input??{})})}),z.push(y(D.finishReason??"stop",D.usage)),z}export{a as turnOf,JD as scriptedProvider,ZD as pinClock,N as ScriptedProviderError,f as ScriptedProvider,R as RecordingProvider,w as RecordingMismatchError,F as NO_AGENT,H as Fingerprints};
5
5
 
@@ -882,6 +882,11 @@ export type AgentStreamEvent<T extends ToolShapes = ToolShapes, O = unknown> = {
882
882
  type: "message-start";
883
883
  messageId: string;
884
884
  role: "assistant";
885
+ /**
886
+ * The message's `AgentMessage.turn` (#1344), when the run knows it: the
887
+ * turn a client shows the reply under while it streams.
888
+ */
889
+ turn?: string;
885
890
  } | {
886
891
  type: "text-delta";
887
892
  messageId: string;
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceR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ACZ,KAAK,EAAE,gBAAgB,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;CAC/B,CAAC"}
@@ -99,6 +99,16 @@ export declare function openMeter(options?: UsageMeterOptions): {
99
99
  close: () => void;
100
100
  };
101
101
  declare function meter<T>(fn: (meter: UsageMeter) => T | Promise<T>, options?: UsageMeterOptions): Promise<MeteredUsage<T>>;
102
+ /**
103
+ * A stopped call's last `usage` event (#1353), recorded as its `finish`
104
+ * would have been: each model's share at that model, `fallback` when the
105
+ * event names none.
106
+ */
107
+ export declare function recordStopped(event: {
108
+ usage: UsageType;
109
+ model?: string;
110
+ byModel?: Record<string, UsageType>;
111
+ }, fallback: string): void;
102
112
  /** Called by the model call sites with each `finish` frame's usage. */
103
113
  export declare function recordUsage(model: string, usage: UsageType | undefined): void;
104
114
  /** One model call's cost under `pricing`; `undefined` when it isn't priced. */
@@ -1 +1 @@
1
- {"version":3,"file":"usageMeter.d.ts","sourceRoot":"","sources":["../../ai/usageMeter.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,KAAK,IAAI,SAAS,EAAE,MAAM,SAAS,CAAC;AAElD;;;;;;;;;;;;;;;;GAgBG;AAEH,sFAAsF;AACtF,MAAM,MAAM,UAAU,GAAG;IACvB,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,EAAE,MAAM,CAAC;IACf,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB;2BACuB;IACvB,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB;wDACoD;IACpD,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB,CAAC;AAEF;;;;;;;;;;GAUG;AACH,MAAM,MAAM,YAAY,GACpB,MAAM,CAAC,MAAM,EAAE,UAAU,CAAC,GAC1B,CAAC,CAAC,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE,SAAS,KAAK,MAAM,GAAG,SAAS,CAAC,CAAC;AAE9D,qDAAqD;AACrD,MAAM,MAAM,SAA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EACb,KAAK,EAAE,SAAS,GACf,MAAM,GAAG,SAAS,CA2BpB;AAED,oCAAoC;AACpC,MAAM,MAAM,aAAa,CAAC,CAAC,IAAI;IAC7B,KAAK,EAAE,CAAC,CAAC;IACT,iDAAiD;IACjD,KAAK,EAAE,SAAS,CAAC;IACjB,uEAAuE;IACvE,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,CAAC;CACpC,CAAC;AAEF;;;;;;;;;GASG;AACH,wBAAsB,YAAY,CAAC,CAAC,EAAE,EAAE,EAAE,MAAM,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,aAAa,CAAC,CAAC,CAAC,CAAC,CASzF;AAED;;;;;;;;;GASG;AACH,MAAM,MAAM,KAAK,GAAG,SAAS,CAAC;AAE9B,eAAO,MAAM,KAAK;IAChB;;;;OAIG;uBACgB;QAAE,OAAO,CAAC,EAAE,YAAY,CAAA;KAAE,GAAG,IAAI;IAGpD;;;;;;;OAOG;;IAEH;;;OAGG;eACQ,MAAM,QAAQ,MAAM,GAAG,IAAI;IAGtC;;;;OAIG;kBACW,MAAM,SAAS,SAAS,GAAG,IAAI;IAG7C,6EAA6E;eAClE,UAAU,GAAG,SAAS;CAGlC,CAAC"}
@@ -37,6 +37,32 @@ type BodyOf<P extends keyof AgentRoutes> = AgentRoutes[P] extends {
37
37
  * the difference will either look hung or look finished.
38
38
  */
39
39
  export type ChatStatus = "idle" | "submitted" | "streaming" | "awaiting-input" | "error";
40
+ /**
41
+ * One reply of the chat's (#1344): a run streaming into it, or a turn waiting
42
+ * on its questions. With runs side by side (`ifBusy: "parallel"`) there is one
43
+ * per running reply, so a UI can show each with its own status and questions.
44
+ *
45
+ * - `id`: a client-side id, the same for as long as the entry is listed: a
46
+ * key for the UI. A turn waiting on its questions is keyed by its turn
47
+ * (`turn:<turn>`), and the answer to that turn alone keeps the id while it
48
+ * streams. An answer that covers several turns' questions gets a new id.
49
+ * - `runId`: the run, once its stream says (`run-start`, or the run an attach
50
+ * asked for). None before that, and none for a turn waiting on its
51
+ * questions: its run has ended.
52
+ * - `turn`: the turn the reply belongs to, `AgentMessage.turn` of its
53
+ * messages, once known: the pending calls of `pending` with the same `turn`
54
+ * are its questions. None until the run's first message starts, for a run
55
+ * answering calls that carry none, or a server older than this field.
56
+ * - `status`: `"submitted"` before the stream says anything, `"streaming"`
57
+ * once a frame of it has landed, `"awaiting-input"` for a turn whose run
58
+ * ended asking.
59
+ */
60
+ export type ChatRun = {
61
+ id: string;
62
+ runId?: string;
63
+ turn?: string;
64
+ status: "submitted" | "streaming" | "awaiting-input";
65
+ };
40
66
  /**
41
67
  * A pending call as `useChat` holds it: the server's `PendingToolCall`, plus
42
68
  * whether this client is answering it right now (#1106).
@@ -379,6 +405,15 @@ export interface UseChatResult<P extends keyof AgentRoutes> {
379
405
  * takes the answer; if the request fails it is plain pending again (#1106).
380
406
  */
381
407
  pending: ChatPendingToolCall<ToolsOf<P>>[];
408
+ /**
409
+ * The replies in progress (#1344): the requests in flight (a send, an
410
+ * answer, an attach that found a run), in the order they started, then the
411
+ * turns waiting on their questions. Empty when the chat is idle: an attach
412
+ * or a probe that has not found a run yet is not listed. One entry for a
413
+ * chat that never runs side by side; several with `ifBusy: "parallel"`.
414
+ * See `ChatRun`.
415
+ */
416
+ runs: ChatRun[];
382
417
  /**
383
418
  * The deferred tools the model has pulled in during the run in flight.
384
419
  *
@@ -1 +1 @@
1
- {"version":3,"file":"useChat.d.ts","sourceRoot":"","sources":["../../ai/useChat.tsx"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,eAAe,CAAC;AAazC,OAAO,KAAK,EACV,UAAU,EACV,YAAY,EACZ,gBAAgB,EAEhB,UAAU,EACV,eAAe,EAEf,YAAY,EACZ,cAAc,EACd,UAAU,EACV,KAAK,EACN,MAAM,SAAS,CAAC;AAEjB;;;;;GAKG;AACH,KAAK,WAAW,GAAG;KAChB,CAAC,IAAI,MAAM,GAA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,EAAE,MAAM,CAAC;IACf,SAAS,CAAC,EAAE,OAAO,CAAC;CACrB,CAAC;AAEF;;;;;;;GAOG;AACH,MAAM,MAAM,aAAa,GAAG;IAAE,KAAK,CAAC,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAAC,WAAW,CAAC,EAAE,MAAM,CAAA;CAAE,CAAC;AAyXxF;;;;;;;;;GASG;AACH,wBAAgB,OAAO,CAAC,CAAC,SAAS,MAAM,WAAW,EACjD,IAAI,EAAE,CAAC,EACP,MAAM,GAAE,aAAa,CAAC,CAAC,CAAM,GAC5B,aAAa,CAAC,CAAC,CAAC,CA0sClB"}
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{$ as SJ,_ as n,aa as bJ,ba as qJ}from"./chunk-t929a66m.js";import{Da as E,Ha as T,Ia as TJ}from"./chunk-v2fd69at.js";import"./chunk-ba1h9pm6.js";import{Ze as GJ,hh as IJ,ih as g,qh as AJ,rh as BJ,sh as RJ}from"./chunk-cb7mgx75.js";import"./chunk-zm6b938z.js";import"./chunk-2kzysesp.js";import{Bi as WJ,xi as jJ,yi as YJ}from"./chunk-fqndtpwm.js";import{Ej as DJ}from"./chunk-h1wmpa03.js";import"./chunk-t6x1r5n6.js";import"./chunk-naj8bmj5.js";import"./chunk-np6vee9d.js";import"./chunk-5exrgw07.js";import"./chunk-jssjfvsz.js";import"./chunk-a119av2z.js";import"./chunk-m3fbewhz.js";import"./chunk-x2dmgge8.js";import"./chunk-fs94x6ef.js";import"./chunk-8476xvk9.js";import"./chunk-kvtvx64t.js";import"./chunk-9jt5qj1b.js";import"./chunk-17ewxwga.js";import"./chunk-sv2mv2q2.js";import{vm as KJ}from"./chunk-gt9ftnhn.js";import"./chunk-qvn0w2rt.js";import{Nm as PJ}from"./chunk-ka8dzc6q.js";import{Pm as f}from"./chunk-3y1h3ncf.js";import"./chunk-ts75gcfd.js";import{createHash as _2}from"crypto";import{join as i,resolve as EJ,sep as vJ}from"path";import{Duplex as cJ}from"stream";import{constants as k,createBrotliCompress as pJ,createGzip as dJ}from"zlib";var lJ=["br","gzip"],oJ=1024,nJ=5,iJ=19,aJ=6;function rJ(J){if(J===void 0)return 1;if(!/^\d+(\.\d{0,3})?$/.test(J.trim()))return 1;let $=Number(J.trim());return Number.isFinite($)?Math.min($,1):1}function tJ(J){if(J===null||J===void 0)return null;let $=new Map;for(let Z of J.split(",")){let[Q,...H]=Z.split(";"),j=Q.trim().toLowerCase();if(j==="")continue;let Y=1;for(let W of H){let V=W.indexOf("=");if(V===-1)continue;if(W.slice(0,V).trim().toLowerCase()==="q"){Y=rJ(W.slice(V+1));break}}$.set(j,Y)}return $}function p(J,$=lJ){let Z=tJ(J);if(!Z)return null;let Q=Z.get("*"),H=null,j=0;for(let Y of $){let W=Z.get(Y)??Q??0;if(W>j)H=Y,j=W}return H}function sJ(J,$){if(!J)return!1;return J.split(",").some((Z)=>Z.trim().toLowerCase().split("=")[0].trim()===$)}function eJ(J,$){if(J==="HEAD")return!1;if($.status<200||$.status===204||$.status===206||$.status===304)return!1;if($.headers.has("Content-Range"))return!1;let Z=$.headers.get("Content-Type");if(!Z||!/^\s*text\/html\s*(;|$)/i.test(Z))return!1;if(!$.body)return!1;let Q=$.headers.get("Content-Encoding");if(Q&&Q.trim().toLowerCase()!=="identity")return!1;if(sJ($.headers.get("Cache-Control"),"no-transform"))return!1;let H=$.headers.get("Content-Length");if(H!==null&&Number(H)<oJ)return!1;return!0}function J2(J){let $=J==="br"?pJ({params:{[k.BROTLI_PARAM_QUALITY]:nJ,[k.BROTLI_PARAM_LGWIN]:iJ},flush:k.BROTLI_OPERATION_FLUSH}):dJ({level:aJ,flush:k.Z_SYNC_FLUSH});return cJ.toWeb($)}function $2(J){let $=J.get("Vary");if(!$){J.set("Vary","Accept-Encoding");return}let Z=$.split(",").map((Q)=>Q.trim().toLowerCase());if(Z.includes("*")||Z.includes("accept-encoding"))return;J.append("Vary","Accept-Encoding")}function ZJ(J,$){if(!eJ(J.method,$))return $;let Z=new Headers($.headers);$2(Z);let Q=p(J.headers.get("Accept-Encoding"));if(!Q)return new Response($.body,{status:$.status,statusText:$.statusText,headers:Z});let H;try{H=J2(Q)}catch{return new Response($.body,{status:$.status,statusText:$.statusText,headers:Z})}return Z.set("Content-Encoding",Q),Z.delete("Content-Length"),new Response($.body.pipeThrough(H),{status:$.status,statusText:$.statusText,headers:Z})}import{readdir as W2,stat as VJ}from"fs/promises";import{join as G2}from"path";import{mkdir as R2,readFile as Z2,stat as T2,writeFile as S2}from"fs/promises";import{dirname as q2,join as Q2}from"path";import{promisify as QJ}from"util";import{brotliCompress as X2,constants as w2,gzip as H2}from"zlib";var j2=".vite/static-assets.json";var XJ={br:".br",gzip:".gz"},Y2=["br","gzip"],k2=QJ(X2),y2=QJ(H2);async function HJ(J){let $;try{$=await Z2(Q2(J,j2),"utf8")}catch{return null}let Z;try{Z=JSON.parse($)?.files}catch{return null}if(!Z||typeof Z!=="object")return null;let Q={files:{}};for(let[H,j]of Object.entries(Z)){if(!Array.isArray(j))continue;Q.files[H]=Y2.filter((Y)=>j.includes(Y))}return Q}function d(J){let $=J.toString(),Z=new Bun.CryptoHasher("sha1");return Z.update($),Z.digest("hex")}async function zJ(J){let $=new Set;async function Z(Q,H){let j;try{j=await W2(Q,{withFileTypes:!0})}catch{return}for(let Y of j){if(Y.name.startsWith("."))continue;if(H&&Y.name==="assets")continue;let W=G2(Q,Y.name),V=Y.isDirectory(),z=Y.isFile();if(Y.isSymbolicLink())try{let C=await VJ(W);V=C.isDirectory(),z=C.isFile()}catch{continue}if(z)$.add(W);else if(V&&!Y.isSymbolicLink())await Z(W,!1)}}return await Z(J,!0),$}var V2="public, max-age=31536000, must-revalidate",z2="public, max-age=31536000, immutable";async function U2(J,$,Z){if(Z.length===0||J.headers.has("Range"))return null;let Q=p(J.headers.get("Accept-Encoding"),Z);if(!Q)return null;let H=$+XJ[Q];try{let j=await VJ(H);return j.isFile()?{encoding:Q,path:H,size:j.size}:null}catch{return null}}async function UJ(J,$,Z={}){let Q=Bun.file($),H=Z.encodings??[],j={"Content-Type":Q.type||"application/octet-stream","Cache-Control":Z.immutable?z2:V2,"Accept-Ranges":"bytes"};if(H.length>0)j.Vary="Accept-Encoding";let Y=await U2(J,$,H);if(Y){let z=Bun.file(Y.path);return new Response(z.stream(),{headers:{...j,"Content-Encoding":Y.encoding,"Content-Length":String(Y.size),ETag:`${d(z.lastModified)}-${Y.encoding}`}})}let W=Q.size;j.ETag=d(Q.lastModified);let V=jJ(J.headers.get("Range"));if(V){let z=YJ(V,W);if(!z)return GJ(W);return new Response(Q.slice(z.start,z.end+1).stream(),{status:206,headers:{...j,"Content-Range":WJ(z.start,z.end,W),"Content-Length":String(z.length)}})}return new Response(Q.stream(),{headers:{...j,"Content-Length":String(W)}})}import{stat as I2}from"fs/promises";var y="app/client.tsx";function OJ(J,$=E){let Z=J[y]?.file;if(!Z)return;return{module:T(Z,$),preload:R(J,y,$)}}function R(J,$,Z=E){let Q=[],H=new Set,j=(Y)=>{if(H.has(Y))return;H.add(Y);let W=J[Y];if(!W?.file)return;Q.push(T(W.file,Z));for(let V of W.imports??[])j(V)};return j($),Q}function K2(J,$,Z=E){let Q=new Set(R(J,$,Z)),H=[],j=new Set,Y=(V)=>{if(j.has(V))return;j.add(V);let z=J[V];if(!z)return;for(let C of z.dynamicImports??[])if(!/(^|\/)node_modules\//.test(C)&&!H.includes(C))H.push(C);for(let C of z.imports??[])Y(C)};Y($);let W=[];for(let V of H)for(let z of R(J,V,Z))if(!Q.has(z))Q.add(z),W.push(z);return W}function xJ(J,$){let Z=[],Q=new Set,H=new Set,j=(Y)=>{if(H.has(Y))return;H.add(Y);let W=J[Y];if(!W)return;for(let V of W.imports??[])j(V);for(let V of W.css??[])if(!Q.has(V))Q.add(V),Z.push(V)};return j($),Z}function CJ(J,$=E){let Z=new Map;return(Q)=>{if(!Z.has(Q)){let H=`${Q}${KJ}`,j=J[H]?.file;Z.set(Q,j?{src:T(j,$),preload:R(J,H,$),dynamicPreload:K2(J,H,$)}:void 0)}return Z.get(Q)}}var LJ="x-gemi-build";var O2="__gemiReload";function x2(J,$,Z,Q){let H=Date.now(),j=function(U){return typeof U==="number"&&H-U>=0&&H-U<Z},Y=function(U){try{let K=U?JSON.parse(U):null;return K&&typeof K==="object"&&!Array.isArray(K)?K:{}}catch{return{}}},W=function(U){let K={};for(let M in U)if(j(U[M]))K[M]=U[M];return K},V=function(U){let K=2166136261;for(let M=0;M<U.length;M++)K=Math.imul(K^U.charCodeAt(M),16777619);return(K>>>0).toString(36)},z=null,C={};try{z=window.sessionStorage,C=Y(z.getItem(J))}catch{z=null}let N=J+":",F="",I="";try{let U=new URL($,window.location.href);F=V(new URL(window.location.href).origin),I=V(U.origin+U.pathname)}catch{}let L=null;try{let U=window.name;if(!I)L=null;else if(U==="")L={};else if(U.indexOf(N)===0){let K=Y(U.slice(N.length)),M=K.m;L=K.o===F&&M&&typeof M==="object"&&!Array.isArray(M)?M:{}}}catch{L=null}if(Q==="tidy"){try{let U=window.name;if(L===null||U.indexOf(N)!==0)return"ok";for(let K in L)if(j(L[K]))return"cooldown";window.name=""}catch{}return"ok"}if(j(C[$])||L&&j(L[I]))return"cooldown";if(!z&&!L)return"storage";if(!Q)return"ok";if(z)try{let U=W(C);U[$]=H;let K=JSON.stringify(U);if(z.setItem(J,K),z.getItem(J)===K)return"ok"}catch{}if(L)try{let U=W(L);U[I]=H;let K=N+JSON.stringify({o:F,m:U});if(window.name=K,window.name===K)return"ok"}catch{}return"storage"}function _J(J,$=30000){let Z=JSON.stringify("gemi:chunk-reload"),Q=JSON.stringify(`Failed to fetch dynamically imported module: ${J}`);return`var g=${x2.toString()};var r=!1;try{r=navigator.onLine!==!1&&g(${Z},window.location.href,${Number($)},!0)==="ok"}catch(e){}if(r)window.location.reload();else throw new Error(${Q});export {r as ${O2}}`}var C2=new RegExp(`^${IJ}/.+\\.m?js$`);function l(J){return C2.test(J)}function MJ(J){if(l(J))return new Response(_J(J),{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store"}});if(g(J))return new Response("Not found",{status:404});return}function NJ(J){let $=J?.trim();if(!$)return;try{let Z=new URL($);if(Z.protocol!=="https:"&&Z.protocol!=="http:")throw Error("not http(s)");return Z.search="",Z.hash="",Z.href.endsWith("/")?Z.href:`${Z.href}/`}catch{console.error(`GEMI_ASSET_FALLBACK_URL is not an absolute http(s) URL (${JSON.stringify($)}); missing assets are not looked up anywhere else.`);return}}function FJ({base:J,timeoutMs:$=3000,missTtlMs:Z=30000,fetch:Q=fetch,now:H=Date.now}){let j=new Map,Y=(W)=>{if(j.delete(W),j.set(W,H()+Z),j.size>1000)j.delete(j.keys().next().value)};return async(W,V)=>{if(W.method!=="GET"&&W.method!=="HEAD")return;let z=j.get(V);if(z!==void 0){if(z>H())return;j.delete(V)}let C;try{C=new URL(V.replace(/^\/+/,""),J)}catch{return}if(!C.href.startsWith(J))return;let N=new AbortController,F=setTimeout(()=>N.abort(),$),I;try{I=await Q(C.href,{method:W.method,signal:N.signal,redirect:"error"})}catch{Y(V);return}finally{clearTimeout(F)}if(I.status!==200){I.body?.cancel().catch(()=>{}),Y(V);return}let L=Bun.file(V).type,U=new Headers({"Content-Type":L!=="application/octet-stream"&&L||I.headers.get("content-type")||"application/octet-stream","Cache-Control":"public, max-age=31536000, immutable",["x-gemi-asset-fallback"]:"1"}),K=I.headers.get("content-length");if(K&&!I.headers.get("content-encoding"))U.set("Content-Length",K);return new Response(W.method==="HEAD"?null:I.body,{status:200,headers:U})}}var L2=`<!DOCTYPE html>
2
+ import{$ as SJ,_ as n,aa as bJ,ba as qJ}from"./chunk-7rxj3x6v.js";import{Da as E,Ha as T,Ia as TJ}from"./chunk-v2fd69at.js";import"./chunk-ba1h9pm6.js";import{Ze as GJ,hh as IJ,ih as g,qh as AJ,rh as BJ,sh as RJ}from"./chunk-cb7mgx75.js";import"./chunk-zm6b938z.js";import"./chunk-2kzysesp.js";import{Bi as WJ,xi as jJ,yi as YJ}from"./chunk-fqndtpwm.js";import{Ej as DJ}from"./chunk-h1wmpa03.js";import"./chunk-t6x1r5n6.js";import"./chunk-naj8bmj5.js";import"./chunk-np6vee9d.js";import"./chunk-5exrgw07.js";import"./chunk-jssjfvsz.js";import"./chunk-a119av2z.js";import"./chunk-m3fbewhz.js";import"./chunk-x2dmgge8.js";import"./chunk-fs94x6ef.js";import"./chunk-8476xvk9.js";import"./chunk-kvtvx64t.js";import"./chunk-9jt5qj1b.js";import"./chunk-17ewxwga.js";import"./chunk-sv2mv2q2.js";import{vm as KJ}from"./chunk-gt9ftnhn.js";import"./chunk-qvn0w2rt.js";import{Nm as PJ}from"./chunk-ka8dzc6q.js";import{Pm as f}from"./chunk-3y1h3ncf.js";import"./chunk-ts75gcfd.js";import{createHash as _2}from"crypto";import{join as i,resolve as EJ,sep as vJ}from"path";import{Duplex as cJ}from"stream";import{constants as k,createBrotliCompress as pJ,createGzip as dJ}from"zlib";var lJ=["br","gzip"],oJ=1024,nJ=5,iJ=19,aJ=6;function rJ(J){if(J===void 0)return 1;if(!/^\d+(\.\d{0,3})?$/.test(J.trim()))return 1;let $=Number(J.trim());return Number.isFinite($)?Math.min($,1):1}function tJ(J){if(J===null||J===void 0)return null;let $=new Map;for(let Z of J.split(",")){let[Q,...H]=Z.split(";"),j=Q.trim().toLowerCase();if(j==="")continue;let Y=1;for(let W of H){let V=W.indexOf("=");if(V===-1)continue;if(W.slice(0,V).trim().toLowerCase()==="q"){Y=rJ(W.slice(V+1));break}}$.set(j,Y)}return $}function p(J,$=lJ){let Z=tJ(J);if(!Z)return null;let Q=Z.get("*"),H=null,j=0;for(let Y of $){let W=Z.get(Y)??Q??0;if(W>j)H=Y,j=W}return H}function sJ(J,$){if(!J)return!1;return J.split(",").some((Z)=>Z.trim().toLowerCase().split("=")[0].trim()===$)}function eJ(J,$){if(J==="HEAD")return!1;if($.status<200||$.status===204||$.status===206||$.status===304)return!1;if($.headers.has("Content-Range"))return!1;let Z=$.headers.get("Content-Type");if(!Z||!/^\s*text\/html\s*(;|$)/i.test(Z))return!1;if(!$.body)return!1;let Q=$.headers.get("Content-Encoding");if(Q&&Q.trim().toLowerCase()!=="identity")return!1;if(sJ($.headers.get("Cache-Control"),"no-transform"))return!1;let H=$.headers.get("Content-Length");if(H!==null&&Number(H)<oJ)return!1;return!0}function J2(J){let $=J==="br"?pJ({params:{[k.BROTLI_PARAM_QUALITY]:nJ,[k.BROTLI_PARAM_LGWIN]:iJ},flush:k.BROTLI_OPERATION_FLUSH}):dJ({level:aJ,flush:k.Z_SYNC_FLUSH});return cJ.toWeb($)}function $2(J){let $=J.get("Vary");if(!$){J.set("Vary","Accept-Encoding");return}let Z=$.split(",").map((Q)=>Q.trim().toLowerCase());if(Z.includes("*")||Z.includes("accept-encoding"))return;J.append("Vary","Accept-Encoding")}function ZJ(J,$){if(!eJ(J.method,$))return $;let Z=new Headers($.headers);$2(Z);let Q=p(J.headers.get("Accept-Encoding"));if(!Q)return new Response($.body,{status:$.status,statusText:$.statusText,headers:Z});let H;try{H=J2(Q)}catch{return new Response($.body,{status:$.status,statusText:$.statusText,headers:Z})}return Z.set("Content-Encoding",Q),Z.delete("Content-Length"),new Response($.body.pipeThrough(H),{status:$.status,statusText:$.statusText,headers:Z})}import{readdir as W2,stat as VJ}from"fs/promises";import{join as G2}from"path";import{mkdir as R2,readFile as Z2,stat as T2,writeFile as S2}from"fs/promises";import{dirname as q2,join as Q2}from"path";import{promisify as QJ}from"util";import{brotliCompress as X2,constants as w2,gzip as H2}from"zlib";var j2=".vite/static-assets.json";var XJ={br:".br",gzip:".gz"},Y2=["br","gzip"],k2=QJ(X2),y2=QJ(H2);async function HJ(J){let $;try{$=await Z2(Q2(J,j2),"utf8")}catch{return null}let Z;try{Z=JSON.parse($)?.files}catch{return null}if(!Z||typeof Z!=="object")return null;let Q={files:{}};for(let[H,j]of Object.entries(Z)){if(!Array.isArray(j))continue;Q.files[H]=Y2.filter((Y)=>j.includes(Y))}return Q}function d(J){let $=J.toString(),Z=new Bun.CryptoHasher("sha1");return Z.update($),Z.digest("hex")}async function zJ(J){let $=new Set;async function Z(Q,H){let j;try{j=await W2(Q,{withFileTypes:!0})}catch{return}for(let Y of j){if(Y.name.startsWith("."))continue;if(H&&Y.name==="assets")continue;let W=G2(Q,Y.name),V=Y.isDirectory(),z=Y.isFile();if(Y.isSymbolicLink())try{let C=await VJ(W);V=C.isDirectory(),z=C.isFile()}catch{continue}if(z)$.add(W);else if(V&&!Y.isSymbolicLink())await Z(W,!1)}}return await Z(J,!0),$}var V2="public, max-age=31536000, must-revalidate",z2="public, max-age=31536000, immutable";async function U2(J,$,Z){if(Z.length===0||J.headers.has("Range"))return null;let Q=p(J.headers.get("Accept-Encoding"),Z);if(!Q)return null;let H=$+XJ[Q];try{let j=await VJ(H);return j.isFile()?{encoding:Q,path:H,size:j.size}:null}catch{return null}}async function UJ(J,$,Z={}){let Q=Bun.file($),H=Z.encodings??[],j={"Content-Type":Q.type||"application/octet-stream","Cache-Control":Z.immutable?z2:V2,"Accept-Ranges":"bytes"};if(H.length>0)j.Vary="Accept-Encoding";let Y=await U2(J,$,H);if(Y){let z=Bun.file(Y.path);return new Response(z.stream(),{headers:{...j,"Content-Encoding":Y.encoding,"Content-Length":String(Y.size),ETag:`${d(z.lastModified)}-${Y.encoding}`}})}let W=Q.size;j.ETag=d(Q.lastModified);let V=jJ(J.headers.get("Range"));if(V){let z=YJ(V,W);if(!z)return GJ(W);return new Response(Q.slice(z.start,z.end+1).stream(),{status:206,headers:{...j,"Content-Range":WJ(z.start,z.end,W),"Content-Length":String(z.length)}})}return new Response(Q.stream(),{headers:{...j,"Content-Length":String(W)}})}import{stat as I2}from"fs/promises";var y="app/client.tsx";function OJ(J,$=E){let Z=J[y]?.file;if(!Z)return;return{module:T(Z,$),preload:R(J,y,$)}}function R(J,$,Z=E){let Q=[],H=new Set,j=(Y)=>{if(H.has(Y))return;H.add(Y);let W=J[Y];if(!W?.file)return;Q.push(T(W.file,Z));for(let V of W.imports??[])j(V)};return j($),Q}function K2(J,$,Z=E){let Q=new Set(R(J,$,Z)),H=[],j=new Set,Y=(V)=>{if(j.has(V))return;j.add(V);let z=J[V];if(!z)return;for(let C of z.dynamicImports??[])if(!/(^|\/)node_modules\//.test(C)&&!H.includes(C))H.push(C);for(let C of z.imports??[])Y(C)};Y($);let W=[];for(let V of H)for(let z of R(J,V,Z))if(!Q.has(z))Q.add(z),W.push(z);return W}function xJ(J,$){let Z=[],Q=new Set,H=new Set,j=(Y)=>{if(H.has(Y))return;H.add(Y);let W=J[Y];if(!W)return;for(let V of W.imports??[])j(V);for(let V of W.css??[])if(!Q.has(V))Q.add(V),Z.push(V)};return j($),Z}function CJ(J,$=E){let Z=new Map;return(Q)=>{if(!Z.has(Q)){let H=`${Q}${KJ}`,j=J[H]?.file;Z.set(Q,j?{src:T(j,$),preload:R(J,H,$),dynamicPreload:K2(J,H,$)}:void 0)}return Z.get(Q)}}var LJ="x-gemi-build";var O2="__gemiReload";function x2(J,$,Z,Q){let H=Date.now(),j=function(U){return typeof U==="number"&&H-U>=0&&H-U<Z},Y=function(U){try{let K=U?JSON.parse(U):null;return K&&typeof K==="object"&&!Array.isArray(K)?K:{}}catch{return{}}},W=function(U){let K={};for(let M in U)if(j(U[M]))K[M]=U[M];return K},V=function(U){let K=2166136261;for(let M=0;M<U.length;M++)K=Math.imul(K^U.charCodeAt(M),16777619);return(K>>>0).toString(36)},z=null,C={};try{z=window.sessionStorage,C=Y(z.getItem(J))}catch{z=null}let N=J+":",F="",I="";try{let U=new URL($,window.location.href);F=V(new URL(window.location.href).origin),I=V(U.origin+U.pathname)}catch{}let L=null;try{let U=window.name;if(!I)L=null;else if(U==="")L={};else if(U.indexOf(N)===0){let K=Y(U.slice(N.length)),M=K.m;L=K.o===F&&M&&typeof M==="object"&&!Array.isArray(M)?M:{}}}catch{L=null}if(Q==="tidy"){try{let U=window.name;if(L===null||U.indexOf(N)!==0)return"ok";for(let K in L)if(j(L[K]))return"cooldown";window.name=""}catch{}return"ok"}if(j(C[$])||L&&j(L[I]))return"cooldown";if(!z&&!L)return"storage";if(!Q)return"ok";if(z)try{let U=W(C);U[$]=H;let K=JSON.stringify(U);if(z.setItem(J,K),z.getItem(J)===K)return"ok"}catch{}if(L)try{let U=W(L);U[I]=H;let K=N+JSON.stringify({o:F,m:U});if(window.name=K,window.name===K)return"ok"}catch{}return"storage"}function _J(J,$=30000){let Z=JSON.stringify("gemi:chunk-reload"),Q=JSON.stringify(`Failed to fetch dynamically imported module: ${J}`);return`var g=${x2.toString()};var r=!1;try{r=navigator.onLine!==!1&&g(${Z},window.location.href,${Number($)},!0)==="ok"}catch(e){}if(r)window.location.reload();else throw new Error(${Q});export {r as ${O2}}`}var C2=new RegExp(`^${IJ}/.+\\.m?js$`);function l(J){return C2.test(J)}function MJ(J){if(l(J))return new Response(_J(J),{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store"}});if(g(J))return new Response("Not found",{status:404});return}function NJ(J){let $=J?.trim();if(!$)return;try{let Z=new URL($);if(Z.protocol!=="https:"&&Z.protocol!=="http:")throw Error("not http(s)");return Z.search="",Z.hash="",Z.href.endsWith("/")?Z.href:`${Z.href}/`}catch{console.error(`GEMI_ASSET_FALLBACK_URL is not an absolute http(s) URL (${JSON.stringify($)}); missing assets are not looked up anywhere else.`);return}}function FJ({base:J,timeoutMs:$=3000,missTtlMs:Z=30000,fetch:Q=fetch,now:H=Date.now}){let j=new Map,Y=(W)=>{if(j.delete(W),j.set(W,H()+Z),j.size>1000)j.delete(j.keys().next().value)};return async(W,V)=>{if(W.method!=="GET"&&W.method!=="HEAD")return;let z=j.get(V);if(z!==void 0){if(z>H())return;j.delete(V)}let C;try{C=new URL(V.replace(/^\/+/,""),J)}catch{return}if(!C.href.startsWith(J))return;let N=new AbortController,F=setTimeout(()=>N.abort(),$),I;try{I=await Q(C.href,{method:W.method,signal:N.signal,redirect:"error"})}catch{Y(V);return}finally{clearTimeout(F)}if(I.status!==200){I.body?.cancel().catch(()=>{}),Y(V);return}let L=Bun.file(V).type,U=new Headers({"Content-Type":L!=="application/octet-stream"&&L||I.headers.get("content-type")||"application/octet-stream","Cache-Control":"public, max-age=31536000, immutable",["x-gemi-asset-fallback"]:"1"}),K=I.headers.get("content-length");if(K&&!I.headers.get("content-encoding"))U.set("Content-Length",K);return new Response(W.method==="HEAD"?null:I.body,{status:200,headers:U})}}var L2=`<!DOCTYPE html>
3
3
  <html lang="en">
4
4
  <head>
5
5
  <meta charset="UTF-8" />
@@ -8,7 +8,7 @@
8
8
  "import { mkdir, readFile, stat, writeFile } from \"node:fs/promises\";\nimport { availableParallelism } from \"node:os\";\nimport { dirname, join } from \"node:path\";\nimport { promisify } from \"node:util\";\nimport { brotliCompress, constants, gzip } from \"node:zlib\";\n\nimport type { ContentEncoding } from \"../server/compression\";\n\n/**\n * Build-time compression of the client bundle (#789).\n *\n * `gemi start` compresses SSR HTML per request, but a hashed chunk is the same\n * bytes for the life of a release, so compressing it per request would spend\n * origin CPU on every visitor for a result that never changes. `gemi build`\n * writes `file.br` (brotli quality 11) and `file.gz` (gzip level 9) next to\n * every compressible build asset instead, once, and the server picks one by\n * `Accept-Encoding`.\n *\n * What the build emitted (and what it carried over from earlier releases, see\n * `previousAssets.ts`) is recorded in `dist/client/.vite/static-assets.json`,\n * with the encodings each file has. The server reads it at boot: a file in the\n * record is a content-hashed build asset, so it is sent as `immutable`, and\n * only the encodings listed for it are offered. A file not in the record (one\n * copied from `public/assets/`, or anything in a build made before this\n * existed) is served as before.\n */\n\n/** Relative to `dist/client`; beside Vite's own manifest, so never served. */\nexport const STATIC_ASSETS_RECORD = \".vite/static-assets.json\";\n\n/**\n * Below this, the encoded body plus its header is not worth a second request\n * representation: a 600-byte chunk saves a few hundred bytes at most, and\n * every file with siblings adds a `stat` per request.\n */\nexport const PRECOMPRESS_MIN_BYTES = 1024;\n\n/**\n * Text-like formats that compress well. Already-compressed formats (images,\n * `woff`/`woff2`, video) are left out: brotli shaves a percent or two off\n * them at best. Source maps are left out because a page never loads one, and\n * only devtools would gain from the extra build time.\n */\nconst COMPRESSIBLE = /\\.(?:m?js|cjs|css|svg|json|webmanifest|wasm|txt|xml|ttf|otf|eot)$/i;\n\nconst TEXT = /\\.(?:m?js|cjs|css|svg|json|webmanifest|txt|xml)$/i;\nconst FONT = /\\.(?:ttf|otf|eot)$/i;\n\nexport const SIBLING_EXTENSION: Record<ContentEncoding, string> = {\n br: \".br\",\n gzip: \".gz\",\n};\n\n/** Server preference: brotli is ~15% smaller than gzip -9 on a JS chunk. */\nconst ENCODINGS: ContentEncoding[] = [\"br\", \"gzip\"];\n\nexport interface StaticAssetsRecord {\n /**\n * Path relative to `dist/client` (`assets/client-DJhrQPW5.js`) → the\n * precompressed siblings it has, in preference order. An empty list is a\n * build asset that is served as identity only (an image, a small file).\n */\n files: Record<string, ContentEncoding[]>;\n}\n\nexport interface PrecompressStats {\n files: number;\n identityBytes: number;\n brBytes: number;\n gzipBytes: number;\n}\n\nconst brotli = promisify(brotliCompress);\nconst gzipAsync = promisify(gzip);\n\nexport function isPrecompressible(file: string): boolean {\n return COMPRESSIBLE.test(file);\n}\n\n/** `true` for `x.js.br` / `x.js.gz`: a sibling, not an asset of its own. */\nexport function isEncodedSibling(file: string): boolean {\n return file.endsWith(\".br\") || file.endsWith(\".gz\");\n}\n\nasync function encode(encoding: ContentEncoding, file: string, input: Buffer): Promise<Buffer> {\n if (encoding === \"gzip\") {\n return gzipAsync(input, { level: 9 });\n }\n return brotli(input, {\n params: {\n [constants.BROTLI_PARAM_QUALITY]: constants.BROTLI_MAX_QUALITY,\n [constants.BROTLI_PARAM_MODE]: TEXT.test(file)\n ? constants.BROTLI_MODE_TEXT\n : FONT.test(file)\n ? constants.BROTLI_MODE_FONT\n : constants.BROTLI_MODE_GENERIC,\n [constants.BROTLI_PARAM_SIZE_HINT]: input.length,\n },\n });\n}\n\nasync function fileSize(path: string): Promise<number | null> {\n try {\n const info = await stat(path);\n return info.isFile() ? info.size : null;\n } catch {\n return null;\n }\n}\n\n/**\n * Writes the `.br`/`.gz` siblings of `files` (paths relative to `clientDir`)\n * and returns the encodings each one ended up with.\n *\n * A sibling is only kept when it is smaller than the file itself; one that is\n * not would cost bytes on the wire, so the file is served as identity for\n * that encoding. With `reuseExisting`, a sibling already on disk is trusted\n * rather than rebuilt — for files carried from an earlier release, whose\n * siblings were copied with them and match by content hash.\n */\nexport async function precompressAssets(\n clientDir: string,\n files: Iterable<string>,\n options: {\n reuseExisting?: boolean;\n minBytes?: number;\n concurrency?: number;\n } = {},\n): Promise<{ record: StaticAssetsRecord; stats: PrecompressStats }> {\n const minBytes = options.minBytes ?? PRECOMPRESS_MIN_BYTES;\n const record: StaticAssetsRecord = { files: {} };\n const stats: PrecompressStats = {\n files: 0,\n identityBytes: 0,\n brBytes: 0,\n gzipBytes: 0,\n };\n\n const queue = [...new Set(files)];\n for (const file of queue) {\n record.files[file] = [];\n }\n\n async function work(file: string) {\n if (!isPrecompressible(file)) {\n return;\n }\n const path = join(clientDir, file);\n const size = await fileSize(path);\n if (size === null || size < minBytes) {\n return;\n }\n\n let input: Buffer | null = null;\n const available: ContentEncoding[] = [];\n const sizes: Partial<Record<ContentEncoding, number>> = {};\n for (const encoding of ENCODINGS) {\n const siblingPath = path + SIBLING_EXTENSION[encoding];\n const existing = options.reuseExisting ? await fileSize(siblingPath) : null;\n if (existing !== null) {\n if (existing < size) {\n available.push(encoding);\n sizes[encoding] = existing;\n }\n continue;\n }\n input ??= await readFile(path);\n const output = await encode(encoding, file, input);\n if (output.length < size) {\n await writeFile(siblingPath, output);\n available.push(encoding);\n sizes[encoding] = output.length;\n }\n }\n\n record.files[file] = available;\n if (available.length > 0) {\n stats.files += 1;\n stats.identityBytes += size;\n stats.brBytes += sizes.br ?? size;\n stats.gzipBytes += sizes.gzip ?? size;\n }\n }\n\n // zlib's async calls run on the libuv thread pool; a few files in flight\n // keep it busy without reading the whole bundle into memory at once.\n const concurrency = Math.max(1, options.concurrency ?? Math.min(8, availableParallelism()));\n let next = 0;\n await Promise.all(\n Array.from({ length: Math.min(concurrency, queue.length) }, async () => {\n while (next < queue.length) {\n await work(queue[next++]);\n }\n }),\n );\n\n return { record, stats };\n}\n\nexport async function writeStaticAssetsRecord(clientDir: string, record: StaticAssetsRecord) {\n const path = join(clientDir, STATIC_ASSETS_RECORD);\n await mkdir(dirname(path), { recursive: true });\n // Sorted, so two builds of the same tree write the same file.\n const files = Object.fromEntries(\n Object.entries(record.files).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)),\n );\n await writeFile(path, `${JSON.stringify({ files }, null, 2)}\\n`);\n}\n\n/**\n * The record a build wrote, or `null` when there is none (a build made before\n * precompression, or an incomplete `dist/`): the server then serves every file\n * as before. A malformed entry is dropped rather than trusted.\n */\nexport async function readStaticAssetsRecord(\n clientDir: string,\n): Promise<StaticAssetsRecord | null> {\n let raw: string;\n try {\n raw = await readFile(join(clientDir, STATIC_ASSETS_RECORD), \"utf8\");\n } catch {\n return null;\n }\n let files: unknown;\n try {\n files = JSON.parse(raw)?.files;\n } catch {\n return null;\n }\n if (!files || typeof files !== \"object\") {\n return null;\n }\n const record: StaticAssetsRecord = { files: {} };\n for (const [file, encodings] of Object.entries(files)) {\n if (!Array.isArray(encodings)) continue;\n record.files[file] = ENCODINGS.filter((encoding) => encodings.includes(encoding));\n }\n return record;\n}\n",
9
9
  "export function generateETag(lastModified: number): string {\n // Assuming the last modified timestamp is in milliseconds\n const lastModifiedStr = lastModified.toString();\n\n const hasher = new Bun.CryptoHasher(\"sha1\");\n hasher.update(lastModifiedStr);\n const hash = hasher.digest(\"hex\");\n\n return hash;\n}\n",
10
10
  "import { DEFAULT_ASSET_BASE, assetUrl } from \"../config/assetBase\";\nimport { ISLAND_ENTRY_QUERY } from \"../internal/islandRuntime\";\n\n/** The subset of a Vite manifest entry this module reads. */\nexport interface ViteManifestChunk {\n file: string;\n imports?: string[];\n dynamicImports?: string[];\n}\n\nexport type ViteManifest = Record<string, ViteManifestChunk>;\n\n/** Vite's manifest key for the module that boots hydration. */\nexport const CLIENT_ENTRY_KEY = \"app/client.tsx\";\n\n/**\n * How the shell boots hydration in production: `module` is imported from the\n * bootstrap script, `preload` is every chunk that import pulls in — see\n * `clientEntry` in `ViewRouteDispatcher` for why the entry does not go through\n * React's `bootstrapModules`.\n *\n * `undefined` when the manifest has no client entry, which means a `dist/`\n * interrupted between the server and client build passes. Degrading beats\n * throwing here: this runs at boot, so a deref would take down API routes,\n * static assets and health checks over what is only a document concern, and\n * the dispatcher already renders a shell that simply does not hydrate.\n *\n * `assetBase` is the base the client build recorded — see `readBuiltAssetBase`.\n */\nexport function createClientEntry(\n manifest: ViteManifest,\n assetBase: string = DEFAULT_ASSET_BASE,\n): { module: string; preload: string[] } | undefined {\n const file = manifest[CLIENT_ENTRY_KEY]?.file;\n if (!file) {\n return undefined;\n }\n return {\n module: assetUrl(file, assetBase),\n preload: collectModulePreloads(manifest, CLIENT_ENTRY_KEY, assetBase),\n };\n}\n\n/**\n * Every chunk URL that importing `entryKey` pulls in, itself first.\n *\n * The browser can only discover these one parse at a time — it learns about a\n * chunk's static imports after the chunk has arrived and been parsed — so a\n * `layout -> view -> child component` graph costs one round trip per level.\n * Handing the whole list to the shell as `modulepreload` hints turns that\n * chain into one parallel fetch (#352).\n *\n * `dynamicImports` are deliberately left out: those are the pieces the app\n * asked to load lazily, and preloading them would download code the current\n * route may never render.\n */\nexport function collectModulePreloads(\n manifest: ViteManifest,\n entryKey: string,\n assetBase: string = DEFAULT_ASSET_BASE,\n): string[] {\n const urls: string[] = [];\n // Chunk graphs are cyclic often enough (two chunks importing each other\n // through a shared module) that walking them without a visited set hangs.\n const visited = new Set<string>();\n\n const walk = (key: string) => {\n if (visited.has(key)) return;\n visited.add(key);\n const chunk = manifest[key];\n if (!chunk?.file) return;\n urls.push(assetUrl(chunk.file, assetBase));\n for (const imported of chunk.imports ?? []) {\n walk(imported);\n }\n };\n\n walk(entryKey);\n\n return urls;\n}\n\n/**\n * The chunks the static import closure of `entryKey` loads lazily, each with\n * its own static closure, minus what that closure already has: every\n * `import()` in the entry's code (and its static dependencies'), one level\n * deep. An island with `preloadDynamic` gets these preloaded too (#932).\n *\n * Dynamic imports into `node_modules` are left out: those are a library's own\n * lazy pieces (gemi's client loads a few on first use), not the app's.\n */\nexport function collectDynamicPreloads(\n manifest: ViteManifest,\n entryKey: string,\n assetBase: string = DEFAULT_ASSET_BASE,\n): string[] {\n const seen = new Set(collectModulePreloads(manifest, entryKey, assetBase));\n const targets: string[] = [];\n const visited = new Set<string>();\n\n const walk = (key: string) => {\n if (visited.has(key)) return;\n visited.add(key);\n const chunk = manifest[key];\n if (!chunk) return;\n for (const target of chunk.dynamicImports ?? []) {\n if (!/(^|\\/)node_modules\\//.test(target) && !targets.includes(target)) {\n targets.push(target);\n }\n }\n for (const imported of chunk.imports ?? []) {\n walk(imported);\n }\n };\n walk(entryKey);\n\n const urls: string[] = [];\n for (const target of targets) {\n for (const url of collectModulePreloads(manifest, target, assetBase)) {\n if (!seen.has(url)) {\n seen.add(url);\n urls.push(url);\n }\n }\n }\n return urls;\n}\n\n/**\n * Every CSS file the static import closure of `entryKey` carries, in import\n * order and without repeats. Vite lists a chunk's CSS on that chunk only, not\n * on the entries that import it, so a page with no client router to load the\n * rest (a static view) has to walk the graph for it.\n */\nexport function collectCss(manifest: ViteManifest, entryKey: string): string[] {\n const files: string[] = [];\n const seen = new Set<string>();\n const visited = new Set<string>();\n\n const walk = (key: string) => {\n if (visited.has(key)) return;\n visited.add(key);\n const chunk = manifest[key] as ViteManifestChunk & { css?: string[] };\n if (!chunk) return;\n for (const imported of chunk.imports ?? []) {\n walk(imported);\n }\n for (const file of chunk.css ?? []) {\n if (!seen.has(file)) {\n seen.add(file);\n files.push(file);\n }\n }\n };\n\n walk(entryKey);\n return files;\n}\n\n/**\n * Where a static page's islands load from: each island module's entry\n * (`<key>?gemi-island`, the module plus the hydrate function), with the\n * chunks importing it pulls in, itself first. React and `react-dom/client`\n * are among those. `dynamicPreload` is what the entry loads lazily (see\n * `collectDynamicPreloads`), for an island with `preloadDynamic`.\n * `undefined` for a module the client build has no island entry for.\n */\nexport function createIslandResolver(\n manifest: ViteManifest,\n assetBase: string = DEFAULT_ASSET_BASE,\n): (moduleKey: string) => { src: string; preload: string[]; dynamicPreload: string[] } | undefined {\n const cache = new Map<\n string,\n { src: string; preload: string[]; dynamicPreload: string[] } | undefined\n >();\n return (moduleKey) => {\n if (!cache.has(moduleKey)) {\n const key = `${moduleKey}${ISLAND_ENTRY_QUERY}`;\n const file = manifest[key]?.file;\n cache.set(\n moduleKey,\n file\n ? {\n src: assetUrl(file, assetBase),\n preload: collectModulePreloads(manifest, key, assetBase),\n dynamicPreload: collectDynamicPreloads(manifest, key, assetBase),\n }\n : undefined,\n );\n }\n return cache.get(moduleKey);\n };\n}\n",
11
- "/**\n * Recovery from a chunk that will not load — almost always a document from an\n * earlier release asking for a chunk the server it reached no longer has\n * (#548). The page cannot continue with the module it wanted, and a full load\n * of the URL it was heading to gets it the current release's document.\n *\n * One reload per page, guarded: a reload that lands on the same failure (a\n * chunk that is genuinely missing, a proxy that keeps refusing it) must not\n * become a loop. A `sessionStorage` marker records when each URL was reloaded\n * onto and survives the reload it guards, so a second failure for the same URL\n * inside the cooldown is left to the route's error boundary. Per URL rather\n * than per tab (#1056): while two releases serve at once every navigation can\n * miss, and a tab-wide cooldown sent the second one to the error boundary.\n * Where `sessionStorage` cannot be used, the marker lives in `window.name`\n * instead (#1186); see `chunkReloadGuard`.\n *\n * The same guard covers a navigation whose data came from another build\n * (`recoverFromBuildMismatch`).\n *\n * No DOM or React import at module scope: the server's reload stub\n * (`server/staticAssetMiss.ts`) embeds the same guard as a script.\n */\n\n/** The `sessionStorage` key the guard lives under, shared with the reload stub. */\nexport const CHUNK_RELOAD_MARKER = \"gemi:chunk-reload\";\n\n/**\n * The response header carrying the client build id on a `.json` navigation\n * (#1056). The document carries its own as `buildId`; they differ when the\n * request reached a server running another release.\n */\nexport const BUILD_HEADER = \"x-gemi-build\";\n\n/** How long after a recovery reload onto a URL another one onto it is refused. */\nexport const DEFAULT_CHUNK_RELOAD_COOLDOWN_MS = 30_000;\n\n/**\n * Where the failure surfaced: a route's view chunk during a client-side\n * navigation or hydration, a `vite:preloadError` (a lazy `import()` in app\n * code, through Vite's preload helper), or an app calling\n * `recoverFromChunkLoadError` from its own error boundary.\n */\nexport type ChunkLoadErrorSource = \"navigation\" | \"hydration\" | \"preload\" | \"app\";\n\n/**\n * Why gemi will not reload, or `null` when it will:\n * - `cooldown`: it already reloaded onto this URL within `cooldownMs`.\n * - `offline`: `navigator.onLine` is false — a reload would only fail harder.\n * - `storage`: neither `sessionStorage` nor the `window.name` fallback can\n * hold the guard, so it cannot survive the reload and the loop it prevents\n * could not be ruled out.\n */\nexport type ChunkReloadBlock = \"cooldown\" | \"offline\" | \"storage\" | null;\n\nexport interface ChunkLoadErrorContext {\n error: unknown;\n /** The URL the reload goes to: the page being navigated to. */\n url: string;\n source: ChunkLoadErrorSource;\n /** Why gemi will not reload, or `null` when it is about to. */\n blocked: ChunkReloadBlock;\n}\n\nexport interface BuildMismatchContext {\n /** The URL the full page load goes to: the page being navigated to. */\n url: string;\n /** The build the page was loaded with. */\n clientBuild: string;\n /** The build that answered the navigation. */\n serverBuild: string;\n /** Why gemi will not reload, or `null` when it is about to. */\n blocked: ChunkReloadBlock;\n}\n\nexport interface ChunkLoadRecoveryOptions {\n /** Default 30 000 ms. */\n cooldownMs?: number;\n /**\n * Called for every chunk load failure gemi sees, before it reloads — the\n * place to report it, or to veto the reload (unsaved input, a page that\n * would rather show its own \"a new version is available\" prompt). Return\n * `false` to skip the reload; anything else lets gemi proceed. It is called\n * when the reload is blocked too, with `blocked` saying why.\n */\n onChunkLoadError?: (context: ChunkLoadErrorContext) => boolean | void;\n /**\n * Called when a client-side navigation's data came from another build (a\n * deploy in progress, two releases behind one load balancer), before gemi\n * loads the page in full. Return `false` to skip that and render the data\n * anyway. Called when the load is blocked too, with `blocked` saying why.\n */\n onBuildMismatch?: (context: BuildMismatchContext) => boolean | void;\n}\n\nlet enabled = true;\nlet options: ChunkLoadRecoveryOptions = {};\n/**\n * The full load gemi started and the page is still waiting on: further\n * failures of the same navigation (a route with several views fails once per\n * view) report it as under way instead of starting another.\n *\n * Not a latch for the life of the page: the load can be cancelled — \"Stay\" on\n * a `beforeunload` prompt (a dirty editor), a handler that stops it — and the\n * page then keeps running with no load coming. It holds only for the\n * navigation that started it (`navigationStarted` clears it) and for the\n * cooldown, so a later failure is judged on its own: another URL loads in\n * full, the same URL inside the cooldown is refused (the data renders, the\n * view's error boundary shows), and after the cooldown it loads again.\n */\nlet pendingLoad: { url: string; at: number } | null = null;\n\n/**\n * Sets how gemi recovers from a failed chunk. `false` turns recovery off: the\n * failure goes to the route's error boundary as it did before. `init` calls\n * this with its `chunkLoadRecovery` option.\n */\nexport function configureChunkLoadRecovery(next: ChunkLoadRecoveryOptions | false | undefined) {\n enabled = next !== false;\n options = next || {};\n tidyWindowName();\n}\n\n/** For tests: back to the defaults, with no reload in flight. */\nexport function __resetChunkLoadRecovery() {\n enabled = true;\n options = {};\n pendingLoad = null;\n clearTimeout(tidyTimer);\n tidyTimer = undefined;\n}\n\n/**\n * The router calls this as each client-side navigation starts. A full load\n * still pending from an earlier one was cancelled (the page would be gone\n * otherwise), so it no longer speaks for this navigation's failures.\n */\nexport function navigationStarted() {\n pendingLoad = null;\n}\n\n/** Whether a full load onto `url` is already under way. */\nfunction loadPending(url: string): boolean {\n return (\n pendingLoad !== null &&\n pendingLoad.url === url &&\n withinCooldown(Date.now() - pendingLoad.at, cooldownMs())\n );\n}\n\n/**\n * Whether `error` is a module that failed to load rather than one that loaded\n * and threw. Each engine words it differently:\n *\n * - Chromium: `Failed to fetch dynamically imported module: <url>`\n * - Firefox: `error loading dynamically imported module: <url>`\n * - Safari: `Importing a module script failed.`, and on iOS 16\n * `Importing module '<specifier>' is not found.` (folio#2117)\n * - Vite's preload helper: `Unable to preload CSS for <url>`\n *\n * A view that throws while evaluating is not one of these, and reloading\n * would only hide it.\n */\nexport function isChunkLoadError(error: unknown): boolean {\n if (!error || typeof error !== \"object\") {\n return false;\n }\n const { name, message } = error as { name?: unknown; message?: unknown };\n if (name === \"ChunkLoadError\") {\n return true;\n }\n if (typeof message !== \"string\") {\n return false;\n }\n return CHUNK_LOAD_MESSAGES.some((pattern) => pattern.test(message));\n}\n\nconst CHUNK_LOAD_MESSAGES = [\n /failed to fetch dynamically imported module/i,\n /error loading dynamically imported module/i,\n /importing a module script failed/i,\n /importing module .* is not found/i,\n /unable to preload css/i,\n /failed to load module script/i,\n // A chunk that loaded but whose dependency came from another build: the\n // dependency's URL answered with the server's reload stub (or another\n // release's file), which lacks the named export the chunk imports, so the\n // module graph fails to link before any of it runs — the stub's own reload\n // never gets the chance. A production build's chunks only import names their\n // own build exports, so outside a mixed deploy this does not happen.\n // - Chromium: `The requested module './index-x.js' does not provide an export named 'a'`\n // - Firefox: `The requested module './index-x.js' doesn't provide an export named: 'a'`,\n // older releases `import not found: a`\n // - Safari: `Importing binding name 'a' is not found.`\n /requested module .* (does not|doesn't) provide an export named/i,\n /^import not found: /i,\n /importing binding name .* is not found/i,\n];\n\n/**\n * The export the server's reload stub carries, true when the stub started a\n * reload. A view chunk answered by the stub then evaluates to a module with no\n * `default`, and rendering it would put the route's error boundary on screen\n * for the moment before the page goes away.\n */\nexport const RELOAD_STUB_EXPORT = \"__gemiReload\";\n\n/**\n * How long a view waits on a full load gemi started before it gives up and\n * fails after all. The load can be cancelled (\"Stay\" on a `beforeunload`\n * prompt), and the page must not sit on its loading state for good then.\n */\nexport const RELOAD_WAIT_MS = 15_000;\n\n/**\n * A promise for a view whose page is being loaded in full: it stays pending,\n * so the route keeps its `Loading` fallback (or the server's HTML) instead of\n * flashing its error boundary while the reload is under way, and rejects with\n * `error` only if the page is still here after `RELOAD_WAIT_MS`.\n */\nexport function waitForReload(error: unknown, ms: number = RELOAD_WAIT_MS): Promise<never> {\n return new Promise((_, reject) => {\n setTimeout(() => reject(error), ms);\n });\n}\n\n/**\n * Reloads the page onto `url` once for a chunk that failed to load, unless the\n * guard or the app's `onChunkLoadError` says not to. Returns whether a reload\n * was started.\n *\n * Errors that are not chunk failures are ignored (`false`), so an app's error\n * boundary can pass everything it catches here.\n */\nexport function recoverFromChunkLoadError(\n error: unknown,\n { source = \"app\", url }: { source?: ChunkLoadErrorSource; url?: string } = {},\n): boolean {\n if (typeof window === \"undefined\" || !enabled || !isChunkLoadError(error)) {\n return false;\n }\n const target = url ?? window.location.href;\n if (loadPending(target)) {\n // A route with several views fails once per view; the first one reloads.\n return true;\n }\n const blocked = reloadBlock(target);\n\n if (options.onChunkLoadError?.({ error, url: target, source, blocked }) === false) {\n return false;\n }\n return loadInFull(target, blocked);\n}\n\n/**\n * Loads `url` in full because the navigation to it got its data from another\n * build (#1056): the views this page runs were not written for that data, and\n * rendering it anyway is how a deploy turned into \"Something went wrong\". The\n * full load gets a document and views of one build. Same guard as a chunk\n * failure, once per URL per cooldown; a navigation refused here renders the\n * data as before. Returns whether the page load was started.\n */\nexport function recoverFromBuildMismatch({\n url,\n clientBuild,\n serverBuild,\n}: {\n url: string;\n clientBuild: string;\n serverBuild: string;\n}): boolean {\n if (typeof window === \"undefined\" || !enabled) {\n return false;\n }\n if (loadPending(url)) {\n return true;\n }\n const blocked = reloadBlock(url);\n if (options.onBuildMismatch?.({ url, clientBuild, serverBuild, blocked }) === false) {\n return false;\n }\n return loadInFull(url, blocked);\n}\n\n/**\n * The build that answered a `.json` navigation, when it is not `clientBuild`;\n * otherwise `null`. Unknown on either side (dev, a test double, a server from\n * before the header) is not a mismatch.\n */\nexport function otherBuild(response: Response, clientBuild: string | undefined): string | null {\n const served = response.headers?.get?.(BUILD_HEADER);\n return clientBuild && served && served !== clientBuild ? served : null;\n}\n\nfunction loadInFull(target: string, blocked: ChunkReloadBlock): boolean {\n if (blocked !== null || !markReload(target)) {\n return false;\n }\n\n pendingLoad = { url: target, at: Date.now() };\n if (target === window.location.href) {\n window.location.reload();\n } else {\n window.location.assign(target);\n }\n return true;\n}\n\nfunction cooldownMs() {\n return options.cooldownMs ?? DEFAULT_CHUNK_RELOAD_COOLDOWN_MS;\n}\n\nfunction reloadBlock(url: string): ChunkReloadBlock {\n if (typeof navigator !== \"undefined\" && navigator.onLine === false) {\n return \"offline\";\n }\n const verdict = chunkReloadGuard(CHUNK_RELOAD_MARKER, url, cooldownMs(), false);\n return verdict === \"ok\" ? null : verdict;\n}\n\n// A marker from the future (the clock was set back since it was written) is\n// stale rather than a cooldown that lasts until the clock catches up.\nfunction withinCooldown(elapsed: number, cooldownMs: number): boolean {\n return elapsed >= 0 && elapsed < cooldownMs;\n}\n\nfunction markReload(url: string): boolean {\n if (chunkReloadGuard(CHUNK_RELOAD_MARKER, url, cooldownMs(), true) !== \"ok\") return false;\n // The load may yet be cancelled (\"Stay\" on a `beforeunload` prompt), and\n // then this page has to take the `window.name` marker down itself.\n tidyWindowName();\n return true;\n}\n\nlet tidyTimer: ReturnType<typeof setTimeout> | undefined;\n\n/**\n * Takes gemi's marker out of `window.name` (back to `\"\"`) once it guards\n * nothing (#1188): the page may want the name for itself, under the same\n * \"only while it is empty\" rule gemi follows. Now when nothing in it is live,\n * otherwise once the newest entry's cooldown has passed, checked again then\n * since a reload may have been recorded in the meantime. Only a name that\n * holds gemi's marker is ever cleared; see `chunkReloadGuard`'s `\"tidy\"`.\n */\nfunction tidyWindowName() {\n clearTimeout(tidyTimer);\n tidyTimer = undefined;\n if (typeof window === \"undefined\") return;\n let delay: number;\n try {\n if (chunkReloadGuard(CHUNK_RELOAD_MARKER, window.location.href, cooldownMs(), \"tidy\") !== \"cooldown\") {\n return;\n }\n const held = JSON.parse(window.name.slice(CHUNK_RELOAD_MARKER.length + 1));\n // An entry from the future (clock set back) is not live and holds nothing back.\n const now = Date.now();\n const latest = Math.max(\n ...Object.values(held.m).filter((at): at is number => typeof at === \"number\" && at <= now),\n );\n delay = latest + cooldownMs() - now;\n } catch {\n return;\n }\n if (!Number.isFinite(delay)) return;\n tidyTimer = setTimeout(tidyWindowName, Math.max(0, delay) + 1);\n}\n\n/**\n * The cross-document guard, shared by the client and the server's reload stub\n * (which embeds this function's source, so it uses nothing but globals and its\n * arguments). With `claim` false it only reads: `\"cooldown\"` when a reload\n * onto `url` was recorded inside `cooldownMs`, `\"storage\"` when no marker can\n * be read at all, otherwise `\"ok\"`. With `claim` true it also records the\n * reload, and answers `\"ok\"` only once the record was written and read back\n * unchanged; a caller navigates on nothing less. With `\"tidy\"` it only looks\n * at `window.name`: a gemi marker with no live entry for this origin (expired,\n * from the future, another origin's, or one that does not parse) is cleared\n * to `\"\"` and `\"ok\"` answered; `\"cooldown\"` while an entry is still live.\n *\n * Two places can hold the marker:\n *\n * - `sessionStorage[key]`: `{ [url]: at }`, the format earlier releases read\n * and write, so a page from one and a stub from another share the guard.\n * - `window.name`, when `sessionStorage` throws or will not take the write\n * (#1186). It survives a load in the same tab, but it is shared state: the\n * page may use it, and another origin the tab goes to can read it. So it is\n * used only while it is empty or already holds gemi's marker — a value of\n * anyone else's is left exactly as it is, and the guard then fails closed —\n * and it holds no URL: `key + \":\" + { o: hash(origin), m: { [hash(origin +\n * pathname)]: at } }`. A marker written by another origin (`o` differs) or\n * one that does not parse holds no reloads and is replaced on the next\n * write. Two paths whose hashes collide share one cooldown, which only ever\n * refuses a reload.\n *\n * A reload recorded in either place counts. Entries past the cooldown — and\n * from the future, after the clock was set back — are dropped as a new one is\n * written, so the marker holds only the reloads it still guards.\n */\nexport function chunkReloadGuard(\n key: string,\n url: string,\n cooldownMs: number,\n claim: boolean | \"tidy\",\n): \"ok\" | \"cooldown\" | \"storage\" {\n const now = Date.now();\n const fresh = function (at: unknown) {\n return typeof at === \"number\" && now - at >= 0 && now - at < cooldownMs;\n };\n const parse = function (raw: string | null): Record<string, unknown> {\n try {\n const value = raw ? JSON.parse(raw) : null;\n return value && typeof value === \"object\" && !Array.isArray(value) ? value : {};\n } catch {\n return {};\n }\n };\n const live = function (marker: Record<string, unknown>) {\n const kept: Record<string, number> = {};\n for (const k in marker) if (fresh(marker[k])) kept[k] = marker[k] as number;\n return kept;\n };\n // FNV-1a, 32 bits, base 36: a short tag, not a secret.\n const hash = function (text: string) {\n let h = 0x811c9dc5;\n for (let i = 0; i < text.length; i++) h = Math.imul(h ^ text.charCodeAt(i), 0x01000193);\n return (h >>> 0).toString(36);\n };\n\n let storage: Storage | null = null;\n let stored: Record<string, unknown> = {};\n try {\n storage = window.sessionStorage;\n stored = parse(storage.getItem(key));\n } catch {\n storage = null;\n }\n\n const prefix = key + \":\";\n let origin = \"\";\n let page = \"\";\n try {\n const target = new URL(url, window.location.href);\n origin = hash(new URL(window.location.href).origin);\n page = hash(target.origin + target.pathname);\n } catch {}\n // `null`: `window.name` is not ours to use (or there is no page to key on).\n let named: Record<string, unknown> | null = null;\n try {\n const name = window.name;\n if (!page) {\n named = null;\n } else if (name === \"\") {\n named = {};\n } else if (name.indexOf(prefix) === 0) {\n const held = parse(name.slice(prefix.length));\n const entries = held.m;\n named =\n held.o === origin && entries && typeof entries === \"object\" && !Array.isArray(entries)\n ? (entries as Record<string, unknown>)\n : {};\n }\n } catch {\n named = null;\n }\n\n if (claim === \"tidy\") {\n try {\n const current = window.name;\n if (named === null || current.indexOf(prefix) !== 0) return \"ok\";\n for (const k in named) if (fresh(named[k])) return \"cooldown\";\n window.name = \"\";\n } catch {}\n return \"ok\";\n }\n if (fresh(stored[url]) || (named && fresh(named[page]))) return \"cooldown\";\n if (!storage && !named) return \"storage\";\n if (!claim) return \"ok\";\n\n if (storage) {\n try {\n const nextStored = live(stored);\n nextStored[url] = now;\n const serialised = JSON.stringify(nextStored);\n storage.setItem(key, serialised);\n if (storage.getItem(key) === serialised) return \"ok\";\n } catch {}\n }\n if (named) {\n try {\n const nextNamed = live(named);\n nextNamed[page] = now;\n const value = prefix + JSON.stringify({ o: origin, m: nextNamed });\n window.name = value;\n if (window.name === value) return \"ok\";\n } catch {}\n }\n return \"storage\";\n}\n\n/**\n * The same guard as a classic script body, for the module the server sends in\n * place of a chunk it does not have. It reloads once per URL per cooldown;\n * inside the cooldown (or with no marker that would survive the reload) it\n * throws an error `isChunkLoadError` recognises, so the importing page's own\n * recovery and error boundary see the failure instead of a module that\n * silently has no exports. It runs `chunkReloadGuard` itself, so it and the\n * page's client share one marker and one reload between them. It exports\n * `RELOAD_STUB_EXPORT`, true when it reloaded, so the client can tell a view\n * answered by the stub from a view and wait for the reload instead of\n * rendering a module with no `default`.\n */\nexport function chunkReloadStubScript(\n pathname: string,\n cooldownMs: number = DEFAULT_CHUNK_RELOAD_COOLDOWN_MS,\n): string {\n const key = JSON.stringify(CHUNK_RELOAD_MARKER);\n const error = JSON.stringify(`Failed to fetch dynamically imported module: ${pathname}`);\n return (\n `var g=${chunkReloadGuard.toString()};var r=!1;` +\n `try{r=navigator.onLine!==!1&&g(${key},window.location.href,${Number(cooldownMs)},!0)===\"ok\"}catch(e){}` +\n `if(r)window.location.reload();else throw new Error(${error});export {r as ${RELOAD_STUB_EXPORT}}`\n );\n}\n",
11
+ "/**\n * Recovery from a chunk that will not load — almost always a document from an\n * earlier release asking for a chunk the server it reached no longer has\n * (#548). The page cannot continue with the module it wanted, and a full load\n * of the URL it was heading to gets it the current release's document.\n *\n * One reload per page, guarded: a reload that lands on the same failure (a\n * chunk that is genuinely missing, a proxy that keeps refusing it) must not\n * become a loop. A `sessionStorage` marker records when each URL was reloaded\n * onto and survives the reload it guards, so a second failure for the same URL\n * inside the cooldown is left to the route's error boundary. Per URL rather\n * than per tab (#1056): while two releases serve at once every navigation can\n * miss, and a tab-wide cooldown sent the second one to the error boundary.\n * Where `sessionStorage` cannot be used, the marker lives in `window.name`\n * instead (#1186); see `chunkReloadGuard`.\n *\n * The same guard covers a navigation whose data came from another build\n * (`recoverFromBuildMismatch`).\n *\n * No DOM or React import at module scope: the server's reload stub\n * (`server/staticAssetMiss.ts`) embeds the same guard as a script.\n */\n\n/** The `sessionStorage` key the guard lives under, shared with the reload stub. */\nexport const CHUNK_RELOAD_MARKER = \"gemi:chunk-reload\";\n\n/**\n * The response header carrying the client build id on a `.json` navigation\n * (#1056). The document carries its own as `buildId`; they differ when the\n * request reached a server running another release.\n */\nexport const BUILD_HEADER = \"x-gemi-build\";\n\n/** How long after a recovery reload onto a URL another one onto it is refused. */\nexport const DEFAULT_CHUNK_RELOAD_COOLDOWN_MS = 30_000;\n\n/**\n * Where the failure surfaced: a route's view chunk during a client-side\n * navigation or hydration, a `vite:preloadError` (a lazy `import()` in app\n * code, through Vite's preload helper), or an app calling\n * `recoverFromChunkLoadError` from its own error boundary.\n */\nexport type ChunkLoadErrorSource = \"navigation\" | \"hydration\" | \"preload\" | \"app\";\n\n/**\n * Why gemi will not reload, or `null` when it will:\n * - `cooldown`: it already reloaded onto this URL within `cooldownMs`.\n * - `offline`: `navigator.onLine` is false — a reload would only fail harder.\n * - `storage`: neither `sessionStorage` nor the `window.name` fallback can\n * hold the guard, so it cannot survive the reload and the loop it prevents\n * could not be ruled out.\n */\nexport type ChunkReloadBlock = \"cooldown\" | \"offline\" | \"storage\" | null;\n\nexport interface ChunkLoadErrorContext {\n error: unknown;\n /** The URL the reload goes to: the page being navigated to. */\n url: string;\n source: ChunkLoadErrorSource;\n /** Why gemi will not reload, or `null` when it is about to. */\n blocked: ChunkReloadBlock;\n}\n\nexport interface BuildMismatchContext {\n /** The URL the full page load goes to: the page being navigated to. */\n url: string;\n /** The build the page was loaded with. */\n clientBuild: string;\n /** The build that answered the navigation. */\n serverBuild: string;\n /** Why gemi will not reload, or `null` when it is about to. */\n blocked: ChunkReloadBlock;\n}\n\nexport interface ChunkLoadRecoveryOptions {\n /** Default 30 000 ms. */\n cooldownMs?: number;\n /**\n * Called for every chunk load failure gemi sees, before it reloads — the\n * place to report it, or to veto the reload (unsaved input, a page that\n * would rather show its own \"a new version is available\" prompt). Return\n * `false` to skip the reload; anything else lets gemi proceed. It is called\n * when the reload is blocked too, with `blocked` saying why.\n */\n onChunkLoadError?: (context: ChunkLoadErrorContext) => boolean | void;\n /**\n * Called when a client-side navigation's data came from another build (a\n * deploy in progress, two releases behind one load balancer), before gemi\n * loads the page in full. Return `false` to skip that and render the data\n * anyway. Called when the load is blocked too, with `blocked` saying why.\n */\n onBuildMismatch?: (context: BuildMismatchContext) => boolean | void;\n}\n\nlet enabled = true;\nlet options: ChunkLoadRecoveryOptions = {};\n/**\n * The full load gemi started and the page is still waiting on: further\n * failures of the same navigation (a route with several views fails once per\n * view) report it as under way instead of starting another.\n *\n * Not a latch for the life of the page: the load can be cancelled — \"Stay\" on\n * a `beforeunload` prompt (a dirty editor), a handler that stops it — and the\n * page then keeps running with no load coming. It holds only for the\n * navigation that started it (`navigationStarted` clears it) and for the\n * cooldown, so a later failure is judged on its own: another URL loads in\n * full, the same URL inside the cooldown is refused (the data renders, the\n * view's error boundary shows), and after the cooldown it loads again.\n */\nlet pendingLoad: { url: string; at: number } | null = null;\n\n/**\n * Sets how gemi recovers from a failed chunk. `false` turns recovery off: the\n * failure goes to the route's error boundary as it did before. `init` calls\n * this with its `chunkLoadRecovery` option.\n */\nexport function configureChunkLoadRecovery(next: ChunkLoadRecoveryOptions | false | undefined) {\n enabled = next !== false;\n options = next || {};\n tidyWindowName();\n}\n\n/** For tests: back to the defaults, with no reload in flight. */\nexport function __resetChunkLoadRecovery() {\n enabled = true;\n options = {};\n pendingLoad = null;\n clearTimeout(tidyTimer);\n tidyTimer = undefined;\n}\n\n/**\n * The router calls this as each client-side navigation starts. A full load\n * still pending from an earlier one was cancelled (the page would be gone\n * otherwise), so it no longer speaks for this navigation's failures.\n */\nexport function navigationStarted() {\n pendingLoad = null;\n}\n\n/** Whether a full load onto `url` is already under way. */\nfunction loadPending(url: string): boolean {\n return (\n pendingLoad !== null &&\n pendingLoad.url === url &&\n withinCooldown(Date.now() - pendingLoad.at, cooldownMs())\n );\n}\n\n/**\n * Whether `error` is a module that failed to load rather than one that loaded\n * and threw. Each engine words it differently:\n *\n * - Chromium: `Failed to fetch dynamically imported module: <url>`\n * - Firefox: `error loading dynamically imported module: <url>`\n * - Safari: `Importing a module script failed.`, and on iOS 16\n * `Importing module '<specifier>' is not found.`\n * - Vite's preload helper: `Unable to preload CSS for <url>`\n *\n * A view that throws while evaluating is not one of these, and reloading\n * would only hide it.\n */\nexport function isChunkLoadError(error: unknown): boolean {\n if (!error || typeof error !== \"object\") {\n return false;\n }\n const { name, message } = error as { name?: unknown; message?: unknown };\n if (name === \"ChunkLoadError\") {\n return true;\n }\n if (typeof message !== \"string\") {\n return false;\n }\n return CHUNK_LOAD_MESSAGES.some((pattern) => pattern.test(message));\n}\n\nconst CHUNK_LOAD_MESSAGES = [\n /failed to fetch dynamically imported module/i,\n /error loading dynamically imported module/i,\n /importing a module script failed/i,\n /importing module .* is not found/i,\n /unable to preload css/i,\n /failed to load module script/i,\n // A chunk that loaded but whose dependency came from another build: the\n // dependency's URL answered with the server's reload stub (or another\n // release's file), which lacks the named export the chunk imports, so the\n // module graph fails to link before any of it runs — the stub's own reload\n // never gets the chance. A production build's chunks only import names their\n // own build exports, so outside a mixed deploy this does not happen.\n // - Chromium: `The requested module './index-x.js' does not provide an export named 'a'`\n // - Firefox: `The requested module './index-x.js' doesn't provide an export named: 'a'`,\n // older releases `import not found: a`\n // - Safari: `Importing binding name 'a' is not found.`\n /requested module .* (does not|doesn't) provide an export named/i,\n /^import not found: /i,\n /importing binding name .* is not found/i,\n];\n\n/**\n * The export the server's reload stub carries, true when the stub started a\n * reload. A view chunk answered by the stub then evaluates to a module with no\n * `default`, and rendering it would put the route's error boundary on screen\n * for the moment before the page goes away.\n */\nexport const RELOAD_STUB_EXPORT = \"__gemiReload\";\n\n/**\n * How long a view waits on a full load gemi started before it gives up and\n * fails after all. The load can be cancelled (\"Stay\" on a `beforeunload`\n * prompt), and the page must not sit on its loading state for good then.\n */\nexport const RELOAD_WAIT_MS = 15_000;\n\n/**\n * A promise for a view whose page is being loaded in full: it stays pending,\n * so the route keeps its `Loading` fallback (or the server's HTML) instead of\n * flashing its error boundary while the reload is under way, and rejects with\n * `error` only if the page is still here after `RELOAD_WAIT_MS`.\n */\nexport function waitForReload(error: unknown, ms: number = RELOAD_WAIT_MS): Promise<never> {\n return new Promise((_, reject) => {\n setTimeout(() => reject(error), ms);\n });\n}\n\n/**\n * Reloads the page onto `url` once for a chunk that failed to load, unless the\n * guard or the app's `onChunkLoadError` says not to. Returns whether a reload\n * was started.\n *\n * Errors that are not chunk failures are ignored (`false`), so an app's error\n * boundary can pass everything it catches here.\n */\nexport function recoverFromChunkLoadError(\n error: unknown,\n { source = \"app\", url }: { source?: ChunkLoadErrorSource; url?: string } = {},\n): boolean {\n if (typeof window === \"undefined\" || !enabled || !isChunkLoadError(error)) {\n return false;\n }\n const target = url ?? window.location.href;\n if (loadPending(target)) {\n // A route with several views fails once per view; the first one reloads.\n return true;\n }\n const blocked = reloadBlock(target);\n\n if (options.onChunkLoadError?.({ error, url: target, source, blocked }) === false) {\n return false;\n }\n return loadInFull(target, blocked);\n}\n\n/**\n * Loads `url` in full because the navigation to it got its data from another\n * build (#1056): the views this page runs were not written for that data, and\n * rendering it anyway is how a deploy turned into \"Something went wrong\". The\n * full load gets a document and views of one build. Same guard as a chunk\n * failure, once per URL per cooldown; a navigation refused here renders the\n * data as before. Returns whether the page load was started.\n */\nexport function recoverFromBuildMismatch({\n url,\n clientBuild,\n serverBuild,\n}: {\n url: string;\n clientBuild: string;\n serverBuild: string;\n}): boolean {\n if (typeof window === \"undefined\" || !enabled) {\n return false;\n }\n if (loadPending(url)) {\n return true;\n }\n const blocked = reloadBlock(url);\n if (options.onBuildMismatch?.({ url, clientBuild, serverBuild, blocked }) === false) {\n return false;\n }\n return loadInFull(url, blocked);\n}\n\n/**\n * The build that answered a `.json` navigation, when it is not `clientBuild`;\n * otherwise `null`. Unknown on either side (dev, a test double, a server from\n * before the header) is not a mismatch.\n */\nexport function otherBuild(response: Response, clientBuild: string | undefined): string | null {\n const served = response.headers?.get?.(BUILD_HEADER);\n return clientBuild && served && served !== clientBuild ? served : null;\n}\n\nfunction loadInFull(target: string, blocked: ChunkReloadBlock): boolean {\n if (blocked !== null || !markReload(target)) {\n return false;\n }\n\n pendingLoad = { url: target, at: Date.now() };\n if (target === window.location.href) {\n window.location.reload();\n } else {\n window.location.assign(target);\n }\n return true;\n}\n\nfunction cooldownMs() {\n return options.cooldownMs ?? DEFAULT_CHUNK_RELOAD_COOLDOWN_MS;\n}\n\nfunction reloadBlock(url: string): ChunkReloadBlock {\n if (typeof navigator !== \"undefined\" && navigator.onLine === false) {\n return \"offline\";\n }\n const verdict = chunkReloadGuard(CHUNK_RELOAD_MARKER, url, cooldownMs(), false);\n return verdict === \"ok\" ? null : verdict;\n}\n\n// A marker from the future (the clock was set back since it was written) is\n// stale rather than a cooldown that lasts until the clock catches up.\nfunction withinCooldown(elapsed: number, cooldownMs: number): boolean {\n return elapsed >= 0 && elapsed < cooldownMs;\n}\n\nfunction markReload(url: string): boolean {\n if (chunkReloadGuard(CHUNK_RELOAD_MARKER, url, cooldownMs(), true) !== \"ok\") return false;\n // The load may yet be cancelled (\"Stay\" on a `beforeunload` prompt), and\n // then this page has to take the `window.name` marker down itself.\n tidyWindowName();\n return true;\n}\n\nlet tidyTimer: ReturnType<typeof setTimeout> | undefined;\n\n/**\n * Takes gemi's marker out of `window.name` (back to `\"\"`) once it guards\n * nothing (#1188): the page may want the name for itself, under the same\n * \"only while it is empty\" rule gemi follows. Now when nothing in it is live,\n * otherwise once the newest entry's cooldown has passed, checked again then\n * since a reload may have been recorded in the meantime. Only a name that\n * holds gemi's marker is ever cleared; see `chunkReloadGuard`'s `\"tidy\"`.\n */\nfunction tidyWindowName() {\n clearTimeout(tidyTimer);\n tidyTimer = undefined;\n if (typeof window === \"undefined\") return;\n let delay: number;\n try {\n if (chunkReloadGuard(CHUNK_RELOAD_MARKER, window.location.href, cooldownMs(), \"tidy\") !== \"cooldown\") {\n return;\n }\n const held = JSON.parse(window.name.slice(CHUNK_RELOAD_MARKER.length + 1));\n // An entry from the future (clock set back) is not live and holds nothing back.\n const now = Date.now();\n const latest = Math.max(\n ...Object.values(held.m).filter((at): at is number => typeof at === \"number\" && at <= now),\n );\n delay = latest + cooldownMs() - now;\n } catch {\n return;\n }\n if (!Number.isFinite(delay)) return;\n tidyTimer = setTimeout(tidyWindowName, Math.max(0, delay) + 1);\n}\n\n/**\n * The cross-document guard, shared by the client and the server's reload stub\n * (which embeds this function's source, so it uses nothing but globals and its\n * arguments). With `claim` false it only reads: `\"cooldown\"` when a reload\n * onto `url` was recorded inside `cooldownMs`, `\"storage\"` when no marker can\n * be read at all, otherwise `\"ok\"`. With `claim` true it also records the\n * reload, and answers `\"ok\"` only once the record was written and read back\n * unchanged; a caller navigates on nothing less. With `\"tidy\"` it only looks\n * at `window.name`: a gemi marker with no live entry for this origin (expired,\n * from the future, another origin's, or one that does not parse) is cleared\n * to `\"\"` and `\"ok\"` answered; `\"cooldown\"` while an entry is still live.\n *\n * Two places can hold the marker:\n *\n * - `sessionStorage[key]`: `{ [url]: at }`, the format earlier releases read\n * and write, so a page from one and a stub from another share the guard.\n * - `window.name`, when `sessionStorage` throws or will not take the write\n * (#1186). It survives a load in the same tab, but it is shared state: the\n * page may use it, and another origin the tab goes to can read it. So it is\n * used only while it is empty or already holds gemi's marker — a value of\n * anyone else's is left exactly as it is, and the guard then fails closed —\n * and it holds no URL: `key + \":\" + { o: hash(origin), m: { [hash(origin +\n * pathname)]: at } }`. A marker written by another origin (`o` differs) or\n * one that does not parse holds no reloads and is replaced on the next\n * write. Two paths whose hashes collide share one cooldown, which only ever\n * refuses a reload.\n *\n * A reload recorded in either place counts. Entries past the cooldown — and\n * from the future, after the clock was set back — are dropped as a new one is\n * written, so the marker holds only the reloads it still guards.\n */\nexport function chunkReloadGuard(\n key: string,\n url: string,\n cooldownMs: number,\n claim: boolean | \"tidy\",\n): \"ok\" | \"cooldown\" | \"storage\" {\n const now = Date.now();\n const fresh = function (at: unknown) {\n return typeof at === \"number\" && now - at >= 0 && now - at < cooldownMs;\n };\n const parse = function (raw: string | null): Record<string, unknown> {\n try {\n const value = raw ? JSON.parse(raw) : null;\n return value && typeof value === \"object\" && !Array.isArray(value) ? value : {};\n } catch {\n return {};\n }\n };\n const live = function (marker: Record<string, unknown>) {\n const kept: Record<string, number> = {};\n for (const k in marker) if (fresh(marker[k])) kept[k] = marker[k] as number;\n return kept;\n };\n // FNV-1a, 32 bits, base 36: a short tag, not a secret.\n const hash = function (text: string) {\n let h = 0x811c9dc5;\n for (let i = 0; i < text.length; i++) h = Math.imul(h ^ text.charCodeAt(i), 0x01000193);\n return (h >>> 0).toString(36);\n };\n\n let storage: Storage | null = null;\n let stored: Record<string, unknown> = {};\n try {\n storage = window.sessionStorage;\n stored = parse(storage.getItem(key));\n } catch {\n storage = null;\n }\n\n const prefix = key + \":\";\n let origin = \"\";\n let page = \"\";\n try {\n const target = new URL(url, window.location.href);\n origin = hash(new URL(window.location.href).origin);\n page = hash(target.origin + target.pathname);\n } catch {}\n // `null`: `window.name` is not ours to use (or there is no page to key on).\n let named: Record<string, unknown> | null = null;\n try {\n const name = window.name;\n if (!page) {\n named = null;\n } else if (name === \"\") {\n named = {};\n } else if (name.indexOf(prefix) === 0) {\n const held = parse(name.slice(prefix.length));\n const entries = held.m;\n named =\n held.o === origin && entries && typeof entries === \"object\" && !Array.isArray(entries)\n ? (entries as Record<string, unknown>)\n : {};\n }\n } catch {\n named = null;\n }\n\n if (claim === \"tidy\") {\n try {\n const current = window.name;\n if (named === null || current.indexOf(prefix) !== 0) return \"ok\";\n for (const k in named) if (fresh(named[k])) return \"cooldown\";\n window.name = \"\";\n } catch {}\n return \"ok\";\n }\n if (fresh(stored[url]) || (named && fresh(named[page]))) return \"cooldown\";\n if (!storage && !named) return \"storage\";\n if (!claim) return \"ok\";\n\n if (storage) {\n try {\n const nextStored = live(stored);\n nextStored[url] = now;\n const serialised = JSON.stringify(nextStored);\n storage.setItem(key, serialised);\n if (storage.getItem(key) === serialised) return \"ok\";\n } catch {}\n }\n if (named) {\n try {\n const nextNamed = live(named);\n nextNamed[page] = now;\n const value = prefix + JSON.stringify({ o: origin, m: nextNamed });\n window.name = value;\n if (window.name === value) return \"ok\";\n } catch {}\n }\n return \"storage\";\n}\n\n/**\n * The same guard as a classic script body, for the module the server sends in\n * place of a chunk it does not have. It reloads once per URL per cooldown;\n * inside the cooldown (or with no marker that would survive the reload) it\n * throws an error `isChunkLoadError` recognises, so the importing page's own\n * recovery and error boundary see the failure instead of a module that\n * silently has no exports. It runs `chunkReloadGuard` itself, so it and the\n * page's client share one marker and one reload between them. It exports\n * `RELOAD_STUB_EXPORT`, true when it reloaded, so the client can tell a view\n * answered by the stub from a view and wait for the reload instead of\n * rendering a module with no `default`.\n */\nexport function chunkReloadStubScript(\n pathname: string,\n cooldownMs: number = DEFAULT_CHUNK_RELOAD_COOLDOWN_MS,\n): string {\n const key = JSON.stringify(CHUNK_RELOAD_MARKER);\n const error = JSON.stringify(`Failed to fetch dynamically imported module: ${pathname}`);\n return (\n `var g=${chunkReloadGuard.toString()};var r=!1;` +\n `try{r=navigator.onLine!==!1&&g(${key},window.location.href,${Number(cooldownMs)},!0)===\"ok\"}catch(e){}` +\n `if(r)window.location.reload();else throw new Error(${error});export {r as ${RELOAD_STUB_EXPORT}}`\n );\n}\n",
12
12
  "import { isReservedAssetPath, RESERVED_ROUTE_PREFIX } from \"../services/router/ViewRouteDispatcher\";\nimport { chunkReloadStubScript } from \"../client/chunkLoadRecovery\";\n\n/**\n * A JavaScript module under `/assets/` — the only shape a client build chunk\n * has. Vite writes every chunk into `assets/` with a `.js` extension (`.mjs`\n * is accepted for a build configured to emit it).\n *\n * The extension is matched at the end of the path, not anywhere in it:\n * `includes(\".js\")` also matched `app.js.map` and `data.json`, so a missing\n * source map was answered with a script that reloads the page.\n */\nconst BUILD_CHUNK = new RegExp(`^${RESERVED_ROUTE_PREFIX}/.+\\\\.m?js$`);\n\nexport function isBuildChunkPath(pathname: string): boolean {\n return BUILD_CHUNK.test(pathname);\n}\n\n/**\n * `/assets` or anything under it — the prefix the router refuses to mount a\n * route on at boot, so nothing there is ever the app's to answer. Defined\n * beside that check so the two cannot drift apart.\n */\nexport { isReservedAssetPath };\n\n/**\n * The answer to a static-looking request with no file behind it in\n * `dist/client`, or `undefined` to hand the request to the app.\n *\n * A missing build chunk is almost always a document rendered by another\n * release asking for its own chunks — a deploy between page load and a lazy\n * `import()`, or two releases serving at once. The page cannot continue with\n * the chunk it wanted, so it gets a module that reloads it onto this release's\n * document. Only for build chunks: outside `/assets/` a `.js` path may be an\n * app route, and a classic `<script src>` answered with a reload reloads\n * forever.\n *\n * `no-store` because the stub is a stand-in for one release's chunk, served\n * under that chunk's URL. Cached — by the browser or by an edge in front of\n * the origin — it would outlive the deploy that caused it and answer the\n * request after the real chunk is back.\n *\n * The body is only the reload. An earlier version opened with\n * `if(caches){caches?.delete(distPath)}`, which was wrong three times over:\n * `CacheStorage.delete` takes a cache *name*, not a URL, so a filesystem path\n * matched nothing; that path told anyone who asked for a missing chunk where\n * the server keeps its files; and `caches` is `[SecureContext]`, so on a\n * plain-http origin the bare identifier is not defined at all and reading it\n * threw a `ReferenceError` before the reload below could run — the recovery\n * failing exactly where it was needed.\n *\n * The reload is guarded by the same `sessionStorage` marker the client\n * router's chunk recovery uses (`client/chunkLoadRecovery.ts`), so the stub\n * and the router together reload once per cooldown. A chunk that is still\n * missing after that reload makes the stub throw a chunk-load error instead —\n * the importing `import()` rejects and the route's error boundary shows,\n * where an unguarded reload used to loop.\n */\nexport function staticAssetMiss(pathname: string): Response | undefined {\n if (isBuildChunkPath(pathname)) {\n return new Response(chunkReloadStubScript(pathname), {\n headers: {\n \"Content-Type\": \"application/javascript\",\n \"Cache-Control\": \"no-store\",\n },\n });\n }\n\n // `/assets` is reserved for build output (the router rejects routes there\n // at boot), so a miss is a miss — 404 without paying for an SSR render.\n if (isReservedAssetPath(pathname)) {\n return new Response(\"Not found\", { status: 404 });\n }\n\n // Anywhere else the public-file pattern matched on extension alone, so this\n // may well be an app route — a file route like\n // `this.file(() => Bun.file(...))` mounted at `/files/logo.svg` lands here\n // too. The app answers it rather than a 404 on its behalf.\n return undefined;\n}\n",
13
13
  "/**\n * A second place to find a build asset this server does not have (#1269).\n *\n * While two releases serve one app (a weighted rollout across revisions, two\n * origins behind a load balancer with no affinity), a document from one\n * release asks for its hashed files and each request can land on the other.\n * Neither release has the other's files, and a reload only rolls the dice\n * again. With a fallback base set — a bucket or blob container the deploy\n * uploads every release's `dist/client/assets` to before it takes traffic —\n * a miss under `/assets/` is fetched from there and streamed back, so any\n * release answers any recent release's chunks, stylesheets and fonts. Without\n * a file there either, the miss is answered as before (the reload stub for a\n * chunk, a 404 for the rest).\n *\n * Read at boot from `GEMI_ASSET_FALLBACK_URL`. Unset, nothing changes.\n */\n\n/** How long the fallback may take to start answering before the miss is answered locally. */\nexport const ASSET_FALLBACK_TIMEOUT_MS = 3_000;\n/** How long a path the fallback did not have is not asked for again. */\nexport const ASSET_FALLBACK_MISS_TTL_MS = 30_000;\n/** At most this many remembered misses, oldest dropped first. */\nconst MAX_REMEMBERED_MISSES = 1_000;\n\n/** Marks a response that came from the fallback, for whoever debugs a deploy. */\nexport const ASSET_FALLBACK_HEADER = \"x-gemi-asset-fallback\";\n\nexport interface AssetFallbackOptions {\n /** Absolute http(s) URL the `/assets/...` path is resolved against. */\n base: string;\n timeoutMs?: number;\n missTtlMs?: number;\n fetch?: typeof fetch;\n now?: () => number;\n}\n\nexport type AssetFallback = (req: Request, pathname: string) => Promise<Response | undefined>;\n\n/**\n * `GEMI_ASSET_FALLBACK_URL`, checked: an absolute http(s) URL, given a\n * trailing `/`. Anything else is reported and ignored, since a typo must not\n * cost the server its boot.\n */\nexport function assetFallbackBase(value: string | undefined): string | undefined {\n const raw = value?.trim();\n if (!raw) return undefined;\n try {\n const url = new URL(raw);\n if (url.protocol !== \"https:\" && url.protocol !== \"http:\") throw new Error(\"not http(s)\");\n url.search = \"\";\n url.hash = \"\";\n return url.href.endsWith(\"/\") ? url.href : `${url.href}/`;\n } catch {\n console.error(\n `GEMI_ASSET_FALLBACK_URL is not an absolute http(s) URL (${JSON.stringify(raw)}); missing assets are not looked up anywhere else.`,\n );\n return undefined;\n }\n}\n\n/**\n * The lookup for one fallback base. Answers `undefined` whenever the fallback\n * has nothing usable — a non-200, a timeout, a network error, a method other\n * than GET/HEAD — and remembers that for `missTtlMs`, so a path that is\n * really gone (an old tab days later, a scanner) costs the fallback one\n * request per window, not one per hit.\n */\nexport function createAssetFallback({\n base,\n timeoutMs = ASSET_FALLBACK_TIMEOUT_MS,\n missTtlMs = ASSET_FALLBACK_MISS_TTL_MS,\n fetch: fetchImpl = fetch,\n now = Date.now,\n}: AssetFallbackOptions): AssetFallback {\n const misses = new Map<string, number>();\n\n const remember = (pathname: string) => {\n misses.delete(pathname);\n misses.set(pathname, now() + missTtlMs);\n if (misses.size > MAX_REMEMBERED_MISSES) {\n misses.delete(misses.keys().next().value!);\n }\n };\n\n return async (req, pathname) => {\n if (req.method !== \"GET\" && req.method !== \"HEAD\") return undefined;\n\n const until = misses.get(pathname);\n if (until !== undefined) {\n if (until > now()) return undefined;\n misses.delete(pathname);\n }\n\n // The path is the request's own, already normalised by `URL`; resolved\n // relative to the base (without its leading `/`) so a base with a path\n // keeps it, and checked to stay under it.\n let target: URL;\n try {\n target = new URL(pathname.replace(/^\\/+/, \"\"), base);\n } catch {\n return undefined;\n }\n if (!target.href.startsWith(base)) return undefined;\n\n // The timeout covers the wait for the answer to start, not the body: a\n // large file that has started streaming is left to finish.\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), timeoutMs);\n let upstream: Response;\n try {\n upstream = await fetchImpl(target.href, {\n method: req.method,\n signal: controller.signal,\n redirect: \"error\",\n });\n } catch {\n remember(pathname);\n return undefined;\n } finally {\n clearTimeout(timer);\n }\n\n if (upstream.status !== 200) {\n // Drained so the connection can be reused.\n upstream.body?.cancel().catch(() => {});\n remember(pathname);\n return undefined;\n }\n\n // The extension decides first, as it does for the files this server has:\n // a store that labels a chunk `application/octet-stream` would otherwise\n // get it refused as a module script.\n const byExtension = Bun.file(pathname).type;\n const headers = new Headers({\n \"Content-Type\":\n (byExtension !== \"application/octet-stream\" && byExtension) ||\n upstream.headers.get(\"content-type\") ||\n \"application/octet-stream\",\n // Content-hashed, like every file the build writes under `/assets/`.\n \"Cache-Control\": \"public, max-age=31536000, immutable\",\n [ASSET_FALLBACK_HEADER]: \"1\",\n });\n // `fetch` decodes a compressed answer, so the upstream length only holds\n // for one that was not encoded.\n const length = upstream.headers.get(\"content-length\");\n if (length && !upstream.headers.get(\"content-encoding\")) {\n headers.set(\"Content-Length\", length);\n }\n return new Response(req.method === \"HEAD\" ? null : upstream.body, { status: 200, headers });\n };\n}\n",
14
14
  "import { stringEraRefusal } from \"../http/Error\";\nimport { isApiPath } from \"../services/router/apiPath\";\n\n// The production server's last resort: an error nothing on the way here turned\n// into a response. Request breakers (auth, 404s, 416s) are answered by the\n// dispatchers before this, so what arrives is a genuine failure — and its\n// message and stack are for the developer, not for whoever triggered it. They\n// can carry absolute paths, dependency versions, SQL fragments and column\n// names. The dev server renders them on purpose (`httpDev.ts`); this does not.\n\nconst GENERIC_500_HTML = `<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"UTF-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n <title>Internal Server Error</title>\n <style>\n body { font-family: system-ui, sans-serif; margin: 0; min-height: 100vh; display: grid; place-items: center; }\n main { text-align: center; padding: 16px; }\n h1 { font-size: 1.5rem; margin: 0 0 0.5rem; }\n p { margin: 0; opacity: 0.7; }\n </style>\n </head>\n <body>\n <main>\n <h1>Something went wrong</h1>\n <p>Please try again later.</p>\n </main>\n </body>\n</html>`;\n\nexport function unhandledErrorResponse(\n err: unknown,\n pathname: string,\n onException?: (error: Error) => void,\n): Response {\n // `onException` is the report, and the default one `App` installs is a\n // `console.error`, so logging here as well printed every failure twice\n // (three times for `/api`, whose dispatcher logs before rethrowing). Only\n // without a reporter does this log itself.\n //\n // Reported for `/api` too: an app's error tracking should see an API failure\n // that got this far, not only a page one. `onRequestFail` is a different\n // hook (route config, called by the dispatchers), so this is not a second\n // report through the same channel.\n if (!onException) {\n console.error(err);\n } else {\n try {\n // The hook is typed to receive an `Error`; a thrown string or object is\n // wrapped so a reporter reading `.stack` or `.name` gets one.\n onException(err instanceof Error ? err : new Error(String(err), { cause: err }));\n } catch (reportError) {\n // A broken reporter must not turn a 500 into a leaked stack either.\n console.error(err);\n console.error(reportError);\n }\n }\n\n if (isApiPath(pathname)) {\n return new Response(\n JSON.stringify({ error: stringEraRefusal(\"server_error\", \"Internal Server Error\", 500) }),\n {\n status: 500,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n\n return new Response(GENERIC_500_HTML, {\n status: 500,\n headers: { \"Content-Type\": \"text/html; charset=utf-8\" },\n });\n}\n"