@lunora/runtime 1.0.0-alpha.207 → 1.0.0-alpha.209

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 R,toFivetranResponse as x}from"./packem_shared/toAirbyteMessages-DY0vsuEn.mjs";import{composeWorker as l,createLunoraHandler as d,createWorker as u,defineRpcEnvelope as _,resolveLunoraOptions as k,withFrameworkWorker as y}from"./packem_shared/composeWorker-kkJnK_7t.mjs";import{createCrossShardRelationCapabilities as O}from"./packem_shared/createCrossShardRelationCapabilities-BmGOuTrp.mjs";import{DEFAULT_REGISTRY_CACHE_TTL_MS as A,SHARD_REGISTRY_DO_NAME as L,createDynamicShardRegistry as T}from"./packem_shared/DEFAULT_REGISTRY_CACHE_TTL_MS-CdACWUQW.mjs";import{parseStackFrames as H,toError as P}from"./packem_shared/parseStackFrames-CZddjveh.mjs";import{LunoraError as v,toErrorResponse as I}from"./packem_shared/LunoraError-DksAgIpa.mjs";import{c as F,a as M,d as N,r as G,b as K,s as U,w as B}from"./packem_shared/export-tap-C2B_SATf.mjs";import{HEALTH_PATH as w,HEALTH_READY_PATH as z,buildHealthRoutes as X,d1Probe as j,durableObjectProbe as V,presenceProbe as W}from"./packem_shared/HEALTH_PATH-CAX2UeFy.mjs";import{LOG_ARCHIVE_PATH as J,resolveLogArchiveFromEnv as Q}from"./packem_shared/LOG_ARCHIVE_PATH-Hmjpz_Ko.mjs";import{memoizeIdentity as $,memoizeIdentityPerRequest as ee}from"./packem_shared/memoizeIdentity-BNnHkqeF.mjs";import{e as oe,a as te}from"./packem_shared/observability-DgurIZIR.mjs";import{analyticsEngineSink as se,combineSinks as ie,consoleSink as pe,otlpSink as ne,pipelineLogSink as ce,webhookSink as me}from"./packem_shared/analyticsEngineSink-BZB-ZYCP.mjs";import{D as Ee,c as Re}from"./packem_shared/pipeline-log-reader-C-nuWG_e.mjs";import{createQueryCoordinator as Se,createStaticShardRegistry as le}from"./packem_shared/createQueryCoordinator-es4jrL6Q.mjs";import{applyJurisdiction as ue,resolveShard as _e}from"./packem_shared/applyJurisdiction-D4vryLhj.mjs";import{a as ye,r as Ce,b as Oe}from"./packem_shared/rest-cache-CmHN871W.mjs";import{a as Ae,b as Le,c as Te,r as he}from"./packem_shared/rest-routes-DQkyqlym.mjs";import{decorateResponse as Pe,enforceOrigin as ge,handleCorsPreflight as ve,resolveSecurity as Ie}from"./packem_shared/decorateResponse-CRrFNW1v.mjs";import{createShardClient as Fe}from"./packem_shared/createShardClient-DIVRljRz.mjs";import{STORAGE_UPLOAD_MAX_BODY_BYTES as Ne}from"./packem_shared/STORAGE_UPLOAD_MAX_BODY_BYTES-BIiV5kqV.mjs";import{LOG_ARCHIVE_NOT_CONFIGURED as Ke}from"./packem_shared/LOG_ARCHIVE_NOT_CONFIGURED-CDpi4yFD.mjs";import{NOOP_EXECUTION_CONTEXT as Be}from"./packem_shared/NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{composeIdentityResolvers as we,routeIdentityResolvers as ze}from"./packem_shared/composeIdentityResolvers-BHZ4jH8o.mjs";const e="0.0.0";export{s as BACKUP_KEY_PREFIX,Ee as DEFAULT_LOG_COLUMNS,A as DEFAULT_REGISTRY_CACHE_TTL_MS,w as HEALTH_PATH,z as HEALTH_READY_PATH,Ke as LOG_ARCHIVE_NOT_CONFIGURED,J as LOG_ARCHIVE_PATH,v as LunoraError,Be as NOOP_EXECUTION_CONTEXT,L as SHARD_REGISTRY_DO_NAME,Ne as STORAGE_UPLOAD_MAX_BODY_BYTES,e as VERSION,se as analyticsEngineSink,ue as applyJurisdiction,ye as applyRestCache,Ae as argsFromQuery,i as backupManifestKey,p as backupObjectKey,n as backupObjectKeyOfManifest,X as buildHealthRoutes,Le as buildRestRoutes,ie as combineSinks,we as composeIdentityResolvers,l as composeWorker,pe as consoleSink,O as createCrossShardRelationCapabilities,T as createDynamicShardRegistry,F as createKvCursorStore,d as createLunoraHandler,M as createMemoryCursorStore,Re as createPipelineLogReader,Se as createQueryCoordinator,Te as createRestRateLimit,Fe as createShardClient,le as createStaticShardRegistry,u as createWorker,j as d1Probe,t as declareAppJurisdiction,Pe as decorateResponse,N as defineExportSink,_ as defineRpcEnvelope,V as durableObjectProbe,oe as emitLogEvent,te as emitRpcEvent,ge as enforceOrigin,ve as handleCorsPreflight,c as isBackupManifestEntry,m as isBackupManifestKey,$ as memoizeIdentity,ee as memoizeIdentityPerRequest,f as normalizeBackupPrefix,ne as otlpSink,H as parseStackFrames,ce as pipelineLogSink,W as presenceProbe,G as r2Sink,Ce as requestCarriesCredentials,Q as resolveLogArchiveFromEnv,k as resolveLunoraOptions,Ie as resolveSecurity,_e as resolveShard,Oe as restCacheHeaders,he as restSurfaceFromRegistry,ze as routeIdentityResolvers,K as runExportTap,U as sanitizeChange,R as toAirbyteMessages,P as toError,I as toErrorResponse,x as toFivetranResponse,B as webhookExportSink,me as webhookSink,y as withFrameworkWorker};
1
+ import{declareAppJurisdiction as t}from"./packem_shared/declareAppJurisdiction-DEba2p42.mjs";import{BACKUP_KEY_PREFIX as s,backupManifestKey as i,backupObjectKey as p,backupObjectKeyOfManifest as n,isBackupManifestEntry as c,isBackupManifestKey as m,normalizeBackupPrefix as f}from"./packem_shared/BACKUP_KEY_PREFIX-BOtSu-_3.mjs";import{toAirbyteMessages as R,toFivetranResponse as x}from"./packem_shared/toAirbyteMessages-DY0vsuEn.mjs";import{composeWorker as l,createLunoraHandler as d,createWorker as u,defineRpcEnvelope as _,resolveLunoraOptions as k,withFrameworkWorker as y}from"./packem_shared/composeWorker-DbWkalF4.mjs";import{createCrossShardRelationCapabilities as O}from"./packem_shared/createCrossShardRelationCapabilities-BmGOuTrp.mjs";import{DEFAULT_REGISTRY_CACHE_TTL_MS as A,SHARD_REGISTRY_DO_NAME as L,createDynamicShardRegistry as T}from"./packem_shared/DEFAULT_REGISTRY_CACHE_TTL_MS-CdACWUQW.mjs";import{parseStackFrames as H,toError as P}from"./packem_shared/parseStackFrames-CZddjveh.mjs";import{LunoraError as v,toErrorResponse as I}from"./packem_shared/LunoraError-DksAgIpa.mjs";import{c as F,a as M,d as N,r as G,b as K,s as U,w as B}from"./packem_shared/export-tap-C2B_SATf.mjs";import{HEALTH_PATH as w,HEALTH_READY_PATH as z,buildHealthRoutes as X,d1Probe as j,durableObjectProbe as V,presenceProbe as W}from"./packem_shared/HEALTH_PATH-CAX2UeFy.mjs";import{LOG_ARCHIVE_PATH as J,resolveLogArchiveFromEnv as Q}from"./packem_shared/LOG_ARCHIVE_PATH-Hmjpz_Ko.mjs";import{memoizeIdentity as $,memoizeIdentityPerRequest as ee}from"./packem_shared/memoizeIdentity-BNnHkqeF.mjs";import{e as oe,a as te}from"./packem_shared/observability-DgurIZIR.mjs";import{analyticsEngineSink as se,combineSinks as ie,consoleSink as pe,otlpSink as ne,pipelineLogSink as ce,webhookSink as me}from"./packem_shared/analyticsEngineSink-BZB-ZYCP.mjs";import{D as Ee,c as Re}from"./packem_shared/pipeline-log-reader-C-nuWG_e.mjs";import{createQueryCoordinator as Se,createStaticShardRegistry as le}from"./packem_shared/createQueryCoordinator-es4jrL6Q.mjs";import{applyJurisdiction as ue,resolveShard as _e}from"./packem_shared/applyJurisdiction-D4vryLhj.mjs";import{a as ye,r as Ce,b as Oe}from"./packem_shared/rest-cache-CmHN871W.mjs";import{a as Ae,b as Le,c as Te,r as he}from"./packem_shared/rest-routes-DQkyqlym.mjs";import{decorateResponse as Pe,enforceOrigin as ge,handleCorsPreflight as ve,resolveSecurity as Ie}from"./packem_shared/decorateResponse-BxMmYMux.mjs";import{createShardClient as Fe}from"./packem_shared/createShardClient-DIVRljRz.mjs";import{STORAGE_UPLOAD_MAX_BODY_BYTES as Ne}from"./packem_shared/STORAGE_UPLOAD_MAX_BODY_BYTES-BIiV5kqV.mjs";import{LOG_ARCHIVE_NOT_CONFIGURED as Ke}from"./packem_shared/LOG_ARCHIVE_NOT_CONFIGURED-CDpi4yFD.mjs";import{NOOP_EXECUTION_CONTEXT as Be}from"./packem_shared/NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{composeIdentityResolvers as we,routeIdentityResolvers as ze}from"./packem_shared/composeIdentityResolvers-BHZ4jH8o.mjs";const e="0.0.0";export{s as BACKUP_KEY_PREFIX,Ee as DEFAULT_LOG_COLUMNS,A as DEFAULT_REGISTRY_CACHE_TTL_MS,w as HEALTH_PATH,z as HEALTH_READY_PATH,Ke as LOG_ARCHIVE_NOT_CONFIGURED,J as LOG_ARCHIVE_PATH,v as LunoraError,Be as NOOP_EXECUTION_CONTEXT,L as SHARD_REGISTRY_DO_NAME,Ne as STORAGE_UPLOAD_MAX_BODY_BYTES,e as VERSION,se as analyticsEngineSink,ue as applyJurisdiction,ye as applyRestCache,Ae as argsFromQuery,i as backupManifestKey,p as backupObjectKey,n as backupObjectKeyOfManifest,X as buildHealthRoutes,Le as buildRestRoutes,ie as combineSinks,we as composeIdentityResolvers,l as composeWorker,pe as consoleSink,O as createCrossShardRelationCapabilities,T as createDynamicShardRegistry,F as createKvCursorStore,d as createLunoraHandler,M as createMemoryCursorStore,Re as createPipelineLogReader,Se as createQueryCoordinator,Te as createRestRateLimit,Fe as createShardClient,le as createStaticShardRegistry,u as createWorker,j as d1Probe,t as declareAppJurisdiction,Pe as decorateResponse,N as defineExportSink,_ as defineRpcEnvelope,V as durableObjectProbe,oe as emitLogEvent,te as emitRpcEvent,ge as enforceOrigin,ve as handleCorsPreflight,c as isBackupManifestEntry,m as isBackupManifestKey,$ as memoizeIdentity,ee as memoizeIdentityPerRequest,f as normalizeBackupPrefix,ne as otlpSink,H as parseStackFrames,ce as pipelineLogSink,W as presenceProbe,G as r2Sink,Ce as requestCarriesCredentials,Q as resolveLogArchiveFromEnv,k as resolveLunoraOptions,Ie as resolveSecurity,_e as resolveShard,Oe as restCacheHeaders,he as restSurfaceFromRegistry,ze as routeIdentityResolvers,K as runExportTap,U as sanitizeChange,R as toAirbyteMessages,P as toError,I as toErrorResponse,x as toFivetranResponse,B as webhookExportSink,me as webhookSink,y as withFrameworkWorker};
@@ -1,6 +1,6 @@
1
- import{isLunoraError as pr,toErrorBody as mr}from"@lunora/errors";import{encodeWire as Te,decodeWire as Xe,encodeArgsOrThrow as wr}from"@lunora/wire";import{e as tn}from"./evict-oldest-BNXsKx4s.mjs";import{NOOP_EXECUTION_CONTEXT as gr}from"./NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{i as yr,e as br,a as _r,E as gt,d as Rr}from"./identity-header-pR617HTs.mjs";import{O as nn,a as rn}from"./origin-paywall-B6eOO67m.mjs";import{o as we,b as on,p as Er,m as Ar,d as Tr,a as Sr,r as Or}from"./otlp-resource-BwFJnvwB.mjs";import{r as vr,f as yt,a as ie,S as bt}from"./observability-DgurIZIR.mjs";import{t as Ir,f as kr}from"./base64-Bl1_r2k1.mjs";import{d as ee,e as ne,M as sn,b as Pr,f as Dr,g as an,w as Nr,h as cn,t as Ur}from"./rest-routes-DQkyqlym.mjs";import{LunoraError as c,toErrorResponse as _t}from"./LunoraError-DksAgIpa.mjs";import{a as M,m as me}from"./method-guard-BG_vJNTl.mjs";import{normalizeBackupPrefix as ot,BACKUP_KEY_PREFIX as st,isBackupManifestKey as Cr,backupObjectKeyOfManifest as dn,backupObjectKey as Br,backupManifestKey as xr}from"./BACKUP_KEY_PREFIX-BOtSu-_3.mjs";import{toHex as Hr,buildStorageAdminRoutes as Lr,STORAGE_UPLOAD_MAX_BODY_BYTES as jr,STORAGE_PATH as Mr}from"./STORAGE_UPLOAD_MAX_BODY_BYTES-BIiV5kqV.mjs";import{b as $r,e as Kr,f as Rt,g as Fr,h as Gr}from"./export-tap-C2B_SATf.mjs";import{buildHealthRoutes as Qr,durableObjectProbe as Wr,d1Probe as zr,presenceProbe as $e}from"./HEALTH_PATH-CAX2UeFy.mjs";import{wrapResolverWithContract as Vr}from"./composeIdentityResolvers-BHZ4jH8o.mjs";import{composeIdentityResolvers as Hi,routeIdentityResolvers as Li}from"./composeIdentityResolvers-BHZ4jH8o.mjs";import{buildLogArchiveAdminRoutes as Jr}from"./LOG_ARCHIVE_PATH-Hmjpz_Ko.mjs";import{pruneShardRegistry as Yr,createQueryCoordinator as qr,createDefaultShardRegistry as Xr}from"./createQueryCoordinator-es4jrL6Q.mjs";import{resolveShard as ge,applyJurisdiction as Ke}from"./applyJurisdiction-D4vryLhj.mjs";import{resolveSecurity as Et,handleCorsPreflight as Zr,enforceOrigin as eo,decorateResponse as Fe,enforceWebSocketOrigin as At}from"./decorateResponse-CRrFNW1v.mjs";const to=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},un="__lunoraBranch",no=e=>typeof e=="object"&&e!==null&&Object.hasOwn(e,un),ro=`may not contain the reserved workflow branch-marker key ("${un}")`,oo=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}},so=/already[\s_-]?exists/iu,ao=e=>so.test(e instanceof Error?e.message:String(e)),Tt="x-lunora-want-error-detail",St="x-lunora-error-detail",io=8192,co=e=>{if(!(e instanceof Error))return{message:String(e),name:typeof e};const{code:t}=e;return{...typeof t=="string"?{code:t}:{},message:e.message,name:e.name,...e.stack===void 0?{}:{stack:e.stack.slice(0,io)}}},Ot=e=>{if(e!=null)try{const t=JSON.parse(decodeURIComponent(e));return typeof t?.message=="string"&&typeof t.name=="string"?t:void 0}catch{return}},uo="cf-ray",lo="x-lunora-ray-id",ho=/^([\da-f]{16})(?:-[a-z]{3,4})?$/i,fo=e=>e==null?void 0:ho.exec(e.trim())?.[1]?.toLowerCase(),po=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"];new Set(po);const mo=new Set(["AE","BH","IL","IQ","IR","JO","KW","LB","OM","PS","QA","SA","SY","TR","YE"]),wo=-100,go=15,yo=e=>{const t=Number(e.longitude??Number.NaN);switch(e.continent){case"AF":return"afr";case"AS":return e.country!==void 0&&mo.has(e.country)?"me":"apac";case"EU":return Number.isFinite(t)&&t>go?"eeur":"weur";case"NA":return Number.isFinite(t)&&t<wo?"wnam":"enam";case"OC":return"oc";case"SA":return"sam";default:return}},vt=e=>{const t=e.cf;return t===void 0?void 0:yo(t)},Ze="::relay::",bo=(e,t)=>`${e}${Ze}${String(t)}`,et="::replica::",_o=(e,t)=>`${e}${et}${t}`,Ro=e=>{if(e==null||!/^\d+$/.test(e))return;const t=Number.parseInt(e,10);return Number.isSafeInteger(t)&&t>0?t:void 0},ln=(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},Eo=(e,t,n,r)=>{const s=e.get(t);if(s!==void 0)return s;tn(e,r);const i=n().catch(d=>{throw e.get(t)===i&&e.delete(t),d});return e.set(t,i),i},at=new TextEncoder,Ao=Array.from({length:32},(e,t)=>t);new RegExp(`[${Ao.map(e=>String.fromCodePoint(e)).join("")}]`,"u");const To=64,So=new Map,hn=async e=>Eo(So,e,async()=>crypto.subtle.importKey("raw",at.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]),To),fn=async(e,t)=>{const n=await hn(e),r=await crypto.subtle.sign("HMAC",n,at.encode(t));return Ir(new Uint8Array(r))},Oo=async(e,t,n)=>{const r=await hn(e);return crypto.subtle.verify("HMAC",r,n,at.encode(t))},vo="/_lunora/scheduler/dispatch",Io="__lunora_relation__:",ko=e=>e.startsWith(Io),pn=(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:ln(t,s.join(" ").trim())},Po=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?ln(await fn(s,t),r):pn(e,n.adminToken)},Do=({forwardedIdentity:e,mutationId:t,traceparent:n})=>{const r={"content-type":"application/json",[rn]:nn,"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},No=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}}},Uo=(e,t,n)=>e?.[n]??t?.[n],Co=(e,t,n,r)=>{const s=Uo(e,t,n);if(!(typeof s!="object"||s===null))return r.every(i=>typeof s[i]=="function")?s:void 0},mn="v1",Bo=6e4,xo=async(e,t={})=>{const n=(t.now??Date.now())+(t.ttlMs??Bo),r=`${mn}.${String(n)}`,s=await fn(e,r);return{expiresAtMs:n,token:`${r}.${s}`}},Ho=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!==mn||d.length===0)return!1;const f=Number(i);if(!Number.isFinite(f)||f<=n)return!1;let h;try{h=kr(d)}catch{return!1}return Oo(e,`${s}.${i}`,h)},N="/_lunora/admin/auth",Lo={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},C=(e,t)=>{const n=e[t];if(typeof n!="string"||n==="")throw new c(`\`${t}\` is required`,{code:"BAD_REQUEST",status:400});return n},he=(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},wn=e=>{if(typeof e=="string"||Array.isArray(e)&&e.every(t=>typeof t=="string"))return e},te=(e,t)=>typeof e[t]=="string"?e[t]:void 0,Ge=(e,t)=>{const n=e[t];return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:void 0},It=e=>{const t=wn(e.role);if(t===void 0||typeof t=="string"&&t.trim()==="")throw new c("`role` is required",{code:"BAD_REQUEST",status:400});return t},kt=e=>{const t=e.permission;if(typeof t!="object"||t===null||Array.isArray(t))throw new c("`permission` object is required",{code:"BAD_REQUEST",status:400});const n={};for(const[r,s]of Object.entries(t))Array.isArray(s)&&s.every(i=>typeof i=="string")&&(n[r]=s);return n},jo={[`${N}/capabilities`]:{build:()=>({}),http:"GET",method:"capabilities"},[`${N}/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"},[`${N}/sessions`]:{build:({paging:e,query:t})=>({...e,userId:t("userId")}),http:"GET",method:"listSessions"},[`${N}/accounts`]:{build:({query:e})=>({userId:he(e,"userId")}),http:"GET",method:"listAccounts"},[`${N}/passkeys`]:{build:({query:e})=>({userId:he(e,"userId")}),http:"GET",method:"listPasskeys"},[`${N}/organizations`]:{build:({paging:e})=>({...e}),http:"GET",method:"listOrganizations"},[`${N}/organizations/members`]:{build:({paging:e,query:t})=>({...e,organizationId:he(t,"organizationId")}),http:"GET",method:"listMembers"},[`${N}/organizations/invitations`]:{build:({paging:e,query:t})=>({...e,organizationId:he(t,"organizationId")}),http:"GET",method:"listInvitations"},[`${N}/sign-up-invitations`]:{build:({paging:e})=>({...e}),http:"GET",method:"listSignUpInvitations"},[`${N}/sign-up-invitations/create`]:{build:({body:e})=>({email:C(e,"email"),expiresInSeconds:typeof e.expiresInSeconds=="number"?e.expiresInSeconds:void 0,invitedBy:te(e,"invitedBy")}),http:"POST",method:"createSignUpInvitation"},[`${N}/sign-up-invitations/revoke`]:{build:({body:e})=>({email:C(e,"email")}),http:"POST",method:"revokeSignUpInvitation",returns:"void"},[`${N}/config`]:{build:()=>({}),http:"GET",method:"config"},[`${N}/organizations/teams`]:{build:({paging:e,query:t})=>({...e,organizationId:he(t,"organizationId")}),http:"GET",method:"listTeams"},[`${N}/organizations/teams/members`]:{build:({paging:e,query:t})=>({...e,teamId:he(t,"teamId")}),http:"GET",method:"listTeamMembers"},[`${N}/organizations/roles`]:{build:({paging:e,query:t})=>({...e,organizationId:he(t,"organizationId")}),http:"GET",method:"listOrgRoles"},[`${N}/users/create`]:{build:({body:e})=>({data:Ge(e,"data"),email:C(e,"email"),name:C(e,"name"),password:te(e,"password"),role:wn(e.role)}),http:"POST",method:"createUser"},[`${N}/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:C(e,"userId")}},http:"POST",method:"updateUser"},[`${N}/users/role`]:{build:({body:e})=>({role:It(e),userId:C(e,"userId")}),http:"POST",method:"setRole"},[`${N}/users/ban`]:{build:({body:e})=>({expiresInSeconds:typeof e.expiresInSeconds=="number"?e.expiresInSeconds:void 0,reason:te(e,"reason"),userId:C(e,"userId")}),http:"POST",method:"banUser"},[`${N}/users/unban`]:{build:({body:e})=>({userId:C(e,"userId")}),http:"POST",method:"unbanUser"},[`${N}/users/password`]:{build:({body:e})=>({newPassword:C(e,"newPassword"),userId:C(e,"userId")}),http:"POST",method:"setUserPassword",returns:"void"},[`${N}/users/remove`]:{build:({body:e})=>({userId:C(e,"userId")}),http:"POST",method:"removeUser",returns:"void"},[`${N}/users/impersonate`]:{build:({body:e})=>({userId:C(e,"userId")}),http:"POST",method:"impersonateUser"},[`${N}/sessions/revoke`]:{build:({body:e})=>({sessionId:C(e,"sessionId")}),http:"POST",method:"revokeUserSession",returns:"void"},[`${N}/sessions/revoke-all`]:{build:({body:e})=>({userId:C(e,"userId")}),http:"POST",method:"revokeUserSessions",returns:"void"},[`${N}/accounts/unlink`]:{build:({body:e})=>({accountId:C(e,"accountId"),userId:C(e,"userId")}),http:"POST",method:"unlinkAccount",returns:"void"},[`${N}/two-factor/disable`]:{build:({body:e})=>({userId:C(e,"userId")}),http:"POST",method:"disableTwoFactor",returns:"void"},[`${N}/passkeys/delete`]:{build:({body:e})=>({passkeyId:C(e,"passkeyId")}),http:"POST",method:"deletePasskey",returns:"void"},[`${N}/organizations/members/remove`]:{build:({body:e})=>({memberId:C(e,"memberId")}),http:"POST",method:"removeMember",returns:"void"},[`${N}/organizations/invitations/cancel`]:{build:({body:e})=>({invitationId:C(e,"invitationId")}),http:"POST",method:"cancelInvitation",returns:"void"},[`${N}/organizations/create`]:{build:({body:e})=>({logo:te(e,"logo"),metadata:Ge(e,"metadata"),name:C(e,"name"),ownerId:te(e,"ownerId"),slug:te(e,"slug")}),http:"POST",method:"createOrganization"},[`${N}/organizations/update`]:{build:({body:e})=>({logo:te(e,"logo"),metadata:Ge(e,"metadata"),name:te(e,"name"),organizationId:C(e,"organizationId"),slug:te(e,"slug")}),http:"POST",method:"updateOrganization"},[`${N}/organizations/remove`]:{build:({body:e})=>({organizationId:C(e,"organizationId")}),http:"POST",method:"deleteOrganization",returns:"void"},[`${N}/organizations/members/add`]:{build:({body:e})=>({organizationId:C(e,"organizationId"),role:te(e,"role"),userId:C(e,"userId")}),http:"POST",method:"addMember"},[`${N}/organizations/members/invite`]:{build:({body:e})=>({email:C(e,"email"),inviterId:te(e,"inviterId"),organizationId:C(e,"organizationId"),role:te(e,"role")}),http:"POST",method:"inviteMember"},[`${N}/organizations/members/role`]:{build:({body:e})=>({memberId:C(e,"memberId"),role:It(e)}),http:"POST",method:"updateMemberRole"},[`${N}/organizations/teams/create`]:{build:({body:e})=>({name:C(e,"name"),organizationId:C(e,"organizationId")}),http:"POST",method:"createTeam"},[`${N}/organizations/teams/update`]:{build:({body:e})=>({name:C(e,"name"),teamId:C(e,"teamId")}),http:"POST",method:"updateTeam"},[`${N}/organizations/teams/remove`]:{build:({body:e})=>({teamId:C(e,"teamId")}),http:"POST",method:"removeTeam",returns:"void"},[`${N}/organizations/teams/members/add`]:{build:({body:e})=>({teamId:C(e,"teamId"),userId:C(e,"userId")}),http:"POST",method:"addTeamMember"},[`${N}/organizations/teams/members/remove`]:{build:({body:e})=>({teamMemberId:C(e,"teamMemberId")}),http:"POST",method:"removeTeamMember",returns:"void"},[`${N}/organizations/roles/create`]:{build:({body:e})=>({organizationId:C(e,"organizationId"),permission:kt(e),role:C(e,"role")}),http:"POST",method:"createOrgRole"},[`${N}/organizations/roles/update`]:{build:({body:e})=>({permission:kt(e),roleId:C(e,"roleId")}),http:"POST",method:"updateOrgRole"},[`${N}/organizations/roles/remove`]:{build:({body:e})=>({roleId:C(e,"roleId")}),http:"POST",method:"deleteOrgRole",returns:"void"}},Mo=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:Lo[f]??500})}},n=async(s,i)=>{if(e.assertAdmin(s),s.method!==i.http)throw new c(`Auth admin endpoint requires ${i.http}`,{code:"METHOD_NOT_ALLOWED",status:405});const d=e.getAuthAdmin();if(d===void 0)throw new c("auth endpoints require an `authAdmin` on the worker",{code:"AUTH_NOT_CONFIGURED",status:400});const f=d[i.method];if(f===void 0)throw new c(`auth admin does not support \`${i.method}\``,{code:"AUTH_OP_NOT_SUPPORTED",status:400});const h=new URL(s.url),m={body:i.http==="POST"?await e.readJsonBody(s):{},paging:e.parsePaging(s),query:S=>e.queryParameter(h,S)},b=i.build(m),T=await t(()=>f(b));return Response.json(i.returns==="void"?{ok:!0}:T,{headers:{"cache-control":"no-store","content-type":"application/json"},status:200})},r={};for(const[s,i]of Object.entries(jo))r[s]=d=>n(d,i);return r},Pt="__lunora_admin__:getAuthAuditLog",Dt=e=>typeof e=="string"&&e!==""?e:void 0,Nt=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0,$o=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=Dt(r.actorId),d=Dt(r.event),f=Nt(r.sinceSeq),h=Nt(r.limit),m={...i===void 0?{}:{actorId:i},...d===void 0?{}:{event:d},...f===void 0?{}:{sinceSeq:f},...h===void 0?{}:{limit:h}};let b;try{b=await s.read(m)}catch(S){throw S instanceof c?S:(console.error("[lunora] auth audit read failed:",S),new c("auth audit read failed",{code:"AUTH_AUDIT_READ_FAILED",status:500}))}const T={entries:b};return Response.json({result:Te(T)},{headers:{"content-type":"application/json"},status:200})},tt="__lunora_admin__:copyAuthToJurisdiction",gn="__lunora_admin__:purgeUnpinnedAuth",Ko=e=>async(t,n,r)=>{if(n!==tt&&n!==gn)return;e.assertAdmin(t);const s=e.getMove();if(s===void 0)throw new c("moving auth into the jurisdiction needs DO-backed auth pinned with `.jurisdiction(…, { pinAuth: true })`",{code:"AUTH_MOVE_NOT_CONFIGURED",status:400});const i=n===tt?await s.copy({force:r.force===!0}):await s.purge();return Response.json({result:Te(i)},{headers:{"content-type":"application/json"},status:200})},Fo=(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}},Go=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??[])},yn=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}=Fo(e,i),h=await Go(t,n,i,f,s,e.defaultShardKey??"__root__"),m=e.exportGlobals,b=r===void 0||d.length>0;return(async function*(){yield*h,b&&m&&(yield*m({tables:d}))})()},Qo=async(e,t,n,r,s,i)=>{for await(const d of await yn(e,t,n,r,i))s(d)},Wo=new TextEncoder,zo=1e3,bn=10,Vo=200,Ut=8,_n="lunoraBackupCron",Ct=24*1048576,Bt=e=>{const t=e.slice(0,bn).map(r=>dn(r)),n=e.length-t.length;return`${t.join(", ")}${n>0?` (+${String(n)} more)`:""}`},Jo=(e,t)=>{const n=new Uint8Array(new ArrayBuffer(t));let r=0;for(const s of e)n.set(s,r),r+=s.byteLength;return n},it=async(e,t,n,r)=>{if(n===void 0||!Number.isInteger(n)||n<=0)return{eligible:0,stale:[]};const s=[];let i;for(let d=0;d<zo;d+=1){const f=await e.list({cursor:i,include:["customMetadata"],prefix:t});for(const h of f.objects)Cr(h.key)&&h.customMetadata?.[_n]===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)}},Yo=async(e,t,n,r,s)=>{const{stale:i}=await it(e,t,n,r),d=new Set(s),f=i.filter(k=>d.has(k)),h=f.slice(0,Vo),m=i.length-h.length,b=s.length-f.length;if(h.length===0)return{deleted:[],failed:[],ignored:b,remaining:m};const T=[],S=[];for(let k=0;k<h.length;k+=Ut){const w=await Promise.allSettled(h.slice(k,k+Ut).map(async g=>(await e.delete(dn(g)),await e.delete(g),g)));for(const[g,y]of w.entries())y.status==="fulfilled"?T.push(y.value):S.push(h[k+g])}return T.length>0&&console.info(`[lunora] backup prune kept the newest ${String(n)} and deleted ${String(T.length)}: ${Bt(T)}`),S.length>0&&console.warn(`[lunora] backup prune failed to remove ${String(S.length)}: ${Bt(S)}`),{deleted:T,failed:S,ignored:b,remaining:m}},qo=async e=>{const t=e.backupStore;if(!t)throw new c("backup retention preview requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});const n=ot(e.backupPrefix??st),r=e.backupCron,{eligible:s,stale:i}=r===void 0?{eligible:0,stale:[]}:await it(t,n,e.backupRetain,r);return{cron:r,eligible:s,keep:e.backupRetain??0,prefix:n,wouldDelete:i}},Xo=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,b=[];await Qo(e,t,d,f,I=>{const E=Wo.encode(`${JSON.stringify(I)}
2
- `);if(h+=1,m+=E.byteLength,m>Ct)throw new c(`scheduled backup reached ${String(m)} bytes of NDJSON, past the ${String(Ct)}-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});b.push(E)},n);const S=ot(e.backupPrefix??st),k=new Date(s.scheduledTime).toISOString(),w=Br(S,k),g=Jo(b,m);b=[];const y=Hr(await crypto.subtle.digest("SHA-256",g));await i.put(w,g,{httpMetadata:{contentType:"application/x-ndjson"},sha256:y});const O={bytes:m,createdAt:k,cron:s.cron,file:w,id:k,rows:h,scheduledTime:s.scheduledTime,sha256:y,...f?{tables:f.join(",")}:{}};await i.put(xr(w),`${JSON.stringify(O,void 0,2)}
3
- `,{customMetadata:{[_n]:s.cron},httpMetadata:{contentType:"application/json"}});try{const{stale:I}=await it(i,S,e.backupRetain,s.cron);if(I.length>0){const E=I.slice(0,bn),H=I.length-E.length;console.info(`[lunora] backup retention: ${String(I.length)} snapshot(s) past the newest ${String(e.backupRetain)} — run \`lunora backup prune\` to remove them: ${E.join(", ")}${H>0?` (+${String(H)} more)`:""}`)}}catch(I){console.warn(`[lunora] backup ${w} was written, but the retention report failed:`,I)}},Zo=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 Yo(n,ot(e.backupPrefix??st),s,r,t)},es="/_lunora/admin/backup/retention",ts="/_lunora/admin/backup/prune",ns=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 qo(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 Zo(t,h),{headers:{"cache-control":"no-store"}})};return{[ts]:d,[es]:i}},xt=500,rs=(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}},os=(e,t)=>{if(e.length>xt)throw new c(`RPC batch exceeds the ${String(xt)}-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}=rs(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},ss="/_lunora/admin/export",as="/_lunora/admin/import",is="/_lunora/admin/sync",cs="/_lunora/admin/connector/sync",ds="/_lunora/admin/apply",us="/_lunora/admin/export-tap/run",ls=new TextEncoder,hs=async e=>{const n=await ne(e,"Export")??{};if(n.tables===void 0)return{tables:void 0};if(!Array.isArray(n.tables))throw new c("Export `tables` must be a string array",{code:"BAD_REQUEST",status:400});const r=[];for(const s of n.tables){if(typeof s!="string"||s.length===0)throw new c("Export `tables` entries must be non-empty strings",{code:"BAD_REQUEST",status:400});r.push(s)}return{tables:r}},Qe=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):void 0,fs=e=>{const{applyGlobals:t,defaultShardKey:n,exportCursorStore:r,exportSinks:s,knownTables:i,queryCoordinator:d,assertAdmin:f,resolveForwardContext:h,shardDO:m,prepareExportRows:b,streamingImport:T,syncGlobals:S}=e,k=async(E,H)=>{const L=me(E,["POST"]);if(L)return L;f(E);const U=await hs(E),{headers:F}=await h(E,H),q=await b(F,U.tables),W=new ReadableStream({async pull(z){try{for await(const V of q)z.enqueue(ls.encode(`${JSON.stringify(V)}
4
- `));z.close()}catch(V){z.error(V)}}});return new Response(W,{headers:{"content-type":"application/x-ndjson"},status:200})},w=async(E,H)=>{const L=me(E,["POST"]);if(L)return L;f(E);const U=await ee(E),F=typeof U.cursors=="object"&&U.cursors!==null?U.cursors:{},q=typeof U.epochs=="object"&&U.epochs!==null?U.epochs:{},W=typeof U.limit=="number"?U.limit:void 0,z=typeof U.globalCursor=="number"?U.globalCursor:0,V=Qe(U.tables),{headers:re}=await h(E,H),Q=V??i(),ce=await d.orchestrateCdcSync(m,{cursors:F,defaultShardKey:n,epochs:q,headers:re,limit:W,tables:Q}),$=S?await S({limit:W,sinceSeq:z}):void 0;return Response.json({global:$,shards:ce.shards},{status:200})},g=async(E,H)=>{const L=me(E,["POST"]);if(L)return L;f(E);const U=await ee(E),F=Kr(U.cursor),q=typeof U.limit=="number"&&U.limit>0?U.limit:void 0,W=Qe(U.tables),{headers:z}=await h(E,H),V=W??i(),re=await d.orchestrateCdcSync(m,{cursors:F.s,defaultShardKey:n,headers:z,limit:q,tables:V}),Q=[],ce={...F.s};let $=!1;for(const se of re.shards)$=Rt(Q,se.changes??[],Gr(q))||$,ce[se.shardKey]=se.cursor;let oe=F.g;if(S){const se=await S({limit:q,sinceSeq:F.g});$=Rt(Q,se.changes,q)||$,oe=se.cursor}const Be=Fr({g:oe,s:ce,v:1}),xe={changes:Q,hasMore:$,nextCursor:Be};return Response.json(xe,{status:200})},y=async(E,H)=>{const L=me(E,["POST"]);if(L)return L;f(E);const U=await ee(E),q=(Array.isArray(U.batches)?U.batches:[]).map(Q=>Q).filter(Q=>Q!==null&&typeof Q=="object"&&typeof Q.shardKey=="string"&&Array.isArray(Q.changes)),W=Array.isArray(U.globalChanges)?U.globalChanges:[],{headers:z}=await h(E,H),V=await d.orchestrateApplyCdc(m,{batches:q,headers:z}),re=W.length>0&&t?await t({changes:W}):0;return Response.json({applied:V.applied+re,failed:V.failed,ok:V.ok},{status:200})},O=async(E,H)=>{const L=me(E,["POST"]);if(L)return L;f(E);const{headers:U}=await h(E,H),F=await T(E,U);return Response.json(F,{headers:{"content-type":"application/json"},status:F.failed.length>0?207:200})},I=async(E,H)=>{const L=me(E,["POST"]);if(L)return L;if(f(E),s===void 0||Object.keys(s).length===0||r===void 0)throw new c("Export-tap endpoint requires `exportSinks` + `exportCursorStore` on the worker",{code:"EXPORT_TAP_NOT_CONFIGURED",status:400});const U=await ee(E),F=typeof U.sink=="string"?U.sink:void 0,q=typeof U.limit=="number"&&U.limit>0?U.limit:void 0,W=Qe(U.tables);if(F===void 0)throw new c("Export-tap `sink` must name a configured sink",{code:"BAD_REQUEST",status:400});const z=s[F];if(z===void 0)throw new c(`Export-tap sink "${F}" is not configured`,{code:"NOT_FOUND",status:404});const{headers:V}=await h(E,H),re=W??i(),Q=await $r({coordinator:d,cursorStore:r,defaultShardKey:n,headers:V,limit:q,shardDO:m,sink:z,tables:re});return Response.json(Q,{headers:{"content-type":"application/json"},status:200})};return{[ds]:y,[cs]:g,[ss]:k,[us]:I,[as]:O,[is]: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}},ms=(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}},ws=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 b="",T=0;const S=k=>{f+=1;const w=k.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:O}=g,I=t.resolveTableSharding?.(O);if(I?.mode.kind==="global"){s.push({doc:y,line:f,table:O});return}const E=ms(y,O,I,n,f);if(!E.ok){r.push(E.error);return}const H=i.get(E.shardKey);H?H.rows.push({doc:y,table:O}):i.set(E.shardKey,{rows:[{doc:y,table:O}],shardKey:E.shardKey,startLine:f})};for(;;){const{done:k,value:w}=await h.read();if(k)break;if(w&&(T+=w.byteLength,T>sn))throw await h.cancel().catch(()=>{}),new c("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});b+=m.decode(w,{stream:!0});let g=b.indexOf(`
1
+ import{isLunoraError as pr,toErrorBody as mr}from"@lunora/errors";import{encodeWire as Te,decodeWire as Xe,encodeArgsOrThrow as wr}from"@lunora/wire";import{e as tn}from"./evict-oldest-BNXsKx4s.mjs";import{NOOP_EXECUTION_CONTEXT as gr}from"./NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{i as yr,e as br,a as _r,E as gt,d as Rr}from"./identity-header-pR617HTs.mjs";import{O as nn,a as rn}from"./origin-paywall-B6eOO67m.mjs";import{o as we,b as on,p as Er,m as Ar,d as Tr,a as Sr,r as Or}from"./otlp-resource-BwFJnvwB.mjs";import{r as vr,f as yt,a as ie,S as bt}from"./observability-DgurIZIR.mjs";import{t as Ir,f as kr}from"./base64-Bl1_r2k1.mjs";import{d as ee,e as ne,M as an,b as Pr,f as Dr,g as sn,w as Nr,h as cn,t as Ur}from"./rest-routes-DQkyqlym.mjs";import{LunoraError as c,toErrorResponse as _t}from"./LunoraError-DksAgIpa.mjs";import{a as M,m as me}from"./method-guard-BG_vJNTl.mjs";import{normalizeBackupPrefix as ot,BACKUP_KEY_PREFIX as at,isBackupManifestKey as Cr,backupObjectKeyOfManifest as dn,backupObjectKey as Br,backupManifestKey as xr}from"./BACKUP_KEY_PREFIX-BOtSu-_3.mjs";import{toHex as Hr,buildStorageAdminRoutes as Lr,STORAGE_UPLOAD_MAX_BODY_BYTES as jr,STORAGE_PATH as Mr}from"./STORAGE_UPLOAD_MAX_BODY_BYTES-BIiV5kqV.mjs";import{b as $r,e as Kr,f as Rt,g as Fr,h as Gr}from"./export-tap-C2B_SATf.mjs";import{buildHealthRoutes as Qr,durableObjectProbe as Wr,d1Probe as zr,presenceProbe as $e}from"./HEALTH_PATH-CAX2UeFy.mjs";import{wrapResolverWithContract as Vr}from"./composeIdentityResolvers-BHZ4jH8o.mjs";import{composeIdentityResolvers as Hi,routeIdentityResolvers as Li}from"./composeIdentityResolvers-BHZ4jH8o.mjs";import{buildLogArchiveAdminRoutes as Jr}from"./LOG_ARCHIVE_PATH-Hmjpz_Ko.mjs";import{pruneShardRegistry as Yr,createQueryCoordinator as qr,createDefaultShardRegistry as Xr}from"./createQueryCoordinator-es4jrL6Q.mjs";import{resolveShard as ge,applyJurisdiction as Ke}from"./applyJurisdiction-D4vryLhj.mjs";import{resolveSecurity as Et,handleCorsPreflight as Zr,enforceOrigin as eo,decorateResponse as Fe,enforceWebSocketOrigin as At}from"./decorateResponse-BxMmYMux.mjs";const to=e=>{const t=e??{};if(typeof t.bucket=="function")return t;const n=t.bucketName,a={...t,bucketName:typeof n=="string"&&n!==""?n:"default"};return a.bucket=()=>a,a},un="__lunoraBranch",no=e=>typeof e=="object"&&e!==null&&Object.hasOwn(e,un),ro=`may not contain the reserved workflow branch-marker key ("${un}")`,oo=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}},ao=/already[\s_-]?exists/iu,so=e=>ao.test(e instanceof Error?e.message:String(e)),Tt="x-lunora-want-error-detail",St="x-lunora-error-detail",io=8192,co=e=>{if(!(e instanceof Error))return{message:String(e),name:typeof e};const{code:t}=e;return{...typeof t=="string"?{code:t}:{},message:e.message,name:e.name,...e.stack===void 0?{}:{stack:e.stack.slice(0,io)}}},Ot=e=>{if(e!=null)try{const t=JSON.parse(decodeURIComponent(e));return typeof t?.message=="string"&&typeof t.name=="string"?t:void 0}catch{return}},uo="cf-ray",lo="x-lunora-ray-id",ho=/^([\da-f]{16})(?:-[a-z]{3,4})?$/i,fo=e=>e==null?void 0:ho.exec(e.trim())?.[1]?.toLowerCase(),po=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"];new Set(po);const mo=new Set(["AE","BH","IL","IQ","IR","JO","KW","LB","OM","PS","QA","SA","SY","TR","YE"]),wo=-100,go=15,yo=e=>{const t=Number(e.longitude??Number.NaN);switch(e.continent){case"AF":return"afr";case"AS":return e.country!==void 0&&mo.has(e.country)?"me":"apac";case"EU":return Number.isFinite(t)&&t>go?"eeur":"weur";case"NA":return Number.isFinite(t)&&t<wo?"wnam":"enam";case"OC":return"oc";case"SA":return"sam";default:return}},vt=e=>{const t=e.cf;return t===void 0?void 0:yo(t)},Ze="::relay::",bo=(e,t)=>`${e}${Ze}${String(t)}`,et="::replica::",_o=(e,t)=>`${e}${et}${t}`,Ro=e=>{if(e==null||!/^\d+$/.test(e))return;const t=Number.parseInt(e,10);return Number.isSafeInteger(t)&&t>0?t:void 0},ln=(e,t)=>{const n=Math.max(e.length,t.length);let r=e.length^t.length;for(let a=0;a<n;a+=1){const i=a<e.length?e.charCodeAt(a):0,d=a<t.length?t.charCodeAt(a):0;r|=i^d}return r===0},Eo=(e,t,n,r)=>{const a=e.get(t);if(a!==void 0)return a;tn(e,r);const i=n().catch(d=>{throw e.get(t)===i&&e.delete(t),d});return e.set(t,i),i},st=new TextEncoder,Ao=Array.from({length:32},(e,t)=>t);new RegExp(`[${Ao.map(e=>String.fromCodePoint(e)).join("")}]`,"u");const To=64,So=new Map,hn=async e=>Eo(So,e,async()=>crypto.subtle.importKey("raw",st.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]),To),fn=async(e,t)=>{const n=await hn(e),r=await crypto.subtle.sign("HMAC",n,st.encode(t));return Ir(new Uint8Array(r))},Oo=async(e,t,n)=>{const r=await hn(e);return crypto.subtle.verify("HMAC",r,n,st.encode(t))},vo="/_lunora/scheduler/dispatch",Io="__lunora_relation__:",ko=e=>e.startsWith(Io),pn=(e,t)=>{if(!t||t.length===0)return!1;const n=e.headers.get("authorization");if(!n)return!1;const[r,...a]=n.split(" ");return r?.toLowerCase()!=="bearer"?!1:ln(t,a.join(" ").trim())},Po=async(e,t,n)=>{const r=e.headers.get("x-lunora-scheduler-signature"),{schedulerSecret:a}=n;return r!==null&&r.length>0&&a!==void 0&&a.length>0?ln(await fn(a,t),r):pn(e,n.adminToken)},Do=({forwardedIdentity:e,mutationId:t,traceparent:n})=>{const r={"content-type":"application/json",[rn]:nn,"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},No=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}}},Uo=(e,t,n)=>e?.[n]??t?.[n],Co=(e,t,n,r)=>{const a=Uo(e,t,n);if(!(typeof a!="object"||a===null))return r.every(i=>typeof a[i]=="function")?a:void 0},mn="v1",Bo=6e4,xo=async(e,t={})=>{const n=(t.now??Date.now())+(t.ttlMs??Bo),r=`${mn}.${String(n)}`,a=await fn(e,r);return{expiresAtMs:n,token:`${r}.${a}`}},Ho=async(e,t,n=Date.now())=>{if(e.length===0||t.length===0)return!1;const r=t.split(".");if(r.length!==3)return!1;const[a,i,d]=r;if(a!==mn||d.length===0)return!1;const f=Number(i);if(!Number.isFinite(f)||f<=n)return!1;let h;try{h=kr(d)}catch{return!1}return Oo(e,`${a}.${i}`,h)},N="/_lunora/admin/auth",Lo={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},C=(e,t)=>{const n=e[t];if(typeof n!="string"||n==="")throw new c(`\`${t}\` is required`,{code:"BAD_REQUEST",status:400});return n},he=(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},wn=e=>{if(typeof e=="string"||Array.isArray(e)&&e.every(t=>typeof t=="string"))return e},te=(e,t)=>typeof e[t]=="string"?e[t]:void 0,Ge=(e,t)=>{const n=e[t];return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:void 0},It=e=>{const t=wn(e.role);if(t===void 0||typeof t=="string"&&t.trim()==="")throw new c("`role` is required",{code:"BAD_REQUEST",status:400});return t},kt=e=>{const t=e.permission;if(typeof t!="object"||t===null||Array.isArray(t))throw new c("`permission` object is required",{code:"BAD_REQUEST",status:400});const n={};for(const[r,a]of Object.entries(t))Array.isArray(a)&&a.every(i=>typeof i=="string")&&(n[r]=a);return n},jo={[`${N}/capabilities`]:{build:()=>({}),http:"GET",method:"capabilities"},[`${N}/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"},[`${N}/sessions`]:{build:({paging:e,query:t})=>({...e,userId:t("userId")}),http:"GET",method:"listSessions"},[`${N}/accounts`]:{build:({query:e})=>({userId:he(e,"userId")}),http:"GET",method:"listAccounts"},[`${N}/passkeys`]:{build:({query:e})=>({userId:he(e,"userId")}),http:"GET",method:"listPasskeys"},[`${N}/organizations`]:{build:({paging:e})=>({...e}),http:"GET",method:"listOrganizations"},[`${N}/organizations/members`]:{build:({paging:e,query:t})=>({...e,organizationId:he(t,"organizationId")}),http:"GET",method:"listMembers"},[`${N}/organizations/invitations`]:{build:({paging:e,query:t})=>({...e,organizationId:he(t,"organizationId")}),http:"GET",method:"listInvitations"},[`${N}/sign-up-invitations`]:{build:({paging:e})=>({...e}),http:"GET",method:"listSignUpInvitations"},[`${N}/sign-up-invitations/create`]:{build:({body:e})=>({email:C(e,"email"),expiresInSeconds:typeof e.expiresInSeconds=="number"?e.expiresInSeconds:void 0,invitedBy:te(e,"invitedBy")}),http:"POST",method:"createSignUpInvitation"},[`${N}/sign-up-invitations/revoke`]:{build:({body:e})=>({email:C(e,"email")}),http:"POST",method:"revokeSignUpInvitation",returns:"void"},[`${N}/config`]:{build:()=>({}),http:"GET",method:"config"},[`${N}/organizations/teams`]:{build:({paging:e,query:t})=>({...e,organizationId:he(t,"organizationId")}),http:"GET",method:"listTeams"},[`${N}/organizations/teams/members`]:{build:({paging:e,query:t})=>({...e,teamId:he(t,"teamId")}),http:"GET",method:"listTeamMembers"},[`${N}/organizations/roles`]:{build:({paging:e,query:t})=>({...e,organizationId:he(t,"organizationId")}),http:"GET",method:"listOrgRoles"},[`${N}/users/create`]:{build:({body:e})=>({data:Ge(e,"data"),email:C(e,"email"),name:C(e,"name"),password:te(e,"password"),role:wn(e.role)}),http:"POST",method:"createUser"},[`${N}/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:C(e,"userId")}},http:"POST",method:"updateUser"},[`${N}/users/role`]:{build:({body:e})=>({role:It(e),userId:C(e,"userId")}),http:"POST",method:"setRole"},[`${N}/users/ban`]:{build:({body:e})=>({expiresInSeconds:typeof e.expiresInSeconds=="number"?e.expiresInSeconds:void 0,reason:te(e,"reason"),userId:C(e,"userId")}),http:"POST",method:"banUser"},[`${N}/users/unban`]:{build:({body:e})=>({userId:C(e,"userId")}),http:"POST",method:"unbanUser"},[`${N}/users/password`]:{build:({body:e})=>({newPassword:C(e,"newPassword"),userId:C(e,"userId")}),http:"POST",method:"setUserPassword",returns:"void"},[`${N}/users/remove`]:{build:({body:e})=>({userId:C(e,"userId")}),http:"POST",method:"removeUser",returns:"void"},[`${N}/users/impersonate`]:{build:({body:e})=>({userId:C(e,"userId")}),http:"POST",method:"impersonateUser"},[`${N}/sessions/revoke`]:{build:({body:e})=>({sessionId:C(e,"sessionId")}),http:"POST",method:"revokeUserSession",returns:"void"},[`${N}/sessions/revoke-all`]:{build:({body:e})=>({userId:C(e,"userId")}),http:"POST",method:"revokeUserSessions",returns:"void"},[`${N}/accounts/unlink`]:{build:({body:e})=>({accountId:C(e,"accountId"),userId:C(e,"userId")}),http:"POST",method:"unlinkAccount",returns:"void"},[`${N}/two-factor/disable`]:{build:({body:e})=>({userId:C(e,"userId")}),http:"POST",method:"disableTwoFactor",returns:"void"},[`${N}/passkeys/delete`]:{build:({body:e})=>({passkeyId:C(e,"passkeyId")}),http:"POST",method:"deletePasskey",returns:"void"},[`${N}/organizations/members/remove`]:{build:({body:e})=>({memberId:C(e,"memberId")}),http:"POST",method:"removeMember",returns:"void"},[`${N}/organizations/invitations/cancel`]:{build:({body:e})=>({invitationId:C(e,"invitationId")}),http:"POST",method:"cancelInvitation",returns:"void"},[`${N}/organizations/create`]:{build:({body:e})=>({logo:te(e,"logo"),metadata:Ge(e,"metadata"),name:C(e,"name"),ownerId:te(e,"ownerId"),slug:te(e,"slug")}),http:"POST",method:"createOrganization"},[`${N}/organizations/update`]:{build:({body:e})=>({logo:te(e,"logo"),metadata:Ge(e,"metadata"),name:te(e,"name"),organizationId:C(e,"organizationId"),slug:te(e,"slug")}),http:"POST",method:"updateOrganization"},[`${N}/organizations/remove`]:{build:({body:e})=>({organizationId:C(e,"organizationId")}),http:"POST",method:"deleteOrganization",returns:"void"},[`${N}/organizations/members/add`]:{build:({body:e})=>({organizationId:C(e,"organizationId"),role:te(e,"role"),userId:C(e,"userId")}),http:"POST",method:"addMember"},[`${N}/organizations/members/invite`]:{build:({body:e})=>({email:C(e,"email"),inviterId:te(e,"inviterId"),organizationId:C(e,"organizationId"),role:te(e,"role")}),http:"POST",method:"inviteMember"},[`${N}/organizations/members/role`]:{build:({body:e})=>({memberId:C(e,"memberId"),role:It(e)}),http:"POST",method:"updateMemberRole"},[`${N}/organizations/teams/create`]:{build:({body:e})=>({name:C(e,"name"),organizationId:C(e,"organizationId")}),http:"POST",method:"createTeam"},[`${N}/organizations/teams/update`]:{build:({body:e})=>({name:C(e,"name"),teamId:C(e,"teamId")}),http:"POST",method:"updateTeam"},[`${N}/organizations/teams/remove`]:{build:({body:e})=>({teamId:C(e,"teamId")}),http:"POST",method:"removeTeam",returns:"void"},[`${N}/organizations/teams/members/add`]:{build:({body:e})=>({teamId:C(e,"teamId"),userId:C(e,"userId")}),http:"POST",method:"addTeamMember"},[`${N}/organizations/teams/members/remove`]:{build:({body:e})=>({teamMemberId:C(e,"teamMemberId")}),http:"POST",method:"removeTeamMember",returns:"void"},[`${N}/organizations/roles/create`]:{build:({body:e})=>({organizationId:C(e,"organizationId"),permission:kt(e),role:C(e,"role")}),http:"POST",method:"createOrgRole"},[`${N}/organizations/roles/update`]:{build:({body:e})=>({permission:kt(e),roleId:C(e,"roleId")}),http:"POST",method:"updateOrgRole"},[`${N}/organizations/roles/remove`]:{build:({body:e})=>({roleId:C(e,"roleId")}),http:"POST",method:"deleteOrgRole",returns:"void"}},Mo=e=>{const t=async a=>{try{return await a()}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:Lo[f]??500})}},n=async(a,i)=>{if(e.assertAdmin(a),a.method!==i.http)throw new c(`Auth admin endpoint requires ${i.http}`,{code:"METHOD_NOT_ALLOWED",status:405});const 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(a.url),m={body:i.http==="POST"?await e.readJsonBody(a):{},paging:e.parsePaging(a),query:S=>e.queryParameter(h,S)},b=i.build(m),T=await t(()=>f(b));return Response.json(i.returns==="void"?{ok:!0}:T,{headers:{"cache-control":"no-store","content-type":"application/json"},status:200})},r={};for(const[a,i]of Object.entries(jo))r[a]=d=>n(d,i);return r},Pt="__lunora_admin__:getAuthAuditLog",Dt=e=>typeof e=="string"&&e!==""?e:void 0,Nt=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0,$o=e=>async(n,r)=>{e.assertAdmin(n);const a=e.getReader();if(a===void 0)throw new c("the auth/security audit endpoint requires an `authAuditReader` on the worker",{code:"AUTH_AUDIT_NOT_CONFIGURED",status:400});const i=Dt(r.actorId),d=Dt(r.event),f=Nt(r.sinceSeq),h=Nt(r.limit),m={...i===void 0?{}:{actorId:i},...d===void 0?{}:{event:d},...f===void 0?{}:{sinceSeq:f},...h===void 0?{}:{limit:h}};let b;try{b=await a.read(m)}catch(S){throw S instanceof c?S:(console.error("[lunora] auth audit read failed:",S),new c("auth audit read failed",{code:"AUTH_AUDIT_READ_FAILED",status:500}))}const T={entries:b};return Response.json({result:Te(T)},{headers:{"content-type":"application/json"},status:200})},tt="__lunora_admin__:copyAuthToJurisdiction",gn="__lunora_admin__:purgeUnpinnedAuth",Ko=e=>async(t,n,r)=>{if(n!==tt&&n!==gn)return;e.assertAdmin(t);const a=e.getMove();if(a===void 0)throw new c("moving auth into the jurisdiction needs DO-backed auth pinned with `.jurisdiction(…, { pinAuth: true })`",{code:"AUTH_MOVE_NOT_CONFIGURED",status:400});const i=n===tt?await a.copy({force:r.force===!0}):await a.purge();return Response.json({result:Te(i)},{headers:{"content-type":"application/json"},status:200})},Fo=(e,t)=>{const n=[],r=[];if(t&&t.length>0)for(const a of t)e.resolveTableSharding?.(a)?.mode.kind==="global"?r.push(a):n.push(a);return{globalTables:r,shardLocalTables:n}},Go=async(e,t,n,r,a,i)=>{if(n!==void 0&&r.length===0)return[];const d=await e.orchestrateExport(a,{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??[])},yn=async(e,t,n,r,a)=>{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}=Fo(e,i),h=await Go(t,n,i,f,a,e.defaultShardKey??"__root__"),m=e.exportGlobals,b=r===void 0||d.length>0;return(async function*(){yield*h,b&&m&&(yield*m({tables:d}))})()},Qo=async(e,t,n,r,a,i)=>{for await(const d of await yn(e,t,n,r,i))a(d)},Wo=new TextEncoder,zo=1e3,bn=10,Vo=200,Ut=8,_n="lunoraBackupCron",Ct=24*1048576,Bt=e=>{const t=e.slice(0,bn).map(r=>dn(r)),n=e.length-t.length;return`${t.join(", ")}${n>0?` (+${String(n)} more)`:""}`},Jo=(e,t)=>{const n=new Uint8Array(new ArrayBuffer(t));let r=0;for(const a of e)n.set(a,r),r+=a.byteLength;return n},it=async(e,t,n,r)=>{if(n===void 0||!Number.isInteger(n)||n<=0)return{eligible:0,stale:[]};const a=[];let i;for(let d=0;d<zo;d+=1){const f=await e.list({cursor:i,include:["customMetadata"],prefix:t});for(const h of f.objects)Cr(h.key)&&h.customMetadata?.[_n]===r&&a.push(h.key);if(!f.truncated||f.cursor===void 0)break;i=f.cursor}return{eligible:a.length,stale:a.toSorted((d,f)=>f.localeCompare(d)).slice(n)}},Yo=async(e,t,n,r,a)=>{const{stale:i}=await it(e,t,n,r),d=new Set(a),f=i.filter(k=>d.has(k)),h=f.slice(0,Vo),m=i.length-h.length,b=a.length-f.length;if(h.length===0)return{deleted:[],failed:[],ignored:b,remaining:m};const T=[],S=[];for(let k=0;k<h.length;k+=Ut){const w=await Promise.allSettled(h.slice(k,k+Ut).map(async g=>(await e.delete(dn(g)),await e.delete(g),g)));for(const[g,y]of w.entries())y.status==="fulfilled"?T.push(y.value):S.push(h[k+g])}return T.length>0&&console.info(`[lunora] backup prune kept the newest ${String(n)} and deleted ${String(T.length)}: ${Bt(T)}`),S.length>0&&console.warn(`[lunora] backup prune failed to remove ${String(S.length)}: ${Bt(S)}`),{deleted:T,failed:S,ignored:b,remaining:m}},qo=async e=>{const t=e.backupStore;if(!t)throw new c("backup retention preview requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});const n=ot(e.backupPrefix??at),r=e.backupCron,{eligible:a,stale:i}=r===void 0?{eligible:0,stale:[]}:await it(t,n,e.backupRetain,r);return{cron:r,eligible:a,keep:e.backupRetain??0,prefix:n,wouldDelete:i}},Xo=async(e,t,n,r,a)=>{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,b=[];await Qo(e,t,d,f,I=>{const E=Wo.encode(`${JSON.stringify(I)}
2
+ `);if(h+=1,m+=E.byteLength,m>Ct)throw new c(`scheduled backup reached ${String(m)} bytes of NDJSON, past the ${String(Ct)}-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});b.push(E)},n);const S=ot(e.backupPrefix??at),k=new Date(a.scheduledTime).toISOString(),w=Br(S,k),g=Jo(b,m);b=[];const y=Hr(await crypto.subtle.digest("SHA-256",g));await i.put(w,g,{httpMetadata:{contentType:"application/x-ndjson"},sha256:y});const O={bytes:m,createdAt:k,cron:a.cron,file:w,id:k,rows:h,scheduledTime:a.scheduledTime,sha256:y,...f?{tables:f.join(",")}:{}};await i.put(xr(w),`${JSON.stringify(O,void 0,2)}
3
+ `,{customMetadata:{[_n]:a.cron},httpMetadata:{contentType:"application/json"}});try{const{stale:I}=await it(i,S,e.backupRetain,a.cron);if(I.length>0){const E=I.slice(0,bn),H=I.length-E.length;console.info(`[lunora] backup retention: ${String(I.length)} snapshot(s) past the newest ${String(e.backupRetain)} — run \`lunora backup prune\` to remove them: ${E.join(", ")}${H>0?` (+${String(H)} more)`:""}`)}}catch(I){console.warn(`[lunora] backup ${w} was written, but the retention report failed:`,I)}},Zo=async(e,t)=>{const n=e.backupStore;if(!n)throw new c("backup prune requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});const r=e.backupCron,a=e.backupRetain;if(r===void 0||a===void 0||!Number.isInteger(a)||a<=0)throw new c("backup prune needs a retention window: set `backupRetain` (and `backupCron`, which decides whose snapshots retention owns) on the worker. Without one there is nothing past the window to remove.",{code:"BACKUP_RETENTION_NOT_CONFIGURED",status:400});return Yo(n,ot(e.backupPrefix??at),a,r,t)},ea="/_lunora/admin/backup/retention",ta="/_lunora/admin/backup/prune",na=e=>{const{options:t,readJsonBody:n,requireAdminOption:r}=e,a=(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"),a(f,"retention preview"),Response.json(await qo(t),{headers:{"cache-control":"no-store"}})),d=async f=>{M(f,"POST","Backup-prune"),a(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 Zo(t,h),{headers:{"cache-control":"no-store"}})};return{[ta]:d,[ea]:i}},xt=500,ra=(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}},oa=(e,t)=>{if(e.length>xt)throw new c(`RPC batch exceeds the ${String(xt)}-call limit`,{code:"BAD_REQUEST",status:400});const n=new Map,r=new Set;for(const[a,i]of e.entries()){const{entry:d,shardKey:f}=ra(i,a,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},aa="/_lunora/admin/export",sa="/_lunora/admin/import",ia="/_lunora/admin/sync",ca="/_lunora/admin/connector/sync",da="/_lunora/admin/apply",ua="/_lunora/admin/export-tap/run",la=new TextEncoder,ha=async e=>{const n=await ne(e,"Export")??{};if(n.tables===void 0)return{tables:void 0};if(!Array.isArray(n.tables))throw new c("Export `tables` must be a string array",{code:"BAD_REQUEST",status:400});const r=[];for(const a of n.tables){if(typeof a!="string"||a.length===0)throw new c("Export `tables` entries must be non-empty strings",{code:"BAD_REQUEST",status:400});r.push(a)}return{tables:r}},Qe=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):void 0,fa=e=>{const{applyGlobals:t,defaultShardKey:n,exportCursorStore:r,exportSinks:a,knownTables:i,queryCoordinator:d,assertAdmin:f,resolveForwardContext:h,shardDO:m,prepareExportRows:b,streamingImport:T,syncGlobals:S}=e,k=async(E,H)=>{const L=me(E,["POST"]);if(L)return L;f(E);const U=await ha(E),{headers:F}=await h(E,H),q=await b(F,U.tables),W=new ReadableStream({async pull(z){try{for await(const V of q)z.enqueue(la.encode(`${JSON.stringify(V)}
4
+ `));z.close()}catch(V){z.error(V)}}});return new Response(W,{headers:{"content-type":"application/x-ndjson"},status:200})},w=async(E,H)=>{const L=me(E,["POST"]);if(L)return L;f(E);const U=await ee(E),F=typeof U.cursors=="object"&&U.cursors!==null?U.cursors:{},q=typeof U.epochs=="object"&&U.epochs!==null?U.epochs:{},W=typeof U.limit=="number"?U.limit:void 0,z=typeof U.globalCursor=="number"?U.globalCursor:0,V=Qe(U.tables),{headers:re}=await h(E,H),Q=V??i(),ce=await d.orchestrateCdcSync(m,{cursors:F,defaultShardKey:n,epochs:q,headers:re,limit:W,tables:Q}),$=S?await S({limit:W,sinceSeq:z}):void 0;return Response.json({global:$,shards:ce.shards},{status:200})},g=async(E,H)=>{const L=me(E,["POST"]);if(L)return L;f(E);const U=await ee(E),F=Kr(U.cursor),q=typeof U.limit=="number"&&U.limit>0?U.limit:void 0,W=Qe(U.tables),{headers:z}=await h(E,H),V=W??i(),re=await d.orchestrateCdcSync(m,{cursors:F.s,defaultShardKey:n,headers:z,limit:q,tables:V}),Q=[],ce={...F.s};let $=!1;for(const ae of re.shards)$=Rt(Q,ae.changes??[],Gr(q))||$,ce[ae.shardKey]=ae.cursor;let oe=F.g;if(S){const ae=await S({limit:q,sinceSeq:F.g});$=Rt(Q,ae.changes,q)||$,oe=ae.cursor}const Be=Fr({g:oe,s:ce,v:1}),xe={changes:Q,hasMore:$,nextCursor:Be};return Response.json(xe,{status:200})},y=async(E,H)=>{const L=me(E,["POST"]);if(L)return L;f(E);const U=await ee(E),q=(Array.isArray(U.batches)?U.batches:[]).map(Q=>Q).filter(Q=>Q!==null&&typeof Q=="object"&&typeof Q.shardKey=="string"&&Array.isArray(Q.changes)),W=Array.isArray(U.globalChanges)?U.globalChanges:[],{headers:z}=await h(E,H),V=await d.orchestrateApplyCdc(m,{batches:q,headers:z}),re=W.length>0&&t?await t({changes:W}):0;return Response.json({applied:V.applied+re,failed:V.failed,ok:V.ok},{status:200})},O=async(E,H)=>{const L=me(E,["POST"]);if(L)return L;f(E);const{headers:U}=await h(E,H),F=await T(E,U);return Response.json(F,{headers:{"content-type":"application/json"},status:F.failed.length>0?207:200})},I=async(E,H)=>{const L=me(E,["POST"]);if(L)return L;if(f(E),a===void 0||Object.keys(a).length===0||r===void 0)throw new c("Export-tap endpoint requires `exportSinks` + `exportCursorStore` on the worker",{code:"EXPORT_TAP_NOT_CONFIGURED",status:400});const U=await ee(E),F=typeof U.sink=="string"?U.sink:void 0,q=typeof U.limit=="number"&&U.limit>0?U.limit:void 0,W=Qe(U.tables);if(F===void 0)throw new c("Export-tap `sink` must name a configured sink",{code:"BAD_REQUEST",status:400});const z=a[F];if(z===void 0)throw new c(`Export-tap sink "${F}" is not configured`,{code:"NOT_FOUND",status:404});const{headers:V}=await h(E,H),re=W??i(),Q=await $r({coordinator:d,cursorStore:r,defaultShardKey:n,headers:V,limit:q,shardDO:m,sink:z,tables:re});return Response.json(Q,{headers:{"content-type":"application/json"},status:200})};return{[da]:y,[ca]:g,[aa]:k,[ua]:I,[sa]:O,[ia]:w}},pa=(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}},ma=(e,t,n,r,a)=>{if(n?.mode.kind==="shardBy"&&typeof n.mode.field=="string"){const i=e[n.mode.field];return i==null?{error:{code:"BAD_ROW",line:a,message:`row missing shard field "${n.mode.field}" for table "${t}"`,table:t},ok:!1}:{ok:!0,shardKey:typeof i=="string"?i:JSON.stringify(i)}}return{ok:!0,shardKey:r}},wa=async(e,t,n)=>{if(!e.body)throw new c("Import endpoint requires a request body",{code:"BAD_REQUEST",status:400});const r=[],a=[],i=new Map;let d=0,f=0;const h=e.body.getReader(),m=new TextDecoder;let b="",T=0;const S=k=>{f+=1;const w=k.trim();if(w.length===0)return;d+=1;const g=pa(w,f);if(!g.ok){r.push(g.error);return}const{doc:y,table:O}=g,I=t.resolveTableSharding?.(O);if(I?.mode.kind==="global"){a.push({doc:y,line:f,table:O});return}const E=ma(y,O,I,n,f);if(!E.ok){r.push(E.error);return}const H=i.get(E.shardKey);H?H.rows.push({doc:y,table:O}):i.set(E.shardKey,{rows:[{doc:y,table:O}],shardKey:E.shardKey,startLine:f})};for(;;){const{done:k,value:w}=await h.read();if(k)break;if(w&&(T+=w.byteLength,T>an))throw await h.cancel().catch(()=>{}),new c("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});b+=m.decode(w,{stream:!0});let g=b.indexOf(`
5
5
  `);for(;g!==-1;){const y=b.slice(0,g);b=b.slice(g+1),S(y),g=b.indexOf(`
6
- `)}}return b.length>0&&S(b),{errors:r,globalRows:s,perShard:i,received:d}},gs=e=>e.flatMap(t=>t.error?[{message:t.error.message,shardKey:t.shardKey,timedOut:t.error.timedOut}]:[]),Ht=(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},ys=async(e,t,n,r,s)=>{const i=t.defaultShardKey??"__root__",{errors:d,globalRows:f,perShard:h,received:m}=await ws(e,t,i),b={conflicts:0,errors:d,failed:[],inserted:{}},T=[];if(t.resolveTableSharding===void 0&&h.size>0&&T.push("no `resolveTableSharding` is configured, so every row was routed to the default shard and no row could be recognised as `.global()` — correct for a single-shard app, silent misplacement for a sharded one"),h.size>0){const S=await n.orchestrateImport(s,{batches:[...h.values()],headers:r});Ht(b,S),b.failed.push(...gs(S.shards))}if(f.length>0)if(t.importGlobals){const S=f[0]?.line??1,k=await t.importGlobals({rows:f,startLine:S});Ht(b,k)}else for(const S of f)b.errors.push({code:"GLOBAL_NOT_CONFIGURED",line:S.line,message:`row targets global table "${S.table}" but no \`importGlobals\` is configured`,table:S.table});return{conflicts:b.conflicts,errors:b.errors,failed:b.failed,inserted:b.inserted,received:m,...T.length>0?{warnings:T}:{}}},bs=Object.freeze({edges:[],nodes:[],modules:[],unresolved:[],version:1}),We=e=>typeof e=="object"&&e!==null?e:{},ze=e=>typeof e.kind=="string"?e.kind:"unknown",_s=(e,t)=>{let n=We(t),r=!1;ze(n)==="optional"&&(r=!0,n=We(n._meta?.inner));const s=ze(n),i=n._meta??{},d={kind:s,name:e,optional:r};if(s==="id"&&typeof i.tableName=="string"&&(d.table=i.tableName),s==="array"){const f=ze(We(i.inner));f!=="unknown"&&(d.element=f)}return d},Rs=e=>typeof e!="object"||e===null?[]:Object.entries(e).map(([t,n])=>_s(t,n)).toSorted((t,n)=>t.name.localeCompare(n.name)),Es="/_lunora/admin/functions",As="/_lunora/admin/cron-jobs",Ts="/_lunora/admin/architecture",Ss="/_lunora/admin/openapi",Os="/_lunora/admin/openrpc",vs="/_lunora/admin/global/tables",Is="/_lunora/admin/global/table",ks="/_lunora/admin/global/facet",Lt=e=>{if(e===void 0||e==="")return;let t;try{t=Xe(JSON.parse(e))}catch{return}if(!Array.isArray(t))return;const n=t.flatMap(r=>{if(typeof r!="object"||r===null||typeof r.column!="string")return[];const{column:s,value:i}=r;return[{column:s,value:i}]});return n.length===0?void 0:n},Ps=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:{}}),Ds=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"}),Ns=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(([O,I])=>I.visibility==="internal"||I.kind==="stream"?[]:[{args:Rs(I.args),kind:I.kind,path:O}]).toSorted((O,I)=>O.path.localeCompare(I.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(([O,I])=>I.map(E=>({args:E.args,cron:O,functionPath:E.functionPath,name:E.name,shardKey:E.shardKey,workflow:E.workflow}))).toSorted((O,I)=>O.name.localeCompare(I.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??bs,{headers:{"content-type":"application/json"},status:200})),m=w=>(M(w,"GET","OpenAPI"),t(w),Response.json(n.openApiSpec??Ps,{headers:{"content-type":"application/json"},status:200})),b=w=>(M(w,"GET","OpenRPC"),t(w),Response.json(n.openRpcSpec??Ds,{headers:{"content-type":"application/json"},status:200})),T=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})},S=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),O=s(y,"table");if(O===void 0)throw new c("Global-table endpoint requires a `table` query param",{code:"BAD_REQUEST",status:400});const I=await g.readTablePage({...r(w),filters:Lt(s(y,"filters")),table:O});return Response.json(I,{headers:{"content-type":"application/json"},status:200})},k=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),O=s(y,"table"),I=s(y,"column");if(O===void 0||I===void 0)throw new c("Global-facet endpoint requires `table` and `column` query params",{code:"BAD_REQUEST",status:400});const E=s(y,"limit"),H=E===void 0?void 0:Number(E),L=await g.facetColumn({column:I,filters:Lt(s(y,"filters")),limit:H!==void 0&&Number.isFinite(H)?H:void 0,table:O});return Response.json(L,{headers:{"content-type":"application/json"},status:200})};return{[As]:f,[Es]:d,[ks]:k,[Is]:S,[vs]:T,[Ts]:h,[Ss]:m,[Os]:b}},Us="/_lunora/admin/kv/namespaces",Cs="/_lunora/admin/kv/keys",Rn="/_lunora/admin/kv/value",En=32*1048576,jt=60,Bs=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),O=y.searchParams.get("namespace")??"",I=y.searchParams.get("key")??"";if(O==="")throw new c(`KV-value ${g} request requires a \`namespace\` query parameter`,{code:"BAD_REQUEST",status:400});if(I==="")throw new c(`KV-value ${g} request requires a \`key\` query parameter`,{code:"BAD_REQUEST",status:400});return{key:I,namespace:O}},d=async(w,g)=>{if(!(await w.listNamespaces()).some(O=>O.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),O=y.searchParams.get("namespace")??"";if(O==="")throw new c("KV-keys request requires a `namespace` query parameter",{code:"BAD_REQUEST",status:400});const I=y.searchParams.get("prefix")??void 0,E=y.searchParams.get("cursor")??void 0,H=y.searchParams.get("limit"),L=H===null?void 0:Number.parseInt(H,10);if(L!==void 0&&(!Number.isInteger(L)||L<1))throw new c("KV-keys `limit` must be a positive integer",{code:"BAD_REQUEST",status:400});const U=L===void 0?void 0:Math.min(L,1e3);return await d(g,O),s(await g.listKeys({cursor:E,limit:U,namespace:O,prefix:I}))},S={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,En);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<jt))throw new c("KV-value PUT `expirationTtl` must be an integer ≥ 60",{code:"BAD_REQUEST",status:400});const O=Math.floor(Date.now()/1e3)+jt;if(y.expiration!==void 0&&(typeof y.expiration!="number"||!Number.isInteger(y.expiration)||y.expiration<O))throw new c("KV-value PUT `expiration` must be a Unix-seconds timestamp at least 60 seconds in the future",{code:"BAD_REQUEST",status:400});return await 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})}},k=w=>{const g=S[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{[Us]:f,[Cs]:h,[Rn]:k}},xs="/_lunora/migrate",Hs="/_lunora/admin/pitr",Ls="/_lunora/admin/rank",js="/_lunora/admin/rankpage",Ms="/_lunora/admin/shard-registry/prune",$s="/_lunora/admin/shard-traffic",Ks=new Set(["__lunora_admin__:migrationStatus","__lunora_admin__:runMigration"]),Fs=new Set(["__lunora_admin__:getPitrBookmark","__lunora_admin__:pitrRestore"]),Gs=async e=>{const n=await ne(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"||!Ks.has(n.functionPath))throw new c("Migration request `functionPath` must be a migration admin op",{code:"BAD_REQUEST",status:400});return{args:n.args??{},functionPath:n.functionPath,table:n.table}},Qs=async e=>{const n=await ne(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}},Ws=e=>{if(e!==void 0){if(!Array.isArray(e)||e.some(t=>t!=="asc"&&t!=="desc"))throw new c('Rank page request `directions` must be an array of "asc"|"desc"',{code:"BAD_REQUEST",status:400});return e}},zs=e=>{if(typeof e.table!="string"||e.table.length===0)throw new c("Rank page request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof e.index!="string"||e.index.length===0)throw new c("Rank page request is missing `index`",{code:"BAD_REQUEST",status:400});if(e.partitionKey!==void 0&&typeof e.partitionKey!="string")throw new c("Rank page request `partitionKey` must be a string",{code:"BAD_REQUEST",status:400});if(e.take!==void 0&&(typeof e.take!="number"||!Number.isFinite(e.take)))throw new c("Rank page request `take` must be a number",{code:"BAD_REQUEST",status:400});if(e.cursor!==void 0&&e.cursor!==null&&typeof e.cursor!="string")throw new c("Rank page request `cursor` must be a string or null",{code:"BAD_REQUEST",status:400})},Vs=async e=>{const n=await ne(e,"Rank page")??{};zs(n);const r=Ws(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}},Js=async e=>{const n=await ne(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}},Ys=async e=>{const n=await ne(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}},qs=async e=>{const n=await ee(e);if(typeof n.functionPath!="string"||!Fs.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}},Xs=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 O=await Gs(g),{headers:I}=await i(g,y),E=await s.orchestrateMigration(d,{args:O.args,defaultShardKey:t,functionPath:O.functionPath,headers:I,table:O.table});return Response.json(E,{headers:{"content-type":"application/json"},status:200})},b=async(g,y)=>{h(g,"Rank");const O=await Qs(g),{headers:I}=await i(g,y),E=await s.orchestrateRank(d,{headers:I,index:O.index,partitionKey:O.partitionKey,rowId:O.rowId,sortValues:O.sortValues,table:O.table});return Response.json(E,{headers:{"content-type":"application/json"},status:200})},T=async(g,y)=>{h(g,"Rank page");const O=await Vs(g),{headers:I}=await i(g,y),E=await s.orchestrateRankPage(d,{...O,headers:I});return Response.json(E,{headers:{"content-type":"application/json"},status:200})},S=async(g,y)=>{h(g,"Shard-traffic");const O=await Js(g),{headers:I}=await i(g,y),E=await s.orchestrateShardTraffic(d,{headers:I,table:O.table});return Response.json(E,{headers:{"content-type":"application/json"},status:200})},k=async(g,y)=>{h(g,"Shard-registry prune");const O=await Ys(g),I=f(),E=(O.tables??[]).filter(U=>!I.includes(U));if(E.length>0)throw new c(`Shard-registry prune names tables that are not \`.shardBy()\`: ${E.join(", ")}`,{code:"BAD_REQUEST",status:400});const{headers:H}=await i(g,y),L=await Yr(s.registry,d,{dryRun:O.dryRun,headers:H,tables:O.tables??I});return Response.json(L,{status:L.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 O=await qs(g),{headers:I}=await i(g,y),E=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:O.args,functionPath:O.functionPath}),headers:I,method:"POST"});return n(d,O.shardKey??t,E)};return{[xs]:m,[Hs]:w,[Ls]:b,[js]:T,[Ms]:k,[$s]:S}},Zs=1,ea=0,ta=32,na=512,ra=/^[a-z][\d_a-z*/-]{0,255}(?:@[a-z][\d_a-z*/-]{0,13})?=[\u0020-\u002B\u002D-\u003C\u003E-\u007E]{1,256}$/,oa=e=>{if(e==null)return;const t=e.trim();if(t.length===0||t.length>na)return;const n=t.split(",");if(!(n.length>ta)){for(const r of n)if(!ra.test(r.trim()))return;return t}},sa=e=>{const t=Er(e.headers.get("traceparent"));if(t===void 0)return;const n=oa(e.headers.get("tracestate"));return{parentSpanId:t.parentSpanId,sampled:t.sampled,traceId:t.traceId,...n===void 0?{}:{traceState:n}}},Mt=(e,t={})=>{const n=sa(e),r=t.trustInbound===!0?n:void 0,s=we(8),i=r?.traceId??we(16),d=vr(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?Zs:ea,traceId:i,...r?.parentSpanId===void 0?{}:{parentSpanId:r.parentSpanId},...r?.traceState===void 0?{}:{traceState:r.traceState},...f===void 0?{}:{rayId:f}}}},$t=(e,t)=>{t.traceparent=on(e.traceId,e.spanId,e.sampled),e.traceState!==void 0&&(t.tracestate=e.traceState),e.rayId!==void 0&&(t[lo]=e.rayId)},aa=(e,t)=>{let n;return()=>{if(n===void 0){const r=Or(e),s=t===void 0?void 0:t.cf;n=Ar(Sr(r),Tr(r,s))}return n}},ia="/_lunora/admin/scheduled",ca="/_lunora/admin/scheduled/status",da="/_lunora/admin/scheduled/ws",ua="/_lunora/admin/scheduled/cancel",la="/_lunora/admin/scheduled/dead",ha="/_lunora/admin/scheduled/dead/retry",fa="/_lunora/admin/scheduled/dead/cancel",pa="/_lunora/admin/scheduled/pool/release",ma=e=>{const{checkWsAdmin:t,requireSchedulerNamespace:n,resolveSchedulerStub:r,schedulerInstanceName:s}=e,i=(m,b)=>T=>{if(T.method!=="GET")throw new c(`${b} endpoint requires GET`,{code:"METHOD_NOT_ALLOWED",status:405});const S=new URL(T.url).searchParams.get("cursor"),k=S===null||S===""?"":`?cursor=${encodeURIComponent(S)}`;return r(T).fetch(new Request(`https://scheduler.internal${m}${k}`,{method:"GET"}))},d=(m,b,T=b)=>async S=>{if(S.method!=="POST")throw new c(`${T} requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});const k=r(S),w=await ne(S,b);if(typeof w?.id!="string"||w.id==="")throw new c(`${b} requires a string \`id\``,{code:"BAD_REQUEST",status:400});return k.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 b=r(m),T=await ne(m,"Scheduled pool-release");if(typeof T?.pool!="string"||T.pool==="")throw new c("Scheduled pool-release requires a string `pool`",{code:"BAD_REQUEST",status:400});const S=typeof T.id=="string"&&T.id!==""?T.id:void 0;return b.fetch(new Request("https://scheduler.internal/complete",{body:JSON.stringify(S===void 0?{pool:T.pool}:{id:S,pool:T.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 b=n();return ge(b,s).fetch(new Request("https://scheduler.internal/ws",{headers:{Upgrade:"websocket"}}))};return{[ua]:d("/cancel","Scheduled-cancel","Scheduled-cancel endpoint"),[fa]:d("/dead/cancel","Scheduled dead-letter action"),[la]:i("/dead","Scheduled dead-letter"),[ha]:d("/dead/retry","Scheduled dead-letter action"),[ia]:i("/list","Scheduled-list"),[pa]:f,[ca]:i("/status","Scheduler-status"),[da]:h}},wa="/_lunora/scheduled",An="/_lunora/queue",Tn=16*1048576,ga=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 ne(d,"Scheduled tick"),b=typeof m?.cron=="string"?m.cron:"";if(b==="")throw new c("scheduled tick requires a `cron` expression",{code:"BAD_REQUEST",status:400});return await n({cron:b,noRetry:()=>{},scheduledTime:Date.now()},f,h),Response.json({cron:b,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 ne(d,"Queue dispatch",Tn);if(!Array.isArray(m?.messages))throw new c("queue dispatch requires a `messages` array",{code:"BAD_REQUEST",status:400});const b=typeof m.queue=="string"?m.queue:"",T=m.messages.filter(k=>typeof k=="object"&&k!==null&&typeof k.id=="string").map(k=>({body:k.body,id:k.id})),S=await r({messages:T,queue:b},f,h);return Response.json({retry:S?.retry??[]})};return{[An]:i,[wa]:s}},ya=(e,...t)=>{let n=e.cf;for(const r of t){if(typeof n!="object"||n===null)return;n=n[r]}return typeof n=="string"?n:void 0},nt={mtls:e=>ya(e,"tlsClientAuth","certVerified")==="SUCCESS"},ba=e=>e===void 0||e===!1?()=>!1:e===!0?()=>!0:typeof e=="function"?e:(Object.hasOwn(nt,e)?nt[e]:void 0)??(()=>!1),_a=e=>typeof e=="string"&&Object.hasOwn(nt,e),Ra=e=>{const t=_a(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.`))}},Ea="/_lunora/admin/vector/indexes",Aa="/_lunora/admin/vector/query",Ta=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{[Ea]:r,[Aa]:s}},Sa="/_lunora/admin/workflows/instances",Oa="/_lunora/admin/workflows/instance",va="/_lunora/admin/workflows/status",Ia={complete:!0,errored:!0,paused:!0,queued:!0,running:!0,terminated:!0,unknown:!0,waiting:!0,waitingForPause:!0},ka=e=>e!==null&&Object.hasOwn(Ia,e)?e:void 0,Kt=(e,t)=>{const n=e.searchParams.get(t);if(n===null)return;const r=Number(n);return Number.isInteger(r)&&r>0?r:void 0},Ve=(e,t)=>{const n=e.searchParams.get(t);if(n===null||n==="")throw new c(`Workflows admin endpoint requires a \`${t}\` query parameter`,{code:"BAD_REQUEST",status:400});return n},Ft=()=>{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})},Pa=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 b=Ve(h,"name"),T=ka(h.searchParams.get("status"));return Response.json(await m.listInstances({page:Kt(h,"page"),perPage:Kt(h,"perPage"),status:T,workflowName:b}))},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")})):Ft()},i=async(d,f)=>{M(d,"POST","Workflows status"),t(d);const h=n(f);if(!h)return Ft();const m=await ne(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:b}=m;if(b!=="pause"&&b!=="resume"&&b!=="terminate")throw new c("Workflows status action must be one of: pause, resume, terminate",{code:"BAD_REQUEST",status:400});return Response.json(await h.setInstanceStatus({action:b,instanceId:m.id,workflowName:m.name}))};return{[Oa]:s,[Sa]:r,[va]:i}},Da={[Rn]:En,[An]:Tn,[Mr]:jr},Gt="/_lunora/rpc",Na="/_lunora/rpc-batch",Ua="/_lunora/ws",Ae=(e,t,n)=>({resourceAttributes:aa(e,t),...n===void 0?{}:{waitUntil:n}}),Je=e=>e?.waitUntil?{waitUntil:t=>e.waitUntil?.(t)}:{},Qt=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=fo(e.headers.get(uo)),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}},Wt="/_lunora/voice/",Ca="/_lunora/admin/cron-jobs/run",Ba="/_lunora/admin/ws-token",xa="/_lunora/admin/",Ce="/_lunora/",Ha="/_lunora/migrate",La="/_lunora/status",ja=e=>e.startsWith(xa)||e===Ha,ke=e=>{if(ko(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})},Pe=async e=>await e===!0,zt=(e,t)=>{const n=e.headers.get(gt);if(n===null)return;const r=Rr(n);if(r===void 0)throw new c(`malformed ${gt} 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})},Vt="/api/auth",Ma="__lunora_admin__:recordAuthEvent",Jt="__lunora_admin__:listPushSubscriptions",$a=["/sign-in","/sign-up","/callback"],Ka=(e,t)=>{const n=t.endsWith("/")?t.slice(0,-1):t;if(!e.startsWith(`${n}/`))return!1;const r=e.slice(n.length);return $a.some(s=>r===s||r.startsWith(`${s}/`))},Yt=(e,t)=>{const n=t.endsWith("/")?t.slice(0,-1):t;return e===n||e.startsWith(`${n}/`)},De=(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}=co(n);return{durationMs:t,error:{code:i,message:f,name:h,status:d,...m===void 0?{}:{stack:m}},functionPath:e,ok:!1,...r.fanOut?{fanOut:{failed:0,shards:0,table:r.fanOut.table}}:{},...r.shardKey?{shardKey:r.shardKey}:{}}},Sn=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},On=({identity:e})=>e!==null&&yr(Sn(e)),Fa=e=>{if(On(e))throw new c("authentication token expired",{code:"TOKEN_EXPIRED",status:401});return e},Ga=e=>{if(!On(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}},qt=e=>e.waitUntil?{waitUntil:t=>{e.waitUntil?.(t)}}:void 0,Qa=e=>{const t=e?.queue;return typeof t=="string"&&t.length>0?t:"unknown"},rt=new WeakMap,Wa=async(e,t,n,r,s=rt.get(e))=>{const i={"content-type":"application/json"},d=e.headers.get("authorization"),f=e.headers.get("cookie"),h=e.headers.get("x-d1-bookmark"),m=e.headers.get("x-lunora-mutation-id"),b=e.headers.get("x-lunora-client-id"),T=e.headers.get("x-lunora-client-seq"),S=e.headers.get("x-lunora-base-seq");d&&(i.authorization=d),f&&(i.cookie=f),h&&(i["x-d1-bookmark"]=h),m&&(i["x-lunora-mutation-id"]=m),b&&(i["x-lunora-client-id"]=b),T&&(i["x-lunora-client-seq"]=T),S&&(i["x-lunora-base-seq"]=S);const k=Ur(e.headers,r);if(k&&(i["x-lunora-client-ip"]=k),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"]=br(w.userId);const g=Sn(w);g!==void 0&&(i["x-lunora-identity-exp"]=String(g));const{userId:y,...O}=w,I=Object.keys(O).length>0?O:null;return I&&(i["x-lunora-identity"]=_r(I)),{claims:I,headers:i,identity:w,userId:y}},za=new Set(["concat","first","groupBy","max","min","rank","sum","topK"]),Va=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"||!za.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},Ja=(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}},Ya=async e=>{const t=await cn(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&&an(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=Va(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}},Ne=new Map,qa=5e3,Xa=4096,Za=async(e,t)=>{const n=Date.now(),r=Ne.get(t);if(r!==void 0&&r.expiresMs>n)return r.relayCount;r!==void 0&&Ne.delete(t);let s=0;try{const i=await ge(e,t).fetch(new Request("https://shard.internal/_lunora/route"));if(i.ok){const f=(await i.json()).relayCount;typeof f=="number"&&f>0&&(s=Math.floor(f))}}catch{s=0}return tn(Ne,Xa),Ne.set(t,{expiresMs:n+qa,relayCount:s}),s},Xt=(e,t)=>{if(!(e===null||typeof e!="object"))return Object.entries(e).find(([,n])=>n===t)?.[0]},Ue=(e,t,n)=>new Request("https://shard.internal/rpc",{body:JSON.stringify({args:t,functionPath:e}),headers:n,method:"POST"}),ei=["x-lunora-userid","x-lunora-identity","x-lunora-identity-exp","x-lunora-client-ip"],ti=(e,t)=>{for(const n of ei){e.delete(n);const r=t[n];r!==void 0&&e.set(n,r)}},Zt=(e,t)=>{const n=new Headers(e.headers),r=[...n.keys()];for(const s of r)s.startsWith("x-lunora-")&&n.delete(s);return ti(n,t),n},en=async(e,t)=>{if(!t||t.length===0)return!1;const n=new URL(e.url).searchParams.get("token");return n===null?!1:Ho(t,n)},ni=(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 zr(`d1:${e}`,t);if(typeof n.list=="function"&&typeof n.head=="function"&&typeof n.createMultipartUpload=="function")return $e(`r2:${e}`,!0);if(typeof n.send=="function"&&typeof n.sendBatch=="function"&&typeof n.get!="function")return $e(`queue:${e}`,!0);if(typeof n.connectionString=="string")return $e(`hyperdrive:${e}`,!0)},ri=e=>{for(const t of Object.keys(e??{}))if(t.slice(t.indexOf(" ")+1).startsWith(Ce))throw new c(`route "${t}" is under the reserved ${Ce} 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})},oi=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})},vn=e=>{oi(e);const t=ba(e.trustInboundTraceContext),n=Ra(e.trustInboundTraceContext),r=e.defaultShardKey??"__root__",s=e.queryCoordinator??qr({registry:Xr(e.resolveTableSharding,r)}),i=Vr(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 b=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.`))},T=async(o,a,l,u=e.shardRegion?.(a))=>ge(o,a,b(u)).fetch(l);let S;const k=()=>e.adminToken??S;let w;const g=o=>{const a=o??{};if(w??=Xt(o,e.shardDO),S!==void 0||e.adminToken!==void 0)return;const l=a.LUNORA_ADMIN_TOKEN;typeof l=="string"&&l.length>0&&(S=l)},y=new WeakSet,O=o=>pn(o,k())||y.has(o),I=async o=>{if(!(e.adminGate===void 0||y.has(o)))try{await Pe(e.adminGate(o,rt.get(o)))&&y.add(o)}catch{}},E=async(o,a,l,u)=>{const p=await Wa(o,a,l,e.trustedClientIpHeader,u);return e.functions!==void 0&&(p.headers[rn]=nn),p},H=async(o,a,l,u)=>Fa(await E(o,a,l,u)),L=async(o,a)=>{const l=await E(o,a,e.resolveIdentity);if(y.has(o)&&l.headers.authorization===void 0){const u=k();u!==void 0&&(l.headers.authorization=`Bearer ${u}`)}return l};let U=!1,F=!1;const q=()=>{F||(F=!0,console.warn("[lunora] `replicaReads: true` has no effect without `functions` — read eligibility is decided from the function registry."))},W=o=>{if(!e.allowUnauthenticatedShardAccess){const 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})}U||(U=!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("")))},z=async(o,a,l=!1)=>{if(a.includes(Ze)||a.includes(et))throw new c("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403});if(!l)if(e.authorizeShard){if(!await Pe(e.authorizeShard({identity:o,shardKey:a})))throw new c("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else a!==r&&W("shard")},V=Xs({defaultShard:r,forwardToShard:T,isAdmin:O,queryCoordinator:s,resolveForwardContext:L,shardDO:d,shardedTables:()=>(e.listSchemaTables?.()??[]).filter(o=>e.resolveTableSharding?.(o)?.mode.kind==="shardBy")}),re=async(o,a,l,u,p,R)=>{ke(o);const v=Do({forwardedIdentity:p,mutationId:u,traceparent:R});return T(d,l,Ue(o,a,v))},Q=async(o,a,l,u,p)=>{const R=Co(l.env,l.context?.exports,o,["create"]);if(R===void 0)throw new c(`${u} targets workflow "${o}", which is on neither ctx.exports nor env`,{code:"CRON_JOB_FAILED",status:500});if(no(a))throw new c(`${u} params ${ro}`,{code:"BAD_REQUEST",status:400});try{await R.create(p===void 0?{params:a}:{id:p,params:a})}catch(v){if(!ao(v))throw v}},ce=async(o,a,l,u)=>{if(o.workflow){await Q(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 re(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})},$=o=>{if(!O(o))throw new c("admin endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403})},oe=(o,a,l)=>{if($(o),a===void 0)throw new c(l.message,{code:l.code,status:400});return a},Be=async(o,a,l,u,p,R)=>{const v=e.cronJobs?.[o];if(!v)return 0;for(const P of v)try{await ce(P,a,l,R)}catch(D){u.push(p(D))}return v.length},xe=async(o,a,l)=>{if($(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 ee(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 R=Object.values(e.cronJobs).flat().find(v=>v.name===p);if(!R)throw new c(`no cron job named "${p}" is registered`,{code:"CRON_JOB_NOT_FOUND",status:404});return await ce(R,a,l),Response.json({name:p,ran:!0},{status:200})},se=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 ge(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{}},In=async(o,a,l)=>{M(o,"POST","Scheduler dispatch");const u=await cn(o),p=a??{},R=typeof p.LUNORA_SCHEDULER_SECRET=="string"?p.LUNORA_SCHEDULER_SECRET:void 0,v=e.adminToken??(typeof p.LUNORA_ADMIN_TOKEN=="string"?p.LUNORA_ADMIN_TOKEN:void 0);if(!await Po(o,u,{adminToken:v,schedulerSecret:R}))throw new c("Scheduler dispatch requires a valid signature or admin bearer",{code:"DISPATCH_UNAUTHENTICATED",status:403});let D;try{D=JSON.parse(u)}catch{throw new c("Scheduler dispatch body must be valid JSON",{code:"BAD_REQUEST",status:400})}const _=D??{},A=_.args??{},B=typeof _.id=="string"&&_.id.length>0?_.id:void 0;if(typeof _.workflow=="string"&&_.workflow.length>0)return await Q(_.workflow,A,{context:l,env:a},"scheduled workflow",B),await se(_),Response.json({ok:!0},{status:200});if(typeof _.functionPath!="string"||_.functionPath.length===0)throw new c("Scheduler dispatch is missing `functionPath`",{code:"BAD_REQUEST",status:400});const j=typeof _.shardKey=="string"&&_.shardKey.length>0?_.shardKey:r,J=No(o),x=await re(_.functionPath,A,j,B,J,o.headers.get("traceparent")??void 0);return await se(_),x},kn=$o({assertAdmin:$,getReader:()=>e.authAuditReader}),Pn=Ko({assertAdmin:$,getMove:()=>e.authJurisdictionMove}),Dn=async(o,a)=>{$(o);const l=e.notifySubscriptionStore;if(l===void 0)return Response.json({result:Te({subscriptions:[]})},{headers:{"content-type":"application/json"},status:200});const u=a?.kind,p=a?.userId,R=a?.limit,v=u==="fcm"||u==="web-push"?u:void 0,P=typeof p=="string"&&p!==""?p:void 0,D=typeof R=="number"&&Number.isFinite(R)?Math.trunc(R):0,_=D>0?Math.min(D,1e3):1e3,B=(await l.list({kind:v,limit:_,userId:P})).filter(j=>v!==void 0&&j.kind!==v?!1:P===void 0||(j.userId??null)===P).map(({keys:j,token:J,...x})=>x);return Response.json({result:Te({subscriptions:B})},{headers:{"content-type":"application/json"},status:200})},Nn=async(o,a)=>{if(!a.fanOut&&!(a.functionPath!==Pt&&a.functionPath!==Jt&&a.functionPath!==tt&&a.functionPath!==gn))return await I(o),a.functionPath===Pt?kn(o,a.args??{}):a.functionPath===Jt?Dn(o,a.args):Pn(o,a.functionPath,a.args??{})},Un=fs({applyGlobals:e.applyGlobals,assertAdmin:$,exportCursorStore:e.exportCursorStore,exportSinks:e.exportSinks,defaultShardKey:r,knownTables:()=>[...e.listSchemaTables?.()??[]],queryCoordinator:s,resolveForwardContext:L,shardDO:d,prepareExportRows:async(o,a)=>yn(e,s,o,a,d),streamingImport:(o,a)=>ys(o,e,s,a,d),syncGlobals:e.syncGlobals}),He=(o,a)=>{const l=o.searchParams.get(a);return l===null||l===""?void 0:l},Le=o=>{const a=new URL(o.url),l=a.searchParams.get("limit"),u=a.searchParams.get("offset"),p=l===null?void 0:Number.parseInt(l,10),R=u===null?void 0:Number.parseInt(u,10);return{limit:p!==void 0&&Number.isFinite(p)&&p>=0?p:void 0,offset:R!==void 0&&Number.isFinite(R)&&R>=0?R:void 0}},ct=()=>{if(f===void 0)throw new c("scheduled endpoints require a `schedulerDO` namespace on the worker",{code:"SCHEDULER_NOT_CONFIGURED",status:400});return f},Cn=ma({checkWsAdmin:async o=>O(o)||en(o,k()),requireSchedulerNamespace:ct,resolveSchedulerStub:o=>($(o),ge(ct(),e.schedulerInstanceName??"default")),schedulerInstanceName:e.schedulerInstanceName??"default"}),Bn=Pa({assertAdmin:$,resolveWorkflowsClient:e.workflowsClient??(()=>{})}),xn=Lr({assertAdmin:$,parsePaging:Le,queryParameter:He,readBodyBytes:Dr,requireAdminOption:oe,storage:{storageBuckets:e.storageBuckets,storageDelete:e.storageDelete,storageDownload:e.storageDownload,storageList:e.storageList,storageSignedUrl:e.storageSignedUrl,storageUpload:e.storageUpload}}),Hn=ns({options:e,readJsonBody:ee,requireAdminOption:oe}),Ln=Ta({readJsonBody:ee,requireAdminOption:oe,vectorIntrospector:e.vectorIntrospector}),jn=Bs({kvIntrospector:e.kvIntrospector,readJsonBody:ee,requireAdminOption:oe}),Mn=Jr({logArchive:e.logArchive,readJsonBody:ee,requireAdminOption:oe}),$n=Ns({assertAdmin:$,options:{cronJobs:e.cronJobs,functions:e.functions,globalIntrospector:e.globalIntrospector,architecture:e.architecture,openApiSpec:e.openApiSpec,openRpcSpec:e.openRpcSpec},parsePaging:Le,queryParameter:He,requireAdminOption:oe}),Kn=o=>{const a=[],l=d??o?.SHARD;if(l!==void 0&&a.push(Wr("durable-object:default",l,r)),e.health?.disableBindingProbes!==!0)for(const[u,p]of Object.entries(o??{})){const R=ni(u,p);R!==void 0&&a.push(R)}for(const u of e.health?.probes??[])a.push(u);return a},Fn=Qr({appName:e.health?.appName,appVersion:e.health?.appVersion,auth:e.health?.auth??"public",cacheTtlMs:e.health?.cacheTtlMs,isAdmin:O,resolveProbes:Kn}),Gn=o=>{const a=_=>"args"in _?{..._,args:Xe(_.args)}:_,l=e.schedulerInstanceName??"default",u=()=>ge(o,l),p=async(_,A)=>{const B=await u().fetch(new Request(`https://scheduler.internal${_}`,A));if(!B.ok)throw new c(`ctx.scheduler: SchedulerDO ${_} failed (${String(B.status)}): ${await B.text()}`,{code:"INTERNAL",status:500});return await B.json()},R=async(_,A)=>await p(_,{body:JSON.stringify(A),headers:{"content-type":"application/json"},method:"POST"}),v=_=>{const A=_;if(A==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 A.binding=="string"&&A.binding.length>0)return{workflow:A.binding};if(typeof A.__lunoraRef=="string")return{functionPath:A.__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})},P=async()=>(await oo(async A=>p(A===void 0?"/list":`/list?cursor=${encodeURIComponent(A)}`,{method:"GET"}))).map(A=>a(A)),D=async(_,A,B={})=>{const j=v(A),{id:J}=await R("/schedule",{args:wr("ctx.scheduler",String(j.functionPath??j.workflow),B),scheduledFor:Math.ceil(_),...j});return J};return{cancel:async _=>await R("/cancel",{id:_}),get:async _=>{const A=await p(`/get?id=${encodeURIComponent(_)}`,{method:"GET"});return A.record===void 0?null:a(A.record)},list:P,runAfter:async(_,A,B)=>{if(!Number.isFinite(_)||_<0)throw new c("ctx.scheduler.runAfter: `delayMs` must be a non-negative finite number",{code:"INVALID_INPUT",status:400});return await D(Date.now()+_,A,B)},runAt:async(_,A,B)=>{if(!Number.isFinite(_))throw new c("ctx.scheduler.runAt: `date` must be a non-negative finite number",{code:"INVALID_INPUT",status:400});return await D(_,A,B)}}},Qn=async(o,a,l)=>{const{claims:u,headers:p,userId:R}=Ga(await E(o,a,i)),v=Ae(a,o,_=>l.waitUntil?.(_)),P=_=>async(A,B={})=>{const j=A.__lunoraRef;if(typeof j!="string")throw new c("ctx.run*: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});ke(j);const J=await Oe(o,j,Te(B),_,{...p,"x-lunora-system":"1"},v),x=await J.json();if(x.error)throw new c(x.error.message??"shard RPC failed",{code:x.error.code??"INTERNAL",status:J.status});return Xe(x.result)},D=P(r);return{auth:{getIdentity:()=>Promise.resolve(u),userId:R},cache:l.cache,fetch:globalThis.fetch.bind(globalThis),forShard:_=>{const A=P(_);return{runAction:A,runMutation:A,runQuery:A}},runAction:D,runMutation:D,runQuery:D,...f===void 0?{}:{scheduler:Gn(f)},...l.waitUntil===void 0?{}:{waitUntil:l.waitUntil.bind(l)},...e.storage===void 0?{}:{storage:to(e.storage(a,new URL(o.url).origin))}}},Wn=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})}},zn=async(o,a,l)=>{if(o.headers.get("Upgrade")!=="websocket")throw new c("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});const u=At(o,ae);if(u)return u;const p=l.searchParams.get("shard")??r,{headers:R,identity:v}=await E(o,a,i),P=O(o)||await en(o,k());await z(v,p,P);const D=Zt(o,R),_=Xt(a,e.shardDO);if(_!==void 0){D.set("x-lunora-shard-binding",_);const A=await Za(d,p);if(A>0){const B=bo(p,Math.floor(Math.random()*A));return T(d,B,new Request(o,{headers:D}),vt(o))}}return T(d,p,new Request(o,{headers:D}))},Vn=async(o,a,l)=>{if(h===void 0)return new Response("Not found",{status:404});if(o.headers.get("Upgrade")!=="websocket")return new Response("Expected a WebSocket upgrade",{headers:{allow:"GET"},status:426});const u=At(o,ae);if(u)return u;let p;try{p=decodeURIComponent(l.pathname.slice(Wt.length))}catch{return new Response("Unknown voice agent",{status:404})}const R=Object.hasOwn(h,p)?h[p]:void 0;if(R===void 0)return new Response("Unknown voice agent",{status:404});const v=l.searchParams.get("threadKey");if(v===null||v.length===0)return new Response("Missing threadKey",{status:400});const{headers:P,identity:D}=await E(o,a,i);if(e.authorizeShard){if(!await Pe(e.authorizeShard({identity:D,shardKey:v})))throw new c("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else W("shard");const _=Zt(o,P);return T(R,v,new Request(o,{headers:_}))},Jn=async(o,a,l)=>{if(e.authorizeFanOut){if(!await Pe(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});W("fan-out")},Se=async(o,a)=>{if(!(!o.fanOut&&o.functionPath.startsWith("__lunora_admin__:"))){if(o.fanOut){await Jn(o.fanOut,o.functionPath,a);return}await z(a,o.shardKey??r)}},Yn=(o,a,l)=>{if(e.replicaReads!==!0)return;if(e.functions===void 0){q();return}if(e.functions[a]?.kind!=="query"||l.includes(et)||l.includes(Ze))return;const u=vt(o);return u===void 0?void 0:{name:_o(l,u),region:u}},qn=async(o,a,l,u,p)=>{const R=Yn(o,a,u);if(R!==void 0){const v={...p,"x-lunora-replica-read":"1",...w===void 0?{}:{"x-lunora-shard-binding":w}},P=Ro(o.headers.get("x-lunora-min-seq"));P!==void 0&&(v["x-lunora-min-seq"]=String(P));const D=await T(d,R.name,Ue(a,l,v),R.region);if(D.status!==421)return D}return T(d,u,Ue(a,l,p))},Oe=async(o,a,l,u,p,R)=>{const v=Date.now(),{observability:P,sampling:D}=e,_=Ye(o),{decision:A,ignoredUpstream:B,trace:j}=Mt(o,{..._.rayId===void 0?{}:{rayId:_.rayId},...D===void 0?{}:{sampling:D},trustInbound:t(o)});B&&n(o);const J={...p,[bt]:A.keepErrors?"1":"0",[Tt]:"1"};$t(j,J);try{const x=await qn(o,a,l,u,J),fe=Ot(x.headers.get(St));ie(P,{..._,...Qt(j),durationMs:Date.now()-v,functionPath:a,ok:x.ok,shardKey:u,...x.ok?{}:{error:{...fe,code:fe?.code??"SHARD_ERROR",message:fe?.message??`shard returned ${String(x.status)}`,status:x.status}}},R,void 0,{isTraced:j.sampled,keepErrors:A.keepErrors});const ye=new Response(x.body,{headers:x.headers,status:x.status,statusText:x.statusText});return ye.headers.set("x-lunora-shard-key",u),ye.headers.delete(St),ye}catch(x){throw ie(P,{..._,...Qt(j),...De(a,Date.now()-v,x,{shardKey:u})},R,void 0,{isTraced:j.sampled,keepErrors:A.keepErrors}),x}},Xn=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)},Zn=async(o,a,l)=>{M(o,"POST","RPC");const u=await Ya(o);Ja(a,u),Xn(u);const p=await Nn(o,u);if(p!==void 0)return p;const{headers:R,identity:v}=await H(o,a,i);zt(o,v),await Se(u,v);const P=qe(u,e);{const D=Date.now(),{observability:_}=e,A=Ye(o),B=Ae(a,o,l&&(x=>l.waitUntil?.(x)));if(u.fanOut)try{const x=await s.fanOut(d,{args:u.args??{},fanOut:u.fanOut,functionPath:u.functionPath,headers:R});return ie(_,{durationMs:Date.now()-D,fanOut:{failed:x.failed,shards:x.ok+x.failed,table:u.fanOut.table},functionPath:u.functionPath,...A,ok:!0},B),Response.json(x,{headers:{"content-type":"application/json"},status:200})}catch(x){throw ie(_,{...De(u.functionPath,Date.now()-D,x,{fanOut:{table:u.fanOut.table}}),...A},B),x}const j=u.shardKey??r,J=()=>Oe(o,u.functionPath,u.args??{},j,R,B);return P&&e.x402Charge?e.x402Charge(o,{functionPath:u.functionPath,price:P.price},J,Je(l)):J()}},er=async(o,a,l)=>{M(o,"POST","RPC batch");const u=await ee(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:R,identity:v}=await H(o,a,i);zt(o,v);const P=os(p,r);for(const K of P.values())for(const G of K)if(e.functions?.[G.functionPath]?.x402)throw new c(`paid (\`.x402\`) function "${G.functionPath}" cannot be called in a batch; dispatch it individually over ${Gt}`,{code:"BAD_REQUEST",status:400});await Promise.all([...P.entries()].flatMap(([K,G])=>G.map(X=>Se({args:X.args,functionPath:X.functionPath,shardKey:K},v))));const{observability:D,sampling:_}=e,A=Ae(a,o,l&&(K=>l.waitUntil?.(K))),B=Ye(o),{decision:j,ignoredUpstream:J,trace:x}=Mt(o,{...B.rayId===void 0?{}:{rayId:B.rayId},..._===void 0?{}:{sampling:_},trustInbound:t(o)});J&&n(o);const fe={isTraced:x.sampled,keepErrors:j.keepErrors},ye=K=>{const G={...R,"content-type":"application/json",[bt]:j.keepErrors?"1":"0",[Tt]:"1"};return $t({...x,spanId:K},G),G},je=K=>({parentSpanId:K,spanId:we(8),traceFlags:x.traceFlags,traceId:x.traceId}),Ie=[],Me=[],ht=(K,G,X,de)=>({body:{error:{code:X,message:de}},id:K.id,status:G}),ft=(K,G,X,de,pe)=>{for(const Z of K)ie(D,pe(Z),A,void 0,fe),Ie.push(ht(Z,G,X,de))},hr=(K,G,X,de,pe,Z)=>{for(const be of K){const _e=pe.get(be.id),ue=_e?.status??Z,le=ue<400,Re=le?void 0:Ot(_e?.errorDetail);ie(D,{durationMs:de,functionPath:be.functionPath,...B,...je(X),ok:le,shardKey:G,...le?{}:{error:{...Re,code:Re?.code??"SHARD_ERROR",message:Re?.message??`batched call returned ${String(ue)}`,status:ue}}},A,void 0,fe)}};await Promise.all([...P.entries()].map(async([K,G])=>{const X=we(8),de=new Request("https://shard.internal/rpc-batch",{body:JSON.stringify({calls:G}),headers:new Headers(ye(X)),method:"POST"}),pe=Date.now();let Z;try{Z=await T(d,K,de)}catch(Y){const Ee=Date.now()-pe,{body:wt}=mr(Y,{fallbackCode:"SHARD_UNAVAILABLE",redactedMessage:"shard unavailable"});ft(G,502,wt.code,wt.message,fr=>({...De(fr.functionPath,Ee,Y,{shardKey:K}),...B,...je(X)}));return}const be=Date.now()-pe,_e=Z.headers.get("x-d1-bookmark");_e&&Me.push(_e);let ue;try{ue=await Z.json()}catch{const Y=`shard batch returned a non-JSON response (${String(Z.status)})`;ft(G,Z.status,"SHARD_ERROR",Y,Ee=>({durationMs:be,error:{code:"SHARD_ERROR",message:Y,status:Z.status},functionPath:Ee.functionPath,...B,...je(X),ok:!1,shardKey:K}));return}const le=Array.isArray(ue.results)?ue.results:[],Re=new Set(le.map(Y=>Y.id));hr(G,K,X,be,new Map(le.map(Y=>[Y.id,Y])),Z.status),Ie.push(...le.map(({errorDetail:Y,...Ee})=>Ee));for(const Y of G)Re.has(Y.id)||Ie.push(ht(Y,Z.status,"SHARD_ERROR",`shard batch omitted result for call ${String(Y.id)}`))}));const pt={"content-type":"application/json"},[mt]=Me;return Me.length===1&&mt!==void 0&&(pt["x-d1-bookmark"]=mt),Response.json({results:Ie},{headers:pt,status:200})},tr=async(o,a,l,u={},p={})=>{try{const R=l.__lunoraRef;if(typeof R!="string")throw new c("serverQuery: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});ke(R);const{headers:v,identity:P}=await H(o,a,i,p.context),D={args:u,functionPath:R,shardKey:p.shardKey};await Se(D,P);const _=p.shardKey??r,A=Ae(a,o,p.waitUntil),B=()=>Oe(o,R,u,_,v,A),j=qe(D,e);return j&&e.x402Charge?await e.x402Charge(o,{functionPath:R,price:j.price},B,Je(p.waitUntil?{waitUntil:p.waitUntil}:p.context)):await B()}catch(R){return _t(R)}},dt=async(o,a,l)=>{const{observability:u}=e,p=Date.now(),R=we(16),v=we(8),P=qt(a),D=on(R,v,!0);try{const _=await l(D);return ie(u,{durationMs:Date.now()-p,functionPath:o,ok:!0,spanId:v,traceId:R},P),_}catch(_){throw ie(u,{...De(o,Date.now()-p,_,{}),spanId:v,traceId:R},P),_}finally{yt(u,P)}},ut=async(o,a,l,u)=>{g(a);const p=[],R=A=>A instanceof Error?A:new Error(String(A)),v=e.crons?.[o.cron];if(v)try{await v(o,a,l)}catch(A){p.push(R(A))}const P=await Be(o.cron,a,l,p,R,u),D=!!e.backupStore&&e.backupCron!==void 0&&e.backupCron===o.cron;if(D)try{await Xo(e,s,d,k(),o)}catch(A){p.push(R(A))}if(!v&&P===0&&!D){const A=[...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: ${A.length===0?"(none)":A.join(", ")}. Check that \`triggers.crons\` in wrangler.jsonc matches the app's cron definitions.`)}const[_]=p;if(p.length===1&&_)throw _;if(p.length>1)throw new AggregateError(p,`scheduled("${o.cron}") had ${String(p.length)} failure(s)`)},nr=ga({assertAdmin:$,dispatchScheduled:ut,queueHandler:e.queueHandler}),rr=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 T(d,r,Ue(Ma,{outcome:a},{authorization:`Bearer ${u}`,"content-type":"application/json"}))}catch{}},or=async(o,a,l,u)=>{if(!e.authHandler)return;const p=e.authBasePath??Vt,R=Yt(l.pathname,p)?Nr(o):void 0;let v;try{v=await e.authHandler(R?.request??o)}catch(P){throw R?.overflowed()?new c("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413}):P}if(R?.overflowed())throw new c("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});if(v)return Ka(l.pathname,p)&&u.waitUntil?.(rr(a,v.status>=400?"fail":"ok")),v},sr=async({args:o,env:a,functionPath:l,request:u,shardKey:p,waitUntil:R})=>{an(o,"REST");const v={functionPath:l,...p===void 0?{}:{shardKey:p}},{headers:P,identity:D}=await H(u,a,i);await Se(v,D);const _=p??r,A=Ae(a,u,R),B=()=>Oe(u,l,o,_,P,A),j=qe(v,e);return j&&e.x402Charge?e.x402Charge(u,{functionPath:l,price:j.price},B,Je({waitUntil:R})):B()},ar=Pr({functions:e.functions??{},invoke:sr,readJsonBody:ee,edgeCache:e.restEdgeCache,...e.restRateLimit?{rateLimit:e.restRateLimit}:{}}),ve=e.routes!==void 0&&Object.keys(e.routes).length>0?e.routes:void 0;ri(ve);const ir={[La]: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"}}),[Ua]:(o,a,l)=>zn(o,a,l),[Gt]:(o,a,l,u)=>Zn(o,a,u),[Na]:(o,a,l,u)=>er(o,a,u),[vo]:(o,a,l,u)=>In(o,a,u),[Ca]:(o,a,l,u)=>xe(o,a,u),[Ba]:async o=>{M(o,"POST","ws-token"),$(o);const a=k();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"}})},...V,...Un,...Cn,...Bn,...xn,...Hn,...Ln,...jn,...Mn,...$n,...Fn,...ar,...Mo({assertAdmin:$,getAuthAdmin:()=>e.authAdmin,parsePaging:Le,queryParameter:He,readJsonBody:ee})};let ae=Et(e.security),lt=!1;const cr=o=>{lt||(lt=!0,ae=Et(e.security,o??{}))},dr=async(o,a)=>{ja(a)&&await I(o)},ur=(o,a)=>{if(!(a.pathname.startsWith(Ce)||e.authHandler!==void 0&&Yt(a.pathname,e.authBasePath??Vt))||o.method!=="POST"&&o.method!=="PUT")return;const u=Number(o.headers.get("content-length")??""),p=Da[a.pathname]??sn;if(Number.isFinite(u)&&u>p)throw new c("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413})},lr=async(o,a,l)=>{rt.set(o,l);const u=new URL(o.url);ur(o,u);const p=await or(o,a,u,l);if(p)return p;if(ve){const _=`${o.method} ${u.pathname}`,A=ve[_]??ve[u.pathname];if(A)return A(o,a,l)}const R=nr[u.pathname];if(R)return R(o,a,l);const v=ir[u.pathname];if(v)return await dr(o,u.pathname),v(o,a,u,l);if(e.voiceAgents!==void 0&&u.pathname.startsWith(Wt))return Vn(o,a,u);if(u.pathname.startsWith(Ce))return new Response("Not found",{status:404});const P=await Wn(o,a,l);if(P&&P.status!==404)return P;const D=await e.authDiscoveryHandler?.(o);return D?(await P?.body?.cancel(),D):P??new Response("Not found",{status:404})};return{async fetch(o,a,l){e.passThroughOnException&&l.passThroughOnException?.(),cr(a),g(a);const u=Zr(o,ae);if(u)return u;const p=eo(o,ae);if(p)return Fe(p,o,ae);try{const R=await lr(o,a,l);return Fe(R,o,ae)}catch(R){return Fe(_t(R),o,ae)}finally{yt(e.observability,qt(l))}},async queue(o,a,l){await dt(`queue:${Qa(o)}`,l,async u=>{await e.queue?.(o,a,l,{traceparent:u})})},async scheduled(o,a,l){await dt(`cron:${o.cron}`,l,async u=>{await ut(o,a,l,u)})},serverQuery:tr}},si=e=>vn(e),ai=e=>typeof e=="function"?{fetch:e}:e,ii=e=>!!e.backupCron||Object.keys(e.crons??{}).length>0||Object.keys(e.cronJobs??{}).length>0,ci=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}:{}},Ni=(e,t)=>{const n=ai(e),{email:r,queue:s,scheduled:i}=ci(e),d=h=>{const b={...si({...h,httpRouter:n})};return i!==void 0&&!ii(h)&&(b.scheduled=async(T,S,k)=>{await i(T,S,k)}),s!==void 0&&h.queue===void 0&&(b.queue=async(T,S,k)=>{await s(T,S,k)}),r!==void 0&&(b.email=async(T,S,k)=>{await r(T,S,k)}),b};if(typeof t!="function")return d(t);const f=t;return{fetch:(h,m,b)=>d(f(m)).fetch(h,m,b),queue:(h,m,b)=>d(f(m)).queue?.(h,m,b)??Promise.resolve(),scheduled:(h,m,b)=>d(f(m)).scheduled(h,m,b),serverQuery:(h,m,b,T,S)=>d(f(m)).serverQuery(h,m,b,T,S),...r===void 0?{}:{email:(h,m,b)=>d(f(m)).email?.(h,m,b)??Promise.resolve()}}},di=(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}},Ui=(e={})=>(t,n,r)=>vn(di(e,n)).fetch(t,n,r??gr),Ci=e=>e;export{tt as COPY_AUTH_TO_JURISDICTION_OP,Pt as GET_AUTH_AUDIT_LOG_OP,gr as NOOP_EXECUTION_CONTEXT,gn as PURGE_UNPINNED_AUTH_OP,Hi as composeIdentityResolvers,si as composeWorker,Ui as createLunoraHandler,vn as createWorker,Ci as defineRpcEnvelope,Za as probeRelayCount,di as resolveLunoraOptions,Li as routeIdentityResolvers,Ni as withFrameworkWorker};
6
+ `)}}return b.length>0&&S(b),{errors:r,globalRows:a,perShard:i,received:d}},ga=e=>e.flatMap(t=>t.error?[{message:t.error.message,shardKey:t.shardKey,timedOut:t.error.timedOut}]:[]),Ht=(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},ya=async(e,t,n,r,a)=>{const i=t.defaultShardKey??"__root__",{errors:d,globalRows:f,perShard:h,received:m}=await wa(e,t,i),b={conflicts:0,errors:d,failed:[],inserted:{}},T=[];if(t.resolveTableSharding===void 0&&h.size>0&&T.push("no `resolveTableSharding` is configured, so every row was routed to the default shard and no row could be recognised as `.global()` — correct for a single-shard app, silent misplacement for a sharded one"),h.size>0){const S=await n.orchestrateImport(a,{batches:[...h.values()],headers:r});Ht(b,S),b.failed.push(...ga(S.shards))}if(f.length>0)if(t.importGlobals){const S=f[0]?.line??1,k=await t.importGlobals({rows:f,startLine:S});Ht(b,k)}else for(const S of f)b.errors.push({code:"GLOBAL_NOT_CONFIGURED",line:S.line,message:`row targets global table "${S.table}" but no \`importGlobals\` is configured`,table:S.table});return{conflicts:b.conflicts,errors:b.errors,failed:b.failed,inserted:b.inserted,received:m,...T.length>0?{warnings:T}:{}}},ba=Object.freeze({edges:[],nodes:[],modules:[],unresolved:[],version:1}),We=e=>typeof e=="object"&&e!==null?e:{},ze=e=>typeof e.kind=="string"?e.kind:"unknown",_a=(e,t)=>{let n=We(t),r=!1;ze(n)==="optional"&&(r=!0,n=We(n._meta?.inner));const a=ze(n),i=n._meta??{},d={kind:a,name:e,optional:r};if(a==="id"&&typeof i.tableName=="string"&&(d.table=i.tableName),a==="array"){const f=ze(We(i.inner));f!=="unknown"&&(d.element=f)}return d},Ra=e=>typeof e!="object"||e===null?[]:Object.entries(e).map(([t,n])=>_a(t,n)).toSorted((t,n)=>t.name.localeCompare(n.name)),Ea="/_lunora/admin/functions",Aa="/_lunora/admin/cron-jobs",Ta="/_lunora/admin/architecture",Sa="/_lunora/admin/openapi",Oa="/_lunora/admin/openrpc",va="/_lunora/admin/global/tables",Ia="/_lunora/admin/global/table",ka="/_lunora/admin/global/facet",Lt=e=>{if(e===void 0||e==="")return;let t;try{t=Xe(JSON.parse(e))}catch{return}if(!Array.isArray(t))return;const n=t.flatMap(r=>{if(typeof r!="object"||r===null||typeof r.column!="string")return[];const{column:a,value:i}=r;return[{column:a,value:i}]});return n.length===0?void 0:n},Pa=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:{}}),Da=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"}),Na=e=>{const{assertAdmin:t,options:n,parsePaging:r,queryParameter:a,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(([O,I])=>I.visibility==="internal"||I.kind==="stream"?[]:[{args:Ra(I.args),kind:I.kind,path:O}]).toSorted((O,I)=>O.path.localeCompare(I.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(([O,I])=>I.map(E=>({args:E.args,cron:O,functionPath:E.functionPath,name:E.name,shardKey:E.shardKey,workflow:E.workflow}))).toSorted((O,I)=>O.name.localeCompare(I.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??ba,{headers:{"content-type":"application/json"},status:200})),m=w=>(M(w,"GET","OpenAPI"),t(w),Response.json(n.openApiSpec??Pa,{headers:{"content-type":"application/json"},status:200})),b=w=>(M(w,"GET","OpenRPC"),t(w),Response.json(n.openRpcSpec??Da,{headers:{"content-type":"application/json"},status:200})),T=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})},S=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),O=a(y,"table");if(O===void 0)throw new c("Global-table endpoint requires a `table` query param",{code:"BAD_REQUEST",status:400});const I=await g.readTablePage({...r(w),filters:Lt(a(y,"filters")),table:O});return Response.json(I,{headers:{"content-type":"application/json"},status:200})},k=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),O=a(y,"table"),I=a(y,"column");if(O===void 0||I===void 0)throw new c("Global-facet endpoint requires `table` and `column` query params",{code:"BAD_REQUEST",status:400});const E=a(y,"limit"),H=E===void 0?void 0:Number(E),L=await g.facetColumn({column:I,filters:Lt(a(y,"filters")),limit:H!==void 0&&Number.isFinite(H)?H:void 0,table:O});return Response.json(L,{headers:{"content-type":"application/json"},status:200})};return{[Aa]:f,[Ea]:d,[ka]:k,[Ia]:S,[va]:T,[Ta]:h,[Sa]:m,[Oa]:b}},Ua="/_lunora/admin/kv/namespaces",Ca="/_lunora/admin/kv/keys",Rn="/_lunora/admin/kv/value",En=32*1048576,jt=60,Ba=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"}),a=w=>Response.json(w,{headers:{"content-type":"application/json"},status:200}),i=(w,g)=>{const y=new URL(w.url),O=y.searchParams.get("namespace")??"",I=y.searchParams.get("key")??"";if(O==="")throw new c(`KV-value ${g} request requires a \`namespace\` query parameter`,{code:"BAD_REQUEST",status:400});if(I==="")throw new c(`KV-value ${g} request requires a \`key\` query parameter`,{code:"BAD_REQUEST",status:400});return{key:I,namespace:O}},d=async(w,g)=>{if(!(await w.listNamespaces()).some(O=>O.binding===g))throw new c(`Unknown KV namespace binding \`${g}\``,{code:"NOT_FOUND",status:404})},f=async w=>(M(w,"GET","KV-namespaces"),a({namespaces:await r(w).listNamespaces()})),h=async w=>{M(w,"GET","KV-keys");const g=r(w),y=new URL(w.url),O=y.searchParams.get("namespace")??"";if(O==="")throw new c("KV-keys request requires a `namespace` query parameter",{code:"BAD_REQUEST",status:400});const I=y.searchParams.get("prefix")??void 0,E=y.searchParams.get("cursor")??void 0,H=y.searchParams.get("limit"),L=H===null?void 0:Number.parseInt(H,10);if(L!==void 0&&(!Number.isInteger(L)||L<1))throw new c("KV-keys `limit` must be a positive integer",{code:"BAD_REQUEST",status:400});const U=L===void 0?void 0:Math.min(L,1e3);return await d(g,O),a(await g.listKeys({cursor:E,limit:U,namespace:O,prefix:I}))},S={DELETE:async w=>{const g=r(w),y=i(w,"DELETE");return await d(g,y.namespace),await g.deleteKey(y),a({deleted:!0})},GET:async w=>{const g=r(w),y=i(w,"GET");return await d(g,y.namespace),a(await g.getValue(y))},PUT:async w=>{const g=r(w),y=await t(w,En);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<jt))throw new c("KV-value PUT `expirationTtl` must be an integer ≥ 60",{code:"BAD_REQUEST",status:400});const O=Math.floor(Date.now()/1e3)+jt;if(y.expiration!==void 0&&(typeof y.expiration!="number"||!Number.isInteger(y.expiration)||y.expiration<O))throw new c("KV-value PUT `expiration` must be a Unix-seconds timestamp at least 60 seconds in the future",{code:"BAD_REQUEST",status:400});return await 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}),a({ok:!0})}},k=w=>{const g=S[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{[Ua]:f,[Ca]:h,[Rn]:k}},xa="/_lunora/migrate",Ha="/_lunora/admin/pitr",La="/_lunora/admin/rank",ja="/_lunora/admin/rankpage",Ma="/_lunora/admin/shard-registry/prune",$a="/_lunora/admin/shard-traffic",Ka=new Set(["__lunora_admin__:migrationStatus","__lunora_admin__:runMigration"]),Fa=new Set(["__lunora_admin__:getPitrBookmark","__lunora_admin__:pitrRestore"]),Ga=async e=>{const n=await ne(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"||!Ka.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}},Qa=async e=>{const n=await ne(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}},Wa=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}},za=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})},Va=async e=>{const n=await ne(e,"Rank page")??{};za(n);const r=Wa(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}},Ja=async e=>{const n=await ne(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}},Ya=async e=>{const n=await ne(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}},qa=async e=>{const n=await ee(e);if(typeof n.functionPath!="string"||!Fa.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}},Xa=e=>{const{defaultShard:t,forwardToShard:n,isAdmin:r,queryCoordinator:a,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 O=await Ga(g),{headers:I}=await i(g,y),E=await a.orchestrateMigration(d,{args:O.args,defaultShardKey:t,functionPath:O.functionPath,headers:I,table:O.table});return Response.json(E,{headers:{"content-type":"application/json"},status:200})},b=async(g,y)=>{h(g,"Rank");const O=await Qa(g),{headers:I}=await i(g,y),E=await a.orchestrateRank(d,{headers:I,index:O.index,partitionKey:O.partitionKey,rowId:O.rowId,sortValues:O.sortValues,table:O.table});return Response.json(E,{headers:{"content-type":"application/json"},status:200})},T=async(g,y)=>{h(g,"Rank page");const O=await Va(g),{headers:I}=await i(g,y),E=await a.orchestrateRankPage(d,{...O,headers:I});return Response.json(E,{headers:{"content-type":"application/json"},status:200})},S=async(g,y)=>{h(g,"Shard-traffic");const O=await Ja(g),{headers:I}=await i(g,y),E=await a.orchestrateShardTraffic(d,{headers:I,table:O.table});return Response.json(E,{headers:{"content-type":"application/json"},status:200})},k=async(g,y)=>{h(g,"Shard-registry prune");const O=await Ya(g),I=f(),E=(O.tables??[]).filter(U=>!I.includes(U));if(E.length>0)throw new c(`Shard-registry prune names tables that are not \`.shardBy()\`: ${E.join(", ")}`,{code:"BAD_REQUEST",status:400});const{headers:H}=await i(g,y),L=await Yr(a.registry,d,{dryRun:O.dryRun,headers:H,tables:O.tables??I});return Response.json(L,{status:L.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 O=await qa(g),{headers:I}=await i(g,y),E=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:O.args,functionPath:O.functionPath}),headers:I,method:"POST"});return n(d,O.shardKey??t,E)};return{[xa]:m,[Ha]:w,[La]:b,[ja]:T,[Ma]:k,[$a]:S}},Za=1,es=0,ts=32,ns=512,rs=/^[a-z][\d_a-z*/-]{0,255}(?:@[a-z][\d_a-z*/-]{0,13})?=[\u0020-\u002B\u002D-\u003C\u003E-\u007E]{1,256}$/,os=e=>{if(e==null)return;const t=e.trim();if(t.length===0||t.length>ns)return;const n=t.split(",");if(!(n.length>ts)){for(const r of n)if(!rs.test(r.trim()))return;return t}},as=e=>{const t=Er(e.headers.get("traceparent"));if(t===void 0)return;const n=os(e.headers.get("tracestate"));return{parentSpanId:t.parentSpanId,sampled:t.sampled,traceId:t.traceId,...n===void 0?{}:{traceState:n}}},Mt=(e,t={})=>{const n=as(e),r=t.trustInbound===!0?n:void 0,a=we(8),i=r?.traceId??we(16),d=vr(t.sampling,r===void 0?a: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:a,traceFlags:h?Za:es,traceId:i,...r?.parentSpanId===void 0?{}:{parentSpanId:r.parentSpanId},...r?.traceState===void 0?{}:{traceState:r.traceState},...f===void 0?{}:{rayId:f}}}},$t=(e,t)=>{t.traceparent=on(e.traceId,e.spanId,e.sampled),e.traceState!==void 0&&(t.tracestate=e.traceState),e.rayId!==void 0&&(t[lo]=e.rayId)},ss=(e,t)=>{let n;return()=>{if(n===void 0){const r=Or(e),a=t===void 0?void 0:t.cf;n=Ar(Sr(r),Tr(r,a))}return n}},is="/_lunora/admin/scheduled",cs="/_lunora/admin/scheduled/status",ds="/_lunora/admin/scheduled/ws",us="/_lunora/admin/scheduled/cancel",ls="/_lunora/admin/scheduled/dead",hs="/_lunora/admin/scheduled/dead/retry",fs="/_lunora/admin/scheduled/dead/cancel",ps="/_lunora/admin/scheduled/pool/release",ms=e=>{const{checkWsAdmin:t,requireSchedulerNamespace:n,resolveSchedulerStub:r,schedulerInstanceName:a}=e,i=(m,b)=>T=>{if(T.method!=="GET")throw new c(`${b} endpoint requires GET`,{code:"METHOD_NOT_ALLOWED",status:405});const S=new URL(T.url).searchParams.get("cursor"),k=S===null||S===""?"":`?cursor=${encodeURIComponent(S)}`;return r(T).fetch(new Request(`https://scheduler.internal${m}${k}`,{method:"GET"}))},d=(m,b,T=b)=>async S=>{if(S.method!=="POST")throw new c(`${T} requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});const k=r(S),w=await ne(S,b);if(typeof w?.id!="string"||w.id==="")throw new c(`${b} requires a string \`id\``,{code:"BAD_REQUEST",status:400});return k.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 b=r(m),T=await ne(m,"Scheduled pool-release");if(typeof T?.pool!="string"||T.pool==="")throw new c("Scheduled pool-release requires a string `pool`",{code:"BAD_REQUEST",status:400});const S=typeof T.id=="string"&&T.id!==""?T.id:void 0;return b.fetch(new Request("https://scheduler.internal/complete",{body:JSON.stringify(S===void 0?{pool:T.pool}:{id:S,pool:T.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 b=n();return ge(b,a).fetch(new Request("https://scheduler.internal/ws",{headers:{Upgrade:"websocket"}}))};return{[us]:d("/cancel","Scheduled-cancel","Scheduled-cancel endpoint"),[fs]:d("/dead/cancel","Scheduled dead-letter action"),[ls]:i("/dead","Scheduled dead-letter"),[hs]:d("/dead/retry","Scheduled dead-letter action"),[is]:i("/list","Scheduled-list"),[ps]:f,[cs]:i("/status","Scheduler-status"),[ds]:h}},ws="/_lunora/scheduled",An="/_lunora/queue",Tn=16*1048576,gs=e=>{const{assertAdmin:t,dispatchScheduled:n,queueHandler:r}=e,a=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 ne(d,"Scheduled tick"),b=typeof m?.cron=="string"?m.cron:"";if(b==="")throw new c("scheduled tick requires a `cron` expression",{code:"BAD_REQUEST",status:400});return await n({cron:b,noRetry:()=>{},scheduledTime:Date.now()},f,h),Response.json({cron:b,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 ne(d,"Queue dispatch",Tn);if(!Array.isArray(m?.messages))throw new c("queue dispatch requires a `messages` array",{code:"BAD_REQUEST",status:400});const b=typeof m.queue=="string"?m.queue:"",T=m.messages.filter(k=>typeof k=="object"&&k!==null&&typeof k.id=="string").map(k=>({body:k.body,id:k.id})),S=await r({messages:T,queue:b},f,h);return Response.json({retry:S?.retry??[]})};return{[An]:i,[ws]:a}},ys=(e,...t)=>{let n=e.cf;for(const r of t){if(typeof n!="object"||n===null)return;n=n[r]}return typeof n=="string"?n:void 0},nt={mtls:e=>ys(e,"tlsClientAuth","certVerified")==="SUCCESS"},bs=e=>e===void 0||e===!1?()=>!1:e===!0?()=>!0:typeof e=="function"?e:(Object.hasOwn(nt,e)?nt[e]:void 0)??(()=>!1),_s=e=>typeof e=="string"&&Object.hasOwn(nt,e),Rs=e=>{const t=_s(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.`))}},Es="/_lunora/admin/vector/indexes",As="/_lunora/admin/vector/query",Ts=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})},a=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{[Es]:r,[As]:a}},Ss="/_lunora/admin/workflows/instances",Os="/_lunora/admin/workflows/instance",vs="/_lunora/admin/workflows/status",Is={complete:!0,errored:!0,paused:!0,queued:!0,running:!0,terminated:!0,unknown:!0,waiting:!0,waitingForPause:!0},ks=e=>e!==null&&Object.hasOwn(Is,e)?e:void 0,Kt=(e,t)=>{const n=e.searchParams.get(t);if(n===null)return;const r=Number(n);return Number.isInteger(r)&&r>0?r:void 0},Ve=(e,t)=>{const n=e.searchParams.get(t);if(n===null||n==="")throw new c(`Workflows admin endpoint requires a \`${t}\` query parameter`,{code:"BAD_REQUEST",status:400});return n},Ft=()=>{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})},Ps=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 b=Ve(h,"name"),T=ks(h.searchParams.get("status"));return Response.json(await m.listInstances({page:Kt(h,"page"),perPage:Kt(h,"perPage"),status:T,workflowName:b}))},a=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")})):Ft()},i=async(d,f)=>{M(d,"POST","Workflows status"),t(d);const h=n(f);if(!h)return Ft();const m=await ne(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:b}=m;if(b!=="pause"&&b!=="resume"&&b!=="terminate")throw new c("Workflows status action must be one of: pause, resume, terminate",{code:"BAD_REQUEST",status:400});return Response.json(await h.setInstanceStatus({action:b,instanceId:m.id,workflowName:m.name}))};return{[Os]:a,[Ss]:r,[vs]:i}},Ds={[Rn]:En,[An]:Tn,[Mr]:jr},Gt="/_lunora/rpc",Ns="/_lunora/rpc-batch",Us="/_lunora/ws",Ae=(e,t,n)=>({resourceAttributes:ss(e,t),...n===void 0?{}:{waitUntil:n}}),Je=e=>e?.waitUntil?{waitUntil:t=>e.waitUntil?.(t)}:{},Qt=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=fo(e.headers.get(uo)),a=r===void 0?{}:{rayId:r};let i;try{i=new URL(e.url)}catch{return{method:t,...a,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,...a,scheme:i.protocol.replace(":",""),userAgent:n}},Wt="/_lunora/voice/",Cs="/_lunora/admin/cron-jobs/run",Bs="/_lunora/admin/ws-token",xs="/_lunora/admin/",Ce="/_lunora/",Hs="/_lunora/migrate",Ls="/_lunora/status",js=e=>e.startsWith(xs)||e===Hs,ke=e=>{if(ko(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})},Pe=async e=>await e===!0,zt=(e,t)=>{const n=e.headers.get(gt);if(n===null)return;const r=Rr(n);if(r===void 0)throw new c(`malformed ${gt} 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})},Vt="/api/auth",Ms="__lunora_admin__:recordAuthEvent",Jt="__lunora_admin__:listPushSubscriptions",$s=["/sign-in","/sign-up","/callback"],Ks=(e,t)=>{const n=t.endsWith("/")?t.slice(0,-1):t;if(!e.startsWith(`${n}/`))return!1;const r=e.slice(n.length);return $s.some(a=>r===a||r.startsWith(`${a}/`))},Yt=(e,t)=>{const n=t.endsWith("/")?t.slice(0,-1):t;return e===n||e.startsWith(`${n}/`)},De=(e,t,n,r)=>{const a=pr(n),i=a?n.code:"INTERNAL_SERVER_ERROR",d=a?n.status:500,{message:f,name:h,stack:m}=co(n);return{durationMs:t,error:{code:i,message:f,name:h,status:d,...m===void 0?{}:{stack:m}},functionPath:e,ok:!1,...r.fanOut?{fanOut:{failed:0,shards:0,table:r.fanOut.table}}:{},...r.shardKey?{shardKey:r.shardKey}:{}}},Sn=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},On=({identity:e})=>e!==null&&yr(Sn(e)),Fs=e=>{if(On(e))throw new c("authentication token expired",{code:"TOKEN_EXPIRED",status:401});return e},Gs=e=>{if(!On(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}},qt=e=>e.waitUntil?{waitUntil:t=>{e.waitUntil?.(t)}}:void 0,Qs=e=>{const t=e?.queue;return typeof t=="string"&&t.length>0?t:"unknown"},rt=new WeakMap,Ws=async(e,t,n,r,a=rt.get(e))=>{const i={"content-type":"application/json"},d=e.headers.get("authorization"),f=e.headers.get("cookie"),h=e.headers.get("x-d1-bookmark"),m=e.headers.get("x-lunora-mutation-id"),b=e.headers.get("x-lunora-client-id"),T=e.headers.get("x-lunora-client-seq"),S=e.headers.get("x-lunora-base-seq");d&&(i.authorization=d),f&&(i.cookie=f),h&&(i["x-d1-bookmark"]=h),m&&(i["x-lunora-mutation-id"]=m),b&&(i["x-lunora-client-id"]=b),T&&(i["x-lunora-client-seq"]=T),S&&(i["x-lunora-base-seq"]=S);const k=Ur(e.headers,r);if(k&&(i["x-lunora-client-ip"]=k),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,a);if(!w||typeof w.userId!="string"||w.userId.length===0)return{claims:null,headers:i,identity:null,userId:null};i["x-lunora-userid"]=br(w.userId);const g=Sn(w);g!==void 0&&(i["x-lunora-identity-exp"]=String(g));const{userId:y,...O}=w,I=Object.keys(O).length>0?O:null;return I&&(i["x-lunora-identity"]=_r(I)),{claims:I,headers:i,identity:w,userId:y}},zs=new Set(["concat","first","groupBy","max","min","rank","sum","topK"]),Vs=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"||!zs.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},Js=(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}},Ys=async e=>{const t=await cn(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&&sn(r.args,"RPC"),r.shardKey!==void 0&&typeof r.shardKey!="string")throw new c("RPC `shardKey` must be a string",{code:"BAD_REQUEST",status:400});const a=n,i=Vs(a.fanOut),d=a.args??{};if(i&&a.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:a.functionPath,shardKey:a.shardKey}},Ne=new Map,qs=5e3,Xs=4096,Zs=async(e,t)=>{const n=Date.now(),r=Ne.get(t);if(r!==void 0&&r.expiresMs>n)return r.relayCount;r!==void 0&&Ne.delete(t);let a=0;try{const i=await ge(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&&(a=Math.floor(d.relayCount))}}catch{a=0}return tn(Ne,Xs),Ne.set(t,{expiresMs:n+qs,relayCount:a}),a},Xt=(e,t)=>{if(!(e===null||typeof e!="object"))return Object.entries(e).find(([,n])=>n===t)?.[0]},Ue=(e,t,n)=>new Request("https://shard.internal/rpc",{body:JSON.stringify({args:t,functionPath:e}),headers:n,method:"POST"}),ei=["x-lunora-userid","x-lunora-identity","x-lunora-identity-exp","x-lunora-client-ip"],ti=(e,t)=>{for(const n of ei){e.delete(n);const r=t[n];r!==void 0&&e.set(n,r)}},Zt=(e,t)=>{const n=new Headers(e.headers),r=[...n.keys()];for(const a of r)a.startsWith("x-lunora-")&&n.delete(a);return ti(n,t),n},en=async(e,t)=>{if(!t||t.length===0)return!1;const n=new URL(e.url).searchParams.get("token");return n===null?!1:Ho(t,n)},ni=(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 zr(`d1:${e}`,t);if(typeof n.list=="function"&&typeof n.head=="function"&&typeof n.createMultipartUpload=="function")return $e(`r2:${e}`,!0);if(typeof n.send=="function"&&typeof n.sendBatch=="function"&&typeof n.get!="function")return $e(`queue:${e}`,!0);if(typeof n.connectionString=="string")return $e(`hyperdrive:${e}`,!0)},ri=e=>{for(const t of Object.keys(e??{}))if(t.slice(t.indexOf(" ")+1).startsWith(Ce))throw new c(`route "${t}" is under the reserved ${Ce} 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})},oi=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})},vn=e=>{oi(e);const t=bs(e.trustInboundTraceContext),n=Rs(e.trustInboundTraceContext),r=e.defaultShardKey??"__root__",a=e.queryCoordinator??qr({registry:Xr(e.resolveTableSharding,r)}),i=Vr(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,s])=>[o,Ke(s,e.jurisdiction)]));let m=!1;const b=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.`))},T=async(o,s,l,u=e.shardRegion?.(s))=>ge(o,s,b(u)).fetch(l);let S;const k=()=>e.adminToken??S;let w;const g=o=>{const s=o??{};if(w??=Xt(o,e.shardDO),S!==void 0||e.adminToken!==void 0)return;const l=s.LUNORA_ADMIN_TOKEN;typeof l=="string"&&l.length>0&&(S=l)},y=new WeakSet,O=o=>pn(o,k())||y.has(o),I=async o=>{if(!(e.adminGate===void 0||y.has(o)))try{await Pe(e.adminGate(o,rt.get(o)))&&y.add(o)}catch{}},E=async(o,s,l,u)=>{const p=await Ws(o,s,l,e.trustedClientIpHeader,u);return e.functions!==void 0&&(p.headers[rn]=nn),p},H=async(o,s,l,u)=>Fs(await E(o,s,l,u)),L=async(o,s)=>{const l=await E(o,s,e.resolveIdentity);if(y.has(o)&&l.headers.authorization===void 0){const u=k();u!==void 0&&(l.headers.authorization=`Bearer ${u}`)}return l};let U=!1,F=!1;const q=()=>{F||(F=!0,console.warn("[lunora] `replicaReads: true` has no effect without `functions` — read eligibility is decided from the function registry."))},W=o=>{if(!e.allowUnauthenticatedShardAccess){const s=o==="fan-out"?"authorizeFanOut":"authorizeShard";throw new c(`${o} access is default-denied: configure \`${s}\` on the worker, or set \`allowUnauthenticatedShardAccess: true\` to explicitly allow unauthenticated ${o} access (relying solely on per-row RLS).`,{code:o==="fan-out"?"FORBIDDEN_FANOUT":"FORBIDDEN_SHARD",status:403})}U||(U=!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("")))},z=async(o,s,l=!1)=>{if(s.includes(Ze)||s.includes(et))throw new c("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403});if(!l)if(e.authorizeShard){if(!await Pe(e.authorizeShard({identity:o,shardKey:s})))throw new c("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else s!==r&&W("shard")},V=Xa({defaultShard:r,forwardToShard:T,isAdmin:O,queryCoordinator:a,resolveForwardContext:L,shardDO:d,shardedTables:()=>(e.listSchemaTables?.()??[]).filter(o=>e.resolveTableSharding?.(o)?.mode.kind==="shardBy")}),re=async(o,s,l,u,p,R)=>{ke(o);const v=Do({forwardedIdentity:p,mutationId:u,traceparent:R});return T(d,l,Ue(o,s,v))},Q=async(o,s,l,u,p)=>{const R=Co(l.env,l.context?.exports,o,["create"]);if(R===void 0)throw new c(`${u} targets workflow "${o}", which is on neither ctx.exports nor env`,{code:"CRON_JOB_FAILED",status:500});if(no(s))throw new c(`${u} params ${ro}`,{code:"BAD_REQUEST",status:400});try{await R.create(p===void 0?{params:s}:{id:p,params:s})}catch(v){if(!so(v))throw v}},ce=async(o,s,l,u)=>{if(o.workflow){await Q(o.workflow,o.args??{},{context:l,env:s},`cron job "${o.name}"`);return}if(o.functionPath===void 0)throw new c(`cron job "${o.name}" has neither a function target nor a workflow target`,{code:"CRON_JOB_FAILED",status:500});const p=await re(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})},$=o=>{if(!O(o))throw new c("admin endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403})},oe=(o,s,l)=>{if($(o),s===void 0)throw new c(l.message,{code:l.code,status:400});return s},Be=async(o,s,l,u,p,R)=>{const v=e.cronJobs?.[o];if(!v)return 0;for(const P of v)try{await ce(P,s,l,R)}catch(D){u.push(p(D))}return v.length},xe=async(o,s,l)=>{if($(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 ee(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 R=Object.values(e.cronJobs).flat().find(v=>v.name===p);if(!R)throw new c(`no cron job named "${p}" is registered`,{code:"CRON_JOB_NOT_FOUND",status:404});return await ce(R,s,l),Response.json({name:p,ran:!0},{status:200})},ae=async o=>{const s=typeof o.pool=="string"&&o.pool.length>0?o.pool:void 0;if(!s||!f||typeof o.id!="string")return;const l=typeof o.instanceName=="string"&&o.instanceName.length>0?o.instanceName:"default";try{await ge(f,l).fetch(new Request("https://scheduler.internal/complete",{body:JSON.stringify({id:o.id,pool:s}),headers:{"content-type":"application/json"},method:"POST"}))}catch{}},In=async(o,s,l)=>{M(o,"POST","Scheduler dispatch");const u=await cn(o),p=s??{},R=typeof p.LUNORA_SCHEDULER_SECRET=="string"?p.LUNORA_SCHEDULER_SECRET:void 0,v=e.adminToken??(typeof p.LUNORA_ADMIN_TOKEN=="string"?p.LUNORA_ADMIN_TOKEN:void 0);if(!await Po(o,u,{adminToken:v,schedulerSecret:R}))throw new c("Scheduler dispatch requires a valid signature or admin bearer",{code:"DISPATCH_UNAUTHENTICATED",status:403});let D;try{D=JSON.parse(u)}catch{throw new c("Scheduler dispatch body must be valid JSON",{code:"BAD_REQUEST",status:400})}const _=D??{},A=_.args??{},B=typeof _.id=="string"&&_.id.length>0?_.id:void 0;if(typeof _.workflow=="string"&&_.workflow.length>0)return await Q(_.workflow,A,{context:l,env:s},"scheduled workflow",B),await ae(_),Response.json({ok:!0},{status:200});if(typeof _.functionPath!="string"||_.functionPath.length===0)throw new c("Scheduler dispatch is missing `functionPath`",{code:"BAD_REQUEST",status:400});const j=typeof _.shardKey=="string"&&_.shardKey.length>0?_.shardKey:r,J=No(o),x=await re(_.functionPath,A,j,B,J,o.headers.get("traceparent")??void 0);return await ae(_),x},kn=$o({assertAdmin:$,getReader:()=>e.authAuditReader}),Pn=Ko({assertAdmin:$,getMove:()=>e.authJurisdictionMove}),Dn=async(o,s)=>{$(o);const l=e.notifySubscriptionStore;if(l===void 0)return Response.json({result:Te({subscriptions:[]})},{headers:{"content-type":"application/json"},status:200});const u=s?.kind,p=s?.userId,R=s?.limit,v=u==="fcm"||u==="web-push"?u:void 0,P=typeof p=="string"&&p!==""?p:void 0,D=typeof R=="number"&&Number.isFinite(R)?Math.trunc(R):0,_=D>0?Math.min(D,1e3):1e3,B=(await l.list({kind:v,limit:_,userId:P})).filter(j=>v!==void 0&&j.kind!==v?!1:P===void 0||(j.userId??null)===P).map(({keys:j,token:J,...x})=>x);return Response.json({result:Te({subscriptions:B})},{headers:{"content-type":"application/json"},status:200})},Nn=async(o,s)=>{if(!s.fanOut&&!(s.functionPath!==Pt&&s.functionPath!==Jt&&s.functionPath!==tt&&s.functionPath!==gn))return await I(o),s.functionPath===Pt?kn(o,s.args??{}):s.functionPath===Jt?Dn(o,s.args):Pn(o,s.functionPath,s.args??{})},Un=fa({applyGlobals:e.applyGlobals,assertAdmin:$,exportCursorStore:e.exportCursorStore,exportSinks:e.exportSinks,defaultShardKey:r,knownTables:()=>[...e.listSchemaTables?.()??[]],queryCoordinator:a,resolveForwardContext:L,shardDO:d,prepareExportRows:async(o,s)=>yn(e,a,o,s,d),streamingImport:(o,s)=>ya(o,e,a,s,d),syncGlobals:e.syncGlobals}),He=(o,s)=>{const l=o.searchParams.get(s);return l===null||l===""?void 0:l},Le=o=>{const s=new URL(o.url),l=s.searchParams.get("limit"),u=s.searchParams.get("offset"),p=l===null?void 0:Number.parseInt(l,10),R=u===null?void 0:Number.parseInt(u,10);return{limit:p!==void 0&&Number.isFinite(p)&&p>=0?p:void 0,offset:R!==void 0&&Number.isFinite(R)&&R>=0?R:void 0}},ct=()=>{if(f===void 0)throw new c("scheduled endpoints require a `schedulerDO` namespace on the worker",{code:"SCHEDULER_NOT_CONFIGURED",status:400});return f},Cn=ms({checkWsAdmin:async o=>O(o)||en(o,k()),requireSchedulerNamespace:ct,resolveSchedulerStub:o=>($(o),ge(ct(),e.schedulerInstanceName??"default")),schedulerInstanceName:e.schedulerInstanceName??"default"}),Bn=Ps({assertAdmin:$,resolveWorkflowsClient:e.workflowsClient??(()=>{})}),xn=Lr({assertAdmin:$,parsePaging:Le,queryParameter:He,readBodyBytes:Dr,requireAdminOption:oe,storage:{storageBuckets:e.storageBuckets,storageDelete:e.storageDelete,storageDownload:e.storageDownload,storageList:e.storageList,storageSignedUrl:e.storageSignedUrl,storageUpload:e.storageUpload}}),Hn=na({options:e,readJsonBody:ee,requireAdminOption:oe}),Ln=Ts({readJsonBody:ee,requireAdminOption:oe,vectorIntrospector:e.vectorIntrospector}),jn=Ba({kvIntrospector:e.kvIntrospector,readJsonBody:ee,requireAdminOption:oe}),Mn=Jr({logArchive:e.logArchive,readJsonBody:ee,requireAdminOption:oe}),$n=Na({assertAdmin:$,options:{cronJobs:e.cronJobs,functions:e.functions,globalIntrospector:e.globalIntrospector,architecture:e.architecture,openApiSpec:e.openApiSpec,openRpcSpec:e.openRpcSpec},parsePaging:Le,queryParameter:He,requireAdminOption:oe}),Kn=o=>{const s=[],l=d??o?.SHARD;if(l!==void 0&&s.push(Wr("durable-object:default",l,r)),e.health?.disableBindingProbes!==!0)for(const[u,p]of Object.entries(o??{})){const R=ni(u,p);R!==void 0&&s.push(R)}for(const u of e.health?.probes??[])s.push(u);return s},Fn=Qr({appName:e.health?.appName,appVersion:e.health?.appVersion,auth:e.health?.auth??"public",cacheTtlMs:e.health?.cacheTtlMs,isAdmin:O,resolveProbes:Kn}),Gn=o=>{const s=_=>"args"in _?{..._,args:Xe(_.args)}:_,l=e.schedulerInstanceName??"default",u=()=>ge(o,l),p=async(_,A)=>{const B=await u().fetch(new Request(`https://scheduler.internal${_}`,A));if(!B.ok)throw new c(`ctx.scheduler: SchedulerDO ${_} failed (${String(B.status)}): ${await B.text()}`,{code:"INTERNAL",status:500});return await B.json()},R=async(_,A)=>await p(_,{body:JSON.stringify(A),headers:{"content-type":"application/json"},method:"POST"}),v=_=>{const A=_;if(A==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 A.binding=="string"&&A.binding.length>0)return{workflow:A.binding};if(typeof A.__lunoraRef=="string")return{functionPath:A.__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})},P=async()=>(await oo(async A=>p(A===void 0?"/list":`/list?cursor=${encodeURIComponent(A)}`,{method:"GET"}))).map(A=>s(A)),D=async(_,A,B={})=>{const j=v(A),{id:J}=await R("/schedule",{args:wr("ctx.scheduler",String(j.functionPath??j.workflow),B),scheduledFor:Math.ceil(_),...j});return J};return{cancel:async _=>await R("/cancel",{id:_}),get:async _=>{const A=await p(`/get?id=${encodeURIComponent(_)}`,{method:"GET"});return A.record===void 0?null:s(A.record)},list:P,runAfter:async(_,A,B)=>{if(!Number.isFinite(_)||_<0)throw new c("ctx.scheduler.runAfter: `delayMs` must be a non-negative finite number",{code:"INVALID_INPUT",status:400});return await D(Date.now()+_,A,B)},runAt:async(_,A,B)=>{if(!Number.isFinite(_))throw new c("ctx.scheduler.runAt: `date` must be a non-negative finite number",{code:"INVALID_INPUT",status:400});return await D(_,A,B)}}},Qn=async(o,s,l)=>{const{claims:u,headers:p,userId:R}=Gs(await E(o,s,i)),v=Ae(s,o,_=>l.waitUntil?.(_)),P=_=>async(A,B={})=>{const j=A.__lunoraRef;if(typeof j!="string")throw new c("ctx.run*: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});ke(j);const J=await Oe(o,j,Te(B),_,{...p,"x-lunora-system":"1"},v),x=await J.json();if(x.error)throw new c(x.error.message??"shard RPC failed",{code:x.error.code??"INTERNAL",status:J.status});return Xe(x.result)},D=P(r);return{auth:{getIdentity:()=>Promise.resolve(u),userId:R},cache:l.cache,fetch:globalThis.fetch.bind(globalThis),forShard:_=>{const A=P(_);return{runAction:A,runMutation:A,runQuery:A}},runAction:D,runMutation:D,runQuery:D,...f===void 0?{}:{scheduler:Gn(f)},...l.waitUntil===void 0?{}:{waitUntil:l.waitUntil.bind(l)},...e.storage===void 0?{}:{storage:to(e.storage(s,new URL(o.url).origin))}}},Wn=async(o,s,l)=>{if(!e.httpRouter)return;const u=await Qn(o,s,l);try{return await e.httpRouter.fetch(o,{...s,__lunoraCtx:u},l)}catch(p){return console.error("[lunora] httpRouter (SSR) handler threw:",p),new Response("Internal Server Error",{status:500})}},zn=async(o,s,l)=>{if(o.headers.get("Upgrade")!=="websocket")throw new c("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});const u=At(o,se);if(u)return u;const p=l.searchParams.get("shard")??r,{headers:R,identity:v}=await E(o,s,i),P=O(o)||await en(o,k());await z(v,p,P);const D=Zt(o,R),_=Xt(s,e.shardDO);if(_!==void 0){D.set("x-lunora-shard-binding",_);const A=await Zs(d,p);if(A>0){const B=bo(p,Math.floor(Math.random()*A));return T(d,B,new Request(o,{headers:D}),vt(o))}}return T(d,p,new Request(o,{headers:D}))},Vn=async(o,s,l)=>{if(h===void 0)return new Response("Not found",{status:404});if(o.headers.get("Upgrade")!=="websocket")return new Response("Expected a WebSocket upgrade",{headers:{allow:"GET"},status:426});const u=At(o,se);if(u)return u;let p;try{p=decodeURIComponent(l.pathname.slice(Wt.length))}catch{return new Response("Unknown voice agent",{status:404})}const R=Object.hasOwn(h,p)?h[p]:void 0;if(R===void 0)return new Response("Unknown voice agent",{status:404});const v=l.searchParams.get("threadKey");if(v===null||v.length===0)return new Response("Missing threadKey",{status:400});const{headers:P,identity:D}=await E(o,s,i);if(e.authorizeShard){if(!await Pe(e.authorizeShard({identity:D,shardKey:v})))throw new c("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else W("shard");const _=Zt(o,P);return T(R,v,new Request(o,{headers:_}))},Jn=async(o,s,l)=>{if(e.authorizeFanOut){if(!await Pe(e.authorizeFanOut(l,o.table,s)))throw new c("Forbidden fan-out",{code:"FORBIDDEN_FANOUT",status:403});return}if(s.startsWith("__lunora_relation__:"))throw new c("reverse cross-backend relation reads (`__lunora_relation__:*`) require `authorizeFanOut` to be configured on the worker",{code:"FORBIDDEN_FANOUT",status:403});if(e.authorizeShard)throw new c("Fan-out requires `authorizeFanOut` to be configured on the worker when `authorizeShard` is set",{code:"FORBIDDEN_FANOUT",status:403});W("fan-out")},Se=async(o,s)=>{if(!(!o.fanOut&&o.functionPath.startsWith("__lunora_admin__:"))){if(o.fanOut){await Jn(o.fanOut,o.functionPath,s);return}await z(s,o.shardKey??r)}},Yn=(o,s,l)=>{if(e.replicaReads!==!0)return;if(e.functions===void 0){q();return}if(e.functions[s]?.kind!=="query"||l.includes(et)||l.includes(Ze))return;const u=vt(o);return u===void 0?void 0:{name:_o(l,u),region:u}},qn=async(o,s,l,u,p)=>{const R=Yn(o,s,u);if(R!==void 0){const v={...p,"x-lunora-replica-read":"1",...w===void 0?{}:{"x-lunora-shard-binding":w}},P=Ro(o.headers.get("x-lunora-min-seq"));P!==void 0&&(v["x-lunora-min-seq"]=String(P));const D=await T(d,R.name,Ue(s,l,v),R.region);if(D.status!==421)return D}return T(d,u,Ue(s,l,p))},Oe=async(o,s,l,u,p,R)=>{const v=Date.now(),{observability:P,sampling:D}=e,_=Ye(o),{decision:A,ignoredUpstream:B,trace:j}=Mt(o,{..._.rayId===void 0?{}:{rayId:_.rayId},...D===void 0?{}:{sampling:D},trustInbound:t(o)});B&&n(o);const J={...p,[bt]:A.keepErrors?"1":"0",[Tt]:"1"};$t(j,J);try{const x=await qn(o,s,l,u,J),fe=Ot(x.headers.get(St));ie(P,{..._,...Qt(j),durationMs:Date.now()-v,functionPath:s,ok:x.ok,shardKey:u,...x.ok?{}:{error:{...fe,code:fe?.code??"SHARD_ERROR",message:fe?.message??`shard returned ${String(x.status)}`,status:x.status}}},R,void 0,{isTraced:j.sampled,keepErrors:A.keepErrors});const ye=new Response(x.body,{headers:x.headers,status:x.status,statusText:x.statusText});return ye.headers.set("x-lunora-shard-key",u),ye.headers.delete(St),ye}catch(x){throw ie(P,{..._,...Qt(j),...De(s,Date.now()-v,x,{shardKey:u})},R,void 0,{isTraced:j.sampled,keepErrors:A.keepErrors}),x}},Xn=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)},Zn=async(o,s,l)=>{M(o,"POST","RPC");const u=await Ys(o);Js(s,u),Xn(u);const p=await Nn(o,u);if(p!==void 0)return p;const{headers:R,identity:v}=await H(o,s,i);zt(o,v),await Se(u,v);const P=qe(u,e);{const D=Date.now(),{observability:_}=e,A=Ye(o),B=Ae(s,o,l&&(x=>l.waitUntil?.(x)));if(u.fanOut)try{const x=await a.fanOut(d,{args:u.args??{},fanOut:u.fanOut,functionPath:u.functionPath,headers:R});return ie(_,{durationMs:Date.now()-D,fanOut:{failed:x.failed,shards:x.ok+x.failed,table:u.fanOut.table},functionPath:u.functionPath,...A,ok:!0},B),Response.json(x,{headers:{"content-type":"application/json"},status:200})}catch(x){throw ie(_,{...De(u.functionPath,Date.now()-D,x,{fanOut:{table:u.fanOut.table}}),...A},B),x}const j=u.shardKey??r,J=()=>Oe(o,u.functionPath,u.args??{},j,R,B);return P&&e.x402Charge?e.x402Charge(o,{functionPath:u.functionPath,price:P.price},J,Je(l)):J()}},er=async(o,s,l)=>{M(o,"POST","RPC batch");const u=await ee(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:R,identity:v}=await H(o,s,i);zt(o,v);const P=oa(p,r);for(const K of P.values())for(const G of K)if(e.functions?.[G.functionPath]?.x402)throw new c(`paid (\`.x402\`) function "${G.functionPath}" cannot be called in a batch; dispatch it individually over ${Gt}`,{code:"BAD_REQUEST",status:400});await Promise.all([...P.entries()].flatMap(([K,G])=>G.map(X=>Se({args:X.args,functionPath:X.functionPath,shardKey:K},v))));const{observability:D,sampling:_}=e,A=Ae(s,o,l&&(K=>l.waitUntil?.(K))),B=Ye(o),{decision:j,ignoredUpstream:J,trace:x}=Mt(o,{...B.rayId===void 0?{}:{rayId:B.rayId},..._===void 0?{}:{sampling:_},trustInbound:t(o)});J&&n(o);const fe={isTraced:x.sampled,keepErrors:j.keepErrors},ye=K=>{const G={...R,"content-type":"application/json",[bt]:j.keepErrors?"1":"0",[Tt]:"1"};return $t({...x,spanId:K},G),G},je=K=>({parentSpanId:K,spanId:we(8),traceFlags:x.traceFlags,traceId:x.traceId}),Ie=[],Me=[],ht=(K,G,X,de)=>({body:{error:{code:X,message:de}},id:K.id,status:G}),ft=(K,G,X,de,pe)=>{for(const Z of K)ie(D,pe(Z),A,void 0,fe),Ie.push(ht(Z,G,X,de))},hr=(K,G,X,de,pe,Z)=>{for(const be of K){const _e=pe.get(be.id),ue=_e?.status??Z,le=ue<400,Re=le?void 0:Ot(_e?.errorDetail);ie(D,{durationMs:de,functionPath:be.functionPath,...B,...je(X),ok:le,shardKey:G,...le?{}:{error:{...Re,code:Re?.code??"SHARD_ERROR",message:Re?.message??`batched call returned ${String(ue)}`,status:ue}}},A,void 0,fe)}};await Promise.all([...P.entries()].map(async([K,G])=>{const X=we(8),de=new Request("https://shard.internal/rpc-batch",{body:JSON.stringify({calls:G}),headers:new Headers(ye(X)),method:"POST"}),pe=Date.now();let Z;try{Z=await T(d,K,de)}catch(Y){const Ee=Date.now()-pe,{body:wt}=mr(Y,{fallbackCode:"SHARD_UNAVAILABLE",redactedMessage:"shard unavailable"});ft(G,502,wt.code,wt.message,fr=>({...De(fr.functionPath,Ee,Y,{shardKey:K}),...B,...je(X)}));return}const be=Date.now()-pe,_e=Z.headers.get("x-d1-bookmark");_e&&Me.push(_e);let ue;try{ue=await Z.json()}catch{const Y=`shard batch returned a non-JSON response (${String(Z.status)})`;ft(G,Z.status,"SHARD_ERROR",Y,Ee=>({durationMs:be,error:{code:"SHARD_ERROR",message:Y,status:Z.status},functionPath:Ee.functionPath,...B,...je(X),ok:!1,shardKey:K}));return}const le=Array.isArray(ue.results)?ue.results:[],Re=new Set(le.map(Y=>Y.id));hr(G,K,X,be,new Map(le.map(Y=>[Y.id,Y])),Z.status),Ie.push(...le.map(({errorDetail:Y,...Ee})=>Ee));for(const Y of G)Re.has(Y.id)||Ie.push(ht(Y,Z.status,"SHARD_ERROR",`shard batch omitted result for call ${String(Y.id)}`))}));const pt={"content-type":"application/json"},[mt]=Me;return Me.length===1&&mt!==void 0&&(pt["x-d1-bookmark"]=mt),Response.json({results:Ie},{headers:pt,status:200})},tr=async(o,s,l,u={},p={})=>{try{const R=l.__lunoraRef;if(typeof R!="string")throw new c("serverQuery: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});ke(R);const{headers:v,identity:P}=await H(o,s,i,p.context),D={args:u,functionPath:R,shardKey:p.shardKey};await Se(D,P);const _=p.shardKey??r,A=Ae(s,o,p.waitUntil),B=()=>Oe(o,R,u,_,v,A),j=qe(D,e);return j&&e.x402Charge?await e.x402Charge(o,{functionPath:R,price:j.price},B,Je(p.waitUntil?{waitUntil:p.waitUntil}:p.context)):await B()}catch(R){return _t(R)}},dt=async(o,s,l)=>{const{observability:u}=e,p=Date.now(),R=we(16),v=we(8),P=qt(s),D=on(R,v,!0);try{const _=await l(D);return ie(u,{durationMs:Date.now()-p,functionPath:o,ok:!0,spanId:v,traceId:R},P),_}catch(_){throw ie(u,{...De(o,Date.now()-p,_,{}),spanId:v,traceId:R},P),_}finally{yt(u,P)}},ut=async(o,s,l,u)=>{g(s);const p=[],R=A=>A instanceof Error?A:new Error(String(A)),v=e.crons?.[o.cron];if(v)try{await v(o,s,l)}catch(A){p.push(R(A))}const P=await Be(o.cron,s,l,p,R,u),D=!!e.backupStore&&e.backupCron!==void 0&&e.backupCron===o.cron;if(D)try{await Xo(e,a,d,k(),o)}catch(A){p.push(R(A))}if(!v&&P===0&&!D){const A=[...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: ${A.length===0?"(none)":A.join(", ")}. Check that \`triggers.crons\` in wrangler.jsonc matches the app's cron definitions.`)}const[_]=p;if(p.length===1&&_)throw _;if(p.length>1)throw new AggregateError(p,`scheduled("${o.cron}") had ${String(p.length)} failure(s)`)},nr=gs({assertAdmin:$,dispatchScheduled:ut,queueHandler:e.queueHandler}),rr=async(o,s)=>{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 T(d,r,Ue(Ms,{outcome:s},{authorization:`Bearer ${u}`,"content-type":"application/json"}))}catch{}},or=async(o,s,l,u)=>{if(!e.authHandler)return;const p=e.authBasePath??Vt,R=Yt(l.pathname,p)?Nr(o):void 0;let v;try{v=await e.authHandler(R?.request??o)}catch(P){throw R?.overflowed()?new c("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413}):P}if(R?.overflowed())throw new c("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});if(v)return Ks(l.pathname,p)&&u.waitUntil?.(rr(s,v.status>=400?"fail":"ok")),v},ar=async({args:o,env:s,functionPath:l,request:u,shardKey:p,waitUntil:R})=>{sn(o,"REST");const v={functionPath:l,...p===void 0?{}:{shardKey:p}},{headers:P,identity:D}=await H(u,s,i);await Se(v,D);const _=p??r,A=Ae(s,u,R),B=()=>Oe(u,l,o,_,P,A),j=qe(v,e);return j&&e.x402Charge?e.x402Charge(u,{functionPath:l,price:j.price},B,Je({waitUntil:R})):B()},sr=Pr({functions:e.functions??{},invoke:ar,readJsonBody:ee,edgeCache:e.restEdgeCache,...e.restRateLimit?{rateLimit:e.restRateLimit}:{}}),ve=e.routes!==void 0&&Object.keys(e.routes).length>0?e.routes:void 0;ri(ve);const ir={[Ls]: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"}}),[Us]:(o,s,l)=>zn(o,s,l),[Gt]:(o,s,l,u)=>Zn(o,s,u),[Ns]:(o,s,l,u)=>er(o,s,u),[vo]:(o,s,l,u)=>In(o,s,u),[Cs]:(o,s,l,u)=>xe(o,s,u),[Bs]:async o=>{M(o,"POST","ws-token"),$(o);const s=k();if(s===void 0)throw new c("ws-token minting requires a configured admin token",{code:"ADMIN_TOKEN_NOT_CONFIGURED",status:400});const l=await xo(s);return Response.json(l,{headers:{"cache-control":"no-store"}})},...V,...Un,...Cn,...Bn,...xn,...Hn,...Ln,...jn,...Mn,...$n,...Fn,...sr,...Mo({assertAdmin:$,getAuthAdmin:()=>e.authAdmin,parsePaging:Le,queryParameter:He,readJsonBody:ee})};let se=Et(e.security),lt=!1;const cr=o=>{lt||(lt=!0,se=Et(e.security,o??{}))},dr=async(o,s)=>{js(s)&&await I(o)},ur=(o,s)=>{if(!(s.pathname.startsWith(Ce)||e.authHandler!==void 0&&Yt(s.pathname,e.authBasePath??Vt))||o.method!=="POST"&&o.method!=="PUT")return;const u=Number(o.headers.get("content-length")??""),p=Ds[s.pathname]??an;if(Number.isFinite(u)&&u>p)throw new c("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413})},lr=async(o,s,l)=>{rt.set(o,l);const u=new URL(o.url);ur(o,u);const p=await or(o,s,u,l);if(p)return p;if(ve){const _=`${o.method} ${u.pathname}`,A=ve[_]??ve[u.pathname];if(A)return A(o,s,l)}const R=nr[u.pathname];if(R)return R(o,s,l);const v=ir[u.pathname];if(v)return await dr(o,u.pathname),v(o,s,u,l);if(e.voiceAgents!==void 0&&u.pathname.startsWith(Wt))return Vn(o,s,u);if(u.pathname.startsWith(Ce))return new Response("Not found",{status:404});const P=await Wn(o,s,l);if(P&&P.status!==404)return P;const D=await e.authDiscoveryHandler?.(o);return D?(await P?.body?.cancel(),D):P??new Response("Not found",{status:404})};return{async fetch(o,s,l){e.passThroughOnException&&l.passThroughOnException?.(),cr(s),g(s);const u=Zr(o,se);if(u)return u;const p=eo(o,se);if(p)return Fe(p,o,se);try{const R=await lr(o,s,l);return Fe(R,o,se)}catch(R){return Fe(_t(R),o,se)}finally{yt(e.observability,qt(l))}},async queue(o,s,l){await dt(`queue:${Qs(o)}`,l,async u=>{await e.queue?.(o,s,l,{traceparent:u})})},async scheduled(o,s,l){await dt(`cron:${o.cron}`,l,async u=>{await ut(o,s,l,u)})},serverQuery:tr}},ai=e=>vn(e),si=e=>typeof e=="function"?{fetch:e}:e,ii=e=>!!e.backupCron||Object.keys(e.crons??{}).length>0||Object.keys(e.cronJobs??{}).length>0,ci=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}:{}},Ni=(e,t)=>{const n=si(e),{email:r,queue:a,scheduled:i}=ci(e),d=h=>{const b={...ai({...h,httpRouter:n})};return i!==void 0&&!ii(h)&&(b.scheduled=async(T,S,k)=>{await i(T,S,k)}),a!==void 0&&h.queue===void 0&&(b.queue=async(T,S,k)=>{await a(T,S,k)}),r!==void 0&&(b.email=async(T,S,k)=>{await r(T,S,k)}),b};if(typeof t!="function")return d(t);const f=t;return{fetch:(h,m,b)=>d(f(m)).fetch(h,m,b),queue:(h,m,b)=>d(f(m)).queue?.(h,m,b)??Promise.resolve(),scheduled:(h,m,b)=>d(f(m)).scheduled(h,m,b),serverQuery:(h,m,b,T,S)=>d(f(m)).serverQuery(h,m,b,T,S),...r===void 0?{}:{email:(h,m,b)=>d(f(m)).email?.(h,m,b)??Promise.resolve()}}},di=(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}},Ui=(e={})=>(t,n,r)=>vn(di(e,n)).fetch(t,n,r??gr),Ci=e=>e;export{tt as COPY_AUTH_TO_JURISDICTION_OP,Pt as GET_AUTH_AUDIT_LOG_OP,gr as NOOP_EXECUTION_CONTEXT,gn as PURGE_UNPINNED_AUTH_OP,Hi as composeIdentityResolvers,ai as composeWorker,Ui as createLunoraHandler,vn as createWorker,Ci as defineRpcEnvelope,Zs as probeRelayCount,di as resolveLunoraOptions,Li as routeIdentityResolvers,Ni as withFrameworkWorker};
@@ -0,0 +1 @@
1
+ import{LunoraError as O}from"./LunoraError-DksAgIpa.mjs";const E=new Set(["0","disabled","false","no","off"]),y=new Set(["1","enabled","on","true","yes"]),d=e=>typeof e=="string"&&E.has(e.trim().toLowerCase()),S=e=>typeof e=="string"&&y.has(e.trim().toLowerCase()),L="default-src 'none'; frame-ancestors 'none'; base-uri 'none'; form-action 'none'",A=e=>{const o=["base-uri 'none'","object-src 'none'"];return e==="DENY"?o.push("frame-ancestors 'none'"):e==="SAMEORIGIN"&&o.push("frame-ancestors 'self'"),o.join("; ")},b="accelerometer=(), autoplay=(), camera=(), display-capture=(), geolocation=(), gyroscope=(), magnetometer=(), microphone=(), payment=(), usb=()",u=["Authorization","Content-Type","Last-Event-ID","X-D1-Bookmark","X-Lunora-Client-Id","X-Lunora-Client-Seq","X-Lunora-Expect-Subject","X-Lunora-Min-Seq","X-Lunora-Mutation-Id","X-Lunora-Shard-Key"],f=["DELETE","GET","HEAD","PATCH","POST","PUT"],v=31536e3,C=new Set(["GET","HEAD","OPTIONS"]),R=e=>{if(e===!1)return;const o=e===void 0||e===!0?{}:e,s=o.maxAge??v,r=o.includeSubDomains??!0;return`max-age=${String(s)}${r?"; includeSubDomains":""}${o.preload?"; preload":""}`},D=(e,o)=>{if(e!==!1)return typeof e=="string"?{htmlValue:e,value:e}:{htmlValue:o,value:L}},_=e=>{if(e===!1)return{coop:void 0,csp:void 0,enabled:!1,frameOptions:void 0,hsts:void 0,permissionsPolicy:void 0,referrerPolicy:void 0};const o=e===void 0||e===!0?{}:e,s=o.frameOptions===!1?void 0:o.frameOptions??"SAMEORIGIN";return{coop:"same-origin",csp:D(o.csp,A(s)),enabled:!0,frameOptions:s,hsts:R(o.hsts),permissionsPolicy:o.permissionsPolicy===!1?void 0:o.permissionsPolicy??b,referrerPolicy:o.referrerPolicy===!1?void 0:o.referrerPolicy??"strict-origin-when-cross-origin"}},N=e=>{const o={allowCredentials:!1,allowedHeaders:u,allowedMethods:f,enabled:!1,isAllowed:()=>!1,isExplicitlyAllowed:()=>!1,maxAge:600};if(e===void 0||e===!1)return o;const s=e.allowCredentials??!1,r=e.allowedOrigins;let t,n;if(typeof r=="function"){const a=m=>r(m)===!0;t=a,n=a,console.warn(`@lunora/runtime: security.cors uses a custom \`allowedOrigins\` predicate. It is trusted by the CSRF and WebSocket origin checks${s?" AND reflects matching origins with credentials (`allowCredentials: true`)":""} — ensure it matches ONLY trusted origins by exact equality; an over-broad predicate (e.g. \`() => true\`, or \`endsWith\`/\`includes\` checks) defeats the allowlist.`)}else{const a=r;if(a.includes("*")&&s)throw new O('@lunora/runtime: security.cors cannot combine a wildcard origin ("*") with allowCredentials: true — browsers reject it and it defeats the allowlist.');t=i=>a.includes("*")||a.includes(i),n=i=>a.includes(i)}return{allowCredentials:s,allowedHeaders:[...new Set([...u,...e.allowedHeaders??[]])],allowedMethods:e.allowedMethods??f,enabled:!0,isAllowed:t,isExplicitlyAllowed:n,maxAge:e.maxAge??600}},H=e=>{if(e===!1)return{allowLoopback:!1,enabled:!1,trustedOrigins:[]};const o=e===void 0||e===!0?{}:e;return{allowLoopback:o.allowLoopback??!0,enabled:!0,trustedOrigins:o.trustedOrigins??[]}},I=e=>{const o=e?.LUNORA_ALLOWED_ORIGINS;if(typeof o!="string")return;const s=o.split(",").map(n=>n.trim()).filter(n=>n.length>0);return s.length===0?void 0:{allowCredentials:!s.includes("*")&&S(e?.LUNORA_CORS_ALLOW_CREDENTIALS),allowedOrigins:s}},j=(e,o)=>{const s=e?.headers??(d(o?.LUNORA_SECURITY_HEADERS)?!1:void 0),r=e?.csrf??(d(o?.LUNORA_SECURITY_CSRF)?!1:void 0),t=e?.cors??I(o);return{cors:N(t),csrf:H(r),headers:_(s)}},x=new Set(["127.0.0.1","::1","[::1]","localhost"]),p=e=>{try{return x.has(new URL(e).hostname)}catch{return!1}},c=e=>{if(e)try{return new URL(e).origin}catch{return}},w=(e,o,s)=>e===o||s.csrf.trustedOrigins.includes(e)||s.csrf.allowLoopback&&p(o)&&p(e)?!0:s.cors.enabled&&s.cors.isExplicitlyAllowed(e),h=(e,o,s)=>Response.json({error:{code:"FORBIDDEN_ORIGIN",expectedOrigin:s,message:`${e} rejected: Origin ${o===void 0?"was missing":`"${o}"`} is not trusted (this worker serves "${s}"). Add it to \`security.csrf.trustedOrigins\` (or LUNORA_ALLOWED_ORIGINS) if it is yours. Behind a dev proxy this usually means the proxy rewrote the host: keep both ends on loopback, or list the dev-server origin.`,receivedOrigin:o}},{headers:{"content-type":"application/json"},status:403}),X=(e,o)=>{if(!o.csrf.enabled||C.has(e.method)||!e.headers.get("cookie"))return;const s=new URL(e.url).origin,r=c(e.headers.get("origin"))??c(e.headers.get("referer"));if(!(r!==void 0&&w(r,s,o)))return h("cross-origin state-changing request",r,s)},F=(e,o)=>{if(!o.csrf.enabled||!e.headers.get("cookie"))return;const s=new URL(e.url).origin,r=c(e.headers.get("origin"));if(!(r!==void 0&&w(r,s,o)))return h("cross-origin websocket upgrade",r,s)},P=["X-D1-Bookmark","X-Lunora-Edge-Cache","X-Lunora-Shard-Key"],g=(e,o)=>{const s=new Headers;return s.set("access-control-allow-origin",e),s.set("access-control-expose-headers",P.join(", ")),s.append("vary","Origin"),o.allowCredentials&&s.set("access-control-allow-credentials","true"),s},B=(e,o)=>{if(!o.cors.enabled||e.method!=="OPTIONS")return;const s=e.headers.get("origin");if(!s||!e.headers.get("access-control-request-method")||!o.cors.isAllowed(s))return;const r=g(s,o.cors),t=e.headers.get("access-control-request-headers");r.set("access-control-allow-methods",o.cors.allowedMethods.join(", "));let n;if(t===null)n=o.cors.allowedHeaders.join(", ");else{const a=new Set(o.cors.allowedHeaders.map(i=>i.toLowerCase()));n=t.split(",").map(i=>i.trim()).filter(i=>i.length>0&&a.has(i.toLowerCase())).join(", ")}return r.set("access-control-allow-headers",n),r.set("access-control-max-age",String(o.cors.maxAge)),new Response(null,{headers:r,status:204})},T=e=>(e.headers.get("content-type")??"").toLowerCase().includes("text/html"),l=(e,o,s)=>{e.has(o)||e.set(o,s)},k=(e,o,s,r)=>{if(r.hsts!==void 0&&new URL(o.url).protocol==="https:"&&l(e,"strict-transport-security",r.hsts),l(e,"x-content-type-options","nosniff"),r.frameOptions!==void 0&&l(e,"x-frame-options",r.frameOptions),r.referrerPolicy!==void 0&&l(e,"referrer-policy",r.referrerPolicy),r.permissionsPolicy!==void 0&&l(e,"permissions-policy",r.permissionsPolicy),r.coop!==void 0&&l(e,"cross-origin-opener-policy",r.coop),r.csp!==void 0){const t=T(s)?r.csp.htmlValue:r.csp.value;t!==void 0&&l(e,"content-security-policy",t)}},U=(e,o,s)=>{const r=o.headers.get("origin");if(!(!r||!s.isAllowed(r)))for(const[t,n]of g(r,s).entries())t==="vary"?e.append("vary",n):l(e,t,n)},V=(e,o,s)=>{if(e.status===101||e.webSocket)return e;const r=new Headers(e.headers);return s.headers.enabled&&k(r,o,e,s.headers),s.cors.enabled&&U(r,o,s.cors),new Response(e.body,{headers:r,status:e.status,statusText:e.statusText})};export{V as decorateResponse,X as enforceOrigin,F as enforceWebSocketOrigin,B as handleCorsPreflight,j as resolveSecurity};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/runtime",
3
- "version": "1.0.0-alpha.207",
3
+ "version": "1.0.0-alpha.209",
4
4
  "description": "Lunora Worker runtime: the RPC router, shard resolver, and query coordinator",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -46,10 +46,10 @@
46
46
  "access": "public"
47
47
  },
48
48
  "dependencies": {
49
- "@lunora/bindings": "1.0.0-alpha.115",
49
+ "@lunora/bindings": "1.0.0-alpha.116",
50
50
  "@lunora/errors": ">=1.0.0-alpha.51 <2.0.0-0",
51
- "@lunora/observability": "1.0.0-alpha.143",
52
- "@lunora/platform": "1.0.0-alpha.65",
51
+ "@lunora/observability": "1.0.0-alpha.144",
52
+ "@lunora/platform": "1.0.0-alpha.66",
53
53
  "@lunora/wire": "1.0.0-alpha.1"
54
54
  },
55
55
  "peerDependencies": {
@@ -1 +0,0 @@
1
- import{LunoraError as O}from"./LunoraError-DksAgIpa.mjs";const E=new Set(["0","disabled","false","no","off"]),y=new Set(["1","enabled","on","true","yes"]),d=e=>typeof e=="string"&&E.has(e.trim().toLowerCase()),S=e=>typeof e=="string"&&y.has(e.trim().toLowerCase()),L="default-src 'none'; frame-ancestors 'none'; base-uri 'none'; form-action 'none'",A=e=>{const o=["base-uri 'none'","object-src 'none'"];return e==="DENY"?o.push("frame-ancestors 'none'"):e==="SAMEORIGIN"&&o.push("frame-ancestors 'self'"),o.join("; ")},b="accelerometer=(), autoplay=(), camera=(), display-capture=(), geolocation=(), gyroscope=(), magnetometer=(), microphone=(), payment=(), usb=()",u=["Authorization","Content-Type","X-D1-Bookmark","X-Lunora-Client-Id","X-Lunora-Client-Seq","X-Lunora-Expect-Subject","X-Lunora-Min-Seq","X-Lunora-Mutation-Id","X-Lunora-Shard-Key"],f=["DELETE","GET","HEAD","PATCH","POST","PUT"],C=31536e3,v=new Set(["GET","HEAD","OPTIONS"]),R=e=>{if(e===!1)return;const o=e===void 0||e===!0?{}:e,s=o.maxAge??C,r=o.includeSubDomains??!0;return`max-age=${String(s)}${r?"; includeSubDomains":""}${o.preload?"; preload":""}`},D=(e,o)=>{if(e!==!1)return typeof e=="string"?{htmlValue:e,value:e}:{htmlValue:o,value:L}},_=e=>{if(e===!1)return{coop:void 0,csp:void 0,enabled:!1,frameOptions:void 0,hsts:void 0,permissionsPolicy:void 0,referrerPolicy:void 0};const o=e===void 0||e===!0?{}:e,s=o.frameOptions===!1?void 0:o.frameOptions??"SAMEORIGIN";return{coop:"same-origin",csp:D(o.csp,A(s)),enabled:!0,frameOptions:s,hsts:R(o.hsts),permissionsPolicy:o.permissionsPolicy===!1?void 0:o.permissionsPolicy??b,referrerPolicy:o.referrerPolicy===!1?void 0:o.referrerPolicy??"strict-origin-when-cross-origin"}},N=e=>{const o={allowCredentials:!1,allowedHeaders:u,allowedMethods:f,enabled:!1,isAllowed:()=>!1,isExplicitlyAllowed:()=>!1,maxAge:600};if(e===void 0||e===!1)return o;const s=e.allowCredentials??!1,r=e.allowedOrigins;let t,n;if(typeof r=="function"){const a=m=>r(m)===!0;t=a,n=a,console.warn(`@lunora/runtime: security.cors uses a custom \`allowedOrigins\` predicate. It is trusted by the CSRF and WebSocket origin checks${s?" AND reflects matching origins with credentials (`allowCredentials: true`)":""} — ensure it matches ONLY trusted origins by exact equality; an over-broad predicate (e.g. \`() => true\`, or \`endsWith\`/\`includes\` checks) defeats the allowlist.`)}else{const a=r;if(a.includes("*")&&s)throw new O('@lunora/runtime: security.cors cannot combine a wildcard origin ("*") with allowCredentials: true — browsers reject it and it defeats the allowlist.');t=i=>a.includes("*")||a.includes(i),n=i=>a.includes(i)}return{allowCredentials:s,allowedHeaders:[...new Set([...u,...e.allowedHeaders??[]])],allowedMethods:e.allowedMethods??f,enabled:!0,isAllowed:t,isExplicitlyAllowed:n,maxAge:e.maxAge??600}},H=e=>{if(e===!1)return{allowLoopback:!1,enabled:!1,trustedOrigins:[]};const o=e===void 0||e===!0?{}:e;return{allowLoopback:o.allowLoopback??!0,enabled:!0,trustedOrigins:o.trustedOrigins??[]}},I=e=>{const o=e?.LUNORA_ALLOWED_ORIGINS;if(typeof o!="string")return;const s=o.split(",").map(n=>n.trim()).filter(n=>n.length>0);return s.length===0?void 0:{allowCredentials:!s.includes("*")&&S(e?.LUNORA_CORS_ALLOW_CREDENTIALS),allowedOrigins:s}},j=(e,o)=>{const s=e?.headers??(d(o?.LUNORA_SECURITY_HEADERS)?!1:void 0),r=e?.csrf??(d(o?.LUNORA_SECURITY_CSRF)?!1:void 0),t=e?.cors??I(o);return{cors:N(t),csrf:H(r),headers:_(s)}},x=new Set(["127.0.0.1","::1","[::1]","localhost"]),p=e=>{try{return x.has(new URL(e).hostname)}catch{return!1}},c=e=>{if(e)try{return new URL(e).origin}catch{return}},w=(e,o,s)=>e===o||s.csrf.trustedOrigins.includes(e)||s.csrf.allowLoopback&&p(o)&&p(e)?!0:s.cors.enabled&&s.cors.isExplicitlyAllowed(e),h=(e,o,s)=>Response.json({error:{code:"FORBIDDEN_ORIGIN",expectedOrigin:s,message:`${e} rejected: Origin ${o===void 0?"was missing":`"${o}"`} is not trusted (this worker serves "${s}"). Add it to \`security.csrf.trustedOrigins\` (or LUNORA_ALLOWED_ORIGINS) if it is yours. Behind a dev proxy this usually means the proxy rewrote the host: keep both ends on loopback, or list the dev-server origin.`,receivedOrigin:o}},{headers:{"content-type":"application/json"},status:403}),X=(e,o)=>{if(!o.csrf.enabled||v.has(e.method)||!e.headers.get("cookie"))return;const s=new URL(e.url).origin,r=c(e.headers.get("origin"))??c(e.headers.get("referer"));if(!(r!==void 0&&w(r,s,o)))return h("cross-origin state-changing request",r,s)},F=(e,o)=>{if(!o.csrf.enabled||!e.headers.get("cookie"))return;const s=new URL(e.url).origin,r=c(e.headers.get("origin"));if(!(r!==void 0&&w(r,s,o)))return h("cross-origin websocket upgrade",r,s)},P=["X-D1-Bookmark","X-Lunora-Edge-Cache","X-Lunora-Shard-Key"],g=(e,o)=>{const s=new Headers;return s.set("access-control-allow-origin",e),s.set("access-control-expose-headers",P.join(", ")),s.append("vary","Origin"),o.allowCredentials&&s.set("access-control-allow-credentials","true"),s},B=(e,o)=>{if(!o.cors.enabled||e.method!=="OPTIONS")return;const s=e.headers.get("origin");if(!s||!e.headers.get("access-control-request-method")||!o.cors.isAllowed(s))return;const r=g(s,o.cors),t=e.headers.get("access-control-request-headers");r.set("access-control-allow-methods",o.cors.allowedMethods.join(", "));let n;if(t===null)n=o.cors.allowedHeaders.join(", ");else{const a=new Set(o.cors.allowedHeaders.map(i=>i.toLowerCase()));n=t.split(",").map(i=>i.trim()).filter(i=>i.length>0&&a.has(i.toLowerCase())).join(", ")}return r.set("access-control-allow-headers",n),r.set("access-control-max-age",String(o.cors.maxAge)),new Response(null,{headers:r,status:204})},T=e=>(e.headers.get("content-type")??"").toLowerCase().includes("text/html"),l=(e,o,s)=>{e.has(o)||e.set(o,s)},k=(e,o,s,r)=>{if(r.hsts!==void 0&&new URL(o.url).protocol==="https:"&&l(e,"strict-transport-security",r.hsts),l(e,"x-content-type-options","nosniff"),r.frameOptions!==void 0&&l(e,"x-frame-options",r.frameOptions),r.referrerPolicy!==void 0&&l(e,"referrer-policy",r.referrerPolicy),r.permissionsPolicy!==void 0&&l(e,"permissions-policy",r.permissionsPolicy),r.coop!==void 0&&l(e,"cross-origin-opener-policy",r.coop),r.csp!==void 0){const t=T(s)?r.csp.htmlValue:r.csp.value;t!==void 0&&l(e,"content-security-policy",t)}},U=(e,o,s)=>{const r=o.headers.get("origin");if(!(!r||!s.isAllowed(r)))for(const[t,n]of g(r,s).entries())t==="vary"?e.append("vary",n):l(e,t,n)},V=(e,o,s)=>{if(e.status===101||e.webSocket)return e;const r=new Headers(e.headers);return s.headers.enabled&&k(r,o,e,s.headers),s.cors.enabled&&U(r,o,s.cors),new Response(e.body,{headers:r,status:e.status,statusText:e.statusText})};export{V as decorateResponse,X as enforceOrigin,F as enforceWebSocketOrigin,B as handleCorsPreflight,j as resolveSecurity};