@lunora/do 1.0.0-alpha.30 → 1.0.0-alpha.301

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/LICENSE.md +201 -104
  2. package/README.md +22 -3
  3. package/dist/index.d.mts +6761 -6179
  4. package/dist/index.d.ts +6761 -6179
  5. package/dist/index.mjs +1 -40
  6. package/dist/packem_chunks/ai-opt-in.mjs +1 -0
  7. package/dist/packem_chunks/sql-assistant.mjs +14 -0
  8. package/dist/packem_shared/ADMIN_REVOCATION_DO_NAME-D43bQNiT.mjs +1 -0
  9. package/dist/packem_shared/AdminRevocationDO-DHjoZWfF.mjs +1 -0
  10. package/dist/packem_shared/MERGED_ROLES-BAMAmIcW.mjs +1 -0
  11. package/dist/packem_shared/ROOT_DO_SIZE_WARN_BYTES-Dj8nZ80f.mjs +13 -0
  12. package/dist/packem_shared/SESSION_DO_TTL_DEFAULT-DSvTwRjc.mjs +1 -0
  13. package/dist/packem_shared/SHARD_REGISTRY_DO_NAME-Dbh8JQJQ.mjs +2 -0
  14. package/dist/packem_shared/admin-token-DrufJIZV.mjs +1 -0
  15. package/dist/packem_shared/constant-time-equal-BRh9yUCr.mjs +1 -0
  16. package/dist/packem_shared/createStableIdFactory-DPDT_chw.mjs +1 -0
  17. package/dist/packem_shared/installDeliveryFence-B6M9KOnb.mjs +1 -0
  18. package/dist/packem_shared/json-response-0Bq2ky0N.mjs +1 -0
  19. package/dist/packem_shared/read-body-text-capped-C6-sQo-i.mjs +1 -0
  20. package/dist/packem_shared/serveRelationFanout-Bms_fuoY.mjs +1 -0
  21. package/package.json +10 -6
  22. package/dist/packem_shared/ADMIN_FUNCTIONS-CAHLZMj8.mjs +0 -367
  23. package/dist/packem_shared/AGGREGATE_SQL_FUNCTION-CQsu2Xga.mjs +0 -56
  24. package/dist/packem_shared/AUTH_METRICS_BUCKETS_TABLE-CiHHYeJi.mjs +0 -84
  25. package/dist/packem_shared/CDC_LOG_TABLE-DjJEHiM2.mjs +0 -107
  26. package/dist/packem_shared/ConflictError-CLoq37xH.mjs +0 -12
  27. package/dist/packem_shared/CountRlsUnsupportedError-BGxj0pgS.mjs +0 -133
  28. package/dist/packem_shared/DATA_MIGRATION_STATE_TABLE-CYwBpyTr.mjs +0 -245
  29. package/dist/packem_shared/DEFAULT_MAX_RELATION_KEYS-BEan1CRD.mjs +0 -211
  30. package/dist/packem_shared/FUNCTION_METRICS_BUCKETS_TABLE-UDNVD7FS.mjs +0 -248
  31. package/dist/packem_shared/LogBuffer-B_Ezju_N.mjs +0 -37
  32. package/dist/packem_shared/MAIL_RETENTION-CPpgl-dX.mjs +0 -104
  33. package/dist/packem_shared/MAX_SQL_ROWS-D57CJaT9.mjs +0 -31
  34. package/dist/packem_shared/MIN_ADMIN_TOKEN_LENGTH-CCAvoFlr.mjs +0 -1
  35. package/dist/packem_shared/NotFoundError-C70b9hLw.mjs +0 -9
  36. package/dist/packem_shared/NotUniqueError-BigrdT_W.mjs +0 -1896
  37. package/dist/packem_shared/RANK_TIEBREAK-CXhdcA1o.mjs +0 -91
  38. package/dist/packem_shared/RLS_UNWRAP_SYMBOL-DTvHvRzY.mjs +0 -141
  39. package/dist/packem_shared/ROOT_DO_SIZE_WARN_BYTES-BA8QOChj.mjs +0 -6561
  40. package/dist/packem_shared/ReactiveCache-BYlSGY0N.mjs +0 -232
  41. package/dist/packem_shared/SCAN_DEP-DLJF8dsj.mjs +0 -19
  42. package/dist/packem_shared/SESSION_DO_TTL_DEFAULT-BnSKgVO4.mjs +0 -169
  43. package/dist/packem_shared/SHARD_REGISTRY_DO_NAME-D99roc-r.mjs +0 -144
  44. package/dist/packem_shared/aggregateTableName-CxNqY1Sl.mjs +0 -64
  45. package/dist/packem_shared/applyOnDelete-BXSq3S70.mjs +0 -176
  46. package/dist/packem_shared/applySelect-WQY8m62C.mjs +0 -103
  47. package/dist/packem_shared/armRestore-4Px61hHS.mjs +0 -49
  48. package/dist/packem_shared/backfillAggregateIndexes-DDoT-UUI.mjs +0 -81
  49. package/dist/packem_shared/buildFtsMatch-BLEMawrp.mjs +0 -38
  50. package/dist/packem_shared/compileWhereSql-DE6yfRcQ.mjs +0 -129
  51. package/dist/packem_shared/constant-time-equal-BVRWZgES.mjs +0 -12
  52. package/dist/packem_shared/createSystemReader-D12eNH13.mjs +0 -82
  53. package/dist/packem_shared/ctx-db-idempotency-BdcNpvY4.mjs +0 -108
  54. package/dist/packem_shared/ctx-db-shapes-Cz9dHyh1.mjs +0 -53
  55. package/dist/packem_shared/diffExternalSource-Cx9HUPJj.mjs +0 -44
  56. package/dist/packem_shared/do-exec-5eQy5cEi.mjs +0 -12
  57. package/dist/packem_shared/do-sql-BCHCWtrD.mjs +0 -87
  58. package/dist/packem_shared/exportShardRows-Dy3oFZ26.mjs +0 -157
  59. package/dist/packem_shared/hasTrigger-5N6_Fx0A.mjs +0 -20
  60. package/dist/packem_shared/isSourceDue-CYkt7Ru8.mjs +0 -41
  61. package/dist/packem_shared/json-response-BdbtpOhm.mjs +0 -3
  62. package/dist/packem_shared/materializeExternalRows-CTqZisSC.mjs +0 -23
  63. package/dist/packem_shared/renderSql-D6eUcn2N.mjs +0 -16
  64. package/dist/packem_shared/runShardMigrations-BGx4v2B6.mjs +0 -105
  65. package/dist/packem_shared/security-audit-CucgBice.mjs +0 -158
  66. package/dist/packem_shared/serialize-sql-BlRUoiQe.mjs +0 -14
  67. package/dist/packem_shared/serveRelationFanout-BgaNg3Hu.mjs +0 -21
  68. package/dist/packem_shared/stableStringify-MydiuScU.mjs +0 -40
  69. package/dist/packem_shared/subscription-delivery-CWigSEr3.mjs +0 -348
  70. package/dist/packem_shared/subscriptionListDeltas-DRLvFlM1.mjs +0 -1
@@ -0,0 +1 @@
1
+ import{createShardKvStore as h,createShardAlarms as u}from"@lunora/platform-cloudflare";import{c as f}from"./constant-time-equal-BRh9yUCr.mjs";import{j as n}from"./json-response-0Bq2ky0N.mjs";const m=10080*60,S=2160*60*60,d=1440*60*1e3,E="x-lunora-session-do-secret",l="x-lunora-session-token",_=/^[\w-]+$/,g=32,N=256,T=256,v=(s,e)=>{const t=e.SESSION_DO_SECRET;if(typeof t!="string"||t.length===0)return!1;const r=s.headers.get(E);return typeof r!="string"||r.length===0?!1:f(t,r)},p=s=>{let e;if(s==null)e=m;else if(typeof s=="number")e=s;else return;if(!(!Number.isFinite(e)||!Number.isInteger(e)||e<=0||e>S))return e},k=s=>{if(typeof s=="string"&&!(s.length<g||s.length>N)&&_.test(s))return s};class A{state;env;kv;alarms;constructor(e,t){this.state=e,this.env=t,this.kv=h(e.storage),this.alarms=u(e.storage)}async fetch(e){const t=this.env??{};if(!v(e,t))return n({error:{code:"UNAUTHORIZED",message:"missing or invalid SessionDO secret"}},401);const r=new URL(e.url);return e.method==="POST"&&r.pathname==="/create"?this.handleCreate(e):e.method==="GET"&&r.pathname==="/get"?this.handleGet(e):e.method==="DELETE"&&r.pathname==="/revoke"?this.handleRevoke(e):n({error:{code:"NOT_FOUND",message:"no such session route"}},404)}async alarm(){if(typeof this.state.storage.list!="function")return;const e=Date.now(),t=await this.kv.list({prefix:"s:"}),r=[];let o=0;for(const[i,a]of t)a.expiresAt<e?r.push(i):o+=1;for(const i of r)await this.kv.delete(i);o>0&&await this.alarms.set(e+d)}async handleCreate(e){let t;try{t=await e.json()}catch{return n({error:"invalid_request"},400)}const r=k(t.token);if(r===void 0)return n({error:"invalid_request"},400);const{userId:o}=t;if(typeof o!="string"||o.length===0||o.length>T)return n({error:"invalid_request"},400);const i=p(t.ttlSeconds);if(i===void 0)return n({error:"invalid_request"},400);const a=Date.now(),c={createdAt:a,expiresAt:a+i*1e3,userId:o};return await this.kv.put(`s:${r}`,c),await this.armGcAlarm(),n({token:r,...c},201)}async armGcAlarm(){await this.alarms.get()===null&&await this.alarms.set(Date.now()+d)}async handleGet(e){const t=e.headers.get(l);if(!t)return n({error:{code:"INVALID_INPUT",message:"token required"}},400);const r=await this.kv.get(`s:${t}`);return r?r.expiresAt<Date.now()?(await this.kv.delete(`s:${t}`),n({error:{code:"EXPIRED",message:"session expired"}},404)):n({token:t,...r},200):n({error:{code:"NOT_FOUND",message:"session not found"}},404)}async handleRevoke(e){const t=e.headers.get(l);return t?(await this.kv.delete(`s:${t}`),n({ok:!0},200)):n({error:{code:"INVALID_INPUT",message:"token required"}},400)}}export{m as SESSION_DO_TTL_DEFAULT,A as SessionDO};
@@ -0,0 +1,2 @@
1
+ import{siblingSecretOf as b,RELAY_SIGNATURE_HEADER as i,verifySiblingBody as S,stubByName as w,signSiblingBody as p}from"@lunora/shard-engine";import{j as o}from"./json-response-0Bq2ky0N.mjs";import{r as T}from"./read-body-text-capped-C6-sQo-i.mjs";const c=(a,e,t)=>{const{pathname:r,search:s}=new URL(e);return`${a.toUpperCase()} ${r}${s}
2
+ ${t}`},E=5e3,u=64*1024,_="__lunora_shard_registry__",R="s:",O="\0",y=2048,h=(a,e)=>`${R}${a}${O}${e}`,g=a=>{let e;try{const s=JSON.parse(a);if(s===null||typeof s!="object")throw new TypeError("not an object");e=s}catch{return{kind:"error",response:o({error:{code:"BAD_REQUEST",message:"invalid JSON body"}},400)}}const t=typeof e.table=="string"?e.table.trim():"",r=typeof e.shardKey=="string"?e.shardKey.trim():"";return!t||!r?{kind:"error",response:o({error:{code:"BAD_REQUEST",message:"table and shardKey required"}},400)}:new TextEncoder().encode(h(t,r)).length>y?{kind:"error",response:o({error:{code:"BAD_REQUEST",message:`table and shardKey exceed the ${String(y)}-byte storage key limit`}},400)}:{kind:"ok",value:{shardKey:r,table:t}}};class N{env;state;tables=new Map;loaded=!1;constructor(e,t){this.state=e,this.env=t}async fetch(e){const t=this.refuseUnsigned(e);if(t)return t;const r=await T(e,u);if(r===null)return o({error:{code:"PAYLOAD_TOO_LARGE",message:`shard registry requests are capped at ${String(u)} bytes`}},413);const s=await this.refuseBadSignature(e,r);if(s)return s;await this.ensureLoaded();const n=new URL(e.url);return e.method==="POST"&&n.pathname==="/register"?this.handleRegister(r):e.method==="POST"&&n.pathname==="/unregister"?this.handleUnregister(r):e.method==="GET"&&n.pathname==="/list"?this.handleList(n):e.method==="GET"&&n.pathname==="/snapshot"?this.handleSnapshot():o({error:{code:"NOT_FOUND",message:`unknown shard-registry route ${e.method} ${n.pathname}`}},404)}refuseUnsigned(e){if(b(this.env)===void 0)return o({error:{code:"FORBIDDEN",message:"the shard registry requires LUNORA_RELAY_SECRET to be set on the Durable Object's environment"}},403);if(!e.headers.has(i))return o({error:{code:"FORBIDDEN",message:"missing or invalid shard registry signature"}},403)}async refuseBadSignature(e,t){const r=c(e.method,e.url,t);if(!await S(this.env,e.headers.get(i),r))return o({error:{code:"FORBIDDEN",message:"missing or invalid shard registry signature"}},403)}async ensureLoaded(){this.loaded||await this.state.blockConcurrencyWhile(async()=>{if(this.loaded)return;const e=await this.state.storage.list({prefix:R});for(const t of e.values()){let r=this.tables.get(t.table);r||(r=new Set,this.tables.set(t.table,r)),r.add(t.shardKey)}this.loaded=!0})}handleList(e){const t=e.searchParams.get("table");return t?o({shardKeys:[...this.tables.get(t)??[]]},200):o({error:{code:"BAD_REQUEST",message:"missing required query parameter: table"}},400)}async handleRegister(e){const t=g(e);if(t.kind==="error")return t.response;const{shardKey:r,table:s}=t.value;return this.state.blockConcurrencyWhile(async()=>{let n=this.tables.get(s);return n?.has(r)?o({changed:!1,ok:!0},200):(await this.state.storage.put(h(s,r),{shardKey:r,table:s}),n||(n=new Set,this.tables.set(s,n)),n.add(r),o({changed:!0,ok:!0},200))})}handleSnapshot(){return o({tables:this.serializeTables()},200)}async handleUnregister(e){const t=g(e);if(t.kind==="error")return t.response;const{shardKey:r,table:s}=t.value;return this.state.blockConcurrencyWhile(async()=>{const n=this.tables.get(s);return n?.has(r)?(await this.state.storage.delete(h(s,r)),n.delete(r),n.size===0&&this.tables.delete(s),o({changed:!0,ok:!0},200)):o({changed:!1,ok:!0},200)})}serializeTables(){return Object.fromEntries([...this.tables].map(([e,t])=>[e,[...t]]))}}const m=async(a,e,t,r,s)=>{if(s===void 0)throw new Error("the shard registry requires LUNORA_RELAY_SECRET; set it on the worker and every Durable Object");const n=`https://shard-registry.internal${e}`,l=JSON.stringify({shardKey:r,table:t}),d=await a.fetch(n,{body:l,headers:{"content-type":"application/json",[i]:await p(s,c("POST",n,l))},method:"POST",signal:AbortSignal.timeout(E)});if(!d.ok)throw new Error(`shard registry ${e} returned ${String(d.status)}: ${await d.text()}`)},A=async(a,e,t,r)=>m(a,"/register",e,t,r),D=async(a,e,t,r)=>m(a,"/unregister",e,t,r),f=async(a,e,t)=>{if(t===void 0)throw new Error("the shard registry requires LUNORA_RELAY_SECRET; set it on the worker and every Durable Object");const r=`https://shard-registry.internal${e}`,s=await a.fetch(r,{headers:{[i]:await p(t,c("GET",r,""))},method:"GET",signal:AbortSignal.timeout(E)});if(!s.ok)throw new Error(`shard registry ${e.split("?")[0]??e} returned ${String(s.status)}: ${await s.text()}`);return await s.json()},k=a=>{const e=a;return typeof e?.register=="function"&&typeof e.unregister=="function"},B=a=>!k(a)&&typeof a=="object"&&a!==null&&"idFromName"in a&&typeof a.idFromName=="function",K=(a,e)=>{const t=()=>{const s=typeof a=="object"&&a!==null&&"SHARD_REGISTRY"in a?a.SHARD_REGISTRY:void 0,n=w(s,_,e);if(n===void 0)throw new Error("the shard registry entrypoint needs this worker's Durable Object namespace bound as SHARD_REGISTRY");return n},r=()=>b(a);return{listShardKeys:async s=>(await f(t(),`/list?table=${encodeURIComponent(s)}`,r())).shardKeys,register:async(s,n)=>A(t(),s,n,r()),snapshot:async()=>(await f(t(),"/snapshot",r())).tables,unregister:async(s,n)=>D(t(),s,n,r())}};export{_ as SHARD_REGISTRY_DO_NAME,N as ShardRegistryDO,K as hostedShardRegistry,B as isRegistryNamespace,k as isRegistryRpc,A as registerShardKey,D as unregisterShardKey};
@@ -0,0 +1 @@
1
+ const E=t=>{const n=atob(t),e=new Uint8Array(n.length);for(let r=0;r<n.length;r+=1)e[r]=n.codePointAt(r)??0;return e},a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",l=t=>{let n="",e=0;const r=t.length-2;for(;e<r;e+=3){const s=t[e]<<16|t[e+1]<<8|t[e+2];n+=a.charAt(s>>18&63)+a.charAt(s>>12&63)+a.charAt(s>>6&63)+a.charAt(s&63)}const o=t.length-e;if(o===1){const s=t[e]<<16;n+=a.charAt(s>>18&63)+a.charAt(s>>12&63)}else if(o===2){const s=t[e]<<16|t[e+1]<<8;n+=a.charAt(s>>18&63)+a.charAt(s>>12&63)+a.charAt(s>>6&63)}return n},N=t=>{const n=t.replaceAll("-","+").replaceAll("_","/"),e=n+"=".repeat((4-n.length%4)%4);return E(e)},p=(t,n)=>{if(t.size<n)return;const e=t.keys().next().value;e!==void 0&&t.delete(e)},y=(t,n,e,r)=>{const o=t.get(n);if(o!==void 0)return o;p(t,r);const s=e().catch(c=>{throw t.get(n)===s&&t.delete(n),c});return t.set(n,s),s},f=new TextEncoder,S=64,v=new Map,u=async t=>y(v,t,async()=>crypto.subtle.importKey("raw",f.encode(t),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]),S),_=new TextEncoder,I=Array.from({length:32},(t,n)=>n);new RegExp(`[${I.map(t=>String.fromCodePoint(t)).join("")}]`,"u");const M=async(t,n)=>{const e=await u(t),r=await crypto.subtle.sign("HMAC",e,_.encode(n));return l(new Uint8Array(r))},T=async(t,n,e)=>{const r=await u(t);return crypto.subtle.verify("HMAC",r,e,_.encode(n))},g="lnat",D="__lunora_admin_revocations__",w=/^[a-z0-9][a-z0-9_-]{0,63}$/u,$=/^[\w-]{43}$/u,O="x-lunora-admin-signal",h="as1",x=6e4,R=5e3,m=t=>w.test(t),C=t=>{const n=t.split(".");if(n.length!==3||n[0]!==g)return;const[,e,r]=n;return m(e)&&$.test(r)?{name:e,secret:r}:void 0},H=t=>{const n=t?/^bearer\s+(\S+)\s*$/iu.exec(t):void 0;return n?.[1]===void 0?void 0:C(n[1])},L=t=>{const n=l(crypto.getRandomValues(new Uint8Array(32)));return{secret:n,token:`${g}.${t}.${n}`}},K=async t=>[...new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t)))].map(e=>e.toString(16).padStart(2,"0")).join(""),U=async(t,n,e=Date.now(),r=Number.POSITIVE_INFINITY)=>{const o=`${h}.${String(Math.floor(Math.min(e+x,r)))}.${n}`;return`${o}.${await M(t,o)}`},B=async(t,n,e=Date.now())=>{if(t.length===0)return;const r=n.split(".");if(r.length!==4)return;const[o,s,c,i]=r,d=Number(s);if(o!==h||!m(c)||!Number.isFinite(d)||d<=e||i.length===0)return;let A;try{A=N(i)}catch{return}return await T(t,`${o}.${s}.${c}`,A)?c:void 0};export{D as A,O as a,B as b,R as c,x as d,p as e,N as f,K as g,L as h,m as i,H as j,U as m,C as p,M as s,l as t,T as v};
@@ -0,0 +1 @@
1
+ const r=(e,n)=>{const c=Math.max(e.length,n.length);let h=e.length^n.length;for(let t=0;t<c;t+=1){const l=t<e.length?e.charCodeAt(t):0,o=t<n.length?n.charCodeAt(t):0;h|=l^o}return h===0};export{r as c};
@@ -0,0 +1 @@
1
+ import{cyrb53 as n}from"@lunora/values";const s=[0,2654435769,2246822507,3266489909],a=e=>{const r=s.map(c=>(n(e,c)%4294967296).toString(16).padStart(8,"0")).join(""),t=`8${r.slice(13,16)}`,o=`${(Number.parseInt(r[16]??"0",16)&3|8).toString(16)}${r.slice(17,20)}`;return`${r.slice(0,8)}-${r.slice(8,12)}-${t}-${o}-${r.slice(20,32)}`},l=(e,r)=>{if(e===void 0||e.length===0)return()=>crypto.randomUUID();let t=0;return()=>(t+=1,a(`${r}\0${e}\0${t.toString()}`))},S=(e,r)=>{if(e===void 0||e.length===0)return()=>Math.random();let t=0;return()=>(t+=1,n(`random\0${r}\0${e}\0${t.toString()}`)/2**53)};export{l as createStableIdFactory,S as createStableRandomFactory};
@@ -0,0 +1 @@
1
+ import{LunoraError as s}from"@lunora/errors";import{siblingSecretOf as n,RELAY_SIGNATURE_HEADER as E,signSiblingBody as a}from"@lunora/shard-engine";const c=r=>{if(typeof r!="object"||r===null)return!1;const e=r;return typeof e.scope=="string"&&e.scope.length>0&&new TextEncoder().encode(e.scope).byteLength<=256&&Number.isSafeInteger(e.epoch)&&(e.epoch??-1)>=0};class h{constructor(e){this.sql=e}sql;initialized=!1;install(e){if(!c(e))throw new TypeError("invalid delivery fence");this.storage().exec("INSERT INTO __lunora_delivery_fence(scope, epoch) VALUES (?, ?) ON CONFLICT(scope) DO UPDATE SET epoch = MAX(epoch, excluded.epoch)",e.scope,e.epoch)}recordReceipt(e,o,t,i){if(!c(t))throw new s("DELIVERY_RECEIPT_FENCED","Receipt has no delivery authority");this.storage().exec("INSERT INTO __lunora_delivery_receipt(identity, mutation_id, scope, epoch, ts) VALUES (?, ?, ?, ?, ?) ON CONFLICT(identity, mutation_id) DO UPDATE SET scope = excluded.scope, epoch = excluded.epoch, ts = excluded.ts",e,o,t.scope,t.epoch,i)}assertReceipt(e,o,t){const i=this.storage().exec("SELECT scope, epoch FROM __lunora_delivery_receipt WHERE identity = ? AND mutation_id = ?",e,o).toArray()[0];if(!c(t)||i?.scope!==t.scope||i.epoch!==t.epoch)throw new s("DELIVERY_RECEIPT_FENCED","Committed receipt belongs to a different delivery authority epoch")}trimReceipts(e){this.storage().exec("DELETE FROM __lunora_delivery_receipt WHERE ts < ?",e)}allows(e){if(!c(e))return!1;const o=this.storage().exec("SELECT epoch FROM __lunora_delivery_fence WHERE scope = ?",e.scope).toArray()[0];return o===void 0||e.epoch>=o.epoch}storage(){const e=this.sql();return this.initialized||(e.exec("CREATE TABLE IF NOT EXISTS __lunora_delivery_fence (scope TEXT PRIMARY KEY, epoch INTEGER NOT NULL)"),e.exec("CREATE TABLE IF NOT EXISTS __lunora_delivery_receipt (identity TEXT NOT NULL, mutation_id TEXT NOT NULL, scope TEXT NOT NULL, epoch INTEGER NOT NULL, ts REAL NOT NULL, PRIMARY KEY (identity, mutation_id))"),this.initialized=!0),e}}const p=async(r,e)=>{const o=n(e.env);if(o===void 0||!c(e.fence))throw new TypeError("delivery fence requires a valid marker and LUNORA_RELAY_SECRET");const t=JSON.stringify({type:"delivery-fence",shardKey:e.shardKey,fence:e.fence}),i=await r.fetch("https://shard.internal/_lunora/delivery-fence",{method:"POST",body:t,headers:{[E]:await a(o,t)}});if(i.status!==204)throw new Error(`delivery fence was not acknowledged (${String(i.status)})`)};export{h as DeliveryFence,p as installDeliveryFence,c as validDeliveryPermit};
@@ -0,0 +1 @@
1
+ const a=(n,s=200,o)=>{const e=new Headers({"content-type":"application/json"});for(const[t,r]of Object.entries(o??{}))e.set(t,r);return Response.json(n,{headers:e,status:s})};export{a as j};
@@ -0,0 +1 @@
1
+ const l=async(r,c)=>{if(!r.body)return"";const a=r.body.getReader(),d=new TextDecoder;let o=0,e="";for(;;){const{done:n,value:t}=await a.read();if(n)break;if(t){if(o+=t.byteLength,o>c)return await a.cancel().catch(()=>{}),null;e+=d.decode(t,{stream:!0})}}return e+=d.decode(),e};export{l as r};
@@ -0,0 +1 @@
1
+ import{LunoraError as l}from"@lunora/errors";import{RELATION_FUNCTION_PREFIX as n}from"@lunora/shard-engine";const E=async(s,e,c,o)=>{const t=typeof o.table=="string"?o.table:"",r=s.tables[t];if(!r)throw new l("UNKNOWN_TABLE",`${n} unknown table "${t}"`,{status:404});if(r.shardMode?.kind==="global")throw new l("BAD_REQUEST",`${n} table "${t}" is global, not shard-local`);const{orderBy:u,relationPolicies:w={},where:i,with:h}=o,a=f=>w[f];return c===`${n}count`?e.count(t,{relationBaseWhere:a,where:i}):(await e.findMany(t,{orderBy:u,relationBaseWhere:a,where:i,with:h})).page};export{E as serveRelationFanout};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/do",
3
- "version": "1.0.0-alpha.30",
3
+ "version": "1.0.0-alpha.301",
4
4
  "description": "Lunora Durable Objects: ShardDO (SQLite, OCC, hibernated WebSocket subscriptions) and SessionDO",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -14,7 +14,7 @@
14
14
  ],
15
15
  "homepage": "https://lunora.sh",
16
16
  "bugs": "https://github.com/anolilab/lunora/issues",
17
- "license": "FSL-1.1-Apache-2.0",
17
+ "license": "Apache-2.0",
18
18
  "author": {
19
19
  "name": "Daniel Bannert",
20
20
  "email": "d.bannert@anolilab.de"
@@ -46,10 +46,14 @@
46
46
  "access": "public"
47
47
  },
48
48
  "dependencies": {
49
- "@lunora/errors": "1.0.0-alpha.4",
50
- "@lunora/fingerprint": "1.0.0-alpha.1",
51
- "@visulima/redact": "3.0.0",
52
- "drizzle-orm": "^0.45.2"
49
+ "@lunora/errors": ">=1.0.0-alpha.51 <2.0.0-0",
50
+ "@lunora/observability": "^1.0.0-alpha.207",
51
+ "@lunora/platform": "^1.0.0-alpha.83",
52
+ "@lunora/platform-cloudflare": "^1.0.0-alpha.125",
53
+ "@lunora/shard-engine": "^1.0.0-alpha.212",
54
+ "@lunora/values": "^1.0.0-alpha.95",
55
+ "@lunora/wire": "1.0.0-alpha.6",
56
+ "drizzle-orm": "1.0.0-rc.5"
53
57
  },
54
58
  "engines": {
55
59
  "node": "^22.15.0 || >=24.11.0"
@@ -1,367 +0,0 @@
1
- import { LunoraError } from '@lunora/errors';
2
-
3
- const quoteIdentifier = (name) => `"${name.replaceAll('"', '""')}"`;
4
-
5
- const ADMIN_FUNCTION_PREFIX = "__lunora_admin__:";
6
- const RELATION_FUNCTION_PREFIX = "__lunora_relation__:";
7
- const FLAGS_FUNCTION_PREFIX = "__lunora_flags__:";
8
- const ADMIN_FUNCTIONS = {
9
- applyCdc: "__lunora_admin__:applyCdc",
10
- cdcSync: "__lunora_admin__:cdcSync",
11
- clearCapturedMail: "__lunora_admin__:clearCapturedMail",
12
- clearQueueMessages: "__lunora_admin__:clearQueueMessages",
13
- clearTable: "__lunora_admin__:clearTable",
14
- createWorkflowInstance: "__lunora_admin__:createWorkflowInstance",
15
- deleteRows: "__lunora_admin__:deleteRows",
16
- describeTable: "__lunora_admin__:describeTable",
17
- describeTables: "__lunora_admin__:describeTables",
18
- exportShard: "__lunora_admin__:exportShard",
19
- facetColumn: "__lunora_admin__:facetColumn",
20
- getAdvisories: "__lunora_admin__:getAdvisories",
21
- getAuditLog: "__lunora_admin__:getAuditLog",
22
- getAuthMetrics: "__lunora_admin__:getAuthMetrics",
23
- getCapturedMail: "__lunora_admin__:getCapturedMail",
24
- getFanoutMetrics: "__lunora_admin__:getFanoutMetrics",
25
- getFunctionStats: "__lunora_admin__:getFunctionStats",
26
- getIssues: "__lunora_admin__:getIssues",
27
- listSubscriptions: "__lunora_admin__:listSubscriptions",
28
- listTableIndexes: "__lunora_admin__:listTableIndexes",
29
- getLogs: "__lunora_admin__:getLogs",
30
- getMetrics: "__lunora_admin__:getMetrics",
31
- getPitrBookmark: "__lunora_admin__:getPitrBookmark",
32
- getQueueMessages: "__lunora_admin__:getQueueMessages",
33
- getRequestLog: "__lunora_admin__:getRequestLog",
34
- getSecurityAudit: "__lunora_admin__:getSecurityAudit",
35
- getSettings: "__lunora_admin__:getSettings",
36
- // eslint-disable-next-line no-secrets/no-secrets -- reserved admin RPC path constant, not a credential
37
- getWorkflowInstanceStatus: "__lunora_admin__:getWorkflowInstanceStatus",
38
- importShard: "__lunora_admin__:importShard",
39
- listFlags: "__lunora_admin__:listFlags",
40
- listQueues: "__lunora_admin__:listQueues",
41
- listTables: "__lunora_admin__:listTables",
42
- listWorkflows: "__lunora_admin__:listWorkflows",
43
- maskPolicies: "__lunora_admin__:maskPolicies",
44
- migrationStatus: "__lunora_admin__:migrationStatus",
45
- pitrRestore: "__lunora_admin__:pitrRestore",
46
- rankBefore: "__lunora_admin__:rankBefore",
47
- rankPage: "__lunora_admin__:rankPage",
48
- readTablePage: "__lunora_admin__:readTablePage",
49
- recordAuthEvent: "__lunora_admin__:recordAuthEvent",
50
- recordContainerEvent: "__lunora_admin__:recordContainerEvent",
51
- recordMail: "__lunora_admin__:recordMail",
52
- recordQueueMessage: "__lunora_admin__:recordQueueMessage",
53
- replayQueueMessage: "__lunora_admin__:replayQueueMessage",
54
- rlsPolicies: "__lunora_admin__:rlsPolicies",
55
- runAs: "__lunora_admin__:runAs",
56
- runMigration: "__lunora_admin__:runMigration",
57
- runSql: "__lunora_admin__:runSql",
58
- sendQueueMessage: "__lunora_admin__:sendQueueMessage",
59
- sendTestMail: "__lunora_admin__:sendTestMail",
60
- storageOrphans: "__lunora_admin__:storageOrphans",
61
- storageReferences: "__lunora_admin__:storageReferences",
62
- storageRules: "__lunora_admin__:storageRules",
63
- studioFeatures: "__lunora_admin__:studioFeatures",
64
- writeRow: "__lunora_admin__:writeRow"
65
- };
66
- const DEFAULT_PAGE_SIZE = 50;
67
- const MAX_PAGE_SIZE = 500;
68
- const DEFAULT_FACET_LIMIT = 30;
69
- const MAX_FACET_LIMIT = 200;
70
- const DOC_COLUMN = "__doc__";
71
- const safeParseObject = (text) => {
72
- try {
73
- const value = JSON.parse(text);
74
- return value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
75
- } catch {
76
- return void 0;
77
- }
78
- };
79
- const expandDocumentRows = (columns, rows) => {
80
- if (!columns.includes(DOC_COLUMN)) {
81
- return { columns, rows };
82
- }
83
- const parsed = [];
84
- for (const row of rows) {
85
- const raw = row[DOC_COLUMN];
86
- const documentData = typeof raw === "string" ? safeParseObject(raw) : void 0;
87
- if (documentData === void 0) {
88
- return { columns, rows };
89
- }
90
- const meta = Object.fromEntries(Object.entries(row).filter(([column]) => column !== DOC_COLUMN));
91
- parsed.push({ ...meta, ...documentData });
92
- }
93
- const metaColumns = columns.filter((name) => name !== DOC_COLUMN);
94
- const documentKeys = [];
95
- const seen = new Set(metaColumns);
96
- for (const documentData of parsed) {
97
- for (const key of Object.keys(documentData)) {
98
- if (!seen.has(key)) {
99
- seen.add(key);
100
- documentKeys.push(key);
101
- }
102
- }
103
- }
104
- return { columns: [...metaColumns, ...documentKeys], rows: parsed };
105
- };
106
- const escapeLike = (value) => value.replaceAll(/[\\%_]/g, (character) => `\\${character}`);
107
- const isInternalTable = (name) => name.startsWith("sqlite_") || name.startsWith("_cf_") || name.startsWith("__miniflare") || name.startsWith("__lunora") || name.includes("__fts_");
108
- const clamp = (value, min, max) => Math.min(Math.max(value, min), max);
109
- const countRows = (sql, quotedTable) => {
110
- const row = sql.exec(`SELECT COUNT(*) AS c FROM ${quotedTable}`).one();
111
- return Number(row.c);
112
- };
113
- const listTables = (sql) => {
114
- const names = sql.exec("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name").toArray();
115
- const tables = [];
116
- for (const { name } of names) {
117
- if (isInternalTable(name)) {
118
- continue;
119
- }
120
- tables.push({ name, rowCount: countRows(sql, quoteIdentifier(name)) });
121
- }
122
- return tables;
123
- };
124
- const tableExists = (sql, table) => sql.exec("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ? LIMIT 1", table).toArray().length > 0;
125
- const FILTER_SQL_OPERATOR = { eq: "=", gt: ">", gte: ">=", lt: "<", lte: "<=", ne: "<>" };
126
- const filterValueText = (value) => {
127
- if (typeof value === "string") {
128
- return value;
129
- }
130
- return typeof value === "number" || typeof value === "boolean" ? String(value) : "";
131
- };
132
- const resolveColumnExpression = (column, physicalColumns) => {
133
- const isPhysical = physicalColumns.includes(column);
134
- const isDocumentStored = physicalColumns.includes(DOC_COLUMN);
135
- if (!isPhysical && !isDocumentStored) {
136
- return void 0;
137
- }
138
- return isPhysical ? { expression: quoteIdentifier(column), params: [] } : { expression: `json_extract(${quoteIdentifier(DOC_COLUMN)}, ?)`, params: [`$."${column.replaceAll('"', '""')}"`] };
139
- };
140
- const buildFilterClause = (clause, physicalColumns) => {
141
- const resolved = resolveColumnExpression(clause.column, physicalColumns);
142
- if (resolved === void 0) {
143
- return void 0;
144
- }
145
- const { expression, params: pathParameters } = resolved;
146
- if (clause.operator === "contains") {
147
- return {
148
- params: [...pathParameters, `%${escapeLike(filterValueText(clause.value))}%`],
149
- sql: String.raw`CAST(${expression} AS TEXT) LIKE ? ESCAPE '\'`
150
- };
151
- }
152
- return { params: [...pathParameters, clause.value], sql: `${expression} ${FILTER_SQL_OPERATOR[clause.operator]} ?` };
153
- };
154
- const buildTablePredicate = (columns, needle, filters) => {
155
- const conjuncts = [];
156
- const parameters = [];
157
- if (needle !== "" && columns.length > 0) {
158
- const pattern = `%${escapeLike(needle)}%`;
159
- conjuncts.push(`(${columns.map((name) => String.raw`CAST(${quoteIdentifier(name)} AS TEXT) LIKE ? ESCAPE '\'`).join(" OR ")})`);
160
- parameters.push(...columns.map(() => pattern));
161
- }
162
- for (const clause of filters ?? []) {
163
- const built = buildFilterClause(clause, columns);
164
- if (built !== void 0) {
165
- conjuncts.push(`(${built.sql})`);
166
- parameters.push(...built.params);
167
- }
168
- }
169
- return conjuncts.length === 0 ? void 0 : { parameters, where: conjuncts.join(" AND ") };
170
- };
171
- const buildOrderBy = (orderBy, physicalColumns) => {
172
- if (orderBy === void 0) {
173
- return void 0;
174
- }
175
- const resolved = resolveColumnExpression(orderBy.column, physicalColumns);
176
- if (resolved === void 0) {
177
- return void 0;
178
- }
179
- const keyword = orderBy.direction === "desc" ? "DESC" : "ASC";
180
- return { params: resolved.params, sql: `${resolved.expression} ${keyword}` };
181
- };
182
- const readTablePage = (sql, options) => {
183
- const { table } = options;
184
- if (isInternalTable(table) || !tableExists(sql, table)) {
185
- throw new LunoraError("UNKNOWN_TABLE", `unknown table: ${table}`, { status: 404 });
186
- }
187
- const limit = clamp(Math.trunc(options.limit ?? DEFAULT_PAGE_SIZE), 1, MAX_PAGE_SIZE);
188
- const offset = Math.max(0, Math.trunc(options.offset ?? 0));
189
- const quoted = quoteIdentifier(table);
190
- const columns = sql.exec(`PRAGMA table_info(${quoted})`).toArray().map((column) => column.name);
191
- const needle = options.search?.trim() ?? "";
192
- const withReferences = (page) => {
193
- if (options.refs === void 0) {
194
- return page;
195
- }
196
- const references = {};
197
- for (const column of page.columns) {
198
- const target = options.refs[column];
199
- if (target !== void 0) {
200
- references[column] = target;
201
- }
202
- }
203
- return Object.keys(references).length > 0 ? { ...page, refs: references } : page;
204
- };
205
- const predicate = buildTablePredicate(columns, needle, options.filters);
206
- const order = buildOrderBy(options.orderBy, columns);
207
- const whereSql = predicate === void 0 ? "" : ` WHERE ${predicate.where}`;
208
- const orderSql = order === void 0 ? "" : ` ORDER BY ${order.sql}`;
209
- const whereParams = predicate?.parameters ?? [];
210
- const orderParams = order?.params ?? [];
211
- let total;
212
- if (!options.skipCount) {
213
- total = predicate === void 0 ? countRows(sql, quoted) : Number(sql.exec(`SELECT COUNT(*) AS c FROM ${quoted}${whereSql}`, ...whereParams).one().c);
214
- }
215
- const rawRows = sql.exec(`SELECT * FROM ${quoted}${whereSql}${orderSql} LIMIT ? OFFSET ?`, ...whereParams, ...orderParams, limit, offset).toArray();
216
- return withReferences({ ...expandDocumentRows(columns, rawRows), total });
217
- };
218
- const selectMatchingIds = (sql, options) => {
219
- const { table } = options;
220
- if (isInternalTable(table) || !tableExists(sql, table)) {
221
- throw new LunoraError("UNKNOWN_TABLE", `unknown table: ${table}`, { status: 404 });
222
- }
223
- const limit = clamp(Math.trunc(options.limit ?? MAX_PAGE_SIZE), 1, MAX_PAGE_SIZE);
224
- const quoted = quoteIdentifier(table);
225
- const columns = sql.exec(`PRAGMA table_info(${quoted})`).toArray().map((column) => column.name);
226
- const needle = options.search?.trim() ?? "";
227
- const predicate = buildTablePredicate(columns, needle, options.filters);
228
- const fetched = predicate === void 0 ? sql.exec(`SELECT id FROM ${quoted} LIMIT ?`, limit + 1).toArray() : sql.exec(`SELECT id FROM ${quoted} WHERE ${predicate.where} LIMIT ?`, ...predicate.parameters, limit + 1).toArray();
229
- const hasMore = fetched.length > limit;
230
- const ids = (hasMore ? fetched.slice(0, limit) : fetched).map((row) => row.id);
231
- return { hasMore, ids };
232
- };
233
- const knownDisplayColumns = (sql, quotedTable, physicalColumns) => {
234
- const known = new Set(physicalColumns.filter((name) => name !== DOC_COLUMN));
235
- if (!physicalColumns.includes(DOC_COLUMN)) {
236
- return known;
237
- }
238
- const sample = sql.exec(`SELECT ${quoteIdentifier(DOC_COLUMN)} AS doc FROM ${quotedTable} LIMIT ?`, MAX_PAGE_SIZE).toArray();
239
- for (const { doc } of sample) {
240
- const documentData = typeof doc === "string" ? safeParseObject(doc) : void 0;
241
- if (documentData !== void 0) {
242
- for (const key of Object.keys(documentData)) {
243
- known.add(key);
244
- }
245
- }
246
- }
247
- return known;
248
- };
249
- const facetColumn = (sql, options) => {
250
- const { column, table } = options;
251
- if (isInternalTable(table) || !tableExists(sql, table)) {
252
- throw new LunoraError("UNKNOWN_TABLE", `unknown table: ${table}`, { status: 404 });
253
- }
254
- const quoted = quoteIdentifier(table);
255
- const physicalColumns = sql.exec(`PRAGMA table_info(${quoted})`).toArray().map((info) => info.name);
256
- if (!knownDisplayColumns(sql, quoted, physicalColumns).has(column)) {
257
- throw new LunoraError("UNKNOWN_COLUMN", `unknown column: ${column}`, { status: 404 });
258
- }
259
- const resolved = resolveColumnExpression(column, physicalColumns);
260
- if (resolved === void 0) {
261
- throw new LunoraError("UNKNOWN_COLUMN", `unknown column: ${column}`, { status: 404 });
262
- }
263
- const limit = clamp(Math.trunc(options.limit ?? DEFAULT_FACET_LIMIT), 1, MAX_FACET_LIMIT);
264
- const needle = options.search?.trim() ?? "";
265
- const predicate = buildTablePredicate(physicalColumns, needle, options.filters);
266
- const whereSql = predicate === void 0 ? "" : ` WHERE ${predicate.where}`;
267
- const whereParams = predicate?.parameters ?? [];
268
- const rows = sql.exec(
269
- `SELECT ${resolved.expression} AS value, COUNT(*) AS count FROM ${quoted}${whereSql} GROUP BY ${resolved.expression} ORDER BY count DESC LIMIT ?`,
270
- ...resolved.params,
271
- ...whereParams,
272
- ...resolved.params,
273
- limit + 1
274
- ).toArray();
275
- const truncated = rows.length > limit;
276
- const kept = truncated ? rows.slice(0, limit) : rows;
277
- return {
278
- truncated,
279
- values: kept.map((row) => {
280
- return { count: Number(row.count), value: row.value };
281
- })
282
- };
283
- };
284
- const findStorageReferences = (sql, storageColumns, keys) => {
285
- const references = {};
286
- const scanned = keys.slice(0, MAX_PAGE_SIZE);
287
- for (const key of scanned) {
288
- references[key] = [];
289
- }
290
- if (scanned.length === 0) {
291
- return { references, storageColumns };
292
- }
293
- const placeholders = scanned.map(() => "?").join(", ");
294
- for (const [table, columns] of Object.entries(storageColumns)) {
295
- if (isInternalTable(table) || !tableExists(sql, table)) {
296
- continue;
297
- }
298
- const quoted = quoteIdentifier(table);
299
- const physicalColumns = sql.exec(`PRAGMA table_info(${quoted})`).toArray().map((column) => column.name);
300
- for (const column of columns) {
301
- const resolved = resolveColumnExpression(column, physicalColumns);
302
- if (resolved === void 0) {
303
- continue;
304
- }
305
- const rows = sql.exec(
306
- `SELECT id, ${resolved.expression} AS ref FROM ${quoted} WHERE ${resolved.expression} IN (${placeholders})`,
307
- ...resolved.params,
308
- ...resolved.params,
309
- ...scanned
310
- ).toArray();
311
- for (const row of rows) {
312
- references[row.ref]?.push({ column, id: row.id, table });
313
- }
314
- }
315
- }
316
- return { references, storageColumns };
317
- };
318
- const summarizeSubscriptions = (attachments) => {
319
- const connections = attachments.map((attachment, id) => {
320
- const subscriptions = Object.values(attachment.subs ?? {}).map((sub) => {
321
- return { args: sub.args, functionPath: sub.functionPath, table: sub.table };
322
- });
323
- return { admin: attachment.admin === true, id, subscriptions };
324
- });
325
- const totalSubscriptions = connections.reduce((sum, connection) => sum + connection.subscriptions.length, 0);
326
- return { connections, totalConnections: connections.length, totalSubscriptions };
327
- };
328
- const DEFAULT_FANOUT_TOPIC_LIMIT = 20;
329
- const createFanoutCounters = () => {
330
- return { maxMs: 0, passes: 0, peakSocketsIterated: 0, socketsDelivered: 0, socketsIterated: 0, totalMs: 0 };
331
- };
332
- const recordFanoutPass = (counters, iterated, delivered, ms) => {
333
- return {
334
- maxMs: Math.max(counters.maxMs, ms),
335
- passes: counters.passes + 1,
336
- peakSocketsIterated: Math.max(counters.peakSocketsIterated, iterated),
337
- socketsDelivered: counters.socketsDelivered + delivered,
338
- socketsIterated: counters.socketsIterated + iterated,
339
- totalMs: counters.totalMs + ms
340
- };
341
- };
342
- const summarizeFanoutTopics = (attachments, limit = DEFAULT_FANOUT_TOPIC_LIMIT) => {
343
- const shapeCounts = /* @__PURE__ */ new Map();
344
- const whisperCounts = /* @__PURE__ */ new Map();
345
- for (const attachment of attachments) {
346
- for (const shape of Object.values(attachment.shapes ?? {})) {
347
- const key = shape.name ?? "(unknown shape)";
348
- shapeCounts.set(key, (shapeCounts.get(key) ?? 0) + 1);
349
- }
350
- for (const topic of attachment.whispers ?? []) {
351
- whisperCounts.set(topic, (whisperCounts.get(topic) ?? 0) + 1);
352
- }
353
- }
354
- const topics = [
355
- ...[...shapeCounts].map(([topic, subscribers]) => {
356
- return { kind: "shape", subscribers, topic };
357
- }),
358
- ...[...whisperCounts].map(([topic, subscribers]) => {
359
- return { kind: "whisper", subscribers, topic };
360
- })
361
- ];
362
- topics.sort((a, b) => b.subscribers - a.subscribers || a.topic.localeCompare(b.topic));
363
- const peakSubscribers = topics[0]?.subscribers ?? 0;
364
- return { peakSubscribers, topics: topics.slice(0, limit), totalConnections: attachments.length };
365
- };
366
-
367
- export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, DEFAULT_FANOUT_TOPIC_LIMIT, FLAGS_FUNCTION_PREFIX, MAX_PAGE_SIZE, RELATION_FUNCTION_PREFIX, createFanoutCounters, facetColumn, findStorageReferences, listTables, readTablePage, recordFanoutPass, selectMatchingIds, summarizeFanoutTopics, summarizeSubscriptions };
@@ -1,56 +0,0 @@
1
- import { LunoraError } from '@lunora/errors';
2
-
3
- const COUNT_OPTION_KEYS = /* @__PURE__ */ new Set(["baseWhere", "relationBaseWhere", "restrictsCounts", "where"]);
4
- const matchesStaticWhere = (document, predicate) => {
5
- for (const [field, expected] of Object.entries(predicate)) {
6
- const actual = document[field];
7
- if (expected !== null && typeof expected === "object" && !Array.isArray(expected)) {
8
- const operatorKeys = Object.keys(expected);
9
- if (operatorKeys.length === 1 && operatorKeys[0] === "eq") {
10
- if (actual !== expected.eq) {
11
- return false;
12
- }
13
- continue;
14
- }
15
- return false;
16
- }
17
- if (actual !== expected) {
18
- return false;
19
- }
20
- }
21
- return true;
22
- };
23
- const normalizeCountArgument = (argument) => {
24
- if (argument === void 0) {
25
- return {};
26
- }
27
- if (typeof argument !== "object" || Array.isArray(argument)) {
28
- return { where: argument };
29
- }
30
- const keys = Object.keys(argument);
31
- if (keys.length === 0) {
32
- return {};
33
- }
34
- if (keys.every((key) => COUNT_OPTION_KEYS.has(key))) {
35
- return argument;
36
- }
37
- return { where: argument };
38
- };
39
- const AGGREGATE_SQL_FUNCTION = { avg: "AVG", count: "COUNT", max: "MAX", min: "MIN", sum: "SUM" };
40
- const aggregateSqlFunction = (op) => {
41
- const sqlFunction = AGGREGATE_SQL_FUNCTION[op];
42
- if (sqlFunction === void 0) {
43
- throw new LunoraError("INTERNAL", `unknown aggregate op "${op}": expected one of ${Object.keys(AGGREGATE_SQL_FUNCTION).join(", ")}`);
44
- }
45
- return sqlFunction;
46
- };
47
- const throwingScheduler = {
48
- runAfter: () => {
49
- throw new LunoraError("INTERNAL", "ctx.scheduler: no scheduler configured for triggers. Pass `scheduler` to the ctx-db factory.");
50
- },
51
- runAt: () => {
52
- throw new LunoraError("INTERNAL", "ctx.scheduler: no scheduler configured for triggers. Pass `scheduler` to the ctx-db factory.");
53
- }
54
- };
55
-
56
- export { AGGREGATE_SQL_FUNCTION, aggregateSqlFunction, matchesStaticWhere, normalizeCountArgument, throwingScheduler };
@@ -1,84 +0,0 @@
1
- const AUTH_METRICS_TABLE = "__lunora_auth_metrics";
2
- const AUTH_METRICS_BUCKETS_TABLE = "__lunora_auth_metrics_buckets";
3
- const AUTH_METRICS_ROW_KEY = "app";
4
- const AUTH_METRICS_BUCKET_MS = 6e4;
5
- const AUTH_METRICS_BUCKET_RETENTION = 1440;
6
- const runSql = (sql, query, ...params) => {
7
- const runner = sql.exec;
8
- return runner.call(sql, query, ...params);
9
- };
10
- const bucketFloor = (ts) => Math.floor(ts / AUTH_METRICS_BUCKET_MS) * AUTH_METRICS_BUCKET_MS;
11
- const ensureAuthMetricsTables = (sql) => {
12
- runSql(
13
- sql,
14
- `CREATE TABLE IF NOT EXISTS "${AUTH_METRICS_TABLE}" (
15
- key TEXT PRIMARY KEY,
16
- attempts INTEGER NOT NULL DEFAULT 0,
17
- failures INTEGER NOT NULL DEFAULT 0,
18
- since_ms INTEGER NOT NULL DEFAULT 0
19
- )`
20
- );
21
- runSql(
22
- sql,
23
- `CREATE TABLE IF NOT EXISTS "${AUTH_METRICS_BUCKETS_TABLE}" (
24
- bucket_ms INTEGER PRIMARY KEY,
25
- attempts INTEGER NOT NULL DEFAULT 0,
26
- failures INTEGER NOT NULL DEFAULT 0
27
- )`
28
- );
29
- };
30
- const recordAuthEvent = (sql, input) => {
31
- ensureAuthMetricsTables(sql);
32
- const failureCount = input.outcome === "fail" ? 1 : 0;
33
- runSql(
34
- sql,
35
- `INSERT INTO "${AUTH_METRICS_TABLE}" (key, attempts, failures, since_ms)
36
- VALUES (?, 1, ?, ?)
37
- ON CONFLICT(key) DO UPDATE SET
38
- attempts = attempts + 1,
39
- failures = failures + excluded.failures,
40
- since_ms = CASE WHEN since_ms = 0 THEN excluded.since_ms ELSE since_ms END`,
41
- AUTH_METRICS_ROW_KEY,
42
- failureCount,
43
- input.ts
44
- );
45
- const bucket = bucketFloor(input.ts);
46
- runSql(
47
- sql,
48
- `INSERT INTO "${AUTH_METRICS_BUCKETS_TABLE}" (bucket_ms, attempts, failures)
49
- VALUES (?, 1, ?)
50
- ON CONFLICT(bucket_ms) DO UPDATE SET
51
- attempts = attempts + 1,
52
- failures = failures + excluded.failures`,
53
- bucket,
54
- failureCount
55
- );
56
- runSql(
57
- sql,
58
- `DELETE FROM "${AUTH_METRICS_BUCKETS_TABLE}"
59
- WHERE bucket_ms <= (
60
- SELECT MAX(bucket_ms) - ? FROM "${AUTH_METRICS_BUCKETS_TABLE}"
61
- )`,
62
- AUTH_METRICS_BUCKET_RETENTION * AUTH_METRICS_BUCKET_MS
63
- );
64
- };
65
- const readAuthMetrics = (sql) => {
66
- ensureAuthMetricsTables(sql);
67
- const row = runSql(
68
- sql,
69
- `SELECT attempts, failures, since_ms FROM "${AUTH_METRICS_TABLE}" WHERE key = ?`,
70
- AUTH_METRICS_ROW_KEY
71
- ).toArray()[0];
72
- const attempts = row?.attempts ?? 0;
73
- const failures = row?.failures ?? 0;
74
- const sinceMs = row?.since_ms ?? 0;
75
- const history = runSql(
76
- sql,
77
- `SELECT bucket_ms, attempts, failures FROM "${AUTH_METRICS_BUCKETS_TABLE}" ORDER BY bucket_ms ASC`
78
- ).toArray().map((bucket) => {
79
- return { attempts: bucket.attempts, bucketMs: bucket.bucket_ms, failures: bucket.failures };
80
- });
81
- return { attempts, failureRate: attempts === 0 ? 0 : failures / attempts, failures, history, sinceMs };
82
- };
83
-
84
- export { AUTH_METRICS_BUCKETS_TABLE, AUTH_METRICS_BUCKET_MS, AUTH_METRICS_BUCKET_RETENTION, AUTH_METRICS_ROW_KEY, AUTH_METRICS_TABLE, ensureAuthMetricsTables, readAuthMetrics, recordAuthEvent };