@lunora/do 1.0.0-alpha.297 → 1.0.0-alpha.298
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.
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import{LunoraError as p,isLunoraError as V,toErrorBody as P}from"@lunora/errors";import{ISSUE_SEVERITIES as Rs,ISSUE_STATUSES as As,ensureRequestLogTable as Zr,readRequestLog as ws,readErrorIssues as Ts,findDanglingReferences as ks,readAuthMetrics as _s,mergeScanAttribution as Is,FUNCTION_METRICS_MAX_PATHS as Mt,latencyBucketIndex as Cs,readFunctionMetrics as Os,readFunctionMetricBuckets as Ms,FUNCTION_METRICS_BUCKET_MS as Nt,recordFunctionMetric as Ns,recordQueryMetric as xs,readQueryInsights as Ds,LogBuffer as Ls,SpanBuffer as Ps,MetricBuffer as Bs,createSensitiveScope as qs,sensitiveValues as xt,sensitiveNames as Dt,emitLogEvent as Us,NO_SENSITIVE_SCOPE as K,resolveTraceAnchor as be,createTracer as Fs,instrumentDatabase as Hs,instrumentSqlClient as Ws,createTracedFetch as $s,createMetrics as Ks,redactArgs as Lt,REQUEST_LOG_TABLE as Pt,createDatabaseTally as Gs,formatTally as Qs,dispatchRootSpan as js,applyHostRootSpan as zs,readFunctionMetricsTotals as Vs,readFunctionMetricIndexHits as Js,readQueryMetrics as Xs,upsertIssueState as Ys,ISSUE_STATE_TABLE as Zs,recordAuthEvent as ei,explainIssue as ti,maskSensitiveArgs as ri,appendRequestLogEntry as si,emitRequestLogEvent as ii,foldTraces as ni,readMetricHistory as oi,buildSecurityAudit as ai,parseLogArgs as ci,createSpanCollector as di,recordMetricHistory as li}from"@lunora/observability";import{createShardHost as hi,createSocketHost as ui,createSecretValueHost as pi}from"@lunora/platform-cloudflare";import{tableFromDepKey as fi,ADMIN_FUNCTION_PREFIX as M,isVacuousFilterClause as mi,ensureAuditTable as Si,readAuditLog as yi,ADMIN_WILDCARD as _,ADMIN_FUNCTIONS as f,facetColumn as bi,runReadonlySql as gi,findStorageReferences as vi,readCapturedMail as Ei,MAIL_TABLE as Ri,readQueueMessages as Ai,QUEUE_TABLE as wi,SCHEDULE_OUTBOX_TABLE as Bt,readScheduleOutbox as Ti,CDC_LOG_TABLE as ki,readCdcEpoch as _i,bumpCdcEpoch as Ii,envOptionalPositiveInt as Et,cdcSeqLeavingRows as Pe,readCdcArchivedThrough as Ci,readCdcChanges as es,cdcArchiveRewound as Oi,archiveCdcSegment as Mi,writeCdcArchivedThrough as Ni,readArchivedCdcChanges as xi,compactCdcDocs as Di,trimCdcChanges as Li,assertImportSessionId as ye,readImportManifest as ts,stagedImportPage as rs,dropImportSession as Pi,sweepImportStaging as Rt,replaceRefusal as Bi,stageImportRows as qi,touchImportManifest as Ui,dropImportManifest as Fi,advanceImportManifest as Hi,readShardImportSession as Wi,touchShardImportSession as $i,markShardImportCommitted as Ki,stagedImportIds as Gi,recordScheduleOutbox as Qi,forgetScheduleOutbox as Be,probeScheduleOutbox as qe,readDueScheduleOutbox as ji,trimScheduleOutbox as zi,readScheduleOutboxState as G,dropScheduleOutbox as qt,requeueScheduleOutbox as Vi,readDueScheduleOutboxEntry as Ut,parkScheduleOutbox as Ft,deferScheduleOutbox as Ji,renderSql as Ht,sqliteInList as Xi,DOC_COLUMN as Wt,readSchemaVersion as Yi,readSchemaHistory as Zi,lintReadonlySql as en,stubByName as tn,siblingSecretOf as ss,quoteIdentifier as dt,stableStringify as At,createShapeProbeCounters as rn,createGlobalPollCounters as sn,CompanionMemo as nn,DurableStreamRunner as on,createFanoutCounters as $t,ShardRunner as an,ReactiveCache as cn,createRelayLink as dn,listTables as Ue,minCdcReplayableSeq as ln,createReplicaLink as hn,readReactorState as un,reactorNeedsRun as pn,MAX_PAGE_SIZE as fn,selectMatchingIds as mn,readCdcCursor as Fe,cdcForkedError as Sn,minCdcSeq as He,cursorBelowRetainedFloor as ge,cdcTrimmedError as yn,cdcCanVouchFor as bn,cdcTouchesTables as gn,readIdempotent as We,writeIdempotent as vn,trimIdempotent as En,readClientWatermark as $e,migrateClientWatermark as Rn,advanceClientWatermark as An,deleteGlobalShapeSnapshot as wn,deleteShapePokeCursor as Tn,TransactionHeadroomTracker as Kt,selectExpiredIds as kn,createDependencyTracker as _n,createReadFootprint as In,reactiveCacheKey as ve,SCAN_DEP as Ee,recordChangedKeys as Cn,DATA_MIGRATION_STATE_TABLE as On,isDevEnvironment as q,gateReplicaDispatch as Mn,RELATION_FUNCTION_PREFIX as Nn,ConflictError as xn,FLAGS_FUNCTION_PREFIX as Re,trySendFrame as N,stableWireKey as Se,verifySiblingBody as Dn,RELAY_SIGNATURE_HEADER as Ln,deleteGlobalShapeSnapshotsForConnection as Pn,deleteShapePokeCursorsForConnection as Bn,parseImportShardArgs as qn,parseExportShardArgs as Un,writeReactorState as Gt,UNVOUCHABLE_DEP as Fn,listReactorStates as Hn,recordCapturedMail as Qt,clearCapturedMail as Wn,recordQueueMessages as $n,clearQueueMessages as Kn,clearCompanionSignatures as Gn,listAdminTokens as Qn,createAdminTokenRecord as jn,revokeAdminTokenRecord as zn,verifyAdminTokenDigest as Vn,adminTokenExists as Jn,readQueueMessageById as Xn,isLossyBody as Yn,appendAuditEntry as Zn,readDeployInfo as eo,readBookmark as to,armRestore as ro,readMigrationStatus as so,buildSettings as io,summarizeSubscriptions as no,summarizeFanoutTopics as oo,DEFAULT_MAX_RELAYS as ao,readTablePage as co,awaitWsDrain as J,mergeChangedKeys as lo,runSocketPool as jt,createShapeDiffCache as Ke,writeShapePokeCursors as ho,recordFanoutPass as Ge,recordShapeProbePass as zt,minShapePokeCursor as uo,readCdcChangeKeys as po,buildShapeDiff as fo,selectShapeRows as mo,projectColumns as So,diffGlobalMembership as Vt,readGlobalShapeSnapshot as yo,writeGlobalShapeSnapshot as bo,nextTtlExpiry as go,isTtlExpired as vo,GlobalPollTick as Qe,globalShapeReadKey as Eo,recordGlobalPollPass as Ro,buildPokeFrames as Ao,readShapePokeCursor as wo,writeShapePokeCursor as To,envPositiveInt as Jt,subscriptionFrames as ko,deltaTableFor as _o,handleReplicaControl as Io,RelayMember as je,OwnerRelay as Xt,VECTOR_BACKFILL_MAX_PAGES as Co,writeTouchesMemo as Oo}from"@lunora/shard-engine";import{subscriptionListDeltas as Gl}from"@lunora/shard-engine";import{isPlainObject as ce,decodeWire as F,encodeWire as D,needsWireEncoding as Mo}from"@lunora/wire";import{drizzle as No}from"drizzle-orm/durable-sqlite";import{t as xo,f as wt,v as Do,s as Lo,e as ze,i as Po,a as Bo,b as qo}from"./admin-token-DrufJIZV.mjs";import{c as le}from"./constant-time-equal-BRh9yUCr.mjs";import{j as b}from"./json-response-0Bq2ky0N.mjs";import{DeliveryFence as Uo,validDeliveryPermit as Yt}from"./installDeliveryFence-B6M9KOnb.mjs";import{sql as H}from"drizzle-orm";import{SHARD_REGISTRY_DO_NAME as Fo,isRegistryNamespace as Ho,isRegistryRpc as Wo,unregisterShardKey as $o,registerShardKey as Ko}from"./SHARD_REGISTRY_DO_NAME-Dbh8JQJQ.mjs";const is=["migrations"],Go=n=>is.some(e=>e===n),Zt=500,Qo=new Set(["exp","expiresAtMs","iat","jti","nbf"]),lt=n=>Array.isArray(n)?`[${n.map(e=>lt(e)).join(",")}]`:typeof n=="object"&&n!==null?`{${Object.entries(n).filter(([,t])=>t!==void 0).sort(([t],[r])=>t<r?-1:t>r?1:0).map(([t,r])=>`${JSON.stringify(t)}:${lt(r)}`).join(",")}}`:JSON.stringify(n)??"null",Tt=n=>{const e=Object.fromEntries(Object.entries(n??{}).filter(([t])=>!Qo.has(t)));return Object.keys(e).length===0?"":lt(e)},jo=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),U=(n,e)=>n>>>e|n<<32-e,zo=n=>{const e=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),t=new Uint8Array(Math.ceil((n.length+9)/64)*64);t.set(n),t[n.length]=128;const r=new DataView(t.buffer);r.setUint32(t.length-8,Math.floor(n.length*8/2**32)),r.setUint32(t.length-4,n.length*8>>>0);const s=new Uint32Array(64);for(let a=0;a<t.length;a+=64){for(let g=0;g<16;g+=1)s[g]=r.getUint32(a+g*4);for(let g=16;g<64;g+=1){const R=s[g-15],y=s[g-2],w=U(R,7)^U(R,18)^R>>>3,T=U(y,17)^U(y,19)^y>>>10;s[g]=s[g-16]+w+s[g-7]+T>>>0}let[c,d,l,h,u,m,S,E]=e;for(let g=0;g<64;g+=1){const R=U(u,6)^U(u,11)^U(u,25),y=u&m^~u&S,w=E+R+y+jo[g]+s[g]>>>0,T=U(c,2)^U(c,13)^U(c,22),k=c&d^c&l^d&l,L=T+k>>>0;E=S,S=m,m=u,u=h+w>>>0,h=l,l=d,d=c,c=w+L>>>0}[c,d,l,h,u,m,S,E].forEach((g,R)=>{e[R]=e[R]+g>>>0})}const i=new Uint8Array(32),o=new DataView(i.buffer);return e.forEach((a,c)=>{o.setUint32(c*4,a)}),i},Ve=(n,e)=>xo(zo(new TextEncoder().encode(`${JSON.stringify(n??null)}|${Tt(e)}`)).subarray(0,16)),Vo=9e5,Jo="DISPATCH_IN_PROGRESS",Xo="x-lunora-dispatch-declined",ns="x-lunora-want-error-detail",er="x-lunora-error-detail",Yo=8192,ht=n=>{if(!(n instanceof Error))return{message:String(n),name:typeof n};const{code:e}=n;return{...typeof e=="string"?{code:e}:{},message:n.message,name:n.name,...n.stack===void 0?{}:{stack:n.stack.slice(0,Yo)}}},tr=n=>typeof n=="object"&&n!==null&&!Array.isArray(n),ut=16384,Zo=(n,e)=>e instanceof Error?{...e,message:e.message,name:e.name}:e,ea=(n,{capped:e=!0}={})=>{if(n instanceof Error)try{const{internal:t}=n;if(!tr(t))return;const r=JSON.stringify(t,Zo);if(e&&r.length>ut)return;const s=JSON.parse(r);return tr(s)?s:void 0}catch{return}},rr=n=>{for(const e of n){if(e instanceof Error)return ht(e);if(typeof e=="object"&&e!==null&&!Array.isArray(e)){const t=Object.values(e).find(r=>r instanceof Error);if(t!==void 0)return ht(t)}}},ta=1024,ra=n=>{const e=encodeURIComponent(JSON.stringify(n));if(e.length<=ut)return e;if(n.internal!==void 0){const t=encodeURIComponent(JSON.stringify({...n,internal:void 0}));if(t.length<=ut)return t}return encodeURIComponent(JSON.stringify({...n.code===void 0?{}:{code:n.code.slice(0,128)},message:n.message.slice(0,ta),name:n.name.slice(0,128)}))},os=new TextDecoder;new TextEncoder;const sr="=",sa=n=>{if(n)try{const e=n[0]==="{"?n:os.decode(wt(n)),t=JSON.parse(e);if(t&&typeof t=="object"&&!Array.isArray(t))return t}catch{}},te=n=>{if(n){if(!n.startsWith(sr))return n;try{return os.decode(wt(n.slice(sr.length)))}catch{return}}},he=n=>{const e=Number(n);return Number.isFinite(e)&&e>0?e:void 0},ue=n=>typeof n=="number"&&Date.now()>=n,ir=n=>{try{n.send(JSON.stringify({code:"TOKEN_EXPIRED",error:{code:"TOKEN_EXPIRED",message:"authentication token expired"},message:"authentication token expired",type:"error"})),n.close?.(4001,"token_expired")}catch{}},ia="/_lunora/live/connect",na="/_lunora/live/control",oa="/_lunora/live/publish",as=(n,e)=>JSON.stringify([n,e]),aa="x-lunora-live-connection",ca="live",da={"cache-control":"no-cache, no-transform","content-type":"text/event-stream; charset=utf-8","x-accel-buffering":"no"},la=(n,e)=>`event: ${ca}
|
|
2
|
+
data: {"topic":${JSON.stringify(n)},"data":${e}}
|
|
3
|
+
|
|
4
|
+
`,ha="room:",z="__lunora_socket__:",oe=256,ua="x-lunora-paywall",pa="1";Array.from({length:256},(n,e)=>e.toString(16).padStart(2,"0"));const Ae=/^[0-9a-f]+$/,fa=(n,e,t=!0)=>`00-${n}-${e}-${t?"01":"00"}`,ma=n=>{if(n==null)return;const e=n.split("-"),[t,r,s,i]=e;if(!(e.length<4||t===void 0||t.length!==2||!Ae.test(t)||t==="ff"||t==="00"&&e.length!==4||r===void 0||s===void 0||i===void 0||i.length!==2||!Ae.test(i)||r.length!==32||s.length!==16||!Ae.test(r)||!Ae.test(s)||r==="00000000000000000000000000000000"||s==="0000000000000000"))return{parentSpanId:s,sampled:(Number.parseInt(i,16)&1)===1,traceId:r}},Je=Object.freeze({durationMs:"lunora.duration_ms",errorMessage:"error.message",errorType:"error.type",functionPath:"lunora.function_path",ok:"lunora.ok",rayId:"cloudflare.ray_id",shardKey:"lunora.shard_key",userId:"lunora.user_id"}),Sa="pageDelta",ya="x-lunora-ray-id",ba="refreshBatch",ga='{"type":"batchStart"}',va='{"type":"batchEnd"}',nr="::relay::",pt=n=>{const e=n.lastIndexOf(nr);if(e===-1)return;const t=n.slice(0,e),r=n.slice(e+nr.length),s=Number(r);if(!(t.length===0||!Number.isInteger(s)||s<0||String(s)!==r))return{ownerKey:t,relayIndex:s}},Ea=(n,e)=>e===void 0?n:`r${String(e)}.${n}`,Ra=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"],Aa=new Set(Ra),wa=n=>typeof n=="string"&&Aa.has(n),or="::replica::",ft=n=>{const e=n.lastIndexOf(or);if(e===-1)return;const t=n.slice(0,e),r=n.slice(e+or.length);if(!(t.length===0||!wa(r)))return{ownerKey:t,region:r}},Ta="x-lunora-sample-errors",ar="/_lunora/ws/reauth",mt=6e4,re=4005,cr="identity_changed",ka="x-lunora-scheduled-for",_a=(n,e,t)=>n?.[t]??e?.[t],Ia=(n,e,t,r)=>{const s=_a(n,e,t);if(!(typeof s!="object"||s===null))return r.every(i=>typeof s[i]=="function")?s:void 0},cs="v1",Ca=async(n,e,t=Date.now())=>{if(n.length===0||e.length===0)return!1;const r=e.split(".");if(r.length!==3)return!1;const[s,i,o]=r;if(s!==cs||o.length===0)return!1;const a=Number(i);if(!Number.isFinite(a)||a<=t)return!1;let c;try{c=wt(o)}catch{return!1}return Do(n,`${s}.${i}`,c)},Oa=`${cs}.admin-socket-binding`,Ma=async n=>Lo(n,Oa),ds="__lunoraBranch",Na=n=>typeof n=="object"&&n!==null&&Object.hasOwn(n,ds),xa=`may not contain the reserved workflow branch-marker key ("${ds}")`,Da=/\(exit (\d+)\)/,La=new Set(["contains","eq","gt","gte","has","lt","lte","ne"]),dr=100,Pa="test@lunora.sh",Ba=new Set(["complete","errored","paused","queued","rollingBack","running","terminated","unknown","waiting","waitingForPause"]),ls=null,Xe=(n,e)=>(n===void 0?"":`,"cursor":${String(n)}`)+(e===void 0?"":`,"epoch":${JSON.stringify(e)}`),xe=(n,e)=>{const[t,r]=n.size<=e.size?[n,e]:[e,n];for(const s of t)if(r.has(s))return!0;return!1},qa=n=>{const e=typeof n.id=="string"?n.id:"";if(e.trim()==="")throw new p("MIGRATION_ID_REQUIRED","runMigration: `id` is required",{status:400});return{batchSize:typeof n.batchSize=="number"?n.batchSize:void 0,direction:n.direction==="down"?"down":"up",dryRun:n.dryRun===!0,id:e,maxBatches:typeof n.maxBatches=="number"?n.maxBatches:void 0}},Ua=n=>{const{op:e}=n,t=typeof n.table=="string"?n.table:"";if(e!=="insert"&&e!=="patch"&&e!=="replace"&&e!=="delete")throw new p("BAD_REQUEST","writeRow: `op` must be insert|patch|replace|delete");if(t.trim()==="")throw new p("BAD_REQUEST","writeRow: `table` is required");const r=typeof n.id=="string"?n.id:void 0,s=typeof n.doc=="object"&&n.doc!==null&&!Array.isArray(n.doc)?n.doc:void 0;if(e!=="insert"&&(r===void 0||r===""))throw new p("BAD_REQUEST",`writeRow: \`id\` is required for op "${e}"`);if(e!=="delete"&&s===void 0)throw new p("BAD_REQUEST",`writeRow: \`doc\` is required for op "${e}"`);return{doc:s,id:r,op:e,table:t}},Fa=n=>typeof n=="string"&&As.includes(n),Ha=n=>typeof n=="string"&&Rs.includes(n),Wa=n=>{const e=typeof n.hash=="string"?n.hash.trim():"";if(e==="")throw new p("BAD_REQUEST","issue triage: `hash` is required");return e},$a=n=>{const e=n.assignee;if(e===null)return ls;if(typeof e=="string"&&e.trim()!=="")return e;throw new p("BAD_REQUEST","assignIssue: `assignee` must be a non-empty string (assign) or null (unassign)")},Ka=n=>{const e=n.severity;if(e===null)return ls;if(Ha(e))return e;throw new p("BAD_REQUEST","setIssueSeverity: `severity` must be one of critical|high|medium|low, or null to clear")},Ga=n=>{const e=typeof n.exportName=="string"?n.exportName.trim():"";if(e==="")throw new p("BAD_REQUEST","createWorkflowInstance: `exportName` is required");const t=typeof n.id=="string"?n.id.trim():"",r=t===""?void 0:t;if(Na(n.params))throw new p("BAD_REQUEST",`createWorkflowInstance: params ${xa}`);return{exportName:e,id:r,params:n.params}},Qa=n=>{const e=typeof n.exportName=="string"?n.exportName.trim():"",t=typeof n.id=="string"?n.id.trim():"";if(e==="")throw new p("BAD_REQUEST","getWorkflowInstanceStatus: `exportName` is required");if(t==="")throw new p("BAD_REQUEST","getWorkflowInstanceStatus: `id` is required");return{exportName:e,id:t}},lr="lunora:",ja=n=>{const e=typeof n.exportName=="string"?n.exportName.trim():"",t=typeof n.id=="string"?n.id.trim():"",r=typeof n.type=="string"?n.type:"";if(e==="")throw new p("BAD_REQUEST","sendWorkflowEvent: `exportName` is required");if(t==="")throw new p("BAD_REQUEST","sendWorkflowEvent: `id` is required");if(r.trim()==="")throw new p("BAD_REQUEST","sendWorkflowEvent: `type` is required");if(r.startsWith(lr))throw new p("BAD_REQUEST",`sendWorkflowEvent: event type "${r}" is reserved — the "${lr}" prefix is used by the framework's own events`);return{exportName:e,id:t,payload:n.payload,type:r}},hr=n=>typeof n=="string"&&Ba.has(n)?n:"unknown",za=n=>{if(typeof n!="object"||n===null)return;const{message:e,name:t}=n;return{message:typeof e=="string"?e:"",name:typeof t=="string"?t:"Error"}},Va=(n,e)=>{if(e!==void 0){if(!Array.isArray(e)||!e.every(t=>typeof t=="string"))throw new p("BAD_REQUEST",`the path for ${n} must be a list of field names`);return e.length===0?void 0:e}},Le=n=>{if(!Array.isArray(n))return;const e=[];for(const t of n){if(typeof t!="object"||t===null)continue;const r=t,{column:s,operator:i}=r;if(typeof s!="string"||s===""||typeof i!="string"||!La.has(i))continue;const o=Va(s,r.path),a={column:s,operator:i,value:r.value,...o===void 0?{}:{path:o}};mi(a)||e.push(a)}return e.length>0?e:void 0},Ja=n=>{if(typeof n!="object"||n===null)return;const{column:e,direction:t}=n;if(!(typeof e!="string"||e===""))return{column:e,direction:t==="desc"?"desc":"asc"}},Xa=n=>{const e=typeof n.table=="string"?n.table:"";if(e.trim()==="")throw new p("BAD_REQUEST","deleteRows: `table` is required");const t=Le(n.filters),r=typeof n.search=="string"?n.search:void 0;if((t===void 0||t.length===0)&&(r===void 0||r.trim()===""))throw new p("BAD_REQUEST","deleteRows: a predicate (`filters` or `search`) is required — use `clearTable` to empty the table");return{filters:t,limit:typeof n.limit=="number"?n.limit:void 0,search:r,table:e}},Ya=n=>{const e=typeof n.table=="string"?n.table:"";if(e.trim()==="")throw new p("BAD_REQUEST","patchRows: `table` is required");const t=n.doc,r=typeof t=="object"&&t!==null&&!Array.isArray(t)?t:void 0;if(r===void 0||Object.keys(r).length===0)throw new p("BAD_REQUEST","patchRows: `doc` must be a non-empty object of fields to set");return{after:typeof n.after=="string"?n.after:void 0,doc:r,filters:Le(n.filters),limit:typeof n.limit=="number"?n.limit:void 0,search:typeof n.search=="string"?n.search:void 0,table:e}},Za=n=>{const e=typeof n.table=="string"?n.table:"";if(e.trim()==="")throw new p("BAD_REQUEST","clearTable: `table` is required");return{limit:typeof n.limit=="number"?n.limit:void 0,table:e}},ec=n=>{const{outcome:e}=n;if(e!=="ok"&&e!=="fail")throw new p("BAD_REQUEST",'recordAuthEvent: `outcome` must be "ok" or "fail"');return{outcome:e}},ur=(n,e)=>{if(typeof n!="object"||n===null||Array.isArray(n))throw new p("BAD_REQUEST",`recordImportAudit: \`${e}\` must be an object of counts`);const t={};for(const[r,s]of Object.entries(n)){if(typeof s!="number"||!Number.isInteger(s)||s<0)throw new p("BAD_REQUEST",`recordImportAudit: \`${e}.${r}\` must be a non-negative integer`);t[r]=s}return t},pr=(n,e)=>{if(typeof n!="number"||!Number.isInteger(n)||n<0)throw new p("BAD_REQUEST",`recordImportAudit: \`${e}\` must be a non-negative integer`);return n},fr=(n,e)=>{if(n!==void 0){if(!Array.isArray(n)||!n.every(t=>typeof t=="string"))throw new p("BAD_REQUEST",`recordImportAudit: \`${e}\` must be an array of table names`);return n}},tc=/^[\w-]{1,64}$/u,rc=n=>{const{op:e}=n;if(e!=="importGlobal"&&e!=="importSections")throw new p("BAD_REQUEST",'recordImportAudit: `op` must be "importGlobal" or "importSections"');const t=fr(n.replaceTables,"replaceTables"),r=fr(n.tables,"tables"),{session:s}=n;if(s!==void 0&&(typeof s!="string"||!tc.test(s)))throw new p("BAD_REQUEST","recordImportAudit: `session` must be an import session id");return{detail:{conflicts:pr(n.conflicts,"conflicts"),errors:pr(n.errors,"errors"),inserted:ur(n.inserted,"inserted"),...n.deleted===void 0?{}:{deleted:ur(n.deleted,"deleted")},...r===void 0?{}:{tables:r},...t===void 0?{}:{mode:"replace",replaceTables:t},...t===void 0&&e==="importGlobal"?{mode:"append"}:{},...typeof s=="string"?{session:s}:{}},op:e}},sc=n=>{const e=n.event;if(typeof e!="object"||e===null||Array.isArray(e))throw new p("BAD_REQUEST","recordContainerEvent: `event` must be an object");const t=e,r=typeof t.container=="string"?t.container:"",s=typeof t.event=="string"?t.event:"";if(r.trim()===""||s.trim()==="")throw new p("BAD_REQUEST","recordContainerEvent: `event.container` and `event.event` are required");const i=t.level==="error"?"error":"info",o=typeof t.message=="string"?t.message:void 0,a=typeof t.ts=="number"?t.ts:Date.now(),c=typeof t.instance=="string"&&t.instance!==""?t.instance:void 0,d=o===void 0?void 0:Da.exec(o)?.[1];return{exitCode:d===void 0?void 0:Number.parseInt(d,10),functionPath:`container:${r}`,instance:c,level:i,message:o===void 0||o===""?s:`${s}: ${o}`,timestamp:a}},ic=n=>{const e=typeof n.functionPath=="string"?n.functionPath:"",t=typeof n.userId=="string"?n.userId:"";if(e.trim()==="")throw new p("BAD_REQUEST","runAs: `functionPath` is required");if(e.startsWith(M))throw new p("BAD_REQUEST","runAs: cannot target a reserved admin function");if(t.trim()==="")throw new p("BAD_REQUEST","runAs: `userId` is required");const r=n.args;if(r!==void 0&&(typeof r!="object"||r===null||Array.isArray(r)))throw new p("BAD_REQUEST","runAs: `args` must be an object");const s=n.identity;if(s!==void 0&&(typeof s!="object"||s===null||Array.isArray(s)))throw new p("BAD_REQUEST","runAs: `identity` must be an object");return{args:r===void 0?{}:r,functionPath:e,userId:t,...s===void 0?{}:{identity:s}}},nc=n=>{const e=S=>{throw new p("BAD_REQUEST",`recordMail: ${S}`)},{bcc:t,cc:r,from:s,headers:i,html:o,replyTo:a,subject:c,text:d,to:l}=n;typeof c!="string"&&e("`subject` must be a string"),typeof l=="string"||Array.isArray(l)&&l.every(S=>typeof S=="string")||e("`to` must be a string or string[]");const u=(S,E)=>{if(S!==void 0)return(!Array.isArray(S)||!S.every(g=>typeof g=="string"))&&e(`\`${E}\` must be a string[]`),S},m=(S,E)=>(S!==void 0&&typeof S!="string"&&e(`\`${E}\` must be a string`),S);return{bcc:u(t,"bcc"),cc:u(r,"cc"),from:m(s,"from"),headers:i!==void 0&&typeof i=="object"&&i!==null?i:void 0,html:m(o,"html"),replyTo:m(a,"replyTo"),subject:c,text:m(d,"text"),to:l}},oc=n=>{const{to:e}=n;if(e!==void 0&&typeof e!="string")throw new p("BAD_REQUEST","sendTestMail: `to` must be a string");const t=e??Pa,r="https://example.test/verify?token=demo";return{from:"Lunora <noreply@lunora.sh>",html:`<p>This is a test email from the Lunora dev mail catcher.</p><p><a href="${r}">Verify your email</a></p>`,subject:"Lunora test email",text:`This is a test email from the Lunora dev mail catcher.
|
|
5
|
+
|
|
6
|
+
Verify your email: ${r}`,to:t}},ac=n=>{const e=s=>{throw new p("BAD_REQUEST",`recordQueueMessage: ${s}`)},t=n.messages;Array.isArray(t)||e("`messages` must be an array");const r=new Set(["ack","error","retry"]);return t.map((s,i)=>{(typeof s!="object"||s===null)&&e(`\`messages[${String(i)}]\` must be an object`);const o=s,a=typeof o.messageId=="string"?o.messageId:"",c=typeof o.queue=="string"?o.queue:"",d=typeof o.outcome=="string"?o.outcome:"";a===""&&e(`\`messages[${String(i)}].messageId\` is required`),c===""&&e(`\`messages[${String(i)}].queue\` is required`),r.has(d)||e(`\`messages[${String(i)}].outcome\` must be one of ack | error | retry`);const{attempts:l,timestamp:h}=o;return{attempts:typeof l=="number"&&Number.isFinite(l)?l:1,body:o.body,deadLettered:o.deadLettered===!0,error:typeof o.error=="string"?o.error:void 0,exportName:typeof o.exportName=="string"?o.exportName:void 0,messageId:a,outcome:d,queue:c,timestamp:typeof h=="number"&&Number.isFinite(h)?h:0}})},X=n=>`${n.traceId}:${n.rootSpanId}`,cc=n=>{const e=typeof n.exportName=="string"?n.exportName.trim():"";if(e==="")throw new p("BAD_REQUEST","sendQueueMessage: `exportName` is required");const t=n.delaySeconds;if(t!==void 0&&(typeof t!="number"||!Number.isFinite(t)||t<0))throw new p("BAD_REQUEST","sendQueueMessage: `delaySeconds` must be a non-negative number");const r=Array.isArray(n.batch)?n.batch:void 0;if(r!==void 0&&(r.length===0||r.length>dr))throw new p("BAD_REQUEST",`sendQueueMessage: \`batch\` must contain between 1 and ${String(dr)} messages`);return{batch:r,body:n.body,contentType:typeof n.contentType=="string"?n.contentType:void 0,delaySeconds:t,exportName:e}},dc=n=>{const e=typeof n.id=="string"?n.id.trim():"";if(e==="")throw new p("BAD_REQUEST","replayQueueMessage: `id` is required");const t=typeof n.target=="string"&&n.target.trim()!==""?n.target.trim():void 0;return{id:e,target:t}},mr=(n,e)=>{const t=typeof e.id=="string"?e.id.trim():"";if(t==="")throw new p("BAD_REQUEST",`${n}: \`id\` is required`);return{id:t}},lc=n=>{const e=Array.isArray(n.tables)?n.tables.filter(t=>typeof t=="string"&&t!==""):[];if(e.length===0)throw new p("BAD_REQUEST","releaseShardRegistration: `tables` must name at least one table");return{dryRun:n.dryRun===!0,tables:e}},hc=n=>{const e=typeof n.table=="string"?n.table:"",t=typeof n.index=="string"?n.index:"",r=typeof n.rowId=="string"?n.rowId:"";if(e.trim()==="")throw new p("BAD_REQUEST","rankBefore: `table` is required");if(t.trim()==="")throw new p("BAD_REQUEST","rankBefore: `index` is required");if(typeof n.partitionKey!="string")throw new p("BAD_REQUEST","rankBefore: `partitionKey` must be a string");if(r.trim()==="")throw new p("BAD_REQUEST","rankBefore: `rowId` is required");if(!Array.isArray(n.sortValues))throw new p("BAD_REQUEST","rankBefore: `sortValues` must be an array");return{index:t,partitionKey:n.partitionKey,rowId:r,sortValues:n.sortValues,table:e}},uc=n=>{if(n!==void 0){if(!Array.isArray(n)||!n.every(e=>typeof e=="string"))throw new p("BAD_REQUEST","findRelated: `edges` must be an array of edge-name strings");return n}},pc=n=>{const e=typeof n.table=="string"?n.table:"",t=typeof n.id=="string"?n.id:"";if(e.trim()==="")throw new p("BAD_REQUEST","findRelated: `table` is required");if(t.trim()==="")throw new p("BAD_REQUEST","findRelated: `id` is required");const{cursor:r,depth:s,direction:i,edges:o,limit:a}=n;if(r!=null&&typeof r!="string")throw new p("BAD_REQUEST","findRelated: `cursor` must be a string");if(s!==void 0&&typeof s!="number")throw new p("BAD_REQUEST","findRelated: `depth` must be a number");if(i!==void 0&&i!=="both"&&i!=="in"&&i!=="out")throw new p("BAD_REQUEST",'findRelated: `direction` must be one of "in", "out" or "both"');if(a!==void 0&&typeof a!="number")throw new p("BAD_REQUEST","findRelated: `limit` must be a number");return{cursor:typeof r=="string"?r:void 0,depth:s,direction:i,edges:uc(o),id:t,limit:a,table:e}},Z=n=>{throw new p("BAD_REQUEST",n)},Sr=(n,e)=>((typeof n!="string"||n.trim()==="")&&Z(`rankPage: \`${e}\` is required`),n),fc=n=>{if(n===void 0)return;(typeof n!="object"||n===null||Array.isArray(n))&&Z("rankPage: `after` must be an object");const e=n;return(typeof e.partitionKey!="string"||typeof e.rowId!="string"||!Array.isArray(e.sortValues))&&Z("rankPage: `after` must have a string partitionKey, string rowId, and array sortValues"),{partitionKey:e.partitionKey,rowId:e.rowId,sortValues:e.sortValues}},mc=n=>{const e=Sr(n.table,"table"),t=Sr(n.index,"index");n.take!==void 0&&typeof n.take!="number"&&Z("rankPage: `take` must be a number"),n.cursor!==void 0&&n.cursor!==null&&typeof n.cursor!="string"&&Z("rankPage: `cursor` must be a string or null"),n.partitionKey!==void 0&&typeof n.partitionKey!="string"&&Z("rankPage: `partitionKey` must be a string"),n.directions!==void 0&&!Array.isArray(n.directions)&&Z("rankPage: `directions` must be an array");const r=n.directions===void 0?void 0:n.directions.map(s=>s==="desc"?"desc":"asc");return{after:fc(n.after),cursor:typeof n.cursor=="string"?n.cursor:void 0,directions:r,index:t,partitionKey:typeof n.partitionKey=="string"?n.partitionKey:void 0,take:typeof n.take=="number"?n.take:void 0,table:e}},Sc=n=>{try{const e=JSON.parse(n);if(Array.isArray(e)&&typeof e[0]=="string"&&typeof e[1]=="string")return{index:e[1],table:e[0]}}catch{}},yc=n=>{const e=n.changes;if(!Array.isArray(e))throw new p("BAD_REQUEST","applyCdc: `changes` must be an array");return{changes:e.map((r,s)=>{const i=r,{op:o}=i,a=typeof i.table=="string"?i.table:"",c=typeof i.id=="string"?i.id:"";if(a===""||c===""||o!=="insert"&&o!=="update"&&o!=="delete")throw new p("BAD_REQUEST",`applyCdc: changes[${String(s)}] must have a table, id, and op of insert|update|delete`);const d=i.doc;if(d!==void 0&&(typeof d!="object"||d===null||Array.isArray(d)))throw new p("BAD_REQUEST",`applyCdc: changes[${String(s)}].doc must be an object`);const l=d;if(l!==void 0&&typeof l._id=="string"&&l._id!==c)throw new p("BAD_REQUEST",`applyCdc: changes[${String(s)}].doc._id must match the entry id`);return{doc:l,id:c,op:o,seq:typeof i.seq=="number"?i.seq:0,table:a,ts:typeof i.ts=="number"?i.ts:0}})}},bc=n=>{const e=r=>{const s=typeof r=="number"?r:Number(r);return Number.isFinite(s)&&s>=0?Math.floor(s):void 0},{sinceEpoch:t}=n;return{limit:e(n.limit),...typeof t=="string"&&t.length>0?{sinceEpoch:t}:{},sinceSeq:e(n.sinceSeq)??0}},Y=n=>n?{"x-d1-bookmark":n}:void 0,we=n=>sa(n),gc=n=>{if(!n)return;const e=Number(n);return Number.isInteger(e)&&e>=0?e:void 0},vc=n=>{if(n!==null)return n!=="0"},Ec=n=>{if(!n)return;const e=Number(n);return Number.isInteger(e)&&e>0?e:void 0},Rc=n=>{const e=new Set;for(const t of n){const r=fi(t);r!==""&&e.add(r)}return e},Ac=n=>{if(n===void 0)return;const e=Number.parseInt(n,10);return Number.isFinite(e)&&e>0?e:void 0},wc=(n,e)=>n==="1"||n==="true"?!0:n==="0"||n==="false"?!1:e,Tc=n=>{if(n===void 0)return 1;let e=Number.NaN;return typeof n=="number"?e=n:typeof n=="string"&&n.trim()!==""&&(e=Number(n)),Number.isFinite(e)?Math.min(1,Math.max(0,e)):1},kc=n=>n>=1?!0:n<=0?!1:Math.random()<n,Ye=n=>{if(!n)return;const[e,...t]=n.split(" ");if(e?.toLowerCase()!=="bearer")return;const r=t.join(" ").trim();return r.length>0?r:void 0},yr=(n,e)=>{const t=Array.isArray(n.tables)?n.tables.filter(s=>typeof s=="string"):[];return{byTable:Object.fromEntries(t.map(s=>[s,e(s)])),tables:new Set(t.length===0?[_]:t)}},_c=(n,e)=>{Si(n);const t=typeof e.limit=="number"?e.limit:void 0,r=typeof e.sinceSeq=="number"?e.sinceSeq:void 0;return{result:{entries:yi(n,{limit:t,sinceSeq:r})},tables:new Set([_])}},Ic=(n,e)=>{Zr(n);const t=e.outcome==="ok"||e.outcome==="error"?e.outcome:void 0;return{result:{entries:ws(n,{functionPathPrefix:typeof e.functionPathPrefix=="string"?e.functionPathPrefix:void 0,limit:typeof e.limit=="number"?e.limit:void 0,outcome:t,shardKey:typeof e.shardKey=="string"?e.shardKey:void 0,sinceSeq:typeof e.sinceSeq=="number"?e.sinceSeq:void 0,tableTouched:typeof e.tableTouched=="string"?e.tableTouched:void 0,userId:typeof e.userId=="string"?e.userId:void 0})},tables:new Set([_])}},Cc=(n,e)=>(Zr(n),{result:{issues:Ts(n,{functionPathPrefix:typeof e.functionPathPrefix=="string"?e.functionPathPrefix:void 0,limit:typeof e.limit=="number"?e.limit:void 0,shardKey:typeof e.shardKey=="string"?e.shardKey:void 0,status:Fa(e.status)?e.status:void 0,userId:typeof e.userId=="string"?e.userId:void 0})},tables:new Set([_])}),Oc=n=>{let e;try{e=_s(n)}catch{e={attempts:0,failureRate:0,failures:0,history:[],sinceMs:0}}return{result:e,tables:new Set([_])}},Mc=(n,e)=>{const t=typeof e.limit=="number"?e.limit:void 0;let r;try{r=Ei(n,{limit:t})}catch{r={entries:[]}}return{result:r,tables:new Set([Ri])}},Nc=(n,e)=>{const t=typeof e.limit=="number"?e.limit:void 0,r=typeof e.queue=="string"?e.queue:void 0;let s;try{s=Ai(n,{limit:t,queue:r})}catch{s={entries:[]}}return{result:s,tables:new Set([wi])}},xc=500,Dc=(n,e)=>{const t=typeof e.limit=="number"&&Number.isInteger(e.limit)&&e.limit>0?e.limit:100,r=typeof e.cursor=="string"?e.cursor:void 0,s=new Set([Bt]);return n.exec("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?",Bt).toArray().length===0?{result:{entries:[],nextCursor:void 0},tables:s}:{result:Ti(n,Math.min(t,xc),r),tables:s}},Lc=(n,e,t)=>{const r=typeof e.table=="string"?e.table:"";return{result:bi(n,{column:typeof e.column=="string"?e.column:"",columnKinds:t,filters:Le(e.filters),limit:typeof e.limit=="number"?e.limit:void 0,search:typeof e.search=="string"?e.search:void 0,table:r}),tables:new Set([r===""?_:r])}},Pc=(n,e)=>{const t=typeof e.sql=="string"?e.sql:"";return{result:gi(n,t),tables:new Set([_])}},Bc=(n,e,t)=>{const r=Array.isArray(e.keys)?e.keys.filter(s=>typeof s=="string"):[];return{result:vi(n,t,r),tables:new Set([_])}},qc=(n,e,t)=>{const r=Array.isArray(e.liveKeys)?e.liveKeys.filter(i=>typeof i=="string"):[],s=ks(n,t,r);return s.truncated&&console.warn(`[@lunora/do] storageOrphans scan truncated after checking ${String(s.scanned)} storage references; reporting the first ${String(s.references.length)} dangling reference(s).`),{result:s,tables:new Set([_])}},Uc=(n,e,t)=>{if(n===f.getAuthMetrics)return Oc(e);if(n===f.getCapturedMail)return Mc(e,t);if(n===f.getQueueMessages)return Nc(e,t);if(n===f.getScheduleOutbox)return Dc(e,t)},B=6e4,br=n=>n+B+1,Fc=300,Hc="LUNORA_ALARM_REARM_LIMIT",kt="__lunora_alarm_rearm_window",hs=(n,e)=>{if(n===void 0)return{currentCount:0,previousCount:0,windowStart:e};const t=e-n.windowStart;if(t<B)return n;const r=Math.floor(t/B);return{currentCount:0,previousCount:r===1?n.currentCount:0,windowStart:n.windowStart+r*B}},De=(n,e)=>{const t=Math.min(Math.max(e-n.windowStart,0),B);return n.currentCount+n.previousCount*(1-t/B)},Wc=(n,e)=>De(hs(n,e),e),gr=(n,e,t)=>{const r=hs(n,e);return De(r,e)>=t?{admitted:!1,window:r}:{admitted:!0,window:{...r,currentCount:r.currentCount+1}}},$c=/^\d+$/u,us=(n,e,t)=>{const r=n?.[e];let s=Number.NaN;return typeof r=="number"?s=r:typeof r=="string"&&$c.test(r.trim())&&(s=Number(r.trim())),!Number.isSafeInteger(s)||s<0?t:s===0?void 0:s},Kc=n=>us(n,Hc,Fc),Gc=n=>{n.exec(`CREATE TABLE IF NOT EXISTS "${kt}" (id INTEGER PRIMARY KEY CHECK (id = 0), window_start INTEGER NOT NULL, current_count INTEGER NOT NULL, previous_count INTEGER NOT NULL)`).toArray()},vr=n=>{const[e]=n.exec(`SELECT window_start, current_count, previous_count FROM "${kt}" WHERE id = 0`).toArray();if(e!==void 0)return{currentCount:e.current_count,previousCount:e.previous_count,windowStart:e.window_start}},Qc=(n,e)=>{const t=n.exec(`INSERT INTO "${kt}" (id, window_start, current_count, previous_count) VALUES (0, ?, ?, ?) ON CONFLICT(id) DO UPDATE SET window_start = excluded.window_start, current_count = excluded.current_count, previous_count = excluded.previous_count`,e.windowStart,e.currentCount,e.previousCount);t.toArray();const{rowsWritten:r}=t;return typeof r=="number"?r:void 0},jc=["x-lunora-userid","x-lunora-identity","x-d1-bookmark","x-lunora-client-ip","x-lunora-origin","x-lunora-system","x-lunora-shard-binding",ns],zc=(n,e)=>{const t=new Headers({"content-type":"application/json"});for(const r of jc){const s=n.headers.get(r);s!==null&&t.set(r,s)}return e.mutationId!==void 0&&t.set("x-lunora-mutation-id",e.mutationId),e.clientId!==void 0&&t.set("x-lunora-client-id",e.clientId),e.clientSeq!==void 0&&t.set("x-lunora-client-seq",String(e.clientSeq)),e.baselineSeq!==void 0&&t.set("x-lunora-base-seq",String(e.baselineSeq)),new Request("https://shard.internal/rpc",{body:JSON.stringify({args:e.args??{},functionPath:e.functionPath}),headers:t,method:"POST"})};class Vc{host;forkSealed=!1;cdcLogPresent=!1;cdcEpochCache;constructor(e){this.host=e}sealForkedTimeline(){if(this.forkSealed)return this.cachedCdcEpoch();const e=this.bumpCdcEpochUncached();return this.forkSealed=!0,e}cdcEnabled(){if(this.cdcLogPresent)return!0;try{this.cdcLogPresent=this.host.sql().exec("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?",ki).toArray().length>0}catch{return!1}return this.cdcLogPresent}cachedCdcEpoch(){return this.cdcEpochCache??=_i(this.host.sql()),this.cdcEpochCache}bumpCdcEpochUncached(){const e=Ii(this.host.sql());return this.invalidateCdcMetaCache(),e}invalidateCdcMetaCache(){this.cdcLogPresent=!1,this.cdcEpochCache=void 0}}const Jc="LUNORA_CDC_ARCHIVE",Er="LUNORA_CDC_LOG_RETENTION",Xc=1e6,Yc=n=>{const e=n?.[Er];if(!(typeof e=="string"&&e.trim().toLowerCase()==="off"))return Et(n,Er)??Xc},Zc=6e4,Ze=5e4,ed=1e4,Rr=n=>{if(typeof n!="object"||n===null)return;const e=n[Jc];if(typeof e!="object"||e===null)return;const t=e;return typeof t.get=="function"&&typeof t.list=="function"&&typeof t.put=="function"?e:void 0};class td{host;lastSweepAt=0;constructor(e){this.host=e}sweep(){if(!this.host.enabled())return;const e=Date.now();if(e-this.lastSweepAt<=Zc)return;this.lastSweepAt=e;const t=this.host.env(),r=Yc(t),s=Et(t,"LUNORA_CDC_PAYLOAD_RETENTION");if(r===void 0&&s===void 0)return;const i=s===void 0?void 0:Math.min(s,r??Number.POSITIVE_INFINITY),o=this.host.sql();try{const a=Rr(t);if(a===void 0||r===void 0){this.applyRetention(o,i,r,Number.POSITIVE_INFINITY,Ze);return}const c=Pe(o,i??r);if(c===void 0||c<=0)return;const d=Math.min(c,this.host.retentionFloor(o)),l=Ci(o),h=es(o,{limit:ed,sinceSeq:l}).changes.filter(S=>S.seq<=d),u=h.at(-1)?.seq;if(u===void 0){this.applyRetention(o,i,r,l,Ze);return}const m=(async()=>{try{const E={epoch:this.host.epoch(),shard:this.host.shardKey()};if(await Oi(a,E,l)){this.host.sealTimeline();return}await Mi(a,E,h),Ni(o,u),this.applyRetention(o,i,r,u,Ze)}catch(S){this.host.recordError("cdc:archive",S)}})();this.host.waitUntil?.(m)}catch(a){this.host.recordError("cdc:sweep",a)}}async syncPage(e,t){try{return e()}catch(r){if(!(r instanceof p)||r.code!=="CDC_LOG_TRIMMED")throw r;const s=Rr(this.host.env()),i=this.host.epoch();if(s===void 0||i===void 0)throw r;let o;try{o=await xi(s,{epoch:i,shard:this.host.shardKey()},t.sinceSeq,t.limit)}catch(a){throw this.host.recordError("cdc:archive-read",a),r}if(o===void 0)throw r;return{...o,epoch:i}}}applyRetention(e,t,r,s,i){const o=this.host.retentionFloor(e);if(t!==void 0){const a=Pe(e,t);a!==void 0&&a>0&&Di(e,Math.min(a,o,s),i)}if(r!==void 0){const a=Pe(e,r);a!==void 0&&a>0&&Li(e,Math.min(a,o,s),i)}}}class ps extends p{constructor(){super("FORBIDDEN","AccessDenied")}}const et=()=>new ps,Te=n=>n instanceof ps,fs=200,rd=8;class sd{host;functionStats=new Map;pendingFunctionMetrics=new Map;pendingStmtSamples=new Map;dispatchesSinceFlush=0;pendingForceFlush=!1;pendingStartedAt;pendingLastAt;constructor(e){this.host=e}recordFunctionCall(e,t,r,s,i,o=!1){const a=Date.now(),c=s?[...s]:[];this.foldFunctionMetric(e,t,a,r,c,i,o);const d=this.functionStats.get(e),l=d??{calls:0,conflicts:0,errors:0,lastCalledAt:a,lastErrorAt:null,lastErrorMessage:null,maxDurationMs:0,path:e,scannedTables:[],scans:0,totalDurationMs:0};if(l.calls+=1,l.totalDurationMs+=t,l.maxDurationMs=Math.max(l.maxDurationMs,t),l.lastCalledAt=a,c.length>0&&(l.scans+=c.length,Is(l.scannedTables,c)),r!==void 0&&(l.errors+=1,l.lastErrorAt=a,l.lastErrorMessage=r),o&&(l.conflicts+=1),d===void 0){if(this.functionStats.size>=Mt)return;this.functionStats.set(e,l)}}foldStmtSamples(e){if(e.size!==0)for(const[t,r]of e){const s=`${String(Cs(r.totalDurationMs/r.count))}:${t}`,i=this.pendingStmtSamples.get(s);i===void 0?this.pendingStmtSamples.set(s,{...r,rawSql:t}):(i.count+=r.count,i.rowsRead+=r.rowsRead,i.rowsWritten+=r.rowsWritten,i.totalDurationMs+=r.totalDurationMs)}}maybeFlushMetrics(){this.dispatchesSinceFlush===0&&this.pendingStmtSamples.size===0||(this.pendingForceFlush||this.dispatchesSinceFlush>=this.metricsFlushEvery()||this.pendingStmtSamples.size>=fs)&&this.flushPendingMetrics()}flushUnwrittenMetrics(){(this.dispatchesSinceFlush>0||this.pendingStmtSamples.size>0)&&this.flushPendingMetrics()}collectFunctionStats(e){this.flushUnwrittenMetrics();try{return{functions:Os(this.host.sql()),sinceMs:e}}catch{return{functions:[...this.functionStats.values()].toSorted((r,s)=>s.lastCalledAt-r.lastCalledAt),sinceMs:e}}}collectFunctionMetricBuckets(){this.flushUnwrittenMetrics();try{return Ms(this.host.sql())}catch{return{buckets:[],truncated:!1}}}foldFunctionMetric(e,t,r,s,i,o,a){this.pendingStartedAt!==void 0&&Math.floor(r/Nt)!==Math.floor(this.pendingStartedAt/Nt)&&this.flushPendingMetrics();let c=this.pendingFunctionMetrics.get(e);c===void 0&&this.pendingFunctionMetrics.size>=Mt&&this.flushPendingMetrics(),this.pendingStartedAt??=r,this.pendingLastAt=r,this.dispatchesSinceFlush+=1,(s!==void 0||a)&&(this.pendingForceFlush=!0),c===void 0&&(c={calls:0,conflicts:0,durationMaxMs:t,durationMinMs:t,durationTotalMs:0,errors:0,indexHits:new Map,lastCalledAt:r,lastErrorAt:null,lastErrorMessage:null,scans:new Map},this.pendingFunctionMetrics.set(e,c)),c.calls+=1,c.durationTotalMs+=t,c.lastCalledAt=r,c.durationMinMs=Math.min(c.durationMinMs,t),c.durationMaxMs=Math.max(c.durationMaxMs,t),s!==void 0&&(c.errors+=1,c.lastErrorAt=r,c.lastErrorMessage=s),a&&(c.conflicts+=1);for(const d of new Set(i))c.scans.set(d,(c.scans.get(d)??0)+1);for(const d of o??[])c.indexHits.set(d,(c.indexHits.get(d)??0)+1)}flushPendingMetrics(){const e=this.pendingFunctionMetrics,t=this.pendingStmtSamples,r=this.pendingLastAt??Date.now();this.pendingFunctionMetrics=new Map,this.pendingStmtSamples=new Map,this.pendingStartedAt=void 0,this.pendingLastAt=void 0,this.pendingForceFlush=!1,this.dispatchesSinceFlush=0;let s=0,i=0,o;for(const[c,d]of e)try{Ns(this.host.sql(),{calls:d.calls,conflicts:d.conflicts,durationMaxMs:d.durationMaxMs,durationMinMs:d.durationMinMs,durationMs:d.durationTotalMs,durationTotalMs:d.durationTotalMs,errored:d.errors>0,errorMessage:d.lastErrorMessage??void 0,errors:d.errors,indexHitCounts:[...d.indexHits].map(([l,h])=>({count:h,hit:Sc(l)})).filter(l=>l.hit!==void 0).map(({count:l,hit:h})=>({...h,count:l})),lastErrorAt:d.lastErrorAt,path:c,scanCounts:[...d.scans].map(([l,h])=>({count:h,table:l})),ts:d.lastCalledAt})}catch(l){s+=1,o??=l}const a=this.host.sql();for(const c of t.values())try{xs(a,c.rawSql,c.totalDurationMs,c.rowsRead,c.rowsWritten,r,c.count)}catch(d){i+=1,o??=d}if(s>0||i>0){const c=o instanceof Error?o.message:String(o);console.warn(`[@lunora/do] metric write failed, dropped ${String(s)} function deltas and ${String(i)} statement samples: ${c}`)}}metricsFlushEvery(){const e=(this.host.env()??{}).LUNORA_METRICS_FLUSH_EVERY;let t=Number.NaN;return typeof e=="number"?t=e:typeof e=="string"&&e.trim()!==""&&(t=Number(e)),Number.isInteger(t)&&t>=1?t:rd}}const id=200,ae=n=>Array.isArray(n)?n.filter(e=>typeof e=="string"):[],nd=n=>(Array.isArray(n)?n:[]).map((e,t)=>{const r=e??{};return{doc:r.doc!==null&&typeof r.doc=="object"&&!Array.isArray(r.doc)?r.doc:{},line:typeof r.line=="number"?r.line:t+1,table:typeof r.table=="string"?r.table:""}}),od=n=>n.table.startsWith("$"),ms=(n,e,t)=>({...t,mode:"replace",replaceTables:e,session:n}),_t=n=>{const{generation:e}=n;if(typeof e!="string"||e.length===0)throw new p("BAD_REQUEST","an import session RPC needs the session's `generation`",{status:400});return e},ad=(n,e,t)=>{const r=ye(e.session),s=_t(e),i=ae(e.tables),o=new Set(i),a=nd(e.rows),c=[];Rt(n.sql,t);for(const l of a){const h=od(l)?void 0:Bi(o,l);h!==void 0&&c.push({code:"BAD_ROW",line:l.line,message:h,table:l.table})}const d=c.length>0?{}:qi(n.sql,r,s,a,t);return n.recordAudit("importStage",{detail:ms(r,i,{errors:c.length,staged:d})}),{errors:c,staged:d}},cd=async(n,e,t)=>{const r={};let s=0;for(;;){const o=rs(n.sql,e,{afterSeq:s,limit:id});if(o.rows.length===0)break;const a=await n.runShardImport({replaceTables:t,rows:o.rows.map(({doc:c,table:d})=>({doc:c,table:d})),startLine:1});if(a.errors.length>0)return{conflicts:0,deleted:{},errors:a.errors.map(c=>({...c,line:o.rows[c.line-1]?.line??c.line})),inserted:{}};for(const[c,d]of Object.entries(a.inserted))r[c]=(r[c]??0)+d;s=o.seq}const i=await n.runShardImport({keepIds:Gi(n.sql,e),replaceTables:t,rows:[]});return{conflicts:0,deleted:i.pruned??{},errors:i.errors,inserted:r}},dd=new p("IMPORT_REFUSED","staged import rolled back",{status:400}),ld=async(n,e,t)=>{const r=ye(e.session),s=ae(e.tables),i=e.dryRun===!0,o=_t(e);Rt(n.sql,t);const a=Wi(n.sql,r);if(a!==void 0&&a.generation!==o)throw new p("IMPORT_SESSION_STALE",`import session "${r}" on this shard belongs to an earlier session of the same id`,{status:409});if(a?.state==="committed")return{...a.result,committed:!0};if(e.staged===!0&&a===void 0)throw new p("IMPORT_SESSION_EXPIRED",`import session "${r}" has no staged rows on this shard (expired, or aborted)`,{status:410});a!==void 0&&$i(n.sql,r,t);let c;try{const d=await n.runInTransaction(async()=>{const l=await cd(n,r,s);if(i||l.errors.length>0)throw c=l,dd;return Ki(n.sql,r,o,l,t),l});return n.recordAudit("importCommit",{detail:ms(r,s,{conflicts:d.conflicts,deleted:d.deleted,errors:d.errors.length,inserted:d.inserted})}),{...d,committed:!0}}catch(d){if(c===void 0)throw d;return{conflicts:0,deleted:{},errors:c.errors,inserted:{}}}},hd=n=>{if(typeof n.step=="string"){const{step:e}=n;if(typeof n.claim=="string")return{claim:n.claim,step:e};if(typeof n.release=="string")return{release:n.release,step:e};if(typeof n.claimant=="string")return{claimant:n.claimant,step:e,stepResult:n.stepResult};throw new p("BAD_REQUEST","a commit step's transition needs the `claim`, `release` or `claimant` of the commit running it",{status:400})}switch(n.state){case"aborting":return{state:"aborting"};case"committed":return{state:"committed"};case"committing":{if(typeof n.batches!="number")throw new p("BAD_REQUEST","a commit's `committing` transition needs the `batches` its prepare saw",{status:400});return{batches:n.batches,state:"committing"}}default:throw new p("BAD_REQUEST","importManifest `advance` needs a `step` or a known `state`",{status:400})}},ud=(n,e,t)=>{const r=ye(e.session);switch(e.op){case"advance":return{manifest:Hi(n.sql,r,hd(e),t)};case"drop":return Fi(n.sql,r,t),{dropped:!0};case"get":return{manifest:ts(n.sql,r,t)??null};case"touch":{const s=Rt(n.sql,t);return{...Ui(n.sql,r,{begin:e.begin===!0,globals:e.globals===!0,received:typeof e.received=="number"?e.received:0,rejected:typeof e.rejected=="number"?e.rejected:0,sections:ae(e.sections),shards:ae(e.shards),storage:e.storage===!0,tables:ae(e.tables)},t),expired:s}}default:throw new p("BAD_REQUEST","importManifest `op` must be `touch`, `get`, `advance` or `drop`",{status:400})}},pd=async(n,e,t)=>{const r=Date.now();switch(e){case f.importAbort:{const s=ye(t.session),i=Pi(n.sql,s,_t(t));return n.recordAudit("importAbort",{detail:{aborted:i,mode:"replace",session:s}}),{aborted:i}}case f.importCommit:return ld(n,t,r);case f.importManifest:return ud(n,t,r);case f.importStage:return ad(n,t,r);case f.importStagedRows:{const s=ye(t.session),i=ts(n.sql,s,r)?.state;if(i!=="committing"&&i!=="open")throw new p("IMPORT_SESSION_NOT_COMMITTING",`import session "${s}" is ${i??"gone"}, not committing`,{status:409});return rs(n.sql,s,{afterSeq:typeof t.afterSeq=="number"?t.afterSeq:0,limit:Math.min(Math.max(typeof t.limit=="number"?t.limit:100,1),1e3),sections:ae(t.sections)})}default:return}},fd=Vo;class md{claims=new Map;claim(e,t){if(e===void 0)return;const r=`${e}\0${t}`,s=Date.now(),i=this.claims.get(r);if(i!==void 0&&s-i.claimedAt<fd)return"declined";const o={claimedAt:s,key:r};return this.claims.set(r,o),o}release(e){this.claims.get(e.key)===e&&this.claims.delete(e.key)}}const tt=32,Sd=1024,yd=2e3,Ar=async n=>{const e=Promise.withResolvers(),t=setTimeout(()=>{e.resolve(!1)},yd);try{return await n(e.promise)}finally{clearTimeout(t)}},St=8,wr=[5e3,15e3,45e3,12e4,36e4,108e4,18e5,18e5],me=5e3,bd=n=>wr[Math.min(n,wr.length-1)]??me,gd=n=>Math.min(Number.MAX_SAFE_INTEGER,n+1),vd=n=>typeof n=="string"?n.length>0:ce(n)?n.isLunoraWorkflow===!0?typeof n.className=="string"&&n.className.length>0&&(n.name===void 0||typeof n.name=="string"):typeof n.__lunoraRef=="string"&&n.__lunoraRef.length>0:!1,Ed=n=>{let e;try{e=JSON.parse(n)}catch{return{ok:!1,reason:"its stored payload is not valid JSON",target:void 0}}if(!ce(e)||!Object.hasOwn(e,"args"))return{ok:!1,reason:"its stored payload is not a scheduled call",target:void 0};const{args:t,options:r,target:s,when:i}=e;if(!vd(s))return{ok:!1,reason:"its target is neither a function reference nor a workflow",target:s};if(typeof i!="number"||!Number.isFinite(i))return{ok:!1,reason:"its fire time is missing",target:s};if(r!==void 0&&!ce(r))return{ok:!1,reason:"its options are not an object",target:s};const o={args:t,options:r,target:s,when:i};try{return{args:F(t),envelope:o,ok:!0}}catch{return{ok:!1,reason:"its arguments cannot be decoded",target:s}}},Ss=new WeakSet,yt=n=>n instanceof Error&&Ss.has(n),Tr=async(n,e)=>{const t=n?.cancel;if(typeof t!="function"){const s=new TypeError("no scheduler with a cancel method is configured on this shard, so the cancel cannot be confirmed");throw Ss.add(s),s}return(await t.call(n,e))?.cancelled===!0},kr=(n,e)=>{const t=Promise.withResolvers();return{release:()=>{t.resolve(void 0)},released:t.promise,stale:!1,token:n,version:e}},Rd=(n,e,t)=>n?.dedupKey!==void 0||t===void 0||!Number.isFinite(t)||t<0?{}:{dedupKey:`${e}-${String(t).replace(".","_")}`},_r=(n,e,t)=>new p("SERVICE_UNAVAILABLE",`deferred schedule ${n} was parked, not dropped: ${e}. It will not be handed over; ${yt(t)?"drop it again to remove it without a confirmed cancel":"drop it again once the scheduler answers"}.`,{cause:t}),Ad=n=>{const e=n.options?.retry;return ce(e)&&e.forever===!0},wd=(n,e,t)=>{if(e)return V(n)&&(n.code==="INVALID_INPUT"||n.code==="INVALID_SCHEDULE_ID")?`the scheduler refused the stored call: ${n.code}`:void 0;if(t>=St)return`${String(St)} attempts all failed — last: ${n instanceof Error?n.message:String(n)}`},Td=6048e5;class kd{host;scheduleOutboxAttempts=new Map;scheduleOutboxDrops=new Map;scheduleOutboxDroppedThrough=new Map;scheduleOutboxCancelledThrough=new Map;scheduleOutboxPendingHandOffs=new Map;unconfirmedScheduleOutboxDrops=new Map;lastScheduleOutboxRecordAt=0;constructor(e){this.host=e}scheduleOutbox(){return{forget:e=>{this.finishScheduleOutboxHandOff(e);try{Be(this.host.sql(),e)}catch{}},handOff:async(e,t,r)=>{await this.runScheduleOutboxHandOff(e,t,r===void 0?void 0:Number(r))},record:(e,t)=>(this.lastScheduleOutboxRecordAt=Math.max(Date.now(),this.lastScheduleOutboxRecordAt+.001),Qi(this.host.sql(),e,JSON.stringify(t),this.lastScheduleOutboxRecordAt),this.scheduleOutboxPendingHandOffs.set(e,(this.scheduleOutboxPendingHandOffs.get(e)??0)+1),String(this.lastScheduleOutboxRecordAt)),wake:()=>{this.host.scheduleGlobalPoll(Date.now()+me).catch(()=>{})},admit:e=>this.host.admitScheduleRate(e)}}async pollScheduleOutbox(e){const t=this.host.sql(),r=Date.now();let s;try{s=qe(t)}catch{return}if(!s.populated)return;let i=!1,o=0;if(s.dueAt!==void 0&&s.dueAt<=r){const c=this.host.scheduler(),d=this.fencedScheduleOutboxIds();for(const l of ji(t,r,tt+d.size))d.has(l.id)?i=!0:o<tt&&(o+=1,i=await this.retryScheduleOutboxEntry(t,c,l,e)||i)}zi(t,r-Td);const{dueAt:a}=qe(t);return i&&o<tt&&a!==void 0?Math.max(a,Date.now()+me):a}armScheduleOutboxRetry(){try{qe(this.host.sql()).dueAt!==void 0&&this.host.scheduleGlobalPoll(Date.now()+me).catch(()=>{})}catch{}}async drop(e,t){const r=this.host.sql(),s=G(r,t);if(s===void 0)return{dropped:!1};const i=this.beginScheduleOutboxCancel(t);this.markScheduleOutboxDropped(t,s.createdAt);try{let o,a=!0;try{a=await Tr(this.host.scheduler(),t)}catch(h){o=h instanceof Error?h:new Error(String(h))}this.recordConfirmedScheduleOutboxCancel(t,s.createdAt,a,o);const c=G(r,t);if(c?.version!==s.version){if(o!==void 0)throw this.host.recordAudit(e,"dropOutboxEntry",{id:t,detail:{outcome:"failed"}}),_r(t,o.message,o);return this.host.recordAudit(e,"dropOutboxEntry",{id:t,detail:{outcome:"applied"}}),{dropped:!0}}const d=this.scheduleOutboxAttempts.get(t);o===void 0&&c.parked&&!s.parked&&(o=new Error("a hand-off that landed during the drop could not be cancelled, so the job may still run"));const l=s.parked&&c.parked&&this.unconfirmedScheduleOutboxDrops.get(t)===s.version;if(this.removeUnconfirmableScheduleOutboxDrop(e,r,t,o,l,d))return{dropped:!0};if(o!==void 0)throw this.parkLiveScheduleOutboxEntry(r,t),this.rememberUnconfirmedScheduleOutboxDrop(t,c.version,o),this.host.logs().push({functionPath:"scheduler:outbox",level:"error",message:`deferred schedule ${t} was dropped by an operator but the scheduler could not confirm the cancel (${o.message}). It is parked and will not be handed over; drop it again once the scheduler answers.`,timestamp:Date.now()}),this.host.recordAudit(e,"dropOutboxEntry",{id:t,detail:{outcome:"parked"}}),_r(t,o.message,o);return this.unconfirmedScheduleOutboxDrops.delete(t),d===void 0||d.size===0?qt(r,t):this.parkLiveScheduleOutboxEntry(r,t),this.auditAppliedScheduleOutboxDrop(e,t,a),{dropped:!0}}finally{i()}}retry(e,t){if(this.isScheduleOutboxBeingDropped(e))return"cancelling";if(!Vi(this.host.sql(),e,t))return"missing";for(const i of this.scheduleOutboxAttempts.get(e)??[])i.stale=!0;this.unconfirmedScheduleOutboxDrops.delete(e);const r=this.scheduleOutboxDroppedThrough.get(e),s=G(this.host.sql(),e);return r!==void 0&&s!==void 0&&s.createdAt<=r&&(this.scheduleOutboxDroppedThrough.delete(e),this.scheduleOutboxCancelledThrough.delete(e)),"retried"}auditAppliedScheduleOutboxDrop(e,t,r){r||this.host.logs().push({functionPath:"scheduler:outbox",level:"warn",message:`deferred schedule ${t} was dropped, but the scheduler held no job under that id. Usually it was never accepted; if an earlier hand-off was accepted and only its answer was lost, the job may already have run.`,timestamp:Date.now()}),this.host.recordAudit(e,"dropOutboxEntry",{id:t,detail:r?{outcome:"applied"}:{outcome:"applied",schedulerHeld:!1}})}removeUnconfirmableScheduleOutboxDrop(e,t,r,s,i,o){return!yt(s)||!i||o!==void 0&&o.size>0?!1:(qt(t,r),this.unconfirmedScheduleOutboxDrops.delete(r),this.host.logs().push({functionPath:"scheduler:outbox",level:"warn",message:`deferred schedule ${r} was removed by a repeated drop without a confirmed cancel: no scheduler is configured on this shard to ask. If it was accepted under a scheduler that has since been removed, it may still run there.`,timestamp:Date.now()}),this.host.recordAudit(e,"dropOutboxEntry",{id:r,detail:{outcome:"applied",schedulerHeld:"unknown"}}),!0)}async retryScheduleOutboxEntry(e,t,r,s){const i=this.scheduleOutboxFences(r.id).length>0,o=i?void 0:Ut(e,r.id,Date.now()),a=G(e,r.id);if(o===void 0)return i;const c=gd(o.attempts),d=Ed(o.envelopeJson);if(!d.ok)return this.parkScheduleOutboxEntry(e,o.id,c,d.target,d.reason,s),!1;const{envelope:l}=d,h=Ad(l);if(t===void 0)return h?this.deferScheduleOutboxEntry(e,o.id,c,!0,s):this.parkScheduleOutboxEntry(e,o.id,c,l.target,"no scheduler is configured on this shard",s),!1;const u=kr(a?.createdAt,a?.version),m=this.scheduleOutboxAttempts.get(o.id)??new Set;m.add(u),this.scheduleOutboxAttempts.set(o.id,m);try{await t.runAt(l.when,l.target,d.args,{...l.options,...Rd(l.options,o.id,a?.createdAt),id:o.id}),await this.settleScheduleOutboxHandOff(e,t,o.id,u,this.wasScheduleOutboxDropped(o.id,u),!0,s)}catch(S){await this.settleFailedScheduleOutboxAttempt(e,t,{attempt:u,attempts:c,envelope:l,error:S,forever:h,id:o.id},s)}finally{this.releaseScheduleOutboxAttempt(o.id,m,u)}return!1}async runScheduleOutboxHandOff(e,t,r){try{if(!this.isScheduleOutboxTokenDropped(e,r)&&!await this.awaitScheduleOutboxFences(e)){this.host.scheduleGlobalPoll(Date.now()+me).catch(()=>{});return}await this.handOffRecordedScheduleOutboxCall(e,t,r)}finally{this.finishScheduleOutboxHandOff(e)}}async awaitScheduleOutboxFences(e){return Ar(async t=>{for(let r=this.scheduleOutboxFences(e);r.length>0;r=this.scheduleOutboxFences(e))if(!await Promise.race([Promise.all(r).then(()=>!0),t]))return!1;return!0})}async handOffRecordedScheduleOutboxCall(e,t,r){const s=this.host.sql(),i=G(s,e);if(this.isScheduleOutboxTokenDropped(e,r)||i?.parked===!0)return;const o=kr(r,i?.version),a=this.scheduleOutboxAttempts.get(e)??new Set;a.add(o),this.scheduleOutboxAttempts.set(e,a);try{await t()}catch(c){try{this.wasScheduleOutboxDropped(e,o)&&await this.settleScheduleOutboxHandOff(s,this.host.scheduler(),e,o,!0,!1)}catch{}finally{this.releaseScheduleOutboxAttempt(e,a,o)}throw c}try{await this.settleScheduleOutboxHandOff(s,this.host.scheduler(),e,o,this.wasScheduleOutboxDropped(e,o),!0)}catch{}finally{this.releaseScheduleOutboxAttempt(e,a,o)}}beginScheduleOutboxCancel(e){const t=Promise.withResolvers(),r=this.scheduleOutboxDrops.get(e)??new Set;return r.add(t.promise),this.scheduleOutboxDrops.set(e,r),()=>{r.delete(t.promise),r.size===0&&this.scheduleOutboxDrops.delete(e),t.resolve(void 0),this.pruneScheduleOutboxDropMarker(e)}}recordConfirmedScheduleOutboxCancel(e,t,r,s){s===void 0&&r&&this.scheduleOutboxCancelledThrough.set(e,Math.max(t,this.scheduleOutboxCancelledThrough.get(e)??0))}rememberUnconfirmedScheduleOutboxDrop(e,t,r){if(yt(r)){if(this.unconfirmedScheduleOutboxDrops.delete(e),this.unconfirmedScheduleOutboxDrops.size>=Sd){const[s]=this.unconfirmedScheduleOutboxDrops.keys();s!==void 0&&this.unconfirmedScheduleOutboxDrops.delete(s)}this.unconfirmedScheduleOutboxDrops.set(e,t)}}markScheduleOutboxDropped(e,t){this.scheduleOutboxDroppedThrough.set(e,Math.max(t,this.scheduleOutboxDroppedThrough.get(e)??0))}isScheduleOutboxBeingDropped(e){return(this.scheduleOutboxDrops.get(e)?.size??0)>0}fencedScheduleOutboxIds(){const e=new Set(this.scheduleOutboxDrops.keys());for(const t of this.scheduleOutboxAttempts.keys())this.scheduleOutboxFences(t).length>0&&e.add(t);return e}scheduleOutboxFences(e){const t=[...this.scheduleOutboxDrops.get(e)??[]];for(const r of this.scheduleOutboxAttempts.get(e)??[])this.wasScheduleOutboxDropped(e,r)&&t.push(r.released);return t}finishScheduleOutboxHandOff(e){const t=(this.scheduleOutboxPendingHandOffs.get(e)??0)-1;t>0?this.scheduleOutboxPendingHandOffs.set(e,t):this.scheduleOutboxPendingHandOffs.delete(e),this.pruneScheduleOutboxDropMarker(e)}pruneScheduleOutboxDropMarker(e){(this.scheduleOutboxPendingHandOffs.get(e)??0)===0&&(this.scheduleOutboxAttempts.get(e)?.size??0)===0&&!this.isScheduleOutboxBeingDropped(e)&&(this.scheduleOutboxDroppedThrough.delete(e),this.scheduleOutboxCancelledThrough.delete(e))}async wasScheduleOutboxCancelConfirmed(e,t,r){const s=()=>t!==void 0&&t<=(this.scheduleOutboxCancelledThrough.get(e)??Number.NEGATIVE_INFINITY);return s()||r.length===0||await Ar(async i=>Promise.race([Promise.all(r),i])),s()}isScheduleOutboxTokenDropped(e,t){const r=this.scheduleOutboxDroppedThrough.get(e);return t!==void 0&&r!==void 0&&t<=r}wasScheduleOutboxDropped(e,t){return this.isScheduleOutboxTokenDropped(e,t.token)}releaseScheduleOutboxAttempt(e,t,r){t.delete(r),r.release(),t.size===0&&(this.scheduleOutboxAttempts.delete(e),this.pruneScheduleOutboxDropMarker(e))}async settleFailedScheduleOutboxAttempt(e,t,r,s){const{attempt:i,attempts:o,envelope:a,error:c,forever:d,id:l}=r;if(V(c)&&c.code==="DUPLICATE_SCHEDULE_ID"){await this.settleScheduleOutboxHandOff(e,t,l,i,this.wasScheduleOutboxDropped(l,i),!0,s);return}if(this.wasScheduleOutboxDropped(l,i)){await this.settleScheduleOutboxHandOff(e,t,l,i,!0,!1,s);return}if(i.stale||G(e,l)?.version!==i.version)return;const h=wd(c,d,o);h===void 0?this.deferScheduleOutboxEntry(e,l,o,d,s):this.parkScheduleOutboxEntry(e,l,o,a.target,h,s)}async settleScheduleOutboxHandOff(e,t,r,s,i,o,a){if(!i){G(e,r)?.createdAt===s.token&&Be(e,r);return}const c=()=>{const h=G(e,r)?.version;return h!==void 0&&h!==s.version},d=[...this.scheduleOutboxDrops.get(r)??[]],l=this.beginScheduleOutboxCancel(r);try{const h=await Tr(t,r);if(o&&!h&&!await this.wasScheduleOutboxCancelConfirmed(r,s.token,d))throw new Error("the scheduler no longer holds the job (it already ran or ended), so the drop could not stop it");c()||Be(e,r)}catch(h){c()||this.parkLiveScheduleOutboxEntry(e,r),this.host.logs().push({functionPath:"scheduler:outbox",level:"error",message:`deferred schedule ${r} was dropped while its hand-off was in flight, and cancelling it at the scheduler failed: ${h instanceof Error?h.message:String(h)}. The job may still run; drop the parked entry again once the scheduler answers.`,timestamp:Date.now(),traceId:a?.traceId})}finally{l()}}parkLiveScheduleOutboxEntry(e,t){const r=Ut(e,t,Number.MAX_SAFE_INTEGER);r!==void 0&&Ft(e,t,r.attempts,Date.now())}deferScheduleOutboxEntry(e,t,r,s,i){Ji(e,t,r,Date.now()+bd(r)),s&&r===St&&this.host.logs().push({functionPath:"scheduler:outbox",level:"warn",message:`deferred schedule ${t} is still waiting for the scheduler after ${String(r)} attempts. Its mutation committed; custody keeps retrying (retry.forever).`,timestamp:Date.now(),traceId:i?.traceId})}parkScheduleOutboxEntry(e,t,r,s,i,o){Ft(e,t,r,Date.now()),this.host.logs().push({functionPath:"scheduler:outbox",level:"error",message:`deferred schedule ${t} (target ${s===void 0?"<unreadable>":JSON.stringify(s)}) will not be enqueued: ${i}. Its mutation committed; the job did not.`,timestamp:Date.now(),traceId:o?.traceId})}}const _d=600,Id="LUNORA_SCHEDULE_RATE_LIMIT",It="__lunora_schedule_rate_window",Cd=n=>us(n,Id,_d),Od=n=>{n.exec(`CREATE TABLE IF NOT EXISTS "${It}" (target TEXT PRIMARY KEY, window_start INTEGER NOT NULL, current_count INTEGER NOT NULL, previous_count INTEGER NOT NULL)`).toArray()},Md=(n,e)=>{const[t]=n.exec(`SELECT window_start, current_count, previous_count FROM "${It}" WHERE target = ?`,e).toArray();if(t!==void 0)return{currentCount:t.current_count,previousCount:t.previous_count,windowStart:t.window_start}},Nd=(n,e,t)=>{n.exec(`INSERT INTO "${It}" (target, window_start, current_count, previous_count) VALUES (?, ?, ?, ?) ON CONFLICT(target) DO UPDATE SET window_start = excluded.window_start, current_count = excluded.current_count, previous_count = excluded.previous_count`,e,t.windowStart,t.currentCount,t.previousCount).toArray()},xd=/^[A-Za-z_$][\w$]*$/u,Dd=n=>xd.test(n)?n:`"${n.replaceAll("\\",String.raw`\\`).replaceAll('"',String.raw`\"`)}"`,Ld=500,Pd=8,Bd=(n,e)=>{if(e.includes(n))return H`${H.identifier(n)}`;if(e.includes(Wt))return H`json_extract(${H.identifier(Wt)}, ${`$.${Dd(n)}`})`},qd=(n,e)=>{const t=[...new Set(e.ids.filter(i=>typeof i=="string"&&i!==""))].slice(0,Ld),r=e.relations.slice(0,Pd);if(t.length===0||r.length===0)return{relations:[]};const s=[];for(const i of r){let o;try{o=n.exec(Ht("sqlite",H`PRAGMA table_info(${H.identifier(i.table)})`).sql).toArray().map(d=>d.name)}catch(d){console.warn(`[@lunora/do] backRelationCounts: skipping "${i.table}.${i.column}" — cannot read its columns:`,d);continue}if(o.length===0)continue;const a=Bd(i.column,o);if(a===void 0)continue;const c={};try{const d=Ht("sqlite",H`SELECT ${a} AS ${H.identifier("parent")}, COUNT(*) AS ${H.identifier("n")}
|
|
7
|
+
FROM ${H.identifier(i.table)}
|
|
8
|
+
WHERE ${Xi(a,t,!1)}
|
|
9
|
+
GROUP BY ${a}`),l=n.exec(d.sql,...d.params).toArray();for(const h of l)typeof h.parent=="string"&&(c[h.parent]=h.n)}catch(d){console.warn(`[@lunora/do] backRelationCounts: skipping "${i.table}.${i.column}" — the count query failed:`,d);continue}s.push({column:i.column,counts:c,table:i.table})}return{relations:s}},bt=(n,e)=>typeof n[e]=="string"?n[e]:"",Ir={"1h":3600*1e3,"1m":60*1e3,"5m":300*1e3,"15m":900*1e3},Ud=n=>Ir[bt(n,"range")]??Ir["15m"]??9e5,Cr={lintSql:(n,e,t)=>({result:en(n,bt(e,"sql")),tables:new Set([t])}),backRelationCounts:(n,e,t)=>{const r=Array.isArray(e.ids)?e.ids.filter(i=>typeof i=="string"):[],s=Array.isArray(e.relations)?e.relations.filter(i=>typeof i=="object"&&i!==null&&typeof i.table=="string"&&typeof i.column=="string"):[];return{result:qd(n,{ids:r,relations:s}),tables:new Set([t])}},getQueryInsights:(n,e,t)=>({result:Ds(n,Ud(e)),tables:new Set([t])}),schemaHistory:(n,e,t)=>({result:{versions:Zi(n)},tables:new Set([t])}),schemaVersion:(n,e,t)=>({result:{version:Yi(n,bt(e,"hash"))},tables:new Set([t])})},Fd=(n,e,t,r,s)=>{if(!n.startsWith(e))return;const i=n.slice(e.length);return Object.hasOwn(Cr,i)?Cr[i]?.(t,r,s):void 0},Hd=3e4,Wd=(n,e)=>n.exec("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?",e).toArray().length===0?!1:n.exec(`SELECT 1 FROM ${dt(e)} LIMIT 1`).toArray().length>0;class $d{host;registeredTables=new Set;registryRetryAt=0;registryTail=Promise.resolve();constructor(e){this.host=e}async register(e){await this.serializeRegistry(async()=>{const t=this.host.registry();if(t===void 0||Date.now()<this.registryRetryAt)return;const r=this.host.shardKey();if(ft(r)!==void 0||pt(r)!==void 0)return;const s=[...e].filter(o=>t.shardedTables.has(o)&&!this.registeredTables.has(o));if(s.length===0)return;const i=this.registryWriter(t.namespace);if(i===void 0){console.error(`[@lunora/do] shard registry binding is neither a Durable Object namespace in this shard's jurisdiction nor a registry entrypoint; shard "${r}" is not registered`);return}await Promise.all(s.map(async o=>{this.registeredTables.add(o);try{await i.register(o,r)}catch(a){this.registeredTables.delete(o),this.registryRetryAt=Date.now()+Hd,console.error(`[@lunora/do] could not register shard "${r}" for "${o}"; cross-shard export, sync and migrations miss it until a later write registers it:`,a)}}))})}async release(e,t){return this.serializeRegistry(async()=>{const r=this.host.registry(),s=r===void 0?void 0:this.registryWriter(r.namespace);if(r===void 0||s===void 0)throw new p("BAD_REQUEST","releaseShardRegistration: this shard has no shard registry bound",{status:400});const i=this.host.shardKey(),o=[],a=[];for(const c of e){if(Wd(this.host.sql(),c)){o.push(c);continue}t||(await s.unregister(c,i),this.registeredTables.delete(c)),a.push(c)}return{kept:o,released:a}})}async serializeRegistry(e){const t=this.registryTail.then(e);return this.registryTail=t.then(()=>{},()=>{}),t}registryStub(e){return tn(e,Fo,this.host.jurisdiction())}registryWriter(e){if(!Ho(e)){if(!Wo(e))return;const s=e;return{register:async(i,o)=>s.register(i,o),unregister:async(i,o)=>s.unregister(i,o)}}const t=this.registryStub(e);if(t===void 0)return;const r=ss(this.host.env());return{register:async(s,i)=>Ko(t,s,i,r),unregister:async(s,i)=>$o(t,s,i,r)}}}const Or=-1;class Kd{memos=new WeakMap;index=new WeakMap;shapeFree=new WeakSet;memo(e,t){return this.memos.get(e)?.get(t)}socketMemos(e){return this.memos.get(e)}setMemo(e,t,r){let s=this.memos.get(e);s||(s=new Map,this.memos.set(e,s)),s.set(t,r),this.widen(e,r.tables)}retable(e,t,r){const s=this.memo(e,t);s!==void 0&&(s.tables=r),this.widen(e,r)}restoreMemo(e,t,r,s){this.memo(e,t)===void 0&&this.setMemo(e,t,{generation:Or,lastJson:s,tables:new Set(r)})}forgetRestoredMemo(e,t){return this.memo(e,t)?.generation!==Or?!1:(this.forgetMemo(e,t),!0)}forgetMemo(e,t){this.memos.get(e)?.delete(t)}resubscribed(e,t){this.forgetMemo(e,t),this.index.delete(e)}forgetSocket(e){this.memos.delete(e),this.index.delete(e)}mayCare(e,t){const r=this.index.get(e)?.tables;return r===void 0||xe(r,t)}beginVisit(e){const t={};return this.index.set(e,t),r=>{t.tables=this.memoTableUnion(e,r)}}isShapeFree(e){return this.shapeFree.has(e)}markShapeFree(e){this.shapeFree.add(e)}markHoldsShapes(e){this.shapeFree.delete(e)}memoTableUnion(e,t){const r=this.memos.get(e),s=new Set;for(const i of Object.keys(t)){if(!t[i]?.functionPath)continue;const o=r?.get(i);if(o===void 0||o.retryData||o.tables.has(_))return;for(const a of o.tables)s.add(a)}return s}widen(e,t){const r=this.index.get(e);if(r?.tables!==void 0){if(t.has(_)){this.index.delete(e);return}for(const s of t)r.tables.add(s)}}}const ys=1e3,Gd=6e4,Mr=n=>n<=1?0:Math.min(ys*2**(n-2),Gd);class Qd{bySocket=new WeakMap;hasFailures(e){return(this.bySocket.get(e)?.size??0)>0}retryHintMs(e,t){const r=this.bySocket.get(e)?.get(t);return r===void 0?void 0:Math.max(Mr(r.failures),ys)}streakMark(e,t){return this.bySocket.get(e)?.get(t)}clearIfUnchanged(e,t,r){this.bySocket.get(e)?.get(t)===r&&this.clear(e,t)}isBackingOff(e,t,r,s){const i=this.bySocket.get(e)?.get(t);return i?.identity===r&&s<i.retryAt}recordFailure(e,t,r,s){let i=this.bySocket.get(e);i===void 0&&(i=new Map,this.bySocket.set(e,i));const o=i.get(t),a=o?.identity===r,c=a?o.failures+1:1;return i.set(t,{failures:c,identity:r,retryAt:s+Mr(c)}),!a}clear(e,t){this.bySocket.get(e)?.delete(t)}clearSocket(e){this.bySocket.delete(e)}}const jd=["fetch","runAction","runMutation","runQuery"],zd=["ai","live","notify","push","queues","scheduler","storage","topics"],Vd=new Set(["queues","topics"]),rt=n=>(typeof n=="object"||typeof n=="function")&&n!==null&&typeof n.then=="function",Jd=n=>{const e=new Map,t=new Map,r=(o,a)=>{if(!rt(a))return a;e.set(o,(e.get(o)??0)+1);const c=()=>{e.set(o,(e.get(o)??1)-1)};return Object.getPrototypeOf(a)===Promise.prototype?a.then(d=>(c(),d),d=>{throw c(),d}):(Promise.resolve(a).then(c).catch(c),a)};for(const o of jd){const a=n[o];typeof a=="function"&&(t.set(o,a),n[o]=function(...d){return r(`ctx.${o}`,Reflect.apply(a,this,d))})}const s=new Map,i=(o,a,c=!1)=>{const d=s.get(a);if(d!==void 0)return d;const l=new Proxy(a,{get:(h,u)=>{const m=Reflect.get(h,u);return typeof m=="object"&&m!==null&&s.has(m)?s.get(m):c&&typeof u=="string"&&typeof m=="object"&&m!==null&&!rt(m)?i(`${o}.${u}`,m):typeof m!="function"||typeof u!="string"?m:(...S)=>{const E=Reflect.apply(m,h,S);return u==="bucket"&&typeof E=="object"&&E!==null&&!rt(E)?i(`${o}.bucket`,E):r(`${o}.${u}`,E)}}});return s.set(a,l),l};for(const o of zd){const a=n[o];typeof a=="object"&&a!==null&&(t.set(o,a),n[o]=i(`ctx.${o}`,a,Vd.has(o)))}return()=>{for(const[o,a]of t)n[o]=a;return[...e].filter(([,o])=>o>0).map(([o,a])=>a>1?`${o} ×${String(a)}`:o)}},Xd=new Set([f.createAdminToken,f.listAdminTokens,f.pitrRestore,f.recordAuthEvent,f.recordContainerEvent,f.recordMail,f.recordQueueMessage,f.revokeAdminToken,f.runAs,f.verifyAdminToken]),Yd=/^[0-9a-f]{64}$/u,A=n=>b({result:D(n)},200),bs=n=>new p("WIRE_ENCODE_FAILED",n instanceof Error?n.message:String(n),{cause:n}),Nr=(n,e)=>n!==void 0&&n.functionPath===e.functionPath&&Se(n.args??{})===Se(e.args??{}),st=n=>{try{return D(n)}catch(e){throw bs(e)}},Zd=n=>{try{return Mo(n)?D(n):n}catch(e){throw bs(e)}},el=n=>{let e;try{e=F(n)}catch{throw new p("BAD_REQUEST","malformed admin RPC arguments")}if(e===null||typeof e!="object"||Array.isArray(e))throw new p("BAD_REQUEST","malformed admin RPC arguments");return e},pe=()=>import("../packem_chunks/sql-assistant.mjs"),tl=()=>import("../packem_chunks/ai-opt-in.mjs"),rl=new Set,sl="lunora-ping",il="lunora-pong",xr=(n,e)=>{const t=JSON.stringify(D(e??null));return`{"type":"message","topic":${JSON.stringify(n)},"data":${t}}`},nl=1024*1024,se=n=>n.signal.aborted,ol=1024,Dr=1e4,al=(n,e)=>n?{}:{authenticated:!1,pendingSince:e},cl=n=>{try{n.send(JSON.stringify({error:{code:"UNAUTHENTICATED",message:"session token required in the connect frame"},type:"error"})),n.close?.(4003,"unauthenticated")}catch{}},Ce=({hint:n,why:e})=>({...e===void 0?{}:{why:e},...n===void 0?{}:{hint:n}}),Lr=(n,e,t,r)=>{const{body:s,redacted:i}=P(t,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"internal error"});i&&console.error(`[@lunora/do] ${r}:`,t),N(n,JSON.stringify({error:{code:s.code,message:s.message,...Ce(s)},id:e,type:"error"}))},Q=(n,e)=>{let t=n.get(e);return t||(t=new Map,n.set(e,t)),t};let Pr=!1,Oe;const Br=async()=>{if(!Pr){Pr=!0;try{const e=(await import("cloudflare:workers")).tracing;Oe=e!==null&&typeof e=="object"&&typeof e.enterSpan=="function"?e:void 0}catch{Oe=void 0}}return Oe},Me=(n,e)=>n!==void 0&&Object.hasOwn(n,e)?n[e]:void 0,Ne=(n,e,t)=>{Object.defineProperty(n,e,{configurable:!0,enumerable:!0,value:t,writable:!0})},ie=(n,e)=>{const t=Me(n,e);return n!==void 0&&t!==void 0&&Reflect.deleteProperty(n,e),t},ke=(n,e,t)=>{n!==void 0&&t!==void 0&&Ne(n,e,t)},dl="identity-free",ll=async n=>{for(const e of n)try{await e()}catch(t){console.error("[@lunora/do] after-commit write hook failed; the write committed and its external projection did not:",t)}},hl=15e3,gt=async(n,e)=>{let t;const r=new Promise(s=>{t=setTimeout(s,e,!1)});try{return await Promise.race([n.then(()=>!0),r])}finally{t!==void 0&&clearTimeout(t)}},it=n=>gt(n,hl),qr=2e3,ul=/^\d+$/u,Ur=(n,e,t)=>{const r=n.maxPages;if(r===void 0)return{};let s=Number.NaN;if(typeof r=="number"?s=r:typeof r=="string"&&ul.test(r)&&(s=Number(r)),!Number.isInteger(s)||s<1||s>t){const i=Number.isFinite(t)?`an integer from 1 to ${String(t)}`:"a positive integer";return{rejection:b({error:{code:"BAD_REQUEST",message:`${e}: maxPages must be ${i}, or omitted`}},400)}}return{maxPages:s}},ne="<undelivered>",pl=8*1024*1024,fl=32*1024*1024,j="delivery mode unsupported with delivery authorization",Fr=Object.freeze({code:"DELIVERY_FENCED",message:"Delivery fenced; operation may have committed"}),ml=1073741824,Hr=864e5,Sl=36e5,yl=At({claims:null,ip:null,system:!1,userId:null}),nt=(n,e)=>`paid (\`.x402\`) function "${n}" cannot be ${e}; call it individually over /_lunora/rpc`,Wr=n=>`query "${n}" runs per-dispatch middleware (rate limit, Turnstile), so it cannot be subscribed to; call it as a one-off query, or move the check to a mutation`,ot=(n,e,t)=>n==="count"?`subscription cap of ${String(e)} reached on this socket (live queries and shapes share it); unsubscribe an idle one, or open a second socket`:`failed to persist the socket attachment, which must stay under the ${String(t)}-byte hibernation limit (live queries and shapes share it); shrink the subscription's arguments, unsubscribe an idle one, or open a second socket`,bl=(n,e)=>n.clientId===void 0?`conn:${n.connectionId??e}`:`client:${n.clientId}`,gl=(n,e)=>({ack:()=>{N(n,JSON.stringify({id:e,type:"ack"}))},chunk:(t,r,s)=>N(n,JSON.stringify(r===void 0?{data:t,id:e,type:"chunk"}:{data:t,generation:s,id:e,seq:r,type:"chunk"})),complete:()=>N(n,JSON.stringify({id:e,type:"complete"})),fail:t=>N(n,JSON.stringify({error:t,id:e,type:"error"}))}),_e="__root__",$r=(n,e,t)=>n!==void 0&&!n.retryData&&!n.tables.has(_)&&(!xe(n.tables,e)||!Oo(n,e,t)),vl=n=>{let e={subs:{},...n};return{deserializeAttachment:()=>e,send:()=>{},serializeAttachment:t=>{e=t}}},El=(n,e,t)=>{let r=0,s=0;for(const i of n)i.userId===e&&(r+=1),t!==void 0&&i.userId===""&&i.ip===t&&(s+=1);return{callerConnections:r,ipConnections:s}},Kr=(n,e,t)=>n===void 0&&e!==void 0?{revalidateAt:t+mt}:{},Ie=Tt,Gr=n=>n.userId!==void 0||Tt(n.identity)!=="",O=n=>({identity:n.identity===void 0?void 0:structuredClone(n.identity),ip:n.ip,userId:n.userId}),Qr=n=>{let e;return()=>(e??=structuredClone(n),e)},vt="first-primary",jr=new Set,Rl=n=>{if(!(n===void 0||n.size===0))return n.size===1?[...n][0]:vt},fe=n=>At({claims:n.identity??null,ip:n.ip??null,system:!1,userId:n.userId??null}),zr=fn,Al=200,wl=20,Tl=3e4,at=256,kl=500,ct="lunora.dispatch",_l=n=>n?[...n.values()].flat():[],gs=n=>Object.entries(n?.tallies??{}).filter(e=>e[1]!==void 0&&e[1].calls>0),Vr=n=>n!==void 0&&(n.collector!==void 0||gs(n).length>0),Il=n=>typeof n=="object"&&n!==null&&n.committed===!0,Jr=(n,e,t,r)=>{const s=Date.now(),i=e.get(n)??{last:s,tokens:t},o=Math.min(t,i.tokens+(s-i.last)/1e3*r);return o<1?(e.set(n,{last:s,tokens:o}),!1):(e.set(n,{last:s,tokens:o-1}),!0)},Cl=async n=>{let e;try{e=await n.json()}catch{return{response:b({error:{code:"BAD_REQUEST",message:"invalid JSON body"}},400)}}const t=typeof e.topic=="string"&&e.topic.length>0?e.topic:void 0;if(t===void 0)return{response:b({error:{code:"BAD_REQUEST",message:"topic is required"}},400)};const r=typeof e.stream=="string"&&e.stream.length>0?e.stream:void 0;if(r===void 0)return{response:b({error:{code:"BAD_REQUEST",message:"stream is required"}},400)};const s=typeof e.subscriptionId=="string"&&e.subscriptionId.length>0?e.subscriptionId:void 0;return s===void 0?{response:b({error:{code:"BAD_REQUEST",message:"subscriptionId is required"}},400)}:t.length>oe||s.length>oe?{response:b({error:{code:"BAD_REQUEST",message:`topic and subscriptionId may be at most ${String(oe)} characters`}},400)}:{action:e.action,connectionId:typeof e.connectionId=="string"?e.connectionId:"",key:as(r,t),subscriptionId:s}},Xr=(n,e,t,r,s)=>{const i=Date.now();if(n.expiresAt!==void 0&&n.expiresAt<=i||r!==void 0&&r<=i)return b({error:{code:"TOKEN_EXPIRED",message:"the credential for this live connection has expired"}},401);const o=n.subscriptions.get(e);if(o!==void 0&&o!==t)return b({error:{code:"CONFLICT",message:"subscriptionId is already in use for another topic"}},409);if(!n.subscriptions.has(e)&&n.subscriptions.size>=s)return b({error:{code:"TOO_MANY_LIVE_TOPICS",message:`a live connection may follow at most ${String(s)} topics`}},429)},Yr=n=>{if(n.startsWith(ha)||n.startsWith(z))throw new p("FORBIDDEN_TOPIC","a room or route topic cannot be published to",{status:403});if(n.length>oe)throw new p("BAD_REQUEST",`topic may be at most ${String(oe)} characters`,{status:400})},Ol=new Set([f.importAbort,f.importCommit,f.importManifest,f.importStage,f.importStagedRows]);class v{static MAX_STREAMS_PER_SOCKET=8;static MAX_ATTACHMENT_BYTES=16384;static MAX_SUBSCRIPTIONS_PER_SOCKET=32;static MAX_REACTOR_RUNS_PER_DRAIN=8;static GLOBAL_SHAPE_POLL_INTERVAL_MS=2e3;static GLOBAL_SHAPE_MAX_ROWS=5e4;static GLOBAL_SHAPE_RESYNC_MS=3e4;static MAX_WHISPER_TOPICS_PER_SOCKET=64;static MAX_WHISPER_VERDICTS_PER_SOCKET=256;static MAX_WHISPER_BYTES=4096;static MAX_QUEUED_ROOM_EVENTS=64;static MAX_QUEUED_SOCKET_EVENTS=64;static MAX_LIVE_TOPICS_PER_CONNECTION=64;static MAX_LIVE_TOPICS_PER_SOCKET=8;static MAX_LIVE_CONNECTIONS=1024;static LIVE_KEEPALIVE_MS=25e3;static MAX_LIVE_CONNECTIONS_PER_CALLER=32;static MAX_LIVE_CONNECTIONS_ANONYMOUS_SHARED=256;static MAX_LIVE_QUEUED_BYTES=256*1024;static WHISPER_RATE_BURST=50;static WHISPER_RATE_PER_SEC=25;static rootSizeWarned=!1;static resetRootSizeWarning(){v.rootSizeWarned=!1}static nextPollAlarmTarget(e,t,r,s,i){const a=[e>0?i+v.GLOBAL_SHAPE_POLL_INTERVAL_MS:void 0,t,r,s].filter(c=>c!==void 0).map(c=>Math.max(c,i));return a.length>0?Math.min(...a):void 0}state;env;reactiveCache;ipKeyedFunctionPaths=new Set;shapeProbe=rn();globalPoll=sn();secretValues;companionMemo=new nn;deliveryAuthorization;deliveryFence=new Uo(()=>this.shardHost.sql);deliveryResponsePermits=new WeakMap;deliveryRequestPermits=new WeakMap;currentDeliveryPermit;transactionRequestScope;subscriptionRegistrations=new WeakMap;ctxDbRelationOptions;ctxDbCacheWired;runner;shardHost;socketHost;drizzleHandle;shardInitOnce;transactionDepth=0;afterCommitQueue;afterCommitTail=Promise.resolve();afterCommitStalled=!1;vectorBackfillRunning=!1;currentRequestBookmark;currentResponseBookmark;currentRequestUserId;adminCallTokens=new WeakMap;currentRequestIp;currentRequestOrigin;currentRequestBaselineSeq;currentRequestSampleErrors;currentRequestTraceparent;currentRequestTrace;currentTriggerTrace;traceSampling=new Map;dispatchSpans=new Map;encodedOutcomes=new WeakMap;lastTelemetrySink;rerunNearLimitWarned=new Set;broadcastSkipWarned=!1;currentRequestMutationId;currentRequestClientId;currentRequestClientSeq;currentMutatorClass;mutationBookkeeping;lastIdempotencyTrimAt=0;inFlightClaims=new md;cdcMeta=new Vc({sql:()=>this.sql});cdcRetention=new td({enabled:()=>this.cdcMeta.cdcEnabled(),env:()=>this.env,epoch:()=>this.currentCdcEpoch(),recordError:(e,t)=>{this.recordShapeError(e,t)},retentionFloor:e=>this.retentionFloor(e),sealTimeline:()=>{this.sealForkedTimeline()},shardKey:()=>this.currentShardKey(),sql:()=>this.sql,waitUntil:e=>this.shardHost.waitUntil?.(e)});currentRequestIdentity;currentRequestSystem=!1;pendingChangedTables=void 0;pendingChangedKeys=void 0;pendingChangedBookmarks=void 0;pendingGlobalWriteTables=void 0;unrecordedQueries=new WeakMap;warnedUnpolledGlobalRead=!1;lastBlindRefreshAt;pendingRefreshBookmarks=void 0;pendingRefreshKeys=void 0;pendingRefreshTables=void 0;refreshInFlight=!1;refreshBatches=new WeakMap;socketIndex=new Kd;attachmentCache=new WeakMap;cacheWiredSockets=new WeakSet;tableSetsRefused=new WeakSet;tableSetsRefusedWarned=!1;subscriptionFailures=new Qd;writeGeneration=0;seedRuns=new Map;identityReadPaths=new Set;identityFreePaths=new Set;shapeMemos=new WeakMap;globalShapeSnapshots=new WeakMap;durableSnapshotStoreAvailable=!1;globalPollArmedAt;alarmRearmTripLogged=!1;scheduleRateTripLoggedAt=new Map;pokeSequence=0;whisperBuckets=new WeakMap;roomJoinBuckets=new WeakMap;membershipEpochs=new WeakMap;pendingRoomJoins=new WeakMap;retainedRoomsNeedCleanup=!0;retainedShapesNeedCleanup=!0;failedRoomJoins=new WeakMap;queuedRoomEvents=new WeakMap;queuedSocketEvents=new WeakMap;closingSockets=new WeakSet;loadingSubscribes=new WeakMap;liveGrantSockets=new Set;liveSocketsByConnection=new Map;liveSocketIndexBuilt=!1;roomChains=new WeakMap;routeCloseSent=new WeakSet;whisperVerdicts=new WeakMap;liveSubscribers=new Map;liveKeepalive;streamCancellers=new WeakMap;durableStreams=new on({sql:()=>this.sql,waitUntil:e=>this.shardHost.waitUntil?.(e)});metrics={errors:0,requests:0,sinceMs:Date.now(),subscriptionRefreshErrors:0};fanout={shapePoke:$t(),whisper:$t()};globalPollCursor;globalResyncRequested=!1;lastGlobalResyncAt=0;shardBinding;shardRegistration=new $d({env:()=>this.env,jurisdiction:()=>this.state.id?.jurisdiction,registry:()=>this.shardRegistry(),shardKey:()=>this.currentShardKey(),sql:()=>this.sql});adminBindingMemo;relay;replica;replicaOwnerHost;usedIndexes=new Set;functionMetrics=new sd({env:()=>this.env,sql:()=>this.shardHost.sql});logs=new Ls;scheduleOutboxRunner=new kd({admitScheduleRate:e=>this.admitScheduleRate(e),logs:()=>this.logs,recordAudit:(e,t,r)=>{this.recordAudit(e,t,r)},scheduleGlobalPoll:async(e,t)=>this.scheduleGlobalPoll(e,t),scheduler:()=>this.scheduleOutboxScheduler(),sql:()=>this.sql});spans=new Ps;metricSeries=new Bs;currentScannedTables;currentIndexHits;currentStmtSamples;instrumentedSql;currentStmtSamplesTruncated;constructor(e,t,r={}){this.state=e,this.env=t,this.deliveryAuthorization=r.deliveryAuthorization,e.blockConcurrencyWhile?.(async()=>{await Br()}).catch(()=>{}),this.shardHost=hi(e),this.socketHost=ui(e),this.secretValues=pi(e.storage,t),this.runner=new an(this.shardHost,this.socketHost,{handlers:{handleAlarm:()=>this.handleAlarmCloudflare(),handleFetch:o=>this.handleFetchCloudflare(o)}}),r.reactiveCache&&(this.reactiveCache=new cn(r.reactiveCache)),this.ctxDbCacheWired=r.ctxDbCacheWired??!1;try{this.lastTelemetrySink=r.telemetrySink?.()}catch{}this.ctxDbRelationOptions={...r.maxRelationKeys===void 0?{}:{maxRelationKeys:r.maxRelationKeys},...r.relationExistsPushDown===void 0?{}:{relationExistsPushDown:r.relationExistsPushDown}};const s={doName:()=>this.runner.shardKey,env:()=>this.env,shardBinding:()=>this.shardBinding,shardJurisdiction:()=>this.state.id?.jurisdiction,sql:()=>this.sql},i={...s,buildShapeDiff:(o,a,c)=>this.diffRelayedShape(o,a,c),relayRoomEvent:o=>this.relayRoomEvent(o),computeOpLogShapeSeed:(o,a)=>this.computeOpLogShapeSeed(o,a),currentCdcEpoch:()=>this.currentCdcEpoch(),deliverWhisperLocal:(o,a,c)=>this.deliverWhisperLocal(o,a,c),deliverLiveLocal:(o,a,c)=>this.deliverLiveLocal(o,a,c),dropIfLapsed:o=>this.dropIfLapsed(o),liveControl:o=>this.handleLiveSocketControl(o),getWebSockets:()=>this.runner.sockets(),maskMetadata:()=>this.maskMetadata(),nextPokeId:()=>(this.pokeSequence+=1,`poke-${String(this.pokeSequence)}`),readAttachment:o=>this.readAttachment(o),recordShapePokeFanout:(o,a,c)=>{this.fanout.shapePoke=Ge(this.fanout.shapePoke,o,a,c)},resolveShape:(o,a,c)=>this.resolveShape(o,a,c),rlsMetadata:()=>this.rlsMetadata()};this.relay=this.deliveryAuthorization?void 0:dn(i),this.replicaOwnerHost={...s,exportRows:async()=>this.runShardExport({}),ownerCursor:()=>this.currentCdcCursor(),ownerEpoch:()=>this.currentCdcEpoch(),ownerFloor:()=>this.cdcMeta.cdcEnabled()?ln(this.sql):void 0,readChanges:(o,a)=>this.runShardCdcSync({limit:a,sinceSeq:o}),rowCount:()=>Ue(this.sql).filter(o=>this.tableColumns(o.name).length>0).reduce((o,a)=>o+a.rowCount,0)},this.replica=hn({...s,applyChanges:async o=>{const{applied:a}=await this.runInTransaction(()=>this.runShardApplyCdc({changes:o}),{independent:!0});try{await this.flushChangedTables()}catch(c){this.recordShapeError("replica.flush",c)}return a},exportRows:async()=>this.runShardExport({}),importRows:async o=>this.runShardImport({rows:o}),reportError:(o,a)=>{this.recordShapeError(o,a)},transactionLimits:()=>this.transactionLimits()}),this.armWebSocketKeepalive()}async fetch(e){if(await this.ensureShardInit(),!this.deliveryAuthorization)return this.runner.handleFetch(e);const t=new URL(e.url);return t.pathname==="/_lunora/delivery-fence"?this.installDeliveryFence(e):this.deliveryRoleSupported()?e.headers.get("Upgrade")?.toLowerCase()==="websocket"?this.socketRoute(t.pathname)!==void 0?b({error:{code:"NOT_IMPLEMENTED",message:j}},501):this.runner.handleFetch(e):t.pathname==="/rpc-batch"&&e.method==="POST"?this.runner.handleFetch(e):t.pathname==="/_lunora/route"?b({relayCount:0}):t.pathname===ar&&e.method==="POST"?this.runner.handleFetch(e):t.pathname!=="/rpc"||e.method!=="POST"?b({error:{code:"NOT_IMPLEMENTED",message:j}},501):this.fetchAuthorizedRpc(e):this.runner.shardKey!==void 0&&ft(this.runner.shardKey)!==void 0?new Response("replica does not support delivery authorization; route to owner",{status:421}):b({error:{code:"NOT_IMPLEMENTED",message:j}},501)}async webSocketMessage(e,t){const r=this.runner.socketFor(e),s=this.closingSockets.has(r);return await this.ensureShardInit(),this.handleWebSocketMessage(r,t,s)}async webSocketClose(e,t,r,s){const i=this.runner.socketFor(e);if(this.closingSockets.has(i))return;this.closingSockets.add(i),await this.ensureShardInit(),this.rejectRetainedRooms(i);const o=this.readAttachment(i);let a;try{try{await this.dispatchCloseHooks(i,o)}finally{for(const c of o.whispers??[])if(this.roomHandlerPath(c)!==void 0){const d=this.dispatchRoomEvent(i,c,"leave",void 0,void 0,{...o});this.shardHost.waitUntil?.(d)}}}catch(c){a={error:c}}finally{const c=this.streamCancellers.get(i);if(c){for(const d of c.values())d.abort();this.streamCancellers.delete(i)}this.socketIndex.forgetSocket(i),this.subscriptionFailures.clearSocket(i),this.shapeMemos.delete(i),this.globalShapeSnapshots.delete(i),this.liveGrantSockets.delete(i),o.connectionId!==void 0&&this.liveSocketsByConnection.get(o.connectionId)===i&&this.liveSocketsByConnection.delete(o.connectionId),this.purgeDurableSocketBaselines(o.connectionId);try{await gt(Promise.resolve(this.relay?.releaseRelayShapes(i)),qr)}catch(d){console.error("[@lunora/do] relay shape release failed during socket close:",d)}this.writeAttachment(i,void 0);try{await gt(Promise.resolve(this.relay?.announceDrain(i)),qr)}catch(d){console.error("[@lunora/do] relay drain failed during socket close:",d)}}if(a!==void 0)throw a.error}async webSocketError(e,t){try{await this.webSocketClose(e,1006,"websocket error",!1)}catch(r){console.error("[@lunora/do] socket error teardown failed:",r,"(original socket error:",t,")")}}async alarm(){return await this.ensureShardInit(),this.withTriggerTrace("alarm",async()=>this.runner.handleAlarm())}admitPendingSocket(e,t){if(t)return!0;let r=0;for(const s of this.socketHost.getSockets()){const i=s.deserializeAttachment();if(i?.authenticated===!1){if((i.pendingSince??e)+Dr<=e){this.dropLiveSocket(i.connectionId);try{s.close(4003,"connect deadline")}catch{}continue}r+=1}}return r<ol}refusePendingSocket(e){this.dropLiveSocket(this.readAttachment(e).connectionId),cl(e)}dropLiveSocket(e){e!==void 0&&this.liveSocketsByConnection.delete(e)}lifecycleHookPaths(e){return[]}roomHandlerPath(e){}socketRoute(e){}async dispatchLifecycle(e,t){for(const r of this.lifecycleHookPaths(e)){const s=t.event;await this.withSensitiveScope(r,s,async i=>{try{await this.withRequestIdentity(t.userId,t.identity,t.ip,()=>this.withSystemDispatch(()=>this.handleRpc(r,s,void 0,void 0,void 0,i)))}catch(o){this.logs.push({functionPath:r,level:"error",message:i.text(o instanceof Error?o.message:String(o)),timestamp:Date.now()})}})}await this.flushAfterDispatch(`lifecycle:${e}:flush`)}async dispatchReactors(e,t){const r=this.lifecycleHookPaths("reactor");if(r.length===0)return;const s=this.sql;for(const i of r){let o;try{o=un(s,i)}catch(a){this.recordReactorError(i,a)}pn(o,e)&&this.claimReactorBudget(i,t)&&await this.dispatchOneReactor(s,i,o?.digest)}}async runReactor(e,t){await Promise.resolve()}recordReactorError(e,t,r){this.recordShapeError(`reactor:${e}`,t,r)}async dispatchShardInit(){const e={shardKey:this.currentShardKey()};for(const t of this.lifecycleHookPaths("init"))try{await this.withSensitiveScope(t,e,r=>this.withSystemDispatch(()=>this.handleRpc(t,e,void 0,void 0,void 0,r)))}catch(r){this.recordShardInitError(t,r)}await this.flushAfterDispatch("shardInit:flush")}runRelationFanoutRead(e,t){throw new p("NOT_IMPLEMENTED","__lunora_relation__: no schema bound — the base ShardDO cannot serve cross-shard relation reads",{status:500})}get sql(){const e=this.shardHost.sql,t=this.currentStmtSamples;if(t===void 0)return e;if(this.instrumentedSql?.samples===t)return this.instrumentedSql.proxy;const r=e.exec;if(typeof r!="function")return e;const s=(a,c,d,l)=>{const h=t.get(a);if(h!==void 0){h.count+=1,h.totalDurationMs+=c,h.rowsRead+=d,h.rowsWritten+=l;return}if(t.size>=fs){this.currentStmtSamplesTruncated=!0;return}t.set(a,{count:1,rowsRead:d,rowsWritten:l,totalDurationMs:c})},i=(a,...c)=>{const d=Date.now(),l=r.call(e,a,...c);let h=!1;if(l!==null&&typeof l=="object"){const u=l,m=R=>{const y=u[R];return typeof y=="number"&&Number.isFinite(y)?y:void 0},S=(R,y)=>{const w=u[R];if(typeof w!="function")return!1;const T=w.bind(u);return u[R]=()=>{const k=T();return s(a,Date.now()-d,m("rowsRead")??y(k),m("rowsWritten")??0),k},!0},E=S("toArray",R=>R.length),g=S("one",()=>1);h=E||g}return h||s(a,Date.now()-d,0,0),l},o=new Proxy(e,{get(a,c){return c==="exec"?i:Reflect.get(a,c,a)}});return this.instrumentedSql={proxy:o,samples:t},o}get db(){return this.drizzleHandle?this.drizzleHandle:(this.drizzleHandle=No(this.state.storage,{logger:!1}),this.drizzleHandle)}isInTransaction(){return this.transactionDepth>0}async deferPastResponse(e){this.runner.background(e)||await e}async deferAfterCommit(e){if(this.afterCommitQueue){this.afterCommitQueue.push(e);return}let t=!0,r;const s=this.linkAfterCommit(async()=>{try{await e()}catch(i){t?r={error:i}:console.error("[@lunora/do] after-commit write hook failed; the write committed and its external projection did not:",i)}});if(this.afterCommitStalled||!await it(s)){t=!1,this.afterCommitStalled=!0;return}if(r)throw r.error}async runInTransaction(e,t){if(this.transactionDepth>0&&!t?.independent)throw new p("NESTED_TRANSACTION","nested transactions are not supported in SQLite-in-DO",{status:500});const r=this.shardHost.sql;if(!r||typeof r.exec!="function")throw new p("SQL_UNAVAILABLE","storage.sql is not available on this ShardDO state",{status:500});const s=this.captureRequestScope();let i=[],o=Promise.resolve(),a;try{a=await this.runner.runInTransaction(async()=>{if(this.transactionDepth>0)throw new p("NESTED_TRANSACTION","nested transactions are not supported in SQLite-in-DO",{status:500});this.restoreRequestScope(s),this.transactionDepth=1,this.transactionRequestScope=s,i=[],this.afterCommitQueue=i;try{return await e()}finally{this.transactionDepth=0,this.transactionRequestScope=void 0,this.afterCommitQueue=void 0}},()=>{i.length!==0&&(o=this.linkAfterCommit(async()=>ll(i)))})}catch(c){throw this.invalidateCompanionMemo(),this.cdcMeta.invalidateCdcMetaCache(),c}return i.length===0||this.afterCommitStalled||(this.afterCommitStalled=!await it(o)),a}getInboundBookmark(){return this.currentRequestBookmark}getCurrentUserId(){return this.currentRequestUserId}getCurrentIp(){return this.currentRequestIp}noteIdentityRead(e){this.identityReadPaths.add(e),this.identityFreePaths.delete(e)}getCurrentOrigin(){return this.currentRequestOrigin}getCurrentBaselineSeq(){return this.currentRequestBaselineSeq}recordStalePatchDropped(e){this.logs.push({level:"warn",message:`dropStalePatches: discarded a stale patch on "${e.table}" row ${e.id} (fields: ${e.fields.join(", ")}) — those fields changed after the caller's baseline`,timestamp:Date.now()})}getCurrentTraceparent(){const e=this.currentRequestTrace;return this.currentRequestTraceparent??(e===void 0?void 0:fa(e.traceId,e.rootSpanId))}getCurrentSampleErrors(){return this.currentRequestSampleErrors}getCurrentTrace(){return this.currentRequestTrace}getCurrentIdentity(){return this.currentRequestIdentity}getCurrentMutationId(){return this.currentRequestMutationId}isSystemDispatch(){return this.currentRequestSystem}runShardDataMigration(e){return Promise.reject(new p("MIGRATION_NOT_FOUND",`data migration "${e.id}" is not registered`,{status:404}))}runShardSearchBackfill(e){throw new p("NOT_IMPLEMENTED","search backfill is unavailable: this shard was built without a generated schema")}runShardVectorBackfill(e){return Promise.reject(new p("NOT_IMPLEMENTED","vector backfill is unavailable: this shard declares no vector index, or its host has no vector store"))}async runOrderedAfterWrites(e,t){let r=a=>{};const s=new Promise(a=>{r=a}),i=it(s.then(()=>{}));try{await this.runInTransaction(async()=>{const a=e();await this.deferAfterCommit(async()=>{try{r({ok:!0,value:await t(a)})}catch(c){r({error:c,ok:!1})}})})}catch(a){throw r({error:a,ok:!1}),a}if(!await i)throw new p("SERVICE_UNAVAILABLE","ordered work did not finish in time: an earlier after-commit hook is stalled; retry later");const o=await s;if(!o.ok)throw o.error;return o.value}ensureMigrated(){}tableRefs(e){}tableIndexes(e){return[]}tableColumns(e){return[]}storageColumns(){return{}}advisories(){return[]}rlsMetadata(){return{policies:[],roles:[]}}maskMetadata(){return{columns:[]}}storageRulesMetadata(){return{rules:[]}}studioFeatures(){return{analytics:!1,auth:!1,containers:!1,flags:!1,kv:!1,mail:!1,notifications:!1,payments:!1,privacy:!1,queues:!1,scheduler:!1,storage:!1,vectors:!1,workflows:!1}}evaluateFlags(e){return Promise.resolve({configured:!1,flags:[]})}runFlagSubscriptionRead(e,t,r){return Promise.resolve(null)}queuesMetadata(){return{queues:[]}}workflowsMetadata(){return{workflows:[]}}async workflowEvent(e){}runtimeAdvisories(){const e=new Set([...this.usedIndexes].map(r=>r.slice(0,r.indexOf(":")))),t=[];for(const r of e)for(const s of this.tableIndexes(r))s.type==="vector"||this.usedIndexes.has(`${r}:${s.name}`)||t.push({cacheKey:`unused_index:${r}:${s.name}`,categories:["PERFORMANCE"],description:"A declared index has not been exercised by any query since this shard instance started. An unused index costs storage and is maintained on every write for no read benefit.",detail:`Index "${s.name}" on table "${r}" has not been used since this instance woke, though other indexes on "${r}" have — it may be redundant.`,facing:"INTERNAL",level:"INFO",metadata:{index:s.name,indexKind:s.type,since:"instance-woke",table:r},name:"unused_index",remediation:"Confirm over a representative window, then drop the index if no query needs it.",title:"Unused index"});return t}runShardExport(e){return Promise.resolve([])}runShardImport(e){return Promise.resolve({conflicts:0,deleted:0,errors:[],inserted:{},replaced:0})}runShardWrite(e,t){return Promise.reject(new p("UNKNOWN_TABLE",`unknown table: ${e.table}`,{status:404}))}async runShardBulkRowOp(e,t,r){const s=Math.min(Math.max(Math.trunc(e.limit??zr),1),zr),{hasMore:i,ids:o}=mn(this.sql,{after:r,columnKinds:this.columnKinds(e.table),filters:e.filters,limit:s,search:e.search,table:e.table});let a=0;for(const c of o)await t(c)&&(a+=1);return{count:a,cursor:r===void 0?void 0:o.at(-1),hasMore:i}}runShardRankBefore(e){return Promise.reject(new p("NOT_IMPLEMENTED","rankBefore is not implemented in base ShardDO",{status:500}))}runShardFindRelated(e){return Promise.reject(new p("NOT_IMPLEMENTED","findRelated is not implemented in base ShardDO",{status:500}))}runShardRankPage(e){return Promise.reject(new p("NOT_IMPLEMENTED","rankPage is not implemented in base ShardDO",{status:500}))}runShardCdcSync(e){const t=this.sql;if(!this.cdcMeta.cdcEnabled())return{changes:[],cursor:e.sinceSeq};const r=Fe(t),s=this.cdcMeta.cachedCdcEpoch();if(e.sinceEpoch!==void 0&&e.sinceEpoch!==s)throw new p("CDC_TIMELINE_FORKED",`cdc epoch ${e.sinceEpoch} is not this shard's current epoch ${s}; the changelog forked after the page you last read (a point-in-time restore, or a rolled-back archive) and an incremental cursor cannot cross a fork — re-seed from a snapshot and resume at epoch ${s}`,{data:{cursor:r,epoch:s},status:409});if(e.sinceSeq>r)throw Sn(r,e.sinceSeq,"shard",this.sealForkedTimeline());const i=He(t);if(i!==void 0&&ge(i,e.sinceSeq))throw yn(i,e.sinceSeq,"shard");const o=es(t,{limit:e.limit,sinceSeq:e.sinceSeq}),a=o.changes.find(c=>c.op!=="delete"&&c.doc===void 0);if(a!==void 0)throw new p("CDC_PAYLOAD_COMPACTED",`cdc payloads at or before seq ${String(a.seq)} have been compacted; resume from a snapshot (sinceSeq ${String(e.sinceSeq)} is below the retained payload window)`,{status:409});return{...o,epoch:s}}cdcSyncPage(e){return this.cdcRetention.syncPage(()=>this.runShardCdcSync(e),e)}currentCdcCursor(){return this.cdcMeta.cdcEnabled()?Fe(this.sql):void 0}currentCdcEpoch(){return this.cdcMeta.cdcEnabled()?this.cdcMeta.cachedCdcEpoch():void 0}sealForkedTimeline(){return this.cdcMeta.sealForkedTimeline()}evaluateResume(e,t,r){const s=this.sql;if(!this.cdcMeta.cdcEnabled())return{cursor:void 0,epoch:void 0,resumable:!1};const i=Fe(s),o=this.cdcMeta.cachedCdcEpoch();if(r!==o)return{cursor:i,epoch:o,resumable:!1};if(e>i)return{cursor:i,epoch:this.sealForkedTimeline(),resumable:!1};if(!bn(s,t))return{cursor:i,epoch:o,resumable:!1};if(e===i)return{cursor:i,epoch:o,resumable:!0};const a=He(s);return a===void 0||ge(a,e)?{cursor:i,epoch:o,resumable:!1}:{cursor:i,epoch:o,resumable:!gn(s,e,t)}}idempotencyNamespace(){const e=this.currentRequestUserId;if(e!==void 0&&e.length>0)return e;if(this.currentRequestSystem)return"system:";const t=this.currentRequestClientId;return t!==void 0&&t.length>0?`anon:${t}`:void 0}readIdempotentResult(e){const t=this.idempotencyNamespace();if(e===void 0||t===void 0)return;let r;try{const s=We(this.sql,t,e);r=s===void 0?void 0:{value:JSON.parse(s.resultJson)}}catch(s){if(this.deliveryAuthorization)throw s;return}return r!==void 0&&this.deliveryAuthorization&&this.deliveryFence.assertReceipt(t,e,this.currentDeliveryPermit),r}persistIdempotentResult(e){const t=this.idempotencyNamespace();if(this.currentRequestMutationId===void 0||t===void 0)return;const r=Date.now(),s=JSON.stringify(e);try{const i=this.deliveryAuthorization?We(this.sql,t,this.currentRequestMutationId):void 0;if(vn(this.sql,t,this.currentRequestMutationId,s,r),this.deliveryAuthorization&&i===void 0&&We(this.sql,t,this.currentRequestMutationId)?.resultJson===s&&this.deliveryFence.recordReceipt(t,this.currentRequestMutationId,this.currentDeliveryPermit,r),r-this.lastIdempotencyTrimAt>Sl){this.lastIdempotencyTrimAt=r;try{this.deliveryAuthorization&&this.deliveryFence.trimReceipts(r-Hr),En(this.sql,r-Hr)}catch{}}}catch(i){if(this.deliveryAuthorization)throw i}}isCustomMutator(e){return!1}prepareFunction(e,t){}holdShardWhileLoading(e){return this.shardHost.runSerialized(async()=>{await e()})}isMutationFunction(e){return!0}classifyClientMutation(){const e=this.currentRequestClientId,t=this.currentRequestClientSeq;if(e===void 0||t===void 0)return;const r=this.currentRequestUserId??"";let s;try{s=$e(this.sql,r,e)}catch{try{Rn(this.sql),s=$e(this.sql,r,e)}catch{return}}const i=s+1;return t<=s?{expected:i,kind:"already"}:t===i?{expected:i,kind:"next"}:{expected:i,kind:"gap"}}rejectNonNextMutation(e,t,r,s){if(!(t===void 0||t.kind==="next"))return this.functionMetrics.recordFunctionCall(e,Date.now()-r,void 0,s.scannedTables,s.indexHits),this.functionMetrics.maybeFlushMetrics(),t.kind==="already"?b({lastMutationId:t.expected-1,result:null},200,Y(this.currentResponseBookmark)):b({error:{code:"OUT_OF_ORDER",expectedMutationId:t.expected,message:`out-of-order mutation; expected sequence ${String(t.expected)}`}},409,Y(this.currentResponseBookmark))}respondFromIdempotencyCache(e,t,r,s,i){if(this.functionMetrics.recordFunctionCall(e,Date.now()-t,void 0,i.scannedTables,i.indexHits),this.functionMetrics.maybeFlushMetrics(),r?.kind==="next")return this.advanceClientMutationWatermark(),this.buildDispatchResponse(r,s);const o=this.mutationCommitCursor();return b(o===void 0?{result:s}:{commitCursor:o,result:s},200,Y(this.currentResponseBookmark))}mutationCommitCursor(){return this.currentRequestMutationId===void 0?void 0:this.currentCdcCursor()}buildDispatchResponse(e,t){if(e?.kind==="next")return b({lastMutationId:this.currentRequestClientSeq,result:t},200,Y(this.currentResponseBookmark));const r=this.mutationCommitCursor();return b(r===void 0?{result:t}:{commitCursor:r,result:t},200,Y(this.currentResponseBookmark))}commitMutationBookkeeping(e){this.transactionRequestScope!==void 0&&this.restoreRequestScope(this.transactionRequestScope),this.persistIdempotentResult(st(e)),this.currentMutatorClass?.kind==="next"&&this.advanceClientMutationWatermark({strict:!0}),this.mutationBookkeeping={mutationId:this.currentRequestMutationId}}recordPostDispatchBookkeeping(e,t){this.mutationBookkeeping!==void 0&&this.mutationBookkeeping.mutationId===this.currentRequestMutationId||(this.persistIdempotentResult(st(e)),t?.kind==="next"&&this.advanceClientMutationWatermark())}advanceClientMutationWatermark(e){const t=this.currentRequestClientId,r=this.currentRequestClientSeq;if(!(t===void 0||r===void 0))try{An(this.sql,this.currentRequestUserId??"",t,r)}catch(s){if(e?.strict)throw s}}runShardApplyCdc(e){return Promise.reject(new p("NOT_IMPLEMENTED","applyCdc is not implemented in base ShardDO",{status:500}))}isPaidFunction(e){return!1}isPerDispatchFunction(e){return!1}sensitiveArgNames(e){return rl}openSensitiveScope(e,t){const r=this.sensitiveArgNames(e);return qs(xt(t,r),Dt(t,r))}async withSensitiveScope(e,t,r){const s=this.openSensitiveScope(e,t);try{return await r(s)}finally{s.clear()}}maskSensitiveError(e,t){return e instanceof Error?(e.message=t.text(e.message),e.stack!==void 0&&(e.stack=t.text(e.stack)),e):new Error(t.text(String(e)))}admitSensitiveArgs(e,t,r){this.admitSensitiveValues(e,r,this.sensitiveArgNames(t))}admitSensitiveValues(e,t,r){e?.add(xt(t,r),Dt(t,r))}subscribe(e,t,r){const s=r.functionPath===void 0?void 0:this.liveQueryRefusal(r.functionPath);if(s!==void 0)return s.status;const i=this.readAttachmentCopy(e),o=Object.hasOwn(i.subs,t)?i.subs[t]:void 0;if(o===void 0&&Object.keys(i.subs).length+Object.keys(i.shapes??{}).length>=v.MAX_SUBSCRIPTIONS_PER_SOCKET)return"too_many";Ne(i.subs,t,r);const a=ie(i.broadcastSubs,t),c=ie(i.subTables,t),d=this.liftRefusedMark(e,o!==void 0),l=i.deliveryPermits?.[t];this.deliveryAuthorization&&i.deliveryPermits!==void 0&&Reflect.deleteProperty(i.deliveryPermits,t);try{this.writeAttachment(e,i)}catch{return o===void 0?delete i.subs[t]:Ne(i.subs,t,o),ke(i.broadcastSubs,t,a),ke(i.subTables,t,c),d(),l!==void 0&&i.deliveryPermits!==void 0&&(i.deliveryPermits[t]=l),"serialize_failed"}return Q(this.subscriptionRegistrations,e).set(t,Symbol("subscription registration")),this.socketIndex.resubscribed(e,t),this.unrecordedQueries.get(e)?.delete(t),this.restartFailureStreakUnlessRetry(e,t,o,r),"ok"}unsubscribe(e,t){const r=this.readAttachmentCopy(e),s=r.subs[t],i=r.deliveryPermits?.[t];r.deliveryPermits!==void 0&&Reflect.deleteProperty(r.deliveryPermits,t);const o=ie(r.broadcastSubs,t),a=ie(r.subTables,t);delete r.subs[t];try{this.writeAttachment(e,r)}catch{s!==void 0&&Ne(r.subs,t,s),ke(r.broadcastSubs,t,o),ke(r.subTables,t,a),i!==void 0&&r.deliveryPermits!==void 0&&(r.deliveryPermits[t]=i);return}this.socketIndex.forgetMemo(e,t),this.tableSetsRefused.delete(e),this.unrecordedQueries.get(e)?.delete(t),this.subscriptionFailures.clear(e,t),this.subscriptionRegistrations.get(e)?.delete(t)}shapeSubscribe(e,t,r){const s=this.readAttachmentCopy(e),i=s.shapes??{},o=Object.hasOwn(i,t)?i[t]:void 0;if(o===void 0&&Object.keys(s.subs).length+Object.keys(i).length>=v.MAX_SUBSCRIPTIONS_PER_SOCKET)return"too_many";i[t]=r,s.shapes=i;try{this.writeAttachment(e,s)}catch{return o===void 0?delete s.shapes[t]:s.shapes[t]=o,"serialize_failed"}return this.socketIndex.markHoldsShapes(e),"ok"}shapeUnsubscribe(e,t){const r=this.readAttachmentCopy(e),{shapes:s}=r;if(!s)return;const i=s[t];delete s[t];try{this.writeAttachment(e,r)}catch{i!==void 0&&(s[t]=i);return}if(this.shapeMemos.get(e)?.delete(t),this.globalShapeSnapshots.get(e)?.delete(t),this.tableSetsRefused.delete(e),r.connectionId!==void 0){try{wn(this.sql,r.connectionId,t)}catch{}try{Tn(this.sql,r.connectionId,t)}catch{}}const o=this.relay?.releaseRelayShapes(e,t).catch(a=>{console.error("[@lunora/do] relay shape release failed:",a)});o!==void 0&&this.shardHost.waitUntil?.(o)}matchesSubscription(e,t){if(e.table!==t.table)return!1;const{args:r}=e;if(!r)return!0;const{row:s}=t;if(!s)return!0;for(const[i,o]of Object.entries(r))if(s[i]!==o)return!1;return!0}broadcastDelta(e){if(this.deliveryAuthorization)throw new p("NOT_IMPLEMENTED","broadcastDelta is unsupported with delivery authorization");const t=this.runner.sockets(),r=JSON.stringify(D(e)),s=Date.now();for(const i of t){const o=this.readAttachment(i);if(this.dropIfLapsed(i,o,s))continue;const{subs:a}=o,c=Gr(o);for(const d of Object.keys(a)){const l=a[d];l===void 0||!this.matchesSubscription(l,e)||this.skipsForReexecution(i,d,l,o)||c&&!l.functionPath||this.sendFrame(i,`{"type":"delta","id":${JSON.stringify(d)},"delta":${r}}`)}}}executeSubscription(e,t,r,s){return Promise.resolve(null)}resolveShape(e,t,r){}isShapeRelayUniform(e,t){return this.relay?.isShapeRelayUniform(e,t)??!1}readGlobalShapeRows(e,t){return Promise.resolve([])}pollExternalSources(e){return Promise.resolve(void 0)}scheduleSourcePoll(){return this.scheduleBootstrapPoll()}ttlSweeps(){return[]}async pollTtlSweeps(e){const t=this.ttlSweeps();if(t.length===0)return;const r=this.sql,s=Date.now(),i=new Kt(this.transactionLimits());for(const o of t){let a=0,c=!0;for(;c&&a<wl;){const d=kn(r,o,s,Al);for(const l of d.ids)if(await this.deleteExpiredTtlRow(o,l,s,i,e))return Date.now();c=d.hasMore,a+=1}}return this.nextTtlWake(t,s)}scheduleTtlSweep(){return this.scheduleBootstrapPoll()}scheduleOutbox(){return this.scheduleOutboxRunner.scheduleOutbox()}scheduleOutboxScheduler(){}async pollScheduleOutbox(e){return this.scheduleOutboxRunner.pollScheduleOutbox(e)}currentShardKey(){return this.runner.shardKey??_e}publishLiveEvent(e,t,r){Yr(t);const s=JSON.stringify(this.declaredLivePayload(e,t,r)??null),{byteLength:i}=new TextEncoder().encode(s);if(i>v.MAX_WHISPER_BYTES)throw new p("PAYLOAD_TOO_LARGE",`a publish may be at most ${String(v.MAX_WHISPER_BYTES)} bytes`,{status:413});return this.broadcastLiveTopic(e,t,s)}loadLiveStream(e){}liveStreams(){}declaredLivePayload(e,t,r){const s=this.liveStreams();if(s===void 0)return r;const i=Object.hasOwn(s,e)?s[e]:void 0;if(i===void 0)throw new p("BAD_REQUEST",`"${e}" is not a declared live stream`,{status:400});try{return D(i.validatePublish(t,F(r)))}catch(o){throw V(o)?o:new p("BAD_REQUEST",`publish to "${t}" was refused: ${o instanceof Error?o.message:String(o)}`,{status:400})}}publishLiveFromAction(e,t,r){if(r.shardKey!==void 0&&r.shardKey!==this.currentShardKey())return Promise.reject(new p("BAD_REQUEST",`ctx.live.publish from an action runs on shard "${this.currentShardKey()}"; "${r.shardKey}" is another shard. Publish from a route or an action on that shard`,{status:400}));try{return Promise.resolve(this.publishLiveWhenLoaded(r.stream,e,D(t??null)))}catch(s){return Promise.reject(s instanceof Error?s:new p("INTERNAL",String(s),{status:500}))}}shardRegistry(){}async ensureShardInit(){this.shardInitOnce??=(async()=>{try{await this.runShardInit()}catch(e){this.recordShardInitError("__shard_init__",e)}this.scheduleOutboxRunner.armScheduleOutboxRetry()})(),await this.shardInitOnce}async runShardInit(){await Promise.resolve()}recordShardInitError(e,t,r){this.recordShapeError(`init:${e}`,t,r)}recordExternalSourceError(e,t,r){this.recordShapeError(`source:${e}`,t,r)}recordExternalSourceWarning(e,t,r){this.logs.push({functionPath:`source:${e}`,level:"warn",message:t,timestamp:Date.now(),traceId:r?.traceId})}executeStream(e,t,r){return null}async runCachedQuery(e,t,r,s,i){if(this.deliveryAuthorization)return r(i);if(!this.reactiveCache)return r();if(i)return r(i);const o=_n(),a=In();let c=!1;const d={footprint:a,markIpRead:()=>{c=!0},tracker:o},l=this.reactiveCache.stats().hits,h={claims:this.getCurrentIdentity()??null,ip:(this.ipKeyedFunctionPaths.has(e)?this.getCurrentIp():void 0)??null,system:this.isSystemDispatch(),userId:this.getCurrentUserId()??null},u=At(h),m=u===yl?null:u,S=async()=>{const g=await r(d);c&&this.ipKeyedFunctionPaths.add(e);const R=a.ranges();for(const y of a.tables)R?.has(y)||o.recordRead(y,Ee);return g},E=await this.reactiveCache.run(ve(e,t,m),o.collect(),S,()=>_l(a.ranges()));return s&&Object.assign(s,{cacheHit:this.reactiveCache.stats().hits>l,readTables:Rc(o.collect())}),E}getCtxDbReadHook(e){return(t,r,s)=>{e?.tracker.recordRead(t,r??Ee),e?.footprint.onRead(t,r??Ee,s),r===Ee&&this.currentScannedTables?.add(t)}}getCtxDbReadRangeHook(e){return t=>{e?.footprint.onReadRange(t)}}getCtxDbIndexUseHook(){return(e,t)=>{this.usedIndexes.add(`${e}:${t}`),this.currentIndexHits?.add(JSON.stringify([e,t]))}}ctxDbTuning(){return{...this.ctxDbRelationOptions,companionMemo:this.companionMemo,...this.reactiveCache===void 0?{}:{cache:this.reactiveCache}}}invalidateCompanionMemo(){this.companionMemo.invalidate()}isCacheableQuery(e){return!1}transactionLimits(){return{}}transactionHeadroom(e="transaction"){return this.mintHeadroom(e,{trace:this.currentRequestTrace,userId:this.getCurrentUserId()})}subscriptionHeadroom(e,t){return this.mintHeadroom(e,{trace:void 0,userId:t?.userId},this.rerunNearLimitWarned)}streamHeadroom(e,t){return this.mintHeadroom(e,{trace:void 0,userId:t?.userId})}async*windowStreamReads(e,t){for await(const r of t)yield r,e.beginReadWindow()}alarmHeadroom(){return this.mintHeadroom("alarm",{trace:void 0,userId:void 0})}recordChangedTable(e,t){this.pendingChangedTables??=new Set,this.pendingChangedTables.add(e),this.pendingChangedKeys=Cn(this.pendingChangedKeys,e,t),this.ctxDbCacheWired||this.reactiveCache?.invalidateTable(e)}recordGlobalWrite(e,t,r={}){this.reactiveCache?.invalidateTable(e),this.recordChangedTable(e),this.pendingGlobalWriteTables??=new Set,this.pendingGlobalWriteTables.add(e),t!==void 0&&(this.pendingChangedBookmarks??=new Map,this.pendingChangedBookmarks.set(r,t))}recordLateGlobalWrite(e){this.recordGlobalWrite(e,vt),this.runner.background(this.flushChangedTables().catch(t=>{this.recordShapeError("global:late-write",t)}))}async flushMigrationProgress(){this.recordChangedTable(On),await this.flushChangedTables()}recordUserLog(e,t,r,s,i,o,a,c,d=rr(i===void 0?r:[...r,i]),l){const h=l===void 0?c??this.currentRequestTrace:l.trace,u={args:r,...d===void 0?{}:{error:d},...a===void 0?{}:{eventName:a},fields:i,functionPath:e,level:t,message:s,...h?.rayId===void 0?{}:{rayId:h.rayId},shardKey:this.runner.shardKey,spanId:h?.rootSpanId,traceId:h?.traceId,ts:Date.now(),userId:l===void 0?this.getCurrentUserId():l.userId};this.logs.push({fields:i,functionPath:e,level:t,message:s,timestamp:u.ts,traceId:u.traceId});try{Us(u)}catch{}if(o?.onLog)try{o.onLog(u,{waitUntil:this.shardHost.waitUntil})}catch{}}makeLogger(e,t,r,s=K){s.hold();const i=o=>(...a)=>{const c=a.map(u=>typeof u=="string"?s.name(u):s.value(u)),{fields:d,message:l}=ci(c,r===void 0?void 0:s.value(r)),h=rr(r===void 0?a:[...a,r]);this.recordUserLog(e,o,s.value(c),s.text(l),s.fields(d),t,void 0,void 0,h===void 0?void 0:s.value(h))};return{debug:i("debug"),error:i("error"),event:(o,a)=>{const c=s.name(o);this.recordUserLog(e,"info",[c],c,s.fields(r?{...r,...a}:a),t,c)},fatal:i("fatal"),info:i("info"),log:i("log"),trace:i("trace"),warn:i("warn"),with:o=>this.makeLogger(e,t,r?{...r,...o}:o,s)}}makeTracer(e,t,r,s=K){const i=r??be(void 0);return Fs({anchor:i,captureRaw:q(this.env),fuseHostSpans:t?.fuseCloudflareTraces===!0,functionPath:e,record:o=>{this.recordSpan(o,t,i.sampled)},resolveHostTracing:Br,scope:s,shardKey:this.runner.shardKey,userId:()=>this.getCurrentUserId()})}resolveDispatchAnchor(e){return(e?void 0:this.getCurrentTrace())??be(void 0)}instrumentDb(e,t,r,s,i=K){const o=this.databaseTelemetryDeps("db",t,r,s,i);return o===void 0?e:Hs(e,o)}instrumentSql(e,t,r,s,i=K){const o=this.databaseTelemetryDeps("sql",t,r,s,i);return o===void 0?e:Ws(e,o)}watchActionWork(e,t){const r=Jd(t),s={trace:this.currentRequestTrace,userId:this.getCurrentUserId()},{lastTelemetrySink:i}=this;return()=>{const o=r();o.length>0&&this.recordUserLog(e,"warn",[],`action returned while ${o.join(", ")} was still running; await it, or it may be cancelled once the response is sent`,{pending:o},i,"lunora.action.unawaited_work",void 0,void 0,s)}}makeFetch(e,t,r,s=K){const i=(a,c)=>globalThis.fetch(a,c);if(r===void 0||r.traceFetch===!1)return i;const o=this.getCurrentUserId();return $s({anchor:t,captureRaw:q(this.env),functionPath:e,...typeof r.traceFetch=="object"&&r.traceFetch.propagate!==void 0?{propagate:r.traceFetch.propagate}:{},record:a=>{this.recordSpan(a,r,t.sampled)},scope:s,shardKey:this.runner.shardKey,userId:()=>o},i)}makeDispatchSpan(e,t,r=K){const s=X(e);this.lastTelemetrySink=t??this.lastTelemetrySink,t!==void 0&&(ze(this.dispatchSpans,at),this.dispatchSpans.set(s,this.dispatchSpans.get(s)??{sink:t}));const i=()=>{ze(this.dispatchSpans,at);const o=this.dispatchSpans.get(s)??{sink:t};return o.collector??=di({...e.sampled===void 0?{}:{sampled:e.sampled},spanId:e.rootSpanId,traceId:e.traceId},q(this.env),r),this.dispatchSpans.set(s,o),o.collector};return{addEvent:(o,a)=>{i().handle.addEvent(o,a)},spanContext:()=>({...e.sampled===void 0?{}:{sampled:e.sampled},spanId:e.rootSpanId,traceId:e.traceId}),addLink:o=>{i().handle.addLink(o)},recordEvaluation:o=>{i().handle.recordEvaluation(o)},recordException:o=>{i().handle.recordException(o)},setAttribute:(o,a)=>{i().handle.setAttribute(o,a)},setAttributes:o=>{i().handle.setAttributes(o)}}}makeMetrics(e,t,r=K){return Ks({functionPath:e,record:s=>{this.recordMetric(s,t)},scope:r,shardKey:this.runner.shardKey})}recordMetric(e,t){const r=this.currentRequestTrace?.traceId,s=r===void 0?e:{...e,traceId:r},i=a=>{try{a()}catch{}};i(()=>{this.metricSeries.push(s)});const o=t?.metricHistory;if(o!==void 0&&o!==!1){const a=this.shardHost.sql,c=typeof o=="object"?o:{};i(()=>{li(a,s,r,c)})}t?.onMetric&&i(()=>t.onMetric?.(s,{waitUntil:this.shardHost.waitUntil}))}async handleWebSocketMessage(e,t,r=!1){if(this.deliveryAuthorization&&!this.deliveryRoleSupported()){this.sendSubscriptionError(e,"","NOT_IMPLEMENTED",j);return}const s=this.readAttachment(e);if(this.dropIfLapsed(e,s))return;if((typeof t=="string"?t.length:t.byteLength)>nl){if(s.authenticated===!1){this.refusePendingSocket(e);return}this.sendFrame(e,JSON.stringify({message:"frame too large",type:"error"}),"control");return}const o=typeof t=="string"?t:new TextDecoder().decode(t);if(s.socketPath!==void 0){r||await this.handleSocketRouteFrame(e,s,o);return}let a;try{a=JSON.parse(o)}catch{if(s.authenticated===!1){this.refusePendingSocket(e);return}this.sendFrame(e,JSON.stringify({message:"invalid envelope",type:"error"}),"control");return}if(s.authenticated===!1&&a.type!=="connect"){this.refusePendingSocket(e);return}if(a.type==="live"){this.sendFrame(e,JSON.stringify({message:"live frames are server-only",type:"error"}),"control");return}if((a.type==="connect"&&s.authenticated!==!1||a.type==="whisper"||a.type==="whisper_subscribe"||a.type==="whisper_unsubscribe")&&this.rejectRetainedRooms(e),this.deliveryAuthorization&&!(a.type==="connect"||a.type==="unsubscribe"||a.type==="shape_unsubscribe"||a.type==="whisper_unsubscribe"||a.type==="subscribe"&&typeof a.query?.functionPath=="string")){this.sendSubscriptionError(e,a.id??"","NOT_IMPLEMENTED",j);return}if(a.type==="connect"){await this.handleConnectFrame(e,a);return}if(a.type==="subscribe"&&a.query){await this.handleSubscribeFrame(e,a,a.query);return}if(a.type==="shape_subscribe"&&a.shape){await this.handleShapeSubscribeFrame(e,a,a.shape);return}if(a.type==="shape_unsubscribe"){this.handleShapeUnsubscribeFrame(e,a);return}if(a.type==="stream"&&a.query?.functionPath){this.handleStreamFrame(e,a,a.query,a.query.functionPath);return}if(a.type==="whisper_subscribe"||a.type==="whisper_unsubscribe"){await this.handleWhisperMembershipFrame(e,a);return}if(a.type==="whisper"){await this.handleWhisperFrame(e,a);return}a.type==="unsubscribe"&&this.handleUnsubscribeFrame(e,a)}async handleFetchCloudflare(e){const t=new URL(e.url),r=e.headers.get("x-lunora-shard-binding");this.shardBinding=r===null||r===""?this.shardBinding:r;const s=await this.routeNonRpc(t,e);if(s!==void 0)return s;if(t.pathname!=="/rpc"||e.method!=="POST")return new Response("Not found",{status:404});let i;try{i=await e.json()}catch{return b({error:{code:"BAD_REQUEST",message:"invalid JSON body"}},400)}if(this.replica!==void 0){const y=await Mn(this.replica,e,i.functionPath);if(y!==void 0)return y}const o=this.preDispatchAnswer(e,i);if(o!==void 0)return await o;const{dispatchAttribution:a,dispatchBookmark:c,dispatchCollectors:d,dispatchHeadroom:l,dispatchStartedAt:h,dispatchTrace:u}=this.beginDispatch(e,i.functionPath);this.recordSchedulerLag(e,i.functionPath,h);let m,S=!1,E,g=this.captureRequestScope(),R;try{const y=F(i.args??{});if(R=this.openSensitiveScope(i.functionPath,y),i.functionPath.startsWith(Nn)){const $=await this.runRelationFanoutRead(i.functionPath,y);return b(D($),200,Y(c.value))}const w=this.isCustomMutator(i.functionPath)?this.classifyClientMutation():void 0;this.currentMutatorClass=w;const T=this.rejectNonNextMutation(i.functionPath,w,h,d);if(T!==void 0)return T;const k=this.captureRequestScope();g=k;const L=this.prepareFunction(i.functionPath,"rpc");if(L!==void 0)try{await L}finally{this.restoreRequestScope(k)}const W=async()=>this.reactiveCache!==void 0&&this.isCacheableQuery(i.functionPath)?this.runCachedQuery(i.functionPath,y,$=>this.handleRpc(i.functionPath,y,l,$,c,R),a):this.handleRpc(i.functionPath,y,l,void 0,c,R),I=k.mutationId,x=async $=>{const de=this.readIdempotentResult($);return de===void 0?{kind:"ran",result:await W()}:{cached:de,kind:"cached"}};let C;if(I===void 0)C={kind:"ran",result:await W()};else if(this.isMutationFunction(i.functionPath))C=await this.shardHost.runSerialized(async()=>(this.restoreRequestScope(k),await x(I)));else{const $=this.readIdempotentResult(I);if($===void 0){const de=this.inFlightClaims.claim(this.idempotencyNamespace(),I);if(de==="declined"){const Ot=this.errorToResponse(new p(Jo,`A dispatch of "${i.functionPath}" carrying this idempotency id is already running on this shard`));return Ot.headers.set(Xo,"1"),Ot}E=de,C={kind:"ran",result:await W()}}else C={cached:$,kind:"cached"}}if(this.restoreRequestScope(k),this.currentResponseBookmark=c.value,C.kind==="cached")return this.respondFromIdempotencyCache(i.functionPath,h,w,C.cached.value,d);const{result:ee}=C;this.recordPostDispatchBookkeeping(ee,w),w?.kind==="next"&&this.advanceClientMutationWatermark();const Ct=Date.now()-h;this.functionMetrics.recordFunctionCall(i.functionPath,Ct,void 0,d.scannedTables,d.indexHits),this.functionMetrics.foldStmtSamples(d.stmtSamples),this.functionMetrics.maybeFlushMetrics();const vs=[...this.pendingChangedTables??[]];this.recordRequestLog(i.functionPath,i.args??{},Ct,"ok",vs,u,a),this.maybeWarnRootSize();const Es=this.buildDispatchResponse(w,this.isMutationFunction(i.functionPath)?st(ee):Zd(ee));return await this.flushChangedTables(),Es}catch(y){this.restoreRequestScope(g),this.metrics.errors+=1,m={thrown:y};const w=Date.now()-h,T=y instanceof Error?y.message:String(y),k=R?.text(T)??T,L=y instanceof xn&&y.kind==="occ";if(y?.code!=="FUNCTION_NOT_FOUND"){const x=Lt(k,q(this.env));this.functionMetrics.recordFunctionCall(i.functionPath,w,x,d.scannedTables,d.indexHits,L)}this.functionMetrics.foldStmtSamples(d.stmtSamples),this.functionMetrics.maybeFlushMetrics(),this.recordRequestLog(i.functionPath,i.args??{},w,"error",[...this.pendingChangedTables??[]],u,a,k),this.logs.push({functionPath:i.functionPath,level:"error",message:k,timestamp:Date.now(),traceId:u.traceId}),this.recordChangedTable(Pt),await this.flushChangedTables();const I=this.errorToResponse(y);if(S=I.status>=500,e.headers.get(ns)==="1"){const x=ea(y);I.headers.set(er,ra({...ht(y),...x===void 0?{}:{internal:x}}))}return I}finally{const y=this.dispatchSpans.get(X(u)),w=this.spans.hasTrace(u.traceId)||Vr(y)?this.recordDispatchRootSpan(i.functionPath,h,m,u,R):void 0;if(this.mirrorHostRootSpan(y?.sink,w,m,S,R),this.dispatchSpans.delete(X(u)),y?.sink?.flush)try{y.sink.flush({waitUntil:this.shardHost.waitUntil})}catch{}this.flushSampledOutTrace(u,m!==void 0),this.traceSampling.delete(u.traceId),E!==void 0&&this.inFlightClaims.release(E),R?.clear(),this.endDispatch(d)}}async handleAlarmCloudflare(){if(this.replica!==void 0)return;const e=this.currentTriggerTrace,t=Date.now();this.globalPollArmedAt=void 0;let r;try{r=await this.pollGlobalShapes(e)}catch(d){this.recordShapeError("shape:poll",d,e),r=1}const s=async(d,l)=>{try{return await l()}catch(h){return this.recordShapeError(d,h,e),Date.now()+v.GLOBAL_SHAPE_POLL_INTERVAL_MS}},i=await s("source:poll",async()=>this.pollExternalSources(e)),o=await s("ttl:sweep",async()=>this.pollTtlSweeps(e)),a=await s("scheduler:outbox",async()=>this.pollScheduleOutbox(e));await this.flushChangedTables();const c=v.nextPollAlarmTarget(r,i,o,a,Date.now());c!==void 0&&await(this.admitAlarmRearm(c,t,a!==void 0)?this.scheduleGlobalPoll(c):this.armRecoveryWake())}captureRequestScope(){return{baselineSeq:this.currentRequestBaselineSeq,bookmark:this.currentRequestBookmark,clientId:this.currentRequestClientId,clientSeq:this.currentRequestClientSeq,deliveryPermit:this.currentDeliveryPermit,identity:this.currentRequestIdentity,ip:this.currentRequestIp,mutationId:this.currentRequestMutationId,mutatorClass:this.currentMutatorClass,origin:this.currentRequestOrigin,sampleErrors:this.currentRequestSampleErrors,system:this.currentRequestSystem,trace:this.currentRequestTrace,traceparent:this.currentRequestTraceparent,userId:this.currentRequestUserId}}restoreRequestScope(e){this.currentRequestBaselineSeq=e.baselineSeq,this.currentRequestBookmark=e.bookmark,this.currentResponseBookmark=void 0,this.currentRequestClientId=e.clientId,this.currentRequestClientSeq=e.clientSeq,this.currentDeliveryPermit=e.deliveryPermit,this.currentRequestIdentity=e.identity,this.currentRequestIp=e.ip,this.currentRequestOrigin=e.origin,this.currentRequestMutationId=e.mutationId,this.currentMutatorClass=e.mutatorClass,this.currentRequestSampleErrors=e.sampleErrors,this.currentRequestSystem=e.system,this.currentRequestTrace=e.trace,this.currentRequestTraceparent=e.traceparent,this.currentRequestUserId=e.userId}async handleConnectFrame(e,t){let r=this.readAttachmentCopy(e);if(r.authenticated===!1){if(r.pendingSince!==void 0&&r.pendingSince+Dr<=Date.now()){this.dropLiveSocket(r.connectionId);try{e.close?.(4003,"connect deadline")}catch{}return}const i=(this.env??{}).LUNORA_WS_BEARER;if(i===void 0||typeof t.token!="string"||!le(t.token,i)){this.refusePendingSocket(e);return}this.rejectRetainedRooms(e),r.authenticated=!0,delete r.pendingSince;try{e.serializeAttachment?.(r)}catch{this.refusePendingSocket(e);return}}if(await this.relay?.announce(),this.closingSockets.has(e)||(r=this.readAttachmentCopy(e),this.sendFrame(e,JSON.stringify({claims:Ve(r.userId,r.identity),connectionId:r.connectionId,...r.revalidateAt===void 0?{}:{revalidateMs:mt},subject:r.userId??null,type:"identity",whisperAck:!0}),"control"),r.connected===!0))return;t.context!==void 0&&(r.context=t.context),t.clientId!==void 0&&(r.clientId=t.clientId),Array.isArray(t.caps)&&(r.pageDeltas=t.caps.includes(Sa),r.refreshBatch=t.caps.includes(ba)),r.connected=!0;let s=!0;try{this.writeAttachment(e,r)}catch{const i={...r};delete i.context;try{this.writeAttachment(e,i)}catch{r.connected=!1,s=!1}}s&&await this.dispatchLifecycle("connect",this.lifecycleInfo(r))}async handleSubscribeFrame(e,t,r){const{functionPath:s}=r,i=s?.startsWith(M)===!0;if(!s&&Gr(this.readAttachment(e))){this.sendSubscriptionError(e,t.id,"SUBSCRIPTION_FUNCTION_REQUIRED","a subscription on an authenticated socket must name a function (functionPath)");return}if(i&&!await this.attachmentAdminAuthorized(this.readAttachment(e))){this.sendFrame(e,JSON.stringify({id:t.id,message:"admin subscription requires admin authorization",type:"error"}),"control");return}let o;try{o=r.args===void 0?r:{...r,args:F(r.args)}}catch{this.sendFrame(e,JSON.stringify({code:"BAD_SUBSCRIPTION_ARGS",error:{code:"BAD_SUBSCRIPTION_ARGS",message:"subscription args failed wire decoding"},id:t.id,type:"error"}),"control");return}{const{sinceClaims:h,...u}=o;o=u,u.sinceSeq!==void 0&&!this.resumesUnderCurrentClaims(e,h,u.functionPath)&&(o={...u,sinceEpoch:void 0,sinceSeq:void 0})}const a=s===void 0||i?void 0:this.prepareForLiveQueryGate(s);if(a===void 0)this.loadingSubscribes.get(e)?.delete(t.id);else if(!await this.subscribeOutlivedLoad(e,t.id,a))return;const c=this.readAttachment(e).subs,d=Object.hasOwn(c,t.id)&&Nr(c[t.id],o),l=this.subscribe(e,t.id,o);if(l!=="ok"){const{code:h,message:u}={paid:{code:"BAD_REQUEST",message:nt(String(s),"subscribed")},per_dispatch:{code:"BAD_REQUEST",message:Wr(String(s))},serialize_failed:{code:"SUBSCRIPTION_PERSIST_FAILED",message:ot("size",v.MAX_SUBSCRIPTIONS_PER_SOCKET,v.MAX_ATTACHMENT_BYTES)},too_many:{code:"TOO_MANY_SUBSCRIPTIONS",message:ot("count",v.MAX_SUBSCRIPTIONS_PER_SOCKET,v.MAX_ATTACHMENT_BYTES)}}[l];this.sendFrame(e,JSON.stringify({code:h,error:{code:h,message:u},id:t.id,type:"error"}),"control");return}this.sendFrame(e,JSON.stringify({id:t.id,type:"ack"}),"control"),s&&await this.seedSubscriptionGuarded(e,t.id,o,s,i,d)}async handleShapeSubscribeFrame(e,t,r){let s;try{s=r.args===void 0?void 0:F(r.args)}catch{this.sendSubscriptionError(e,t.id,"BAD_SUBSCRIPTION_ARGS","shape args failed wire decoding");return}await this.handleShapeSubscribe(e,t.id,{args:s,name:r.name,...t.sinceCheckpoint===void 0||this.resumesUnderCurrentClaims(e,t.sinceClaims,r.name)?{sinceEpoch:t.sinceEpoch,sinceSeq:t.sinceCheckpoint}:{}})}handleShapeUnsubscribeFrame(e,t){this.shapeUnsubscribe(e,t.id),this.sendFrame(e,JSON.stringify({id:t.id,type:"ack"}),"control")}handleStreamFrame(e,t,r,s){if(s.startsWith(M)){this.sendFrame(e,JSON.stringify({id:t.id,message:"streams must be public",type:"error"}),"control");return}if(this.isPaidFunction(s)){this.sendSubscriptionError(e,t.id,"BAD_REQUEST",nt(s,"streamed"));return}let i;try{i=F(r.args??{})}catch{this.sendFrame(e,JSON.stringify({error:{code:"BAD_SUBSCRIPTION_ARGS",message:"stream args failed wire decoding"},id:t.id,type:"error"}),"control");return}this.handleStream(e,t.id,s,i,Number.isInteger(t.sinceChunk)&&t.sinceChunk>0?t.sinceChunk:0,Number.isInteger(t.generation)&&t.generation>0?t.generation:void 0).catch(()=>{})}async handleWhisperMembershipFrame(e,t){const{topic:r}=t;if(!(typeof r=="string"&&r.startsWith(z))&&typeof r=="string"&&r.length>0){const s=t.type==="whisper_subscribe";if(s&&!await this.authorizeWhisper(e,r,"subscribe")){this.acknowledgeLiveJoin(e,r);return}if(this.closingSockets.has(e)||s&&this.roomHandlerPath(r)!==void 0&&!this.allowRoomJoin(e))return;if(!this.setWhisperMembership(e,r,s)){s&&this.acknowledgeLiveJoin(e,r);return}const i=s?this.membershipEpoch(e,r):void 0;s&&this.acknowledgeLiveJoin(e,r);const o=await this.dispatchSettlingJoin(e,r,s,i);if(s&&!o)return;s&&await this.relay?.announce()}}async handleWhisperFrame(e,t){if(!(typeof t.topic=="string"&&t.topic.startsWith(z))&&typeof t.topic=="string"&&t.topic.length>0&&await this.authorizeWhisper(e,t.topic,"send")){if(this.dropIfLapsed(e))return;this.roomHandlerPath(t.topic)===void 0?await this.broadcastWhisper(e,t.topic,t.data):!this.closingSockets.has(e)&&this.isWhisperMember(e,t.topic)&&this.allowWhisper(e)&&this.fitsWhisperCap(t.data)&&await this.dispatchRoomEvent(e,t.topic,"message",t.data,this.membershipEpoch(e,t.topic))}}handleUnsubscribeFrame(e,t){const r=this.streamCancellers.get(e),s=r?.get(t.id);s&&(s.abort(),r?.delete(t.id)),this.loadingSubscribes.get(e)?.delete(t.id),this.unsubscribe(e,t.id),this.sendFrame(e,JSON.stringify({id:t.id,type:"ack"}),"control")}prepareForLiveQueryGate(e){if(!e.startsWith(M))try{return this.prepareFunction(e,"subscription")?.catch(()=>{})}catch{return}}async subscribeOutlivedLoad(e,t,r){const s=Symbol(t),i=this.loadingSubscribes.get(e)??new Map;i.set(t,s),this.loadingSubscribes.set(e,i),await r;const o=i.get(t)===s;return o&&i.delete(t),o&&!this.closingSockets.has(e)}subscriptionRegistration(e,t){const r=Q(this.subscriptionRegistrations,e),s=r.get(t)??Symbol("subscription registration");return r.set(t,s),s}holdsRegistration(e,t,r){return this.subscriptionRegistrations.get(e)?.get(t)===r}dropIfNotLive(e,t,r,s,i){if(r.startsWith(M)&&!s)return this.unsubscribe(e,t),this.sendSubscriptionError(e,t,"FORBIDDEN","admin authorization for this socket is no longer valid"),Promise.resolve(!0);const o=()=>{if(!this.holdsRegistration(e,t,i))return!0;const c=this.liveQueryRefusal(r);return c===void 0?!1:(this.unsubscribe(e,t),this.sendSubscriptionError(e,t,"BAD_REQUEST",c.message),!0)},a=this.prepareForLiveQueryGate(r);return a!==void 0?a.then(o):o()?Promise.resolve(!0):void 0}liveQueryRefusal(e){if(this.isPaidFunction(e))return{message:nt(e,"subscribed"),status:"paid"};if(this.isPerDispatchFunction(e))return{message:Wr(e),status:"per_dispatch"}}servedByReexecution(e,t,r,s){return r?r.startsWith(M)||r.startsWith(Re)?!0:this.executeSubscription===v.prototype.executeSubscription?!1:s.broadcastSubs?.[t]!==r||this.socketIndex.memo(e,t)!==void 0:!1}skipsForReexecution(e,t,r,s){return this.servedByReexecution(e,t,r.functionPath,s)?(this.broadcastSkipWarned||(this.broadcastSkipWarned=!0,console.warn("[@lunora/do] broadcastDelta skipped a subscription this shard serves by re-execution; re-execution delivers its updates. Broadcast reaches only subscriptions the shard does not re-run.")),!0):!1}markBroadcastSubscription(e,t,r){if(this.executeSubscription===v.prototype.executeSubscription)return;const s=this.readAttachment(e);if(s.subs[t]?.functionPath!==r||s.broadcastSubs?.[t]===r)return;const i=this.readAttachmentCopy(e);i.broadcastSubs={...i.broadcastSubs,[t]:r};try{this.writeAttachment(e,i)}catch{}}unmarkBroadcastSubscription(e,t){if(this.readAttachment(e).broadcastSubs?.[t]===void 0)return;const r=this.readAttachmentCopy(e);ie(r.broadcastSubs,t);try{this.writeAttachment(e,r)}catch{}}deliveryRoleSupported(){const e=this.runner.shardKey;return e===void 0||pt(e)===void 0&&ft(e)===void 0}revokeSubscription(e,t){Object.hasOwn(this.readAttachment(e).subs,t)&&(this.unsubscribe(e,t),this.socketIndex.forgetMemo(e,t),this.subscriptionRegistrations.get(e)?.delete(t),this.sendSubscriptionError(e,t,"FORBIDDEN","AccessDenied"))}sendFrame(e,t,r){if(this.deliveryAuthorization&&r!=="control"){if(r===void 0)return!1;const{permit:s,subId:i}=r;if(s===void 0||this.subscriptionRegistrations.get(e)?.get(i)!==s.registration)return!1;if(!this.deliveryRoleSupported()||!this.deliveryFence.allows(s))return this.revokeSubscription(e,i),!1}return this.refreshBatches.get(e)===!1&&(this.refreshBatches.set(e,!0),N(e,ga)),N(e,t)}async inRefreshBatch(e,t){const r=this.readAttachment(e);if(r.refreshBatch!==!0||Object.keys(r.subs).length<2){await t();return}this.refreshBatches.set(e,!1);try{await t()}finally{this.refreshBatches.get(e)===!0&&N(e,va),this.refreshBatches.delete(e)}}async authorizeSubscription(e,t,r,s,i){if(!this.deliveryAuthorization)return;const o=this.readAttachment(e).subs[t];if(o?.functionPath!==s||Se(o.args??{})!==Se(i))return;const a=Q(this.subscriptionRegistrations,e),c=this.subscriptionRegistration(e,t);let d;try{d=await this.authorizeDelivery(r,s,i,"subscription",{admin:!1,system:!1})}catch(u){if(a.get(t)!==c||this.endSubscriptionOnAuthorityFailure(e,t,s,u))return;throw u}if(a.get(t)!==c||d===void 0)return;if(!this.deliveryRoleSupported()||!this.deliveryFence.allows(d))throw et();const l=this.readAttachment(e);if(!Object.hasOwn(l.subs,t))return;const h=l.deliveryPermits?.[t];if(h?.scope!==d.scope||h.epoch!==d.epoch){const u={...l,deliveryPermits:{...l.deliveryPermits,[t]:d}};try{this.writeAttachment(e,u);const m=this.socketIndex.memo(e,t);m!==void 0&&(m.lastJson=ne)}catch{throw new p("SUBSCRIPTION_PERSIST_FAILED",`subscription attachment exceeds the ${String(v.MAX_ATTACHMENT_BYTES)}-byte limit`)}}return{...d,registration:c}}endSubscriptionOnAuthorityFailure(e,t,r,s){if(Te(s))return this.revokeSubscription(e,t),!0;if(!V(s)||!["FORBIDDEN","INTERNAL"].includes(s.code))return!1;this.unsubscribe(e,t);const{body:i}=P(s,{redactedMessage:"internal error"});return this.sendSubscriptionError(e,t,i.code,i.message,i),this.recordSubscriptionRefreshError(r,s,{subId:t}),!0}async authorizeDelivery(e,t,r,s,i){if(!this.deliveryAuthorization)return;const o=await this.deliveryAuthorization({identity:e,functionPath:t,args:r,shardKey:this.runner.shardKey,transport:s,...i});if(o===void 0)throw et();if(!Yt(o))throw new p("INTERNAL","delivery authority returned an invalid permit");if(!this.deliveryFence.allows(o))throw et();return{scope:o.scope,epoch:o.epoch}}async installDeliveryFence(e){const t=await e.text();if(!this.deliveryAuthorization||e.method!=="POST"||!ss(this.env)||!await Dn(this.env,e.headers.get(Ln),t))return new Response("Forbidden",{status:403});let r;try{r=JSON.parse(t)}catch{return new Response("Bad request",{status:400})}const s=r;if(s?.type!=="delivery-fence"||s.shardKey!==this.runner.shardKey||!Yt(s.fence))return new Response("Bad request",{status:400});this.deliveryFence.install(s.fence);for(const i of this.runner.sockets()){const o=this.readAttachment(i);for(const a of Object.keys(o.subs)){const c=o.deliveryPermits?.[a];c!==void 0&&!this.deliveryFence.allows(c)&&this.revokeSubscription(i,a)}}return new Response(void 0,{status:204})}async fetchAuthorizedRpc(e){let t;try{t=await e.clone().json()}catch{return b({error:{code:"BAD_REQUEST",message:"invalid JSON body"}},400)}if(!ce(t)||typeof t.functionPath!="string")return b({error:{code:"BAD_REQUEST",message:"invalid RPC request"}},400);const{functionPath:r}=t,s={identity:we(e.headers.get("x-lunora-identity")),userId:te(e.headers.get("x-lunora-userid")),ip:e.headers.get("x-lunora-client-ip")??void 0};let i;try{i=F(t.args===void 0?{}:t.args)}catch{return b({error:{code:"BAD_REQUEST",message:"invalid wire arguments"}},400)}if(!ce(i))return b({error:{code:"BAD_REQUEST",message:"invalid wire arguments"}},400);const o=i;let a;try{a=await this.authorizeDelivery(s,r,o,"rpc",{admin:r.startsWith(M)&&await this.adminCaller(e)!==void 0,system:e.headers.get("x-lunora-system")==="1"})}catch(h){return V(h)?this.errorToResponse(h):b({error:{code:"SHARD_UNAVAILABLE",message:"delivery authority unavailable"}},503)}a!==void 0&&this.deliveryRequestPermits.set(e,a);const c=await this.runner.handleFetch(e),d=await c.arrayBuffer();if(!this.deliveryFence.allows(a))return b({error:Fr},409);const l=new Response(d,c);return a!==void 0&&this.deliveryResponsePermits.set(l,a),l}databaseTelemetryDeps(e,t,r,s,i){const o=s===void 0?"off":s.instrumentDatabase??"summary";if(o==="off")return;const a=this.getCurrentUserId();return{anchor:r,captureRaw:q(this.env),functionPath:t,mode:o,record:c=>{this.recordSpan(c,s,r.sampled)},scope:i,shardKey:this.runner.shardKey,tally:this.dispatchTally(r,e),userId:()=>a}}dispatchTally(e,t){ze(this.dispatchSpans,at);const r=X(e),s=this.dispatchSpans.get(r)??{},i=s.tallies??{},o=i[t]??Gs();return i[t]=o,s.tallies=i,this.dispatchSpans.set(r,s),o}async withTriggerTrace(e,t){const r=be(void 0),s=Date.now(),i=this.currentRequestTrace===void 0;i&&(this.currentRequestTrace=r);const o=this.currentTriggerTrace;this.currentTriggerTrace=r;let a;try{return await t()}catch(c){throw a={thrown:c},c}finally{this.currentTriggerTrace=o,i&&this.currentRequestTrace===r&&(this.currentRequestTrace=void 0);const c=this.dispatchSpans.get(X(r)),d=this.spans.hasTrace(r.traceId)||Vr(c)?this.recordDispatchRootSpan(e,s,a,r):void 0;this.mirrorHostRootSpan(c?.sink??this.lastTelemetrySink,d,a,!0),this.dispatchSpans.delete(X(r)),this.flushTelemetry()}}flushTelemetry(){try{this.lastTelemetrySink?.flush?.({waitUntil:this.shardHost.waitUntil})}catch{}}recordDispatchRootSpan(e,t,r,s,i){const o=this.dispatchSpans.get(X(s)),a=Date.now()-t,c={};for(const[S,E]of gs(o))Object.assign(c,Qs(E,S));const d=this.currentStmtSamplesTruncated?{"db.stmt_samples_truncated":!0}:void 0,l={...c,...d,...o?.collector?.collected.attributes},h=Object.keys(l).length===0?void 0:{attributes:l,events:[],links:[]},u=o?.collector===void 0?h:{...o.collector.collected,attributes:l};let m;try{m=js({anchor:s,captureRaw:q(this.env),...u===void 0?{}:{collected:u},durationMs:a,failure:r,functionPath:e,scope:i,shardKey:this.runner.shardKey,startTs:t,userId:this.getCurrentUserId()}),this.spans.push(m)}catch{}return o?.collector!==void 0&&this.exportWideEvent(e,a,r,s,{collected:u??o.collector.collected,sink:o.sink}),m}mirrorHostRootSpan(e,t,r,s,i=K){if(e?.fuseCloudflareTraces===!0)try{zs(Oe,{...t?.attributes===void 0?{}:{attributes:t.attributes},...r===void 0?{}:{error:{message:Lt(i.text(r.thrown instanceof Error?r.thrown.message:String(r.thrown)),q(this.env)),serverFault:s}}})}catch{}}exportWideEvent(e,t,r,s,i){try{const{attributes:o}=i.collected;this.recordUserLog(e,r===void 0?"info":"error",[ct],ct,{...o,[Je.durationMs]:t,[Je.functionPath]:e,[Je.ok]:r===void 0},i.sink,ct,s)}catch{}}recordSpan(e,t,r){try{this.spans.push(e)}catch{}if(!t?.onSpan)return;const s=this.traceSampling.get(e.traceId);if(s!==void 0){if(!s.sampled){if(s.sink=t,e.dispatch!==!0){const i=s.held??(s.held=[]);i.push(e),i.length>kl&&i.shift()}return}this.emitSpan(e,t,!0);return}r!==!1&&this.emitSpan(e,t,!0)}emitSpan(e,t,r){if(t.onSpan)try{t.onSpan({...e,sampled:r},{waitUntil:this.shardHost.waitUntil})}catch{}}flushSampledOutTrace(e,t){const r=this.traceSampling.get(e.traceId);if(!r||r.sampled||!r.keepErrors)return;const{held:s,sink:i}=r;if(!(!i?.onSpan||s===void 0||s.length===0||!(t||s.some(a=>!a.ok))))for(const a of s)this.emitSpan(a,i,!1)}lifecycleInfo(e){return{event:{connectionId:e.connectionId??"",shardKey:this.runner.shardKey??_e,userId:e.userId??null,...e.context===void 0?{}:{context:structuredClone(e.context)}},...O(e)}}async withSystemDispatch(e){const t=this.currentRequestSystem;this.currentRequestSystem=!0;try{return await e()}finally{this.currentRequestSystem=t}}collectMetrics(){this.functionMetrics.flushUnwrittenMetrics();const e=this.shardHost.sql.databaseSize;let{requests:t}=this.metrics,{errors:r}=this.metrics;try{const a=Vs(this.shardHost.sql);t=a.requests,r=a.errors}catch{}let s=[];try{s=Js(this.shardHost.sql)}catch{}let i=[];try{i=Xs(this.shardHost.sql)}catch{}const o=this.functionMetrics.collectFunctionMetricBuckets();return{cache:this.reactiveCache?this.reactiveCache.stats():null,databaseSize:typeof e=="number"?e:null,errors:r,functions:this.functionMetrics.collectFunctionStats(this.metrics.sinceMs).functions,history:o.buckets,historyTruncated:o.truncated,indexHits:s,queryStats:i,requests:t,shard:this.runner.shardKey??_e,sinceMs:this.metrics.sinceMs,subscriptionRefreshErrors:this.metrics.subscriptionRefreshErrors,uptimeMs:Date.now()-this.metrics.sinceMs}}purgeDurableSocketBaselines(e){if(e!==void 0){try{Pn(this.sql,e)}catch{}try{Bn(this.sql,e)}catch{}}}maybeWarnRootSize(){if(v.rootSizeWarned||this.runner.shardKey!==_e)return;const t=this.shardHost.sql.databaseSize;typeof t!="number"||t<ml||(v.rootSizeWarned=!0,console.warn(`[@lunora/do] __root__ Durable Object SQLite size is ${String(t)} bytes (>= 1 GiB, 10% of the 10 GiB per-DO ceiling). Plan a \`.shardBy()\` migration before you hit the wall. See https://lunora.sh/docs/concepts/sharding for guidance.`))}errorToResponse(e){const{body:t,redacted:r,status:s}=P(e,{encodeData:D,fallbackCode:"RPC_FAILED",redactedMessage:"internal error"});return r&&console.error("[@lunora/do] internal error:",e),b({error:t},s)}async handleBatchRpc(e){let t;try{t=await e.json()}catch{return b({error:{code:"BAD_REQUEST",message:"invalid JSON body"}},400)}if(!Array.isArray(t.calls))return b({error:{code:"BAD_REQUEST",message:"batch `calls` must be an array"}},400);if(t.calls.length>Zt)return b({error:{code:"BAD_REQUEST",message:`batch exceeds the ${String(Zt)}-call limit`}},400);const r=[],s=[];let i;for(const a of t.calls){const c=await this.dispatchBatchEntry(e,a);s.push({bookmark:c.bookmark,permit:c.permit}),r.push({body:c.body,...c.errorDetail===void 0?{}:{errorDetail:c.errorDetail},id:c.id,status:c.status})}const o=r.map((a,c)=>{const d=s[c];return this.deliveryAuthorization&&d?.permit!==void 0&&!this.deliveryFence.allows(d.permit)?{id:a.id,status:409,body:{error:Fr}}:(d?.bookmark!==void 0&&(i=d.bookmark),a)});return b({results:o},200,Y(i))}async dispatchBatchEntry(e,t){try{const r=await this.fetch(zc(e,t));return{body:await r.json(),permit:this.deliveryResponsePermits.get(r),bookmark:r.headers.get("x-d1-bookmark")??void 0,errorDetail:r.headers.get(er)??void 0,id:t.id,status:r.status}}catch(r){const{body:s,status:i}=P(r,{fallbackCode:"BATCH_ENTRY_FAILED"});return{body:{error:s},bookmark:void 0,id:t?.id,status:i}}}async handleBulkRowOp(e,t){let r=0,s;const i=this.transactionHeadroom();try{const o=e===f.clearTable;if(o||e===f.deleteRows){const d=o?Za(t):Xa(t),l=await this.runShardBulkRowOp(d,async h=>(await this.runShardWrite({hard:!0,id:h,op:"delete",table:d.table},i),r+=1,!0));return this.recordAudit(t,o?"clearTable":"deleteRows",{table:d.table,detail:{deleted:l.count,hasMore:l.hasMore}}),A(l)}const a=Ya(t),c=await this.runShardBulkRowOp(a,async d=>{if(this.shardRowExists(a.table,d)===!1)return!1;try{return await this.runShardWrite({doc:a.doc,id:d,op:"patch",table:a.table},i),r+=1,!0}catch(l){throw s=d,l}},a.after);return this.recordAudit(t,"patchRows",{table:a.table,detail:{fields:Object.keys(a.doc),hasMore:c.hasMore,patched:c.count}}),A(c)}catch(o){throw(r>0||s!==void 0)&&this.recordAudit(t,"bulkRowOpFailed",{table:typeof t.table=="string"?t.table:void 0,detail:{applied:r,...s===void 0?{}:{failedRow:s}}}),o}finally{await this.flushChangedTables().catch(o=>{this.recordShapeError("bulkRowOp:flush",o)})}}importAdminRpc(e,t){return e===f.importShard?this.importAdminShard(t):Ol.has(e)?this.importSessionAdmin(e,t):void 0}async importSessionAdmin(e,t){const r=await pd({recordAudit:(s,i)=>{this.recordAudit(t,s,i)},runInTransaction:async s=>this.runInTransaction(s),runShardImport:async s=>this.runShardImport(s),sql:this.shardHost.sql},e,t);return await this.flushChangedTables(),A(r)}async importAdminShard(e){const t=qn(e),r=await this.runShardImport({deletes:t.deletes,dryRun:t.dryRun,onConflict:t.onConflict,rows:t.rows,startLine:t.startLine});return t.dryRun?A({...r,dryRun:!0}):(await this.flushChangedTables(),this.recordAudit(e,"importShard",{detail:{conflicts:r.conflicts,deleted:r.deleted,errors:r.errors.length,inserted:r.inserted,mode:"append",replaced:r.replaced}}),A(r))}async authorizeAdminCall(e,t){const r=await this.adminCaller(e);return r===void 0?b({error:{code:"ADMIN_FORBIDDEN",message:"admin introspection is disabled or the bearer token is invalid"}},403):r.tokenName!==void 0&&Xd.has(t)?b({error:{code:"ADMIN_ROOT_REQUIRED",message:`${t} requires the root admin token`}},403):r}async handleAdminRpc(e,t,r){const s=await this.authorizeAdminCall(e,t);if(s instanceof Response)return s;try{const i=el(r);s.tokenName!==void 0&&this.adminCallTokens.set(i,s.tokenName);const o=this.readAdminOp(t,i);if(o)return A(o.result);if(t===f.runMigration){const d=qa(i),l=await this.runShardDataMigration(d);return await this.flushChangedTables(),this.recordAudit(i,"runMigration",{id:d.id,detail:{changed:l.changed,direction:l.direction,dryRun:l.dryRun,processed:l.processed}}),A(l)}if(t===f.exportShard){const d=Un(i),l=await this.runShardExport({batchSize:d.batchSize,tables:d.tables});return A({rows:l})}const a=this.importAdminRpc(t,i);if(a!==void 0)return await a;if(t===f.writeRow){const d=Ua(i),l=await this.runShardWrite(d);return await this.flushChangedTables(),this.recordAudit(i,"writeRow",{table:d.table,id:l.id??d.id,detail:{op:l.op}}),A(l)}if(t===f.deleteRows||t===f.clearTable||t===f.patchRows)return await this.handleBulkRowOp(t,i);if(t===f.rankBefore){const d=await this.runShardRankBefore(hc(i));return A(d)}if(t===f.rankPage){const d=await this.runShardRankPage(mc(i));return A(d)}if(t===f.cdcSync){const d=await this.cdcSyncPage(bc(i));return A(d)}if(t===f.applyCdc){const d=await this.runShardApplyCdc(yc(i));return await this.flushChangedTables(),this.recordAudit(i,"applyCdc",{detail:{applied:d.applied}}),A(d)}if(t===f.runAs)return this.handleRunAs(i);const c=await this.handleExtraAdminOp(t,i);return c||b({error:{code:"UNKNOWN_ADMIN_OP",message:`unknown admin op: ${t}`}},404)}catch(i){return this.errorToResponse(i)}}async handleExtraAdminOp(e,t){const r=this.simpleAdminHandlers()[e];if(r!==void 0)return r(t);const s=this.aiAdminHandlers()[e];if(s!==void 0)return s(t);const i=await this.handleIssueTriageOp(e,t);return i!==void 0?i:this.handleInspectAdminOp(e)??this.handlePitrAdminOp(e,t)}handleInspectAdminOp(e){if(e===f.listReactors)return this.handleListReactors()}async handleIssueTriageOp(e,t){const r=this.parseIssueTriagePatch(e,t);if(r===void 0)return;const s=Wa(t),i=typeof t.updatedBy=="string"?t.updatedBy:void 0,o=this.shardHost.sql,a=Ys(o,s,r,Date.now(),i);return this.recordChangedTable(Zs),await this.flushChangedTables(),this.recordAudit(t,e.slice(M.length),{detail:{...r,hash:s}}),A({state:a})}parseIssueTriagePatch(e,t){if(e===f.resolveIssue)return{status:"resolved"};if(e===f.ignoreIssue)return{status:"ignored"};if(e===f.assignIssue)return{assignee:$a(t),status:"open"};if(e===f.setIssueSeverity)return{severity:Ka(t)}}handleBackfillSearch(e){const t=Ur(e,"backfillSearch",Number.POSITIVE_INFINITY);if("rejection"in t)return t.rejection;const r=this.runShardSearchBackfill(t);return this.recordAudit(e,"backfillSearch",{detail:{done:r.done,pages:r.pages}}),A(r)}linkAfterCommit(e){const t=this.afterCommitTail.then(async()=>e().finally(()=>{this.afterCommitTail===t&&(this.afterCommitStalled=!1)}));return this.afterCommitTail=t,t}async handleBackfillVectors(e){const t=e.restart,r=Ur(e,"backfillVectors",Co);if("rejection"in r)return r.rejection;if(t!==void 0&&typeof t!="boolean")return b({error:{code:"BAD_REQUEST",message:"backfillVectors: restart must be a boolean"}},400);if(this.vectorBackfillRunning)return b({error:{code:"CONFLICT",message:"backfillVectors: a backfill is already running on this shard; retry once it returns"}},409);this.vectorBackfillRunning=!0;let s;try{s=await this.runShardVectorBackfill({...r,...t===!0?{restart:!0}:{}})}finally{this.vectorBackfillRunning=!1}return this.recordAudit(e,"backfillVectors",{detail:{done:s.done,error:s.error,failed:s.failed,pages:s.pages,restart:t===!0,rows:s.rows}}),s.error!==void 0?b({error:{code:"SERVICE_UNAVAILABLE",message:`backfillVectors: ${s.error}`},result:s},503):A(s)}handleRecordAuthEvent(e){const t=ec(e);try{ei(this.shardHost.sql,{outcome:t.outcome,ts:Date.now()})}catch{}return A({recorded:!0})}handleRecordImportAudit(e){const t=rc(e);return this.recordAudit(e,t.op,{detail:t.detail}),A({recorded:!0})}async handleRecordContainerEvent(e){const t=sc(e);if(this.logs.push(t),t.level==="error"||t.exitCode!==void 0&&t.exitCode!==0){const s={durationMs:0,errorMessage:t.message,functionPath:t.functionPath,outcome:"error",shardKey:this.runner.shardKey,ts:t.timestamp};this.persistRequestLog(s,this.requestLogConfig()),this.recordChangedTable(Pt),await this.flushChangedTables()}return A({recorded:!0})}async handleRunAs(e){const t=ic(e),r=await this.withSensitiveScope(t.functionPath,t.args,s=>this.withRequestIdentity(t.userId,t.identity,void 0,()=>this.handleRpc(t.functionPath,t.args,void 0,void 0,void 0,s))).catch(async s=>{throw await this.flushAfterDispatch("runAs:flush"),s});return await this.flushChangedTables(),this.recordAudit(e,"runAs",{detail:{functionPath:t.functionPath,runAsUserId:t.userId}}),A(r)}async flushAfterDispatch(e){await this.flushChangedTables().catch(t=>{this.recordShapeError(e,t)})}declaredWorkflowHandle(e){const t=this.workflowsMetadata().workflows.find(s=>s.exportName===e);if(!t)throw new p("BAD_REQUEST",`workflow "${e}" is not declared`);const r=Ia(this.env,this.state.exports,t.className,["create","get"]);if(r===void 0)throw new p("BAD_REQUEST",`workflow "${t.className}" is not available on this deployment`);return r}async handleCreateWorkflowInstance(e){const t=Ga(e),s=await this.declaredWorkflowHandle(t.exportName).create({id:t.id,params:t.params}),i=await s.status(),o={id:s.id,status:hr(i.status)};return this.recordAudit(e,"createWorkflowInstance",{id:s.id,detail:{exportName:t.exportName}}),A(o)}async handleGetWorkflowInstanceStatus(e){const t=Qa(e),i=await(await this.declaredWorkflowHandle(t.exportName).get(t.id)).status(),o={error:za(i.error),id:t.id,output:i.output,status:hr(i.status)};return A(o)}async handleSendWorkflowEvent(e){const t=ja(e),r=this.declaredWorkflowHandle(t.exportName),s=await this.workflowEvent(t.type);if(s===void 0){const a=this.workflowsMetadata().eventTypes??[],c=a.length===0?"no events are declared":`known types: ${a.map(d=>JSON.stringify(d)).join(", ")}`;throw new p("BAD_REQUEST",`sendWorkflowEvent: no \`defineWorkflowEvent\` export declares type ${JSON.stringify(t.type)} (${c})`)}let i;try{i=s.payload.parse(t.payload)}catch(a){const c=a instanceof Error?a.message:String(a);throw new p("BAD_REQUEST",`sendWorkflowEvent: event ${JSON.stringify(t.type)} payload validation failed: ${c}`)}const o=await r.get(t.id);if(typeof o.sendEvent!="function")throw new p("BAD_REQUEST",`workflow "${t.exportName}" instances do not accept events on this deployment`);await o.sendEvent({payload:i,type:t.type});try{this.recordAudit(e,"sendWorkflowEvent",{id:t.id,detail:{exportName:t.exportName,type:t.type}})}catch(a){console.error("[@lunora/do] sendWorkflowEvent audit write failed; the event was delivered:",a)}return A({sent:!0})}async dispatchOneReactor(e,t,r){try{const s=await this.runReactor(t,r);s!==void 0&&Gt(e,t,{digest:s.digest,now:Date.now(),result:s.ran?"ran":"suppressed",tables:s.tables.filter(i=>i!==Fn)})}catch(s){this.recordReactorError(t,s);try{Gt(e,t,{error:s instanceof Error?s.message:String(s),now:Date.now(),result:"error"})}catch(i){this.recordReactorError(t,i)}}finally{await this.flushChangedTables()}}claimReactorBudget(e,t){const r=t.get(e)??0;return r<v.MAX_REACTOR_RUNS_PER_DRAIN?(t.set(e,r+1),!0):(r===v.MAX_REACTOR_RUNS_PER_DRAIN&&(t.set(e,r+1),this.recordReactorError(e,new Error(`reactor did not converge: ran ${String(v.MAX_REACTOR_RUNS_PER_DRAIN)} times in one refresh drain and its watched read kept changing. Its handler is rewriting what its own select observes; stopped for this drain.`))),!1)}handleListReactors(){const e=new Map(Hn(this.sql).map(r=>[r.path,r.state])),t=this.lifecycleHookPaths("reactor").map(r=>{const s=e.get(r);return s===void 0?{errors:0,path:r,runs:0,state:"idle",suppressed:0}:{errors:s.stats.errors,...s.lastError===void 0?{}:{lastError:s.lastError},...s.lastRanAt===0?{}:{lastRanAt:s.lastRanAt},path:r,runs:s.stats.runs,state:s.lastError===void 0?"active":"failing",suppressed:s.stats.suppressed,...s.tables===void 0?{}:{tables:s.tables}}});return A({reactors:t})}async handleListFlags(e){const t=e.context,r=typeof t=="object"&&t!==null&&!Array.isArray(t)?t:void 0,s=await this.evaluateFlags(r);return A(s)}async withAdminRequestScope(e){const t=this.captureRequestScope(),r=this.mutationBookkeeping;this.currentRequestBookmark=void 0,this.currentResponseBookmark=void 0,this.currentRequestUserId=void 0,this.currentRequestIdentity=void 0,this.currentRequestClientId=void 0,this.currentRequestClientSeq=void 0,this.currentRequestBaselineSeq=void 0,this.currentRequestIp=void 0,this.currentRequestOrigin=void 0,this.currentRequestMutationId=void 0,this.currentMutatorClass=void 0,this.mutationBookkeeping=void 0,this.currentRequestSampleErrors=void 0,this.currentRequestSystem=!1,this.currentRequestTraceparent=void 0;try{return await e()}finally{this.restoreRequestScope(t),this.mutationBookkeeping=r}}async withRequestIdentity(e,t,r,s){const i=this.currentRequestUserId,o=this.currentRequestIdentity,a=this.currentRequestIp;this.currentRequestUserId=e,this.currentRequestIdentity=t,this.currentRequestIp=r;try{return await s()}finally{this.currentRequestUserId=i,this.currentRequestIdentity=o,this.currentRequestIp=a}}handleRecordMail(e){const t=nc(e),r=Qt(this.shardHost.sql,t,Date.now());return A(r)}handleClearCapturedMail(){const e=Wn(this.shardHost.sql);return A(e)}handleSendTestMail(e){const t=oc(e),r=Qt(this.shardHost.sql,t,Date.now());return A(r)}handleRecordQueueMessage(e){const t=ac(e),r=$n(this.shardHost.sql,t,Date.now());return A(r)}async handleDropOutboxEntry(e){const{id:t}=mr("dropOutboxEntry",e);return A(await this.scheduleOutboxRunner.drop(e,t))}async handleRetryOutboxEntry(e){const{id:t}=mr("retryOutboxEntry",e),r=Date.now(),s=this.scheduleOutboxRunner.retry(t,r);if(s==="cancelling")throw this.recordAudit(e,"retryOutboxEntry",{id:t,detail:{outcome:"refused"}}),new p("CONFLICT",`retryOutboxEntry: a cancel of "${t}" at the scheduler is still in flight; retry once it settles`,{status:409});const i=s==="retried";if(i){this.globalPollArmedAt=void 0;try{await this.scheduleGlobalPoll(r,!0)}catch(o){throw this.recordAudit(e,"retryOutboxEntry",{id:t,detail:{outcome:"failed"}}),o}this.recordAudit(e,"retryOutboxEntry",{id:t,detail:{outcome:"applied"}})}return A({retried:i})}handleClearQueueMessages(){const e=Kn(this.shardHost.sql);return A(e)}handleRebuildCompanions(e){return Gn(this.shardHost.sql),this.invalidateCompanionMemo(),this.recordAudit(e,"rebuildCompanions"),A({ok:!0})}async handleSendQueueMessage(e){const t=cc(e),{binding:r}=this.resolveQueueBinding(t.exportName);let s;return t.batch===void 0?(await r.send(t.body,{contentType:t.contentType,delaySeconds:t.delaySeconds}),s=1):(await r.sendBatch(t.batch.map(i=>({body:i,contentType:t.contentType,delaySeconds:t.delaySeconds}))),s=t.batch.length),this.recordAudit(e,"sendQueueMessage",{detail:{count:s,exportName:t.exportName}}),A({sent:s})}async handleExplainIssue(e){const t=await ti(await this.aiBinding(),e);return t.degraded?t.reason!=="no-ai-binding"&&this.recordAudit(e,"explainIssue",{detail:{groundedId:t.groundedId,reason:t.reason}}):this.recordAudit(e,"explainIssue",{detail:{groundedId:t.groundedId,model:t.model}}),A(t)}async handleGenerateSql(e){this.ensureMigrated();const t=this.state.storage.sql,r=Ue(t).map(o=>({columns:this.tableColumns(o.name).map(a=>a.name),table:o.name})),{generateSql:s}=await pe(),i=await s(await this.aiBinding(),e,r);return i.degraded?i.reason!=="no-ai-binding"&&this.recordAudit(e,"aiGenerateSql",{detail:{reason:i.reason}}):this.recordAudit(e,"aiGenerateSql",{detail:{sql:i.sql}}),A(i)}async handleFindRelated(e){return A(await this.runShardFindRelated(pc(e)))}simpleAdminHandlers(){return{[f.backfillSearch]:e=>this.handleBackfillSearch(e),[f.backfillVectors]:e=>this.handleBackfillVectors(e),[f.findRelated]:e=>this.handleFindRelated(e),[f.clearCapturedMail]:()=>this.handleClearCapturedMail(),[f.clearQueueMessages]:()=>this.handleClearQueueMessages(),[f.createAdminToken]:e=>this.handleCreateAdminToken(e),[f.createWorkflowInstance]:e=>this.handleCreateWorkflowInstance(e),[f.dropOutboxEntry]:e=>this.handleDropOutboxEntry(e),[f.explainIssue]:e=>this.handleExplainIssue(e),[f.getWorkflowInstanceStatus]:e=>this.handleGetWorkflowInstanceStatus(e),[f.listAdminTokens]:()=>A({tokens:Qn(this.shardHost.sql)}),[f.listFlags]:e=>this.handleListFlags(e),[f.rebuildCompanions]:e=>this.handleRebuildCompanions(e),[f.recordAuthEvent]:e=>this.handleRecordAuthEvent(e),[f.recordContainerEvent]:e=>this.handleRecordContainerEvent(e),[f.recordImportAudit]:e=>this.handleRecordImportAudit(e),[f.recordMail]:e=>this.handleRecordMail(e),[f.recordQueueMessage]:e=>this.handleRecordQueueMessage(e),[f.releaseShardRegistration]:e=>this.handleReleaseShardRegistration(e),[f.replayQueueMessage]:e=>this.handleReplayQueueMessage(e),[f.retryOutboxEntry]:e=>this.handleRetryOutboxEntry(e),[f.revokeAdminToken]:e=>this.handleRevokeAdminToken(e),[f.sendQueueMessage]:e=>this.handleSendQueueMessage(e),[f.sendTestMail]:e=>this.handleSendTestMail(e),[f.sendWorkflowEvent]:e=>this.handleSendWorkflowEvent(e),[f.verifyAdminToken]:e=>this.handleVerifyAdminToken(e)}}handleCreateAdminToken(e){const{digest:t,expiresAt:r,name:s}=e;if(typeof s!="string"||!Po(s)||typeof t!="string"||!Yd.test(t))throw new p("BAD_REQUEST","createAdminToken: expected { name: /^[a-z0-9][a-z0-9_-]{0,63}$/, digest: <sha-256 hex> }",{status:400});if(r!==void 0&&(typeof r!="number"||!Number.isFinite(r)))throw new p("BAD_REQUEST","createAdminToken: `expiresAt` must be an epoch-ms number",{status:400});if(e.scopes!==void 0&&(!Array.isArray(e.scopes)||!e.scopes.every(Go)))throw new p("BAD_REQUEST",`createAdminToken: \`scopes\` must be a list of ${is.join(", ")}`,{status:400});const i=Array.isArray(e.scopes)?e.scopes:[],o=typeof e.createdAt=="number"&&Number.isSafeInteger(e.createdAt)?e.createdAt:Date.now();if(!jn(this.shardHost.sql,{createdAt:o,digest:t,expiresAt:r,name:s,scopes:i}))throw new p("ADMIN_TOKEN_EXISTS",`an admin token named "${s}" already exists — revoke it first`,{status:409});return this.recordAuditAfterTokenChange(e,"createAdminToken",s),A({createdAt:o,name:s,scopes:i,...r===void 0?{}:{expiresAt:r}})}recordAuditAfterTokenChange(e,t,r){try{this.recordAudit(e,t,{id:r})}catch(s){console.error(`[@lunora/do] ${t} audit write failed for "${r}"; the change was applied:`,s)}}handleRevokeAdminToken(e){if(typeof e.name!="string"||typeof e.createdAt!="number")throw new p("BAD_REQUEST","revokeAdminToken: expected { name, createdAt }",{status:400});const t=zn(this.shardHost.sql,e.name,e.createdAt);return t&&this.recordAuditAfterTokenChange(e,"revokeAdminToken",e.name),A({revoked:t})}handleVerifyAdminToken(e){const{digest:t,name:r}=e,s=typeof r=="string"&&typeof t=="string"?Vn(this.shardHost.sql,r,t,Date.now()):void 0;return A(s!==void 0?{ok:!0,...s}:{known:typeof r=="string"&&Jn(this.shardHost.sql,r),ok:!1})}aiAdminHandlers(){return{[f.aiChartConfig]:async e=>this.handleAiChartConfig(e),[f.aiCronExpression]:async e=>this.handleAiCronExpression(e),[f.aiGenerateSql]:async e=>this.handleGenerateSql(e),[f.aiNameQuery]:async e=>this.handleAiNameQuery(e),[f.aiTableFilter]:async e=>this.handleAiTableFilter(e)}}async handleAiNameQuery(e){const{generateQueryName:t}=await pe(),r=await t(await this.aiBinding(),e);return r.degraded&&r.reason!=="no-ai-binding"&&this.recordAudit(e,"aiNameQuery",{detail:{reason:r.reason}}),A(r)}async handleAiCronExpression(e){const{generateCron:t}=await pe(),r=await t(await this.aiBinding(),e);return r.degraded&&r.reason!=="no-ai-binding"&&this.recordAudit(e,"aiCronExpression",{detail:{reason:r.reason}}),A(r)}async handleAiTableFilter(e){this.ensureMigrated();const t=typeof e.table=="string"?e.table:"",r=t===""?[]:this.tableColumns(t).map(c=>c.name),s=r.length===0?[]:this.sql.exec(`PRAGMA table_info(${dt(t)})`).toArray().map(c=>c.name),i=this.columnKinds(t)??{},{generateFilter:o}=await pe(),a=await o(await this.aiBinding(),e,r,s,i);return a.degraded&&a.reason!=="no-ai-binding"&&this.recordAudit(e,"aiTableFilter",{detail:{reason:a.reason,table:t}}),A(a)}async aiBinding(){const{asOptInLevel:e}=await tl(),t=this.env;return e(t?.LUNORA_AI_OPT_IN)==="disabled"?void 0:t?.AI}async handleAiChartConfig(e){const t=Array.isArray(e.columns)?e.columns.filter(c=>typeof c=="string").slice(0,64):[],r=typeof e.types=="object"&&e.types!==null?e.types:void 0,s=r===void 0?void 0:Object.fromEntries(Object.entries(r).filter(c=>typeof c[1]=="string")),i=typeof e.rowCount=="number"?e.rowCount:0,{generateChart:o}=await pe(),a=await o(await this.aiBinding(),e,{columns:t,rowCount:i,types:s});return a.degraded&&a.reason!=="no-ai-binding"&&this.recordAudit(e,"aiChartConfig",{detail:{reason:a.reason}}),A(a)}async handleReplayQueueMessage(e){const t=dc(e),r=Xn(this.shardHost.sql,t.id);if(r===void 0)throw new p("BAD_REQUEST",`replayQueueMessage: captured message "${t.id}" was not found`,{status:404});if(Yn(r.body))throw new p("BAD_REQUEST",`replayQueueMessage: captured message "${t.id}" has a truncated or unserializable body and can't be replayed faithfully`,{status:422});const s=t.target??this.resolveReplayTarget(r.queue)??r.exportName;if(typeof s!="string"||s==="")throw new p("BAD_REQUEST",`replayQueueMessage: captured message "${t.id}" has no declared producer to replay onto (pass \`target\`)`);const{binding:i}=this.resolveQueueBinding(s);return await i.send(r.body),this.recordAudit(e,"replayQueueMessage",{detail:{messageId:r.messageId,target:s},id:t.id}),A({sent:1,target:s})}resolveQueueBinding(e){const t=this.queuesMetadata().queues.find(s=>s.exportName===e);if(!t)throw new p("BAD_REQUEST",`queue "${e}" is not declared`);const r=this.env?.[t.binding];if(typeof r!="object"||r===null||typeof r.send!="function")throw new p("BAD_REQUEST",`queue binding "${t.binding}" is not available on this deployment`);return{binding:r,metadata:t}}resolveReplayTarget(e){const{queues:t}=this.queuesMetadata(),r=t.find(s=>s.deadLetterQueue===e);return r!==void 0?r.exportName:t.find(s=>s.name===e)?.exportName}recordAudit(e,t,r={}){const s=this.shardHost.sql,i=this.getCurrentUserId(),o=this.adminCallTokens.get(e),a=i===void 0&&o===void 0?r.detail:{...r.detail,...i===void 0?{}:{userId:i},...o===void 0?{}:{adminToken:o}};Zn(s,{detail:a,id:r.id,op:t,table:r.table,ts:Date.now()})}recordRequestLog(e,t,r,s,i,o,a,c){const d=this.requestLogConfig();if(s==="ok"&&!kc(d.sampleRate))return;const l={cacheHit:a.cacheHit,durationMs:r,errorMessage:c,functionPath:e,identity:this.currentRequestIdentity,outcome:s,...o.rayId===void 0?{}:{rayId:o.rayId},redactedArgs:Object.keys(t).length===0?void 0:ri(t,this.sensitiveArgNames(e)),shardKey:this.runner.shardKey,tablesRead:a.readTables===void 0?[]:[...a.readTables],tablesWritten:i,traceId:o.traceId,ts:Date.now(),userId:this.getCurrentUserId()};this.persistRequestLog(l,d)}persistRequestLog(e,t){const r={captureRaw:t.captureRaw,retention:t.retention},s=this.attributeToDeploy(e);try{si(this.shardHost.sql,s,r)}catch{}if(t.emit||s.outcome==="error")try{ii(s,r)}catch{}}attributeToDeploy(e){const{deploymentId:t,versionTag:r}=eo(this.env);return t===void 0&&r===void 0?e:{...e,...t===void 0?{}:{deploymentId:t},...r===void 0?{}:{versionTag:r}}}requestLogConfig(){const e=this.env??{};return{captureRaw:q(this.env),emit:wc(e.LUNORA_REQUEST_LOG_EMIT,q(this.env)),retention:Ac(e.LUNORA_REQUEST_LOG_RETENTION),sampleRate:Tc(e.LUNORA_REQUEST_LOG_SAMPLE)}}async handlePitrAdminOp(e,t){const r=typeof t.time=="number"||typeof t.time=="string"?t.time:void 0;if(e===f.getPitrBookmark)return A(await to(this.state.storage,r));if(e!==f.pitrRestore)return;const s=t.restart===!0,i=typeof t.bookmark=="string"?t.bookmark:void 0,o=await ro(this.state.storage,{bookmark:i,time:r});this.cdcMeta.cdcEnabled()&&this.cdcMeta.bumpCdcEpochUncached(),this.recordAudit(t,"pitrRestore",{detail:{restart:s,restoredTo:o.restoredTo,undoBookmark:o.undoBookmark}});const a=A({...o,restarted:s});return s&&this.state.abort?.("lunora PITR restore"),a}readAdminOp(e,t){this.ensureMigrated();const r=this.shardHost.sql,s=this.readAdminWildcardOp(e);if(s!==void 0)return{result:s,tables:new Set([_])};if(e===f.getAuditLog)return _c(r,t);if(e===f.getRequestLog)return Ic(r,t);if(e===f.getIssues)return Cc(r,t);const i=Uc(e,r,t);if(i)return i;if(e===f.readTablePage)return this.readAdminTablePage(r,t);if(e===f.facetColumn)return Lc(r,t,this.columnKinds(typeof t.table=="string"?t.table:""));if(e===f.runSql)return this.functionMetrics.flushUnwrittenMetrics(),Pc(r,t);e===f.getQueryInsights&&this.functionMetrics.flushUnwrittenMetrics();const o=Fd(e,M,r,t,_);if(o!==void 0)return o;const a=this.readAdminTableSignal(e,r,t);if(a)return a;const c=this.readAdminStorageSignal(e,r,t);return c||null}readAdminTableSignal(e,t,r){if(e===f.listTableIndexes||e===f.describeTable){const s=typeof r.table=="string"?r.table:"";return{result:e===f.describeTable?{columns:this.tableColumns(s)}:{indexes:this.tableIndexes(s)},tables:new Set([s===""?_:s])}}if(e===f.describeTables){const{byTable:s,tables:i}=yr(r,o=>this.tableColumns(o));return{result:{columnsByTable:s},tables:i}}if(e===f.listTablesIndexes){const{byTable:s,tables:i}=yr(r,o=>this.tableIndexes(o));return{result:{indexesByTable:s},tables:i}}if(e===f.migrationStatus){const s=typeof r.id=="string"?r.id:void 0;return{result:{migrations:so(t,s)},tables:new Set([_])}}}readAdminStorageSignal(e,t,r){if(e===f.storageReferences)return Bc(t,r,this.storageColumns());if(e===f.storageOrphans)return qc(t,r,this.storageColumns())}readAdminWildcardOp(e){if(e===f.listTables)return Ue(this.shardHost.sql);if(e===f.getMetrics)return this.collectMetrics();if(e===f.getFunctionStats)return this.functionMetrics.collectFunctionStats(this.metrics.sinceMs);if(e===f.listSubscriptions)return this.collectSubscriptions();if(e===f.getFanoutMetrics)return this.collectFanoutMetrics();if(e===f.getLogs)return{dropped:this.logs.dropped,entries:this.logs.entries()};if(e===f.getTraces){const t=ni(this.spans.entries());return{dropped:this.spans.dropped,total:t.total,traces:t.traces}}if(e===f.getMetricSeries)return{series:this.metricSeries.entries()};if(e===f.getMetricHistory)return oi(this.sql);if(e===f.getSettings)return io(this.env);if(e===f.getSecurityAudit)return ai(this.env,{dev:q(this.env)});if(e===f.getAdvisories)return{advisories:[...this.advisories(),...this.runtimeAdvisories()]};if(e===f.rlsPolicies)return this.rlsMetadata();if(e===f.maskPolicies)return this.maskMetadata();if(e===f.storageRules)return this.storageRulesMetadata();if(e===f.studioFeatures)return this.studioFeatures();if(e===f.listWorkflows)return this.workflowsMetadata();if(e===f.listQueues)return this.queuesMetadata()}collectSubscriptions(){return no(this.runner.sockets().map(e=>this.readAttachment(e)))}collectFanoutMetrics(){const e=oo(this.runner.sockets().map(r=>this.readAttachment(r))),t=this.relay?.relayCount()??0;return{...e,globalPoll:this.globalPoll,maxRelays:this.relay?.maxRelays()??ao,promoted:t>0,relayCount:t,shapePoke:this.fanout.shapePoke,shapeProbe:this.shapeProbe,sinceMs:this.metrics.sinceMs,whisper:this.fanout.whisper}}columnKinds(e){const t=this.tableColumns(e);return t.length===0?void 0:Object.fromEntries(t.map(r=>[r.name,r.type]))}readAdminTablePage(e,t){const r=typeof t.table=="string"?t.table:"";return{result:co(e,{filters:Le(t.filters),limit:typeof t.limit=="number"?t.limit:void 0,offset:typeof t.offset=="number"?t.offset:void 0,orderBy:Ja(t.orderBy),columnKinds:this.columnKinds(r),refs:this.tableRefs(r),search:typeof t.search=="string"?t.search:void 0,skipCount:typeof t.skipCount=="boolean"?t.skipCount:void 0,table:r}),tables:new Set([r===""?_:r])}}executeAdminSubscription(e,t){const r=this.readAdminOp(e,t);return r?{result:r.result,tables:r.tables}:null}async resolveReactiveOutcome(e,t,r,s,i){if(r)return this.executeAdminSubscription(e,t);if(e.startsWith(Re)){const a=await this.runFlagSubscriptionRead(e,t,s);return a===null?null:{result:a,tables:new Set([_])}}const o=await this.executeSubscription(e,t,s,i);return o?.identityTracked===!0&&this.settleIdentityUse(e,o),o}settleIdentityUse(e,t){if(!this.identityReadPaths.has(e)){try{this.encodeOutcome(t)}catch{return}this.identityReadPaths.has(e)||this.identityFreePaths.add(e)}}isIdentityIndependent(e){return e.startsWith(M)}resolveReactiveOutcomeDeduped(e,t,r,s,i,o,a){if(this.deliveryAuthorization)return this.resolveReactiveOutcome(e,r(),s,O(i),a);const{key:c,leader:d}=this.reactiveRunKey(e,t,i),l=o.get(c);if(l!==void 0)return this.joinReactiveRun(l,e,r,s,i,a);const h=this.resolveReactiveOutcome(e,r(),s,O(i),a);return o.set(c,{leader:d,pending:h}),h}reactiveRunKey(e,t,r){if(this.isIdentityIndependent(e))return{key:ve(e,t,null)};const s=fe(r);return this.identityFreePaths.has(e)?{key:ve(e,t,dl),leader:s}:{key:ve(e,t,s)}}joinReactiveRun(e,t,r,s,i,o){if(e.leader===void 0||e.leader===fe(i))return e.pending;const a=()=>this.resolveReactiveOutcome(t,r(),s,O(i),o);return e.pending.then(c=>c?.identityTracked===!0&&!this.identityReadPaths.has(t)&&this.encodedOutcomes.has(c)?c:a(),a)}resolveSeedOutcome(e,t,r,s,i,o){if(this.deliveryAuthorization)return this.resolveReactiveOutcome(e,r(),s,O(i));const{key:a,leader:c}=this.reactiveRunKey(e,t,i),d=`${o}\0${a}`,l=this.seedRuns.get(d);if(l!==void 0)return this.joinReactiveRun(l,e,r,s,i);const h=this.resolveReactiveOutcome(e,r(),s,O(i)).finally(()=>{this.seedRuns.get(d)?.pending===h&&this.seedRuns.delete(d)});return this.seedRuns.set(d,{leader:c,pending:h}),h}async adminCaller(e){const t=(this.env??{}).LUNORA_ADMIN_TOKEN;if(!t||t.length===0)return;const r=Ye(e.headers.get("authorization"));if(r!==void 0&&le(r,t))return{};const s=e.headers.get(Bo),i=s===null?void 0:await qo(t,s);return i===void 0?void 0:{tokenName:i}}async handleStream(e,t,r,s,i=0,o){const a=this.readAttachment(e);if(this.deliveryAuthorization){this.sendSubscriptionError(e,t,"NOT_IMPLEMENTED",j);return}const c=this.reserveStream(e,t);if(c===void 0)return;let d=!1;try{d=await this.startStream(e,t,r,s,a,c.controller,i,o)}catch(l){se(c.controller)||Lr(e,t,l,"unhandled stream error")}finally{this.releaseStream(e,t,c.cancellers,c.controller,d)}}reserveStream(e,t){const r=this.streamCancellers.get(e);if(r?.has(t)){this.sendFrame(e,JSON.stringify({error:{code:"STREAM_ID_IN_USE",message:`stream id ${JSON.stringify(t)} is already live on this socket`},id:t,type:"error"}),"control");return}if((r?.size??0)>=v.MAX_STREAMS_PER_SOCKET){this.sendFrame(e,JSON.stringify({error:{code:"TOO_MANY_STREAMS",message:`stream cap of ${String(v.MAX_STREAMS_PER_SOCKET)} reached on this socket`},id:t,type:"error"}),"control");return}const s=r??Q(this.streamCancellers,e),i=new AbortController;return s.set(t,i),{cancellers:s,controller:i}}async startStream(e,t,r,s,i,o,a,c){const d=this.prepareFunction(r,"stream");if(d!==void 0)try{await d}catch(h){return se(o)||Lr(e,t,h,"stream preparation failed"),!1}if(this.isStreamStopped(e,o))return!1;const l=this.executeStream(r,s,O(i));return l?l.durable?(await this.attachDurableStream(e,t,r,s,{durable:l.durable,iterator:l.iterator},o,a,c),!0):(await this.pumpStream(e,t,l.iterator,o),!1):(N(e,JSON.stringify({error:{code:"NOT_FOUND",message:`stream not registered: ${r}`},id:t,type:"error"})),!1)}async pumpStream(e,t,r,s){N(e,JSON.stringify({id:t,type:"ack"}));for await(const i of r(s.signal)){if(se(s))break;if(this.dropIfLapsed(e)){s.abort();break}if(await J(e),se(s))break;if(this.dropIfLapsed(e)){s.abort();break}e.send(JSON.stringify({data:D(i),id:t,type:"chunk"}))}se(s)||e.send(JSON.stringify({id:t,type:"complete"}))}isStreamStopped(e,t){return se(t)||this.closingSockets.has(e)}releaseStream(e,t,r,s,i){i||r.get(t)!==s||(r.delete(t),r.size===0&&this.streamCancellers.delete(e))}async attachDurableStream(e,t,r,s,i,o,a,c){const d=this.readAttachment(e),h=`${d.userId??bl(d,t)}\0${Ve(d.userId,d.identity)}\0${r}:${Se(s)}`,u=Q(this.streamCancellers,e),m=gl(e,t);m.ack();const S=()=>{u.get(t)===o&&u.delete(t),u.size===0&&this.streamCancellers.delete(e)};let E=0;const g={chunk:R=>R.seq<=E?!0:this.dropIfLapsed(e)?(S(),!1):(E=R.seq,m.chunk(R.data,R.seq,R.generation)),complete:()=>{m.complete(),S()},fail:R=>{m.fail(R),S()}};o.signal.addEventListener("abort",()=>{this.durableStreams.detach(h,g),S()}),await this.durableStreams.attach({...c===void 0?{}:{generation:c},iterator:i.iterator,runKey:h,sinceChunk:a,sink:g,...i.durable.ttlMs===void 0?{}:{ttlMs:i.durable.ttlMs}})}async handleReleaseShardRegistration(e){const{dryRun:t,tables:r}=lc(e),s=await this.shardRegistration.release(r,t);return!t&&s.released.length>0&&this.recordAudit(e,"releaseShardRegistration",{detail:{released:s.released}}),A(s)}async flushChangedTables(){const e=this.pendingChangedTables,t=this.pendingChangedKeys,r=this.pendingChangedBookmarks,s=this.pendingGlobalWriteTables;if(this.pendingChangedTables=void 0,this.pendingChangedKeys=void 0,this.pendingChangedBookmarks=void 0,this.pendingGlobalWriteTables=void 0,!(!e||e.size===0)){for(const i of s??[])this.reactiveCache?.invalidateTable(i);this.mergeSubscriptionRefresh(new Set(e),t,r===void 0?void 0:new Set(r.values())),await this.armTtlSweepAfterWrite(e).catch(i=>{this.recordShapeError("ttl:arm",i)}),this.shardRegistry()!==void 0&&await this.deferPastResponse(this.shardRegistration.register(e)),await this.startSubscriptionRefresh()}}mergeSubscriptionRefresh(e,t,r){if(this.writeGeneration+=1,this.pendingRefreshTables)for(const s of e)this.pendingRefreshTables.add(s);else this.pendingRefreshTables=e;this.pendingRefreshKeys=lo(this.pendingRefreshKeys,t,e);for(const s of r??[])this.pendingRefreshBookmarks??=new Set,this.pendingRefreshBookmarks.add(s)}async startSubscriptionRefresh(){if(this.pendingRefreshTables===void 0||this.refreshInFlight)return;const e=this.drainSubscriptionRefreshes();this.runner.background(e)||await e}async drainSubscriptionRefreshes(){if(this.refreshInFlight)return;this.refreshInFlight=!0;const e=new Map;try{let t=this.pendingRefreshTables,r=this.pendingRefreshKeys,s=this.pendingRefreshBookmarks;for(;t&&t.size>0;){this.pendingRefreshTables=void 0,this.pendingRefreshKeys=void 0,this.pendingRefreshBookmarks=void 0;const i=this.currentCdcCursor(),o=this.currentCdcEpoch();await Promise.all([this.refreshSubscriptions(t,i,o,r,Rl(s)),this.pokeShapeSubscribers(t,i,o),this.relay?.onFlush(t,i??0)]),await this.dispatchReactors(t,e),t=this.pendingRefreshTables,r=this.pendingRefreshKeys,s=this.pendingRefreshBookmarks}this.cdcRetention.sweep()}finally{this.refreshInFlight=!1}}recordSubscriptionRefreshError(e,t,r){this.metrics.subscriptionRefreshErrors+=1;try{const{body:s}=P(t,{fallbackCode:"SUBSCRIPTION_REFRESH_FAILED",redactedMessage:"subscription refresh failed"});this.recordUserLog(e,"error",[s],s.message,r,this.lastTelemetrySink,"subscriptionRefreshError")}catch{}}failureIdentityKey(e,t){return this.subscriptionFailures.hasFailures(e)?fe(O(t)):""}restartFailureStreakUnlessRetry(e,t,r,s){Nr(r,s)||this.subscriptionFailures.clear(e,t)}isDeterministicSubscriptionFailure(e){return Te(e)||V(e)&&(e.code==="SUBSCRIPTION_RESULT_TOO_LARGE"||this.deliveryAuthorization!==void 0&&e.code==="SUBSCRIPTION_PERSIST_FAILED")}failRefresh(e,t,r,s,i){if(this.socketIndex.forgetRestoredMemo(e,t)&&this.persistSubscriptionTables(e,t),this.isDeterministicSubscriptionFailure(s)){if(Te(s)){this.revokeSubscription(e,t);return}this.unsubscribe(e,t);const{body:o}=P(s);this.sendSubscriptionError(e,t,o.code,o.message,o),this.recordSubscriptionRefreshError(r,s,{subId:t});return}this.noteFailingSubscription(e,t,r,s,i)}noteFailingSubscription(e,t,r,s,i){if(this.recordSubscriptionRefreshError(r,s,{subId:t}),!this.subscriptionFailures.recordFailure(e,t,fe(O(i)),Date.now())||this.deliveryAuthorization)return;const{body:a}=P(s,{fallbackCode:"SUBSCRIPTION_REFRESH_FAILED",redactedMessage:"subscription refresh failed"});this.sendSubscriptionError(e,t,a.code,a.message,a,this.subscriptionFailures.retryHintMs(e,t))}memoSkipsRun(e,t,r,s){const i=this.socketIndex.memo(e,t);return this.deliveryAuthorization!==void 0&&i!==void 0&&i.lastJson!==ne&&$r(i,r,s)}async refreshSubscriptions(e,t,r,s,i){const o=[...this.runner.sockets()].filter(l=>this.deliveryAuthorization!==void 0||this.socketIndex.mayCare(l,e)),a=this.writeGeneration,c=new Map,d=async l=>{const h=this.socketIndex.beginVisit(l),u=this.readAttachment(l);if(this.dropIfLapsed(l,u))return;const m=this.socketDelivery(u),S=await this.attachmentAdminAuthorized(u),E=this.failureIdentityKey(l,u),{subs:g}=u,R=async(y,w,T,k,L,W)=>{const I=()=>this.holdsRegistration(l,y,w);try{const x=Qr(k);let C;if(this.deliveryAuthorization&&(C=await this.authorizeSubscription(l,y,O(u),T,x())),this.deliveryAuthorization&&C===void 0||W)return;if(this.memoSkipsRun(l,y,e,s)){this.sendSubscriptionSettlement(l,y,{cursor:t,epoch:r,generation:a},m,C,!0);return}const ee=await this.resolveReactiveOutcomeDeduped(T,k,x,L,u,c,i);if(!I())return;if(!ee){this.subscriptionFailures.clear(l,y),this.noteUnrecordedQuery(l,y),this.socketIndex.forgetRestoredMemo(l,y),this.dropSubscriptionTables(l,y);return}if(await J(l),!I())return;this.unmarkBroadcastSubscription(l,y),this.pushSubscriptionData(l,y,ee,{cursor:t,epoch:r,generation:a},m,C),this.subscriptionFailures.clear(l,y)}catch(x){I()&&this.failRefresh(l,y,T,x,u)}};for(const y of Object.keys(g)){const w=g[y];if(!w?.functionPath)continue;const{functionPath:T}=w,k=this.subscriptionRegistration(l,y),L=this.dropIfNotLive(l,y,T,S,k);if(L!==void 0&&await L)continue;const W=T.startsWith(M),I=Me(this.readAttachment(l).subTables,y);I!==void 0&&this.socketIndex.restoreMemo(l,y,I,ne);const x=this.socketIndex.memo(l,y);if(!this.deliveryAuthorization&&$r(x,e,s))continue;const C=this.subscriptionFailures.isBackingOff(l,y,E,Date.now());C&&!this.deliveryAuthorization||await R(y,k,T,w.args??{},W,C)}h(g)};await jt(o,l=>this.inRefreshBatch(l,()=>d(l)))}retryFailedSeed(e,t,r,s){this.recordSubscriptionRefreshError(r,s,{subId:t}),this.subscriptionFailures.recordFailure(e,t,fe(O(this.readAttachment(e))),Date.now());const{body:i}=P(s,{fallbackCode:"SUBSCRIPTION_REFRESH_FAILED",redactedMessage:"subscription refresh failed"});this.sendSubscriptionError(e,t,i.code,i.message,i,this.subscriptionFailures.retryHintMs(e,t))}async seedSubscriptionGuarded(e,t,r,s,i,o){const a=this.subscriptionFailures.streakMark(e,t),c=this.subscriptionRegistration(e,t);try{await this.seedSubscription(e,t,r,s,i),this.subscriptionFailures.clearIfUnchanged(e,t,a)}catch(d){if(!this.holdsRegistration(e,t,c)){this.recordSubscriptionRefreshError(s,d,{});return}if(o){if(this.deliveryAuthorization===void 0&&!this.isDeterministicSubscriptionFailure(d)){this.retryFailedSeed(e,t,s,d);return}if(this.subscriptionFailures.clear(e,t),Te(d)){this.revokeSubscription(e,t);return}}this.unsubscribe(e,t),this.recordSubscriptionRefreshError(s,d,{subId:t});const{body:l,redacted:h}=P(d,{fallbackCode:"SUBSCRIPTION_SEED_FAILED",redactedMessage:"subscription seed failed"});h&&console.error(`[@lunora/do] subscription seed failed for ${s}:`,d),this.sendSubscriptionError(e,t,l.code,l.message,l)}}async seedSubscription(e,t,r,s,i){const o=r.args??{},a=Qr(o),c=this.readAttachment(e),d=this.currentCdcCursor(),l=i?void 0:this.currentCdcEpoch(),h=this.writeGeneration,u=this.subscriptionRegistration(e,t),m=this.deliveryAuthorization?await this.authorizeSubscription(e,t,O(c),s,a()):void 0;if(this.deliveryAuthorization&&m===void 0)return;const S=await this.resolveSeedOutcome(s,o,a,i,c,`${String(h)}|${String(d)}|${String(l)}`);if(!S){!i&&!s.startsWith(Re)&&this.markBroadcastSubscription(e,t,s);return}if(await this.watchGlobalReads(s,S.tables),!this.holdsRegistration(e,t,u))return;const{sinceEpoch:E,sinceSeq:g}=r,R=this.deliveryAuthorization||i||g===void 0?void 0:this.evaluateResume(g,S.tables,E),y=i?void 0:R?.epoch??l;if(!this.dropIfLapsed(e)){if(R?.resumable){this.seedSubscriptionMemo(e,t,S,h);try{N(e,`{"type":"resume","id":${JSON.stringify(t)}${Xe(R.cursor??0,y)}}`)}catch{}return}this.pushSubscriptionData(e,t,S,{cursor:d,epoch:y,generation:h},this.socketDelivery(this.readAttachment(e)),m)}}socketDelivery(e){return{clientWatermark:this.socketClientWatermark(e),pageDeltas:e.pageDeltas===!0}}async handleShapeSubscribe(e,t,r){const s=this.shapeSubscribe(e,t,r);if(s!=="ok"){const o=s==="too_many"?"TOO_MANY_SUBSCRIPTIONS":"SUBSCRIPTION_PERSIST_FAILED",a=ot(s==="too_many"?"count":"size",v.MAX_SUBSCRIPTIONS_PER_SOCKET,v.MAX_ATTACHMENT_BYTES);this.sendSubscriptionError(e,t,o,a);return}const i=await this.seedShapeSubscription(e,t,r);if(i!=="ok"){this.shapeUnsubscribe(e,t),this.sendSubscriptionError(e,t,i.code,i.message,i);return}try{this.sendFrame(e,JSON.stringify({id:t,type:"ack"}),"control")}catch{}}sendSubscriptionError(e,t,r,s,i={},o){const a=o===void 0?{}:{retryAfterMs:o};try{this.sendFrame(e,JSON.stringify({code:r,error:{code:r,message:s,...Ce(i),...a},id:t,type:"error"}),"control")}catch{}}async seedShapeSubscription(e,t,r){const s=this.readAttachment(e),i=O(s),o=await this.relay?.seedRelayShape(e,t,r,i);if(o!==void 0)return o;let a;try{a=this.resolveShape(r.name,structuredClone(r.args??{}),i)}catch(c){this.recordShapeError(`shape:seed:${t}`,c);const{body:d}=P(c,{fallbackCode:"SHAPE_RESOLVE_FAILED",redactedMessage:"shape resolution failed"});return{code:d.code,message:d.message,...Ce(d)}}if(!a)return{code:"SHAPE_NOT_FOUND",message:`shape "${r.name}" not found or not permitted`};if(!a.global&&!this.cdcMeta.cdcEnabled())return{code:"SHAPE_REQUIRES_CDC",message:`shape "${r.name}" replicates from the changelog, which this app has not enabled — call .cdc() on defineApp()`};try{return a.global?await this.seedGlobalShape(e,t,a,i,s.connectionId??""):await this.seedOpLogShape(e,s.connectionId??"",t,r,a)}catch(c){this.recordShapeError(`shape:seed:${t}`,c);const{body:d}=P(c,{fallbackCode:"SHAPE_SEED_FAILED",redactedMessage:"shape seed failed"});return{code:d.code,message:d.message,...Ce(d)}}}async seedOpLogShape(e,t,r,s,i){await J(e);const{baseCheckpoint:o,cursor:a,epoch:c,reset:d,rowsPatch:l}=this.computeOpLogShapeSeed(s,i);return this.sendPoke(e,[{baseCheckpoint:o,reset:d,rowsPatch:l,shapeId:r}],a,c,o)&&this.recordShapeMemo(e,t,r,a,{carriedRows:!0}),"ok"}computeOpLogShapeSeed(e,t){const r=this.sql,s=this.currentCdcCursor()??0,i=this.currentCdcEpoch(),o=this.cdcMeta.cdcEnabled()?He(r):void 0,a=i!==void 0&&e.sinceEpoch===i,d=this.cdcMeta.cdcEnabled()&&e.sinceSeq!==void 0&&a&&e.sinceSeq>s?this.sealForkedTimeline():i,l=this.cdcMeta.cdcEnabled()&&e.sinceSeq!==void 0&&a&&e.sinceSeq<=s&&(e.sinceSeq===s||o!==void 0&&!ge(o,e.sinceSeq)),h=l&&e.sinceSeq!==void 0?this.diffShape(r,t,e.sinceSeq,s,Ke()):this.buildShapeSeed(r,t);return{baseCheckpoint:l?e.sinceSeq:void 0,cursor:s,epoch:d,reset:!l,rowsPatch:h}}rejectRetainedShapesAndRooms(){return this.rejectRetainedRooms()+this.rejectRetainedShapes()}rejectRetainedShapes(){if(!this.deliveryAuthorization||!this.retainedShapesNeedCleanup)return 0;let e=0;for(const t of this.runner.sockets()){for(const r of Object.keys(this.readAttachment(t).shapes??{}))this.sendSubscriptionError(t,r,"NOT_IMPLEMENTED",j),this.shapeUnsubscribe(t,r);e+=Object.keys(this.readAttachment(t).shapes??{}).length}return this.retainedShapesNeedCleanup=e>0,e}async pokeShapeSubscribers(e,t,r){if(this.deliveryAuthorization){this.rejectRetainedShapesAndRooms();return}const s=[...this.runner.sockets()].filter(u=>!this.socketIndex.isShapeFree(u)),i=t??this.currentCdcCursor()??0,o=this.sql,a=Ke();let c=0;const d=[],l=async u=>{const m=this.readAttachment(u);if(this.dropIfLapsed(u,m))return;const{shapes:S}=m;if(!S||Object.keys(S).length===0){this.socketIndex.markShapeFree(u);return}const E=m.connectionId??"";try{const g=O(m),{emptyAdvanced:R,partAdvanced:y,parts:w}=this.collectShapePokeParts(u,E,S,g,e,i,o,a);for(const T of R)this.recordShapeMemo(u,E,T,i,{carriedRows:!1,pending:d});if(w.length>0){for(const T of y)this.markShapeOwed(u,T);if(await J(u),this.sendPoke(u,w,i,r,void 0)){c+=1;for(const T of y)this.recordShapeMemo(u,E,T,i,{carriedRows:!0,pending:d})}}}catch(g){this.recordSubscriptionRefreshError(`${M}pokeShapeSubscribers`,g,{shapeIds:Object.keys(S)})}},h=Date.now();if(await jt(s,l),d.length>0)try{ho(this.sql,d)}catch{}this.fanout.shapePoke=Ge(this.fanout.shapePoke,s.length,c,Date.now()-h),this.shapeProbe=zt(this.shapeProbe,a.probesRun,a.probesServed)}retentionFloor(e){const t=this.currentCdcCursor()??0,r=[uo(e),this.relay?.minShapeCursor()].filter(s=>s!==void 0);return Math.max(0,r.length===0?t:Math.min(t,...r))}collectShapePokeParts(e,t,r,s,i,o,a,c){const d=[],l=[],h=[];for(const[u,m]of Object.entries(r))try{const S=this.resolveShape(m.name,structuredClone(m.args??{}),s);if(!S||S.global)continue;const E=this.shapeMemos.get(e)?.get(u);if(E!==void 0&&E.owed!==!0&&!i.has(S.table)){l.push(u);continue}const g=this.readShapeMemoCursor(e,t,u,m.sinceSeq),R=this.diffShape(a,S,g,o,c);if(R.length>0){const y=this.shapeMemos.get(e)?.get(u)?.delivered;d.push({baseCheckpoint:y,rowsPatch:R,shapeId:u}),h.push(u)}else l.push(u)}catch(S){this.markShapeOwed(e,u),this.recordSubscriptionRefreshError(`${M}pokeShapeSubscribers`,S,{subId:u})}return{emptyAdvanced:l,partAdvanced:h,parts:d}}readShapeCdcKeys(e,t,r,s){return po(e,t,r,s)}diffRelayedShape(e,t,r){const s=Ke(),i=this.diffShape(this.sql,e,t,r,s);return this.shapeProbe=zt(this.shapeProbe,s.probesRun,s.probesServed),i}diffShape(e,t,r,s,i){return fo(e,t,r,s,i,(o,a,c,d)=>this.readShapeCdcKeys(o,a,c,d))}buildShapeSeed(e,t){return mo(e,t.table,t.effectiveWhere).map(r=>({key:r.id,op:"insert",table:t.table,value:So(r.doc,t.columns)}))}async seedGlobalShape(e,t,r,s,i){const o=await this.readGlobalShapeRows(r,s);if(!this.withinGlobalShapeBound(o.length,`shape:seed:${t}`,r.table))return{code:"SHAPE_GLOBAL_TOO_LARGE",message:`global shape membership for "${r.table}" exceeds the ${String(v.GLOBAL_SHAPE_MAX_ROWS)}-row cap; narrow it with a shape predicate or an RLS read policy`};const{next:a,rowsPatch:c}=Vt(o,new Map,{columns:r.columns,table:r.table});return await J(e),this.sendPoke(e,[{reset:!0,rowsPatch:c,shapeId:t}],this.currentCdcCursor()??0,this.currentCdcEpoch(),void 0)&&(this.recordGlobalSnapshot(e,t,a),this.saveGlobalSnapshot(i,t,a)),await this.scheduleGlobalPoll(),"ok"}async refreshGlobalShape(e,t,r,s,i,o){const a=await this.readGlobalShapeRowsCached(r,s,o);if(!this.withinGlobalShapeBound(a.length,`shape:poll:${t}`,r.table)){o.requestResync();return}const{lost:c,snapshot:d}=this.readGlobalSnapshot(e,t,i),{next:l,rowsPatch:h}=Vt(a,d,{columns:r.columns,table:r.table});if(c){if(await J(e),this.sendPoke(e,[{reset:!0,rowsPatch:h,shapeId:t}],this.currentCdcCursor()??0,this.currentCdcEpoch(),void 0)){this.recordGlobalSnapshot(e,t,l),this.saveGlobalSnapshot(i,t,l);return}o.requestResync();return}if(h.length===0){this.recordGlobalSnapshot(e,t,l);return}if(await J(e),this.sendPoke(e,[{rowsPatch:h,shapeId:t}],this.currentCdcCursor()??0,this.currentCdcEpoch(),void 0)){this.recordGlobalSnapshot(e,t,l),this.saveGlobalSnapshot(i,t,l);return}o.requestResync()}readGlobalSnapshot(e,t,r){const s=this.globalShapeSnapshots.get(e)?.get(t);if(s)return{lost:!1,snapshot:s};const i=this.loadGlobalSnapshot(r,t),o=i??new Map;return this.recordGlobalSnapshot(e,t,o),{lost:i===void 0&&this.durableSnapshotStoreAvailable,snapshot:o}}recordGlobalSnapshot(e,t,r){Q(this.globalShapeSnapshots,e).set(t,r)}loadGlobalSnapshot(e,t){if(e!=="")try{const r=yo(this.sql,e,t);return this.durableSnapshotStoreAvailable=!0,r}catch{this.durableSnapshotStoreAvailable=!1;return}}saveGlobalSnapshot(e,t,r){if(e!=="")try{bo(this.sql,e,t,r),this.durableSnapshotStoreAvailable=!0}catch(s){(V(s)||this.durableSnapshotStoreAvailable)&&this.recordShapeError(`shape:snapshot:${t}`,s)}}async scheduleGlobalPoll(e,t=!1){const r=e??Date.now()+v.GLOBAL_SHAPE_POLL_INTERVAL_MS,s=this.globalPollArmedAt;if(!(s!==void 0&&s<=r)){this.globalPollArmedAt=r;try{await this.shardHost.alarms.set(r)}catch(i){if(this.globalPollArmedAt===r&&(this.globalPollArmedAt=s),t)throw i}}}scheduleBootstrapPoll(e){const t=this.globalPollArmedAt,r=Date.now(),s=e??r+v.GLOBAL_SHAPE_POLL_INTERVAL_MS;return t!==void 0&&t<=s?this.scheduleGlobalPoll(s):this.admitAlarmRearm(s,r,!1)?this.scheduleGlobalPoll(s):this.armRecoveryWake()}async armRecoveryWake(){const e=Date.now(),t=br(e),r=await Promise.resolve(this.shardHost.alarms.get()).catch(()=>{});typeof r=="number"&&r>e&&r<=t||await this.scheduleGlobalPoll(t)}admitAlarmRearm(e,t,r){const s=Kc(this.env);if(s===void 0)return!0;const i=Date.now(),o=e-t>=v.GLOBAL_SHAPE_POLL_INTERVAL_MS,{sql:a}=this.shardHost;let c,d;try{if(Gc(a),o)d=Wc(vr(a),i),c=r||d<s;else{const l=gr(vr(a),i,r?Number.POSITIVE_INFINITY:s);Qc(a,l.window),c=l.admitted,d=De(l.window,i)}}catch{return!0}return c?this.alarmRearmTripLogged=!1:this.alarmRearmTripLogged||(this.alarmRearmTripLogged=!0,this.recordAlarmRearmTrip(s,d)),c}recordAlarmRearmTrip(e,t){const r=`alarm re-arm breaker tripped: ${String(t)} re-arms in the last ${String(B)} ms (limit ${String(e)}). Re-arms are refused until the window drains, and a recovery wake is armed one window out. Tune with LUNORA_ALARM_REARM_LIMIT, or set it to 0 to disable.`;try{this.recordUserLog("alarm:rearm","error",[r],r,{limit:e,rearms:t,windowMs:B},this.lastTelemetrySink,"alarmRearmBreakerTripped"),this.recordMetric({functionPath:"alarm:rearm",kind:"counter",name:"shard.alarm_rearm.refused",ts:Date.now(),value:1},this.lastTelemetrySink)}catch{}}admitScheduleRate(e){const t=Cd(this.env);if(t===void 0)return;const{sql:r}=this.shardHost;let s;try{Od(r),s=gr(Md(r,e),Date.now(),t),Nd(r,e,s.window)}catch{return}if(s.admitted)return;const i=Date.now();return this.recordScheduleRateDeferral(e,t,De(s.window,i)),br(i)}recordScheduleRateDeferral(e,t,r){try{const s=Date.now();this.recordMetric({functionPath:"schedule:rate",kind:"counter",name:"shard.schedule_rate.deferred",ts:s,value:1},this.lastTelemetrySink);const i=this.scheduleRateTripLoggedAt.get(e);if(i!==void 0&&s-i<B)return;this.scheduleRateTripLoggedAt.set(e,s);const o=`schedule rate breaker tripped: ${e} was scheduled by ${String(r)} invocations in the last ${String(B)} ms (limit ${String(t)}). Its schedules are deferred one window, not dropped. Tune with LUNORA_SCHEDULE_RATE_LIMIT, or set it to 0 to disable.`;this.recordUserLog("schedule:rate","error",[o],o,{invocations:r,limit:t,target:e,windowMs:B},this.lastTelemetrySink,"scheduleRateBreakerTripped")}catch{}}nextTtlWake(e,t){const r=this.sql;let s;for(const i of e){const o=go(r,i);o!==void 0&&(s===void 0||o<s)&&(s=o)}return s===void 0?void 0:Math.max(s+1,t+Tl)}async armTtlSweepAfterWrite(e){if(this.replica!==void 0)return;const t=this.ttlSweeps().filter(s=>e.has(s.table));if(t.length===0)return;const r=this.nextTtlWake(t,Date.now());r!==void 0&&await this.scheduleBootstrapPoll(r)}async deleteExpiredTtlRow(e,t,r,s,i){const{table:o}=e;if(!vo(this.sql,e,t,r))return!1;try{return await this.runShardWrite({id:t,op:"delete",table:o},s),!1}catch(a){if(a instanceof p&&a.code==="TRANSACTION_LIMIT_EXCEEDED")return this.logs.push({functionPath:"ttl:sweep",level:"warn",message:`TTL sweep for "${o}" hit the transaction limit mid-batch; resuming next tick: ${a.message}`,timestamp:Date.now(),traceId:i?.traceId}),!0;throw a}}recordShapeError(e,t,r){this.logs.push({functionPath:e,level:"error",message:t instanceof Error?t.message:String(t),timestamp:Date.now(),traceId:r?.traceId})}withinGlobalShapeBound(e,t,r){return e<=v.GLOBAL_SHAPE_MAX_ROWS?!0:(this.recordShapeError(t,new Error(`global shape membership for "${r}" (${String(e)} rows) exceeds the ${String(v.GLOBAL_SHAPE_MAX_ROWS)}-row cap; narrow it with a shape predicate or an RLS read policy`)),!1)}globalCdcOptions(e){const t=Et(this.env,"LUNORA_GLOBAL_CDC_RETENTION_MS");return{cdc:e,...t===void 0?{}:{cdcRetentionMs:t}}}readGlobalChangedTables(e,t){return Promise.resolve(void 0)}shardRowExists(e,t){try{return this.sql.exec(`SELECT 1 FROM ${dt(e)} WHERE "id" = ? LIMIT 1`,t).toArray().length>0}catch{return}}polledGlobalTables(){return jr}globalTables(){return jr}preDispatchAnswer(e,t){if(t.functionPath.startsWith(M))return this.withAdminRequestScope(async()=>await this.handleAdminRpc(e,t.functionPath,t.args??{}));if(e.headers.get(ua)!==pa&&this.isPaidFunction(t.functionPath))return b({error:{code:"MISCONFIGURED",message:`paid (\`.x402\`) function "${t.functionPath}" reached the shard without passing the origin paywall, so nothing charged for it; an origin worker must be built with \`defineApp()\` (or passed \`functions\`) to read the \`.x402\` tag, and a server-side \`createShardClient\` caller must keep its default system privilege`}},500)}recordSchedulerLag(e,t,r){const s=e.headers.get(ka),i=s===null?Number.NaN:Number(s);!this.currentRequestSystem||!Number.isFinite(i)||this.recordMetric({attributes:{function:t},functionPath:t,kind:"histogram",name:"scheduler.lag_ms",shardKey:this.runner.shardKey,ts:r,value:Math.max(0,r-i)},this.lastTelemetrySink)}mintHeadroom(e,t,r){return new Kt(this.transactionLimits(),s=>{const i=`${e}\0${s.kind}`;r?.has(i)||(r?.add(i),this.recordUserLog(e,"warn",[],`transaction reached ${String(Math.round(s.used/s.limit*100))}% of its ${s.kind} limit (${String(s.used)} of ${String(s.limit)}); past it the transaction fails with TRANSACTION_LIMIT_EXCEEDED`,{...s},this.lastTelemetrySink,"lunora.transaction.near_limit",void 0,void 0,t))})}beginDispatch(e,t){this.currentDeliveryPermit=this.deliveryRequestPermits.get(e),this.currentRequestBookmark=e.headers.get("x-d1-bookmark")??void 0,this.currentResponseBookmark=void 0,this.currentRequestUserId=te(e.headers.get("x-lunora-userid")),this.currentRequestMutationId=e.headers.get("x-lunora-mutation-id")??void 0,this.currentRequestClientId=e.headers.get("x-lunora-client-id")??void 0,this.currentRequestClientSeq=Ec(e.headers.get("x-lunora-client-seq")),this.currentRequestBaselineSeq=gc(e.headers.get("x-lunora-base-seq")),this.currentMutatorClass=void 0,this.mutationBookkeeping=void 0,this.currentRequestIdentity=we(e.headers.get("x-lunora-identity")),this.currentRequestIp=e.headers.get("x-lunora-client-ip")??void 0,this.currentRequestOrigin=e.headers.get("x-lunora-origin")??void 0,this.currentRequestSystem=e.headers.get("x-lunora-system")==="1",this.currentRequestTraceparent=e.headers.get("traceparent")??void 0,this.currentRequestSampleErrors=vc(e.headers.get(Ta)),this.currentRequestTrace=be(this.currentRequestTraceparent,e.headers.get(ya));const r=this.currentRequestTrace;this.traceSampling.set(r.traceId,{keepErrors:this.currentRequestSampleErrors??!0,sampled:ma(this.currentRequestTraceparent)?.sampled??!0}),this.metrics.requests+=1;const s=Date.now(),i=new Set;this.currentScannedTables=i;const o=this.mintHeadroom(t,{trace:r,userId:this.getCurrentUserId()}),a=new Set;this.currentIndexHits=a;const c=new Map;return this.currentStmtSamples=c,this.currentStmtSamplesTruncated=void 0,{dispatchAttribution:{},dispatchBookmark:{value:void 0},dispatchCollectors:{indexHits:a,scannedTables:i,stmtSamples:c},dispatchHeadroom:o,dispatchStartedAt:s,dispatchTrace:r}}endDispatch(e){this.currentDeliveryPermit=void 0,this.currentRequestTrace=void 0,this.currentRequestBookmark=void 0,this.currentResponseBookmark=void 0,this.currentRequestUserId=void 0,this.currentRequestMutationId=void 0,this.currentRequestClientId=void 0,this.currentRequestClientSeq=void 0,this.currentRequestBaselineSeq=void 0,this.currentMutatorClass=void 0,this.mutationBookkeeping=void 0,this.currentRequestIdentity=void 0,this.currentRequestIp=void 0,this.currentRequestOrigin=void 0,this.currentRequestSampleErrors=void 0,this.currentRequestSystem=!1,this.currentRequestTraceparent=void 0,this.currentScannedTables===e.scannedTables&&(this.currentScannedTables=void 0),this.currentIndexHits===e.indexHits&&(this.currentIndexHits=void 0),this.currentStmtSamples===e.stmtSamples&&(this.currentStmtSamples=void 0,this.currentStmtSamplesTruncated=void 0),this.instrumentedSql?.samples===e.stmtSamples&&(this.instrumentedSql=void 0)}async openGlobalPollTick(e){const t=Date.now(),r=this.globalResyncRequested||t-this.lastGlobalResyncAt>=v.GLOBAL_SHAPE_RESYNC_MS;this.globalResyncRequested=!1,r&&(this.lastGlobalResyncAt=t);const s=this.globalPollCursor===void 0||r;try{const i=await this.readGlobalChangedTables(this.globalPollCursor??0,s);if(i===void 0)return{bookmark:void 0,tables:void 0,tick:new Qe,visible:!1};const o=ge(i.floor,this.globalPollCursor??0);this.globalPollCursor=i.cursor;const a=s||o?void 0:new Set(i.tables);return{bookmark:i.bookmark,tables:a,tick:new Qe(a),visible:!0}}catch(i){return this.recordShapeError("shape:poll:cdc",i,e),{bookmark:void 0,tables:void 0,tick:new Qe,visible:!1}}}async readGlobalShapeRowsCached(e,t,r){return r.rows(Eo(e,t),async()=>this.readGlobalShapeRows(e,t))}async pollGlobalShapes(e){const t=this.countGlobalQueryReaders();if(this.deliveryAuthorization){const c=this.rejectRetainedShapesAndRooms();return t>0&&await this.refreshFromGlobalPoll(await this.openGlobalPollTick(e)),c+t}const r=[...this.runner.sockets()];let s=0;const i=[];for(const c of r){const d=this.readAttachment(c);this.dropIfLapsed(c,d)||d.shapes&&i.push({attachment:d,ws:c})}if(i.length===0&&t===0)return 0;const o=await this.openGlobalPollTick(e),{tick:a}=o;for(const{attachment:c,ws:d}of i){const l=O(c);s+=await this.pollSocketGlobalShapes(d,c.shapes??{},l,c.connectionId??"",a,e)}return this.globalPoll=Ro(this.globalPoll,a.readCount,a.skipped),this.globalResyncRequested=a.resyncRequested,t>0&&await this.refreshFromGlobalPoll(o),s+t}countGlobalQueryReaders(){const e=this.polledGlobalTables();if(e.size===0)return 0;let t=0;for(const r of this.runner.sockets()){const s=this.unrecordedQueries.get(r);for(const[i,o]of Object.entries(this.readAttachment(r).subs)){if(!o.functionPath||o.functionPath.startsWith(M)||o.functionPath.startsWith(Re))continue;const a=this.socketIndex.memo(r,i);(a===void 0?s?.has(i)!==!0:xe(a.tables,e))&&(t+=1)}}return t}async watchGlobalReads(e,t){if(xe(t,this.polledGlobalTables())){await this.scheduleGlobalPoll();return}this.warnIfGlobalReadUnpolled(e,t)}noteUnrecordedQuery(e,t){let r=this.unrecordedQueries.get(e);r===void 0&&(r=new Set,this.unrecordedQueries.set(e,r)),r.add(t)}warnIfGlobalReadUnpolled(e,t){if(this.warnedUnpolledGlobalRead||this.polledGlobalTables().size>0)return;const r=[...t].filter(s=>this.globalTables().has(s));r.length!==0&&(this.warnedUnpolledGlobalRead=!0,this.logs.push({functionPath:e,level:"warn",message:`live query reads .global() table(s) ${r.join(", ")}, but CDC is off: a write to them on another shard will not refresh it. Call .cdc() on the app to turn on the global changelog.`,timestamp:Date.now()}))}async refreshFromGlobalPoll(e){if(!e.visible){const s=Date.now();if(this.lastBlindRefreshAt!==void 0&&s-this.lastBlindRefreshAt<v.GLOBAL_SHAPE_RESYNC_MS)return;this.lastBlindRefreshAt=s,this.logs.push({functionPath:"global:poll",level:"warn",message:"the global changelog could not be read, so live queries on .global() tables re-run at the primary once per resync interval until it can",timestamp:s})}const t=this.polledGlobalTables(),r=new Set([...e.visible?e.tables??t:t].filter(s=>t.has(s)));if(r.size!==0){for(const s of r)this.reactiveCache?.invalidateTable(s);this.mergeSubscriptionRefresh(r,void 0,new Set([e.bookmark??vt])),await this.startSubscriptionRefresh()}}async pollSocketGlobalShapes(e,t,r,s,i,o){let a=0;for(const[c,d]of Object.entries(t)){let l;try{l=this.resolveShape(d.name,structuredClone(d.args??{}),r)}catch(h){a+=1,this.recordShapeError(`shape:poll:${c}`,h,o);continue}if(l?.global&&(a+=1,!!i.shouldRead(l.table)))try{await this.refreshGlobalShape(e,c,l,r,s,i)}catch(h){i.requestResync(),this.recordShapeError(`shape:poll:${c}`,h,o)}}return a}sendPoke(e,t,r,s,i){if(this.dropIfLapsed(e))return!1;this.pokeSequence+=1;const o=`poke-${String(this.pokeSequence)}`,a=Ao(t,{baseCheckpoint:i,checkpoint:r,epoch:s,lastMutationId:this.socketClientWatermark(this.readAttachment(e)),pokeId:o});try{for(const c of a)if(!this.sendFrame(e,c))return!1;return!0}catch{return!1}}socketClientWatermark(e){const{clientId:t}=e;if(t!==void 0)try{return $e(this.sql,e.userId??"",t)}catch{return}}recordShapeMemo(e,t,r,s,i){const{carriedRows:o}=i,a=Q(this.shapeMemos,e),c=o?s:a.get(r)?.delivered;a.set(r,{cursor:s,...c===void 0?{}:{delivered:c}}),i.pending===void 0?this.saveShapePokeCursor(t,r,s):t!==""&&i.pending.push({connectionId:t,cursor:s,subId:r})}markShapeOwed(e,t){const r=this.shapeMemos.get(e)?.get(t);r!==void 0&&(r.owed=!0)}readShapeMemoCursor(e,t,r,s){const i=this.shapeMemos.get(e)?.get(r)?.cursor;if(i!==void 0)return i;const a=this.loadShapePokeCursor(t,r)??s??0,c=a>(this.currentCdcCursor()??0)?0:a;return Q(this.shapeMemos,e).set(r,{cursor:c}),c}loadShapePokeCursor(e,t){if(e!=="")try{return wo(this.sql,e,t)}catch{return}}saveShapePokeCursor(e,t,r){if(e!=="")try{To(this.sql,e,t,r)}catch{}}encodeOutcome(e){let t=this.encodedOutcomes.get(e);return t===void 0&&(t=JSON.stringify(D(e.result??null)),this.encodedOutcomes.set(e,t)),t}assertResultWithinLimit(e){const t=Jt(this.env,"LUNORA_SUBSCRIPTION_MAX_RESULT_CHARS",pl);if(e.length>t)throw new p("SUBSCRIPTION_RESULT_TOO_LARGE",`subscription result is ${String(e.length)} characters, over the ${String(t)}-character limit; narrow or paginate the query`,{status:413})}boundedBaseline(e,t,r){let s=r.length;for(const[i,o]of e??[])i!==t&&o.lastJson!==ne&&(s+=o.lastJson.length);return s>Jt(this.env,"LUNORA_SUBSCRIPTION_MEMO_MAX_CHARS",fl)?ne:r}seedSubscriptionMemo(e,t,r,s){const i=this.socketIndex.socketMemos(e);if((i?.get(t)?.generation??-1)>s)return;const o=this.encodeOutcome(r);this.assertResultWithinLimit(o),this.socketIndex.setMemo(e,t,{generation:s,lastJson:this.boundedBaseline(i,t,o),ranges:r.ranges,tables:r.tables}),this.persistSubscriptionTables(e,t)}liftRefusedMark(e,t){return!t||!this.tableSetsRefused.delete(e)?()=>{}:()=>{this.tableSetsRefused.add(e)}}markTableSetsRefused(e){this.tableSetsRefused.add(e),this.tableSetsRefusedWarned||(this.tableSetsRefusedWarned=!0,console.warn(`[@lunora/do] a socket's attachment is at the ${String(v.MAX_ATTACHMENT_BYTES)}-byte limit and cannot hold its live queries' table sets; they will re-run after each hibernation wake until it holds fewer or smaller subscriptions.`))}dropSubscriptionTables(e,t){if(Me(this.readAttachment(e).subTables,t)===void 0)return;const r=this.readAttachmentCopy(e);ie(r.subTables,t);try{this.writeAttachment(e,r)}catch{}}persistSubscriptionTables(e,t){const r=this.readAttachment(e);if(!Object.hasOwn(r.subs,t))return;const s=Me(r.subTables,t),i=this.socketIndex.memo(e,t);if(i===void 0||i.retryData===!0||i.tables.has(_)){this.dropSubscriptionTables(e,t);return}if(s!==void 0&&[...i.tables].every(a=>s.includes(a)))return;if(this.tableSetsRefused.has(e)){this.dropSubscriptionTables(e,t);return}const o=this.readAttachmentCopy(e);o.subTables={...o.subTables,[t]:[...new Set([...s??[],...i.tables])]};try{this.writeAttachment(e,o,{shedTableSets:!1})}catch{this.markTableSetsRefused(e),this.dropSubscriptionTables(e,t)}}pushSubscriptionData(e,t,r,s,i,o){if(this.dropIfLapsed(e)||!this.allowsSubscriptionOutcome(e,t,o,s.generation))return;const a=this.socketIndex.memo(e,t),{cursor:c,epoch:d,generation:l}=s,h=Xe(c,d),{clientWatermark:u,pageDeltas:m}=i,S=this.encodeOutcome(r);if(this.assertResultWithinLimit(S),a?.lastJson===S){if(!this.sendSubscriptionSettlement(e,t,s,i,o)&&this.deliveryAuthorization)return;a.generation=l,a.retryData=!1,this.socketIndex.retable(e,t,r.tables),this.persistSubscriptionTables(e,t),a.ranges=r.ranges;return}const g=ko({cursorSuffix:h,diffKey:r,lastMutationId:u,nextResult:r.result,pageDeltas:m,previousJson:a?.lastJson,snapshotJson:S,subId:t,table:_o(r.tables)}).map(y=>this.sendFrame(e,y,{subId:t,permit:o})).every(Boolean),R=this.deliveryAuthorization!==void 0&&!g;R&&a!==void 0&&this.socketIndex.memo(e,t)===a&&(a.retryData=!0,this.persistSubscriptionTables(e,t)),!R&&(this.socketIndex.setMemo(e,t,{cursor:g?c:a?.cursor,epoch:g?d:a?.epoch,clientWatermark:g?u:a?.clientWatermark,generation:g?l:a?.generation??l,lastJson:g?this.boundedBaseline(this.socketIndex.socketMemos(e),t,S):a?.lastJson??ne,ranges:r.ranges,tables:r.tables}),this.persistSubscriptionTables(e,t))}sendSubscriptionSettlement(e,t,r,s,i,o=!1){const a=this.socketIndex.memo(e,t);if(a===void 0||!this.allowsSubscriptionOutcome(e,t,i,r.generation)||this.dropIfLapsed(e)||o&&(r.cursor===void 0||r.cursor===a.cursor&&r.epoch===a.epoch)&&(s.clientWatermark===void 0||s.clientWatermark<=(a.clientWatermark??0)))return!1;const c=s.clientWatermark===void 0?"":`,"lastMutationId":${String(s.clientWatermark)}`,d=`{"type":"settled","id":${JSON.stringify(t)}${c}${Xe(r.cursor,r.epoch)}}`;return this.sendFrame(e,d,{subId:t,permit:i})?(a.cursor=r.cursor,a.epoch=r.epoch,a.clientWatermark=s.clientWatermark,a.generation=r.generation,!0):!1}allowsSubscriptionOutcome(e,t,r,s){if(this.deliveryAuthorization&&r!==void 0&&this.subscriptionRegistrations.get(e)?.get(t)!==r.registration)return!1;if(this.deliveryAuthorization&&!this.deliveryFence.allows(r))return this.revokeSubscription(e,t),!1;const i=this.socketIndex.memo(e,t);return i===void 0||s>=i.generation}isUpgradeAllowed(e,t,r){const s=this.env??{},i=s.LUNORA_ALLOWED_ORIGINS;if(i&&i.trim()!==""){const d=e.headers.get("origin");if(!d)return!1;const l=new Set(i.split(",").map(h=>h.trim()).filter(h=>h.length>0));if(!l.has("*")&&!l.has(d))return!1}const o=new URL(e.url).searchParams.getAll("token"),a=[s.LUNORA_ADMIN_TOKEN,s.LUNORA_WS_BEARER];return!o.some(d=>a.some(l=>l!==void 0&&l.length>0&&le(d,l)))&&(!t||r)}async isUpgradeAuthenticated(e){const t=(this.env??{}).LUNORA_WS_BEARER;if(t===void 0||t.length===0)return!0;const r=Ye(e.headers.get("authorization"));return r!==void 0&&le(r,t)?!0:this.isAdminSocket(e)}async isAdminSocket(e){const t=(this.env??{}).LUNORA_ADMIN_TOKEN;if(!t||t.length===0)return!1;const r=Ye(e.headers.get("authorization")),s=new URL(e.url).searchParams.get("token")??void 0;for(const i of[r,s])if(i!==void 0&&await Ca(t,i))return!0;return r!==void 0&&le(r,t)}async currentAdminBinding(){const e=this.env?.LUNORA_ADMIN_TOKEN;if(!(e===void 0||e.length===0))return this.adminBindingMemo?.token!==e&&(this.adminBindingMemo={binding:Ma(e),token:e}),this.adminBindingMemo.binding}async attachmentAdminAuthorized(e){if(e.admin!==!0)return!1;const t=await this.currentAdminBinding();return t!==void 0&&e.adminBinding===t}armWebSocketKeepalive(){const e=this.state.setWebSocketAutoResponse;typeof e!="function"||typeof WebSocketRequestResponsePair>"u"||e.call(this.state,new WebSocketRequestResponsePair(sl,il))}async routeLive(e,t){if(e.pathname===ia&&t.method==="GET")return this.handleLiveConnect(t);if(e.pathname===na&&t.method==="POST")return this.handleLiveControl(t);if(e.pathname===oa&&t.method==="POST")return this.handleLivePublish(t);if(e.pathname===ar&&t.method==="POST")return this.handleSocketReauth(t)}async handleSocketReauth(e){let t;try{t=await e.json()}catch{return b({error:{code:"BAD_REQUEST",message:"invalid JSON body"}},400)}if(typeof t?.connectionId!="string"||t.connectionId.length===0||t.connectionId.length>oe)return b({error:{code:"BAD_REQUEST",message:"connectionId is required"}},400);const r=we(e.headers.get("x-lunora-identity")),s=he(e.headers.get("x-lunora-identity-exp"));return this.handleLiveSocketControl({action:"reauth",...e.headers.get("x-lunora-admin-reauth")==="1"?{adminReauth:!0}:{},callerId:te(e.headers.get("x-lunora-userid"))??"",connectionId:t.connectionId,...r===void 0?{}:{identity:r},...s===void 0?{}:{identityExpiry:s},key:"",subscriptionId:""})}async reauthenticateAdminSocket(e,t){const r=this.readAttachment(e);return t.adminReauth!==!0||!await this.attachmentAdminAuthorized(r)?(this.dropLapsedSocket(e,re,"identity_stale"),b({error:{code:"IDENTITY_STALE",message:"the admin credential no longer holds; reconnect"}},409)):r.userId===void 0?b({ok:!0}):(r.userId??"")!==t.callerId||Ie(r.identity)!==Ie(t.identity)?(this.dropLapsedSocket(e,re,cr),b({error:{code:"IDENTITY_CHANGED",message:"the user on this admin socket changed; reconnect"}},409)):this.reauthenticateSocket(e,t)}reauthenticateSocket(e,t){const r=this.readAttachment(e),{identity:s,identityExpiry:i}=t;if(ue(r.revalidateAt))return this.dropLapsedSocket(e,re,"identity_stale"),b({error:{code:"IDENTITY_STALE",message:"the socket's revalidation window passed; reconnect"}},409);if(t.callerId==="")return b({error:{code:"UNAUTHENTICATED",message:"an anonymous socket has no credential to refresh"}},401);if(ue(i))return b({error:{code:"TOKEN_EXPIRED",message:"authentication token expired"}},401);if(Ie(r.identity)!==Ie(s))return this.dropLapsedSocket(e,re,cr),b({error:{code:"IDENTITY_CHANGED",message:"the credential's claims differ from the socket's; reconnect"}},409);if(r.expiresAt!==void 0&&(i===void 0||i<r.expiresAt))return b({error:{code:"STALE_CREDENTIAL",message:"the socket already holds a later credential"}},409);const o={...r};i===void 0?delete o.expiresAt:o.expiresAt=i,s===void 0?delete o.identity:o.identity=s,r.revalidateAt!==void 0&&(o.revalidateAt=Date.now()+mt);try{this.writeAttachment(e,o)}catch{return b({error:{code:"SUBSCRIPTION_PERSIST_FAILED",message:"the socket attachment could not be updated; reconnect"}},409)}return b({ok:!0})}async routeNonRpc(e,t){if(e.pathname==="/_lunora/relay"&&t.method==="POST")return this.relay?await this.relay.handleControl(t):new Response("relay tier inactive",{status:404});if(e.pathname==="/_lunora/replica"&&t.method==="POST")return Io(this.replicaOwnerHost,t);if(e.pathname==="/_lunora/route"&&t.method==="GET")return b({relayCount:this.relay?.relayCount()??0});if(e.pathname==="/rpc-batch"&&t.method==="POST")return this.handleBatchRpc(t);if(t.headers.get("Upgrade")?.toLowerCase()==="websocket")return this.handleWebSocketUpgrade(t);const r=await this.routeLive(e,t);if(r!==void 0)return r}async handleWebSocketUpgrade(e){if(this.replica!==void 0)return new Response("replica does not serve subscriptions",{status:421});const t=new URL(e.url),r=this.socketRoute(t.pathname),s=await this.isUpgradeAuthenticated(e);if(!this.isUpgradeAllowed(e,r!==void 0,s))return new Response("Forbidden",{status:403});const i=te(e.headers.get("x-lunora-userid")),o=we(e.headers.get("x-lunora-identity")),a=he(e.headers.get("x-lunora-identity-exp")),c=e.headers.get("x-lunora-client-ip")??void 0,d=r===void 0?void 0:this.refuseRouteUpgrade(r,i,a);if(d!==void 0)return d;const l=await this.isAdminSocket(e),h=Date.now();if(!this.admitPendingSocket(h,s))return new Response("Service Unavailable",{status:503});const{client:u,server:m}=this.socketHost.newPair(),S=l?await this.currentAdminBinding():void 0,E=r===void 0?void 0:`${z}${r.functionPath}`,g=Ea(crypto.randomUUID(),pt(this.runner.shardKey??"")?.relayIndex),R=this.socketHost.accept(m,{admin:l,connectionId:g,subs:{},...al(s,h),...S===void 0?{}:{adminBinding:S},...a===void 0?{}:{expiresAt:a},...o===void 0?{}:{identity:o},...c===void 0?{}:{ip:c},...Kr(r,i,h),...r===void 0?{}:{socketFunction:r.functionPath,socketPath:t.pathname},...E===void 0?{}:{whispers:[E]},...i===void 0?{}:{userId:i}});if(this.liveSocketsByConnection.set(g,R),r!==void 0){const y=this.dispatchSocketEvent(R,{functionPath:r.functionPath,path:t.pathname},"open").catch(()=>{});this.shardHost.waitUntil?.(y),this.relay?.announce().catch(()=>{})}return this.socketHost.upgradeResponse(u)}refuseRouteUpgrade(e,t,r){if(e.auth&&t===void 0)return new Response("Unauthorized",{status:401});if(t===void 0||!ue(r))return;const{client:s,server:i}=this.socketHost.newPair();return ir(this.socketHost.accept(i,{...r===void 0?{}:{expiresAt:r},subs:{}})),this.socketHost.upgradeResponse(s)}dropIfLapsed(e,t=this.readAttachment(e),r=Date.now()){const{expiresAt:s,revalidateAt:i}=t;if(s===void 0&&i===void 0&&t.userId===void 0)return!1;if(typeof s=="number"&&r>=s)return this.dropLapsedSocket(e,4001,"token_expired"),!0;if(typeof i=="number"&&r>=i)return this.dropLapsedSocket(e,re,"identity_stale"),!0;if(t.revalidateAt===void 0&&t.userId!==void 0&&t.socketPath===void 0&&t.socketFunction===void 0){Object.assign(t,Kr(void 0,t.userId,r));try{this.writeAttachment(e,t)}catch{return this.dropLapsedSocket(e,re,"identity_stale"),!0}}return!1}resumesUnderCurrentClaims(e,t,r){const{identity:s,userId:i}=this.readAttachment(e);return t!==void 0&&t===Ve(i,s)&&(r===void 0||!this.ipKeyedFunctionPaths.has(r))}dropLapsedSocket(e,t,r){const s=this.webSocketClose(e,t,r,!0).catch(i=>{console.error("[@lunora/do] lapsed-socket teardown failed:",i)});if(this.shardHost.waitUntil?.(s),t===4001){ir(e);return}try{e.close?.(t,r)}catch{}}routeOfSocket(e){if(e.socketPath===void 0)return;const t=this.socketRoute(e.socketPath);if(!(t===void 0||t.functionPath!==e.socketFunction))return{auth:t.auth,functionPath:t.functionPath,path:e.socketPath}}async authorizeWhisper(e,t,r){if(this.relay instanceof je&&this.roomHandlerPath(t)!==void 0)return!0;const s=this.lifecycleHookPaths("whisper");if(s.length===0)return!0;if(r==="send"&&this.roomHandlerPath(t)!==void 0)return this.runWhisperAuthorizers(s,e,t,r);const i=`${r}:${t}`;let o=this.whisperVerdicts.get(e);const a=o?.get(i);if(a!==void 0)return await a;if(o!==void 0&&o.size>=v.MAX_WHISPER_VERDICTS_PER_SOCKET){const l=`whisper authorization cap of ${String(v.MAX_WHISPER_VERDICTS_PER_SOCKET)} distinct topics reached on this socket; reconnect to reset it`;return this.sendFrame(e,JSON.stringify({code:"TOO_MANY_WHISPER_TOPICS",error:{code:"TOO_MANY_WHISPER_TOPICS",message:l},type:"error"}),"control"),!1}o||(o=new Map,this.whisperVerdicts.set(e,o));const c=this.runWhisperAuthorizers(s,e,t,r);o.set(i,c);let d;try{d=await c}catch(l){throw o.delete(i),l}return o.set(i,d),d}async runWhisperAuthorizers(e,t,r,s){const i=this.lifecycleInfo(this.readAttachment(t)),o={...i.event,action:s,topic:r};let a=!0;for(const c of e){const d=o;if(await this.withSensitiveScope(c,d,async h=>{try{return await this.withRequestIdentity(i.userId,i.identity,i.ip,()=>this.withSystemDispatch(()=>this.handleRpc(c,d,void 0,void 0,void 0,h)))}catch(u){return this.logs.push({functionPath:c,level:"error",message:h.text(u instanceof Error?u.message:String(u)),timestamp:Date.now()}),!1}})!==!0){a=!1;break}}return await this.flushAfterDispatch("whisper:flush"),a}rejectRetainedRooms(e){if(!this.deliveryAuthorization||!this.retainedRoomsNeedCleanup)return 0;const t=new Set(this.runner.sockets());e!==void 0&&t.add(e);let r=0;for(const s of t){for(const i of this.readAttachment(s).whispers??[]){const o=j;this.sendFrame(s,JSON.stringify({type:"error",code:"NOT_IMPLEMENTED",error:{code:"NOT_IMPLEMENTED",message:o},topic:i}),"control"),this.setWhisperMembership(s,i,!1)&&(this.whisperVerdicts.get(s)?.delete(`subscribe:${i}`),this.whisperVerdicts.get(s)?.delete(`send:${i}`))}r+=this.readAttachment(s).whispers?.length??0}return this.retainedRoomsNeedCleanup=r>0,r}setWhisperMembership(e,t,r){const s=this.readAttachmentCopy(e),i=s.whispers??[],o=i.includes(t);if(r){if(o||i.length>=v.MAX_WHISPER_TOPICS_PER_SOCKET)return!1;s.whispers=[...i,t]}else{if(!o)return!1;const c=i.filter(d=>d!==t);c.length===0?delete s.whispers:s.whispers=c}try{this.writeAttachment(e,s)}catch{return!1}const a=this.membershipEpochs.get(e)??new Map;return a.set(t,this.membershipEpoch(e,t)+1),this.membershipEpochs.set(e,a),!0}isWhisperMember(e,t){return(this.readAttachment(e).whispers??[]).includes(t)}allowWhisper(e){return Jr(e,this.whisperBuckets,v.WHISPER_RATE_BURST,v.WHISPER_RATE_PER_SEC)}allowRoomJoin(e){return Jr(e,this.roomJoinBuckets,v.WHISPER_RATE_BURST,v.WHISPER_RATE_PER_SEC)}fitsWhisperCap(e){const t=JSON.stringify(e??null);return new TextEncoder().encode(t).byteLength<=v.MAX_WHISPER_BYTES}membershipEpoch(e,t){return this.membershipEpochs.get(e)?.get(t)??0}async broadcastWhisper(e,t,r){if(this.deliveryAuthorization){this.rejectRetainedRooms();return}if(!this.allowWhisper(e))return;const s=JSON.stringify(r??null);if(s.length>v.MAX_WHISPER_BYTES)return;const i=this.readAttachment(e).userId,o=i===void 0?"":`,"from":${JSON.stringify(i)}`,a=`{"type":"whisper","topic":${JSON.stringify(t)},"data":${s}${o}}`;this.deliverWhisperLocal(t,a,e),await this.relay?.forwardWhisper(t,a)}socketMayReceiveRouteTopic(e,t){if(!t.startsWith(z))return!0;if(e.socketPath===void 0)return!1;const r=this.socketRoute(e.socketPath);return r===void 0||`${z}${r.functionPath}`!==t?!1:!r.auth||e.userId!==void 0}deliverWhisperLocal(e,t,r){if(this.deliveryAuthorization)return this.rejectRetainedRooms(),0;let s=0,i=0;const o=e.startsWith(z),a=Date.now();for(const c of this.runner.sockets()){if(s+=1,c===r)continue;const d=this.readAttachment(c);d.whispers?.includes(e)===!0&&(o&&!this.socketMayReceiveRouteTopic(d,e)||(this.pendingRoomJoins.get(c)?.get(e)??0)>0||this.dropIfLapsed(c,d,a)||this.sendFrame(c,t)&&(i+=1))}return this.fanout.whisper=Ge(this.fanout.whisper,s,i,0),i}async handleSocketRouteFrame(e,t,r){const s=this.routeOfSocket(t);if(s===void 0||s.auth&&t.userId===void 0||!this.allowWhisper(e))return;let i;try{i=JSON.parse(r)}catch(o){this.logs.push({functionPath:s.functionPath,level:"error",message:`socket frame dropped: invalid JSON (${o instanceof Error?o.message:String(o)})`,timestamp:Date.now()});return}await this.dispatchSocketEvent(e,{functionPath:s.functionPath,path:s.path},"message",i)}async dispatchCloseHooks(e,t){if(t.socketPath!==void 0){const r=this.routeOfSocket(t);r!==void 0&&!this.routeCloseSent.has(e)&&(this.routeCloseSent.add(e),await this.dispatchSocketEvent(e,{functionPath:r.functionPath,path:r.path},"close"))}else t.connectionId!==void 0&&t.authenticated!==!1&&await this.dispatchLifecycle("disconnect",this.lifecycleInfo(t))}dispatchSocketEvent(e,t,r,s){if(this.deliveryAuthorization)return Promise.resolve();const i=this.queuedSocketEvents.get(e)??0;if(r==="message"&&i>=v.MAX_QUEUED_SOCKET_EVENTS)return this.logs.push({functionPath:t.functionPath,level:"error",message:"socket frame refused: this socket already has the maximum number of frames queued",timestamp:Date.now()}),Promise.resolve();this.queuedSocketEvents.set(e,i+1);const o=this.lifecycleInfo(this.readAttachment(e)),c=(this.roomChains.get(e)??Promise.resolve()).then(()=>this.runSocketEvent(e,t,r,o,s)),d=()=>{this.queuedSocketEvents.set(e,(this.queuedSocketEvents.get(e)??1)-1)};return this.roomChains.set(e,c.finally(d).then(()=>{},()=>{})),c}async runSocketEvent(e,t,r,s,i){const o=`${z}${t.functionPath}`,a=[],c={broadcast:l=>{const h=xr(o,l);a.push(()=>{this.broadcastSocketMessage(o,h)})},connectionId:s.event.connectionId,path:t.path,send:l=>{const h=xr(o,l);a.push(()=>{N(e,h)})},shardKey:s.event.shardKey,userId:s.event.userId};let d;try{const l={kind:r,socket:c,...r==="message"?{message:F(i)}:{}};d=this.openSensitiveScope(t.functionPath,l);const h=d;await this.withRequestIdentity(s.userId,s.identity,s.ip,()=>this.withSystemDispatch(()=>this.handleRpc(t.functionPath,l,void 0,void 0,void 0,h)))}catch(l){if(!this.absorbCommittedFailure(t.functionPath,l,d)){const h=l instanceof Error?l.message:String(l);this.logs.push({functionPath:t.functionPath,level:"error",message:d?.text(h)??h,timestamp:Date.now()}),d?.clear(),await this.flushAfterDispatch(`socket:${t.functionPath}:flush`);return}}finally{d?.clear()}for(const l of a)try{l()}catch(h){this.logs.push({functionPath:t.functionPath,level:"error",message:h instanceof Error?h.message:String(h),timestamp:Date.now()})}await this.flushAfterDispatch(`socket:${t.functionPath}:flush`)}broadcastSocketMessage(e,t){const{byteLength:r}=new TextEncoder().encode(t);if(r>v.MAX_WHISPER_BYTES)throw new p("PAYLOAD_TOO_LARGE",`route broadcast is ${String(r)} bytes, over the ${String(v.MAX_WHISPER_BYTES)}-byte limit`);this.deliverWhisperLocal(e,t,void 0);const{relay:s}=this;s&&s.forwardWhisper(e,t).catch(i=>{console.error("[@lunora/do] socket route broadcast relay failed:",i)})}dispatchRoomEvent(e,t,r,s,i,o){const a=this.roomHandlerPath(t);if(a===void 0)return Promise.resolve(!0);const c=this.queuedRoomEvents.get(e)??0;if(r!=="leave"&&c>=v.MAX_QUEUED_ROOM_EVENTS)return this.logs.push({functionPath:a,level:"error",message:"room event refused: this socket already has the maximum number of room events queued",timestamp:Date.now()}),r==="join"&&this.rollBackJoin(e,t,i),Promise.resolve(!1);this.queuedRoomEvents.set(e,c+1);const l=(this.roomChains.get(e)??Promise.resolve()).then(()=>this.runRoomHandler(e,t,a,r,s,i,o)).catch(u=>this.refuseRoomEvent(e,t,a,r,i,u)),h=()=>{this.queuedRoomEvents.set(e,(this.queuedRoomEvents.get(e)??1)-1)};return this.roomChains.set(e,l.finally(h).then(()=>{},()=>{})),l}acknowledgeLiveJoin(e,t){this.roomHandlerPath(t)===void 0&&N(e,JSON.stringify({topic:t,type:"whisper_subscribed"}))}async dispatchSettlingJoin(e,t,r,s){if(!r||this.roomHandlerPath(t)===void 0)return this.dispatchRoomEvent(e,t,r?"join":"leave",void 0,s);const i=this.pendingRoomJoins.get(e)??new Map;this.pendingRoomJoins.set(e,i),i.set(t,(i.get(t)??0)+1);try{return await this.dispatchRoomEvent(e,t,"join",void 0,s)}finally{const o=(i.get(t)??1)-1;o>0?i.set(t,o):i.delete(t)}}absorbCommittedFailure(e,t,r){if(!Il(t))return!1;const s=t instanceof Error?t.message:String(t);return this.logs.push({functionPath:e,level:"error",message:r?.text(s)??s,timestamp:Date.now()}),!0}refuseRoomEvent(e,t,r,s,i,o,a){const c=o instanceof Error?o.message:String(o);if(this.logs.push({functionPath:r,level:"error",message:a?.text(c)??c,timestamp:Date.now()}),s==="join"){this.rollBackJoin(e,t,i);const d=this.failedRoomJoins.get(e)??new Set;d.add(t),this.failedRoomJoins.set(e,d)}return!1}rollBackJoin(e,t,r){r===this.membershipEpoch(e,t)&&this.setWhisperMembership(e,t,!1)}skipsQueuedRoomEvent(e,t,r,s){return r==="message"?!this.isWhisperMember(e,t)||this.membershipEpoch(e,t)!==s:r==="leave"&&this.failedRoomJoins.get(e)?.delete(t)===!0}async runRelayedRoomEvent(e,t,r,s,i,o,a){return await this.forwardRoomEvent(e,t,s,i,a)?(s==="join"&&this.failedRoomJoins.get(e)?.delete(t),!0):this.refuseRoomEvent(e,t,r,s,o,new p("INTERNAL","the shard owner refused the room event"))}async runRoomHandler(e,t,r,s,i,o,a){if(this.deliveryAuthorization)return this.rejectRetainedRooms(e),!1;if(s!=="leave"&&this.roomSenderLapsed(e))return!1;if(this.skipsQueuedRoomEvent(e,t,s,o))return!0;if(this.relay instanceof je)return this.runRelayedRoomEvent(e,t,r,s,i,o,a);const c=this.lifecycleInfo(a??this.readAttachment(e)),d=[],l={broadcast:m=>{d.push(m)},connectionId:c.event.connectionId,...c.event.context===void 0?{}:{context:c.event.context},shardKey:c.event.shardKey,userId:c.event.userId},h={kind:s,socket:l,...s==="message"?{message:F(i)}:{}},u=await this.withSensitiveScope(r,h,async m=>{try{return await this.withRequestIdentity(c.userId,c.identity,c.ip,()=>this.withSystemDispatch(()=>this.handleRpc(r,h,void 0,void 0,void 0,m))),!0}catch(S){return this.absorbCommittedFailure(r,S,m)?!0:this.refuseRoomEvent(e,t,r,s,o,S,m)}});return await this.flushAfterDispatch(`room:${r}:flush`),!u||(s==="join"&&this.failedRoomJoins.get(e)?.delete(t),s!=="leave"&&this.roomSenderLapsed(e))?!1:(this.broadcastPending(e,t,r,s,d),!0)}roomSenderLapsed(e){const t=this.readAttachment(e);return!ue(t.expiresAt)&&!ue(t.revalidateAt)?!1:(typeof e.close=="function"&&this.dropIfLapsed(e,t),!0)}broadcastPending(e,t,r,s,i){for(const o of i)try{this.broadcastRoomMessage(t,o,s==="join"?e:void 0)}catch(a){this.logs.push({functionPath:r,level:"error",message:a instanceof Error?a.message:String(a),timestamp:Date.now()})}}broadcastRoomMessage(e,t,r){if(this.deliveryAuthorization){this.rejectRetainedRooms();return}const s=JSON.stringify(D(t??null)),{byteLength:i}=new TextEncoder().encode(s);if(i>v.MAX_WHISPER_BYTES)throw new p("PAYLOAD_TOO_LARGE",`room broadcast is ${String(i)} bytes, over the ${String(v.MAX_WHISPER_BYTES)}-byte limit`);const o=`{"type":"whisper","topic":${JSON.stringify(e)},"data":${s}}`;this.deliverWhisperLocal(e,o,r);const{relay:a}=this;if(a){const c=r===void 0?void 0:this.readAttachment(r).connectionId;a.forwardWhisper(e,o,c).catch(d=>{console.error("[@lunora/do] room broadcast relay failed:",d)})}}forwardRoomEvent(e,t,r,s,i){const o=i??this.readAttachment(e),{connectionId:a}=o;return a===void 0||!(this.relay instanceof je)?Promise.resolve(!1):this.relay.forwardRoomEvent({attachment:{connectionId:a,context:o.context,expiresAt:o.expiresAt,identity:o.identity,ip:o.ip,revalidateAt:o.revalidateAt,userId:o.userId},connectionId:a,data:r==="message"?s:void 0,kind:r,topic:t})}async relayRoomEvent(e){const{topic:t}=e;if(this.roomHandlerPath(t)===void 0)return{admitted:!1};const r=vl(e.attachment);return e.kind==="join"?!await this.authorizeWhisper(r,t,"subscribe")||!this.setWhisperMembership(r,t,!0)?{admitted:!1}:{admitted:await this.dispatchSettlingJoin(r,t,!0,this.membershipEpoch(r,t))}:e.kind==="leave"?(await this.dispatchRoomEvent(r,t,"leave"),{admitted:!0}):!await this.authorizeWhisper(r,t,"send")||!this.setWhisperMembership(r,t,!0)?{admitted:!1}:{admitted:await this.dispatchRoomEvent(r,t,"message",e.data,this.membershipEpoch(r,t))}}startLiveKeepalive(){if(this.liveKeepalive!==void 0)return;const e=new TextEncoder().encode(`:ka
|
|
10
|
+
|
|
11
|
+
`);this.liveKeepalive=setInterval(()=>{if(this.liveSubscribers.size===0){clearInterval(this.liveKeepalive),this.liveKeepalive=void 0;return}const t=Date.now();for(const[r,s]of this.liveSubscribers)this.endExpiredLiveSubscriber(r,s,t)||s.enqueue(e)},v.LIVE_KEEPALIVE_MS)}endExpiredLiveSubscriber(e,t,r){return t.expiresAt===void 0||t.expiresAt>r?!1:(this.liveSubscribers.delete(e),t.close(),!0)}handleLiveConnect(e){if(this.liveSubscribers.size>=v.MAX_LIVE_CONNECTIONS)return b({error:{code:"LIVE_CONNECTION_LIMIT",message:"this shard holds the maximum number of live connections"}},503);const t=te(e.headers.get("x-lunora-userid"))??"",r=e.headers.get("x-lunora-client-ip")??void 0,s=t===""&&r!==void 0?void 0:t,i=s===void 0?r:void 0,{callerConnections:o,ipConnections:a}=El(this.liveSubscribers.values(),s,i),c=s===""?v.MAX_LIVE_CONNECTIONS_ANONYMOUS_SHARED:v.MAX_LIVE_CONNECTIONS_PER_CALLER;if(s!==void 0&&o>=c)return b({error:{code:"LIVE_CONNECTION_LIMIT",message:"this caller holds the maximum number of live connections"}},503);if(i!==void 0&&a>=v.MAX_LIVE_CONNECTIONS_PER_CALLER)return b({error:{code:"LIVE_CONNECTION_LIMIT",message:"this client holds the maximum number of live connections"}},503);const d=he(e.headers.get("x-lunora-identity-exp")),l=new TextEncoder,h=crypto.randomUUID(),u={close:()=>{},enqueue:()=>{},...d===void 0?{}:{expiresAt:d},...r===void 0?{}:{ip:r},subscriptions:new Map,userId:t},m=new ReadableStream({cancel:()=>{this.liveSubscribers.delete(h)},start:E=>{u.close=()=>{try{E.close()}catch{}},u.enqueue=g=>{if(E.desiredSize!==null&&E.desiredSize<g.byteLength){this.liveSubscribers.delete(h),u.close();return}try{E.enqueue(g)}catch{}},E.enqueue(l.encode(`:ok
|
|
12
|
+
|
|
13
|
+
`))}},{highWaterMark:v.MAX_LIVE_QUEUED_BYTES,size:E=>E.byteLength});this.liveSubscribers.set(h,u),this.startLiveKeepalive();const S=()=>{this.liveSubscribers.delete(h),u.close()};return e.signal.aborted?S():e.signal.addEventListener("abort",S,{once:!0}),new Response(m,{headers:{...da,[aa]:h}})}async handleLiveControl(e){const t=await Cl(e);if("response"in t)return t.response;const{action:r,connectionId:s,key:i,subscriptionId:o}=t;if(r==="reauth")return b({error:{code:"BAD_REQUEST",message:"action must be subscribe or unsubscribe"}},400);const a=this.liveSubscribers.get(s),c=te(e.headers.get("x-lunora-userid"))??"";if(a===void 0){const d=he(e.headers.get("x-lunora-identity-exp"));return this.handleLiveSocketControl({action:r,callerId:c,connectionId:s,identityExpiry:d,key:i,subscriptionId:o})}if(a.userId!==c)return b({error:{code:"LIVE_CONNECTION_NOT_FOUND",message:"no such live connection"}},404);if(r==="subscribe"){const d=Xr(a,o,i,he(e.headers.get("x-lunora-identity-exp")),v.MAX_LIVE_TOPICS_PER_CONNECTION);return d!==void 0?d:(a.subscriptions.set(o,i),b({ok:!0}))}return r==="unsubscribe"?(a.subscriptions.get(o)===i&&a.subscriptions.delete(o),b({ok:!0})):b({error:{code:"BAD_REQUEST",message:"action must be subscribe or unsubscribe"}},400)}async handleLiveSocketControl(e){const{action:t,callerId:r,connectionId:s,identityExpiry:i,key:o,subscriptionId:a}=e,c=this.findLiveSocket(s);if(c===void 0&&this.relay instanceof Xt){const h=await this.relay.forwardLiveControl(e);if(h!==void 0)return h}if(c!==void 0&&t==="reauth"&&this.readAttachment(c).admin===!0&&(e.adminReauth===!0||(this.readAttachment(c).userId??"")===r))return this.reauthenticateAdminSocket(c,e);if(c===void 0||(this.readAttachment(c).userId??"")!==r)return b({error:{code:"LIVE_CONNECTION_NOT_FOUND",message:"no such live connection"}},404);if(t==="reauth")return this.reauthenticateSocket(c,e);const d=this.readAttachment(c),l=d.liveGrants??{};if(t==="subscribe"){const h=Xr({expiresAt:d.expiresAt,subscriptions:new Map(Object.entries(l))},a,o,i,v.MAX_LIVE_TOPICS_PER_SOCKET);return h!==void 0?h:this.persistSocketGrants(c,d,{...l,[a]:o})}return t==="unsubscribe"?l[a]!==o?b({ok:!0}):this.persistSocketGrants(c,d,Object.fromEntries(Object.entries(l).filter(([h])=>h!==a))):b({error:{code:"BAD_REQUEST",message:"action must be subscribe or unsubscribe"}},400)}publishLiveWhenLoaded(e,t,r){Yr(t);const s=this.loadLiveStream(e);return s===void 0?this.publishLiveEvent(e,t,r):s.then(()=>this.publishLiveEvent(e,t,r))}async handleLivePublish(e){let t;try{t=await e.json()}catch{return b({error:{code:"BAD_REQUEST",message:"invalid JSON body"}},400)}const r=typeof t.topic=="string"?t.topic:void 0,s=typeof t.stream=="string"&&t.stream.length>0?t.stream:void 0;if(r===void 0||r.length===0||s===void 0)return b({error:{code:"BAD_REQUEST",message:"topic and stream are required"}},400);try{return b({delivered:await this.publishLiveWhenLoaded(s,r,t.data)})}catch(i){if(V(i))return b({error:{code:i.code,message:i.message}},i.status);throw i}}broadcastLiveTopic(e,t,r){const s=la(t,r),i=as(e,t),o=new TextEncoder().encode(s);let a=0;const c=Date.now();for(const[l,h]of this.liveSubscribers){if(this.endExpiredLiveSubscriber(l,h,c))continue;let u=!1;for(const m of h.subscriptions.values())if(m===i){u=!0;break}u&&(h.enqueue(o),a+=1)}const d=`{"type":"live","stream":${JSON.stringify(e)},"topic":${JSON.stringify(t)},"data":${r}}`;return this.relay instanceof Xt&&this.relay.forwardLiveFrame(t,i,d).catch(l=>{console.error("[@lunora/do] live publish relay failed:",l)}),a+this.deliverLiveLocal(t,i,d)}deliverLiveLocal(e,t,r){this.ensureLiveSocketIndex();let s=0;const i=Date.now();for(const o of this.liveGrantSockets){const a=this.readAttachment(o),c=Object.values(a.liveGrants??{});if(c.length===0){this.liveGrantSockets.delete(o);continue}a.whispers?.includes(e)!==!0||!c.includes(t)||(this.pendingRoomJoins.get(o)?.get(e)??0)>0||this.dropIfLapsed(o,a,i)||(N(o,r),s+=1)}return s}ensureLiveSocketIndex(){if(!this.liveSocketIndexBuilt){for(const e of this.runner.sockets()){const t=this.readAttachment(e);t.connectionId!==void 0&&this.liveSocketsByConnection.set(t.connectionId,e),Object.keys(t.liveGrants??{}).length>0&&this.liveGrantSockets.add(e)}this.liveSocketIndexBuilt=!0}}findLiveSocket(e){this.ensureLiveSocketIndex();const t=this.liveSocketsByConnection.get(e);if(t!==void 0&&this.readAttachment(t).connectionId!==e){this.liveSocketsByConnection.delete(e);return}return t}persistSocketGrants(e,t,r){const s={...t,liveGrants:r};Object.keys(r).length===0&&delete s.liveGrants;try{this.writeAttachment(e,s)}catch{return b({error:{code:"TOO_MANY_LIVE_TOPICS",message:"this socket's live subscriptions no longer fit its attachment; unsubscribe a topic"}},429)}return Object.keys(r).length>0?this.liveGrantSockets.add(e):this.liveGrantSockets.delete(e),b({ok:!0})}readAttachment(e){const t=this.attachmentCache.get(e);if(t!==void 0)return t;const r=e,s=r.deserializeAttachment?.();return s&&typeof s=="object"&&"subs"in s&&s.subs?(this.wireAttachmentCache(e,r)&&this.attachmentCache.set(e,s),s):{subs:{}}}wireAttachmentCache(e,t){if(this.cacheWiredSockets.has(e))return!0;const r=t.serializeAttachment;if(r===void 0)return!1;try{t.serializeAttachment=s=>{r.call(t,s),s===void 0?this.attachmentCache.delete(e):this.attachmentCache.set(e,s)}}catch{return!1}return this.cacheWiredSockets.add(e),!0}readAttachmentCopy(e){return structuredClone(this.readAttachment(e))}writeAttachment(e,t,r={}){const s=e;if(s.serializeAttachment===void 0)return;let i=t;try{s.serializeAttachment(i)}catch(o){if(r.shedTableSets===!1||t?.subTables===void 0||Object.keys(t.subTables).length===0)throw this.attachmentCache.delete(e),o;i={...t},delete i.subTables;try{s.serializeAttachment(i)}catch(a){throw this.attachmentCache.delete(e),a}this.markTableSetsRefused(e)}i===void 0?this.attachmentCache.delete(e):this.attachmentCache.set(e,i)}}export{ml as ROOT_DO_SIZE_WARN_BYTES,_e as ROOT_SHARD_NAME,v as ShardDO,Tl as TTL_SWEEP_INTERVAL_MS,Gl as subscriptionListDeltas};
|