@lunora/shard-engine 1.0.0-alpha.20 → 1.0.0-alpha.201
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-B0nxRm8q.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-BezPdXmB.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-nXMzGae5.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-BxYuR8CF.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 R}from"@lunora/errors";import{q as St}from"./MAX_TOKEN_LENGTH-iFEGEcDL-DBPC6ZWl.mjs";import{S as Qn,l as Pe,s as Vn}from"./fts-companion-CE3EmIjk.mjs";import{decodeWire as Jn,stableWireKey as Gt}from"@lunora/wire";import{sql as f}from"drizzle-orm";import{throwingScheduler as zn,aggregateSqlFunction as Oe,normalizeCountArgument as Yn}from"./AGGREGATE_SQL_FUNCTION-C_ZipS9R.mjs";import{aggregateTableName as st,encodeAggregateKey as ct,readAggregateValue as at}from"./aggregateTableName-B_CtIQCS.mjs";import{mergeWhere as Q,CountRlsUnsupportedError as dt,selectIndexForGroupBy as Xn,selectIndexForCount as Zn,selectIndexForAggregate as eo}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{backfillSearchIndexesForTable as to,searchIndexCoversTable as no}from"./backfillAggregateIndexes-BwCpPW7h.mjs";import{backfillAggregateIndexes as es,backfillRankIndexes as ts,backfillSearchIndexes as ns}from"./backfillAggregateIndexes-BwCpPW7h.mjs";import{appendCdcChange as oo,readCdcDocAtOrBefore as ro}from"./CDC_LOG_TABLE-BFGgqai8.mjs";import{CDC_LOG_TABLE as rs,applyCdcChanges as is,bumpCdcEpoch as ss,cdcCanVouchFor as cs,cdcForkedError as as,cdcSeqLeavingRows as ds,cdcTouchesTables as ls,cdcTrimmedError as us,compactCdcDocs as fs,cursorBelowRetainedFloor as hs,minCdcReplayableSeq as ws,minCdcSeq as ps,readCdcChangeKeys as gs,readCdcChanges as ys,readCdcCursor as Es,readCdcEpoch as $s,trimCdcChanges as ms}from"./CDC_LOG_TABLE-BFGgqai8.mjs";import{allocateCommitSeq as io,COMMIT_SEQ_FIELD as so}from"./COMMIT_SEQ_FIELD-Da1DjGqo.mjs";import{createCompanionSync as co}from"./createCompanionSync-DO92CQek.mjs";import{isMemoryTable as jt}from"./clearMemoryTables-aMRERF0w.mjs";import{computeRankPage as Ht}from"./computeRankPage-B6umzbg4.mjs";import{SCAN_DEP as G,PRIMARY_READ as ao}from"./SCAN_DEP-B4Uu4g7l.mjs";import{runSql as pe,runDrizzle as K}from"./runDrizzle-RC09zZrh.mjs";import{p as lo,j as pt,D as ie,r as xe,W as uo,k as fe,b as Ue,A as lt,a as Ge,m as he,e as we,s as fo,t as ho,u as wo,i as po,q as Kt,h as En,g as go}from"./do-sql-105TONaE.mjs";import{renderSql as $n,unionAll as mn,WORKERD_SQLITE_LIMITS as Rn}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{a as yo,u as Eo}from"./estimate-bytes-C-C35VXL.mjs";import{coveringGeohashes as $o,boundingBoxGeohashes as mo,haversineMeters as Ro,pointInBoundingBox as So}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{NotFoundError as vo}from"./NotFoundError-BhF7FeFr.mjs";import{resolvePatch as _o,assertPatchAllowed as To,operatorFields as Ao,readPatchField as Nt}from"./assertPatchAllowed-CA_H466g.mjs";import{tiebreakDirectionFor as Io,encodeCursor as gt,nullsOrderSuffix as bo,normalizeOrderKeys as Qt,uniqueIndexFields as xo,buildSeekWhere as Co,decodeCursor as Vt,buildSeekBeforeWhere as Mo,softDeleteScope as Ie,applySelect as Sn}from"./CURSOR_PREFIX-rOdoinP8.mjs";import{rankTableName as Jt,sortColumnName as zt,resolveRankPartition as Do,encodePartitionKey as ko,RANK_TIEBREAK as Lo,rankPivotConditionSql as Fo}from"./RANK_TIEBREAK-D3ye2GsL.mjs";import{UNVOUCHABLE_DEP as Yt}from"./ADMIN_WILDCARD-BUrgWQ3-.mjs";import{idIndexKey as Bo,withUnknownIndexKeys as Wo,indexKeysForRow as qo,buildIndexRange as Po}from"./buildIndexRange-BTChxh3k.mjs";import{r as Ve,j as Ce,c as Z,t as Ye,i as Xt}from"./where-sql-BjY4rnqb.mjs";import{serializeSqlValue as Me}from"./serializeSqlValue-DeoBMpZ2.mjs";import{quoteIdentifier as De}from"./quoteIdentifier-CObIFRhb.mjs";import{whereOfFilter as Oo,isPushableWhere as Uo}from"./isPushableWhere-BeYAOjUb.mjs";import{deriveRelationEdges as Go,findRelated as jo}from"./RELATED_DEFAULT_LIMIT-CAh3WUMn.mjs";import{assertFlatPredicate as ut,findManyPage as Ho,resolveRelationPredicates as Ko,composeReadPredicate as No}from"./DEFAULT_MAX_RELATION_KEYS-B0nxRm8q.mjs";import{describeRelationWrites as Qo}from"./describeRelationWrites-omar6-u9.mjs";import{runRowValidators as je,transformOnlyDefinition as Vo,applyInsertDefaults as yt,resolveWith as Jo,relationHooks as zo,applyOnDelete as Yo,fanOutScalarCounts as Xo,CASCADE_MAX_ROWS as Zo}from"./applyInsertDefaults-nXMzGae5.mjs";import{guardWriter as er}from"./RLS_UNWRAP_SYMBOL-CZIpCjzt.mjs";import{mayHoldProjectedValue as tr}from"./BIGINT_KEY_DIGITS-DE6yshOt.mjs";import{createSystemReader as nr}from"./createSystemReader-BSCxr8Qs.mjs";import{ConflictError as ae}from"./ConflictError-C8GtJmjS.mjs";import{hasTrigger as Zt,runTriggers as or}from"./hasTrigger-CjlwI4le.mjs";import{advanceClientWatermark as Ss,migrateClientWatermark as vs,readClientWatermark as _s}from"./CLIENT_WATERMARK_TABLE-De7z_OHV.mjs";import{IDEMPOTENCY_TABLE as As,readIdempotent as Is,trimIdempotent as bs,writeIdempotent as xs}from"./IDEMPOTENCY_TABLE-COrgeP3O.mjs";import{runShardMigrations as Ms}from"./runShardMigrations-Bc7PsQhM.mjs";import{selectShapeMembers as ks,selectShapeRows as Ls}from"./selectShapeMembers-Dqx_m7BF.mjs";const rr=n=>{const i=atob(n),o=Uint8Array.from(i,s=>s.codePointAt(0)??0);return new TextDecoder().decode(o)},ir=()=>new R("INVALID_CURSOR","invalid cursor"),en=16,tn=8,z=1024,vt=(n,i)=>i.query(n),sr=(n,i)=>{if(n.length===0)return 0;let o=0;for(const[s,c]of i.entries()){const h=s===i.length-1;let g=0;for(const m of n)(h?m.startsWith(c):m===c)&&(g+=1);if(g===0)return 0;o+=g}return o},cr=(n,i)=>{if(!i)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)}},ar=(n,i,o)=>{const s={eq:(c,h)=>{if(!n.definition.filterFields?.includes(c))throw new R("INTERNAL",`field "${c}" is not a filter field of search index "${n.indexName}" on table "${i}"`);if(n.filters.length>=tn)throw new R("BAD_REQUEST",`search index "${n.indexName}" on table "${i}": at most ${String(tn)} .eq() filters are supported per search query`);return n.filters.push({field:c,value:h}),s},search:(c,h)=>{const g=n;if(c!==g.definition.field)throw new R("INTERNAL",`search index "${g.indexName}" on table "${i}" indexes "${g.definition.field}", not "${c}"`);const m=vt(h,o).length;if(m>en)throw new R("BAD_REQUEST",`search index "${g.indexName}" on table "${i}": at most ${String(en)} search terms are supported (got ${String(m)})`);return g.field=c,g.query=h,g.hasQuery=!0,s}};return s},dr=n=>{if(n.length>z)throw new R("BAD_REQUEST",`more than ${String(z)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},lr=n=>Math.min(n.offset+n.numItems+1,z),ur=n=>btoa(`search:${String(n)}`),fr=n=>{let i;try{i=rr(n)}catch{return}if(!i.startsWith("search:"))return;const o=Number(i.slice(7));return Number.isInteger(o)&&o>=0?o:void 0},hr=n=>{if(typeof n.endCursor=="string")throw new R("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 R("BAD_REQUEST",`search pagination needs a finite numItems, got ${String(n.numItems)}`);const i=Math.max(0,Math.floor(n.numItems)),o=n.cursor?fr(n.cursor):0;if(o===void 0)throw ir();if(o+i>=z)throw new R("BAD_REQUEST",`search pagination reaches the ${String(z)}-document limit (offset ${String(o)} + ${String(i)} requested) — a page must end below the cap so the probe row that answers \`hasMore\` still fits: retry with numItems ${String(Math.max(1,z-o-1))} or fewer, or narrow the query or the filters instead`);return{numItems:i,offset:o}},wr=(n,i)=>{const o=i.offset+i.numItems,s=i.numItems>0&&n.length>o;return{continueCursor:s?ur(o):null,isDone:!s,page:n.slice(i.offset,o)}},pr=n=>{if(n===void 0)return z+1;if(!Number.isFinite(n))return z;const i=Math.max(0,Math.floor(n));if(i>z)throw new R("BAD_REQUEST",`search returns at most ${String(z)} documents (asked for ${String(i)}) — narrow the query or paginate instead`);return i},vn=500,_n=(n,i,o)=>{if(n!==void 0&&n!==Number.POSITIVE_INFINITY&&(!Number.isInteger(n)||n<0))throw o(`${i}: batch limit must be a non-negative integer`);return n??vn},Tn=(n,i,o,s)=>{if(n>i)throw s(`${o}: batch of ${String(n)} exceeds the limit of ${String(i)} (raise options.limit or chunk the call)`)},gr=32,yr=1024,An=(n,i,o,s)=>{const c=`SELECT id, _creationTime, ${De(ie)} FROM ${De(n)}`,h=`ORDER BY ${o}${s===void 0?"":` LIMIT ${String(s)}`}`;return i===void 0?Ve(`${c} ${h}`):Ce(`${c} WHERE `,i,` ${h}`)},Xe={fieldRef:n=>Ve(pt(n)),rangeTypeGuard:(n,i)=>Ve(lo(n,i)),serialize:Me},Er=n=>n===void 0?"":bo(n==="first"),In=n=>{const i=n.map(o=>`${pt(o.field)} ${o.direction==="desc"?"DESC":"ASC"}${Er(o.nulls)}`);return n.some(o=>o.field==="_id"||o.field==="id")||i.push(`${pt("id")} ${Io(n)==="desc"?"DESC":"ASC"}`),i.join(", ")},$r={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},bn=n=>new Set(n.sqlConditions.filter(i=>i.comparator==="=").map(i=>i.field)),mr=n=>{const i=bn(n);let o=0;for(;o<n.indexFields.length&&i.has(n.indexFields[o]??"");)o+=1;return n.indexFields.slice(o)},Rr=(n,i)=>{const o=n.order,s=mr(n),{shape:c}=i;return s.length>0?Qt(s.map(h=>({[h]:o})),c,{pinned:bn(n),uniqueBy:xo(i.indexes,c)}):Qt([{_creationTime:o}],c)},Sr=(n,i,o,s)=>{const c=n.sqlConditions.map(h=>({[h.field]:{[$r[h.comparator]??"eq"]:h.value}}));if(o&&c.push(Co(i,Vt(o))),s&&c.push(Mo(i,Vt(s))),c.length!==0)return c.length===1?c[0]:{AND:c}},vr=n=>{if(n.want!==void 0)return n.selective?Math.max(n.want,gr):n.want},Et=(n,i,o,s,c,h,g)=>{const m=Rr(s,o),E=In(m),u=[],{filters:C,want:T}=h;let v=h.cursor??void 0,b=vr(h);if(T===0)return{documents:u,orderKeys:m};for(;;){const W=Z(Sr(s,m,v,h.endCursor),Xe,Ye),q=An(i,c&&W?Ce(W," AND ",c):c??W,E,b),B=pe(n,q.text,...q.params).toArray();let O={};g(B.length);for(const j of B)if(O=xe(j),C.every(ee=>ee(O))&&u.push(O)===T)return{documents:u,orderKeys:m};if(b===void 0||B.length<b)return{documents:u,orderKeys:m};v=gt(O,m),b=Math.max(b,Math.min(b*2,yr))}},_r=(n,i,o,s,c,h,g,m)=>{const E=Math.max(0,Math.floor(c.numItems));if(typeof c.endCursor=="string"){const{documents:W,orderKeys:q}=Et(n,i,o,s,h,{cursor:c.cursor,endCursor:c.endCursor,filters:g.all,selective:g.selective,want:void 0},m),B=W.length>=2?W[Math.floor(W.length/2)-1]:void 0;return{continueCursor:c.endCursor,isDone:!0,page:W,splitCursor:B?gt(B,q):null}}const{documents:u,orderKeys:C}=Et(n,i,o,s,h,{cursor:c.cursor,filters:g.all,selective:g.selective,want:E+1},m),T=u.length>E,v=T?u.slice(0,E):u,b=v.at(-1);return{continueCursor:T&&b?gt(b,C):null,isDone:!T,page:v}},Ze=n=>{const i=new Map;return o=>{const s=i.get(o);if(s!==void 0)return s;const c=n(De(o));return i.set(o,c),c}},ge=De(ie),Tr=Ze(n=>`INSERT INTO ${n} (id, _creationTime, ${ge}) VALUES (?, ?, ?)`),nn=Ze(n=>`UPDATE ${n} SET ${ge} = ? WHERE id = ? AND ${ge} = ?`),Ar=Ze(n=>`UPDATE ${n} SET _creationTime = ?, ${ge} = ? WHERE id = ? AND ${ge} = ?`),Ir=Ze(n=>`DELETE FROM ${n} WHERE id = ? AND ${ge} = ?`),br="SELECT changes() AS changed",on=new Map,xr="",Cr=n=>{const i=JSON.stringify(n),o=on.get(i);if(o!==void 0)return o;const s=n.map(h=>f`SELECT ${f.raw(`'${h.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${f.identifier(ie)} FROM ${f.identifier(h)} WHERE id = ${xr}`),{sql:c}=$n("sqlite",f`${mn(s)} LIMIT 1`);return on.set(i,c),c},Mr=(n,i)=>i.map(()=>n),Dr=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,kr=n=>{if(!Dr.test(n))throw new R("INTERNAL",`invalid clientId ${JSON.stringify(n)}: a client-supplied row id must be a UUID`)},$t=n=>{if(n.includes("\0"))throw new R("BAD_REQUEST",`invalid row id ${JSON.stringify(n)}: a row id cannot hold a NUL character (U+0000)`)},Lr=(n,i,o,s)=>{if(o!==!0)return;const c=n!==void 0&&"serverDefault"in(n.shape._id?._meta?.column??{});for(const h of i){const g=c?yt(n,h,s)._id:h._id;typeof g=="string"&&$t(g)}},rn=50,He=Math.floor(Rn.boundParams/3),sn=Rn.boundParams,Fr=128,Je=n=>new R("BATCH_LIMIT_EXCEEDED",n,{status:400}),Ke=(n,i,o)=>{Tn(n,_n(i,o,Je),o,Je)},cn=async(n,i,o,s,c)=>{const h=_n(s,c,Je),{page:g}=await n.findMany(i,Number.isFinite(h)?{limit:h+1,omitContinueCursor:!0,where:o}:{where:o});return g.length>h&&Tn(Math.max(await n.count(i,{where:o}),g.length),h,c,Je),g},Br=n=>{const i={eq:(o,s)=>(n.sqlConditions.push({comparator:"=",field:o,value:s}),i),gt:(o,s)=>(n.sqlConditions.push({comparator:">",field:o,value:s}),i),gte:(o,s)=>(n.sqlConditions.push({comparator:">=",field:o,value:s}),i),lt:(o,s)=>(n.sqlConditions.push({comparator:"<",field:o,value:s}),i),lte:(o,s)=>(n.sqlConditions.push({comparator:"<=",field:o,value:s}),i)};return i},Wr=n=>Math.max(n,z),xn=(n,i)=>{const o=n.filters.map(s=>f`${we(s.field)} = ${Me(s.value)}`);return i&&o.push(i),o},qr=(n,i,o,s,c)=>{const h=vt(o.query,St(o.definition.language));if(h.length===0)return[];const g=Qn(i,o.indexName),m=`${g}__vocab`,E=h.length-1,u=h.map((q,B)=>{const O=cr(q,B===E),j=O.exact?f`${f.identifier("term")} = ${O.lower}`:f`${f.identifier("term")} >= ${O.lower} AND ${f.identifier("term")} < ${O.upper}`;return f`SELECT ${f.identifier("doc")}, ${f.raw(String(B))} AS ${f.identifier("__term__")}, COUNT(*) AS ${f.identifier("__n__")} FROM ${f.identifier(m)} WHERE ${j} GROUP BY ${f.identifier("doc")}`}),C=h.map((q,B)=>f`SUM(CASE WHEN u.${f.identifier("__term__")} = ${f.raw(String(B))} THEN u.${f.identifier("__n__")} ELSE 0 END)`),T=f`SELECT f.${f.identifier(Pe)} AS ${f.identifier(Pe)}, ${f.join(C,f` + `)} AS ${f.identifier("__score__")} FROM (${mn(u)}) u JOIN ${f.identifier(g)} f ON f.rowid = u.${f.identifier("doc")} GROUP BY f.${f.identifier(Pe)} HAVING ${f.join(C.map(q=>f`${q} > 0`),f` AND `)}`,v=xn(o,c);let b=f`SELECT m.id, m._creationTime, m.${f.identifier(ie)}, s.${f.identifier("__score__")} AS ${f.identifier("__score__")} FROM (${T}) s JOIN ${f.identifier(i)} m ON m.id = s.${f.identifier(Pe)}`;v.length>0&&(b=f`${b} WHERE ${f.join(v,f` AND `)}`),b=f`${b} ORDER BY s.${f.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${f.raw(String(s))}`;const W=[];for(const q of K(n,b)){const B=En(q);if(B){const O=q.__score__;W.push({document:B,score:typeof O=="number"?O:Number(O??0)})}}return W},Pr=(n,i,o,s,c)=>{const h=St(o.definition.language),g=vt(o.query,h);if(g.length===0)return[];const m=xn(o,c);let E=f`SELECT id, _creationTime, ${f.identifier(ie)} FROM ${f.identifier(i)}`;m.length>0&&(E=f`${E} WHERE ${f.join(m,f` AND `)}`),E=f`${E} ORDER BY _creationTime DESC, id ASC LIMIT ${f.raw(String(Wr(s)))}`;const u=K(n,E).toArray(),C=[];for(const T of u){const v=En(T);if(!v)continue;const b=sr(Vn(v,o.definition),g);b>0&&C.push({creationTime:typeof v._creationTime=="number"?v._creationTime:0,doc:v,id:typeof v._id=="string"?v._id:"",score:b})}return C.sort((T,v)=>v.score-T.score||v.creationTime-T.creationTime||T.id.localeCompare(v.id)),C.slice(0,s).map(T=>({document:T.doc,score:T.score}))},ft=(n,i,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 R("BAD_REQUEST",`geo index "${s}" on table "${o}": ${i} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},Or=(n,i)=>{const o=n,s={near:(c,h)=>{if(o.within)throw new R("INTERNAL",`geo index "${o.indexName}" on table "${i}": call .near() or .within(), not both`);if(ft(c,".near() point",i,o.indexName),!Number.isFinite(h)||h<=0)throw new R("BAD_REQUEST",`geo index "${o.indexName}" on table "${i}": .near() radiusMeters must be a finite number > 0, got ${String(h)}`);return o.near={point:{lat:c.lat,lng:c.lng},radiusMeters:h},s},within:c=>{if(o.near)throw new R("INTERNAL",`geo index "${o.indexName}" on table "${i}": call .near() or .within(), not both`);if(ft(c.sw,".within() sw corner",i,o.indexName),ft(c.ne,".within() ne corner",i,o.indexName),c.sw.lat>c.ne.lat)throw new R("BAD_REQUEST",`geo index "${o.indexName}" on table "${i}": .within() corners are transposed (sw.lat > ne.lat)`);if(c.sw.lng>c.ne.lng)throw new R("BAD_REQUEST",`geo index "${o.indexName}" on table "${i}": .within() box crosses the antimeridian (sw.lng > ne.lng), which is not supported — split it into two boxes at ±180 and union the results`);return o.within={ne:{lat:c.ne.lat,lng:c.ne.lng},sw:{lat:c.sw.lat,lng:c.sw.lng}},s}};return s},Ur=(n,i)=>{const o=n[i];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},Gr=(n,i)=>{const o=Ur(n,i.definition.field);if(!o)return;const s=typeof n._creationTime=="number"?n._creationTime:0;if(i.near){const c=Ro(i.near.point,o);return c<=i.near.radiusMeters?{creationTime:s,distance:c}:void 0}return So(o,i.within)?{creationTime:s,distance:0}:void 0},jr=(n,i,o,s)=>{if(!o.near&&!o.within)throw new R("INTERNAL",`geo index "${o.indexName}" on table "${i}": call .near(point, radius) or .within(box)`);const c=o.near?$o(o.near.point,o.near.radiusMeters):mo(o.within),h=go(i,o.indexName),g=c.map(T=>f`(g.${f.identifier("__geohash__")} >= ${T} AND g.${f.identifier("__geohash__")} < ${`${T}{`})`),m=[f`(${f.join(g,f` OR `)})`];s&&m.push(s);const E=f`SELECT m.id, m._creationTime, m.${f.identifier(ie)} FROM ${f.identifier(h)} g JOIN ${f.identifier(i)} m ON m.id = g.${f.identifier("__id__")} WHERE ${f.join(m,f` AND `)}`,u=K(n,E).toArray(),C=[];for(const T of u){const v=xe(T),b=v?Gr(v,o):void 0;v&&b&&C.push({creationTime:b.creationTime,distance:b.distance,doc:v})}return C.sort((T,v)=>T.distance-v.distance||v.creationTime-T.creationTime),C},Cn=(n,i,o,s)=>{const c=[];for(const h of n)if(i.every(g=>g(s(h)))&&(c.push(h),typeof o=="number"&&c.length>=o))break;return c},Hr=(n,i,o,s,c,h=()=>{})=>{const g=o.within!==void 0,m=jr(n,i,o,c).map(E=>({distanceMeters:g?null:E.distance,document:E.doc}));return h(m.length),typeof s=="number"?m.slice(0,Math.max(0,Math.floor(s))):m},an=(n,i,o,s,c,h,g=()=>{})=>{const{geo:m}=o;if(!m)throw new R("INTERNAL","runGeoTerminalScored called without a staged geo query");const E=c.length>0,u=Hr(n,i,m,E?void 0:h,s,g);return E?Cn(u,c,h,C=>C.document):u},dn=(n,i,o)=>{const s=n.shape[i];if(s!==void 0&&tr(s))throw new R("BAD_REQUEST",`${o}: "${i}" may hold an order-preserving key rather than a value SQL can reduce or group — declare an aggregateIndex covering this (by, field, op) so the maintained companion answers it instead (its running total is a REAL, so it stays exact only while the total is inside 2^53)`)},Kr=n=>{let i=0;const o=[],s={...Xe,relationExists:c=>{const{childWhere:h,negated:g,parentTable:m,relation:E}=c,u=`__rel_${String(i)}`,C=o.at(-1)??m;i+=1,n(E.table,G);const T=E.kind==="one"?E.field:E.references,v=E.kind==="one"?E.references:E.field,b=Ve(`${Kt(u,v)} = ${Kt(C,T)}`);o.push(u);const W=Z(h,s,Ye);o.pop();const q=W===void 0?b:Ce(b," AND ",W),B=Ce("EXISTS (SELECT 1 FROM ",Xt(E.table)," AS ",Xt(u)," WHERE ",q,")");return g?Ce("NOT ",B):B}};return s};class Nr extends R{constructor(i="unique() found more than one matching document"){super("NOT_UNIQUE",i,{name:"NotUniqueError"})}}const Qr=/\s/u,Vr=String.fromCodePoint(0),ln=(n,i,o)=>{if(!n.tables[i])throw new R("INTERNAL",`unknown table: ${i}`);return typeof o!="string"||o.length===0||Qr.test(o)||o.includes(Vr)?null:o},Mn=(n,i,o,s=()=>{},c=()=>{},h=()=>{},g)=>{const m=i.tables[o];if(!m)throw new R("INTERNAL",`unknown table: ${o}`);const E=Ie(m.softDeleteMode,void 0),u=g??{indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[],verifyFilters:[]},C=()=>{const S=Q(E,u.pushedWhere);return S?Z(S,he):void 0},T=()=>{const S=Q(E,u.pushedWhere);return S?Z(S,Xe,Ye):void 0},v=()=>[...u.inMemoryFilters,...u.verifyFilters];let b=0;const W=S=>{const{search:M}=u;if(!M)throw new R("INTERNAL","runSearchFetch called without a staged search");to(wo(n),o,m);const L=u.inMemoryFilters.length>0,F=pr(L?void 0:S),k=po(n);if(k&&!no(n,o,M.definition))throw new R("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 ye=C(),te=k?qr(n,o,M,F,ye):Pr(n,o,M,F,ye);!L&&S===void 0&&dr(te);const Ee=v();return b=te.length,Ee.length>0?Cn(te,Ee,S,J=>J.document):te},q=S=>W(S).map(M=>M.document),B=S=>{const M=hr(S);return wr(q(lr(M)),M)},O=()=>{if(u.search||u.geo||u.indexName===void 0){c(void 0);return}c(Po(o,u.indexName,u.indexFields,u.sqlConditions,Me))},j=S=>{O();let M=0;const L=(()=>{if(u.search){const F=q(S);return M=b,F}return u.geo?an(n,o,u,C(),v(),S,F=>{M=F}).map(F=>F.document):Et(n,o,m,u,T(),{filters:v(),selective:u.inMemoryFilters.length>0,want:S===void 0?void 0:Math.max(0,Math.floor(S))},F=>{M+=F}).documents})();return h(Math.max(M,L.length)),L},ee=()=>{if(!u.search&&!u.geo)throw new R("INTERNAL",`ctx.db.query("${o}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);O();let S=0;const M=(()=>{if(u.search){const L=W(void 0);return S=b,L}return an(n,o,u,C(),v(),void 0,L=>{S=L})})();return h(Math.max(S,M.length)),M},N={async*[Symbol.asyncIterator](){const S=Mn(n,i,o,s,c,h,{...u,indexFields:[...u.indexFields],inMemoryFilters:[...u.inMemoryFilters],sqlConditions:[...u.sqlConditions],verifyFilters:[...u.verifyFilters]});if(u.search){yield*await S.collect();return}let M;for(;;){const L=await S.paginate({cursor:M??null,numItems:Fr});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=Oo(S);return M!==void 0&&Uo(M,m.shape)?(u.pushedWhere=Q(u.pushedWhere,M),u.verifyFilters.push(S)):u.inMemoryFilters.push(S),N},async first(){return j(1)[0]??null},order(S){return u.order=S==="desc"?"desc":"asc",N},async paginate(S){let M=0;if(O(),u.search){const F=B(S);return h(F.page.length),F}if(u.geo)throw new R("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const L=_r(n,o,m,u,S,T(),{all:v(),selective:u.inMemoryFilters.length>0},F=>{M+=F});return h(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 Nr(`unique() on table "${o}" matched ${String(S.length)} documents; expected at most one`);return S[0]??null},withGeoIndex(S,M){const L=(m.geoIndexes??[]).find(k=>k.name===S);if(!L)throw new R("INTERNAL",`unknown geo index "${S}" on table "${o}"`);s(o,S,"geo");const F={definition:L,indexName:S};if(u.geo=F,M(Or(F,o)),!F.near&&!F.within)throw new R("INTERNAL",`geo index "${S}" on table "${o}" requires a .near(point, radius) or .within(box) call`);return N},withIndex(S,M){const L=m.indexes.find(F=>F.name===S);if(!L)throw new R("INTERNAL",`unknown index "${S}" on table "${o}"`);return s(o,S,"index"),u.indexName=S,u.indexFields=L.fields,M&&M(Br(u)),N},withSearchIndex(S,M){const L=(m.searchIndexes??[]).find(k=>k.name===S);if(!L)throw new R("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(u.search=F,M(ar(F,o,St(L.language))),!F.hasQuery)throw new R("INTERNAL",`search index "${S}" on table "${o}" requires a .search(field, query) call`);return N}};return N},ht=(n,i,o,s)=>{const c=o;for(const[h,g]of ho(n)){if(g.serverDefault){h in i&&(c[h]=g.serverDefault({auth:s}));continue}g.onUpdateFn&&!(h in i)&&(c[h]=g.onUpdateFn())}},un=5,fn=(n,i)=>{for(const o of Object.keys(i))if(i[o]===void 0)throw new R("INTERNAL",`Cannot ${n} field '${o}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},hn=["_commitSeq","_creationTime","_id"],Ne=n=>hn.some(i=>i in n)?Object.fromEntries(Object.entries(n).filter(([i])=>!hn.includes(i))):n,Jr=/unique constraint failed/i,zr=n=>n instanceof Error&&Jr.test(n.message),Yr=/string or blob too big/iu,Xr=(n,i)=>{if(!(!(n instanceof Error)||!Yr.test(n.message)))throw new R("PAYLOAD_TOO_LARGE",`document is too large to store in "${i}": a single row cannot exceed the storage engine's per-row ceiling (2 MB on a Durable Object's SQLite). The limit is on the STORED bytes, which are UTF-8, and v.bytes()/v.bigint() columns are stored twice on a shard-local table. Keep the payload in R2 (ctx.storage) and store a reference on the row.`)},mt=(n,i,o,s)=>{try{pe(n,o,...s)}catch(c){throw zr(c)?new ae(`unique constraint violation on "${i}"`,"unique"):(Xr(c,i),c)}},Qe=(n,i,o,s)=>{if(mt(n,i,o,s),pe(n,br).one().changed===0)throw new ae(`optimistic concurrency conflict on "${i}" — the row changed during this mutation; refetch and retry`,"occ")},wn=(n,i,o,s,c,h,g)=>{const m=[];for(let T=0;T<o.length+1;T+=1){const v=o[T],b=s[T],W=b?.direction==="desc"?"desc":"asc",q=v===void 0||b===void 0?f`${f.identifier(Lo)} < ${g}`:Fo(v,h[T],W,!1);if(q===void 0)continue;const B=[];for(let j=0;j<T;j+=1)B.push(f`${f.identifier(o[j])} IS ${h[j]}`);B.push(q);const[O]=B;m.push(B.length===1&&O!==void 0?O:f`(${f.join(B,f` AND `)})`)}const E=m.length>0?f.join(m,f` OR `):f`1 = 0`,u=K(n,f`SELECT COUNT(*) AS c FROM ${f.identifier(i)} WHERE ${f.identifier("__partition__")} = ${c} AND (${E})`).one(),C=K(n,f`SELECT COUNT(*) AS c FROM ${f.identifier(i)} WHERE ${f.identifier("__partition__")} = ${c}`).one();return{before:u.c,total:C.c}},Zr=n=>{const i=new Map;for(const[s,c]of Object.entries(n.tables))for(const h of Object.values(c.relationMap??{}))h.kind==="one"&&(h.onDelete==="cascade"||h.onDelete==="set null")&&i.set(h.table,[...i.get(h.table)??[],{holder:s,op:h.onDelete==="cascade"?"delete":"update"}]);const o=s=>{const c=new Set,h=[s];for(let g=h.pop();g!==void 0;g=h.pop())for(const{holder:m,op:E}of i.get(g)??[]){if(m===s||Zt(n,m,E))return!0;c.has(m)||(c.add(m),h.push(m))}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))},ei=n=>{const i=new Map;for(const[o,s]of Object.entries(n.tables))s.softDeleteMode&&i.set(o,s.softDeleteMode.field);return i},wt=new WeakMap,ti=(n,i)=>{let o=wt.get(i.tables);if(!wt.has(i.tables)){const c=Object.keys(i.tables).map(h=>h.replaceAll(/[$()*+.?[\\\]^{|}]/gu,String.raw`\$&`));o=c.length===0?void 0:new RegExp(`"(${c.join("|")})"`,"gu"),wt.set(i.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},ni=(n,i,o)=>{for(const s of n){const c=s,h=c?.[ie];if(typeof h=="string"){const g=c?.id,m=Eo(h);typeof g!="string"?i.recordReadBytes(m):o===void 0?i.recordDocumentRead(`${g}\0${String(m)}`,m):i.recordDocumentRead(`${o}\0${g}`,m)}}},oi=(n,i,o)=>{if(i===void 0)return n;const s=(c,...h)=>{const g=n.exec(c,...h),m=g.one.bind(g),E=g[Symbol.iterator].bind(g),u=o===void 0?void 0:ti(c,o);let C=!1;const T=v=>{ni(v,i,u)};return g.toArray=()=>{const v=[];for(const b of{[Symbol.iterator]:E})T([b]),v.push(b);return v},g.one=()=>{C=!0;try{const v=m();return T([v]),v}finally{C=!1}},g[Symbol.iterator]=function*(){for(const b of{[Symbol.iterator]:E})C||T([b]),yield b},g};return new Proxy(n,{get:(c,h)=>h==="exec"?s:h===uo?c:Reflect.get(c,h,c)})},ri=new Map([["findFirst","rows"],["findFirstOrThrow","rows"],["findMany","page"],["get","rows"],["lookupById","lookup"],["rankPage","page"]]),ii=new Map([["collect","rows"],["collectWithScores","scored"],["first","rows"],["paginate","page"],["take","rows"],["unique","rows"]]),be=(n,i,o)=>{if(typeof n!="object"||n===null)return;const s=yo(n);if(s===void 0)return;const c=n._id;typeof c=="string"?o.recordDocumentRead(`global\0${i}\0${c}`,s):o.recordReadBytes(s)},ze=(n,i,o,s)=>{if(typeof n!="object"||n===null)return;const c=n;switch(i){case"lookup":{be(c.row,typeof c.tableName=="string"?c.tableName:o,s);return}case"page":{for(const h of c.page??[])be(h,o,s);return}case"rows":{for(const h of Array.isArray(n)?n:[n])be(h,o,s);return}default:for(const h of Array.isArray(n)?n:[])be(h.document,o,s)}},Dn=(n,i,o)=>new Proxy(n,{get:(s,c)=>{const h=Reflect.get(s,c,s);if(typeof h!="function")return h;if(c===Symbol.asyncIterator)return async function*(){for await(const E of Reflect.apply(h,s,[]))be(E,i,o),yield E};const g=ii.get(c);return(...m)=>{const E=Reflect.apply(h,s,m);return g!==void 0?Promise.resolve(E).then(u=>(ze(u,g,i,o),u)):typeof E=="object"&&E!==null&&!(E instanceof Promise)?Dn(E,i,o):E}}}),si=new Set(["findFirst","findFirstOrThrow","findMany"]),ci=n=>{const i=n[1],o=i?.select;if(!Array.isArray(o))return;const s=Object.fromEntries(Object.entries(i).filter(([g])=>g!=="select")),c=s.with,h=g=>Sn(g,o,c);return{args:[n[0],s,...n.slice(2)],project:(g,m)=>typeof g!="object"||g===null?g:m==="page"?{...g,page:h(g.page)}:h([g])[0]}},pn=256,Rt=4096,ai=1024*1024,di=async(n,i,o,s)=>{const c=i[1]??{},h=[];let{cursor:g}=c,m=pn,E=0;for(;;){const u=await n([i[0],{...c,cursor:g,limit:m},...i.slice(2)]);if(Array.isArray(u))return ze(u,"rows",o,s),[...h,...u];const C=s.headroom().readBytes;if(ze(u,"page",o,s),h.push(...u.page),u.isDone||typeof u.continueCursor!="string")return{continueCursor:null,isDone:!0,page:h};g=u.continueCursor,E+=s.headroom().readBytes-C,m=E>0?Math.min(Rt,Math.max(pn,Math.floor(ai*h.length/E))):Rt}},li=(n,i)=>n===void 0||i===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)=>Dn(Reflect.apply(c,o,g),String(g[0]),i);const h=ri.get(s);return h===void 0?c:async(...g)=>{const m=si.has(s)?ci(g):void 0;let E=m?.args??g;const u=String(g[0]),C=E[1],T=s==="findMany"&&typeof C?.endCursor=="string",v=s==="findMany"&&typeof C?.limit!="number"&&!T;if(T&&typeof C.limit!="number"&&(E=[E[0],{...C,limit:Rt},...E.slice(2)]),v){const W=await di(q=>Reflect.apply(c,o,q),E,u,i);return m===void 0?W:m.project(W,h)}const b=await Reflect.apply(c,o,E);return ze(b,h,u,i),m===void 0?b:m.project(b,h)}}}),gn=new WeakMap,yn=new WeakMap,ui=500,fi=n=>{const{baselineSeq:i,onStalePatchDropped:o}=n,{headroom:s}=n,c=gn.get(n)??{value:void 0},h=yn.get(n)??{value:0};let g;const m=()=>{if(g===void 0){const e={...n,enforceRls:!1,headroom:void 0};gn.set(e,c),yn.set(e,h),g=fi(e)}return g},E=oi(n.sql,s,n.schema),{schema:u}=n,C=n.broadcast??(()=>{}),T=(e,t)=>{if(!Object.hasOwn(u.tables,e))throw new R("BAD_REQUEST",`${t}: "${e}" is not a table in this schema`)},v=Go(u),b=new Map;for(const e of v){const t=r=>(u.tables[r]?.shardMode?.kind??"root")==="root";!e.array&&t(e.sourceTable)&&t(e.targetTable)&&b.set(e.sourceTable,[...b.get(e.sourceTable)??[],e])}const W=(e,t,r)=>{for(const a of b.get(e)??[]){const l=t[a.column];if(typeof l!="string"||r?.[a.column]===l||a.targetTable===e&&t._id===l)continue;if(K(E,f`SELECT 1 FROM ${f.identifier(a.targetTable)} WHERE id = ${l} LIMIT 1`).toArray().length===0)throw new R("VALIDATION_ERROR",`${a.name} references ${a.targetTable} row "${l}", which does not exist`)}},q=Qo(u,n.inTransaction),B=Zr(u),O=ei(u),j=()=>n.inTransaction?.()===!0,ee=e=>u.tables[e]?.commitOrderedMode!==!0?{}:((c.value===void 0||!j())&&(c.value=io(E)),{[so]:c.value}),N=(e,...t)=>{const r=u.tables[e]?.indexes??[],a=[];let l;for(const p of t)p&&(typeof p._id=="string"&&p._id!==l&&(l=p._id,a.push(Bo(l))),a.push(...Wo(r,qo(r,p,Me))));return a.length>0?a:void 0},S=n.onRead??(()=>{}),M=e=>{jt(u.tables[e])&&S(Yt,Yt)},L=n.onReadRange??(e=>{S(e.table,G)}),F=e=>{M(e.table),L(e)},k=(e,t,r)=>{t!==void 0&&(r===!0||t!==G)&&s?.recordRead(1),M(e),S(e,t,r)},ye=(e,t)=>{const r=e.row._id;k(e.tableName,typeof r=="string"?r:t,typeof r=="string")},te=n.onIndexUse??(()=>{}),Ee=n.onWrite??(()=>{}),J=e=>{s?.recordWrite(e)},$e=async e=>{J(e.doc),await Ee(e)},{cache:de}=n,me=n.clock??(()=>Date.now()),_t=n.idGenerator??(()=>crypto.randomUUID()),Tt=n.scheduler??zn,Re=li(n.globalDb,s),le=n.auth??{identity:null,userId:null},At=n.cdc??!1,et=Tt,kn=nr({scheduler:typeof et.list=="function"&&typeof et.get=="function"?et:void 0,storage:n.storage}),Se=(e,t,r,a)=>{At&&!jt(u.tables[e])&&oo(E,me(),e,t,r,a)},It=(e,t,r,a)=>{const l=u.tables[e];if(l?.dropStalePatchesMode!==!0||!At)return!1;const p=i?.();if(p===void 0)return!1;const d=ro(E,e,t,p);if(d===void 0)return!1;const w=Ao(l,r);return Object.keys(Ne(r)).some(y=>!w.has(y)&&Gt(Nt(d,y))!==Gt(Nt(a,y)))},se=e=>u.tables[e]?.shardMode?.kind==="global",bt=(e,t)=>{if(se(e)){if(!Re)throw new R("INTERNAL",`cross-backend ${t} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return Re}return U},tt=e=>bt(e,"cascade"),H=(e,t)=>{if(se(e)){if(!Re)throw new R("INTERNAL",`${t} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return Re}},ce=(e,t,r)=>{de?.invalidateTable(t),C({key:r,op:e,table:t})},xt=async(e,t,r,a,l)=>{l&&J(r);const p=await e.insert(t,r,a);return C({key:p,op:"insert",row:{...r,_id:p},table:t}),p},Ln=(e,t)=>bt(e,"relation load").findMany(e,t),Fn=e=>e.through===void 0?[e.table]:[e.through.table,e.table],Ct=e=>{for(const t of e===void 0?[]:Fn(e))se(t)&&k(t,G)},Mt=(e,t)=>{const r=u.tables[e]?.relationMap??{};for(const[a,l]of Object.entries(t??{})){if(a==="_count"){for(const d of Object.keys(typeof l=="object"?l:{}))Ct(r[d]);continue}const p=r[a];p===void 0||l===void 0||l===!1||(Ct(p),typeof l=="object"&&Mt(p.table,l.with))}},nt=(e,t)=>(se(e)&&(k(e,G),Mt(e,t.with)),Ln(e,t)),Bn=e=>!se(e.table),Dt=n.relationExistsPushDown??"auto",kt=Dt!=="never",{maxRelationKeys:Lt}=n,ke=(e,t,r)=>Ko(e,{fetcher:nt,maxRelationKeys:Lt,relationBaseWhere:r,schema:u,tableName:t}),Wn=async(e,t,r,a)=>{const l=H(e,"relation grouped count");if(l)return k(e,G),Xo(($,P)=>l.count($,P),e,t,r,a);const p=u.tables[e];if(!p)throw new R("INTERNAL",`unknown table: ${e}`);k(e,G);const d=Ie(p.softDeleteMode,void 0),w={[t]:{in:r}},y=Q(Q(w,a),d),A=await ke(y,e,void 0),x=Z(A,he),I=we(t);let _=f`SELECT ${I} AS __fk__, COUNT(*) AS count FROM ${f.identifier(e)}`;x&&(_=f`${_} WHERE ${x}`),_=f`${_} GROUP BY ${I}`;const D=K(E,_).toArray();return new Map(D.map($=>[$.__fk__,$.count]))},Ft=new Set;for(const[e,t]of Object.entries(u.tables))for(const r of Object.values(t.triggerMap??{}))Ft.add(`${e} ${r.timing} ${r.op}`);const ne=(e,t,r)=>Ft.has(`${e} ${t} ${r}`),oe=async(e,t,r)=>{if(h.value+=1,h.value>rn)throw h.value-=1,new ae(`trigger recursion exceeded ${String(rn)} levels on "${r.table}" — check for a self-triggering write`,"trigger");try{await or({ctx:Kn,event:r,op:t,schema:u,tableName:r.table,timing:e})}finally{h.value-=1}},{ensureBackfilledForTable:ve,ensureBackfilledIndex:ot,ensureRankBackfilled:rt,ensureRankBackfilledForTable:_e,syncAggregates:Le,syncCompanionsForInsert:Bt,syncGeo:Fe,syncRanks:Te,syncSearch:Be}=co({broadcast:C,indexKeysFor:(e,t)=>N(e,t),invalidateCache:(e,t,r)=>de?.invalidate(e,t,N(e,r)),recordCdc:Se,schema:u,sql:E,verified:n.companionMemo?.verified}),Wt=(e,t,r)=>{const{shardMode:a}=t;if(a?.kind==="shardBy"&&!(a.field!==void 0&&(r.partitionBy??[]).includes(a.field)))throw Object.assign(new Error(`rank index "${r.name}" on "${e}" partitions across shards (shard key "${a.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})},qt=e=>Object.entries(u.tables).filter(([,t])=>t.shardMode?.kind!=="global").map(([t])=>t).filter(t=>e===void 0||t===e),Ae=e=>e===void 0||se(e)?Re:void 0,qn=e=>Object.entries(u.tables).flatMap(([t,r])=>se(t)?Object.values(r.relationMap??{}).flatMap(a=>a.through!==void 0||a.kind!=="one"||a.table!==e?[]:a.onDelete!=="cascade"&&a.onDelete!=="set null"?[]:[{action:a.onDelete==="cascade"?"delete":"update",field:a.field,holderTable:t,references:a.references}]):[]),Pn=async(e,t,r,a)=>r==="_id"?a:(await e.get(t,a))?.[r],On=async(e,t,r,a,l)=>{const p=[];let d;do{const w=await e.findMany(t,{cursor:d,includeDeleted:l,limit:ui,where:{[r]:a}});for(const y of w.page)p.push(String(y._id));d=w.isDone?void 0:w.continueCursor??void 0}while(d!==void 0&&p.length<=Zo);return p},Un=async(e,t,r,a,l,p)=>{const{action:d,field:w,holderTable:y,references:A}=r,x=await Pn(e,t,A,a);if(x==null)return{effects:[],toExpand:[]};const I=await On(e,y,w,x,p),_=I.filter($=>!l.announced.has(`${d}:${y}:${$}`)),D=d==="delete"?I.filter($=>!l.expanded.has(`${y}:${$}`)):[];for(const $ of _)l.announced.add(`${d}:${y}:${$}`);for(const $ of D)l.expanded.add(`${y}:${$}`);return{effects:_.map($=>({id:$,op:d,table:y})),toExpand:D}},Pt=async(e,t,r,a,l)=>{const p=[];for(const d of qn(t))for(const w of r){const y=await Un(e,t,d,w,a,l);p.push(...y.effects),y.toExpand.length>0&&p.push(...await Pt(e,d.holderTable,y.toExpand,a,l))}return p},it=async(e,t,r,a,l)=>{for(let d=0;d<r.length;d+=1)J(void 0);const p=a?.skipOnDelete===!0?[]:await Pt(e,t,r,{announced:new Set,expanded:new Set},a?.hard===!0);try{if(l!==void 0&&e.deleteMany!==void 0)try{return await e.deleteMany(t,r,l.options)}finally{for(const d of r)ce("delete",t,d)}for(const d of r)try{await e.delete(t,d,a)}finally{ce("delete",t,d)}return{deleted:r.length}}finally{for(const d of p)ce(d.op,d.table,d.id)}},re=(e,t)=>{const r=qt(t);for(let a=0;a<r.length;a+=sn){const l=r.slice(a,a+sn),[p]=pe(E,Cr(l),...Mr(e,l)).toArray();if(!p)continue;const d=p.__t__,w=xe(p);if(typeof d!="string"||!w)return;const y=p[ie];return{docJson:typeof y=="string"?y:fe(y??{}),row:w,tableName:d}}},Ot={assertRankPartitionLocal:Wt,ensureRankBackfilled:rt,onRead:k,rowToDocument:xe,schema:u,sql:E},Gn=(e,t,r)=>{const a=Z(r,he);return a===void 0||K(E,f`SELECT 1 FROM ${f.identifier(e)} WHERE ${f.identifier("id")} = ${t} AND ${a}`).toArray().length>0},jn=(e,t,r,a)=>It(e,t,r,a)?(o?.({fields:Object.keys(Ne(r)),id:t,table:e}),!0):!1,Hn=async(e,t,r,a,l)=>{const p=re(t,e);if(!p)return{applied:!1,doc:null};if(k(e,t),!Gn(e,t,r.where)||jn(e,t,r.patch,p.row))return{applied:!1,doc:p.row};try{await l(r.patch)}catch(d){if(d instanceof ae&&d.kind==="occ"&&a)return;throw d}return{applied:!0,doc:re(t,e)?.row??null}},Ut=async(e,t,r,a)=>{const{fetchLimit:l,limit:p,orderKeys:d,predicate:w}=await No(t,r,{canPushExists:kt?Bn:void 0,existsPushMode:Dt==="always"?"always":"auto",fetcher:nt,maxRelationKeys:Lt,schema:u,tableName:e}),y=kt?Kr(a):Xe,A=Z(w,y,Ye),x=An(e,A,In(d),l);return{limit:p,orderKeys:d,statement:x}},U={system:kn,async aggregate(e,t){const r=H(e,"aggregate");if(r)return k(e,G),r.aggregate(e,t);const a=u.tables[e];if(!a)throw new R("INTERNAL",`unknown table: ${e}`);if(Oe(t.op),t.op==="count")return U.count(e,{baseWhere:t.baseWhere,relationBaseWhere:t.relationBaseWhere,restrictsCounts:t.restrictsCounts,where:t.where});if(!t.field)throw new R("INTERNAL",`aggregate(${e}, { op: "${t.op}" }): "field" is required for non-count reducers`);k(e,G);const l=Ie(a.softDeleteMode,void 0),p=Q(Q(t.baseWhere,t.where),l),d=await ke(p,e,t.relationBaseWhere),w=d!==p;if(a.aggregateIndexes&&!t.baseWhere&&!w){const $=eo(a.aggregateIndexes,t.op,t.field,t.where);if($){ot(e,$.index);const P=ct($.index.by??[],$.key),Y=st(e,$.index.name),X=K(E,f`SELECT ${Ue} AS value, ${lt} AS count FROM ${f.identifier(Y)} WHERE ${Ge} = ${P}`).toArray()[0];return at(t.op,X)}}dn(a,t.field,`aggregate(${e}, { op: "${t.op}", field: "${t.field}" })`);const y=Z(d,he),A=Oe(t.op),x=we(t.field);let I=f`SELECT ${f.raw(A)}(${x}) AS value FROM ${f.identifier(e)}`;y&&(I=f`${I} WHERE ${y}`);const D=K(E,I).toArray()[0]?.value;return D??null},asId(e,t){const r=ln(u,e,t);if(r===null)throw new R("BAD_REQUEST",`asId("${e}", …): "${t}" is not a valid id for table "${e}"`,{status:400});return r},async count(e,t){const r=H(e,"count");if(r)return k(e,G),r.count(e,t);const a=u.tables[e];if(!a)throw new R("INTERNAL",`unknown table: ${e}`);const l=Yn(t);if(l.restrictsCounts)throw new dt(e);k(e,G);const p=Ie(a.softDeleteMode,void 0),d=Q(Q(l.baseWhere,l.where),p),w=await ke(d,e,l.relationBaseWhere),y=w!==d;if(a.aggregateIndexes&&!l.baseWhere&&!y){const _=Zn(a.aggregateIndexes,l.where);if(_){ot(e,_.index);const D=ct(_.index.by??[],_.key),$=st(e,_.index.name),P=K(E,f`SELECT ${Ue} AS value FROM ${f.identifier($)} WHERE ${Ge} = ${D}`).toArray();return P[0]===void 0?0:P[0].value??0}}const A=Z(w,he);let x=f`SELECT COUNT(*) AS count FROM ${f.identifier(e)}`;return A&&(x=f`${x} WHERE ${A}`),K(E,x).one().count},async delete(e,t,r){T(e,"ctx.db.delete(table, id)");const a=re(t,e);if(!a){const _=Ae(e);_&&await it(_,e,[t],r);return}const{docJson:l,row:p,tableName:d}=a,w=u.tables[d],y=r?.hard===!0,A=!y&&w?.softDeleteMode?w:void 0,x=A?.softDeleteMode?.field;if(x&&p[x]!==null&&p[x]!==void 0)return;if(ne(d,"before","delete")&&await oe("before","delete",{id:t,op:"delete",previous:p,table:d}),r?.skipOnDelete!==!0&&await Yo({deletedId:t,deletedReference:_=>p[_],findHolders:async(_,D,$,P)=>(await tt(_).findMany(_,{...P,includeDeleted:y,where:{[D]:$}})).page,onCascade:(_,D)=>tt(_).delete(_,D,r),onRestrict:_=>{throw new ae(_,"restrict")},onSetNull:(_,D,$)=>tt(_).patch(_,D,{[$]:null}),schema:u,tableName:d}),ve(d),_e(d),A&&x){const _={[x]:me()},D={...p,...ee(d),..._,_id:t};ht(A,_,D,le),Qe(E,d,nn(d),[fe(D),t,l]),Be(d,t,D,p),Fe(d,t,void 0),Le(d,p,D),Te(d,t,p,void 0);const $=N(d,p,D);de?.invalidate(d,t,$),Se(d,t,"update",D),C({indexKeys:$,key:t,op:"update",row:D,table:d}),ne(d,"after","delete")&&await oe("after","delete",{id:t,op:"delete",previous:p,table:d}),await $e({id:t,op:"delete",table:d});return}Qe(E,d,Ir(d),[t,l]),Be(d,t,void 0),Fe(d,t,void 0),Le(d,p,void 0),Te(d,t,p,void 0);const I=N(d,p);de?.invalidate(d,t,I),Se(d,t,"delete"),C({indexKeys:I,key:t,op:"delete",table:d}),ne(d,"after","delete")&&await oe("after","delete",{id:t,op:"delete",previous:p,table:d}),await $e({id:t,op:"delete",table:d})},async deleteAll(e,t){if(!u.tables[e])throw new R("INTERNAL",`unknown table: ${e}`);if(s!==void 0)return m().deleteAll(e,t);const r=Math.max(1,t?.chunkSize??vn),a=t?.hard===void 0?void 0:{hard:t.hard},l=H(e,"deleteAll");let p=0;for(;;){const w=(await U.findMany(e,{includeDeleted:t?.hard===!0,limit:r})).page.map(y=>String(y._id));if(w.length===0)break;for(const y of w)await(l===void 0?U.delete(e,y,a):it(l,e,[y],a)),p+=1;if(w.length<r)break}return{deleted:p}},async deleteMany(e,t,r){T(e,"ctx.db.deleteMany(table, ids)"),Ke(t.length,r?.limit,"deleteMany");for(const a of t)await U.delete(e,a);return{deleted:t.length}},async deleteWhere(e,t,r){const a=H(e,"deleteWhere"),p=(await cn(a??U,e,t,r?.limit,"deleteWhere")).map(d=>String(d._id));if(a)return it(a,e,p,void 0,{options:r});if(U.deleteMany===void 0)throw new R("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return U.deleteMany(e,p,r)},async findFirst(e,t={}){return(await U.findMany(e,{...t,limit:1,omitContinueCursor:!0})).page[0]??null},async findFirstOrThrow(e,t={}){const r=await U.findFirst(e,t);if(r===null)throw new vo(`findFirstOrThrow: no "${e}" document matched`);return r},async findMany(e,t={}){const r=H(e,"findMany");if(r)return k(e,G),t.consistency==="primary"&&S(e,ao),r.findMany(e,t);const a=u.tables[e];if(!a)throw new R("INTERNAL",`unknown table: ${e}`);const l=!t.where&&!t.baseWhere;l?k(e,G):k(e);const{limit:p,orderKeys:d,statement:w}=await Ut(e,a,t,k),y=pe(E,w.text,...w.params).toArray();l&&s?.recordRead(y.length);const A=[];for(const I of y){const _=xe(I);_&&(A.push(_),!l&&typeof _._id=="string"&&k(e,_._id))}const x=Ho(A,{endCursor:t.endCursor,limit:p,omitContinueCursor:t.omitContinueCursor,orderKeys:d});return t.with&&await Jo({fetcher:nt,groupedCounter:Wn,parents:x.page,...zo(t),schema:u,tableName:e,with:t.with}),{...x,page:Sn(x.page,t.select,t.with)}},async explain(e,t={}){const r=H(e,"explain");if(r)return r.explain(e,t);const a=u.tables[e];if(!a)throw new R("INTERNAL",`unknown table: ${e}`);const{statement:l}=await Ut(e,a,t,()=>{}),p=pe(E,`EXPLAIN QUERY PLAN ${l.text}`,...l.params).toArray();return{params:l.params,plan:p.map(d=>String(d.detail)),sql:l.text}},async get(e,t){T(e,"ctx.db.get(table, id)");const r=re(t,e);if(!r){const a=Ae(e);return a?(S(e,t,!0),a.get(e,t)):(M(e),S(e,t,!0),null)}return ye(r,t),r.row},async lookupById(e,t){const r=re(e,t);if(!r){for(const a of qt(t))M(a),S(a,e,!0);return null}return ye(r,e),{row:r.row,tableName:r.tableName}},async groupBy(e,t){const r=H(e,"groupBy");if(r)return k(e,G),r.groupBy(e,t);const a=u.tables[e];if(!a)throw new R("INTERNAL",`unknown table: ${e}`);k(e,G);const l=t.agg??{op:"count"};if(Oe(l.op),l.op!=="count"&&!l.field)throw new R("INTERNAL",`groupBy(${e}, { agg: { op: "${l.op}" } }): "field" is required for non-count reducers`);const p=Ie(a.softDeleteMode,void 0),d=Q(Q(t.baseWhere,t.where),p),w=await ke(d,e,t.relationBaseWhere),y=w!==d;if(a.aggregateIndexes&&!t.baseWhere&&!y){const $=Xn(a.aggregateIndexes,l.op,l.field,t.by,t.where),P=$===void 0?0:Object.keys($.partial).length,Y=$?.index.by?.length??0;if($&&(P===0||P===Y)){ot(e,$.index);const X=st(e,$.index.name),V=Object.keys($.partial),ue=[];if(V.length===($.index.by??[]).length&&V.length>0){const We=ct($.index.by??[],$.partial),qe=K(E,f`SELECT ${Ue} AS value, ${lt} AS count FROM ${f.identifier(X)} WHERE ${Ge} = ${We}`).toArray();return qe.length>0&&ue.push({key:{...$.partial},value:at(l.op,qe[0])}),ue}const Nn=K(E,f`SELECT ${Ge} AS key, ${Ue} AS value, ${lt} AS count FROM ${f.identifier(X)}`).toArray();for(const We of Nn){const qe=Jn(JSON.parse(We.key));ue.push({key:qe,value:at(l.op,We)})}return ue}}for(const $ of[...t.by,l.field]){if($===void 0)continue;const P=$===l.field?`groupBy(${e}, { agg: { op: "${l.op}", field: "${$}" } })`:`groupBy(${e}, { by: [..."${$}"] })`;dn(a,$,P)}const A=Z(w,he),x=t.by.map($=>f`${we($)} AS ${f.identifier($)}`);if(l.op==="count")x.push(f`COUNT(*) AS value`);else{const{field:$}=l;if($===void 0)throw new R("INTERNAL",`groupBy(${e}, { agg: { op: "${l.op}" } }): "field" is required for non-count reducers`);x.push(f`${f.raw(Oe(l.op))}(${we($)}) AS value`)}let I=f`SELECT ${f.join(x,f`, `)} FROM ${f.identifier(e)}`;A&&(I=f`${I} WHERE ${A}`),I=f`${I} GROUP BY ${f.join(t.by.map($=>we($)),f`, `)}`;const _=K(E,I).toArray(),D=[];for(const $ of _){const P={};for(const X of t.by)P[X]=fo(a.shape[X],$[X]??null);const{value:Y}=$;D.push({key:P,value:Y==null?null:Number(Y)})}return D},async insert(e,t,r){const a=H(e,"insert");if(a)return xt(a,e,t,r,!0);const l=u.tables[e];if(!l)throw new R("INTERNAL",`unknown table: ${e}`);const p=r?.allowExplicitId===!0,d=je(l,yt(l,t,le),{supplied:t,trusted:p});let w;r?.clientId!==void 0?(kr(r.clientId),w=r.clientId):r?.allowExplicitId&&typeof d._id=="string"?($t(d._id),w=d._id):w=_t();const y=r?.allowExplicitId&&typeof d._creationTime=="number"?d._creationTime:me(),A={...d,...ee(e),_creationTime:y,_id:w};return ne(e,"before","insert")&&await oe("before","insert",{doc:{...A},id:w,op:"insert",table:e}),p||W(e,A),ve(e),_e(e),mt(E,e,Tr(e),[w,y,fe(A)]),Bt(e,w,A),ne(e,"after","insert")&&await oe("after","insert",{doc:A,id:w,op:"insert",table:e}),await $e({doc:A,id:w,op:"insert",table:e}),w},async insertManyUnsafe(e,t,r){if(Ke(t.length,r?.limit,"insertManyUnsafe"),t.length===0)return[];const a=H(e,"insert");if(a){const y=[];Lr(u.tables[e],t,r?.allowExplicitId,le);for(const A of t)J(A);for(const A of t){const x=await a.insert(e,A,{allowExplicitId:r?.allowExplicitId});C({key:x,op:"insert",row:{...A,_id:x},table:e}),y.push(x)}return y}const l=u.tables[e];if(!l)throw new R("INTERNAL",`unknown table: ${e}`);ve(e),_e(e);const p=[];for(let y=0;y<t.length;y+=He)p.push(ee(e));const d=r?.allowExplicitId===!0?void 0:Vo(l),w=t.map((y,A)=>{const x=yt(l,y,le),I=d===void 0?x:je(d,x,{supplied:y}),_=r?.allowExplicitId===!0&&typeof I._id=="string"?I._id:void 0;_!==void 0&&$t(_);const D=_??_t(),$=r?.allowExplicitId===!0&&typeof I._creationTime=="number"?I._creationTime:me(),P={...I,...p[Math.floor(A/He)],_creationTime:$,_id:D};return{creationTime:$,document:P,id:D}});for(const y of w)J(y.document);for(let y=0;y<w.length;y+=He){const A=f.join(w.slice(y,y+He).map(I=>f`(${I.id}, ${I.creationTime}, ${fe(I.document)})`),f`, `),x=$n("sqlite",f`INSERT INTO ${f.identifier(e)} (id, _creationTime, ${f.identifier(ie)}) VALUES ${A}`);mt(E,e,x.sql,x.params)}for(const{document:y,id:A}of w)Bt(e,A,y),await Ee({doc:y,id:A,op:"insert",table:e});return w.map(y=>y.id)},async insertMany(e,t,r){Ke(t.length,r?.limit,"insertMany");const a=r?.skipDuplicates===!0,l=[],p=H(e,"insert");if(p)for(const w of t)J(w);const d=async w=>p?xt(p,e,w,void 0,!1):U.insert(e,w);for(const w of t)try{l.push(await d(w))}catch(y){if(a&&y instanceof ae&&y.kind==="unique")l.push(null);else throw y}return l},normalizeId(e,t){return ln(u,e,t)},async patch(e,t,r,a){T(e,"ctx.db.patch(table, id, values)");const l=re(t,e);if(!l){const D=Ae(e);if(D){J(r);try{await D.patch(e,t,r,a)}finally{ce("update",e,t)}return}throw new R("NOT_FOUND",`document not found: ${t}`)}const{docJson:p,row:d,tableName:w}=l,y=u.tables[w];if(!y)throw new R("INTERNAL",`unknown table: ${w}`);if(k(w,t),fn("patch",r),It(w,t,r,d)){o?.({fields:Object.keys(Ne(r)),id:t,table:w});return}const A=_o(y,r,d),x={...d,...Ne(A),...ee(w),_id:t};ht(y,A,x,le);const I=je(y,x,{only:new Set(Object.keys(A)),previous:()=>d,tolerateStoredNull:!0});To(a,d,I),ne(w,"before","update")&&await oe("before","update",{doc:{...I},id:t,op:"update",previous:d,table:w}),W(w,I,d),ve(w),_e(w),Qe(E,w,nn(w),[fe(I),t,p]),Be(w,t,I,d),Fe(w,t,I),Le(w,d,I),Te(w,t,d,I);const _=N(w,d,I);de?.invalidate(w,t,_),Se(w,t,"update",I),C({indexKeys:_,key:t,op:"update",row:I,table:w}),ne(w,"after","update")&&await oe("after","update",{doc:I,id:t,op:"update",previous:d,table:w}),await $e({doc:I,id:t,op:"update",table:w})},async patchIf(e,t,r){const a=H(e,"patchIf");if(a){if(a.patchIf===void 0)throw new R("INTERNAL",`ctx.db.patchIf on global table '${e}' is unsupported: its backend has no conditional write`);J(r.patch);let l;try{l=await a.patchIf(e,t,r)}catch(p){throw ce("update",e,t),p}return l.applied&&ce("update",e,t),l}if(!u.tables[e])throw new R("INTERNAL",`unknown table: ${e}`);for(let l=1;l<=un;l+=1){const p=await Hn(e,t,r,l<un,d=>U.patch(e,t,d,{verify:r.verify}));if(p!==void 0)return p}throw new ae(`patchIf on "${e}" kept conflicting; the row changed on every attempt`,"occ")},async patchMany(e,t,r){T(e,"ctx.db.patchMany(table, patches)"),Ke(t.length,r?.limit,"patchMany");for(const a of t)await U.patch(e,a.id,a.patch);return{patched:t.length}},async patchWhere(e,t,r){const a=H(e,"patchWhere")??U,p=(await cn(a,e,t.where,r?.limit,"patchWhere")).map(d=>({id:String(d._id),patch:t.patch}));if(U.patchMany===void 0)throw new R("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await U.patchMany(e,p,r),{patched:p.length}},async related(e,t){return jo(U,v,e,t)},relationEdges:v,deleteRereadTables:B,inTransaction:j,softDeleteFields:O,relationWrites:q,query(e){const t=H(e,"query");return t?(k(e,G),t.query(e)):Mn(E,u,e,te,r=>{r?F(r):k(e,G)},r=>{s?.recordRead(r)})},async rank(e,t,r){const a=H(e,"rank");if(te(e,t,"rank"),a)return k(e,G),a.rank(e,t,r);const l=u.tables[e];if(!l)throw new R("INTERNAL",`unknown table: ${e}`);const p=l.rankIndexes?.find(V=>V.name===t);if(!p)throw new R("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(Wt(e,l,p),r.restrictsCounts)throw new dt(e);k(e,G),rt(e,p);const d=typeof r.row=="string"?r.row:r.row._id;if(!d)return null;const w=Jt(e,p.name),y=p.sortBy.map((V,ue)=>zt(ue)),A=y.map(V=>De(V)).join(", "),x=K(E,f`SELECT ${f.identifier("__partition__")}, ${f.raw(A)} FROM ${f.identifier(w)} WHERE ${f.identifier("__id__")} = ${d}`).toArray(),[I]=x;if(I===void 0)return null;let _=I.__partition__;const D=Q(r.baseWhere,r.where);ut(D,u,e,"rank");const $=Do(p,D);if($){const V=ko(p.partitionBy??[],$);if(V!==_)return null;_=V}const P=y.map(V=>I[V]),{before:Y,total:X}=wn(E,w,y,p.sortBy,_,P,d);return{position:Y+1,total:X}},async rankBefore(e,t,r){if(se(e))throw new R("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const a=u.tables[e];if(!a)throw new R("INTERNAL",`unknown table: ${e}`);const l=a.rankIndexes?.find(y=>y.name===t);if(!l)throw new R("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(r.restrictsCounts)throw new dt(e);k(e,G),rt(e,l);const p=Jt(e,l.name),d=l.sortBy.map((y,A)=>zt(A)),w=l.sortBy.map((y,A)=>Me(r.sortValues[A]??null));return wn(E,p,d,l.sortBy,r.partitionKey,w,r.rowId)},async rankPage(e,t,r={}){ut(Q(r.baseWhere,r.where),u,e,"rankPage");const a=H(e,"rankPage");if(te(e,t,"rank"),a)return k(e,G),a.rankPage(e,t,r);const{continueCursor:l,hasMore:p,rows:d}=Ht(Ot,e,t,r);return{continueCursor:l,isDone:!p,page:d.map(w=>w.doc)}},async rankPageRows(e,t,r={}){ut(Q(r.baseWhere,r.where),u,e,"rankPage"),te(e,t,"rank");const{directions:a,hasMore:l,rows:p}=Ht(Ot,e,t,r);return{directions:a,hasMore:l,rows:p}},async restore(e,t){T(e,"ctx.db.restore(table, id)");const r=re(t,e);if(!r){const p=Ae(e);if(p?.restore){try{await p.restore(e,t)}finally{ce("update",e,t)}return}throw new R("NOT_FOUND",`document not found: ${t}`)}const a=u.tables[r.tableName]?.softDeleteMode?.field;if(!a)throw new R("INTERNAL",`ctx.db.restore: table "${r.tableName}" is not a .softDelete() table`);const l=r.row[a]!==null&&r.row[a]!==void 0;await U.patch(e,t,{[a]:null}),l&&Te(r.tableName,t,void 0,r.row)},async replace(e,t,r,a){T(e,"ctx.db.replace(table, id, document)");const l=re(t,e);if(!l){const P=Ae(e);if(P){J(r);try{await P.replace(e,t,r,a)}finally{ce("update",e,t)}return}throw new R("NOT_FOUND",`document not found: ${t}`)}const{docJson:p,row:d,tableName:w}=l,y=u.tables[w];if(!y)throw new R("INTERNAL",`unknown table: ${w}`);fn("replace",r);const A=a?.allowExplicitId&&typeof r._creationTime=="number"?r._creationTime:void 0,x=typeof d._creationTime=="number"?d._creationTime:void 0,I=A??x??me(),_={...r,...ee(w),_creationTime:I,_id:t};ht(y,r,_,le);const D=a?.allowExplicitId===!0,$=je(y,_,{previous:()=>d,supplied:r,trusted:D});ne(w,"before","update")&&await oe("before","update",{doc:{...$},id:t,op:"update",previous:d,table:w}),D||W(w,$,d),ve(w),_e(w),Qe(E,w,Ar(w),[I,fe($),t,p]),Be(w,t,$,d),Fe(w,t,$),Le(w,d,$),Te(w,t,d,$),de?.invalidate(w,t,N(w,d,$)),Se(w,t,"update",$),C({indexKeys:N(w,d,$),key:t,op:"update",row:$,table:w}),ne(w,"after","update")&&await oe("after","update",{doc:$,id:t,op:"update",previous:d,table:w}),await $e({doc:$,id:t,op:"update",table:w})},async wipeShard(e){const t=new Set(e?.exclude),r=e?.tables,a=Object.entries(u.tables).filter(([w,y])=>t.has(w)||r!==void 0&&!r.includes(w)?!1:y.shardMode?.kind!=="global").map(([w])=>w);if(r!==void 0){for(const w of r)if(!u.tables[w])throw new R("INTERNAL",`wipeShard: unknown table: ${w}`)}const l={};let p=0;const{deleteAll:d}=U;if(d===void 0)throw new R("INTERNAL","wipeShard: this writer has no deleteAll");for(const w of a){const y=await d(w,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});l[w]=y.deleted,p+=y.deleted}return{deleted:p,tables:l}}},Kn={db:U,scheduler:Tt};return n.enforceRls===!0?er(U,u,(e,t)=>re(e,t)?.tableName,v):U};export{rs as CDC_LOG_TABLE,As as IDEMPOTENCY_TABLE,Nr as NotUniqueError,Ss as advanceClientWatermark,is as applyCdcChanges,fn as assertNoExplicitUndefined,$t as assertStorableRowId,kr as assertValidClientId,es as backfillAggregateIndexes,ts as backfillRankIndexes,ns as backfillSearchIndexes,ss as bumpCdcEpoch,cs as cdcCanVouchFor,as as cdcForkedError,ds as cdcSeqLeavingRows,ls as cdcTouchesTables,us as cdcTrimmedError,fs as compactCdcDocs,fi as createShardCtxDb,hs as cursorBelowRetainedFloor,oi as meterReadBytes,vs as migrateClientWatermark,ws as minCdcReplayableSeq,ps as minCdcSeq,ln as normalizeIdStructurally,gs as readCdcChangeKeys,ys as readCdcChanges,Es as readCdcCursor,$s as readCdcEpoch,_s as readClientWatermark,Is as readIdempotent,Ms as runShardMigrations,ks as selectShapeMembers,Ls as selectShapeRows,Ne as stripReservedPatchFields,ms as trimCdcChanges,bs as trimIdempotent,xs 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{N as CASCADE_MAX_ROWS,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};
|