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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{declareAppJurisdiction as t}from"./packem_shared/declareAppJurisdiction-DEba2p42.mjs";import{BACKUP_KEY_PREFIX as s,backupManifestKey as i,backupObjectKey as p,backupObjectKeyOfManifest as n,isBackupManifestEntry as c,isBackupManifestKey as m,normalizeBackupPrefix as f}from"./packem_shared/BACKUP_KEY_PREFIX-BOtSu-_3.mjs";import{toAirbyteMessages as R,toFivetranResponse as x}from"./packem_shared/toAirbyteMessages-DY0vsuEn.mjs";import{composeWorker as l,createLunoraHandler as d,createWorker as u,defineRpcEnvelope as _,resolveLunoraOptions as k,withFrameworkWorker as y}from"./packem_shared/composeWorker-kkJnK_7t.mjs";import{createCrossShardRelationCapabilities as O}from"./packem_shared/createCrossShardRelationCapabilities-BmGOuTrp.mjs";import{DEFAULT_REGISTRY_CACHE_TTL_MS as A,SHARD_REGISTRY_DO_NAME as L,createDynamicShardRegistry as T}from"./packem_shared/DEFAULT_REGISTRY_CACHE_TTL_MS-CdACWUQW.mjs";import{parseStackFrames as H,toError as P}from"./packem_shared/parseStackFrames-CZddjveh.mjs";import{LunoraError as v,toErrorResponse as I}from"./packem_shared/LunoraError-DksAgIpa.mjs";import{c as F,a as M,d as N,r as G,b as K,s as U,w as B}from"./packem_shared/export-tap-C2B_SATf.mjs";import{HEALTH_PATH as w,HEALTH_READY_PATH as z,buildHealthRoutes as X,d1Probe as j,durableObjectProbe as V,presenceProbe as W}from"./packem_shared/HEALTH_PATH-CAX2UeFy.mjs";import{LOG_ARCHIVE_PATH as J,resolveLogArchiveFromEnv as Q}from"./packem_shared/LOG_ARCHIVE_PATH-Hmjpz_Ko.mjs";import{memoizeIdentity as $,memoizeIdentityPerRequest as ee}from"./packem_shared/memoizeIdentity-BNnHkqeF.mjs";import{e as oe,a as te}from"./packem_shared/observability-DgurIZIR.mjs";import{analyticsEngineSink as se,combineSinks as ie,consoleSink as pe,otlpSink as ne,pipelineLogSink as ce,webhookSink as me}from"./packem_shared/analyticsEngineSink-BZB-ZYCP.mjs";import{D as Ee,c as Re}from"./packem_shared/pipeline-log-reader-C-nuWG_e.mjs";import{createQueryCoordinator as Se,createStaticShardRegistry as le}from"./packem_shared/createQueryCoordinator-es4jrL6Q.mjs";import{applyJurisdiction as ue,resolveShard as _e}from"./packem_shared/applyJurisdiction-D4vryLhj.mjs";import{a as ye,r as Ce,b as Oe}from"./packem_shared/rest-cache-CmHN871W.mjs";import{a as Ae,b as Le,c as Te,r as he}from"./packem_shared/rest-routes-DQkyqlym.mjs";import{decorateResponse as Pe,enforceOrigin as ge,handleCorsPreflight as ve,resolveSecurity as Ie}from"./packem_shared/decorateResponse-CRrFNW1v.mjs";import{createShardClient as Fe}from"./packem_shared/createShardClient-DIVRljRz.mjs";import{STORAGE_UPLOAD_MAX_BODY_BYTES as Ne}from"./packem_shared/STORAGE_UPLOAD_MAX_BODY_BYTES-BIiV5kqV.mjs";import{LOG_ARCHIVE_NOT_CONFIGURED as Ke}from"./packem_shared/LOG_ARCHIVE_NOT_CONFIGURED-CDpi4yFD.mjs";import{NOOP_EXECUTION_CONTEXT as Be}from"./packem_shared/NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{composeIdentityResolvers as we,routeIdentityResolvers as ze}from"./packem_shared/composeIdentityResolvers-BHZ4jH8o.mjs";const e="0.0.0";export{s as BACKUP_KEY_PREFIX,Ee as DEFAULT_LOG_COLUMNS,A as DEFAULT_REGISTRY_CACHE_TTL_MS,w as HEALTH_PATH,z as HEALTH_READY_PATH,Ke as LOG_ARCHIVE_NOT_CONFIGURED,J as LOG_ARCHIVE_PATH,v as LunoraError,Be as NOOP_EXECUTION_CONTEXT,L as SHARD_REGISTRY_DO_NAME,Ne as STORAGE_UPLOAD_MAX_BODY_BYTES,e as VERSION,se as analyticsEngineSink,ue as applyJurisdiction,ye as applyRestCache,Ae as argsFromQuery,i as backupManifestKey,p as backupObjectKey,n as backupObjectKeyOfManifest,X as buildHealthRoutes,Le as buildRestRoutes,ie as combineSinks,we as composeIdentityResolvers,l as composeWorker,pe as consoleSink,O as createCrossShardRelationCapabilities,T as createDynamicShardRegistry,F as createKvCursorStore,d as createLunoraHandler,M as createMemoryCursorStore,Re as createPipelineLogReader,Se as createQueryCoordinator,Te as createRestRateLimit,Fe as createShardClient,le as createStaticShardRegistry,u as createWorker,j as d1Probe,t as declareAppJurisdiction,Pe as decorateResponse,N as defineExportSink,_ as defineRpcEnvelope,V as durableObjectProbe,oe as emitLogEvent,te as emitRpcEvent,ge as enforceOrigin,ve as handleCorsPreflight,c as isBackupManifestEntry,m as isBackupManifestKey,$ as memoizeIdentity,ee as memoizeIdentityPerRequest,f as normalizeBackupPrefix,ne as otlpSink,H as parseStackFrames,ce as pipelineLogSink,W as presenceProbe,G as r2Sink,Ce as requestCarriesCredentials,Q as resolveLogArchiveFromEnv,k as resolveLunoraOptions,Ie as resolveSecurity,_e as resolveShard,Oe as restCacheHeaders,he as restSurfaceFromRegistry,ze as routeIdentityResolvers,K as runExportTap,U as sanitizeChange,R as toAirbyteMessages,P as toError,I as toErrorResponse,x as toFivetranResponse,B as webhookExportSink,me as webhookSink,y as withFrameworkWorker};
1
+ import{declareAppJurisdiction as t}from"./packem_shared/declareAppJurisdiction-DEba2p42.mjs";import{BACKUP_KEY_PREFIX as s,backupManifestKey as i,backupObjectKey as p,backupObjectKeyOfManifest as n,isBackupManifestEntry as c,isBackupManifestKey as m,normalizeBackupPrefix as f}from"./packem_shared/BACKUP_KEY_PREFIX-BOtSu-_3.mjs";import{toAirbyteMessages as R,toFivetranResponse as x}from"./packem_shared/toAirbyteMessages-DY0vsuEn.mjs";import{composeWorker as l,createLunoraHandler as d,createWorker as u,defineRpcEnvelope as _,resolveLunoraOptions as k,withFrameworkWorker as y}from"./packem_shared/composeWorker-BZL15nWe.mjs";import{createCrossShardRelationCapabilities as O}from"./packem_shared/createCrossShardRelationCapabilities-BmGOuTrp.mjs";import{DEFAULT_REGISTRY_CACHE_TTL_MS as A,SHARD_REGISTRY_DO_NAME as L,createDynamicShardRegistry as T}from"./packem_shared/DEFAULT_REGISTRY_CACHE_TTL_MS-CdACWUQW.mjs";import{parseStackFrames as H,toError as P}from"./packem_shared/parseStackFrames-CZddjveh.mjs";import{LunoraError as v,toErrorResponse as I}from"./packem_shared/LunoraError-DksAgIpa.mjs";import{c as F,a as M,d as N,r as G,b as K,s as U,w as B}from"./packem_shared/export-tap-C2B_SATf.mjs";import{HEALTH_PATH as w,HEALTH_READY_PATH as z,buildHealthRoutes as X,d1Probe as j,durableObjectProbe as V,presenceProbe as W}from"./packem_shared/HEALTH_PATH-CAX2UeFy.mjs";import{LOG_ARCHIVE_PATH as J,resolveLogArchiveFromEnv as Q}from"./packem_shared/LOG_ARCHIVE_PATH-Hmjpz_Ko.mjs";import{memoizeIdentity as $,memoizeIdentityPerRequest as ee}from"./packem_shared/memoizeIdentity-BNnHkqeF.mjs";import{e as oe,a as te}from"./packem_shared/observability-DgurIZIR.mjs";import{analyticsEngineSink as se,combineSinks as ie,consoleSink as pe,otlpSink as ne,pipelineLogSink as ce,webhookSink as me}from"./packem_shared/analyticsEngineSink-BZB-ZYCP.mjs";import{D as Ee,c as Re}from"./packem_shared/pipeline-log-reader-C-nuWG_e.mjs";import{createQueryCoordinator as Se,createStaticShardRegistry as le}from"./packem_shared/createQueryCoordinator-es4jrL6Q.mjs";import{applyJurisdiction as ue,resolveShard as _e}from"./packem_shared/applyJurisdiction-D4vryLhj.mjs";import{a as ye,r as Ce,b as Oe}from"./packem_shared/rest-cache-CmHN871W.mjs";import{a as Ae,b as Le,c as Te,r as he}from"./packem_shared/rest-routes-DQkyqlym.mjs";import{decorateResponse as Pe,enforceOrigin as ge,handleCorsPreflight as ve,resolveSecurity as Ie}from"./packem_shared/decorateResponse-BxMmYMux.mjs";import{createShardClient as Fe}from"./packem_shared/createShardClient-DIVRljRz.mjs";import{STORAGE_UPLOAD_MAX_BODY_BYTES as Ne}from"./packem_shared/STORAGE_UPLOAD_MAX_BODY_BYTES-BIiV5kqV.mjs";import{LOG_ARCHIVE_NOT_CONFIGURED as Ke}from"./packem_shared/LOG_ARCHIVE_NOT_CONFIGURED-CDpi4yFD.mjs";import{NOOP_EXECUTION_CONTEXT as Be}from"./packem_shared/NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{composeIdentityResolvers as we,routeIdentityResolvers as ze}from"./packem_shared/composeIdentityResolvers-BHZ4jH8o.mjs";const e="0.0.0";export{s as BACKUP_KEY_PREFIX,Ee as DEFAULT_LOG_COLUMNS,A as DEFAULT_REGISTRY_CACHE_TTL_MS,w as HEALTH_PATH,z as HEALTH_READY_PATH,Ke as LOG_ARCHIVE_NOT_CONFIGURED,J as LOG_ARCHIVE_PATH,v as LunoraError,Be as NOOP_EXECUTION_CONTEXT,L as SHARD_REGISTRY_DO_NAME,Ne as STORAGE_UPLOAD_MAX_BODY_BYTES,e as VERSION,se as analyticsEngineSink,ue as applyJurisdiction,ye as applyRestCache,Ae as argsFromQuery,i as backupManifestKey,p as backupObjectKey,n as backupObjectKeyOfManifest,X as buildHealthRoutes,Le as buildRestRoutes,ie as combineSinks,we as composeIdentityResolvers,l as composeWorker,pe as consoleSink,O as createCrossShardRelationCapabilities,T as createDynamicShardRegistry,F as createKvCursorStore,d as createLunoraHandler,M as createMemoryCursorStore,Re as createPipelineLogReader,Se as createQueryCoordinator,Te as createRestRateLimit,Fe as createShardClient,le as createStaticShardRegistry,u as createWorker,j as d1Probe,t as declareAppJurisdiction,Pe as decorateResponse,N as defineExportSink,_ as defineRpcEnvelope,V as durableObjectProbe,oe as emitLogEvent,te as emitRpcEvent,ge as enforceOrigin,ve as handleCorsPreflight,c as isBackupManifestEntry,m as isBackupManifestKey,$ as memoizeIdentity,ee as memoizeIdentityPerRequest,f as normalizeBackupPrefix,ne as otlpSink,H as parseStackFrames,ce as pipelineLogSink,W as presenceProbe,G as r2Sink,Ce as requestCarriesCredentials,Q as resolveLogArchiveFromEnv,k as resolveLunoraOptions,Ie as resolveSecurity,_e as resolveShard,Oe as restCacheHeaders,he as restSurfaceFromRegistry,ze as routeIdentityResolvers,K as runExportTap,U as sanitizeChange,R as toAirbyteMessages,P as toError,I as toErrorResponse,x as toFivetranResponse,B as webhookExportSink,me as webhookSink,y as withFrameworkWorker};
@@ -1,4 +1,4 @@
1
- import{isLunoraError as pr,toErrorBody as mr}from"@lunora/errors";import{encodeWire as Te,decodeWire as Xe,encodeArgsOrThrow as wr}from"@lunora/wire";import{e as tn}from"./evict-oldest-BNXsKx4s.mjs";import{NOOP_EXECUTION_CONTEXT as gr}from"./NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{i as yr,e as br,a as _r,E as gt,d as Rr}from"./identity-header-pR617HTs.mjs";import{O as nn,a as rn}from"./origin-paywall-B6eOO67m.mjs";import{o as we,b as on,p as Er,m as Ar,d as Tr,a as Sr,r as Or}from"./otlp-resource-BwFJnvwB.mjs";import{r as vr,f as yt,a as ie,S as bt}from"./observability-DgurIZIR.mjs";import{t as Ir,f as kr}from"./base64-Bl1_r2k1.mjs";import{d as ee,e as ne,M as sn,b as Pr,f as Dr,g as an,w as Nr,h as cn,t as Ur}from"./rest-routes-DQkyqlym.mjs";import{LunoraError as c,toErrorResponse as _t}from"./LunoraError-DksAgIpa.mjs";import{a as M,m as me}from"./method-guard-BG_vJNTl.mjs";import{normalizeBackupPrefix as ot,BACKUP_KEY_PREFIX as st,isBackupManifestKey as Cr,backupObjectKeyOfManifest as dn,backupObjectKey as Br,backupManifestKey as xr}from"./BACKUP_KEY_PREFIX-BOtSu-_3.mjs";import{toHex as Hr,buildStorageAdminRoutes as Lr,STORAGE_UPLOAD_MAX_BODY_BYTES as jr,STORAGE_PATH as Mr}from"./STORAGE_UPLOAD_MAX_BODY_BYTES-BIiV5kqV.mjs";import{b as $r,e as Kr,f as Rt,g as Fr,h as Gr}from"./export-tap-C2B_SATf.mjs";import{buildHealthRoutes as Qr,durableObjectProbe as Wr,d1Probe as zr,presenceProbe as $e}from"./HEALTH_PATH-CAX2UeFy.mjs";import{wrapResolverWithContract as Vr}from"./composeIdentityResolvers-BHZ4jH8o.mjs";import{composeIdentityResolvers as Hi,routeIdentityResolvers as Li}from"./composeIdentityResolvers-BHZ4jH8o.mjs";import{buildLogArchiveAdminRoutes as Jr}from"./LOG_ARCHIVE_PATH-Hmjpz_Ko.mjs";import{pruneShardRegistry as Yr,createQueryCoordinator as qr,createDefaultShardRegistry as Xr}from"./createQueryCoordinator-es4jrL6Q.mjs";import{resolveShard as ge,applyJurisdiction as Ke}from"./applyJurisdiction-D4vryLhj.mjs";import{resolveSecurity as Et,handleCorsPreflight as Zr,enforceOrigin as eo,decorateResponse as Fe,enforceWebSocketOrigin as At}from"./decorateResponse-CRrFNW1v.mjs";const to=e=>{const t=e??{};if(typeof t.bucket=="function")return t;const n=t.bucketName,s={...t,bucketName:typeof n=="string"&&n!==""?n:"default"};return s.bucket=()=>s,s},un="__lunoraBranch",no=e=>typeof e=="object"&&e!==null&&Object.hasOwn(e,un),ro=`may not contain the reserved workflow branch-marker key ("${un}")`,oo=async e=>{const t=[];let n;for(;;){const r=await e(n);if(t.push(...Array.isArray(r.records)?r.records:[]),r.truncated!==!0||typeof r.cursor!="string"||r.cursor.length===0)return t;if(r.cursor===n)throw new Error("collectPages: the list did not advance its cursor — refusing to page forever");n=r.cursor}},so=/already[\s_-]?exists/iu,ao=e=>so.test(e instanceof Error?e.message:String(e)),Tt="x-lunora-want-error-detail",St="x-lunora-error-detail",io=8192,co=e=>{if(!(e instanceof Error))return{message:String(e),name:typeof e};const{code:t}=e;return{...typeof t=="string"?{code:t}:{},message:e.message,name:e.name,...e.stack===void 0?{}:{stack:e.stack.slice(0,io)}}},Ot=e=>{if(e!=null)try{const t=JSON.parse(decodeURIComponent(e));return typeof t?.message=="string"&&typeof t.name=="string"?t:void 0}catch{return}},uo="cf-ray",lo="x-lunora-ray-id",ho=/^([\da-f]{16})(?:-[a-z]{3,4})?$/i,fo=e=>e==null?void 0:ho.exec(e.trim())?.[1]?.toLowerCase(),po=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"];new Set(po);const mo=new Set(["AE","BH","IL","IQ","IR","JO","KW","LB","OM","PS","QA","SA","SY","TR","YE"]),wo=-100,go=15,yo=e=>{const t=Number(e.longitude??Number.NaN);switch(e.continent){case"AF":return"afr";case"AS":return e.country!==void 0&&mo.has(e.country)?"me":"apac";case"EU":return Number.isFinite(t)&&t>go?"eeur":"weur";case"NA":return Number.isFinite(t)&&t<wo?"wnam":"enam";case"OC":return"oc";case"SA":return"sam";default:return}},vt=e=>{const t=e.cf;return t===void 0?void 0:yo(t)},Ze="::relay::",bo=(e,t)=>`${e}${Ze}${String(t)}`,et="::replica::",_o=(e,t)=>`${e}${et}${t}`,Ro=e=>{if(e==null||!/^\d+$/.test(e))return;const t=Number.parseInt(e,10);return Number.isSafeInteger(t)&&t>0?t:void 0},ln=(e,t)=>{const n=Math.max(e.length,t.length);let r=e.length^t.length;for(let s=0;s<n;s+=1){const i=s<e.length?e.charCodeAt(s):0,d=s<t.length?t.charCodeAt(s):0;r|=i^d}return r===0},Eo=(e,t,n,r)=>{const s=e.get(t);if(s!==void 0)return s;tn(e,r);const i=n().catch(d=>{throw e.get(t)===i&&e.delete(t),d});return e.set(t,i),i},at=new TextEncoder,Ao=Array.from({length:32},(e,t)=>t);new RegExp(`[${Ao.map(e=>String.fromCodePoint(e)).join("")}]`,"u");const To=64,So=new Map,hn=async e=>Eo(So,e,async()=>crypto.subtle.importKey("raw",at.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]),To),fn=async(e,t)=>{const n=await hn(e),r=await crypto.subtle.sign("HMAC",n,at.encode(t));return Ir(new Uint8Array(r))},Oo=async(e,t,n)=>{const r=await hn(e);return crypto.subtle.verify("HMAC",r,n,at.encode(t))},vo="/_lunora/scheduler/dispatch",Io="__lunora_relation__:",ko=e=>e.startsWith(Io),pn=(e,t)=>{if(!t||t.length===0)return!1;const n=e.headers.get("authorization");if(!n)return!1;const[r,...s]=n.split(" ");return r?.toLowerCase()!=="bearer"?!1:ln(t,s.join(" ").trim())},Po=async(e,t,n)=>{const r=e.headers.get("x-lunora-scheduler-signature"),{schedulerSecret:s}=n;return r!==null&&r.length>0&&s!==void 0&&s.length>0?ln(await fn(s,t),r):pn(e,n.adminToken)},Do=({forwardedIdentity:e,mutationId:t,traceparent:n})=>{const r={"content-type":"application/json",[rn]:nn,"x-lunora-system":"1"};return e?.userId!==void 0&&e.userId.length>0&&(r["x-lunora-userid"]=e.userId),e?.identity!==void 0&&e.identity.length>0&&(r["x-lunora-identity"]=e.identity),t!==void 0&&t.length>0&&(r["x-lunora-mutation-id"]=t),n!==void 0&&n.length>0&&(r.traceparent=n),r},No=e=>{const t=e.headers.get("x-lunora-userid"),n=e.headers.get("x-lunora-identity");if(!(t===null&&n===null))return{...n===null?{}:{identity:n},...t===null?{}:{userId:t}}},Uo=(e,t,n)=>e?.[n]??t?.[n],Co=(e,t,n,r)=>{const s=Uo(e,t,n);if(!(typeof s!="object"||s===null))return r.every(i=>typeof s[i]=="function")?s:void 0},mn="v1",Bo=6e4,xo=async(e,t={})=>{const n=(t.now??Date.now())+(t.ttlMs??Bo),r=`${mn}.${String(n)}`,s=await fn(e,r);return{expiresAtMs:n,token:`${r}.${s}`}},Ho=async(e,t,n=Date.now())=>{if(e.length===0||t.length===0)return!1;const r=t.split(".");if(r.length!==3)return!1;const[s,i,d]=r;if(s!==mn||d.length===0)return!1;const f=Number(i);if(!Number.isFinite(f)||f<=n)return!1;let h;try{h=kr(d)}catch{return!1}return Oo(e,`${s}.${i}`,h)},N="/_lunora/admin/auth",Lo={INVITER_REQUIRED:400,ORG_SLUG_INVALID:400,ORG_SLUG_TAKEN:409,PASSWORD_TOO_LONG:400,PASSWORD_TOO_SHORT:400,USER_ALREADY_EXISTS:409,USER_NOT_FOUND:404},C=(e,t)=>{const n=e[t];if(typeof n!="string"||n==="")throw new c(`\`${t}\` is required`,{code:"BAD_REQUEST",status:400});return n},he=(e,t)=>{const n=e(t);if(n===void 0)throw new c(`\`${t}\` query parameter is required`,{code:"BAD_REQUEST",status:400});return n},wn=e=>{if(typeof e=="string"||Array.isArray(e)&&e.every(t=>typeof t=="string"))return e},te=(e,t)=>typeof e[t]=="string"?e[t]:void 0,Ge=(e,t)=>{const n=e[t];return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:void 0},It=e=>{const t=wn(e.role);if(t===void 0||typeof t=="string"&&t.trim()==="")throw new c("`role` is required",{code:"BAD_REQUEST",status:400});return t},kt=e=>{const t=e.permission;if(typeof t!="object"||t===null||Array.isArray(t))throw new c("`permission` object is required",{code:"BAD_REQUEST",status:400});const n={};for(const[r,s]of Object.entries(t))Array.isArray(s)&&s.every(i=>typeof i=="string")&&(n[r]=s);return n},jo={[`${N}/capabilities`]:{build:()=>({}),http:"GET",method:"capabilities"},[`${N}/users`]:{build:({paging:e,query:t})=>{const n=t("sortDirection");return{...e,filterField:t("filterField"),filterValue:t("filterValue"),search:t("search"),searchField:t("searchField"),sortBy:t("sortBy"),sortDirection:n==="asc"||n==="desc"?n:void 0}},http:"GET",method:"listUsers"},[`${N}/sessions`]:{build:({paging:e,query:t})=>({...e,userId:t("userId")}),http:"GET",method:"listSessions"},[`${N}/accounts`]:{build:({query:e})=>({userId:he(e,"userId")}),http:"GET",method:"listAccounts"},[`${N}/passkeys`]:{build:({query:e})=>({userId:he(e,"userId")}),http:"GET",method:"listPasskeys"},[`${N}/organizations`]:{build:({paging:e})=>({...e}),http:"GET",method:"listOrganizations"},[`${N}/organizations/members`]:{build:({paging:e,query:t})=>({...e,organizationId:he(t,"organizationId")}),http:"GET",method:"listMembers"},[`${N}/organizations/invitations`]:{build:({paging:e,query:t})=>({...e,organizationId:he(t,"organizationId")}),http:"GET",method:"listInvitations"},[`${N}/sign-up-invitations`]:{build:({paging:e})=>({...e}),http:"GET",method:"listSignUpInvitations"},[`${N}/sign-up-invitations/create`]:{build:({body:e})=>({email:C(e,"email"),expiresInSeconds:typeof e.expiresInSeconds=="number"?e.expiresInSeconds:void 0,invitedBy:te(e,"invitedBy")}),http:"POST",method:"createSignUpInvitation"},[`${N}/sign-up-invitations/revoke`]:{build:({body:e})=>({email:C(e,"email")}),http:"POST",method:"revokeSignUpInvitation",returns:"void"},[`${N}/config`]:{build:()=>({}),http:"GET",method:"config"},[`${N}/organizations/teams`]:{build:({paging:e,query:t})=>({...e,organizationId:he(t,"organizationId")}),http:"GET",method:"listTeams"},[`${N}/organizations/teams/members`]:{build:({paging:e,query:t})=>({...e,teamId:he(t,"teamId")}),http:"GET",method:"listTeamMembers"},[`${N}/organizations/roles`]:{build:({paging:e,query:t})=>({...e,organizationId:he(t,"organizationId")}),http:"GET",method:"listOrgRoles"},[`${N}/users/create`]:{build:({body:e})=>({data:Ge(e,"data"),email:C(e,"email"),name:C(e,"name"),password:te(e,"password"),role:wn(e.role)}),http:"POST",method:"createUser"},[`${N}/users/update`]:{build:({body:e})=>{const{data:t}=e;if(typeof t!="object"||t===null||Array.isArray(t))throw new c("`data` object is required",{code:"BAD_REQUEST",status:400});return{data:t,userId:C(e,"userId")}},http:"POST",method:"updateUser"},[`${N}/users/role`]:{build:({body:e})=>({role:It(e),userId:C(e,"userId")}),http:"POST",method:"setRole"},[`${N}/users/ban`]:{build:({body:e})=>({expiresInSeconds:typeof e.expiresInSeconds=="number"?e.expiresInSeconds:void 0,reason:te(e,"reason"),userId:C(e,"userId")}),http:"POST",method:"banUser"},[`${N}/users/unban`]:{build:({body:e})=>({userId:C(e,"userId")}),http:"POST",method:"unbanUser"},[`${N}/users/password`]:{build:({body:e})=>({newPassword:C(e,"newPassword"),userId:C(e,"userId")}),http:"POST",method:"setUserPassword",returns:"void"},[`${N}/users/remove`]:{build:({body:e})=>({userId:C(e,"userId")}),http:"POST",method:"removeUser",returns:"void"},[`${N}/users/impersonate`]:{build:({body:e})=>({userId:C(e,"userId")}),http:"POST",method:"impersonateUser"},[`${N}/sessions/revoke`]:{build:({body:e})=>({sessionId:C(e,"sessionId")}),http:"POST",method:"revokeUserSession",returns:"void"},[`${N}/sessions/revoke-all`]:{build:({body:e})=>({userId:C(e,"userId")}),http:"POST",method:"revokeUserSessions",returns:"void"},[`${N}/accounts/unlink`]:{build:({body:e})=>({accountId:C(e,"accountId"),userId:C(e,"userId")}),http:"POST",method:"unlinkAccount",returns:"void"},[`${N}/two-factor/disable`]:{build:({body:e})=>({userId:C(e,"userId")}),http:"POST",method:"disableTwoFactor",returns:"void"},[`${N}/passkeys/delete`]:{build:({body:e})=>({passkeyId:C(e,"passkeyId")}),http:"POST",method:"deletePasskey",returns:"void"},[`${N}/organizations/members/remove`]:{build:({body:e})=>({memberId:C(e,"memberId")}),http:"POST",method:"removeMember",returns:"void"},[`${N}/organizations/invitations/cancel`]:{build:({body:e})=>({invitationId:C(e,"invitationId")}),http:"POST",method:"cancelInvitation",returns:"void"},[`${N}/organizations/create`]:{build:({body:e})=>({logo:te(e,"logo"),metadata:Ge(e,"metadata"),name:C(e,"name"),ownerId:te(e,"ownerId"),slug:te(e,"slug")}),http:"POST",method:"createOrganization"},[`${N}/organizations/update`]:{build:({body:e})=>({logo:te(e,"logo"),metadata:Ge(e,"metadata"),name:te(e,"name"),organizationId:C(e,"organizationId"),slug:te(e,"slug")}),http:"POST",method:"updateOrganization"},[`${N}/organizations/remove`]:{build:({body:e})=>({organizationId:C(e,"organizationId")}),http:"POST",method:"deleteOrganization",returns:"void"},[`${N}/organizations/members/add`]:{build:({body:e})=>({organizationId:C(e,"organizationId"),role:te(e,"role"),userId:C(e,"userId")}),http:"POST",method:"addMember"},[`${N}/organizations/members/invite`]:{build:({body:e})=>({email:C(e,"email"),inviterId:te(e,"inviterId"),organizationId:C(e,"organizationId"),role:te(e,"role")}),http:"POST",method:"inviteMember"},[`${N}/organizations/members/role`]:{build:({body:e})=>({memberId:C(e,"memberId"),role:It(e)}),http:"POST",method:"updateMemberRole"},[`${N}/organizations/teams/create`]:{build:({body:e})=>({name:C(e,"name"),organizationId:C(e,"organizationId")}),http:"POST",method:"createTeam"},[`${N}/organizations/teams/update`]:{build:({body:e})=>({name:C(e,"name"),teamId:C(e,"teamId")}),http:"POST",method:"updateTeam"},[`${N}/organizations/teams/remove`]:{build:({body:e})=>({teamId:C(e,"teamId")}),http:"POST",method:"removeTeam",returns:"void"},[`${N}/organizations/teams/members/add`]:{build:({body:e})=>({teamId:C(e,"teamId"),userId:C(e,"userId")}),http:"POST",method:"addTeamMember"},[`${N}/organizations/teams/members/remove`]:{build:({body:e})=>({teamMemberId:C(e,"teamMemberId")}),http:"POST",method:"removeTeamMember",returns:"void"},[`${N}/organizations/roles/create`]:{build:({body:e})=>({organizationId:C(e,"organizationId"),permission:kt(e),role:C(e,"role")}),http:"POST",method:"createOrgRole"},[`${N}/organizations/roles/update`]:{build:({body:e})=>({permission:kt(e),roleId:C(e,"roleId")}),http:"POST",method:"updateOrgRole"},[`${N}/organizations/roles/remove`]:{build:({body:e})=>({roleId:C(e,"roleId")}),http:"POST",method:"deleteOrgRole",returns:"void"}},Mo=e=>{const t=async s=>{try{return await s()}catch(i){if(i instanceof c)throw i;const d=i,f=typeof d.code=="string"?d.code:"AUTH_ADMIN_ERROR";throw console.error("[lunora] auth admin operation failed:",i),new c("auth admin operation failed",{code:f,status:Lo[f]??500})}},n=async(s,i)=>{if(e.assertAdmin(s),s.method!==i.http)throw new c(`Auth admin endpoint requires ${i.http}`,{code:"METHOD_NOT_ALLOWED",status:405});const d=e.getAuthAdmin();if(d===void 0)throw new c("auth endpoints require an `authAdmin` on the worker",{code:"AUTH_NOT_CONFIGURED",status:400});const f=d[i.method];if(f===void 0)throw new c(`auth admin does not support \`${i.method}\``,{code:"AUTH_OP_NOT_SUPPORTED",status:400});const h=new URL(s.url),m={body:i.http==="POST"?await e.readJsonBody(s):{},paging:e.parsePaging(s),query:S=>e.queryParameter(h,S)},b=i.build(m),T=await t(()=>f(b));return Response.json(i.returns==="void"?{ok:!0}:T,{headers:{"cache-control":"no-store","content-type":"application/json"},status:200})},r={};for(const[s,i]of Object.entries(jo))r[s]=d=>n(d,i);return r},Pt="__lunora_admin__:getAuthAuditLog",Dt=e=>typeof e=="string"&&e!==""?e:void 0,Nt=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0,$o=e=>async(n,r)=>{e.assertAdmin(n);const s=e.getReader();if(s===void 0)throw new c("the auth/security audit endpoint requires an `authAuditReader` on the worker",{code:"AUTH_AUDIT_NOT_CONFIGURED",status:400});const i=Dt(r.actorId),d=Dt(r.event),f=Nt(r.sinceSeq),h=Nt(r.limit),m={...i===void 0?{}:{actorId:i},...d===void 0?{}:{event:d},...f===void 0?{}:{sinceSeq:f},...h===void 0?{}:{limit:h}};let b;try{b=await s.read(m)}catch(S){throw S instanceof c?S:(console.error("[lunora] auth audit read failed:",S),new c("auth audit read failed",{code:"AUTH_AUDIT_READ_FAILED",status:500}))}const T={entries:b};return Response.json({result:Te(T)},{headers:{"content-type":"application/json"},status:200})},tt="__lunora_admin__:copyAuthToJurisdiction",gn="__lunora_admin__:purgeUnpinnedAuth",Ko=e=>async(t,n,r)=>{if(n!==tt&&n!==gn)return;e.assertAdmin(t);const s=e.getMove();if(s===void 0)throw new c("moving auth into the jurisdiction needs DO-backed auth pinned with `.jurisdiction(…, { pinAuth: true })`",{code:"AUTH_MOVE_NOT_CONFIGURED",status:400});const i=n===tt?await s.copy({force:r.force===!0}):await s.purge();return Response.json({result:Te(i)},{headers:{"content-type":"application/json"},status:200})},Fo=(e,t)=>{const n=[],r=[];if(t&&t.length>0)for(const s of t)e.resolveTableSharding?.(s)?.mode.kind==="global"?r.push(s):n.push(s);return{globalTables:r,shardLocalTables:n}},Go=async(e,t,n,r,s,i)=>{if(n!==void 0&&r.length===0)return[];const d=await e.orchestrateExport(s,{args:{tables:r},defaultShardKey:i,headers:t,tables:r}),f=d.shards.filter(h=>h.error);if(f.length>0){const h=f.map(m=>`${m.shardKey}: ${m.error?.message??"unknown error"}`).join("; ");throw new c(`export failed on ${String(f.length)} of ${String(d.shards.length)} shard(s) — ${h}`,{code:"EXPORT_SHARD_FAILED",status:502})}return d.shards.flatMap(h=>h.rows??[])},yn=async(e,t,n,r,s)=>{const i=r??e.listSchemaTables?.();r===void 0&&e.listSchemaTables===void 0&&console.warn("[lunora] export: no table list available (`listSchemaTables` is unset and no `tables` were named), so only the default shard is reachable. A `.shardBy()` deployment's other shards will be missing from this export. Name the tables explicitly, or regenerate the worker so codegen supplies the list.");const{globalTables:d,shardLocalTables:f}=Fo(e,i),h=await Go(t,n,i,f,s,e.defaultShardKey??"__root__"),m=e.exportGlobals,b=r===void 0||d.length>0;return(async function*(){yield*h,b&&m&&(yield*m({tables:d}))})()},Qo=async(e,t,n,r,s,i)=>{for await(const d of await yn(e,t,n,r,i))s(d)},Wo=new TextEncoder,zo=1e3,bn=10,Vo=200,Ut=8,_n="lunoraBackupCron",Ct=24*1048576,Bt=e=>{const t=e.slice(0,bn).map(r=>dn(r)),n=e.length-t.length;return`${t.join(", ")}${n>0?` (+${String(n)} more)`:""}`},Jo=(e,t)=>{const n=new Uint8Array(new ArrayBuffer(t));let r=0;for(const s of e)n.set(s,r),r+=s.byteLength;return n},it=async(e,t,n,r)=>{if(n===void 0||!Number.isInteger(n)||n<=0)return{eligible:0,stale:[]};const s=[];let i;for(let d=0;d<zo;d+=1){const f=await e.list({cursor:i,include:["customMetadata"],prefix:t});for(const h of f.objects)Cr(h.key)&&h.customMetadata?.[_n]===r&&s.push(h.key);if(!f.truncated||f.cursor===void 0)break;i=f.cursor}return{eligible:s.length,stale:s.toSorted((d,f)=>f.localeCompare(d)).slice(n)}},Yo=async(e,t,n,r,s)=>{const{stale:i}=await it(e,t,n,r),d=new Set(s),f=i.filter(k=>d.has(k)),h=f.slice(0,Vo),m=i.length-h.length,b=s.length-f.length;if(h.length===0)return{deleted:[],failed:[],ignored:b,remaining:m};const T=[],S=[];for(let k=0;k<h.length;k+=Ut){const w=await Promise.allSettled(h.slice(k,k+Ut).map(async g=>(await e.delete(dn(g)),await e.delete(g),g)));for(const[g,y]of w.entries())y.status==="fulfilled"?T.push(y.value):S.push(h[k+g])}return T.length>0&&console.info(`[lunora] backup prune kept the newest ${String(n)} and deleted ${String(T.length)}: ${Bt(T)}`),S.length>0&&console.warn(`[lunora] backup prune failed to remove ${String(S.length)}: ${Bt(S)}`),{deleted:T,failed:S,ignored:b,remaining:m}},qo=async e=>{const t=e.backupStore;if(!t)throw new c("backup retention preview requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});const n=ot(e.backupPrefix??st),r=e.backupCron,{eligible:s,stale:i}=r===void 0?{eligible:0,stale:[]}:await it(t,n,e.backupRetain,r);return{cron:r,eligible:s,keep:e.backupRetain??0,prefix:n,wouldDelete:i}},Xo=async(e,t,n,r,s)=>{const i=e.backupStore;if(!i)throw new c("scheduled backup requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});if(!r||r.length===0)throw new c("scheduled backup requires an `adminToken` (or `env.LUNORA_ADMIN_TOKEN`) to authenticate the per-shard export gate",{code:"BACKUP_NOT_CONFIGURED",status:500});const d={authorization:`Bearer ${r}`,"content-type":"application/json"},f=e.backupTables;let h=0,m=0,b=[];await Qo(e,t,d,f,I=>{const E=Wo.encode(`${JSON.stringify(I)}
1
+ import{isLunoraError as pr,toErrorBody as mr}from"@lunora/errors";import{encodeWire as Te,decodeWire as Xe,encodeArgsOrThrow as wr}from"@lunora/wire";import{e as tn}from"./evict-oldest-BNXsKx4s.mjs";import{NOOP_EXECUTION_CONTEXT as gr}from"./NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{i as yr,e as br,a as _r,E as gt,d as Rr}from"./identity-header-pR617HTs.mjs";import{O as nn,a as rn}from"./origin-paywall-B6eOO67m.mjs";import{o as we,b as on,p as Er,m as Ar,d as Tr,a as Sr,r as Or}from"./otlp-resource-BwFJnvwB.mjs";import{r as vr,f as yt,a as ie,S as bt}from"./observability-DgurIZIR.mjs";import{t as Ir,f as kr}from"./base64-Bl1_r2k1.mjs";import{d as ee,e as ne,M as sn,b as Pr,f as Dr,g as an,w as Nr,h as cn,t as Ur}from"./rest-routes-DQkyqlym.mjs";import{LunoraError as c,toErrorResponse as _t}from"./LunoraError-DksAgIpa.mjs";import{a as M,m as me}from"./method-guard-BG_vJNTl.mjs";import{normalizeBackupPrefix as ot,BACKUP_KEY_PREFIX as st,isBackupManifestKey as Cr,backupObjectKeyOfManifest as dn,backupObjectKey as Br,backupManifestKey as xr}from"./BACKUP_KEY_PREFIX-BOtSu-_3.mjs";import{toHex as Hr,buildStorageAdminRoutes as Lr,STORAGE_UPLOAD_MAX_BODY_BYTES as jr,STORAGE_PATH as Mr}from"./STORAGE_UPLOAD_MAX_BODY_BYTES-BIiV5kqV.mjs";import{b as $r,e as Kr,f as Rt,g as Fr,h as Gr}from"./export-tap-C2B_SATf.mjs";import{buildHealthRoutes as Qr,durableObjectProbe as Wr,d1Probe as zr,presenceProbe as $e}from"./HEALTH_PATH-CAX2UeFy.mjs";import{wrapResolverWithContract as Vr}from"./composeIdentityResolvers-BHZ4jH8o.mjs";import{composeIdentityResolvers as Hi,routeIdentityResolvers as Li}from"./composeIdentityResolvers-BHZ4jH8o.mjs";import{buildLogArchiveAdminRoutes as Jr}from"./LOG_ARCHIVE_PATH-Hmjpz_Ko.mjs";import{pruneShardRegistry as Yr,createQueryCoordinator as qr,createDefaultShardRegistry as Xr}from"./createQueryCoordinator-es4jrL6Q.mjs";import{resolveShard as ge,applyJurisdiction as Ke}from"./applyJurisdiction-D4vryLhj.mjs";import{resolveSecurity as Et,handleCorsPreflight as Zr,enforceOrigin as eo,decorateResponse as Fe,enforceWebSocketOrigin as At}from"./decorateResponse-BxMmYMux.mjs";const to=e=>{const t=e??{};if(typeof t.bucket=="function")return t;const n=t.bucketName,s={...t,bucketName:typeof n=="string"&&n!==""?n:"default"};return s.bucket=()=>s,s},un="__lunoraBranch",no=e=>typeof e=="object"&&e!==null&&Object.hasOwn(e,un),ro=`may not contain the reserved workflow branch-marker key ("${un}")`,oo=async e=>{const t=[];let n;for(;;){const r=await e(n);if(t.push(...Array.isArray(r.records)?r.records:[]),r.truncated!==!0||typeof r.cursor!="string"||r.cursor.length===0)return t;if(r.cursor===n)throw new Error("collectPages: the list did not advance its cursor — refusing to page forever");n=r.cursor}},so=/already[\s_-]?exists/iu,ao=e=>so.test(e instanceof Error?e.message:String(e)),Tt="x-lunora-want-error-detail",St="x-lunora-error-detail",io=8192,co=e=>{if(!(e instanceof Error))return{message:String(e),name:typeof e};const{code:t}=e;return{...typeof t=="string"?{code:t}:{},message:e.message,name:e.name,...e.stack===void 0?{}:{stack:e.stack.slice(0,io)}}},Ot=e=>{if(e!=null)try{const t=JSON.parse(decodeURIComponent(e));return typeof t?.message=="string"&&typeof t.name=="string"?t:void 0}catch{return}},uo="cf-ray",lo="x-lunora-ray-id",ho=/^([\da-f]{16})(?:-[a-z]{3,4})?$/i,fo=e=>e==null?void 0:ho.exec(e.trim())?.[1]?.toLowerCase(),po=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"];new Set(po);const mo=new Set(["AE","BH","IL","IQ","IR","JO","KW","LB","OM","PS","QA","SA","SY","TR","YE"]),wo=-100,go=15,yo=e=>{const t=Number(e.longitude??Number.NaN);switch(e.continent){case"AF":return"afr";case"AS":return e.country!==void 0&&mo.has(e.country)?"me":"apac";case"EU":return Number.isFinite(t)&&t>go?"eeur":"weur";case"NA":return Number.isFinite(t)&&t<wo?"wnam":"enam";case"OC":return"oc";case"SA":return"sam";default:return}},vt=e=>{const t=e.cf;return t===void 0?void 0:yo(t)},Ze="::relay::",bo=(e,t)=>`${e}${Ze}${String(t)}`,et="::replica::",_o=(e,t)=>`${e}${et}${t}`,Ro=e=>{if(e==null||!/^\d+$/.test(e))return;const t=Number.parseInt(e,10);return Number.isSafeInteger(t)&&t>0?t:void 0},ln=(e,t)=>{const n=Math.max(e.length,t.length);let r=e.length^t.length;for(let s=0;s<n;s+=1){const i=s<e.length?e.charCodeAt(s):0,d=s<t.length?t.charCodeAt(s):0;r|=i^d}return r===0},Eo=(e,t,n,r)=>{const s=e.get(t);if(s!==void 0)return s;tn(e,r);const i=n().catch(d=>{throw e.get(t)===i&&e.delete(t),d});return e.set(t,i),i},at=new TextEncoder,Ao=Array.from({length:32},(e,t)=>t);new RegExp(`[${Ao.map(e=>String.fromCodePoint(e)).join("")}]`,"u");const To=64,So=new Map,hn=async e=>Eo(So,e,async()=>crypto.subtle.importKey("raw",at.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]),To),fn=async(e,t)=>{const n=await hn(e),r=await crypto.subtle.sign("HMAC",n,at.encode(t));return Ir(new Uint8Array(r))},Oo=async(e,t,n)=>{const r=await hn(e);return crypto.subtle.verify("HMAC",r,n,at.encode(t))},vo="/_lunora/scheduler/dispatch",Io="__lunora_relation__:",ko=e=>e.startsWith(Io),pn=(e,t)=>{if(!t||t.length===0)return!1;const n=e.headers.get("authorization");if(!n)return!1;const[r,...s]=n.split(" ");return r?.toLowerCase()!=="bearer"?!1:ln(t,s.join(" ").trim())},Po=async(e,t,n)=>{const r=e.headers.get("x-lunora-scheduler-signature"),{schedulerSecret:s}=n;return r!==null&&r.length>0&&s!==void 0&&s.length>0?ln(await fn(s,t),r):pn(e,n.adminToken)},Do=({forwardedIdentity:e,mutationId:t,traceparent:n})=>{const r={"content-type":"application/json",[rn]:nn,"x-lunora-system":"1"};return e?.userId!==void 0&&e.userId.length>0&&(r["x-lunora-userid"]=e.userId),e?.identity!==void 0&&e.identity.length>0&&(r["x-lunora-identity"]=e.identity),t!==void 0&&t.length>0&&(r["x-lunora-mutation-id"]=t),n!==void 0&&n.length>0&&(r.traceparent=n),r},No=e=>{const t=e.headers.get("x-lunora-userid"),n=e.headers.get("x-lunora-identity");if(!(t===null&&n===null))return{...n===null?{}:{identity:n},...t===null?{}:{userId:t}}},Uo=(e,t,n)=>e?.[n]??t?.[n],Co=(e,t,n,r)=>{const s=Uo(e,t,n);if(!(typeof s!="object"||s===null))return r.every(i=>typeof s[i]=="function")?s:void 0},mn="v1",Bo=6e4,xo=async(e,t={})=>{const n=(t.now??Date.now())+(t.ttlMs??Bo),r=`${mn}.${String(n)}`,s=await fn(e,r);return{expiresAtMs:n,token:`${r}.${s}`}},Ho=async(e,t,n=Date.now())=>{if(e.length===0||t.length===0)return!1;const r=t.split(".");if(r.length!==3)return!1;const[s,i,d]=r;if(s!==mn||d.length===0)return!1;const f=Number(i);if(!Number.isFinite(f)||f<=n)return!1;let h;try{h=kr(d)}catch{return!1}return Oo(e,`${s}.${i}`,h)},N="/_lunora/admin/auth",Lo={INVITER_REQUIRED:400,ORG_SLUG_INVALID:400,ORG_SLUG_TAKEN:409,PASSWORD_TOO_LONG:400,PASSWORD_TOO_SHORT:400,USER_ALREADY_EXISTS:409,USER_NOT_FOUND:404},C=(e,t)=>{const n=e[t];if(typeof n!="string"||n==="")throw new c(`\`${t}\` is required`,{code:"BAD_REQUEST",status:400});return n},he=(e,t)=>{const n=e(t);if(n===void 0)throw new c(`\`${t}\` query parameter is required`,{code:"BAD_REQUEST",status:400});return n},wn=e=>{if(typeof e=="string"||Array.isArray(e)&&e.every(t=>typeof t=="string"))return e},te=(e,t)=>typeof e[t]=="string"?e[t]:void 0,Ge=(e,t)=>{const n=e[t];return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:void 0},It=e=>{const t=wn(e.role);if(t===void 0||typeof t=="string"&&t.trim()==="")throw new c("`role` is required",{code:"BAD_REQUEST",status:400});return t},kt=e=>{const t=e.permission;if(typeof t!="object"||t===null||Array.isArray(t))throw new c("`permission` object is required",{code:"BAD_REQUEST",status:400});const n={};for(const[r,s]of Object.entries(t))Array.isArray(s)&&s.every(i=>typeof i=="string")&&(n[r]=s);return n},jo={[`${N}/capabilities`]:{build:()=>({}),http:"GET",method:"capabilities"},[`${N}/users`]:{build:({paging:e,query:t})=>{const n=t("sortDirection");return{...e,filterField:t("filterField"),filterValue:t("filterValue"),search:t("search"),searchField:t("searchField"),sortBy:t("sortBy"),sortDirection:n==="asc"||n==="desc"?n:void 0}},http:"GET",method:"listUsers"},[`${N}/sessions`]:{build:({paging:e,query:t})=>({...e,userId:t("userId")}),http:"GET",method:"listSessions"},[`${N}/accounts`]:{build:({query:e})=>({userId:he(e,"userId")}),http:"GET",method:"listAccounts"},[`${N}/passkeys`]:{build:({query:e})=>({userId:he(e,"userId")}),http:"GET",method:"listPasskeys"},[`${N}/organizations`]:{build:({paging:e})=>({...e}),http:"GET",method:"listOrganizations"},[`${N}/organizations/members`]:{build:({paging:e,query:t})=>({...e,organizationId:he(t,"organizationId")}),http:"GET",method:"listMembers"},[`${N}/organizations/invitations`]:{build:({paging:e,query:t})=>({...e,organizationId:he(t,"organizationId")}),http:"GET",method:"listInvitations"},[`${N}/sign-up-invitations`]:{build:({paging:e})=>({...e}),http:"GET",method:"listSignUpInvitations"},[`${N}/sign-up-invitations/create`]:{build:({body:e})=>({email:C(e,"email"),expiresInSeconds:typeof e.expiresInSeconds=="number"?e.expiresInSeconds:void 0,invitedBy:te(e,"invitedBy")}),http:"POST",method:"createSignUpInvitation"},[`${N}/sign-up-invitations/revoke`]:{build:({body:e})=>({email:C(e,"email")}),http:"POST",method:"revokeSignUpInvitation",returns:"void"},[`${N}/config`]:{build:()=>({}),http:"GET",method:"config"},[`${N}/organizations/teams`]:{build:({paging:e,query:t})=>({...e,organizationId:he(t,"organizationId")}),http:"GET",method:"listTeams"},[`${N}/organizations/teams/members`]:{build:({paging:e,query:t})=>({...e,teamId:he(t,"teamId")}),http:"GET",method:"listTeamMembers"},[`${N}/organizations/roles`]:{build:({paging:e,query:t})=>({...e,organizationId:he(t,"organizationId")}),http:"GET",method:"listOrgRoles"},[`${N}/users/create`]:{build:({body:e})=>({data:Ge(e,"data"),email:C(e,"email"),name:C(e,"name"),password:te(e,"password"),role:wn(e.role)}),http:"POST",method:"createUser"},[`${N}/users/update`]:{build:({body:e})=>{const{data:t}=e;if(typeof t!="object"||t===null||Array.isArray(t))throw new c("`data` object is required",{code:"BAD_REQUEST",status:400});return{data:t,userId:C(e,"userId")}},http:"POST",method:"updateUser"},[`${N}/users/role`]:{build:({body:e})=>({role:It(e),userId:C(e,"userId")}),http:"POST",method:"setRole"},[`${N}/users/ban`]:{build:({body:e})=>({expiresInSeconds:typeof e.expiresInSeconds=="number"?e.expiresInSeconds:void 0,reason:te(e,"reason"),userId:C(e,"userId")}),http:"POST",method:"banUser"},[`${N}/users/unban`]:{build:({body:e})=>({userId:C(e,"userId")}),http:"POST",method:"unbanUser"},[`${N}/users/password`]:{build:({body:e})=>({newPassword:C(e,"newPassword"),userId:C(e,"userId")}),http:"POST",method:"setUserPassword",returns:"void"},[`${N}/users/remove`]:{build:({body:e})=>({userId:C(e,"userId")}),http:"POST",method:"removeUser",returns:"void"},[`${N}/users/impersonate`]:{build:({body:e})=>({userId:C(e,"userId")}),http:"POST",method:"impersonateUser"},[`${N}/sessions/revoke`]:{build:({body:e})=>({sessionId:C(e,"sessionId")}),http:"POST",method:"revokeUserSession",returns:"void"},[`${N}/sessions/revoke-all`]:{build:({body:e})=>({userId:C(e,"userId")}),http:"POST",method:"revokeUserSessions",returns:"void"},[`${N}/accounts/unlink`]:{build:({body:e})=>({accountId:C(e,"accountId"),userId:C(e,"userId")}),http:"POST",method:"unlinkAccount",returns:"void"},[`${N}/two-factor/disable`]:{build:({body:e})=>({userId:C(e,"userId")}),http:"POST",method:"disableTwoFactor",returns:"void"},[`${N}/passkeys/delete`]:{build:({body:e})=>({passkeyId:C(e,"passkeyId")}),http:"POST",method:"deletePasskey",returns:"void"},[`${N}/organizations/members/remove`]:{build:({body:e})=>({memberId:C(e,"memberId")}),http:"POST",method:"removeMember",returns:"void"},[`${N}/organizations/invitations/cancel`]:{build:({body:e})=>({invitationId:C(e,"invitationId")}),http:"POST",method:"cancelInvitation",returns:"void"},[`${N}/organizations/create`]:{build:({body:e})=>({logo:te(e,"logo"),metadata:Ge(e,"metadata"),name:C(e,"name"),ownerId:te(e,"ownerId"),slug:te(e,"slug")}),http:"POST",method:"createOrganization"},[`${N}/organizations/update`]:{build:({body:e})=>({logo:te(e,"logo"),metadata:Ge(e,"metadata"),name:te(e,"name"),organizationId:C(e,"organizationId"),slug:te(e,"slug")}),http:"POST",method:"updateOrganization"},[`${N}/organizations/remove`]:{build:({body:e})=>({organizationId:C(e,"organizationId")}),http:"POST",method:"deleteOrganization",returns:"void"},[`${N}/organizations/members/add`]:{build:({body:e})=>({organizationId:C(e,"organizationId"),role:te(e,"role"),userId:C(e,"userId")}),http:"POST",method:"addMember"},[`${N}/organizations/members/invite`]:{build:({body:e})=>({email:C(e,"email"),inviterId:te(e,"inviterId"),organizationId:C(e,"organizationId"),role:te(e,"role")}),http:"POST",method:"inviteMember"},[`${N}/organizations/members/role`]:{build:({body:e})=>({memberId:C(e,"memberId"),role:It(e)}),http:"POST",method:"updateMemberRole"},[`${N}/organizations/teams/create`]:{build:({body:e})=>({name:C(e,"name"),organizationId:C(e,"organizationId")}),http:"POST",method:"createTeam"},[`${N}/organizations/teams/update`]:{build:({body:e})=>({name:C(e,"name"),teamId:C(e,"teamId")}),http:"POST",method:"updateTeam"},[`${N}/organizations/teams/remove`]:{build:({body:e})=>({teamId:C(e,"teamId")}),http:"POST",method:"removeTeam",returns:"void"},[`${N}/organizations/teams/members/add`]:{build:({body:e})=>({teamId:C(e,"teamId"),userId:C(e,"userId")}),http:"POST",method:"addTeamMember"},[`${N}/organizations/teams/members/remove`]:{build:({body:e})=>({teamMemberId:C(e,"teamMemberId")}),http:"POST",method:"removeTeamMember",returns:"void"},[`${N}/organizations/roles/create`]:{build:({body:e})=>({organizationId:C(e,"organizationId"),permission:kt(e),role:C(e,"role")}),http:"POST",method:"createOrgRole"},[`${N}/organizations/roles/update`]:{build:({body:e})=>({permission:kt(e),roleId:C(e,"roleId")}),http:"POST",method:"updateOrgRole"},[`${N}/organizations/roles/remove`]:{build:({body:e})=>({roleId:C(e,"roleId")}),http:"POST",method:"deleteOrgRole",returns:"void"}},Mo=e=>{const t=async s=>{try{return await s()}catch(i){if(i instanceof c)throw i;const d=i,f=typeof d.code=="string"?d.code:"AUTH_ADMIN_ERROR";throw console.error("[lunora] auth admin operation failed:",i),new c("auth admin operation failed",{code:f,status:Lo[f]??500})}},n=async(s,i)=>{if(e.assertAdmin(s),s.method!==i.http)throw new c(`Auth admin endpoint requires ${i.http}`,{code:"METHOD_NOT_ALLOWED",status:405});const d=e.getAuthAdmin();if(d===void 0)throw new c("auth endpoints require an `authAdmin` on the worker",{code:"AUTH_NOT_CONFIGURED",status:400});const f=d[i.method];if(f===void 0)throw new c(`auth admin does not support \`${i.method}\``,{code:"AUTH_OP_NOT_SUPPORTED",status:400});const h=new URL(s.url),m={body:i.http==="POST"?await e.readJsonBody(s):{},paging:e.parsePaging(s),query:S=>e.queryParameter(h,S)},b=i.build(m),T=await t(()=>f(b));return Response.json(i.returns==="void"?{ok:!0}:T,{headers:{"cache-control":"no-store","content-type":"application/json"},status:200})},r={};for(const[s,i]of Object.entries(jo))r[s]=d=>n(d,i);return r},Pt="__lunora_admin__:getAuthAuditLog",Dt=e=>typeof e=="string"&&e!==""?e:void 0,Nt=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0,$o=e=>async(n,r)=>{e.assertAdmin(n);const s=e.getReader();if(s===void 0)throw new c("the auth/security audit endpoint requires an `authAuditReader` on the worker",{code:"AUTH_AUDIT_NOT_CONFIGURED",status:400});const i=Dt(r.actorId),d=Dt(r.event),f=Nt(r.sinceSeq),h=Nt(r.limit),m={...i===void 0?{}:{actorId:i},...d===void 0?{}:{event:d},...f===void 0?{}:{sinceSeq:f},...h===void 0?{}:{limit:h}};let b;try{b=await s.read(m)}catch(S){throw S instanceof c?S:(console.error("[lunora] auth audit read failed:",S),new c("auth audit read failed",{code:"AUTH_AUDIT_READ_FAILED",status:500}))}const T={entries:b};return Response.json({result:Te(T)},{headers:{"content-type":"application/json"},status:200})},tt="__lunora_admin__:copyAuthToJurisdiction",gn="__lunora_admin__:purgeUnpinnedAuth",Ko=e=>async(t,n,r)=>{if(n!==tt&&n!==gn)return;e.assertAdmin(t);const s=e.getMove();if(s===void 0)throw new c("moving auth into the jurisdiction needs DO-backed auth pinned with `.jurisdiction(…, { pinAuth: true })`",{code:"AUTH_MOVE_NOT_CONFIGURED",status:400});const i=n===tt?await s.copy({force:r.force===!0}):await s.purge();return Response.json({result:Te(i)},{headers:{"content-type":"application/json"},status:200})},Fo=(e,t)=>{const n=[],r=[];if(t&&t.length>0)for(const s of t)e.resolveTableSharding?.(s)?.mode.kind==="global"?r.push(s):n.push(s);return{globalTables:r,shardLocalTables:n}},Go=async(e,t,n,r,s,i)=>{if(n!==void 0&&r.length===0)return[];const d=await e.orchestrateExport(s,{args:{tables:r},defaultShardKey:i,headers:t,tables:r}),f=d.shards.filter(h=>h.error);if(f.length>0){const h=f.map(m=>`${m.shardKey}: ${m.error?.message??"unknown error"}`).join("; ");throw new c(`export failed on ${String(f.length)} of ${String(d.shards.length)} shard(s) — ${h}`,{code:"EXPORT_SHARD_FAILED",status:502})}return d.shards.flatMap(h=>h.rows??[])},yn=async(e,t,n,r,s)=>{const i=r??e.listSchemaTables?.();r===void 0&&e.listSchemaTables===void 0&&console.warn("[lunora] export: no table list available (`listSchemaTables` is unset and no `tables` were named), so only the default shard is reachable. A `.shardBy()` deployment's other shards will be missing from this export. Name the tables explicitly, or regenerate the worker so codegen supplies the list.");const{globalTables:d,shardLocalTables:f}=Fo(e,i),h=await Go(t,n,i,f,s,e.defaultShardKey??"__root__"),m=e.exportGlobals,b=r===void 0||d.length>0;return(async function*(){yield*h,b&&m&&(yield*m({tables:d}))})()},Qo=async(e,t,n,r,s,i)=>{for await(const d of await yn(e,t,n,r,i))s(d)},Wo=new TextEncoder,zo=1e3,bn=10,Vo=200,Ut=8,_n="lunoraBackupCron",Ct=24*1048576,Bt=e=>{const t=e.slice(0,bn).map(r=>dn(r)),n=e.length-t.length;return`${t.join(", ")}${n>0?` (+${String(n)} more)`:""}`},Jo=(e,t)=>{const n=new Uint8Array(new ArrayBuffer(t));let r=0;for(const s of e)n.set(s,r),r+=s.byteLength;return n},it=async(e,t,n,r)=>{if(n===void 0||!Number.isInteger(n)||n<=0)return{eligible:0,stale:[]};const s=[];let i;for(let d=0;d<zo;d+=1){const f=await e.list({cursor:i,include:["customMetadata"],prefix:t});for(const h of f.objects)Cr(h.key)&&h.customMetadata?.[_n]===r&&s.push(h.key);if(!f.truncated||f.cursor===void 0)break;i=f.cursor}return{eligible:s.length,stale:s.toSorted((d,f)=>f.localeCompare(d)).slice(n)}},Yo=async(e,t,n,r,s)=>{const{stale:i}=await it(e,t,n,r),d=new Set(s),f=i.filter(k=>d.has(k)),h=f.slice(0,Vo),m=i.length-h.length,b=s.length-f.length;if(h.length===0)return{deleted:[],failed:[],ignored:b,remaining:m};const T=[],S=[];for(let k=0;k<h.length;k+=Ut){const w=await Promise.allSettled(h.slice(k,k+Ut).map(async g=>(await e.delete(dn(g)),await e.delete(g),g)));for(const[g,y]of w.entries())y.status==="fulfilled"?T.push(y.value):S.push(h[k+g])}return T.length>0&&console.info(`[lunora] backup prune kept the newest ${String(n)} and deleted ${String(T.length)}: ${Bt(T)}`),S.length>0&&console.warn(`[lunora] backup prune failed to remove ${String(S.length)}: ${Bt(S)}`),{deleted:T,failed:S,ignored:b,remaining:m}},qo=async e=>{const t=e.backupStore;if(!t)throw new c("backup retention preview requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});const n=ot(e.backupPrefix??st),r=e.backupCron,{eligible:s,stale:i}=r===void 0?{eligible:0,stale:[]}:await it(t,n,e.backupRetain,r);return{cron:r,eligible:s,keep:e.backupRetain??0,prefix:n,wouldDelete:i}},Xo=async(e,t,n,r,s)=>{const i=e.backupStore;if(!i)throw new c("scheduled backup requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});if(!r||r.length===0)throw new c("scheduled backup requires an `adminToken` (or `env.LUNORA_ADMIN_TOKEN`) to authenticate the per-shard export gate",{code:"BACKUP_NOT_CONFIGURED",status:500});const d={authorization:`Bearer ${r}`,"content-type":"application/json"},f=e.backupTables;let h=0,m=0,b=[];await Qo(e,t,d,f,I=>{const E=Wo.encode(`${JSON.stringify(I)}
2
2
  `);if(h+=1,m+=E.byteLength,m>Ct)throw new c(`scheduled backup reached ${String(m)} bytes of NDJSON, past the ${String(Ct)}-byte limit for a snapshot assembled inside a Worker — nothing was written. Narrow it with \`backupTables\`, or take this snapshot off-platform with \`lunora backup create --bucket\`.`,{code:"BACKUP_TOO_LARGE",status:507});b.push(E)},n);const S=ot(e.backupPrefix??st),k=new Date(s.scheduledTime).toISOString(),w=Br(S,k),g=Jo(b,m);b=[];const y=Hr(await crypto.subtle.digest("SHA-256",g));await i.put(w,g,{httpMetadata:{contentType:"application/x-ndjson"},sha256:y});const O={bytes:m,createdAt:k,cron:s.cron,file:w,id:k,rows:h,scheduledTime:s.scheduledTime,sha256:y,...f?{tables:f.join(",")}:{}};await i.put(xr(w),`${JSON.stringify(O,void 0,2)}
3
3
  `,{customMetadata:{[_n]:s.cron},httpMetadata:{contentType:"application/json"}});try{const{stale:I}=await it(i,S,e.backupRetain,s.cron);if(I.length>0){const E=I.slice(0,bn),H=I.length-E.length;console.info(`[lunora] backup retention: ${String(I.length)} snapshot(s) past the newest ${String(e.backupRetain)} — run \`lunora backup prune\` to remove them: ${E.join(", ")}${H>0?` (+${String(H)} more)`:""}`)}}catch(I){console.warn(`[lunora] backup ${w} was written, but the retention report failed:`,I)}},Zo=async(e,t)=>{const n=e.backupStore;if(!n)throw new c("backup prune requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});const r=e.backupCron,s=e.backupRetain;if(r===void 0||s===void 0||!Number.isInteger(s)||s<=0)throw new c("backup prune needs a retention window: set `backupRetain` (and `backupCron`, which decides whose snapshots retention owns) on the worker. Without one there is nothing past the window to remove.",{code:"BACKUP_RETENTION_NOT_CONFIGURED",status:400});return Yo(n,ot(e.backupPrefix??st),s,r,t)},es="/_lunora/admin/backup/retention",ts="/_lunora/admin/backup/prune",ns=e=>{const{options:t,readJsonBody:n,requireAdminOption:r}=e,s=(f,h)=>{r(f,t.backupStore,{code:"BACKUP_NOT_CONFIGURED",message:`backup ${h} requires a \`backupStore\` on the worker`})},i=async f=>(M(f,"GET","Backup-retention"),s(f,"retention preview"),Response.json(await qo(t),{headers:{"cache-control":"no-store"}})),d=async f=>{M(f,"POST","Backup-prune"),s(f,"prune");const{confirm:h}=await n(f);if(!Array.isArray(h)||h.some(m=>typeof m!="string"))throw new c("backup prune requires a `confirm` array of the sidecar keys to remove — read them from `GET /_lunora/admin/backup/retention` and pass back the ones you mean to delete",{code:"BAD_REQUEST",status:400});return Response.json(await Zo(t,h),{headers:{"cache-control":"no-store"}})};return{[ts]:d,[es]:i}},xt=500,rs=(e,t,n)=>{if(typeof e!="object"||e===null||Array.isArray(e))throw new c("each batch call must be an object",{code:"BAD_REQUEST",status:400});const r=e;if(typeof r.functionPath!="string")throw new c("each batch call needs a string `functionPath`",{code:"BAD_REQUEST",status:400});if(r.functionPath.startsWith("__lunora_relation__:")||r.functionPath.startsWith("__lunora_admin__"))throw new c("reserved function path cannot be batched",{code:"FORBIDDEN",status:403});if(r.args!==void 0&&(typeof r.args!="object"||r.args===null||Array.isArray(r.args)))throw new c("each batch call `args` must be an object",{code:"BAD_REQUEST",status:400});if(r.id!==void 0&&typeof r.id!="number")throw new c("each batch call `id` must be a number",{code:"BAD_REQUEST",status:400});return{entry:{args:r.args===void 0?{}:r.args,baselineSeq:typeof r.baselineSeq=="number"?r.baselineSeq:void 0,clientId:typeof r.clientId=="string"?r.clientId:void 0,clientSeq:typeof r.clientSeq=="number"?r.clientSeq:void 0,functionPath:r.functionPath,id:typeof r.id=="number"?r.id:t,mutationId:typeof r.mutationId=="string"?r.mutationId:void 0},shardKey:typeof r.shardKey=="string"?r.shardKey:n}},os=(e,t)=>{if(e.length>xt)throw new c(`RPC batch exceeds the ${String(xt)}-call limit`,{code:"BAD_REQUEST",status:400});const n=new Map,r=new Set;for(const[s,i]of e.entries()){const{entry:d,shardKey:f}=rs(i,s,t);if(r.has(d.id))throw new c(`batch call id ${String(d.id)} is used twice; ids must be distinct`,{code:"BAD_REQUEST",status:400});r.add(d.id);const h=n.get(f)??[];h.push(d),n.set(f,h)}return n},ss="/_lunora/admin/export",as="/_lunora/admin/import",is="/_lunora/admin/sync",cs="/_lunora/admin/connector/sync",ds="/_lunora/admin/apply",us="/_lunora/admin/export-tap/run",ls=new TextEncoder,hs=async e=>{const n=await ne(e,"Export")??{};if(n.tables===void 0)return{tables:void 0};if(!Array.isArray(n.tables))throw new c("Export `tables` must be a string array",{code:"BAD_REQUEST",status:400});const r=[];for(const s of n.tables){if(typeof s!="string"||s.length===0)throw new c("Export `tables` entries must be non-empty strings",{code:"BAD_REQUEST",status:400});r.push(s)}return{tables:r}},Qe=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):void 0,fs=e=>{const{applyGlobals:t,defaultShardKey:n,exportCursorStore:r,exportSinks:s,knownTables:i,queryCoordinator:d,assertAdmin:f,resolveForwardContext:h,shardDO:m,prepareExportRows:b,streamingImport:T,syncGlobals:S}=e,k=async(E,H)=>{const L=me(E,["POST"]);if(L)return L;f(E);const U=await hs(E),{headers:F}=await h(E,H),q=await b(F,U.tables),W=new ReadableStream({async pull(z){try{for await(const V of q)z.enqueue(ls.encode(`${JSON.stringify(V)}
4
4
  `));z.close()}catch(V){z.error(V)}}});return new Response(W,{headers:{"content-type":"application/x-ndjson"},status:200})},w=async(E,H)=>{const L=me(E,["POST"]);if(L)return L;f(E);const U=await ee(E),F=typeof U.cursors=="object"&&U.cursors!==null?U.cursors:{},q=typeof U.epochs=="object"&&U.epochs!==null?U.epochs:{},W=typeof U.limit=="number"?U.limit:void 0,z=typeof U.globalCursor=="number"?U.globalCursor:0,V=Qe(U.tables),{headers:re}=await h(E,H),Q=V??i(),ce=await d.orchestrateCdcSync(m,{cursors:F,defaultShardKey:n,epochs:q,headers:re,limit:W,tables:Q}),$=S?await S({limit:W,sinceSeq:z}):void 0;return Response.json({global:$,shards:ce.shards},{status:200})},g=async(E,H)=>{const L=me(E,["POST"]);if(L)return L;f(E);const U=await ee(E),F=Kr(U.cursor),q=typeof U.limit=="number"&&U.limit>0?U.limit:void 0,W=Qe(U.tables),{headers:z}=await h(E,H),V=W??i(),re=await d.orchestrateCdcSync(m,{cursors:F.s,defaultShardKey:n,headers:z,limit:q,tables:V}),Q=[],ce={...F.s};let $=!1;for(const se of re.shards)$=Rt(Q,se.changes??[],Gr(q))||$,ce[se.shardKey]=se.cursor;let oe=F.g;if(S){const se=await S({limit:q,sinceSeq:F.g});$=Rt(Q,se.changes,q)||$,oe=se.cursor}const Be=Fr({g:oe,s:ce,v:1}),xe={changes:Q,hasMore:$,nextCursor:Be};return Response.json(xe,{status:200})},y=async(E,H)=>{const L=me(E,["POST"]);if(L)return L;f(E);const U=await ee(E),q=(Array.isArray(U.batches)?U.batches:[]).map(Q=>Q).filter(Q=>Q!==null&&typeof Q=="object"&&typeof Q.shardKey=="string"&&Array.isArray(Q.changes)),W=Array.isArray(U.globalChanges)?U.globalChanges:[],{headers:z}=await h(E,H),V=await d.orchestrateApplyCdc(m,{batches:q,headers:z}),re=W.length>0&&t?await t({changes:W}):0;return Response.json({applied:V.applied+re,failed:V.failed,ok:V.ok},{status:200})},O=async(E,H)=>{const L=me(E,["POST"]);if(L)return L;f(E);const{headers:U}=await h(E,H),F=await T(E,U);return Response.json(F,{headers:{"content-type":"application/json"},status:F.failed.length>0?207:200})},I=async(E,H)=>{const L=me(E,["POST"]);if(L)return L;if(f(E),s===void 0||Object.keys(s).length===0||r===void 0)throw new c("Export-tap endpoint requires `exportSinks` + `exportCursorStore` on the worker",{code:"EXPORT_TAP_NOT_CONFIGURED",status:400});const U=await ee(E),F=typeof U.sink=="string"?U.sink:void 0,q=typeof U.limit=="number"&&U.limit>0?U.limit:void 0,W=Qe(U.tables);if(F===void 0)throw new c("Export-tap `sink` must name a configured sink",{code:"BAD_REQUEST",status:400});const z=s[F];if(z===void 0)throw new c(`Export-tap sink "${F}" is not configured`,{code:"NOT_FOUND",status:404});const{headers:V}=await h(E,H),re=W??i(),Q=await $r({coordinator:d,cursorStore:r,defaultShardKey:n,headers:V,limit:q,shardDO:m,sink:z,tables:re});return Response.json(Q,{headers:{"content-type":"application/json"},status:200})};return{[ds]:y,[cs]:g,[ss]:k,[us]:I,[as]:O,[is]:w}},ps=(e,t)=>{let n;try{n=JSON.parse(e)}catch{return{error:{code:"BAD_ROW",line:t,message:"line is not valid JSON",table:""},ok:!1}}if(!n||typeof n!="object"||Array.isArray(n))return{error:{code:"BAD_ROW",line:t,message:"row must be a JSON object",table:""},ok:!1};const r=n;return typeof r.table!="string"||r.table.length===0?{error:{code:"BAD_ROW",line:t,message:"row is missing `table`",table:""},ok:!1}:!r.doc||typeof r.doc!="object"||Array.isArray(r.doc)?{error:{code:"BAD_ROW",line:t,message:"row is missing or malformed `doc`",table:r.table},ok:!1}:{doc:r.doc,ok:!0,table:r.table}},ms=(e,t,n,r,s)=>{if(n?.mode.kind==="shardBy"&&typeof n.mode.field=="string"){const i=e[n.mode.field];return i==null?{error:{code:"BAD_ROW",line:s,message:`row missing shard field "${n.mode.field}" for table "${t}"`,table:t},ok:!1}:{ok:!0,shardKey:typeof i=="string"?i:JSON.stringify(i)}}return{ok:!0,shardKey:r}},ws=async(e,t,n)=>{if(!e.body)throw new c("Import endpoint requires a request body",{code:"BAD_REQUEST",status:400});const r=[],s=[],i=new Map;let d=0,f=0;const h=e.body.getReader(),m=new TextDecoder;let b="",T=0;const S=k=>{f+=1;const w=k.trim();if(w.length===0)return;d+=1;const g=ps(w,f);if(!g.ok){r.push(g.error);return}const{doc:y,table:O}=g,I=t.resolveTableSharding?.(O);if(I?.mode.kind==="global"){s.push({doc:y,line:f,table:O});return}const E=ms(y,O,I,n,f);if(!E.ok){r.push(E.error);return}const H=i.get(E.shardKey);H?H.rows.push({doc:y,table:O}):i.set(E.shardKey,{rows:[{doc:y,table:O}],shardKey:E.shardKey,startLine:f})};for(;;){const{done:k,value:w}=await h.read();if(k)break;if(w&&(T+=w.byteLength,T>sn))throw await h.cancel().catch(()=>{}),new c("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});b+=m.decode(w,{stream:!0});let g=b.indexOf(`
@@ -0,0 +1 @@
1
+ import{LunoraError as O}from"./LunoraError-DksAgIpa.mjs";const E=new Set(["0","disabled","false","no","off"]),y=new Set(["1","enabled","on","true","yes"]),d=e=>typeof e=="string"&&E.has(e.trim().toLowerCase()),S=e=>typeof e=="string"&&y.has(e.trim().toLowerCase()),L="default-src 'none'; frame-ancestors 'none'; base-uri 'none'; form-action 'none'",A=e=>{const o=["base-uri 'none'","object-src 'none'"];return e==="DENY"?o.push("frame-ancestors 'none'"):e==="SAMEORIGIN"&&o.push("frame-ancestors 'self'"),o.join("; ")},b="accelerometer=(), autoplay=(), camera=(), display-capture=(), geolocation=(), gyroscope=(), magnetometer=(), microphone=(), payment=(), usb=()",u=["Authorization","Content-Type","Last-Event-ID","X-D1-Bookmark","X-Lunora-Client-Id","X-Lunora-Client-Seq","X-Lunora-Expect-Subject","X-Lunora-Min-Seq","X-Lunora-Mutation-Id","X-Lunora-Shard-Key"],f=["DELETE","GET","HEAD","PATCH","POST","PUT"],v=31536e3,C=new Set(["GET","HEAD","OPTIONS"]),R=e=>{if(e===!1)return;const o=e===void 0||e===!0?{}:e,s=o.maxAge??v,r=o.includeSubDomains??!0;return`max-age=${String(s)}${r?"; includeSubDomains":""}${o.preload?"; preload":""}`},D=(e,o)=>{if(e!==!1)return typeof e=="string"?{htmlValue:e,value:e}:{htmlValue:o,value:L}},_=e=>{if(e===!1)return{coop:void 0,csp:void 0,enabled:!1,frameOptions:void 0,hsts:void 0,permissionsPolicy:void 0,referrerPolicy:void 0};const o=e===void 0||e===!0?{}:e,s=o.frameOptions===!1?void 0:o.frameOptions??"SAMEORIGIN";return{coop:"same-origin",csp:D(o.csp,A(s)),enabled:!0,frameOptions:s,hsts:R(o.hsts),permissionsPolicy:o.permissionsPolicy===!1?void 0:o.permissionsPolicy??b,referrerPolicy:o.referrerPolicy===!1?void 0:o.referrerPolicy??"strict-origin-when-cross-origin"}},N=e=>{const o={allowCredentials:!1,allowedHeaders:u,allowedMethods:f,enabled:!1,isAllowed:()=>!1,isExplicitlyAllowed:()=>!1,maxAge:600};if(e===void 0||e===!1)return o;const s=e.allowCredentials??!1,r=e.allowedOrigins;let t,n;if(typeof r=="function"){const a=m=>r(m)===!0;t=a,n=a,console.warn(`@lunora/runtime: security.cors uses a custom \`allowedOrigins\` predicate. It is trusted by the CSRF and WebSocket origin checks${s?" AND reflects matching origins with credentials (`allowCredentials: true`)":""} — ensure it matches ONLY trusted origins by exact equality; an over-broad predicate (e.g. \`() => true\`, or \`endsWith\`/\`includes\` checks) defeats the allowlist.`)}else{const a=r;if(a.includes("*")&&s)throw new O('@lunora/runtime: security.cors cannot combine a wildcard origin ("*") with allowCredentials: true — browsers reject it and it defeats the allowlist.');t=i=>a.includes("*")||a.includes(i),n=i=>a.includes(i)}return{allowCredentials:s,allowedHeaders:[...new Set([...u,...e.allowedHeaders??[]])],allowedMethods:e.allowedMethods??f,enabled:!0,isAllowed:t,isExplicitlyAllowed:n,maxAge:e.maxAge??600}},H=e=>{if(e===!1)return{allowLoopback:!1,enabled:!1,trustedOrigins:[]};const o=e===void 0||e===!0?{}:e;return{allowLoopback:o.allowLoopback??!0,enabled:!0,trustedOrigins:o.trustedOrigins??[]}},I=e=>{const o=e?.LUNORA_ALLOWED_ORIGINS;if(typeof o!="string")return;const s=o.split(",").map(n=>n.trim()).filter(n=>n.length>0);return s.length===0?void 0:{allowCredentials:!s.includes("*")&&S(e?.LUNORA_CORS_ALLOW_CREDENTIALS),allowedOrigins:s}},j=(e,o)=>{const s=e?.headers??(d(o?.LUNORA_SECURITY_HEADERS)?!1:void 0),r=e?.csrf??(d(o?.LUNORA_SECURITY_CSRF)?!1:void 0),t=e?.cors??I(o);return{cors:N(t),csrf:H(r),headers:_(s)}},x=new Set(["127.0.0.1","::1","[::1]","localhost"]),p=e=>{try{return x.has(new URL(e).hostname)}catch{return!1}},c=e=>{if(e)try{return new URL(e).origin}catch{return}},w=(e,o,s)=>e===o||s.csrf.trustedOrigins.includes(e)||s.csrf.allowLoopback&&p(o)&&p(e)?!0:s.cors.enabled&&s.cors.isExplicitlyAllowed(e),h=(e,o,s)=>Response.json({error:{code:"FORBIDDEN_ORIGIN",expectedOrigin:s,message:`${e} rejected: Origin ${o===void 0?"was missing":`"${o}"`} is not trusted (this worker serves "${s}"). Add it to \`security.csrf.trustedOrigins\` (or LUNORA_ALLOWED_ORIGINS) if it is yours. Behind a dev proxy this usually means the proxy rewrote the host: keep both ends on loopback, or list the dev-server origin.`,receivedOrigin:o}},{headers:{"content-type":"application/json"},status:403}),X=(e,o)=>{if(!o.csrf.enabled||C.has(e.method)||!e.headers.get("cookie"))return;const s=new URL(e.url).origin,r=c(e.headers.get("origin"))??c(e.headers.get("referer"));if(!(r!==void 0&&w(r,s,o)))return h("cross-origin state-changing request",r,s)},F=(e,o)=>{if(!o.csrf.enabled||!e.headers.get("cookie"))return;const s=new URL(e.url).origin,r=c(e.headers.get("origin"));if(!(r!==void 0&&w(r,s,o)))return h("cross-origin websocket upgrade",r,s)},P=["X-D1-Bookmark","X-Lunora-Edge-Cache","X-Lunora-Shard-Key"],g=(e,o)=>{const s=new Headers;return s.set("access-control-allow-origin",e),s.set("access-control-expose-headers",P.join(", ")),s.append("vary","Origin"),o.allowCredentials&&s.set("access-control-allow-credentials","true"),s},B=(e,o)=>{if(!o.cors.enabled||e.method!=="OPTIONS")return;const s=e.headers.get("origin");if(!s||!e.headers.get("access-control-request-method")||!o.cors.isAllowed(s))return;const r=g(s,o.cors),t=e.headers.get("access-control-request-headers");r.set("access-control-allow-methods",o.cors.allowedMethods.join(", "));let n;if(t===null)n=o.cors.allowedHeaders.join(", ");else{const a=new Set(o.cors.allowedHeaders.map(i=>i.toLowerCase()));n=t.split(",").map(i=>i.trim()).filter(i=>i.length>0&&a.has(i.toLowerCase())).join(", ")}return r.set("access-control-allow-headers",n),r.set("access-control-max-age",String(o.cors.maxAge)),new Response(null,{headers:r,status:204})},T=e=>(e.headers.get("content-type")??"").toLowerCase().includes("text/html"),l=(e,o,s)=>{e.has(o)||e.set(o,s)},k=(e,o,s,r)=>{if(r.hsts!==void 0&&new URL(o.url).protocol==="https:"&&l(e,"strict-transport-security",r.hsts),l(e,"x-content-type-options","nosniff"),r.frameOptions!==void 0&&l(e,"x-frame-options",r.frameOptions),r.referrerPolicy!==void 0&&l(e,"referrer-policy",r.referrerPolicy),r.permissionsPolicy!==void 0&&l(e,"permissions-policy",r.permissionsPolicy),r.coop!==void 0&&l(e,"cross-origin-opener-policy",r.coop),r.csp!==void 0){const t=T(s)?r.csp.htmlValue:r.csp.value;t!==void 0&&l(e,"content-security-policy",t)}},U=(e,o,s)=>{const r=o.headers.get("origin");if(!(!r||!s.isAllowed(r)))for(const[t,n]of g(r,s).entries())t==="vary"?e.append("vary",n):l(e,t,n)},V=(e,o,s)=>{if(e.status===101||e.webSocket)return e;const r=new Headers(e.headers);return s.headers.enabled&&k(r,o,e,s.headers),s.cors.enabled&&U(r,o,s.cors),new Response(e.body,{headers:r,status:e.status,statusText:e.statusText})};export{V as decorateResponse,X as enforceOrigin,F as enforceWebSocketOrigin,B as handleCorsPreflight,j as resolveSecurity};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/runtime",
3
- "version": "1.0.0-alpha.207",
3
+ "version": "1.0.0-alpha.208",
4
4
  "description": "Lunora Worker runtime: the RPC router, shard resolver, and query coordinator",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -1 +0,0 @@
1
- import{LunoraError as O}from"./LunoraError-DksAgIpa.mjs";const E=new Set(["0","disabled","false","no","off"]),y=new Set(["1","enabled","on","true","yes"]),d=e=>typeof e=="string"&&E.has(e.trim().toLowerCase()),S=e=>typeof e=="string"&&y.has(e.trim().toLowerCase()),L="default-src 'none'; frame-ancestors 'none'; base-uri 'none'; form-action 'none'",A=e=>{const o=["base-uri 'none'","object-src 'none'"];return e==="DENY"?o.push("frame-ancestors 'none'"):e==="SAMEORIGIN"&&o.push("frame-ancestors 'self'"),o.join("; ")},b="accelerometer=(), autoplay=(), camera=(), display-capture=(), geolocation=(), gyroscope=(), magnetometer=(), microphone=(), payment=(), usb=()",u=["Authorization","Content-Type","X-D1-Bookmark","X-Lunora-Client-Id","X-Lunora-Client-Seq","X-Lunora-Expect-Subject","X-Lunora-Min-Seq","X-Lunora-Mutation-Id","X-Lunora-Shard-Key"],f=["DELETE","GET","HEAD","PATCH","POST","PUT"],C=31536e3,v=new Set(["GET","HEAD","OPTIONS"]),R=e=>{if(e===!1)return;const o=e===void 0||e===!0?{}:e,s=o.maxAge??C,r=o.includeSubDomains??!0;return`max-age=${String(s)}${r?"; includeSubDomains":""}${o.preload?"; preload":""}`},D=(e,o)=>{if(e!==!1)return typeof e=="string"?{htmlValue:e,value:e}:{htmlValue:o,value:L}},_=e=>{if(e===!1)return{coop:void 0,csp:void 0,enabled:!1,frameOptions:void 0,hsts:void 0,permissionsPolicy:void 0,referrerPolicy:void 0};const o=e===void 0||e===!0?{}:e,s=o.frameOptions===!1?void 0:o.frameOptions??"SAMEORIGIN";return{coop:"same-origin",csp:D(o.csp,A(s)),enabled:!0,frameOptions:s,hsts:R(o.hsts),permissionsPolicy:o.permissionsPolicy===!1?void 0:o.permissionsPolicy??b,referrerPolicy:o.referrerPolicy===!1?void 0:o.referrerPolicy??"strict-origin-when-cross-origin"}},N=e=>{const o={allowCredentials:!1,allowedHeaders:u,allowedMethods:f,enabled:!1,isAllowed:()=>!1,isExplicitlyAllowed:()=>!1,maxAge:600};if(e===void 0||e===!1)return o;const s=e.allowCredentials??!1,r=e.allowedOrigins;let t,n;if(typeof r=="function"){const a=m=>r(m)===!0;t=a,n=a,console.warn(`@lunora/runtime: security.cors uses a custom \`allowedOrigins\` predicate. It is trusted by the CSRF and WebSocket origin checks${s?" AND reflects matching origins with credentials (`allowCredentials: true`)":""} — ensure it matches ONLY trusted origins by exact equality; an over-broad predicate (e.g. \`() => true\`, or \`endsWith\`/\`includes\` checks) defeats the allowlist.`)}else{const a=r;if(a.includes("*")&&s)throw new O('@lunora/runtime: security.cors cannot combine a wildcard origin ("*") with allowCredentials: true — browsers reject it and it defeats the allowlist.');t=i=>a.includes("*")||a.includes(i),n=i=>a.includes(i)}return{allowCredentials:s,allowedHeaders:[...new Set([...u,...e.allowedHeaders??[]])],allowedMethods:e.allowedMethods??f,enabled:!0,isAllowed:t,isExplicitlyAllowed:n,maxAge:e.maxAge??600}},H=e=>{if(e===!1)return{allowLoopback:!1,enabled:!1,trustedOrigins:[]};const o=e===void 0||e===!0?{}:e;return{allowLoopback:o.allowLoopback??!0,enabled:!0,trustedOrigins:o.trustedOrigins??[]}},I=e=>{const o=e?.LUNORA_ALLOWED_ORIGINS;if(typeof o!="string")return;const s=o.split(",").map(n=>n.trim()).filter(n=>n.length>0);return s.length===0?void 0:{allowCredentials:!s.includes("*")&&S(e?.LUNORA_CORS_ALLOW_CREDENTIALS),allowedOrigins:s}},j=(e,o)=>{const s=e?.headers??(d(o?.LUNORA_SECURITY_HEADERS)?!1:void 0),r=e?.csrf??(d(o?.LUNORA_SECURITY_CSRF)?!1:void 0),t=e?.cors??I(o);return{cors:N(t),csrf:H(r),headers:_(s)}},x=new Set(["127.0.0.1","::1","[::1]","localhost"]),p=e=>{try{return x.has(new URL(e).hostname)}catch{return!1}},c=e=>{if(e)try{return new URL(e).origin}catch{return}},w=(e,o,s)=>e===o||s.csrf.trustedOrigins.includes(e)||s.csrf.allowLoopback&&p(o)&&p(e)?!0:s.cors.enabled&&s.cors.isExplicitlyAllowed(e),h=(e,o,s)=>Response.json({error:{code:"FORBIDDEN_ORIGIN",expectedOrigin:s,message:`${e} rejected: Origin ${o===void 0?"was missing":`"${o}"`} is not trusted (this worker serves "${s}"). Add it to \`security.csrf.trustedOrigins\` (or LUNORA_ALLOWED_ORIGINS) if it is yours. Behind a dev proxy this usually means the proxy rewrote the host: keep both ends on loopback, or list the dev-server origin.`,receivedOrigin:o}},{headers:{"content-type":"application/json"},status:403}),X=(e,o)=>{if(!o.csrf.enabled||v.has(e.method)||!e.headers.get("cookie"))return;const s=new URL(e.url).origin,r=c(e.headers.get("origin"))??c(e.headers.get("referer"));if(!(r!==void 0&&w(r,s,o)))return h("cross-origin state-changing request",r,s)},F=(e,o)=>{if(!o.csrf.enabled||!e.headers.get("cookie"))return;const s=new URL(e.url).origin,r=c(e.headers.get("origin"));if(!(r!==void 0&&w(r,s,o)))return h("cross-origin websocket upgrade",r,s)},P=["X-D1-Bookmark","X-Lunora-Edge-Cache","X-Lunora-Shard-Key"],g=(e,o)=>{const s=new Headers;return s.set("access-control-allow-origin",e),s.set("access-control-expose-headers",P.join(", ")),s.append("vary","Origin"),o.allowCredentials&&s.set("access-control-allow-credentials","true"),s},B=(e,o)=>{if(!o.cors.enabled||e.method!=="OPTIONS")return;const s=e.headers.get("origin");if(!s||!e.headers.get("access-control-request-method")||!o.cors.isAllowed(s))return;const r=g(s,o.cors),t=e.headers.get("access-control-request-headers");r.set("access-control-allow-methods",o.cors.allowedMethods.join(", "));let n;if(t===null)n=o.cors.allowedHeaders.join(", ");else{const a=new Set(o.cors.allowedHeaders.map(i=>i.toLowerCase()));n=t.split(",").map(i=>i.trim()).filter(i=>i.length>0&&a.has(i.toLowerCase())).join(", ")}return r.set("access-control-allow-headers",n),r.set("access-control-max-age",String(o.cors.maxAge)),new Response(null,{headers:r,status:204})},T=e=>(e.headers.get("content-type")??"").toLowerCase().includes("text/html"),l=(e,o,s)=>{e.has(o)||e.set(o,s)},k=(e,o,s,r)=>{if(r.hsts!==void 0&&new URL(o.url).protocol==="https:"&&l(e,"strict-transport-security",r.hsts),l(e,"x-content-type-options","nosniff"),r.frameOptions!==void 0&&l(e,"x-frame-options",r.frameOptions),r.referrerPolicy!==void 0&&l(e,"referrer-policy",r.referrerPolicy),r.permissionsPolicy!==void 0&&l(e,"permissions-policy",r.permissionsPolicy),r.coop!==void 0&&l(e,"cross-origin-opener-policy",r.coop),r.csp!==void 0){const t=T(s)?r.csp.htmlValue:r.csp.value;t!==void 0&&l(e,"content-security-policy",t)}},U=(e,o,s)=>{const r=o.headers.get("origin");if(!(!r||!s.isAllowed(r)))for(const[t,n]of g(r,s).entries())t==="vary"?e.append("vary",n):l(e,t,n)},V=(e,o,s)=>{if(e.status===101||e.webSocket)return e;const r=new Headers(e.headers);return s.headers.enabled&&k(r,o,e,s.headers),s.cors.enabled&&U(r,o,s.cors),new Response(e.body,{headers:r,status:e.status,statusText:e.statusText})};export{V as decorateResponse,X as enforceOrigin,F as enforceWebSocketOrigin,B as handleCorsPreflight,j as resolveSecurity};