@lunora/runtime 1.0.0-alpha.181 → 1.0.0-alpha.182
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 +1 -1
- package/dist/packem_shared/{composeWorker-PP4n0KPn.mjs → composeWorker-NZoqX7r-.mjs} +1 -1
- package/dist/packem_shared/{createCrossShardRelationCapabilities-BiXSW10v.mjs → createCrossShardRelationCapabilities-CWQpukAv.mjs} +1 -1
- package/dist/packem_shared/{createKvCursorStore-DQXTTD0l.mjs → createKvCursorStore-4nVJ0-ad.mjs} +1 -1
- package/dist/packem_shared/{createShardClient-BLW9uJZN.mjs → createShardClient-C2YyONnL.mjs} +1 -1
- package/dist/packem_shared/{export-tap-CAyZ2TWC.mjs → export-tap-GSRLYAb6.mjs} +1 -1
- package/dist/packem_shared/{portable-json-BSCiOfqE.mjs → portable-json-CTm_YALS.mjs} +1 -1
- package/dist/packem_shared/{toAirbyteMessages-2d_iJXPf.mjs → toAirbyteMessages-Cmw-8nDf.mjs} +1 -1
- package/dist/packem_shared/wire-codec-BkjZMyIW.mjs +1 -0
- package/package.json +2 -2
- package/dist/packem_shared/wire-codec-BLvSm5Mn.mjs +0 -1
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-
|
|
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-Cmw-8nDf.mjs";import{composeWorker as l,createLunoraHandler as d,createWorker as u,defineRpcEnvelope as _,resolveLunoraOptions as k,withFrameworkWorker as y}from"./packem_shared/composeWorker-NZoqX7r-.mjs";import{createCrossShardRelationCapabilities as O}from"./packem_shared/createCrossShardRelationCapabilities-CWQpukAv.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-GSRLYAb6.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-DnOj3QRi.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-CDfEAQHU.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-CXdh_RxT.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-D3ShCTHh.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-C2YyONnL.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 wr,toErrorBody as gr}from"@lunora/errors";import{e as sn}from"./evict-oldest-BNXsKx4s.mjs";import{NOOP_EXECUTION_CONTEXT as yr}from"./NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{t as br,f as _r}from"./base64-Bl1_r2k1.mjs";import{i as Rr,e as Er,a as Ar,E as bt,d as Tr}from"./identity-header-pR617HTs.mjs";import{O as _t,a as Rt}from"./origin-paywall-B6eOO67m.mjs";import{o as ge,b as cn,p as Sr,m as Or,d as vr,a as Ir,r as kr}from"./otlp-resource-BwFJnvwB.mjs";import{r as Pr,f as Et,a as de,S as At}from"./observability-DgurIZIR.mjs";import{e as Oe,d as Xe,a as Dr}from"./wire-codec-BLvSm5Mn.mjs";import{d as ee,e as ne,M as dn,b as Nr,f as Ur,g as un,w as Cr,h as ln,t as Br}from"./rest-routes-D3ShCTHh.mjs";import{LunoraError as c,toErrorResponse as Tt}from"./LunoraError-DksAgIpa.mjs";import{a as M,m as we}from"./method-guard-BG_vJNTl.mjs";import{normalizeBackupPrefix as ot,BACKUP_KEY_PREFIX as at,isBackupManifestKey as xr,backupObjectKeyOfManifest as hn,backupObjectKey as Hr,backupManifestKey as Lr}from"./BACKUP_KEY_PREFIX-BOtSu-_3.mjs";import{toHex as jr,buildStorageAdminRoutes as Mr,STORAGE_UPLOAD_MAX_BODY_BYTES as $r,STORAGE_PATH as Kr}from"./STORAGE_UPLOAD_MAX_BODY_BYTES-BIiV5kqV.mjs";import{b as Fr,e as Gr,f as St,g as Qr,h as Wr}from"./export-tap-CAyZ2TWC.mjs";import{buildHealthRoutes as zr,durableObjectProbe as Vr,d1Probe as Jr,presenceProbe as $e}from"./HEALTH_PATH-CAX2UeFy.mjs";import{wrapResolverWithContract as Yr}from"./composeIdentityResolvers-BHZ4jH8o.mjs";import{composeIdentityResolvers as Mi,routeIdentityResolvers as $i}from"./composeIdentityResolvers-BHZ4jH8o.mjs";import{buildLogArchiveAdminRoutes as qr}from"./LOG_ARCHIVE_PATH-Hmjpz_Ko.mjs";import{pruneShardRegistry as Xr,createQueryCoordinator as Zr,createDefaultShardRegistry as eo}from"./createQueryCoordinator-CXdh_RxT.mjs";import{resolveShard as ye,applyJurisdiction as Ke}from"./applyJurisdiction-D4vryLhj.mjs";import{resolveSecurity as Ot,handleCorsPreflight as to,enforceOrigin as no,decorateResponse as Fe,enforceWebSocketOrigin as vt}from"./decorateResponse-CRrFNW1v.mjs";const ro=e=>{const t=e??{};if(typeof t.bucket=="function")return t;const n=t.bucketName,a={...t,bucketName:typeof n=="string"&&n!==""?n:"default"};return a.bucket=()=>a,a},fn="__lunoraBranch",oo=e=>typeof e=="object"&&e!==null&&Object.hasOwn(e,fn),ao=`may not contain the reserved workflow branch-marker key ("${fn}")`,so=async e=>{const t=[];let n;for(;;){const o=await e(n);if(t.push(...Array.isArray(o.records)?o.records:[]),o.truncated!==!0||typeof o.cursor!="string"||o.cursor.length===0)return t;if(o.cursor===n)throw new Error("collectPages: the list did not advance its cursor — refusing to page forever");n=o.cursor}},st=(e,t)=>{const n=Math.max(e.length,t.length);let o=e.length^t.length;for(let a=0;a<n;a+=1){const i=a<e.length?e.charCodeAt(a):0,d=a<t.length?t.charCodeAt(a):0;o|=i^d}return o===0},io=/already[\s_-]?exists/iu,co=e=>io.test(e instanceof Error?e.message:String(e)),It="x-lunora-want-error-detail",kt="x-lunora-error-detail",uo=8192,lo=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,uo)}}},Pt=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}},ho=(e,t,n,o)=>{const a=e.get(t);if(a!==void 0)return a;sn(e,o);const i=n().catch(d=>{throw e.get(t)===i&&e.delete(t),d});return e.set(t,i),i},it=new TextEncoder,fo=Array.from({length:32},(e,t)=>t);new RegExp(`[${fo.map(e=>String.fromCodePoint(e)).join("")}]`,"u");const po=64,mo=new Map,pn=async e=>ho(mo,e,async()=>crypto.subtle.importKey("raw",it.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]),po),mn=async(e,t)=>{const n=await pn(e),o=await crypto.subtle.sign("HMAC",n,it.encode(t));return br(new Uint8Array(o))},wo=async(e,t,n)=>{const o=await pn(e);return crypto.subtle.verify("HMAC",o,n,it.encode(t))},go="cf-ray",yo="x-lunora-ray-id",bo=/^([\da-f]{16})(?:-[a-z]{3,4})?$/i,_o=e=>e==null?void 0:bo.exec(e.trim())?.[1]?.toLowerCase(),Ro=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"];new Set(Ro);const Eo=new Set(["AE","BH","IL","IQ","IR","JO","KW","LB","OM","PS","QA","SA","SY","TR","YE"]),Ao=-100,To=15,So=e=>{const t=Number(e.longitude??Number.NaN);switch(e.continent){case"AF":return"afr";case"AS":return e.country!==void 0&&Eo.has(e.country)?"me":"apac";case"EU":return Number.isFinite(t)&&t>To?"eeur":"weur";case"NA":return Number.isFinite(t)&&t<Ao?"wnam":"enam";case"OC":return"oc";case"SA":return"sam";default:return}},Dt=e=>{const t=e.cf;return t===void 0?void 0:So(t)},Ze="::relay::",Oo=(e,t)=>`${e}${Ze}${String(t)}`,et="::replica::",vo=(e,t)=>`${e}${et}${t}`,Io=e=>{if(e==null||!/^\d+$/.test(e))return;const t=Number.parseInt(e,10);return Number.isSafeInteger(t)&&t>0?t:void 0},ko=(e,t,n)=>e?.[n]??t?.[n],Po=(e,t,n,o)=>{const a=ko(e,t,n);if(!(typeof a!="object"||a===null))return o.every(i=>typeof a[i]=="function")?a:void 0},Do=new Set(["1","enabled","on","true","yes"]),No=new Set(["0","disabled","false","no","off"]),Uo=(e,t)=>{const n=(e??"").trim().toLowerCase();return Do.has(n)?!0:No.has(n)?!1:t},wn="v1",Co=6e4,Bo=async(e,t={})=>{const n=(t.now??Date.now())+(t.ttlMs??Co),o=`${wn}.${String(n)}`,a=await mn(e,o);return{expiresAtMs:n,token:`${o}.${a}`}},xo=async(e,t,n=Date.now())=>{if(e.length===0||t.length===0)return!1;const o=t.split(".");if(o.length!==3)return!1;const[a,i,d]=o;if(a!==wn||d.length===0)return!1;const f=Number(i);if(!Number.isFinite(f)||f<=n)return!1;let h;try{h=_r(d)}catch{return!1}return wo(e,`${a}.${i}`,h)},N="/_lunora/admin/auth",Ho={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},pe=(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},gn=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},Nt=e=>{const t=gn(e.role);if(t===void 0||typeof t=="string"&&t.trim()==="")throw new c("`role` is required",{code:"BAD_REQUEST",status:400});return t},Ut=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[o,a]of Object.entries(t))Array.isArray(a)&&a.every(i=>typeof i=="string")&&(n[o]=a);return n},Lo={[`${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:pe(e,"userId")}),http:"GET",method:"listAccounts"},[`${N}/passkeys`]:{build:({query:e})=>({userId:pe(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:pe(t,"organizationId")}),http:"GET",method:"listMembers"},[`${N}/organizations/invitations`]:{build:({paging:e,query:t})=>({...e,organizationId:pe(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:pe(t,"organizationId")}),http:"GET",method:"listTeams"},[`${N}/organizations/teams/members`]:{build:({paging:e,query:t})=>({...e,teamId:pe(t,"teamId")}),http:"GET",method:"listTeamMembers"},[`${N}/organizations/roles`]:{build:({paging:e,query:t})=>({...e,organizationId:pe(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:gn(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:Nt(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:Nt(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:Ut(e),role:C(e,"role")}),http:"POST",method:"createOrgRole"},[`${N}/organizations/roles/update`]:{build:({body:e})=>({permission:Ut(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"}},jo=e=>{const t=async a=>{try{return await a()}catch(i){if(i instanceof c)throw i;const d=i,f=typeof d.code=="string"?d.code:"AUTH_ADMIN_ERROR";throw console.error("[lunora] auth admin operation failed:",i),new c("auth admin operation failed",{code:f,status:Ho[f]??500})}},n=async(a,i)=>{if(e.assertAdmin(a),a.method!==i.http)throw new c(`Auth admin endpoint requires ${i.http}`,{code:"METHOD_NOT_ALLOWED",status:405});const d=e.getAuthAdmin();if(d===void 0)throw new c("auth endpoints require an `authAdmin` on the worker",{code:"AUTH_NOT_CONFIGURED",status:400});const f=d[i.method];if(f===void 0)throw new c(`auth admin does not support \`${i.method}\``,{code:"AUTH_OP_NOT_SUPPORTED",status:400});const h=new URL(a.url),m={body:i.http==="POST"?await e.readJsonBody(a):{},paging:e.parsePaging(a),query:S=>e.queryParameter(h,S)},b=i.build(m),T=await t(()=>f(b));return Response.json(i.returns==="void"?{ok:!0}:T,{headers:{"cache-control":"no-store","content-type":"application/json"},status:200})},o={};for(const[a,i]of Object.entries(Lo))o[a]=d=>n(d,i);return o},Ct="__lunora_admin__:getAuthAuditLog",Bt=e=>typeof e=="string"&&e!==""?e:void 0,xt=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0,Mo=e=>async(n,o)=>{e.assertAdmin(n);const a=e.getReader();if(a===void 0)throw new c("the auth/security audit endpoint requires an `authAuditReader` on the worker",{code:"AUTH_AUDIT_NOT_CONFIGURED",status:400});const i=Bt(o.actorId),d=Bt(o.event),f=xt(o.sinceSeq),h=xt(o.limit),m={...i===void 0?{}:{actorId:i},...d===void 0?{}:{event:d},...f===void 0?{}:{sinceSeq:f},...h===void 0?{}:{limit:h}};let b;try{b=await a.read(m)}catch(S){throw S instanceof c?S:(console.error("[lunora] auth audit read failed:",S),new c("auth audit read failed",{code:"AUTH_AUDIT_READ_FAILED",status:500}))}const T={entries:b};return Response.json({result:Oe(T)},{headers:{"content-type":"application/json"},status:200})},tt="__lunora_admin__:copyAuthToJurisdiction",yn="__lunora_admin__:purgeUnpinnedAuth",$o=e=>async(t,n,o)=>{if(n!==tt&&n!==yn)return;e.assertAdmin(t);const a=e.getMove();if(a===void 0)throw new c("moving auth into the jurisdiction needs DO-backed auth pinned with `.jurisdiction(…, { pinAuth: true })`",{code:"AUTH_MOVE_NOT_CONFIGURED",status:400});const i=n===tt?await a.copy({force:o.force===!0}):await a.purge();return Response.json({result:Oe(i)},{headers:{"content-type":"application/json"},status:200})},Ko=(e,t)=>{const n=[],o=[];if(t&&t.length>0)for(const a of t)e.resolveTableSharding?.(a)?.mode.kind==="global"?o.push(a):n.push(a);return{globalTables:o,shardLocalTables:n}},Fo=async(e,t,n,o,a,i)=>{if(n!==void 0&&o.length===0)return[];const d=await e.orchestrateExport(a,{args:{tables:o},defaultShardKey:i,headers:t,tables:o}),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??[])},bn=async(e,t,n,o,a)=>{const i=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:d,shardLocalTables:f}=Ko(e,i),h=await Fo(t,n,i,f,a,e.defaultShardKey??"__root__"),m=e.exportGlobals,b=o===void 0||d.length>0;return(async function*(){yield*h,b&&m&&(yield*m({tables:d}))})()},Go=async(e,t,n,o,a,i)=>{for await(const d of await bn(e,t,n,o,i))a(d)},Qo=new TextEncoder,Wo=1e3,_n=10,zo=200,Ht=8,Rn="lunoraBackupCron",Lt=24*1048576,jt=e=>{const t=e.slice(0,_n).map(o=>hn(o)),n=e.length-t.length;return`${t.join(", ")}${n>0?` (+${String(n)} more)`:""}`},Vo=(e,t)=>{const n=new Uint8Array(new ArrayBuffer(t));let o=0;for(const a of e)n.set(a,o),o+=a.byteLength;return n},ct=async(e,t,n,o)=>{if(n===void 0||!Number.isInteger(n)||n<=0)return{eligible:0,stale:[]};const a=[];let i;for(let d=0;d<Wo;d+=1){const f=await e.list({cursor:i,include:["customMetadata"],prefix:t});for(const h of f.objects)xr(h.key)&&h.customMetadata?.[Rn]===o&&a.push(h.key);if(!f.truncated||f.cursor===void 0)break;i=f.cursor}return{eligible:a.length,stale:a.toSorted((d,f)=>f.localeCompare(d)).slice(n)}},Jo=async(e,t,n,o,a)=>{const{stale:i}=await ct(e,t,n,o),d=new Set(a),f=i.filter(k=>d.has(k)),h=f.slice(0,zo),m=i.length-h.length,b=a.length-f.length;if(h.length===0)return{deleted:[],failed:[],ignored:b,remaining:m};const T=[],S=[];for(let k=0;k<h.length;k+=Ht){const w=await Promise.allSettled(h.slice(k,k+Ht).map(async g=>(await e.delete(hn(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)}: ${jt(T)}`),S.length>0&&console.warn(`[lunora] backup prune failed to remove ${String(S.length)}: ${jt(S)}`),{deleted:T,failed:S,ignored:b,remaining:m}},Yo=async e=>{const t=e.backupStore;if(!t)throw new c("backup retention preview requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});const n=ot(e.backupPrefix??at),o=e.backupCron,{eligible:a,stale:i}=o===void 0?{eligible:0,stale:[]}:await ct(t,n,e.backupRetain,o);return{cron:o,eligible:a,keep:e.backupRetain??0,prefix:n,wouldDelete:i}},qo=async(e,t,n,o,a)=>{const i=e.backupStore;if(!i)throw new c("scheduled backup requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});if(!o||o.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 ${o}`,"content-type":"application/json"},f=e.backupTables;let h=0,m=0,b=[];await Go(e,t,d,f,I=>{const E=Qo.encode(`${JSON.stringify(I)}
|
|
1
|
+
import{isLunoraError as wr,toErrorBody as gr}from"@lunora/errors";import{e as sn}from"./evict-oldest-BNXsKx4s.mjs";import{NOOP_EXECUTION_CONTEXT as yr}from"./NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{t as br,f as _r}from"./base64-Bl1_r2k1.mjs";import{i as Rr,e as Er,a as Ar,E as bt,d as Tr}from"./identity-header-pR617HTs.mjs";import{O as _t,a as Rt}from"./origin-paywall-B6eOO67m.mjs";import{o as ge,b as cn,p as Sr,m as Or,d as vr,a as Ir,r as kr}from"./otlp-resource-BwFJnvwB.mjs";import{r as Pr,f as Et,a as de,S as At}from"./observability-DgurIZIR.mjs";import{e as Oe,d as Xe,a as Dr}from"./wire-codec-BkjZMyIW.mjs";import{d as ee,e as ne,M as dn,b as Nr,f as Ur,g as un,w as Cr,h as ln,t as Br}from"./rest-routes-D3ShCTHh.mjs";import{LunoraError as c,toErrorResponse as Tt}from"./LunoraError-DksAgIpa.mjs";import{a as M,m as we}from"./method-guard-BG_vJNTl.mjs";import{normalizeBackupPrefix as ot,BACKUP_KEY_PREFIX as at,isBackupManifestKey as xr,backupObjectKeyOfManifest as hn,backupObjectKey as Hr,backupManifestKey as Lr}from"./BACKUP_KEY_PREFIX-BOtSu-_3.mjs";import{toHex as jr,buildStorageAdminRoutes as Mr,STORAGE_UPLOAD_MAX_BODY_BYTES as $r,STORAGE_PATH as Kr}from"./STORAGE_UPLOAD_MAX_BODY_BYTES-BIiV5kqV.mjs";import{b as Fr,e as Gr,f as St,g as Qr,h as Wr}from"./export-tap-GSRLYAb6.mjs";import{buildHealthRoutes as zr,durableObjectProbe as Vr,d1Probe as Jr,presenceProbe as $e}from"./HEALTH_PATH-CAX2UeFy.mjs";import{wrapResolverWithContract as Yr}from"./composeIdentityResolvers-BHZ4jH8o.mjs";import{composeIdentityResolvers as Mi,routeIdentityResolvers as $i}from"./composeIdentityResolvers-BHZ4jH8o.mjs";import{buildLogArchiveAdminRoutes as qr}from"./LOG_ARCHIVE_PATH-Hmjpz_Ko.mjs";import{pruneShardRegistry as Xr,createQueryCoordinator as Zr,createDefaultShardRegistry as eo}from"./createQueryCoordinator-CXdh_RxT.mjs";import{resolveShard as ye,applyJurisdiction as Ke}from"./applyJurisdiction-D4vryLhj.mjs";import{resolveSecurity as Ot,handleCorsPreflight as to,enforceOrigin as no,decorateResponse as Fe,enforceWebSocketOrigin as vt}from"./decorateResponse-CRrFNW1v.mjs";const ro=e=>{const t=e??{};if(typeof t.bucket=="function")return t;const n=t.bucketName,a={...t,bucketName:typeof n=="string"&&n!==""?n:"default"};return a.bucket=()=>a,a},fn="__lunoraBranch",oo=e=>typeof e=="object"&&e!==null&&Object.hasOwn(e,fn),ao=`may not contain the reserved workflow branch-marker key ("${fn}")`,so=async e=>{const t=[];let n;for(;;){const o=await e(n);if(t.push(...Array.isArray(o.records)?o.records:[]),o.truncated!==!0||typeof o.cursor!="string"||o.cursor.length===0)return t;if(o.cursor===n)throw new Error("collectPages: the list did not advance its cursor — refusing to page forever");n=o.cursor}},st=(e,t)=>{const n=Math.max(e.length,t.length);let o=e.length^t.length;for(let a=0;a<n;a+=1){const i=a<e.length?e.charCodeAt(a):0,d=a<t.length?t.charCodeAt(a):0;o|=i^d}return o===0},io=/already[\s_-]?exists/iu,co=e=>io.test(e instanceof Error?e.message:String(e)),It="x-lunora-want-error-detail",kt="x-lunora-error-detail",uo=8192,lo=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,uo)}}},Pt=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}},ho=(e,t,n,o)=>{const a=e.get(t);if(a!==void 0)return a;sn(e,o);const i=n().catch(d=>{throw e.get(t)===i&&e.delete(t),d});return e.set(t,i),i},it=new TextEncoder,fo=Array.from({length:32},(e,t)=>t);new RegExp(`[${fo.map(e=>String.fromCodePoint(e)).join("")}]`,"u");const po=64,mo=new Map,pn=async e=>ho(mo,e,async()=>crypto.subtle.importKey("raw",it.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]),po),mn=async(e,t)=>{const n=await pn(e),o=await crypto.subtle.sign("HMAC",n,it.encode(t));return br(new Uint8Array(o))},wo=async(e,t,n)=>{const o=await pn(e);return crypto.subtle.verify("HMAC",o,n,it.encode(t))},go="cf-ray",yo="x-lunora-ray-id",bo=/^([\da-f]{16})(?:-[a-z]{3,4})?$/i,_o=e=>e==null?void 0:bo.exec(e.trim())?.[1]?.toLowerCase(),Ro=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"];new Set(Ro);const Eo=new Set(["AE","BH","IL","IQ","IR","JO","KW","LB","OM","PS","QA","SA","SY","TR","YE"]),Ao=-100,To=15,So=e=>{const t=Number(e.longitude??Number.NaN);switch(e.continent){case"AF":return"afr";case"AS":return e.country!==void 0&&Eo.has(e.country)?"me":"apac";case"EU":return Number.isFinite(t)&&t>To?"eeur":"weur";case"NA":return Number.isFinite(t)&&t<Ao?"wnam":"enam";case"OC":return"oc";case"SA":return"sam";default:return}},Dt=e=>{const t=e.cf;return t===void 0?void 0:So(t)},Ze="::relay::",Oo=(e,t)=>`${e}${Ze}${String(t)}`,et="::replica::",vo=(e,t)=>`${e}${et}${t}`,Io=e=>{if(e==null||!/^\d+$/.test(e))return;const t=Number.parseInt(e,10);return Number.isSafeInteger(t)&&t>0?t:void 0},ko=(e,t,n)=>e?.[n]??t?.[n],Po=(e,t,n,o)=>{const a=ko(e,t,n);if(!(typeof a!="object"||a===null))return o.every(i=>typeof a[i]=="function")?a:void 0},Do=new Set(["1","enabled","on","true","yes"]),No=new Set(["0","disabled","false","no","off"]),Uo=(e,t)=>{const n=(e??"").trim().toLowerCase();return Do.has(n)?!0:No.has(n)?!1:t},wn="v1",Co=6e4,Bo=async(e,t={})=>{const n=(t.now??Date.now())+(t.ttlMs??Co),o=`${wn}.${String(n)}`,a=await mn(e,o);return{expiresAtMs:n,token:`${o}.${a}`}},xo=async(e,t,n=Date.now())=>{if(e.length===0||t.length===0)return!1;const o=t.split(".");if(o.length!==3)return!1;const[a,i,d]=o;if(a!==wn||d.length===0)return!1;const f=Number(i);if(!Number.isFinite(f)||f<=n)return!1;let h;try{h=_r(d)}catch{return!1}return wo(e,`${a}.${i}`,h)},N="/_lunora/admin/auth",Ho={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},pe=(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},gn=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},Nt=e=>{const t=gn(e.role);if(t===void 0||typeof t=="string"&&t.trim()==="")throw new c("`role` is required",{code:"BAD_REQUEST",status:400});return t},Ut=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[o,a]of Object.entries(t))Array.isArray(a)&&a.every(i=>typeof i=="string")&&(n[o]=a);return n},Lo={[`${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:pe(e,"userId")}),http:"GET",method:"listAccounts"},[`${N}/passkeys`]:{build:({query:e})=>({userId:pe(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:pe(t,"organizationId")}),http:"GET",method:"listMembers"},[`${N}/organizations/invitations`]:{build:({paging:e,query:t})=>({...e,organizationId:pe(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:pe(t,"organizationId")}),http:"GET",method:"listTeams"},[`${N}/organizations/teams/members`]:{build:({paging:e,query:t})=>({...e,teamId:pe(t,"teamId")}),http:"GET",method:"listTeamMembers"},[`${N}/organizations/roles`]:{build:({paging:e,query:t})=>({...e,organizationId:pe(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:gn(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:Nt(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:Nt(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:Ut(e),role:C(e,"role")}),http:"POST",method:"createOrgRole"},[`${N}/organizations/roles/update`]:{build:({body:e})=>({permission:Ut(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"}},jo=e=>{const t=async a=>{try{return await a()}catch(i){if(i instanceof c)throw i;const d=i,f=typeof d.code=="string"?d.code:"AUTH_ADMIN_ERROR";throw console.error("[lunora] auth admin operation failed:",i),new c("auth admin operation failed",{code:f,status:Ho[f]??500})}},n=async(a,i)=>{if(e.assertAdmin(a),a.method!==i.http)throw new c(`Auth admin endpoint requires ${i.http}`,{code:"METHOD_NOT_ALLOWED",status:405});const d=e.getAuthAdmin();if(d===void 0)throw new c("auth endpoints require an `authAdmin` on the worker",{code:"AUTH_NOT_CONFIGURED",status:400});const f=d[i.method];if(f===void 0)throw new c(`auth admin does not support \`${i.method}\``,{code:"AUTH_OP_NOT_SUPPORTED",status:400});const h=new URL(a.url),m={body:i.http==="POST"?await e.readJsonBody(a):{},paging:e.parsePaging(a),query:S=>e.queryParameter(h,S)},b=i.build(m),T=await t(()=>f(b));return Response.json(i.returns==="void"?{ok:!0}:T,{headers:{"cache-control":"no-store","content-type":"application/json"},status:200})},o={};for(const[a,i]of Object.entries(Lo))o[a]=d=>n(d,i);return o},Ct="__lunora_admin__:getAuthAuditLog",Bt=e=>typeof e=="string"&&e!==""?e:void 0,xt=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0,Mo=e=>async(n,o)=>{e.assertAdmin(n);const a=e.getReader();if(a===void 0)throw new c("the auth/security audit endpoint requires an `authAuditReader` on the worker",{code:"AUTH_AUDIT_NOT_CONFIGURED",status:400});const i=Bt(o.actorId),d=Bt(o.event),f=xt(o.sinceSeq),h=xt(o.limit),m={...i===void 0?{}:{actorId:i},...d===void 0?{}:{event:d},...f===void 0?{}:{sinceSeq:f},...h===void 0?{}:{limit:h}};let b;try{b=await a.read(m)}catch(S){throw S instanceof c?S:(console.error("[lunora] auth audit read failed:",S),new c("auth audit read failed",{code:"AUTH_AUDIT_READ_FAILED",status:500}))}const T={entries:b};return Response.json({result:Oe(T)},{headers:{"content-type":"application/json"},status:200})},tt="__lunora_admin__:copyAuthToJurisdiction",yn="__lunora_admin__:purgeUnpinnedAuth",$o=e=>async(t,n,o)=>{if(n!==tt&&n!==yn)return;e.assertAdmin(t);const a=e.getMove();if(a===void 0)throw new c("moving auth into the jurisdiction needs DO-backed auth pinned with `.jurisdiction(…, { pinAuth: true })`",{code:"AUTH_MOVE_NOT_CONFIGURED",status:400});const i=n===tt?await a.copy({force:o.force===!0}):await a.purge();return Response.json({result:Oe(i)},{headers:{"content-type":"application/json"},status:200})},Ko=(e,t)=>{const n=[],o=[];if(t&&t.length>0)for(const a of t)e.resolveTableSharding?.(a)?.mode.kind==="global"?o.push(a):n.push(a);return{globalTables:o,shardLocalTables:n}},Fo=async(e,t,n,o,a,i)=>{if(n!==void 0&&o.length===0)return[];const d=await e.orchestrateExport(a,{args:{tables:o},defaultShardKey:i,headers:t,tables:o}),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??[])},bn=async(e,t,n,o,a)=>{const i=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:d,shardLocalTables:f}=Ko(e,i),h=await Fo(t,n,i,f,a,e.defaultShardKey??"__root__"),m=e.exportGlobals,b=o===void 0||d.length>0;return(async function*(){yield*h,b&&m&&(yield*m({tables:d}))})()},Go=async(e,t,n,o,a,i)=>{for await(const d of await bn(e,t,n,o,i))a(d)},Qo=new TextEncoder,Wo=1e3,_n=10,zo=200,Ht=8,Rn="lunoraBackupCron",Lt=24*1048576,jt=e=>{const t=e.slice(0,_n).map(o=>hn(o)),n=e.length-t.length;return`${t.join(", ")}${n>0?` (+${String(n)} more)`:""}`},Vo=(e,t)=>{const n=new Uint8Array(new ArrayBuffer(t));let o=0;for(const a of e)n.set(a,o),o+=a.byteLength;return n},ct=async(e,t,n,o)=>{if(n===void 0||!Number.isInteger(n)||n<=0)return{eligible:0,stale:[]};const a=[];let i;for(let d=0;d<Wo;d+=1){const f=await e.list({cursor:i,include:["customMetadata"],prefix:t});for(const h of f.objects)xr(h.key)&&h.customMetadata?.[Rn]===o&&a.push(h.key);if(!f.truncated||f.cursor===void 0)break;i=f.cursor}return{eligible:a.length,stale:a.toSorted((d,f)=>f.localeCompare(d)).slice(n)}},Jo=async(e,t,n,o,a)=>{const{stale:i}=await ct(e,t,n,o),d=new Set(a),f=i.filter(k=>d.has(k)),h=f.slice(0,zo),m=i.length-h.length,b=a.length-f.length;if(h.length===0)return{deleted:[],failed:[],ignored:b,remaining:m};const T=[],S=[];for(let k=0;k<h.length;k+=Ht){const w=await Promise.allSettled(h.slice(k,k+Ht).map(async g=>(await e.delete(hn(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)}: ${jt(T)}`),S.length>0&&console.warn(`[lunora] backup prune failed to remove ${String(S.length)}: ${jt(S)}`),{deleted:T,failed:S,ignored:b,remaining:m}},Yo=async e=>{const t=e.backupStore;if(!t)throw new c("backup retention preview requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});const n=ot(e.backupPrefix??at),o=e.backupCron,{eligible:a,stale:i}=o===void 0?{eligible:0,stale:[]}:await ct(t,n,e.backupRetain,o);return{cron:o,eligible:a,keep:e.backupRetain??0,prefix:n,wouldDelete:i}},qo=async(e,t,n,o,a)=>{const i=e.backupStore;if(!i)throw new c("scheduled backup requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});if(!o||o.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 ${o}`,"content-type":"application/json"},f=e.backupTables;let h=0,m=0,b=[];await Go(e,t,d,f,I=>{const E=Qo.encode(`${JSON.stringify(I)}
|
|
2
2
|
`);if(h+=1,m+=E.byteLength,m>Lt)throw new c(`scheduled backup reached ${String(m)} bytes of NDJSON, past the ${String(Lt)}-byte limit for a snapshot assembled inside a Worker — nothing was written. Narrow it with \`backupTables\`, or take this snapshot off-platform with \`lunora backup create --bucket\`.`,{code:"BACKUP_TOO_LARGE",status:507});b.push(E)},n);const S=ot(e.backupPrefix??at),k=new Date(a.scheduledTime).toISOString(),w=Hr(S,k),g=Vo(b,m);b=[];const y=jr(await crypto.subtle.digest("SHA-256",g));await i.put(w,g,{httpMetadata:{contentType:"application/x-ndjson"},sha256:y});const v={bytes:m,createdAt:k,cron:a.cron,file:w,id:k,rows:h,scheduledTime:a.scheduledTime,sha256:y,...f?{tables:f.join(",")}:{}};await i.put(Lr(w),`${JSON.stringify(v,void 0,2)}
|
|
3
3
|
`,{customMetadata:{[Rn]:a.cron},httpMetadata:{contentType:"application/json"}});try{const{stale:I}=await ct(i,S,e.backupRetain,a.cron);if(I.length>0){const E=I.slice(0,_n),j=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(", ")}${j>0?` (+${String(j)} more)`:""}`)}}catch(I){console.warn(`[lunora] backup ${w} was written, but the retention report failed:`,I)}},Xo=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 o=e.backupCron,a=e.backupRetain;if(o===void 0||a===void 0||!Number.isInteger(a)||a<=0)throw new c("backup prune needs a retention window: set `backupRetain` (and `backupCron`, which decides whose snapshots retention owns) on the worker. Without one there is nothing past the window to remove.",{code:"BACKUP_RETENTION_NOT_CONFIGURED",status:400});return Jo(n,ot(e.backupPrefix??at),a,o,t)},Zo="/_lunora/admin/backup/retention",ea="/_lunora/admin/backup/prune",ta=e=>{const{options:t,readJsonBody:n,requireAdminOption:o}=e,a=(f,h)=>{o(f,t.backupStore,{code:"BACKUP_NOT_CONFIGURED",message:`backup ${h} requires a \`backupStore\` on the worker`})},i=async f=>(M(f,"GET","Backup-retention"),a(f,"retention preview"),Response.json(await Yo(t),{headers:{"cache-control":"no-store"}})),d=async f=>{M(f,"POST","Backup-prune"),a(f,"prune");const{confirm:h}=await n(f);if(!Array.isArray(h)||h.some(m=>typeof m!="string"))throw new c("backup prune requires a `confirm` array of the sidecar keys to remove — read them from `GET /_lunora/admin/backup/retention` and pass back the ones you mean to delete",{code:"BAD_REQUEST",status:400});return Response.json(await Xo(t,h),{headers:{"cache-control":"no-store"}})};return{[ea]:d,[Zo]:i}},Mt=500,na=(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 o=e;if(typeof o.functionPath!="string")throw new c("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 c("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 c("each batch call `args` must be an object",{code:"BAD_REQUEST",status:400});if(o.id!==void 0&&typeof o.id!="number")throw new c("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}},ra=(e,t)=>{if(e.length>Mt)throw new c(`RPC batch exceeds the ${String(Mt)}-call limit`,{code:"BAD_REQUEST",status:400});const n=new Map,o=new Set;for(const[a,i]of e.entries()){const{entry:d,shardKey:f}=na(i,a,t);if(o.has(d.id))throw new c(`batch call id ${String(d.id)} is used twice; ids must be distinct`,{code:"BAD_REQUEST",status:400});o.add(d.id);const h=n.get(f)??[];h.push(d),n.set(f,h)}return n},oa="/_lunora/admin/export",aa="/_lunora/admin/import",sa="/_lunora/admin/sync",ia="/_lunora/admin/connector/sync",ca="/_lunora/admin/apply",da="/_lunora/admin/export-tap/run",ua=new TextEncoder,la=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 o=[];for(const a of n.tables){if(typeof a!="string"||a.length===0)throw new c("Export `tables` entries must be non-empty strings",{code:"BAD_REQUEST",status:400});o.push(a)}return{tables:o}},Qe=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):void 0,ha=e=>{const{applyGlobals:t,defaultShardKey:n,exportCursorStore:o,exportSinks:a,knownTables:i,queryCoordinator:d,assertAdmin:f,resolveForwardContext:h,shardDO:m,prepareExportRows:b,streamingImport:T,syncGlobals:S}=e,k=async(E,j)=>{const H=we(E,["POST"]);if(H)return H;f(E);const U=await la(E),{headers:K}=await h(E,j),W=await b(K,U.tables),Y=new ReadableStream({async pull(q){try{for await(const G of W)q.enqueue(ua.encode(`${JSON.stringify(G)}
|
|
4
4
|
`));q.close()}catch(G){q.error(G)}}});return new Response(Y,{headers:{"content-type":"application/x-ndjson"},status:200})},w=async(E,j)=>{const H=we(E,["POST"]);if(H)return H;f(E);const U=await ee(E),K=typeof U.cursors=="object"&&U.cursors!==null?U.cursors:{},W=typeof U.epochs=="object"&&U.epochs!==null?U.epochs:{},Y=typeof U.limit=="number"?U.limit:void 0,q=typeof U.globalCursor=="number"?U.globalCursor:0,G=Qe(U.tables),{headers:re}=await h(E,j),Q=G??i(),ue=await d.orchestrateCdcSync(m,{cursors:K,defaultShardKey:n,epochs:W,headers:re,limit:Y,tables:Q}),oe=S?await S({limit:Y,sinceSeq:q}):void 0;return Response.json({global:oe,shards:ue.shards},{status:200})},g=async(E,j)=>{const H=we(E,["POST"]);if(H)return H;f(E);const U=await ee(E),K=Gr(U.cursor),W=typeof U.limit=="number"&&U.limit>0?U.limit:void 0,Y=Qe(U.tables),{headers:q}=await h(E,j),G=Y??i(),re=await d.orchestrateCdcSync(m,{cursors:K.s,defaultShardKey:n,headers:q,limit:W,tables:G}),Q=[],ue={...K.s};let oe=!1;for(const se of re.shards)oe=St(Q,se.changes??[],Wr(W))||oe,ue[se.shardKey]=se.cursor;let be=K.g;if(S){const se=await S({limit:W,sinceSeq:K.g});oe=St(Q,se.changes,W)||oe,be=se.cursor}const z=Qr({g:be,s:ue,v:1}),ae={changes:Q,hasMore:oe,nextCursor:z};return Response.json(ae,{status:200})},y=async(E,j)=>{const H=we(E,["POST"]);if(H)return H;f(E);const U=await ee(E),W=(Array.isArray(U.batches)?U.batches:[]).map(Q=>Q).filter(Q=>Q!==null&&typeof Q=="object"&&typeof Q.shardKey=="string"&&Array.isArray(Q.changes)),Y=Array.isArray(U.globalChanges)?U.globalChanges:[],{headers:q}=await h(E,j),G=await d.orchestrateApplyCdc(m,{batches:W,headers:q}),re=Y.length>0&&t?await t({changes:Y}):0;return Response.json({applied:G.applied+re,failed:G.failed,ok:G.ok},{status:200})},v=async(E,j)=>{const H=we(E,["POST"]);if(H)return H;f(E);const{headers:U}=await h(E,j),K=await T(E,U);return Response.json(K,{headers:{"content-type":"application/json"},status:K.failed.length>0?207:200})},I=async(E,j)=>{const H=we(E,["POST"]);if(H)return H;if(f(E),a===void 0||Object.keys(a).length===0||o===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),K=typeof U.sink=="string"?U.sink:void 0,W=typeof U.limit=="number"&&U.limit>0?U.limit:void 0,Y=Qe(U.tables);if(K===void 0)throw new c("Export-tap `sink` must name a configured sink",{code:"BAD_REQUEST",status:400});const q=a[K];if(q===void 0)throw new c(`Export-tap sink "${K}" is not configured`,{code:"NOT_FOUND",status:404});const{headers:G}=await h(E,j),re=Y??i(),Q=await Fr({coordinator:d,cursorStore:o,defaultShardKey:n,headers:G,limit:W,shardDO:m,sink:q,tables:re});return Response.json(Q,{headers:{"content-type":"application/json"},status:200})};return{[ca]:y,[ia]:g,[oa]:k,[da]:I,[aa]:v,[sa]:w}},fa=(e,t)=>{let n;try{n=JSON.parse(e)}catch{return{error:{code:"BAD_ROW",line:t,message:"line is not valid JSON",table:""},ok:!1}}if(!n||typeof n!="object"||Array.isArray(n))return{error:{code:"BAD_ROW",line:t,message:"row must be a JSON object",table:""},ok:!1};const o=n;return typeof o.table!="string"||o.table.length===0?{error:{code:"BAD_ROW",line:t,message:"row is missing `table`",table:""},ok:!1}:!o.doc||typeof o.doc!="object"||Array.isArray(o.doc)?{error:{code:"BAD_ROW",line:t,message:"row is missing or malformed `doc`",table:o.table},ok:!1}:{doc:o.doc,ok:!0,table:o.table}},pa=(e,t,n,o,a)=>{if(n?.mode.kind==="shardBy"&&typeof n.mode.field=="string"){const i=e[n.mode.field];return i==null?{error:{code:"BAD_ROW",line:a,message:`row missing shard field "${n.mode.field}" for table "${t}"`,table:t},ok:!1}:{ok:!0,shardKey:typeof i=="string"?i:JSON.stringify(i)}}return{ok:!0,shardKey:o}},ma=async(e,t,n)=>{if(!e.body)throw new c("Import endpoint requires a request body",{code:"BAD_REQUEST",status:400});const o=[],a=[],i=new Map;let d=0,f=0;const h=e.body.getReader(),m=new TextDecoder;let b="",T=0;const S=k=>{f+=1;const w=k.trim();if(w.length===0)return;d+=1;const g=fa(w,f);if(!g.ok){o.push(g.error);return}const{doc:y,table:v}=g,I=t.resolveTableSharding?.(v);if(I?.mode.kind==="global"){a.push({doc:y,line:f,table:v});return}const E=pa(y,v,I,n,f);if(!E.ok){o.push(E.error);return}const j=i.get(E.shardKey);j?j.rows.push({doc:y,table:v}):i.set(E.shardKey,{rows:[{doc:y,table:v}],shardKey:E.shardKey,startLine:f})};for(;;){const{done:k,value:w}=await h.read();if(k)break;if(w&&(T+=w.byteLength,T>dn))throw await h.cancel().catch(()=>{}),new c("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});b+=m.decode(w,{stream:!0});let g=b.indexOf(`
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{e as c,a as u}from"./identity-header-pR617HTs.mjs";import{d as f}from"./wire-codec-
|
|
1
|
+
import{e as c,a as u}from"./identity-header-pR617HTs.mjs";import{d as f}from"./wire-codec-BkjZMyIW.mjs";import{LunoraError as s}from"./LunoraError-DksAgIpa.mjs";const l="/_lunora/rpc",h=e=>{const a={"content-type":"application/json"};return e.userId!==void 0&&e.userId.length>0&&(a["x-lunora-userid"]=c(e.userId)),e.identity!==void 0&&(a["x-lunora-identity"]=u(e.identity)),a},d=async(e,a,o)=>{const t=await(e.fetch??globalThis.fetch)(new Request(`${e.origin}${l}`,{body:JSON.stringify(a),headers:h(e),method:"POST"}));if(!t.ok)throw new s(`cross-shard relation ${o} failed: worker returned ${String(t.status)}`);const r=await t.json();if(typeof r.failed=="number"&&r.failed>0){const i=(typeof r.ok=="number"?r.ok:0)+r.failed;throw new s(`cross-shard relation ${o} failed on ${String(r.failed)} of ${String(i)} shard(s) — refusing to return a partial result`)}return f(r.data)},_=e=>({crossShardCounter:async(n,t)=>{const r=await d(e,{args:{table:n,where:t},fanOut:{merge:{kind:"sum"},table:n},functionPath:"__lunora_relation__:count"},"count");return typeof r=="number"?r:0},crossShardReader:async(n,t)=>{const r=await d(e,{args:{...t,table:n},fanOut:{merge:{kind:"concat"},table:n},functionPath:"__lunora_relation__:read"},"read");return{continueCursor:null,isDone:!0,page:Array.isArray(r)?r:[]}}});export{_ as createCrossShardRelationCapabilities};
|
package/dist/packem_shared/{createKvCursorStore-DQXTTD0l.mjs → createKvCursorStore-4nVJ0-ad.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{c as o,a as s,d as t,r as i,b as n,s as p,w as S}from"./export-tap-
|
|
1
|
+
import{c as o,a as s,d as t,r as i,b as n,s as p,w as S}from"./export-tap-GSRLYAb6.mjs";import"./portable-json-CTm_YALS.mjs";export{o as createKvCursorStore,s as createMemoryCursorStore,t as defineExportSink,i as r2Sink,n as runExportTap,p as sanitizeChange,S as webhookExportSink};
|
package/dist/packem_shared/{createShardClient-BLW9uJZN.mjs → createShardClient-C2YyONnL.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as n}from"@lunora/errors";import{e as S,a as I}from"./identity-header-pR617HTs.mjs";import{O as w,a as p}from"./origin-paywall-B6eOO67m.mjs";import{e as N,d as f}from"./wire-codec-
|
|
1
|
+
import{LunoraError as n}from"@lunora/errors";import{e as S,a as I}from"./identity-header-pR617HTs.mjs";import{O as w,a as p}from"./origin-paywall-B6eOO67m.mjs";import{e as N,d as f}from"./wire-codec-BkjZMyIW.mjs";import{applyJurisdiction as g,resolveShard as L}from"./applyJurisdiction-D4vryLhj.mjs";const A=e=>{if(typeof e=="string")return e;const t=e?.__lunoraRef;if(typeof t!="string"||t.length===0)throw new n("INTERNAL","createShardClient: expected a generated function reference (api.*/internal.*) or a 'namespace:fn' string");return t},E=e=>{const t=new n(e.code,e.message);return e.data!==void 0&&(t.data=f(e.data)),t},x=(e,t={})=>{const l=g(e,t.jurisdiction),m=t.system??!0,c=r=>x(e,{...t,...r});return{as:r=>c({as:r}),asSystem:()=>c({as:void 0}),call:async(r,y,o)=>{const i=A(r),h=o?.shardKey??t.shardKey;if(h===void 0||h.length===0)throw new n("INTERNAL",`createShardClient: no shard key for "${i}" — pass one to createShardClient({ shardKey }), .forShard(key), or the call's options`);const a={"content-type":"application/json"};m&&(a[p]=w,a["x-lunora-system"]="1"),t.as&&(a["x-lunora-userid"]=S(t.as.userId),t.as.claims&&(a["x-lunora-identity"]=I(t.as.claims))),o?.mutationId!==void 0&&o.mutationId.length>0&&(a["x-lunora-mutation-id"]=o.mutationId);const s=await L(l,h).fetch(new Request("https://shard.internal/rpc",{body:JSON.stringify({args:N(y??{}),functionPath:i}),headers:a,method:"POST"})),u=s.statusText?` ${s.statusText}`:"";let d;try{d=await s.json()}catch{throw new n("INTERNAL",`createShardClient: shard response for "${i}" was not JSON (status ${String(s.status)}${u})`)}if("error"in d)throw E(d.error);if(!s.ok)throw new n("INTERNAL",`createShardClient: shard call "${i}" failed (status ${String(s.status)}${u})`);return f(d.result)},forShard:r=>c({shardKey:r})}};export{x as createShardClient};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{f as K,t as j}from"./base64-Bl1_r2k1.mjs";import{t as O}from"./portable-json-
|
|
1
|
+
import{f as K,t as j}from"./base64-Bl1_r2k1.mjs";import{t as O}from"./portable-json-CTm_YALS.mjs";const N=new TextEncoder,q=e=>j(N.encode(JSON.stringify(e))),B=e=>{const r={g:0,s:{},v:1};if(typeof e!="string"||e.length===0)return r;try{const t=JSON.parse(new TextDecoder().decode(K(e))),o=t.s&&typeof t.s=="object"?t.s:{},s={};for(const[i,n]of Object.entries(o))typeof n=="number"&&Number.isFinite(n)&&(s[i]=n);return{g:typeof t.g=="number"&&Number.isFinite(t.g)?t.g:0,s,v:1}}catch{return r}},P=e=>{const r=typeof e.table=="string"?e.table:"",t=typeof e.op=="string"?e.op:"",o=t==="delete"||t==="insert"||t==="update"?t:"upsert",s=typeof e.id=="string"?e.id:void 0;return{doc:(e.doc&&typeof e.doc=="object"?e.doc:void 0)??(s===void 0?{}:{_id:s}),op:o,table:r}},M=e=>Math.max(1,Math.min(e??1e3,1e4)),D=(e,r,t)=>{for(const o of r)e.push(P(o));return t!==void 0&&r.length>=t},R=e=>new Promise(r=>{setTimeout(r,e)}),$=e=>{const r=typeof e.table=="string"?e.table:"",t=typeof e.op=="string"?e.op:"",o=t==="delete"||t==="insert"||t==="update"?t:"upsert",s=typeof e.id=="string"?e.id:void 0,i=e.doc&&typeof e.doc=="object"?O(e.doc):void 0,n=typeof e.seq=="number"&&Number.isFinite(e.seq)?e.seq:void 0,c=typeof e.ts=="number"&&Number.isFinite(e.ts)?e.ts:void 0;return{op:o,table:r,...i===void 0?{}:{doc:i},...s===void 0?{}:{id:s},...n===void 0?{}:{seq:n},...c===void 0?{}:{ts:c}}},T=async(e,r,t,o,s,i)=>{let n=0;for(;;)try{await e.deliver(r);return}catch(c){if(n>=t)throw c instanceof Error?c:new Error(String(c));const d=Math.min(o*2**n,s);await i(d),n+=1}},I=async e=>{const{coordinator:r,cursorStore:t,defaultShardKey:o,headers:s,initialBackoffMs:i=100,limit:n,maxBackoffMs:c=5e3,maxRetries:d=3,shardDO:S,sink:p,sleep:k=R,tables:C}=e,h=await t.read(p.name),b=await r.orchestrateCdcSync(S,{cursors:h,defaultShardKey:o,headers:s,limit:n,tables:C}),l={...h},m=[];let v=0,f=!1;for(const a of b.shards){if(a.error){m.push({error:a.error.message,shardKey:a.shardKey}),f=!0;continue}const y=a.changes??[];if(y.length===0){l[a.shardKey]=a.cursor;continue}const g=y.map(u=>$(u)),E={changes:g,cursor:a.cursor,shardKey:a.shardKey,sink:p.name};try{await T(p,E,d,i,c,k),l[a.shardKey]=a.cursor,v+=g.length,y.length>=M(n)&&(f=!0)}catch(u){m.push({error:u instanceof Error?u.message:String(u),shardKey:a.shardKey}),f=!0}}return await t.write(p.name,l),{cursors:l,delivered:v,failures:m,hasMore:f,shards:b.shards.length}},x=e=>{if(typeof e.name!="string"||e.name.length===0)throw new Error("defineExportSink: `name` must be a non-empty string");if(typeof e.deliver!="function")throw new TypeError("defineExportSink: `deliver` must be a function");return{deliver:e.deliver,name:e.name}},w=e=>`${e.map(r=>JSON.stringify(r)).join(`
|
|
2
2
|
`)}
|
|
3
3
|
`,J=e=>{const r=e.fetchImpl??((t,o)=>fetch(t,o));return x({deliver:async t=>{const o=await r(e.url,{body:w(t.changes),headers:{"content-type":"application/x-ndjson","x-lunora-cursor":String(t.cursor),"x-lunora-shard":t.shardKey,"x-lunora-sink":t.sink,...e.headers},method:"POST"});if(!o.ok)throw new Error(`webhook export sink "${e.name}" returned ${String(o.status)}`)},name:e.name})},U=e=>{let r=e.prefix??"cdc";for(;r.endsWith("/");)r=r.slice(0,-1);return x({deliver:async t=>{const o=`${r}/${t.shardKey}/${String(t.cursor)}.ndjson`;await e.bucket.put(o,w(t.changes),{httpMetadata:{contentType:"application/x-ndjson"}})},name:e.name})},z=()=>{const e={};return{read:r=>Promise.resolve({...e[r]}),snapshot:()=>structuredClone(e),write:(r,t)=>(e[r]={...t},Promise.resolve())}},W=(e,r)=>{const t=r?.keyPrefix??"__lunora_source_cursor:export",o=s=>`${t}:${s}`;return{read:async s=>{const i=await e.get(o(s),"json");if(i===null||typeof i!="object")return{};const n={};for(const[c,d]of Object.entries(i))typeof d=="number"&&Number.isFinite(d)&&(n[c]=d);return n},write:async(s,i)=>{await e.put(o(s),JSON.stringify(i))}}};export{z as a,I as b,W as c,x as d,B as e,D as f,q as g,M as h,U as r,$ as s,J as w};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as i}from"./base64-Bl1_r2k1.mjs";import{d as f,i as s}from"./wire-codec-
|
|
1
|
+
import{a as i}from"./base64-Bl1_r2k1.mjs";import{d as f,i as s}from"./wire-codec-BkjZMyIW.mjs";const o=r=>{if(typeof r=="bigint")return r.toString();if(r instanceof ArrayBuffer)return i(new Uint8Array(r));if(ArrayBuffer.isView(r))return i(new Uint8Array(r.buffer,r.byteOffset,r.byteLength));if(Array.isArray(r))return r.map(t=>o(t));if(s(r)){const t={};for(const e of Object.keys(r)){const n=o(r[e]);e==="__proto__"?Object.defineProperty(t,e,{configurable:!0,enumerable:!0,value:n,writable:!0}):t[e]=n}return t}return r},y=r=>o(f(r));export{y as t};
|
package/dist/packem_shared/{toAirbyteMessages-2d_iJXPf.mjs → toAirbyteMessages-Cmw-8nDf.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{t as b}from"./portable-json-
|
|
1
|
+
import{t as b}from"./portable-json-CTm_YALS.mjs";const p="_id",f=(t,n=p)=>{const o=Object.create(null),s=Object.create(null),c=Object.create(null),a=Object.create(null),h=e=>typeof n=="string"?n:n[e]??p,l=(e,r)=>{const u=e[r];if(u)return u;const d=[];return e[r]=d,d};for(const e of t.changes){a[e.table]??={primary_key:[h(e.table)]};const r=b(e.doc);e.op==="delete"?l(c,e.table).push(r):e.op==="update"?l(s,e.table).push(r):l(o,e.table).push(r)}return{delete:c,hasMore:t.hasMore,insert:o,schema:a,state:{cursor:t.nextCursor},update:s}},m=(t,n=Date.now())=>{const o=[];for(const s of t.changes){const c=b(s.doc),a=s.op==="delete"?{...c,_lunora_deleted:!0}:c;o.push({record:{data:a,emitted_at:n,stream:s.table},type:"RECORD"})}return o.push({state:{data:{cursor:t.nextCursor}},type:"STATE"}),o};export{m as toAirbyteMessages,f as toFivetranResponse};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as d,b as E}from"./base64-Bl1_r2k1.mjs";const o="$lunora.wire$",w=64,g=1024,p="__proto__",A={BigInt64Array,BigUint64Array,Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array},l={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},O=e=>{if(e===null||typeof e!="object")return!1;const n=Object.getPrototypeOf(e);return n===null||n===Object.prototype},y=(e,n=0)=>{if(n>w)throw new RangeError(`wire-codec: value nesting exceeds the ${w}-level limit`);if(e===void 0)return[o,"undefined"];if(e===null)return null;const b=typeof e;if(b==="bigint"){const r=e.toString();if(r.length>g)throw new RangeError(`wire-codec: over-long bigint (max ${g} digits)`);return[o,"bigint",r]}if(b==="number"){const r=e;return Number.isNaN(r)?[o,"nan"]:r===1/0?[o,"inf"]:r===-1/0?[o,"-inf"]:r}if(b!=="object")return e;if(e instanceof Date)return[o,"date",y(e.getTime(),n+1)];if(e instanceof Error){const r=e,t=y(Object.fromEntries(Object.keys(r).map(c=>[c,r[c]])),n+1),i=[o,"error",String(r.name),String(r.message),t];return r.cause!==void 0&&i.push(y(r.cause,n+1)),i}if(e instanceof URL)return[o,"url",e.href];if(e instanceof Map)return[o,"map",[...e.entries()].map(([r,t])=>[y(r,n+1),y(t,n+1)])];if(e instanceof Set)return[o,"set",[...e].map(r=>y(r,n+1))];if(e instanceof ArrayBuffer)return[o,"bytes",d(new Uint8Array(e)),"ArrayBuffer"];if(ArrayBuffer.isView(e)){const r=e,t=r.constructor.name,i=new Uint8Array(r.buffer,r.byteOffset,r.byteLength);return t==="Uint8Array"?[o,"bytes",d(i)]:[o,"bytes",d(i),t]}if(Array.isArray(e)){const r=e.map(t=>y(t,n+1));return r.length>0&&r[0]===o?[o,"arr",r]:r}if(!O(e)){const r=e.constructor?.name??"value";throw new TypeError(`wire-codec: cannot encode a ${r} over the Lunora wire — only plain objects, arrays, and the supported built-ins (Date, Error, URL, Map, Set, ArrayBuffer/typed arrays, bigint) round-trip`)}const s=e,a={};for(const r of Object.keys(s)){const t=s[r];if(t===void 0)continue;const i=y(t,n+1);r===p?Object.defineProperty(a,r,{configurable:!0,enumerable:!0,value:i,writable:!0}):a[r]=i}return a},f=(e,n=0)=>{if(n>w)throw new RangeError(`wire-codec: value nesting exceeds the ${w}-level limit`);if(e===null||typeof e!="object")return e;if(Array.isArray(e)){if(e[0]===o)switch(e[1]){case"-inf":return-1/0;case"arr":return e[2].map(r=>f(r,n+1));case"bigint":{const r=e[2];if(typeof r!="string"||r.length>g||!/^-?\d+$/.test(r))throw new RangeError(`wire-codec: invalid or over-long bigint (max ${g} digits)`);return BigInt(r)}case"date":{const r=f(e[2],n+1);if(typeof r!="number")throw new TypeError("wire-codec: malformed date — epoch must be a number");return new Date(r)}case"map":{const r=e[2];return new Map(r.map(t=>{if(!Array.isArray(t)||t.length!==2)throw new TypeError("wire-codec: malformed map entry — expected a [key, value] pair");return[f(t[0],n+1),f(t[1],n+1)]}))}case"set":return new Set(e[2].map(r=>f(r,n+1)));case"url":{const r=e[2];if(typeof r!="string")throw new TypeError("wire-codec: malformed url — href must be a string");return new URL(r)}case"error":{const r=e[2],t=e[3];if(typeof r!="string"||typeof t!="string")throw new TypeError("wire-codec: malformed error — name and message must be strings");const i=(Object.hasOwn(l,r)?l[r]:void 0)??Error,c=new i(t);c.name!==r&&Object.defineProperty(c,"name",{configurable:!0,value:r,writable:!0});const u=f(e[4],n+1);if(u===null||typeof u!="object"||Array.isArray(u))throw new TypeError("wire-codec: malformed error — props must be an object");for(const m of Object.keys(u))m===p?Object.defineProperty(c,m,{configurable:!0,enumerable:!0,value:u[m],writable:!0}):c[m]=u[m];return e.length>5&&Object.defineProperty(c,"cause",{configurable:!0,value:f(e[5],n+1),writable:!0}),c}case"bytes":{const r=e[2];if(typeof r!="string")throw new TypeError("wire-codec: malformed bytes — payload must be a base64 string");const t=E(r);if(d(t)!==r)throw new TypeError("wire-codec: malformed bytes — payload must be canonical padded base64");const i=e[3]??"Uint8Array";if(i==="ArrayBuffer")return t.buffer.byteLength===t.byteLength?t.buffer:t.slice().buffer;const c=Object.hasOwn(A,i)?A[i]:void 0;return c?new c(t.slice().buffer):t}case"inf":return 1/0;case"nan":return Number.NaN;case"undefined":return;default:return e.map(r=>f(r,n+1))}return e.map(a=>f(a,n+1))}const b=e,s={};for(const a of Object.keys(b)){const r=f(b[a],n+1);a===p?Object.defineProperty(s,a,{configurable:!0,enumerable:!0,value:r,writable:!0}):s[a]=r}return s},T=(e,n,b)=>{try{return y(b)}catch(s){throw new TypeError(`${e}: cannot encode args for '${n}' — ${s instanceof Error?s.message:String(s)}`,s instanceof Error?{cause:s}:void 0)}};export{T as a,f as d,y as e,O as i};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/runtime",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.182",
|
|
4
4
|
"description": "Lunora Worker runtime: the RPC router, shard resolver, and query coordinator",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cloudflare",
|
|
@@ -48,7 +48,7 @@
|
|
|
48
48
|
"dependencies": {
|
|
49
49
|
"@lunora/bindings": "1.0.0-alpha.98",
|
|
50
50
|
"@lunora/errors": "1.0.0-alpha.50",
|
|
51
|
-
"@lunora/observability": "1.0.0-alpha.
|
|
51
|
+
"@lunora/observability": "1.0.0-alpha.125",
|
|
52
52
|
"@lunora/platform": "1.0.0-alpha.56"
|
|
53
53
|
},
|
|
54
54
|
"peerDependencies": {
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a as d,b as E}from"./base64-Bl1_r2k1.mjs";const o="$lunora.wire$",w=64,p=1024,g="__proto__",l={BigInt64Array,BigUint64Array,Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array},A={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},O=e=>{if(e===null||typeof e!="object")return!1;const n=Object.getPrototypeOf(e);return n===null||n===Object.prototype},u=(e,n=0)=>{if(n>w)throw new RangeError(`wire-codec: value nesting exceeds the ${w}-level limit`);if(e===void 0)return[o,"undefined"];if(e===null)return null;const b=typeof e;if(b==="bigint")return[o,"bigint",e.toString()];if(b==="number"){const r=e;return Number.isNaN(r)?[o,"nan"]:r===1/0?[o,"inf"]:r===-1/0?[o,"-inf"]:r}if(b!=="object")return e;if(e instanceof Date)return[o,"date",u(e.getTime(),n+1)];if(e instanceof Error){const r=e,t={};for(const i of Object.keys(r)){if(r[i]===void 0)continue;const y=u(r[i],n+1);i===g?Object.defineProperty(t,i,{configurable:!0,enumerable:!0,value:y,writable:!0}):t[i]=y}const s=[o,"error",String(r.name),String(r.message),t];return r.cause!==void 0&&s.push(u(r.cause,n+1)),s}if(e instanceof URL)return[o,"url",e.href];if(e instanceof Map)return[o,"map",[...e.entries()].map(([r,t])=>[u(r,n+1),u(t,n+1)])];if(e instanceof Set)return[o,"set",[...e].map(r=>u(r,n+1))];if(e instanceof ArrayBuffer)return[o,"bytes",d(new Uint8Array(e)),"ArrayBuffer"];if(ArrayBuffer.isView(e)){const r=e,t=r.constructor.name,s=new Uint8Array(r.buffer,r.byteOffset,r.byteLength);return t==="Uint8Array"?[o,"bytes",d(s)]:[o,"bytes",d(s),t]}if(Array.isArray(e)){const r=e.map(t=>u(t,n+1));return r.length>0&&r[0]===o?[o,"arr",r]:r}if(!O(e)){const r=e.constructor?.name??"value";throw new TypeError(`wire-codec: cannot encode a ${r} over the Lunora wire — only plain objects, arrays, and the supported built-ins (Date, Error, URL, Map, Set, ArrayBuffer/typed arrays, bigint) round-trip`)}const c=e,a={};for(const r of Object.keys(c)){const t=c[r];if(t===void 0)continue;const s=u(t,n+1);r===g?Object.defineProperty(a,r,{configurable:!0,enumerable:!0,value:s,writable:!0}):a[r]=s}return a},f=(e,n=0)=>{if(n>w)throw new RangeError(`wire-codec: value nesting exceeds the ${w}-level limit`);if(e===null||typeof e!="object")return e;if(Array.isArray(e)){if(e[0]===o)switch(e[1]){case"-inf":return-1/0;case"arr":return e[2].map(r=>f(r,n+1));case"bigint":{const r=e[2];if(typeof r!="string"||r.length>p||!/^-?\d+$/.test(r))throw new RangeError(`wire-codec: invalid or over-long bigint (max ${p} digits)`);return BigInt(r)}case"date":{const r=f(e[2],n+1);if(typeof r!="number")throw new TypeError("wire-codec: malformed date — epoch must be a number");return new Date(r)}case"map":{const r=e[2];return new Map(r.map(t=>{if(!Array.isArray(t)||t.length!==2)throw new TypeError("wire-codec: malformed map entry — expected a [key, value] pair");return[f(t[0],n+1),f(t[1],n+1)]}))}case"set":return new Set(e[2].map(r=>f(r,n+1)));case"url":{const r=e[2];if(typeof r!="string")throw new TypeError("wire-codec: malformed url — href must be a string");return new URL(r)}case"error":{const r=e[2],t=e[3];if(typeof r!="string"||typeof t!="string")throw new TypeError("wire-codec: malformed error — name and message must be strings");const s=(Object.hasOwn(A,r)?A[r]:void 0)??Error,i=new s(t);i.name!==r&&Object.defineProperty(i,"name",{configurable:!0,value:r,writable:!0});const y=f(e[4],n+1);if(y===null||typeof y!="object"||Array.isArray(y))throw new TypeError("wire-codec: malformed error — props must be an object");for(const m of Object.keys(y))m===g?Object.defineProperty(i,m,{configurable:!0,enumerable:!0,value:y[m],writable:!0}):i[m]=y[m];return e.length>5&&Object.defineProperty(i,"cause",{configurable:!0,value:f(e[5],n+1),writable:!0}),i}case"bytes":{const r=e[2];if(typeof r!="string")throw new TypeError("wire-codec: malformed bytes — payload must be a base64 string");const t=E(r);if(d(t)!==r)throw new TypeError("wire-codec: malformed bytes — payload must be canonical padded base64");const s=e[3]??"Uint8Array";if(s==="ArrayBuffer")return t.buffer.byteLength===t.byteLength?t.buffer:t.slice().buffer;const i=Object.hasOwn(l,s)?l[s]:void 0;return i?new i(t.slice().buffer):t}case"inf":return 1/0;case"nan":return Number.NaN;case"undefined":return;default:return e.map(r=>f(r,n+1))}return e.map(a=>f(a,n+1))}const b=e,c={};for(const a of Object.keys(b)){const r=f(b[a],n+1);a===g?Object.defineProperty(c,a,{configurable:!0,enumerable:!0,value:r,writable:!0}):c[a]=r}return c},T=(e,n,b)=>{try{return u(b)}catch(c){throw new TypeError(`${e}: cannot encode args for '${n}' — ${c instanceof Error?c.message:String(c)}`,c instanceof Error?{cause:c}:void 0)}};export{T as a,f as d,u as e,O as i};
|