@lunora/runtime 1.0.0-alpha.90 → 1.0.0-alpha.92
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +4 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/HEALTH_PATH-D0i8LhwT.mjs +1 -0
- package/dist/packem_shared/composeWorker-CgM6lJBI.mjs +6 -0
- package/package.json +5 -5
- package/dist/packem_shared/HEALTH_PATH-jZsuCmSs.mjs +0 -1
- package/dist/packem_shared/composeWorker-DI7IRbBa.mjs +0 -6
package/dist/index.d.mts
CHANGED
|
@@ -4193,6 +4193,10 @@ interface WorkerOptions {
|
|
|
4193
4193
|
* origin worker refuses to dispatch a paid procedure with a config error
|
|
4194
4194
|
* (`500`) when this is absent, rather than serving it free — the paywall is
|
|
4195
4195
|
* fail-closed by construction. See {@link X402ChargeGate}.
|
|
4196
|
+
*
|
|
4197
|
+
* The converse also holds: setting this without {@link WorkerOptions.functions}
|
|
4198
|
+
* throws at construction. The `.x402` tags are read off that registry, so a
|
|
4199
|
+
* gate with no registry would paywall nothing.
|
|
4196
4200
|
*/
|
|
4197
4201
|
x402Charge?: X402ChargeGate;
|
|
4198
4202
|
}
|
package/dist/index.d.ts
CHANGED
|
@@ -4193,6 +4193,10 @@ interface WorkerOptions {
|
|
|
4193
4193
|
* origin worker refuses to dispatch a paid procedure with a config error
|
|
4194
4194
|
* (`500`) when this is absent, rather than serving it free — the paywall is
|
|
4195
4195
|
* fail-closed by construction. See {@link X402ChargeGate}.
|
|
4196
|
+
*
|
|
4197
|
+
* The converse also holds: setting this without {@link WorkerOptions.functions}
|
|
4198
|
+
* throws at construction. The `.x402` tags are read off that registry, so a
|
|
4199
|
+
* gate with no registry would paywall nothing.
|
|
4196
4200
|
*/
|
|
4197
4201
|
x402Charge?: X402ChargeGate;
|
|
4198
4202
|
}
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{BACKUP_KEY_PREFIX as t,backupManifestKey as a,backupObjectKey as s,backupObjectKeyOfManifest as i,isBackupManifestEntry as n,isBackupManifestKey as p,normalizeBackupPrefix as c}from"./packem_shared/BACKUP_KEY_PREFIX-BOtSu-_3.mjs";import{toAirbyteMessages as f,toFivetranResponse as E}from"./packem_shared/toAirbyteMessages-CetjLpiw.mjs";import{composeWorker as x,createLunoraHandler as S,createWorker as l,defineRpcEnvelope as u,resolveLunoraOptions as _,withFrameworkWorker as d}from"./packem_shared/composeWorker-
|
|
1
|
+
import{BACKUP_KEY_PREFIX as t,backupManifestKey as a,backupObjectKey as s,backupObjectKeyOfManifest as i,isBackupManifestEntry as n,isBackupManifestKey as p,normalizeBackupPrefix as c}from"./packem_shared/BACKUP_KEY_PREFIX-BOtSu-_3.mjs";import{toAirbyteMessages as f,toFivetranResponse as E}from"./packem_shared/toAirbyteMessages-CetjLpiw.mjs";import{composeWorker as x,createLunoraHandler as S,createWorker as l,defineRpcEnvelope as u,resolveLunoraOptions as _,withFrameworkWorker as d}from"./packem_shared/composeWorker-CgM6lJBI.mjs";import{createCrossShardRelationCapabilities as y}from"./packem_shared/createCrossShardRelationCapabilities-DlM1uNSP.mjs";import{DEFAULT_REGISTRY_CACHE_TTL_MS as O,SHARD_REGISTRY_DO_NAME as b,createDynamicShardRegistry as A}from"./packem_shared/DEFAULT_REGISTRY_CACHE_TTL_MS-D5O7elXI.mjs";import{LunoraError as T,toErrorResponse as h}from"./packem_shared/LunoraError-DksAgIpa.mjs";import{c as P,a as g,d as v,r as I,b as D,s as M,w as F}from"./packem_shared/export-tap-H6oPBoSr.mjs";import{HEALTH_PATH as G,HEALTH_READY_PATH as K,buildHealthRoutes as U,d1Probe as B,durableObjectProbe as Y,presenceProbe as w}from"./packem_shared/HEALTH_PATH-D0i8LhwT.mjs";import{LOG_ARCHIVE_PATH as X,resolveLogArchiveFromEnv as j}from"./packem_shared/LOG_ARCHIVE_PATH-Hmjpz_Ko.mjs";import{memoizeIdentity as W,memoizeIdentityPerRequest as q}from"./packem_shared/memoizeIdentity-DnOj3QRi.mjs";import{e as J,a as Z}from"./packem_shared/observability-B1hLjwgx.mjs";import{analyticsEngineSink as ee,combineSinks as re,consoleSink as oe,otlpSink as te,pipelineLogSink as ae,sentrySink as se,webhookSink as ie}from"./packem_shared/analyticsEngineSink-DOreZlpn.mjs";import{D as pe,c as ce}from"./packem_shared/pipeline-log-reader-C-nuWG_e.mjs";import{createQueryCoordinator as fe,createStaticShardRegistry as Ee}from"./packem_shared/createQueryCoordinator-DlWITOu1.mjs";import{applyJurisdiction as xe,resolveShard as Se}from"./packem_shared/applyJurisdiction-C0ddU7Tg.mjs";import{a as ue,r as _e,b as de}from"./packem_shared/rest-cache-D1BlbZb1.mjs";import{a as ye,b as Ce,c as Oe,r as be}from"./packem_shared/rest-routes-CpwDstbq.mjs";import{decorateResponse as Le,enforceOrigin as Te,handleCorsPreflight as he,resolveSecurity as He}from"./packem_shared/decorateResponse-CCRm2CFM.mjs";import{createShardClient as ge}from"./packem_shared/createShardClient-BaZZLHHu.mjs";import{STORAGE_UPLOAD_MAX_BODY_BYTES as Ie}from"./packem_shared/STORAGE_UPLOAD_MAX_BODY_BYTES-BqyO-1l6.mjs";import{LOG_ARCHIVE_NOT_CONFIGURED as Me}from"./packem_shared/LOG_ARCHIVE_NOT_CONFIGURED-CDpi4yFD.mjs";import{NOOP_EXECUTION_CONTEXT as Ne}from"./packem_shared/NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{composeIdentityResolvers as Ke,routeIdentityResolvers as Ue}from"./packem_shared/composeIdentityResolvers-BHZ4jH8o.mjs";const e="0.0.0";export{t as BACKUP_KEY_PREFIX,pe as DEFAULT_LOG_COLUMNS,O as DEFAULT_REGISTRY_CACHE_TTL_MS,G as HEALTH_PATH,K as HEALTH_READY_PATH,Me as LOG_ARCHIVE_NOT_CONFIGURED,X as LOG_ARCHIVE_PATH,T as LunoraError,Ne as NOOP_EXECUTION_CONTEXT,b as SHARD_REGISTRY_DO_NAME,Ie as STORAGE_UPLOAD_MAX_BODY_BYTES,e as VERSION,ee as analyticsEngineSink,xe as applyJurisdiction,ue as applyRestCache,ye as argsFromQuery,a as backupManifestKey,s as backupObjectKey,i as backupObjectKeyOfManifest,U as buildHealthRoutes,Ce as buildRestRoutes,re as combineSinks,Ke as composeIdentityResolvers,x as composeWorker,oe as consoleSink,y as createCrossShardRelationCapabilities,A as createDynamicShardRegistry,P as createKvCursorStore,S as createLunoraHandler,g as createMemoryCursorStore,ce as createPipelineLogReader,fe as createQueryCoordinator,Oe as createRestRateLimit,ge as createShardClient,Ee as createStaticShardRegistry,l as createWorker,B as d1Probe,Le as decorateResponse,v as defineExportSink,u as defineRpcEnvelope,Y as durableObjectProbe,J as emitLogEvent,Z as emitRpcEvent,Te as enforceOrigin,he as handleCorsPreflight,n as isBackupManifestEntry,p as isBackupManifestKey,W as memoizeIdentity,q as memoizeIdentityPerRequest,c as normalizeBackupPrefix,te as otlpSink,ae as pipelineLogSink,w as presenceProbe,I as r2Sink,_e as requestCarriesCredentials,j as resolveLogArchiveFromEnv,_ as resolveLunoraOptions,He as resolveSecurity,Se as resolveShard,de as restCacheHeaders,be as restSurfaceFromRegistry,Ue as routeIdentityResolvers,D as runExportTap,M as sanitizeChange,se as sentrySink,f as toAirbyteMessages,h as toErrorResponse,E as toFivetranResponse,F as webhookExportSink,ie as webhookSink,d as withFrameworkWorker};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as T}from"./LunoraError-DksAgIpa.mjs";import{m as A}from"./method-guard-BG_vJNTl.mjs";import{resolveShard as R}from"./applyJurisdiction-C0ddU7Tg.mjs";const H="/_lunora/health",C="/_lunora/health/ready",N=t=>t==="liveness"?["liveness"]:t==="readiness"?["readiness"]:["liveness","readiness"];class P{#e=new Map;addChecker(e,s,r){this.#e.set(e,{run:s,types:r.type})}async getReport(e){const s=[...this.#e].filter(([,a])=>e===void 0||a.types.includes(e)),r=await Promise.all(s.map(async([a,o])=>[a,await o.run()]));return{healthy:r.every(([,a])=>a.health.healthy),report:Object.fromEntries(r)}}}const S=t=>{const e=new P,s=new Set;for(const r of t)r.critical&&s.add(r.name),e.addChecker(r.name,async()=>{let a;try{a=await r.check()}catch(o){a={healthy:!1,message:o instanceof Error?o.message:"probe failed"}}return{health:{healthy:a.healthy,...a.message===void 0?{}:{message:a.message}}}},{type:N(r.kind)});return{criticalNames:s,registry:e}},_=(t,e)=>{const s=t.includes(":")?t.slice(0,t.indexOf(":")):"probe",r=(e.get(s)??0)+1;return e.set(s,r),r===1?s:`${s}#${String(r)}`},j=(t,e)=>t?"unhealthy":e?"degraded":"healthy",M=(t,e,s,r,a)=>{const o=[];let u=!1,d=!1;const y=new Map;for(const[h,c]of Object.entries(t)){const n=e.has(h),i=c.health.healthy;d=d||!i,u=u||!i&&n;const l=s==="admin"?h:_(h,y);o.push({critical:n,...s==="admin"&&c.health.message!==void 0?{message:c.health.message}:{},name:l,status:i?"up":"down"})}return o.sort((h,c)=>h.name<c.name?-1:+(h.name>c.name)),{anyCriticalDown:u,body:{appName:r,appVersion:a,checks:o,status:j(u,d),timestamp:new Date().toISOString()}}},G=t=>{const{appName:e="lunora",appVersion:s="0.0.0",auth:r="public",cacheTtlMs:a,isAdmin:o,resolveProbes:u}=t,d=n=>a!==void 0?a:n==="readiness"?0:r==="public"?5e3:0,y={},h=n=>{if(r==="admin"&&!o(n))throw new T("health endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403})},c=async(n,i,l)=>{const p=A(n,["GET","HEAD"]);if(p)return p;h(n);const f=d(l);if(f>0){const m=y[l];if(m!==void 0&&Date.now()<m.expiresAt)return Response.json(m.body,{headers:{"cache-control":"no-store"},status:m.down?503:200})}const{criticalNames:b,registry:v}=S(u(i)),{healthy:E,report:k}=await v.getReport(l==="readiness"?"readiness":void 0),{anyCriticalDown:D,body:g}=M(k,b,r,e,s),w=l==="readiness"?!E:D;return f>0&&(y[l]={body:g,down:w,expiresAt:Date.now()+f}),Response.json(g,{headers:{"cache-control":"no-store"},status:w?503:200})};return{[H]:(n,i)=>c(n,i,"aggregate"),[C]:(n,i)=>c(n,i,"readiness")}},I=(t,e,s)=>({check:async()=>{try{return await R(e,s).fetch(new Request("https://shard.internal/_lunora/status",{method:"GET"})),{healthy:!0}}catch{return{healthy:!1,message:"durable object unreachable"}}},critical:!0,name:t}),q=(t,e)=>({check:async()=>{try{return await e.prepare("SELECT 1").first(),{healthy:!0}}catch{return{healthy:!1,message:"d1 query failed"}}},critical:!0,name:t}),B=(t,e)=>({check:()=>e?{healthy:!0}:{healthy:!1,message:"binding not configured"},critical:!1,name:t});export{H as HEALTH_PATH,C as HEALTH_READY_PATH,G as buildHealthRoutes,q as d1Probe,I as durableObjectProbe,B as presenceProbe};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import{isLunoraError as Bn,toErrorBody as xn}from"@lunora/errors";import{e as Ht}from"./evict-oldest-BNXsKx4s.mjs";import{NOOP_EXECUTION_CONTEXT as Hn}from"./NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{t as Ln,f as Mn}from"./base64-Bl1_r2k1.mjs";import{e as jn,a as $n}from"./identity-header-C4Z5pldl.mjs";import{o as ve,b as Kn,p as Fn,m as Gn,d as Qn,a as zn,r as Wn}from"./otlp-resource-DeXhb949.mjs";import{e as We,d as Vn}from"./wire-codec-DBWN80s9.mjs";import{d as ee,e as he,M as Lt,b as Jn,f as qn,g as Mt,h as jt}from"./rest-routes-CpwDstbq.mjs";import{LunoraError as c,toErrorResponse as ct}from"./LunoraError-DksAgIpa.mjs";import{a as j,m as we}from"./method-guard-BG_vJNTl.mjs";import{normalizeBackupPrefix as Ye,BACKUP_KEY_PREFIX as Xe,isBackupManifestKey as Yn,backupObjectKeyOfManifest as $t,backupObjectKey as Xn,backupManifestKey as Zn}from"./BACKUP_KEY_PREFIX-BOtSu-_3.mjs";import{toHex as er,buildStorageAdminRoutes as tr,STORAGE_UPLOAD_MAX_BODY_BYTES as nr,STORAGE_PATH as rr}from"./STORAGE_UPLOAD_MAX_BODY_BYTES-BqyO-1l6.mjs";import{b as or,e as ar,f as dt,g as sr,h as ir}from"./export-tap-H6oPBoSr.mjs";import{buildHealthRoutes as cr,durableObjectProbe as dr,d1Probe as ur,presenceProbe as He}from"./HEALTH_PATH-D0i8LhwT.mjs";import{wrapResolverWithContract as lr}from"./composeIdentityResolvers-BHZ4jH8o.mjs";import{composeIdentityResolvers as Us,routeIdentityResolvers as Cs}from"./composeIdentityResolvers-BHZ4jH8o.mjs";import{buildLogArchiveAdminRoutes as hr}from"./LOG_ARCHIVE_PATH-Hmjpz_Ko.mjs";import{r as fr,f as ut,a as ce}from"./observability-B1hLjwgx.mjs";import{resolveShard as ge,applyJurisdiction as lt}from"./applyJurisdiction-C0ddU7Tg.mjs";import{resolveSecurity as ht,handleCorsPreflight as pr,enforceOrigin as mr,decorateResponse as Le,enforceWebSocketOrigin as ft}from"./decorateResponse-CCRm2CFM.mjs";const wr=e=>{const t=e??{};if(typeof t.bucket=="function")return t;const n=t.bucketName,a={...t,bucketName:typeof n=="string"&&n!==""?n:"default"};return a.bucket=()=>a,a},Kt="__lunoraBranch",gr=e=>typeof e=="object"&&e!==null&&Object.hasOwn(e,Kt),yr=`may not contain the reserved workflow branch-marker key ("${Kt}")`,br=async e=>{const t=[];let n;for(;;){const r=await e(n);if(t.push(...Array.isArray(r.records)?r.records:[]),r.truncated!==!0||typeof r.cursor!="string"||r.cursor.length===0)return t;if(r.cursor===n)throw new Error("collectPages: the list did not advance its cursor — refusing to page forever");n=r.cursor}},Ze=(e,t)=>{const n=Math.max(e.length,t.length);let r=e.length^t.length;for(let a=0;a<n;a+=1){const i=a<e.length?e.charCodeAt(a):0,u=a<t.length?t.charCodeAt(a):0;r|=i^u}return r===0},_r=(e,t,n,r)=>{const a=e.get(t);if(a!==void 0)return a;Ht(e,r);const i=n().catch(u=>{throw e.get(t)===i&&e.delete(t),u});return e.set(t,i),i},et=new TextEncoder,Rr=Array.from({length:32},(e,t)=>t);new RegExp(`[${Rr.map(e=>String.fromCodePoint(e)).join("")}]`,"u");const Er=64,Ar=new Map,Ft=async e=>_r(Ar,e,async()=>crypto.subtle.importKey("raw",et.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]),Er),Gt=async(e,t)=>{const n=await Ft(e),r=await crypto.subtle.sign("HMAC",n,et.encode(t));return Ln(new Uint8Array(r))},Sr=async(e,t,n)=>{const r=await Ft(e);return crypto.subtle.verify("HMAC",r,n,et.encode(t))},Tr=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"];new Set(Tr);const Or=new Set(["AE","BH","IL","IQ","IR","JO","KW","LB","OM","PS","QA","SA","SY","TR","YE"]),vr=-100,kr=15,Ir=e=>{const t=Number(e.longitude??Number.NaN);switch(e.continent){case"AF":return"afr";case"AS":return e.country!==void 0&&Or.has(e.country)?"me":"apac";case"EU":return Number.isFinite(t)&&t>kr?"eeur":"weur";case"NA":return Number.isFinite(t)&&t<vr?"wnam":"enam";case"OC":return"oc";case"SA":return"sam";default:return}},pt=e=>{const t=e.cf;return t===void 0?void 0:Ir(t)},Ve="::relay::",Pr=(e,t)=>`${e}${Ve}${String(t)}`,Je="::replica::",Nr=(e,t)=>`${e}${Je}${t}`,Dr=e=>{if(e==null||!/^\d+$/.test(e))return;const t=Number.parseInt(e,10);return Number.isSafeInteger(t)&&t>0?t:void 0},Ur=new Set(["1","enabled","on","true","yes"]),Cr=new Set(["0","disabled","false","no","off"]),Br=(e,t)=>{const n=(e??"").trim().toLowerCase();return Ur.has(n)?!0:Cr.has(n)?!1:t},Qt="v1",xr=6e4,Hr=async(e,t={})=>{const n=(t.now??Date.now())+(t.ttlMs??xr),r=`${Qt}.${String(n)}`,a=await Gt(e,r);return{expiresAtMs:n,token:`${r}.${a}`}},Lr=async(e,t,n=Date.now())=>{if(e.length===0||t.length===0)return!1;const r=t.split(".");if(r.length!==3)return!1;const[a,i,u]=r;if(a!==Qt||u.length===0)return!1;const h=Number(i);if(!Number.isFinite(h)||h<=n)return!1;let p;try{p=Mn(u)}catch{return!1}return Sr(e,`${a}.${i}`,p)},P="/_lunora/admin/auth",Mr={INVITER_REQUIRED:400,ORG_SLUG_INVALID:400,ORG_SLUG_TAKEN:409,PASSWORD_TOO_LONG:400,PASSWORD_TOO_SHORT:400,USER_ALREADY_EXISTS:409,USER_NOT_FOUND:404},D=(e,t)=>{const n=e[t];if(typeof n!="string"||n==="")throw new c(`\`${t}\` is required`,{code:"BAD_REQUEST",status:400});return n},le=(e,t)=>{const n=e(t);if(n===void 0)throw new c(`\`${t}\` query parameter is required`,{code:"BAD_REQUEST",status:400});return n},zt=e=>{if(typeof e=="string"||Array.isArray(e)&&e.every(t=>typeof t=="string"))return e},oe=(e,t)=>typeof e[t]=="string"?e[t]:void 0,Me=(e,t)=>{const n=e[t];return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:void 0},mt=e=>{const t=zt(e.role);if(t===void 0||typeof t=="string"&&t.trim()==="")throw new c("`role` is required",{code:"BAD_REQUEST",status:400});return t},wt=e=>{const t=e.permission;if(typeof t!="object"||t===null||Array.isArray(t))throw new c("`permission` object is required",{code:"BAD_REQUEST",status:400});const n={};for(const[r,a]of Object.entries(t))Array.isArray(a)&&a.every(i=>typeof i=="string")&&(n[r]=a);return n},jr={[`${P}/capabilities`]:{build:()=>({}),http:"GET",method:"capabilities"},[`${P}/users`]:{build:({paging:e,query:t})=>{const n=t("sortDirection");return{...e,filterField:t("filterField"),filterValue:t("filterValue"),search:t("search"),searchField:t("searchField"),sortBy:t("sortBy"),sortDirection:n==="asc"||n==="desc"?n:void 0}},http:"GET",method:"listUsers"},[`${P}/sessions`]:{build:({paging:e,query:t})=>({...e,userId:t("userId")}),http:"GET",method:"listSessions"},[`${P}/accounts`]:{build:({query:e})=>({userId:le(e,"userId")}),http:"GET",method:"listAccounts"},[`${P}/passkeys`]:{build:({query:e})=>({userId:le(e,"userId")}),http:"GET",method:"listPasskeys"},[`${P}/organizations`]:{build:({paging:e})=>({...e}),http:"GET",method:"listOrganizations"},[`${P}/organizations/members`]:{build:({paging:e,query:t})=>({...e,organizationId:le(t,"organizationId")}),http:"GET",method:"listMembers"},[`${P}/organizations/invitations`]:{build:({paging:e,query:t})=>({...e,organizationId:le(t,"organizationId")}),http:"GET",method:"listInvitations"},[`${P}/config`]:{build:()=>({}),http:"GET",method:"config"},[`${P}/organizations/teams`]:{build:({paging:e,query:t})=>({...e,organizationId:le(t,"organizationId")}),http:"GET",method:"listTeams"},[`${P}/organizations/teams/members`]:{build:({paging:e,query:t})=>({...e,teamId:le(t,"teamId")}),http:"GET",method:"listTeamMembers"},[`${P}/organizations/roles`]:{build:({paging:e,query:t})=>({...e,organizationId:le(t,"organizationId")}),http:"GET",method:"listOrgRoles"},[`${P}/users/create`]:{build:({body:e})=>({data:Me(e,"data"),email:D(e,"email"),name:D(e,"name"),password:oe(e,"password"),role:zt(e.role)}),http:"POST",method:"createUser"},[`${P}/users/update`]:{build:({body:e})=>{const{data:t}=e;if(typeof t!="object"||t===null||Array.isArray(t))throw new c("`data` object is required",{code:"BAD_REQUEST",status:400});return{data:t,userId:D(e,"userId")}},http:"POST",method:"updateUser"},[`${P}/users/role`]:{build:({body:e})=>({role:mt(e),userId:D(e,"userId")}),http:"POST",method:"setRole"},[`${P}/users/ban`]:{build:({body:e})=>({expiresInSeconds:typeof e.expiresInSeconds=="number"?e.expiresInSeconds:void 0,reason:oe(e,"reason"),userId:D(e,"userId")}),http:"POST",method:"banUser"},[`${P}/users/unban`]:{build:({body:e})=>({userId:D(e,"userId")}),http:"POST",method:"unbanUser"},[`${P}/users/password`]:{build:({body:e})=>({newPassword:D(e,"newPassword"),userId:D(e,"userId")}),http:"POST",method:"setUserPassword",returns:"void"},[`${P}/users/remove`]:{build:({body:e})=>({userId:D(e,"userId")}),http:"POST",method:"removeUser",returns:"void"},[`${P}/users/impersonate`]:{build:({body:e})=>({userId:D(e,"userId")}),http:"POST",method:"impersonateUser"},[`${P}/sessions/revoke`]:{build:({body:e})=>({sessionId:D(e,"sessionId")}),http:"POST",method:"revokeUserSession",returns:"void"},[`${P}/sessions/revoke-all`]:{build:({body:e})=>({userId:D(e,"userId")}),http:"POST",method:"revokeUserSessions",returns:"void"},[`${P}/accounts/unlink`]:{build:({body:e})=>({accountId:D(e,"accountId"),userId:D(e,"userId")}),http:"POST",method:"unlinkAccount",returns:"void"},[`${P}/two-factor/disable`]:{build:({body:e})=>({userId:D(e,"userId")}),http:"POST",method:"disableTwoFactor",returns:"void"},[`${P}/passkeys/delete`]:{build:({body:e})=>({passkeyId:D(e,"passkeyId")}),http:"POST",method:"deletePasskey",returns:"void"},[`${P}/organizations/members/remove`]:{build:({body:e})=>({memberId:D(e,"memberId")}),http:"POST",method:"removeMember",returns:"void"},[`${P}/organizations/invitations/cancel`]:{build:({body:e})=>({invitationId:D(e,"invitationId")}),http:"POST",method:"cancelInvitation",returns:"void"},[`${P}/organizations/create`]:{build:({body:e})=>({logo:oe(e,"logo"),metadata:Me(e,"metadata"),name:D(e,"name"),ownerId:oe(e,"ownerId"),slug:oe(e,"slug")}),http:"POST",method:"createOrganization"},[`${P}/organizations/update`]:{build:({body:e})=>({logo:oe(e,"logo"),metadata:Me(e,"metadata"),name:oe(e,"name"),organizationId:D(e,"organizationId"),slug:oe(e,"slug")}),http:"POST",method:"updateOrganization"},[`${P}/organizations/remove`]:{build:({body:e})=>({organizationId:D(e,"organizationId")}),http:"POST",method:"deleteOrganization",returns:"void"},[`${P}/organizations/members/add`]:{build:({body:e})=>({organizationId:D(e,"organizationId"),role:oe(e,"role"),userId:D(e,"userId")}),http:"POST",method:"addMember"},[`${P}/organizations/members/invite`]:{build:({body:e})=>({email:D(e,"email"),inviterId:oe(e,"inviterId"),organizationId:D(e,"organizationId"),role:oe(e,"role")}),http:"POST",method:"inviteMember"},[`${P}/organizations/members/role`]:{build:({body:e})=>({memberId:D(e,"memberId"),role:mt(e)}),http:"POST",method:"updateMemberRole"},[`${P}/organizations/teams/create`]:{build:({body:e})=>({name:D(e,"name"),organizationId:D(e,"organizationId")}),http:"POST",method:"createTeam"},[`${P}/organizations/teams/update`]:{build:({body:e})=>({name:D(e,"name"),teamId:D(e,"teamId")}),http:"POST",method:"updateTeam"},[`${P}/organizations/teams/remove`]:{build:({body:e})=>({teamId:D(e,"teamId")}),http:"POST",method:"removeTeam",returns:"void"},[`${P}/organizations/teams/members/add`]:{build:({body:e})=>({teamId:D(e,"teamId"),userId:D(e,"userId")}),http:"POST",method:"addTeamMember"},[`${P}/organizations/teams/members/remove`]:{build:({body:e})=>({teamMemberId:D(e,"teamMemberId")}),http:"POST",method:"removeTeamMember",returns:"void"},[`${P}/organizations/roles/create`]:{build:({body:e})=>({organizationId:D(e,"organizationId"),permission:wt(e),role:D(e,"role")}),http:"POST",method:"createOrgRole"},[`${P}/organizations/roles/update`]:{build:({body:e})=>({permission:wt(e),roleId:D(e,"roleId")}),http:"POST",method:"updateOrgRole"},[`${P}/organizations/roles/remove`]:{build:({body:e})=>({roleId:D(e,"roleId")}),http:"POST",method:"deleteOrgRole",returns:"void"}},$r=e=>{const t=async a=>{try{return await a()}catch(i){if(i instanceof c)throw i;const u=i,h=typeof u.code=="string"?u.code:"AUTH_ADMIN_ERROR";throw console.error("[lunora] auth admin operation failed:",i),new c("auth admin operation failed",{code:h,status:Mr[h]??500})}},n=async(a,i)=>{if(e.assertAdmin(a),a.method!==i.http)throw new c(`Auth admin endpoint requires ${i.http}`,{code:"METHOD_NOT_ALLOWED",status:405});const u=e.getAuthAdmin();if(u===void 0)throw new c("auth endpoints require an `authAdmin` on the worker",{code:"AUTH_NOT_CONFIGURED",status:400});const h=u[i.method];if(h===void 0)throw new c(`auth admin does not support \`${i.method}\``,{code:"AUTH_OP_NOT_SUPPORTED",status:400});const p=new URL(a.url),m={body:i.http==="POST"?await e.readJsonBody(a):{},paging:e.parsePaging(a),query:T=>e.queryParameter(p,T)},A=i.build(m),S=await t(()=>h(A));return Response.json(i.returns==="void"?{ok:!0}:S,{headers:{"cache-control":"no-store","content-type":"application/json"},status:200})},r={};for(const[a,i]of Object.entries(jr))r[a]=u=>n(u,i);return r},gt="__lunora_admin__:getAuthAuditLog",yt=e=>typeof e=="string"&&e!==""?e:void 0,bt=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0,Kr=e=>async(n,r)=>{e.assertAdmin(n);const a=e.getReader();if(a===void 0)throw new c("the auth/security audit endpoint requires an `authAuditReader` on the worker",{code:"AUTH_AUDIT_NOT_CONFIGURED",status:400});const i=yt(r.actorId),u=yt(r.event),h=bt(r.sinceSeq),p=bt(r.limit),m={...i===void 0?{}:{actorId:i},...u===void 0?{}:{event:u},...h===void 0?{}:{sinceSeq:h},...p===void 0?{}:{limit:p}};let A;try{A=await a.read(m)}catch(T){throw T instanceof c?T:(console.error("[lunora] auth audit read failed:",T),new c("auth audit read failed",{code:"AUTH_AUDIT_READ_FAILED",status:500}))}const S={entries:A};return Response.json({result:We(S)},{headers:{"content-type":"application/json"},status:200})},Fr=(e,t)=>{const n=[],r=[];if(t&&t.length>0)for(const a of t)e.resolveTableSharding?.(a)?.mode.kind==="global"?r.push(a):n.push(a);return{globalTables:r,shardLocalTables:n}},Gr=async(e,t,n,r,a,i,u)=>{if(n!==void 0&&r.length===0)return;const h=await e.orchestrateExport(i,{args:{tables:r},defaultShardKey:u,headers:t,tables:r});for(const p of h.shards)if(!p.error)for(const m of p.rows??[])a(m)},Wt=async(e,t,n,r,a,i)=>{const u=r??e.listSchemaTables?.();r===void 0&&e.listSchemaTables===void 0&&console.warn("[lunora] export: no table list available (`listSchemaTables` is unset and no `tables` were named), so only the default shard is reachable. A `.shardBy()` deployment's other shards will be missing from this export. Name the tables explicitly, or regenerate the worker so codegen supplies the list.");const{globalTables:h,shardLocalTables:p}=Fr(e,u);await Gr(t,n,u,p,a,i,e.defaultShardKey??"__root__");const m=e.exportGlobals;if((r===void 0||h.length>0)&&m)for await(const S of m({tables:h}))a(S)},Qr=new TextEncoder,zr=1e3,Vt=10,Wr=200,_t=8,Jt="lunoraBackupCron",Rt=24*1048576,Et=e=>{const t=e.slice(0,Vt).map(r=>$t(r)),n=e.length-t.length;return`${t.join(", ")}${n>0?` (+${String(n)} more)`:""}`},Vr=(e,t)=>{const n=new Uint8Array(new ArrayBuffer(t));let r=0;for(const a of e)n.set(a,r),r+=a.byteLength;return n},tt=async(e,t,n,r)=>{if(n===void 0||!Number.isInteger(n)||n<=0)return{eligible:0,stale:[]};const a=[];let i;for(let u=0;u<zr;u+=1){const h=await e.list({cursor:i,include:["customMetadata"],prefix:t});for(const p of h.objects)Yn(p.key)&&p.customMetadata?.[Jt]===r&&a.push(p.key);if(!h.truncated||h.cursor===void 0)break;i=h.cursor}return{eligible:a.length,stale:a.toSorted((u,h)=>h.localeCompare(u)).slice(n)}},Jr=async(e,t,n,r,a)=>{const{stale:i}=await tt(e,t,n,r),u=new Set(a),h=i.filter(g=>u.has(g)),p=h.slice(0,Wr),m=i.length-p.length,A=a.length-h.length;if(p.length===0)return{deleted:[],failed:[],ignored:A,remaining:m};const S=[],T=[];for(let g=0;g<p.length;g+=_t){const y=await Promise.allSettled(p.slice(g,g+_t).map(async _=>(await e.delete($t(_)),await e.delete(_),_)));for(const[_,f]of y.entries())f.status==="fulfilled"?S.push(f.value):T.push(p[g+_])}return S.length>0&&console.info(`[lunora] backup prune kept the newest ${String(n)} and deleted ${String(S.length)}: ${Et(S)}`),T.length>0&&console.warn(`[lunora] backup prune failed to remove ${String(T.length)}: ${Et(T)}`),{deleted:S,failed:T,ignored:A,remaining:m}},qr=async e=>{const t=e.backupStore;if(!t)throw new c("backup retention preview requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});const n=Ye(e.backupPrefix??Xe),r=e.backupCron,{eligible:a,stale:i}=r===void 0?{eligible:0,stale:[]}:await tt(t,n,e.backupRetain,r);return{cron:r,eligible:a,keep:e.backupRetain??0,prefix:n,wouldDelete:i}},Yr=async(e,t,n,r)=>{const a=e.backupStore,i=e.queryCoordinator;if(!a)throw new c("scheduled backup requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});if(!i)throw new c("scheduled backup requires a `queryCoordinator` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});if(!n||n.length===0)throw new c("scheduled backup requires an `adminToken` (or `env.LUNORA_ADMIN_TOKEN`) to authenticate the per-shard export gate",{code:"BACKUP_NOT_CONFIGURED",status:500});const u={authorization:`Bearer ${n}`,"content-type":"application/json"},h=e.backupTables;let p=0,m=0,A=[];await Wt(e,i,u,h,N=>{const M=Qr.encode(`${JSON.stringify(N)}
|
|
2
|
+
`);if(p+=1,m+=M.byteLength,m>Rt)throw new c(`scheduled backup reached ${String(m)} bytes of NDJSON, past the ${String(Rt)}-byte limit for a snapshot assembled inside a Worker — nothing was written. Narrow it with \`backupTables\`, or take this snapshot off-platform with \`lunora backup create --bucket\`.`,{code:"BACKUP_TOO_LARGE",status:507});A.push(M)},t);const T=Ye(e.backupPrefix??Xe),g=new Date(r.scheduledTime).toISOString(),y=Xn(T,g),_=Vr(A,m);A=[];const f=er(await crypto.subtle.digest("SHA-256",_));await a.put(y,_,{httpMetadata:{contentType:"application/x-ndjson"},sha256:f});const O={bytes:m,createdAt:g,cron:r.cron,file:y,id:g,rows:p,scheduledTime:r.scheduledTime,sha256:f,...h?{tables:h.join(",")}:{}};await a.put(Zn(y),`${JSON.stringify(O,void 0,2)}
|
|
3
|
+
`,{customMetadata:{[Jt]:r.cron},httpMetadata:{contentType:"application/json"}});try{const{stale:N}=await tt(a,T,e.backupRetain,r.cron);if(N.length>0){const M=N.slice(0,Vt),k=N.length-M.length;console.info(`[lunora] backup retention: ${String(N.length)} snapshot(s) past the newest ${String(e.backupRetain)} — run \`lunora backup prune\` to remove them: ${M.join(", ")}${k>0?` (+${String(k)} more)`:""}`)}}catch(N){console.warn(`[lunora] backup ${y} was written, but the retention report failed:`,N)}},Xr=async(e,t)=>{const n=e.backupStore;if(!n)throw new c("backup prune requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});const r=e.backupCron,a=e.backupRetain;if(r===void 0||a===void 0||!Number.isInteger(a)||a<=0)throw new c("backup prune needs a retention window: set `backupRetain` (and `backupCron`, which decides whose snapshots retention owns) on the worker. Without one there is nothing past the window to remove.",{code:"BACKUP_RETENTION_NOT_CONFIGURED",status:400});return Jr(n,Ye(e.backupPrefix??Xe),a,r,t)},Zr="/_lunora/admin/backup/retention",eo="/_lunora/admin/backup/prune",to=e=>{const{options:t,readJsonBody:n,requireAdminOption:r}=e,a=(h,p)=>{r(h,t.backupStore,{code:"BACKUP_NOT_CONFIGURED",message:`backup ${p} requires a \`backupStore\` on the worker`})},i=async h=>(j(h,"GET","Backup-retention"),a(h,"retention preview"),Response.json(await qr(t),{headers:{"cache-control":"no-store"}})),u=async h=>{j(h,"POST","Backup-prune"),a(h,"prune");const{confirm:p}=await n(h);if(!Array.isArray(p)||p.some(m=>typeof m!="string"))throw new c("backup prune requires a `confirm` array of the sidecar keys to remove — read them from `GET /_lunora/admin/backup/retention` and pass back the ones you mean to delete",{code:"BAD_REQUEST",status:400});return Response.json(await Xr(t,p),{headers:{"cache-control":"no-store"}})};return{[eo]:u,[Zr]:i}},At=500,no=(e,t,n)=>{if(typeof e!="object"||e===null||Array.isArray(e))throw new c("each batch call must be an object",{code:"BAD_REQUEST",status:400});const r=e;if(typeof r.functionPath!="string")throw new c("each batch call needs a string `functionPath`",{code:"BAD_REQUEST",status:400});if(r.functionPath.startsWith("__lunora_relation__:")||r.functionPath.startsWith("__lunora_admin__"))throw new c("reserved function path cannot be batched",{code:"FORBIDDEN",status:403});if(r.args!==void 0&&(typeof r.args!="object"||r.args===null||Array.isArray(r.args)))throw new c("each batch call `args` must be an object",{code:"BAD_REQUEST",status:400});return{entry:{args:r.args===void 0?{}:r.args,clientId:typeof r.clientId=="string"?r.clientId:void 0,clientSeq:typeof r.clientSeq=="number"?r.clientSeq:void 0,functionPath:r.functionPath,id:typeof r.id=="number"?r.id:t,mutationId:typeof r.mutationId=="string"?r.mutationId:void 0},shardKey:typeof r.shardKey=="string"?r.shardKey:n}},ro=(e,t)=>{if(e.length>At)throw new c(`RPC batch exceeds the ${String(At)}-call limit`,{code:"BAD_REQUEST",status:400});const n=new Map;for(const[r,a]of e.entries()){const{entry:i,shardKey:u}=no(a,r,t),h=n.get(u)??[];h.push(i),n.set(u,h)}return n},oo="/_lunora/admin/export",ao="/_lunora/admin/import",so="/_lunora/admin/sync",io="/_lunora/admin/connector/sync",co="/_lunora/admin/apply",uo="/_lunora/admin/export-tap/run",lo=new TextEncoder,ho=async e=>{const n=await he(e,"Export")??{};if(n.tables===void 0)return{tables:void 0};if(!Array.isArray(n.tables))throw new c("Export `tables` must be a string array",{code:"BAD_REQUEST",status:400});const r=[];for(const a of n.tables){if(typeof a!="string"||a.length===0)throw new c("Export `tables` entries must be non-empty strings",{code:"BAD_REQUEST",status:400});r.push(a)}return{tables:r}},je=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):void 0,fo=e=>{const{applyGlobals:t,defaultShardKey:n,exportCursorStore:r,exportSinks:a,knownTables:i,queryCoordinator:u,assertAdmin:h,requireAdminOption:p,resolveForwardContext:m,shardDO:A,streamExportRows:S,streamingImport:T,syncGlobals:g}=e,y=async(k,K)=>{const $=we(k,["POST"]);if($)return $;const W=p(k,u,{code:"BAD_REQUEST",message:"Export endpoint requires a `queryCoordinator` on the worker"}),C=await ho(k),{headers:V}=await m(k,K),F=new ReadableStream({async pull(J){const Z=H=>{J.enqueue(lo.encode(`${JSON.stringify(H)}
|
|
4
|
+
`))};try{await S(W,V,C.tables,Z),J.close()}catch(H){J.error(H)}}});return new Response(F,{headers:{"content-type":"application/x-ndjson"},status:200})},_=async(k,K)=>{const $=we(k,["POST"]);if($)return $;const W=p(k,u,{code:"BAD_REQUEST",message:"Sync endpoint requires a `queryCoordinator` on the worker"}),C=await ee(k),V=typeof C.cursors=="object"&&C.cursors!==null?C.cursors:{},F=typeof C.limit=="number"?C.limit:void 0,J=typeof C.globalCursor=="number"?C.globalCursor:0,Z=je(C.tables),{headers:H}=await m(k,K),q=Z??i(),G=await W.orchestrateCdcSync(A,{cursors:V,defaultShardKey:n,headers:H,limit:F,tables:q}),fe=g?await g({limit:F,sinceSeq:J}):void 0;return Response.json({global:fe,shards:G.shards},{status:200})},f=async(k,K)=>{const $=we(k,["POST"]);if($)return $;const W=p(k,u,{code:"BAD_REQUEST",message:"Connector sync endpoint requires a `queryCoordinator` on the worker"}),C=await ee(k),V=ar(C.cursor),F=typeof C.limit=="number"&&C.limit>0?C.limit:void 0,J=je(C.tables),{headers:Z}=await m(k,K),H=J??i(),q=await W.orchestrateCdcSync(A,{cursors:V.s,defaultShardKey:n,headers:Z,limit:F,tables:H}),G=[],fe={...V.s};let ae=!1;for(const se of q.shards)ae=dt(G,se.changes??[],ir(F))||ae,fe[se.shardKey]=se.cursor;let _e=V.g;if(g){const se=await g({limit:F,sinceSeq:V.g});ae=dt(G,se.changes,F)||ae,_e=se.cursor}const ke=sr({g:_e,s:fe,v:1}),Ie={changes:G,hasMore:ae,nextCursor:ke};return Response.json(Ie,{status:200})},O=async(k,K)=>{const $=we(k,["POST"]);if($)return $;const W=p(k,u,{code:"BAD_REQUEST",message:"Apply endpoint requires a `queryCoordinator` on the worker"}),C=await ee(k),F=(Array.isArray(C.batches)?C.batches:[]).map(G=>G).filter(G=>G!==null&&typeof G=="object"&&typeof G.shardKey=="string"&&Array.isArray(G.changes)),J=Array.isArray(C.globalChanges)?C.globalChanges:[],{headers:Z}=await m(k,K),H=await W.orchestrateApplyCdc(A,{batches:F,headers:Z}),q=J.length>0&&t?await t({changes:J}):0;return Response.json({applied:H.applied+q,failed:H.failed,ok:H.ok},{status:200})},N=async(k,K)=>{const $=we(k,["POST"]);if($)return $;h(k);const{headers:W}=await m(k,K),C=await T(k,W);return Response.json(C,{headers:{"content-type":"application/json"},status:C.failed.length>0?207:200})},M=async(k,K)=>{const $=we(k,["POST"]);if($)return $;const W=p(k,u,{code:"BAD_REQUEST",message:"Export-tap endpoint requires a `queryCoordinator` on the worker"});if(a===void 0||Object.keys(a).length===0||r===void 0)throw new c("Export-tap endpoint requires `exportSinks` + `exportCursorStore` on the worker",{code:"EXPORT_TAP_NOT_CONFIGURED",status:400});const C=await ee(k),V=typeof C.sink=="string"?C.sink:void 0,F=typeof C.limit=="number"&&C.limit>0?C.limit:void 0,J=je(C.tables);if(V===void 0)throw new c("Export-tap `sink` must name a configured sink",{code:"BAD_REQUEST",status:400});const Z=a[V];if(Z===void 0)throw new c(`Export-tap sink "${V}" is not configured`,{code:"NOT_FOUND",status:404});const{headers:H}=await m(k,K),q=J??i(),G=await or({coordinator:W,cursorStore:r,defaultShardKey:n,headers:H,limit:F,shardDO:A,sink:Z,tables:q});return Response.json(G,{headers:{"content-type":"application/json"},status:200})};return{[co]:O,[io]:f,[oo]:y,[uo]:M,[ao]:N,[so]:_}},po=(e,t)=>{let n;try{n=JSON.parse(e)}catch{return{error:{code:"BAD_ROW",line:t,message:"line is not valid JSON",table:""},ok:!1}}if(!n||typeof n!="object"||Array.isArray(n))return{error:{code:"BAD_ROW",line:t,message:"row must be a JSON object",table:""},ok:!1};const r=n;return typeof r.table!="string"||r.table.length===0?{error:{code:"BAD_ROW",line:t,message:"row is missing `table`",table:""},ok:!1}:!r.doc||typeof r.doc!="object"||Array.isArray(r.doc)?{error:{code:"BAD_ROW",line:t,message:"row is missing or malformed `doc`",table:r.table},ok:!1}:{doc:r.doc,ok:!0,table:r.table}},mo=(e,t,n,r,a)=>{if(n?.mode.kind==="shardBy"&&typeof n.mode.field=="string"){const i=e[n.mode.field];return i==null?{error:{code:"BAD_ROW",line:a,message:`row missing shard field "${n.mode.field}" for table "${t}"`,table:t},ok:!1}:{ok:!0,shardKey:typeof i=="string"?i:JSON.stringify(i)}}return{ok:!0,shardKey:r}},wo=async(e,t,n)=>{if(!e.body)throw new c("Import endpoint requires a request body",{code:"BAD_REQUEST",status:400});const r=[],a=[],i=new Map;let u=0,h=0;const p=e.body.getReader(),m=new TextDecoder;let A="",S=0;const T=g=>{h+=1;const y=g.trim();if(y.length===0)return;u+=1;const _=po(y,h);if(!_.ok){r.push(_.error);return}const{doc:f,table:O}=_,N=t.resolveTableSharding?.(O);if(N?.mode.kind==="global"){a.push({doc:f,line:h,table:O});return}const M=mo(f,O,N,n,h);if(!M.ok){r.push(M.error);return}const k=i.get(M.shardKey);k?k.rows.push({doc:f,table:O}):i.set(M.shardKey,{rows:[{doc:f,table:O}],shardKey:M.shardKey,startLine:h})};for(;;){const{done:g,value:y}=await p.read();if(g)break;if(y&&(S+=y.byteLength,S>Lt))throw await p.cancel().catch(()=>{}),new c("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});A+=m.decode(y,{stream:!0});let _=A.indexOf(`
|
|
5
|
+
`);for(;_!==-1;){const f=A.slice(0,_);A=A.slice(_+1),T(f),_=A.indexOf(`
|
|
6
|
+
`)}}return A.length>0&&T(A),{errors:r,globalRows:a,perShard:i,received:u}},go=e=>e.flatMap(t=>t.error?[{message:t.error.message,shardKey:t.shardKey,timedOut:t.error.timedOut}]:[]),St=(e,t)=>{for(const[n,r]of Object.entries(t.inserted))e.inserted[n]=(e.inserted[n]??0)+r;for(const n of t.errors)e.errors.push({...n});e.conflicts+=t.conflicts},yo=async(e,t,n,r)=>{const a=t.defaultShardKey??"__root__",{errors:i,globalRows:u,perShard:h,received:p}=await wo(e,t,a),m={conflicts:0,errors:i,failed:[],inserted:{}},A=[];if(t.resolveTableSharding===void 0&&h.size>0&&A.push("no `resolveTableSharding` is configured, so every row was routed to the default shard and no row could be recognised as `.global()` — correct for a single-shard app, silent misplacement for a sharded one"),h.size>0){const S=t.queryCoordinator;if(!S)throw new c("Import endpoint requires a `queryCoordinator` on the worker",{code:"BAD_REQUEST",status:400});const T=await S.orchestrateImport(r,{batches:[...h.values()],headers:n});St(m,T),m.failed.push(...go(T.shards))}if(u.length>0)if(t.importGlobals){const S=u[0]?.line??1,T=await t.importGlobals({rows:u,startLine:S});St(m,T)}else for(const S of u)m.errors.push({code:"GLOBAL_NOT_CONFIGURED",line:S.line,message:`row targets global table "${S.table}" but no \`importGlobals\` is configured`,table:S.table});return{conflicts:m.conflicts,errors:m.errors,failed:m.failed,inserted:m.inserted,received:p,...A.length>0?{warnings:A}:{}}},$e=e=>typeof e=="object"&&e!==null?e:{},Ke=e=>typeof e.kind=="string"?e.kind:"unknown",bo=(e,t)=>{let n=$e(t),r=!1;Ke(n)==="optional"&&(r=!0,n=$e(n._meta?.inner));const a=Ke(n),i=n._meta??{},u={kind:a,name:e,optional:r};if(a==="id"&&typeof i.tableName=="string"&&(u.table=i.tableName),a==="array"){const h=Ke($e(i.inner));h!=="unknown"&&(u.element=h)}return u},_o=e=>typeof e!="object"||e===null?[]:Object.entries(e).map(([t,n])=>bo(t,n)).toSorted((t,n)=>t.name.localeCompare(n.name)),Ro="/_lunora/admin/functions",Eo="/_lunora/admin/cron-jobs",Ao="/_lunora/admin/openapi",So="/_lunora/admin/openrpc",To="/_lunora/admin/global/tables",Oo="/_lunora/admin/global/table",vo="/_lunora/admin/global/facet",Tt=e=>{if(e===void 0||e==="")return;let t;try{t=Vn(JSON.parse(e))}catch{return}if(!Array.isArray(t))return;const n=t.flatMap(r=>{if(typeof r!="object"||r===null||typeof r.column!="string")return[];const{column:a,value:i}=r;return[{column:a,value:i}]});return n.length===0?void 0:n},ko=Object.freeze({info:{description:'No OpenAPI spec is configured on this worker. Run `lunora codegen`, then wire the generated module to `createWorker`: `import { openApiSpec } from "./lunora/_generated/openapi"`.',title:"Lunora API",version:"0.0.0"},openapi:"3.1.0",paths:{}}),Io=Object.freeze({info:{description:'No OpenRPC spec is configured on this worker. Run `lunora codegen --api-spec openrpc` (or `both`), then wire the generated module to `createWorker`: `import { openRpcSpec } from "./lunora/_generated/openrpc"`.',title:"Lunora RPC",version:"0.0.0"},methods:[],openrpc:"1.3.2"}),Po=e=>{const{assertAdmin:t,options:n,parsePaging:r,queryParameter:a,requireAdminOption:i}=e,u=g=>{j(g,"GET","Functions");const y=i(g,n.functions,{code:"FUNCTIONS_NOT_CONFIGURED",message:"functions endpoint requires a `functions` registry on the worker"}),_=Object.entries(y).flatMap(([f,O])=>O.visibility==="internal"||O.kind==="stream"?[]:[{args:_o(O.args),kind:O.kind,path:f}]).toSorted((f,O)=>f.path.localeCompare(O.path));return Response.json({functions:_},{headers:{"content-type":"application/json"},status:200})},h=g=>{j(g,"GET","Cron-jobs");const y=i(g,n.cronJobs,{code:"CRON_JOBS_NOT_CONFIGURED",message:"cron-jobs endpoint requires a `cronJobs` map on the worker"}),_=Object.entries(y).flatMap(([f,O])=>O.map(N=>({args:N.args,cron:f,functionPath:N.functionPath,name:N.name,shardKey:N.shardKey,workflow:N.workflow}))).toSorted((f,O)=>f.name.localeCompare(O.name));return Response.json({jobs:_},{headers:{"content-type":"application/json"},status:200})},p=g=>(j(g,"GET","OpenAPI"),t(g),Response.json(n.openApiSpec??ko,{headers:{"content-type":"application/json"},status:200})),m=g=>(j(g,"GET","OpenRPC"),t(g),Response.json(n.openRpcSpec??Io,{headers:{"content-type":"application/json"},status:200})),A=async g=>{j(g,"GET","Global-tables");const y=i(g,n.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"});return Response.json(await y.listTables(),{headers:{"content-type":"application/json"},status:200})},S=async g=>{j(g,"GET","Global-table");const y=i(g,n.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),_=new URL(g.url),f=a(_,"table");if(f===void 0)throw new c("Global-table endpoint requires a `table` query param",{code:"BAD_REQUEST",status:400});const O=await y.readTablePage({...r(g),filters:Tt(a(_,"filters")),table:f});return Response.json(O,{headers:{"content-type":"application/json"},status:200})},T=async g=>{j(g,"GET","Global-facet");const y=i(g,n.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),_=new URL(g.url),f=a(_,"table"),O=a(_,"column");if(f===void 0||O===void 0)throw new c("Global-facet endpoint requires `table` and `column` query params",{code:"BAD_REQUEST",status:400});const N=a(_,"limit"),M=N===void 0?void 0:Number(N),k=await y.facetColumn({column:O,filters:Tt(a(_,"filters")),limit:M!==void 0&&Number.isFinite(M)?M:void 0,table:f});return Response.json(k,{headers:{"content-type":"application/json"},status:200})};return{[Eo]:h,[Ro]:u,[vo]:T,[Oo]:S,[To]:A,[Ao]:p,[So]:m}},No="/_lunora/admin/kv/namespaces",Do="/_lunora/admin/kv/keys",qt="/_lunora/admin/kv/value",Yt=32*1048576,Ot=60,Uo=e=>{const{readJsonBody:t,requireAdminOption:n}=e,r=y=>n(y,e.kvIntrospector,{code:"KV_NOT_CONFIGURED",message:"KV endpoints require a `kvIntrospector` on the worker"}),a=y=>Response.json(y,{headers:{"content-type":"application/json"},status:200}),i=(y,_)=>{const f=new URL(y.url),O=f.searchParams.get("namespace")??"",N=f.searchParams.get("key")??"";if(O==="")throw new c(`KV-value ${_} request requires a \`namespace\` query parameter`,{code:"BAD_REQUEST",status:400});if(N==="")throw new c(`KV-value ${_} request requires a \`key\` query parameter`,{code:"BAD_REQUEST",status:400});return{key:N,namespace:O}},u=async(y,_)=>{if(!(await y.listNamespaces()).some(O=>O.binding===_))throw new c(`Unknown KV namespace binding \`${_}\``,{code:"NOT_FOUND",status:404})},h=async y=>(j(y,"GET","KV-namespaces"),a({namespaces:await r(y).listNamespaces()})),p=async y=>{j(y,"GET","KV-keys");const _=r(y),f=new URL(y.url),O=f.searchParams.get("namespace")??"";if(O==="")throw new c("KV-keys request requires a `namespace` query parameter",{code:"BAD_REQUEST",status:400});const N=f.searchParams.get("prefix")??void 0,M=f.searchParams.get("cursor")??void 0,k=f.searchParams.get("limit"),K=k===null?void 0:Number.parseInt(k,10);if(K!==void 0&&(!Number.isInteger(K)||K<1))throw new c("KV-keys `limit` must be a positive integer",{code:"BAD_REQUEST",status:400});const $=K===void 0?void 0:Math.min(K,1e3);return await u(_,O),a(await _.listKeys({cursor:M,limit:$,namespace:O,prefix:N}))},T={DELETE:async y=>{const _=r(y),f=i(y,"DELETE");return await u(_,f.namespace),await _.deleteKey(f),a({deleted:!0})},GET:async y=>{const _=r(y),f=i(y,"GET");return await u(_,f.namespace),a(await _.getValue(f))},PUT:async y=>{const _=r(y),f=await t(y,Yt);if(typeof f.namespace!="string"||f.namespace==="")throw new c("KV-value PUT request requires a `namespace` string",{code:"BAD_REQUEST",status:400});if(typeof f.key!="string"||f.key==="")throw new c("KV-value PUT request requires a `key` string",{code:"BAD_REQUEST",status:400});if(typeof f.value!="string")throw new c("KV-value PUT request requires a `value` string",{code:"BAD_REQUEST",status:400});if(f.expirationTtl!==void 0&&(typeof f.expirationTtl!="number"||!Number.isInteger(f.expirationTtl)||f.expirationTtl<Ot))throw new c("KV-value PUT `expirationTtl` must be an integer ≥ 60",{code:"BAD_REQUEST",status:400});const O=Math.floor(Date.now()/1e3)+Ot;if(f.expiration!==void 0&&(typeof f.expiration!="number"||!Number.isInteger(f.expiration)||f.expiration<O))throw new c("KV-value PUT `expiration` must be a Unix-seconds timestamp at least 60 seconds in the future",{code:"BAD_REQUEST",status:400});return await u(_,f.namespace),await _.putValue({expiration:f.expiration,expirationTtl:f.expirationTtl,key:f.key,metadata:f.metadata,namespace:f.namespace,value:f.value}),a({ok:!0})}},g=y=>{const _=T[y.method];if(!_)throw new c("KV-value endpoint requires GET, PUT, or DELETE",{code:"METHOD_NOT_ALLOWED",status:405});return _(y)};return{[No]:h,[Do]:p,[qt]:g}},Co="/_lunora/migrate",Bo="/_lunora/admin/pitr",xo="/_lunora/admin/rank",Ho="/_lunora/admin/rankpage",Lo="/_lunora/admin/shard-traffic",Mo=new Set(["__lunora_admin__:migrationStatus","__lunora_admin__:runMigration"]),jo=new Set(["__lunora_admin__:getPitrBookmark","__lunora_admin__:pitrRestore"]),$o=async e=>{const n=await he(e,"Migration")??{};if(typeof n.table!="string"||n.table.length===0)throw new c("Migration request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof n.functionPath!="string"||!Mo.has(n.functionPath))throw new c("Migration request `functionPath` must be a migration admin op",{code:"BAD_REQUEST",status:400});return{args:n.args??{},functionPath:n.functionPath,table:n.table}},Ko=async e=>{const n=await he(e,"Rank")??{};if(typeof n.table!="string"||n.table.length===0)throw new c("Rank request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof n.index!="string"||n.index.length===0)throw new c("Rank request is missing `index`",{code:"BAD_REQUEST",status:400});if(typeof n.partitionKey!="string")throw new c("Rank request `partitionKey` must be a string",{code:"BAD_REQUEST",status:400});if(typeof n.rowId!="string"||n.rowId.length===0)throw new c("Rank request is missing `rowId`",{code:"BAD_REQUEST",status:400});if(!Array.isArray(n.sortValues))throw new c("Rank request `sortValues` must be an array",{code:"BAD_REQUEST",status:400});return{index:n.index,partitionKey:n.partitionKey,rowId:n.rowId,sortValues:n.sortValues,table:n.table}},Fo=e=>{if(e!==void 0){if(!Array.isArray(e)||e.some(t=>t!=="asc"&&t!=="desc"))throw new c('Rank page request `directions` must be an array of "asc"|"desc"',{code:"BAD_REQUEST",status:400});return e}},Go=e=>{if(typeof e.table!="string"||e.table.length===0)throw new c("Rank page request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof e.index!="string"||e.index.length===0)throw new c("Rank page request is missing `index`",{code:"BAD_REQUEST",status:400});if(e.partitionKey!==void 0&&typeof e.partitionKey!="string")throw new c("Rank page request `partitionKey` must be a string",{code:"BAD_REQUEST",status:400});if(e.take!==void 0&&(typeof e.take!="number"||!Number.isFinite(e.take)))throw new c("Rank page request `take` must be a number",{code:"BAD_REQUEST",status:400});if(e.cursor!==void 0&&e.cursor!==null&&typeof e.cursor!="string")throw new c("Rank page request `cursor` must be a string or null",{code:"BAD_REQUEST",status:400})},Qo=async e=>{const n=await he(e,"Rank page")??{};Go(n);const r=Fo(n.directions);return{cursor:typeof n.cursor=="string"?n.cursor:null,directions:r,index:n.index,partitionKey:typeof n.partitionKey=="string"?n.partitionKey:void 0,table:n.table,take:typeof n.take=="number"?n.take:void 0}},zo=async e=>{const n=await he(e,"Shard-traffic")??{};if(typeof n.table!="string"||n.table.length===0)throw new c("Shard-traffic request is missing `table`",{code:"BAD_REQUEST",status:400});return{table:n.table}},Wo=async e=>{const n=await ee(e);if(typeof n.functionPath!="string"||!jo.has(n.functionPath))throw new c("PITR request `functionPath` must be a PITR admin op",{code:"BAD_REQUEST",status:400});if(n.shardKey!==void 0&&typeof n.shardKey!="string")throw new c("PITR `shardKey` must be a string",{code:"BAD_REQUEST",status:400});return{args:n.args??{},functionPath:n.functionPath,shardKey:n.shardKey}},Vo=e=>{const{defaultShard:t,forwardToShard:n,isAdmin:r,queryCoordinator:a,resolveForwardContext:i,shardDO:u}=e,h=(g,y)=>{if(g.method!=="POST")throw new c(`${y} endpoint requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});if(!r(g))throw new c("Admin auth required",{code:"FORBIDDEN",status:403});if(!a)throw new c(`${y} endpoint requires a \`queryCoordinator\` on the worker`,{code:"BAD_REQUEST",status:400});return a},p=async(g,y)=>{const _=h(g,"Migration"),f=await $o(g),{headers:O}=await i(g,y),N=await _.orchestrateMigration(u,{args:f.args,defaultShardKey:t,functionPath:f.functionPath,headers:O,table:f.table});return Response.json(N,{headers:{"content-type":"application/json"},status:200})},m=async(g,y)=>{const _=h(g,"Rank"),f=await Ko(g),{headers:O}=await i(g,y),N=await _.orchestrateRank(u,{headers:O,index:f.index,partitionKey:f.partitionKey,rowId:f.rowId,sortValues:f.sortValues,table:f.table});return Response.json(N,{headers:{"content-type":"application/json"},status:200})},A=async(g,y)=>{const _=h(g,"Rank page"),f=await Qo(g),{headers:O}=await i(g,y),N=await _.orchestrateRankPage(u,{...f,headers:O});return Response.json(N,{headers:{"content-type":"application/json"},status:200})},S=async(g,y)=>{const _=h(g,"Shard-traffic"),f=await zo(g),{headers:O}=await i(g,y),N=await _.orchestrateShardTraffic(u,{headers:O,table:f.table});return Response.json(N,{headers:{"content-type":"application/json"},status:200})},T=async(g,y)=>{if(j(g,"POST","PITR"),!r(g))throw new c("admin PITR endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403});const _=await Wo(g),{headers:f}=await i(g,y),O=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:_.args,functionPath:_.functionPath}),headers:f,method:"POST"});return n(u,_.shardKey??t,O)};return{[Co]:p,[Bo]:T,[xo]:m,[Ho]:A,[Lo]:S}},Jo=1,qo=0,Yo=32,Xo=512,Zo=/^[a-z][\d_a-z*/-]{0,255}(?:@[a-z][\d_a-z*/-]{0,13})?=[\u0020-\u002B\u002D-\u003C\u003E-\u007E]{1,256}$/,ea=e=>{if(e==null)return;const t=e.trim();if(t.length===0||t.length>Xo)return;const n=t.split(",");if(!(n.length>Yo)){for(const r of n)if(!Zo.test(r.trim()))return;return t}},ta=e=>{const t=Fn(e.headers.get("traceparent"));if(t===void 0)return;const n=ea(e.headers.get("tracestate"));return{parentSpanId:t.parentSpanId,sampled:t.sampled,traceId:t.traceId,...n===void 0?{}:{traceState:n}}},na=(e,t={})=>{const n=ta(e),r=t.trustInbound===!0?n:void 0,a=ve(8),i=r?.traceId??ve(16),u=fr(t.sampling,r===void 0?a:i),h=u.isTraced&&(r===void 0||r.sampled);return{decision:u,ignoredUpstream:n!==void 0&&r===void 0,trace:{sampled:h,spanId:a,traceFlags:h?Jo:qo,traceId:i,...r?.parentSpanId===void 0?{}:{parentSpanId:r.parentSpanId},...r?.traceState===void 0?{}:{traceState:r.traceState}}}},ra=(e,t)=>{t.traceparent=Kn(e.traceId,e.spanId,e.sampled),e.traceState!==void 0&&(t.tracestate=e.traceState)},oa=(e,t)=>{let n;return()=>{if(n===void 0){const r=Wn(e),a=t===void 0?void 0:t.cf;n=Gn(zn(r),Qn(r,a))}return n}},aa="/_lunora/admin/scheduled",sa="/_lunora/admin/scheduled/status",ia="/_lunora/admin/scheduled/ws",ca="/_lunora/admin/scheduled/cancel",da="/_lunora/admin/scheduled/dead",ua="/_lunora/admin/scheduled/dead/retry",la="/_lunora/admin/scheduled/dead/cancel",ha="/_lunora/admin/scheduled/pool/release",fa=e=>{const{checkWsAdmin:t,requireSchedulerNamespace:n,resolveSchedulerStub:r,schedulerInstanceName:a}=e,i=(m,A)=>S=>{if(S.method!=="GET")throw new c(`${A} endpoint requires GET`,{code:"METHOD_NOT_ALLOWED",status:405});const T=new URL(S.url).searchParams.get("cursor"),g=T===null||T===""?"":`?cursor=${encodeURIComponent(T)}`;return r(S).fetch(new Request(`https://scheduler.internal${m}${g}`,{method:"GET"}))},u=(m,A,S=A)=>async T=>{if(T.method!=="POST")throw new c(`${S} requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});const g=r(T),y=await he(T,A);if(typeof y?.id!="string"||y.id==="")throw new c(`${A} requires a string \`id\``,{code:"BAD_REQUEST",status:400});return g.fetch(new Request(`https://scheduler.internal${m}`,{body:JSON.stringify({id:y.id}),headers:{"content-type":"application/json"},method:"POST"}))},h=async m=>{if(m.method!=="POST")throw new c("Scheduled pool-release endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const A=r(m),S=await he(m,"Scheduled pool-release");if(typeof S?.pool!="string"||S.pool==="")throw new c("Scheduled pool-release requires a string `pool`",{code:"BAD_REQUEST",status:400});const T=typeof S.id=="string"&&S.id!==""?S.id:void 0;return A.fetch(new Request("https://scheduler.internal/complete",{body:JSON.stringify(T===void 0?{pool:S.pool}:{id:T,pool:S.pool}),headers:{"content-type":"application/json"},method:"POST"}))},p=async m=>{if(m.headers.get("Upgrade")!=="websocket")throw new c("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});if(!await t(m))throw new c("admin authorization required",{code:"ADMIN_FORBIDDEN",status:403});const A=n();return ge(A,a).fetch(new Request("https://scheduler.internal/ws",{headers:{Upgrade:"websocket"}}))};return{[ca]:u("/cancel","Scheduled-cancel","Scheduled-cancel endpoint"),[la]:u("/dead/cancel","Scheduled dead-letter action"),[da]:i("/dead","Scheduled dead-letter"),[ua]:u("/dead/retry","Scheduled dead-letter action"),[aa]:i("/list","Scheduled-list"),[ha]:h,[sa]:i("/status","Scheduler-status"),[ia]:p}},pa=(e,...t)=>{let n=e.cf;for(const r of t){if(typeof n!="object"||n===null)return;n=n[r]}return typeof n=="string"?n:void 0},vt={mtls:e=>pa(e,"tlsClientAuth","certVerified")==="SUCCESS"},ma=e=>e===void 0||e===!1?()=>!1:e===!0?()=>!0:typeof e=="function"?e:(Object.hasOwn(vt,e)?vt[e]:void 0)??(()=>!1),wa=e=>{if(e!==void 0)return()=>{};let t=!1;return()=>{t||(t=!0,console.warn('[lunora] Ignored an inbound `traceparent`, so this request starts a new trace instead of joining the caller\'s. That is the safe default: the header is caller-supplied, and trusting it lets any client choose which trace its spans and logs join. If this worker sits behind a gateway, service mesh, or Cloudflare Access that sets `traceparent` itself, set `trustInboundTraceContext: true` on createWorker() (or `"mtls"` to trust only edge-verified client certificates). Set it to `false` to keep this behaviour and silence this message.'))}},ga="/_lunora/admin/vector/indexes",ya="/_lunora/admin/vector/query",ba=e=>{const{readJsonBody:t,requireAdminOption:n}=e,r=async i=>{j(i,"GET","Vector-indexes");const u=n(i,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});return Response.json({indexes:await u.listIndexes()},{headers:{"content-type":"application/json"},status:200})},a=async i=>{j(i,"POST","Vector-query");const u=n(i,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});if(u.queryIndex===void 0)throw new c("vector index querying is not enabled on this worker",{code:"VECTOR_QUERY_UNSUPPORTED",status:400});const p=await t(i);if(typeof p.name!="string"||p.name==="")throw new c("Vector-query request requires a `name` string",{code:"BAD_REQUEST",status:400});if(typeof p.text!="string"||p.text==="")throw new c("Vector-query request requires a `text` string",{code:"BAD_REQUEST",status:400});if(p.topK!==void 0&&(typeof p.topK!="number"||!Number.isInteger(p.topK)||p.topK<1))throw new c("Vector-query `topK` must be a positive integer",{code:"BAD_REQUEST",status:400});const m=await u.queryIndex({name:p.name,text:p.text,topK:p.topK});return Response.json(m,{headers:{"content-type":"application/json"},status:200})};return{[ga]:r,[ya]:a}},_a="/_lunora/admin/workflows/instances",Ra="/_lunora/admin/workflows/instance",Ea="/_lunora/admin/workflows/status",Aa={complete:!0,errored:!0,paused:!0,queued:!0,running:!0,terminated:!0,unknown:!0,waiting:!0,waitingForPause:!0},Sa=e=>e!==null&&Object.hasOwn(Aa,e)?e:void 0,kt=(e,t)=>{const n=e.searchParams.get(t);if(n===null)return;const r=Number(n);return Number.isInteger(r)&&r>0?r:void 0},Fe=(e,t)=>{const n=e.searchParams.get(t);if(n===null||n==="")throw new c(`Workflows admin endpoint requires a \`${t}\` query parameter`,{code:"BAD_REQUEST",status:400});return n},It=()=>{throw new c("Workflow inspection is unconfigured. Set CLOUDFLARE_ACCOUNT_ID + CLOUDFLARE_API_TOKEN in your .dev.vars to enable it.",{code:"WORKFLOWS_NOT_CONFIGURED",status:501})},Ta=e=>{const{assertAdmin:t,resolveWorkflowsClient:n}=e,r=async(u,h,p)=>{j(u,"GET","Workflows instances"),t(u);const m=n(h);if(!m)return Response.json({configured:!1,instances:[],page:1,perPage:0,totalCount:0});const A=Fe(p,"name"),S=Sa(p.searchParams.get("status"));return Response.json(await m.listInstances({page:kt(p,"page"),perPage:kt(p,"perPage"),status:S,workflowName:A}))},a=async(u,h,p)=>{j(u,"GET","Workflows instance"),t(u);const m=n(h);return m?Response.json(await m.getInstance({instanceId:Fe(p,"id"),workflowName:Fe(p,"name")})):It()},i=async(u,h)=>{j(u,"POST","Workflows status"),t(u);const p=n(h);if(!p)return It();const m=await u.json().catch(()=>{});if(typeof m?.name!="string"||m.name===""||typeof m.id!="string"||m.id==="")throw new c("Workflows status action requires string `name` and `id`",{code:"BAD_REQUEST",status:400});const{action:A}=m;if(A!=="pause"&&A!=="resume"&&A!=="terminate")throw new c("Workflows status action must be one of: pause, resume, terminate",{code:"BAD_REQUEST",status:400});return Response.json(await p.setInstanceStatus({action:A,instanceId:m.id,workflowName:m.name}))};return{[Ra]:a,[_a]:r,[Ea]:i}},Oa={[qt]:Yt,[rr]:nr},Pt="/_lunora/rpc",va="/_lunora/rpc-batch",ka="/_lunora/ws",Ee=(e,t,n)=>({resourceAttributes:oa(e,t),...n===void 0?{}:{waitUntil:n}}),Ge=e=>e?.waitUntil?{waitUntil:t=>e.waitUntil?.(t)}:{},Nt=e=>({spanId:e.spanId,traceFlags:e.traceFlags,traceId:e.traceId,...e.parentSpanId===void 0?{}:{parentSpanId:e.parentSpanId}}),Qe=e=>{const{method:t}=e,n=e.headers.get("user-agent")??void 0;let r;try{r=new URL(e.url)}catch{return{method:t,userAgent:n}}const a=r.port===""?void 0:Number(r.port);return{host:r.hostname,method:t,path:r.pathname,port:Number.isNaN(a)?void 0:a,scheme:r.protocol.replace(":",""),userAgent:n}},Dt="/_lunora/voice/",Ia="/_lunora/scheduler/dispatch",Pa="/_lunora/admin/cron-jobs/run",Na="/_lunora/admin/ws-token",Da="/_lunora/admin/",Ua="/_lunora/migrate",Ca="/_lunora/status",Ba=e=>e.startsWith(Da)||e===Ua,xa="__lunora_relation__:",Ae=e=>{if(e.startsWith(xa))throw new c("`__lunora_relation__:*` is a fan-out-only reserved RPC and cannot be dispatched to a single shard",{code:"FORBIDDEN",status:403})},Se=async e=>await e===!0,Ha=e=>{const t=e.headers.get("x-lunora-userid"),n=e.headers.get("x-lunora-identity");if(!(t===null&&n===null))return{...n===null?{}:{identity:n},...t===null?{}:{userId:t}}},La="/api/auth",Ma="__lunora_admin__:recordAuthEvent",ja="__lunora_admin__:listPushSubscriptions",$a=["/sign-in","/sign-up","/callback"],Ka=(e,t)=>{const n=t.endsWith("/")?t.slice(0,-1):t;if(!e.startsWith(`${n}/`))return!1;const r=e.slice(n.length);return $a.some(a=>r===a||r.startsWith(`${a}/`))},Te=(e,t,n,r)=>{const a=Bn(n),i=a?n.code:"INTERNAL_SERVER_ERROR",u=a?n.status:500,h=n instanceof Error?n.message:String(n);return{durationMs:t,error:{code:i,message:h,status:u},functionPath:e,ok:!1,...r.fanOut?{fanOut:{failed:0,shards:0,table:r.fanOut.table}}:{},...r.shardKey?{shardKey:r.shardKey}:{}}},Fa=e=>{const{exp:t,expiresAtMs:n}=e;if(typeof n=="number"&&Number.isFinite(n))return n;if(typeof t=="number"&&Number.isFinite(t))return t*1e3},Ut=e=>e.waitUntil?{waitUntil:t=>{e.waitUntil?.(t)}}:void 0,Ga=e=>{const t=e?.queue;return typeof t=="string"&&t.length>0?t:"unknown"},qe=new WeakMap,de=async(e,t,n,r=qe.get(e))=>{const a={"content-type":"application/json"},i=e.headers.get("authorization"),u=e.headers.get("cookie"),h=e.headers.get("x-d1-bookmark"),p=e.headers.get("x-lunora-mutation-id"),m=e.headers.get("x-lunora-client-id"),A=e.headers.get("x-lunora-client-seq");i&&(a.authorization=i),u&&(a.cookie=u),h&&(a["x-d1-bookmark"]=h),p&&(a["x-lunora-mutation-id"]=p),m&&(a["x-lunora-client-id"]=m),A&&(a["x-lunora-client-seq"]=A);const S=e.headers.get("cf-connecting-ip");if(S&&(a["x-lunora-client-ip"]=S),!n)return{claims:null,headers:a,identity:null,userId:null};const T=await n(e,t,r);if(!T||typeof T.userId!="string"||T.userId.length===0)return{claims:null,headers:a,identity:null,userId:null};a["x-lunora-userid"]=jn(T.userId);const g=Fa(T);g!==void 0&&(a["x-lunora-identity-exp"]=String(g));const{userId:y,..._}=T,f=Object.keys(_).length>0?_:null;return f&&(a["x-lunora-identity"]=$n(f)),{claims:f,headers:a,identity:T,userId:y}},Qa=new Set(["concat","first","groupBy","max","min","rank","sum","topK"]),za=e=>{if(e===void 0)return;if(!e||typeof e!="object")throw new c("RPC `fanOut` must be an object",{code:"BAD_REQUEST",status:400});const t=e;if(typeof t.table!="string"||t.table.length===0)throw new c("RPC `fanOut.table` must be a non-empty string",{code:"BAD_REQUEST",status:400});if(!t.merge||typeof t.merge!="object")throw new c("RPC `fanOut.merge` must be an object",{code:"BAD_REQUEST",status:400});const n=t.merge;if(typeof n.kind!="string"||!Qa.has(n.kind))throw new c("RPC `fanOut.merge.kind` is not a recognized merge strategy",{code:"BAD_REQUEST",status:400});if(n.kind==="topK"){if(typeof n.k!="number"||!Number.isInteger(n.k)||n.k<0)throw new c("RPC `fanOut.merge.k` must be a non-negative integer",{code:"BAD_REQUEST",status:400});if(typeof n.by!="string"||n.by.length===0)throw new c("RPC `fanOut.merge.by` must be a non-empty string",{code:"BAD_REQUEST",status:400})}return t},Wa=(e,t)=>{e?.LUNORA_DEBUG_RPC&&console.warn(`[lunora:rpc] ${t.fanOut?"fan-out":`shard=${t.shardKey??"(root)"}`} ${t.functionPath}`)},ze=(e,t)=>{if(t.functions===void 0)return;const n=t.functions[e.functionPath]?.x402;if(n){if(e.fanOut)throw new c("a paid (`.x402`) function cannot be fanned out",{code:"BAD_REQUEST",status:400});if(!t.x402Charge)throw new c(`function "${e.functionPath}" is marked paid (.x402) but no x402Charge gate is configured on the worker`,{code:"MISCONFIGURED",status:500});return n}},Va=async e=>{const t=await jt(e);let n;try{n=JSON.parse(t)}catch{throw new c("RPC body must be valid JSON",{code:"BAD_REQUEST",status:400})}if(!n||typeof n!="object"||typeof n.functionPath!="string")throw new c("RPC envelope is missing `functionPath`",{code:"BAD_REQUEST",status:400});const r=n;if(r.args!==void 0&&Mt(r.args,"RPC"),r.shardKey!==void 0&&typeof r.shardKey!="string")throw new c("RPC `shardKey` must be a string",{code:"BAD_REQUEST",status:400});const a=n,i=za(a.fanOut),u=a.args??{};if(i&&a.functionPath.startsWith("__lunora_relation__:")){const h=u.table;if(typeof h=="string"&&h!==i.table)throw new c("RPC `args.table` must match the authorized `fanOut.table` for a relation fan-out",{code:"BAD_REQUEST",status:400});u.table=i.table}return{args:u,fanOut:i,functionPath:a.functionPath,shardKey:a.shardKey}},Oe=new Map,Ja=5e3,qa=4096,Ya=async(e,t)=>{const n=Date.now(),r=Oe.get(t);if(r!==void 0&&r.expiresMs>n)return r.relayCount;r!==void 0&&Oe.delete(t);let a=0;try{const i=await ge(e,t).fetch(new Request("https://shard.internal/_lunora/route"));if(i.ok){const h=(await i.json()).relayCount;typeof h=="number"&&h>0&&(a=Math.floor(h))}}catch{a=0}return Ht(Oe,qa),Oe.set(t,{expiresMs:n+Ja,relayCount:a}),a},Ct=(e,t)=>{if(!(e===null||typeof e!="object"))return Object.entries(e).find(([,n])=>n===t)?.[0]},be=(e,t,n)=>new Request("https://shard.internal/rpc",{body:JSON.stringify({args:t,functionPath:e}),headers:n,method:"POST"}),Xa=["x-lunora-userid","x-lunora-identity","x-lunora-identity-exp"],Za=(e,t)=>{for(const n of Xa){e.delete(n);const r=t[n];r!==void 0&&e.set(n,r)}},Bt=(e,t)=>{const n=new Headers(e.headers),r=[...n.keys()];for(const a of r)a.startsWith("x-lunora-")&&n.delete(a);return Za(n,t),n},es=async(e,t,n)=>e.length===0||n.length===0?!1:Ze(await Gt(e,t),n),xt=(e,t)=>{if(!t||t.length===0)return!1;const n=e.headers.get("authorization");if(!n)return!1;const[r,...a]=n.split(" ");return r?.toLowerCase()!=="bearer"?!1:Ze(t,a.join(" ").trim())},ts=async(e,t,n)=>{if(!t||t.length===0)return!1;const r=new URL(e.url).searchParams.get("token");return r===null?!1:await Lr(t,r)?!0:n?!1:Ze(t,r)},ns=(e,t)=>{if(t===null||typeof t!="object"&&typeof t!="function")return;const n=t;if(typeof n.prepare=="function"&&typeof n.batch=="function"&&typeof n.dump=="function")return ur(`d1:${e}`,t);if(typeof n.list=="function"&&typeof n.head=="function"&&typeof n.createMultipartUpload=="function")return He(`r2:${e}`,!0);if(typeof n.send=="function"&&typeof n.sendBatch=="function"&&typeof n.get!="function")return He(`queue:${e}`,!0);if(typeof n.connectionString=="string")return He(`hyperdrive:${e}`,!0)},rs=e=>{if(e.x402Charge!==void 0&&e.functions===void 0)throw new c("`x402Charge` requires `functions`: paid (.x402) procedures are read from the function registry, so without it every paid procedure would dispatch FREE. Build the worker with `defineApp()` (which supplies the registry) or pass `functions` explicitly.",{code:"MISCONFIGURED",status:500})},Xt=e=>{rs(e);const t=ma(e.trustInboundTraceContext),n=wa(e.trustInboundTraceContext),r=e.defaultShardKey??"__root__",a=lr(e.resolveIdentity,e.identity),i=lt(e.shardDO,e.jurisdiction),u=e.schedulerDO===void 0?void 0:lt(e.schedulerDO,e.jurisdiction);let h=!1;const p=o=>{if(o===void 0||e.jurisdiction===void 0)return o;h||(h=!0,console.warn(`[lunora] jurisdiction "${e.jurisdiction}" pins placement, so region hints (\`shardRegion\`, replica and relay placement) are not sent. Residency wins.`))},m=async(o,s,l,d=e.shardRegion?.(s))=>ge(o,s,p(d)).fetch(l);let A;const S=()=>e.adminToken??A;let T;const g=()=>e.requireEphemeralWsToken??T??!0;let y;const _=o=>{const s=o??{};if(y??=Ct(o,e.shardDO),T===void 0&&e.requireEphemeralWsToken===void 0){const d=s.LUNORA_REQUIRE_EPHEMERAL_WS_TOKEN;typeof d=="string"&&d.length>0&&(T=Br(d,!0))}if(A!==void 0||e.adminToken!==void 0)return;const l=s.LUNORA_ADMIN_TOKEN;typeof l=="string"&&l.length>0&&(A=l)},f=new WeakSet,O=o=>xt(o,S())||f.has(o),N=async o=>{if(!(e.adminGate===void 0||f.has(o)))try{await Se(e.adminGate(o,qe.get(o)))&&f.add(o)}catch{}},M=async(o,s)=>{const l=await de(o,s,e.resolveIdentity);if(f.has(o)&&l.headers.authorization===void 0){const d=S();d!==void 0&&(l.headers.authorization=`Bearer ${d}`)}return l};let k=!1,K=!1;const $=()=>{K||(K=!0,console.warn("[lunora] `replicaReads: true` has no effect without `functions` — read eligibility is decided from the function registry."))},W=o=>{if(!e.allowUnauthenticatedShardAccess){const s=o==="fan-out"?"authorizeFanOut":"authorizeShard";throw new c(`${o} access is default-denied: configure \`${s}\` on the worker, or set \`allowUnauthenticatedShardAccess: true\` to explicitly allow unauthenticated ${o} access (relying solely on per-row RLS).`,{code:o==="fan-out"?"FORBIDDEN_FANOUT":"FORBIDDEN_SHARD",status:403})}k||(k=!0,console.warn([`[lunora] SECURITY: serving ${o} access with \`allowUnauthenticatedShardAccess: true\` and no \`authorizeShard\`/\`authorizeFanOut\` — `,"any caller (including unauthenticated ones) can target any shard / fan out across the table. ","This is safe only if every table is protected by per-row RLS. Configure `authorizeShard`/`authorizeFanOut` to gate it."].join("")))},C=async(o,s)=>{if(s.includes(Ve)||s.includes(Je))throw new c("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403});if(e.authorizeShard){if(!await Se(e.authorizeShard({identity:o,shardKey:s})))throw new c("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else s!==r&&W("shard")},V=Vo({defaultShard:r,forwardToShard:m,isAdmin:O,queryCoordinator:e.queryCoordinator,resolveForwardContext:M,shardDO:i}),F=async(o,s,l,d,w)=>{Ae(o);const b={"content-type":"application/json","x-lunora-system":"1"};return w?.userId!==void 0&&w.userId.length>0&&(b["x-lunora-userid"]=w.userId),w?.identity!==void 0&&w.identity.length>0&&(b["x-lunora-identity"]=w.identity),d!==void 0&&d.length>0&&(b["x-lunora-mutation-id"]=d),m(i,l,be(o,s,b))},J=async(o,s,l,d)=>{const w=l?.[o];if(!w||typeof w.create!="function")throw new c(`${d} targets workflow binding "${o}", which is not bound on env`,{code:"CRON_JOB_FAILED",status:500});if(gr(s))throw new c(`${d} params ${yr}`,{code:"BAD_REQUEST",status:400});await w.create({params:s})},Z=async(o,s)=>{if(o.workflow){await J(o.workflow,o.args??{},s,`cron job "${o.name}"`);return}if(o.functionPath===void 0)throw new c(`cron job "${o.name}" has neither a function target nor a workflow target`,{code:"CRON_JOB_FAILED",status:500});const l=await F(o.functionPath,o.args??{},o.shardKey??r);if(!l.ok)throw new c(`cron job "${o.name}" (${o.functionPath}) failed with shard status ${String(l.status)}`,{code:"CRON_JOB_FAILED",status:500})},H=o=>{if(!O(o))throw new c("admin endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403})},q=(o,s,l)=>{if(H(o),s===void 0)throw new c(l.message,{code:l.code,status:400});return s},G=async(o,s,l,d)=>{const w=e.cronJobs?.[o];if(!w)return 0;for(const b of w)try{await Z(b,s)}catch(I){l.push(d(I))}return w.length},fe=async(o,s)=>{if(H(o),j(o,"POST","cron-jobs run"),!e.cronJobs)throw new c("cron-jobs run endpoint requires a `cronJobs` map on the worker",{code:"CRON_JOBS_NOT_CONFIGURED",status:400});const l=await ee(o),d=typeof l.name=="string"?l.name:"";if(d==="")throw new c("cron-jobs run endpoint requires a job `name`",{code:"BAD_REQUEST",status:400});const w=Object.values(e.cronJobs).flat().find(b=>b.name===d);if(!w)throw new c(`no cron job named "${d}" is registered`,{code:"CRON_JOB_NOT_FOUND",status:404});return await Z(w,s),Response.json({name:d,ran:!0},{status:200})},ae=async o=>{const s=typeof o.pool=="string"&&o.pool.length>0?o.pool:void 0;if(!s||!u||typeof o.id!="string")return;const l=typeof o.instanceName=="string"&&o.instanceName.length>0?o.instanceName:"default";try{await ge(u,l).fetch(new Request("https://scheduler.internal/complete",{body:JSON.stringify({id:o.id,pool:s}),headers:{"content-type":"application/json"},method:"POST"}))}catch{}},_e=async(o,s)=>{j(o,"POST","Scheduler dispatch");const l=await jt(o),d=s??{},w=typeof d.LUNORA_SCHEDULER_SECRET=="string"?d.LUNORA_SCHEDULER_SECRET:void 0,b=e.adminToken??(typeof d.LUNORA_ADMIN_TOKEN=="string"?d.LUNORA_ADMIN_TOKEN:void 0),I=o.headers.get("x-lunora-scheduler-signature");let v=!1;if(I&&w?v=await es(w,l,I):b&&(v=xt(o,b)),!v)throw new c("Scheduler dispatch requires a valid signature or admin bearer",{code:"DISPATCH_UNAUTHENTICATED",status:403});let E;try{E=JSON.parse(l)}catch{throw new c("Scheduler dispatch body must be valid JSON",{code:"BAD_REQUEST",status:400})}const R=E??{},U=R.args??{};if(typeof R.workflow=="string"&&R.workflow.length>0)return await J(R.workflow,U,s,"scheduled workflow"),await ae(R),Response.json({ok:!0},{status:200});if(typeof R.functionPath!="string"||R.functionPath.length===0)throw new c("Scheduler dispatch is missing `functionPath`",{code:"BAD_REQUEST",status:400});const x=typeof R.shardKey=="string"&&R.shardKey.length>0?R.shardKey:r,B=typeof R.id=="string"&&R.id.length>0?R.id:void 0,ne=Ha(o),L=await F(R.functionPath,U,x,B,ne);return await ae(R),L},ke=Kr({assertAdmin:H,getReader:()=>e.authAuditReader}),Ie=async(o,s)=>{H(o);const l=e.notifySubscriptionStore;if(l===void 0)return Response.json({result:We({subscriptions:[]})},{headers:{"content-type":"application/json"},status:200});const d=s?.kind,w=s?.userId,b=s?.limit,I=d==="fcm"||d==="web-push"?d:void 0,v=typeof w=="string"&&w!==""?w:void 0,E=typeof b=="number"&&Number.isFinite(b)?Math.trunc(b):0,R=E>0?Math.min(E,1e3):1e3,x=(await l.list({kind:I,limit:R,userId:v})).filter(B=>I!==void 0&&B.kind!==I?!1:v===void 0||(B.userId??null)===v).map(({keys:B,token:ne,...L})=>L);return Response.json({result:We({subscriptions:x})},{headers:{"content-type":"application/json"},status:200})},se=async(o,s)=>{if(!s.fanOut&&!(s.functionPath!==gt&&s.functionPath!==ja))return await N(o),s.functionPath===gt?ke(o,s.args??{}):Ie(o,s.args)},Zt=fo({applyGlobals:e.applyGlobals,assertAdmin:H,exportCursorStore:e.exportCursorStore,exportSinks:e.exportSinks,defaultShardKey:r,knownTables:()=>[...e.listSchemaTables?.()??[]],queryCoordinator:e.queryCoordinator,requireAdminOption:q,resolveForwardContext:M,shardDO:i,streamExportRows:(o,s,l,d)=>Wt(e,o,s,l,d,i),streamingImport:(o,s)=>yo(o,e,s,i),syncGlobals:e.syncGlobals}),Pe=(o,s)=>{const l=o.searchParams.get(s);return l===null||l===""?void 0:l},Ne=o=>{const s=new URL(o.url),l=s.searchParams.get("limit"),d=s.searchParams.get("offset"),w=l===null?void 0:Number.parseInt(l,10),b=d===null?void 0:Number.parseInt(d,10);return{limit:w!==void 0&&Number.isFinite(w)&&w>=0?w:void 0,offset:b!==void 0&&Number.isFinite(b)&&b>=0?b:void 0}},nt=()=>{if(u===void 0)throw new c("scheduled endpoints require a `schedulerDO` namespace on the worker",{code:"SCHEDULER_NOT_CONFIGURED",status:400});return u},en=fa({checkWsAdmin:async o=>O(o)||ts(o,S(),g()),requireSchedulerNamespace:nt,resolveSchedulerStub:o=>(H(o),ge(nt(),e.schedulerInstanceName??"default")),schedulerInstanceName:e.schedulerInstanceName??"default"}),tn=Ta({assertAdmin:H,resolveWorkflowsClient:e.workflowsClient??(()=>{})}),nn=tr({assertAdmin:H,parsePaging:Ne,queryParameter:Pe,readBodyBytes:qn,requireAdminOption:q,storage:{storageBuckets:e.storageBuckets,storageDelete:e.storageDelete,storageDownload:e.storageDownload,storageList:e.storageList,storageSignedUrl:e.storageSignedUrl,storageUpload:e.storageUpload}}),rn=to({options:e,readJsonBody:ee,requireAdminOption:q}),on=ba({readJsonBody:ee,requireAdminOption:q,vectorIntrospector:e.vectorIntrospector}),an=Uo({kvIntrospector:e.kvIntrospector,readJsonBody:ee,requireAdminOption:q}),sn=hr({logArchive:e.logArchive,readJsonBody:ee,requireAdminOption:q}),cn=Po({assertAdmin:H,options:{cronJobs:e.cronJobs,functions:e.functions,globalIntrospector:e.globalIntrospector,openApiSpec:e.openApiSpec,openRpcSpec:e.openRpcSpec},parsePaging:Ne,queryParameter:Pe,requireAdminOption:q}),dn=o=>{const s=[],l=i??o?.SHARD;if(l!==void 0&&s.push(dr("durable-object:default",l,r)),e.health?.disableBindingProbes!==!0)for(const[d,w]of Object.entries(o??{})){const b=ns(d,w);b!==void 0&&s.push(b)}for(const d of e.health?.probes??[])s.push(d);return s},un=cr({appName:e.health?.appName,appVersion:e.health?.appVersion,auth:e.health?.auth??"public",cacheTtlMs:e.health?.cacheTtlMs,isAdmin:O,resolveProbes:dn}),ln=o=>{const s=e.schedulerInstanceName??"default",l=()=>ge(o,s),d=async(E,R)=>{const U=await l().fetch(new Request(`https://scheduler.internal${E}`,R));if(!U.ok)throw new c(`ctx.scheduler: SchedulerDO ${E} failed (${String(U.status)}): ${await U.text()}`,{code:"INTERNAL",status:500});return await U.json()},w=async(E,R)=>await d(E,{body:JSON.stringify(R),headers:{"content-type":"application/json"},method:"POST"}),b=E=>{const R=E;if(R==null)throw new c("ctx.scheduler: target is required — pass a reference from the generated `internal` / `workflows` / `agents`",{code:"BAD_REQUEST",status:400});if(typeof R.binding=="string"&&R.binding.length>0)return{workflow:R.binding};if(typeof R.__lunoraRef=="string")return{functionPath:R.__lunoraRef};throw new c("ctx.scheduler: expected a reference from the generated `internal` / `workflows` / `agents` — a bare function-path string is refused here, because an HTTP action can be reached unauthenticated",{code:"BAD_REQUEST",status:400})},I=async()=>await br(async E=>d(E===void 0?"/list":`/list?cursor=${encodeURIComponent(E)}`,{method:"GET"})),v=async(E,R,U={})=>{const{id:x}=await w("/schedule",{args:U,scheduledFor:E,...b(R)});return x};return{cancel:async E=>await w("/cancel",{id:E}),get:async E=>await d(`/get?id=${encodeURIComponent(E)}`,{method:"GET"}),list:I,runAfter:async(E,R,U)=>{if(!Number.isFinite(E)||E<0)throw new c("ctx.scheduler.runAfter: `delayMs` must be a non-negative finite number",{code:"INVALID_INPUT",status:400});return await v(Date.now()+E,R,U)},runAt:async(E,R,U)=>{if(!Number.isFinite(E))throw new c("ctx.scheduler.runAt: `date` must be a non-negative finite number",{code:"INVALID_INPUT",status:400});return await v(E,R,U)}}},hn=async(o,s,l)=>{const{claims:d,headers:w,userId:b}=await de(o,s,a),I=async(v,E={})=>{const R=v.__lunoraRef;if(typeof R!="string")throw new c("ctx.run*: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});Ae(R);const U=be(R,E,{...w,"x-lunora-system":"1"}),x=await m(i,r,U),B=await x.json();if(B.error)throw new c(B.error.message??"shard RPC failed",{code:B.error.code??"INTERNAL",status:x.status});return B.result};return{auth:{getIdentity:()=>Promise.resolve(d),userId:b},cache:l.cache,fetch:globalThis.fetch.bind(globalThis),runAction:I,runMutation:I,runQuery:I,...u===void 0?{}:{scheduler:ln(u)},...l.waitUntil===void 0?{}:{waitUntil:l.waitUntil.bind(l)},...e.storage===void 0?{}:{storage:wr(e.storage(s))}}},fn=async(o,s,l)=>{if(!e.httpRouter)return;const d=await hn(o,s,l);try{return await e.httpRouter.fetch(o,{...s,__lunoraCtx:d},l)}catch(w){return console.error("[lunora] httpRouter (SSR) handler threw:",w),new Response("Internal Server Error",{status:500})}},pn=async(o,s,l)=>{if(o.headers.get("Upgrade")!=="websocket")throw new c("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});const d=ft(o,ie);if(d)return d;const w=l.searchParams.get("shard")??r,{headers:b,identity:I}=await de(o,s,a);await C(I,w);const v=Bt(o,b),E=Ct(s,e.shardDO);if(E!==void 0){v.set("x-lunora-shard-binding",E);const R=await Ya(i,w);if(R>0){const U=Pr(w,Math.floor(Math.random()*R));return m(i,U,new Request(o,{headers:v}),pt(o))}}return m(i,w,new Request(o,{headers:v}))},mn=async(o,s,l)=>{const{voiceAgents:d}=e;if(d===void 0)return new Response("Not found",{status:404});if(o.headers.get("Upgrade")!=="websocket")return new Response("Expected a WebSocket upgrade",{headers:{allow:"GET"},status:426});const w=ft(o,ie);if(w)return w;let b;try{b=decodeURIComponent(l.pathname.slice(Dt.length))}catch{return new Response("Unknown voice agent",{status:404})}const I=Object.hasOwn(d,b)?d[b]:void 0;if(I===void 0)return new Response("Unknown voice agent",{status:404});const v=l.searchParams.get("threadKey");if(v===null||v.length===0)return new Response("Missing threadKey",{status:400});const{headers:E,identity:R}=await de(o,s,a);if(e.authorizeShard){if(!await Se(e.authorizeShard({identity:R,shardKey:v})))throw new c("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else W("shard");const U=Bt(o,E);return m(I,v,new Request(o,{headers:U}))},wn=async(o,s,l)=>{if(e.authorizeFanOut){if(!await Se(e.authorizeFanOut(l,o.table,s)))throw new c("Forbidden fan-out",{code:"FORBIDDEN_FANOUT",status:403});return}if(s.startsWith("__lunora_relation__:"))throw new c("reverse cross-backend relation reads (`__lunora_relation__:*`) require `authorizeFanOut` to be configured on the worker",{code:"FORBIDDEN_FANOUT",status:403});if(e.authorizeShard)throw new c("Fan-out requires `authorizeFanOut` to be configured on the worker when `authorizeShard` is set",{code:"FORBIDDEN_FANOUT",status:403});W("fan-out")},Re=async(o,s)=>{if(!(!o.fanOut&&o.functionPath.startsWith("__lunora_admin__:"))){if(o.fanOut){await wn(o.fanOut,o.functionPath,s);return}await C(s,o.shardKey??r)}},gn=(o,s,l)=>{if(e.replicaReads!==!0)return;if(e.functions===void 0){$();return}if(e.functions[s]?.kind!=="query"||l.includes(Je)||l.includes(Ve))return;const d=pt(o);return d===void 0?void 0:{name:Nr(l,d),region:d}},yn=async(o,s,l,d,w)=>{const b=gn(o,s,d);if(b!==void 0){const I={...w,"x-lunora-replica-read":"1",...y===void 0?{}:{"x-lunora-shard-binding":y}},v=Dr(o.headers.get("x-lunora-min-seq"));v!==void 0&&(I["x-lunora-min-seq"]=String(v));const E=await m(i,b.name,be(s,l,I),b.region);if(E.status!==421)return E}return m(i,d,be(s,l,w))},De=async(o,s,l,d,w,b)=>{const I=Date.now(),{observability:v,sampling:E}=e,R=Qe(o),{decision:U,ignoredUpstream:x,trace:B}=na(o,{...E===void 0?{}:{sampling:E},trustInbound:t(o)});x&&n();const ne={...w,"x-lunora-sample-errors":U.keepErrors?"1":"0"};ra(B,ne);try{const L=await yn(o,s,l,d,ne);ce(v,{...R,...Nt(B),durationMs:Date.now()-I,functionPath:s,ok:L.ok,shardKey:d,...L.ok?{}:{error:{code:"SHARD_ERROR",message:`shard returned ${String(L.status)}`,status:L.status}}},b,void 0,{isTraced:B.sampled,keepErrors:U.keepErrors});const te=new Response(L.body,{headers:L.headers,status:L.status,statusText:L.statusText});return te.headers.set("x-lunora-shard-key",d),te}catch(L){throw ce(v,{...R,...Nt(B),...Te(s,Date.now()-I,L,{shardKey:d})},b,void 0,{isTraced:B.sampled,keepErrors:U.keepErrors}),L}},bn=o=>{if(o.fanOut&&o.shardKey)throw new c("RPC envelope cannot set both `shardKey` and `fanOut`",{code:"BAD_REQUEST",status:400});if(o.fanOut||Ae(o.functionPath),o.fanOut&&!e.queryCoordinator)throw new c("RPC envelope set `fanOut` but no `queryCoordinator` is configured on the worker",{code:"BAD_REQUEST",status:400})},_n=async(o,s,l)=>{j(o,"POST","RPC");const d=await Va(o);Wa(s,d),bn(d);const w=await se(o,d);if(w!==void 0)return w;const{headers:b,identity:I}=await de(o,s,a);await Re(d,I);const v=ze(d,e);{const E=Date.now(),{observability:R}=e,U=Qe(o),x=Ee(s,o,l&&(L=>l.waitUntil?.(L)));if(d.fanOut){const L=e.queryCoordinator;if(!L)throw new c("RPC envelope set `fanOut` but no `queryCoordinator` is configured on the worker",{code:"BAD_REQUEST",status:400});try{const te=await L.fanOut(i,{args:d.args??{},fanOut:d.fanOut,functionPath:d.functionPath,headers:b});return ce(R,{durationMs:Date.now()-E,fanOut:{failed:te.failed,shards:te.ok+te.failed,table:d.fanOut.table},functionPath:d.functionPath,...U,ok:!0},x),Response.json(te,{headers:{"content-type":"application/json"},status:200})}catch(te){throw ce(R,{...Te(d.functionPath,Date.now()-E,te,{fanOut:{table:d.fanOut.table}}),...U},x),te}}const B=d.shardKey??r,ne=()=>De(o,d.functionPath,d.args??{},B,b,x);return v&&e.x402Charge?e.x402Charge(o,{functionPath:d.functionPath,price:v.price},ne,Ge(l)):ne()}},Rn=async(o,s,l)=>{j(o,"POST","RPC batch");const d=await ee(o),{calls:w}=d;if(!Array.isArray(w))throw new c("RPC batch `calls` must be an array",{code:"BAD_REQUEST",status:400});const{headers:b,identity:I}=await de(o,s,a),v=ro(w,r);for(const Q of v.values())for(const z of Q)if(e.functions?.[z.functionPath]?.x402)throw new c(`paid (\`.x402\`) function "${z.functionPath}" cannot be called in a batch; dispatch it individually over ${Pt}`,{code:"BAD_REQUEST",status:400});await Promise.all([...v.entries()].flatMap(([Q,z])=>z.map(re=>Re({args:re.args,functionPath:re.functionPath,shardKey:Q},I))));const{observability:E}=e,R=Ee(s,o,l&&(Q=>l.waitUntil?.(Q))),U=Qe(o),x=[],B=[],ne=(Q,z,re,ue)=>({body:{error:{code:re,message:ue}},id:Q.id,status:z}),L=(Q,z,re,ue,pe)=>{for(const Y of Q)ce(E,pe(Y),R),x.push(ne(Y,z,re,ue))},te=(Q,z,re,ue,pe)=>{for(const Y of Q){const me=ue.get(Y.id)??pe,ye=me<400;ce(E,{durationMs:re,functionPath:Y.functionPath,...U,ok:ye,shardKey:z,...ye?{}:{error:{code:"SHARD_ERROR",message:`batched call returned ${String(me)}`,status:me}}},R)}};await Promise.all([...v.entries()].map(async([Q,z])=>{const re=new Headers(b);re.set("content-type","application/json");const ue=new Request("https://shard.internal/rpc-batch",{body:JSON.stringify({calls:z}),headers:re,method:"POST"}),pe=Date.now();let Y;try{Y=await m(i,Q,ue)}catch(X){const xe=Date.now()-pe,{body:it}=xn(X,{fallbackCode:"SHARD_UNAVAILABLE",redactedMessage:"shard unavailable"});L(z,502,it.code,it.message,Cn=>({...Te(Cn.functionPath,xe,X,{shardKey:Q}),...U}));return}const me=Date.now()-pe,ye=Y.headers.get("x-d1-bookmark");ye&&B.push(ye);let Ce;try{Ce=await Y.json()}catch{const X=`shard batch returned a non-JSON response (${String(Y.status)})`;L(z,Y.status,"SHARD_ERROR",X,xe=>({durationMs:me,error:{code:"SHARD_ERROR",message:X,status:Y.status},functionPath:xe.functionPath,...U,ok:!1,shardKey:Q}));return}const Be=Array.isArray(Ce.results)?Ce.results:[],Dn=new Map(Be.map(X=>[X.id,X.status??Y.status])),Un=new Set(Be.map(X=>X.id));te(z,Q,me,Dn,Y.status),x.push(...Be);for(const X of z)Un.has(X.id)||x.push(ne(X,Y.status,"SHARD_ERROR",`shard batch omitted result for call ${String(X.id)}`))}));const at={"content-type":"application/json"},[st]=B;return B.length===1&&st!==void 0&&(at["x-d1-bookmark"]=st),Response.json({results:x},{headers:at,status:200})},En=async(o,s,l,d={},w={})=>{try{const b=l.__lunoraRef;if(typeof b!="string")throw new c("serverQuery: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});Ae(b);const{headers:I,identity:v}=await de(o,s,a,w.context),E={args:d,functionPath:b,shardKey:w.shardKey};await Re(E,v);const R=w.shardKey??r,U=Ee(s,o,w.waitUntil),x=()=>De(o,b,d,R,I,U),B=ze(E,e);return B&&e.x402Charge?await e.x402Charge(o,{functionPath:b,price:B.price},x,Ge(w.waitUntil?{waitUntil:w.waitUntil}:w.context)):await x()}catch(b){return ct(b)}},rt=async(o,s,l)=>{const{observability:d}=e,w=Date.now(),b=ve(16),I=ve(8),v=Ut(s);try{const E=await l();return ce(d,{durationMs:Date.now()-w,functionPath:o,ok:!0,spanId:I,traceId:b},v),E}catch(E){throw ce(d,{...Te(o,Date.now()-w,E,{}),spanId:I,traceId:b},v),E}finally{ut(d,v)}},An=async(o,s,l)=>{_(s);const d=[],w=R=>R instanceof Error?R:new Error(String(R)),b=e.crons?.[o.cron];if(b)try{await b(o,s,l)}catch(R){d.push(w(R))}const I=await G(o.cron,s,d,w),v=!!e.backupStore&&e.backupCron!==void 0&&e.backupCron===o.cron;if(v)try{await Yr(e,i,S(),o)}catch(R){d.push(w(R))}if(!b&&I===0&&!v){const R=[...new Set([...Object.keys(e.crons??{}),...Object.keys(e.cronJobs??{})])];console.warn(`[lunora] scheduled("${o.cron}") fired but no cron handler is registered for that expression. Registered: ${R.length===0?"(none)":R.join(", ")}. Check that \`triggers.crons\` in wrangler.jsonc matches the app's cron definitions.`)}const[E]=d;if(d.length===1&&E)throw E;if(d.length>1)throw new AggregateError(d,`scheduled("${o.cron}") had ${String(d.length)} failure(s)`)},Sn=async(o,s)=>{try{const l=o??{},d=e.adminToken??(typeof l.LUNORA_ADMIN_TOKEN=="string"?l.LUNORA_ADMIN_TOKEN:void 0);if(!d||d.length===0)return;await m(i,r,be(Ma,{outcome:s},{authorization:`Bearer ${d}`,"content-type":"application/json"}))}catch{}},Tn=async(o,s,l,d)=>{if(!e.authHandler)return;const w=await e.authHandler(o);if(!w)return;const b=e.authBasePath??La;return Ka(l.pathname,b)&&d.waitUntil?.(Sn(s,w.status>=400?"fail":"ok")),w},On=async({args:o,env:s,functionPath:l,request:d,shardKey:w,waitUntil:b})=>{Mt(o,"REST");const I={functionPath:l,...w===void 0?{}:{shardKey:w}},{headers:v,identity:E}=await de(d,s,a);await Re(I,E);const R=w??r,U=Ee(s,d,b),x=()=>De(d,l,o,R,v,U),B=ze(I,e);return B&&e.x402Charge?e.x402Charge(d,{functionPath:l,price:B.price},x,Ge({waitUntil:b})):x()},vn=Jn({functions:e.functions??{},invoke:On,readJsonBody:ee,edgeCache:e.restEdgeCache,...e.restRateLimit?{rateLimit:e.restRateLimit}:{}}),Ue=e.routes!==void 0&&Object.keys(e.routes).length>0?e.routes:void 0,kn={[Ca]:o=>o.method!=="GET"&&o.method!=="HEAD"?new Response(void 0,{headers:{allow:"GET, HEAD"},status:405}):Response.json({ok:!0},{headers:{"cache-control":"no-store"}}),[ka]:(o,s,l)=>pn(o,s,l),[Pt]:(o,s,l,d)=>_n(o,s,d),[va]:(o,s,l,d)=>Rn(o,s,d),[Ia]:(o,s)=>_e(o,s),[Pa]:(o,s)=>fe(o,s),[Na]:async o=>{j(o,"POST","ws-token"),H(o);const s=S();if(s===void 0)throw new c("ws-token minting requires a configured admin token",{code:"ADMIN_TOKEN_NOT_CONFIGURED",status:400});const l=await Hr(s);return Response.json(l,{headers:{"cache-control":"no-store"}})},...V,...Zt,...en,...tn,...nn,...rn,...on,...an,...sn,...cn,...un,...vn,...$r({assertAdmin:H,getAuthAdmin:()=>e.authAdmin,parsePaging:Ne,queryParameter:Pe,readJsonBody:ee})};let ie=ht(e.security),ot=!1;const In=o=>{ot||(ot=!0,ie=ht(e.security,o??{}))},Pn=async(o,s)=>{Ba(s)&&await N(o)},Nn=async(o,s,l)=>{qe.set(o,l);const d=new URL(o.url);if(o.method==="POST"||o.method==="PUT"){const v=Number(o.headers.get("content-length")??""),E=Oa[d.pathname]??Lt;if(Number.isFinite(v)&&v>E)throw new c("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413})}const w=await Tn(o,s,d,l);if(w)return w;if(Ue){const v=`${o.method} ${d.pathname}`,E=Ue[v]??Ue[d.pathname];if(E)return E(o,s,l)}const b=kn[d.pathname];if(b)return await Pn(o,d.pathname),b(o,s,d,l);if(e.voiceAgents!==void 0&&d.pathname.startsWith(Dt))return mn(o,s,d);const I=await fn(o,s,l);return I||new Response("Not found",{status:404})};return{async fetch(o,s,l){e.passThroughOnException&&l.passThroughOnException?.(),In(s),_(s);const d=pr(o,ie);if(d)return d;const w=mr(o,ie);if(w)return Le(w,o,ie);try{const b=await Nn(o,s,l);return Le(b,o,ie)}catch(b){return Le(ct(b),o,ie)}finally{ut(e.observability,Ut(l))}},async queue(o,s,l){await rt(`queue:${Ga(o)}`,l,async()=>{await e.queue?.(o,s,l)})},async scheduled(o,s,l){await rt(`cron:${o.cron}`,l,async()=>{await An(o,s,l)})},serverQuery:En}},os=e=>Xt(e),as=e=>typeof e=="function"?{fetch:e}:e,ss=e=>!!(e.crons??e.cronJobs??e.backupCron),ks=(e,t)=>{const n=as(e),r=typeof e=="object"&&typeof e.scheduled=="function"?e.scheduled:void 0,a=u=>{const h=os({...u,httpRouter:n});return r!==void 0&&!ss(u)?{...h,scheduled:async(p,m,A)=>{await r(p,m,A)}}:h};if(typeof t!="function")return a(t);const i=t;return{fetch:(u,h,p)=>a(i(h)).fetch(u,h,p),queue:(u,h,p)=>a(i(h)).queue?.(u,h,p)??Promise.resolve(),scheduled:(u,h,p)=>a(i(h)).scheduled(u,h,p),serverQuery:(u,h,p,m,A)=>a(i(h)).serverQuery(u,h,p,m,A)}},is=(e,t)=>{if(typeof e=="function")return e(t);const n=e.shardDO??t?.SHARD;if(!n)throw new c("@lunora/runtime: no shard Durable Object namespace found. Bind `SHARD` in wrangler.jsonc, or pass `createLunoraHandler({ shardDO: env.MY_SHARD })`.");return{...e,shardDO:n}},Is=(e={})=>(t,n,r)=>Xt(is(e,n)).fetch(t,n,r??Hn),Ps=e=>e;export{gt as GET_AUTH_AUDIT_LOG_OP,Hn as NOOP_EXECUTION_CONTEXT,Us as composeIdentityResolvers,os as composeWorker,Is as createLunoraHandler,Xt as createWorker,Ps as defineRpcEnvelope,Ya as probeRelayCount,is as resolveLunoraOptions,Cs as routeIdentityResolvers,ks as withFrameworkWorker};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/runtime",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.92",
|
|
4
4
|
"description": "Lunora Worker runtime: the RPC router, shard resolver, and query coordinator",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cloudflare",
|
|
@@ -46,10 +46,10 @@
|
|
|
46
46
|
"access": "public"
|
|
47
47
|
},
|
|
48
48
|
"dependencies": {
|
|
49
|
-
"@lunora/bindings": "1.0.0-alpha.
|
|
50
|
-
"@lunora/errors": "1.0.0-alpha.
|
|
51
|
-
"@lunora/observability": "1.0.0-alpha.
|
|
52
|
-
"@lunora/platform": "1.0.0-alpha.
|
|
49
|
+
"@lunora/bindings": "1.0.0-alpha.49",
|
|
50
|
+
"@lunora/errors": "1.0.0-alpha.31",
|
|
51
|
+
"@lunora/observability": "1.0.0-alpha.56",
|
|
52
|
+
"@lunora/platform": "1.0.0-alpha.26"
|
|
53
53
|
},
|
|
54
54
|
"peerDependencies": {
|
|
55
55
|
"@lunora/shard-engine": ">=1.0.0-alpha.24 <2.0.0-0",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as T}from"./LunoraError-DksAgIpa.mjs";import{m as A}from"./method-guard-BG_vJNTl.mjs";import{resolveShard as R}from"./applyJurisdiction-C0ddU7Tg.mjs";const C="/_lunora/health",H="/_lunora/health/ready",N=t=>t==="liveness"?["liveness"]:t==="readiness"?["readiness"]:["liveness","readiness"];class P{#e=new Map;addChecker(e,s,r){this.#e.set(e,{run:s,types:r.type})}async getReport(e){const s=[...this.#e].filter(([,a])=>e===void 0||a.types.includes(e)),r=await Promise.all(s.map(async([a,o])=>[a,await o.run()]));return{healthy:r.every(([,a])=>a.health.healthy),report:Object.fromEntries(r)}}}const S=t=>{const e=new P,s=new Set;for(const r of t)r.critical&&s.add(r.name),e.addChecker(r.name,async()=>{let a;try{a=await r.check()}catch(o){a={healthy:!1,message:o instanceof Error?o.message:"probe failed"}}return{health:{healthy:a.healthy,...a.message===void 0?{}:{message:a.message}}}},{type:N(r.kind)});return{criticalNames:s,registry:e}},_=(t,e)=>{const s=t.includes(":")?t.slice(0,t.indexOf(":")):"probe",r=(e.get(s)??0)+1;return e.set(s,r),r===1?s:`${s}#${String(r)}`},j=(t,e)=>t?"unhealthy":e?"degraded":"healthy",M=(t,e,s,r,a)=>{const o=[];let u=!1,d=!1;const y=new Map;for(const[h,i]of Object.entries(t)){const n=e.has(h),c=i.health.healthy;d=d||!c,u=u||!c&&n;const l=s==="admin"?h:_(h,y);o.push({critical:n,...s==="admin"&&i.health.message!==void 0?{message:i.health.message}:{},name:l,status:c?"up":"down"})}return o.sort((h,i)=>h.name.localeCompare(i.name)),{anyCriticalDown:u,body:{appName:r,appVersion:a,checks:o,status:j(u,d),timestamp:new Date().toISOString()}}},G=t=>{const{appName:e="lunora",appVersion:s="0.0.0",auth:r="public",cacheTtlMs:a,isAdmin:o,resolveProbes:u}=t,d=n=>a!==void 0?a:n==="readiness"?0:r==="public"?5e3:0,y={},h=n=>{if(r==="admin"&&!o(n))throw new T("health endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403})},i=async(n,c,l)=>{const p=A(n,["GET","HEAD"]);if(p)return p;h(n);const f=d(l);if(f>0){const m=y[l];if(m!==void 0&&Date.now()<m.expiresAt)return Response.json(m.body,{headers:{"cache-control":"no-store"},status:m.down?503:200})}const{criticalNames:b,registry:v}=S(u(c)),{healthy:E,report:k}=await v.getReport(l==="readiness"?"readiness":void 0),{anyCriticalDown:D,body:g}=M(k,b,r,e,s),w=l==="readiness"?!E:D;return f>0&&(y[l]={body:g,down:w,expiresAt:Date.now()+f}),Response.json(g,{headers:{"cache-control":"no-store"},status:w?503:200})};return{[C]:(n,c)=>i(n,c,"aggregate"),[H]:(n,c)=>i(n,c,"readiness")}},I=(t,e,s)=>({check:async()=>{try{return await R(e,s).fetch(new Request("https://shard.internal/_lunora/status",{method:"GET"})),{healthy:!0}}catch{return{healthy:!1,message:"durable object unreachable"}}},critical:!0,name:t}),q=(t,e)=>({check:async()=>{try{return await e.prepare("SELECT 1").first(),{healthy:!0}}catch{return{healthy:!1,message:"d1 query failed"}}},critical:!0,name:t}),B=(t,e)=>({check:()=>e?{healthy:!0}:{healthy:!1,message:"binding not configured"},critical:!1,name:t});export{C as HEALTH_PATH,H as HEALTH_READY_PATH,G as buildHealthRoutes,q as d1Probe,I as durableObjectProbe,B as presenceProbe};
|
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
import{isLunoraError as Nn,toErrorBody as Un}from"@lunora/errors";import{e as Bt}from"./evict-oldest-BNXsKx4s.mjs";import{NOOP_EXECUTION_CONTEXT as Cn}from"./NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{t as Bn,f as xn}from"./base64-Bl1_r2k1.mjs";import{e as Hn,a as Ln}from"./identity-header-C4Z5pldl.mjs";import{o as Oe,b as jn,p as Mn,m as $n,d as Kn,a as Fn,r as Gn}from"./otlp-resource-DeXhb949.mjs";import{e as ze,d as Qn}from"./wire-codec-DBWN80s9.mjs";import{d as Z,e as be,M as xt,b as zn,f as Wn,g as Ht,h as Lt}from"./rest-routes-CpwDstbq.mjs";import{LunoraError as d,toErrorResponse as it}from"./LunoraError-DksAgIpa.mjs";import{a as $,m as me}from"./method-guard-BG_vJNTl.mjs";import{normalizeBackupPrefix as qe,BACKUP_KEY_PREFIX as Ye,isBackupManifestKey as Vn,backupObjectKeyOfManifest as jt,backupObjectKey as Jn,backupManifestKey as qn}from"./BACKUP_KEY_PREFIX-BOtSu-_3.mjs";import{toHex as Yn,buildStorageAdminRoutes as Xn,STORAGE_UPLOAD_MAX_BODY_BYTES as Zn,STORAGE_PATH as er}from"./STORAGE_UPLOAD_MAX_BODY_BYTES-BqyO-1l6.mjs";import{b as tr,e as nr,f as ct,g as rr,h as or}from"./export-tap-H6oPBoSr.mjs";import{buildHealthRoutes as ar,durableObjectProbe as sr,d1Probe as ir,presenceProbe as xe}from"./HEALTH_PATH-jZsuCmSs.mjs";import{wrapResolverWithContract as cr}from"./composeIdentityResolvers-BHZ4jH8o.mjs";import{composeIdentityResolvers as Is,routeIdentityResolvers as Ps}from"./composeIdentityResolvers-BHZ4jH8o.mjs";import{buildLogArchiveAdminRoutes as dr}from"./LOG_ARCHIVE_PATH-Hmjpz_Ko.mjs";import{r as ur,f as dt,a as ie}from"./observability-B1hLjwgx.mjs";import{resolveShard as we,applyJurisdiction as ut}from"./applyJurisdiction-C0ddU7Tg.mjs";import{resolveSecurity as lt,handleCorsPreflight as lr,enforceOrigin as hr,decorateResponse as He,enforceWebSocketOrigin as ht}from"./decorateResponse-CCRm2CFM.mjs";const fr=e=>{const t=e??{};if(typeof t.bucket=="function")return t;const n=t.bucketName,a={...t,bucketName:typeof n=="string"&&n!==""?n:"default"};return a.bucket=()=>a,a},Mt="__lunoraBranch",pr=e=>typeof e=="object"&&e!==null&&Object.hasOwn(e,Mt),mr=`may not contain the reserved workflow branch-marker key ("${Mt}")`,wr=async e=>{const t=[];let n;for(;;){const r=await e(n);if(t.push(...Array.isArray(r.records)?r.records:[]),r.truncated!==!0||typeof r.cursor!="string"||r.cursor.length===0)return t;if(r.cursor===n)throw new Error("collectPages: the list did not advance its cursor — refusing to page forever");n=r.cursor}},Xe=(e,t)=>{const n=Math.max(e.length,t.length);let r=e.length^t.length;for(let a=0;a<n;a+=1){const i=a<e.length?e.charCodeAt(a):0,u=a<t.length?t.charCodeAt(a):0;r|=i^u}return r===0},gr=(e,t,n,r)=>{const a=e.get(t);if(a!==void 0)return a;Bt(e,r);const i=n().catch(u=>{throw e.get(t)===i&&e.delete(t),u});return e.set(t,i),i},Ze=new TextEncoder,yr=Array.from({length:32},(e,t)=>t);new RegExp(`[${yr.map(e=>String.fromCodePoint(e)).join("")}]`,"u");const br=64,_r=new Map,$t=async e=>gr(_r,e,async()=>crypto.subtle.importKey("raw",Ze.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]),br),Kt=async(e,t)=>{const n=await $t(e),r=await crypto.subtle.sign("HMAC",n,Ze.encode(t));return Bn(new Uint8Array(r))},Rr=async(e,t,n)=>{const r=await $t(e);return crypto.subtle.verify("HMAC",r,n,Ze.encode(t))},Er=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"];new Set(Er);const Sr=new Set(["AE","BH","IL","IQ","IR","JO","KW","LB","OM","PS","QA","SA","SY","TR","YE"]),Ar=-100,Tr=15,Or=e=>{const t=Number(e.longitude??Number.NaN);switch(e.continent){case"AF":return"afr";case"AS":return e.country!==void 0&&Sr.has(e.country)?"me":"apac";case"EU":return Number.isFinite(t)&&t>Tr?"eeur":"weur";case"NA":return Number.isFinite(t)&&t<Ar?"wnam":"enam";case"OC":return"oc";case"SA":return"sam";default:return}},ft=e=>{const t=e.cf;return t===void 0?void 0:Or(t)},We="::relay::",vr=(e,t)=>`${e}${We}${String(t)}`,Ve="::replica::",kr=(e,t)=>`${e}${Ve}${t}`,Ir=e=>{if(e==null||!/^\d+$/.test(e))return;const t=Number.parseInt(e,10);return Number.isSafeInteger(t)&&t>0?t:void 0},Pr=new Set(["1","enabled","on","true","yes"]),Dr=new Set(["0","disabled","false","no","off"]),Nr=(e,t)=>{const n=(e??"").trim().toLowerCase();return Pr.has(n)?!0:Dr.has(n)?!1:t},Ft="v1",Ur=6e4,Cr=async(e,t={})=>{const n=(t.now??Date.now())+(t.ttlMs??Ur),r=`${Ft}.${String(n)}`,a=await Kt(e,r);return{expiresAtMs:n,token:`${r}.${a}`}},Br=async(e,t,n=Date.now())=>{if(e.length===0||t.length===0)return!1;const r=t.split(".");if(r.length!==3)return!1;const[a,i,u]=r;if(a!==Ft||u.length===0)return!1;const h=Number(i);if(!Number.isFinite(h)||h<=n)return!1;let f;try{f=xn(u)}catch{return!1}return Rr(e,`${a}.${i}`,f)},P="/_lunora/admin/auth",xr={INVITER_REQUIRED:400,ORG_SLUG_INVALID:400,ORG_SLUG_TAKEN:409,PASSWORD_TOO_LONG:400,PASSWORD_TOO_SHORT:400,USER_ALREADY_EXISTS:409,USER_NOT_FOUND:404},N=(e,t)=>{const n=e[t];if(typeof n!="string"||n==="")throw new d(`\`${t}\` is required`,{code:"BAD_REQUEST",status:400});return n},he=(e,t)=>{const n=e(t);if(n===void 0)throw new d(`\`${t}\` query parameter is required`,{code:"BAD_REQUEST",status:400});return n},Gt=e=>{if(typeof e=="string"||Array.isArray(e)&&e.every(t=>typeof t=="string"))return e},re=(e,t)=>typeof e[t]=="string"?e[t]:void 0,Le=(e,t)=>{const n=e[t];return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:void 0},pt=e=>{const t=Gt(e.role);if(t===void 0||typeof t=="string"&&t.trim()==="")throw new d("`role` is required",{code:"BAD_REQUEST",status:400});return t},mt=e=>{const t=e.permission;if(typeof t!="object"||t===null||Array.isArray(t))throw new d("`permission` object is required",{code:"BAD_REQUEST",status:400});const n={};for(const[r,a]of Object.entries(t))Array.isArray(a)&&a.every(i=>typeof i=="string")&&(n[r]=a);return n},Hr={[`${P}/capabilities`]:{build:()=>({}),http:"GET",method:"capabilities"},[`${P}/users`]:{build:({paging:e,query:t})=>{const n=t("sortDirection");return{...e,filterField:t("filterField"),filterValue:t("filterValue"),search:t("search"),searchField:t("searchField"),sortBy:t("sortBy"),sortDirection:n==="asc"||n==="desc"?n:void 0}},http:"GET",method:"listUsers"},[`${P}/sessions`]:{build:({paging:e,query:t})=>({...e,userId:t("userId")}),http:"GET",method:"listSessions"},[`${P}/accounts`]:{build:({query:e})=>({userId:he(e,"userId")}),http:"GET",method:"listAccounts"},[`${P}/passkeys`]:{build:({query:e})=>({userId:he(e,"userId")}),http:"GET",method:"listPasskeys"},[`${P}/organizations`]:{build:({paging:e})=>({...e}),http:"GET",method:"listOrganizations"},[`${P}/organizations/members`]:{build:({paging:e,query:t})=>({...e,organizationId:he(t,"organizationId")}),http:"GET",method:"listMembers"},[`${P}/organizations/invitations`]:{build:({paging:e,query:t})=>({...e,organizationId:he(t,"organizationId")}),http:"GET",method:"listInvitations"},[`${P}/config`]:{build:()=>({}),http:"GET",method:"config"},[`${P}/organizations/teams`]:{build:({paging:e,query:t})=>({...e,organizationId:he(t,"organizationId")}),http:"GET",method:"listTeams"},[`${P}/organizations/teams/members`]:{build:({paging:e,query:t})=>({...e,teamId:he(t,"teamId")}),http:"GET",method:"listTeamMembers"},[`${P}/organizations/roles`]:{build:({paging:e,query:t})=>({...e,organizationId:he(t,"organizationId")}),http:"GET",method:"listOrgRoles"},[`${P}/users/create`]:{build:({body:e})=>({data:Le(e,"data"),email:N(e,"email"),name:N(e,"name"),password:re(e,"password"),role:Gt(e.role)}),http:"POST",method:"createUser"},[`${P}/users/update`]:{build:({body:e})=>{const{data:t}=e;if(typeof t!="object"||t===null||Array.isArray(t))throw new d("`data` object is required",{code:"BAD_REQUEST",status:400});return{data:t,userId:N(e,"userId")}},http:"POST",method:"updateUser"},[`${P}/users/role`]:{build:({body:e})=>({role:pt(e),userId:N(e,"userId")}),http:"POST",method:"setRole"},[`${P}/users/ban`]:{build:({body:e})=>({expiresInSeconds:typeof e.expiresInSeconds=="number"?e.expiresInSeconds:void 0,reason:re(e,"reason"),userId:N(e,"userId")}),http:"POST",method:"banUser"},[`${P}/users/unban`]:{build:({body:e})=>({userId:N(e,"userId")}),http:"POST",method:"unbanUser"},[`${P}/users/password`]:{build:({body:e})=>({newPassword:N(e,"newPassword"),userId:N(e,"userId")}),http:"POST",method:"setUserPassword",returns:"void"},[`${P}/users/remove`]:{build:({body:e})=>({userId:N(e,"userId")}),http:"POST",method:"removeUser",returns:"void"},[`${P}/users/impersonate`]:{build:({body:e})=>({userId:N(e,"userId")}),http:"POST",method:"impersonateUser"},[`${P}/sessions/revoke`]:{build:({body:e})=>({sessionId:N(e,"sessionId")}),http:"POST",method:"revokeUserSession",returns:"void"},[`${P}/sessions/revoke-all`]:{build:({body:e})=>({userId:N(e,"userId")}),http:"POST",method:"revokeUserSessions",returns:"void"},[`${P}/accounts/unlink`]:{build:({body:e})=>({accountId:N(e,"accountId"),userId:N(e,"userId")}),http:"POST",method:"unlinkAccount",returns:"void"},[`${P}/two-factor/disable`]:{build:({body:e})=>({userId:N(e,"userId")}),http:"POST",method:"disableTwoFactor",returns:"void"},[`${P}/passkeys/delete`]:{build:({body:e})=>({passkeyId:N(e,"passkeyId")}),http:"POST",method:"deletePasskey",returns:"void"},[`${P}/organizations/members/remove`]:{build:({body:e})=>({memberId:N(e,"memberId")}),http:"POST",method:"removeMember",returns:"void"},[`${P}/organizations/invitations/cancel`]:{build:({body:e})=>({invitationId:N(e,"invitationId")}),http:"POST",method:"cancelInvitation",returns:"void"},[`${P}/organizations/create`]:{build:({body:e})=>({logo:re(e,"logo"),metadata:Le(e,"metadata"),name:N(e,"name"),ownerId:re(e,"ownerId"),slug:re(e,"slug")}),http:"POST",method:"createOrganization"},[`${P}/organizations/update`]:{build:({body:e})=>({logo:re(e,"logo"),metadata:Le(e,"metadata"),name:re(e,"name"),organizationId:N(e,"organizationId"),slug:re(e,"slug")}),http:"POST",method:"updateOrganization"},[`${P}/organizations/remove`]:{build:({body:e})=>({organizationId:N(e,"organizationId")}),http:"POST",method:"deleteOrganization",returns:"void"},[`${P}/organizations/members/add`]:{build:({body:e})=>({organizationId:N(e,"organizationId"),role:re(e,"role"),userId:N(e,"userId")}),http:"POST",method:"addMember"},[`${P}/organizations/members/invite`]:{build:({body:e})=>({email:N(e,"email"),inviterId:re(e,"inviterId"),organizationId:N(e,"organizationId"),role:re(e,"role")}),http:"POST",method:"inviteMember"},[`${P}/organizations/members/role`]:{build:({body:e})=>({memberId:N(e,"memberId"),role:pt(e)}),http:"POST",method:"updateMemberRole"},[`${P}/organizations/teams/create`]:{build:({body:e})=>({name:N(e,"name"),organizationId:N(e,"organizationId")}),http:"POST",method:"createTeam"},[`${P}/organizations/teams/update`]:{build:({body:e})=>({name:N(e,"name"),teamId:N(e,"teamId")}),http:"POST",method:"updateTeam"},[`${P}/organizations/teams/remove`]:{build:({body:e})=>({teamId:N(e,"teamId")}),http:"POST",method:"removeTeam",returns:"void"},[`${P}/organizations/teams/members/add`]:{build:({body:e})=>({teamId:N(e,"teamId"),userId:N(e,"userId")}),http:"POST",method:"addTeamMember"},[`${P}/organizations/teams/members/remove`]:{build:({body:e})=>({teamMemberId:N(e,"teamMemberId")}),http:"POST",method:"removeTeamMember",returns:"void"},[`${P}/organizations/roles/create`]:{build:({body:e})=>({organizationId:N(e,"organizationId"),permission:mt(e),role:N(e,"role")}),http:"POST",method:"createOrgRole"},[`${P}/organizations/roles/update`]:{build:({body:e})=>({permission:mt(e),roleId:N(e,"roleId")}),http:"POST",method:"updateOrgRole"},[`${P}/organizations/roles/remove`]:{build:({body:e})=>({roleId:N(e,"roleId")}),http:"POST",method:"deleteOrgRole",returns:"void"}},Lr=e=>{const t=async a=>{try{return await a()}catch(i){if(i instanceof d)throw i;const u=i,h=typeof u.code=="string"?u.code:"AUTH_ADMIN_ERROR";throw console.error("[lunora] auth admin operation failed:",i),new d("auth admin operation failed",{code:h,status:xr[h]??500})}},n=async(a,i)=>{if(e.assertAdmin(a),a.method!==i.http)throw new d(`Auth admin endpoint requires ${i.http}`,{code:"METHOD_NOT_ALLOWED",status:405});const u=e.getAuthAdmin();if(u===void 0)throw new d("auth endpoints require an `authAdmin` on the worker",{code:"AUTH_NOT_CONFIGURED",status:400});const h=u[i.method];if(h===void 0)throw new d(`auth admin does not support \`${i.method}\``,{code:"AUTH_OP_NOT_SUPPORTED",status:400});const f=new URL(a.url),m={body:i.http==="POST"?await e.readJsonBody(a):{},paging:e.parsePaging(a),query:T=>e.queryParameter(f,T)},S=i.build(m),A=await t(()=>h(S));return Response.json(i.returns==="void"?{ok:!0}:A,{headers:{"cache-control":"no-store","content-type":"application/json"},status:200})},r={};for(const[a,i]of Object.entries(Hr))r[a]=u=>n(u,i);return r},jr="__lunora_admin__:getAuthAuditLog",wt=e=>typeof e=="string"&&e!==""?e:void 0,gt=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0,Mr=e=>async(n,r)=>{e.assertAdmin(n);const a=e.getReader();if(a===void 0)throw new d("the auth/security audit endpoint requires an `authAuditReader` on the worker",{code:"AUTH_AUDIT_NOT_CONFIGURED",status:400});const i=wt(r.actorId),u=wt(r.event),h=gt(r.sinceSeq),f=gt(r.limit),m={...i===void 0?{}:{actorId:i},...u===void 0?{}:{event:u},...h===void 0?{}:{sinceSeq:h},...f===void 0?{}:{limit:f}};let S;try{S=await a.read(m)}catch(T){throw T instanceof d?T:(console.error("[lunora] auth audit read failed:",T),new d("auth audit read failed",{code:"AUTH_AUDIT_READ_FAILED",status:500}))}const A={entries:S};return Response.json({result:ze(A)},{headers:{"content-type":"application/json"},status:200})},$r=(e,t)=>{const n=[],r=[];if(t&&t.length>0)for(const a of t)e.resolveTableSharding?.(a)?.mode.kind==="global"?r.push(a):n.push(a);return{globalTables:r,shardLocalTables:n}},Kr=async(e,t,n,r,a,i,u)=>{if(n!==void 0&&r.length===0)return;const h=await e.orchestrateExport(i,{args:{tables:r},defaultShardKey:u,headers:t,tables:r});for(const f of h.shards)if(!f.error)for(const m of f.rows??[])a(m)},Qt=async(e,t,n,r,a,i)=>{const u=r??e.listSchemaTables?.();r===void 0&&e.listSchemaTables===void 0&&console.warn("[lunora] export: no table list available (`listSchemaTables` is unset and no `tables` were named), so only the default shard is reachable. A `.shardBy()` deployment's other shards will be missing from this export. Name the tables explicitly, or regenerate the worker so codegen supplies the list.");const{globalTables:h,shardLocalTables:f}=$r(e,u);await Kr(t,n,u,f,a,i,e.defaultShardKey??"__root__");const m=e.exportGlobals;if((r===void 0||h.length>0)&&m)for await(const A of m({tables:h}))a(A)},Fr=new TextEncoder,Gr=1e3,zt=10,Qr=200,yt=8,Wt="lunoraBackupCron",bt=24*1048576,_t=e=>{const t=e.slice(0,zt).map(r=>jt(r)),n=e.length-t.length;return`${t.join(", ")}${n>0?` (+${String(n)} more)`:""}`},zr=(e,t)=>{const n=new Uint8Array(new ArrayBuffer(t));let r=0;for(const a of e)n.set(a,r),r+=a.byteLength;return n},et=async(e,t,n,r)=>{if(n===void 0||!Number.isInteger(n)||n<=0)return{eligible:0,stale:[]};const a=[];let i;for(let u=0;u<Gr;u+=1){const h=await e.list({cursor:i,include:["customMetadata"],prefix:t});for(const f of h.objects)Vn(f.key)&&f.customMetadata?.[Wt]===r&&a.push(f.key);if(!h.truncated||h.cursor===void 0)break;i=h.cursor}return{eligible:a.length,stale:a.toSorted((u,h)=>h.localeCompare(u)).slice(n)}},Wr=async(e,t,n,r,a)=>{const{stale:i}=await et(e,t,n,r),u=new Set(a),h=i.filter(g=>u.has(g)),f=h.slice(0,Qr),m=i.length-f.length,S=a.length-h.length;if(f.length===0)return{deleted:[],failed:[],ignored:S,remaining:m};const A=[],T=[];for(let g=0;g<f.length;g+=yt){const y=await Promise.allSettled(f.slice(g,g+yt).map(async _=>(await e.delete(jt(_)),await e.delete(_),_)));for(const[_,p]of y.entries())p.status==="fulfilled"?A.push(p.value):T.push(f[g+_])}return A.length>0&&console.info(`[lunora] backup prune kept the newest ${String(n)} and deleted ${String(A.length)}: ${_t(A)}`),T.length>0&&console.warn(`[lunora] backup prune failed to remove ${String(T.length)}: ${_t(T)}`),{deleted:A,failed:T,ignored:S,remaining:m}},Vr=async e=>{const t=e.backupStore;if(!t)throw new d("backup retention preview requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});const n=qe(e.backupPrefix??Ye),r=e.backupCron,{eligible:a,stale:i}=r===void 0?{eligible:0,stale:[]}:await et(t,n,e.backupRetain,r);return{cron:r,eligible:a,keep:e.backupRetain??0,prefix:n,wouldDelete:i}},Jr=async(e,t,n,r)=>{const a=e.backupStore,i=e.queryCoordinator;if(!a)throw new d("scheduled backup requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});if(!i)throw new d("scheduled backup requires a `queryCoordinator` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});if(!n||n.length===0)throw new d("scheduled backup requires an `adminToken` (or `env.LUNORA_ADMIN_TOKEN`) to authenticate the per-shard export gate",{code:"BACKUP_NOT_CONFIGURED",status:500});const u={authorization:`Bearer ${n}`,"content-type":"application/json"},h=e.backupTables;let f=0,m=0,S=[];await Qt(e,i,u,h,D=>{const j=Fr.encode(`${JSON.stringify(D)}
|
|
2
|
-
`);if(f+=1,m+=j.byteLength,m>bt)throw new d(`scheduled backup reached ${String(m)} bytes of NDJSON, past the ${String(bt)}-byte limit for a snapshot assembled inside a Worker — nothing was written. Narrow it with \`backupTables\`, or take this snapshot off-platform with \`lunora backup create --bucket\`.`,{code:"BACKUP_TOO_LARGE",status:507});S.push(j)},t);const T=qe(e.backupPrefix??Ye),g=new Date(r.scheduledTime).toISOString(),y=Jn(T,g),_=zr(S,m);S=[];const p=Yn(await crypto.subtle.digest("SHA-256",_));await a.put(y,_,{httpMetadata:{contentType:"application/x-ndjson"},sha256:p});const O={bytes:m,createdAt:g,cron:r.cron,file:y,id:g,rows:f,scheduledTime:r.scheduledTime,sha256:p,...h?{tables:h.join(",")}:{}};await a.put(qn(y),`${JSON.stringify(O,void 0,2)}
|
|
3
|
-
`,{customMetadata:{[Wt]:r.cron},httpMetadata:{contentType:"application/json"}});try{const{stale:D}=await et(a,T,e.backupRetain,r.cron);if(D.length>0){const j=D.slice(0,zt),k=D.length-j.length;console.info(`[lunora] backup retention: ${String(D.length)} snapshot(s) past the newest ${String(e.backupRetain)} — run \`lunora backup prune\` to remove them: ${j.join(", ")}${k>0?` (+${String(k)} more)`:""}`)}}catch(D){console.warn(`[lunora] backup ${y} was written, but the retention report failed:`,D)}},qr=async(e,t)=>{const n=e.backupStore;if(!n)throw new d("backup prune requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});const r=e.backupCron,a=e.backupRetain;if(r===void 0||a===void 0||!Number.isInteger(a)||a<=0)throw new d("backup prune needs a retention window: set `backupRetain` (and `backupCron`, which decides whose snapshots retention owns) on the worker. Without one there is nothing past the window to remove.",{code:"BACKUP_RETENTION_NOT_CONFIGURED",status:400});return Wr(n,qe(e.backupPrefix??Ye),a,r,t)},Yr="/_lunora/admin/backup/retention",Xr="/_lunora/admin/backup/prune",Zr=e=>{const{options:t,readJsonBody:n,requireAdminOption:r}=e,a=(h,f)=>{r(h,t.backupStore,{code:"BACKUP_NOT_CONFIGURED",message:`backup ${f} requires a \`backupStore\` on the worker`})},i=async h=>($(h,"GET","Backup-retention"),a(h,"retention preview"),Response.json(await Vr(t),{headers:{"cache-control":"no-store"}})),u=async h=>{$(h,"POST","Backup-prune"),a(h,"prune");const{confirm:f}=await n(h);if(!Array.isArray(f)||f.some(m=>typeof m!="string"))throw new d("backup prune requires a `confirm` array of the sidecar keys to remove — read them from `GET /_lunora/admin/backup/retention` and pass back the ones you mean to delete",{code:"BAD_REQUEST",status:400});return Response.json(await qr(t,f),{headers:{"cache-control":"no-store"}})};return{[Xr]:u,[Yr]:i}},Rt=500,eo=(e,t,n)=>{if(typeof e!="object"||e===null||Array.isArray(e))throw new d("each batch call must be an object",{code:"BAD_REQUEST",status:400});const r=e;if(typeof r.functionPath!="string")throw new d("each batch call needs a string `functionPath`",{code:"BAD_REQUEST",status:400});if(r.functionPath.startsWith("__lunora_relation__:")||r.functionPath.startsWith("__lunora_admin__"))throw new d("reserved function path cannot be batched",{code:"FORBIDDEN",status:403});if(r.args!==void 0&&(typeof r.args!="object"||r.args===null||Array.isArray(r.args)))throw new d("each batch call `args` must be an object",{code:"BAD_REQUEST",status:400});return{entry:{args:r.args===void 0?{}:r.args,clientId:typeof r.clientId=="string"?r.clientId:void 0,clientSeq:typeof r.clientSeq=="number"?r.clientSeq:void 0,functionPath:r.functionPath,id:typeof r.id=="number"?r.id:t,mutationId:typeof r.mutationId=="string"?r.mutationId:void 0},shardKey:typeof r.shardKey=="string"?r.shardKey:n}},to=(e,t)=>{if(e.length>Rt)throw new d(`RPC batch exceeds the ${String(Rt)}-call limit`,{code:"BAD_REQUEST",status:400});const n=new Map;for(const[r,a]of e.entries()){const{entry:i,shardKey:u}=eo(a,r,t),h=n.get(u)??[];h.push(i),n.set(u,h)}return n},no="/_lunora/admin/export",ro="/_lunora/admin/import",oo="/_lunora/admin/sync",ao="/_lunora/admin/connector/sync",so="/_lunora/admin/apply",io="/_lunora/admin/export-tap/run",co=new TextEncoder,uo=async e=>{const n=await be(e,"Export")??{};if(n.tables===void 0)return{tables:void 0};if(!Array.isArray(n.tables))throw new d("Export `tables` must be a string array",{code:"BAD_REQUEST",status:400});const r=[];for(const a of n.tables){if(typeof a!="string"||a.length===0)throw new d("Export `tables` entries must be non-empty strings",{code:"BAD_REQUEST",status:400});r.push(a)}return{tables:r}},je=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):void 0,lo=e=>{const{applyGlobals:t,defaultShardKey:n,exportCursorStore:r,exportSinks:a,knownTables:i,queryCoordinator:u,assertAdmin:h,requireAdminOption:f,resolveForwardContext:m,shardDO:S,streamExportRows:A,streamingImport:T,syncGlobals:g}=e,y=async(k,F)=>{const H=me(k,["POST"]);if(H)return H;const Y=f(k,u,{code:"BAD_REQUEST",message:"Export endpoint requires a `queryCoordinator` on the worker"}),C=await uo(k),{headers:G}=await m(k,F),Q=new ReadableStream({async pull(J){const M=K=>{J.enqueue(co.encode(`${JSON.stringify(K)}
|
|
4
|
-
`))};try{await A(Y,G,C.tables,M),J.close()}catch(K){J.error(K)}}});return new Response(Q,{headers:{"content-type":"application/x-ndjson"},status:200})},_=async(k,F)=>{const H=me(k,["POST"]);if(H)return H;const Y=f(k,u,{code:"BAD_REQUEST",message:"Sync endpoint requires a `queryCoordinator` on the worker"}),C=await Z(k),G=typeof C.cursors=="object"&&C.cursors!==null?C.cursors:{},Q=typeof C.limit=="number"?C.limit:void 0,J=typeof C.globalCursor=="number"?C.globalCursor:0,M=je(C.tables),{headers:K}=await m(k,F),oe=M??i(),z=await Y.orchestrateCdcSync(S,{cursors:G,defaultShardKey:n,headers:K,limit:Q,tables:oe}),de=g?await g({limit:Q,sinceSeq:J}):void 0;return Response.json({global:de,shards:z.shards},{status:200})},p=async(k,F)=>{const H=me(k,["POST"]);if(H)return H;const Y=f(k,u,{code:"BAD_REQUEST",message:"Connector sync endpoint requires a `queryCoordinator` on the worker"}),C=await Z(k),G=nr(C.cursor),Q=typeof C.limit=="number"&&C.limit>0?C.limit:void 0,J=je(C.tables),{headers:M}=await m(k,F),K=J??i(),oe=await Y.orchestrateCdcSync(S,{cursors:G.s,defaultShardKey:n,headers:M,limit:Q,tables:K}),z=[],de={...G.s};let ue=!1;for(const ae of oe.shards)ue=ct(z,ae.changes??[],or(Q))||ue,de[ae.shardKey]=ae.cursor;let _e=G.g;if(g){const ae=await g({limit:Q,sinceSeq:G.g});ue=ct(z,ae.changes,Q)||ue,_e=ae.cursor}const ve=rr({g:_e,s:de,v:1}),ke={changes:z,hasMore:ue,nextCursor:ve};return Response.json(ke,{status:200})},O=async(k,F)=>{const H=me(k,["POST"]);if(H)return H;const Y=f(k,u,{code:"BAD_REQUEST",message:"Apply endpoint requires a `queryCoordinator` on the worker"}),C=await Z(k),Q=(Array.isArray(C.batches)?C.batches:[]).map(z=>z).filter(z=>z!==null&&typeof z=="object"&&typeof z.shardKey=="string"&&Array.isArray(z.changes)),J=Array.isArray(C.globalChanges)?C.globalChanges:[],{headers:M}=await m(k,F),K=await Y.orchestrateApplyCdc(S,{batches:Q,headers:M}),oe=J.length>0&&t?await t({changes:J}):0;return Response.json({applied:K.applied+oe,failed:K.failed,ok:K.ok},{status:200})},D=async(k,F)=>{const H=me(k,["POST"]);if(H)return H;h(k);const{headers:Y}=await m(k,F),C=await T(k,Y);return Response.json(C,{headers:{"content-type":"application/json"},status:C.failed.length>0?207:200})},j=async(k,F)=>{const H=me(k,["POST"]);if(H)return H;const Y=f(k,u,{code:"BAD_REQUEST",message:"Export-tap endpoint requires a `queryCoordinator` on the worker"});if(a===void 0||Object.keys(a).length===0||r===void 0)throw new d("Export-tap endpoint requires `exportSinks` + `exportCursorStore` on the worker",{code:"EXPORT_TAP_NOT_CONFIGURED",status:400});const C=await Z(k),G=typeof C.sink=="string"?C.sink:void 0,Q=typeof C.limit=="number"&&C.limit>0?C.limit:void 0,J=je(C.tables);if(G===void 0)throw new d("Export-tap `sink` must name a configured sink",{code:"BAD_REQUEST",status:400});const M=a[G];if(M===void 0)throw new d(`Export-tap sink "${G}" is not configured`,{code:"NOT_FOUND",status:404});const{headers:K}=await m(k,F),oe=J??i(),z=await tr({coordinator:Y,cursorStore:r,defaultShardKey:n,headers:K,limit:Q,shardDO:S,sink:M,tables:oe});return Response.json(z,{headers:{"content-type":"application/json"},status:200})};return{[so]:O,[ao]:p,[no]:y,[io]:j,[ro]:D,[oo]:_}},ho=(e,t)=>{let n;try{n=JSON.parse(e)}catch{return{error:{code:"BAD_ROW",line:t,message:"line is not valid JSON",table:""},ok:!1}}if(!n||typeof n!="object"||Array.isArray(n))return{error:{code:"BAD_ROW",line:t,message:"row must be a JSON object",table:""},ok:!1};const r=n;return typeof r.table!="string"||r.table.length===0?{error:{code:"BAD_ROW",line:t,message:"row is missing `table`",table:""},ok:!1}:!r.doc||typeof r.doc!="object"||Array.isArray(r.doc)?{error:{code:"BAD_ROW",line:t,message:"row is missing or malformed `doc`",table:r.table},ok:!1}:{doc:r.doc,ok:!0,table:r.table}},fo=(e,t,n,r,a)=>{if(n?.mode.kind==="shardBy"&&typeof n.mode.field=="string"){const i=e[n.mode.field];return i==null?{error:{code:"BAD_ROW",line:a,message:`row missing shard field "${n.mode.field}" for table "${t}"`,table:t},ok:!1}:{ok:!0,shardKey:typeof i=="string"?i:JSON.stringify(i)}}return{ok:!0,shardKey:r}},po=async(e,t,n)=>{if(!e.body)throw new d("Import endpoint requires a request body",{code:"BAD_REQUEST",status:400});const r=[],a=[],i=new Map;let u=0,h=0;const f=e.body.getReader(),m=new TextDecoder;let S="",A=0;const T=g=>{h+=1;const y=g.trim();if(y.length===0)return;u+=1;const _=ho(y,h);if(!_.ok){r.push(_.error);return}const{doc:p,table:O}=_,D=t.resolveTableSharding?.(O);if(D?.mode.kind==="global"){a.push({doc:p,line:h,table:O});return}const j=fo(p,O,D,n,h);if(!j.ok){r.push(j.error);return}const k=i.get(j.shardKey);k?k.rows.push({doc:p,table:O}):i.set(j.shardKey,{rows:[{doc:p,table:O}],shardKey:j.shardKey,startLine:h})};for(;;){const{done:g,value:y}=await f.read();if(g)break;if(y&&(A+=y.byteLength,A>xt))throw await f.cancel().catch(()=>{}),new d("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});S+=m.decode(y,{stream:!0});let _=S.indexOf(`
|
|
5
|
-
`);for(;_!==-1;){const p=S.slice(0,_);S=S.slice(_+1),T(p),_=S.indexOf(`
|
|
6
|
-
`)}}return S.length>0&&T(S),{errors:r,globalRows:a,perShard:i,received:u}},mo=e=>e.flatMap(t=>t.error?[{message:t.error.message,shardKey:t.shardKey,timedOut:t.error.timedOut}]:[]),Et=(e,t)=>{for(const[n,r]of Object.entries(t.inserted))e.inserted[n]=(e.inserted[n]??0)+r;for(const n of t.errors)e.errors.push({...n});e.conflicts+=t.conflicts},wo=async(e,t,n,r)=>{const a=t.defaultShardKey??"__root__",{errors:i,globalRows:u,perShard:h,received:f}=await po(e,t,a),m={conflicts:0,errors:i,failed:[],inserted:{}},S=[];if(t.resolveTableSharding===void 0&&h.size>0&&S.push("no `resolveTableSharding` is configured, so every row was routed to the default shard and no row could be recognised as `.global()` — correct for a single-shard app, silent misplacement for a sharded one"),h.size>0){const A=t.queryCoordinator;if(!A)throw new d("Import endpoint requires a `queryCoordinator` on the worker",{code:"BAD_REQUEST",status:400});const T=await A.orchestrateImport(r,{batches:[...h.values()],headers:n});Et(m,T),m.failed.push(...mo(T.shards))}if(u.length>0)if(t.importGlobals){const A=u[0]?.line??1,T=await t.importGlobals({rows:u,startLine:A});Et(m,T)}else for(const A of u)m.errors.push({code:"GLOBAL_NOT_CONFIGURED",line:A.line,message:`row targets global table "${A.table}" but no \`importGlobals\` is configured`,table:A.table});return{conflicts:m.conflicts,errors:m.errors,failed:m.failed,inserted:m.inserted,received:f,...S.length>0?{warnings:S}:{}}},Me=e=>typeof e=="object"&&e!==null?e:{},$e=e=>typeof e.kind=="string"?e.kind:"unknown",go=(e,t)=>{let n=Me(t),r=!1;$e(n)==="optional"&&(r=!0,n=Me(n._meta?.inner));const a=$e(n),i=n._meta??{},u={kind:a,name:e,optional:r};if(a==="id"&&typeof i.tableName=="string"&&(u.table=i.tableName),a==="array"){const h=$e(Me(i.inner));h!=="unknown"&&(u.element=h)}return u},yo=e=>typeof e!="object"||e===null?[]:Object.entries(e).map(([t,n])=>go(t,n)).toSorted((t,n)=>t.name.localeCompare(n.name)),bo="/_lunora/admin/functions",_o="/_lunora/admin/cron-jobs",Ro="/_lunora/admin/openapi",Eo="/_lunora/admin/openrpc",So="/_lunora/admin/global/tables",Ao="/_lunora/admin/global/table",To="/_lunora/admin/global/facet",St=e=>{if(e===void 0||e==="")return;let t;try{t=Qn(JSON.parse(e))}catch{return}if(!Array.isArray(t))return;const n=t.flatMap(r=>{if(typeof r!="object"||r===null||typeof r.column!="string")return[];const{column:a,value:i}=r;return[{column:a,value:i}]});return n.length===0?void 0:n},Oo=Object.freeze({info:{description:'No OpenAPI spec is configured on this worker. Run `lunora codegen`, then wire the generated module to `createWorker`: `import { openApiSpec } from "./lunora/_generated/openapi"`.',title:"Lunora API",version:"0.0.0"},openapi:"3.1.0",paths:{}}),vo=Object.freeze({info:{description:'No OpenRPC spec is configured on this worker. Run `lunora codegen --api-spec openrpc` (or `both`), then wire the generated module to `createWorker`: `import { openRpcSpec } from "./lunora/_generated/openrpc"`.',title:"Lunora RPC",version:"0.0.0"},methods:[],openrpc:"1.3.2"}),ko=e=>{const{assertAdmin:t,options:n,parsePaging:r,queryParameter:a,requireAdminOption:i}=e,u=g=>{$(g,"GET","Functions");const y=i(g,n.functions,{code:"FUNCTIONS_NOT_CONFIGURED",message:"functions endpoint requires a `functions` registry on the worker"}),_=Object.entries(y).flatMap(([p,O])=>O.visibility==="internal"||O.kind==="stream"?[]:[{args:yo(O.args),kind:O.kind,path:p}]).toSorted((p,O)=>p.path.localeCompare(O.path));return Response.json({functions:_},{headers:{"content-type":"application/json"},status:200})},h=g=>{$(g,"GET","Cron-jobs");const y=i(g,n.cronJobs,{code:"CRON_JOBS_NOT_CONFIGURED",message:"cron-jobs endpoint requires a `cronJobs` map on the worker"}),_=Object.entries(y).flatMap(([p,O])=>O.map(D=>({args:D.args,cron:p,functionPath:D.functionPath,name:D.name,shardKey:D.shardKey,workflow:D.workflow}))).toSorted((p,O)=>p.name.localeCompare(O.name));return Response.json({jobs:_},{headers:{"content-type":"application/json"},status:200})},f=g=>($(g,"GET","OpenAPI"),t(g),Response.json(n.openApiSpec??Oo,{headers:{"content-type":"application/json"},status:200})),m=g=>($(g,"GET","OpenRPC"),t(g),Response.json(n.openRpcSpec??vo,{headers:{"content-type":"application/json"},status:200})),S=async g=>{$(g,"GET","Global-tables");const y=i(g,n.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"});return Response.json(await y.listTables(),{headers:{"content-type":"application/json"},status:200})},A=async g=>{$(g,"GET","Global-table");const y=i(g,n.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),_=new URL(g.url),p=a(_,"table");if(p===void 0)throw new d("Global-table endpoint requires a `table` query param",{code:"BAD_REQUEST",status:400});const O=await y.readTablePage({...r(g),filters:St(a(_,"filters")),table:p});return Response.json(O,{headers:{"content-type":"application/json"},status:200})},T=async g=>{$(g,"GET","Global-facet");const y=i(g,n.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),_=new URL(g.url),p=a(_,"table"),O=a(_,"column");if(p===void 0||O===void 0)throw new d("Global-facet endpoint requires `table` and `column` query params",{code:"BAD_REQUEST",status:400});const D=a(_,"limit"),j=D===void 0?void 0:Number(D),k=await y.facetColumn({column:O,filters:St(a(_,"filters")),limit:j!==void 0&&Number.isFinite(j)?j:void 0,table:p});return Response.json(k,{headers:{"content-type":"application/json"},status:200})};return{[_o]:h,[bo]:u,[To]:T,[Ao]:A,[So]:S,[Ro]:f,[Eo]:m}},Io="/_lunora/admin/kv/namespaces",Po="/_lunora/admin/kv/keys",Vt="/_lunora/admin/kv/value",Jt=32*1048576,At=60,Do=e=>{const{readJsonBody:t,requireAdminOption:n}=e,r=y=>n(y,e.kvIntrospector,{code:"KV_NOT_CONFIGURED",message:"KV endpoints require a `kvIntrospector` on the worker"}),a=y=>Response.json(y,{headers:{"content-type":"application/json"},status:200}),i=(y,_)=>{const p=new URL(y.url),O=p.searchParams.get("namespace")??"",D=p.searchParams.get("key")??"";if(O==="")throw new d(`KV-value ${_} request requires a \`namespace\` query parameter`,{code:"BAD_REQUEST",status:400});if(D==="")throw new d(`KV-value ${_} request requires a \`key\` query parameter`,{code:"BAD_REQUEST",status:400});return{key:D,namespace:O}},u=async(y,_)=>{if(!(await y.listNamespaces()).some(O=>O.binding===_))throw new d(`Unknown KV namespace binding \`${_}\``,{code:"NOT_FOUND",status:404})},h=async y=>($(y,"GET","KV-namespaces"),a({namespaces:await r(y).listNamespaces()})),f=async y=>{$(y,"GET","KV-keys");const _=r(y),p=new URL(y.url),O=p.searchParams.get("namespace")??"";if(O==="")throw new d("KV-keys request requires a `namespace` query parameter",{code:"BAD_REQUEST",status:400});const D=p.searchParams.get("prefix")??void 0,j=p.searchParams.get("cursor")??void 0,k=p.searchParams.get("limit"),F=k===null?void 0:Number.parseInt(k,10);if(F!==void 0&&(!Number.isInteger(F)||F<1))throw new d("KV-keys `limit` must be a positive integer",{code:"BAD_REQUEST",status:400});const H=F===void 0?void 0:Math.min(F,1e3);return await u(_,O),a(await _.listKeys({cursor:j,limit:H,namespace:O,prefix:D}))},T={DELETE:async y=>{const _=r(y),p=i(y,"DELETE");return await u(_,p.namespace),await _.deleteKey(p),a({deleted:!0})},GET:async y=>{const _=r(y),p=i(y,"GET");return await u(_,p.namespace),a(await _.getValue(p))},PUT:async y=>{const _=r(y),p=await t(y,Jt);if(typeof p.namespace!="string"||p.namespace==="")throw new d("KV-value PUT request requires a `namespace` string",{code:"BAD_REQUEST",status:400});if(typeof p.key!="string"||p.key==="")throw new d("KV-value PUT request requires a `key` string",{code:"BAD_REQUEST",status:400});if(typeof p.value!="string")throw new d("KV-value PUT request requires a `value` string",{code:"BAD_REQUEST",status:400});if(p.expirationTtl!==void 0&&(typeof p.expirationTtl!="number"||!Number.isInteger(p.expirationTtl)||p.expirationTtl<At))throw new d("KV-value PUT `expirationTtl` must be an integer ≥ 60",{code:"BAD_REQUEST",status:400});const O=Math.floor(Date.now()/1e3)+At;if(p.expiration!==void 0&&(typeof p.expiration!="number"||!Number.isInteger(p.expiration)||p.expiration<O))throw new d("KV-value PUT `expiration` must be a Unix-seconds timestamp at least 60 seconds in the future",{code:"BAD_REQUEST",status:400});return await u(_,p.namespace),await _.putValue({expiration:p.expiration,expirationTtl:p.expirationTtl,key:p.key,metadata:p.metadata,namespace:p.namespace,value:p.value}),a({ok:!0})}},g=y=>{const _=T[y.method];if(!_)throw new d("KV-value endpoint requires GET, PUT, or DELETE",{code:"METHOD_NOT_ALLOWED",status:405});return _(y)};return{[Io]:h,[Po]:f,[Vt]:g}},No="/_lunora/migrate",Uo="/_lunora/admin/pitr",Co="/_lunora/admin/rank",Bo="/_lunora/admin/rankpage",xo="/_lunora/admin/shard-traffic",Ho=new Set(["__lunora_admin__:migrationStatus","__lunora_admin__:runMigration"]),Lo=new Set(["__lunora_admin__:getPitrBookmark","__lunora_admin__:pitrRestore"]),jo=async e=>{const n=await be(e,"Migration")??{};if(typeof n.table!="string"||n.table.length===0)throw new d("Migration request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof n.functionPath!="string"||!Ho.has(n.functionPath))throw new d("Migration request `functionPath` must be a migration admin op",{code:"BAD_REQUEST",status:400});return{args:n.args??{},functionPath:n.functionPath,table:n.table}},Mo=async e=>{const n=await be(e,"Rank")??{};if(typeof n.table!="string"||n.table.length===0)throw new d("Rank request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof n.index!="string"||n.index.length===0)throw new d("Rank request is missing `index`",{code:"BAD_REQUEST",status:400});if(typeof n.partitionKey!="string")throw new d("Rank request `partitionKey` must be a string",{code:"BAD_REQUEST",status:400});if(typeof n.rowId!="string"||n.rowId.length===0)throw new d("Rank request is missing `rowId`",{code:"BAD_REQUEST",status:400});if(!Array.isArray(n.sortValues))throw new d("Rank request `sortValues` must be an array",{code:"BAD_REQUEST",status:400});return{index:n.index,partitionKey:n.partitionKey,rowId:n.rowId,sortValues:n.sortValues,table:n.table}},$o=e=>{if(e!==void 0){if(!Array.isArray(e)||e.some(t=>t!=="asc"&&t!=="desc"))throw new d('Rank page request `directions` must be an array of "asc"|"desc"',{code:"BAD_REQUEST",status:400});return e}},Ko=e=>{if(typeof e.table!="string"||e.table.length===0)throw new d("Rank page request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof e.index!="string"||e.index.length===0)throw new d("Rank page request is missing `index`",{code:"BAD_REQUEST",status:400});if(e.partitionKey!==void 0&&typeof e.partitionKey!="string")throw new d("Rank page request `partitionKey` must be a string",{code:"BAD_REQUEST",status:400});if(e.take!==void 0&&(typeof e.take!="number"||!Number.isFinite(e.take)))throw new d("Rank page request `take` must be a number",{code:"BAD_REQUEST",status:400});if(e.cursor!==void 0&&e.cursor!==null&&typeof e.cursor!="string")throw new d("Rank page request `cursor` must be a string or null",{code:"BAD_REQUEST",status:400})},Fo=async e=>{const n=await be(e,"Rank page")??{};Ko(n);const r=$o(n.directions);return{cursor:typeof n.cursor=="string"?n.cursor:null,directions:r,index:n.index,partitionKey:typeof n.partitionKey=="string"?n.partitionKey:void 0,table:n.table,take:typeof n.take=="number"?n.take:void 0}},Go=async e=>{const n=await be(e,"Shard-traffic")??{};if(typeof n.table!="string"||n.table.length===0)throw new d("Shard-traffic request is missing `table`",{code:"BAD_REQUEST",status:400});return{table:n.table}},Qo=async e=>{const n=await Z(e);if(typeof n.functionPath!="string"||!Lo.has(n.functionPath))throw new d("PITR request `functionPath` must be a PITR admin op",{code:"BAD_REQUEST",status:400});if(n.shardKey!==void 0&&typeof n.shardKey!="string")throw new d("PITR `shardKey` must be a string",{code:"BAD_REQUEST",status:400});return{args:n.args??{},functionPath:n.functionPath,shardKey:n.shardKey}},zo=e=>{const{defaultShard:t,forwardToShard:n,isAdmin:r,queryCoordinator:a,resolveForwardContext:i,shardDO:u}=e,h=(g,y)=>{if(g.method!=="POST")throw new d(`${y} endpoint requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});if(!r(g))throw new d("Admin auth required",{code:"FORBIDDEN",status:403});if(!a)throw new d(`${y} endpoint requires a \`queryCoordinator\` on the worker`,{code:"BAD_REQUEST",status:400});return a},f=async(g,y)=>{const _=h(g,"Migration"),p=await jo(g),{headers:O}=await i(g,y),D=await _.orchestrateMigration(u,{args:p.args,defaultShardKey:t,functionPath:p.functionPath,headers:O,table:p.table});return Response.json(D,{headers:{"content-type":"application/json"},status:200})},m=async(g,y)=>{const _=h(g,"Rank"),p=await Mo(g),{headers:O}=await i(g,y),D=await _.orchestrateRank(u,{headers:O,index:p.index,partitionKey:p.partitionKey,rowId:p.rowId,sortValues:p.sortValues,table:p.table});return Response.json(D,{headers:{"content-type":"application/json"},status:200})},S=async(g,y)=>{const _=h(g,"Rank page"),p=await Fo(g),{headers:O}=await i(g,y),D=await _.orchestrateRankPage(u,{...p,headers:O});return Response.json(D,{headers:{"content-type":"application/json"},status:200})},A=async(g,y)=>{const _=h(g,"Shard-traffic"),p=await Go(g),{headers:O}=await i(g,y),D=await _.orchestrateShardTraffic(u,{headers:O,table:p.table});return Response.json(D,{headers:{"content-type":"application/json"},status:200})},T=async(g,y)=>{if($(g,"POST","PITR"),!r(g))throw new d("admin PITR endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403});const _=await Qo(g),{headers:p}=await i(g,y),O=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:_.args,functionPath:_.functionPath}),headers:p,method:"POST"});return n(u,_.shardKey??t,O)};return{[No]:f,[Uo]:T,[Co]:m,[Bo]:S,[xo]:A}},Wo=1,Vo=0,Jo=32,qo=512,Yo=/^[a-z][\d_a-z*/-]{0,255}(?:@[a-z][\d_a-z*/-]{0,13})?=[\u0020-\u002B\u002D-\u003C\u003E-\u007E]{1,256}$/,Xo=e=>{if(e==null)return;const t=e.trim();if(t.length===0||t.length>qo)return;const n=t.split(",");if(!(n.length>Jo)){for(const r of n)if(!Yo.test(r.trim()))return;return t}},Zo=e=>{const t=Mn(e.headers.get("traceparent"));if(t===void 0)return;const n=Xo(e.headers.get("tracestate"));return{parentSpanId:t.parentSpanId,sampled:t.sampled,traceId:t.traceId,...n===void 0?{}:{traceState:n}}},ea=(e,t={})=>{const n=Zo(e),r=t.trustInbound===!0?n:void 0,a=Oe(8),i=r?.traceId??Oe(16),u=ur(t.sampling,r===void 0?a:i),h=u.isTraced&&(r===void 0||r.sampled);return{decision:u,ignoredUpstream:n!==void 0&&r===void 0,trace:{sampled:h,spanId:a,traceFlags:h?Wo:Vo,traceId:i,...r?.parentSpanId===void 0?{}:{parentSpanId:r.parentSpanId},...r?.traceState===void 0?{}:{traceState:r.traceState}}}},ta=(e,t)=>{t.traceparent=jn(e.traceId,e.spanId,e.sampled),e.traceState!==void 0&&(t.tracestate=e.traceState)},na=(e,t)=>{let n;return()=>{if(n===void 0){const r=Gn(e),a=t===void 0?void 0:t.cf;n=$n(Fn(r),Kn(r,a))}return n}},ra="/_lunora/admin/scheduled",oa="/_lunora/admin/scheduled/status",aa="/_lunora/admin/scheduled/ws",sa="/_lunora/admin/scheduled/cancel",ia="/_lunora/admin/scheduled/dead",ca="/_lunora/admin/scheduled/dead/retry",da="/_lunora/admin/scheduled/dead/cancel",ua="/_lunora/admin/scheduled/pool/release",la=e=>{const{checkWsAdmin:t,requireSchedulerNamespace:n,resolveSchedulerStub:r,schedulerInstanceName:a}=e,i=(m,S)=>A=>{if(A.method!=="GET")throw new d(`${S} endpoint requires GET`,{code:"METHOD_NOT_ALLOWED",status:405});const T=new URL(A.url).searchParams.get("cursor"),g=T===null||T===""?"":`?cursor=${encodeURIComponent(T)}`;return r(A).fetch(new Request(`https://scheduler.internal${m}${g}`,{method:"GET"}))},u=(m,S,A=S)=>async T=>{if(T.method!=="POST")throw new d(`${A} requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});const g=r(T),y=await T.json().catch(()=>{});if(typeof y?.id!="string"||y.id==="")throw new d(`${S} requires a string \`id\``,{code:"BAD_REQUEST",status:400});return g.fetch(new Request(`https://scheduler.internal${m}`,{body:JSON.stringify({id:y.id}),headers:{"content-type":"application/json"},method:"POST"}))},h=async m=>{if(m.method!=="POST")throw new d("Scheduled pool-release endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const S=r(m),A=await m.json().catch(()=>{});if(typeof A?.pool!="string"||A.pool==="")throw new d("Scheduled pool-release requires a string `pool`",{code:"BAD_REQUEST",status:400});const T=typeof A.id=="string"&&A.id!==""?A.id:void 0;return S.fetch(new Request("https://scheduler.internal/complete",{body:JSON.stringify(T===void 0?{pool:A.pool}:{id:T,pool:A.pool}),headers:{"content-type":"application/json"},method:"POST"}))},f=async m=>{if(m.headers.get("Upgrade")!=="websocket")throw new d("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});if(!await t(m))throw new d("admin authorization required",{code:"ADMIN_FORBIDDEN",status:403});const S=n();return we(S,a).fetch(new Request("https://scheduler.internal/ws",{headers:{Upgrade:"websocket"}}))};return{[sa]:u("/cancel","Scheduled-cancel","Scheduled-cancel endpoint"),[da]:u("/dead/cancel","Scheduled dead-letter action"),[ia]:i("/dead","Scheduled dead-letter"),[ca]:u("/dead/retry","Scheduled dead-letter action"),[ra]:i("/list","Scheduled-list"),[ua]:h,[oa]:i("/status","Scheduler-status"),[aa]:f}},ha=(e,...t)=>{let n=e.cf;for(const r of t){if(typeof n!="object"||n===null)return;n=n[r]}return typeof n=="string"?n:void 0},Tt={mtls:e=>ha(e,"tlsClientAuth","certVerified")==="SUCCESS"},fa=e=>e===void 0||e===!1?()=>!1:e===!0?()=>!0:typeof e=="function"?e:(Object.hasOwn(Tt,e)?Tt[e]:void 0)??(()=>!1),pa=e=>{if(e!==void 0)return()=>{};let t=!1;return()=>{t||(t=!0,console.warn('[lunora] Ignored an inbound `traceparent`, so this request starts a new trace instead of joining the caller\'s. That is the safe default: the header is caller-supplied, and trusting it lets any client choose which trace its spans and logs join. If this worker sits behind a gateway, service mesh, or Cloudflare Access that sets `traceparent` itself, set `trustInboundTraceContext: true` on createWorker() (or `"mtls"` to trust only edge-verified client certificates). Set it to `false` to keep this behaviour and silence this message.'))}},ma="/_lunora/admin/vector/indexes",wa="/_lunora/admin/vector/query",ga=e=>{const{readJsonBody:t,requireAdminOption:n}=e,r=async i=>{$(i,"GET","Vector-indexes");const u=n(i,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});return Response.json({indexes:await u.listIndexes()},{headers:{"content-type":"application/json"},status:200})},a=async i=>{$(i,"POST","Vector-query");const u=n(i,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});if(u.queryIndex===void 0)throw new d("vector index querying is not enabled on this worker",{code:"VECTOR_QUERY_UNSUPPORTED",status:400});const f=await t(i);if(typeof f.name!="string"||f.name==="")throw new d("Vector-query request requires a `name` string",{code:"BAD_REQUEST",status:400});if(typeof f.text!="string"||f.text==="")throw new d("Vector-query request requires a `text` string",{code:"BAD_REQUEST",status:400});if(f.topK!==void 0&&(typeof f.topK!="number"||!Number.isInteger(f.topK)||f.topK<1))throw new d("Vector-query `topK` must be a positive integer",{code:"BAD_REQUEST",status:400});const m=await u.queryIndex({name:f.name,text:f.text,topK:f.topK});return Response.json(m,{headers:{"content-type":"application/json"},status:200})};return{[ma]:r,[wa]:a}},ya="/_lunora/admin/workflows/instances",ba="/_lunora/admin/workflows/instance",_a="/_lunora/admin/workflows/status",Ra={complete:!0,errored:!0,paused:!0,queued:!0,running:!0,terminated:!0,unknown:!0,waiting:!0,waitingForPause:!0},Ea=e=>e!==null&&Object.hasOwn(Ra,e)?e:void 0,Ot=(e,t)=>{const n=e.searchParams.get(t);if(n===null)return;const r=Number(n);return Number.isInteger(r)&&r>0?r:void 0},Ke=(e,t)=>{const n=e.searchParams.get(t);if(n===null||n==="")throw new d(`Workflows admin endpoint requires a \`${t}\` query parameter`,{code:"BAD_REQUEST",status:400});return n},vt=()=>{throw new d("Workflow inspection is unconfigured. Set CLOUDFLARE_ACCOUNT_ID + CLOUDFLARE_API_TOKEN in your .dev.vars to enable it.",{code:"WORKFLOWS_NOT_CONFIGURED",status:501})},Sa=e=>{const{assertAdmin:t,resolveWorkflowsClient:n}=e,r=async(u,h,f)=>{$(u,"GET","Workflows instances"),t(u);const m=n(h);if(!m)return Response.json({configured:!1,instances:[],page:1,perPage:0,totalCount:0});const S=Ke(f,"name"),A=Ea(f.searchParams.get("status"));return Response.json(await m.listInstances({page:Ot(f,"page"),perPage:Ot(f,"perPage"),status:A,workflowName:S}))},a=async(u,h,f)=>{$(u,"GET","Workflows instance"),t(u);const m=n(h);return m?Response.json(await m.getInstance({instanceId:Ke(f,"id"),workflowName:Ke(f,"name")})):vt()},i=async(u,h)=>{$(u,"POST","Workflows status"),t(u);const f=n(h);if(!f)return vt();const m=await u.json().catch(()=>{});if(typeof m?.name!="string"||m.name===""||typeof m.id!="string"||m.id==="")throw new d("Workflows status action requires string `name` and `id`",{code:"BAD_REQUEST",status:400});const{action:S}=m;if(S!=="pause"&&S!=="resume"&&S!=="terminate")throw new d("Workflows status action must be one of: pause, resume, terminate",{code:"BAD_REQUEST",status:400});return Response.json(await f.setInstanceStatus({action:S,instanceId:m.id,workflowName:m.name}))};return{[ba]:a,[ya]:r,[_a]:i}},Aa={[Vt]:Jt,[er]:Zn},kt="/_lunora/rpc",Ta="/_lunora/rpc-batch",Oa="/_lunora/ws",Ee=(e,t,n)=>({resourceAttributes:na(e,t),...n===void 0?{}:{waitUntil:n}}),Fe=e=>e?.waitUntil?{waitUntil:t=>e.waitUntil?.(t)}:{},It=e=>({spanId:e.spanId,traceFlags:e.traceFlags,traceId:e.traceId,...e.parentSpanId===void 0?{}:{parentSpanId:e.parentSpanId}}),Ge=e=>{const{method:t}=e,n=e.headers.get("user-agent")??void 0;let r;try{r=new URL(e.url)}catch{return{method:t,userAgent:n}}const a=r.port===""?void 0:Number(r.port);return{host:r.hostname,method:t,path:r.pathname,port:Number.isNaN(a)?void 0:a,scheme:r.protocol.replace(":",""),userAgent:n}},Pt="/_lunora/voice/",va="/_lunora/scheduler/dispatch",ka="/_lunora/admin/cron-jobs/run",Ia="/_lunora/admin/ws-token",Pa="/_lunora/admin/",Da="/_lunora/migrate",Na="/_lunora/status",Ua=e=>e.startsWith(Pa)||e===Da,Se=async e=>await e===!0,Ca=e=>{const t=e.headers.get("x-lunora-userid"),n=e.headers.get("x-lunora-identity");if(!(t===null&&n===null))return{...n===null?{}:{identity:n},...t===null?{}:{userId:t}}},Ba="/api/auth",xa="__lunora_admin__:recordAuthEvent",Ha="__lunora_admin__:listPushSubscriptions",La=["/sign-in","/sign-up","/callback"],ja=(e,t)=>{const n=t.endsWith("/")?t.slice(0,-1):t;if(!e.startsWith(`${n}/`))return!1;const r=e.slice(n.length);return La.some(a=>r===a||r.startsWith(`${a}/`))},Ae=(e,t,n,r)=>{const a=Nn(n),i=a?n.code:"INTERNAL_SERVER_ERROR",u=a?n.status:500,h=n instanceof Error?n.message:String(n);return{durationMs:t,error:{code:i,message:h,status:u},functionPath:e,ok:!1,...r.fanOut?{fanOut:{failed:0,shards:0,table:r.fanOut.table}}:{},...r.shardKey?{shardKey:r.shardKey}:{}}},Ma=e=>{const{exp:t,expiresAtMs:n}=e;if(typeof n=="number"&&Number.isFinite(n))return n;if(typeof t=="number"&&Number.isFinite(t))return t*1e3},Dt=e=>e.waitUntil?{waitUntil:t=>{e.waitUntil?.(t)}}:void 0,$a=e=>{const t=e?.queue;return typeof t=="string"&&t.length>0?t:"unknown"},Je=new WeakMap,ce=async(e,t,n,r=Je.get(e))=>{const a={"content-type":"application/json"},i=e.headers.get("authorization"),u=e.headers.get("cookie"),h=e.headers.get("x-d1-bookmark"),f=e.headers.get("x-lunora-mutation-id"),m=e.headers.get("x-lunora-client-id"),S=e.headers.get("x-lunora-client-seq");i&&(a.authorization=i),u&&(a.cookie=u),h&&(a["x-d1-bookmark"]=h),f&&(a["x-lunora-mutation-id"]=f),m&&(a["x-lunora-client-id"]=m),S&&(a["x-lunora-client-seq"]=S);const A=e.headers.get("cf-connecting-ip");if(A&&(a["x-lunora-client-ip"]=A),!n)return{claims:null,headers:a,identity:null,userId:null};const T=await n(e,t,r);if(!T||typeof T.userId!="string"||T.userId.length===0)return{claims:null,headers:a,identity:null,userId:null};a["x-lunora-userid"]=Hn(T.userId);const g=Ma(T);g!==void 0&&(a["x-lunora-identity-exp"]=String(g));const{userId:y,..._}=T,p=Object.keys(_).length>0?_:null;return p&&(a["x-lunora-identity"]=Ln(p)),{claims:p,headers:a,identity:T,userId:y}},Ka=new Set(["concat","first","groupBy","max","min","rank","sum","topK"]),Fa=e=>{if(e===void 0)return;if(!e||typeof e!="object")throw new d("RPC `fanOut` must be an object",{code:"BAD_REQUEST",status:400});const t=e;if(typeof t.table!="string"||t.table.length===0)throw new d("RPC `fanOut.table` must be a non-empty string",{code:"BAD_REQUEST",status:400});if(!t.merge||typeof t.merge!="object")throw new d("RPC `fanOut.merge` must be an object",{code:"BAD_REQUEST",status:400});const n=t.merge;if(typeof n.kind!="string"||!Ka.has(n.kind))throw new d("RPC `fanOut.merge.kind` is not a recognized merge strategy",{code:"BAD_REQUEST",status:400});if(n.kind==="topK"){if(typeof n.k!="number"||!Number.isInteger(n.k)||n.k<0)throw new d("RPC `fanOut.merge.k` must be a non-negative integer",{code:"BAD_REQUEST",status:400});if(typeof n.by!="string"||n.by.length===0)throw new d("RPC `fanOut.merge.by` must be a non-empty string",{code:"BAD_REQUEST",status:400})}return t},Ga=(e,t)=>{e?.LUNORA_DEBUG_RPC&&console.warn(`[lunora:rpc] ${t.fanOut?"fan-out":`shard=${t.shardKey??"(root)"}`} ${t.functionPath}`)},Qe=(e,t)=>{const n=t.functions?.[e.functionPath]?.x402;if(n){if(e.fanOut)throw new d("a paid (`.x402`) function cannot be fanned out",{code:"BAD_REQUEST",status:400});if(!t.x402Charge)throw new d(`function "${e.functionPath}" is marked paid (.x402) but no x402Charge gate is configured on the worker`,{code:"MISCONFIGURED",status:500});return n}},Qa=async e=>{const t=await Lt(e);let n;try{n=JSON.parse(t)}catch{throw new d("RPC body must be valid JSON",{code:"BAD_REQUEST",status:400})}if(!n||typeof n!="object"||typeof n.functionPath!="string")throw new d("RPC envelope is missing `functionPath`",{code:"BAD_REQUEST",status:400});const r=n;if(r.args!==void 0&&Ht(r.args,"RPC"),r.shardKey!==void 0&&typeof r.shardKey!="string")throw new d("RPC `shardKey` must be a string",{code:"BAD_REQUEST",status:400});const a=n,i=Fa(a.fanOut),u=a.args??{};if(i&&a.functionPath.startsWith("__lunora_relation__:")){const h=u.table;if(typeof h=="string"&&h!==i.table)throw new d("RPC `args.table` must match the authorized `fanOut.table` for a relation fan-out",{code:"BAD_REQUEST",status:400});u.table=i.table}return{args:u,fanOut:i,functionPath:a.functionPath,shardKey:a.shardKey}},Te=new Map,za=5e3,Wa=4096,Va=async(e,t)=>{const n=Date.now(),r=Te.get(t);if(r!==void 0&&r.expiresMs>n)return r.relayCount;r!==void 0&&Te.delete(t);let a=0;try{const i=await we(e,t).fetch(new Request("https://shard.internal/_lunora/route"));if(i.ok){const h=(await i.json()).relayCount;typeof h=="number"&&h>0&&(a=Math.floor(h))}}catch{a=0}return Bt(Te,Wa),Te.set(t,{expiresMs:n+za,relayCount:a}),a},Nt=(e,t)=>{if(!(e===null||typeof e!="object"))return Object.entries(e).find(([,n])=>n===t)?.[0]},ye=(e,t,n)=>new Request("https://shard.internal/rpc",{body:JSON.stringify({args:t,functionPath:e}),headers:n,method:"POST"}),Ja=["x-lunora-userid","x-lunora-identity","x-lunora-identity-exp"],qa=(e,t)=>{for(const n of Ja){e.delete(n);const r=t[n];r!==void 0&&e.set(n,r)}},Ut=(e,t)=>{const n=new Headers(e.headers),r=[...n.keys()];for(const a of r)a.startsWith("x-lunora-")&&n.delete(a);return qa(n,t),n},Ya=async(e,t,n)=>e.length===0||n.length===0?!1:Xe(await Kt(e,t),n),Ct=(e,t)=>{if(!t||t.length===0)return!1;const n=e.headers.get("authorization");if(!n)return!1;const[r,...a]=n.split(" ");return r?.toLowerCase()!=="bearer"?!1:Xe(t,a.join(" ").trim())},Xa=async(e,t,n)=>{if(!t||t.length===0)return!1;const r=new URL(e.url).searchParams.get("token");return r===null?!1:await Br(t,r)?!0:n?!1:Xe(t,r)},Za=(e,t)=>{if(t===null||typeof t!="object"&&typeof t!="function")return;const n=t;if(typeof n.prepare=="function"&&typeof n.batch=="function"&&typeof n.dump=="function")return ir(`d1:${e}`,t);if(typeof n.list=="function"&&typeof n.head=="function"&&typeof n.createMultipartUpload=="function")return xe(`r2:${e}`,!0);if(typeof n.send=="function"&&typeof n.sendBatch=="function"&&typeof n.get!="function")return xe(`queue:${e}`,!0);if(typeof n.connectionString=="string")return xe(`hyperdrive:${e}`,!0)},qt=e=>{const t=fa(e.trustInboundTraceContext),n=pa(e.trustInboundTraceContext),r=e.defaultShardKey??"__root__",a=cr(e.resolveIdentity,e.identity),i=ut(e.shardDO,e.jurisdiction),u=e.schedulerDO===void 0?void 0:ut(e.schedulerDO,e.jurisdiction);let h=!1;const f=o=>{if(o===void 0||e.jurisdiction===void 0)return o;h||(h=!0,console.warn(`[lunora] jurisdiction "${e.jurisdiction}" pins placement, so region hints (\`shardRegion\`, replica and relay placement) are not sent. Residency wins.`))},m=async(o,s,l,c=e.shardRegion?.(s))=>we(o,s,f(c)).fetch(l);let S;const A=()=>e.adminToken??S;let T;const g=()=>e.requireEphemeralWsToken??T??!0;let y;const _=o=>{const s=o??{};if(y??=Nt(o,e.shardDO),T===void 0&&e.requireEphemeralWsToken===void 0){const c=s.LUNORA_REQUIRE_EPHEMERAL_WS_TOKEN;typeof c=="string"&&c.length>0&&(T=Nr(c,!0))}if(S!==void 0||e.adminToken!==void 0)return;const l=s.LUNORA_ADMIN_TOKEN;typeof l=="string"&&l.length>0&&(S=l)},p=new WeakSet,O=o=>Ct(o,A())||p.has(o),D=async(o,s)=>{const l=await ce(o,s,e.resolveIdentity);if(p.has(o)&&l.headers.authorization===void 0){const c=A();c!==void 0&&(l.headers.authorization=`Bearer ${c}`)}return l};let j=!1,k=!1;const F=()=>{k||(k=!0,console.warn("[lunora] `replicaReads: true` has no effect without `functions` — read eligibility is decided from the function registry."))},H=o=>{if(!e.allowUnauthenticatedShardAccess){const s=o==="fan-out"?"authorizeFanOut":"authorizeShard";throw new d(`${o} access is default-denied: configure \`${s}\` on the worker, or set \`allowUnauthenticatedShardAccess: true\` to explicitly allow unauthenticated ${o} access (relying solely on per-row RLS).`,{code:o==="fan-out"?"FORBIDDEN_FANOUT":"FORBIDDEN_SHARD",status:403})}j||(j=!0,console.warn([`[lunora] SECURITY: serving ${o} access with \`allowUnauthenticatedShardAccess: true\` and no \`authorizeShard\`/\`authorizeFanOut\` — `,"any caller (including unauthenticated ones) can target any shard / fan out across the table. ","This is safe only if every table is protected by per-row RLS. Configure `authorizeShard`/`authorizeFanOut` to gate it."].join("")))},Y=async(o,s)=>{if(s.includes(We)||s.includes(Ve))throw new d("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403});if(e.authorizeShard){if(!await Se(e.authorizeShard({identity:o,shardKey:s})))throw new d("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else s!==r&&H("shard")},C=zo({defaultShard:r,forwardToShard:m,isAdmin:O,queryCoordinator:e.queryCoordinator,resolveForwardContext:D,shardDO:i}),G=async(o,s,l,c,w)=>{const b={"content-type":"application/json","x-lunora-system":"1"};return w?.userId!==void 0&&w.userId.length>0&&(b["x-lunora-userid"]=w.userId),w?.identity!==void 0&&w.identity.length>0&&(b["x-lunora-identity"]=w.identity),c!==void 0&&c.length>0&&(b["x-lunora-mutation-id"]=c),m(i,l,ye(o,s,b))},Q=async(o,s,l,c)=>{const w=l?.[o];if(!w||typeof w.create!="function")throw new d(`${c} targets workflow binding "${o}", which is not bound on env`,{code:"CRON_JOB_FAILED",status:500});if(pr(s))throw new d(`${c} params ${mr}`,{code:"BAD_REQUEST",status:400});await w.create({params:s})},J=async(o,s)=>{if(o.workflow){await Q(o.workflow,o.args??{},s,`cron job "${o.name}"`);return}if(o.functionPath===void 0)throw new d(`cron job "${o.name}" has neither a function target nor a workflow target`,{code:"CRON_JOB_FAILED",status:500});const l=await G(o.functionPath,o.args??{},o.shardKey??r);if(!l.ok)throw new d(`cron job "${o.name}" (${o.functionPath}) failed with shard status ${String(l.status)}`,{code:"CRON_JOB_FAILED",status:500})},M=o=>{if(!O(o))throw new d("admin endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403})},K=(o,s,l)=>{if(M(o),s===void 0)throw new d(l.message,{code:l.code,status:400});return s},oe=async(o,s,l,c)=>{const w=e.cronJobs?.[o];if(!w)return 0;for(const b of w)try{await J(b,s)}catch(I){l.push(c(I))}return w.length},z=async(o,s)=>{if(M(o),$(o,"POST","cron-jobs run"),!e.cronJobs)throw new d("cron-jobs run endpoint requires a `cronJobs` map on the worker",{code:"CRON_JOBS_NOT_CONFIGURED",status:400});const l=await Z(o),c=typeof l.name=="string"?l.name:"";if(c==="")throw new d("cron-jobs run endpoint requires a job `name`",{code:"BAD_REQUEST",status:400});const w=Object.values(e.cronJobs).flat().find(b=>b.name===c);if(!w)throw new d(`no cron job named "${c}" is registered`,{code:"CRON_JOB_NOT_FOUND",status:404});return await J(w,s),Response.json({name:c,ran:!0},{status:200})},de=async o=>{const s=typeof o.pool=="string"&&o.pool.length>0?o.pool:void 0;if(!s||!u||typeof o.id!="string")return;const l=typeof o.instanceName=="string"&&o.instanceName.length>0?o.instanceName:"default";try{await we(u,l).fetch(new Request("https://scheduler.internal/complete",{body:JSON.stringify({id:o.id,pool:s}),headers:{"content-type":"application/json"},method:"POST"}))}catch{}},ue=async(o,s)=>{$(o,"POST","Scheduler dispatch");const l=await Lt(o),c=s??{},w=typeof c.LUNORA_SCHEDULER_SECRET=="string"?c.LUNORA_SCHEDULER_SECRET:void 0,b=e.adminToken??(typeof c.LUNORA_ADMIN_TOKEN=="string"?c.LUNORA_ADMIN_TOKEN:void 0),I=o.headers.get("x-lunora-scheduler-signature");let v=!1;if(I&&w?v=await Ya(w,l,I):b&&(v=Ct(o,b)),!v)throw new d("Scheduler dispatch requires a valid signature or admin bearer",{code:"DISPATCH_UNAUTHENTICATED",status:403});let E;try{E=JSON.parse(l)}catch{throw new d("Scheduler dispatch body must be valid JSON",{code:"BAD_REQUEST",status:400})}const R=E??{},U=R.args??{};if(typeof R.workflow=="string"&&R.workflow.length>0)return await Q(R.workflow,U,s,"scheduled workflow"),await de(R),Response.json({ok:!0},{status:200});if(typeof R.functionPath!="string"||R.functionPath.length===0)throw new d("Scheduler dispatch is missing `functionPath`",{code:"BAD_REQUEST",status:400});const x=typeof R.shardKey=="string"&&R.shardKey.length>0?R.shardKey:r,B=typeof R.id=="string"&&R.id.length>0?R.id:void 0,te=Ca(o),L=await G(R.functionPath,U,x,B,te);return await de(R),L},_e=Mr({assertAdmin:M,getReader:()=>e.authAuditReader}),ve=async(o,s)=>{M(o);const l=e.notifySubscriptionStore;if(l===void 0)return Response.json({result:ze({subscriptions:[]})},{headers:{"content-type":"application/json"},status:200});const c=s?.kind,w=s?.userId,b=s?.limit,I=c==="fcm"||c==="web-push"?c:void 0,v=typeof w=="string"&&w!==""?w:void 0,E=typeof b=="number"&&Number.isFinite(b)?Math.trunc(b):0,R=E>0?Math.min(E,1e3):1e3,x=(await l.list({kind:I,limit:R,userId:v})).filter(B=>I!==void 0&&B.kind!==I?!1:v===void 0||(B.userId??null)===v).map(({keys:B,token:te,...L})=>L);return Response.json({result:ze({subscriptions:x})},{headers:{"content-type":"application/json"},status:200})},ke=async(o,s)=>{if(!s.fanOut){if(s.functionPath===jr)return _e(o,s.args??{});if(s.functionPath===Ha)return ve(o,s.args)}},ae=lo({applyGlobals:e.applyGlobals,assertAdmin:M,exportCursorStore:e.exportCursorStore,exportSinks:e.exportSinks,defaultShardKey:r,knownTables:()=>[...e.listSchemaTables?.()??[]],queryCoordinator:e.queryCoordinator,requireAdminOption:K,resolveForwardContext:D,shardDO:i,streamExportRows:(o,s,l,c)=>Qt(e,o,s,l,c,i),streamingImport:(o,s)=>wo(o,e,s,i),syncGlobals:e.syncGlobals}),Ie=(o,s)=>{const l=o.searchParams.get(s);return l===null||l===""?void 0:l},Pe=o=>{const s=new URL(o.url),l=s.searchParams.get("limit"),c=s.searchParams.get("offset"),w=l===null?void 0:Number.parseInt(l,10),b=c===null?void 0:Number.parseInt(c,10);return{limit:w!==void 0&&Number.isFinite(w)&&w>=0?w:void 0,offset:b!==void 0&&Number.isFinite(b)&&b>=0?b:void 0}},tt=()=>{if(u===void 0)throw new d("scheduled endpoints require a `schedulerDO` namespace on the worker",{code:"SCHEDULER_NOT_CONFIGURED",status:400});return u},Yt=la({checkWsAdmin:async o=>O(o)||Xa(o,A(),g()),requireSchedulerNamespace:tt,resolveSchedulerStub:o=>(M(o),we(tt(),e.schedulerInstanceName??"default")),schedulerInstanceName:e.schedulerInstanceName??"default"}),Xt=Sa({assertAdmin:M,resolveWorkflowsClient:e.workflowsClient??(()=>{})}),Zt=Xn({assertAdmin:M,parsePaging:Pe,queryParameter:Ie,readBodyBytes:Wn,requireAdminOption:K,storage:{storageBuckets:e.storageBuckets,storageDelete:e.storageDelete,storageDownload:e.storageDownload,storageList:e.storageList,storageSignedUrl:e.storageSignedUrl,storageUpload:e.storageUpload}}),en=Zr({options:e,readJsonBody:Z,requireAdminOption:K}),tn=ga({readJsonBody:Z,requireAdminOption:K,vectorIntrospector:e.vectorIntrospector}),nn=Do({kvIntrospector:e.kvIntrospector,readJsonBody:Z,requireAdminOption:K}),rn=dr({logArchive:e.logArchive,readJsonBody:Z,requireAdminOption:K}),on=ko({assertAdmin:M,options:{cronJobs:e.cronJobs,functions:e.functions,globalIntrospector:e.globalIntrospector,openApiSpec:e.openApiSpec,openRpcSpec:e.openRpcSpec},parsePaging:Pe,queryParameter:Ie,requireAdminOption:K}),an=o=>{const s=[],l=i??o?.SHARD;if(l!==void 0&&s.push(sr("durable-object:default",l,r)),e.health?.disableBindingProbes!==!0)for(const[c,w]of Object.entries(o??{})){const b=Za(c,w);b!==void 0&&s.push(b)}for(const c of e.health?.probes??[])s.push(c);return s},sn=ar({appName:e.health?.appName,appVersion:e.health?.appVersion,auth:e.health?.auth??"public",cacheTtlMs:e.health?.cacheTtlMs,isAdmin:O,resolveProbes:an}),cn=o=>{const s=e.schedulerInstanceName??"default",l=()=>we(o,s),c=async(E,R)=>{const U=await l().fetch(new Request(`https://scheduler.internal${E}`,R));if(!U.ok)throw new d(`ctx.scheduler: SchedulerDO ${E} failed (${String(U.status)}): ${await U.text()}`,{code:"INTERNAL",status:500});return await U.json()},w=async(E,R)=>await c(E,{body:JSON.stringify(R),headers:{"content-type":"application/json"},method:"POST"}),b=E=>{const R=E;if(R==null)throw new d("ctx.scheduler: target is required — pass a reference from the generated `internal` / `workflows` / `agents`",{code:"BAD_REQUEST",status:400});if(typeof R.binding=="string"&&R.binding.length>0)return{workflow:R.binding};if(typeof R.__lunoraRef=="string")return{functionPath:R.__lunoraRef};throw new d("ctx.scheduler: expected a reference from the generated `internal` / `workflows` / `agents` — a bare function-path string is refused here, because an HTTP action can be reached unauthenticated",{code:"BAD_REQUEST",status:400})},I=async()=>await wr(async E=>c(E===void 0?"/list":`/list?cursor=${encodeURIComponent(E)}`,{method:"GET"})),v=async(E,R,U={})=>{const{id:x}=await w("/schedule",{args:U,scheduledFor:E,...b(R)});return x};return{cancel:async E=>await w("/cancel",{id:E}),get:async E=>await c(`/get?id=${encodeURIComponent(E)}`,{method:"GET"}),list:I,runAfter:async(E,R,U)=>{if(!Number.isFinite(E)||E<0)throw new d("ctx.scheduler.runAfter: `delayMs` must be a non-negative finite number",{code:"INVALID_INPUT",status:400});return await v(Date.now()+E,R,U)},runAt:async(E,R,U)=>{if(!Number.isFinite(E))throw new d("ctx.scheduler.runAt: `date` must be a non-negative finite number",{code:"INVALID_INPUT",status:400});return await v(E,R,U)}}},dn=async(o,s,l)=>{const{claims:c,headers:w,userId:b}=await ce(o,s,a),I=async(v,E={})=>{const R=v.__lunoraRef;if(typeof R!="string")throw new d("ctx.run*: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});const U=ye(R,E,{...w,"x-lunora-system":"1"}),x=await m(i,r,U),B=await x.json();if(B.error)throw new d(B.error.message??"shard RPC failed",{code:B.error.code??"INTERNAL",status:x.status});return B.result};return{auth:{getIdentity:()=>Promise.resolve(c),userId:b},cache:l.cache,fetch:globalThis.fetch.bind(globalThis),runAction:I,runMutation:I,runQuery:I,...u===void 0?{}:{scheduler:cn(u)},...l.waitUntil===void 0?{}:{waitUntil:l.waitUntil.bind(l)},...e.storage===void 0?{}:{storage:fr(e.storage(s))}}},un=async(o,s,l)=>{if(!e.httpRouter)return;const c=await dn(o,s,l);try{return await e.httpRouter.fetch(o,{...s,__lunoraCtx:c},l)}catch(w){return console.error("[lunora] httpRouter (SSR) handler threw:",w),new Response("Internal Server Error",{status:500})}},ln=async(o,s,l)=>{if(o.headers.get("Upgrade")!=="websocket")throw new d("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});const c=ht(o,se);if(c)return c;const w=l.searchParams.get("shard")??r,{headers:b,identity:I}=await ce(o,s,a);await Y(I,w);const v=Ut(o,b),E=Nt(s,e.shardDO);if(E!==void 0){v.set("x-lunora-shard-binding",E);const R=await Va(i,w);if(R>0){const U=vr(w,Math.floor(Math.random()*R));return m(i,U,new Request(o,{headers:v}),ft(o))}}return m(i,w,new Request(o,{headers:v}))},hn=async(o,s,l)=>{const{voiceAgents:c}=e;if(c===void 0)return new Response("Not found",{status:404});if(o.headers.get("Upgrade")!=="websocket")return new Response("Expected a WebSocket upgrade",{headers:{allow:"GET"},status:426});const w=ht(o,se);if(w)return w;let b;try{b=decodeURIComponent(l.pathname.slice(Pt.length))}catch{return new Response("Unknown voice agent",{status:404})}const I=Object.hasOwn(c,b)?c[b]:void 0;if(I===void 0)return new Response("Unknown voice agent",{status:404});const v=l.searchParams.get("threadKey");if(v===null||v.length===0)return new Response("Missing threadKey",{status:400});const{headers:E,identity:R}=await ce(o,s,a);if(e.authorizeShard){if(!await Se(e.authorizeShard({identity:R,shardKey:v})))throw new d("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else H("shard");const U=Ut(o,E);return m(I,v,new Request(o,{headers:U}))},fn=async(o,s,l)=>{if(e.authorizeFanOut){if(!await Se(e.authorizeFanOut(l,o.table,s)))throw new d("Forbidden fan-out",{code:"FORBIDDEN_FANOUT",status:403});return}if(s.startsWith("__lunora_relation__:"))throw new d("reverse cross-backend relation reads (`__lunora_relation__:*`) require `authorizeFanOut` to be configured on the worker",{code:"FORBIDDEN_FANOUT",status:403});if(e.authorizeShard)throw new d("Fan-out requires `authorizeFanOut` to be configured on the worker when `authorizeShard` is set",{code:"FORBIDDEN_FANOUT",status:403});H("fan-out")},Re=async(o,s)=>{if(!(!o.fanOut&&o.functionPath.startsWith("__lunora_admin__:"))){if(o.fanOut){await fn(o.fanOut,o.functionPath,s);return}await Y(s,o.shardKey??r)}},pn=(o,s,l)=>{if(e.replicaReads!==!0)return;if(e.functions===void 0){F();return}if(e.functions[s]?.kind!=="query"||l.includes(Ve)||l.includes(We))return;const c=ft(o);return c===void 0?void 0:{name:kr(l,c),region:c}},mn=async(o,s,l,c,w)=>{const b=pn(o,s,c);if(b!==void 0){const I={...w,"x-lunora-replica-read":"1",...y===void 0?{}:{"x-lunora-shard-binding":y}},v=Ir(o.headers.get("x-lunora-min-seq"));v!==void 0&&(I["x-lunora-min-seq"]=String(v));const E=await m(i,b.name,ye(s,l,I),b.region);if(E.status!==421)return E}return m(i,c,ye(s,l,w))},De=async(o,s,l,c,w,b)=>{const I=Date.now(),{observability:v,sampling:E}=e,R=Ge(o),{decision:U,ignoredUpstream:x,trace:B}=ea(o,{...E===void 0?{}:{sampling:E},trustInbound:t(o)});x&&n();const te={...w,"x-lunora-sample-errors":U.keepErrors?"1":"0"};ta(B,te);try{const L=await mn(o,s,l,c,te);ie(v,{...R,...It(B),durationMs:Date.now()-I,functionPath:s,ok:L.ok,shardKey:c,...L.ok?{}:{error:{code:"SHARD_ERROR",message:`shard returned ${String(L.status)}`,status:L.status}}},b,void 0,{isTraced:B.sampled,keepErrors:U.keepErrors});const ee=new Response(L.body,{headers:L.headers,status:L.status,statusText:L.statusText});return ee.headers.set("x-lunora-shard-key",c),ee}catch(L){throw ie(v,{...R,...It(B),...Ae(s,Date.now()-I,L,{shardKey:c})},b,void 0,{isTraced:B.sampled,keepErrors:U.keepErrors}),L}},wn=o=>{if(o.fanOut&&o.shardKey)throw new d("RPC envelope cannot set both `shardKey` and `fanOut`",{code:"BAD_REQUEST",status:400});if(!o.fanOut&&o.functionPath.startsWith("__lunora_relation__:"))throw new d("`__lunora_relation__:*` is a fan-out-only reserved RPC and cannot be dispatched to a single shard",{code:"FORBIDDEN",status:403});if(o.fanOut&&!e.queryCoordinator)throw new d("RPC envelope set `fanOut` but no `queryCoordinator` is configured on the worker",{code:"BAD_REQUEST",status:400})},gn=async(o,s,l)=>{$(o,"POST","RPC");const c=await Qa(o);Ga(s,c),wn(c);const w=await ke(o,c);if(w!==void 0)return w;const{headers:b,identity:I}=await ce(o,s,a);await Re(c,I);const v=Qe(c,e);{const E=Date.now(),{observability:R}=e,U=Ge(o),x=Ee(s,o,l&&(L=>l.waitUntil?.(L)));if(c.fanOut){const L=e.queryCoordinator;if(!L)throw new d("RPC envelope set `fanOut` but no `queryCoordinator` is configured on the worker",{code:"BAD_REQUEST",status:400});try{const ee=await L.fanOut(i,{args:c.args??{},fanOut:c.fanOut,functionPath:c.functionPath,headers:b});return ie(R,{durationMs:Date.now()-E,fanOut:{failed:ee.failed,shards:ee.ok+ee.failed,table:c.fanOut.table},functionPath:c.functionPath,...U,ok:!0},x),Response.json(ee,{headers:{"content-type":"application/json"},status:200})}catch(ee){throw ie(R,{...Ae(c.functionPath,Date.now()-E,ee,{fanOut:{table:c.fanOut.table}}),...U},x),ee}}const B=c.shardKey??r,te=()=>De(o,c.functionPath,c.args??{},B,b,x);return v&&e.x402Charge?e.x402Charge(o,{functionPath:c.functionPath,price:v.price},te,Fe(l)):te()}},yn=async(o,s,l)=>{$(o,"POST","RPC batch");const c=await Z(o),{calls:w}=c;if(!Array.isArray(w))throw new d("RPC batch `calls` must be an array",{code:"BAD_REQUEST",status:400});const{headers:b,identity:I}=await ce(o,s,a),v=to(w,r);for(const W of v.values())for(const V of W)if(e.functions?.[V.functionPath]?.x402)throw new d(`paid (\`.x402\`) function "${V.functionPath}" cannot be called in a batch; dispatch it individually over ${kt}`,{code:"BAD_REQUEST",status:400});await Promise.all([...v.entries()].flatMap(([W,V])=>V.map(ne=>Re({args:ne.args,functionPath:ne.functionPath,shardKey:W},I))));const{observability:E}=e,R=Ee(s,o,l&&(W=>l.waitUntil?.(W))),U=Ge(o),x=[],B=[],te=(W,V,ne,le)=>({body:{error:{code:ne,message:le}},id:W.id,status:V}),L=(W,V,ne,le,fe)=>{for(const q of W)ie(E,fe(q),R),x.push(te(q,V,ne,le))},ee=(W,V,ne,le,fe)=>{for(const q of W){const pe=le.get(q.id)??fe,ge=pe<400;ie(E,{durationMs:ne,functionPath:q.functionPath,...U,ok:ge,shardKey:V,...ge?{}:{error:{code:"SHARD_ERROR",message:`batched call returned ${String(pe)}`,status:pe}}},R)}};await Promise.all([...v.entries()].map(async([W,V])=>{const ne=new Headers(b);ne.set("content-type","application/json");const le=new Request("https://shard.internal/rpc-batch",{body:JSON.stringify({calls:V}),headers:ne,method:"POST"}),fe=Date.now();let q;try{q=await m(i,W,le)}catch(X){const Be=Date.now()-fe,{body:st}=Un(X,{fallbackCode:"SHARD_UNAVAILABLE",redactedMessage:"shard unavailable"});L(V,502,st.code,st.message,Dn=>({...Ae(Dn.functionPath,Be,X,{shardKey:W}),...U}));return}const pe=Date.now()-fe,ge=q.headers.get("x-d1-bookmark");ge&&B.push(ge);let Ue;try{Ue=await q.json()}catch{const X=`shard batch returned a non-JSON response (${String(q.status)})`;L(V,q.status,"SHARD_ERROR",X,Be=>({durationMs:pe,error:{code:"SHARD_ERROR",message:X,status:q.status},functionPath:Be.functionPath,...U,ok:!1,shardKey:W}));return}const Ce=Array.isArray(Ue.results)?Ue.results:[],In=new Map(Ce.map(X=>[X.id,X.status??q.status])),Pn=new Set(Ce.map(X=>X.id));ee(V,W,pe,In,q.status),x.push(...Ce);for(const X of V)Pn.has(X.id)||x.push(te(X,q.status,"SHARD_ERROR",`shard batch omitted result for call ${String(X.id)}`))}));const ot={"content-type":"application/json"},[at]=B;return B.length===1&&at!==void 0&&(ot["x-d1-bookmark"]=at),Response.json({results:x},{headers:ot,status:200})},bn=async(o,s,l,c={},w={})=>{try{const b=l.__lunoraRef;if(typeof b!="string")throw new d("serverQuery: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});const{headers:I,identity:v}=await ce(o,s,a,w.context),E={args:c,functionPath:b,shardKey:w.shardKey};await Re(E,v);const R=w.shardKey??r,U=Ee(s,o,w.waitUntil),x=()=>De(o,b,c,R,I,U),B=Qe(E,e);return B&&e.x402Charge?await e.x402Charge(o,{functionPath:b,price:B.price},x,Fe(w.waitUntil?{waitUntil:w.waitUntil}:w.context)):await x()}catch(b){return it(b)}},nt=async(o,s,l)=>{const{observability:c}=e,w=Date.now(),b=Oe(16),I=Oe(8),v=Dt(s);try{const E=await l();return ie(c,{durationMs:Date.now()-w,functionPath:o,ok:!0,spanId:I,traceId:b},v),E}catch(E){throw ie(c,{...Ae(o,Date.now()-w,E,{}),spanId:I,traceId:b},v),E}finally{dt(c,v)}},_n=async(o,s,l)=>{_(s);const c=[],w=R=>R instanceof Error?R:new Error(String(R)),b=e.crons?.[o.cron];if(b)try{await b(o,s,l)}catch(R){c.push(w(R))}const I=await oe(o.cron,s,c,w),v=!!e.backupStore&&e.backupCron!==void 0&&e.backupCron===o.cron;if(v)try{await Jr(e,i,A(),o)}catch(R){c.push(w(R))}if(!b&&I===0&&!v){const R=[...new Set([...Object.keys(e.crons??{}),...Object.keys(e.cronJobs??{})])];console.warn(`[lunora] scheduled("${o.cron}") fired but no cron handler is registered for that expression. Registered: ${R.length===0?"(none)":R.join(", ")}. Check that \`triggers.crons\` in wrangler.jsonc matches the app's cron definitions.`)}const[E]=c;if(c.length===1&&E)throw E;if(c.length>1)throw new AggregateError(c,`scheduled("${o.cron}") had ${String(c.length)} failure(s)`)},Rn=async(o,s)=>{try{const l=o??{},c=e.adminToken??(typeof l.LUNORA_ADMIN_TOKEN=="string"?l.LUNORA_ADMIN_TOKEN:void 0);if(!c||c.length===0)return;await m(i,r,ye(xa,{outcome:s},{authorization:`Bearer ${c}`,"content-type":"application/json"}))}catch{}},En=async(o,s,l,c)=>{if(!e.authHandler)return;const w=await e.authHandler(o);if(!w)return;const b=e.authBasePath??Ba;return ja(l.pathname,b)&&c.waitUntil?.(Rn(s,w.status>=400?"fail":"ok")),w},Sn=async({args:o,env:s,functionPath:l,request:c,shardKey:w,waitUntil:b})=>{Ht(o,"REST");const I={functionPath:l,...w===void 0?{}:{shardKey:w}},{headers:v,identity:E}=await ce(c,s,a);await Re(I,E);const R=w??r,U=Ee(s,c,b),x=()=>De(c,l,o,R,v,U),B=Qe(I,e);return B&&e.x402Charge?e.x402Charge(c,{functionPath:l,price:B.price},x,Fe({waitUntil:b})):x()},An=zn({functions:e.functions??{},invoke:Sn,readJsonBody:Z,edgeCache:e.restEdgeCache,...e.restRateLimit?{rateLimit:e.restRateLimit}:{}}),Ne=e.routes!==void 0&&Object.keys(e.routes).length>0?e.routes:void 0,Tn={[Na]:o=>o.method!=="GET"&&o.method!=="HEAD"?new Response(void 0,{headers:{allow:"GET, HEAD"},status:405}):Response.json({ok:!0},{headers:{"cache-control":"no-store"}}),[Oa]:(o,s,l)=>ln(o,s,l),[kt]:(o,s,l,c)=>gn(o,s,c),[Ta]:(o,s,l,c)=>yn(o,s,c),[va]:(o,s)=>ue(o,s),[ka]:(o,s)=>z(o,s),[Ia]:async o=>{$(o,"POST","ws-token"),M(o);const s=A();if(s===void 0)throw new d("ws-token minting requires a configured admin token",{code:"ADMIN_TOKEN_NOT_CONFIGURED",status:400});const l=await Cr(s);return Response.json(l,{headers:{"cache-control":"no-store"}})},...C,...ae,...Yt,...Xt,...Zt,...en,...tn,...nn,...rn,...on,...sn,...An,...Lr({assertAdmin:M,getAuthAdmin:()=>e.authAdmin,parsePaging:Pe,queryParameter:Ie,readJsonBody:Z})};let se=lt(e.security),rt=!1;const On=o=>{rt||(rt=!0,se=lt(e.security,o??{}))},vn=async(o,s)=>{if(!(e.adminGate===void 0||!Ua(s)))try{await Se(e.adminGate(o,Je.get(o)))&&p.add(o)}catch{}},kn=async(o,s,l)=>{Je.set(o,l);const c=new URL(o.url);if(o.method==="POST"||o.method==="PUT"){const v=Number(o.headers.get("content-length")??""),E=Aa[c.pathname]??xt;if(Number.isFinite(v)&&v>E)throw new d("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413})}const w=await En(o,s,c,l);if(w)return w;if(Ne){const v=`${o.method} ${c.pathname}`,E=Ne[v]??Ne[c.pathname];if(E)return E(o,s,l)}const b=Tn[c.pathname];if(b)return await vn(o,c.pathname),b(o,s,c,l);if(e.voiceAgents!==void 0&&c.pathname.startsWith(Pt))return hn(o,s,c);const I=await un(o,s,l);return I||new Response("Not found",{status:404})};return{async fetch(o,s,l){e.passThroughOnException&&l.passThroughOnException?.(),On(s),_(s);const c=lr(o,se);if(c)return c;const w=hr(o,se);if(w)return He(w,o,se);try{const b=await kn(o,s,l);return He(b,o,se)}catch(b){return He(it(b),o,se)}finally{dt(e.observability,Dt(l))}},async queue(o,s,l){await nt(`queue:${$a(o)}`,l,async()=>{await e.queue?.(o,s,l)})},async scheduled(o,s,l){await nt(`cron:${o.cron}`,l,async()=>{await _n(o,s,l)})},serverQuery:bn}},es=e=>qt(e),ts=e=>typeof e=="function"?{fetch:e}:e,ns=e=>!!(e.crons??e.cronJobs??e.backupCron),As=(e,t)=>{const n=ts(e),r=typeof e=="object"&&typeof e.scheduled=="function"?e.scheduled:void 0,a=u=>{const h=es({...u,httpRouter:n});return r!==void 0&&!ns(u)?{...h,scheduled:async(f,m,S)=>{await r(f,m,S)}}:h};if(typeof t!="function")return a(t);const i=t;return{fetch:(u,h,f)=>a(i(h)).fetch(u,h,f),queue:(u,h,f)=>a(i(h)).queue?.(u,h,f)??Promise.resolve(),scheduled:(u,h,f)=>a(i(h)).scheduled(u,h,f),serverQuery:(u,h,f,m,S)=>a(i(h)).serverQuery(u,h,f,m,S)}},rs=(e,t)=>{if(typeof e=="function")return e(t);const n=e.shardDO??t?.SHARD;if(!n)throw new d("@lunora/runtime: no shard Durable Object namespace found. Bind `SHARD` in wrangler.jsonc, or pass `createLunoraHandler({ shardDO: env.MY_SHARD })`.");return{...e,shardDO:n}},Ts=(e={})=>(t,n,r)=>qt(rs(e,n)).fetch(t,n,r??Cn),Os=e=>e;export{jr as GET_AUTH_AUDIT_LOG_OP,Cn as NOOP_EXECUTION_CONTEXT,Is as composeIdentityResolvers,es as composeWorker,Ts as createLunoraHandler,qt as createWorker,Os as defineRpcEnvelope,Va as probeRelayCount,rs as resolveLunoraOptions,Ps as routeIdentityResolvers,As as withFrameworkWorker};
|