@lunora/runtime 1.0.0-alpha.47 → 1.0.0-alpha.49
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
|
@@ -2644,6 +2644,18 @@ interface HttpActionContext {
|
|
|
2644
2644
|
* from the app's own source, never caller-supplied.
|
|
2645
2645
|
*/
|
|
2646
2646
|
scheduler?: SchedulerContext;
|
|
2647
|
+
/**
|
|
2648
|
+
* Object storage, present only when the app declared a `.storage(...)`.
|
|
2649
|
+
*
|
|
2650
|
+
* R2 is a worker binding, so an HTTP handler reaches it in the same place an
|
|
2651
|
+
* action does — the previous omission was incidental rather than principled.
|
|
2652
|
+
* (`db` stays absent, which is not the same category: an HTTP handler is not
|
|
2653
|
+
* transactional.)
|
|
2654
|
+
*
|
|
2655
|
+
* Typed `unknown` so the runtime stays free of a `@lunora/storage`
|
|
2656
|
+
* dependency; the server side narrows it to the real `Storage`.
|
|
2657
|
+
*/
|
|
2658
|
+
storage?: unknown;
|
|
2647
2659
|
}
|
|
2648
2660
|
/**
|
|
2649
2661
|
* The scheduler surface on an HTTP action context. Mirrors `@lunora/server`'s
|
|
@@ -3628,6 +3640,23 @@ interface WorkerOptions {
|
|
|
3628
3640
|
security?: SecurityOptions;
|
|
3629
3641
|
/** Namespace binding for the shard Durable Object (typically `env.SHARD`). */
|
|
3630
3642
|
shardDO: ShardNamespaceLike;
|
|
3643
|
+
/**
|
|
3644
|
+
* Resolve the app-facing storage capability from the worker `env` — the same
|
|
3645
|
+
* `createStorage(...)` / `createBucketStorage(...)` result the shard DO
|
|
3646
|
+
* receives, built over the same R2 bindings.
|
|
3647
|
+
*
|
|
3648
|
+
* This is what backs `ctx.storage` on an HTTP action. R2 is a worker binding,
|
|
3649
|
+
* so an HTTP handler can reach it directly and needs no shard hop; omitting
|
|
3650
|
+
* it left `HttpActionCtx` without storage, so a handler could not store an
|
|
3651
|
+
* upload or mint a presigned URL. The requirement then propagated outward:
|
|
3652
|
+
* any helper the ctx was threaded into had to be typed for the worst case,
|
|
3653
|
+
* which barred every HTTP caller from the helper entirely — even on the
|
|
3654
|
+
* branches that never touch storage.
|
|
3655
|
+
*
|
|
3656
|
+
* Distinct from the `storage*` options below, which are the admin-gated
|
|
3657
|
+
* studio file-browser ops, not the app surface.
|
|
3658
|
+
*/
|
|
3659
|
+
storage?: (env: unknown) => unknown;
|
|
3631
3660
|
/**
|
|
3632
3661
|
* Names of the storage buckets the studio's file browser offers in its bucket
|
|
3633
3662
|
* picker, backing `GET /_lunora/admin/storage/buckets`. Supply the keys of a
|
package/dist/index.d.ts
CHANGED
|
@@ -2644,6 +2644,18 @@ interface HttpActionContext {
|
|
|
2644
2644
|
* from the app's own source, never caller-supplied.
|
|
2645
2645
|
*/
|
|
2646
2646
|
scheduler?: SchedulerContext;
|
|
2647
|
+
/**
|
|
2648
|
+
* Object storage, present only when the app declared a `.storage(...)`.
|
|
2649
|
+
*
|
|
2650
|
+
* R2 is a worker binding, so an HTTP handler reaches it in the same place an
|
|
2651
|
+
* action does — the previous omission was incidental rather than principled.
|
|
2652
|
+
* (`db` stays absent, which is not the same category: an HTTP handler is not
|
|
2653
|
+
* transactional.)
|
|
2654
|
+
*
|
|
2655
|
+
* Typed `unknown` so the runtime stays free of a `@lunora/storage`
|
|
2656
|
+
* dependency; the server side narrows it to the real `Storage`.
|
|
2657
|
+
*/
|
|
2658
|
+
storage?: unknown;
|
|
2647
2659
|
}
|
|
2648
2660
|
/**
|
|
2649
2661
|
* The scheduler surface on an HTTP action context. Mirrors `@lunora/server`'s
|
|
@@ -3628,6 +3640,23 @@ interface WorkerOptions {
|
|
|
3628
3640
|
security?: SecurityOptions;
|
|
3629
3641
|
/** Namespace binding for the shard Durable Object (typically `env.SHARD`). */
|
|
3630
3642
|
shardDO: ShardNamespaceLike;
|
|
3643
|
+
/**
|
|
3644
|
+
* Resolve the app-facing storage capability from the worker `env` — the same
|
|
3645
|
+
* `createStorage(...)` / `createBucketStorage(...)` result the shard DO
|
|
3646
|
+
* receives, built over the same R2 bindings.
|
|
3647
|
+
*
|
|
3648
|
+
* This is what backs `ctx.storage` on an HTTP action. R2 is a worker binding,
|
|
3649
|
+
* so an HTTP handler can reach it directly and needs no shard hop; omitting
|
|
3650
|
+
* it left `HttpActionCtx` without storage, so a handler could not store an
|
|
3651
|
+
* upload or mint a presigned URL. The requirement then propagated outward:
|
|
3652
|
+
* any helper the ctx was threaded into had to be typed for the worst case,
|
|
3653
|
+
* which barred every HTTP caller from the helper entirely — even on the
|
|
3654
|
+
* branches that never touch storage.
|
|
3655
|
+
*
|
|
3656
|
+
* Distinct from the `storage*` options below, which are the admin-gated
|
|
3657
|
+
* studio file-browser ops, not the app surface.
|
|
3658
|
+
*/
|
|
3659
|
+
storage?: (env: unknown) => unknown;
|
|
3631
3660
|
/**
|
|
3632
3661
|
* Names of the storage buckets the studio's file browser offers in its bucket
|
|
3633
3662
|
* picker, backing `GET /_lunora/admin/storage/buckets`. Supply the keys of a
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{toAirbyteMessages as t,toFivetranResponse as a}from"./packem_shared/toAirbyteMessages-DBTuFjb5.mjs";import{composeWorker as s,createLunoraHandler as n,createWorker as p,defineRpcEnvelope as m,resolveLunoraOptions as c,withFrameworkWorker as R}from"./packem_shared/composeWorker-
|
|
1
|
+
import{toAirbyteMessages as t,toFivetranResponse as a}from"./packem_shared/toAirbyteMessages-DBTuFjb5.mjs";import{composeWorker as s,createLunoraHandler as n,createWorker as p,defineRpcEnvelope as m,resolveLunoraOptions as c,withFrameworkWorker as R}from"./packem_shared/composeWorker-HS52JXMo.mjs";import{createCrossShardRelationCapabilities as E}from"./packem_shared/createCrossShardRelationCapabilities-CMWiFA5s.mjs";import{DEFAULT_REGISTRY_CACHE_TTL_MS as f,SHARD_REGISTRY_DO_NAME as l,createDynamicShardRegistry as x}from"./packem_shared/DEFAULT_REGISTRY_CACHE_TTL_MS-BclNO0yc.mjs";import{LunoraError as C,toErrorResponse as L}from"./packem_shared/LunoraError-ByasbDmd.mjs";import{createKvCursorStore as y,createMemoryCursorStore as g,defineExportSink as T,r2Sink as A,runExportTap as h,sanitizeChange as k,webhookExportSink as O}from"./packem_shared/createKvCursorStore-C24tEuYk.mjs";import{HEALTH_PATH as v,HEALTH_READY_PATH as I,buildHealthRoutes as b,d1Probe as F,durableObjectProbe as P,presenceProbe as D}from"./packem_shared/HEALTH_PATH-BpCNEAIa.mjs";import{LOG_ARCHIVE_PATH as G,resolveLogArchiveFromEnv as M}from"./packem_shared/LOG_ARCHIVE_PATH-DGsEec3K.mjs";import{memoizeIdentity as w,memoizeIdentityPerRequest as z}from"./packem_shared/memoizeIdentity-CZGtDc4H.mjs";import{e as W,a as Y}from"./packem_shared/observability-DYnm-d4g.mjs";import{analyticsEngineSink as K,combineSinks as Q,consoleSink as X,otlpSink as j,pipelineLogSink as J,sentrySink as B,webhookSink as Z}from"./packem_shared/analyticsEngineSink-CUWYuLHs.mjs";import{D as ee,a as re,c as oe}from"./packem_shared/pipeline-log-reader-DU_CCGDA.mjs";import{createQueryCoordinator as ae,createStaticShardRegistry as ie,mergeStrategyForAggregate as se}from"./packem_shared/createQueryCoordinator-DYm2p9dH.mjs";import{applyJurisdiction as pe,resolveShard as me}from"./packem_shared/applyJurisdiction-8bzZjAPR.mjs";import{R as Re,d as Se,o as Ee}from"./packem_shared/rest-cache-5unAzdFN.mjs";import{argsFromQuery as fe,buildRestRoutes as le,createRestRateLimit as xe,readShardKey as _e,restSurfaceFromRegistry as Ce}from"./packem_shared/argsFromQuery-BkJXnIpe.mjs";import{decorateResponse as ue,enforceOrigin as ye,handleCorsPreflight as ge,resolveSecurity as Te}from"./packem_shared/decorateResponse-DBIWsRSZ.mjs";import{createShardClient as he}from"./packem_shared/createShardClient-BkZ9FokE.mjs";import{LOG_ARCHIVE_NOT_CONFIGURED as Oe}from"./packem_shared/LOG_ARCHIVE_NOT_CONFIGURED-CDpi4yFD.mjs";import{NOOP_EXECUTION_CONTEXT as ve}from"./packem_shared/NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{composeIdentityResolvers as be,routeIdentityResolvers as Fe}from"./packem_shared/composeIdentityResolvers-DwE0Jbww.mjs";const e="0.0.0";export{ee as DEFAULT_LOG_COLUMNS,re as DEFAULT_LOG_LIMIT,f as DEFAULT_REGISTRY_CACHE_TTL_MS,v as HEALTH_PATH,I as HEALTH_READY_PATH,Oe as LOG_ARCHIVE_NOT_CONFIGURED,G as LOG_ARCHIVE_PATH,C as LunoraError,ve as NOOP_EXECUTION_CONTEXT,l as SHARD_REGISTRY_DO_NAME,e as VERSION,K as analyticsEngineSink,pe as applyJurisdiction,Re as applyRestCache,fe as argsFromQuery,b as buildHealthRoutes,le as buildRestRoutes,Q as combineSinks,be as composeIdentityResolvers,s as composeWorker,X as consoleSink,E as createCrossShardRelationCapabilities,x as createDynamicShardRegistry,y as createKvCursorStore,n as createLunoraHandler,g as createMemoryCursorStore,oe as createPipelineLogReader,ae as createQueryCoordinator,xe as createRestRateLimit,he as createShardClient,ie as createStaticShardRegistry,p as createWorker,F as d1Probe,ue as decorateResponse,T as defineExportSink,m as defineRpcEnvelope,P as durableObjectProbe,W as emitLogEvent,Y as emitRpcEvent,ye as enforceOrigin,ge as handleCorsPreflight,w as memoizeIdentity,z as memoizeIdentityPerRequest,se as mergeStrategyForAggregate,j as otlpSink,J as pipelineLogSink,D as presenceProbe,A as r2Sink,_e as readShardKey,Se as requestCarriesCredentials,M as resolveLogArchiveFromEnv,c as resolveLunoraOptions,Te as resolveSecurity,me as resolveShard,Ee as restCacheHeaders,Ce as restSurfaceFromRegistry,Fe as routeIdentityResolvers,h as runExportTap,k as sanitizeChange,B as sentrySink,t as toAirbyteMessages,L as toErrorResponse,a as toFivetranResponse,O as webhookExportSink,Z as webhookSink,R as withFrameworkWorker};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import{isLunoraError as nr,toErrorBody as or}from"@lunora/errors";import{NOOP_EXECUTION_CONTEXT as ar}from"./NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{O as Re,m as sr,A as ir,R as dr,d as ur,i as cr,s as lr}from"./otlp-resource-B-ByO9qo.mjs";import{LunoraError as a,toErrorResponse as We}from"./LunoraError-ByasbDmd.mjs";import{runExportTap as hr}from"./createKvCursorStore-C24tEuYk.mjs";import{d as me}from"./method-guard-BbuR0VfS.mjs";import{buildHealthRoutes as pr,durableObjectProbe as fr,d1Probe as wr,presenceProbe as Ne}from"./HEALTH_PATH-BpCNEAIa.mjs";import{wrapResolverWithContract as mr}from"./composeIdentityResolvers-DwE0Jbww.mjs";import{composeIdentityResolvers as ga,routeIdentityResolvers as ba}from"./composeIdentityResolvers-DwE0Jbww.mjs";import{buildLogArchiveAdminRoutes as yr}from"./LOG_ARCHIVE_PATH-DGsEec3K.mjs";import{o as gr,f as He,a as ue}from"./observability-DYnm-d4g.mjs";import{resolveShard as Se,applyJurisdiction as Je}from"./applyJurisdiction-8bzZjAPR.mjs";import{buildRestRoutes as br}from"./argsFromQuery-BkJXnIpe.mjs";import{resolveSecurity as Ve,handleCorsPreflight as Or,enforceOrigin as Er,decorateResponse as Ue,enforceWebSocketOrigin as Ye}from"./decorateResponse-DBIWsRSZ.mjs";const Tr=e=>{const t=e??{};if(typeof t.bucket=="function")return t;const r={...t,bucketName:"default"};return r.bucket=()=>r,r},yt=(e,t)=>{if(e.size<t)return;const r=e.keys().next().value;r!==void 0&&e.delete(r)},_r="::relay::",Rr=(e,t)=>`${e}${_r}${String(t)}`,je=new TextEncoder,Sr=e=>{const t=String.fromCodePoint(...e);return btoa(t).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")},Ar=e=>{const t=e.replaceAll("-","+").replaceAll("_","/")+"===".slice((e.length+3)%4),r=atob(t),n=new Uint8Array(r.length);for(let s=0;s<r.length;s+=1)n[s]=r.codePointAt(s)??0;return n},vr=64,qe=new Map,gt=async e=>{const t=qe.get(e);if(t)return t;yt(qe,vr);const r=crypto.subtle.importKey("raw",je.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]);return qe.set(e,r),r},Dr=async(e,t)=>{const r=await gt(e),n=await crypto.subtle.sign("HMAC",r,je.encode(t));return Sr(new Uint8Array(n))},kr=async(e,t,r)=>{const n=await gt(e);return crypto.subtle.verify("HMAC",n,r,je.encode(t))},bt="v1",Ir=6e4,Pr=async(e,t={})=>{const r=(t.now??Date.now())+(t.ttlMs??Ir),n=`${bt}.${String(r)}`,s=await Dr(e,n);return{expiresAtMs:r,token:`${n}.${s}`}},Nr=async(e,t,r=Date.now())=>{if(e.length===0||t.length===0)return!1;const n=t.split(".");if(n.length!==3)return!1;const[s,d,c]=n;if(s!==bt||c.length===0)return!1;const l=Number(d);if(!Number.isFinite(l)||l<=r)return!1;let b;try{b=Ar(c)}catch{return!1}return kr(e,`${s}.${d}`,b)},k="/_lunora/admin/auth",Ur={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},P=(e,t)=>{const r=e[t];if(typeof r!="string"||r==="")throw new a(`\`${t}\` is required`,{code:"BAD_REQUEST",status:400});return r},he=(e,t)=>{const r=e(t);if(r===void 0)throw new a(`\`${t}\` query parameter is required`,{code:"BAD_REQUEST",status:400});return r},$e=e=>{if(typeof e=="string"||Array.isArray(e)&&e.every(t=>typeof t=="string"))return e},ee=(e,t)=>typeof e[t]=="string"?e[t]:void 0,Xe=(e,t)=>{const r=e[t];return typeof r=="object"&&r!==null&&!Array.isArray(r)?r:void 0},Ze=e=>{const t=e.permission;if(typeof t!="object"||t===null||Array.isArray(t))throw new a("`permission` object is required",{code:"BAD_REQUEST",status:400});const r={};for(const[n,s]of Object.entries(t))Array.isArray(s)&&s.every(d=>typeof d=="string")&&(r[n]=s);return r},qr={[`${k}/capabilities`]:{build:()=>({}),http:"GET",method:"capabilities"},[`${k}/users`]:{build:({paging:e,query:t})=>{const r=t("sortDirection");return{...e,filterField:t("filterField"),filterValue:t("filterValue"),search:t("search"),searchField:t("searchField"),sortBy:t("sortBy"),sortDirection:r==="asc"||r==="desc"?r:void 0}},http:"GET",method:"listUsers"},[`${k}/sessions`]:{build:({paging:e,query:t})=>({...e,userId:t("userId")}),http:"GET",method:"listSessions"},[`${k}/accounts`]:{build:({query:e})=>({userId:he(e,"userId")}),http:"GET",method:"listAccounts"},[`${k}/passkeys`]:{build:({query:e})=>({userId:he(e,"userId")}),http:"GET",method:"listPasskeys"},[`${k}/organizations`]:{build:({paging:e})=>({...e}),http:"GET",method:"listOrganizations"},[`${k}/organizations/members`]:{build:({paging:e,query:t})=>({...e,organizationId:he(t,"organizationId")}),http:"GET",method:"listMembers"},[`${k}/organizations/invitations`]:{build:({paging:e,query:t})=>({...e,organizationId:he(t,"organizationId")}),http:"GET",method:"listInvitations"},[`${k}/config`]:{build:()=>({}),http:"GET",method:"config"},[`${k}/organizations/teams`]:{build:({paging:e,query:t})=>({...e,organizationId:he(t,"organizationId")}),http:"GET",method:"listTeams"},[`${k}/organizations/teams/members`]:{build:({paging:e,query:t})=>({...e,teamId:he(t,"teamId")}),http:"GET",method:"listTeamMembers"},[`${k}/organizations/roles`]:{build:({paging:e,query:t})=>({...e,organizationId:he(t,"organizationId")}),http:"GET",method:"listOrgRoles"},[`${k}/users/create`]:{build:({body:e})=>({data:typeof e.data=="object"&&e.data!==null&&!Array.isArray(e.data)?e.data:void 0,email:P(e,"email"),name:P(e,"name"),password:ee(e,"password"),role:$e(e.role)}),http:"POST",method:"createUser"},[`${k}/users/update`]:{build:({body:e})=>{const{data:t}=e;if(typeof t!="object"||t===null||Array.isArray(t))throw new a("`data` object is required",{code:"BAD_REQUEST",status:400});return{data:t,userId:P(e,"userId")}},http:"POST",method:"updateUser"},[`${k}/users/role`]:{build:({body:e})=>{const t=$e(e.role);if(t===void 0||typeof t=="string"&&t.trim()==="")throw new a("`role` is required",{code:"BAD_REQUEST",status:400});return{role:t,userId:P(e,"userId")}},http:"POST",method:"setRole"},[`${k}/users/ban`]:{build:({body:e})=>({expiresInSeconds:typeof e.expiresInSeconds=="number"?e.expiresInSeconds:void 0,reason:ee(e,"reason"),userId:P(e,"userId")}),http:"POST",method:"banUser"},[`${k}/users/unban`]:{build:({body:e})=>({userId:P(e,"userId")}),http:"POST",method:"unbanUser"},[`${k}/users/password`]:{build:({body:e})=>({newPassword:P(e,"newPassword"),userId:P(e,"userId")}),http:"POST",method:"setUserPassword",returns:"void"},[`${k}/users/remove`]:{build:({body:e})=>({userId:P(e,"userId")}),http:"POST",method:"removeUser",returns:"void"},[`${k}/users/impersonate`]:{build:({body:e})=>({userId:P(e,"userId")}),http:"POST",method:"impersonateUser"},[`${k}/sessions/revoke`]:{build:({body:e})=>({sessionId:P(e,"sessionId")}),http:"POST",method:"revokeUserSession",returns:"void"},[`${k}/sessions/revoke-all`]:{build:({body:e})=>({userId:P(e,"userId")}),http:"POST",method:"revokeUserSessions",returns:"void"},[`${k}/accounts/unlink`]:{build:({body:e})=>({accountId:P(e,"accountId"),userId:P(e,"userId")}),http:"POST",method:"unlinkAccount",returns:"void"},[`${k}/two-factor/disable`]:{build:({body:e})=>({userId:P(e,"userId")}),http:"POST",method:"disableTwoFactor",returns:"void"},[`${k}/passkeys/delete`]:{build:({body:e})=>({passkeyId:P(e,"passkeyId")}),http:"POST",method:"deletePasskey",returns:"void"},[`${k}/organizations/members/remove`]:{build:({body:e})=>({memberId:P(e,"memberId")}),http:"POST",method:"removeMember",returns:"void"},[`${k}/organizations/invitations/cancel`]:{build:({body:e})=>({invitationId:P(e,"invitationId")}),http:"POST",method:"cancelInvitation",returns:"void"},[`${k}/organizations/create`]:{build:({body:e})=>({logo:ee(e,"logo"),metadata:Xe(e,"metadata"),name:P(e,"name"),ownerId:ee(e,"ownerId"),slug:ee(e,"slug")}),http:"POST",method:"createOrganization"},[`${k}/organizations/update`]:{build:({body:e})=>({logo:ee(e,"logo"),metadata:Xe(e,"metadata"),name:ee(e,"name"),organizationId:P(e,"organizationId"),slug:ee(e,"slug")}),http:"POST",method:"updateOrganization"},[`${k}/organizations/remove`]:{build:({body:e})=>({organizationId:P(e,"organizationId")}),http:"POST",method:"deleteOrganization",returns:"void"},[`${k}/organizations/members/add`]:{build:({body:e})=>({organizationId:P(e,"organizationId"),role:ee(e,"role"),userId:P(e,"userId")}),http:"POST",method:"addMember"},[`${k}/organizations/members/invite`]:{build:({body:e})=>({email:P(e,"email"),inviterId:ee(e,"inviterId"),organizationId:P(e,"organizationId"),role:ee(e,"role")}),http:"POST",method:"inviteMember"},[`${k}/organizations/members/role`]:{build:({body:e})=>{const t=$e(e.role);if(t===void 0||typeof t=="string"&&t.trim()==="")throw new a("`role` is required",{code:"BAD_REQUEST",status:400});return{memberId:P(e,"memberId"),role:t}},http:"POST",method:"updateMemberRole"},[`${k}/organizations/teams/create`]:{build:({body:e})=>({name:P(e,"name"),organizationId:P(e,"organizationId")}),http:"POST",method:"createTeam"},[`${k}/organizations/teams/update`]:{build:({body:e})=>({name:P(e,"name"),teamId:P(e,"teamId")}),http:"POST",method:"updateTeam"},[`${k}/organizations/teams/remove`]:{build:({body:e})=>({teamId:P(e,"teamId")}),http:"POST",method:"removeTeam",returns:"void"},[`${k}/organizations/teams/members/add`]:{build:({body:e})=>({teamId:P(e,"teamId"),userId:P(e,"userId")}),http:"POST",method:"addTeamMember"},[`${k}/organizations/teams/members/remove`]:{build:({body:e})=>({teamMemberId:P(e,"teamMemberId")}),http:"POST",method:"removeTeamMember",returns:"void"},[`${k}/organizations/roles/create`]:{build:({body:e})=>({organizationId:P(e,"organizationId"),permission:Ze(e),role:P(e,"role")}),http:"POST",method:"createOrgRole"},[`${k}/organizations/roles/update`]:{build:({body:e})=>({permission:Ze(e),roleId:P(e,"roleId")}),http:"POST",method:"updateOrgRole"},[`${k}/organizations/roles/remove`]:{build:({body:e})=>({roleId:P(e,"roleId")}),http:"POST",method:"deleteOrgRole",returns:"void"}},$r=e=>{const t=async s=>{try{return await s()}catch(d){if(d instanceof a)throw d;const c=d,l=typeof c.code=="string"?c.code:"AUTH_ADMIN_ERROR";throw console.error("[lunora] auth admin operation failed:",d),new a("auth admin operation failed",{code:l,status:Ur[l]??500})}},r=async(s,d)=>{if(e.assertAdmin(s),s.method!==d.http)throw new a(`Auth admin endpoint requires ${d.http}`,{code:"METHOD_NOT_ALLOWED",status:405});const c=e.getAuthAdmin();if(c===void 0)throw new a("auth endpoints require an `authAdmin` on the worker",{code:"AUTH_NOT_CONFIGURED",status:400});const l=c[d.method];if(l===void 0)throw new a(`auth admin does not support \`${d.method}\``,{code:"AUTH_OP_NOT_SUPPORTED",status:400});const b=new URL(s.url),T={body:d.http==="POST"?await e.readJsonBody(s):{},paging:e.parsePaging(s),query:g=>e.queryParameter(b,g)},D=d.build(T),w=await t(()=>l(D));return Response.json(d.returns==="void"?{ok:!0}:w,{headers:{"content-type":"application/json"},status:200})},n={};for(const[s,d]of Object.entries(qr))n[s]=c=>r(c,d);return n},xr="__lunora_admin__:getAuthAuditLog",et=e=>typeof e=="string"&&e!==""?e:void 0,tt=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0,Lr=e=>async(t,r)=>{e.assertAdmin(t);const n=e.getReader();if(n===void 0)throw new a("the auth/security audit endpoint requires an `authAuditReader` on the worker",{code:"AUTH_AUDIT_NOT_CONFIGURED",status:400});const s={},d=et(r.actorId),c=et(r.event),l=tt(r.sinceSeq),b=tt(r.limit);d!==void 0&&(s.actorId=d),c!==void 0&&(s.event=c),l!==void 0&&(s.sinceSeq=l),b!==void 0&&(s.limit=b);let T;try{T=await n.read(s)}catch(w){throw w instanceof a?w:(console.error("[lunora] auth audit read failed:",w),new a("auth audit read failed",{code:"AUTH_AUDIT_READ_FAILED",status:500}))}const D={entries:T};return Response.json(D,{headers:{"content-type":"application/json"},status:200})},rt=500,Br=(e,t,r)=>{if(typeof e!="object"||e===null||Array.isArray(e))throw new a("each batch call must be an object",{code:"BAD_REQUEST",status:400});const n=e;if(typeof n.functionPath!="string")throw new a("each batch call needs a string `functionPath`",{code:"BAD_REQUEST",status:400});if(n.functionPath.startsWith("__lunora_relation__:")||n.functionPath.startsWith("__lunora_admin__"))throw new a("reserved function path cannot be batched",{code:"FORBIDDEN",status:403});if(n.args!==void 0&&(typeof n.args!="object"||n.args===null||Array.isArray(n.args)))throw new a("each batch call `args` must be an object",{code:"BAD_REQUEST",status:400});return{entry:{args:n.args===void 0?{}:n.args,clientId:typeof n.clientId=="string"?n.clientId:void 0,clientSeq:typeof n.clientSeq=="number"?n.clientSeq:void 0,functionPath:n.functionPath,id:typeof n.id=="number"?n.id:t,mutationId:typeof n.mutationId=="string"?n.mutationId:void 0},shardKey:typeof n.shardKey=="string"?n.shardKey:r}},Cr=(e,t)=>{if(e.length>rt)throw new a(`RPC batch exceeds the ${String(rt)}-call limit`,{code:"BAD_REQUEST",status:400});const r=new Map;for(const[n,s]of e.entries()){const{entry:d,shardKey:c}=Br(s,n,t),l=r.get(c)??[];l.push(d),r.set(c,l)}return r},ge=1048576,se=async(e,t=ge)=>{if(!e.body)return"";const r=e.body.getReader(),n=new TextDecoder;let s=0,d="";for(;;){const{done:c,value:l}=await r.read();if(c)break;if(l){if(s+=l.byteLength,s>t)throw await r.cancel().catch(()=>{}),new a("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});d+=n.decode(l,{stream:!0})}}return d+=n.decode(),d},jr=async(e,t=ge)=>{if(!e.body)return new ArrayBuffer(0);const r=e.body.getReader(),n=[];let s=0;for(;;){const{done:l,value:b}=await r.read();if(l)break;if(b){if(s+=b.byteLength,s>t)throw await r.cancel().catch(()=>{}),new a("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});n.push(b)}}const d=new Uint8Array(s);let c=0;for(const l of n)d.set(l,c),c+=l.byteLength;return d.buffer},te=async(e,t=ge)=>{try{const r=await se(e,t);return r===""?{}:JSON.parse(r)}catch(r){throw r instanceof a?r:new a("Request body must be valid JSON",{code:"BAD_REQUEST",status:400})}},Gr=new TextEncoder,Mr=e=>{const t=JSON.stringify(e),r=Gr.encode(t);let n="";for(const s of r)n+=String.fromCodePoint(s);return btoa(n).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")},Kr=e=>{const t={g:0,s:{},v:1};if(typeof e!="string"||e.length===0)return t;try{const r=atob(e.replaceAll("-","+").replaceAll("_","/")),n=new Uint8Array(r.length);for(let l=0;l<r.length;l+=1)n[l]=r.codePointAt(l)??0;const s=JSON.parse(new TextDecoder().decode(n)),d=s.s&&typeof s.s=="object"?s.s:{},c={};for(const[l,b]of Object.entries(d))typeof b=="number"&&Number.isFinite(b)&&(c[l]=b);return{g:typeof s.g=="number"&&Number.isFinite(s.g)?s.g:0,s:c,v:1}}catch{return t}},Fr=e=>{const t=typeof e.table=="string"?e.table:"",r=typeof e.op=="string"?e.op:"",n=r==="delete"||r==="insert"||r==="update"?r:"upsert",s=typeof e.id=="string"?e.id:void 0;return{doc:(e.doc&&typeof e.doc=="object"?e.doc:void 0)??(s===void 0?{}:{_id:s}),op:n,table:t}},nt=(e,t,r)=>{for(const n of t)e.push(Fr(n));return r!==void 0&&t.length>=r},Qr="/_lunora/admin/export",zr="/_lunora/admin/import",Wr="/_lunora/admin/sync",Hr="/_lunora/admin/connector/sync",Jr="/_lunora/admin/apply",Vr="/_lunora/admin/export-tap/run",Yr=new TextEncoder,Xr=async e=>{let t;try{const s=await se(e);t=s===""?{}:JSON.parse(s)}catch(s){throw s instanceof a?s:new a("Export body must be valid JSON",{code:"BAD_REQUEST",status:400})}const r=t??{};if(r.tables===void 0)return{tables:void 0};if(!Array.isArray(r.tables))throw new a("Export `tables` must be a string array",{code:"BAD_REQUEST",status:400});const n=[];for(const s of r.tables){if(typeof s!="string"||s.length===0)throw new a("Export `tables` entries must be non-empty strings",{code:"BAD_REQUEST",status:400});n.push(s)}return{tables:n}},Zr=e=>{const{applyGlobals:t,exportCursorStore:r,exportSinks:n,knownTables:s,queryCoordinator:d,assertAdmin:c,requireAdminOption:l,resolveForwardContext:b,shardDO:T,streamExportRows:D,streamingImport:w,syncGlobals:g}=e,p=async(v,B)=>{const C=me(v,["POST"]);if(C)return C;const Y=l(v,d,{code:"BAD_REQUEST",message:"Export endpoint requires a `queryCoordinator` on the worker"}),N=await Xr(v),{headers:K}=await b(v,B),F=new ReadableStream({async pull(j){const M=X=>{j.enqueue(Yr.encode(`${JSON.stringify(X)}
|
|
2
|
+
`))};try{await D(Y,K,N.tables,M),j.close()}catch(X){j.error(X)}}});return new Response(F,{headers:{"content-type":"application/x-ndjson"},status:200})},y=async(v,B)=>{const C=me(v,["POST"]);if(C)return C;const Y=l(v,d,{code:"BAD_REQUEST",message:"Sync endpoint requires a `queryCoordinator` on the worker"}),N=await te(v),K=typeof N.cursors=="object"&&N.cursors!==null?N.cursors:{},F=typeof N.limit=="number"?N.limit:void 0,j=typeof N.globalCursor=="number"?N.globalCursor:0,M=Array.isArray(N.tables)?N.tables.filter(Z=>typeof Z=="string"):void 0,{headers:X}=await b(v,B),J=M??s(),oe=await Y.orchestrateCdcSync(T,{cursors:K,headers:X,limit:F,tables:J}),ie=g?await g({limit:F,sinceSeq:j}):void 0;return Response.json({global:ie,shards:oe.shards},{status:200})},_=async(v,B)=>{const C=me(v,["POST"]);if(C)return C;const Y=l(v,d,{code:"BAD_REQUEST",message:"Connector sync endpoint requires a `queryCoordinator` on the worker"}),N=await te(v),K=Kr(N.cursor),F=typeof N.limit=="number"&&N.limit>0?N.limit:void 0,j=Array.isArray(N.tables)?N.tables.filter(re=>typeof re=="string"):void 0,{headers:M}=await b(v,B),X=j??s(),J=await Y.orchestrateCdcSync(T,{cursors:K.s,headers:M,limit:F,tables:X}),oe=[],ie={...K.s};let Z=!1;for(const re of J.shards)Z=nt(oe,re.changes??[],F)||Z,ie[re.shardKey]=re.cursor;let pe=K.g;if(g){const re=await g({limit:F,sinceSeq:K.g});Z=nt(oe,re.changes,F)||Z,pe=re.cursor}const be=Mr({g:pe,s:ie,v:1}),Ae={changes:oe,hasMore:Z,nextCursor:be};return Response.json(Ae,{status:200})},R=async(v,B)=>{const C=me(v,["POST"]);if(C)return C;const Y=l(v,d,{code:"BAD_REQUEST",message:"Apply endpoint requires a `queryCoordinator` on the worker"}),N=await te(v),K=(Array.isArray(N.batches)?N.batches:[]).map(J=>J).filter(J=>J!==null&&typeof J=="object"&&typeof J.shardKey=="string"&&Array.isArray(J.changes)),F=Array.isArray(N.globalChanges)?N.globalChanges:[],{headers:j}=await b(v,B),M=await Y.orchestrateApplyCdc(T,{batches:K,headers:j}),X=F.length>0&&t?await t({changes:F}):0;return Response.json({applied:M.applied+X,failed:M.failed,ok:M.ok},{status:200})},I=async(v,B)=>{const C=me(v,["POST"]);if(C)return C;c(v);const{headers:Y}=await b(v,B),N=await w(v,Y);return Response.json(N,{headers:{"content-type":"application/json"},status:200})},x=async(v,B)=>{const C=me(v,["POST"]);if(C)return C;const Y=l(v,d,{code:"BAD_REQUEST",message:"Export-tap endpoint requires a `queryCoordinator` on the worker"});if(n===void 0||Object.keys(n).length===0||r===void 0)throw new a("Export-tap endpoint requires `exportSinks` + `exportCursorStore` on the worker",{code:"EXPORT_TAP_NOT_CONFIGURED",status:400});const N=await te(v),K=typeof N.sink=="string"?N.sink:void 0,F=typeof N.limit=="number"&&N.limit>0?N.limit:void 0,j=Array.isArray(N.tables)?N.tables.filter(ie=>typeof ie=="string"):void 0;if(K===void 0)throw new a("Export-tap `sink` must name a configured sink",{code:"BAD_REQUEST",status:400});const M=n[K];if(M===void 0)throw new a(`Export-tap sink "${K}" is not configured`,{code:"NOT_FOUND",status:404});const{headers:X}=await b(v,B),J=j??s(),oe=await hr({coordinator:Y,cursorStore:r,headers:X,limit:F,shardDO:T,sink:M,tables:J});return Response.json(oe,{headers:{"content-type":"application/json"},status:200})};return{[Jr]:R,[Hr]:_,[Qr]:p,[Vr]:x,[zr]:I,[Wr]:y}},Ot=e=>[],en=(e,t)=>{const r=[],n=[];if(t&&t.length>0)for(const s of t)e.resolveTableSharding?.(s)?.mode.kind==="global"?n.push(s):r.push(s);return{globalTables:n,shardLocalTables:r}},tn=async(e,t,r,n,s,d,c)=>{if(n!==void 0&&s.length===0)return;const l=n===void 0?[]:s,b=n===void 0?Ot():[],T=l.length>0?l:b,D=await t.orchestrateExport(c,{args:{tables:l},headers:r,tables:T});for(const w of D.shards)if(!w.error)for(const g of w.rows??[])d(g)},ot=async(e,t,r,n,s,d)=>{const{globalTables:c,shardLocalTables:l}=en(e,n);await tn(e,t,r,n,l,s,d);const b=e.exportGlobals;if((n===void 0||c.length>0)&&b){const T=n===void 0?[]:c;for await(const D of b({tables:T}))s(D)}},rn=(e,t)=>{let r;try{r=JSON.parse(e)}catch{return{error:{code:"BAD_ROW",line:t,message:"line is not valid JSON",table:""},ok:!1}}if(!r||typeof r!="object"||Array.isArray(r))return{error:{code:"BAD_ROW",line:t,message:"row must be a JSON object",table:""},ok:!1};const n=r;return typeof n.table!="string"||n.table.length===0?{error:{code:"BAD_ROW",line:t,message:"row is missing `table`",table:""},ok:!1}:!n.doc||typeof n.doc!="object"||Array.isArray(n.doc)?{error:{code:"BAD_ROW",line:t,message:"row is missing or malformed `doc`",table:n.table},ok:!1}:{doc:n.doc,ok:!0,table:n.table}},nn=(e,t,r,n,s)=>{if(r?.mode.kind==="shardBy"&&typeof r.mode.field=="string"){const d=e[r.mode.field];return d==null?{error:{code:"BAD_ROW",line:s,message:`row missing shard field "${r.mode.field}" for table "${t}"`,table:t},ok:!1}:{ok:!0,shardKey:typeof d=="string"?d:JSON.stringify(d)}}return{ok:!0,shardKey:n}},on=async(e,t,r)=>{if(!e.body)throw new a("Import endpoint requires a request body",{code:"BAD_REQUEST",status:400});const n=[],s=[],d=new Map;let c=0,l=0;const b=e.body.getReader(),T=new TextDecoder;let D="",w=0;const g=p=>{l+=1;const y=p.trim();if(y.length===0)return;c+=1;const _=rn(y,l);if(!_.ok){n.push(_.error);return}const{doc:R,table:I}=_,x=t.resolveTableSharding?.(I);if(x?.mode.kind==="global"){s.push({doc:R,line:l,table:I});return}const v=nn(R,I,x,r,l);if(!v.ok){n.push(v.error);return}const B=d.get(v.shardKey);B?B.rows.push({doc:R,table:I}):d.set(v.shardKey,{rows:[{doc:R,table:I}],shardKey:v.shardKey,startLine:l})};for(;;){const{done:p,value:y}=await b.read();if(p)break;if(y&&(w+=y.byteLength,w>ge))throw await b.cancel().catch(()=>{}),new a("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});D+=T.decode(y,{stream:!0});let _=D.indexOf(`
|
|
3
|
+
`);for(;_!==-1;){const R=D.slice(0,_);D=D.slice(_+1),g(R),_=D.indexOf(`
|
|
4
|
+
`)}}return D.length>0&&g(D),{errors:n,globalRows:s,perShard:d,received:c}},at=(e,t)=>{for(const[r,n]of Object.entries(t.inserted))e.inserted[r]=(e.inserted[r]??0)+n;for(const r of t.errors)e.errors.push({...r});e.conflicts+=t.conflicts},an=async(e,t,r,n)=>{const s=t.defaultShardKey??"__root__",{errors:d,globalRows:c,perShard:l,received:b}=await on(e,t,s),T={conflicts:0,errors:d,inserted:{}},D=[];if(t.resolveTableSharding===void 0&&l.size>0&&D.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"),l.size>0){const w=t.queryCoordinator;if(!w)throw new a("Import endpoint requires a `queryCoordinator` on the worker",{code:"BAD_REQUEST",status:400});const g=await w.orchestrateImport(n,{batches:[...l.values()],headers:r});at(T,g)}if(c.length>0)if(t.importGlobals){const w=c[0]?.line??1,g=await t.importGlobals({rows:c,startLine:w});at(T,g)}else for(const w of c)T.errors.push({code:"GLOBAL_NOT_CONFIGURED",line:w.line,message:`row targets global table "${w.table}" but no \`importGlobals\` is configured`,table:w.table});return{conflicts:T.conflicts,errors:T.errors,inserted:T.inserted,received:b,...D.length>0?{warnings:D}:{}}},xe=e=>typeof e=="object"&&e!==null?e:{},Le=e=>typeof e.kind=="string"?e.kind:"unknown",sn=(e,t)=>{let r=xe(t),n=!1;Le(r)==="optional"&&(n=!0,r=xe(r._meta?.inner));const s=Le(r),d=r._meta??{},c={kind:s,name:e,optional:n};if(s==="id"&&typeof d.tableName=="string"&&(c.table=d.tableName),s==="array"){const l=Le(xe(d.inner));l!=="unknown"&&(c.element=l)}return c},dn=e=>typeof e!="object"||e===null?[]:Object.entries(e).map(([t,r])=>sn(t,r)).toSorted((t,r)=>t.name.localeCompare(r.name)),un="/_lunora/admin/functions",cn="/_lunora/admin/cron-jobs",ln="/_lunora/admin/openapi",hn="/_lunora/admin/openrpc",pn="/_lunora/admin/global/tables",fn="/_lunora/admin/global/table",wn="/_lunora/admin/global/facet",st=e=>{if(e===void 0||e==="")return;let t;try{t=JSON.parse(e)}catch{return}if(!Array.isArray(t))return;const r=t.flatMap(n=>{if(typeof n!="object"||n===null||typeof n.column!="string")return[];const{column:s,value:d}=n;return[{column:s,value:d}]});return r.length===0?void 0:r},mn=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:{}}),yn=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"}),gn=e=>{const{assertAdmin:t,options:r,parsePaging:n,queryParameter:s,requireAdminOption:d}=e,c=p=>{if(p.method!=="GET")throw new a("Functions endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});const y=d(p,r.functions,{code:"FUNCTIONS_NOT_CONFIGURED",message:"functions endpoint requires a `functions` registry on the worker"}),_=Object.entries(y).flatMap(([R,I])=>I.visibility==="internal"||I.kind==="stream"?[]:[{args:dn(I.args),kind:I.kind,path:R}]).toSorted((R,I)=>R.path.localeCompare(I.path));return Response.json({functions:_},{headers:{"content-type":"application/json"},status:200})},l=p=>{if(p.method!=="GET")throw new a("Cron-jobs endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});const y=d(p,r.cronJobs,{code:"CRON_JOBS_NOT_CONFIGURED",message:"cron-jobs endpoint requires a `cronJobs` map on the worker"}),_=Object.entries(y).flatMap(([R,I])=>I.map(x=>({args:x.args,cron:R,functionPath:x.functionPath,name:x.name,shardKey:x.shardKey,workflow:x.workflow}))).toSorted((R,I)=>R.name.localeCompare(I.name));return Response.json({jobs:_},{headers:{"content-type":"application/json"},status:200})},b=p=>{if(p.method!=="GET")throw new a("OpenAPI endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});return t(p),Response.json(r.openApiSpec??mn,{headers:{"content-type":"application/json"},status:200})},T=p=>{if(p.method!=="GET")throw new a("OpenRPC endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});return t(p),Response.json(r.openRpcSpec??yn,{headers:{"content-type":"application/json"},status:200})},D=async p=>{if(p.method!=="GET")throw new a("Global-tables endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});const y=d(p,r.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"});return Response.json(await y.listTables(),{headers:{"content-type":"application/json"},status:200})},w=async p=>{if(p.method!=="GET")throw new a("Global-table endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});const y=d(p,r.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),_=new URL(p.url),R=s(_,"table");if(R===void 0)throw new a("Global-table endpoint requires a `table` query param",{code:"BAD_REQUEST",status:400});const I=await y.readTablePage({...n(p),filters:st(s(_,"filters")),table:R});return Response.json(I,{headers:{"content-type":"application/json"},status:200})},g=async p=>{if(p.method!=="GET")throw new a("Global-facet endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});const y=d(p,r.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),_=new URL(p.url),R=s(_,"table"),I=s(_,"column");if(R===void 0||I===void 0)throw new a("Global-facet endpoint requires `table` and `column` query params",{code:"BAD_REQUEST",status:400});const x=s(_,"limit"),v=x===void 0?void 0:Number(x),B=await y.facetColumn({column:I,filters:st(s(_,"filters")),limit:v!==void 0&&Number.isFinite(v)?v:void 0,table:R});return Response.json(B,{headers:{"content-type":"application/json"},status:200})};return{[cn]:l,[un]:c,[wn]:g,[fn]:w,[pn]:D,[ln]:b,[hn]:T}},bn="/_lunora/admin/kv/namespaces",On="/_lunora/admin/kv/keys",Et="/_lunora/admin/kv/value",Tt=32*1048576,it=60,En=e=>{const{readJsonBody:t,requireAdminOption:r}=e,n=w=>r(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}),d=(w,g)=>{const p=new URL(w.url),y=p.searchParams.get("namespace")??"",_=p.searchParams.get("key")??"";if(y==="")throw new a(`KV-value ${g} request requires a \`namespace\` query parameter`,{code:"BAD_REQUEST",status:400});if(_==="")throw new a(`KV-value ${g} request requires a \`key\` query parameter`,{code:"BAD_REQUEST",status:400});return{key:_,namespace:y}},c=async(w,g)=>{if(!(await w.listNamespaces()).some(p=>p.binding===g))throw new a(`Unknown KV namespace binding \`${g}\``,{code:"NOT_FOUND",status:404})},l=async w=>{if(w.method!=="GET")throw new a("KV-namespaces endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});return s({namespaces:await n(w).listNamespaces()})},b=async w=>{if(w.method!=="GET")throw new a("KV-keys endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});const g=n(w),p=new URL(w.url),y=p.searchParams.get("namespace")??"";if(y==="")throw new a("KV-keys request requires a `namespace` query parameter",{code:"BAD_REQUEST",status:400});const _=p.searchParams.get("prefix")??void 0,R=p.searchParams.get("cursor")??void 0,I=p.searchParams.get("limit"),x=I===null?void 0:Number.parseInt(I,10);if(x!==void 0&&(!Number.isInteger(x)||x<1))throw new a("KV-keys `limit` must be a positive integer",{code:"BAD_REQUEST",status:400});const v=x===void 0?void 0:Math.min(x,1e3);return await c(g,y),s(await g.listKeys({cursor:R,limit:v,namespace:y,prefix:_}))},T={DELETE:async w=>{const g=n(w),p=d(w,"DELETE");return await c(g,p.namespace),await g.deleteKey(p),s({deleted:!0})},GET:async w=>{const g=n(w),p=d(w,"GET");return await c(g,p.namespace),s(await g.getValue(p))},PUT:async w=>{const g=n(w),p=await t(w,Tt);if(typeof p.namespace!="string"||p.namespace==="")throw new a("KV-value PUT request requires a `namespace` string",{code:"BAD_REQUEST",status:400});if(typeof p.key!="string"||p.key==="")throw new a("KV-value PUT request requires a `key` string",{code:"BAD_REQUEST",status:400});if(typeof p.value!="string")throw new a("KV-value PUT request requires a `value` string",{code:"BAD_REQUEST",status:400});if(p.expirationTtl!==void 0&&(typeof p.expirationTtl!="number"||!Number.isInteger(p.expirationTtl)||p.expirationTtl<it))throw new a("KV-value PUT `expirationTtl` must be an integer ≥ 60",{code:"BAD_REQUEST",status:400});const y=Math.floor(Date.now()/1e3)+it;if(p.expiration!==void 0&&(typeof p.expiration!="number"||!Number.isInteger(p.expiration)||p.expiration<y))throw new a("KV-value PUT `expiration` must be a Unix-seconds timestamp at least 60 seconds in the future",{code:"BAD_REQUEST",status:400});return await c(g,p.namespace),await g.putValue({expiration:p.expiration,expirationTtl:p.expirationTtl,key:p.key,metadata:p.metadata,namespace:p.namespace,value:p.value}),s({ok:!0})}},D=w=>{const g=T[w.method];if(!g)throw new a("KV-value endpoint requires GET, PUT, or DELETE",{code:"METHOD_NOT_ALLOWED",status:405});return g(w)};return{[bn]:l,[On]:b,[Et]:D}},Tn="/_lunora/migrate",_n="/_lunora/admin/pitr",Rn="/_lunora/admin/rank",Sn="/_lunora/admin/rankpage",An="/_lunora/admin/shard-traffic",vn=new Set(["__lunora_admin__:migrationStatus","__lunora_admin__:runMigration"]),Dn=new Set(["__lunora_admin__:getPitrBookmark","__lunora_admin__:pitrRestore"]),kn=async e=>{let t;try{const n=await se(e);t=n===""?{}:JSON.parse(n)}catch(n){throw n instanceof a?n:new a("Migration body must be valid JSON",{code:"BAD_REQUEST",status:400})}const r=t??{};if(typeof r.table!="string"||r.table.length===0)throw new a("Migration request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof r.functionPath!="string"||!vn.has(r.functionPath))throw new a("Migration request `functionPath` must be a migration admin op",{code:"BAD_REQUEST",status:400});return{args:r.args??{},functionPath:r.functionPath,table:r.table}},In=async e=>{let t;try{const n=await se(e);t=n===""?{}:JSON.parse(n)}catch(n){throw n instanceof a?n:new a("Rank body must be valid JSON",{code:"BAD_REQUEST",status:400})}const r=t??{};if(typeof r.table!="string"||r.table.length===0)throw new a("Rank request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof r.index!="string"||r.index.length===0)throw new a("Rank request is missing `index`",{code:"BAD_REQUEST",status:400});if(typeof r.partitionKey!="string")throw new a("Rank request `partitionKey` must be a string",{code:"BAD_REQUEST",status:400});if(typeof r.rowId!="string"||r.rowId.length===0)throw new a("Rank request is missing `rowId`",{code:"BAD_REQUEST",status:400});if(!Array.isArray(r.sortValues))throw new a("Rank request `sortValues` must be an array",{code:"BAD_REQUEST",status:400});return{index:r.index,partitionKey:r.partitionKey,rowId:r.rowId,sortValues:r.sortValues,table:r.table}},Pn=e=>{if(e!==void 0){if(!Array.isArray(e)||e.some(t=>t!=="asc"&&t!=="desc"))throw new a('Rank page request `directions` must be an array of "asc"|"desc"',{code:"BAD_REQUEST",status:400});return e}},Nn=e=>{if(typeof e.table!="string"||e.table.length===0)throw new a("Rank page request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof e.index!="string"||e.index.length===0)throw new a("Rank page request is missing `index`",{code:"BAD_REQUEST",status:400});if(e.partitionKey!==void 0&&typeof e.partitionKey!="string")throw new a("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 a("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 a("Rank page request `cursor` must be a string or null",{code:"BAD_REQUEST",status:400})},Un=async e=>{let t;try{const s=await se(e);t=s===""?{}:JSON.parse(s)}catch(s){throw s instanceof a?s:new a("Rank page body must be valid JSON",{code:"BAD_REQUEST",status:400})}const r=t??{};Nn(r);const n=Pn(r.directions);return{cursor:typeof r.cursor=="string"?r.cursor:null,directions:n,index:r.index,partitionKey:typeof r.partitionKey=="string"?r.partitionKey:void 0,table:r.table,take:typeof r.take=="number"?r.take:void 0}},qn=async e=>{let t;try{const n=await se(e);t=n===""?{}:JSON.parse(n)}catch(n){throw n instanceof a?n:new a("Shard-traffic body must be valid JSON",{code:"BAD_REQUEST",status:400})}const r=t??{};if(typeof r.table!="string"||r.table.length===0)throw new a("Shard-traffic request is missing `table`",{code:"BAD_REQUEST",status:400});return{table:r.table}},$n=async e=>{const t=await te(e);if(typeof t.functionPath!="string"||!Dn.has(t.functionPath))throw new a("PITR request `functionPath` must be a PITR admin op",{code:"BAD_REQUEST",status:400});if(t.shardKey!==void 0&&typeof t.shardKey!="string")throw new a("PITR `shardKey` must be a string",{code:"BAD_REQUEST",status:400});return{args:t.args??{},functionPath:t.functionPath,shardKey:t.shardKey}},xn=e=>{const{defaultShard:t,forwardToShard:r,isAdmin:n,queryCoordinator:s,resolveForwardContext:d,shardDO:c}=e,l=async(g,p)=>{if(g.method!=="POST")throw new a("Migration endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});if(!n(g))throw new a("Admin auth required",{code:"FORBIDDEN",status:403});if(!s)throw new a("Migration endpoint requires a `queryCoordinator` on the worker",{code:"BAD_REQUEST",status:400});const y=await kn(g),{headers:_}=await d(g,p),R=await s.orchestrateMigration(c,{args:y.args,functionPath:y.functionPath,headers:_,table:y.table});return Response.json(R,{headers:{"content-type":"application/json"},status:200})},b=async(g,p)=>{if(g.method!=="POST")throw new a("Rank endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});if(!n(g))throw new a("Admin auth required",{code:"FORBIDDEN",status:403});if(!s)throw new a("Rank endpoint requires a `queryCoordinator` on the worker",{code:"BAD_REQUEST",status:400});const y=await In(g),{headers:_}=await d(g,p),R=await s.orchestrateRank(c,{headers:_,index:y.index,partitionKey:y.partitionKey,rowId:y.rowId,sortValues:y.sortValues,table:y.table});return Response.json(R,{headers:{"content-type":"application/json"},status:200})},T=async(g,p)=>{if(g.method!=="POST")throw new a("Rank page endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});if(!n(g))throw new a("Admin auth required",{code:"FORBIDDEN",status:403});if(!s)throw new a("Rank page endpoint requires a `queryCoordinator` on the worker",{code:"BAD_REQUEST",status:400});const y=await Un(g),{headers:_}=await d(g,p),R=await s.orchestrateRankPage(c,{...y,headers:_});return Response.json(R,{headers:{"content-type":"application/json"},status:200})},D=async(g,p)=>{if(g.method!=="POST")throw new a("Shard-traffic endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});if(!n(g))throw new a("Admin auth required",{code:"FORBIDDEN",status:403});if(!s)throw new a("Shard-traffic endpoint requires a `queryCoordinator` on the worker",{code:"BAD_REQUEST",status:400});const y=await qn(g),{headers:_}=await d(g,p),R=await s.orchestrateShardTraffic(c,{headers:_,table:y.table});return Response.json(R,{headers:{"content-type":"application/json"},status:200})},w=async(g,p)=>{if(g.method!=="POST")throw new a("PITR endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});if(!n(g))throw new a("admin PITR endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403});const y=await $n(g),{headers:_}=await d(g,p),R=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:y.args,functionPath:y.functionPath}),headers:_,method:"POST"});return r(c,y.shardKey??t,R)};return{[Tn]:l,[_n]:w,[Rn]:b,[Sn]:T,[An]:D}},Ln=1,Bn=0,Cn=32,jn=512,Gn=/^[a-z][\d_a-z*/-]{0,255}(?:@[a-z][\d_a-z*/-]{0,13})?=[\u0020-\u002B\u002D-\u003C\u003E-\u007E]{1,256}$/,Mn=e=>{if(e==null)return;const t=e.trim();if(t.length===0||t.length>jn)return;const r=t.split(",");if(!(r.length>Cn)){for(const n of r)if(!Gn.test(n.trim()))return;return t}},Kn=e=>{const t=ir(e.headers.get("traceparent"));if(t===void 0)return;const r=Mn(e.headers.get("tracestate"));return{parentSpanId:t.parentSpanId,sampled:t.sampled,traceId:t.traceId,...r===void 0?{}:{traceState:r}}},Fn=(e,t={})=>{const r=Kn(e),n=t.trustInbound===!0?r:void 0,s=Re(8),d=n?.traceId??Re(16),c=gr(t.sampling,n===void 0?s:d),l=c.isTraced&&(n===void 0||n.sampled);return{decision:c,ignoredUpstream:r!==void 0&&n===void 0,trace:{sampled:l,spanId:s,traceFlags:l?Ln:Bn,traceId:d,...n?.parentSpanId===void 0?{}:{parentSpanId:n.parentSpanId},...n?.traceState===void 0?{}:{traceState:n.traceState}}}},Qn=(e,t)=>{t.traceparent=sr(e.traceId,e.spanId,e.sampled),e.traceState!==void 0&&(t.tracestate=e.traceState)},zn=(e,t)=>{let r;return()=>{if(r===void 0){const n=lr(e),s=t===void 0?void 0:t.cf;r=dr(cr(n),ur(n,s))}return r}},Wn="/_lunora/admin/scheduled",Hn="/_lunora/admin/scheduled/status",Jn="/_lunora/admin/scheduled/ws",Vn="/_lunora/admin/scheduled/cancel",Yn="/_lunora/admin/scheduled/dead",Xn="/_lunora/admin/scheduled/dead/retry",Zn="/_lunora/admin/scheduled/dead/cancel",eo=e=>{const{checkWsAdmin:t,requireSchedulerNamespace:r,resolveSchedulerStub:n,schedulerInstanceName:s}=e,d=async w=>{if(w.method!=="GET")throw new a("Scheduled-list endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});return n(w).fetch(new Request("https://scheduler.internal/list",{method:"GET"}))},c=async w=>{if(w.method!=="GET")throw new a("Scheduler-status endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});return n(w).fetch(new Request("https://scheduler.internal/status",{method:"GET"}))},l=async w=>{if(w.headers.get("Upgrade")!=="websocket")throw new a("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});if(!await t(w))throw new a("admin authorization required",{code:"ADMIN_FORBIDDEN",status:403});const g=r();return Se(g,s).fetch(new Request("https://scheduler.internal/ws",{headers:{Upgrade:"websocket"}}))},b=async w=>{if(w.method!=="POST")throw new a("Scheduled-cancel endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const g=n(w),p=await w.json().catch(()=>{});if(typeof p?.id!="string"||p.id==="")throw new a("Scheduled-cancel requires a string `id`",{code:"BAD_REQUEST",status:400});return g.fetch(new Request("https://scheduler.internal/cancel",{body:JSON.stringify({id:p.id}),headers:{"content-type":"application/json"},method:"POST"}))},T=async w=>{if(w.method!=="GET")throw new a("Scheduled dead-letter endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});return n(w).fetch(new Request("https://scheduler.internal/dead",{method:"GET"}))},D=w=>async g=>{if(g.method!=="POST")throw new a("Scheduled dead-letter action requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const p=n(g),y=await g.json().catch(()=>{});if(typeof y?.id!="string"||y.id==="")throw new a("Scheduled dead-letter action requires a string `id`",{code:"BAD_REQUEST",status:400});return p.fetch(new Request(`https://scheduler.internal${w}`,{body:JSON.stringify({id:y.id}),headers:{"content-type":"application/json"},method:"POST"}))};return{[Vn]:b,[Zn]:D("/dead/cancel"),[Yn]:T,[Xn]:D("/dead/retry"),[Wn]:d,[Hn]:c,[Jn]:l}},to="/_lunora/admin/storage",ro="/_lunora/admin/storage/url",no="/_lunora/admin/storage/buckets",oo=10080*60,ao=e=>{const{assertAdmin:t,parsePaging:r,queryParameter:n,readBodyBytes:s,requireAdminOption:d,storage:c}=e,l=y=>{const _=n(y,"key");if(_===void 0)throw new a("Storage endpoint requires a `key` query parameter",{code:"BAD_REQUEST",status:400});return _},b=async y=>{const _=d(y,c.storageList,{code:"STORAGE_NOT_CONFIGURED",message:"storage endpoint requires a `storageList` function on the worker"}),R=new URL(y.url),I=await _(n(R,"prefix"),{bucket:n(R,"bucket"),cursor:n(R,"cursor"),...r(y)});return Response.json(I,{headers:{"content-type":"application/json"},status:200})},T=y=>{if(y.method!=="GET")throw new a("Storage-buckets endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});return t(y),Response.json({buckets:c.storageBuckets??[]},{headers:{"content-type":"application/json"},status:200})},D=async y=>{const _=d(y,c.storageDelete,{code:"STORAGE_DELETE_NOT_CONFIGURED",message:"storage delete requires a `storageDelete` function on the worker"}),R=new URL(y.url),I=l(R);return await _(I,{bucket:n(R,"bucket")}),Response.json({deleted:!0,key:I},{headers:{"content-type":"application/json"},status:200})},w=async y=>{const _=d(y,c.storageUpload,{code:"STORAGE_UPLOAD_NOT_CONFIGURED",message:"storage upload requires a `storageUpload` function on the worker"}),R=new URL(y.url),I=l(R),x=await s(y),v=y.headers.get("content-type"),B=v===null||v===""?void 0:v,C=await _(I,x,{bucket:n(R,"bucket"),contentType:B});return Response.json(C,{headers:{"content-type":"application/json"},status:200})},g=async y=>{switch(y.method){case"DELETE":return D(y);case"GET":return b(y);case"POST":case"PUT":return w(y);default:throw new a("Storage endpoint requires GET, PUT, POST, or DELETE",{code:"METHOD_NOT_ALLOWED",status:405})}},p=async y=>{if(y.method!=="GET")throw new a("Storage URL endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});const _=d(y,c.storageSignedUrl,{code:"STORAGE_URL_NOT_CONFIGURED",message:"storage URL endpoint requires a `storageSignedUrl` function on the worker"}),R=new URL(y.url),I=l(R),x=Number(n(R,"expiresIn")??""),v=Number.isFinite(x)&&x>0?Math.min(x,oo):void 0,B=await _(I,{bucket:n(R,"bucket"),expiresInSeconds:v});return Response.json({key:I,url:B},{headers:{"content-type":"application/json"},status:200})};return{[no]:T,[to]:g,[ro]:p}},so=(e,...t)=>{let r=e.cf;for(const n of t){if(typeof r!="object"||r===null)return;r=r[n]}return typeof r=="string"?r:void 0},io={mtls:e=>so(e,"tlsClientAuth","certVerified")==="SUCCESS"},uo=e=>e===void 0||e===!1?()=>!1:e===!0?()=>!0:typeof e=="function"?e:Object.entries(io).find(([t])=>t===e)?.[1]??(()=>!1),co=e=>{if(e!==void 0)return()=>{};let t=!1;return()=>{t||(t=!0,console.warn('[lunora] Ignored an inbound `traceparent`, so this request starts a new trace instead of joining the caller\'s. That is the safe default: the header is caller-supplied, and trusting it lets any client choose which trace its spans and logs join. If this worker sits behind a gateway, service mesh, or Cloudflare Access that sets `traceparent` itself, set `trustInboundTraceContext: true` on createWorker() (or `"mtls"` to trust only edge-verified client certificates). Set it to `false` to keep this behaviour and silence this message.'))}},lo="/_lunora/admin/vector/indexes",ho="/_lunora/admin/vector/query",po=e=>{const{readJsonBody:t,requireAdminOption:r}=e,n=async d=>{if(d.method!=="GET")throw new a("Vector-indexes endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});const c=r(d,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});return Response.json({indexes:await c.listIndexes()},{headers:{"content-type":"application/json"},status:200})},s=async d=>{if(d.method!=="POST")throw new a("Vector-query endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const c=r(d,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});if(c.queryIndex===void 0)throw new a("vector index querying is not enabled on this worker",{code:"VECTOR_QUERY_UNSUPPORTED",status:400});const l=await t(d);if(typeof l.name!="string"||l.name==="")throw new a("Vector-query request requires a `name` string",{code:"BAD_REQUEST",status:400});if(typeof l.text!="string"||l.text==="")throw new a("Vector-query request requires a `text` string",{code:"BAD_REQUEST",status:400});if(l.topK!==void 0&&(typeof l.topK!="number"||!Number.isInteger(l.topK)||l.topK<1))throw new a("Vector-query `topK` must be a positive integer",{code:"BAD_REQUEST",status:400});const b=await c.queryIndex({name:l.name,text:l.text,topK:l.topK});return Response.json(b,{headers:{"content-type":"application/json"},status:200})};return{[lo]:n,[ho]:s}},fo="/_lunora/admin/workflows/instances",wo="/_lunora/admin/workflows/instance",mo="/_lunora/admin/workflows/status",yo={complete:!0,errored:!0,paused:!0,queued:!0,running:!0,terminated:!0,unknown:!0,waiting:!0,waitingForPause:!0},go=e=>e!==null&&Object.hasOwn(yo,e)?e:void 0,dt=(e,t)=>{const r=e.searchParams.get(t);if(r===null)return;const n=Number(r);return Number.isInteger(n)&&n>0?n:void 0},Be=(e,t)=>{const r=e.searchParams.get(t);if(r===null||r==="")throw new a(`Workflows admin endpoint requires a \`${t}\` query parameter`,{code:"BAD_REQUEST",status:400});return r},ut=()=>{throw new a("Workflow inspection is unconfigured. Set CLOUDFLARE_ACCOUNT_ID + CLOUDFLARE_API_TOKEN in your .dev.vars to enable it.",{code:"WORKFLOWS_NOT_CONFIGURED",status:501})},bo=e=>{const{assertAdmin:t,resolveWorkflowsClient:r}=e,n=async(c,l,b)=>{if(c.method!=="GET")throw new a("Workflows instances endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});t(c);const T=r(l);if(!T)return Response.json({configured:!1,instances:[],page:1,perPage:0,totalCount:0});const D=Be(b,"name"),w=go(b.searchParams.get("status"));return Response.json(await T.listInstances({page:dt(b,"page"),perPage:dt(b,"perPage"),status:w,workflowName:D}))},s=async(c,l,b)=>{if(c.method!=="GET")throw new a("Workflows instance endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});t(c);const T=r(l);return T?Response.json(await T.getInstance({instanceId:Be(b,"id"),workflowName:Be(b,"name")})):ut()},d=async(c,l)=>{if(c.method!=="POST")throw new a("Workflows status endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});t(c);const b=r(l);if(!b)return ut();const T=await c.json().catch(()=>{});if(typeof T?.name!="string"||T.name===""||typeof T.id!="string"||T.id==="")throw new a("Workflows status action requires string `name` and `id`",{code:"BAD_REQUEST",status:400});const{action:D}=T;if(D!=="pause"&&D!=="resume"&&D!=="terminate")throw new a("Workflows status action must be one of: pause, resume, terminate",{code:"BAD_REQUEST",status:400});return Response.json(await b.setInstanceStatus({action:D,instanceId:T.id,workflowName:T.name}))};return{[wo]:s,[fo]:n,[mo]:d}},Oo=new TextEncoder,ct="/_lunora/rpc",Eo="/_lunora/rpc-batch",To="/_lunora/ws",Ee=(e,t,r)=>({resourceAttributes:zn(e,t),...r===void 0?{}:{waitUntil:r}}),lt=e=>e?.waitUntil?{waitUntil:t=>e.waitUntil?.(t)}:{},ht=e=>({spanId:e.spanId,traceFlags:e.traceFlags,traceId:e.traceId,...e.parentSpanId===void 0?{}:{parentSpanId:e.parentSpanId}}),Ce=e=>{const{method:t}=e,r=e.headers.get("user-agent")??void 0;let n;try{n=new URL(e.url)}catch{return{method:t,userAgent:r}}const s=n.port===""?void 0:Number(n.port);return{host:n.hostname,method:t,path:n.pathname,port:Number.isNaN(s)?void 0:s,scheme:n.protocol.replace(":",""),userAgent:r}},pt="/_lunora/voice/",_o="/_lunora/scheduler/dispatch",Ro="/_lunora/admin/cron-jobs/run",So="/_lunora/admin/ws-token",Ao="/_lunora/admin/",vo="/_lunora/migrate",Do="/_lunora/status",ko=e=>e.startsWith(Ao)||e===vo,Io=new Set(["1","enabled","on","true","yes"]),Po=e=>{const t=e.headers.get("x-lunora-userid"),r=e.headers.get("x-lunora-identity");if(!(t===null&&r===null))return{...r===null?{}:{identity:r},...t===null?{}:{userId:t}}},No="/api/auth",Uo="__lunora_admin__:recordAuthEvent",qo="__lunora_admin__:listPushSubscriptions",$o=["/sign-in","/sign-up","/callback"],xo=(e,t)=>{const r=t.endsWith("/")?t.slice(0,-1):t;if(!e.startsWith(`${r}/`))return!1;const n=e.slice(r.length);return $o.some(s=>n===s||n.startsWith(`${s}/`))},Te=(e,t,r,n)=>{const s=nr(r),d=s?r.code:"INTERNAL_SERVER_ERROR",c=s?r.status:500,l=r instanceof Error?r.message:String(r);return{durationMs:t,error:{code:d,message:l,status:c},functionPath:e,ok:!1,...n.fanOut?{fanOut:{failed:0,shards:0,table:n.fanOut.table}}:{},...n.shardKey?{shardKey:n.shardKey}:{}}},Lo=e=>{const{exp:t,expiresAtMs:r}=e;if(typeof r=="number"&&Number.isFinite(r))return r;if(typeof t=="number"&&Number.isFinite(t))return t*1e3},ft=e=>e.waitUntil?{waitUntil:t=>{e.waitUntil?.(t)}}:void 0,Bo=e=>{const t=e?.queue;return typeof t=="string"&&t.length>0?t:"unknown"},ce=async(e,t,r)=>{const n={"content-type":"application/json"},s=e.headers.get("authorization"),d=e.headers.get("cookie"),c=e.headers.get("x-d1-bookmark"),l=e.headers.get("x-lunora-mutation-id"),b=e.headers.get("x-lunora-client-id"),T=e.headers.get("x-lunora-client-seq");s&&(n.authorization=s),d&&(n.cookie=d),c&&(n["x-d1-bookmark"]=c),l&&(n["x-lunora-mutation-id"]=l),b&&(n["x-lunora-client-id"]=b),T&&(n["x-lunora-client-seq"]=T);const D=e.headers.get("cf-connecting-ip");if(D&&(n["x-lunora-client-ip"]=D),!r)return{claims:null,headers:n,identity:null,userId:null};const w=await r(e,t);if(!w||typeof w.userId!="string"||w.userId.length===0)return{claims:null,headers:n,identity:null,userId:null};n["x-lunora-userid"]=w.userId;const g=Lo(w);g!==void 0&&(n["x-lunora-identity-exp"]=String(g));const{userId:p,...y}=w,_=Object.keys(y).length>0?y:null;return _&&(n["x-lunora-identity"]=JSON.stringify(_)),{claims:_,headers:n,identity:w,userId:p}},Co=new Set(["concat","first","groupBy","max","min","rank","sum","topK"]),jo=e=>{if(e===void 0)return;if(!e||typeof e!="object")throw new a("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 a("RPC `fanOut.table` must be a non-empty string",{code:"BAD_REQUEST",status:400});if(!t.merge||typeof t.merge!="object")throw new a("RPC `fanOut.merge` must be an object",{code:"BAD_REQUEST",status:400});const r=t.merge;if(typeof r.kind!="string"||!Co.has(r.kind))throw new a("RPC `fanOut.merge.kind` is not a recognized merge strategy",{code:"BAD_REQUEST",status:400});if(r.kind==="topK"){if(typeof r.k!="number"||!Number.isInteger(r.k)||r.k<0)throw new a("RPC `fanOut.merge.k` must be a non-negative integer",{code:"BAD_REQUEST",status:400});if(typeof r.by!="string"||r.by.length===0)throw new a("RPC `fanOut.merge.by` must be a non-empty string",{code:"BAD_REQUEST",status:400})}return t},Go=(e,t)=>{e?.LUNORA_DEBUG_RPC&&console.warn(`[lunora:rpc] ${t.fanOut?"fan-out":`shard=${t.shardKey??"(root)"}`} ${t.functionPath}`)},wt=(e,t)=>{const r=t.functions?.[e.functionPath]?.x402;if(r){if(e.fanOut)throw new a("a paid (`.x402`) function cannot be fanned out",{code:"BAD_REQUEST",status:400});if(!t.x402Charge)throw new a(`function "${e.functionPath}" is marked paid (.x402) but no x402Charge gate is configured on the worker`,{code:"MISCONFIGURED",status:500});return r}},Mo=async e=>{const t=await se(e);let r;try{r=JSON.parse(t)}catch{throw new a("RPC body must be valid JSON",{code:"BAD_REQUEST",status:400})}if(!r||typeof r!="object"||typeof r.functionPath!="string")throw new a("RPC envelope is missing `functionPath`",{code:"BAD_REQUEST",status:400});const n=r;if(n.args!==void 0&&(typeof n.args!="object"||n.args===null||Array.isArray(n.args)))throw new a("RPC `args` must be an object",{code:"BAD_REQUEST",status:400});if(n.shardKey!==void 0&&typeof n.shardKey!="string")throw new a("RPC `shardKey` must be a string",{code:"BAD_REQUEST",status:400});const s=r,d=jo(s.fanOut),c=s.args??{};if(d&&s.functionPath.startsWith("__lunora_relation__:")){const l=c.table;if(typeof l=="string"&&l!==d.table)throw new a("RPC `args.table` must match the authorized `fanOut.table` for a relation fan-out",{code:"BAD_REQUEST",status:400});c.table=d.table}return{args:c,fanOut:d,functionPath:s.functionPath,shardKey:s.shardKey}},ae=async(e,t,r)=>Se(e,t).fetch(r),_e=new Map,Ko=5e3,Fo=4096,Qo=async(e,t)=>{const r=Date.now(),n=_e.get(t);if(n!==void 0&&n.expiresMs>r)return n.relayCount;n!==void 0&&_e.delete(t);let s=0;try{const d=await Se(e,t).fetch(new Request("https://shard.internal/_lunora/route"));if(d.ok){const c=(await d.json()).relayCount;typeof c=="number"&&c>0&&(s=Math.floor(c))}}catch{s=0}return yt(_e,Fo),_e.set(t,{expiresMs:r+Ko,relayCount:s}),s},zo=(e,t)=>{if(!(e===null||typeof e!="object")){for(const[r,n]of Object.entries(e))if(n===t)return r}},Ge=(e,t)=>{const r=Math.max(e.length,t.length);let n=e.length^t.length;for(let s=0;s<r;s+=1){const d=s<e.length?e.codePointAt(s)??0:0,c=s<t.length?t.codePointAt(s)??0:0;n|=d^c}return n===0},Wo=async(e,t,r)=>{if(e.length===0||r.length===0)return!1;const n=new TextEncoder,s=await crypto.subtle.importKey("raw",n.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign"]),d=await crypto.subtle.sign("HMAC",s,n.encode(t)),c=new Uint8Array(d);let l="";for(const T of c)l+=String.fromCodePoint(T);const b=btoa(l).replaceAll("+","-").replaceAll("/","_").replaceAll("=","");return Ge(b,r)},mt=(e,t)=>{if(!t||t.length===0)return!1;const r=e.headers.get("authorization");if(!r)return!1;const[n,...s]=r.split(" ");return n?.toLowerCase()!=="bearer"?!1:Ge(t,s.join(" ").trim())},Ho=async(e,t,r)=>{if(!t||t.length===0)return!1;const n=new URL(e.url).searchParams.get("token");return n===null?!1:await Nr(t,n)?!0:r?!1:Ge(t,n)},Jo=(e,t)=>{if(t===null||typeof t!="object"&&typeof t!="function")return;const r=t;if(typeof r.prepare=="function"&&typeof r.batch=="function"&&typeof r.dump=="function")return wr(`d1:${e}`,t);if(typeof r.list=="function"&&typeof r.head=="function"&&typeof r.createMultipartUpload=="function")return Ne(`r2:${e}`,!0);if(typeof r.send=="function"&&typeof r.sendBatch=="function"&&typeof r.get!="function")return Ne(`queue:${e}`,!0);if(typeof r.connectionString=="string")return Ne(`hyperdrive:${e}`,!0)},_t=e=>{const t=uo(e.trustInboundTraceContext),r=co(e.trustInboundTraceContext),n=e.defaultShardKey??"__root__",s=mr(e.resolveIdentity,e.identity),d=Je(e.shardDO,e.jurisdiction),c=e.schedulerDO===void 0?void 0:Je(e.schedulerDO,e.jurisdiction);let l;const b=()=>e.adminToken??l;let T;const D=()=>e.requireEphemeralWsToken??T??!1,w=o=>{const i=o??{};if(T===void 0&&e.requireEphemeralWsToken===void 0){const u=i.LUNORA_REQUIRE_EPHEMERAL_WS_TOKEN;typeof u=="string"&&u.length>0&&(T=Io.has(u.trim().toLowerCase()))}if(l!==void 0||e.adminToken!==void 0)return;const h=i.LUNORA_ADMIN_TOKEN;typeof h=="string"&&h.length>0&&(l=h)},g=new WeakSet,p=o=>mt(o,b())||g.has(o),y=async(o,i)=>{const h=await ce(o,i,e.resolveIdentity);if(g.has(o)&&h.headers.authorization===void 0){const u=b();u!==void 0&&(h.headers.authorization=`Bearer ${u}`)}return h};let _=!1;const R=o=>{if(!e.allowUnauthenticatedShardAccess){const i=o==="fan-out"?"authorizeFanOut":"authorizeShard";throw new a(`${o} access is default-denied: configure \`${i}\` 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})}_||(_=!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("")))},I=xn({defaultShard:n,forwardToShard:ae,isAdmin:p,queryCoordinator:e.queryCoordinator,resolveForwardContext:y,shardDO:d}),x=async(o,i,h,u,f)=>{if(e.authorizeShard&&!await e.authorizeShard(null,h))throw new a("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403});const O={"content-type":"application/json","x-lunora-system":"1"};f?.userId!==void 0&&f.userId.length>0&&(O["x-lunora-userid"]=f.userId),f?.identity!==void 0&&f.identity.length>0&&(O["x-lunora-identity"]=f.identity),u!==void 0&&u.length>0&&(O["x-lunora-mutation-id"]=u);const S=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:i,functionPath:o}),headers:O,method:"POST"});return ae(d,h,S)},v=async(o,i,h,u)=>{const f=h?.[o];if(!f||typeof f.create!="function")throw new a(`${u} targets workflow binding "${o}", which is not bound on env`,{code:"CRON_JOB_FAILED",status:500});await f.create({params:i})},B=async(o,i,h)=>v(o,i.args??{},h,`cron job "${i.name}"`),C=async(o,i)=>{if(o.workflow){await B(o.workflow,o,i);return}if(o.functionPath===void 0)throw new a(`cron job "${o.name}" has neither a function target nor a workflow target`,{code:"CRON_JOB_FAILED",status:500});const h=await x(o.functionPath,o.args??{},o.shardKey??n);if(!h.ok)throw new a(`cron job "${o.name}" (${o.functionPath}) failed with shard status ${String(h.status)}`,{code:"CRON_JOB_FAILED",status:500})},Y=async(o,i,h,u)=>{const f=e.cronJobs?.[o];if(f)for(const O of f)try{await C(O,i)}catch(S){h.push(u(S))}},N=async(o,i)=>{if(!p(o))throw new a("admin endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403});if(o.method!=="POST")throw new a("cron-jobs run endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});if(!e.cronJobs)throw new a("cron-jobs run endpoint requires a `cronJobs` map on the worker",{code:"CRON_JOBS_NOT_CONFIGURED",status:400});const h=await te(o),u=typeof h.name=="string"?h.name:"";if(u==="")throw new a("cron-jobs run endpoint requires a job `name`",{code:"BAD_REQUEST",status:400});const f=Object.values(e.cronJobs).flat().find(O=>O.name===u);if(!f)throw new a(`no cron job named "${u}" is registered`,{code:"CRON_JOB_NOT_FOUND",status:404});return await C(f,i),Response.json({name:u,ran:!0},{status:200})},K=async o=>{const i=typeof o.pool=="string"&&o.pool.length>0?o.pool:void 0;if(!i||!c||typeof o.id!="string")return;const h=typeof o.instanceName=="string"&&o.instanceName.length>0?o.instanceName:"default";try{await c.get(c.idFromName(h)).fetch(new Request("https://scheduler.internal/complete",{body:JSON.stringify({id:o.id,pool:i}),headers:{"content-type":"application/json"},method:"POST"}))}catch{}},F=async(o,i)=>{if(o.method!=="POST")throw new a("Scheduler dispatch endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const h=await se(o),u=i??{},f=typeof u.LUNORA_SCHEDULER_SECRET=="string"?u.LUNORA_SCHEDULER_SECRET:void 0,O=e.adminToken??(typeof u.LUNORA_ADMIN_TOKEN=="string"?u.LUNORA_ADMIN_TOKEN:void 0),S=o.headers.get("x-lunora-scheduler-signature");let m=!1;if(S&&f?m=await Wo(f,h,S):O&&(m=mt(o,O)),!m)throw new a("Scheduler dispatch requires a valid signature or admin bearer",{code:"FORBIDDEN",status:403});let E;try{E=JSON.parse(h)}catch{throw new a("Scheduler dispatch body must be valid JSON",{code:"BAD_REQUEST",status:400})}const A=E??{},U=A.args??{};if(typeof A.workflow=="string"&&A.workflow.length>0)return await v(A.workflow,U,i,"scheduled workflow"),Response.json({ok:!0},{status:200});if(typeof A.functionPath!="string"||A.functionPath.length===0)throw new a("Scheduler dispatch is missing `functionPath`",{code:"BAD_REQUEST",status:400});const q=typeof A.shardKey=="string"&&A.shardKey.length>0?A.shardKey:n,$=typeof A.id=="string"&&A.id.length>0?A.id:void 0,L=Po(o),W=await x(A.functionPath,U,q,$,L);return await K(A),W},j=o=>{if(!p(o))throw new a("admin endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403})},M=(o,i,h)=>{if(j(o),i===void 0)throw new a(h.message,{code:h.code,status:400});return i},X=Lr({assertAdmin:j,getReader:()=>e.authAuditReader}),J=async(o,i)=>{j(o);const h=e.notifySubscriptionStore;if(h===void 0)return Response.json({subscriptions:[]},{headers:{"content-type":"application/json"},status:200});const u=i?.kind,f=i?.userId,O=i?.limit,S=u==="fcm"||u==="web-push"?u:void 0,m=typeof f=="string"&&f!==""?f:void 0,E=typeof O=="number"&&Number.isFinite(O)?Math.trunc(O):0,A=E>0?Math.min(E,1e3):1e3,U=(await h.list({kind:S,limit:A,userId:m})).filter(q=>S!==void 0&&q.kind!==S?!1:m===void 0||(q.userId??null)===m).map(({keys:q,token:$,...L})=>L);return Response.json({subscriptions:U},{headers:{"content-type":"application/json"},status:200})},oe=async(o,i)=>{if(!i.fanOut){if(i.functionPath===xr)return X(o,i.args??{});if(i.functionPath===qo)return J(o,i.args)}},ie=Zr({applyGlobals:e.applyGlobals,assertAdmin:j,exportCursorStore:e.exportCursorStore,exportSinks:e.exportSinks,knownTables:()=>Ot(),queryCoordinator:e.queryCoordinator,requireAdminOption:M,resolveForwardContext:y,shardDO:d,streamExportRows:(o,i,h,u)=>ot(e,o,i,h,u,d),streamingImport:(o,i)=>an(o,e,i,d),syncGlobals:e.syncGlobals}),Z=(o,i)=>{const h=o.searchParams.get(i);return h===null||h===""?void 0:h},pe=o=>{const i=new URL(o.url),h=i.searchParams.get("limit"),u=i.searchParams.get("offset"),f=h===null?void 0:Number.parseInt(h,10),O=u===null?void 0:Number.parseInt(u,10);return{limit:f!==void 0&&Number.isFinite(f)&&f>=0?f:void 0,offset:O!==void 0&&Number.isFinite(O)&&O>=0?O:void 0}},be=()=>{if(c===void 0)throw new a("scheduled endpoints require a `schedulerDO` namespace on the worker",{code:"SCHEDULER_NOT_CONFIGURED",status:400});return c},Ae=eo({checkWsAdmin:async o=>p(o)||Ho(o,b(),D()),requireSchedulerNamespace:be,resolveSchedulerStub:o=>(j(o),Se(be(),e.schedulerInstanceName??"default")),schedulerInstanceName:e.schedulerInstanceName??"default"}),re=bo({assertAdmin:j,resolveWorkflowsClient:e.workflowsClient??(()=>{})}),Rt=ao({assertAdmin:j,parsePaging:pe,queryParameter:Z,readBodyBytes:jr,requireAdminOption:M,storage:{storageBuckets:e.storageBuckets,storageDelete:e.storageDelete,storageList:e.storageList,storageSignedUrl:e.storageSignedUrl,storageUpload:e.storageUpload}}),St=po({readJsonBody:te,requireAdminOption:M,vectorIntrospector:e.vectorIntrospector}),At=En({kvIntrospector:e.kvIntrospector,readJsonBody:te,requireAdminOption:M}),vt=yr({logArchive:e.logArchive,readJsonBody:te,requireAdminOption:M}),Dt=gn({assertAdmin:j,options:{cronJobs:e.cronJobs,functions:e.functions,globalIntrospector:e.globalIntrospector,openApiSpec:e.openApiSpec,openRpcSpec:e.openRpcSpec},parsePaging:pe,queryParameter:Z,requireAdminOption:M}),kt=o=>{const i=[],h=d??o?.SHARD;if(h!==void 0&&i.push(fr("durable-object:default",h,n)),e.health?.disableBindingProbes!==!0)for(const[u,f]of Object.entries(o??{})){const O=Jo(u,f);O!==void 0&&i.push(O)}for(const u of e.health?.probes??[])i.push(u);return i},It=pr({appName:e.health?.appName,appVersion:e.health?.appVersion,auth:e.health?.auth??"public",cacheTtlMs:e.health?.cacheTtlMs,isAdmin:p,resolveProbes:kt}),Pt=o=>{const i=e.schedulerInstanceName??"default",h=()=>o.get(o.idFromName(i)),u=async(m,E)=>{const A=await h().fetch(new Request(`https://scheduler.internal${m}`,E));if(!A.ok)throw new a(`ctx.scheduler: SchedulerDO ${m} failed (${String(A.status)}): ${await A.text()}`,{code:"INTERNAL",status:500});return await A.json()},f=async(m,E)=>await u(m,{body:JSON.stringify(E),headers:{"content-type":"application/json"},method:"POST"}),O=m=>{const E=m;if(E==null)throw new a("ctx.scheduler: target is required — pass a reference from the generated `internal` / `workflows` / `agents`",{code:"BAD_REQUEST",status:400});if(typeof E.binding=="string"&&E.binding.length>0)return{workflow:E.binding};if(typeof E.__lunoraRef=="string")return{functionPath:E.__lunoraRef};throw new a("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})},S=async(m,E,A={})=>{const{id:U}=await f("/schedule",{args:A,scheduledFor:m,...O(E)});return U};return{cancel:async m=>await f("/cancel",{id:m}),get:async m=>await u(`/get?id=${encodeURIComponent(m)}`,{method:"GET"}),list:async()=>await u("/list",{method:"GET"}),runAfter:async(m,E,A)=>{if(!Number.isFinite(m)||m<0)throw new a("ctx.scheduler.runAfter: `delayMs` must be a non-negative finite number",{code:"BAD_REQUEST",status:400});return await S(Date.now()+m,E,A)},runAt:async(m,E,A)=>{if(!Number.isFinite(m))throw new a("ctx.scheduler.runAt: `timestampMs` must be a finite epoch-millisecond number",{code:"BAD_REQUEST",status:400});return await S(m,E,A)}}},Nt=async(o,i,h)=>{const{claims:u,headers:f,userId:O}=await ce(o,i,s),S=async(m,E={})=>{const A=m.__lunoraRef;if(typeof A!="string")throw new a("ctx.run*: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});const U=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:E,functionPath:A}),headers:{...f,"x-lunora-system":"1"},method:"POST"}),q=await ae(d,n,U),$=await q.json();if($.error)throw new a($.error.message??"shard RPC failed",{code:$.error.code??"INTERNAL",status:q.status});return $.result};return{auth:{getIdentity:()=>Promise.resolve(u),userId:O},cache:h.cache,fetch:globalThis.fetch.bind(globalThis),runAction:S,runMutation:S,runQuery:S,...c===void 0?{}:{scheduler:Pt(c)},...e.storage===void 0?{}:{storage:Tr(e.storage(i))}}},Ut=async(o,i,h)=>{if(!e.httpRouter)return;const u=await Nt(o,i,h);try{return await e.httpRouter.fetch(o,{...i,__lunoraCtx:u},h)}catch(f){return console.error("[lunora] httpRouter (SSR) handler threw:",f),new Response("Internal Server Error",{status:500})}},qt=async(o,i,h)=>{if(o.headers.get("Upgrade")!=="websocket")throw new a("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});const u=Ye(o,de);if(u)return u;const f=h.searchParams.get("shard")??n,{headers:O,identity:S}=await ce(o,i,s);if(e.authorizeShard){if(!await e.authorizeShard(S,f))throw new a("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else f!==n&&R("shard");const m=new Headers(o.headers),E=[...m.keys()];for(const L of E)L.startsWith("x-lunora-")&&m.delete(L);const A=O["x-lunora-userid"],U=O["x-lunora-identity"],q=O["x-lunora-identity-exp"];A!==void 0&&m.set("x-lunora-userid",A),U!==void 0&&m.set("x-lunora-identity",U),q!==void 0&&m.set("x-lunora-identity-exp",q);const $=zo(i,e.shardDO);if($!==void 0){m.set("x-lunora-shard-binding",$);const L=await Qo(d,f);if(L>0){const W=Rr(f,Math.floor(Math.random()*L));return ae(d,W,new Request(o,{headers:m}))}}return ae(d,f,new Request(o,{headers:m}))},$t=async(o,i,h)=>{const{voiceAgents:u}=e;if(u===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 f=Ye(o,de);if(f)return f;let O;try{O=decodeURIComponent(h.pathname.slice(pt.length))}catch{return new Response("Unknown voice agent",{status:404})}const S=Object.hasOwn(u,O)?u[O]:void 0;if(S===void 0)return new Response("Unknown voice agent",{status:404});const m=h.searchParams.get("threadKey");if(m===null||m.length===0)return new Response("Missing threadKey",{status:400});const{headers:E,identity:A}=await ce(o,i,s);if(e.authorizeShard){if(!await e.authorizeShard(A,m))return new Response("Forbidden",{status:403})}else R("shard");const U=new Headers(o.headers);U.delete("x-lunora-userid"),U.delete("x-lunora-identity"),U.delete("x-lunora-identity-exp");const q=E["x-lunora-userid"],$=E["x-lunora-identity"],L=E["x-lunora-identity-exp"];return q!==void 0&&U.set("x-lunora-userid",q),$!==void 0&&U.set("x-lunora-identity",$),L!==void 0&&U.set("x-lunora-identity-exp",L),ae(S,m,new Request(o,{headers:U}))},xt=async(o,i,h)=>{if(e.authorizeFanOut){if(!await e.authorizeFanOut(h,o.table,i))throw new a("Forbidden fan-out",{code:"FORBIDDEN_FANOUT",status:403});return}if(i.startsWith("__lunora_relation__:"))throw new a("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 a("Fan-out requires `authorizeFanOut` to be configured on the worker when `authorizeShard` is set",{code:"FORBIDDEN_FANOUT",status:403});R("fan-out")},Oe=async(o,i)=>{if(!(!o.fanOut&&o.functionPath.startsWith("__lunora_admin__:"))){if(o.fanOut){await xt(o.fanOut,o.functionPath,i);return}if(e.authorizeShard){const h=o.shardKey??n;if(!await e.authorizeShard(i,h))throw new a("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else o.shardKey!==void 0&&o.shardKey!==n&&R("shard")}},ve=async(o,i,h,u,f,O)=>{const S=Date.now(),{observability:m,sampling:E}=e,A=Ce(o),{decision:U,ignoredUpstream:q,trace:$}=Fn(o,{...E===void 0?{}:{sampling:E},trustInbound:t(o)});q&&r();const L={...f,"x-lunora-sample-errors":U.keepErrors?"1":"0"};Qn($,L);const W=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:h,functionPath:i}),headers:L,method:"POST"});try{const G=await ae(d,u,W);return ue(m,{...A,...ht($),durationMs:Date.now()-S,functionPath:i,ok:G.ok,shardKey:u,...G.ok?{}:{error:{code:"SHARD_ERROR",message:`shard returned ${String(G.status)}`,status:G.status}}},O,void 0,{isTraced:$.sampled,keepErrors:U.keepErrors}),G}catch(G){throw ue(m,{...A,...ht($),...Te(i,Date.now()-S,G,{shardKey:u})},O,void 0,{isTraced:$.sampled,keepErrors:U.keepErrors}),G}},Lt=o=>{if(o.fanOut&&o.shardKey)throw new a("RPC envelope cannot set both `shardKey` and `fanOut`",{code:"BAD_REQUEST",status:400});if(!o.fanOut&&o.functionPath.startsWith("__lunora_relation__:"))throw new a("`__lunora_relation__:*` is a fan-out-only reserved RPC and cannot be dispatched to a single shard",{code:"FORBIDDEN",status:403});if(o.fanOut&&!e.queryCoordinator)throw new a("RPC envelope set `fanOut` but no `queryCoordinator` is configured on the worker",{code:"BAD_REQUEST",status:400})},Bt=async(o,i,h)=>{if(o.method!=="POST")throw new a("RPC endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const u=await Mo(o);Go(i,u),Lt(u);const f=await oe(o,u);if(f!==void 0)return f;const{headers:O,identity:S}=await ce(o,i,s);await Oe(u,S);const m=wt(u,e);{const E=Date.now(),{observability:A}=e,U=Ce(o),q=Ee(i,o,h&&(W=>h.waitUntil?.(W)));if(u.fanOut){const W=e.queryCoordinator;if(!W)throw new a("RPC envelope set `fanOut` but no `queryCoordinator` is configured on the worker",{code:"BAD_REQUEST",status:400});try{const G=await W.fanOut(d,{args:u.args??{},fanOut:u.fanOut,functionPath:u.functionPath,headers:O});return ue(A,{durationMs:Date.now()-E,fanOut:{failed:G.failed,shards:G.ok+G.failed,table:u.fanOut.table},functionPath:u.functionPath,...U,ok:!0},q),Response.json(G,{headers:{"content-type":"application/json"},status:200})}catch(G){throw ue(A,{...Te(u.functionPath,Date.now()-E,G,{fanOut:{table:u.fanOut.table}}),...U},q),G}}const $=u.shardKey??n,L=()=>ve(o,u.functionPath,u.args??{},$,O,q);return m&&e.x402Charge?e.x402Charge(o,{functionPath:u.functionPath,price:m.price},L,lt(h)):L()}},Ct=async(o,i,h)=>{if(o.method!=="POST")throw new a("RPC batch endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const u=await se(o);let f;try{f=JSON.parse(u)}catch{throw new a("RPC batch body must be valid JSON",{code:"BAD_REQUEST",status:400})}if(typeof f!="object"||f===null||Array.isArray(f))throw new a("RPC batch body must be an object",{code:"BAD_REQUEST",status:400});const{calls:O}=f;if(!Array.isArray(O))throw new a("RPC batch `calls` must be an array",{code:"BAD_REQUEST",status:400});const{headers:S,identity:m}=await ce(o,i,s),E=Cr(O,n);for(const Q of E.values())for(const z of Q)if(e.functions?.[z.functionPath]?.x402)throw new a(`paid (\`.x402\`) function "${z.functionPath}" cannot be called in a batch; dispatch it individually over ${ct}`,{code:"BAD_REQUEST",status:400});await Promise.all([...E.entries()].flatMap(([Q,z])=>z.map(ne=>Oe({functionPath:ne.functionPath,shardKey:Q},m))));const{observability:A}=e,U=Ee(i,o,h&&(Q=>h.waitUntil?.(Q))),q=Ce(o),$=[],L=[],W=(Q,z,ne,le)=>({body:{error:{code:ne,message:le}},id:Q.id,status:z}),G=(Q,z,ne,le,fe)=>{for(const H of Q)ue(A,fe(H),U),$.push(W(H,z,ne,le))},Zt=(Q,z,ne,le,fe)=>{for(const H of Q){const we=le.get(H.id)??fe,ye=we<400;ue(A,{durationMs:ne,functionPath:H.functionPath,...q,ok:ye,shardKey:z,...ye?{}:{error:{code:"SHARD_ERROR",message:`batched call returned ${String(we)}`,status:we}}},U)}};await Promise.all([...E.entries()].map(async([Q,z])=>{const ne=new Headers(S);ne.set("content-type","application/json");const le=new Request("https://shard.internal/rpc-batch",{body:JSON.stringify({calls:z}),headers:ne,method:"POST"}),fe=Date.now();let H;try{H=await ae(d,Q,le)}catch(V){const Pe=Date.now()-fe,{body:ze}=or(V,{fallbackCode:"SHARD_UNAVAILABLE",redactedMessage:"shard unavailable"});G(z,502,ze.code,ze.message,rr=>({...Te(rr.functionPath,Pe,V,{shardKey:Q}),...q}));return}const we=Date.now()-fe,ye=H.headers.get("x-d1-bookmark");ye&&L.push(ye);let ke;try{ke=await H.json()}catch{const V=`shard batch returned a non-JSON response (${String(H.status)})`;G(z,H.status,"SHARD_ERROR",V,Pe=>({durationMs:we,error:{code:"SHARD_ERROR",message:V,status:H.status},functionPath:Pe.functionPath,...q,ok:!1,shardKey:Q}));return}const Ie=Array.isArray(ke.results)?ke.results:[],er=new Map(Ie.map(V=>[V.id,V.status??H.status])),tr=new Set(Ie.map(V=>V.id));Zt(z,Q,we,er,H.status),$.push(...Ie);for(const V of z)tr.has(V.id)||$.push(W(V,H.status,"SHARD_ERROR",`shard batch omitted result for call ${String(V.id)}`))}));const Fe={"content-type":"application/json"},[Qe]=L;return L.length===1&&Qe!==void 0&&(Fe["x-d1-bookmark"]=Qe),Response.json({results:$},{headers:Fe,status:200})},jt=async(o,i,h,u={},f={})=>{try{const O=h.__lunoraRef;if(typeof O!="string")throw new a("serverQuery: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});const{headers:S,identity:m}=await ce(o,i,s);await Oe({functionPath:O,shardKey:f.shardKey},m);const E=f.shardKey??n,A=Ee(i,o,f.waitUntil);return await ve(o,O,u,E,S,A)}catch(O){return We(O)}},Gt=1e3,Mt=async(o,i)=>{const h=e.backupRetain;if(h===void 0||h<=0)return;const u=[];let f;for(let S=0;S<Gt;S+=1){const m=await o.list({cursor:f,prefix:i});for(const E of m.objects)E.key.endsWith(".manifest.json")&&u.push(E.key);if(!m.truncated||m.cursor===void 0)break;f=m.cursor}const O=u.toSorted((S,m)=>m.localeCompare(S)).slice(h);await Promise.all(O.flatMap(S=>{const m=S.slice(0,-14);return[o.delete(S),o.delete(m)]}))},Kt=async o=>{const i=e.backupStore,h=e.queryCoordinator;if(!i)throw new a("scheduled backup requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});if(!h)throw new a("scheduled backup requires a `queryCoordinator` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});const u=b();if(!u||u.length===0)throw new a("scheduled backup requires an `adminToken` (or `env.LUNORA_ADMIN_TOKEN`) to authenticate the per-shard export gate",{code:"BACKUP_NOT_CONFIGURED",status:500});const f={authorization:`Bearer ${u}`,"content-type":"application/json"},O=e.backupTables;let S=0,m=0;const E=[];await ot(e,h,f,O,W=>{const G=`${JSON.stringify(W)}
|
|
5
|
+
`;S+=1,m+=Oo.encode(G).byteLength,E.push(G)},d);const A=e.backupPrefix??"backups/",U=new Date(o.scheduledTime).toISOString(),q=`${A}lunora-backup-${U.replaceAll(/[.:]/gu,"-")}.ndjson`,$=`${q}.manifest.json`;await i.put(q,new Blob(E,{type:"application/x-ndjson"}),{httpMetadata:{contentType:"application/x-ndjson"}});const L={bytes:m,createdAt:U,cron:o.cron,file:q,id:U,rows:S,scheduledTime:o.scheduledTime,...O?{tables:O.join(",")}:{}};await i.put($,`${JSON.stringify(L,void 0,2)}
|
|
6
|
+
`,{httpMetadata:{contentType:"application/json"}}),await Mt(i,A)},Me=async(o,i,h)=>{const{observability:u}=e,f=Date.now(),O=Re(16),S=Re(8),m=ft(i);try{const E=await h();return ue(u,{durationMs:Date.now()-f,functionPath:o,ok:!0,spanId:S,traceId:O},m),E}catch(E){throw ue(u,{...Te(o,Date.now()-f,E,{}),spanId:S,traceId:O},m),E}finally{He(u,m)}},Ft=async(o,i,h)=>{w(i);const u=[],f=m=>m instanceof Error?m:new Error(String(m)),O=e.crons?.[o.cron];if(O)try{await O(o,i,h)}catch(m){u.push(f(m))}if(await Y(o.cron,i,u,f),e.backupStore&&e.backupCron!==void 0&&e.backupCron===o.cron)try{await Kt(o)}catch(m){u.push(f(m))}const[S]=u;if(u.length===1&&S)throw S;if(u.length>1)throw new AggregateError(u,`scheduled("${o.cron}") had ${String(u.length)} failure(s)`)},Qt=async(o,i)=>{try{const h=o??{},u=e.adminToken??(typeof h.LUNORA_ADMIN_TOKEN=="string"?h.LUNORA_ADMIN_TOKEN:void 0);if(!u||u.length===0)return;const f=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:{outcome:i},functionPath:Uo}),headers:{authorization:`Bearer ${u}`,"content-type":"application/json"},method:"POST"});await ae(d,n,f)}catch{}},zt=async(o,i,h,u)=>{if(!e.authHandler)return;const f=await e.authHandler(o);if(!f)return;const O=e.authBasePath??No;return xo(h.pathname,O)&&u.waitUntil?.(Qt(i,f.status>=400?"fail":"ok")),f},Wt=async({args:o,env:i,functionPath:h,request:u,shardKey:f,waitUntil:O})=>{const S={functionPath:h,...f===void 0?{}:{shardKey:f}},{headers:m,identity:E}=await ce(u,i,s);await Oe(S,E);const A=f??n,U=Ee(i,u,O),q=()=>ve(u,h,o,A,m,U),$=wt(S,e);return $&&e.x402Charge?e.x402Charge(u,{functionPath:h,price:$.price},q,lt({waitUntil:O})):q()},Ht=br({functions:e.functions??{},invoke:Wt,readJsonBody:te,...e.restRateLimit?{rateLimit:e.restRateLimit}:{}}),De=e.routes!==void 0&&Object.keys(e.routes).length>0?e.routes:void 0,Jt={[Do]: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"}}),[To]:(o,i,h)=>qt(o,i,h),[ct]:(o,i,h,u)=>Bt(o,i,u),[Eo]:(o,i,h,u)=>Ct(o,i,u),[_o]:(o,i)=>F(o,i),[Ro]:(o,i)=>N(o,i),[So]:async o=>{if(o.method!=="POST")throw new a("ws-token endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});j(o);const i=b();if(i===void 0)throw new a("ws-token minting requires a configured admin token",{code:"ADMIN_TOKEN_NOT_CONFIGURED",status:400});const h=await Pr(i);return Response.json(h,{headers:{"cache-control":"no-store"}})},...I,...ie,...Ae,...re,...Rt,...St,...At,...vt,...Dt,...It,...Ht,...$r({assertAdmin:j,getAuthAdmin:()=>e.authAdmin,parsePaging:pe,queryParameter:Z,readJsonBody:te})};let de=Ve(e.security),Ke=!1;const Vt=o=>{Ke||(Ke=!0,de=Ve(e.security,o??{}))},Yt=async(o,i)=>{if(!(e.adminGate===void 0||!ko(i)))try{await e.adminGate(o)&&g.add(o)}catch{}},Xt=async(o,i,h)=>{const u=new URL(o.url);if(o.method==="POST"||o.method==="PUT"){const m=Number(o.headers.get("content-length")??""),E=u.pathname===Et?Tt:ge;if(Number.isFinite(m)&&m>E)throw new a("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413})}const f=await zt(o,i,u,h);if(f)return f;if(De){const m=`${o.method} ${u.pathname}`,E=De[m]??De[u.pathname];if(E)return E(o,i,h)}const O=Jt[u.pathname];return O?(await Yt(o,u.pathname),O(o,i,u,h)):e.voiceAgents!==void 0&&u.pathname.startsWith(pt)?$t(o,i,u):await Ut(o,i,h)||new Response("Not found",{status:404})};return{async fetch(o,i,h){e.passThroughOnException&&h.passThroughOnException?.(),Vt(i),w(i);const u=Or(o,de);if(u)return u;const f=Er(o,de);if(f)return Ue(f,o,de);try{const O=await Xt(o,i,h);return Ue(O,o,de)}catch(O){return Ue(We(O),o,de)}finally{He(e.observability,ft(h))}},async queue(o,i,h){await Me(`queue:${Bo(o)}`,h,async()=>{await e.queue?.(o,i,h)})},async scheduled(o,i,h){await Me(`cron:${o.cron}`,h,async()=>{await Ft(o,i,h)})},serverQuery:jt}},Vo=e=>_t(e),Yo=e=>typeof e=="function"?{fetch:e}:e,Xo=e=>!!(e.crons??e.cronJobs??e.backupCron),pa=(e,t)=>{const r=Yo(e),n=typeof e=="object"&&typeof e.scheduled=="function"?e.scheduled:void 0,s=c=>{const l=Vo({...c,httpRouter:r});return n!==void 0&&!Xo(c)?{...l,scheduled:async(b,T,D)=>{await n(b,T,D)}}:l};if(typeof t!="function")return s(t);const d=t;return{fetch:(c,l,b)=>s(d(l)).fetch(c,l,b),queue:(c,l,b)=>s(d(l)).queue?.(c,l,b)??Promise.resolve(),scheduled:(c,l,b)=>s(d(l)).scheduled(c,l,b),serverQuery:(c,l,b,T,D)=>s(d(l)).serverQuery(c,l,b,T,D)}},Zo=(e,t)=>{if(typeof e=="function")return e(t);const r=e.shardDO??t?.SHARD;if(!r)throw new a("@lunora/runtime: no shard Durable Object namespace found. Bind `SHARD` in wrangler.jsonc, or pass `createLunoraHandler({ shardDO: env.MY_SHARD })`.");return{...e,shardDO:r}},fa=(e={})=>(t,r,n)=>_t(Zo(e,r)).fetch(t,r,n??ar),wa=e=>e;export{xr as GET_AUTH_AUDIT_LOG_OP,ar as NOOP_EXECUTION_CONTEXT,ga as composeIdentityResolvers,Vo as composeWorker,fa as createLunoraHandler,_t as createWorker,wa as defineRpcEnvelope,Qo as probeRelayCount,Zo as resolveLunoraOptions,ba as routeIdentityResolvers,pa 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.49",
|
|
4
4
|
"description": "Lunora Worker runtime: the RPC router, shard resolver, and query coordinator",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cloudflare",
|
|
@@ -46,8 +46,8 @@
|
|
|
46
46
|
"access": "public"
|
|
47
47
|
},
|
|
48
48
|
"dependencies": {
|
|
49
|
-
"@lunora/bindings": "1.0.0-alpha.
|
|
50
|
-
"@lunora/errors": "1.0.0-alpha.
|
|
49
|
+
"@lunora/bindings": "1.0.0-alpha.15",
|
|
50
|
+
"@lunora/errors": "1.0.0-alpha.10",
|
|
51
51
|
"@lunora/platform": "1.0.0-alpha.1"
|
|
52
52
|
},
|
|
53
53
|
"engines": {
|
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
import{isLunoraError as nr,toErrorBody as or}from"@lunora/errors";import{NOOP_EXECUTION_CONTEXT as ar}from"./NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{O as Re,m as sr,A as ir,R as dr,d as ur,i as cr,s as lr}from"./otlp-resource-B-ByO9qo.mjs";import{LunoraError as a,toErrorResponse as We}from"./LunoraError-ByasbDmd.mjs";import{runExportTap as hr}from"./createKvCursorStore-C24tEuYk.mjs";import{d as me}from"./method-guard-BbuR0VfS.mjs";import{buildHealthRoutes as pr,durableObjectProbe as fr,d1Probe as wr,presenceProbe as Ne}from"./HEALTH_PATH-BpCNEAIa.mjs";import{wrapResolverWithContract as mr}from"./composeIdentityResolvers-DwE0Jbww.mjs";import{composeIdentityResolvers as ya,routeIdentityResolvers as ga}from"./composeIdentityResolvers-DwE0Jbww.mjs";import{buildLogArchiveAdminRoutes as yr}from"./LOG_ARCHIVE_PATH-DGsEec3K.mjs";import{o as gr,f as He,a as ue}from"./observability-DYnm-d4g.mjs";import{resolveShard as Se,applyJurisdiction as Je}from"./applyJurisdiction-8bzZjAPR.mjs";import{buildRestRoutes as br}from"./argsFromQuery-BkJXnIpe.mjs";import{resolveSecurity as Ve,handleCorsPreflight as Or,enforceOrigin as Er,decorateResponse as Ue,enforceWebSocketOrigin as Ye}from"./decorateResponse-DBIWsRSZ.mjs";const yt=(e,t)=>{if(e.size<t)return;const r=e.keys().next().value;r!==void 0&&e.delete(r)},Tr="::relay::",_r=(e,t)=>`${e}${Tr}${String(t)}`,je=new TextEncoder,Rr=e=>{const t=String.fromCodePoint(...e);return btoa(t).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")},Sr=e=>{const t=e.replaceAll("-","+").replaceAll("_","/")+"===".slice((e.length+3)%4),r=atob(t),n=new Uint8Array(r.length);for(let s=0;s<r.length;s+=1)n[s]=r.codePointAt(s)??0;return n},Ar=64,qe=new Map,gt=async e=>{const t=qe.get(e);if(t)return t;yt(qe,Ar);const r=crypto.subtle.importKey("raw",je.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]);return qe.set(e,r),r},vr=async(e,t)=>{const r=await gt(e),n=await crypto.subtle.sign("HMAC",r,je.encode(t));return Rr(new Uint8Array(n))},Dr=async(e,t,r)=>{const n=await gt(e);return crypto.subtle.verify("HMAC",n,r,je.encode(t))},bt="v1",kr=6e4,Ir=async(e,t={})=>{const r=(t.now??Date.now())+(t.ttlMs??kr),n=`${bt}.${String(r)}`,s=await vr(e,n);return{expiresAtMs:r,token:`${n}.${s}`}},Pr=async(e,t,r=Date.now())=>{if(e.length===0||t.length===0)return!1;const n=t.split(".");if(n.length!==3)return!1;const[s,d,c]=n;if(s!==bt||c.length===0)return!1;const l=Number(d);if(!Number.isFinite(l)||l<=r)return!1;let y;try{y=Sr(c)}catch{return!1}return Dr(e,`${s}.${d}`,y)},k="/_lunora/admin/auth",Nr={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},I=(e,t)=>{const r=e[t];if(typeof r!="string"||r==="")throw new a(`\`${t}\` is required`,{code:"BAD_REQUEST",status:400});return r},he=(e,t)=>{const r=e(t);if(r===void 0)throw new a(`\`${t}\` query parameter is required`,{code:"BAD_REQUEST",status:400});return r},$e=e=>{if(typeof e=="string"||Array.isArray(e)&&e.every(t=>typeof t=="string"))return e},ee=(e,t)=>typeof e[t]=="string"?e[t]:void 0,Xe=(e,t)=>{const r=e[t];return typeof r=="object"&&r!==null&&!Array.isArray(r)?r:void 0},Ze=e=>{const t=e.permission;if(typeof t!="object"||t===null||Array.isArray(t))throw new a("`permission` object is required",{code:"BAD_REQUEST",status:400});const r={};for(const[n,s]of Object.entries(t))Array.isArray(s)&&s.every(d=>typeof d=="string")&&(r[n]=s);return r},Ur={[`${k}/capabilities`]:{build:()=>({}),http:"GET",method:"capabilities"},[`${k}/users`]:{build:({paging:e,query:t})=>{const r=t("sortDirection");return{...e,filterField:t("filterField"),filterValue:t("filterValue"),search:t("search"),searchField:t("searchField"),sortBy:t("sortBy"),sortDirection:r==="asc"||r==="desc"?r:void 0}},http:"GET",method:"listUsers"},[`${k}/sessions`]:{build:({paging:e,query:t})=>({...e,userId:t("userId")}),http:"GET",method:"listSessions"},[`${k}/accounts`]:{build:({query:e})=>({userId:he(e,"userId")}),http:"GET",method:"listAccounts"},[`${k}/passkeys`]:{build:({query:e})=>({userId:he(e,"userId")}),http:"GET",method:"listPasskeys"},[`${k}/organizations`]:{build:({paging:e})=>({...e}),http:"GET",method:"listOrganizations"},[`${k}/organizations/members`]:{build:({paging:e,query:t})=>({...e,organizationId:he(t,"organizationId")}),http:"GET",method:"listMembers"},[`${k}/organizations/invitations`]:{build:({paging:e,query:t})=>({...e,organizationId:he(t,"organizationId")}),http:"GET",method:"listInvitations"},[`${k}/config`]:{build:()=>({}),http:"GET",method:"config"},[`${k}/organizations/teams`]:{build:({paging:e,query:t})=>({...e,organizationId:he(t,"organizationId")}),http:"GET",method:"listTeams"},[`${k}/organizations/teams/members`]:{build:({paging:e,query:t})=>({...e,teamId:he(t,"teamId")}),http:"GET",method:"listTeamMembers"},[`${k}/organizations/roles`]:{build:({paging:e,query:t})=>({...e,organizationId:he(t,"organizationId")}),http:"GET",method:"listOrgRoles"},[`${k}/users/create`]:{build:({body:e})=>({data:typeof e.data=="object"&&e.data!==null&&!Array.isArray(e.data)?e.data:void 0,email:I(e,"email"),name:I(e,"name"),password:ee(e,"password"),role:$e(e.role)}),http:"POST",method:"createUser"},[`${k}/users/update`]:{build:({body:e})=>{const{data:t}=e;if(typeof t!="object"||t===null||Array.isArray(t))throw new a("`data` object is required",{code:"BAD_REQUEST",status:400});return{data:t,userId:I(e,"userId")}},http:"POST",method:"updateUser"},[`${k}/users/role`]:{build:({body:e})=>{const t=$e(e.role);if(t===void 0||typeof t=="string"&&t.trim()==="")throw new a("`role` is required",{code:"BAD_REQUEST",status:400});return{role:t,userId:I(e,"userId")}},http:"POST",method:"setRole"},[`${k}/users/ban`]:{build:({body:e})=>({expiresInSeconds:typeof e.expiresInSeconds=="number"?e.expiresInSeconds:void 0,reason:ee(e,"reason"),userId:I(e,"userId")}),http:"POST",method:"banUser"},[`${k}/users/unban`]:{build:({body:e})=>({userId:I(e,"userId")}),http:"POST",method:"unbanUser"},[`${k}/users/password`]:{build:({body:e})=>({newPassword:I(e,"newPassword"),userId:I(e,"userId")}),http:"POST",method:"setUserPassword",returns:"void"},[`${k}/users/remove`]:{build:({body:e})=>({userId:I(e,"userId")}),http:"POST",method:"removeUser",returns:"void"},[`${k}/users/impersonate`]:{build:({body:e})=>({userId:I(e,"userId")}),http:"POST",method:"impersonateUser"},[`${k}/sessions/revoke`]:{build:({body:e})=>({sessionId:I(e,"sessionId")}),http:"POST",method:"revokeUserSession",returns:"void"},[`${k}/sessions/revoke-all`]:{build:({body:e})=>({userId:I(e,"userId")}),http:"POST",method:"revokeUserSessions",returns:"void"},[`${k}/accounts/unlink`]:{build:({body:e})=>({accountId:I(e,"accountId"),userId:I(e,"userId")}),http:"POST",method:"unlinkAccount",returns:"void"},[`${k}/two-factor/disable`]:{build:({body:e})=>({userId:I(e,"userId")}),http:"POST",method:"disableTwoFactor",returns:"void"},[`${k}/passkeys/delete`]:{build:({body:e})=>({passkeyId:I(e,"passkeyId")}),http:"POST",method:"deletePasskey",returns:"void"},[`${k}/organizations/members/remove`]:{build:({body:e})=>({memberId:I(e,"memberId")}),http:"POST",method:"removeMember",returns:"void"},[`${k}/organizations/invitations/cancel`]:{build:({body:e})=>({invitationId:I(e,"invitationId")}),http:"POST",method:"cancelInvitation",returns:"void"},[`${k}/organizations/create`]:{build:({body:e})=>({logo:ee(e,"logo"),metadata:Xe(e,"metadata"),name:I(e,"name"),ownerId:ee(e,"ownerId"),slug:ee(e,"slug")}),http:"POST",method:"createOrganization"},[`${k}/organizations/update`]:{build:({body:e})=>({logo:ee(e,"logo"),metadata:Xe(e,"metadata"),name:ee(e,"name"),organizationId:I(e,"organizationId"),slug:ee(e,"slug")}),http:"POST",method:"updateOrganization"},[`${k}/organizations/remove`]:{build:({body:e})=>({organizationId:I(e,"organizationId")}),http:"POST",method:"deleteOrganization",returns:"void"},[`${k}/organizations/members/add`]:{build:({body:e})=>({organizationId:I(e,"organizationId"),role:ee(e,"role"),userId:I(e,"userId")}),http:"POST",method:"addMember"},[`${k}/organizations/members/invite`]:{build:({body:e})=>({email:I(e,"email"),inviterId:ee(e,"inviterId"),organizationId:I(e,"organizationId"),role:ee(e,"role")}),http:"POST",method:"inviteMember"},[`${k}/organizations/members/role`]:{build:({body:e})=>{const t=$e(e.role);if(t===void 0||typeof t=="string"&&t.trim()==="")throw new a("`role` is required",{code:"BAD_REQUEST",status:400});return{memberId:I(e,"memberId"),role:t}},http:"POST",method:"updateMemberRole"},[`${k}/organizations/teams/create`]:{build:({body:e})=>({name:I(e,"name"),organizationId:I(e,"organizationId")}),http:"POST",method:"createTeam"},[`${k}/organizations/teams/update`]:{build:({body:e})=>({name:I(e,"name"),teamId:I(e,"teamId")}),http:"POST",method:"updateTeam"},[`${k}/organizations/teams/remove`]:{build:({body:e})=>({teamId:I(e,"teamId")}),http:"POST",method:"removeTeam",returns:"void"},[`${k}/organizations/teams/members/add`]:{build:({body:e})=>({teamId:I(e,"teamId"),userId:I(e,"userId")}),http:"POST",method:"addTeamMember"},[`${k}/organizations/teams/members/remove`]:{build:({body:e})=>({teamMemberId:I(e,"teamMemberId")}),http:"POST",method:"removeTeamMember",returns:"void"},[`${k}/organizations/roles/create`]:{build:({body:e})=>({organizationId:I(e,"organizationId"),permission:Ze(e),role:I(e,"role")}),http:"POST",method:"createOrgRole"},[`${k}/organizations/roles/update`]:{build:({body:e})=>({permission:Ze(e),roleId:I(e,"roleId")}),http:"POST",method:"updateOrgRole"},[`${k}/organizations/roles/remove`]:{build:({body:e})=>({roleId:I(e,"roleId")}),http:"POST",method:"deleteOrgRole",returns:"void"}},qr=e=>{const t=async s=>{try{return await s()}catch(d){if(d instanceof a)throw d;const c=d,l=typeof c.code=="string"?c.code:"AUTH_ADMIN_ERROR";throw console.error("[lunora] auth admin operation failed:",d),new a("auth admin operation failed",{code:l,status:Nr[l]??500})}},r=async(s,d)=>{if(e.assertAdmin(s),s.method!==d.http)throw new a(`Auth admin endpoint requires ${d.http}`,{code:"METHOD_NOT_ALLOWED",status:405});const c=e.getAuthAdmin();if(c===void 0)throw new a("auth endpoints require an `authAdmin` on the worker",{code:"AUTH_NOT_CONFIGURED",status:400});const l=c[d.method];if(l===void 0)throw new a(`auth admin does not support \`${d.method}\``,{code:"AUTH_OP_NOT_SUPPORTED",status:400});const y=new URL(s.url),E={body:d.http==="POST"?await e.readJsonBody(s):{},paging:e.parsePaging(s),query:b=>e.queryParameter(y,b)},D=d.build(E),g=await t(()=>l(D));return Response.json(d.returns==="void"?{ok:!0}:g,{headers:{"content-type":"application/json"},status:200})},n={};for(const[s,d]of Object.entries(Ur))n[s]=c=>r(c,d);return n},$r="__lunora_admin__:getAuthAuditLog",et=e=>typeof e=="string"&&e!==""?e:void 0,tt=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0,xr=e=>async(t,r)=>{e.assertAdmin(t);const n=e.getReader();if(n===void 0)throw new a("the auth/security audit endpoint requires an `authAuditReader` on the worker",{code:"AUTH_AUDIT_NOT_CONFIGURED",status:400});const s={},d=et(r.actorId),c=et(r.event),l=tt(r.sinceSeq),y=tt(r.limit);d!==void 0&&(s.actorId=d),c!==void 0&&(s.event=c),l!==void 0&&(s.sinceSeq=l),y!==void 0&&(s.limit=y);let E;try{E=await n.read(s)}catch(g){throw g instanceof a?g:(console.error("[lunora] auth audit read failed:",g),new a("auth audit read failed",{code:"AUTH_AUDIT_READ_FAILED",status:500}))}const D={entries:E};return Response.json(D,{headers:{"content-type":"application/json"},status:200})},rt=500,Lr=(e,t,r)=>{if(typeof e!="object"||e===null||Array.isArray(e))throw new a("each batch call must be an object",{code:"BAD_REQUEST",status:400});const n=e;if(typeof n.functionPath!="string")throw new a("each batch call needs a string `functionPath`",{code:"BAD_REQUEST",status:400});if(n.functionPath.startsWith("__lunora_relation__:")||n.functionPath.startsWith("__lunora_admin__"))throw new a("reserved function path cannot be batched",{code:"FORBIDDEN",status:403});if(n.args!==void 0&&(typeof n.args!="object"||n.args===null||Array.isArray(n.args)))throw new a("each batch call `args` must be an object",{code:"BAD_REQUEST",status:400});return{entry:{args:n.args===void 0?{}:n.args,clientId:typeof n.clientId=="string"?n.clientId:void 0,clientSeq:typeof n.clientSeq=="number"?n.clientSeq:void 0,functionPath:n.functionPath,id:typeof n.id=="number"?n.id:t,mutationId:typeof n.mutationId=="string"?n.mutationId:void 0},shardKey:typeof n.shardKey=="string"?n.shardKey:r}},Br=(e,t)=>{if(e.length>rt)throw new a(`RPC batch exceeds the ${String(rt)}-call limit`,{code:"BAD_REQUEST",status:400});const r=new Map;for(const[n,s]of e.entries()){const{entry:d,shardKey:c}=Lr(s,n,t),l=r.get(c)??[];l.push(d),r.set(c,l)}return r},ge=1048576,se=async(e,t=ge)=>{if(!e.body)return"";const r=e.body.getReader(),n=new TextDecoder;let s=0,d="";for(;;){const{done:c,value:l}=await r.read();if(c)break;if(l){if(s+=l.byteLength,s>t)throw await r.cancel().catch(()=>{}),new a("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});d+=n.decode(l,{stream:!0})}}return d+=n.decode(),d},Cr=async(e,t=ge)=>{if(!e.body)return new ArrayBuffer(0);const r=e.body.getReader(),n=[];let s=0;for(;;){const{done:l,value:y}=await r.read();if(l)break;if(y){if(s+=y.byteLength,s>t)throw await r.cancel().catch(()=>{}),new a("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});n.push(y)}}const d=new Uint8Array(s);let c=0;for(const l of n)d.set(l,c),c+=l.byteLength;return d.buffer},te=async(e,t=ge)=>{try{const r=await se(e,t);return r===""?{}:JSON.parse(r)}catch(r){throw r instanceof a?r:new a("Request body must be valid JSON",{code:"BAD_REQUEST",status:400})}},jr=new TextEncoder,Gr=e=>{const t=JSON.stringify(e),r=jr.encode(t);let n="";for(const s of r)n+=String.fromCodePoint(s);return btoa(n).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")},Mr=e=>{const t={g:0,s:{},v:1};if(typeof e!="string"||e.length===0)return t;try{const r=atob(e.replaceAll("-","+").replaceAll("_","/")),n=new Uint8Array(r.length);for(let l=0;l<r.length;l+=1)n[l]=r.codePointAt(l)??0;const s=JSON.parse(new TextDecoder().decode(n)),d=s.s&&typeof s.s=="object"?s.s:{},c={};for(const[l,y]of Object.entries(d))typeof y=="number"&&Number.isFinite(y)&&(c[l]=y);return{g:typeof s.g=="number"&&Number.isFinite(s.g)?s.g:0,s:c,v:1}}catch{return t}},Kr=e=>{const t=typeof e.table=="string"?e.table:"",r=typeof e.op=="string"?e.op:"",n=r==="delete"||r==="insert"||r==="update"?r:"upsert",s=typeof e.id=="string"?e.id:void 0;return{doc:(e.doc&&typeof e.doc=="object"?e.doc:void 0)??(s===void 0?{}:{_id:s}),op:n,table:t}},nt=(e,t,r)=>{for(const n of t)e.push(Kr(n));return r!==void 0&&t.length>=r},Fr="/_lunora/admin/export",Qr="/_lunora/admin/import",zr="/_lunora/admin/sync",Wr="/_lunora/admin/connector/sync",Hr="/_lunora/admin/apply",Jr="/_lunora/admin/export-tap/run",Vr=new TextEncoder,Yr=async e=>{let t;try{const s=await se(e);t=s===""?{}:JSON.parse(s)}catch(s){throw s instanceof a?s:new a("Export body must be valid JSON",{code:"BAD_REQUEST",status:400})}const r=t??{};if(r.tables===void 0)return{tables:void 0};if(!Array.isArray(r.tables))throw new a("Export `tables` must be a string array",{code:"BAD_REQUEST",status:400});const n=[];for(const s of r.tables){if(typeof s!="string"||s.length===0)throw new a("Export `tables` entries must be non-empty strings",{code:"BAD_REQUEST",status:400});n.push(s)}return{tables:n}},Xr=e=>{const{applyGlobals:t,exportCursorStore:r,exportSinks:n,knownTables:s,queryCoordinator:d,assertAdmin:c,requireAdminOption:l,resolveForwardContext:y,shardDO:E,streamExportRows:D,streamingImport:g,syncGlobals:b}=e,p=async(v,G)=>{const B=me(v,["POST"]);if(B)return B;const Y=l(v,d,{code:"BAD_REQUEST",message:"Export endpoint requires a `queryCoordinator` on the worker"}),N=await Yr(v),{headers:K}=await y(v,G),F=new ReadableStream({async pull(C){const M=X=>{C.enqueue(Vr.encode(`${JSON.stringify(X)}
|
|
2
|
-
`))};try{await D(Y,K,N.tables,M),C.close()}catch(X){C.error(X)}}});return new Response(F,{headers:{"content-type":"application/x-ndjson"},status:200})},m=async(v,G)=>{const B=me(v,["POST"]);if(B)return B;const Y=l(v,d,{code:"BAD_REQUEST",message:"Sync endpoint requires a `queryCoordinator` on the worker"}),N=await te(v),K=typeof N.cursors=="object"&&N.cursors!==null?N.cursors:{},F=typeof N.limit=="number"?N.limit:void 0,C=typeof N.globalCursor=="number"?N.globalCursor:0,M=Array.isArray(N.tables)?N.tables.filter(Z=>typeof Z=="string"):void 0,{headers:X}=await y(v,G),J=M??s(),oe=await Y.orchestrateCdcSync(E,{cursors:K,headers:X,limit:F,tables:J}),ie=b?await b({limit:F,sinceSeq:C}):void 0;return Response.json({global:ie,shards:oe.shards},{status:200})},_=async(v,G)=>{const B=me(v,["POST"]);if(B)return B;const Y=l(v,d,{code:"BAD_REQUEST",message:"Connector sync endpoint requires a `queryCoordinator` on the worker"}),N=await te(v),K=Mr(N.cursor),F=typeof N.limit=="number"&&N.limit>0?N.limit:void 0,C=Array.isArray(N.tables)?N.tables.filter(re=>typeof re=="string"):void 0,{headers:M}=await y(v,G),X=C??s(),J=await Y.orchestrateCdcSync(E,{cursors:K.s,headers:M,limit:F,tables:X}),oe=[],ie={...K.s};let Z=!1;for(const re of J.shards)Z=nt(oe,re.changes??[],F)||Z,ie[re.shardKey]=re.cursor;let pe=K.g;if(b){const re=await b({limit:F,sinceSeq:K.g});Z=nt(oe,re.changes,F)||Z,pe=re.cursor}const be=Gr({g:pe,s:ie,v:1}),Ae={changes:oe,hasMore:Z,nextCursor:be};return Response.json(Ae,{status:200})},R=async(v,G)=>{const B=me(v,["POST"]);if(B)return B;const Y=l(v,d,{code:"BAD_REQUEST",message:"Apply endpoint requires a `queryCoordinator` on the worker"}),N=await te(v),K=(Array.isArray(N.batches)?N.batches:[]).map(J=>J).filter(J=>J!==null&&typeof J=="object"&&typeof J.shardKey=="string"&&Array.isArray(J.changes)),F=Array.isArray(N.globalChanges)?N.globalChanges:[],{headers:C}=await y(v,G),M=await Y.orchestrateApplyCdc(E,{batches:K,headers:C}),X=F.length>0&&t?await t({changes:F}):0;return Response.json({applied:M.applied+X,failed:M.failed,ok:M.ok},{status:200})},P=async(v,G)=>{const B=me(v,["POST"]);if(B)return B;c(v);const{headers:Y}=await y(v,G),N=await g(v,Y);return Response.json(N,{headers:{"content-type":"application/json"},status:200})},q=async(v,G)=>{const B=me(v,["POST"]);if(B)return B;const Y=l(v,d,{code:"BAD_REQUEST",message:"Export-tap endpoint requires a `queryCoordinator` on the worker"});if(n===void 0||Object.keys(n).length===0||r===void 0)throw new a("Export-tap endpoint requires `exportSinks` + `exportCursorStore` on the worker",{code:"EXPORT_TAP_NOT_CONFIGURED",status:400});const N=await te(v),K=typeof N.sink=="string"?N.sink:void 0,F=typeof N.limit=="number"&&N.limit>0?N.limit:void 0,C=Array.isArray(N.tables)?N.tables.filter(ie=>typeof ie=="string"):void 0;if(K===void 0)throw new a("Export-tap `sink` must name a configured sink",{code:"BAD_REQUEST",status:400});const M=n[K];if(M===void 0)throw new a(`Export-tap sink "${K}" is not configured`,{code:"NOT_FOUND",status:404});const{headers:X}=await y(v,G),J=C??s(),oe=await hr({coordinator:Y,cursorStore:r,headers:X,limit:F,shardDO:E,sink:M,tables:J});return Response.json(oe,{headers:{"content-type":"application/json"},status:200})};return{[Hr]:R,[Wr]:_,[Fr]:p,[Jr]:q,[Qr]:P,[zr]:m}},Ot=e=>[],Zr=(e,t)=>{const r=[],n=[];if(t&&t.length>0)for(const s of t)e.resolveTableSharding?.(s)?.mode.kind==="global"?n.push(s):r.push(s);return{globalTables:n,shardLocalTables:r}},en=async(e,t,r,n,s,d,c)=>{if(n!==void 0&&s.length===0)return;const l=n===void 0?[]:s,y=n===void 0?Ot():[],E=l.length>0?l:y,D=await t.orchestrateExport(c,{args:{tables:l},headers:r,tables:E});for(const g of D.shards)if(!g.error)for(const b of g.rows??[])d(b)},ot=async(e,t,r,n,s,d)=>{const{globalTables:c,shardLocalTables:l}=Zr(e,n);await en(e,t,r,n,l,s,d);const y=e.exportGlobals;if((n===void 0||c.length>0)&&y){const E=n===void 0?[]:c;for await(const D of y({tables:E}))s(D)}},tn=(e,t)=>{let r;try{r=JSON.parse(e)}catch{return{error:{code:"BAD_ROW",line:t,message:"line is not valid JSON",table:""},ok:!1}}if(!r||typeof r!="object"||Array.isArray(r))return{error:{code:"BAD_ROW",line:t,message:"row must be a JSON object",table:""},ok:!1};const n=r;return typeof n.table!="string"||n.table.length===0?{error:{code:"BAD_ROW",line:t,message:"row is missing `table`",table:""},ok:!1}:!n.doc||typeof n.doc!="object"||Array.isArray(n.doc)?{error:{code:"BAD_ROW",line:t,message:"row is missing or malformed `doc`",table:n.table},ok:!1}:{doc:n.doc,ok:!0,table:n.table}},rn=(e,t,r,n,s)=>{if(r?.mode.kind==="shardBy"&&typeof r.mode.field=="string"){const d=e[r.mode.field];return d==null?{error:{code:"BAD_ROW",line:s,message:`row missing shard field "${r.mode.field}" for table "${t}"`,table:t},ok:!1}:{ok:!0,shardKey:typeof d=="string"?d:JSON.stringify(d)}}return{ok:!0,shardKey:n}},nn=async(e,t,r)=>{if(!e.body)throw new a("Import endpoint requires a request body",{code:"BAD_REQUEST",status:400});const n=[],s=[],d=new Map;let c=0;const l=e.body.getReader(),y=new TextDecoder;let E="",D=0;const g=b=>{c+=1;const p=b.trim();if(p.length===0)return;const m=tn(p,c);if(!m.ok){n.push(m.error);return}const{doc:_,table:R}=m,P=t.resolveTableSharding?.(R);if(P?.mode.kind==="global"){s.push({doc:_,line:c,table:R});return}const q=rn(_,R,P,r,c);if(!q.ok){n.push(q.error);return}const v=d.get(q.shardKey);v?v.rows.push({doc:_,table:R}):d.set(q.shardKey,{rows:[{doc:_,table:R}],shardKey:q.shardKey,startLine:c})};for(;;){const{done:b,value:p}=await l.read();if(b)break;if(p&&(D+=p.byteLength,D>ge))throw await l.cancel().catch(()=>{}),new a("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});E+=y.decode(p,{stream:!0});let m=E.indexOf(`
|
|
3
|
-
`);for(;m!==-1;){const _=E.slice(0,m);E=E.slice(m+1),g(_),m=E.indexOf(`
|
|
4
|
-
`)}}return E.length>0&&g(E),{errors:n,globalRows:s,perShard:d}},at=(e,t)=>{for(const[r,n]of Object.entries(t.inserted))e.inserted[r]=(e.inserted[r]??0)+n;for(const r of t.errors)e.errors.push({...r});e.conflicts+=t.conflicts},on=async(e,t,r,n)=>{const s=t.defaultShardKey??"__root__",{errors:d,globalRows:c,perShard:l}=await nn(e,t,s),y={conflicts:0,errors:d,inserted:{}};if(l.size>0){const E=t.queryCoordinator;if(!E)throw new a("Import endpoint requires a `queryCoordinator` on the worker",{code:"BAD_REQUEST",status:400});const D=await E.orchestrateImport(n,{batches:[...l.values()],headers:r});at(y,D)}if(c.length>0)if(t.importGlobals){const E=c[0]?.line??1,D=await t.importGlobals({rows:c,startLine:E});at(y,D)}else for(const E of c)y.errors.push({code:"GLOBAL_NOT_CONFIGURED",line:E.line,message:`row targets global table "${E.table}" but no \`importGlobals\` is configured`,table:E.table});return{conflicts:y.conflicts,errors:y.errors,inserted:y.inserted}},xe=e=>typeof e=="object"&&e!==null?e:{},Le=e=>typeof e.kind=="string"?e.kind:"unknown",an=(e,t)=>{let r=xe(t),n=!1;Le(r)==="optional"&&(n=!0,r=xe(r._meta?.inner));const s=Le(r),d=r._meta??{},c={kind:s,name:e,optional:n};if(s==="id"&&typeof d.tableName=="string"&&(c.table=d.tableName),s==="array"){const l=Le(xe(d.inner));l!=="unknown"&&(c.element=l)}return c},sn=e=>typeof e!="object"||e===null?[]:Object.entries(e).map(([t,r])=>an(t,r)).toSorted((t,r)=>t.name.localeCompare(r.name)),dn="/_lunora/admin/functions",un="/_lunora/admin/cron-jobs",cn="/_lunora/admin/openapi",ln="/_lunora/admin/openrpc",hn="/_lunora/admin/global/tables",pn="/_lunora/admin/global/table",fn="/_lunora/admin/global/facet",st=e=>{if(e===void 0||e==="")return;let t;try{t=JSON.parse(e)}catch{return}if(!Array.isArray(t))return;const r=t.flatMap(n=>{if(typeof n!="object"||n===null||typeof n.column!="string")return[];const{column:s,value:d}=n;return[{column:s,value:d}]});return r.length===0?void 0:r},wn=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:{}}),mn=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"}),yn=e=>{const{assertAdmin:t,options:r,parsePaging:n,queryParameter:s,requireAdminOption:d}=e,c=p=>{if(p.method!=="GET")throw new a("Functions endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});const m=d(p,r.functions,{code:"FUNCTIONS_NOT_CONFIGURED",message:"functions endpoint requires a `functions` registry on the worker"}),_=Object.entries(m).flatMap(([R,P])=>P.visibility==="internal"||P.kind==="stream"?[]:[{args:sn(P.args),kind:P.kind,path:R}]).toSorted((R,P)=>R.path.localeCompare(P.path));return Response.json({functions:_},{headers:{"content-type":"application/json"},status:200})},l=p=>{if(p.method!=="GET")throw new a("Cron-jobs endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});const m=d(p,r.cronJobs,{code:"CRON_JOBS_NOT_CONFIGURED",message:"cron-jobs endpoint requires a `cronJobs` map on the worker"}),_=Object.entries(m).flatMap(([R,P])=>P.map(q=>({args:q.args,cron:R,functionPath:q.functionPath,name:q.name,shardKey:q.shardKey,workflow:q.workflow}))).toSorted((R,P)=>R.name.localeCompare(P.name));return Response.json({jobs:_},{headers:{"content-type":"application/json"},status:200})},y=p=>{if(p.method!=="GET")throw new a("OpenAPI endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});return t(p),Response.json(r.openApiSpec??wn,{headers:{"content-type":"application/json"},status:200})},E=p=>{if(p.method!=="GET")throw new a("OpenRPC endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});return t(p),Response.json(r.openRpcSpec??mn,{headers:{"content-type":"application/json"},status:200})},D=async p=>{if(p.method!=="GET")throw new a("Global-tables endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});const m=d(p,r.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"});return Response.json(await m.listTables(),{headers:{"content-type":"application/json"},status:200})},g=async p=>{if(p.method!=="GET")throw new a("Global-table endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});const m=d(p,r.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),_=new URL(p.url),R=s(_,"table");if(R===void 0)throw new a("Global-table endpoint requires a `table` query param",{code:"BAD_REQUEST",status:400});const P=await m.readTablePage({...n(p),filters:st(s(_,"filters")),table:R});return Response.json(P,{headers:{"content-type":"application/json"},status:200})},b=async p=>{if(p.method!=="GET")throw new a("Global-facet endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});const m=d(p,r.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),_=new URL(p.url),R=s(_,"table"),P=s(_,"column");if(R===void 0||P===void 0)throw new a("Global-facet endpoint requires `table` and `column` query params",{code:"BAD_REQUEST",status:400});const q=s(_,"limit"),v=q===void 0?void 0:Number(q),G=await m.facetColumn({column:P,filters:st(s(_,"filters")),limit:v!==void 0&&Number.isFinite(v)?v:void 0,table:R});return Response.json(G,{headers:{"content-type":"application/json"},status:200})};return{[un]:l,[dn]:c,[fn]:b,[pn]:g,[hn]:D,[cn]:y,[ln]:E}},gn="/_lunora/admin/kv/namespaces",bn="/_lunora/admin/kv/keys",Et="/_lunora/admin/kv/value",Tt=32*1048576,it=60,On=e=>{const{readJsonBody:t,requireAdminOption:r}=e,n=g=>r(g,e.kvIntrospector,{code:"KV_NOT_CONFIGURED",message:"KV endpoints require a `kvIntrospector` on the worker"}),s=g=>Response.json(g,{headers:{"content-type":"application/json"},status:200}),d=(g,b)=>{const p=new URL(g.url),m=p.searchParams.get("namespace")??"",_=p.searchParams.get("key")??"";if(m==="")throw new a(`KV-value ${b} request requires a \`namespace\` query parameter`,{code:"BAD_REQUEST",status:400});if(_==="")throw new a(`KV-value ${b} request requires a \`key\` query parameter`,{code:"BAD_REQUEST",status:400});return{key:_,namespace:m}},c=async(g,b)=>{if(!(await g.listNamespaces()).some(p=>p.binding===b))throw new a(`Unknown KV namespace binding \`${b}\``,{code:"NOT_FOUND",status:404})},l=async g=>{if(g.method!=="GET")throw new a("KV-namespaces endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});return s({namespaces:await n(g).listNamespaces()})},y=async g=>{if(g.method!=="GET")throw new a("KV-keys endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});const b=n(g),p=new URL(g.url),m=p.searchParams.get("namespace")??"";if(m==="")throw new a("KV-keys request requires a `namespace` query parameter",{code:"BAD_REQUEST",status:400});const _=p.searchParams.get("prefix")??void 0,R=p.searchParams.get("cursor")??void 0,P=p.searchParams.get("limit"),q=P===null?void 0:Number.parseInt(P,10);if(q!==void 0&&(!Number.isInteger(q)||q<1))throw new a("KV-keys `limit` must be a positive integer",{code:"BAD_REQUEST",status:400});const v=q===void 0?void 0:Math.min(q,1e3);return await c(b,m),s(await b.listKeys({cursor:R,limit:v,namespace:m,prefix:_}))},E={DELETE:async g=>{const b=n(g),p=d(g,"DELETE");return await c(b,p.namespace),await b.deleteKey(p),s({deleted:!0})},GET:async g=>{const b=n(g),p=d(g,"GET");return await c(b,p.namespace),s(await b.getValue(p))},PUT:async g=>{const b=n(g),p=await t(g,Tt);if(typeof p.namespace!="string"||p.namespace==="")throw new a("KV-value PUT request requires a `namespace` string",{code:"BAD_REQUEST",status:400});if(typeof p.key!="string"||p.key==="")throw new a("KV-value PUT request requires a `key` string",{code:"BAD_REQUEST",status:400});if(typeof p.value!="string")throw new a("KV-value PUT request requires a `value` string",{code:"BAD_REQUEST",status:400});if(p.expirationTtl!==void 0&&(typeof p.expirationTtl!="number"||!Number.isInteger(p.expirationTtl)||p.expirationTtl<it))throw new a("KV-value PUT `expirationTtl` must be an integer ≥ 60",{code:"BAD_REQUEST",status:400});const m=Math.floor(Date.now()/1e3)+it;if(p.expiration!==void 0&&(typeof p.expiration!="number"||!Number.isInteger(p.expiration)||p.expiration<m))throw new a("KV-value PUT `expiration` must be a Unix-seconds timestamp at least 60 seconds in the future",{code:"BAD_REQUEST",status:400});return await c(b,p.namespace),await b.putValue({expiration:p.expiration,expirationTtl:p.expirationTtl,key:p.key,metadata:p.metadata,namespace:p.namespace,value:p.value}),s({ok:!0})}},D=g=>{const b=E[g.method];if(!b)throw new a("KV-value endpoint requires GET, PUT, or DELETE",{code:"METHOD_NOT_ALLOWED",status:405});return b(g)};return{[gn]:l,[bn]:y,[Et]:D}},En="/_lunora/migrate",Tn="/_lunora/admin/pitr",_n="/_lunora/admin/rank",Rn="/_lunora/admin/rankpage",Sn="/_lunora/admin/shard-traffic",An=new Set(["__lunora_admin__:migrationStatus","__lunora_admin__:runMigration"]),vn=new Set(["__lunora_admin__:getPitrBookmark","__lunora_admin__:pitrRestore"]),Dn=async e=>{let t;try{const n=await se(e);t=n===""?{}:JSON.parse(n)}catch(n){throw n instanceof a?n:new a("Migration body must be valid JSON",{code:"BAD_REQUEST",status:400})}const r=t??{};if(typeof r.table!="string"||r.table.length===0)throw new a("Migration request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof r.functionPath!="string"||!An.has(r.functionPath))throw new a("Migration request `functionPath` must be a migration admin op",{code:"BAD_REQUEST",status:400});return{args:r.args??{},functionPath:r.functionPath,table:r.table}},kn=async e=>{let t;try{const n=await se(e);t=n===""?{}:JSON.parse(n)}catch(n){throw n instanceof a?n:new a("Rank body must be valid JSON",{code:"BAD_REQUEST",status:400})}const r=t??{};if(typeof r.table!="string"||r.table.length===0)throw new a("Rank request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof r.index!="string"||r.index.length===0)throw new a("Rank request is missing `index`",{code:"BAD_REQUEST",status:400});if(typeof r.partitionKey!="string")throw new a("Rank request `partitionKey` must be a string",{code:"BAD_REQUEST",status:400});if(typeof r.rowId!="string"||r.rowId.length===0)throw new a("Rank request is missing `rowId`",{code:"BAD_REQUEST",status:400});if(!Array.isArray(r.sortValues))throw new a("Rank request `sortValues` must be an array",{code:"BAD_REQUEST",status:400});return{index:r.index,partitionKey:r.partitionKey,rowId:r.rowId,sortValues:r.sortValues,table:r.table}},In=e=>{if(e!==void 0){if(!Array.isArray(e)||e.some(t=>t!=="asc"&&t!=="desc"))throw new a('Rank page request `directions` must be an array of "asc"|"desc"',{code:"BAD_REQUEST",status:400});return e}},Pn=e=>{if(typeof e.table!="string"||e.table.length===0)throw new a("Rank page request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof e.index!="string"||e.index.length===0)throw new a("Rank page request is missing `index`",{code:"BAD_REQUEST",status:400});if(e.partitionKey!==void 0&&typeof e.partitionKey!="string")throw new a("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 a("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 a("Rank page request `cursor` must be a string or null",{code:"BAD_REQUEST",status:400})},Nn=async e=>{let t;try{const s=await se(e);t=s===""?{}:JSON.parse(s)}catch(s){throw s instanceof a?s:new a("Rank page body must be valid JSON",{code:"BAD_REQUEST",status:400})}const r=t??{};Pn(r);const n=In(r.directions);return{cursor:typeof r.cursor=="string"?r.cursor:null,directions:n,index:r.index,partitionKey:typeof r.partitionKey=="string"?r.partitionKey:void 0,table:r.table,take:typeof r.take=="number"?r.take:void 0}},Un=async e=>{let t;try{const n=await se(e);t=n===""?{}:JSON.parse(n)}catch(n){throw n instanceof a?n:new a("Shard-traffic body must be valid JSON",{code:"BAD_REQUEST",status:400})}const r=t??{};if(typeof r.table!="string"||r.table.length===0)throw new a("Shard-traffic request is missing `table`",{code:"BAD_REQUEST",status:400});return{table:r.table}},qn=async e=>{const t=await te(e);if(typeof t.functionPath!="string"||!vn.has(t.functionPath))throw new a("PITR request `functionPath` must be a PITR admin op",{code:"BAD_REQUEST",status:400});if(t.shardKey!==void 0&&typeof t.shardKey!="string")throw new a("PITR `shardKey` must be a string",{code:"BAD_REQUEST",status:400});return{args:t.args??{},functionPath:t.functionPath,shardKey:t.shardKey}},$n=e=>{const{defaultShard:t,forwardToShard:r,isAdmin:n,queryCoordinator:s,resolveForwardContext:d,shardDO:c}=e,l=async(b,p)=>{if(b.method!=="POST")throw new a("Migration endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});if(!n(b))throw new a("Admin auth required",{code:"FORBIDDEN",status:403});if(!s)throw new a("Migration endpoint requires a `queryCoordinator` on the worker",{code:"BAD_REQUEST",status:400});const m=await Dn(b),{headers:_}=await d(b,p),R=await s.orchestrateMigration(c,{args:m.args,functionPath:m.functionPath,headers:_,table:m.table});return Response.json(R,{headers:{"content-type":"application/json"},status:200})},y=async(b,p)=>{if(b.method!=="POST")throw new a("Rank endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});if(!n(b))throw new a("Admin auth required",{code:"FORBIDDEN",status:403});if(!s)throw new a("Rank endpoint requires a `queryCoordinator` on the worker",{code:"BAD_REQUEST",status:400});const m=await kn(b),{headers:_}=await d(b,p),R=await s.orchestrateRank(c,{headers:_,index:m.index,partitionKey:m.partitionKey,rowId:m.rowId,sortValues:m.sortValues,table:m.table});return Response.json(R,{headers:{"content-type":"application/json"},status:200})},E=async(b,p)=>{if(b.method!=="POST")throw new a("Rank page endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});if(!n(b))throw new a("Admin auth required",{code:"FORBIDDEN",status:403});if(!s)throw new a("Rank page endpoint requires a `queryCoordinator` on the worker",{code:"BAD_REQUEST",status:400});const m=await Nn(b),{headers:_}=await d(b,p),R=await s.orchestrateRankPage(c,{...m,headers:_});return Response.json(R,{headers:{"content-type":"application/json"},status:200})},D=async(b,p)=>{if(b.method!=="POST")throw new a("Shard-traffic endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});if(!n(b))throw new a("Admin auth required",{code:"FORBIDDEN",status:403});if(!s)throw new a("Shard-traffic endpoint requires a `queryCoordinator` on the worker",{code:"BAD_REQUEST",status:400});const m=await Un(b),{headers:_}=await d(b,p),R=await s.orchestrateShardTraffic(c,{headers:_,table:m.table});return Response.json(R,{headers:{"content-type":"application/json"},status:200})},g=async(b,p)=>{if(b.method!=="POST")throw new a("PITR endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});if(!n(b))throw new a("admin PITR endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403});const m=await qn(b),{headers:_}=await d(b,p),R=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:m.args,functionPath:m.functionPath}),headers:_,method:"POST"});return r(c,m.shardKey??t,R)};return{[En]:l,[Tn]:g,[_n]:y,[Rn]:E,[Sn]:D}},xn=1,Ln=0,Bn=32,Cn=512,jn=/^[a-z][\d_a-z*/-]{0,255}(?:@[a-z][\d_a-z*/-]{0,13})?=[\u0020-\u002B\u002D-\u003C\u003E-\u007E]{1,256}$/,Gn=e=>{if(e==null)return;const t=e.trim();if(t.length===0||t.length>Cn)return;const r=t.split(",");if(!(r.length>Bn)){for(const n of r)if(!jn.test(n.trim()))return;return t}},Mn=e=>{const t=ir(e.headers.get("traceparent"));if(t===void 0)return;const r=Gn(e.headers.get("tracestate"));return{parentSpanId:t.parentSpanId,sampled:t.sampled,traceId:t.traceId,...r===void 0?{}:{traceState:r}}},Kn=(e,t={})=>{const r=Mn(e),n=t.trustInbound===!0?r:void 0,s=Re(8),d=n?.traceId??Re(16),c=gr(t.sampling,n===void 0?s:d),l=c.isTraced&&(n===void 0||n.sampled);return{decision:c,ignoredUpstream:r!==void 0&&n===void 0,trace:{sampled:l,spanId:s,traceFlags:l?xn:Ln,traceId:d,...n?.parentSpanId===void 0?{}:{parentSpanId:n.parentSpanId},...n?.traceState===void 0?{}:{traceState:n.traceState}}}},Fn=(e,t)=>{t.traceparent=sr(e.traceId,e.spanId,e.sampled),e.traceState!==void 0&&(t.tracestate=e.traceState)},Qn=(e,t)=>{let r;return()=>{if(r===void 0){const n=lr(e),s=t===void 0?void 0:t.cf;r=dr(cr(n),ur(n,s))}return r}},zn="/_lunora/admin/scheduled",Wn="/_lunora/admin/scheduled/status",Hn="/_lunora/admin/scheduled/ws",Jn="/_lunora/admin/scheduled/cancel",Vn="/_lunora/admin/scheduled/dead",Yn="/_lunora/admin/scheduled/dead/retry",Xn="/_lunora/admin/scheduled/dead/cancel",Zn=e=>{const{checkWsAdmin:t,requireSchedulerNamespace:r,resolveSchedulerStub:n,schedulerInstanceName:s}=e,d=async g=>{if(g.method!=="GET")throw new a("Scheduled-list endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});return n(g).fetch(new Request("https://scheduler.internal/list",{method:"GET"}))},c=async g=>{if(g.method!=="GET")throw new a("Scheduler-status endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});return n(g).fetch(new Request("https://scheduler.internal/status",{method:"GET"}))},l=async g=>{if(g.headers.get("Upgrade")!=="websocket")throw new a("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});if(!await t(g))throw new a("admin authorization required",{code:"ADMIN_FORBIDDEN",status:403});const b=r();return Se(b,s).fetch(new Request("https://scheduler.internal/ws",{headers:{Upgrade:"websocket"}}))},y=async g=>{if(g.method!=="POST")throw new a("Scheduled-cancel endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const b=n(g),p=await g.json().catch(()=>{});if(typeof p?.id!="string"||p.id==="")throw new a("Scheduled-cancel requires a string `id`",{code:"BAD_REQUEST",status:400});return b.fetch(new Request("https://scheduler.internal/cancel",{body:JSON.stringify({id:p.id}),headers:{"content-type":"application/json"},method:"POST"}))},E=async g=>{if(g.method!=="GET")throw new a("Scheduled dead-letter endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});return n(g).fetch(new Request("https://scheduler.internal/dead",{method:"GET"}))},D=g=>async b=>{if(b.method!=="POST")throw new a("Scheduled dead-letter action requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const p=n(b),m=await b.json().catch(()=>{});if(typeof m?.id!="string"||m.id==="")throw new a("Scheduled dead-letter action requires a string `id`",{code:"BAD_REQUEST",status:400});return p.fetch(new Request(`https://scheduler.internal${g}`,{body:JSON.stringify({id:m.id}),headers:{"content-type":"application/json"},method:"POST"}))};return{[Jn]:y,[Xn]:D("/dead/cancel"),[Vn]:E,[Yn]:D("/dead/retry"),[zn]:d,[Wn]:c,[Hn]:l}},eo="/_lunora/admin/storage",to="/_lunora/admin/storage/url",ro="/_lunora/admin/storage/buckets",no=10080*60,oo=e=>{const{assertAdmin:t,parsePaging:r,queryParameter:n,readBodyBytes:s,requireAdminOption:d,storage:c}=e,l=m=>{const _=n(m,"key");if(_===void 0)throw new a("Storage endpoint requires a `key` query parameter",{code:"BAD_REQUEST",status:400});return _},y=async m=>{const _=d(m,c.storageList,{code:"STORAGE_NOT_CONFIGURED",message:"storage endpoint requires a `storageList` function on the worker"}),R=new URL(m.url),P=await _(n(R,"prefix"),{bucket:n(R,"bucket"),cursor:n(R,"cursor"),...r(m)});return Response.json(P,{headers:{"content-type":"application/json"},status:200})},E=m=>{if(m.method!=="GET")throw new a("Storage-buckets endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});return t(m),Response.json({buckets:c.storageBuckets??[]},{headers:{"content-type":"application/json"},status:200})},D=async m=>{const _=d(m,c.storageDelete,{code:"STORAGE_DELETE_NOT_CONFIGURED",message:"storage delete requires a `storageDelete` function on the worker"}),R=new URL(m.url),P=l(R);return await _(P,{bucket:n(R,"bucket")}),Response.json({deleted:!0,key:P},{headers:{"content-type":"application/json"},status:200})},g=async m=>{const _=d(m,c.storageUpload,{code:"STORAGE_UPLOAD_NOT_CONFIGURED",message:"storage upload requires a `storageUpload` function on the worker"}),R=new URL(m.url),P=l(R),q=await s(m),v=m.headers.get("content-type"),G=v===null||v===""?void 0:v,B=await _(P,q,{bucket:n(R,"bucket"),contentType:G});return Response.json(B,{headers:{"content-type":"application/json"},status:200})},b=async m=>{switch(m.method){case"DELETE":return D(m);case"GET":return y(m);case"POST":case"PUT":return g(m);default:throw new a("Storage endpoint requires GET, PUT, POST, or DELETE",{code:"METHOD_NOT_ALLOWED",status:405})}},p=async m=>{if(m.method!=="GET")throw new a("Storage URL endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});const _=d(m,c.storageSignedUrl,{code:"STORAGE_URL_NOT_CONFIGURED",message:"storage URL endpoint requires a `storageSignedUrl` function on the worker"}),R=new URL(m.url),P=l(R),q=Number(n(R,"expiresIn")??""),v=Number.isFinite(q)&&q>0?Math.min(q,no):void 0,G=await _(P,{bucket:n(R,"bucket"),expiresInSeconds:v});return Response.json({key:P,url:G},{headers:{"content-type":"application/json"},status:200})};return{[ro]:E,[eo]:b,[to]:p}},ao=(e,...t)=>{let r=e.cf;for(const n of t){if(typeof r!="object"||r===null)return;r=r[n]}return typeof r=="string"?r:void 0},so={mtls:e=>ao(e,"tlsClientAuth","certVerified")==="SUCCESS"},io=e=>e===void 0||e===!1?()=>!1:e===!0?()=>!0:typeof e=="function"?e:Object.entries(so).find(([t])=>t===e)?.[1]??(()=>!1),uo=e=>{if(e!==void 0)return()=>{};let t=!1;return()=>{t||(t=!0,console.warn('[lunora] Ignored an inbound `traceparent`, so this request starts a new trace instead of joining the caller\'s. That is the safe default: the header is caller-supplied, and trusting it lets any client choose which trace its spans and logs join. If this worker sits behind a gateway, service mesh, or Cloudflare Access that sets `traceparent` itself, set `trustInboundTraceContext: true` on createWorker() (or `"mtls"` to trust only edge-verified client certificates). Set it to `false` to keep this behaviour and silence this message.'))}},co="/_lunora/admin/vector/indexes",lo="/_lunora/admin/vector/query",ho=e=>{const{readJsonBody:t,requireAdminOption:r}=e,n=async d=>{if(d.method!=="GET")throw new a("Vector-indexes endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});const c=r(d,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});return Response.json({indexes:await c.listIndexes()},{headers:{"content-type":"application/json"},status:200})},s=async d=>{if(d.method!=="POST")throw new a("Vector-query endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const c=r(d,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});if(c.queryIndex===void 0)throw new a("vector index querying is not enabled on this worker",{code:"VECTOR_QUERY_UNSUPPORTED",status:400});const l=await t(d);if(typeof l.name!="string"||l.name==="")throw new a("Vector-query request requires a `name` string",{code:"BAD_REQUEST",status:400});if(typeof l.text!="string"||l.text==="")throw new a("Vector-query request requires a `text` string",{code:"BAD_REQUEST",status:400});if(l.topK!==void 0&&(typeof l.topK!="number"||!Number.isInteger(l.topK)||l.topK<1))throw new a("Vector-query `topK` must be a positive integer",{code:"BAD_REQUEST",status:400});const y=await c.queryIndex({name:l.name,text:l.text,topK:l.topK});return Response.json(y,{headers:{"content-type":"application/json"},status:200})};return{[co]:n,[lo]:s}},po="/_lunora/admin/workflows/instances",fo="/_lunora/admin/workflows/instance",wo="/_lunora/admin/workflows/status",mo={complete:!0,errored:!0,paused:!0,queued:!0,running:!0,terminated:!0,unknown:!0,waiting:!0,waitingForPause:!0},yo=e=>e!==null&&Object.hasOwn(mo,e)?e:void 0,dt=(e,t)=>{const r=e.searchParams.get(t);if(r===null)return;const n=Number(r);return Number.isInteger(n)&&n>0?n:void 0},Be=(e,t)=>{const r=e.searchParams.get(t);if(r===null||r==="")throw new a(`Workflows admin endpoint requires a \`${t}\` query parameter`,{code:"BAD_REQUEST",status:400});return r},ut=()=>{throw new a("Workflow inspection is unconfigured. Set CLOUDFLARE_ACCOUNT_ID + CLOUDFLARE_API_TOKEN in your .dev.vars to enable it.",{code:"WORKFLOWS_NOT_CONFIGURED",status:501})},go=e=>{const{assertAdmin:t,resolveWorkflowsClient:r}=e,n=async(c,l,y)=>{if(c.method!=="GET")throw new a("Workflows instances endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});t(c);const E=r(l);if(!E)return Response.json({configured:!1,instances:[],page:1,perPage:0,totalCount:0});const D=Be(y,"name"),g=yo(y.searchParams.get("status"));return Response.json(await E.listInstances({page:dt(y,"page"),perPage:dt(y,"perPage"),status:g,workflowName:D}))},s=async(c,l,y)=>{if(c.method!=="GET")throw new a("Workflows instance endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});t(c);const E=r(l);return E?Response.json(await E.getInstance({instanceId:Be(y,"id"),workflowName:Be(y,"name")})):ut()},d=async(c,l)=>{if(c.method!=="POST")throw new a("Workflows status endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});t(c);const y=r(l);if(!y)return ut();const E=await c.json().catch(()=>{});if(typeof E?.name!="string"||E.name===""||typeof E.id!="string"||E.id==="")throw new a("Workflows status action requires string `name` and `id`",{code:"BAD_REQUEST",status:400});const{action:D}=E;if(D!=="pause"&&D!=="resume"&&D!=="terminate")throw new a("Workflows status action must be one of: pause, resume, terminate",{code:"BAD_REQUEST",status:400});return Response.json(await y.setInstanceStatus({action:D,instanceId:E.id,workflowName:E.name}))};return{[fo]:s,[po]:n,[wo]:d}},bo=new TextEncoder,ct="/_lunora/rpc",Oo="/_lunora/rpc-batch",Eo="/_lunora/ws",Ee=(e,t,r)=>({resourceAttributes:Qn(e,t),...r===void 0?{}:{waitUntil:r}}),lt=e=>e?.waitUntil?{waitUntil:t=>e.waitUntil?.(t)}:{},ht=e=>({spanId:e.spanId,traceFlags:e.traceFlags,traceId:e.traceId,...e.parentSpanId===void 0?{}:{parentSpanId:e.parentSpanId}}),Ce=e=>{const{method:t}=e,r=e.headers.get("user-agent")??void 0;let n;try{n=new URL(e.url)}catch{return{method:t,userAgent:r}}const s=n.port===""?void 0:Number(n.port);return{host:n.hostname,method:t,path:n.pathname,port:Number.isNaN(s)?void 0:s,scheme:n.protocol.replace(":",""),userAgent:r}},pt="/_lunora/voice/",To="/_lunora/scheduler/dispatch",_o="/_lunora/admin/cron-jobs/run",Ro="/_lunora/admin/ws-token",So="/_lunora/admin/",Ao="/_lunora/migrate",vo="/_lunora/status",Do=e=>e.startsWith(So)||e===Ao,ko=new Set(["1","enabled","on","true","yes"]),Io=e=>{const t=e.headers.get("x-lunora-userid"),r=e.headers.get("x-lunora-identity");if(!(t===null&&r===null))return{...r===null?{}:{identity:r},...t===null?{}:{userId:t}}},Po="/api/auth",No="__lunora_admin__:recordAuthEvent",Uo="__lunora_admin__:listPushSubscriptions",qo=["/sign-in","/sign-up","/callback"],$o=(e,t)=>{const r=t.endsWith("/")?t.slice(0,-1):t;if(!e.startsWith(`${r}/`))return!1;const n=e.slice(r.length);return qo.some(s=>n===s||n.startsWith(`${s}/`))},Te=(e,t,r,n)=>{const s=nr(r),d=s?r.code:"INTERNAL_SERVER_ERROR",c=s?r.status:500,l=r instanceof Error?r.message:String(r);return{durationMs:t,error:{code:d,message:l,status:c},functionPath:e,ok:!1,...n.fanOut?{fanOut:{failed:0,shards:0,table:n.fanOut.table}}:{},...n.shardKey?{shardKey:n.shardKey}:{}}},xo=e=>{const{exp:t,expiresAtMs:r}=e;if(typeof r=="number"&&Number.isFinite(r))return r;if(typeof t=="number"&&Number.isFinite(t))return t*1e3},ft=e=>e.waitUntil?{waitUntil:t=>{e.waitUntil?.(t)}}:void 0,Lo=e=>{const t=e?.queue;return typeof t=="string"&&t.length>0?t:"unknown"},ce=async(e,t,r)=>{const n={"content-type":"application/json"},s=e.headers.get("authorization"),d=e.headers.get("cookie"),c=e.headers.get("x-d1-bookmark"),l=e.headers.get("x-lunora-mutation-id"),y=e.headers.get("x-lunora-client-id"),E=e.headers.get("x-lunora-client-seq");s&&(n.authorization=s),d&&(n.cookie=d),c&&(n["x-d1-bookmark"]=c),l&&(n["x-lunora-mutation-id"]=l),y&&(n["x-lunora-client-id"]=y),E&&(n["x-lunora-client-seq"]=E);const D=e.headers.get("cf-connecting-ip");if(D&&(n["x-lunora-client-ip"]=D),!r)return{claims:null,headers:n,identity:null,userId:null};const g=await r(e,t);if(!g||typeof g.userId!="string"||g.userId.length===0)return{claims:null,headers:n,identity:null,userId:null};n["x-lunora-userid"]=g.userId;const b=xo(g);b!==void 0&&(n["x-lunora-identity-exp"]=String(b));const{userId:p,...m}=g,_=Object.keys(m).length>0?m:null;return _&&(n["x-lunora-identity"]=JSON.stringify(_)),{claims:_,headers:n,identity:g,userId:p}},Bo=new Set(["concat","first","groupBy","max","min","rank","sum","topK"]),Co=e=>{if(e===void 0)return;if(!e||typeof e!="object")throw new a("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 a("RPC `fanOut.table` must be a non-empty string",{code:"BAD_REQUEST",status:400});if(!t.merge||typeof t.merge!="object")throw new a("RPC `fanOut.merge` must be an object",{code:"BAD_REQUEST",status:400});const r=t.merge;if(typeof r.kind!="string"||!Bo.has(r.kind))throw new a("RPC `fanOut.merge.kind` is not a recognized merge strategy",{code:"BAD_REQUEST",status:400});if(r.kind==="topK"){if(typeof r.k!="number"||!Number.isInteger(r.k)||r.k<0)throw new a("RPC `fanOut.merge.k` must be a non-negative integer",{code:"BAD_REQUEST",status:400});if(typeof r.by!="string"||r.by.length===0)throw new a("RPC `fanOut.merge.by` must be a non-empty string",{code:"BAD_REQUEST",status:400})}return t},jo=(e,t)=>{e?.LUNORA_DEBUG_RPC&&console.warn(`[lunora:rpc] ${t.fanOut?"fan-out":`shard=${t.shardKey??"(root)"}`} ${t.functionPath}`)},wt=(e,t)=>{const r=t.functions?.[e.functionPath]?.x402;if(r){if(e.fanOut)throw new a("a paid (`.x402`) function cannot be fanned out",{code:"BAD_REQUEST",status:400});if(!t.x402Charge)throw new a(`function "${e.functionPath}" is marked paid (.x402) but no x402Charge gate is configured on the worker`,{code:"MISCONFIGURED",status:500});return r}},Go=async e=>{const t=await se(e);let r;try{r=JSON.parse(t)}catch{throw new a("RPC body must be valid JSON",{code:"BAD_REQUEST",status:400})}if(!r||typeof r!="object"||typeof r.functionPath!="string")throw new a("RPC envelope is missing `functionPath`",{code:"BAD_REQUEST",status:400});const n=r;if(n.args!==void 0&&(typeof n.args!="object"||n.args===null||Array.isArray(n.args)))throw new a("RPC `args` must be an object",{code:"BAD_REQUEST",status:400});if(n.shardKey!==void 0&&typeof n.shardKey!="string")throw new a("RPC `shardKey` must be a string",{code:"BAD_REQUEST",status:400});const s=r,d=Co(s.fanOut),c=s.args??{};if(d&&s.functionPath.startsWith("__lunora_relation__:")){const l=c.table;if(typeof l=="string"&&l!==d.table)throw new a("RPC `args.table` must match the authorized `fanOut.table` for a relation fan-out",{code:"BAD_REQUEST",status:400});c.table=d.table}return{args:c,fanOut:d,functionPath:s.functionPath,shardKey:s.shardKey}},ae=async(e,t,r)=>Se(e,t).fetch(r),_e=new Map,Mo=5e3,Ko=4096,Fo=async(e,t)=>{const r=Date.now(),n=_e.get(t);if(n!==void 0&&n.expiresMs>r)return n.relayCount;n!==void 0&&_e.delete(t);let s=0;try{const d=await Se(e,t).fetch(new Request("https://shard.internal/_lunora/route"));if(d.ok){const c=(await d.json()).relayCount;typeof c=="number"&&c>0&&(s=Math.floor(c))}}catch{s=0}return yt(_e,Ko),_e.set(t,{expiresMs:r+Mo,relayCount:s}),s},Qo=(e,t)=>{if(!(e===null||typeof e!="object")){for(const[r,n]of Object.entries(e))if(n===t)return r}},Ge=(e,t)=>{const r=Math.max(e.length,t.length);let n=e.length^t.length;for(let s=0;s<r;s+=1){const d=s<e.length?e.codePointAt(s)??0:0,c=s<t.length?t.codePointAt(s)??0:0;n|=d^c}return n===0},zo=async(e,t,r)=>{if(e.length===0||r.length===0)return!1;const n=new TextEncoder,s=await crypto.subtle.importKey("raw",n.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign"]),d=await crypto.subtle.sign("HMAC",s,n.encode(t)),c=new Uint8Array(d);let l="";for(const E of c)l+=String.fromCodePoint(E);const y=btoa(l).replaceAll("+","-").replaceAll("/","_").replaceAll("=","");return Ge(y,r)},mt=(e,t)=>{if(!t||t.length===0)return!1;const r=e.headers.get("authorization");if(!r)return!1;const[n,...s]=r.split(" ");return n?.toLowerCase()!=="bearer"?!1:Ge(t,s.join(" ").trim())},Wo=async(e,t,r)=>{if(!t||t.length===0)return!1;const n=new URL(e.url).searchParams.get("token");return n===null?!1:await Pr(t,n)?!0:r?!1:Ge(t,n)},Ho=(e,t)=>{if(t===null||typeof t!="object"&&typeof t!="function")return;const r=t;if(typeof r.prepare=="function"&&typeof r.batch=="function"&&typeof r.dump=="function")return wr(`d1:${e}`,t);if(typeof r.list=="function"&&typeof r.head=="function"&&typeof r.createMultipartUpload=="function")return Ne(`r2:${e}`,!0);if(typeof r.send=="function"&&typeof r.sendBatch=="function"&&typeof r.get!="function")return Ne(`queue:${e}`,!0);if(typeof r.connectionString=="string")return Ne(`hyperdrive:${e}`,!0)},_t=e=>{const t=io(e.trustInboundTraceContext),r=uo(e.trustInboundTraceContext),n=e.defaultShardKey??"__root__",s=mr(e.resolveIdentity,e.identity),d=Je(e.shardDO,e.jurisdiction),c=e.schedulerDO===void 0?void 0:Je(e.schedulerDO,e.jurisdiction);let l;const y=()=>e.adminToken??l;let E;const D=()=>e.requireEphemeralWsToken??E??!1,g=o=>{const i=o??{};if(E===void 0&&e.requireEphemeralWsToken===void 0){const u=i.LUNORA_REQUIRE_EPHEMERAL_WS_TOKEN;typeof u=="string"&&u.length>0&&(E=ko.has(u.trim().toLowerCase()))}if(l!==void 0||e.adminToken!==void 0)return;const h=i.LUNORA_ADMIN_TOKEN;typeof h=="string"&&h.length>0&&(l=h)},b=new WeakSet,p=o=>mt(o,y())||b.has(o),m=async(o,i)=>{const h=await ce(o,i,e.resolveIdentity);if(b.has(o)&&h.headers.authorization===void 0){const u=y();u!==void 0&&(h.headers.authorization=`Bearer ${u}`)}return h};let _=!1;const R=o=>{if(!e.allowUnauthenticatedShardAccess){const i=o==="fan-out"?"authorizeFanOut":"authorizeShard";throw new a(`${o} access is default-denied: configure \`${i}\` 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})}_||(_=!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("")))},P=$n({defaultShard:n,forwardToShard:ae,isAdmin:p,queryCoordinator:e.queryCoordinator,resolveForwardContext:m,shardDO:d}),q=async(o,i,h,u,f)=>{if(e.authorizeShard&&!await e.authorizeShard(null,h))throw new a("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403});const O={"content-type":"application/json","x-lunora-system":"1"};f?.userId!==void 0&&f.userId.length>0&&(O["x-lunora-userid"]=f.userId),f?.identity!==void 0&&f.identity.length>0&&(O["x-lunora-identity"]=f.identity),u!==void 0&&u.length>0&&(O["x-lunora-mutation-id"]=u);const S=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:i,functionPath:o}),headers:O,method:"POST"});return ae(d,h,S)},v=async(o,i,h,u)=>{const f=h?.[o];if(!f||typeof f.create!="function")throw new a(`${u} targets workflow binding "${o}", which is not bound on env`,{code:"CRON_JOB_FAILED",status:500});await f.create({params:i})},G=async(o,i,h)=>v(o,i.args??{},h,`cron job "${i.name}"`),B=async(o,i)=>{if(o.workflow){await G(o.workflow,o,i);return}if(o.functionPath===void 0)throw new a(`cron job "${o.name}" has neither a function target nor a workflow target`,{code:"CRON_JOB_FAILED",status:500});const h=await q(o.functionPath,o.args??{},o.shardKey??n);if(!h.ok)throw new a(`cron job "${o.name}" (${o.functionPath}) failed with shard status ${String(h.status)}`,{code:"CRON_JOB_FAILED",status:500})},Y=async(o,i,h,u)=>{const f=e.cronJobs?.[o];if(f)for(const O of f)try{await B(O,i)}catch(S){h.push(u(S))}},N=async(o,i)=>{if(!p(o))throw new a("admin endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403});if(o.method!=="POST")throw new a("cron-jobs run endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});if(!e.cronJobs)throw new a("cron-jobs run endpoint requires a `cronJobs` map on the worker",{code:"CRON_JOBS_NOT_CONFIGURED",status:400});const h=await te(o),u=typeof h.name=="string"?h.name:"";if(u==="")throw new a("cron-jobs run endpoint requires a job `name`",{code:"BAD_REQUEST",status:400});const f=Object.values(e.cronJobs).flat().find(O=>O.name===u);if(!f)throw new a(`no cron job named "${u}" is registered`,{code:"CRON_JOB_NOT_FOUND",status:404});return await B(f,i),Response.json({name:u,ran:!0},{status:200})},K=async o=>{const i=typeof o.pool=="string"&&o.pool.length>0?o.pool:void 0;if(!i||!c||typeof o.id!="string")return;const h=typeof o.instanceName=="string"&&o.instanceName.length>0?o.instanceName:"default";try{await c.get(c.idFromName(h)).fetch(new Request("https://scheduler.internal/complete",{body:JSON.stringify({id:o.id,pool:i}),headers:{"content-type":"application/json"},method:"POST"}))}catch{}},F=async(o,i)=>{if(o.method!=="POST")throw new a("Scheduler dispatch endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const h=await se(o),u=i??{},f=typeof u.LUNORA_SCHEDULER_SECRET=="string"?u.LUNORA_SCHEDULER_SECRET:void 0,O=e.adminToken??(typeof u.LUNORA_ADMIN_TOKEN=="string"?u.LUNORA_ADMIN_TOKEN:void 0),S=o.headers.get("x-lunora-scheduler-signature");let w=!1;if(S&&f?w=await zo(f,h,S):O&&(w=mt(o,O)),!w)throw new a("Scheduler dispatch requires a valid signature or admin bearer",{code:"FORBIDDEN",status:403});let T;try{T=JSON.parse(h)}catch{throw new a("Scheduler dispatch body must be valid JSON",{code:"BAD_REQUEST",status:400})}const A=T??{},U=A.args??{};if(typeof A.workflow=="string"&&A.workflow.length>0)return await v(A.workflow,U,i,"scheduled workflow"),Response.json({ok:!0},{status:200});if(typeof A.functionPath!="string"||A.functionPath.length===0)throw new a("Scheduler dispatch is missing `functionPath`",{code:"BAD_REQUEST",status:400});const $=typeof A.shardKey=="string"&&A.shardKey.length>0?A.shardKey:n,x=typeof A.id=="string"&&A.id.length>0?A.id:void 0,L=Io(o),W=await q(A.functionPath,U,$,x,L);return await K(A),W},C=o=>{if(!p(o))throw new a("admin endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403})},M=(o,i,h)=>{if(C(o),i===void 0)throw new a(h.message,{code:h.code,status:400});return i},X=xr({assertAdmin:C,getReader:()=>e.authAuditReader}),J=async(o,i)=>{C(o);const h=e.notifySubscriptionStore;if(h===void 0)return Response.json({subscriptions:[]},{headers:{"content-type":"application/json"},status:200});const u=i?.kind,f=i?.userId,O=i?.limit,S=u==="fcm"||u==="web-push"?u:void 0,w=typeof f=="string"&&f!==""?f:void 0,T=typeof O=="number"&&Number.isFinite(O)?Math.trunc(O):0,A=T>0?Math.min(T,1e3):1e3,U=(await h.list({kind:S,limit:A,userId:w})).filter($=>S!==void 0&&$.kind!==S?!1:w===void 0||($.userId??null)===w).map(({keys:$,token:x,...L})=>L);return Response.json({subscriptions:U},{headers:{"content-type":"application/json"},status:200})},oe=async(o,i)=>{if(!i.fanOut){if(i.functionPath===$r)return X(o,i.args??{});if(i.functionPath===Uo)return J(o,i.args)}},ie=Xr({applyGlobals:e.applyGlobals,assertAdmin:C,exportCursorStore:e.exportCursorStore,exportSinks:e.exportSinks,knownTables:()=>Ot(),queryCoordinator:e.queryCoordinator,requireAdminOption:M,resolveForwardContext:m,shardDO:d,streamExportRows:(o,i,h,u)=>ot(e,o,i,h,u,d),streamingImport:(o,i)=>on(o,e,i,d),syncGlobals:e.syncGlobals}),Z=(o,i)=>{const h=o.searchParams.get(i);return h===null||h===""?void 0:h},pe=o=>{const i=new URL(o.url),h=i.searchParams.get("limit"),u=i.searchParams.get("offset"),f=h===null?void 0:Number.parseInt(h,10),O=u===null?void 0:Number.parseInt(u,10);return{limit:f!==void 0&&Number.isFinite(f)&&f>=0?f:void 0,offset:O!==void 0&&Number.isFinite(O)&&O>=0?O:void 0}},be=()=>{if(c===void 0)throw new a("scheduled endpoints require a `schedulerDO` namespace on the worker",{code:"SCHEDULER_NOT_CONFIGURED",status:400});return c},Ae=Zn({checkWsAdmin:async o=>p(o)||Wo(o,y(),D()),requireSchedulerNamespace:be,resolveSchedulerStub:o=>(C(o),Se(be(),e.schedulerInstanceName??"default")),schedulerInstanceName:e.schedulerInstanceName??"default"}),re=go({assertAdmin:C,resolveWorkflowsClient:e.workflowsClient??(()=>{})}),Rt=oo({assertAdmin:C,parsePaging:pe,queryParameter:Z,readBodyBytes:Cr,requireAdminOption:M,storage:{storageBuckets:e.storageBuckets,storageDelete:e.storageDelete,storageList:e.storageList,storageSignedUrl:e.storageSignedUrl,storageUpload:e.storageUpload}}),St=ho({readJsonBody:te,requireAdminOption:M,vectorIntrospector:e.vectorIntrospector}),At=On({kvIntrospector:e.kvIntrospector,readJsonBody:te,requireAdminOption:M}),vt=yr({logArchive:e.logArchive,readJsonBody:te,requireAdminOption:M}),Dt=yn({assertAdmin:C,options:{cronJobs:e.cronJobs,functions:e.functions,globalIntrospector:e.globalIntrospector,openApiSpec:e.openApiSpec,openRpcSpec:e.openRpcSpec},parsePaging:pe,queryParameter:Z,requireAdminOption:M}),kt=o=>{const i=[],h=d??o?.SHARD;if(h!==void 0&&i.push(fr("durable-object:default",h,n)),e.health?.disableBindingProbes!==!0)for(const[u,f]of Object.entries(o??{})){const O=Ho(u,f);O!==void 0&&i.push(O)}for(const u of e.health?.probes??[])i.push(u);return i},It=pr({appName:e.health?.appName,appVersion:e.health?.appVersion,auth:e.health?.auth??"public",cacheTtlMs:e.health?.cacheTtlMs,isAdmin:p,resolveProbes:kt}),Pt=o=>{const i=e.schedulerInstanceName??"default",h=()=>o.get(o.idFromName(i)),u=async(w,T)=>{const A=await h().fetch(new Request(`https://scheduler.internal${w}`,T));if(!A.ok)throw new a(`ctx.scheduler: SchedulerDO ${w} failed (${String(A.status)}): ${await A.text()}`,{code:"INTERNAL",status:500});return await A.json()},f=async(w,T)=>await u(w,{body:JSON.stringify(T),headers:{"content-type":"application/json"},method:"POST"}),O=w=>{const T=w;if(T==null)throw new a("ctx.scheduler: target is required — pass a reference from the generated `internal` / `workflows` / `agents`",{code:"BAD_REQUEST",status:400});if(typeof T.binding=="string"&&T.binding.length>0)return{workflow:T.binding};if(typeof T.__lunoraRef=="string")return{functionPath:T.__lunoraRef};throw new a("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})},S=async(w,T,A={})=>{const{id:U}=await f("/schedule",{args:A,scheduledFor:w,...O(T)});return U};return{cancel:async w=>await f("/cancel",{id:w}),get:async w=>await u(`/get?id=${encodeURIComponent(w)}`,{method:"GET"}),list:async()=>await u("/list",{method:"GET"}),runAfter:async(w,T,A)=>{if(!Number.isFinite(w)||w<0)throw new a("ctx.scheduler.runAfter: `delayMs` must be a non-negative finite number",{code:"BAD_REQUEST",status:400});return await S(Date.now()+w,T,A)},runAt:async(w,T,A)=>{if(!Number.isFinite(w))throw new a("ctx.scheduler.runAt: `timestampMs` must be a finite epoch-millisecond number",{code:"BAD_REQUEST",status:400});return await S(w,T,A)}}},Nt=async(o,i,h)=>{const{claims:u,headers:f,userId:O}=await ce(o,i,s),S=async(w,T={})=>{const A=w.__lunoraRef;if(typeof A!="string")throw new a("ctx.run*: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});const U=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:T,functionPath:A}),headers:{...f,"x-lunora-system":"1"},method:"POST"}),$=await ae(d,n,U),x=await $.json();if(x.error)throw new a(x.error.message??"shard RPC failed",{code:x.error.code??"INTERNAL",status:$.status});return x.result};return{auth:{getIdentity:()=>Promise.resolve(u),userId:O},cache:h.cache,fetch:globalThis.fetch.bind(globalThis),runAction:S,runMutation:S,runQuery:S,...c===void 0?{}:{scheduler:Pt(c)}}},Ut=async(o,i,h)=>{if(!e.httpRouter)return;const u=await Nt(o,i,h);try{return await e.httpRouter.fetch(o,{...i,__lunoraCtx:u},h)}catch(f){return console.error("[lunora] httpRouter (SSR) handler threw:",f),new Response("Internal Server Error",{status:500})}},qt=async(o,i,h)=>{if(o.headers.get("Upgrade")!=="websocket")throw new a("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});const u=Ye(o,de);if(u)return u;const f=h.searchParams.get("shard")??n,{headers:O,identity:S}=await ce(o,i,s);if(e.authorizeShard){if(!await e.authorizeShard(S,f))throw new a("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else f!==n&&R("shard");const w=new Headers(o.headers),T=[...w.keys()];for(const L of T)L.startsWith("x-lunora-")&&w.delete(L);const A=O["x-lunora-userid"],U=O["x-lunora-identity"],$=O["x-lunora-identity-exp"];A!==void 0&&w.set("x-lunora-userid",A),U!==void 0&&w.set("x-lunora-identity",U),$!==void 0&&w.set("x-lunora-identity-exp",$);const x=Qo(i,e.shardDO);if(x!==void 0){w.set("x-lunora-shard-binding",x);const L=await Fo(d,f);if(L>0){const W=_r(f,Math.floor(Math.random()*L));return ae(d,W,new Request(o,{headers:w}))}}return ae(d,f,new Request(o,{headers:w}))},$t=async(o,i,h)=>{const{voiceAgents:u}=e;if(u===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 f=Ye(o,de);if(f)return f;let O;try{O=decodeURIComponent(h.pathname.slice(pt.length))}catch{return new Response("Unknown voice agent",{status:404})}const S=Object.hasOwn(u,O)?u[O]:void 0;if(S===void 0)return new Response("Unknown voice agent",{status:404});const w=h.searchParams.get("threadKey");if(w===null||w.length===0)return new Response("Missing threadKey",{status:400});const{headers:T,identity:A}=await ce(o,i,s);if(e.authorizeShard){if(!await e.authorizeShard(A,w))return new Response("Forbidden",{status:403})}else R("shard");const U=new Headers(o.headers);U.delete("x-lunora-userid"),U.delete("x-lunora-identity"),U.delete("x-lunora-identity-exp");const $=T["x-lunora-userid"],x=T["x-lunora-identity"],L=T["x-lunora-identity-exp"];return $!==void 0&&U.set("x-lunora-userid",$),x!==void 0&&U.set("x-lunora-identity",x),L!==void 0&&U.set("x-lunora-identity-exp",L),ae(S,w,new Request(o,{headers:U}))},xt=async(o,i,h)=>{if(e.authorizeFanOut){if(!await e.authorizeFanOut(h,o.table,i))throw new a("Forbidden fan-out",{code:"FORBIDDEN_FANOUT",status:403});return}if(i.startsWith("__lunora_relation__:"))throw new a("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 a("Fan-out requires `authorizeFanOut` to be configured on the worker when `authorizeShard` is set",{code:"FORBIDDEN_FANOUT",status:403});R("fan-out")},Oe=async(o,i)=>{if(!(!o.fanOut&&o.functionPath.startsWith("__lunora_admin__:"))){if(o.fanOut){await xt(o.fanOut,o.functionPath,i);return}if(e.authorizeShard){const h=o.shardKey??n;if(!await e.authorizeShard(i,h))throw new a("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else o.shardKey!==void 0&&o.shardKey!==n&&R("shard")}},ve=async(o,i,h,u,f,O)=>{const S=Date.now(),{observability:w,sampling:T}=e,A=Ce(o),{decision:U,ignoredUpstream:$,trace:x}=Kn(o,{...T===void 0?{}:{sampling:T},trustInbound:t(o)});$&&r();const L={...f,"x-lunora-sample-errors":U.keepErrors?"1":"0"};Fn(x,L);const W=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:h,functionPath:i}),headers:L,method:"POST"});try{const j=await ae(d,u,W);return ue(w,{...A,...ht(x),durationMs:Date.now()-S,functionPath:i,ok:j.ok,shardKey:u,...j.ok?{}:{error:{code:"SHARD_ERROR",message:`shard returned ${String(j.status)}`,status:j.status}}},O,void 0,{isTraced:x.sampled,keepErrors:U.keepErrors}),j}catch(j){throw ue(w,{...A,...ht(x),...Te(i,Date.now()-S,j,{shardKey:u})},O,void 0,{isTraced:x.sampled,keepErrors:U.keepErrors}),j}},Lt=o=>{if(o.fanOut&&o.shardKey)throw new a("RPC envelope cannot set both `shardKey` and `fanOut`",{code:"BAD_REQUEST",status:400});if(!o.fanOut&&o.functionPath.startsWith("__lunora_relation__:"))throw new a("`__lunora_relation__:*` is a fan-out-only reserved RPC and cannot be dispatched to a single shard",{code:"FORBIDDEN",status:403});if(o.fanOut&&!e.queryCoordinator)throw new a("RPC envelope set `fanOut` but no `queryCoordinator` is configured on the worker",{code:"BAD_REQUEST",status:400})},Bt=async(o,i,h)=>{if(o.method!=="POST")throw new a("RPC endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const u=await Go(o);jo(i,u),Lt(u);const f=await oe(o,u);if(f!==void 0)return f;const{headers:O,identity:S}=await ce(o,i,s);await Oe(u,S);const w=wt(u,e);{const T=Date.now(),{observability:A}=e,U=Ce(o),$=Ee(i,o,h&&(W=>h.waitUntil?.(W)));if(u.fanOut){const W=e.queryCoordinator;if(!W)throw new a("RPC envelope set `fanOut` but no `queryCoordinator` is configured on the worker",{code:"BAD_REQUEST",status:400});try{const j=await W.fanOut(d,{args:u.args??{},fanOut:u.fanOut,functionPath:u.functionPath,headers:O});return ue(A,{durationMs:Date.now()-T,fanOut:{failed:j.failed,shards:j.ok+j.failed,table:u.fanOut.table},functionPath:u.functionPath,...U,ok:!0},$),Response.json(j,{headers:{"content-type":"application/json"},status:200})}catch(j){throw ue(A,{...Te(u.functionPath,Date.now()-T,j,{fanOut:{table:u.fanOut.table}}),...U},$),j}}const x=u.shardKey??n,L=()=>ve(o,u.functionPath,u.args??{},x,O,$);return w&&e.x402Charge?e.x402Charge(o,{functionPath:u.functionPath,price:w.price},L,lt(h)):L()}},Ct=async(o,i,h)=>{if(o.method!=="POST")throw new a("RPC batch endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const u=await se(o);let f;try{f=JSON.parse(u)}catch{throw new a("RPC batch body must be valid JSON",{code:"BAD_REQUEST",status:400})}if(typeof f!="object"||f===null||Array.isArray(f))throw new a("RPC batch body must be an object",{code:"BAD_REQUEST",status:400});const{calls:O}=f;if(!Array.isArray(O))throw new a("RPC batch `calls` must be an array",{code:"BAD_REQUEST",status:400});const{headers:S,identity:w}=await ce(o,i,s),T=Br(O,n);for(const Q of T.values())for(const z of Q)if(e.functions?.[z.functionPath]?.x402)throw new a(`paid (\`.x402\`) function "${z.functionPath}" cannot be called in a batch; dispatch it individually over ${ct}`,{code:"BAD_REQUEST",status:400});await Promise.all([...T.entries()].flatMap(([Q,z])=>z.map(ne=>Oe({functionPath:ne.functionPath,shardKey:Q},w))));const{observability:A}=e,U=Ee(i,o,h&&(Q=>h.waitUntil?.(Q))),$=Ce(o),x=[],L=[],W=(Q,z,ne,le)=>({body:{error:{code:ne,message:le}},id:Q.id,status:z}),j=(Q,z,ne,le,fe)=>{for(const H of Q)ue(A,fe(H),U),x.push(W(H,z,ne,le))},Zt=(Q,z,ne,le,fe)=>{for(const H of Q){const we=le.get(H.id)??fe,ye=we<400;ue(A,{durationMs:ne,functionPath:H.functionPath,...$,ok:ye,shardKey:z,...ye?{}:{error:{code:"SHARD_ERROR",message:`batched call returned ${String(we)}`,status:we}}},U)}};await Promise.all([...T.entries()].map(async([Q,z])=>{const ne=new Headers(S);ne.set("content-type","application/json");const le=new Request("https://shard.internal/rpc-batch",{body:JSON.stringify({calls:z}),headers:ne,method:"POST"}),fe=Date.now();let H;try{H=await ae(d,Q,le)}catch(V){const Pe=Date.now()-fe,{body:ze}=or(V,{fallbackCode:"SHARD_UNAVAILABLE",redactedMessage:"shard unavailable"});j(z,502,ze.code,ze.message,rr=>({...Te(rr.functionPath,Pe,V,{shardKey:Q}),...$}));return}const we=Date.now()-fe,ye=H.headers.get("x-d1-bookmark");ye&&L.push(ye);let ke;try{ke=await H.json()}catch{const V=`shard batch returned a non-JSON response (${String(H.status)})`;j(z,H.status,"SHARD_ERROR",V,Pe=>({durationMs:we,error:{code:"SHARD_ERROR",message:V,status:H.status},functionPath:Pe.functionPath,...$,ok:!1,shardKey:Q}));return}const Ie=Array.isArray(ke.results)?ke.results:[],er=new Map(Ie.map(V=>[V.id,V.status??H.status])),tr=new Set(Ie.map(V=>V.id));Zt(z,Q,we,er,H.status),x.push(...Ie);for(const V of z)tr.has(V.id)||x.push(W(V,H.status,"SHARD_ERROR",`shard batch omitted result for call ${String(V.id)}`))}));const Fe={"content-type":"application/json"},[Qe]=L;return L.length===1&&Qe!==void 0&&(Fe["x-d1-bookmark"]=Qe),Response.json({results:x},{headers:Fe,status:200})},jt=async(o,i,h,u={},f={})=>{try{const O=h.__lunoraRef;if(typeof O!="string")throw new a("serverQuery: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});const{headers:S,identity:w}=await ce(o,i,s);await Oe({functionPath:O,shardKey:f.shardKey},w);const T=f.shardKey??n,A=Ee(i,o,f.waitUntil);return await ve(o,O,u,T,S,A)}catch(O){return We(O)}},Gt=1e3,Mt=async(o,i)=>{const h=e.backupRetain;if(h===void 0||h<=0)return;const u=[];let f;for(let S=0;S<Gt;S+=1){const w=await o.list({cursor:f,prefix:i});for(const T of w.objects)T.key.endsWith(".manifest.json")&&u.push(T.key);if(!w.truncated||w.cursor===void 0)break;f=w.cursor}const O=u.toSorted((S,w)=>w.localeCompare(S)).slice(h);await Promise.all(O.flatMap(S=>{const w=S.slice(0,-14);return[o.delete(S),o.delete(w)]}))},Kt=async o=>{const i=e.backupStore,h=e.queryCoordinator;if(!i)throw new a("scheduled backup requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});if(!h)throw new a("scheduled backup requires a `queryCoordinator` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});const u=y();if(!u||u.length===0)throw new a("scheduled backup requires an `adminToken` (or `env.LUNORA_ADMIN_TOKEN`) to authenticate the per-shard export gate",{code:"BACKUP_NOT_CONFIGURED",status:500});const f={authorization:`Bearer ${u}`,"content-type":"application/json"},O=e.backupTables;let S=0,w=0;const T=[];await ot(e,h,f,O,W=>{const j=`${JSON.stringify(W)}
|
|
5
|
-
`;S+=1,w+=bo.encode(j).byteLength,T.push(j)},d);const A=e.backupPrefix??"backups/",U=new Date(o.scheduledTime).toISOString(),$=`${A}lunora-backup-${U.replaceAll(/[.:]/gu,"-")}.ndjson`,x=`${$}.manifest.json`;await i.put($,new Blob(T,{type:"application/x-ndjson"}),{httpMetadata:{contentType:"application/x-ndjson"}});const L={bytes:w,createdAt:U,cron:o.cron,file:$,id:U,rows:S,scheduledTime:o.scheduledTime,...O?{tables:O.join(",")}:{}};await i.put(x,`${JSON.stringify(L,void 0,2)}
|
|
6
|
-
`,{httpMetadata:{contentType:"application/json"}}),await Mt(i,A)},Me=async(o,i,h)=>{const{observability:u}=e,f=Date.now(),O=Re(16),S=Re(8),w=ft(i);try{const T=await h();return ue(u,{durationMs:Date.now()-f,functionPath:o,ok:!0,spanId:S,traceId:O},w),T}catch(T){throw ue(u,{...Te(o,Date.now()-f,T,{}),spanId:S,traceId:O},w),T}finally{He(u,w)}},Ft=async(o,i,h)=>{g(i);const u=[],f=w=>w instanceof Error?w:new Error(String(w)),O=e.crons?.[o.cron];if(O)try{await O(o,i,h)}catch(w){u.push(f(w))}if(await Y(o.cron,i,u,f),e.backupStore&&e.backupCron!==void 0&&e.backupCron===o.cron)try{await Kt(o)}catch(w){u.push(f(w))}const[S]=u;if(u.length===1&&S)throw S;if(u.length>1)throw new AggregateError(u,`scheduled("${o.cron}") had ${String(u.length)} failure(s)`)},Qt=async(o,i)=>{try{const h=o??{},u=e.adminToken??(typeof h.LUNORA_ADMIN_TOKEN=="string"?h.LUNORA_ADMIN_TOKEN:void 0);if(!u||u.length===0)return;const f=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:{outcome:i},functionPath:No}),headers:{authorization:`Bearer ${u}`,"content-type":"application/json"},method:"POST"});await ae(d,n,f)}catch{}},zt=async(o,i,h,u)=>{if(!e.authHandler)return;const f=await e.authHandler(o);if(!f)return;const O=e.authBasePath??Po;return $o(h.pathname,O)&&u.waitUntil?.(Qt(i,f.status>=400?"fail":"ok")),f},Wt=async({args:o,env:i,functionPath:h,request:u,shardKey:f,waitUntil:O})=>{const S={functionPath:h,...f===void 0?{}:{shardKey:f}},{headers:w,identity:T}=await ce(u,i,s);await Oe(S,T);const A=f??n,U=Ee(i,u,O),$=()=>ve(u,h,o,A,w,U),x=wt(S,e);return x&&e.x402Charge?e.x402Charge(u,{functionPath:h,price:x.price},$,lt({waitUntil:O})):$()},Ht=br({functions:e.functions??{},invoke:Wt,readJsonBody:te,...e.restRateLimit?{rateLimit:e.restRateLimit}:{}}),De=e.routes!==void 0&&Object.keys(e.routes).length>0?e.routes:void 0,Jt={[vo]: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"}}),[Eo]:(o,i,h)=>qt(o,i,h),[ct]:(o,i,h,u)=>Bt(o,i,u),[Oo]:(o,i,h,u)=>Ct(o,i,u),[To]:(o,i)=>F(o,i),[_o]:(o,i)=>N(o,i),[Ro]:async o=>{if(o.method!=="POST")throw new a("ws-token endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});C(o);const i=y();if(i===void 0)throw new a("ws-token minting requires a configured admin token",{code:"ADMIN_TOKEN_NOT_CONFIGURED",status:400});const h=await Ir(i);return Response.json(h,{headers:{"cache-control":"no-store"}})},...P,...ie,...Ae,...re,...Rt,...St,...At,...vt,...Dt,...It,...Ht,...qr({assertAdmin:C,getAuthAdmin:()=>e.authAdmin,parsePaging:pe,queryParameter:Z,readJsonBody:te})};let de=Ve(e.security),Ke=!1;const Vt=o=>{Ke||(Ke=!0,de=Ve(e.security,o??{}))},Yt=async(o,i)=>{if(!(e.adminGate===void 0||!Do(i)))try{await e.adminGate(o)&&b.add(o)}catch{}},Xt=async(o,i,h)=>{const u=new URL(o.url);if(o.method==="POST"||o.method==="PUT"){const w=Number(o.headers.get("content-length")??""),T=u.pathname===Et?Tt:ge;if(Number.isFinite(w)&&w>T)throw new a("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413})}const f=await zt(o,i,u,h);if(f)return f;if(De){const w=`${o.method} ${u.pathname}`,T=De[w]??De[u.pathname];if(T)return T(o,i,h)}const O=Jt[u.pathname];return O?(await Yt(o,u.pathname),O(o,i,u,h)):e.voiceAgents!==void 0&&u.pathname.startsWith(pt)?$t(o,i,u):await Ut(o,i,h)||new Response("Not found",{status:404})};return{async fetch(o,i,h){e.passThroughOnException&&h.passThroughOnException?.(),Vt(i),g(i);const u=Or(o,de);if(u)return u;const f=Er(o,de);if(f)return Ue(f,o,de);try{const O=await Xt(o,i,h);return Ue(O,o,de)}catch(O){return Ue(We(O),o,de)}finally{He(e.observability,ft(h))}},async queue(o,i,h){await Me(`queue:${Lo(o)}`,h,async()=>{await e.queue?.(o,i,h)})},async scheduled(o,i,h){await Me(`cron:${o.cron}`,h,async()=>{await Ft(o,i,h)})},serverQuery:jt}},Jo=e=>_t(e),Vo=e=>typeof e=="function"?{fetch:e}:e,Yo=e=>!!(e.crons??e.cronJobs??e.backupCron),ha=(e,t)=>{const r=Vo(e),n=typeof e=="object"&&typeof e.scheduled=="function"?e.scheduled:void 0,s=c=>{const l=Jo({...c,httpRouter:r});return n!==void 0&&!Yo(c)?{...l,scheduled:async(y,E,D)=>{await n(y,E,D)}}:l};if(typeof t!="function")return s(t);const d=t;return{fetch:(c,l,y)=>s(d(l)).fetch(c,l,y),queue:(c,l,y)=>s(d(l)).queue?.(c,l,y)??Promise.resolve(),scheduled:(c,l,y)=>s(d(l)).scheduled(c,l,y),serverQuery:(c,l,y,E,D)=>s(d(l)).serverQuery(c,l,y,E,D)}},Xo=(e,t)=>{if(typeof e=="function")return e(t);const r=e.shardDO??t?.SHARD;if(!r)throw new a("@lunora/runtime: no shard Durable Object namespace found. Bind `SHARD` in wrangler.jsonc, or pass `createLunoraHandler({ shardDO: env.MY_SHARD })`.");return{...e,shardDO:r}},pa=(e={})=>(t,r,n)=>_t(Xo(e,r)).fetch(t,r,n??ar),fa=e=>e;export{$r as GET_AUTH_AUDIT_LOG_OP,ar as NOOP_EXECUTION_CONTEXT,ya as composeIdentityResolvers,Jo as composeWorker,pa as createLunoraHandler,_t as createWorker,fa as defineRpcEnvelope,Fo as probeRelayCount,Xo as resolveLunoraOptions,ga as routeIdentityResolvers,ha as withFrameworkWorker};
|