@lunora/runtime 1.0.0-alpha.85 → 1.0.0-alpha.87
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{BACKUP_KEY_PREFIX as t,backupManifestKey as a,backupObjectKey as s,backupObjectKeyOfManifest as i,isBackupManifestEntry as n,isBackupManifestKey as p,normalizeBackupPrefix as c}from"./packem_shared/BACKUP_KEY_PREFIX-BOtSu-_3.mjs";import{toAirbyteMessages as f,toFivetranResponse as E}from"./packem_shared/toAirbyteMessages-DvYrhqLf.mjs";import{composeWorker as x,createLunoraHandler as S,createWorker as l,defineRpcEnvelope as u,resolveLunoraOptions as _,withFrameworkWorker as d}from"./packem_shared/composeWorker-
|
|
1
|
+
import{BACKUP_KEY_PREFIX as t,backupManifestKey as a,backupObjectKey as s,backupObjectKeyOfManifest as i,isBackupManifestEntry as n,isBackupManifestKey as p,normalizeBackupPrefix as c}from"./packem_shared/BACKUP_KEY_PREFIX-BOtSu-_3.mjs";import{toAirbyteMessages as f,toFivetranResponse as E}from"./packem_shared/toAirbyteMessages-DvYrhqLf.mjs";import{composeWorker as x,createLunoraHandler as S,createWorker as l,defineRpcEnvelope as u,resolveLunoraOptions as _,withFrameworkWorker as d}from"./packem_shared/composeWorker-DnsDkxiF.mjs";import{createCrossShardRelationCapabilities as y}from"./packem_shared/createCrossShardRelationCapabilities-BYNkv1Ys.mjs";import{DEFAULT_REGISTRY_CACHE_TTL_MS as O,SHARD_REGISTRY_DO_NAME as b,createDynamicShardRegistry as A}from"./packem_shared/DEFAULT_REGISTRY_CACHE_TTL_MS-D5O7elXI.mjs";import{LunoraError as T,toErrorResponse as h}from"./packem_shared/LunoraError-DksAgIpa.mjs";import{c as P,a as g,d as v,r as I,b as D,s as M,w as F}from"./packem_shared/export-tap-CGR3Xd9F.mjs";import{HEALTH_PATH as G,HEALTH_READY_PATH as K,buildHealthRoutes as U,d1Probe as B,durableObjectProbe as Y,presenceProbe as w}from"./packem_shared/HEALTH_PATH-jZsuCmSs.mjs";import{LOG_ARCHIVE_PATH as X,resolveLogArchiveFromEnv as j}from"./packem_shared/LOG_ARCHIVE_PATH-Hmjpz_Ko.mjs";import{memoizeIdentity as W,memoizeIdentityPerRequest as q}from"./packem_shared/memoizeIdentity-DnOj3QRi.mjs";import{e as J,a as Z}from"./packem_shared/observability-vDK-rMbs.mjs";import{analyticsEngineSink as ee,combineSinks as re,consoleSink as oe,otlpSink as te,pipelineLogSink as ae,sentrySink as se,webhookSink as ie}from"./packem_shared/analyticsEngineSink-B3sQ6FPW.mjs";import{D as pe,c as ce}from"./packem_shared/pipeline-log-reader-C-nuWG_e.mjs";import{createQueryCoordinator as fe,createStaticShardRegistry as Ee}from"./packem_shared/createQueryCoordinator-Ctr3eqmp.mjs";import{applyJurisdiction as xe,resolveShard as Se}from"./packem_shared/applyJurisdiction-C0ddU7Tg.mjs";import{a as ue,r as _e,b as de}from"./packem_shared/rest-cache-CPSyD1RD.mjs";import{a as ye,b as Ce,c as Oe,r as be}from"./packem_shared/rest-routes-ZZES0ngM.mjs";import{decorateResponse as Le,enforceOrigin as Te,handleCorsPreflight as he,resolveSecurity as He}from"./packem_shared/decorateResponse-BuqVnrmc.mjs";import{createShardClient as ge}from"./packem_shared/createShardClient-DoKTlCKb.mjs";import{STORAGE_UPLOAD_MAX_BODY_BYTES as Ie}from"./packem_shared/STORAGE_UPLOAD_MAX_BODY_BYTES-BqyO-1l6.mjs";import{LOG_ARCHIVE_NOT_CONFIGURED as Me}from"./packem_shared/LOG_ARCHIVE_NOT_CONFIGURED-CDpi4yFD.mjs";import{NOOP_EXECUTION_CONTEXT as Ne}from"./packem_shared/NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{composeIdentityResolvers as Ke,routeIdentityResolvers as Ue}from"./packem_shared/composeIdentityResolvers-BHZ4jH8o.mjs";const e="0.0.0";export{t as BACKUP_KEY_PREFIX,pe as DEFAULT_LOG_COLUMNS,O as DEFAULT_REGISTRY_CACHE_TTL_MS,G as HEALTH_PATH,K as HEALTH_READY_PATH,Me as LOG_ARCHIVE_NOT_CONFIGURED,X as LOG_ARCHIVE_PATH,T as LunoraError,Ne as NOOP_EXECUTION_CONTEXT,b as SHARD_REGISTRY_DO_NAME,Ie as STORAGE_UPLOAD_MAX_BODY_BYTES,e as VERSION,ee as analyticsEngineSink,xe as applyJurisdiction,ue as applyRestCache,ye as argsFromQuery,a as backupManifestKey,s as backupObjectKey,i as backupObjectKeyOfManifest,U as buildHealthRoutes,Ce as buildRestRoutes,re as combineSinks,Ke as composeIdentityResolvers,x as composeWorker,oe as consoleSink,y as createCrossShardRelationCapabilities,A as createDynamicShardRegistry,P as createKvCursorStore,S as createLunoraHandler,g as createMemoryCursorStore,ce as createPipelineLogReader,fe as createQueryCoordinator,Oe as createRestRateLimit,ge as createShardClient,Ee as createStaticShardRegistry,l as createWorker,B as d1Probe,Le as decorateResponse,v as defineExportSink,u as defineRpcEnvelope,Y as durableObjectProbe,J as emitLogEvent,Z as emitRpcEvent,Te as enforceOrigin,he as handleCorsPreflight,n as isBackupManifestEntry,p as isBackupManifestKey,W as memoizeIdentity,q as memoizeIdentityPerRequest,c as normalizeBackupPrefix,te as otlpSink,ae as pipelineLogSink,w as presenceProbe,I as r2Sink,_e as requestCarriesCredentials,j as resolveLogArchiveFromEnv,_ as resolveLunoraOptions,He as resolveSecurity,Se as resolveShard,de as restCacheHeaders,be as restSurfaceFromRegistry,Ue as routeIdentityResolvers,D as runExportTap,M as sanitizeChange,se as sentrySink,f as toAirbyteMessages,h as toErrorResponse,E as toFivetranResponse,F as webhookExportSink,ie as webhookSink,d as withFrameworkWorker};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import{isLunoraError as Dn,toErrorBody as Nn}from"@lunora/errors";import{e as Nt}from"./evict-oldest-BNXsKx4s.mjs";import{NOOP_EXECUTION_CONTEXT as Un}from"./NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{t as Cn,f as Bn}from"./base64-Bl1_r2k1.mjs";import{e as xn,a as Hn}from"./identity-header-C4Z5pldl.mjs";import{o as Te,b as Ln,p as Mn,m as Kn,d as jn,a as $n,r as Fn}from"./otlp-resource-DeXhb949.mjs";import{e as Qe,d as Gn}from"./wire-codec-CMVqBlcF.mjs";import{d as Z,e as be,M as Ut,b as Qn,f as zn,g as Ct,h as Bt}from"./rest-routes-ZZES0ngM.mjs";import{LunoraError as d,toErrorResponse as ot}from"./LunoraError-DksAgIpa.mjs";import{a as j,m as me}from"./method-guard-BG_vJNTl.mjs";import{normalizeBackupPrefix as We,BACKUP_KEY_PREFIX as Ve,isBackupManifestKey as Wn,backupObjectKeyOfManifest as xt,backupObjectKey as Vn,backupManifestKey as Jn}from"./BACKUP_KEY_PREFIX-BOtSu-_3.mjs";import{toHex as qn,buildStorageAdminRoutes as Yn,STORAGE_UPLOAD_MAX_BODY_BYTES as Xn,STORAGE_PATH as Zn}from"./STORAGE_UPLOAD_MAX_BODY_BYTES-BqyO-1l6.mjs";import{b as er,e as tr,f as at,g as nr,h as rr}from"./export-tap-CGR3Xd9F.mjs";import{buildHealthRoutes as or,durableObjectProbe as ar,d1Probe as sr,presenceProbe as Be}from"./HEALTH_PATH-jZsuCmSs.mjs";import{wrapResolverWithContract as ir}from"./composeIdentityResolvers-BHZ4jH8o.mjs";import{composeIdentityResolvers as Os,routeIdentityResolvers as vs}from"./composeIdentityResolvers-BHZ4jH8o.mjs";import{buildLogArchiveAdminRoutes as cr}from"./LOG_ARCHIVE_PATH-Hmjpz_Ko.mjs";import{r as dr,f as st,a as ie}from"./observability-vDK-rMbs.mjs";import{resolveShard as we,applyJurisdiction as it}from"./applyJurisdiction-C0ddU7Tg.mjs";import{resolveSecurity as ct,handleCorsPreflight as ur,enforceOrigin as lr,decorateResponse as xe,enforceWebSocketOrigin as dt}from"./decorateResponse-BuqVnrmc.mjs";const hr=e=>{const t=e??{};if(typeof t.bucket=="function")return t;const n={...t,bucketName:"default"};return n.bucket=()=>n,n},Ht="__lunoraBranch",fr=e=>typeof e=="object"&&e!==null&&Object.hasOwn(e,Ht),pr=`may not contain the reserved workflow branch-marker key ("${Ht}")`,Je=(e,t)=>{const n=Math.max(e.length,t.length);let o=e.length^t.length;for(let a=0;a<n;a+=1){const i=a<e.length?e.charCodeAt(a):0,u=a<t.length?t.charCodeAt(a):0;o|=i^u}return o===0},mr=(e,t,n,o)=>{const a=e.get(t);if(a!==void 0)return a;Nt(e,o);const i=n().catch(u=>{throw e.get(t)===i&&e.delete(t),u});return e.set(t,i),i},qe=new TextEncoder,wr=Array.from({length:32},(e,t)=>t);new RegExp(`[${wr.map(e=>String.fromCodePoint(e)).join("")}]`,"u");const gr=64,yr=new Map,Lt=async e=>mr(yr,e,async()=>crypto.subtle.importKey("raw",qe.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]),gr),Mt=async(e,t)=>{const n=await Lt(e),o=await crypto.subtle.sign("HMAC",n,qe.encode(t));return Cn(new Uint8Array(o))},br=async(e,t,n)=>{const o=await Lt(e);return crypto.subtle.verify("HMAC",o,n,qe.encode(t))},_r=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"];new Set(_r);const Rr=new Set(["AE","BH","IL","IQ","IR","JO","KW","LB","OM","PS","QA","SA","SY","TR","YE"]),Er=-100,Sr=15,Ar=e=>{const t=Number(e.longitude??Number.NaN);switch(e.continent){case"AF":return"afr";case"AS":return e.country!==void 0&&Rr.has(e.country)?"me":"apac";case"EU":return Number.isFinite(t)&&t>Sr?"eeur":"weur";case"NA":return Number.isFinite(t)&&t<Er?"wnam":"enam";case"OC":return"oc";case"SA":return"sam";default:return}},ut=e=>{const t=e.cf;return t===void 0?void 0:Ar(t)},Kt="::relay::",Tr=(e,t)=>`${e}${Kt}${String(t)}`,jt="::replica::",Or=(e,t)=>`${e}${jt}${t}`,vr=e=>{if(e==null||!/^\d+$/.test(e))return;const t=Number.parseInt(e,10);return Number.isSafeInteger(t)&&t>0?t:void 0},kr=new Set(["1","enabled","on","true","yes"]),Ir=new Set(["0","disabled","false","no","off"]),Pr=(e,t)=>{const n=(e??"").trim().toLowerCase();return kr.has(n)?!0:Ir.has(n)?!1:t},$t="v1",Dr=6e4,Nr=async(e,t={})=>{const n=(t.now??Date.now())+(t.ttlMs??Dr),o=`${$t}.${String(n)}`,a=await Mt(e,o);return{expiresAtMs:n,token:`${o}.${a}`}},Ur=async(e,t,n=Date.now())=>{if(e.length===0||t.length===0)return!1;const o=t.split(".");if(o.length!==3)return!1;const[a,i,u]=o;if(a!==$t||u.length===0)return!1;const h=Number(i);if(!Number.isFinite(h)||h<=n)return!1;let f;try{f=Bn(u)}catch{return!1}return br(e,`${a}.${i}`,f)},P="/_lunora/admin/auth",Cr={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},N=(e,t)=>{const n=e[t];if(typeof n!="string"||n==="")throw new d(`\`${t}\` is required`,{code:"BAD_REQUEST",status:400});return n},he=(e,t)=>{const n=e(t);if(n===void 0)throw new d(`\`${t}\` query parameter is required`,{code:"BAD_REQUEST",status:400});return n},Ft=e=>{if(typeof e=="string"||Array.isArray(e)&&e.every(t=>typeof t=="string"))return e},re=(e,t)=>typeof e[t]=="string"?e[t]:void 0,He=(e,t)=>{const n=e[t];return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:void 0},lt=e=>{const t=Ft(e.role);if(t===void 0||typeof t=="string"&&t.trim()==="")throw new d("`role` is required",{code:"BAD_REQUEST",status:400});return t},ht=e=>{const t=e.permission;if(typeof t!="object"||t===null||Array.isArray(t))throw new d("`permission` object is required",{code:"BAD_REQUEST",status:400});const n={};for(const[o,a]of Object.entries(t))Array.isArray(a)&&a.every(i=>typeof i=="string")&&(n[o]=a);return n},Br={[`${P}/capabilities`]:{build:()=>({}),http:"GET",method:"capabilities"},[`${P}/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"},[`${P}/sessions`]:{build:({paging:e,query:t})=>({...e,userId:t("userId")}),http:"GET",method:"listSessions"},[`${P}/accounts`]:{build:({query:e})=>({userId:he(e,"userId")}),http:"GET",method:"listAccounts"},[`${P}/passkeys`]:{build:({query:e})=>({userId:he(e,"userId")}),http:"GET",method:"listPasskeys"},[`${P}/organizations`]:{build:({paging:e})=>({...e}),http:"GET",method:"listOrganizations"},[`${P}/organizations/members`]:{build:({paging:e,query:t})=>({...e,organizationId:he(t,"organizationId")}),http:"GET",method:"listMembers"},[`${P}/organizations/invitations`]:{build:({paging:e,query:t})=>({...e,organizationId:he(t,"organizationId")}),http:"GET",method:"listInvitations"},[`${P}/config`]:{build:()=>({}),http:"GET",method:"config"},[`${P}/organizations/teams`]:{build:({paging:e,query:t})=>({...e,organizationId:he(t,"organizationId")}),http:"GET",method:"listTeams"},[`${P}/organizations/teams/members`]:{build:({paging:e,query:t})=>({...e,teamId:he(t,"teamId")}),http:"GET",method:"listTeamMembers"},[`${P}/organizations/roles`]:{build:({paging:e,query:t})=>({...e,organizationId:he(t,"organizationId")}),http:"GET",method:"listOrgRoles"},[`${P}/users/create`]:{build:({body:e})=>({data:He(e,"data"),email:N(e,"email"),name:N(e,"name"),password:re(e,"password"),role:Ft(e.role)}),http:"POST",method:"createUser"},[`${P}/users/update`]:{build:({body:e})=>{const{data:t}=e;if(typeof t!="object"||t===null||Array.isArray(t))throw new d("`data` object is required",{code:"BAD_REQUEST",status:400});return{data:t,userId:N(e,"userId")}},http:"POST",method:"updateUser"},[`${P}/users/role`]:{build:({body:e})=>({role:lt(e),userId:N(e,"userId")}),http:"POST",method:"setRole"},[`${P}/users/ban`]:{build:({body:e})=>({expiresInSeconds:typeof e.expiresInSeconds=="number"?e.expiresInSeconds:void 0,reason:re(e,"reason"),userId:N(e,"userId")}),http:"POST",method:"banUser"},[`${P}/users/unban`]:{build:({body:e})=>({userId:N(e,"userId")}),http:"POST",method:"unbanUser"},[`${P}/users/password`]:{build:({body:e})=>({newPassword:N(e,"newPassword"),userId:N(e,"userId")}),http:"POST",method:"setUserPassword",returns:"void"},[`${P}/users/remove`]:{build:({body:e})=>({userId:N(e,"userId")}),http:"POST",method:"removeUser",returns:"void"},[`${P}/users/impersonate`]:{build:({body:e})=>({userId:N(e,"userId")}),http:"POST",method:"impersonateUser"},[`${P}/sessions/revoke`]:{build:({body:e})=>({sessionId:N(e,"sessionId")}),http:"POST",method:"revokeUserSession",returns:"void"},[`${P}/sessions/revoke-all`]:{build:({body:e})=>({userId:N(e,"userId")}),http:"POST",method:"revokeUserSessions",returns:"void"},[`${P}/accounts/unlink`]:{build:({body:e})=>({accountId:N(e,"accountId"),userId:N(e,"userId")}),http:"POST",method:"unlinkAccount",returns:"void"},[`${P}/two-factor/disable`]:{build:({body:e})=>({userId:N(e,"userId")}),http:"POST",method:"disableTwoFactor",returns:"void"},[`${P}/passkeys/delete`]:{build:({body:e})=>({passkeyId:N(e,"passkeyId")}),http:"POST",method:"deletePasskey",returns:"void"},[`${P}/organizations/members/remove`]:{build:({body:e})=>({memberId:N(e,"memberId")}),http:"POST",method:"removeMember",returns:"void"},[`${P}/organizations/invitations/cancel`]:{build:({body:e})=>({invitationId:N(e,"invitationId")}),http:"POST",method:"cancelInvitation",returns:"void"},[`${P}/organizations/create`]:{build:({body:e})=>({logo:re(e,"logo"),metadata:He(e,"metadata"),name:N(e,"name"),ownerId:re(e,"ownerId"),slug:re(e,"slug")}),http:"POST",method:"createOrganization"},[`${P}/organizations/update`]:{build:({body:e})=>({logo:re(e,"logo"),metadata:He(e,"metadata"),name:re(e,"name"),organizationId:N(e,"organizationId"),slug:re(e,"slug")}),http:"POST",method:"updateOrganization"},[`${P}/organizations/remove`]:{build:({body:e})=>({organizationId:N(e,"organizationId")}),http:"POST",method:"deleteOrganization",returns:"void"},[`${P}/organizations/members/add`]:{build:({body:e})=>({organizationId:N(e,"organizationId"),role:re(e,"role"),userId:N(e,"userId")}),http:"POST",method:"addMember"},[`${P}/organizations/members/invite`]:{build:({body:e})=>({email:N(e,"email"),inviterId:re(e,"inviterId"),organizationId:N(e,"organizationId"),role:re(e,"role")}),http:"POST",method:"inviteMember"},[`${P}/organizations/members/role`]:{build:({body:e})=>({memberId:N(e,"memberId"),role:lt(e)}),http:"POST",method:"updateMemberRole"},[`${P}/organizations/teams/create`]:{build:({body:e})=>({name:N(e,"name"),organizationId:N(e,"organizationId")}),http:"POST",method:"createTeam"},[`${P}/organizations/teams/update`]:{build:({body:e})=>({name:N(e,"name"),teamId:N(e,"teamId")}),http:"POST",method:"updateTeam"},[`${P}/organizations/teams/remove`]:{build:({body:e})=>({teamId:N(e,"teamId")}),http:"POST",method:"removeTeam",returns:"void"},[`${P}/organizations/teams/members/add`]:{build:({body:e})=>({teamId:N(e,"teamId"),userId:N(e,"userId")}),http:"POST",method:"addTeamMember"},[`${P}/organizations/teams/members/remove`]:{build:({body:e})=>({teamMemberId:N(e,"teamMemberId")}),http:"POST",method:"removeTeamMember",returns:"void"},[`${P}/organizations/roles/create`]:{build:({body:e})=>({organizationId:N(e,"organizationId"),permission:ht(e),role:N(e,"role")}),http:"POST",method:"createOrgRole"},[`${P}/organizations/roles/update`]:{build:({body:e})=>({permission:ht(e),roleId:N(e,"roleId")}),http:"POST",method:"updateOrgRole"},[`${P}/organizations/roles/remove`]:{build:({body:e})=>({roleId:N(e,"roleId")}),http:"POST",method:"deleteOrgRole",returns:"void"}},xr=e=>{const t=async a=>{try{return await a()}catch(i){if(i instanceof d)throw i;const u=i,h=typeof u.code=="string"?u.code:"AUTH_ADMIN_ERROR";throw console.error("[lunora] auth admin operation failed:",i),new d("auth admin operation failed",{code:h,status:Cr[h]??500})}},n=async(a,i)=>{if(e.assertAdmin(a),a.method!==i.http)throw new d(`Auth admin endpoint requires ${i.http}`,{code:"METHOD_NOT_ALLOWED",status:405});const u=e.getAuthAdmin();if(u===void 0)throw new d("auth endpoints require an `authAdmin` on the worker",{code:"AUTH_NOT_CONFIGURED",status:400});const h=u[i.method];if(h===void 0)throw new d(`auth admin does not support \`${i.method}\``,{code:"AUTH_OP_NOT_SUPPORTED",status:400});const f=new URL(a.url),w={body:i.http==="POST"?await e.readJsonBody(a):{},paging:e.parsePaging(a),query:v=>e.queryParameter(f,v)},E=i.build(w),O=await t(()=>h(E));return Response.json(i.returns==="void"?{ok:!0}:O,{headers:{"content-type":"application/json"},status:200})},o={};for(const[a,i]of Object.entries(Br))o[a]=u=>n(u,i);return o},Hr="__lunora_admin__:getAuthAuditLog",ft=e=>typeof e=="string"&&e!==""?e:void 0,pt=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0,Lr=e=>async(n,o)=>{e.assertAdmin(n);const a=e.getReader();if(a===void 0)throw new d("the auth/security audit endpoint requires an `authAuditReader` on the worker",{code:"AUTH_AUDIT_NOT_CONFIGURED",status:400});const i=ft(o.actorId),u=ft(o.event),h=pt(o.sinceSeq),f=pt(o.limit),w={...i===void 0?{}:{actorId:i},...u===void 0?{}:{event:u},...h===void 0?{}:{sinceSeq:h},...f===void 0?{}:{limit:f}};let E;try{E=await a.read(w)}catch(v){throw v instanceof d?v:(console.error("[lunora] auth audit read failed:",v),new d("auth audit read failed",{code:"AUTH_AUDIT_READ_FAILED",status:500}))}const O={entries:E};return Response.json({result:Qe(O)},{headers:{"content-type":"application/json"},status:200})},Mr=(e,t)=>{const n=[],o=[];if(t&&t.length>0)for(const a of t)e.resolveTableSharding?.(a)?.mode.kind==="global"?o.push(a):n.push(a);return{globalTables:o,shardLocalTables:n}},Kr=async(e,t,n,o,a,i,u)=>{if(n!==void 0&&o.length===0)return;const h=await e.orchestrateExport(i,{args:{tables:o},defaultShardKey:u,headers:t,tables:o});for(const f of h.shards)if(!f.error)for(const w of f.rows??[])a(w)},Gt=async(e,t,n,o,a,i)=>{const u=o??e.listSchemaTables?.();o===void 0&&e.listSchemaTables===void 0&&console.warn("[lunora] export: no table list available (`listSchemaTables` is unset and no `tables` were named), so only the default shard is reachable. A `.shardBy()` deployment's other shards will be missing from this export. Name the tables explicitly, or regenerate the worker so codegen supplies the list.");const{globalTables:h,shardLocalTables:f}=Mr(e,u);await Kr(t,n,u,f,a,i,e.defaultShardKey??"__root__");const w=e.exportGlobals;if((o===void 0||h.length>0)&&w)for await(const O of w({tables:h}))a(O)},jr=new TextEncoder,$r=1e3,Qt=10,Fr=200,mt=8,zt="lunoraBackupCron",wt=24*1048576,gt=e=>{const t=e.slice(0,Qt).map(o=>xt(o)),n=e.length-t.length;return`${t.join(", ")}${n>0?` (+${String(n)} more)`:""}`},Gr=(e,t)=>{const n=new Uint8Array(new ArrayBuffer(t));let o=0;for(const a of e)n.set(a,o),o+=a.byteLength;return n},Ye=async(e,t,n,o)=>{if(n===void 0||!Number.isInteger(n)||n<=0)return{eligible:0,stale:[]};const a=[];let i;for(let u=0;u<$r;u+=1){const h=await e.list({cursor:i,include:["customMetadata"],prefix:t});for(const f of h.objects)Wn(f.key)&&f.customMetadata?.[zt]===o&&a.push(f.key);if(!h.truncated||h.cursor===void 0)break;i=h.cursor}return{eligible:a.length,stale:a.toSorted((u,h)=>h.localeCompare(u)).slice(n)}},Qr=async(e,t,n,o,a)=>{const{stale:i}=await Ye(e,t,n,o),u=new Set(a),h=i.filter(g=>u.has(g)),f=h.slice(0,Fr),w=i.length-f.length,E=a.length-h.length;if(f.length===0)return{deleted:[],failed:[],ignored:E,remaining:w};const O=[],v=[];for(let g=0;g<f.length;g+=mt){const b=await Promise.allSettled(f.slice(g,g+mt).map(async _=>(await e.delete(xt(_)),await e.delete(_),_)));for(const[_,p]of b.entries())p.status==="fulfilled"?O.push(p.value):v.push(f[g+_])}return O.length>0&&console.info(`[lunora] backup prune kept the newest ${String(n)} and deleted ${String(O.length)}: ${gt(O)}`),v.length>0&&console.warn(`[lunora] backup prune failed to remove ${String(v.length)}: ${gt(v)}`),{deleted:O,failed:v,ignored:E,remaining:w}},zr=async e=>{const t=e.backupStore;if(!t)throw new d("backup retention preview requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});const n=We(e.backupPrefix??Ve),o=e.backupCron,{eligible:a,stale:i}=o===void 0?{eligible:0,stale:[]}:await Ye(t,n,e.backupRetain,o);return{cron:o,eligible:a,keep:e.backupRetain??0,prefix:n,wouldDelete:i}},Wr=async(e,t,n,o)=>{const a=e.backupStore,i=e.queryCoordinator;if(!a)throw new d("scheduled backup requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});if(!i)throw new d("scheduled backup requires a `queryCoordinator` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});if(!n||n.length===0)throw new d("scheduled backup requires an `adminToken` (or `env.LUNORA_ADMIN_TOKEN`) to authenticate the per-shard export gate",{code:"BACKUP_NOT_CONFIGURED",status:500});const u={authorization:`Bearer ${n}`,"content-type":"application/json"},h=e.backupTables;let f=0,w=0,E=[];await Gt(e,i,u,h,D=>{const M=jr.encode(`${JSON.stringify(D)}
|
|
2
|
+
`);if(f+=1,w+=M.byteLength,w>wt)throw new d(`scheduled backup reached ${String(w)} bytes of NDJSON, past the ${String(wt)}-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});E.push(M)},t);const v=We(e.backupPrefix??Ve),g=new Date(o.scheduledTime).toISOString(),b=Vn(v,g),_=Gr(E,w);E=[];const p=qn(await crypto.subtle.digest("SHA-256",_));await a.put(b,_,{httpMetadata:{contentType:"application/x-ndjson"},sha256:p});const A={bytes:w,createdAt:g,cron:o.cron,file:b,id:g,rows:f,scheduledTime:o.scheduledTime,sha256:p,...h?{tables:h.join(",")}:{}};await a.put(Jn(b),`${JSON.stringify(A,void 0,2)}
|
|
3
|
+
`,{customMetadata:{[zt]:o.cron},httpMetadata:{contentType:"application/json"}});try{const{stale:D}=await Ye(a,v,e.backupRetain,o.cron);if(D.length>0){const M=D.slice(0,Qt),I=D.length-M.length;console.info(`[lunora] backup retention: ${String(D.length)} snapshot(s) past the newest ${String(e.backupRetain)} — run \`lunora backup prune\` to remove them: ${M.join(", ")}${I>0?` (+${String(I)} more)`:""}`)}}catch(D){console.warn(`[lunora] backup ${b} was written, but the retention report failed:`,D)}},Vr=async(e,t)=>{const n=e.backupStore;if(!n)throw new d("backup prune requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});const o=e.backupCron,a=e.backupRetain;if(o===void 0||a===void 0||!Number.isInteger(a)||a<=0)throw new d("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 Qr(n,We(e.backupPrefix??Ve),a,o,t)},Jr="/_lunora/admin/backup/retention",qr="/_lunora/admin/backup/prune",Yr=e=>{const{options:t,readJsonBody:n,requireAdminOption:o}=e,a=(h,f)=>{o(h,t.backupStore,{code:"BACKUP_NOT_CONFIGURED",message:`backup ${f} requires a \`backupStore\` on the worker`})},i=async h=>(j(h,"GET","Backup-retention"),a(h,"retention preview"),Response.json(await zr(t),{headers:{"cache-control":"no-store"}})),u=async h=>{j(h,"POST","Backup-prune"),a(h,"prune");const{confirm:f}=await n(h);if(!Array.isArray(f)||f.some(w=>typeof w!="string"))throw new d("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 Vr(t,f),{headers:{"cache-control":"no-store"}})};return{[qr]:u,[Jr]:i}},yt=500,Xr=(e,t,n)=>{if(typeof e!="object"||e===null||Array.isArray(e))throw new d("each batch call must be an object",{code:"BAD_REQUEST",status:400});const o=e;if(typeof o.functionPath!="string")throw new d("each batch call needs a string `functionPath`",{code:"BAD_REQUEST",status:400});if(o.functionPath.startsWith("__lunora_relation__:")||o.functionPath.startsWith("__lunora_admin__"))throw new d("reserved function path cannot be batched",{code:"FORBIDDEN",status:403});if(o.args!==void 0&&(typeof o.args!="object"||o.args===null||Array.isArray(o.args)))throw new d("each batch call `args` must be an object",{code:"BAD_REQUEST",status:400});return{entry:{args:o.args===void 0?{}:o.args,clientId:typeof o.clientId=="string"?o.clientId:void 0,clientSeq:typeof o.clientSeq=="number"?o.clientSeq:void 0,functionPath:o.functionPath,id:typeof o.id=="number"?o.id:t,mutationId:typeof o.mutationId=="string"?o.mutationId:void 0},shardKey:typeof o.shardKey=="string"?o.shardKey:n}},Zr=(e,t)=>{if(e.length>yt)throw new d(`RPC batch exceeds the ${String(yt)}-call limit`,{code:"BAD_REQUEST",status:400});const n=new Map;for(const[o,a]of e.entries()){const{entry:i,shardKey:u}=Xr(a,o,t),h=n.get(u)??[];h.push(i),n.set(u,h)}return n},eo="/_lunora/admin/export",to="/_lunora/admin/import",no="/_lunora/admin/sync",ro="/_lunora/admin/connector/sync",oo="/_lunora/admin/apply",ao="/_lunora/admin/export-tap/run",so=new TextEncoder,io=async e=>{const n=await be(e,"Export")??{};if(n.tables===void 0)return{tables:void 0};if(!Array.isArray(n.tables))throw new d("Export `tables` must be a string array",{code:"BAD_REQUEST",status:400});const o=[];for(const a of n.tables){if(typeof a!="string"||a.length===0)throw new d("Export `tables` entries must be non-empty strings",{code:"BAD_REQUEST",status:400});o.push(a)}return{tables:o}},Le=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):void 0,co=e=>{const{applyGlobals:t,defaultShardKey:n,exportCursorStore:o,exportSinks:a,knownTables:i,queryCoordinator:u,assertAdmin:h,requireAdminOption:f,resolveForwardContext:w,shardDO:E,streamExportRows:O,streamingImport:v,syncGlobals:g}=e,b=async(I,F)=>{const H=me(I,["POST"]);if(H)return H;const Y=f(I,u,{code:"BAD_REQUEST",message:"Export endpoint requires a `queryCoordinator` on the worker"}),U=await io(I),{headers:G}=await w(I,F),Q=new ReadableStream({async pull(J){const K=$=>{J.enqueue(so.encode(`${JSON.stringify($)}
|
|
4
|
+
`))};try{await O(Y,G,U.tables,K),J.close()}catch($){J.error($)}}});return new Response(Q,{headers:{"content-type":"application/x-ndjson"},status:200})},_=async(I,F)=>{const H=me(I,["POST"]);if(H)return H;const Y=f(I,u,{code:"BAD_REQUEST",message:"Sync endpoint requires a `queryCoordinator` on the worker"}),U=await Z(I),G=typeof U.cursors=="object"&&U.cursors!==null?U.cursors:{},Q=typeof U.limit=="number"?U.limit:void 0,J=typeof U.globalCursor=="number"?U.globalCursor:0,K=Le(U.tables),{headers:$}=await w(I,F),oe=K??i(),z=await Y.orchestrateCdcSync(E,{cursors:G,defaultShardKey:n,headers:$,limit:Q,tables:oe}),de=g?await g({limit:Q,sinceSeq:J}):void 0;return Response.json({global:de,shards:z.shards},{status:200})},p=async(I,F)=>{const H=me(I,["POST"]);if(H)return H;const Y=f(I,u,{code:"BAD_REQUEST",message:"Connector sync endpoint requires a `queryCoordinator` on the worker"}),U=await Z(I),G=tr(U.cursor),Q=typeof U.limit=="number"&&U.limit>0?U.limit:void 0,J=Le(U.tables),{headers:K}=await w(I,F),$=J??i(),oe=await Y.orchestrateCdcSync(E,{cursors:G.s,defaultShardKey:n,headers:K,limit:Q,tables:$}),z=[],de={...G.s};let ue=!1;for(const ae of oe.shards)ue=at(z,ae.changes??[],rr(Q))||ue,de[ae.shardKey]=ae.cursor;let _e=G.g;if(g){const ae=await g({limit:Q,sinceSeq:G.g});ue=at(z,ae.changes,Q)||ue,_e=ae.cursor}const Oe=nr({g:_e,s:de,v:1}),ve={changes:z,hasMore:ue,nextCursor:Oe};return Response.json(ve,{status:200})},A=async(I,F)=>{const H=me(I,["POST"]);if(H)return H;const Y=f(I,u,{code:"BAD_REQUEST",message:"Apply endpoint requires a `queryCoordinator` on the worker"}),U=await Z(I),Q=(Array.isArray(U.batches)?U.batches:[]).map(z=>z).filter(z=>z!==null&&typeof z=="object"&&typeof z.shardKey=="string"&&Array.isArray(z.changes)),J=Array.isArray(U.globalChanges)?U.globalChanges:[],{headers:K}=await w(I,F),$=await Y.orchestrateApplyCdc(E,{batches:Q,headers:K}),oe=J.length>0&&t?await t({changes:J}):0;return Response.json({applied:$.applied+oe,failed:$.failed,ok:$.ok},{status:200})},D=async(I,F)=>{const H=me(I,["POST"]);if(H)return H;h(I);const{headers:Y}=await w(I,F),U=await v(I,Y);return Response.json(U,{headers:{"content-type":"application/json"},status:U.failed.length>0?207:200})},M=async(I,F)=>{const H=me(I,["POST"]);if(H)return H;const Y=f(I,u,{code:"BAD_REQUEST",message:"Export-tap endpoint requires a `queryCoordinator` on the worker"});if(a===void 0||Object.keys(a).length===0||o===void 0)throw new d("Export-tap endpoint requires `exportSinks` + `exportCursorStore` on the worker",{code:"EXPORT_TAP_NOT_CONFIGURED",status:400});const U=await Z(I),G=typeof U.sink=="string"?U.sink:void 0,Q=typeof U.limit=="number"&&U.limit>0?U.limit:void 0,J=Le(U.tables);if(G===void 0)throw new d("Export-tap `sink` must name a configured sink",{code:"BAD_REQUEST",status:400});const K=a[G];if(K===void 0)throw new d(`Export-tap sink "${G}" is not configured`,{code:"NOT_FOUND",status:404});const{headers:$}=await w(I,F),oe=J??i(),z=await er({coordinator:Y,cursorStore:o,defaultShardKey:n,headers:$,limit:Q,shardDO:E,sink:K,tables:oe});return Response.json(z,{headers:{"content-type":"application/json"},status:200})};return{[oo]:A,[ro]:p,[eo]:b,[ao]:M,[to]:D,[no]:_}},uo=(e,t)=>{let n;try{n=JSON.parse(e)}catch{return{error:{code:"BAD_ROW",line:t,message:"line is not valid JSON",table:""},ok:!1}}if(!n||typeof n!="object"||Array.isArray(n))return{error:{code:"BAD_ROW",line:t,message:"row must be a JSON object",table:""},ok:!1};const o=n;return typeof o.table!="string"||o.table.length===0?{error:{code:"BAD_ROW",line:t,message:"row is missing `table`",table:""},ok:!1}:!o.doc||typeof o.doc!="object"||Array.isArray(o.doc)?{error:{code:"BAD_ROW",line:t,message:"row is missing or malformed `doc`",table:o.table},ok:!1}:{doc:o.doc,ok:!0,table:o.table}},lo=(e,t,n,o,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:o}},ho=async(e,t,n)=>{if(!e.body)throw new d("Import endpoint requires a request body",{code:"BAD_REQUEST",status:400});const o=[],a=[],i=new Map;let u=0,h=0;const f=e.body.getReader(),w=new TextDecoder;let E="",O=0;const v=g=>{h+=1;const b=g.trim();if(b.length===0)return;u+=1;const _=uo(b,h);if(!_.ok){o.push(_.error);return}const{doc:p,table:A}=_,D=t.resolveTableSharding?.(A);if(D?.mode.kind==="global"){a.push({doc:p,line:h,table:A});return}const M=lo(p,A,D,n,h);if(!M.ok){o.push(M.error);return}const I=i.get(M.shardKey);I?I.rows.push({doc:p,table:A}):i.set(M.shardKey,{rows:[{doc:p,table:A}],shardKey:M.shardKey,startLine:h})};for(;;){const{done:g,value:b}=await f.read();if(g)break;if(b&&(O+=b.byteLength,O>Ut))throw await f.cancel().catch(()=>{}),new d("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});E+=w.decode(b,{stream:!0});let _=E.indexOf(`
|
|
5
|
+
`);for(;_!==-1;){const p=E.slice(0,_);E=E.slice(_+1),v(p),_=E.indexOf(`
|
|
6
|
+
`)}}return E.length>0&&v(E),{errors:o,globalRows:a,perShard:i,received:u}},fo=e=>e.flatMap(t=>t.error?[{message:t.error.message,shardKey:t.shardKey,timedOut:t.error.timedOut}]:[]),bt=(e,t)=>{for(const[n,o]of Object.entries(t.inserted))e.inserted[n]=(e.inserted[n]??0)+o;for(const n of t.errors)e.errors.push({...n});e.conflicts+=t.conflicts},po=async(e,t,n,o)=>{const a=t.defaultShardKey??"__root__",{errors:i,globalRows:u,perShard:h,received:f}=await ho(e,t,a),w={conflicts:0,errors:i,failed:[],inserted:{}},E=[];if(t.resolveTableSharding===void 0&&h.size>0&&E.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 O=t.queryCoordinator;if(!O)throw new d("Import endpoint requires a `queryCoordinator` on the worker",{code:"BAD_REQUEST",status:400});const v=await O.orchestrateImport(o,{batches:[...h.values()],headers:n});bt(w,v),w.failed.push(...fo(v.shards))}if(u.length>0)if(t.importGlobals){const O=u[0]?.line??1,v=await t.importGlobals({rows:u,startLine:O});bt(w,v)}else for(const O of u)w.errors.push({code:"GLOBAL_NOT_CONFIGURED",line:O.line,message:`row targets global table "${O.table}" but no \`importGlobals\` is configured`,table:O.table});return{conflicts:w.conflicts,errors:w.errors,failed:w.failed,inserted:w.inserted,received:f,...E.length>0?{warnings:E}:{}}},Me=e=>typeof e=="object"&&e!==null?e:{},Ke=e=>typeof e.kind=="string"?e.kind:"unknown",mo=(e,t)=>{let n=Me(t),o=!1;Ke(n)==="optional"&&(o=!0,n=Me(n._meta?.inner));const a=Ke(n),i=n._meta??{},u={kind:a,name:e,optional:o};if(a==="id"&&typeof i.tableName=="string"&&(u.table=i.tableName),a==="array"){const h=Ke(Me(i.inner));h!=="unknown"&&(u.element=h)}return u},wo=e=>typeof e!="object"||e===null?[]:Object.entries(e).map(([t,n])=>mo(t,n)).toSorted((t,n)=>t.name.localeCompare(n.name)),go="/_lunora/admin/functions",yo="/_lunora/admin/cron-jobs",bo="/_lunora/admin/openapi",_o="/_lunora/admin/openrpc",Ro="/_lunora/admin/global/tables",Eo="/_lunora/admin/global/table",So="/_lunora/admin/global/facet",_t=e=>{if(e===void 0||e==="")return;let t;try{t=Gn(JSON.parse(e))}catch{return}if(!Array.isArray(t))return;const n=t.flatMap(o=>{if(typeof o!="object"||o===null||typeof o.column!="string")return[];const{column:a,value:i}=o;return[{column:a,value:i}]});return n.length===0?void 0:n},Ao=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:{}}),To=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"}),Oo=e=>{const{assertAdmin:t,options:n,parsePaging:o,queryParameter:a,requireAdminOption:i}=e,u=g=>{j(g,"GET","Functions");const b=i(g,n.functions,{code:"FUNCTIONS_NOT_CONFIGURED",message:"functions endpoint requires a `functions` registry on the worker"}),_=Object.entries(b).flatMap(([p,A])=>A.visibility==="internal"||A.kind==="stream"?[]:[{args:wo(A.args),kind:A.kind,path:p}]).toSorted((p,A)=>p.path.localeCompare(A.path));return Response.json({functions:_},{headers:{"content-type":"application/json"},status:200})},h=g=>{j(g,"GET","Cron-jobs");const b=i(g,n.cronJobs,{code:"CRON_JOBS_NOT_CONFIGURED",message:"cron-jobs endpoint requires a `cronJobs` map on the worker"}),_=Object.entries(b).flatMap(([p,A])=>A.map(D=>({args:D.args,cron:p,functionPath:D.functionPath,name:D.name,shardKey:D.shardKey,workflow:D.workflow}))).toSorted((p,A)=>p.name.localeCompare(A.name));return Response.json({jobs:_},{headers:{"content-type":"application/json"},status:200})},f=g=>(j(g,"GET","OpenAPI"),t(g),Response.json(n.openApiSpec??Ao,{headers:{"content-type":"application/json"},status:200})),w=g=>(j(g,"GET","OpenRPC"),t(g),Response.json(n.openRpcSpec??To,{headers:{"content-type":"application/json"},status:200})),E=async g=>{j(g,"GET","Global-tables");const b=i(g,n.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"});return Response.json(await b.listTables(),{headers:{"content-type":"application/json"},status:200})},O=async g=>{j(g,"GET","Global-table");const b=i(g,n.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),_=new URL(g.url),p=a(_,"table");if(p===void 0)throw new d("Global-table endpoint requires a `table` query param",{code:"BAD_REQUEST",status:400});const A=await b.readTablePage({...o(g),filters:_t(a(_,"filters")),table:p});return Response.json(A,{headers:{"content-type":"application/json"},status:200})},v=async g=>{j(g,"GET","Global-facet");const b=i(g,n.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),_=new URL(g.url),p=a(_,"table"),A=a(_,"column");if(p===void 0||A===void 0)throw new d("Global-facet endpoint requires `table` and `column` query params",{code:"BAD_REQUEST",status:400});const D=a(_,"limit"),M=D===void 0?void 0:Number(D),I=await b.facetColumn({column:A,filters:_t(a(_,"filters")),limit:M!==void 0&&Number.isFinite(M)?M:void 0,table:p});return Response.json(I,{headers:{"content-type":"application/json"},status:200})};return{[yo]:h,[go]:u,[So]:v,[Eo]:O,[Ro]:E,[bo]:f,[_o]:w}},vo="/_lunora/admin/kv/namespaces",ko="/_lunora/admin/kv/keys",Wt="/_lunora/admin/kv/value",Vt=32*1048576,Rt=60,Io=e=>{const{readJsonBody:t,requireAdminOption:n}=e,o=b=>n(b,e.kvIntrospector,{code:"KV_NOT_CONFIGURED",message:"KV endpoints require a `kvIntrospector` on the worker"}),a=b=>Response.json(b,{headers:{"content-type":"application/json"},status:200}),i=(b,_)=>{const p=new URL(b.url),A=p.searchParams.get("namespace")??"",D=p.searchParams.get("key")??"";if(A==="")throw new d(`KV-value ${_} request requires a \`namespace\` query parameter`,{code:"BAD_REQUEST",status:400});if(D==="")throw new d(`KV-value ${_} request requires a \`key\` query parameter`,{code:"BAD_REQUEST",status:400});return{key:D,namespace:A}},u=async(b,_)=>{if(!(await b.listNamespaces()).some(A=>A.binding===_))throw new d(`Unknown KV namespace binding \`${_}\``,{code:"NOT_FOUND",status:404})},h=async b=>(j(b,"GET","KV-namespaces"),a({namespaces:await o(b).listNamespaces()})),f=async b=>{j(b,"GET","KV-keys");const _=o(b),p=new URL(b.url),A=p.searchParams.get("namespace")??"";if(A==="")throw new d("KV-keys request requires a `namespace` query parameter",{code:"BAD_REQUEST",status:400});const D=p.searchParams.get("prefix")??void 0,M=p.searchParams.get("cursor")??void 0,I=p.searchParams.get("limit"),F=I===null?void 0:Number.parseInt(I,10);if(F!==void 0&&(!Number.isInteger(F)||F<1))throw new d("KV-keys `limit` must be a positive integer",{code:"BAD_REQUEST",status:400});const H=F===void 0?void 0:Math.min(F,1e3);return await u(_,A),a(await _.listKeys({cursor:M,limit:H,namespace:A,prefix:D}))},v={DELETE:async b=>{const _=o(b),p=i(b,"DELETE");return await u(_,p.namespace),await _.deleteKey(p),a({deleted:!0})},GET:async b=>{const _=o(b),p=i(b,"GET");return await u(_,p.namespace),a(await _.getValue(p))},PUT:async b=>{const _=o(b),p=await t(b,Vt);if(typeof p.namespace!="string"||p.namespace==="")throw new d("KV-value PUT request requires a `namespace` string",{code:"BAD_REQUEST",status:400});if(typeof p.key!="string"||p.key==="")throw new d("KV-value PUT request requires a `key` string",{code:"BAD_REQUEST",status:400});if(typeof p.value!="string")throw new d("KV-value PUT request requires a `value` string",{code:"BAD_REQUEST",status:400});if(p.expirationTtl!==void 0&&(typeof p.expirationTtl!="number"||!Number.isInteger(p.expirationTtl)||p.expirationTtl<Rt))throw new d("KV-value PUT `expirationTtl` must be an integer ≥ 60",{code:"BAD_REQUEST",status:400});const A=Math.floor(Date.now()/1e3)+Rt;if(p.expiration!==void 0&&(typeof p.expiration!="number"||!Number.isInteger(p.expiration)||p.expiration<A))throw new d("KV-value PUT `expiration` must be a Unix-seconds timestamp at least 60 seconds in the future",{code:"BAD_REQUEST",status:400});return await u(_,p.namespace),await _.putValue({expiration:p.expiration,expirationTtl:p.expirationTtl,key:p.key,metadata:p.metadata,namespace:p.namespace,value:p.value}),a({ok:!0})}},g=b=>{const _=v[b.method];if(!_)throw new d("KV-value endpoint requires GET, PUT, or DELETE",{code:"METHOD_NOT_ALLOWED",status:405});return _(b)};return{[vo]:h,[ko]:f,[Wt]:g}},Po="/_lunora/migrate",Do="/_lunora/admin/pitr",No="/_lunora/admin/rank",Uo="/_lunora/admin/rankpage",Co="/_lunora/admin/shard-traffic",Bo=new Set(["__lunora_admin__:migrationStatus","__lunora_admin__:runMigration"]),xo=new Set(["__lunora_admin__:getPitrBookmark","__lunora_admin__:pitrRestore"]),Ho=async e=>{const n=await be(e,"Migration")??{};if(typeof n.table!="string"||n.table.length===0)throw new d("Migration request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof n.functionPath!="string"||!Bo.has(n.functionPath))throw new d("Migration request `functionPath` must be a migration admin op",{code:"BAD_REQUEST",status:400});return{args:n.args??{},functionPath:n.functionPath,table:n.table}},Lo=async e=>{const n=await be(e,"Rank")??{};if(typeof n.table!="string"||n.table.length===0)throw new d("Rank request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof n.index!="string"||n.index.length===0)throw new d("Rank request is missing `index`",{code:"BAD_REQUEST",status:400});if(typeof n.partitionKey!="string")throw new d("Rank request `partitionKey` must be a string",{code:"BAD_REQUEST",status:400});if(typeof n.rowId!="string"||n.rowId.length===0)throw new d("Rank request is missing `rowId`",{code:"BAD_REQUEST",status:400});if(!Array.isArray(n.sortValues))throw new d("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}},Mo=e=>{if(e!==void 0){if(!Array.isArray(e)||e.some(t=>t!=="asc"&&t!=="desc"))throw new d('Rank page request `directions` must be an array of "asc"|"desc"',{code:"BAD_REQUEST",status:400});return e}},Ko=e=>{if(typeof e.table!="string"||e.table.length===0)throw new d("Rank page request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof e.index!="string"||e.index.length===0)throw new d("Rank page request is missing `index`",{code:"BAD_REQUEST",status:400});if(e.partitionKey!==void 0&&typeof e.partitionKey!="string")throw new d("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 d("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 d("Rank page request `cursor` must be a string or null",{code:"BAD_REQUEST",status:400})},jo=async e=>{const n=await be(e,"Rank page")??{};Ko(n);const o=Mo(n.directions);return{cursor:typeof n.cursor=="string"?n.cursor:null,directions:o,index:n.index,partitionKey:typeof n.partitionKey=="string"?n.partitionKey:void 0,table:n.table,take:typeof n.take=="number"?n.take:void 0}},$o=async e=>{const n=await be(e,"Shard-traffic")??{};if(typeof n.table!="string"||n.table.length===0)throw new d("Shard-traffic request is missing `table`",{code:"BAD_REQUEST",status:400});return{table:n.table}},Fo=async e=>{const n=await Z(e);if(typeof n.functionPath!="string"||!xo.has(n.functionPath))throw new d("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 d("PITR `shardKey` must be a string",{code:"BAD_REQUEST",status:400});return{args:n.args??{},functionPath:n.functionPath,shardKey:n.shardKey}},Go=e=>{const{defaultShard:t,forwardToShard:n,isAdmin:o,queryCoordinator:a,resolveForwardContext:i,shardDO:u}=e,h=(g,b)=>{if(g.method!=="POST")throw new d(`${b} endpoint requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});if(!o(g))throw new d("Admin auth required",{code:"FORBIDDEN",status:403});if(!a)throw new d(`${b} endpoint requires a \`queryCoordinator\` on the worker`,{code:"BAD_REQUEST",status:400});return a},f=async(g,b)=>{const _=h(g,"Migration"),p=await Ho(g),{headers:A}=await i(g,b),D=await _.orchestrateMigration(u,{args:p.args,defaultShardKey:t,functionPath:p.functionPath,headers:A,table:p.table});return Response.json(D,{headers:{"content-type":"application/json"},status:200})},w=async(g,b)=>{const _=h(g,"Rank"),p=await Lo(g),{headers:A}=await i(g,b),D=await _.orchestrateRank(u,{headers:A,index:p.index,partitionKey:p.partitionKey,rowId:p.rowId,sortValues:p.sortValues,table:p.table});return Response.json(D,{headers:{"content-type":"application/json"},status:200})},E=async(g,b)=>{const _=h(g,"Rank page"),p=await jo(g),{headers:A}=await i(g,b),D=await _.orchestrateRankPage(u,{...p,headers:A});return Response.json(D,{headers:{"content-type":"application/json"},status:200})},O=async(g,b)=>{const _=h(g,"Shard-traffic"),p=await $o(g),{headers:A}=await i(g,b),D=await _.orchestrateShardTraffic(u,{headers:A,table:p.table});return Response.json(D,{headers:{"content-type":"application/json"},status:200})},v=async(g,b)=>{if(j(g,"POST","PITR"),!o(g))throw new d("admin PITR endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403});const _=await Fo(g),{headers:p}=await i(g,b),A=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:_.args,functionPath:_.functionPath}),headers:p,method:"POST"});return n(u,_.shardKey??t,A)};return{[Po]:f,[Do]:v,[No]:w,[Uo]:E,[Co]:O}},Qo=1,zo=0,Wo=32,Vo=512,Jo=/^[a-z][\d_a-z*/-]{0,255}(?:@[a-z][\d_a-z*/-]{0,13})?=[\u0020-\u002B\u002D-\u003C\u003E-\u007E]{1,256}$/,qo=e=>{if(e==null)return;const t=e.trim();if(t.length===0||t.length>Vo)return;const n=t.split(",");if(!(n.length>Wo)){for(const o of n)if(!Jo.test(o.trim()))return;return t}},Yo=e=>{const t=Mn(e.headers.get("traceparent"));if(t===void 0)return;const n=qo(e.headers.get("tracestate"));return{parentSpanId:t.parentSpanId,sampled:t.sampled,traceId:t.traceId,...n===void 0?{}:{traceState:n}}},Xo=(e,t={})=>{const n=Yo(e),o=t.trustInbound===!0?n:void 0,a=Te(8),i=o?.traceId??Te(16),u=dr(t.sampling,o===void 0?a:i),h=u.isTraced&&(o===void 0||o.sampled);return{decision:u,ignoredUpstream:n!==void 0&&o===void 0,trace:{sampled:h,spanId:a,traceFlags:h?Qo:zo,traceId:i,...o?.parentSpanId===void 0?{}:{parentSpanId:o.parentSpanId},...o?.traceState===void 0?{}:{traceState:o.traceState}}}},Zo=(e,t)=>{t.traceparent=Ln(e.traceId,e.spanId,e.sampled),e.traceState!==void 0&&(t.tracestate=e.traceState)},ea=(e,t)=>{let n;return()=>{if(n===void 0){const o=Fn(e),a=t===void 0?void 0:t.cf;n=Kn($n(o),jn(o,a))}return n}},ta="/_lunora/admin/scheduled",na="/_lunora/admin/scheduled/status",ra="/_lunora/admin/scheduled/ws",oa="/_lunora/admin/scheduled/cancel",aa="/_lunora/admin/scheduled/dead",sa="/_lunora/admin/scheduled/dead/retry",ia="/_lunora/admin/scheduled/dead/cancel",ca=e=>{const{checkWsAdmin:t,requireSchedulerNamespace:n,resolveSchedulerStub:o,schedulerInstanceName:a}=e,i=(f,w)=>E=>{if(E.method!=="GET")throw new d(`${w} endpoint requires GET`,{code:"METHOD_NOT_ALLOWED",status:405});return o(E).fetch(new Request(`https://scheduler.internal${f}`,{method:"GET"}))},u=(f,w,E=w)=>async O=>{if(O.method!=="POST")throw new d(`${E} requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});const v=o(O),g=await O.json().catch(()=>{});if(typeof g?.id!="string"||g.id==="")throw new d(`${w} requires a string \`id\``,{code:"BAD_REQUEST",status:400});return v.fetch(new Request(`https://scheduler.internal${f}`,{body:JSON.stringify({id:g.id}),headers:{"content-type":"application/json"},method:"POST"}))},h=async f=>{if(f.headers.get("Upgrade")!=="websocket")throw new d("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});if(!await t(f))throw new d("admin authorization required",{code:"ADMIN_FORBIDDEN",status:403});const w=n();return we(w,a).fetch(new Request("https://scheduler.internal/ws",{headers:{Upgrade:"websocket"}}))};return{[oa]:u("/cancel","Scheduled-cancel","Scheduled-cancel endpoint"),[ia]:u("/dead/cancel","Scheduled dead-letter action"),[aa]:i("/dead","Scheduled dead-letter"),[sa]:u("/dead/retry","Scheduled dead-letter action"),[ta]:i("/list","Scheduled-list"),[na]:i("/status","Scheduler-status"),[ra]:h}},da=(e,...t)=>{let n=e.cf;for(const o of t){if(typeof n!="object"||n===null)return;n=n[o]}return typeof n=="string"?n:void 0},Et={mtls:e=>da(e,"tlsClientAuth","certVerified")==="SUCCESS"},ua=e=>e===void 0||e===!1?()=>!1:e===!0?()=>!0:typeof e=="function"?e:(Object.hasOwn(Et,e)?Et[e]:void 0)??(()=>!1),la=e=>{if(e!==void 0)return()=>{};let t=!1;return()=>{t||(t=!0,console.warn('[lunora] Ignored an inbound `traceparent`, so this request starts a new trace instead of joining the caller\'s. That is the safe default: the header is caller-supplied, and trusting it lets any client choose which trace its spans and logs join. If this worker sits behind a gateway, service mesh, or Cloudflare Access that sets `traceparent` itself, set `trustInboundTraceContext: true` on createWorker() (or `"mtls"` to trust only edge-verified client certificates). Set it to `false` to keep this behaviour and silence this message.'))}},ha="/_lunora/admin/vector/indexes",fa="/_lunora/admin/vector/query",pa=e=>{const{readJsonBody:t,requireAdminOption:n}=e,o=async i=>{j(i,"GET","Vector-indexes");const u=n(i,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});return Response.json({indexes:await u.listIndexes()},{headers:{"content-type":"application/json"},status:200})},a=async i=>{j(i,"POST","Vector-query");const u=n(i,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});if(u.queryIndex===void 0)throw new d("vector index querying is not enabled on this worker",{code:"VECTOR_QUERY_UNSUPPORTED",status:400});const f=await t(i);if(typeof f.name!="string"||f.name==="")throw new d("Vector-query request requires a `name` string",{code:"BAD_REQUEST",status:400});if(typeof f.text!="string"||f.text==="")throw new d("Vector-query request requires a `text` string",{code:"BAD_REQUEST",status:400});if(f.topK!==void 0&&(typeof f.topK!="number"||!Number.isInteger(f.topK)||f.topK<1))throw new d("Vector-query `topK` must be a positive integer",{code:"BAD_REQUEST",status:400});const w=await u.queryIndex({name:f.name,text:f.text,topK:f.topK});return Response.json(w,{headers:{"content-type":"application/json"},status:200})};return{[ha]:o,[fa]:a}},ma="/_lunora/admin/workflows/instances",wa="/_lunora/admin/workflows/instance",ga="/_lunora/admin/workflows/status",ya={complete:!0,errored:!0,paused:!0,queued:!0,running:!0,terminated:!0,unknown:!0,waiting:!0,waitingForPause:!0},ba=e=>e!==null&&Object.hasOwn(ya,e)?e:void 0,St=(e,t)=>{const n=e.searchParams.get(t);if(n===null)return;const o=Number(n);return Number.isInteger(o)&&o>0?o:void 0},je=(e,t)=>{const n=e.searchParams.get(t);if(n===null||n==="")throw new d(`Workflows admin endpoint requires a \`${t}\` query parameter`,{code:"BAD_REQUEST",status:400});return n},At=()=>{throw new d("Workflow inspection is unconfigured. Set CLOUDFLARE_ACCOUNT_ID + CLOUDFLARE_API_TOKEN in your .dev.vars to enable it.",{code:"WORKFLOWS_NOT_CONFIGURED",status:501})},_a=e=>{const{assertAdmin:t,resolveWorkflowsClient:n}=e,o=async(u,h,f)=>{j(u,"GET","Workflows instances"),t(u);const w=n(h);if(!w)return Response.json({configured:!1,instances:[],page:1,perPage:0,totalCount:0});const E=je(f,"name"),O=ba(f.searchParams.get("status"));return Response.json(await w.listInstances({page:St(f,"page"),perPage:St(f,"perPage"),status:O,workflowName:E}))},a=async(u,h,f)=>{j(u,"GET","Workflows instance"),t(u);const w=n(h);return w?Response.json(await w.getInstance({instanceId:je(f,"id"),workflowName:je(f,"name")})):At()},i=async(u,h)=>{j(u,"POST","Workflows status"),t(u);const f=n(h);if(!f)return At();const w=await u.json().catch(()=>{});if(typeof w?.name!="string"||w.name===""||typeof w.id!="string"||w.id==="")throw new d("Workflows status action requires string `name` and `id`",{code:"BAD_REQUEST",status:400});const{action:E}=w;if(E!=="pause"&&E!=="resume"&&E!=="terminate")throw new d("Workflows status action must be one of: pause, resume, terminate",{code:"BAD_REQUEST",status:400});return Response.json(await f.setInstanceStatus({action:E,instanceId:w.id,workflowName:w.name}))};return{[wa]:a,[ma]:o,[ga]:i}},Ra={[Wt]:Vt,[Zn]:Xn},Tt="/_lunora/rpc",Ea="/_lunora/rpc-batch",Sa="/_lunora/ws",Ee=(e,t,n)=>({resourceAttributes:ea(e,t),...n===void 0?{}:{waitUntil:n}}),$e=e=>e?.waitUntil?{waitUntil:t=>e.waitUntil?.(t)}:{},Ot=e=>({spanId:e.spanId,traceFlags:e.traceFlags,traceId:e.traceId,...e.parentSpanId===void 0?{}:{parentSpanId:e.parentSpanId}}),Fe=e=>{const{method:t}=e,n=e.headers.get("user-agent")??void 0;let o;try{o=new URL(e.url)}catch{return{method:t,userAgent:n}}const a=o.port===""?void 0:Number(o.port);return{host:o.hostname,method:t,path:o.pathname,port:Number.isNaN(a)?void 0:a,scheme:o.protocol.replace(":",""),userAgent:n}},vt="/_lunora/voice/",Aa="/_lunora/scheduler/dispatch",Ta="/_lunora/admin/cron-jobs/run",Oa="/_lunora/admin/ws-token",va="/_lunora/admin/",ka="/_lunora/migrate",Ia="/_lunora/status",Pa=e=>e.startsWith(va)||e===ka,Da=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}}},Na="/api/auth",Ua="__lunora_admin__:recordAuthEvent",Ca="__lunora_admin__:listPushSubscriptions",Ba=["/sign-in","/sign-up","/callback"],xa=(e,t)=>{const n=t.endsWith("/")?t.slice(0,-1):t;if(!e.startsWith(`${n}/`))return!1;const o=e.slice(n.length);return Ba.some(a=>o===a||o.startsWith(`${a}/`))},Se=(e,t,n,o)=>{const a=Dn(n),i=a?n.code:"INTERNAL_SERVER_ERROR",u=a?n.status:500,h=n instanceof Error?n.message:String(n);return{durationMs:t,error:{code:i,message:h,status:u},functionPath:e,ok:!1,...o.fanOut?{fanOut:{failed:0,shards:0,table:o.fanOut.table}}:{},...o.shardKey?{shardKey:o.shardKey}:{}}},Ha=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},kt=e=>e.waitUntil?{waitUntil:t=>{e.waitUntil?.(t)}}:void 0,La=e=>{const t=e?.queue;return typeof t=="string"&&t.length>0?t:"unknown"},ze=new WeakMap,ce=async(e,t,n,o=ze.get(e))=>{const a={"content-type":"application/json"},i=e.headers.get("authorization"),u=e.headers.get("cookie"),h=e.headers.get("x-d1-bookmark"),f=e.headers.get("x-lunora-mutation-id"),w=e.headers.get("x-lunora-client-id"),E=e.headers.get("x-lunora-client-seq");i&&(a.authorization=i),u&&(a.cookie=u),h&&(a["x-d1-bookmark"]=h),f&&(a["x-lunora-mutation-id"]=f),w&&(a["x-lunora-client-id"]=w),E&&(a["x-lunora-client-seq"]=E);const O=e.headers.get("cf-connecting-ip");if(O&&(a["x-lunora-client-ip"]=O),!n)return{claims:null,headers:a,identity:null,userId:null};const v=await n(e,t,o);if(!v||typeof v.userId!="string"||v.userId.length===0)return{claims:null,headers:a,identity:null,userId:null};a["x-lunora-userid"]=xn(v.userId);const g=Ha(v);g!==void 0&&(a["x-lunora-identity-exp"]=String(g));const{userId:b,..._}=v,p=Object.keys(_).length>0?_:null;return p&&(a["x-lunora-identity"]=Hn(p)),{claims:p,headers:a,identity:v,userId:b}},Ma=new Set(["concat","first","groupBy","max","min","rank","sum","topK"]),Ka=e=>{if(e===void 0)return;if(!e||typeof e!="object")throw new d("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 d("RPC `fanOut.table` must be a non-empty string",{code:"BAD_REQUEST",status:400});if(!t.merge||typeof t.merge!="object")throw new d("RPC `fanOut.merge` must be an object",{code:"BAD_REQUEST",status:400});const n=t.merge;if(typeof n.kind!="string"||!Ma.has(n.kind))throw new d("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 d("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 d("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}`)},Ge=(e,t)=>{const n=t.functions?.[e.functionPath]?.x402;if(n){if(e.fanOut)throw new d("a paid (`.x402`) function cannot be fanned out",{code:"BAD_REQUEST",status:400});if(!t.x402Charge)throw new d(`function "${e.functionPath}" is marked paid (.x402) but no x402Charge gate is configured on the worker`,{code:"MISCONFIGURED",status:500});return n}},$a=async e=>{const t=await Bt(e);let n;try{n=JSON.parse(t)}catch{throw new d("RPC body must be valid JSON",{code:"BAD_REQUEST",status:400})}if(!n||typeof n!="object"||typeof n.functionPath!="string")throw new d("RPC envelope is missing `functionPath`",{code:"BAD_REQUEST",status:400});const o=n;if(o.args!==void 0&&Ct(o.args,"RPC"),o.shardKey!==void 0&&typeof o.shardKey!="string")throw new d("RPC `shardKey` must be a string",{code:"BAD_REQUEST",status:400});const a=n,i=Ka(a.fanOut),u=a.args??{};if(i&&a.functionPath.startsWith("__lunora_relation__:")){const h=u.table;if(typeof h=="string"&&h!==i.table)throw new d("RPC `args.table` must match the authorized `fanOut.table` for a relation fan-out",{code:"BAD_REQUEST",status:400});u.table=i.table}return{args:u,fanOut:i,functionPath:a.functionPath,shardKey:a.shardKey}},Ae=new Map,Fa=5e3,Ga=4096,Qa=async(e,t)=>{const n=Date.now(),o=Ae.get(t);if(o!==void 0&&o.expiresMs>n)return o.relayCount;o!==void 0&&Ae.delete(t);let a=0;try{const i=await we(e,t).fetch(new Request("https://shard.internal/_lunora/route"));if(i.ok){const h=(await i.json()).relayCount;typeof h=="number"&&h>0&&(a=Math.floor(h))}}catch{a=0}return Nt(Ae,Ga),Ae.set(t,{expiresMs:n+Fa,relayCount:a}),a},It=(e,t)=>{if(!(e===null||typeof e!="object"))return Object.entries(e).find(([,n])=>n===t)?.[0]},ye=(e,t,n)=>new Request("https://shard.internal/rpc",{body:JSON.stringify({args:t,functionPath:e}),headers:n,method:"POST"}),za=["x-lunora-userid","x-lunora-identity","x-lunora-identity-exp"],Wa=(e,t)=>{for(const n of za){e.delete(n);const o=t[n];o!==void 0&&e.set(n,o)}},Pt=(e,t)=>{const n=new Headers(e.headers),o=[...n.keys()];for(const a of o)a.startsWith("x-lunora-")&&n.delete(a);return Wa(n,t),n},Va=async(e,t,n)=>e.length===0||n.length===0?!1:Je(await Mt(e,t),n),Dt=(e,t)=>{if(!t||t.length===0)return!1;const n=e.headers.get("authorization");if(!n)return!1;const[o,...a]=n.split(" ");return o?.toLowerCase()!=="bearer"?!1:Je(t,a.join(" ").trim())},Ja=async(e,t,n)=>{if(!t||t.length===0)return!1;const o=new URL(e.url).searchParams.get("token");return o===null?!1:await Ur(t,o)?!0:n?!1:Je(t,o)},qa=(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 sr(`d1:${e}`,t);if(typeof n.list=="function"&&typeof n.head=="function"&&typeof n.createMultipartUpload=="function")return Be(`r2:${e}`,!0);if(typeof n.send=="function"&&typeof n.sendBatch=="function"&&typeof n.get!="function")return Be(`queue:${e}`,!0);if(typeof n.connectionString=="string")return Be(`hyperdrive:${e}`,!0)},Jt=e=>{const t=ua(e.trustInboundTraceContext),n=la(e.trustInboundTraceContext),o=e.defaultShardKey??"__root__",a=ir(e.resolveIdentity,e.identity),i=it(e.shardDO,e.jurisdiction),u=e.schedulerDO===void 0?void 0:it(e.schedulerDO,e.jurisdiction);let h=!1;const f=r=>{if(r===void 0||e.jurisdiction===void 0)return r;h||(h=!0,console.warn(`[lunora] jurisdiction "${e.jurisdiction}" pins placement, so region hints (\`shardRegion\`, replica and relay placement) are not sent. Residency wins.`))},w=async(r,s,l,c=e.shardRegion?.(s))=>we(r,s,f(c)).fetch(l);let E;const O=()=>e.adminToken??E;let v;const g=()=>e.requireEphemeralWsToken??v??!0;let b;const _=r=>{const s=r??{};if(b??=It(r,e.shardDO),v===void 0&&e.requireEphemeralWsToken===void 0){const c=s.LUNORA_REQUIRE_EPHEMERAL_WS_TOKEN;typeof c=="string"&&c.length>0&&(v=Pr(c,!0))}if(E!==void 0||e.adminToken!==void 0)return;const l=s.LUNORA_ADMIN_TOKEN;typeof l=="string"&&l.length>0&&(E=l)},p=new WeakSet,A=r=>Dt(r,O())||p.has(r),D=async(r,s)=>{const l=await ce(r,s,e.resolveIdentity);if(p.has(r)&&l.headers.authorization===void 0){const c=O();c!==void 0&&(l.headers.authorization=`Bearer ${c}`)}return l};let M=!1,I=!1;const F=()=>{I||(I=!0,console.warn("[lunora] `replicaReads: true` has no effect without `functions` — read eligibility is decided from the function registry."))},H=r=>{if(!e.allowUnauthenticatedShardAccess){const s=r==="fan-out"?"authorizeFanOut":"authorizeShard";throw new d(`${r} access is default-denied: configure \`${s}\` on the worker, or set \`allowUnauthenticatedShardAccess: true\` to explicitly allow unauthenticated ${r} access (relying solely on per-row RLS).`,{code:r==="fan-out"?"FORBIDDEN_FANOUT":"FORBIDDEN_SHARD",status:403})}M||(M=!0,console.warn([`[lunora] SECURITY: serving ${r} access with \`allowUnauthenticatedShardAccess: true\` and no \`authorizeShard\`/\`authorizeFanOut\` — `,"any caller (including unauthenticated ones) can target any shard / fan out across the table. ","This is safe only if every table is protected by per-row RLS. Configure `authorizeShard`/`authorizeFanOut` to gate it."].join("")))},Y=async(r,s)=>{if(e.authorizeShard){if(!await e.authorizeShard({identity:r,shardKey:s}))throw new d("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else s!==o&&H("shard")},U=Go({defaultShard:o,forwardToShard:w,isAdmin:A,queryCoordinator:e.queryCoordinator,resolveForwardContext:D,shardDO:i}),G=async(r,s,l,c,m)=>{const R={"content-type":"application/json","x-lunora-system":"1"};return m?.userId!==void 0&&m.userId.length>0&&(R["x-lunora-userid"]=m.userId),m?.identity!==void 0&&m.identity.length>0&&(R["x-lunora-identity"]=m.identity),c!==void 0&&c.length>0&&(R["x-lunora-mutation-id"]=c),w(i,l,ye(r,s,R))},Q=async(r,s,l,c)=>{const m=l?.[r];if(!m||typeof m.create!="function")throw new d(`${c} targets workflow binding "${r}", which is not bound on env`,{code:"CRON_JOB_FAILED",status:500});if(fr(s))throw new d(`${c} params ${pr}`,{code:"BAD_REQUEST",status:400});await m.create({params:s})},J=async(r,s)=>{if(r.workflow){await Q(r.workflow,r.args??{},s,`cron job "${r.name}"`);return}if(r.functionPath===void 0)throw new d(`cron job "${r.name}" has neither a function target nor a workflow target`,{code:"CRON_JOB_FAILED",status:500});const l=await G(r.functionPath,r.args??{},r.shardKey??o);if(!l.ok)throw new d(`cron job "${r.name}" (${r.functionPath}) failed with shard status ${String(l.status)}`,{code:"CRON_JOB_FAILED",status:500})},K=r=>{if(!A(r))throw new d("admin endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403})},$=(r,s,l)=>{if(K(r),s===void 0)throw new d(l.message,{code:l.code,status:400});return s},oe=async(r,s,l,c)=>{const m=e.cronJobs?.[r];if(m)for(const R of m)try{await J(R,s)}catch(k){l.push(c(k))}},z=async(r,s)=>{if(K(r),j(r,"POST","cron-jobs run"),!e.cronJobs)throw new d("cron-jobs run endpoint requires a `cronJobs` map on the worker",{code:"CRON_JOBS_NOT_CONFIGURED",status:400});const l=await Z(r),c=typeof l.name=="string"?l.name:"";if(c==="")throw new d("cron-jobs run endpoint requires a job `name`",{code:"BAD_REQUEST",status:400});const m=Object.values(e.cronJobs).flat().find(R=>R.name===c);if(!m)throw new d(`no cron job named "${c}" is registered`,{code:"CRON_JOB_NOT_FOUND",status:404});return await J(m,s),Response.json({name:c,ran:!0},{status:200})},de=async r=>{const s=typeof r.pool=="string"&&r.pool.length>0?r.pool:void 0;if(!s||!u||typeof r.id!="string")return;const l=typeof r.instanceName=="string"&&r.instanceName.length>0?r.instanceName:"default";try{await we(u,l).fetch(new Request("https://scheduler.internal/complete",{body:JSON.stringify({id:r.id,pool:s}),headers:{"content-type":"application/json"},method:"POST"}))}catch{}},ue=async(r,s)=>{j(r,"POST","Scheduler dispatch");const l=await Bt(r),c=s??{},m=typeof c.LUNORA_SCHEDULER_SECRET=="string"?c.LUNORA_SCHEDULER_SECRET:void 0,R=e.adminToken??(typeof c.LUNORA_ADMIN_TOKEN=="string"?c.LUNORA_ADMIN_TOKEN:void 0),k=r.headers.get("x-lunora-scheduler-signature");let y=!1;if(k&&m?y=await Va(m,l,k):R&&(y=Dt(r,R)),!y)throw new d("Scheduler dispatch requires a valid signature or admin bearer",{code:"FORBIDDEN",status:403});let S;try{S=JSON.parse(l)}catch{throw new d("Scheduler dispatch body must be valid JSON",{code:"BAD_REQUEST",status:400})}const T=S??{},B=T.args??{};if(typeof T.workflow=="string"&&T.workflow.length>0)return await Q(T.workflow,B,s,"scheduled workflow"),await de(T),Response.json({ok:!0},{status:200});if(typeof T.functionPath!="string"||T.functionPath.length===0)throw new d("Scheduler dispatch is missing `functionPath`",{code:"BAD_REQUEST",status:400});const x=typeof T.shardKey=="string"&&T.shardKey.length>0?T.shardKey:o,C=typeof T.id=="string"&&T.id.length>0?T.id:void 0,te=Da(r),L=await G(T.functionPath,B,x,C,te);return await de(T),L},_e=Lr({assertAdmin:K,getReader:()=>e.authAuditReader}),Oe=async(r,s)=>{K(r);const l=e.notifySubscriptionStore;if(l===void 0)return Response.json({result:Qe({subscriptions:[]})},{headers:{"content-type":"application/json"},status:200});const c=s?.kind,m=s?.userId,R=s?.limit,k=c==="fcm"||c==="web-push"?c:void 0,y=typeof m=="string"&&m!==""?m:void 0,S=typeof R=="number"&&Number.isFinite(R)?Math.trunc(R):0,T=S>0?Math.min(S,1e3):1e3,x=(await l.list({kind:k,limit:T,userId:y})).filter(C=>k!==void 0&&C.kind!==k?!1:y===void 0||(C.userId??null)===y).map(({keys:C,token:te,...L})=>L);return Response.json({result:Qe({subscriptions:x})},{headers:{"content-type":"application/json"},status:200})},ve=async(r,s)=>{if(!s.fanOut){if(s.functionPath===Hr)return _e(r,s.args??{});if(s.functionPath===Ca)return Oe(r,s.args)}},ae=co({applyGlobals:e.applyGlobals,assertAdmin:K,exportCursorStore:e.exportCursorStore,exportSinks:e.exportSinks,defaultShardKey:o,knownTables:()=>[...e.listSchemaTables?.()??[]],queryCoordinator:e.queryCoordinator,requireAdminOption:$,resolveForwardContext:D,shardDO:i,streamExportRows:(r,s,l,c)=>Gt(e,r,s,l,c,i),streamingImport:(r,s)=>po(r,e,s,i),syncGlobals:e.syncGlobals}),ke=(r,s)=>{const l=r.searchParams.get(s);return l===null||l===""?void 0:l},Ie=r=>{const s=new URL(r.url),l=s.searchParams.get("limit"),c=s.searchParams.get("offset"),m=l===null?void 0:Number.parseInt(l,10),R=c===null?void 0:Number.parseInt(c,10);return{limit:m!==void 0&&Number.isFinite(m)&&m>=0?m:void 0,offset:R!==void 0&&Number.isFinite(R)&&R>=0?R:void 0}},Xe=()=>{if(u===void 0)throw new d("scheduled endpoints require a `schedulerDO` namespace on the worker",{code:"SCHEDULER_NOT_CONFIGURED",status:400});return u},qt=ca({checkWsAdmin:async r=>A(r)||Ja(r,O(),g()),requireSchedulerNamespace:Xe,resolveSchedulerStub:r=>(K(r),we(Xe(),e.schedulerInstanceName??"default")),schedulerInstanceName:e.schedulerInstanceName??"default"}),Yt=_a({assertAdmin:K,resolveWorkflowsClient:e.workflowsClient??(()=>{})}),Xt=Yn({assertAdmin:K,parsePaging:Ie,queryParameter:ke,readBodyBytes:zn,requireAdminOption:$,storage:{storageBuckets:e.storageBuckets,storageDelete:e.storageDelete,storageDownload:e.storageDownload,storageList:e.storageList,storageSignedUrl:e.storageSignedUrl,storageUpload:e.storageUpload}}),Zt=Yr({options:e,readJsonBody:Z,requireAdminOption:$}),en=pa({readJsonBody:Z,requireAdminOption:$,vectorIntrospector:e.vectorIntrospector}),tn=Io({kvIntrospector:e.kvIntrospector,readJsonBody:Z,requireAdminOption:$}),nn=cr({logArchive:e.logArchive,readJsonBody:Z,requireAdminOption:$}),rn=Oo({assertAdmin:K,options:{cronJobs:e.cronJobs,functions:e.functions,globalIntrospector:e.globalIntrospector,openApiSpec:e.openApiSpec,openRpcSpec:e.openRpcSpec},parsePaging:Ie,queryParameter:ke,requireAdminOption:$}),on=r=>{const s=[],l=i??r?.SHARD;if(l!==void 0&&s.push(ar("durable-object:default",l,o)),e.health?.disableBindingProbes!==!0)for(const[c,m]of Object.entries(r??{})){const R=qa(c,m);R!==void 0&&s.push(R)}for(const c of e.health?.probes??[])s.push(c);return s},an=or({appName:e.health?.appName,appVersion:e.health?.appVersion,auth:e.health?.auth??"public",cacheTtlMs:e.health?.cacheTtlMs,isAdmin:A,resolveProbes:on}),sn=r=>{const s=e.schedulerInstanceName??"default",l=()=>we(r,s),c=async(y,S)=>{const T=await l().fetch(new Request(`https://scheduler.internal${y}`,S));if(!T.ok)throw new d(`ctx.scheduler: SchedulerDO ${y} failed (${String(T.status)}): ${await T.text()}`,{code:"INTERNAL",status:500});return await T.json()},m=async(y,S)=>await c(y,{body:JSON.stringify(S),headers:{"content-type":"application/json"},method:"POST"}),R=y=>{const S=y;if(S==null)throw new d("ctx.scheduler: target is required — pass a reference from the generated `internal` / `workflows` / `agents`",{code:"BAD_REQUEST",status:400});if(typeof S.binding=="string"&&S.binding.length>0)return{workflow:S.binding};if(typeof S.__lunoraRef=="string")return{functionPath:S.__lunoraRef};throw new d("ctx.scheduler: expected a reference from the generated `internal` / `workflows` / `agents` — a bare function-path string is refused here, because an HTTP action can be reached unauthenticated",{code:"BAD_REQUEST",status:400})},k=async(y,S,T={})=>{const{id:B}=await m("/schedule",{args:T,scheduledFor:y,...R(S)});return B};return{cancel:async y=>await m("/cancel",{id:y}),get:async y=>await c(`/get?id=${encodeURIComponent(y)}`,{method:"GET"}),list:async()=>await c("/list",{method:"GET"}),runAfter:async(y,S,T)=>{if(!Number.isFinite(y)||y<0)throw new d("ctx.scheduler.runAfter: `delayMs` must be a non-negative finite number",{code:"BAD_REQUEST",status:400});return await k(Date.now()+y,S,T)},runAt:async(y,S,T)=>{if(!Number.isFinite(y))throw new d("ctx.scheduler.runAt: `timestampMs` must be a finite epoch-millisecond number",{code:"BAD_REQUEST",status:400});return await k(y,S,T)}}},cn=async(r,s,l)=>{const{claims:c,headers:m,userId:R}=await ce(r,s,a),k=async(y,S={})=>{const T=y.__lunoraRef;if(typeof T!="string")throw new d("ctx.run*: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});const B=ye(T,S,{...m,"x-lunora-system":"1"}),x=await w(i,o,B),C=await x.json();if(C.error)throw new d(C.error.message??"shard RPC failed",{code:C.error.code??"INTERNAL",status:x.status});return C.result};return{auth:{getIdentity:()=>Promise.resolve(c),userId:R},cache:l.cache,fetch:globalThis.fetch.bind(globalThis),runAction:k,runMutation:k,runQuery:k,...u===void 0?{}:{scheduler:sn(u)},...e.storage===void 0?{}:{storage:hr(e.storage(s))}}},dn=async(r,s,l)=>{if(!e.httpRouter)return;const c=await cn(r,s,l);try{return await e.httpRouter.fetch(r,{...s,__lunoraCtx:c},l)}catch(m){return console.error("[lunora] httpRouter (SSR) handler threw:",m),new Response("Internal Server Error",{status:500})}},un=async(r,s,l)=>{if(r.headers.get("Upgrade")!=="websocket")throw new d("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});const c=dt(r,se);if(c)return c;const m=l.searchParams.get("shard")??o,{headers:R,identity:k}=await ce(r,s,a);await Y(k,m);const y=Pt(r,R),S=It(s,e.shardDO);if(S!==void 0){y.set("x-lunora-shard-binding",S);const T=await Qa(i,m);if(T>0){const B=Tr(m,Math.floor(Math.random()*T));return w(i,B,new Request(r,{headers:y}),ut(r))}}return w(i,m,new Request(r,{headers:y}))},ln=async(r,s,l)=>{const{voiceAgents:c}=e;if(c===void 0)return new Response("Not found",{status:404});if(r.headers.get("Upgrade")!=="websocket")return new Response("Expected a WebSocket upgrade",{headers:{allow:"GET"},status:426});const m=dt(r,se);if(m)return m;let R;try{R=decodeURIComponent(l.pathname.slice(vt.length))}catch{return new Response("Unknown voice agent",{status:404})}const k=Object.hasOwn(c,R)?c[R]:void 0;if(k===void 0)return new Response("Unknown voice agent",{status:404});const y=l.searchParams.get("threadKey");if(y===null||y.length===0)return new Response("Missing threadKey",{status:400});const{headers:S,identity:T}=await ce(r,s,a);if(e.authorizeShard){if(!await e.authorizeShard({identity:T,shardKey:y}))throw new d("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else H("shard");const B=Pt(r,S);return w(k,y,new Request(r,{headers:B}))},hn=async(r,s,l)=>{if(e.authorizeFanOut){if(!await e.authorizeFanOut(l,r.table,s))throw new d("Forbidden fan-out",{code:"FORBIDDEN_FANOUT",status:403});return}if(s.startsWith("__lunora_relation__:"))throw new d("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 d("Fan-out requires `authorizeFanOut` to be configured on the worker when `authorizeShard` is set",{code:"FORBIDDEN_FANOUT",status:403});H("fan-out")},Re=async(r,s)=>{if(!(!r.fanOut&&r.functionPath.startsWith("__lunora_admin__:"))){if(r.fanOut){await hn(r.fanOut,r.functionPath,s);return}await Y(s,r.shardKey??o)}},fn=(r,s,l)=>{if(e.replicaReads!==!0)return;if(e.functions===void 0){F();return}if(e.functions[s]?.kind!=="query"||l.includes(jt)||l.includes(Kt))return;const c=ut(r);return c===void 0?void 0:{name:Or(l,c),region:c}},pn=async(r,s,l,c,m)=>{const R=fn(r,s,c);if(R!==void 0){const k={...m,"x-lunora-replica-read":"1",...b===void 0?{}:{"x-lunora-shard-binding":b}},y=vr(r.headers.get("x-lunora-min-seq"));y!==void 0&&(k["x-lunora-min-seq"]=String(y));const S=await w(i,R.name,ye(s,l,k),R.region);if(S.status!==421)return S}return w(i,c,ye(s,l,m))},Pe=async(r,s,l,c,m,R)=>{const k=Date.now(),{observability:y,sampling:S}=e,T=Fe(r),{decision:B,ignoredUpstream:x,trace:C}=Xo(r,{...S===void 0?{}:{sampling:S},trustInbound:t(r)});x&&n();const te={...m,"x-lunora-sample-errors":B.keepErrors?"1":"0"};Zo(C,te);try{const L=await pn(r,s,l,c,te);ie(y,{...T,...Ot(C),durationMs:Date.now()-k,functionPath:s,ok:L.ok,shardKey:c,...L.ok?{}:{error:{code:"SHARD_ERROR",message:`shard returned ${String(L.status)}`,status:L.status}}},R,void 0,{isTraced:C.sampled,keepErrors:B.keepErrors});const ee=new Response(L.body,{headers:L.headers,status:L.status,statusText:L.statusText});return ee.headers.set("x-lunora-shard-key",c),ee}catch(L){throw ie(y,{...T,...Ot(C),...Se(s,Date.now()-k,L,{shardKey:c})},R,void 0,{isTraced:C.sampled,keepErrors:B.keepErrors}),L}},mn=r=>{if(r.fanOut&&r.shardKey)throw new d("RPC envelope cannot set both `shardKey` and `fanOut`",{code:"BAD_REQUEST",status:400});if(!r.fanOut&&r.functionPath.startsWith("__lunora_relation__:"))throw new d("`__lunora_relation__:*` is a fan-out-only reserved RPC and cannot be dispatched to a single shard",{code:"FORBIDDEN",status:403});if(r.fanOut&&!e.queryCoordinator)throw new d("RPC envelope set `fanOut` but no `queryCoordinator` is configured on the worker",{code:"BAD_REQUEST",status:400})},wn=async(r,s,l)=>{j(r,"POST","RPC");const c=await $a(r);ja(s,c),mn(c);const m=await ve(r,c);if(m!==void 0)return m;const{headers:R,identity:k}=await ce(r,s,a);await Re(c,k);const y=Ge(c,e);{const S=Date.now(),{observability:T}=e,B=Fe(r),x=Ee(s,r,l&&(L=>l.waitUntil?.(L)));if(c.fanOut){const L=e.queryCoordinator;if(!L)throw new d("RPC envelope set `fanOut` but no `queryCoordinator` is configured on the worker",{code:"BAD_REQUEST",status:400});try{const ee=await L.fanOut(i,{args:c.args??{},fanOut:c.fanOut,functionPath:c.functionPath,headers:R});return ie(T,{durationMs:Date.now()-S,fanOut:{failed:ee.failed,shards:ee.ok+ee.failed,table:c.fanOut.table},functionPath:c.functionPath,...B,ok:!0},x),Response.json(ee,{headers:{"content-type":"application/json"},status:200})}catch(ee){throw ie(T,{...Se(c.functionPath,Date.now()-S,ee,{fanOut:{table:c.fanOut.table}}),...B},x),ee}}const C=c.shardKey??o,te=()=>Pe(r,c.functionPath,c.args??{},C,R,x);return y&&e.x402Charge?e.x402Charge(r,{functionPath:c.functionPath,price:y.price},te,$e(l)):te()}},gn=async(r,s,l)=>{j(r,"POST","RPC batch");const c=await Z(r),{calls:m}=c;if(!Array.isArray(m))throw new d("RPC batch `calls` must be an array",{code:"BAD_REQUEST",status:400});const{headers:R,identity:k}=await ce(r,s,a),y=Zr(m,o);for(const W of y.values())for(const V of W)if(e.functions?.[V.functionPath]?.x402)throw new d(`paid (\`.x402\`) function "${V.functionPath}" cannot be called in a batch; dispatch it individually over ${Tt}`,{code:"BAD_REQUEST",status:400});await Promise.all([...y.entries()].flatMap(([W,V])=>V.map(ne=>Re({args:ne.args,functionPath:ne.functionPath,shardKey:W},k))));const{observability:S}=e,T=Ee(s,r,l&&(W=>l.waitUntil?.(W))),B=Fe(r),x=[],C=[],te=(W,V,ne,le)=>({body:{error:{code:ne,message:le}},id:W.id,status:V}),L=(W,V,ne,le,fe)=>{for(const q of W)ie(S,fe(q),T),x.push(te(q,V,ne,le))},ee=(W,V,ne,le,fe)=>{for(const q of W){const pe=le.get(q.id)??fe,ge=pe<400;ie(S,{durationMs:ne,functionPath:q.functionPath,...B,ok:ge,shardKey:V,...ge?{}:{error:{code:"SHARD_ERROR",message:`batched call returned ${String(pe)}`,status:pe}}},T)}};await Promise.all([...y.entries()].map(async([W,V])=>{const ne=new Headers(R);ne.set("content-type","application/json");const le=new Request("https://shard.internal/rpc-batch",{body:JSON.stringify({calls:V}),headers:ne,method:"POST"}),fe=Date.now();let q;try{q=await w(i,W,le)}catch(X){const Ce=Date.now()-fe,{body:rt}=Nn(X,{fallbackCode:"SHARD_UNAVAILABLE",redactedMessage:"shard unavailable"});L(V,502,rt.code,rt.message,Pn=>({...Se(Pn.functionPath,Ce,X,{shardKey:W}),...B}));return}const pe=Date.now()-fe,ge=q.headers.get("x-d1-bookmark");ge&&C.push(ge);let Ne;try{Ne=await q.json()}catch{const X=`shard batch returned a non-JSON response (${String(q.status)})`;L(V,q.status,"SHARD_ERROR",X,Ce=>({durationMs:pe,error:{code:"SHARD_ERROR",message:X,status:q.status},functionPath:Ce.functionPath,...B,ok:!1,shardKey:W}));return}const Ue=Array.isArray(Ne.results)?Ne.results:[],kn=new Map(Ue.map(X=>[X.id,X.status??q.status])),In=new Set(Ue.map(X=>X.id));ee(V,W,pe,kn,q.status),x.push(...Ue);for(const X of V)In.has(X.id)||x.push(te(X,q.status,"SHARD_ERROR",`shard batch omitted result for call ${String(X.id)}`))}));const tt={"content-type":"application/json"},[nt]=C;return C.length===1&&nt!==void 0&&(tt["x-d1-bookmark"]=nt),Response.json({results:x},{headers:tt,status:200})},yn=async(r,s,l,c={},m={})=>{try{const R=l.__lunoraRef;if(typeof R!="string")throw new d("serverQuery: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});const{headers:k,identity:y}=await ce(r,s,a,m.context),S={args:c,functionPath:R,shardKey:m.shardKey};await Re(S,y);const T=m.shardKey??o,B=Ee(s,r,m.waitUntil),x=()=>Pe(r,R,c,T,k,B),C=Ge(S,e);return C&&e.x402Charge?await e.x402Charge(r,{functionPath:R,price:C.price},x,$e(m.waitUntil?{waitUntil:m.waitUntil}:m.context)):await x()}catch(R){return ot(R)}},Ze=async(r,s,l)=>{const{observability:c}=e,m=Date.now(),R=Te(16),k=Te(8),y=kt(s);try{const S=await l();return ie(c,{durationMs:Date.now()-m,functionPath:r,ok:!0,spanId:k,traceId:R},y),S}catch(S){throw ie(c,{...Se(r,Date.now()-m,S,{}),spanId:k,traceId:R},y),S}finally{st(c,y)}},bn=async(r,s,l)=>{_(s);const c=[],m=y=>y instanceof Error?y:new Error(String(y)),R=e.crons?.[r.cron];if(R)try{await R(r,s,l)}catch(y){c.push(m(y))}if(await oe(r.cron,s,c,m),e.backupStore&&e.backupCron!==void 0&&e.backupCron===r.cron)try{await Wr(e,i,O(),r)}catch(y){c.push(m(y))}const[k]=c;if(c.length===1&&k)throw k;if(c.length>1)throw new AggregateError(c,`scheduled("${r.cron}") had ${String(c.length)} failure(s)`)},_n=async(r,s)=>{try{const l=r??{},c=e.adminToken??(typeof l.LUNORA_ADMIN_TOKEN=="string"?l.LUNORA_ADMIN_TOKEN:void 0);if(!c||c.length===0)return;await w(i,o,ye(Ua,{outcome:s},{authorization:`Bearer ${c}`,"content-type":"application/json"}))}catch{}},Rn=async(r,s,l,c)=>{if(!e.authHandler)return;const m=await e.authHandler(r);if(!m)return;const R=e.authBasePath??Na;return xa(l.pathname,R)&&c.waitUntil?.(_n(s,m.status>=400?"fail":"ok")),m},En=async({args:r,env:s,functionPath:l,request:c,shardKey:m,waitUntil:R})=>{Ct(r,"REST");const k={functionPath:l,...m===void 0?{}:{shardKey:m}},{headers:y,identity:S}=await ce(c,s,a);await Re(k,S);const T=m??o,B=Ee(s,c,R),x=()=>Pe(c,l,r,T,y,B),C=Ge(k,e);return C&&e.x402Charge?e.x402Charge(c,{functionPath:l,price:C.price},x,$e({waitUntil:R})):x()},Sn=Qn({functions:e.functions??{},invoke:En,readJsonBody:Z,edgeCache:e.restEdgeCache,...e.restRateLimit?{rateLimit:e.restRateLimit}:{}}),De=e.routes!==void 0&&Object.keys(e.routes).length>0?e.routes:void 0,An={[Ia]:r=>r.method!=="GET"&&r.method!=="HEAD"?new Response(void 0,{headers:{allow:"GET, HEAD"},status:405}):Response.json({ok:!0},{headers:{"cache-control":"no-store"}}),[Sa]:(r,s,l)=>un(r,s,l),[Tt]:(r,s,l,c)=>wn(r,s,c),[Ea]:(r,s,l,c)=>gn(r,s,c),[Aa]:(r,s)=>ue(r,s),[Ta]:(r,s)=>z(r,s),[Oa]:async r=>{j(r,"POST","ws-token"),K(r);const s=O();if(s===void 0)throw new d("ws-token minting requires a configured admin token",{code:"ADMIN_TOKEN_NOT_CONFIGURED",status:400});const l=await Nr(s);return Response.json(l,{headers:{"cache-control":"no-store"}})},...U,...ae,...qt,...Yt,...Xt,...Zt,...en,...tn,...nn,...rn,...an,...Sn,...xr({assertAdmin:K,getAuthAdmin:()=>e.authAdmin,parsePaging:Ie,queryParameter:ke,readJsonBody:Z})};let se=ct(e.security),et=!1;const Tn=r=>{et||(et=!0,se=ct(e.security,r??{}))},On=async(r,s)=>{if(!(e.adminGate===void 0||!Pa(s)))try{await e.adminGate(r,ze.get(r))&&p.add(r)}catch{}},vn=async(r,s,l)=>{ze.set(r,l);const c=new URL(r.url);if(r.method==="POST"||r.method==="PUT"){const y=Number(r.headers.get("content-length")??""),S=Ra[c.pathname]??Ut;if(Number.isFinite(y)&&y>S)throw new d("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413})}const m=await Rn(r,s,c,l);if(m)return m;if(De){const y=`${r.method} ${c.pathname}`,S=De[y]??De[c.pathname];if(S)return S(r,s,l)}const R=An[c.pathname];if(R)return await On(r,c.pathname),R(r,s,c,l);if(e.voiceAgents!==void 0&&c.pathname.startsWith(vt))return ln(r,s,c);const k=await dn(r,s,l);return k||new Response("Not found",{status:404})};return{async fetch(r,s,l){e.passThroughOnException&&l.passThroughOnException?.(),Tn(s),_(s);const c=ur(r,se);if(c)return c;const m=lr(r,se);if(m)return xe(m,r,se);try{const R=await vn(r,s,l);return xe(R,r,se)}catch(R){return xe(ot(R),r,se)}finally{st(e.observability,kt(l))}},async queue(r,s,l){await Ze(`queue:${La(r)}`,l,async()=>{await e.queue?.(r,s,l)})},async scheduled(r,s,l){await Ze(`cron:${r.cron}`,l,async()=>{await bn(r,s,l)})},serverQuery:yn}},Ya=e=>Jt(e),Xa=e=>typeof e=="function"?{fetch:e}:e,Za=e=>!!(e.crons??e.cronJobs??e.backupCron),Rs=(e,t)=>{const n=Xa(e),o=typeof e=="object"&&typeof e.scheduled=="function"?e.scheduled:void 0,a=u=>{const h=Ya({...u,httpRouter:n});return o!==void 0&&!Za(u)?{...h,scheduled:async(f,w,E)=>{await o(f,w,E)}}:h};if(typeof t!="function")return a(t);const i=t;return{fetch:(u,h,f)=>a(i(h)).fetch(u,h,f),queue:(u,h,f)=>a(i(h)).queue?.(u,h,f)??Promise.resolve(),scheduled:(u,h,f)=>a(i(h)).scheduled(u,h,f),serverQuery:(u,h,f,w,E)=>a(i(h)).serverQuery(u,h,f,w,E)}},es=(e,t)=>{if(typeof e=="function")return e(t);const n=e.shardDO??t?.SHARD;if(!n)throw new d("@lunora/runtime: no shard Durable Object namespace found. Bind `SHARD` in wrangler.jsonc, or pass `createLunoraHandler({ shardDO: env.MY_SHARD })`.");return{...e,shardDO:n}},Es=(e={})=>(t,n,o)=>Jt(es(e,n)).fetch(t,n,o??Un),Ss=e=>e;export{Hr as GET_AUTH_AUDIT_LOG_OP,Un as NOOP_EXECUTION_CONTEXT,Os as composeIdentityResolvers,Ya as composeWorker,Es as createLunoraHandler,Jt as createWorker,Ss as defineRpcEnvelope,Qa as probeRelayCount,es as resolveLunoraOptions,vs as routeIdentityResolvers,Rs as withFrameworkWorker};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/runtime",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.87",
|
|
4
4
|
"description": "Lunora Worker runtime: the RPC router, shard resolver, and query coordinator",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cloudflare",
|
|
@@ -46,8 +46,8 @@
|
|
|
46
46
|
"access": "public"
|
|
47
47
|
},
|
|
48
48
|
"dependencies": {
|
|
49
|
-
"@lunora/bindings": "1.0.0-alpha.
|
|
50
|
-
"@lunora/errors": "1.0.0-alpha.
|
|
49
|
+
"@lunora/bindings": "1.0.0-alpha.45",
|
|
50
|
+
"@lunora/errors": "1.0.0-alpha.28",
|
|
51
51
|
"@lunora/platform": "1.0.0-alpha.23"
|
|
52
52
|
},
|
|
53
53
|
"peerDependencies": {
|
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
import{isLunoraError as Dn,toErrorBody as Nn}from"@lunora/errors";import{e as Nt}from"./evict-oldest-BNXsKx4s.mjs";import{NOOP_EXECUTION_CONTEXT as Un}from"./NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{t as Cn,f as Bn}from"./base64-Bl1_r2k1.mjs";import{e as xn,a as Hn}from"./identity-header-C4Z5pldl.mjs";import{o as Te,b as Ln,p as Mn,m as Kn,d as jn,a as $n,r as Fn}from"./otlp-resource-DeXhb949.mjs";import{e as Qe}from"./wire-codec-CMVqBlcF.mjs";import{d as ee,e as be,M as Ut,b as Gn,f as Qn,g as Ct,h as Bt}from"./rest-routes-ZZES0ngM.mjs";import{LunoraError as d,toErrorResponse as ot}from"./LunoraError-DksAgIpa.mjs";import{a as K,m as me}from"./method-guard-BG_vJNTl.mjs";import{normalizeBackupPrefix as We,BACKUP_KEY_PREFIX as Ve,isBackupManifestKey as zn,backupObjectKeyOfManifest as xt,backupObjectKey as Wn,backupManifestKey as Vn}from"./BACKUP_KEY_PREFIX-BOtSu-_3.mjs";import{toHex as qn,buildStorageAdminRoutes as Jn,STORAGE_UPLOAD_MAX_BODY_BYTES as Yn,STORAGE_PATH as Xn}from"./STORAGE_UPLOAD_MAX_BODY_BYTES-BqyO-1l6.mjs";import{b as Zn,e as er,f as at,g as tr,h as nr}from"./export-tap-CGR3Xd9F.mjs";import{buildHealthRoutes as rr,durableObjectProbe as or,d1Probe as ar,presenceProbe as Be}from"./HEALTH_PATH-jZsuCmSs.mjs";import{wrapResolverWithContract as sr}from"./composeIdentityResolvers-BHZ4jH8o.mjs";import{composeIdentityResolvers as As,routeIdentityResolvers as Ts}from"./composeIdentityResolvers-BHZ4jH8o.mjs";import{buildLogArchiveAdminRoutes as ir}from"./LOG_ARCHIVE_PATH-Hmjpz_Ko.mjs";import{r as cr,f as st,a as de}from"./observability-vDK-rMbs.mjs";import{resolveShard as we,applyJurisdiction as it}from"./applyJurisdiction-C0ddU7Tg.mjs";import{resolveSecurity as ct,handleCorsPreflight as dr,enforceOrigin as ur,decorateResponse as xe,enforceWebSocketOrigin as dt}from"./decorateResponse-BuqVnrmc.mjs";const lr=e=>{const t=e??{};if(typeof t.bucket=="function")return t;const n={...t,bucketName:"default"};return n.bucket=()=>n,n},Ht="__lunoraBranch",hr=e=>typeof e=="object"&&e!==null&&Object.hasOwn(e,Ht),fr=`may not contain the reserved workflow branch-marker key ("${Ht}")`,qe=(e,t)=>{const n=Math.max(e.length,t.length);let o=e.length^t.length;for(let a=0;a<n;a+=1){const i=a<e.length?e.charCodeAt(a):0,u=a<t.length?t.charCodeAt(a):0;o|=i^u}return o===0},pr=(e,t,n,o)=>{const a=e.get(t);if(a!==void 0)return a;Nt(e,o);const i=n().catch(u=>{throw e.get(t)===i&&e.delete(t),u});return e.set(t,i),i},Je=new TextEncoder,mr=Array.from({length:32},(e,t)=>t);new RegExp(`[${mr.map(e=>String.fromCodePoint(e)).join("")}]`,"u");const wr=64,gr=new Map,Lt=async e=>pr(gr,e,async()=>crypto.subtle.importKey("raw",Je.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]),wr),Mt=async(e,t)=>{const n=await Lt(e),o=await crypto.subtle.sign("HMAC",n,Je.encode(t));return Cn(new Uint8Array(o))},yr=async(e,t,n)=>{const o=await Lt(e);return crypto.subtle.verify("HMAC",o,n,Je.encode(t))},br=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"];new Set(br);const _r=new Set(["AE","BH","IL","IQ","IR","JO","KW","LB","OM","PS","QA","SA","SY","TR","YE"]),Rr=-100,Er=15,Sr=e=>{const t=Number(e.longitude??Number.NaN);switch(e.continent){case"AF":return"afr";case"AS":return e.country!==void 0&&_r.has(e.country)?"me":"apac";case"EU":return Number.isFinite(t)&&t>Er?"eeur":"weur";case"NA":return Number.isFinite(t)&&t<Rr?"wnam":"enam";case"OC":return"oc";case"SA":return"sam";default:return}},ut=e=>{const t=e.cf;return t===void 0?void 0:Sr(t)},Kt="::relay::",Ar=(e,t)=>`${e}${Kt}${String(t)}`,jt="::replica::",Tr=(e,t)=>`${e}${jt}${t}`,Or=e=>{if(e==null||!/^\d+$/.test(e))return;const t=Number.parseInt(e,10);return Number.isSafeInteger(t)&&t>0?t:void 0},vr=new Set(["1","enabled","on","true","yes"]),kr=new Set(["0","disabled","false","no","off"]),Ir=(e,t)=>{const n=(e??"").trim().toLowerCase();return vr.has(n)?!0:kr.has(n)?!1:t},$t="v1",Pr=6e4,Dr=async(e,t={})=>{const n=(t.now??Date.now())+(t.ttlMs??Pr),o=`${$t}.${String(n)}`,a=await Mt(e,o);return{expiresAtMs:n,token:`${o}.${a}`}},Nr=async(e,t,n=Date.now())=>{if(e.length===0||t.length===0)return!1;const o=t.split(".");if(o.length!==3)return!1;const[a,i,u]=o;if(a!==$t||u.length===0)return!1;const h=Number(i);if(!Number.isFinite(h)||h<=n)return!1;let f;try{f=Bn(u)}catch{return!1}return yr(e,`${a}.${i}`,f)},P="/_lunora/admin/auth",Ur={INVITER_REQUIRED:400,ORG_SLUG_INVALID:400,ORG_SLUG_TAKEN:409,PASSWORD_TOO_LONG:400,PASSWORD_TOO_SHORT:400,USER_ALREADY_EXISTS:409,USER_NOT_FOUND:404},N=(e,t)=>{const n=e[t];if(typeof n!="string"||n==="")throw new d(`\`${t}\` is required`,{code:"BAD_REQUEST",status:400});return n},he=(e,t)=>{const n=e(t);if(n===void 0)throw new d(`\`${t}\` query parameter is required`,{code:"BAD_REQUEST",status:400});return n},Ft=e=>{if(typeof e=="string"||Array.isArray(e)&&e.every(t=>typeof t=="string"))return e},ae=(e,t)=>typeof e[t]=="string"?e[t]:void 0,He=(e,t)=>{const n=e[t];return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:void 0},lt=e=>{const t=Ft(e.role);if(t===void 0||typeof t=="string"&&t.trim()==="")throw new d("`role` is required",{code:"BAD_REQUEST",status:400});return t},ht=e=>{const t=e.permission;if(typeof t!="object"||t===null||Array.isArray(t))throw new d("`permission` object is required",{code:"BAD_REQUEST",status:400});const n={};for(const[o,a]of Object.entries(t))Array.isArray(a)&&a.every(i=>typeof i=="string")&&(n[o]=a);return n},Cr={[`${P}/capabilities`]:{build:()=>({}),http:"GET",method:"capabilities"},[`${P}/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"},[`${P}/sessions`]:{build:({paging:e,query:t})=>({...e,userId:t("userId")}),http:"GET",method:"listSessions"},[`${P}/accounts`]:{build:({query:e})=>({userId:he(e,"userId")}),http:"GET",method:"listAccounts"},[`${P}/passkeys`]:{build:({query:e})=>({userId:he(e,"userId")}),http:"GET",method:"listPasskeys"},[`${P}/organizations`]:{build:({paging:e})=>({...e}),http:"GET",method:"listOrganizations"},[`${P}/organizations/members`]:{build:({paging:e,query:t})=>({...e,organizationId:he(t,"organizationId")}),http:"GET",method:"listMembers"},[`${P}/organizations/invitations`]:{build:({paging:e,query:t})=>({...e,organizationId:he(t,"organizationId")}),http:"GET",method:"listInvitations"},[`${P}/config`]:{build:()=>({}),http:"GET",method:"config"},[`${P}/organizations/teams`]:{build:({paging:e,query:t})=>({...e,organizationId:he(t,"organizationId")}),http:"GET",method:"listTeams"},[`${P}/organizations/teams/members`]:{build:({paging:e,query:t})=>({...e,teamId:he(t,"teamId")}),http:"GET",method:"listTeamMembers"},[`${P}/organizations/roles`]:{build:({paging:e,query:t})=>({...e,organizationId:he(t,"organizationId")}),http:"GET",method:"listOrgRoles"},[`${P}/users/create`]:{build:({body:e})=>({data:He(e,"data"),email:N(e,"email"),name:N(e,"name"),password:ae(e,"password"),role:Ft(e.role)}),http:"POST",method:"createUser"},[`${P}/users/update`]:{build:({body:e})=>{const{data:t}=e;if(typeof t!="object"||t===null||Array.isArray(t))throw new d("`data` object is required",{code:"BAD_REQUEST",status:400});return{data:t,userId:N(e,"userId")}},http:"POST",method:"updateUser"},[`${P}/users/role`]:{build:({body:e})=>({role:lt(e),userId:N(e,"userId")}),http:"POST",method:"setRole"},[`${P}/users/ban`]:{build:({body:e})=>({expiresInSeconds:typeof e.expiresInSeconds=="number"?e.expiresInSeconds:void 0,reason:ae(e,"reason"),userId:N(e,"userId")}),http:"POST",method:"banUser"},[`${P}/users/unban`]:{build:({body:e})=>({userId:N(e,"userId")}),http:"POST",method:"unbanUser"},[`${P}/users/password`]:{build:({body:e})=>({newPassword:N(e,"newPassword"),userId:N(e,"userId")}),http:"POST",method:"setUserPassword",returns:"void"},[`${P}/users/remove`]:{build:({body:e})=>({userId:N(e,"userId")}),http:"POST",method:"removeUser",returns:"void"},[`${P}/users/impersonate`]:{build:({body:e})=>({userId:N(e,"userId")}),http:"POST",method:"impersonateUser"},[`${P}/sessions/revoke`]:{build:({body:e})=>({sessionId:N(e,"sessionId")}),http:"POST",method:"revokeUserSession",returns:"void"},[`${P}/sessions/revoke-all`]:{build:({body:e})=>({userId:N(e,"userId")}),http:"POST",method:"revokeUserSessions",returns:"void"},[`${P}/accounts/unlink`]:{build:({body:e})=>({accountId:N(e,"accountId"),userId:N(e,"userId")}),http:"POST",method:"unlinkAccount",returns:"void"},[`${P}/two-factor/disable`]:{build:({body:e})=>({userId:N(e,"userId")}),http:"POST",method:"disableTwoFactor",returns:"void"},[`${P}/passkeys/delete`]:{build:({body:e})=>({passkeyId:N(e,"passkeyId")}),http:"POST",method:"deletePasskey",returns:"void"},[`${P}/organizations/members/remove`]:{build:({body:e})=>({memberId:N(e,"memberId")}),http:"POST",method:"removeMember",returns:"void"},[`${P}/organizations/invitations/cancel`]:{build:({body:e})=>({invitationId:N(e,"invitationId")}),http:"POST",method:"cancelInvitation",returns:"void"},[`${P}/organizations/create`]:{build:({body:e})=>({logo:ae(e,"logo"),metadata:He(e,"metadata"),name:N(e,"name"),ownerId:ae(e,"ownerId"),slug:ae(e,"slug")}),http:"POST",method:"createOrganization"},[`${P}/organizations/update`]:{build:({body:e})=>({logo:ae(e,"logo"),metadata:He(e,"metadata"),name:ae(e,"name"),organizationId:N(e,"organizationId"),slug:ae(e,"slug")}),http:"POST",method:"updateOrganization"},[`${P}/organizations/remove`]:{build:({body:e})=>({organizationId:N(e,"organizationId")}),http:"POST",method:"deleteOrganization",returns:"void"},[`${P}/organizations/members/add`]:{build:({body:e})=>({organizationId:N(e,"organizationId"),role:ae(e,"role"),userId:N(e,"userId")}),http:"POST",method:"addMember"},[`${P}/organizations/members/invite`]:{build:({body:e})=>({email:N(e,"email"),inviterId:ae(e,"inviterId"),organizationId:N(e,"organizationId"),role:ae(e,"role")}),http:"POST",method:"inviteMember"},[`${P}/organizations/members/role`]:{build:({body:e})=>({memberId:N(e,"memberId"),role:lt(e)}),http:"POST",method:"updateMemberRole"},[`${P}/organizations/teams/create`]:{build:({body:e})=>({name:N(e,"name"),organizationId:N(e,"organizationId")}),http:"POST",method:"createTeam"},[`${P}/organizations/teams/update`]:{build:({body:e})=>({name:N(e,"name"),teamId:N(e,"teamId")}),http:"POST",method:"updateTeam"},[`${P}/organizations/teams/remove`]:{build:({body:e})=>({teamId:N(e,"teamId")}),http:"POST",method:"removeTeam",returns:"void"},[`${P}/organizations/teams/members/add`]:{build:({body:e})=>({teamId:N(e,"teamId"),userId:N(e,"userId")}),http:"POST",method:"addTeamMember"},[`${P}/organizations/teams/members/remove`]:{build:({body:e})=>({teamMemberId:N(e,"teamMemberId")}),http:"POST",method:"removeTeamMember",returns:"void"},[`${P}/organizations/roles/create`]:{build:({body:e})=>({organizationId:N(e,"organizationId"),permission:ht(e),role:N(e,"role")}),http:"POST",method:"createOrgRole"},[`${P}/organizations/roles/update`]:{build:({body:e})=>({permission:ht(e),roleId:N(e,"roleId")}),http:"POST",method:"updateOrgRole"},[`${P}/organizations/roles/remove`]:{build:({body:e})=>({roleId:N(e,"roleId")}),http:"POST",method:"deleteOrgRole",returns:"void"}},Br=e=>{const t=async a=>{try{return await a()}catch(i){if(i instanceof d)throw i;const u=i,h=typeof u.code=="string"?u.code:"AUTH_ADMIN_ERROR";throw console.error("[lunora] auth admin operation failed:",i),new d("auth admin operation failed",{code:h,status:Ur[h]??500})}},n=async(a,i)=>{if(e.assertAdmin(a),a.method!==i.http)throw new d(`Auth admin endpoint requires ${i.http}`,{code:"METHOD_NOT_ALLOWED",status:405});const u=e.getAuthAdmin();if(u===void 0)throw new d("auth endpoints require an `authAdmin` on the worker",{code:"AUTH_NOT_CONFIGURED",status:400});const h=u[i.method];if(h===void 0)throw new d(`auth admin does not support \`${i.method}\``,{code:"AUTH_OP_NOT_SUPPORTED",status:400});const f=new URL(a.url),w={body:i.http==="POST"?await e.readJsonBody(a):{},paging:e.parsePaging(a),query:v=>e.queryParameter(f,v)},E=i.build(w),O=await t(()=>h(E));return Response.json(i.returns==="void"?{ok:!0}:O,{headers:{"content-type":"application/json"},status:200})},o={};for(const[a,i]of Object.entries(Cr))o[a]=u=>n(u,i);return o},xr="__lunora_admin__:getAuthAuditLog",ft=e=>typeof e=="string"&&e!==""?e:void 0,pt=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0,Hr=e=>async(n,o)=>{e.assertAdmin(n);const a=e.getReader();if(a===void 0)throw new d("the auth/security audit endpoint requires an `authAuditReader` on the worker",{code:"AUTH_AUDIT_NOT_CONFIGURED",status:400});const i=ft(o.actorId),u=ft(o.event),h=pt(o.sinceSeq),f=pt(o.limit),w={...i===void 0?{}:{actorId:i},...u===void 0?{}:{event:u},...h===void 0?{}:{sinceSeq:h},...f===void 0?{}:{limit:f}};let E;try{E=await a.read(w)}catch(v){throw v instanceof d?v:(console.error("[lunora] auth audit read failed:",v),new d("auth audit read failed",{code:"AUTH_AUDIT_READ_FAILED",status:500}))}const O={entries:E};return Response.json({result:Qe(O)},{headers:{"content-type":"application/json"},status:200})},Lr=(e,t)=>{const n=[],o=[];if(t&&t.length>0)for(const a of t)e.resolveTableSharding?.(a)?.mode.kind==="global"?o.push(a):n.push(a);return{globalTables:o,shardLocalTables:n}},Mr=async(e,t,n,o,a,i,u)=>{if(n!==void 0&&o.length===0)return;const h=await e.orchestrateExport(i,{args:{tables:o},defaultShardKey:u,headers:t,tables:o});for(const f of h.shards)if(!f.error)for(const w of f.rows??[])a(w)},Gt=async(e,t,n,o,a,i)=>{const u=o??e.listSchemaTables?.();o===void 0&&e.listSchemaTables===void 0&&console.warn("[lunora] export: no table list available (`listSchemaTables` is unset and no `tables` were named), so only the default shard is reachable. A `.shardBy()` deployment's other shards will be missing from this export. Name the tables explicitly, or regenerate the worker so codegen supplies the list.");const{globalTables:h,shardLocalTables:f}=Lr(e,u);await Mr(t,n,u,f,a,i,e.defaultShardKey??"__root__");const w=e.exportGlobals;if((o===void 0||h.length>0)&&w)for await(const O of w({tables:h}))a(O)},Kr=new TextEncoder,jr=1e3,Qt=10,$r=200,mt=8,zt="lunoraBackupCron",wt=24*1048576,gt=e=>{const t=e.slice(0,Qt).map(o=>xt(o)),n=e.length-t.length;return`${t.join(", ")}${n>0?` (+${String(n)} more)`:""}`},Fr=(e,t)=>{const n=new Uint8Array(new ArrayBuffer(t));let o=0;for(const a of e)n.set(a,o),o+=a.byteLength;return n},Ye=async(e,t,n,o)=>{if(n===void 0||!Number.isInteger(n)||n<=0)return{eligible:0,stale:[]};const a=[];let i;for(let u=0;u<jr;u+=1){const h=await e.list({cursor:i,include:["customMetadata"],prefix:t});for(const f of h.objects)zn(f.key)&&f.customMetadata?.[zt]===o&&a.push(f.key);if(!h.truncated||h.cursor===void 0)break;i=h.cursor}return{eligible:a.length,stale:a.toSorted((u,h)=>h.localeCompare(u)).slice(n)}},Gr=async(e,t,n,o,a)=>{const{stale:i}=await Ye(e,t,n,o),u=new Set(a),h=i.filter(g=>u.has(g)),f=h.slice(0,$r),w=i.length-f.length,E=a.length-h.length;if(f.length===0)return{deleted:[],failed:[],ignored:E,remaining:w};const O=[],v=[];for(let g=0;g<f.length;g+=mt){const b=await Promise.allSettled(f.slice(g,g+mt).map(async _=>(await e.delete(xt(_)),await e.delete(_),_)));for(const[_,p]of b.entries())p.status==="fulfilled"?O.push(p.value):v.push(f[g+_])}return O.length>0&&console.info(`[lunora] backup prune kept the newest ${String(n)} and deleted ${String(O.length)}: ${gt(O)}`),v.length>0&&console.warn(`[lunora] backup prune failed to remove ${String(v.length)}: ${gt(v)}`),{deleted:O,failed:v,ignored:E,remaining:w}},Qr=async e=>{const t=e.backupStore;if(!t)throw new d("backup retention preview requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});const n=We(e.backupPrefix??Ve),o=e.backupCron,{eligible:a,stale:i}=o===void 0?{eligible:0,stale:[]}:await Ye(t,n,e.backupRetain,o);return{cron:o,eligible:a,keep:e.backupRetain??0,prefix:n,wouldDelete:i}},zr=async(e,t,n,o)=>{const a=e.backupStore,i=e.queryCoordinator;if(!a)throw new d("scheduled backup requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});if(!i)throw new d("scheduled backup requires a `queryCoordinator` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});if(!n||n.length===0)throw new d("scheduled backup requires an `adminToken` (or `env.LUNORA_ADMIN_TOKEN`) to authenticate the per-shard export gate",{code:"BACKUP_NOT_CONFIGURED",status:500});const u={authorization:`Bearer ${n}`,"content-type":"application/json"},h=e.backupTables;let f=0,w=0,E=[];await Gt(e,i,u,h,D=>{const M=Kr.encode(`${JSON.stringify(D)}
|
|
2
|
-
`);if(f+=1,w+=M.byteLength,w>wt)throw new d(`scheduled backup reached ${String(w)} bytes of NDJSON, past the ${String(wt)}-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});E.push(M)},t);const v=We(e.backupPrefix??Ve),g=new Date(o.scheduledTime).toISOString(),b=Wn(v,g),_=Fr(E,w);E=[];const p=qn(await crypto.subtle.digest("SHA-256",_));await a.put(b,_,{httpMetadata:{contentType:"application/x-ndjson"},sha256:p});const A={bytes:w,createdAt:g,cron:o.cron,file:b,id:g,rows:f,scheduledTime:o.scheduledTime,sha256:p,...h?{tables:h.join(",")}:{}};await a.put(Vn(b),`${JSON.stringify(A,void 0,2)}
|
|
3
|
-
`,{customMetadata:{[zt]:o.cron},httpMetadata:{contentType:"application/json"}});try{const{stale:D}=await Ye(a,v,e.backupRetain,o.cron);if(D.length>0){const M=D.slice(0,Qt),I=D.length-M.length;console.info(`[lunora] backup retention: ${String(D.length)} snapshot(s) past the newest ${String(e.backupRetain)} — run \`lunora backup prune\` to remove them: ${M.join(", ")}${I>0?` (+${String(I)} more)`:""}`)}}catch(D){console.warn(`[lunora] backup ${b} was written, but the retention report failed:`,D)}},Wr=async(e,t)=>{const n=e.backupStore;if(!n)throw new d("backup prune requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});const o=e.backupCron,a=e.backupRetain;if(o===void 0||a===void 0||!Number.isInteger(a)||a<=0)throw new d("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 Gr(n,We(e.backupPrefix??Ve),a,o,t)},Vr="/_lunora/admin/backup/retention",qr="/_lunora/admin/backup/prune",Jr=e=>{const{options:t,readJsonBody:n,requireAdminOption:o}=e,a=(h,f)=>{o(h,t.backupStore,{code:"BACKUP_NOT_CONFIGURED",message:`backup ${f} requires a \`backupStore\` on the worker`})},i=async h=>(K(h,"GET","Backup-retention"),a(h,"retention preview"),Response.json(await Qr(t),{headers:{"cache-control":"no-store"}})),u=async h=>{K(h,"POST","Backup-prune"),a(h,"prune");const{confirm:f}=await n(h);if(!Array.isArray(f)||f.some(w=>typeof w!="string"))throw new d("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 Wr(t,f),{headers:{"cache-control":"no-store"}})};return{[qr]:u,[Vr]:i}},yt=500,Yr=(e,t,n)=>{if(typeof e!="object"||e===null||Array.isArray(e))throw new d("each batch call must be an object",{code:"BAD_REQUEST",status:400});const o=e;if(typeof o.functionPath!="string")throw new d("each batch call needs a string `functionPath`",{code:"BAD_REQUEST",status:400});if(o.functionPath.startsWith("__lunora_relation__:")||o.functionPath.startsWith("__lunora_admin__"))throw new d("reserved function path cannot be batched",{code:"FORBIDDEN",status:403});if(o.args!==void 0&&(typeof o.args!="object"||o.args===null||Array.isArray(o.args)))throw new d("each batch call `args` must be an object",{code:"BAD_REQUEST",status:400});return{entry:{args:o.args===void 0?{}:o.args,clientId:typeof o.clientId=="string"?o.clientId:void 0,clientSeq:typeof o.clientSeq=="number"?o.clientSeq:void 0,functionPath:o.functionPath,id:typeof o.id=="number"?o.id:t,mutationId:typeof o.mutationId=="string"?o.mutationId:void 0},shardKey:typeof o.shardKey=="string"?o.shardKey:n}},Xr=(e,t)=>{if(e.length>yt)throw new d(`RPC batch exceeds the ${String(yt)}-call limit`,{code:"BAD_REQUEST",status:400});const n=new Map;for(const[o,a]of e.entries()){const{entry:i,shardKey:u}=Yr(a,o,t),h=n.get(u)??[];h.push(i),n.set(u,h)}return n},Zr="/_lunora/admin/export",eo="/_lunora/admin/import",to="/_lunora/admin/sync",no="/_lunora/admin/connector/sync",ro="/_lunora/admin/apply",oo="/_lunora/admin/export-tap/run",ao=new TextEncoder,so=async e=>{const n=await be(e,"Export")??{};if(n.tables===void 0)return{tables:void 0};if(!Array.isArray(n.tables))throw new d("Export `tables` must be a string array",{code:"BAD_REQUEST",status:400});const o=[];for(const a of n.tables){if(typeof a!="string"||a.length===0)throw new d("Export `tables` entries must be non-empty strings",{code:"BAD_REQUEST",status:400});o.push(a)}return{tables:o}},Le=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):void 0,io=e=>{const{applyGlobals:t,defaultShardKey:n,exportCursorStore:o,exportSinks:a,knownTables:i,queryCoordinator:u,assertAdmin:h,requireAdminOption:f,resolveForwardContext:w,shardDO:E,streamExportRows:O,streamingImport:v,syncGlobals:g}=e,b=async(I,j)=>{const H=me(I,["POST"]);if(H)return H;const Y=f(I,u,{code:"BAD_REQUEST",message:"Export endpoint requires a `queryCoordinator` on the worker"}),U=await so(I),{headers:$}=await w(I,j),F=new ReadableStream({async pull(W){const te=V=>{W.enqueue(ao.encode(`${JSON.stringify(V)}
|
|
4
|
-
`))};try{await O(Y,$,U.tables,te),W.close()}catch(V){W.error(V)}}});return new Response(F,{headers:{"content-type":"application/x-ndjson"},status:200})},_=async(I,j)=>{const H=me(I,["POST"]);if(H)return H;const Y=f(I,u,{code:"BAD_REQUEST",message:"Sync endpoint requires a `queryCoordinator` on the worker"}),U=await ee(I),$=typeof U.cursors=="object"&&U.cursors!==null?U.cursors:{},F=typeof U.limit=="number"?U.limit:void 0,W=typeof U.globalCursor=="number"?U.globalCursor:0,te=Le(U.tables),{headers:V}=await w(I,j),se=te??i(),G=await Y.orchestrateCdcSync(E,{cursors:$,defaultShardKey:n,headers:V,limit:F,tables:se}),q=g?await g({limit:F,sinceSeq:W}):void 0;return Response.json({global:q,shards:G.shards},{status:200})},p=async(I,j)=>{const H=me(I,["POST"]);if(H)return H;const Y=f(I,u,{code:"BAD_REQUEST",message:"Connector sync endpoint requires a `queryCoordinator` on the worker"}),U=await ee(I),$=er(U.cursor),F=typeof U.limit=="number"&&U.limit>0?U.limit:void 0,W=Le(U.tables),{headers:te}=await w(I,j),V=W??i(),se=await Y.orchestrateCdcSync(E,{cursors:$.s,defaultShardKey:n,headers:te,limit:F,tables:V}),G=[],q={...$.s};let Z=!1;for(const ie of se.shards)Z=at(G,ie.changes??[],nr(F))||Z,q[ie.shardKey]=ie.cursor;let _e=$.g;if(g){const ie=await g({limit:F,sinceSeq:$.g});Z=at(G,ie.changes,F)||Z,_e=ie.cursor}const Oe=tr({g:_e,s:q,v:1}),ve={changes:G,hasMore:Z,nextCursor:Oe};return Response.json(ve,{status:200})},A=async(I,j)=>{const H=me(I,["POST"]);if(H)return H;const Y=f(I,u,{code:"BAD_REQUEST",message:"Apply endpoint requires a `queryCoordinator` on the worker"}),U=await ee(I),F=(Array.isArray(U.batches)?U.batches:[]).map(G=>G).filter(G=>G!==null&&typeof G=="object"&&typeof G.shardKey=="string"&&Array.isArray(G.changes)),W=Array.isArray(U.globalChanges)?U.globalChanges:[],{headers:te}=await w(I,j),V=await Y.orchestrateApplyCdc(E,{batches:F,headers:te}),se=W.length>0&&t?await t({changes:W}):0;return Response.json({applied:V.applied+se,failed:V.failed,ok:V.ok},{status:200})},D=async(I,j)=>{const H=me(I,["POST"]);if(H)return H;h(I);const{headers:Y}=await w(I,j),U=await v(I,Y);return Response.json(U,{headers:{"content-type":"application/json"},status:U.failed.length>0?207:200})},M=async(I,j)=>{const H=me(I,["POST"]);if(H)return H;const Y=f(I,u,{code:"BAD_REQUEST",message:"Export-tap endpoint requires a `queryCoordinator` on the worker"});if(a===void 0||Object.keys(a).length===0||o===void 0)throw new d("Export-tap endpoint requires `exportSinks` + `exportCursorStore` on the worker",{code:"EXPORT_TAP_NOT_CONFIGURED",status:400});const U=await ee(I),$=typeof U.sink=="string"?U.sink:void 0,F=typeof U.limit=="number"&&U.limit>0?U.limit:void 0,W=Le(U.tables);if($===void 0)throw new d("Export-tap `sink` must name a configured sink",{code:"BAD_REQUEST",status:400});const te=a[$];if(te===void 0)throw new d(`Export-tap sink "${$}" is not configured`,{code:"NOT_FOUND",status:404});const{headers:V}=await w(I,j),se=W??i(),G=await Zn({coordinator:Y,cursorStore:o,defaultShardKey:n,headers:V,limit:F,shardDO:E,sink:te,tables:se});return Response.json(G,{headers:{"content-type":"application/json"},status:200})};return{[ro]:A,[no]:p,[Zr]:b,[oo]:M,[eo]:D,[to]:_}},co=(e,t)=>{let n;try{n=JSON.parse(e)}catch{return{error:{code:"BAD_ROW",line:t,message:"line is not valid JSON",table:""},ok:!1}}if(!n||typeof n!="object"||Array.isArray(n))return{error:{code:"BAD_ROW",line:t,message:"row must be a JSON object",table:""},ok:!1};const o=n;return typeof o.table!="string"||o.table.length===0?{error:{code:"BAD_ROW",line:t,message:"row is missing `table`",table:""},ok:!1}:!o.doc||typeof o.doc!="object"||Array.isArray(o.doc)?{error:{code:"BAD_ROW",line:t,message:"row is missing or malformed `doc`",table:o.table},ok:!1}:{doc:o.doc,ok:!0,table:o.table}},uo=(e,t,n,o,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:o}},lo=async(e,t,n)=>{if(!e.body)throw new d("Import endpoint requires a request body",{code:"BAD_REQUEST",status:400});const o=[],a=[],i=new Map;let u=0,h=0;const f=e.body.getReader(),w=new TextDecoder;let E="",O=0;const v=g=>{h+=1;const b=g.trim();if(b.length===0)return;u+=1;const _=co(b,h);if(!_.ok){o.push(_.error);return}const{doc:p,table:A}=_,D=t.resolveTableSharding?.(A);if(D?.mode.kind==="global"){a.push({doc:p,line:h,table:A});return}const M=uo(p,A,D,n,h);if(!M.ok){o.push(M.error);return}const I=i.get(M.shardKey);I?I.rows.push({doc:p,table:A}):i.set(M.shardKey,{rows:[{doc:p,table:A}],shardKey:M.shardKey,startLine:h})};for(;;){const{done:g,value:b}=await f.read();if(g)break;if(b&&(O+=b.byteLength,O>Ut))throw await f.cancel().catch(()=>{}),new d("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});E+=w.decode(b,{stream:!0});let _=E.indexOf(`
|
|
5
|
-
`);for(;_!==-1;){const p=E.slice(0,_);E=E.slice(_+1),v(p),_=E.indexOf(`
|
|
6
|
-
`)}}return E.length>0&&v(E),{errors:o,globalRows:a,perShard:i,received:u}},ho=e=>e.flatMap(t=>t.error?[{message:t.error.message,shardKey:t.shardKey,timedOut:t.error.timedOut}]:[]),bt=(e,t)=>{for(const[n,o]of Object.entries(t.inserted))e.inserted[n]=(e.inserted[n]??0)+o;for(const n of t.errors)e.errors.push({...n});e.conflicts+=t.conflicts},fo=async(e,t,n,o)=>{const a=t.defaultShardKey??"__root__",{errors:i,globalRows:u,perShard:h,received:f}=await lo(e,t,a),w={conflicts:0,errors:i,failed:[],inserted:{}},E=[];if(t.resolveTableSharding===void 0&&h.size>0&&E.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 O=t.queryCoordinator;if(!O)throw new d("Import endpoint requires a `queryCoordinator` on the worker",{code:"BAD_REQUEST",status:400});const v=await O.orchestrateImport(o,{batches:[...h.values()],headers:n});bt(w,v),w.failed.push(...ho(v.shards))}if(u.length>0)if(t.importGlobals){const O=u[0]?.line??1,v=await t.importGlobals({rows:u,startLine:O});bt(w,v)}else for(const O of u)w.errors.push({code:"GLOBAL_NOT_CONFIGURED",line:O.line,message:`row targets global table "${O.table}" but no \`importGlobals\` is configured`,table:O.table});return{conflicts:w.conflicts,errors:w.errors,failed:w.failed,inserted:w.inserted,received:f,...E.length>0?{warnings:E}:{}}},Me=e=>typeof e=="object"&&e!==null?e:{},Ke=e=>typeof e.kind=="string"?e.kind:"unknown",po=(e,t)=>{let n=Me(t),o=!1;Ke(n)==="optional"&&(o=!0,n=Me(n._meta?.inner));const a=Ke(n),i=n._meta??{},u={kind:a,name:e,optional:o};if(a==="id"&&typeof i.tableName=="string"&&(u.table=i.tableName),a==="array"){const h=Ke(Me(i.inner));h!=="unknown"&&(u.element=h)}return u},mo=e=>typeof e!="object"||e===null?[]:Object.entries(e).map(([t,n])=>po(t,n)).toSorted((t,n)=>t.name.localeCompare(n.name)),wo="/_lunora/admin/functions",go="/_lunora/admin/cron-jobs",yo="/_lunora/admin/openapi",bo="/_lunora/admin/openrpc",_o="/_lunora/admin/global/tables",Ro="/_lunora/admin/global/table",Eo="/_lunora/admin/global/facet",_t=e=>{if(e===void 0||e==="")return;let t;try{t=JSON.parse(e)}catch{return}if(!Array.isArray(t))return;const n=t.flatMap(o=>{if(typeof o!="object"||o===null||typeof o.column!="string")return[];const{column:a,value:i}=o;return[{column:a,value:i}]});return n.length===0?void 0:n},So=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:{}}),Ao=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"}),To=e=>{const{assertAdmin:t,options:n,parsePaging:o,queryParameter:a,requireAdminOption:i}=e,u=g=>{K(g,"GET","Functions");const b=i(g,n.functions,{code:"FUNCTIONS_NOT_CONFIGURED",message:"functions endpoint requires a `functions` registry on the worker"}),_=Object.entries(b).flatMap(([p,A])=>A.visibility==="internal"||A.kind==="stream"?[]:[{args:mo(A.args),kind:A.kind,path:p}]).toSorted((p,A)=>p.path.localeCompare(A.path));return Response.json({functions:_},{headers:{"content-type":"application/json"},status:200})},h=g=>{K(g,"GET","Cron-jobs");const b=i(g,n.cronJobs,{code:"CRON_JOBS_NOT_CONFIGURED",message:"cron-jobs endpoint requires a `cronJobs` map on the worker"}),_=Object.entries(b).flatMap(([p,A])=>A.map(D=>({args:D.args,cron:p,functionPath:D.functionPath,name:D.name,shardKey:D.shardKey,workflow:D.workflow}))).toSorted((p,A)=>p.name.localeCompare(A.name));return Response.json({jobs:_},{headers:{"content-type":"application/json"},status:200})},f=g=>(K(g,"GET","OpenAPI"),t(g),Response.json(n.openApiSpec??So,{headers:{"content-type":"application/json"},status:200})),w=g=>(K(g,"GET","OpenRPC"),t(g),Response.json(n.openRpcSpec??Ao,{headers:{"content-type":"application/json"},status:200})),E=async g=>{K(g,"GET","Global-tables");const b=i(g,n.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"});return Response.json(await b.listTables(),{headers:{"content-type":"application/json"},status:200})},O=async g=>{K(g,"GET","Global-table");const b=i(g,n.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),_=new URL(g.url),p=a(_,"table");if(p===void 0)throw new d("Global-table endpoint requires a `table` query param",{code:"BAD_REQUEST",status:400});const A=await b.readTablePage({...o(g),filters:_t(a(_,"filters")),table:p});return Response.json(A,{headers:{"content-type":"application/json"},status:200})},v=async g=>{K(g,"GET","Global-facet");const b=i(g,n.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),_=new URL(g.url),p=a(_,"table"),A=a(_,"column");if(p===void 0||A===void 0)throw new d("Global-facet endpoint requires `table` and `column` query params",{code:"BAD_REQUEST",status:400});const D=a(_,"limit"),M=D===void 0?void 0:Number(D),I=await b.facetColumn({column:A,filters:_t(a(_,"filters")),limit:M!==void 0&&Number.isFinite(M)?M:void 0,table:p});return Response.json(I,{headers:{"content-type":"application/json"},status:200})};return{[go]:h,[wo]:u,[Eo]:v,[Ro]:O,[_o]:E,[yo]:f,[bo]:w}},Oo="/_lunora/admin/kv/namespaces",vo="/_lunora/admin/kv/keys",Wt="/_lunora/admin/kv/value",Vt=32*1048576,Rt=60,ko=e=>{const{readJsonBody:t,requireAdminOption:n}=e,o=b=>n(b,e.kvIntrospector,{code:"KV_NOT_CONFIGURED",message:"KV endpoints require a `kvIntrospector` on the worker"}),a=b=>Response.json(b,{headers:{"content-type":"application/json"},status:200}),i=(b,_)=>{const p=new URL(b.url),A=p.searchParams.get("namespace")??"",D=p.searchParams.get("key")??"";if(A==="")throw new d(`KV-value ${_} request requires a \`namespace\` query parameter`,{code:"BAD_REQUEST",status:400});if(D==="")throw new d(`KV-value ${_} request requires a \`key\` query parameter`,{code:"BAD_REQUEST",status:400});return{key:D,namespace:A}},u=async(b,_)=>{if(!(await b.listNamespaces()).some(A=>A.binding===_))throw new d(`Unknown KV namespace binding \`${_}\``,{code:"NOT_FOUND",status:404})},h=async b=>(K(b,"GET","KV-namespaces"),a({namespaces:await o(b).listNamespaces()})),f=async b=>{K(b,"GET","KV-keys");const _=o(b),p=new URL(b.url),A=p.searchParams.get("namespace")??"";if(A==="")throw new d("KV-keys request requires a `namespace` query parameter",{code:"BAD_REQUEST",status:400});const D=p.searchParams.get("prefix")??void 0,M=p.searchParams.get("cursor")??void 0,I=p.searchParams.get("limit"),j=I===null?void 0:Number.parseInt(I,10);if(j!==void 0&&(!Number.isInteger(j)||j<1))throw new d("KV-keys `limit` must be a positive integer",{code:"BAD_REQUEST",status:400});const H=j===void 0?void 0:Math.min(j,1e3);return await u(_,A),a(await _.listKeys({cursor:M,limit:H,namespace:A,prefix:D}))},v={DELETE:async b=>{const _=o(b),p=i(b,"DELETE");return await u(_,p.namespace),await _.deleteKey(p),a({deleted:!0})},GET:async b=>{const _=o(b),p=i(b,"GET");return await u(_,p.namespace),a(await _.getValue(p))},PUT:async b=>{const _=o(b),p=await t(b,Vt);if(typeof p.namespace!="string"||p.namespace==="")throw new d("KV-value PUT request requires a `namespace` string",{code:"BAD_REQUEST",status:400});if(typeof p.key!="string"||p.key==="")throw new d("KV-value PUT request requires a `key` string",{code:"BAD_REQUEST",status:400});if(typeof p.value!="string")throw new d("KV-value PUT request requires a `value` string",{code:"BAD_REQUEST",status:400});if(p.expirationTtl!==void 0&&(typeof p.expirationTtl!="number"||!Number.isInteger(p.expirationTtl)||p.expirationTtl<Rt))throw new d("KV-value PUT `expirationTtl` must be an integer ≥ 60",{code:"BAD_REQUEST",status:400});const A=Math.floor(Date.now()/1e3)+Rt;if(p.expiration!==void 0&&(typeof p.expiration!="number"||!Number.isInteger(p.expiration)||p.expiration<A))throw new d("KV-value PUT `expiration` must be a Unix-seconds timestamp at least 60 seconds in the future",{code:"BAD_REQUEST",status:400});return await u(_,p.namespace),await _.putValue({expiration:p.expiration,expirationTtl:p.expirationTtl,key:p.key,metadata:p.metadata,namespace:p.namespace,value:p.value}),a({ok:!0})}},g=b=>{const _=v[b.method];if(!_)throw new d("KV-value endpoint requires GET, PUT, or DELETE",{code:"METHOD_NOT_ALLOWED",status:405});return _(b)};return{[Oo]:h,[vo]:f,[Wt]:g}},Io="/_lunora/migrate",Po="/_lunora/admin/pitr",Do="/_lunora/admin/rank",No="/_lunora/admin/rankpage",Uo="/_lunora/admin/shard-traffic",Co=new Set(["__lunora_admin__:migrationStatus","__lunora_admin__:runMigration"]),Bo=new Set(["__lunora_admin__:getPitrBookmark","__lunora_admin__:pitrRestore"]),xo=async e=>{const n=await be(e,"Migration")??{};if(typeof n.table!="string"||n.table.length===0)throw new d("Migration request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof n.functionPath!="string"||!Co.has(n.functionPath))throw new d("Migration request `functionPath` must be a migration admin op",{code:"BAD_REQUEST",status:400});return{args:n.args??{},functionPath:n.functionPath,table:n.table}},Ho=async e=>{const n=await be(e,"Rank")??{};if(typeof n.table!="string"||n.table.length===0)throw new d("Rank request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof n.index!="string"||n.index.length===0)throw new d("Rank request is missing `index`",{code:"BAD_REQUEST",status:400});if(typeof n.partitionKey!="string")throw new d("Rank request `partitionKey` must be a string",{code:"BAD_REQUEST",status:400});if(typeof n.rowId!="string"||n.rowId.length===0)throw new d("Rank request is missing `rowId`",{code:"BAD_REQUEST",status:400});if(!Array.isArray(n.sortValues))throw new d("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}},Lo=e=>{if(e!==void 0){if(!Array.isArray(e)||e.some(t=>t!=="asc"&&t!=="desc"))throw new d('Rank page request `directions` must be an array of "asc"|"desc"',{code:"BAD_REQUEST",status:400});return e}},Mo=e=>{if(typeof e.table!="string"||e.table.length===0)throw new d("Rank page request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof e.index!="string"||e.index.length===0)throw new d("Rank page request is missing `index`",{code:"BAD_REQUEST",status:400});if(e.partitionKey!==void 0&&typeof e.partitionKey!="string")throw new d("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 d("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 d("Rank page request `cursor` must be a string or null",{code:"BAD_REQUEST",status:400})},Ko=async e=>{const n=await be(e,"Rank page")??{};Mo(n);const o=Lo(n.directions);return{cursor:typeof n.cursor=="string"?n.cursor:null,directions:o,index:n.index,partitionKey:typeof n.partitionKey=="string"?n.partitionKey:void 0,table:n.table,take:typeof n.take=="number"?n.take:void 0}},jo=async e=>{const n=await be(e,"Shard-traffic")??{};if(typeof n.table!="string"||n.table.length===0)throw new d("Shard-traffic request is missing `table`",{code:"BAD_REQUEST",status:400});return{table:n.table}},$o=async e=>{const n=await ee(e);if(typeof n.functionPath!="string"||!Bo.has(n.functionPath))throw new d("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 d("PITR `shardKey` must be a string",{code:"BAD_REQUEST",status:400});return{args:n.args??{},functionPath:n.functionPath,shardKey:n.shardKey}},Fo=e=>{const{defaultShard:t,forwardToShard:n,isAdmin:o,queryCoordinator:a,resolveForwardContext:i,shardDO:u}=e,h=(g,b)=>{if(g.method!=="POST")throw new d(`${b} endpoint requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});if(!o(g))throw new d("Admin auth required",{code:"FORBIDDEN",status:403});if(!a)throw new d(`${b} endpoint requires a \`queryCoordinator\` on the worker`,{code:"BAD_REQUEST",status:400});return a},f=async(g,b)=>{const _=h(g,"Migration"),p=await xo(g),{headers:A}=await i(g,b),D=await _.orchestrateMigration(u,{args:p.args,defaultShardKey:t,functionPath:p.functionPath,headers:A,table:p.table});return Response.json(D,{headers:{"content-type":"application/json"},status:200})},w=async(g,b)=>{const _=h(g,"Rank"),p=await Ho(g),{headers:A}=await i(g,b),D=await _.orchestrateRank(u,{headers:A,index:p.index,partitionKey:p.partitionKey,rowId:p.rowId,sortValues:p.sortValues,table:p.table});return Response.json(D,{headers:{"content-type":"application/json"},status:200})},E=async(g,b)=>{const _=h(g,"Rank page"),p=await Ko(g),{headers:A}=await i(g,b),D=await _.orchestrateRankPage(u,{...p,headers:A});return Response.json(D,{headers:{"content-type":"application/json"},status:200})},O=async(g,b)=>{const _=h(g,"Shard-traffic"),p=await jo(g),{headers:A}=await i(g,b),D=await _.orchestrateShardTraffic(u,{headers:A,table:p.table});return Response.json(D,{headers:{"content-type":"application/json"},status:200})},v=async(g,b)=>{if(K(g,"POST","PITR"),!o(g))throw new d("admin PITR endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403});const _=await $o(g),{headers:p}=await i(g,b),A=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:_.args,functionPath:_.functionPath}),headers:p,method:"POST"});return n(u,_.shardKey??t,A)};return{[Io]:f,[Po]:v,[Do]:w,[No]:E,[Uo]:O}},Go=1,Qo=0,zo=32,Wo=512,Vo=/^[a-z][\d_a-z*/-]{0,255}(?:@[a-z][\d_a-z*/-]{0,13})?=[\u0020-\u002B\u002D-\u003C\u003E-\u007E]{1,256}$/,qo=e=>{if(e==null)return;const t=e.trim();if(t.length===0||t.length>Wo)return;const n=t.split(",");if(!(n.length>zo)){for(const o of n)if(!Vo.test(o.trim()))return;return t}},Jo=e=>{const t=Mn(e.headers.get("traceparent"));if(t===void 0)return;const n=qo(e.headers.get("tracestate"));return{parentSpanId:t.parentSpanId,sampled:t.sampled,traceId:t.traceId,...n===void 0?{}:{traceState:n}}},Yo=(e,t={})=>{const n=Jo(e),o=t.trustInbound===!0?n:void 0,a=Te(8),i=o?.traceId??Te(16),u=cr(t.sampling,o===void 0?a:i),h=u.isTraced&&(o===void 0||o.sampled);return{decision:u,ignoredUpstream:n!==void 0&&o===void 0,trace:{sampled:h,spanId:a,traceFlags:h?Go:Qo,traceId:i,...o?.parentSpanId===void 0?{}:{parentSpanId:o.parentSpanId},...o?.traceState===void 0?{}:{traceState:o.traceState}}}},Xo=(e,t)=>{t.traceparent=Ln(e.traceId,e.spanId,e.sampled),e.traceState!==void 0&&(t.tracestate=e.traceState)},Zo=(e,t)=>{let n;return()=>{if(n===void 0){const o=Fn(e),a=t===void 0?void 0:t.cf;n=Kn($n(o),jn(o,a))}return n}},ea="/_lunora/admin/scheduled",ta="/_lunora/admin/scheduled/status",na="/_lunora/admin/scheduled/ws",ra="/_lunora/admin/scheduled/cancel",oa="/_lunora/admin/scheduled/dead",aa="/_lunora/admin/scheduled/dead/retry",sa="/_lunora/admin/scheduled/dead/cancel",ia=e=>{const{checkWsAdmin:t,requireSchedulerNamespace:n,resolveSchedulerStub:o,schedulerInstanceName:a}=e,i=(f,w)=>E=>{if(E.method!=="GET")throw new d(`${w} endpoint requires GET`,{code:"METHOD_NOT_ALLOWED",status:405});return o(E).fetch(new Request(`https://scheduler.internal${f}`,{method:"GET"}))},u=(f,w,E=w)=>async O=>{if(O.method!=="POST")throw new d(`${E} requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});const v=o(O),g=await O.json().catch(()=>{});if(typeof g?.id!="string"||g.id==="")throw new d(`${w} requires a string \`id\``,{code:"BAD_REQUEST",status:400});return v.fetch(new Request(`https://scheduler.internal${f}`,{body:JSON.stringify({id:g.id}),headers:{"content-type":"application/json"},method:"POST"}))},h=async f=>{if(f.headers.get("Upgrade")!=="websocket")throw new d("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});if(!await t(f))throw new d("admin authorization required",{code:"ADMIN_FORBIDDEN",status:403});const w=n();return we(w,a).fetch(new Request("https://scheduler.internal/ws",{headers:{Upgrade:"websocket"}}))};return{[ra]:u("/cancel","Scheduled-cancel","Scheduled-cancel endpoint"),[sa]:u("/dead/cancel","Scheduled dead-letter action"),[oa]:i("/dead","Scheduled dead-letter"),[aa]:u("/dead/retry","Scheduled dead-letter action"),[ea]:i("/list","Scheduled-list"),[ta]:i("/status","Scheduler-status"),[na]:h}},ca=(e,...t)=>{let n=e.cf;for(const o of t){if(typeof n!="object"||n===null)return;n=n[o]}return typeof n=="string"?n:void 0},Et={mtls:e=>ca(e,"tlsClientAuth","certVerified")==="SUCCESS"},da=e=>e===void 0||e===!1?()=>!1:e===!0?()=>!0:typeof e=="function"?e:(Object.hasOwn(Et,e)?Et[e]:void 0)??(()=>!1),ua=e=>{if(e!==void 0)return()=>{};let t=!1;return()=>{t||(t=!0,console.warn('[lunora] Ignored an inbound `traceparent`, so this request starts a new trace instead of joining the caller\'s. That is the safe default: the header is caller-supplied, and trusting it lets any client choose which trace its spans and logs join. If this worker sits behind a gateway, service mesh, or Cloudflare Access that sets `traceparent` itself, set `trustInboundTraceContext: true` on createWorker() (or `"mtls"` to trust only edge-verified client certificates). Set it to `false` to keep this behaviour and silence this message.'))}},la="/_lunora/admin/vector/indexes",ha="/_lunora/admin/vector/query",fa=e=>{const{readJsonBody:t,requireAdminOption:n}=e,o=async i=>{K(i,"GET","Vector-indexes");const u=n(i,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});return Response.json({indexes:await u.listIndexes()},{headers:{"content-type":"application/json"},status:200})},a=async i=>{K(i,"POST","Vector-query");const u=n(i,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});if(u.queryIndex===void 0)throw new d("vector index querying is not enabled on this worker",{code:"VECTOR_QUERY_UNSUPPORTED",status:400});const f=await t(i);if(typeof f.name!="string"||f.name==="")throw new d("Vector-query request requires a `name` string",{code:"BAD_REQUEST",status:400});if(typeof f.text!="string"||f.text==="")throw new d("Vector-query request requires a `text` string",{code:"BAD_REQUEST",status:400});if(f.topK!==void 0&&(typeof f.topK!="number"||!Number.isInteger(f.topK)||f.topK<1))throw new d("Vector-query `topK` must be a positive integer",{code:"BAD_REQUEST",status:400});const w=await u.queryIndex({name:f.name,text:f.text,topK:f.topK});return Response.json(w,{headers:{"content-type":"application/json"},status:200})};return{[la]:o,[ha]:a}},pa="/_lunora/admin/workflows/instances",ma="/_lunora/admin/workflows/instance",wa="/_lunora/admin/workflows/status",ga={complete:!0,errored:!0,paused:!0,queued:!0,running:!0,terminated:!0,unknown:!0,waiting:!0,waitingForPause:!0},ya=e=>e!==null&&Object.hasOwn(ga,e)?e:void 0,St=(e,t)=>{const n=e.searchParams.get(t);if(n===null)return;const o=Number(n);return Number.isInteger(o)&&o>0?o:void 0},je=(e,t)=>{const n=e.searchParams.get(t);if(n===null||n==="")throw new d(`Workflows admin endpoint requires a \`${t}\` query parameter`,{code:"BAD_REQUEST",status:400});return n},At=()=>{throw new d("Workflow inspection is unconfigured. Set CLOUDFLARE_ACCOUNT_ID + CLOUDFLARE_API_TOKEN in your .dev.vars to enable it.",{code:"WORKFLOWS_NOT_CONFIGURED",status:501})},ba=e=>{const{assertAdmin:t,resolveWorkflowsClient:n}=e,o=async(u,h,f)=>{K(u,"GET","Workflows instances"),t(u);const w=n(h);if(!w)return Response.json({configured:!1,instances:[],page:1,perPage:0,totalCount:0});const E=je(f,"name"),O=ya(f.searchParams.get("status"));return Response.json(await w.listInstances({page:St(f,"page"),perPage:St(f,"perPage"),status:O,workflowName:E}))},a=async(u,h,f)=>{K(u,"GET","Workflows instance"),t(u);const w=n(h);return w?Response.json(await w.getInstance({instanceId:je(f,"id"),workflowName:je(f,"name")})):At()},i=async(u,h)=>{K(u,"POST","Workflows status"),t(u);const f=n(h);if(!f)return At();const w=await u.json().catch(()=>{});if(typeof w?.name!="string"||w.name===""||typeof w.id!="string"||w.id==="")throw new d("Workflows status action requires string `name` and `id`",{code:"BAD_REQUEST",status:400});const{action:E}=w;if(E!=="pause"&&E!=="resume"&&E!=="terminate")throw new d("Workflows status action must be one of: pause, resume, terminate",{code:"BAD_REQUEST",status:400});return Response.json(await f.setInstanceStatus({action:E,instanceId:w.id,workflowName:w.name}))};return{[ma]:a,[pa]:o,[wa]:i}},_a={[Wt]:Vt,[Xn]:Yn},Tt="/_lunora/rpc",Ra="/_lunora/rpc-batch",Ea="/_lunora/ws",Ee=(e,t,n)=>({resourceAttributes:Zo(e,t),...n===void 0?{}:{waitUntil:n}}),$e=e=>e?.waitUntil?{waitUntil:t=>e.waitUntil?.(t)}:{},Ot=e=>({spanId:e.spanId,traceFlags:e.traceFlags,traceId:e.traceId,...e.parentSpanId===void 0?{}:{parentSpanId:e.parentSpanId}}),Fe=e=>{const{method:t}=e,n=e.headers.get("user-agent")??void 0;let o;try{o=new URL(e.url)}catch{return{method:t,userAgent:n}}const a=o.port===""?void 0:Number(o.port);return{host:o.hostname,method:t,path:o.pathname,port:Number.isNaN(a)?void 0:a,scheme:o.protocol.replace(":",""),userAgent:n}},vt="/_lunora/voice/",Sa="/_lunora/scheduler/dispatch",Aa="/_lunora/admin/cron-jobs/run",Ta="/_lunora/admin/ws-token",Oa="/_lunora/admin/",va="/_lunora/migrate",ka="/_lunora/status",Ia=e=>e.startsWith(Oa)||e===va,Pa=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}}},Da="/api/auth",Na="__lunora_admin__:recordAuthEvent",Ua="__lunora_admin__:listPushSubscriptions",Ca=["/sign-in","/sign-up","/callback"],Ba=(e,t)=>{const n=t.endsWith("/")?t.slice(0,-1):t;if(!e.startsWith(`${n}/`))return!1;const o=e.slice(n.length);return Ca.some(a=>o===a||o.startsWith(`${a}/`))},Se=(e,t,n,o)=>{const a=Dn(n),i=a?n.code:"INTERNAL_SERVER_ERROR",u=a?n.status:500,h=n instanceof Error?n.message:String(n);return{durationMs:t,error:{code:i,message:h,status:u},functionPath:e,ok:!1,...o.fanOut?{fanOut:{failed:0,shards:0,table:o.fanOut.table}}:{},...o.shardKey?{shardKey:o.shardKey}:{}}},xa=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},kt=e=>e.waitUntil?{waitUntil:t=>{e.waitUntil?.(t)}}:void 0,Ha=e=>{const t=e?.queue;return typeof t=="string"&&t.length>0?t:"unknown"},ze=new WeakMap,ue=async(e,t,n,o=ze.get(e))=>{const a={"content-type":"application/json"},i=e.headers.get("authorization"),u=e.headers.get("cookie"),h=e.headers.get("x-d1-bookmark"),f=e.headers.get("x-lunora-mutation-id"),w=e.headers.get("x-lunora-client-id"),E=e.headers.get("x-lunora-client-seq");i&&(a.authorization=i),u&&(a.cookie=u),h&&(a["x-d1-bookmark"]=h),f&&(a["x-lunora-mutation-id"]=f),w&&(a["x-lunora-client-id"]=w),E&&(a["x-lunora-client-seq"]=E);const O=e.headers.get("cf-connecting-ip");if(O&&(a["x-lunora-client-ip"]=O),!n)return{claims:null,headers:a,identity:null,userId:null};const v=await n(e,t,o);if(!v||typeof v.userId!="string"||v.userId.length===0)return{claims:null,headers:a,identity:null,userId:null};a["x-lunora-userid"]=xn(v.userId);const g=xa(v);g!==void 0&&(a["x-lunora-identity-exp"]=String(g));const{userId:b,..._}=v,p=Object.keys(_).length>0?_:null;return p&&(a["x-lunora-identity"]=Hn(p)),{claims:p,headers:a,identity:v,userId:b}},La=new Set(["concat","first","groupBy","max","min","rank","sum","topK"]),Ma=e=>{if(e===void 0)return;if(!e||typeof e!="object")throw new d("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 d("RPC `fanOut.table` must be a non-empty string",{code:"BAD_REQUEST",status:400});if(!t.merge||typeof t.merge!="object")throw new d("RPC `fanOut.merge` must be an object",{code:"BAD_REQUEST",status:400});const n=t.merge;if(typeof n.kind!="string"||!La.has(n.kind))throw new d("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 d("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 d("RPC `fanOut.merge.by` must be a non-empty string",{code:"BAD_REQUEST",status:400})}return t},Ka=(e,t)=>{e?.LUNORA_DEBUG_RPC&&console.warn(`[lunora:rpc] ${t.fanOut?"fan-out":`shard=${t.shardKey??"(root)"}`} ${t.functionPath}`)},Ge=(e,t)=>{const n=t.functions?.[e.functionPath]?.x402;if(n){if(e.fanOut)throw new d("a paid (`.x402`) function cannot be fanned out",{code:"BAD_REQUEST",status:400});if(!t.x402Charge)throw new d(`function "${e.functionPath}" is marked paid (.x402) but no x402Charge gate is configured on the worker`,{code:"MISCONFIGURED",status:500});return n}},ja=async e=>{const t=await Bt(e);let n;try{n=JSON.parse(t)}catch{throw new d("RPC body must be valid JSON",{code:"BAD_REQUEST",status:400})}if(!n||typeof n!="object"||typeof n.functionPath!="string")throw new d("RPC envelope is missing `functionPath`",{code:"BAD_REQUEST",status:400});const o=n;if(o.args!==void 0&&Ct(o.args,"RPC"),o.shardKey!==void 0&&typeof o.shardKey!="string")throw new d("RPC `shardKey` must be a string",{code:"BAD_REQUEST",status:400});const a=n,i=Ma(a.fanOut),u=a.args??{};if(i&&a.functionPath.startsWith("__lunora_relation__:")){const h=u.table;if(typeof h=="string"&&h!==i.table)throw new d("RPC `args.table` must match the authorized `fanOut.table` for a relation fan-out",{code:"BAD_REQUEST",status:400});u.table=i.table}return{args:u,fanOut:i,functionPath:a.functionPath,shardKey:a.shardKey}},Ae=new Map,$a=5e3,Fa=4096,Ga=async(e,t)=>{const n=Date.now(),o=Ae.get(t);if(o!==void 0&&o.expiresMs>n)return o.relayCount;o!==void 0&&Ae.delete(t);let a=0;try{const i=await we(e,t).fetch(new Request("https://shard.internal/_lunora/route"));if(i.ok){const h=(await i.json()).relayCount;typeof h=="number"&&h>0&&(a=Math.floor(h))}}catch{a=0}return Nt(Ae,Fa),Ae.set(t,{expiresMs:n+$a,relayCount:a}),a},It=(e,t)=>{if(!(e===null||typeof e!="object"))return Object.entries(e).find(([,n])=>n===t)?.[0]},ye=(e,t,n)=>new Request("https://shard.internal/rpc",{body:JSON.stringify({args:t,functionPath:e}),headers:n,method:"POST"}),Qa=["x-lunora-userid","x-lunora-identity","x-lunora-identity-exp"],Pt=(e,t)=>{for(const n of Qa){e.delete(n);const o=t[n];o!==void 0&&e.set(n,o)}},za=async(e,t,n)=>e.length===0||n.length===0?!1:qe(await Mt(e,t),n),Dt=(e,t)=>{if(!t||t.length===0)return!1;const n=e.headers.get("authorization");if(!n)return!1;const[o,...a]=n.split(" ");return o?.toLowerCase()!=="bearer"?!1:qe(t,a.join(" ").trim())},Wa=async(e,t,n)=>{if(!t||t.length===0)return!1;const o=new URL(e.url).searchParams.get("token");return o===null?!1:await Nr(t,o)?!0:n?!1:qe(t,o)},Va=(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 ar(`d1:${e}`,t);if(typeof n.list=="function"&&typeof n.head=="function"&&typeof n.createMultipartUpload=="function")return Be(`r2:${e}`,!0);if(typeof n.send=="function"&&typeof n.sendBatch=="function"&&typeof n.get!="function")return Be(`queue:${e}`,!0);if(typeof n.connectionString=="string")return Be(`hyperdrive:${e}`,!0)},qt=e=>{const t=da(e.trustInboundTraceContext),n=ua(e.trustInboundTraceContext),o=e.defaultShardKey??"__root__",a=sr(e.resolveIdentity,e.identity),i=it(e.shardDO,e.jurisdiction),u=e.schedulerDO===void 0?void 0:it(e.schedulerDO,e.jurisdiction);let h=!1;const f=r=>{if(r===void 0||e.jurisdiction===void 0)return r;h||(h=!0,console.warn(`[lunora] jurisdiction "${e.jurisdiction}" pins placement, so region hints (\`shardRegion\`, replica and relay placement) are not sent. Residency wins.`))},w=async(r,s,l,c=e.shardRegion?.(s))=>we(r,s,f(c)).fetch(l);let E;const O=()=>e.adminToken??E;let v;const g=()=>e.requireEphemeralWsToken??v??!0;let b;const _=r=>{const s=r??{};if(b??=It(r,e.shardDO),v===void 0&&e.requireEphemeralWsToken===void 0){const c=s.LUNORA_REQUIRE_EPHEMERAL_WS_TOKEN;typeof c=="string"&&c.length>0&&(v=Ir(c,!0))}if(E!==void 0||e.adminToken!==void 0)return;const l=s.LUNORA_ADMIN_TOKEN;typeof l=="string"&&l.length>0&&(E=l)},p=new WeakSet,A=r=>Dt(r,O())||p.has(r),D=async(r,s)=>{const l=await ue(r,s,e.resolveIdentity);if(p.has(r)&&l.headers.authorization===void 0){const c=O();c!==void 0&&(l.headers.authorization=`Bearer ${c}`)}return l};let M=!1,I=!1;const j=()=>{I||(I=!0,console.warn("[lunora] `replicaReads: true` has no effect without `functions` — read eligibility is decided from the function registry."))},H=r=>{if(!e.allowUnauthenticatedShardAccess){const s=r==="fan-out"?"authorizeFanOut":"authorizeShard";throw new d(`${r} access is default-denied: configure \`${s}\` on the worker, or set \`allowUnauthenticatedShardAccess: true\` to explicitly allow unauthenticated ${r} access (relying solely on per-row RLS).`,{code:r==="fan-out"?"FORBIDDEN_FANOUT":"FORBIDDEN_SHARD",status:403})}M||(M=!0,console.warn([`[lunora] SECURITY: serving ${r} access with \`allowUnauthenticatedShardAccess: true\` and no \`authorizeShard\`/\`authorizeFanOut\` — `,"any caller (including unauthenticated ones) can target any shard / fan out across the table. ","This is safe only if every table is protected by per-row RLS. Configure `authorizeShard`/`authorizeFanOut` to gate it."].join("")))},Y=async(r,s)=>{if(e.authorizeShard){if(!await e.authorizeShard({identity:r,shardKey:s}))throw new d("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else s!==o&&H("shard")},U=Fo({defaultShard:o,forwardToShard:w,isAdmin:A,queryCoordinator:e.queryCoordinator,resolveForwardContext:D,shardDO:i}),$=async(r,s,l,c,m)=>{const R={"content-type":"application/json","x-lunora-system":"1"};return m?.userId!==void 0&&m.userId.length>0&&(R["x-lunora-userid"]=m.userId),m?.identity!==void 0&&m.identity.length>0&&(R["x-lunora-identity"]=m.identity),c!==void 0&&c.length>0&&(R["x-lunora-mutation-id"]=c),w(i,l,ye(r,s,R))},F=async(r,s,l,c)=>{const m=l?.[r];if(!m||typeof m.create!="function")throw new d(`${c} targets workflow binding "${r}", which is not bound on env`,{code:"CRON_JOB_FAILED",status:500});if(hr(s))throw new d(`${c} params ${fr}`,{code:"BAD_REQUEST",status:400});await m.create({params:s})},W=async(r,s)=>{if(r.workflow){await F(r.workflow,r.args??{},s,`cron job "${r.name}"`);return}if(r.functionPath===void 0)throw new d(`cron job "${r.name}" has neither a function target nor a workflow target`,{code:"CRON_JOB_FAILED",status:500});const l=await $(r.functionPath,r.args??{},r.shardKey??o);if(!l.ok)throw new d(`cron job "${r.name}" (${r.functionPath}) failed with shard status ${String(l.status)}`,{code:"CRON_JOB_FAILED",status:500})},te=async(r,s,l,c)=>{const m=e.cronJobs?.[r];if(m)for(const R of m)try{await W(R,s)}catch(k){l.push(c(k))}},V=async(r,s)=>{if(!A(r))throw new d("admin endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403});if(K(r,"POST","cron-jobs run"),!e.cronJobs)throw new d("cron-jobs run endpoint requires a `cronJobs` map on the worker",{code:"CRON_JOBS_NOT_CONFIGURED",status:400});const l=await ee(r),c=typeof l.name=="string"?l.name:"";if(c==="")throw new d("cron-jobs run endpoint requires a job `name`",{code:"BAD_REQUEST",status:400});const m=Object.values(e.cronJobs).flat().find(R=>R.name===c);if(!m)throw new d(`no cron job named "${c}" is registered`,{code:"CRON_JOB_NOT_FOUND",status:404});return await W(m,s),Response.json({name:c,ran:!0},{status:200})},se=async r=>{const s=typeof r.pool=="string"&&r.pool.length>0?r.pool:void 0;if(!s||!u||typeof r.id!="string")return;const l=typeof r.instanceName=="string"&&r.instanceName.length>0?r.instanceName:"default";try{await we(u,l).fetch(new Request("https://scheduler.internal/complete",{body:JSON.stringify({id:r.id,pool:s}),headers:{"content-type":"application/json"},method:"POST"}))}catch{}},G=async(r,s)=>{K(r,"POST","Scheduler dispatch");const l=await Bt(r),c=s??{},m=typeof c.LUNORA_SCHEDULER_SECRET=="string"?c.LUNORA_SCHEDULER_SECRET:void 0,R=e.adminToken??(typeof c.LUNORA_ADMIN_TOKEN=="string"?c.LUNORA_ADMIN_TOKEN:void 0),k=r.headers.get("x-lunora-scheduler-signature");let y=!1;if(k&&m?y=await za(m,l,k):R&&(y=Dt(r,R)),!y)throw new d("Scheduler dispatch requires a valid signature or admin bearer",{code:"FORBIDDEN",status:403});let S;try{S=JSON.parse(l)}catch{throw new d("Scheduler dispatch body must be valid JSON",{code:"BAD_REQUEST",status:400})}const T=S??{},C=T.args??{};if(typeof T.workflow=="string"&&T.workflow.length>0)return await F(T.workflow,C,s,"scheduled workflow"),await se(T),Response.json({ok:!0},{status:200});if(typeof T.functionPath!="string"||T.functionPath.length===0)throw new d("Scheduler dispatch is missing `functionPath`",{code:"BAD_REQUEST",status:400});const B=typeof T.shardKey=="string"&&T.shardKey.length>0?T.shardKey:o,x=typeof T.id=="string"&&T.id.length>0?T.id:void 0,re=Pa(r),L=await $(T.functionPath,C,B,x,re);return await se(T),L},q=r=>{if(!A(r))throw new d("admin endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403})},Z=(r,s,l)=>{if(q(r),s===void 0)throw new d(l.message,{code:l.code,status:400});return s},_e=Hr({assertAdmin:q,getReader:()=>e.authAuditReader}),Oe=async(r,s)=>{q(r);const l=e.notifySubscriptionStore;if(l===void 0)return Response.json({result:Qe({subscriptions:[]})},{headers:{"content-type":"application/json"},status:200});const c=s?.kind,m=s?.userId,R=s?.limit,k=c==="fcm"||c==="web-push"?c:void 0,y=typeof m=="string"&&m!==""?m:void 0,S=typeof R=="number"&&Number.isFinite(R)?Math.trunc(R):0,T=S>0?Math.min(S,1e3):1e3,B=(await l.list({kind:k,limit:T,userId:y})).filter(x=>k!==void 0&&x.kind!==k?!1:y===void 0||(x.userId??null)===y).map(({keys:x,token:re,...L})=>L);return Response.json({result:Qe({subscriptions:B})},{headers:{"content-type":"application/json"},status:200})},ve=async(r,s)=>{if(!s.fanOut){if(s.functionPath===xr)return _e(r,s.args??{});if(s.functionPath===Ua)return Oe(r,s.args)}},ie=io({applyGlobals:e.applyGlobals,assertAdmin:q,exportCursorStore:e.exportCursorStore,exportSinks:e.exportSinks,defaultShardKey:o,knownTables:()=>[...e.listSchemaTables?.()??[]],queryCoordinator:e.queryCoordinator,requireAdminOption:Z,resolveForwardContext:D,shardDO:i,streamExportRows:(r,s,l,c)=>Gt(e,r,s,l,c,i),streamingImport:(r,s)=>fo(r,e,s,i),syncGlobals:e.syncGlobals}),ke=(r,s)=>{const l=r.searchParams.get(s);return l===null||l===""?void 0:l},Ie=r=>{const s=new URL(r.url),l=s.searchParams.get("limit"),c=s.searchParams.get("offset"),m=l===null?void 0:Number.parseInt(l,10),R=c===null?void 0:Number.parseInt(c,10);return{limit:m!==void 0&&Number.isFinite(m)&&m>=0?m:void 0,offset:R!==void 0&&Number.isFinite(R)&&R>=0?R:void 0}},Xe=()=>{if(u===void 0)throw new d("scheduled endpoints require a `schedulerDO` namespace on the worker",{code:"SCHEDULER_NOT_CONFIGURED",status:400});return u},Jt=ia({checkWsAdmin:async r=>A(r)||Wa(r,O(),g()),requireSchedulerNamespace:Xe,resolveSchedulerStub:r=>(q(r),we(Xe(),e.schedulerInstanceName??"default")),schedulerInstanceName:e.schedulerInstanceName??"default"}),Yt=ba({assertAdmin:q,resolveWorkflowsClient:e.workflowsClient??(()=>{})}),Xt=Jn({assertAdmin:q,parsePaging:Ie,queryParameter:ke,readBodyBytes:Qn,requireAdminOption:Z,storage:{storageBuckets:e.storageBuckets,storageDelete:e.storageDelete,storageDownload:e.storageDownload,storageList:e.storageList,storageSignedUrl:e.storageSignedUrl,storageUpload:e.storageUpload}}),Zt=Jr({options:e,readJsonBody:ee,requireAdminOption:Z}),en=fa({readJsonBody:ee,requireAdminOption:Z,vectorIntrospector:e.vectorIntrospector}),tn=ko({kvIntrospector:e.kvIntrospector,readJsonBody:ee,requireAdminOption:Z}),nn=ir({logArchive:e.logArchive,readJsonBody:ee,requireAdminOption:Z}),rn=To({assertAdmin:q,options:{cronJobs:e.cronJobs,functions:e.functions,globalIntrospector:e.globalIntrospector,openApiSpec:e.openApiSpec,openRpcSpec:e.openRpcSpec},parsePaging:Ie,queryParameter:ke,requireAdminOption:Z}),on=r=>{const s=[],l=i??r?.SHARD;if(l!==void 0&&s.push(or("durable-object:default",l,o)),e.health?.disableBindingProbes!==!0)for(const[c,m]of Object.entries(r??{})){const R=Va(c,m);R!==void 0&&s.push(R)}for(const c of e.health?.probes??[])s.push(c);return s},an=rr({appName:e.health?.appName,appVersion:e.health?.appVersion,auth:e.health?.auth??"public",cacheTtlMs:e.health?.cacheTtlMs,isAdmin:A,resolveProbes:on}),sn=r=>{const s=e.schedulerInstanceName??"default",l=()=>we(r,s),c=async(y,S)=>{const T=await l().fetch(new Request(`https://scheduler.internal${y}`,S));if(!T.ok)throw new d(`ctx.scheduler: SchedulerDO ${y} failed (${String(T.status)}): ${await T.text()}`,{code:"INTERNAL",status:500});return await T.json()},m=async(y,S)=>await c(y,{body:JSON.stringify(S),headers:{"content-type":"application/json"},method:"POST"}),R=y=>{const S=y;if(S==null)throw new d("ctx.scheduler: target is required — pass a reference from the generated `internal` / `workflows` / `agents`",{code:"BAD_REQUEST",status:400});if(typeof S.binding=="string"&&S.binding.length>0)return{workflow:S.binding};if(typeof S.__lunoraRef=="string")return{functionPath:S.__lunoraRef};throw new d("ctx.scheduler: expected a reference from the generated `internal` / `workflows` / `agents` — a bare function-path string is refused here, because an HTTP action can be reached unauthenticated",{code:"BAD_REQUEST",status:400})},k=async(y,S,T={})=>{const{id:C}=await m("/schedule",{args:T,scheduledFor:y,...R(S)});return C};return{cancel:async y=>await m("/cancel",{id:y}),get:async y=>await c(`/get?id=${encodeURIComponent(y)}`,{method:"GET"}),list:async()=>await c("/list",{method:"GET"}),runAfter:async(y,S,T)=>{if(!Number.isFinite(y)||y<0)throw new d("ctx.scheduler.runAfter: `delayMs` must be a non-negative finite number",{code:"BAD_REQUEST",status:400});return await k(Date.now()+y,S,T)},runAt:async(y,S,T)=>{if(!Number.isFinite(y))throw new d("ctx.scheduler.runAt: `timestampMs` must be a finite epoch-millisecond number",{code:"BAD_REQUEST",status:400});return await k(y,S,T)}}},cn=async(r,s,l)=>{const{claims:c,headers:m,userId:R}=await ue(r,s,a),k=async(y,S={})=>{const T=y.__lunoraRef;if(typeof T!="string")throw new d("ctx.run*: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});const C=ye(T,S,{...m,"x-lunora-system":"1"}),B=await w(i,o,C),x=await B.json();if(x.error)throw new d(x.error.message??"shard RPC failed",{code:x.error.code??"INTERNAL",status:B.status});return x.result};return{auth:{getIdentity:()=>Promise.resolve(c),userId:R},cache:l.cache,fetch:globalThis.fetch.bind(globalThis),runAction:k,runMutation:k,runQuery:k,...u===void 0?{}:{scheduler:sn(u)},...e.storage===void 0?{}:{storage:lr(e.storage(s))}}},dn=async(r,s,l)=>{if(!e.httpRouter)return;const c=await cn(r,s,l);try{return await e.httpRouter.fetch(r,{...s,__lunoraCtx:c},l)}catch(m){return console.error("[lunora] httpRouter (SSR) handler threw:",m),new Response("Internal Server Error",{status:500})}},un=async(r,s,l)=>{if(r.headers.get("Upgrade")!=="websocket")throw new d("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});const c=dt(r,ce);if(c)return c;const m=l.searchParams.get("shard")??o,{headers:R,identity:k}=await ue(r,s,a);await Y(k,m);const y=new Headers(r.headers),S=[...y.keys()];for(const C of S)C.startsWith("x-lunora-")&&y.delete(C);Pt(y,R);const T=It(s,e.shardDO);if(T!==void 0){y.set("x-lunora-shard-binding",T);const C=await Ga(i,m);if(C>0){const B=Ar(m,Math.floor(Math.random()*C));return w(i,B,new Request(r,{headers:y}),ut(r))}}return w(i,m,new Request(r,{headers:y}))},ln=async(r,s,l)=>{const{voiceAgents:c}=e;if(c===void 0)return new Response("Not found",{status:404});if(r.headers.get("Upgrade")!=="websocket")return new Response("Expected a WebSocket upgrade",{headers:{allow:"GET"},status:426});const m=dt(r,ce);if(m)return m;let R;try{R=decodeURIComponent(l.pathname.slice(vt.length))}catch{return new Response("Unknown voice agent",{status:404})}const k=Object.hasOwn(c,R)?c[R]:void 0;if(k===void 0)return new Response("Unknown voice agent",{status:404});const y=l.searchParams.get("threadKey");if(y===null||y.length===0)return new Response("Missing threadKey",{status:400});const{headers:S,identity:T}=await ue(r,s,a);if(e.authorizeShard){if(!await e.authorizeShard({identity:T,shardKey:y}))throw new d("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else H("shard");const C=new Headers(r.headers);for(const B of C.keys())B.startsWith("x-lunora-")&&C.delete(B);return Pt(C,S),w(k,y,new Request(r,{headers:C}))},hn=async(r,s,l)=>{if(e.authorizeFanOut){if(!await e.authorizeFanOut(l,r.table,s))throw new d("Forbidden fan-out",{code:"FORBIDDEN_FANOUT",status:403});return}if(s.startsWith("__lunora_relation__:"))throw new d("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 d("Fan-out requires `authorizeFanOut` to be configured on the worker when `authorizeShard` is set",{code:"FORBIDDEN_FANOUT",status:403});H("fan-out")},Re=async(r,s)=>{if(!(!r.fanOut&&r.functionPath.startsWith("__lunora_admin__:"))){if(r.fanOut){await hn(r.fanOut,r.functionPath,s);return}await Y(s,r.shardKey??o)}},fn=(r,s,l)=>{if(e.replicaReads!==!0)return;if(e.functions===void 0){j();return}if(e.functions[s]?.kind!=="query"||l.includes(jt)||l.includes(Kt))return;const c=ut(r);return c===void 0?void 0:{name:Tr(l,c),region:c}},pn=async(r,s,l,c,m)=>{const R=fn(r,s,c);if(R!==void 0){const k={...m,"x-lunora-replica-read":"1",...b===void 0?{}:{"x-lunora-shard-binding":b}},y=Or(r.headers.get("x-lunora-min-seq"));y!==void 0&&(k["x-lunora-min-seq"]=String(y));const S=await w(i,R.name,ye(s,l,k),R.region);if(S.status!==421)return S}return w(i,c,ye(s,l,m))},Pe=async(r,s,l,c,m,R)=>{const k=Date.now(),{observability:y,sampling:S}=e,T=Fe(r),{decision:C,ignoredUpstream:B,trace:x}=Yo(r,{...S===void 0?{}:{sampling:S},trustInbound:t(r)});B&&n();const re={...m,"x-lunora-sample-errors":C.keepErrors?"1":"0"};Xo(x,re);try{const L=await pn(r,s,l,c,re);de(y,{...T,...Ot(x),durationMs:Date.now()-k,functionPath:s,ok:L.ok,shardKey:c,...L.ok?{}:{error:{code:"SHARD_ERROR",message:`shard returned ${String(L.status)}`,status:L.status}}},R,void 0,{isTraced:x.sampled,keepErrors:C.keepErrors});const ne=new Response(L.body,{headers:L.headers,status:L.status,statusText:L.statusText});return ne.headers.set("x-lunora-shard-key",c),ne}catch(L){throw de(y,{...T,...Ot(x),...Se(s,Date.now()-k,L,{shardKey:c})},R,void 0,{isTraced:x.sampled,keepErrors:C.keepErrors}),L}},mn=r=>{if(r.fanOut&&r.shardKey)throw new d("RPC envelope cannot set both `shardKey` and `fanOut`",{code:"BAD_REQUEST",status:400});if(!r.fanOut&&r.functionPath.startsWith("__lunora_relation__:"))throw new d("`__lunora_relation__:*` is a fan-out-only reserved RPC and cannot be dispatched to a single shard",{code:"FORBIDDEN",status:403});if(r.fanOut&&!e.queryCoordinator)throw new d("RPC envelope set `fanOut` but no `queryCoordinator` is configured on the worker",{code:"BAD_REQUEST",status:400})},wn=async(r,s,l)=>{K(r,"POST","RPC");const c=await ja(r);Ka(s,c),mn(c);const m=await ve(r,c);if(m!==void 0)return m;const{headers:R,identity:k}=await ue(r,s,a);await Re(c,k);const y=Ge(c,e);{const S=Date.now(),{observability:T}=e,C=Fe(r),B=Ee(s,r,l&&(L=>l.waitUntil?.(L)));if(c.fanOut){const L=e.queryCoordinator;if(!L)throw new d("RPC envelope set `fanOut` but no `queryCoordinator` is configured on the worker",{code:"BAD_REQUEST",status:400});try{const ne=await L.fanOut(i,{args:c.args??{},fanOut:c.fanOut,functionPath:c.functionPath,headers:R});return de(T,{durationMs:Date.now()-S,fanOut:{failed:ne.failed,shards:ne.ok+ne.failed,table:c.fanOut.table},functionPath:c.functionPath,...C,ok:!0},B),Response.json(ne,{headers:{"content-type":"application/json"},status:200})}catch(ne){throw de(T,{...Se(c.functionPath,Date.now()-S,ne,{fanOut:{table:c.fanOut.table}}),...C},B),ne}}const x=c.shardKey??o,re=()=>Pe(r,c.functionPath,c.args??{},x,R,B);return y&&e.x402Charge?e.x402Charge(r,{functionPath:c.functionPath,price:y.price},re,$e(l)):re()}},gn=async(r,s,l)=>{K(r,"POST","RPC batch");const c=await ee(r),{calls:m}=c;if(!Array.isArray(m))throw new d("RPC batch `calls` must be an array",{code:"BAD_REQUEST",status:400});const{headers:R,identity:k}=await ue(r,s,a),y=Xr(m,o);for(const Q of y.values())for(const z of Q)if(e.functions?.[z.functionPath]?.x402)throw new d(`paid (\`.x402\`) function "${z.functionPath}" cannot be called in a batch; dispatch it individually over ${Tt}`,{code:"BAD_REQUEST",status:400});await Promise.all([...y.entries()].flatMap(([Q,z])=>z.map(oe=>Re({args:oe.args,functionPath:oe.functionPath,shardKey:Q},k))));const{observability:S}=e,T=Ee(s,r,l&&(Q=>l.waitUntil?.(Q))),C=Fe(r),B=[],x=[],re=(Q,z,oe,le)=>({body:{error:{code:oe,message:le}},id:Q.id,status:z}),L=(Q,z,oe,le,fe)=>{for(const J of Q)de(S,fe(J),T),B.push(re(J,z,oe,le))},ne=(Q,z,oe,le,fe)=>{for(const J of Q){const pe=le.get(J.id)??fe,ge=pe<400;de(S,{durationMs:oe,functionPath:J.functionPath,...C,ok:ge,shardKey:z,...ge?{}:{error:{code:"SHARD_ERROR",message:`batched call returned ${String(pe)}`,status:pe}}},T)}};await Promise.all([...y.entries()].map(async([Q,z])=>{const oe=new Headers(R);oe.set("content-type","application/json");const le=new Request("https://shard.internal/rpc-batch",{body:JSON.stringify({calls:z}),headers:oe,method:"POST"}),fe=Date.now();let J;try{J=await w(i,Q,le)}catch(X){const Ce=Date.now()-fe,{body:rt}=Nn(X,{fallbackCode:"SHARD_UNAVAILABLE",redactedMessage:"shard unavailable"});L(z,502,rt.code,rt.message,Pn=>({...Se(Pn.functionPath,Ce,X,{shardKey:Q}),...C}));return}const pe=Date.now()-fe,ge=J.headers.get("x-d1-bookmark");ge&&x.push(ge);let Ne;try{Ne=await J.json()}catch{const X=`shard batch returned a non-JSON response (${String(J.status)})`;L(z,J.status,"SHARD_ERROR",X,Ce=>({durationMs:pe,error:{code:"SHARD_ERROR",message:X,status:J.status},functionPath:Ce.functionPath,...C,ok:!1,shardKey:Q}));return}const Ue=Array.isArray(Ne.results)?Ne.results:[],kn=new Map(Ue.map(X=>[X.id,X.status??J.status])),In=new Set(Ue.map(X=>X.id));ne(z,Q,pe,kn,J.status),B.push(...Ue);for(const X of z)In.has(X.id)||B.push(re(X,J.status,"SHARD_ERROR",`shard batch omitted result for call ${String(X.id)}`))}));const tt={"content-type":"application/json"},[nt]=x;return x.length===1&&nt!==void 0&&(tt["x-d1-bookmark"]=nt),Response.json({results:B},{headers:tt,status:200})},yn=async(r,s,l,c={},m={})=>{try{const R=l.__lunoraRef;if(typeof R!="string")throw new d("serverQuery: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});const{headers:k,identity:y}=await ue(r,s,a,m.context),S={args:c,functionPath:R,shardKey:m.shardKey};await Re(S,y);const T=m.shardKey??o,C=Ee(s,r,m.waitUntil),B=()=>Pe(r,R,c,T,k,C),x=Ge(S,e);return x&&e.x402Charge?await e.x402Charge(r,{functionPath:R,price:x.price},B,$e(m.waitUntil?{waitUntil:m.waitUntil}:m.context)):await B()}catch(R){return ot(R)}},Ze=async(r,s,l)=>{const{observability:c}=e,m=Date.now(),R=Te(16),k=Te(8),y=kt(s);try{const S=await l();return de(c,{durationMs:Date.now()-m,functionPath:r,ok:!0,spanId:k,traceId:R},y),S}catch(S){throw de(c,{...Se(r,Date.now()-m,S,{}),spanId:k,traceId:R},y),S}finally{st(c,y)}},bn=async(r,s,l)=>{_(s);const c=[],m=y=>y instanceof Error?y:new Error(String(y)),R=e.crons?.[r.cron];if(R)try{await R(r,s,l)}catch(y){c.push(m(y))}if(await te(r.cron,s,c,m),e.backupStore&&e.backupCron!==void 0&&e.backupCron===r.cron)try{await zr(e,i,O(),r)}catch(y){c.push(m(y))}const[k]=c;if(c.length===1&&k)throw k;if(c.length>1)throw new AggregateError(c,`scheduled("${r.cron}") had ${String(c.length)} failure(s)`)},_n=async(r,s)=>{try{const l=r??{},c=e.adminToken??(typeof l.LUNORA_ADMIN_TOKEN=="string"?l.LUNORA_ADMIN_TOKEN:void 0);if(!c||c.length===0)return;await w(i,o,ye(Na,{outcome:s},{authorization:`Bearer ${c}`,"content-type":"application/json"}))}catch{}},Rn=async(r,s,l,c)=>{if(!e.authHandler)return;const m=await e.authHandler(r);if(!m)return;const R=e.authBasePath??Da;return Ba(l.pathname,R)&&c.waitUntil?.(_n(s,m.status>=400?"fail":"ok")),m},En=async({args:r,env:s,functionPath:l,request:c,shardKey:m,waitUntil:R})=>{Ct(r,"REST");const k={functionPath:l,...m===void 0?{}:{shardKey:m}},{headers:y,identity:S}=await ue(c,s,a);await Re(k,S);const T=m??o,C=Ee(s,c,R),B=()=>Pe(c,l,r,T,y,C),x=Ge(k,e);return x&&e.x402Charge?e.x402Charge(c,{functionPath:l,price:x.price},B,$e({waitUntil:R})):B()},Sn=Gn({functions:e.functions??{},invoke:En,readJsonBody:ee,edgeCache:e.restEdgeCache,...e.restRateLimit?{rateLimit:e.restRateLimit}:{}}),De=e.routes!==void 0&&Object.keys(e.routes).length>0?e.routes:void 0,An={[ka]:r=>r.method!=="GET"&&r.method!=="HEAD"?new Response(void 0,{headers:{allow:"GET, HEAD"},status:405}):Response.json({ok:!0},{headers:{"cache-control":"no-store"}}),[Ea]:(r,s,l)=>un(r,s,l),[Tt]:(r,s,l,c)=>wn(r,s,c),[Ra]:(r,s,l,c)=>gn(r,s,c),[Sa]:(r,s)=>G(r,s),[Aa]:(r,s)=>V(r,s),[Ta]:async r=>{K(r,"POST","ws-token"),q(r);const s=O();if(s===void 0)throw new d("ws-token minting requires a configured admin token",{code:"ADMIN_TOKEN_NOT_CONFIGURED",status:400});const l=await Dr(s);return Response.json(l,{headers:{"cache-control":"no-store"}})},...U,...ie,...Jt,...Yt,...Xt,...Zt,...en,...tn,...nn,...rn,...an,...Sn,...Br({assertAdmin:q,getAuthAdmin:()=>e.authAdmin,parsePaging:Ie,queryParameter:ke,readJsonBody:ee})};let ce=ct(e.security),et=!1;const Tn=r=>{et||(et=!0,ce=ct(e.security,r??{}))},On=async(r,s)=>{if(!(e.adminGate===void 0||!Ia(s)))try{await e.adminGate(r,ze.get(r))&&p.add(r)}catch{}},vn=async(r,s,l)=>{ze.set(r,l);const c=new URL(r.url);if(r.method==="POST"||r.method==="PUT"){const y=Number(r.headers.get("content-length")??""),S=_a[c.pathname]??Ut;if(Number.isFinite(y)&&y>S)throw new d("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413})}const m=await Rn(r,s,c,l);if(m)return m;if(De){const y=`${r.method} ${c.pathname}`,S=De[y]??De[c.pathname];if(S)return S(r,s,l)}const R=An[c.pathname];if(R)return await On(r,c.pathname),R(r,s,c,l);if(e.voiceAgents!==void 0&&c.pathname.startsWith(vt))return ln(r,s,c);const k=await dn(r,s,l);return k||new Response("Not found",{status:404})};return{async fetch(r,s,l){e.passThroughOnException&&l.passThroughOnException?.(),Tn(s),_(s);const c=dr(r,ce);if(c)return c;const m=ur(r,ce);if(m)return xe(m,r,ce);try{const R=await vn(r,s,l);return xe(R,r,ce)}catch(R){return xe(ot(R),r,ce)}finally{st(e.observability,kt(l))}},async queue(r,s,l){await Ze(`queue:${Ha(r)}`,l,async()=>{await e.queue?.(r,s,l)})},async scheduled(r,s,l){await Ze(`cron:${r.cron}`,l,async()=>{await bn(r,s,l)})},serverQuery:yn}},qa=e=>qt(e),Ja=e=>typeof e=="function"?{fetch:e}:e,Ya=e=>!!(e.crons??e.cronJobs??e.backupCron),bs=(e,t)=>{const n=Ja(e),o=typeof e=="object"&&typeof e.scheduled=="function"?e.scheduled:void 0,a=u=>{const h=qa({...u,httpRouter:n});return o!==void 0&&!Ya(u)?{...h,scheduled:async(f,w,E)=>{await o(f,w,E)}}:h};if(typeof t!="function")return a(t);const i=t;return{fetch:(u,h,f)=>a(i(h)).fetch(u,h,f),queue:(u,h,f)=>a(i(h)).queue?.(u,h,f)??Promise.resolve(),scheduled:(u,h,f)=>a(i(h)).scheduled(u,h,f),serverQuery:(u,h,f,w,E)=>a(i(h)).serverQuery(u,h,f,w,E)}},Xa=(e,t)=>{if(typeof e=="function")return e(t);const n=e.shardDO??t?.SHARD;if(!n)throw new d("@lunora/runtime: no shard Durable Object namespace found. Bind `SHARD` in wrangler.jsonc, or pass `createLunoraHandler({ shardDO: env.MY_SHARD })`.");return{...e,shardDO:n}},_s=(e={})=>(t,n,o)=>qt(Xa(e,n)).fetch(t,n,o??Un),Rs=e=>e;export{xr as GET_AUTH_AUDIT_LOG_OP,Un as NOOP_EXECUTION_CONTEXT,As as composeIdentityResolvers,qa as composeWorker,_s as createLunoraHandler,qt as createWorker,Rs as defineRpcEnvelope,Ga as probeRelayCount,Xa as resolveLunoraOptions,Ts as routeIdentityResolvers,bs as withFrameworkWorker};
|