@lunora/runtime 1.0.0-alpha.216 → 1.0.0-alpha.217
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
CHANGED
|
@@ -3334,6 +3334,20 @@ interface FunctionRegistryEntry {
|
|
|
3334
3334
|
* callers pass the generated `LUNORA_FUNCTIONS` map without a cast.
|
|
3335
3335
|
*/
|
|
3336
3336
|
kind: "action" | "mutation" | "query" | "stream";
|
|
3337
|
+
/**
|
|
3338
|
+
* The lifecycle moment a registration fires on, when it is a lifecycle hook,
|
|
3339
|
+
* a `defineRoom` registration, or a `defineWebSocket` route. Present on the
|
|
3340
|
+
* generated `LUNORA_FUNCTIONS` values (they are the live runtime objects);
|
|
3341
|
+
* the worker reads `"socket"` entries to recognise a route's path as a
|
|
3342
|
+
* WebSocket-upgrade endpoint rather than an unknown app route.
|
|
3343
|
+
*/
|
|
3344
|
+
lifecycle?: "connect" | "disconnect" | "init" | "reactor" | "room" | "socket" | "whisper";
|
|
3345
|
+
/**
|
|
3346
|
+
* Set on a `defineWebSocket` route: the URL path it serves. The worker
|
|
3347
|
+
* forwards an upgrade at this path to the shard Durable Object, which
|
|
3348
|
+
* resolves the registration through its generated socket map.
|
|
3349
|
+
*/
|
|
3350
|
+
socketPath?: string;
|
|
3337
3351
|
visibility?: "internal" | "public";
|
|
3338
3352
|
/**
|
|
3339
3353
|
* x402 payment tag set by the `.x402({ price })` builder modifier. Present
|
package/dist/index.d.ts
CHANGED
|
@@ -3334,6 +3334,20 @@ interface FunctionRegistryEntry {
|
|
|
3334
3334
|
* callers pass the generated `LUNORA_FUNCTIONS` map without a cast.
|
|
3335
3335
|
*/
|
|
3336
3336
|
kind: "action" | "mutation" | "query" | "stream";
|
|
3337
|
+
/**
|
|
3338
|
+
* The lifecycle moment a registration fires on, when it is a lifecycle hook,
|
|
3339
|
+
* a `defineRoom` registration, or a `defineWebSocket` route. Present on the
|
|
3340
|
+
* generated `LUNORA_FUNCTIONS` values (they are the live runtime objects);
|
|
3341
|
+
* the worker reads `"socket"` entries to recognise a route's path as a
|
|
3342
|
+
* WebSocket-upgrade endpoint rather than an unknown app route.
|
|
3343
|
+
*/
|
|
3344
|
+
lifecycle?: "connect" | "disconnect" | "init" | "reactor" | "room" | "socket" | "whisper";
|
|
3345
|
+
/**
|
|
3346
|
+
* Set on a `defineWebSocket` route: the URL path it serves. The worker
|
|
3347
|
+
* forwards an upgrade at this path to the shard Durable Object, which
|
|
3348
|
+
* resolves the registration through its generated socket map.
|
|
3349
|
+
*/
|
|
3350
|
+
socketPath?: string;
|
|
3337
3351
|
visibility?: "internal" | "public";
|
|
3338
3352
|
/**
|
|
3339
3353
|
* x402 payment tag set by the `.x402({ price })` builder modifier. Present
|
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 R,toFivetranResponse as x}from"./packem_shared/toAirbyteMessages-DY0vsuEn.mjs";import{composeWorker as l,createLunoraHandler as d,createWorker as u,defineRpcEnvelope as _,resolveLunoraOptions as k,withFrameworkWorker as y}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 R,toFivetranResponse as x}from"./packem_shared/toAirbyteMessages-DY0vsuEn.mjs";import{composeWorker as l,createLunoraHandler as d,createWorker as u,defineRpcEnvelope as _,resolveLunoraOptions as k,withFrameworkWorker as y}from"./packem_shared/composeWorker-D91f8MfK.mjs";import{createCrossShardRelationCapabilities as O}from"./packem_shared/createCrossShardRelationCapabilities-BmGOuTrp.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-CdACWUQW.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-DksAgIpa.mjs";import{c as F,a as M,d as N,r as G,b as K,s as U,w as B}from"./packem_shared/export-tap-C2B_SATf.mjs";import{HEALTH_PATH as w,HEALTH_READY_PATH as z,buildHealthRoutes as X,d1Probe as j,durableObjectProbe as V,presenceProbe as W}from"./packem_shared/HEALTH_PATH-CAX2UeFy.mjs";import{LOG_ARCHIVE_PATH as J,resolveLogArchiveFromEnv as Q}from"./packem_shared/LOG_ARCHIVE_PATH-Hmjpz_Ko.mjs";import{memoizeIdentity as $,memoizeIdentityPerRequest as ee}from"./packem_shared/memoizeIdentity-BNnHkqeF.mjs";import{e as oe,a as te}from"./packem_shared/observability-DgurIZIR.mjs";import{analyticsEngineSink as se,combineSinks as ie,consoleSink as pe,otlpSink as ne,pipelineLogSink as ce,webhookSink as me}from"./packem_shared/analyticsEngineSink-BZB-ZYCP.mjs";import{D as Ee,c as Re}from"./packem_shared/pipeline-log-reader-C-nuWG_e.mjs";import{createQueryCoordinator as Se,createStaticShardRegistry as le}from"./packem_shared/createQueryCoordinator-es4jrL6Q.mjs";import{applyJurisdiction as ue,resolveShard as _e}from"./packem_shared/applyJurisdiction-D4vryLhj.mjs";import{a as ye,r as Ce,b as Oe}from"./packem_shared/rest-cache-CmHN871W.mjs";import{a as Ae,b as Le,c as Te,r as he}from"./packem_shared/rest-routes-DQkyqlym.mjs";import{decorateResponse as Pe,enforceOrigin as ge,handleCorsPreflight as ve,resolveSecurity as Ie}from"./packem_shared/decorateResponse-CRBbtPYT.mjs";import{createShardClient as Fe}from"./packem_shared/createShardClient-DIVRljRz.mjs";import{STORAGE_UPLOAD_MAX_BODY_BYTES as Ne}from"./packem_shared/STORAGE_UPLOAD_MAX_BODY_BYTES-BIiV5kqV.mjs";import{LOG_ARCHIVE_NOT_CONFIGURED as Ke}from"./packem_shared/LOG_ARCHIVE_NOT_CONFIGURED-CDpi4yFD.mjs";import{NOOP_EXECUTION_CONTEXT as Be}from"./packem_shared/NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{composeIdentityResolvers as we,routeIdentityResolvers as ze}from"./packem_shared/composeIdentityResolvers-BHZ4jH8o.mjs";const e="0.0.0";export{s as BACKUP_KEY_PREFIX,Ee as DEFAULT_LOG_COLUMNS,A as DEFAULT_REGISTRY_CACHE_TTL_MS,w as HEALTH_PATH,z as HEALTH_READY_PATH,Ke as LOG_ARCHIVE_NOT_CONFIGURED,J as LOG_ARCHIVE_PATH,v as LunoraError,Be as NOOP_EXECUTION_CONTEXT,L as SHARD_REGISTRY_DO_NAME,Ne as STORAGE_UPLOAD_MAX_BODY_BYTES,e as VERSION,se as analyticsEngineSink,ue as applyJurisdiction,ye as applyRestCache,Ae as argsFromQuery,i as backupManifestKey,p as backupObjectKey,n as backupObjectKeyOfManifest,X as buildHealthRoutes,Le as buildRestRoutes,ie as combineSinks,we as composeIdentityResolvers,l as composeWorker,pe as consoleSink,O as createCrossShardRelationCapabilities,T as createDynamicShardRegistry,F as createKvCursorStore,d as createLunoraHandler,M as createMemoryCursorStore,Re as createPipelineLogReader,Se as createQueryCoordinator,Te as createRestRateLimit,Fe as createShardClient,le as createStaticShardRegistry,u as createWorker,j as d1Probe,t as declareAppJurisdiction,Pe as decorateResponse,N as defineExportSink,_ as defineRpcEnvelope,V as durableObjectProbe,oe as emitLogEvent,te as emitRpcEvent,ge as enforceOrigin,ve as handleCorsPreflight,c as isBackupManifestEntry,m as isBackupManifestKey,$ as memoizeIdentity,ee as memoizeIdentityPerRequest,f as normalizeBackupPrefix,ne as otlpSink,H as parseStackFrames,ce as pipelineLogSink,W as presenceProbe,G as r2Sink,Ce as requestCarriesCredentials,Q as resolveLogArchiveFromEnv,k as resolveLunoraOptions,Ie as resolveSecurity,_e as resolveShard,Oe as restCacheHeaders,he as restSurfaceFromRegistry,ze as routeIdentityResolvers,K as runExportTap,U as sanitizeChange,R as toAirbyteMessages,P as toError,I as toErrorResponse,x as toFivetranResponse,B as webhookExportSink,me as webhookSink,y as withFrameworkWorker};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import{isLunoraError as yr,toErrorBody as br}from"@lunora/errors";import{encodeWire as ye,decodeWire as Ze,encodeArgsOrThrow as _r}from"@lunora/wire";import{e as an}from"./evict-oldest-BNXsKx4s.mjs";import{NOOP_EXECUTION_CONTEXT as Rr}from"./NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{i as Er,e as Sr,a as Tr,E as Rt,d as Ar}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 Or,m as vr,d as Ir,a as Pr,r as kr}from"./otlp-resource-BwFJnvwB.mjs";import{r as Dr,f as Et,a as ue,S as St}from"./observability-DgurIZIR.mjs";import{t as Nr,f as Ur}from"./base64-Bl1_r2k1.mjs";import{d as ne,e as oe,M as ln,b as Cr,f as Br,g as hn,w as xr,h as fn,t as Hr}from"./rest-routes-DQkyqlym.mjs";import{LunoraError as c,toErrorResponse as Tt}from"./LunoraError-DksAgIpa.mjs";import{a as M,m as ge}from"./method-guard-BG_vJNTl.mjs";import{normalizeBackupPrefix as st,BACKUP_KEY_PREFIX as at,isBackupManifestKey as Lr,backupObjectKeyOfManifest as pn,backupObjectKey as jr,backupManifestKey as Mr}from"./BACKUP_KEY_PREFIX-BOtSu-_3.mjs";import{toHex as $r,buildStorageAdminRoutes as Fr,STORAGE_UPLOAD_MAX_BODY_BYTES as Kr,STORAGE_PATH as Gr}from"./STORAGE_UPLOAD_MAX_BODY_BYTES-BIiV5kqV.mjs";import{b as Qr,e as Wr,f as At,g as zr,h as Vr}from"./export-tap-C2B_SATf.mjs";import{buildHealthRoutes as Jr,durableObjectProbe as Yr,d1Probe as Xr,presenceProbe as $e}from"./HEALTH_PATH-CAX2UeFy.mjs";import{wrapResolverWithContract as qr}from"./composeIdentityResolvers-BHZ4jH8o.mjs";import{composeIdentityResolvers as Gi,routeIdentityResolvers as Qi}from"./composeIdentityResolvers-BHZ4jH8o.mjs";import{buildLogArchiveAdminRoutes as Zr}from"./LOG_ARCHIVE_PATH-Hmjpz_Ko.mjs";import{pruneShardRegistry as eo,createQueryCoordinator as to,createDefaultShardRegistry as no}from"./createQueryCoordinator-es4jrL6Q.mjs";import{resolveShard as _e,applyJurisdiction as Fe}from"./applyJurisdiction-D4vryLhj.mjs";import{resolveSecurity as Ot,handleCorsPreflight as ro,enforceOrigin as oo,decorateResponse as Ke,enforceWebSocketOrigin as vt}from"./decorateResponse-CRBbtPYT.mjs";const so=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",ao=e=>typeof e=="object"&&e!==null&&Object.hasOwn(e,mn),io=`may not contain the reserved workflow branch-marker key ("${mn}")`,co=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}},uo=/already[\s_-]?exists/iu,lo=e=>uo.test(e instanceof Error?e.message:String(e)),It="x-lunora-want-error-detail",Pt="x-lunora-error-detail",ho=8192,fo=e=>{if(!(e instanceof Error))return{message:String(e),name:typeof e};const{code:t}=e;return{...typeof t=="string"?{code:t}:{},message:e.message,name:e.name,...e.stack===void 0?{}:{stack:e.stack.slice(0,ho)}}},kt=e=>{if(e!=null)try{const t=JSON.parse(decodeURIComponent(e));return typeof t?.message=="string"&&typeof t.name=="string"?t:void 0}catch{return}},po="/_lunora/live/publish",mo="cf-ray",wo="x-lunora-ray-id",go=/^([\da-f]{16})(?:-[a-z]{3,4})?$/i,yo=e=>e==null?void 0:go.exec(e.trim())?.[1]?.toLowerCase(),bo=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"];new Set(bo);const _o=new Set(["AE","BH","IL","IQ","IR","JO","KW","LB","OM","PS","QA","SA","SY","TR","YE"]),Ro=-100,Eo=15,So=e=>{const t=Number(e.longitude??Number.NaN);switch(e.continent){case"AF":return"afr";case"AS":return e.country!==void 0&&_o.has(e.country)?"me":"apac";case"EU":return Number.isFinite(t)&&t>Eo?"eeur":"weur";case"NA":return Number.isFinite(t)&&t<Ro?"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::",Ao=(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 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},vo=(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,Io=Array.from({length:32},(e,t)=>t);new RegExp(`[${Io.map(e=>String.fromCodePoint(e)).join("")}]`,"u");const Po=64,ko=new Map,gn=async e=>vo(ko,e,async()=>crypto.subtle.importKey("raw",it.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]),Po),yn=async(e,t)=>{const n=await gn(e),o=await crypto.subtle.sign("HMAC",n,it.encode(t));return Nr(new Uint8Array(o))},Do=async(e,t,n)=>{const o=await gn(e);return crypto.subtle.verify("HMAC",o,n,it.encode(t))},No="/_lunora/scheduler/dispatch",Uo="__lunora_relation__:",Co=e=>e.startsWith(Uo),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())},Bo=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)},xo=({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},Ho=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}}},Lo=(e,t,n)=>e?.[n]??t?.[n],jo=(e,t,n,o)=>{const s=Lo(e,t,n);if(!(typeof s!="object"||s===null))return o.every(i=>typeof s[i]=="function")?s:void 0},_n="v1",Mo=6e4,$o=async(e,t={})=>{const n=(t.now??Date.now())+(t.ttlMs??Mo),o=`${_n}.${String(n)}`,s=await yn(e,o);return{expiresAtMs:n,token:`${o}.${s}`}},Fo=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=Ur(d)}catch{return!1}return Do(e,`${s}.${i}`,h)},U="/_lunora/admin/auth",Ko={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,Ge=(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},Go={[`${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:Ge(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:Ge(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:Ge(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"}},Qo=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:Ko[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:T=>e.queryParameter(h,T)},_=i.build(m),S=await t(()=>f(_));return Response.json(i.returns==="void"?{ok:!0}:S,{headers:{"cache-control":"no-store","content-type":"application/json"},status:200})},o={};for(const[s,i]of Object.entries(Go))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,Wo=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 _;try{_=await s.read(m)}catch(T){throw T instanceof c?T:(console.error("[lunora] auth audit read failed:",T),new c("auth audit read failed",{code:"AUTH_AUDIT_READ_FAILED",status:500}))}const S={entries:_};return Response.json({result:ye(S)},{headers:{"content-type":"application/json"},status:200})},nt="__lunora_admin__:copyAuthToJurisdiction",En="__lunora_admin__:purgeUnpinnedAuth",zo=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})},Vo=(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}},Jo=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??[])},Sn=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}=Vo(e,i),h=await Jo(t,n,i,f,s,e.defaultShardKey??"__root__"),m=e.exportGlobals,_=o===void 0||d.length>0;return(async function*(){yield*h,_&&m&&(yield*m({tables:d}))})()},Yo=async(e,t,n,o,s,i)=>{for await(const d of await Sn(e,t,n,o,i))s(d)},Xo=new TextEncoder,qo=1e3,Tn=10,Zo=200,Ht=8,An="lunoraBackupCron",Lt=24*1048576,jt=e=>{const t=e.slice(0,Tn).map(o=>pn(o)),n=e.length-t.length;return`${t.join(", ")}${n>0?` (+${String(n)} more)`:""}`},es=(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<qo;d+=1){const f=await e.list({cursor:i,include:["customMetadata"],prefix:t});for(const h of f.objects)Lr(h.key)&&h.customMetadata?.[An]===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)}},ts=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,Zo),m=i.length-h.length,_=s.length-f.length;if(h.length===0)return{deleted:[],failed:[],ignored:_,remaining:m};const S=[],T=[];for(let P=0;P<h.length;P+=Ht){const w=await Promise.allSettled(h.slice(P,P+Ht).map(async g=>(await e.delete(pn(g)),await e.delete(g),g)));for(const[g,b]of w.entries())b.status==="fulfilled"?S.push(b.value):T.push(h[P+g])}return S.length>0&&console.info(`[lunora] backup prune kept the newest ${String(n)} and deleted ${String(S.length)}: ${jt(S)}`),T.length>0&&console.warn(`[lunora] backup prune failed to remove ${String(T.length)}: ${jt(T)}`),{deleted:S,failed:T,ignored:_,remaining:m}},ns=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}},rs=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,_=[];await Yo(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});_.push(E)},n);const T=st(e.backupPrefix??at),P=new Date(s.scheduledTime).toISOString(),w=jr(T,P),g=es(_,m);_=[];const b=$r(await crypto.subtle.digest("SHA-256",g));await i.put(w,g,{httpMetadata:{contentType:"application/x-ndjson"},sha256:b});const A={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(Mr(w),`${JSON.stringify(A,void 0,2)}
|
|
3
|
+
`,{customMetadata:{[An]:s.cron},httpMetadata:{contentType:"application/json"}});try{const{stale:I}=await ct(i,T,e.backupRetain,s.cron);if(I.length>0){const E=I.slice(0,Tn),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)}},os=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 ts(n,st(e.backupPrefix??at),s,o,t)},ss="/_lunora/admin/backup/retention",as="/_lunora/admin/backup/prune",is=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 ns(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 os(t,h),{headers:{"cache-control":"no-store"}})};return{[as]:d,[ss]:i}},Mt=500,cs=(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}},ds=(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}=cs(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},us="/_lunora/admin/export",ls="/_lunora/admin/import",hs="/_lunora/admin/sync",fs="/_lunora/admin/connector/sync",ps="/_lunora/admin/apply",ms="/_lunora/admin/export-tap/run",ws=new TextEncoder,gs=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}},Qe=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):void 0,ys=e=>{const{applyGlobals:t,defaultShardKey:n,exportCursorStore:o,exportSinks:s,knownTables:i,queryCoordinator:d,assertAdmin:f,resolveForwardContext:h,shardDO:m,prepareExportRows:_,streamingImport:S,syncGlobals:T}=e,P=async(E,L)=>{const j=ge(E,["POST"]);if(j)return j;f(E);const C=await gs(E),{headers:K}=await h(E,L),X=await _(K,C.tables),V=new ReadableStream({async pull(G){try{for await(const J of X)G.enqueue(ws.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:{},X=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=Qe(C.tables),{headers:se}=await h(E,L),W=J??i(),le=await d.orchestrateCdcSync(m,{cursors:K,defaultShardKey:n,epochs:X,headers:se,limit:V,tables:W}),ae=T?await T({limit:V,sinceSeq:G}):void 0;return Response.json({global:ae,shards:le.shards},{status:200})},g=async(E,L)=>{const j=ge(E,["POST"]);if(j)return j;f(E);const C=await ne(E),K=Wr(C.cursor),X=typeof C.limit=="number"&&C.limit>0?C.limit:void 0,V=Qe(C.tables),{headers:G}=await h(E,L),J=V??i(),se=await d.orchestrateCdcSync(m,{cursors:K.s,defaultShardKey:n,headers:G,limit:X,tables:J}),W=[],le={...K.s};let ae=!1;for(const ce of se.shards)ae=At(W,ce.changes??[],Vr(X))||ae,le[ce.shardKey]=ce.cursor;let z=K.g;if(T){const ce=await T({limit:X,sinceSeq:K.g});ae=At(W,ce.changes,X)||ae,z=ce.cursor}const ie=zr({g:z,s:le,v:1}),xe={changes:W,hasMore:ae,nextCursor:ie};return Response.json(xe,{status:200})},b=async(E,L)=>{const j=ge(E,["POST"]);if(j)return j;f(E);const C=await ne(E),X=(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:X,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})},A=async(E,L)=>{const j=ge(E,["POST"]);if(j)return j;f(E);const{headers:C}=await h(E,L),K=await S(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,X=typeof C.limit=="number"&&C.limit>0?C.limit:void 0,V=Qe(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 Qr({coordinator:d,cursorStore:o,defaultShardKey:n,headers:J,limit:X,shardDO:m,sink:G,tables:se});return Response.json(W,{headers:{"content-type":"application/json"},status:200})};return{[ps]:b,[fs]:g,[us]:P,[ms]:I,[ls]:A,[hs]:w}},bs=(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}},_s=(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}},Rs=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 _="",S=0;const T=P=>{f+=1;const w=P.trim();if(w.length===0)return;d+=1;const g=bs(w,f);if(!g.ok){o.push(g.error);return}const{doc:b,table:A}=g,I=t.resolveTableSharding?.(A);if(I?.mode.kind==="global"){s.push({doc:b,line:f,table:A});return}const E=_s(b,A,I,n,f);if(!E.ok){o.push(E.error);return}const L=i.get(E.shardKey);L?L.rows.push({doc:b,table:A}):i.set(E.shardKey,{rows:[{doc:b,table:A}],shardKey:E.shardKey,startLine:f})};for(;;){const{done:P,value:w}=await h.read();if(P)break;if(w&&(S+=w.byteLength,S>ln))throw await h.cancel().catch(()=>{}),new c("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});_+=m.decode(w,{stream:!0});let g=_.indexOf(`
|
|
5
|
+
`);for(;g!==-1;){const b=_.slice(0,g);_=_.slice(g+1),T(b),g=_.indexOf(`
|
|
6
|
+
`)}}return _.length>0&&T(_),{errors:o,globalRows:s,perShard:i,received:d}},Es=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},Ss=async(e,t,n,o,s)=>{const i=t.defaultShardKey??"__root__",{errors:d,globalRows:f,perShard:h,received:m}=await Rs(e,t,i),_={conflicts:0,errors:d,failed:[],inserted:{}},S=[];if(t.resolveTableSharding===void 0&&h.size>0&&S.push("no `resolveTableSharding` is configured, so every row was routed to the default shard and no row could be recognised as `.global()` — correct for a single-shard app, silent misplacement for a sharded one"),h.size>0){const T=await n.orchestrateImport(s,{batches:[...h.values()],headers:o});$t(_,T),_.failed.push(...Es(T.shards))}if(f.length>0)if(t.importGlobals){const T=f[0]?.line??1,P=await t.importGlobals({rows:f,startLine:T});$t(_,P)}else for(const T of f)_.errors.push({code:"GLOBAL_NOT_CONFIGURED",line:T.line,message:`row targets global table "${T.table}" but no \`importGlobals\` is configured`,table:T.table});return{conflicts:_.conflicts,errors:_.errors,failed:_.failed,inserted:_.inserted,received:m,...S.length>0?{warnings:S}:{}}},Ts=Object.freeze({edges:[],nodes:[],modules:[],unresolved:[],version:1}),We=e=>typeof e=="object"&&e!==null?e:{},ze=e=>typeof e.kind=="string"?e.kind:"unknown",As=(e,t)=>{let n=We(t),o=!1;ze(n)==="optional"&&(o=!0,n=We(n._meta?.inner));const s=ze(n),i=n._meta??{},d={kind:s,name:e,optional:o};if(s==="id"&&typeof i.tableName=="string"&&(d.table=i.tableName),s==="array"){const f=ze(We(i.inner));f!=="unknown"&&(d.element=f)}return d},Os=e=>typeof e!="object"||e===null?[]:Object.entries(e).map(([t,n])=>As(t,n)).toSorted((t,n)=>t.name.localeCompare(n.name)),vs="/_lunora/admin/functions",Is="/_lunora/admin/cron-jobs",Ps="/_lunora/admin/architecture",ks="/_lunora/admin/openapi",Ds="/_lunora/admin/openrpc",Ns="/_lunora/admin/global/tables",Us="/_lunora/admin/global/table",Cs="/_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},Bs=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:{}}),xs=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"}),Hs=e=>{const{assertAdmin:t,options:n,parsePaging:o,queryParameter:s,requireAdminOption:i}=e,d=w=>{M(w,"GET","Functions");const g=i(w,n.functions,{code:"FUNCTIONS_NOT_CONFIGURED",message:"functions endpoint requires a `functions` registry on the worker"}),b=Object.entries(g).flatMap(([A,I])=>I.visibility==="internal"||I.kind==="stream"?[]:[{args:[...I.argumentDescriptors??Os(I.args)],kind:I.kind,path:A}]).toSorted((A,I)=>A.path.localeCompare(I.path));return Response.json({functions:b},{headers:{"content-type":"application/json"},status:200})},f=w=>{M(w,"GET","Cron-jobs");const g=i(w,n.cronJobs,{code:"CRON_JOBS_NOT_CONFIGURED",message:"cron-jobs endpoint requires a `cronJobs` map on the worker"}),b=Object.entries(g).flatMap(([A,I])=>I.map(E=>({args:E.args,cron:A,functionPath:E.functionPath,name:E.name,shardKey:E.shardKey,workflow:E.workflow}))).toSorted((A,I)=>A.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??Bs,{headers:{"content-type":"application/json"},status:200})),_=w=>(M(w,"GET","OpenRPC"),t(w),Response.json(n.openRpcSpec??xs,{headers:{"content-type":"application/json"},status:200})),S=async w=>{M(w,"GET","Global-tables");const g=i(w,n.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"});return Response.json(await g.listTables(),{headers:{"content-type":"application/json"},status:200})},T=async w=>{M(w,"GET","Global-table");const g=i(w,n.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),b=new URL(w.url),A=s(b,"table");if(A===void 0)throw new c("Global-table endpoint requires a `table` query param",{code:"BAD_REQUEST",status:400});const I=await g.readTablePage({...o(w),filters:Ft(s(b,"filters")),table:A});return Response.json(I,{headers:{"content-type":"application/json"},status:200})},P=async w=>{M(w,"GET","Global-facet");const g=i(w,n.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),b=new URL(w.url),A=s(b,"table"),I=s(b,"column");if(A===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 g.facetColumn({column:I,filters:Ft(s(b,"filters")),limit:L!==void 0&&Number.isFinite(L)?L:void 0,table:A});return Response.json(j,{headers:{"content-type":"application/json"},status:200})};return{[Is]:f,[vs]:d,[Cs]:P,[Us]:T,[Ns]:S,[Ps]:h,[ks]:m,[Ds]:_}},Ls="/_lunora/admin/kv/namespaces",js="/_lunora/admin/kv/keys",On="/_lunora/admin/kv/value",vn=32*1048576,Kt=60,Ms=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,g)=>{const b=new URL(w.url),A=b.searchParams.get("namespace")??"",I=b.searchParams.get("key")??"";if(A==="")throw new c(`KV-value ${g} request requires a \`namespace\` query parameter`,{code:"BAD_REQUEST",status:400});if(I==="")throw new c(`KV-value ${g} request requires a \`key\` query parameter`,{code:"BAD_REQUEST",status:400});return{key:I,namespace:A}},d=async(w,g)=>{if(!(await w.listNamespaces()).some(A=>A.binding===g))throw new c(`Unknown KV namespace binding \`${g}\``,{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 g=o(w),b=new URL(w.url),A=b.searchParams.get("namespace")??"";if(A==="")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(g,A),s(await g.listKeys({cursor:E,limit:C,namespace:A,prefix:I}))},T={DELETE:async w=>{const g=o(w),b=i(w,"DELETE");return await d(g,b.namespace),await g.deleteKey(b),s({deleted:!0})},GET:async w=>{const g=o(w),b=i(w,"GET");return await d(g,b.namespace),s(await g.getValue(b))},PUT:async w=>{const g=o(w),b=await t(w,vn);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 A=Math.floor(Date.now()/1e3)+Kt;if(b.expiration!==void 0&&(typeof b.expiration!="number"||!Number.isInteger(b.expiration)||b.expiration<A))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(g,b.namespace),await g.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 g=T[w.method];if(!g)throw new c("KV-value endpoint requires GET, PUT, or DELETE",{code:"METHOD_NOT_ALLOWED",status:405});return g(w)};return{[Ls]:f,[js]:h,[On]:P}},$s="/_lunora/migrate",Fs="/_lunora/admin/pitr",Ks="/_lunora/admin/rank",Gs="/_lunora/admin/rankpage",Qs="/_lunora/admin/shard-registry/prune",Ws="/_lunora/admin/shard-traffic",zs=new Set(["__lunora_admin__:migrationStatus","__lunora_admin__:runMigration"]),Vs=new Set(["__lunora_admin__:getPitrBookmark","__lunora_admin__:pitrRestore"]),Js=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"||!zs.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}},Ys=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}},qs=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})},Zs=async e=>{const n=await oe(e,"Rank page")??{};qs(n);const o=Xs(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}},ea=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}},ta=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}},na=async e=>{const n=await ne(e);if(typeof n.functionPath!="string"||!Vs.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}},ra=e=>{const{defaultShard:t,forwardToShard:n,isAdmin:o,queryCoordinator:s,resolveForwardContext:i,shardDO:d,shardedTables:f}=e,h=(g,b)=>{if(g.method!=="POST")throw new c(`${b} endpoint requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});if(!o(g))throw new c("Admin auth required",{code:"FORBIDDEN",status:403})},m=async(g,b)=>{h(g,"Migration");const A=await Js(g),{headers:I}=await i(g,b),E=await s.orchestrateMigration(d,{args:A.args,defaultShardKey:t,functionPath:A.functionPath,headers:I,table:A.table});return Response.json(E,{headers:{"content-type":"application/json"},status:200})},_=async(g,b)=>{h(g,"Rank");const A=await Ys(g),{headers:I}=await i(g,b),E=await s.orchestrateRank(d,{headers:I,index:A.index,partitionKey:A.partitionKey,rowId:A.rowId,sortValues:A.sortValues,table:A.table});return Response.json(E,{headers:{"content-type":"application/json"},status:200})},S=async(g,b)=>{h(g,"Rank page");const A=await Zs(g),{headers:I}=await i(g,b),E=await s.orchestrateRankPage(d,{...A,headers:I});return Response.json(E,{headers:{"content-type":"application/json"},status:200})},T=async(g,b)=>{h(g,"Shard-traffic");const A=await ea(g),{headers:I}=await i(g,b),E=await s.orchestrateShardTraffic(d,{headers:I,table:A.table});return Response.json(E,{headers:{"content-type":"application/json"},status:200})},P=async(g,b)=>{h(g,"Shard-registry prune");const A=await ta(g),I=f(),E=(A.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(g,b),j=await eo(s.registry,d,{dryRun:A.dryRun,headers:L,tables:A.tables??I});return Response.json(j,{status:j.failed.length>0?207:200})},w=async(g,b)=>{if(M(g,"POST","PITR"),!o(g))throw new c("admin PITR endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403});const A=await na(g),{headers:I}=await i(g,b),E=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:A.args,functionPath:A.functionPath}),headers:I,method:"POST"});return n(d,A.shardKey??t,E)};return{[$s]:m,[Fs]:w,[Ks]:_,[Gs]:S,[Qs]:P,[Ws]:T}},oa=1,sa=0,aa=32,ia=512,ca=/^[a-z][\d_a-z*/-]{0,255}(?:@[a-z][\d_a-z*/-]{0,13})?=[\u0020-\u002B\u002D-\u003C\u003E-\u007E]{1,256}$/,da=e=>{if(e==null)return;const t=e.trim();if(t.length===0||t.length>ia)return;const n=t.split(",");if(!(n.length>aa)){for(const o of n)if(!ca.test(o.trim()))return;return t}},ua=e=>{const t=Or(e.headers.get("traceparent"));if(t===void 0)return;const n=da(e.headers.get("tracestate"));return{parentSpanId:t.parentSpanId,sampled:t.sampled,traceId:t.traceId,...n===void 0?{}:{traceState:n}}},Gt=(e,t={})=>{const n=ua(e),o=t.trustInbound===!0?n:void 0,s=be(8),i=o?.traceId??be(16),d=Dr(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?oa:sa,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[wo]=e.rayId)},la=(e,t)=>{let n;return()=>{if(n===void 0){const o=kr(e),s=t===void 0?void 0:t.cf;n=vr(Pr(o),Ir(o,s))}return n}},ha="/_lunora/admin/scheduled",fa="/_lunora/admin/scheduled/status",pa="/_lunora/admin/scheduled/ws",ma="/_lunora/admin/scheduled/cancel",wa="/_lunora/admin/scheduled/dead",ga="/_lunora/admin/scheduled/dead/retry",ya="/_lunora/admin/scheduled/dead/cancel",ba="/_lunora/admin/scheduled/pool/release",_a=e=>{const{checkWsAdmin:t,requireSchedulerNamespace:n,resolveSchedulerStub:o,schedulerInstanceName:s}=e,i=(m,_)=>S=>{if(S.method!=="GET")throw new c(`${_} endpoint requires GET`,{code:"METHOD_NOT_ALLOWED",status:405});const T=new URL(S.url).searchParams.get("cursor"),P=T===null||T===""?"":`?cursor=${encodeURIComponent(T)}`;return o(S).fetch(new Request(`https://scheduler.internal${m}${P}`,{method:"GET"}))},d=(m,_,S=_)=>async T=>{if(T.method!=="POST")throw new c(`${S} requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});const P=o(T),w=await oe(T,_);if(typeof w?.id!="string"||w.id==="")throw new c(`${_} 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 _=o(m),S=await oe(m,"Scheduled pool-release");if(typeof S?.pool!="string"||S.pool==="")throw new c("Scheduled pool-release requires a string `pool`",{code:"BAD_REQUEST",status:400});const T=typeof S.id=="string"&&S.id!==""?S.id:void 0;return _.fetch(new Request("https://scheduler.internal/complete",{body:JSON.stringify(T===void 0?{pool:S.pool}:{id:T,pool:S.pool}),headers:{"content-type":"application/json"},method:"POST"}))},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 _=n();return _e(_,s).fetch(new Request("https://scheduler.internal/ws",{headers:{Upgrade:"websocket"}}))};return{[ma]:d("/cancel","Scheduled-cancel","Scheduled-cancel endpoint"),[ya]:d("/dead/cancel","Scheduled dead-letter action"),[wa]:i("/dead","Scheduled dead-letter"),[ga]:d("/dead/retry","Scheduled dead-letter action"),[ha]:i("/list","Scheduled-list"),[ba]:f,[fa]:i("/status","Scheduler-status"),[pa]:h}},Ra="/_lunora/scheduled",In="/_lunora/queue",Pn=16*1048576,Ea=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"),_=typeof m?.cron=="string"?m.cron:"";if(_==="")throw new c("scheduled tick requires a `cron` expression",{code:"BAD_REQUEST",status:400});return await n({cron:_,noRetry:()=>{},scheduledTime:Date.now()},f,h),Response.json({cron:_,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",Pn);if(!Array.isArray(m?.messages))throw new c("queue dispatch requires a `messages` array",{code:"BAD_REQUEST",status:400});const _=typeof m.queue=="string"?m.queue:"",S=m.messages.filter(P=>typeof P=="object"&&P!==null&&typeof P.id=="string").map(P=>({body:P.body,id:P.id})),T=await o({messages:S,queue:_},f,h);return Response.json({retry:T?.retry??[]})};return{[In]:i,[Ra]:s}},Sa=(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=>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),Aa=e=>typeof e=="string"&&Object.hasOwn(rt,e),Oa=e=>{const t=Aa(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.`))}},va="/_lunora/admin/vector/indexes",Ia="/_lunora/admin/vector/query",Pa=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{[va]:o,[Ia]:s}},ka="/_lunora/admin/workflows/instances",Da="/_lunora/admin/workflows/instance",Na="/_lunora/admin/workflows/status",Ua={complete:!0,errored:!0,paused:!0,queued:!0,running:!0,terminated:!0,unknown:!0,waiting:!0,waitingForPause:!0},Ca=e=>e!==null&&Object.hasOwn(Ua,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})},Ba=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 _=Ve(h,"name"),S=Ca(h.searchParams.get("status"));return Response.json(await m.listInstances({page:Wt(h,"page"),perPage:Wt(h,"perPage"),status:S,workflowName:_}))},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:_}=m;if(_!=="pause"&&_!=="resume"&&_!=="terminate")throw new c("Workflows status action must be one of: pause, resume, terminate",{code:"BAD_REQUEST",status:400});return Response.json(await h.setInstanceStatus({action:_,instanceId:m.id,workflowName:m.name}))};return{[Da]:s,[ka]:o,[Na]:i}},xa={[On]:vn,[In]:Pn,[Gr]:Kr},Ha="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}))}),La=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",ja="/_lunora/rpc-batch",Ma="/_lunora/ws",Ae=(e,t,n)=>({resourceAttributes:la(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=yo(e.headers.get(mo)),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}},Xt="/_lunora/voice/",$a="/_lunora/admin/cron-jobs/run",Fa="/_lunora/admin/ws-token",Ka="/_lunora/admin/",Be="/_lunora/",Ga="/_lunora/migrate",Qa="/_lunora/status",Wa=e=>e.startsWith(Ka)||e===Ga,ke=e=>{if(Co(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,qt=(e,t)=>{const n=e.headers.get(Rt);if(n===null)return;const o=Ar(n);if(o===void 0)throw new c(`malformed ${Rt} 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",za="__lunora_admin__:recordAuthEvent",en="__lunora_admin__:listPushSubscriptions",Va=["/sign-in","/sign-up","/callback"],Ja=(e,t)=>{const n=t.endsWith("/")?t.slice(0,-1):t;if(!e.startsWith(`${n}/`))return!1;const o=e.slice(n.length);return Va.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=yr(n),i=s?n.code:"INTERNAL_SERVER_ERROR",d=s?n.status:500,{message:f,name:h,stack:m}=fo(n);return{durationMs:t,error:{code:i,message:f,name:h,status:d,...m===void 0?{}:{stack:m}},functionPath:e,ok:!1,...o.fanOut?{fanOut:{failed:0,shards:0,table:o.fanOut.table}}:{},...o.shardKey?{shardKey:o.shardKey}:{}}},kn=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},Dn=({identity:e})=>e!==null&&Er(kn(e)),Ya=e=>{if(Dn(e))throw new c("authentication token expired",{code:"TOKEN_EXPIRED",status:401});return e},Xa=e=>{if(!Dn(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,qa=e=>{const t=e?.queue;return typeof t=="string"&&t.length>0?t:"unknown"},ot=new WeakMap,Za=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"),_=e.headers.get("x-lunora-client-id"),S=e.headers.get("x-lunora-client-seq"),T=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),_&&(i["x-lunora-client-id"]=_),S&&(i["x-lunora-client-seq"]=S),T&&(i["x-lunora-base-seq"]=T);const P=Hr(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"]=Sr(w.userId);const g=kn(w);g!==void 0&&(i["x-lunora-identity-exp"]=String(g));const{userId:b,...A}=w,I=Object.keys(A).length>0?A:null;return I&&(i["x-lunora-identity"]=Tr(I)),{claims:I,headers:i,identity:w,userId:b}},ei=new Set(["concat","first","groupBy","max","min","rank","sum","topK"]),ti=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"||!ei.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},ni=(e,t)=>{e?.LUNORA_DEBUG_RPC&&console.warn(`[lunora:rpc] ${t.fanOut?"fan-out":`shard=${t.shardKey??"(root)"}`} ${t.functionPath}`)},Xe=(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}},ri=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=ti(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,oi=5e3,si=4096,ai=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,si),Ue.set(t,{expiresMs:n+oi,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"}),ii=["x-lunora-userid","x-lunora-identity","x-lunora-identity-exp","x-lunora-client-ip"],ci=(e,t)=>{for(const n of ii){e.delete(n);const o=t[n];o!==void 0&&e.set(n,o)}},qe=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 ci(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:Fo(t,n)},di=(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 Xr(`d1:${e}`,t);if(typeof n.list=="function"&&typeof n.head=="function"&&typeof n.createMultipartUpload=="function")return $e(`r2:${e}`,!0);if(typeof n.send=="function"&&typeof n.sendBatch=="function"&&typeof n.get!="function")return $e(`queue:${e}`,!0);if(typeof n.connectionString=="string")return $e(`hyperdrive:${e}`,!0)},ui=e=>{for(const t of Object.keys(e??{}))if(t.slice(t.indexOf(" ")+1).startsWith(Be))throw new c(`route "${t}" is under the reserved ${Be} 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})},li=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})},Nn=e=>{li(e);const t=Ta(e.trustInboundTraceContext),n=Oa(e.trustInboundTraceContext),o=e.defaultShardKey??"__root__",s=e.queryCoordinator??to({registry:no(e.resolveTableSharding,o)}),i=qr(e.resolveIdentity,e.identity),d=Fe(e.shardDO,e.jurisdiction),f=e.schedulerDO===void 0?void 0:Fe(e.schedulerDO,e.jurisdiction),h=e.voiceAgents===void 0?void 0:Object.fromEntries(Object.entries(e.voiceAgents).map(([r,a])=>[r,Fe(a,e.jurisdiction)]));let m=!1;const _=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.`))},S=async(r,a,l,u=e.shardRegion?.(a))=>_e(r,a,_(u)).fetch(l);let T;const P=()=>e.adminToken??T;let w;const g=r=>{const a=r??{};if(w??=rn(r,e.shardDO),T!==void 0||e.adminToken!==void 0)return;const l=a.LUNORA_ADMIN_TOKEN;typeof l=="string"&&l.length>0&&(T=l)},b=new WeakSet,A=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 Za(r,a,l,e.trustedClientIpHeader,u);return e.functions!==void 0&&(p.headers[dn]=cn),p},L=async(r,a,l,u)=>Ya(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 X=()=>{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=ra({defaultShard:o,forwardToShard:S,isAdmin:A,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 y=u.shardKey??o;p==="trusted"?await G(null,y,!0):y!==o&&await G(p.identity,y);const O=await S(d,y,new Request(new URL(po,r),{body:JSON.stringify({data:ye(l??null),stream:u.stream,topic:a}),headers:{"content-type":"application/json"},method:"POST"}));if(!O.ok)throw await La(O,a)},W=async(r,a,l,u,p,y)=>{ke(r);const O=xo({forwardedIdentity:p,mutationId:u,traceparent:y});return S(d,l,Ce(r,a,O))},le=async(r,a,l,u,p)=>{const y=jo(l.env,l.context?.exports,r,["create"]);if(y===void 0)throw new c(`${u} targets workflow "${r}", which is on neither ctx.exports nor env`,{code:"CRON_JOB_FAILED",status:500});if(ao(a))throw new c(`${u} params ${io}`,{code:"BAD_REQUEST",status:400});try{await y.create(p===void 0?{params:a}:{id:p,params:a})}catch(O){if(!lo(O))throw O}},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(!A(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},xe=async(r,a,l,u,p,y)=>{const O=e.cronJobs?.[r];if(!O)return 0;for(const D of O)try{await ae(D,a,l,y)}catch(N){u.push(p(N))}return O.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 y=Object.values(e.cronJobs).flat().find(O=>O.name===p);if(!y)throw new c(`no cron job named "${p}" is registered`,{code:"CRON_JOB_NOT_FOUND",status:404});return await ae(y,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{}},Un=async(r,a,l)=>{M(r,"POST","Scheduler dispatch");const u=await fn(r),p=a??{},y=typeof p.LUNORA_SCHEDULER_SECRET=="string"?p.LUNORA_SCHEDULER_SECRET:void 0,O=e.adminToken??(typeof p.LUNORA_ADMIN_TOKEN=="string"?p.LUNORA_ADMIN_TOKEN:void 0);if(!await Bo(r,u,{adminToken:O,schedulerSecret:y}))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??{},v=R.args??{},k=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,v,{context:l,env:a},"scheduled workflow",k),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,$=Ho(r),x=await W(R.functionPath,v,H,k,$,r.headers.get("traceparent")??void 0);return await dt(R),x},Cn=Wo({assertAdmin:z,getReader:()=>e.authAuditReader}),Bn=zo({assertAdmin:z,getMove:()=>e.authJurisdictionMove}),xn=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,y=a?.limit,O=u==="fcm"||u==="web-push"?u:void 0,D=typeof p=="string"&&p!==""?p:void 0,N=typeof y=="number"&&Number.isFinite(y)?Math.trunc(y):0,R=N>0?Math.min(N,1e3):1e3,k=(await l.list({kind:O,limit:R,userId:D})).filter(H=>O!==void 0&&H.kind!==O?!1:D===void 0||(H.userId??null)===D).map(({keys:H,token:$,...x})=>x);return Response.json({result:ye({subscriptions:k})},{headers:{"content-type":"application/json"},status:200})},Hn=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?Cn(r,a.args??{}):a.functionPath===en?xn(r,a.args):Bn(r,a.functionPath,a.args??{})},Ln=ys({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)=>Sn(e,s,r,a,d),streamingImport:(r,a)=>Ss(r,e,s,a,d),syncGlobals:e.syncGlobals}),He=(r,a)=>{const l=r.searchParams.get(a);return l===null||l===""?void 0:l},Le=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),y=u===null?void 0:Number.parseInt(u,10);return{limit:p!==void 0&&Number.isFinite(p)&&p>=0?p:void 0,offset:y!==void 0&&Number.isFinite(y)&&y>=0?y: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},jn=_a({checkWsAdmin:async r=>A(r)||sn(r,P()),requireSchedulerNamespace:ut,resolveSchedulerStub:r=>(z(r),_e(ut(),e.schedulerInstanceName??"default")),schedulerInstanceName:e.schedulerInstanceName??"default"}),Mn=Ba({assertAdmin:z,resolveWorkflowsClient:e.workflowsClient??(()=>{})}),$n=Fr({assertAdmin:z,parsePaging:Le,queryParameter:He,readBodyBytes:Br,requireAdminOption:ie,storage:{storageBuckets:e.storageBuckets,storageDelete:e.storageDelete,storageDownload:e.storageDownload,storageList:e.storageList,storageSignedUrl:e.storageSignedUrl,storageUpload:e.storageUpload}}),Fn=is({options:e,readJsonBody:ne,requireAdminOption:ie}),Kn=Pa({readJsonBody:ne,requireAdminOption:ie,vectorIntrospector:e.vectorIntrospector}),Gn=Ms({kvIntrospector:e.kvIntrospector,readJsonBody:ne,requireAdminOption:ie}),Qn=Zr({logArchive:e.logArchive,readJsonBody:ne,requireAdminOption:ie}),Wn=Hs({assertAdmin:z,options:{cronJobs:e.cronJobs,functions:e.functions,globalIntrospector:e.globalIntrospector,architecture:e.architecture,openApiSpec:e.openApiSpec,openRpcSpec:e.openRpcSpec},parsePaging:Le,queryParameter:He,requireAdminOption:ie}),zn=r=>{const a=[],l=d??r?.SHARD;if(l!==void 0&&a.push(Yr("durable-object:default",l,o)),e.health?.disableBindingProbes!==!0)for(const[u,p]of Object.entries(r??{})){const y=di(u,p);y!==void 0&&a.push(y)}for(const u of e.health?.probes??[])a.push(u);return a},Vn=Jr({appName:e.health?.appName,appVersion:e.health?.appVersion,auth:e.health?.auth??"public",cacheTtlMs:e.health?.cacheTtlMs,isAdmin:A,resolveProbes:zn}),Jn=r=>{const a=R=>"args"in R?{...R,args:Ze(R.args)}:R,l=e.schedulerInstanceName??"default",u=()=>_e(r,l),p=async(R,v)=>{const k=await u().fetch(new Request(`https://scheduler.internal${R}`,v));if(!k.ok)throw new c(`ctx.scheduler: SchedulerDO ${R} failed (${String(k.status)}): ${await k.text()}`,{code:"INTERNAL",status:500});return await k.json()},y=async(R,v)=>await p(R,{body:JSON.stringify(v),headers:{"content-type":"application/json"},method:"POST"}),O=R=>{const v=R;if(v==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 v.binding=="string"&&v.binding.length>0)return{workflow:v.binding};if(typeof v.__lunoraRef=="string")return{functionPath:v.__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})},D=async()=>(await co(async v=>p(v===void 0?"/list":`/list?cursor=${encodeURIComponent(v)}`,{method:"GET"}))).map(v=>a(v)),N=async(R,v,k={})=>{const H=O(v),{id:$}=await y("/schedule",{args:_r("ctx.scheduler",String(H.functionPath??H.workflow),k),scheduledFor:Math.ceil(R),...H});return $};return{cancel:async R=>await y("/cancel",{id:R}),get:async R=>{const v=await p(`/get?id=${encodeURIComponent(R)}`,{method:"GET"});return v.record===void 0?null:a(v.record)},list:D,runAfter:async(R,v,k)=>{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,v,k)},runAt:async(R,v,k)=>{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,v,k)}}},Yn=async(r,a,l)=>{const{claims:u,headers:p,identity:y,userId:O}=Xa(await E(r,a,i)),D=Ae(a,r,k=>l.waitUntil?.(k)),N=k=>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),k!==o&&await G(y,k);const q=await ve(r,x,ye($),k,{...p,"x-lunora-system":"1"},D),Z=await q.json();if(Z.error)throw new c(Z.error.message??"shard RPC failed",{code:Z.error.code??"INTERNAL",status:q.status});return Ze(Z.result)},R=N(o),v=async(k,H,$={})=>{k!==void 0&&k!==o&&await G(y,k);const x=new Headers;for(const[q,Z]of Object.entries($.headers??{}))q.toLowerCase().startsWith("x-lunora-")||x.set(q,Z);for(const[q,Z]of Object.entries(p))x.set(q,Z);return S(d,k??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:O},cache:l.cache,fetch:globalThis.fetch.bind(globalThis),fetchShard:v,forShard:k=>{const H=N(k);return{runAction:H,runMutation:H,runQuery:H}},live:e.liveStreams===!1?Vt():{publish:(k,H,$)=>se(r.url,k,H,$,{identity:y})},runAction:R,runMutation:R,runQuery:R,...f===void 0?{}:{scheduler:Jn(f)},...l.waitUntil===void 0?{}:{waitUntil:l.waitUntil.bind(l)},...e.storage===void 0?{}:{storage:so(e.storage(a,new URL(r.url).origin))}}},Xn=async(r,a,l)=>{if(!e.httpRouter)return;const u=await Yn(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(!qe(r))throw new c("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});const u=vt(r,de);if(u)return u;const p=l.searchParams.get("shard")??o,{headers:y,identity:O}=await E(r,a,i),D=A(r)||await sn(r,P());await G(O,p,D);const N=on(r,y),R=rn(a,e.shardDO);if(R!==void 0){N.set("x-lunora-shard-binding",R);const v=lt.has(l.pathname)?0:await ai(d,p);if(v>0){const k=To(p,Math.floor(Math.random()*v));return S(d,k,new Request(r,{headers:N}),Dt(r))}}return S(d,p,new Request(r,{headers:N}))},qn=async(r,a,l)=>{if(h===void 0)return new Response("Not found",{status:404});if(!qe(r))return new Response("Expected a WebSocket upgrade",{headers:{allow:"GET"},status:426});const u=vt(r,de);if(u)return u;let p;try{p=decodeURIComponent(l.pathname.slice(Xt.length))}catch{return new Response("Unknown voice agent",{status:404})}const y=Object.hasOwn(h,p)?h[p]:void 0;if(y===void 0)return new Response("Unknown voice agent",{status:404});const O=l.searchParams.get("threadKey");if(O===null||O.length===0)return new Response("Missing threadKey",{status:400});const{headers:D,identity:N}=await E(r,a,i);if(e.authorizeShard){if(!await De(e.authorizeShard({identity:N,shardKey:O})))throw new c("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else V("shard");const R=on(r,D);return S(y,O,new Request(r,{headers:R}))},Zn=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")},Oe=async(r,a)=>{if(!(!r.fanOut&&r.functionPath.startsWith("__lunora_admin__:"))){if(r.fanOut){await Zn(r.fanOut,r.functionPath,a);return}await G(a,r.shardKey??o)}},er=(r,a,l)=>{if(e.replicaReads!==!0)return;if(e.functions===void 0){X();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:Ao(l,u),region:u}},tr=async(r,a,l,u,p)=>{const y=er(r,a,u);if(y!==void 0){const O={...p,"x-lunora-replica-read":"1",...w===void 0?{}:{"x-lunora-shard-binding":w}},D=Oo(r.headers.get("x-lunora-min-seq"));D!==void 0&&(O["x-lunora-min-seq"]=String(D));const N=await S(d,y.name,Ce(a,l,O),y.region);if(N.status!==421)return N}return S(d,u,Ce(a,l,p))},ve=async(r,a,l,u,p,y)=>{const O=Date.now(),{observability:D,sampling:N}=e,R=Ye(r),{decision:v,ignoredUpstream:k,trace:H}=Gt(r,{...R.rayId===void 0?{}:{rayId:R.rayId},...N===void 0?{}:{sampling:N},trustInbound:t(r)});k&&n(r);const $={...p,[St]:v.keepErrors?"1":"0",[It]:"1"};Qt(H,$);try{const x=await tr(r,a,l,u,$),q=kt(x.headers.get(Pt));ue(D,{...R,...Yt(H),durationMs:Date.now()-O,functionPath:a,ok:x.ok,shardKey:u,...x.ok?{}:{error:{...q,code:q?.code??"SHARD_ERROR",message:q?.message??`shard returned ${String(x.status)}`,status:x.status}}},y,void 0,{isTraced:H.sampled,keepErrors:v.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(Pt),Z}catch(x){throw ue(D,{...R,...Yt(H),...Ne(a,Date.now()-O,x,{shardKey:u})},y,void 0,{isTraced:H.sampled,keepErrors:v.keepErrors}),x}},nr=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)},rr=async(r,a,l)=>{M(r,"POST","RPC");const u=await ri(r);ni(a,u),nr(u);const p=await Hn(r,u);if(p!==void 0)return p;const{headers:y,identity:O}=await L(r,a,i);qt(r,O),await Oe(u,O);const D=Xe(u,e);{const N=Date.now(),{observability:R}=e,v=Ye(r),k=Ae(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:y});return ue(R,{durationMs:Date.now()-N,fanOut:{failed:x.failed,shards:x.ok+x.failed,table:u.fanOut.table},functionPath:u.functionPath,...v,ok:!0},k),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}}),...v},k),x}const H=u.shardKey??o,$=()=>ve(r,u.functionPath,u.args??{},H,y,k);return D&&e.x402Charge?e.x402Charge(r,{functionPath:u.functionPath,price:D.price},$,Je(l)):$()}},or=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:y,identity:O}=await L(r,a,i);qt(r,O);const D=ds(p,o);for(const F of D.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([...D.entries()].flatMap(([F,Q])=>Q.map(ee=>Oe({args:ee.args,functionPath:ee.functionPath,shardKey:F},O))));const{observability:N,sampling:R}=e,v=Ae(a,r,l&&(F=>l.waitUntil?.(F))),k=Ye(r),{decision:H,ignoredUpstream:$,trace:x}=Gt(r,{...k.rayId===void 0?{}:{rayId:k.rayId},...R===void 0?{}:{sampling:R},trustInbound:t(r)});$&&n(r);const q={isTraced:x.sampled,keepErrors:H.keepErrors},Z=F=>{const Q={...y,"content-type":"application/json",[St]:H.keepErrors?"1":"0",[It]:"1"};return Qt({...x,spanId:F},Q),Q},je=F=>({parentSpanId:F,spanId:be(8),traceFlags:x.traceFlags,traceId:x.traceId}),Pe=[],Me=[],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),v,void 0,q),Pe.push(wt(te,Q,ee,he))},wr=(F,Q,ee,he,we,te)=>{for(const Re of F){const Ee=we.get(Re.id),fe=Ee?.status??te,pe=fe<400,Se=pe?void 0:kt(Ee?.errorDetail);ue(N,{durationMs:he,functionPath:Re.functionPath,...k,...je(ee),ok:pe,shardKey:Q,...pe?{}:{error:{...Se,code:Se?.code??"SHARD_ERROR",message:Se?.message??`batched call returned ${String(fe)}`,status:fe}}},v,void 0,q)}};await Promise.all([...D.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 S(d,F,he)}catch(Y){const Te=Date.now()-we,{body:_t}=br(Y,{fallbackCode:"SHARD_UNAVAILABLE",redactedMessage:"shard unavailable"});gt(Q,502,_t.code,_t.message,gr=>({...Ne(gr.functionPath,Te,Y,{shardKey:F}),...k,...je(ee)}));return}const Re=Date.now()-we,Ee=te.headers.get("x-d1-bookmark");Ee&&Me.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_ERROR",Y,Te=>({durationMs:Re,error:{code:"SHARD_ERROR",message:Y,status:te.status},functionPath:Te.functionPath,...k,...je(ee),ok:!1,shardKey:F}));return}const pe=Array.isArray(fe.results)?fe.results:[],Se=new Set(pe.map(Y=>Y.id));wr(Q,F,ee,Re,new Map(pe.map(Y=>[Y.id,Y])),te.status),Pe.push(...pe.map(({errorDetail:Y,...Te})=>Te));for(const Y of Q)Se.has(Y.id)||Pe.push(wt(Y,te.status,"SHARD_ERROR",`shard batch omitted result for call ${String(Y.id)}`))}));const yt={"content-type":"application/json"},[bt]=Me;return Me.length===1&&bt!==void 0&&(yt["x-d1-bookmark"]=bt),Response.json({results:Pe},{headers:yt,status:200})},sr=async(r,a,l,u={},p={})=>{try{const y=l.__lunoraRef;if(typeof y!="string")throw new c("serverQuery: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});ke(y);const{headers:O,identity:D}=await L(r,a,i,p.context),N={args:u,functionPath:y,shardKey:p.shardKey};await Oe(N,D);const R=p.shardKey??o,v=Ae(a,r,p.waitUntil),k=()=>ve(r,y,u,R,O,v),H=Xe(N,e);return H&&e.x402Charge?await e.x402Charge(r,{functionPath:y,price:H.price},k,Je(p.waitUntil?{waitUntil:p.waitUntil}:p.context)):await k()}catch(y){return Tt(y)}},ft=async(r,a,l)=>{const{observability:u}=e,p=Date.now(),y=be(16),O=be(8),D=nn(a),N=un(y,O,!0);try{const R=await l(N);return ue(u,{durationMs:Date.now()-p,functionPath:r,ok:!0,spanId:O,traceId:y},D),R}catch(R){throw ue(u,{...Ne(r,Date.now()-p,R,{}),spanId:O,traceId:y},D),R}finally{Et(u,D)}},pt=async(r,a,l,u)=>{g(a);const p=[],y=v=>v instanceof Error?v:new Error(String(v)),O=e.crons?.[r.cron];if(O)try{await O(r,a,l)}catch(v){p.push(y(v))}const D=await xe(r.cron,a,l,p,y,u),N=!!e.backupStore&&e.backupCron!==void 0&&e.backupCron===r.cron;if(N)try{await rs(e,s,d,P(),r)}catch(v){p.push(y(v))}if(!O&&D===0&&!N){const v=[...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: ${v.length===0?"(none)":v.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)`)},ar=Ea({assertAdmin:z,dispatchScheduled:pt,queueHandler:e.queueHandler}),ir=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 S(d,o,Ce(za,{outcome:a},{authorization:`Bearer ${u}`,"content-type":"application/json"}))}catch{}},cr=async(r,a,l,u)=>{if(!e.authHandler)return;const p=e.authBasePath??Zt,y=tn(l.pathname,p)?xr(r):void 0;let O;try{O=await e.authHandler(y?.request??r)}catch(D){throw y?.overflowed()?new c("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413}):D}if(y?.overflowed())throw new c("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});if(O)return Ja(l.pathname,p)&&u.waitUntil?.(ir(a,O.status>=400?"fail":"ok")),O},dr=async({args:r,env:a,functionPath:l,request:u,shardKey:p,waitUntil:y})=>{hn(r,"REST");const O={functionPath:l,...p===void 0?{}:{shardKey:p}},{headers:D,identity:N}=await L(u,a,i);await Oe(O,N);const R=p??o,v=Ae(a,u,y),k=()=>ve(u,l,r,R,D,v),H=Xe(O,e);return H&&e.x402Charge?e.x402Charge(u,{functionPath:l,price:H.price},k,Je({waitUntil:y})):k()},ur=Cr({functions:e.functions??{},invoke:dr,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;ui(Ie);const lr={[Qa]: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"}}),[Ma]:(r,a,l)=>ht(r,a,l),[Jt]:(r,a,l,u)=>rr(r,a,u),[ja]:(r,a,l,u)=>or(r,a,u),[No]:(r,a,l,u)=>Un(r,a,u),[$a]:(r,a,l,u)=>ce(r,a,u),[Fa]: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 $o(a);return Response.json(l,{headers:{"cache-control":"no-store"}})},...J,...Ln,...jn,...Mn,...$n,...Fn,...Kn,...Gn,...Qn,...Wn,...Vn,...ur,...Qo({assertAdmin:z,getAuthAdmin:()=>e.authAdmin,parsePaging:Le,queryParameter:He,readJsonBody:ne})};let de=Ot(e.security),mt=!1;const hr=r=>{mt||(mt=!0,de=Ot(e.security,r??{}))},fr=async(r,a)=>{Wa(a)&&await I(r)},pr=(r,a)=>{if(!(a.pathname.startsWith(Be)||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=xa[a.pathname]??ln;if(Number.isFinite(u)&&u>p)throw new c("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413})},mr=async(r,a,l)=>{ot.set(r,l);const u=new URL(r.url);pr(r,u);const p=await cr(r,a,u,l);if(p)return p;if(lt.has(u.pathname)&&r.method==="GET"&&qe(r))return ht(r,a,u);if(Ie){const R=`${r.method} ${u.pathname}`,v=Ie[R]??Ie[u.pathname];if(v)return v(r,a,l)}const y=ar[u.pathname];if(y)return y(r,a,l);const O=lr[u.pathname];if(O)return await fr(r,u.pathname),O(r,a,u,l);if(e.voiceAgents!==void 0&&u.pathname.startsWith(Xt))return qn(r,a,u);if(u.pathname.startsWith(Be))return new Response("Not found",{status:404});const D=await Xn(r,a,l);if(D&&D.status!==404)return D;const N=await e.authDiscoveryHandler?.(r);return N?(await D?.body?.cancel(),N):D??new Response("Not found",{status:404})};return{async fetch(r,a,l){e.passThroughOnException&&l.passThroughOnException?.(),hr(a),g(a);const u=ro(r,de);if(u)return u;const p=oo(r,de);if(p)return Ke(p,r,de);try{const y=await mr(r,a,l);return Ke(y,r,de)}catch(y){return Ke(Tt(y),r,de)}finally{Et(e.observability,nn(l))}},async queue(r,a,l){await ft(`queue:${qa(r)}`,l,async u=>{const p=e.liveStreams===!1?Vt():{publish:(y,O,D)=>se(Ha,y,O,D,"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:sr}},hi=e=>Nn(e),fi=e=>typeof e=="function"?{fetch:e}:e,pi=e=>!!e.backupCron||Object.keys(e.crons??{}).length>0||Object.keys(e.cronJobs??{}).length>0,mi=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}:{}},ji=(e,t)=>{const n=fi(e),{email:o,queue:s,scheduled:i}=mi(e),d=h=>{const _={...hi({...h,httpRouter:n})};return i!==void 0&&!pi(h)&&(_.scheduled=async(S,T,P)=>{await i(S,T,P)}),s!==void 0&&h.queue===void 0&&(_.queue=async(S,T,P)=>{await s(S,T,P)}),o!==void 0&&(_.email=async(S,T,P)=>{await o(S,T,P)}),_};if(typeof t!="function")return d(t);const f=t;return{fetch:(h,m,_)=>d(f(m)).fetch(h,m,_),queue:(h,m,_)=>d(f(m)).queue?.(h,m,_)??Promise.resolve(),scheduled:(h,m,_)=>d(f(m)).scheduled(h,m,_),serverQuery:(h,m,_,S,T)=>d(f(m)).serverQuery(h,m,_,S,T),...o===void 0?{}:{email:(h,m,_)=>d(f(m)).email?.(h,m,_)??Promise.resolve()}}},wi=(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}},Mi=(e={})=>(t,n,o)=>Nn(wi(e,n)).fetch(t,n,o??Rr),$i=e=>e;export{nt as COPY_AUTH_TO_JURISDICTION_OP,Ct as GET_AUTH_AUDIT_LOG_OP,Rr as NOOP_EXECUTION_CONTEXT,En as PURGE_UNPINNED_AUTH_OP,Gi as composeIdentityResolvers,hi as composeWorker,Mi as createLunoraHandler,Nn as createWorker,$i as defineRpcEnvelope,ai as probeRelayCount,wi as resolveLunoraOptions,Qi as routeIdentityResolvers,ji 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.217",
|
|
4
4
|
"description": "Lunora Worker runtime: the RPC router, shard resolver, and query coordinator",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cloudflare",
|
|
@@ -46,10 +46,10 @@
|
|
|
46
46
|
"access": "public"
|
|
47
47
|
},
|
|
48
48
|
"dependencies": {
|
|
49
|
-
"@lunora/bindings": "1.0.0-alpha.
|
|
49
|
+
"@lunora/bindings": "1.0.0-alpha.122",
|
|
50
50
|
"@lunora/errors": ">=1.0.0-alpha.51 <2.0.0-0",
|
|
51
|
-
"@lunora/observability": "1.0.0-alpha.
|
|
52
|
-
"@lunora/platform": "1.0.0-alpha.
|
|
51
|
+
"@lunora/observability": "1.0.0-alpha.151",
|
|
52
|
+
"@lunora/platform": "1.0.0-alpha.69",
|
|
53
53
|
"@lunora/wire": "1.0.0-alpha.1"
|
|
54
54
|
},
|
|
55
55
|
"peerDependencies": {
|
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
import{isLunoraError as wr,toErrorBody as gr}from"@lunora/errors";import{encodeWire as ye,decodeWire as Xe,encodeArgsOrThrow as yr}from"@lunora/wire";import{e as rn}from"./evict-oldest-BNXsKx4s.mjs";import{NOOP_EXECUTION_CONTEXT as br}from"./NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{i as _r,e as Rr,a as Er,E as yt,d as Sr}from"./identity-header-pR617HTs.mjs";import{O as on,a as sn}from"./origin-paywall-B6eOO67m.mjs";import{o as be,b as an,p as Tr,m as Ar,d as Or,a as vr,r as Ir}from"./otlp-resource-BwFJnvwB.mjs";import{r as Pr,f as bt,a as ue,S as _t}from"./observability-DgurIZIR.mjs";import{t as kr,f as Dr}from"./base64-Bl1_r2k1.mjs";import{d as ne,e as oe,M as cn,b as Nr,f as Ur,g as dn,w as Cr,h as un,t as Br}from"./rest-routes-DQkyqlym.mjs";import{LunoraError as c,toErrorResponse as Rt}from"./LunoraError-DksAgIpa.mjs";import{a as M,m as ge}from"./method-guard-BG_vJNTl.mjs";import{normalizeBackupPrefix as ot,BACKUP_KEY_PREFIX as st,isBackupManifestKey as xr,backupObjectKeyOfManifest as ln,backupObjectKey as Hr,backupManifestKey as Lr}from"./BACKUP_KEY_PREFIX-BOtSu-_3.mjs";import{toHex as jr,buildStorageAdminRoutes as Mr,STORAGE_UPLOAD_MAX_BODY_BYTES as $r,STORAGE_PATH as Fr}from"./STORAGE_UPLOAD_MAX_BODY_BYTES-BIiV5kqV.mjs";import{b as Kr,e as Gr,f as Et,g as Qr,h as Wr}from"./export-tap-C2B_SATf.mjs";import{buildHealthRoutes as zr,durableObjectProbe as Vr,d1Probe as Jr,presenceProbe as $e}from"./HEALTH_PATH-CAX2UeFy.mjs";import{wrapResolverWithContract as Yr}from"./composeIdentityResolvers-BHZ4jH8o.mjs";import{composeIdentityResolvers as Fi,routeIdentityResolvers as Ki}from"./composeIdentityResolvers-BHZ4jH8o.mjs";import{buildLogArchiveAdminRoutes as qr}from"./LOG_ARCHIVE_PATH-Hmjpz_Ko.mjs";import{pruneShardRegistry as Xr,createQueryCoordinator as Zr,createDefaultShardRegistry as eo}from"./createQueryCoordinator-es4jrL6Q.mjs";import{resolveShard as _e,applyJurisdiction as Fe}from"./applyJurisdiction-D4vryLhj.mjs";import{resolveSecurity as St,handleCorsPreflight as to,enforceOrigin as no,decorateResponse as Ke,enforceWebSocketOrigin as Tt}from"./decorateResponse-CRBbtPYT.mjs";const ro=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},hn="__lunoraBranch",oo=e=>typeof e=="object"&&e!==null&&Object.hasOwn(e,hn),so=`may not contain the reserved workflow branch-marker key ("${hn}")`,ao=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}},io=/already[\s_-]?exists/iu,co=e=>io.test(e instanceof Error?e.message:String(e)),At="x-lunora-want-error-detail",Ot="x-lunora-error-detail",uo=8192,lo=e=>{if(!(e instanceof Error))return{message:String(e),name:typeof e};const{code:t}=e;return{...typeof t=="string"?{code:t}:{},message:e.message,name:e.name,...e.stack===void 0?{}:{stack:e.stack.slice(0,uo)}}},vt=e=>{if(e!=null)try{const t=JSON.parse(decodeURIComponent(e));return typeof t?.message=="string"&&typeof t.name=="string"?t:void 0}catch{return}},ho="/_lunora/live/publish",fo="cf-ray",po="x-lunora-ray-id",mo=/^([\da-f]{16})(?:-[a-z]{3,4})?$/i,wo=e=>e==null?void 0:mo.exec(e.trim())?.[1]?.toLowerCase(),go=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"];new Set(go);const yo=new Set(["AE","BH","IL","IQ","IR","JO","KW","LB","OM","PS","QA","SA","SY","TR","YE"]),bo=-100,_o=15,Ro=e=>{const t=Number(e.longitude??Number.NaN);switch(e.continent){case"AF":return"afr";case"AS":return e.country!==void 0&&yo.has(e.country)?"me":"apac";case"EU":return Number.isFinite(t)&&t>_o?"eeur":"weur";case"NA":return Number.isFinite(t)&&t<bo?"wnam":"enam";case"OC":return"oc";case"SA":return"sam";default:return}},It=e=>{const t=e.cf;return t===void 0?void 0:Ro(t)},Ze="::relay::",Eo=(e,t)=>`${e}${Ze}${String(t)}`,et="::replica::",So=(e,t)=>`${e}${et}${t}`,To=e=>{if(e==null||!/^\d+$/.test(e))return;const t=Number.parseInt(e,10);return Number.isSafeInteger(t)&&t>0?t:void 0},fn=(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},Ao=(e,t,n,r)=>{const s=e.get(t);if(s!==void 0)return s;rn(e,r);const i=n().catch(d=>{throw e.get(t)===i&&e.delete(t),d});return e.set(t,i),i},at=new TextEncoder,Oo=Array.from({length:32},(e,t)=>t);new RegExp(`[${Oo.map(e=>String.fromCodePoint(e)).join("")}]`,"u");const vo=64,Io=new Map,pn=async e=>Ao(Io,e,async()=>crypto.subtle.importKey("raw",at.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]),vo),mn=async(e,t)=>{const n=await pn(e),r=await crypto.subtle.sign("HMAC",n,at.encode(t));return kr(new Uint8Array(r))},Po=async(e,t,n)=>{const r=await pn(e);return crypto.subtle.verify("HMAC",r,n,at.encode(t))},ko="/_lunora/scheduler/dispatch",Do="__lunora_relation__:",No=e=>e.startsWith(Do),wn=(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:fn(t,s.join(" ").trim())},Uo=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?fn(await mn(s,t),r):wn(e,n.adminToken)},Co=({forwardedIdentity:e,mutationId:t,traceparent:n})=>{const r={"content-type":"application/json",[sn]:on,"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},Bo=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}}},xo=(e,t,n)=>e?.[n]??t?.[n],Ho=(e,t,n,r)=>{const s=xo(e,t,n);if(!(typeof s!="object"||s===null))return r.every(i=>typeof s[i]=="function")?s:void 0},gn="v1",Lo=6e4,jo=async(e,t={})=>{const n=(t.now??Date.now())+(t.ttlMs??Lo),r=`${gn}.${String(n)}`,s=await mn(e,r);return{expiresAtMs:n,token:`${r}.${s}`}},Mo=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!==gn||d.length===0)return!1;const f=Number(i);if(!Number.isFinite(f)||f<=n)return!1;let h;try{h=Dr(d)}catch{return!1}return Po(e,`${s}.${i}`,h)},U="/_lunora/admin/auth",$o={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},yn=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,Ge=(e,t)=>{const n=e[t];return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:void 0},Pt=e=>{const t=yn(e.role);if(t===void 0||typeof t=="string"&&t.trim()==="")throw new c("`role` is required",{code:"BAD_REQUEST",status:400});return t},kt=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},Fo={[`${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:Ge(e,"data"),email:B(e,"email"),name:B(e,"name"),password:re(e,"password"),role:yn(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:Pt(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:Ge(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:Ge(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:Pt(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:kt(e),role:B(e,"role")}),http:"POST",method:"createOrgRole"},[`${U}/organizations/roles/update`]:{build:({body:e})=>({permission:kt(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"}},Ko=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:$o[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:T=>e.queryParameter(h,T)},_=i.build(m),S=await t(()=>f(_));return Response.json(i.returns==="void"?{ok:!0}:S,{headers:{"cache-control":"no-store","content-type":"application/json"},status:200})},r={};for(const[s,i]of Object.entries(Fo))r[s]=d=>n(d,i);return r},Dt="__lunora_admin__:getAuthAuditLog",Nt=e=>typeof e=="string"&&e!==""?e:void 0,Ut=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0,Go=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=Nt(r.actorId),d=Nt(r.event),f=Ut(r.sinceSeq),h=Ut(r.limit),m={...i===void 0?{}:{actorId:i},...d===void 0?{}:{event:d},...f===void 0?{}:{sinceSeq:f},...h===void 0?{}:{limit:h}};let _;try{_=await s.read(m)}catch(T){throw T instanceof c?T:(console.error("[lunora] auth audit read failed:",T),new c("auth audit read failed",{code:"AUTH_AUDIT_READ_FAILED",status:500}))}const S={entries:_};return Response.json({result:ye(S)},{headers:{"content-type":"application/json"},status:200})},tt="__lunora_admin__:copyAuthToJurisdiction",bn="__lunora_admin__:purgeUnpinnedAuth",Qo=e=>async(t,n,r)=>{if(n!==tt&&n!==bn)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===tt?await s.copy({force:r.force===!0}):await s.purge();return Response.json({result:ye(i)},{headers:{"content-type":"application/json"},status:200})},Wo=(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}},zo=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??[])},_n=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}=Wo(e,i),h=await zo(t,n,i,f,s,e.defaultShardKey??"__root__"),m=e.exportGlobals,_=r===void 0||d.length>0;return(async function*(){yield*h,_&&m&&(yield*m({tables:d}))})()},Vo=async(e,t,n,r,s,i)=>{for await(const d of await _n(e,t,n,r,i))s(d)},Jo=new TextEncoder,Yo=1e3,Rn=10,qo=200,Ct=8,En="lunoraBackupCron",Bt=24*1048576,xt=e=>{const t=e.slice(0,Rn).map(r=>ln(r)),n=e.length-t.length;return`${t.join(", ")}${n>0?` (+${String(n)} more)`:""}`},Xo=(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},it=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<Yo;d+=1){const f=await e.list({cursor:i,include:["customMetadata"],prefix:t});for(const h of f.objects)xr(h.key)&&h.customMetadata?.[En]===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)}},Zo=async(e,t,n,r,s)=>{const{stale:i}=await it(e,t,n,r),d=new Set(s),f=i.filter(P=>d.has(P)),h=f.slice(0,qo),m=i.length-h.length,_=s.length-f.length;if(h.length===0)return{deleted:[],failed:[],ignored:_,remaining:m};const S=[],T=[];for(let P=0;P<h.length;P+=Ct){const w=await Promise.allSettled(h.slice(P,P+Ct).map(async g=>(await e.delete(ln(g)),await e.delete(g),g)));for(const[g,b]of w.entries())b.status==="fulfilled"?S.push(b.value):T.push(h[P+g])}return S.length>0&&console.info(`[lunora] backup prune kept the newest ${String(n)} and deleted ${String(S.length)}: ${xt(S)}`),T.length>0&&console.warn(`[lunora] backup prune failed to remove ${String(T.length)}: ${xt(T)}`),{deleted:S,failed:T,ignored:_,remaining:m}},es=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=ot(e.backupPrefix??st),r=e.backupCron,{eligible:s,stale:i}=r===void 0?{eligible:0,stale:[]}:await it(t,n,e.backupRetain,r);return{cron:r,eligible:s,keep:e.backupRetain??0,prefix:n,wouldDelete:i}},ts=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,_=[];await Vo(e,t,d,f,I=>{const E=Jo.encode(`${JSON.stringify(I)}
|
|
2
|
-
`);if(h+=1,m+=E.byteLength,m>Bt)throw new c(`scheduled backup reached ${String(m)} bytes of NDJSON, past the ${String(Bt)}-byte limit for a snapshot assembled inside a Worker — nothing was written. Narrow it with \`backupTables\`, or take this snapshot off-platform with \`lunora backup create --bucket\`.`,{code:"BACKUP_TOO_LARGE",status:507});_.push(E)},n);const T=ot(e.backupPrefix??st),P=new Date(s.scheduledTime).toISOString(),w=Hr(T,P),g=Xo(_,m);_=[];const b=jr(await crypto.subtle.digest("SHA-256",g));await i.put(w,g,{httpMetadata:{contentType:"application/x-ndjson"},sha256:b});const A={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(Lr(w),`${JSON.stringify(A,void 0,2)}
|
|
3
|
-
`,{customMetadata:{[En]:s.cron},httpMetadata:{contentType:"application/json"}});try{const{stale:I}=await it(i,T,e.backupRetain,s.cron);if(I.length>0){const E=I.slice(0,Rn),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)}},ns=async(e,t)=>{const n=e.backupStore;if(!n)throw new c("backup prune requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});const r=e.backupCron,s=e.backupRetain;if(r===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 Zo(n,ot(e.backupPrefix??st),s,r,t)},rs="/_lunora/admin/backup/retention",os="/_lunora/admin/backup/prune",ss=e=>{const{options:t,readJsonBody:n,requireAdminOption:r}=e,s=(f,h)=>{r(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 es(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 ns(t,h),{headers:{"cache-control":"no-store"}})};return{[os]:d,[rs]:i}},Ht=500,as=(e,t,n)=>{if(typeof e!="object"||e===null||Array.isArray(e))throw new c("each batch call must be an object",{code:"BAD_REQUEST",status:400});const r=e;if(typeof r.functionPath!="string")throw new c("each batch call needs a string `functionPath`",{code:"BAD_REQUEST",status:400});if(r.functionPath.startsWith("__lunora_relation__:")||r.functionPath.startsWith("__lunora_admin__"))throw new c("reserved function path cannot be batched",{code:"FORBIDDEN",status:403});if(r.args!==void 0&&(typeof r.args!="object"||r.args===null||Array.isArray(r.args)))throw new c("each batch call `args` must be an object",{code:"BAD_REQUEST",status:400});if(r.id!==void 0&&typeof r.id!="number")throw new c("each batch call `id` must be a number",{code:"BAD_REQUEST",status:400});return{entry:{args:r.args===void 0?{}:r.args,baselineSeq:typeof r.baselineSeq=="number"?r.baselineSeq:void 0,clientId:typeof r.clientId=="string"?r.clientId:void 0,clientSeq:typeof r.clientSeq=="number"?r.clientSeq:void 0,functionPath:r.functionPath,id:typeof r.id=="number"?r.id:t,mutationId:typeof r.mutationId=="string"?r.mutationId:void 0},shardKey:typeof r.shardKey=="string"?r.shardKey:n}},is=(e,t)=>{if(e.length>Ht)throw new c(`RPC batch exceeds the ${String(Ht)}-call limit`,{code:"BAD_REQUEST",status:400});const n=new Map,r=new Set;for(const[s,i]of e.entries()){const{entry:d,shardKey:f}=as(i,s,t);if(r.has(d.id))throw new c(`batch call id ${String(d.id)} is used twice; ids must be distinct`,{code:"BAD_REQUEST",status:400});r.add(d.id);const h=n.get(f)??[];h.push(d),n.set(f,h)}return n},cs="/_lunora/admin/export",ds="/_lunora/admin/import",us="/_lunora/admin/sync",ls="/_lunora/admin/connector/sync",hs="/_lunora/admin/apply",fs="/_lunora/admin/export-tap/run",ps=new TextEncoder,ms=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 r=[];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});r.push(s)}return{tables:r}},Qe=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):void 0,ws=e=>{const{applyGlobals:t,defaultShardKey:n,exportCursorStore:r,exportSinks:s,knownTables:i,queryCoordinator:d,assertAdmin:f,resolveForwardContext:h,shardDO:m,prepareExportRows:_,streamingImport:S,syncGlobals:T}=e,P=async(E,L)=>{const j=ge(E,["POST"]);if(j)return j;f(E);const C=await ms(E),{headers:K}=await h(E,L),q=await _(K,C.tables),V=new ReadableStream({async pull(G){try{for await(const J of q)G.enqueue(ps.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=Qe(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=T?await T({limit:V,sinceSeq:G}):void 0;return Response.json({global:ae,shards:le.shards},{status:200})},g=async(E,L)=>{const j=ge(E,["POST"]);if(j)return j;f(E);const C=await ne(E),K=Gr(C.cursor),q=typeof C.limit=="number"&&C.limit>0?C.limit:void 0,V=Qe(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=Et(W,ce.changes??[],Wr(q))||ae,le[ce.shardKey]=ce.cursor;let z=K.g;if(T){const ce=await T({limit:q,sinceSeq:K.g});ae=Et(W,ce.changes,q)||ae,z=ce.cursor}const ie=Qr({g:z,s:le,v:1}),xe={changes:W,hasMore:ae,nextCursor:ie};return Response.json(xe,{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})},A=async(E,L)=>{const j=ge(E,["POST"]);if(j)return j;f(E);const{headers:C}=await h(E,L),K=await S(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||r===void 0)throw new c("Export-tap endpoint requires `exportSinks` + `exportCursorStore` on the worker",{code:"EXPORT_TAP_NOT_CONFIGURED",status:400});const C=await ne(E),K=typeof C.sink=="string"?C.sink:void 0,q=typeof C.limit=="number"&&C.limit>0?C.limit:void 0,V=Qe(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 Kr({coordinator:d,cursorStore:r,defaultShardKey:n,headers:J,limit:q,shardDO:m,sink:G,tables:se});return Response.json(W,{headers:{"content-type":"application/json"},status:200})};return{[hs]:b,[ls]:g,[cs]:P,[fs]:I,[ds]:A,[us]:w}},gs=(e,t)=>{let n;try{n=JSON.parse(e)}catch{return{error:{code:"BAD_ROW",line:t,message:"line is not valid JSON",table:""},ok:!1}}if(!n||typeof n!="object"||Array.isArray(n))return{error:{code:"BAD_ROW",line:t,message:"row must be a JSON object",table:""},ok:!1};const r=n;return typeof r.table!="string"||r.table.length===0?{error:{code:"BAD_ROW",line:t,message:"row is missing `table`",table:""},ok:!1}:!r.doc||typeof r.doc!="object"||Array.isArray(r.doc)?{error:{code:"BAD_ROW",line:t,message:"row is missing or malformed `doc`",table:r.table},ok:!1}:{doc:r.doc,ok:!0,table:r.table}},ys=(e,t,n,r,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:r}},bs=async(e,t,n)=>{if(!e.body)throw new c("Import endpoint requires a request body",{code:"BAD_REQUEST",status:400});const r=[],s=[],i=new Map;let d=0,f=0;const h=e.body.getReader(),m=new TextDecoder;let _="",S=0;const T=P=>{f+=1;const w=P.trim();if(w.length===0)return;d+=1;const g=gs(w,f);if(!g.ok){r.push(g.error);return}const{doc:b,table:A}=g,I=t.resolveTableSharding?.(A);if(I?.mode.kind==="global"){s.push({doc:b,line:f,table:A});return}const E=ys(b,A,I,n,f);if(!E.ok){r.push(E.error);return}const L=i.get(E.shardKey);L?L.rows.push({doc:b,table:A}):i.set(E.shardKey,{rows:[{doc:b,table:A}],shardKey:E.shardKey,startLine:f})};for(;;){const{done:P,value:w}=await h.read();if(P)break;if(w&&(S+=w.byteLength,S>cn))throw await h.cancel().catch(()=>{}),new c("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});_+=m.decode(w,{stream:!0});let g=_.indexOf(`
|
|
5
|
-
`);for(;g!==-1;){const b=_.slice(0,g);_=_.slice(g+1),T(b),g=_.indexOf(`
|
|
6
|
-
`)}}return _.length>0&&T(_),{errors:r,globalRows:s,perShard:i,received:d}},_s=e=>e.flatMap(t=>t.error?[{message:t.error.message,shardKey:t.shardKey,timedOut:t.error.timedOut}]:[]),Lt=(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},Rs=async(e,t,n,r,s)=>{const i=t.defaultShardKey??"__root__",{errors:d,globalRows:f,perShard:h,received:m}=await bs(e,t,i),_={conflicts:0,errors:d,failed:[],inserted:{}},S=[];if(t.resolveTableSharding===void 0&&h.size>0&&S.push("no `resolveTableSharding` is configured, so every row was routed to the default shard and no row could be recognised as `.global()` — correct for a single-shard app, silent misplacement for a sharded one"),h.size>0){const T=await n.orchestrateImport(s,{batches:[...h.values()],headers:r});Lt(_,T),_.failed.push(..._s(T.shards))}if(f.length>0)if(t.importGlobals){const T=f[0]?.line??1,P=await t.importGlobals({rows:f,startLine:T});Lt(_,P)}else for(const T of f)_.errors.push({code:"GLOBAL_NOT_CONFIGURED",line:T.line,message:`row targets global table "${T.table}" but no \`importGlobals\` is configured`,table:T.table});return{conflicts:_.conflicts,errors:_.errors,failed:_.failed,inserted:_.inserted,received:m,...S.length>0?{warnings:S}:{}}},Es=Object.freeze({edges:[],nodes:[],modules:[],unresolved:[],version:1}),We=e=>typeof e=="object"&&e!==null?e:{},ze=e=>typeof e.kind=="string"?e.kind:"unknown",Ss=(e,t)=>{let n=We(t),r=!1;ze(n)==="optional"&&(r=!0,n=We(n._meta?.inner));const s=ze(n),i=n._meta??{},d={kind:s,name:e,optional:r};if(s==="id"&&typeof i.tableName=="string"&&(d.table=i.tableName),s==="array"){const f=ze(We(i.inner));f!=="unknown"&&(d.element=f)}return d},Ts=e=>typeof e!="object"||e===null?[]:Object.entries(e).map(([t,n])=>Ss(t,n)).toSorted((t,n)=>t.name.localeCompare(n.name)),As="/_lunora/admin/functions",Os="/_lunora/admin/cron-jobs",vs="/_lunora/admin/architecture",Is="/_lunora/admin/openapi",Ps="/_lunora/admin/openrpc",ks="/_lunora/admin/global/tables",Ds="/_lunora/admin/global/table",Ns="/_lunora/admin/global/facet",jt=e=>{if(e===void 0||e==="")return;let t;try{t=Xe(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},Us=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:{}}),Cs=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"}),Bs=e=>{const{assertAdmin:t,options:n,parsePaging:r,queryParameter:s,requireAdminOption:i}=e,d=w=>{M(w,"GET","Functions");const g=i(w,n.functions,{code:"FUNCTIONS_NOT_CONFIGURED",message:"functions endpoint requires a `functions` registry on the worker"}),b=Object.entries(g).flatMap(([A,I])=>I.visibility==="internal"||I.kind==="stream"?[]:[{args:[...I.argumentDescriptors??Ts(I.args)],kind:I.kind,path:A}]).toSorted((A,I)=>A.path.localeCompare(I.path));return Response.json({functions:b},{headers:{"content-type":"application/json"},status:200})},f=w=>{M(w,"GET","Cron-jobs");const g=i(w,n.cronJobs,{code:"CRON_JOBS_NOT_CONFIGURED",message:"cron-jobs endpoint requires a `cronJobs` map on the worker"}),b=Object.entries(g).flatMap(([A,I])=>I.map(E=>({args:E.args,cron:A,functionPath:E.functionPath,name:E.name,shardKey:E.shardKey,workflow:E.workflow}))).toSorted((A,I)=>A.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??Es,{headers:{"content-type":"application/json"},status:200})),m=w=>(M(w,"GET","OpenAPI"),t(w),Response.json(n.openApiSpec??Us,{headers:{"content-type":"application/json"},status:200})),_=w=>(M(w,"GET","OpenRPC"),t(w),Response.json(n.openRpcSpec??Cs,{headers:{"content-type":"application/json"},status:200})),S=async w=>{M(w,"GET","Global-tables");const g=i(w,n.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"});return Response.json(await g.listTables(),{headers:{"content-type":"application/json"},status:200})},T=async w=>{M(w,"GET","Global-table");const g=i(w,n.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),b=new URL(w.url),A=s(b,"table");if(A===void 0)throw new c("Global-table endpoint requires a `table` query param",{code:"BAD_REQUEST",status:400});const I=await g.readTablePage({...r(w),filters:jt(s(b,"filters")),table:A});return Response.json(I,{headers:{"content-type":"application/json"},status:200})},P=async w=>{M(w,"GET","Global-facet");const g=i(w,n.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),b=new URL(w.url),A=s(b,"table"),I=s(b,"column");if(A===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 g.facetColumn({column:I,filters:jt(s(b,"filters")),limit:L!==void 0&&Number.isFinite(L)?L:void 0,table:A});return Response.json(j,{headers:{"content-type":"application/json"},status:200})};return{[Os]:f,[As]:d,[Ns]:P,[Ds]:T,[ks]:S,[vs]:h,[Is]:m,[Ps]:_}},xs="/_lunora/admin/kv/namespaces",Hs="/_lunora/admin/kv/keys",Sn="/_lunora/admin/kv/value",Tn=32*1048576,Mt=60,Ls=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,g)=>{const b=new URL(w.url),A=b.searchParams.get("namespace")??"",I=b.searchParams.get("key")??"";if(A==="")throw new c(`KV-value ${g} request requires a \`namespace\` query parameter`,{code:"BAD_REQUEST",status:400});if(I==="")throw new c(`KV-value ${g} request requires a \`key\` query parameter`,{code:"BAD_REQUEST",status:400});return{key:I,namespace:A}},d=async(w,g)=>{if(!(await w.listNamespaces()).some(A=>A.binding===g))throw new c(`Unknown KV namespace binding \`${g}\``,{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 g=r(w),b=new URL(w.url),A=b.searchParams.get("namespace")??"";if(A==="")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(g,A),s(await g.listKeys({cursor:E,limit:C,namespace:A,prefix:I}))},T={DELETE:async w=>{const g=r(w),b=i(w,"DELETE");return await d(g,b.namespace),await g.deleteKey(b),s({deleted:!0})},GET:async w=>{const g=r(w),b=i(w,"GET");return await d(g,b.namespace),s(await g.getValue(b))},PUT:async w=>{const g=r(w),b=await t(w,Tn);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<Mt))throw new c("KV-value PUT `expirationTtl` must be an integer ≥ 60",{code:"BAD_REQUEST",status:400});const A=Math.floor(Date.now()/1e3)+Mt;if(b.expiration!==void 0&&(typeof b.expiration!="number"||!Number.isInteger(b.expiration)||b.expiration<A))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(g,b.namespace),await g.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 g=T[w.method];if(!g)throw new c("KV-value endpoint requires GET, PUT, or DELETE",{code:"METHOD_NOT_ALLOWED",status:405});return g(w)};return{[xs]:f,[Hs]:h,[Sn]:P}},js="/_lunora/migrate",Ms="/_lunora/admin/pitr",$s="/_lunora/admin/rank",Fs="/_lunora/admin/rankpage",Ks="/_lunora/admin/shard-registry/prune",Gs="/_lunora/admin/shard-traffic",Qs=new Set(["__lunora_admin__:migrationStatus","__lunora_admin__:runMigration"]),Ws=new Set(["__lunora_admin__:getPitrBookmark","__lunora_admin__:pitrRestore"]),zs=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"||!Qs.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}},Vs=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}},Js=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}},Ys=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})},qs=async e=>{const n=await oe(e,"Rank page")??{};Ys(n);const r=Js(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}},Xs=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}},Zs=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}},ea=async e=>{const n=await ne(e);if(typeof n.functionPath!="string"||!Ws.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}},ta=e=>{const{defaultShard:t,forwardToShard:n,isAdmin:r,queryCoordinator:s,resolveForwardContext:i,shardDO:d,shardedTables:f}=e,h=(g,b)=>{if(g.method!=="POST")throw new c(`${b} endpoint requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});if(!r(g))throw new c("Admin auth required",{code:"FORBIDDEN",status:403})},m=async(g,b)=>{h(g,"Migration");const A=await zs(g),{headers:I}=await i(g,b),E=await s.orchestrateMigration(d,{args:A.args,defaultShardKey:t,functionPath:A.functionPath,headers:I,table:A.table});return Response.json(E,{headers:{"content-type":"application/json"},status:200})},_=async(g,b)=>{h(g,"Rank");const A=await Vs(g),{headers:I}=await i(g,b),E=await s.orchestrateRank(d,{headers:I,index:A.index,partitionKey:A.partitionKey,rowId:A.rowId,sortValues:A.sortValues,table:A.table});return Response.json(E,{headers:{"content-type":"application/json"},status:200})},S=async(g,b)=>{h(g,"Rank page");const A=await qs(g),{headers:I}=await i(g,b),E=await s.orchestrateRankPage(d,{...A,headers:I});return Response.json(E,{headers:{"content-type":"application/json"},status:200})},T=async(g,b)=>{h(g,"Shard-traffic");const A=await Xs(g),{headers:I}=await i(g,b),E=await s.orchestrateShardTraffic(d,{headers:I,table:A.table});return Response.json(E,{headers:{"content-type":"application/json"},status:200})},P=async(g,b)=>{h(g,"Shard-registry prune");const A=await Zs(g),I=f(),E=(A.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(g,b),j=await Xr(s.registry,d,{dryRun:A.dryRun,headers:L,tables:A.tables??I});return Response.json(j,{status:j.failed.length>0?207:200})},w=async(g,b)=>{if(M(g,"POST","PITR"),!r(g))throw new c("admin PITR endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403});const A=await ea(g),{headers:I}=await i(g,b),E=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:A.args,functionPath:A.functionPath}),headers:I,method:"POST"});return n(d,A.shardKey??t,E)};return{[js]:m,[Ms]:w,[$s]:_,[Fs]:S,[Ks]:P,[Gs]:T}},na=1,ra=0,oa=32,sa=512,aa=/^[a-z][\d_a-z*/-]{0,255}(?:@[a-z][\d_a-z*/-]{0,13})?=[\u0020-\u002B\u002D-\u003C\u003E-\u007E]{1,256}$/,ia=e=>{if(e==null)return;const t=e.trim();if(t.length===0||t.length>sa)return;const n=t.split(",");if(!(n.length>oa)){for(const r of n)if(!aa.test(r.trim()))return;return t}},ca=e=>{const t=Tr(e.headers.get("traceparent"));if(t===void 0)return;const n=ia(e.headers.get("tracestate"));return{parentSpanId:t.parentSpanId,sampled:t.sampled,traceId:t.traceId,...n===void 0?{}:{traceState:n}}},$t=(e,t={})=>{const n=ca(e),r=t.trustInbound===!0?n:void 0,s=be(8),i=r?.traceId??be(16),d=Pr(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?na:ra,traceId:i,...r?.parentSpanId===void 0?{}:{parentSpanId:r.parentSpanId},...r?.traceState===void 0?{}:{traceState:r.traceState},...f===void 0?{}:{rayId:f}}}},Ft=(e,t)=>{t.traceparent=an(e.traceId,e.spanId,e.sampled),e.traceState!==void 0&&(t.tracestate=e.traceState),e.rayId!==void 0&&(t[po]=e.rayId)},da=(e,t)=>{let n;return()=>{if(n===void 0){const r=Ir(e),s=t===void 0?void 0:t.cf;n=Ar(vr(r),Or(r,s))}return n}},ua="/_lunora/admin/scheduled",la="/_lunora/admin/scheduled/status",ha="/_lunora/admin/scheduled/ws",fa="/_lunora/admin/scheduled/cancel",pa="/_lunora/admin/scheduled/dead",ma="/_lunora/admin/scheduled/dead/retry",wa="/_lunora/admin/scheduled/dead/cancel",ga="/_lunora/admin/scheduled/pool/release",ya=e=>{const{checkWsAdmin:t,requireSchedulerNamespace:n,resolveSchedulerStub:r,schedulerInstanceName:s}=e,i=(m,_)=>S=>{if(S.method!=="GET")throw new c(`${_} endpoint requires GET`,{code:"METHOD_NOT_ALLOWED",status:405});const T=new URL(S.url).searchParams.get("cursor"),P=T===null||T===""?"":`?cursor=${encodeURIComponent(T)}`;return r(S).fetch(new Request(`https://scheduler.internal${m}${P}`,{method:"GET"}))},d=(m,_,S=_)=>async T=>{if(T.method!=="POST")throw new c(`${S} requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});const P=r(T),w=await oe(T,_);if(typeof w?.id!="string"||w.id==="")throw new c(`${_} 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 _=r(m),S=await oe(m,"Scheduled pool-release");if(typeof S?.pool!="string"||S.pool==="")throw new c("Scheduled pool-release requires a string `pool`",{code:"BAD_REQUEST",status:400});const T=typeof S.id=="string"&&S.id!==""?S.id:void 0;return _.fetch(new Request("https://scheduler.internal/complete",{body:JSON.stringify(T===void 0?{pool:S.pool}:{id:T,pool:S.pool}),headers:{"content-type":"application/json"},method:"POST"}))},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 _=n();return _e(_,s).fetch(new Request("https://scheduler.internal/ws",{headers:{Upgrade:"websocket"}}))};return{[fa]:d("/cancel","Scheduled-cancel","Scheduled-cancel endpoint"),[wa]:d("/dead/cancel","Scheduled dead-letter action"),[pa]:i("/dead","Scheduled dead-letter"),[ma]:d("/dead/retry","Scheduled dead-letter action"),[ua]:i("/list","Scheduled-list"),[ga]:f,[la]:i("/status","Scheduler-status"),[ha]:h}},ba="/_lunora/scheduled",An="/_lunora/queue",On=16*1048576,_a=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"),_=typeof m?.cron=="string"?m.cron:"";if(_==="")throw new c("scheduled tick requires a `cron` expression",{code:"BAD_REQUEST",status:400});return await n({cron:_,noRetry:()=>{},scheduledTime:Date.now()},f,h),Response.json({cron:_,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",On);if(!Array.isArray(m?.messages))throw new c("queue dispatch requires a `messages` array",{code:"BAD_REQUEST",status:400});const _=typeof m.queue=="string"?m.queue:"",S=m.messages.filter(P=>typeof P=="object"&&P!==null&&typeof P.id=="string").map(P=>({body:P.body,id:P.id})),T=await r({messages:S,queue:_},f,h);return Response.json({retry:T?.retry??[]})};return{[An]:i,[ba]:s}},Ra=(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},nt={mtls:e=>Ra(e,"tlsClientAuth","certVerified")==="SUCCESS"},Ea=e=>e===void 0||e===!1?()=>!1:e===!0?()=>!0:typeof e=="function"?e:(Object.hasOwn(nt,e)?nt[e]:void 0)??(()=>!1),Sa=e=>typeof e=="string"&&Object.hasOwn(nt,e),Ta=e=>{const t=Sa(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.`))}},Aa="/_lunora/admin/vector/indexes",Oa="/_lunora/admin/vector/query",va=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{[Aa]:r,[Oa]:s}},Ia="/_lunora/admin/workflows/instances",Pa="/_lunora/admin/workflows/instance",ka="/_lunora/admin/workflows/status",Da={complete:!0,errored:!0,paused:!0,queued:!0,running:!0,terminated:!0,unknown:!0,waiting:!0,waitingForPause:!0},Na=e=>e!==null&&Object.hasOwn(Da,e)?e:void 0,Kt=(e,t)=>{const n=e.searchParams.get(t);if(n===null)return;const r=Number(n);return Number.isInteger(r)&&r>0?r:void 0},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},Gt=()=>{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})},Ua=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 _=Ve(h,"name"),S=Na(h.searchParams.get("status"));return Response.json(await m.listInstances({page:Kt(h,"page"),perPage:Kt(h,"perPage"),status:S,workflowName:_}))},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")})):Gt()},i=async(d,f)=>{M(d,"POST","Workflows status"),t(d);const h=n(f);if(!h)return Gt();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:_}=m;if(_!=="pause"&&_!=="resume"&&_!=="terminate")throw new c("Workflows status action must be one of: pause, resume, terminate",{code:"BAD_REQUEST",status:400});return Response.json(await h.setInstanceStatus({action:_,instanceId:m.id,workflowName:m.name}))};return{[Pa]:s,[Ia]:r,[ka]:i}},Ca={[Sn]:Tn,[An]:On,[Fr]:$r},Ba="https://queue.lunora.internal",Qt=()=>({publish:()=>Promise.reject(new c("ctx.live.publish is unavailable: this worker does not serve live streams",{code:"LIVE_STREAMS_UNSUPPORTED",status:501}))}),xa=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})},Wt="/_lunora/rpc",Ha="/_lunora/rpc-batch",La="/_lunora/ws",Ae=(e,t,n)=>({resourceAttributes:da(e,t),...n===void 0?{}:{waitUntil:n}}),Je=e=>e?.waitUntil?{waitUntil:t=>e.waitUntil?.(t)}:{},zt=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=wo(e.headers.get(fo)),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}},Vt="/_lunora/voice/",ja="/_lunora/admin/cron-jobs/run",Ma="/_lunora/admin/ws-token",$a="/_lunora/admin/",Be="/_lunora/",Fa="/_lunora/migrate",Ka="/_lunora/status",Ga=e=>e.startsWith($a)||e===Fa,ke=e=>{if(No(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,Jt=(e,t)=>{const n=e.headers.get(yt);if(n===null)return;const r=Sr(n);if(r===void 0)throw new c(`malformed ${yt} 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})},Yt="/api/auth",Qa="__lunora_admin__:recordAuthEvent",qt="__lunora_admin__:listPushSubscriptions",Wa=["/sign-in","/sign-up","/callback"],za=(e,t)=>{const n=t.endsWith("/")?t.slice(0,-1):t;if(!e.startsWith(`${n}/`))return!1;const r=e.slice(n.length);return Wa.some(s=>r===s||r.startsWith(`${s}/`))},Xt=(e,t)=>{const n=t.endsWith("/")?t.slice(0,-1):t;return e===n||e.startsWith(`${n}/`)},Ne=(e,t,n,r)=>{const s=wr(n),i=s?n.code:"INTERNAL_SERVER_ERROR",d=s?n.status:500,{message:f,name:h,stack:m}=lo(n);return{durationMs:t,error:{code:i,message:f,name:h,status:d,...m===void 0?{}:{stack:m}},functionPath:e,ok:!1,...r.fanOut?{fanOut:{failed:0,shards:0,table:r.fanOut.table}}:{},...r.shardKey?{shardKey:r.shardKey}:{}}},vn=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},In=({identity:e})=>e!==null&&_r(vn(e)),Va=e=>{if(In(e))throw new c("authentication token expired",{code:"TOKEN_EXPIRED",status:401});return e},Ja=e=>{if(!In(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}},Zt=e=>e.waitUntil?{waitUntil:t=>{e.waitUntil?.(t)}}:void 0,Ya=e=>{const t=e?.queue;return typeof t=="string"&&t.length>0?t:"unknown"},rt=new WeakMap,qa=async(e,t,n,r,s=rt.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"),_=e.headers.get("x-lunora-client-id"),S=e.headers.get("x-lunora-client-seq"),T=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),_&&(i["x-lunora-client-id"]=_),S&&(i["x-lunora-client-seq"]=S),T&&(i["x-lunora-base-seq"]=T);const P=Br(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"]=Rr(w.userId);const g=vn(w);g!==void 0&&(i["x-lunora-identity-exp"]=String(g));const{userId:b,...A}=w,I=Object.keys(A).length>0?A:null;return I&&(i["x-lunora-identity"]=Er(I)),{claims:I,headers:i,identity:w,userId:b}},Xa=new Set(["concat","first","groupBy","max","min","rank","sum","topK"]),Za=e=>{if(e===void 0)return;if(!e||typeof e!="object")throw new c("RPC `fanOut` must be an object",{code:"BAD_REQUEST",status:400});const t=e;if(typeof t.table!="string"||t.table.length===0)throw new c("RPC `fanOut.table` must be a non-empty string",{code:"BAD_REQUEST",status:400});if(!t.merge||typeof t.merge!="object")throw new c("RPC `fanOut.merge` must be an object",{code:"BAD_REQUEST",status:400});const n=t.merge;if(typeof n.kind!="string"||!Xa.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},ei=(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}},ti=async e=>{const t=await un(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&&dn(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=Za(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,ni=5e3,ri=4096,oi=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 rn(Ue,ri),Ue.set(t,{expiresMs:n+ni,relayCount:s}),s},en=(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"}),si=["x-lunora-userid","x-lunora-identity","x-lunora-identity-exp","x-lunora-client-ip"],ai=(e,t)=>{for(const n of si){e.delete(n);const r=t[n];r!==void 0&&e.set(n,r)}},tn=(e,t)=>{const n=new Headers(e.headers),r=[...n.keys()];for(const s of r)s.startsWith("x-lunora-")&&n.delete(s);return ai(n,t),n},nn=async(e,t)=>{if(!t||t.length===0)return!1;const n=new URL(e.url).searchParams.get("token");return n===null?!1:Mo(t,n)},ii=(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 Jr(`d1:${e}`,t);if(typeof n.list=="function"&&typeof n.head=="function"&&typeof n.createMultipartUpload=="function")return $e(`r2:${e}`,!0);if(typeof n.send=="function"&&typeof n.sendBatch=="function"&&typeof n.get!="function")return $e(`queue:${e}`,!0);if(typeof n.connectionString=="string")return $e(`hyperdrive:${e}`,!0)},ci=e=>{for(const t of Object.keys(e??{}))if(t.slice(t.indexOf(" ")+1).startsWith(Be))throw new c(`route "${t}" is under the reserved ${Be} 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})},di=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})},Pn=e=>{di(e);const t=Ea(e.trustInboundTraceContext),n=Ta(e.trustInboundTraceContext),r=e.defaultShardKey??"__root__",s=e.queryCoordinator??Zr({registry:eo(e.resolveTableSharding,r)}),i=Yr(e.resolveIdentity,e.identity),d=Fe(e.shardDO,e.jurisdiction),f=e.schedulerDO===void 0?void 0:Fe(e.schedulerDO,e.jurisdiction),h=e.voiceAgents===void 0?void 0:Object.fromEntries(Object.entries(e.voiceAgents).map(([o,a])=>[o,Fe(a,e.jurisdiction)]));let m=!1;const _=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.`))},S=async(o,a,l,u=e.shardRegion?.(a))=>_e(o,a,_(u)).fetch(l);let T;const P=()=>e.adminToken??T;let w;const g=o=>{const a=o??{};if(w??=en(o,e.shardDO),T!==void 0||e.adminToken!==void 0)return;const l=a.LUNORA_ADMIN_TOKEN;typeof l=="string"&&l.length>0&&(T=l)},b=new WeakSet,A=o=>wn(o,P())||b.has(o),I=async o=>{if(!(e.adminGate===void 0||b.has(o)))try{await De(e.adminGate(o,rt.get(o)))&&b.add(o)}catch{}},E=async(o,a,l,u)=>{const p=await qa(o,a,l,e.trustedClientIpHeader,u);return e.functions!==void 0&&(p.headers[sn]=on),p},L=async(o,a,l,u)=>Va(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(Ze)||a.includes(et))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=ta({defaultShard:r,forwardToShard:S,isAdmin:A,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 y=u.shardKey??r;p==="trusted"?await G(null,y,!0):y!==r&&await G(p.identity,y);const O=await S(d,y,new Request(new URL(ho,o),{body:JSON.stringify({data:ye(l??null),stream:u.stream,topic:a}),headers:{"content-type":"application/json"},method:"POST"}));if(!O.ok)throw await xa(O,a)},W=async(o,a,l,u,p,y)=>{ke(o);const O=Co({forwardedIdentity:p,mutationId:u,traceparent:y});return S(d,l,Ce(o,a,O))},le=async(o,a,l,u,p)=>{const y=Ho(l.env,l.context?.exports,o,["create"]);if(y===void 0)throw new c(`${u} targets workflow "${o}", which is on neither ctx.exports nor env`,{code:"CRON_JOB_FAILED",status:500});if(oo(a))throw new c(`${u} params ${so}`,{code:"BAD_REQUEST",status:400});try{await y.create(p===void 0?{params:a}:{id:p,params:a})}catch(O){if(!co(O))throw O}},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(!A(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},xe=async(o,a,l,u,p,y)=>{const O=e.cronJobs?.[o];if(!O)return 0;for(const D of O)try{await ae(D,a,l,y)}catch(N){u.push(p(N))}return O.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 y=Object.values(e.cronJobs).flat().find(O=>O.name===p);if(!y)throw new c(`no cron job named "${p}" is registered`,{code:"CRON_JOB_NOT_FOUND",status:404});return await ae(y,a,l),Response.json({name:p,ran:!0},{status:200})},ct=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{}},kn=async(o,a,l)=>{M(o,"POST","Scheduler dispatch");const u=await un(o),p=a??{},y=typeof p.LUNORA_SCHEDULER_SECRET=="string"?p.LUNORA_SCHEDULER_SECRET:void 0,O=e.adminToken??(typeof p.LUNORA_ADMIN_TOKEN=="string"?p.LUNORA_ADMIN_TOKEN:void 0);if(!await Uo(o,u,{adminToken:O,schedulerSecret:y}))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??{},v=R.args??{},k=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,v,{context:l,env:a},"scheduled workflow",k),await ct(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,$=Bo(o),x=await W(R.functionPath,v,H,k,$,o.headers.get("traceparent")??void 0);return await ct(R),x},Dn=Go({assertAdmin:z,getReader:()=>e.authAuditReader}),Nn=Qo({assertAdmin:z,getMove:()=>e.authJurisdictionMove}),Un=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,y=a?.limit,O=u==="fcm"||u==="web-push"?u:void 0,D=typeof p=="string"&&p!==""?p:void 0,N=typeof y=="number"&&Number.isFinite(y)?Math.trunc(y):0,R=N>0?Math.min(N,1e3):1e3,k=(await l.list({kind:O,limit:R,userId:D})).filter(H=>O!==void 0&&H.kind!==O?!1:D===void 0||(H.userId??null)===D).map(({keys:H,token:$,...x})=>x);return Response.json({result:ye({subscriptions:k})},{headers:{"content-type":"application/json"},status:200})},Cn=async(o,a)=>{if(!a.fanOut&&!(a.functionPath!==Dt&&a.functionPath!==qt&&a.functionPath!==tt&&a.functionPath!==bn))return await I(o),a.functionPath===Dt?Dn(o,a.args??{}):a.functionPath===qt?Un(o,a.args):Nn(o,a.functionPath,a.args??{})},Bn=ws({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)=>_n(e,s,o,a,d),streamingImport:(o,a)=>Rs(o,e,s,a,d),syncGlobals:e.syncGlobals}),He=(o,a)=>{const l=o.searchParams.get(a);return l===null||l===""?void 0:l},Le=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),y=u===null?void 0:Number.parseInt(u,10);return{limit:p!==void 0&&Number.isFinite(p)&&p>=0?p:void 0,offset:y!==void 0&&Number.isFinite(y)&&y>=0?y:void 0}},dt=()=>{if(f===void 0)throw new c("scheduled endpoints require a `schedulerDO` namespace on the worker",{code:"SCHEDULER_NOT_CONFIGURED",status:400});return f},xn=ya({checkWsAdmin:async o=>A(o)||nn(o,P()),requireSchedulerNamespace:dt,resolveSchedulerStub:o=>(z(o),_e(dt(),e.schedulerInstanceName??"default")),schedulerInstanceName:e.schedulerInstanceName??"default"}),Hn=Ua({assertAdmin:z,resolveWorkflowsClient:e.workflowsClient??(()=>{})}),Ln=Mr({assertAdmin:z,parsePaging:Le,queryParameter:He,readBodyBytes:Ur,requireAdminOption:ie,storage:{storageBuckets:e.storageBuckets,storageDelete:e.storageDelete,storageDownload:e.storageDownload,storageList:e.storageList,storageSignedUrl:e.storageSignedUrl,storageUpload:e.storageUpload}}),jn=ss({options:e,readJsonBody:ne,requireAdminOption:ie}),Mn=va({readJsonBody:ne,requireAdminOption:ie,vectorIntrospector:e.vectorIntrospector}),$n=Ls({kvIntrospector:e.kvIntrospector,readJsonBody:ne,requireAdminOption:ie}),Fn=qr({logArchive:e.logArchive,readJsonBody:ne,requireAdminOption:ie}),Kn=Bs({assertAdmin:z,options:{cronJobs:e.cronJobs,functions:e.functions,globalIntrospector:e.globalIntrospector,architecture:e.architecture,openApiSpec:e.openApiSpec,openRpcSpec:e.openRpcSpec},parsePaging:Le,queryParameter:He,requireAdminOption:ie}),Gn=o=>{const a=[],l=d??o?.SHARD;if(l!==void 0&&a.push(Vr("durable-object:default",l,r)),e.health?.disableBindingProbes!==!0)for(const[u,p]of Object.entries(o??{})){const y=ii(u,p);y!==void 0&&a.push(y)}for(const u of e.health?.probes??[])a.push(u);return a},Qn=zr({appName:e.health?.appName,appVersion:e.health?.appVersion,auth:e.health?.auth??"public",cacheTtlMs:e.health?.cacheTtlMs,isAdmin:A,resolveProbes:Gn}),Wn=o=>{const a=R=>"args"in R?{...R,args:Xe(R.args)}:R,l=e.schedulerInstanceName??"default",u=()=>_e(o,l),p=async(R,v)=>{const k=await u().fetch(new Request(`https://scheduler.internal${R}`,v));if(!k.ok)throw new c(`ctx.scheduler: SchedulerDO ${R} failed (${String(k.status)}): ${await k.text()}`,{code:"INTERNAL",status:500});return await k.json()},y=async(R,v)=>await p(R,{body:JSON.stringify(v),headers:{"content-type":"application/json"},method:"POST"}),O=R=>{const v=R;if(v==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 v.binding=="string"&&v.binding.length>0)return{workflow:v.binding};if(typeof v.__lunoraRef=="string")return{functionPath:v.__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})},D=async()=>(await ao(async v=>p(v===void 0?"/list":`/list?cursor=${encodeURIComponent(v)}`,{method:"GET"}))).map(v=>a(v)),N=async(R,v,k={})=>{const H=O(v),{id:$}=await y("/schedule",{args:yr("ctx.scheduler",String(H.functionPath??H.workflow),k),scheduledFor:Math.ceil(R),...H});return $};return{cancel:async R=>await y("/cancel",{id:R}),get:async R=>{const v=await p(`/get?id=${encodeURIComponent(R)}`,{method:"GET"});return v.record===void 0?null:a(v.record)},list:D,runAfter:async(R,v,k)=>{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,v,k)},runAt:async(R,v,k)=>{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,v,k)}}},zn=async(o,a,l)=>{const{claims:u,headers:p,identity:y,userId:O}=Ja(await E(o,a,i)),D=Ae(a,o,k=>l.waitUntil?.(k)),N=k=>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),k!==r&&await G(y,k);const X=await ve(o,x,ye($),k,{...p,"x-lunora-system":"1"},D),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 Xe(Z.result)},R=N(r),v=async(k,H,$={})=>{k!==void 0&&k!==r&&await G(y,k);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 S(d,k??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:O},cache:l.cache,fetch:globalThis.fetch.bind(globalThis),fetchShard:v,forShard:k=>{const H=N(k);return{runAction:H,runMutation:H,runQuery:H}},live:e.liveStreams===!1?Qt():{publish:(k,H,$)=>se(o.url,k,H,$,{identity:y})},runAction:R,runMutation:R,runQuery:R,...f===void 0?{}:{scheduler:Wn(f)},...l.waitUntil===void 0?{}:{waitUntil:l.waitUntil.bind(l)},...e.storage===void 0?{}:{storage:ro(e.storage(a,new URL(o.url).origin))}}},Vn=async(o,a,l)=>{if(!e.httpRouter)return;const u=await zn(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})}},Jn=async(o,a,l)=>{if(o.headers.get("Upgrade")!=="websocket")throw new c("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});const u=Tt(o,de);if(u)return u;const p=l.searchParams.get("shard")??r,{headers:y,identity:O}=await E(o,a,i),D=A(o)||await nn(o,P());await G(O,p,D);const N=tn(o,y),R=en(a,e.shardDO);if(R!==void 0){N.set("x-lunora-shard-binding",R);const v=await oi(d,p);if(v>0){const k=Eo(p,Math.floor(Math.random()*v));return S(d,k,new Request(o,{headers:N}),It(o))}}return S(d,p,new Request(o,{headers:N}))},Yn=async(o,a,l)=>{if(h===void 0)return new Response("Not found",{status:404});if(o.headers.get("Upgrade")!=="websocket")return new Response("Expected a WebSocket upgrade",{headers:{allow:"GET"},status:426});const u=Tt(o,de);if(u)return u;let p;try{p=decodeURIComponent(l.pathname.slice(Vt.length))}catch{return new Response("Unknown voice agent",{status:404})}const y=Object.hasOwn(h,p)?h[p]:void 0;if(y===void 0)return new Response("Unknown voice agent",{status:404});const O=l.searchParams.get("threadKey");if(O===null||O.length===0)return new Response("Missing threadKey",{status:400});const{headers:D,identity:N}=await E(o,a,i);if(e.authorizeShard){if(!await De(e.authorizeShard({identity:N,shardKey:O})))throw new c("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else V("shard");const R=tn(o,D);return S(y,O,new Request(o,{headers:R}))},qn=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")},Oe=async(o,a)=>{if(!(!o.fanOut&&o.functionPath.startsWith("__lunora_admin__:"))){if(o.fanOut){await qn(o.fanOut,o.functionPath,a);return}await G(a,o.shardKey??r)}},Xn=(o,a,l)=>{if(e.replicaReads!==!0)return;if(e.functions===void 0){q();return}if(e.functions[a]?.kind!=="query"||l.includes(et)||l.includes(Ze))return;const u=It(o);return u===void 0?void 0:{name:So(l,u),region:u}},Zn=async(o,a,l,u,p)=>{const y=Xn(o,a,u);if(y!==void 0){const O={...p,"x-lunora-replica-read":"1",...w===void 0?{}:{"x-lunora-shard-binding":w}},D=To(o.headers.get("x-lunora-min-seq"));D!==void 0&&(O["x-lunora-min-seq"]=String(D));const N=await S(d,y.name,Ce(a,l,O),y.region);if(N.status!==421)return N}return S(d,u,Ce(a,l,p))},ve=async(o,a,l,u,p,y)=>{const O=Date.now(),{observability:D,sampling:N}=e,R=Ye(o),{decision:v,ignoredUpstream:k,trace:H}=$t(o,{...R.rayId===void 0?{}:{rayId:R.rayId},...N===void 0?{}:{sampling:N},trustInbound:t(o)});k&&n(o);const $={...p,[_t]:v.keepErrors?"1":"0",[At]:"1"};Ft(H,$);try{const x=await Zn(o,a,l,u,$),X=vt(x.headers.get(Ot));ue(D,{...R,...zt(H),durationMs:Date.now()-O,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}}},y,void 0,{isTraced:H.sampled,keepErrors:v.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(Ot),Z}catch(x){throw ue(D,{...R,...zt(H),...Ne(a,Date.now()-O,x,{shardKey:u})},y,void 0,{isTraced:H.sampled,keepErrors:v.keepErrors}),x}},er=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)},tr=async(o,a,l)=>{M(o,"POST","RPC");const u=await ti(o);ei(a,u),er(u);const p=await Cn(o,u);if(p!==void 0)return p;const{headers:y,identity:O}=await L(o,a,i);Jt(o,O),await Oe(u,O);const D=qe(u,e);{const N=Date.now(),{observability:R}=e,v=Ye(o),k=Ae(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:y});return ue(R,{durationMs:Date.now()-N,fanOut:{failed:x.failed,shards:x.ok+x.failed,table:u.fanOut.table},functionPath:u.functionPath,...v,ok:!0},k),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}}),...v},k),x}const H=u.shardKey??r,$=()=>ve(o,u.functionPath,u.args??{},H,y,k);return D&&e.x402Charge?e.x402Charge(o,{functionPath:u.functionPath,price:D.price},$,Je(l)):$()}},nr=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:y,identity:O}=await L(o,a,i);Jt(o,O);const D=is(p,r);for(const F of D.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 ${Wt}`,{code:"BAD_REQUEST",status:400});await Promise.all([...D.entries()].flatMap(([F,Q])=>Q.map(ee=>Oe({args:ee.args,functionPath:ee.functionPath,shardKey:F},O))));const{observability:N,sampling:R}=e,v=Ae(a,o,l&&(F=>l.waitUntil?.(F))),k=Ye(o),{decision:H,ignoredUpstream:$,trace:x}=$t(o,{...k.rayId===void 0?{}:{rayId:k.rayId},...R===void 0?{}:{sampling:R},trustInbound:t(o)});$&&n(o);const X={isTraced:x.sampled,keepErrors:H.keepErrors},Z=F=>{const Q={...y,"content-type":"application/json",[_t]:H.keepErrors?"1":"0",[At]:"1"};return Ft({...x,spanId:F},Q),Q},je=F=>({parentSpanId:F,spanId:be(8),traceFlags:x.traceFlags,traceId:x.traceId}),Pe=[],Me=[],ft=(F,Q,ee,he)=>({body:{error:{code:ee,message:he}},id:F.id,status:Q}),pt=(F,Q,ee,he,we)=>{for(const te of F)ue(N,we(te),v,void 0,X),Pe.push(ft(te,Q,ee,he))},pr=(F,Q,ee,he,we,te)=>{for(const Re of F){const Ee=we.get(Re.id),fe=Ee?.status??te,pe=fe<400,Se=pe?void 0:vt(Ee?.errorDetail);ue(N,{durationMs:he,functionPath:Re.functionPath,...k,...je(ee),ok:pe,shardKey:Q,...pe?{}:{error:{...Se,code:Se?.code??"SHARD_ERROR",message:Se?.message??`batched call returned ${String(fe)}`,status:fe}}},v,void 0,X)}};await Promise.all([...D.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 S(d,F,he)}catch(Y){const Te=Date.now()-we,{body:gt}=gr(Y,{fallbackCode:"SHARD_UNAVAILABLE",redactedMessage:"shard unavailable"});pt(Q,502,gt.code,gt.message,mr=>({...Ne(mr.functionPath,Te,Y,{shardKey:F}),...k,...je(ee)}));return}const Re=Date.now()-we,Ee=te.headers.get("x-d1-bookmark");Ee&&Me.push(Ee);let fe;try{fe=await te.json()}catch{const Y=`shard batch returned a non-JSON response (${String(te.status)})`;pt(Q,te.status,"SHARD_ERROR",Y,Te=>({durationMs:Re,error:{code:"SHARD_ERROR",message:Y,status:te.status},functionPath:Te.functionPath,...k,...je(ee),ok:!1,shardKey:F}));return}const pe=Array.isArray(fe.results)?fe.results:[],Se=new Set(pe.map(Y=>Y.id));pr(Q,F,ee,Re,new Map(pe.map(Y=>[Y.id,Y])),te.status),Pe.push(...pe.map(({errorDetail:Y,...Te})=>Te));for(const Y of Q)Se.has(Y.id)||Pe.push(ft(Y,te.status,"SHARD_ERROR",`shard batch omitted result for call ${String(Y.id)}`))}));const mt={"content-type":"application/json"},[wt]=Me;return Me.length===1&&wt!==void 0&&(mt["x-d1-bookmark"]=wt),Response.json({results:Pe},{headers:mt,status:200})},rr=async(o,a,l,u={},p={})=>{try{const y=l.__lunoraRef;if(typeof y!="string")throw new c("serverQuery: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});ke(y);const{headers:O,identity:D}=await L(o,a,i,p.context),N={args:u,functionPath:y,shardKey:p.shardKey};await Oe(N,D);const R=p.shardKey??r,v=Ae(a,o,p.waitUntil),k=()=>ve(o,y,u,R,O,v),H=qe(N,e);return H&&e.x402Charge?await e.x402Charge(o,{functionPath:y,price:H.price},k,Je(p.waitUntil?{waitUntil:p.waitUntil}:p.context)):await k()}catch(y){return Rt(y)}},ut=async(o,a,l)=>{const{observability:u}=e,p=Date.now(),y=be(16),O=be(8),D=Zt(a),N=an(y,O,!0);try{const R=await l(N);return ue(u,{durationMs:Date.now()-p,functionPath:o,ok:!0,spanId:O,traceId:y},D),R}catch(R){throw ue(u,{...Ne(o,Date.now()-p,R,{}),spanId:O,traceId:y},D),R}finally{bt(u,D)}},lt=async(o,a,l,u)=>{g(a);const p=[],y=v=>v instanceof Error?v:new Error(String(v)),O=e.crons?.[o.cron];if(O)try{await O(o,a,l)}catch(v){p.push(y(v))}const D=await xe(o.cron,a,l,p,y,u),N=!!e.backupStore&&e.backupCron!==void 0&&e.backupCron===o.cron;if(N)try{await ts(e,s,d,P(),o)}catch(v){p.push(y(v))}if(!O&&D===0&&!N){const v=[...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: ${v.length===0?"(none)":v.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)`)},or=_a({assertAdmin:z,dispatchScheduled:lt,queueHandler:e.queueHandler}),sr=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 S(d,r,Ce(Qa,{outcome:a},{authorization:`Bearer ${u}`,"content-type":"application/json"}))}catch{}},ar=async(o,a,l,u)=>{if(!e.authHandler)return;const p=e.authBasePath??Yt,y=Xt(l.pathname,p)?Cr(o):void 0;let O;try{O=await e.authHandler(y?.request??o)}catch(D){throw y?.overflowed()?new c("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413}):D}if(y?.overflowed())throw new c("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});if(O)return za(l.pathname,p)&&u.waitUntil?.(sr(a,O.status>=400?"fail":"ok")),O},ir=async({args:o,env:a,functionPath:l,request:u,shardKey:p,waitUntil:y})=>{dn(o,"REST");const O={functionPath:l,...p===void 0?{}:{shardKey:p}},{headers:D,identity:N}=await L(u,a,i);await Oe(O,N);const R=p??r,v=Ae(a,u,y),k=()=>ve(u,l,o,R,D,v),H=qe(O,e);return H&&e.x402Charge?e.x402Charge(u,{functionPath:l,price:H.price},k,Je({waitUntil:y})):k()},cr=Nr({functions:e.functions??{},invoke:ir,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;ci(Ie);const dr={[Ka]: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"}}),[La]:(o,a,l)=>Jn(o,a,l),[Wt]:(o,a,l,u)=>tr(o,a,u),[Ha]:(o,a,l,u)=>nr(o,a,u),[ko]:(o,a,l,u)=>kn(o,a,u),[ja]:(o,a,l,u)=>ce(o,a,u),[Ma]: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 jo(a);return Response.json(l,{headers:{"cache-control":"no-store"}})},...J,...Bn,...xn,...Hn,...Ln,...jn,...Mn,...$n,...Fn,...Kn,...Qn,...cr,...Ko({assertAdmin:z,getAuthAdmin:()=>e.authAdmin,parsePaging:Le,queryParameter:He,readJsonBody:ne})};let de=St(e.security),ht=!1;const ur=o=>{ht||(ht=!0,de=St(e.security,o??{}))},lr=async(o,a)=>{Ga(a)&&await I(o)},hr=(o,a)=>{if(!(a.pathname.startsWith(Be)||e.authHandler!==void 0&&Xt(a.pathname,e.authBasePath??Yt))||o.method!=="POST"&&o.method!=="PUT")return;const u=Number(o.headers.get("content-length")??""),p=Ca[a.pathname]??cn;if(Number.isFinite(u)&&u>p)throw new c("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413})},fr=async(o,a,l)=>{rt.set(o,l);const u=new URL(o.url);hr(o,u);const p=await ar(o,a,u,l);if(p)return p;if(Ie){const R=`${o.method} ${u.pathname}`,v=Ie[R]??Ie[u.pathname];if(v)return v(o,a,l)}const y=or[u.pathname];if(y)return y(o,a,l);const O=dr[u.pathname];if(O)return await lr(o,u.pathname),O(o,a,u,l);if(e.voiceAgents!==void 0&&u.pathname.startsWith(Vt))return Yn(o,a,u);if(u.pathname.startsWith(Be))return new Response("Not found",{status:404});const D=await Vn(o,a,l);if(D&&D.status!==404)return D;const N=await e.authDiscoveryHandler?.(o);return N?(await D?.body?.cancel(),N):D??new Response("Not found",{status:404})};return{async fetch(o,a,l){e.passThroughOnException&&l.passThroughOnException?.(),ur(a),g(a);const u=to(o,de);if(u)return u;const p=no(o,de);if(p)return Ke(p,o,de);try{const y=await fr(o,a,l);return Ke(y,o,de)}catch(y){return Ke(Rt(y),o,de)}finally{bt(e.observability,Zt(l))}},async queue(o,a,l){await ut(`queue:${Ya(o)}`,l,async u=>{const p=e.liveStreams===!1?Qt():{publish:(y,O,D)=>se(Ba,y,O,D,"trusted")};await e.queue?.(o,a,l,{traceparent:u},p,e.queueFetchImpl)})},async scheduled(o,a,l){await ut(`cron:${o.cron}`,l,async u=>{await lt(o,a,l,u)})},serverQuery:rr}},ui=e=>Pn(e),li=e=>typeof e=="function"?{fetch:e}:e,hi=e=>!!e.backupCron||Object.keys(e.crons??{}).length>0||Object.keys(e.cronJobs??{}).length>0,fi=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}:{}},Hi=(e,t)=>{const n=li(e),{email:r,queue:s,scheduled:i}=fi(e),d=h=>{const _={...ui({...h,httpRouter:n})};return i!==void 0&&!hi(h)&&(_.scheduled=async(S,T,P)=>{await i(S,T,P)}),s!==void 0&&h.queue===void 0&&(_.queue=async(S,T,P)=>{await s(S,T,P)}),r!==void 0&&(_.email=async(S,T,P)=>{await r(S,T,P)}),_};if(typeof t!="function")return d(t);const f=t;return{fetch:(h,m,_)=>d(f(m)).fetch(h,m,_),queue:(h,m,_)=>d(f(m)).queue?.(h,m,_)??Promise.resolve(),scheduled:(h,m,_)=>d(f(m)).scheduled(h,m,_),serverQuery:(h,m,_,S,T)=>d(f(m)).serverQuery(h,m,_,S,T),...r===void 0?{}:{email:(h,m,_)=>d(f(m)).email?.(h,m,_)??Promise.resolve()}}},pi=(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}},Li=(e={})=>(t,n,r)=>Pn(pi(e,n)).fetch(t,n,r??br),ji=e=>e;export{tt as COPY_AUTH_TO_JURISDICTION_OP,Dt as GET_AUTH_AUDIT_LOG_OP,br as NOOP_EXECUTION_CONTEXT,bn as PURGE_UNPINNED_AUTH_OP,Fi as composeIdentityResolvers,ui as composeWorker,Li as createLunoraHandler,Pn as createWorker,ji as defineRpcEnvelope,oi as probeRelayCount,pi as resolveLunoraOptions,Ki as routeIdentityResolvers,Hi as withFrameworkWorker};
|