@lunora/runtime 1.0.0-alpha.55 → 1.0.0-alpha.57

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.
Files changed (22) hide show
  1. package/dist/index.d.mts +66 -30
  2. package/dist/index.d.ts +66 -30
  3. package/dist/index.mjs +1 -1
  4. package/dist/packem_shared/{DEFAULT_REGISTRY_CACHE_TTL_MS-CXdcx3iw.mjs → DEFAULT_REGISTRY_CACHE_TTL_MS-CCDyswsf.mjs} +1 -1
  5. package/dist/packem_shared/{HEALTH_PATH-CmjJOkwf.mjs → HEALTH_PATH-BuLCcWNS.mjs} +1 -1
  6. package/dist/packem_shared/{LOG_ARCHIVE_PATH-5vxNUndx.mjs → LOG_ARCHIVE_PATH-CuHKuDCS.mjs} +1 -1
  7. package/dist/packem_shared/{LunoraError-C08OP5Uq.mjs → LunoraError-ByasbDmd.mjs} +1 -1
  8. package/dist/packem_shared/applyJurisdiction-Dsm_m5zW.mjs +1 -0
  9. package/dist/packem_shared/{argsFromQuery-Cp8uiYaU.mjs → argsFromQuery-nMGzM5bK.mjs} +1 -1
  10. package/dist/packem_shared/{composeIdentityResolvers-DlBbYmBJ.mjs → composeIdentityResolvers-DwE0Jbww.mjs} +1 -1
  11. package/dist/packem_shared/composeWorker-DxXwbTng.mjs +6 -0
  12. package/dist/packem_shared/createCrossShardRelationCapabilities-CQfrCIWR.mjs +1 -0
  13. package/dist/packem_shared/{createQueryCoordinator-NT5oasVP.mjs → createQueryCoordinator-BkPfcxUG.mjs} +1 -1
  14. package/dist/packem_shared/{createShardClient-D4mXb3vL.mjs → createShardClient-BYYzDbMc.mjs} +1 -1
  15. package/dist/packem_shared/{decorateResponse-C6TZSzID.mjs → decorateResponse-DBIWsRSZ.mjs} +1 -1
  16. package/dist/packem_shared/{method-guard-CfF0J5OT.mjs → method-guard-rzvo19pa.mjs} +1 -1
  17. package/dist/packem_shared/{rest-routes--GsO-U9C.mjs → rest-routes-BqldHiaH.mjs} +1 -1
  18. package/package.json +3 -3
  19. package/dist/packem_shared/GET_AUTH_AUDIT_LOG_OP-CS_7Hcs1.mjs +0 -1
  20. package/dist/packem_shared/applyJurisdiction-8bzZjAPR.mjs +0 -1
  21. package/dist/packem_shared/composeWorker-DCZ854Rw.mjs +0 -6
  22. package/dist/packem_shared/createCrossShardRelationCapabilities-BokiysHJ.mjs +0 -1
@@ -1,6 +0,0 @@
1
- import{isLunoraError as lr,toErrorBody as hr}from"@lunora/errors";import{d as bt}from"./evict-oldest-C2XU6HBR.mjs";import{NOOP_EXECUTION_CONTEXT as pr}from"./NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{f as fr,u as mr}from"./identity-header-pdXOyDU4.mjs";import{O as Te,m as wr,A as gr,R as yr,d as br,i as Er,s as Rr}from"./otlp-resource-B-ByO9qo.mjs";import{h as ee,f as ye,i as Et,E as _r,w as Rt,e as _t,b as Sr}from"./rest-routes--GsO-U9C.mjs";import{LunoraError as c,toErrorResponse as Je}from"./LunoraError-C08OP5Uq.mjs";import{GET_AUTH_AUDIT_LOG_OP as Or,buildGetAuthAuditLog as Tr}from"./GET_AUTH_AUDIT_LOG_OP-CS_7Hcs1.mjs";import{runExportTap as Ar}from"./createKvCursorStore-C24tEuYk.mjs";import{t as we,r as L}from"./method-guard-CfF0J5OT.mjs";import{buildHealthRoutes as vr,durableObjectProbe as kr,d1Probe as Ir,presenceProbe as Ne}from"./HEALTH_PATH-CmjJOkwf.mjs";import{wrapResolverWithContract as Dr}from"./composeIdentityResolvers-DlBbYmBJ.mjs";import{composeIdentityResolvers as Co,routeIdentityResolvers as xo}from"./composeIdentityResolvers-DlBbYmBJ.mjs";import{buildLogArchiveAdminRoutes as Pr}from"./LOG_ARCHIVE_PATH-5vxNUndx.mjs";import{o as Ur,f as Ve,a as ce}from"./observability-DWlkDJJw.mjs";import{resolveShard as Ae,applyJurisdiction as Ye}from"./applyJurisdiction-8bzZjAPR.mjs";import{resolveSecurity as Xe,handleCorsPreflight as Nr,enforceOrigin as qr,decorateResponse as qe,enforceWebSocketOrigin as Ze}from"./decorateResponse-C6TZSzID.mjs";const Cr=e=>{const t=e??{};if(typeof t.bucket=="function")return t;const r={...t,bucketName:"default"};return r.bucket=()=>r,r},St="__lunoraBranch",xr=e=>typeof e=="object"&&e!==null&&Object.hasOwn(e,St),jr=`may not contain the reserved workflow branch-marker key ("${St}")`,Ge=(e,t)=>{const r=Math.max(e.length,t.length);let n=e.length^t.length;for(let o=0;o<r;o+=1){const d=o<e.length?e.charCodeAt(o):0,l=o<t.length?t.charCodeAt(o):0;n|=d^l}return n===0},Fe=new TextEncoder,Br=Array.from({length:32},(e,t)=>t);new RegExp(`[${Br.map(e=>String.fromCodePoint(e)).join("")}]`,"u");const $r=e=>{const t=String.fromCodePoint(...e);return btoa(t).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")},Lr=e=>{const t=e.replaceAll("-","+").replaceAll("_","/")+"===".slice((e.length+3)%4),r=atob(t),n=new Uint8Array(r.length);for(let o=0;o<r.length;o+=1)n[o]=r.codePointAt(o)??0;return n},Kr=64,Ce=new Map,Ot=async e=>{const t=Ce.get(e);if(t)return t;bt(Ce,Kr);const r=crypto.subtle.importKey("raw",Fe.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]);return Ce.set(e,r),r},Tt=async(e,t)=>{const r=await Ot(e),n=await crypto.subtle.sign("HMAC",r,Fe.encode(t));return $r(new Uint8Array(n))},Gr=async(e,t,r)=>{const n=await Ot(e);return crypto.subtle.verify("HMAC",n,r,Fe.encode(t))},Fr="::relay::",Qr=(e,t)=>`${e}${Fr}${String(t)}`,At="v1",Mr=6e4,zr=async(e,t={})=>{const r=(t.now??Date.now())+(t.ttlMs??Mr),n=`${At}.${String(r)}`,o=await Tt(e,n);return{expiresAtMs:r,token:`${n}.${o}`}},Wr=async(e,t,r=Date.now())=>{if(e.length===0||t.length===0)return!1;const n=t.split(".");if(n.length!==3)return!1;const[o,d,l]=n;if(o!==At||l.length===0)return!1;const h=Number(d);if(!Number.isFinite(h)||h<=r)return!1;let w;try{w=Lr(l)}catch{return!1}return Gr(e,`${o}.${d}`,w)},D="/_lunora/admin/auth",Hr={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},U=(e,t)=>{const r=e[t];if(typeof r!="string"||r==="")throw new c(`\`${t}\` is required`,{code:"BAD_REQUEST",status:400});return r},le=(e,t)=>{const r=e(t);if(r===void 0)throw new c(`\`${t}\` query parameter is required`,{code:"BAD_REQUEST",status:400});return r},vt=e=>{if(typeof e=="string"||Array.isArray(e)&&e.every(t=>typeof t=="string"))return e},te=(e,t)=>typeof e[t]=="string"?e[t]:void 0,xe=(e,t)=>{const r=e[t];return typeof r=="object"&&r!==null&&!Array.isArray(r)?r:void 0},et=e=>{const t=vt(e.role);if(t===void 0||typeof t=="string"&&t.trim()==="")throw new c("`role` is required",{code:"BAD_REQUEST",status:400});return t},tt=e=>{const t=e.permission;if(typeof t!="object"||t===null||Array.isArray(t))throw new c("`permission` object is required",{code:"BAD_REQUEST",status:400});const r={};for(const[n,o]of Object.entries(t))Array.isArray(o)&&o.every(d=>typeof d=="string")&&(r[n]=o);return r},Jr={[`${D}/capabilities`]:{build:()=>({}),http:"GET",method:"capabilities"},[`${D}/users`]:{build:({paging:e,query:t})=>{const r=t("sortDirection");return{...e,filterField:t("filterField"),filterValue:t("filterValue"),search:t("search"),searchField:t("searchField"),sortBy:t("sortBy"),sortDirection:r==="asc"||r==="desc"?r:void 0}},http:"GET",method:"listUsers"},[`${D}/sessions`]:{build:({paging:e,query:t})=>({...e,userId:t("userId")}),http:"GET",method:"listSessions"},[`${D}/accounts`]:{build:({query:e})=>({userId:le(e,"userId")}),http:"GET",method:"listAccounts"},[`${D}/passkeys`]:{build:({query:e})=>({userId:le(e,"userId")}),http:"GET",method:"listPasskeys"},[`${D}/organizations`]:{build:({paging:e})=>({...e}),http:"GET",method:"listOrganizations"},[`${D}/organizations/members`]:{build:({paging:e,query:t})=>({...e,organizationId:le(t,"organizationId")}),http:"GET",method:"listMembers"},[`${D}/organizations/invitations`]:{build:({paging:e,query:t})=>({...e,organizationId:le(t,"organizationId")}),http:"GET",method:"listInvitations"},[`${D}/config`]:{build:()=>({}),http:"GET",method:"config"},[`${D}/organizations/teams`]:{build:({paging:e,query:t})=>({...e,organizationId:le(t,"organizationId")}),http:"GET",method:"listTeams"},[`${D}/organizations/teams/members`]:{build:({paging:e,query:t})=>({...e,teamId:le(t,"teamId")}),http:"GET",method:"listTeamMembers"},[`${D}/organizations/roles`]:{build:({paging:e,query:t})=>({...e,organizationId:le(t,"organizationId")}),http:"GET",method:"listOrgRoles"},[`${D}/users/create`]:{build:({body:e})=>({data:xe(e,"data"),email:U(e,"email"),name:U(e,"name"),password:te(e,"password"),role:vt(e.role)}),http:"POST",method:"createUser"},[`${D}/users/update`]:{build:({body:e})=>{const{data:t}=e;if(typeof t!="object"||t===null||Array.isArray(t))throw new c("`data` object is required",{code:"BAD_REQUEST",status:400});return{data:t,userId:U(e,"userId")}},http:"POST",method:"updateUser"},[`${D}/users/role`]:{build:({body:e})=>({role:et(e),userId:U(e,"userId")}),http:"POST",method:"setRole"},[`${D}/users/ban`]:{build:({body:e})=>({expiresInSeconds:typeof e.expiresInSeconds=="number"?e.expiresInSeconds:void 0,reason:te(e,"reason"),userId:U(e,"userId")}),http:"POST",method:"banUser"},[`${D}/users/unban`]:{build:({body:e})=>({userId:U(e,"userId")}),http:"POST",method:"unbanUser"},[`${D}/users/password`]:{build:({body:e})=>({newPassword:U(e,"newPassword"),userId:U(e,"userId")}),http:"POST",method:"setUserPassword",returns:"void"},[`${D}/users/remove`]:{build:({body:e})=>({userId:U(e,"userId")}),http:"POST",method:"removeUser",returns:"void"},[`${D}/users/impersonate`]:{build:({body:e})=>({userId:U(e,"userId")}),http:"POST",method:"impersonateUser"},[`${D}/sessions/revoke`]:{build:({body:e})=>({sessionId:U(e,"sessionId")}),http:"POST",method:"revokeUserSession",returns:"void"},[`${D}/sessions/revoke-all`]:{build:({body:e})=>({userId:U(e,"userId")}),http:"POST",method:"revokeUserSessions",returns:"void"},[`${D}/accounts/unlink`]:{build:({body:e})=>({accountId:U(e,"accountId"),userId:U(e,"userId")}),http:"POST",method:"unlinkAccount",returns:"void"},[`${D}/two-factor/disable`]:{build:({body:e})=>({userId:U(e,"userId")}),http:"POST",method:"disableTwoFactor",returns:"void"},[`${D}/passkeys/delete`]:{build:({body:e})=>({passkeyId:U(e,"passkeyId")}),http:"POST",method:"deletePasskey",returns:"void"},[`${D}/organizations/members/remove`]:{build:({body:e})=>({memberId:U(e,"memberId")}),http:"POST",method:"removeMember",returns:"void"},[`${D}/organizations/invitations/cancel`]:{build:({body:e})=>({invitationId:U(e,"invitationId")}),http:"POST",method:"cancelInvitation",returns:"void"},[`${D}/organizations/create`]:{build:({body:e})=>({logo:te(e,"logo"),metadata:xe(e,"metadata"),name:U(e,"name"),ownerId:te(e,"ownerId"),slug:te(e,"slug")}),http:"POST",method:"createOrganization"},[`${D}/organizations/update`]:{build:({body:e})=>({logo:te(e,"logo"),metadata:xe(e,"metadata"),name:te(e,"name"),organizationId:U(e,"organizationId"),slug:te(e,"slug")}),http:"POST",method:"updateOrganization"},[`${D}/organizations/remove`]:{build:({body:e})=>({organizationId:U(e,"organizationId")}),http:"POST",method:"deleteOrganization",returns:"void"},[`${D}/organizations/members/add`]:{build:({body:e})=>({organizationId:U(e,"organizationId"),role:te(e,"role"),userId:U(e,"userId")}),http:"POST",method:"addMember"},[`${D}/organizations/members/invite`]:{build:({body:e})=>({email:U(e,"email"),inviterId:te(e,"inviterId"),organizationId:U(e,"organizationId"),role:te(e,"role")}),http:"POST",method:"inviteMember"},[`${D}/organizations/members/role`]:{build:({body:e})=>({memberId:U(e,"memberId"),role:et(e)}),http:"POST",method:"updateMemberRole"},[`${D}/organizations/teams/create`]:{build:({body:e})=>({name:U(e,"name"),organizationId:U(e,"organizationId")}),http:"POST",method:"createTeam"},[`${D}/organizations/teams/update`]:{build:({body:e})=>({name:U(e,"name"),teamId:U(e,"teamId")}),http:"POST",method:"updateTeam"},[`${D}/organizations/teams/remove`]:{build:({body:e})=>({teamId:U(e,"teamId")}),http:"POST",method:"removeTeam",returns:"void"},[`${D}/organizations/teams/members/add`]:{build:({body:e})=>({teamId:U(e,"teamId"),userId:U(e,"userId")}),http:"POST",method:"addTeamMember"},[`${D}/organizations/teams/members/remove`]:{build:({body:e})=>({teamMemberId:U(e,"teamMemberId")}),http:"POST",method:"removeTeamMember",returns:"void"},[`${D}/organizations/roles/create`]:{build:({body:e})=>({organizationId:U(e,"organizationId"),permission:tt(e),role:U(e,"role")}),http:"POST",method:"createOrgRole"},[`${D}/organizations/roles/update`]:{build:({body:e})=>({permission:tt(e),roleId:U(e,"roleId")}),http:"POST",method:"updateOrgRole"},[`${D}/organizations/roles/remove`]:{build:({body:e})=>({roleId:U(e,"roleId")}),http:"POST",method:"deleteOrgRole",returns:"void"}},Vr=e=>{const t=async o=>{try{return await o()}catch(d){if(d instanceof c)throw d;const l=d,h=typeof l.code=="string"?l.code:"AUTH_ADMIN_ERROR";throw console.error("[lunora] auth admin operation failed:",d),new c("auth admin operation failed",{code:h,status:Hr[h]??500})}},r=async(o,d)=>{if(e.assertAdmin(o),o.method!==d.http)throw new c(`Auth admin endpoint requires ${d.http}`,{code:"METHOD_NOT_ALLOWED",status:405});const l=e.getAuthAdmin();if(l===void 0)throw new c("auth endpoints require an `authAdmin` on the worker",{code:"AUTH_NOT_CONFIGURED",status:400});const h=l[d.method];if(h===void 0)throw new c(`auth admin does not support \`${d.method}\``,{code:"AUTH_OP_NOT_SUPPORTED",status:400});const w=new URL(o.url),R={body:d.http==="POST"?await e.readJsonBody(o):{},paging:e.parsePaging(o),query:k=>e.queryParameter(w,k)},I=d.build(R),b=await t(()=>h(I));return Response.json(d.returns==="void"?{ok:!0}:b,{headers:{"content-type":"application/json"},status:200})},n={};for(const[o,d]of Object.entries(Jr))n[o]=l=>r(l,d);return n},rt=500,Yr=(e,t,r)=>{if(typeof e!="object"||e===null||Array.isArray(e))throw new c("each batch call must be an object",{code:"BAD_REQUEST",status:400});const n=e;if(typeof n.functionPath!="string")throw new c("each batch call needs a string `functionPath`",{code:"BAD_REQUEST",status:400});if(n.functionPath.startsWith("__lunora_relation__:")||n.functionPath.startsWith("__lunora_admin__"))throw new c("reserved function path cannot be batched",{code:"FORBIDDEN",status:403});if(n.args!==void 0&&(typeof n.args!="object"||n.args===null||Array.isArray(n.args)))throw new c("each batch call `args` must be an object",{code:"BAD_REQUEST",status:400});return{entry:{args:n.args===void 0?{}:n.args,clientId:typeof n.clientId=="string"?n.clientId:void 0,clientSeq:typeof n.clientSeq=="number"?n.clientSeq:void 0,functionPath:n.functionPath,id:typeof n.id=="number"?n.id:t,mutationId:typeof n.mutationId=="string"?n.mutationId:void 0},shardKey:typeof n.shardKey=="string"?n.shardKey:r}},Xr=(e,t)=>{if(e.length>rt)throw new c(`RPC batch exceeds the ${String(rt)}-call limit`,{code:"BAD_REQUEST",status:400});const r=new Map;for(const[n,o]of e.entries()){const{entry:d,shardKey:l}=Yr(o,n,t),h=r.get(l)??[];h.push(d),r.set(l,h)}return r},Zr=new TextEncoder,en=e=>{const t=JSON.stringify(e),r=Zr.encode(t);let n="";for(const o of r)n+=String.fromCodePoint(o);return btoa(n).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")},tn=e=>{const t={g:0,s:{},v:1};if(typeof e!="string"||e.length===0)return t;try{const r=atob(e.replaceAll("-","+").replaceAll("_","/")),n=new Uint8Array(r.length);for(let h=0;h<r.length;h+=1)n[h]=r.codePointAt(h)??0;const o=JSON.parse(new TextDecoder().decode(n)),d=o.s&&typeof o.s=="object"?o.s:{},l={};for(const[h,w]of Object.entries(d))typeof w=="number"&&Number.isFinite(w)&&(l[h]=w);return{g:typeof o.g=="number"&&Number.isFinite(o.g)?o.g:0,s:l,v:1}}catch{return t}},rn=e=>{const t=typeof e.table=="string"?e.table:"",r=typeof e.op=="string"?e.op:"",n=r==="delete"||r==="insert"||r==="update"?r:"upsert",o=typeof e.id=="string"?e.id:void 0;return{doc:(e.doc&&typeof e.doc=="object"?e.doc:void 0)??(o===void 0?{}:{_id:o}),op:n,table:t}},nt=(e,t,r)=>{for(const n of t)e.push(rn(n));return r!==void 0&&t.length>=r},nn="/_lunora/admin/export",an="/_lunora/admin/import",on="/_lunora/admin/sync",sn="/_lunora/admin/connector/sync",cn="/_lunora/admin/apply",dn="/_lunora/admin/export-tap/run",un=new TextEncoder,ln=async e=>{const t=await ye(e,"Export")??{};if(t.tables===void 0)return{tables:void 0};if(!Array.isArray(t.tables))throw new c("Export `tables` must be a string array",{code:"BAD_REQUEST",status:400});const r=[];for(const n of t.tables){if(typeof n!="string"||n.length===0)throw new c("Export `tables` entries must be non-empty strings",{code:"BAD_REQUEST",status:400});r.push(n)}return{tables:r}},je=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):void 0,hn=e=>{const{applyGlobals:t,exportCursorStore:r,exportSinks:n,knownTables:o,queryCoordinator:d,assertAdmin:l,requireAdminOption:h,resolveForwardContext:w,shardDO:R,streamExportRows:I,streamingImport:b,syncGlobals:k}=e,p=async(A,j)=>{const x=we(A,["POST"]);if(x)return x;const F=h(A,d,{code:"BAD_REQUEST",message:"Export endpoint requires a `queryCoordinator` on the worker"}),P=await ln(A),{headers:Q}=await w(A,j),M=new ReadableStream({async pull(B){const K=X=>{B.enqueue(un.encode(`${JSON.stringify(X)}
2
- `))};try{await I(F,Q,P.tables,K),B.close()}catch(X){B.error(X)}}});return new Response(M,{headers:{"content-type":"application/x-ndjson"},status:200})},g=async(A,j)=>{const x=we(A,["POST"]);if(x)return x;const F=h(A,d,{code:"BAD_REQUEST",message:"Sync endpoint requires a `queryCoordinator` on the worker"}),P=await ee(A),Q=typeof P.cursors=="object"&&P.cursors!==null?P.cursors:{},M=typeof P.limit=="number"?P.limit:void 0,B=typeof P.globalCursor=="number"?P.globalCursor:0,K=je(P.tables),{headers:X}=await w(A,j),J=K??o(),ne=await F.orchestrateCdcSync(R,{cursors:Q,headers:X,limit:M,tables:J}),he=k?await k({limit:M,sinceSeq:B}):void 0;return Response.json({global:he,shards:ne.shards},{status:200})},_=async(A,j)=>{const x=we(A,["POST"]);if(x)return x;const F=h(A,d,{code:"BAD_REQUEST",message:"Connector sync endpoint requires a `queryCoordinator` on the worker"}),P=await ee(A),Q=tn(P.cursor),M=typeof P.limit=="number"&&P.limit>0?P.limit:void 0,B=je(P.tables),{headers:K}=await w(A,j),X=B??o(),J=await F.orchestrateCdcSync(R,{cursors:Q.s,headers:K,limit:M,tables:X}),ne=[],he={...Q.s};let ae=!1;for(const se of J.shards)ae=nt(ne,se.changes??[],M)||ae,he[se.shardKey]=se.cursor;let pe=Q.g;if(k){const se=await k({limit:M,sinceSeq:Q.g});ae=nt(ne,se.changes,M)||ae,pe=se.cursor}const be=en({g:pe,s:he,v:1}),ve={changes:ne,hasMore:ae,nextCursor:be};return Response.json(ve,{status:200})},E=async(A,j)=>{const x=we(A,["POST"]);if(x)return x;const F=h(A,d,{code:"BAD_REQUEST",message:"Apply endpoint requires a `queryCoordinator` on the worker"}),P=await ee(A),Q=(Array.isArray(P.batches)?P.batches:[]).map(J=>J).filter(J=>J!==null&&typeof J=="object"&&typeof J.shardKey=="string"&&Array.isArray(J.changes)),M=Array.isArray(P.globalChanges)?P.globalChanges:[],{headers:B}=await w(A,j),K=await F.orchestrateApplyCdc(R,{batches:Q,headers:B}),X=M.length>0&&t?await t({changes:M}):0;return Response.json({applied:K.applied+X,failed:K.failed,ok:K.ok},{status:200})},T=async(A,j)=>{const x=we(A,["POST"]);if(x)return x;l(A);const{headers:F}=await w(A,j),P=await b(A,F);return Response.json(P,{headers:{"content-type":"application/json"},status:200})},N=async(A,j)=>{const x=we(A,["POST"]);if(x)return x;const F=h(A,d,{code:"BAD_REQUEST",message:"Export-tap endpoint requires a `queryCoordinator` on the worker"});if(n===void 0||Object.keys(n).length===0||r===void 0)throw new c("Export-tap endpoint requires `exportSinks` + `exportCursorStore` on the worker",{code:"EXPORT_TAP_NOT_CONFIGURED",status:400});const P=await ee(A),Q=typeof P.sink=="string"?P.sink:void 0,M=typeof P.limit=="number"&&P.limit>0?P.limit:void 0,B=je(P.tables);if(Q===void 0)throw new c("Export-tap `sink` must name a configured sink",{code:"BAD_REQUEST",status:400});const K=n[Q];if(K===void 0)throw new c(`Export-tap sink "${Q}" is not configured`,{code:"NOT_FOUND",status:404});const{headers:X}=await w(A,j),J=B??o(),ne=await Ar({coordinator:F,cursorStore:r,headers:X,limit:M,shardDO:R,sink:K,tables:J});return Response.json(ne,{headers:{"content-type":"application/json"},status:200})};return{[cn]:E,[sn]:_,[nn]:p,[dn]:N,[an]:T,[on]:g}},pn=(e,t)=>{const r=[],n=[];if(t&&t.length>0)for(const o of t)e.resolveTableSharding?.(o)?.mode.kind==="global"?n.push(o):r.push(o);return{globalTables:n,shardLocalTables:r}},fn=async(e,t,r,n,o,d)=>{if(r!==void 0&&n.length===0)return;const l=await e.orchestrateExport(d,{args:{tables:n},headers:t,tables:n});for(const h of l.shards)if(!h.error)for(const w of h.rows??[])o(w)},at=async(e,t,r,n,o,d)=>{const{globalTables:l,shardLocalTables:h}=pn(e,n);await fn(t,r,n,h,o,d);const w=e.exportGlobals;if((n===void 0||l.length>0)&&w)for await(const R of w({tables:l}))o(R)},mn=(e,t)=>{let r;try{r=JSON.parse(e)}catch{return{error:{code:"BAD_ROW",line:t,message:"line is not valid JSON",table:""},ok:!1}}if(!r||typeof r!="object"||Array.isArray(r))return{error:{code:"BAD_ROW",line:t,message:"row must be a JSON object",table:""},ok:!1};const n=r;return typeof n.table!="string"||n.table.length===0?{error:{code:"BAD_ROW",line:t,message:"row is missing `table`",table:""},ok:!1}:!n.doc||typeof n.doc!="object"||Array.isArray(n.doc)?{error:{code:"BAD_ROW",line:t,message:"row is missing or malformed `doc`",table:n.table},ok:!1}:{doc:n.doc,ok:!0,table:n.table}},wn=(e,t,r,n,o)=>{if(r?.mode.kind==="shardBy"&&typeof r.mode.field=="string"){const d=e[r.mode.field];return d==null?{error:{code:"BAD_ROW",line:o,message:`row missing shard field "${r.mode.field}" for table "${t}"`,table:t},ok:!1}:{ok:!0,shardKey:typeof d=="string"?d:JSON.stringify(d)}}return{ok:!0,shardKey:n}},gn=async(e,t,r)=>{if(!e.body)throw new c("Import endpoint requires a request body",{code:"BAD_REQUEST",status:400});const n=[],o=[],d=new Map;let l=0,h=0;const w=e.body.getReader(),R=new TextDecoder;let I="",b=0;const k=p=>{h+=1;const g=p.trim();if(g.length===0)return;l+=1;const _=mn(g,h);if(!_.ok){n.push(_.error);return}const{doc:E,table:T}=_,N=t.resolveTableSharding?.(T);if(N?.mode.kind==="global"){o.push({doc:E,line:h,table:T});return}const A=wn(E,T,N,r,h);if(!A.ok){n.push(A.error);return}const j=d.get(A.shardKey);j?j.rows.push({doc:E,table:T}):d.set(A.shardKey,{rows:[{doc:E,table:T}],shardKey:A.shardKey,startLine:h})};for(;;){const{done:p,value:g}=await w.read();if(p)break;if(g&&(b+=g.byteLength,b>Et))throw await w.cancel().catch(()=>{}),new c("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});I+=R.decode(g,{stream:!0});let _=I.indexOf(`
3
- `);for(;_!==-1;){const E=I.slice(0,_);I=I.slice(_+1),k(E),_=I.indexOf(`
4
- `)}}return I.length>0&&k(I),{errors:n,globalRows:o,perShard:d,received:l}},ot=(e,t)=>{for(const[r,n]of Object.entries(t.inserted))e.inserted[r]=(e.inserted[r]??0)+n;for(const r of t.errors)e.errors.push({...r});e.conflicts+=t.conflicts},yn=async(e,t,r,n)=>{const o=t.defaultShardKey??"__root__",{errors:d,globalRows:l,perShard:h,received:w}=await gn(e,t,o),R={conflicts:0,errors:d,inserted:{}},I=[];if(t.resolveTableSharding===void 0&&h.size>0&&I.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 b=t.queryCoordinator;if(!b)throw new c("Import endpoint requires a `queryCoordinator` on the worker",{code:"BAD_REQUEST",status:400});const k=await b.orchestrateImport(n,{batches:[...h.values()],headers:r});ot(R,k)}if(l.length>0)if(t.importGlobals){const b=l[0]?.line??1,k=await t.importGlobals({rows:l,startLine:b});ot(R,k)}else for(const b of l)R.errors.push({code:"GLOBAL_NOT_CONFIGURED",line:b.line,message:`row targets global table "${b.table}" but no \`importGlobals\` is configured`,table:b.table});return{conflicts:R.conflicts,errors:R.errors,inserted:R.inserted,received:w,...I.length>0?{warnings:I}:{}}},Be=e=>typeof e=="object"&&e!==null?e:{},$e=e=>typeof e.kind=="string"?e.kind:"unknown",bn=(e,t)=>{let r=Be(t),n=!1;$e(r)==="optional"&&(n=!0,r=Be(r._meta?.inner));const o=$e(r),d=r._meta??{},l={kind:o,name:e,optional:n};if(o==="id"&&typeof d.tableName=="string"&&(l.table=d.tableName),o==="array"){const h=$e(Be(d.inner));h!=="unknown"&&(l.element=h)}return l},En=e=>typeof e!="object"||e===null?[]:Object.entries(e).map(([t,r])=>bn(t,r)).toSorted((t,r)=>t.name.localeCompare(r.name)),Rn="/_lunora/admin/functions",_n="/_lunora/admin/cron-jobs",Sn="/_lunora/admin/openapi",On="/_lunora/admin/openrpc",Tn="/_lunora/admin/global/tables",An="/_lunora/admin/global/table",vn="/_lunora/admin/global/facet",st=e=>{if(e===void 0||e==="")return;let t;try{t=JSON.parse(e)}catch{return}if(!Array.isArray(t))return;const r=t.flatMap(n=>{if(typeof n!="object"||n===null||typeof n.column!="string")return[];const{column:o,value:d}=n;return[{column:o,value:d}]});return r.length===0?void 0:r},kn=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:{}}),In=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"}),Dn=e=>{const{assertAdmin:t,options:r,parsePaging:n,queryParameter:o,requireAdminOption:d}=e,l=p=>{L(p,"GET","Functions");const g=d(p,r.functions,{code:"FUNCTIONS_NOT_CONFIGURED",message:"functions endpoint requires a `functions` registry on the worker"}),_=Object.entries(g).flatMap(([E,T])=>T.visibility==="internal"||T.kind==="stream"?[]:[{args:En(T.args),kind:T.kind,path:E}]).toSorted((E,T)=>E.path.localeCompare(T.path));return Response.json({functions:_},{headers:{"content-type":"application/json"},status:200})},h=p=>{L(p,"GET","Cron-jobs");const g=d(p,r.cronJobs,{code:"CRON_JOBS_NOT_CONFIGURED",message:"cron-jobs endpoint requires a `cronJobs` map on the worker"}),_=Object.entries(g).flatMap(([E,T])=>T.map(N=>({args:N.args,cron:E,functionPath:N.functionPath,name:N.name,shardKey:N.shardKey,workflow:N.workflow}))).toSorted((E,T)=>E.name.localeCompare(T.name));return Response.json({jobs:_},{headers:{"content-type":"application/json"},status:200})},w=p=>(L(p,"GET","OpenAPI"),t(p),Response.json(r.openApiSpec??kn,{headers:{"content-type":"application/json"},status:200})),R=p=>(L(p,"GET","OpenRPC"),t(p),Response.json(r.openRpcSpec??In,{headers:{"content-type":"application/json"},status:200})),I=async p=>{L(p,"GET","Global-tables");const g=d(p,r.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"});return Response.json(await g.listTables(),{headers:{"content-type":"application/json"},status:200})},b=async p=>{L(p,"GET","Global-table");const g=d(p,r.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),_=new URL(p.url),E=o(_,"table");if(E===void 0)throw new c("Global-table endpoint requires a `table` query param",{code:"BAD_REQUEST",status:400});const T=await g.readTablePage({...n(p),filters:st(o(_,"filters")),table:E});return Response.json(T,{headers:{"content-type":"application/json"},status:200})},k=async p=>{L(p,"GET","Global-facet");const g=d(p,r.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),_=new URL(p.url),E=o(_,"table"),T=o(_,"column");if(E===void 0||T===void 0)throw new c("Global-facet endpoint requires `table` and `column` query params",{code:"BAD_REQUEST",status:400});const N=o(_,"limit"),A=N===void 0?void 0:Number(N),j=await g.facetColumn({column:T,filters:st(o(_,"filters")),limit:A!==void 0&&Number.isFinite(A)?A:void 0,table:E});return Response.json(j,{headers:{"content-type":"application/json"},status:200})};return{[_n]:h,[Rn]:l,[vn]:k,[An]:b,[Tn]:I,[Sn]:w,[On]:R}},Pn="/_lunora/admin/kv/namespaces",Un="/_lunora/admin/kv/keys",kt="/_lunora/admin/kv/value",It=32*1048576,it=60,Nn=e=>{const{readJsonBody:t,requireAdminOption:r}=e,n=b=>r(b,e.kvIntrospector,{code:"KV_NOT_CONFIGURED",message:"KV endpoints require a `kvIntrospector` on the worker"}),o=b=>Response.json(b,{headers:{"content-type":"application/json"},status:200}),d=(b,k)=>{const p=new URL(b.url),g=p.searchParams.get("namespace")??"",_=p.searchParams.get("key")??"";if(g==="")throw new c(`KV-value ${k} request requires a \`namespace\` query parameter`,{code:"BAD_REQUEST",status:400});if(_==="")throw new c(`KV-value ${k} request requires a \`key\` query parameter`,{code:"BAD_REQUEST",status:400});return{key:_,namespace:g}},l=async(b,k)=>{if(!(await b.listNamespaces()).some(p=>p.binding===k))throw new c(`Unknown KV namespace binding \`${k}\``,{code:"NOT_FOUND",status:404})},h=async b=>(L(b,"GET","KV-namespaces"),o({namespaces:await n(b).listNamespaces()})),w=async b=>{L(b,"GET","KV-keys");const k=n(b),p=new URL(b.url),g=p.searchParams.get("namespace")??"";if(g==="")throw new c("KV-keys request requires a `namespace` query parameter",{code:"BAD_REQUEST",status:400});const _=p.searchParams.get("prefix")??void 0,E=p.searchParams.get("cursor")??void 0,T=p.searchParams.get("limit"),N=T===null?void 0:Number.parseInt(T,10);if(N!==void 0&&(!Number.isInteger(N)||N<1))throw new c("KV-keys `limit` must be a positive integer",{code:"BAD_REQUEST",status:400});const A=N===void 0?void 0:Math.min(N,1e3);return await l(k,g),o(await k.listKeys({cursor:E,limit:A,namespace:g,prefix:_}))},R={DELETE:async b=>{const k=n(b),p=d(b,"DELETE");return await l(k,p.namespace),await k.deleteKey(p),o({deleted:!0})},GET:async b=>{const k=n(b),p=d(b,"GET");return await l(k,p.namespace),o(await k.getValue(p))},PUT:async b=>{const k=n(b),p=await t(b,It);if(typeof p.namespace!="string"||p.namespace==="")throw new c("KV-value PUT request requires a `namespace` string",{code:"BAD_REQUEST",status:400});if(typeof p.key!="string"||p.key==="")throw new c("KV-value PUT request requires a `key` string",{code:"BAD_REQUEST",status:400});if(typeof p.value!="string")throw new c("KV-value PUT request requires a `value` string",{code:"BAD_REQUEST",status:400});if(p.expirationTtl!==void 0&&(typeof p.expirationTtl!="number"||!Number.isInteger(p.expirationTtl)||p.expirationTtl<it))throw new c("KV-value PUT `expirationTtl` must be an integer ≥ 60",{code:"BAD_REQUEST",status:400});const g=Math.floor(Date.now()/1e3)+it;if(p.expiration!==void 0&&(typeof p.expiration!="number"||!Number.isInteger(p.expiration)||p.expiration<g))throw new c("KV-value PUT `expiration` must be a Unix-seconds timestamp at least 60 seconds in the future",{code:"BAD_REQUEST",status:400});return await l(k,p.namespace),await k.putValue({expiration:p.expiration,expirationTtl:p.expirationTtl,key:p.key,metadata:p.metadata,namespace:p.namespace,value:p.value}),o({ok:!0})}},I=b=>{const k=R[b.method];if(!k)throw new c("KV-value endpoint requires GET, PUT, or DELETE",{code:"METHOD_NOT_ALLOWED",status:405});return k(b)};return{[Pn]:h,[Un]:w,[kt]:I}},qn="/_lunora/migrate",Cn="/_lunora/admin/pitr",xn="/_lunora/admin/rank",jn="/_lunora/admin/rankpage",Bn="/_lunora/admin/shard-traffic",$n=new Set(["__lunora_admin__:migrationStatus","__lunora_admin__:runMigration"]),Ln=new Set(["__lunora_admin__:getPitrBookmark","__lunora_admin__:pitrRestore"]),Kn=async e=>{const t=await ye(e,"Migration")??{};if(typeof t.table!="string"||t.table.length===0)throw new c("Migration request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof t.functionPath!="string"||!$n.has(t.functionPath))throw new c("Migration request `functionPath` must be a migration admin op",{code:"BAD_REQUEST",status:400});return{args:t.args??{},functionPath:t.functionPath,table:t.table}},Gn=async e=>{const t=await ye(e,"Rank")??{};if(typeof t.table!="string"||t.table.length===0)throw new c("Rank request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof t.index!="string"||t.index.length===0)throw new c("Rank request is missing `index`",{code:"BAD_REQUEST",status:400});if(typeof t.partitionKey!="string")throw new c("Rank request `partitionKey` must be a string",{code:"BAD_REQUEST",status:400});if(typeof t.rowId!="string"||t.rowId.length===0)throw new c("Rank request is missing `rowId`",{code:"BAD_REQUEST",status:400});if(!Array.isArray(t.sortValues))throw new c("Rank request `sortValues` must be an array",{code:"BAD_REQUEST",status:400});return{index:t.index,partitionKey:t.partitionKey,rowId:t.rowId,sortValues:t.sortValues,table:t.table}},Fn=e=>{if(e!==void 0){if(!Array.isArray(e)||e.some(t=>t!=="asc"&&t!=="desc"))throw new c('Rank page request `directions` must be an array of "asc"|"desc"',{code:"BAD_REQUEST",status:400});return e}},Qn=e=>{if(typeof e.table!="string"||e.table.length===0)throw new c("Rank page request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof e.index!="string"||e.index.length===0)throw new c("Rank page request is missing `index`",{code:"BAD_REQUEST",status:400});if(e.partitionKey!==void 0&&typeof e.partitionKey!="string")throw new c("Rank page request `partitionKey` must be a string",{code:"BAD_REQUEST",status:400});if(e.take!==void 0&&(typeof e.take!="number"||!Number.isFinite(e.take)))throw new c("Rank page request `take` must be a number",{code:"BAD_REQUEST",status:400});if(e.cursor!==void 0&&e.cursor!==null&&typeof e.cursor!="string")throw new c("Rank page request `cursor` must be a string or null",{code:"BAD_REQUEST",status:400})},Mn=async e=>{const t=await ye(e,"Rank page")??{};Qn(t);const r=Fn(t.directions);return{cursor:typeof t.cursor=="string"?t.cursor:null,directions:r,index:t.index,partitionKey:typeof t.partitionKey=="string"?t.partitionKey:void 0,table:t.table,take:typeof t.take=="number"?t.take:void 0}},zn=async e=>{const t=await ye(e,"Shard-traffic")??{};if(typeof t.table!="string"||t.table.length===0)throw new c("Shard-traffic request is missing `table`",{code:"BAD_REQUEST",status:400});return{table:t.table}},Wn=async e=>{const t=await ee(e);if(typeof t.functionPath!="string"||!Ln.has(t.functionPath))throw new c("PITR request `functionPath` must be a PITR admin op",{code:"BAD_REQUEST",status:400});if(t.shardKey!==void 0&&typeof t.shardKey!="string")throw new c("PITR `shardKey` must be a string",{code:"BAD_REQUEST",status:400});return{args:t.args??{},functionPath:t.functionPath,shardKey:t.shardKey}},Hn=e=>{const{defaultShard:t,forwardToShard:r,isAdmin:n,queryCoordinator:o,resolveForwardContext:d,shardDO:l}=e,h=(p,g)=>{if(p.method!=="POST")throw new c(`${g} endpoint requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});if(!n(p))throw new c("Admin auth required",{code:"FORBIDDEN",status:403});if(!o)throw new c(`${g} endpoint requires a \`queryCoordinator\` on the worker`,{code:"BAD_REQUEST",status:400});return o},w=async(p,g)=>{const _=h(p,"Migration"),E=await Kn(p),{headers:T}=await d(p,g),N=await _.orchestrateMigration(l,{args:E.args,functionPath:E.functionPath,headers:T,table:E.table});return Response.json(N,{headers:{"content-type":"application/json"},status:200})},R=async(p,g)=>{const _=h(p,"Rank"),E=await Gn(p),{headers:T}=await d(p,g),N=await _.orchestrateRank(l,{headers:T,index:E.index,partitionKey:E.partitionKey,rowId:E.rowId,sortValues:E.sortValues,table:E.table});return Response.json(N,{headers:{"content-type":"application/json"},status:200})},I=async(p,g)=>{const _=h(p,"Rank page"),E=await Mn(p),{headers:T}=await d(p,g),N=await _.orchestrateRankPage(l,{...E,headers:T});return Response.json(N,{headers:{"content-type":"application/json"},status:200})},b=async(p,g)=>{const _=h(p,"Shard-traffic"),E=await zn(p),{headers:T}=await d(p,g),N=await _.orchestrateShardTraffic(l,{headers:T,table:E.table});return Response.json(N,{headers:{"content-type":"application/json"},status:200})},k=async(p,g)=>{if(L(p,"POST","PITR"),!n(p))throw new c("admin PITR endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403});const _=await Wn(p),{headers:E}=await d(p,g),T=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:_.args,functionPath:_.functionPath}),headers:E,method:"POST"});return r(l,_.shardKey??t,T)};return{[qn]:w,[Cn]:k,[xn]:R,[jn]:I,[Bn]:b}},Jn=1,Vn=0,Yn=32,Xn=512,Zn=/^[a-z][\d_a-z*/-]{0,255}(?:@[a-z][\d_a-z*/-]{0,13})?=[\u0020-\u002B\u002D-\u003C\u003E-\u007E]{1,256}$/,ea=e=>{if(e==null)return;const t=e.trim();if(t.length===0||t.length>Xn)return;const r=t.split(",");if(!(r.length>Yn)){for(const n of r)if(!Zn.test(n.trim()))return;return t}},ta=e=>{const t=gr(e.headers.get("traceparent"));if(t===void 0)return;const r=ea(e.headers.get("tracestate"));return{parentSpanId:t.parentSpanId,sampled:t.sampled,traceId:t.traceId,...r===void 0?{}:{traceState:r}}},ra=(e,t={})=>{const r=ta(e),n=t.trustInbound===!0?r:void 0,o=Te(8),d=n?.traceId??Te(16),l=Ur(t.sampling,n===void 0?o:d),h=l.isTraced&&(n===void 0||n.sampled);return{decision:l,ignoredUpstream:r!==void 0&&n===void 0,trace:{sampled:h,spanId:o,traceFlags:h?Jn:Vn,traceId:d,...n?.parentSpanId===void 0?{}:{parentSpanId:n.parentSpanId},...n?.traceState===void 0?{}:{traceState:n.traceState}}}},na=(e,t)=>{t.traceparent=wr(e.traceId,e.spanId,e.sampled),e.traceState!==void 0&&(t.tracestate=e.traceState)},aa=(e,t)=>{let r;return()=>{if(r===void 0){const n=Rr(e),o=t===void 0?void 0:t.cf;r=yr(Er(n),br(n,o))}return r}},oa="/_lunora/admin/scheduled",sa="/_lunora/admin/scheduled/status",ia="/_lunora/admin/scheduled/ws",ca="/_lunora/admin/scheduled/cancel",da="/_lunora/admin/scheduled/dead",ua="/_lunora/admin/scheduled/dead/retry",la="/_lunora/admin/scheduled/dead/cancel",ha=e=>{const{checkWsAdmin:t,requireSchedulerNamespace:r,resolveSchedulerStub:n,schedulerInstanceName:o}=e,d=(w,R)=>I=>{if(I.method!=="GET")throw new c(`${R} endpoint requires GET`,{code:"METHOD_NOT_ALLOWED",status:405});return n(I).fetch(new Request(`https://scheduler.internal${w}`,{method:"GET"}))},l=(w,R,I=R)=>async b=>{if(b.method!=="POST")throw new c(`${I} requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});const k=n(b),p=await b.json().catch(()=>{});if(typeof p?.id!="string"||p.id==="")throw new c(`${R} requires a string \`id\``,{code:"BAD_REQUEST",status:400});return k.fetch(new Request(`https://scheduler.internal${w}`,{body:JSON.stringify({id:p.id}),headers:{"content-type":"application/json"},method:"POST"}))},h=async w=>{if(w.headers.get("Upgrade")!=="websocket")throw new c("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});if(!await t(w))throw new c("admin authorization required",{code:"ADMIN_FORBIDDEN",status:403});const R=r();return Ae(R,o).fetch(new Request("https://scheduler.internal/ws",{headers:{Upgrade:"websocket"}}))};return{[ca]:l("/cancel","Scheduled-cancel","Scheduled-cancel endpoint"),[la]:l("/dead/cancel","Scheduled dead-letter action"),[da]:d("/dead","Scheduled dead-letter"),[ua]:l("/dead/retry","Scheduled dead-letter action"),[oa]:d("/list","Scheduled-list"),[sa]:d("/status","Scheduler-status"),[ia]:h}},Dt="/_lunora/admin/storage",pa="/_lunora/admin/storage/url",fa="/_lunora/admin/storage/buckets",ma=10080*60,Pt=32*1048576,wa=new Set(["GET","PUT"]),ga=e=>{const t=new Uint8Array(e);let r="";for(const n of t)r+=n.toString(16).padStart(2,"0");return r},ya=e=>{const{assertAdmin:t,parsePaging:r,queryParameter:n,readBodyBytes:o,requireAdminOption:d,storage:l}=e,h=g=>{const _=n(g,"key");if(_===void 0)throw new c("Storage endpoint requires a `key` query parameter",{code:"BAD_REQUEST",status:400});return _},w=async g=>{const _=d(g,l.storageList,{code:"STORAGE_NOT_CONFIGURED",message:"storage endpoint requires a `storageList` function on the worker"}),E=new URL(g.url),T=await _(n(E,"prefix"),{bucket:n(E,"bucket"),cursor:n(E,"cursor"),...r(g)});return Response.json(T,{headers:{"content-type":"application/json"},status:200})},R=g=>(L(g,"GET","Storage-buckets"),t(g),Response.json({buckets:l.storageBuckets??[]},{headers:{"content-type":"application/json"},status:200})),I=async g=>{const _=d(g,l.storageDelete,{code:"STORAGE_DELETE_NOT_CONFIGURED",message:"storage delete requires a `storageDelete` function on the worker"}),E=new URL(g.url),T=h(E);return await _(T,{bucket:n(E,"bucket")}),Response.json({deleted:!0,key:T},{headers:{"content-type":"application/json"},status:200})},b=async g=>{const _=d(g,l.storageUpload,{code:"STORAGE_UPLOAD_NOT_CONFIGURED",message:"storage upload requires a `storageUpload` function on the worker"}),E=new URL(g.url),T=h(E),N=await o(g,Pt),A=g.headers.get("content-type"),j=A===null||A===""?void 0:A,x=n(E,"expectedSha256"),F=n(E,"expectedSize");let P;if(x!==void 0||F!==void 0){const M=await crypto.subtle.digest("SHA-256",N);P=ga(M);const B=F!==void 0&&N.byteLength!==Number(F),K=x!==void 0&&P!==x.toLowerCase();if(B||K)throw new c("Upload failed verification — the body did not match the declared size or SHA-256 checksum, so nothing was written",{code:"STORAGE_CHECKSUM_MISMATCH",status:400})}const Q=await _(T,N,{bucket:n(E,"bucket"),contentType:j,sha256:P});return Response.json(P===void 0?Q:{...Q,sha256:P},{headers:{"content-type":"application/json"},status:200})},k=async g=>{switch(g.method){case"DELETE":return I(g);case"GET":return w(g);case"POST":case"PUT":return b(g);default:throw new c("Storage endpoint requires GET, PUT, POST, or DELETE",{code:"METHOD_NOT_ALLOWED",status:405})}},p=async g=>{L(g,"GET","Storage URL");const _=d(g,l.storageSignedUrl,{code:"STORAGE_URL_NOT_CONFIGURED",message:"storage URL endpoint requires a `storageSignedUrl` function on the worker"}),E=new URL(g.url),T=h(E),N=Number(n(E,"expiresIn")??""),A=Number.isFinite(N)&&N>0?Math.min(N,ma):void 0,j=n(E,"method");if(j!==void 0&&!wa.has(j))throw new c("Storage URL `method` must be GET or PUT",{code:"BAD_REQUEST",status:400});const x=j,F=n(E,"contentType"),P=await _(T,{bucket:n(E,"bucket"),contentType:F,expiresInSeconds:A,method:x});return Response.json({key:T,url:P},{headers:{"content-type":"application/json"},status:200})};return{[fa]:R,[Dt]:k,[pa]:p}},ba=(e,...t)=>{let r=e.cf;for(const n of t){if(typeof r!="object"||r===null)return;r=r[n]}return typeof r=="string"?r:void 0},ct={mtls:e=>ba(e,"tlsClientAuth","certVerified")==="SUCCESS"},Ea=e=>e===void 0||e===!1?()=>!1:e===!0?()=>!0:typeof e=="function"?e:(Object.hasOwn(ct,e)?ct[e]:void 0)??(()=>!1),Ra=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.'))}},_a="/_lunora/admin/vector/indexes",Sa="/_lunora/admin/vector/query",Oa=e=>{const{readJsonBody:t,requireAdminOption:r}=e,n=async d=>{L(d,"GET","Vector-indexes");const l=r(d,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});return Response.json({indexes:await l.listIndexes()},{headers:{"content-type":"application/json"},status:200})},o=async d=>{L(d,"POST","Vector-query");const l=r(d,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});if(l.queryIndex===void 0)throw new c("vector index querying is not enabled on this worker",{code:"VECTOR_QUERY_UNSUPPORTED",status:400});const h=await t(d);if(typeof h.name!="string"||h.name==="")throw new c("Vector-query request requires a `name` string",{code:"BAD_REQUEST",status:400});if(typeof h.text!="string"||h.text==="")throw new c("Vector-query request requires a `text` string",{code:"BAD_REQUEST",status:400});if(h.topK!==void 0&&(typeof h.topK!="number"||!Number.isInteger(h.topK)||h.topK<1))throw new c("Vector-query `topK` must be a positive integer",{code:"BAD_REQUEST",status:400});const w=await l.queryIndex({name:h.name,text:h.text,topK:h.topK});return Response.json(w,{headers:{"content-type":"application/json"},status:200})};return{[_a]:n,[Sa]:o}},Ta="/_lunora/admin/workflows/instances",Aa="/_lunora/admin/workflows/instance",va="/_lunora/admin/workflows/status",ka={complete:!0,errored:!0,paused:!0,queued:!0,running:!0,terminated:!0,unknown:!0,waiting:!0,waitingForPause:!0},Ia=e=>e!==null&&Object.hasOwn(ka,e)?e:void 0,dt=(e,t)=>{const r=e.searchParams.get(t);if(r===null)return;const n=Number(r);return Number.isInteger(n)&&n>0?n:void 0},Le=(e,t)=>{const r=e.searchParams.get(t);if(r===null||r==="")throw new c(`Workflows admin endpoint requires a \`${t}\` query parameter`,{code:"BAD_REQUEST",status:400});return r},ut=()=>{throw new c("Workflow inspection is unconfigured. Set CLOUDFLARE_ACCOUNT_ID + CLOUDFLARE_API_TOKEN in your .dev.vars to enable it.",{code:"WORKFLOWS_NOT_CONFIGURED",status:501})},Da=e=>{const{assertAdmin:t,resolveWorkflowsClient:r}=e,n=async(l,h,w)=>{L(l,"GET","Workflows instances"),t(l);const R=r(h);if(!R)return Response.json({configured:!1,instances:[],page:1,perPage:0,totalCount:0});const I=Le(w,"name"),b=Ia(w.searchParams.get("status"));return Response.json(await R.listInstances({page:dt(w,"page"),perPage:dt(w,"perPage"),status:b,workflowName:I}))},o=async(l,h,w)=>{L(l,"GET","Workflows instance"),t(l);const R=r(h);return R?Response.json(await R.getInstance({instanceId:Le(w,"id"),workflowName:Le(w,"name")})):ut()},d=async(l,h)=>{L(l,"POST","Workflows status"),t(l);const w=r(h);if(!w)return ut();const R=await l.json().catch(()=>{});if(typeof R?.name!="string"||R.name===""||typeof R.id!="string"||R.id==="")throw new c("Workflows status action requires string `name` and `id`",{code:"BAD_REQUEST",status:400});const{action:I}=R;if(I!=="pause"&&I!=="resume"&&I!=="terminate")throw new c("Workflows status action must be one of: pause, resume, terminate",{code:"BAD_REQUEST",status:400});return Response.json(await w.setInstanceStatus({action:I,instanceId:R.id,workflowName:R.name}))};return{[Aa]:o,[Ta]:n,[va]:d}},Pa={[kt]:It,[Dt]:Pt},Ua=new TextEncoder,lt="/_lunora/rpc",Na="/_lunora/rpc-batch",qa="/_lunora/ws",Re=(e,t,r)=>({resourceAttributes:aa(e,t),...r===void 0?{}:{waitUntil:r}}),ht=e=>e?.waitUntil?{waitUntil:t=>e.waitUntil?.(t)}:{},pt=e=>({spanId:e.spanId,traceFlags:e.traceFlags,traceId:e.traceId,...e.parentSpanId===void 0?{}:{parentSpanId:e.parentSpanId}}),Ke=e=>{const{method:t}=e,r=e.headers.get("user-agent")??void 0;let n;try{n=new URL(e.url)}catch{return{method:t,userAgent:r}}const o=n.port===""?void 0:Number(n.port);return{host:n.hostname,method:t,path:n.pathname,port:Number.isNaN(o)?void 0:o,scheme:n.protocol.replace(":",""),userAgent:r}},ft="/_lunora/voice/",Ca="/_lunora/scheduler/dispatch",xa="/_lunora/admin/cron-jobs/run",ja="/_lunora/admin/ws-token",Ba="/_lunora/admin/",$a="/_lunora/migrate",La="/_lunora/status",Ka=e=>e.startsWith(Ba)||e===$a,Ga=new Set(["1","enabled","on","true","yes"]),Fa=e=>{const t=e.headers.get("x-lunora-userid"),r=e.headers.get("x-lunora-identity");if(!(t===null&&r===null))return{...r===null?{}:{identity:r},...t===null?{}:{userId:t}}},Qa="/api/auth",Ma="__lunora_admin__:recordAuthEvent",za="__lunora_admin__:listPushSubscriptions",Wa=["/sign-in","/sign-up","/callback"],Ha=(e,t)=>{const r=t.endsWith("/")?t.slice(0,-1):t;if(!e.startsWith(`${r}/`))return!1;const n=e.slice(r.length);return Wa.some(o=>n===o||n.startsWith(`${o}/`))},_e=(e,t,r,n)=>{const o=lr(r),d=o?r.code:"INTERNAL_SERVER_ERROR",l=o?r.status:500,h=r instanceof Error?r.message:String(r);return{durationMs:t,error:{code:d,message:h,status:l},functionPath:e,ok:!1,...n.fanOut?{fanOut:{failed:0,shards:0,table:n.fanOut.table}}:{},...n.shardKey?{shardKey:n.shardKey}:{}}},Ja=e=>{const{exp:t,expiresAtMs:r}=e;if(typeof r=="number"&&Number.isFinite(r))return r;if(typeof t=="number"&&Number.isFinite(t))return t*1e3},mt=e=>e.waitUntil?{waitUntil:t=>{e.waitUntil?.(t)}}:void 0,Va=e=>{const t=e?.queue;return typeof t=="string"&&t.length>0?t:"unknown"},de=async(e,t,r)=>{const n={"content-type":"application/json"},o=e.headers.get("authorization"),d=e.headers.get("cookie"),l=e.headers.get("x-d1-bookmark"),h=e.headers.get("x-lunora-mutation-id"),w=e.headers.get("x-lunora-client-id"),R=e.headers.get("x-lunora-client-seq");o&&(n.authorization=o),d&&(n.cookie=d),l&&(n["x-d1-bookmark"]=l),h&&(n["x-lunora-mutation-id"]=h),w&&(n["x-lunora-client-id"]=w),R&&(n["x-lunora-client-seq"]=R);const I=e.headers.get("cf-connecting-ip");if(I&&(n["x-lunora-client-ip"]=I),!r)return{claims:null,headers:n,identity:null,userId:null};const b=await r(e,t);if(!b||typeof b.userId!="string"||b.userId.length===0)return{claims:null,headers:n,identity:null,userId:null};n["x-lunora-userid"]=fr(b.userId);const k=Ja(b);k!==void 0&&(n["x-lunora-identity-exp"]=String(k));const{userId:p,...g}=b,_=Object.keys(g).length>0?g:null;return _&&(n["x-lunora-identity"]=mr(_)),{claims:_,headers:n,identity:b,userId:p}},Ya=new Set(["concat","first","groupBy","max","min","rank","sum","topK"]),Xa=e=>{if(e===void 0)return;if(!e||typeof e!="object")throw new c("RPC `fanOut` must be an object",{code:"BAD_REQUEST",status:400});const t=e;if(typeof t.table!="string"||t.table.length===0)throw new c("RPC `fanOut.table` must be a non-empty string",{code:"BAD_REQUEST",status:400});if(!t.merge||typeof t.merge!="object")throw new c("RPC `fanOut.merge` must be an object",{code:"BAD_REQUEST",status:400});const r=t.merge;if(typeof r.kind!="string"||!Ya.has(r.kind))throw new c("RPC `fanOut.merge.kind` is not a recognized merge strategy",{code:"BAD_REQUEST",status:400});if(r.kind==="topK"){if(typeof r.k!="number"||!Number.isInteger(r.k)||r.k<0)throw new c("RPC `fanOut.merge.k` must be a non-negative integer",{code:"BAD_REQUEST",status:400});if(typeof r.by!="string"||r.by.length===0)throw new c("RPC `fanOut.merge.by` must be a non-empty string",{code:"BAD_REQUEST",status:400})}return t},Za=(e,t)=>{e?.LUNORA_DEBUG_RPC&&console.warn(`[lunora:rpc] ${t.fanOut?"fan-out":`shard=${t.shardKey??"(root)"}`} ${t.functionPath}`)},wt=(e,t)=>{const r=t.functions?.[e.functionPath]?.x402;if(r){if(e.fanOut)throw new c("a paid (`.x402`) function cannot be fanned out",{code:"BAD_REQUEST",status:400});if(!t.x402Charge)throw new c(`function "${e.functionPath}" is marked paid (.x402) but no x402Charge gate is configured on the worker`,{code:"MISCONFIGURED",status:500});return r}},eo=async e=>{const t=await Rt(e);let r;try{r=JSON.parse(t)}catch{throw new c("RPC body must be valid JSON",{code:"BAD_REQUEST",status:400})}if(!r||typeof r!="object"||typeof r.functionPath!="string")throw new c("RPC envelope is missing `functionPath`",{code:"BAD_REQUEST",status:400});const n=r;if(n.args!==void 0&&_t(n.args,"RPC"),n.shardKey!==void 0&&typeof n.shardKey!="string")throw new c("RPC `shardKey` must be a string",{code:"BAD_REQUEST",status:400});const o=r,d=Xa(o.fanOut),l=o.args??{};if(d&&o.functionPath.startsWith("__lunora_relation__:")){const h=l.table;if(typeof h=="string"&&h!==d.table)throw new c("RPC `args.table` must match the authorized `fanOut.table` for a relation fan-out",{code:"BAD_REQUEST",status:400});l.table=d.table}return{args:l,fanOut:d,functionPath:o.functionPath,shardKey:o.shardKey}},oe=async(e,t,r)=>Ae(e,t).fetch(r),Se=new Map,to=5e3,ro=4096,no=async(e,t)=>{const r=Date.now(),n=Se.get(t);if(n!==void 0&&n.expiresMs>r)return n.relayCount;n!==void 0&&Se.delete(t);let o=0;try{const d=await Ae(e,t).fetch(new Request("https://shard.internal/_lunora/route"));if(d.ok){const l=(await d.json()).relayCount;typeof l=="number"&&l>0&&(o=Math.floor(l))}}catch{o=0}return bt(Se,ro),Se.set(t,{expiresMs:r+to,relayCount:o}),o},ao=(e,t)=>{if(!(e===null||typeof e!="object"))return Object.entries(e).find(([,r])=>r===t)?.[0]},Oe=(e,t,r)=>new Request("https://shard.internal/rpc",{body:JSON.stringify({args:t,functionPath:e}),headers:r,method:"POST"}),oo=["x-lunora-userid","x-lunora-identity","x-lunora-identity-exp"],gt=(e,t)=>{for(const r of oo){e.delete(r);const n=t[r];n!==void 0&&e.set(r,n)}},so=async(e,t,r)=>e.length===0||r.length===0?!1:Ge(await Tt(e,t),r),yt=(e,t)=>{if(!t||t.length===0)return!1;const r=e.headers.get("authorization");if(!r)return!1;const[n,...o]=r.split(" ");return n?.toLowerCase()!=="bearer"?!1:Ge(t,o.join(" ").trim())},io=async(e,t,r)=>{if(!t||t.length===0)return!1;const n=new URL(e.url).searchParams.get("token");return n===null?!1:await Wr(t,n)?!0:r?!1:Ge(t,n)},co=(e,t)=>{if(t===null||typeof t!="object"&&typeof t!="function")return;const r=t;if(typeof r.prepare=="function"&&typeof r.batch=="function"&&typeof r.dump=="function")return Ir(`d1:${e}`,t);if(typeof r.list=="function"&&typeof r.head=="function"&&typeof r.createMultipartUpload=="function")return Ne(`r2:${e}`,!0);if(typeof r.send=="function"&&typeof r.sendBatch=="function"&&typeof r.get!="function")return Ne(`queue:${e}`,!0);if(typeof r.connectionString=="string")return Ne(`hyperdrive:${e}`,!0)},Ut=e=>{const t=Ea(e.trustInboundTraceContext),r=Ra(e.trustInboundTraceContext),n=e.defaultShardKey??"__root__",o=Dr(e.resolveIdentity,e.identity),d=Ye(e.shardDO,e.jurisdiction),l=e.schedulerDO===void 0?void 0:Ye(e.schedulerDO,e.jurisdiction);let h;const w=()=>e.adminToken??h;let R;const I=()=>e.requireEphemeralWsToken??R??!1,b=a=>{const s=a??{};if(R===void 0&&e.requireEphemeralWsToken===void 0){const i=s.LUNORA_REQUIRE_EPHEMERAL_WS_TOKEN;typeof i=="string"&&i.length>0&&(R=Ga.has(i.trim().toLowerCase()))}if(h!==void 0||e.adminToken!==void 0)return;const u=s.LUNORA_ADMIN_TOKEN;typeof u=="string"&&u.length>0&&(h=u)},k=new WeakSet,p=a=>yt(a,w())||k.has(a),g=async(a,s)=>{const u=await de(a,s,e.resolveIdentity);if(k.has(a)&&u.headers.authorization===void 0){const i=w();i!==void 0&&(u.headers.authorization=`Bearer ${i}`)}return u};let _=!1;const E=a=>{if(!e.allowUnauthenticatedShardAccess){const s=a==="fan-out"?"authorizeFanOut":"authorizeShard";throw new c(`${a} access is default-denied: configure \`${s}\` on the worker, or set \`allowUnauthenticatedShardAccess: true\` to explicitly allow unauthenticated ${a} access (relying solely on per-row RLS).`,{code:a==="fan-out"?"FORBIDDEN_FANOUT":"FORBIDDEN_SHARD",status:403})}_||(_=!0,console.warn([`[lunora] SECURITY: serving ${a} 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("")))},T=async(a,s,u=!0)=>{if(e.authorizeShard){if(!await e.authorizeShard(a,s))throw new c("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else u&&s!==n&&E("shard")},N=Hn({defaultShard:n,forwardToShard:oe,isAdmin:p,queryCoordinator:e.queryCoordinator,resolveForwardContext:g,shardDO:d}),A=async(a,s,u,i,m)=>{await T(null,u,!1);const y={"content-type":"application/json","x-lunora-system":"1"};return m?.userId!==void 0&&m.userId.length>0&&(y["x-lunora-userid"]=m.userId),m?.identity!==void 0&&m.identity.length>0&&(y["x-lunora-identity"]=m.identity),i!==void 0&&i.length>0&&(y["x-lunora-mutation-id"]=i),oe(d,u,Oe(a,s,y))},j=async(a,s,u,i)=>{const m=u?.[a];if(!m||typeof m.create!="function")throw new c(`${i} targets workflow binding "${a}", which is not bound on env`,{code:"CRON_JOB_FAILED",status:500});if(xr(s))throw new c(`${i} params ${jr}`,{code:"BAD_REQUEST",status:400});await m.create({params:s})},x=async(a,s)=>{if(a.workflow){await j(a.workflow,a.args??{},s,`cron job "${a.name}"`);return}if(a.functionPath===void 0)throw new c(`cron job "${a.name}" has neither a function target nor a workflow target`,{code:"CRON_JOB_FAILED",status:500});const u=await A(a.functionPath,a.args??{},a.shardKey??n);if(!u.ok)throw new c(`cron job "${a.name}" (${a.functionPath}) failed with shard status ${String(u.status)}`,{code:"CRON_JOB_FAILED",status:500})},F=async(a,s,u,i)=>{const m=e.cronJobs?.[a];if(m)for(const y of m)try{await x(y,s)}catch(v){u.push(i(v))}},P=async(a,s)=>{if(!p(a))throw new c("admin endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403});if(L(a,"POST","cron-jobs run"),!e.cronJobs)throw new c("cron-jobs run endpoint requires a `cronJobs` map on the worker",{code:"CRON_JOBS_NOT_CONFIGURED",status:400});const u=await ee(a),i=typeof u.name=="string"?u.name:"";if(i==="")throw new c("cron-jobs run endpoint requires a job `name`",{code:"BAD_REQUEST",status:400});const m=Object.values(e.cronJobs).flat().find(y=>y.name===i);if(!m)throw new c(`no cron job named "${i}" is registered`,{code:"CRON_JOB_NOT_FOUND",status:404});return await x(m,s),Response.json({name:i,ran:!0},{status:200})},Q=async a=>{const s=typeof a.pool=="string"&&a.pool.length>0?a.pool:void 0;if(!s||!l||typeof a.id!="string")return;const u=typeof a.instanceName=="string"&&a.instanceName.length>0?a.instanceName:"default";try{await l.get(l.idFromName(u)).fetch(new Request("https://scheduler.internal/complete",{body:JSON.stringify({id:a.id,pool:s}),headers:{"content-type":"application/json"},method:"POST"}))}catch{}},M=async(a,s)=>{L(a,"POST","Scheduler dispatch");const u=await Rt(a),i=s??{},m=typeof i.LUNORA_SCHEDULER_SECRET=="string"?i.LUNORA_SCHEDULER_SECRET:void 0,y=e.adminToken??(typeof i.LUNORA_ADMIN_TOKEN=="string"?i.LUNORA_ADMIN_TOKEN:void 0),v=a.headers.get("x-lunora-scheduler-signature");let f=!1;if(v&&m?f=await so(m,u,v):y&&(f=yt(a,y)),!f)throw new c("Scheduler dispatch requires a valid signature or admin bearer",{code:"FORBIDDEN",status:403});let S;try{S=JSON.parse(u)}catch{throw new c("Scheduler dispatch body must be valid JSON",{code:"BAD_REQUEST",status:400})}const O=S??{},q=O.args??{};if(typeof O.workflow=="string"&&O.workflow.length>0)return await j(O.workflow,q,s,"scheduled workflow"),Response.json({ok:!0},{status:200});if(typeof O.functionPath!="string"||O.functionPath.length===0)throw new c("Scheduler dispatch is missing `functionPath`",{code:"BAD_REQUEST",status:400});const C=typeof O.shardKey=="string"&&O.shardKey.length>0?O.shardKey:n,$=typeof O.id=="string"&&O.id.length>0?O.id:void 0,V=Fa(a),Z=await A(O.functionPath,q,C,$,V);return await Q(O),Z},B=a=>{if(!p(a))throw new c("admin endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403})},K=(a,s,u)=>{if(B(a),s===void 0)throw new c(u.message,{code:u.code,status:400});return s},X=Tr({assertAdmin:B,getReader:()=>e.authAuditReader}),J=async(a,s)=>{B(a);const u=e.notifySubscriptionStore;if(u===void 0)return Response.json({subscriptions:[]},{headers:{"content-type":"application/json"},status:200});const i=s?.kind,m=s?.userId,y=s?.limit,v=i==="fcm"||i==="web-push"?i:void 0,f=typeof m=="string"&&m!==""?m:void 0,S=typeof y=="number"&&Number.isFinite(y)?Math.trunc(y):0,O=S>0?Math.min(S,1e3):1e3,q=(await u.list({kind:v,limit:O,userId:f})).filter(C=>v!==void 0&&C.kind!==v?!1:f===void 0||(C.userId??null)===f).map(({keys:C,token:$,...V})=>V);return Response.json({subscriptions:q},{headers:{"content-type":"application/json"},status:200})},ne=async(a,s)=>{if(!s.fanOut){if(s.functionPath===Or)return X(a,s.args??{});if(s.functionPath===za)return J(a,s.args)}},he=hn({applyGlobals:e.applyGlobals,assertAdmin:B,exportCursorStore:e.exportCursorStore,exportSinks:e.exportSinks,knownTables:()=>[],queryCoordinator:e.queryCoordinator,requireAdminOption:K,resolveForwardContext:g,shardDO:d,streamExportRows:(a,s,u,i)=>at(e,a,s,u,i,d),streamingImport:(a,s)=>yn(a,e,s,d),syncGlobals:e.syncGlobals}),ae=(a,s)=>{const u=a.searchParams.get(s);return u===null||u===""?void 0:u},pe=a=>{const s=new URL(a.url),u=s.searchParams.get("limit"),i=s.searchParams.get("offset"),m=u===null?void 0:Number.parseInt(u,10),y=i===null?void 0:Number.parseInt(i,10);return{limit:m!==void 0&&Number.isFinite(m)&&m>=0?m:void 0,offset:y!==void 0&&Number.isFinite(y)&&y>=0?y:void 0}},be=()=>{if(l===void 0)throw new c("scheduled endpoints require a `schedulerDO` namespace on the worker",{code:"SCHEDULER_NOT_CONFIGURED",status:400});return l},ve=ha({checkWsAdmin:async a=>p(a)||io(a,w(),I()),requireSchedulerNamespace:be,resolveSchedulerStub:a=>(B(a),Ae(be(),e.schedulerInstanceName??"default")),schedulerInstanceName:e.schedulerInstanceName??"default"}),se=Da({assertAdmin:B,resolveWorkflowsClient:e.workflowsClient??(()=>{})}),Nt=ya({assertAdmin:B,parsePaging:pe,queryParameter:ae,readBodyBytes:Sr,requireAdminOption:K,storage:{storageBuckets:e.storageBuckets,storageDelete:e.storageDelete,storageList:e.storageList,storageSignedUrl:e.storageSignedUrl,storageUpload:e.storageUpload}}),qt=Oa({readJsonBody:ee,requireAdminOption:K,vectorIntrospector:e.vectorIntrospector}),Ct=Nn({kvIntrospector:e.kvIntrospector,readJsonBody:ee,requireAdminOption:K}),xt=Pr({logArchive:e.logArchive,readJsonBody:ee,requireAdminOption:K}),jt=Dn({assertAdmin:B,options:{cronJobs:e.cronJobs,functions:e.functions,globalIntrospector:e.globalIntrospector,openApiSpec:e.openApiSpec,openRpcSpec:e.openRpcSpec},parsePaging:pe,queryParameter:ae,requireAdminOption:K}),Bt=a=>{const s=[],u=d??a?.SHARD;if(u!==void 0&&s.push(kr("durable-object:default",u,n)),e.health?.disableBindingProbes!==!0)for(const[i,m]of Object.entries(a??{})){const y=co(i,m);y!==void 0&&s.push(y)}for(const i of e.health?.probes??[])s.push(i);return s},$t=vr({appName:e.health?.appName,appVersion:e.health?.appVersion,auth:e.health?.auth??"public",cacheTtlMs:e.health?.cacheTtlMs,isAdmin:p,resolveProbes:Bt}),Lt=a=>{const s=e.schedulerInstanceName??"default",u=()=>a.get(a.idFromName(s)),i=async(f,S)=>{const O=await u().fetch(new Request(`https://scheduler.internal${f}`,S));if(!O.ok)throw new c(`ctx.scheduler: SchedulerDO ${f} failed (${String(O.status)}): ${await O.text()}`,{code:"INTERNAL",status:500});return await O.json()},m=async(f,S)=>await i(f,{body:JSON.stringify(S),headers:{"content-type":"application/json"},method:"POST"}),y=f=>{const S=f;if(S==null)throw new c("ctx.scheduler: target is required — pass a reference from the generated `internal` / `workflows` / `agents`",{code:"BAD_REQUEST",status:400});if(typeof S.binding=="string"&&S.binding.length>0)return{workflow:S.binding};if(typeof S.__lunoraRef=="string")return{functionPath:S.__lunoraRef};throw new c("ctx.scheduler: expected a reference from the generated `internal` / `workflows` / `agents` — a bare function-path string is refused here, because an HTTP action can be reached unauthenticated",{code:"BAD_REQUEST",status:400})},v=async(f,S,O={})=>{const{id:q}=await m("/schedule",{args:O,scheduledFor:f,...y(S)});return q};return{cancel:async f=>await m("/cancel",{id:f}),get:async f=>await i(`/get?id=${encodeURIComponent(f)}`,{method:"GET"}),list:async()=>await i("/list",{method:"GET"}),runAfter:async(f,S,O)=>{if(!Number.isFinite(f)||f<0)throw new c("ctx.scheduler.runAfter: `delayMs` must be a non-negative finite number",{code:"BAD_REQUEST",status:400});return await v(Date.now()+f,S,O)},runAt:async(f,S,O)=>{if(!Number.isFinite(f))throw new c("ctx.scheduler.runAt: `timestampMs` must be a finite epoch-millisecond number",{code:"BAD_REQUEST",status:400});return await v(f,S,O)}}},Kt=async(a,s,u)=>{const{claims:i,headers:m,userId:y}=await de(a,s,o),v=async(f,S={})=>{const O=f.__lunoraRef;if(typeof O!="string")throw new c("ctx.run*: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});const q=Oe(O,S,{...m,"x-lunora-system":"1"}),C=await oe(d,n,q),$=await C.json();if($.error)throw new c($.error.message??"shard RPC failed",{code:$.error.code??"INTERNAL",status:C.status});return $.result};return{auth:{getIdentity:()=>Promise.resolve(i),userId:y},cache:u.cache,fetch:globalThis.fetch.bind(globalThis),runAction:v,runMutation:v,runQuery:v,...l===void 0?{}:{scheduler:Lt(l)},...e.storage===void 0?{}:{storage:Cr(e.storage(s))}}},Gt=async(a,s,u)=>{if(!e.httpRouter)return;const i=await Kt(a,s,u);try{return await e.httpRouter.fetch(a,{...s,__lunoraCtx:i},u)}catch(m){return console.error("[lunora] httpRouter (SSR) handler threw:",m),new Response("Internal Server Error",{status:500})}},Ft=async(a,s,u)=>{if(a.headers.get("Upgrade")!=="websocket")throw new c("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});const i=Ze(a,ie);if(i)return i;const m=u.searchParams.get("shard")??n,{headers:y,identity:v}=await de(a,s,o);await T(v,m);const f=new Headers(a.headers),S=[...f.keys()];for(const q of S)q.startsWith("x-lunora-")&&f.delete(q);gt(f,y);const O=ao(s,e.shardDO);if(O!==void 0){f.set("x-lunora-shard-binding",O);const q=await no(d,m);if(q>0){const C=Qr(m,Math.floor(Math.random()*q));return oe(d,C,new Request(a,{headers:f}))}}return oe(d,m,new Request(a,{headers:f}))},Qt=async(a,s,u)=>{const{voiceAgents:i}=e;if(i===void 0)return new Response("Not found",{status:404});if(a.headers.get("Upgrade")!=="websocket")return new Response("Expected a WebSocket upgrade",{headers:{allow:"GET"},status:426});const m=Ze(a,ie);if(m)return m;let y;try{y=decodeURIComponent(u.pathname.slice(ft.length))}catch{return new Response("Unknown voice agent",{status:404})}const v=Object.hasOwn(i,y)?i[y]:void 0;if(v===void 0)return new Response("Unknown voice agent",{status:404});const f=u.searchParams.get("threadKey");if(f===null||f.length===0)return new Response("Missing threadKey",{status:400});const{headers:S,identity:O}=await de(a,s,o);if(e.authorizeShard){if(!await e.authorizeShard(O,f))return new Response("Forbidden",{status:403})}else E("shard");const q=new Headers(a.headers);return gt(q,S),oe(v,f,new Request(a,{headers:q}))},Mt=async(a,s,u)=>{if(e.authorizeFanOut){if(!await e.authorizeFanOut(u,a.table,s))throw new c("Forbidden fan-out",{code:"FORBIDDEN_FANOUT",status:403});return}if(s.startsWith("__lunora_relation__:"))throw new c("reverse cross-backend relation reads (`__lunora_relation__:*`) require `authorizeFanOut` to be configured on the worker",{code:"FORBIDDEN_FANOUT",status:403});if(e.authorizeShard)throw new c("Fan-out requires `authorizeFanOut` to be configured on the worker when `authorizeShard` is set",{code:"FORBIDDEN_FANOUT",status:403});E("fan-out")},Ee=async(a,s)=>{if(!(!a.fanOut&&a.functionPath.startsWith("__lunora_admin__:"))){if(a.fanOut){await Mt(a.fanOut,a.functionPath,s);return}await T(s,a.shardKey??n)}},ke=async(a,s,u,i,m,y)=>{const v=Date.now(),{observability:f,sampling:S}=e,O=Ke(a),{decision:q,ignoredUpstream:C,trace:$}=ra(a,{...S===void 0?{}:{sampling:S},trustInbound:t(a)});C&&r();const V={...m,"x-lunora-sample-errors":q.keepErrors?"1":"0"};na($,V);const Z=Oe(s,u,V);try{const G=await oe(d,i,Z);return ce(f,{...O,...pt($),durationMs:Date.now()-v,functionPath:s,ok:G.ok,shardKey:i,...G.ok?{}:{error:{code:"SHARD_ERROR",message:`shard returned ${String(G.status)}`,status:G.status}}},y,void 0,{isTraced:$.sampled,keepErrors:q.keepErrors}),G}catch(G){throw ce(f,{...O,...pt($),..._e(s,Date.now()-v,G,{shardKey:i})},y,void 0,{isTraced:$.sampled,keepErrors:q.keepErrors}),G}},zt=a=>{if(a.fanOut&&a.shardKey)throw new c("RPC envelope cannot set both `shardKey` and `fanOut`",{code:"BAD_REQUEST",status:400});if(!a.fanOut&&a.functionPath.startsWith("__lunora_relation__:"))throw new c("`__lunora_relation__:*` is a fan-out-only reserved RPC and cannot be dispatched to a single shard",{code:"FORBIDDEN",status:403});if(a.fanOut&&!e.queryCoordinator)throw new c("RPC envelope set `fanOut` but no `queryCoordinator` is configured on the worker",{code:"BAD_REQUEST",status:400})},Wt=async(a,s,u)=>{L(a,"POST","RPC");const i=await eo(a);Za(s,i),zt(i);const m=await ne(a,i);if(m!==void 0)return m;const{headers:y,identity:v}=await de(a,s,o);await Ee(i,v);const f=wt(i,e);{const S=Date.now(),{observability:O}=e,q=Ke(a),C=Re(s,a,u&&(Z=>u.waitUntil?.(Z)));if(i.fanOut){const Z=e.queryCoordinator;if(!Z)throw new c("RPC envelope set `fanOut` but no `queryCoordinator` is configured on the worker",{code:"BAD_REQUEST",status:400});try{const G=await Z.fanOut(d,{args:i.args??{},fanOut:i.fanOut,functionPath:i.functionPath,headers:y});return ce(O,{durationMs:Date.now()-S,fanOut:{failed:G.failed,shards:G.ok+G.failed,table:i.fanOut.table},functionPath:i.functionPath,...q,ok:!0},C),Response.json(G,{headers:{"content-type":"application/json"},status:200})}catch(G){throw ce(O,{..._e(i.functionPath,Date.now()-S,G,{fanOut:{table:i.fanOut.table}}),...q},C),G}}const $=i.shardKey??n,V=()=>ke(a,i.functionPath,i.args??{},$,y,C);return f&&e.x402Charge?e.x402Charge(a,{functionPath:i.functionPath,price:f.price},V,ht(u)):V()}},Ht=async(a,s,u)=>{L(a,"POST","RPC batch");const i=await ee(a),{calls:m}=i;if(!Array.isArray(m))throw new c("RPC batch `calls` must be an array",{code:"BAD_REQUEST",status:400});const{headers:y,identity:v}=await de(a,s,o),f=Xr(m,n);for(const z of f.values())for(const W of z)if(e.functions?.[W.functionPath]?.x402)throw new c(`paid (\`.x402\`) function "${W.functionPath}" cannot be called in a batch; dispatch it individually over ${lt}`,{code:"BAD_REQUEST",status:400});await Promise.all([...f.entries()].flatMap(([z,W])=>W.map(re=>Ee({functionPath:re.functionPath,shardKey:z},v))));const{observability:S}=e,O=Re(s,a,u&&(z=>u.waitUntil?.(z))),q=Ke(a),C=[],$=[],V=(z,W,re,ue)=>({body:{error:{code:re,message:ue}},id:z.id,status:W}),Z=(z,W,re,ue,fe)=>{for(const H of z)ce(S,fe(H),O),C.push(V(H,W,re,ue))},G=(z,W,re,ue,fe)=>{for(const H of z){const me=ue.get(H.id)??fe,ge=me<400;ce(S,{durationMs:re,functionPath:H.functionPath,...q,ok:ge,shardKey:W,...ge?{}:{error:{code:"SHARD_ERROR",message:`batched call returned ${String(me)}`,status:me}}},O)}};await Promise.all([...f.entries()].map(async([z,W])=>{const re=new Headers(y);re.set("content-type","application/json");const ue=new Request("https://shard.internal/rpc-batch",{body:JSON.stringify({calls:W}),headers:re,method:"POST"}),fe=Date.now();let H;try{H=await oe(d,z,ue)}catch(Y){const Ue=Date.now()-fe,{body:He}=hr(Y,{fallbackCode:"SHARD_UNAVAILABLE",redactedMessage:"shard unavailable"});Z(W,502,He.code,He.message,ur=>({..._e(ur.functionPath,Ue,Y,{shardKey:z}),...q}));return}const me=Date.now()-fe,ge=H.headers.get("x-d1-bookmark");ge&&$.push(ge);let De;try{De=await H.json()}catch{const Y=`shard batch returned a non-JSON response (${String(H.status)})`;Z(W,H.status,"SHARD_ERROR",Y,Ue=>({durationMs:me,error:{code:"SHARD_ERROR",message:Y,status:H.status},functionPath:Ue.functionPath,...q,ok:!1,shardKey:z}));return}const Pe=Array.isArray(De.results)?De.results:[],cr=new Map(Pe.map(Y=>[Y.id,Y.status??H.status])),dr=new Set(Pe.map(Y=>Y.id));G(W,z,me,cr,H.status),C.push(...Pe);for(const Y of W)dr.has(Y.id)||C.push(V(Y,H.status,"SHARD_ERROR",`shard batch omitted result for call ${String(Y.id)}`))}));const ze={"content-type":"application/json"},[We]=$;return $.length===1&&We!==void 0&&(ze["x-d1-bookmark"]=We),Response.json({results:C},{headers:ze,status:200})},Jt=async(a,s,u,i={},m={})=>{try{const y=u.__lunoraRef;if(typeof y!="string")throw new c("serverQuery: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});const{headers:v,identity:f}=await de(a,s,o);await Ee({functionPath:y,shardKey:m.shardKey},f);const S=m.shardKey??n,O=Re(s,a,m.waitUntil);return await ke(a,y,i,S,v,O)}catch(y){return Je(y)}},Vt=1e3,Yt=async(a,s)=>{const u=e.backupRetain;if(u===void 0||u<=0)return;const i=[];let m;for(let v=0;v<Vt;v+=1){const f=await a.list({cursor:m,prefix:s});for(const S of f.objects)S.key.endsWith(".manifest.json")&&i.push(S.key);if(!f.truncated||f.cursor===void 0)break;m=f.cursor}const y=i.toSorted((v,f)=>f.localeCompare(v)).slice(u);await Promise.all(y.flatMap(v=>{const f=v.slice(0,-14);return[a.delete(v),a.delete(f)]}))},Xt=async a=>{const s=e.backupStore,u=e.queryCoordinator;if(!s)throw new c("scheduled backup requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});if(!u)throw new c("scheduled backup requires a `queryCoordinator` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});const i=w();if(!i||i.length===0)throw new c("scheduled backup requires an `adminToken` (or `env.LUNORA_ADMIN_TOKEN`) to authenticate the per-shard export gate",{code:"BACKUP_NOT_CONFIGURED",status:500});const m={authorization:`Bearer ${i}`,"content-type":"application/json"},y=e.backupTables;let v=0,f=0;const S=[];await at(e,u,m,y,Z=>{const G=`${JSON.stringify(Z)}
5
- `;v+=1,f+=Ua.encode(G).byteLength,S.push(G)},d);const O=e.backupPrefix??"backups/",q=new Date(a.scheduledTime).toISOString(),C=`${O}lunora-backup-${q.replaceAll(/[.:]/gu,"-")}.ndjson`,$=`${C}.manifest.json`;await s.put(C,new Blob(S,{type:"application/x-ndjson"}),{httpMetadata:{contentType:"application/x-ndjson"}});const V={bytes:f,createdAt:q,cron:a.cron,file:C,id:q,rows:v,scheduledTime:a.scheduledTime,...y?{tables:y.join(",")}:{}};await s.put($,`${JSON.stringify(V,void 0,2)}
6
- `,{httpMetadata:{contentType:"application/json"}}),await Yt(s,O)},Qe=async(a,s,u)=>{const{observability:i}=e,m=Date.now(),y=Te(16),v=Te(8),f=mt(s);try{const S=await u();return ce(i,{durationMs:Date.now()-m,functionPath:a,ok:!0,spanId:v,traceId:y},f),S}catch(S){throw ce(i,{..._e(a,Date.now()-m,S,{}),spanId:v,traceId:y},f),S}finally{Ve(i,f)}},Zt=async(a,s,u)=>{b(s);const i=[],m=f=>f instanceof Error?f:new Error(String(f)),y=e.crons?.[a.cron];if(y)try{await y(a,s,u)}catch(f){i.push(m(f))}if(await F(a.cron,s,i,m),e.backupStore&&e.backupCron!==void 0&&e.backupCron===a.cron)try{await Xt(a)}catch(f){i.push(m(f))}const[v]=i;if(i.length===1&&v)throw v;if(i.length>1)throw new AggregateError(i,`scheduled("${a.cron}") had ${String(i.length)} failure(s)`)},er=async(a,s)=>{try{const u=a??{},i=e.adminToken??(typeof u.LUNORA_ADMIN_TOKEN=="string"?u.LUNORA_ADMIN_TOKEN:void 0);if(!i||i.length===0)return;await oe(d,n,Oe(Ma,{outcome:s},{authorization:`Bearer ${i}`,"content-type":"application/json"}))}catch{}},tr=async(a,s,u,i)=>{if(!e.authHandler)return;const m=await e.authHandler(a);if(!m)return;const y=e.authBasePath??Qa;return Ha(u.pathname,y)&&i.waitUntil?.(er(s,m.status>=400?"fail":"ok")),m},rr=async({args:a,env:s,functionPath:u,request:i,shardKey:m,waitUntil:y})=>{_t(a,"REST");const v={functionPath:u,...m===void 0?{}:{shardKey:m}},{headers:f,identity:S}=await de(i,s,o);await Ee(v,S);const O=m??n,q=Re(s,i,y),C=()=>ke(i,u,a,O,f,q),$=wt(v,e);return $&&e.x402Charge?e.x402Charge(i,{functionPath:u,price:$.price},C,ht({waitUntil:y})):C()},nr=_r({functions:e.functions??{},invoke:rr,readJsonBody:ee,...e.restRateLimit?{rateLimit:e.restRateLimit}:{}}),Ie=e.routes!==void 0&&Object.keys(e.routes).length>0?e.routes:void 0,ar={[La]:a=>a.method!=="GET"&&a.method!=="HEAD"?new Response(void 0,{headers:{allow:"GET, HEAD"},status:405}):Response.json({ok:!0},{headers:{"cache-control":"no-store"}}),[qa]:(a,s,u)=>Ft(a,s,u),[lt]:(a,s,u,i)=>Wt(a,s,i),[Na]:(a,s,u,i)=>Ht(a,s,i),[Ca]:(a,s)=>M(a,s),[xa]:(a,s)=>P(a,s),[ja]:async a=>{L(a,"POST","ws-token"),B(a);const s=w();if(s===void 0)throw new c("ws-token minting requires a configured admin token",{code:"ADMIN_TOKEN_NOT_CONFIGURED",status:400});const u=await zr(s);return Response.json(u,{headers:{"cache-control":"no-store"}})},...N,...he,...ve,...se,...Nt,...qt,...Ct,...xt,...jt,...$t,...nr,...Vr({assertAdmin:B,getAuthAdmin:()=>e.authAdmin,parsePaging:pe,queryParameter:ae,readJsonBody:ee})};let ie=Xe(e.security),Me=!1;const or=a=>{Me||(Me=!0,ie=Xe(e.security,a??{}))},sr=async(a,s)=>{if(!(e.adminGate===void 0||!Ka(s)))try{await e.adminGate(a)&&k.add(a)}catch{}},ir=async(a,s,u)=>{const i=new URL(a.url);if(a.method==="POST"||a.method==="PUT"){const f=Number(a.headers.get("content-length")??""),S=Pa[i.pathname]??Et;if(Number.isFinite(f)&&f>S)throw new c("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413})}const m=await tr(a,s,i,u);if(m)return m;if(Ie){const f=`${a.method} ${i.pathname}`,S=Ie[f]??Ie[i.pathname];if(S)return S(a,s,u)}const y=ar[i.pathname];return y?(await sr(a,i.pathname),y(a,s,i,u)):e.voiceAgents!==void 0&&i.pathname.startsWith(ft)?Qt(a,s,i):await Gt(a,s,u)||new Response("Not found",{status:404})};return{async fetch(a,s,u){e.passThroughOnException&&u.passThroughOnException?.(),or(s),b(s);const i=Nr(a,ie);if(i)return i;const m=qr(a,ie);if(m)return qe(m,a,ie);try{const y=await ir(a,s,u);return qe(y,a,ie)}catch(y){return qe(Je(y),a,ie)}finally{Ve(e.observability,mt(u))}},async queue(a,s,u){await Qe(`queue:${Va(a)}`,u,async()=>{await e.queue?.(a,s,u)})},async scheduled(a,s,u){await Qe(`cron:${a.cron}`,u,async()=>{await Zt(a,s,u)})},serverQuery:Jt}},uo=e=>Ut(e),lo=e=>typeof e=="function"?{fetch:e}:e,ho=e=>!!(e.crons??e.cronJobs??e.backupCron),Do=(e,t)=>{const r=lo(e),n=typeof e=="object"&&typeof e.scheduled=="function"?e.scheduled:void 0,o=l=>{const h=uo({...l,httpRouter:r});return n!==void 0&&!ho(l)?{...h,scheduled:async(w,R,I)=>{await n(w,R,I)}}:h};if(typeof t!="function")return o(t);const d=t;return{fetch:(l,h,w)=>o(d(h)).fetch(l,h,w),queue:(l,h,w)=>o(d(h)).queue?.(l,h,w)??Promise.resolve(),scheduled:(l,h,w)=>o(d(h)).scheduled(l,h,w),serverQuery:(l,h,w,R,I)=>o(d(h)).serverQuery(l,h,w,R,I)}},po=(e,t)=>{if(typeof e=="function")return e(t);const r=e.shardDO??t?.SHARD;if(!r)throw new c("@lunora/runtime: no shard Durable Object namespace found. Bind `SHARD` in wrangler.jsonc, or pass `createLunoraHandler({ shardDO: env.MY_SHARD })`.");return{...e,shardDO:r}},Po=(e={})=>(t,r,n)=>Ut(po(e,r)).fetch(t,r,n??pr),Uo=e=>e;export{Or as GET_AUTH_AUDIT_LOG_OP,pr as NOOP_EXECUTION_CONTEXT,Co as composeIdentityResolvers,uo as composeWorker,Po as createLunoraHandler,Ut as createWorker,Uo as defineRpcEnvelope,no as probeRelayCount,po as resolveLunoraOptions,xo as routeIdentityResolvers,Do as withFrameworkWorker};
@@ -1 +0,0 @@
1
- import{f as u,u as d}from"./identity-header-pdXOyDU4.mjs";import{LunoraError as o}from"./LunoraError-C08OP5Uq.mjs";const l="/_lunora/rpc",c=r=>{const t={"content-type":"application/json"};return r.userId!==void 0&&r.userId.length>0&&(t["x-lunora-userid"]=u(r.userId)),r.identity!==void 0&&(t["x-lunora-identity"]=d(r.identity)),t},i=async(r,t,a)=>{const e=await(r.fetch??globalThis.fetch)(new Request(`${r.origin}${l}`,{body:JSON.stringify(t),headers:c(r),method:"POST"}));if(!e.ok)throw new o(`cross-shard relation ${a} failed: worker returned ${String(e.status)}`);const n=await e.json();if(typeof n.failed=="number"&&n.failed>0){const s=(typeof n.ok=="number"?n.ok:0)+n.failed;throw new o(`cross-shard relation ${a} failed on ${String(n.failed)} of ${String(s)} shard(s) — refusing to return a partial result`)}return n.data},y=r=>({crossShardCounter:async(t,a)=>{const e=await i(r,{args:{table:t,where:a},fanOut:{merge:{kind:"sum"},table:t},functionPath:"__lunora_relation__:count"},"count");return typeof e=="number"?e:0},crossShardReader:async(t,a)=>{const e=await i(r,{args:{orderBy:a?.orderBy,table:t,where:a?.where,with:a?.with},fanOut:{merge:{kind:"concat"},table:t},functionPath:"__lunora_relation__:read"},"read");return{continueCursor:null,isDone:!0,page:Array.isArray(e)?e:[]}}});export{y as createCrossShardRelationCapabilities};