@lunora/shard-engine 1.0.0-alpha.50 → 1.0.0-alpha.52
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/conformance/index.mjs +1 -1
- package/dist/index.d.mts +24 -19
- package/dist/index.d.ts +24 -19
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/{ADMIN_FUNCTIONS-oJ7IyZP6.mjs → ADMIN_FUNCTIONS-1OWiZgrN.mjs} +1 -1
- package/dist/packem_shared/AGG_COUNT-gkJ8xtVW.mjs +1 -0
- package/dist/packem_shared/{sql-projection-BqmxFxQU.mjs → BIGINT_KEY_DIGITS-Djq7G5Xx.mjs} +1 -1
- package/dist/packem_shared/{CDC_LOG_TABLE-gl0FuepJ.mjs → CDC_LOG_TABLE-Cva29kfS.mjs} +4 -4
- package/dist/packem_shared/CURSOR_PREFIX-B1i1J8Zi.mjs +1 -0
- package/dist/packem_shared/DATA_MIGRATION_STATE_TABLE-Jrx6cqEc.mjs +31 -0
- package/dist/packem_shared/DEFAULT_MAX_RELATION_KEYS-BbmpfQE4.mjs +1 -0
- package/dist/packem_shared/DEFAULT_MAX_RELAYS-BVaTptvb.mjs +1 -0
- package/dist/packem_shared/DEFAULT_PROMOTION_THRESHOLDS-CrzPqmGP.mjs +1 -0
- package/dist/packem_shared/{DEFAULT_TRANSACTION_LIMITS-Bcoi7Bvf.mjs → DEFAULT_TRANSACTION_LIMITS-D_gjjTFo.mjs} +1 -1
- package/dist/packem_shared/DurableStreamRunner-Ds3cmo3F.mjs +1 -0
- package/dist/packem_shared/NotUniqueError-C7gJLEay.mjs +1 -0
- package/dist/packem_shared/{RANK_TIEBREAK-D157XEqw.mjs → RANK_TIEBREAK-BXD4YaG3.mjs} +1 -1
- package/dist/packem_shared/RLS_UNWRAP_SYMBOL-CepZvBVl.mjs +1 -0
- package/dist/packem_shared/{ReactiveCache-BngdZxr9.mjs → ReactiveCache-CwSgH_wK.mjs} +1 -1
- package/dist/packem_shared/SEARCH_STATE_TABLE-xmYM_nOd.mjs +1 -0
- package/dist/packem_shared/{ShapeDiffCache-CLm5XXd1.mjs → ShapeDiffCache-BmVH30dI.mjs} +1 -1
- package/dist/packem_shared/{aggregateTableName-CGi8gxeK.mjs → aggregateTableName-CCCIulmn.mjs} +1 -1
- package/dist/packem_shared/applyOnDelete-CeHLU-Hh.mjs +1 -0
- package/dist/packem_shared/{awaitWsDrain-CjWMVZOG.mjs → awaitWsDrain-BqSGNI0W.mjs} +1 -1
- package/dist/packem_shared/backfillAggregateIndexes-BCmY3OYO.mjs +1 -0
- package/dist/packem_shared/{buildPokeFrames-C8km3IhJ.mjs → buildPokeFrames-CySyxldi.mjs} +1 -1
- package/dist/packem_shared/buildReprojectionMigration-D-9DU7D2.mjs +1 -0
- package/dist/packem_shared/{buildShapeDiff-Ds5Q0GJ_.mjs → buildShapeDiff-C-jrV9kY.mjs} +1 -1
- package/dist/packem_shared/{compileWhereSql-CCvDjnfy.mjs → compileWhereSql-ByHAmOE-.mjs} +1 -1
- package/dist/packem_shared/{computeRankPage-BxtyiLn9.mjs → computeRankPage-CuWuhRZN.mjs} +1 -1
- package/dist/packem_shared/createCompanionSync-DlYfWB_e.mjs +1 -0
- package/dist/packem_shared/{createReplicaLink-DujqFlHs.mjs → createReplicaLink-COCkDNMK.mjs} +1 -1
- package/dist/packem_shared/ctx-db-companions-CTabzjgb.mjs +1 -0
- package/dist/packem_shared/ctx-db-relay-shapes-B4bmET4W.mjs +17 -0
- package/dist/packem_shared/{defineEngineContractSuite-zN1RA5V-.mjs → defineEngineContractSuite-BQBhgHJM.mjs} +1 -1
- package/dist/packem_shared/do-sql-qxXsaO03.mjs +1 -0
- package/dist/packem_shared/estimate-bytes-D6KN5_7y.mjs +1 -0
- package/dist/packem_shared/exportShardRows-4Xezo8F6.mjs +1 -0
- package/dist/packem_shared/{isSoftDeleted-D6x6VWds.mjs → isSoftDeleted-cRWEfyMb.mjs} +1 -1
- package/dist/packem_shared/{materializeExternalRows-DGjC_8Hc.mjs → materializeExternalRows-DDXDqsGW.mjs} +1 -1
- package/dist/packem_shared/runShardMigrations-DiCqfU82.mjs +5 -0
- package/dist/packem_shared/{selectExpiredIds-D784Mqvh.mjs → selectExpiredIds-DHm7CSED.mjs} +1 -1
- package/dist/packem_shared/{selectShapeMembers-Dva-Z9VQ.mjs → selectShapeMembers-CPdl1Ht1.mjs} +1 -1
- package/dist/packem_shared/serializeSqlValue-BBtrWwiu.mjs +1 -0
- package/dist/packem_shared/{stableWireKey-9bjKL5Gy.mjs → stableWireKey-CSJKu_ID.mjs} +1 -1
- package/dist/packem_shared/where-sql-B1l5NcUZ.mjs +1 -0
- package/dist/packem_shared/wire-codec-UyQIjlyN.mjs +1 -0
- package/package.json +3 -3
- package/dist/packem_shared/AGG_COUNT-JTc_jUaL.mjs +0 -1
- package/dist/packem_shared/CURSOR_PREFIX-D4DUGY5z.mjs +0 -1
- package/dist/packem_shared/DATA_MIGRATION_STATE_TABLE-Cp6pbyAp.mjs +0 -31
- package/dist/packem_shared/DEFAULT_MAX_RELATION_KEYS-B3krmwZL.mjs +0 -1
- package/dist/packem_shared/DEFAULT_MAX_RELAYS-Bjx0HDbs.mjs +0 -1
- package/dist/packem_shared/DEFAULT_PROMOTION_THRESHOLDS-DpUu_mpH.mjs +0 -1
- package/dist/packem_shared/DurableStreamRunner-CWqdczw1.mjs +0 -1
- package/dist/packem_shared/NotUniqueError-Cxbfyre8.mjs +0 -1
- package/dist/packem_shared/RLS_UNWRAP_SYMBOL-BWloGsd3.mjs +0 -1
- package/dist/packem_shared/SEARCH_STATE_TABLE-BCqn5ksa.mjs +0 -1
- package/dist/packem_shared/applyOnDelete-9f4D4g1z.mjs +0 -1
- package/dist/packem_shared/backfillAggregateIndexes-BCLXdiIS.mjs +0 -1
- package/dist/packem_shared/buildReprojectionMigration-CR2RSgJd.mjs +0 -1
- package/dist/packem_shared/createCompanionSync-CJo2Uiq7.mjs +0 -1
- package/dist/packem_shared/ctx-db-companions-CN8hWTF_.mjs +0 -1
- package/dist/packem_shared/ctx-db-relay-shapes-CakvRIFx.mjs +0 -17
- package/dist/packem_shared/do-sql-bkXQEBl8.mjs +0 -1
- package/dist/packem_shared/estimate-bytes-CzG5x1f8.mjs +0 -1
- package/dist/packem_shared/exportShardRows-CegEECNc.mjs +0 -1
- package/dist/packem_shared/runShardMigrations-D6rTX7Bn.mjs +0 -5
- package/dist/packem_shared/serializeSqlValue-DbI1VQYM.mjs +0 -1
- package/dist/packem_shared/where-sql-D6MSVjdL.mjs +0 -1
- package/dist/packem_shared/wire-codec-COhOSEe4.mjs +0 -1
package/dist/packem_shared/{selectShapeMembers-Dva-Z9VQ.mjs → selectShapeMembers-CPdl1Ht1.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{sql as e}from"drizzle-orm";import{runDrizzle as m}from"./runDrizzle-2ULFQR_k.mjs";import{D as p,r as d,e as h}from"./do-sql-
|
|
1
|
+
import{sql as e}from"drizzle-orm";import{runDrizzle as m}from"./runDrizzle-2ULFQR_k.mjs";import{D as p,r as d,e as h}from"./do-sql-qxXsaO03.mjs";import{sqliteInList as w}from"./param-DlozcSQu.mjs";import{c as S}from"./where-sql-B1l5NcUZ.mjs";import{serializeSqlValue as $}from"./serializeSqlValue-BBtrWwiu.mjs";const C={fieldRef:h,serialize:$},g=o=>{if(o.length!==0)return w(e`${e.identifier("id")}`,o,!1)},u=(o,i)=>{const r=[];i&&r.push(i);const t=S(o,C);return t&&r.push(t),r.length===0?e``:e` WHERE ${e.join(r,e` AND `)}`},v=(o,i,r)=>{const t=u(r,void 0),s=m(o,e`SELECT id, _creationTime, ${e.identifier(p)} FROM ${e.identifier(i)}${t}`).toArray(),f=[];for(const l of s){const n=d(l),{id:c}=l;n!==void 0&&typeof c=="string"&&f.push({doc:n,id:c})}return f},z=(o,i,r,t)=>{const s=new Map;if(t.length===0)return s;const f=u(r,g(t)),l=m(o,e`SELECT id, _creationTime, ${e.identifier(p)} FROM ${e.identifier(i)}${f}`).toArray();for(const n of l){const c=d(n),{id:a}=n;c!==void 0&&typeof a=="string"&&s.set(a,c)}return s};export{z as selectShapeMembers,v as selectShapeRows};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{sqlComparableProjection as o}from"./BIGINT_KEY_DIGITS-Djq7G5Xx.mjs";const n=r=>typeof r=="boolean"?r?1:0:r===null||typeof r=="string"||typeof r=="number"?r:o(r)??JSON.stringify(r);export{n as serializeSqlValue};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{stableStringify as r}from"./stableStringify-DibjylKD.mjs";import{e as o}from"./wire-codec-
|
|
1
|
+
import{stableStringify as r}from"./stableStringify-DibjylKD.mjs";import{e as o}from"./wire-codec-UyQIjlyN.mjs";const m=e=>r(o(e));export{m as stableWireKey};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as T}from"@lunora/errors";import{sql as l}from"drizzle-orm";import{sqliteInList as A,isJsonSafe as $,WORKERD_SQLITE_LIMITS as O}from"./param-DlozcSQu.mjs";import{quoteIdentifier as m}from"./quoteIdentifier-CObIFRhb.mjs";import{RELATION_EXISTS_KEY as L}from"./RELATION_EXISTS_KEY-CFUhnZSZ.mjs";const R={binary:(n,t,o)=>l`${n} ${l.raw(t)} ${o}`,constant:n=>n?l`1 = 1`:l`0 = 1`,connect:(n,t,o)=>l`(${n}) ${l.raw(o)} (${t})`,contains:(n,t)=>l`instr(lower(${n}), lower(${t})) > 0`,inList:(n,t,o,i)=>A(n,t,o,i),negate:n=>l`NOT (${n})`,nullCheck:(n,t)=>t?l`${n} IS NOT NULL`:l`${n} IS NULL`,value:n=>l`${n}`},p=(...n)=>{let t="";const o=[];for(const i of n)typeof i=="string"?t+=i:(t+=i.text,o.push(...i.params));return{params:o,text:t}},f=n=>({params:[n],text:"?"}),I=n=>({params:[],text:n}),Y=n=>I(m(n)),Q={binary:(n,t,o)=>p(n," ".concat(t," "),f(o)),constant:n=>I(n?"1 = 1":"0 = 1"),connect:(n,t,o)=>p("(",n,") ".concat(o," ("),t,")"),contains:(n,t)=>p("instr(lower(",n,"), lower(",t,")) > 0"),inList:(n,t,o,i)=>{const s=o?" NOT IN ":" IN ";if(t.length>i&&!t.every(r=>$(r)))throw new T("BAD_REQUEST",`an "in" list of ${String(t.length)} values holds a value JSON cannot carry (bytes, a non-finite number, or malformed text), so it cannot be bound as one parameter — and ${String(t.length)} placeholders exceed SQLite's per-statement cap of 100 on Durable Objects and D1. Narrow the list to ${String(i)} values or fewer.`);if(t.length<=i){const r=[n,s,"("];for(const[c,e]of t.entries())c>0&&r.push(", "),r.push(f(e));return r.push(")"),p(...r)}return p(n,s,'(SELECT "value" FROM json_each(',f(JSON.stringify(t)),"))")},negate:n=>p("NOT (",n,")"),nullCheck:(n,t)=>p(n,t?" IS NOT NULL":" IS NULL"),value:f},x=O.boundParams/2,S=["eq","ne","lt","lte","gt","gte","in","notIn","isNull","contains"],_=new Set(S),j={eq:"=",gt:">",gte:">=",lt:"<",lte:"<=",ne:"<>"},E=n=>{if(n===null||typeof n!="object"||Array.isArray(n))return!1;const t=Object.keys(n);return t.length>0&&t.every(o=>_.has(o))},w=(n,t,o,i)=>{const s=i.value(o.serialize(t));return o.containsExpr?o.containsExpr(n,s):i.contains(n,s)},y=(n,t,o,i,s,r)=>i===null?t==="eq"||t==="ne"?r.nullCheck(n,t==="ne"):r.constant(!1):r.binary(n,o,s.serialize(i)),C=(n,t,o,i,s,r)=>{if(!Array.isArray(i))throw new T("BAD_REQUEST",`\`${o==="IN"?"in":"notIn"}\` on "${n}" expects an array of values, received ${i===null?"null":typeof i}`);const c=i;if(c.length===0)return r.constant(o==="NOT IN");const e=c.map(u=>s.serialize(u)),a=o==="NOT IN";return s.inList?s.inList(t,e,a):r.inList(t,e,a,x)},G=(n,t,o)=>{const i=l.join(t.map(s=>l`${s}`),l`, `);return o?l`${n} NOT IN (${i})`:l`${n} IN (${i})`},D=(n,t,o,i,s)=>{const r=o,c=[];for(const e of S){if(!(e in r))continue;const a=r[e],u=j[e];u?c.push(y(t,e,u,a,i,s)):e==="isNull"?c.push(s.nullCheck(t,!a)):e==="contains"?c.push(w(t,a,i,s)):c.push(C(n,t,e==="in"?"IN":"NOT IN",a,i,s))}return c},U=(n,t,o,i)=>{const s=o.fieldRef(n);return E(t)?D(n,s,t,o,i):t===null?[i.nullCheck(s,!1)]:[i.binary(s,"=",o.serialize(t))]},h=(n,t,o)=>{if(n.length<=1)return n[0];const i=Math.floor(n.length/2);return o.connect(h(n.slice(0,i),t,o),h(n.slice(i),t,o),t)},k=(n,t,o,i)=>{const s=Array.isArray(n)?n:[],r=[];for(const c of s){const e=N(c??{},o,i);e!==void 0&&r.push(e)}return r.length===0?t==="OR"?i.constant(!1):void 0:h(r,t,i)},M=new Set(["AND","NOT","OR",L]),P=(n,t,o,i)=>{if(n===L){if(!o.relationExists)throw new T("INTERNAL","encountered a relation EXISTS marker without a relationExists strategy hook");return o.relationExists(t)}if(n==="NOT"){const s=N(t??{},o,i);return s===void 0?void 0:i.negate(s)}return k(t,n,o,i)},N=(n,t,o)=>{const i=[];for(const[s,r]of Object.entries(n))if(M.has(s)){const c=P(s,r,t,o);c!==void 0&&i.push(c)}else i.push(...U(s,r,t,o));return h(i,"AND",o)},q=O.boundParams/2,d=n=>{let t=0,o=0;const i=s=>{const r=d(s);t+=r.lists,o+=r.scalars};if(Array.isArray(n)){for(const s of n)i(s);return{lists:t,scalars:o}}if(n===null||typeof n!="object")return{lists:t,scalars:o};for(const[s,r]of Object.entries(n))s==="in"||s==="notIn"?t+=1:s==="AND"||s==="NOT"||s==="OR"||E(r)?i(r):o+=1;return{lists:t,scalars:o}},J=(n,t,o=R)=>{if(!n||Object.keys(n).length===0)return;const{lists:i,scalars:s}=d(n);if(i===0)return N(n,t,o);const r=Math.max(1,Math.floor(Math.min(q,O.boundParams-s)/i)),c=t.inList??((e,a,u,b)=>o.inList(e,a,u,b??r));return N(n,{...t,inList:(e,a,u)=>c(e,a,u,r)},o)};export{J as c,Y as i,p as j,G as l,I as r,Q as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{t as g,f as l}from"./base64-DfpzS4o_.mjs";const o="$lunora.wire$",d=64,A=1024,w="__proto__",p={BigInt64Array,BigUint64Array,Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array},E={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},j=r=>{if(r===null||typeof r!="object")return!1;const t=Object.getPrototypeOf(r);return t===null||t===Object.prototype},O=(r,t=0)=>{if(t>d)return!0;if(r===null)return!1;const c=typeof r;if(c==="string"||c==="boolean")return!1;if(c==="number")return!Number.isFinite(r);if(c!=="object")return!0;if(Array.isArray(r))return r.length>0&&r[0]===o?!0:r.some(f=>f===void 0||O(f,t+1));if(!j(r)||Object.hasOwn(r,w))return!0;for(const f of Object.keys(r)){const i=r[f];if(i!==void 0&&O(i,t+1))return!0}return!1},u=(r,t=0)=>{if(t>d)throw new RangeError(`wire-codec: value nesting exceeds the ${d}-level limit`);if(r===void 0)return[o,"undefined"];if(r===null)return null;const c=typeof r;if(c==="bigint")return[o,"bigint",r.toString()];if(c==="number"){const e=r;return Number.isNaN(e)?[o,"nan"]:e===1/0?[o,"inf"]:e===-1/0?[o,"-inf"]:e}if(c!=="object")return r;if(r instanceof Date)return[o,"date",u(r.getTime(),t+1)];if(r instanceof Error){const e=r,n={};for(const a of Object.keys(e))e[a]!==void 0&&(n[a]=u(e[a],t+1));const s=[o,"error",e.name,e.message,n];return e.cause!==void 0&&s.push(u(e.cause,t+1)),s}if(r instanceof URL)return[o,"url",r.href];if(r instanceof Map)return[o,"map",[...r.entries()].map(([e,n])=>[u(e,t+1),u(n,t+1)])];if(r instanceof Set)return[o,"set",[...r].map(e=>u(e,t+1))];if(r instanceof ArrayBuffer)return[o,"bytes",g(new Uint8Array(r)),"ArrayBuffer"];if(ArrayBuffer.isView(r)){const e=r,n=e.constructor.name,s=new Uint8Array(e.buffer,e.byteOffset,e.byteLength);return n==="Uint8Array"?[o,"bytes",g(s)]:[o,"bytes",g(s),n]}if(Array.isArray(r)){const e=r.map(n=>u(n,t+1));return e.length>0&&e[0]===o?[o,"arr",e]:e}if(!j(r)){const e=r.constructor?.name??"value";throw new TypeError(`wire-codec: cannot encode a ${e} 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 f=r,i={};for(const e of Object.keys(f)){const n=f[e];if(n===void 0)continue;const s=u(n,t+1);e===w?Object.defineProperty(i,e,{configurable:!0,enumerable:!0,value:s,writable:!0}):i[e]=s}return i},y=(r,t=0)=>{if(t>d)throw new RangeError(`wire-codec: value nesting exceeds the ${d}-level limit`);if(r===null||typeof r!="object")return r;if(Array.isArray(r)){if(r[0]===o)switch(r[1]){case"-inf":return-1/0;case"arr":return r[2].map(e=>y(e,t+1));case"bigint":{const e=r[2];if(typeof e!="string"||e.length>A||!/^-?\d+$/.test(e))throw new RangeError(`wire-codec: invalid or over-long bigint (max ${A} digits)`);return BigInt(e)}case"date":{if(r.length<3)throw new TypeError("wire-codec: malformed date — missing payload");return new Date(y(r[2],t+1))}case"map":{const e=r[2];return new Map(e.map(n=>{if(!Array.isArray(n)||n.length!==2)throw new TypeError("wire-codec: malformed map entry — expected a [key, value] pair");return[y(n[0],t+1),y(n[1],t+1)]}))}case"set":return new Set(r[2].map(e=>y(e,t+1)));case"url":return new URL(r[2]);case"error":{const e=r[2],n=r[3],s=(Object.hasOwn(E,e)?E[e]:void 0)??Error,a=new s(n);a.name!==e&&Object.defineProperty(a,"name",{configurable:!0,value:e,writable:!0});const b=y(r[4],t+1);if(b===null||typeof b!="object"||Array.isArray(b))throw new TypeError("wire-codec: malformed error — props must be an object");for(const m of Object.keys(b))m===w?Object.defineProperty(a,m,{configurable:!0,enumerable:!0,value:b[m],writable:!0}):a[m]=b[m];return r.length>5&&Object.defineProperty(a,"cause",{configurable:!0,value:y(r[5],t+1),writable:!0}),a}case"bytes":{const e=l(r[2]),n=r[3]??"Uint8Array";if(n==="ArrayBuffer")return e.buffer.byteLength===e.byteLength?e.buffer:e.slice().buffer;const s=Object.hasOwn(p,n)?p[n]:void 0;return s?new s(e.slice().buffer):e}case"inf":return 1/0;case"nan":return Number.NaN;case"undefined":return;default:return r.map(e=>y(e,t+1))}return r.map(i=>y(i,t+1))}const c=r,f={};for(const i of Object.keys(c)){const e=y(c[i],t+1);i===w?Object.defineProperty(f,i,{configurable:!0,enumerable:!0,value:e,writable:!0}):f[i]=e}return f};export{y as d,u as e,j as i,O as n};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/shard-engine",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.52",
|
|
4
4
|
"description": "Host-neutral reactive engine for Lunora: per-shard state, OCC, CDC, reactive subscriptions, and the poke protocol. Consumes @lunora/platform host contracts and can be mounted on any platform host.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cloudflare",
|
|
@@ -48,8 +48,8 @@
|
|
|
48
48
|
"access": "public"
|
|
49
49
|
},
|
|
50
50
|
"dependencies": {
|
|
51
|
-
"@lunora/errors": "1.0.0-alpha.
|
|
52
|
-
"@lunora/platform": "1.0.0-alpha.
|
|
51
|
+
"@lunora/errors": "1.0.0-alpha.29",
|
|
52
|
+
"@lunora/platform": "1.0.0-alpha.24",
|
|
53
53
|
"drizzle-orm": "^0.45.2"
|
|
54
54
|
},
|
|
55
55
|
"engines": {
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{A as r,a as l,b as i,D as n,n as m,c as q,d as c,l as d,k as f,g as p,i as u,j as A,e as D,q as G,f as S,r as _,t as h,h as C}from"./do-sql-bkXQEBl8.mjs";import{quoteIdentifier as b}from"./quoteIdentifier-CObIFRhb.mjs";import"./wire-codec-COhOSEe4.mjs";import"./runDrizzle-2ULFQR_k.mjs";import"./sql-projection-BqmxFxQU.mjs";import{serializeSqlValue as x}from"./serializeSqlValue-DbI1VQYM.mjs";export{r as AGG_COUNT,l as AGG_KEY,i as AGG_VALUE,n as DOC_COLUMN,m as DOC_ORIGINALS_KEY,q as aggUpsertSql,c as createIndexSql,d as decodeDocJson,f as encodeDocJson,p as geoTableName,u as isFtsAvailable,A as jsonPath,D as jsonPathSql,G as qualifiedJsonPath,S as qualifiedJsonPathSql,b as quoteIdentifier,_ as rowToDocument,x as serializeSqlValue,h as tableColumns,C as tryRowToDocument};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as b}from"@lunora/errors";import{d as S,e as m}from"./wire-codec-COhOSEe4.mjs";const _="id",E=e=>e.at(-1)?.direction==="desc"?"desc":"asc",N=new Set(["_id","id"]),y=new Set(["_creationTime","_id","id"]),C=(e,t)=>{if(y.has(e))return!1;const o=t?.[e];return o===void 0?!0:o.kind==="optional"||o._meta?.column?.notNull===!1},I=(e,t)=>{const o=[];for(const r of e??[])for(const[n,i]of Object.entries(r))o.push({direction:i,field:n,nullable:C(n,t)});return o.length===0?[{direction:"asc",field:"_creationTime",nullable:!1}]:o},F=/[\u0080-\u{10FFFF}]/u,O=e=>{if(!F.test(e))return btoa(e);const t=new TextEncoder().encode(e);let o="";for(const r of t)o+=String.fromCodePoint(r);return btoa(o)},v=e=>{const t=atob(e),o=Uint8Array.from(t,r=>r.codePointAt(0)??0);return new TextDecoder().decode(o)},a="~2",L=(e,t)=>{const o=t.map(r=>e[r.field]??null);return o.push(e._id),a+O(JSON.stringify(m(o)))},u=()=>new b("BAD_REQUEST","invalid cursor"),T=e=>{if(!e.startsWith(a))throw u();let t;try{t=S(JSON.parse(v(e.slice(a.length))))}catch{throw u()}if(!Array.isArray(t))throw u();return t.map(o=>o??null)},R=(e,t,o,r)=>{const{field:n}=e,i=e.direction!=="desc"===o;if(t===null)return i?r?{OR:[{[n]:{isNull:!1}},{[n]:{isNull:!0}}]}:{[n]:{isNull:!1}}:r?{[n]:{isNull:!0}}:{OR:[]};let s=i?"gt":"lt";r&&(s=i?"gte":"lte");const c={[n]:{[s]:t}};return i||!e.nullable?c:{OR:[c,{[n]:{isNull:!0}}]}},f=(e,t,o,r)=>{const n=e.some(s=>N.has(s.field))?e:[...e,{direction:E(e),field:_,nullable:!1}];if(t.length<n.length)throw u();const i=[];for(const[s,c]of n.entries()){const l=[];for(const[p,h]of n.slice(0,s).entries())l.push({[h.field]:{eq:t[p]}});l.push(R(c,t[s],o,r&&s===n.length-1));const[d]=l;i.push(l.length===1&&d!==void 0?d:{AND:l})}return{OR:i}},A=(e,t)=>f(e,t,!0,!1),k=(e,t)=>f(e,t,!1,!0),g=["_id","_creationTime"],W=(e,t,o)=>{if(!t)return e;const r=new Set([...t,...g,...o?Object.keys(o):[]]);return e.map(n=>{const i={};for(const s of r)s in n&&(i[s]=n[s]);return i})},B=(e,t)=>e&&t!==!0?{[e.field]:{isNull:!0}}:void 0,U=(e,t)=>t===void 0||e[t]===null||e[t]===void 0;export{a as CURSOR_PREFIX,W as applySelect,k as buildSeekBeforeWhere,A as buildSeekWhere,T as decodeCursor,L as encodeCursor,v as fromBase64,u as invalidCursor,U as isLiveForCompanion,I as normalizeOrderKeys,B as softDeleteScope,E as tiebreakDirectionFor,O as toBase64};
|
|
@@ -1,31 +0,0 @@
|
|
|
1
|
-
import{LunoraError as b}from"@lunora/errors";import{runSql as c}from"./runDrizzle-2ULFQR_k.mjs";const n="__lunora_migrations",x=100,N=3e4,y=1e4,M=e=>{c(e,`CREATE TABLE IF NOT EXISTS "${n}" (
|
|
2
|
-
id TEXT PRIMARY KEY,
|
|
3
|
-
direction TEXT NOT NULL,
|
|
4
|
-
status TEXT NOT NULL,
|
|
5
|
-
cursor TEXT,
|
|
6
|
-
processed INTEGER NOT NULL DEFAULT 0,
|
|
7
|
-
changed INTEGER NOT NULL DEFAULT 0,
|
|
8
|
-
started_at REAL,
|
|
9
|
-
updated_at REAL,
|
|
10
|
-
error TEXT
|
|
11
|
-
)`)},R=e=>({changed:e.changed,cursor:typeof e.cursor=="string"?e.cursor:null,direction:e.direction==="down"?"down":"up",processed:e.processed,status:e.status==="completed"||e.status==="failed"?e.status:"in_progress"}),S=(e,t)=>{const r=c(e,`SELECT * FROM "${n}" WHERE id = ?`,t).toArray()[0];if(r)return{...R(r),startedAt:typeof r.started_at=="number"?r.started_at:void 0}},U=(e,t,s)=>{c(e,`DELETE FROM "${n}"
|
|
12
|
-
WHERE id = ? AND (status <> 'in_progress' OR updated_at IS NULL OR updated_at <= ?)`,t,s)},h=(e,t)=>{c(e,`INSERT INTO "${n}"
|
|
13
|
-
(id, direction, status, cursor, processed, changed, started_at, updated_at, error)
|
|
14
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
15
|
-
ON CONFLICT(id) DO UPDATE SET
|
|
16
|
-
direction = excluded.direction,
|
|
17
|
-
status = excluded.status,
|
|
18
|
-
cursor = excluded.cursor,
|
|
19
|
-
processed = excluded.processed,
|
|
20
|
-
changed = excluded.changed,
|
|
21
|
-
updated_at = excluded.updated_at,
|
|
22
|
-
error = excluded.error`,t.id,t.direction,t.status,t.cursor,t.processed,t.changed,t.startedAt,t.updatedAt,t.error)},C=(e,t,s,r)=>(c(e,`INSERT INTO "${n}"
|
|
23
|
-
(id, direction, status, cursor, processed, changed, started_at, updated_at, error)
|
|
24
|
-
VALUES (?, ?, 'in_progress', NULL, 0, 0, ?, ?, NULL)
|
|
25
|
-
ON CONFLICT(id) DO UPDATE SET
|
|
26
|
-
status = 'in_progress',
|
|
27
|
-
updated_at = excluded.updated_at
|
|
28
|
-
WHERE
|
|
29
|
-
"${n}".status <> 'in_progress'
|
|
30
|
-
OR "${n}".updated_at IS NULL
|
|
31
|
-
OR "${n}".updated_at <= excluded.updated_at - ${String(N)}`,t,s,r,r),c(e,"SELECT changes() AS changed").one().changed>0),$=(e,t,s)=>{c(e,`UPDATE "${n}" SET updated_at = ? WHERE id = ? AND status = 'in_progress'`,s,t)},F=(e,t)=>{c(e,`UPDATE "${n}" SET updated_at = 0 WHERE id = ? AND status = 'in_progress'`,t)},B=(e,t)=>{if(c(e,"SELECT name FROM sqlite_master WHERE type = 'table' AND name = ? LIMIT 1",n).toArray().length===0)return[];const r=t===void 0?" ORDER BY id":" WHERE id = ?",i=t===void 0?[]:[t];return c(e,`SELECT * FROM "${n}"${r}`,...i).toArray().map(a=>({...R(a),error:typeof a.error=="string"?a.error:null,id:a.id,startedAt:typeof a.started_at=="number"?a.started_at:null,updatedAt:typeof a.updated_at=="number"?a.updated_at:null}))},w=async e=>{const{migration:t,sql:s,writer:r}=e,i=e.direction??"up",o=e.dryRun??!1,a=e.clock??(()=>Date.now()),I=e.maxBatches??Number.POSITIVE_INFINITY,O=e.batchSize??t.batchSize??x,f=i==="up"?t.up:t.down;if(!f)throw new b("INTERNAL",`data migration "${t.id}" has no \`${i}\` transform`);const D={db:{count:r.count.bind(r),findFirst:r.findFirst.bind(r),findMany:r.findMany.bind(r),get:r.get.bind(r)}};let p=null,_=0,g=0,A=a();if(!o){M(s);const d=S(s,t.id);if(d?.direction===i&&d.status==="completed")return{changed:d.changed,cursor:null,direction:i,dryRun:o,id:t.id,processed:d.processed,status:"completed"};if(d&&d.direction!==i&&U(s,t.id,a()-N),!C(s,t.id,i,a())){const u=S(s,t.id);return{changed:u?.changed??0,cursor:u?.cursor??p,direction:u?.direction??i,dryRun:o,id:t.id,processed:u?.processed??0,status:u?.status??"in_progress"}}const l=d?.direction===i?d:void 0;l&&(p=l.cursor,_=l.processed,g=l.changed,A=l.startedAt??A)}let T=!1,m=0,L=A;try{for(;!T&&m<I;){const d=await r.findMany(t.table,{cursor:p,limit:O});for(const E of d.page){_+=1;const l=await f(E,D);if(l!==void 0&&(g+=1,o||await r.replace(String(E._id),{...l,_creationTime:E._creationTime,_id:E._id},void 0,{allowExplicitId:!0})),!o){const u=a();u-L>=y&&($(s,t.id,u),L=u)}}if(p=d.continueCursor,T=d.isDone,m+=1,!o){const E=a();h(s,{changed:g,cursor:T?null:p,direction:i,error:null,id:t.id,processed:_,startedAt:A,status:T?"completed":"in_progress",updatedAt:E}),L=E;try{await e.onBatch?.({batches:m,changed:g,processed:_})}catch{}}}}catch(d){throw o||h(s,{changed:g,cursor:p,direction:i,error:d instanceof Error?d.message:String(d),id:t.id,processed:_,startedAt:A,status:"failed",updatedAt:a()}),d}if(!o&&!T)try{F(s,t.id)}catch(d){console.warn(`data migration "${t.id}": releaseClaim failed`,d)}return{changed:g,cursor:T?null:p,direction:i,dryRun:o,id:t.id,processed:_,status:T?"completed":"in_progress"}};export{n as DATA_MIGRATION_STATE_TABLE,B as readMigrationStatus,w as runDataMigration};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as h}from"@lunora/errors";import{distinctValues as w}from"./applyOnDelete-9f4D4g1z.mjs";import{RELATION_EXISTS_KEY as N}from"./RELATION_EXISTS_KEY-CFUhnZSZ.mjs";const g={every:{kind:"many",negateChild:!0,negated:!0},is:{kind:"one",negated:!1},isNot:{kind:"one",negated:!0,nullDisjunct:!0},none:{kind:"many",negated:!0},some:{kind:"many",negated:!1}},T=new Set(Object.keys(g)),p=e=>{const t=g[e];if(!t)throw new h("INTERNAL",`unknown relation operator "${e}"`);return t},j=e=>e.kind==="one"?{clause:e.field,project:e.references}:{clause:e.references,project:e.field},S=5e3,l=Symbol("relation-key-overflow"),b=e=>Array.isArray(e)?e.map(t=>t??{}):[],R=e=>{if(e.length===1){const[t]=e;return t??{}}return e.length===0?{}:{AND:e}},y=e=>{if(e===null||typeof e!="object"||Array.isArray(e))return!1;const t=Object.keys(e);return t.length>0&&t.every(n=>T.has(n))},u=(e,t,n)=>{const r=t.tables[n]?.relationMap??{};return Object.keys(e).some(s=>{const a=e[s];return s==="AND"||s==="OR"?b(a).some(o=>u(o,t,n)):s==="NOT"?u(a??{},t,n):!!r[s]&&y(a)})},K=(e,t,n,r)=>{if(e&&u(e,t,n))throw new h("INTERNAL",`relation-crossing predicates are not supported in ${r}() — use them in findMany/findFirst or an RLS read policy`)},P=async(e,t,n,r,s)=>{const a=await d(t,e.table,r),{page:o}=await r.fetcher(e.table,{baseWhere:r.relationBaseWhere?.(e.table),relationBaseWhere:r.relationBaseWhere,where:a}),i=w(o,n);if(i.length>r.maxRelationKeys){if(s)return l;throw new h("INTERNAL",`relation predicate on "${e.table}" matched ${String(i.length)} rows, exceeding the ${String(r.maxRelationKeys)}-key limit; narrow the predicate (a same-shard EXISTS push-down lifts this cap)`)}return i},$=async(e,t,n,r,s)=>{const a=p(e),{clause:o,project:i}=j(t),c=await P(t,a.negateChild?{NOT:n}:n,i,r,s);return c===l?l:a.negated?a.nullDisjunct?{OR:[{[o]:{notIn:c}},{[o]:{isNull:!0}}]}:{[o]:{notIn:c}}:{[o]:{in:c}}},m=async(e,t,n,r,s)=>{const a=p(e),o=s.relationBaseWhere?.(t.table),i=a.negateChild?{NOT:n}:n,A={childWhere:await d(o?{AND:[o,i]}:i,t.table,s),negated:a.negated,parentTable:r,relation:t};return{[N]:A}},k=(e,t,n)=>{const r=g[e];if(r&&r.kind!==n.kind)throw new h("INTERNAL",`relation operator "${e}" requires a to-${r.kind} relation, but "${t}" is to-${n.kind}`)},I=async(e,t,n,r,s)=>{const a=[];for(const o of Object.keys(n)){k(o,e,t);const i=n[o]??{},c=s.canPushExists?.(t)??!1;if(c&&s.existsPushMode==="always"){a.push(await m(o,t,i,r,s));continue}const f=await $(o,t,i,s,c);f===l?a.push(await m(o,t,i,r,s)):a.push(f)}return R(a)},L=async(e,t,n,r)=>{if(e==="AND"||e==="OR"){const a=[];for(const o of b(t))a.push(await d(o,n,r));return{[e]:a}}if(e==="NOT")return{NOT:await d(t??{},n,r)};const s=r.schema.tables[n]?.relationMap?.[e];return s&&y(t)?I(e,s,t,n,r):{[e]:t}},d=async(e,t,n)=>{const r=[];for(const s of Object.keys(e))r.push(await L(s,e[s],t,n));return R(r)},v=async(e,t)=>!e||!u(e,t.schema,t.tableName)?e:d(e,t.tableName,{canPushExists:t.canPushExists,existsPushMode:t.existsPushMode??"auto",fetcher:t.fetcher,maxRelationKeys:t.maxRelationKeys??S,relationBaseWhere:t.relationBaseWhere,schema:t.schema}),O=(e,t,n)=>{for(const r of e){const s=E(r,t,n);if(s)return s}},M=(e,t,n,r)=>{if(e==="AND"||e==="OR")return O(b(t),n,r);if(e==="NOT")return O([t??{}],n,r);const s=n.tables[r]?.relationMap?.[e];if(!(!s||!y(t)))return n.tables[s.table]?.shardMode?.kind==="shardBy"?{relation:e,target:s.table}:O(Object.values(t),n,s.table)},E=(e,t,n)=>{for(const r of Object.keys(e)){const s=M(r,e[r],t,n);if(s)return s}},B=(e,t,n)=>{if(!e)return;const r=E(e,t,n);if(r)throw Object.assign(new Error(`shape on "${n}" joins the sharded table "${r.target}" via relation "${r.relation}" — a live shape cannot replicate rows that live in another shard's Durable Object. Fix it by (a) denormalizing the joined columns into "${n}", or (b) moving "${r.target}" to .global() so it is served through the latency-tiered D1 shape tier.`),{code:"SHAPE_CROSS_SHARD_JOIN",name:"LunoraError",status:400})};export{S as DEFAULT_MAX_RELATION_KEYS,K as assertFlatPredicate,B as assertShapeShardable,u as containsRelationPredicate,y as isRelationPredicate,v as resolveRelationPredicates};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{toErrorBody as P,LunoraError as M}from"@lunora/errors";import{e as x,d as I}from"./wire-codec-COhOSEe4.mjs";import{w as _,a as w,m as k,r as N,d as C,b as O}from"./ctx-db-relay-shapes-CakvRIFx.mjs";import{envPositiveInt as g}from"./envOptionalPositiveInt-D2pY-c64.mjs";import{relayName as m,DEFAULT_PROMOTION_THRESHOLDS as E,nextPromotionState as D,shapeRoutingKey as R,parseRelayName as F,clampPromotionThresholds as U}from"./DEFAULT_PROMOTION_THRESHOLDS-DpUu_mpH.mjs";import{encodeRowsPatch as W,buildPokeFrames as T}from"./buildPokeFrames-C8km3IhJ.mjs";import{v as K,R as v,s as Y,a as B,b as H}from"./sibling-channel-Cxvk0Zca.mjs";import{awaitWsDrain as $,trySendFrame as A}from"./awaitWsDrain-CjWMVZOG.mjs";import{stableWireKey as f}from"./stableWireKey-9bjKL5Gy.mjs";const j=2,z=8,b={},G=c=>{throw new M("INTERNAL",`unhandled relay frame: ${JSON.stringify(c)}`)},X=(c,e)=>c===void 0||c.epoch!==e.epoch?!1:c.cursor>=e.fromCursor&&c.cursor<e.checkpoint,J=c=>Response.json(c,{headers:{"content-type":"application/json"}}),S=()=>new Response(null,{status:204});class L{constructor(e,t){this.host=e,this.roleId=t}host;roleId;async handleControl(e){let t;try{t=await e.text()}catch{return new Response("bad request",{status:400})}if(!await K(this.host.env(),e.headers.get(v),t))return new Response("forbidden",{status:403});let s;try{s=JSON.parse(t)}catch{return new Response("bad request",{status:400})}switch(s.type){case"relay_attach":return this.onAttach(s.relayIndex),S();case"relay_detach":return this.onDetach(s.relayIndex),S();case"relay_frame":return this.host.deliverWhisperLocal(s.topic,s.frame,void 0),await this.onWhisperFrame(s),S();case"relay_shape_poke":{const r=this.host.getWebSockets().length,o=Date.now(),a=this.onShapePoke({...s,args:I(s.args)});return this.host.recordShapePokeFanout(r,a,Date.now()-o),S()}case"relay_shape_subscribe":return J(this.onShapeSubscribe({...s,args:I(s.args)}));default:return G(s)}}maxRelays(){return g(this.host.env(),"LUNORA_MAX_RELAYS",z)}canAddressSiblings(){return this.siblingStub(this.roleId.ownerKey)!==void 0}siblingStub(e){return Y(this.host.env(),this.bindingName(),e)}bindingName(){return this.host.shardBinding()}async postRelayMessage(e,t){await this.requestRelayMessage(e,t)}async requestRelayMessage(e,t){const s=this.siblingStub(e);if(s===void 0)return;const r=JSON.stringify(t),o={"content-type":"application/json","x-lunora-shard-binding":this.host.shardBinding()??""},a=B(this.host.env());a!==void 0&&(o[v]=await H(a,r));try{return await s.fetch("https://relay.internal/_lunora/relay",{body:r,headers:o,method:"POST"})}catch{return}}}class V extends L{shapeUniformCache=new Map;relaySetCache;registryCache;recordedBinding;promotionState="owned";constructor(e,t){super(e,{ownerKey:t})}async forwardWhisper(e,t){if(!this.canAddressSiblings())return;const s=this.ownerRelaySet();s.size!==0&&await Promise.all([...s].map(r=>this.postRelayMessage(m(this.roleId.ownerKey,r),{frame:t,topic:e,type:"relay_frame"})))}async onFlush(e,t){this.canAddressSiblings()&&await Promise.all([this.multicastShapePokes(e,t),this.proxyShapePokes(e,t)])}seedRelayShape(){return Promise.resolve(void 0)}announce(){return Promise.resolve()}announceDrain(){return Promise.resolve()}relayCount(){const e=this.host.getWebSockets().length,t=g(this.host.env(),"LUNORA_RELAY_THRESHOLD",E.tUp),s=g(this.host.env(),"LUNORA_RELAY_COLLAPSE_THRESHOLD",E.tDown);if(this.promotionState=D(this.promotionState,e,U(t,s)),this.promotionState==="owned")return 0;const r=g(this.host.env(),"LUNORA_RELAY_FAN",j);return Math.min(this.maxRelays(),Math.max(1,r))}minShapeCursor(){const{cohort:e,proxies:t}=this.relayShapes();let s;for(const r of[...e.values(),...t.values()])s=s===void 0?r.cursor:Math.min(s,r.cursor);return s}isShapeRelayUniform(e,t){const s=R(e,t),r=this.shapeUniformCache.get(s);if(r!==void 0)return r;const o=this.probeShapeRelayUniform(e,t);return this.shapeUniformCache.set(s,o),o}onAttach(e){this.addRelayToSet(e)}onDetach(e){this.removeRelayFromSet(e)}async onWhisperFrame(e){await Promise.all([...this.ownerRelaySet()].filter(t=>t!==e.originRelay).map(t=>this.postRelayMessage(m(this.roleId.ownerKey,t),{frame:e.frame,topic:e.topic,type:"relay_frame"})))}onShapeSubscribe(e){return this.buildShapeSeedFrames(e)}onShapePoke(){return 0}buildShapePoke(e,t,s,r,o){let a;try{a=this.host.resolveShape(e.name,e.args,t)}catch{return}if(a===void 0||a.global===!0||!s.has(a.table))return;const n=e,l=n.cursor,i=this.host.buildShapeDiff(a,l,r);if(i.length!==0)return n.cursor=r,_(this.host.sql(),n.key,r),{args:x(e.args),checkpoint:r,epoch:o,fromCursor:l,name:e.name,rowsPatch:W(i),type:"relay_shape_poke"}}async multicastShapePokes(e,t){const s=this.ownerRelaySet();if(s.size===0)return;const{cohort:r}=this.relayShapes();if(r.size===0)return;const o=this.host.currentCdcEpoch(),a=[];for(const n of r.values()){const l=this.buildShapePoke(n,b,e,t,o);l&&a.push(this.multicastToRelays(s,l,n))}await Promise.all(a)}async multicastToRelays(e,t,s){(await Promise.all([...e].map(async o=>(await this.requestRelayMessage(m(this.roleId.ownerKey,o),t))?.ok===!0))).includes(!1)&&this.rewindShapeCursor(s,t.fromCursor)}async proxyShapePokes(e,t){if(this.ownerRelaySet().size===0)return;const{proxies:s}=this.relayShapes();if(s.size===0)return;const r=this.host.currentCdcEpoch(),o=[];for(const a of s.values()){const n=this.buildShapePoke(a,a.identity,e,t,r);n&&o.push(this.proxyToRelay(n,a))}await Promise.all(o)}async proxyToRelay(e,t){(await this.requestRelayMessage(m(this.roleId.ownerKey,t.relayIndex),{...e,targetConnectionId:t.connectionId}))?.ok!==!0&&this.rewindShapeCursor(t,e.fromCursor)}buildShapeSeedFrames(e){const t={identity:e.identity,userId:e.userId};let s;try{s=this.host.resolveShape(e.name,e.args,t)}catch(h){const{body:u}=P(h,{fallbackCode:"SHAPE_RESOLVE_FAILED",redactedMessage:"shape resolution failed"});return{error:{code:u.code,message:u.message}}}if(s===void 0||s.global===!0)return{error:{code:"SHAPE_NOT_FOUND",message:`shape not relayable: ${e.name}`}};e.relayIndex!==void 0&&this.addRelayToSet(e.relayIndex);const{baseCheckpoint:r,cursor:o,epoch:a,reset:n,rowsPatch:l}=this.host.computeOpLogShapeSeed({args:e.args,name:e.name,sinceEpoch:e.sinceEpoch,sinceSeq:e.sinceSeq},s);let i=o;const{cohort:d,proxies:p}=this.relayShapes();if(this.isShapeRelayUniform(e.name,e.args)){const h=R(e.name,e.args);let u=d.get(h);u===void 0&&(u={args:e.args,cursor:o,key:h,name:e.name},d.set(h,u),w(this.host.sql(),u)),i=u.cursor}else if(e.relayIndex!==void 0&&e.connectionId!==void 0){const h=`${String(e.relayIndex)}:${e.connectionId}:${e.subId}`,u={args:e.args,connectionId:e.connectionId,cursor:o,identity:t,key:h,name:e.name,relayIndex:e.relayIndex};p.set(h,u),w(this.host.sql(),u)}else return{error:{code:"RELAY_SHAPE_UNROUTABLE",message:`shape ${e.name} is per-socket on a relay, but the subscribe carries no ${e.relayIndex===void 0?"relay index":"connection id"}`}};const y=T([{reset:n,rowsPatch:l,shapeId:e.subId}],{baseCheckpoint:r,checkpoint:i,epoch:a,lastMutationId:void 0,pokeId:this.host.nextPokeId()});return{cursor:i,epoch:a,frames:y}}ensureRelayTables(){this.host.sql().exec("CREATE TABLE IF NOT EXISTS __lunora_relays (idx INTEGER PRIMARY KEY)"),this.host.sql().exec("CREATE TABLE IF NOT EXISTS __lunora_relay_binding (id INTEGER PRIMARY KEY, binding TEXT NOT NULL)"),k(this.host.sql())}bindingName(){const e=this.host.shardBinding();if(e!==void 0&&e!=="")return e!==this.recordedBinding&&(this.recordedBinding=e,this.ensureRelayTables(),this.host.sql().exec("INSERT INTO __lunora_relay_binding (id, binding) VALUES (1, ?) ON CONFLICT(id) DO UPDATE SET binding = excluded.binding",e)),e;if(this.recordedBinding!==void 0)return this.recordedBinding;try{const t=this.host.sql().exec("SELECT binding FROM __lunora_relay_binding WHERE id = 1").toArray();this.recordedBinding=t[0]?.binding}catch{this.recordedBinding=void 0}return this.recordedBinding}relayShapes(){const e=this.registryCache;if(e!==void 0)return e;this.ensureRelayTables();const t={cohort:new Map,proxies:new Map};for(const s of N(this.host.sql()))s.relayIndex===void 0||s.connectionId===void 0?t.cohort.set(s.key,{args:s.args,cursor:s.cursor,key:s.key,name:s.name}):t.proxies.set(s.key,{args:s.args,connectionId:s.connectionId,cursor:s.cursor,identity:s.identity??{},key:s.key,name:s.name,relayIndex:s.relayIndex});return this.registryCache=t,t}rewindShapeCursor(e,t){const s=e;s.cursor<=t||(s.cursor=t,_(this.host.sql(),s.key,t))}ownerRelaySet(){if(this.relaySetCache===void 0){this.ensureRelayTables();const e=this.host.sql().exec("SELECT idx FROM __lunora_relays").toArray();this.relaySetCache=new Set(e.map(t=>Number(t.idx)))}return this.relaySetCache}addRelayToSet(e){this.ensureRelayTables(),this.host.sql().exec("INSERT OR IGNORE INTO __lunora_relays (idx) VALUES (?)",e),this.ownerRelaySet().add(e)}removeRelayFromSet(e){this.ensureRelayTables(),this.host.sql().exec("DELETE FROM __lunora_relays WHERE idx = ?",e);const t=this.ownerRelaySet();t.delete(e);const{cohort:s,proxies:r}=this.relayShapes();for(const[o,a]of r)a.relayIndex===e&&r.delete(o);C(this.host.sql(),e),t.size===0&&(s.clear(),this.shapeUniformCache.clear(),O(this.host.sql()))}probeShapeRelayUniform(e,t){let s;try{s=this.host.resolveShape(e,t,b)}catch{return!1}if(s===void 0||s.global===!0||this.host.rlsMetadata().policies.some(i=>i.on==="read"&&i.table===s.table)||this.tableHasAnyMask(s.table))return!1;const r=f(s.effectiveWhere),o=f(s.columns);let a=!1;const n=i=>{const d={groups:[`grp_${i}`],roles:[i],sub:`__lunora_probe_${i}__`};return{identity:new Proxy(d,{get:(y,h)=>typeof h=="symbol"||h in y?Reflect.get(y,h):`${i}:${h}`,getOwnPropertyDescriptor:(y,h)=>(a=!0,Reflect.getOwnPropertyDescriptor(y,h)),has:(y,h)=>typeof h=="symbol"?Reflect.has(y,h):!0,ownKeys:y=>(a=!0,Reflect.ownKeys(y))}),userId:`__lunora_probe_${i}__`}};return[b,n("a"),n("b")].every(i=>{let d;try{d=this.host.resolveShape(e,t,i)}catch{return!1}return d!==void 0&&d.global!==!0&&d.table===s.table&&f(d.effectiveWhere)===r&&f(d.columns)===o})&&!a}tableHasAnyMask(e){return this.host.maskMetadata().columns.some(t=>t.table===e)}}class Q extends L{relayAnnounced=!1;shapeRelayMemos=new WeakMap;constructor(e,t,s){super(e,{ownerKey:t,relayIndex:s})}async forwardWhisper(e,t){this.canAddressSiblings()&&await this.postRelayMessage(this.roleId.ownerKey,{frame:t,originRelay:this.roleId.relayIndex,topic:e,type:"relay_frame"})}onFlush(){return Promise.resolve()}async seedRelayShape(e,t,s,r){if(!this.canAddressSiblings())return{code:"RELAY_MISCONFIGURED",message:"relay cannot address its owner"};await this.announce();const o={args:x(s.args??{}),connectionId:this.host.readAttachment(e).connectionId,identity:r.identity,name:s.name,relayIndex:this.roleId.relayIndex,sinceEpoch:s.sinceEpoch,sinceSeq:s.sinceSeq,subId:t,type:"relay_shape_subscribe",userId:r.userId},a=await this.requestRelayMessage(this.roleId.ownerKey,o);if(a===void 0)return{code:"RELAY_SEED_FAILED",message:"owner did not answer the shape seed"};let n;try{n=await a.json()}catch{return{code:"RELAY_SEED_FAILED",message:"malformed shape seed from owner"}}if(n.error!==void 0)return n.error;if(n.frames===void 0)return{code:"RELAY_SEED_FAILED",message:"owner returned no shape frames"};await $(e);for(const l of n.frames)A(e,l);return this.recordRelayShapeMemo(e,t,n.cursor??0,n.epoch),"ok"}async announce(){if(this.relayAnnounced||!this.canAddressSiblings())return;this.relayAnnounced=!0,(await this.requestRelayMessage(this.roleId.ownerKey,{relayIndex:this.roleId.relayIndex,type:"relay_attach"}))?.ok||(this.relayAnnounced=!1)}async announceDrain(e){this.canAddressSiblings()&&(this.host.getWebSockets().some(t=>t!==e)||(this.relayAnnounced=!1,await this.postRelayMessage(this.roleId.ownerKey,{relayIndex:this.roleId.relayIndex,type:"relay_detach"})))}relayCount(){return 0}isShapeRelayUniform(){return!1}minShapeCursor(){}onAttach(){}onDetach(){}onWhisperFrame(){return Promise.resolve()}onShapeSubscribe(){return{error:{code:"RELAY_CANNOT_SEED",message:"a relay has no op-log to seed from"}}}onShapePoke(e){return this.deliverShapePoke(e)}recordRelayShapeMemo(e,t,s,r){let o=this.shapeRelayMemos.get(e);o===void 0&&(o=new Map,this.shapeRelayMemos.set(e,o)),o.set(t,{cursor:s,epoch:r})}deliverShapePoke(e){const t=R(e.name,e.args);let s=0;for(const r of this.host.getWebSockets()){const o=this.host.readAttachment(r),{shapes:a}=o,n=this.shapeRelayMemos.get(r);if(!(a===void 0||n===void 0)&&!(e.targetConnectionId!==void 0&&o.connectionId!==e.targetConnectionId))for(const[l,i]of Object.entries(a)){const d=n.get(l);if(R(i.name,i.args)!==t||!X(d,e))continue;const p=T([{baseCheckpoint:d?.cursor,rowsPatch:e.rowsPatch,shapeId:l}],{baseCheckpoint:void 0,checkpoint:e.checkpoint,epoch:e.epoch,lastMutationId:void 0,pokeId:this.host.nextPokeId()},{preEncoded:!0});for(const y of p)A(r,y);n.set(l,{cursor:e.checkpoint,epoch:e.epoch}),s+=1}}return s}}const ie=c=>{const e=c.doName();if(e===void 0)return;const t=F(e);return t===void 0?new V(c,e):new Q(c,t.ownerKey,t.relayIndex)};export{z as DEFAULT_MAX_RELAYS,V as OwnerRelay,Q as RelayMember,ie as createRelayLink};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as m}from"@lunora/errors";import{stableWireKey as a}from"./stableWireKey-9bjKL5Gy.mjs";const i="::relay::",f=(t,n)=>`${t}${i}${String(n)}`,s=t=>{const n=t.lastIndexOf(i);if(n===-1)return;const o=t.slice(0,n),e=t.slice(n+i.length),r=Number(e);if(!(o.length===0||!Number.isInteger(r)||r<0||String(r)!==e))return{ownerKey:o,relayIndex:r}},d=(t,n)=>a({args:n??{},name:t}),c={tDown:4e3,tUp:8e3},l=(t,n,o=c)=>{if(o.tDown>=o.tUp)throw new m("INTERNAL",`invalid promotion thresholds: tDown (${String(o.tDown)}) must be < tUp (${String(o.tUp)})`);return t==="owned"?n>=o.tUp?"promoted":"owned":n<o.tDown?"owned":"promoted"},g=(t,n)=>n<t?{tDown:n,tUp:t}:{tDown:Math.min(Math.max(1,Math.floor(t/2)),t-1),tUp:t},N=(t,n,o)=>{if(t<=n||n<=0)return 0;const e=t-n,r=Math.ceil(e/n);return Math.min(r,Math.max(0,o))};export{c as DEFAULT_PROMOTION_THRESHOLDS,i as RELAY_NAME_INFIX,g as clampPromotionThresholds,l as nextPromotionState,s as parseRelayName,N as relayCountFor,f as relayName,d as shapeRoutingKey};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{toErrorBody as R,LunoraError as k}from"@lunora/errors";import{e as A}from"./wire-codec-COhOSEe4.mjs";import{readStreamRun as T,deleteStreamRun as w,claimStreamRun as _,appendStreamChunk as b,finishStreamRun as E,trimStreamRuns as y,readStreamChunks as v}from"./appendStreamChunk-8eH4HB1Q.mjs";const p=5e4,S=64*1024*1024,M=864e5,N=36e5,L=(i,e)=>{const r=i?.startedAt??e.live?.generation;return e.resuming&&e.generation!==void 0&&r!==void 0&&e.generation!==r?"interrupted":e.live!==void 0?"attach":i===void 0?e.resuming?"interrupted":"attach":i.status==="complete"||i.status==="error"?e.resuming?"replay-terminal":"reclaim":e.resuming?"interrupted":"reclaim"},O=(i,e,r)=>{(i||r())&&e.fail({code:"STREAM_INTERRUPTED",message:i?"the run this durable stream resumed from no longer exists; start a new run":"the producer for this durable stream did not survive; start a new run"})};class I{lastTrimAt=0;runs=new Map;sql;waitUntil;constructor(e){this.sql=e.sql,this.waitUntil=e.waitUntil}async attach(e){try{await this.attachOrThrow(e)}catch(r){const{body:t,redacted:o}=R(r,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"internal error"});o&&console.error("[@lunora/shard-engine] durable stream attach failed:",r),e.sink.fail({code:t.code,message:t.message})}}detach(e,r){this.runs.get(e)?.sinks.delete(r)}isLive(e){return this.runs.has(e)}async attachOrThrow(e){const r=this.sql(),{runKey:t,sinceChunk:o,sink:c}=e,n=T(r,t),u=o>0,s=this.runs.get(t),a=n?.startedAt??s?.generation,l=L(n,{generation:e.generation,live:s,resuming:u}),d=()=>{for(const g of v(r,t,o))if(!c.chunk({data:JSON.parse(g.dataJson),generation:a,seq:g.seq}))return!1;return!0};if(l==="replay-terminal"){d()&&(n?.status==="error"?c.fail({code:n.errorCode??"INTERNAL_SERVER_ERROR",message:n.error??"stream failed"}):c.complete());return}if(l==="interrupted"){O(e.generation!==void 0&&a!==void 0&&e.generation!==a,c,d);return}if(s){d()&&s.sinks.add(c);return}l==="reclaim"&&w(r,t),this.trim(r);const m=Math.max(Date.now(),n===void 0?0:n.startedAt+1);_(r,t,m,e.ttlMs??M);const h={generation:m,sinks:new Set([c])};this.runs.set(t,h);const f=this.produce(t,e.iterator,h);this.waitUntil?.(f),await f}async produce(e,r,t){const o=this.sql(),c=new AbortController;let n=0,u=0;try{for await(const s of r(c.signal)){const a=A(s),l=JSON.stringify(a);if(n+=1,u+=l.length,n>p||u>S)throw new k("STREAM_TOO_LONG",`durable stream exceeded its ceiling (${String(p)} chunks / ${String(S)} bytes); yield less, or drop \`durable\``,{status:507});b(o,e,n,l);for(const d of t.sinks)d.chunk({data:a,generation:t.generation,seq:n})||t.sinks.delete(d)}E(o,e,"complete",n);for(const s of t.sinks)s.complete()}catch(s){const{body:a,redacted:l}=R(s,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"internal error"});l&&console.error("[@lunora/shard-engine] unhandled durable stream error:",s),E(o,e,"error",n,{code:a.code,message:a.message});for(const d of t.sinks)d.fail({code:a.code,message:a.message})}finally{this.runs.delete(e)}}trim(e){const r=Date.now();if(!(r-this.lastTrimAt<=N)){this.lastTrimAt=r;try{y(e,r)}catch{}}}}export{I as DurableStreamRunner,S as MAX_DURABLE_STREAM_BYTES,p as MAX_DURABLE_STREAM_CHUNKS,L as decideDurableAttach};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as $}from"@lunora/errors";import{c as on,q as ot,S as rn,l as Me,a as sn}from"./ctx-db-companions-CN8hWTF_.mjs";import{sql as i}from"drizzle-orm";import{d as cn}from"./wire-codec-COhOSEe4.mjs";import{throwingScheduler as an,aggregateSqlFunction as De,normalizeCountArgument as dn}from"./AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs";import{aggregateTableName as je,encodeAggregateKey as Ke,readAggregateValue as Qe}from"./aggregateTableName-CGi8gxeK.mjs";import{mergeWhere as Q,CountRlsUnsupportedError as ze,selectIndexForGroupBy as ln,selectIndexForCount as un,selectIndexForAggregate as fn}from"./CountRlsUnsupportedError-Bdfupt3g.mjs";import{backfillSearchIndexesForTable as hn}from"./backfillAggregateIndexes-BCLXdiIS.mjs";import{backfillAggregateIndexes as ur,backfillRankIndexes as fr,backfillSearchIndexes as hr}from"./backfillAggregateIndexes-BCLXdiIS.mjs";import{appendCdcChange as wn}from"./CDC_LOG_TABLE-gl0FuepJ.mjs";import{CDC_LOG_TABLE as pr,applyCdcChanges as gr,bumpCdcEpoch as $r,cdcCanVouchFor as yr,cdcSeqLeavingRows as Er,cdcTouchesTables as mr,cdcTrimmedError as Sr,compactCdcDocs as _r,cursorBelowRetainedFloor as Tr,minCdcReplayableSeq as Rr,minCdcSeq as vr,readCdcChangeKeys as Ar,readCdcChanges as Ir,readCdcCursor as Cr,readCdcEpoch as xr,trimCdcChanges as br}from"./CDC_LOG_TABLE-gl0FuepJ.mjs";import{allocateCommitSeq as pn,COMMIT_SEQ_FIELD as gn}from"./COMMIT_SEQ_FIELD-BUdOMG5y.mjs";import{isMemoryTable as $n}from"./clearMemoryTables-BGbmag2i.mjs";import{computeRankPage as Et}from"./computeRankPage-BxtyiLn9.mjs";import{SCAN_DEP as G}from"./SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as O,runSql as me}from"./runDrizzle-2ULFQR_k.mjs";import{D as ne,k as se,r as de,b as ke,A as Je,a as Le,e as Y,t as Pt,j as We,q as mt,i as yn,h as Gt,g as En}from"./do-sql-bkXQEBl8.mjs";import{renderSql as Ht,unionAll as rt,WORKERD_SQLITE_LIMITS as Nt,sqliteInList as mn}from"./param-DlozcSQu.mjs";import{coveringGeohashes as Sn,boundingBoxGeohashes as _n,haversineMeters as Tn,pointInBoundingBox as Rn}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{NotFoundError as vn}from"./NotFoundError-BhF7FeFr.mjs";import{softDeleteScope as ae,normalizeOrderKeys as Ze,buildSeekWhere as Ot,decodeCursor as et,applySelect as St,encodeCursor as tt,tiebreakDirectionFor as An,buildSeekBeforeWhere as In}from"./CURSOR_PREFIX-D4DUGY5z.mjs";import{rankTableName as _t,sortColumnName as Tt,resolveRankPartition as Cn,encodePartitionKey as xn,RANK_TIEBREAK as bn}from"./RANK_TIEBREAK-D157XEqw.mjs";import{indexKeysForRow as Mn,buildIndexRange as Dn}from"./buildIndexRange-CBKQmHSS.mjs";import{assertFlatPredicate as Ve,resolveRelationPredicates as Rt}from"./DEFAULT_MAX_RELATION_KEYS-B3krmwZL.mjs";import{runRowValidators as Ye,resolveWith as vt,relationHooks as At,applyOnDelete as kn,fanOutScalarCounts as Ln}from"./applyOnDelete-9f4D4g1z.mjs";import{guardWriter as Fn}from"./RLS_UNWRAP_SYMBOL-BWloGsd3.mjs";import{quoteIdentifier as Se}from"./quoteIdentifier-CObIFRhb.mjs";import{i as qn}from"./sql-projection-BqmxFxQU.mjs";import{createSystemReader as Wn}from"./createSystemReader-DcDLFfC-.mjs";import{ConflictError as ye}from"./ConflictError-C8GtJmjS.mjs";import{runTriggers as Bn}from"./hasTrigger-CjlwI4le.mjs";import{c as te,t as Ue,r as Be,j as Ee,i as It}from"./where-sql-D6MSVjdL.mjs";import{CLIENT_WATERMARK_TABLE as Dr,advanceClientWatermark as kr,migrateClientWatermark as Lr,readClientWatermark as Fr}from"./CLIENT_WATERMARK_TABLE-CRnrAnJ2.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as Wr,deleteGlobalShapeSnapshot as Br,deleteGlobalShapeSnapshotsForConnection as Ur,migrateGlobalShapeSnapshot as Pr,readGlobalShapeSnapshot as Gr,writeGlobalShapeSnapshot as Hr}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-DSA6mzyx.mjs";import{IDEMPOTENCY_TABLE as Or,readIdempotent as jr,trimIdempotent as Kr,writeIdempotent as Qr}from"./IDEMPOTENCY_TABLE-DOpm_oMF.mjs";import{runShardMigrations as Jr}from"./runShardMigrations-D6rTX7Bn.mjs";import{SEARCH_STATE_TABLE as Yr}from"./SEARCH_STATE_TABLE-BCqn5ksa.mjs";import{selectShapeMembers as Zr,selectShapeRows as ei}from"./selectShapeMembers-Dva-Z9VQ.mjs";import{serializeSqlValue as oe}from"./serializeSqlValue-DbI1VQYM.mjs";const Un=o=>{const r=atob(o),t=Uint8Array.from(r,a=>a.codePointAt(0)??0);return new TextDecoder().decode(t)},Pn=()=>new $("BAD_REQUEST","invalid cursor"),Ct=16,xt=8,X=1024,it=(o,r)=>r.query(o),Gn=(o,r)=>{if(o.length===0)return 0;let t=0;for(const[a,l]of r.entries()){const p=a===r.length-1;let E=0;for(const S of o)(p?S.startsWith(l):S===l)&&(E+=1);if(E===0)return 0;t+=E}return t},Hn=(o,r)=>{if(!r)return{exact:!0,lower:o,upper:o};const t=[...o].at(-1)??"",a=(t.codePointAt(0)??0)+1;if(a>=55296&&a<=57343||a>1114111)return{exact:!0,lower:o,upper:o};const l=o.slice(0,o.length-t.length);return{exact:!1,lower:o,upper:l+String.fromCodePoint(a)}},Nn=(o,r,t)=>{const a={eq:(l,p)=>{if(!o.definition.filterFields?.includes(l))throw new $("INTERNAL",`field "${l}" is not a filter field of search index "${o.indexName}" on table "${r}"`);if(o.filters.length>=xt)throw new $("BAD_REQUEST",`search index "${o.indexName}" on table "${r}": at most ${String(xt)} .eq() filters are supported per search query`);return o.filters.push({field:l,value:p}),a},search:(l,p)=>{const E=o;if(l!==E.definition.field)throw new $("INTERNAL",`search index "${E.indexName}" on table "${r}" indexes "${E.definition.field}", not "${l}"`);const S=it(p,t).length;if(S>Ct)throw new $("BAD_REQUEST",`search index "${E.indexName}" on table "${r}": at most ${String(Ct)} search terms are supported (got ${String(S)})`);return E.field=l,E.query=p,E.hasQuery=!0,a}};return a},On=o=>{if(o.length>X)throw new $("BAD_REQUEST",`more than ${String(X)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},jn=o=>Math.min(o.offset+o.numItems+1,X),Kn=o=>btoa(`search:${String(o)}`),Qn=o=>{let r;try{r=Un(o)}catch{return}if(!r.startsWith("search:"))return;const t=Number(r.slice(7));return Number.isInteger(t)&&t>=0?t:void 0},zn=o=>{if(typeof o.endCursor=="string")throw new $("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");if(!Number.isFinite(o.numItems))throw new $("BAD_REQUEST",`search pagination needs a finite numItems, got ${String(o.numItems)}`);const r=Math.max(0,Math.floor(o.numItems)),t=o.cursor?Qn(o.cursor):0;if(t===void 0)throw Pn();if(t+r>=X)throw new $("BAD_REQUEST",`search pagination reaches the ${String(X)}-document limit (offset ${String(t)} + ${String(r)} requested) — a page must end below the cap so the probe row that answers \`hasMore\` still fits: retry with numItems ${String(Math.max(1,X-t-1))} or fewer, or narrow the query or the filters instead`);return{numItems:r,offset:t}},Jn=(o,r)=>{const t=r.offset+r.numItems,a=r.numItems>0&&o.length>t;return{continueCursor:a?Kn(t):null,isDone:!a,page:o.slice(r.offset,t)}},Vn=o=>{if(o===void 0)return X+1;if(!Number.isFinite(o))return X;const r=Math.max(0,Math.floor(o));if(r>X)throw new $("BAD_REQUEST",`search returns at most ${String(X)} documents (asked for ${String(r)}) — narrow the query or paginate instead`);return r},Pe=o=>{const r=new Map;return t=>{const a=r.get(t);if(a!==void 0)return a;const l=o(Se(t));return r.set(t,l),l}},le=Se(ne),Yn=Pe(o=>`INSERT INTO ${o} (id, _creationTime, ${le}) VALUES (?, ?, ?)`),bt=Pe(o=>`UPDATE ${o} SET ${le} = ? WHERE id = ? AND ${le} = ?`),Xn=Pe(o=>`UPDATE ${o} SET _creationTime = ?, ${le} = ? WHERE id = ? AND ${le} = ?`),Zn=Pe(o=>`DELETE FROM ${o} WHERE id = ? AND ${le} = ?`),eo="SELECT changes() AS changed",Mt=new Map,to="",no=o=>{const r=JSON.stringify(o),t=Mt.get(r);if(t!==void 0)return t;const a=o.map(p=>i`SELECT ${i.raw(`'${p.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${i.identifier(ne)} FROM ${i.identifier(p)} WHERE id = ${to}`),{sql:l}=Ht("sqlite",i`${rt(a)} LIMIT 1`);return Mt.set(r,l),l},oo=(o,r)=>r.map(()=>o),ro=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,io=o=>{if(!ro.test(o))throw new $("INTERNAL",`invalid clientId ${JSON.stringify(o)}: a client-supplied row id must be a UUID`)},Dt=50,jt=500,Fe=Math.floor(Nt.boundParams/3),ge=Nt.boundParams,so=128,ce=(o,r,t)=>{const a=r??jt;if(o>a)throw new $("BATCH_LIMIT_EXCEEDED",`${t}: batch of ${String(o)} exceeds the limit of ${String(a)} (raise options.limit or chunk the call)`,{status:400})},co=o=>{const r={eq:(t,a)=>(o.sqlConditions.push({comparator:"=",field:t,value:a}),r),gt:(t,a)=>(o.sqlConditions.push({comparator:">",field:t,value:a}),r),gte:(t,a)=>(o.sqlConditions.push({comparator:">=",field:t,value:a}),r),lt:(t,a)=>(o.sqlConditions.push({comparator:"<",field:t,value:a}),r),lte:(t,a)=>(o.sqlConditions.push({comparator:"<=",field:t,value:a}),r)};return r},ao=o=>Math.max(o,X),Kt=(o,r)=>{const t=o.filters.map(a=>i`${Y(a.field)} = ${oe(a.value)}`);return r&&t.push(r),t},lo=(o,r,t,a,l)=>{const p=it(t.query,ot(t.definition.language));if(p.length===0)return[];const E=rn(r,t.indexName),S=`${E}__vocab`,T=p.length-1,L=p.map((F,M)=>{const q=Hn(F,M===T),z=q.exact?i`${i.identifier("term")} = ${q.lower}`:i`${i.identifier("term")} >= ${q.lower} AND ${i.identifier("term")} < ${q.upper}`;return i`SELECT ${i.identifier("doc")}, ${i.raw(String(M))} AS ${i.identifier("__term__")}, COUNT(*) AS ${i.identifier("__n__")} FROM ${i.identifier(S)} WHERE ${z} GROUP BY ${i.identifier("doc")}`}),y=p.map((F,M)=>i`SUM(CASE WHEN u.${i.identifier("__term__")} = ${i.raw(String(M))} THEN u.${i.identifier("__n__")} ELSE 0 END)`),A=i`SELECT f.${i.identifier(Me)} AS ${i.identifier(Me)}, ${i.join(y,i` + `)} AS ${i.identifier("__score__")} FROM (${rt(L)}) u JOIN ${i.identifier(E)} f ON f.rowid = u.${i.identifier("doc")} GROUP BY f.${i.identifier(Me)} HAVING ${i.join(y.map(F=>i`${F} > 0`),i` AND `)}`,v=Kt(t,l);let _=i`SELECT m.id, m._creationTime, m.${i.identifier(ne)}, s.${i.identifier("__score__")} AS ${i.identifier("__score__")} FROM (${A}) s JOIN ${i.identifier(r)} m ON m.id = s.${i.identifier(Me)}`;v.length>0&&(_=i`${_} WHERE ${i.join(v,i` AND `)}`),_=i`${_} ORDER BY s.${i.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${i.raw(String(a))}`;const H=[];for(const F of O(o,_)){const M=Gt(F);if(M){const q=F.__score__;H.push({document:M,score:typeof q=="number"?q:Number(q??0)})}}return H},uo=(o,r,t,a,l)=>{const p=ot(t.definition.language),E=it(t.query,p);if(E.length===0)return[];const S=Kt(t,l);let T=i`SELECT id, _creationTime, ${i.identifier(ne)} FROM ${i.identifier(r)}`;S.length>0&&(T=i`${T} WHERE ${i.join(S,i` AND `)}`),T=i`${T} ORDER BY _creationTime DESC, id ASC LIMIT ${i.raw(String(ao(a)))}`;const L=O(o,T).toArray(),y=[];for(const A of L){const v=Gt(A);if(!v)continue;const _=Gn(sn(v,t.definition),E);_>0&&y.push({creationTime:typeof v._creationTime=="number"?v._creationTime:0,doc:v,id:typeof v._id=="string"?v._id:"",score:_})}return y.sort((A,v)=>v.score-A.score||v.creationTime-A.creationTime||A.id.localeCompare(v.id)),y.slice(0,a).map(A=>({document:A.doc,score:A.score}))},Xe=(o,r,t,a)=>{if(!Number.isFinite(o.lat)||o.lat<-90||o.lat>90||!Number.isFinite(o.lng)||o.lng<-180||o.lng>180)throw new $("BAD_REQUEST",`geo index "${a}" on table "${t}": ${r} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},fo=(o,r)=>{const t=o,a={near:(l,p)=>{if(t.within)throw new $("INTERNAL",`geo index "${t.indexName}" on table "${r}": call .near() or .within(), not both`);if(Xe(l,".near() point",r,t.indexName),!Number.isFinite(p)||p<=0)throw new $("BAD_REQUEST",`geo index "${t.indexName}" on table "${r}": .near() radiusMeters must be a finite number > 0, got ${String(p)}`);return t.near={point:{lat:l.lat,lng:l.lng},radiusMeters:p},a},within:l=>{if(t.near)throw new $("INTERNAL",`geo index "${t.indexName}" on table "${r}": call .near() or .within(), not both`);if(Xe(l.sw,".within() sw corner",r,t.indexName),Xe(l.ne,".within() ne corner",r,t.indexName),l.sw.lat>l.ne.lat)throw new $("BAD_REQUEST",`geo index "${t.indexName}" on table "${r}": .within() corners are transposed (sw.lat > ne.lat)`);if(l.sw.lng>l.ne.lng)throw new $("BAD_REQUEST",`geo index "${t.indexName}" on table "${r}": .within() box crosses the antimeridian (sw.lng > ne.lng), which is not supported — split it into two boxes at ±180 and union the results`);return t.within={ne:{lat:l.ne.lat,lng:l.ne.lng},sw:{lat:l.sw.lat,lng:l.sw.lng}},a}};return a},ho=(o,r)=>{const t=o[r];if(t===null||typeof t!="object")return;const{lat:a,lng:l}=t;return typeof a=="number"&&typeof l=="number"?{lat:a,lng:l}:void 0},wo=(o,r)=>{const t=ho(o,r.definition.field);if(!t)return;const a=typeof o._creationTime=="number"?o._creationTime:0;if(r.near){const l=Tn(r.near.point,t);return l<=r.near.radiusMeters?{creationTime:a,distance:l}:void 0}return Rn(t,r.within)?{creationTime:a,distance:0}:void 0},po=(o,r,t,a)=>{if(!t.near&&!t.within)throw new $("INTERNAL",`geo index "${t.indexName}" on table "${r}": call .near(point, radius) or .within(box)`);const l=t.near?Sn(t.near.point,t.near.radiusMeters):_n(t.within),p=En(r,t.indexName),E=l.map(A=>i`(g.${i.identifier("__geohash__")} >= ${A} AND g.${i.identifier("__geohash__")} < ${`${A}{`})`),S=[i`(${i.join(E,i` OR `)})`];a&&S.push(a);const T=i`SELECT m.id, m._creationTime, m.${i.identifier(ne)} FROM ${i.identifier(p)} g JOIN ${i.identifier(r)} m ON m.id = g.${i.identifier("__id__")} WHERE ${i.join(S,i` AND `)}`,L=O(o,T).toArray(),y=[];for(const A of L){const v=de(A),_=v?wo(v,t):void 0;v&&_&&y.push({creationTime:_.creationTime,distance:_.distance,doc:v})}return y.sort((A,v)=>A.distance-v.distance||v.creationTime-A.creationTime),y},Qt=(o,r,t,a)=>{const l=[];for(const p of o)if(r.every(E=>E(a(p)))&&(l.push(p),typeof t=="number"&&l.length>=t))break;return l},go=(o,r,t,a,l,p=()=>{})=>{const E=t.within!==void 0,S=po(o,r,t,l).map(T=>({distanceMeters:E?null:T.distance,document:T.doc}));return p(S.length),typeof a=="number"?S.slice(0,Math.max(0,Math.floor(a))):S},zt=(o,r,t,a,l,p=()=>{})=>{const{geo:E}=t;if(!E)throw new $("INTERNAL","runGeoTerminalScored called without a staged geo query");const S=t.inMemoryFilters.length>0,T=go(o,r,E,S?void 0:l,a,p);return S?Qt(T,t.inMemoryFilters,l,L=>L.document):T},Jt=(o,r,t,a)=>{const l=`SELECT id, _creationTime, ${Se(ne)} FROM ${Se(o)}`,p=`ORDER BY ${t}${a===void 0?"":` LIMIT ${String(a)}`}`;return r===void 0?Be(`${l} ${p}`):Ee(`${l} WHERE `,r,` ${p}`)},$o=(o,r,t,a,l,p=()=>{})=>zt(o,r,t,a,l,p).map(E=>E.document),yo=(o,r,t,a,l,p,E=()=>{})=>{const S=[];for(const A of t.sqlConditions)S.push(i`${Y(A.field)} ${i.raw(A.comparator)} ${oe(A.value)}`);a&&S.push(a);let T=i`SELECT id, _creationTime, ${i.identifier(ne)} FROM ${i.identifier(r)}`;S.length>0&&(T=i`${T} WHERE ${i.join(S,i` AND `)}`),T=i`${T} ORDER BY ${l}`,typeof p=="number"&&t.inMemoryFilters.length===0&&(T=i`${T} LIMIT ${i.raw(String(Math.max(0,Math.floor(p))))}`);const L=O(o,T).toArray();E(L.length);const y=[];for(const A of L){const v=de(A);if(v&&t.inMemoryFilters.every(_=>_(v))&&(y.push(v),typeof p=="number"&&y.length>=p))break}return y},$e={fieldRef:Y,serialize:oe},Vt=(o,r)=>{const t=r===void 0?void 0:o.shape[r];return t!==void 0&&qn(t)},kt=(o,r)=>r.some(t=>Vt(o,t)),Lt=(o,r,t)=>{if(Vt(o,r))throw new $("BAD_REQUEST",`${t}: "${r}" is stored as an order-preserving key, which SQL cannot reduce or group — declare an aggregateIndex covering this (by, field, op) so the maintained companion answers it`)},st={fieldRef:o=>Be(We(o)),serialize:oe},Eo=o=>{let r=0;const t=[],a={fieldRef:l=>Be(We(l)),relationExists:l=>{const{childWhere:p,negated:E,parentTable:S,relation:T}=l,L=`__rel_${String(r)}`,y=t.at(-1)??S;r+=1,o(T.table,G);const A=T.kind==="one"?T.field:T.references,v=T.kind==="one"?T.references:T.field,_=Be(`${mt(L,v)} = ${mt(y,A)}`);t.push(L);const H=te(p,a,Ue);t.pop();const F=H===void 0?_:Ee(_," AND ",H),M=Ee("EXISTS (SELECT 1 FROM ",It(T.table)," AS ",It(L)," WHERE ",F,")");return E?Ee("NOT ",M):M},serialize:oe};return a},Yt=o=>{const r=o.map(t=>`${We(t.field)} ${t.direction==="desc"?"DESC":"ASC"}`);return o.some(t=>t.field==="_id"||t.field==="id")||r.push(`${We("id")} ${An(o)==="desc"?"DESC":"ASC"}`),r.join(", ")},mo={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},So=(o,r)=>{const t=o.order;return o.indexFields.length>0?Ze(o.indexFields.map(a=>({[a]:t})),r):Ze([{_creationTime:t}],r)},_o=(o,r,t,a)=>{const l=o.sqlConditions.map(p=>({[p.field]:{[mo[p.comparator]??"eq"]:p.value}}));if(t&&l.push(Ot(r,et(t))),a&&l.push(In(r,et(a))),l.length!==0)return l.length===1?l[0]:{AND:l}},To=(o,r,t)=>{const a=[];for(const l of o){const p=de(l);if(p&&r.every(E=>E(p))&&(a.push(p),t!==void 0&&a.length>t))break}return a},Ro=(o,r,t,a,l,p,E=()=>{})=>{const S=Math.max(0,Math.floor(l.numItems)),T=So(a,t),L=typeof l.endCursor=="string",y=te(_o(a,T,l.cursor,l.endCursor),st,Ue),A=p&&y?Ee(y," AND ",p):p??y,v=a.inMemoryFilters.length>0,_=Jt(r,A,Yt(T),v||L?void 0:S+1),H=me(o,_.text,..._.params).toArray();E(H.length);const F=To(H,a.inMemoryFilters,v||L?void 0:S);if(L){const N=F.length>=2?F[Math.floor(F.length/2)-1]:void 0;return{continueCursor:l.endCursor??null,isDone:!0,page:F,splitCursor:N?tt(N,T):null}}const M=F.length>S,q=M?F.slice(0,S):F,z=q.at(-1);return{continueCursor:M&&z?tt(z,T):null,isDone:!M,page:q}};class vo extends ${constructor(r="unique() found more than one matching document"){super("NOT_UNIQUE",r,{name:"NotUniqueError"})}}const Ao=/\s/u,Io=String.fromCodePoint(0),Ft=(o,r,t)=>{if(!o.tables[r])throw new $("INTERNAL",`unknown table: ${r}`);return typeof t!="string"||t.length===0||Ao.test(t)||t.includes(Io)?null:t},Co=(o,r,t,a=()=>{},l=()=>{},p=()=>{})=>{const E=r.tables[t];if(!E)throw new $("INTERNAL",`unknown table: ${t}`);const S=ae(E.softDeleteMode,void 0),T=S?te(S,$e):void 0,L=S?te(S,st,Ue):void 0,y={indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[]};let A=0;const v=m=>{const{search:b}=y;if(!b)throw new $("INTERNAL","runSearchFetch called without a staged search");hn(o,t,E);const I=y.inMemoryFilters.length>0,x=Vn(I?void 0:m),J=yn(o)?lo(o,t,b,x,T):uo(o,t,b,x,T);return I?(A=J.length,Qt(J,y.inMemoryFilters,m,ue=>ue.document)):(m===void 0&&On(J),J)},_=m=>v(m).map(b=>b.document),H=m=>{const b=zn(m);return Jn(_(jn(b)),b)},F=()=>{const m=y.indexFields.length>0?y.indexFields:["_creationTime"],b=y.order==="desc"?"DESC":"ASC",I=m.map(x=>i`${Y(x)} ${i.raw(b)}`);return m.includes("_creationTime")||I.push(i`${Y("_creationTime")} ${i.raw(b)}`),m.some(x=>x==="_id"||x==="id")||I.push(i`${Y("id")} ${i.raw(b)}`),i.join(I,i`, `)},M=()=>{if(y.search||y.geo||y.indexName===void 0){l(void 0);return}l(Dn(t,y.indexName,y.indexFields,y.sqlConditions,oe))},q=m=>{M();let b=0;const I=(()=>{if(y.search){const x=_(m);return b=A,x}return y.geo?$o(o,t,y,T,m,x=>{b=x}):yo(o,t,y,T,F(),m,x=>{b=x})})();return p(Math.max(b,I.length)),I},z=()=>{if(!y.search&&!y.geo)throw new $("INTERNAL",`ctx.db.query("${t}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);M();let m=0;const b=(()=>{if(y.search){const I=v(void 0);return m=A,I}return zt(o,t,y,T,void 0,I=>{m=I})})();return p(Math.max(m,b.length)),b},N={async*[Symbol.asyncIterator](){if(y.search){yield*q(void 0);return}const m=[...y.inMemoryFilters];let b;y.inMemoryFilters=[];try{for(;;){const I=await N.paginate({cursor:b??null,numItems:so});for(const x of I.page)m.every(J=>J(x))&&(yield x);if(I.isDone||I.continueCursor===null)return;b=I.continueCursor}}finally{y.inMemoryFilters=m}},async collect(){return q(void 0)},async collectWithScores(){return z()},filter(m){return y.inMemoryFilters.push(m),N},async first(){return q(y.inMemoryFilters.length>0?void 0:1)[0]??null},order(m){return y.order=m==="desc"?"desc":"asc",N},async paginate(m){let b=0;if(M(),y.search){const x=H(m);return p(x.page.length),x}if(y.geo)throw new $("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const I=Ro(o,t,E.shape,y,m,L,x=>{b=x});return p(Math.max(b,I.page.length)),I},async take(m){return q(m)},async unique(){const m=q(y.inMemoryFilters.length>0?void 0:2);if(m.length>1)throw new vo(`unique() on table "${t}" matched ${String(m.length)} documents; expected at most one`);return m[0]??null},withGeoIndex(m,b){const I=(E.geoIndexes??[]).find(J=>J.name===m);if(!I)throw new $("INTERNAL",`unknown geo index "${m}" on table "${t}"`);a(t,m,"geo");const x={definition:I,indexName:m};if(y.geo=x,b(fo(x,t)),!x.near&&!x.within)throw new $("INTERNAL",`geo index "${m}" on table "${t}" requires a .near(point, radius) or .within(box) call`);return N},withIndex(m,b){const I=E.indexes.find(x=>x.name===m);if(!I)throw new $("INTERNAL",`unknown index "${m}" on table "${t}"`);return a(t,m,"index"),y.indexName=m,y.indexFields=I.fields,b&&b(co(y)),N},withSearchIndex(m,b){const I=(E.searchIndexes??[]).find(J=>J.name===m);if(!I)throw new $("INTERNAL",`unknown search index "${m}" on table "${t}"`);a(t,m,"search");const x={definition:I,field:I.field,filters:[],hasQuery:!1,indexName:m,query:""};if(y.search=x,b(Nn(x,t,ot(I.language))),!x.hasQuery)throw new $("INTERNAL",`search index "${m}" on table "${t}" requires a .search(field, query) call`);return N}};return N},qt=(o,r,t)=>{const a={...r};for(const[l,p]of Pt(o)){if(p.serverDefault){a[l]=p.serverDefault({auth:t});continue}a[l]===void 0&&(p.defaultFn?a[l]=p.defaultFn():"defaultValue"in p&&(a[l]=p.defaultValue))}return a},Wt=(o,r,t,a)=>{const l=t;for(const[p,E]of Pt(o)){if(E.serverDefault){p in r&&(l[p]=E.serverDefault({auth:a}));continue}E.onUpdateFn&&!(p in r)&&(l[p]=E.onUpdateFn())}},Bt=(o,r)=>{for(const t of Object.keys(r))if(r[t]===void 0)throw new $("INTERNAL",`Cannot ${o} field '${t}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},xo=/unique constraint failed/i,bo=o=>o instanceof Error&&xo.test(o.message),nt=(o,r,t,a)=>{try{me(o,t,...a)}catch(l){throw bo(l)?new ye(`unique constraint violation on "${r}"`,"unique"):l}},qe=(o,r,t,a)=>{if(nt(o,r,t,a),me(o,eo).one().changed===0)throw new ye(`optimistic concurrency conflict on "${r}" — the row changed during this mutation; refetch and retry`,"occ")},Ut=(o,r,t,a,l,p,E)=>{const S=[];for(let A=0;A<t.length+1;A+=1){const v=[];for(let M=0;M<A;M+=1)v.push(i`${i.identifier(t[M])} IS ${p[M]}`);const _=t[A],H=a[A];if(_!==void 0&&H!==void 0){const M=H.direction==="desc"?">":"<";v.push(i`${i.identifier(_)} ${i.raw(M)} ${p[A]}`)}else v.push(i`${i.identifier(bn)} < ${E}`);const[F]=v;S.push(v.length===1&&F!==void 0?F:i`(${i.join(v,i` AND `)})`)}const T=i.join(S,i` OR `),L=O(o,i`SELECT COUNT(*) AS c FROM ${i.identifier(r)} WHERE ${i.identifier("__partition__")} = ${l} AND (${T})`).one(),y=O(o,i`SELECT COUNT(*) AS c FROM ${i.identifier(r)} WHERE ${i.identifier("__partition__")} = ${l}`).one();return{before:L.c,total:y.c}},ar=o=>{const{sql:r}=o,{schema:t}=o,a=o.broadcast??(()=>{});let l;const p=()=>o.inTransaction?.()===!0,E=e=>t.tables[e]?.commitOrderedMode!==!0?{}:((l===void 0||!p())&&(l=pn(r)),{[gn]:l}),S=(e,...n)=>{const s=t.tables[e]?.indexes;if(!s||s.length===0)return;const f=[];for(const h of n)h&&f.push(...Mn(s,h,oe));return f.length>0?f:void 0},{headroom:T}=o;let L=!1;const y=async e=>{const n=L;L=!0;try{return await e()}finally{L=n}},A=o.onRead??(()=>{}),v=o.onReadRange??(e=>{A(e.table,G)}),_=(e,n)=>{n!==void 0&&n!==G&&!L&&T?.recordRead(1),A(e,n)},H=o.onIndexUse??(()=>{}),F=o.onWrite??(()=>{}),M=e=>{L||T?.recordWrite(e)},q=async e=>{M(e.doc),await F(e)},{cache:z}=o,N=o.clock??(()=>Date.now()),m=o.idGenerator??(()=>crypto.randomUUID()),b=o.scheduler??an,{globalDb:I}=o,x=o.auth??{identity:null,userId:null},J=o.cdc??!1,ue=b,Xt=Wn({scheduler:typeof ue.list=="function"&&typeof ue.get=="function"?ue:void 0,storage:o.storage}),fe=(e,n,s,f)=>{J&&!$n(t.tables[e])&&wn(r,N(),e,n,s,f)},ie=e=>t.tables[e]?.shardMode?.kind==="global",ct=(e,n)=>{if(ie(e)){if(!I)throw new $("INTERNAL",`cross-backend ${n} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return I}return B},Ge=e=>ct(e,"cascade"),K=(e,n)=>{if(ie(e)){if(!I)throw new $("INTERNAL",`${n} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return I}},at=async(e,n,s,f,h)=>{h&&M(s);const u=await e.insert(n,s,f);return a({key:u,op:"insert",row:{...s,_id:u},table:n}),u},He=(e,n)=>ct(e,"relation load").findMany(e,n),dt=(e,n)=>(ie(e)&&_(e,G),He(e,n)),Zt=e=>!ie(e.table),lt=o.relationExistsPushDown??"auto",ut=lt!=="never",{maxRelationKeys:ft}=o,_e=(e,n,s)=>Rt(e,{fetcher:dt,maxRelationKeys:ft,relationBaseWhere:s,schema:t,tableName:n}),ht=async(e,n,s,f)=>{const h=K(e,"relation grouped count");if(h)return _(e,G),Ln((W,C)=>h.count(W,C),e,n,s,f);const u=t.tables[e];if(!u)throw new $("INTERNAL",`unknown table: ${e}`);_(e,G);const c=ae(u.softDeleteMode,void 0),d={[n]:{in:s}},w=Q(Q(d,f),c),R=await _e(w,e,void 0),g=te(R,$e),k=Y(n);let D=i`SELECT ${k} AS __fk__, COUNT(*) AS count FROM ${i.identifier(e)}`;g&&(D=i`${D} WHERE ${g}`),D=i`${D} GROUP BY ${k}`;const U=O(r,D).toArray();return new Map(U.map(W=>[W.__fk__,W.count]))};let Te=0;const wt=new Set;for(const[e,n]of Object.entries(t.tables))for(const s of Object.values(n.triggerMap??{}))wt.add(`${e} ${s.timing} ${s.op}`);const Z=(e,n,s)=>wt.has(`${e} ${n} ${s}`),ee=async(e,n,s)=>{if(Te+=1,Te>Dt)throw Te-=1,new ye(`trigger recursion exceeded ${String(Dt)} levels on "${s.table}" — check for a self-triggering write`,"trigger");try{await Bn({ctx:tn,event:s,op:n,schema:t,tableName:s.table,timing:e})}finally{Te-=1}},{ensureBackfilledForTable:he,ensureBackfilledIndex:Ne,ensureRankBackfilled:Oe,ensureRankBackfilledForTable:we,syncAggregates:Re,syncCompanionsForInsert:pt,syncGeo:ve,syncRanks:pe,syncSearch:Ae}=on({broadcast:a,indexKeysFor:(e,n)=>S(e,n),invalidateCache:(e,n,s)=>z?.invalidate(e,n,S(e,s)),recordCdc:fe,schema:t,sql:r}),gt=(e,n,s)=>{const{shardMode:f}=n;if(f?.kind==="shardBy"&&!(f.field!==void 0&&(s.partitionBy??[]).includes(f.field)))throw Object.assign(new Error(`rank index "${s.name}" on "${e}" partitions across shards (shard key "${f.field??"?"}" is not in partitionBy) — a shard-local rank()/rankPage() would be wrong; roll it up through the Query Coordinator instead`),{code:"CROSS_SHARD_RANK_UNSUPPORTED",name:"LunoraError",status:400})},$t=e=>Object.entries(t.tables).filter(([,n])=>n.shardMode?.kind!=="global").map(([n])=>n).filter(n=>e===void 0||n===e),re=(e,n)=>{const s=$t(n);for(let f=0;f<s.length;f+=ge){const h=s.slice(f,f+ge),[u]=me(r,no(h),...oo(e,h)).toArray();if(!u)continue;const c=u.__t__,d=de(u);if(typeof c!="string"||!d)return;const w=u[ne];return{docJson:typeof w=="string"?w:se(w??{}),row:d,tableName:c}}},en=(e,n)=>{const s=[...new Set(e)],f=new Map;if(s.length===0)return f;const h=$t(n);for(let u=0;u<h.length;u+=ge){const c=h.slice(u,u+ge),d=Math.floor(ge/c.length),w=mn(i`${i.identifier("id")}`,s,!1,d),R=c.map(g=>i`SELECT ${i.raw(`'${g.replaceAll("'","''")}'`)} AS __t__, id FROM ${i.identifier(g)} WHERE ${w}`);for(const g of O(r,rt(R))){const{id:k,__t__:D}=g;typeof D=="string"&&typeof k=="string"&&f.set(k,D)}}return f},yt={assertRankPartitionLocal:gt,ensureRankBackfilled:Oe,onRead:_,rowToDocument:de,schema:t,sql:r},B={system:Xt,async aggregate(e,n){const s=K(e,"aggregate");if(s)return _(e,G),s.aggregate(e,n);const f=t.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);if(De(n.op),n.op==="count")return B.count(e,{baseWhere:n.baseWhere,relationBaseWhere:n.relationBaseWhere,restrictsCounts:n.restrictsCounts,where:n.where});if(!n.field)throw new $("INTERNAL",`aggregate(${e}, { op: "${n.op}" }): "field" is required for non-count reducers`);_(e,G);const h=ae(f.softDeleteMode,void 0),u=Q(Q(n.baseWhere,n.where),h),c=await _e(u,e,n.relationBaseWhere),d=c!==u;if(f.aggregateIndexes&&!n.baseWhere&&!d&&(!h||kt(f,[n.field]))){const W=fn(f.aggregateIndexes,n.op,n.field,n.where);if(W){Ne(e,W.index);const C=Ke(W.index.by??[],W.key),j=je(e,W.index.name),V=O(r,i`SELECT ${ke} AS value, ${Je} AS count FROM ${i.identifier(j)} WHERE ${Le} = ${C}`).toArray()[0];return Qe(n.op,V)}}Lt(f,n.field,`aggregate(${e}, { op: "${n.op}", field: "${n.field}" })`);const w=te(c,$e),R=De(n.op),g=Y(n.field);let k=i`SELECT ${i.raw(R)}(${g}) AS value FROM ${i.identifier(e)}`;w&&(k=i`${k} WHERE ${w}`);const U=O(r,k).toArray()[0]?.value;return U??null},asId(e,n){const s=Ft(t,e,n);if(s===null)throw new $("BAD_REQUEST",`asId("${e}", …): "${n}" is not a valid id for table "${e}"`,{status:400});return s},async count(e,n){const s=K(e,"count");if(s)return _(e,G),s.count(e,n);const f=t.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);const h=dn(n);if(h.restrictsCounts)throw new ze(e);_(e,G);const u=ae(f.softDeleteMode,void 0),c=Q(Q(h.baseWhere,h.where),u),d=await _e(c,e,h.relationBaseWhere),w=d!==c;if(f.aggregateIndexes&&!h.baseWhere&&!w&&!u){const D=un(f.aggregateIndexes,h.where);if(D){Ne(e,D.index);const U=Ke(D.index.by??[],D.key),W=je(e,D.index.name),C=O(r,i`SELECT ${ke} AS value FROM ${i.identifier(W)} WHERE ${Le} = ${U}`).toArray();return C[0]===void 0?0:C[0].value??0}}const R=te(d,$e);let g=i`SELECT COUNT(*) AS count FROM ${i.identifier(e)}`;return R&&(g=i`${g} WHERE ${R}`),O(r,g).one().count},async delete(e,n,s){const f=re(e,n);if(!f){const g=n===void 0?I:void 0;g&&(M(void 0),await g.delete(e,void 0,s));return}const{docJson:h,row:u,tableName:c}=f,d=t.tables[c],w=s?.hard===!0,R=!w&&d?.softDeleteMode?d.softDeleteMode.field:void 0;if(!(R&&u[R]!==null&&u[R]!==void 0)){if(Z(c,"before","delete")&&await ee("before","delete",{id:e,op:"delete",previous:u,table:c}),await kn({deletedId:e,deletedReference:g=>u[g],findHolders:async(g,k,D)=>(await Ge(g).findMany(g,{includeDeleted:w,where:{[k]:D}})).page,onCascade:(g,k)=>Ge(g).delete(k,void 0,s),onRestrict:g=>{throw new ye(g,"restrict")},onSetNull:(g,k,D)=>Ge(g).patch(k,{[D]:null}),schema:t,tableName:c}),he(c),we(c),R){const g={...u,...E(c),[R]:N(),_id:e};qe(r,c,bt(c),[se(g),e,h]),Ae(c,e,g,u),ve(c,e,void 0),Re(c,u,g),pe(c,e,u,void 0),z?.invalidate(c,e,S(c,u,g)),fe(c,e,"update",g),a({indexKeys:S(c,u,g),key:e,op:"update",row:g,table:c}),Z(c,"after","delete")&&await ee("after","delete",{id:e,op:"delete",previous:u,table:c}),await q({id:e,op:"delete",table:c});return}qe(r,c,Zn(c),[e,h]),Ae(c,e,void 0),ve(c,e,void 0),Re(c,u,void 0),pe(c,e,u,void 0),z?.invalidate(c,e,S(c,u)),fe(c,e,"delete"),a({indexKeys:S(c,u),key:e,op:"delete",table:c}),Z(c,"after","delete")&&await ee("after","delete",{id:e,op:"delete",previous:u,table:c}),await q({id:e,op:"delete",table:c})}},async deleteAll(e,n){if(!t.tables[e])throw new $("INTERNAL",`unknown table: ${e}`);const s=Math.max(1,n?.chunkSize??jt),f=n?.hard===void 0?void 0:{hard:n.hard},h=ie(e)?void 0:e;let u=0;return await y(async()=>{for(;;){const d=(await B.findMany(e,{limit:s})).page.map(w=>String(w._id));if(d.length===0)break;for(const w of d)await B.delete(w,h,f),u+=1;if(d.length<s)break}}),{deleted:u}},async deleteMany(e,n,s){ce(e.length,n?.limit,"deleteMany");for(const f of e)await B.delete(f,s);return{deleted:e.length}},async deleteWhere(e,n,s){const u=(await(K(e,"deleteWhere")??B).findMany(e,{where:n})).page.map(c=>String(c._id));if(ce(u.length,s?.limit,"deleteWhere"),B.deleteMany===void 0)throw new $("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return B.deleteMany(u,s)},async findFirst(e,n={}){return(await B.findMany(e,{...n,limit:1,omitContinueCursor:!0})).page[0]??null},async findFirstOrThrow(e,n={}){const s=await B.findFirst(e,n);if(s===null)throw new vn(`findFirstOrThrow: no "${e}" document matched`);return s},async findMany(e,n={}){const s=K(e,"findMany");if(s)return _(e,G),s.findMany(e,n);const f=t.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);const h=!n.where&&!n.baseWhere;h?_(e,G):_(e);const u=Ze(n.orderBy,f.shape),c=n.cursor?Ot(u,et(n.cursor)):void 0;let d=Q(n.baseWhere,n.where);d=Q(d,ae(f.softDeleteMode,n.includeDeleted)),d=await Rt(d,{canPushExists:ut?Zt:void 0,existsPushMode:lt==="always"?"always":"auto",fetcher:dt,maxRelationKeys:ft,relationBaseWhere:n.relationBaseWhere,schema:t,tableName:e}),c&&(d=d?{AND:[d,c]}:c);const w=ut?Eo(_):st,R=te(d,w,Ue),g=typeof n.limit=="number"?Math.max(0,Math.floor(n.limit)):void 0,k=Jt(e,R,Yt(u),g===void 0?void 0:g+1),D=me(r,k.text,...k.params).toArray();h&&!L&&T?.recordRead(D.length);const U=[];for(const V of D){const P=de(V);P&&(U.push(P),!h&&typeof P._id=="string"&&_(e,P._id))}if(g===void 0)return n.with&&await vt({groupedCounter:ht,fetcher:He,parents:U,...At(n),schema:t,tableName:e,with:n.with}),{continueCursor:null,isDone:!0,page:St(U,n.select,n.with)};const W=U.length>g,C=W?U.slice(0,g):U,j=C.at(-1);return n.with&&await vt({fetcher:He,groupedCounter:ht,parents:C,...At(n),schema:t,tableName:e,with:n.with}),{continueCursor:W&&j&&n.omitContinueCursor!==!0?tt(j,u):null,isDone:!W,page:St(C,n.select,n.with)}},async get(e,n){const s=re(e,n);if(!s){const f=n===void 0?I:void 0;return f?f.get(e):null}return _(s.tableName,e),s.row},async lookupById(e,n){const s=re(e,n);return s?(_(s.tableName,e),{row:s.row,tableName:s.tableName}):null},async groupBy(e,n){const s=K(e,"groupBy");if(s)return _(e,G),s.groupBy(e,n);const f=t.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);_(e,G);const h=n.agg??{op:"count"};if(De(h.op),h.op!=="count"&&!h.field)throw new $("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);const u=ae(f.softDeleteMode,void 0),c=Q(Q(n.baseWhere,n.where),u),d=await _e(c,e,n.relationBaseWhere),w=d!==c,R=[...n.by,h.field];if(f.aggregateIndexes&&!n.baseWhere&&!w&&(!u||kt(f,R))){const C=ln(f.aggregateIndexes,h.op,h.field,n.by,n.where),j=C===void 0?0:Object.keys(C.partial).length,V=C?.index.by?.length??0;if(C&&(j===0||j===V)){Ne(e,C.index);const P=je(e,C.index.name),Ie=Object.keys(C.partial),Ce=[];if(Ie.length===(C.index.by??[]).length&&Ie.length>0){const xe=Ke(C.index.by??[],C.partial),be=O(r,i`SELECT ${ke} AS value, ${Je} AS count FROM ${i.identifier(P)} WHERE ${Le} = ${xe}`).toArray();return be.length>0&&Ce.push({key:{...C.partial},value:Qe(h.op,be[0])}),Ce}const nn=O(r,i`SELECT ${Le} AS key, ${ke} AS value, ${Je} AS count FROM ${i.identifier(P)}`).toArray();for(const xe of nn){const be=cn(JSON.parse(xe.key));Ce.push({key:be,value:Qe(h.op,xe)})}return Ce}}for(const C of R){if(C===void 0)continue;const j=C===h.field?`groupBy(${e}, { agg: { op: "${h.op}", field: "${C}" } })`:`groupBy(${e}, { by: [..."${C}"] })`;Lt(f,C,j)}const g=te(d,$e),k=n.by.map(C=>i`${Y(C)} AS ${i.identifier(C)}`);if(h.op==="count")k.push(i`COUNT(*) AS value`);else{const{field:C}=h;if(C===void 0)throw new $("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);k.push(i`${i.raw(De(h.op))}(${Y(C)}) AS value`)}let D=i`SELECT ${i.join(k,i`, `)} FROM ${i.identifier(e)}`;g&&(D=i`${D} WHERE ${g}`),D=i`${D} GROUP BY ${i.join(n.by.map(C=>Y(C)),i`, `)}`;const U=O(r,D).toArray(),W=[];for(const C of U){const j={};for(const P of n.by)j[P]=C[P]??null;const{value:V}=C;W.push({key:j,value:V==null?null:Number(V)})}return W},async insert(e,n,s){const f=K(e,"insert");if(f)return at(f,e,n,s,!0);const h=t.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);const u=qt(h,n,x);Ye(h,u);let c;s?.clientId!==void 0?(io(s.clientId),c=s.clientId):s?.allowExplicitId&&typeof u._id=="string"?c=u._id:c=m();const d=s?.allowExplicitId&&typeof u._creationTime=="number"?u._creationTime:N(),w={...u,...E(e),_creationTime:d,_id:c};return Z(e,"before","insert")&&await ee("before","insert",{doc:{...w},id:c,op:"insert",table:e}),he(e),we(e),nt(r,e,Yn(e),[c,d,se(w)]),pt(e,c,w),Z(e,"after","insert")&&await ee("after","insert",{doc:w,id:c,op:"insert",table:e}),await q({doc:w,id:c,op:"insert",table:e}),c},async insertManyUnsafe(e,n,s){if(ce(n.length,s?.limit,"insertManyUnsafe"),n.length===0)return[];const f=K(e,"insert");if(f){const d=[];for(const w of n)M(w);for(const w of n){const R=await f.insert(e,w,{allowExplicitId:s?.allowExplicitId});a({key:R,op:"insert",row:{...w,_id:R},table:e}),d.push(R)}return d}const h=t.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);he(e),we(e);const u=[];for(let d=0;d<n.length;d+=Fe)u.push(E(e));const c=n.map((d,w)=>{const R=qt(h,d,x),g=s?.allowExplicitId===!0&&typeof R._id=="string"?R._id:m(),k=s?.allowExplicitId===!0&&typeof R._creationTime=="number"?R._creationTime:N(),D={...R,...u[Math.floor(w/Fe)],_creationTime:k,_id:g};return{creationTime:k,document:D,id:g}});for(const d of c)M(d.document);for(let d=0;d<c.length;d+=Fe){const w=i.join(c.slice(d,d+Fe).map(g=>i`(${g.id}, ${g.creationTime}, ${se(g.document)})`),i`, `),R=Ht("sqlite",i`INSERT INTO ${i.identifier(e)} (id, _creationTime, ${i.identifier(ne)}) VALUES ${w}`);nt(r,e,R.sql,R.params)}for(const{document:d,id:w}of c)pt(e,w,d),await F({doc:d,id:w,op:"insert",table:e});return c.map(d=>d.id)},async insertMany(e,n,s){ce(n.length,s?.limit,"insertMany");const f=s?.skipDuplicates===!0,h=[],u=K(e,"insert");if(u)for(const d of n)M(d);const c=async d=>u?at(u,e,d,void 0,!1):B.insert(e,d);for(const d of n)try{h.push(await c(d))}catch(w){if(f&&w instanceof ye&&w.kind==="unique")h.push(null);else throw w}return h},normalizeId(e,n){return Ft(t,e,n)},async patch(e,n,s){const f=re(e,s);if(!f){const R=s===void 0?I:void 0;if(R){M(n),await R.patch(e,n);return}throw new $("NOT_FOUND",`document not found: ${e}`)}const{docJson:h,row:u,tableName:c}=f,d=t.tables[c];if(!d)throw new $("INTERNAL",`unknown table: ${c}`);_(c,e),Bt("patch",n);const w={...u,...n,...E(c),_id:e};Wt(d,n,w,x),Ye(d,w,!0),Z(c,"before","update")&&await ee("before","update",{doc:{...w},id:e,op:"update",previous:u,table:c}),he(c),we(c),qe(r,c,bt(c),[se(w),e,h]),Ae(c,e,w,u),ve(c,e,w),Re(c,u,w),pe(c,e,u,w),z?.invalidate(c,e,S(c,u,w)),fe(c,e,"update",w),a({indexKeys:S(c,u,w),key:e,op:"update",row:w,table:c}),Z(c,"after","update")&&await ee("after","update",{doc:w,id:e,op:"update",previous:u,table:c}),await q({doc:w,id:e,op:"update",table:c})},async patchMany(e,n,s){ce(e.length,n?.limit,"patchMany");for(const f of e)await B.patch(f.id,f.patch,s);return{patched:e.length}},async patchWhere(e,n,s){const u=(await(K(e,"patchWhere")??B).findMany(e,{where:n.where})).page.map(c=>({id:String(c._id),patch:n.patch}));if(ce(u.length,s?.limit,"patchWhere"),B.patchMany===void 0)throw new $("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await B.patchMany(u,s),{patched:u.length}},query(e){const n=K(e,"query");return n?(_(e,G),n.query(e)):Co(r,t,e,H,s=>{s?v(s):_(e,G)},s=>{L||T?.recordRead(s)})},async rank(e,n,s){const f=K(e,"rank");if(f)return _(e,G),f.rank(e,n,s);H(e,n,"rank");const h=t.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);const u=h.rankIndexes?.find(P=>P.name===n);if(!u)throw new $("INTERNAL",`unknown rankIndex "${n}" on table "${e}"`);if(gt(e,h,u),s.restrictsCounts)throw new ze(e);_(e,G),Oe(e,u);const c=typeof s.row=="string"?s.row:s.row._id;if(!c)return null;const d=_t(e,u.name),w=u.sortBy.map((P,Ie)=>Tt(Ie)),R=w.map(P=>Se(P)).join(", "),g=O(r,i`SELECT ${i.identifier("__partition__")}, ${i.raw(R)} FROM ${i.identifier(d)} WHERE ${i.identifier("__id__")} = ${c}`).toArray(),[k]=g;if(k===void 0)return null;let D=k.__partition__;const U=Q(s.baseWhere,s.where);Ve(U,t,e,"rank");const W=Cn(u,U);if(W){const P=xn(u.partitionBy??[],W);if(P!==D)return null;D=P}const C=w.map(P=>k[P]),{before:j,total:V}=Ut(r,d,w,u.sortBy,D,C,c);return{position:j+1,total:V}},async rankBefore(e,n,s){if(ie(e))throw new $("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const f=t.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);const h=f.rankIndexes?.find(w=>w.name===n);if(!h)throw new $("INTERNAL",`unknown rankIndex "${n}" on table "${e}"`);if(s.restrictsCounts)throw new ze(e);_(e,G),Oe(e,h);const u=_t(e,h.name),c=h.sortBy.map((w,R)=>Tt(R)),d=h.sortBy.map((w,R)=>oe(s.sortValues[R]??null));return Ut(r,u,c,h.sortBy,s.partitionKey,d,s.rowId)},async rankPage(e,n,s={}){Ve(Q(s.baseWhere,s.where),t,e,"rankPage");const f=K(e,"rankPage");if(f)return _(e,G),f.rankPage(e,n,s);H(e,n,"rank");const{continueCursor:h,hasMore:u,rows:c}=Et(yt,e,n,s);return{continueCursor:h,isDone:!u,page:c.map(d=>d.doc)}},async rankPageRows(e,n,s={}){Ve(Q(s.baseWhere,s.where),t,e,"rankPage"),H(e,n,"rank");const{directions:f,hasMore:h,rows:u}=Et(yt,e,n,s);return{directions:f,hasMore:h,rows:u}},async restore(e,n){const s=re(e,n);if(!s){const u=n===void 0?I:void 0;if(u?.restore){await u.restore(e);return}throw new $("NOT_FOUND",`document not found: ${e}`)}const f=t.tables[s.tableName]?.softDeleteMode?.field;if(!f)throw new $("INTERNAL",`ctx.db.restore: table "${s.tableName}" is not a .softDelete() table`);const h=s.row[f]!==null&&s.row[f]!==void 0;await B.patch(e,{[f]:null},n),h&&pe(s.tableName,e,void 0,s.row)},async replace(e,n,s,f){const h=re(e,s);if(!h){const k=s===void 0?I:void 0;if(k){M(n),await k.replace(e,n,void 0,f);return}throw new $("NOT_FOUND",`document not found: ${e}`)}const{docJson:u,row:c,tableName:d}=h,w=t.tables[d];if(!w)throw new $("INTERNAL",`unknown table: ${d}`);Bt("replace",n);const R=f?.allowExplicitId&&typeof n._creationTime=="number"?n._creationTime:N(),g={...n,...E(d),_creationTime:R,_id:e};Wt(w,n,g,x),Ye(w,g),Z(d,"before","update")&&await ee("before","update",{doc:{...g},id:e,op:"update",previous:c,table:d}),he(d),we(d),qe(r,d,Xn(d),[R,se(g),e,u]),Ae(d,e,g,c),ve(d,e,g),Re(d,c,g),pe(d,e,c,g),z?.invalidate(d,e,S(d,c,g)),fe(d,e,"update",g),a({indexKeys:S(d,c,g),key:e,op:"update",row:g,table:d}),Z(d,"after","update")&&await ee("after","update",{doc:g,id:e,op:"update",previous:c,table:d}),await q({doc:g,id:e,op:"update",table:d})},async wipeShard(e){const n=new Set(e?.exclude),s=e?.tables,f=Object.entries(t.tables).filter(([d,w])=>n.has(d)||s!==void 0&&!s.includes(d)?!1:w.shardMode?.kind!=="global").map(([d])=>d);if(s!==void 0){for(const d of s)if(!t.tables[d])throw new $("INTERNAL",`wipeShard: unknown table: ${d}`)}const h={};let u=0;const{deleteAll:c}=B;if(c===void 0)throw new $("INTERNAL","wipeShard: this writer has no deleteAll");for(const d of f){const w=await c(d,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});h[d]=w.deleted,u+=w.deleted}return{deleted:u,tables:h}}},tn={db:B,scheduler:b};return o.enforceRls===!0?Fn(B,t,(e,n)=>re(e,n)?.tableName,(e,n)=>en(e,n)):B};export{pr as CDC_LOG_TABLE,Dr as CLIENT_WATERMARK_TABLE,Wr as GLOBAL_SHAPE_SNAPSHOT_TABLE,Or as IDEMPOTENCY_TABLE,vo as NotUniqueError,Yr as SEARCH_STATE_TABLE,kr as advanceClientWatermark,gr as applyCdcChanges,Bt as assertNoExplicitUndefined,io as assertValidClientId,ur as backfillAggregateIndexes,fr as backfillRankIndexes,hr as backfillSearchIndexes,$r as bumpCdcEpoch,yr as cdcCanVouchFor,Er as cdcSeqLeavingRows,mr as cdcTouchesTables,Sr as cdcTrimmedError,_r as compactCdcDocs,ar as createShardCtxDb,Tr as cursorBelowRetainedFloor,Br as deleteGlobalShapeSnapshot,Ur as deleteGlobalShapeSnapshotsForConnection,Lr as migrateClientWatermark,Pr as migrateGlobalShapeSnapshot,Rr as minCdcReplayableSeq,vr as minCdcSeq,Ft as normalizeIdStructurally,Ar as readCdcChangeKeys,Ir as readCdcChanges,Cr as readCdcCursor,xr as readCdcEpoch,Fr as readClientWatermark,Gr as readGlobalShapeSnapshot,jr as readIdempotent,Jr as runShardMigrations,Zr as selectShapeMembers,ei as selectShapeRows,br as trimCdcChanges,Kr as trimIdempotent,Hr as writeGlobalShapeSnapshot,Qr as writeIdempotent};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as g}from"@lunora/errors";const p=Symbol.for("lunora.ctxdb.rls-unwrap");class R extends g{table;constructor(a){super("RLS_REQUIRED",`ctx.db access to "${a}" is denied: the schema is marked .rls("required"), so this table is protected. Apply RLS with .use(rls(policies)) in the procedure, or mark the table .public() to opt it out.`,{name:"RlsRequiredError"}),this.table=a}}const S=o=>Object.entries(o.tables).filter(([,a])=>a.shardMode?.kind!=="global").map(([a])=>a),M=(o,a,l)=>{const u=a?.tables,n=new Set(a?.exclude);for(const d of o)(u===void 0||u.includes(d))&&!n.has(d)&&l(d)},m=["aggregate","count","deleteAll","findFirst","findFirstOrThrow","findMany","groupBy","insert","insertMany","insertManyUnsafe","query","rank","rankBefore","rankPage","rankPageRows"],v=(o,a,l,u)=>{if(a.rlsMode!=="required")return o;const n=o,d=r=>{const t=a.tables[r];return t!==void 0&&t.isPublic!==!0},s=r=>{if(d(r))throw new R(r)},c=async(r,t)=>{if(t!==void 0){s(t);return}const e=await l(r);e!==void 0&&s(e)},h=async(r,t)=>{if(t!==void 0){s(t);return}if(!u){for(const i of r)await c(i,t);return}const e=await u([...new Set(r)],t);for(const i of r){const y=e.get(i);y!==void 0&&s(y)}},f={...o,[p]:o,delete:async(r,t,e)=>(await c(r,t),n.delete(r,t,e)),deleteMany:async(r,t,e)=>(await h(r,e),n.deleteMany(r,t,e)),deleteWhere:n.deleteWhere?async(r,t,e)=>(s(r),await n.deleteWhere?.(r,t,e)):void 0,get:async(r,t)=>(await c(r,t),n.get(r,t)),lookupById:async(r,t)=>(await c(r,t),n.lookupById?.(r,t)??null),patch:async(r,t,e)=>(await c(r,e),n.patch(r,t,e)),patchMany:async(r,t,e)=>(await h(r.map(i=>i.id),e),n.patchMany(r,t,e)),patchWhere:n.patchWhere?async(r,t,e)=>(s(r),await n.patchWhere?.(r,t,e)):void 0,replace:async(r,t,e,i)=>(await c(r,e),n.replace(r,t,e,i)),restore:async(r,t)=>(await c(r,t),n.restore?.(r,t))},w=n;for(const r of m){const t=w[r];typeof t=="function"&&(f[r]=(e,...i)=>(s(e),t.call(n,e,...i)))}if(n.wipeShard){const{wipeShard:r}=n;f.wipeShard=t=>(M(S(a),t,s),r.call(n,t))}return f};export{p as RLS_UNWRAP_SYMBOL,R as RlsRequiredError,v as guardWriter};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{sql as i}from"drizzle-orm";import{runDrizzle as o}from"./runDrizzle-2ULFQR_k.mjs";const n="__lunora_search_state",s=e=>{o(e,i`CREATE TABLE IF NOT EXISTS ${i.identifier(n)} (${i.identifier("companion")} TEXT PRIMARY KEY, ${i.identifier("cursor")} TEXT, ${i.identifier("done")} INTEGER NOT NULL DEFAULT 0, ${i.identifier("profile")} TEXT)`);try{o(e,i`ALTER TABLE ${i.identifier(n)} ADD COLUMN ${i.identifier("profile")} TEXT`)}catch{}},$=e=>e===1||e===!0||e==="1",l=(e,t)=>{const r=o(e,i`SELECT ${i.identifier("cursor")}, ${i.identifier("done")}, ${i.identifier("profile")} FROM ${i.identifier(n)} WHERE ${i.identifier("companion")} = ${t}`).toArray()[0];return r?{cursor:r.cursor??void 0,done:$(r.done),profile:r.profile??void 0}:{cursor:void 0,done:!1,profile:void 0}},a=(e,t,d,r,f)=>{const c=d??null;o(e,i`INSERT INTO ${i.identifier(n)} (${i.identifier("companion")}, ${i.identifier("cursor")}, ${i.identifier("done")}, ${i.identifier("profile")}) VALUES (${t}, ${c}, ${r?1:0}, ${f}) ON CONFLICT (${i.identifier("companion")}) DO UPDATE SET ${i.identifier("cursor")} = excluded.${i.identifier("cursor")}, ${i.identifier("done")} = excluded.${i.identifier("done")}, ${i.identifier("profile")} = excluded.${i.identifier("profile")}`)};export{n as SEARCH_STATE_TABLE,s as migrateSearchState,l as readSearchBackfillState,a as writeSearchBackfillState};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as R}from"@lunora/errors";import{applySelect as B}from"./CURSOR_PREFIX-D4DUGY5z.mjs";const _=c=>({relationBaseWhere:c.relationBaseWhere,relationMask:c.relationMask}),W=(c,o)=>o.select?B(c,o.select,o.with):c,E=async(c,o,t,r,s)=>{const u=await Promise.all(r.map(async i=>{const w=s?{AND:[{[t]:i},s]}:{[t]:i};return[i,await c(o,w)]}));return new Map(u)},O=(c,o)=>{const t=new Set;for(const r of c){const s=r[o];s!=null&&t.add(s)}return[...t]},L=async c=>{const{groupedCounter:o,fetcher:t,parents:r,relationBaseWhere:s,relationMask:u,schema:i,tableName:w,with:D}=c,M=(a,e)=>u?.(a,e)??e;if(r.length===0)return;const y=i.tables[w];if(!y)throw new R("INTERNAL",`unknown table: ${w}`);const N=y.relationMap??{},v=a=>{const e=N[a];if(!e)throw new R("INTERNAL",`unknown relation "${a}" on table "${w}"`);return e},m=async(a,e,n)=>{const p=O(r,e.field);if(p.length===0){for(const l of r)l[a]=null;return}const{page:b}=await t(e.table,{baseWhere:s?.(e.table),relationBaseWhere:s,relationMask:u,where:{[e.references]:{in:p}},with:n.with}),k=new Map;for(const l of M(e.table,b))k.set(l[e.references],l);for(const l of r){const h=k.get(l[e.field]);l[a]=h?W([h],n)[0]??null:null}},$=async(a,e,n)=>{const p=O(r,e.references);if(p.length===0){for(const f of r)f[a]=[];return}const b={[e.field]:{in:p}},k=n.where?{AND:[n.where,b]}:b,{page:l}=await t(e.table,{baseWhere:s?.(e.table),orderBy:n.orderBy,relationBaseWhere:s,relationMask:u,where:k,with:n.with}),h=new Map;for(const f of M(e.table,l)){const d=f[e.field],V=h.get(d);V?V.push(f):h.set(d,[f])}const g=typeof n.limit=="number"?Math.max(0,Math.floor(n.limit)):void 0;for(const f of r){const d=h.get(f[e.references])??[];f[a]=W(g===void 0?d:d.slice(0,g),n)}},j=async a=>{for(const e of Object.keys(a)){const n=v(e),[p,b]=n.kind==="many"?[n.field,n.references]:[n.references,n.field],k=s?.(n.table),l=O(r,b),h=l.length===0?new Map:await o(n.table,p,l,k);for(const g of r){const f=g._count??{},d=g[b];f[e]=d==null?0:h.get(d)??0,g._count=f}}};for(const[a,e]of Object.entries(D)){if(e===void 0||e===!1)continue;if(a==="_count"){await j(e);continue}const n=v(a),p=e===!0?{}:e;await(n.kind==="one"?m(a,n,p):$(a,n,p))}},I=async(c,o,t)=>{const{deletedId:r,deletedReference:s,findHolders:u,onCascade:i,onRestrict:w,onSetNull:D,tableName:M}=c,y=t.references==="_id"?r:s(t.references);if(y==null)return;const N=await u(o,t.field,y);if(N.length!==0){t.onDelete==="restrict"&&w(`cannot delete "${M}" row: "${o}.${t.field}" still references it`);for(const v of N){const m=v._id;typeof m=="string"&&await(t.onDelete==="cascade"?i(o,m):D(o,m,t.field))}}},S=async c=>{const{schema:o,tableName:t}=c;if(!o.tables[t])throw new R("INTERNAL",`unknown table: ${t}`);for(const[r,s]of Object.entries(o.tables)){const u=s.relationMap;if(u)for(const i of Object.values(u))i.kind!=="one"||i.table!==t||!i.onDelete||await I(c,r,i)}},x=(c,o,t=!1)=>{for(const[r,s]of Object.entries(c.shape))r in o&&typeof s.parse=="function"&&(t&&o[r]===null&&s.kind==="optional"||s.parse(o[r]))};export{S as applyOnDelete,O as distinctValues,E as fanOutScalarCounts,_ as relationHooks,L as resolveWith,x as runRowValidators};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{r as R,i as k,S as A,q as O,l as h,y as $,d as C}from"./ctx-db-companions-CN8hWTF_.mjs";import{sql as t}from"drizzle-orm";import{matchesStaticWhere as L}from"./AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs";import{aggregateTableName as M,encodeAggregateKey as x,foldAggregateTally as N}from"./aggregateTableName-CGi8gxeK.mjs";import{migrateSearchState as _,readSearchBackfillState as F,writeSearchBackfillState as y}from"./SEARCH_STATE_TABLE-BCqn5ksa.mjs";import{runDrizzle as l}from"./runDrizzle-2ULFQR_k.mjs";import{i as E,r as T,a as D,b as v,A as B,D as S,h as G}from"./do-sql-bkXQEBl8.mjs";import{isLiveForCompanion as U}from"./CURSOR_PREFIX-D4DUGY5z.mjs";import{rankTableName as P,matchesRankStaticWhere as W}from"./RANK_TIEBREAK-D157XEqw.mjs";const H=(e,n)=>e.profile!==n?{cursor:void 0,finished:!1,wipe:e.cursor!==void 0||e.done}:{cursor:e.cursor,finished:e.done,wipe:!1},b=(e,n)=>l(e,t`SELECT COUNT(*) AS count FROM ${t.identifier(n)}`).one().count>0,p=(e,n)=>l(e,t`SELECT id, _creationTime, ${t.identifier(S)} FROM ${t.identifier(n)}`).toArray(),V=(e,n,r,o)=>{const i=M(n,r.name);if(b(e,i))return;const a=r.by??[],s=new Map,c=p(e,n);for(const d of c){const f=T(d);if(!f||!U(f,o)||r.where&&!L(f,r.where))continue;const g=x(a,f);N(s,g,r,f)}for(const[d,f]of s)l(e,t`INSERT INTO ${t.identifier(i)} (${D}, ${v}, ${B}) VALUES (${d}, ${f.value}, ${f.count})`)},ne=(e,n)=>{for(const[r,o]of Object.entries(n.tables))if(!(o.shardMode?.kind==="global"||!o.aggregateIndexes))for(const i of o.aggregateIndexes)V(e,r,i,o.softDeleteMode?.field)},Y=(e,n,r)=>{const o=P(n,r.name);if(b(e,o))return;const i=R(r),a=p(e,n);for(const s of a){const c=T(s);!c||r.where&&!W(c,r.where)||k(e,o,r,i,c._id,c)}},re=(e,n)=>{for(const[r,o]of Object.entries(n.tables))if(!(o.shardMode?.kind==="global"||!o.rankIndexes))for(const i of o.rankIndexes)Y(e,r,i)},m=500,w=(e,n,r)=>{const o=A(n,r.name),{profile:i}=O(r.language),a=H(F(e,o),i);if(a.finished)return{done:!0,rows:0};a.wipe&&l(e,t`DELETE FROM ${t.identifier(o)}`);const{cursor:s}=a,c=l(e,s===void 0?t`SELECT id, _creationTime, ${t.identifier(S)} FROM ${t.identifier(n)} ORDER BY id ASC LIMIT ${t.raw(String(m))}`:t`SELECT id, _creationTime, ${t.identifier(S)} FROM ${t.identifier(n)} WHERE id > ${s} ORDER BY id ASC LIMIT ${t.raw(String(m))}`).toArray();let d=s;for(const g of c){const{id:u}=g;if(typeof u!="string")continue;d=u,l(e,t`DELETE FROM ${t.identifier(o)} WHERE ${t.identifier(h)} = ${u}`);const I=G(g);I&&l(e,t`INSERT INTO ${t.identifier(o)} (${t.identifier($)}, ${t.identifier(h)}) VALUES (${C(I,r)}, ${u})`)}const f=c.length<m;return y(e,o,d,f,i),{done:f,rows:c.length}},te=(e,n,r)=>{if(E(e))for(const o of r.searchIndexes??[])o.staged||w(e,n,o)},j=(e,n,r,o)=>{let i=0;for(;;){if(i>=o)return{done:!1,pages:i};const a=w(e,n,r);if(a.rows>0&&(i+=1),a.done)return{done:!0,pages:i}}},ie=(e,n,r={})=>{if(!E(e))return{done:!0,pages:0};_(e);const o=r.maxPages??Number.POSITIVE_INFINITY;let i=0;for(const[a,s]of Object.entries(n.tables))if(!(s.shardMode?.kind==="global"||!s.searchIndexes))for(const c of s.searchIndexes){const d=j(e,a,c,o-i);if(i+=d.pages,!d.done)return{done:!1,pages:i}}return{done:!0,pages:i}};export{ne as backfillAggregateIndexes,re as backfillRankIndexes,ie as backfillSearchIndexes,te as backfillSearchIndexesForTable};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{quoteIdentifier as l}from"./quoteIdentifier-CObIFRhb.mjs";import{reprojectionMigrationTable as u}from"./REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{REPROJECTION_MIGRATION_PREFIX as v,reprojectionMigrationId as w}from"./REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{e as m}from"./wire-codec-COhOSEe4.mjs";import{runSql as p}from"./runDrizzle-2ULFQR_k.mjs";import{k as d,D as E}from"./do-sql-bkXQEBl8.mjs";import{m as g}from"./sql-projection-BqmxFxQU.mjs";const b=m(0n)[0],_=e=>e.shardMode?.kind==="global"?[]:Object.entries(e.shape).filter(([,r])=>g(r)).map(([r])=>r),M=e=>Object.entries(e.tables).filter(([,r])=>_(r).length>0).map(([r])=>r),f=e=>{const r=`json_each(${l(E)}) AS __f__`;return{params:[JSON.stringify(e),b,"bigint","bytes"],sql:`EXISTS (SELECT 1 FROM ${r} WHERE __f__.type = 'array' AND __f__.key IN (SELECT value FROM json_each(?)) AND json_extract(__f__.value, '$[0]') = ? AND json_extract(__f__.value, '$[1]') IN (?, ?))`}},N=(e,r,o)=>{if(o.length===0)return 0;const{params:t,sql:n}=f(o);return p(e,`SELECT COUNT(*) AS count FROM ${l(r)} WHERE ${n}`,...t).toArray()[0]?.count??0},R=(e,r,o,t)=>{const{params:n,sql:i}=f(o);return p(e,`SELECT 1 FROM ${l(r)} WHERE id = ? AND (${i}) LIMIT 1`,t,...n).toArray().length>0},S=(e,r,o)=>{const t=u(e);if(t===void 0)return;const n=r.tables[t];if(!n)return;const i=_(n);if(i.length!==0)return{id:e,table:t,up:s=>{const a=s._id;if(!(typeof a!="string"||!R(o,t,i,a))){try{d(s)}catch(c){console.warn(`${e}: skipping row ${a} — it cannot be re-projected: ${c instanceof Error?c.message:String(c)}`);return}return s}}}};export{v as REPROJECTION_MIGRATION_PREFIX,S as buildReprojectionMigration,N as countLegacyRows,_ as reprojectableFields,w as reprojectionMigrationId,M as reprojectionTables};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{c as l,i as C,r as R}from"./ctx-db-companions-CN8hWTF_.mjs";import"./AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs";import"./aggregateTableName-CGi8gxeK.mjs";import"./runDrizzle-2ULFQR_k.mjs";import"./do-sql-bkXQEBl8.mjs";import"./param-DlozcSQu.mjs";import"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import"./CURSOR_PREFIX-D4DUGY5z.mjs";import"./RANK_TIEBREAK-D157XEqw.mjs";import"./sql-projection-BqmxFxQU.mjs";import"./serializeSqlValue-DbI1VQYM.mjs";export{l as createCompanionSync,C as insertRankRow,R as rankColumnsSql};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{sql as e}from"drizzle-orm";import{matchesStaticWhere as P,aggregateSqlFunction as le}from"./AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs";import{aggregateTableName as N,encodeAggregateKey as I,foldAggregateTally as J,coerceAggregateNumber as C}from"./aggregateTableName-CGi8gxeK.mjs";import{runDrizzle as $}from"./runDrizzle-2ULFQR_k.mjs";import{i as fe,g as ue,D,r as M,a as q,b as S,A as g,c as j,e as z}from"./do-sql-bkXQEBl8.mjs";import{param as de,WORKERD_SQLITE_LIMITS as $e}from"./param-DlozcSQu.mjs";import{encodeGeohash as me,GEO_DEFAULT_PRECISION as Ee}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{isLiveForCompanion as Q}from"./CURSOR_PREFIX-D4DUGY5z.mjs";import{encodePartitionKey as pe,sortColumnName as he,rankTableName as Z,matchesRankStaticWhere as x}from"./RANK_TIEBREAK-D157XEqw.mjs";import{m as ge}from"./sql-projection-BqmxFxQU.mjs";import{serializeSqlValue as ee}from"./serializeSqlValue-DbI1VQYM.mjs";const ye=["de","en","es","fr","it","nl","none","pt"],_e=n=>ye.includes(n),Se="a an and are as at be but by for if in into is it no not of on or such that the their then there these they this to was will with",we="aber als am an auch auf aus bei bin bis bist da dass der den des dem die das denn dir du ein eine für hat ich im in ist mit nicht noch nur oder sich sie sind über und von vor war wie wir zu zum zur",Te="a al como con de del el en es la las lo los mas no o para pero por que se su sus un una uno y ya",ve="au aux avec ce ces dans de des du elle en et eux il je la le les leur lui ma mais me même mes moi mon ne nos notre nous on ou par pas pour qu que qui sa se ses son sur ta te tes toi ton tu un une vos votre vous y",Re="a ai al alla anche che chi ci coi col come con da dal degli dei del della di do e ed gli ha hai hanno i il in la le lo ma mi ne nei nel non o per più quale quanto se si sono su sul tra un una uno vi",Ae="aan al als bij dan dat de der deze die dit door een en er het hij ij in is je kan me men met mij na naar niet nog nu of om ons ook op over te tot uit van voor was wat we wij zij zijn zo",Fe="a ao aos as até com como da das de do dos e em entre era essa esse esta este eu foi há isso já mais mas me mesmo meu na nas no nos num numa o os ou para pela pelo por qual que quem se sem seu só sua também te tem um uma você",be=/[\u0300-\u036F]/gu,Oe=/[\u0080-\u{10FFFF}]/u,Le=/[\p{L}\p{N}]+/gu,oe=n=>Oe.test(n)?n.normalize("NFD").replaceAll(be,"").normalize("NFC").toLowerCase():n.toLowerCase(),k=n=>new Set(oe(n).split(" ")),Ie={de:k(we),en:k(Se),es:k(Te),fr:k(ve),it:k(Re),nl:k(Ae),none:new Set,pt:k(Fe)},ke=2,qe=256,X=new Map,Ce=n=>{const s=n!==void 0&&_e(n)?n:"none",c=X.get(s);if(c)return c;const w=Ie[s],y=r=>{const A=(oe(r).match(Le)??[]).filter(T=>T.length<=qe);return w.size===0?A:A.filter(T=>!w.has(T))},E={document:y,profile:`${s}-v${String(ke)}`,query:r=>{const A=y(r);return A.filter((T,b)=>A.lastIndexOf(T)===b)}};return X.set(s,E),E},je=(n,s)=>{if(!s.includes("."))return n[s];let c=n;for(const w of s.split(".")){if(c===null||typeof c!="object"||Array.isArray(c))return;c=c[w]}return c},De=(n,s)=>`${n}__fts_${s}`,Me="__text__",Y="__id__",ze=1e3,Ue=(n,s)=>s.document(n),U=(n,s)=>je(n,s),We=n=>typeof n=="string"?n:n==null?"":typeof n=="number"||typeof n=="bigint"||typeof n=="boolean"?String(n):JSON.stringify(n)??"",He=(n,s,c)=>n!==void 0&&s!==void 0&&U(n,c.field)===U(s,c.field),Be=(n,s)=>Ue(We(U(n,s.field)),Ce(s.language)).slice(0,ze),Ke=(n,s)=>Be(n,s).join(" "),Ve=(n,s,c)=>[...n.partitionBy??[],...n.sortBy.map(y=>y.field),...n.where?Object.keys(n.where):[]].every(y=>s[y]===c[y]),ne=n=>e.join(["__id__","__partition__",...n.sortBy.map((s,c)=>he(c))].map(s=>e.identifier(s)),e`, `),te=(n,s,c,w,y,E)=>{const r=pe(c.partitionBy??[],E),A=c.sortBy.map(b=>ee(E[b.field]??null)),T=e.join([y,r,...A].map(b=>de(b)),e`, `);$(n,e`INSERT INTO ${e.identifier(s)} (${w}) VALUES (${T})`)},Ge=(n,s,c,w,y,E)=>{if(y&&E&&Ve(c,y,E))return;const r=Z(s,c.name);y&&$(n,e`DELETE FROM ${e.identifier(r)} WHERE ${e.identifier("__id__")} = ${w}`),!(!E||c.where&&!x(E,c.where))&&te(n,r,c,ne(c),w,E)},so=n=>{const{broadcast:s,indexKeysFor:c,invalidateCache:w,recordCdc:y,schema:E,sql:r}=n,A=new Set,T=t=>E.tables[t]?.softDeleteMode?.field,b=new Set,W=(t,o)=>{const a=`${t}::${o.name}`;if(A.has(a))return;const f=N(t,o.name),u=o.by??[],d=T(t),p=new Map,_=$(r,e`SELECT id, _creationTime, ${e.identifier(D)} FROM ${e.identifier(t)}`).toArray();for(const v of _){const m=M(v);if(!m||!Q(m,d)||o.where&&!P(m,o.where))continue;const R=I(u,m);J(p,R,o,m)}$(r,e`DELETE FROM ${e.identifier(f)}`);const F=Math.floor($e.boundParams/3),O=[...p];for(let v=0;v<O.length;v+=F){const m=O.slice(v,v+F),R=e.join(m.map(([i,l])=>e`(${i}, ${l.value}, ${l.count})`),e`, `);$(r,e`INSERT INTO ${e.identifier(f)} (${q}, ${S}, ${g}) VALUES ${R}`)}A.add(a)},se=(t,o,a)=>{const f=o.by??[],u=o.field??"",d=[],p=(i,l)=>{const h=ee(l);h===null?d.push(e`${z(i)} IS NULL`):d.push(e`${z(i)} = ${h}`)};for(const i of f)p(i,a[i]??null);const _=T(t);_!==void 0&&p(_,null);for(const[i,l]of Object.entries(o.where??{}))p(i,l!==null&&typeof l=="object"&&!Array.isArray(l)?l.eq:l);const F=d.length>0?e` WHERE ${e.join(d,e` AND `)}`:e``,O=E.tables[t]?.shape[u];if(O&&ge(O)){const i=$(r,e`SELECT id, _creationTime, ${e.identifier(D)} FROM ${e.identifier(t)}${F}`).toArray(),l=new Map;for(const h of i){const L=M(h);L&&J(l,"",o,L)}return{value:l.get("")?.value??null}}const v=le(o.op),m=z(u);return{value:$(r,e`SELECT ${e.raw(v)}(${m}) AS value FROM ${e.identifier(t)}${F}`).one().value??null}},ie=(t,o,a,f)=>{const u=N(t,o.name),{op:d}=o,p=o.field??"",_=i=>{$(r,e`DELETE FROM ${e.identifier(u)} WHERE ${q} = ${i} AND ${g} <= 0`)},F=T(t),O=i=>!o.where||P(i,o.where),v=i=>Q(i,F)&&O(i);f!==void 0&&d!=="count"&&O(f)&&C(f[p]);const m=a&&v(a)?a:void 0,R=f&&v(f)?f:void 0;if(!(!m&&!R)){if(d==="count"){for(const[i,l]of[[m,-1],[R,1]]){if(!i)continue;const h=I(o.by??[],i);$(r,j(u,h,l,l,e`${S} = ${S} + excluded.${S}, ${g} = ${g} + excluded.${g}`))}m&&_(I(o.by??[],m));return}if(d==="sum"||d==="avg"){for(const[i,l]of[[m,-1],[R,1]]){if(!i)continue;const h=C(i[p]);if(h===void 0)continue;const L=I(o.by??[],i);$(r,j(u,L,l*h,l,e`${S} = COALESCE(${S}, 0) + excluded.${S}, ${g} = ${g} + excluded.${g}`))}m&&_(I(o.by??[],m));return}if(m){const i=I(o.by??[],m),l=C(m[p]),h=$(r,e`SELECT ${S} AS value, ${g} AS count FROM ${e.identifier(u)} WHERE ${q} = ${i}`).toArray()[0],L=(h?.count??0)-1;if(L<=0)$(r,e`DELETE FROM ${e.identifier(u)} WHERE ${q} = ${i}`);else if(h&&l!==void 0&&h.value!==null&&l===h.value){const ce=se(t,o,m);$(r,e`UPDATE ${e.identifier(u)} SET ${S} = ${ce.value}, ${g} = ${L} WHERE ${q} = ${i}`)}else $(r,e`UPDATE ${e.identifier(u)} SET ${g} = ${g} - 1 WHERE ${q} = ${i}`)}if(R){const i=I(o.by??[],R),l=C(R[p]);if(l===void 0)$(r,j(u,i,null,1,e`${g} = ${g} + 1`));else{const h=d==="min"?"MIN":"MAX";$(r,j(u,i,l,1,e`${S} = ${e.raw(h)}(COALESCE(${S}, excluded.${S}), excluded.${S}), ${g} = ${g} + 1`))}}}},re=t=>{for(const o of E.tables[t]?.aggregateIndexes??[])W(t,o)},H=(t,o,a)=>{for(const f of E.tables[t]?.aggregateIndexes??[])ie(t,f,o,a)},B=(t,o)=>{const a=`${t}::rank::${o.name}`;if(b.has(a))return;const f=Z(t,o.name),u=$(r,e`SELECT id, _creationTime, ${e.identifier(D)} FROM ${e.identifier(t)}`).toArray();$(r,e`DELETE FROM ${e.identifier(f)}`);const d=ne(o);for(const p of u){const _=M(p);!_||o.where&&!x(_,o.where)||te(r,f,o,d,_._id,_)}b.add(a)},ae=t=>{for(const o of E.tables[t]?.rankIndexes??[])B(t,o)},K=(t,o,a,f)=>{for(const u of E.tables[t]?.rankIndexes??[])Ge(r,t,u,o,a,f)},V=(t,o,a,f)=>{const u=E.tables[t]?.searchIndexes??[];if(!(u.length===0||!fe(r)))for(const d of u){if(He(f,a,d))continue;const p=De(t,d.name);$(r,e`DELETE FROM ${e.identifier(p)} WHERE ${e.identifier(Y)} = ${o}`),a&&$(r,e`INSERT INTO ${e.identifier(p)} (${e.identifier(Me)}, ${e.identifier(Y)}) VALUES (${Ke(a,d)}, ${o})`)}},G=(t,o,a)=>{for(const f of E.tables[t]?.geoIndexes??[]){const u=ue(t,f.name);$(r,e`DELETE FROM ${e.identifier(u)} WHERE ${e.identifier("__id__")} = ${o}`);const d=a?.[f.field];if(d!==null&&typeof d=="object"&&typeof d.lat=="number"&&typeof d.lng=="number"){const{lat:p,lng:_}=d,F=me({lat:p,lng:_},f.precision??Ee);$(r,e`INSERT INTO ${e.identifier(u)} (${e.identifier("__id__")}, ${e.identifier("__geohash__")}, ${e.identifier("__lat__")}, ${e.identifier("__lng__")}) VALUES (${o}, ${F}, ${p}, ${_})`)}}};return{ensureBackfilledForTable:re,ensureBackfilledIndex:W,ensureRankBackfilled:B,ensureRankBackfilledForTable:ae,syncAggregates:H,syncCompanionsForInsert:(t,o,a)=>{V(t,o,a),G(t,o,a),H(t,void 0,a),K(t,o,void 0,a),w(t,o,a),y(t,o,"insert",a),s({indexKeys:c(t,a),key:o,op:"insert",row:a,table:t})},syncGeo:G,syncRanks:K,syncSearch:V}};export{De as S,Be as a,so as c,Ke as d,te as i,Y as l,Ce as q,ne as r,Me as y};
|
|
@@ -1,17 +0,0 @@
|
|
|
1
|
-
import{sql as i}from"drizzle-orm";import{e as o,d as l}from"./wire-codec-COhOSEe4.mjs";import{runDrizzle as d}from"./runDrizzle-2ULFQR_k.mjs";const a="__lunora_relay_shapes",t=null,u=e=>{d(e,i`CREATE TABLE IF NOT EXISTS ${i.identifier(a)} (
|
|
2
|
-
key TEXT PRIMARY KEY,
|
|
3
|
-
relay_idx INTEGER,
|
|
4
|
-
connection_id TEXT,
|
|
5
|
-
name TEXT NOT NULL,
|
|
6
|
-
args TEXT NOT NULL,
|
|
7
|
-
identity TEXT NOT NULL,
|
|
8
|
-
cursor INTEGER NOT NULL
|
|
9
|
-
)`)},s=e=>JSON.stringify(o(e)),c=e=>l(JSON.parse(e)),m=e=>d(e,i`SELECT key, relay_idx, connection_id, name, args, identity, cursor FROM ${i.identifier(a)}`).toArray().map(r=>({args:c(r.args),connectionId:r.connection_id??void 0,cursor:Number(r.cursor),identity:c(r.identity),key:r.key,name:r.name,relayIndex:r.relay_idx===null?void 0:Number(r.relay_idx)})),_=(e,n)=>{d(e,i`INSERT INTO ${i.identifier(a)} (key, relay_idx, connection_id, name, args, identity, cursor)
|
|
10
|
-
VALUES (${n.key}, ${n.relayIndex??t}, ${n.connectionId??t}, ${n.name}, ${s(n.args)}, ${s(n.identity??{})}, ${n.cursor})
|
|
11
|
-
ON CONFLICT(key) DO UPDATE SET
|
|
12
|
-
relay_idx = excluded.relay_idx,
|
|
13
|
-
connection_id = excluded.connection_id,
|
|
14
|
-
name = excluded.name,
|
|
15
|
-
args = excluded.args,
|
|
16
|
-
identity = excluded.identity,
|
|
17
|
-
cursor = excluded.cursor`)},N=(e,n,r)=>{d(e,i`UPDATE ${i.identifier(a)} SET cursor = ${r} WHERE key = ${n}`)},L=(e,n)=>{d(e,i`DELETE FROM ${i.identifier(a)} WHERE relay_idx = ${n}`)},R=e=>{d(e,i`DELETE FROM ${i.identifier(a)}`)};export{_ as a,R as b,L as d,u as m,m as r,N as w};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as _}from"@lunora/errors";import{sql as o}from"drizzle-orm";import{quoteIdentifier as A}from"./quoteIdentifier-CObIFRhb.mjs";import{d as T,n as $,e as p}from"./wire-codec-COhOSEe4.mjs";import{runDrizzle as l}from"./runDrizzle-2ULFQR_k.mjs";import{s as S}from"./sql-projection-BqmxFxQU.mjs";import"./serializeSqlValue-DbI1VQYM.mjs";const O=/^[A-Za-z_$][\w$]*$/u,b=e=>O.test(e)?e:`"${e.replaceAll("\\",String.raw`\\`).replaceAll('"',String.raw`\"`)}"`,m="__doc__",i="__originals__",R=e=>{if(Object.hasOwn(e,i))throw new _("BAD_REQUEST",`"${i}" is reserved by the row store's document encoding and cannot be used as a field name — rename the field`);let t,r;for(const[s,a]of Object.entries(e)){const c=S(a);c!==void 0&&(t??={...e},r??=Object.create(null),t[s]=c,r[s]=a)}t&&r&&(t[i]=r);const n=t??e;try{return $(n)?JSON.stringify(p(n)):JSON.stringify(n)}catch(s){throw new _("BAD_REQUEST",`this document cannot be stored: ${s instanceof Error?s.message:String(s)}`)}},h=e=>{const t=T(JSON.parse(e)),r=t[i];if(r===null||typeof r!="object"||Array.isArray(r))return t;const n={...t};return delete n[i],{...n,...r}},G=(e,t)=>`${e}__geo_${t}`,E=(e,t)=>t==="_id"||t==="id"?`${e}id`:t==="_creationTime"?`${e}_creationTime`:`json_extract(${e}${m}, '$.${b(t).replaceAll("'","''")}')`,g=e=>E("",e),J=e=>o.raw(g(e)),N=(e,t)=>E(`${A(e)}.`,t),q=(e,t)=>o.raw(N(e,t)),B=(e,t,r,n)=>o`CREATE ${n?o`UNIQUE `:o``}INDEX IF NOT EXISTS ${o.identifier(e)} ON ${o.identifier(t)} (${r})`,f=o.identifier("__key__"),y=o.identifier("__value__"),I=o.identifier("__count__"),z=(e,t,r,n,s)=>o`INSERT INTO ${o.identifier(e)} (${f}, ${y}, ${I}) VALUES (${t}, ${r}, ${n}) ON CONFLICT(${f}) DO UPDATE SET ${s}`,d=new WeakMap,F=e=>{const t=d.get(e);if(t!==void 0)return t;const r=[];for(const[n,s]of Object.entries(e.shape)){const a=s._meta?.column;a&&r.push(Object.freeze([n,a]))}return Object.freeze(r),d.set(e,r),r},j=e=>{if(!e)return;const t=e[m];let r;typeof t=="string"?r=h(t):t&&typeof t=="object"?r=t:r={};const{id:n}=e;typeof n=="string"&&(r._id=n);const s=e._creationTime;return typeof s=="number"&&(r._creationTime=s),r},W=e=>{try{return j(e)}catch{return}},u=new WeakMap,k=e=>{const t=u.get(e);if(t!==void 0)return t;let r;try{l(e,o`CREATE VIRTUAL TABLE IF NOT EXISTS ${o.identifier("__lunora_fts_probe")} USING fts5(x)`),r=!0}catch{r=!1}finally{try{l(e,o`DROP TABLE IF EXISTS ${o.identifier("__lunora_fts_probe")}`)}catch{}}return u.set(e,r),r};export{I as A,m as D,f as a,y as b,z as c,B as d,J as e,q as f,G as g,W as h,k as i,g as j,R as k,h as l,b as m,i as n,N as q,j as r,F as t};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{B as s}from"./sql-projection-BqmxFxQU.mjs";const n=40,f=i=>{let e=0;const o=(r,t)=>typeof t=="bigint"?(e+=s+1+n,t.toString()):t instanceof ArrayBuffer||ArrayBuffer.isView(t)?(e+=2*Math.ceil(t.byteLength/3)*4+n,""):t;try{const r=JSON.stringify(i,o);return(r===void 0?0:r.length)+e}catch{return}};export{f as e};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{toErrorBody as f}from"@lunora/errors";const l=200,b=(r,n)=>{const i=e=>{const o=r.tables[e];return o!==void 0&&o.shardMode?.kind!=="global"};return(n&&n.length>0?[...n]:Object.keys(r.tables)).filter(e=>i(e))},p=async function*(r,n,i=l){let e=null,o=!1;for(;!o;){const t=await r.findMany(n,{cursor:e,limit:i});for(const s of t.page)yield{doc:s,table:n};e=t.continueCursor,o=t.isDone||e===null}},A=async function*(r,n,i){const e=b(n,i.tables),o=i.batchSize??l;for(const t of e)yield*p(r,t,o)},u=new Set(["_creationTime","_id"]),y=(r,n)=>{for(const[i,e]of Object.entries(r.shape)){const o=n[i];if(o===void 0&&e.kind==="optional")continue;const t=e.parse;if(typeof t=="function")try{t(o)}catch(s){const c=s instanceof Error?s.message:String(s);return`field "${i}": ${c}`}}},h=(r,n,i)=>{const e=r.tables[n];if(!e)return`unknown table: ${n}`;if(e.shardMode?.kind==="global")return`table "${n}" is a global (.global()) table and is not importable through the shard import path`;const o=Object.fromEntries(Object.entries(i).filter(([t])=>!u.has(t)));for(const t of Object.keys(o))if(!(t in e.shape))return`unexpected field "${t}": not declared in table "${n}"`;return y(e,o)},m=async(r,n)=>{try{return await r.get(n)!==null}catch{return!1}},g=async(r,n,i,e)=>{const{doc:o,table:t}=i;if(typeof t!="string"||t.length===0)return{error:{code:"BAD_ROW",line:e,message:"row is missing `table`",table:t},kind:"error"};if(!o||typeof o!="object"||Array.isArray(o))return{error:{code:"BAD_ROW",line:e,message:"row is missing or malformed `doc`",table:t},kind:"error"};const s=h(n,t,o);if(s!==void 0)return{error:{code:"VALIDATION_ERROR",line:e,message:s,table:t},kind:"error"};const c=typeof o._id=="string"?o._id:void 0;if(c!==void 0&&await m(r,c))return{kind:"conflict"};try{return await r.insert(t,o,{allowExplicitId:!0}),{kind:"inserted",table:t}}catch(a){const{body:d}=f(a,{fallbackCode:"INSERT_FAILED"});return{error:{code:d.code,line:e,message:d.message,table:t},kind:"error"}}},S=async(r,n,i)=>{const e=[],o={};let t=0,s=(i.startLine??1)-1;for(const c of i.rows){s+=1;const a=await g(r,n,c,s);a.kind==="error"?e.push(a.error):a.kind==="conflict"?t+=1:o[a.table]=(o[a.table]??0)+1}return{conflicts:t,errors:e,inserted:o}},k=r=>{const n=Array.isArray(r.tables)?r.tables.filter(e=>typeof e=="string"):void 0;return{batchSize:typeof r.batchSize=="number"?r.batchSize:void 0,tables:n}},E=r=>{const n=Array.isArray(r.rows)?r.rows:[],i=[];for(const o of n){if(!o||typeof o!="object")continue;const t=o;if(typeof t.table!="string"||!t.doc||typeof t.doc!="object"||Array.isArray(t.doc)){i.push({doc:t.doc??{},table:typeof t.table=="string"?t.table:""});continue}i.push({doc:t.doc,table:t.table})}const e=typeof r.startLine=="number"?r.startLine:void 0;return{rows:i,startLine:e}};export{A as exportShardRows,S as importShardRows,k as parseExportShardArgs,E as parseImportShardArgs,b as selectExportTables,h as validateImportRow};
|
|
@@ -1,5 +0,0 @@
|
|
|
1
|
-
import{S as A,y as u,l as L}from"./ctx-db-companions-CN8hWTF_.mjs";import{sql as e}from"drizzle-orm";import{aggregateTableName as p}from"./aggregateTableName-CGi8gxeK.mjs";import{backfillSearchIndexesForTable as N}from"./backfillAggregateIndexes-BCLXdiIS.mjs";import{migrateCdcLog as h,migrateCdcMeta as R}from"./CDC_LOG_TABLE-gl0FuepJ.mjs";import{migrateClientWatermark as x}from"./CLIENT_WATERMARK_TABLE-CRnrAnJ2.mjs";import{migrateCommitSeq as l}from"./COMMIT_SEQ_FIELD-BUdOMG5y.mjs";import{migrateGlobalShapeSnapshot as O}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-DSA6mzyx.mjs";import{migrateIdempotency as C}from"./IDEMPOTENCY_TABLE-DOpm_oMF.mjs";import{m as b}from"./ctx-db-relay-shapes-CakvRIFx.mjs";import{migrateSearchState as U}from"./SEARCH_STATE_TABLE-BCqn5ksa.mjs";import{migrateShapePokeCursor as $}from"./SHAPE_POKE_CURSOR_TABLE-ByJVDHds.mjs";import{runDrizzle as a}from"./runDrizzle-2ULFQR_k.mjs";import{D,e as g,d as T,t as X,i as G,g as F,a as M,b as B,A as I}from"./do-sql-bkXQEBl8.mjs";import{renderSql as k}from"./param-DlozcSQu.mjs";import{migrateDurableStreams as Y}from"./appendStreamChunk-8eH4HB1Q.mjs";import{rankTableName as v,sortColumnName as y}from"./RANK_TIEBREAK-D157XEqw.mjs";import{migrateReactorState as P}from"./REACTOR_STATE_TABLE-QPRFyxMS.mjs";import{recordSchemaVersion as j}from"./SCHEMA_HISTORY_MAX_VERSIONS-BluIj2s-.mjs";const K=e`_creationTime, id`,V=(r,o,n,i,t)=>{const m=a(r,e`SELECT sql FROM sqlite_master WHERE type = 'index' AND name = ${o} AND tbl_name = ${n}`).toArray()[0]?.sql;if(m==null)return;const f=c=>{const _=c.indexOf("(");return _===-1?void 0:c.slice(_,c.lastIndexOf(")")+1)},d=f(k("sqlite",T(o,n,i,t)).sql),E=f(m);d===void 0||E===void 0||d===E||a(r,e`DROP INDEX IF EXISTS ${e.identifier(o)}`)},w=(r,o,n)=>{for(const i of n.indexes){const t=`${o}_${i.name}`,s=i.unique??!1,m=e.join(i.fields.map(d=>g(d)),e`, `),f=s?m:e`${m}, ${K}`;V(r,t,o,f,s),a(r,T(t,o,f,s))}for(const[i,t]of X(n)){if(!t.unique)continue;const s=`${o}_unique_${i}`;a(r,T(s,o,g(i),!0))}},z=(r,o,n)=>{if(!(!n.searchIndexes||n.searchIndexes.length===0||!G(r))){for(const i of n.searchIndexes){const t=A(o,i.name);a(r,e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(t)} USING fts5(${e.identifier(u)}, ${e.identifier(L)} UNINDEXED)`),a(r,e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(`${t}__vocab`)} USING fts5vocab(${e.identifier(t)}, ${e.raw("instance")})`)}N(r,o,n)}},W=(r,o,n)=>{if(n.geoIndexes)for(const i of n.geoIndexes){const t=F(o,i.name);a(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(t)} (${e.identifier("__id__")} TEXT PRIMARY KEY, ${e.identifier("__geohash__")} TEXT NOT NULL, ${e.identifier("__lat__")} REAL NOT NULL, ${e.identifier("__lng__")} REAL NOT NULL)`);const s=`${o}__geo_${i.name}__btree`;a(r,T(s,t,e`${e.identifier("__geohash__")} ASC, ${e.identifier("__id__")} ASC`,!1))}},H=(r,o,n)=>{if(n.aggregateIndexes)for(const i of n.aggregateIndexes){const t=p(o,i.name);a(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(t)} (${M} TEXT PRIMARY KEY, ${B} REAL, ${I} INTEGER NOT NULL DEFAULT 0)`),a(r,e`PRAGMA table_info(${e.identifier(t)})`).toArray().some(m=>m.name==="__count__")||a(r,e`ALTER TABLE ${e.identifier(t)} ADD COLUMN ${I} INTEGER NOT NULL DEFAULT 0`)}},J=(r,o,n)=>{if(n.rankIndexes)for(const i of n.rankIndexes){const t=v(o,i.name),s=i.sortBy.map((c,_)=>y(_)),m=s.map(c=>e`${e.identifier(c)} BLOB`),f=m.length>0?e`, ${e.join(m,e`, `)}`:e``;a(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(t)} (${e.identifier("__id__")} TEXT PRIMARY KEY, ${e.identifier("__partition__")} TEXT NOT NULL${f})`);const d=[e`${e.identifier("__partition__")} ASC`];for(const[c,_]of s.entries()){const S=i.sortBy[c]?.direction;d.push(e`${e.identifier(_)} ${e.raw(S==="desc"?"DESC":"ASC")}`)}d.push(e`${e.identifier("__id__")} ASC`);const E=`${o}__rank_${i.name}__btree`;a(r,T(E,t,e.join(d,e`, `),!1))}},Ie=(r,o,n={})=>{n.schemaSnapshot!==void 0&&j(r,n.schemaSnapshot.hash,n.schemaSnapshot.json),U(r);for(const[i,t]of Object.entries(o.tables))t.shardMode?.kind!=="global"&&(a(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(i)} (
|
|
2
|
-
id TEXT PRIMARY KEY,
|
|
3
|
-
_creationTime REAL NOT NULL,
|
|
4
|
-
${e.identifier(D)} TEXT NOT NULL
|
|
5
|
-
)`),w(r,i,t),z(r,i,t),W(r,i,t),H(r,i,t),J(r,i,t));n.cdc&&(h(r),R(r),x(r),$(r),b(r)),Object.values(o.tables).some(i=>i.commitOrderedMode===!0)&&l(r),P(r),C(r),O(r),Y(r)};export{Ie as runShardMigrations};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{s as o}from"./sql-projection-BqmxFxQU.mjs";const n=r=>typeof r=="boolean"?r?1:0:r===null||typeof r=="string"||typeof r=="number"?r:o(r)??JSON.stringify(r);export{n as serializeSqlValue};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as O}from"@lunora/errors";import{sql as l}from"drizzle-orm";import{sqliteInList as A,isJsonSafe as R,WORKERD_SQLITE_LIMITS as T}from"./param-DlozcSQu.mjs";import{quoteIdentifier as b}from"./quoteIdentifier-CObIFRhb.mjs";import{RELATION_EXISTS_KEY as L}from"./RELATION_EXISTS_KEY-CFUhnZSZ.mjs";const $={binary:(n,t,o)=>l`${n} ${l.raw(t)} ${o}`,constant:n=>n?l`1 = 1`:l`0 = 1`,connect:(n,t,o)=>l`(${n}) ${l.raw(o)} (${t})`,contains:(n,t)=>l`instr(lower(${n}), lower(${t})) > 0`,inList:(n,t,o,i)=>A(n,t,o,i),negate:n=>l`NOT (${n})`,nullCheck:(n,t)=>t?l`${n} IS NOT NULL`:l`${n} IS NULL`,value:n=>l`${n}`},u=(...n)=>{let t="";const o=[];for(const i of n)typeof i=="string"?t+=i:(t+=i.text,o.push(...i.params));return{params:o,text:t}},p=n=>({params:[n],text:"?"}),S=n=>({params:[],text:n}),Y=n=>S(b(n)),B={binary:(n,t,o)=>u(n," ".concat(t," "),p(o)),constant:n=>S(n?"1 = 1":"0 = 1"),connect:(n,t,o)=>u("(",n,") ".concat(o," ("),t,")"),contains:(n,t)=>u("instr(lower(",n,"), lower(",t,")) > 0"),inList:(n,t,o,i)=>{const r=o?" NOT IN ":" IN ";if(t.length>i&&!t.every(s=>R(s)))throw new O("BAD_REQUEST",`an "in" list of ${String(t.length)} values holds a value JSON cannot carry (bytes, a non-finite number, or malformed text), so it cannot be bound as one parameter — and ${String(t.length)} placeholders exceed SQLite's per-statement cap of 100 on Durable Objects and D1. Narrow the list to ${String(i)} values or fewer.`);if(t.length<=i){const s=[n,r,"("];for(const[e,c]of t.entries())e>0&&s.push(", "),s.push(p(c));return s.push(")"),u(...s)}return u(n,r,'(SELECT "value" FROM json_each(',p(JSON.stringify(t)),"))")},negate:n=>u("NOT (",n,")"),nullCheck:(n,t)=>u(n,t?" IS NOT NULL":" IS NULL"),value:p},m=T.boundParams/2,I=["eq","ne","lt","lte","gt","gte","in","notIn","isNull","contains"],x=new Set(I),_={eq:"=",gt:">",gte:">=",lt:"<",lte:"<=",ne:"<>"},E=n=>{if(n===null||typeof n!="object"||Array.isArray(n))return!1;const t=Object.keys(n);return t.length>0&&t.every(o=>x.has(o))},j=(n,t,o,i)=>{const r=i.value(o.serialize(t));return o.containsExpr?o.containsExpr(n,r):i.contains(n,r)},w=(n,t,o,i,r,s)=>i===null?t==="eq"||t==="ne"?s.nullCheck(n,t==="ne"):s.constant(!1):s.binary(n,o,r.serialize(i)),C=(n,t,o,i,r)=>{const s=Array.isArray(o)?o:[];if(s.length===0)return r.constant(t==="NOT IN");const e=s.map(a=>i.serialize(a)),c=t==="NOT IN";return i.inList?i.inList(n,e,c):r.inList(n,e,c,m)},G=(n,t,o)=>{const i=l.join(t.map(r=>l`${r}`),l`, `);return o?l`${n} NOT IN (${i})`:l`${n} IN (${i})`},y=(n,t,o,i)=>{const r=t,s=[];for(const e of I){if(!(e in r))continue;const c=r[e],a=_[e];a?s.push(w(n,e,a,c,o,i)):e==="isNull"?s.push(i.nullCheck(n,!c)):e==="contains"?s.push(j(n,c,o,i)):s.push(C(n,e==="in"?"IN":"NOT IN",c,o,i))}return s},k=(n,t,o,i)=>{const r=o.fieldRef(n);return E(t)?y(r,t,o,i):t===null?[i.nullCheck(r,!1)]:[i.binary(r,"=",o.serialize(t))]},h=(n,t,o)=>{if(n.length<=1)return n[0];const i=Math.floor(n.length/2);return o.connect(h(n.slice(0,i),t,o),h(n.slice(i),t,o),t)},D=(n,t,o,i)=>{const r=Array.isArray(n)?n:[],s=[];for(const e of r){const c=N(e??{},o,i);c!==void 0&&s.push(c)}return s.length===0?t==="OR"?i.constant(!1):void 0:h(s,t,i)},U=new Set(["AND","NOT","OR",L]),q=(n,t,o,i)=>{if(n===L){if(!o.relationExists)throw new O("INTERNAL","encountered a relation EXISTS marker without a relationExists strategy hook");return o.relationExists(t)}if(n==="NOT"){const r=N(t??{},o,i);return r===void 0?void 0:i.negate(r)}return D(t,n,o,i)},N=(n,t,o)=>{const i=[];for(const[r,s]of Object.entries(n))if(U.has(r)){const e=q(r,s,t,o);e!==void 0&&i.push(e)}else i.push(...k(r,s,t,o));return h(i,"AND",o)},v=T.boundParams/2,f=n=>{if(Array.isArray(n))return n.reduce((o,i)=>o+f(i),0);if(n===null||typeof n!="object")return 0;let t=0;for(const[o,i]of Object.entries(n))o==="in"||o==="notIn"?t+=1:(o==="AND"||o==="NOT"||o==="OR"||E(i))&&(t+=f(i));return t},J=(n,t,o=$)=>{if(!n||Object.keys(n).length===0)return;const i=f(n);if(i===0)return N(n,t,o);const r=Math.max(1,Math.floor(v/i)),s=t.inList??((e,c,a,d)=>o.inList(e,c,a,d??r));return N(n,{...t,inList:(e,c,a)=>s(e,c,a,r)},o)};export{J as c,Y as i,u as j,G as l,S as r,B as t};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{t as w,f as l}from"./base64-DfpzS4o_.mjs";const o="$lunora.wire$",m=64,A=1024,g="__proto__",p={BigInt64Array,BigUint64Array,Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array},O={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},j=r=>{if(r===null||typeof r!="object")return!1;const t=Object.getPrototypeOf(r);return t===null||t===Object.prototype},E=(r,t=0)=>{if(t>m)return!0;if(r===null)return!1;const c=typeof r;if(c==="string"||c==="boolean")return!1;if(c==="number")return!Number.isFinite(r);if(c!=="object")return!0;if(Array.isArray(r))return r.length>0&&r[0]===o?!0:r.some(f=>f===void 0||E(f,t+1));if(!j(r)||Object.hasOwn(r,g))return!0;for(const f of Object.keys(r)){const i=r[f];if(i!==void 0&&E(i,t+1))return!0}return!1},u=(r,t=0)=>{if(t>m)throw new RangeError(`wire-codec: value nesting exceeds the ${m}-level limit`);if(r===void 0)return[o,"undefined"];if(r===null)return null;const c=typeof r;if(c==="bigint")return[o,"bigint",r.toString()];if(c==="number"){const e=r;return Number.isNaN(e)?[o,"nan"]:e===1/0?[o,"inf"]:e===-1/0?[o,"-inf"]:e}if(c!=="object")return r;if(r instanceof Date)return[o,"date",u(r.getTime(),t+1)];if(r instanceof Error){const e=r,n={};for(const a of Object.keys(e))e[a]!==void 0&&(n[a]=u(e[a],t+1));const s=[o,"error",e.name,e.message,n];return e.cause!==void 0&&s.push(u(e.cause,t+1)),s}if(r instanceof URL)return[o,"url",r.href];if(r instanceof Map)return[o,"map",[...r.entries()].map(([e,n])=>[u(e,t+1),u(n,t+1)])];if(r instanceof Set)return[o,"set",[...r].map(e=>u(e,t+1))];if(r instanceof ArrayBuffer)return[o,"bytes",w(new Uint8Array(r)),"ArrayBuffer"];if(ArrayBuffer.isView(r)){const e=r,n=e.constructor.name,s=new Uint8Array(e.buffer,e.byteOffset,e.byteLength);return n==="Uint8Array"?[o,"bytes",w(s)]:[o,"bytes",w(s),n]}if(Array.isArray(r)){const e=r.map(n=>u(n,t+1));return e.length>0&&e[0]===o?[o,"arr",e]:e}if(!j(r)){const e=r.constructor?.name??"value";throw new TypeError(`wire-codec: cannot encode a ${e} 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 f=r,i={};for(const e of Object.keys(f)){const n=f[e];if(n===void 0)continue;const s=u(n,t+1);e===g?Object.defineProperty(i,e,{configurable:!0,enumerable:!0,value:s,writable:!0}):i[e]=s}return i},y=(r,t=0)=>{if(t>m)throw new RangeError(`wire-codec: value nesting exceeds the ${m}-level limit`);if(r===null||typeof r!="object")return r;if(Array.isArray(r)){if(r[0]===o)switch(r[1]){case"-inf":return-1/0;case"arr":return r[2].map(e=>y(e,t+1));case"bigint":{const e=r[2];if(typeof e!="string"||e.length>A||!/^-?\d+$/.test(e))throw new RangeError(`wire-codec: invalid or over-long bigint (max ${A} digits)`);return BigInt(e)}case"date":return new Date(y(r[2],t+1));case"map":{const e=r[2];return new Map(e.map(n=>{if(!Array.isArray(n)||n.length!==2)throw new TypeError("wire-codec: malformed map entry — expected a [key, value] pair");return[y(n[0],t+1),y(n[1],t+1)]}))}case"set":return new Set(r[2].map(e=>y(e,t+1)));case"url":return new URL(r[2]);case"error":{const e=r[2],n=r[3],s=(Object.hasOwn(O,e)?O[e]:void 0)??Error,a=new s(n);a.name!==e&&Object.defineProperty(a,"name",{configurable:!0,value:e,writable:!0});const d=y(r[4],t+1);for(const b of Object.keys(d))b===g?Object.defineProperty(a,b,{configurable:!0,enumerable:!0,value:d[b],writable:!0}):a[b]=d[b];return r.length>5&&Object.defineProperty(a,"cause",{configurable:!0,value:y(r[5],t+1),writable:!0}),a}case"bytes":{const e=l(r[2]),n=r[3]??"Uint8Array";if(n==="ArrayBuffer")return e.buffer.byteLength===e.byteLength?e.buffer:e.slice().buffer;const s=Object.hasOwn(p,n)?p[n]:void 0;return s?new s(e.slice().buffer):e}case"inf":return 1/0;case"nan":return Number.NaN;case"undefined":return;default:return r.map(e=>y(e,t+1))}return r.map(i=>y(i,t+1))}const c=r,f={};for(const i of Object.keys(c)){const e=y(c[i],t+1);i===g?Object.defineProperty(f,i,{configurable:!0,enumerable:!0,value:e,writable:!0}):f[i]=e}return f};export{y as d,u as e,j as i,E as n};
|