@lunora/shard-engine 1.0.0-alpha.20 → 1.0.0-alpha.200
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/LICENSE.md +201 -104
- package/README.md +1 -1
- package/dist/conformance/index.mjs +1 -1
- package/dist/index.d.mts +1042 -227
- package/dist/index.d.ts +1042 -227
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/ADMIN_FUNCTIONS-CSz3ZK2d.mjs +14 -0
- package/dist/packem_shared/ADMIN_TOKEN_TABLE-DfQ5osdI.mjs +1 -0
- package/dist/packem_shared/ADMIN_WILDCARD-BUrgWQ3-.mjs +1 -0
- package/dist/packem_shared/AGGREGATE_SQL_FUNCTION-C_ZipS9R.mjs +1 -0
- package/dist/packem_shared/AGG_COUNT-dVi3FAjZ.mjs +1 -0
- package/dist/packem_shared/AUDIT_LOG_TABLE-BFJ65SRS.mjs +8 -0
- package/dist/packem_shared/BIGINT_KEY_DIGITS-DE6yshOt.mjs +1 -0
- package/dist/packem_shared/CDC_LOG_TABLE-BFGgqai8.mjs +18 -0
- package/dist/packem_shared/CLIENT_WATERMARK_TABLE-De7z_OHV.mjs +7 -0
- package/dist/packem_shared/COMMIT_SEQ_FIELD-Da1DjGqo.mjs +4 -0
- package/dist/packem_shared/CURSOR_PREFIX-rOdoinP8.mjs +1 -0
- package/dist/packem_shared/CompanionMemo-BXU5vfak.mjs +1 -0
- package/dist/packem_shared/CountRlsUnsupportedError-BvsDqfO2.mjs +1 -0
- package/dist/packem_shared/DATA_MIGRATION_STATE_TABLE-CPWZjliE.mjs +31 -0
- package/dist/packem_shared/DEFAULT_MAX_RELATION_KEYS-B_BOc9w_.mjs +1 -0
- package/dist/packem_shared/DEFAULT_MAX_RELAYS-BZLpaaq1.mjs +8 -0
- package/dist/packem_shared/DEFAULT_PROMOTION_THRESHOLDS-VU44O5kq.mjs +1 -0
- package/dist/packem_shared/DEFAULT_TRANSACTION_LIMITS-D7p7Ys0M.mjs +1 -0
- package/dist/packem_shared/DELTA_PLACEHOLDER_TABLE-CHxtV9xh.mjs +1 -0
- package/dist/packem_shared/DurableStreamRunner-MMlV5qKQ.mjs +1 -0
- package/dist/packem_shared/GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs +1 -0
- package/dist/packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-Bb6-aZuH.mjs +7 -0
- package/dist/packem_shared/GlobalPollTick-BNK4o-XT.mjs +1 -0
- package/dist/packem_shared/IDEMPOTENCY_TABLE-COrgeP3O.mjs +7 -0
- package/dist/packem_shared/MAIL_RETENTION-DMolrLYt.mjs +18 -0
- package/dist/packem_shared/MAX_SQL_ROWS-B4WlVI-e.mjs +5 -0
- package/dist/packem_shared/MAX_TOKEN_LENGTH-iFEGEcDL-DBPC6ZWl.mjs +1 -0
- package/dist/packem_shared/NotUniqueError-T-8lMmWk.mjs +1 -0
- package/dist/packem_shared/QUEUE_TABLE-C-goXtGd.mjs +17 -0
- package/dist/packem_shared/RANK_TIEBREAK-D3ye2GsL.mjs +1 -0
- package/dist/packem_shared/REACTOR_STATE_TABLE-D2Mn204f.mjs +28 -0
- package/dist/packem_shared/RELATED_DEFAULT_LIMIT-CAh3WUMn.mjs +1 -0
- package/dist/packem_shared/RELATION_EXISTS_KEY-wxgj6rSL.mjs +1 -0
- package/dist/packem_shared/RELAY_SIGNATURE_HEADER-CAfC4tqg.mjs +1 -0
- package/dist/packem_shared/REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs +1 -0
- package/dist/packem_shared/RLS_UNWRAP_SYMBOL-CZIpCjzt.mjs +1 -0
- package/dist/packem_shared/ReactiveCache-BG9z3FE9.mjs +1 -0
- package/dist/packem_shared/SCAN_DEP-B4Uu4g7l.mjs +1 -0
- package/dist/packem_shared/SCHEDULE_OUTBOX_TABLE-iyyiSjsO.mjs +18 -0
- package/dist/packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-CEwFjj-O.mjs +6 -0
- package/dist/packem_shared/SEARCH_STATE_TABLE-D7w8mRsm.mjs +1 -0
- package/dist/packem_shared/SHAPE_POKE_CURSOR_TABLE-BGvY3sFI.mjs +8 -0
- package/dist/packem_shared/ShapeDiffCache-iNO-hUiy.mjs +1 -0
- package/dist/packem_shared/ShardRunner-CrveaPId.mjs +1 -0
- package/dist/packem_shared/VECTOR_BACKFILL_MAX_PAGES-DJ6iD61G.mjs +1 -0
- package/dist/packem_shared/WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs +1 -0
- package/dist/packem_shared/accepts-null-D1zmJbyR.mjs +1 -0
- package/dist/packem_shared/adminTokenExists-CQ0qedmu.mjs +8 -0
- package/dist/packem_shared/aggregateTableName-B_CtIQCS.mjs +1 -0
- package/dist/packem_shared/appendStreamChunk-BZYgGE9Y.mjs +17 -0
- package/dist/packem_shared/applyInsertDefaults-BJ4dP3OL.mjs +1 -0
- package/dist/packem_shared/archiveCdcSegment-Cr8oGLfB.mjs +4 -0
- package/dist/packem_shared/{armRestore-BNzdvQ_o.mjs → armRestore-Bu1_8SUa.mjs} +1 -1
- package/dist/packem_shared/assertPatchAllowed-CA_H466g.mjs +1 -0
- package/dist/packem_shared/backfillAggregateIndexes-BwCpPW7h.mjs +1 -0
- package/dist/packem_shared/buildIndexRange-BTChxh3k.mjs +1 -0
- package/dist/packem_shared/buildPokeFrames-WR-hp0mX.mjs +1 -0
- package/dist/packem_shared/buildReprojectionMigration-B8aEpETD.mjs +1 -0
- package/dist/packem_shared/buildSettings-CFkvTaHx.mjs +1 -0
- package/dist/packem_shared/buildShapeDiff-CdLJTijm.mjs +1 -0
- package/dist/packem_shared/clearMemoryTables-aMRERF0w.mjs +1 -0
- package/dist/packem_shared/compileWhereSql-TgKZIvWM.mjs +1 -0
- package/dist/packem_shared/computeRankPage-B6umzbg4.mjs +1 -0
- package/dist/packem_shared/constant-time-equal-BRh9yUCr.mjs +1 -0
- package/dist/packem_shared/createCompanionSync-DO92CQek.mjs +1 -0
- package/dist/packem_shared/createReplicaLink-DtqXBi-0.mjs +7 -0
- package/dist/packem_shared/createSystemReader-BSCxr8Qs.mjs +1 -0
- package/dist/packem_shared/ctx-db-relay-shapes-DBobAek2.mjs +17 -0
- package/dist/packem_shared/ctx-db-search-state-CPKPy8N6.mjs +1 -0
- package/dist/packem_shared/defineEngineContractSuite-BToZWQxH.mjs +1 -0
- package/dist/packem_shared/describeRelationWrites-omar6-u9.mjs +1 -0
- package/dist/packem_shared/diffExternalSource-B0FZlDoL.mjs +1 -0
- package/dist/packem_shared/do-sql-105TONaE.mjs +1 -0
- package/dist/packem_shared/effective-kind-BmG_zCAy.mjs +1 -0
- package/dist/packem_shared/envOptionalPositiveInt-D2pY-c64.mjs +1 -0
- package/dist/packem_shared/estimate-bytes-C-C35VXL.mjs +1 -0
- package/dist/packem_shared/exportShardRows-CZh4wrvI.mjs +1 -0
- package/dist/packem_shared/fts-companion-CE3EmIjk.mjs +1 -0
- package/dist/packem_shared/ftsCompanionDdl-B0bFCy6d.mjs +1 -0
- package/dist/packem_shared/hasTrigger-CjlwI4le.mjs +1 -0
- package/dist/packem_shared/isInternalTableName-BoljO2tP.mjs +1 -0
- package/dist/packem_shared/isPushableWhere-BeYAOjUb.mjs +1 -0
- package/dist/packem_shared/isSoftDeleted-BBWKE0Sm.mjs +9 -0
- package/dist/packem_shared/isTtlExpired-DNxmZA6e.mjs +1 -0
- package/dist/packem_shared/json-field-path-DeJW4U9z.mjs +1 -0
- package/dist/packem_shared/liftSourceId-CA3ENhXj.mjs +1 -0
- package/dist/packem_shared/materializeExternalRows-CHPRx8fu.mjs +1 -0
- package/dist/packem_shared/mergeChangedKeys-DPKhen6e.mjs +1 -0
- package/dist/packem_shared/relation-operators-BEg-CvCH.mjs +1 -0
- package/dist/packem_shared/relay-CKEdfUjH.mjs +1 -0
- package/dist/packem_shared/runDrizzle-RC09zZrh.mjs +1 -0
- package/dist/packem_shared/runShardMigrations-Bc7PsQhM.mjs +5 -0
- package/dist/packem_shared/runSocketPool-CZJ2X9cF.mjs +1 -0
- package/dist/packem_shared/selectShapeMembers-Dqx_m7BF.mjs +1 -0
- package/dist/packem_shared/serializeSqlValue-DeoBMpZ2.mjs +1 -0
- package/dist/packem_shared/stubByName-DQSivmvb.mjs +1 -0
- package/dist/packem_shared/where-sql-BjY4rnqb.mjs +1 -0
- package/package.json +6 -5
- package/dist/packem_shared/ADMIN_FUNCTIONS-OnYxyTXW.mjs +0 -1
- package/dist/packem_shared/AGGREGATE_SQL_FUNCTION-CTo0-9iZ.mjs +0 -1
- package/dist/packem_shared/AGG_COUNT-CqQLWpb4.mjs +0 -1
- package/dist/packem_shared/AUDIT_LOG_TABLE-C6nwXFPd.mjs +0 -8
- package/dist/packem_shared/CDC_LOG_TABLE-ZqcflEen.mjs +0 -8
- package/dist/packem_shared/CLIENT_WATERMARK_TABLE-CzApRlyv.mjs +0 -7
- package/dist/packem_shared/CountRlsUnsupportedError-8BqPYQoP.mjs +0 -1
- package/dist/packem_shared/DATA_MIGRATION_STATE_TABLE-BrpAGtXf.mjs +0 -31
- package/dist/packem_shared/DEFAULT_MAX_RELATION_KEYS-sPcXaWFW.mjs +0 -1
- package/dist/packem_shared/DEFAULT_MAX_RELAYS-CPBmX1FO.mjs +0 -1
- package/dist/packem_shared/DEFAULT_PROMOTION_THRESHOLDS-B2rUe1bg.mjs +0 -1
- package/dist/packem_shared/DEFAULT_TRANSACTION_LIMITS-q7ouI3i0.mjs +0 -1
- package/dist/packem_shared/GEO_DEFAULT_PRECISION-DyI5zggj.mjs +0 -1
- package/dist/packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-soMJDSBs.mjs +0 -7
- package/dist/packem_shared/IDEMPOTENCY_TABLE-Bvu9JkiL.mjs +0 -7
- package/dist/packem_shared/MAIL_RETENTION-BefR9Sei.mjs +0 -18
- package/dist/packem_shared/MAX_SQL_ROWS-nMwkxv5f.mjs +0 -2
- package/dist/packem_shared/NotUniqueError-BItFDsAw.mjs +0 -1
- package/dist/packem_shared/QUEUE_TABLE-DgBqWrXX.mjs +0 -17
- package/dist/packem_shared/RANK_TIEBREAK-DYDRmLKH.mjs +0 -1
- package/dist/packem_shared/RELATION_EXISTS_KEY-BaqSIFU1.mjs +0 -1
- package/dist/packem_shared/REPROJECTION_MIGRATION_PREFIX-D2dltRFC.mjs +0 -1
- package/dist/packem_shared/RLS_UNWRAP_SYMBOL-DcqORh2s.mjs +0 -1
- package/dist/packem_shared/ReactiveCache-Cu8IfE1M.mjs +0 -1
- package/dist/packem_shared/SCAN_DEP-D_yR9EeV.mjs +0 -1
- package/dist/packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-BEU0CuW5.mjs +0 -6
- package/dist/packem_shared/SEARCH_STATE_TABLE-BZ_fxI5l.mjs +0 -1
- package/dist/packem_shared/ShardRunner-DIqVdWtk.mjs +0 -1
- package/dist/packem_shared/aggregateTableName-DV-K7ft2.mjs +0 -1
- package/dist/packem_shared/applyOnDelete-BB6tr2G0.mjs +0 -1
- package/dist/packem_shared/applySelect-i17LYhIU.mjs +0 -1
- package/dist/packem_shared/awaitWsDrain-Bp2jKzIb.mjs +0 -1
- package/dist/packem_shared/backfillAggregateIndexes-tK0jrl43.mjs +0 -1
- package/dist/packem_shared/base64-fKomMf5D.mjs +0 -1
- package/dist/packem_shared/buildIndexRange-DFsdtPjD.mjs +0 -1
- package/dist/packem_shared/buildPokeFrames-CqxaN8_H.mjs +0 -1
- package/dist/packem_shared/buildReprojectionMigration-Ctl4r84d.mjs +0 -1
- package/dist/packem_shared/buildSettings-COIJsw7a.mjs +0 -1
- package/dist/packem_shared/compileWhereSql-B4rPariq.mjs +0 -1
- package/dist/packem_shared/computeRankPage-CRFgJbuz.mjs +0 -1
- package/dist/packem_shared/createCompanionSync-Gp-AesYj.mjs +0 -1
- package/dist/packem_shared/createReadFootprint-DIrrxRTE.mjs +0 -1
- package/dist/packem_shared/createSystemReader-DcDcrtM3.mjs +0 -1
- package/dist/packem_shared/ctx-db-companions-CAJOSdN-.mjs +0 -1
- package/dist/packem_shared/defineEngineContractSuite-CZccUN4c.mjs +0 -1
- package/dist/packem_shared/diffExternalSource-DMpkJta1.mjs +0 -1
- package/dist/packem_shared/do-sql-1Yi1_Yq0.mjs +0 -1
- package/dist/packem_shared/estimate-bytes-Drp8rhPs.mjs +0 -1
- package/dist/packem_shared/exportShardRows-Bbi_JGfn.mjs +0 -1
- package/dist/packem_shared/hasTrigger-CbkOHExZ.mjs +0 -1
- package/dist/packem_shared/isSoftDeleted-Bo-y3DOe.mjs +0 -9
- package/dist/packem_shared/liftSourceId-DApAbu7Q.mjs +0 -1
- package/dist/packem_shared/materializeExternalRows-DcCENzpV.mjs +0 -1
- package/dist/packem_shared/mergeChangedKeys-BXtUgIPW.mjs +0 -1
- package/dist/packem_shared/param-B5lF5Jd9.mjs +0 -1
- package/dist/packem_shared/runDrizzle-B6rnz3so.mjs +0 -1
- package/dist/packem_shared/runShardMigrations-n2dKcH5E.mjs +0 -5
- package/dist/packem_shared/runSocketPool-DPQLVyWF.mjs +0 -1
- package/dist/packem_shared/selectExpiredIds-C6nQK7E2.mjs +0 -1
- package/dist/packem_shared/selectShapeMemberIds-BdBcbrUP.mjs +0 -1
- package/dist/packem_shared/serializeSqlValue-BR4UOWoP.mjs +0 -1
- package/dist/packem_shared/sql-projection-jfoe331H.mjs +0 -1
- package/dist/packem_shared/stableStringify-BjLh4gvA.mjs +0 -1
- package/dist/packem_shared/stableWireKey-l3cjIt-9.mjs +0 -1
- package/dist/packem_shared/wire-codec-Dsy70M3Q.mjs +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as $}from"@lunora/errors";import{q as $t}from"./MAX_TOKEN_LENGTH-iFEGEcDL-DBPC6ZWl.mjs";import{S as qn,l as qe,s as Pn}from"./fts-companion-CE3EmIjk.mjs";import{decodeWire as Un,stableWireKey as Pt}from"@lunora/wire";import{sql as a}from"drizzle-orm";import{throwingScheduler as On,aggregateSqlFunction as Pe,normalizeCountArgument as Gn}from"./AGGREGATE_SQL_FUNCTION-C_ZipS9R.mjs";import{aggregateTableName as rt,encodeAggregateKey as it,readAggregateValue as st}from"./aggregateTableName-B_CtIQCS.mjs";import{mergeWhere as Q,CountRlsUnsupportedError as ct,selectIndexForGroupBy as jn,selectIndexForCount as Hn,selectIndexForAggregate as Kn}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{backfillSearchIndexesForTable as Nn,searchIndexCoversTable as Qn}from"./backfillAggregateIndexes-BwCpPW7h.mjs";import{backfillAggregateIndexes as ji,backfillRankIndexes as Hi,backfillSearchIndexes as Ki}from"./backfillAggregateIndexes-BwCpPW7h.mjs";import{appendCdcChange as Vn,readCdcDocAtOrBefore as Jn}from"./CDC_LOG_TABLE-BFGgqai8.mjs";import{CDC_LOG_TABLE as Qi,applyCdcChanges as Vi,bumpCdcEpoch as Ji,cdcCanVouchFor as zi,cdcForkedError as Yi,cdcSeqLeavingRows as Xi,cdcTouchesTables as Zi,cdcTrimmedError as es,compactCdcDocs as ts,cursorBelowRetainedFloor as ns,minCdcReplayableSeq as os,minCdcSeq as rs,readCdcChangeKeys as is,readCdcChanges as ss,readCdcCursor as cs,readCdcEpoch as as,trimCdcChanges as ds}from"./CDC_LOG_TABLE-BFGgqai8.mjs";import{allocateCommitSeq as zn,COMMIT_SEQ_FIELD as Yn}from"./COMMIT_SEQ_FIELD-Da1DjGqo.mjs";import{createCompanionSync as Xn}from"./createCompanionSync-DO92CQek.mjs";import{isMemoryTable as Ut}from"./clearMemoryTables-aMRERF0w.mjs";import{computeRankPage as Ot}from"./computeRankPage-B6umzbg4.mjs";import{SCAN_DEP as G,PRIMARY_READ as Zn}from"./SCAN_DEP-B4Uu4g7l.mjs";import{runSql as he,runDrizzle as K}from"./runDrizzle-RC09zZrh.mjs";import{p as eo,j as ht,D as ie,r as xe,W as to,k as le,b as Ue,A as at,a as Oe,m as ue,e as fe,s as no,t as oo,u as ro,i as io,q as Gt,h as pn,g as so}from"./do-sql-105TONaE.mjs";import{renderSql as gn,unionAll as yn,WORKERD_SQLITE_LIMITS as mn}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{a as co,u as ao}from"./estimate-bytes-C-C35VXL.mjs";import{coveringGeohashes as lo,boundingBoxGeohashes as uo,haversineMeters as fo,pointInBoundingBox as ho}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{NotFoundError as wo}from"./NotFoundError-BhF7FeFr.mjs";import{resolvePatch as po,assertPatchAllowed as go,operatorFields as yo,readPatchField as jt}from"./assertPatchAllowed-CA_H466g.mjs";import{tiebreakDirectionFor as mo,encodeCursor as wt,nullsOrderSuffix as Eo,normalizeOrderKeys as Ht,uniqueIndexFields as $o,buildSeekWhere as Ro,decodeCursor as Kt,buildSeekBeforeWhere as So,softDeleteScope as Ae,applySelect as En}from"./CURSOR_PREFIX-rOdoinP8.mjs";import{rankTableName as Nt,sortColumnName as Qt,resolveRankPartition as vo,encodePartitionKey as _o,RANK_TIEBREAK as To,rankPivotConditionSql as Ao}from"./RANK_TIEBREAK-D3ye2GsL.mjs";import{UNVOUCHABLE_DEP as Vt}from"./ADMIN_WILDCARD-BUrgWQ3-.mjs";import{idIndexKey as Io,withUnknownIndexKeys as xo,indexKeysForRow as bo,buildIndexRange as Co}from"./buildIndexRange-BTChxh3k.mjs";import{r as Qe,j as be,c as Z,t as ze,i as Jt}from"./where-sql-BjY4rnqb.mjs";import{serializeSqlValue as Ce}from"./serializeSqlValue-DeoBMpZ2.mjs";import{quoteIdentifier as Me}from"./quoteIdentifier-CObIFRhb.mjs";import{whereOfFilter as Mo,isPushableWhere as Do}from"./isPushableWhere-BeYAOjUb.mjs";import{deriveRelationEdges as ko,findRelated as Lo}from"./RELATED_DEFAULT_LIMIT-CAh3WUMn.mjs";import{assertFlatPredicate as dt,findManyPage as Fo,resolveRelationPredicates as Bo,composeReadPredicate as Wo}from"./DEFAULT_MAX_RELATION_KEYS-B_BOc9w_.mjs";import{describeRelationWrites as qo}from"./describeRelationWrites-omar6-u9.mjs";import{runRowValidators as Ge,transformOnlyDefinition as Po,applyInsertDefaults as pt,resolveWith as Uo,relationHooks as Oo,applyOnDelete as Go,fanOutScalarCounts as jo}from"./applyInsertDefaults-BJ4dP3OL.mjs";import{guardWriter as Ho}from"./RLS_UNWRAP_SYMBOL-CZIpCjzt.mjs";import{mayHoldProjectedValue as Ko}from"./BIGINT_KEY_DIGITS-DE6yshOt.mjs";import{createSystemReader as No}from"./createSystemReader-BSCxr8Qs.mjs";import{ConflictError as se}from"./ConflictError-C8GtJmjS.mjs";import{hasTrigger as zt,runTriggers as Qo}from"./hasTrigger-CjlwI4le.mjs";import{advanceClientWatermark as us,migrateClientWatermark as fs,readClientWatermark as hs}from"./CLIENT_WATERMARK_TABLE-De7z_OHV.mjs";import{IDEMPOTENCY_TABLE as ps,readIdempotent as gs,trimIdempotent as ys,writeIdempotent as ms}from"./IDEMPOTENCY_TABLE-COrgeP3O.mjs";import{runShardMigrations as $s}from"./runShardMigrations-Bc7PsQhM.mjs";import{selectShapeMembers as Ss,selectShapeRows as vs}from"./selectShapeMembers-Dqx_m7BF.mjs";const Vo=n=>{const r=atob(n),o=Uint8Array.from(r,s=>s.codePointAt(0)??0);return new TextDecoder().decode(o)},Jo=()=>new $("INVALID_CURSOR","invalid cursor"),Yt=16,Xt=8,z=1024,Rt=(n,r)=>r.query(n),zo=(n,r)=>{if(n.length===0)return 0;let o=0;for(const[s,c]of r.entries()){const u=s===r.length-1;let g=0;for(const E of n)(u?E.startsWith(c):E===c)&&(g+=1);if(g===0)return 0;o+=g}return o},Yo=(n,r)=>{if(!r)return{exact:!0,lower:n,upper:n};const o=[...n].at(-1)??"",s=(o.codePointAt(0)??0)+1;if(s>=55296&&s<=57343||s>1114111)return{exact:!0,lower:n,upper:n};const c=n.slice(0,n.length-o.length);return{exact:!1,lower:n,upper:c+String.fromCodePoint(s)}},Xo=(n,r,o)=>{const s={eq:(c,u)=>{if(!n.definition.filterFields?.includes(c))throw new $("INTERNAL",`field "${c}" is not a filter field of search index "${n.indexName}" on table "${r}"`);if(n.filters.length>=Xt)throw new $("BAD_REQUEST",`search index "${n.indexName}" on table "${r}": at most ${String(Xt)} .eq() filters are supported per search query`);return n.filters.push({field:c,value:u}),s},search:(c,u)=>{const g=n;if(c!==g.definition.field)throw new $("INTERNAL",`search index "${g.indexName}" on table "${r}" indexes "${g.definition.field}", not "${c}"`);const E=Rt(u,o).length;if(E>Yt)throw new $("BAD_REQUEST",`search index "${g.indexName}" on table "${r}": at most ${String(Yt)} search terms are supported (got ${String(E)})`);return g.field=c,g.query=u,g.hasQuery=!0,s}};return s},Zo=n=>{if(n.length>z)throw new $("BAD_REQUEST",`more than ${String(z)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},er=n=>Math.min(n.offset+n.numItems+1,z),tr=n=>btoa(`search:${String(n)}`),nr=n=>{let r;try{r=Vo(n)}catch{return}if(!r.startsWith("search:"))return;const o=Number(r.slice(7));return Number.isInteger(o)&&o>=0?o:void 0},or=n=>{if(typeof n.endCursor=="string")throw new $("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");if(!Number.isFinite(n.numItems))throw new $("BAD_REQUEST",`search pagination needs a finite numItems, got ${String(n.numItems)}`);const r=Math.max(0,Math.floor(n.numItems)),o=n.cursor?nr(n.cursor):0;if(o===void 0)throw Jo();if(o+r>=z)throw new $("BAD_REQUEST",`search pagination reaches the ${String(z)}-document limit (offset ${String(o)} + ${String(r)} requested) — a page must end below the cap so the probe row that answers \`hasMore\` still fits: retry with numItems ${String(Math.max(1,z-o-1))} or fewer, or narrow the query or the filters instead`);return{numItems:r,offset:o}},rr=(n,r)=>{const o=r.offset+r.numItems,s=r.numItems>0&&n.length>o;return{continueCursor:s?tr(o):null,isDone:!s,page:n.slice(r.offset,o)}},ir=n=>{if(n===void 0)return z+1;if(!Number.isFinite(n))return z;const r=Math.max(0,Math.floor(n));if(r>z)throw new $("BAD_REQUEST",`search returns at most ${String(z)} documents (asked for ${String(r)}) — narrow the query or paginate instead`);return r},$n=500,Rn=(n,r,o)=>{if(n!==void 0&&n!==Number.POSITIVE_INFINITY&&(!Number.isInteger(n)||n<0))throw o(`${r}: batch limit must be a non-negative integer`);return n??$n},Sn=(n,r,o,s)=>{if(n>r)throw s(`${o}: batch of ${String(n)} exceeds the limit of ${String(r)} (raise options.limit or chunk the call)`)},sr=32,cr=1024,vn=(n,r,o,s)=>{const c=`SELECT id, _creationTime, ${Me(ie)} FROM ${Me(n)}`,u=`ORDER BY ${o}${s===void 0?"":` LIMIT ${String(s)}`}`;return r===void 0?Qe(`${c} ${u}`):be(`${c} WHERE `,r,` ${u}`)},Ye={fieldRef:n=>Qe(ht(n)),rangeTypeGuard:(n,r)=>Qe(eo(n,r)),serialize:Ce},ar=n=>n===void 0?"":Eo(n==="first"),_n=n=>{const r=n.map(o=>`${ht(o.field)} ${o.direction==="desc"?"DESC":"ASC"}${ar(o.nulls)}`);return n.some(o=>o.field==="_id"||o.field==="id")||r.push(`${ht("id")} ${mo(n)==="desc"?"DESC":"ASC"}`),r.join(", ")},dr={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},Tn=n=>new Set(n.sqlConditions.filter(r=>r.comparator==="=").map(r=>r.field)),lr=n=>{const r=Tn(n);let o=0;for(;o<n.indexFields.length&&r.has(n.indexFields[o]??"");)o+=1;return n.indexFields.slice(o)},ur=(n,r)=>{const o=n.order,s=lr(n),{shape:c}=r;return s.length>0?Ht(s.map(u=>({[u]:o})),c,{pinned:Tn(n),uniqueBy:$o(r.indexes,c)}):Ht([{_creationTime:o}],c)},fr=(n,r,o,s)=>{const c=n.sqlConditions.map(u=>({[u.field]:{[dr[u.comparator]??"eq"]:u.value}}));if(o&&c.push(Ro(r,Kt(o))),s&&c.push(So(r,Kt(s))),c.length!==0)return c.length===1?c[0]:{AND:c}},hr=n=>{if(n.want!==void 0)return n.selective?Math.max(n.want,sr):n.want},gt=(n,r,o,s,c,u,g)=>{const E=ur(s,o),y=_n(E),d=[],{filters:b,want:_}=u;let v=u.cursor??void 0,x=hr(u);if(_===0)return{documents:d,orderKeys:E};for(;;){const W=Z(fr(s,E,v,u.endCursor),Ye,ze),q=vn(r,c&&W?be(W," AND ",c):c??W,y,x),B=he(n,q.text,...q.params).toArray();let U={};g(B.length);for(const j of B)if(U=xe(j),b.every(ee=>ee(U))&&d.push(U)===_)return{documents:d,orderKeys:E};if(x===void 0||B.length<x)return{documents:d,orderKeys:E};v=wt(U,E),x=Math.max(x,Math.min(x*2,cr))}},wr=(n,r,o,s,c,u,g,E)=>{const y=Math.max(0,Math.floor(c.numItems));if(typeof c.endCursor=="string"){const{documents:W,orderKeys:q}=gt(n,r,o,s,u,{cursor:c.cursor,endCursor:c.endCursor,filters:g.all,selective:g.selective,want:void 0},E),B=W.length>=2?W[Math.floor(W.length/2)-1]:void 0;return{continueCursor:c.endCursor,isDone:!0,page:W,splitCursor:B?wt(B,q):null}}const{documents:d,orderKeys:b}=gt(n,r,o,s,u,{cursor:c.cursor,filters:g.all,selective:g.selective,want:y+1},E),_=d.length>y,v=_?d.slice(0,y):d,x=v.at(-1);return{continueCursor:_&&x?wt(x,b):null,isDone:!_,page:v}},Xe=n=>{const r=new Map;return o=>{const s=r.get(o);if(s!==void 0)return s;const c=n(Me(o));return r.set(o,c),c}},we=Me(ie),pr=Xe(n=>`INSERT INTO ${n} (id, _creationTime, ${we}) VALUES (?, ?, ?)`),Zt=Xe(n=>`UPDATE ${n} SET ${we} = ? WHERE id = ? AND ${we} = ?`),gr=Xe(n=>`UPDATE ${n} SET _creationTime = ?, ${we} = ? WHERE id = ? AND ${we} = ?`),yr=Xe(n=>`DELETE FROM ${n} WHERE id = ? AND ${we} = ?`),mr="SELECT changes() AS changed",en=new Map,Er="",$r=n=>{const r=JSON.stringify(n),o=en.get(r);if(o!==void 0)return o;const s=n.map(u=>a`SELECT ${a.raw(`'${u.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${a.identifier(ie)} FROM ${a.identifier(u)} WHERE id = ${Er}`),{sql:c}=gn("sqlite",a`${yn(s)} LIMIT 1`);return en.set(r,c),c},Rr=(n,r)=>r.map(()=>n),Sr=/^[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(!Sr.test(n))throw new $("INTERNAL",`invalid clientId ${JSON.stringify(n)}: a client-supplied row id must be a UUID`)},yt=n=>{if(n.includes("\0"))throw new $("BAD_REQUEST",`invalid row id ${JSON.stringify(n)}: a row id cannot hold a NUL character (U+0000)`)},_r=(n,r,o,s)=>{if(o!==!0)return;const c=n!==void 0&&"serverDefault"in(n.shape._id?._meta?.column??{});for(const u of r){const g=c?pt(n,u,s)._id:u._id;typeof g=="string"&&yt(g)}},tn=50,je=Math.floor(mn.boundParams/3),nn=mn.boundParams,Tr=128,Ve=n=>new $("BATCH_LIMIT_EXCEEDED",n,{status:400}),He=(n,r,o)=>{Sn(n,Rn(r,o,Ve),o,Ve)},on=async(n,r,o,s,c)=>{const u=Rn(s,c,Ve),{page:g}=await n.findMany(r,Number.isFinite(u)?{limit:u+1,omitContinueCursor:!0,where:o}:{where:o});return g.length>u&&Sn(Math.max(await n.count(r,{where:o}),g.length),u,c,Ve),g},Ar=n=>{const r={eq:(o,s)=>(n.sqlConditions.push({comparator:"=",field:o,value:s}),r),gt:(o,s)=>(n.sqlConditions.push({comparator:">",field:o,value:s}),r),gte:(o,s)=>(n.sqlConditions.push({comparator:">=",field:o,value:s}),r),lt:(o,s)=>(n.sqlConditions.push({comparator:"<",field:o,value:s}),r),lte:(o,s)=>(n.sqlConditions.push({comparator:"<=",field:o,value:s}),r)};return r},Ir=n=>Math.max(n,z),An=(n,r)=>{const o=n.filters.map(s=>a`${fe(s.field)} = ${Ce(s.value)}`);return r&&o.push(r),o},xr=(n,r,o,s,c)=>{const u=Rt(o.query,$t(o.definition.language));if(u.length===0)return[];const g=qn(r,o.indexName),E=`${g}__vocab`,y=u.length-1,d=u.map((q,B)=>{const U=Yo(q,B===y),j=U.exact?a`${a.identifier("term")} = ${U.lower}`:a`${a.identifier("term")} >= ${U.lower} AND ${a.identifier("term")} < ${U.upper}`;return a`SELECT ${a.identifier("doc")}, ${a.raw(String(B))} AS ${a.identifier("__term__")}, COUNT(*) AS ${a.identifier("__n__")} FROM ${a.identifier(E)} WHERE ${j} GROUP BY ${a.identifier("doc")}`}),b=u.map((q,B)=>a`SUM(CASE WHEN u.${a.identifier("__term__")} = ${a.raw(String(B))} THEN u.${a.identifier("__n__")} ELSE 0 END)`),_=a`SELECT f.${a.identifier(qe)} AS ${a.identifier(qe)}, ${a.join(b,a` + `)} AS ${a.identifier("__score__")} FROM (${yn(d)}) u JOIN ${a.identifier(g)} f ON f.rowid = u.${a.identifier("doc")} GROUP BY f.${a.identifier(qe)} HAVING ${a.join(b.map(q=>a`${q} > 0`),a` AND `)}`,v=An(o,c);let x=a`SELECT m.id, m._creationTime, m.${a.identifier(ie)}, s.${a.identifier("__score__")} AS ${a.identifier("__score__")} FROM (${_}) s JOIN ${a.identifier(r)} m ON m.id = s.${a.identifier(qe)}`;v.length>0&&(x=a`${x} WHERE ${a.join(v,a` AND `)}`),x=a`${x} ORDER BY s.${a.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${a.raw(String(s))}`;const W=[];for(const q of K(n,x)){const B=pn(q);if(B){const U=q.__score__;W.push({document:B,score:typeof U=="number"?U:Number(U??0)})}}return W},br=(n,r,o,s,c)=>{const u=$t(o.definition.language),g=Rt(o.query,u);if(g.length===0)return[];const E=An(o,c);let y=a`SELECT id, _creationTime, ${a.identifier(ie)} FROM ${a.identifier(r)}`;E.length>0&&(y=a`${y} WHERE ${a.join(E,a` AND `)}`),y=a`${y} ORDER BY _creationTime DESC, id ASC LIMIT ${a.raw(String(Ir(s)))}`;const d=K(n,y).toArray(),b=[];for(const _ of d){const v=pn(_);if(!v)continue;const x=zo(Pn(v,o.definition),g);x>0&&b.push({creationTime:typeof v._creationTime=="number"?v._creationTime:0,doc:v,id:typeof v._id=="string"?v._id:"",score:x})}return b.sort((_,v)=>v.score-_.score||v.creationTime-_.creationTime||_.id.localeCompare(v.id)),b.slice(0,s).map(_=>({document:_.doc,score:_.score}))},lt=(n,r,o,s)=>{if(!Number.isFinite(n.lat)||n.lat<-90||n.lat>90||!Number.isFinite(n.lng)||n.lng<-180||n.lng>180)throw new $("BAD_REQUEST",`geo index "${s}" on table "${o}": ${r} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},Cr=(n,r)=>{const o=n,s={near:(c,u)=>{if(o.within)throw new $("INTERNAL",`geo index "${o.indexName}" on table "${r}": call .near() or .within(), not both`);if(lt(c,".near() point",r,o.indexName),!Number.isFinite(u)||u<=0)throw new $("BAD_REQUEST",`geo index "${o.indexName}" on table "${r}": .near() radiusMeters must be a finite number > 0, got ${String(u)}`);return o.near={point:{lat:c.lat,lng:c.lng},radiusMeters:u},s},within:c=>{if(o.near)throw new $("INTERNAL",`geo index "${o.indexName}" on table "${r}": call .near() or .within(), not both`);if(lt(c.sw,".within() sw corner",r,o.indexName),lt(c.ne,".within() ne corner",r,o.indexName),c.sw.lat>c.ne.lat)throw new $("BAD_REQUEST",`geo index "${o.indexName}" on table "${r}": .within() corners are transposed (sw.lat > ne.lat)`);if(c.sw.lng>c.ne.lng)throw new $("BAD_REQUEST",`geo index "${o.indexName}" on table "${r}": .within() box crosses the antimeridian (sw.lng > ne.lng), which is not supported — split it into two boxes at ±180 and union the results`);return o.within={ne:{lat:c.ne.lat,lng:c.ne.lng},sw:{lat:c.sw.lat,lng:c.sw.lng}},s}};return s},Mr=(n,r)=>{const o=n[r];if(o===null||typeof o!="object")return;const{lat:s,lng:c}=o;return typeof s=="number"&&typeof c=="number"?{lat:s,lng:c}:void 0},Dr=(n,r)=>{const o=Mr(n,r.definition.field);if(!o)return;const s=typeof n._creationTime=="number"?n._creationTime:0;if(r.near){const c=fo(r.near.point,o);return c<=r.near.radiusMeters?{creationTime:s,distance:c}:void 0}return ho(o,r.within)?{creationTime:s,distance:0}:void 0},kr=(n,r,o,s)=>{if(!o.near&&!o.within)throw new $("INTERNAL",`geo index "${o.indexName}" on table "${r}": call .near(point, radius) or .within(box)`);const c=o.near?lo(o.near.point,o.near.radiusMeters):uo(o.within),u=so(r,o.indexName),g=c.map(_=>a`(g.${a.identifier("__geohash__")} >= ${_} AND g.${a.identifier("__geohash__")} < ${`${_}{`})`),E=[a`(${a.join(g,a` OR `)})`];s&&E.push(s);const y=a`SELECT m.id, m._creationTime, m.${a.identifier(ie)} FROM ${a.identifier(u)} g JOIN ${a.identifier(r)} m ON m.id = g.${a.identifier("__id__")} WHERE ${a.join(E,a` AND `)}`,d=K(n,y).toArray(),b=[];for(const _ of d){const v=xe(_),x=v?Dr(v,o):void 0;v&&x&&b.push({creationTime:x.creationTime,distance:x.distance,doc:v})}return b.sort((_,v)=>_.distance-v.distance||v.creationTime-_.creationTime),b},In=(n,r,o,s)=>{const c=[];for(const u of n)if(r.every(g=>g(s(u)))&&(c.push(u),typeof o=="number"&&c.length>=o))break;return c},Lr=(n,r,o,s,c,u=()=>{})=>{const g=o.within!==void 0,E=kr(n,r,o,c).map(y=>({distanceMeters:g?null:y.distance,document:y.doc}));return u(E.length),typeof s=="number"?E.slice(0,Math.max(0,Math.floor(s))):E},rn=(n,r,o,s,c,u,g=()=>{})=>{const{geo:E}=o;if(!E)throw new $("INTERNAL","runGeoTerminalScored called without a staged geo query");const y=c.length>0,d=Lr(n,r,E,y?void 0:u,s,g);return y?In(d,c,u,b=>b.document):d},sn=(n,r,o)=>{const s=n.shape[r];if(s!==void 0&&Ko(s))throw new $("BAD_REQUEST",`${o}: "${r}" 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)`)},Fr=n=>{let r=0;const o=[],s={...Ye,relationExists:c=>{const{childWhere:u,negated:g,parentTable:E,relation:y}=c,d=`__rel_${String(r)}`,b=o.at(-1)??E;r+=1,n(y.table,G);const _=y.kind==="one"?y.field:y.references,v=y.kind==="one"?y.references:y.field,x=Qe(`${Gt(d,v)} = ${Gt(b,_)}`);o.push(d);const W=Z(u,s,ze);o.pop();const q=W===void 0?x:be(x," AND ",W),B=be("EXISTS (SELECT 1 FROM ",Jt(y.table)," AS ",Jt(d)," WHERE ",q,")");return g?be("NOT ",B):B}};return s};class Br extends ${constructor(r="unique() found more than one matching document"){super("NOT_UNIQUE",r,{name:"NotUniqueError"})}}const Wr=/\s/u,qr=String.fromCodePoint(0),cn=(n,r,o)=>{if(!n.tables[r])throw new $("INTERNAL",`unknown table: ${r}`);return typeof o!="string"||o.length===0||Wr.test(o)||o.includes(qr)?null:o},xn=(n,r,o,s=()=>{},c=()=>{},u=()=>{},g)=>{const E=r.tables[o];if(!E)throw new $("INTERNAL",`unknown table: ${o}`);const y=Ae(E.softDeleteMode,void 0),d=g??{indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[],verifyFilters:[]},b=()=>{const S=Q(y,d.pushedWhere);return S?Z(S,ue):void 0},_=()=>{const S=Q(y,d.pushedWhere);return S?Z(S,Ye,ze):void 0},v=()=>[...d.inMemoryFilters,...d.verifyFilters];let x=0;const W=S=>{const{search:M}=d;if(!M)throw new $("INTERNAL","runSearchFetch called without a staged search");Nn(ro(n),o,E);const L=d.inMemoryFilters.length>0,F=ir(L?void 0:S),k=io(n);if(k&&!Qn(n,o,M.definition))throw new $("SEARCH_INDEX_BUILDING",`search index "${M.indexName}" on table "${o}" 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 pe=b(),te=k?xr(n,o,M,F,pe):br(n,o,M,F,pe);!L&&S===void 0&&Zo(te);const ge=v();return x=te.length,ge.length>0?In(te,ge,S,J=>J.document):te},q=S=>W(S).map(M=>M.document),B=S=>{const M=or(S);return rr(q(er(M)),M)},U=()=>{if(d.search||d.geo||d.indexName===void 0){c(void 0);return}c(Co(o,d.indexName,d.indexFields,d.sqlConditions,Ce))},j=S=>{U();let M=0;const L=(()=>{if(d.search){const F=q(S);return M=x,F}return d.geo?rn(n,o,d,b(),v(),S,F=>{M=F}).map(F=>F.document):gt(n,o,E,d,_(),{filters:v(),selective:d.inMemoryFilters.length>0,want:S===void 0?void 0:Math.max(0,Math.floor(S))},F=>{M+=F}).documents})();return u(Math.max(M,L.length)),L},ee=()=>{if(!d.search&&!d.geo)throw new $("INTERNAL",`ctx.db.query("${o}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);U();let S=0;const M=(()=>{if(d.search){const L=W(void 0);return S=x,L}return rn(n,o,d,b(),v(),void 0,L=>{S=L})})();return u(Math.max(S,M.length)),M},N={async*[Symbol.asyncIterator](){const S=xn(n,r,o,s,c,u,{...d,indexFields:[...d.indexFields],inMemoryFilters:[...d.inMemoryFilters],sqlConditions:[...d.sqlConditions],verifyFilters:[...d.verifyFilters]});if(d.search){yield*await S.collect();return}let M;for(;;){const L=await S.paginate({cursor:M??null,numItems:Tr});if(yield*L.page,L.isDone||L.continueCursor===null)return;M=L.continueCursor}},async collect(){return j(void 0)},async collectWithScores(){return ee()},filter(S){const M=Mo(S);return M!==void 0&&Do(M,E.shape)?(d.pushedWhere=Q(d.pushedWhere,M),d.verifyFilters.push(S)):d.inMemoryFilters.push(S),N},async first(){return j(1)[0]??null},order(S){return d.order=S==="desc"?"desc":"asc",N},async paginate(S){let M=0;if(U(),d.search){const F=B(S);return u(F.page.length),F}if(d.geo)throw new $("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const L=wr(n,o,E,d,S,_(),{all:v(),selective:d.inMemoryFilters.length>0},F=>{M+=F});return u(Math.max(M,L.page.length)),L},async take(S){return j(S)},async unique(){const S=j(2);if(S.length>1)throw new Br(`unique() on table "${o}" matched ${String(S.length)} documents; expected at most one`);return S[0]??null},withGeoIndex(S,M){const L=(E.geoIndexes??[]).find(k=>k.name===S);if(!L)throw new $("INTERNAL",`unknown geo index "${S}" on table "${o}"`);s(o,S,"geo");const F={definition:L,indexName:S};if(d.geo=F,M(Cr(F,o)),!F.near&&!F.within)throw new $("INTERNAL",`geo index "${S}" on table "${o}" requires a .near(point, radius) or .within(box) call`);return N},withIndex(S,M){const L=E.indexes.find(F=>F.name===S);if(!L)throw new $("INTERNAL",`unknown index "${S}" on table "${o}"`);return s(o,S,"index"),d.indexName=S,d.indexFields=L.fields,M&&M(Ar(d)),N},withSearchIndex(S,M){const L=(E.searchIndexes??[]).find(k=>k.name===S);if(!L)throw new $("INTERNAL",`unknown search index "${S}" on table "${o}"`);s(o,S,"search");const F={definition:L,field:L.field,filters:[],hasQuery:!1,indexName:S,query:""};if(d.search=F,M(Xo(F,o,$t(L.language))),!F.hasQuery)throw new $("INTERNAL",`search index "${S}" on table "${o}" requires a .search(field, query) call`);return N}};return N},ut=(n,r,o,s)=>{const c=o;for(const[u,g]of oo(n)){if(g.serverDefault){u in r&&(c[u]=g.serverDefault({auth:s}));continue}g.onUpdateFn&&!(u in r)&&(c[u]=g.onUpdateFn())}},an=5,dn=(n,r)=>{for(const o of Object.keys(r))if(r[o]===void 0)throw new $("INTERNAL",`Cannot ${n} field '${o}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},ln=["_commitSeq","_creationTime","_id"],Ke=n=>ln.some(r=>r in n)?Object.fromEntries(Object.entries(n).filter(([r])=>!ln.includes(r))):n,Pr=/unique constraint failed/i,Ur=n=>n instanceof Error&&Pr.test(n.message),Or=/string or blob too big/iu,Gr=(n,r)=>{if(!(!(n instanceof Error)||!Or.test(n.message)))throw new $("PAYLOAD_TOO_LARGE",`document is too large to store in "${r}": 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.`)},mt=(n,r,o,s)=>{try{he(n,o,...s)}catch(c){throw Ur(c)?new se(`unique constraint violation on "${r}"`,"unique"):(Gr(c,r),c)}},Ne=(n,r,o,s)=>{if(mt(n,r,o,s),he(n,mr).one().changed===0)throw new se(`optimistic concurrency conflict on "${r}" — the row changed during this mutation; refetch and retry`,"occ")},un=(n,r,o,s,c,u,g)=>{const E=[];for(let _=0;_<o.length+1;_+=1){const v=o[_],x=s[_],W=x?.direction==="desc"?"desc":"asc",q=v===void 0||x===void 0?a`${a.identifier(To)} < ${g}`:Ao(v,u[_],W,!1);if(q===void 0)continue;const B=[];for(let j=0;j<_;j+=1)B.push(a`${a.identifier(o[j])} IS ${u[j]}`);B.push(q);const[U]=B;E.push(B.length===1&&U!==void 0?U:a`(${a.join(B,a` AND `)})`)}const y=E.length>0?a.join(E,a` OR `):a`1 = 0`,d=K(n,a`SELECT COUNT(*) AS c FROM ${a.identifier(r)} WHERE ${a.identifier("__partition__")} = ${c} AND (${y})`).one(),b=K(n,a`SELECT COUNT(*) AS c FROM ${a.identifier(r)} WHERE ${a.identifier("__partition__")} = ${c}`).one();return{before:d.c,total:b.c}},jr=n=>{const r=new Map;for(const[s,c]of Object.entries(n.tables))for(const u of Object.values(c.relationMap??{}))u.kind==="one"&&(u.onDelete==="cascade"||u.onDelete==="set null")&&r.set(u.table,[...r.get(u.table)??[],{holder:s,op:u.onDelete==="cascade"?"delete":"update"}]);const o=s=>{const c=new Set,u=[s];for(let g=u.pop();g!==void 0;g=u.pop())for(const{holder:E,op:y}of r.get(g)??[]){if(E===s||zt(n,E,y))return!0;c.has(E)||(c.add(E),u.push(E))}return!1};return new Set(Object.entries(n.tables).filter(([s,c])=>c.shardMode?.kind==="global"||zt(n,s,"delete")||o(s)).map(([s])=>s))},Hr=n=>{const r=new Map;for(const[o,s]of Object.entries(n.tables))s.softDeleteMode&&r.set(o,s.softDeleteMode.field);return r},ft=new WeakMap,Kr=(n,r)=>{let o=ft.get(r.tables);if(!ft.has(r.tables)){const c=Object.keys(r.tables).map(u=>u.replaceAll(/[$()*+.?[\\\]^{|}]/gu,String.raw`\$&`));o=c.length===0?void 0:new RegExp(`"(${c.join("|")})"`,"gu"),ft.set(r.tables,o)}if(o===void 0)return;const s=new Set;for(const c of n.matchAll(o))s.add(c[1]);return s.size===1?[...s][0]:void 0},Nr=(n,r,o)=>{for(const s of n){const c=s,u=c?.[ie];if(typeof u=="string"){const g=c?.id,E=ao(u);typeof g!="string"?r.recordReadBytes(E):o===void 0?r.recordDocumentRead(`${g}\0${String(E)}`,E):r.recordDocumentRead(`${o}\0${g}`,E)}}},Qr=(n,r,o)=>{if(r===void 0)return n;const s=(c,...u)=>{const g=n.exec(c,...u),E=g.one.bind(g),y=g[Symbol.iterator].bind(g),d=o===void 0?void 0:Kr(c,o);let b=!1;const _=v=>{Nr(v,r,d)};return g.toArray=()=>{const v=[];for(const x of{[Symbol.iterator]:y})_([x]),v.push(x);return v},g.one=()=>{b=!0;try{const v=E();return _([v]),v}finally{b=!1}},g[Symbol.iterator]=function*(){for(const x of{[Symbol.iterator]:y})b||_([x]),yield x},g};return new Proxy(n,{get:(c,u)=>u==="exec"?s:u===to?c:Reflect.get(c,u,c)})},Vr=new Map([["findFirst","rows"],["findFirstOrThrow","rows"],["findMany","page"],["get","rows"],["lookupById","lookup"],["rankPage","page"]]),Jr=new Map([["collect","rows"],["collectWithScores","scored"],["first","rows"],["paginate","page"],["take","rows"],["unique","rows"]]),Ie=(n,r,o)=>{if(typeof n!="object"||n===null)return;const s=co(n);if(s===void 0)return;const c=n._id;typeof c=="string"?o.recordDocumentRead(`global\0${r}\0${c}`,s):o.recordReadBytes(s)},Je=(n,r,o,s)=>{if(typeof n!="object"||n===null)return;const c=n;switch(r){case"lookup":{Ie(c.row,typeof c.tableName=="string"?c.tableName:o,s);return}case"page":{for(const u of c.page??[])Ie(u,o,s);return}case"rows":{for(const u of Array.isArray(n)?n:[n])Ie(u,o,s);return}default:for(const u of Array.isArray(n)?n:[])Ie(u.document,o,s)}},bn=(n,r,o)=>new Proxy(n,{get:(s,c)=>{const u=Reflect.get(s,c,s);if(typeof u!="function")return u;if(c===Symbol.asyncIterator)return async function*(){for await(const y of Reflect.apply(u,s,[]))Ie(y,r,o),yield y};const g=Jr.get(c);return(...E)=>{const y=Reflect.apply(u,s,E);return g!==void 0?Promise.resolve(y).then(d=>(Je(d,g,r,o),d)):typeof y=="object"&&y!==null&&!(y instanceof Promise)?bn(y,r,o):y}}}),zr=new Set(["findFirst","findFirstOrThrow","findMany"]),Yr=n=>{const r=n[1],o=r?.select;if(!Array.isArray(o))return;const s=Object.fromEntries(Object.entries(r).filter(([g])=>g!=="select")),c=s.with,u=g=>En(g,o,c);return{args:[n[0],s,...n.slice(2)],project:(g,E)=>typeof g!="object"||g===null?g:E==="page"?{...g,page:u(g.page)}:u([g])[0]}},fn=256,Et=4096,Xr=1024*1024,Zr=async(n,r,o,s)=>{const c=r[1]??{},u=[];let{cursor:g}=c,E=fn,y=0;for(;;){const d=await n([r[0],{...c,cursor:g,limit:E},...r.slice(2)]);if(Array.isArray(d))return Je(d,"rows",o,s),[...u,...d];const b=s.headroom().readBytes;if(Je(d,"page",o,s),u.push(...d.page),d.isDone||typeof d.continueCursor!="string")return{continueCursor:null,isDone:!0,page:u};g=d.continueCursor,y+=s.headroom().readBytes-b,E=y>0?Math.min(Et,Math.max(fn,Math.floor(Xr*u.length/y))):Et}},ei=(n,r)=>n===void 0||r===void 0?n:new Proxy(n,{get:(o,s)=>{const c=Reflect.get(o,s,o);if(typeof c!="function")return c;if(s==="query")return(...g)=>bn(Reflect.apply(c,o,g),String(g[0]),r);const u=Vr.get(s);return u===void 0?c:async(...g)=>{const E=zr.has(s)?Yr(g):void 0;let y=E?.args??g;const d=String(g[0]),b=y[1],_=s==="findMany"&&typeof b?.endCursor=="string",v=s==="findMany"&&typeof b?.limit!="number"&&!_;if(_&&typeof b.limit!="number"&&(y=[y[0],{...b,limit:Et},...y.slice(2)]),v){const W=await Zr(q=>Reflect.apply(c,o,q),y,d,r);return E===void 0?W:E.project(W,u)}const x=await Reflect.apply(c,o,y);return Je(x,u,d,r),E===void 0?x:E.project(x,u)}}}),hn=new WeakMap,wn=new WeakMap,ti=n=>{const{baselineSeq:r,onStalePatchDropped:o}=n,{headroom:s}=n,c=hn.get(n)??{value:void 0},u=wn.get(n)??{value:0};let g;const E=()=>{if(g===void 0){const e={...n,enforceRls:!1,headroom:void 0};hn.set(e,c),wn.set(e,u),g=ti(e)}return g},y=Qr(n.sql,s,n.schema),{schema:d}=n,b=n.broadcast??(()=>{}),_=(e,t)=>{if(!Object.hasOwn(d.tables,e))throw new $("BAD_REQUEST",`${t}: "${e}" is not a table in this schema`)},v=ko(d),x=new Map;for(const e of v){const t=i=>(d.tables[i]?.shardMode?.kind??"root")==="root";!e.array&&t(e.sourceTable)&&t(e.targetTable)&&x.set(e.sourceTable,[...x.get(e.sourceTable)??[],e])}const W=(e,t,i)=>{for(const l of x.get(e)??[]){const w=t[l.column];if(typeof w!="string"||i?.[l.column]===w||l.targetTable===e&&t._id===w)continue;if(K(y,a`SELECT 1 FROM ${a.identifier(l.targetTable)} WHERE id = ${w} LIMIT 1`).toArray().length===0)throw new $("VALIDATION_ERROR",`${l.name} references ${l.targetTable} row "${w}", which does not exist`)}},q=qo(d,n.inTransaction),B=jr(d),U=Hr(d),j=()=>n.inTransaction?.()===!0,ee=e=>d.tables[e]?.commitOrderedMode!==!0?{}:((c.value===void 0||!j())&&(c.value=zn(y)),{[Yn]:c.value}),N=(e,...t)=>{const i=d.tables[e]?.indexes??[],l=[];let w;for(const p of t)p&&(typeof p._id=="string"&&p._id!==w&&(w=p._id,l.push(Io(w))),l.push(...xo(i,bo(i,p,Ce))));return l.length>0?l:void 0},S=n.onRead??(()=>{}),M=e=>{Ut(d.tables[e])&&S(Vt,Vt)},L=n.onReadRange??(e=>{S(e.table,G)}),F=e=>{M(e.table),L(e)},k=(e,t,i)=>{t!==void 0&&(i===!0||t!==G)&&s?.recordRead(1),M(e),S(e,t,i)},pe=(e,t)=>{const i=e.row._id;k(e.tableName,typeof i=="string"?i:t,typeof i=="string")},te=n.onIndexUse??(()=>{}),ge=n.onWrite??(()=>{}),J=e=>{s?.recordWrite(e)},ye=async e=>{J(e.doc),await ge(e)},{cache:me}=n,Ee=n.clock??(()=>Date.now()),St=n.idGenerator??(()=>crypto.randomUUID()),vt=n.scheduler??On,$e=ei(n.globalDb,s),ce=n.auth??{identity:null,userId:null},_t=n.cdc??!1,Ze=vt,Cn=No({scheduler:typeof Ze.list=="function"&&typeof Ze.get=="function"?Ze:void 0,storage:n.storage}),Re=(e,t,i,l)=>{_t&&!Ut(d.tables[e])&&Vn(y,Ee(),e,t,i,l)},Tt=(e,t,i,l)=>{const w=d.tables[e];if(w?.dropStalePatchesMode!==!0||!_t)return!1;const p=r?.();if(p===void 0)return!1;const f=Jn(y,e,t,p);if(f===void 0)return!1;const h=yo(w,i);return Object.keys(Ke(i)).some(m=>!h.has(m)&&Pt(jt(f,m))!==Pt(jt(l,m)))},ae=e=>d.tables[e]?.shardMode?.kind==="global",At=(e,t)=>{if(ae(e)){if(!$e)throw new $("INTERNAL",`cross-backend ${t} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return $e}return O},et=e=>At(e,"cascade"),H=(e,t)=>{if(ae(e)){if(!$e)throw new $("INTERNAL",`${t} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return $e}},It=async(e,t,i,l,w)=>{w&&J(i);const p=await e.insert(t,i,l);return b({key:p,op:"insert",row:{...i,_id:p},table:t}),p},xt=(e,t)=>At(e,"relation load").findMany(e,t),bt=(e,t)=>(ae(e)&&k(e,G),xt(e,t)),Mn=e=>!ae(e.table),Ct=n.relationExistsPushDown??"auto",Mt=Ct!=="never",{maxRelationKeys:Dt}=n,De=(e,t,i)=>Bo(e,{fetcher:bt,maxRelationKeys:Dt,relationBaseWhere:i,schema:d,tableName:t}),Dn=async(e,t,i,l)=>{const w=H(e,"relation grouped count");if(w)return k(e,G),jo((R,P)=>w.count(R,P),e,t,i,l);const p=d.tables[e];if(!p)throw new $("INTERNAL",`unknown table: ${e}`);k(e,G);const f=Ae(p.softDeleteMode,void 0),h={[t]:{in:i}},m=Q(Q(h,l),f),A=await De(m,e,void 0),C=Z(A,ue),I=fe(t);let T=a`SELECT ${I} AS __fk__, COUNT(*) AS count FROM ${a.identifier(e)}`;C&&(T=a`${T} WHERE ${C}`),T=a`${T} GROUP BY ${I}`;const D=K(y,T).toArray();return new Map(D.map(R=>[R.__fk__,R.count]))},kt=new Set;for(const[e,t]of Object.entries(d.tables))for(const i of Object.values(t.triggerMap??{}))kt.add(`${e} ${i.timing} ${i.op}`);const ne=(e,t,i)=>kt.has(`${e} ${t} ${i}`),oe=async(e,t,i)=>{if(u.value+=1,u.value>tn)throw u.value-=1,new se(`trigger recursion exceeded ${String(tn)} levels on "${i.table}" — check for a self-triggering write`,"trigger");try{await Qo({ctx:Bn,event:i,op:t,schema:d,tableName:i.table,timing:e})}finally{u.value-=1}},{ensureBackfilledForTable:Se,ensureBackfilledIndex:tt,ensureRankBackfilled:nt,ensureRankBackfilledForTable:ve,syncAggregates:ke,syncCompanionsForInsert:Lt,syncGeo:Le,syncRanks:_e,syncSearch:Fe}=Xn({broadcast:b,indexKeysFor:(e,t)=>N(e,t),invalidateCache:(e,t,i)=>me?.invalidate(e,t,N(e,i)),recordCdc:Re,schema:d,sql:y,verified:n.companionMemo?.verified}),Ft=(e,t,i)=>{const{shardMode:l}=t;if(l?.kind==="shardBy"&&!(l.field!==void 0&&(i.partitionBy??[]).includes(l.field)))throw Object.assign(new Error(`rank index "${i.name}" on "${e}" partitions across shards (shard key "${l.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})},Bt=e=>Object.entries(d.tables).filter(([,t])=>t.shardMode?.kind!=="global").map(([t])=>t).filter(t=>e===void 0||t===e),Te=e=>e===void 0||ae(e)?$e:void 0,ot=async(e,t,i,l,w)=>{for(let p=0;p<i.length;p+=1)J(void 0);if(w!==void 0&&e.deleteMany!==void 0)return e.deleteMany(t,i,w.options);for(const p of i)await e.delete(t,p,l);return{deleted:i.length}},re=(e,t)=>{const i=Bt(t);for(let l=0;l<i.length;l+=nn){const w=i.slice(l,l+nn),[p]=he(y,$r(w),...Rr(e,w)).toArray();if(!p)continue;const f=p.__t__,h=xe(p);if(typeof f!="string"||!h)return;const m=p[ie];return{docJson:typeof m=="string"?m:le(m??{}),row:h,tableName:f}}},Wt={assertRankPartitionLocal:Ft,ensureRankBackfilled:nt,onRead:k,rowToDocument:xe,schema:d,sql:y},kn=(e,t,i)=>{const l=Z(i,ue);return l===void 0||K(y,a`SELECT 1 FROM ${a.identifier(e)} WHERE ${a.identifier("id")} = ${t} AND ${l}`).toArray().length>0},Ln=(e,t,i,l)=>Tt(e,t,i,l)?(o?.({fields:Object.keys(Ke(i)),id:t,table:e}),!0):!1,Fn=async(e,t,i,l,w)=>{const p=re(t,e);if(!p)return{applied:!1,doc:null};if(k(e,t),!kn(e,t,i.where)||Ln(e,t,i.patch,p.row))return{applied:!1,doc:p.row};try{await w(i.patch)}catch(f){if(f instanceof se&&f.kind==="occ"&&l)return;throw f}return{applied:!0,doc:re(t,e)?.row??null}},qt=async(e,t,i,l)=>{const{fetchLimit:w,limit:p,orderKeys:f,predicate:h}=await Wo(t,i,{canPushExists:Mt?Mn:void 0,existsPushMode:Ct==="always"?"always":"auto",fetcher:bt,maxRelationKeys:Dt,schema:d,tableName:e}),m=Mt?Fr(l):Ye,A=Z(h,m,ze),C=vn(e,A,_n(f),w);return{limit:p,orderKeys:f,statement:C}},O={system:Cn,async aggregate(e,t){const i=H(e,"aggregate");if(i)return k(e,G),i.aggregate(e,t);const l=d.tables[e];if(!l)throw new $("INTERNAL",`unknown table: ${e}`);if(Pe(t.op),t.op==="count")return O.count(e,{baseWhere:t.baseWhere,relationBaseWhere:t.relationBaseWhere,restrictsCounts:t.restrictsCounts,where:t.where});if(!t.field)throw new $("INTERNAL",`aggregate(${e}, { op: "${t.op}" }): "field" is required for non-count reducers`);k(e,G);const w=Ae(l.softDeleteMode,void 0),p=Q(Q(t.baseWhere,t.where),w),f=await De(p,e,t.relationBaseWhere),h=f!==p;if(l.aggregateIndexes&&!t.baseWhere&&!h){const R=Kn(l.aggregateIndexes,t.op,t.field,t.where);if(R){tt(e,R.index);const P=it(R.index.by??[],R.key),Y=rt(e,R.index.name),X=K(y,a`SELECT ${Ue} AS value, ${at} AS count FROM ${a.identifier(Y)} WHERE ${Oe} = ${P}`).toArray()[0];return st(t.op,X)}}sn(l,t.field,`aggregate(${e}, { op: "${t.op}", field: "${t.field}" })`);const m=Z(f,ue),A=Pe(t.op),C=fe(t.field);let I=a`SELECT ${a.raw(A)}(${C}) AS value FROM ${a.identifier(e)}`;m&&(I=a`${I} WHERE ${m}`);const D=K(y,I).toArray()[0]?.value;return D??null},asId(e,t){const i=cn(d,e,t);if(i===null)throw new $("BAD_REQUEST",`asId("${e}", …): "${t}" is not a valid id for table "${e}"`,{status:400});return i},async count(e,t){const i=H(e,"count");if(i)return k(e,G),i.count(e,t);const l=d.tables[e];if(!l)throw new $("INTERNAL",`unknown table: ${e}`);const w=Gn(t);if(w.restrictsCounts)throw new ct(e);k(e,G);const p=Ae(l.softDeleteMode,void 0),f=Q(Q(w.baseWhere,w.where),p),h=await De(f,e,w.relationBaseWhere),m=h!==f;if(l.aggregateIndexes&&!w.baseWhere&&!m){const T=Hn(l.aggregateIndexes,w.where);if(T){tt(e,T.index);const D=it(T.index.by??[],T.key),R=rt(e,T.index.name),P=K(y,a`SELECT ${Ue} AS value FROM ${a.identifier(R)} WHERE ${Oe} = ${D}`).toArray();return P[0]===void 0?0:P[0].value??0}}const A=Z(h,ue);let C=a`SELECT COUNT(*) AS count FROM ${a.identifier(e)}`;return A&&(C=a`${C} WHERE ${A}`),K(y,C).one().count},async delete(e,t,i){_(e,"ctx.db.delete(table, id)");const l=re(t,e);if(!l){const T=Te(e);T&&await ot(T,e,[t],i);return}const{docJson:w,row:p,tableName:f}=l,h=d.tables[f],m=i?.hard===!0,A=!m&&h?.softDeleteMode?h:void 0,C=A?.softDeleteMode?.field;if(C&&p[C]!==null&&p[C]!==void 0)return;if(ne(f,"before","delete")&&await oe("before","delete",{id:t,op:"delete",previous:p,table:f}),i?.skipOnDelete!==!0&&await Go({deletedId:t,deletedReference:T=>p[T],findHolders:async(T,D,R,P)=>(await et(T).findMany(T,{...P,includeDeleted:m,where:{[D]:R}})).page,onCascade:(T,D)=>et(T).delete(T,D,i),onRestrict:T=>{throw new se(T,"restrict")},onSetNull:(T,D,R)=>et(T).patch(T,D,{[R]:null}),schema:d,tableName:f}),Se(f),ve(f),A&&C){const T={[C]:Ee()},D={...p,...ee(f),...T,_id:t};ut(A,T,D,ce),Ne(y,f,Zt(f),[le(D),t,w]),Fe(f,t,D,p),Le(f,t,void 0),ke(f,p,D),_e(f,t,p,void 0);const R=N(f,p,D);me?.invalidate(f,t,R),Re(f,t,"update",D),b({indexKeys:R,key:t,op:"update",row:D,table:f}),ne(f,"after","delete")&&await oe("after","delete",{id:t,op:"delete",previous:p,table:f}),await ye({id:t,op:"delete",table:f});return}Ne(y,f,yr(f),[t,w]),Fe(f,t,void 0),Le(f,t,void 0),ke(f,p,void 0),_e(f,t,p,void 0);const I=N(f,p);me?.invalidate(f,t,I),Re(f,t,"delete"),b({indexKeys:I,key:t,op:"delete",table:f}),ne(f,"after","delete")&&await oe("after","delete",{id:t,op:"delete",previous:p,table:f}),await ye({id:t,op:"delete",table:f})},async deleteAll(e,t){if(!d.tables[e])throw new $("INTERNAL",`unknown table: ${e}`);if(s!==void 0)return E().deleteAll(e,t);const i=Math.max(1,t?.chunkSize??$n),l=t?.hard===void 0?void 0:{hard:t.hard},w=H(e,"deleteAll");let p=0;for(;;){const h=(await O.findMany(e,{includeDeleted:t?.hard===!0,limit:i})).page.map(m=>String(m._id));if(h.length===0)break;for(const m of h)await(w===void 0?O.delete(e,m,l):ot(w,e,[m],l)),p+=1;if(h.length<i)break}return{deleted:p}},async deleteMany(e,t,i){_(e,"ctx.db.deleteMany(table, ids)"),He(t.length,i?.limit,"deleteMany");for(const l of t)await O.delete(e,l);return{deleted:t.length}},async deleteWhere(e,t,i){const l=H(e,"deleteWhere"),p=(await on(l??O,e,t,i?.limit,"deleteWhere")).map(f=>String(f._id));if(l)return ot(l,e,p,void 0,{options:i});if(O.deleteMany===void 0)throw new $("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return O.deleteMany(e,p,i)},async findFirst(e,t={}){return(await O.findMany(e,{...t,limit:1,omitContinueCursor:!0})).page[0]??null},async findFirstOrThrow(e,t={}){const i=await O.findFirst(e,t);if(i===null)throw new wo(`findFirstOrThrow: no "${e}" document matched`);return i},async findMany(e,t={}){const i=H(e,"findMany");if(i)return k(e,G),t.consistency==="primary"&&S(e,Zn),i.findMany(e,t);const l=d.tables[e];if(!l)throw new $("INTERNAL",`unknown table: ${e}`);const w=!t.where&&!t.baseWhere;w?k(e,G):k(e);const{limit:p,orderKeys:f,statement:h}=await qt(e,l,t,k),m=he(y,h.text,...h.params).toArray();w&&s?.recordRead(m.length);const A=[];for(const I of m){const T=xe(I);T&&(A.push(T),!w&&typeof T._id=="string"&&k(e,T._id))}const C=Fo(A,{endCursor:t.endCursor,limit:p,omitContinueCursor:t.omitContinueCursor,orderKeys:f});return t.with&&await Uo({fetcher:xt,groupedCounter:Dn,parents:C.page,...Oo(t),schema:d,tableName:e,with:t.with}),{...C,page:En(C.page,t.select,t.with)}},async explain(e,t={}){const i=H(e,"explain");if(i)return i.explain(e,t);const l=d.tables[e];if(!l)throw new $("INTERNAL",`unknown table: ${e}`);const{statement:w}=await qt(e,l,t,()=>{}),p=he(y,`EXPLAIN QUERY PLAN ${w.text}`,...w.params).toArray();return{params:w.params,plan:p.map(f=>String(f.detail)),sql:w.text}},async get(e,t){_(e,"ctx.db.get(table, id)");const i=re(t,e);if(!i){const l=Te(e);return l?l.get(e,t):(M(e),S(e,t,!0),null)}return pe(i,t),i.row},async lookupById(e,t){const i=re(e,t);if(!i){for(const l of Bt(t))M(l),S(l,e,!0);return null}return pe(i,e),{row:i.row,tableName:i.tableName}},async groupBy(e,t){const i=H(e,"groupBy");if(i)return k(e,G),i.groupBy(e,t);const l=d.tables[e];if(!l)throw new $("INTERNAL",`unknown table: ${e}`);k(e,G);const w=t.agg??{op:"count"};if(Pe(w.op),w.op!=="count"&&!w.field)throw new $("INTERNAL",`groupBy(${e}, { agg: { op: "${w.op}" } }): "field" is required for non-count reducers`);const p=Ae(l.softDeleteMode,void 0),f=Q(Q(t.baseWhere,t.where),p),h=await De(f,e,t.relationBaseWhere),m=h!==f;if(l.aggregateIndexes&&!t.baseWhere&&!m){const R=jn(l.aggregateIndexes,w.op,w.field,t.by,t.where),P=R===void 0?0:Object.keys(R.partial).length,Y=R?.index.by?.length??0;if(R&&(P===0||P===Y)){tt(e,R.index);const X=rt(e,R.index.name),V=Object.keys(R.partial),de=[];if(V.length===(R.index.by??[]).length&&V.length>0){const Be=it(R.index.by??[],R.partial),We=K(y,a`SELECT ${Ue} AS value, ${at} AS count FROM ${a.identifier(X)} WHERE ${Oe} = ${Be}`).toArray();return We.length>0&&de.push({key:{...R.partial},value:st(w.op,We[0])}),de}const Wn=K(y,a`SELECT ${Oe} AS key, ${Ue} AS value, ${at} AS count FROM ${a.identifier(X)}`).toArray();for(const Be of Wn){const We=Un(JSON.parse(Be.key));de.push({key:We,value:st(w.op,Be)})}return de}}for(const R of[...t.by,w.field]){if(R===void 0)continue;const P=R===w.field?`groupBy(${e}, { agg: { op: "${w.op}", field: "${R}" } })`:`groupBy(${e}, { by: [..."${R}"] })`;sn(l,R,P)}const A=Z(h,ue),C=t.by.map(R=>a`${fe(R)} AS ${a.identifier(R)}`);if(w.op==="count")C.push(a`COUNT(*) AS value`);else{const{field:R}=w;if(R===void 0)throw new $("INTERNAL",`groupBy(${e}, { agg: { op: "${w.op}" } }): "field" is required for non-count reducers`);C.push(a`${a.raw(Pe(w.op))}(${fe(R)}) AS value`)}let I=a`SELECT ${a.join(C,a`, `)} FROM ${a.identifier(e)}`;A&&(I=a`${I} WHERE ${A}`),I=a`${I} GROUP BY ${a.join(t.by.map(R=>fe(R)),a`, `)}`;const T=K(y,I).toArray(),D=[];for(const R of T){const P={};for(const X of t.by)P[X]=no(l.shape[X],R[X]??null);const{value:Y}=R;D.push({key:P,value:Y==null?null:Number(Y)})}return D},async insert(e,t,i){const l=H(e,"insert");if(l)return It(l,e,t,i,!0);const w=d.tables[e];if(!w)throw new $("INTERNAL",`unknown table: ${e}`);const p=i?.allowExplicitId===!0,f=Ge(w,pt(w,t,ce),{supplied:t,trusted:p});let h;i?.clientId!==void 0?(vr(i.clientId),h=i.clientId):i?.allowExplicitId&&typeof f._id=="string"?(yt(f._id),h=f._id):h=St();const m=i?.allowExplicitId&&typeof f._creationTime=="number"?f._creationTime:Ee(),A={...f,...ee(e),_creationTime:m,_id:h};return ne(e,"before","insert")&&await oe("before","insert",{doc:{...A},id:h,op:"insert",table:e}),p||W(e,A),Se(e),ve(e),mt(y,e,pr(e),[h,m,le(A)]),Lt(e,h,A),ne(e,"after","insert")&&await oe("after","insert",{doc:A,id:h,op:"insert",table:e}),await ye({doc:A,id:h,op:"insert",table:e}),h},async insertManyUnsafe(e,t,i){if(He(t.length,i?.limit,"insertManyUnsafe"),t.length===0)return[];const l=H(e,"insert");if(l){const m=[];_r(d.tables[e],t,i?.allowExplicitId,ce);for(const A of t)J(A);for(const A of t){const C=await l.insert(e,A,{allowExplicitId:i?.allowExplicitId});b({key:C,op:"insert",row:{...A,_id:C},table:e}),m.push(C)}return m}const w=d.tables[e];if(!w)throw new $("INTERNAL",`unknown table: ${e}`);Se(e),ve(e);const p=[];for(let m=0;m<t.length;m+=je)p.push(ee(e));const f=i?.allowExplicitId===!0?void 0:Po(w),h=t.map((m,A)=>{const C=pt(w,m,ce),I=f===void 0?C:Ge(f,C,{supplied:m}),T=i?.allowExplicitId===!0&&typeof I._id=="string"?I._id:void 0;T!==void 0&&yt(T);const D=T??St(),R=i?.allowExplicitId===!0&&typeof I._creationTime=="number"?I._creationTime:Ee(),P={...I,...p[Math.floor(A/je)],_creationTime:R,_id:D};return{creationTime:R,document:P,id:D}});for(const m of h)J(m.document);for(let m=0;m<h.length;m+=je){const A=a.join(h.slice(m,m+je).map(I=>a`(${I.id}, ${I.creationTime}, ${le(I.document)})`),a`, `),C=gn("sqlite",a`INSERT INTO ${a.identifier(e)} (id, _creationTime, ${a.identifier(ie)}) VALUES ${A}`);mt(y,e,C.sql,C.params)}for(const{document:m,id:A}of h)Lt(e,A,m),await ge({doc:m,id:A,op:"insert",table:e});return h.map(m=>m.id)},async insertMany(e,t,i){He(t.length,i?.limit,"insertMany");const l=i?.skipDuplicates===!0,w=[],p=H(e,"insert");if(p)for(const h of t)J(h);const f=async h=>p?It(p,e,h,void 0,!1):O.insert(e,h);for(const h of t)try{w.push(await f(h))}catch(m){if(l&&m instanceof se&&m.kind==="unique")w.push(null);else throw m}return w},normalizeId(e,t){return cn(d,e,t)},async patch(e,t,i,l){_(e,"ctx.db.patch(table, id, values)");const w=re(t,e);if(!w){const D=Te(e);if(D){J(i),await D.patch(e,t,i,l);return}throw new $("NOT_FOUND",`document not found: ${t}`)}const{docJson:p,row:f,tableName:h}=w,m=d.tables[h];if(!m)throw new $("INTERNAL",`unknown table: ${h}`);if(k(h,t),dn("patch",i),Tt(h,t,i,f)){o?.({fields:Object.keys(Ke(i)),id:t,table:h});return}const A=po(m,i,f),C={...f,...Ke(A),...ee(h),_id:t};ut(m,A,C,ce);const I=Ge(m,C,{only:new Set(Object.keys(A)),previous:()=>f,tolerateStoredNull:!0});go(l,f,I),ne(h,"before","update")&&await oe("before","update",{doc:{...I},id:t,op:"update",previous:f,table:h}),W(h,I,f),Se(h),ve(h),Ne(y,h,Zt(h),[le(I),t,p]),Fe(h,t,I,f),Le(h,t,I),ke(h,f,I),_e(h,t,f,I);const T=N(h,f,I);me?.invalidate(h,t,T),Re(h,t,"update",I),b({indexKeys:T,key:t,op:"update",row:I,table:h}),ne(h,"after","update")&&await oe("after","update",{doc:I,id:t,op:"update",previous:f,table:h}),await ye({doc:I,id:t,op:"update",table:h})},async patchIf(e,t,i){const l=H(e,"patchIf");if(l){if(l.patchIf===void 0)throw new $("INTERNAL",`ctx.db.patchIf on global table '${e}' is unsupported: its backend has no conditional write`);return J(i.patch),l.patchIf(e,t,i)}if(!d.tables[e])throw new $("INTERNAL",`unknown table: ${e}`);for(let w=1;w<=an;w+=1){const p=await Fn(e,t,i,w<an,f=>O.patch(e,t,f,{verify:i.verify}));if(p!==void 0)return p}throw new se(`patchIf on "${e}" kept conflicting; the row changed on every attempt`,"occ")},async patchMany(e,t,i){_(e,"ctx.db.patchMany(table, patches)"),He(t.length,i?.limit,"patchMany");for(const l of t)await O.patch(e,l.id,l.patch);return{patched:t.length}},async patchWhere(e,t,i){const l=H(e,"patchWhere")??O,p=(await on(l,e,t.where,i?.limit,"patchWhere")).map(f=>({id:String(f._id),patch:t.patch}));if(O.patchMany===void 0)throw new $("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await O.patchMany(e,p,i),{patched:p.length}},async related(e,t){return Lo(O,v,e,t)},relationEdges:v,deleteRereadTables:B,inTransaction:j,softDeleteFields:U,relationWrites:q,query(e){const t=H(e,"query");return t?(k(e,G),t.query(e)):xn(y,d,e,te,i=>{i?F(i):k(e,G)},i=>{s?.recordRead(i)})},async rank(e,t,i){const l=H(e,"rank");if(te(e,t,"rank"),l)return k(e,G),l.rank(e,t,i);const w=d.tables[e];if(!w)throw new $("INTERNAL",`unknown table: ${e}`);const p=w.rankIndexes?.find(V=>V.name===t);if(!p)throw new $("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(Ft(e,w,p),i.restrictsCounts)throw new ct(e);k(e,G),nt(e,p);const f=typeof i.row=="string"?i.row:i.row._id;if(!f)return null;const h=Nt(e,p.name),m=p.sortBy.map((V,de)=>Qt(de)),A=m.map(V=>Me(V)).join(", "),C=K(y,a`SELECT ${a.identifier("__partition__")}, ${a.raw(A)} FROM ${a.identifier(h)} WHERE ${a.identifier("__id__")} = ${f}`).toArray(),[I]=C;if(I===void 0)return null;let T=I.__partition__;const D=Q(i.baseWhere,i.where);dt(D,d,e,"rank");const R=vo(p,D);if(R){const V=_o(p.partitionBy??[],R);if(V!==T)return null;T=V}const P=m.map(V=>I[V]),{before:Y,total:X}=un(y,h,m,p.sortBy,T,P,f);return{position:Y+1,total:X}},async rankBefore(e,t,i){if(ae(e))throw new $("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const l=d.tables[e];if(!l)throw new $("INTERNAL",`unknown table: ${e}`);const w=l.rankIndexes?.find(m=>m.name===t);if(!w)throw new $("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(i.restrictsCounts)throw new ct(e);k(e,G),nt(e,w);const p=Nt(e,w.name),f=w.sortBy.map((m,A)=>Qt(A)),h=w.sortBy.map((m,A)=>Ce(i.sortValues[A]??null));return un(y,p,f,w.sortBy,i.partitionKey,h,i.rowId)},async rankPage(e,t,i={}){dt(Q(i.baseWhere,i.where),d,e,"rankPage");const l=H(e,"rankPage");if(te(e,t,"rank"),l)return k(e,G),l.rankPage(e,t,i);const{continueCursor:w,hasMore:p,rows:f}=Ot(Wt,e,t,i);return{continueCursor:w,isDone:!p,page:f.map(h=>h.doc)}},async rankPageRows(e,t,i={}){dt(Q(i.baseWhere,i.where),d,e,"rankPage"),te(e,t,"rank");const{directions:l,hasMore:w,rows:p}=Ot(Wt,e,t,i);return{directions:l,hasMore:w,rows:p}},async restore(e,t){_(e,"ctx.db.restore(table, id)");const i=re(t,e);if(!i){const p=Te(e);if(p?.restore){await p.restore(e,t);return}throw new $("NOT_FOUND",`document not found: ${t}`)}const l=d.tables[i.tableName]?.softDeleteMode?.field;if(!l)throw new $("INTERNAL",`ctx.db.restore: table "${i.tableName}" is not a .softDelete() table`);const w=i.row[l]!==null&&i.row[l]!==void 0;await O.patch(e,t,{[l]:null}),w&&_e(i.tableName,t,void 0,i.row)},async replace(e,t,i,l){_(e,"ctx.db.replace(table, id, document)");const w=re(t,e);if(!w){const P=Te(e);if(P){J(i),await P.replace(e,t,i,l);return}throw new $("NOT_FOUND",`document not found: ${t}`)}const{docJson:p,row:f,tableName:h}=w,m=d.tables[h];if(!m)throw new $("INTERNAL",`unknown table: ${h}`);dn("replace",i);const A=l?.allowExplicitId&&typeof i._creationTime=="number"?i._creationTime:void 0,C=typeof f._creationTime=="number"?f._creationTime:void 0,I=A??C??Ee(),T={...i,...ee(h),_creationTime:I,_id:t};ut(m,i,T,ce);const D=l?.allowExplicitId===!0,R=Ge(m,T,{previous:()=>f,supplied:i,trusted:D});ne(h,"before","update")&&await oe("before","update",{doc:{...R},id:t,op:"update",previous:f,table:h}),D||W(h,R,f),Se(h),ve(h),Ne(y,h,gr(h),[I,le(R),t,p]),Fe(h,t,R,f),Le(h,t,R),ke(h,f,R),_e(h,t,f,R),me?.invalidate(h,t,N(h,f,R)),Re(h,t,"update",R),b({indexKeys:N(h,f,R),key:t,op:"update",row:R,table:h}),ne(h,"after","update")&&await oe("after","update",{doc:R,id:t,op:"update",previous:f,table:h}),await ye({doc:R,id:t,op:"update",table:h})},async wipeShard(e){const t=new Set(e?.exclude),i=e?.tables,l=Object.entries(d.tables).filter(([h,m])=>t.has(h)||i!==void 0&&!i.includes(h)?!1:m.shardMode?.kind!=="global").map(([h])=>h);if(i!==void 0){for(const h of i)if(!d.tables[h])throw new $("INTERNAL",`wipeShard: unknown table: ${h}`)}const w={};let p=0;const{deleteAll:f}=O;if(f===void 0)throw new $("INTERNAL","wipeShard: this writer has no deleteAll");for(const h of l){const m=await f(h,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});w[h]=m.deleted,p+=m.deleted}return{deleted:p,tables:w}}},Bn={db:O,scheduler:vt};return n.enforceRls===!0?Ho(O,d,(e,t)=>re(e,t)?.tableName,v):O};export{Qi as CDC_LOG_TABLE,ps as IDEMPOTENCY_TABLE,Br as NotUniqueError,us as advanceClientWatermark,Vi as applyCdcChanges,dn as assertNoExplicitUndefined,yt as assertStorableRowId,vr as assertValidClientId,ji as backfillAggregateIndexes,Hi as backfillRankIndexes,Ki as backfillSearchIndexes,Ji as bumpCdcEpoch,zi as cdcCanVouchFor,Yi as cdcForkedError,Xi as cdcSeqLeavingRows,Zi as cdcTouchesTables,es as cdcTrimmedError,ts as compactCdcDocs,ti as createShardCtxDb,ns as cursorBelowRetainedFloor,Qr as meterReadBytes,fs as migrateClientWatermark,os as minCdcReplayableSeq,rs as minCdcSeq,cn as normalizeIdStructurally,is as readCdcChangeKeys,ss as readCdcChanges,cs as readCdcCursor,as as readCdcEpoch,hs as readClientWatermark,gs as readIdempotent,$s as runShardMigrations,Ss as selectShapeMembers,vs as selectShapeRows,Ke as stripReservedPatchFields,ds as trimCdcChanges,ys as trimIdempotent,ms as writeIdempotent};
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import{runSql as o,orNull as a,decodeJsonColumn as _}from"./runDrizzle-RC09zZrh.mjs";const s="__lunora_queue_messages",n=500,E=128*1024,T="… [truncated by the dev queue catcher]",c="[unserializable message body]",R=e=>{if(e===void 0)return"null";try{const r=JSON.stringify(e);return r.length>E?JSON.stringify(`${r.slice(0,E)}${T}`):r}catch{return JSON.stringify(c)}},g=e=>typeof e=="string"&&(e===c||e.endsWith(T)),u=e=>{o(e,`CREATE TABLE IF NOT EXISTS "${s}" (
|
|
2
|
+
id TEXT PRIMARY KEY,
|
|
3
|
+
captured_at INTEGER NOT NULL,
|
|
4
|
+
message_id TEXT NOT NULL,
|
|
5
|
+
queue TEXT NOT NULL,
|
|
6
|
+
export_name TEXT,
|
|
7
|
+
body TEXT NOT NULL,
|
|
8
|
+
attempts INTEGER NOT NULL,
|
|
9
|
+
outcome TEXT NOT NULL,
|
|
10
|
+
error TEXT,
|
|
11
|
+
dead_lettered INTEGER NOT NULL,
|
|
12
|
+
message_ts INTEGER NOT NULL
|
|
13
|
+
)`)},p=(e,r,d)=>{u(e);for(const t of r)o(e,`INSERT INTO "${s}" (id, captured_at, message_id, queue, export_name, body, attempts, outcome, error, dead_lettered, message_ts)
|
|
14
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,crypto.randomUUID(),d,t.messageId,t.queue,a(t.exportName),R(t.body),t.attempts,t.outcome,a(t.error),t.deadLettered===!0?1:0,t.timestamp);return o(e,`DELETE FROM "${s}"
|
|
15
|
+
WHERE id NOT IN (
|
|
16
|
+
SELECT id FROM "${s}" ORDER BY captured_at DESC, id DESC LIMIT ?
|
|
17
|
+
)`,n),{recorded:r.length}},i=e=>({attempts:e.attempts,body:_(e.body),capturedAt:e.captured_at,deadLettered:e.dead_lettered===1,error:e.error??void 0,exportName:e.export_name??void 0,id:e.id,messageId:e.message_id,outcome:e.outcome,queue:e.queue,timestamp:e.message_ts}),y=(e,r={})=>{u(e);const d=Math.min(Math.max(r.limit??100,1),n),t=typeof r.queue=="string"&&r.queue.length>0?r.queue:void 0,m=t===void 0?"":"WHERE queue = ?",N=t===void 0?[d]:[t,d];return{entries:o(e,`SELECT * FROM "${s}" ${m} ORDER BY captured_at DESC, id DESC LIMIT ?`,...N).toArray().map(L=>i(L))}},S=(e,r)=>{u(e);const t=o(e,`SELECT * FROM "${s}" WHERE id = ? LIMIT 1`,r).toArray()[0];return t===void 0?void 0:i(t)},U=e=>(u(e),o(e,`DELETE FROM "${s}"`),{cleared:!0});export{E as MAX_BODY_CHARS,n as QUEUE_RETENTION,s as QUEUE_TABLE,U as clearQueueMessages,u as ensureQueueTable,g as isLossyBody,S as readQueueMessageById,y as readQueueMessages,p as recordQueueMessages};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{sql as s}from"drizzle-orm";import{matchesStaticWhere as f}from"./AGGREGATE_SQL_FUNCTION-C_ZipS9R.mjs";import{compareStrings as l}from"./aggregateTableName-B_CtIQCS.mjs";import{serializeSqlValue as d}from"./serializeSqlValue-DeoBMpZ2.mjs";const a=Symbol("not-resolvable"),m=r=>{if(r!==null&&typeof r=="object"&&!Array.isArray(r)){const t=Object.keys(r);return t.length===1&&t[0]==="eq"?r.eq:a}return r},y=(r,t)=>{if(r.length===0)return"";const e={};for(const n of r.toSorted(l))e[n]=t[n]??null;return JSON.stringify(e)},k="__id__",N=r=>`__sort_k${String(r)}__`,h=(r,t)=>{const e=r.partitionBy??[],n=t??{};for(const o of Object.keys(n))if(o==="AND"||o==="OR"||o==="NOT")return;const i={};for(const o of e)if(o in n){const c=m(n[o]);if(c===a)return;i[o]=c}else if(r.where&&o in r.where)i[o]=r.where[o];else return;return i},O=(r,t)=>`${r}__rank_${t}`,$=(r,t)=>({partitionKey:y(r.partitionBy??[],t),rowId:t._id,sortValues:r.sortBy.map(e=>d(t[e.field]??null))}),K=(r,t,e,n)=>{const i=e!=="desc"===n;if(t==null)return i?s`${s.identifier(r)} IS NOT NULL`:void 0;const o=s`${s.identifier(r)} ${s.raw(i?">":"<")} ${t}`;return i?o:s`(${o} OR ${s.identifier(r)} IS NULL)`},R=f;export{k as RANK_TIEBREAK,y as encodePartitionKey,R as matchesRankStaticWhere,$ as rankKeyFromDoc,K as rankPivotConditionSql,O as rankTableName,h as resolveRankPartition,N as sortColumnName};
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import{sql as t}from"drizzle-orm";import{runDrizzle as o}from"./runDrizzle-RC09zZrh.mjs";const a="__reactor_state",c=[["runs","runs INTEGER NOT NULL DEFAULT 0"],["suppressed","suppressed INTEGER NOT NULL DEFAULT 0"],["errors","errors INTEGER NOT NULL DEFAULT 0"],["last_ran_at","last_ran_at INTEGER NOT NULL DEFAULT 0"],["last_error","last_error TEXT"]],O=r=>{o(r,t`CREATE TABLE IF NOT EXISTS ${t.identifier(a)} (
|
|
2
|
+
path TEXT PRIMARY KEY,
|
|
3
|
+
digest TEXT NOT NULL,
|
|
4
|
+
tables TEXT NOT NULL,
|
|
5
|
+
runs INTEGER NOT NULL DEFAULT 0,
|
|
6
|
+
suppressed INTEGER NOT NULL DEFAULT 0,
|
|
7
|
+
errors INTEGER NOT NULL DEFAULT 0,
|
|
8
|
+
last_ran_at INTEGER NOT NULL DEFAULT 0,
|
|
9
|
+
last_error TEXT
|
|
10
|
+
)`);const e=new Set(o(r,t`PRAGMA table_info(${t.identifier(a)})`).toArray().map(s=>s.name));for(const[s,i]of c)e.has(s)||o(r,t`ALTER TABLE ${t.identifier(a)} ADD COLUMN ${t.raw(i)}`)},R=r=>{if(typeof r=="string")try{const e=JSON.parse(r);return Array.isArray(e)&&e.every(s=>typeof s=="string")?e:void 0}catch{return}},T=r=>typeof r=="number"&&Number.isFinite(r)?r:0,d=r=>({digest:r.digest,...typeof r.last_error=="string"&&r.last_error.length>0?{lastError:r.last_error}:{},lastRanAt:T(r.last_ran_at),stats:{errors:T(r.errors),runs:T(r.runs),suppressed:T(r.suppressed)},tables:R(r.tables)}),l="path, digest, tables, runs, suppressed, errors, last_ran_at, last_error",f=(r,e)=>{const[s]=o(r,t`SELECT ${t.raw(l)} FROM ${t.identifier(a)} WHERE path = ${e}`);if(!(s===void 0||typeof s.digest!="string"))return d(s)},U=r=>o(r,t`SELECT ${t.raw(l)} FROM ${t.identifier(a)} ORDER BY path`).toArray().filter(e=>typeof e.digest=="string").map(e=>({path:e.path,state:d(e)})),g=(r,e,s)=>{const{digest:i,error:p,now:u,result:n,tables:E}=s,L=i??"",N=E===void 0?"":JSON.stringify([...E]),_=p??null;o(r,t`INSERT INTO ${t.identifier(a)} (path, digest, tables, runs, suppressed, errors, last_ran_at, last_error)
|
|
11
|
+
VALUES (
|
|
12
|
+
${e},
|
|
13
|
+
${L},
|
|
14
|
+
${N},
|
|
15
|
+
${n==="ran"?1:0},
|
|
16
|
+
${n==="suppressed"?1:0},
|
|
17
|
+
${n==="error"?1:0},
|
|
18
|
+
${u},
|
|
19
|
+
${_}
|
|
20
|
+
)
|
|
21
|
+
ON CONFLICT(path) DO UPDATE SET
|
|
22
|
+
digest = ${i===void 0?t.raw(`${a}.digest`):t`excluded.digest`},
|
|
23
|
+
tables = ${E===void 0?t.raw(`${a}.tables`):t`excluded.tables`},
|
|
24
|
+
runs = ${t.raw(`${a}.runs`)} + ${n==="ran"?1:0},
|
|
25
|
+
suppressed = ${t.raw(`${a}.suppressed`)} + ${n==="suppressed"?1:0},
|
|
26
|
+
errors = ${t.raw(`${a}.errors`)} + ${n==="error"?1:0},
|
|
27
|
+
last_ran_at = excluded.last_ran_at,
|
|
28
|
+
last_error = ${n==="error"?t`excluded.last_error`:t.raw("NULL")}`)},S=(r,e)=>r?.tables===void 0?!0:r.tables.some(s=>e.has(s));export{a as REACTOR_STATE_TABLE,U as listReactorStates,O as migrateReactorState,S as reactorNeedsRun,f as readReactorState,g as writeReactorState};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as h}from"@lunora/errors";import{mergeWhere as A}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{decodeCursor as S,CURSOR_PREFIX as v,toBase64 as B}from"./CURSOR_PREFIX-rOdoinP8.mjs";const O=4,C=1,L=50,$=200,T=1e4,x=.5,D=t=>{if(t.kind==="id"){const e=t._meta?.tableName;return typeof e=="string"&&e.length>0?{array:!1,targetTable:e}:void 0}if(t.kind!=="array"&&t.kind!=="optional")return;const n=t._meta?.inner,r=n===void 0?void 0:D(n);if(r!==void 0)return{array:r.array||t.kind==="array",targetTable:r.targetTable}},X=t=>{const n=[];for(const[r,e]of Object.entries(t.tables))for(const[s,o]of Object.entries(e.shape)){const a=D(o);a===void 0||t.tables[a.targetTable]===void 0||n.push({array:a.array,column:s,name:`${r}.${s}`,sourceTable:r,targetTable:a.targetTable})}return n},N=t=>v+B(JSON.stringify([t])),U=t=>{const[n]=S(t);if(typeof n!="number"||!Number.isInteger(n)||n<0)throw new h("INVALID_CURSOR","invalid cursor");if(n>T)throw new h("BAD_REQUEST",`ctx.db.related: cursor offset ${String(n)} exceeds the maximum of ${String(T)} — narrow the walk with \`edges\` or \`direction\` instead of paging past it`);return n},k=(t,n,r,e)=>{if(t===void 0)return n;if(!Number.isInteger(t)||t<1||t>r)throw new h("BAD_REQUEST",`ctx.db.related: \`${e}\` must be an integer between 1 and ${String(r)}, got ${String(t)}`);return t},M=(t,n)=>{if(n===void 0)return[...t];const r=new Set(t.map(o=>o.name)),e=n.filter(o=>!r.has(o));if(e.length>0)throw new h("BAD_REQUEST",`ctx.db.related: unknown edge ${e.length===1?"name":"names"}: ${e.join(", ")}`);const s=new Set(n);return t.filter(o=>s.has(o.name))},W=(t,n)=>{const r=t[n.column];return n.array?Array.isArray(r)?r.filter(e=>typeof e=="string"&&e.length>0):[]:typeof r=="string"&&r.length>0?[r]:[]},I=async(t,n,r,e)=>{const s=await t.findMany(n,{limit:e.limit,omitContinueCursor:!0,where:A(r,e.relationBaseWhere?.(n))??r});return e.mask?.(n,s.page)??s.page},F={in:{keyColumn:t=>t.column,keysOf:(t,n)=>n.array||t.table!==n.targetTable?[]:[t.id],skipVisitedKeys:!1,table:t=>t.sourceTable},out:{keyColumn:()=>"_id",keysOf:(t,n)=>t.table===n.sourceTable?W(t.document,n):[],skipVisitedKeys:!0,table:t=>t.targetTable}},_=async(t,n,r,e,s)=>{const o=F[s],a=o.keyColumn(r),l=o.table(r),u=new Map;for(const c of n)for(const i of o.keysOf(c,r))!u.has(i)&&!(o.skipVisitedKeys&&e.visited.has(i))&&u.set(i,c);if(u.size===0)return[];const f=await I(t,l,{[a]:{in:[...u.keys()]}},e),m=[];for(const c of f){const i=c._id,g=c[a],d=typeof g=="string"?u.get(g):void 0;typeof i!="string"||d===void 0||e.visited.has(i)||(e.visited.add(i),m.push({document:c,id:i,path:[...d.path,r.name],pathIds:[...d.pathIds,i],table:l}))}return m},Q=async(t,n,r,e)=>{const s=[],o=()=>e.budget-s.length,a=()=>({limit:o(),mask:e.mask,relationBaseWhere:e.relationBaseWhere,visited:e.visited});for(const l of r)e.direction!=="in"&&o()>0&&s.push(...await _(t,n,l,a(),"out")),e.direction!=="out"&&o()>0&&s.push(...await _(t,n,l,a(),"in"));return s},H=async(t,n)=>{const r=n._id;if(typeof r=="string"&&r.length>0){const o=await t.lookupById?.(r);if(!o)throw new h("BAD_REQUEST","ctx.db.related: could not resolve the start document's table from its `_id` — pass `{ table, id }` instead");return{id:r,table:o.tableName}}const{id:e,table:s}=n;if(typeof s!="string"||s.length===0||typeof e!="string"||e.length===0)throw new h("BAD_REQUEST","ctx.db.related: `start` must be a loaded document or `{ table, id }`");return{id:e,table:s}},j=async(t,n,r,e={})=>{const s=k(e.depth,C,O,"depth"),o=k(e.limit,L,$,"limit"),a=e.cursor?U(e.cursor):0,l=e.direction??"both",u=M(n,e.edges),{id:f,table:m}=await H(t,r),[c]=await I(t,m,{_id:f},{limit:1,mask:e.relationMask,relationBaseWhere:e.relationBaseWhere,visited:new Set});if(c===void 0)throw new h("NOT_FOUND",`ctx.db.related: no "${m}" row with id ${f}`);const i=a+o+1,g=new Set([f]),d=[];let w=[{document:c,id:f,path:[],pathIds:[f],table:m}];for(let b=1;b<=s&&w.length>0&&d.length<i;b+=1){const p=await Q(t,w,u,{budget:i-d.length,direction:l,mask:e.relationMask,relationBaseWhere:e.relationBaseWhere,visited:g}),R=x**(b-1);for(const y of p)d.push({depth:b,document:y.document,path:y.path,pathIds:y.pathIds,score:R,table:y.table});w=p}const E=d.length<=a+o;return{continueCursor:E?null:N(a+o),isDone:E,nodes:d.slice(a,a+o)}};export{L as RELATED_DEFAULT_LIMIT,x as RELATED_DEPTH_DECAY,O as RELATED_MAX_DEPTH,$ as RELATED_MAX_LIMIT,T as RELATED_MAX_OFFSET,X as deriveRelationEdges,j as findRelated};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const E=Symbol("lunora.seekRange"),o="__relationExists";export{o as RELATION_EXISTS_KEY,E as SEEK_RANGE};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{c as i}from"./constant-time-equal-BRh9yUCr.mjs";const a=(t,e)=>{if(t.size<e)return;const n=t.keys().next().value;n!==void 0&&t.delete(n)},l=(t,e,n,o)=>{const s=t.get(e);if(s!==void 0)return s;a(t,o);const r=n().catch(c=>{throw t.get(e)===r&&t.delete(e),c});return t.set(e,r),r},E=new TextEncoder,d=64,u=new Map,y=async t=>l(u,t,async()=>crypto.subtle.importKey("raw",E.encode(t),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]),d),g="LUNORA_RELAY_SECRET",w="x-lunora-relay-sig",f=t=>{const e=t?.[g];return typeof e=="string"&&e.length>0?e:void 0},A=async(t,e)=>{const n=await crypto.subtle.sign("HMAC",await y(t),new TextEncoder().encode(e));return[...new Uint8Array(n)].map(o=>o.toString(16).padStart(2,"0")).join("")},S=async(t,e,n)=>{const o=f(t);return o===void 0?!0:e===null?!1:i(e,await A(o,n))};export{w as RELAY_SIGNATURE_HEADER,f as siblingSecretOf,A as signSiblingBody,S as verifySiblingBody};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const o="__lunora_reproject__",e=t=>`${o}${t}`,n=t=>{if(!t.startsWith(o))return;const r=t.slice(o.length);return r===""?void 0:r};export{o as REPROJECTION_MIGRATION_PREFIX,e as reprojectionMigrationId,n as reprojectionMigrationTable};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as f}from"@lunora/errors";import{findRelated as y}from"./RELATED_DEFAULT_LIMIT-CAh3WUMn.mjs";const w=Symbol.for("lunora.ctxdb.rls-unwrap");class b extends f{table;constructor(o){super("RLS_REQUIRED",`ctx.db access to "${o}" 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=o}}const R=n=>Object.entries(n.tables).filter(([,o])=>o.shardMode?.kind!=="global").map(([o])=>o),m=(n,o,l)=>{const i=o?.tables,a=new Set(o?.exclude);for(const s of n)(i===void 0||i.includes(s))&&!a.has(s)&&l(s)},g={aggregate:"loop-gated",asId:"ungated",assertPatchAllowed:"inline-table-gated",cdcChangedTables:"ungated",count:"loop-gated",delete:"inline-table-gated",deleteAll:"loop-gated",deleteMany:"inline-table-gated",deleteWhere:"inline-table-gated",explain:"loop-gated",findFirst:"loop-gated",findFirstOrThrow:"loop-gated",findMany:"loop-gated",get:"inline-table-gated",groupBy:"loop-gated",insert:"loop-gated",insertMany:"loop-gated",insertManyUnsafe:"loop-gated",inTransaction:"ungated",lookupById:"id-gated",normalizeId:"ungated",patch:"inline-table-gated",patchIf:"loop-gated",patchMany:"inline-table-gated",patchWhere:"inline-table-gated",query:"loop-gated",rank:"loop-gated",rankBefore:"loop-gated",rankPage:"loop-gated",rankPageRows:"loop-gated",related:"rebound",relationEdges:"ungated",deleteRereadTables:"ungated",relationWrites:"ungated",softDeleteFields:"ungated",replace:"inline-table-gated",restore:"inline-table-gated",system:"ungated",wipeShard:"sweep-gated"},M=Object.entries(g).filter(([,n])=>n==="loop-gated").map(([n])=>n),S={related:(n,o)=>(...l)=>{const[i,a]=l;return y(n,o,i,a)}},E=Object.entries(g).filter(([,n])=>n==="rebound").map(([n])=>n),O=(n,o,l)=>{for(const i of E)typeof o[i]=="function"&&(n[i]=S[i](n,l))},k=(n,o,l,i=[])=>{if(o.rlsMode!=="required")return n;const a=n,s=e=>{const t=o.tables[e];return t!==void 0&&t.isPublic!==!0},d=e=>{if(s(e))throw new b(e)},p=async(e,t)=>{if(t!==void 0){d(t);return}const r=await l(e);r!==void 0&&d(r)},c={...n,delete:async(e,t,r)=>(d(e),await a.delete(e,t,r)),deleteMany:async(e,t,r)=>(d(e),await a.deleteMany(e,t,r)),deleteWhere:a.deleteWhere?async(e,t,r)=>(d(e),await a.deleteWhere?.(e,t,r)):void 0,get:async(e,t)=>(d(e),await a.get(e,t)),lookupById:async(e,t)=>(await p(e,t),a.lookupById?.(e,t)??null),patch:async(e,t,r,u)=>(d(e),await a.patch(e,t,r,u)),patchMany:async(e,t,r)=>(d(e),await a.patchMany(e,t,r)),assertPatchAllowed:async(e,t)=>(d(e),await a.assertPatchAllowed?.(e,t)),patchWhere:a.patchWhere?async(e,t,r)=>(d(e),await a.patchWhere?.(e,t,r)):void 0,replace:async(e,t,r,u)=>(d(e),await a.replace(e,t,r,u)),restore:async(e,t)=>(d(e),await a.restore?.(e,t))},h=a;for(const e of M){const t=h[e];typeof t=="function"&&(c[e]=(r,...u)=>(d(r),t.call(a,r,...u)))}if(O(c,a,i),a.wipeShard){const{wipeShard:e}=a;c.wipeShard=t=>(m(R(o),t,d),e.call(a,t))}return Object.defineProperty(c,w,{configurable:!0,enumerable:!1,value:n,writable:!1}),c};export{M as LOOP_GATED_METHODS,w as RLS_UNWRAP_SYMBOL,b as RlsRequiredError,g as WRITER_METHOD_GATING,k as guardWriter};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{stableWireKey as y}from"@lunora/wire";import{stableStringify as T,stableWireKey as _}from"@lunora/wire";import{isPrimaryReadDep as p,depKey as l,SCAN_DEP as m}from"./SCAN_DEP-B4Uu4g7l.mjs";import{e as x}from"./estimate-bytes-C-C35VXL.mjs";import{isPointRange as v,keysTouchRanges as E}from"./buildIndexRange-BTChxh3k.mjs";const f=(a,t,e)=>{let s=a.get(t);return s===void 0&&(s=e(),a.set(t,s)),s},B=1e3,I=4*1024*1024;class A{entries=new Map;tableIndex=new Map;rangeIndex=new Map;totalBytes=0;hits=0;misses=0;evictions=0;maxEntries;maxBytes;now;monotonic=0;generation=0;constructor(t={}){this.maxEntries=t.maxEntries??B,this.maxBytes=t.maxBytes??I,this.now=t.now??(()=>(this.monotonic+=1,this.monotonic))}async run(t,e,s,i=()=>[]){const r=this.entries.get(t);if(r)return this.hits+=1,r.lastUsed=this.now(),this.entries.delete(t),this.entries.set(t,r),r.result;this.misses+=1;const c=this.generation,o=await s();if(this.generation!==c)return o;for(const n of e)if(p(n))return o;const h=x(o);if(h===void 0)return o;const b=i().filter(n=>!v(n)||!e.has(l(n.table,n.lo))),u={bytes:h,deps:e,ranges:b,lastUsed:this.now(),result:o,subscribers:new Set},d=this.entries.get(t);if(d){this.dropEntry(t,d);for(const n of d.subscribers)u.subscribers.add(n)}this.entries.set(t,u),this.totalBytes+=h;for(const n of e)f(this.tableIndex,n,()=>new Set).add(t);for(const n of b){const g=f(this.rangeIndex,n.table,()=>new Map);f(g,n,()=>new Set).add(t)}return this.evict(),o}invalidate(t,e,s){this.generation+=1;const i=[];return this.collectAndDrop(l(t,e),i),this.collectAndDrop(l(t,m),i),this.dropRangeDeps(t,s,i),i}invalidateTable(t){this.generation+=1;const e=[],s=`${t}:`;for(const i of this.tableIndex.keys())i.startsWith(s)&&this.collectAndDrop(i,e);return this.dropRangeDeps(t,void 0,e),e}subscribe(t,e){const s=this.entries.get(t);s&&s.subscribers.add(e)}unsubscribe(t,e){const s=this.entries.get(t);s&&s.subscribers.delete(e)}size(){return{bytes:this.totalBytes,entries:this.entries.size}}clear(){this.generation+=1,this.entries.clear(),this.tableIndex.clear(),this.rangeIndex.clear(),this.totalBytes=0}subscribers(t){const e=this.entries.get(t);return e?[...e.subscribers]:[]}stats(){return{bytes:this.totalBytes,entries:this.entries.size,evictions:this.evictions,hits:this.hits,misses:this.misses}}dropRangeDeps(t,e,s){const i=this.rangeIndex.get(t);if(!(!i||i.size===0))for(const[r,c]of i)E([r],e)&&this.dropKeys(c,s)}collectAndDrop(t,e){const s=this.tableIndex.get(t);s&&this.dropKeys(s,e)}dropKeys(t,e){for(const s of t){const i=this.entries.get(s);i&&(this.dropEntry(s,i),e.push(s))}}dropEntry(t,e){this.entries.delete(t),this.totalBytes-=e.bytes;for(const s of e.deps){const i=this.tableIndex.get(s);i&&(i.delete(t),i.size===0&&this.tableIndex.delete(s))}for(const s of e.ranges){const i=this.rangeIndex.get(s.table),r=i?.get(s);r?.delete(t),i&&r?.size===0&&(i.delete(s),i.size===0&&this.rangeIndex.delete(s.table))}}evict(){if(!(this.entries.size<=this.maxEntries&&this.totalBytes<=this.maxBytes))for(const[t,e]of this.entries){if(this.entries.size<=this.maxEntries&&this.totalBytes<=this.maxBytes)return;e.subscribers.size>0||(this.dropEntry(t,e),this.evictions+=1)}}}const K=(a,t,e)=>`${e??"\0anon"}\0${a}:${y(t)}`;export{A as ReactiveCache,K as reactiveCacheKey,T as stableStringify,_ as stableWireKey};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const c="\0primary",r=`:${c}`,s="*scan",R=c,a=e=>e.endsWith(r),o=(e,n)=>`${e}:${n}`,d=e=>{const n=e.indexOf(":");return n===-1?e:e.slice(0,n)},A=()=>{const e=new Set;return{collect(){return e},recordRead(n,t){e.add(o(n,t))}}};export{R as PRIMARY_READ,s as SCAN_DEP,A as createDependencyTracker,o as depKey,a as isPrimaryReadDep,d as tableFromDepKey};
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import{LunoraError as $}from"@lunora/errors";import{isPlainObject as S}from"@lunora/wire";import{sql as n}from"drizzle-orm";import{runDrizzle as d}from"./runDrizzle-RC09zZrh.mjs";const a="__schedule_outbox",h=t=>{d(t,n`CREATE TABLE IF NOT EXISTS ${n.identifier(a)} (
|
|
2
|
+
id TEXT PRIMARY KEY,
|
|
3
|
+
envelope_json TEXT NOT NULL,
|
|
4
|
+
attempts INTEGER NOT NULL,
|
|
5
|
+
next_attempt_at REAL NOT NULL,
|
|
6
|
+
created_at REAL NOT NULL,
|
|
7
|
+
dead INTEGER NOT NULL DEFAULT 0
|
|
8
|
+
)`),d(t,n`CREATE INDEX IF NOT EXISTS ${n.identifier(`${a}_due`)} ON ${n.identifier(a)} (dead, next_attempt_at)`),d(t,n`CREATE INDEX IF NOT EXISTS ${n.identifier(`${a}_age`)} ON ${n.identifier(a)} (created_at, id)`)},L=(t,e,r,o)=>{d(t,n`INSERT OR REPLACE INTO ${n.identifier(a)} (id, envelope_json, attempts, next_attempt_at, created_at, dead)
|
|
9
|
+
VALUES (${e}, ${r}, 0, ${o}, ${o}, 0)`)},A=(t,e)=>{d(t,n`DELETE FROM ${n.identifier(a)} WHERE id = ${e}`)},b=(t,e,r)=>d(t,n`SELECT id, envelope_json, attempts, next_attempt_at FROM ${n.identifier(a)}
|
|
10
|
+
WHERE dead = 0 AND next_attempt_at <= ${e}
|
|
11
|
+
ORDER BY next_attempt_at ASC LIMIT ${r}`).toArray().map(E=>({attempts:E.attempts,envelopeJson:E.envelope_json,id:E.id,nextAttemptAt:E.next_attempt_at})),D=(t,e,r)=>{const o=d(t,n`SELECT id, envelope_json, attempts, next_attempt_at FROM ${n.identifier(a)}
|
|
12
|
+
WHERE id = ${e} AND dead = 0 AND next_attempt_at <= ${r}`).toArray()[0];return o===void 0?void 0:{attempts:o.attempts,envelopeJson:o.envelope_json,id:o.id,nextAttemptAt:o.next_attempt_at}},j=(t,e,r,o)=>{d(t,n`UPDATE ${n.identifier(a)} SET attempts = ${r}, next_attempt_at = ${o} WHERE id = ${e}`)},y=(t,e,r,o)=>{d(t,n`UPDATE ${n.identifier(a)} SET attempts = ${r}, next_attempt_at = ${o}, dead = 1 WHERE id = ${e}`)},C=t=>{const r=d(t,n`SELECT MIN(CASE WHEN dead = 0 THEN next_attempt_at END) AS due, COUNT(*) AS total FROM ${n.identifier(a)}`).toArray()[0];return{dueAt:r?.due??void 0,populated:(r?.total??0)>0}},H=(t,e)=>{d(t,n`DELETE FROM ${n.identifier(a)} WHERE dead = 1 AND next_attempt_at < ${e}`)},N=t=>{if(typeof t=="string")return t;if(S(t))return typeof t.__lunoraRef=="string"?t.__lunoraRef:typeof t.className=="string"?t.className:void 0},T=t=>{let e;if(t.target_type==="text")e=t.target;else if(t.target_type==="object"&&typeof t.target=="string")try{e=JSON.parse(t.target)}catch{e=void 0}return{attempts:t.attempts,createdAt:t.created_at,forever:t.forever===1,id:t.id,nextAttemptAt:t.next_attempt_at,parked:t.dead===1,target:N(e),when:typeof t.when_ts=="number"?t.when_ts:void 0}},m=/^(\d+(?:\.\d+)?):(.+)$/su,f=t=>`${String(t.createdAt)}:${t.id}`,O=t=>{const e=m.exec(t);if(e!==null)return{createdAt:Number(e[1]),id:e[2]}},g=(t,e,r)=>{const o=r===void 0?void 0:O(r);if(r!==void 0&&o===void 0)throw new $("BAD_REQUEST",`getScheduleOutbox: malformed cursor ${JSON.stringify(r)}`);const E=o===void 0?n``:n`WHERE (created_at, id) > (${o.createdAt}, ${o.id})`,i=n`(CASE WHEN json_valid(envelope_json) THEN envelope_json END)`,s=d(t,n`SELECT id, attempts, next_attempt_at, created_at, dead,
|
|
13
|
+
CASE WHEN json_type(${i}) = 'object' THEN json_type(${i}, '$.target') END AS target_type,
|
|
14
|
+
CASE WHEN json_type(${i}) = 'object' AND json_type(${i}, '$.target') IN ('text', 'object') THEN json_extract(${i}, '$.target') END AS target,
|
|
15
|
+
CASE WHEN json_type(${i}) = 'object' AND json_type(${i}, '$.when') IN ('integer', 'real') THEN json_extract(${i}, '$.when') END AS when_ts,
|
|
16
|
+
CASE WHEN json_type(${i}) = 'object' AND json_type(${i}, '$.options.retry.forever') = 'true' THEN 1 ELSE 0 END AS forever
|
|
17
|
+
FROM ${n.identifier(a)}
|
|
18
|
+
${E} ORDER BY created_at ASC, id ASC LIMIT ${e+1}`).toArray(),_=s.slice(0,e).map(u=>T(u)),c=_.at(-1);return{entries:_,nextCursor:s.length>e&&c!==void 0?f(c):void 0}},I=(t,e)=>{const r=d(t,n`SELECT created_at, envelope_json, dead FROM ${n.identifier(a)} WHERE id = ${e}`).toArray()[0];return r===void 0?void 0:{createdAt:r.created_at,parked:r.dead===1,version:`${String(r.created_at)}:${r.envelope_json}`}},p=(t,e)=>d(t,n`SELECT id FROM ${n.identifier(a)} WHERE id = ${e}`).toArray().length>0,U=(t,e,r)=>p(t,e)?(d(t,n`UPDATE ${n.identifier(a)} SET attempts = 0, next_attempt_at = ${r}, dead = 0 WHERE id = ${e}`),!0):!1,W=(t,e)=>p(t,e)?(A(t,e),!0):!1;export{a as SCHEDULE_OUTBOX_TABLE,j as deferScheduleOutbox,W as dropScheduleOutbox,A as forgetScheduleOutbox,p as hasScheduleOutboxEntry,h as migrateScheduleOutbox,y as parkScheduleOutbox,C as probeScheduleOutbox,b as readDueScheduleOutbox,D as readDueScheduleOutboxEntry,g as readScheduleOutbox,I as readScheduleOutboxState,L as recordScheduleOutbox,U as requeueScheduleOutbox,H as trimScheduleOutbox};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import{quoteIdentifier as i}from"./quoteIdentifier-CObIFRhb.mjs";import{runSql as n}from"./runDrizzle-RC09zZrh.mjs";const p="__lunora_schema_history",c=50,e=i(p),E=t=>({appliedAt:typeof t.applied_at=="number"?t.applied_at:0,hash:typeof t.hash=="string"?t.hash:"",seq:typeof t.seq=="number"?t.seq:0}),a=t=>{n(t,`CREATE TABLE IF NOT EXISTS ${e} (
|
|
2
|
+
hash TEXT PRIMARY KEY,
|
|
3
|
+
seq INTEGER NOT NULL,
|
|
4
|
+
snapshot_json TEXT NOT NULL,
|
|
5
|
+
applied_at INTEGER NOT NULL
|
|
6
|
+
)`)},S=t=>{n(t,`DELETE FROM ${e} WHERE hash NOT IN (SELECT hash FROM ${e} ORDER BY seq DESC LIMIT ?)`,c)},I=(t,s,r,h=Date.now())=>{if(s===""||r==="")return!1;try{if(a(t),n(t,`SELECT hash FROM ${e} WHERE hash = ? LIMIT 1`,s).toArray().length>0)return!1;const[o]=n(t,`SELECT COALESCE(MAX(seq), 0) + 1 AS next FROM ${e}`).toArray(),T=typeof o?.next=="number"?o.next:1;return n(t,`INSERT INTO ${e} (hash, seq, snapshot_json, applied_at) VALUES (?, ?, ?, ?) ON CONFLICT(hash) DO NOTHING`,s,T,r,h),S(t),!0}catch{return!1}},_=t=>{try{return a(t),n(t,`SELECT hash, seq, applied_at FROM ${e} ORDER BY seq DESC`).toArray().map(s=>E(s))}catch{return[]}},u=(t,s)=>{try{a(t);const[r]=n(t,`SELECT hash, seq, applied_at, snapshot_json FROM ${e} WHERE hash = ? LIMIT 1`,s).toArray();return r===void 0?void 0:{...E(r),snapshotJson:typeof r.snapshot_json=="string"?r.snapshot_json:""}}catch{return}};export{c as SCHEMA_HISTORY_MAX_VERSIONS,_ as readSchemaHistory,u as readSchemaVersion,I as recordSchemaVersion};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{S as t,m as S,b as c,r as i,a as l,w as s}from"./ctx-db-search-state-CPKPy8N6.mjs";import"./runDrizzle-RC09zZrh.mjs";export{t as SEARCH_STATE_TABLE,S as migrateSearchState,c as readBackfillState,i as readSearchBackfillState,l as readSearchIndexCoverage,s as writeSearchBackfillState};
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import{sql as o}from"drizzle-orm";import{runDrizzle as s}from"./runDrizzle-RC09zZrh.mjs";import{WORKERD_SQLITE_LIMITS as d}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";const c="__shape_poke_cursor",L=r=>{s(r,o`CREATE TABLE IF NOT EXISTS ${o.identifier(c)} (
|
|
2
|
+
connection_id TEXT NOT NULL,
|
|
3
|
+
sub_id TEXT NOT NULL,
|
|
4
|
+
cursor INTEGER NOT NULL,
|
|
5
|
+
PRIMARY KEY (connection_id, sub_id)
|
|
6
|
+
)`)},N=(r,e,n)=>s(r,o`SELECT cursor FROM ${o.identifier(c)} WHERE connection_id = ${e} AND sub_id = ${n} LIMIT 1`).toArray()[0]?.cursor,a=(r,e,n,i)=>{s(r,o`INSERT INTO ${o.identifier(c)} (connection_id, sub_id, cursor) VALUES (${e}, ${n}, ${i})
|
|
7
|
+
ON CONFLICT(connection_id, sub_id) DO UPDATE SET cursor = excluded.cursor`)},T=3,R=(r,e)=>{const n=Math.floor(d.boundParams/T);for(let i=0;i<e.length;i+=n){const E=e.slice(i,i+n),u=o.join(E.map(t=>o`(${t.connectionId}, ${t.subId}, ${t.cursor})`),o`, `);s(r,o`INSERT INTO ${o.identifier(c)} (connection_id, sub_id, cursor) VALUES ${u}
|
|
8
|
+
ON CONFLICT(connection_id, sub_id) DO UPDATE SET cursor = excluded.cursor`)}},$=r=>s(r,o`SELECT MIN(cursor) AS cursor FROM ${o.identifier(c)}`).toArray()[0]?.cursor??void 0,C=(r,e,n)=>{s(r,o`DELETE FROM ${o.identifier(c)} WHERE connection_id = ${e} AND sub_id = ${n}`)},I=(r,e)=>{s(r,o`DELETE FROM ${o.identifier(c)} WHERE connection_id = ${e}`)};export{c as SHAPE_POKE_CURSOR_TABLE,C as deleteShapePokeCursor,I as deleteShapePokeCursorsForConnection,L as migrateShapePokeCursor,$ as minShapePokeCursor,N as readShapePokeCursor,a as writeShapePokeCursor,R as writeShapePokeCursors};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{stableWireKey as o}from"@lunora/wire";const s=r=>r.map(e=>`${String(e.length)}:${e}`).join(""),c=r=>o(r.effectiveWhere??null),g=(r,e,t)=>s([r,String(e),String(t)]),h=(r,e)=>{try{return s([c(r),e])}catch{return}};class d{keyScans=new Map;memberProbes=new Map;run=0;served=0;get probesRun(){return this.run}get probesServed(){return this.served}changedKeys(e,t){return this.getOrLoad(this.keyScans,e,t)}members(e,t,n){return this.getOrLoad(this.memberProbes,h(e,t),n)}getOrLoad(e,t,n){if(t!==void 0){const a=e.get(t);if(a!==void 0)return this.served+=1,a}this.run+=1;const i=n();return t!==void 0&&e.set(t,i),i}}const p=()=>new d,b=(r,e)=>{try{return s([r.table,c(r),o({identity:e.identity,userId:e.userId})])}catch{return}};export{d as ShapeDiffCache,p as createShapeDiffCache,b as globalShapeReadKey,g as shapeRangeKey};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
class n{shardHost;socketHost;options;constructor(t,s,r={}){this.shardHost=t,this.socketHost=s,this.options=r}get shardKey(){return this.shardHost.shardKey}socketFor(t){return this.socketHost.handleFor(t)??t}sockets(t){return this.socketHost.getSockets(t)}background(t){return this.shardHost.waitUntil===void 0?!1:(this.shardHost.waitUntil(t),!0)}async runInTransaction(t,s){return this.shardHost.runSerialized(async()=>{const r=await this.shardHost.transaction(t);return s?.(),r})}async handleFetch(t){return this.options.handlers?.handleFetch?this.options.handlers.handleFetch(t):new Response("Not implemented",{status:501})}async handleAlarm(){this.options.handlers?.handleAlarm&&await this.options.handlers.handleAlarm()}}export{n as ShardRunner};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{isLunoraError as S}from"@lunora/errors";import{l as R,b as L}from"./ctx-db-search-state-CPKPy8N6.mjs";import{sql as e}from"drizzle-orm";import{readKeysetPage as _}from"./backfillAggregateIndexes-BwCpPW7h.mjs";import{runDrizzle as p}from"./runDrizzle-RC09zZrh.mjs";import{h}from"./do-sql-105TONaE.mjs";const u="__lunora_vector_backfill",m=50,k=20,w=20,N=3,O=i=>{p(i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(u)} (${e.identifier("companion")} TEXT PRIMARY KEY, ${e.identifier("cursor")} TEXT, ${e.identifier("done")} INTEGER NOT NULL DEFAULT 0, ${e.identifier("profile")} TEXT, ${e.identifier("strikes")} INTEGER NOT NULL DEFAULT 0)`);try{p(i,e`ALTER TABLE ${e.identifier(u)} ADD COLUMN ${e.identifier("strikes")} INTEGER NOT NULL DEFAULT 0`)}catch{}},C=(i,o)=>{const[s]=p(i,e`SELECT ${e.identifier("strikes")} FROM ${e.identifier(u)} WHERE ${e.identifier("companion")} = ${o}`).toArray();return s?.strikes??0},$=(i,o,s,d,t,r=0)=>{const n=s??null;p(i,e`INSERT INTO ${e.identifier(u)} (${e.identifier("companion")}, ${e.identifier("cursor")}, ${e.identifier("done")}, ${e.identifier("profile")}, ${e.identifier("strikes")}) VALUES (${o}, ${n}, ${d?1:0}, ${t}, ${r}) 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("strikes")} = excluded.${e.identifier("strikes")}`)},A=(i,o,s)=>{const d=_(i,o,s,m+1),t={documents:[],lastId:s,more:d.length>m,unparseable:[]};for(const r of d.slice(0,m)){if(typeof r.id!="string")continue;t.lastId=r.id;const n=h(r);n?t.documents.push({doc:n,id:t.lastId}):t.unparseable.push(t.lastId)}return t},D=(i,o,s,d,t)=>{const r=t instanceof Error?t.message:String(t),n=L(i,u,o),a=n.profile===d&&n.cursor===s?C(i,o):0;if(S(t)&&t.code==="SERVICE_UNAVAILABLE")return a>0&&$(i,o,s,!1,d,0),{error:r};const f=a+1;if(f<N)return $(i,o,s,!1,d,f),{error:r};const c=A(i,o,s),l=[...c.documents.map(E=>E.id),...c.unparseable];return console.warn(`[@lunora/shard-engine] vector backfill: a page of "${o}" failed ${String(f)} times in a row; its ${String(l.length)} row(s) are recorded as failed:`,t),{failedIds:l,page:c}},F=async(i,o,s,d,t)=>{const{profile:r,table:n}=o;try{const{failures:a,page:f}=await t(()=>A(i,n,s),async c=>({failures:await d(n,c.documents),page:c}));return a.length>0&&console.warn(`[@lunora/shard-engine] vector backfill: ${String(a.length)} row(s) of "${n}" could not be indexed:`,a),{failedIds:[...f.unparseable,...a.map(c=>c.id)],page:f}}catch(a){return D(i,n,s,r,a)}},y=async(i,o,s,d)=>{if(O(i),d.restart===!0)for(const{profile:n,table:a}of o)$(i,a,void 0,!1,n);const t=Math.min(d.maxPages??1,k),r={done:!1,failed:0,failedIds:[],pages:0,rows:0};for(const{profile:n,table:a}of o){const f=R(L(i,u,a),n);let{cursor:c}=f,l=f.finished;for(;!l;){if(r.pages>=t)return r;const E=await F(i,{profile:n,table:a},c,s,d.ordered);if("error"in E)return{...r,error:E.error};const{failedIds:g,page:T}=E,I=T.documents.length+T.unparseable.length;r.pages+=I>0?1:0,r.rows+=I,r.failed+=g.length,r.failedIds=[...r.failedIds,...g].slice(0,w),c=T.lastId,l=!T.more,$(i,a,c,l,n)}}return{...r,done:!0}};export{k as VECTOR_BACKFILL_MAX_PAGES,m as VECTOR_BACKFILL_PAGE_ROWS,y as backfillVectorIndexes};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as f}from"@lunora/errors";import{sql as t}from"drizzle-orm";import{SQLiteDialect as u}from"drizzle-orm/sqlite-core";const S=new u,s={boundParams:100,compoundSelect:5,likePattern:50,sqlTextLength:1e5},d=s.boundParams/2,h=n=>n===null||typeof n=="boolean"?!0:typeof n=="number"?Number.isFinite(n):typeof n=="string"&&n.isWellFormed(),p=n=>{const e=[];for(const r of n){if(!(r instanceof Uint8Array))return;e.push(Array.from(r,o=>o.toString(16).padStart(2,"0")).join(""))}return JSON.stringify(e)},N=(n,e)=>{if(n!=="sqlite")throw new f("INTERNAL",`renderSql only renders SQLite; use SqlDialect.render for "${n}"`);const{params:r,sql:o}=S.sqlToQuery(e);return{params:r,sql:o}},L=n=>t`${n}`,y=n=>{if(n.length===0)throw new Error("unionAll: expected at least one branch");let e=[...n];for(;e.length>s.compoundSelect;){const r=[];for(let o=0;o<e.length;o+=s.compoundSelect){const i=t.join(e.slice(o,o+s.compoundSelect),t` UNION ALL `);r.push(t`SELECT * FROM (${i}) ${t.identifier("__u__")}`)}e=r}return t.join(e,t` UNION ALL `)},T=(n,e,r,o=d)=>{const i=r?t` NOT IN `:t` IN `,a=e.every(l=>h(l)),c=e.length>o&&!a?p(e):void 0;if(c!==void 0)return t`${n}${i}(SELECT unhex(${t.identifier("value")}) FROM json_each(${c}))`;if(e.length>o&&!a)throw new f("BAD_REQUEST",`an "in" list of ${String(e.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(e.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 e.length<=o?t`${n}${i}(${t.join(e.map(l=>L(l)),t`, `)})`:t`${n}${i}(SELECT ${t.identifier("value")} FROM json_each(${JSON.stringify(e)}))`};export{s as WORKERD_SQLITE_LIMITS,p as bytesAsHexJson,h as isJsonSafe,L as param,N as renderSql,T as sqliteInList,y as unionAll};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{e as o}from"./effective-kind-BmG_zCAy.mjs";const a=new Set(["any","null"]),s=(t,n)=>{const l=n.kindOf(t);return l!==void 0&&a.has(l)||n.nullableOf(t)?!0:l==="union"&&(n.membersOf(t)??[]).some(i=>s(i,n))},e=t=>{const n=t._meta?.inner;return t.kind==="optional"&&n?e(n):t},u=t=>s(t,{kindOf:o,membersOf:n=>e(n)._meta?.members,nullableOf:n=>e(n)._meta?.column?.notNull===!1});export{u as v};
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import{ADMIN_TOKEN_TABLE as n}from"./ADMIN_TOKEN_TABLE-DfQ5osdI.mjs";import{c as T}from"./constant-time-equal-BRh9yUCr.mjs";import{runSql as r}from"./runDrizzle-RC09zZrh.mjs";const u=["migrations"],A=e=>u.some(t=>t===e),m=6e4,d=new WeakSet,o=e=>{if(r(e,`CREATE TABLE IF NOT EXISTS "${n}" (
|
|
2
|
+
name TEXT PRIMARY KEY,
|
|
3
|
+
digest TEXT NOT NULL,
|
|
4
|
+
created_at REAL NOT NULL,
|
|
5
|
+
last_used_at REAL,
|
|
6
|
+
expires_at REAL,
|
|
7
|
+
scopes TEXT
|
|
8
|
+
)`),d.has(e))return;r(e,`PRAGMA table_info("${n}")`).toArray().some(a=>a.name==="scopes")||r(e,`ALTER TABLE "${n}" ADD COLUMN scopes TEXT`),d.add(e)},p=e=>e===void 0||e.length===0?null:JSON.stringify([...new Set(e)]),E=e=>{if(e===null)return[];const t=JSON.parse(e);return Array.isArray(t)?t.filter(A):[]},c=(e,t)=>r(e,`SELECT name, digest, created_at, last_used_at, expires_at, scopes FROM "${n}" WHERE name = ?`,t).toArray()[0],f=(e,t)=>(o(e),c(e,t.name)!==void 0?!1:(r(e,`INSERT INTO "${n}" (name, digest, created_at, expires_at, scopes) VALUES (?, ?, ?, ?, ?)`,t.name,t.digest,t.createdAt,t.expiresAt??null,p(t.scopes)),!0)),L=e=>(o(e),r(e,`SELECT name, created_at, last_used_at, expires_at, scopes FROM "${n}" ORDER BY name`).toArray().map(t=>{const a={createdAt:t.created_at,name:t.name,scopes:E(t.scopes)};return t.last_used_at!==null&&(a.lastUsedAt=t.last_used_at),t.expires_at!==null&&(a.expiresAt=t.expires_at),a})),N=(e,t,a)=>(o(e),c(e,t)?.created_at!==a?!1:(r(e,`DELETE FROM "${n}" WHERE name = ? AND created_at = ?`,t,a),!0)),x=(e,t,a,i)=>{o(e);const s=c(e,t);if(s===void 0||!T(s.digest,a)||s.expires_at!==null&&s.expires_at<=i)return;(s.last_used_at===null||i-s.last_used_at>=m)&&r(e,`UPDATE "${n}" SET last_used_at = ? WHERE name = ?`,i,t);const _=E(s.scopes);return s.expires_at===null?{createdAt:s.created_at,scopes:_}:{createdAt:s.created_at,expiresAt:s.expires_at,scopes:_}},O=(e,t)=>(o(e),c(e,t)!==void 0);export{n as ADMIN_TOKEN_TABLE,O as adminTokenExists,f as createAdminTokenRecord,L as listAdminTokens,N as revokeAdminTokenRecord,x as verifyAdminTokenDigest};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as g}from"@lunora/errors";import{encodeWire as i}from"@lunora/wire";const a=BigInt(Number.MAX_SAFE_INTEGER),c=(e,t)=>e<t?-1:e>t?1:0,s=(e,t)=>`${e}__agg_${t}`,l=e=>{if(typeof e=="bigint"){if(e>a||e<-a)throw new g("BAD_REQUEST",`bigint ${e.toString()} exceeds Number.MAX_SAFE_INTEGER, so an aggregateIndex declared over this column cannot tally it exactly (the companion's value column is a REAL) — drop the aggregateIndex, aggregate a narrower column, or read the rows and reduce them in the handler`);return Number(e)}if(typeof e=="number")return Number.isFinite(e)?e:void 0},v=(e,t,n,u)=>{const r=e.get(t)??{count:0,value:null};if(n.op==="count"){r.count+=1,r.value=r.count,e.set(t,r);return}const o=l(u[n.field??""]);if(n.op==="sum"||n.op==="avg"){o!==void 0&&(r.value=(r.value??0)+o,r.count+=1),e.set(t,r);return}r.count+=1,o!==void 0&&(r.value===null?r.value=o:r.value=n.op==="min"?Math.min(r.value,o):Math.max(r.value,o)),e.set(t,r)},d=(e,t)=>e==="count"?t?.value??0:!t||t.count===0?null:e==="avg"?t.value===null?null:t.value/t.count:t.value,A=(e,t)=>{if(e.length===0)return"";const n={};for(const u of e.toSorted(c))n[u]=t[u]??null;return JSON.stringify(i(n))};export{s as aggregateTableName,l as coerceAggregateNumber,c as compareStrings,A as encodeAggregateKey,v as foldAggregateTally,d as readAggregateValue};
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import{sql as t}from"drizzle-orm";import{runDrizzle as o}from"./runDrizzle-RC09zZrh.mjs";const E="__stream_runs",i="__stream_chunks",N=r=>{o(r,t`CREATE TABLE IF NOT EXISTS ${t.identifier(E)} (
|
|
2
|
+
run_key TEXT PRIMARY KEY,
|
|
3
|
+
status TEXT NOT NULL,
|
|
4
|
+
last_seq INTEGER NOT NULL DEFAULT 0,
|
|
5
|
+
error_code TEXT,
|
|
6
|
+
error TEXT,
|
|
7
|
+
started_at REAL NOT NULL,
|
|
8
|
+
ttl_ms REAL NOT NULL
|
|
9
|
+
)`),o(r,t`CREATE TABLE IF NOT EXISTS ${t.identifier(i)} (
|
|
10
|
+
run_key TEXT NOT NULL,
|
|
11
|
+
seq INTEGER NOT NULL,
|
|
12
|
+
data_json TEXT NOT NULL,
|
|
13
|
+
PRIMARY KEY (run_key, seq)
|
|
14
|
+
)`)},_=(r,e)=>{const s=o(r,t`SELECT status, last_seq, error_code, error, started_at FROM ${t.identifier(E)} WHERE run_key = ${e} LIMIT 1`).toArray()[0];if(s!==void 0)return{...s.error===null?{}:{error:s.error},...s.error_code===null?{}:{errorCode:s.error_code},lastSeq:s.last_seq,startedAt:s.started_at,status:s.status}},T=(r,e)=>{o(r,t`DELETE FROM ${t.identifier(i)} WHERE run_key = ${e}`)},c=(r,e,n,s)=>_(r,e)!==void 0?!1:(T(r,e),o(r,t`INSERT INTO ${t.identifier(E)} (run_key, status, last_seq, started_at, ttl_ms)
|
|
15
|
+
VALUES (${e}, ${"running"}, 0, ${n}, ${s})`),!0),R=(r,e)=>{T(r,e),o(r,t`DELETE FROM ${t.identifier(E)} WHERE run_key = ${e}`)},m=(r,e,n,s)=>{o(r,t`INSERT OR IGNORE INTO ${t.identifier(i)} (run_key, seq, data_json) VALUES (${e}, ${n}, ${s})`)},A=(r,e,n)=>o(r,t`SELECT seq, data_json FROM ${t.identifier(i)} WHERE run_key = ${e} AND seq > ${n} ORDER BY seq ASC`).toArray().map(s=>({dataJson:s.data_json,seq:s.seq})),$=(r,e,n,s,a)=>{if(_(r,e)===void 0){T(r,e);return}const d=a?.code??null,u=a?.message??null;o(r,t`UPDATE ${t.identifier(E)}
|
|
16
|
+
SET status = ${n}, last_seq = ${s}, error_code = ${d}, error = ${u}
|
|
17
|
+
WHERE run_key = ${e}`)},f=(r,e,n)=>{const s=o(r,t`SELECT run_key FROM ${t.identifier(E)} WHERE started_at + ttl_ms < ${e}`).toArray();for(const{run_key:a}of s)n.has(a)||R(r,a)};export{m as appendStreamChunk,c as claimStreamRun,R as deleteStreamRun,$ as finishStreamRun,N as migrateDurableStreams,A as readStreamChunks,_ as readStreamRun,f as trimStreamRuns};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as S}from"@lunora/errors";import{t as z}from"./do-sql-105TONaE.mjs";import{applySelect as Y}from"./CURSOR_PREFIX-rOdoinP8.mjs";const U=Symbol.for("lunora.relations.fanOutBudget"),de=e=>({fanOutBudget:e[U],relationBaseWhere:e.relationBaseWhere,relationMask:e.relationMask}),L=(e,t)=>t.select?Y(e,t.select,t.with):e,pe=async(e,t,n,r,o)=>{const a=await Promise.all(r.map(async c=>{const u=o?{AND:[{[n]:c},o]}:{[n]:c};return[c,await e(t,u)]}));return new Map(a)},ee=32,B=1e4,te=(e,t,n)=>{const r=new Map;for(const o of e)for(const a of n(o)){const c=a[t],u=r.get(c);u?u.push(a):r.set(c,[a])}return r},W=(e,t)=>({...e,[U]:t}),ne=(e,t)=>{const n=new Map;for(const[o,a]of e)for(const c of a){const u=n.get(c);u?u.push(o):n.set(c,[o])}const r=new Map;for(const o of t)for(const a of n.get(o._id)??[]){const c=r.get(a);c?c.push(o):r.set(a,[o])}return r},D=(e,t)=>{const n=new Set;for(const r of e){const o=r[t];o!=null&&n.add(o)}return[...n]},he=async e=>{const{groupedCounter:t,fanOutBudget:n,fetcher:r,parents:o,relationBaseWhere:a,relationMask:c,schema:u,tableName:p,with:b}=e,O=n??{remaining:ee},y=(f,s)=>c?.(f,s)??s;if(o.length===0)return;const M=u.tables[p];if(!M)throw new S("INTERNAL",`unknown table: ${p}`);const _=M.relationMap??{},G=(f,s)=>{const i=d=>u.tables[d]?.shardMode?.kind??"root";return i(f)===i(s)&&i(f)!=="shardBy"},R=f=>{const s=_[f];if(!s)throw new S("INTERNAL",`unknown relation "${f}" on table "${p}"`);return s},X=async(f,s,i)=>{const d=D(o,s.field);if(d.length===0){for(const h of o)h[f]=null;return}const{page:l}=await r(s.table,W({baseWhere:a?.(s.table),relationBaseWhere:a,relationMask:c,where:{[s.references]:{in:d}},with:i.with},O)),w=new Map;for(const h of y(s.table,l))w.set(h[s.references],h);for(const h of o){const A=w.get(h[s.field]);h[f]=A?L([A],i)[0]??null:null}},j=async(f,s,i,d)=>{const{page:l}=await r(f,W({baseWhere:a?.(f),limit:d,orderBy:s.orderBy,relationBaseWhere:a,relationMask:c,where:s.where?{AND:[s.where,i]}:i,with:s.with},O));return l},T=(f,s,i,d,l)=>{for(const w of o){const h=l.get(w[d])??[];w[f]=L(i===void 0?h:h.slice(0,i),s)}},K=async(f,s,i)=>{const d=D(o,s.references);if(d.length===0){for(const g of o)g[f]=[];return}const l=typeof i.limit=="number"?Math.max(0,Math.floor(i.limit)):void 0,w=(g,k)=>j(s.table,i,g,k);if(l===0){for(const g of o)g[f]=[];return}const h=l!==void 0&&d.length<=O.remaining;h&&(O.remaining-=d.length);const A=h?await Promise.all(d.map(async g=>w({[s.field]:g},l))):[await w({[s.field]:{in:d}},void 0)],m=te(A,s.field,g=>y(s.table,g));T(f,i,l,s.references,m)},I=async f=>{const{from:s,table:i,to:d}=f.through,l=new Map,w=D(o,"_id");if(w.length===0)return l;const h=await j(i,{},{[s]:{in:w}},B+1);if(h.length>B)throw new S("INTERNAL",`loading "${p}" relations through "${i}" read more than ${String(B)} join rows for one page; load fewer ${p} rows at a time`);for(const A of y(i,h)){const m=A[s],g=A[d];if(m==null||g===null||g===void 0)continue;const k=l.get(m);k?k.add(g):l.set(m,new Set([g]))}return l},q=async(f,s,i)=>{const d=typeof i.limit=="number"?Math.max(0,Math.floor(i.limit)):void 0,l=d===0?new Map:await I(s),w=(A,m)=>j(s.table,i,{_id:{in:[...A]}},m);let h=new Map;if(l.size>0&&d!==void 0&&l.size<=O.remaining){O.remaining-=l.size;const A=[...l.keys()],m=await Promise.all([...l.values()].map(async g=>w(g,d)));h=new Map(A.map((g,k)=>[g,y(s.table,m[k]??[])]))}else if(l.size>0){const A=new Set([...l.values()].flatMap(m=>[...m]));h=ne(l,y(s.table,await w(A,void 0)))}T(f,i,d,"_id",h)},Z=async(f,s)=>{const i=[...s];if(i.length===0)return new Set;if(G(p,f)){const l=await t(f,"_id",i,a?.(f));return new Set(i.filter(w=>(l.get(w)??0)>0))}const d=await j(f,{},{_id:{in:i}},void 0);return new Set(d.map(l=>l._id))},J=async(f,s)=>{const i=await I(s),d=await Z(s.table,new Set([...i.values()].flatMap(l=>[...l])));for(const l of o){const w=l._count??{};w[f]=[...i.get(l._id)??[]].filter(h=>d.has(h)).length,l._count=w}},Q=async f=>{for(const s of Object.keys(f)){const i=R(s);if(i.through!==void 0){await J(s,i);continue}const[d,l]=i.kind==="many"?[i.field,i.references]:[i.references,i.field],w=a?.(i.table),h=D(o,l),A=h.length===0?new Map:await t(i.table,d,h,w);for(const m of o){const g=m._count??{},k=m[l];g[s]=k==null?0:A.get(k)??0,m._count=g}}};for(const[f,s]of Object.entries(b)){if(s===void 0||s===!1)continue;if(f==="_count"){await Q(s);continue}const i=R(f),d=s===!0?{}:s;i.through===void 0?await(i.kind==="one"?X(f,i,d):K(f,i,d)):await q(f,i,d)}},N=1e4,x=500,oe=async(e,t,n,r,o)=>{const a=new Set;let c=o;for(;;){const u=c!==void 0,p=c??await e();let b=!1;c=void 0;for(const O of p){const y=O._id;if(!(typeof y!="string"||a.has(y))){if(a.add(y),b=!0,a.size>N)throw n();await t(y)}}if(!u){if(p.length<x)return;if(!b)throw new S("INTERNAL",r)}}},H=(e,t,n)=>new S("CASCADE_LIMIT",`cannot delete "${e}" row: more than ${String(N)} ${t} rows reference it (onDelete: ${n}) — delete or re-point them in batches first`,{status:400}),re=async(e,t,n,r)=>{const{deletedId:o,deletedReference:a,findHolders:c,onRestrict:u,tableName:p}=e,b=n.references==="_id"?o:a(n.references);if(b==null)return;const{field:O}=n,y=`"${t}.${O}"`,M=await c(t,O,b,{limit:r==="restrict"?1:N+1,select:["_id"]});if(M.length!==0){if(r==="restrict")return u(`cannot delete "${p}" row: ${y} still references it`);if(M.length>N)throw H(p,y,r);return{action:r,field:O,holderTable:t,label:y,probe:M,referencedValue:b}}},se=async(e,t,n)=>{const{findHolders:r,onCascade:o,onSetNull:a,tableName:c}=e,{action:u,field:p,holderTable:b,label:O,probe:y,referencedValue:M}=t;await oe(()=>r(b,p,M,{limit:x}),_=>u==="cascade"?o(b,_):a(b,_,p),()=>H(c,O,u),`onDelete on "${c}" made no progress: ${O} rows still match after being processed`,n?y:void 0)},we=async e=>{const{schema:t,tableName:n}=e;if(!t.tables[n])throw new S("INTERNAL",`unknown table: ${n}`);const r=[];for(const[o,a]of Object.entries(t.tables)){const c=a.relationMap;if(c)for(const u of Object.values(c)){if(u.kind!=="one"||u.table!==n||!u.onDelete)continue;const p=await re(e,o,u,u.onDelete);p&&r.push(p)}}for(const[o,a]of r.entries())await se(e,a,o===0)},P=new WeakMap,V=e=>{const t=P.get(e);if(t!==void 0)return t;const n=e._meta,r=[n?.inner,n?.keyValidator,n?.valueValidator,...n?.members??[],...Object.values(n?.shape??{})],o=e.kind==="from"||r.some(a=>a!==void 0&&V(a));return P.set(e,o),o},$=e=>{const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},F=e=>e instanceof ArrayBuffer?new Uint8Array(e):ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):void 0,E=(e,t)=>{if(Object.is(e,t))return!0;if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();const n=F(e),r=F(t);if(n!==void 0||r!==void 0)return n!==void 0&&r!==void 0&&Object.getPrototypeOf(e)===Object.getPrototypeOf(t)&&n.length===r.length&&n.every((u,p)=>u===r[p]);if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((u,p)=>E(u,t[p]));if(typeof e!="object"||typeof t!="object"||e===null||t===null||!$(e)||!$(t))return!1;const o=e,a=t,c=Object.keys(o);return c.length===Object.keys(a).length&&c.every(u=>u in a&&E(o[u],a[u]))},C=new WeakMap,ge=e=>{if(C.has(e))return C.get(e);const t=Object.fromEntries(Object.entries(e.shape).filter(([,r])=>V(r))),n=Object.keys(t).length>0?{...e,shape:t}:void 0;return C.set(e,n),n},ie=e=>{let t;return(n,r)=>e===void 0?!1:(t??=e()??{},n in t&&E(r,t[n]))},ae=(e,t)=>{const n=new Set(Object.keys(t).filter(r=>t[r]!==void 0));for(const[r,o]of z(e))o.serverDefault&&n.delete(r);return n},ce=(e,t,n,r,o)=>n.trusted===!0||r!==void 0&&!r.has(e)||o(e,t),v=e=>typeof e!="object"||e===null?e:e instanceof Date?new Date(e):e instanceof ArrayBuffer||ArrayBuffer.isView(e)?structuredClone(e):Array.isArray(e)?e.map(t=>v(t)):e instanceof Map?new Map([...e].map(([t,n])=>[v(t),v(n)])):e instanceof Set?new Set([...e].map(t=>v(t))):$(e)?Object.fromEntries(Object.entries(e).map(([t,n])=>[t,v(n)])):e,ye=(e,t,n)=>{const r={...t};for(const[o,a]of z(e)){if(a.serverDefault){r[o]=a.serverDefault({auth:n});continue}if(r[o]===void 0){if(a.defaultFn)r[o]=a.defaultFn();else if("defaultValue"in a){const{defaultValue:c}=a;r[o]=v(c)}}}return r},me=(e,t,n={})=>{let r;const o=ie(n.previous),a=n.only??(n.supplied===void 0?void 0:ae(e,n.supplied));for(const[c,u]of Object.entries(e.shape)){if(!(c in t)||typeof u.parse!="function")continue;const p=V(u);if(p&&ce(c,t[c],n,a,o)||n.tolerateStoredNull===!0&&t[c]===null&&u.kind==="optional")continue;const b=u.parse(t[c]);p&&(r??={...t},r[c]=b)}return r??t};export{B as MAX_LINK_ROWS,ye as applyInsertDefaults,we as applyOnDelete,D as distinctValues,pe as fanOutScalarCounts,de as relationHooks,he as resolveWith,me as runRowValidators,ge as transformOnlyDefinition};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import{sql as s}from"drizzle-orm";import{runDrizzle as d}from"./runDrizzle-RC09zZrh.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
|
+
id INTEGER PRIMARY KEY CHECK (id = 1),
|
|
3
|
+
seq INTEGER NOT NULL
|
|
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{LunoraError as a}from"@lunora/errors";const t=()=>Object.assign(new Error("native PITR is unavailable here (local dev or a non-SQLite Durable Object); use `lunora backup restore` for off-platform recovery"),{code:"PITR_UNAVAILABLE",name:"LunoraError",status:409}),i=o=>{if(typeof o=="number")return o;const r=Date.parse(o);if(Number.isNaN(r))throw new a("BAD_REQUEST",`pitr: invalid time "${o}" — expected epoch-ms or an ISO timestamp`);return r},
|
|
1
|
+
import{LunoraError as a}from"@lunora/errors";const t=()=>Object.assign(new Error("native PITR is unavailable here (local dev or a non-SQLite Durable Object); use `lunora backup restore` for off-platform recovery"),{code:"PITR_UNAVAILABLE",name:"LunoraError",status:409}),i=o=>{if(typeof o=="number")return o;const r=Date.parse(o);if(Number.isNaN(r))throw new a("BAD_REQUEST",`pitr: invalid time "${o}" — expected epoch-ms or an ISO timestamp`);return r},k=async(o,r)=>{if(!o.getCurrentBookmark)throw t();const e=await o.getCurrentBookmark();return r===void 0||!o.getBookmarkForTime?{current:e}:{current:e,forTime:await o.getBookmarkForTime(i(r))}},s=async(o,r)=>{if(!o.onNextSessionRestoreBookmark)throw t();let e=r.bookmark;if(e===void 0){if(r.time===void 0)throw new a("BAD_REQUEST","pitrRestore: provide a `bookmark` or a `time` to restore to");if(!o.getBookmarkForTime)throw t();e=await o.getBookmarkForTime(i(r.time))}const n=await o.onNextSessionRestoreBookmark(e);return{restoredTo:e,undoBookmark:n}};export{s as armRestore,k as readBookmark};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as a}from"@lunora/errors";import{e as u}from"./effective-kind-BmG_zCAy.mjs";import{a as k,i as m,r as $,F as g,e as R,s as F}from"./json-field-path-DeJW4U9z.mjs";const d={decrement:{apply:(e,t)=>e-t,kind:"number"},divide:{apply:(e,t)=>e/t,kind:"number"},increment:{apply:(e,t)=>e+t,kind:"number"},multiply:{apply:(e,t)=>e*t,kind:"number"},toggle:{kind:"boolean"}};class s extends Error{}const w=e=>{if(!k(e))return;const t=Object.keys(e),[n]=t;if(!(t.length!==1||n===void 0||!Object.hasOwn(d,n)))return{operand:e[n],operator:n}},b=e=>w(e)!==void 0,P=(e,t,n,o)=>{const r=d[t];if(r.apply===void 0){if(n!==!0)throw new s(`patch: use { toggle: true } on "${e}".`);if(typeof o!="boolean")throw new s(`patch: cannot toggle "${e}" — its current value is ${String(o)}; set a boolean first.`);return!o}if(typeof n!="number"||!Number.isFinite(n))throw new s(`patch: "${t}" on "${e}" needs a finite number, got ${String(n)}.`);if(typeof o!="number"||!Number.isFinite(o))throw new s(`patch: cannot ${t} "${e}" — its current value is ${String(o)}; set a number first.`);if(t==="divide"&&n===0)throw new s(`patch: cannot divide "${e}" by zero.`);const i=r.apply(o,n);if(!Number.isFinite(i))throw new s(`patch: "${t}" on "${e}" overflows to ${String(i)}.`);return i},v=(e,t)=>{const n=new Set;for(const[o,r]of Object.entries(e))t(o)!==void 0&&b(r)&&n.add(o);return n},E=(e,t,n)=>{let o;for(const r of v(e,n)){const{operand:i,operator:c}=w(e[r]),f=n(r);if(d[c].kind!==f)throw new s(`patch: "${c}" does not apply to the ${String(f)} column "${r}".`);o??={...e},o[r]=P(r,c,i,t[r])}return o??e},j=new Set(["date","number","timestamp"]),l=e=>e.kind==="optional"&&e._meta?.inner!==void 0?l(e._meta.inner):e,p=e=>{const t=l(e);if(t.kind!==void 0&&j.has(t.kind))return"number";if(t.kind==="boolean")return"boolean";if(t.kind!=="union")return;const n=new Set((t._meta?.members??[]).filter(r=>u(r)!=="null").map(r=>p(r))),[o]=n;return n.size===1?o:void 0},O=e=>t=>{const n=Object.hasOwn(e.shape,t)?e.shape[t]:void 0;return n===void 0?void 0:p(n)},A=(e,t)=>v(t,O(e)),I=(e,t,n)=>{try{return E(t,n,O(e))}catch(o){throw o instanceof s?new a("VALIDATION_ERROR",o.message):o}},h=e=>{throw e instanceof g?new a("VALIDATION_ERROR",e.message):e},y=e=>{if(e===void 0)return;const t=l(e);if(t.kind==="object")return t._meta?.shape;if(t.kind!=="union")return;const n=(t._meta?.members??[]).filter(o=>u(o)!=="null");return n.length===1?y(n[0]):void 0},N=(e,t)=>{let n=e.shape[t[0]??""];for(const o of t.slice(1)){const r=y(n);n=r!==void 0&&Object.hasOwn(r,o)?r[o]:void 0}return n},_=(e,t,n)=>{let o=[];try{o=F(t)}catch(i){h(i)}const r=N(e,o);if(r===void 0)throw new a("VALIDATION_ERROR",`patch: "${t}" is not a path into an object column of this table`);if(p(r)!==void 0&&b(n))throw new a("VALIDATION_ERROR",`patch: "${t}" is nested inside a column; operators like increment apply to a top-level column only`);if(typeof r.parse=="function")try{r.parse(n)}catch(i){throw new a("VALIDATION_ERROR",`patch: "${t}" ${i instanceof Error?i.message:"is invalid"}`)}},S=(e,t,n)=>{for(const[o,r]of Object.entries(t))m(o)&&_(e,o,r);try{return R(t,n)}catch(o){return h(o)}},V=(e,t,n)=>S(e,I(e,t,n),n),x=(e,t)=>A(e,t).size>0||Object.keys(t).some(n=>m(n)),z=(e,t,n)=>{if(e?.verify!==void 0&&!e.verify(t,n))throw new a("FORBIDDEN","update denied by policy")},K=(e,t)=>{try{return $(e,t)}catch(n){return h(n)}};export{z as assertPatchAllowed,A as operatorFields,x as patchDependsOnRow,K as readPatchField,V as resolvePatch};
|
|
@@ -0,0 +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-CPKPy8N6.mjs";import{S as I,c as L,g as _,d as x,e as b,a as k}from"./fts-companion-CE3EmIjk.mjs";import{sql as i}from"drizzle-orm";import{ensureAggregateCompanion as y,ensureRankCompanion as B}from"./createCompanionSync-DO92CQek.mjs";import{runDrizzle as p,runAll as C}from"./runDrizzle-RC09zZrh.mjs";import{i as M,D as m,h as A}from"./do-sql-105TONaE.mjs";import{sqliteInList as U}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.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};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{compareStrings as S}from"./aggregateTableName-B_CtIQCS.mjs";import{float64SqlKey as I}from"./BIGINT_KEY_DIGITS-DE6yshOt.mjs";const a="!",d="",f=void 0,R=e=>{const n=new TextEncoder().encode(e);let o="";for(const t of n)o+=t.toString(16).padStart(2,"0");return o},g=e=>e===null?"0":typeof e=="number"?Number.isFinite(e)?`1${I(e)}`:f:typeof e=="string"?`2${R(e)}`:f,m=e=>{const n=[];for(const o of e){const t=g(o);if(t===f)return f;n.push(t)}return n.join(a)},v="=",E=new Set([">",">="]),K=new Set(["<","<="]),N=(e,n,o,t)=>{const r=n.comparator===v,i=E.has(n.comparator)||K.has(n.comparator);return!r&&!i||e.indexOf(n.field)!==o?!1:t===void 0?!0:!r&&t===n.field},k=(e,n,o)=>{const t={equalities:[],lowerExclusive:!1,upperExclusive:!1};let r;for(const i of n){const s=i.comparator===v,u=E.has(i.comparator);if(!N(e,i,t.equalities.length,r))return;if(s){t.equalities.push(o(i.value));continue}if(r=i.field,u){if(t.lower!==void 0)return;t.lower=o(i.value),t.lowerExclusive=i.comparator===">"}else{if(t.upper!==void 0)return;t.upper=o(i.value),t.upperExclusive=i.comparator==="<"}}return t},h=(e,n)=>{const o=g(n);if(o!==void 0)return e===""?o:e+a+o},B=(e,n,o,t,r)=>{if(o.length===0)return;const i=k(o,t,r);if(!i)return;const s=m(i.equalities);if(s===void 0)return;let u=s,l=s+d;if(i.lower!==void 0){const c=h(s,i.lower);if(c===void 0)return;u=i.lowerExclusive?c+a+d:c}if(i.upper!==void 0){const c=h(s,i.upper);if(c===void 0)return;l=i.upperExclusive?c:c+d}if(!(u>=l))return{hi:l,index:n,lo:u,table:e}},C=(e,n,o)=>{const t=[];for(const r of e){const i=m(r.fields.map(s=>o(n[s])));i!==void 0&&t.push({index:r.name,key:i})}return t},H=(e,n)=>e.index===n.index&&n.key>=e.lo&&n.key<e.hi,y="!id",p=d,L=(e,n)=>{if(n.length===e.length)return n;const o=new Set(n.map(t=>t.index));return[...n,...e.filter(t=>!o.has(t.name)).map(t=>({index:t.name,key:p}))]},O=e=>({index:y,key:e}),w=new WeakSet,U=(e,n)=>{const o={hi:`${n}\0`,index:y,lo:n,table:e};return w.add(o),o},Y=e=>w.has(e),A=e=>{const n=e.toSorted((t,r)=>S(t.lo,r.lo)),o=[];for(const t of n){const r=o.at(-1);r&&t.lo<=r.hi?t.hi>r.hi&&(o[o.length-1]={...r,hi:t.hi}):o.push(t)}return o},T=(e,n)=>{let o=0,t=e.length-1;for(;o<=t;){const r=Math.floor((o+t)/2),i=e[r];if(n<i.lo)t=r-1;else if(n>=i.hi)o=r+1;else return!0}return!1},x=(e,n)=>{const o=new Map;for(const t of e){const r=o.get(t.index);r?r.push(n(t)):o.set(t.index,[n(t)])}return o},q=(e,n)=>{let o=!1;for(const t of n)if(t.index===e.index){if(t.key===p||t.key>=e.lo&&t.key<e.hi)return!0;o=!0}return!o},D=(e,n)=>{if(!e||e.length===0||!n||n.length===0)return!0;if(e.length===1)return q(e[0],n);const o=x(n,r=>r.key);if(e.some(r=>!o.has(r.index)))return!0;const t=x(e,r=>r);for(const[r,i]of t){const s=i.length===1?i:A(i);if(o.get(r).some(u=>u===p||T(s,u)))return!0}return!1};export{B as buildIndexRange,O as idIndexKey,U as idRange,C as indexKeysForRow,Y as isPointRange,D as keysTouchRanges,H as rangeContains,L as withUnknownIndexKeys};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{encodeWire as h}from"@lunora/wire";const u=(t,e)=>{if(!e)return t;const a=Object.create(null);for(const s of["_id","_creationTime",...e])Object.hasOwn(t,s)&&(a[s]=t[s]);return a},y=(t,e,a)=>{const{columns:s,table:p}=a,i=new Map,c=[];for(const{doc:n,id:r}of t){const o=u(n,s),d=JSON.stringify(h(o));i.set(r,d);const f=e.get(r);f===void 0?c.push({key:r,op:"insert",table:p,value:o}):f!==d&&c.push({key:r,op:"update",table:p,value:o})}for(const n of e.keys())i.has(n)||c.push({key:n,op:"delete",table:p});return{next:i,rowsPatch:c}},k=t=>t.map(e=>e.value===void 0?e:{...e,value:h(e.value)}),b=(t,e,a={})=>{const{baseCheckpoint:s,checkpoint:p,epoch:i,lastMutationId:c,pokeId:n}=e,r=[JSON.stringify({baseCheckpoint:s,epoch:i,pokeId:n,type:"pokeStart"})];for(const o of t){const d=a.preEncoded?o.rowsPatch:k(o.rowsPatch),f=o.baseCheckpoint??s;r.push(JSON.stringify({pokeId:n,rowsPatch:d,shapeId:o.shapeId,type:"pokePart",...c===void 0?{}:{lastMutationId:c},...f===void 0?{}:{baseCheckpoint:f},...o.reset===!0?{reset:!0}:{}}))}return r.push(JSON.stringify({checkpoint:p,epoch:i,pokeId:n,type:"pokeEnd"})),r};export{b as buildPokeFrames,y as diffGlobalMembership,k as encodeRowsPatch,u as projectColumns};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{encodeWire as u}from"@lunora/wire";import{quoteIdentifier as l}from"./quoteIdentifier-CObIFRhb.mjs";import{reprojectionMigrationTable as d}from"./REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{REPROJECTION_MIGRATION_PREFIX as v,reprojectionMigrationId as w}from"./REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{runSql as p}from"./runDrizzle-RC09zZrh.mjs";import{k as m,D as E}from"./do-sql-105TONaE.mjs";import{mayHoldProjectedValue as g}from"./BIGINT_KEY_DIGITS-DE6yshOt.mjs";const b=u(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=d(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};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const f="CF_VERSION_METADATA",l=/key|secret|token|password|passwd|credential|private|auth|bearer|session|cookie|salt|signature|dsn|webhook/iu,d=new Set(["LUNORA_ADMIN_TOKEN","LUNORA_WS_BEARER"]),p=["CF_PAGES_URL","WORKER_URL","LUNORA_WORKER_URL"],u=["CF_ENV","ENVIRONMENT","WORKER_ENV","NODE_ENV"],R=n=>n.length<=4?"••••":`${n.slice(0,4)}${"•".repeat(Math.min(8,n.length-4))}`,N=n=>l.test(n),E=n=>{const e=o=>typeof n[o]=="function";return e("idFromName")||e("idFromString")?"durable-object":e("createMultipartUpload")||e("put")&&e("get")&&e("list")&&e("head")?"r2":e("getWithMetadata")?"kv":e("prepare")&&e("dump")?"d1":e("send")&&e("sendBatch")?"queue":e("fetch")&&!e("get")?"service":"object"},_=n=>{if(typeof n!="object"||n===null)return{};const e=n,o=i=>i.map(c=>e[c]).find(c=>typeof c=="string"&&c!==""),t={},r=o(p),s=o(u);r!==void 0&&(t.workerUrl=r),s!==void 0&&(t.environment=s);const a=e[f];if(a!==null&&typeof a=="object"){const i=a;typeof i.id=="string"&&(t.deploymentId=i.id),typeof i.tag=="string"&&(t.versionTag=i.tag)}return t},g=/^(?:dev(?:elopment)?|local(?:host)?|test)$/iu,A=n=>{const e=n??{};for(const o of u){const t=e[o];if(typeof t=="string"&&g.test(t))return!0}return!1},v=n=>{const e=n??{},o=[];for(const[t,r]of Object.entries(e))if(!d.has(t)){if(typeof r=="string"){const s=N(t);o.push({kind:s?"secret":"var",name:t,value:R(r)});continue}if(typeof r=="number"||typeof r=="boolean"){o.push({kind:"var",name:t,value:String(r)});continue}if(r!==null&&typeof r=="object"){o.push({bindingType:E(r),kind:"binding",name:t,value:null});continue}o.push({kind:"var",name:t,value:null})}return o.sort((t,r)=>t.name.localeCompare(r.name)),{deploy:_(e),settings:o}};export{v as buildSettings,A as isDevEnvironment,_ as readDeployInfo};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{readCdcChangeKeys as s}from"./CDC_LOG_TABLE-BFGgqai8.mjs";import{selectShapeMembers as h}from"./selectShapeMembers-Dqx_m7BF.mjs";import{shapeRangeKey as u}from"./ShapeDiffCache-iNO-hUiy.mjs";import{projectColumns as g}from"./buildPokeFrames-WR-hp0mX.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};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{sql as t}from"drizzle-orm";import{runDrizzle as s}from"./runDrizzle-RC09zZrh.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};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"./json-field-path-DeJW4U9z.mjs";import"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{c as p,s}from"./where-sql-BjY4rnqb.mjs";import"./RELATION_EXISTS_KEY-wxgj6rSL.mjs";export{p as compileWhereSql,s as serverInList};
|
|
@@ -0,0 +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-B4Uu4g7l.mjs";import{runDrizzle as A}from"./runDrizzle-RC09zZrh.mjs";import{sqliteInList as O}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{decodeCursor as F,CURSOR_PREFIX as P,toBase64 as U}from"./CURSOR_PREFIX-rOdoinP8.mjs";import{rankTableName as V,sortColumnName as z,resolveRankPartition as H,RANK_TIEBREAK as _,encodePartitionKey as J,rankPivotConditionSql as X}from"./RANK_TIEBREAK-D3ye2GsL.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};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const r=(e,n)=>{const c=Math.max(e.length,n.length);let h=e.length^n.length;for(let t=0;t<c;t+=1){const l=t<e.length?e.charCodeAt(t):0,o=t<n.length?n.charCodeAt(t):0;h|=l^o}return h===0};export{r as c};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{N as uo,S as $o,d as Eo,e as go,a as po}from"./fts-companion-CE3EmIjk.mjs";import{sql as o}from"drizzle-orm";import{r as Y}from"./json-field-path-DeJW4U9z.mjs";import{matchesStaticWhere as X,aggregateSqlFunction as mo}from"./AGGREGATE_SQL_FUNCTION-C_ZipS9R.mjs";import{aggregateTableName as j,foldAggregateTally as J,encodeAggregateKey as k,coerceAggregateNumber as U}from"./aggregateTableName-B_CtIQCS.mjs";import{aggregateSignature as ho,readCompanionSignature as Z,rankSignature as So,writeCompanionSignature as N}from"./CompanionMemo-BXU5vfak.mjs";import{runAll as _o,runDrizzle as g}from"./runDrizzle-RC09zZrh.mjs";import{i as yo,g as Ro,a as F,b as A,A as h,c as H,D as x,u as oo,r as eo,e as V}from"./do-sql-105TONaE.mjs";import{WORKERD_SQLITE_LIMITS as no,param as q}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{encodeGeohash as To,GEO_DEFAULT_PRECISION as Ao}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{isLiveForCompanion as to}from"./CURSOR_PREFIX-rOdoinP8.mjs";import{rankTableName as B,matchesRankStaticWhere as ro,sortColumnName as wo,encodePartitionKey as Co}from"./RANK_TIEBREAK-D3ye2GsL.mjs";import{mayHoldProjectedValue as Io}from"./BIGINT_KEY_DIGITS-DE6yshOt.mjs";import{serializeSqlValue as so}from"./serializeSqlValue-DeoBMpZ2.mjs";const Oo=(r,f,t)=>[...r.partitionBy??[],...r.sortBy.map(l=>l.field),...r.where?Object.keys(r.where):[]].every(l=>Y(f,l)===Y(t,l)),io=r=>o.join(["__id__","__partition__",...r.sortBy.map((f,t)=>wo(t))].map(f=>o.identifier(f)),o`, `),co=(r,f,t)=>{const $=Co(r.partitionBy??[],t),l=r.sortBy.map(s=>so(t[s.field]??null)),c=o.join([f,$,...l].map(s=>q(s)),o`, `);return o`(${c})`},vo=(r,f,t,$,l,c)=>{g(r,o`INSERT INTO ${o.identifier(f)} (${$}) VALUES ${co(t,l,c)}`)},Q=1e3,ao=function*(f,t,$,l){let c;for(;;){const s=c===void 0?o``:o` WHERE id > ${q(c)}`,y=[...g(oo(f),o`SELECT id, _creationTime, ${o.identifier(x)} FROM ${o.identifier(t)}${s} ORDER BY id LIMIT ${q(Q)}`)];for(const S of y){const R=eo(S);R&&to(R,$)&&l(R)&&(yield R)}if(y.length<Q)return;c=String(y.at(-1)?.id)}},ko=(r,f,t,$,l)=>{const c=j(f,t.name),s=t.by??[],y=new Map;for(const w of ao(r,f,$,I=>!t.where||X(I,t.where)))J(y,k(s,w),t,w);g(r,o`DELETE FROM ${o.identifier(c)}`);const S=Math.floor(no.boundParams/3),R=[...y];for(let w=0;w<R.length;w+=S){const I=R.slice(w,w+S),P=o.join(I.map(([b,D])=>o`(${b}, ${D.value}, ${D.count})`),o`, `);g(r,o`INSERT INTO ${o.identifier(c)} (${F}, ${A}, ${h}) VALUES ${P}`)}N(r,c,l)},Lo=(r,f,t,$)=>{const l=ho(t,$);Z(r,j(f,t.name))!==l&&ko(r,f,t,$,l)},Fo=(r,f,t,$,l)=>{const c=B(f,t.name),s=io(t);g(r,o`DELETE FROM ${o.identifier(c)}`);const y=Math.max(1,Math.floor(no.boundParams/(2+t.sortBy.length)));let S=[];const R=()=>{S.length>0&&(g(r,o`INSERT INTO ${o.identifier(c)} (${s}) VALUES ${o.join(S,o`, `)}`),S=[])};for(const w of ao(r,f,$,I=>!t.where||ro(I,t.where)))S.push(co(t,w._id,w)),S.length>=y&&R();R(),N(r,c,l)},Do=(r,f,t,$)=>{const l=So(t,$);Z(r,B(f,t.name))!==l&&Fo(r,f,t,$,l)},Mo=(r,f,t,$,l,c)=>{if(l&&c&&Oo(t,l,c))return;const s=B(f,t.name);l&&g(r,o`DELETE FROM ${o.identifier(s)} WHERE ${o.identifier("__id__")} = ${$}`),!(!c||t.where&&!ro(c,t.where))&&vo(r,s,t,io(t),$,c)},Jo=r=>{const{broadcast:f,indexKeysFor:t,invalidateCache:$,recordCdc:l,schema:c,sql:s}=r,y=r.verified??new Set,S=e=>c.tables[e]?.softDeleteMode?.field,R=(e,n)=>{const a=j(e,n.name);y.has(a)||(Lo(s,e,n,S(e)),y.add(a))},w=(e,n,a)=>{const p=n.by??[],d=n.field??"",E=[],_=(i,u)=>{const m=so(u);m===null?E.push(o`${V(i)} IS NULL`):E.push(o`${V(i)} = ${m}`)};for(const i of p)_(i,a[i]??null);const C=S(e);C!==void 0&&_(C,null);for(const[i,u]of Object.entries(n.where??{}))_(i,u!==null&&typeof u=="object"&&!Array.isArray(u)?u.eq:u);const L=E.length>0?o` WHERE ${o.join(E,o` AND `)}`:o``,M=c.tables[e]?.shape[d];if(M&&Io(M)){const i=g(oo(s),o`SELECT id, _creationTime, ${o.identifier(x)} FROM ${o.identifier(e)}${L}`).toArray(),u=new Map;for(const m of i){const v=eo(m);v&&J(u,"",n,v)}return{value:u.get("")?.value??null}}const W=mo(n.op),T=V(d);return{value:g(s,o`SELECT ${o.raw(W)}(${T}) AS value FROM ${o.identifier(e)}${L}`).one().value??null}},I=(e,n,a,p)=>{const d=j(e,n.name),{op:E}=n,_=n.field??"",C=i=>{g(s,o`DELETE FROM ${o.identifier(d)} WHERE ${F} = ${i} AND ${h} <= 0`)},L=S(e),M=i=>!n.where||X(i,n.where),W=i=>to(i,L)&&M(i);p!==void 0&&E!=="count"&&M(p)&&U(p[_]);const T=a&&W(a)?a:void 0,O=p&&W(p)?p:void 0;if(!(!T&&!O)){if(E==="count"){for(const[i,u]of[[T,-1],[O,1]]){if(!i)continue;const m=k(n.by??[],i);g(s,H(d,m,u,u,o`${A} = ${A} + excluded.${A}, ${h} = ${h} + excluded.${h}`))}T&&C(k(n.by??[],T));return}if(E==="sum"||E==="avg"){for(const[i,u]of[[T,-1],[O,1]]){if(!i)continue;const m=U(i[_]);if(m===void 0)continue;const v=k(n.by??[],i);g(s,H(d,v,u*m,u,o`${A} = COALESCE(${A}, 0) + excluded.${A}, ${h} = ${h} + excluded.${h}`))}T&&C(k(n.by??[],T));return}if(T){const i=k(n.by??[],T),u=U(T[_]),m=g(s,o`SELECT ${A} AS value, ${h} AS count FROM ${o.identifier(d)} WHERE ${F} = ${i}`).toArray()[0],v=(m?.count??0)-1;if(v<=0)g(s,o`DELETE FROM ${o.identifier(d)} WHERE ${F} = ${i}`);else if(m&&u!==void 0&&m.value!==null&&u===m.value){const lo=w(e,n,T);g(s,o`UPDATE ${o.identifier(d)} SET ${A} = ${lo.value}, ${h} = ${v} WHERE ${F} = ${i}`)}else g(s,o`UPDATE ${o.identifier(d)} SET ${h} = ${h} - 1 WHERE ${F} = ${i}`)}if(O){const i=k(n.by??[],O),u=U(O[_]);if(u===void 0)g(s,H(d,i,null,1,o`${h} = ${h} + 1`));else{const m=E==="min"?"MIN":"MAX";g(s,H(d,i,u,1,o`${A} = ${o.raw(m)}(COALESCE(${A}, excluded.${A}), excluded.${A}), ${h} = ${h} + 1`))}}}},P=e=>{for(const n of c.tables[e]?.aggregateIndexes??[])R(e,n)},b=(e,n,a)=>{for(const p of c.tables[e]?.aggregateIndexes??[])I(e,p,n,a)},D=(e,n)=>{const a=B(e,n.name);y.has(a)||(Do(s,e,n,S(e)),y.add(a))},fo=e=>{for(const n of c.tables[e]?.rankIndexes??[])D(e,n)},G=(e,n,a,p)=>{for(const d of c.tables[e]?.rankIndexes??[])Mo(s,e,d,n,a,p)},K=(e,n,a,p)=>{const d=c.tables[e]?.searchIndexes??[];if(!(d.length===0||!yo(s)))for(const E of d){if(uo(p,a,E))continue;const _=$o(e,E.name);_o(s,a?Eo(_,n,go(a,E)):po(_,n))}},z=(e,n,a)=>{for(const p of c.tables[e]?.geoIndexes??[]){const d=Ro(e,p.name);g(s,o`DELETE FROM ${o.identifier(d)} WHERE ${o.identifier("__id__")} = ${n}`);const E=a?.[p.field];if(E!==null&&typeof E=="object"&&typeof E.lat=="number"&&typeof E.lng=="number"){const{lat:_,lng:C}=E,L=To({lat:_,lng:C},p.precision??Ao);g(s,o`INSERT INTO ${o.identifier(d)} (${o.identifier("__id__")}, ${o.identifier("__geohash__")}, ${o.identifier("__lat__")}, ${o.identifier("__lng__")}) VALUES (${n}, ${L}, ${_}, ${C})`)}}};return{ensureBackfilledForTable:P,ensureBackfilledIndex:R,ensureRankBackfilled:D,ensureRankBackfilledForTable:fo,syncAggregates:b,syncCompanionsForInsert:(e,n,a)=>{K(e,n,a),z(e,n,a),b(e,void 0,a),G(e,n,void 0,a),$(e,n,a),l(e,n,"insert",a),f({indexKeys:t(e,a),key:n,op:"insert",row:a,table:e})},syncGeo:z,syncRanks:G,syncSearch:K}};export{Jo as createCompanionSync,Lo as ensureAggregateCompanion,Do as ensureRankCompanion};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import{LunoraError as T}from"@lunora/errors";import{decodeWire as v,encodeWire as N}from"@lunora/wire";import{cursorBelowRetainedFloor as b}from"./CDC_LOG_TABLE-BFGgqai8.mjs";import{envPositiveInt as E}from"./envOptionalPositiveInt-D2pY-c64.mjs";import{e as I}from"./estimate-bytes-C-C35VXL.mjs";import{siblingStub as L}from"./stubByName-DQSivmvb.mjs";import{DEFAULT_TRANSACTION_LIMITS as O}from"./DEFAULT_TRANSACTION_LIMITS-D7p7Ys0M.mjs";import{verifySiblingBody as C,RELAY_SIGNATURE_HEADER as S,siblingSecretOf as R,signSiblingBody as U}from"./RELAY_SIGNATURE_HEADER-CAfC4tqg.mjs";const q=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"],x=new Set(q),F=r=>typeof r=="string"&&x.has(r),w="::replica::",_=r=>{const e=r.lastIndexOf(w);if(e===-1)return;const t=r.slice(0,e),s=r.slice(e+w.length);if(!(t.length===0||!F(s)))return{ownerKey:t,region:s}},M=r=>{if(r==null||!/^\d+$/.test(r))return;const e=Number.parseInt(r,10);return Number.isSafeInteger(e)&&e>0?e:void 0},P=1e3,A=1e3,B=10,D=5e4,W=r=>E(r,"LUNORA_REPLICA_MAX_BOOTSTRAP_ROWS",D),f="__replica_state",g=new WeakSet,m=r=>{g.has(r)||(r.exec(`CREATE TABLE IF NOT EXISTS ${f} (
|
|
2
|
+
id INTEGER PRIMARY KEY CHECK (id = 1),
|
|
3
|
+
epoch TEXT NOT NULL,
|
|
4
|
+
applied_seq INTEGER NOT NULL,
|
|
5
|
+
synced_at REAL NOT NULL
|
|
6
|
+
)`),g.add(r))},h=r=>(m(r),r.exec(`SELECT epoch, applied_seq AS appliedSeq, synced_at AS syncedAtMs FROM ${f} WHERE id = 1`).toArray()[0]),l=(r,e)=>{m(r),r.exec(`INSERT INTO ${f} (id, epoch, applied_seq, synced_at) VALUES (1, ?, ?, ?)
|
|
7
|
+
ON CONFLICT(id) DO UPDATE SET epoch = excluded.epoch, applied_seq = excluded.applied_seq, synced_at = excluded.synced_at`,e.epoch,e.appliedSeq,e.syncedAtMs)},$=r=>{const e=r.doName();if(e!==void 0&&_(e)!==void 0)return new Response("replica cannot serve replicas",{status:409});if(r.ownerEpoch()===void 0)return new Response("shard has no changelog to replicate",{status:409});if(R(r.env())===void 0)return new Response("replica control requires LUNORA_RELAY_SECRET",{status:403})},p=r=>Response.json(N(r)),X=async(r,e)=>{if(r.rowCount()>W(r.env()))return p({cursor:0,epoch:e,rows:[],truncated:!0});const t=r.ownerCursor()??0,s=await r.exportRows();return p({cursor:t,epoch:e,rows:s})},k=(r,e,t)=>{const s=r.ownerFloor();if(b(s,t))return p({changes:[],cursor:r.ownerCursor()??t,epoch:e,floor:s});const n=r.ownerCursor()??0;if(t>n)return p({changes:[],cursor:n,epoch:e,...s===void 0?{}:{floor:s}});const{changes:o,cursor:i}=r.readChanges(t,A);return p({changes:o,cursor:i,epoch:e,...s===void 0?{}:{floor:s}})},te=async(r,e)=>{const t=$(r);if(t!==void 0)return t;const s=r.ownerEpoch();let n;try{n=await e.text()}catch{return new Response("bad request",{status:400})}if(!await C(r.env(),e.headers.get(S),n))return new Response("forbidden",{status:403});let o;try{o=JSON.parse(n)}catch{return new Response("bad request",{status:400})}if(o.type==="replica_bootstrap")return X(r,s);if(o.type==="replica_pull"){const i=typeof o.sinceSeq=="number"&&Number.isInteger(o.sinceSeq)&&o.sinceSeq>=0?o.sinceSeq:0;return k(r,s,i)}return new Response("unknown replica frame",{status:400})},K=r=>{const e=r;return typeof r=="object"&&(e?.retryable===!0||e?.overloaded===!0)},j=(r,e)=>{const t=e.changes.length===0&&e.cursor>r.appliedSeq,s=e.floor??(t?e.cursor:0),n=s>0&&s>r.appliedSeq+1,o=e.cursor<r.appliedSeq;return e.epoch!==r.epoch||o?"fork":n?"compacted":void 0},y=(r,e)=>`${r}\0${e}`;class H{constructor(e,t,s){this.host=e,this.ownerKey=t,this.region=s}host;ownerKey;region;divergent=!1;inFlight;async ensureFresh(e){if(this.divergent)return"unavailable";if(this.isCaughtUp(e))return"fresh";this.inFlight??=this.advance(e).finally(()=>{this.inFlight=void 0});const t=await this.inFlight;return t==="fresh"&&!this.isCaughtUp(e)?"stale":t}appliedSeq(){return h(this.host.sql())?.appliedSeq??0}isDivergent(){return this.divergent}async advance(e){let t=h(this.host.sql());if(t===void 0){const s=await this.bootstrap();if(s===void 0)return"unavailable";t=s}return this.catchUp(t,e)}isCaughtUp(e){const t=h(this.host.sql());return t!==void 0&&this.isFreshEnough(t,e)}async catchUp(e,t){let s=e,n=!1;for(let o=0;o<B;o+=1){const i=await this.pull(s.appliedSeq);if(i===void 0)return this.whenOwnerUnreachable(s,t);const c=j(s,i);if(c!==void 0){const a=await this.recover(s,c,n);if(typeof a=="string")return a;n=!0,s=a;continue}const d=i.changes.length<A,u=await this.applyPage(i,s,d);if(u===void 0)return"unavailable";if(s=u,d||this.isFreshEnough(s,t))return this.verdict(s,t)}return this.verdict(s,t)}verdict(e,t){return this.isFreshEnough(e,t)?"fresh":"stale"}async recover(e,t,s){return t==="fork"?(this.divergent=!0,"unavailable"):s?"unavailable":await this.resnapshot(e)??"unavailable"}whenOwnerUnreachable(e,t){return t===void 0&&this.isFreshEnough(e,void 0)?"fresh":"unavailable"}async applyPage(e,t,s){if(!await this.applyAtomically("replica.applyPage",e.changes))return;const n={appliedSeq:e.cursor,epoch:e.epoch,syncedAtMs:s?Date.now():t.syncedAtMs};return l(this.host.sql(),n),n}async applyAtomically(e,t){if(t.length===0)return!0;try{return await this.host.applyChanges(t),!0}catch(s){return K(s)||(this.divergent=!0),this.host.reportError?.(e,s),!1}}async fetchSnapshot(){const e=await this.request({type:"replica_bootstrap"});if(e===void 0)return;const t=v(await e.json());if(t.truncated===!0){this.divergent=!0;return}return t}async resnapshot(e){const t=await this.fetchSnapshot();if(t===void 0)return;const s={...O,...this.host.transactionLimits()},n=[],o=new Set;let i=0;for(const{doc:d,table:u}of t.rows){const a=String(d._id);o.add(y(u,a)),i+=I(d)??Number.POSITIVE_INFINITY,n.push({doc:d,id:a,op:"insert",seq:t.cursor,table:u,ts:0})}if(this.overWriteBudget(n.length,i,s))return;for(const{doc:d,table:u}of await this.host.exportRows()){const a=String(d._id);o.has(y(u,a))||n.push({id:a,op:"delete",seq:t.cursor,table:u,ts:0})}if(this.overWriteBudget(n.length,i,s)||!await this.applyAtomically("replica.resnapshot",n))return;const c={appliedSeq:t.cursor,epoch:t.epoch,syncedAtMs:e.syncedAtMs};return l(this.host.sql(),c),c}overWriteBudget(e,t,s){return e<=s.maxWrittenRows&&t<=s.maxWrittenBytes?!1:(this.host.reportError?.("replica.resnapshot",new T("TRANSACTION_LIMIT_EXCEEDED",`a re-snapshot would write ${String(e)} documents and ${String(t)} bytes, over the ${String(s.maxWrittenRows)}-document / ${String(s.maxWrittenBytes)}-byte transaction limit`)),!0)}async bootstrap(){const e=await this.fetchSnapshot();if(e===void 0)return;const{errors:t}=await this.host.importRows(e.rows);if(t.length>0){this.divergent=!0;return}const s={appliedSeq:e.cursor,epoch:e.epoch,syncedAtMs:Date.now()};return l(this.host.sql(),s),s}isFreshEnough(e,t){return t!==void 0?e.appliedSeq>=t:Date.now()-e.syncedAtMs<=E(this.host.env(),"LUNORA_REPLICA_MAX_STALENESS_MS",P)}async pull(e){const t=await this.request({sinceSeq:e,type:"replica_pull"});return t===void 0?void 0:v(await t.json())}async request(e){const t=this.host.shardBinding(),s=L(this.host.env(),t,this.ownerKey,this.host.shardJurisdiction());if(s===void 0)return;const n=JSON.stringify(e),o={"content-type":"application/json","x-lunora-shard-binding":t??""},i=R(this.host.env());i!==void 0&&(o[S]=await U(i,n));try{const c=await s.fetch("https://replica.internal/_lunora/replica",{body:n,headers:o,method:"POST"});return c.ok?c:void 0}catch{return}}}const re=r=>{const e=r.doName();if(e===void 0)return;const t=_(e);return t===void 0?void 0:new H(r,t.ownerKey,t.region)},se=async(r,e,t)=>{if(e.headers.get("x-lunora-replica-read")!=="1")return Response.json({error:{code:"REPLICA_READ_ONLY",message:`"${t}" is a write and cannot run on a read replica`}},{status:421});const s=await r.ensureFresh(M(e.headers.get("x-lunora-min-seq")));if(s!=="fresh")return Response.json({error:{code:"REPLICA_NOT_READY",message:`replica is ${s} for this read`}},{headers:{"x-lunora-replica-fallback":s},status:421})};export{re as createReplicaLink,se as gateReplicaDispatch,te as handleReplicaControl};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as i}from"@lunora/errors";const f=t=>{const e={args:t.args??{},enqueuedAt:typeof t.enqueuedAt=="number"?t.enqueuedAt:0,id:typeof t.id=="string"?t.id:"",scheduledFor:typeof t.scheduledFor=="number"?t.scheduledFor:0};typeof t.attempts=="number"&&(e.attempts=t.attempts),typeof t.functionPath=="string"&&(e.functionPath=t.functionPath),typeof t.pool=="string"&&(e.pool=t.pool),typeof t.shardKey=="string"&&(e.shardKey=t.shardKey),typeof t.workflow=="string"&&(e.workflow=t.workflow);const{state:n}=t;return(n==="canceled"||n==="failed"||n==="pending"||n==="running"||n==="succeeded")&&(e.state=n),typeof t.completedAt=="number"&&(e.completedAt=t.completedAt),typeof t.error=="string"&&(e.error=t.error),e},c=t=>{const e={key:typeof t.key=="string"?t.key:"",size:typeof t.size=="number"?t.size:0},n=t.httpMetadata?.contentType??t.contentType;typeof n=="string"&&(e.contentType=n),t.customMetadata&&typeof t.customMetadata=="object"&&(e.customMetadata=t.customMetadata),typeof t.sha256=="string"&&(e.sha256=t.sha256);const{uploaded:s}=t;return typeof s=="number"?e.uploaded=s:s instanceof Date&&(e.uploaded=s.getTime()),e},p=(t={})=>{const e=()=>{if(!t.scheduler)throw new i("INTERNAL",'ctx.db.system.query("_scheduled_functions"): no scheduler configured. Pass `scheduler` to createShardDO().');return t.scheduler},n=()=>{if(!t.storage)throw new i("INTERNAL",'ctx.db.system.query("_storage"): no storage configured. Pass `storage` to createShardDO().');return t.storage},s=async()=>(await e().list()).map(o=>f(o)),d=async()=>{const{objects:a}=await n().list();return a.map(o=>c(o))};return{get:(async(a,o)=>{if(a==="_scheduled_functions"){const r=await e().get(o);return r?f(r):null}const u=await n().getMetadata(o);return u?c(u):null}),query:(a=>a==="_scheduled_functions"?{collect:s}:{collect:d})}};export{p as createSystemReader};
|