@lunora/runtime 1.0.0-alpha.293 → 1.0.0-alpha.295

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{declareAppJurisdiction as t}from"./packem_shared/declareAppJurisdiction-DEba2p42.mjs";import{BACKUP_KEY_PREFIX as s,backupManifestKey as i,backupObjectKey as p,backupObjectKeyOfManifest as n,isBackupManifestEntry as c,isBackupManifestKey as m,normalizeBackupPrefix as f}from"./packem_shared/BACKUP_KEY_PREFIX-BOtSu-_3.mjs";import{toAirbyteMessages as E,toFivetranResponse as R}from"./packem_shared/toAirbyteMessages-BVogmTPJ.mjs";import{composeWorker as d,createLunoraHandler as l,createWorker as u,defineRpcEnvelope as _,resolveLunoraOptions as k,withFrameworkWorker as b}from"./packem_shared/composeWorker-C7SAGqH1.mjs";import{createCrossShardRelationCapabilities as C}from"./packem_shared/createCrossShardRelationCapabilities-BBUXTMhk.mjs";import{DEFAULT_REGISTRY_CACHE_TTL_MS as A,SHARD_REGISTRY_DO_NAME as L,createDynamicShardRegistry as T}from"./packem_shared/DEFAULT_REGISTRY_CACHE_TTL_MS-w_RLPiwj.mjs";import{parseStackFrames as H,toError as P}from"./packem_shared/parseStackFrames-CZddjveh.mjs";import{LunoraError as v,toErrorResponse as I}from"./packem_shared/LunoraError-PkZWF-_g.mjs";import{c as F,a as M,d as N,r as G,b as K,s as U,w}from"./packem_shared/export-tap-CMyD7rin.mjs";import{HEALTH_PATH as Y,HEALTH_READY_PATH as z,buildHealthRoutes as X,d1Probe as j,durableObjectProbe as V,presenceProbe as W}from"./packem_shared/HEALTH_PATH-B8ndDG3s.mjs";import{LOG_ARCHIVE_PATH as J,resolveLogArchiveFromEnv as Q}from"./packem_shared/LOG_ARCHIVE_PATH-dTuCzfyj.mjs";import{m as $,a as ee}from"./packem_shared/memoize-identity-Cbr1Sdt3.mjs";import{e as oe,a as te}from"./packem_shared/observability-9slk__Gi.mjs";import{enrichSink as se,filterSink as ie}from"./packem_shared/enrichSink-8_qnPWNH.mjs";import{a as ne,c as ce,b as me,o as fe,p as xe,w as Ee}from"./packem_shared/observability-sinks-BA76CH4h.mjs";import{D as Se,c as de}from"./packem_shared/pipeline-log-reader-C-nuWG_e.mjs";import{createQueryCoordinator as ue,createStaticShardRegistry as _e}from"./packem_shared/createQueryCoordinator-DIrlAqnz.mjs";import{applyJurisdiction as be,resolveShard as ye}from"./packem_shared/applyJurisdiction-DKQE8kOA.mjs";import{a as Oe,r as Ae,b as Le}from"./packem_shared/rest-cache-q5V06Etw.mjs";import{a as he,b as He,c as Pe,r as ge}from"./packem_shared/rest-routes-D5NWHmVl.mjs";import{d as Ie,e as De,h as Fe,r as Me}from"./packem_shared/security-headers-0DqdJ04h.mjs";import{createShardClient as Ge}from"./packem_shared/createShardClient-M_c0MHVS.mjs";import{STORAGE_UPLOAD_MAX_BODY_BYTES as Ue}from"./packem_shared/STORAGE_UPLOAD_MAX_BODY_BYTES-Onz8HkiB.mjs";import{loadStudioDocument as Be}from"./packem_shared/loadStudioDocument-BSYQEMnd.mjs";import{LOG_ARCHIVE_NOT_CONFIGURED as ze}from"./packem_shared/LOG_ARCHIVE_NOT_CONFIGURED-CDpi4yFD.mjs";import{NOOP_EXECUTION_CONTEXT as je}from"./packem_shared/NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{composeIdentityResolvers as We,routeIdentityResolvers as qe}from"./packem_shared/composeIdentityResolvers-CpdHuDyk.mjs";const e="0.0.0";export{s as BACKUP_KEY_PREFIX,Se as DEFAULT_LOG_COLUMNS,A as DEFAULT_REGISTRY_CACHE_TTL_MS,Y as HEALTH_PATH,z as HEALTH_READY_PATH,ze as LOG_ARCHIVE_NOT_CONFIGURED,J as LOG_ARCHIVE_PATH,v as LunoraError,je as NOOP_EXECUTION_CONTEXT,L as SHARD_REGISTRY_DO_NAME,Ue as STORAGE_UPLOAD_MAX_BODY_BYTES,e as VERSION,ne as analyticsEngineSink,be as applyJurisdiction,Oe as applyRestCache,he as argsFromQuery,i as backupManifestKey,p as backupObjectKey,n as backupObjectKeyOfManifest,X as buildHealthRoutes,He as buildRestRoutes,ce as combineSinks,We as composeIdentityResolvers,d as composeWorker,me as consoleSink,C as createCrossShardRelationCapabilities,T as createDynamicShardRegistry,F as createKvCursorStore,l as createLunoraHandler,M as createMemoryCursorStore,de as createPipelineLogReader,ue as createQueryCoordinator,Pe as createRestRateLimit,Ge as createShardClient,_e as createStaticShardRegistry,u as createWorker,j as d1Probe,t as declareAppJurisdiction,Ie as decorateResponse,N as defineExportSink,_ as defineRpcEnvelope,V as durableObjectProbe,oe as emitLogEvent,te as emitRpcEvent,De as enforceOrigin,se as enrichSink,ie as filterSink,Fe as handleCorsPreflight,c as isBackupManifestEntry,m as isBackupManifestKey,Be as loadStudioDocument,$ as memoizeIdentity,ee as memoizeIdentityPerRequest,f as normalizeBackupPrefix,fe as otlpSink,H as parseStackFrames,xe as pipelineLogSink,W as presenceProbe,G as r2Sink,Ae as requestCarriesCredentials,Q as resolveLogArchiveFromEnv,k as resolveLunoraOptions,Me as resolveSecurity,ye as resolveShard,Le as restCacheHeaders,ge as restSurfaceFromRegistry,qe as routeIdentityResolvers,K as runExportTap,U as sanitizeChange,E as toAirbyteMessages,P as toError,I as toErrorResponse,R as toFivetranResponse,w as webhookExportSink,Ee as webhookSink,b as withFrameworkWorker};
1
+ import{declareAppJurisdiction as t}from"./packem_shared/declareAppJurisdiction-DEba2p42.mjs";import{BACKUP_KEY_PREFIX as s,backupManifestKey as i,backupObjectKey as p,backupObjectKeyOfManifest as n,isBackupManifestEntry as c,isBackupManifestKey as m,normalizeBackupPrefix as f}from"./packem_shared/BACKUP_KEY_PREFIX-BOtSu-_3.mjs";import{toAirbyteMessages as E,toFivetranResponse as R}from"./packem_shared/toAirbyteMessages-BVogmTPJ.mjs";import{composeWorker as d,createLunoraHandler as l,createWorker as u,defineRpcEnvelope as _,resolveLunoraOptions as k,withFrameworkWorker as b}from"./packem_shared/composeWorker-9bAMAwiY.mjs";import{createCrossShardRelationCapabilities as C}from"./packem_shared/createCrossShardRelationCapabilities-BBUXTMhk.mjs";import{DEFAULT_REGISTRY_CACHE_TTL_MS as A,SHARD_REGISTRY_DO_NAME as L,createDynamicShardRegistry as T}from"./packem_shared/DEFAULT_REGISTRY_CACHE_TTL_MS-w_RLPiwj.mjs";import{parseStackFrames as H,toError as P}from"./packem_shared/parseStackFrames-CZddjveh.mjs";import{LunoraError as v,toErrorResponse as I}from"./packem_shared/LunoraError-PkZWF-_g.mjs";import{c as F,a as M,d as N,r as G,b as K,s as U,w}from"./packem_shared/export-tap-CMyD7rin.mjs";import{HEALTH_PATH as Y,HEALTH_READY_PATH as z,buildHealthRoutes as X,d1Probe as j,durableObjectProbe as V,presenceProbe as W}from"./packem_shared/HEALTH_PATH-B8ndDG3s.mjs";import{LOG_ARCHIVE_PATH as J,resolveLogArchiveFromEnv as Q}from"./packem_shared/LOG_ARCHIVE_PATH-dTuCzfyj.mjs";import{m as $,a as ee}from"./packem_shared/memoize-identity-Cbr1Sdt3.mjs";import{e as oe,a as te}from"./packem_shared/observability-9slk__Gi.mjs";import{enrichSink as se,filterSink as ie}from"./packem_shared/enrichSink-8_qnPWNH.mjs";import{a as ne,c as ce,b as me,o as fe,p as xe,w as Ee}from"./packem_shared/observability-sinks-BA76CH4h.mjs";import{D as Se,c as de}from"./packem_shared/pipeline-log-reader-C-nuWG_e.mjs";import{createQueryCoordinator as ue,createStaticShardRegistry as _e}from"./packem_shared/createQueryCoordinator-DIrlAqnz.mjs";import{applyJurisdiction as be,resolveShard as ye}from"./packem_shared/applyJurisdiction-DKQE8kOA.mjs";import{a as Oe,r as Ae,b as Le}from"./packem_shared/rest-cache-q5V06Etw.mjs";import{a as he,b as He,c as Pe,r as ge}from"./packem_shared/rest-routes-D5NWHmVl.mjs";import{d as Ie,e as De,h as Fe,r as Me}from"./packem_shared/security-headers-0DqdJ04h.mjs";import{createShardClient as Ge}from"./packem_shared/createShardClient-M_c0MHVS.mjs";import{STORAGE_UPLOAD_MAX_BODY_BYTES as Ue}from"./packem_shared/STORAGE_UPLOAD_MAX_BODY_BYTES-Onz8HkiB.mjs";import{loadStudioDocument as Be}from"./packem_shared/loadStudioDocument-BSYQEMnd.mjs";import{LOG_ARCHIVE_NOT_CONFIGURED as ze}from"./packem_shared/LOG_ARCHIVE_NOT_CONFIGURED-CDpi4yFD.mjs";import{NOOP_EXECUTION_CONTEXT as je}from"./packem_shared/NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{composeIdentityResolvers as We,routeIdentityResolvers as qe}from"./packem_shared/composeIdentityResolvers-CpdHuDyk.mjs";const e="0.0.0";export{s as BACKUP_KEY_PREFIX,Se as DEFAULT_LOG_COLUMNS,A as DEFAULT_REGISTRY_CACHE_TTL_MS,Y as HEALTH_PATH,z as HEALTH_READY_PATH,ze as LOG_ARCHIVE_NOT_CONFIGURED,J as LOG_ARCHIVE_PATH,v as LunoraError,je as NOOP_EXECUTION_CONTEXT,L as SHARD_REGISTRY_DO_NAME,Ue as STORAGE_UPLOAD_MAX_BODY_BYTES,e as VERSION,ne as analyticsEngineSink,be as applyJurisdiction,Oe as applyRestCache,he as argsFromQuery,i as backupManifestKey,p as backupObjectKey,n as backupObjectKeyOfManifest,X as buildHealthRoutes,He as buildRestRoutes,ce as combineSinks,We as composeIdentityResolvers,d as composeWorker,me as consoleSink,C as createCrossShardRelationCapabilities,T as createDynamicShardRegistry,F as createKvCursorStore,l as createLunoraHandler,M as createMemoryCursorStore,de as createPipelineLogReader,ue as createQueryCoordinator,Pe as createRestRateLimit,Ge as createShardClient,_e as createStaticShardRegistry,u as createWorker,j as d1Probe,t as declareAppJurisdiction,Ie as decorateResponse,N as defineExportSink,_ as defineRpcEnvelope,V as durableObjectProbe,oe as emitLogEvent,te as emitRpcEvent,De as enforceOrigin,se as enrichSink,ie as filterSink,Fe as handleCorsPreflight,c as isBackupManifestEntry,m as isBackupManifestKey,Be as loadStudioDocument,$ as memoizeIdentity,ee as memoizeIdentityPerRequest,f as normalizeBackupPrefix,fe as otlpSink,H as parseStackFrames,xe as pipelineLogSink,W as presenceProbe,G as r2Sink,Ae as requestCarriesCredentials,Q as resolveLogArchiveFromEnv,k as resolveLunoraOptions,Me as resolveSecurity,ye as resolveShard,Le as restCacheHeaders,ge as restSurfaceFromRegistry,qe as routeIdentityResolvers,K as runExportTap,U as sanitizeChange,E as toAirbyteMessages,P as toError,I as toErrorResponse,R as toFivetranResponse,w as webhookExportSink,Ee as webhookSink,b as withFrameworkWorker};
@@ -31,7 +31,7 @@ ${wt(`refused — ${X}`)}`;continue}if(a?.aborted)return Te("ai-error");E({name:
31
31
  ${wt(Q)}`}return Te("ai-error")},gu={"cache-control":"no-cache, no-transform","content-type":"text/event-stream; charset=utf-8","x-accel-buffering":"no"},yu=(e,t,n)=>{const o=JSON.stringify(e),r="",s=t===void 0?"":`event: ${t}
32
32
  `;return`${r}${s}data: ${o}
33
33
 
34
- `},_u="__lunora_admin__:aiChat",bu="__lunora_admin__:aiAvailable",Su=new Set(["__lunora_admin__:aiChartConfig","__lunora_admin__:aiCronExpression","__lunora_admin__:aiGenerateSql","__lunora_admin__:aiNameQuery","__lunora_admin__:aiTableFilter","__lunora_admin__:explainIssue"]),as=60,Ko=120,Eu=e=>{if(typeof e!="object"||e===null)return;const{columns:t,table:n}=e;if(!(typeof n!="string"||n===""||!Array.isArray(t)))return{columns:t.slice(0,ns).filter(o=>typeof o=="string").map(o=>o.slice(0,Ko)),table:n.slice(0,Ko)}},Au={describeTables:"__lunora_admin__:describeTables",readAdvisors:"__lunora_admin__:getAdvisories",readLogs:"__lunora_admin__:getLogs",readPolicies:"__lunora_admin__:rlsPolicies",runSql:"__lunora_admin__:runSql"},Tu="__lunora_admin__:listTables",Ru=(e,t,n,o,r)=>{const s=async(c,d,h)=>{const p=await e(o,c,d,t,await n(),void 0,h);if(!p.ok)return{error:`the tool call failed (${p.status.toString()})`};const w=await p.json();return It(w.result)},a=async c=>{if(r.length>0)return r.map(h=>h.table);const d=await s(Tu,{},c);return Array.isArray(d)?d.map(h=>h.name).filter(h=>typeof h=="string").slice(0,as):[]};return async(c,d)=>{const h=Au[c.name];return c.name==="describeTables"?s(h,{tables:await a(d)},d):s(h,c.sql===void 0?{}:{sql:c.sql},d)}},vu=e=>async(n,o,r)=>{e.assertAdmin(n);const s=e.getBinding(r),a=o.schema,c=o.shardKey,d=typeof c=="string"&&c!==""?c:e.defaultShardKey();if(d.includes(Nt)||d.includes(Dt))throw new l("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403});const h={approval:o.approval,approvalSecret:e.approvalSecret(r),knowledge:o.knowledge,...typeof o.model=="string"?{model:o.model}:{},prompt:o.prompt,shardKey:d,transcript:o.transcript},p=Array.isArray(a)?a.slice(0,as).map(S=>Eu(S)).filter(S=>S!==void 0):[],w=e.optInLevel(r),g=s===void 0||w==="disabled"||e.forwardToShard===void 0?void 0:await(async()=>{const{forward:S,headers:k}=await e.forwardToShard(n,r);if(k.authorization===void 0&&k[Rt]===void 0)return;const{resolveToolHeaders:A}=e;return Ru(S,d,async()=>A===void 0?k:A(k),n,p)})(),v=new TextEncoder,E=new AbortController,b=()=>{E.abort()};n.signal.aborted?b():n.signal.addEventListener("abort",b,{once:!0});const _=new ReadableStream({cancel(){b()},async start(S){let k=!0;const A=(U,R)=>{if(k)try{S.enqueue(v.encode(yu(U,R)))}catch{k=!1}};try{const U=await wu(s,h,p,w,g,R=>{A(R)},E.signal);E.signal.aborted||A({result:Re(U)},"complete")}catch{A({code:"AI_CHAT_FAILED",message:"the assistant turn failed"},"error")}finally{n.signal.removeEventListener("abort",b);try{S.close()}catch{}}}});return new Response(_,{headers:gu,status:200})},Ou=e=>(n,o,r)=>{e.assertAdmin(n);const s=e.optInLevel(r),a={available:s!=="disabled"&&e.getBinding(r)!==void 0,level:s};return Promise.resolve(Response.json({result:Re(a)},{headers:{"content-type":"application/json"},status:200}))},Iu=e=>(t,n,o)=>{if(!(!Su.has(n)||e.optInLevel(o)!=="disabled"))return e.assertAdmin(t),Response.json({result:Re({degraded:!0,reason:"no-ai-binding"})},{headers:{"content-type":"application/json"},status:200})},M="/_lunora/admin/auth",ku=new Set(["banUser","cancelInvitation","capabilities","config","deleteApiKey","listAccounts","listApiKeys","listInvitations","listMembers","listOrganizations","listOrgRoles","listPasskeys","listSessions","listSignUpInvitations","listTeamMembers","listTeams","listUsers","revokeSignUpInvitation","revokeUserSession","revokeUserSessions"]),Nu={INVITER_REQUIRED:400,LAST_ORGANIZATION_OWNER:409,MEMBERSHIP_CHANGED:409,ORG_SLUG_INVALID:400,ORG_SLUG_TAKEN:409,PASSWORD_TOO_LONG:400,PASSWORD_TOO_SHORT:400,USER_ALREADY_EXISTS:409,USER_NOT_FOUND:404},H=(e,t)=>{const n=e[t];if(typeof n!="string"||n==="")throw new l(`\`${t}\` is required`,{code:"BAD_REQUEST",status:400});return n},Ue=(e,t)=>{const n=e(t);if(n===void 0)throw new l(`\`${t}\` query parameter is required`,{code:"BAD_REQUEST",status:400});return n},is=e=>{if(typeof e=="string"||Array.isArray(e)&&e.every(t=>typeof t=="string"))return e},ge=(e,t)=>typeof e[t]=="string"?e[t]:void 0,sn=(e,t)=>{const n=e[t];return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:void 0},Fo=e=>{const t=is(e.role);if(t===void 0||typeof t=="string"&&t.trim()==="")throw new l("`role` is required",{code:"BAD_REQUEST",status:400});return t},Wo=e=>{const t=e.permission;if(typeof t!="object"||t===null||Array.isArray(t))throw new l("`permission` object is required",{code:"BAD_REQUEST",status:400});const n={};for(const[o,r]of Object.entries(t))Array.isArray(r)&&r.every(s=>typeof s=="string")&&(n[o]=r);return n},Du={[`${M}/capabilities`]:{build:()=>({}),http:"GET",method:"capabilities"},[`${M}/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"},[`${M}/sessions`]:{build:({paging:e,query:t})=>({...e,userId:t("userId")}),http:"GET",method:"listSessions"},[`${M}/accounts`]:{build:({query:e})=>({userId:Ue(e,"userId")}),http:"GET",method:"listAccounts"},[`${M}/passkeys`]:{build:({query:e})=>({userId:Ue(e,"userId")}),http:"GET",method:"listPasskeys"},[`${M}/api-keys`]:{build:({query:e})=>({userId:Ue(e,"userId")}),http:"GET",method:"listApiKeys"},[`${M}/api-keys/delete`]:{build:({body:e})=>({apiKeyId:H(e,"apiKeyId")}),http:"POST",method:"deleteApiKey",returns:"void"},[`${M}/organizations`]:{build:({paging:e})=>({...e}),http:"GET",method:"listOrganizations"},[`${M}/organizations/members`]:{build:({paging:e,query:t})=>({...e,organizationId:Ue(t,"organizationId")}),http:"GET",method:"listMembers"},[`${M}/organizations/invitations`]:{build:({paging:e,query:t})=>({...e,organizationId:Ue(t,"organizationId")}),http:"GET",method:"listInvitations"},[`${M}/sign-up-invitations`]:{build:({paging:e})=>({...e}),http:"GET",method:"listSignUpInvitations"},[`${M}/sign-up-invitations/create`]:{build:({body:e})=>({email:H(e,"email"),expiresInSeconds:typeof e.expiresInSeconds=="number"?e.expiresInSeconds:void 0,invitedBy:ge(e,"invitedBy")}),http:"POST",method:"createSignUpInvitation"},[`${M}/sign-up-invitations/revoke`]:{build:({body:e})=>({email:H(e,"email")}),http:"POST",method:"revokeSignUpInvitation",returns:"void"},[`${M}/config`]:{build:()=>({}),http:"GET",method:"config"},[`${M}/organizations/teams`]:{build:({paging:e,query:t})=>({...e,organizationId:Ue(t,"organizationId")}),http:"GET",method:"listTeams"},[`${M}/organizations/teams/members`]:{build:({paging:e,query:t})=>({...e,teamId:Ue(t,"teamId")}),http:"GET",method:"listTeamMembers"},[`${M}/organizations/roles`]:{build:({paging:e,query:t})=>({...e,organizationId:Ue(t,"organizationId")}),http:"GET",method:"listOrgRoles"},[`${M}/users/create`]:{build:({body:e})=>({data:sn(e,"data"),email:H(e,"email"),name:H(e,"name"),password:ge(e,"password"),role:is(e.role)}),http:"POST",method:"createUser"},[`${M}/users/update`]:{build:({body:e})=>{const{data:t}=e;if(typeof t!="object"||t===null||Array.isArray(t))throw new l("`data` object is required",{code:"BAD_REQUEST",status:400});return{data:t,userId:H(e,"userId")}},http:"POST",method:"updateUser"},[`${M}/users/role`]:{build:({body:e})=>({role:Fo(e),userId:H(e,"userId")}),http:"POST",method:"setRole"},[`${M}/users/ban`]:{build:({body:e})=>({expiresInSeconds:typeof e.expiresInSeconds=="number"?e.expiresInSeconds:void 0,reason:ge(e,"reason"),userId:H(e,"userId")}),http:"POST",method:"banUser"},[`${M}/users/unban`]:{build:({body:e})=>({userId:H(e,"userId")}),http:"POST",method:"unbanUser"},[`${M}/users/password`]:{build:({body:e})=>({newPassword:H(e,"newPassword"),userId:H(e,"userId")}),http:"POST",method:"setUserPassword",returns:"void"},[`${M}/users/remove`]:{build:({body:e})=>({userId:H(e,"userId")}),http:"POST",method:"removeUser",returns:"void"},[`${M}/users/impersonate`]:{build:({body:e})=>({userId:H(e,"userId")}),http:"POST",method:"impersonateUser"},[`${M}/sessions/revoke`]:{build:({body:e})=>({sessionId:H(e,"sessionId")}),http:"POST",method:"revokeUserSession",returns:"void"},[`${M}/sessions/revoke-all`]:{build:({body:e})=>({userId:H(e,"userId")}),http:"POST",method:"revokeUserSessions",returns:"void"},[`${M}/accounts/unlink`]:{build:({body:e})=>({accountId:H(e,"accountId"),userId:H(e,"userId")}),http:"POST",method:"unlinkAccount",returns:"void"},[`${M}/two-factor/disable`]:{build:({body:e})=>({userId:H(e,"userId")}),http:"POST",method:"disableTwoFactor",returns:"void"},[`${M}/passkeys/delete`]:{build:({body:e})=>({passkeyId:H(e,"passkeyId")}),http:"POST",method:"deletePasskey",returns:"void"},[`${M}/organizations/members/remove`]:{build:({body:e})=>({memberId:H(e,"memberId")}),http:"POST",method:"removeMember",returns:"void"},[`${M}/organizations/invitations/cancel`]:{build:({body:e})=>({invitationId:H(e,"invitationId")}),http:"POST",method:"cancelInvitation",returns:"void"},[`${M}/organizations/create`]:{build:({body:e})=>({logo:ge(e,"logo"),metadata:sn(e,"metadata"),name:H(e,"name"),ownerId:ge(e,"ownerId"),slug:ge(e,"slug")}),http:"POST",method:"createOrganization"},[`${M}/organizations/update`]:{build:({body:e})=>({logo:ge(e,"logo"),metadata:sn(e,"metadata"),name:ge(e,"name"),organizationId:H(e,"organizationId"),slug:ge(e,"slug")}),http:"POST",method:"updateOrganization"},[`${M}/organizations/remove`]:{build:({body:e})=>({organizationId:H(e,"organizationId")}),http:"POST",method:"deleteOrganization",returns:"void"},[`${M}/organizations/members/add`]:{build:({body:e})=>({organizationId:H(e,"organizationId"),role:ge(e,"role"),userId:H(e,"userId")}),http:"POST",method:"addMember"},[`${M}/organizations/members/invite`]:{build:({body:e})=>({email:H(e,"email"),inviterId:ge(e,"inviterId"),organizationId:H(e,"organizationId"),role:ge(e,"role")}),http:"POST",method:"inviteMember"},[`${M}/organizations/members/role`]:{build:({body:e})=>({memberId:H(e,"memberId"),role:Fo(e)}),http:"POST",method:"updateMemberRole"},[`${M}/organizations/teams/create`]:{build:({body:e})=>({name:H(e,"name"),organizationId:H(e,"organizationId")}),http:"POST",method:"createTeam"},[`${M}/organizations/teams/update`]:{build:({body:e})=>({name:H(e,"name"),teamId:H(e,"teamId")}),http:"POST",method:"updateTeam"},[`${M}/organizations/teams/remove`]:{build:({body:e})=>({teamId:H(e,"teamId")}),http:"POST",method:"removeTeam",returns:"void"},[`${M}/organizations/teams/members/add`]:{build:({body:e})=>({teamId:H(e,"teamId"),userId:H(e,"userId")}),http:"POST",method:"addTeamMember"},[`${M}/organizations/teams/members/remove`]:{build:({body:e})=>({teamMemberId:H(e,"teamMemberId")}),http:"POST",method:"removeTeamMember",returns:"void"},[`${M}/organizations/roles/create`]:{build:({body:e})=>({organizationId:H(e,"organizationId"),permission:Wo(e),role:H(e,"role")}),http:"POST",method:"createOrgRole"},[`${M}/organizations/roles/update`]:{build:({body:e})=>({permission:Wo(e),roleId:H(e,"roleId")}),http:"POST",method:"updateOrgRole"},[`${M}/organizations/roles/remove`]:{build:({body:e})=>({roleId:H(e,"roleId")}),http:"POST",method:"deleteOrgRole",returns:"void"}},Pu=e=>{const t=async r=>{try{return await r()}catch(s){if(s instanceof l)throw s;const a=s,c=typeof a.code=="string"?a.code:"AUTH_ADMIN_ERROR";throw console.error("[lunora] auth admin operation failed:",s),new l("auth admin operation failed",{code:c,status:Nu[c]??500})}},n=async(r,s)=>{if(e.assertAdmin(r),ku.has(s.method)||e.assertRootAdmin(r),r.method!==s.http)throw new l(`Auth admin endpoint requires ${s.http}`,{code:"METHOD_NOT_ALLOWED",status:405});const a=e.getAuthAdmin();if(a===void 0)throw new l("auth endpoints require an `authAdmin` on the worker",{code:"AUTH_NOT_CONFIGURED",status:400});const c=a[s.method];if(c===void 0)throw new l(`auth admin does not support \`${s.method}\``,{code:"AUTH_OP_NOT_SUPPORTED",status:400});const d=new URL(r.url),h={body:s.http==="POST"?await e.readJsonBody(r):{},paging:e.parsePaging(r),query:g=>e.queryParameter(d,g)},p=s.build(h),w=await t(()=>c(p));return Response.json(s.returns==="void"?{ok:!0}:w,{headers:{"cache-control":"no-store","content-type":"application/json"},status:200})},o={};for(const[r,s]of Object.entries(Du))o[r]=a=>n(a,s);return o},Uu="__lunora_admin__:getAuthAuditLog",Qo=e=>typeof e=="string"&&e!==""?e:void 0,Vo=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0,Cu=e=>async(n,o)=>{e.assertAdmin(n);const r=e.getReader();if(r===void 0)throw new l("the auth/security audit endpoint requires an `authAuditReader` on the worker",{code:"AUTH_AUDIT_NOT_CONFIGURED",status:400});const s=Qo(o.actorId),a=Qo(o.event),c=Vo(o.sinceSeq),d=Vo(o.limit),h={...s===void 0?{}:{actorId:s},...a===void 0?{}:{event:a},...c===void 0?{}:{sinceSeq:c},...d===void 0?{}:{limit:d}};let p;try{p=await r.read(h)}catch(g){throw g instanceof l?g:(console.error("[lunora] auth audit read failed:",g),new l("auth audit read failed",{code:"AUTH_AUDIT_READ_FAILED",status:500}))}const w={entries:p};return Response.json({result:Re(w)},{headers:{"content-type":"application/json"},status:200})},zo="__lunora_admin__:copyAuthToJurisdiction",Lu="__lunora_admin__:purgeUnpinnedAuth",$u=e=>async(t,n,o)=>{if(n!==zo&&n!==Lu)return;e.assertAdmin(t);const r=e.getMove();if(r===void 0)throw new l("moving auth into the jurisdiction needs DO-backed auth pinned with `.jurisdiction(…, { pinAuth: true })`",{code:"AUTH_MOVE_NOT_CONFIGURED",status:400});const s=n===zo?await r.copy({force:o.force===!0}):await r.purge();return Response.json({result:Re(s)},{headers:{"content-type":"application/json"},status:200})},cs=e=>`${JSON.stringify({end:!0,rows:e})}
34
+ `},_u="__lunora_admin__:aiChat",bu="__lunora_admin__:aiAvailable",Su=new Set(["__lunora_admin__:aiChartConfig","__lunora_admin__:aiCronExpression","__lunora_admin__:aiGenerateSql","__lunora_admin__:aiNameQuery","__lunora_admin__:aiTableFilter","__lunora_admin__:explainIssue"]),as=60,Ko=120,Eu=e=>{if(typeof e!="object"||e===null)return;const{columns:t,table:n}=e;if(!(typeof n!="string"||n===""||!Array.isArray(t)))return{columns:t.slice(0,ns).filter(o=>typeof o=="string").map(o=>o.slice(0,Ko)),table:n.slice(0,Ko)}},Au={describeTables:"__lunora_admin__:describeTables",readAdvisors:"__lunora_admin__:getAdvisories",readLogs:"__lunora_admin__:getLogs",readPolicies:"__lunora_admin__:rlsPolicies",runSql:"__lunora_admin__:runSql"},Tu="__lunora_admin__:listTables",Ru=(e,t,n,o,r)=>{const s=async(c,d,h)=>{const p=await e(o,c,d,t,await n(),void 0,h);if(!p.ok)return{error:`the tool call failed (${p.status.toString()})`};const w=await p.json();return It(w.result)},a=async c=>{if(r.length>0)return r.map(h=>h.table);const d=await s(Tu,{},c);return Array.isArray(d)?d.map(h=>h.name).filter(h=>typeof h=="string").slice(0,as):[]};return async(c,d)=>{const h=Au[c.name];return c.name==="describeTables"?s(h,{tables:await a(d)},d):s(h,c.sql===void 0?{}:{sql:c.sql},d)}},vu=e=>async(n,o,r)=>{e.assertAdmin(n);const s=e.getBinding(r),a=o.schema,c=o.shardKey,d=typeof c=="string"&&c!==""?c:e.defaultShardKey();if(d.includes(Nt)||d.includes(Dt))throw new l("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403});const h={approval:o.approval,approvalSecret:e.approvalSecret(r),knowledge:o.knowledge,...typeof o.model=="string"?{model:o.model}:{},prompt:o.prompt,shardKey:d,transcript:o.transcript},p=Array.isArray(a)?a.slice(0,as).map(S=>Eu(S)).filter(S=>S!==void 0):[],w=e.optInLevel(r),g=s===void 0||w==="disabled"||e.forwardToShard===void 0?void 0:await(async()=>{const{forward:S,headers:k}=await e.forwardToShard(n,r);if(k.authorization===void 0&&k[Rt]===void 0)return;const{resolveToolHeaders:A}=e;return Ru(S,d,async()=>A===void 0?k:A(k),n,p)})(),v=new TextEncoder,E=new AbortController,b=()=>{E.abort()};n.signal.aborted?b():n.signal.addEventListener("abort",b,{once:!0});const _=new ReadableStream({cancel(){b()},async start(S){let k=!0;const A=(U,R)=>{if(k)try{S.enqueue(v.encode(yu(U,R)))}catch{k=!1}};try{const U=await wu(s,h,p,w,g,R=>{A(R)},E.signal);E.signal.aborted||A({result:Re(U)},"complete")}catch{A({code:"AI_CHAT_FAILED",message:"the assistant turn failed"},"error")}finally{n.signal.removeEventListener("abort",b);try{S.close()}catch{}}}});return new Response(_,{headers:gu,status:200})},Ou=e=>(n,o,r)=>{e.assertAdmin(n);const s=e.optInLevel(r),a={available:s!=="disabled"&&e.getBinding(r)!==void 0,level:s};return Promise.resolve(Response.json({result:Re(a)},{headers:{"content-type":"application/json"},status:200}))},Iu=e=>(t,n,o)=>{if(!(!Su.has(n)||e.optInLevel(o)!=="disabled"))return e.assertAdmin(t),Response.json({result:Re({degraded:!0,reason:"no-ai-binding"})},{headers:{"content-type":"application/json"},status:200})},M="/_lunora/admin/auth",ku=new Set(["banUser","cancelInvitation","capabilities","config","deleteApiKey","listAccounts","listApiKeys","listInvitations","listMembers","listOrganizations","listOrgRoles","listPasskeys","listSessions","listSignUpInvitations","listTeamMembers","listTeams","listUsers","revokeSignUpInvitation","revokeUserSession","revokeUserSessions"]),Nu={API_KEY_NOT_FOUND:404,API_KEY_STORAGE_UNSUPPORTED:409,INVITER_REQUIRED:400,LAST_ORGANIZATION_OWNER:409,MEMBERSHIP_CHANGED:409,ORG_SLUG_INVALID:400,ORG_SLUG_TAKEN:409,PASSWORD_TOO_LONG:400,PASSWORD_TOO_SHORT:400,USER_ALREADY_EXISTS:409,USER_NOT_FOUND:404},H=(e,t)=>{const n=e[t];if(typeof n!="string"||n==="")throw new l(`\`${t}\` is required`,{code:"BAD_REQUEST",status:400});return n},Ue=(e,t)=>{const n=e(t);if(n===void 0)throw new l(`\`${t}\` query parameter is required`,{code:"BAD_REQUEST",status:400});return n},is=e=>{if(typeof e=="string"||Array.isArray(e)&&e.every(t=>typeof t=="string"))return e},ge=(e,t)=>typeof e[t]=="string"?e[t]:void 0,sn=(e,t)=>{const n=e[t];return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:void 0},Fo=e=>{const t=is(e.role);if(t===void 0||typeof t=="string"&&t.trim()==="")throw new l("`role` is required",{code:"BAD_REQUEST",status:400});return t},Wo=e=>{const t=e.permission;if(typeof t!="object"||t===null||Array.isArray(t))throw new l("`permission` object is required",{code:"BAD_REQUEST",status:400});const n={};for(const[o,r]of Object.entries(t))Array.isArray(r)&&r.every(s=>typeof s=="string")&&(n[o]=r);return n},Du={[`${M}/capabilities`]:{build:()=>({}),http:"GET",method:"capabilities"},[`${M}/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"},[`${M}/sessions`]:{build:({paging:e,query:t})=>({...e,userId:t("userId")}),http:"GET",method:"listSessions"},[`${M}/accounts`]:{build:({query:e})=>({userId:Ue(e,"userId")}),http:"GET",method:"listAccounts"},[`${M}/passkeys`]:{build:({query:e})=>({userId:Ue(e,"userId")}),http:"GET",method:"listPasskeys"},[`${M}/api-keys`]:{build:({query:e})=>({userId:Ue(e,"userId")}),http:"GET",method:"listApiKeys"},[`${M}/api-keys/delete`]:{build:({body:e})=>({apiKeyId:H(e,"apiKeyId")}),http:"POST",method:"deleteApiKey",returns:"void"},[`${M}/organizations`]:{build:({paging:e})=>({...e}),http:"GET",method:"listOrganizations"},[`${M}/organizations/members`]:{build:({paging:e,query:t})=>({...e,organizationId:Ue(t,"organizationId")}),http:"GET",method:"listMembers"},[`${M}/organizations/invitations`]:{build:({paging:e,query:t})=>({...e,organizationId:Ue(t,"organizationId")}),http:"GET",method:"listInvitations"},[`${M}/sign-up-invitations`]:{build:({paging:e})=>({...e}),http:"GET",method:"listSignUpInvitations"},[`${M}/sign-up-invitations/create`]:{build:({body:e})=>({email:H(e,"email"),expiresInSeconds:typeof e.expiresInSeconds=="number"?e.expiresInSeconds:void 0,invitedBy:ge(e,"invitedBy")}),http:"POST",method:"createSignUpInvitation"},[`${M}/sign-up-invitations/revoke`]:{build:({body:e})=>({email:H(e,"email")}),http:"POST",method:"revokeSignUpInvitation",returns:"void"},[`${M}/config`]:{build:()=>({}),http:"GET",method:"config"},[`${M}/organizations/teams`]:{build:({paging:e,query:t})=>({...e,organizationId:Ue(t,"organizationId")}),http:"GET",method:"listTeams"},[`${M}/organizations/teams/members`]:{build:({paging:e,query:t})=>({...e,teamId:Ue(t,"teamId")}),http:"GET",method:"listTeamMembers"},[`${M}/organizations/roles`]:{build:({paging:e,query:t})=>({...e,organizationId:Ue(t,"organizationId")}),http:"GET",method:"listOrgRoles"},[`${M}/users/create`]:{build:({body:e})=>({data:sn(e,"data"),email:H(e,"email"),name:H(e,"name"),password:ge(e,"password"),role:is(e.role)}),http:"POST",method:"createUser"},[`${M}/users/update`]:{build:({body:e})=>{const{data:t}=e;if(typeof t!="object"||t===null||Array.isArray(t))throw new l("`data` object is required",{code:"BAD_REQUEST",status:400});return{data:t,userId:H(e,"userId")}},http:"POST",method:"updateUser"},[`${M}/users/role`]:{build:({body:e})=>({role:Fo(e),userId:H(e,"userId")}),http:"POST",method:"setRole"},[`${M}/users/ban`]:{build:({body:e})=>({expiresInSeconds:typeof e.expiresInSeconds=="number"?e.expiresInSeconds:void 0,reason:ge(e,"reason"),userId:H(e,"userId")}),http:"POST",method:"banUser"},[`${M}/users/unban`]:{build:({body:e})=>({userId:H(e,"userId")}),http:"POST",method:"unbanUser"},[`${M}/users/password`]:{build:({body:e})=>({newPassword:H(e,"newPassword"),userId:H(e,"userId")}),http:"POST",method:"setUserPassword",returns:"void"},[`${M}/users/remove`]:{build:({body:e})=>({userId:H(e,"userId")}),http:"POST",method:"removeUser",returns:"void"},[`${M}/users/impersonate`]:{build:({body:e})=>({userId:H(e,"userId")}),http:"POST",method:"impersonateUser"},[`${M}/sessions/revoke`]:{build:({body:e})=>({sessionId:H(e,"sessionId")}),http:"POST",method:"revokeUserSession",returns:"void"},[`${M}/sessions/revoke-all`]:{build:({body:e})=>({userId:H(e,"userId")}),http:"POST",method:"revokeUserSessions",returns:"void"},[`${M}/accounts/unlink`]:{build:({body:e})=>({accountId:H(e,"accountId"),userId:H(e,"userId")}),http:"POST",method:"unlinkAccount",returns:"void"},[`${M}/two-factor/disable`]:{build:({body:e})=>({userId:H(e,"userId")}),http:"POST",method:"disableTwoFactor",returns:"void"},[`${M}/passkeys/delete`]:{build:({body:e})=>({passkeyId:H(e,"passkeyId")}),http:"POST",method:"deletePasskey",returns:"void"},[`${M}/organizations/members/remove`]:{build:({body:e})=>({memberId:H(e,"memberId")}),http:"POST",method:"removeMember",returns:"void"},[`${M}/organizations/invitations/cancel`]:{build:({body:e})=>({invitationId:H(e,"invitationId")}),http:"POST",method:"cancelInvitation",returns:"void"},[`${M}/organizations/create`]:{build:({body:e})=>({logo:ge(e,"logo"),metadata:sn(e,"metadata"),name:H(e,"name"),ownerId:ge(e,"ownerId"),slug:ge(e,"slug")}),http:"POST",method:"createOrganization"},[`${M}/organizations/update`]:{build:({body:e})=>({logo:ge(e,"logo"),metadata:sn(e,"metadata"),name:ge(e,"name"),organizationId:H(e,"organizationId"),slug:ge(e,"slug")}),http:"POST",method:"updateOrganization"},[`${M}/organizations/remove`]:{build:({body:e})=>({organizationId:H(e,"organizationId")}),http:"POST",method:"deleteOrganization",returns:"void"},[`${M}/organizations/members/add`]:{build:({body:e})=>({organizationId:H(e,"organizationId"),role:ge(e,"role"),userId:H(e,"userId")}),http:"POST",method:"addMember"},[`${M}/organizations/members/invite`]:{build:({body:e})=>({email:H(e,"email"),inviterId:ge(e,"inviterId"),organizationId:H(e,"organizationId"),role:ge(e,"role")}),http:"POST",method:"inviteMember"},[`${M}/organizations/members/role`]:{build:({body:e})=>({memberId:H(e,"memberId"),role:Fo(e)}),http:"POST",method:"updateMemberRole"},[`${M}/organizations/teams/create`]:{build:({body:e})=>({name:H(e,"name"),organizationId:H(e,"organizationId")}),http:"POST",method:"createTeam"},[`${M}/organizations/teams/update`]:{build:({body:e})=>({name:H(e,"name"),teamId:H(e,"teamId")}),http:"POST",method:"updateTeam"},[`${M}/organizations/teams/remove`]:{build:({body:e})=>({teamId:H(e,"teamId")}),http:"POST",method:"removeTeam",returns:"void"},[`${M}/organizations/teams/members/add`]:{build:({body:e})=>({teamId:H(e,"teamId"),userId:H(e,"userId")}),http:"POST",method:"addTeamMember"},[`${M}/organizations/teams/members/remove`]:{build:({body:e})=>({teamMemberId:H(e,"teamMemberId")}),http:"POST",method:"removeTeamMember",returns:"void"},[`${M}/organizations/roles/create`]:{build:({body:e})=>({organizationId:H(e,"organizationId"),permission:Wo(e),role:H(e,"role")}),http:"POST",method:"createOrgRole"},[`${M}/organizations/roles/update`]:{build:({body:e})=>({permission:Wo(e),roleId:H(e,"roleId")}),http:"POST",method:"updateOrgRole"},[`${M}/organizations/roles/remove`]:{build:({body:e})=>({roleId:H(e,"roleId")}),http:"POST",method:"deleteOrgRole",returns:"void"}},Pu=e=>{const t=async r=>{try{return await r()}catch(s){if(s instanceof l)throw s;const a=s,c=typeof a.code=="string"?a.code:"AUTH_ADMIN_ERROR";throw console.error("[lunora] auth admin operation failed:",s),new l("auth admin operation failed",{code:c,status:Nu[c]??500})}},n=async(r,s)=>{if(e.assertAdmin(r),ku.has(s.method)||e.assertRootAdmin(r),r.method!==s.http)throw new l(`Auth admin endpoint requires ${s.http}`,{code:"METHOD_NOT_ALLOWED",status:405});const a=e.getAuthAdmin();if(a===void 0)throw new l("auth endpoints require an `authAdmin` on the worker",{code:"AUTH_NOT_CONFIGURED",status:400});const c=a[s.method];if(c===void 0)throw new l(`auth admin does not support \`${s.method}\``,{code:"AUTH_OP_NOT_SUPPORTED",status:400});const d=new URL(r.url),h={body:s.http==="POST"?await e.readJsonBody(r):{},paging:e.parsePaging(r),query:g=>e.queryParameter(d,g)},p=s.build(h),w=await t(()=>c(p));return Response.json(s.returns==="void"?{ok:!0}:w,{headers:{"cache-control":"no-store","content-type":"application/json"},status:200})},o={};for(const[r,s]of Object.entries(Du))o[r]=a=>n(a,s);return o},Uu="__lunora_admin__:getAuthAuditLog",Qo=e=>typeof e=="string"&&e!==""?e:void 0,Vo=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0,Cu=e=>async(n,o)=>{e.assertAdmin(n);const r=e.getReader();if(r===void 0)throw new l("the auth/security audit endpoint requires an `authAuditReader` on the worker",{code:"AUTH_AUDIT_NOT_CONFIGURED",status:400});const s=Qo(o.actorId),a=Qo(o.event),c=Vo(o.sinceSeq),d=Vo(o.limit),h={...s===void 0?{}:{actorId:s},...a===void 0?{}:{event:a},...c===void 0?{}:{sinceSeq:c},...d===void 0?{}:{limit:d}};let p;try{p=await r.read(h)}catch(g){throw g instanceof l?g:(console.error("[lunora] auth audit read failed:",g),new l("auth audit read failed",{code:"AUTH_AUDIT_READ_FAILED",status:500}))}const w={entries:p};return Response.json({result:Re(w)},{headers:{"content-type":"application/json"},status:200})},zo="__lunora_admin__:copyAuthToJurisdiction",Lu="__lunora_admin__:purgeUnpinnedAuth",$u=e=>async(t,n,o)=>{if(n!==zo&&n!==Lu)return;e.assertAdmin(t);const r=e.getMove();if(r===void 0)throw new l("moving auth into the jurisdiction needs DO-backed auth pinned with `.jurisdiction(…, { pinAuth: true })`",{code:"AUTH_MOVE_NOT_CONFIGURED",status:400});const s=n===zo?await r.copy({force:o.force===!0}):await r.purge();return Response.json({result:Re(s)},{headers:{"content-type":"application/json"},status:200})},cs=e=>`${JSON.stringify({end:!0,rows:e})}
35
35
  `,Mu=e=>{if(e===null||typeof e!="object"||Array.isArray(e))return;const t=e;if(!(t.end!==!0||t.table!==void 0))return typeof t.rows=="number"&&Number.isSafeInteger(t.rows)&&t.rows>=0?t.rows:Number.NaN},Bu=(e,t)=>{const n=[],o=[];if(t&&t.length>0)for(const r of t)e.resolveTableSharding?.(r)?.mode.kind==="global"?o.push(r):n.push(r);return{globalTables:o,shardLocalTables:n}},xu=async(e,t,n,o,r,s)=>{if(n!==void 0&&o.length===0)return[];const a=await e.orchestrateExport(r,{args:{tables:o},defaultShardKey:s,headers:t,tables:o}),c=a.shards.filter(d=>d.error);if(c.length>0){const d=c.map(h=>`${h.shardKey}: ${h.error?.message??"unknown error"}`).join("; ");throw new l(`export failed on ${String(c.length)} of ${String(a.shards.length)} shard(s) — ${d}`,{code:"EXPORT_SHARD_FAILED",status:502})}return a.shards.flatMap(d=>d.rows??[])},ds=async(e,t,n,o,r)=>{const s=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:a,shardLocalTables:c}=Bu(e,s),d=await xu(t,n,s,c,r,e.defaultShardKey??"__root__"),h=e.exportGlobals,p=o===void 0||a.length>0;return(async function*(){yield*d,p&&h&&(yield*h({tables:a}))})()},Hu=async(e,t,n,o,r,s)=>{for await(const a of await ds(e,t,n,o,s))r(a)},Jo=new TextEncoder,ju=1e3,us=10,Gu=200,Yo=8,ls="lunoraBackupCron",En=24*1048576,Xo=e=>new l(`scheduled backup reached ${String(e)} bytes of NDJSON, past the ${String(En)}-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}),qo=e=>{const t=e.slice(0,us).map(o=>Br(o)),n=e.length-t.length;return`${t.join(", ")}${n>0?` (+${String(n)} more)`:""}`},Ku=(e,t)=>{const n=new Uint8Array(new ArrayBuffer(t));let o=0;for(const r of e)n.set(r,o),o+=r.byteLength;return n},Ln=async(e,t,n,o)=>{if(n===void 0||!Number.isInteger(n)||n<=0)return{eligible:0,stale:[]};const r=[];let s;for(let a=0;a<ju;a+=1){const c=await e.list({cursor:s,include:["customMetadata"],prefix:t});for(const d of c.objects)Pi(d.key)&&d.customMetadata?.[ls]===o&&r.push(d.key);if(!c.truncated||c.cursor===void 0)break;s=c.cursor}return{eligible:r.length,stale:r.toSorted((a,c)=>c.localeCompare(a)).slice(n)}},Fu=async(e,t,n,o,r)=>{const{stale:s}=await Ln(e,t,n,o),a=new Set(r),c=s.filter(v=>a.has(v)),d=c.slice(0,Gu),h=s.length-d.length,p=r.length-c.length;if(d.length===0)return{deleted:[],failed:[],ignored:p,remaining:h};const w=[],g=[];for(let v=0;v<d.length;v+=Yo){const E=await Promise.allSettled(d.slice(v,v+Yo).map(async b=>(await e.delete(Br(b)),await e.delete(b),b)));for(const[b,_]of E.entries())_.status==="fulfilled"?w.push(_.value):g.push(d[v+b])}return w.length>0&&console.info(`[lunora] backup prune kept the newest ${String(n)} and deleted ${String(w.length)}: ${qo(w)}`),g.length>0&&console.warn(`[lunora] backup prune failed to remove ${String(g.length)}: ${qo(g)}`),{deleted:w,failed:g,ignored:p,remaining:h}},Wu=async e=>{const t=e.backupStore;if(!t)throw new l("backup retention preview requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});const n=Pn(e.backupPrefix??Un),o=e.backupCron,{eligible:r,stale:s}=o===void 0?{eligible:0,stale:[]}:await Ln(t,n,e.backupRetain,o);return{cron:o,eligible:r,keep:e.backupRetain??0,prefix:n,wouldDelete:s}},Qu=async(e,t,n,o,r)=>{const s=e.backupStore;if(!s)throw new l("scheduled backup requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});if(!o||o.length===0)throw new l("scheduled backup requires an `adminToken` (or `env.LUNORA_ADMIN_TOKEN`) to authenticate the per-shard export gate",{code:"BACKUP_NOT_CONFIGURED",status:500});const a={authorization:`Bearer ${o}`,"content-type":"application/json"},c=e.backupTables;let d=0,h=0,p=[];await Hu(e,t,a,c,A=>{const U=Jo.encode(`${JSON.stringify(A)}
36
36
  `);if(d+=1,h+=U.byteLength,h>En)throw Xo(h);p.push(U)},n);const g=Jo.encode(cs(d));if(h+=g.byteLength,h>En)throw Xo(h);p.push(g);const v=Pn(e.backupPrefix??Un),E=new Date(r.scheduledTime).toISOString(),b=Ui(v,E),_=Ku(p,h);p=[];const S=Ze(await crypto.subtle.digest("SHA-256",_));await s.put(b,_,{httpMetadata:{contentType:"application/x-ndjson"},sha256:S});const k={bytes:h,createdAt:E,cron:r.cron,file:b,id:E,rows:d,scheduledTime:r.scheduledTime,sha256:S,...c?{tables:c.join(",")}:{}};await s.put(Ci(b),`${JSON.stringify(k,void 0,2)}
37
37
  `,{customMetadata:{[ls]:r.cron},httpMetadata:{contentType:"application/json"}});try{const{stale:A}=await Ln(s,v,e.backupRetain,r.cron);if(A.length>0){const U=A.slice(0,us),R=A.length-U.length;console.info(`[lunora] backup retention: ${String(A.length)} snapshot(s) past the newest ${String(e.backupRetain)} — run \`lunora backup prune\` to remove them: ${U.join(", ")}${R>0?` (+${String(R)} more)`:""}`)}}catch(A){console.warn(`[lunora] backup ${b} was written, but the retention report failed:`,A)}},Vu=async(e,t)=>{const n=e.backupStore;if(!n)throw new l("backup prune requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});const o=e.backupCron,r=e.backupRetain;if(o===void 0||r===void 0||!Number.isInteger(r)||r<=0)throw new l("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 Fu(n,Pn(e.backupPrefix??Un),r,o,t)},zu="/_lunora/admin/backup/retention",Ju="/_lunora/admin/backup/prune",Yu=e=>{const{options:t,readJsonBody:n,requireAdminOption:o}=e,r=(c,d)=>{o(c,t.backupStore,{code:"BACKUP_NOT_CONFIGURED",message:`backup ${d} requires a \`backupStore\` on the worker`})},s=async c=>(Y(c,"GET","Backup-retention"),r(c,"retention preview"),Response.json(await Wu(t),{headers:{"cache-control":"no-store"}})),a=async c=>{Y(c,"POST","Backup-prune"),r(c,"prune");const{confirm:d}=await n(c);if(!Array.isArray(d)||d.some(h=>typeof h!="string"))throw new l("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 Vu(t,d),{headers:{"cache-control":"no-store"}})};return{[Ju]:a,[zu]:s}},Zo=500,Xu=(e,t,n)=>{if(typeof e!="object"||e===null||Array.isArray(e))throw new l("each batch call must be an object",{code:"BAD_REQUEST",status:400});const o=e;if(typeof o.functionPath!="string")throw new l("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 l("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 l("each batch call `args` must be an object",{code:"BAD_REQUEST",status:400});if(o.id!==void 0&&typeof o.id!="number")throw new l("each batch call `id` must be a number",{code:"BAD_REQUEST",status:400});return{entry:{args:o.args===void 0?{}:o.args,baselineSeq:typeof o.baselineSeq=="number"?o.baselineSeq:void 0,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}},qu=(e,t)=>{if(e.length>Zo)throw new l(`RPC batch exceeds the ${String(Zo)}-call limit`,{code:"BAD_REQUEST",status:400});const n=new Map,o=new Set;for(const[r,s]of e.entries()){const{entry:a,shardKey:c}=Xu(s,r,t);if(o.has(a.id))throw new l(`batch call id ${String(a.id)} is used twice; ids must be distinct`,{code:"BAD_REQUEST",status:400});o.add(a.id);const d=n.get(c)??[];d.push(a),n.set(c,d)}return n},Zu=3e5,$t=e=>e instanceof Error?e.message:JSON.stringify(e),$n=async(e,t,n)=>{const o=await e.fetch(new Request(`https://scheduler.internal${t}`,{body:JSON.stringify(n),headers:{"content-type":"application/json"},method:"POST"}));if(!o.ok)throw new Error(`SchedulerDO ${t} answered ${String(o.status)}`);return o.json()},el=(e,t,n)=>{const o=setInterval(()=>{$n(e,"/cron/renew",{name:t,runId:n}).then(r=>{r.renewed===!1&&clearInterval(o)}).catch(r=>{console.warn(`[lunora] cron job "${t}" could not renew its lease: ${$t(r)}`)})},Zu);return o},er=async(e,t)=>{if(e===void 0)return{skip:!1};try{const n=await $n(e,"/cron/begin",{name:t});if(n.acquired===!1)return{reason:typeof n.reason=="string"?n.reason:"in-flight",skip:!0};const o=typeof n.runId=="string"?n.runId:void 0;return o===void 0?{skip:!1}:{renewal:el(e,t,o),runId:o,skip:!1}}catch(n){return console.warn(`[lunora] cron job "${t}" runs without its overlap guard: ${$t(n)}`),{skip:!1}}},gt=async(e,t,n,o)=>{if(!(e===void 0||n.skip||n.runId===void 0)){clearInterval(n.renewal);try{await $n(e,"/cron/end",{name:t,runId:n.runId,...o===void 0?{status:"succeeded"}:{error:$t(o),status:"failed"}})}catch(r){console.warn(`[lunora] cron job "${t}" ran but its outcome was not recorded: ${$t(r)}`)}}},Mt="_lunora/restore/",tl=1440*60*1e3,hs=9999999999999,nl=/^[\da-f]{64}\/(\d{13})\//u,ol=5*1024*1024,rl=1e4,sl=1e3,Je=12,tr=new Map,fs=async e=>{let t=tr.get(e);return t===void 0&&(t=(async()=>{const n=await crypto.subtle.importKey("raw",new TextEncoder().encode(e),"HKDF",!1,["deriveKey"]);return crypto.subtle.deriveKey({hash:"SHA-256",info:new TextEncoder().encode("restore-staging"),name:"HKDF",salt:new TextEncoder().encode("lunora")},n,{length:256,name:"AES-GCM"},!1,["encrypt","decrypt"])})(),tr.set(e,t)),t},Mn=async(e,t,n)=>{const o=crypto.getRandomValues(new Uint8Array(Je)),r=await crypto.subtle.encrypt({additionalData:new TextEncoder().encode(t),iv:o,name:"AES-GCM"},await fs(e),n),s=new Uint8Array(Je+r.byteLength);return s.set(o),s.set(new Uint8Array(r),Je),s.buffer},ps=async(e,t,n)=>{if(!(n.byteLength<=Je))try{const o=await crypto.subtle.decrypt({additionalData:new TextEncoder().encode(t),iv:n.subarray(0,Je),name:"AES-GCM"},await fs(e),n.subarray(Je));return new Uint8Array(o)}catch{return}},Ke=e=>{const{adminToken:t,storageDelete:n,storageDownload:o,storageList:r,storageUpload:s}=e;return n&&o&&r&&s&&t?{delete:n,download:o,list:r,secret:t,upload:s}:void 0},Ft=e=>{const{data:t,last:n,offset:o,sha256:r,size:s}=e,a=n!==!0||typeof s=="number"&&Number.isInteger(s)&&s>=0;if(typeof t!="string"||typeof o!="number"||!Number.isInteger(o)||o<0||!a)return;let c;try{c=Dr(t)}catch{return}return{bytes:c,lastSize:n===!0?s:void 0,offset:o,...typeof r=="string"?{sha256:r}:{}}},Bn=async function*(t,n,o){let r,s=!0;for(;s;){const a=await t(n,{...o,cursor:r,limit:sl});yield*a.objects,r=a.cursor,s=r!==void 0&&(a.truncated??!0)}},ms=async function*(t,n){let o=new Uint8Array(n),r=0;for await(const s of t)for(let a=0;a<s.byteLength;){const c=Math.min(n-r,s.byteLength-a);o.set(s.subarray(a,a+c),r),r+=c,a+=c,r===n&&(yield o,o=new Uint8Array(n),r=0)}r>0&&(yield o.subarray(0,r))},ws=async e=>`${Mt}${Ze(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(e)))}/`,al=(e,t)=>`${e}${String(hs-t).padStart(13,"0")}/`,gs=async(e,t,n)=>{const{objects:o}=await e.list(t,{...n,limit:1}),r=o[0]?.key,s=r?.startsWith(t)?r.indexOf("/",t.length):-1;return r===void 0||s===-1?void 0:r.slice(0,s+1)},xn=(e,t)=>`${e}${String(t).padStart(16,"0")}`,il=async(e,t,n,o)=>{const r=o.offset===0?al(t,Date.now()):await gs(e,t,n);if(r===void 0)return!1;const s=xn(r,o.offset);return await e.upload(s,await Mn(e.secret,s,o.bytes),n),!0},cl=async(e,t,n)=>{const o=[];for await(const r of Bn(e.list,t,n))o.push(r.key);await Promise.all(o.map(async r=>e.delete(r,n)))},Wt=async function*(t,n,o,r,s){const a=h=>new l(h,{code:`${s}_RESTORE_INCOMPLETE`}),c=xr.create();let d=0;if(r.offset+r.bytes.byteLength!==r.lastSize)throw a(`chunks add up to ${String(r.offset+r.bytes.byteLength)} of ${String(r.lastSize)} bytes`);for(;d<r.offset;){const h=xn(o,d),p=await t.download(h,n);if(!p?.body)throw a(`the chunk at byte ${String(d)} never arrived`);const w=await ps(t.secret,h,new Uint8Array(await new Response(p.body).arrayBuffer()));if(w===void 0)throw a(`the chunk at byte ${String(d)} was not staged by this deployment`);if(w.byteLength===0||d+w.byteLength>r.offset)throw a(`the chunk at byte ${String(d)} overlaps the last chunk`);c.update(w),yield w,d+=w.byteLength}if(c.update(r.bytes),yield r.bytes,r.sha256!==void 0&&Ze(c.digest())!==r.sha256.toLowerCase())throw new l(`the restored bytes do not match the exported sha256 ${r.sha256}`,{code:`${s}_SHA256_MISMATCH`})},Hn=(e,t)=>{if(e.bytes.byteLength!==e.lastSize)throw new l(`the record holds ${String(e.bytes.byteLength)} of ${String(e.lastSize)} bytes`,{code:`${t}_RESTORE_INCOMPLETE`});if(e.sha256!==void 0&&Ze(xr(e.bytes))!==e.sha256.toLowerCase())throw new l(`the restored bytes do not match the exported sha256 ${e.sha256}`,{code:`${t}_SHA256_MISMATCH`})},Qt=async(e,t)=>{const n=new Uint8Array(t);let o=0;for await(const r of e)n.set(r,o),o+=r.byteLength;return n},ys=async(e,t,n)=>{const o=[];try{for await(const r of ms(t,Math.max(ol,Math.ceil(n/rl))))o.push(await e.uploadPart(o.length+1,r));await e.complete(o)}catch(r){throw await e.abort().catch(()=>{}),r}},dl=e=>{const t=nl.exec(e.slice(Mt.length));return t?.[1]===void 0?void 0:hs-Number(t[1])},ul=async(e,t,n)=>{let o=0;for(const r of t){const s=r===void 0?{}:{bucket:r},a=[];for await(const{key:c}of Bn(e.list,Mt,s)){const d=dl(c);c.startsWith(Mt)&&(d===void 0||n-d>tl)&&a.push(c)}await Promise.all(a.map(async c=>e.delete(c,s))),o+=a.length}return o},An=2,Xe="$lunora",ye="$auth",_e="$kv",be="$storage",ll=new Set([ye,Xe,_e,be]),nr=["auth","kv","storage"],hl=["kv","storage"],ze=512*1024,Bt=25*1024*1024,_s="_lunora/",bs=60,fl=1e3,at=e=>e.storageBuckets!==void 0&&e.storageBuckets.length>0?e.storageBuckets:[void 0],Ss=(e,t)=>{const{bucket:n}=t.where;if(!(n===void 0||at(e).includes(n)))return`${t.key} is in the bucket "${n}", which this worker does not declare`},pl=(e,t)=>t.filter(n=>{switch(n){case"auth":return e.authData!==void 0;case"kv":return e.kvIntrospector!==void 0;case"storage":return e.storageList!==void 0&&e.storageDownload!==void 0;default:return!1}}),ml=async function*(t){const n=t.getReader();let o=!1;try{for(;;){const{done:r,value:s}=await n.read();if(r){o=!0;return}yield s}}finally{o||await n.cancel().catch(()=>{})}},wl=async function*(t){let n;for await(const o of t)n&&(yield{bytes:n,last:!1}),n=o;yield{bytes:n??new Uint8Array(0),last:!0}},Es=async function*(t,n){let o;do{const r=await t.listKeys({cursor:o,limit:fl,namespace:n});yield*r.keys,o=r.listComplete?void 0:r.cursor}while(o!==void 0)},gl=async function*(t,n,o){const r=Dr(n);if(r.byteLength<=ze){yield{doc:{...t,value:n,...o},table:_e};return}const s=Ze(await crypto.subtle.digest("SHA-256",r));for(let a=0;a<r.byteLength;a+=ze){const c=Gt(r.subarray(a,a+ze)),d=a+ze>=r.byteLength?{last:!0,sha256:s,size:r.byteLength,...o}:{};yield{doc:{...t,data:c,offset:a,...d},table:_e}}},yl=async function*(t){for(const{binding:n}of await t.listNamespaces())for await(const o of Es(t,n)){const{metadata:r,value:s}=await t.getValue({encoding:"base64",key:o.name,namespace:n});s!==null&&(yield*gl({key:o.name,namespace:n},s,{...r==null?{}:{metadata:r},...o.expiration===void 0?{}:{expiration:o.expiration}}))}},As=async function*(t,n){for await(const o of Bn(t,void 0,n===void 0?{}:{bucket:n}))o.key.startsWith(_s)||(yield o)},_l=(e,t,n)=>({last:!0,size:n,...t===void 0?{}:{contentType:t},...e.customMetadata===void 0||Object.keys(e.customMetadata).length===0?{}:{customMetadata:e.customMetadata},...e.sha256===void 0?{}:{sha256:e.sha256}}),bl=async function*(t,n,o){const r=n===void 0?{key:t.key}:{bucket:n,key:t.key},s=t.httpMetadata?.contentType??o.httpMetadata?.contentType;let a=0;for await(const{bytes:c,last:d}of wl(ms(ml(o.body),ze))){const h=d?_l(t,s,a+c.byteLength):{};yield{doc:{...r,data:Gt(c),offset:a,...h},table:be},a+=c.byteLength}},Sl=async function*(t,n,o){for(const r of o)for await(const s of As(t,r)){const a=await n(s.key,{bucket:r});a?.body&&(yield*bl(s,r,{body:a.body,httpMetadata:a.httpMetadata}))}},El=async function*(t){for await(const n of t.exportRows())yield{doc:{row:n.doc,table:n.table},table:ye}},Al=(e,t)=>{const n=pl(e,t),{authData:o,kvIntrospector:r,storageDownload:s,storageList:a}=e;return{header:n.length===0?void 0:{doc:{format:An,sections:n},table:Xe},rows:(async function*(){o&&n.includes("auth")&&(yield*El(o)),r&&n.includes("kv")&&(yield*yl(r)),a&&s&&n.includes("storage")&&(yield*Sl(a,s,at(e)))})()}},Tl=e=>{const{format:t}=e;if(typeof t!="number"||!Number.isInteger(t)||t<1||t>An)throw new l(`Import format ${JSON.stringify(t)} is not supported (this runtime reads formats 1-${String(An)})`,{code:"IMPORT_FORMAT_UNSUPPORTED",status:400})},et=(e,t,n=1)=>{e.inserted[t]=(e.inserted[t]??0)+n},jn=e=>{e.conflicts+=1},ne=(e,t,n,o)=>{e.errors.push({code:n,line:t.line,message:o,table:t.table})},Gn=e=>e instanceof Error?e.message:String(e),Kn=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Rl=async(e,t,n)=>{const o=[];for(const s of t){const{row:a,table:c}=s.doc;typeof c!="string"||!Kn(a)?ne(n,s,"BAD_ROW","an `$auth` record needs a string `table` and an object `row`"):e.authData?o.push({doc:a,row:s,table:c}):ne(n,s,"AUTH_NOT_CONFIGURED","row targets an auth table but this worker has no auth data port (`authData`)")}if(o.length===0||!e.authData)return;const r=await e.authData.importRows(o.map(({doc:s,table:a})=>({doc:s,table:a})));et(n,ye,r.inserted),n.conflicts+=r.conflicts;for(const s of r.errors){const a=o[s.index]?.row;n.errors.push({code:"AUTH_IMPORT_FAILED",line:a?.line??0,message:s.message,table:ye})}},Ts=e=>e instanceof l&&(e.code.endsWith("_RESTORE_INCOMPLETE")||e.code.endsWith("_SHA256_MISMATCH")),Rs=async(e,t,n,o,r)=>{await il(e,n.root,n.where,o)?et(r,t.table):ne(r,t,`${n.kind}_RESTORE_INCOMPLETE`,`the chunk at byte 0 never arrived, so the one at byte ${String(o.offset)} has nothing to join`)},vs=async(e,t,n,o,r,s)=>{const a=o.offset===0?void 0:await gs(e,n.root,n.where);if(o.offset>0&&a===void 0){ne(r,t,`${n.kind}_RESTORE_INCOMPLETE`,"the chunk at byte 0 never arrived");return}try{await s(Wt(e,n.where,a??"",o,n.kind))}catch(c){if(!Ts(c))throw c;ne(r,t,c.code,c.message)}a!==void 0&&await cl(e,a,n.where)},Os=async(e,t,n)=>{const{expiration:o,key:r,kv:s,metadata:a,namespace:c}=e,d=await s.getValue({key:r,namespace:c}),h=o!==void 0&&o<Math.floor(Date.now()/1e3)+bs;if(d.value!==null||h){jn(n);return}await s.putValue({encoding:"base64",key:r,namespace:c,value:t,...o===void 0?{}:{expiration:o},...a===void 0?{}:{metadata:a}}),et(n,_e)},vl=async(e,t,n,o,r,s)=>{const a=Ke(e),c=`KV value ${n.namespace}/${n.key}`;if(!a||o.offset+o.bytes.byteLength>Bt){o.lastSize!==void 0&&!a?ne(r,t,"KV_STAGING_NOT_CONFIGURED",`${c} is over ${String(ze)} bytes; its chunks are staged in the default storage bucket, and this worker has no storage ops`):o.lastSize!==void 0&&ne(r,t,"KV_VALUE_TOO_LARGE",`${c} is ${String(o.lastSize)} bytes, over KV's ${String(Bt)}`);return}const d={kind:"KV",root:await ws(`kv\0${n.namespace}\0${n.key}\0${s}`),where:{}},h=o.lastSize;await(h===void 0?Rs(a,t,d,o,r):vs(a,t,d,o,r,async p=>Os(n,Gt(await Qt(p,h)),r)))},Ol=async(e,t,n,o)=>{const r=e.kvIntrospector,{expiration:s,key:a,metadata:c,namespace:d,value:h}=t.doc;if(!r){ne(n,t,"KV_NOT_CONFIGURED","row targets a KV namespace but this worker has no `kvIntrospector`");return}if(typeof d!="string"||typeof a!="string"){ne(n,t,"BAD_ROW","a `$kv` record needs a string `namespace` and `key`");return}const p=h===void 0?Ft(t.doc):void 0;if(typeof h!="string"&&!p||s!==void 0&&typeof s!="number"){ne(n,t,"BAD_ROW","a `$kv` record needs a base64 string `value` (or a chunk's `data` and `offset`) and a numeric `expiration` if any");return}const w={expiration:s,key:a,kv:r,metadata:c,namespace:d};try{typeof h=="string"?await Os(w,h,n):p&&await vl(e,t,w,p,n,o)}catch(g){ne(n,t,"KV_IMPORT_FAILED",`KV ${d}/${a}: ${Gn(g)}`)}},Il=8192,kl=e=>{if(!Kn(e))return!1;const t=new TextEncoder;let n=0;for(const[o,r]of Object.entries(e)){if(typeof r!="string")return!1;n+=t.encode(o).byteLength+t.encode(r).byteLength}return n<=Il},Fn=e=>{const{bucket:t,contentType:n,customMetadata:o,key:r}=e,s=Ft(e);if(typeof r!="string"||r.startsWith(_s)||!s||t!==void 0&&typeof t!="string")return;const a=o===void 0||kl(o)?o:!1;if(a===!1)return;const c=t===void 0?{}:{bucket:t};return{...s,key:r,upload:{...c,...typeof n=="string"?{contentType:n}:{},...a===void 0?{}:{customMetadata:a},...s.sha256===void 0?{}:{sha256:s.sha256}},where:c}},Is=async(e,t)=>{const n=await e.storageDownload?.(t.key,t.where);return await n?.body?.cancel(),n!=null},Nl=async(e,t,n,o,r,s)=>{const a=o.lastSize??0,c=a>Le?e.storageMultipartUpload:void 0;if(a>Le&&!c){ne(s,n,"STORAGE_OBJECT_TOO_LARGE",`${o.key} is ${String(a)} bytes; restoring an object over ${String(Le)} bytes needs \`storageMultipartUpload\` on the worker (the export holds it)`);return}await vs(t,n,r,o,s,async d=>{if(await Is(e,o)){jn(s);return}if(c){const{contentType:h,customMetadata:p}=o.upload;await ys(await c(o.key,{...o.where,contentType:h,customMetadata:p}),d,a)}else{const h=await Qt(d,a);await t.upload(o.key,h.buffer,o.upload)}et(s,be)})},Dl=async(e,t,n,o,r)=>{try{Hn(n,"STORAGE")}catch(s){if(!Ts(s))throw s;ne(o,t,s.code,s.message);return}await Is(e,n)?jn(o):(await r(n.key,n.bytes.buffer,n.upload),et(o,be))},Pl=async(e,t,n,o,r)=>{const s=e.storageUpload;if(!s){ne(o,t,"STORAGE_NOT_CONFIGURED","row targets a storage bucket but this worker has no `storageUpload`");return}if(n.offset===0&&n.lastSize!==void 0){await Dl(e,t,n,o,s);return}const a=Ke(e);if(!a){n.lastSize!==void 0&&ne(o,t,"STORAGE_NOT_CONFIGURED","restoring a multi-chunk object needs `storageUpload`, `storageDownload`, `storageList` and `storageDelete` on the worker");return}const c={kind:"STORAGE",root:await ws(`storage\0${n.where.bucket??""}\0${n.key}\0${r}`),where:n.where};n.lastSize!==void 0?await Nl(e,a,t,n,c,o):(e.storageMultipartUpload||n.offset+n.bytes.byteLength<=Le)&&await Rs(a,t,c,n,o)},Ul=async(e,t,n,o)=>{const r=Fn(t.doc);if(!r){ne(n,t,"BAD_ROW","a `$storage` record needs a string `key` outside `_lunora/` and base64 `data`, an integer `offset`, a `size` on its last chunk, and string `customMetadata` within 8,192 bytes if any");return}const s=Ss(e,r);if(s!==void 0){ne(n,t,"BAD_ROW",s);return}try{await Pl(e,t,r,n,o)}catch(a){ne(n,t,"STORAGE_IMPORT_FAILED",`${r.key}: ${Gn(a)}`)}},Cl=async(e,t,n)=>{const o=Ke(e);if(o)try{await ul(o,at(e),Date.now())}catch(r){ne(n,t,"RESTORE_STAGING_SWEEP_FAILED",`could not delete stale staged chunks: ${Gn(r)}`)}},Ll=async(e,t,n)=>{const o={conflicts:0,errors:[],inserted:{}};await Rl(e,t.filter(r=>r.table===ye),o);for(const r of t)switch(r.table){case Xe:{et(o,Xe),await Cl(e,r,o);break}case _e:{await Ol(e,r,o,n);break}case be:{await Ul(e,r,o,n);break}}return o},$l=e=>ll.has(e),Ml="/_lunora/admin/export",Bl="/_lunora/admin/import",xl="/_lunora/admin/import/commit",Hl="/_lunora/admin/import/abort",jl="/_lunora/admin/sync",Gl="/_lunora/admin/connector/sync",Kl="/_lunora/admin/apply",Fl="/_lunora/admin/export-tap/run",or=new TextEncoder,Wl=e=>{if(e!==void 0){if(!Array.isArray(e)||e.some(t=>!nr.includes(t)))throw new l(`Export \`sections\` must be an array of ${nr.map(t=>`"${t}"`).join(", ")}`,{code:"BAD_REQUEST",status:400});return e}},Ql=async e=>{const n=await pe(e,"Export")??{},o=Wl(n.sections);if(n.tables===void 0)return{sections:o,tables:void 0};if(!Array.isArray(n.tables))throw new l("Export `tables` must be a string array",{code:"BAD_REQUEST",status:400});const r=[];for(const s of n.tables){if(typeof s!="string"||s.length===0)throw new l("Export `tables` entries must be non-empty strings",{code:"BAD_REQUEST",status:400});r.push(s)}return{sections:o,tables:r}},an=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):void 0,Vl=e=>{const{applyGlobals:t,defaultShardKey:n,exportCursorStore:o,exportSectionRows:r,exportSinks:s,importSession:a,knownTables:c,queryCoordinator:d,assertAdmin:h,resolveForwardContext:p,shardDO:w,prepareExportRows:g,streamingImport:v,syncGlobals:E}=e,b=async(L,V)=>{const j=Oe(L,["POST"]);if(j)return j;h(L);const $=await Ql(L),{headers:F}=await p(L,V),W=await g(F,$.tables),K=r($.sections??($.tables===void 0?hl:[])),se=(async function*(){K.header&&(yield K.header),yield*W,yield*K.rows})()[Symbol.asyncIterator]();let ce=0;const Z=new ReadableStream({async cancel(){await se.return(void 0)},async pull(we){try{const de=await se.next();de.done?(we.enqueue(or.encode(cs(ce))),we.close()):(ce+=1,we.enqueue(or.encode(`${JSON.stringify(de.value)}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/runtime",
3
- "version": "1.0.0-alpha.293",
3
+ "version": "1.0.0-alpha.295",
4
4
  "description": "Lunora Worker runtime: the RPC router, shard resolver, and query coordinator",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -46,12 +46,12 @@
46
46
  "access": "public"
47
47
  },
48
48
  "dependencies": {
49
- "@lunora/bindings": "^1.0.0-alpha.152",
49
+ "@lunora/bindings": "^1.0.0-alpha.154",
50
50
  "@lunora/errors": ">=1.0.0-alpha.51 <2.0.0-0",
51
- "@lunora/observability": "^1.0.0-alpha.203",
52
- "@lunora/platform": "^1.0.0-alpha.81",
51
+ "@lunora/observability": "^1.0.0-alpha.205",
52
+ "@lunora/platform": "^1.0.0-alpha.83",
53
53
  "@lunora/wire": "1.0.0-alpha.6",
54
- "@noble/hashes": "2.2.0"
54
+ "@noble/hashes": "2.4.0"
55
55
  },
56
56
  "peerDependencies": {
57
57
  "@lunora/shard-engine": ">=1.0.0-alpha.135 <2.0.0-0",