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