@lunora/runtime 1.0.0-alpha.232 → 1.0.0-alpha.234
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 +5 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/DEFAULT_REGISTRY_CACHE_TTL_MS-BAyo4d38.mjs +1 -0
- package/dist/packem_shared/{composeWorker-CDD6Inr3.mjs → composeWorker-Dycssvhe.mjs} +5 -5
- package/package.json +2 -2
- package/dist/packem_shared/DEFAULT_REGISTRY_CACHE_TTL_MS-Jrpa-kBx.mjs +0 -1
package/dist/index.d.mts
CHANGED
|
@@ -4201,6 +4201,11 @@ interface WorkerOptions {
|
|
|
4201
4201
|
* other DOs of a `.shardBy(...)` one.
|
|
4202
4202
|
*/
|
|
4203
4203
|
listSchemaTables?: () => ReadonlyArray<string>;
|
|
4204
|
+
/**
|
|
4205
|
+
* The `"METHOD path"` keys of the declared live-stream routes served by `httpRouter`. They are dispatched ahead of
|
|
4206
|
+
* {@link WorkerOptions.routes}, so an explicit route at one of those keys can not shadow a declared stream.
|
|
4207
|
+
*/
|
|
4208
|
+
liveStreamRoutes?: ReadonlyArray<string>;
|
|
4204
4209
|
/**
|
|
4205
4210
|
* Whether the target serves live topic streams. Defaults to `true`. `false` keeps
|
|
4206
4211
|
* `ctx.live` on the HTTP action context and on a direct queue consumer, but its `publish`
|
package/dist/index.d.ts
CHANGED
|
@@ -4201,6 +4201,11 @@ interface WorkerOptions {
|
|
|
4201
4201
|
* other DOs of a `.shardBy(...)` one.
|
|
4202
4202
|
*/
|
|
4203
4203
|
listSchemaTables?: () => ReadonlyArray<string>;
|
|
4204
|
+
/**
|
|
4205
|
+
* The `"METHOD path"` keys of the declared live-stream routes served by `httpRouter`. They are dispatched ahead of
|
|
4206
|
+
* {@link WorkerOptions.routes}, so an explicit route at one of those keys can not shadow a declared stream.
|
|
4207
|
+
*/
|
|
4208
|
+
liveStreamRoutes?: ReadonlyArray<string>;
|
|
4204
4209
|
/**
|
|
4205
4210
|
* Whether the target serves live topic streams. Defaults to `true`. `false` keeps
|
|
4206
4211
|
* `ctx.live` on the HTTP action context and on a direct queue consumer, but its `publish`
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{declareAppJurisdiction as t}from"./packem_shared/declareAppJurisdiction-DEba2p42.mjs";import{BACKUP_KEY_PREFIX as s,backupManifestKey as i,backupObjectKey as p,backupObjectKeyOfManifest as n,isBackupManifestEntry as c,isBackupManifestKey as m,normalizeBackupPrefix as f}from"./packem_shared/BACKUP_KEY_PREFIX-BOtSu-_3.mjs";import{toAirbyteMessages as x,toFivetranResponse as R}from"./packem_shared/toAirbyteMessages-DY0vsuEn.mjs";import{composeWorker as l,createLunoraHandler as d,createWorker as u,defineRpcEnvelope as _,resolveLunoraOptions as k,withFrameworkWorker as b}from"./packem_shared/composeWorker-
|
|
1
|
+
import{declareAppJurisdiction as t}from"./packem_shared/declareAppJurisdiction-DEba2p42.mjs";import{BACKUP_KEY_PREFIX as s,backupManifestKey as i,backupObjectKey as p,backupObjectKeyOfManifest as n,isBackupManifestEntry as c,isBackupManifestKey as m,normalizeBackupPrefix as f}from"./packem_shared/BACKUP_KEY_PREFIX-BOtSu-_3.mjs";import{toAirbyteMessages as x,toFivetranResponse as R}from"./packem_shared/toAirbyteMessages-DY0vsuEn.mjs";import{composeWorker as l,createLunoraHandler as d,createWorker as u,defineRpcEnvelope as _,resolveLunoraOptions as k,withFrameworkWorker as b}from"./packem_shared/composeWorker-Dycssvhe.mjs";import{createCrossShardRelationCapabilities as C}from"./packem_shared/createCrossShardRelationCapabilities-C8lpyW1a.mjs";import{DEFAULT_REGISTRY_CACHE_TTL_MS as A,SHARD_REGISTRY_DO_NAME as L,createDynamicShardRegistry as T}from"./packem_shared/DEFAULT_REGISTRY_CACHE_TTL_MS-BAyo4d38.mjs";import{parseStackFrames as H,toError as P}from"./packem_shared/parseStackFrames-CZddjveh.mjs";import{LunoraError as v,toErrorResponse as I}from"./packem_shared/LunoraError-PkZWF-_g.mjs";import{c as F,a as M,d as N,r as G,b as K,s as U,w}from"./packem_shared/export-tap-C2B_SATf.mjs";import{HEALTH_PATH as Y,HEALTH_READY_PATH as z,buildHealthRoutes as X,d1Probe as j,durableObjectProbe as V,presenceProbe as W}from"./packem_shared/HEALTH_PATH-B8ndDG3s.mjs";import{LOG_ARCHIVE_PATH as J,resolveLogArchiveFromEnv as Q}from"./packem_shared/LOG_ARCHIVE_PATH-dTuCzfyj.mjs";import{memoizeIdentity as $,memoizeIdentityPerRequest as ee}from"./packem_shared/memoizeIdentity-BNnHkqeF.mjs";import{e as oe,a as te}from"./packem_shared/observability-9slk__Gi.mjs";import{enrichSink as se,filterSink as ie}from"./packem_shared/enrichSink-44NOapaE.mjs";import{a as ne,c as ce,b as me,o as fe,p as Ee,w as xe}from"./packem_shared/observability-sinks-lLKqc_rV.mjs";import{D as Se,c as le}from"./packem_shared/pipeline-log-reader-C-nuWG_e.mjs";import{createQueryCoordinator as ue,createStaticShardRegistry as _e}from"./packem_shared/createQueryCoordinator-Bt6xVTQn.mjs";import{applyJurisdiction as be,resolveShard as ye}from"./packem_shared/applyJurisdiction-DKQE8kOA.mjs";import{a as Oe,r as Ae,b as Le}from"./packem_shared/rest-cache-CmHN871W.mjs";import{a as he,b as He,c as Pe,r as ge}from"./packem_shared/rest-routes-CDQ1F7kI.mjs";import{decorateResponse as Ie,enforceOrigin as De,handleCorsPreflight as Fe,resolveSecurity as Me}from"./packem_shared/decorateResponse-CdelJSUs.mjs";import{createShardClient as Ge}from"./packem_shared/createShardClient-BlcK9Nok.mjs";import{STORAGE_UPLOAD_MAX_BODY_BYTES as Ue}from"./packem_shared/STORAGE_UPLOAD_MAX_BODY_BYTES-DiZho96u.mjs";import{LOG_ARCHIVE_NOT_CONFIGURED as Be}from"./packem_shared/LOG_ARCHIVE_NOT_CONFIGURED-CDpi4yFD.mjs";import{NOOP_EXECUTION_CONTEXT as ze}from"./packem_shared/NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{composeIdentityResolvers as je,routeIdentityResolvers as Ve}from"./packem_shared/composeIdentityResolvers-CpdHuDyk.mjs";const e="0.0.0";export{s as BACKUP_KEY_PREFIX,Se as DEFAULT_LOG_COLUMNS,A as DEFAULT_REGISTRY_CACHE_TTL_MS,Y as HEALTH_PATH,z as HEALTH_READY_PATH,Be as LOG_ARCHIVE_NOT_CONFIGURED,J as LOG_ARCHIVE_PATH,v as LunoraError,ze as NOOP_EXECUTION_CONTEXT,L as SHARD_REGISTRY_DO_NAME,Ue as STORAGE_UPLOAD_MAX_BODY_BYTES,e as VERSION,ne as analyticsEngineSink,be as applyJurisdiction,Oe as applyRestCache,he as argsFromQuery,i as backupManifestKey,p as backupObjectKey,n as backupObjectKeyOfManifest,X as buildHealthRoutes,He as buildRestRoutes,ce as combineSinks,je as composeIdentityResolvers,l as composeWorker,me as consoleSink,C as createCrossShardRelationCapabilities,T as createDynamicShardRegistry,F as createKvCursorStore,d as createLunoraHandler,M as createMemoryCursorStore,le as createPipelineLogReader,ue as createQueryCoordinator,Pe as createRestRateLimit,Ge as createShardClient,_e as createStaticShardRegistry,u as createWorker,j as d1Probe,t as declareAppJurisdiction,Ie as decorateResponse,N as defineExportSink,_ as defineRpcEnvelope,V as durableObjectProbe,oe as emitLogEvent,te as emitRpcEvent,De as enforceOrigin,se as enrichSink,ie as filterSink,Fe as handleCorsPreflight,c as isBackupManifestEntry,m as isBackupManifestKey,$ as memoizeIdentity,ee as memoizeIdentityPerRequest,f as normalizeBackupPrefix,fe as otlpSink,H as parseStackFrames,Ee as pipelineLogSink,W as presenceProbe,G as r2Sink,Ae as requestCarriesCredentials,Q as resolveLogArchiveFromEnv,k as resolveLunoraOptions,Me as resolveSecurity,ye as resolveShard,Le as restCacheHeaders,ge as restSurfaceFromRegistry,Ve as routeIdentityResolvers,K as runExportTap,U as sanitizeChange,x as toAirbyteMessages,P as toError,I as toErrorResponse,R as toFivetranResponse,w as webhookExportSink,xe as webhookSink,b as withFrameworkWorker};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as c}from"./LunoraError-PkZWF-_g.mjs";import{applyJurisdiction as l,resolveShard as m}from"./applyJurisdiction-DKQE8kOA.mjs";const R="__lunora_shard_registry__",T=3e4,p="https://shard-registry.internal",w=async n=>await n.json(),A=n=>{const f=n.instanceName??R,d=n.cacheTtlMs??T,a=new Map,s=new Map,S=l(n.namespace,n.jurisdiction),h=()=>m(S,f),y=async(e,t)=>h().fetch(new Request(`${p}${e}`,{body:JSON.stringify(t),headers:{"content-type":"application/json"},method:"POST"})),g=async e=>h().fetch(new Request(`${p}${e}`,{method:"GET"}));return{invalidate(e){e===void 0?(a.clear(),s.clear()):(a.delete(e),s.delete(e))},async listShardKeys(e){const t=Date.now(),r=a.get(e);if(r&&r.expiresAt>t)return r.shardKeys;const u=s.get(e);if(u)return u;const o=(async()=>{const i=await g(`/list?table=${encodeURIComponent(e)}`);if(!i.ok)throw new c(`shard registry /list returned ${String(i.status)}`);const{shardKeys:_}=await w(i);return _})();d>0&&s.set(e,o);try{const i=await o;return d>0&&s.get(e)===o&&a.set(e,{expiresAt:t+d,shardKeys:i}),i}finally{s.get(e)===o&&s.delete(e)}},async register(e,t){const r=await y("/register",{shardKey:t,table:e});if(!r.ok)throw new c(`shard registry /register returned ${String(r.status)}`);a.delete(e),s.delete(e)},async snapshot(){const e=await g("/snapshot");if(!e.ok)throw new c(`shard registry /snapshot returned ${String(e.status)}`);const{tables:t}=await w(e);return t},async unregister(e,t){const r=await y("/unregister",{shardKey:t,table:e});if(!r.ok)throw new c(`shard registry /unregister returned ${String(r.status)}`);a.delete(e),s.delete(e)}}};export{T as DEFAULT_REGISTRY_CACHE_TTL_MS,R as SHARD_REGISTRY_DO_NAME,A as createDynamicShardRegistry};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{isLunoraError as br,toErrorBody as _r}from"@lunora/errors";import{encodeWire as ye,decodeWire as Ze,encodeArgsOrThrow as Rr}from"@lunora/wire";import{d as Rt,E as Et,a as Er,b as Ar,W as At}from"./error-detail-C46mdOTW.mjs";import{e as an}from"./evict-oldest-BNXsKx4s.mjs";import{NOOP_EXECUTION_CONTEXT as Sr}from"./NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{i as Tr,e as vr,a as Or,E as St,d as Ir}from"./identity-header-pR617HTs.mjs";import{O as cn,a as dn}from"./origin-paywall-B6eOO67m.mjs";import{o as be,b as un,p as Pr,m as kr,d as Dr,a as Nr,r as Ur}from"./otlp-resource-Ch_8_U0e.mjs";import{r as Cr,f as Tt,a as ue,S as vt}from"./observability-9slk__Gi.mjs";import{t as Br,f as xr}from"./base64-Bl1_r2k1.mjs";import{d as ne,e as oe,M as ln,b as Hr,f as Lr,g as hn,w as jr,h as fn,t as Mr}from"./rest-routes-CDQ1F7kI.mjs";import{LunoraError as c,toErrorResponse as Ot}from"./LunoraError-PkZWF-_g.mjs";import{a as M,m as ge}from"./method-guard-8Jo4Q8uS.mjs";import{normalizeBackupPrefix as st,BACKUP_KEY_PREFIX as at,isBackupManifestKey as $r,backupObjectKeyOfManifest as pn,backupObjectKey as Fr,backupManifestKey as Kr}from"./BACKUP_KEY_PREFIX-BOtSu-_3.mjs";import{toHex as Gr,buildStorageAdminRoutes as Qr,STORAGE_UPLOAD_MAX_BODY_BYTES as Wr,STORAGE_PATH as zr}from"./STORAGE_UPLOAD_MAX_BODY_BYTES-DiZho96u.mjs";import{b as Vr,e as Jr,f as It,g as Yr,h as qr}from"./export-tap-C2B_SATf.mjs";import{buildHealthRoutes as Xr,durableObjectProbe as Zr,d1Probe as eo,presenceProbe as Fe}from"./HEALTH_PATH-B8ndDG3s.mjs";import{wrapResolverWithContract as to}from"./composeIdentityResolvers-CpdHuDyk.mjs";import{composeIdentityResolvers as Wi,routeIdentityResolvers as zi}from"./composeIdentityResolvers-CpdHuDyk.mjs";import{buildLogArchiveAdminRoutes as no}from"./LOG_ARCHIVE_PATH-dTuCzfyj.mjs";import{pruneShardRegistry as ro,createQueryCoordinator as oo,createDefaultShardRegistry as so}from"./createQueryCoordinator-Bt6xVTQn.mjs";import{resolveShard as _e,applyJurisdiction as Ke}from"./applyJurisdiction-DKQE8kOA.mjs";import{resolveSecurity as Pt,handleCorsPreflight as ao,enforceOrigin as io,decorateResponse as Ge,enforceWebSocketOrigin as kt}from"./decorateResponse-CdelJSUs.mjs";const co=e=>{const t=e??{};if(typeof t.bucket=="function")return t;const n=t.bucketName,s={...t,bucketName:typeof n=="string"&&n!==""?n:"default"};return s.bucket=()=>s,s},mn="__lunoraBranch",uo=e=>typeof e=="object"&&e!==null&&Object.hasOwn(e,mn),lo=`may not contain the reserved workflow branch-marker key ("${mn}")`,ho=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}},fo=/already[\s_-]?exists/iu,po=e=>fo.test(e instanceof Error?e.message:String(e)),mo="/_lunora/live/publish",wo="cf-ray",go="x-lunora-ray-id",yo=/^([\da-f]{16})(?:-[a-z]{3,4})?$/i,bo=e=>e==null?void 0:yo.exec(e.trim())?.[1]?.toLowerCase(),_o=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"];new Set(_o);const Ro=new Set(["AE","BH","IL","IQ","IR","JO","KW","LB","OM","PS","QA","SA","SY","TR","YE"]),Eo=-100,Ao=15,So=e=>{const t=Number(e.longitude??Number.NaN);switch(e.continent){case"AF":return"afr";case"AS":return e.country!==void 0&&Ro.has(e.country)?"me":"apac";case"EU":return Number.isFinite(t)&&t>Ao?"eeur":"weur";case"NA":return Number.isFinite(t)&&t<Eo?"wnam":"enam";case"OC":return"oc";case"SA":return"sam";default:return}},Dt=e=>{const t=e.cf;return t===void 0?void 0:So(t)},et="::relay::",To=(e,t)=>`${e}${et}${String(t)}`,tt="::replica::",vo=(e,t)=>`${e}${tt}${t}`,Oo=e=>{if(e==null||!/^\d+$/.test(e))return;const t=Number.parseInt(e,10);return Number.isSafeInteger(t)&&t>0?t:void 0},wn=(e,t)=>{const n=Math.max(e.length,t.length);let r=e.length^t.length;for(let s=0;s<n;s+=1){const i=s<e.length?e.charCodeAt(s):0,d=s<t.length?t.charCodeAt(s):0;r|=i^d}return r===0},Io=(e,t,n,r)=>{const s=e.get(t);if(s!==void 0)return s;an(e,r);const i=n().catch(d=>{throw e.get(t)===i&&e.delete(t),d});return e.set(t,i),i},it=new TextEncoder,Po=Array.from({length:32},(e,t)=>t);new RegExp(`[${Po.map(e=>String.fromCodePoint(e)).join("")}]`,"u");const ko=64,Do=new Map,gn=async e=>Io(Do,e,async()=>crypto.subtle.importKey("raw",it.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]),ko),yn=async(e,t)=>{const n=await gn(e),r=await crypto.subtle.sign("HMAC",n,it.encode(t));return Br(new Uint8Array(r))},No=async(e,t,n)=>{const r=await gn(e);return crypto.subtle.verify("HMAC",r,n,it.encode(t))},Uo="/_lunora/scheduler/dispatch",Co="__lunora_relation__:",Bo=e=>e.startsWith(Co),bn=(e,t)=>{if(!t||t.length===0)return!1;const n=e.headers.get("authorization");if(!n)return!1;const[r,...s]=n.split(" ");return r?.toLowerCase()!=="bearer"?!1:wn(t,s.join(" ").trim())},xo=async(e,t,n)=>{const r=e.headers.get("x-lunora-scheduler-signature"),{schedulerSecret:s}=n;return r!==null&&r.length>0&&s!==void 0&&s.length>0?wn(await yn(s,t),r):bn(e,n.adminToken)},Ho=({forwardedIdentity:e,mutationId:t,traceparent:n})=>{const r={"content-type":"application/json",[dn]:cn,"x-lunora-system":"1"};return e?.userId!==void 0&&e.userId.length>0&&(r["x-lunora-userid"]=e.userId),e?.identity!==void 0&&e.identity.length>0&&(r["x-lunora-identity"]=e.identity),t!==void 0&&t.length>0&&(r["x-lunora-mutation-id"]=t),n!==void 0&&n.length>0&&(r.traceparent=n),r},Lo=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}}},jo=(e,t,n)=>e?.[n]??t?.[n],Mo=(e,t,n,r)=>{const s=jo(e,t,n);if(!(typeof s!="object"||s===null))return r.every(i=>typeof s[i]=="function")?s:void 0},_n="v1",$o=6e4,Fo=async(e,t={})=>{const n=(t.now??Date.now())+(t.ttlMs??$o),r=`${_n}.${String(n)}`,s=await yn(e,r);return{expiresAtMs:n,token:`${r}.${s}`}},Ko=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[s,i,d]=r;if(s!==_n||d.length===0)return!1;const f=Number(i);if(!Number.isFinite(f)||f<=n)return!1;let h;try{h=xr(d)}catch{return!1}return No(e,`${s}.${i}`,h)},U="/_lunora/admin/auth",Go={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},B=(e,t)=>{const n=e[t];if(typeof n!="string"||n==="")throw new c(`\`${t}\` is required`,{code:"BAD_REQUEST",status:400});return n},me=(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},Rn=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,Qe=(e,t)=>{const n=e[t];return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:void 0},Nt=e=>{const t=Rn(e.role);if(t===void 0||typeof t=="string"&&t.trim()==="")throw new c("`role` is required",{code:"BAD_REQUEST",status:400});return t},Ut=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,s]of Object.entries(t))Array.isArray(s)&&s.every(i=>typeof i=="string")&&(n[r]=s);return n},Qo={[`${U}/capabilities`]:{build:()=>({}),http:"GET",method:"capabilities"},[`${U}/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"},[`${U}/sessions`]:{build:({paging:e,query:t})=>({...e,userId:t("userId")}),http:"GET",method:"listSessions"},[`${U}/accounts`]:{build:({query:e})=>({userId:me(e,"userId")}),http:"GET",method:"listAccounts"},[`${U}/passkeys`]:{build:({query:e})=>({userId:me(e,"userId")}),http:"GET",method:"listPasskeys"},[`${U}/organizations`]:{build:({paging:e})=>({...e}),http:"GET",method:"listOrganizations"},[`${U}/organizations/members`]:{build:({paging:e,query:t})=>({...e,organizationId:me(t,"organizationId")}),http:"GET",method:"listMembers"},[`${U}/organizations/invitations`]:{build:({paging:e,query:t})=>({...e,organizationId:me(t,"organizationId")}),http:"GET",method:"listInvitations"},[`${U}/sign-up-invitations`]:{build:({paging:e})=>({...e}),http:"GET",method:"listSignUpInvitations"},[`${U}/sign-up-invitations/create`]:{build:({body:e})=>({email:B(e,"email"),expiresInSeconds:typeof e.expiresInSeconds=="number"?e.expiresInSeconds:void 0,invitedBy:re(e,"invitedBy")}),http:"POST",method:"createSignUpInvitation"},[`${U}/sign-up-invitations/revoke`]:{build:({body:e})=>({email:B(e,"email")}),http:"POST",method:"revokeSignUpInvitation",returns:"void"},[`${U}/config`]:{build:()=>({}),http:"GET",method:"config"},[`${U}/organizations/teams`]:{build:({paging:e,query:t})=>({...e,organizationId:me(t,"organizationId")}),http:"GET",method:"listTeams"},[`${U}/organizations/teams/members`]:{build:({paging:e,query:t})=>({...e,teamId:me(t,"teamId")}),http:"GET",method:"listTeamMembers"},[`${U}/organizations/roles`]:{build:({paging:e,query:t})=>({...e,organizationId:me(t,"organizationId")}),http:"GET",method:"listOrgRoles"},[`${U}/users/create`]:{build:({body:e})=>({data:Qe(e,"data"),email:B(e,"email"),name:B(e,"name"),password:re(e,"password"),role:Rn(e.role)}),http:"POST",method:"createUser"},[`${U}/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:B(e,"userId")}},http:"POST",method:"updateUser"},[`${U}/users/role`]:{build:({body:e})=>({role:Nt(e),userId:B(e,"userId")}),http:"POST",method:"setRole"},[`${U}/users/ban`]:{build:({body:e})=>({expiresInSeconds:typeof e.expiresInSeconds=="number"?e.expiresInSeconds:void 0,reason:re(e,"reason"),userId:B(e,"userId")}),http:"POST",method:"banUser"},[`${U}/users/unban`]:{build:({body:e})=>({userId:B(e,"userId")}),http:"POST",method:"unbanUser"},[`${U}/users/password`]:{build:({body:e})=>({newPassword:B(e,"newPassword"),userId:B(e,"userId")}),http:"POST",method:"setUserPassword",returns:"void"},[`${U}/users/remove`]:{build:({body:e})=>({userId:B(e,"userId")}),http:"POST",method:"removeUser",returns:"void"},[`${U}/users/impersonate`]:{build:({body:e})=>({userId:B(e,"userId")}),http:"POST",method:"impersonateUser"},[`${U}/sessions/revoke`]:{build:({body:e})=>({sessionId:B(e,"sessionId")}),http:"POST",method:"revokeUserSession",returns:"void"},[`${U}/sessions/revoke-all`]:{build:({body:e})=>({userId:B(e,"userId")}),http:"POST",method:"revokeUserSessions",returns:"void"},[`${U}/accounts/unlink`]:{build:({body:e})=>({accountId:B(e,"accountId"),userId:B(e,"userId")}),http:"POST",method:"unlinkAccount",returns:"void"},[`${U}/two-factor/disable`]:{build:({body:e})=>({userId:B(e,"userId")}),http:"POST",method:"disableTwoFactor",returns:"void"},[`${U}/passkeys/delete`]:{build:({body:e})=>({passkeyId:B(e,"passkeyId")}),http:"POST",method:"deletePasskey",returns:"void"},[`${U}/organizations/members/remove`]:{build:({body:e})=>({memberId:B(e,"memberId")}),http:"POST",method:"removeMember",returns:"void"},[`${U}/organizations/invitations/cancel`]:{build:({body:e})=>({invitationId:B(e,"invitationId")}),http:"POST",method:"cancelInvitation",returns:"void"},[`${U}/organizations/create`]:{build:({body:e})=>({logo:re(e,"logo"),metadata:Qe(e,"metadata"),name:B(e,"name"),ownerId:re(e,"ownerId"),slug:re(e,"slug")}),http:"POST",method:"createOrganization"},[`${U}/organizations/update`]:{build:({body:e})=>({logo:re(e,"logo"),metadata:Qe(e,"metadata"),name:re(e,"name"),organizationId:B(e,"organizationId"),slug:re(e,"slug")}),http:"POST",method:"updateOrganization"},[`${U}/organizations/remove`]:{build:({body:e})=>({organizationId:B(e,"organizationId")}),http:"POST",method:"deleteOrganization",returns:"void"},[`${U}/organizations/members/add`]:{build:({body:e})=>({organizationId:B(e,"organizationId"),role:re(e,"role"),userId:B(e,"userId")}),http:"POST",method:"addMember"},[`${U}/organizations/members/invite`]:{build:({body:e})=>({email:B(e,"email"),inviterId:re(e,"inviterId"),organizationId:B(e,"organizationId"),role:re(e,"role")}),http:"POST",method:"inviteMember"},[`${U}/organizations/members/role`]:{build:({body:e})=>({memberId:B(e,"memberId"),role:Nt(e)}),http:"POST",method:"updateMemberRole"},[`${U}/organizations/teams/create`]:{build:({body:e})=>({name:B(e,"name"),organizationId:B(e,"organizationId")}),http:"POST",method:"createTeam"},[`${U}/organizations/teams/update`]:{build:({body:e})=>({name:B(e,"name"),teamId:B(e,"teamId")}),http:"POST",method:"updateTeam"},[`${U}/organizations/teams/remove`]:{build:({body:e})=>({teamId:B(e,"teamId")}),http:"POST",method:"removeTeam",returns:"void"},[`${U}/organizations/teams/members/add`]:{build:({body:e})=>({teamId:B(e,"teamId"),userId:B(e,"userId")}),http:"POST",method:"addTeamMember"},[`${U}/organizations/teams/members/remove`]:{build:({body:e})=>({teamMemberId:B(e,"teamMemberId")}),http:"POST",method:"removeTeamMember",returns:"void"},[`${U}/organizations/roles/create`]:{build:({body:e})=>({organizationId:B(e,"organizationId"),permission:Ut(e),role:B(e,"role")}),http:"POST",method:"createOrgRole"},[`${U}/organizations/roles/update`]:{build:({body:e})=>({permission:Ut(e),roleId:B(e,"roleId")}),http:"POST",method:"updateOrgRole"},[`${U}/organizations/roles/remove`]:{build:({body:e})=>({roleId:B(e,"roleId")}),http:"POST",method:"deleteOrgRole",returns:"void"}},Wo=e=>{const t=async s=>{try{return await s()}catch(i){if(i instanceof c)throw i;const d=i,f=typeof d.code=="string"?d.code:"AUTH_ADMIN_ERROR";throw console.error("[lunora] auth admin operation failed:",i),new c("auth admin operation failed",{code:f,status:Go[f]??500})}},n=async(s,i)=>{if(e.assertAdmin(s),s.method!==i.http)throw new c(`Auth admin endpoint requires ${i.http}`,{code:"METHOD_NOT_ALLOWED",status:405});const d=e.getAuthAdmin();if(d===void 0)throw new c("auth endpoints require an `authAdmin` on the worker",{code:"AUTH_NOT_CONFIGURED",status:400});const f=d[i.method];if(f===void 0)throw new c(`auth admin does not support \`${i.method}\``,{code:"AUTH_OP_NOT_SUPPORTED",status:400});const h=new URL(s.url),m={body:i.http==="POST"?await e.readJsonBody(s):{},paging:e.parsePaging(s),query:S=>e.queryParameter(h,S)},g=i.build(m),A=await t(()=>f(g));return Response.json(i.returns==="void"?{ok:!0}:A,{headers:{"cache-control":"no-store","content-type":"application/json"},status:200})},r={};for(const[s,i]of Object.entries(Qo))r[s]=d=>n(d,i);return r},Ct="__lunora_admin__:getAuthAuditLog",Bt=e=>typeof e=="string"&&e!==""?e:void 0,xt=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0,zo=e=>async(n,r)=>{e.assertAdmin(n);const s=e.getReader();if(s===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=Bt(r.actorId),d=Bt(r.event),f=xt(r.sinceSeq),h=xt(r.limit),m={...i===void 0?{}:{actorId:i},...d===void 0?{}:{event:d},...f===void 0?{}:{sinceSeq:f},...h===void 0?{}:{limit:h}};let g;try{g=await s.read(m)}catch(S){throw S instanceof c?S:(console.error("[lunora] auth audit read failed:",S),new c("auth audit read failed",{code:"AUTH_AUDIT_READ_FAILED",status:500}))}const A={entries:g};return Response.json({result:ye(A)},{headers:{"content-type":"application/json"},status:200})},nt="__lunora_admin__:copyAuthToJurisdiction",En="__lunora_admin__:purgeUnpinnedAuth",Vo=e=>async(t,n,r)=>{if(n!==nt&&n!==En)return;e.assertAdmin(t);const s=e.getMove();if(s===void 0)throw new c("moving auth into the jurisdiction needs DO-backed auth pinned with `.jurisdiction(…, { pinAuth: true })`",{code:"AUTH_MOVE_NOT_CONFIGURED",status:400});const i=n===nt?await s.copy({force:r.force===!0}):await s.purge();return Response.json({result:ye(i)},{headers:{"content-type":"application/json"},status:200})},Jo=(e,t)=>{const n=[],r=[];if(t&&t.length>0)for(const s of t)e.resolveTableSharding?.(s)?.mode.kind==="global"?r.push(s):n.push(s);return{globalTables:r,shardLocalTables:n}},Yo=async(e,t,n,r,s,i)=>{if(n!==void 0&&r.length===0)return[];const d=await e.orchestrateExport(s,{args:{tables:r},defaultShardKey:i,headers:t,tables:r}),f=d.shards.filter(h=>h.error);if(f.length>0){const h=f.map(m=>`${m.shardKey}: ${m.error?.message??"unknown error"}`).join("; ");throw new c(`export failed on ${String(f.length)} of ${String(d.shards.length)} shard(s) — ${h}`,{code:"EXPORT_SHARD_FAILED",status:502})}return d.shards.flatMap(h=>h.rows??[])},An=async(e,t,n,r,s)=>{const i=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:d,shardLocalTables:f}=Jo(e,i),h=await Yo(t,n,i,f,s,e.defaultShardKey??"__root__"),m=e.exportGlobals,g=r===void 0||d.length>0;return(async function*(){yield*h,g&&m&&(yield*m({tables:d}))})()},qo=async(e,t,n,r,s,i)=>{for await(const d of await An(e,t,n,r,i))s(d)},Xo=new TextEncoder,Zo=1e3,Sn=10,es=200,Ht=8,Tn="lunoraBackupCron",Lt=24*1048576,jt=e=>{const t=e.slice(0,Sn).map(r=>pn(r)),n=e.length-t.length;return`${t.join(", ")}${n>0?` (+${String(n)} more)`:""}`},ts=(e,t)=>{const n=new Uint8Array(new ArrayBuffer(t));let r=0;for(const s of e)n.set(s,r),r+=s.byteLength;return n},ct=async(e,t,n,r)=>{if(n===void 0||!Number.isInteger(n)||n<=0)return{eligible:0,stale:[]};const s=[];let i;for(let d=0;d<Zo;d+=1){const f=await e.list({cursor:i,include:["customMetadata"],prefix:t});for(const h of f.objects)$r(h.key)&&h.customMetadata?.[Tn]===r&&s.push(h.key);if(!f.truncated||f.cursor===void 0)break;i=f.cursor}return{eligible:s.length,stale:s.toSorted((d,f)=>f.localeCompare(d)).slice(n)}},ns=async(e,t,n,r,s)=>{const{stale:i}=await ct(e,t,n,r),d=new Set(s),f=i.filter(P=>d.has(P)),h=f.slice(0,es),m=i.length-h.length,g=s.length-f.length;if(h.length===0)return{deleted:[],failed:[],ignored:g,remaining:m};const A=[],S=[];for(let P=0;P<h.length;P+=Ht){const w=await Promise.allSettled(h.slice(P,P+Ht).map(async y=>(await e.delete(pn(y)),await e.delete(y),y)));for(const[y,b]of w.entries())b.status==="fulfilled"?A.push(b.value):S.push(h[P+y])}return A.length>0&&console.info(`[lunora] backup prune kept the newest ${String(n)} and deleted ${String(A.length)}: ${jt(A)}`),S.length>0&&console.warn(`[lunora] backup prune failed to remove ${String(S.length)}: ${jt(S)}`),{deleted:A,failed:S,ignored:g,remaining:m}},rs=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=st(e.backupPrefix??at),r=e.backupCron,{eligible:s,stale:i}=r===void 0?{eligible:0,stale:[]}:await ct(t,n,e.backupRetain,r);return{cron:r,eligible:s,keep:e.backupRetain??0,prefix:n,wouldDelete:i}},os=async(e,t,n,r,s)=>{const i=e.backupStore;if(!i)throw new c("scheduled backup requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});if(!r||r.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 d={authorization:`Bearer ${r}`,"content-type":"application/json"},f=e.backupTables;let h=0,m=0,g=[];await qo(e,t,d,f,I=>{const E=Xo.encode(`${JSON.stringify(I)}
|
|
2
|
-
`);if(h+=1,m+=E.byteLength,m>Lt)throw new c(`scheduled backup reached ${String(m)} bytes of NDJSON, past the ${String(Lt)}-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});g.push(E)},n);const S=st(e.backupPrefix??at),P=new Date(s.scheduledTime).toISOString(),w=
|
|
3
|
-
`,{customMetadata:{[Tn]:s.cron},httpMetadata:{contentType:"application/json"}});try{const{stale:I}=await ct(i,S,e.backupRetain,s.cron);if(I.length>0){const E=I.slice(0,Sn),L=I.length-E.length;console.info(`[lunora] backup retention: ${String(I.length)} snapshot(s) past the newest ${String(e.backupRetain)} — run \`lunora backup prune\` to remove them: ${E.join(", ")}${L>0?` (+${String(L)} more)`:""}`)}}catch(I){console.warn(`[lunora] backup ${w} was written, but the retention report failed:`,I)}},
|
|
4
|
-
`));G.close()}catch(J){G.error(J)}}});return new Response(V,{headers:{"content-type":"application/x-ndjson"},status:200})},w=async(E,L)=>{const j=ge(E,["POST"]);if(j)return j;f(E);const C=await ne(E),K=typeof C.cursors=="object"&&C.cursors!==null?C.cursors:{},q=typeof C.epochs=="object"&&C.epochs!==null?C.epochs:{},V=typeof C.limit=="number"?C.limit:void 0,G=typeof C.globalCursor=="number"?C.globalCursor:0,J=We(C.tables),{headers:se}=await h(E,L),W=J??i(),le=await d.orchestrateCdcSync(m,{cursors:K,defaultShardKey:n,epochs:q,headers:se,limit:V,tables:W}),ae=S?await S({limit:V,sinceSeq:G}):void 0;return Response.json({global:ae,shards:le.shards},{status:200})},y=async(E,L)=>{const j=ge(E,["POST"]);if(j)return j;f(E);const C=await ne(E),K=
|
|
1
|
+
import{isLunoraError as Rr,toErrorBody as Er}from"@lunora/errors";import{encodeWire as ye,decodeWire as Ze,encodeArgsOrThrow as Ar}from"@lunora/wire";import{d as Rt,E as Et,a as Sr,b as Tr,W as At}from"./error-detail-C46mdOTW.mjs";import{e as an}from"./evict-oldest-BNXsKx4s.mjs";import{NOOP_EXECUTION_CONTEXT as vr}from"./NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{i as Or,e as Ir,a as Pr,E as St,d as kr}from"./identity-header-pR617HTs.mjs";import{O as cn,a as dn}from"./origin-paywall-B6eOO67m.mjs";import{o as be,b as un,p as Dr,m as Nr,d as Ur,a as Cr,r as Br}from"./otlp-resource-Ch_8_U0e.mjs";import{r as xr,f as Tt,a as ue,S as vt}from"./observability-9slk__Gi.mjs";import{t as Hr,f as Lr}from"./base64-Bl1_r2k1.mjs";import{d as ne,e as oe,M as ln,b as jr,f as Mr,g as hn,w as $r,h as fn,t as Fr}from"./rest-routes-CDQ1F7kI.mjs";import{LunoraError as c,toErrorResponse as Ot}from"./LunoraError-PkZWF-_g.mjs";import{a as M,m as ge}from"./method-guard-8Jo4Q8uS.mjs";import{normalizeBackupPrefix as st,BACKUP_KEY_PREFIX as at,isBackupManifestKey as Kr,backupObjectKeyOfManifest as pn,backupObjectKey as Gr,backupManifestKey as Qr}from"./BACKUP_KEY_PREFIX-BOtSu-_3.mjs";import{toHex as Wr,buildStorageAdminRoutes as zr,STORAGE_UPLOAD_MAX_BODY_BYTES as Vr,STORAGE_PATH as Jr}from"./STORAGE_UPLOAD_MAX_BODY_BYTES-DiZho96u.mjs";import{b as Yr,e as qr,f as It,g as Xr,h as Zr}from"./export-tap-C2B_SATf.mjs";import{buildHealthRoutes as eo,durableObjectProbe as to,d1Probe as no,presenceProbe as Fe}from"./HEALTH_PATH-B8ndDG3s.mjs";import{wrapResolverWithContract as ro}from"./composeIdentityResolvers-CpdHuDyk.mjs";import{composeIdentityResolvers as Vi,routeIdentityResolvers as Ji}from"./composeIdentityResolvers-CpdHuDyk.mjs";import{buildLogArchiveAdminRoutes as oo}from"./LOG_ARCHIVE_PATH-dTuCzfyj.mjs";import{pruneShardRegistry as so,createQueryCoordinator as ao,createDefaultShardRegistry as io}from"./createQueryCoordinator-Bt6xVTQn.mjs";import{resolveShard as _e,applyJurisdiction as Ke}from"./applyJurisdiction-DKQE8kOA.mjs";import{resolveSecurity as Pt,handleCorsPreflight as co,enforceOrigin as uo,decorateResponse as Ge,enforceWebSocketOrigin as kt}from"./decorateResponse-CdelJSUs.mjs";const lo=e=>{const t=e??{};if(typeof t.bucket=="function")return t;const n=t.bucketName,s={...t,bucketName:typeof n=="string"&&n!==""?n:"default"};return s.bucket=()=>s,s},mn="__lunoraBranch",ho=e=>typeof e=="object"&&e!==null&&Object.hasOwn(e,mn),fo=`may not contain the reserved workflow branch-marker key ("${mn}")`,po=async e=>{const t=[];let n;for(;;){const o=await e(n);if(t.push(...Array.isArray(o.records)?o.records:[]),o.truncated!==!0||typeof o.cursor!="string"||o.cursor.length===0)return t;if(o.cursor===n)throw new Error("collectPages: the list did not advance its cursor — refusing to page forever");n=o.cursor}},mo=/already[\s_-]?exists/iu,wo=e=>mo.test(e instanceof Error?e.message:String(e)),go="/_lunora/live/publish",yo="cf-ray",bo="x-lunora-ray-id",_o=/^([\da-f]{16})(?:-[a-z]{3,4})?$/i,Ro=e=>e==null?void 0:_o.exec(e.trim())?.[1]?.toLowerCase(),Eo=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"];new Set(Eo);const Ao=new Set(["AE","BH","IL","IQ","IR","JO","KW","LB","OM","PS","QA","SA","SY","TR","YE"]),So=-100,To=15,vo=e=>{const t=Number(e.longitude??Number.NaN);switch(e.continent){case"AF":return"afr";case"AS":return e.country!==void 0&&Ao.has(e.country)?"me":"apac";case"EU":return Number.isFinite(t)&&t>To?"eeur":"weur";case"NA":return Number.isFinite(t)&&t<So?"wnam":"enam";case"OC":return"oc";case"SA":return"sam";default:return}},Dt=e=>{const t=e.cf;return t===void 0?void 0:vo(t)},et="::relay::",Oo=(e,t)=>`${e}${et}${String(t)}`,tt="::replica::",Io=(e,t)=>`${e}${tt}${t}`,Po=e=>{if(e==null||!/^\d+$/.test(e))return;const t=Number.parseInt(e,10);return Number.isSafeInteger(t)&&t>0?t:void 0},wn=(e,t)=>{const n=Math.max(e.length,t.length);let o=e.length^t.length;for(let s=0;s<n;s+=1){const i=s<e.length?e.charCodeAt(s):0,d=s<t.length?t.charCodeAt(s):0;o|=i^d}return o===0},ko=(e,t,n,o)=>{const s=e.get(t);if(s!==void 0)return s;an(e,o);const i=n().catch(d=>{throw e.get(t)===i&&e.delete(t),d});return e.set(t,i),i},it=new TextEncoder,Do=Array.from({length:32},(e,t)=>t);new RegExp(`[${Do.map(e=>String.fromCodePoint(e)).join("")}]`,"u");const No=64,Uo=new Map,gn=async e=>ko(Uo,e,async()=>crypto.subtle.importKey("raw",it.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]),No),yn=async(e,t)=>{const n=await gn(e),o=await crypto.subtle.sign("HMAC",n,it.encode(t));return Hr(new Uint8Array(o))},Co=async(e,t,n)=>{const o=await gn(e);return crypto.subtle.verify("HMAC",o,n,it.encode(t))},Bo="/_lunora/scheduler/dispatch",xo="__lunora_relation__:",Ho=e=>e.startsWith(xo),bn=(e,t)=>{if(!t||t.length===0)return!1;const n=e.headers.get("authorization");if(!n)return!1;const[o,...s]=n.split(" ");return o?.toLowerCase()!=="bearer"?!1:wn(t,s.join(" ").trim())},Lo=async(e,t,n)=>{const o=e.headers.get("x-lunora-scheduler-signature"),{schedulerSecret:s}=n;return o!==null&&o.length>0&&s!==void 0&&s.length>0?wn(await yn(s,t),o):bn(e,n.adminToken)},jo=({forwardedIdentity:e,mutationId:t,traceparent:n})=>{const o={"content-type":"application/json",[dn]:cn,"x-lunora-system":"1"};return e?.userId!==void 0&&e.userId.length>0&&(o["x-lunora-userid"]=e.userId),e?.identity!==void 0&&e.identity.length>0&&(o["x-lunora-identity"]=e.identity),t!==void 0&&t.length>0&&(o["x-lunora-mutation-id"]=t),n!==void 0&&n.length>0&&(o.traceparent=n),o},Mo=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}}},$o=(e,t,n)=>e?.[n]??t?.[n],Fo=(e,t,n,o)=>{const s=$o(e,t,n);if(!(typeof s!="object"||s===null))return o.every(i=>typeof s[i]=="function")?s:void 0},_n="v1",Ko=6e4,Go=async(e,t={})=>{const n=(t.now??Date.now())+(t.ttlMs??Ko),o=`${_n}.${String(n)}`,s=await yn(e,o);return{expiresAtMs:n,token:`${o}.${s}`}},Qo=async(e,t,n=Date.now())=>{if(e.length===0||t.length===0)return!1;const o=t.split(".");if(o.length!==3)return!1;const[s,i,d]=o;if(s!==_n||d.length===0)return!1;const f=Number(i);if(!Number.isFinite(f)||f<=n)return!1;let h;try{h=Lr(d)}catch{return!1}return Co(e,`${s}.${i}`,h)},U="/_lunora/admin/auth",Wo={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},B=(e,t)=>{const n=e[t];if(typeof n!="string"||n==="")throw new c(`\`${t}\` is required`,{code:"BAD_REQUEST",status:400});return n},me=(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},Rn=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,Qe=(e,t)=>{const n=e[t];return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:void 0},Nt=e=>{const t=Rn(e.role);if(t===void 0||typeof t=="string"&&t.trim()==="")throw new c("`role` is required",{code:"BAD_REQUEST",status:400});return t},Ut=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[o,s]of Object.entries(t))Array.isArray(s)&&s.every(i=>typeof i=="string")&&(n[o]=s);return n},zo={[`${U}/capabilities`]:{build:()=>({}),http:"GET",method:"capabilities"},[`${U}/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"},[`${U}/sessions`]:{build:({paging:e,query:t})=>({...e,userId:t("userId")}),http:"GET",method:"listSessions"},[`${U}/accounts`]:{build:({query:e})=>({userId:me(e,"userId")}),http:"GET",method:"listAccounts"},[`${U}/passkeys`]:{build:({query:e})=>({userId:me(e,"userId")}),http:"GET",method:"listPasskeys"},[`${U}/organizations`]:{build:({paging:e})=>({...e}),http:"GET",method:"listOrganizations"},[`${U}/organizations/members`]:{build:({paging:e,query:t})=>({...e,organizationId:me(t,"organizationId")}),http:"GET",method:"listMembers"},[`${U}/organizations/invitations`]:{build:({paging:e,query:t})=>({...e,organizationId:me(t,"organizationId")}),http:"GET",method:"listInvitations"},[`${U}/sign-up-invitations`]:{build:({paging:e})=>({...e}),http:"GET",method:"listSignUpInvitations"},[`${U}/sign-up-invitations/create`]:{build:({body:e})=>({email:B(e,"email"),expiresInSeconds:typeof e.expiresInSeconds=="number"?e.expiresInSeconds:void 0,invitedBy:re(e,"invitedBy")}),http:"POST",method:"createSignUpInvitation"},[`${U}/sign-up-invitations/revoke`]:{build:({body:e})=>({email:B(e,"email")}),http:"POST",method:"revokeSignUpInvitation",returns:"void"},[`${U}/config`]:{build:()=>({}),http:"GET",method:"config"},[`${U}/organizations/teams`]:{build:({paging:e,query:t})=>({...e,organizationId:me(t,"organizationId")}),http:"GET",method:"listTeams"},[`${U}/organizations/teams/members`]:{build:({paging:e,query:t})=>({...e,teamId:me(t,"teamId")}),http:"GET",method:"listTeamMembers"},[`${U}/organizations/roles`]:{build:({paging:e,query:t})=>({...e,organizationId:me(t,"organizationId")}),http:"GET",method:"listOrgRoles"},[`${U}/users/create`]:{build:({body:e})=>({data:Qe(e,"data"),email:B(e,"email"),name:B(e,"name"),password:re(e,"password"),role:Rn(e.role)}),http:"POST",method:"createUser"},[`${U}/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:B(e,"userId")}},http:"POST",method:"updateUser"},[`${U}/users/role`]:{build:({body:e})=>({role:Nt(e),userId:B(e,"userId")}),http:"POST",method:"setRole"},[`${U}/users/ban`]:{build:({body:e})=>({expiresInSeconds:typeof e.expiresInSeconds=="number"?e.expiresInSeconds:void 0,reason:re(e,"reason"),userId:B(e,"userId")}),http:"POST",method:"banUser"},[`${U}/users/unban`]:{build:({body:e})=>({userId:B(e,"userId")}),http:"POST",method:"unbanUser"},[`${U}/users/password`]:{build:({body:e})=>({newPassword:B(e,"newPassword"),userId:B(e,"userId")}),http:"POST",method:"setUserPassword",returns:"void"},[`${U}/users/remove`]:{build:({body:e})=>({userId:B(e,"userId")}),http:"POST",method:"removeUser",returns:"void"},[`${U}/users/impersonate`]:{build:({body:e})=>({userId:B(e,"userId")}),http:"POST",method:"impersonateUser"},[`${U}/sessions/revoke`]:{build:({body:e})=>({sessionId:B(e,"sessionId")}),http:"POST",method:"revokeUserSession",returns:"void"},[`${U}/sessions/revoke-all`]:{build:({body:e})=>({userId:B(e,"userId")}),http:"POST",method:"revokeUserSessions",returns:"void"},[`${U}/accounts/unlink`]:{build:({body:e})=>({accountId:B(e,"accountId"),userId:B(e,"userId")}),http:"POST",method:"unlinkAccount",returns:"void"},[`${U}/two-factor/disable`]:{build:({body:e})=>({userId:B(e,"userId")}),http:"POST",method:"disableTwoFactor",returns:"void"},[`${U}/passkeys/delete`]:{build:({body:e})=>({passkeyId:B(e,"passkeyId")}),http:"POST",method:"deletePasskey",returns:"void"},[`${U}/organizations/members/remove`]:{build:({body:e})=>({memberId:B(e,"memberId")}),http:"POST",method:"removeMember",returns:"void"},[`${U}/organizations/invitations/cancel`]:{build:({body:e})=>({invitationId:B(e,"invitationId")}),http:"POST",method:"cancelInvitation",returns:"void"},[`${U}/organizations/create`]:{build:({body:e})=>({logo:re(e,"logo"),metadata:Qe(e,"metadata"),name:B(e,"name"),ownerId:re(e,"ownerId"),slug:re(e,"slug")}),http:"POST",method:"createOrganization"},[`${U}/organizations/update`]:{build:({body:e})=>({logo:re(e,"logo"),metadata:Qe(e,"metadata"),name:re(e,"name"),organizationId:B(e,"organizationId"),slug:re(e,"slug")}),http:"POST",method:"updateOrganization"},[`${U}/organizations/remove`]:{build:({body:e})=>({organizationId:B(e,"organizationId")}),http:"POST",method:"deleteOrganization",returns:"void"},[`${U}/organizations/members/add`]:{build:({body:e})=>({organizationId:B(e,"organizationId"),role:re(e,"role"),userId:B(e,"userId")}),http:"POST",method:"addMember"},[`${U}/organizations/members/invite`]:{build:({body:e})=>({email:B(e,"email"),inviterId:re(e,"inviterId"),organizationId:B(e,"organizationId"),role:re(e,"role")}),http:"POST",method:"inviteMember"},[`${U}/organizations/members/role`]:{build:({body:e})=>({memberId:B(e,"memberId"),role:Nt(e)}),http:"POST",method:"updateMemberRole"},[`${U}/organizations/teams/create`]:{build:({body:e})=>({name:B(e,"name"),organizationId:B(e,"organizationId")}),http:"POST",method:"createTeam"},[`${U}/organizations/teams/update`]:{build:({body:e})=>({name:B(e,"name"),teamId:B(e,"teamId")}),http:"POST",method:"updateTeam"},[`${U}/organizations/teams/remove`]:{build:({body:e})=>({teamId:B(e,"teamId")}),http:"POST",method:"removeTeam",returns:"void"},[`${U}/organizations/teams/members/add`]:{build:({body:e})=>({teamId:B(e,"teamId"),userId:B(e,"userId")}),http:"POST",method:"addTeamMember"},[`${U}/organizations/teams/members/remove`]:{build:({body:e})=>({teamMemberId:B(e,"teamMemberId")}),http:"POST",method:"removeTeamMember",returns:"void"},[`${U}/organizations/roles/create`]:{build:({body:e})=>({organizationId:B(e,"organizationId"),permission:Ut(e),role:B(e,"role")}),http:"POST",method:"createOrgRole"},[`${U}/organizations/roles/update`]:{build:({body:e})=>({permission:Ut(e),roleId:B(e,"roleId")}),http:"POST",method:"updateOrgRole"},[`${U}/organizations/roles/remove`]:{build:({body:e})=>({roleId:B(e,"roleId")}),http:"POST",method:"deleteOrgRole",returns:"void"}},Vo=e=>{const t=async s=>{try{return await s()}catch(i){if(i instanceof c)throw i;const d=i,f=typeof d.code=="string"?d.code:"AUTH_ADMIN_ERROR";throw console.error("[lunora] auth admin operation failed:",i),new c("auth admin operation failed",{code:f,status:Wo[f]??500})}},n=async(s,i)=>{if(e.assertAdmin(s),s.method!==i.http)throw new c(`Auth admin endpoint requires ${i.http}`,{code:"METHOD_NOT_ALLOWED",status:405});const d=e.getAuthAdmin();if(d===void 0)throw new c("auth endpoints require an `authAdmin` on the worker",{code:"AUTH_NOT_CONFIGURED",status:400});const f=d[i.method];if(f===void 0)throw new c(`auth admin does not support \`${i.method}\``,{code:"AUTH_OP_NOT_SUPPORTED",status:400});const h=new URL(s.url),m={body:i.http==="POST"?await e.readJsonBody(s):{},paging:e.parsePaging(s),query:S=>e.queryParameter(h,S)},g=i.build(m),A=await t(()=>f(g));return Response.json(i.returns==="void"?{ok:!0}:A,{headers:{"cache-control":"no-store","content-type":"application/json"},status:200})},o={};for(const[s,i]of Object.entries(zo))o[s]=d=>n(d,i);return o},Ct="__lunora_admin__:getAuthAuditLog",Bt=e=>typeof e=="string"&&e!==""?e:void 0,xt=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0,Jo=e=>async(n,o)=>{e.assertAdmin(n);const s=e.getReader();if(s===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=Bt(o.actorId),d=Bt(o.event),f=xt(o.sinceSeq),h=xt(o.limit),m={...i===void 0?{}:{actorId:i},...d===void 0?{}:{event:d},...f===void 0?{}:{sinceSeq:f},...h===void 0?{}:{limit:h}};let g;try{g=await s.read(m)}catch(S){throw S instanceof c?S:(console.error("[lunora] auth audit read failed:",S),new c("auth audit read failed",{code:"AUTH_AUDIT_READ_FAILED",status:500}))}const A={entries:g};return Response.json({result:ye(A)},{headers:{"content-type":"application/json"},status:200})},nt="__lunora_admin__:copyAuthToJurisdiction",En="__lunora_admin__:purgeUnpinnedAuth",Yo=e=>async(t,n,o)=>{if(n!==nt&&n!==En)return;e.assertAdmin(t);const s=e.getMove();if(s===void 0)throw new c("moving auth into the jurisdiction needs DO-backed auth pinned with `.jurisdiction(…, { pinAuth: true })`",{code:"AUTH_MOVE_NOT_CONFIGURED",status:400});const i=n===nt?await s.copy({force:o.force===!0}):await s.purge();return Response.json({result:ye(i)},{headers:{"content-type":"application/json"},status:200})},qo=(e,t)=>{const n=[],o=[];if(t&&t.length>0)for(const s of t)e.resolveTableSharding?.(s)?.mode.kind==="global"?o.push(s):n.push(s);return{globalTables:o,shardLocalTables:n}},Xo=async(e,t,n,o,s,i)=>{if(n!==void 0&&o.length===0)return[];const d=await e.orchestrateExport(s,{args:{tables:o},defaultShardKey:i,headers:t,tables:o}),f=d.shards.filter(h=>h.error);if(f.length>0){const h=f.map(m=>`${m.shardKey}: ${m.error?.message??"unknown error"}`).join("; ");throw new c(`export failed on ${String(f.length)} of ${String(d.shards.length)} shard(s) — ${h}`,{code:"EXPORT_SHARD_FAILED",status:502})}return d.shards.flatMap(h=>h.rows??[])},An=async(e,t,n,o,s)=>{const i=o??e.listSchemaTables?.();o===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:d,shardLocalTables:f}=qo(e,i),h=await Xo(t,n,i,f,s,e.defaultShardKey??"__root__"),m=e.exportGlobals,g=o===void 0||d.length>0;return(async function*(){yield*h,g&&m&&(yield*m({tables:d}))})()},Zo=async(e,t,n,o,s,i)=>{for await(const d of await An(e,t,n,o,i))s(d)},es=new TextEncoder,ts=1e3,Sn=10,ns=200,Ht=8,Tn="lunoraBackupCron",Lt=24*1048576,jt=e=>{const t=e.slice(0,Sn).map(o=>pn(o)),n=e.length-t.length;return`${t.join(", ")}${n>0?` (+${String(n)} more)`:""}`},rs=(e,t)=>{const n=new Uint8Array(new ArrayBuffer(t));let o=0;for(const s of e)n.set(s,o),o+=s.byteLength;return n},ct=async(e,t,n,o)=>{if(n===void 0||!Number.isInteger(n)||n<=0)return{eligible:0,stale:[]};const s=[];let i;for(let d=0;d<ts;d+=1){const f=await e.list({cursor:i,include:["customMetadata"],prefix:t});for(const h of f.objects)Kr(h.key)&&h.customMetadata?.[Tn]===o&&s.push(h.key);if(!f.truncated||f.cursor===void 0)break;i=f.cursor}return{eligible:s.length,stale:s.toSorted((d,f)=>f.localeCompare(d)).slice(n)}},os=async(e,t,n,o,s)=>{const{stale:i}=await ct(e,t,n,o),d=new Set(s),f=i.filter(P=>d.has(P)),h=f.slice(0,ns),m=i.length-h.length,g=s.length-f.length;if(h.length===0)return{deleted:[],failed:[],ignored:g,remaining:m};const A=[],S=[];for(let P=0;P<h.length;P+=Ht){const w=await Promise.allSettled(h.slice(P,P+Ht).map(async y=>(await e.delete(pn(y)),await e.delete(y),y)));for(const[y,b]of w.entries())b.status==="fulfilled"?A.push(b.value):S.push(h[P+y])}return A.length>0&&console.info(`[lunora] backup prune kept the newest ${String(n)} and deleted ${String(A.length)}: ${jt(A)}`),S.length>0&&console.warn(`[lunora] backup prune failed to remove ${String(S.length)}: ${jt(S)}`),{deleted:A,failed:S,ignored:g,remaining:m}},ss=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=st(e.backupPrefix??at),o=e.backupCron,{eligible:s,stale:i}=o===void 0?{eligible:0,stale:[]}:await ct(t,n,e.backupRetain,o);return{cron:o,eligible:s,keep:e.backupRetain??0,prefix:n,wouldDelete:i}},as=async(e,t,n,o,s)=>{const i=e.backupStore;if(!i)throw new c("scheduled backup requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});if(!o||o.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 d={authorization:`Bearer ${o}`,"content-type":"application/json"},f=e.backupTables;let h=0,m=0,g=[];await Zo(e,t,d,f,I=>{const E=es.encode(`${JSON.stringify(I)}
|
|
2
|
+
`);if(h+=1,m+=E.byteLength,m>Lt)throw new c(`scheduled backup reached ${String(m)} bytes of NDJSON, past the ${String(Lt)}-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});g.push(E)},n);const S=st(e.backupPrefix??at),P=new Date(s.scheduledTime).toISOString(),w=Gr(S,P),y=rs(g,m);g=[];const b=Wr(await crypto.subtle.digest("SHA-256",y));await i.put(w,y,{httpMetadata:{contentType:"application/x-ndjson"},sha256:b});const T={bytes:m,createdAt:P,cron:s.cron,file:w,id:P,rows:h,scheduledTime:s.scheduledTime,sha256:b,...f?{tables:f.join(",")}:{}};await i.put(Qr(w),`${JSON.stringify(T,void 0,2)}
|
|
3
|
+
`,{customMetadata:{[Tn]:s.cron},httpMetadata:{contentType:"application/json"}});try{const{stale:I}=await ct(i,S,e.backupRetain,s.cron);if(I.length>0){const E=I.slice(0,Sn),L=I.length-E.length;console.info(`[lunora] backup retention: ${String(I.length)} snapshot(s) past the newest ${String(e.backupRetain)} — run \`lunora backup prune\` to remove them: ${E.join(", ")}${L>0?` (+${String(L)} more)`:""}`)}}catch(I){console.warn(`[lunora] backup ${w} was written, but the retention report failed:`,I)}},is=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 o=e.backupCron,s=e.backupRetain;if(o===void 0||s===void 0||!Number.isInteger(s)||s<=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 os(n,st(e.backupPrefix??at),s,o,t)},cs="/_lunora/admin/backup/retention",ds="/_lunora/admin/backup/prune",us=e=>{const{options:t,readJsonBody:n,requireAdminOption:o}=e,s=(f,h)=>{o(f,t.backupStore,{code:"BACKUP_NOT_CONFIGURED",message:`backup ${h} requires a \`backupStore\` on the worker`})},i=async f=>(M(f,"GET","Backup-retention"),s(f,"retention preview"),Response.json(await ss(t),{headers:{"cache-control":"no-store"}})),d=async f=>{M(f,"POST","Backup-prune"),s(f,"prune");const{confirm:h}=await n(f);if(!Array.isArray(h)||h.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 is(t,h),{headers:{"cache-control":"no-store"}})};return{[ds]:d,[cs]:i}},Mt=500,ls=(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 o=e;if(typeof o.functionPath!="string")throw new c("each batch call needs a string `functionPath`",{code:"BAD_REQUEST",status:400});if(o.functionPath.startsWith("__lunora_relation__:")||o.functionPath.startsWith("__lunora_admin__"))throw new c("reserved function path cannot be batched",{code:"FORBIDDEN",status:403});if(o.args!==void 0&&(typeof o.args!="object"||o.args===null||Array.isArray(o.args)))throw new c("each batch call `args` must be an object",{code:"BAD_REQUEST",status:400});if(o.id!==void 0&&typeof o.id!="number")throw new c("each batch call `id` must be a number",{code:"BAD_REQUEST",status:400});return{entry:{args:o.args===void 0?{}:o.args,baselineSeq:typeof o.baselineSeq=="number"?o.baselineSeq:void 0,clientId:typeof o.clientId=="string"?o.clientId:void 0,clientSeq:typeof o.clientSeq=="number"?o.clientSeq:void 0,functionPath:o.functionPath,id:typeof o.id=="number"?o.id:t,mutationId:typeof o.mutationId=="string"?o.mutationId:void 0},shardKey:typeof o.shardKey=="string"?o.shardKey:n}},hs=(e,t)=>{if(e.length>Mt)throw new c(`RPC batch exceeds the ${String(Mt)}-call limit`,{code:"BAD_REQUEST",status:400});const n=new Map,o=new Set;for(const[s,i]of e.entries()){const{entry:d,shardKey:f}=ls(i,s,t);if(o.has(d.id))throw new c(`batch call id ${String(d.id)} is used twice; ids must be distinct`,{code:"BAD_REQUEST",status:400});o.add(d.id);const h=n.get(f)??[];h.push(d),n.set(f,h)}return n},fs="/_lunora/admin/export",ps="/_lunora/admin/import",ms="/_lunora/admin/sync",ws="/_lunora/admin/connector/sync",gs="/_lunora/admin/apply",ys="/_lunora/admin/export-tap/run",bs=new TextEncoder,_s=async e=>{const n=await oe(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 o=[];for(const s of n.tables){if(typeof s!="string"||s.length===0)throw new c("Export `tables` entries must be non-empty strings",{code:"BAD_REQUEST",status:400});o.push(s)}return{tables:o}},We=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):void 0,Rs=e=>{const{applyGlobals:t,defaultShardKey:n,exportCursorStore:o,exportSinks:s,knownTables:i,queryCoordinator:d,assertAdmin:f,resolveForwardContext:h,shardDO:m,prepareExportRows:g,streamingImport:A,syncGlobals:S}=e,P=async(E,L)=>{const j=ge(E,["POST"]);if(j)return j;f(E);const C=await _s(E),{headers:K}=await h(E,L),q=await g(K,C.tables),V=new ReadableStream({async pull(G){try{for await(const J of q)G.enqueue(bs.encode(`${JSON.stringify(J)}
|
|
4
|
+
`));G.close()}catch(J){G.error(J)}}});return new Response(V,{headers:{"content-type":"application/x-ndjson"},status:200})},w=async(E,L)=>{const j=ge(E,["POST"]);if(j)return j;f(E);const C=await ne(E),K=typeof C.cursors=="object"&&C.cursors!==null?C.cursors:{},q=typeof C.epochs=="object"&&C.epochs!==null?C.epochs:{},V=typeof C.limit=="number"?C.limit:void 0,G=typeof C.globalCursor=="number"?C.globalCursor:0,J=We(C.tables),{headers:se}=await h(E,L),W=J??i(),le=await d.orchestrateCdcSync(m,{cursors:K,defaultShardKey:n,epochs:q,headers:se,limit:V,tables:W}),ae=S?await S({limit:V,sinceSeq:G}):void 0;return Response.json({global:ae,shards:le.shards},{status:200})},y=async(E,L)=>{const j=ge(E,["POST"]);if(j)return j;f(E);const C=await ne(E),K=qr(C.cursor),q=typeof C.limit=="number"&&C.limit>0?C.limit:void 0,V=We(C.tables),{headers:G}=await h(E,L),J=V??i(),se=await d.orchestrateCdcSync(m,{cursors:K.s,defaultShardKey:n,headers:G,limit:q,tables:J}),W=[],le={...K.s};let ae=!1;for(const ce of se.shards)ae=It(W,ce.changes??[],Zr(q))||ae,le[ce.shardKey]=ce.cursor;let z=K.g;if(S){const ce=await S({limit:q,sinceSeq:K.g});ae=It(W,ce.changes,q)||ae,z=ce.cursor}const ie=Xr({g:z,s:le,v:1}),He={changes:W,hasMore:ae,nextCursor:ie};return Response.json(He,{status:200})},b=async(E,L)=>{const j=ge(E,["POST"]);if(j)return j;f(E);const C=await ne(E),q=(Array.isArray(C.batches)?C.batches:[]).map(W=>W).filter(W=>W!==null&&typeof W=="object"&&typeof W.shardKey=="string"&&Array.isArray(W.changes)),V=Array.isArray(C.globalChanges)?C.globalChanges:[],{headers:G}=await h(E,L),J=await d.orchestrateApplyCdc(m,{batches:q,headers:G}),se=V.length>0&&t?await t({changes:V}):0;return Response.json({applied:J.applied+se,failed:J.failed,ok:J.ok},{status:200})},T=async(E,L)=>{const j=ge(E,["POST"]);if(j)return j;f(E);const{headers:C}=await h(E,L),K=await A(E,C);return Response.json(K,{headers:{"content-type":"application/json"},status:K.failed.length>0?207:200})},I=async(E,L)=>{const j=ge(E,["POST"]);if(j)return j;if(f(E),s===void 0||Object.keys(s).length===0||o===void 0)throw new c("Export-tap endpoint requires `exportSinks` + `exportCursorStore` on the worker",{code:"EXPORT_TAP_NOT_CONFIGURED",status:400});const C=await ne(E),K=typeof C.sink=="string"?C.sink:void 0,q=typeof C.limit=="number"&&C.limit>0?C.limit:void 0,V=We(C.tables);if(K===void 0)throw new c("Export-tap `sink` must name a configured sink",{code:"BAD_REQUEST",status:400});const G=s[K];if(G===void 0)throw new c(`Export-tap sink "${K}" is not configured`,{code:"NOT_FOUND",status:404});const{headers:J}=await h(E,L),se=V??i(),W=await Yr({coordinator:d,cursorStore:o,defaultShardKey:n,headers:J,limit:q,shardDO:m,sink:G,tables:se});return Response.json(W,{headers:{"content-type":"application/json"},status:200})};return{[gs]:b,[ws]:y,[fs]:P,[ys]:I,[ps]:T,[ms]:w}},Es=(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 o=n;return typeof o.table!="string"||o.table.length===0?{error:{code:"BAD_ROW",line:t,message:"row is missing `table`",table:""},ok:!1}:!o.doc||typeof o.doc!="object"||Array.isArray(o.doc)?{error:{code:"BAD_ROW",line:t,message:"row is missing or malformed `doc`",table:o.table},ok:!1}:{doc:o.doc,ok:!0,table:o.table}},As=(e,t,n,o,s)=>{if(n?.mode.kind==="shardBy"&&typeof n.mode.field=="string"){const i=e[n.mode.field];return i==null?{error:{code:"BAD_ROW",line:s,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:o}},Ss=async(e,t,n)=>{if(!e.body)throw new c("Import endpoint requires a request body",{code:"BAD_REQUEST",status:400});const o=[],s=[],i=new Map;let d=0,f=0;const h=e.body.getReader(),m=new TextDecoder;let g="",A=0;const S=P=>{f+=1;const w=P.trim();if(w.length===0)return;d+=1;const y=Es(w,f);if(!y.ok){o.push(y.error);return}const{doc:b,table:T}=y,I=t.resolveTableSharding?.(T);if(I?.mode.kind==="global"){s.push({doc:b,line:f,table:T});return}const E=As(b,T,I,n,f);if(!E.ok){o.push(E.error);return}const L=i.get(E.shardKey);L?L.rows.push({doc:b,table:T}):i.set(E.shardKey,{rows:[{doc:b,table:T}],shardKey:E.shardKey,startLine:f})};for(;;){const{done:P,value:w}=await h.read();if(P)break;if(w&&(A+=w.byteLength,A>ln))throw await h.cancel().catch(()=>{}),new c("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});g+=m.decode(w,{stream:!0});let y=g.indexOf(`
|
|
5
5
|
`);for(;y!==-1;){const b=g.slice(0,y);g=g.slice(y+1),S(b),y=g.indexOf(`
|
|
6
|
-
`)}}return g.length>0&&S(g),{errors:r,globalRows:s,perShard:i,received:d}},As=e=>e.flatMap(t=>t.error?[{message:t.error.message,shardKey:t.shardKey,timedOut:t.error.timedOut}]:[]),$t=(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},Ss=async(e,t,n,r,s)=>{const i=t.defaultShardKey??"__root__",{errors:d,globalRows:f,perShard:h,received:m}=await Es(e,t,i),g={conflicts:0,errors:d,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=await n.orchestrateImport(s,{batches:[...h.values()],headers:r});$t(g,S),g.failed.push(...As(S.shards))}if(f.length>0)if(t.importGlobals){const S=f[0]?.line??1,P=await t.importGlobals({rows:f,startLine:S});$t(g,P)}else for(const S of f)g.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:g.conflicts,errors:g.errors,failed:g.failed,inserted:g.inserted,received:m,...A.length>0?{warnings:A}:{}}},Ts=Object.freeze({edges:[],nodes:[],modules:[],unresolved:[],version:1}),Be=e=>typeof e=="object"&&e!==null?e:{},vn=e=>{const t=Be(e)._meta??{};if(t.sensitive===!0)return!0;const n=Array.isArray(t.members)?t.members:[],r=typeof t.shape=="object"&&t.shape!==null?Object.values(t.shape):[];return[t.inner,t.keyValidator,t.valueValidator,...n,...r].some(s=>typeof s=="object"&&s!==null&&vn(s))},ze=e=>typeof e.kind=="string"?e.kind:"unknown",vs=(e,t)=>{let n=Be(t),r=!1;ze(n)==="optional"&&(r=!0,n=Be(n._meta?.inner));const s=ze(n),i=n._meta??{},d={kind:s,name:e,optional:r};if(vn(t)&&(d.sensitive=!0),s==="id"&&typeof i.tableName=="string"&&(d.table=i.tableName),s==="array"){const f=ze(Be(i.inner));f!=="unknown"&&(d.element=f)}return d},Os=e=>typeof e!="object"||e===null?[]:Object.entries(e).map(([t,n])=>vs(t,n)).toSorted((t,n)=>t.name.localeCompare(n.name)),Is="/_lunora/admin/functions",Ps="/_lunora/admin/cron-jobs",ks="/_lunora/admin/architecture",Ds="/_lunora/admin/openapi",Ns="/_lunora/admin/openrpc",Us="/_lunora/admin/global/tables",Cs="/_lunora/admin/global/table",Bs="/_lunora/admin/global/facet",Ft=e=>{if(e===void 0||e==="")return;let t;try{t=Ze(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:s,value:i}=r;return[{column:s,value:i}]});return n.length===0?void 0:n},xs=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:{}}),Hs=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"}),Ls=e=>{const{assertAdmin:t,options:n,parsePaging:r,queryParameter:s,requireAdminOption:i}=e,d=w=>{M(w,"GET","Functions");const y=i(w,n.functions,{code:"FUNCTIONS_NOT_CONFIGURED",message:"functions endpoint requires a `functions` registry on the worker"}),b=Object.entries(y).flatMap(([T,I])=>I.visibility==="internal"||I.kind==="stream"?[]:[{args:[...I.argumentDescriptors??Os(I.args)],kind:I.kind,path:T}]).toSorted((T,I)=>T.path.localeCompare(I.path));return Response.json({functions:b},{headers:{"content-type":"application/json"},status:200})},f=w=>{M(w,"GET","Cron-jobs");const y=i(w,n.cronJobs,{code:"CRON_JOBS_NOT_CONFIGURED",message:"cron-jobs endpoint requires a `cronJobs` map on the worker"}),b=Object.entries(y).flatMap(([T,I])=>I.map(E=>({args:E.args,cron:T,functionPath:E.functionPath,name:E.name,shardKey:E.shardKey,workflow:E.workflow}))).toSorted((T,I)=>T.name.localeCompare(I.name));return Response.json({jobs:b},{headers:{"content-type":"application/json"},status:200})},h=w=>(M(w,"GET","Architecture"),t(w),Response.json(n.architecture??Ts,{headers:{"content-type":"application/json"},status:200})),m=w=>(M(w,"GET","OpenAPI"),t(w),Response.json(n.openApiSpec??xs,{headers:{"content-type":"application/json"},status:200})),g=w=>(M(w,"GET","OpenRPC"),t(w),Response.json(n.openRpcSpec??Hs,{headers:{"content-type":"application/json"},status:200})),A=async w=>{M(w,"GET","Global-tables");const y=i(w,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 w=>{M(w,"GET","Global-table");const y=i(w,n.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),b=new URL(w.url),T=s(b,"table");if(T===void 0)throw new c("Global-table endpoint requires a `table` query param",{code:"BAD_REQUEST",status:400});const I=await y.readTablePage({...r(w),filters:Ft(s(b,"filters")),table:T});return Response.json(I,{headers:{"content-type":"application/json"},status:200})},P=async w=>{M(w,"GET","Global-facet");const y=i(w,n.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),b=new URL(w.url),T=s(b,"table"),I=s(b,"column");if(T===void 0||I===void 0)throw new c("Global-facet endpoint requires `table` and `column` query params",{code:"BAD_REQUEST",status:400});const E=s(b,"limit"),L=E===void 0?void 0:Number(E),j=await y.facetColumn({column:I,filters:Ft(s(b,"filters")),limit:L!==void 0&&Number.isFinite(L)?L:void 0,table:T});return Response.json(j,{headers:{"content-type":"application/json"},status:200})};return{[Ps]:f,[Is]:d,[Bs]:P,[Cs]:S,[Us]:A,[ks]:h,[Ds]:m,[Ns]:g}},js="/_lunora/admin/kv/namespaces",Ms="/_lunora/admin/kv/keys",On="/_lunora/admin/kv/value",In=32*1048576,Kt=60,$s=e=>{const{readJsonBody:t,requireAdminOption:n}=e,r=w=>n(w,e.kvIntrospector,{code:"KV_NOT_CONFIGURED",message:"KV endpoints require a `kvIntrospector` on the worker"}),s=w=>Response.json(w,{headers:{"content-type":"application/json"},status:200}),i=(w,y)=>{const b=new URL(w.url),T=b.searchParams.get("namespace")??"",I=b.searchParams.get("key")??"";if(T==="")throw new c(`KV-value ${y} request requires a \`namespace\` query parameter`,{code:"BAD_REQUEST",status:400});if(I==="")throw new c(`KV-value ${y} request requires a \`key\` query parameter`,{code:"BAD_REQUEST",status:400});return{key:I,namespace:T}},d=async(w,y)=>{if(!(await w.listNamespaces()).some(T=>T.binding===y))throw new c(`Unknown KV namespace binding \`${y}\``,{code:"NOT_FOUND",status:404})},f=async w=>(M(w,"GET","KV-namespaces"),s({namespaces:await r(w).listNamespaces()})),h=async w=>{M(w,"GET","KV-keys");const y=r(w),b=new URL(w.url),T=b.searchParams.get("namespace")??"";if(T==="")throw new c("KV-keys request requires a `namespace` query parameter",{code:"BAD_REQUEST",status:400});const I=b.searchParams.get("prefix")??void 0,E=b.searchParams.get("cursor")??void 0,L=b.searchParams.get("limit"),j=L===null?void 0:Number.parseInt(L,10);if(j!==void 0&&(!Number.isInteger(j)||j<1))throw new c("KV-keys `limit` must be a positive integer",{code:"BAD_REQUEST",status:400});const C=j===void 0?void 0:Math.min(j,1e3);return await d(y,T),s(await y.listKeys({cursor:E,limit:C,namespace:T,prefix:I}))},S={DELETE:async w=>{const y=r(w),b=i(w,"DELETE");return await d(y,b.namespace),await y.deleteKey(b),s({deleted:!0})},GET:async w=>{const y=r(w),b=i(w,"GET");return await d(y,b.namespace),s(await y.getValue(b))},PUT:async w=>{const y=r(w),b=await t(w,In);if(typeof b.namespace!="string"||b.namespace==="")throw new c("KV-value PUT request requires a `namespace` string",{code:"BAD_REQUEST",status:400});if(typeof b.key!="string"||b.key==="")throw new c("KV-value PUT request requires a `key` string",{code:"BAD_REQUEST",status:400});if(typeof b.value!="string")throw new c("KV-value PUT request requires a `value` string",{code:"BAD_REQUEST",status:400});if(b.expirationTtl!==void 0&&(typeof b.expirationTtl!="number"||!Number.isInteger(b.expirationTtl)||b.expirationTtl<Kt))throw new c("KV-value PUT `expirationTtl` must be an integer ≥ 60",{code:"BAD_REQUEST",status:400});const T=Math.floor(Date.now()/1e3)+Kt;if(b.expiration!==void 0&&(typeof b.expiration!="number"||!Number.isInteger(b.expiration)||b.expiration<T))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 d(y,b.namespace),await y.putValue({expiration:b.expiration,expirationTtl:b.expirationTtl,key:b.key,metadata:b.metadata,namespace:b.namespace,value:b.value}),s({ok:!0})}},P=w=>{const y=S[w.method];if(!y)throw new c("KV-value endpoint requires GET, PUT, or DELETE",{code:"METHOD_NOT_ALLOWED",status:405});return y(w)};return{[js]:f,[Ms]:h,[On]:P}},Fs="/_lunora/migrate",Ks="/_lunora/admin/pitr",Gs="/_lunora/admin/rank",Qs="/_lunora/admin/rankpage",Ws="/_lunora/admin/shard-registry/prune",zs="/_lunora/admin/shard-traffic",Vs=new Set(["__lunora_admin__:migrationStatus","__lunora_admin__:runMigration"]),Js=new Set(["__lunora_admin__:getPitrBookmark","__lunora_admin__:pitrRestore"]),Ys=async e=>{const n=await oe(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"||!Vs.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}},qs=async e=>{const n=await oe(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}},Xs=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}},Zs=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})},ea=async e=>{const n=await oe(e,"Rank page")??{};Zs(n);const r=Xs(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}},ta=async e=>{const n=await oe(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}},na=async e=>{const n=await oe(e,"Shard-registry prune")??{};if(n.tables!==void 0&&!(Array.isArray(n.tables)&&n.tables.every(r=>typeof r=="string")))throw new c("Shard-registry prune `tables` must be an array of table names",{code:"BAD_REQUEST",status:400});return{dryRun:n.dryRun===!0,tables:n.tables}},ra=async e=>{const n=await ne(e);if(typeof n.functionPath!="string"||!Js.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}},oa=e=>{const{defaultShard:t,forwardToShard:n,isAdmin:r,queryCoordinator:s,resolveForwardContext:i,shardDO:d,shardedTables:f}=e,h=(y,b)=>{if(y.method!=="POST")throw new c(`${b} endpoint requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});if(!r(y))throw new c("Admin auth required",{code:"FORBIDDEN",status:403})},m=async(y,b)=>{h(y,"Migration");const T=await Ys(y),{headers:I}=await i(y,b),E=await s.orchestrateMigration(d,{args:T.args,defaultShardKey:t,functionPath:T.functionPath,headers:I,table:T.table});return Response.json(E,{headers:{"content-type":"application/json"},status:200})},g=async(y,b)=>{h(y,"Rank");const T=await qs(y),{headers:I}=await i(y,b),E=await s.orchestrateRank(d,{headers:I,index:T.index,partitionKey:T.partitionKey,rowId:T.rowId,sortValues:T.sortValues,table:T.table});return Response.json(E,{headers:{"content-type":"application/json"},status:200})},A=async(y,b)=>{h(y,"Rank page");const T=await ea(y),{headers:I}=await i(y,b),E=await s.orchestrateRankPage(d,{...T,headers:I});return Response.json(E,{headers:{"content-type":"application/json"},status:200})},S=async(y,b)=>{h(y,"Shard-traffic");const T=await ta(y),{headers:I}=await i(y,b),E=await s.orchestrateShardTraffic(d,{headers:I,table:T.table});return Response.json(E,{headers:{"content-type":"application/json"},status:200})},P=async(y,b)=>{h(y,"Shard-registry prune");const T=await na(y),I=f(),E=(T.tables??[]).filter(C=>!I.includes(C));if(E.length>0)throw new c(`Shard-registry prune names tables that are not \`.shardBy()\`: ${E.join(", ")}`,{code:"BAD_REQUEST",status:400});const{headers:L}=await i(y,b),j=await ro(s.registry,d,{dryRun:T.dryRun,headers:L,tables:T.tables??I});return Response.json(j,{status:j.failed.length>0?207:200})},w=async(y,b)=>{if(M(y,"POST","PITR"),!r(y))throw new c("admin PITR endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403});const T=await ra(y),{headers:I}=await i(y,b),E=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:T.args,functionPath:T.functionPath}),headers:I,method:"POST"});return n(d,T.shardKey??t,E)};return{[Fs]:m,[Ks]:w,[Gs]:g,[Qs]:A,[Ws]:P,[zs]:S}},sa=1,aa=0,ia=32,ca=512,da=/^[a-z][\d_a-z*/-]{0,255}(?:@[a-z][\d_a-z*/-]{0,13})?=[\u0020-\u002B\u002D-\u003C\u003E-\u007E]{1,256}$/,ua=e=>{if(e==null)return;const t=e.trim();if(t.length===0||t.length>ca)return;const n=t.split(",");if(!(n.length>ia)){for(const r of n)if(!da.test(r.trim()))return;return t}},la=e=>{const t=Pr(e.headers.get("traceparent"));if(t===void 0)return;const n=ua(e.headers.get("tracestate"));return{parentSpanId:t.parentSpanId,sampled:t.sampled,traceId:t.traceId,...n===void 0?{}:{traceState:n}}},Gt=(e,t={})=>{const n=la(e),r=t.trustInbound===!0?n:void 0,s=be(8),i=r?.traceId??be(16),d=Cr(t.sampling,r===void 0?s:i),{rayId:f}=t,h=d.isTraced&&(r===void 0||r.sampled);return{decision:d,ignoredUpstream:n!==void 0&&r===void 0,trace:{sampled:h,spanId:s,traceFlags:h?sa:aa,traceId:i,...r?.parentSpanId===void 0?{}:{parentSpanId:r.parentSpanId},...r?.traceState===void 0?{}:{traceState:r.traceState},...f===void 0?{}:{rayId:f}}}},Qt=(e,t)=>{t.traceparent=un(e.traceId,e.spanId,e.sampled),e.traceState!==void 0&&(t.tracestate=e.traceState),e.rayId!==void 0&&(t[go]=e.rayId)},ha=(e,t)=>{let n;return()=>{if(n===void 0){const r=Ur(e),s=t===void 0?void 0:t.cf;n=kr(Nr(r),Dr(r,s))}return n}},fa="/_lunora/admin/scheduled",pa="/_lunora/admin/scheduled/status",ma="/_lunora/admin/scheduled/ws",wa="/_lunora/admin/scheduled/cancel",ga="/_lunora/admin/scheduled/dead",ya="/_lunora/admin/scheduled/dead/retry",ba="/_lunora/admin/scheduled/dead/cancel",_a="/_lunora/admin/scheduled/pool/release",Ra=e=>{const{checkWsAdmin:t,requireSchedulerNamespace:n,resolveSchedulerStub:r,schedulerInstanceName:s}=e,i=(m,g)=>A=>{if(A.method!=="GET")throw new c(`${g} endpoint requires GET`,{code:"METHOD_NOT_ALLOWED",status:405});const S=new URL(A.url).searchParams.get("cursor"),P=S===null||S===""?"":`?cursor=${encodeURIComponent(S)}`;return r(A).fetch(new Request(`https://scheduler.internal${m}${P}`,{method:"GET"}))},d=(m,g,A=g)=>async S=>{if(S.method!=="POST")throw new c(`${A} requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});const P=r(S),w=await oe(S,g);if(typeof w?.id!="string"||w.id==="")throw new c(`${g} requires a string \`id\``,{code:"BAD_REQUEST",status:400});return P.fetch(new Request(`https://scheduler.internal${m}`,{body:JSON.stringify({id:w.id}),headers:{"content-type":"application/json"},method:"POST"}))},f=async m=>{if(m.method!=="POST")throw new c("Scheduled pool-release endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const g=r(m),A=await oe(m,"Scheduled pool-release");if(typeof A?.pool!="string"||A.pool==="")throw new c("Scheduled pool-release requires a string `pool`",{code:"BAD_REQUEST",status:400});const S=typeof A.id=="string"&&A.id!==""?A.id:void 0;return g.fetch(new Request("https://scheduler.internal/complete",{body:JSON.stringify(S===void 0?{pool:A.pool}:{id:S,pool:A.pool}),headers:{"content-type":"application/json"},method:"POST"}))},h=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 g=n();return _e(g,s).fetch(new Request("https://scheduler.internal/ws",{headers:{Upgrade:"websocket"}}))};return{[wa]:d("/cancel","Scheduled-cancel","Scheduled-cancel endpoint"),[ba]:d("/dead/cancel","Scheduled dead-letter action"),[ga]:i("/dead","Scheduled dead-letter"),[ya]:d("/dead/retry","Scheduled dead-letter action"),[fa]:i("/list","Scheduled-list"),[_a]:f,[pa]:i("/status","Scheduler-status"),[ma]:h}},Ea="/_lunora/scheduled",Pn="/_lunora/queue",kn=16*1048576,Aa=e=>{const{assertAdmin:t,dispatchScheduled:n,queueHandler:r}=e,s=async(d,f,h)=>{if(t(d),d.method!=="POST")throw new c("scheduled tick endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const m=await oe(d,"Scheduled tick"),g=typeof m?.cron=="string"?m.cron:"";if(g==="")throw new c("scheduled tick requires a `cron` expression",{code:"BAD_REQUEST",status:400});return await n({cron:g,noRetry:()=>{},scheduledTime:Date.now()},f,h),Response.json({cron:g,ok:!0})},i=async(d,f,h)=>{if(t(d),d.method!=="POST")throw new c("queue dispatch endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});if(!r)throw new c("no queueHandler configured",{code:"BAD_REQUEST",status:400});const m=await oe(d,"Queue dispatch",kn);if(!Array.isArray(m?.messages))throw new c("queue dispatch requires a `messages` array",{code:"BAD_REQUEST",status:400});const g=typeof m.queue=="string"?m.queue:"",A=m.messages.filter(P=>typeof P=="object"&&P!==null&&typeof P.id=="string").map(P=>({body:P.body,id:P.id})),S=await r({messages:A,queue:g},f,h);return Response.json({retry:S?.retry??[]})};return{[Pn]:i,[Ea]:s}},Sa=(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},rt={mtls:e=>Sa(e,"tlsClientAuth","certVerified")==="SUCCESS"},Ta=e=>e===void 0||e===!1?()=>!1:e===!0?()=>!0:typeof e=="function"?e:(Object.hasOwn(rt,e)?rt[e]:void 0)??(()=>!1),va=e=>typeof e=="string"&&Object.hasOwn(rt,e),Oa=e=>{const t=va(e)?e:void 0;if(e!==void 0&&t===void 0)return()=>{};let n=!1;return r=>{n||t!==void 0&&r.cf!==void 0||(n=!0,console.warn(t===void 0?'[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.':`[lunora] \`trustInboundTraceContext: "${t}"\` cannot be satisfied on this host: the request carries no platform-injected \`cf\` metadata, which is what that signal reads, so every inbound \`traceparent\` is ignored and this request starts a new trace. Off Cloudflare, trust the upstream some other way — \`trustInboundTraceContext: true\` when nothing untrusted can reach this worker, or a predicate that verifies whatever your own front door sets. Set it to \`false\` to keep this behaviour and silence this message.`))}},Ia="/_lunora/admin/vector/indexes",Pa="/_lunora/admin/vector/query",ka=e=>{const{readJsonBody:t,requireAdminOption:n}=e,r=async i=>{M(i,"GET","Vector-indexes");const d=n(i,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});return Response.json({indexes:await d.listIndexes()},{headers:{"content-type":"application/json"},status:200})},s=async i=>{M(i,"POST","Vector-query");const d=n(i,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});if(d.queryIndex===void 0)throw new c("vector index querying is not enabled on this worker",{code:"VECTOR_QUERY_UNSUPPORTED",status:400});const h=await t(i);if(typeof h.name!="string"||h.name==="")throw new c("Vector-query request requires a `name` string",{code:"BAD_REQUEST",status:400});if(typeof h.text!="string"||h.text==="")throw new c("Vector-query request requires a `text` string",{code:"BAD_REQUEST",status:400});if(h.topK!==void 0&&(typeof h.topK!="number"||!Number.isInteger(h.topK)||h.topK<1))throw new c("Vector-query `topK` must be a positive integer",{code:"BAD_REQUEST",status:400});const m=await d.queryIndex({name:h.name,text:h.text,topK:h.topK});return Response.json(m,{headers:{"content-type":"application/json"},status:200})};return{[Ia]:r,[Pa]:s}},Da="/_lunora/admin/workflows/instances",Na="/_lunora/admin/workflows/instance",Ua="/_lunora/admin/workflows/status",Ca={complete:!0,errored:!0,paused:!0,queued:!0,rollingBack:!0,running:!0,terminated:!0,unknown:!0,waiting:!0,waitingForPause:!0},Ba=e=>e!==null&&Object.hasOwn(Ca,e)?e:void 0,Wt=(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},Ve=(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},zt=()=>{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})},xa=e=>{const{assertAdmin:t,resolveWorkflowsClient:n}=e,r=async(d,f,h)=>{M(d,"GET","Workflows instances"),t(d);const m=n(f);if(!m)return Response.json({configured:!1,instances:[],page:1,perPage:0,totalCount:0});const g=Ve(h,"name"),A=Ba(h.searchParams.get("status"));return Response.json(await m.listInstances({page:Wt(h,"page"),perPage:Wt(h,"perPage"),status:A,workflowName:g}))},s=async(d,f,h)=>{M(d,"GET","Workflows instance"),t(d);const m=n(f);return m?Response.json(await m.getInstance({instanceId:Ve(h,"id"),workflowName:Ve(h,"name")})):zt()},i=async(d,f)=>{M(d,"POST","Workflows status"),t(d);const h=n(f);if(!h)return zt();const m=await oe(d,"Workflows status");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:g}=m;if(g!=="pause"&&g!=="restart"&&g!=="resume"&&g!=="terminate")throw new c("Workflows status action must be one of: pause, restart, resume, terminate",{code:"BAD_REQUEST",status:400});return Response.json(await h.setInstanceStatus({action:g,instanceId:m.id,workflowName:m.name}))};return{[Na]:s,[Da]:r,[Ua]:i}},Ha={[On]:In,[Pn]:kn,[zr]:Wr},La="https://queue.lunora.internal",Vt=()=>({publish:()=>Promise.reject(new c("ctx.live.publish is unavailable: this worker does not serve live streams",{code:"LIVE_STREAMS_UNSUPPORTED",status:501}))}),ja=async(e,t)=>{const n=new c(`ctx.live.publish to "${t}" failed with HTTP ${String(e.status)}`,{code:"INTERNAL",status:e.status>=400?e.status:500});let r;try{r=await e.json()}catch{return n}const s=r?.error;return typeof s?.code!="string"||e.status<400?n:new c(typeof s.message=="string"?s.message:`ctx.live.publish to "${t}" was refused`,{code:s.code,status:e.status})},Jt="/_lunora/rpc",Ma="/_lunora/rpc-batch",$a="/_lunora/ws",Te=(e,t,n)=>({resourceAttributes:ha(e,t),...n===void 0?{}:{waitUntil:n}}),Je=e=>e?.waitUntil?{waitUntil:t=>e.waitUntil?.(t)}:{},Yt=e=>({spanId:e.spanId,traceFlags:e.traceFlags,traceId:e.traceId,...e.parentSpanId===void 0?{}:{parentSpanId:e.parentSpanId}}),Ye=e=>{const{method:t}=e,n=e.headers.get("user-agent")??void 0,r=bo(e.headers.get(wo)),s=r===void 0?{}:{rayId:r};let i;try{i=new URL(e.url)}catch{return{method:t,...s,userAgent:n}}const d=i.port===""?void 0:Number(i.port);return{host:i.hostname,method:t,path:i.pathname,port:Number.isNaN(d)?void 0:d,...s,scheme:i.protocol.replace(":",""),userAgent:n}},qt="/_lunora/voice/",Fa="/_lunora/admin/cron-jobs/run",Ka="/_lunora/admin/ws-token",Ga="/_lunora/admin/",xe="/_lunora/",Qa="/_lunora/migrate",Wa="/_lunora/status",za=e=>e.startsWith(Ga)||e===Qa,ke=e=>{if(Bo(e))throw new c("`__lunora_relation__:*` is a fan-out-only reserved RPC and cannot be dispatched to a single shard",{code:"FORBIDDEN",status:403})},De=async e=>await e===!0,Xt=(e,t)=>{const n=e.headers.get(St);if(n===null)return;const r=Ir(n);if(r===void 0)throw new c(`malformed ${St} header`,{code:"BAD_REQUEST",status:400});if(r.subject!==(t?.userId??null))throw new c("the session changed since this write was queued",{code:"IDENTITY_MISMATCH",status:409})},Zt="/api/auth",Va="__lunora_admin__:recordAuthEvent",en="__lunora_admin__:listPushSubscriptions",Ja=["/sign-in","/sign-up","/callback"],Ya=(e,t)=>{const n=t.endsWith("/")?t.slice(0,-1):t;if(!e.startsWith(`${n}/`))return!1;const r=e.slice(n.length);return Ja.some(s=>r===s||r.startsWith(`${s}/`))},tn=(e,t)=>{const n=t.endsWith("/")?t.slice(0,-1):t;return e===n||e.startsWith(`${n}/`)},Ne=(e,t,n,r)=>{const s=br(n),i=s?n.code:"INTERNAL_SERVER_ERROR",d=s?n.status:500,{message:f,name:h,stack:m}=Er(n),g=Ar(n,{capped:!1});return{durationMs:t,error:{code:i,message:f,name:h,status:d,...m===void 0?{}:{stack:m},...g===void 0?{}:{internal:g}},functionPath:e,ok:!1,...r.fanOut?{fanOut:{failed:0,shards:0,table:r.fanOut.table}}:{},...r.shardKey?{shardKey:r.shardKey}:{}}},Dn=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},Nn=({identity:e})=>e!==null&&Tr(Dn(e)),qa=e=>{if(Nn(e))throw new c("authentication token expired",{code:"TOKEN_EXPIRED",status:401});return e},Xa=e=>{if(!Nn(e))return e;const t={...e.headers};return delete t["x-lunora-identity"],delete t["x-lunora-identity-exp"],delete t["x-lunora-userid"],{claims:null,headers:t,identity:null,userId:null}},nn=e=>e.waitUntil?{waitUntil:t=>{e.waitUntil?.(t)}}:void 0,Za=e=>{const t=e?.queue;return typeof t=="string"&&t.length>0?t:"unknown"},ot=new WeakMap,ei=async(e,t,n,r,s=ot.get(e))=>{const i={"content-type":"application/json"},d=e.headers.get("authorization"),f=e.headers.get("cookie"),h=e.headers.get("x-d1-bookmark"),m=e.headers.get("x-lunora-mutation-id"),g=e.headers.get("x-lunora-client-id"),A=e.headers.get("x-lunora-client-seq"),S=e.headers.get("x-lunora-base-seq");d&&(i.authorization=d),f&&(i.cookie=f),h&&(i["x-d1-bookmark"]=h),m&&(i["x-lunora-mutation-id"]=m),g&&(i["x-lunora-client-id"]=g),A&&(i["x-lunora-client-seq"]=A),S&&(i["x-lunora-base-seq"]=S);const P=Mr(e.headers,r);if(P&&(i["x-lunora-client-ip"]=P),i["x-lunora-origin"]=new URL(e.url).origin,!n)return{claims:null,headers:i,identity:null,userId:null};const w=await n(e,t,s);if(!w||typeof w.userId!="string"||w.userId.length===0)return{claims:null,headers:i,identity:null,userId:null};i["x-lunora-userid"]=vr(w.userId);const y=Dn(w);y!==void 0&&(i["x-lunora-identity-exp"]=String(y));const{userId:b,...T}=w,I=Object.keys(T).length>0?T:null;return I&&(i["x-lunora-identity"]=Or(I)),{claims:I,headers:i,identity:w,userId:b}},ti=new Set(["concat","first","groupBy","max","min","rank","sum","topK"]),ni=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"||!ti.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},ri=(e,t)=>{e?.LUNORA_DEBUG_RPC&&console.warn(`[lunora:rpc] ${t.fanOut?"fan-out":`shard=${t.shardKey??"(root)"}`} ${t.functionPath}`)},qe=(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}},oi=async e=>{const t=await fn(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&&hn(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 s=n,i=ni(s.fanOut),d=s.args??{};if(i&&s.functionPath.startsWith("__lunora_relation__:")){const f=d.table;if(typeof f=="string"&&f!==i.table)throw new c("RPC `args.table` must match the authorized `fanOut.table` for a relation fan-out",{code:"BAD_REQUEST",status:400});d.table=i.table}return{args:d,fanOut:i,functionPath:s.functionPath,shardKey:s.shardKey}},Ue=new Map,si=5e3,ai=4096,ii=async(e,t)=>{const n=Date.now(),r=Ue.get(t);if(r!==void 0&&r.expiresMs>n)return r.relayCount;r!==void 0&&Ue.delete(t);let s=0;try{const i=await _e(e,t).fetch(new Request("https://shard.internal/_lunora/route"));if(i.ok){const d=await i.json();typeof d.relayCount=="number"&&d.relayCount>0&&(s=Math.floor(d.relayCount))}}catch{s=0}return an(Ue,ai),Ue.set(t,{expiresMs:n+si,relayCount:s}),s},rn=(e,t)=>{if(!(e===null||typeof e!="object"))return Object.entries(e).find(([,n])=>n===t)?.[0]},Ce=(e,t,n)=>new Request("https://shard.internal/rpc",{body:JSON.stringify({args:t,functionPath:e}),headers:n,method:"POST"}),ci=["x-lunora-userid","x-lunora-identity","x-lunora-identity-exp","x-lunora-client-ip"],di=(e,t)=>{for(const n of ci){e.delete(n);const r=t[n];r!==void 0&&e.set(n,r)}},Xe=e=>e.headers.get("Upgrade")?.toLowerCase()==="websocket",on=(e,t)=>{const n=new Headers(e.headers),r=[...n.keys()];for(const s of r)s.startsWith("x-lunora-")&&n.delete(s);return di(n,t),n},sn=async(e,t)=>{if(!t||t.length===0)return!1;const n=new URL(e.url).searchParams.get("token");return n===null?!1:Ko(t,n)},ui=(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 eo(`d1:${e}`,t);if(typeof n.list=="function"&&typeof n.head=="function"&&typeof n.createMultipartUpload=="function")return Fe(`r2:${e}`,!0);if(typeof n.send=="function"&&typeof n.sendBatch=="function"&&typeof n.get!="function")return Fe(`queue:${e}`,!0);if(typeof n.connectionString=="string")return Fe(`hyperdrive:${e}`,!0)},li=e=>{for(const t of Object.keys(e??{}))if(t.slice(t.indexOf(" ")+1).startsWith(xe))throw new c(`route "${t}" is under the reserved ${xe} prefix, which the framework owns. App routes registered there shadow the internal endpoint AND its admin gate — pick a path outside the prefix.`,{code:"MISCONFIGURED",status:500})},hi=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})},Un=e=>{hi(e);const t=Ta(e.trustInboundTraceContext),n=Oa(e.trustInboundTraceContext),r=e.defaultShardKey??"__root__",s=e.queryCoordinator??oo({registry:so(e.resolveTableSharding,r)}),i=to(e.resolveIdentity,e.identity),d=Ke(e.shardDO,e.jurisdiction),f=e.schedulerDO===void 0?void 0:Ke(e.schedulerDO,e.jurisdiction),h=e.voiceAgents===void 0?void 0:Object.fromEntries(Object.entries(e.voiceAgents).map(([o,a])=>[o,Ke(a,e.jurisdiction)]));let m=!1;const g=o=>{if(o===void 0||e.jurisdiction===void 0)return o;m||(m=!0,console.warn(`[lunora] jurisdiction "${e.jurisdiction}" pins placement, so region hints (\`shardRegion\`, replica and relay placement) are not sent. Residency wins.`))},A=async(o,a,l,u=e.shardRegion?.(a))=>_e(o,a,g(u)).fetch(l);let S;const P=()=>e.adminToken??S;let w;const y=o=>{const a=o??{};if(w??=rn(o,e.shardDO),S!==void 0||e.adminToken!==void 0)return;const l=a.LUNORA_ADMIN_TOKEN;typeof l=="string"&&l.length>0&&(S=l)},b=new WeakSet,T=o=>bn(o,P())||b.has(o),I=async o=>{if(!(e.adminGate===void 0||b.has(o)))try{await De(e.adminGate(o,ot.get(o)))&&b.add(o)}catch{}},E=async(o,a,l,u)=>{const p=await ei(o,a,l,e.trustedClientIpHeader,u);return e.functions!==void 0&&(p.headers[dn]=cn),p},L=async(o,a,l,u)=>qa(await E(o,a,l,u)),j=async(o,a)=>{const l=await E(o,a,e.resolveIdentity);if(b.has(o)&&l.headers.authorization===void 0){const u=P();u!==void 0&&(l.headers.authorization=`Bearer ${u}`)}return l};let C=!1,K=!1;const q=()=>{K||(K=!0,console.warn("[lunora] `replicaReads: true` has no effect without `functions` — read eligibility is decided from the function registry."))},V=o=>{if(!e.allowUnauthenticatedShardAccess){const a=o==="fan-out"?"authorizeFanOut":"authorizeShard";throw new c(`${o} access is default-denied: configure \`${a}\` 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})}C||(C=!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("")))},G=async(o,a,l=!1)=>{if(a.includes(et)||a.includes(tt))throw new c("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403});if(!l)if(e.authorizeShard){if(!await De(e.authorizeShard({identity:o,shardKey:a})))throw new c("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else a!==r&&V("shard")},J=oa({defaultShard:r,forwardToShard:A,isAdmin:T,queryCoordinator:s,resolveForwardContext:j,shardDO:d,shardedTables:()=>(e.listSchemaTables?.()??[]).filter(o=>e.resolveTableSharding?.(o)?.mode.kind==="shardBy")}),se=async(o,a,l,u,p)=>{const{__lunoraLive:_,topic:v}=a,k=u?.shardKey??r;p==="trusted"?await G(null,k,!0):k!==r&&await G(p.identity,k);const N=await A(d,k,new Request(new URL(mo,o),{body:JSON.stringify({data:ye(l??null),stream:_,topic:v}),headers:{"content-type":"application/json"},method:"POST"}));if(!N.ok)throw await ja(N,v)},W=async(o,a,l,u,p,_)=>{ke(o);const v=Ho({forwardedIdentity:p,mutationId:u,traceparent:_});return A(d,l,Ce(o,a,v))},le=async(o,a,l,u,p)=>{const _=Mo(l.env,l.context?.exports,o,["create"]);if(_===void 0)throw new c(`${u} targets workflow "${o}", which is on neither ctx.exports nor env`,{code:"CRON_JOB_FAILED",status:500});if(uo(a))throw new c(`${u} params ${lo}`,{code:"BAD_REQUEST",status:400});try{await _.create(p===void 0?{params:a}:{id:p,params:a})}catch(v){if(!po(v))throw v}},ae=async(o,a,l,u)=>{if(o.workflow){await le(o.workflow,o.args??{},{context:l,env:a},`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 p=await W(o.functionPath,o.args??{},o.shardKey??r,void 0,void 0,u);if(!p.ok)throw new c(`cron job "${o.name}" (${o.functionPath}) failed with shard status ${String(p.status)}`,{code:"CRON_JOB_FAILED",status:500})},z=o=>{if(!T(o))throw new c("admin endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403})},ie=(o,a,l)=>{if(z(o),a===void 0)throw new c(l.message,{code:l.code,status:400});return a},He=async(o,a,l,u,p,_)=>{const v=e.cronJobs?.[o];if(!v)return 0;for(const k of v)try{await ae(k,a,l,_)}catch(N){u.push(p(N))}return v.length},ce=async(o,a,l)=>{if(z(o),M(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 u=await ne(o),p=typeof u.name=="string"?u.name:"";if(p==="")throw new c("cron-jobs run endpoint requires a job `name`",{code:"BAD_REQUEST",status:400});const _=Object.values(e.cronJobs).flat().find(v=>v.name===p);if(!_)throw new c(`no cron job named "${p}" is registered`,{code:"CRON_JOB_NOT_FOUND",status:404});return await ae(_,a,l),Response.json({name:p,ran:!0},{status:200})},dt=async o=>{const a=typeof o.pool=="string"&&o.pool.length>0?o.pool:void 0;if(!a||!f||typeof o.id!="string")return;const l=typeof o.instanceName=="string"&&o.instanceName.length>0?o.instanceName:"default";try{await _e(f,l).fetch(new Request("https://scheduler.internal/complete",{body:JSON.stringify({id:o.id,pool:a}),headers:{"content-type":"application/json"},method:"POST"}))}catch{}},Cn=async(o,a,l)=>{M(o,"POST","Scheduler dispatch");const u=await fn(o),p=a??{},_=typeof p.LUNORA_SCHEDULER_SECRET=="string"?p.LUNORA_SCHEDULER_SECRET:void 0,v=e.adminToken??(typeof p.LUNORA_ADMIN_TOKEN=="string"?p.LUNORA_ADMIN_TOKEN:void 0);if(!await xo(o,u,{adminToken:v,schedulerSecret:_}))throw new c("Scheduler dispatch requires a valid signature or admin bearer",{code:"DISPATCH_UNAUTHENTICATED",status:403});let N;try{N=JSON.parse(u)}catch{throw new c("Scheduler dispatch body must be valid JSON",{code:"BAD_REQUEST",status:400})}const R=N??{},O=R.args??{},D=typeof R.id=="string"&&R.id.length>0?R.id:void 0;if(typeof R.workflow=="string"&&R.workflow.length>0)return await le(R.workflow,O,{context:l,env:a},"scheduled workflow",D),await dt(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 H=typeof R.shardKey=="string"&&R.shardKey.length>0?R.shardKey:r,$=Lo(o),x=await W(R.functionPath,O,H,D,$,o.headers.get("traceparent")??void 0);return await dt(R),x},Bn=zo({assertAdmin:z,getReader:()=>e.authAuditReader}),xn=Vo({assertAdmin:z,getMove:()=>e.authJurisdictionMove}),Hn=async(o,a)=>{z(o);const l=e.notifySubscriptionStore;if(l===void 0)return Response.json({result:ye({subscriptions:[]})},{headers:{"content-type":"application/json"},status:200});const u=a?.kind,p=a?.userId,_=a?.limit,v=u==="fcm"||u==="web-push"?u:void 0,k=typeof p=="string"&&p!==""?p:void 0,N=typeof _=="number"&&Number.isFinite(_)?Math.trunc(_):0,R=N>0?Math.min(N,1e3):1e3,D=(await l.list({kind:v,limit:R,userId:k})).filter(H=>v!==void 0&&H.kind!==v?!1:k===void 0||(H.userId??null)===k).map(({keys:H,token:$,...x})=>x);return Response.json({result:ye({subscriptions:D})},{headers:{"content-type":"application/json"},status:200})},Ln=async(o,a)=>{if(!a.fanOut&&!(a.functionPath!==Ct&&a.functionPath!==en&&a.functionPath!==nt&&a.functionPath!==En))return await I(o),a.functionPath===Ct?Bn(o,a.args??{}):a.functionPath===en?Hn(o,a.args):xn(o,a.functionPath,a.args??{})},jn=bs({applyGlobals:e.applyGlobals,assertAdmin:z,exportCursorStore:e.exportCursorStore,exportSinks:e.exportSinks,defaultShardKey:r,knownTables:()=>[...e.listSchemaTables?.()??[]],queryCoordinator:s,resolveForwardContext:j,shardDO:d,prepareExportRows:async(o,a)=>An(e,s,o,a,d),streamingImport:(o,a)=>Ss(o,e,s,a,d),syncGlobals:e.syncGlobals}),Le=(o,a)=>{const l=o.searchParams.get(a);return l===null||l===""?void 0:l},je=o=>{const a=new URL(o.url),l=a.searchParams.get("limit"),u=a.searchParams.get("offset"),p=l===null?void 0:Number.parseInt(l,10),_=u===null?void 0:Number.parseInt(u,10);return{limit:p!==void 0&&Number.isFinite(p)&&p>=0?p:void 0,offset:_!==void 0&&Number.isFinite(_)&&_>=0?_:void 0}},ut=()=>{if(f===void 0)throw new c("scheduled endpoints require a `schedulerDO` namespace on the worker",{code:"SCHEDULER_NOT_CONFIGURED",status:400});return f},Mn=Ra({checkWsAdmin:async o=>T(o)||sn(o,P()),requireSchedulerNamespace:ut,resolveSchedulerStub:o=>(z(o),_e(ut(),e.schedulerInstanceName??"default")),schedulerInstanceName:e.schedulerInstanceName??"default"}),$n=xa({assertAdmin:z,resolveWorkflowsClient:e.workflowsClient??(()=>{})}),Fn=Qr({assertAdmin:z,parsePaging:je,queryParameter:Le,readBodyBytes:Lr,requireAdminOption:ie,storage:{storageBuckets:e.storageBuckets,storageDelete:e.storageDelete,storageDownload:e.storageDownload,storageList:e.storageList,storageSignedUrl:e.storageSignedUrl,storageUpload:e.storageUpload}}),Kn=cs({options:e,readJsonBody:ne,requireAdminOption:ie}),Gn=ka({readJsonBody:ne,requireAdminOption:ie,vectorIntrospector:e.vectorIntrospector}),Qn=$s({kvIntrospector:e.kvIntrospector,readJsonBody:ne,requireAdminOption:ie}),Wn=no({logArchive:e.logArchive,readJsonBody:ne,requireAdminOption:ie}),zn=Ls({assertAdmin:z,options:{cronJobs:e.cronJobs,functions:e.functions,globalIntrospector:e.globalIntrospector,architecture:e.architecture,openApiSpec:e.openApiSpec,openRpcSpec:e.openRpcSpec},parsePaging:je,queryParameter:Le,requireAdminOption:ie}),Vn=o=>{const a=[],l=d??o?.SHARD;if(l!==void 0&&a.push(Zr("durable-object:default",l,r)),e.health?.disableBindingProbes!==!0)for(const[u,p]of Object.entries(o??{})){const _=ui(u,p);_!==void 0&&a.push(_)}for(const u of e.health?.probes??[])a.push(u);return a},Jn=Xr({appName:e.health?.appName,appVersion:e.health?.appVersion,auth:e.health?.auth??"public",cacheTtlMs:e.health?.cacheTtlMs,isAdmin:T,resolveProbes:Vn}),Yn=o=>{const a=R=>"args"in R?{...R,args:Ze(R.args)}:R,l=e.schedulerInstanceName??"default",u=()=>_e(o,l),p=async(R,O)=>{const D=await u().fetch(new Request(`https://scheduler.internal${R}`,O));if(!D.ok)throw new c(`ctx.scheduler: SchedulerDO ${R} failed (${String(D.status)}): ${await D.text()}`,{code:"INTERNAL",status:500});return await D.json()},_=async(R,O)=>await p(R,{body:JSON.stringify(O),headers:{"content-type":"application/json"},method:"POST"}),v=R=>{const O=R;if(O==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 O.binding=="string"&&O.binding.length>0)return{workflow:O.binding};if(typeof O.__lunoraRef=="string")return{functionPath:O.__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})},k=async()=>(await ho(async O=>p(O===void 0?"/list":`/list?cursor=${encodeURIComponent(O)}`,{method:"GET"}))).map(O=>a(O)),N=async(R,O,D={})=>{const H=v(O),{id:$}=await _("/schedule",{args:Rr("ctx.scheduler",String(H.functionPath??H.workflow),D),scheduledFor:Math.ceil(R),...H});return $};return{cancel:async R=>await _("/cancel",{id:R}),get:async R=>{const O=await p(`/get?id=${encodeURIComponent(R)}`,{method:"GET"});return O.record===void 0?null:a(O.record)},list:k,runAfter:async(R,O,D)=>{if(!Number.isFinite(R)||R<0)throw new c("ctx.scheduler.runAfter: `delayMs` must be a non-negative finite number",{code:"INVALID_INPUT",status:400});return await N(Date.now()+R,O,D)},runAt:async(R,O,D)=>{if(!Number.isFinite(R))throw new c("ctx.scheduler.runAt: `date` must be a non-negative finite number",{code:"INVALID_INPUT",status:400});return await N(R,O,D)}}},qn=async(o,a,l)=>{const{claims:u,headers:p,identity:_,userId:v}=Xa(await E(o,a,i)),k=Te(a,o,D=>l.waitUntil?.(D)),N=D=>async(H,$={})=>{const x=H.__lunoraRef;if(typeof x!="string")throw new c("ctx.run*: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});ke(x),D!==r&&await G(_,D);const X=await Oe(o,x,ye($),D,{...p,"x-lunora-system":"1"},k),Z=await X.json();if(Z.error)throw new c(Z.error.message??"shard RPC failed",{code:Z.error.code??"INTERNAL",status:X.status});return Ze(Z.result)},R=N(r),O=async(D,H,$={})=>{D!==void 0&&D!==r&&await G(_,D);const x=new Headers;for(const[X,Z]of Object.entries($.headers??{}))X.toLowerCase().startsWith("x-lunora-")||x.set(X,Z);for(const[X,Z]of Object.entries(p))x.set(X,Z);return A(d,D??r,new Request(new URL(H,o.url),{headers:x,method:$.method??"GET",...$.body===void 0?{}:{body:$.body}}))};return{auth:{getIdentity:()=>Promise.resolve(u),userId:v},cache:l.cache,fetch:globalThis.fetch.bind(globalThis),fetchShard:O,forShard:D=>{const H=N(D);return{runAction:H,runMutation:H,runQuery:H}},live:e.liveStreams===!1?Vt():{publish:(D,H,$)=>se(o.url,D,H,$,{identity:_})},runAction:R,runMutation:R,runQuery:R,...f===void 0?{}:{scheduler:Yn(f)},...l.waitUntil===void 0?{}:{waitUntil:l.waitUntil.bind(l)},...e.storage===void 0?{}:{storage:co(e.storage(a,new URL(o.url).origin))}}},Xn=async(o,a,l)=>{if(!e.httpRouter)return;const u=await qn(o,a,l);try{return await e.httpRouter.fetch(o,{...a,__lunoraCtx:u},l)}catch(p){return console.error("[lunora] httpRouter (SSR) handler threw:",p),new Response("Internal Server Error",{status:500})}},lt=new Set(Object.values(e.functions??{}).flatMap(o=>o.lifecycle==="socket"&&typeof o.socketPath=="string"?[o.socketPath]:[])),ht=async(o,a,l)=>{if(!Xe(o))throw new c("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});const u=kt(o,de);if(u)return u;const p=l.searchParams.get("shard")??r,{headers:_,identity:v}=await E(o,a,i),k=T(o)||await sn(o,P());await G(v,p,k);const N=on(o,_),R=rn(a,e.shardDO);if(R!==void 0){N.set("x-lunora-shard-binding",R);const O=lt.has(l.pathname)?0:await ii(d,p);if(O>0){const D=To(p,Math.floor(Math.random()*O));return A(d,D,new Request(o,{headers:N}),Dt(o))}}return A(d,p,new Request(o,{headers:N}))},Zn=async(o,a,l)=>{if(h===void 0)return new Response("Not found",{status:404});if(!Xe(o))return new Response("Expected a WebSocket upgrade",{headers:{allow:"GET"},status:426});const u=kt(o,de);if(u)return u;let p;try{p=decodeURIComponent(l.pathname.slice(qt.length))}catch{return new Response("Unknown voice agent",{status:404})}const _=Object.hasOwn(h,p)?h[p]:void 0;if(_===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:k,identity:N}=await E(o,a,i);if(e.authorizeShard){if(!await De(e.authorizeShard({identity:N,shardKey:v})))throw new c("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else V("shard");const R=on(o,k);return A(_,v,new Request(o,{headers:R}))},er=async(o,a,l)=>{if(e.authorizeFanOut){if(!await De(e.authorizeFanOut(l,o.table,a)))throw new c("Forbidden fan-out",{code:"FORBIDDEN_FANOUT",status:403});return}if(a.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});V("fan-out")},ve=async(o,a)=>{if(!(!o.fanOut&&o.functionPath.startsWith("__lunora_admin__:"))){if(o.fanOut){await er(o.fanOut,o.functionPath,a);return}await G(a,o.shardKey??r)}},tr=(o,a,l)=>{if(e.replicaReads!==!0)return;if(e.functions===void 0){q();return}if(e.functions[a]?.kind!=="query"||l.includes(tt)||l.includes(et))return;const u=Dt(o);return u===void 0?void 0:{name:vo(l,u),region:u}},nr=async(o,a,l,u,p)=>{const _=tr(o,a,u);if(_!==void 0){const v={...p,"x-lunora-replica-read":"1",...w===void 0?{}:{"x-lunora-shard-binding":w}},k=Oo(o.headers.get("x-lunora-min-seq"));k!==void 0&&(v["x-lunora-min-seq"]=String(k));const N=await A(d,_.name,Ce(a,l,v),_.region);if(N.status!==421)return N}return A(d,u,Ce(a,l,p))},Oe=async(o,a,l,u,p,_)=>{const v=Date.now(),{observability:k,sampling:N}=e,R=Ye(o),{decision:O,ignoredUpstream:D,trace:H}=Gt(o,{...R.rayId===void 0?{}:{rayId:R.rayId},...N===void 0?{}:{sampling:N},trustInbound:t(o)});D&&n(o);const $={...p,[vt]:O.keepErrors?"1":"0",[At]:"1"};Qt(H,$);try{const x=await nr(o,a,l,u,$),X=Rt(x.headers.get(Et));ue(k,{...R,...Yt(H),durationMs:Date.now()-v,functionPath:a,ok:x.ok,shardKey:u,...x.ok?{}:{error:{...X,code:X?.code??"SHARD_ERROR",message:X?.message??`shard returned ${String(x.status)}`,status:x.status}}},_,void 0,{isTraced:H.sampled,keepErrors:O.keepErrors});const Z=new Response(x.body,{headers:x.headers,status:x.status,statusText:x.statusText});return Z.headers.set("x-lunora-shard-key",u),Z.headers.delete(Et),Z}catch(x){throw ue(k,{...R,...Yt(H),...Ne(a,Date.now()-v,x,{shardKey:u})},_,void 0,{isTraced:H.sampled,keepErrors:O.keepErrors}),x}},rr=o=>{if(o.fanOut&&o.shardKey)throw new c("RPC envelope cannot set both `shardKey` and `fanOut`",{code:"BAD_REQUEST",status:400});o.fanOut||ke(o.functionPath)},or=async(o,a,l)=>{M(o,"POST","RPC");const u=await oi(o);ri(a,u),rr(u);const p=await Ln(o,u);if(p!==void 0)return p;const{headers:_,identity:v}=await L(o,a,i);Xt(o,v),await ve(u,v);const k=qe(u,e);{const N=Date.now(),{observability:R}=e,O=Ye(o),D=Te(a,o,l&&(x=>l.waitUntil?.(x)));if(u.fanOut)try{const x=await s.fanOut(d,{args:u.args??{},fanOut:u.fanOut,functionPath:u.functionPath,headers:_});return ue(R,{durationMs:Date.now()-N,fanOut:{failed:x.failed,shards:x.ok+x.failed,table:u.fanOut.table},functionPath:u.functionPath,...O,ok:!0},D),Response.json(x,{headers:{"content-type":"application/json"},status:200})}catch(x){throw ue(R,{...Ne(u.functionPath,Date.now()-N,x,{fanOut:{table:u.fanOut.table}}),...O},D),x}const H=u.shardKey??r,$=()=>Oe(o,u.functionPath,u.args??{},H,_,D);return k&&e.x402Charge?e.x402Charge(o,{functionPath:u.functionPath,price:k.price},$,Je(l)):$()}},sr=async(o,a,l)=>{M(o,"POST","RPC batch");const u=await ne(o),{calls:p}=u;if(!Array.isArray(p))throw new c("RPC batch `calls` must be an array",{code:"BAD_REQUEST",status:400});const{headers:_,identity:v}=await L(o,a,i);Xt(o,v);const k=us(p,r);for(const F of k.values())for(const Q of F)if(e.functions?.[Q.functionPath]?.x402)throw new c(`paid (\`.x402\`) function "${Q.functionPath}" cannot be called in a batch; dispatch it individually over ${Jt}`,{code:"BAD_REQUEST",status:400});await Promise.all([...k.entries()].flatMap(([F,Q])=>Q.map(ee=>ve({args:ee.args,functionPath:ee.functionPath,shardKey:F},v))));const{observability:N,sampling:R}=e,O=Te(a,o,l&&(F=>l.waitUntil?.(F))),D=Ye(o),{decision:H,ignoredUpstream:$,trace:x}=Gt(o,{...D.rayId===void 0?{}:{rayId:D.rayId},...R===void 0?{}:{sampling:R},trustInbound:t(o)});$&&n(o);const X={isTraced:x.sampled,keepErrors:H.keepErrors},Z=F=>{const Q={..._,"content-type":"application/json",[vt]:H.keepErrors?"1":"0",[At]:"1"};return Qt({...x,spanId:F},Q),Q},Me=F=>({parentSpanId:F,spanId:be(8),traceFlags:x.traceFlags,traceId:x.traceId}),Pe=[],$e=[],wt=(F,Q,ee,he)=>({body:{error:{code:ee,message:he}},id:F.id,status:Q}),gt=(F,Q,ee,he,we)=>{for(const te of F)ue(N,we(te),O,void 0,X),Pe.push(wt(te,Q,ee,he))},gr=(F,Q,ee,he,we,te)=>{for(const Re of F){const Ee=we.get(Re.id),fe=Ee?.status??te,pe=fe<400,Ae=pe?void 0:Rt(Ee?.errorDetail);ue(N,{durationMs:he,functionPath:Re.functionPath,...D,...Me(ee),ok:pe,shardKey:Q,...pe?{}:{error:{...Ae,code:Ae?.code??"SHARD_ERROR",message:Ae?.message??`batched call returned ${String(fe)}`,status:fe}}},O,void 0,X)}};await Promise.all([...k.entries()].map(async([F,Q])=>{const ee=be(8),he=new Request("https://shard.internal/rpc-batch",{body:JSON.stringify({calls:Q}),headers:new Headers(Z(ee)),method:"POST"}),we=Date.now();let te;try{te=await A(d,F,he)}catch(Y){const Se=Date.now()-we,{body:_t}=_r(Y,{fallbackCode:"SHARD_UNAVAILABLE",redactedMessage:"shard unavailable"});gt(Q,502,_t.code,_t.message,yr=>({...Ne(yr.functionPath,Se,Y,{shardKey:F}),...D,...Me(ee)}));return}const Re=Date.now()-we,Ee=te.headers.get("x-d1-bookmark");Ee&&$e.push(Ee);let fe;try{fe=await te.json()}catch{const Y=`shard batch returned a non-JSON response (${String(te.status)})`;gt(Q,te.status,"SHARD_UNAVAILABLE",Y,Se=>({durationMs:Re,error:{code:"SHARD_UNAVAILABLE",message:Y,status:te.status},functionPath:Se.functionPath,...D,...Me(ee),ok:!1,shardKey:F}));return}const pe=Array.isArray(fe.results)?fe.results:[],Ae=new Set(pe.map(Y=>Y.id));gr(Q,F,ee,Re,new Map(pe.map(Y=>[Y.id,Y])),te.status),Pe.push(...pe.map(({errorDetail:Y,...Se})=>Se));for(const Y of Q)Ae.has(Y.id)||Pe.push(wt(Y,te.status,"SHARD_UNAVAILABLE",`shard batch omitted result for call ${String(Y.id)}`))}));const yt={"content-type":"application/json"},[bt]=$e;return $e.length===1&&bt!==void 0&&(yt["x-d1-bookmark"]=bt),Response.json({results:Pe},{headers:yt,status:200})},ar=async(o,a,l,u={},p={})=>{try{const _=l.__lunoraRef;if(typeof _!="string")throw new c("serverQuery: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});ke(_);const{headers:v,identity:k}=await L(o,a,i,p.context),N={args:u,functionPath:_,shardKey:p.shardKey};await ve(N,k);const R=p.shardKey??r,O=Te(a,o,p.waitUntil),D=()=>Oe(o,_,u,R,v,O),H=qe(N,e);return H&&e.x402Charge?await e.x402Charge(o,{functionPath:_,price:H.price},D,Je(p.waitUntil?{waitUntil:p.waitUntil}:p.context)):await D()}catch(_){return Ot(_)}},ft=async(o,a,l)=>{const{observability:u}=e,p=Date.now(),_=be(16),v=be(8),k=nn(a),N=un(_,v,!0);try{const R=await l(N);return ue(u,{durationMs:Date.now()-p,functionPath:o,ok:!0,spanId:v,traceId:_},k),R}catch(R){throw ue(u,{...Ne(o,Date.now()-p,R,{}),spanId:v,traceId:_},k),R}finally{Tt(u,k)}},pt=async(o,a,l,u)=>{y(a);const p=[],_=O=>O instanceof Error?O:new Error(String(O)),v=e.crons?.[o.cron];if(v)try{await v(o,a,l)}catch(O){p.push(_(O))}const k=await He(o.cron,a,l,p,_,u),N=!!e.backupStore&&e.backupCron!==void 0&&e.backupCron===o.cron;if(N)try{await os(e,s,d,P(),o)}catch(O){p.push(_(O))}if(!v&&k===0&&!N){const O=[...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: ${O.length===0?"(none)":O.join(", ")}. Check that \`triggers.crons\` in wrangler.jsonc matches the app's cron definitions.`)}const[R]=p;if(p.length===1&&R)throw R;if(p.length>1)throw new AggregateError(p,`scheduled("${o.cron}") had ${String(p.length)} failure(s)`)},ir=Aa({assertAdmin:z,dispatchScheduled:pt,queueHandler:e.queueHandler}),cr=async(o,a)=>{try{const l=o??{},u=e.adminToken??(typeof l.LUNORA_ADMIN_TOKEN=="string"?l.LUNORA_ADMIN_TOKEN:void 0);if(!u||u.length===0)return;await A(d,r,Ce(Va,{outcome:a},{authorization:`Bearer ${u}`,"content-type":"application/json"}))}catch{}},dr=async(o,a,l,u)=>{if(!e.authHandler)return;const p=e.authBasePath??Zt,_=tn(l.pathname,p)?jr(o):void 0;let v;try{v=await e.authHandler(_?.request??o)}catch(k){throw _?.overflowed()?new c("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413}):k}if(_?.overflowed())throw new c("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});if(v)return Ya(l.pathname,p)&&u.waitUntil?.(cr(a,v.status>=400?"fail":"ok")),v},ur=async({args:o,env:a,functionPath:l,request:u,shardKey:p,waitUntil:_})=>{hn(o,"REST");const v={functionPath:l,...p===void 0?{}:{shardKey:p}},{headers:k,identity:N}=await L(u,a,i);await ve(v,N);const R=p??r,O=Te(a,u,_),D=()=>Oe(u,l,o,R,k,O),H=qe(v,e);return H&&e.x402Charge?e.x402Charge(u,{functionPath:l,price:H.price},D,Je({waitUntil:_})):D()},lr=Hr({functions:e.functions??{},invoke:ur,readJsonBody:ne,edgeCache:e.restEdgeCache,...e.restRateLimit?{rateLimit:e.restRateLimit}:{}}),Ie=e.routes!==void 0&&Object.keys(e.routes).length>0?e.routes:void 0;li(Ie);const hr={[Wa]: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"}}),[$a]:(o,a,l)=>ht(o,a,l),[Jt]:(o,a,l,u)=>or(o,a,u),[Ma]:(o,a,l,u)=>sr(o,a,u),[Uo]:(o,a,l,u)=>Cn(o,a,u),[Fa]:(o,a,l,u)=>ce(o,a,u),[Ka]:async o=>{M(o,"POST","ws-token"),z(o);const a=P();if(a===void 0)throw new c("ws-token minting requires a configured admin token",{code:"ADMIN_TOKEN_NOT_CONFIGURED",status:400});const l=await Fo(a);return Response.json(l,{headers:{"cache-control":"no-store"}})},...J,...jn,...Mn,...$n,...Fn,...Kn,...Gn,...Qn,...Wn,...zn,...Jn,...lr,...Wo({assertAdmin:z,getAuthAdmin:()=>e.authAdmin,parsePaging:je,queryParameter:Le,readJsonBody:ne})};let de=Pt(e.security),mt=!1;const fr=o=>{mt||(mt=!0,de=Pt(e.security,o??{}))},pr=async(o,a)=>{za(a)&&await I(o)},mr=(o,a)=>{if(!(a.pathname.startsWith(xe)||e.authHandler!==void 0&&tn(a.pathname,e.authBasePath??Zt))||o.method!=="POST"&&o.method!=="PUT")return;const u=Number(o.headers.get("content-length")??""),p=Ha[a.pathname]??ln;if(Number.isFinite(u)&&u>p)throw new c("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413})},wr=async(o,a,l)=>{ot.set(o,l);const u=new URL(o.url);mr(o,u);const p=await dr(o,a,u,l);if(p)return p;if(lt.has(u.pathname)&&o.method==="GET"&&Xe(o))return ht(o,a,u);if(Ie){const R=`${o.method} ${u.pathname}`,O=Ie[R]??Ie[u.pathname];if(O)return O(o,a,l)}const _=ir[u.pathname];if(_)return _(o,a,l);const v=hr[u.pathname];if(v)return await pr(o,u.pathname),v(o,a,u,l);if(e.voiceAgents!==void 0&&u.pathname.startsWith(qt))return Zn(o,a,u);if(u.pathname.startsWith(xe))return new Response("Not found",{status:404});const k=await Xn(o,a,l);if(k&&k.status!==404)return k;const N=await e.authDiscoveryHandler?.(o);return N?(await k?.body?.cancel(),N):k??new Response("Not found",{status:404})};return{async fetch(o,a,l){e.passThroughOnException&&l.passThroughOnException?.(),fr(a),y(a);const u=ao(o,de);if(u)return u;const p=io(o,de);if(p)return Ge(p,o,de);try{const _=await wr(o,a,l);return Ge(_,o,de)}catch(_){return Ge(Ot(_),o,de)}finally{Tt(e.observability,nn(l))}},async queue(o,a,l){await ft(`queue:${Za(o)}`,l,async u=>{const p=e.liveStreams===!1?Vt():{publish:(_,v,k)=>se(La,_,v,k,"trusted")};await e.queue?.(o,a,l,{traceparent:u},p,e.queueFetchImpl)})},async scheduled(o,a,l){await ft(`cron:${o.cron}`,l,async u=>{await pt(o,a,l,u)})},serverQuery:ar}},fi=e=>Un(e),pi=e=>typeof e=="function"?{fetch:e}:e,mi=e=>!!e.backupCron||Object.keys(e.crons??{}).length>0||Object.keys(e.cronJobs??{}).length>0,wi=e=>typeof e!="object"?{}:{...typeof e.email=="function"?{email:e.email}:{},...typeof e.queue=="function"?{queue:e.queue}:{},...typeof e.scheduled=="function"?{scheduled:e.scheduled}:{}},$i=(e,t)=>{const n=pi(e),{email:r,queue:s,scheduled:i}=wi(e),d=h=>{const g={...fi({...h,httpRouter:n})};return i!==void 0&&!mi(h)&&(g.scheduled=async(A,S,P)=>{await i(A,S,P)}),s!==void 0&&h.queue===void 0&&(g.queue=async(A,S,P)=>{await s(A,S,P)}),r!==void 0&&(g.email=async(A,S,P)=>{await r(A,S,P)}),g};if(typeof t!="function")return d(t);const f=t;return{fetch:(h,m,g)=>d(f(m)).fetch(h,m,g),queue:(h,m,g)=>d(f(m)).queue?.(h,m,g)??Promise.resolve(),scheduled:(h,m,g)=>d(f(m)).scheduled(h,m,g),serverQuery:(h,m,g,A,S)=>d(f(m)).serverQuery(h,m,g,A,S),...r===void 0?{}:{email:(h,m,g)=>d(f(m)).email?.(h,m,g)??Promise.resolve()}}},gi=(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}},Fi=(e={})=>(t,n,r)=>Un(gi(e,n)).fetch(t,n,r??Sr),Ki=e=>e;export{nt as COPY_AUTH_TO_JURISDICTION_OP,Ct as GET_AUTH_AUDIT_LOG_OP,Sr as NOOP_EXECUTION_CONTEXT,En as PURGE_UNPINNED_AUTH_OP,Wi as composeIdentityResolvers,fi as composeWorker,Fi as createLunoraHandler,Un as createWorker,Ki as defineRpcEnvelope,ii as probeRelayCount,gi as resolveLunoraOptions,zi as routeIdentityResolvers,$i as withFrameworkWorker};
|
|
6
|
+
`)}}return g.length>0&&S(g),{errors:o,globalRows:s,perShard:i,received:d}},Ts=e=>e.flatMap(t=>t.error?[{message:t.error.message,shardKey:t.shardKey,timedOut:t.error.timedOut}]:[]),$t=(e,t)=>{for(const[n,o]of Object.entries(t.inserted))e.inserted[n]=(e.inserted[n]??0)+o;for(const n of t.errors)e.errors.push({...n});e.conflicts+=t.conflicts},vs=async(e,t,n,o,s)=>{const i=t.defaultShardKey??"__root__",{errors:d,globalRows:f,perShard:h,received:m}=await Ss(e,t,i),g={conflicts:0,errors:d,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=await n.orchestrateImport(s,{batches:[...h.values()],headers:o});$t(g,S),g.failed.push(...Ts(S.shards))}if(f.length>0)if(t.importGlobals){const S=f[0]?.line??1,P=await t.importGlobals({rows:f,startLine:S});$t(g,P)}else for(const S of f)g.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:g.conflicts,errors:g.errors,failed:g.failed,inserted:g.inserted,received:m,...A.length>0?{warnings:A}:{}}},Os=Object.freeze({edges:[],nodes:[],modules:[],unresolved:[],version:1}),Be=e=>typeof e=="object"&&e!==null?e:{},vn=e=>{const t=Be(e)._meta??{};if(t.sensitive===!0)return!0;const n=Array.isArray(t.members)?t.members:[],o=typeof t.shape=="object"&&t.shape!==null?Object.values(t.shape):[];return[t.inner,t.keyValidator,t.valueValidator,...n,...o].some(s=>typeof s=="object"&&s!==null&&vn(s))},ze=e=>typeof e.kind=="string"?e.kind:"unknown",Is=(e,t)=>{let n=Be(t),o=!1;ze(n)==="optional"&&(o=!0,n=Be(n._meta?.inner));const s=ze(n),i=n._meta??{},d={kind:s,name:e,optional:o};if(vn(t)&&(d.sensitive=!0),s==="id"&&typeof i.tableName=="string"&&(d.table=i.tableName),s==="array"){const f=ze(Be(i.inner));f!=="unknown"&&(d.element=f)}return d},Ps=e=>typeof e!="object"||e===null?[]:Object.entries(e).map(([t,n])=>Is(t,n)).toSorted((t,n)=>t.name.localeCompare(n.name)),ks="/_lunora/admin/functions",Ds="/_lunora/admin/cron-jobs",Ns="/_lunora/admin/architecture",Us="/_lunora/admin/openapi",Cs="/_lunora/admin/openrpc",Bs="/_lunora/admin/global/tables",xs="/_lunora/admin/global/table",Hs="/_lunora/admin/global/facet",Ft=e=>{if(e===void 0||e==="")return;let t;try{t=Ze(JSON.parse(e))}catch{return}if(!Array.isArray(t))return;const n=t.flatMap(o=>{if(typeof o!="object"||o===null||typeof o.column!="string")return[];const{column:s,value:i}=o;return[{column:s,value:i}]});return n.length===0?void 0:n},Ls=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:{}}),js=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"}),Ms=e=>{const{assertAdmin:t,options:n,parsePaging:o,queryParameter:s,requireAdminOption:i}=e,d=w=>{M(w,"GET","Functions");const y=i(w,n.functions,{code:"FUNCTIONS_NOT_CONFIGURED",message:"functions endpoint requires a `functions` registry on the worker"}),b=Object.entries(y).flatMap(([T,I])=>I.visibility==="internal"||I.kind==="stream"?[]:[{args:[...I.argumentDescriptors??Ps(I.args)],kind:I.kind,path:T}]).toSorted((T,I)=>T.path.localeCompare(I.path));return Response.json({functions:b},{headers:{"content-type":"application/json"},status:200})},f=w=>{M(w,"GET","Cron-jobs");const y=i(w,n.cronJobs,{code:"CRON_JOBS_NOT_CONFIGURED",message:"cron-jobs endpoint requires a `cronJobs` map on the worker"}),b=Object.entries(y).flatMap(([T,I])=>I.map(E=>({args:E.args,cron:T,functionPath:E.functionPath,name:E.name,shardKey:E.shardKey,workflow:E.workflow}))).toSorted((T,I)=>T.name.localeCompare(I.name));return Response.json({jobs:b},{headers:{"content-type":"application/json"},status:200})},h=w=>(M(w,"GET","Architecture"),t(w),Response.json(n.architecture??Os,{headers:{"content-type":"application/json"},status:200})),m=w=>(M(w,"GET","OpenAPI"),t(w),Response.json(n.openApiSpec??Ls,{headers:{"content-type":"application/json"},status:200})),g=w=>(M(w,"GET","OpenRPC"),t(w),Response.json(n.openRpcSpec??js,{headers:{"content-type":"application/json"},status:200})),A=async w=>{M(w,"GET","Global-tables");const y=i(w,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 w=>{M(w,"GET","Global-table");const y=i(w,n.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),b=new URL(w.url),T=s(b,"table");if(T===void 0)throw new c("Global-table endpoint requires a `table` query param",{code:"BAD_REQUEST",status:400});const I=await y.readTablePage({...o(w),filters:Ft(s(b,"filters")),table:T});return Response.json(I,{headers:{"content-type":"application/json"},status:200})},P=async w=>{M(w,"GET","Global-facet");const y=i(w,n.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),b=new URL(w.url),T=s(b,"table"),I=s(b,"column");if(T===void 0||I===void 0)throw new c("Global-facet endpoint requires `table` and `column` query params",{code:"BAD_REQUEST",status:400});const E=s(b,"limit"),L=E===void 0?void 0:Number(E),j=await y.facetColumn({column:I,filters:Ft(s(b,"filters")),limit:L!==void 0&&Number.isFinite(L)?L:void 0,table:T});return Response.json(j,{headers:{"content-type":"application/json"},status:200})};return{[Ds]:f,[ks]:d,[Hs]:P,[xs]:S,[Bs]:A,[Ns]:h,[Us]:m,[Cs]:g}},$s="/_lunora/admin/kv/namespaces",Fs="/_lunora/admin/kv/keys",On="/_lunora/admin/kv/value",In=32*1048576,Kt=60,Ks=e=>{const{readJsonBody:t,requireAdminOption:n}=e,o=w=>n(w,e.kvIntrospector,{code:"KV_NOT_CONFIGURED",message:"KV endpoints require a `kvIntrospector` on the worker"}),s=w=>Response.json(w,{headers:{"content-type":"application/json"},status:200}),i=(w,y)=>{const b=new URL(w.url),T=b.searchParams.get("namespace")??"",I=b.searchParams.get("key")??"";if(T==="")throw new c(`KV-value ${y} request requires a \`namespace\` query parameter`,{code:"BAD_REQUEST",status:400});if(I==="")throw new c(`KV-value ${y} request requires a \`key\` query parameter`,{code:"BAD_REQUEST",status:400});return{key:I,namespace:T}},d=async(w,y)=>{if(!(await w.listNamespaces()).some(T=>T.binding===y))throw new c(`Unknown KV namespace binding \`${y}\``,{code:"NOT_FOUND",status:404})},f=async w=>(M(w,"GET","KV-namespaces"),s({namespaces:await o(w).listNamespaces()})),h=async w=>{M(w,"GET","KV-keys");const y=o(w),b=new URL(w.url),T=b.searchParams.get("namespace")??"";if(T==="")throw new c("KV-keys request requires a `namespace` query parameter",{code:"BAD_REQUEST",status:400});const I=b.searchParams.get("prefix")??void 0,E=b.searchParams.get("cursor")??void 0,L=b.searchParams.get("limit"),j=L===null?void 0:Number.parseInt(L,10);if(j!==void 0&&(!Number.isInteger(j)||j<1))throw new c("KV-keys `limit` must be a positive integer",{code:"BAD_REQUEST",status:400});const C=j===void 0?void 0:Math.min(j,1e3);return await d(y,T),s(await y.listKeys({cursor:E,limit:C,namespace:T,prefix:I}))},S={DELETE:async w=>{const y=o(w),b=i(w,"DELETE");return await d(y,b.namespace),await y.deleteKey(b),s({deleted:!0})},GET:async w=>{const y=o(w),b=i(w,"GET");return await d(y,b.namespace),s(await y.getValue(b))},PUT:async w=>{const y=o(w),b=await t(w,In);if(typeof b.namespace!="string"||b.namespace==="")throw new c("KV-value PUT request requires a `namespace` string",{code:"BAD_REQUEST",status:400});if(typeof b.key!="string"||b.key==="")throw new c("KV-value PUT request requires a `key` string",{code:"BAD_REQUEST",status:400});if(typeof b.value!="string")throw new c("KV-value PUT request requires a `value` string",{code:"BAD_REQUEST",status:400});if(b.expirationTtl!==void 0&&(typeof b.expirationTtl!="number"||!Number.isInteger(b.expirationTtl)||b.expirationTtl<Kt))throw new c("KV-value PUT `expirationTtl` must be an integer ≥ 60",{code:"BAD_REQUEST",status:400});const T=Math.floor(Date.now()/1e3)+Kt;if(b.expiration!==void 0&&(typeof b.expiration!="number"||!Number.isInteger(b.expiration)||b.expiration<T))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 d(y,b.namespace),await y.putValue({expiration:b.expiration,expirationTtl:b.expirationTtl,key:b.key,metadata:b.metadata,namespace:b.namespace,value:b.value}),s({ok:!0})}},P=w=>{const y=S[w.method];if(!y)throw new c("KV-value endpoint requires GET, PUT, or DELETE",{code:"METHOD_NOT_ALLOWED",status:405});return y(w)};return{[$s]:f,[Fs]:h,[On]:P}},Gs="/_lunora/migrate",Qs="/_lunora/admin/pitr",Ws="/_lunora/admin/rank",zs="/_lunora/admin/rankpage",Vs="/_lunora/admin/shard-registry/prune",Js="/_lunora/admin/shard-traffic",Ys=new Set(["__lunora_admin__:migrationStatus","__lunora_admin__:runMigration"]),qs=new Set(["__lunora_admin__:getPitrBookmark","__lunora_admin__:pitrRestore"]),Xs=async e=>{const n=await oe(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"||!Ys.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}},Zs=async e=>{const n=await oe(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}},ea=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}},ta=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})},na=async e=>{const n=await oe(e,"Rank page")??{};ta(n);const o=ea(n.directions);return{cursor:typeof n.cursor=="string"?n.cursor:null,directions:o,index:n.index,partitionKey:typeof n.partitionKey=="string"?n.partitionKey:void 0,table:n.table,take:typeof n.take=="number"?n.take:void 0}},ra=async e=>{const n=await oe(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}},oa=async e=>{const n=await oe(e,"Shard-registry prune")??{};if(n.tables!==void 0&&!(Array.isArray(n.tables)&&n.tables.every(o=>typeof o=="string")))throw new c("Shard-registry prune `tables` must be an array of table names",{code:"BAD_REQUEST",status:400});return{dryRun:n.dryRun===!0,tables:n.tables}},sa=async e=>{const n=await ne(e);if(typeof n.functionPath!="string"||!qs.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}},aa=e=>{const{defaultShard:t,forwardToShard:n,isAdmin:o,queryCoordinator:s,resolveForwardContext:i,shardDO:d,shardedTables:f}=e,h=(y,b)=>{if(y.method!=="POST")throw new c(`${b} endpoint requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});if(!o(y))throw new c("Admin auth required",{code:"FORBIDDEN",status:403})},m=async(y,b)=>{h(y,"Migration");const T=await Xs(y),{headers:I}=await i(y,b),E=await s.orchestrateMigration(d,{args:T.args,defaultShardKey:t,functionPath:T.functionPath,headers:I,table:T.table});return Response.json(E,{headers:{"content-type":"application/json"},status:200})},g=async(y,b)=>{h(y,"Rank");const T=await Zs(y),{headers:I}=await i(y,b),E=await s.orchestrateRank(d,{headers:I,index:T.index,partitionKey:T.partitionKey,rowId:T.rowId,sortValues:T.sortValues,table:T.table});return Response.json(E,{headers:{"content-type":"application/json"},status:200})},A=async(y,b)=>{h(y,"Rank page");const T=await na(y),{headers:I}=await i(y,b),E=await s.orchestrateRankPage(d,{...T,headers:I});return Response.json(E,{headers:{"content-type":"application/json"},status:200})},S=async(y,b)=>{h(y,"Shard-traffic");const T=await ra(y),{headers:I}=await i(y,b),E=await s.orchestrateShardTraffic(d,{headers:I,table:T.table});return Response.json(E,{headers:{"content-type":"application/json"},status:200})},P=async(y,b)=>{h(y,"Shard-registry prune");const T=await oa(y),I=f(),E=(T.tables??[]).filter(C=>!I.includes(C));if(E.length>0)throw new c(`Shard-registry prune names tables that are not \`.shardBy()\`: ${E.join(", ")}`,{code:"BAD_REQUEST",status:400});const{headers:L}=await i(y,b),j=await so(s.registry,d,{dryRun:T.dryRun,headers:L,tables:T.tables??I});return Response.json(j,{status:j.failed.length>0?207:200})},w=async(y,b)=>{if(M(y,"POST","PITR"),!o(y))throw new c("admin PITR endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403});const T=await sa(y),{headers:I}=await i(y,b),E=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:T.args,functionPath:T.functionPath}),headers:I,method:"POST"});return n(d,T.shardKey??t,E)};return{[Gs]:m,[Qs]:w,[Ws]:g,[zs]:A,[Vs]:P,[Js]:S}},ia=1,ca=0,da=32,ua=512,la=/^[a-z][\d_a-z*/-]{0,255}(?:@[a-z][\d_a-z*/-]{0,13})?=[\u0020-\u002B\u002D-\u003C\u003E-\u007E]{1,256}$/,ha=e=>{if(e==null)return;const t=e.trim();if(t.length===0||t.length>ua)return;const n=t.split(",");if(!(n.length>da)){for(const o of n)if(!la.test(o.trim()))return;return t}},fa=e=>{const t=Dr(e.headers.get("traceparent"));if(t===void 0)return;const n=ha(e.headers.get("tracestate"));return{parentSpanId:t.parentSpanId,sampled:t.sampled,traceId:t.traceId,...n===void 0?{}:{traceState:n}}},Gt=(e,t={})=>{const n=fa(e),o=t.trustInbound===!0?n:void 0,s=be(8),i=o?.traceId??be(16),d=xr(t.sampling,o===void 0?s:i),{rayId:f}=t,h=d.isTraced&&(o===void 0||o.sampled);return{decision:d,ignoredUpstream:n!==void 0&&o===void 0,trace:{sampled:h,spanId:s,traceFlags:h?ia:ca,traceId:i,...o?.parentSpanId===void 0?{}:{parentSpanId:o.parentSpanId},...o?.traceState===void 0?{}:{traceState:o.traceState},...f===void 0?{}:{rayId:f}}}},Qt=(e,t)=>{t.traceparent=un(e.traceId,e.spanId,e.sampled),e.traceState!==void 0&&(t.tracestate=e.traceState),e.rayId!==void 0&&(t[bo]=e.rayId)},pa=(e,t)=>{let n;return()=>{if(n===void 0){const o=Br(e),s=t===void 0?void 0:t.cf;n=Nr(Cr(o),Ur(o,s))}return n}},ma="/_lunora/admin/scheduled",wa="/_lunora/admin/scheduled/status",ga="/_lunora/admin/scheduled/ws",ya="/_lunora/admin/scheduled/cancel",ba="/_lunora/admin/scheduled/dead",_a="/_lunora/admin/scheduled/dead/retry",Ra="/_lunora/admin/scheduled/dead/cancel",Ea="/_lunora/admin/scheduled/pool/release",Aa=e=>{const{checkWsAdmin:t,requireSchedulerNamespace:n,resolveSchedulerStub:o,schedulerInstanceName:s}=e,i=(m,g)=>A=>{if(A.method!=="GET")throw new c(`${g} endpoint requires GET`,{code:"METHOD_NOT_ALLOWED",status:405});const S=new URL(A.url).searchParams.get("cursor"),P=S===null||S===""?"":`?cursor=${encodeURIComponent(S)}`;return o(A).fetch(new Request(`https://scheduler.internal${m}${P}`,{method:"GET"}))},d=(m,g,A=g)=>async S=>{if(S.method!=="POST")throw new c(`${A} requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});const P=o(S),w=await oe(S,g);if(typeof w?.id!="string"||w.id==="")throw new c(`${g} requires a string \`id\``,{code:"BAD_REQUEST",status:400});return P.fetch(new Request(`https://scheduler.internal${m}`,{body:JSON.stringify({id:w.id}),headers:{"content-type":"application/json"},method:"POST"}))},f=async m=>{if(m.method!=="POST")throw new c("Scheduled pool-release endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const g=o(m),A=await oe(m,"Scheduled pool-release");if(typeof A?.pool!="string"||A.pool==="")throw new c("Scheduled pool-release requires a string `pool`",{code:"BAD_REQUEST",status:400});const S=typeof A.id=="string"&&A.id!==""?A.id:void 0;return g.fetch(new Request("https://scheduler.internal/complete",{body:JSON.stringify(S===void 0?{pool:A.pool}:{id:S,pool:A.pool}),headers:{"content-type":"application/json"},method:"POST"}))},h=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 g=n();return _e(g,s).fetch(new Request("https://scheduler.internal/ws",{headers:{Upgrade:"websocket"}}))};return{[ya]:d("/cancel","Scheduled-cancel","Scheduled-cancel endpoint"),[Ra]:d("/dead/cancel","Scheduled dead-letter action"),[ba]:i("/dead","Scheduled dead-letter"),[_a]:d("/dead/retry","Scheduled dead-letter action"),[ma]:i("/list","Scheduled-list"),[Ea]:f,[wa]:i("/status","Scheduler-status"),[ga]:h}},Sa="/_lunora/scheduled",Pn="/_lunora/queue",kn=16*1048576,Ta=e=>{const{assertAdmin:t,dispatchScheduled:n,queueHandler:o}=e,s=async(d,f,h)=>{if(t(d),d.method!=="POST")throw new c("scheduled tick endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const m=await oe(d,"Scheduled tick"),g=typeof m?.cron=="string"?m.cron:"";if(g==="")throw new c("scheduled tick requires a `cron` expression",{code:"BAD_REQUEST",status:400});return await n({cron:g,noRetry:()=>{},scheduledTime:Date.now()},f,h),Response.json({cron:g,ok:!0})},i=async(d,f,h)=>{if(t(d),d.method!=="POST")throw new c("queue dispatch endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});if(!o)throw new c("no queueHandler configured",{code:"BAD_REQUEST",status:400});const m=await oe(d,"Queue dispatch",kn);if(!Array.isArray(m?.messages))throw new c("queue dispatch requires a `messages` array",{code:"BAD_REQUEST",status:400});const g=typeof m.queue=="string"?m.queue:"",A=m.messages.filter(P=>typeof P=="object"&&P!==null&&typeof P.id=="string").map(P=>({body:P.body,id:P.id})),S=await o({messages:A,queue:g},f,h);return Response.json({retry:S?.retry??[]})};return{[Pn]:i,[Sa]:s}},va=(e,...t)=>{let n=e.cf;for(const o of t){if(typeof n!="object"||n===null)return;n=n[o]}return typeof n=="string"?n:void 0},rt={mtls:e=>va(e,"tlsClientAuth","certVerified")==="SUCCESS"},Oa=e=>e===void 0||e===!1?()=>!1:e===!0?()=>!0:typeof e=="function"?e:(Object.hasOwn(rt,e)?rt[e]:void 0)??(()=>!1),Ia=e=>typeof e=="string"&&Object.hasOwn(rt,e),Pa=e=>{const t=Ia(e)?e:void 0;if(e!==void 0&&t===void 0)return()=>{};let n=!1;return o=>{n||t!==void 0&&o.cf!==void 0||(n=!0,console.warn(t===void 0?'[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.':`[lunora] \`trustInboundTraceContext: "${t}"\` cannot be satisfied on this host: the request carries no platform-injected \`cf\` metadata, which is what that signal reads, so every inbound \`traceparent\` is ignored and this request starts a new trace. Off Cloudflare, trust the upstream some other way — \`trustInboundTraceContext: true\` when nothing untrusted can reach this worker, or a predicate that verifies whatever your own front door sets. Set it to \`false\` to keep this behaviour and silence this message.`))}},ka="/_lunora/admin/vector/indexes",Da="/_lunora/admin/vector/query",Na=e=>{const{readJsonBody:t,requireAdminOption:n}=e,o=async i=>{M(i,"GET","Vector-indexes");const d=n(i,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});return Response.json({indexes:await d.listIndexes()},{headers:{"content-type":"application/json"},status:200})},s=async i=>{M(i,"POST","Vector-query");const d=n(i,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});if(d.queryIndex===void 0)throw new c("vector index querying is not enabled on this worker",{code:"VECTOR_QUERY_UNSUPPORTED",status:400});const h=await t(i);if(typeof h.name!="string"||h.name==="")throw new c("Vector-query request requires a `name` string",{code:"BAD_REQUEST",status:400});if(typeof h.text!="string"||h.text==="")throw new c("Vector-query request requires a `text` string",{code:"BAD_REQUEST",status:400});if(h.topK!==void 0&&(typeof h.topK!="number"||!Number.isInteger(h.topK)||h.topK<1))throw new c("Vector-query `topK` must be a positive integer",{code:"BAD_REQUEST",status:400});const m=await d.queryIndex({name:h.name,text:h.text,topK:h.topK});return Response.json(m,{headers:{"content-type":"application/json"},status:200})};return{[ka]:o,[Da]:s}},Ua="/_lunora/admin/workflows/instances",Ca="/_lunora/admin/workflows/instance",Ba="/_lunora/admin/workflows/status",xa={complete:!0,errored:!0,paused:!0,queued:!0,rollingBack:!0,running:!0,terminated:!0,unknown:!0,waiting:!0,waitingForPause:!0},Ha=e=>e!==null&&Object.hasOwn(xa,e)?e:void 0,Wt=(e,t)=>{const n=e.searchParams.get(t);if(n===null)return;const o=Number(n);return Number.isInteger(o)&&o>0?o:void 0},Ve=(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},zt=()=>{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})},La=e=>{const{assertAdmin:t,resolveWorkflowsClient:n}=e,o=async(d,f,h)=>{M(d,"GET","Workflows instances"),t(d);const m=n(f);if(!m)return Response.json({configured:!1,instances:[],page:1,perPage:0,totalCount:0});const g=Ve(h,"name"),A=Ha(h.searchParams.get("status"));return Response.json(await m.listInstances({page:Wt(h,"page"),perPage:Wt(h,"perPage"),status:A,workflowName:g}))},s=async(d,f,h)=>{M(d,"GET","Workflows instance"),t(d);const m=n(f);return m?Response.json(await m.getInstance({instanceId:Ve(h,"id"),workflowName:Ve(h,"name")})):zt()},i=async(d,f)=>{M(d,"POST","Workflows status"),t(d);const h=n(f);if(!h)return zt();const m=await oe(d,"Workflows status");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:g}=m;if(g!=="pause"&&g!=="restart"&&g!=="resume"&&g!=="terminate")throw new c("Workflows status action must be one of: pause, restart, resume, terminate",{code:"BAD_REQUEST",status:400});return Response.json(await h.setInstanceStatus({action:g,instanceId:m.id,workflowName:m.name}))};return{[Ca]:s,[Ua]:o,[Ba]:i}},ja={[On]:In,[Pn]:kn,[Jr]:Vr},Ma="https://queue.lunora.internal",Vt=()=>({publish:()=>Promise.reject(new c("ctx.live.publish is unavailable: this worker does not serve live streams",{code:"LIVE_STREAMS_UNSUPPORTED",status:501}))}),$a=async(e,t)=>{const n=new c(`ctx.live.publish to "${t}" failed with HTTP ${String(e.status)}`,{code:"INTERNAL",status:e.status>=400?e.status:500});let o;try{o=await e.json()}catch{return n}const s=o?.error;return typeof s?.code!="string"||e.status<400?n:new c(typeof s.message=="string"?s.message:`ctx.live.publish to "${t}" was refused`,{code:s.code,status:e.status})},Jt="/_lunora/rpc",Fa="/_lunora/rpc-batch",Ka="/_lunora/ws",Te=(e,t,n)=>({resourceAttributes:pa(e,t),...n===void 0?{}:{waitUntil:n}}),Je=e=>e?.waitUntil?{waitUntil:t=>e.waitUntil?.(t)}:{},Yt=e=>({spanId:e.spanId,traceFlags:e.traceFlags,traceId:e.traceId,...e.parentSpanId===void 0?{}:{parentSpanId:e.parentSpanId}}),Ye=e=>{const{method:t}=e,n=e.headers.get("user-agent")??void 0,o=Ro(e.headers.get(yo)),s=o===void 0?{}:{rayId:o};let i;try{i=new URL(e.url)}catch{return{method:t,...s,userAgent:n}}const d=i.port===""?void 0:Number(i.port);return{host:i.hostname,method:t,path:i.pathname,port:Number.isNaN(d)?void 0:d,...s,scheme:i.protocol.replace(":",""),userAgent:n}},qt="/_lunora/voice/",Ga="/_lunora/admin/cron-jobs/run",Qa="/_lunora/admin/ws-token",Wa="/_lunora/admin/",xe="/_lunora/",za="/_lunora/migrate",Va="/_lunora/status",Ja=e=>e.startsWith(Wa)||e===za,ke=e=>{if(Ho(e))throw new c("`__lunora_relation__:*` is a fan-out-only reserved RPC and cannot be dispatched to a single shard",{code:"FORBIDDEN",status:403})},De=async e=>await e===!0,Xt=(e,t)=>{const n=e.headers.get(St);if(n===null)return;const o=kr(n);if(o===void 0)throw new c(`malformed ${St} header`,{code:"BAD_REQUEST",status:400});if(o.subject!==(t?.userId??null))throw new c("the session changed since this write was queued",{code:"IDENTITY_MISMATCH",status:409})},Zt="/api/auth",Ya="__lunora_admin__:recordAuthEvent",en="__lunora_admin__:listPushSubscriptions",qa=["/sign-in","/sign-up","/callback"],Xa=(e,t)=>{const n=t.endsWith("/")?t.slice(0,-1):t;if(!e.startsWith(`${n}/`))return!1;const o=e.slice(n.length);return qa.some(s=>o===s||o.startsWith(`${s}/`))},tn=(e,t)=>{const n=t.endsWith("/")?t.slice(0,-1):t;return e===n||e.startsWith(`${n}/`)},Ne=(e,t,n,o)=>{const s=Rr(n),i=s?n.code:"INTERNAL_SERVER_ERROR",d=s?n.status:500,{message:f,name:h,stack:m}=Sr(n),g=Tr(n,{capped:!1});return{durationMs:t,error:{code:i,message:f,name:h,status:d,...m===void 0?{}:{stack:m},...g===void 0?{}:{internal:g}},functionPath:e,ok:!1,...o.fanOut?{fanOut:{failed:0,shards:0,table:o.fanOut.table}}:{},...o.shardKey?{shardKey:o.shardKey}:{}}},Dn=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},Nn=({identity:e})=>e!==null&&Or(Dn(e)),Za=e=>{if(Nn(e))throw new c("authentication token expired",{code:"TOKEN_EXPIRED",status:401});return e},ei=e=>{if(!Nn(e))return e;const t={...e.headers};return delete t["x-lunora-identity"],delete t["x-lunora-identity-exp"],delete t["x-lunora-userid"],{claims:null,headers:t,identity:null,userId:null}},nn=e=>e.waitUntil?{waitUntil:t=>{e.waitUntil?.(t)}}:void 0,ti=e=>{const t=e?.queue;return typeof t=="string"&&t.length>0?t:"unknown"},ot=new WeakMap,ni=async(e,t,n,o,s=ot.get(e))=>{const i={"content-type":"application/json"},d=e.headers.get("authorization"),f=e.headers.get("cookie"),h=e.headers.get("x-d1-bookmark"),m=e.headers.get("x-lunora-mutation-id"),g=e.headers.get("x-lunora-client-id"),A=e.headers.get("x-lunora-client-seq"),S=e.headers.get("x-lunora-base-seq");d&&(i.authorization=d),f&&(i.cookie=f),h&&(i["x-d1-bookmark"]=h),m&&(i["x-lunora-mutation-id"]=m),g&&(i["x-lunora-client-id"]=g),A&&(i["x-lunora-client-seq"]=A),S&&(i["x-lunora-base-seq"]=S);const P=Fr(e.headers,o);if(P&&(i["x-lunora-client-ip"]=P),i["x-lunora-origin"]=new URL(e.url).origin,!n)return{claims:null,headers:i,identity:null,userId:null};const w=await n(e,t,s);if(!w||typeof w.userId!="string"||w.userId.length===0)return{claims:null,headers:i,identity:null,userId:null};i["x-lunora-userid"]=Ir(w.userId);const y=Dn(w);y!==void 0&&(i["x-lunora-identity-exp"]=String(y));const{userId:b,...T}=w,I=Object.keys(T).length>0?T:null;return I&&(i["x-lunora-identity"]=Pr(I)),{claims:I,headers:i,identity:w,userId:b}},ri=new Set(["concat","first","groupBy","max","min","rank","sum","topK"]),oi=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"||!ri.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},si=(e,t)=>{e?.LUNORA_DEBUG_RPC&&console.warn(`[lunora:rpc] ${t.fanOut?"fan-out":`shard=${t.shardKey??"(root)"}`} ${t.functionPath}`)},qe=(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}},ai=async e=>{const t=await fn(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 o=n;if(o.args!==void 0&&hn(o.args,"RPC"),o.shardKey!==void 0&&typeof o.shardKey!="string")throw new c("RPC `shardKey` must be a string",{code:"BAD_REQUEST",status:400});const s=n,i=oi(s.fanOut),d=s.args??{};if(i&&s.functionPath.startsWith("__lunora_relation__:")){const f=d.table;if(typeof f=="string"&&f!==i.table)throw new c("RPC `args.table` must match the authorized `fanOut.table` for a relation fan-out",{code:"BAD_REQUEST",status:400});d.table=i.table}return{args:d,fanOut:i,functionPath:s.functionPath,shardKey:s.shardKey}},Ue=new Map,ii=5e3,ci=4096,di=async(e,t)=>{const n=Date.now(),o=Ue.get(t);if(o!==void 0&&o.expiresMs>n)return o.relayCount;o!==void 0&&Ue.delete(t);let s=0;try{const i=await _e(e,t).fetch(new Request("https://shard.internal/_lunora/route"));if(i.ok){const d=await i.json();typeof d.relayCount=="number"&&d.relayCount>0&&(s=Math.floor(d.relayCount))}}catch{s=0}return an(Ue,ci),Ue.set(t,{expiresMs:n+ii,relayCount:s}),s},rn=(e,t)=>{if(!(e===null||typeof e!="object"))return Object.entries(e).find(([,n])=>n===t)?.[0]},Ce=(e,t,n)=>new Request("https://shard.internal/rpc",{body:JSON.stringify({args:t,functionPath:e}),headers:n,method:"POST"}),ui=["x-lunora-userid","x-lunora-identity","x-lunora-identity-exp","x-lunora-client-ip"],li=(e,t)=>{for(const n of ui){e.delete(n);const o=t[n];o!==void 0&&e.set(n,o)}},Xe=e=>e.headers.get("Upgrade")?.toLowerCase()==="websocket",on=(e,t)=>{const n=new Headers(e.headers),o=[...n.keys()];for(const s of o)s.startsWith("x-lunora-")&&n.delete(s);return li(n,t),n},sn=async(e,t)=>{if(!t||t.length===0)return!1;const n=new URL(e.url).searchParams.get("token");return n===null?!1:Qo(t,n)},hi=(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 no(`d1:${e}`,t);if(typeof n.list=="function"&&typeof n.head=="function"&&typeof n.createMultipartUpload=="function")return Fe(`r2:${e}`,!0);if(typeof n.send=="function"&&typeof n.sendBatch=="function"&&typeof n.get!="function")return Fe(`queue:${e}`,!0);if(typeof n.connectionString=="string")return Fe(`hyperdrive:${e}`,!0)},fi=e=>{for(const t of Object.keys(e??{}))if(t.slice(t.indexOf(" ")+1).startsWith(xe))throw new c(`route "${t}" is under the reserved ${xe} prefix, which the framework owns. App routes registered there shadow the internal endpoint AND its admin gate — pick a path outside the prefix.`,{code:"MISCONFIGURED",status:500})},pi=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})},Un=e=>{pi(e);const t=Oa(e.trustInboundTraceContext),n=Pa(e.trustInboundTraceContext),o=e.defaultShardKey??"__root__",s=e.queryCoordinator??ao({registry:io(e.resolveTableSharding,o)}),i=ro(e.resolveIdentity,e.identity),d=Ke(e.shardDO,e.jurisdiction),f=e.schedulerDO===void 0?void 0:Ke(e.schedulerDO,e.jurisdiction),h=e.voiceAgents===void 0?void 0:Object.fromEntries(Object.entries(e.voiceAgents).map(([r,a])=>[r,Ke(a,e.jurisdiction)]));let m=!1;const g=r=>{if(r===void 0||e.jurisdiction===void 0)return r;m||(m=!0,console.warn(`[lunora] jurisdiction "${e.jurisdiction}" pins placement, so region hints (\`shardRegion\`, replica and relay placement) are not sent. Residency wins.`))},A=async(r,a,l,u=e.shardRegion?.(a))=>_e(r,a,g(u)).fetch(l);let S;const P=()=>e.adminToken??S;let w;const y=r=>{const a=r??{};if(w??=rn(r,e.shardDO),S!==void 0||e.adminToken!==void 0)return;const l=a.LUNORA_ADMIN_TOKEN;typeof l=="string"&&l.length>0&&(S=l)},b=new WeakSet,T=r=>bn(r,P())||b.has(r),I=async r=>{if(!(e.adminGate===void 0||b.has(r)))try{await De(e.adminGate(r,ot.get(r)))&&b.add(r)}catch{}},E=async(r,a,l,u)=>{const p=await ni(r,a,l,e.trustedClientIpHeader,u);return e.functions!==void 0&&(p.headers[dn]=cn),p},L=async(r,a,l,u)=>Za(await E(r,a,l,u)),j=async(r,a)=>{const l=await E(r,a,e.resolveIdentity);if(b.has(r)&&l.headers.authorization===void 0){const u=P();u!==void 0&&(l.headers.authorization=`Bearer ${u}`)}return l};let C=!1,K=!1;const q=()=>{K||(K=!0,console.warn("[lunora] `replicaReads: true` has no effect without `functions` — read eligibility is decided from the function registry."))},V=r=>{if(!e.allowUnauthenticatedShardAccess){const a=r==="fan-out"?"authorizeFanOut":"authorizeShard";throw new c(`${r} access is default-denied: configure \`${a}\` on the worker, or set \`allowUnauthenticatedShardAccess: true\` to explicitly allow unauthenticated ${r} access (relying solely on per-row RLS).`,{code:r==="fan-out"?"FORBIDDEN_FANOUT":"FORBIDDEN_SHARD",status:403})}C||(C=!0,console.warn([`[lunora] SECURITY: serving ${r} 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("")))},G=async(r,a,l=!1)=>{if(a.includes(et)||a.includes(tt))throw new c("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403});if(!l)if(e.authorizeShard){if(!await De(e.authorizeShard({identity:r,shardKey:a})))throw new c("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else a!==o&&V("shard")},J=aa({defaultShard:o,forwardToShard:A,isAdmin:T,queryCoordinator:s,resolveForwardContext:j,shardDO:d,shardedTables:()=>(e.listSchemaTables?.()??[]).filter(r=>e.resolveTableSharding?.(r)?.mode.kind==="shardBy")}),se=async(r,a,l,u,p)=>{const{__lunoraLive:_,topic:v}=a,N=u?.shardKey??o;p==="trusted"?await G(null,N,!0):N!==o&&await G(p.identity,N);const k=await A(d,N,new Request(new URL(go,r),{body:JSON.stringify({data:ye(l??null),stream:_,topic:v}),headers:{"content-type":"application/json"},method:"POST"}));if(!k.ok)throw await $a(k,v)},W=async(r,a,l,u,p,_)=>{ke(r);const v=jo({forwardedIdentity:p,mutationId:u,traceparent:_});return A(d,l,Ce(r,a,v))},le=async(r,a,l,u,p)=>{const _=Fo(l.env,l.context?.exports,r,["create"]);if(_===void 0)throw new c(`${u} targets workflow "${r}", which is on neither ctx.exports nor env`,{code:"CRON_JOB_FAILED",status:500});if(ho(a))throw new c(`${u} params ${fo}`,{code:"BAD_REQUEST",status:400});try{await _.create(p===void 0?{params:a}:{id:p,params:a})}catch(v){if(!wo(v))throw v}},ae=async(r,a,l,u)=>{if(r.workflow){await le(r.workflow,r.args??{},{context:l,env:a},`cron job "${r.name}"`);return}if(r.functionPath===void 0)throw new c(`cron job "${r.name}" has neither a function target nor a workflow target`,{code:"CRON_JOB_FAILED",status:500});const p=await W(r.functionPath,r.args??{},r.shardKey??o,void 0,void 0,u);if(!p.ok)throw new c(`cron job "${r.name}" (${r.functionPath}) failed with shard status ${String(p.status)}`,{code:"CRON_JOB_FAILED",status:500})},z=r=>{if(!T(r))throw new c("admin endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403})},ie=(r,a,l)=>{if(z(r),a===void 0)throw new c(l.message,{code:l.code,status:400});return a},He=async(r,a,l,u,p,_)=>{const v=e.cronJobs?.[r];if(!v)return 0;for(const N of v)try{await ae(N,a,l,_)}catch(k){u.push(p(k))}return v.length},ce=async(r,a,l)=>{if(z(r),M(r,"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 u=await ne(r),p=typeof u.name=="string"?u.name:"";if(p==="")throw new c("cron-jobs run endpoint requires a job `name`",{code:"BAD_REQUEST",status:400});const _=Object.values(e.cronJobs).flat().find(v=>v.name===p);if(!_)throw new c(`no cron job named "${p}" is registered`,{code:"CRON_JOB_NOT_FOUND",status:404});return await ae(_,a,l),Response.json({name:p,ran:!0},{status:200})},dt=async r=>{const a=typeof r.pool=="string"&&r.pool.length>0?r.pool:void 0;if(!a||!f||typeof r.id!="string")return;const l=typeof r.instanceName=="string"&&r.instanceName.length>0?r.instanceName:"default";try{await _e(f,l).fetch(new Request("https://scheduler.internal/complete",{body:JSON.stringify({id:r.id,pool:a}),headers:{"content-type":"application/json"},method:"POST"}))}catch{}},Cn=async(r,a,l)=>{M(r,"POST","Scheduler dispatch");const u=await fn(r),p=a??{},_=typeof p.LUNORA_SCHEDULER_SECRET=="string"?p.LUNORA_SCHEDULER_SECRET:void 0,v=e.adminToken??(typeof p.LUNORA_ADMIN_TOKEN=="string"?p.LUNORA_ADMIN_TOKEN:void 0);if(!await Lo(r,u,{adminToken:v,schedulerSecret:_}))throw new c("Scheduler dispatch requires a valid signature or admin bearer",{code:"DISPATCH_UNAUTHENTICATED",status:403});let k;try{k=JSON.parse(u)}catch{throw new c("Scheduler dispatch body must be valid JSON",{code:"BAD_REQUEST",status:400})}const R=k??{},O=R.args??{},D=typeof R.id=="string"&&R.id.length>0?R.id:void 0;if(typeof R.workflow=="string"&&R.workflow.length>0)return await le(R.workflow,O,{context:l,env:a},"scheduled workflow",D),await dt(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 H=typeof R.shardKey=="string"&&R.shardKey.length>0?R.shardKey:o,$=Mo(r),x=await W(R.functionPath,O,H,D,$,r.headers.get("traceparent")??void 0);return await dt(R),x},Bn=Jo({assertAdmin:z,getReader:()=>e.authAuditReader}),xn=Yo({assertAdmin:z,getMove:()=>e.authJurisdictionMove}),Hn=async(r,a)=>{z(r);const l=e.notifySubscriptionStore;if(l===void 0)return Response.json({result:ye({subscriptions:[]})},{headers:{"content-type":"application/json"},status:200});const u=a?.kind,p=a?.userId,_=a?.limit,v=u==="fcm"||u==="web-push"?u:void 0,N=typeof p=="string"&&p!==""?p:void 0,k=typeof _=="number"&&Number.isFinite(_)?Math.trunc(_):0,R=k>0?Math.min(k,1e3):1e3,D=(await l.list({kind:v,limit:R,userId:N})).filter(H=>v!==void 0&&H.kind!==v?!1:N===void 0||(H.userId??null)===N).map(({keys:H,token:$,...x})=>x);return Response.json({result:ye({subscriptions:D})},{headers:{"content-type":"application/json"},status:200})},Ln=async(r,a)=>{if(!a.fanOut&&!(a.functionPath!==Ct&&a.functionPath!==en&&a.functionPath!==nt&&a.functionPath!==En))return await I(r),a.functionPath===Ct?Bn(r,a.args??{}):a.functionPath===en?Hn(r,a.args):xn(r,a.functionPath,a.args??{})},jn=Rs({applyGlobals:e.applyGlobals,assertAdmin:z,exportCursorStore:e.exportCursorStore,exportSinks:e.exportSinks,defaultShardKey:o,knownTables:()=>[...e.listSchemaTables?.()??[]],queryCoordinator:s,resolveForwardContext:j,shardDO:d,prepareExportRows:async(r,a)=>An(e,s,r,a,d),streamingImport:(r,a)=>vs(r,e,s,a,d),syncGlobals:e.syncGlobals}),Le=(r,a)=>{const l=r.searchParams.get(a);return l===null||l===""?void 0:l},je=r=>{const a=new URL(r.url),l=a.searchParams.get("limit"),u=a.searchParams.get("offset"),p=l===null?void 0:Number.parseInt(l,10),_=u===null?void 0:Number.parseInt(u,10);return{limit:p!==void 0&&Number.isFinite(p)&&p>=0?p:void 0,offset:_!==void 0&&Number.isFinite(_)&&_>=0?_:void 0}},ut=()=>{if(f===void 0)throw new c("scheduled endpoints require a `schedulerDO` namespace on the worker",{code:"SCHEDULER_NOT_CONFIGURED",status:400});return f},Mn=Aa({checkWsAdmin:async r=>T(r)||sn(r,P()),requireSchedulerNamespace:ut,resolveSchedulerStub:r=>(z(r),_e(ut(),e.schedulerInstanceName??"default")),schedulerInstanceName:e.schedulerInstanceName??"default"}),$n=La({assertAdmin:z,resolveWorkflowsClient:e.workflowsClient??(()=>{})}),Fn=zr({assertAdmin:z,parsePaging:je,queryParameter:Le,readBodyBytes:Mr,requireAdminOption:ie,storage:{storageBuckets:e.storageBuckets,storageDelete:e.storageDelete,storageDownload:e.storageDownload,storageList:e.storageList,storageSignedUrl:e.storageSignedUrl,storageUpload:e.storageUpload}}),Kn=us({options:e,readJsonBody:ne,requireAdminOption:ie}),Gn=Na({readJsonBody:ne,requireAdminOption:ie,vectorIntrospector:e.vectorIntrospector}),Qn=Ks({kvIntrospector:e.kvIntrospector,readJsonBody:ne,requireAdminOption:ie}),Wn=oo({logArchive:e.logArchive,readJsonBody:ne,requireAdminOption:ie}),zn=Ms({assertAdmin:z,options:{cronJobs:e.cronJobs,functions:e.functions,globalIntrospector:e.globalIntrospector,architecture:e.architecture,openApiSpec:e.openApiSpec,openRpcSpec:e.openRpcSpec},parsePaging:je,queryParameter:Le,requireAdminOption:ie}),Vn=r=>{const a=[],l=d??r?.SHARD;if(l!==void 0&&a.push(to("durable-object:default",l,o)),e.health?.disableBindingProbes!==!0)for(const[u,p]of Object.entries(r??{})){const _=hi(u,p);_!==void 0&&a.push(_)}for(const u of e.health?.probes??[])a.push(u);return a},Jn=eo({appName:e.health?.appName,appVersion:e.health?.appVersion,auth:e.health?.auth??"public",cacheTtlMs:e.health?.cacheTtlMs,isAdmin:T,resolveProbes:Vn}),Yn=r=>{const a=R=>"args"in R?{...R,args:Ze(R.args)}:R,l=e.schedulerInstanceName??"default",u=()=>_e(r,l),p=async(R,O)=>{const D=await u().fetch(new Request(`https://scheduler.internal${R}`,O));if(!D.ok)throw new c(`ctx.scheduler: SchedulerDO ${R} failed (${String(D.status)}): ${await D.text()}`,{code:"INTERNAL",status:500});return await D.json()},_=async(R,O)=>await p(R,{body:JSON.stringify(O),headers:{"content-type":"application/json"},method:"POST"}),v=R=>{const O=R;if(O==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 O.binding=="string"&&O.binding.length>0)return{workflow:O.binding};if(typeof O.__lunoraRef=="string")return{functionPath:O.__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})},N=async()=>(await po(async O=>p(O===void 0?"/list":`/list?cursor=${encodeURIComponent(O)}`,{method:"GET"}))).map(O=>a(O)),k=async(R,O,D={})=>{const H=v(O),{id:$}=await _("/schedule",{args:Ar("ctx.scheduler",String(H.functionPath??H.workflow),D),scheduledFor:Math.ceil(R),...H});return $};return{cancel:async R=>await _("/cancel",{id:R}),get:async R=>{const O=await p(`/get?id=${encodeURIComponent(R)}`,{method:"GET"});return O.record===void 0?null:a(O.record)},list:N,runAfter:async(R,O,D)=>{if(!Number.isFinite(R)||R<0)throw new c("ctx.scheduler.runAfter: `delayMs` must be a non-negative finite number",{code:"INVALID_INPUT",status:400});return await k(Date.now()+R,O,D)},runAt:async(R,O,D)=>{if(!Number.isFinite(R))throw new c("ctx.scheduler.runAt: `date` must be a non-negative finite number",{code:"INVALID_INPUT",status:400});return await k(R,O,D)}}},qn=async(r,a,l)=>{const{claims:u,headers:p,identity:_,userId:v}=ei(await E(r,a,i)),N=Te(a,r,D=>l.waitUntil?.(D)),k=D=>async(H,$={})=>{const x=H.__lunoraRef;if(typeof x!="string")throw new c("ctx.run*: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});ke(x),D!==o&&await G(_,D);const X=await Oe(r,x,ye($),D,{...p,"x-lunora-system":"1"},N),Z=await X.json();if(Z.error)throw new c(Z.error.message??"shard RPC failed",{code:Z.error.code??"INTERNAL",status:X.status});return Ze(Z.result)},R=k(o),O=async(D,H,$={})=>{D!==void 0&&D!==o&&await G(_,D);const x=new Headers;for(const[X,Z]of Object.entries($.headers??{}))X.toLowerCase().startsWith("x-lunora-")||x.set(X,Z);for(const[X,Z]of Object.entries(p))x.set(X,Z);return A(d,D??o,new Request(new URL(H,r.url),{headers:x,method:$.method??"GET",...$.body===void 0?{}:{body:$.body}}))};return{auth:{getIdentity:()=>Promise.resolve(u),userId:v},cache:l.cache,fetch:globalThis.fetch.bind(globalThis),fetchShard:O,forShard:D=>{const H=k(D);return{runAction:H,runMutation:H,runQuery:H}},live:e.liveStreams===!1?Vt():{publish:(D,H,$)=>se(r.url,D,H,$,{identity:_})},runAction:R,runMutation:R,runQuery:R,...f===void 0?{}:{scheduler:Yn(f)},...l.waitUntil===void 0?{}:{waitUntil:l.waitUntil.bind(l)},...e.storage===void 0?{}:{storage:lo(e.storage(a,new URL(r.url).origin))}}},Xn=async(r,a,l)=>{if(!e.httpRouter)return;const u=await qn(r,a,l);try{return await e.httpRouter.fetch(r,{...a,__lunoraCtx:u},l)}catch(p){return console.error("[lunora] httpRouter (SSR) handler threw:",p),new Response("Internal Server Error",{status:500})}},lt=new Set(Object.values(e.functions??{}).flatMap(r=>r.lifecycle==="socket"&&typeof r.socketPath=="string"?[r.socketPath]:[])),ht=async(r,a,l)=>{if(!Xe(r))throw new c("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});const u=kt(r,de);if(u)return u;const p=l.searchParams.get("shard")??o,{headers:_,identity:v}=await E(r,a,i),N=T(r)||await sn(r,P());await G(v,p,N);const k=on(r,_),R=rn(a,e.shardDO);if(R!==void 0){k.set("x-lunora-shard-binding",R);const O=lt.has(l.pathname)?0:await di(d,p);if(O>0){const D=Oo(p,Math.floor(Math.random()*O));return A(d,D,new Request(r,{headers:k}),Dt(r))}}return A(d,p,new Request(r,{headers:k}))},Zn=async(r,a,l)=>{if(h===void 0)return new Response("Not found",{status:404});if(!Xe(r))return new Response("Expected a WebSocket upgrade",{headers:{allow:"GET"},status:426});const u=kt(r,de);if(u)return u;let p;try{p=decodeURIComponent(l.pathname.slice(qt.length))}catch{return new Response("Unknown voice agent",{status:404})}const _=Object.hasOwn(h,p)?h[p]:void 0;if(_===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:N,identity:k}=await E(r,a,i);if(e.authorizeShard){if(!await De(e.authorizeShard({identity:k,shardKey:v})))throw new c("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else V("shard");const R=on(r,N);return A(_,v,new Request(r,{headers:R}))},er=async(r,a,l)=>{if(e.authorizeFanOut){if(!await De(e.authorizeFanOut(l,r.table,a)))throw new c("Forbidden fan-out",{code:"FORBIDDEN_FANOUT",status:403});return}if(a.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});V("fan-out")},ve=async(r,a)=>{if(!(!r.fanOut&&r.functionPath.startsWith("__lunora_admin__:"))){if(r.fanOut){await er(r.fanOut,r.functionPath,a);return}await G(a,r.shardKey??o)}},tr=(r,a,l)=>{if(e.replicaReads!==!0)return;if(e.functions===void 0){q();return}if(e.functions[a]?.kind!=="query"||l.includes(tt)||l.includes(et))return;const u=Dt(r);return u===void 0?void 0:{name:Io(l,u),region:u}},nr=async(r,a,l,u,p)=>{const _=tr(r,a,u);if(_!==void 0){const v={...p,"x-lunora-replica-read":"1",...w===void 0?{}:{"x-lunora-shard-binding":w}},N=Po(r.headers.get("x-lunora-min-seq"));N!==void 0&&(v["x-lunora-min-seq"]=String(N));const k=await A(d,_.name,Ce(a,l,v),_.region);if(k.status!==421)return k}return A(d,u,Ce(a,l,p))},Oe=async(r,a,l,u,p,_)=>{const v=Date.now(),{observability:N,sampling:k}=e,R=Ye(r),{decision:O,ignoredUpstream:D,trace:H}=Gt(r,{...R.rayId===void 0?{}:{rayId:R.rayId},...k===void 0?{}:{sampling:k},trustInbound:t(r)});D&&n(r);const $={...p,[vt]:O.keepErrors?"1":"0",[At]:"1"};Qt(H,$);try{const x=await nr(r,a,l,u,$),X=Rt(x.headers.get(Et));ue(N,{...R,...Yt(H),durationMs:Date.now()-v,functionPath:a,ok:x.ok,shardKey:u,...x.ok?{}:{error:{...X,code:X?.code??"SHARD_ERROR",message:X?.message??`shard returned ${String(x.status)}`,status:x.status}}},_,void 0,{isTraced:H.sampled,keepErrors:O.keepErrors});const Z=new Response(x.body,{headers:x.headers,status:x.status,statusText:x.statusText});return Z.headers.set("x-lunora-shard-key",u),Z.headers.delete(Et),Z}catch(x){throw ue(N,{...R,...Yt(H),...Ne(a,Date.now()-v,x,{shardKey:u})},_,void 0,{isTraced:H.sampled,keepErrors:O.keepErrors}),x}},rr=r=>{if(r.fanOut&&r.shardKey)throw new c("RPC envelope cannot set both `shardKey` and `fanOut`",{code:"BAD_REQUEST",status:400});r.fanOut||ke(r.functionPath)},or=async(r,a,l)=>{M(r,"POST","RPC");const u=await ai(r);si(a,u),rr(u);const p=await Ln(r,u);if(p!==void 0)return p;const{headers:_,identity:v}=await L(r,a,i);Xt(r,v),await ve(u,v);const N=qe(u,e);{const k=Date.now(),{observability:R}=e,O=Ye(r),D=Te(a,r,l&&(x=>l.waitUntil?.(x)));if(u.fanOut)try{const x=await s.fanOut(d,{args:u.args??{},fanOut:u.fanOut,functionPath:u.functionPath,headers:_});return ue(R,{durationMs:Date.now()-k,fanOut:{failed:x.failed,shards:x.ok+x.failed,table:u.fanOut.table},functionPath:u.functionPath,...O,ok:!0},D),Response.json(x,{headers:{"content-type":"application/json"},status:200})}catch(x){throw ue(R,{...Ne(u.functionPath,Date.now()-k,x,{fanOut:{table:u.fanOut.table}}),...O},D),x}const H=u.shardKey??o,$=()=>Oe(r,u.functionPath,u.args??{},H,_,D);return N&&e.x402Charge?e.x402Charge(r,{functionPath:u.functionPath,price:N.price},$,Je(l)):$()}},sr=async(r,a,l)=>{M(r,"POST","RPC batch");const u=await ne(r),{calls:p}=u;if(!Array.isArray(p))throw new c("RPC batch `calls` must be an array",{code:"BAD_REQUEST",status:400});const{headers:_,identity:v}=await L(r,a,i);Xt(r,v);const N=hs(p,o);for(const F of N.values())for(const Q of F)if(e.functions?.[Q.functionPath]?.x402)throw new c(`paid (\`.x402\`) function "${Q.functionPath}" cannot be called in a batch; dispatch it individually over ${Jt}`,{code:"BAD_REQUEST",status:400});await Promise.all([...N.entries()].flatMap(([F,Q])=>Q.map(ee=>ve({args:ee.args,functionPath:ee.functionPath,shardKey:F},v))));const{observability:k,sampling:R}=e,O=Te(a,r,l&&(F=>l.waitUntil?.(F))),D=Ye(r),{decision:H,ignoredUpstream:$,trace:x}=Gt(r,{...D.rayId===void 0?{}:{rayId:D.rayId},...R===void 0?{}:{sampling:R},trustInbound:t(r)});$&&n(r);const X={isTraced:x.sampled,keepErrors:H.keepErrors},Z=F=>{const Q={..._,"content-type":"application/json",[vt]:H.keepErrors?"1":"0",[At]:"1"};return Qt({...x,spanId:F},Q),Q},Me=F=>({parentSpanId:F,spanId:be(8),traceFlags:x.traceFlags,traceId:x.traceId}),Pe=[],$e=[],wt=(F,Q,ee,he)=>({body:{error:{code:ee,message:he}},id:F.id,status:Q}),gt=(F,Q,ee,he,we)=>{for(const te of F)ue(k,we(te),O,void 0,X),Pe.push(wt(te,Q,ee,he))},br=(F,Q,ee,he,we,te)=>{for(const Re of F){const Ee=we.get(Re.id),fe=Ee?.status??te,pe=fe<400,Ae=pe?void 0:Rt(Ee?.errorDetail);ue(k,{durationMs:he,functionPath:Re.functionPath,...D,...Me(ee),ok:pe,shardKey:Q,...pe?{}:{error:{...Ae,code:Ae?.code??"SHARD_ERROR",message:Ae?.message??`batched call returned ${String(fe)}`,status:fe}}},O,void 0,X)}};await Promise.all([...N.entries()].map(async([F,Q])=>{const ee=be(8),he=new Request("https://shard.internal/rpc-batch",{body:JSON.stringify({calls:Q}),headers:new Headers(Z(ee)),method:"POST"}),we=Date.now();let te;try{te=await A(d,F,he)}catch(Y){const Se=Date.now()-we,{body:_t}=Er(Y,{fallbackCode:"SHARD_UNAVAILABLE",redactedMessage:"shard unavailable"});gt(Q,502,_t.code,_t.message,_r=>({...Ne(_r.functionPath,Se,Y,{shardKey:F}),...D,...Me(ee)}));return}const Re=Date.now()-we,Ee=te.headers.get("x-d1-bookmark");Ee&&$e.push(Ee);let fe;try{fe=await te.json()}catch{const Y=`shard batch returned a non-JSON response (${String(te.status)})`;gt(Q,te.status,"SHARD_UNAVAILABLE",Y,Se=>({durationMs:Re,error:{code:"SHARD_UNAVAILABLE",message:Y,status:te.status},functionPath:Se.functionPath,...D,...Me(ee),ok:!1,shardKey:F}));return}const pe=Array.isArray(fe.results)?fe.results:[],Ae=new Set(pe.map(Y=>Y.id));br(Q,F,ee,Re,new Map(pe.map(Y=>[Y.id,Y])),te.status),Pe.push(...pe.map(({errorDetail:Y,...Se})=>Se));for(const Y of Q)Ae.has(Y.id)||Pe.push(wt(Y,te.status,"SHARD_UNAVAILABLE",`shard batch omitted result for call ${String(Y.id)}`))}));const yt={"content-type":"application/json"},[bt]=$e;return $e.length===1&&bt!==void 0&&(yt["x-d1-bookmark"]=bt),Response.json({results:Pe},{headers:yt,status:200})},ar=async(r,a,l,u={},p={})=>{try{const _=l.__lunoraRef;if(typeof _!="string")throw new c("serverQuery: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});ke(_);const{headers:v,identity:N}=await L(r,a,i,p.context),k={args:u,functionPath:_,shardKey:p.shardKey};await ve(k,N);const R=p.shardKey??o,O=Te(a,r,p.waitUntil),D=()=>Oe(r,_,u,R,v,O),H=qe(k,e);return H&&e.x402Charge?await e.x402Charge(r,{functionPath:_,price:H.price},D,Je(p.waitUntil?{waitUntil:p.waitUntil}:p.context)):await D()}catch(_){return Ot(_)}},ft=async(r,a,l)=>{const{observability:u}=e,p=Date.now(),_=be(16),v=be(8),N=nn(a),k=un(_,v,!0);try{const R=await l(k);return ue(u,{durationMs:Date.now()-p,functionPath:r,ok:!0,spanId:v,traceId:_},N),R}catch(R){throw ue(u,{...Ne(r,Date.now()-p,R,{}),spanId:v,traceId:_},N),R}finally{Tt(u,N)}},pt=async(r,a,l,u)=>{y(a);const p=[],_=O=>O instanceof Error?O:new Error(String(O)),v=e.crons?.[r.cron];if(v)try{await v(r,a,l)}catch(O){p.push(_(O))}const N=await He(r.cron,a,l,p,_,u),k=!!e.backupStore&&e.backupCron!==void 0&&e.backupCron===r.cron;if(k)try{await as(e,s,d,P(),r)}catch(O){p.push(_(O))}if(!v&&N===0&&!k){const O=[...new Set([...Object.keys(e.crons??{}),...Object.keys(e.cronJobs??{})])];console.warn(`[lunora] scheduled("${r.cron}") fired but no cron handler is registered for that expression. Registered: ${O.length===0?"(none)":O.join(", ")}. Check that \`triggers.crons\` in wrangler.jsonc matches the app's cron definitions.`)}const[R]=p;if(p.length===1&&R)throw R;if(p.length>1)throw new AggregateError(p,`scheduled("${r.cron}") had ${String(p.length)} failure(s)`)},ir=Ta({assertAdmin:z,dispatchScheduled:pt,queueHandler:e.queueHandler}),cr=async(r,a)=>{try{const l=r??{},u=e.adminToken??(typeof l.LUNORA_ADMIN_TOKEN=="string"?l.LUNORA_ADMIN_TOKEN:void 0);if(!u||u.length===0)return;await A(d,o,Ce(Ya,{outcome:a},{authorization:`Bearer ${u}`,"content-type":"application/json"}))}catch{}},dr=async(r,a,l,u)=>{if(!e.authHandler)return;const p=e.authBasePath??Zt,_=tn(l.pathname,p)?$r(r):void 0;let v;try{v=await e.authHandler(_?.request??r)}catch(N){throw _?.overflowed()?new c("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413}):N}if(_?.overflowed())throw new c("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});if(v)return Xa(l.pathname,p)&&u.waitUntil?.(cr(a,v.status>=400?"fail":"ok")),v},ur=async({args:r,env:a,functionPath:l,request:u,shardKey:p,waitUntil:_})=>{hn(r,"REST");const v={functionPath:l,...p===void 0?{}:{shardKey:p}},{headers:N,identity:k}=await L(u,a,i);await ve(v,k);const R=p??o,O=Te(a,u,_),D=()=>Oe(u,l,r,R,N,O),H=qe(v,e);return H&&e.x402Charge?e.x402Charge(u,{functionPath:l,price:H.price},D,Je({waitUntil:_})):D()},lr=jr({functions:e.functions??{},invoke:ur,readJsonBody:ne,edgeCache:e.restEdgeCache,...e.restRateLimit?{rateLimit:e.restRateLimit}:{}}),Ie=e.routes!==void 0&&Object.keys(e.routes).length>0?e.routes:void 0,hr=new Set(e.liveStreamRoutes),fr=(r,a)=>{if(!Ie)return;const l=`${r.method} ${a.pathname}`;if(!hr.has(l))return Ie[l]??Ie[a.pathname]};fi(Ie);const pr={[Va]:r=>r.method!=="GET"&&r.method!=="HEAD"?new Response(void 0,{headers:{allow:"GET, HEAD"},status:405}):Response.json({ok:!0},{headers:{"cache-control":"no-store"}}),[Ka]:(r,a,l)=>ht(r,a,l),[Jt]:(r,a,l,u)=>or(r,a,u),[Fa]:(r,a,l,u)=>sr(r,a,u),[Bo]:(r,a,l,u)=>Cn(r,a,u),[Ga]:(r,a,l,u)=>ce(r,a,u),[Qa]:async r=>{M(r,"POST","ws-token"),z(r);const a=P();if(a===void 0)throw new c("ws-token minting requires a configured admin token",{code:"ADMIN_TOKEN_NOT_CONFIGURED",status:400});const l=await Go(a);return Response.json(l,{headers:{"cache-control":"no-store"}})},...J,...jn,...Mn,...$n,...Fn,...Kn,...Gn,...Qn,...Wn,...zn,...Jn,...lr,...Vo({assertAdmin:z,getAuthAdmin:()=>e.authAdmin,parsePaging:je,queryParameter:Le,readJsonBody:ne})};let de=Pt(e.security),mt=!1;const mr=r=>{mt||(mt=!0,de=Pt(e.security,r??{}))},wr=async(r,a)=>{Ja(a)&&await I(r)},gr=(r,a)=>{if(!(a.pathname.startsWith(xe)||e.authHandler!==void 0&&tn(a.pathname,e.authBasePath??Zt))||r.method!=="POST"&&r.method!=="PUT")return;const u=Number(r.headers.get("content-length")??""),p=ja[a.pathname]??ln;if(Number.isFinite(u)&&u>p)throw new c("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413})},yr=async(r,a,l)=>{ot.set(r,l);const u=new URL(r.url);gr(r,u);const p=await dr(r,a,u,l);if(p)return p;if(lt.has(u.pathname)&&r.method==="GET"&&Xe(r))return ht(r,a,u);const _=fr(r,u);if(_)return _(r,a,l);const v=ir[u.pathname];if(v)return v(r,a,l);const N=pr[u.pathname];if(N)return await wr(r,u.pathname),N(r,a,u,l);if(e.voiceAgents!==void 0&&u.pathname.startsWith(qt))return Zn(r,a,u);if(u.pathname.startsWith(xe))return new Response("Not found",{status:404});const k=await Xn(r,a,l);if(k&&k.status!==404)return k;const R=await e.authDiscoveryHandler?.(r);return R?(await k?.body?.cancel(),R):k??new Response("Not found",{status:404})};return{async fetch(r,a,l){e.passThroughOnException&&l.passThroughOnException?.(),mr(a),y(a);const u=co(r,de);if(u)return u;const p=uo(r,de);if(p)return Ge(p,r,de);try{const _=await yr(r,a,l);return Ge(_,r,de)}catch(_){return Ge(Ot(_),r,de)}finally{Tt(e.observability,nn(l))}},async queue(r,a,l){await ft(`queue:${ti(r)}`,l,async u=>{const p=e.liveStreams===!1?Vt():{publish:(_,v,N)=>se(Ma,_,v,N,"trusted")};await e.queue?.(r,a,l,{traceparent:u},p,e.queueFetchImpl)})},async scheduled(r,a,l){await ft(`cron:${r.cron}`,l,async u=>{await pt(r,a,l,u)})},serverQuery:ar}},mi=e=>Un(e),wi=e=>typeof e=="function"?{fetch:e}:e,gi=e=>!!e.backupCron||Object.keys(e.crons??{}).length>0||Object.keys(e.cronJobs??{}).length>0,yi=e=>typeof e!="object"?{}:{...typeof e.email=="function"?{email:e.email}:{},...typeof e.queue=="function"?{queue:e.queue}:{},...typeof e.scheduled=="function"?{scheduled:e.scheduled}:{}},Ki=(e,t)=>{const n=wi(e),{email:o,queue:s,scheduled:i}=yi(e),d=h=>{const g={...mi({...h,httpRouter:n})};return i!==void 0&&!gi(h)&&(g.scheduled=async(A,S,P)=>{await i(A,S,P)}),s!==void 0&&h.queue===void 0&&(g.queue=async(A,S,P)=>{await s(A,S,P)}),o!==void 0&&(g.email=async(A,S,P)=>{await o(A,S,P)}),g};if(typeof t!="function")return d(t);const f=t;return{fetch:(h,m,g)=>d(f(m)).fetch(h,m,g),queue:(h,m,g)=>d(f(m)).queue?.(h,m,g)??Promise.resolve(),scheduled:(h,m,g)=>d(f(m)).scheduled(h,m,g),serverQuery:(h,m,g,A,S)=>d(f(m)).serverQuery(h,m,g,A,S),...o===void 0?{}:{email:(h,m,g)=>d(f(m)).email?.(h,m,g)??Promise.resolve()}}},bi=(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}},Gi=(e={})=>(t,n,o)=>Un(bi(e,n)).fetch(t,n,o??vr),Qi=e=>e;export{nt as COPY_AUTH_TO_JURISDICTION_OP,Ct as GET_AUTH_AUDIT_LOG_OP,vr as NOOP_EXECUTION_CONTEXT,En as PURGE_UNPINNED_AUTH_OP,Vi as composeIdentityResolvers,mi as composeWorker,Gi as createLunoraHandler,Un as createWorker,Qi as defineRpcEnvelope,di as probeRelayCount,bi as resolveLunoraOptions,Ji as routeIdentityResolvers,Ki 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.234",
|
|
4
4
|
"description": "Lunora Worker runtime: the RPC router, shard resolver, and query coordinator",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cloudflare",
|
|
@@ -48,7 +48,7 @@
|
|
|
48
48
|
"dependencies": {
|
|
49
49
|
"@lunora/bindings": "1.0.0-alpha.131",
|
|
50
50
|
"@lunora/errors": ">=1.0.0-alpha.51 <2.0.0-0",
|
|
51
|
-
"@lunora/observability": "1.0.0-alpha.
|
|
51
|
+
"@lunora/observability": "1.0.0-alpha.166",
|
|
52
52
|
"@lunora/platform": "1.0.0-alpha.74",
|
|
53
53
|
"@lunora/wire": "1.0.0-alpha.2"
|
|
54
54
|
},
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as a}from"./LunoraError-PkZWF-_g.mjs";import{applyJurisdiction as S,resolveShard as _}from"./applyJurisdiction-DKQE8kOA.mjs";const l="__lunora_shard_registry__",f=3e4,y="https://shard-registry.internal",g=async r=>await r.json(),T=r=>{const p=r.instanceName??l,i=r.cacheTtlMs??f,n=new Map,w=S(r.namespace,r.jurisdiction),c=()=>_(w,p),d=async(e,t)=>c().fetch(new Request(`${y}${e}`,{body:JSON.stringify(t),headers:{"content-type":"application/json"},method:"POST"})),h=async e=>c().fetch(new Request(`${y}${e}`,{method:"GET"}));return{invalidate(e){e===void 0?n.clear():n.delete(e)},async listShardKeys(e){const t=Date.now(),s=n.get(e);if(s&&s.expiresAt>t)return s.shardKeys;const o=await h(`/list?table=${encodeURIComponent(e)}`);if(!o.ok)throw new a(`shard registry /list returned ${String(o.status)}`);const{shardKeys:u}=await g(o);return i>0&&n.set(e,{expiresAt:t+i,shardKeys:u}),u},async register(e,t){const s=await d("/register",{shardKey:t,table:e});if(!s.ok)throw new a(`shard registry /register returned ${String(s.status)}`);n.delete(e)},async snapshot(){const e=await h("/snapshot");if(!e.ok)throw new a(`shard registry /snapshot returned ${String(e.status)}`);const{tables:t}=await g(e);return t},async unregister(e,t){const s=await d("/unregister",{shardKey:t,table:e});if(!s.ok)throw new a(`shard registry /unregister returned ${String(s.status)}`);n.delete(e)}}};export{f as DEFAULT_REGISTRY_CACHE_TTL_MS,l as SHARD_REGISTRY_DO_NAME,T as createDynamicShardRegistry};
|