@lunora/shard-engine 1.0.0-alpha.127 → 1.0.0-alpha.129
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 +1 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/{ADMIN_FUNCTIONS-Bsvi2ytY.mjs → ADMIN_FUNCTIONS-DmacEYTh.mjs} +1 -1
- package/dist/packem_shared/{AGG_COUNT-D77Ynq1b.mjs → AGG_COUNT-DYFE3qB4.mjs} +1 -1
- package/dist/packem_shared/{AUDIT_LOG_TABLE-CZNxCRLv.mjs → AUDIT_LOG_TABLE-CuIP7PJ0.mjs} +1 -1
- package/dist/packem_shared/{CDC_LOG_TABLE-BPEzVAil.mjs → CDC_LOG_TABLE-CvInVdXu.mjs} +1 -1
- package/dist/packem_shared/{CLIENT_WATERMARK_TABLE-vLjfNhBR.mjs → CLIENT_WATERMARK_TABLE-_CkdMnT2.mjs} +1 -1
- package/dist/packem_shared/{COMMIT_SEQ_FIELD-BY_vc9bw.mjs → COMMIT_SEQ_FIELD-BcUO15fR.mjs} +1 -1
- package/dist/packem_shared/{DATA_MIGRATION_STATE_TABLE-CqPrNKql.mjs → DATA_MIGRATION_STATE_TABLE-CGF7qQsu.mjs} +1 -1
- package/dist/packem_shared/{DEFAULT_MAX_RELATION_KEYS-Bk8B9GIQ.mjs → DEFAULT_MAX_RELATION_KEYS-COmk7y1x.mjs} +1 -1
- package/dist/packem_shared/{DEFAULT_MAX_RELAYS-BqSpObEl.mjs → DEFAULT_MAX_RELAYS-DSIYUnPB.mjs} +1 -1
- package/dist/packem_shared/{DurableStreamRunner-y2CRbfuZ.mjs → DurableStreamRunner-SCTUaMG0.mjs} +1 -1
- package/dist/packem_shared/{GLOBAL_SHAPE_SNAPSHOT_TABLE-pMxZ-obU.mjs → GLOBAL_SHAPE_SNAPSHOT_TABLE-Du0PbPdS.mjs} +1 -1
- package/dist/packem_shared/{IDEMPOTENCY_TABLE-AOJCuq5U.mjs → IDEMPOTENCY_TABLE-CymJf4r0.mjs} +1 -1
- package/dist/packem_shared/{MAIL_RETENTION-BxAGL3hK.mjs → MAIL_RETENTION-BP1GSXQ0.mjs} +1 -1
- package/dist/packem_shared/NotUniqueError-B69J01E7.mjs +1 -0
- package/dist/packem_shared/{QUEUE_TABLE-DKANxmEZ.mjs → QUEUE_TABLE-jEc6-2wm.mjs} +1 -1
- package/dist/packem_shared/{REACTOR_STATE_TABLE-B8IehLv8.mjs → REACTOR_STATE_TABLE-DHaBP_vb.mjs} +1 -1
- package/dist/packem_shared/RLS_UNWRAP_SYMBOL-BV39QRFd.mjs +1 -0
- package/dist/packem_shared/{SCHEDULE_OUTBOX_TABLE-CgLvGxpY.mjs → SCHEDULE_OUTBOX_TABLE-C_Me442c.mjs} +1 -1
- package/dist/packem_shared/{SCHEMA_HISTORY_MAX_VERSIONS-BMcUIqBY.mjs → SCHEMA_HISTORY_MAX_VERSIONS-SQVxBlum.mjs} +1 -1
- package/dist/packem_shared/{SEARCH_STATE_TABLE-wgl-SePe.mjs → SEARCH_STATE_TABLE-BThmEiED.mjs} +1 -1
- package/dist/packem_shared/{SHAPE_POKE_CURSOR_TABLE-cn0stGAL.mjs → SHAPE_POKE_CURSOR_TABLE-B6MXBH-p.mjs} +1 -1
- package/dist/packem_shared/{VECTOR_BACKFILL_MAX_PAGES-D9DeCfM2.mjs → VECTOR_BACKFILL_MAX_PAGES-CIi7v65O.mjs} +1 -1
- package/dist/packem_shared/WORKERD_SQLITE_LIMITS-BdNnnMj0.mjs +1 -0
- package/dist/packem_shared/{appendStreamChunk-7ZyAZGg_.mjs → appendStreamChunk-DF_Jrgpy.mjs} +1 -1
- package/dist/packem_shared/{archiveCdcSegment-BON69Nug.mjs → archiveCdcSegment-CIiYU1FU.mjs} +1 -1
- package/dist/packem_shared/{backfillAggregateIndexes-CJrtolQ9.mjs → backfillAggregateIndexes-DBrKU3Ya.mjs} +1 -1
- package/dist/packem_shared/{buildReprojectionMigration-CRS4SNgc.mjs → buildReprojectionMigration-D29YmeMF.mjs} +1 -1
- package/dist/packem_shared/{buildShapeDiff-C3hPtSKO.mjs → buildShapeDiff-CdT2gjFd.mjs} +1 -1
- package/dist/packem_shared/{clearCompanionSignatures-C2CSfkeQ.mjs → clearCompanionSignatures-Qf67j6dd.mjs} +1 -1
- package/dist/packem_shared/{clearMemoryTables-CogAvVHR.mjs → clearMemoryTables-Lu0S2GOb.mjs} +1 -1
- package/dist/packem_shared/{compileWhereSql-BaMGeXXq.mjs → compileWhereSql-Dol9VRTW.mjs} +1 -1
- package/dist/packem_shared/{computeRankPage-CFeFkZ_k.mjs → computeRankPage-D9mACvr3.mjs} +1 -1
- package/dist/packem_shared/{createCompanionSync-B7dV2y4L.mjs → createCompanionSync-C2cZNaCR.mjs} +1 -1
- package/dist/packem_shared/{createReplicaLink-B9F5PAQ0.mjs → createReplicaLink-DjykIKTn.mjs} +1 -1
- package/dist/packem_shared/{ctx-db-relay-shapes-kGRKSxRs.mjs → ctx-db-relay-shapes-OAI2tSoy.mjs} +1 -1
- package/dist/packem_shared/{ctx-db-search-state-DVCp4JQf.mjs → ctx-db-search-state-CrTLPmFN.mjs} +1 -1
- package/dist/packem_shared/{defineEngineContractSuite-dlOQgRU1.mjs → defineEngineContractSuite-DCw8RIP6.mjs} +1 -1
- package/dist/packem_shared/{do-sql-Cg3zXJpF.mjs → do-sql-CeuVvE0W.mjs} +1 -1
- package/dist/packem_shared/{exportShardRows-CTDgQEF8.mjs → exportShardRows-yxw7vFf9.mjs} +1 -1
- package/dist/packem_shared/{fts-companion-pUdD6kF-.mjs → fts-companion-DzfEHonU.mjs} +1 -1
- package/dist/packem_shared/{ftsCompanionDdl-Co6WSyCB.mjs → ftsCompanionDdl-Cka6_-Fm.mjs} +1 -1
- package/dist/packem_shared/{isSoftDeleted-BTGu2iBl.mjs → isSoftDeleted-CLY0FNLV.mjs} +1 -1
- package/dist/packem_shared/{materializeExternalRows-Cx6_A2W3.mjs → materializeExternalRows-UxGuXjjF.mjs} +1 -1
- package/dist/packem_shared/{runDrizzle-Du5HLitO.mjs → runDrizzle-B2GG3IJa.mjs} +1 -1
- package/dist/packem_shared/{runShardMigrations-eqHNBW6S.mjs → runShardMigrations-B6FUu4iW.mjs} +1 -1
- package/dist/packem_shared/{selectExpiredIds-CilDdUr2.mjs → selectExpiredIds-CGR1ndMV.mjs} +1 -1
- package/dist/packem_shared/{selectShapeMembers-CU8Kl2Bq.mjs → selectShapeMembers-DS28-P_Z.mjs} +1 -1
- package/dist/packem_shared/{where-sql-Dn9trjRu.mjs → where-sql-CxnXsLbt.mjs} +1 -1
- package/package.json +1 -1
- package/dist/packem_shared/NotUniqueError-BXDZxdAt.mjs +0 -1
- package/dist/packem_shared/RLS_UNWRAP_SYMBOL-qYcAxjuk.mjs +0 -1
- package/dist/packem_shared/WORKERD_SQLITE_LIMITS-DBH23L_S.mjs +0 -1
package/dist/packem_shared/{archiveCdcSegment-BON69Nug.mjs → archiveCdcSegment-CIiYU1FU.mjs}
RENAMED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{sql as s}from"drizzle-orm";import{runDrizzle as d}from"./runDrizzle-
|
|
1
|
+
import{sql as s}from"drizzle-orm";import{runDrizzle as d}from"./runDrizzle-B2GG3IJa.mjs";const C=16,T=32,v=1e4,R=1e3,h=t=>String(t).padStart(C,"0"),f=t=>`cdc/${encodeURIComponent(t.shard)}/${encodeURIComponent(t.epoch)}/`,y=(t,n)=>`${f(t)}${h(n)}.json`,E="__cdc_archive",g=t=>{d(t,s`CREATE TABLE IF NOT EXISTS ${s.identifier(E)} (
|
|
2
2
|
id INTEGER PRIMARY KEY CHECK (id = 1),
|
|
3
3
|
seq INTEGER NOT NULL
|
|
4
4
|
)`)},$=t=>(g(t),d(t,s`SELECT seq FROM ${s.identifier(E)} WHERE id = 1`).toArray()[0]?.seq??0),w=(t,n)=>{g(t),d(t,s`INSERT INTO ${s.identifier(E)} (id, seq) VALUES (1, ${n}) ON CONFLICT (id) DO UPDATE SET seq = ${n}`)},L=async(t,n,e)=>{const o=e[0]?.seq,r=e.at(-1)?.seq;o===void 0||r===void 0||await t.put(y(n,r),JSON.stringify({changes:e,from:o,to:r}),{httpMetadata:{contentType:"application/json"}})},j=async(t,n,e)=>{const o=f(n);return(await t.list({limit:1,prefix:o,startAfter:`${o}${h(e)}.json`})).objects.length>0},S=t=>{let n;try{n=JSON.parse(t)}catch{return}if(typeof n!="object"||n===null)return;const e=n;return typeof e.from=="number"&&typeof e.to=="number"&&Array.isArray(e.changes)?e:void 0},_=(t,n)=>{const e=[];for(const o of t.changes)if(!(o.seq<=n)){if(o.op!=="delete"&&o.doc===void 0)break;e.push(o)}return e},I=(t,n,e)=>{let o=e;for(const r of n){if(r.seq!==o+1)break;t.push(r),o=r.seq}return o},b=async(t,n)=>{const e=await t.get(n);return e===null?void 0:S(await e.text())},q=async(t,n,e,o)=>{const r=f(n),p=Math.max(1,Math.min(o??R,v)),A=await t.list({limit:T,prefix:r,startAfter:`${r}${h(e)}.json`}),c=[];let i=e;for(const l of A.objects){const a=await b(t,l.key);if(a===void 0)break;const m=_(a,i);if(i=I(c,m,i),c.length>=p||i!==a.to)break}if(c[0]?.seq!==e+1)return;const u=c.slice(0,p);return{changes:u,cursor:u.at(-1)?.seq??e}};export{L as archiveCdcSegment,j as cdcArchiveRewound,q as readArchivedCdcChanges,$ as readCdcArchivedThrough,w as writeCdcArchivedThrough};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{m as P,c as E,l as w,r as T,a as D,w as F}from"./ctx-db-search-state-
|
|
1
|
+
import{m as P,c as E,l as w,r as T,a as D,w as F}from"./ctx-db-search-state-CrTLPmFN.mjs";import{S as I,c as L,g as _,d as x,e as b,a as k}from"./fts-companion-DzfEHonU.mjs";import{sql as i}from"drizzle-orm";import{ensureAggregateCompanion as y,ensureRankCompanion as B}from"./createCompanionSync-C2cZNaCR.mjs";import{runDrizzle as p,runAll as C}from"./runDrizzle-B2GG3IJa.mjs";import{i as M,D as m,h as A}from"./do-sql-CeuVvE0W.mjs";import{sqliteInList as U}from"./WORKERD_SQLITE_LIMITS-BdNnnMj0.mjs";const v=(e,o)=>p(e,i`SELECT 1 FROM ${i.identifier(o)} LIMIT 1`).toArray().length>0,Q=(e,o)=>{for(const[r,n]of Object.entries(o.tables))if(n.shardMode?.kind!=="global")for(const t of n.aggregateIndexes??[])y(e,r,t,n.softDeleteMode?.field)},X=(e,o)=>{for(const[r,n]of Object.entries(o.tables))if(n.shardMode?.kind!=="global")for(const t of n.rankIndexes??[])B(e,r,t,n.softDeleteMode?.field)},H=(e,o,r,n)=>p(e,r===void 0?i`SELECT id, _creationTime, ${i.identifier(m)} FROM ${i.identifier(o)} ORDER BY id ASC LIMIT ${i.raw(String(n))}`:i`SELECT id, _creationTime, ${i.identifier(m)} FROM ${i.identifier(o)} WHERE id > ${r} ORDER BY id ASC LIMIT ${i.raw(String(n))}`).toArray(),h=500,O=(e,o,r)=>{const n=I(o,r.name),t=E(r),a=w(T(e,n),t);if(a.finished)return{done:!0,rows:0};const{cursor:c}=a,s=H(e,o,c,h);let f=c;for(const g of s){const{id:u}=g;if(typeof u!="string")continue;f=u;const S=A(g);C(e,S?x(n,u,b(S,r)):k(n,u))}const d=s.length<h;return F(e,n,f,d,t),{done:d,rows:s.length}},l=(e,o)=>i`${i.identifier(e)}.${i.identifier(o)}`,R=500,$=(e,o,r)=>{const n=I(o,r.name),t=p(e,L(n,R)).toArray(),a=_(t);if(a.size===0)return!0;const c=new Map;for(const s of p(e,i`SELECT ${l(o,"id")}, ${l(o,"_creationTime")}, ${l(o,m)} FROM ${i.identifier(o)} WHERE ${U(l(o,"id"),[...a.keys()],!1)}`))c.set(String(s.id),s);for(const[s,f]of a){const d=c.get(s),g=d?A(d):void 0;C(e,g?x(n,s,b(g,r),{unmappedRowids:f}):k(n,s,{unmappedRowids:f}))}return t.length<R},W=(e,o,r,n)=>{let t=0;for(;t<n&&!$(e,o,r);)t+=1;return t},Z=(e,o,r)=>{const n=I(o,r.name),t=E(r);return w(T(e,n),t).finished?!0:D(e,n)},q=(e,o,r)=>{if(M(e))for(const n of r.searchIndexes??[])$(e,o,n),!(n.staged&&v(e,o))&&O(e,o,n)},j=(e,o,r,n)=>{let t=0;for(;;){if(t>=n)return{done:!1,pages:t};const a=O(e,o,r);if(a.rows>0&&(t+=1),a.done)return{done:!0,pages:t}}},ee=(e,o,r={})=>{if(!M(e))return{done:!0,pages:0};P(e);const n=r.maxPages??Number.POSITIVE_INFINITY;let t=0;for(const[a,c]of Object.entries(o.tables))if(!(c.shardMode?.kind==="global"||!c.searchIndexes))for(const s of c.searchIndexes){if(t+=W(e,a,s,n-t),t>=n)return{done:!1,pages:t};const f=j(e,a,s,n-t);if(t+=f.pages,!f.done)return{done:!1,pages:t}}return{done:!0,pages:t}};export{Q as backfillAggregateIndexes,X as backfillRankIndexes,ee as backfillSearchIndexes,q as backfillSearchIndexesForTable,H as readKeysetPage,Z as searchIndexCoversTable};
|
|
@@ -1 +1 @@
|
|
|
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 d}from"./wire-codec-BYCSiazv.mjs";import{runSql as p}from"./runDrizzle-
|
|
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 d}from"./wire-codec-BYCSiazv.mjs";import{runSql as p}from"./runDrizzle-B2GG3IJa.mjs";import{k as m,D as E}from"./do-sql-CeuVvE0W.mjs";import{mayHoldProjectedValue as g}from"./BIGINT_KEY_DIGITS-C9a7Ix7k.mjs";const b=d(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{m(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 +1 @@
|
|
|
1
|
-
import{readCdcChangeKeys as s}from"./CDC_LOG_TABLE-
|
|
1
|
+
import{readCdcChangeKeys as s}from"./CDC_LOG_TABLE-CvInVdXu.mjs";import{selectShapeMembers as h}from"./selectShapeMembers-DS28-P_Z.mjs";import{shapeRangeKey as u}from"./ShapeDiffCache-Br3kxusw.mjs";import{projectColumns as g}from"./buildPokeFrames-CDOP-XYp.mjs";const C=(m,e,a,i,p,f=s)=>{const r=u(e.table,a,i),n=p.changedKeys(r,()=>f(m,e.table,a,i));if(n.length===0)return[];const b=p.members(e,r,()=>h(m,e.table,e.effectiveWhere,n.map(t=>t.id))),o=[];for(const t of n){const c=b.get(t.id);if(c===void 0){t.op!=="insert"&&o.push({key:t.id,op:"delete",table:e.table});continue}o.push({key:t.id,op:t.op,table:e.table,value:g(c,e.columns)})}return o};export{C as buildShapeDiff};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{sql as t}from"drizzle-orm";import{compareStrings as a,encodeAggregateKey as T}from"./aggregateTableName-DbAttCNH.mjs";import{runDrizzle as r}from"./runDrizzle-
|
|
1
|
+
import{sql as t}from"drizzle-orm";import{compareStrings as a,encodeAggregateKey as T}from"./aggregateTableName-DbAttCNH.mjs";import{runDrizzle as r}from"./runDrizzle-B2GG3IJa.mjs";import{sqliteInList as f}from"./WORKERD_SQLITE_LIMITS-BdNnnMj0.mjs";const n="__lunora_companion_state",g=1,c=1,E=i=>i?T(Object.keys(i),i):"",$=(i,e)=>JSON.stringify([g,(i.by??[]).toSorted(a),i.field??"",i.op,E(i.where),e??""]),d=(i,e)=>JSON.stringify([c,(i.partitionBy??[]).toSorted(a),i.sortBy.map(o=>o.field),E(i.where),e??""]),s=i=>{r(i,t`CREATE TABLE IF NOT EXISTS ${t.identifier(n)} (${t.identifier("companion")} TEXT PRIMARY KEY, ${t.identifier("signature")} TEXT NOT NULL)`)},u=(i,e)=>{s(i),r(i,e.length===0?t`DELETE FROM ${t.identifier(n)}`:t`DELETE FROM ${t.identifier(n)} WHERE ${f(t.raw('"companion"'),e,!0)}`)},R=(i,e)=>r(i,t`SELECT ${t.identifier("signature")} FROM ${t.identifier(n)} WHERE ${t.identifier("companion")} = ${e}`).toArray()[0]?.signature,A=(i,e,o)=>{r(i,t`INSERT INTO ${t.identifier(n)} (${t.identifier("companion")}, ${t.identifier("signature")}) VALUES (${e}, ${o}) ON CONFLICT (${t.identifier("companion")}) DO UPDATE SET ${t.identifier("signature")} = excluded.${t.identifier("signature")}`)},N=i=>{s(i),r(i,t`DELETE FROM ${t.identifier(n)}`)};export{$ as aggregateSignature,N as clearCompanionSignatures,u as migrateCompanionState,d as rankSignature,R as readCompanionSignature,A as writeCompanionSignature};
|
package/dist/packem_shared/{clearMemoryTables-CogAvVHR.mjs → clearMemoryTables-Lu0S2GOb.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{sql as t}from"drizzle-orm";import{runDrizzle as s}from"./runDrizzle-
|
|
1
|
+
import{sql as t}from"drizzle-orm";import{runDrizzle as s}from"./runDrizzle-B2GG3IJa.mjs";const a=r=>r?.memoryMode===!0,l=r=>Object.entries(r.tables).filter(([,e])=>a(e)&&e.shardMode?.kind!=="global").map(([e])=>e),i=(r,e)=>{const o=l(e);for(const m of o)s(r,t`DELETE FROM ${t.identifier(m)}`);return o.length};export{i as clearMemoryTables,a as isMemoryTable,l as memoryTableNames};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import"./json-field-path-B2fjnGc3.mjs";import"./WORKERD_SQLITE_LIMITS-
|
|
1
|
+
import"./json-field-path-B2fjnGc3.mjs";import"./WORKERD_SQLITE_LIMITS-BdNnnMj0.mjs";import{c as p,s}from"./where-sql-CxnXsLbt.mjs";import"./RELATION_EXISTS_KEY-wxgj6rSL.mjs";export{p as compileWhereSql,s as serverInList};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as g}from"@lunora/errors";import{sql as o}from"drizzle-orm";import{mergeWhere as b}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{SCAN_DEP as j}from"./SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as A}from"./runDrizzle-
|
|
1
|
+
import{LunoraError as g}from"@lunora/errors";import{sql as o}from"drizzle-orm";import{mergeWhere as b}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{SCAN_DEP as j}from"./SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as A}from"./runDrizzle-B2GG3IJa.mjs";import{sqliteInList as O}from"./WORKERD_SQLITE_LIMITS-BdNnnMj0.mjs";import{decodeCursor as F,CURSOR_PREFIX as P,toBase64 as U}from"./CURSOR_PREFIX-BztyXqNP.mjs";import{rankTableName as V,sortColumnName as z,resolveRankPartition as H,RANK_TIEBREAK as _,encodePartitionKey as J,rankPivotConditionSql as X}from"./RANK_TIEBREAK-BKugKf70.mjs";const Y="__doc__",G=n=>P+U(JSON.stringify(n)),Q=n=>n.after?[n.after.partitionKey,...n.after.sortValues,n.after.rowId]:n.cursor?F(n.cursor):void 0,Z=(n,r,f)=>{if(n?.length!==1+r.length+1)return;const t=[{column:"__partition__",direction:"asc"}];for(const[c,u]of r.entries())t.push({column:u,direction:f[c]?.direction??"asc"});t.push({column:_,direction:"asc"});const e=[];for(const[c,u]of t.entries()){const d=X(u.column,n[c],u.direction,!0);if(d===void 0)continue;const s=[];for(const[m,l]of t.slice(0,c).entries())s.push(o`${o.identifier(l.column)} IS ${n[m]}`);s.push(d);const[i]=s;e.push(s.length===1&&i!==void 0?i:o`(${o.join(s,o` AND `)})`)}return e.length===0?o`(1 = 0)`:o`(${o.join(e,o` OR `)})`},v=null,oo=(n,r)=>{if(n===void 0)return v;const f=[n.__partition__,...r.map(t=>n[t]),n[_]];return G(f)},no=(n,r,f)=>{const t=[];for(const e of n){const c=e[_];if(typeof c!="string")continue;const u=r.get(c);if(!u)continue;const d=typeof e.__partition__=="string"?e.__partition__:"",s=f.map(i=>e[i]??null);t.push({doc:u,key:{partitionKey:d,rowId:c,sortValues:s}})}return t},to=o`${o.identifier("id")}`,ro=(n,r,f)=>{const{rowToDocument:t}=n,e=new Map;if(f.length===0)return e;const c=A(n.sql,o`SELECT id, _creationTime, ${o.identifier(Y)} FROM ${o.identifier(r)} WHERE ${O(to,f,!1)}`).toArray();for(const u of c){const d=t(u),s=u.id;d&&typeof s=="string"&&e.set(s,d)}return e},_o=(n,r,f,t)=>{const{assertRankPartitionLocal:e,ensureRankBackfilled:c,onRead:u,schema:d}=n,s=d.tables[r];if(!s)throw new g("INTERNAL",`unknown table: ${r}`);const i=s.rankIndexes?.find(a=>a.name===f);if(!i)throw new g("INTERNAL",`unknown rankIndex "${f}" on table "${r}"`);e(r,s,i),u(r,j),c(r,i);const m=V(r,i.name),l=i.sortBy.map((a,w)=>z(w)),h=Math.max(1,Math.min(1e3,Math.floor(t.take??100))),T=b(t.baseWhere,t.where),k=H(i,T),R=[o`${o.identifier("__partition__")} ASC`];for(const[a,w]of l.entries()){const W=i.sortBy[a]?.direction;R.push(o`${o.identifier(w)} ${o.raw(W==="desc"?"DESC":"ASC")}`)}R.push(o`${o.identifier(_)} ASC`);const p=[];typeof t.partitionKey=="string"?p.push(o`${o.identifier("__partition__")} = ${t.partitionKey}`):k&&p.push(o`${o.identifier("__partition__")} = ${J(i.partitionBy??[],k)}`);const B=Q(t),E=Z(B,l,i.sortBy);E&&p.push(E);const I=o.identifier(_),S=o.identifier("__partition__"),D=p.length>0?o` WHERE ${o.join(p,o` AND `)}`:o``,L=l.length>0?o`${I}, ${S}, ${o.join(l.map(a=>o.identifier(a)),o`, `)}`:o`${I}, ${S}`,M=o`SELECT ${L} FROM ${o.identifier(m)}${D} ORDER BY ${o.join(R,o`, `)} LIMIT ${o.raw(String(h+1))}`,$=A(n.sql,M).toArray(),C=$.length>h,y=C?$.slice(0,h):$,K=y.map(a=>a[_]),q=no(y,ro(n,r,K),l),x=C?oo(y.at(-1),l):v,N=i.sortBy.map(a=>a.direction==="desc"?"desc":"asc");return{continueCursor:x,directions:N,hasMore:C,rows:q}};export{_o as computeRankPage,Q as resolveRankSeekTuple};
|
package/dist/packem_shared/{createCompanionSync-B7dV2y4L.mjs → createCompanionSync-C2cZNaCR.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{N as co,S as ao,d as fo,e as lo,a as uo}from"./fts-companion-
|
|
1
|
+
import{N as co,S as ao,d as fo,e as lo,a as uo}from"./fts-companion-DzfEHonU.mjs";import{sql as o}from"drizzle-orm";import{r as z}from"./json-field-path-B2fjnGc3.mjs";import{matchesStaticWhere as Q,aggregateSqlFunction as $o}from"./AGGREGATE_SQL_FUNCTION-BMtvQHac.mjs";import{aggregateTableName as H,foldAggregateTally as X,encodeAggregateKey as k,coerceAggregateNumber as U}from"./aggregateTableName-DbAttCNH.mjs";import{aggregateSignature as Eo,readCompanionSignature as Y,rankSignature as go,writeCompanionSignature as J}from"./clearCompanionSignatures-Qf67j6dd.mjs";import{runAll as po,runDrizzle as g}from"./runDrizzle-B2GG3IJa.mjs";import{i as mo,g as _o,a as O,b as T,A as _,c as j,D as Z,r as N,e as P}from"./do-sql-CeuVvE0W.mjs";import{WORKERD_SQLITE_LIMITS as yo,param as ho}from"./WORKERD_SQLITE_LIMITS-BdNnnMj0.mjs";import{encodeGeohash as So,GEO_DEFAULT_PRECISION as To}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{isLiveForCompanion as x}from"./CURSOR_PREFIX-BztyXqNP.mjs";import{rankTableName as B,matchesRankStaticWhere as oo,sortColumnName as Ro,encodePartitionKey as Ao}from"./RANK_TIEBREAK-BKugKf70.mjs";import{mayHoldProjectedValue as wo}from"./BIGINT_KEY_DIGITS-C9a7Ix7k.mjs";import{serializeSqlValue as eo}from"./serializeSqlValue-BbZ5hKM7.mjs";const Co=(s,l,r)=>[...s.partitionBy??[],...s.sortBy.map(f=>f.field),...s.where?Object.keys(s.where):[]].every(f=>z(l,f)===z(r,f)),no=s=>o.join(["__id__","__partition__",...s.sortBy.map((l,r)=>Ro(r))].map(l=>o.identifier(l)),o`, `),ro=(s,l,r,E,f,a)=>{const t=Ao(r.partitionBy??[],a),R=r.sortBy.map(A=>eo(a[A.field]??null)),y=o.join([f,t,...R].map(A=>ho(A)),o`, `);g(s,o`INSERT INTO ${o.identifier(l)} (${E}) VALUES (${y})`)},to=(s,l,r,E)=>{const f=[];for(const a of g(s,o`SELECT id, _creationTime, ${o.identifier(Z)} FROM ${o.identifier(l)}`)){const t=N(a);t&&x(t,r)&&E(t)&&f.push(t)}return f},vo=(s,l,r,E,f)=>{const a=H(l,r.name),t=r.by??[],R=new Map;for(const w of to(s,l,E,L=>!r.where||Q(L,r.where)))X(R,k(t,w),r,w);g(s,o`DELETE FROM ${o.identifier(a)}`);const y=Math.floor(yo.boundParams/3),A=[...R];for(let w=0;w<A.length;w+=y){const L=A.slice(w,w+y),G=o.join(L.map(([b,D])=>o`(${b}, ${D.value}, ${D.count})`),o`, `);g(s,o`INSERT INTO ${o.identifier(a)} (${O}, ${T}, ${_}) VALUES ${G}`)}J(s,a,f)},Io=(s,l,r,E)=>{const f=Eo(r,E);Y(s,H(l,r.name))!==f&&vo(s,l,r,E,f)},ko=(s,l,r,E,f)=>{const a=B(l,r.name),t=no(r),R=to(s,l,E,y=>!r.where||oo(y,r.where));g(s,o`DELETE FROM ${o.identifier(a)}`);for(const y of R)ro(s,a,r,t,y._id,y);J(s,a,f)},Fo=(s,l,r,E)=>{const f=go(r,E);Y(s,B(l,r.name))!==f&&ko(s,l,r,E,f)},Oo=(s,l,r,E,f,a)=>{if(f&&a&&Co(r,f,a))return;const t=B(l,r.name);f&&g(s,o`DELETE FROM ${o.identifier(t)} WHERE ${o.identifier("__id__")} = ${E}`),!(!a||r.where&&!oo(a,r.where))&&ro(s,t,r,no(r),E,a)},Qo=s=>{const{broadcast:l,indexKeysFor:r,invalidateCache:E,recordCdc:f,schema:a,sql:t}=s,R=new Set,y=e=>a.tables[e]?.softDeleteMode?.field,A=(e,n)=>{const c=H(e,n.name);R.has(c)||(Io(t,e,n,y(e)),R.add(c))},w=(e,n,c)=>{const p=n.by??[],d=n.field??"",$=[],h=(i,u)=>{const m=eo(u);m===null?$.push(o`${P(i)} IS NULL`):$.push(o`${P(i)} = ${m}`)};for(const i of p)h(i,c[i]??null);const C=y(e);C!==void 0&&h(C,null);for(const[i,u]of Object.entries(n.where??{}))h(i,u!==null&&typeof u=="object"&&!Array.isArray(u)?u.eq:u);const F=$.length>0?o` WHERE ${o.join($,o` AND `)}`:o``,M=a.tables[e]?.shape[d];if(M&&wo(M)){const i=g(t,o`SELECT id, _creationTime, ${o.identifier(Z)} FROM ${o.identifier(e)}${F}`).toArray(),u=new Map;for(const m of i){const I=N(m);I&&X(u,"",n,I)}return{value:u.get("")?.value??null}}const W=$o(n.op),S=P(d);return{value:g(t,o`SELECT ${o.raw(W)}(${S}) AS value FROM ${o.identifier(e)}${F}`).one().value??null}},L=(e,n,c,p)=>{const d=H(e,n.name),{op:$}=n,h=n.field??"",C=i=>{g(t,o`DELETE FROM ${o.identifier(d)} WHERE ${O} = ${i} AND ${_} <= 0`)},F=y(e),M=i=>!n.where||Q(i,n.where),W=i=>x(i,F)&&M(i);p!==void 0&&$!=="count"&&M(p)&&U(p[h]);const S=c&&W(c)?c:void 0,v=p&&W(p)?p:void 0;if(!(!S&&!v)){if($==="count"){for(const[i,u]of[[S,-1],[v,1]]){if(!i)continue;const m=k(n.by??[],i);g(t,j(d,m,u,u,o`${T} = ${T} + excluded.${T}, ${_} = ${_} + excluded.${_}`))}S&&C(k(n.by??[],S));return}if($==="sum"||$==="avg"){for(const[i,u]of[[S,-1],[v,1]]){if(!i)continue;const m=U(i[h]);if(m===void 0)continue;const I=k(n.by??[],i);g(t,j(d,I,u*m,u,o`${T} = COALESCE(${T}, 0) + excluded.${T}, ${_} = ${_} + excluded.${_}`))}S&&C(k(n.by??[],S));return}if(S){const i=k(n.by??[],S),u=U(S[h]),m=g(t,o`SELECT ${T} AS value, ${_} AS count FROM ${o.identifier(d)} WHERE ${O} = ${i}`).toArray()[0],I=(m?.count??0)-1;if(I<=0)g(t,o`DELETE FROM ${o.identifier(d)} WHERE ${O} = ${i}`);else if(m&&u!==void 0&&m.value!==null&&u===m.value){const io=w(e,n,S);g(t,o`UPDATE ${o.identifier(d)} SET ${T} = ${io.value}, ${_} = ${I} WHERE ${O} = ${i}`)}else g(t,o`UPDATE ${o.identifier(d)} SET ${_} = ${_} - 1 WHERE ${O} = ${i}`)}if(v){const i=k(n.by??[],v),u=U(v[h]);if(u===void 0)g(t,j(d,i,null,1,o`${_} = ${_} + 1`));else{const m=$==="min"?"MIN":"MAX";g(t,j(d,i,u,1,o`${T} = ${o.raw(m)}(COALESCE(${T}, excluded.${T}), excluded.${T}), ${_} = ${_} + 1`))}}}},G=e=>{for(const n of a.tables[e]?.aggregateIndexes??[])A(e,n)},b=(e,n,c)=>{for(const p of a.tables[e]?.aggregateIndexes??[])L(e,p,n,c)},D=(e,n)=>{const c=B(e,n.name);R.has(c)||(Fo(t,e,n,y(e)),R.add(c))},so=e=>{for(const n of a.tables[e]?.rankIndexes??[])D(e,n)},V=(e,n,c,p)=>{for(const d of a.tables[e]?.rankIndexes??[])Oo(t,e,d,n,c,p)},K=(e,n,c,p)=>{const d=a.tables[e]?.searchIndexes??[];if(!(d.length===0||!mo(t)))for(const $ of d){if(co(p,c,$))continue;const h=ao(e,$.name);po(t,c?fo(h,n,lo(c,$)):uo(h,n))}},q=(e,n,c)=>{for(const p of a.tables[e]?.geoIndexes??[]){const d=_o(e,p.name);g(t,o`DELETE FROM ${o.identifier(d)} WHERE ${o.identifier("__id__")} = ${n}`);const $=c?.[p.field];if($!==null&&typeof $=="object"&&typeof $.lat=="number"&&typeof $.lng=="number"){const{lat:h,lng:C}=$,F=So({lat:h,lng:C},p.precision??To);g(t,o`INSERT INTO ${o.identifier(d)} (${o.identifier("__id__")}, ${o.identifier("__geohash__")}, ${o.identifier("__lat__")}, ${o.identifier("__lng__")}) VALUES (${n}, ${F}, ${h}, ${C})`)}}};return{ensureBackfilledForTable:G,ensureBackfilledIndex:A,ensureRankBackfilled:D,ensureRankBackfilledForTable:so,syncAggregates:b,syncCompanionsForInsert:(e,n,c)=>{K(e,n,c),q(e,n,c),b(e,void 0,c),V(e,n,void 0,c),E(e,n,c),f(e,n,"insert",c),l({indexKeys:r(e,c),key:n,op:"insert",row:c,table:e})},syncGeo:q,syncRanks:V,syncSearch:K}};export{Qo as createCompanionSync,Io as ensureAggregateCompanion,Fo as ensureRankCompanion};
|
package/dist/packem_shared/{createReplicaLink-B9F5PAQ0.mjs → createReplicaLink-DjykIKTn.mjs}
RENAMED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{d as p,e as S}from"./wire-codec-BYCSiazv.mjs";import{cursorBelowRetainedFloor as y}from"./CDC_LOG_TABLE-
|
|
1
|
+
import{d as p,e as S}from"./wire-codec-BYCSiazv.mjs";import{cursorBelowRetainedFloor as y}from"./CDC_LOG_TABLE-CvInVdXu.mjs";import{envPositiveInt as v}from"./envOptionalPositiveInt-D2pY-c64.mjs";import{verifySiblingBody as A,RELAY_SIGNATURE_HEADER as g,siblingStub as N,siblingSecretOf as E,signSiblingBody as T}from"./stubByName-C_P73AOx.mjs";const L=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"],O=new Set(L),I=s=>typeof s=="string"&&O.has(s),h="::replica::",R=s=>{const e=s.lastIndexOf(h);if(e===-1)return;const t=s.slice(0,e),r=s.slice(e+h.length);if(!(t.length===0||!I(r)))return{ownerKey:t,region:r}},b=s=>{if(s==null||!/^\d+$/.test(s))return;const e=Number.parseInt(s,10);return Number.isSafeInteger(e)&&e>0?e:void 0},m=1e3,w=1e3,C=10,U=5e4,F=s=>v(s,"LUNORA_REPLICA_MAX_BOOTSTRAP_ROWS",U),d="__replica_state",l=new WeakSet,_=s=>{l.has(s)||(s.exec(`CREATE TABLE IF NOT EXISTS ${d} (
|
|
2
2
|
id INTEGER PRIMARY KEY CHECK (id = 1),
|
|
3
3
|
epoch TEXT NOT NULL,
|
|
4
4
|
applied_seq INTEGER NOT NULL,
|
package/dist/packem_shared/{ctx-db-relay-shapes-kGRKSxRs.mjs → ctx-db-relay-shapes-OAI2tSoy.mjs}
RENAMED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{sql as i}from"drizzle-orm";import{e as l,d as E}from"./wire-codec-BYCSiazv.mjs";import{runDrizzle as a}from"./runDrizzle-
|
|
1
|
+
import{sql as i}from"drizzle-orm";import{e as l,d as E}from"./wire-codec-BYCSiazv.mjs";import{runDrizzle as a}from"./runDrizzle-B2GG3IJa.mjs";import{relayProxyKey as T}from"./DEFAULT_PROMOTION_THRESHOLDS-DEURXMvk.mjs";const t="__lunora_relay_shapes",o=null,R=e=>{a(e,i`CREATE TABLE IF NOT EXISTS ${i.identifier(t)} (
|
|
2
2
|
key TEXT PRIMARY KEY,
|
|
3
3
|
relay_idx INTEGER,
|
|
4
4
|
connection_id TEXT,
|
package/dist/packem_shared/{ctx-db-search-state-DVCp4JQf.mjs → ctx-db-search-state-CrTLPmFN.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{D as E}from"./MAX_TOKEN_LENGTH-BakL9FUy-B3VwYY8C.mjs";import{sql as e}from"drizzle-orm";import{runDrizzle as t}from"./runDrizzle-
|
|
1
|
+
import{D as E}from"./MAX_TOKEN_LENGTH-BakL9FUy-B3VwYY8C.mjs";import{sql as e}from"drizzle-orm";import{runDrizzle as t}from"./runDrizzle-B2GG3IJa.mjs";const S=i=>`${E(i.language).profile}:${i.field}`,c=i=>{const r=i.slice(i.indexOf(":")+1),o=r.lastIndexOf("/");return o===-1?r:r.slice(0,o)},N=(i,r)=>i.profile!==r?{cursor:void 0,finished:!1,wipe:i.cursor!==void 0||i.done}:{cursor:i.cursor,finished:i.done,wipe:!1},T=(i,r)=>typeof i=="string"&&c(i)===c(r),n="__lunora_search_state",R=i=>{t(i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(n)} (${e.identifier("companion")} TEXT PRIMARY KEY, ${e.identifier("cursor")} TEXT, ${e.identifier("done")} INTEGER NOT NULL DEFAULT 0, ${e.identifier("profile")} TEXT, ${e.identifier("covered")} INTEGER NOT NULL DEFAULT 0)`);try{t(i,e`ALTER TABLE ${e.identifier(n)} ADD COLUMN ${e.identifier("profile")} TEXT`)}catch{}try{t(i,e`ALTER TABLE ${e.identifier(n)} ADD COLUMN ${e.identifier("covered")} INTEGER NOT NULL DEFAULT 0`)}catch{}t(i,e`UPDATE ${e.identifier(n)} SET ${e.identifier("covered")} = 1 WHERE ${e.identifier("done")} = 1 AND ${e.identifier("covered")} = 0`)},s=i=>i===1||i===!0||i==="1",O=(i,r)=>{const o=t(i,e`SELECT ${e.identifier("covered")} FROM ${e.identifier(n)} WHERE ${e.identifier("companion")} = ${r}`).toArray();return s(o[0]?.covered)},l=(i,r,o)=>{const d=t(i,e`SELECT ${e.identifier("cursor")}, ${e.identifier("done")}, ${e.identifier("profile")} FROM ${e.identifier(r)} WHERE ${e.identifier("companion")} = ${o}`).toArray()[0];return d?{cursor:d.cursor??void 0,done:s(d.done),profile:d.profile??void 0}:{cursor:void 0,done:!1,profile:void 0}},u=(i,r)=>l(i,n,r),D=(i,r,o,f,d)=>{const $=o??null,a=T(u(i,r).profile,d)?e`MAX(${e.identifier(n)}.${e.identifier("covered")}, excluded.${e.identifier("covered")})`:e`excluded.${e.identifier("covered")}`;t(i,e`INSERT INTO ${e.identifier(n)} (${e.identifier("companion")}, ${e.identifier("cursor")}, ${e.identifier("done")}, ${e.identifier("profile")}, ${e.identifier("covered")}) VALUES (${r}, ${$}, ${f?1:0}, ${d}, ${f?1:0}) ON CONFLICT (${e.identifier("companion")}) DO UPDATE SET ${e.identifier("cursor")} = excluded.${e.identifier("cursor")}, ${e.identifier("done")} = excluded.${e.identifier("done")}, ${e.identifier("profile")} = excluded.${e.identifier("profile")}, ${e.identifier("covered")} = ${a}`)};export{n as S,O as a,l as b,S as c,N as l,R as m,u as r,D as w};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createShardCtxDb as _}from"./NotUniqueError-
|
|
1
|
+
import{createShardCtxDb as _}from"./NotUniqueError-B69J01E7.mjs";import{createRelayLink as I}from"./DEFAULT_MAX_RELAYS-DSIYUnPB.mjs";import{ConflictError as q}from"./ConflictError-C8GtJmjS.mjs";import{runShardMigrations as E}from"./runShardMigrations-B6FUu4iW.mjs";import{relayName as F}from"./DEFAULT_PROMOTION_THRESHOLDS-DEURXMvk.mjs";const S=(O,m={})=>({_meta:{column:{notNull:!0,...m}},kind:O}),A=(O,m,x)=>{const{describe:v,expect:d,it:b}=x;v(`engine contract: ${O}`,()=>{v("optimistic concurrency",()=>{const w=u=>({tables:{items:{indexes:[],shape:{title:S("string"),version:S("number",{notNull:!1})},triggerMap:{clobber:{handler:()=>{u.exec(`UPDATE "items" SET "__doc__" = json_set("__doc__", '$.version', 99) WHERE "id" = 'i1'`)},op:"update",timing:"before"}}}}});b("raises a CONFLICT of kind `occ` when a write's snapshot is clobbered",async()=>{const{close:u,host:h}=m();try{const c=h.sql,p=w(c);E(c,p);const s=_({schema:p,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0}),await d(s.patch("i1",{title:"second"})).rejects.toBeInstanceOf(q)}finally{u?.()}}),b("reports the conflict as CONFLICT/409 rather than retrying it away",async()=>{const{close:u,host:h}=m();try{const c=h.sql,p=w(c);E(c,p);const s=_({schema:p,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let a;try{await s.patch("i1",{title:"second"})}catch(t){a=t}const e=a;d(e.code).toBe("CONFLICT"),d(e.kind).toBe("occ")}finally{u?.()}}),b("leaves the row readable and unchanged after a conflict",async()=>{const{close:u,host:h}=m();try{const c=h.sql,p=w(c);E(c,p);const s=_({schema:p,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});try{await s.patch("i1",{title:"second"})}catch{}const a=await s.get("i1");d(a?.title).toBe("first"),d(a?.version).toBe(99)}finally{u?.()}}),b("raises a CONFLICT of kind `trigger` when a trigger writes its own row through the db",async()=>{const{close:u,host:h}=m();try{const c=h.sql,p={tables:{items:{indexes:[],shape:{title:S("string"),version:S("number",{notNull:!1})},triggerMap:{recurse:{handler:async(t,o)=>{await t.db.patch(o.doc._id,{version:99})},op:"update",timing:"before"}}}}};E(c,p);const s=_({schema:p,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let a;try{await s.patch("i1",{title:"second"})}catch(t){a=t}const e=a;d(e).toBeInstanceOf(q),d(e.code).toBe("CONFLICT"),d(e.kind).toBe("trigger")}finally{u?.()}})}),v("shape-poke ordering",()=>{const w="shard-a",u={args:{},name:"messages"},h=(e,t,o,n)=>e.accept(t?.()??{},{connectionId:o,shapes:{[n]:u}}),c=(e,t,o)=>{let n=0,l=0;const r=k=>()=>{throw new Error(`the relay poke path must not reach RelayHost.${k}`)},i={fetch:(k,C)=>{if(JSON.parse(C?.body??"{}").type!=="relay_shape_subscribe")return Promise.resolve(new Response(void 0,{status:204}));const N=o[l];if(l+=1,N===void 0)throw new Error("the relay asked for more seeds than this fixture supplies");return Promise.resolve(Response.json(N))}},f={get:()=>i,getByName:()=>i,idFromName:k=>k},g={buildShapeDiff:r("buildShapeDiff"),computeOpLogShapeSeed:r("computeOpLogShapeSeed"),currentCdcEpoch:r("currentCdcEpoch"),deliverWhisperLocal:r("deliverWhisperLocal"),doName:()=>F(w,0),env:()=>({SHARD:f}),getWebSockets:()=>e.getSockets(),maskMetadata:r("maskMetadata"),nextPokeId:()=>(n+=1,`poke-${String(n)}`),readAttachment:k=>k.deserializeAttachment?.(),recordShapePokeFanout:()=>{},resolveShape:r("resolveShape"),rlsMetadata:r("rlsMetadata"),shardBinding:()=>"SHARD",shardJurisdiction:()=>{},sql:()=>t},y=I(g);if(y===void 0)throw new Error("expected a relay link for a `…::relay::N` name");return y},p=e=>new Request("https://relay.internal/_lunora/relay",{body:JSON.stringify(e),headers:{"content-type":"application/json"},method:"POST"}),s=async(e,t,o)=>{const n=await e.seedRelayShape(t,o,u,{identity:void 0,userId:void 0});if(n!=="ok")throw new Error(`seed failed: ${JSON.stringify(n)}`)},a=(e={})=>p({...u,checkpoint:20,epoch:"e1",fromCursor:10,rowsPatch:[{id:"r1",op:"upsert",value:{title:"hello"}}],type:"relay_shape_poke",...e});b("frames a poke as pokeStart → pokePart per shape → pokeEnd, under one poke id",async()=>{const{close:e,createSocket:t,host:o,readFrames:n,sockets:l}=m();try{const r=c(l,o.sql,[{cursor:10,epoch:"e1",frames:[]}]),i=h(l,t,"c-alice","s1");await s(r,i,"s1"),await r.handleControl(a());const g=(await n(i)).map(y=>JSON.parse(y));d(g.map(y=>y.type)).toStrictEqual(["pokeStart","pokePart","pokeEnd"]),d(new Set(g.map(y=>y.pokeId)).size).toBe(1),d(g[1]?.shapeId).toBe("s1"),d(g[2]?.checkpoint).toBe(20)}finally{e?.()}}),b("delivers a poke only to sockets whose cursor matches, and advances them past it",async()=>{const{close:e,createSocket:t,host:o,readFrames:n,sockets:l}=m();try{const r=c(l,o.sql,[{cursor:10,epoch:"e1",frames:[]},{cursor:7,epoch:"e1",frames:[]}]),i=h(l,t,"c-alice","s1"),f=h(l,t,"c-bob","s2");await s(r,i,"s1"),await s(r,f,"s2"),await r.handleControl(a());const g=await n(i);d(g.length).toBe(3);const y=await n(f);d(y.length).toBe(0),await r.handleControl(a());const k=await n(i);d(k.length).toBe(3)}finally{e?.()}}),b("skips a socket whose cursor matches under a different CDC epoch",async()=>{const{close:e,createSocket:t,host:o,readFrames:n,sockets:l}=m();try{const r=c(l,o.sql,[{cursor:10,epoch:"e1",frames:[]}]),i=h(l,t,"c-alice","s1");await s(r,i,"s1"),await r.handleControl(a({epoch:"e2"}));const f=await n(i);d(f.length).toBe(0),await r.handleControl(a());const g=await n(i);d(g.length).toBe(3)}finally{e?.()}})}),v("orderBy null placement",()=>{const w=[["a",void 0],["b",3],["c",void 0],["d",1],["e",void 0],["f",3],["g",2],["h",void 0]],u=[{nulls:"first",sort:"asc"},{nulls:"last",sort:"asc"},{nulls:"first",sort:"desc"},{nulls:"last",sort:"desc"}],h=({nulls:p,sort:s})=>{const a=new Map(w.map(([t],o)=>[t,o])),e=s==="asc"?1:-1;return w.toSorted(([t,o],[n,l])=>o!==l?o===void 0?p==="first"?-1:1:l===void 0?p==="first"?1:-1:(o-l)*e:((a.get(t)??0)-(a.get(n)??0))*e).map(([t])=>t)},c=p=>p.map(s=>String(s.label));b("pages every placement in threes with no row skipped or repeated",async()=>{const{close:p,host:s}=m();try{const a=s.sql,e=u.map((r,i)=>`items_${String(i)}`),t={label:S("string"),score:S("number",{notNull:!1})},o={tables:Object.fromEntries(e.map(r=>[r,{indexes:[{fields:["score"],name:"by_score"}],shape:t}]))};E(a,o);let n=17e11;const l=_({clock:()=>(n+=1e3,n),schema:o,sql:a});for(const r of e)for(const[i,f]of w)await l.insert(r,f===void 0?{label:i}:{label:i,score:f});for(const[r,i]of u.entries()){const f=e[r]??"",g=await l.findMany(f,{orderBy:[{score:i}]});d(c(g.page)).toStrictEqual(h(i));const y=[];let k;for(let C=0;C<w.length+2;C+=1){const B=await l.findMany(f,{cursor:k,limit:3,orderBy:[{score:i}]});if(y.push(...c(B.page)),B.isDone)break;k=B.continueCursor}d(y).toStrictEqual(h(i))}}finally{p?.()}})}),v("RLS identity under live subscription",()=>{const w="shard-a",u={args:{},name:"lobby-messages"},h={args:{},name:"my-orders"},c=s=>{const a=[],e=[],t={fetch:(l,r)=>(a.push(JSON.parse(r?.body??"{}")),Promise.resolve(new Response(void 0,{status:204})))},n=I({buildShapeDiff:()=>[{id:"r1",op:"upsert",value:{}}],computeOpLogShapeSeed:()=>({baseCheckpoint:void 0,cursor:10,epoch:"e1",reset:!0,rowsPatch:[]}),currentCdcEpoch:()=>"e1",deliverWhisperLocal:()=>0,doName:()=>w,env:()=>({SHARD:{get:()=>t,getByName:()=>t,idFromName:l=>l}}),getWebSockets:()=>[],maskMetadata:()=>({columns:[]}),nextPokeId:()=>"poke-1",readAttachment:()=>({}),recordShapePokeFanout:()=>{},resolveShape:(l,r,i)=>(e.push(i),l===h.name?{columns:["id"],effectiveWhere:{org:i?.identity?.org??"anonymous"},global:!1,table:"orders"}:{columns:["id"],effectiveWhere:{room:"lobby"},global:!1,table:"messages"}),rlsMetadata:()=>({policies:[]}),shardBinding:()=>"SHARD",shardJurisdiction:()=>{},sql:()=>s});if(n===void 0)throw new Error("expected an owner link for an un-suffixed DO name");return{owner:n,posts:a,resolvedUnder:e}},p=async(s,a)=>{await s.handleControl(new Request("https://owner.internal/_lunora/relay",{body:JSON.stringify({...a,connectionId:"c-alice",identity:{org:"acme"},relayIndex:0,subId:"s1",type:"relay_shape_subscribe",userId:"u1"}),headers:{"content-type":"application/json"},method:"POST"}))};b("seeds a subscriber under its own forwarded identity, never the anonymous one",async()=>{const{close:s,host:a}=m();try{const{owner:e,resolvedUnder:t}=c(a.sql);await p(e,h),d(t.some(o=>o?.userId==="u1"&&o.identity?.org==="acme")).toBe(!0)}finally{s?.()}}),b("routes an identity-scoped shape to a per-socket poke, not the cohort multicast",async()=>{const{close:s,host:a}=m();try{const{owner:e,posts:t}=c(a.sql);await p(e,h),t.length=0,await e.onFlush(new Set(["orders"]),20);const o=t.filter(n=>n.type==="relay_shape_poke");d(o.length).toBe(1),d(o[0]?.targetConnectionId).toBe("c-alice")}finally{s?.()}}),b("still multicasts an identity-blind shape to the whole cohort",async()=>{const{close:s,host:a}=m();try{const{owner:e,posts:t}=c(a.sql);await p(e,u),t.length=0,await e.onFlush(new Set(["messages"]),20);const o=t.filter(n=>n.type==="relay_shape_poke");d(o.length).toBe(1),d(o[0]?.targetConnectionId).toBeUndefined()}finally{s?.()}})})})};export{A as defineEngineContractSuite};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as c}from"@lunora/errors";import{sql as o}from"drizzle-orm";import{e as T}from"./effective-kind-BmG_zCAy.mjs";import{S as h,i as A,s as $,F as O}from"./json-field-path-B2fjnGc3.mjs";import{quoteIdentifier as g}from"./quoteIdentifier-CObIFRhb.mjs";import{d as y,n as N,e as b}from"./wire-codec-BYCSiazv.mjs";import{runDrizzle as f}from"./runDrizzle-
|
|
1
|
+
import{LunoraError as c}from"@lunora/errors";import{sql as o}from"drizzle-orm";import{e as T}from"./effective-kind-BmG_zCAy.mjs";import{S as h,i as A,s as $,F as O}from"./json-field-path-B2fjnGc3.mjs";import{quoteIdentifier as g}from"./quoteIdentifier-CObIFRhb.mjs";import{d as y,n as N,e as b}from"./wire-codec-BYCSiazv.mjs";import{runDrizzle as f}from"./runDrizzle-B2GG3IJa.mjs";import{serializeSqlValue as I}from"./serializeSqlValue-BbZ5hKM7.mjs";import{sqlComparableProjection as j}from"./BIGINT_KEY_DIGITS-C9a7Ix7k.mjs";const L=/^[A-Za-z_$][\w$]*$/u,d=e=>L.test(e)?e:`"${e.replaceAll("\\",String.raw`\\`).replaceAll('"',String.raw`\"`)}"`,l="__doc__",i="__originals__",X=e=>{if(Object.hasOwn(e,i))throw new c("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 _=j(a);_!==void 0&&(t??={...e},r??=Object.create(null),t[s]=_,r[s]=a)}t&&r&&(t[i]=r);const n=t??e;try{return N(n)?JSON.stringify(b(n)):JSON.stringify(n)}catch(s){throw new c("BAD_REQUEST",`this document cannot be stored: ${s instanceof Error?s.message:String(s)}`)}},w=e=>{const t=y(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}},Y=(e,t)=>`${e}__geo_${t}`,D=e=>{try{return $(e)}catch(t){throw t instanceof O?new c("VALIDATION_ERROR",t.message):t}},S=e=>`'$.${(A(e)?D(e).map(r=>d(r)).join("."):d(e)).replaceAll("'","''")}'`,E=(e,t)=>t==="_id"||t==="id"?`${e}id`:t==="_creationTime"?`${e}_creationTime`:`json_extract(${e}${l}, ${S(t)})`,P=e=>E("",e),C=(e,t)=>`NULLIF(json_type(${l}, ${S(e)}), 'null') IN (${h[t]})`,R=e=>o.raw(P(e)),U=(e,t)=>o.raw(C(e,t)),G=(e,t)=>E(`${g(e)}.`,t),x=(e,t)=>o.raw(G(e,t)),H=(e,t,r,n)=>o`CREATE ${n?o`UNIQUE `:o``}INDEX IF NOT EXISTS ${o.identifier(e)} ON ${o.identifier(t)} (${r})`,u=o.identifier("__key__"),q=o.identifier("__value__"),v=o.identifier("__count__"),Z=(e,t,r,n,s)=>o`INSERT INTO ${o.identifier(e)} (${u}, ${q}, ${v}) VALUES (${t}, ${r}, ${n}) ON CONFLICT(${u}) DO UPDATE SET ${s}`,ee=(e,t)=>e===void 0||t!==0&&t!==1||T(e)!=="boolean"?t:t===1,m=new WeakMap,te=e=>{const t=m.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),m.set(e,r),r},F=e=>{if(!e)return;const t=e[l];let r;typeof t=="string"?r=w(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},re=e=>{try{return F(e)}catch{return}},p=new WeakMap,oe=e=>{const t=p.get(e);if(t!==void 0)return t;let r;try{f(e,o`CREATE VIRTUAL TABLE IF NOT EXISTS ${o.identifier("__lunora_fts_probe")} USING fts5(x)`),r=!0}catch{r=!1}finally{try{f(e,o`DROP TABLE IF EXISTS ${o.identifier("__lunora_fts_probe")}`)}catch{}}return p.set(e,r),r},ne={fieldRef:R,rangeTypeGuard:U,serialize:I};export{v as A,l as D,u as a,q as b,Z as c,H as d,R as e,x as f,Y as g,re as h,oe as i,P as j,X as k,w as l,ne as m,i as n,d as o,C as p,G as q,F as r,ee as s,te as t,U as u};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{toErrorBody as b}from"@lunora/errors";import{COMMIT_SEQ_FIELD as l}from"./COMMIT_SEQ_FIELD-
|
|
1
|
+
import{toErrorBody as b}from"@lunora/errors";import{COMMIT_SEQ_FIELD as l}from"./COMMIT_SEQ_FIELD-BcUO15fR.mjs";const f=200,u=(o,n)=>{const i=r=>{const e=o.tables[r];return e!==void 0&&e.shardMode?.kind!=="global"};return(n&&n.length>0?[...n]:Object.keys(o.tables)).filter(r=>i(r))},p=async function*(o,n,i=f){let r=null,e=!1;for(;!e;){const t=await o.findMany(n,{cursor:r,includeDeleted:!0,limit:i});for(const s of t.page)yield{doc:s,table:n};r=t.continueCursor,e=t.isDone||r===null}},O=async function*(o,n,i){const r=u(n,i.tables),e=i.batchSize??f;for(const t of r)yield*p(o,t,e)},y=new Set(["_creationTime","_id"]),h=(o,n)=>{for(const[i,r]of Object.entries(o.shape)){const e=n[i];if(e===void 0&&r.kind==="optional")continue;const t=r.parse;if(typeof t=="function")try{t(e)}catch(s){const c=s instanceof Error?s.message:String(s);return`field "${i}": ${c}`}}},m=(o,n,i)=>{const r=o.tables[n];if(!r)return`unknown table: ${n}`;if(r.shardMode?.kind==="global")return`table "${n}" is a global (.global()) table and is not importable through the shard import path`;const e=Object.fromEntries(Object.entries(i).filter(([t])=>!y.has(t)));for(const t of Object.keys(e))if(!Object.hasOwn(r.shape,t))return`unexpected field "${t}": not declared in table "${n}"`;return h(r,e)},g=async(o,n,i)=>{try{if(o.lookupById){const r=await o.lookupById(i);return r===null?void 0:r.tableName}return await o.get(i,n)===null?void 0:n}catch{return}},w=o=>l in o?Object.fromEntries(Object.entries(o).filter(([n])=>n!==l)):o,S=async(o,n,i,r)=>{const{table:e}=i;let{doc:t}=i;if(typeof e!="string"||e.length===0)return{error:{code:"BAD_ROW",line:r,message:"row is missing `table`",table:e},kind:"error"};if(!t||typeof t!="object"||Array.isArray(t))return{error:{code:"BAD_ROW",line:r,message:"row is missing or malformed `doc`",table:e},kind:"error"};t=w(t);const s=m(n,e,t);if(s!==void 0)return{error:{code:"VALIDATION_ERROR",line:r,message:s,table:e},kind:"error"};const c=typeof t._id=="string"?t._id:void 0;if(c!==void 0){const a=await g(o,e,c);if(a===e)return{kind:"conflict"};if(a!==void 0)return{error:{code:"ID_COLLISION",line:r,message:`_id "${c}" already belongs to table "${a}"`,table:e},kind:"error"}}try{return await o.insert(e,t,{allowExplicitId:!0}),{kind:"inserted",table:e}}catch(a){const{body:d}=b(a,{fallbackCode:"INSERT_FAILED"});return{error:{code:d.code,line:r,message:d.message,table:e},kind:"error"}}},v=async(o,n,i)=>{const r=[],e={};let t=0,s=(i.startLine??1)-1;for(const c of i.rows){s+=1;const a=await S(o,n,c,s);a.kind==="error"?r.push(a.error):a.kind==="conflict"?t+=1:e[a.table]=(e[a.table]??0)+1}return{conflicts:t,errors:r,inserted:e}},E=o=>{const n=Array.isArray(o.tables)?o.tables.filter(r=>typeof r=="string"):void 0;return{batchSize:typeof o.batchSize=="number"?o.batchSize:void 0,tables:n}},I=o=>{const n=Array.isArray(o.rows)?o.rows:[],i=[];for(const e of n){if(!e||typeof e!="object")continue;const t=e;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 r=typeof o.startLine=="number"?o.startLine:void 0;return{rows:i,startLine:r}};export{O as exportShardRows,v as importShardRows,E as parseExportShardArgs,I as parseImportShardArgs,u as selectExportTables,m as validateImportRow};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{D as I}from"./MAX_TOKEN_LENGTH-BakL9FUy-B3VwYY8C.mjs";import{sql as e}from"drizzle-orm";import{sqliteInList as L}from"./WORKERD_SQLITE_LIMITS-
|
|
1
|
+
import{D as I}from"./MAX_TOKEN_LENGTH-BakL9FUy-B3VwYY8C.mjs";import{sql as e}from"drizzle-orm";import{sqliteInList as L}from"./WORKERD_SQLITE_LIMITS-BdNnnMj0.mjs";const u=(i,t)=>{if(!t.includes("."))return i[t];let r=i;for(const $ of t.split(".")){if(r===null||typeof r!="object"||Array.isArray(r))return;r=r[$]}return r},D=(i,t)=>`${i}__fts_${t}`,o="__text__",s="__id__",A=1e3,O=(i,t)=>t.document(i),N=(i,t)=>u(i,t),_=i=>typeof i=="string"?i:i==null?"":typeof i=="number"||typeof i=="bigint"||typeof i=="boolean"?String(i):JSON.stringify(i)??"",w=(i,t,r)=>i!==void 0&&t!==void 0&&N(i,r.field)===N(t,r.field),c=(i,t)=>O(_(N(i,t.field)),I(t.language)).slice(0,A),M=(i,t)=>c(i,t).join(" "),a=50,n="__rowid__",T=i=>`${i}__ids`,E=(i,t)=>e`${e.identifier(i)}.${e.identifier(t)}`,S=(i,t,{guard:r,unmappedRowids:$})=>{const d=T(i),f=r===void 0?e``:e` AND ${r}`,R=$===void 0?e`${E(i,"rowid")} > 0`:L(E(i,"rowid"),$,!1,a);return[e`DELETE FROM ${e.identifier(i)} WHERE ${R} AND CAST(${E(i,s)} AS TEXT) = ${t}${f}`,e`DELETE FROM ${e.identifier(i)} WHERE ${E(i,"rowid")} = (SELECT ${E(d,n)} FROM ${e.identifier(d)} WHERE ${E(d,s)} = ${t}) AND ${E(i,s)} = ${t}${f}`]},U=i=>[e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(i)} USING fts5(${e.identifier(o)}, ${e.identifier(s)} UNINDEXED)`,e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(`${i}__vocab`)} USING fts5vocab(${e.identifier(i)}, ${e.raw("instance")})`,e`CREATE TABLE IF NOT EXISTS ${e.identifier(T(i))} (${e.identifier(n)} INTEGER PRIMARY KEY, ${e.identifier(s)} TEXT NOT NULL UNIQUE)`,e`INSERT INTO ${e.identifier(i)} (rowid, ${e.identifier(o)}, ${e.identifier(s)}) SELECT 0, '', '' WHERE NOT EXISTS (SELECT 1 FROM ${e.identifier(i)} WHERE ${E(i,"rowid")} = 0)`],F=(i,t,r,$={})=>{const d=T(i),f=$.guard===void 0?e``:e` AND ${$.guard}`,R=e`MIN(COALESCE((SELECT MIN(${E(d,n)}) FROM ${e.identifier(d)}), 0), 0) - 1`;return[...S(i,t,$),e`INSERT OR REPLACE INTO ${e.identifier(d)} (${e.identifier(n)}, ${e.identifier(s)}) SELECT ${R}, ${t} WHERE 1 = 1${f}`,e`INSERT OR REPLACE INTO ${e.identifier(i)} (rowid, ${e.identifier(o)}, ${e.identifier(s)}) SELECT ${E(d,n)}, ${r}, ${E(d,s)} FROM ${e.identifier(d)} WHERE ${E(d,s)} = ${t}${f}`]},y=(i,t,r={})=>{const $=T(i),d=r.guard===void 0?e``:e` AND ${r.guard}`;return[...S(i,t,r),e`DELETE FROM ${e.identifier($)} WHERE ${E($,s)} = ${t}${d}`]},W=(i,t,r=0)=>e`SELECT ${E(i,"rowid")} AS ${e.identifier("rowid")}, ${E(i,s)} AS ${e.identifier("id")} FROM ${e.identifier(i)} WHERE ${E(i,"rowid")} > ${e.param(Math.max(0,r))} AND ${E(i,s)} IS NOT NULL ORDER BY ${E(i,"rowid")} ASC LIMIT ${e.raw(String(t))}`,b=i=>{const t=new Map;for(const r of i){const $=String(r.id);t.set($,[...t.get($)??[],Number(r.rowid)])}return t};export{w as N,D as S,y as a,T as b,W as c,F as d,M as e,U as f,b as g,c as h,s as l};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{f as t,a as e,b as p,c as m,d as f,g as n}from"./fts-companion-
|
|
1
|
+
import{f as t,a as e,b as p,c as m,d as f,g as n}from"./fts-companion-DzfEHonU.mjs";import"./WORKERD_SQLITE_LIMITS-BdNnnMj0.mjs";export{t as ftsCompanionDdl,e as ftsPurgeDocument,p as ftsRowidMapName,m as ftsUnmappedPage,f as ftsWriteDocument,n as groupUnmappedRows};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{LunoraError as T}from"@lunora/errors";import{sql as m}from"drizzle-orm";import{runDrizzle as S}from"./runDrizzle-
|
|
1
|
+
import{LunoraError as T}from"@lunora/errors";import{sql as m}from"drizzle-orm";import{runDrizzle as S}from"./runDrizzle-B2GG3IJa.mjs";import{liftSourceId as A}from"./liftSourceId-CA3ENhXj.mjs";import{normalizeSourceValue as W}from"./liftSourceId-CA3ENhXj.mjs";import{runExternalSourceTick as C,materializeExternalRowsIncremental as D}from"./materializeExternalRows-UxGuXjjF.mjs";const p="__lunora_source_cursor",M=e=>e instanceof Date?`d:${e.toISOString()}`:typeof e=="bigint"?`b:${e.toString()}`:typeof e=="number"?`n:${e.toString()}`:`s:${e}`,v=e=>{const t=e.slice(2);switch(e[0]){case"b":return BigInt(t);case"d":return new Date(t);case"n":return Number(t);default:return t}},h=/^-?\d+$/,N=/^-?\d+(?:\.\d+)?$/,x=(e,t)=>e instanceof Date&&t instanceof Date?e.getTime()>t.getTime():typeof e=="bigint"&&typeof t=="bigint"||typeof e=="number"&&typeof t=="number"?e>t:typeof e=="string"&&typeof t=="string"&&N.test(e)&&N.test(t)?h.test(e)&&h.test(t)?BigInt(e)>BigInt(t):Number(e)>Number(t):String(e)>String(t),O=(e,t,o)=>{let n=o===null?void 0:v(o);for(const r of e){const c=r[t];if(c==null)continue;const a=c;(n===void 0||x(a,n))&&(n=a)}return n===void 0?null:M(n)},B=e=>{S(e,m`CREATE TABLE IF NOT EXISTS ${m.identifier(p)} (
|
|
2
2
|
table_name TEXT NOT NULL,
|
|
3
3
|
shard_key TEXT NOT NULL,
|
|
4
4
|
watermark TEXT,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{applyCdcChanges as p}from"./CDC_LOG_TABLE-
|
|
1
|
+
import{applyCdcChanges as p}from"./CDC_LOG_TABLE-CvInVdXu.mjs";import{selectShapeRows as m}from"./selectShapeMembers-DS28-P_Z.mjs";import{diffExternalSource as g,projectExternalSourceRow as l}from"./diffExternalSource-DgDJhslq.mjs";import{stableStringify as d}from"./stableStringify-DibjylKD.mjs";const x=async(t,s,a,e)=>{const{changes:o,nextBaseline:n}=g(s,a,e);return await p(t,o),{applied:o.length,nextBaseline:n}},R=async(t,s,a)=>{const{columns:e,deletedIds:o,table:n}=a,r=[];for(const f of s){const i=l(f,e),c=String(i._id);if(o?.has(c)){await t.get(c,n)&&r.push({id:c,op:"delete",seq:0,table:n,ts:0});continue}const u=await t.get(c,n);u&&d(l({...u,_id:c},e))===d(i)||r.push({doc:i,id:c,op:"insert",seq:0,table:n,ts:0})}return await p(t,r),{applied:r.length}},h=(t,s,a)=>{const e=new Map;for(const{doc:o,id:n}of m(t,s,void 0))e.set(n,d(l({...o,_id:n},a)));return e},_=async(t,s,a,e)=>{const o=h(t,e.table,e.columns);return x(s,a,o,e)};export{x as materializeExternalRows,R as materializeExternalRowsIncremental,h as readExternalSourceBaseline,_ as runExternalSourceTick};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as i}from"@lunora/errors";import{renderSql as l,WORKERD_SQLITE_LIMITS as e}from"./WORKERD_SQLITE_LIMITS-
|
|
1
|
+
import{LunoraError as i}from"@lunora/errors";import{renderSql as l,WORKERD_SQLITE_LIMITS as e}from"./WORKERD_SQLITE_LIMITS-BdNnnMj0.mjs";const c=(t,n,...r)=>{if(n.length*3>e.sqlTextLength){const s=new TextEncoder().encode(n).length;if(s>e.sqlTextLength)throw new i("INTERNAL",`SQL statement is ${String(s)} bytes, over this runtime's ${String(e.sqlTextLength)}-byte limit`)}if(r.length>e.boundParams)throw new i("INTERNAL",`SQL statement binds ${String(r.length)} parameters, over this runtime's limit of ${String(e.boundParams)}`);return t.exec.call(t,n,...r)},u=(t,n)=>{const{params:r,sql:o}=l("sqlite",n);return c(t,o,...r)},d=(t,n)=>{for(const r of n)u(t,r)},g=t=>t??null,S=t=>{if(!(t==null||t===""))try{return JSON.parse(t)}catch{return}};export{S as decodeJsonColumn,g as orNull,d as runAll,u as runDrizzle,c as runSql};
|
package/dist/packem_shared/{runShardMigrations-eqHNBW6S.mjs → runShardMigrations-B6FUu4iW.mjs}
RENAMED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{LunoraError as h}from"@lunora/errors";import{f as x,S as O}from"./fts-companion-
|
|
1
|
+
import{LunoraError as h}from"@lunora/errors";import{f as x,S as O}from"./fts-companion-DzfEHonU.mjs";import{sql as r}from"drizzle-orm";import{aggregateTableName as A}from"./aggregateTableName-DbAttCNH.mjs";import{backfillSearchIndexesForTable as R}from"./backfillAggregateIndexes-DBrKU3Ya.mjs";import{migrateCdcLog as C,migrateCdcMeta as N}from"./CDC_LOG_TABLE-CvInVdXu.mjs";import{migrateClientWatermark as b}from"./CLIENT_WATERMARK_TABLE-_CkdMnT2.mjs";import{migrateCommitSeq as D}from"./COMMIT_SEQ_FIELD-BcUO15fR.mjs";import{migrateCompanionState as $}from"./clearCompanionSignatures-Qf67j6dd.mjs";import{migrateGlobalShapeSnapshot as U}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-Du0PbPdS.mjs";import{migrateIdempotency as M}from"./IDEMPOTENCY_TABLE-CymJf4r0.mjs";import{m as G}from"./ctx-db-relay-shapes-OAI2tSoy.mjs";import{migrateScheduleOutbox as X}from"./SCHEDULE_OUTBOX_TABLE-C_Me442c.mjs";import{m as y}from"./ctx-db-search-state-CrTLPmFN.mjs";import{migrateShapePokeCursor as F}from"./SHAPE_POKE_CURSOR_TABLE-B6MXBH-p.mjs";import{runDrizzle as m,runAll as k}from"./runDrizzle-B2GG3IJa.mjs";import{D as P,d as E,e as u,t as Y,i as B,g as j,a as v,b as w,A as p}from"./do-sql-CeuVvE0W.mjs";import{renderSql as H}from"./WORKERD_SQLITE_LIMITS-BdNnnMj0.mjs";import{migrateDurableStreams as K}from"./appendStreamChunk-DF_Jrgpy.mjs";import{rankTableName as S,sortColumnName as W}from"./RANK_TIEBREAK-BKugKf70.mjs";import{migrateReactorState as V}from"./REACTOR_STATE_TABLE-DHaBP_vb.mjs";import{recordSchemaVersion as z}from"./SCHEMA_HISTORY_MAX_VERSIONS-SQVxBlum.mjs";const l=r`_creationTime, id`,L=(e,n,o,i,t,a)=>{const s=r.join(t.map(d=>r`${d} IS NOT NULL`),r` AND `);if(m(e,r`SELECT 1 FROM ${r.identifier(o)} WHERE ${s} GROUP BY ${i} HAVING COUNT(*) > 1 LIMIT 1`).toArray().length>0)throw new h("INTERNAL",`unique index "${n}" on "${o}" ${a}: existing rows are duplicates under it. De-duplicate the table with a data migration first; the previous index is left in place.`)},J=(e,n,o,i,t,a)=>{const c=m(e,r`SELECT sql FROM sqlite_master WHERE type = 'index' AND name = ${n} AND tbl_name = ${o}`).toArray()[0]?.sql;if(c==null)return;const d=_=>{const g=_.indexOf("(");return g===-1?void 0:_.slice(g,_.lastIndexOf(")")+1)},T=d(H("sqlite",E(n,o,i,t)).sql),f=d(c);T===void 0||f===void 0||T===f||(t&&L(e,n,o,i,a,"cannot be re-created with its new column list"),m(e,r`DROP INDEX IF EXISTS ${r.identifier(n)}`))},Q=(e,n,o)=>m(e,r`SELECT 1 FROM sqlite_master WHERE type = 'index' AND name = ${n} AND tbl_name = ${o} LIMIT 1`).toArray().length>0,I=(e,n,o,i,t,a)=>{t&&!Q(e,n,o)&&L(e,n,o,i,a,"cannot be created"),m(e,E(n,o,i,t))},Z=(e,n,o)=>{for(const i of o.indexes){const t=`${n}_${i.name}`,a=i.unique??!1,s=i.fields.map(T=>u(T)),c=r.join(s,r`, `),d=a?c:r`${c}, ${l}`;J(e,t,n,d,a,s),I(e,t,n,d,a,s)}for(const[i,t]of Y(o)){if(!t.unique)continue;const a=u(i);I(e,`${n}_unique_${i}`,n,a,!0,[a])}},q=(e,n,o)=>{if(!(!o.searchIndexes||o.searchIndexes.length===0||!B(e))){for(const i of o.searchIndexes)k(e,x(O(n,i.name)));R(e,n,o)}},ee=(e,n,o)=>{if(o.geoIndexes)for(const i of o.geoIndexes){const t=j(n,i.name);m(e,r`CREATE TABLE IF NOT EXISTS ${r.identifier(t)} (${r.identifier("__id__")} TEXT PRIMARY KEY, ${r.identifier("__geohash__")} TEXT NOT NULL, ${r.identifier("__lat__")} REAL NOT NULL, ${r.identifier("__lng__")} REAL NOT NULL)`);const a=`${n}__geo_${i.name}__btree`;m(e,E(a,t,r`${r.identifier("__geohash__")} ASC, ${r.identifier("__id__")} ASC`,!1))}},re=(e,n,o)=>{if(o.aggregateIndexes)for(const i of o.aggregateIndexes){const t=A(n,i.name);m(e,r`CREATE TABLE IF NOT EXISTS ${r.identifier(t)} (${v} TEXT PRIMARY KEY, ${w} REAL, ${p} INTEGER NOT NULL DEFAULT 0)`),m(e,r`PRAGMA table_info(${r.identifier(t)})`).toArray().some(s=>s.name==="__count__")||m(e,r`ALTER TABLE ${r.identifier(t)} ADD COLUMN ${p} INTEGER NOT NULL DEFAULT 0`)}},te=(e,n,o)=>{if(o.rankIndexes)for(const i of o.rankIndexes){const t=S(n,i.name),a=i.sortBy.map((f,_)=>W(_)),s=a.map(f=>r`${r.identifier(f)} BLOB`),c=s.length>0?r`, ${r.join(s,r`, `)}`:r``;m(e,r`CREATE TABLE IF NOT EXISTS ${r.identifier(t)} (${r.identifier("__id__")} TEXT PRIMARY KEY, ${r.identifier("__partition__")} TEXT NOT NULL${c})`);const d=[r`${r.identifier("__partition__")} ASC`];for(const[f,_]of a.entries()){const g=i.sortBy[f]?.direction;d.push(r`${r.identifier(_)} ${r.raw(g==="desc"?"DESC":"ASC")}`)}d.push(r`${r.identifier("__id__")} ASC`);const T=`${n}__rank_${i.name}__btree`;m(e,E(T,t,r.join(d,r`, `),!1))}},Oe=(e,n,o={})=>{o.schemaSnapshot!==void 0&&z(e,o.schemaSnapshot.hash,o.schemaSnapshot.json),y(e);const i=[];for(const[t,a]of Object.entries(n.tables))a.shardMode?.kind!=="global"&&(m(e,r`CREATE TABLE IF NOT EXISTS ${r.identifier(t)} (
|
|
2
2
|
id TEXT PRIMARY KEY,
|
|
3
3
|
_creationTime REAL NOT NULL,
|
|
4
4
|
${r.identifier(P)} TEXT NOT NULL
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{sql as o}from"drizzle-orm";import{runDrizzle as h}from"./runDrizzle-
|
|
1
|
+
import{sql as o}from"drizzle-orm";import{runDrizzle as h}from"./runDrizzle-B2GG3IJa.mjs";import{e}from"./do-sql-CeuVvE0W.mjs";const E=(s,t,f,r)=>{const d=f-(t.after??0),i=[o`${e(t.field)} IS NOT NULL`,o`${e(t.field)} < ${d}`];t.softDeleteField!==void 0&&i.push(o`${e(t.softDeleteField)} IS NULL`);const l=o`SELECT id FROM ${o.identifier(t.table)} WHERE ${o.join(i,o` AND `)} LIMIT ${o.raw(String(Math.max(0,Math.floor(r))+1))}`,n=h(s,l).toArray(),a=n.length>r,$=n.slice(0,r).map(c=>c.id);return{hasMore:a,ids:$}};export{E as selectExpiredIds};
|
package/dist/packem_shared/{selectShapeMembers-CU8Kl2Bq.mjs → selectShapeMembers-DS28-P_Z.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{sql as e}from"drizzle-orm";import{runDrizzle as l}from"./runDrizzle-
|
|
1
|
+
import{sql as e}from"drizzle-orm";import{runDrizzle as l}from"./runDrizzle-B2GG3IJa.mjs";import{D as p,r as a,m as h}from"./do-sql-CeuVvE0W.mjs";import{sqliteInList as w}from"./WORKERD_SQLITE_LIMITS-BdNnnMj0.mjs";import{c as $}from"./where-sql-CxnXsLbt.mjs";const C=o=>{if(o.length!==0)return w(e`${e.identifier("id")}`,o,!1)},u=(o,i)=>{const r=[];i&&r.push(i);const t=$(o,h);return t&&r.push(t),r.length===0?e``:e` WHERE ${e.join(r,e` AND `)}`},M=(o,i,r)=>{const t=u(r,void 0),n=l(o,e`SELECT id, _creationTime, ${e.identifier(p)} FROM ${e.identifier(i)}${t}`).toArray(),f=[];for(const m of n){const s=a(m),{id:c}=m;s!==void 0&&typeof c=="string"&&f.push({doc:s,id:c})}return f},T=(o,i,r,t)=>{const n=new Map;if(t.length===0)return n;const f=u(r,C(t)),m=l(o,e`SELECT id, _creationTime, ${e.identifier(p)} FROM ${e.identifier(i)}${f}`).toArray();for(const s of m){const c=a(s),{id:d}=s;c!==void 0&&typeof d=="string"&&n.set(d,c)}return n};export{T as selectShapeMembers,M as selectShapeRows};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as S}from"@lunora/errors";import{sql as c}from"drizzle-orm";import{i as T,a as y}from"./json-field-path-B2fjnGc3.mjs";import{sqliteInList as x,isJsonSafe as O,bytesAsHexJson as C,WORKERD_SQLITE_LIMITS as L}from"./WORKERD_SQLITE_LIMITS-
|
|
1
|
+
import{LunoraError as S}from"@lunora/errors";import{sql as c}from"drizzle-orm";import{i as T,a as y}from"./json-field-path-B2fjnGc3.mjs";import{sqliteInList as x,isJsonSafe as O,bytesAsHexJson as C,WORKERD_SQLITE_LIMITS as L}from"./WORKERD_SQLITE_LIMITS-BdNnnMj0.mjs";import{quoteIdentifier as w}from"./quoteIdentifier-CObIFRhb.mjs";import{RELATION_EXISTS_KEY as b,SEEK_RANGE as j}from"./RELATION_EXISTS_KEY-wxgj6rSL.mjs";const U={binary:(t,n,s)=>c`${t} ${c.raw(n)} ${s}`,constant:t=>t?c`1 = 1`:c`0 = 1`,connect:(t,n,s)=>c`(${t}) ${c.raw(s)} (${n})`,contains:(t,n)=>c`instr(lower(${t}), lower(${n})) > 0`,inList:(t,n,s,o)=>x(t,n,s,o),negate:t=>c`NOT (${t})`,nullCheck:(t,n)=>n?c`${t} IS NOT NULL`:c`${t} IS NULL`,value:t=>c`${t}`},h=(...t)=>{let n="";const s=[];for(const o of t)typeof o=="string"?n+=o:(n+=o.text,s.push(...o.params));return{params:s,text:n}},E=t=>({params:[t],text:"?"}),A=t=>({params:[],text:t}),nt=t=>A(w(t)),st={binary:(t,n,s)=>h(t," ".concat(n," "),E(s)),constant:t=>A(t?"1 = 1":"0 = 1"),connect:(t,n,s)=>h("(",t,") ".concat(s," ("),n,")"),contains:(t,n)=>h("instr(lower(",t,"), lower(",n,")) > 0"),inList:(t,n,s,o)=>{const i=s?" NOT IN ":" IN ",e=n.every(l=>O(l)),r=n.length>o&&!e?C(n):void 0;if(r!==void 0)return h(t,i,'(SELECT unhex("value") FROM json_each(',E(r),"))");if(n.length>o&&!e)throw new S("BAD_REQUEST",`an "in" list of ${String(n.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(n.length)} placeholders exceed SQLite's per-statement cap of 100 on Durable Objects and D1. Narrow the list to ${String(o)} values or fewer.`);if(n.length<=o){const l=[t,i,"("];for(const[a,u]of n.entries())a>0&&l.push(", "),l.push(E(u));return l.push(")"),h(...l)}return h(t,i,'(SELECT "value" FROM json_each(',E(JSON.stringify(n)),"))")},negate:t=>h("NOT (",t,")"),nullCheck:(t,n)=>h(t,n?" IS NOT NULL":" IS NULL"),value:E},v=L.boundParams/2,I=["eq","ne","lt","lte","gt","gte","in","notIn","isNull","contains"],M=new Set(I),R=new Set(["gt","gte","lt","lte"]),D={eq:"=",gt:">",gte:">=",lt:"<",lte:"<=",ne:"<>"},d=t=>{if(t===null||typeof t!="object"||Array.isArray(t))return!1;const n=Object.keys(t);return n.length>0&&n.every(s=>M.has(s))},P=(t,n,s,o,i)=>{const e=i.value(o.serialize(s,t));return o.containsExpr?o.containsExpr(n,e):i.contains(n,e)},g=(t,n,s,o,i)=>{const e=y(s);return e===void 0?i.constant(!1):i.connect(n,o.rangeTypeGuard(t,e),"AND")},k=(t,n,s,o,i,e,r,l)=>{if(i===null)return s==="eq"||s==="ne"?r.nullCheck(n,s==="ne"):r.constant(!1);const a=r.binary(n,o,e.serialize(i,t));return!l&&R.has(s)&&T(t)?g(t,a,i,e,r):a},F=(t,n,s,o,i,e)=>{if(!Array.isArray(o))throw new S("BAD_REQUEST",`\`${s==="IN"?"in":"notIn"}\` on "${t}" expects an array of values, received ${o===null?"null":typeof o}`);const r=o;if(r.length===0)return e.constant(s==="NOT IN");const l=r.map(u=>i.serialize(u,t)),a=s==="NOT IN";return i.inList?i.inList(n,l,a):e.inList(n,l,a,v)},$=L.boundParams/2,G=6e4,B=(t,n)=>{const s={bytes:[],hasNull:!1,numbers:[],strings:[]};for(const o of t)if(o===null)s.hasNull=!0;else if(o instanceof Uint8Array)s.bytes.push(Array.from(o,i=>i.toString(16).padStart(2,"0")).join(""));else if(typeof o=="number"&&O(o))s.numbers.push(o);else if(typeof o=="string"&&O(o))s.strings.push(o);else throw new S("BAD_REQUEST",`an "in" list of ${String(t.length)} values holds a value that cannot be bound as one parameter (a non-finite number, or malformed text). Narrow the list to ${String(n)} values or fewer.`);return s},q=(t,n,s)=>{const o=[],i=c.identifier("v"),e=c.identifier("__in__"),r=a=>c`jsonb_array_elements_text(CAST(CAST(${JSON.stringify(a)} AS text) AS jsonb))`,l=(a,u)=>c`JSON_TABLE(${JSON.stringify(a)}, '$[*]' COLUMNS (${i} ${c.raw(u)} PATH '$')) ${e}`;return s.strings.length>0&&o.push(t==="postgres"?c`${n} IN (SELECT ${r(s.strings)})`:c`${n} IN (SELECT CONVERT(${i} USING utf8mb4) FROM ${l(s.strings,"LONGTEXT")})`),s.numbers.length>0&&o.push(t==="postgres"?c`${n} IN (SELECT CAST(${r(s.numbers)} AS double precision))`:c`${n} IN (SELECT ${i} FROM ${l(s.numbers,"DOUBLE")})`),s.bytes.length>0&&o.push(t==="postgres"?c`${n} IN (SELECT decode(${r(s.bytes)}, 'hex'))`:c`${n} IN (SELECT UNHEX(${i}) FROM ${l(s.bytes,"LONGTEXT")})`),o},ot=t=>(n,s,o,i=$)=>{const e=Math.floor(G*i/$);if(s.length<=e){const u=c.join(s.map(p=>c`${p}`),c`, `);return o?c`${n} NOT IN (${u})`:c`${n} IN (${u})`}const r=B(s,e);if(o&&r.hasNull)return c`1 = 0`;const l=q(t,n,r);if(l.length===0)return c`1 = 0`;const a=l.length===1?l[0]:c`(${c.join(l,c` OR `)})`;return o?c`NOT (${a})`:a},K=(t,n,s,o,i)=>{const e=s,r=[];for(const l of I){if(!(l in e))continue;const a=e[l],u=D[l];u?r.push(k(t,n,l,u,a,o,i,s[j]===!0)):l==="isNull"?r.push(i.nullCheck(n,!a)):l==="contains"?r.push(P(t,n,a,o,i)):r.push(F(t,n,l==="in"?"IN":"NOT IN",a,o,i))}return r},z=(t,n,s,o)=>{const i=s.fieldRef(t);return d(n)?K(t,i,n,s,o):n===null?[o.nullCheck(i,!1)]:[o.binary(i,"=",s.serialize(n,t))]},N=(t,n,s)=>{if(t.length<=1)return t[0];const o=Math.floor(t.length/2);return s.connect(N(t.slice(0,o),n,s),N(t.slice(o),n,s),n)},J=(t,n,s,o)=>{const i=Array.isArray(t)?t:[],e=[];for(const r of i){const l=f(r??{},s,o);if(l!==void 0)e.push(l);else if(n==="OR")return}return e.length===0?n==="OR"?o.constant(!1):void 0:N(e,n,o)},Y=new Set(["AND","NOT","OR",b]),Q=(t,n,s,o)=>{if(t===b){if(!s.relationExists)throw new S("INTERNAL","encountered a relation EXISTS marker without a relationExists strategy hook");return s.relationExists(n)}if(t==="NOT"){const i=f(n??{},s,o);return i===void 0?o.constant(!1):o.negate(i)}return J(n,t,s,o)},f=(t,n,s)=>{const o=[];for(const[i,e]of Object.entries(t))if(Y.has(i)){const r=Q(i,e,n,s);r!==void 0&&o.push(r)}else o.push(...z(i,e,n,s));return N(o,"AND",s)},m=t=>{let n=0,s=0;const o=i=>{const e=m(i);n+=e.lists,s+=e.scalars};if(Array.isArray(t)){for(const i of t)o(i);return{lists:n,scalars:s}}if(t===null||typeof t!="object")return{lists:n,scalars:s};for(const[i,e]of Object.entries(t))i==="in"||i==="notIn"?n+=1:i==="AND"||i==="NOT"||i==="OR"||d(e)?(o(e),T(i)&&(s+=1+Object.keys(e).filter(r=>R.has(r)).length)):s+=T(i)?2:1;return{lists:n,scalars:s}},it=(t,n,s=U,o=0)=>{if(!t||Object.keys(t).length===0)return;const{lists:i,scalars:e}=m(t);if(i===0)return f(t,n,s);const r=Math.max(1,Math.floor(Math.min($,L.boundParams-e-o)/i)),l=n.inList??((a,u,p,_)=>s.inList(a,u,p,_??r));return f(t,{...n,inList:(a,u,p)=>l(a,u,p,r)},s)};export{it as c,nt as i,h as j,A as r,ot as s,st as t};
|
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.129",
|
|
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",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as y}from"@lunora/errors";import{D as lt}from"./MAX_TOKEN_LENGTH-BakL9FUy-B3VwYY8C.mjs";import{S as Sn,l as Fe,h as _n}from"./fts-companion-pUdD6kF-.mjs";import{sql as c}from"drizzle-orm";import{d as Rn}from"./wire-codec-BYCSiazv.mjs";import{stableWireKey as Ct}from"./stableWireKey-Bdh5JSdg.mjs";import{throwingScheduler as Tn,aggregateSqlFunction as qe,normalizeCountArgument as vn}from"./AGGREGATE_SQL_FUNCTION-BMtvQHac.mjs";import{aggregateTableName as Xe,encodeAggregateKey as Ze,readAggregateValue as et}from"./aggregateTableName-DbAttCNH.mjs";import{mergeWhere as N,CountRlsUnsupportedError as tt,selectIndexForGroupBy as An,selectIndexForCount as In,selectIndexForAggregate as Cn}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{backfillSearchIndexesForTable as xn,searchIndexCoversTable as bn}from"./backfillAggregateIndexes-CJrtolQ9.mjs";import{backfillAggregateIndexes as ni,backfillRankIndexes as ri,backfillSearchIndexes as oi}from"./backfillAggregateIndexes-CJrtolQ9.mjs";import{appendCdcChange as Mn,readCdcDocAtOrBefore as Dn}from"./CDC_LOG_TABLE-BPEzVAil.mjs";import{CDC_LOG_TABLE as si,applyCdcChanges as ci,bumpCdcEpoch as ai,cdcCanVouchFor as di,cdcForkedError as li,cdcSeqLeavingRows as ui,cdcTouchesTables as fi,cdcTrimmedError as hi,compactCdcDocs as wi,cursorBelowRetainedFloor as pi,minCdcReplayableSeq as gi,minCdcSeq as yi,readCdcChangeKeys as $i,readCdcChanges as Ei,readCdcCursor as mi,readCdcEpoch as Si,trimCdcChanges as _i}from"./CDC_LOG_TABLE-BPEzVAil.mjs";import{allocateCommitSeq as kn,COMMIT_SEQ_FIELD as Ln}from"./COMMIT_SEQ_FIELD-BY_vc9bw.mjs";import{createCompanionSync as Fn}from"./createCompanionSync-B7dV2y4L.mjs";import{isMemoryTable as xt}from"./clearMemoryTables-CogAvVHR.mjs";import{computeRankPage as bt}from"./computeRankPage-CFeFkZ_k.mjs";import{SCAN_DEP as O}from"./SCAN_DEP-D7qE3iUe.mjs";import{runSql as we,runDrizzle as G}from"./runDrizzle-Du5HLitO.mjs";import{p as qn,j as ct,D as oe,r as Te,k as le,b as We,A as nt,a as Be,m as fe,e as he,s as Wn,t as tn,i as Bn,q as Mt,h as nn,g as Pn}from"./do-sql-Cg3zXJpF.mjs";import{renderSql as rn,unionAll as ut,WORKERD_SQLITE_LIMITS as on,sqliteInList as Un}from"./WORKERD_SQLITE_LIMITS-DBH23L_S.mjs";import{coveringGeohashes as On,boundingBoxGeohashes as Hn,haversineMeters as Gn,pointInBoundingBox as jn}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{NotFoundError as Kn}from"./NotFoundError-BhF7FeFr.mjs";import{resolvePatch as Nn,assertPatchAllowed as Qn,operatorFields as Vn,readPatchField as Dt}from"./assertPatchAllowed-BJ_2LgkQ.mjs";import{tiebreakDirectionFor as Jn,encodeCursor as He,nullsOrderSuffix as zn,normalizeOrderKeys as kt,uniqueIndexFields as Yn,buildSeekWhere as Xn,decodeCursor as Lt,buildSeekBeforeWhere as Zn,softDeleteScope as Re,applySelect as Ft}from"./CURSOR_PREFIX-BztyXqNP.mjs";import{rankTableName as qt,sortColumnName as Wt,resolveRankPartition as er,encodePartitionKey as tr,RANK_TIEBREAK as nr,rankPivotConditionSql as rr}from"./RANK_TIEBREAK-BKugKf70.mjs";import{UNVOUCHABLE_DEP as Bt}from"./UNVOUCHABLE_DEP-C68htACn.mjs";import{indexKeysForRow as or,buildIndexRange as ir}from"./buildIndexRange-6nIZDf4m.mjs";import{r as Ge,j as ve,c as X,t as je,i as Pt}from"./where-sql-Dn9trjRu.mjs";import{serializeSqlValue as Ae}from"./serializeSqlValue-BbZ5hKM7.mjs";import{quoteIdentifier as Ie}from"./quoteIdentifier-CObIFRhb.mjs";import{whereOfFilter as sr,isPushableWhere as cr}from"./isPushableWhere-BeYAOjUb.mjs";import{deriveRelationEdges as ar,findRelated as dr}from"./RELATED_DEFAULT_LIMIT-Me5elP-K.mjs";import{assertFlatPredicate as rt,resolveRelationPredicates as lr,composeReadPredicate as ur}from"./DEFAULT_MAX_RELATION_KEYS-Bk8B9GIQ.mjs";import{describeRelationWrites as fr}from"./describeRelationWrites-omar6-u9.mjs";import{runRowValidators as ot,resolveWith as Ut,relationHooks as Ot,applyOnDelete as hr,fanOutScalarCounts as wr}from"./applyOnDelete-CGVYKtaW.mjs";import{guardWriter as pr}from"./RLS_UNWRAP_SYMBOL-qYcAxjuk.mjs";import{mayHoldProjectedValue as gr}from"./BIGINT_KEY_DIGITS-C9a7Ix7k.mjs";import{createSystemReader as yr}from"./createSystemReader-DcDLFfC-.mjs";import{ConflictError as ae}from"./ConflictError-C8GtJmjS.mjs";import{runTriggers as $r}from"./hasTrigger-CjlwI4le.mjs";import{advanceClientWatermark as Ti,migrateClientWatermark as vi,readClientWatermark as Ai}from"./CLIENT_WATERMARK_TABLE-vLjfNhBR.mjs";import{IDEMPOTENCY_TABLE as Ci,readIdempotent as xi,trimIdempotent as bi,writeIdempotent as Mi}from"./IDEMPOTENCY_TABLE-AOJCuq5U.mjs";import{runShardMigrations as ki}from"./runShardMigrations-eqHNBW6S.mjs";import{selectShapeMembers as Fi,selectShapeRows as qi}from"./selectShapeMembers-CU8Kl2Bq.mjs";const Er=n=>{const i=atob(n),r=Uint8Array.from(i,a=>a.codePointAt(0)??0);return new TextDecoder().decode(r)},mr=()=>new y("BAD_REQUEST","invalid cursor"),Ht=16,Gt=8,z=1024,ft=(n,i)=>i.query(n),Sr=(n,i)=>{if(n.length===0)return 0;let r=0;for(const[a,s]of i.entries()){const w=a===i.length-1;let A=0;for(const T of n)(w?T.startsWith(s):T===s)&&(A+=1);if(A===0)return 0;r+=A}return r},_r=(n,i)=>{if(!i)return{exact:!0,lower:n,upper:n};const r=[...n].at(-1)??"",a=(r.codePointAt(0)??0)+1;if(a>=55296&&a<=57343||a>1114111)return{exact:!0,lower:n,upper:n};const s=n.slice(0,n.length-r.length);return{exact:!1,lower:n,upper:s+String.fromCodePoint(a)}},Rr=(n,i,r)=>{const a={eq:(s,w)=>{if(!n.definition.filterFields?.includes(s))throw new y("INTERNAL",`field "${s}" is not a filter field of search index "${n.indexName}" on table "${i}"`);if(n.filters.length>=Gt)throw new y("BAD_REQUEST",`search index "${n.indexName}" on table "${i}": at most ${String(Gt)} .eq() filters are supported per search query`);return n.filters.push({field:s,value:w}),a},search:(s,w)=>{const A=n;if(s!==A.definition.field)throw new y("INTERNAL",`search index "${A.indexName}" on table "${i}" indexes "${A.definition.field}", not "${s}"`);const T=ft(w,r).length;if(T>Ht)throw new y("BAD_REQUEST",`search index "${A.indexName}" on table "${i}": at most ${String(Ht)} search terms are supported (got ${String(T)})`);return A.field=s,A.query=w,A.hasQuery=!0,a}};return a},Tr=n=>{if(n.length>z)throw new y("BAD_REQUEST",`more than ${String(z)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},vr=n=>Math.min(n.offset+n.numItems+1,z),Ar=n=>btoa(`search:${String(n)}`),Ir=n=>{let i;try{i=Er(n)}catch{return}if(!i.startsWith("search:"))return;const r=Number(i.slice(7));return Number.isInteger(r)&&r>=0?r:void 0},Cr=n=>{if(typeof n.endCursor=="string")throw new y("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");if(!Number.isFinite(n.numItems))throw new y("BAD_REQUEST",`search pagination needs a finite numItems, got ${String(n.numItems)}`);const i=Math.max(0,Math.floor(n.numItems)),r=n.cursor?Ir(n.cursor):0;if(r===void 0)throw mr();if(r+i>=z)throw new y("BAD_REQUEST",`search pagination reaches the ${String(z)}-document limit (offset ${String(r)} + ${String(i)} requested) — a page must end below the cap so the probe row that answers \`hasMore\` still fits: retry with numItems ${String(Math.max(1,z-r-1))} or fewer, or narrow the query or the filters instead`);return{numItems:i,offset:r}},xr=(n,i)=>{const r=i.offset+i.numItems,a=i.numItems>0&&n.length>r;return{continueCursor:a?Ar(r):null,isDone:!a,page:n.slice(i.offset,r)}},br=n=>{if(n===void 0)return z+1;if(!Number.isFinite(n))return z;const i=Math.max(0,Math.floor(n));if(i>z)throw new y("BAD_REQUEST",`search returns at most ${String(z)} documents (asked for ${String(i)}) — narrow the query or paginate instead`);return i},Mr=32,Dr=1024,sn=(n,i,r,a)=>{const s=`SELECT id, _creationTime, ${Ie(oe)} FROM ${Ie(n)}`,w=`ORDER BY ${r}${a===void 0?"":` LIMIT ${String(a)}`}`;return i===void 0?Ge(`${s} ${w}`):ve(`${s} WHERE `,i,` ${w}`)},Ke={fieldRef:n=>Ge(ct(n)),rangeTypeGuard:(n,i)=>Ge(qn(n,i)),serialize:Ae},kr=n=>n===void 0?"":zn(n==="first"),cn=n=>{const i=n.map(r=>`${ct(r.field)} ${r.direction==="desc"?"DESC":"ASC"}${kr(r.nulls)}`);return n.some(r=>r.field==="_id"||r.field==="id")||i.push(`${ct("id")} ${Jn(n)==="desc"?"DESC":"ASC"}`),i.join(", ")},Lr={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},an=n=>new Set(n.sqlConditions.filter(i=>i.comparator==="=").map(i=>i.field)),Fr=n=>{const i=an(n);let r=0;for(;r<n.indexFields.length&&i.has(n.indexFields[r]??"");)r+=1;return n.indexFields.slice(r)},qr=(n,i)=>{const r=n.order,a=Fr(n),{shape:s}=i;return a.length>0?kt(a.map(w=>({[w]:r})),s,{pinned:an(n),uniqueBy:Yn(i.indexes,s)}):kt([{_creationTime:r}],s)},Wr=(n,i,r,a)=>{const s=n.sqlConditions.map(w=>({[w.field]:{[Lr[w.comparator]??"eq"]:w.value}}));if(r&&s.push(Xn(i,Lt(r))),a&&s.push(Zn(i,Lt(a))),s.length!==0)return s.length===1?s[0]:{AND:s}},Br=n=>{if(n.want!==void 0)return n.selective?Math.max(n.want,Mr):n.want},at=(n,i,r,a,s,w,A)=>{const T=qr(a,r),b=cn(T),g=[],{filters:k,want:v}=w;let C=w.cursor??void 0,x=Br(w);if(v===0)return{documents:g,orderKeys:T};for(;;){const U=X(Wr(a,T,C,w.endCursor),Ke,je),q=sn(i,s&&U?ve(U," AND ",s):s??U,b,x),F=we(n,q.text,...q.params).toArray();let W={};A(F.length);for(const j of F)if(W=Te(j),k.every(L=>L(W))&&g.push(W)===v)return{documents:g,orderKeys:T};if(x===void 0||F.length<x)return{documents:g,orderKeys:T};C=He(W,T),x=Math.max(x,Math.min(x*2,Dr))}},Pr=(n,i,r,a,s,w,A,T)=>{const b=Math.max(0,Math.floor(s.numItems));if(typeof s.endCursor=="string"){const{documents:U,orderKeys:q}=at(n,i,r,a,w,{cursor:s.cursor,endCursor:s.endCursor,filters:A.all,selective:A.selective,want:void 0},T),F=U.length>=2?U[Math.floor(U.length/2)-1]:void 0;return{continueCursor:s.endCursor,isDone:!0,page:U,splitCursor:F?He(F,q):null}}const{documents:g,orderKeys:k}=at(n,i,r,a,w,{cursor:s.cursor,filters:A.all,selective:A.selective,want:b+1},T),v=g.length>b,C=v?g.slice(0,b):g,x=C.at(-1);return{continueCursor:v&&x?He(x,k):null,isDone:!v,page:C}},Ne=n=>{const i=new Map;return r=>{const a=i.get(r);if(a!==void 0)return a;const s=n(Ie(r));return i.set(r,s),s}},pe=Ie(oe),Ur=Ne(n=>`INSERT INTO ${n} (id, _creationTime, ${pe}) VALUES (?, ?, ?)`),jt=Ne(n=>`UPDATE ${n} SET ${pe} = ? WHERE id = ? AND ${pe} = ?`),Or=Ne(n=>`UPDATE ${n} SET _creationTime = ?, ${pe} = ? WHERE id = ? AND ${pe} = ?`),Hr=Ne(n=>`DELETE FROM ${n} WHERE id = ? AND ${pe} = ?`),Gr="SELECT changes() AS changed",Kt=new Map,jr="",Kr=n=>{const i=JSON.stringify(n),r=Kt.get(i);if(r!==void 0)return r;const a=n.map(w=>c`SELECT ${c.raw(`'${w.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${c.identifier(oe)} FROM ${c.identifier(w)} WHERE id = ${jr}`),{sql:s}=rn("sqlite",c`${ut(a)} LIMIT 1`);return Kt.set(i,s),s},Nr=(n,i)=>i.map(()=>n),Qr=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,Vr=n=>{if(!Qr.test(n))throw new y("INTERNAL",`invalid clientId ${JSON.stringify(n)}: a client-supplied row id must be a UUID`)},Nt=50,dn=500,Pe=Math.floor(on.boundParams/3),_e=on.boundParams,Jr=128,ue=(n,i,r)=>{const a=i??dn;if(n>a)throw new y("BATCH_LIMIT_EXCEEDED",`${r}: batch of ${String(n)} exceeds the limit of ${String(a)} (raise options.limit or chunk the call)`,{status:400})},zr=n=>{const i={eq:(r,a)=>(n.sqlConditions.push({comparator:"=",field:r,value:a}),i),gt:(r,a)=>(n.sqlConditions.push({comparator:">",field:r,value:a}),i),gte:(r,a)=>(n.sqlConditions.push({comparator:">=",field:r,value:a}),i),lt:(r,a)=>(n.sqlConditions.push({comparator:"<",field:r,value:a}),i),lte:(r,a)=>(n.sqlConditions.push({comparator:"<=",field:r,value:a}),i)};return i},Yr=n=>Math.max(n,z),ln=(n,i)=>{const r=n.filters.map(a=>c`${he(a.field)} = ${Ae(a.value)}`);return i&&r.push(i),r},Xr=(n,i,r,a,s)=>{const w=ft(r.query,lt(r.definition.language));if(w.length===0)return[];const A=Sn(i,r.indexName),T=`${A}__vocab`,b=w.length-1,g=w.map((q,F)=>{const W=_r(q,F===b),j=W.exact?c`${c.identifier("term")} = ${W.lower}`:c`${c.identifier("term")} >= ${W.lower} AND ${c.identifier("term")} < ${W.upper}`;return c`SELECT ${c.identifier("doc")}, ${c.raw(String(F))} AS ${c.identifier("__term__")}, COUNT(*) AS ${c.identifier("__n__")} FROM ${c.identifier(T)} WHERE ${j} GROUP BY ${c.identifier("doc")}`}),k=w.map((q,F)=>c`SUM(CASE WHEN u.${c.identifier("__term__")} = ${c.raw(String(F))} THEN u.${c.identifier("__n__")} ELSE 0 END)`),v=c`SELECT f.${c.identifier(Fe)} AS ${c.identifier(Fe)}, ${c.join(k,c` + `)} AS ${c.identifier("__score__")} FROM (${ut(g)}) u JOIN ${c.identifier(A)} f ON f.rowid = u.${c.identifier("doc")} GROUP BY f.${c.identifier(Fe)} HAVING ${c.join(k.map(q=>c`${q} > 0`),c` AND `)}`,C=ln(r,s);let x=c`SELECT m.id, m._creationTime, m.${c.identifier(oe)}, s.${c.identifier("__score__")} AS ${c.identifier("__score__")} FROM (${v}) s JOIN ${c.identifier(i)} m ON m.id = s.${c.identifier(Fe)}`;C.length>0&&(x=c`${x} WHERE ${c.join(C,c` AND `)}`),x=c`${x} ORDER BY s.${c.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${c.raw(String(a))}`;const U=[];for(const q of G(n,x)){const F=nn(q);if(F){const W=q.__score__;U.push({document:F,score:typeof W=="number"?W:Number(W??0)})}}return U},Zr=(n,i,r,a,s)=>{const w=lt(r.definition.language),A=ft(r.query,w);if(A.length===0)return[];const T=ln(r,s);let b=c`SELECT id, _creationTime, ${c.identifier(oe)} FROM ${c.identifier(i)}`;T.length>0&&(b=c`${b} WHERE ${c.join(T,c` AND `)}`),b=c`${b} ORDER BY _creationTime DESC, id ASC LIMIT ${c.raw(String(Yr(a)))}`;const g=G(n,b).toArray(),k=[];for(const v of g){const C=nn(v);if(!C)continue;const x=Sr(_n(C,r.definition),A);x>0&&k.push({creationTime:typeof C._creationTime=="number"?C._creationTime:0,doc:C,id:typeof C._id=="string"?C._id:"",score:x})}return k.sort((v,C)=>C.score-v.score||C.creationTime-v.creationTime||v.id.localeCompare(C.id)),k.slice(0,a).map(v=>({document:v.doc,score:v.score}))},it=(n,i,r,a)=>{if(!Number.isFinite(n.lat)||n.lat<-90||n.lat>90||!Number.isFinite(n.lng)||n.lng<-180||n.lng>180)throw new y("BAD_REQUEST",`geo index "${a}" on table "${r}": ${i} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},eo=(n,i)=>{const r=n,a={near:(s,w)=>{if(r.within)throw new y("INTERNAL",`geo index "${r.indexName}" on table "${i}": call .near() or .within(), not both`);if(it(s,".near() point",i,r.indexName),!Number.isFinite(w)||w<=0)throw new y("BAD_REQUEST",`geo index "${r.indexName}" on table "${i}": .near() radiusMeters must be a finite number > 0, got ${String(w)}`);return r.near={point:{lat:s.lat,lng:s.lng},radiusMeters:w},a},within:s=>{if(r.near)throw new y("INTERNAL",`geo index "${r.indexName}" on table "${i}": call .near() or .within(), not both`);if(it(s.sw,".within() sw corner",i,r.indexName),it(s.ne,".within() ne corner",i,r.indexName),s.sw.lat>s.ne.lat)throw new y("BAD_REQUEST",`geo index "${r.indexName}" on table "${i}": .within() corners are transposed (sw.lat > ne.lat)`);if(s.sw.lng>s.ne.lng)throw new y("BAD_REQUEST",`geo index "${r.indexName}" on table "${i}": .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 r.within={ne:{lat:s.ne.lat,lng:s.ne.lng},sw:{lat:s.sw.lat,lng:s.sw.lng}},a}};return a},to=(n,i)=>{const r=n[i];if(r===null||typeof r!="object")return;const{lat:a,lng:s}=r;return typeof a=="number"&&typeof s=="number"?{lat:a,lng:s}:void 0},no=(n,i)=>{const r=to(n,i.definition.field);if(!r)return;const a=typeof n._creationTime=="number"?n._creationTime:0;if(i.near){const s=Gn(i.near.point,r);return s<=i.near.radiusMeters?{creationTime:a,distance:s}:void 0}return jn(r,i.within)?{creationTime:a,distance:0}:void 0},ro=(n,i,r,a)=>{if(!r.near&&!r.within)throw new y("INTERNAL",`geo index "${r.indexName}" on table "${i}": call .near(point, radius) or .within(box)`);const s=r.near?On(r.near.point,r.near.radiusMeters):Hn(r.within),w=Pn(i,r.indexName),A=s.map(v=>c`(g.${c.identifier("__geohash__")} >= ${v} AND g.${c.identifier("__geohash__")} < ${`${v}{`})`),T=[c`(${c.join(A,c` OR `)})`];a&&T.push(a);const b=c`SELECT m.id, m._creationTime, m.${c.identifier(oe)} FROM ${c.identifier(w)} g JOIN ${c.identifier(i)} m ON m.id = g.${c.identifier("__id__")} WHERE ${c.join(T,c` AND `)}`,g=G(n,b).toArray(),k=[];for(const v of g){const C=Te(v),x=C?no(C,r):void 0;C&&x&&k.push({creationTime:x.creationTime,distance:x.distance,doc:C})}return k.sort((v,C)=>v.distance-C.distance||C.creationTime-v.creationTime),k},un=(n,i,r,a)=>{const s=[];for(const w of n)if(i.every(A=>A(a(w)))&&(s.push(w),typeof r=="number"&&s.length>=r))break;return s},oo=(n,i,r,a,s,w=()=>{})=>{const A=r.within!==void 0,T=ro(n,i,r,s).map(b=>({distanceMeters:A?null:b.distance,document:b.doc}));return w(T.length),typeof a=="number"?T.slice(0,Math.max(0,Math.floor(a))):T},Qt=(n,i,r,a,s,w,A=()=>{})=>{const{geo:T}=r;if(!T)throw new y("INTERNAL","runGeoTerminalScored called without a staged geo query");const b=s.length>0,g=oo(n,i,T,b?void 0:w,a,A);return b?un(g,s,w,k=>k.document):g},Vt=(n,i,r)=>{const a=n.shape[i];if(a!==void 0&&gr(a))throw new y("BAD_REQUEST",`${r}: "${i}" may hold an order-preserving key rather than a value SQL can reduce or group — declare an aggregateIndex covering this (by, field, op) so the maintained companion answers it instead (its running total is a REAL, so it stays exact only while the total is inside 2^53)`)},io=n=>{let i=0;const r=[],a={...Ke,relationExists:s=>{const{childWhere:w,negated:A,parentTable:T,relation:b}=s,g=`__rel_${String(i)}`,k=r.at(-1)??T;i+=1,n(b.table,O);const v=b.kind==="one"?b.field:b.references,C=b.kind==="one"?b.references:b.field,x=Ge(`${Mt(g,C)} = ${Mt(k,v)}`);r.push(g);const U=X(w,a,je);r.pop();const q=U===void 0?x:ve(x," AND ",U),F=ve("EXISTS (SELECT 1 FROM ",Pt(b.table)," AS ",Pt(g)," WHERE ",q,")");return A?ve("NOT ",F):F}};return a};class so extends y{constructor(i="unique() found more than one matching document"){super("NOT_UNIQUE",i,{name:"NotUniqueError"})}}const co=/\s/u,ao=String.fromCodePoint(0),Jt=(n,i,r)=>{if(!n.tables[i])throw new y("INTERNAL",`unknown table: ${i}`);return typeof r!="string"||r.length===0||co.test(r)||r.includes(ao)?null:r},fn=(n,i,r,a=()=>{},s=()=>{},w=()=>{},A)=>{const T=i.tables[r];if(!T)throw new y("INTERNAL",`unknown table: ${r}`);const b=Re(T.softDeleteMode,void 0),g=A??{indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[],verifyFilters:[]},k=()=>{const $=N(b,g.pushedWhere);return $?X($,fe):void 0},v=()=>{const $=N(b,g.pushedWhere);return $?X($,Ke,je):void 0},C=()=>[...g.inMemoryFilters,...g.verifyFilters];let x=0;const U=$=>{const{search:I}=g;if(!I)throw new y("INTERNAL","runSearchFetch called without a staged search");xn(n,r,T);const M=g.inMemoryFilters.length>0,D=br(M?void 0:$),Q=Bn(n);if(Q&&!bn(n,r,I.definition))throw new y("SEARCH_INDEX_BUILDING",`search index "${I.indexName}" on table "${r}" is still backfilling and currently covers only part of the table — retry once it finishes, or run the backfillSearch admin operation to complete it now`);const ge=k(),ie=Q?Xr(n,r,I,D,ge):Zr(n,r,I,D,ge);!M&&$===void 0&&Tr(ie);const re=C();return x=ie.length,re.length>0?un(ie,re,$,se=>se.document):ie},q=$=>U($).map(I=>I.document),F=$=>{const I=Cr($);return xr(q(vr(I)),I)},W=()=>{if(g.search||g.geo||g.indexName===void 0){s(void 0);return}s(ir(r,g.indexName,g.indexFields,g.sqlConditions,Ae))},j=$=>{W();let I=0;const M=(()=>{if(g.search){const D=q($);return I=x,D}return g.geo?Qt(n,r,g,k(),C(),$,D=>{I=D}).map(D=>D.document):at(n,r,T,g,v(),{filters:C(),selective:g.inMemoryFilters.length>0,want:$===void 0?void 0:Math.max(0,Math.floor($))},D=>{I+=D}).documents})();return w(Math.max(I,M.length)),M},L=()=>{if(!g.search&&!g.geo)throw new y("INTERNAL",`ctx.db.query("${r}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);W();let $=0;const I=(()=>{if(g.search){const M=U(void 0);return $=x,M}return Qt(n,r,g,k(),C(),void 0,M=>{$=M})})();return w(Math.max($,I.length)),I},J={async*[Symbol.asyncIterator](){const $=fn(n,i,r,a,s,w,{...g,indexFields:[...g.indexFields],inMemoryFilters:[...g.inMemoryFilters],sqlConditions:[...g.sqlConditions],verifyFilters:[...g.verifyFilters]});if(g.search){yield*await $.collect();return}let I;for(;;){const M=await $.paginate({cursor:I??null,numItems:Jr});if(yield*M.page,M.isDone||M.continueCursor===null)return;I=M.continueCursor}},async collect(){return j(void 0)},async collectWithScores(){return L()},filter($){const I=sr($);return I!==void 0&&cr(I,T.shape)?(g.pushedWhere=N(g.pushedWhere,I),g.verifyFilters.push($)):g.inMemoryFilters.push($),J},async first(){return j(1)[0]??null},order($){return g.order=$==="desc"?"desc":"asc",J},async paginate($){let I=0;if(W(),g.search){const D=F($);return w(D.page.length),D}if(g.geo)throw new y("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const M=Pr(n,r,T,g,$,v(),{all:C(),selective:g.inMemoryFilters.length>0},D=>{I+=D});return w(Math.max(I,M.page.length)),M},async take($){return j($)},async unique(){const $=j(2);if($.length>1)throw new so(`unique() on table "${r}" matched ${String($.length)} documents; expected at most one`);return $[0]??null},withGeoIndex($,I){const M=(T.geoIndexes??[]).find(Q=>Q.name===$);if(!M)throw new y("INTERNAL",`unknown geo index "${$}" on table "${r}"`);a(r,$,"geo");const D={definition:M,indexName:$};if(g.geo=D,I(eo(D,r)),!D.near&&!D.within)throw new y("INTERNAL",`geo index "${$}" on table "${r}" requires a .near(point, radius) or .within(box) call`);return J},withIndex($,I){const M=T.indexes.find(D=>D.name===$);if(!M)throw new y("INTERNAL",`unknown index "${$}" on table "${r}"`);return a(r,$,"index"),g.indexName=$,g.indexFields=M.fields,I&&I(zr(g)),J},withSearchIndex($,I){const M=(T.searchIndexes??[]).find(Q=>Q.name===$);if(!M)throw new y("INTERNAL",`unknown search index "${$}" on table "${r}"`);a(r,$,"search");const D={definition:M,field:M.field,filters:[],hasQuery:!1,indexName:$,query:""};if(g.search=D,I(Rr(D,r,lt(M.language))),!D.hasQuery)throw new y("INTERNAL",`search index "${$}" on table "${r}" requires a .search(field, query) call`);return J}};return J},zt=(n,i,r)=>{const a={...i};for(const[s,w]of tn(n)){if(w.serverDefault){a[s]=w.serverDefault({auth:r});continue}a[s]===void 0&&(w.defaultFn?a[s]=w.defaultFn():"defaultValue"in w&&(a[s]=w.defaultValue))}return a},st=(n,i,r,a)=>{const s=r;for(const[w,A]of tn(n)){if(A.serverDefault){w in i&&(s[w]=A.serverDefault({auth:a}));continue}A.onUpdateFn&&!(w in i)&&(s[w]=A.onUpdateFn())}},Yt=5,Xt=(n,i)=>{for(const r of Object.keys(i))if(i[r]===void 0)throw new y("INTERNAL",`Cannot ${n} field '${r}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},Zt=["_commitSeq","_creationTime","_id"],Ue=n=>Zt.some(i=>i in n)?Object.fromEntries(Object.entries(n).filter(([i])=>!Zt.includes(i))):n,lo=/unique constraint failed/i,uo=n=>n instanceof Error&&lo.test(n.message),fo=/string or blob too big/iu,ho=(n,i)=>{if(!(!(n instanceof Error)||!fo.test(n.message)))throw new y("PAYLOAD_TOO_LARGE",`document is too large to store in "${i}": a single row cannot exceed the storage engine's per-row ceiling (2 MB on a Durable Object's SQLite). The limit is on the STORED bytes, which are UTF-8, and v.bytes()/v.bigint() columns are stored twice on a shard-local table. Keep the payload in R2 (ctx.storage) and store a reference on the row.`)},dt=(n,i,r,a)=>{try{we(n,r,...a)}catch(s){throw uo(s)?new ae(`unique constraint violation on "${i}"`,"unique"):(ho(s,i),s)}},Oe=(n,i,r,a)=>{if(dt(n,i,r,a),we(n,Gr).one().changed===0)throw new ae(`optimistic concurrency conflict on "${i}" — the row changed during this mutation; refetch and retry`,"occ")},en=(n,i,r,a,s,w,A)=>{const T=[];for(let v=0;v<r.length+1;v+=1){const C=r[v],x=a[v],U=x?.direction==="desc"?"desc":"asc",q=C===void 0||x===void 0?c`${c.identifier(nr)} < ${A}`:rr(C,w[v],U,!1);if(q===void 0)continue;const F=[];for(let j=0;j<v;j+=1)F.push(c`${c.identifier(r[j])} IS ${w[j]}`);F.push(q);const[W]=F;T.push(F.length===1&&W!==void 0?W:c`(${c.join(F,c` AND `)})`)}const b=T.length>0?c.join(T,c` OR `):c`1 = 0`,g=G(n,c`SELECT COUNT(*) AS c FROM ${c.identifier(i)} WHERE ${c.identifier("__partition__")} = ${s} AND (${b})`).one(),k=G(n,c`SELECT COUNT(*) AS c FROM ${c.identifier(i)} WHERE ${c.identifier("__partition__")} = ${s}`).one();return{before:g.c,total:k.c}},Zo=n=>{const{baselineSeq:i,onStalePatchDropped:r}=n,{sql:a}=n,{schema:s}=n,w=n.broadcast??(()=>{}),A=ar(s),T=fr(s,n.inTransaction);let b;const g=()=>n.inTransaction?.()===!0,k=e=>s.tables[e]?.commitOrderedMode!==!0?{}:((b===void 0||!g())&&(b=kn(a)),{[Ln]:b}),v=(e,...t)=>{const o=s.tables[e]?.indexes;if(!o||o.length===0)return;const u=[];for(const h of t)h&&u.push(...or(o,h,Ae));return u.length>0?u:void 0},{headroom:C}=n;let x=!1;const U=async e=>{const t=x;x=!0;try{return await e()}finally{x=t}},q=n.onRead??(()=>{}),F=e=>{xt(s.tables[e])&&q(Bt,Bt)},W=n.onReadRange??(e=>{q(e.table,O)}),j=e=>{F(e.table),W(e)},L=(e,t)=>{t!==void 0&&t!==O&&!x&&C?.recordRead(1),F(e),q(e,t)},J=n.onIndexUse??(()=>{}),$=n.onWrite??(()=>{}),I=e=>{x||C?.recordWrite(e)},M=async e=>{I(e.doc),await $(e)},{cache:D}=n,Q=n.clock??(()=>Date.now()),ge=n.idGenerator??(()=>crypto.randomUUID()),ie=n.scheduler??Tn,{globalDb:re}=n,se=n.auth??{identity:null,userId:null},ht=n.cdc??!1,Qe=ie,hn=yr({scheduler:typeof Qe.list=="function"&&typeof Qe.get=="function"?Qe:void 0,storage:n.storage}),ye=(e,t,o,u)=>{ht&&!xt(s.tables[e])&&Mn(a,Q(),e,t,o,u)},wt=(e,t,o,u)=>{const h=s.tables[e];if(h?.dropStalePatchesMode!==!0||!ht)return!1;const f=i?.();if(f===void 0)return!1;const d=Dn(a,e,t,f);if(d===void 0)return!1;const l=Vn(h,o);return Object.keys(Ue(o)).some(p=>!l.has(p)&&Ct(Dt(d,p))!==Ct(Dt(u,p)))},ce=e=>s.tables[e]?.shardMode?.kind==="global",pt=(e,t)=>{if(ce(e)){if(!re)throw new y("INTERNAL",`cross-backend ${t} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return re}return B},Ve=e=>pt(e,"cascade"),K=(e,t)=>{if(ce(e)){if(!re)throw new y("INTERNAL",`${t} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return re}},gt=async(e,t,o,u,h)=>{h&&I(o);const f=await e.insert(t,o,u);return w({key:f,op:"insert",row:{...o,_id:f},table:t}),f},Je=(e,t)=>pt(e,"relation load").findMany(e,t),yt=(e,t)=>(ce(e)&&L(e,O),Je(e,t)),wn=e=>!ce(e.table),$t=n.relationExistsPushDown??"auto",Et=$t!=="never",{maxRelationKeys:mt}=n,Ce=(e,t,o)=>lr(e,{fetcher:yt,maxRelationKeys:mt,relationBaseWhere:o,schema:s,tableName:t}),St=async(e,t,o,u)=>{const h=K(e,"relation grouped count");if(h)return L(e,O),wr((_,H)=>h.count(_,H),e,t,o,u);const f=s.tables[e];if(!f)throw new y("INTERNAL",`unknown table: ${e}`);L(e,O);const d=Re(f.softDeleteMode,void 0),l={[t]:{in:o}},p=N(N(l,u),d),R=await Ce(p,e,void 0),E=X(R,fe),S=he(t);let m=c`SELECT ${S} AS __fk__, COUNT(*) AS count FROM ${c.identifier(e)}`;E&&(m=c`${m} WHERE ${E}`),m=c`${m} GROUP BY ${S}`;const P=G(a,m).toArray();return new Map(P.map(_=>[_.__fk__,_.count]))};let xe=0;const _t=new Set;for(const[e,t]of Object.entries(s.tables))for(const o of Object.values(t.triggerMap??{}))_t.add(`${e} ${o.timing} ${o.op}`);const Z=(e,t,o)=>_t.has(`${e} ${t} ${o}`),ee=async(e,t,o)=>{if(xe+=1,xe>Nt)throw xe-=1,new ae(`trigger recursion exceeded ${String(Nt)} levels on "${o.table}" — check for a self-triggering write`,"trigger");try{await $r({ctx:En,event:o,op:t,schema:s,tableName:o.table,timing:e})}finally{xe-=1}},{ensureBackfilledForTable:$e,ensureBackfilledIndex:ze,ensureRankBackfilled:Ye,ensureRankBackfilledForTable:Ee,syncAggregates:be,syncCompanionsForInsert:Rt,syncGeo:Me,syncRanks:me,syncSearch:De}=Fn({broadcast:w,indexKeysFor:(e,t)=>v(e,t),invalidateCache:(e,t,o)=>D?.invalidate(e,t,v(e,o)),recordCdc:ye,schema:s,sql:a}),Tt=(e,t,o)=>{const{shardMode:u}=t;if(u?.kind==="shardBy"&&!(u.field!==void 0&&(o.partitionBy??[]).includes(u.field)))throw Object.assign(new Error(`rank index "${o.name}" on "${e}" partitions across shards (shard key "${u.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})},vt=e=>Object.entries(s.tables).filter(([,t])=>t.shardMode?.kind!=="global").map(([t])=>t).filter(t=>e===void 0||t===e),Se=e=>e===void 0||ce(e)?re:void 0,te=(e,t)=>{const o=vt(t);for(let u=0;u<o.length;u+=_e){const h=o.slice(u,u+_e),[f]=we(a,Kr(h),...Nr(e,h)).toArray();if(!f)continue;const d=f.__t__,l=Te(f);if(typeof d!="string"||!l)return;const p=f[oe];return{docJson:typeof p=="string"?p:le(p??{}),row:l,tableName:d}}},pn=(e,t)=>{const o=[...new Set(e)],u=new Map;if(o.length===0)return u;const h=vt(t);for(let f=0;f<h.length;f+=_e){const d=h.slice(f,f+_e),l=Math.floor(_e/d.length),p=Un(c`${c.identifier("id")}`,o,!1,l),R=d.map(E=>c`SELECT ${c.raw(`'${E.replaceAll("'","''")}'`)} AS __t__, id FROM ${c.identifier(E)} WHERE ${p}`);for(const E of G(a,ut(R))){const{id:S,__t__:m}=E;typeof m=="string"&&typeof S=="string"&&u.set(S,m)}}return u},At={assertRankPartitionLocal:Tt,ensureRankBackfilled:Ye,onRead:L,rowToDocument:Te,schema:s,sql:a},gn=(e,t,o)=>{const u=X(o,fe);return u===void 0||G(a,c`SELECT 1 FROM ${c.identifier(e)} WHERE ${c.identifier("id")} = ${t} AND ${u}`).toArray().length>0},yn=(e,t,o,u)=>wt(e,t,o,u)?(r?.({fields:Object.keys(Ue(o)),id:t,table:e}),!0):!1,$n=async(e,t,o,u,h)=>{const f=te(t,e);if(!f)return{applied:!1,doc:null};if(L(e,t),!gn(e,t,o.where)||yn(e,t,o.patch,f.row))return{applied:!1,doc:f.row};try{await h(o.patch)}catch(d){if(d instanceof ae&&d.kind==="occ"&&u)return;throw d}return{applied:!0,doc:te(t,e)?.row??null}},It=async(e,t,o,u)=>{const{fetchLimit:h,limit:f,orderKeys:d,predicate:l}=await ur(t,o,{canPushExists:Et?wn:void 0,existsPushMode:$t==="always"?"always":"auto",fetcher:yt,maxRelationKeys:mt,schema:s,tableName:e}),p=Et?io(u):Ke,R=X(l,p,je),E=sn(e,R,cn(d),h);return{limit:f,orderKeys:d,statement:E}},B={system:hn,async aggregate(e,t){const o=K(e,"aggregate");if(o)return L(e,O),o.aggregate(e,t);const u=s.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);if(qe(t.op),t.op==="count")return B.count(e,{baseWhere:t.baseWhere,relationBaseWhere:t.relationBaseWhere,restrictsCounts:t.restrictsCounts,where:t.where});if(!t.field)throw new y("INTERNAL",`aggregate(${e}, { op: "${t.op}" }): "field" is required for non-count reducers`);L(e,O);const h=Re(u.softDeleteMode,void 0),f=N(N(t.baseWhere,t.where),h),d=await Ce(f,e,t.relationBaseWhere),l=d!==f;if(u.aggregateIndexes&&!t.baseWhere&&!l){const _=Cn(u.aggregateIndexes,t.op,t.field,t.where);if(_){ze(e,_.index);const H=Ze(_.index.by??[],_.key),ne=Xe(e,_.index.name),Y=G(a,c`SELECT ${We} AS value, ${nt} AS count FROM ${c.identifier(ne)} WHERE ${Be} = ${H}`).toArray()[0];return et(t.op,Y)}}Vt(u,t.field,`aggregate(${e}, { op: "${t.op}", field: "${t.field}" })`);const p=X(d,fe),R=qe(t.op),E=he(t.field);let S=c`SELECT ${c.raw(R)}(${E}) AS value FROM ${c.identifier(e)}`;p&&(S=c`${S} WHERE ${p}`);const P=G(a,S).toArray()[0]?.value;return P??null},asId(e,t){const o=Jt(s,e,t);if(o===null)throw new y("BAD_REQUEST",`asId("${e}", …): "${t}" is not a valid id for table "${e}"`,{status:400});return o},async count(e,t){const o=K(e,"count");if(o)return L(e,O),o.count(e,t);const u=s.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);const h=vn(t);if(h.restrictsCounts)throw new tt(e);L(e,O);const f=Re(u.softDeleteMode,void 0),d=N(N(h.baseWhere,h.where),f),l=await Ce(d,e,h.relationBaseWhere),p=l!==d;if(u.aggregateIndexes&&!h.baseWhere&&!p){const m=In(u.aggregateIndexes,h.where);if(m){ze(e,m.index);const P=Ze(m.index.by??[],m.key),_=Xe(e,m.index.name),H=G(a,c`SELECT ${We} AS value FROM ${c.identifier(_)} WHERE ${Be} = ${P}`).toArray();return H[0]===void 0?0:H[0].value??0}}const R=X(l,fe);let E=c`SELECT COUNT(*) AS count FROM ${c.identifier(e)}`;return R&&(E=c`${E} WHERE ${R}`),G(a,E).one().count},async delete(e,t,o){const u=te(e,t);if(!u){const S=Se(t);S&&(I(void 0),await S.delete(e,t,o));return}const{docJson:h,row:f,tableName:d}=u,l=s.tables[d],p=o?.hard===!0,R=!p&&l?.softDeleteMode?l:void 0,E=R?.softDeleteMode?.field;if(!(E&&f[E]!==null&&f[E]!==void 0)){if(Z(d,"before","delete")&&await ee("before","delete",{id:e,op:"delete",previous:f,table:d}),await hr({deletedId:e,deletedReference:S=>f[S],findHolders:async(S,m,P)=>(await Ve(S).findMany(S,{includeDeleted:p,where:{[m]:P}})).page,onCascade:(S,m)=>Ve(S).delete(m,void 0,o),onRestrict:S=>{throw new ae(S,"restrict")},onSetNull:(S,m,P)=>Ve(S).patch(m,{[P]:null}),schema:s,tableName:d}),$e(d),Ee(d),R&&E){const S={[E]:Q()},m={...f,...k(d),...S,_id:e};st(R,S,m,se),Oe(a,d,jt(d),[le(m),e,h]),De(d,e,m,f),Me(d,e,void 0),be(d,f,m),me(d,e,f,void 0),D?.invalidate(d,e,v(d,f,m)),ye(d,e,"update",m),w({indexKeys:v(d,f,m),key:e,op:"update",row:m,table:d}),Z(d,"after","delete")&&await ee("after","delete",{id:e,op:"delete",previous:f,table:d}),await M({id:e,op:"delete",table:d});return}Oe(a,d,Hr(d),[e,h]),De(d,e,void 0),Me(d,e,void 0),be(d,f,void 0),me(d,e,f,void 0),D?.invalidate(d,e,v(d,f)),ye(d,e,"delete"),w({indexKeys:v(d,f),key:e,op:"delete",table:d}),Z(d,"after","delete")&&await ee("after","delete",{id:e,op:"delete",previous:f,table:d}),await M({id:e,op:"delete",table:d})}},async deleteAll(e,t){if(!s.tables[e])throw new y("INTERNAL",`unknown table: ${e}`);const o=Math.max(1,t?.chunkSize??dn),u=t?.hard===void 0?void 0:{hard:t.hard},h=ce(e)?void 0:e;let f=0;return await U(async()=>{for(;;){const l=(await B.findMany(e,{limit:o})).page.map(p=>String(p._id));if(l.length===0)break;for(const p of l)await B.delete(p,h,u),f+=1;if(l.length<o)break}}),{deleted:f}},async deleteMany(e,t,o){ue(e.length,t?.limit,"deleteMany");for(const u of e)await B.delete(u,o);return{deleted:e.length}},async deleteWhere(e,t,o){const f=(await(K(e,"deleteWhere")??B).findMany(e,{where:t})).page.map(d=>String(d._id));if(ue(f.length,o?.limit,"deleteWhere"),B.deleteMany===void 0)throw new y("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return B.deleteMany(f,o)},async findFirst(e,t={}){return(await B.findMany(e,{...t,limit:1,omitContinueCursor:!0})).page[0]??null},async findFirstOrThrow(e,t={}){const o=await B.findFirst(e,t);if(o===null)throw new Kn(`findFirstOrThrow: no "${e}" document matched`);return o},async findMany(e,t={}){const o=K(e,"findMany");if(o)return L(e,O),o.findMany(e,t);const u=s.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);const h=!t.where&&!t.baseWhere;h?L(e,O):L(e);const{limit:f,orderKeys:d,statement:l}=await It(e,u,t,L),p=we(a,l.text,...l.params).toArray();h&&!x&&C?.recordRead(p.length);const R=[];for(const P of p){const _=Te(P);_&&(R.push(_),!h&&typeof _._id=="string"&&L(e,_._id))}if(f===void 0)return t.with&&await Ut({groupedCounter:St,fetcher:Je,parents:R,...Ot(t),schema:s,tableName:e,with:t.with}),{continueCursor:null,isDone:!0,page:Ft(R,t.select,t.with)};const E=R.length>f,S=E?R.slice(0,f):R,m=S.at(-1);return t.with&&await Ut({fetcher:Je,groupedCounter:St,parents:S,...Ot(t),schema:s,tableName:e,with:t.with}),{continueCursor:E&&m&&t.omitContinueCursor!==!0?He(m,d):null,isDone:!E,page:Ft(S,t.select,t.with)}},async explain(e,t={}){const o=K(e,"explain");if(o)return o.explain(e,t);const u=s.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);const{statement:h}=await It(e,u,t,()=>{}),f=we(a,`EXPLAIN QUERY PLAN ${h.text}`,...h.params).toArray();return{params:h.params,plan:f.map(d=>String(d.detail)),sql:h.text}},async get(e,t){const o=te(e,t);if(!o){const u=Se(t);return u?u.get(e,t):null}return L(o.tableName,e),o.row},async lookupById(e,t){const o=te(e,t);return o?(L(o.tableName,e),{row:o.row,tableName:o.tableName}):null},async groupBy(e,t){const o=K(e,"groupBy");if(o)return L(e,O),o.groupBy(e,t);const u=s.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);L(e,O);const h=t.agg??{op:"count"};if(qe(h.op),h.op!=="count"&&!h.field)throw new y("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);const f=Re(u.softDeleteMode,void 0),d=N(N(t.baseWhere,t.where),f),l=await Ce(d,e,t.relationBaseWhere),p=l!==d;if(u.aggregateIndexes&&!t.baseWhere&&!p){const _=An(u.aggregateIndexes,h.op,h.field,t.by,t.where),H=_===void 0?0:Object.keys(_.partial).length,ne=_?.index.by?.length??0;if(_&&(H===0||H===ne)){ze(e,_.index);const Y=Xe(e,_.index.name),V=Object.keys(_.partial),de=[];if(V.length===(_.index.by??[]).length&&V.length>0){const ke=Ze(_.index.by??[],_.partial),Le=G(a,c`SELECT ${We} AS value, ${nt} AS count FROM ${c.identifier(Y)} WHERE ${Be} = ${ke}`).toArray();return Le.length>0&&de.push({key:{..._.partial},value:et(h.op,Le[0])}),de}const mn=G(a,c`SELECT ${Be} AS key, ${We} AS value, ${nt} AS count FROM ${c.identifier(Y)}`).toArray();for(const ke of mn){const Le=Rn(JSON.parse(ke.key));de.push({key:Le,value:et(h.op,ke)})}return de}}for(const _ of[...t.by,h.field]){if(_===void 0)continue;const H=_===h.field?`groupBy(${e}, { agg: { op: "${h.op}", field: "${_}" } })`:`groupBy(${e}, { by: [..."${_}"] })`;Vt(u,_,H)}const R=X(l,fe),E=t.by.map(_=>c`${he(_)} AS ${c.identifier(_)}`);if(h.op==="count")E.push(c`COUNT(*) AS value`);else{const{field:_}=h;if(_===void 0)throw new y("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);E.push(c`${c.raw(qe(h.op))}(${he(_)}) AS value`)}let S=c`SELECT ${c.join(E,c`, `)} FROM ${c.identifier(e)}`;R&&(S=c`${S} WHERE ${R}`),S=c`${S} GROUP BY ${c.join(t.by.map(_=>he(_)),c`, `)}`;const m=G(a,S).toArray(),P=[];for(const _ of m){const H={};for(const Y of t.by)H[Y]=Wn(u.shape[Y],_[Y]??null);const{value:ne}=_;P.push({key:H,value:ne==null?null:Number(ne)})}return P},async insert(e,t,o){const u=K(e,"insert");if(u)return gt(u,e,t,o,!0);const h=s.tables[e];if(!h)throw new y("INTERNAL",`unknown table: ${e}`);const f=zt(h,t,se);ot(h,f);let d;o?.clientId!==void 0?(Vr(o.clientId),d=o.clientId):o?.allowExplicitId&&typeof f._id=="string"?d=f._id:d=ge();const l=o?.allowExplicitId&&typeof f._creationTime=="number"?f._creationTime:Q(),p={...f,...k(e),_creationTime:l,_id:d};return Z(e,"before","insert")&&await ee("before","insert",{doc:{...p},id:d,op:"insert",table:e}),$e(e),Ee(e),dt(a,e,Ur(e),[d,l,le(p)]),Rt(e,d,p),Z(e,"after","insert")&&await ee("after","insert",{doc:p,id:d,op:"insert",table:e}),await M({doc:p,id:d,op:"insert",table:e}),d},async insertManyUnsafe(e,t,o){if(ue(t.length,o?.limit,"insertManyUnsafe"),t.length===0)return[];const u=K(e,"insert");if(u){const l=[];for(const p of t)I(p);for(const p of t){const R=await u.insert(e,p,{allowExplicitId:o?.allowExplicitId});w({key:R,op:"insert",row:{...p,_id:R},table:e}),l.push(R)}return l}const h=s.tables[e];if(!h)throw new y("INTERNAL",`unknown table: ${e}`);$e(e),Ee(e);const f=[];for(let l=0;l<t.length;l+=Pe)f.push(k(e));const d=t.map((l,p)=>{const R=zt(h,l,se),E=o?.allowExplicitId===!0&&typeof R._id=="string"?R._id:ge(),S=o?.allowExplicitId===!0&&typeof R._creationTime=="number"?R._creationTime:Q(),m={...R,...f[Math.floor(p/Pe)],_creationTime:S,_id:E};return{creationTime:S,document:m,id:E}});for(const l of d)I(l.document);for(let l=0;l<d.length;l+=Pe){const p=c.join(d.slice(l,l+Pe).map(E=>c`(${E.id}, ${E.creationTime}, ${le(E.document)})`),c`, `),R=rn("sqlite",c`INSERT INTO ${c.identifier(e)} (id, _creationTime, ${c.identifier(oe)}) VALUES ${p}`);dt(a,e,R.sql,R.params)}for(const{document:l,id:p}of d)Rt(e,p,l),await $({doc:l,id:p,op:"insert",table:e});return d.map(l=>l.id)},async insertMany(e,t,o){ue(t.length,o?.limit,"insertMany");const u=o?.skipDuplicates===!0,h=[],f=K(e,"insert");if(f)for(const l of t)I(l);const d=async l=>f?gt(f,e,l,void 0,!1):B.insert(e,l);for(const l of t)try{h.push(await d(l))}catch(p){if(u&&p instanceof ae&&p.kind==="unique")h.push(null);else throw p}return h},normalizeId(e,t){return Jt(s,e,t)},async patch(e,t,o,u){const h=te(e,o);if(!h){const S=Se(o);if(S){I(t),await S.patch(e,t,o,u);return}throw new y("NOT_FOUND",`document not found: ${e}`)}const{docJson:f,row:d,tableName:l}=h,p=s.tables[l];if(!p)throw new y("INTERNAL",`unknown table: ${l}`);if(L(l,e),Xt("patch",t),wt(l,e,t,d)){r?.({fields:Object.keys(Ue(t)),id:e,table:l});return}const R=Nn(p,t,d),E={...d,...Ue(R),...k(l),_id:e};st(p,R,E,se),Qn(u,d,E),ot(p,E,!0),Z(l,"before","update")&&await ee("before","update",{doc:{...E},id:e,op:"update",previous:d,table:l}),$e(l),Ee(l),Oe(a,l,jt(l),[le(E),e,f]),De(l,e,E,d),Me(l,e,E),be(l,d,E),me(l,e,d,E),D?.invalidate(l,e,v(l,d,E)),ye(l,e,"update",E),w({indexKeys:v(l,d,E),key:e,op:"update",row:E,table:l}),Z(l,"after","update")&&await ee("after","update",{doc:E,id:e,op:"update",previous:d,table:l}),await M({doc:E,id:e,op:"update",table:l})},async patchIf(e,t,o){const u=K(e,"patchIf");if(u){if(u.patchIf===void 0)throw new y("INTERNAL",`ctx.db.patchIf on global table '${e}' is unsupported: its backend has no conditional write`);return I(o.patch),u.patchIf(e,t,o)}if(!s.tables[e])throw new y("INTERNAL",`unknown table: ${e}`);for(let h=1;h<=Yt;h+=1){const f=await $n(e,t,o,h<Yt,d=>B.patch(t,d,e,{verify:o.verify}));if(f!==void 0)return f}throw new ae(`patchIf on "${e}" kept conflicting; the row changed on every attempt`,"occ")},async patchMany(e,t,o){ue(e.length,t?.limit,"patchMany");for(const u of e)await B.patch(u.id,u.patch,o);return{patched:e.length}},async patchWhere(e,t,o){const f=(await(K(e,"patchWhere")??B).findMany(e,{where:t.where})).page.map(d=>({id:String(d._id),patch:t.patch}));if(ue(f.length,o?.limit,"patchWhere"),B.patchMany===void 0)throw new y("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await B.patchMany(f,o),{patched:f.length}},async related(e,t){return dr(B,A,e,t)},relationEdges:A,relationWrites:T,query(e){const t=K(e,"query");return t?(L(e,O),t.query(e)):fn(a,s,e,J,o=>{o?j(o):L(e,O)},o=>{x||C?.recordRead(o)})},async rank(e,t,o){const u=K(e,"rank");if(u)return L(e,O),u.rank(e,t,o);J(e,t,"rank");const h=s.tables[e];if(!h)throw new y("INTERNAL",`unknown table: ${e}`);const f=h.rankIndexes?.find(V=>V.name===t);if(!f)throw new y("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(Tt(e,h,f),o.restrictsCounts)throw new tt(e);L(e,O),Ye(e,f);const d=typeof o.row=="string"?o.row:o.row._id;if(!d)return null;const l=qt(e,f.name),p=f.sortBy.map((V,de)=>Wt(de)),R=p.map(V=>Ie(V)).join(", "),E=G(a,c`SELECT ${c.identifier("__partition__")}, ${c.raw(R)} FROM ${c.identifier(l)} WHERE ${c.identifier("__id__")} = ${d}`).toArray(),[S]=E;if(S===void 0)return null;let m=S.__partition__;const P=N(o.baseWhere,o.where);rt(P,s,e,"rank");const _=er(f,P);if(_){const V=tr(f.partitionBy??[],_);if(V!==m)return null;m=V}const H=p.map(V=>S[V]),{before:ne,total:Y}=en(a,l,p,f.sortBy,m,H,d);return{position:ne+1,total:Y}},async rankBefore(e,t,o){if(ce(e))throw new y("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const u=s.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);const h=u.rankIndexes?.find(p=>p.name===t);if(!h)throw new y("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(o.restrictsCounts)throw new tt(e);L(e,O),Ye(e,h);const f=qt(e,h.name),d=h.sortBy.map((p,R)=>Wt(R)),l=h.sortBy.map((p,R)=>Ae(o.sortValues[R]??null));return en(a,f,d,h.sortBy,o.partitionKey,l,o.rowId)},async rankPage(e,t,o={}){rt(N(o.baseWhere,o.where),s,e,"rankPage");const u=K(e,"rankPage");if(u)return L(e,O),u.rankPage(e,t,o);J(e,t,"rank");const{continueCursor:h,hasMore:f,rows:d}=bt(At,e,t,o);return{continueCursor:h,isDone:!f,page:d.map(l=>l.doc)}},async rankPageRows(e,t,o={}){rt(N(o.baseWhere,o.where),s,e,"rankPage"),J(e,t,"rank");const{directions:u,hasMore:h,rows:f}=bt(At,e,t,o);return{directions:u,hasMore:h,rows:f}},async restore(e,t){const o=te(e,t);if(!o){const f=Se(t);if(f?.restore){await f.restore(e,t);return}throw new y("NOT_FOUND",`document not found: ${e}`)}const u=s.tables[o.tableName]?.softDeleteMode?.field;if(!u)throw new y("INTERNAL",`ctx.db.restore: table "${o.tableName}" is not a .softDelete() table`);const h=o.row[u]!==null&&o.row[u]!==void 0;await B.patch(e,{[u]:null},t),h&&me(o.tableName,e,void 0,o.row)},async replace(e,t,o,u){const h=te(e,o);if(!h){const P=Se(o);if(P){I(t),await P.replace(e,t,o,u);return}throw new y("NOT_FOUND",`document not found: ${e}`)}const{docJson:f,row:d,tableName:l}=h,p=s.tables[l];if(!p)throw new y("INTERNAL",`unknown table: ${l}`);Xt("replace",t);const R=u?.allowExplicitId&&typeof t._creationTime=="number"?t._creationTime:void 0,E=typeof d._creationTime=="number"?d._creationTime:void 0,S=R??E??Q(),m={...t,...k(l),_creationTime:S,_id:e};st(p,t,m,se),ot(p,m),Z(l,"before","update")&&await ee("before","update",{doc:{...m},id:e,op:"update",previous:d,table:l}),$e(l),Ee(l),Oe(a,l,Or(l),[S,le(m),e,f]),De(l,e,m,d),Me(l,e,m),be(l,d,m),me(l,e,d,m),D?.invalidate(l,e,v(l,d,m)),ye(l,e,"update",m),w({indexKeys:v(l,d,m),key:e,op:"update",row:m,table:l}),Z(l,"after","update")&&await ee("after","update",{doc:m,id:e,op:"update",previous:d,table:l}),await M({doc:m,id:e,op:"update",table:l})},async wipeShard(e){const t=new Set(e?.exclude),o=e?.tables,u=Object.entries(s.tables).filter(([l,p])=>t.has(l)||o!==void 0&&!o.includes(l)?!1:p.shardMode?.kind!=="global").map(([l])=>l);if(o!==void 0){for(const l of o)if(!s.tables[l])throw new y("INTERNAL",`wipeShard: unknown table: ${l}`)}const h={};let f=0;const{deleteAll:d}=B;if(d===void 0)throw new y("INTERNAL","wipeShard: this writer has no deleteAll");for(const l of u){const p=await d(l,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});h[l]=p.deleted,f+=p.deleted}return{deleted:f,tables:h}}},En={db:B,scheduler:ie};return n.enforceRls===!0?pr(B,s,(e,t)=>te(e,t)?.tableName,(e,t)=>pn(e,t),A):B};export{si as CDC_LOG_TABLE,Ci as IDEMPOTENCY_TABLE,so as NotUniqueError,Ti as advanceClientWatermark,ci as applyCdcChanges,Xt as assertNoExplicitUndefined,Vr as assertValidClientId,ni as backfillAggregateIndexes,ri as backfillRankIndexes,oi as backfillSearchIndexes,ai as bumpCdcEpoch,di as cdcCanVouchFor,li as cdcForkedError,ui as cdcSeqLeavingRows,fi as cdcTouchesTables,hi as cdcTrimmedError,wi as compactCdcDocs,Zo as createShardCtxDb,pi as cursorBelowRetainedFloor,vi as migrateClientWatermark,gi as minCdcReplayableSeq,yi as minCdcSeq,Jt as normalizeIdStructurally,$i as readCdcChangeKeys,Ei as readCdcChanges,mi as readCdcCursor,Si as readCdcEpoch,Ai as readClientWatermark,xi as readIdempotent,ki as runShardMigrations,Fi as selectShapeMembers,qi as selectShapeRows,Ue as stripReservedPatchFields,_i as trimCdcChanges,bi as trimIdempotent,Mi as writeIdempotent};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as R}from"@lunora/errors";import{findRelated as m}from"./RELATED_DEFAULT_LIMIT-Me5elP-K.mjs";const M=Symbol.for("lunora.ctxdb.rls-unwrap");class S extends R{table;constructor(n){super("RLS_REQUIRED",`ctx.db access to "${n}" 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=n}}const E=o=>Object.entries(o.tables).filter(([,n])=>n.shardMode?.kind!=="global").map(([n])=>n),b=(o,n,c)=>{const d=n?.tables,u=new Set(n?.exclude);for(const r of o)(d===void 0||d.includes(r))&&!u.has(r)&&c(r)},y={aggregate:"loop-gated",asId:"ungated",assertPatchAllowed:"id-gated",cdcChangedTables:"ungated",count:"loop-gated",delete:"id-gated",deleteAll:"loop-gated",deleteMany:"id-gated",deleteWhere:"inline-table-gated",explain:"loop-gated",findFirst:"loop-gated",findFirstOrThrow:"loop-gated",findMany:"loop-gated",get:"id-gated",groupBy:"loop-gated",insert:"loop-gated",insertMany:"loop-gated",insertManyUnsafe:"loop-gated",lookupById:"id-gated",normalizeId:"ungated",patch:"id-gated",patchIf:"loop-gated",patchMany:"id-gated",patchWhere:"inline-table-gated",query:"loop-gated",rank:"loop-gated",rankBefore:"loop-gated",rankPage:"loop-gated",rankPageRows:"loop-gated",related:"rebound",relationEdges:"ungated",relationWrites:"ungated",replace:"id-gated",restore:"id-gated",system:"ungated",wipeShard:"sweep-gated"},W=Object.entries(y).filter(([,o])=>o==="loop-gated").map(([o])=>o),I={related:(o,n)=>(...c)=>{const[d,u]=c;return m(o,n,d,u)}},O=Object.entries(y).filter(([,o])=>o==="rebound").map(([o])=>o),k=(o,n,c)=>{for(const d of O)typeof n[d]=="function"&&(o[d]=I[d](o,c))},P=(o,n,c,d,u=[])=>{if(n.rlsMode!=="required")return o;const r=o,p=e=>{const t=n.tables[e];return t!==void 0&&t.isPublic!==!0},i=e=>{if(p(e))throw new S(e)},l=async(e,t)=>{if(t!==void 0){i(t);return}const a=await c(e);a!==void 0&&i(a)},f=async(e,t)=>{if(t!==void 0){i(t);return}if(!d){for(const s of e)await l(s,t);return}const a=await d([...new Set(e)],t);for(const s of e){const h=a.get(s);h!==void 0&&i(h)}},g={...o,delete:async(e,t,a)=>(await l(e,t),r.delete(e,t,a)),deleteMany:async(e,t,a)=>(await f(e,a),r.deleteMany(e,t,a)),deleteWhere:r.deleteWhere?async(e,t,a)=>(i(e),await r.deleteWhere?.(e,t,a)):void 0,get:async(e,t)=>(await l(e,t),r.get(e,t)),lookupById:async(e,t)=>(await l(e,t),r.lookupById?.(e,t)??null),patch:async(e,t,a,s)=>(await l(e,a),r.patch(e,t,a,s)),patchMany:async(e,t,a)=>(await f(e.map(s=>s.id),a),r.patchMany(e,t,a)),assertPatchAllowed:async(e,t)=>(await l(e,t),r.assertPatchAllowed?.(e,t)),patchWhere:r.patchWhere?async(e,t,a)=>(i(e),await r.patchWhere?.(e,t,a)):void 0,replace:async(e,t,a,s)=>(await l(e,a),r.replace(e,t,a,s)),restore:async(e,t)=>(await l(e,t),r.restore?.(e,t))},w=r;for(const e of W){const t=w[e];typeof t=="function"&&(g[e]=(a,...s)=>(i(a),t.call(r,a,...s)))}if(k(g,r,u),r.wipeShard){const{wipeShard:e}=r;g.wipeShard=t=>(b(E(n),t,i),e.call(r,t))}return Object.defineProperty(g,M,{configurable:!0,enumerable:!1,value:o,writable:!1}),g};export{W as LOOP_GATED_METHODS,M as RLS_UNWRAP_SYMBOL,S as RlsRequiredError,y as WRITER_METHOD_GATING,P as guardWriter};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as f}from"@lunora/errors";import{sql as e}from"drizzle-orm";import{MySqlDialect as u}from"drizzle-orm/mysql-core";import{PgDialect as S}from"drizzle-orm/pg-core";import{SQLiteSyncDialect as p}from"drizzle-orm/sqlite-core";const d=new S,h=new u,m=new p,L={mysql:h,postgres:d,sqlite:m},i={boundParams:100,compoundSelect:5,likePattern:50,sqlTextLength:1e5},E=i.boundParams/2,$=t=>t===null||typeof t=="boolean"?!0:typeof t=="number"?Number.isFinite(t):typeof t=="string"&&t.isWellFormed(),g=t=>{const n=[];for(const r of t){if(!(r instanceof Uint8Array))return;n.push(Array.from(r,o=>o.toString(16).padStart(2,"0")).join(""))}return JSON.stringify(n)},D=(t,n)=>{const{params:r,sql:o}=L[t].sqlToQuery(n);return{params:r,sql:o}},y=t=>e`${t}`,w=t=>{if(t.length===0)throw new Error("unionAll: expected at least one branch");let n=[...t];for(;n.length>i.compoundSelect;){const r=[];for(let o=0;o<n.length;o+=i.compoundSelect){const s=e.join(n.slice(o,o+i.compoundSelect),e` UNION ALL `);r.push(e`SELECT * FROM (${s}) ${e.identifier("__u__")}`)}n=r}return e.join(n,e` UNION ALL `)},O=(t,n,r,o=E)=>{const s=r?e` NOT IN `:e` IN `,a=n.every(l=>$(l)),c=n.length>o&&!a?g(n):void 0;if(c!==void 0)return e`${t}${s}(SELECT unhex(${e.identifier("value")}) FROM json_each(${c}))`;if(n.length>o&&!a)throw new f("BAD_REQUEST",`an "in" list of ${String(n.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(n.length)} placeholders exceed SQLite's per-statement cap of 100 on Durable Objects and D1. Narrow the list to ${String(o)} values or fewer.`);return n.length<=o?e`${t}${s}(${e.join(n.map(l=>y(l)),e`, `)})`:e`${t}${s}(SELECT ${e.identifier("value")} FROM json_each(${JSON.stringify(n)}))`};export{i as WORKERD_SQLITE_LIMITS,g as bytesAsHexJson,$ as isJsonSafe,y as param,D as renderSql,O as sqliteInList,w as unionAll};
|