@lunora/do 1.0.0-alpha.100 → 1.0.0-alpha.101
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{serveRelationFanout as a}from"./packem_shared/serveRelationFanout-DcSjzAZv.mjs";import{SESSION_DO_TTL_DEFAULT as t,SessionDO as c}from"./packem_shared/SESSION_DO_TTL_DEFAULT-C4oEfgFy.mjs";import{ROOT_DO_SIZE_WARN_BYTES as i,ROOT_SHARD_NAME as s,ShardDO as n}from"./packem_shared/ROOT_DO_SIZE_WARN_BYTES-
|
|
1
|
+
import{serveRelationFanout as a}from"./packem_shared/serveRelationFanout-DcSjzAZv.mjs";import{SESSION_DO_TTL_DEFAULT as t,SessionDO as c}from"./packem_shared/SESSION_DO_TTL_DEFAULT-C4oEfgFy.mjs";import{ROOT_DO_SIZE_WARN_BYTES as i,ROOT_SHARD_NAME as s,ShardDO as n}from"./packem_shared/ROOT_DO_SIZE_WARN_BYTES-B0Fd2VCk.mjs";import{SHARD_REGISTRY_DO_NAME as R,ShardRegistryDO as d}from"./packem_shared/SHARD_REGISTRY_DO_NAME-CF4ion0i.mjs";import{createShardAlarms as h,createShardDirectory as D,createShardHost as O,createShardKvStore as _,createShardPlatform as E,createSocketHost as m,createWorkerPlatform as u}from"@lunora/platform-cloudflare";import{REPROJECTION_MIGRATION_PREFIX as x,UNVOUCHABLE_DEP as I,applyCdcChanges as f,assertShapeShardable as A,backfillSearchIndexes as b,buildReprojectionMigration as M,clearMemoryTables as g,countLegacyRows as N,createReadFootprint as k,createShardCtxDb as y,exportShardRows as C,importShardRows as H,isSourceDue as L,markUnvouchableReads as P,pullExternalSourceIncrementalTick as F,pullExternalSourceTick as U,reprojectionMigrationId as j,reprojectionTables as v,runDataMigration as w,runShardMigrations as B,subscriptionListDeltas as G}from"@lunora/shard-engine";export{x as REPROJECTION_MIGRATION_PREFIX,i as ROOT_DO_SIZE_WARN_BYTES,s as ROOT_SHARD_NAME,t as SESSION_DO_TTL_DEFAULT,R as SHARD_REGISTRY_DO_NAME,c as SessionDO,n as ShardDO,d as ShardRegistryDO,I as UNVOUCHABLE_DEP,f as applyCdcChanges,A as assertShapeShardable,b as backfillSearchIndexes,M as buildReprojectionMigration,g as clearMemoryTables,N as countLegacyRows,k as createReadFootprint,h as createShardAlarms,y as createShardCtxDb,D as createShardDirectory,O as createShardHost,_ as createShardKvStore,E as createShardPlatform,m as createSocketHost,u as createWorkerPlatform,C as exportShardRows,H as importShardRows,L as isSourceDue,P as markUnvouchableReads,F as pullExternalSourceIncrementalTick,U as pullExternalSourceTick,j as reprojectionMigrationId,v as reprojectionTables,w as runDataMigration,B as runShardMigrations,a as serveRelationFanout,G as subscriptionListDeltas};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{LunoraError as p,toErrorBody as B}from"@lunora/errors";import{ISSUE_STATUSES as mt,ISSUE_SEVERITIES as yt,readQueryInsights as St,LogBuffer as bt,SpanBuffer as gt,MetricBuffer as Rt,emitLogEvent as At,resolveTraceAnchor as Q,createTracer as Et,instrumentDatabase as vt,createTracedFetch as wt,createMetrics as Tt,redactArgs as Ct,REQUEST_LOG_TABLE as we,createDatabaseTally as It,formatTally as _t,dispatchRootSpan as kt,readFunctionMetricsTotals as Mt,readFunctionMetricIndexHits as Ot,readQueryMetrics as qt,recordFunctionMetric as Nt,mergeScanAttribution as xt,recordQueryMetric as Pt,readFunctionMetrics as Dt,readFunctionMetricBuckets as Lt,upsertIssueState as Bt,ISSUE_STATE_TABLE as Ut,recordAuthEvent as Ht,explainIssue as Ft,appendRequestLogEntry as Wt,emitRequestLogEvent as $t,findDanglingReferences as Qt,foldTraces as Kt,readMetricHistory as jt,buildSecurityAudit as Gt,ensureRequestLogTable as Te,readRequestLog as zt,readErrorIssues as Jt,readAuthMetrics as Xt,parseLogArgs as Yt,createSpanCollector as Vt,recordMetricHistory as Zt}from"@lunora/observability";import{createShardHost as er,createSocketHost as tr}from"@lunora/platform-cloudflare";import{tableFromDepKey as rr,ADMIN_FUNCTION_PREFIX as _,DOC_COLUMN as Ce,readSchemaVersion as sr,readSchemaHistory as nr,lintReadonlySql as ir,createShapeProbeCounters as or,createGlobalPollCounters as ar,DurableStreamRunner as cr,createFanoutCounters as Ie,ShardRunner as dr,ReactiveCache as lr,createRelayLink as ur,listTables as V,minCdcReplayableSeq as hr,createReplicaLink as pr,deleteGlobalShapeSnapshotsForConnection as fr,deleteShapePokeCursorsForConnection as mr,readReactorState as yr,reactorNeedsRun as Sr,MAX_PAGE_SIZE as br,selectMatchingIds as gr,CDC_LOG_TABLE as _e,minCdcSeq as Z,cursorBelowRetainedFloor as K,cdcTrimmedError as Rr,readCdcChanges as Ar,readCdcCursor as ke,readCdcEpoch as ee,bumpCdcEpoch as Me,cdcCanVouchFor as Er,cdcTouchesTables as vr,readIdempotent as wr,writeIdempotent as Tr,trimIdempotent as Cr,readClientWatermark as te,migrateClientWatermark as Ir,advanceClientWatermark as _r,deleteGlobalShapeSnapshot as kr,deleteShapePokeCursor as Mr,trySendFrame as D,selectExpiredIds as Or,createDependencyTracker as qr,createReadFootprint as Nr,stableStringify as xr,reactiveCacheKey as Oe,SCAN_DEP as j,TransactionHeadroomTracker as re,recordChangedKeys as Pr,DATA_MIGRATION_STATE_TABLE as Dr,isDevEnvironment as O,gateReplicaDispatch as Lr,RELATION_FUNCTION_PREFIX as Br,ConflictError as Ur,ADMIN_FUNCTIONS as h,parseExportShardArgs as Hr,parseImportShardArgs as Fr,writeReactorState as qe,UNVOUCHABLE_DEP as Ne,listReactorStates as Wr,recordCapturedMail as xe,clearCapturedMail as $r,recordQueueMessages as Qr,clearQueueMessages as Kr,readQueueMessageById as jr,isLossyBody as Gr,appendAuditEntry as zr,readBookmark as Jr,armRestore as Xr,readMigrationStatus as Yr,findStorageReferences as Vr,buildSettings as Zr,summarizeSubscriptions as es,summarizeFanoutTopics as ts,DEFAULT_MAX_RELAYS as rs,ensureAuditTable as ss,readAuditLog as ns,readCapturedMail as is,MAIL_TABLE as os,readQueueMessages as as,QUEUE_TABLE as cs,readTablePage as ds,facetColumn as ls,runReadonlySql as us,FLAGS_FUNCTION_PREFIX as hs,awaitWsDrain as U,stableWireKey as ps,mergeChangedKeys as fs,runSocketPool as Pe,createShapeDiffCache as se,recordFanoutPass as ne,recordShapeProbePass as De,envOptionalPositiveInt as ie,cdcSeqLeavingRows as Le,compactCdcDocs as ms,trimCdcChanges as ys,minShapePokeCursor as Ss,readCdcChangeKeys as bs,buildShapeDiff as gs,selectShapeRows as Rs,projectColumns as As,diffGlobalMembership as Be,readGlobalShapeSnapshot as Es,writeGlobalShapeSnapshot as vs,GlobalPollTick as oe,globalShapeReadKey as ws,recordGlobalPollPass as Ts,buildPokeFrames as Cs,readShapePokeCursor as Is,writeShapePokeCursor as _s,subscriptionFrames as ks,handleReplicaControl as Ms,writeTouchesMemo as Os}from"@lunora/shard-engine";import{subscriptionListDeltas as Xi}from"@lunora/shard-engine";import{drizzle as qs}from"drizzle-orm/durable-sqlite";import{c as ae}from"./constant-time-equal-BRh9yUCr.mjs";import{j as v}from"./json-response-wrh9TBPw.mjs";const Ue=500,J=(i,e)=>{if(i.size<e)return;const t=i.keys().next().value;t!==void 0&&i.delete(t)},ce=i=>{let e="";for(let r=0;r<i.length;r+=32768)e+=String.fromCharCode(...i.subarray(r,r+32768));return btoa(e)},rt=i=>{const e=atob(i),t=new Uint8Array(e.length);for(let r=0;r<e.length;r+=1)t[r]=e.codePointAt(r)??0;return t},st=i=>{const e=i.replaceAll("-","+").replaceAll("_","/"),t=e+"=".repeat((4-e.length%4)%4);return rt(t)},nt=new TextDecoder;new TextEncoder;const He="=",Ns=i=>{if(i)try{const e=i[0]==="{"?i:nt.decode(st(i)),t=JSON.parse(e);if(t&&typeof t=="object"&&!Array.isArray(t))return t}catch{}},Fe=i=>{if(i){if(!i.startsWith(He))return i;try{return nt.decode(st(i.slice(He.length)))}catch{return}}},xs=i=>{const e=Number(i);return Number.isFinite(e)&&e>0?e:void 0},Ps=i=>typeof i=="number"&&Date.now()>=i,Ds=i=>{try{i.send(JSON.stringify({code:"TOKEN_EXPIRED",error:{code:"TOKEN_EXPIRED",message:"authentication token expired"},type:"error"})),i.close?.(4001,"token_expired")}catch{}},G=/^[0-9a-f]+$/,Ls=i=>{if(i==null)return;const e=i.trim().toLowerCase().split("-"),[t,r,n,s]=e;if(!(e.length<4||t===void 0||t.length!==2||!G.test(t)||t==="ff"||t==="00"&&e.length!==4||r===void 0||n===void 0||s===void 0||s.length!==2||!G.test(s)||r.length!==32||n.length!==16||!G.test(r)||!G.test(n)||r==="00000000000000000000000000000000"||n==="0000000000000000"))return{parentSpanId:n,sampled:(Number.parseInt(s,16)&1)===1,traceId:r}},de=Object.freeze({durationMs:"lunora.duration_ms",errorMessage:"error.message",errorType:"error.type",functionPath:"lunora.function_path",ok:"lunora.ok",shardKey:"lunora.shard_key",userId:"lunora.user_id"}),w="$lunora.wire$",X=64,We=1024,me="__proto__",$e={BigInt64Array,BigUint64Array,Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array},Qe={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},Bs=i=>{if(i===null||typeof i!="object")return!1;const e=Object.getPrototypeOf(i);return e===null||e===Object.prototype},T=(i,e=0)=>{if(e>X)throw new RangeError(`wire-codec: value nesting exceeds the ${X}-level limit`);if(i===void 0)return[w,"undefined"];if(i===null)return null;const t=typeof i;if(t==="bigint")return[w,"bigint",i.toString()];if(t==="number"){const s=i;return Number.isNaN(s)?[w,"nan"]:s===1/0?[w,"inf"]:s===-1/0?[w,"-inf"]:s}if(t!=="object")return i;if(i instanceof Date)return[w,"date",T(i.getTime(),e+1)];if(i instanceof Error){const s=i,o={};for(const c of Object.keys(s))s[c]!==void 0&&(o[c]=T(s[c],e+1));const a=[w,"error",s.name,s.message,o];return s.cause!==void 0&&a.push(T(s.cause,e+1)),a}if(i instanceof URL)return[w,"url",i.href];if(i instanceof Map)return[w,"map",[...i.entries()].map(([s,o])=>[T(s,e+1),T(o,e+1)])];if(i instanceof Set)return[w,"set",[...i].map(s=>T(s,e+1))];if(i instanceof ArrayBuffer)return[w,"bytes",ce(new Uint8Array(i)),"ArrayBuffer"];if(ArrayBuffer.isView(i)){const s=i,o=s.constructor.name,a=new Uint8Array(s.buffer,s.byteOffset,s.byteLength);return o==="Uint8Array"?[w,"bytes",ce(a)]:[w,"bytes",ce(a),o]}if(Array.isArray(i)){const s=i.map(o=>T(o,e+1));return s.length>0&&s[0]===w?[w,"arr",s]:s}if(!Bs(i)){const s=i.constructor?.name??"value";throw new TypeError(`wire-codec: cannot encode a ${s} 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 r=i,n={};for(const s of Object.keys(r)){const o=r[s];if(o===void 0)continue;const a=T(o,e+1);s===me?Object.defineProperty(n,s,{configurable:!0,enumerable:!0,value:a,writable:!0}):n[s]=a}return n},C=(i,e=0)=>{if(e>X)throw new RangeError(`wire-codec: value nesting exceeds the ${X}-level limit`);if(i===null||typeof i!="object")return i;if(Array.isArray(i)){if(i[0]===w)switch(i[1]){case"-inf":return-1/0;case"arr":return i[2].map(s=>C(s,e+1));case"bigint":{const s=i[2];if(typeof s!="string"||s.length>We||!/^-?\d+$/.test(s))throw new RangeError(`wire-codec: invalid or over-long bigint (max ${We} digits)`);return BigInt(s)}case"date":return new Date(C(i[2],e+1));case"map":return new Map(i[2].map(([s,o])=>[C(s,e+1),C(o,e+1)]));case"set":return new Set(i[2].map(s=>C(s,e+1)));case"url":return new URL(i[2]);case"error":{const s=i[2],o=i[3],a=(Object.hasOwn(Qe,s)?Qe[s]:void 0)??Error,c=new a(o);c.name!==s&&Object.defineProperty(c,"name",{configurable:!0,value:s,writable:!0});const l=C(i[4],e+1);for(const d of Object.keys(l))d===me?Object.defineProperty(c,d,{configurable:!0,enumerable:!0,value:l[d],writable:!0}):c[d]=l[d];return i.length>5&&Object.defineProperty(c,"cause",{configurable:!0,value:C(i[5],e+1),writable:!0}),c}case"bytes":{const s=rt(i[2]),o=i[3]??"Uint8Array";if(o==="ArrayBuffer")return s.buffer.byteLength===s.byteLength?s.buffer:s.slice().buffer;const a=Object.hasOwn($e,o)?$e[o]:void 0;return a?new a(s.slice().buffer):s}case"inf":return 1/0;case"nan":return Number.NaN;case"undefined":return;default:return i.map(s=>C(s,e+1))}return i.map(n=>C(n,e+1))}const t=i,r={};for(const n of Object.keys(t)){const s=C(t[n],e+1);n===me?Object.defineProperty(r,n,{configurable:!0,enumerable:!0,value:s,writable:!0}):r[n]=s}return r},Us="pageDelta",Hs=(i,e,t,r)=>{const n=i.get(e);if(n!==void 0)return n;J(i,r);const s=t().catch(o=>{throw i.get(e)===s&&i.delete(e),o});return i.set(e,s),s},it=new TextEncoder,Fs=Array.from({length:32},(i,e)=>e);new RegExp(`[${Fs.map(i=>String.fromCodePoint(i)).join("")}]`,"u");const Ws=i=>{const e=i.replaceAll("-","+").replaceAll("_","/")+"===".slice((i.length+3)%4),t=atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;n+=1)r[n]=t.codePointAt(n)??0;return r},$s=64,Qs=new Map,Ks=async i=>Hs(Qs,i,async()=>crypto.subtle.importKey("raw",it.encode(i),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]),$s),js=async(i,e,t)=>{const r=await Ks(i);return crypto.subtle.verify("HMAC",r,t,it.encode(e))},Gs=new Set(["1","enabled","on","true","yes"]),zs=new Set(["0","disabled","false","no","off"]),Js=(i,e)=>{const t=(i??"").trim().toLowerCase();return Gs.has(t)?!0:zs.has(t)?!1:e},Xs="v1",Ys=async(i,e,t=Date.now())=>{if(i.length===0||e.length===0)return!1;const r=e.split(".");if(r.length!==3)return!1;const[n,s,o]=r;if(n!==Xs||o.length===0)return!1;const a=Number(s);if(!Number.isFinite(a)||a<=t)return!1;let c;try{c=Ws(o)}catch{return!1}return js(i,`${n}.${s}`,c)},ot="__lunoraBranch",Vs=i=>typeof i=="object"&&i!==null&&Object.hasOwn(i,ot),Zs=`may not contain the reserved workflow branch-marker key ("${ot}")`,en=/\(exit (\d+)\)/,tn=new Set(["contains","eq","gt","gte","lt","lte","ne"]),Ke=100,rn="test@lunora.sh",sn=new Set(["complete","errored","paused","queued","running","terminated","unknown","waiting","waitingForPause"]),at=null,je=(i,e)=>(i===void 0?"":`,"cursor":${String(i)}`)+(e===void 0?"":`,"epoch":${JSON.stringify(e)}`),nn=(i,e)=>{const[t,r]=i.size<=e.size?[i,e]:[e,i];for(const n of t)if(r.has(n))return!0;return!1},on=i=>{const e=typeof i.id=="string"?i.id:"";if(e.trim()==="")throw new p("MIGRATION_ID_REQUIRED","runMigration: `id` is required",{status:400});return{batchSize:typeof i.batchSize=="number"?i.batchSize:void 0,direction:i.direction==="down"?"down":"up",dryRun:i.dryRun===!0,id:e,maxBatches:typeof i.maxBatches=="number"?i.maxBatches:void 0}},an=i=>{const{op:e}=i,t=typeof i.table=="string"?i.table:"";if(e!=="insert"&&e!=="patch"&&e!=="replace"&&e!=="delete")throw new p("BAD_REQUEST","writeRow: `op` must be insert|patch|replace|delete");if(t.trim()==="")throw new p("BAD_REQUEST","writeRow: `table` is required");const r=typeof i.id=="string"?i.id:void 0,n=typeof i.doc=="object"&&i.doc!==null&&!Array.isArray(i.doc)?i.doc:void 0;if(e!=="insert"&&(r===void 0||r===""))throw new p("BAD_REQUEST",`writeRow: \`id\` is required for op "${e}"`);if(e!=="delete"&&n===void 0)throw new p("BAD_REQUEST",`writeRow: \`doc\` is required for op "${e}"`);return{doc:n,id:r,op:e,table:t}},cn=i=>typeof i=="string"&&mt.includes(i),dn=i=>typeof i=="string"&&yt.includes(i),ln=i=>{const e=typeof i.hash=="string"?i.hash.trim():"";if(e==="")throw new p("BAD_REQUEST","issue triage: `hash` is required");return e},un=i=>{const e=i.assignee;if(e===null)return at;if(typeof e=="string"&&e.trim()!=="")return e;throw new p("BAD_REQUEST","assignIssue: `assignee` must be a non-empty string (assign) or null (unassign)")},hn=i=>{const e=i.severity;if(e===null)return at;if(dn(e))return e;throw new p("BAD_REQUEST","setIssueSeverity: `severity` must be one of critical|high|medium|low, or null to clear")},pn=i=>{const e=typeof i.exportName=="string"?i.exportName.trim():"";if(e==="")throw new p("BAD_REQUEST","createWorkflowInstance: `exportName` is required");const t=typeof i.id=="string"&&i.id!==""?i.id:void 0;if(Vs(i.params))throw new p("BAD_REQUEST",`createWorkflowInstance: params ${Zs}`);return{exportName:e,id:t,params:i.params}},fn=i=>{const e=typeof i.exportName=="string"?i.exportName.trim():"",t=typeof i.id=="string"?i.id.trim():"";if(e==="")throw new p("BAD_REQUEST","getWorkflowInstanceStatus: `exportName` is required");if(t==="")throw new p("BAD_REQUEST","getWorkflowInstanceStatus: `id` is required");return{exportName:e,id:t}},Ge=i=>typeof i=="string"&&sn.has(i)?i:"unknown",mn=i=>{if(typeof i!="object"||i===null)return;const{message:e,name:t}=i;return{message:typeof e=="string"?e:"",name:typeof t=="string"?t:"Error"}},ye=i=>{if(!Array.isArray(i))return;const e=[];for(const t of i){if(typeof t!="object"||t===null)continue;const r=t,{column:n,operator:s}=r;typeof n!="string"||n===""||typeof s!="string"||!tn.has(s)||e.push({column:n,operator:s,value:r.value})}return e.length>0?e:void 0},yn=i=>{if(typeof i!="object"||i===null)return;const{column:e,direction:t}=i;if(!(typeof e!="string"||e===""))return{column:e,direction:t==="desc"?"desc":"asc"}},Sn=i=>{const e=typeof i.table=="string"?i.table:"";if(e.trim()==="")throw new p("BAD_REQUEST","deleteRows: `table` is required");return{filters:ye(i.filters),limit:typeof i.limit=="number"?i.limit:void 0,search:typeof i.search=="string"?i.search:void 0,table:e}},bn=i=>{const e=typeof i.table=="string"?i.table:"";if(e.trim()==="")throw new p("BAD_REQUEST","clearTable: `table` is required");return{limit:typeof i.limit=="number"?i.limit:void 0,table:e}},gn=i=>{const{outcome:e}=i;if(e!=="ok"&&e!=="fail")throw new p("BAD_REQUEST",'recordAuthEvent: `outcome` must be "ok" or "fail"');return{outcome:e}},Rn=i=>{const e=i.event;if(typeof e!="object"||e===null||Array.isArray(e))throw new p("BAD_REQUEST","recordContainerEvent: `event` must be an object");const t=e,r=typeof t.container=="string"?t.container:"",n=typeof t.event=="string"?t.event:"";if(r.trim()===""||n.trim()==="")throw new p("BAD_REQUEST","recordContainerEvent: `event.container` and `event.event` are required");const s=t.level==="error"?"error":"info",o=typeof t.message=="string"?t.message:void 0,a=typeof t.ts=="number"?t.ts:Date.now(),c=typeof t.instance=="string"&&t.instance!==""?t.instance:void 0,l=o===void 0?void 0:en.exec(o)?.[1];return{exitCode:l===void 0?void 0:Number.parseInt(l,10),functionPath:`container:${r}`,instance:c,level:s,message:o===void 0||o===""?n:`${n}: ${o}`,timestamp:a}},An=i=>{const e=typeof i.functionPath=="string"?i.functionPath:"",t=typeof i.userId=="string"?i.userId:"";if(e.trim()==="")throw new p("BAD_REQUEST","runAs: `functionPath` is required");if(e.startsWith(_))throw new p("BAD_REQUEST","runAs: cannot target a reserved admin function");if(t.trim()==="")throw new p("BAD_REQUEST","runAs: `userId` is required");const r=i.args;if(r!==void 0&&(typeof r!="object"||r===null||Array.isArray(r)))throw new p("BAD_REQUEST","runAs: `args` must be an object");const n=i.identity;if(n!==void 0&&(typeof n!="object"||n===null||Array.isArray(n)))throw new p("BAD_REQUEST","runAs: `identity` must be an object");return{args:r===void 0?{}:r,functionPath:e,userId:t,...n===void 0?{}:{identity:n}}},En=i=>{const e=m=>{throw new p("BAD_REQUEST",`recordMail: ${m}`)},{bcc:t,cc:r,from:n,headers:s,html:o,replyTo:a,subject:c,text:l,to:d}=i;typeof c!="string"&&e("`subject` must be a string"),typeof d=="string"||Array.isArray(d)&&d.every(m=>typeof m=="string")||e("`to` must be a string or string[]");const f=(m,y)=>{if(m!==void 0)return(!Array.isArray(m)||!m.every(R=>typeof R=="string"))&&e(`\`${y}\` must be a string[]`),m},S=(m,y)=>(m!==void 0&&typeof m!="string"&&e(`\`${y}\` must be a string`),m);return{bcc:f(t,"bcc"),cc:f(r,"cc"),from:S(n,"from"),headers:s!==void 0&&typeof s=="object"&&s!==null?s:void 0,html:S(o,"html"),replyTo:S(a,"replyTo"),subject:c,text:S(l,"text"),to:d}},vn=i=>{const{to:e}=i;if(e!==void 0&&typeof e!="string")throw new p("BAD_REQUEST","sendTestMail: `to` must be a string");const t=e??rn,r="https://example.test/verify?token=demo";return{from:"Lunora <noreply@lunora.sh>",html:`<p>This is a test email from the Lunora dev mail catcher.</p><p><a href="${r}">Verify your email</a></p>`,subject:"Lunora test email",text:`This is a test email from the Lunora dev mail catcher.
|
|
1
|
+
import{LunoraError as p,toErrorBody as B}from"@lunora/errors";import{ISSUE_STATUSES as mt,ISSUE_SEVERITIES as yt,readQueryInsights as St,LogBuffer as bt,SpanBuffer as gt,MetricBuffer as Rt,emitLogEvent as At,resolveTraceAnchor as Q,createTracer as Et,instrumentDatabase as vt,createTracedFetch as wt,createMetrics as Tt,redactArgs as Ct,REQUEST_LOG_TABLE as we,createDatabaseTally as It,formatTally as _t,dispatchRootSpan as kt,readFunctionMetricsTotals as Mt,readFunctionMetricIndexHits as Ot,readQueryMetrics as qt,recordFunctionMetric as Nt,mergeScanAttribution as xt,recordQueryMetric as Pt,readFunctionMetrics as Dt,readFunctionMetricBuckets as Lt,upsertIssueState as Bt,ISSUE_STATE_TABLE as Ut,recordAuthEvent as Ht,explainIssue as Ft,appendRequestLogEntry as Wt,emitRequestLogEvent as $t,findDanglingReferences as Qt,foldTraces as Kt,readMetricHistory as jt,buildSecurityAudit as Gt,ensureRequestLogTable as Te,readRequestLog as zt,readErrorIssues as Jt,readAuthMetrics as Xt,parseLogArgs as Yt,createSpanCollector as Vt,recordMetricHistory as Zt}from"@lunora/observability";import{createShardHost as er,createSocketHost as tr}from"@lunora/platform-cloudflare";import{tableFromDepKey as rr,ADMIN_FUNCTION_PREFIX as _,DOC_COLUMN as Ce,readSchemaVersion as sr,readSchemaHistory as nr,lintReadonlySql as ir,createShapeProbeCounters as or,createGlobalPollCounters as ar,DurableStreamRunner as cr,createFanoutCounters as Ie,ShardRunner as dr,ReactiveCache as lr,createRelayLink as ur,listTables as V,minCdcReplayableSeq as hr,createReplicaLink as pr,deleteGlobalShapeSnapshotsForConnection as fr,deleteShapePokeCursorsForConnection as mr,readReactorState as yr,reactorNeedsRun as Sr,MAX_PAGE_SIZE as br,selectMatchingIds as gr,CDC_LOG_TABLE as _e,minCdcSeq as Z,cursorBelowRetainedFloor as K,cdcTrimmedError as Rr,readCdcChanges as Ar,readCdcCursor as ke,readCdcEpoch as ee,bumpCdcEpoch as Me,cdcCanVouchFor as Er,cdcTouchesTables as vr,readIdempotent as wr,writeIdempotent as Tr,trimIdempotent as Cr,readClientWatermark as te,migrateClientWatermark as Ir,advanceClientWatermark as _r,deleteGlobalShapeSnapshot as kr,deleteShapePokeCursor as Mr,trySendFrame as D,selectExpiredIds as Or,createDependencyTracker as qr,createReadFootprint as Nr,stableStringify as xr,reactiveCacheKey as Oe,SCAN_DEP as j,TransactionHeadroomTracker as re,recordChangedKeys as Pr,DATA_MIGRATION_STATE_TABLE as Dr,isDevEnvironment as O,gateReplicaDispatch as Lr,RELATION_FUNCTION_PREFIX as Br,ConflictError as Ur,ADMIN_FUNCTIONS as h,parseExportShardArgs as Hr,parseImportShardArgs as Fr,writeReactorState as qe,UNVOUCHABLE_DEP as Ne,listReactorStates as Wr,recordCapturedMail as xe,clearCapturedMail as $r,recordQueueMessages as Qr,clearQueueMessages as Kr,readQueueMessageById as jr,isLossyBody as Gr,appendAuditEntry as zr,readBookmark as Jr,armRestore as Xr,readMigrationStatus as Yr,findStorageReferences as Vr,buildSettings as Zr,summarizeSubscriptions as es,summarizeFanoutTopics as ts,DEFAULT_MAX_RELAYS as rs,ensureAuditTable as ss,readAuditLog as ns,readCapturedMail as is,MAIL_TABLE as os,readQueueMessages as as,QUEUE_TABLE as cs,readTablePage as ds,facetColumn as ls,runReadonlySql as us,FLAGS_FUNCTION_PREFIX as hs,awaitWsDrain as U,stableWireKey as ps,mergeChangedKeys as fs,runSocketPool as Pe,createShapeDiffCache as se,recordFanoutPass as ne,recordShapeProbePass as De,envOptionalPositiveInt as ie,cdcSeqLeavingRows as Le,compactCdcDocs as ms,trimCdcChanges as ys,minShapePokeCursor as Ss,readCdcChangeKeys as bs,buildShapeDiff as gs,selectShapeRows as Rs,projectColumns as As,diffGlobalMembership as Be,readGlobalShapeSnapshot as Es,writeGlobalShapeSnapshot as vs,GlobalPollTick as oe,globalShapeReadKey as ws,recordGlobalPollPass as Ts,buildPokeFrames as Cs,readShapePokeCursor as Is,writeShapePokeCursor as _s,subscriptionFrames as ks,handleReplicaControl as Ms,writeTouchesMemo as Os}from"@lunora/shard-engine";import{subscriptionListDeltas as Xi}from"@lunora/shard-engine";import{drizzle as qs}from"drizzle-orm/durable-sqlite";import{c as ae}from"./constant-time-equal-BRh9yUCr.mjs";import{j as v}from"./json-response-wrh9TBPw.mjs";const Ue=500,J=(i,e)=>{if(i.size<e)return;const t=i.keys().next().value;t!==void 0&&i.delete(t)},ce=i=>{let e="";for(let r=0;r<i.length;r+=32768)e+=String.fromCharCode(...i.subarray(r,r+32768));return btoa(e)},rt=i=>{const e=atob(i),t=new Uint8Array(e.length);for(let r=0;r<e.length;r+=1)t[r]=e.codePointAt(r)??0;return t},st=i=>{const e=i.replaceAll("-","+").replaceAll("_","/"),t=e+"=".repeat((4-e.length%4)%4);return rt(t)},nt=new TextDecoder;new TextEncoder;const He="=",Ns=i=>{if(i)try{const e=i[0]==="{"?i:nt.decode(st(i)),t=JSON.parse(e);if(t&&typeof t=="object"&&!Array.isArray(t))return t}catch{}},Fe=i=>{if(i){if(!i.startsWith(He))return i;try{return nt.decode(st(i.slice(He.length)))}catch{return}}},xs=i=>{const e=Number(i);return Number.isFinite(e)&&e>0?e:void 0},Ps=i=>typeof i=="number"&&Date.now()>=i,Ds=i=>{try{i.send(JSON.stringify({code:"TOKEN_EXPIRED",error:{code:"TOKEN_EXPIRED",message:"authentication token expired"},type:"error"})),i.close?.(4001,"token_expired")}catch{}};Array.from({length:256},(i,e)=>e.toString(16).padStart(2,"0"));const G=/^[0-9a-f]+$/,Ls=i=>{if(i==null)return;const e=i.trim().toLowerCase().split("-"),[t,r,n,s]=e;if(!(e.length<4||t===void 0||t.length!==2||!G.test(t)||t==="ff"||t==="00"&&e.length!==4||r===void 0||n===void 0||s===void 0||s.length!==2||!G.test(s)||r.length!==32||n.length!==16||!G.test(r)||!G.test(n)||r==="00000000000000000000000000000000"||n==="0000000000000000"))return{parentSpanId:n,sampled:(Number.parseInt(s,16)&1)===1,traceId:r}},de=Object.freeze({durationMs:"lunora.duration_ms",errorMessage:"error.message",errorType:"error.type",functionPath:"lunora.function_path",ok:"lunora.ok",shardKey:"lunora.shard_key",userId:"lunora.user_id"}),w="$lunora.wire$",X=64,We=1024,me="__proto__",$e={BigInt64Array,BigUint64Array,Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array},Qe={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},Bs=i=>{if(i===null||typeof i!="object")return!1;const e=Object.getPrototypeOf(i);return e===null||e===Object.prototype},T=(i,e=0)=>{if(e>X)throw new RangeError(`wire-codec: value nesting exceeds the ${X}-level limit`);if(i===void 0)return[w,"undefined"];if(i===null)return null;const t=typeof i;if(t==="bigint")return[w,"bigint",i.toString()];if(t==="number"){const s=i;return Number.isNaN(s)?[w,"nan"]:s===1/0?[w,"inf"]:s===-1/0?[w,"-inf"]:s}if(t!=="object")return i;if(i instanceof Date)return[w,"date",T(i.getTime(),e+1)];if(i instanceof Error){const s=i,o={};for(const c of Object.keys(s))s[c]!==void 0&&(o[c]=T(s[c],e+1));const a=[w,"error",s.name,s.message,o];return s.cause!==void 0&&a.push(T(s.cause,e+1)),a}if(i instanceof URL)return[w,"url",i.href];if(i instanceof Map)return[w,"map",[...i.entries()].map(([s,o])=>[T(s,e+1),T(o,e+1)])];if(i instanceof Set)return[w,"set",[...i].map(s=>T(s,e+1))];if(i instanceof ArrayBuffer)return[w,"bytes",ce(new Uint8Array(i)),"ArrayBuffer"];if(ArrayBuffer.isView(i)){const s=i,o=s.constructor.name,a=new Uint8Array(s.buffer,s.byteOffset,s.byteLength);return o==="Uint8Array"?[w,"bytes",ce(a)]:[w,"bytes",ce(a),o]}if(Array.isArray(i)){const s=i.map(o=>T(o,e+1));return s.length>0&&s[0]===w?[w,"arr",s]:s}if(!Bs(i)){const s=i.constructor?.name??"value";throw new TypeError(`wire-codec: cannot encode a ${s} 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 r=i,n={};for(const s of Object.keys(r)){const o=r[s];if(o===void 0)continue;const a=T(o,e+1);s===me?Object.defineProperty(n,s,{configurable:!0,enumerable:!0,value:a,writable:!0}):n[s]=a}return n},C=(i,e=0)=>{if(e>X)throw new RangeError(`wire-codec: value nesting exceeds the ${X}-level limit`);if(i===null||typeof i!="object")return i;if(Array.isArray(i)){if(i[0]===w)switch(i[1]){case"-inf":return-1/0;case"arr":return i[2].map(s=>C(s,e+1));case"bigint":{const s=i[2];if(typeof s!="string"||s.length>We||!/^-?\d+$/.test(s))throw new RangeError(`wire-codec: invalid or over-long bigint (max ${We} digits)`);return BigInt(s)}case"date":return new Date(C(i[2],e+1));case"map":return new Map(i[2].map(([s,o])=>[C(s,e+1),C(o,e+1)]));case"set":return new Set(i[2].map(s=>C(s,e+1)));case"url":return new URL(i[2]);case"error":{const s=i[2],o=i[3],a=(Object.hasOwn(Qe,s)?Qe[s]:void 0)??Error,c=new a(o);c.name!==s&&Object.defineProperty(c,"name",{configurable:!0,value:s,writable:!0});const l=C(i[4],e+1);for(const d of Object.keys(l))d===me?Object.defineProperty(c,d,{configurable:!0,enumerable:!0,value:l[d],writable:!0}):c[d]=l[d];return i.length>5&&Object.defineProperty(c,"cause",{configurable:!0,value:C(i[5],e+1),writable:!0}),c}case"bytes":{const s=rt(i[2]),o=i[3]??"Uint8Array";if(o==="ArrayBuffer")return s.buffer.byteLength===s.byteLength?s.buffer:s.slice().buffer;const a=Object.hasOwn($e,o)?$e[o]:void 0;return a?new a(s.slice().buffer):s}case"inf":return 1/0;case"nan":return Number.NaN;case"undefined":return;default:return i.map(s=>C(s,e+1))}return i.map(n=>C(n,e+1))}const t=i,r={};for(const n of Object.keys(t)){const s=C(t[n],e+1);n===me?Object.defineProperty(r,n,{configurable:!0,enumerable:!0,value:s,writable:!0}):r[n]=s}return r},Us="pageDelta",Hs=(i,e,t,r)=>{const n=i.get(e);if(n!==void 0)return n;J(i,r);const s=t().catch(o=>{throw i.get(e)===s&&i.delete(e),o});return i.set(e,s),s},it=new TextEncoder,Fs=Array.from({length:32},(i,e)=>e);new RegExp(`[${Fs.map(i=>String.fromCodePoint(i)).join("")}]`,"u");const Ws=i=>{const e=i.replaceAll("-","+").replaceAll("_","/")+"===".slice((i.length+3)%4),t=atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;n+=1)r[n]=t.codePointAt(n)??0;return r},$s=64,Qs=new Map,Ks=async i=>Hs(Qs,i,async()=>crypto.subtle.importKey("raw",it.encode(i),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]),$s),js=async(i,e,t)=>{const r=await Ks(i);return crypto.subtle.verify("HMAC",r,t,it.encode(e))},Gs=new Set(["1","enabled","on","true","yes"]),zs=new Set(["0","disabled","false","no","off"]),Js=(i,e)=>{const t=(i??"").trim().toLowerCase();return Gs.has(t)?!0:zs.has(t)?!1:e},Xs="v1",Ys=async(i,e,t=Date.now())=>{if(i.length===0||e.length===0)return!1;const r=e.split(".");if(r.length!==3)return!1;const[n,s,o]=r;if(n!==Xs||o.length===0)return!1;const a=Number(s);if(!Number.isFinite(a)||a<=t)return!1;let c;try{c=Ws(o)}catch{return!1}return js(i,`${n}.${s}`,c)},ot="__lunoraBranch",Vs=i=>typeof i=="object"&&i!==null&&Object.hasOwn(i,ot),Zs=`may not contain the reserved workflow branch-marker key ("${ot}")`,en=/\(exit (\d+)\)/,tn=new Set(["contains","eq","gt","gte","lt","lte","ne"]),Ke=100,rn="test@lunora.sh",sn=new Set(["complete","errored","paused","queued","running","terminated","unknown","waiting","waitingForPause"]),at=null,je=(i,e)=>(i===void 0?"":`,"cursor":${String(i)}`)+(e===void 0?"":`,"epoch":${JSON.stringify(e)}`),nn=(i,e)=>{const[t,r]=i.size<=e.size?[i,e]:[e,i];for(const n of t)if(r.has(n))return!0;return!1},on=i=>{const e=typeof i.id=="string"?i.id:"";if(e.trim()==="")throw new p("MIGRATION_ID_REQUIRED","runMigration: `id` is required",{status:400});return{batchSize:typeof i.batchSize=="number"?i.batchSize:void 0,direction:i.direction==="down"?"down":"up",dryRun:i.dryRun===!0,id:e,maxBatches:typeof i.maxBatches=="number"?i.maxBatches:void 0}},an=i=>{const{op:e}=i,t=typeof i.table=="string"?i.table:"";if(e!=="insert"&&e!=="patch"&&e!=="replace"&&e!=="delete")throw new p("BAD_REQUEST","writeRow: `op` must be insert|patch|replace|delete");if(t.trim()==="")throw new p("BAD_REQUEST","writeRow: `table` is required");const r=typeof i.id=="string"?i.id:void 0,n=typeof i.doc=="object"&&i.doc!==null&&!Array.isArray(i.doc)?i.doc:void 0;if(e!=="insert"&&(r===void 0||r===""))throw new p("BAD_REQUEST",`writeRow: \`id\` is required for op "${e}"`);if(e!=="delete"&&n===void 0)throw new p("BAD_REQUEST",`writeRow: \`doc\` is required for op "${e}"`);return{doc:n,id:r,op:e,table:t}},cn=i=>typeof i=="string"&&mt.includes(i),dn=i=>typeof i=="string"&&yt.includes(i),ln=i=>{const e=typeof i.hash=="string"?i.hash.trim():"";if(e==="")throw new p("BAD_REQUEST","issue triage: `hash` is required");return e},un=i=>{const e=i.assignee;if(e===null)return at;if(typeof e=="string"&&e.trim()!=="")return e;throw new p("BAD_REQUEST","assignIssue: `assignee` must be a non-empty string (assign) or null (unassign)")},hn=i=>{const e=i.severity;if(e===null)return at;if(dn(e))return e;throw new p("BAD_REQUEST","setIssueSeverity: `severity` must be one of critical|high|medium|low, or null to clear")},pn=i=>{const e=typeof i.exportName=="string"?i.exportName.trim():"";if(e==="")throw new p("BAD_REQUEST","createWorkflowInstance: `exportName` is required");const t=typeof i.id=="string"&&i.id!==""?i.id:void 0;if(Vs(i.params))throw new p("BAD_REQUEST",`createWorkflowInstance: params ${Zs}`);return{exportName:e,id:t,params:i.params}},fn=i=>{const e=typeof i.exportName=="string"?i.exportName.trim():"",t=typeof i.id=="string"?i.id.trim():"";if(e==="")throw new p("BAD_REQUEST","getWorkflowInstanceStatus: `exportName` is required");if(t==="")throw new p("BAD_REQUEST","getWorkflowInstanceStatus: `id` is required");return{exportName:e,id:t}},Ge=i=>typeof i=="string"&&sn.has(i)?i:"unknown",mn=i=>{if(typeof i!="object"||i===null)return;const{message:e,name:t}=i;return{message:typeof e=="string"?e:"",name:typeof t=="string"?t:"Error"}},ye=i=>{if(!Array.isArray(i))return;const e=[];for(const t of i){if(typeof t!="object"||t===null)continue;const r=t,{column:n,operator:s}=r;typeof n!="string"||n===""||typeof s!="string"||!tn.has(s)||e.push({column:n,operator:s,value:r.value})}return e.length>0?e:void 0},yn=i=>{if(typeof i!="object"||i===null)return;const{column:e,direction:t}=i;if(!(typeof e!="string"||e===""))return{column:e,direction:t==="desc"?"desc":"asc"}},Sn=i=>{const e=typeof i.table=="string"?i.table:"";if(e.trim()==="")throw new p("BAD_REQUEST","deleteRows: `table` is required");return{filters:ye(i.filters),limit:typeof i.limit=="number"?i.limit:void 0,search:typeof i.search=="string"?i.search:void 0,table:e}},bn=i=>{const e=typeof i.table=="string"?i.table:"";if(e.trim()==="")throw new p("BAD_REQUEST","clearTable: `table` is required");return{limit:typeof i.limit=="number"?i.limit:void 0,table:e}},gn=i=>{const{outcome:e}=i;if(e!=="ok"&&e!=="fail")throw new p("BAD_REQUEST",'recordAuthEvent: `outcome` must be "ok" or "fail"');return{outcome:e}},Rn=i=>{const e=i.event;if(typeof e!="object"||e===null||Array.isArray(e))throw new p("BAD_REQUEST","recordContainerEvent: `event` must be an object");const t=e,r=typeof t.container=="string"?t.container:"",n=typeof t.event=="string"?t.event:"";if(r.trim()===""||n.trim()==="")throw new p("BAD_REQUEST","recordContainerEvent: `event.container` and `event.event` are required");const s=t.level==="error"?"error":"info",o=typeof t.message=="string"?t.message:void 0,a=typeof t.ts=="number"?t.ts:Date.now(),c=typeof t.instance=="string"&&t.instance!==""?t.instance:void 0,l=o===void 0?void 0:en.exec(o)?.[1];return{exitCode:l===void 0?void 0:Number.parseInt(l,10),functionPath:`container:${r}`,instance:c,level:s,message:o===void 0||o===""?n:`${n}: ${o}`,timestamp:a}},An=i=>{const e=typeof i.functionPath=="string"?i.functionPath:"",t=typeof i.userId=="string"?i.userId:"";if(e.trim()==="")throw new p("BAD_REQUEST","runAs: `functionPath` is required");if(e.startsWith(_))throw new p("BAD_REQUEST","runAs: cannot target a reserved admin function");if(t.trim()==="")throw new p("BAD_REQUEST","runAs: `userId` is required");const r=i.args;if(r!==void 0&&(typeof r!="object"||r===null||Array.isArray(r)))throw new p("BAD_REQUEST","runAs: `args` must be an object");const n=i.identity;if(n!==void 0&&(typeof n!="object"||n===null||Array.isArray(n)))throw new p("BAD_REQUEST","runAs: `identity` must be an object");return{args:r===void 0?{}:r,functionPath:e,userId:t,...n===void 0?{}:{identity:n}}},En=i=>{const e=m=>{throw new p("BAD_REQUEST",`recordMail: ${m}`)},{bcc:t,cc:r,from:n,headers:s,html:o,replyTo:a,subject:c,text:l,to:d}=i;typeof c!="string"&&e("`subject` must be a string"),typeof d=="string"||Array.isArray(d)&&d.every(m=>typeof m=="string")||e("`to` must be a string or string[]");const f=(m,y)=>{if(m!==void 0)return(!Array.isArray(m)||!m.every(R=>typeof R=="string"))&&e(`\`${y}\` must be a string[]`),m},S=(m,y)=>(m!==void 0&&typeof m!="string"&&e(`\`${y}\` must be a string`),m);return{bcc:f(t,"bcc"),cc:f(r,"cc"),from:S(n,"from"),headers:s!==void 0&&typeof s=="object"&&s!==null?s:void 0,html:S(o,"html"),replyTo:S(a,"replyTo"),subject:c,text:S(l,"text"),to:d}},vn=i=>{const{to:e}=i;if(e!==void 0&&typeof e!="string")throw new p("BAD_REQUEST","sendTestMail: `to` must be a string");const t=e??rn,r="https://example.test/verify?token=demo";return{from:"Lunora <noreply@lunora.sh>",html:`<p>This is a test email from the Lunora dev mail catcher.</p><p><a href="${r}">Verify your email</a></p>`,subject:"Lunora test email",text:`This is a test email from the Lunora dev mail catcher.
|
|
2
2
|
|
|
3
3
|
Verify your email: ${r}`,to:t}},wn=i=>{const e=n=>{throw new p("BAD_REQUEST",`recordQueueMessage: ${n}`)},t=i.messages;Array.isArray(t)||e("`messages` must be an array");const r=new Set(["ack","error","retry"]);return t.map((n,s)=>{(typeof n!="object"||n===null)&&e(`\`messages[${String(s)}]\` must be an object`);const o=n,a=typeof o.messageId=="string"?o.messageId:"",c=typeof o.queue=="string"?o.queue:"",l=typeof o.outcome=="string"?o.outcome:"";a===""&&e(`\`messages[${String(s)}].messageId\` is required`),c===""&&e(`\`messages[${String(s)}].queue\` is required`),r.has(l)||e(`\`messages[${String(s)}].outcome\` must be one of ack | error | retry`);const{attempts:d,timestamp:u}=o;return{attempts:typeof d=="number"&&Number.isFinite(d)?d:1,body:o.body,deadLettered:o.deadLettered===!0,error:typeof o.error=="string"?o.error:void 0,exportName:typeof o.exportName=="string"?o.exportName:void 0,messageId:a,outcome:l,queue:c,timestamp:typeof u=="number"&&Number.isFinite(u)?u:0}})},N=i=>`${i.traceId}:${i.rootSpanId}`,Tn=i=>{const e=typeof i.exportName=="string"?i.exportName.trim():"";if(e==="")throw new p("BAD_REQUEST","sendQueueMessage: `exportName` is required");const t=i.delaySeconds;if(t!==void 0&&(typeof t!="number"||!Number.isFinite(t)||t<0))throw new p("BAD_REQUEST","sendQueueMessage: `delaySeconds` must be a non-negative number");const r=Array.isArray(i.batch)?i.batch:void 0;if(r!==void 0&&(r.length===0||r.length>Ke))throw new p("BAD_REQUEST",`sendQueueMessage: \`batch\` must contain between 1 and ${String(Ke)} messages`);return{batch:r,body:i.body,contentType:typeof i.contentType=="string"?i.contentType:void 0,delaySeconds:t,exportName:e}},Cn=i=>{const e=typeof i.id=="string"?i.id.trim():"";if(e==="")throw new p("BAD_REQUEST","replayQueueMessage: `id` is required");const t=typeof i.target=="string"&&i.target.trim()!==""?i.target.trim():void 0;return{id:e,target:t}},In=i=>{const e=typeof i.table=="string"?i.table:"",t=typeof i.index=="string"?i.index:"",r=typeof i.rowId=="string"?i.rowId:"";if(e.trim()==="")throw new p("BAD_REQUEST","rankBefore: `table` is required");if(t.trim()==="")throw new p("BAD_REQUEST","rankBefore: `index` is required");if(typeof i.partitionKey!="string")throw new p("BAD_REQUEST","rankBefore: `partitionKey` must be a string");if(r.trim()==="")throw new p("BAD_REQUEST","rankBefore: `rowId` is required");if(!Array.isArray(i.sortValues))throw new p("BAD_REQUEST","rankBefore: `sortValues` must be an array");return{index:t,partitionKey:i.partitionKey,rowId:r,sortValues:i.sortValues,table:e}},L=i=>{throw new p("BAD_REQUEST",i)},ze=(i,e)=>((typeof i!="string"||i.trim()==="")&&L(`rankPage: \`${e}\` is required`),i),_n=i=>{if(i===void 0)return;(typeof i!="object"||i===null||Array.isArray(i))&&L("rankPage: `after` must be an object");const e=i;return(typeof e.partitionKey!="string"||typeof e.rowId!="string"||!Array.isArray(e.sortValues))&&L("rankPage: `after` must have a string partitionKey, string rowId, and array sortValues"),{partitionKey:e.partitionKey,rowId:e.rowId,sortValues:e.sortValues}},kn=i=>{const e=ze(i.table,"table"),t=ze(i.index,"index");i.take!==void 0&&typeof i.take!="number"&&L("rankPage: `take` must be a number"),i.cursor!==void 0&&i.cursor!==null&&typeof i.cursor!="string"&&L("rankPage: `cursor` must be a string or null"),i.partitionKey!==void 0&&typeof i.partitionKey!="string"&&L("rankPage: `partitionKey` must be a string"),i.directions!==void 0&&!Array.isArray(i.directions)&&L("rankPage: `directions` must be an array");const r=i.directions===void 0?void 0:i.directions.map(n=>n==="desc"?"desc":"asc");return{after:_n(i.after),cursor:typeof i.cursor=="string"?i.cursor:void 0,directions:r,index:t,partitionKey:typeof i.partitionKey=="string"?i.partitionKey:void 0,take:typeof i.take=="number"?i.take:void 0,table:e}},Mn=i=>{try{const e=JSON.parse(i);if(Array.isArray(e)&&typeof e[0]=="string"&&typeof e[1]=="string")return{index:e[1],table:e[0]}}catch{}},On=i=>{const e=i.changes;if(!Array.isArray(e))throw new p("BAD_REQUEST","applyCdc: `changes` must be an array");return{changes:e.map((r,n)=>{const s=r,{op:o}=s,a=typeof s.table=="string"?s.table:"",c=typeof s.id=="string"?s.id:"";if(a===""||c===""||o!=="insert"&&o!=="update"&&o!=="delete")throw new p("BAD_REQUEST",`applyCdc: changes[${String(n)}] must have a table, id, and op of insert|update|delete`);const l=s.doc;if(l!==void 0&&(typeof l!="object"||l===null||Array.isArray(l)))throw new p("BAD_REQUEST",`applyCdc: changes[${String(n)}].doc must be an object`);const d=l;if(d!==void 0&&typeof d._id=="string"&&d._id!==c)throw new p("BAD_REQUEST",`applyCdc: changes[${String(n)}].doc._id must match the entry id`);return{doc:d,id:c,op:o,seq:typeof s.seq=="number"?s.seq:0,table:a,ts:typeof s.ts=="number"?s.ts:0}})}},qn=i=>{const e=t=>{const r=typeof t=="number"?t:Number(t);return Number.isFinite(r)&&r>=0?Math.floor(r):void 0};return{limit:e(i.limit),sinceSeq:e(i.sinceSeq)??0}},x=i=>i?{"x-d1-bookmark":i}:void 0,Je=i=>Ns(i),Nn=i=>{if(!i)return;const e=Number(i);return Number.isInteger(e)&&e>0?e:void 0},xn=i=>{const e=new Set;for(const t of i){const r=rr(t);r!==""&&e.add(r)}return e},Pn=i=>{if(i===void 0)return;const e=Number.parseInt(i,10);return Number.isFinite(e)&&e>0?e:void 0},Dn=(i,e)=>i==="1"||i==="true"?!0:i==="0"||i==="false"?!1:e,Ln=i=>{if(i===void 0)return 1;const e=Number.parseFloat(i);return Number.isFinite(e)?Math.min(1,Math.max(0,e)):1},Bn=i=>i>=1?!0:i<=0?!1:Math.random()<i,le=i=>{if(!i)return;const[e,...t]=i.split(" ");if(e?.toLowerCase()!=="bearer")return;const r=t.join(" ").trim();return r.length>0?r:void 0},Un=["x-lunora-userid","x-lunora-identity","x-d1-bookmark","x-lunora-client-ip","x-lunora-system","x-lunora-shard-binding"],Hn=(i,e)=>{const t=new Headers({"content-type":"application/json"});for(const r of Un){const n=i.headers.get(r);n!==null&&t.set(r,n)}return e.mutationId!==void 0&&t.set("x-lunora-mutation-id",e.mutationId),e.clientId!==void 0&&t.set("x-lunora-client-id",e.clientId),e.clientSeq!==void 0&&t.set("x-lunora-client-seq",String(e.clientSeq)),new Request("https://shard.internal/rpc",{body:JSON.stringify({args:e.args??{},functionPath:e.functionPath}),headers:t,method:"POST"})},Y=i=>`"${i.replaceAll('"','""')}"`,Fn=500,Wn=8,$n=(i,e)=>{if(e.includes(i))return{expression:Y(i),params:[]};if(e.includes(Ce))return{expression:`json_extract(${Y(Ce)}, ?)`,params:[`$."${i.replaceAll('"','""')}"`]}},Qn=(i,e)=>{const t=[...new Set(e.ids.filter(s=>typeof s=="string"&&s!==""))].slice(0,Fn),r=e.relations.slice(0,Wn);if(t.length===0||r.length===0)return{relations:[]};const n=[];for(const s of r){let o;try{o=i.exec(`PRAGMA table_info(${Y(s.table)})`).toArray().map(d=>d.name)}catch{continue}if(o.length===0)continue;const a=$n(s.column,o);if(a===void 0)continue;const c=t.map(()=>"?").join(", "),l={};try{const d=i.exec(`SELECT ${a.expression} AS parent, COUNT(*) AS n
|
|
4
4
|
FROM ${Y(s.table)}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/do",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.101",
|
|
4
4
|
"description": "Lunora Durable Objects: ShardDO (SQLite, OCC, hibernated WebSocket subscriptions) and SessionDO",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cloudflare",
|
|
@@ -47,10 +47,10 @@
|
|
|
47
47
|
},
|
|
48
48
|
"dependencies": {
|
|
49
49
|
"@lunora/errors": "1.0.0-alpha.24",
|
|
50
|
-
"@lunora/observability": "1.0.0-alpha.
|
|
50
|
+
"@lunora/observability": "1.0.0-alpha.41",
|
|
51
51
|
"@lunora/platform": "1.0.0-alpha.18",
|
|
52
52
|
"@lunora/platform-cloudflare": "1.0.0-alpha.23",
|
|
53
|
-
"@lunora/shard-engine": "1.0.0-alpha.
|
|
53
|
+
"@lunora/shard-engine": "1.0.0-alpha.40",
|
|
54
54
|
"drizzle-orm": "^0.45.2"
|
|
55
55
|
},
|
|
56
56
|
"engines": {
|