@lunora/shard-engine 1.0.0-alpha.191 → 1.0.0-alpha.193

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (19) hide show
  1. package/dist/conformance/index.mjs +1 -1
  2. package/dist/index.mjs +1 -1
  3. package/dist/packem_shared/CURSOR_PREFIX-rOdoinP8.mjs +1 -0
  4. package/dist/packem_shared/{DATA_MIGRATION_STATE_TABLE-CFvBS9-M.mjs → DATA_MIGRATION_STATE_TABLE-CPWZjliE.mjs} +1 -1
  5. package/dist/packem_shared/{DEFAULT_MAX_RELATION_KEYS-BBtZ_jRj.mjs → DEFAULT_MAX_RELATION_KEYS-B_BOc9w_.mjs} +1 -1
  6. package/dist/packem_shared/NotUniqueError-B2OuN937.mjs +1 -0
  7. package/dist/packem_shared/RELATED_DEFAULT_LIMIT-CAh3WUMn.mjs +1 -0
  8. package/dist/packem_shared/{RLS_UNWRAP_SYMBOL-H6J96vgK.mjs → RLS_UNWRAP_SYMBOL-CZIpCjzt.mjs} +1 -1
  9. package/dist/packem_shared/{VECTOR_BACKFILL_MAX_PAGES-DcQpf83n.mjs → VECTOR_BACKFILL_MAX_PAGES-DJ6iD61G.mjs} +1 -1
  10. package/dist/packem_shared/{applyInsertDefaults-CVukTkQ5.mjs → applyInsertDefaults-BJ4dP3OL.mjs} +1 -1
  11. package/dist/packem_shared/{backfillAggregateIndexes-Pk0KLrfk.mjs → backfillAggregateIndexes-BwCpPW7h.mjs} +1 -1
  12. package/dist/packem_shared/{computeRankPage-xm-70mLy.mjs → computeRankPage-B6umzbg4.mjs} +1 -1
  13. package/dist/packem_shared/{createCompanionSync-CEht4hXX.mjs → createCompanionSync-DO92CQek.mjs} +1 -1
  14. package/dist/packem_shared/{defineEngineContractSuite-Bap9eB0W.mjs → defineEngineContractSuite-Cjuq82Ys.mjs} +1 -1
  15. package/dist/packem_shared/{runShardMigrations-BPFg3Ht6.mjs → runShardMigrations-Bc7PsQhM.mjs} +1 -1
  16. package/package.json +2 -2
  17. package/dist/packem_shared/CURSOR_PREFIX-6offuG6M.mjs +0 -1
  18. package/dist/packem_shared/NotUniqueError-vJf9tj6U.mjs +0 -1
  19. package/dist/packem_shared/RELATED_DEFAULT_LIMIT-CVqN4JEu.mjs +0 -1
@@ -1 +1 @@
1
- import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite-Bap9eB0W.mjs";export{t as defineEngineContractSuite};
1
+ import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite-Cjuq82Ys.mjs";export{t as defineEngineContractSuite};
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{exportShardRows as o,importShardRows as a,parseExportShardArgs as t,parseImportShardArgs as i,selectExportTables as s,validateImportRow as n}from"./packem_shared/exportShardRows-CZh4wrvI.mjs";import{adminTokenExists as d,createAdminTokenRecord as c,listAdminTokens as m,revokeAdminTokenRecord as p,verifyAdminTokenDigest as u}from"./packem_shared/adminTokenExists-CjKKZzfY.mjs";import{AGGREGATE_SQL_FUNCTION as f,aggregateSqlFunction as x,matchesStaticWhere as E,normalizeCountArgument as h,throwingScheduler as T}from"./packem_shared/AGGREGATE_SQL_FUNCTION-C_ZipS9R.mjs";import{aggregateTableName as A,coerceAggregateNumber as C,encodeAggregateKey as g,foldAggregateTally as _,readAggregateValue as I}from"./packem_shared/aggregateTableName-B_CtIQCS.mjs";import{CountRlsUnsupportedError as L,mergeWhere as D,planAggregateLookup as O,selectIndexForAggregate as P,selectIndexForCount as y,selectIndexForGroupBy as M}from"./packem_shared/CountRlsUnsupportedError-BvsDqfO2.mjs";import{AUDIT_LOG_TABLE as k,appendAuditEntry as N,ensureAuditTable as B,readAuditLog as U}from"./packem_shared/AUDIT_LOG_TABLE-BFJ65SRS.mjs";import{NotUniqueError as w,assertNoExplicitUndefined as q,assertStorableRowId as v,assertValidClientId as K,createShardCtxDb as W,normalizeIdStructurally as X,stripReservedPatchFields as H}from"./packem_shared/NotUniqueError-vJf9tj6U.mjs";import{backfillAggregateIndexes as z,backfillRankIndexes as Q,backfillSearchIndexes as Y,backfillSearchIndexesForTable as j}from"./packem_shared/backfillAggregateIndexes-Pk0KLrfk.mjs";import{CDC_LOG_TABLE as Z,CDC_LOG_TABLE_SEQ_INDEX as $,CDC_META_TABLE as ee,appendCdcChange as re,applyCdcChanges as oe,bumpCdcEpoch as ae,cdcCanVouchFor as te,cdcForkedError as ie,cdcSeqLeavingRows as se,cdcTouchesTables as ne,cdcTrimmedError as le,compactCdcDocs as de,cursorBelowRetainedFloor as ce,migrateCdcLog as me,migrateCdcMeta as pe,minCdcReplayableSeq as ue,minCdcSeq as Se,readCdcChangeKeys as fe,readCdcChanges as xe,readCdcCursor as Ee,readCdcEpoch as he,trimCdcChanges as Te}from"./packem_shared/CDC_LOG_TABLE-BFGgqai8.mjs";import{archiveCdcSegment as Ae,cdcArchiveRewound as Ce,readArchivedCdcChanges as ge,readCdcArchivedThrough as _e,writeCdcArchivedThrough as Ie}from"./packem_shared/archiveCdcSegment-Cr8oGLfB.mjs";import{CLIENT_WATERMARK_TABLE as Le,advanceClientWatermark as De,migrateClientWatermark as Oe,readClientWatermark as Pe}from"./packem_shared/CLIENT_WATERMARK_TABLE-De7z_OHV.mjs";import{COMMIT_SEQ_FIELD as Me,COMMIT_SEQ_TABLE as Fe,allocateCommitSeq as ke,migrateCommitSeq as Ne,readCommitSeq as Be}from"./packem_shared/COMMIT_SEQ_FIELD-Da1DjGqo.mjs";import{CompanionMemo as Ge,clearCompanionSignatures as we}from"./packem_shared/CompanionMemo-BXU5vfak.mjs";import{createCompanionSync as ve}from"./packem_shared/createCompanionSync-CEht4hXX.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as We,deleteGlobalShapeSnapshot as Xe,deleteGlobalShapeSnapshotsForConnection as He,migrateGlobalShapeSnapshot as Ve,readGlobalShapeSnapshot as ze,writeGlobalShapeSnapshot as Qe}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-Bb6-aZuH.mjs";import{IDEMPOTENCY_TABLE as je,migrateIdempotency as Je,readIdempotent as Ze,trimIdempotent as $e,writeIdempotent as er}from"./packem_shared/IDEMPOTENCY_TABLE-COrgeP3O.mjs";import{clearMemoryTables as or,isMemoryTable as ar,memoryTableNames as tr}from"./packem_shared/clearMemoryTables-aMRERF0w.mjs";import{computeRankPage as sr,resolveRankSeekTuple as nr}from"./packem_shared/computeRankPage-xm-70mLy.mjs";import{SCHEDULE_OUTBOX_TABLE as dr,deferScheduleOutbox as cr,dropScheduleOutbox as mr,forgetScheduleOutbox as pr,hasScheduleOutboxEntry as ur,migrateScheduleOutbox as Sr,parkScheduleOutbox as fr,probeScheduleOutbox as xr,readDueScheduleOutbox as Er,readDueScheduleOutboxEntry as hr,readScheduleOutbox as Tr,readScheduleOutboxState as Rr,recordScheduleOutbox as Ar,requeueScheduleOutbox as Cr,trimScheduleOutbox as gr}from"./packem_shared/SCHEDULE_OUTBOX_TABLE-iyyiSjsO.mjs";import{S as Ir,m as br,r as Lr,w as Dr}from"./packem_shared/ctx-db-search-state-CPKPy8N6.mjs";import{SHAPE_POKE_CURSOR_TABLE as Pr,deleteShapePokeCursor as yr,deleteShapePokeCursorsForConnection as Mr,migrateShapePokeCursor as Fr,minShapePokeCursor as kr,readShapePokeCursor as Nr,writeShapePokeCursor as Br,writeShapePokeCursors as Ur}from"./packem_shared/SHAPE_POKE_CURSOR_TABLE-BGvY3sFI.mjs";import{selectShapeMembers as wr,selectShapeRows as qr}from"./packem_shared/selectShapeMembers-Dqx_m7BF.mjs";import{DATA_MIGRATION_STATE_TABLE as Kr,readMigrationStatus as Wr,runDataMigration as Xr}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-CFvBS9-M.mjs";import{SCAN_DEP as Vr,createDependencyTracker as zr,depKey as Qr,tableFromDepKey as Yr}from"./packem_shared/SCAN_DEP-B4Uu4g7l.mjs";import{runDrizzle as Jr,runSql as Zr}from"./packem_shared/runDrizzle-RC09zZrh.mjs";import{A as eo,a as ro,b as oo,D as ao,c as to,d as io,g as so,i as no,j as lo,e as co,q as mo,f as po,r as uo,t as So,h as fo}from"./packem_shared/do-sql-105TONaE.mjs";import{WORKERD_SQLITE_LIMITS as Eo,param as ho,renderSql as To,sqliteInList as Ro,unionAll as Ao}from"./packem_shared/WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{appendStreamChunk as go,claimStreamRun as _o,deleteStreamRun as Io,finishStreamRun as bo,migrateDurableStreams as Lo,readStreamChunks as Do,readStreamRun as Oo,trimStreamRuns as Po}from"./packem_shared/appendStreamChunk-BZYgGE9Y.mjs";import{DurableStreamRunner as Mo,MAX_DURABLE_STREAM_BYTES as Fo,MAX_DURABLE_STREAM_CHUNKS as ko,decideDurableAttach as No}from"./packem_shared/DurableStreamRunner-MMlV5qKQ.mjs";import{envOptionalPositiveInt as Uo,envPositiveInt as Go}from"./packem_shared/envOptionalPositiveInt-D2pY-c64.mjs";import{diffExternalSource as qo}from"./packem_shared/diffExternalSource-B0FZlDoL.mjs";import{liftSourceId as Ko,normalizeSourceDocument as Wo,normalizeSourceValue as Xo}from"./packem_shared/liftSourceId-CA3ENhXj.mjs";import{materializeExternalRows as Vo,materializeExternalRowsIncremental as zo,readExternalSourceBaseline as Qo,runExternalSourceTick as Yo}from"./packem_shared/materializeExternalRows-CHPRx8fu.mjs";import{isSoftDeleted as Jo,isSourceDue as Zo,pullExternalSourceIncrementalTick as $o,pullExternalSourceTick as ea}from"./packem_shared/isSoftDeleted-BBWKE0Sm.mjs";import{f as oa,a as aa,b as ta,c as ia,d as sa,g as na}from"./packem_shared/fts-companion-CE3EmIjk.mjs";import{GEO_DEFAULT_PRECISION as da,boundingBoxCenter as ca,boundingBoxGeohashes as ma,coveringGeohashes as pa,encodeGeohash as ua,haversineMeters as Sa,pointInBoundingBox as fa}from"./packem_shared/GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{default as Ea}from"./packem_shared/GlobalPollTick-BNK4o-XT.mjs";import{ADMIN_FUNCTIONS as Ta,ADMIN_FUNCTION_PREFIX as Ra,DEFAULT_FANOUT_TOPIC_LIMIT as Aa,FLAGS_FUNCTION_PREFIX as Ca,MAX_PAGE_SIZE as ga,RELATION_FUNCTION_PREFIX as _a,createFanoutCounters as Ia,createGlobalPollCounters as ba,createShapeProbeCounters as La,facetColumn as Da,findStorageReferences as Oa,isVacuousFilterClause as Pa,listTables as ya,readTablePage as Ma,recordFanoutPass as Fa,recordGlobalPollPass as ka,recordShapeProbePass as Na,selectMatchingIds as Ba,summarizeFanoutTopics as Ua,summarizeSubscriptions as Ga}from"./packem_shared/ADMIN_FUNCTIONS-CSz3ZK2d.mjs";import{MAIL_RETENTION as qa,MAIL_TABLE as va,clearCapturedMail as Ka,ensureMailTable as Wa,readCapturedMail as Xa,recordCapturedMail as Ha}from"./packem_shared/MAIL_RETENTION-DMolrLYt.mjs";import{NotFoundError as za}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{assertPatchAllowed as Ya,operatorFields as ja,patchDependsOnRow as Ja,readPatchField as Za,resolvePatch as $a}from"./packem_shared/assertPatchAllowed-CA_H466g.mjs";import{armRestore as rt,readBookmark as ot}from"./packem_shared/armRestore-Bu1_8SUa.mjs";import{CURSOR_PREFIX as tt,applySelect as it,buildSeekBeforeWhere as st,buildSeekWhere as nt,decodeCursor as lt,encodeCursor as dt,equalityPinnedFields as ct,normalizeOrderKeys as mt,nullsFirstOf as pt,nullsOrderSuffix as ut,softDeleteScope as St,tiebreakDirectionFor as ft,uniqueIndexFields as xt}from"./packem_shared/CURSOR_PREFIX-6offuG6M.mjs";import{QUEUE_TABLE as ht,clearQueueMessages as Tt,isLossyBody as Rt,readQueueMessageById as At,readQueueMessages as Ct,recordQueueMessages as gt}from"./packem_shared/QUEUE_TABLE-C-goXtGd.mjs";import{RANK_TIEBREAK as It,encodePartitionKey as bt,matchesRankStaticWhere as Lt,rankKeyFromDoc as Dt,rankPivotConditionSql as Ot,rankTableName as Pt,resolveRankPartition as yt,sortColumnName as Mt}from"./packem_shared/RANK_TIEBREAK-D3ye2GsL.mjs";import{ReactiveCache as kt,reactiveCacheKey as Nt}from"./packem_shared/ReactiveCache-BG9z3FE9.mjs";import{REACTOR_STATE_TABLE as Ut,listReactorStates as Gt,migrateReactorState as wt,reactorNeedsRun as qt,readReactorState as vt,writeReactorState as Kt}from"./packem_shared/REACTOR_STATE_TABLE-D2Mn204f.mjs";import{UNVOUCHABLE_DEP as Xt,createReadFootprint as Ht,markUnvouchableReads as Vt}from"./packem_shared/UNVOUCHABLE_DEP-Ds9gxVqs.mjs";import{buildIndexRange as Qt,indexKeysForRow as Yt,keysTouchRanges as jt}from"./packem_shared/buildIndexRange-BTChxh3k.mjs";import{isPushableWhere as Zt,whereFilter as $t,whereOfFilter as ei}from"./packem_shared/isPushableWhere-BeYAOjUb.mjs";import{RELATED_DEFAULT_LIMIT as oi,RELATED_DEPTH_DECAY as ai,RELATED_MAX_DEPTH as ti,RELATED_MAX_LIMIT as ii,deriveRelationEdges as si,findRelated as ni}from"./packem_shared/RELATED_DEFAULT_LIMIT-CVqN4JEu.mjs";import{DEFAULT_MAX_RELATION_KEYS as di,assertFlatPredicate as ci,assertShapeShardable as mi,composeReadPredicate as pi,containsRelationPredicate as ui,findManyPage as Si,isRelationPredicate as fi,resolveRelationPredicates as xi}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-BBtZ_jRj.mjs";import{describeRelationWrites as hi}from"./packem_shared/describeRelationWrites-omar6-u9.mjs";import{applyInsertDefaults as Ri,applyOnDelete as Ai,distinctValues as Ci,fanOutScalarCounts as gi,relationHooks as _i,resolveWith as Ii,runRowValidators as bi}from"./packem_shared/applyInsertDefaults-CVukTkQ5.mjs";import{D as Di,c as Oi,n as Pi,r as yi,s as Mi}from"./packem_shared/relay-CKEdfUjH.mjs";import{DEFAULT_MAX_RELAYS as ki,OwnerRelay as Ni,RelayMember as Bi,createRelayLink as Ui}from"./packem_shared/DEFAULT_MAX_RELAYS-Bc6PI-xy.mjs";import{createReplicaLink as wi,gateReplicaDispatch as qi,handleReplicaControl as vi}from"./packem_shared/createReplicaLink-DtqXBi-0.mjs";import{buildReprojectionMigration as Wi,countLegacyRows as Xi,reprojectableFields as Hi,reprojectionTables as Vi}from"./packem_shared/buildReprojectionMigration-B8aEpETD.mjs";import{RLS_UNWRAP_SYMBOL as Qi,RlsRequiredError as Yi,guardWriter as ji}from"./packem_shared/RLS_UNWRAP_SYMBOL-H6J96vgK.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as Zi,readSchemaHistory as $i,readSchemaVersion as es,recordSchemaVersion as rs}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-CEwFjj-O.mjs";import{serializeSqlValue as as}from"./packem_shared/serializeSqlValue-DeoBMpZ2.mjs";import{buildSettings as is,isDevEnvironment as ss,readDeployInfo as ns}from"./packem_shared/buildSettings-CFkvTaHx.mjs";import{buildShapeDiff as ds}from"./packem_shared/buildShapeDiff-CdLJTijm.mjs";import{ShapeDiffCache as ms,createShapeDiffCache as ps,globalShapeReadKey as us}from"./packem_shared/ShapeDiffCache-iNO-hUiy.mjs";import{buildPokeFrames as fs,diffGlobalMembership as xs,encodeRowsPatch as Es,projectColumns as hs}from"./packem_shared/buildPokeFrames-WR-hp0mX.mjs";import{ShardRunner as Rs}from"./packem_shared/ShardRunner-CrveaPId.mjs";import{stubByName as Cs}from"./packem_shared/stubByName-DQSivmvb.mjs";import{runSocketPool as _s}from"./packem_shared/runSocketPool-CZJ2X9cF.mjs";import{MAX_SQL_ROWS as bs,assertReadonly as Ls,lintReadonlySql as Ds,runReadonlySql as Os}from"./packem_shared/MAX_SQL_ROWS-B4WlVI-e.mjs";import{BIGINT_KEY_DIGITS as ys,bigintSqlKey as Ms,decodeBigintSqlKey as Fs,decodeFloat64SqlKey as ks,float64SqlKey as Ns}from"./packem_shared/BIGINT_KEY_DIGITS-DE6yshOt.mjs";import{awaitWsDrain as Us,subscriptionFrames as Gs,subscriptionListDeltas as ws,trySendFrame as qs}from"./packem_shared/awaitWsDrain-DMcWBQ7I.mjs";import{mergeChangedKeys as Ks,recordChangedKeys as Ws,writeTouchesMemo as Xs}from"./packem_shared/mergeChangedKeys-DPKhen6e.mjs";import{createSystemReader as Vs}from"./packem_shared/createSystemReader-BSCxr8Qs.mjs";import{ConflictError as Qs}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as js,TransactionHeadroomTracker as Js}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS-D7p7Ys0M.mjs";import{hasTrigger as $s,runTriggers as en}from"./packem_shared/hasTrigger-CjlwI4le.mjs";import{isTtlExpired as on,nextTtlExpiry as an,selectExpiredIds as tn}from"./packem_shared/isTtlExpired-DNxmZA6e.mjs";import{VECTOR_BACKFILL_MAX_PAGES as nn,backfillVectorIndexes as ln}from"./packem_shared/VECTOR_BACKFILL_MAX_PAGES-DcQpf83n.mjs";import{c as cn,s as mn}from"./packem_shared/where-sql-BjY4rnqb.mjs";import{RELATION_EXISTS_KEY as un}from"./packem_shared/RELATION_EXISTS_KEY-wxgj6rSL.mjs";import{ADMIN_TOKEN_TABLE as fn}from"./packem_shared/ADMIN_TOKEN_TABLE-DfQ5osdI.mjs";import{RELAY_SIGNATURE_HEADER as En,siblingSecretOf as hn,signSiblingBody as Tn,verifySiblingBody as Rn}from"./packem_shared/RELAY_SIGNATURE_HEADER-CAfC4tqg.mjs";import{REPROJECTION_MIGRATION_PREFIX as Cn,reprojectionMigrationId as gn}from"./packem_shared/REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{isInternalTableName as In}from"./packem_shared/isInternalTableName-BoljO2tP.mjs";import{quoteIdentifier as Ln}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as On}from"./packem_shared/runShardMigrations-BPFg3Ht6.mjs";import{stableStringify as yn,stableWireKey as Mn}from"@lunora/wire";export{Ta as ADMIN_FUNCTIONS,Ra as ADMIN_FUNCTION_PREFIX,fn as ADMIN_TOKEN_TABLE,f as AGGREGATE_SQL_FUNCTION,eo as AGG_COUNT,ro as AGG_KEY,oo as AGG_VALUE,k as AUDIT_LOG_TABLE,ys as BIGINT_KEY_DIGITS,Z as CDC_LOG_TABLE,$ as CDC_LOG_TABLE_SEQ_INDEX,ee as CDC_META_TABLE,Le as CLIENT_WATERMARK_TABLE,Me as COMMIT_SEQ_FIELD,Fe as COMMIT_SEQ_TABLE,tt as CURSOR_PREFIX,Ge as CompanionMemo,Qs as ConflictError,L as CountRlsUnsupportedError,Kr as DATA_MIGRATION_STATE_TABLE,Aa as DEFAULT_FANOUT_TOPIC_LIMIT,di as DEFAULT_MAX_RELATION_KEYS,ki as DEFAULT_MAX_RELAYS,Di as DEFAULT_PROMOTION_THRESHOLDS,js as DEFAULT_TRANSACTION_LIMITS,ao as DOC_COLUMN,Mo as DurableStreamRunner,Ca as FLAGS_FUNCTION_PREFIX,da as GEO_DEFAULT_PRECISION,We as GLOBAL_SHAPE_SNAPSHOT_TABLE,Ea as GlobalPollTick,je as IDEMPOTENCY_TABLE,qa as MAIL_RETENTION,va as MAIL_TABLE,Fo as MAX_DURABLE_STREAM_BYTES,ko as MAX_DURABLE_STREAM_CHUNKS,ga as MAX_PAGE_SIZE,bs as MAX_SQL_ROWS,za as NotFoundError,w as NotUniqueError,Ni as OwnerRelay,ht as QUEUE_TABLE,It as RANK_TIEBREAK,Ut as REACTOR_STATE_TABLE,oi as RELATED_DEFAULT_LIMIT,ai as RELATED_DEPTH_DECAY,ti as RELATED_MAX_DEPTH,ii as RELATED_MAX_LIMIT,un as RELATION_EXISTS_KEY,_a as RELATION_FUNCTION_PREFIX,En as RELAY_SIGNATURE_HEADER,Cn as REPROJECTION_MIGRATION_PREFIX,Qi as RLS_UNWRAP_SYMBOL,kt as ReactiveCache,Bi as RelayMember,Yi as RlsRequiredError,Vr as SCAN_DEP,dr as SCHEDULE_OUTBOX_TABLE,Zi as SCHEMA_HISTORY_MAX_VERSIONS,Ir as SEARCH_STATE_TABLE,Pr as SHAPE_POKE_CURSOR_TABLE,ms as ShapeDiffCache,Rs as ShardRunner,Js as TransactionHeadroomTracker,Xt as UNVOUCHABLE_DEP,nn as VECTOR_BACKFILL_MAX_PAGES,Eo as WORKERD_SQLITE_LIMITS,d as adminTokenExists,De as advanceClientWatermark,to as aggUpsertSql,x as aggregateSqlFunction,A as aggregateTableName,ke as allocateCommitSeq,N as appendAuditEntry,re as appendCdcChange,go as appendStreamChunk,oe as applyCdcChanges,Ri as applyInsertDefaults,Ai as applyOnDelete,it as applySelect,Ae as archiveCdcSegment,rt as armRestore,ci as assertFlatPredicate,q as assertNoExplicitUndefined,Ya as assertPatchAllowed,Ls as assertReadonly,mi as assertShapeShardable,v as assertStorableRowId,K as assertValidClientId,Us as awaitWsDrain,z as backfillAggregateIndexes,Q as backfillRankIndexes,Y as backfillSearchIndexes,j as backfillSearchIndexesForTable,ln as backfillVectorIndexes,Ms as bigintSqlKey,ca as boundingBoxCenter,ma as boundingBoxGeohashes,Qt as buildIndexRange,fs as buildPokeFrames,Wi as buildReprojectionMigration,st as buildSeekBeforeWhere,nt as buildSeekWhere,is as buildSettings,ds as buildShapeDiff,ae as bumpCdcEpoch,Ce as cdcArchiveRewound,te as cdcCanVouchFor,ie as cdcForkedError,se as cdcSeqLeavingRows,ne as cdcTouchesTables,le as cdcTrimmedError,_o as claimStreamRun,Oi as clampPromotionThresholds,Ka as clearCapturedMail,we as clearCompanionSignatures,or as clearMemoryTables,Tt as clearQueueMessages,C as coerceAggregateNumber,de as compactCdcDocs,cn as compileWhereSql,pi as composeReadPredicate,sr as computeRankPage,ui as containsRelationPredicate,Xi as countLegacyRows,pa as coveringGeohashes,c as createAdminTokenRecord,ve as createCompanionSync,zr as createDependencyTracker,Ia as createFanoutCounters,ba as createGlobalPollCounters,io as createIndexSql,Ht as createReadFootprint,Ui as createRelayLink,wi as createReplicaLink,ps as createShapeDiffCache,La as createShapeProbeCounters,W as createShardCtxDb,Vs as createSystemReader,ce as cursorBelowRetainedFloor,No as decideDurableAttach,Fs as decodeBigintSqlKey,lt as decodeCursor,ks as decodeFloat64SqlKey,cr as deferScheduleOutbox,Xe as deleteGlobalShapeSnapshot,He as deleteGlobalShapeSnapshotsForConnection,yr as deleteShapePokeCursor,Mr as deleteShapePokeCursorsForConnection,Io as deleteStreamRun,Qr as depKey,si as deriveRelationEdges,hi as describeRelationWrites,qo as diffExternalSource,xs as diffGlobalMembership,Ci as distinctValues,mr as dropScheduleOutbox,g as encodeAggregateKey,dt as encodeCursor,ua as encodeGeohash,bt as encodePartitionKey,Es as encodeRowsPatch,B as ensureAuditTable,Wa as ensureMailTable,Uo as envOptionalPositiveInt,Go as envPositiveInt,ct as equalityPinnedFields,o as exportShardRows,Da as facetColumn,gi as fanOutScalarCounts,Si as findManyPage,ni as findRelated,Oa as findStorageReferences,bo as finishStreamRun,Ns as float64SqlKey,_ as foldAggregateTally,pr as forgetScheduleOutbox,oa as ftsCompanionDdl,aa as ftsPurgeDocument,ta as ftsRowidMapName,ia as ftsUnmappedPage,sa as ftsWriteDocument,qi as gateReplicaDispatch,so as geoTableName,us as globalShapeReadKey,na as groupUnmappedRows,ji as guardWriter,vi as handleReplicaControl,ur as hasScheduleOutboxEntry,$s as hasTrigger,Sa as haversineMeters,a as importShardRows,Yt as indexKeysForRow,ss as isDevEnvironment,no as isFtsAvailable,In as isInternalTableName,Rt as isLossyBody,ar as isMemoryTable,Zt as isPushableWhere,fi as isRelationPredicate,Jo as isSoftDeleted,Zo as isSourceDue,on as isTtlExpired,Pa as isVacuousFilterClause,lo as jsonPath,co as jsonPathSql,jt as keysTouchRanges,Ko as liftSourceId,Ds as lintReadonlySql,m as listAdminTokens,Gt as listReactorStates,ya as listTables,Vt as markUnvouchableReads,Lt as matchesRankStaticWhere,E as matchesStaticWhere,Vo as materializeExternalRows,zo as materializeExternalRowsIncremental,tr as memoryTableNames,Ks as mergeChangedKeys,D as mergeWhere,me as migrateCdcLog,pe as migrateCdcMeta,Oe as migrateClientWatermark,Ne as migrateCommitSeq,Lo as migrateDurableStreams,Ve as migrateGlobalShapeSnapshot,Je as migrateIdempotency,wt as migrateReactorState,Sr as migrateScheduleOutbox,br as migrateSearchState,Fr as migrateShapePokeCursor,ue as minCdcReplayableSeq,Se as minCdcSeq,kr as minShapePokeCursor,Pi as nextPromotionState,an as nextTtlExpiry,h as normalizeCountArgument,X as normalizeIdStructurally,mt as normalizeOrderKeys,Wo as normalizeSourceDocument,Xo as normalizeSourceValue,pt as nullsFirstOf,ut as nullsOrderSuffix,ja as operatorFields,ho as param,fr as parkScheduleOutbox,t as parseExportShardArgs,i as parseImportShardArgs,Ja as patchDependsOnRow,O as planAggregateLookup,fa as pointInBoundingBox,xr as probeScheduleOutbox,hs as projectColumns,$o as pullExternalSourceIncrementalTick,ea as pullExternalSourceTick,mo as qualifiedJsonPath,po as qualifiedJsonPathSql,Ln as quoteIdentifier,Dt as rankKeyFromDoc,Ot as rankPivotConditionSql,Pt as rankTableName,Nt as reactiveCacheKey,qt as reactorNeedsRun,I as readAggregateValue,ge as readArchivedCdcChanges,U as readAuditLog,ot as readBookmark,Xa as readCapturedMail,_e as readCdcArchivedThrough,fe as readCdcChangeKeys,xe as readCdcChanges,Ee as readCdcCursor,he as readCdcEpoch,Pe as readClientWatermark,Be as readCommitSeq,ns as readDeployInfo,Er as readDueScheduleOutbox,hr as readDueScheduleOutboxEntry,Qo as readExternalSourceBaseline,ze as readGlobalShapeSnapshot,Ze as readIdempotent,Wr as readMigrationStatus,Za as readPatchField,At as readQueueMessageById,Ct as readQueueMessages,vt as readReactorState,Tr as readScheduleOutbox,Rr as readScheduleOutboxState,$i as readSchemaHistory,es as readSchemaVersion,Lr as readSearchBackfillState,Nr as readShapePokeCursor,Do as readStreamChunks,Oo as readStreamRun,Ma as readTablePage,Ha as recordCapturedMail,Ws as recordChangedKeys,Fa as recordFanoutPass,ka as recordGlobalPollPass,gt as recordQueueMessages,Ar as recordScheduleOutbox,rs as recordSchemaVersion,Na as recordShapeProbePass,_i as relationHooks,yi as relayCountFor,To as renderSql,Hi as reprojectableFields,gn as reprojectionMigrationId,Vi as reprojectionTables,Cr as requeueScheduleOutbox,$a as resolvePatch,yt as resolveRankPartition,nr as resolveRankSeekTuple,xi as resolveRelationPredicates,Ii as resolveWith,p as revokeAdminTokenRecord,uo as rowToDocument,Xr as runDataMigration,Jr as runDrizzle,Yo as runExternalSourceTick,Os as runReadonlySql,bi as runRowValidators,On as runShardMigrations,_s as runSocketPool,Zr as runSql,en as runTriggers,tn as selectExpiredIds,s as selectExportTables,P as selectIndexForAggregate,y as selectIndexForCount,M as selectIndexForGroupBy,Ba as selectMatchingIds,wr as selectShapeMembers,qr as selectShapeRows,as as serializeSqlValue,mn as serverInList,Mi as shapeRoutingKey,hn as siblingSecretOf,Tn as signSiblingBody,St as softDeleteScope,Mt as sortColumnName,Ro as sqliteInList,yn as stableStringify,Mn as stableWireKey,H as stripReservedPatchFields,Cs as stubByName,Gs as subscriptionFrames,ws as subscriptionListDeltas,Ua as summarizeFanoutTopics,Ga as summarizeSubscriptions,So as tableColumns,Yr as tableFromDepKey,T as throwingScheduler,ft as tiebreakDirectionFor,Te as trimCdcChanges,$e as trimIdempotent,gr as trimScheduleOutbox,Po as trimStreamRuns,fo as tryRowToDocument,qs as trySendFrame,Ao as unionAll,xt as uniqueIndexFields,n as validateImportRow,u as verifyAdminTokenDigest,Rn as verifySiblingBody,$t as whereFilter,ei as whereOfFilter,Ie as writeCdcArchivedThrough,Qe as writeGlobalShapeSnapshot,er as writeIdempotent,Kt as writeReactorState,Dr as writeSearchBackfillState,Br as writeShapePokeCursor,Ur as writeShapePokeCursors,Xs as writeTouchesMemo};
1
+ import{exportShardRows as o,importShardRows as a,parseExportShardArgs as t,parseImportShardArgs as i,selectExportTables as s,validateImportRow as n}from"./packem_shared/exportShardRows-CZh4wrvI.mjs";import{adminTokenExists as d,createAdminTokenRecord as c,listAdminTokens as m,revokeAdminTokenRecord as p,verifyAdminTokenDigest as u}from"./packem_shared/adminTokenExists-CjKKZzfY.mjs";import{AGGREGATE_SQL_FUNCTION as f,aggregateSqlFunction as x,matchesStaticWhere as E,normalizeCountArgument as h,throwingScheduler as T}from"./packem_shared/AGGREGATE_SQL_FUNCTION-C_ZipS9R.mjs";import{aggregateTableName as A,coerceAggregateNumber as C,encodeAggregateKey as g,foldAggregateTally as _,readAggregateValue as I}from"./packem_shared/aggregateTableName-B_CtIQCS.mjs";import{CountRlsUnsupportedError as L,mergeWhere as D,planAggregateLookup as O,selectIndexForAggregate as P,selectIndexForCount as y,selectIndexForGroupBy as M}from"./packem_shared/CountRlsUnsupportedError-BvsDqfO2.mjs";import{AUDIT_LOG_TABLE as k,appendAuditEntry as N,ensureAuditTable as B,readAuditLog as U}from"./packem_shared/AUDIT_LOG_TABLE-BFJ65SRS.mjs";import{NotUniqueError as w,assertNoExplicitUndefined as q,assertStorableRowId as v,assertValidClientId as K,createShardCtxDb as W,normalizeIdStructurally as X,stripReservedPatchFields as H}from"./packem_shared/NotUniqueError-B2OuN937.mjs";import{backfillAggregateIndexes as z,backfillRankIndexes as Q,backfillSearchIndexes as Y,backfillSearchIndexesForTable as j}from"./packem_shared/backfillAggregateIndexes-BwCpPW7h.mjs";import{CDC_LOG_TABLE as Z,CDC_LOG_TABLE_SEQ_INDEX as $,CDC_META_TABLE as ee,appendCdcChange as re,applyCdcChanges as oe,bumpCdcEpoch as ae,cdcCanVouchFor as te,cdcForkedError as ie,cdcSeqLeavingRows as se,cdcTouchesTables as ne,cdcTrimmedError as le,compactCdcDocs as de,cursorBelowRetainedFloor as ce,migrateCdcLog as me,migrateCdcMeta as pe,minCdcReplayableSeq as ue,minCdcSeq as Se,readCdcChangeKeys as fe,readCdcChanges as xe,readCdcCursor as Ee,readCdcEpoch as he,trimCdcChanges as Te}from"./packem_shared/CDC_LOG_TABLE-BFGgqai8.mjs";import{archiveCdcSegment as Ae,cdcArchiveRewound as Ce,readArchivedCdcChanges as ge,readCdcArchivedThrough as _e,writeCdcArchivedThrough as Ie}from"./packem_shared/archiveCdcSegment-Cr8oGLfB.mjs";import{CLIENT_WATERMARK_TABLE as Le,advanceClientWatermark as De,migrateClientWatermark as Oe,readClientWatermark as Pe}from"./packem_shared/CLIENT_WATERMARK_TABLE-De7z_OHV.mjs";import{COMMIT_SEQ_FIELD as Me,COMMIT_SEQ_TABLE as Fe,allocateCommitSeq as ke,migrateCommitSeq as Ne,readCommitSeq as Be}from"./packem_shared/COMMIT_SEQ_FIELD-Da1DjGqo.mjs";import{CompanionMemo as Ge,clearCompanionSignatures as we}from"./packem_shared/CompanionMemo-BXU5vfak.mjs";import{createCompanionSync as ve}from"./packem_shared/createCompanionSync-DO92CQek.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as We,deleteGlobalShapeSnapshot as Xe,deleteGlobalShapeSnapshotsForConnection as He,migrateGlobalShapeSnapshot as Ve,readGlobalShapeSnapshot as ze,writeGlobalShapeSnapshot as Qe}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-Bb6-aZuH.mjs";import{IDEMPOTENCY_TABLE as je,migrateIdempotency as Je,readIdempotent as Ze,trimIdempotent as $e,writeIdempotent as er}from"./packem_shared/IDEMPOTENCY_TABLE-COrgeP3O.mjs";import{clearMemoryTables as or,isMemoryTable as ar,memoryTableNames as tr}from"./packem_shared/clearMemoryTables-aMRERF0w.mjs";import{computeRankPage as sr,resolveRankSeekTuple as nr}from"./packem_shared/computeRankPage-B6umzbg4.mjs";import{SCHEDULE_OUTBOX_TABLE as dr,deferScheduleOutbox as cr,dropScheduleOutbox as mr,forgetScheduleOutbox as pr,hasScheduleOutboxEntry as ur,migrateScheduleOutbox as Sr,parkScheduleOutbox as fr,probeScheduleOutbox as xr,readDueScheduleOutbox as Er,readDueScheduleOutboxEntry as hr,readScheduleOutbox as Tr,readScheduleOutboxState as Rr,recordScheduleOutbox as Ar,requeueScheduleOutbox as Cr,trimScheduleOutbox as gr}from"./packem_shared/SCHEDULE_OUTBOX_TABLE-iyyiSjsO.mjs";import{S as Ir,m as br,r as Lr,w as Dr}from"./packem_shared/ctx-db-search-state-CPKPy8N6.mjs";import{SHAPE_POKE_CURSOR_TABLE as Pr,deleteShapePokeCursor as yr,deleteShapePokeCursorsForConnection as Mr,migrateShapePokeCursor as Fr,minShapePokeCursor as kr,readShapePokeCursor as Nr,writeShapePokeCursor as Br,writeShapePokeCursors as Ur}from"./packem_shared/SHAPE_POKE_CURSOR_TABLE-BGvY3sFI.mjs";import{selectShapeMembers as wr,selectShapeRows as qr}from"./packem_shared/selectShapeMembers-Dqx_m7BF.mjs";import{DATA_MIGRATION_STATE_TABLE as Kr,readMigrationStatus as Wr,runDataMigration as Xr}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-CPWZjliE.mjs";import{SCAN_DEP as Vr,createDependencyTracker as zr,depKey as Qr,tableFromDepKey as Yr}from"./packem_shared/SCAN_DEP-B4Uu4g7l.mjs";import{runDrizzle as Jr,runSql as Zr}from"./packem_shared/runDrizzle-RC09zZrh.mjs";import{A as eo,a as ro,b as oo,D as ao,c as to,d as io,g as so,i as no,j as lo,e as co,q as mo,f as po,r as uo,t as So,h as fo}from"./packem_shared/do-sql-105TONaE.mjs";import{WORKERD_SQLITE_LIMITS as Eo,param as ho,renderSql as To,sqliteInList as Ro,unionAll as Ao}from"./packem_shared/WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{appendStreamChunk as go,claimStreamRun as _o,deleteStreamRun as Io,finishStreamRun as bo,migrateDurableStreams as Lo,readStreamChunks as Do,readStreamRun as Oo,trimStreamRuns as Po}from"./packem_shared/appendStreamChunk-BZYgGE9Y.mjs";import{DurableStreamRunner as Mo,MAX_DURABLE_STREAM_BYTES as Fo,MAX_DURABLE_STREAM_CHUNKS as ko,decideDurableAttach as No}from"./packem_shared/DurableStreamRunner-MMlV5qKQ.mjs";import{envOptionalPositiveInt as Uo,envPositiveInt as Go}from"./packem_shared/envOptionalPositiveInt-D2pY-c64.mjs";import{diffExternalSource as qo}from"./packem_shared/diffExternalSource-B0FZlDoL.mjs";import{liftSourceId as Ko,normalizeSourceDocument as Wo,normalizeSourceValue as Xo}from"./packem_shared/liftSourceId-CA3ENhXj.mjs";import{materializeExternalRows as Vo,materializeExternalRowsIncremental as zo,readExternalSourceBaseline as Qo,runExternalSourceTick as Yo}from"./packem_shared/materializeExternalRows-CHPRx8fu.mjs";import{isSoftDeleted as Jo,isSourceDue as Zo,pullExternalSourceIncrementalTick as $o,pullExternalSourceTick as ea}from"./packem_shared/isSoftDeleted-BBWKE0Sm.mjs";import{f as oa,a as aa,b as ta,c as ia,d as sa,g as na}from"./packem_shared/fts-companion-CE3EmIjk.mjs";import{GEO_DEFAULT_PRECISION as da,boundingBoxCenter as ca,boundingBoxGeohashes as ma,coveringGeohashes as pa,encodeGeohash as ua,haversineMeters as Sa,pointInBoundingBox as fa}from"./packem_shared/GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{default as Ea}from"./packem_shared/GlobalPollTick-BNK4o-XT.mjs";import{ADMIN_FUNCTIONS as Ta,ADMIN_FUNCTION_PREFIX as Ra,DEFAULT_FANOUT_TOPIC_LIMIT as Aa,FLAGS_FUNCTION_PREFIX as Ca,MAX_PAGE_SIZE as ga,RELATION_FUNCTION_PREFIX as _a,createFanoutCounters as Ia,createGlobalPollCounters as ba,createShapeProbeCounters as La,facetColumn as Da,findStorageReferences as Oa,isVacuousFilterClause as Pa,listTables as ya,readTablePage as Ma,recordFanoutPass as Fa,recordGlobalPollPass as ka,recordShapeProbePass as Na,selectMatchingIds as Ba,summarizeFanoutTopics as Ua,summarizeSubscriptions as Ga}from"./packem_shared/ADMIN_FUNCTIONS-CSz3ZK2d.mjs";import{MAIL_RETENTION as qa,MAIL_TABLE as va,clearCapturedMail as Ka,ensureMailTable as Wa,readCapturedMail as Xa,recordCapturedMail as Ha}from"./packem_shared/MAIL_RETENTION-DMolrLYt.mjs";import{NotFoundError as za}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{assertPatchAllowed as Ya,operatorFields as ja,patchDependsOnRow as Ja,readPatchField as Za,resolvePatch as $a}from"./packem_shared/assertPatchAllowed-CA_H466g.mjs";import{armRestore as rt,readBookmark as ot}from"./packem_shared/armRestore-Bu1_8SUa.mjs";import{CURSOR_PREFIX as tt,applySelect as it,buildSeekBeforeWhere as st,buildSeekWhere as nt,decodeCursor as lt,encodeCursor as dt,equalityPinnedFields as ct,normalizeOrderKeys as mt,nullsFirstOf as pt,nullsOrderSuffix as ut,softDeleteScope as St,tiebreakDirectionFor as ft,uniqueIndexFields as xt}from"./packem_shared/CURSOR_PREFIX-rOdoinP8.mjs";import{QUEUE_TABLE as ht,clearQueueMessages as Tt,isLossyBody as Rt,readQueueMessageById as At,readQueueMessages as Ct,recordQueueMessages as gt}from"./packem_shared/QUEUE_TABLE-C-goXtGd.mjs";import{RANK_TIEBREAK as It,encodePartitionKey as bt,matchesRankStaticWhere as Lt,rankKeyFromDoc as Dt,rankPivotConditionSql as Ot,rankTableName as Pt,resolveRankPartition as yt,sortColumnName as Mt}from"./packem_shared/RANK_TIEBREAK-D3ye2GsL.mjs";import{ReactiveCache as kt,reactiveCacheKey as Nt}from"./packem_shared/ReactiveCache-BG9z3FE9.mjs";import{REACTOR_STATE_TABLE as Ut,listReactorStates as Gt,migrateReactorState as wt,reactorNeedsRun as qt,readReactorState as vt,writeReactorState as Kt}from"./packem_shared/REACTOR_STATE_TABLE-D2Mn204f.mjs";import{UNVOUCHABLE_DEP as Xt,createReadFootprint as Ht,markUnvouchableReads as Vt}from"./packem_shared/UNVOUCHABLE_DEP-Ds9gxVqs.mjs";import{buildIndexRange as Qt,indexKeysForRow as Yt,keysTouchRanges as jt}from"./packem_shared/buildIndexRange-BTChxh3k.mjs";import{isPushableWhere as Zt,whereFilter as $t,whereOfFilter as ei}from"./packem_shared/isPushableWhere-BeYAOjUb.mjs";import{RELATED_DEFAULT_LIMIT as oi,RELATED_DEPTH_DECAY as ai,RELATED_MAX_DEPTH as ti,RELATED_MAX_LIMIT as ii,deriveRelationEdges as si,findRelated as ni}from"./packem_shared/RELATED_DEFAULT_LIMIT-CAh3WUMn.mjs";import{DEFAULT_MAX_RELATION_KEYS as di,assertFlatPredicate as ci,assertShapeShardable as mi,composeReadPredicate as pi,containsRelationPredicate as ui,findManyPage as Si,isRelationPredicate as fi,resolveRelationPredicates as xi}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-B_BOc9w_.mjs";import{describeRelationWrites as hi}from"./packem_shared/describeRelationWrites-omar6-u9.mjs";import{applyInsertDefaults as Ri,applyOnDelete as Ai,distinctValues as Ci,fanOutScalarCounts as gi,relationHooks as _i,resolveWith as Ii,runRowValidators as bi}from"./packem_shared/applyInsertDefaults-BJ4dP3OL.mjs";import{D as Di,c as Oi,n as Pi,r as yi,s as Mi}from"./packem_shared/relay-CKEdfUjH.mjs";import{DEFAULT_MAX_RELAYS as ki,OwnerRelay as Ni,RelayMember as Bi,createRelayLink as Ui}from"./packem_shared/DEFAULT_MAX_RELAYS-Bc6PI-xy.mjs";import{createReplicaLink as wi,gateReplicaDispatch as qi,handleReplicaControl as vi}from"./packem_shared/createReplicaLink-DtqXBi-0.mjs";import{buildReprojectionMigration as Wi,countLegacyRows as Xi,reprojectableFields as Hi,reprojectionTables as Vi}from"./packem_shared/buildReprojectionMigration-B8aEpETD.mjs";import{RLS_UNWRAP_SYMBOL as Qi,RlsRequiredError as Yi,guardWriter as ji}from"./packem_shared/RLS_UNWRAP_SYMBOL-CZIpCjzt.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as Zi,readSchemaHistory as $i,readSchemaVersion as es,recordSchemaVersion as rs}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-CEwFjj-O.mjs";import{serializeSqlValue as as}from"./packem_shared/serializeSqlValue-DeoBMpZ2.mjs";import{buildSettings as is,isDevEnvironment as ss,readDeployInfo as ns}from"./packem_shared/buildSettings-CFkvTaHx.mjs";import{buildShapeDiff as ds}from"./packem_shared/buildShapeDiff-CdLJTijm.mjs";import{ShapeDiffCache as ms,createShapeDiffCache as ps,globalShapeReadKey as us}from"./packem_shared/ShapeDiffCache-iNO-hUiy.mjs";import{buildPokeFrames as fs,diffGlobalMembership as xs,encodeRowsPatch as Es,projectColumns as hs}from"./packem_shared/buildPokeFrames-WR-hp0mX.mjs";import{ShardRunner as Rs}from"./packem_shared/ShardRunner-CrveaPId.mjs";import{stubByName as Cs}from"./packem_shared/stubByName-DQSivmvb.mjs";import{runSocketPool as _s}from"./packem_shared/runSocketPool-CZJ2X9cF.mjs";import{MAX_SQL_ROWS as bs,assertReadonly as Ls,lintReadonlySql as Ds,runReadonlySql as Os}from"./packem_shared/MAX_SQL_ROWS-B4WlVI-e.mjs";import{BIGINT_KEY_DIGITS as ys,bigintSqlKey as Ms,decodeBigintSqlKey as Fs,decodeFloat64SqlKey as ks,float64SqlKey as Ns}from"./packem_shared/BIGINT_KEY_DIGITS-DE6yshOt.mjs";import{awaitWsDrain as Us,subscriptionFrames as Gs,subscriptionListDeltas as ws,trySendFrame as qs}from"./packem_shared/awaitWsDrain-DMcWBQ7I.mjs";import{mergeChangedKeys as Ks,recordChangedKeys as Ws,writeTouchesMemo as Xs}from"./packem_shared/mergeChangedKeys-DPKhen6e.mjs";import{createSystemReader as Vs}from"./packem_shared/createSystemReader-BSCxr8Qs.mjs";import{ConflictError as Qs}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as js,TransactionHeadroomTracker as Js}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS-D7p7Ys0M.mjs";import{hasTrigger as $s,runTriggers as en}from"./packem_shared/hasTrigger-CjlwI4le.mjs";import{isTtlExpired as on,nextTtlExpiry as an,selectExpiredIds as tn}from"./packem_shared/isTtlExpired-DNxmZA6e.mjs";import{VECTOR_BACKFILL_MAX_PAGES as nn,backfillVectorIndexes as ln}from"./packem_shared/VECTOR_BACKFILL_MAX_PAGES-DJ6iD61G.mjs";import{c as cn,s as mn}from"./packem_shared/where-sql-BjY4rnqb.mjs";import{RELATION_EXISTS_KEY as un}from"./packem_shared/RELATION_EXISTS_KEY-wxgj6rSL.mjs";import{ADMIN_TOKEN_TABLE as fn}from"./packem_shared/ADMIN_TOKEN_TABLE-DfQ5osdI.mjs";import{RELAY_SIGNATURE_HEADER as En,siblingSecretOf as hn,signSiblingBody as Tn,verifySiblingBody as Rn}from"./packem_shared/RELAY_SIGNATURE_HEADER-CAfC4tqg.mjs";import{REPROJECTION_MIGRATION_PREFIX as Cn,reprojectionMigrationId as gn}from"./packem_shared/REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{isInternalTableName as In}from"./packem_shared/isInternalTableName-BoljO2tP.mjs";import{quoteIdentifier as Ln}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as On}from"./packem_shared/runShardMigrations-Bc7PsQhM.mjs";import{stableStringify as yn,stableWireKey as Mn}from"@lunora/wire";export{Ta as ADMIN_FUNCTIONS,Ra as ADMIN_FUNCTION_PREFIX,fn as ADMIN_TOKEN_TABLE,f as AGGREGATE_SQL_FUNCTION,eo as AGG_COUNT,ro as AGG_KEY,oo as AGG_VALUE,k as AUDIT_LOG_TABLE,ys as BIGINT_KEY_DIGITS,Z as CDC_LOG_TABLE,$ as CDC_LOG_TABLE_SEQ_INDEX,ee as CDC_META_TABLE,Le as CLIENT_WATERMARK_TABLE,Me as COMMIT_SEQ_FIELD,Fe as COMMIT_SEQ_TABLE,tt as CURSOR_PREFIX,Ge as CompanionMemo,Qs as ConflictError,L as CountRlsUnsupportedError,Kr as DATA_MIGRATION_STATE_TABLE,Aa as DEFAULT_FANOUT_TOPIC_LIMIT,di as DEFAULT_MAX_RELATION_KEYS,ki as DEFAULT_MAX_RELAYS,Di as DEFAULT_PROMOTION_THRESHOLDS,js as DEFAULT_TRANSACTION_LIMITS,ao as DOC_COLUMN,Mo as DurableStreamRunner,Ca as FLAGS_FUNCTION_PREFIX,da as GEO_DEFAULT_PRECISION,We as GLOBAL_SHAPE_SNAPSHOT_TABLE,Ea as GlobalPollTick,je as IDEMPOTENCY_TABLE,qa as MAIL_RETENTION,va as MAIL_TABLE,Fo as MAX_DURABLE_STREAM_BYTES,ko as MAX_DURABLE_STREAM_CHUNKS,ga as MAX_PAGE_SIZE,bs as MAX_SQL_ROWS,za as NotFoundError,w as NotUniqueError,Ni as OwnerRelay,ht as QUEUE_TABLE,It as RANK_TIEBREAK,Ut as REACTOR_STATE_TABLE,oi as RELATED_DEFAULT_LIMIT,ai as RELATED_DEPTH_DECAY,ti as RELATED_MAX_DEPTH,ii as RELATED_MAX_LIMIT,un as RELATION_EXISTS_KEY,_a as RELATION_FUNCTION_PREFIX,En as RELAY_SIGNATURE_HEADER,Cn as REPROJECTION_MIGRATION_PREFIX,Qi as RLS_UNWRAP_SYMBOL,kt as ReactiveCache,Bi as RelayMember,Yi as RlsRequiredError,Vr as SCAN_DEP,dr as SCHEDULE_OUTBOX_TABLE,Zi as SCHEMA_HISTORY_MAX_VERSIONS,Ir as SEARCH_STATE_TABLE,Pr as SHAPE_POKE_CURSOR_TABLE,ms as ShapeDiffCache,Rs as ShardRunner,Js as TransactionHeadroomTracker,Xt as UNVOUCHABLE_DEP,nn as VECTOR_BACKFILL_MAX_PAGES,Eo as WORKERD_SQLITE_LIMITS,d as adminTokenExists,De as advanceClientWatermark,to as aggUpsertSql,x as aggregateSqlFunction,A as aggregateTableName,ke as allocateCommitSeq,N as appendAuditEntry,re as appendCdcChange,go as appendStreamChunk,oe as applyCdcChanges,Ri as applyInsertDefaults,Ai as applyOnDelete,it as applySelect,Ae as archiveCdcSegment,rt as armRestore,ci as assertFlatPredicate,q as assertNoExplicitUndefined,Ya as assertPatchAllowed,Ls as assertReadonly,mi as assertShapeShardable,v as assertStorableRowId,K as assertValidClientId,Us as awaitWsDrain,z as backfillAggregateIndexes,Q as backfillRankIndexes,Y as backfillSearchIndexes,j as backfillSearchIndexesForTable,ln as backfillVectorIndexes,Ms as bigintSqlKey,ca as boundingBoxCenter,ma as boundingBoxGeohashes,Qt as buildIndexRange,fs as buildPokeFrames,Wi as buildReprojectionMigration,st as buildSeekBeforeWhere,nt as buildSeekWhere,is as buildSettings,ds as buildShapeDiff,ae as bumpCdcEpoch,Ce as cdcArchiveRewound,te as cdcCanVouchFor,ie as cdcForkedError,se as cdcSeqLeavingRows,ne as cdcTouchesTables,le as cdcTrimmedError,_o as claimStreamRun,Oi as clampPromotionThresholds,Ka as clearCapturedMail,we as clearCompanionSignatures,or as clearMemoryTables,Tt as clearQueueMessages,C as coerceAggregateNumber,de as compactCdcDocs,cn as compileWhereSql,pi as composeReadPredicate,sr as computeRankPage,ui as containsRelationPredicate,Xi as countLegacyRows,pa as coveringGeohashes,c as createAdminTokenRecord,ve as createCompanionSync,zr as createDependencyTracker,Ia as createFanoutCounters,ba as createGlobalPollCounters,io as createIndexSql,Ht as createReadFootprint,Ui as createRelayLink,wi as createReplicaLink,ps as createShapeDiffCache,La as createShapeProbeCounters,W as createShardCtxDb,Vs as createSystemReader,ce as cursorBelowRetainedFloor,No as decideDurableAttach,Fs as decodeBigintSqlKey,lt as decodeCursor,ks as decodeFloat64SqlKey,cr as deferScheduleOutbox,Xe as deleteGlobalShapeSnapshot,He as deleteGlobalShapeSnapshotsForConnection,yr as deleteShapePokeCursor,Mr as deleteShapePokeCursorsForConnection,Io as deleteStreamRun,Qr as depKey,si as deriveRelationEdges,hi as describeRelationWrites,qo as diffExternalSource,xs as diffGlobalMembership,Ci as distinctValues,mr as dropScheduleOutbox,g as encodeAggregateKey,dt as encodeCursor,ua as encodeGeohash,bt as encodePartitionKey,Es as encodeRowsPatch,B as ensureAuditTable,Wa as ensureMailTable,Uo as envOptionalPositiveInt,Go as envPositiveInt,ct as equalityPinnedFields,o as exportShardRows,Da as facetColumn,gi as fanOutScalarCounts,Si as findManyPage,ni as findRelated,Oa as findStorageReferences,bo as finishStreamRun,Ns as float64SqlKey,_ as foldAggregateTally,pr as forgetScheduleOutbox,oa as ftsCompanionDdl,aa as ftsPurgeDocument,ta as ftsRowidMapName,ia as ftsUnmappedPage,sa as ftsWriteDocument,qi as gateReplicaDispatch,so as geoTableName,us as globalShapeReadKey,na as groupUnmappedRows,ji as guardWriter,vi as handleReplicaControl,ur as hasScheduleOutboxEntry,$s as hasTrigger,Sa as haversineMeters,a as importShardRows,Yt as indexKeysForRow,ss as isDevEnvironment,no as isFtsAvailable,In as isInternalTableName,Rt as isLossyBody,ar as isMemoryTable,Zt as isPushableWhere,fi as isRelationPredicate,Jo as isSoftDeleted,Zo as isSourceDue,on as isTtlExpired,Pa as isVacuousFilterClause,lo as jsonPath,co as jsonPathSql,jt as keysTouchRanges,Ko as liftSourceId,Ds as lintReadonlySql,m as listAdminTokens,Gt as listReactorStates,ya as listTables,Vt as markUnvouchableReads,Lt as matchesRankStaticWhere,E as matchesStaticWhere,Vo as materializeExternalRows,zo as materializeExternalRowsIncremental,tr as memoryTableNames,Ks as mergeChangedKeys,D as mergeWhere,me as migrateCdcLog,pe as migrateCdcMeta,Oe as migrateClientWatermark,Ne as migrateCommitSeq,Lo as migrateDurableStreams,Ve as migrateGlobalShapeSnapshot,Je as migrateIdempotency,wt as migrateReactorState,Sr as migrateScheduleOutbox,br as migrateSearchState,Fr as migrateShapePokeCursor,ue as minCdcReplayableSeq,Se as minCdcSeq,kr as minShapePokeCursor,Pi as nextPromotionState,an as nextTtlExpiry,h as normalizeCountArgument,X as normalizeIdStructurally,mt as normalizeOrderKeys,Wo as normalizeSourceDocument,Xo as normalizeSourceValue,pt as nullsFirstOf,ut as nullsOrderSuffix,ja as operatorFields,ho as param,fr as parkScheduleOutbox,t as parseExportShardArgs,i as parseImportShardArgs,Ja as patchDependsOnRow,O as planAggregateLookup,fa as pointInBoundingBox,xr as probeScheduleOutbox,hs as projectColumns,$o as pullExternalSourceIncrementalTick,ea as pullExternalSourceTick,mo as qualifiedJsonPath,po as qualifiedJsonPathSql,Ln as quoteIdentifier,Dt as rankKeyFromDoc,Ot as rankPivotConditionSql,Pt as rankTableName,Nt as reactiveCacheKey,qt as reactorNeedsRun,I as readAggregateValue,ge as readArchivedCdcChanges,U as readAuditLog,ot as readBookmark,Xa as readCapturedMail,_e as readCdcArchivedThrough,fe as readCdcChangeKeys,xe as readCdcChanges,Ee as readCdcCursor,he as readCdcEpoch,Pe as readClientWatermark,Be as readCommitSeq,ns as readDeployInfo,Er as readDueScheduleOutbox,hr as readDueScheduleOutboxEntry,Qo as readExternalSourceBaseline,ze as readGlobalShapeSnapshot,Ze as readIdempotent,Wr as readMigrationStatus,Za as readPatchField,At as readQueueMessageById,Ct as readQueueMessages,vt as readReactorState,Tr as readScheduleOutbox,Rr as readScheduleOutboxState,$i as readSchemaHistory,es as readSchemaVersion,Lr as readSearchBackfillState,Nr as readShapePokeCursor,Do as readStreamChunks,Oo as readStreamRun,Ma as readTablePage,Ha as recordCapturedMail,Ws as recordChangedKeys,Fa as recordFanoutPass,ka as recordGlobalPollPass,gt as recordQueueMessages,Ar as recordScheduleOutbox,rs as recordSchemaVersion,Na as recordShapeProbePass,_i as relationHooks,yi as relayCountFor,To as renderSql,Hi as reprojectableFields,gn as reprojectionMigrationId,Vi as reprojectionTables,Cr as requeueScheduleOutbox,$a as resolvePatch,yt as resolveRankPartition,nr as resolveRankSeekTuple,xi as resolveRelationPredicates,Ii as resolveWith,p as revokeAdminTokenRecord,uo as rowToDocument,Xr as runDataMigration,Jr as runDrizzle,Yo as runExternalSourceTick,Os as runReadonlySql,bi as runRowValidators,On as runShardMigrations,_s as runSocketPool,Zr as runSql,en as runTriggers,tn as selectExpiredIds,s as selectExportTables,P as selectIndexForAggregate,y as selectIndexForCount,M as selectIndexForGroupBy,Ba as selectMatchingIds,wr as selectShapeMembers,qr as selectShapeRows,as as serializeSqlValue,mn as serverInList,Mi as shapeRoutingKey,hn as siblingSecretOf,Tn as signSiblingBody,St as softDeleteScope,Mt as sortColumnName,Ro as sqliteInList,yn as stableStringify,Mn as stableWireKey,H as stripReservedPatchFields,Cs as stubByName,Gs as subscriptionFrames,ws as subscriptionListDeltas,Ua as summarizeFanoutTopics,Ga as summarizeSubscriptions,So as tableColumns,Yr as tableFromDepKey,T as throwingScheduler,ft as tiebreakDirectionFor,Te as trimCdcChanges,$e as trimIdempotent,gr as trimScheduleOutbox,Po as trimStreamRuns,fo as tryRowToDocument,qs as trySendFrame,Ao as unionAll,xt as uniqueIndexFields,n as validateImportRow,u as verifyAdminTokenDigest,Rn as verifySiblingBody,$t as whereFilter,ei as whereOfFilter,Ie as writeCdcArchivedThrough,Qe as writeGlobalShapeSnapshot,er as writeIdempotent,Kt as writeReactorState,Dr as writeSearchBackfillState,Br as writeShapePokeCursor,Ur as writeShapePokeCursors,Xs as writeTouchesMemo};
@@ -0,0 +1 @@
1
+ import{LunoraError as S}from"@lunora/errors";import{decodeWire as O,encodeWire as p}from"@lunora/wire";import{v as _}from"./accepts-null-D1zmJbyR.mjs";import{r as A}from"./json-field-path-DeJW4U9z.mjs";import{SEEK_RANGE as E}from"./RELATION_EXISTS_KEY-wxgj6rSL.mjs";const R="id",h=e=>e.at(-1)?.direction==="desc"?"desc":"asc",b=new Set(["_id","id"]),F=new Set(["_creationTime","_id","id"]),g=(e,t)=>{if(F.has(e))return!1;const n=t?.[e];return n===void 0?!0:n.kind==="optional"||n._meta?.column?.notNull===!1||_(n)},I=new Set(["AND","NOT","OR"]),U=e=>{const t=new Set;if(typeof e!="object"||Array.isArray(e))return t;for(const[n,r]of Object.entries(e)){if(I.has(n))continue;if(r===null||typeof r!="object"||Array.isArray(r)){t.add(n);continue}const o=Object.keys(r);o.length===1&&o[0]==="eq"&&t.add(n)}return t},x=(e,t)=>{const n=[];for(const r of e??[])r.unique===!0&&n.push(r.fields);for(const[r,o]of Object.entries(t??{}))o._meta?.column?.unique===!0&&n.push([r]);return n},T=(e,t)=>(t??[]).some(n=>n.length>0&&n.every(r=>e.has(r))),y=e=>e.nulls===void 0?e.direction!=="desc":e.nulls==="first",K=e=>e?" NULLS FIRST":" NULLS LAST",L=e=>{if(typeof e!="object"||e===null)return!1;const{nulls:t,sort:n}=e;return(n==="asc"||n==="desc")&&(t==="first"||t==="last")},D=(e,t,n)=>{if(t!=="asc"&&t!=="desc"&&!L(t))throw new S("VALIDATION_ERROR",`orderBy "${e}": expected "asc", "desc" or { sort: "asc" | "desc", nulls: "first" | "last" }`);const r=typeof t=="string"?t:t.sort,o=g(e,n);return typeof t=="string"||!o||y({direction:r})===(t.nulls==="first")?{direction:r,field:e,nullable:o}:{direction:r,field:e,nullable:o,nulls:t.nulls}},J=(e,t,n)=>{const r=[],o=new Set(n?.pinned);let l="asc";for(const i of e??[])for(const[c,s]of Object.entries(i)){const u=D(c,s,t),{direction:f}=u;l=f,o.add(c),!n?.pinned?.has(c)&&r.push(u)}return r.length===0?[{direction:l,field:"_creationTime",nullable:!1}]:(r.some(i=>b.has(i.field)||i.field==="_creationTime")||T(o,n?.uniqueBy)||r.push({direction:h(r),field:"_creationTime",nullable:!1}),r)},w=/[\u0080-\u{10FFFF}]/u,C=e=>{if(!w.test(e))return btoa(e);const t=new TextEncoder().encode(e);let n="";for(const r of t)n+=String.fromCodePoint(r);return btoa(n)},v=e=>{const t=atob(e),n=Uint8Array.from(t,r=>r.codePointAt(0)??0);return new TextDecoder().decode(n)},a="~4",z=(e,t)=>{const n=t.map(r=>A(e,r.field)??null);return n.push(e._id),a+C(JSON.stringify(p(n)))},d=()=>new S("INVALID_CURSOR","invalid cursor"),G=e=>{if(!e.startsWith(a))throw d();let t;try{t=O(JSON.parse(v(e.slice(a.length))))}catch{throw d()}if(!Array.isArray(t))throw d();return t.map(n=>n??null)},m=(e,t,n,r)=>{const{field:o}=e,l=e.direction!=="desc"===n,i=y(e)===n;if(t===null)return i?r?{OR:[{[o]:{isNull:!1}},{[o]:{isNull:!0}}]}:{[o]:{isNull:!1}}:r?{[o]:{isNull:!0}}:{OR:[]};let c=l?"gt":"lt";r&&(c=l?"gte":"lte");const s={[o]:{[c]:t,[E]:!0}};return i||!e.nullable?s:{OR:[s,{[o]:{isNull:!0}}]}},N=(e,t,n,r)=>{const o=e.some(s=>b.has(s.field))?e:[...e,{direction:h(e),field:R,nullable:!1}];if(t.length<o.length)throw d();const l=s=>{const u=o[s];if(u===void 0)throw d();const f=m(u,t[s],n,r&&s===o.length-1);return s===o.length-1?f:{OR:[f,{AND:[{[u.field]:{eq:t[s]}},l(s+1)]}]}},i=l(0),[c]=o;return o.length<2||c===void 0||c.nullable||t[0]===null?i:{AND:[m(c,t[0],n,!0),i]}},H=(e,t)=>N(e,t,!0,!1),M=(e,t)=>N(e,t,!1,!0),j=["_id","_creationTime"],X=(e,t,n)=>{if(!t)return e;const r=new Set([...t,...j,...n?Object.keys(n):[]]);return e.map(o=>{const l={};for(const i of r)i in o&&(l[i]=o[i]);return l})},Y=(e,t)=>e&&t!==!0?{[e.field]:{isNull:!0}}:void 0,$=(e,t)=>t===void 0||e[t]===null||e[t]===void 0;export{a as CURSOR_PREFIX,X as applySelect,M as buildSeekBeforeWhere,H as buildSeekWhere,G as decodeCursor,z as encodeCursor,U as equalityPinnedFields,v as fromBase64,$ as isLiveForCompanion,J as normalizeOrderKeys,y as nullsFirstOf,K as nullsOrderSuffix,Y as softDeleteScope,h as tiebreakDirectionFor,C as toBase64,x as uniqueIndexFields};
@@ -1,4 +1,4 @@
1
- import{LunoraError as D}from"@lunora/errors";import{stableWireKey as S}from"@lunora/wire";import{runSql as E}from"./runDrizzle-RC09zZrh.mjs";import{encodeCursor as w,CURSOR_PREFIX as C}from"./CURSOR_PREFIX-6offuG6M.mjs";import{ConflictError as x}from"./ConflictError-C8GtJmjS.mjs";const i="__lunora_migrations",M=100,y=3e4,U=1e4,$=e=>{E(e,`CREATE TABLE IF NOT EXISTS "${i}" (
1
+ import{LunoraError as D}from"@lunora/errors";import{stableWireKey as S}from"@lunora/wire";import{runSql as E}from"./runDrizzle-RC09zZrh.mjs";import{encodeCursor as w,CURSOR_PREFIX as C}from"./CURSOR_PREFIX-rOdoinP8.mjs";import{ConflictError as x}from"./ConflictError-C8GtJmjS.mjs";const i="__lunora_migrations",M=100,y=3e4,U=1e4,$=e=>{E(e,`CREATE TABLE IF NOT EXISTS "${i}" (
2
2
  id TEXT PRIMARY KEY,
3
3
  direction TEXT NOT NULL,
4
4
  status TEXT NOT NULL,
@@ -1 +1 @@
1
- import{LunoraError as l}from"@lunora/errors";import{i as j,R as k}from"./relation-operators-BEg-CvCH.mjs";import{mergeWhere as w}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{isMemoryTable as N}from"./clearMemoryTables-aMRERF0w.mjs";import{normalizeOrderKeys as P,uniqueIndexFields as _,equalityPinnedFields as D,buildSeekWhere as K,decodeCursor as E,buildSeekBeforeWhere as B,softDeleteScope as I,encodeCursor as R}from"./CURSOR_PREFIX-6offuG6M.mjs";import{distinctValues as T}from"./applyInsertDefaults-CVukTkQ5.mjs";import{RELATION_EXISTS_KEY as W}from"./RELATION_EXISTS_KEY-wxgj6rSL.mjs";const $={every:{kind:"many",negateChild:!0,negated:!0},is:{kind:"one",negated:!1},isNot:{kind:"one",negated:!0,nullDisjunct:!0},none:{kind:"many",negated:!0},some:{kind:"many",negated:!1}},S=e=>k.has(e)?e:void 0,p=e=>{const t=S(e),r=t===void 0?void 0:$[t];if(!r)throw new l("INTERNAL",`unknown relation operator "${e}"`);return r},F=e=>e.kind==="one"?{clause:e.field,project:e.references}:{clause:e.references,project:e.field},q=5e3,m=Symbol("relation-key-overflow"),y=e=>Array.isArray(e)?e.map(t=>t??{}):[],C=e=>{if(e.length===1){const[t]=e;return t??{}}return e.length===0?{}:{AND:e}},b=e=>j(e),f=(e,t,r)=>{const n=t.tables[r]?.relationMap??{};return Object.keys(e).some(o=>{const s=e[o];return o==="AND"||o==="OR"?y(s).some(i=>f(i,t,r)):o==="NOT"?f(s??{},t,r):!!n[o]&&b(s)})},de=(e,t,r,n)=>{if(e&&f(e,t,r))throw new l("INTERNAL",`relation-crossing predicates are not supported in ${n}() — use them in findMany/findFirst or an RLS read policy`)},H=async(e,t,r,n)=>{const o=await u(t,e.table,n),{page:s}=await n.fetcher(e.table,{baseWhere:n.relationBaseWhere?.(e.table),relationBaseWhere:n.relationBaseWhere,where:o});return T(s,r)},z=(e,t,r)=>{throw new l("INTERNAL",`relation predicate on "${e.table}" matched ${String(t)} rows, exceeding the ${String(r.maxRelationKeys)}-key limit; narrow the predicate (a same-shard EXISTS push-down lifts this cap)`)},Y=(e,t,r)=>{throw new l("INTERNAL",`relation predicate on "${e.table}" matched at least ${String(t)} distinct keys, exceeding the ${String(r.maxRelationKeys)}-key limit; narrow the predicate`)},Q=async(e,t,r,n,o)=>{const s=await H(e,t,r,n);return s.length<=n.maxRelationKeys?s:o?m:z(e,s.length,n)},v=async(e,t,r,n)=>{const o=await u(t,e.table,n),s=n.maxRelationKeys+1,i=new Set;let a;for(;;){const d=await n.fetcher(e.table,{baseWhere:n.relationBaseWhere?.(e.table),cursor:a,limit:s,relationBaseWhere:n.relationBaseWhere,where:o});if(d.page.length>s)throw new l("INTERNAL",`relation predicate on "${e.table}" read ${String(d.page.length)} rows for a page of at most ${String(s)}; the fetcher did not honour the page limit`);for(const c of T(d.page,r))i.add(c);if(i.size>n.maxRelationKeys&&Y(e,i.size,n),d.isDone)return[...i];if(typeof d.continueCursor!="string")throw new l("INTERNAL",`relation predicate on "${e.table}" returned a page that is not final but has no cursor to continue from`);if(d.continueCursor===a)throw new l("INTERNAL",`relation predicate on "${e.table}" paged with a cursor that did not advance`);a=d.continueCursor}},X=async(e,t,r,n,o)=>{const s=p(e),{clause:i,project:a}=F(t),d=await Q(t,s.negateChild?{NOT:r}:r,a,n,o);return d===m?m:s.negated?s.nullDisjunct?{OR:[{[i]:{notIn:d}},{[i]:{isNull:!0}}]}:{[i]:{notIn:d}}:{[i]:{in:d}}},x=async(e,t,r,n)=>{const o=p(e),{from:s,table:i,to:a}=t.through,d=await v(t,o.negateChild?{NOT:r}:r,"_id",n),c=d.length===0?[]:await v({table:i},{[a]:{in:d}},s,n);return{_id:o.negated?{notIn:c}:{in:c}}},O=async(e,t,r,n,o)=>{const s=p(e),i=o.relationBaseWhere?.(t.table),a=s.negateChild?{NOT:r}:r,L={childWhere:await u(i?{AND:[i,a]}:a,t.table,o),negated:s.negated,parentTable:n,relation:t};return{[W]:L}},U=(e,t,r)=>{const n=S(e),o=n===void 0?void 0:$[n];if(o&&o.kind!==r.kind)throw new l("INTERNAL",`relation operator "${e}" requires a to-${o.kind} relation, but "${t}" is to-${r.kind}`)},V=async(e,t,r,n,o)=>{const s=[];for(const i of Object.keys(r)){U(i,e,t);const a=r[i]??{};if(t.through!==void 0){s.push(await x(i,t,a,o));continue}const d=o.canPushExists?.(t)??!1;if(d&&o.existsPushMode==="always"){s.push(await O(i,t,a,n,o));continue}const c=await X(i,t,a,o,d);c===m?s.push(await O(i,t,a,n,o)):s.push(c)}return C(s)},J=async(e,t,r,n)=>{if(e==="AND"||e==="OR"){const s=[];for(const i of y(t))s.push(await u(i,r,n));return{[e]:s}}if(e==="NOT")return{NOT:await u(t??{},r,n)};const o=n.schema.tables[r]?.relationMap?.[e];return o&&b(t)?V(e,o,t,r,n):{[e]:t}},u=async(e,t,r)=>{const n=[];for(const o of Object.keys(e))n.push(await J(o,e[o],t,r));return C(n)},G=async(e,t)=>!e||!f(e,t.schema,t.tableName)?e:u(e,t.tableName,{canPushExists:t.canPushExists,existsPushMode:t.existsPushMode??"auto",fetcher:t.fetcher,maxRelationKeys:t.maxRelationKeys??q,relationBaseWhere:t.relationBaseWhere,schema:t.schema}),A=100,h=e=>{if(e===void 0)return 0;let t=0;for(const[r,n]of Object.entries(e))r==="AND"||r==="OR"?t+=n.reduce((o,s)=>o+h(s),0):r==="NOT"?t+=h(n):typeof n=="object"&&n!==null?t+=Object.keys(n).filter(o=>o!=="isNull").length:t+=1;return t},ce=async(e,t,r)=>{const n=P(t.orderBy,e.shape,{pinned:D(t.where),uniqueBy:_(e.indexes,e.shape)}),o=typeof t.cursor=="string"?K(n,E(t.cursor)):void 0,s=typeof t.endCursor=="string"?B(n,E(t.endCursor)):void 0;if(s!==void 0&&h(o)+h(s)>A)throw new l("BAD_REQUEST",`findMany: an endCursor read with this orderBy binds ${String(h(o)+h(s))} cursor parameters, and a statement takes at most ${String(A)} — order by fewer fields`);let i=w(t.baseWhere,t.where);i=w(i,I(e.softDeleteMode,t.includeDeleted)),i=await G(i,{...r,relationBaseWhere:t.relationBaseWhere});for(const d of[o,s])d&&(i=i?{AND:[i,d]}:d);const a=typeof t.limit=="number"?Math.max(0,Math.floor(t.limit)):void 0;return{fetchLimit:a===void 0?void 0:a+1,limit:a,orderKeys:n,predicate:i}},le=(e,t)=>{const{endCursor:r,limit:n,omitContinueCursor:o,orderKeys:s}=t,i=n!==void 0&&e.length>n,a=i?e.slice(0,n):e;if(typeof r=="string"){let c;return a.length>=2?c=a[Math.floor(a.length/2)-1]:i&&([c]=a),{continueCursor:r,isDone:!0,page:a,splitCursor:c&&o!==!0?R(c,s):null,...i?{splitRequired:!0}:{}}}const d=a.at(-1);return{continueCursor:i&&d&&o!==!0?R(d,s):null,isDone:!i,page:a}},g=(e,t,r)=>{for(const n of e){const o=M(n,t,r);if(o)return o}},Z=(e,t,r,n)=>{if(e==="AND"||e==="OR")return g(y(t),r,n);if(e==="NOT")return g([t??{}],r,n);const o=r.tables[n]?.relationMap?.[e];if(!o||!b(t))return;const s=o.through===void 0?[o.table]:[o.table,o.through.table],i=s.find(d=>r.tables[d]?.shardMode?.kind==="shardBy");if(i!==void 0)return{kind:"shard",relation:e,target:i};const a=s.find(d=>N(r.tables[d]));return a!==void 0?{kind:"memory",relation:e,target:a}:g(Object.values(t),r,o.table)},M=(e,t,r)=>{for(const n of Object.keys(e)){const o=Z(n,e[n],t,r);if(o)return o}},ee=(e,t,r)=>{if(!(t.tables[r]?.shardMode?.kind==="global"||!f(e,t,r)))throw Object.assign(new Error(`shape on "${r}" filters by a relation, which a shard-local shape cannot replicate: its seed and membership probe read "${r}" alone, so the relation never matches, and a write that only touches the related table never moves the shape. Fix it by (a) denormalizing the related columns into "${r}" and filtering on those, (b) moving "${r}" to .global() so it is served through the latency-tiered D1 shape tier, or (c) reading it through a live query (\`useQuery\`), which does resolve relations.`),{code:"SHAPE_RELATION_PREDICATE",name:"LunoraError",status:400})},he=(e,t,r)=>{if(N(t.tables[r]))throw Object.assign(new Error(`shape on "${r}" replicates from the changelog, which never records a .memory() table — the shape would seed once and never update again. Fix it by (a) dropping .memory() from "${r}" so its writes reach the changelog, or (b) reading it through a live query (\`useQuery\`), which refreshes off the changed-table set rather than the log.`),{code:"SHAPE_MEMORY_TABLE",name:"LunoraError",status:400});if(!e)return;const n=M(e,t,r);if(!n){ee(e,t,r);return}throw n.kind==="memory"?Object.assign(new Error(`shape on "${r}" joins the .memory() table "${n.target}" via relation "${n.relation}" — writes to a .memory() table never reach the changelog, so the shape is never told its membership changed and would serve stale rows indefinitely. Fix it by (a) dropping .memory() from "${n.target}", or (b) reading it through a live query (\`useQuery\`), which refreshes off the changed-table set rather than the log.`),{code:"SHAPE_MEMORY_TABLE",name:"LunoraError",status:400}):Object.assign(new Error(`shape on "${r}" joins the sharded table "${n.target}" via relation "${n.relation}" — a live shape cannot replicate rows that live in another shard's Durable Object. Fix it by (a) denormalizing the joined columns into "${r}", or (b) moving "${n.target}" to .global() so it is served through the latency-tiered D1 shape tier.`),{code:"SHAPE_CROSS_SHARD_JOIN",name:"LunoraError",status:400})};export{q as DEFAULT_MAX_RELATION_KEYS,de as assertFlatPredicate,he as assertShapeShardable,ce as composeReadPredicate,f as containsRelationPredicate,le as findManyPage,b as isRelationPredicate,G as resolveRelationPredicates};
1
+ import{LunoraError as l}from"@lunora/errors";import{i as j,R as k}from"./relation-operators-BEg-CvCH.mjs";import{mergeWhere as w}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{isMemoryTable as N}from"./clearMemoryTables-aMRERF0w.mjs";import{normalizeOrderKeys as P,uniqueIndexFields as _,equalityPinnedFields as D,buildSeekWhere as K,decodeCursor as E,buildSeekBeforeWhere as B,softDeleteScope as I,encodeCursor as R}from"./CURSOR_PREFIX-rOdoinP8.mjs";import{distinctValues as T}from"./applyInsertDefaults-BJ4dP3OL.mjs";import{RELATION_EXISTS_KEY as W}from"./RELATION_EXISTS_KEY-wxgj6rSL.mjs";const $={every:{kind:"many",negateChild:!0,negated:!0},is:{kind:"one",negated:!1},isNot:{kind:"one",negated:!0,nullDisjunct:!0},none:{kind:"many",negated:!0},some:{kind:"many",negated:!1}},S=e=>k.has(e)?e:void 0,p=e=>{const t=S(e),r=t===void 0?void 0:$[t];if(!r)throw new l("INTERNAL",`unknown relation operator "${e}"`);return r},F=e=>e.kind==="one"?{clause:e.field,project:e.references}:{clause:e.references,project:e.field},q=5e3,m=Symbol("relation-key-overflow"),y=e=>Array.isArray(e)?e.map(t=>t??{}):[],C=e=>{if(e.length===1){const[t]=e;return t??{}}return e.length===0?{}:{AND:e}},b=e=>j(e),f=(e,t,r)=>{const n=t.tables[r]?.relationMap??{};return Object.keys(e).some(o=>{const s=e[o];return o==="AND"||o==="OR"?y(s).some(i=>f(i,t,r)):o==="NOT"?f(s??{},t,r):!!n[o]&&b(s)})},de=(e,t,r,n)=>{if(e&&f(e,t,r))throw new l("INTERNAL",`relation-crossing predicates are not supported in ${n}() — use them in findMany/findFirst or an RLS read policy`)},H=async(e,t,r,n)=>{const o=await u(t,e.table,n),{page:s}=await n.fetcher(e.table,{baseWhere:n.relationBaseWhere?.(e.table),relationBaseWhere:n.relationBaseWhere,where:o});return T(s,r)},z=(e,t,r)=>{throw new l("INTERNAL",`relation predicate on "${e.table}" matched ${String(t)} rows, exceeding the ${String(r.maxRelationKeys)}-key limit; narrow the predicate (a same-shard EXISTS push-down lifts this cap)`)},Y=(e,t,r)=>{throw new l("INTERNAL",`relation predicate on "${e.table}" matched at least ${String(t)} distinct keys, exceeding the ${String(r.maxRelationKeys)}-key limit; narrow the predicate`)},Q=async(e,t,r,n,o)=>{const s=await H(e,t,r,n);return s.length<=n.maxRelationKeys?s:o?m:z(e,s.length,n)},v=async(e,t,r,n)=>{const o=await u(t,e.table,n),s=n.maxRelationKeys+1,i=new Set;let a;for(;;){const d=await n.fetcher(e.table,{baseWhere:n.relationBaseWhere?.(e.table),cursor:a,limit:s,relationBaseWhere:n.relationBaseWhere,where:o});if(d.page.length>s)throw new l("INTERNAL",`relation predicate on "${e.table}" read ${String(d.page.length)} rows for a page of at most ${String(s)}; the fetcher did not honour the page limit`);for(const c of T(d.page,r))i.add(c);if(i.size>n.maxRelationKeys&&Y(e,i.size,n),d.isDone)return[...i];if(typeof d.continueCursor!="string")throw new l("INTERNAL",`relation predicate on "${e.table}" returned a page that is not final but has no cursor to continue from`);if(d.continueCursor===a)throw new l("INTERNAL",`relation predicate on "${e.table}" paged with a cursor that did not advance`);a=d.continueCursor}},X=async(e,t,r,n,o)=>{const s=p(e),{clause:i,project:a}=F(t),d=await Q(t,s.negateChild?{NOT:r}:r,a,n,o);return d===m?m:s.negated?s.nullDisjunct?{OR:[{[i]:{notIn:d}},{[i]:{isNull:!0}}]}:{[i]:{notIn:d}}:{[i]:{in:d}}},x=async(e,t,r,n)=>{const o=p(e),{from:s,table:i,to:a}=t.through,d=await v(t,o.negateChild?{NOT:r}:r,"_id",n),c=d.length===0?[]:await v({table:i},{[a]:{in:d}},s,n);return{_id:o.negated?{notIn:c}:{in:c}}},O=async(e,t,r,n,o)=>{const s=p(e),i=o.relationBaseWhere?.(t.table),a=s.negateChild?{NOT:r}:r,L={childWhere:await u(i?{AND:[i,a]}:a,t.table,o),negated:s.negated,parentTable:n,relation:t};return{[W]:L}},U=(e,t,r)=>{const n=S(e),o=n===void 0?void 0:$[n];if(o&&o.kind!==r.kind)throw new l("INTERNAL",`relation operator "${e}" requires a to-${o.kind} relation, but "${t}" is to-${r.kind}`)},V=async(e,t,r,n,o)=>{const s=[];for(const i of Object.keys(r)){U(i,e,t);const a=r[i]??{};if(t.through!==void 0){s.push(await x(i,t,a,o));continue}const d=o.canPushExists?.(t)??!1;if(d&&o.existsPushMode==="always"){s.push(await O(i,t,a,n,o));continue}const c=await X(i,t,a,o,d);c===m?s.push(await O(i,t,a,n,o)):s.push(c)}return C(s)},J=async(e,t,r,n)=>{if(e==="AND"||e==="OR"){const s=[];for(const i of y(t))s.push(await u(i,r,n));return{[e]:s}}if(e==="NOT")return{NOT:await u(t??{},r,n)};const o=n.schema.tables[r]?.relationMap?.[e];return o&&b(t)?V(e,o,t,r,n):{[e]:t}},u=async(e,t,r)=>{const n=[];for(const o of Object.keys(e))n.push(await J(o,e[o],t,r));return C(n)},G=async(e,t)=>!e||!f(e,t.schema,t.tableName)?e:u(e,t.tableName,{canPushExists:t.canPushExists,existsPushMode:t.existsPushMode??"auto",fetcher:t.fetcher,maxRelationKeys:t.maxRelationKeys??q,relationBaseWhere:t.relationBaseWhere,schema:t.schema}),A=100,h=e=>{if(e===void 0)return 0;let t=0;for(const[r,n]of Object.entries(e))r==="AND"||r==="OR"?t+=n.reduce((o,s)=>o+h(s),0):r==="NOT"?t+=h(n):typeof n=="object"&&n!==null?t+=Object.keys(n).filter(o=>o!=="isNull").length:t+=1;return t},ce=async(e,t,r)=>{const n=P(t.orderBy,e.shape,{pinned:D(t.where),uniqueBy:_(e.indexes,e.shape)}),o=typeof t.cursor=="string"?K(n,E(t.cursor)):void 0,s=typeof t.endCursor=="string"?B(n,E(t.endCursor)):void 0;if(s!==void 0&&h(o)+h(s)>A)throw new l("BAD_REQUEST",`findMany: an endCursor read with this orderBy binds ${String(h(o)+h(s))} cursor parameters, and a statement takes at most ${String(A)} — order by fewer fields`);let i=w(t.baseWhere,t.where);i=w(i,I(e.softDeleteMode,t.includeDeleted)),i=await G(i,{...r,relationBaseWhere:t.relationBaseWhere});for(const d of[o,s])d&&(i=i?{AND:[i,d]}:d);const a=typeof t.limit=="number"?Math.max(0,Math.floor(t.limit)):void 0;return{fetchLimit:a===void 0?void 0:a+1,limit:a,orderKeys:n,predicate:i}},le=(e,t)=>{const{endCursor:r,limit:n,omitContinueCursor:o,orderKeys:s}=t,i=n!==void 0&&e.length>n,a=i?e.slice(0,n):e;if(typeof r=="string"){let c;return a.length>=2?c=a[Math.floor(a.length/2)-1]:i&&([c]=a),{continueCursor:r,isDone:!0,page:a,splitCursor:c&&o!==!0?R(c,s):null,...i?{splitRequired:!0}:{}}}const d=a.at(-1);return{continueCursor:i&&d&&o!==!0?R(d,s):null,isDone:!i,page:a}},g=(e,t,r)=>{for(const n of e){const o=M(n,t,r);if(o)return o}},Z=(e,t,r,n)=>{if(e==="AND"||e==="OR")return g(y(t),r,n);if(e==="NOT")return g([t??{}],r,n);const o=r.tables[n]?.relationMap?.[e];if(!o||!b(t))return;const s=o.through===void 0?[o.table]:[o.table,o.through.table],i=s.find(d=>r.tables[d]?.shardMode?.kind==="shardBy");if(i!==void 0)return{kind:"shard",relation:e,target:i};const a=s.find(d=>N(r.tables[d]));return a!==void 0?{kind:"memory",relation:e,target:a}:g(Object.values(t),r,o.table)},M=(e,t,r)=>{for(const n of Object.keys(e)){const o=Z(n,e[n],t,r);if(o)return o}},ee=(e,t,r)=>{if(!(t.tables[r]?.shardMode?.kind==="global"||!f(e,t,r)))throw Object.assign(new Error(`shape on "${r}" filters by a relation, which a shard-local shape cannot replicate: its seed and membership probe read "${r}" alone, so the relation never matches, and a write that only touches the related table never moves the shape. Fix it by (a) denormalizing the related columns into "${r}" and filtering on those, (b) moving "${r}" to .global() so it is served through the latency-tiered D1 shape tier, or (c) reading it through a live query (\`useQuery\`), which does resolve relations.`),{code:"SHAPE_RELATION_PREDICATE",name:"LunoraError",status:400})},he=(e,t,r)=>{if(N(t.tables[r]))throw Object.assign(new Error(`shape on "${r}" replicates from the changelog, which never records a .memory() table — the shape would seed once and never update again. Fix it by (a) dropping .memory() from "${r}" so its writes reach the changelog, or (b) reading it through a live query (\`useQuery\`), which refreshes off the changed-table set rather than the log.`),{code:"SHAPE_MEMORY_TABLE",name:"LunoraError",status:400});if(!e)return;const n=M(e,t,r);if(!n){ee(e,t,r);return}throw n.kind==="memory"?Object.assign(new Error(`shape on "${r}" joins the .memory() table "${n.target}" via relation "${n.relation}" — writes to a .memory() table never reach the changelog, so the shape is never told its membership changed and would serve stale rows indefinitely. Fix it by (a) dropping .memory() from "${n.target}", or (b) reading it through a live query (\`useQuery\`), which refreshes off the changed-table set rather than the log.`),{code:"SHAPE_MEMORY_TABLE",name:"LunoraError",status:400}):Object.assign(new Error(`shape on "${r}" joins the sharded table "${n.target}" via relation "${n.relation}" — a live shape cannot replicate rows that live in another shard's Durable Object. Fix it by (a) denormalizing the joined columns into "${r}", or (b) moving "${n.target}" to .global() so it is served through the latency-tiered D1 shape tier.`),{code:"SHAPE_CROSS_SHARD_JOIN",name:"LunoraError",status:400})};export{q as DEFAULT_MAX_RELATION_KEYS,de as assertFlatPredicate,he as assertShapeShardable,ce as composeReadPredicate,f as containsRelationPredicate,le as findManyPage,b as isRelationPredicate,G as resolveRelationPredicates};
@@ -0,0 +1 @@
1
+ import{LunoraError as $}from"@lunora/errors";import{q as $t}from"./MAX_TOKEN_LENGTH-iFEGEcDL-DBPC6ZWl.mjs";import{S as qn,l as qe,s as Pn}from"./fts-companion-CE3EmIjk.mjs";import{decodeWire as Un,stableWireKey as Pt}from"@lunora/wire";import{sql as a}from"drizzle-orm";import{throwingScheduler as On,aggregateSqlFunction as Pe,normalizeCountArgument as Gn}from"./AGGREGATE_SQL_FUNCTION-C_ZipS9R.mjs";import{aggregateTableName as rt,encodeAggregateKey as it,readAggregateValue as st}from"./aggregateTableName-B_CtIQCS.mjs";import{mergeWhere as Q,CountRlsUnsupportedError as ct,selectIndexForGroupBy as jn,selectIndexForCount as Hn,selectIndexForAggregate as Kn}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{backfillSearchIndexesForTable as Nn,searchIndexCoversTable as Qn}from"./backfillAggregateIndexes-BwCpPW7h.mjs";import{backfillAggregateIndexes as ji,backfillRankIndexes as Hi,backfillSearchIndexes as Ki}from"./backfillAggregateIndexes-BwCpPW7h.mjs";import{appendCdcChange as Vn,readCdcDocAtOrBefore as Jn}from"./CDC_LOG_TABLE-BFGgqai8.mjs";import{CDC_LOG_TABLE as Qi,applyCdcChanges as Vi,bumpCdcEpoch as Ji,cdcCanVouchFor as zi,cdcForkedError as Yi,cdcSeqLeavingRows as Xi,cdcTouchesTables as Zi,cdcTrimmedError as es,compactCdcDocs as ts,cursorBelowRetainedFloor as ns,minCdcReplayableSeq as os,minCdcSeq as rs,readCdcChangeKeys as is,readCdcChanges as ss,readCdcCursor as cs,readCdcEpoch as as,trimCdcChanges as ds}from"./CDC_LOG_TABLE-BFGgqai8.mjs";import{allocateCommitSeq as zn,COMMIT_SEQ_FIELD as Yn}from"./COMMIT_SEQ_FIELD-Da1DjGqo.mjs";import{createCompanionSync as Xn}from"./createCompanionSync-DO92CQek.mjs";import{isMemoryTable as Ut}from"./clearMemoryTables-aMRERF0w.mjs";import{computeRankPage as Ot}from"./computeRankPage-B6umzbg4.mjs";import{SCAN_DEP as G,PRIMARY_READ as Zn}from"./SCAN_DEP-B4Uu4g7l.mjs";import{runSql as he,runDrizzle as K}from"./runDrizzle-RC09zZrh.mjs";import{p as eo,j as ht,D as ie,r as xe,W as to,k as le,b as Ue,A as at,a as Oe,m as ue,e as fe,s as no,t as oo,u as ro,i as io,q as Gt,h as pn,g as so}from"./do-sql-105TONaE.mjs";import{renderSql as gn,unionAll as yn,WORKERD_SQLITE_LIMITS as mn}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{a as co,u as ao}from"./estimate-bytes-C-C35VXL.mjs";import{coveringGeohashes as lo,boundingBoxGeohashes as uo,haversineMeters as fo,pointInBoundingBox as ho}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{NotFoundError as wo}from"./NotFoundError-BhF7FeFr.mjs";import{resolvePatch as po,assertPatchAllowed as go,operatorFields as yo,readPatchField as jt}from"./assertPatchAllowed-CA_H466g.mjs";import{tiebreakDirectionFor as mo,encodeCursor as wt,nullsOrderSuffix as Eo,normalizeOrderKeys as Ht,uniqueIndexFields as $o,buildSeekWhere as Ro,decodeCursor as Kt,buildSeekBeforeWhere as So,softDeleteScope as Ae,applySelect as En}from"./CURSOR_PREFIX-rOdoinP8.mjs";import{rankTableName as Nt,sortColumnName as Qt,resolveRankPartition as vo,encodePartitionKey as _o,RANK_TIEBREAK as To,rankPivotConditionSql as Ao}from"./RANK_TIEBREAK-D3ye2GsL.mjs";import{UNVOUCHABLE_DEP as Vt}from"./UNVOUCHABLE_DEP-Ds9gxVqs.mjs";import{idIndexKey as Io,withUnknownIndexKeys as xo,indexKeysForRow as bo,buildIndexRange as Co}from"./buildIndexRange-BTChxh3k.mjs";import{r as Qe,j as be,c as Z,t as ze,i as Jt}from"./where-sql-BjY4rnqb.mjs";import{serializeSqlValue as Ce}from"./serializeSqlValue-DeoBMpZ2.mjs";import{quoteIdentifier as Me}from"./quoteIdentifier-CObIFRhb.mjs";import{whereOfFilter as Mo,isPushableWhere as Do}from"./isPushableWhere-BeYAOjUb.mjs";import{deriveRelationEdges as ko,findRelated as Lo}from"./RELATED_DEFAULT_LIMIT-CAh3WUMn.mjs";import{assertFlatPredicate as dt,findManyPage as Fo,resolveRelationPredicates as Bo,composeReadPredicate as Wo}from"./DEFAULT_MAX_RELATION_KEYS-B_BOc9w_.mjs";import{describeRelationWrites as qo}from"./describeRelationWrites-omar6-u9.mjs";import{runRowValidators as Ge,transformOnlyDefinition as Po,applyInsertDefaults as pt,resolveWith as Uo,relationHooks as Oo,applyOnDelete as Go,fanOutScalarCounts as jo}from"./applyInsertDefaults-BJ4dP3OL.mjs";import{guardWriter as Ho}from"./RLS_UNWRAP_SYMBOL-CZIpCjzt.mjs";import{mayHoldProjectedValue as Ko}from"./BIGINT_KEY_DIGITS-DE6yshOt.mjs";import{createSystemReader as No}from"./createSystemReader-BSCxr8Qs.mjs";import{ConflictError as se}from"./ConflictError-C8GtJmjS.mjs";import{hasTrigger as zt,runTriggers as Qo}from"./hasTrigger-CjlwI4le.mjs";import{advanceClientWatermark as us,migrateClientWatermark as fs,readClientWatermark as hs}from"./CLIENT_WATERMARK_TABLE-De7z_OHV.mjs";import{IDEMPOTENCY_TABLE as ps,readIdempotent as gs,trimIdempotent as ys,writeIdempotent as ms}from"./IDEMPOTENCY_TABLE-COrgeP3O.mjs";import{runShardMigrations as $s}from"./runShardMigrations-Bc7PsQhM.mjs";import{selectShapeMembers as Ss,selectShapeRows as vs}from"./selectShapeMembers-Dqx_m7BF.mjs";const Vo=n=>{const r=atob(n),o=Uint8Array.from(r,s=>s.codePointAt(0)??0);return new TextDecoder().decode(o)},Jo=()=>new $("INVALID_CURSOR","invalid cursor"),Yt=16,Xt=8,z=1024,Rt=(n,r)=>r.query(n),zo=(n,r)=>{if(n.length===0)return 0;let o=0;for(const[s,c]of r.entries()){const u=s===r.length-1;let g=0;for(const E of n)(u?E.startsWith(c):E===c)&&(g+=1);if(g===0)return 0;o+=g}return o},Yo=(n,r)=>{if(!r)return{exact:!0,lower:n,upper:n};const o=[...n].at(-1)??"",s=(o.codePointAt(0)??0)+1;if(s>=55296&&s<=57343||s>1114111)return{exact:!0,lower:n,upper:n};const c=n.slice(0,n.length-o.length);return{exact:!1,lower:n,upper:c+String.fromCodePoint(s)}},Xo=(n,r,o)=>{const s={eq:(c,u)=>{if(!n.definition.filterFields?.includes(c))throw new $("INTERNAL",`field "${c}" is not a filter field of search index "${n.indexName}" on table "${r}"`);if(n.filters.length>=Xt)throw new $("BAD_REQUEST",`search index "${n.indexName}" on table "${r}": at most ${String(Xt)} .eq() filters are supported per search query`);return n.filters.push({field:c,value:u}),s},search:(c,u)=>{const g=n;if(c!==g.definition.field)throw new $("INTERNAL",`search index "${g.indexName}" on table "${r}" indexes "${g.definition.field}", not "${c}"`);const E=Rt(u,o).length;if(E>Yt)throw new $("BAD_REQUEST",`search index "${g.indexName}" on table "${r}": at most ${String(Yt)} search terms are supported (got ${String(E)})`);return g.field=c,g.query=u,g.hasQuery=!0,s}};return s},Zo=n=>{if(n.length>z)throw new $("BAD_REQUEST",`more than ${String(z)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},er=n=>Math.min(n.offset+n.numItems+1,z),tr=n=>btoa(`search:${String(n)}`),nr=n=>{let r;try{r=Vo(n)}catch{return}if(!r.startsWith("search:"))return;const o=Number(r.slice(7));return Number.isInteger(o)&&o>=0?o:void 0},or=n=>{if(typeof n.endCursor=="string")throw new $("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");if(!Number.isFinite(n.numItems))throw new $("BAD_REQUEST",`search pagination needs a finite numItems, got ${String(n.numItems)}`);const r=Math.max(0,Math.floor(n.numItems)),o=n.cursor?nr(n.cursor):0;if(o===void 0)throw Jo();if(o+r>=z)throw new $("BAD_REQUEST",`search pagination reaches the ${String(z)}-document limit (offset ${String(o)} + ${String(r)} requested) — a page must end below the cap so the probe row that answers \`hasMore\` still fits: retry with numItems ${String(Math.max(1,z-o-1))} or fewer, or narrow the query or the filters instead`);return{numItems:r,offset:o}},rr=(n,r)=>{const o=r.offset+r.numItems,s=r.numItems>0&&n.length>o;return{continueCursor:s?tr(o):null,isDone:!s,page:n.slice(r.offset,o)}},ir=n=>{if(n===void 0)return z+1;if(!Number.isFinite(n))return z;const r=Math.max(0,Math.floor(n));if(r>z)throw new $("BAD_REQUEST",`search returns at most ${String(z)} documents (asked for ${String(r)}) — narrow the query or paginate instead`);return r},$n=500,Rn=(n,r,o)=>{if(n!==void 0&&n!==Number.POSITIVE_INFINITY&&(!Number.isInteger(n)||n<0))throw o(`${r}: batch limit must be a non-negative integer`);return n??$n},Sn=(n,r,o,s)=>{if(n>r)throw s(`${o}: batch of ${String(n)} exceeds the limit of ${String(r)} (raise options.limit or chunk the call)`)},sr=32,cr=1024,vn=(n,r,o,s)=>{const c=`SELECT id, _creationTime, ${Me(ie)} FROM ${Me(n)}`,u=`ORDER BY ${o}${s===void 0?"":` LIMIT ${String(s)}`}`;return r===void 0?Qe(`${c} ${u}`):be(`${c} WHERE `,r,` ${u}`)},Ye={fieldRef:n=>Qe(ht(n)),rangeTypeGuard:(n,r)=>Qe(eo(n,r)),serialize:Ce},ar=n=>n===void 0?"":Eo(n==="first"),_n=n=>{const r=n.map(o=>`${ht(o.field)} ${o.direction==="desc"?"DESC":"ASC"}${ar(o.nulls)}`);return n.some(o=>o.field==="_id"||o.field==="id")||r.push(`${ht("id")} ${mo(n)==="desc"?"DESC":"ASC"}`),r.join(", ")},dr={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},Tn=n=>new Set(n.sqlConditions.filter(r=>r.comparator==="=").map(r=>r.field)),lr=n=>{const r=Tn(n);let o=0;for(;o<n.indexFields.length&&r.has(n.indexFields[o]??"");)o+=1;return n.indexFields.slice(o)},ur=(n,r)=>{const o=n.order,s=lr(n),{shape:c}=r;return s.length>0?Ht(s.map(u=>({[u]:o})),c,{pinned:Tn(n),uniqueBy:$o(r.indexes,c)}):Ht([{_creationTime:o}],c)},fr=(n,r,o,s)=>{const c=n.sqlConditions.map(u=>({[u.field]:{[dr[u.comparator]??"eq"]:u.value}}));if(o&&c.push(Ro(r,Kt(o))),s&&c.push(So(r,Kt(s))),c.length!==0)return c.length===1?c[0]:{AND:c}},hr=n=>{if(n.want!==void 0)return n.selective?Math.max(n.want,sr):n.want},gt=(n,r,o,s,c,u,g)=>{const E=ur(s,o),y=_n(E),d=[],{filters:b,want:_}=u;let v=u.cursor??void 0,x=hr(u);if(_===0)return{documents:d,orderKeys:E};for(;;){const W=Z(fr(s,E,v,u.endCursor),Ye,ze),q=vn(r,c&&W?be(W," AND ",c):c??W,y,x),B=he(n,q.text,...q.params).toArray();let U={};g(B.length);for(const j of B)if(U=xe(j),b.every(ee=>ee(U))&&d.push(U)===_)return{documents:d,orderKeys:E};if(x===void 0||B.length<x)return{documents:d,orderKeys:E};v=wt(U,E),x=Math.max(x,Math.min(x*2,cr))}},wr=(n,r,o,s,c,u,g,E)=>{const y=Math.max(0,Math.floor(c.numItems));if(typeof c.endCursor=="string"){const{documents:W,orderKeys:q}=gt(n,r,o,s,u,{cursor:c.cursor,endCursor:c.endCursor,filters:g.all,selective:g.selective,want:void 0},E),B=W.length>=2?W[Math.floor(W.length/2)-1]:void 0;return{continueCursor:c.endCursor,isDone:!0,page:W,splitCursor:B?wt(B,q):null}}const{documents:d,orderKeys:b}=gt(n,r,o,s,u,{cursor:c.cursor,filters:g.all,selective:g.selective,want:y+1},E),_=d.length>y,v=_?d.slice(0,y):d,x=v.at(-1);return{continueCursor:_&&x?wt(x,b):null,isDone:!_,page:v}},Xe=n=>{const r=new Map;return o=>{const s=r.get(o);if(s!==void 0)return s;const c=n(Me(o));return r.set(o,c),c}},we=Me(ie),pr=Xe(n=>`INSERT INTO ${n} (id, _creationTime, ${we}) VALUES (?, ?, ?)`),Zt=Xe(n=>`UPDATE ${n} SET ${we} = ? WHERE id = ? AND ${we} = ?`),gr=Xe(n=>`UPDATE ${n} SET _creationTime = ?, ${we} = ? WHERE id = ? AND ${we} = ?`),yr=Xe(n=>`DELETE FROM ${n} WHERE id = ? AND ${we} = ?`),mr="SELECT changes() AS changed",en=new Map,Er="",$r=n=>{const r=JSON.stringify(n),o=en.get(r);if(o!==void 0)return o;const s=n.map(u=>a`SELECT ${a.raw(`'${u.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${a.identifier(ie)} FROM ${a.identifier(u)} WHERE id = ${Er}`),{sql:c}=gn("sqlite",a`${yn(s)} LIMIT 1`);return en.set(r,c),c},Rr=(n,r)=>r.map(()=>n),Sr=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,vr=n=>{if(!Sr.test(n))throw new $("INTERNAL",`invalid clientId ${JSON.stringify(n)}: a client-supplied row id must be a UUID`)},yt=n=>{if(n.includes("\0"))throw new $("BAD_REQUEST",`invalid row id ${JSON.stringify(n)}: a row id cannot hold a NUL character (U+0000)`)},_r=(n,r,o,s)=>{if(o!==!0)return;const c=n!==void 0&&"serverDefault"in(n.shape._id?._meta?.column??{});for(const u of r){const g=c?pt(n,u,s)._id:u._id;typeof g=="string"&&yt(g)}},tn=50,je=Math.floor(mn.boundParams/3),nn=mn.boundParams,Tr=128,Ve=n=>new $("BATCH_LIMIT_EXCEEDED",n,{status:400}),He=(n,r,o)=>{Sn(n,Rn(r,o,Ve),o,Ve)},on=async(n,r,o,s,c)=>{const u=Rn(s,c,Ve),{page:g}=await n.findMany(r,Number.isFinite(u)?{limit:u+1,omitContinueCursor:!0,where:o}:{where:o});return g.length>u&&Sn(Math.max(await n.count(r,{where:o}),g.length),u,c,Ve),g},Ar=n=>{const r={eq:(o,s)=>(n.sqlConditions.push({comparator:"=",field:o,value:s}),r),gt:(o,s)=>(n.sqlConditions.push({comparator:">",field:o,value:s}),r),gte:(o,s)=>(n.sqlConditions.push({comparator:">=",field:o,value:s}),r),lt:(o,s)=>(n.sqlConditions.push({comparator:"<",field:o,value:s}),r),lte:(o,s)=>(n.sqlConditions.push({comparator:"<=",field:o,value:s}),r)};return r},Ir=n=>Math.max(n,z),An=(n,r)=>{const o=n.filters.map(s=>a`${fe(s.field)} = ${Ce(s.value)}`);return r&&o.push(r),o},xr=(n,r,o,s,c)=>{const u=Rt(o.query,$t(o.definition.language));if(u.length===0)return[];const g=qn(r,o.indexName),E=`${g}__vocab`,y=u.length-1,d=u.map((q,B)=>{const U=Yo(q,B===y),j=U.exact?a`${a.identifier("term")} = ${U.lower}`:a`${a.identifier("term")} >= ${U.lower} AND ${a.identifier("term")} < ${U.upper}`;return a`SELECT ${a.identifier("doc")}, ${a.raw(String(B))} AS ${a.identifier("__term__")}, COUNT(*) AS ${a.identifier("__n__")} FROM ${a.identifier(E)} WHERE ${j} GROUP BY ${a.identifier("doc")}`}),b=u.map((q,B)=>a`SUM(CASE WHEN u.${a.identifier("__term__")} = ${a.raw(String(B))} THEN u.${a.identifier("__n__")} ELSE 0 END)`),_=a`SELECT f.${a.identifier(qe)} AS ${a.identifier(qe)}, ${a.join(b,a` + `)} AS ${a.identifier("__score__")} FROM (${yn(d)}) u JOIN ${a.identifier(g)} f ON f.rowid = u.${a.identifier("doc")} GROUP BY f.${a.identifier(qe)} HAVING ${a.join(b.map(q=>a`${q} > 0`),a` AND `)}`,v=An(o,c);let x=a`SELECT m.id, m._creationTime, m.${a.identifier(ie)}, s.${a.identifier("__score__")} AS ${a.identifier("__score__")} FROM (${_}) s JOIN ${a.identifier(r)} m ON m.id = s.${a.identifier(qe)}`;v.length>0&&(x=a`${x} WHERE ${a.join(v,a` AND `)}`),x=a`${x} ORDER BY s.${a.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${a.raw(String(s))}`;const W=[];for(const q of K(n,x)){const B=pn(q);if(B){const U=q.__score__;W.push({document:B,score:typeof U=="number"?U:Number(U??0)})}}return W},br=(n,r,o,s,c)=>{const u=$t(o.definition.language),g=Rt(o.query,u);if(g.length===0)return[];const E=An(o,c);let y=a`SELECT id, _creationTime, ${a.identifier(ie)} FROM ${a.identifier(r)}`;E.length>0&&(y=a`${y} WHERE ${a.join(E,a` AND `)}`),y=a`${y} ORDER BY _creationTime DESC, id ASC LIMIT ${a.raw(String(Ir(s)))}`;const d=K(n,y).toArray(),b=[];for(const _ of d){const v=pn(_);if(!v)continue;const x=zo(Pn(v,o.definition),g);x>0&&b.push({creationTime:typeof v._creationTime=="number"?v._creationTime:0,doc:v,id:typeof v._id=="string"?v._id:"",score:x})}return b.sort((_,v)=>v.score-_.score||v.creationTime-_.creationTime||_.id.localeCompare(v.id)),b.slice(0,s).map(_=>({document:_.doc,score:_.score}))},lt=(n,r,o,s)=>{if(!Number.isFinite(n.lat)||n.lat<-90||n.lat>90||!Number.isFinite(n.lng)||n.lng<-180||n.lng>180)throw new $("BAD_REQUEST",`geo index "${s}" on table "${o}": ${r} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},Cr=(n,r)=>{const o=n,s={near:(c,u)=>{if(o.within)throw new $("INTERNAL",`geo index "${o.indexName}" on table "${r}": call .near() or .within(), not both`);if(lt(c,".near() point",r,o.indexName),!Number.isFinite(u)||u<=0)throw new $("BAD_REQUEST",`geo index "${o.indexName}" on table "${r}": .near() radiusMeters must be a finite number > 0, got ${String(u)}`);return o.near={point:{lat:c.lat,lng:c.lng},radiusMeters:u},s},within:c=>{if(o.near)throw new $("INTERNAL",`geo index "${o.indexName}" on table "${r}": call .near() or .within(), not both`);if(lt(c.sw,".within() sw corner",r,o.indexName),lt(c.ne,".within() ne corner",r,o.indexName),c.sw.lat>c.ne.lat)throw new $("BAD_REQUEST",`geo index "${o.indexName}" on table "${r}": .within() corners are transposed (sw.lat > ne.lat)`);if(c.sw.lng>c.ne.lng)throw new $("BAD_REQUEST",`geo index "${o.indexName}" on table "${r}": .within() box crosses the antimeridian (sw.lng > ne.lng), which is not supported — split it into two boxes at ±180 and union the results`);return o.within={ne:{lat:c.ne.lat,lng:c.ne.lng},sw:{lat:c.sw.lat,lng:c.sw.lng}},s}};return s},Mr=(n,r)=>{const o=n[r];if(o===null||typeof o!="object")return;const{lat:s,lng:c}=o;return typeof s=="number"&&typeof c=="number"?{lat:s,lng:c}:void 0},Dr=(n,r)=>{const o=Mr(n,r.definition.field);if(!o)return;const s=typeof n._creationTime=="number"?n._creationTime:0;if(r.near){const c=fo(r.near.point,o);return c<=r.near.radiusMeters?{creationTime:s,distance:c}:void 0}return ho(o,r.within)?{creationTime:s,distance:0}:void 0},kr=(n,r,o,s)=>{if(!o.near&&!o.within)throw new $("INTERNAL",`geo index "${o.indexName}" on table "${r}": call .near(point, radius) or .within(box)`);const c=o.near?lo(o.near.point,o.near.radiusMeters):uo(o.within),u=so(r,o.indexName),g=c.map(_=>a`(g.${a.identifier("__geohash__")} >= ${_} AND g.${a.identifier("__geohash__")} < ${`${_}{`})`),E=[a`(${a.join(g,a` OR `)})`];s&&E.push(s);const y=a`SELECT m.id, m._creationTime, m.${a.identifier(ie)} FROM ${a.identifier(u)} g JOIN ${a.identifier(r)} m ON m.id = g.${a.identifier("__id__")} WHERE ${a.join(E,a` AND `)}`,d=K(n,y).toArray(),b=[];for(const _ of d){const v=xe(_),x=v?Dr(v,o):void 0;v&&x&&b.push({creationTime:x.creationTime,distance:x.distance,doc:v})}return b.sort((_,v)=>_.distance-v.distance||v.creationTime-_.creationTime),b},In=(n,r,o,s)=>{const c=[];for(const u of n)if(r.every(g=>g(s(u)))&&(c.push(u),typeof o=="number"&&c.length>=o))break;return c},Lr=(n,r,o,s,c,u=()=>{})=>{const g=o.within!==void 0,E=kr(n,r,o,c).map(y=>({distanceMeters:g?null:y.distance,document:y.doc}));return u(E.length),typeof s=="number"?E.slice(0,Math.max(0,Math.floor(s))):E},rn=(n,r,o,s,c,u,g=()=>{})=>{const{geo:E}=o;if(!E)throw new $("INTERNAL","runGeoTerminalScored called without a staged geo query");const y=c.length>0,d=Lr(n,r,E,y?void 0:u,s,g);return y?In(d,c,u,b=>b.document):d},sn=(n,r,o)=>{const s=n.shape[r];if(s!==void 0&&Ko(s))throw new $("BAD_REQUEST",`${o}: "${r}" may hold an order-preserving key rather than a value SQL can reduce or group — declare an aggregateIndex covering this (by, field, op) so the maintained companion answers it instead (its running total is a REAL, so it stays exact only while the total is inside 2^53)`)},Fr=n=>{let r=0;const o=[],s={...Ye,relationExists:c=>{const{childWhere:u,negated:g,parentTable:E,relation:y}=c,d=`__rel_${String(r)}`,b=o.at(-1)??E;r+=1,n(y.table,G);const _=y.kind==="one"?y.field:y.references,v=y.kind==="one"?y.references:y.field,x=Qe(`${Gt(d,v)} = ${Gt(b,_)}`);o.push(d);const W=Z(u,s,ze);o.pop();const q=W===void 0?x:be(x," AND ",W),B=be("EXISTS (SELECT 1 FROM ",Jt(y.table)," AS ",Jt(d)," WHERE ",q,")");return g?be("NOT ",B):B}};return s};class Br extends ${constructor(r="unique() found more than one matching document"){super("NOT_UNIQUE",r,{name:"NotUniqueError"})}}const Wr=/\s/u,qr=String.fromCodePoint(0),cn=(n,r,o)=>{if(!n.tables[r])throw new $("INTERNAL",`unknown table: ${r}`);return typeof o!="string"||o.length===0||Wr.test(o)||o.includes(qr)?null:o},xn=(n,r,o,s=()=>{},c=()=>{},u=()=>{},g)=>{const E=r.tables[o];if(!E)throw new $("INTERNAL",`unknown table: ${o}`);const y=Ae(E.softDeleteMode,void 0),d=g??{indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[],verifyFilters:[]},b=()=>{const S=Q(y,d.pushedWhere);return S?Z(S,ue):void 0},_=()=>{const S=Q(y,d.pushedWhere);return S?Z(S,Ye,ze):void 0},v=()=>[...d.inMemoryFilters,...d.verifyFilters];let x=0;const W=S=>{const{search:M}=d;if(!M)throw new $("INTERNAL","runSearchFetch called without a staged search");Nn(ro(n),o,E);const L=d.inMemoryFilters.length>0,F=ir(L?void 0:S),k=io(n);if(k&&!Qn(n,o,M.definition))throw new $("SEARCH_INDEX_BUILDING",`search index "${M.indexName}" on table "${o}" is still backfilling and currently covers only part of the table — retry once it finishes, or run the backfillSearch admin operation to complete it now`);const pe=b(),te=k?xr(n,o,M,F,pe):br(n,o,M,F,pe);!L&&S===void 0&&Zo(te);const ge=v();return x=te.length,ge.length>0?In(te,ge,S,J=>J.document):te},q=S=>W(S).map(M=>M.document),B=S=>{const M=or(S);return rr(q(er(M)),M)},U=()=>{if(d.search||d.geo||d.indexName===void 0){c(void 0);return}c(Co(o,d.indexName,d.indexFields,d.sqlConditions,Ce))},j=S=>{U();let M=0;const L=(()=>{if(d.search){const F=q(S);return M=x,F}return d.geo?rn(n,o,d,b(),v(),S,F=>{M=F}).map(F=>F.document):gt(n,o,E,d,_(),{filters:v(),selective:d.inMemoryFilters.length>0,want:S===void 0?void 0:Math.max(0,Math.floor(S))},F=>{M+=F}).documents})();return u(Math.max(M,L.length)),L},ee=()=>{if(!d.search&&!d.geo)throw new $("INTERNAL",`ctx.db.query("${o}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);U();let S=0;const M=(()=>{if(d.search){const L=W(void 0);return S=x,L}return rn(n,o,d,b(),v(),void 0,L=>{S=L})})();return u(Math.max(S,M.length)),M},N={async*[Symbol.asyncIterator](){const S=xn(n,r,o,s,c,u,{...d,indexFields:[...d.indexFields],inMemoryFilters:[...d.inMemoryFilters],sqlConditions:[...d.sqlConditions],verifyFilters:[...d.verifyFilters]});if(d.search){yield*await S.collect();return}let M;for(;;){const L=await S.paginate({cursor:M??null,numItems:Tr});if(yield*L.page,L.isDone||L.continueCursor===null)return;M=L.continueCursor}},async collect(){return j(void 0)},async collectWithScores(){return ee()},filter(S){const M=Mo(S);return M!==void 0&&Do(M,E.shape)?(d.pushedWhere=Q(d.pushedWhere,M),d.verifyFilters.push(S)):d.inMemoryFilters.push(S),N},async first(){return j(1)[0]??null},order(S){return d.order=S==="desc"?"desc":"asc",N},async paginate(S){let M=0;if(U(),d.search){const F=B(S);return u(F.page.length),F}if(d.geo)throw new $("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const L=wr(n,o,E,d,S,_(),{all:v(),selective:d.inMemoryFilters.length>0},F=>{M+=F});return u(Math.max(M,L.page.length)),L},async take(S){return j(S)},async unique(){const S=j(2);if(S.length>1)throw new Br(`unique() on table "${o}" matched ${String(S.length)} documents; expected at most one`);return S[0]??null},withGeoIndex(S,M){const L=(E.geoIndexes??[]).find(k=>k.name===S);if(!L)throw new $("INTERNAL",`unknown geo index "${S}" on table "${o}"`);s(o,S,"geo");const F={definition:L,indexName:S};if(d.geo=F,M(Cr(F,o)),!F.near&&!F.within)throw new $("INTERNAL",`geo index "${S}" on table "${o}" requires a .near(point, radius) or .within(box) call`);return N},withIndex(S,M){const L=E.indexes.find(F=>F.name===S);if(!L)throw new $("INTERNAL",`unknown index "${S}" on table "${o}"`);return s(o,S,"index"),d.indexName=S,d.indexFields=L.fields,M&&M(Ar(d)),N},withSearchIndex(S,M){const L=(E.searchIndexes??[]).find(k=>k.name===S);if(!L)throw new $("INTERNAL",`unknown search index "${S}" on table "${o}"`);s(o,S,"search");const F={definition:L,field:L.field,filters:[],hasQuery:!1,indexName:S,query:""};if(d.search=F,M(Xo(F,o,$t(L.language))),!F.hasQuery)throw new $("INTERNAL",`search index "${S}" on table "${o}" requires a .search(field, query) call`);return N}};return N},ut=(n,r,o,s)=>{const c=o;for(const[u,g]of oo(n)){if(g.serverDefault){u in r&&(c[u]=g.serverDefault({auth:s}));continue}g.onUpdateFn&&!(u in r)&&(c[u]=g.onUpdateFn())}},an=5,dn=(n,r)=>{for(const o of Object.keys(r))if(r[o]===void 0)throw new $("INTERNAL",`Cannot ${n} field '${o}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},ln=["_commitSeq","_creationTime","_id"],Ke=n=>ln.some(r=>r in n)?Object.fromEntries(Object.entries(n).filter(([r])=>!ln.includes(r))):n,Pr=/unique constraint failed/i,Ur=n=>n instanceof Error&&Pr.test(n.message),Or=/string or blob too big/iu,Gr=(n,r)=>{if(!(!(n instanceof Error)||!Or.test(n.message)))throw new $("PAYLOAD_TOO_LARGE",`document is too large to store in "${r}": a single row cannot exceed the storage engine's per-row ceiling (2 MB on a Durable Object's SQLite). The limit is on the STORED bytes, which are UTF-8, and v.bytes()/v.bigint() columns are stored twice on a shard-local table. Keep the payload in R2 (ctx.storage) and store a reference on the row.`)},mt=(n,r,o,s)=>{try{he(n,o,...s)}catch(c){throw Ur(c)?new se(`unique constraint violation on "${r}"`,"unique"):(Gr(c,r),c)}},Ne=(n,r,o,s)=>{if(mt(n,r,o,s),he(n,mr).one().changed===0)throw new se(`optimistic concurrency conflict on "${r}" — the row changed during this mutation; refetch and retry`,"occ")},un=(n,r,o,s,c,u,g)=>{const E=[];for(let _=0;_<o.length+1;_+=1){const v=o[_],x=s[_],W=x?.direction==="desc"?"desc":"asc",q=v===void 0||x===void 0?a`${a.identifier(To)} < ${g}`:Ao(v,u[_],W,!1);if(q===void 0)continue;const B=[];for(let j=0;j<_;j+=1)B.push(a`${a.identifier(o[j])} IS ${u[j]}`);B.push(q);const[U]=B;E.push(B.length===1&&U!==void 0?U:a`(${a.join(B,a` AND `)})`)}const y=E.length>0?a.join(E,a` OR `):a`1 = 0`,d=K(n,a`SELECT COUNT(*) AS c FROM ${a.identifier(r)} WHERE ${a.identifier("__partition__")} = ${c} AND (${y})`).one(),b=K(n,a`SELECT COUNT(*) AS c FROM ${a.identifier(r)} WHERE ${a.identifier("__partition__")} = ${c}`).one();return{before:d.c,total:b.c}},jr=n=>{const r=new Map;for(const[s,c]of Object.entries(n.tables))for(const u of Object.values(c.relationMap??{}))u.kind==="one"&&(u.onDelete==="cascade"||u.onDelete==="set null")&&r.set(u.table,[...r.get(u.table)??[],{holder:s,op:u.onDelete==="cascade"?"delete":"update"}]);const o=s=>{const c=new Set,u=[s];for(let g=u.pop();g!==void 0;g=u.pop())for(const{holder:E,op:y}of r.get(g)??[]){if(E===s||zt(n,E,y))return!0;c.has(E)||(c.add(E),u.push(E))}return!1};return new Set(Object.entries(n.tables).filter(([s,c])=>c.shardMode?.kind==="global"||zt(n,s,"delete")||o(s)).map(([s])=>s))},Hr=n=>{const r=new Map;for(const[o,s]of Object.entries(n.tables))s.softDeleteMode&&r.set(o,s.softDeleteMode.field);return r},ft=new WeakMap,Kr=(n,r)=>{let o=ft.get(r.tables);if(!ft.has(r.tables)){const c=Object.keys(r.tables).map(u=>u.replaceAll(/[$()*+.?[\\\]^{|}]/gu,String.raw`\$&`));o=c.length===0?void 0:new RegExp(`"(${c.join("|")})"`,"gu"),ft.set(r.tables,o)}if(o===void 0)return;const s=new Set;for(const c of n.matchAll(o))s.add(c[1]);return s.size===1?[...s][0]:void 0},Nr=(n,r,o)=>{for(const s of n){const c=s,u=c?.[ie];if(typeof u=="string"){const g=c?.id,E=ao(u);typeof g!="string"?r.recordReadBytes(E):o===void 0?r.recordDocumentRead(`${g}\0${String(E)}`,E):r.recordDocumentRead(`${o}\0${g}`,E)}}},Qr=(n,r,o)=>{if(r===void 0)return n;const s=(c,...u)=>{const g=n.exec(c,...u),E=g.one.bind(g),y=g[Symbol.iterator].bind(g),d=o===void 0?void 0:Kr(c,o);let b=!1;const _=v=>{Nr(v,r,d)};return g.toArray=()=>{const v=[];for(const x of{[Symbol.iterator]:y})_([x]),v.push(x);return v},g.one=()=>{b=!0;try{const v=E();return _([v]),v}finally{b=!1}},g[Symbol.iterator]=function*(){for(const x of{[Symbol.iterator]:y})b||_([x]),yield x},g};return new Proxy(n,{get:(c,u)=>u==="exec"?s:u===to?c:Reflect.get(c,u,c)})},Vr=new Map([["findFirst","rows"],["findFirstOrThrow","rows"],["findMany","page"],["get","rows"],["lookupById","lookup"],["rankPage","page"]]),Jr=new Map([["collect","rows"],["collectWithScores","scored"],["first","rows"],["paginate","page"],["take","rows"],["unique","rows"]]),Ie=(n,r,o)=>{if(typeof n!="object"||n===null)return;const s=co(n);if(s===void 0)return;const c=n._id;typeof c=="string"?o.recordDocumentRead(`global\0${r}\0${c}`,s):o.recordReadBytes(s)},Je=(n,r,o,s)=>{if(typeof n!="object"||n===null)return;const c=n;switch(r){case"lookup":{Ie(c.row,typeof c.tableName=="string"?c.tableName:o,s);return}case"page":{for(const u of c.page??[])Ie(u,o,s);return}case"rows":{for(const u of Array.isArray(n)?n:[n])Ie(u,o,s);return}default:for(const u of Array.isArray(n)?n:[])Ie(u.document,o,s)}},bn=(n,r,o)=>new Proxy(n,{get:(s,c)=>{const u=Reflect.get(s,c,s);if(typeof u!="function")return u;if(c===Symbol.asyncIterator)return async function*(){for await(const y of Reflect.apply(u,s,[]))Ie(y,r,o),yield y};const g=Jr.get(c);return(...E)=>{const y=Reflect.apply(u,s,E);return g!==void 0?Promise.resolve(y).then(d=>(Je(d,g,r,o),d)):typeof y=="object"&&y!==null&&!(y instanceof Promise)?bn(y,r,o):y}}}),zr=new Set(["findFirst","findFirstOrThrow","findMany"]),Yr=n=>{const r=n[1],o=r?.select;if(!Array.isArray(o))return;const s=Object.fromEntries(Object.entries(r).filter(([g])=>g!=="select")),c=s.with,u=g=>En(g,o,c);return{args:[n[0],s,...n.slice(2)],project:(g,E)=>typeof g!="object"||g===null?g:E==="page"?{...g,page:u(g.page)}:u([g])[0]}},fn=256,Et=4096,Xr=1024*1024,Zr=async(n,r,o,s)=>{const c=r[1]??{},u=[];let{cursor:g}=c,E=fn,y=0;for(;;){const d=await n([r[0],{...c,cursor:g,limit:E},...r.slice(2)]);if(Array.isArray(d))return Je(d,"rows",o,s),[...u,...d];const b=s.headroom().readBytes;if(Je(d,"page",o,s),u.push(...d.page),d.isDone||typeof d.continueCursor!="string")return{continueCursor:null,isDone:!0,page:u};g=d.continueCursor,y+=s.headroom().readBytes-b,E=y>0?Math.min(Et,Math.max(fn,Math.floor(Xr*u.length/y))):Et}},ei=(n,r)=>n===void 0||r===void 0?n:new Proxy(n,{get:(o,s)=>{const c=Reflect.get(o,s,o);if(typeof c!="function")return c;if(s==="query")return(...g)=>bn(Reflect.apply(c,o,g),String(g[0]),r);const u=Vr.get(s);return u===void 0?c:async(...g)=>{const E=zr.has(s)?Yr(g):void 0;let y=E?.args??g;const d=String(g[0]),b=y[1],_=s==="findMany"&&typeof b?.endCursor=="string",v=s==="findMany"&&typeof b?.limit!="number"&&!_;if(_&&typeof b.limit!="number"&&(y=[y[0],{...b,limit:Et},...y.slice(2)]),v){const W=await Zr(q=>Reflect.apply(c,o,q),y,d,r);return E===void 0?W:E.project(W,u)}const x=await Reflect.apply(c,o,y);return Je(x,u,d,r),E===void 0?x:E.project(x,u)}}}),hn=new WeakMap,wn=new WeakMap,ti=n=>{const{baselineSeq:r,onStalePatchDropped:o}=n,{headroom:s}=n,c=hn.get(n)??{value:void 0},u=wn.get(n)??{value:0};let g;const E=()=>{if(g===void 0){const e={...n,enforceRls:!1,headroom:void 0};hn.set(e,c),wn.set(e,u),g=ti(e)}return g},y=Qr(n.sql,s,n.schema),{schema:d}=n,b=n.broadcast??(()=>{}),_=(e,t)=>{if(!Object.hasOwn(d.tables,e))throw new $("BAD_REQUEST",`${t}: "${e}" is not a table in this schema`)},v=ko(d),x=new Map;for(const e of v){const t=i=>(d.tables[i]?.shardMode?.kind??"root")==="root";!e.array&&t(e.sourceTable)&&t(e.targetTable)&&x.set(e.sourceTable,[...x.get(e.sourceTable)??[],e])}const W=(e,t,i)=>{for(const l of x.get(e)??[]){const w=t[l.column];if(typeof w!="string"||i?.[l.column]===w||l.targetTable===e&&t._id===w)continue;if(K(y,a`SELECT 1 FROM ${a.identifier(l.targetTable)} WHERE id = ${w} LIMIT 1`).toArray().length===0)throw new $("VALIDATION_ERROR",`${l.name} references ${l.targetTable} row "${w}", which does not exist`)}},q=qo(d,n.inTransaction),B=jr(d),U=Hr(d),j=()=>n.inTransaction?.()===!0,ee=e=>d.tables[e]?.commitOrderedMode!==!0?{}:((c.value===void 0||!j())&&(c.value=zn(y)),{[Yn]:c.value}),N=(e,...t)=>{const i=d.tables[e]?.indexes??[],l=[];let w;for(const p of t)p&&(typeof p._id=="string"&&p._id!==w&&(w=p._id,l.push(Io(w))),l.push(...xo(i,bo(i,p,Ce))));return l.length>0?l:void 0},S=n.onRead??(()=>{}),M=e=>{Ut(d.tables[e])&&S(Vt,Vt)},L=n.onReadRange??(e=>{S(e.table,G)}),F=e=>{M(e.table),L(e)},k=(e,t,i)=>{t!==void 0&&(i===!0||t!==G)&&s?.recordRead(1),M(e),S(e,t,i)},pe=(e,t)=>{const i=e.row._id;k(e.tableName,typeof i=="string"?i:t,typeof i=="string")},te=n.onIndexUse??(()=>{}),ge=n.onWrite??(()=>{}),J=e=>{s?.recordWrite(e)},ye=async e=>{J(e.doc),await ge(e)},{cache:me}=n,Ee=n.clock??(()=>Date.now()),St=n.idGenerator??(()=>crypto.randomUUID()),vt=n.scheduler??On,$e=ei(n.globalDb,s),ce=n.auth??{identity:null,userId:null},_t=n.cdc??!1,Ze=vt,Cn=No({scheduler:typeof Ze.list=="function"&&typeof Ze.get=="function"?Ze:void 0,storage:n.storage}),Re=(e,t,i,l)=>{_t&&!Ut(d.tables[e])&&Vn(y,Ee(),e,t,i,l)},Tt=(e,t,i,l)=>{const w=d.tables[e];if(w?.dropStalePatchesMode!==!0||!_t)return!1;const p=r?.();if(p===void 0)return!1;const f=Jn(y,e,t,p);if(f===void 0)return!1;const h=yo(w,i);return Object.keys(Ke(i)).some(m=>!h.has(m)&&Pt(jt(f,m))!==Pt(jt(l,m)))},ae=e=>d.tables[e]?.shardMode?.kind==="global",At=(e,t)=>{if(ae(e)){if(!$e)throw new $("INTERNAL",`cross-backend ${t} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return $e}return O},et=e=>At(e,"cascade"),H=(e,t)=>{if(ae(e)){if(!$e)throw new $("INTERNAL",`${t} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return $e}},It=async(e,t,i,l,w)=>{w&&J(i);const p=await e.insert(t,i,l);return b({key:p,op:"insert",row:{...i,_id:p},table:t}),p},xt=(e,t)=>At(e,"relation load").findMany(e,t),bt=(e,t)=>(ae(e)&&k(e,G),xt(e,t)),Mn=e=>!ae(e.table),Ct=n.relationExistsPushDown??"auto",Mt=Ct!=="never",{maxRelationKeys:Dt}=n,De=(e,t,i)=>Bo(e,{fetcher:bt,maxRelationKeys:Dt,relationBaseWhere:i,schema:d,tableName:t}),Dn=async(e,t,i,l)=>{const w=H(e,"relation grouped count");if(w)return k(e,G),jo((R,P)=>w.count(R,P),e,t,i,l);const p=d.tables[e];if(!p)throw new $("INTERNAL",`unknown table: ${e}`);k(e,G);const f=Ae(p.softDeleteMode,void 0),h={[t]:{in:i}},m=Q(Q(h,l),f),A=await De(m,e,void 0),C=Z(A,ue),I=fe(t);let T=a`SELECT ${I} AS __fk__, COUNT(*) AS count FROM ${a.identifier(e)}`;C&&(T=a`${T} WHERE ${C}`),T=a`${T} GROUP BY ${I}`;const D=K(y,T).toArray();return new Map(D.map(R=>[R.__fk__,R.count]))},kt=new Set;for(const[e,t]of Object.entries(d.tables))for(const i of Object.values(t.triggerMap??{}))kt.add(`${e} ${i.timing} ${i.op}`);const ne=(e,t,i)=>kt.has(`${e} ${t} ${i}`),oe=async(e,t,i)=>{if(u.value+=1,u.value>tn)throw u.value-=1,new se(`trigger recursion exceeded ${String(tn)} levels on "${i.table}" — check for a self-triggering write`,"trigger");try{await Qo({ctx:Bn,event:i,op:t,schema:d,tableName:i.table,timing:e})}finally{u.value-=1}},{ensureBackfilledForTable:Se,ensureBackfilledIndex:tt,ensureRankBackfilled:nt,ensureRankBackfilledForTable:ve,syncAggregates:ke,syncCompanionsForInsert:Lt,syncGeo:Le,syncRanks:_e,syncSearch:Fe}=Xn({broadcast:b,indexKeysFor:(e,t)=>N(e,t),invalidateCache:(e,t,i)=>me?.invalidate(e,t,N(e,i)),recordCdc:Re,schema:d,sql:y,verified:n.companionMemo?.verified}),Ft=(e,t,i)=>{const{shardMode:l}=t;if(l?.kind==="shardBy"&&!(l.field!==void 0&&(i.partitionBy??[]).includes(l.field)))throw Object.assign(new Error(`rank index "${i.name}" on "${e}" partitions across shards (shard key "${l.field??"?"}" is not in partitionBy) — a shard-local rank()/rankPage() would be wrong; roll it up through the Query Coordinator instead`),{code:"CROSS_SHARD_RANK_UNSUPPORTED",name:"LunoraError",status:400})},Bt=e=>Object.entries(d.tables).filter(([,t])=>t.shardMode?.kind!=="global").map(([t])=>t).filter(t=>e===void 0||t===e),Te=e=>e===void 0||ae(e)?$e:void 0,ot=async(e,t,i,l,w)=>{for(let p=0;p<i.length;p+=1)J(void 0);if(w!==void 0&&e.deleteMany!==void 0)return e.deleteMany(t,i,w.options);for(const p of i)await e.delete(t,p,l);return{deleted:i.length}},re=(e,t)=>{const i=Bt(t);for(let l=0;l<i.length;l+=nn){const w=i.slice(l,l+nn),[p]=he(y,$r(w),...Rr(e,w)).toArray();if(!p)continue;const f=p.__t__,h=xe(p);if(typeof f!="string"||!h)return;const m=p[ie];return{docJson:typeof m=="string"?m:le(m??{}),row:h,tableName:f}}},Wt={assertRankPartitionLocal:Ft,ensureRankBackfilled:nt,onRead:k,rowToDocument:xe,schema:d,sql:y},kn=(e,t,i)=>{const l=Z(i,ue);return l===void 0||K(y,a`SELECT 1 FROM ${a.identifier(e)} WHERE ${a.identifier("id")} = ${t} AND ${l}`).toArray().length>0},Ln=(e,t,i,l)=>Tt(e,t,i,l)?(o?.({fields:Object.keys(Ke(i)),id:t,table:e}),!0):!1,Fn=async(e,t,i,l,w)=>{const p=re(t,e);if(!p)return{applied:!1,doc:null};if(k(e,t),!kn(e,t,i.where)||Ln(e,t,i.patch,p.row))return{applied:!1,doc:p.row};try{await w(i.patch)}catch(f){if(f instanceof se&&f.kind==="occ"&&l)return;throw f}return{applied:!0,doc:re(t,e)?.row??null}},qt=async(e,t,i,l)=>{const{fetchLimit:w,limit:p,orderKeys:f,predicate:h}=await Wo(t,i,{canPushExists:Mt?Mn:void 0,existsPushMode:Ct==="always"?"always":"auto",fetcher:bt,maxRelationKeys:Dt,schema:d,tableName:e}),m=Mt?Fr(l):Ye,A=Z(h,m,ze),C=vn(e,A,_n(f),w);return{limit:p,orderKeys:f,statement:C}},O={system:Cn,async aggregate(e,t){const i=H(e,"aggregate");if(i)return k(e,G),i.aggregate(e,t);const l=d.tables[e];if(!l)throw new $("INTERNAL",`unknown table: ${e}`);if(Pe(t.op),t.op==="count")return O.count(e,{baseWhere:t.baseWhere,relationBaseWhere:t.relationBaseWhere,restrictsCounts:t.restrictsCounts,where:t.where});if(!t.field)throw new $("INTERNAL",`aggregate(${e}, { op: "${t.op}" }): "field" is required for non-count reducers`);k(e,G);const w=Ae(l.softDeleteMode,void 0),p=Q(Q(t.baseWhere,t.where),w),f=await De(p,e,t.relationBaseWhere),h=f!==p;if(l.aggregateIndexes&&!t.baseWhere&&!h){const R=Kn(l.aggregateIndexes,t.op,t.field,t.where);if(R){tt(e,R.index);const P=it(R.index.by??[],R.key),Y=rt(e,R.index.name),X=K(y,a`SELECT ${Ue} AS value, ${at} AS count FROM ${a.identifier(Y)} WHERE ${Oe} = ${P}`).toArray()[0];return st(t.op,X)}}sn(l,t.field,`aggregate(${e}, { op: "${t.op}", field: "${t.field}" })`);const m=Z(f,ue),A=Pe(t.op),C=fe(t.field);let I=a`SELECT ${a.raw(A)}(${C}) AS value FROM ${a.identifier(e)}`;m&&(I=a`${I} WHERE ${m}`);const D=K(y,I).toArray()[0]?.value;return D??null},asId(e,t){const i=cn(d,e,t);if(i===null)throw new $("BAD_REQUEST",`asId("${e}", …): "${t}" is not a valid id for table "${e}"`,{status:400});return i},async count(e,t){const i=H(e,"count");if(i)return k(e,G),i.count(e,t);const l=d.tables[e];if(!l)throw new $("INTERNAL",`unknown table: ${e}`);const w=Gn(t);if(w.restrictsCounts)throw new ct(e);k(e,G);const p=Ae(l.softDeleteMode,void 0),f=Q(Q(w.baseWhere,w.where),p),h=await De(f,e,w.relationBaseWhere),m=h!==f;if(l.aggregateIndexes&&!w.baseWhere&&!m){const T=Hn(l.aggregateIndexes,w.where);if(T){tt(e,T.index);const D=it(T.index.by??[],T.key),R=rt(e,T.index.name),P=K(y,a`SELECT ${Ue} AS value FROM ${a.identifier(R)} WHERE ${Oe} = ${D}`).toArray();return P[0]===void 0?0:P[0].value??0}}const A=Z(h,ue);let C=a`SELECT COUNT(*) AS count FROM ${a.identifier(e)}`;return A&&(C=a`${C} WHERE ${A}`),K(y,C).one().count},async delete(e,t,i){_(e,"ctx.db.delete(table, id)");const l=re(t,e);if(!l){const T=Te(e);T&&await ot(T,e,[t],i);return}const{docJson:w,row:p,tableName:f}=l,h=d.tables[f],m=i?.hard===!0,A=!m&&h?.softDeleteMode?h:void 0,C=A?.softDeleteMode?.field;if(C&&p[C]!==null&&p[C]!==void 0)return;if(ne(f,"before","delete")&&await oe("before","delete",{id:t,op:"delete",previous:p,table:f}),i?.skipOnDelete!==!0&&await Go({deletedId:t,deletedReference:T=>p[T],findHolders:async(T,D,R,P)=>(await et(T).findMany(T,{...P,includeDeleted:m,where:{[D]:R}})).page,onCascade:(T,D)=>et(T).delete(T,D,i),onRestrict:T=>{throw new se(T,"restrict")},onSetNull:(T,D,R)=>et(T).patch(T,D,{[R]:null}),schema:d,tableName:f}),Se(f),ve(f),A&&C){const T={[C]:Ee()},D={...p,...ee(f),...T,_id:t};ut(A,T,D,ce),Ne(y,f,Zt(f),[le(D),t,w]),Fe(f,t,D,p),Le(f,t,void 0),ke(f,p,D),_e(f,t,p,void 0);const R=N(f,p,D);me?.invalidate(f,t,R),Re(f,t,"update",D),b({indexKeys:R,key:t,op:"update",row:D,table:f}),ne(f,"after","delete")&&await oe("after","delete",{id:t,op:"delete",previous:p,table:f}),await ye({id:t,op:"delete",table:f});return}Ne(y,f,yr(f),[t,w]),Fe(f,t,void 0),Le(f,t,void 0),ke(f,p,void 0),_e(f,t,p,void 0);const I=N(f,p);me?.invalidate(f,t,I),Re(f,t,"delete"),b({indexKeys:I,key:t,op:"delete",table:f}),ne(f,"after","delete")&&await oe("after","delete",{id:t,op:"delete",previous:p,table:f}),await ye({id:t,op:"delete",table:f})},async deleteAll(e,t){if(!d.tables[e])throw new $("INTERNAL",`unknown table: ${e}`);if(s!==void 0)return E().deleteAll(e,t);const i=Math.max(1,t?.chunkSize??$n),l=t?.hard===void 0?void 0:{hard:t.hard},w=H(e,"deleteAll");let p=0;for(;;){const h=(await O.findMany(e,{limit:i})).page.map(m=>String(m._id));if(h.length===0)break;for(const m of h)await(w===void 0?O.delete(e,m,l):ot(w,e,[m],l)),p+=1;if(h.length<i)break}return{deleted:p}},async deleteMany(e,t,i){_(e,"ctx.db.deleteMany(table, ids)"),He(t.length,i?.limit,"deleteMany");for(const l of t)await O.delete(e,l);return{deleted:t.length}},async deleteWhere(e,t,i){const l=H(e,"deleteWhere"),p=(await on(l??O,e,t,i?.limit,"deleteWhere")).map(f=>String(f._id));if(l)return ot(l,e,p,void 0,{options:i});if(O.deleteMany===void 0)throw new $("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return O.deleteMany(e,p,i)},async findFirst(e,t={}){return(await O.findMany(e,{...t,limit:1,omitContinueCursor:!0})).page[0]??null},async findFirstOrThrow(e,t={}){const i=await O.findFirst(e,t);if(i===null)throw new wo(`findFirstOrThrow: no "${e}" document matched`);return i},async findMany(e,t={}){const i=H(e,"findMany");if(i)return k(e,G),t.consistency==="primary"&&S(e,Zn),i.findMany(e,t);const l=d.tables[e];if(!l)throw new $("INTERNAL",`unknown table: ${e}`);const w=!t.where&&!t.baseWhere;w?k(e,G):k(e);const{limit:p,orderKeys:f,statement:h}=await qt(e,l,t,k),m=he(y,h.text,...h.params).toArray();w&&s?.recordRead(m.length);const A=[];for(const I of m){const T=xe(I);T&&(A.push(T),!w&&typeof T._id=="string"&&k(e,T._id))}const C=Fo(A,{endCursor:t.endCursor,limit:p,omitContinueCursor:t.omitContinueCursor,orderKeys:f});return t.with&&await Uo({fetcher:xt,groupedCounter:Dn,parents:C.page,...Oo(t),schema:d,tableName:e,with:t.with}),{...C,page:En(C.page,t.select,t.with)}},async explain(e,t={}){const i=H(e,"explain");if(i)return i.explain(e,t);const l=d.tables[e];if(!l)throw new $("INTERNAL",`unknown table: ${e}`);const{statement:w}=await qt(e,l,t,()=>{}),p=he(y,`EXPLAIN QUERY PLAN ${w.text}`,...w.params).toArray();return{params:w.params,plan:p.map(f=>String(f.detail)),sql:w.text}},async get(e,t){_(e,"ctx.db.get(table, id)");const i=re(t,e);if(!i){const l=Te(e);return l?l.get(e,t):(M(e),S(e,t,!0),null)}return pe(i,t),i.row},async lookupById(e,t){const i=re(e,t);if(!i){for(const l of Bt(t))M(l),S(l,e,!0);return null}return pe(i,e),{row:i.row,tableName:i.tableName}},async groupBy(e,t){const i=H(e,"groupBy");if(i)return k(e,G),i.groupBy(e,t);const l=d.tables[e];if(!l)throw new $("INTERNAL",`unknown table: ${e}`);k(e,G);const w=t.agg??{op:"count"};if(Pe(w.op),w.op!=="count"&&!w.field)throw new $("INTERNAL",`groupBy(${e}, { agg: { op: "${w.op}" } }): "field" is required for non-count reducers`);const p=Ae(l.softDeleteMode,void 0),f=Q(Q(t.baseWhere,t.where),p),h=await De(f,e,t.relationBaseWhere),m=h!==f;if(l.aggregateIndexes&&!t.baseWhere&&!m){const R=jn(l.aggregateIndexes,w.op,w.field,t.by,t.where),P=R===void 0?0:Object.keys(R.partial).length,Y=R?.index.by?.length??0;if(R&&(P===0||P===Y)){tt(e,R.index);const X=rt(e,R.index.name),V=Object.keys(R.partial),de=[];if(V.length===(R.index.by??[]).length&&V.length>0){const Be=it(R.index.by??[],R.partial),We=K(y,a`SELECT ${Ue} AS value, ${at} AS count FROM ${a.identifier(X)} WHERE ${Oe} = ${Be}`).toArray();return We.length>0&&de.push({key:{...R.partial},value:st(w.op,We[0])}),de}const Wn=K(y,a`SELECT ${Oe} AS key, ${Ue} AS value, ${at} AS count FROM ${a.identifier(X)}`).toArray();for(const Be of Wn){const We=Un(JSON.parse(Be.key));de.push({key:We,value:st(w.op,Be)})}return de}}for(const R of[...t.by,w.field]){if(R===void 0)continue;const P=R===w.field?`groupBy(${e}, { agg: { op: "${w.op}", field: "${R}" } })`:`groupBy(${e}, { by: [..."${R}"] })`;sn(l,R,P)}const A=Z(h,ue),C=t.by.map(R=>a`${fe(R)} AS ${a.identifier(R)}`);if(w.op==="count")C.push(a`COUNT(*) AS value`);else{const{field:R}=w;if(R===void 0)throw new $("INTERNAL",`groupBy(${e}, { agg: { op: "${w.op}" } }): "field" is required for non-count reducers`);C.push(a`${a.raw(Pe(w.op))}(${fe(R)}) AS value`)}let I=a`SELECT ${a.join(C,a`, `)} FROM ${a.identifier(e)}`;A&&(I=a`${I} WHERE ${A}`),I=a`${I} GROUP BY ${a.join(t.by.map(R=>fe(R)),a`, `)}`;const T=K(y,I).toArray(),D=[];for(const R of T){const P={};for(const X of t.by)P[X]=no(l.shape[X],R[X]??null);const{value:Y}=R;D.push({key:P,value:Y==null?null:Number(Y)})}return D},async insert(e,t,i){const l=H(e,"insert");if(l)return It(l,e,t,i,!0);const w=d.tables[e];if(!w)throw new $("INTERNAL",`unknown table: ${e}`);const p=i?.allowExplicitId===!0,f=Ge(w,pt(w,t,ce),{supplied:t,trusted:p});let h;i?.clientId!==void 0?(vr(i.clientId),h=i.clientId):i?.allowExplicitId&&typeof f._id=="string"?(yt(f._id),h=f._id):h=St();const m=i?.allowExplicitId&&typeof f._creationTime=="number"?f._creationTime:Ee(),A={...f,...ee(e),_creationTime:m,_id:h};return ne(e,"before","insert")&&await oe("before","insert",{doc:{...A},id:h,op:"insert",table:e}),p||W(e,A),Se(e),ve(e),mt(y,e,pr(e),[h,m,le(A)]),Lt(e,h,A),ne(e,"after","insert")&&await oe("after","insert",{doc:A,id:h,op:"insert",table:e}),await ye({doc:A,id:h,op:"insert",table:e}),h},async insertManyUnsafe(e,t,i){if(He(t.length,i?.limit,"insertManyUnsafe"),t.length===0)return[];const l=H(e,"insert");if(l){const m=[];_r(d.tables[e],t,i?.allowExplicitId,ce);for(const A of t)J(A);for(const A of t){const C=await l.insert(e,A,{allowExplicitId:i?.allowExplicitId});b({key:C,op:"insert",row:{...A,_id:C},table:e}),m.push(C)}return m}const w=d.tables[e];if(!w)throw new $("INTERNAL",`unknown table: ${e}`);Se(e),ve(e);const p=[];for(let m=0;m<t.length;m+=je)p.push(ee(e));const f=i?.allowExplicitId===!0?void 0:Po(w),h=t.map((m,A)=>{const C=pt(w,m,ce),I=f===void 0?C:Ge(f,C,{supplied:m}),T=i?.allowExplicitId===!0&&typeof I._id=="string"?I._id:void 0;T!==void 0&&yt(T);const D=T??St(),R=i?.allowExplicitId===!0&&typeof I._creationTime=="number"?I._creationTime:Ee(),P={...I,...p[Math.floor(A/je)],_creationTime:R,_id:D};return{creationTime:R,document:P,id:D}});for(const m of h)J(m.document);for(let m=0;m<h.length;m+=je){const A=a.join(h.slice(m,m+je).map(I=>a`(${I.id}, ${I.creationTime}, ${le(I.document)})`),a`, `),C=gn("sqlite",a`INSERT INTO ${a.identifier(e)} (id, _creationTime, ${a.identifier(ie)}) VALUES ${A}`);mt(y,e,C.sql,C.params)}for(const{document:m,id:A}of h)Lt(e,A,m),await ge({doc:m,id:A,op:"insert",table:e});return h.map(m=>m.id)},async insertMany(e,t,i){He(t.length,i?.limit,"insertMany");const l=i?.skipDuplicates===!0,w=[],p=H(e,"insert");if(p)for(const h of t)J(h);const f=async h=>p?It(p,e,h,void 0,!1):O.insert(e,h);for(const h of t)try{w.push(await f(h))}catch(m){if(l&&m instanceof se&&m.kind==="unique")w.push(null);else throw m}return w},normalizeId(e,t){return cn(d,e,t)},async patch(e,t,i,l){_(e,"ctx.db.patch(table, id, values)");const w=re(t,e);if(!w){const D=Te(e);if(D){J(i),await D.patch(e,t,i,l);return}throw new $("NOT_FOUND",`document not found: ${t}`)}const{docJson:p,row:f,tableName:h}=w,m=d.tables[h];if(!m)throw new $("INTERNAL",`unknown table: ${h}`);if(k(h,t),dn("patch",i),Tt(h,t,i,f)){o?.({fields:Object.keys(Ke(i)),id:t,table:h});return}const A=po(m,i,f),C={...f,...Ke(A),...ee(h),_id:t};ut(m,A,C,ce);const I=Ge(m,C,{only:new Set(Object.keys(A)),previous:()=>f,tolerateStoredNull:!0});go(l,f,I),ne(h,"before","update")&&await oe("before","update",{doc:{...I},id:t,op:"update",previous:f,table:h}),W(h,I,f),Se(h),ve(h),Ne(y,h,Zt(h),[le(I),t,p]),Fe(h,t,I,f),Le(h,t,I),ke(h,f,I),_e(h,t,f,I);const T=N(h,f,I);me?.invalidate(h,t,T),Re(h,t,"update",I),b({indexKeys:T,key:t,op:"update",row:I,table:h}),ne(h,"after","update")&&await oe("after","update",{doc:I,id:t,op:"update",previous:f,table:h}),await ye({doc:I,id:t,op:"update",table:h})},async patchIf(e,t,i){const l=H(e,"patchIf");if(l){if(l.patchIf===void 0)throw new $("INTERNAL",`ctx.db.patchIf on global table '${e}' is unsupported: its backend has no conditional write`);return J(i.patch),l.patchIf(e,t,i)}if(!d.tables[e])throw new $("INTERNAL",`unknown table: ${e}`);for(let w=1;w<=an;w+=1){const p=await Fn(e,t,i,w<an,f=>O.patch(e,t,f,{verify:i.verify}));if(p!==void 0)return p}throw new se(`patchIf on "${e}" kept conflicting; the row changed on every attempt`,"occ")},async patchMany(e,t,i){_(e,"ctx.db.patchMany(table, patches)"),He(t.length,i?.limit,"patchMany");for(const l of t)await O.patch(e,l.id,l.patch);return{patched:t.length}},async patchWhere(e,t,i){const l=H(e,"patchWhere")??O,p=(await on(l,e,t.where,i?.limit,"patchWhere")).map(f=>({id:String(f._id),patch:t.patch}));if(O.patchMany===void 0)throw new $("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await O.patchMany(e,p,i),{patched:p.length}},async related(e,t){return Lo(O,v,e,t)},relationEdges:v,deleteRereadTables:B,inTransaction:j,softDeleteFields:U,relationWrites:q,query(e){const t=H(e,"query");return t?(k(e,G),t.query(e)):xn(y,d,e,te,i=>{i?F(i):k(e,G)},i=>{s?.recordRead(i)})},async rank(e,t,i){const l=H(e,"rank");if(l)return k(e,G),l.rank(e,t,i);te(e,t,"rank");const w=d.tables[e];if(!w)throw new $("INTERNAL",`unknown table: ${e}`);const p=w.rankIndexes?.find(V=>V.name===t);if(!p)throw new $("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(Ft(e,w,p),i.restrictsCounts)throw new ct(e);k(e,G),nt(e,p);const f=typeof i.row=="string"?i.row:i.row._id;if(!f)return null;const h=Nt(e,p.name),m=p.sortBy.map((V,de)=>Qt(de)),A=m.map(V=>Me(V)).join(", "),C=K(y,a`SELECT ${a.identifier("__partition__")}, ${a.raw(A)} FROM ${a.identifier(h)} WHERE ${a.identifier("__id__")} = ${f}`).toArray(),[I]=C;if(I===void 0)return null;let T=I.__partition__;const D=Q(i.baseWhere,i.where);dt(D,d,e,"rank");const R=vo(p,D);if(R){const V=_o(p.partitionBy??[],R);if(V!==T)return null;T=V}const P=m.map(V=>I[V]),{before:Y,total:X}=un(y,h,m,p.sortBy,T,P,f);return{position:Y+1,total:X}},async rankBefore(e,t,i){if(ae(e))throw new $("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const l=d.tables[e];if(!l)throw new $("INTERNAL",`unknown table: ${e}`);const w=l.rankIndexes?.find(m=>m.name===t);if(!w)throw new $("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(i.restrictsCounts)throw new ct(e);k(e,G),nt(e,w);const p=Nt(e,w.name),f=w.sortBy.map((m,A)=>Qt(A)),h=w.sortBy.map((m,A)=>Ce(i.sortValues[A]??null));return un(y,p,f,w.sortBy,i.partitionKey,h,i.rowId)},async rankPage(e,t,i={}){dt(Q(i.baseWhere,i.where),d,e,"rankPage");const l=H(e,"rankPage");if(l)return k(e,G),l.rankPage(e,t,i);te(e,t,"rank");const{continueCursor:w,hasMore:p,rows:f}=Ot(Wt,e,t,i);return{continueCursor:w,isDone:!p,page:f.map(h=>h.doc)}},async rankPageRows(e,t,i={}){dt(Q(i.baseWhere,i.where),d,e,"rankPage"),te(e,t,"rank");const{directions:l,hasMore:w,rows:p}=Ot(Wt,e,t,i);return{directions:l,hasMore:w,rows:p}},async restore(e,t){_(e,"ctx.db.restore(table, id)");const i=re(t,e);if(!i){const p=Te(e);if(p?.restore){await p.restore(e,t);return}throw new $("NOT_FOUND",`document not found: ${t}`)}const l=d.tables[i.tableName]?.softDeleteMode?.field;if(!l)throw new $("INTERNAL",`ctx.db.restore: table "${i.tableName}" is not a .softDelete() table`);const w=i.row[l]!==null&&i.row[l]!==void 0;await O.patch(e,t,{[l]:null}),w&&_e(i.tableName,t,void 0,i.row)},async replace(e,t,i,l){_(e,"ctx.db.replace(table, id, document)");const w=re(t,e);if(!w){const P=Te(e);if(P){J(i),await P.replace(e,t,i,l);return}throw new $("NOT_FOUND",`document not found: ${t}`)}const{docJson:p,row:f,tableName:h}=w,m=d.tables[h];if(!m)throw new $("INTERNAL",`unknown table: ${h}`);dn("replace",i);const A=l?.allowExplicitId&&typeof i._creationTime=="number"?i._creationTime:void 0,C=typeof f._creationTime=="number"?f._creationTime:void 0,I=A??C??Ee(),T={...i,...ee(h),_creationTime:I,_id:t};ut(m,i,T,ce);const D=l?.allowExplicitId===!0,R=Ge(m,T,{previous:()=>f,supplied:i,trusted:D});ne(h,"before","update")&&await oe("before","update",{doc:{...R},id:t,op:"update",previous:f,table:h}),D||W(h,R,f),Se(h),ve(h),Ne(y,h,gr(h),[I,le(R),t,p]),Fe(h,t,R,f),Le(h,t,R),ke(h,f,R),_e(h,t,f,R),me?.invalidate(h,t,N(h,f,R)),Re(h,t,"update",R),b({indexKeys:N(h,f,R),key:t,op:"update",row:R,table:h}),ne(h,"after","update")&&await oe("after","update",{doc:R,id:t,op:"update",previous:f,table:h}),await ye({doc:R,id:t,op:"update",table:h})},async wipeShard(e){const t=new Set(e?.exclude),i=e?.tables,l=Object.entries(d.tables).filter(([h,m])=>t.has(h)||i!==void 0&&!i.includes(h)?!1:m.shardMode?.kind!=="global").map(([h])=>h);if(i!==void 0){for(const h of i)if(!d.tables[h])throw new $("INTERNAL",`wipeShard: unknown table: ${h}`)}const w={};let p=0;const{deleteAll:f}=O;if(f===void 0)throw new $("INTERNAL","wipeShard: this writer has no deleteAll");for(const h of l){const m=await f(h,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});w[h]=m.deleted,p+=m.deleted}return{deleted:p,tables:w}}},Bn={db:O,scheduler:vt};return n.enforceRls===!0?Ho(O,d,(e,t)=>re(e,t)?.tableName,v):O};export{Qi as CDC_LOG_TABLE,ps as IDEMPOTENCY_TABLE,Br as NotUniqueError,us as advanceClientWatermark,Vi as applyCdcChanges,dn as assertNoExplicitUndefined,yt as assertStorableRowId,vr as assertValidClientId,ji as backfillAggregateIndexes,Hi as backfillRankIndexes,Ki as backfillSearchIndexes,Ji as bumpCdcEpoch,zi as cdcCanVouchFor,Yi as cdcForkedError,Xi as cdcSeqLeavingRows,Zi as cdcTouchesTables,es as cdcTrimmedError,ts as compactCdcDocs,ti as createShardCtxDb,ns as cursorBelowRetainedFloor,Qr as meterReadBytes,fs as migrateClientWatermark,os as minCdcReplayableSeq,rs as minCdcSeq,cn as normalizeIdStructurally,is as readCdcChangeKeys,ss as readCdcChanges,cs as readCdcCursor,as as readCdcEpoch,hs as readClientWatermark,gs as readIdempotent,$s as runShardMigrations,Ss as selectShapeMembers,vs as selectShapeRows,Ke as stripReservedPatchFields,ds as trimCdcChanges,ys as trimIdempotent,ms as writeIdempotent};
@@ -0,0 +1 @@
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};
@@ -1 +1 @@
1
- import{LunoraError as f}from"@lunora/errors";import{findRelated as y}from"./RELATED_DEFAULT_LIMIT-CVqN4JEu.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};
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};
@@ -1 +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-Pk0KLrfk.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};
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};
@@ -1 +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-6offuG6M.mjs";const U=Symbol.for("lunora.relations.fanOutBudget"),de=e=>({fanOutBudget:e[U],relationBaseWhere:e.relationBaseWhere,relationMask:e.relationMask}),L=(e,t)=>t.select?Y(e,t.select,t.with):e,pe=async(e,t,n,r,o)=>{const a=await Promise.all(r.map(async c=>{const u=o?{AND:[{[n]:c},o]}:{[n]:c};return[c,await e(t,u)]}));return new Map(a)},ee=32,B=1e4,te=(e,t,n)=>{const r=new Map;for(const o of e)for(const a of n(o)){const c=a[t],u=r.get(c);u?u.push(a):r.set(c,[a])}return r},W=(e,t)=>({...e,[U]:t}),ne=(e,t)=>{const n=new Map;for(const[o,a]of e)for(const c of a){const u=n.get(c);u?u.push(o):n.set(c,[o])}const r=new Map;for(const o of t)for(const a of n.get(o._id)??[]){const c=r.get(a);c?c.push(o):r.set(a,[o])}return r},D=(e,t)=>{const n=new Set;for(const r of e){const o=r[t];o!=null&&n.add(o)}return[...n]},he=async e=>{const{groupedCounter:t,fanOutBudget:n,fetcher:r,parents:o,relationBaseWhere:a,relationMask:c,schema:u,tableName:p,with:b}=e,O=n??{remaining:ee},y=(f,s)=>c?.(f,s)??s;if(o.length===0)return;const M=u.tables[p];if(!M)throw new S("INTERNAL",`unknown table: ${p}`);const _=M.relationMap??{},G=(f,s)=>{const i=d=>u.tables[d]?.shardMode?.kind??"root";return i(f)===i(s)&&i(f)!=="shardBy"},R=f=>{const s=_[f];if(!s)throw new S("INTERNAL",`unknown relation "${f}" on table "${p}"`);return s},X=async(f,s,i)=>{const d=D(o,s.field);if(d.length===0){for(const h of o)h[f]=null;return}const{page:l}=await r(s.table,W({baseWhere:a?.(s.table),relationBaseWhere:a,relationMask:c,where:{[s.references]:{in:d}},with:i.with},O)),w=new Map;for(const h of y(s.table,l))w.set(h[s.references],h);for(const h of o){const A=w.get(h[s.field]);h[f]=A?L([A],i)[0]??null:null}},j=async(f,s,i,d)=>{const{page:l}=await r(f,W({baseWhere:a?.(f),limit:d,orderBy:s.orderBy,relationBaseWhere:a,relationMask:c,where:s.where?{AND:[s.where,i]}:i,with:s.with},O));return l},T=(f,s,i,d,l)=>{for(const w of o){const h=l.get(w[d])??[];w[f]=L(i===void 0?h:h.slice(0,i),s)}},K=async(f,s,i)=>{const d=D(o,s.references);if(d.length===0){for(const g of o)g[f]=[];return}const l=typeof i.limit=="number"?Math.max(0,Math.floor(i.limit)):void 0,w=(g,k)=>j(s.table,i,g,k);if(l===0){for(const g of o)g[f]=[];return}const h=l!==void 0&&d.length<=O.remaining;h&&(O.remaining-=d.length);const A=h?await Promise.all(d.map(async g=>w({[s.field]:g},l))):[await w({[s.field]:{in:d}},void 0)],m=te(A,s.field,g=>y(s.table,g));T(f,i,l,s.references,m)},I=async f=>{const{from:s,table:i,to:d}=f.through,l=new Map,w=D(o,"_id");if(w.length===0)return l;const h=await j(i,{},{[s]:{in:w}},B+1);if(h.length>B)throw new S("INTERNAL",`loading "${p}" relations through "${i}" read more than ${String(B)} join rows for one page; load fewer ${p} rows at a time`);for(const A of y(i,h)){const m=A[s],g=A[d];if(m==null||g===null||g===void 0)continue;const k=l.get(m);k?k.add(g):l.set(m,new Set([g]))}return l},q=async(f,s,i)=>{const d=typeof i.limit=="number"?Math.max(0,Math.floor(i.limit)):void 0,l=d===0?new Map:await I(s),w=(A,m)=>j(s.table,i,{_id:{in:[...A]}},m);let h=new Map;if(l.size>0&&d!==void 0&&l.size<=O.remaining){O.remaining-=l.size;const A=[...l.keys()],m=await Promise.all([...l.values()].map(async g=>w(g,d)));h=new Map(A.map((g,k)=>[g,y(s.table,m[k]??[])]))}else if(l.size>0){const A=new Set([...l.values()].flatMap(m=>[...m]));h=ne(l,y(s.table,await w(A,void 0)))}T(f,i,d,"_id",h)},Z=async(f,s)=>{const i=[...s];if(i.length===0)return new Set;if(G(p,f)){const l=await t(f,"_id",i,a?.(f));return new Set(i.filter(w=>(l.get(w)??0)>0))}const d=await j(f,{},{_id:{in:i}},void 0);return new Set(d.map(l=>l._id))},J=async(f,s)=>{const i=await I(s),d=await Z(s.table,new Set([...i.values()].flatMap(l=>[...l])));for(const l of o){const w=l._count??{};w[f]=[...i.get(l._id)??[]].filter(h=>d.has(h)).length,l._count=w}},Q=async f=>{for(const s of Object.keys(f)){const i=R(s);if(i.through!==void 0){await J(s,i);continue}const[d,l]=i.kind==="many"?[i.field,i.references]:[i.references,i.field],w=a?.(i.table),h=D(o,l),A=h.length===0?new Map:await t(i.table,d,h,w);for(const m of o){const g=m._count??{},k=m[l];g[s]=k==null?0:A.get(k)??0,m._count=g}}};for(const[f,s]of Object.entries(b)){if(s===void 0||s===!1)continue;if(f==="_count"){await Q(s);continue}const i=R(f),d=s===!0?{}:s;i.through===void 0?await(i.kind==="one"?X(f,i,d):K(f,i,d)):await q(f,i,d)}},N=1e4,x=500,oe=async(e,t,n,r,o)=>{const a=new Set;let c=o;for(;;){const u=c!==void 0,p=c??await e();let b=!1;c=void 0;for(const O of p){const y=O._id;if(!(typeof y!="string"||a.has(y))){if(a.add(y),b=!0,a.size>N)throw n();await t(y)}}if(!u){if(p.length<x)return;if(!b)throw new S("INTERNAL",r)}}},H=(e,t,n)=>new S("CASCADE_LIMIT",`cannot delete "${e}" row: more than ${String(N)} ${t} rows reference it (onDelete: ${n}) — delete or re-point them in batches first`,{status:400}),re=async(e,t,n,r)=>{const{deletedId:o,deletedReference:a,findHolders:c,onRestrict:u,tableName:p}=e,b=n.references==="_id"?o:a(n.references);if(b==null)return;const{field:O}=n,y=`"${t}.${O}"`,M=await c(t,O,b,{limit:r==="restrict"?1:N+1,select:["_id"]});if(M.length!==0){if(r==="restrict")return u(`cannot delete "${p}" row: ${y} still references it`);if(M.length>N)throw H(p,y,r);return{action:r,field:O,holderTable:t,label:y,probe:M,referencedValue:b}}},se=async(e,t,n)=>{const{findHolders:r,onCascade:o,onSetNull:a,tableName:c}=e,{action:u,field:p,holderTable:b,label:O,probe:y,referencedValue:M}=t;await oe(()=>r(b,p,M,{limit:x}),_=>u==="cascade"?o(b,_):a(b,_,p),()=>H(c,O,u),`onDelete on "${c}" made no progress: ${O} rows still match after being processed`,n?y:void 0)},we=async e=>{const{schema:t,tableName:n}=e;if(!t.tables[n])throw new S("INTERNAL",`unknown table: ${n}`);const r=[];for(const[o,a]of Object.entries(t.tables)){const c=a.relationMap;if(c)for(const u of Object.values(c)){if(u.kind!=="one"||u.table!==n||!u.onDelete)continue;const p=await re(e,o,u,u.onDelete);p&&r.push(p)}}for(const[o,a]of r.entries())await se(e,a,o===0)},P=new WeakMap,V=e=>{const t=P.get(e);if(t!==void 0)return t;const n=e._meta,r=[n?.inner,n?.keyValidator,n?.valueValidator,...n?.members??[],...Object.values(n?.shape??{})],o=e.kind==="from"||r.some(a=>a!==void 0&&V(a));return P.set(e,o),o},$=e=>{const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},F=e=>e instanceof ArrayBuffer?new Uint8Array(e):ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):void 0,E=(e,t)=>{if(Object.is(e,t))return!0;if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();const n=F(e),r=F(t);if(n!==void 0||r!==void 0)return n!==void 0&&r!==void 0&&Object.getPrototypeOf(e)===Object.getPrototypeOf(t)&&n.length===r.length&&n.every((u,p)=>u===r[p]);if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((u,p)=>E(u,t[p]));if(typeof e!="object"||typeof t!="object"||e===null||t===null||!$(e)||!$(t))return!1;const o=e,a=t,c=Object.keys(o);return c.length===Object.keys(a).length&&c.every(u=>u in a&&E(o[u],a[u]))},C=new WeakMap,ge=e=>{if(C.has(e))return C.get(e);const t=Object.fromEntries(Object.entries(e.shape).filter(([,r])=>V(r))),n=Object.keys(t).length>0?{...e,shape:t}:void 0;return C.set(e,n),n},ie=e=>{let t;return(n,r)=>e===void 0?!1:(t??=e()??{},n in t&&E(r,t[n]))},ae=(e,t)=>{const n=new Set(Object.keys(t).filter(r=>t[r]!==void 0));for(const[r,o]of z(e))o.serverDefault&&n.delete(r);return n},ce=(e,t,n,r,o)=>n.trusted===!0||r!==void 0&&!r.has(e)||o(e,t),v=e=>typeof e!="object"||e===null?e:e instanceof Date?new Date(e):e instanceof ArrayBuffer||ArrayBuffer.isView(e)?structuredClone(e):Array.isArray(e)?e.map(t=>v(t)):e instanceof Map?new Map([...e].map(([t,n])=>[v(t),v(n)])):e instanceof Set?new Set([...e].map(t=>v(t))):$(e)?Object.fromEntries(Object.entries(e).map(([t,n])=>[t,v(n)])):e,ye=(e,t,n)=>{const r={...t};for(const[o,a]of z(e)){if(a.serverDefault){r[o]=a.serverDefault({auth:n});continue}if(r[o]===void 0){if(a.defaultFn)r[o]=a.defaultFn();else if("defaultValue"in a){const{defaultValue:c}=a;r[o]=v(c)}}}return r},me=(e,t,n={})=>{let r;const o=ie(n.previous),a=n.only??(n.supplied===void 0?void 0:ae(e,n.supplied));for(const[c,u]of Object.entries(e.shape)){if(!(c in t)||typeof u.parse!="function")continue;const p=V(u);if(p&&ce(c,t[c],n,a,o)||n.tolerateStoredNull===!0&&t[c]===null&&u.kind==="optional")continue;const b=u.parse(t[c]);p&&(r??={...t},r[c]=b)}return r??t};export{B as MAX_LINK_ROWS,ye as applyInsertDefaults,we as applyOnDelete,D as distinctValues,pe as fanOutScalarCounts,de as relationHooks,he as resolveWith,me as runRowValidators,ge as transformOnlyDefinition};
1
+ import{LunoraError as S}from"@lunora/errors";import{t as z}from"./do-sql-105TONaE.mjs";import{applySelect as Y}from"./CURSOR_PREFIX-rOdoinP8.mjs";const U=Symbol.for("lunora.relations.fanOutBudget"),de=e=>({fanOutBudget:e[U],relationBaseWhere:e.relationBaseWhere,relationMask:e.relationMask}),L=(e,t)=>t.select?Y(e,t.select,t.with):e,pe=async(e,t,n,r,o)=>{const a=await Promise.all(r.map(async c=>{const u=o?{AND:[{[n]:c},o]}:{[n]:c};return[c,await e(t,u)]}));return new Map(a)},ee=32,B=1e4,te=(e,t,n)=>{const r=new Map;for(const o of e)for(const a of n(o)){const c=a[t],u=r.get(c);u?u.push(a):r.set(c,[a])}return r},W=(e,t)=>({...e,[U]:t}),ne=(e,t)=>{const n=new Map;for(const[o,a]of e)for(const c of a){const u=n.get(c);u?u.push(o):n.set(c,[o])}const r=new Map;for(const o of t)for(const a of n.get(o._id)??[]){const c=r.get(a);c?c.push(o):r.set(a,[o])}return r},D=(e,t)=>{const n=new Set;for(const r of e){const o=r[t];o!=null&&n.add(o)}return[...n]},he=async e=>{const{groupedCounter:t,fanOutBudget:n,fetcher:r,parents:o,relationBaseWhere:a,relationMask:c,schema:u,tableName:p,with:b}=e,O=n??{remaining:ee},y=(f,s)=>c?.(f,s)??s;if(o.length===0)return;const M=u.tables[p];if(!M)throw new S("INTERNAL",`unknown table: ${p}`);const _=M.relationMap??{},G=(f,s)=>{const i=d=>u.tables[d]?.shardMode?.kind??"root";return i(f)===i(s)&&i(f)!=="shardBy"},R=f=>{const s=_[f];if(!s)throw new S("INTERNAL",`unknown relation "${f}" on table "${p}"`);return s},X=async(f,s,i)=>{const d=D(o,s.field);if(d.length===0){for(const h of o)h[f]=null;return}const{page:l}=await r(s.table,W({baseWhere:a?.(s.table),relationBaseWhere:a,relationMask:c,where:{[s.references]:{in:d}},with:i.with},O)),w=new Map;for(const h of y(s.table,l))w.set(h[s.references],h);for(const h of o){const A=w.get(h[s.field]);h[f]=A?L([A],i)[0]??null:null}},j=async(f,s,i,d)=>{const{page:l}=await r(f,W({baseWhere:a?.(f),limit:d,orderBy:s.orderBy,relationBaseWhere:a,relationMask:c,where:s.where?{AND:[s.where,i]}:i,with:s.with},O));return l},T=(f,s,i,d,l)=>{for(const w of o){const h=l.get(w[d])??[];w[f]=L(i===void 0?h:h.slice(0,i),s)}},K=async(f,s,i)=>{const d=D(o,s.references);if(d.length===0){for(const g of o)g[f]=[];return}const l=typeof i.limit=="number"?Math.max(0,Math.floor(i.limit)):void 0,w=(g,k)=>j(s.table,i,g,k);if(l===0){for(const g of o)g[f]=[];return}const h=l!==void 0&&d.length<=O.remaining;h&&(O.remaining-=d.length);const A=h?await Promise.all(d.map(async g=>w({[s.field]:g},l))):[await w({[s.field]:{in:d}},void 0)],m=te(A,s.field,g=>y(s.table,g));T(f,i,l,s.references,m)},I=async f=>{const{from:s,table:i,to:d}=f.through,l=new Map,w=D(o,"_id");if(w.length===0)return l;const h=await j(i,{},{[s]:{in:w}},B+1);if(h.length>B)throw new S("INTERNAL",`loading "${p}" relations through "${i}" read more than ${String(B)} join rows for one page; load fewer ${p} rows at a time`);for(const A of y(i,h)){const m=A[s],g=A[d];if(m==null||g===null||g===void 0)continue;const k=l.get(m);k?k.add(g):l.set(m,new Set([g]))}return l},q=async(f,s,i)=>{const d=typeof i.limit=="number"?Math.max(0,Math.floor(i.limit)):void 0,l=d===0?new Map:await I(s),w=(A,m)=>j(s.table,i,{_id:{in:[...A]}},m);let h=new Map;if(l.size>0&&d!==void 0&&l.size<=O.remaining){O.remaining-=l.size;const A=[...l.keys()],m=await Promise.all([...l.values()].map(async g=>w(g,d)));h=new Map(A.map((g,k)=>[g,y(s.table,m[k]??[])]))}else if(l.size>0){const A=new Set([...l.values()].flatMap(m=>[...m]));h=ne(l,y(s.table,await w(A,void 0)))}T(f,i,d,"_id",h)},Z=async(f,s)=>{const i=[...s];if(i.length===0)return new Set;if(G(p,f)){const l=await t(f,"_id",i,a?.(f));return new Set(i.filter(w=>(l.get(w)??0)>0))}const d=await j(f,{},{_id:{in:i}},void 0);return new Set(d.map(l=>l._id))},J=async(f,s)=>{const i=await I(s),d=await Z(s.table,new Set([...i.values()].flatMap(l=>[...l])));for(const l of o){const w=l._count??{};w[f]=[...i.get(l._id)??[]].filter(h=>d.has(h)).length,l._count=w}},Q=async f=>{for(const s of Object.keys(f)){const i=R(s);if(i.through!==void 0){await J(s,i);continue}const[d,l]=i.kind==="many"?[i.field,i.references]:[i.references,i.field],w=a?.(i.table),h=D(o,l),A=h.length===0?new Map:await t(i.table,d,h,w);for(const m of o){const g=m._count??{},k=m[l];g[s]=k==null?0:A.get(k)??0,m._count=g}}};for(const[f,s]of Object.entries(b)){if(s===void 0||s===!1)continue;if(f==="_count"){await Q(s);continue}const i=R(f),d=s===!0?{}:s;i.through===void 0?await(i.kind==="one"?X(f,i,d):K(f,i,d)):await q(f,i,d)}},N=1e4,x=500,oe=async(e,t,n,r,o)=>{const a=new Set;let c=o;for(;;){const u=c!==void 0,p=c??await e();let b=!1;c=void 0;for(const O of p){const y=O._id;if(!(typeof y!="string"||a.has(y))){if(a.add(y),b=!0,a.size>N)throw n();await t(y)}}if(!u){if(p.length<x)return;if(!b)throw new S("INTERNAL",r)}}},H=(e,t,n)=>new S("CASCADE_LIMIT",`cannot delete "${e}" row: more than ${String(N)} ${t} rows reference it (onDelete: ${n}) — delete or re-point them in batches first`,{status:400}),re=async(e,t,n,r)=>{const{deletedId:o,deletedReference:a,findHolders:c,onRestrict:u,tableName:p}=e,b=n.references==="_id"?o:a(n.references);if(b==null)return;const{field:O}=n,y=`"${t}.${O}"`,M=await c(t,O,b,{limit:r==="restrict"?1:N+1,select:["_id"]});if(M.length!==0){if(r==="restrict")return u(`cannot delete "${p}" row: ${y} still references it`);if(M.length>N)throw H(p,y,r);return{action:r,field:O,holderTable:t,label:y,probe:M,referencedValue:b}}},se=async(e,t,n)=>{const{findHolders:r,onCascade:o,onSetNull:a,tableName:c}=e,{action:u,field:p,holderTable:b,label:O,probe:y,referencedValue:M}=t;await oe(()=>r(b,p,M,{limit:x}),_=>u==="cascade"?o(b,_):a(b,_,p),()=>H(c,O,u),`onDelete on "${c}" made no progress: ${O} rows still match after being processed`,n?y:void 0)},we=async e=>{const{schema:t,tableName:n}=e;if(!t.tables[n])throw new S("INTERNAL",`unknown table: ${n}`);const r=[];for(const[o,a]of Object.entries(t.tables)){const c=a.relationMap;if(c)for(const u of Object.values(c)){if(u.kind!=="one"||u.table!==n||!u.onDelete)continue;const p=await re(e,o,u,u.onDelete);p&&r.push(p)}}for(const[o,a]of r.entries())await se(e,a,o===0)},P=new WeakMap,V=e=>{const t=P.get(e);if(t!==void 0)return t;const n=e._meta,r=[n?.inner,n?.keyValidator,n?.valueValidator,...n?.members??[],...Object.values(n?.shape??{})],o=e.kind==="from"||r.some(a=>a!==void 0&&V(a));return P.set(e,o),o},$=e=>{const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},F=e=>e instanceof ArrayBuffer?new Uint8Array(e):ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):void 0,E=(e,t)=>{if(Object.is(e,t))return!0;if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();const n=F(e),r=F(t);if(n!==void 0||r!==void 0)return n!==void 0&&r!==void 0&&Object.getPrototypeOf(e)===Object.getPrototypeOf(t)&&n.length===r.length&&n.every((u,p)=>u===r[p]);if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((u,p)=>E(u,t[p]));if(typeof e!="object"||typeof t!="object"||e===null||t===null||!$(e)||!$(t))return!1;const o=e,a=t,c=Object.keys(o);return c.length===Object.keys(a).length&&c.every(u=>u in a&&E(o[u],a[u]))},C=new WeakMap,ge=e=>{if(C.has(e))return C.get(e);const t=Object.fromEntries(Object.entries(e.shape).filter(([,r])=>V(r))),n=Object.keys(t).length>0?{...e,shape:t}:void 0;return C.set(e,n),n},ie=e=>{let t;return(n,r)=>e===void 0?!1:(t??=e()??{},n in t&&E(r,t[n]))},ae=(e,t)=>{const n=new Set(Object.keys(t).filter(r=>t[r]!==void 0));for(const[r,o]of z(e))o.serverDefault&&n.delete(r);return n},ce=(e,t,n,r,o)=>n.trusted===!0||r!==void 0&&!r.has(e)||o(e,t),v=e=>typeof e!="object"||e===null?e:e instanceof Date?new Date(e):e instanceof ArrayBuffer||ArrayBuffer.isView(e)?structuredClone(e):Array.isArray(e)?e.map(t=>v(t)):e instanceof Map?new Map([...e].map(([t,n])=>[v(t),v(n)])):e instanceof Set?new Set([...e].map(t=>v(t))):$(e)?Object.fromEntries(Object.entries(e).map(([t,n])=>[t,v(n)])):e,ye=(e,t,n)=>{const r={...t};for(const[o,a]of z(e)){if(a.serverDefault){r[o]=a.serverDefault({auth:n});continue}if(r[o]===void 0){if(a.defaultFn)r[o]=a.defaultFn();else if("defaultValue"in a){const{defaultValue:c}=a;r[o]=v(c)}}}return r},me=(e,t,n={})=>{let r;const o=ie(n.previous),a=n.only??(n.supplied===void 0?void 0:ae(e,n.supplied));for(const[c,u]of Object.entries(e.shape)){if(!(c in t)||typeof u.parse!="function")continue;const p=V(u);if(p&&ce(c,t[c],n,a,o)||n.tolerateStoredNull===!0&&t[c]===null&&u.kind==="optional")continue;const b=u.parse(t[c]);p&&(r??={...t},r[c]=b)}return r??t};export{B as MAX_LINK_ROWS,ye as applyInsertDefaults,we as applyOnDelete,D as distinctValues,pe as fanOutScalarCounts,de as relationHooks,he as resolveWith,me as runRowValidators,ge as transformOnlyDefinition};
@@ -1 +1 @@
1
- import{m as P,c as E,l as w,r as T,a as D,w as F}from"./ctx-db-search-state-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-CEht4hXX.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};
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};
@@ -1 +1 @@
1
- import{LunoraError as g}from"@lunora/errors";import{sql as o}from"drizzle-orm";import{mergeWhere as b}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{SCAN_DEP as j}from"./SCAN_DEP-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-6offuG6M.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};
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};
@@ -1 +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-6offuG6M.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};
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};
@@ -1 +1 @@
1
- import{createShardCtxDb as C}from"./NotUniqueError-vJf9tj6U.mjs";import{createRelayLink as N}from"./DEFAULT_MAX_RELAYS-Bc6PI-xy.mjs";import{ConflictError as q}from"./ConflictError-C8GtJmjS.mjs";import{runShardMigrations as B}from"./runShardMigrations-BPFg3Ht6.mjs";import{d as x}from"./relay-CKEdfUjH.mjs";const v=(O,y={})=>({_meta:{column:{notNull:!0,...y}},kind:O}),W=(O,y,F)=>{const{describe:_,expect:l,it:b}=F;_(`engine contract: ${O}`,()=>{_("optimistic concurrency",()=>{const g=u=>({tables:{items:{indexes:[],shape:{title:v("string"),version:v("number",{notNull:!1})},triggerMap:{clobber:{handler:()=>{u.exec(`UPDATE "items" SET "__doc__" = json_set("__doc__", '$.version', 99) WHERE "id" = 'i1'`)},op:"update",timing:"before"}}}}});b("raises a CONFLICT of kind `occ` when a write's snapshot is clobbered",async()=>{const{close:u,host:h}=y();try{const d=h.sql,p=g(d);B(d,p);const s=C({schema:p,sql:d});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0}),await l(s.patch("items","i1",{title:"second"})).rejects.toBeInstanceOf(q)}finally{u?.()}}),b("reports the conflict as CONFLICT/409 rather than retrying it away",async()=>{const{close:u,host:h}=y();try{const d=h.sql,p=g(d);B(d,p);const s=C({schema:p,sql:d});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let r;try{await s.patch("items","i1",{title:"second"})}catch(t){r=t}const e=r;l(e.code).toBe("CONFLICT"),l(e.kind).toBe("occ")}finally{u?.()}}),b("leaves the row readable and unchanged after a conflict",async()=>{const{close:u,host:h}=y();try{const d=h.sql,p=g(d);B(d,p);const s=C({schema:p,sql:d});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});try{await s.patch("items","i1",{title:"second"})}catch{}const r=await s.get("items","i1");l(r?.title).toBe("first"),l(r?.version).toBe(99)}finally{u?.()}}),b("raises a CONFLICT of kind `trigger` when a trigger writes its own row through the db",async()=>{const{close:u,host:h}=y();try{const d=h.sql,p={tables:{items:{indexes:[],shape:{title:v("string"),version:v("number",{notNull:!1})},triggerMap:{recurse:{handler:async(t,a)=>{await t.db.patch("items",a.doc._id,{version:99})},op:"update",timing:"before"}}}}};B(d,p);const s=C({schema:p,sql:d});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let r;try{await s.patch("items","i1",{title:"second"})}catch(t){r=t}const e=r;l(e).toBeInstanceOf(q),l(e.code).toBe("CONFLICT"),l(e.kind).toBe("trigger")}finally{u?.()}})}),_("shape-poke ordering",()=>{const g="shard-a",u={args:{},name:"messages"},h=(e,t,a,n)=>e.accept(t?.()??{},{connectionId:a,shapes:{[n]:u}}),d=(e,t,a,n=new Set)=>{let c=0,i=0;const o=k=>()=>{throw new Error(`the relay poke path must not reach RelayHost.${k}`)},m={fetch:(k,E)=>{if(JSON.parse(E?.body??"{}").type!=="relay_shape_subscribe")return Promise.resolve(new Response(void 0,{status:204}));const I=a[i];if(i+=1,I===void 0)throw new Error("the relay asked for more seeds than this fixture supplies");return Promise.resolve(Response.json(I))}},f={get:()=>m,getByName:()=>m,idFromName:k=>k},w={buildShapeDiff:o("buildShapeDiff"),computeOpLogShapeSeed:o("computeOpLogShapeSeed"),currentCdcEpoch:o("currentCdcEpoch"),deliverWhisperLocal:o("deliverWhisperLocal"),dropIfLapsed:k=>n.has((k.deserializeAttachment?.()).connectionId??""),doName:()=>x(g,0),env:()=>({SHARD:f}),getWebSockets:()=>e.getSockets(),maskMetadata:o("maskMetadata"),nextPokeId:()=>(c+=1,`poke-${String(c)}`),readAttachment:k=>k.deserializeAttachment?.(),recordShapePokeFanout:()=>{},resolveShape:o("resolveShape"),rlsMetadata:o("rlsMetadata"),shardBinding:()=>"SHARD",shardJurisdiction:()=>{},sql:()=>t},S=N(w);if(S===void 0)throw new Error("expected a relay link for a `…::relay::N` name");return S},p=e=>new Request("https://relay.internal/_lunora/relay",{body:JSON.stringify(e),headers:{"content-type":"application/json"},method:"POST"}),s=async(e,t,a)=>{const n=await e.seedRelayShape(t,a,u,{identity:void 0,userId:void 0});if(n!=="ok")throw new Error(`seed failed: ${JSON.stringify(n)}`)},r=(e={})=>p({...u,checkpoint:20,epoch:"e1",fromCursor:10,rowsPatch:[{id:"r1",op:"upsert",value:{title:"hello"}}],type:"relay_shape_poke",...e});b("frames a poke as pokeStart → pokePart per shape → pokeEnd, under one poke id",async()=>{const{close:e,createSocket:t,host:a,readFrames:n,sockets:c}=y();try{const i=d(c,a.sql,[{cursor:10,epoch:"e1",frames:[]}]),o=h(c,t,"c-alice","s1");await s(i,o,"s1"),await i.handleControl(r());const f=(await n(o)).map(w=>JSON.parse(w));l(f.map(w=>w.type)).toStrictEqual(["pokeStart","pokePart","pokeEnd"]),l(new Set(f.map(w=>w.pokeId)).size).toBe(1),l(f[1]?.shapeId).toBe("s1"),l(f[2]?.checkpoint).toBe(20)}finally{e?.()}}),b("delivers a poke only to sockets whose cursor matches, and advances them past it",async()=>{const{close:e,createSocket:t,host:a,readFrames:n,sockets:c}=y();try{const i=d(c,a.sql,[{cursor:10,epoch:"e1",frames:[]},{cursor:7,epoch:"e1",frames:[]}]),o=h(c,t,"c-alice","s1"),m=h(c,t,"c-bob","s2");await s(i,o,"s1"),await s(i,m,"s2"),await i.handleControl(r());const f=await n(o);l(f.length).toBe(3);const w=await n(m);l(w.length).toBe(0),await i.handleControl(r());const S=await n(o);l(S.length).toBe(3)}finally{e?.()}}),b("pokes no subscriber the host reports lapsed, and still pokes the others",async()=>{const{close:e,createSocket:t,host:a,readFrames:n,sockets:c}=y();try{const i=new Set,o=d(c,a.sql,[{cursor:10,epoch:"e1",frames:[]},{cursor:10,epoch:"e1",frames:[]}],i),m=h(c,t,"c-alice","s1"),f=h(c,t,"c-bob","s2");await s(o,m,"s1"),await s(o,f,"s2"),i.add("c-bob"),await o.handleControl(r());const w=await n(m),S=await n(f);l(w.length).toBe(3),l(S.length).toBe(0)}finally{e?.()}}),b("skips a socket whose cursor matches under a different CDC epoch",async()=>{const{close:e,createSocket:t,host:a,readFrames:n,sockets:c}=y();try{const i=d(c,a.sql,[{cursor:10,epoch:"e1",frames:[]}]),o=h(c,t,"c-alice","s1");await s(i,o,"s1"),await i.handleControl(r({epoch:"e2"}));const m=await n(o);l(m.length).toBe(0),await i.handleControl(r());const f=await n(o);l(f.length).toBe(3)}finally{e?.()}})}),_("orderBy null placement",()=>{const g=[["a",void 0],["b",3],["c",void 0],["d",1],["e",void 0],["f",3],["g",2],["h",void 0]],u=[{nulls:"first",sort:"asc"},{nulls:"last",sort:"asc"},{nulls:"first",sort:"desc"},{nulls:"last",sort:"desc"}],h=({nulls:p,sort:s})=>{const r=new Map(g.map(([t],a)=>[t,a])),e=s==="asc"?1:-1;return g.toSorted(([t,a],[n,c])=>a!==c?a===void 0?p==="first"?-1:1:c===void 0?p==="first"?1:-1:(a-c)*e:((r.get(t)??0)-(r.get(n)??0))*e).map(([t])=>t)},d=p=>p.map(s=>String(s.label));b("pages every placement in threes with no row skipped or repeated",async()=>{const{close:p,host:s}=y();try{const r=s.sql,e=u.map((i,o)=>`items_${String(o)}`),t={label:v("string"),score:v("number",{notNull:!1})},a={tables:Object.fromEntries(e.map(i=>[i,{indexes:[{fields:["score"],name:"by_score"}],shape:t}]))};B(r,a);let n=17e11;const c=C({clock:()=>(n+=1e3,n),schema:a,sql:r});for(const i of e)for(const[o,m]of g)await c.insert(i,m===void 0?{label:o}:{label:o,score:m});for(const[i,o]of u.entries()){const m=e[i]??"",f=await c.findMany(m,{orderBy:[{score:o}]});l(d(f.page)).toStrictEqual(h(o));const w=[];let S;for(let k=0;k<g.length+2;k+=1){const E=await c.findMany(m,{cursor:S,limit:3,orderBy:[{score:o}]});if(w.push(...d(E.page)),E.isDone)break;S=E.continueCursor}l(w).toStrictEqual(h(o))}}finally{p?.()}})}),_("RLS identity under live subscription",()=>{const g="shard-a",u={args:{},name:"lobby-messages"},h={args:{},name:"my-orders"},d=s=>{const r=[],e=[],t={fetch:(c,i)=>(r.push(JSON.parse(i?.body??"{}")),Promise.resolve(new Response(void 0,{status:204})))},n=N({buildShapeDiff:()=>[{id:"r1",op:"upsert",value:{}}],computeOpLogShapeSeed:()=>({baseCheckpoint:void 0,cursor:10,epoch:"e1",reset:!0,rowsPatch:[]}),currentCdcEpoch:()=>"e1",deliverWhisperLocal:()=>0,dropIfLapsed:()=>!1,doName:()=>g,env:()=>({SHARD:{get:()=>t,getByName:()=>t,idFromName:c=>c}}),getWebSockets:()=>[],maskMetadata:()=>({columns:[]}),nextPokeId:()=>"poke-1",readAttachment:()=>({}),recordShapePokeFanout:()=>{},resolveShape:(c,i,o)=>(e.push(o),c===h.name?{columns:["id"],effectiveWhere:{org:o?.identity?.org??"anonymous"},global:!1,table:"orders"}:{columns:["id"],effectiveWhere:{room:"lobby"},global:!1,table:"messages"}),rlsMetadata:()=>({policies:[]}),shardBinding:()=>"SHARD",shardJurisdiction:()=>{},sql:()=>s});if(n===void 0)throw new Error("expected an owner link for an un-suffixed DO name");return{owner:n,posts:r,resolvedUnder:e}},p=async(s,r)=>{await s.handleControl(new Request("https://owner.internal/_lunora/relay",{body:JSON.stringify({...r,connectionId:"c-alice",identity:{org:"acme"},relayIndex:0,subId:"s1",type:"relay_shape_subscribe",userId:"u1"}),headers:{"content-type":"application/json"},method:"POST"}))};b("seeds a subscriber under its own forwarded identity, never the anonymous one",async()=>{const{close:s,host:r}=y();try{const{owner:e,resolvedUnder:t}=d(r.sql);await p(e,h),l(t.some(a=>a?.userId==="u1"&&a.identity?.org==="acme")).toBe(!0)}finally{s?.()}}),b("routes an identity-scoped shape to a per-socket poke, not the cohort multicast",async()=>{const{close:s,host:r}=y();try{const{owner:e,posts:t}=d(r.sql);await p(e,h),t.length=0,await e.onFlush(new Set(["orders"]),20);const a=t.filter(n=>n.type==="relay_shape_poke");l(a.length).toBe(1),l(a[0]?.targetConnectionId).toBe("c-alice")}finally{s?.()}}),b("still multicasts an identity-blind shape to the whole cohort",async()=>{const{close:s,host:r}=y();try{const{owner:e,posts:t}=d(r.sql);await p(e,u),t.length=0,await e.onFlush(new Set(["messages"]),20);const a=t.filter(n=>n.type==="relay_shape_poke");l(a.length).toBe(1),l(a[0]?.targetConnectionId).toBeUndefined()}finally{s?.()}})})})};export{W as defineEngineContractSuite};
1
+ import{createShardCtxDb as C}from"./NotUniqueError-B2OuN937.mjs";import{createRelayLink as N}from"./DEFAULT_MAX_RELAYS-Bc6PI-xy.mjs";import{ConflictError as q}from"./ConflictError-C8GtJmjS.mjs";import{runShardMigrations as B}from"./runShardMigrations-Bc7PsQhM.mjs";import{d as x}from"./relay-CKEdfUjH.mjs";const v=(O,y={})=>({_meta:{column:{notNull:!0,...y}},kind:O}),W=(O,y,F)=>{const{describe:_,expect:l,it:b}=F;_(`engine contract: ${O}`,()=>{_("optimistic concurrency",()=>{const g=u=>({tables:{items:{indexes:[],shape:{title:v("string"),version:v("number",{notNull:!1})},triggerMap:{clobber:{handler:()=>{u.exec(`UPDATE "items" SET "__doc__" = json_set("__doc__", '$.version', 99) WHERE "id" = 'i1'`)},op:"update",timing:"before"}}}}});b("raises a CONFLICT of kind `occ` when a write's snapshot is clobbered",async()=>{const{close:u,host:h}=y();try{const d=h.sql,p=g(d);B(d,p);const s=C({schema:p,sql:d});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0}),await l(s.patch("items","i1",{title:"second"})).rejects.toBeInstanceOf(q)}finally{u?.()}}),b("reports the conflict as CONFLICT/409 rather than retrying it away",async()=>{const{close:u,host:h}=y();try{const d=h.sql,p=g(d);B(d,p);const s=C({schema:p,sql:d});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let r;try{await s.patch("items","i1",{title:"second"})}catch(t){r=t}const e=r;l(e.code).toBe("CONFLICT"),l(e.kind).toBe("occ")}finally{u?.()}}),b("leaves the row readable and unchanged after a conflict",async()=>{const{close:u,host:h}=y();try{const d=h.sql,p=g(d);B(d,p);const s=C({schema:p,sql:d});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});try{await s.patch("items","i1",{title:"second"})}catch{}const r=await s.get("items","i1");l(r?.title).toBe("first"),l(r?.version).toBe(99)}finally{u?.()}}),b("raises a CONFLICT of kind `trigger` when a trigger writes its own row through the db",async()=>{const{close:u,host:h}=y();try{const d=h.sql,p={tables:{items:{indexes:[],shape:{title:v("string"),version:v("number",{notNull:!1})},triggerMap:{recurse:{handler:async(t,a)=>{await t.db.patch("items",a.doc._id,{version:99})},op:"update",timing:"before"}}}}};B(d,p);const s=C({schema:p,sql:d});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let r;try{await s.patch("items","i1",{title:"second"})}catch(t){r=t}const e=r;l(e).toBeInstanceOf(q),l(e.code).toBe("CONFLICT"),l(e.kind).toBe("trigger")}finally{u?.()}})}),_("shape-poke ordering",()=>{const g="shard-a",u={args:{},name:"messages"},h=(e,t,a,n)=>e.accept(t?.()??{},{connectionId:a,shapes:{[n]:u}}),d=(e,t,a,n=new Set)=>{let c=0,i=0;const o=k=>()=>{throw new Error(`the relay poke path must not reach RelayHost.${k}`)},m={fetch:(k,E)=>{if(JSON.parse(E?.body??"{}").type!=="relay_shape_subscribe")return Promise.resolve(new Response(void 0,{status:204}));const I=a[i];if(i+=1,I===void 0)throw new Error("the relay asked for more seeds than this fixture supplies");return Promise.resolve(Response.json(I))}},f={get:()=>m,getByName:()=>m,idFromName:k=>k},w={buildShapeDiff:o("buildShapeDiff"),computeOpLogShapeSeed:o("computeOpLogShapeSeed"),currentCdcEpoch:o("currentCdcEpoch"),deliverWhisperLocal:o("deliverWhisperLocal"),dropIfLapsed:k=>n.has((k.deserializeAttachment?.()).connectionId??""),doName:()=>x(g,0),env:()=>({SHARD:f}),getWebSockets:()=>e.getSockets(),maskMetadata:o("maskMetadata"),nextPokeId:()=>(c+=1,`poke-${String(c)}`),readAttachment:k=>k.deserializeAttachment?.(),recordShapePokeFanout:()=>{},resolveShape:o("resolveShape"),rlsMetadata:o("rlsMetadata"),shardBinding:()=>"SHARD",shardJurisdiction:()=>{},sql:()=>t},S=N(w);if(S===void 0)throw new Error("expected a relay link for a `…::relay::N` name");return S},p=e=>new Request("https://relay.internal/_lunora/relay",{body:JSON.stringify(e),headers:{"content-type":"application/json"},method:"POST"}),s=async(e,t,a)=>{const n=await e.seedRelayShape(t,a,u,{identity:void 0,userId:void 0});if(n!=="ok")throw new Error(`seed failed: ${JSON.stringify(n)}`)},r=(e={})=>p({...u,checkpoint:20,epoch:"e1",fromCursor:10,rowsPatch:[{id:"r1",op:"upsert",value:{title:"hello"}}],type:"relay_shape_poke",...e});b("frames a poke as pokeStart → pokePart per shape → pokeEnd, under one poke id",async()=>{const{close:e,createSocket:t,host:a,readFrames:n,sockets:c}=y();try{const i=d(c,a.sql,[{cursor:10,epoch:"e1",frames:[]}]),o=h(c,t,"c-alice","s1");await s(i,o,"s1"),await i.handleControl(r());const f=(await n(o)).map(w=>JSON.parse(w));l(f.map(w=>w.type)).toStrictEqual(["pokeStart","pokePart","pokeEnd"]),l(new Set(f.map(w=>w.pokeId)).size).toBe(1),l(f[1]?.shapeId).toBe("s1"),l(f[2]?.checkpoint).toBe(20)}finally{e?.()}}),b("delivers a poke only to sockets whose cursor matches, and advances them past it",async()=>{const{close:e,createSocket:t,host:a,readFrames:n,sockets:c}=y();try{const i=d(c,a.sql,[{cursor:10,epoch:"e1",frames:[]},{cursor:7,epoch:"e1",frames:[]}]),o=h(c,t,"c-alice","s1"),m=h(c,t,"c-bob","s2");await s(i,o,"s1"),await s(i,m,"s2"),await i.handleControl(r());const f=await n(o);l(f.length).toBe(3);const w=await n(m);l(w.length).toBe(0),await i.handleControl(r());const S=await n(o);l(S.length).toBe(3)}finally{e?.()}}),b("pokes no subscriber the host reports lapsed, and still pokes the others",async()=>{const{close:e,createSocket:t,host:a,readFrames:n,sockets:c}=y();try{const i=new Set,o=d(c,a.sql,[{cursor:10,epoch:"e1",frames:[]},{cursor:10,epoch:"e1",frames:[]}],i),m=h(c,t,"c-alice","s1"),f=h(c,t,"c-bob","s2");await s(o,m,"s1"),await s(o,f,"s2"),i.add("c-bob"),await o.handleControl(r());const w=await n(m),S=await n(f);l(w.length).toBe(3),l(S.length).toBe(0)}finally{e?.()}}),b("skips a socket whose cursor matches under a different CDC epoch",async()=>{const{close:e,createSocket:t,host:a,readFrames:n,sockets:c}=y();try{const i=d(c,a.sql,[{cursor:10,epoch:"e1",frames:[]}]),o=h(c,t,"c-alice","s1");await s(i,o,"s1"),await i.handleControl(r({epoch:"e2"}));const m=await n(o);l(m.length).toBe(0),await i.handleControl(r());const f=await n(o);l(f.length).toBe(3)}finally{e?.()}})}),_("orderBy null placement",()=>{const g=[["a",void 0],["b",3],["c",void 0],["d",1],["e",void 0],["f",3],["g",2],["h",void 0]],u=[{nulls:"first",sort:"asc"},{nulls:"last",sort:"asc"},{nulls:"first",sort:"desc"},{nulls:"last",sort:"desc"}],h=({nulls:p,sort:s})=>{const r=new Map(g.map(([t],a)=>[t,a])),e=s==="asc"?1:-1;return g.toSorted(([t,a],[n,c])=>a!==c?a===void 0?p==="first"?-1:1:c===void 0?p==="first"?1:-1:(a-c)*e:((r.get(t)??0)-(r.get(n)??0))*e).map(([t])=>t)},d=p=>p.map(s=>String(s.label));b("pages every placement in threes with no row skipped or repeated",async()=>{const{close:p,host:s}=y();try{const r=s.sql,e=u.map((i,o)=>`items_${String(o)}`),t={label:v("string"),score:v("number",{notNull:!1})},a={tables:Object.fromEntries(e.map(i=>[i,{indexes:[{fields:["score"],name:"by_score"}],shape:t}]))};B(r,a);let n=17e11;const c=C({clock:()=>(n+=1e3,n),schema:a,sql:r});for(const i of e)for(const[o,m]of g)await c.insert(i,m===void 0?{label:o}:{label:o,score:m});for(const[i,o]of u.entries()){const m=e[i]??"",f=await c.findMany(m,{orderBy:[{score:o}]});l(d(f.page)).toStrictEqual(h(o));const w=[];let S;for(let k=0;k<g.length+2;k+=1){const E=await c.findMany(m,{cursor:S,limit:3,orderBy:[{score:o}]});if(w.push(...d(E.page)),E.isDone)break;S=E.continueCursor}l(w).toStrictEqual(h(o))}}finally{p?.()}})}),_("RLS identity under live subscription",()=>{const g="shard-a",u={args:{},name:"lobby-messages"},h={args:{},name:"my-orders"},d=s=>{const r=[],e=[],t={fetch:(c,i)=>(r.push(JSON.parse(i?.body??"{}")),Promise.resolve(new Response(void 0,{status:204})))},n=N({buildShapeDiff:()=>[{id:"r1",op:"upsert",value:{}}],computeOpLogShapeSeed:()=>({baseCheckpoint:void 0,cursor:10,epoch:"e1",reset:!0,rowsPatch:[]}),currentCdcEpoch:()=>"e1",deliverWhisperLocal:()=>0,dropIfLapsed:()=>!1,doName:()=>g,env:()=>({SHARD:{get:()=>t,getByName:()=>t,idFromName:c=>c}}),getWebSockets:()=>[],maskMetadata:()=>({columns:[]}),nextPokeId:()=>"poke-1",readAttachment:()=>({}),recordShapePokeFanout:()=>{},resolveShape:(c,i,o)=>(e.push(o),c===h.name?{columns:["id"],effectiveWhere:{org:o?.identity?.org??"anonymous"},global:!1,table:"orders"}:{columns:["id"],effectiveWhere:{room:"lobby"},global:!1,table:"messages"}),rlsMetadata:()=>({policies:[]}),shardBinding:()=>"SHARD",shardJurisdiction:()=>{},sql:()=>s});if(n===void 0)throw new Error("expected an owner link for an un-suffixed DO name");return{owner:n,posts:r,resolvedUnder:e}},p=async(s,r)=>{await s.handleControl(new Request("https://owner.internal/_lunora/relay",{body:JSON.stringify({...r,connectionId:"c-alice",identity:{org:"acme"},relayIndex:0,subId:"s1",type:"relay_shape_subscribe",userId:"u1"}),headers:{"content-type":"application/json"},method:"POST"}))};b("seeds a subscriber under its own forwarded identity, never the anonymous one",async()=>{const{close:s,host:r}=y();try{const{owner:e,resolvedUnder:t}=d(r.sql);await p(e,h),l(t.some(a=>a?.userId==="u1"&&a.identity?.org==="acme")).toBe(!0)}finally{s?.()}}),b("routes an identity-scoped shape to a per-socket poke, not the cohort multicast",async()=>{const{close:s,host:r}=y();try{const{owner:e,posts:t}=d(r.sql);await p(e,h),t.length=0,await e.onFlush(new Set(["orders"]),20);const a=t.filter(n=>n.type==="relay_shape_poke");l(a.length).toBe(1),l(a[0]?.targetConnectionId).toBe("c-alice")}finally{s?.()}}),b("still multicasts an identity-blind shape to the whole cohort",async()=>{const{close:s,host:r}=y();try{const{owner:e,posts:t}=d(r.sql);await p(e,u),t.length=0,await e.onFlush(new Set(["messages"]),20);const a=t.filter(n=>n.type==="relay_shape_poke");l(a.length).toBe(1),l(a[0]?.targetConnectionId).toBeUndefined()}finally{s?.()}})})})};export{W as defineEngineContractSuite};
@@ -1,4 +1,4 @@
1
- import{LunoraError as $}from"@lunora/errors";import{f as y,S as k}from"./fts-companion-CE3EmIjk.mjs";import{sql as t}from"drizzle-orm";import{aggregateTableName as R}from"./aggregateTableName-B_CtIQCS.mjs";import{backfillSearchIndexesForTable as w}from"./backfillAggregateIndexes-Pk0KLrfk.mjs";import{migrateCdcLog as b,migrateCdcMeta as P}from"./CDC_LOG_TABLE-BFGgqai8.mjs";import{migrateClientWatermark as B}from"./CLIENT_WATERMARK_TABLE-De7z_OHV.mjs";import{migrateCommitSeq as G}from"./COMMIT_SEQ_FIELD-Da1DjGqo.mjs";import{migrateCompanionState as Y}from"./CompanionMemo-BXU5vfak.mjs";import{migrateGlobalShapeSnapshot as v}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-Bb6-aZuH.mjs";import{migrateIdempotency as W}from"./IDEMPOTENCY_TABLE-COrgeP3O.mjs";import{m as j}from"./ctx-db-relay-shapes-DBobAek2.mjs";import{migrateScheduleOutbox as H}from"./SCHEDULE_OUTBOX_TABLE-iyyiSjsO.mjs";import{m as K}from"./ctx-db-search-state-CPKPy8N6.mjs";import{migrateShapePokeCursor as V}from"./SHAPE_POKE_CURSOR_TABLE-BGvY3sFI.mjs";import{runDrizzle as d,runAll as z}from"./runDrizzle-RC09zZrh.mjs";import{D as Q,d as L,e as p,t as Z,i as J,g as q,a as ee,b as te,A as O}from"./do-sql-105TONaE.mjs";import{renderSql as N}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{migrateDurableStreams as re}from"./appendStreamChunk-BZYgGE9Y.mjs";import{rankTableName as x,sortColumnName as ne}from"./RANK_TIEBREAK-D3ye2GsL.mjs";import{migrateReactorState as oe}from"./REACTOR_STATE_TABLE-D2Mn204f.mjs";import{recordSchemaVersion as ie}from"./SCHEMA_HISTORY_MAX_VERSIONS-CEwFjj-O.mjs";import{ttlIndexColumns as ae}from"./isTtlExpired-DNxmZA6e.mjs";const g=t`_creationTime, id`,D="__by_creation",se="__ttl",de=`, ${N("sqlite",g).sql})`,A="__lunora_framework_indexes",f=e=>e.replaceAll(/[A-Z]/gu,r=>r.toLowerCase());class F extends ${}const M=(e,r,n,a,i,o)=>{const s=t.join(i.map(m=>t`${m} IS NOT NULL`),t` AND `);if(d(e,t`SELECT 1 FROM ${t.identifier(n)} WHERE ${s} GROUP BY ${a} HAVING COUNT(*) > 1 LIMIT 1`).toArray().length>0)throw new F("UNIQUE_INDEX_DUPLICATES",`unique index "${r}" on "${n}" ${o}: existing rows are duplicates under it. De-duplicate the table with a data migration first; the previous index is left in place.`)},S=(e,r,n,a,i,o)=>{const c=d(e,t`SELECT sql FROM sqlite_master WHERE type = 'index' AND name = ${r} COLLATE NOCASE AND tbl_name = ${n} COLLATE NOCASE`).toArray()[0]?.sql;if(c==null)return;const m=E=>{const I=E.indexOf("(");return I===-1?void 0:E.slice(I,E.lastIndexOf(")")+1)},_=m(N("sqlite",L(r,n,a,i)).sql),T=m(c);_===void 0||T===void 0||_===T||(i&&M(e,r,n,a,o,"cannot be re-created with its new column list"),d(e,t`DROP INDEX IF EXISTS ${t.identifier(r)}`))},U=(e,r,n)=>d(e,t`SELECT 1 FROM sqlite_master WHERE type = 'index' AND name = ${r} COLLATE NOCASE AND tbl_name = ${n} COLLATE NOCASE LIMIT 1`).toArray().length>0,C=(e,r,n,a,i,o)=>{i&&!U(e,r,n)&&M(e,r,n,a,o,"cannot be created"),d(e,L(r,n,a,i))},h=(e,r)=>{try{r()}catch(n){if(e===void 0||!(n instanceof F))throw n;e.push(n.message)}},ce=(e,r,n)=>f(r).startsWith(`${f(e)}_`)&&f(r)!==f(`${e}${D}`)&&n!==null&&(n.includes("json_extract(")||n.trimEnd().endsWith(de)),l=new WeakMap,u=(e,r,n)=>{let a=l.get(e);a===void 0&&(a=new Set(d(e,t`SELECT name FROM ${t.identifier(A)}`).toArray().map(i=>f(i.name))),l.set(e,a)),!a.has(f(r))&&(d(e,t`INSERT OR IGNORE INTO ${t.identifier(A)} (name, table_name) VALUES (${r}, ${n})`),a.add(f(r)))},me=(e,r)=>d(e,t`SELECT 1 FROM ${t.identifier(A)} WHERE name = ${r} COLLATE NOCASE LIMIT 1`).toArray().length>0,fe=(e,r)=>{const n=d(e,t`SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ${A} COLLATE NOCASE`).toArray().length>0;if(d(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(A)} (name TEXT PRIMARY KEY COLLATE NOCASE, table_name TEXT NOT NULL)`),!n)for(const a of r){const i=d(e,t`SELECT name, sql FROM sqlite_master WHERE type = 'index' AND tbl_name = ${a} COLLATE NOCASE AND sql IS NOT NULL`).toArray();for(const{name:o,sql:s}of i)ce(a,o,s)&&u(e,o,a)}},Ee=(e,r,n)=>{const a=new Set([...n].map(o=>f(o))),i=d(e,t`SELECT "l"."name" FROM ${t.identifier(A)} AS "l" WHERE "l"."table_name" = ${r} COLLATE NOCASE`).toArray();for(const{name:o}of i)a.has(f(o))||(d(e,t`DROP INDEX IF EXISTS ${t.identifier(o)}`),d(e,t`DELETE FROM ${t.identifier(A)} WHERE ${t.identifier(A)}."name" = ${o}`),l.get(e)?.delete(f(o)))},_e=(e,r,n,a)=>{const i=`${r}${se}`,o=new Set([...a].map(c=>f(c)));if(n.ttlPolicy===void 0||o.has(f(i))||U(e,i,r)&&!me(e,i))return;const s=ae(n.ttlPolicy.field,n.softDeleteMode?.field);a.add(i);try{S(e,i,r,s,!1,[]),d(e,L(i,r,s,!1)),u(e,i,r)}catch{}},Te=(e,r,n,a)=>{const i=new Set;for(const o of n.indexes){const s=`${r}_${o.name}`,c=o.unique??!1,m=o.fields.map(E=>p(E)),_=t.join(m,t`, `),T=c?_:t`${_}, ${g}`;i.add(s),h(a,()=>{S(e,s,r,T,c,m),C(e,s,r,T,c,m),u(e,s,r)})}for(const[o,s]of Z(n)){if(!s.unique)continue;const c=p(o),m=`${r}_unique_${o}`;i.add(m),h(a,()=>{S(e,m,r,c,!0,[c]),C(e,m,r,c,!0,[c]),u(e,m,r)})}_e(e,r,n,i),Ee(e,r,i)},Ae=(e,r,n)=>{if(!(!n.searchIndexes||n.searchIndexes.length===0||!J(e))){for(const a of n.searchIndexes)z(e,y(k(r,a.name)));w(e,r,n)}},Ie=(e,r,n)=>{if(n.geoIndexes)for(const a of n.geoIndexes){const i=q(r,a.name);d(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(i)} (${t.identifier("__id__")} TEXT PRIMARY KEY, ${t.identifier("__geohash__")} TEXT NOT NULL, ${t.identifier("__lat__")} REAL NOT NULL, ${t.identifier("__lng__")} REAL NOT NULL)`);const o=`${r}__geo_${a.name}__btree`;d(e,L(o,i,t`${t.identifier("__geohash__")} ASC, ${t.identifier("__id__")} ASC`,!1))}},Le=(e,r,n)=>{if(n.aggregateIndexes)for(const a of n.aggregateIndexes){const i=R(r,a.name);d(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(i)} (${ee} TEXT PRIMARY KEY, ${te} REAL, ${O} INTEGER NOT NULL DEFAULT 0)`),d(e,t`PRAGMA table_info(${t.identifier(i)})`).toArray().some(s=>s.name==="__count__")||d(e,t`ALTER TABLE ${t.identifier(i)} ADD COLUMN ${O} INTEGER NOT NULL DEFAULT 0`)}},Se=(e,r,n)=>{const a=d(e,t`PRAGMA table_info(${t.identifier(r)})`).toArray().map(i=>i.name).filter(i=>i.startsWith("__sort_k"));a.length>0&&(a.length!==n.length||a.some((i,o)=>i!==n[o]))&&d(e,t`DROP TABLE ${t.identifier(r)}`)},le=(e,r,n)=>{if(n.rankIndexes)for(const a of n.rankIndexes){const i=x(r,a.name),o=a.sortBy.map((E,I)=>ne(I)),s=o.map(E=>t`${t.identifier(E)} BLOB`),c=s.length>0?t`, ${t.join(s,t`, `)}`:t``;Se(e,i,o),d(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(i)} (${t.identifier("__id__")} TEXT PRIMARY KEY, ${t.identifier("__partition__")} TEXT NOT NULL${c})`);const m=[t`${t.identifier("__partition__")} ASC`];for(const[E,I]of o.entries()){const X=a.sortBy[E]?.direction;m.push(t`${t.identifier(I)} ${t.raw(X==="desc"?"DESC":"ASC")}`)}m.push(t`${t.identifier("__id__")} ASC`);const _=`${r}__rank_${a.name}__btree`,T=t.join(m,t`, `);S(e,_,i,T,!1,[]),d(e,L(_,i,T,!1))}},ve=(e,r,n={})=>{const a=n.deferBlockedUniqueIndexes?[]:void 0;l.delete(e),n.schemaSnapshot!==void 0&&ie(e,n.schemaSnapshot.hash,n.schemaSnapshot.json),K(e),fe(e,Object.entries(r.tables).filter(([,o])=>o.shardMode?.kind!=="global").map(([o])=>o));const i=[];for(const[o,s]of Object.entries(r.tables))s.shardMode?.kind!=="global"&&(d(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(o)} (
1
+ import{LunoraError as $}from"@lunora/errors";import{f as y,S as k}from"./fts-companion-CE3EmIjk.mjs";import{sql as t}from"drizzle-orm";import{aggregateTableName as R}from"./aggregateTableName-B_CtIQCS.mjs";import{backfillSearchIndexesForTable as w}from"./backfillAggregateIndexes-BwCpPW7h.mjs";import{migrateCdcLog as b,migrateCdcMeta as P}from"./CDC_LOG_TABLE-BFGgqai8.mjs";import{migrateClientWatermark as B}from"./CLIENT_WATERMARK_TABLE-De7z_OHV.mjs";import{migrateCommitSeq as G}from"./COMMIT_SEQ_FIELD-Da1DjGqo.mjs";import{migrateCompanionState as Y}from"./CompanionMemo-BXU5vfak.mjs";import{migrateGlobalShapeSnapshot as v}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-Bb6-aZuH.mjs";import{migrateIdempotency as W}from"./IDEMPOTENCY_TABLE-COrgeP3O.mjs";import{m as j}from"./ctx-db-relay-shapes-DBobAek2.mjs";import{migrateScheduleOutbox as H}from"./SCHEDULE_OUTBOX_TABLE-iyyiSjsO.mjs";import{m as K}from"./ctx-db-search-state-CPKPy8N6.mjs";import{migrateShapePokeCursor as V}from"./SHAPE_POKE_CURSOR_TABLE-BGvY3sFI.mjs";import{runDrizzle as d,runAll as z}from"./runDrizzle-RC09zZrh.mjs";import{D as Q,d as L,e as p,t as Z,i as J,g as q,a as ee,b as te,A as O}from"./do-sql-105TONaE.mjs";import{renderSql as N}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{migrateDurableStreams as re}from"./appendStreamChunk-BZYgGE9Y.mjs";import{rankTableName as x,sortColumnName as ne}from"./RANK_TIEBREAK-D3ye2GsL.mjs";import{migrateReactorState as oe}from"./REACTOR_STATE_TABLE-D2Mn204f.mjs";import{recordSchemaVersion as ie}from"./SCHEMA_HISTORY_MAX_VERSIONS-CEwFjj-O.mjs";import{ttlIndexColumns as ae}from"./isTtlExpired-DNxmZA6e.mjs";const g=t`_creationTime, id`,D="__by_creation",se="__ttl",de=`, ${N("sqlite",g).sql})`,A="__lunora_framework_indexes",f=e=>e.replaceAll(/[A-Z]/gu,r=>r.toLowerCase());class F extends ${}const M=(e,r,n,a,i,o)=>{const s=t.join(i.map(m=>t`${m} IS NOT NULL`),t` AND `);if(d(e,t`SELECT 1 FROM ${t.identifier(n)} WHERE ${s} GROUP BY ${a} HAVING COUNT(*) > 1 LIMIT 1`).toArray().length>0)throw new F("UNIQUE_INDEX_DUPLICATES",`unique index "${r}" on "${n}" ${o}: existing rows are duplicates under it. De-duplicate the table with a data migration first; the previous index is left in place.`)},S=(e,r,n,a,i,o)=>{const c=d(e,t`SELECT sql FROM sqlite_master WHERE type = 'index' AND name = ${r} COLLATE NOCASE AND tbl_name = ${n} COLLATE NOCASE`).toArray()[0]?.sql;if(c==null)return;const m=E=>{const I=E.indexOf("(");return I===-1?void 0:E.slice(I,E.lastIndexOf(")")+1)},_=m(N("sqlite",L(r,n,a,i)).sql),T=m(c);_===void 0||T===void 0||_===T||(i&&M(e,r,n,a,o,"cannot be re-created with its new column list"),d(e,t`DROP INDEX IF EXISTS ${t.identifier(r)}`))},U=(e,r,n)=>d(e,t`SELECT 1 FROM sqlite_master WHERE type = 'index' AND name = ${r} COLLATE NOCASE AND tbl_name = ${n} COLLATE NOCASE LIMIT 1`).toArray().length>0,C=(e,r,n,a,i,o)=>{i&&!U(e,r,n)&&M(e,r,n,a,o,"cannot be created"),d(e,L(r,n,a,i))},h=(e,r)=>{try{r()}catch(n){if(e===void 0||!(n instanceof F))throw n;e.push(n.message)}},ce=(e,r,n)=>f(r).startsWith(`${f(e)}_`)&&f(r)!==f(`${e}${D}`)&&n!==null&&(n.includes("json_extract(")||n.trimEnd().endsWith(de)),l=new WeakMap,u=(e,r,n)=>{let a=l.get(e);a===void 0&&(a=new Set(d(e,t`SELECT name FROM ${t.identifier(A)}`).toArray().map(i=>f(i.name))),l.set(e,a)),!a.has(f(r))&&(d(e,t`INSERT OR IGNORE INTO ${t.identifier(A)} (name, table_name) VALUES (${r}, ${n})`),a.add(f(r)))},me=(e,r)=>d(e,t`SELECT 1 FROM ${t.identifier(A)} WHERE name = ${r} COLLATE NOCASE LIMIT 1`).toArray().length>0,fe=(e,r)=>{const n=d(e,t`SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ${A} COLLATE NOCASE`).toArray().length>0;if(d(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(A)} (name TEXT PRIMARY KEY COLLATE NOCASE, table_name TEXT NOT NULL)`),!n)for(const a of r){const i=d(e,t`SELECT name, sql FROM sqlite_master WHERE type = 'index' AND tbl_name = ${a} COLLATE NOCASE AND sql IS NOT NULL`).toArray();for(const{name:o,sql:s}of i)ce(a,o,s)&&u(e,o,a)}},Ee=(e,r,n)=>{const a=new Set([...n].map(o=>f(o))),i=d(e,t`SELECT "l"."name" FROM ${t.identifier(A)} AS "l" WHERE "l"."table_name" = ${r} COLLATE NOCASE`).toArray();for(const{name:o}of i)a.has(f(o))||(d(e,t`DROP INDEX IF EXISTS ${t.identifier(o)}`),d(e,t`DELETE FROM ${t.identifier(A)} WHERE ${t.identifier(A)}."name" = ${o}`),l.get(e)?.delete(f(o)))},_e=(e,r,n,a)=>{const i=`${r}${se}`,o=new Set([...a].map(c=>f(c)));if(n.ttlPolicy===void 0||o.has(f(i))||U(e,i,r)&&!me(e,i))return;const s=ae(n.ttlPolicy.field,n.softDeleteMode?.field);a.add(i);try{S(e,i,r,s,!1,[]),d(e,L(i,r,s,!1)),u(e,i,r)}catch{}},Te=(e,r,n,a)=>{const i=new Set;for(const o of n.indexes){const s=`${r}_${o.name}`,c=o.unique??!1,m=o.fields.map(E=>p(E)),_=t.join(m,t`, `),T=c?_:t`${_}, ${g}`;i.add(s),h(a,()=>{S(e,s,r,T,c,m),C(e,s,r,T,c,m),u(e,s,r)})}for(const[o,s]of Z(n)){if(!s.unique)continue;const c=p(o),m=`${r}_unique_${o}`;i.add(m),h(a,()=>{S(e,m,r,c,!0,[c]),C(e,m,r,c,!0,[c]),u(e,m,r)})}_e(e,r,n,i),Ee(e,r,i)},Ae=(e,r,n)=>{if(!(!n.searchIndexes||n.searchIndexes.length===0||!J(e))){for(const a of n.searchIndexes)z(e,y(k(r,a.name)));w(e,r,n)}},Ie=(e,r,n)=>{if(n.geoIndexes)for(const a of n.geoIndexes){const i=q(r,a.name);d(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(i)} (${t.identifier("__id__")} TEXT PRIMARY KEY, ${t.identifier("__geohash__")} TEXT NOT NULL, ${t.identifier("__lat__")} REAL NOT NULL, ${t.identifier("__lng__")} REAL NOT NULL)`);const o=`${r}__geo_${a.name}__btree`;d(e,L(o,i,t`${t.identifier("__geohash__")} ASC, ${t.identifier("__id__")} ASC`,!1))}},Le=(e,r,n)=>{if(n.aggregateIndexes)for(const a of n.aggregateIndexes){const i=R(r,a.name);d(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(i)} (${ee} TEXT PRIMARY KEY, ${te} REAL, ${O} INTEGER NOT NULL DEFAULT 0)`),d(e,t`PRAGMA table_info(${t.identifier(i)})`).toArray().some(s=>s.name==="__count__")||d(e,t`ALTER TABLE ${t.identifier(i)} ADD COLUMN ${O} INTEGER NOT NULL DEFAULT 0`)}},Se=(e,r,n)=>{const a=d(e,t`PRAGMA table_info(${t.identifier(r)})`).toArray().map(i=>i.name).filter(i=>i.startsWith("__sort_k"));a.length>0&&(a.length!==n.length||a.some((i,o)=>i!==n[o]))&&d(e,t`DROP TABLE ${t.identifier(r)}`)},le=(e,r,n)=>{if(n.rankIndexes)for(const a of n.rankIndexes){const i=x(r,a.name),o=a.sortBy.map((E,I)=>ne(I)),s=o.map(E=>t`${t.identifier(E)} BLOB`),c=s.length>0?t`, ${t.join(s,t`, `)}`:t``;Se(e,i,o),d(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(i)} (${t.identifier("__id__")} TEXT PRIMARY KEY, ${t.identifier("__partition__")} TEXT NOT NULL${c})`);const m=[t`${t.identifier("__partition__")} ASC`];for(const[E,I]of o.entries()){const X=a.sortBy[E]?.direction;m.push(t`${t.identifier(I)} ${t.raw(X==="desc"?"DESC":"ASC")}`)}m.push(t`${t.identifier("__id__")} ASC`);const _=`${r}__rank_${a.name}__btree`,T=t.join(m,t`, `);S(e,_,i,T,!1,[]),d(e,L(_,i,T,!1))}},ve=(e,r,n={})=>{const a=n.deferBlockedUniqueIndexes?[]:void 0;l.delete(e),n.schemaSnapshot!==void 0&&ie(e,n.schemaSnapshot.hash,n.schemaSnapshot.json),K(e),fe(e,Object.entries(r.tables).filter(([,o])=>o.shardMode?.kind!=="global").map(([o])=>o));const i=[];for(const[o,s]of Object.entries(r.tables))s.shardMode?.kind!=="global"&&(d(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(o)} (
2
2
  id TEXT PRIMARY KEY,
3
3
  _creationTime REAL NOT NULL,
4
4
  ${t.identifier(Q)} TEXT NOT NULL
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/shard-engine",
3
- "version": "1.0.0-alpha.191",
3
+ "version": "1.0.0-alpha.193",
4
4
  "description": "Host-neutral reactive engine for Lunora: per-shard state, OCC, CDC, reactive subscriptions, and the poke protocol. Consumes @lunora/platform host contracts and can be mounted on any platform host.",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -48,7 +48,7 @@
48
48
  "access": "public"
49
49
  },
50
50
  "dependencies": {
51
- "@lunora/errors": ">=1.0.0-alpha.77 <2.0.0-0",
51
+ "@lunora/errors": ">=1.0.0-alpha.87 <2.0.0-0",
52
52
  "@lunora/platform": "1.0.0-alpha.80",
53
53
  "@lunora/wire": "1.0.0-alpha.6",
54
54
  "drizzle-orm": "1.0.0-rc.5"
@@ -1 +0,0 @@
1
- import{LunoraError as S}from"@lunora/errors";import{decodeWire as p,encodeWire as O}from"@lunora/wire";import{v as _}from"./accepts-null-D1zmJbyR.mjs";import{r as E}from"./json-field-path-DeJW4U9z.mjs";import{SEEK_RANGE as A}from"./RELATION_EXISTS_KEY-wxgj6rSL.mjs";const R="id",h=e=>e.at(-1)?.direction==="desc"?"desc":"asc",b=new Set(["_id","id"]),F=new Set(["_creationTime","_id","id"]),g=(e,t)=>{if(F.has(e))return!1;const n=t?.[e];return n===void 0?!0:n.kind==="optional"||n._meta?.column?.notNull===!1||_(n)},T=new Set(["AND","NOT","OR"]),U=e=>{const t=new Set;if(typeof e!="object"||Array.isArray(e))return t;for(const[n,r]of Object.entries(e)){if(T.has(n))continue;if(r===null||typeof r!="object"||Array.isArray(r)){t.add(n);continue}const o=Object.keys(r);o.length===1&&o[0]==="eq"&&t.add(n)}return t},x=(e,t)=>{const n=[];for(const r of e??[])r.unique===!0&&n.push(r.fields);for(const[r,o]of Object.entries(t??{}))o._meta?.column?.unique===!0&&n.push([r]);return n},I=(e,t)=>(t??[]).some(n=>n.length>0&&n.every(r=>e.has(r))),y=e=>e.nulls===void 0?e.direction!=="desc":e.nulls==="first",K=e=>e?" NULLS FIRST":" NULLS LAST",D=e=>{if(typeof e!="object"||e===null)return!1;const{nulls:t,sort:n}=e;return(n==="asc"||n==="desc")&&(t==="first"||t==="last")},L=(e,t,n)=>{if(t!=="asc"&&t!=="desc"&&!D(t))throw new S("VALIDATION_ERROR",`orderBy "${e}": expected "asc", "desc" or { sort: "asc" | "desc", nulls: "first" | "last" }`);const r=typeof t=="string"?t:t.sort,o=g(e,n);return typeof t=="string"||!o||y({direction:r})===(t.nulls==="first")?{direction:r,field:e,nullable:o}:{direction:r,field:e,nullable:o,nulls:t.nulls}},J=(e,t,n)=>{const r=[],o=new Set(n?.pinned);let l="asc";for(const i of e??[])for(const[c,s]of Object.entries(i)){const u=L(c,s,t),{direction:f}=u;l=f,o.add(c),!n?.pinned?.has(c)&&r.push(u)}return r.length===0?[{direction:l,field:"_creationTime",nullable:!1}]:(r.some(i=>b.has(i.field)||i.field==="_creationTime")||I(o,n?.uniqueBy)||r.push({direction:h(r),field:"_creationTime",nullable:!1}),r)},w=/[\u0080-\u{10FFFF}]/u,v=e=>{if(!w.test(e))return btoa(e);const t=new TextEncoder().encode(e);let n="";for(const r of t)n+=String.fromCodePoint(r);return btoa(n)},C=e=>{const t=atob(e),n=Uint8Array.from(t,r=>r.codePointAt(0)??0);return new TextDecoder().decode(n)},a="~4",z=(e,t)=>{const n=t.map(r=>E(e,r.field)??null);return n.push(e._id),a+v(JSON.stringify(O(n)))},d=()=>new S("BAD_REQUEST","invalid cursor"),G=e=>{if(!e.startsWith(a))throw d();let t;try{t=p(JSON.parse(C(e.slice(a.length))))}catch{throw d()}if(!Array.isArray(t))throw d();return t.map(n=>n??null)},m=(e,t,n,r)=>{const{field:o}=e,l=e.direction!=="desc"===n,i=y(e)===n;if(t===null)return i?r?{OR:[{[o]:{isNull:!1}},{[o]:{isNull:!0}}]}:{[o]:{isNull:!1}}:r?{[o]:{isNull:!0}}:{OR:[]};let c=l?"gt":"lt";r&&(c=l?"gte":"lte");const s={[o]:{[c]:t,[A]:!0}};return i||!e.nullable?s:{OR:[s,{[o]:{isNull:!0}}]}},N=(e,t,n,r)=>{const o=e.some(s=>b.has(s.field))?e:[...e,{direction:h(e),field:R,nullable:!1}];if(t.length<o.length)throw d();const l=s=>{const u=o[s];if(u===void 0)throw d();const f=m(u,t[s],n,r&&s===o.length-1);return s===o.length-1?f:{OR:[f,{AND:[{[u.field]:{eq:t[s]}},l(s+1)]}]}},i=l(0),[c]=o;return o.length<2||c===void 0||c.nullable||t[0]===null?i:{AND:[m(c,t[0],n,!0),i]}},H=(e,t)=>N(e,t,!0,!1),M=(e,t)=>N(e,t,!1,!0),j=["_id","_creationTime"],Q=(e,t,n)=>{if(!t)return e;const r=new Set([...t,...j,...n?Object.keys(n):[]]);return e.map(o=>{const l={};for(const i of r)i in o&&(l[i]=o[i]);return l})},X=(e,t)=>e&&t!==!0?{[e.field]:{isNull:!0}}:void 0,Y=(e,t)=>t===void 0||e[t]===null||e[t]===void 0;export{a as CURSOR_PREFIX,Q as applySelect,M as buildSeekBeforeWhere,H as buildSeekWhere,G as decodeCursor,z as encodeCursor,U as equalityPinnedFields,C as fromBase64,Y as isLiveForCompanion,J as normalizeOrderKeys,y as nullsFirstOf,K as nullsOrderSuffix,X as softDeleteScope,h as tiebreakDirectionFor,v as toBase64,x as uniqueIndexFields};
@@ -1 +0,0 @@
1
- import{LunoraError as $}from"@lunora/errors";import{q as $t}from"./MAX_TOKEN_LENGTH-iFEGEcDL-DBPC6ZWl.mjs";import{S as qn,l as qe,s as Pn}from"./fts-companion-CE3EmIjk.mjs";import{decodeWire as Un,stableWireKey as Pt}from"@lunora/wire";import{sql as a}from"drizzle-orm";import{throwingScheduler as On,aggregateSqlFunction as Pe,normalizeCountArgument as Gn}from"./AGGREGATE_SQL_FUNCTION-C_ZipS9R.mjs";import{aggregateTableName as rt,encodeAggregateKey as it,readAggregateValue as st}from"./aggregateTableName-B_CtIQCS.mjs";import{mergeWhere as Q,CountRlsUnsupportedError as ct,selectIndexForGroupBy as jn,selectIndexForCount as Hn,selectIndexForAggregate as Kn}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{backfillSearchIndexesForTable as Nn,searchIndexCoversTable as Qn}from"./backfillAggregateIndexes-Pk0KLrfk.mjs";import{backfillAggregateIndexes as ji,backfillRankIndexes as Hi,backfillSearchIndexes as Ki}from"./backfillAggregateIndexes-Pk0KLrfk.mjs";import{appendCdcChange as Vn,readCdcDocAtOrBefore as Jn}from"./CDC_LOG_TABLE-BFGgqai8.mjs";import{CDC_LOG_TABLE as Qi,applyCdcChanges as Vi,bumpCdcEpoch as Ji,cdcCanVouchFor as zi,cdcForkedError as Yi,cdcSeqLeavingRows as Xi,cdcTouchesTables as Zi,cdcTrimmedError as es,compactCdcDocs as ts,cursorBelowRetainedFloor as ns,minCdcReplayableSeq as os,minCdcSeq as rs,readCdcChangeKeys as is,readCdcChanges as ss,readCdcCursor as cs,readCdcEpoch as as,trimCdcChanges as ds}from"./CDC_LOG_TABLE-BFGgqai8.mjs";import{allocateCommitSeq as zn,COMMIT_SEQ_FIELD as Yn}from"./COMMIT_SEQ_FIELD-Da1DjGqo.mjs";import{createCompanionSync as Xn}from"./createCompanionSync-CEht4hXX.mjs";import{isMemoryTable as Ut}from"./clearMemoryTables-aMRERF0w.mjs";import{computeRankPage as Ot}from"./computeRankPage-xm-70mLy.mjs";import{SCAN_DEP as G,PRIMARY_READ as Zn}from"./SCAN_DEP-B4Uu4g7l.mjs";import{runSql as he,runDrizzle as K}from"./runDrizzle-RC09zZrh.mjs";import{p as eo,j as ht,D as ie,r as xe,W as to,k as le,b as Ue,A as at,a as Oe,m as ue,e as fe,s as no,t as oo,u as ro,i as io,q as Gt,h as pn,g as so}from"./do-sql-105TONaE.mjs";import{renderSql as gn,unionAll as yn,WORKERD_SQLITE_LIMITS as En}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{a as co,u as ao}from"./estimate-bytes-C-C35VXL.mjs";import{coveringGeohashes as lo,boundingBoxGeohashes as uo,haversineMeters as fo,pointInBoundingBox as ho}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{NotFoundError as wo}from"./NotFoundError-BhF7FeFr.mjs";import{resolvePatch as po,assertPatchAllowed as go,operatorFields as yo,readPatchField as jt}from"./assertPatchAllowed-CA_H466g.mjs";import{tiebreakDirectionFor as Eo,encodeCursor as wt,nullsOrderSuffix as mo,normalizeOrderKeys as Ht,uniqueIndexFields as $o,buildSeekWhere as Ro,decodeCursor as Kt,buildSeekBeforeWhere as So,softDeleteScope as Ae,applySelect as mn}from"./CURSOR_PREFIX-6offuG6M.mjs";import{rankTableName as Nt,sortColumnName as Qt,resolveRankPartition as vo,encodePartitionKey as _o,RANK_TIEBREAK as To,rankPivotConditionSql as Ao}from"./RANK_TIEBREAK-D3ye2GsL.mjs";import{UNVOUCHABLE_DEP as Vt}from"./UNVOUCHABLE_DEP-Ds9gxVqs.mjs";import{idIndexKey as Io,withUnknownIndexKeys as xo,indexKeysForRow as bo,buildIndexRange as Co}from"./buildIndexRange-BTChxh3k.mjs";import{r as Qe,j as be,c as Z,t as ze,i as Jt}from"./where-sql-BjY4rnqb.mjs";import{serializeSqlValue as Ce}from"./serializeSqlValue-DeoBMpZ2.mjs";import{quoteIdentifier as Me}from"./quoteIdentifier-CObIFRhb.mjs";import{whereOfFilter as Mo,isPushableWhere as Do}from"./isPushableWhere-BeYAOjUb.mjs";import{deriveRelationEdges as ko,findRelated as Lo}from"./RELATED_DEFAULT_LIMIT-CVqN4JEu.mjs";import{assertFlatPredicate as dt,findManyPage as Fo,resolveRelationPredicates as Bo,composeReadPredicate as Wo}from"./DEFAULT_MAX_RELATION_KEYS-BBtZ_jRj.mjs";import{describeRelationWrites as qo}from"./describeRelationWrites-omar6-u9.mjs";import{runRowValidators as Ge,transformOnlyDefinition as Po,applyInsertDefaults as pt,resolveWith as Uo,relationHooks as Oo,applyOnDelete as Go,fanOutScalarCounts as jo}from"./applyInsertDefaults-CVukTkQ5.mjs";import{guardWriter as Ho}from"./RLS_UNWRAP_SYMBOL-H6J96vgK.mjs";import{mayHoldProjectedValue as Ko}from"./BIGINT_KEY_DIGITS-DE6yshOt.mjs";import{createSystemReader as No}from"./createSystemReader-BSCxr8Qs.mjs";import{ConflictError as se}from"./ConflictError-C8GtJmjS.mjs";import{hasTrigger as zt,runTriggers as Qo}from"./hasTrigger-CjlwI4le.mjs";import{advanceClientWatermark as us,migrateClientWatermark as fs,readClientWatermark as hs}from"./CLIENT_WATERMARK_TABLE-De7z_OHV.mjs";import{IDEMPOTENCY_TABLE as ps,readIdempotent as gs,trimIdempotent as ys,writeIdempotent as Es}from"./IDEMPOTENCY_TABLE-COrgeP3O.mjs";import{runShardMigrations as $s}from"./runShardMigrations-BPFg3Ht6.mjs";import{selectShapeMembers as Ss,selectShapeRows as vs}from"./selectShapeMembers-Dqx_m7BF.mjs";const Vo=n=>{const r=atob(n),o=Uint8Array.from(r,s=>s.codePointAt(0)??0);return new TextDecoder().decode(o)},Jo=()=>new $("BAD_REQUEST","invalid cursor"),Yt=16,Xt=8,z=1024,Rt=(n,r)=>r.query(n),zo=(n,r)=>{if(n.length===0)return 0;let o=0;for(const[s,c]of r.entries()){const u=s===r.length-1;let g=0;for(const m of n)(u?m.startsWith(c):m===c)&&(g+=1);if(g===0)return 0;o+=g}return o},Yo=(n,r)=>{if(!r)return{exact:!0,lower:n,upper:n};const o=[...n].at(-1)??"",s=(o.codePointAt(0)??0)+1;if(s>=55296&&s<=57343||s>1114111)return{exact:!0,lower:n,upper:n};const c=n.slice(0,n.length-o.length);return{exact:!1,lower:n,upper:c+String.fromCodePoint(s)}},Xo=(n,r,o)=>{const s={eq:(c,u)=>{if(!n.definition.filterFields?.includes(c))throw new $("INTERNAL",`field "${c}" is not a filter field of search index "${n.indexName}" on table "${r}"`);if(n.filters.length>=Xt)throw new $("BAD_REQUEST",`search index "${n.indexName}" on table "${r}": at most ${String(Xt)} .eq() filters are supported per search query`);return n.filters.push({field:c,value:u}),s},search:(c,u)=>{const g=n;if(c!==g.definition.field)throw new $("INTERNAL",`search index "${g.indexName}" on table "${r}" indexes "${g.definition.field}", not "${c}"`);const m=Rt(u,o).length;if(m>Yt)throw new $("BAD_REQUEST",`search index "${g.indexName}" on table "${r}": at most ${String(Yt)} search terms are supported (got ${String(m)})`);return g.field=c,g.query=u,g.hasQuery=!0,s}};return s},Zo=n=>{if(n.length>z)throw new $("BAD_REQUEST",`more than ${String(z)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},er=n=>Math.min(n.offset+n.numItems+1,z),tr=n=>btoa(`search:${String(n)}`),nr=n=>{let r;try{r=Vo(n)}catch{return}if(!r.startsWith("search:"))return;const o=Number(r.slice(7));return Number.isInteger(o)&&o>=0?o:void 0},or=n=>{if(typeof n.endCursor=="string")throw new $("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");if(!Number.isFinite(n.numItems))throw new $("BAD_REQUEST",`search pagination needs a finite numItems, got ${String(n.numItems)}`);const r=Math.max(0,Math.floor(n.numItems)),o=n.cursor?nr(n.cursor):0;if(o===void 0)throw Jo();if(o+r>=z)throw new $("BAD_REQUEST",`search pagination reaches the ${String(z)}-document limit (offset ${String(o)} + ${String(r)} requested) — a page must end below the cap so the probe row that answers \`hasMore\` still fits: retry with numItems ${String(Math.max(1,z-o-1))} or fewer, or narrow the query or the filters instead`);return{numItems:r,offset:o}},rr=(n,r)=>{const o=r.offset+r.numItems,s=r.numItems>0&&n.length>o;return{continueCursor:s?tr(o):null,isDone:!s,page:n.slice(r.offset,o)}},ir=n=>{if(n===void 0)return z+1;if(!Number.isFinite(n))return z;const r=Math.max(0,Math.floor(n));if(r>z)throw new $("BAD_REQUEST",`search returns at most ${String(z)} documents (asked for ${String(r)}) — narrow the query or paginate instead`);return r},$n=500,Rn=(n,r,o)=>{if(n!==void 0&&n!==Number.POSITIVE_INFINITY&&(!Number.isInteger(n)||n<0))throw o(`${r}: batch limit must be a non-negative integer`);return n??$n},Sn=(n,r,o,s)=>{if(n>r)throw s(`${o}: batch of ${String(n)} exceeds the limit of ${String(r)} (raise options.limit or chunk the call)`)},sr=32,cr=1024,vn=(n,r,o,s)=>{const c=`SELECT id, _creationTime, ${Me(ie)} FROM ${Me(n)}`,u=`ORDER BY ${o}${s===void 0?"":` LIMIT ${String(s)}`}`;return r===void 0?Qe(`${c} ${u}`):be(`${c} WHERE `,r,` ${u}`)},Ye={fieldRef:n=>Qe(ht(n)),rangeTypeGuard:(n,r)=>Qe(eo(n,r)),serialize:Ce},ar=n=>n===void 0?"":mo(n==="first"),_n=n=>{const r=n.map(o=>`${ht(o.field)} ${o.direction==="desc"?"DESC":"ASC"}${ar(o.nulls)}`);return n.some(o=>o.field==="_id"||o.field==="id")||r.push(`${ht("id")} ${Eo(n)==="desc"?"DESC":"ASC"}`),r.join(", ")},dr={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},Tn=n=>new Set(n.sqlConditions.filter(r=>r.comparator==="=").map(r=>r.field)),lr=n=>{const r=Tn(n);let o=0;for(;o<n.indexFields.length&&r.has(n.indexFields[o]??"");)o+=1;return n.indexFields.slice(o)},ur=(n,r)=>{const o=n.order,s=lr(n),{shape:c}=r;return s.length>0?Ht(s.map(u=>({[u]:o})),c,{pinned:Tn(n),uniqueBy:$o(r.indexes,c)}):Ht([{_creationTime:o}],c)},fr=(n,r,o,s)=>{const c=n.sqlConditions.map(u=>({[u.field]:{[dr[u.comparator]??"eq"]:u.value}}));if(o&&c.push(Ro(r,Kt(o))),s&&c.push(So(r,Kt(s))),c.length!==0)return c.length===1?c[0]:{AND:c}},hr=n=>{if(n.want!==void 0)return n.selective?Math.max(n.want,sr):n.want},gt=(n,r,o,s,c,u,g)=>{const m=ur(s,o),y=_n(m),d=[],{filters:b,want:_}=u;let v=u.cursor??void 0,x=hr(u);if(_===0)return{documents:d,orderKeys:m};for(;;){const W=Z(fr(s,m,v,u.endCursor),Ye,ze),q=vn(r,c&&W?be(W," AND ",c):c??W,y,x),B=he(n,q.text,...q.params).toArray();let U={};g(B.length);for(const j of B)if(U=xe(j),b.every(ee=>ee(U))&&d.push(U)===_)return{documents:d,orderKeys:m};if(x===void 0||B.length<x)return{documents:d,orderKeys:m};v=wt(U,m),x=Math.max(x,Math.min(x*2,cr))}},wr=(n,r,o,s,c,u,g,m)=>{const y=Math.max(0,Math.floor(c.numItems));if(typeof c.endCursor=="string"){const{documents:W,orderKeys:q}=gt(n,r,o,s,u,{cursor:c.cursor,endCursor:c.endCursor,filters:g.all,selective:g.selective,want:void 0},m),B=W.length>=2?W[Math.floor(W.length/2)-1]:void 0;return{continueCursor:c.endCursor,isDone:!0,page:W,splitCursor:B?wt(B,q):null}}const{documents:d,orderKeys:b}=gt(n,r,o,s,u,{cursor:c.cursor,filters:g.all,selective:g.selective,want:y+1},m),_=d.length>y,v=_?d.slice(0,y):d,x=v.at(-1);return{continueCursor:_&&x?wt(x,b):null,isDone:!_,page:v}},Xe=n=>{const r=new Map;return o=>{const s=r.get(o);if(s!==void 0)return s;const c=n(Me(o));return r.set(o,c),c}},we=Me(ie),pr=Xe(n=>`INSERT INTO ${n} (id, _creationTime, ${we}) VALUES (?, ?, ?)`),Zt=Xe(n=>`UPDATE ${n} SET ${we} = ? WHERE id = ? AND ${we} = ?`),gr=Xe(n=>`UPDATE ${n} SET _creationTime = ?, ${we} = ? WHERE id = ? AND ${we} = ?`),yr=Xe(n=>`DELETE FROM ${n} WHERE id = ? AND ${we} = ?`),Er="SELECT changes() AS changed",en=new Map,mr="",$r=n=>{const r=JSON.stringify(n),o=en.get(r);if(o!==void 0)return o;const s=n.map(u=>a`SELECT ${a.raw(`'${u.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${a.identifier(ie)} FROM ${a.identifier(u)} WHERE id = ${mr}`),{sql:c}=gn("sqlite",a`${yn(s)} LIMIT 1`);return en.set(r,c),c},Rr=(n,r)=>r.map(()=>n),Sr=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,vr=n=>{if(!Sr.test(n))throw new $("INTERNAL",`invalid clientId ${JSON.stringify(n)}: a client-supplied row id must be a UUID`)},yt=n=>{if(n.includes("\0"))throw new $("BAD_REQUEST",`invalid row id ${JSON.stringify(n)}: a row id cannot hold a NUL character (U+0000)`)},_r=(n,r,o,s)=>{if(o!==!0)return;const c=n!==void 0&&"serverDefault"in(n.shape._id?._meta?.column??{});for(const u of r){const g=c?pt(n,u,s)._id:u._id;typeof g=="string"&&yt(g)}},tn=50,je=Math.floor(En.boundParams/3),nn=En.boundParams,Tr=128,Ve=n=>new $("BATCH_LIMIT_EXCEEDED",n,{status:400}),He=(n,r,o)=>{Sn(n,Rn(r,o,Ve),o,Ve)},on=async(n,r,o,s,c)=>{const u=Rn(s,c,Ve),{page:g}=await n.findMany(r,Number.isFinite(u)?{limit:u+1,omitContinueCursor:!0,where:o}:{where:o});return g.length>u&&Sn(Math.max(await n.count(r,{where:o}),g.length),u,c,Ve),g},Ar=n=>{const r={eq:(o,s)=>(n.sqlConditions.push({comparator:"=",field:o,value:s}),r),gt:(o,s)=>(n.sqlConditions.push({comparator:">",field:o,value:s}),r),gte:(o,s)=>(n.sqlConditions.push({comparator:">=",field:o,value:s}),r),lt:(o,s)=>(n.sqlConditions.push({comparator:"<",field:o,value:s}),r),lte:(o,s)=>(n.sqlConditions.push({comparator:"<=",field:o,value:s}),r)};return r},Ir=n=>Math.max(n,z),An=(n,r)=>{const o=n.filters.map(s=>a`${fe(s.field)} = ${Ce(s.value)}`);return r&&o.push(r),o},xr=(n,r,o,s,c)=>{const u=Rt(o.query,$t(o.definition.language));if(u.length===0)return[];const g=qn(r,o.indexName),m=`${g}__vocab`,y=u.length-1,d=u.map((q,B)=>{const U=Yo(q,B===y),j=U.exact?a`${a.identifier("term")} = ${U.lower}`:a`${a.identifier("term")} >= ${U.lower} AND ${a.identifier("term")} < ${U.upper}`;return a`SELECT ${a.identifier("doc")}, ${a.raw(String(B))} AS ${a.identifier("__term__")}, COUNT(*) AS ${a.identifier("__n__")} FROM ${a.identifier(m)} WHERE ${j} GROUP BY ${a.identifier("doc")}`}),b=u.map((q,B)=>a`SUM(CASE WHEN u.${a.identifier("__term__")} = ${a.raw(String(B))} THEN u.${a.identifier("__n__")} ELSE 0 END)`),_=a`SELECT f.${a.identifier(qe)} AS ${a.identifier(qe)}, ${a.join(b,a` + `)} AS ${a.identifier("__score__")} FROM (${yn(d)}) u JOIN ${a.identifier(g)} f ON f.rowid = u.${a.identifier("doc")} GROUP BY f.${a.identifier(qe)} HAVING ${a.join(b.map(q=>a`${q} > 0`),a` AND `)}`,v=An(o,c);let x=a`SELECT m.id, m._creationTime, m.${a.identifier(ie)}, s.${a.identifier("__score__")} AS ${a.identifier("__score__")} FROM (${_}) s JOIN ${a.identifier(r)} m ON m.id = s.${a.identifier(qe)}`;v.length>0&&(x=a`${x} WHERE ${a.join(v,a` AND `)}`),x=a`${x} ORDER BY s.${a.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${a.raw(String(s))}`;const W=[];for(const q of K(n,x)){const B=pn(q);if(B){const U=q.__score__;W.push({document:B,score:typeof U=="number"?U:Number(U??0)})}}return W},br=(n,r,o,s,c)=>{const u=$t(o.definition.language),g=Rt(o.query,u);if(g.length===0)return[];const m=An(o,c);let y=a`SELECT id, _creationTime, ${a.identifier(ie)} FROM ${a.identifier(r)}`;m.length>0&&(y=a`${y} WHERE ${a.join(m,a` AND `)}`),y=a`${y} ORDER BY _creationTime DESC, id ASC LIMIT ${a.raw(String(Ir(s)))}`;const d=K(n,y).toArray(),b=[];for(const _ of d){const v=pn(_);if(!v)continue;const x=zo(Pn(v,o.definition),g);x>0&&b.push({creationTime:typeof v._creationTime=="number"?v._creationTime:0,doc:v,id:typeof v._id=="string"?v._id:"",score:x})}return b.sort((_,v)=>v.score-_.score||v.creationTime-_.creationTime||_.id.localeCompare(v.id)),b.slice(0,s).map(_=>({document:_.doc,score:_.score}))},lt=(n,r,o,s)=>{if(!Number.isFinite(n.lat)||n.lat<-90||n.lat>90||!Number.isFinite(n.lng)||n.lng<-180||n.lng>180)throw new $("BAD_REQUEST",`geo index "${s}" on table "${o}": ${r} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},Cr=(n,r)=>{const o=n,s={near:(c,u)=>{if(o.within)throw new $("INTERNAL",`geo index "${o.indexName}" on table "${r}": call .near() or .within(), not both`);if(lt(c,".near() point",r,o.indexName),!Number.isFinite(u)||u<=0)throw new $("BAD_REQUEST",`geo index "${o.indexName}" on table "${r}": .near() radiusMeters must be a finite number > 0, got ${String(u)}`);return o.near={point:{lat:c.lat,lng:c.lng},radiusMeters:u},s},within:c=>{if(o.near)throw new $("INTERNAL",`geo index "${o.indexName}" on table "${r}": call .near() or .within(), not both`);if(lt(c.sw,".within() sw corner",r,o.indexName),lt(c.ne,".within() ne corner",r,o.indexName),c.sw.lat>c.ne.lat)throw new $("BAD_REQUEST",`geo index "${o.indexName}" on table "${r}": .within() corners are transposed (sw.lat > ne.lat)`);if(c.sw.lng>c.ne.lng)throw new $("BAD_REQUEST",`geo index "${o.indexName}" on table "${r}": .within() box crosses the antimeridian (sw.lng > ne.lng), which is not supported — split it into two boxes at ±180 and union the results`);return o.within={ne:{lat:c.ne.lat,lng:c.ne.lng},sw:{lat:c.sw.lat,lng:c.sw.lng}},s}};return s},Mr=(n,r)=>{const o=n[r];if(o===null||typeof o!="object")return;const{lat:s,lng:c}=o;return typeof s=="number"&&typeof c=="number"?{lat:s,lng:c}:void 0},Dr=(n,r)=>{const o=Mr(n,r.definition.field);if(!o)return;const s=typeof n._creationTime=="number"?n._creationTime:0;if(r.near){const c=fo(r.near.point,o);return c<=r.near.radiusMeters?{creationTime:s,distance:c}:void 0}return ho(o,r.within)?{creationTime:s,distance:0}:void 0},kr=(n,r,o,s)=>{if(!o.near&&!o.within)throw new $("INTERNAL",`geo index "${o.indexName}" on table "${r}": call .near(point, radius) or .within(box)`);const c=o.near?lo(o.near.point,o.near.radiusMeters):uo(o.within),u=so(r,o.indexName),g=c.map(_=>a`(g.${a.identifier("__geohash__")} >= ${_} AND g.${a.identifier("__geohash__")} < ${`${_}{`})`),m=[a`(${a.join(g,a` OR `)})`];s&&m.push(s);const y=a`SELECT m.id, m._creationTime, m.${a.identifier(ie)} FROM ${a.identifier(u)} g JOIN ${a.identifier(r)} m ON m.id = g.${a.identifier("__id__")} WHERE ${a.join(m,a` AND `)}`,d=K(n,y).toArray(),b=[];for(const _ of d){const v=xe(_),x=v?Dr(v,o):void 0;v&&x&&b.push({creationTime:x.creationTime,distance:x.distance,doc:v})}return b.sort((_,v)=>_.distance-v.distance||v.creationTime-_.creationTime),b},In=(n,r,o,s)=>{const c=[];for(const u of n)if(r.every(g=>g(s(u)))&&(c.push(u),typeof o=="number"&&c.length>=o))break;return c},Lr=(n,r,o,s,c,u=()=>{})=>{const g=o.within!==void 0,m=kr(n,r,o,c).map(y=>({distanceMeters:g?null:y.distance,document:y.doc}));return u(m.length),typeof s=="number"?m.slice(0,Math.max(0,Math.floor(s))):m},rn=(n,r,o,s,c,u,g=()=>{})=>{const{geo:m}=o;if(!m)throw new $("INTERNAL","runGeoTerminalScored called without a staged geo query");const y=c.length>0,d=Lr(n,r,m,y?void 0:u,s,g);return y?In(d,c,u,b=>b.document):d},sn=(n,r,o)=>{const s=n.shape[r];if(s!==void 0&&Ko(s))throw new $("BAD_REQUEST",`${o}: "${r}" may hold an order-preserving key rather than a value SQL can reduce or group — declare an aggregateIndex covering this (by, field, op) so the maintained companion answers it instead (its running total is a REAL, so it stays exact only while the total is inside 2^53)`)},Fr=n=>{let r=0;const o=[],s={...Ye,relationExists:c=>{const{childWhere:u,negated:g,parentTable:m,relation:y}=c,d=`__rel_${String(r)}`,b=o.at(-1)??m;r+=1,n(y.table,G);const _=y.kind==="one"?y.field:y.references,v=y.kind==="one"?y.references:y.field,x=Qe(`${Gt(d,v)} = ${Gt(b,_)}`);o.push(d);const W=Z(u,s,ze);o.pop();const q=W===void 0?x:be(x," AND ",W),B=be("EXISTS (SELECT 1 FROM ",Jt(y.table)," AS ",Jt(d)," WHERE ",q,")");return g?be("NOT ",B):B}};return s};class Br extends ${constructor(r="unique() found more than one matching document"){super("NOT_UNIQUE",r,{name:"NotUniqueError"})}}const Wr=/\s/u,qr=String.fromCodePoint(0),cn=(n,r,o)=>{if(!n.tables[r])throw new $("INTERNAL",`unknown table: ${r}`);return typeof o!="string"||o.length===0||Wr.test(o)||o.includes(qr)?null:o},xn=(n,r,o,s=()=>{},c=()=>{},u=()=>{},g)=>{const m=r.tables[o];if(!m)throw new $("INTERNAL",`unknown table: ${o}`);const y=Ae(m.softDeleteMode,void 0),d=g??{indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[],verifyFilters:[]},b=()=>{const S=Q(y,d.pushedWhere);return S?Z(S,ue):void 0},_=()=>{const S=Q(y,d.pushedWhere);return S?Z(S,Ye,ze):void 0},v=()=>[...d.inMemoryFilters,...d.verifyFilters];let x=0;const W=S=>{const{search:M}=d;if(!M)throw new $("INTERNAL","runSearchFetch called without a staged search");Nn(ro(n),o,m);const L=d.inMemoryFilters.length>0,F=ir(L?void 0:S),k=io(n);if(k&&!Qn(n,o,M.definition))throw new $("SEARCH_INDEX_BUILDING",`search index "${M.indexName}" on table "${o}" is still backfilling and currently covers only part of the table — retry once it finishes, or run the backfillSearch admin operation to complete it now`);const pe=b(),te=k?xr(n,o,M,F,pe):br(n,o,M,F,pe);!L&&S===void 0&&Zo(te);const ge=v();return x=te.length,ge.length>0?In(te,ge,S,J=>J.document):te},q=S=>W(S).map(M=>M.document),B=S=>{const M=or(S);return rr(q(er(M)),M)},U=()=>{if(d.search||d.geo||d.indexName===void 0){c(void 0);return}c(Co(o,d.indexName,d.indexFields,d.sqlConditions,Ce))},j=S=>{U();let M=0;const L=(()=>{if(d.search){const F=q(S);return M=x,F}return d.geo?rn(n,o,d,b(),v(),S,F=>{M=F}).map(F=>F.document):gt(n,o,m,d,_(),{filters:v(),selective:d.inMemoryFilters.length>0,want:S===void 0?void 0:Math.max(0,Math.floor(S))},F=>{M+=F}).documents})();return u(Math.max(M,L.length)),L},ee=()=>{if(!d.search&&!d.geo)throw new $("INTERNAL",`ctx.db.query("${o}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);U();let S=0;const M=(()=>{if(d.search){const L=W(void 0);return S=x,L}return rn(n,o,d,b(),v(),void 0,L=>{S=L})})();return u(Math.max(S,M.length)),M},N={async*[Symbol.asyncIterator](){const S=xn(n,r,o,s,c,u,{...d,indexFields:[...d.indexFields],inMemoryFilters:[...d.inMemoryFilters],sqlConditions:[...d.sqlConditions],verifyFilters:[...d.verifyFilters]});if(d.search){yield*await S.collect();return}let M;for(;;){const L=await S.paginate({cursor:M??null,numItems:Tr});if(yield*L.page,L.isDone||L.continueCursor===null)return;M=L.continueCursor}},async collect(){return j(void 0)},async collectWithScores(){return ee()},filter(S){const M=Mo(S);return M!==void 0&&Do(M,m.shape)?(d.pushedWhere=Q(d.pushedWhere,M),d.verifyFilters.push(S)):d.inMemoryFilters.push(S),N},async first(){return j(1)[0]??null},order(S){return d.order=S==="desc"?"desc":"asc",N},async paginate(S){let M=0;if(U(),d.search){const F=B(S);return u(F.page.length),F}if(d.geo)throw new $("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const L=wr(n,o,m,d,S,_(),{all:v(),selective:d.inMemoryFilters.length>0},F=>{M+=F});return u(Math.max(M,L.page.length)),L},async take(S){return j(S)},async unique(){const S=j(2);if(S.length>1)throw new Br(`unique() on table "${o}" matched ${String(S.length)} documents; expected at most one`);return S[0]??null},withGeoIndex(S,M){const L=(m.geoIndexes??[]).find(k=>k.name===S);if(!L)throw new $("INTERNAL",`unknown geo index "${S}" on table "${o}"`);s(o,S,"geo");const F={definition:L,indexName:S};if(d.geo=F,M(Cr(F,o)),!F.near&&!F.within)throw new $("INTERNAL",`geo index "${S}" on table "${o}" requires a .near(point, radius) or .within(box) call`);return N},withIndex(S,M){const L=m.indexes.find(F=>F.name===S);if(!L)throw new $("INTERNAL",`unknown index "${S}" on table "${o}"`);return s(o,S,"index"),d.indexName=S,d.indexFields=L.fields,M&&M(Ar(d)),N},withSearchIndex(S,M){const L=(m.searchIndexes??[]).find(k=>k.name===S);if(!L)throw new $("INTERNAL",`unknown search index "${S}" on table "${o}"`);s(o,S,"search");const F={definition:L,field:L.field,filters:[],hasQuery:!1,indexName:S,query:""};if(d.search=F,M(Xo(F,o,$t(L.language))),!F.hasQuery)throw new $("INTERNAL",`search index "${S}" on table "${o}" requires a .search(field, query) call`);return N}};return N},ut=(n,r,o,s)=>{const c=o;for(const[u,g]of oo(n)){if(g.serverDefault){u in r&&(c[u]=g.serverDefault({auth:s}));continue}g.onUpdateFn&&!(u in r)&&(c[u]=g.onUpdateFn())}},an=5,dn=(n,r)=>{for(const o of Object.keys(r))if(r[o]===void 0)throw new $("INTERNAL",`Cannot ${n} field '${o}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},ln=["_commitSeq","_creationTime","_id"],Ke=n=>ln.some(r=>r in n)?Object.fromEntries(Object.entries(n).filter(([r])=>!ln.includes(r))):n,Pr=/unique constraint failed/i,Ur=n=>n instanceof Error&&Pr.test(n.message),Or=/string or blob too big/iu,Gr=(n,r)=>{if(!(!(n instanceof Error)||!Or.test(n.message)))throw new $("PAYLOAD_TOO_LARGE",`document is too large to store in "${r}": a single row cannot exceed the storage engine's per-row ceiling (2 MB on a Durable Object's SQLite). The limit is on the STORED bytes, which are UTF-8, and v.bytes()/v.bigint() columns are stored twice on a shard-local table. Keep the payload in R2 (ctx.storage) and store a reference on the row.`)},Et=(n,r,o,s)=>{try{he(n,o,...s)}catch(c){throw Ur(c)?new se(`unique constraint violation on "${r}"`,"unique"):(Gr(c,r),c)}},Ne=(n,r,o,s)=>{if(Et(n,r,o,s),he(n,Er).one().changed===0)throw new se(`optimistic concurrency conflict on "${r}" — the row changed during this mutation; refetch and retry`,"occ")},un=(n,r,o,s,c,u,g)=>{const m=[];for(let _=0;_<o.length+1;_+=1){const v=o[_],x=s[_],W=x?.direction==="desc"?"desc":"asc",q=v===void 0||x===void 0?a`${a.identifier(To)} < ${g}`:Ao(v,u[_],W,!1);if(q===void 0)continue;const B=[];for(let j=0;j<_;j+=1)B.push(a`${a.identifier(o[j])} IS ${u[j]}`);B.push(q);const[U]=B;m.push(B.length===1&&U!==void 0?U:a`(${a.join(B,a` AND `)})`)}const y=m.length>0?a.join(m,a` OR `):a`1 = 0`,d=K(n,a`SELECT COUNT(*) AS c FROM ${a.identifier(r)} WHERE ${a.identifier("__partition__")} = ${c} AND (${y})`).one(),b=K(n,a`SELECT COUNT(*) AS c FROM ${a.identifier(r)} WHERE ${a.identifier("__partition__")} = ${c}`).one();return{before:d.c,total:b.c}},jr=n=>{const r=new Map;for(const[s,c]of Object.entries(n.tables))for(const u of Object.values(c.relationMap??{}))u.kind==="one"&&(u.onDelete==="cascade"||u.onDelete==="set null")&&r.set(u.table,[...r.get(u.table)??[],{holder:s,op:u.onDelete==="cascade"?"delete":"update"}]);const o=s=>{const c=new Set,u=[s];for(let g=u.pop();g!==void 0;g=u.pop())for(const{holder:m,op:y}of r.get(g)??[]){if(m===s||zt(n,m,y))return!0;c.has(m)||(c.add(m),u.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))},Hr=n=>{const r=new Map;for(const[o,s]of Object.entries(n.tables))s.softDeleteMode&&r.set(o,s.softDeleteMode.field);return r},ft=new WeakMap,Kr=(n,r)=>{let o=ft.get(r.tables);if(!ft.has(r.tables)){const c=Object.keys(r.tables).map(u=>u.replaceAll(/[$()*+.?[\\\]^{|}]/gu,String.raw`\$&`));o=c.length===0?void 0:new RegExp(`"(${c.join("|")})"`,"gu"),ft.set(r.tables,o)}if(o===void 0)return;const s=new Set;for(const c of n.matchAll(o))s.add(c[1]);return s.size===1?[...s][0]:void 0},Nr=(n,r,o)=>{for(const s of n){const c=s,u=c?.[ie];if(typeof u=="string"){const g=c?.id,m=ao(u);typeof g!="string"?r.recordReadBytes(m):o===void 0?r.recordDocumentRead(`${g}\0${String(m)}`,m):r.recordDocumentRead(`${o}\0${g}`,m)}}},Qr=(n,r,o)=>{if(r===void 0)return n;const s=(c,...u)=>{const g=n.exec(c,...u),m=g.one.bind(g),y=g[Symbol.iterator].bind(g),d=o===void 0?void 0:Kr(c,o);let b=!1;const _=v=>{Nr(v,r,d)};return g.toArray=()=>{const v=[];for(const x of{[Symbol.iterator]:y})_([x]),v.push(x);return v},g.one=()=>{b=!0;try{const v=m();return _([v]),v}finally{b=!1}},g[Symbol.iterator]=function*(){for(const x of{[Symbol.iterator]:y})b||_([x]),yield x},g};return new Proxy(n,{get:(c,u)=>u==="exec"?s:u===to?c:Reflect.get(c,u,c)})},Vr=new Map([["findFirst","rows"],["findFirstOrThrow","rows"],["findMany","page"],["get","rows"],["lookupById","lookup"],["rankPage","page"]]),Jr=new Map([["collect","rows"],["collectWithScores","scored"],["first","rows"],["paginate","page"],["take","rows"],["unique","rows"]]),Ie=(n,r,o)=>{if(typeof n!="object"||n===null)return;const s=co(n);if(s===void 0)return;const c=n._id;typeof c=="string"?o.recordDocumentRead(`global\0${r}\0${c}`,s):o.recordReadBytes(s)},Je=(n,r,o,s)=>{if(typeof n!="object"||n===null)return;const c=n;switch(r){case"lookup":{Ie(c.row,typeof c.tableName=="string"?c.tableName:o,s);return}case"page":{for(const u of c.page??[])Ie(u,o,s);return}case"rows":{for(const u of Array.isArray(n)?n:[n])Ie(u,o,s);return}default:for(const u of Array.isArray(n)?n:[])Ie(u.document,o,s)}},bn=(n,r,o)=>new Proxy(n,{get:(s,c)=>{const u=Reflect.get(s,c,s);if(typeof u!="function")return u;if(c===Symbol.asyncIterator)return async function*(){for await(const y of Reflect.apply(u,s,[]))Ie(y,r,o),yield y};const g=Jr.get(c);return(...m)=>{const y=Reflect.apply(u,s,m);return g!==void 0?Promise.resolve(y).then(d=>(Je(d,g,r,o),d)):typeof y=="object"&&y!==null&&!(y instanceof Promise)?bn(y,r,o):y}}}),zr=new Set(["findFirst","findFirstOrThrow","findMany"]),Yr=n=>{const r=n[1],o=r?.select;if(!Array.isArray(o))return;const s=Object.fromEntries(Object.entries(r).filter(([g])=>g!=="select")),c=s.with,u=g=>mn(g,o,c);return{args:[n[0],s,...n.slice(2)],project:(g,m)=>typeof g!="object"||g===null?g:m==="page"?{...g,page:u(g.page)}:u([g])[0]}},fn=256,mt=4096,Xr=1024*1024,Zr=async(n,r,o,s)=>{const c=r[1]??{},u=[];let{cursor:g}=c,m=fn,y=0;for(;;){const d=await n([r[0],{...c,cursor:g,limit:m},...r.slice(2)]);if(Array.isArray(d))return Je(d,"rows",o,s),[...u,...d];const b=s.headroom().readBytes;if(Je(d,"page",o,s),u.push(...d.page),d.isDone||typeof d.continueCursor!="string")return{continueCursor:null,isDone:!0,page:u};g=d.continueCursor,y+=s.headroom().readBytes-b,m=y>0?Math.min(mt,Math.max(fn,Math.floor(Xr*u.length/y))):mt}},ei=(n,r)=>n===void 0||r===void 0?n:new Proxy(n,{get:(o,s)=>{const c=Reflect.get(o,s,o);if(typeof c!="function")return c;if(s==="query")return(...g)=>bn(Reflect.apply(c,o,g),String(g[0]),r);const u=Vr.get(s);return u===void 0?c:async(...g)=>{const m=zr.has(s)?Yr(g):void 0;let y=m?.args??g;const d=String(g[0]),b=y[1],_=s==="findMany"&&typeof b?.endCursor=="string",v=s==="findMany"&&typeof b?.limit!="number"&&!_;if(_&&typeof b.limit!="number"&&(y=[y[0],{...b,limit:mt},...y.slice(2)]),v){const W=await Zr(q=>Reflect.apply(c,o,q),y,d,r);return m===void 0?W:m.project(W,u)}const x=await Reflect.apply(c,o,y);return Je(x,u,d,r),m===void 0?x:m.project(x,u)}}}),hn=new WeakMap,wn=new WeakMap,ti=n=>{const{baselineSeq:r,onStalePatchDropped:o}=n,{headroom:s}=n,c=hn.get(n)??{value:void 0},u=wn.get(n)??{value:0};let g;const m=()=>{if(g===void 0){const e={...n,enforceRls:!1,headroom:void 0};hn.set(e,c),wn.set(e,u),g=ti(e)}return g},y=Qr(n.sql,s,n.schema),{schema:d}=n,b=n.broadcast??(()=>{}),_=(e,t)=>{if(!Object.hasOwn(d.tables,e))throw new $("BAD_REQUEST",`${t}: "${e}" is not a table in this schema`)},v=ko(d),x=new Map;for(const e of v){const t=i=>(d.tables[i]?.shardMode?.kind??"root")==="root";!e.array&&t(e.sourceTable)&&t(e.targetTable)&&x.set(e.sourceTable,[...x.get(e.sourceTable)??[],e])}const W=(e,t,i)=>{for(const l of x.get(e)??[]){const w=t[l.column];if(typeof w!="string"||i?.[l.column]===w||l.targetTable===e&&t._id===w)continue;if(K(y,a`SELECT 1 FROM ${a.identifier(l.targetTable)} WHERE id = ${w} LIMIT 1`).toArray().length===0)throw new $("VALIDATION_ERROR",`${l.name} references ${l.targetTable} row "${w}", which does not exist`)}},q=qo(d,n.inTransaction),B=jr(d),U=Hr(d),j=()=>n.inTransaction?.()===!0,ee=e=>d.tables[e]?.commitOrderedMode!==!0?{}:((c.value===void 0||!j())&&(c.value=zn(y)),{[Yn]:c.value}),N=(e,...t)=>{const i=d.tables[e]?.indexes??[],l=[];let w;for(const p of t)p&&(typeof p._id=="string"&&p._id!==w&&(w=p._id,l.push(Io(w))),l.push(...xo(i,bo(i,p,Ce))));return l.length>0?l:void 0},S=n.onRead??(()=>{}),M=e=>{Ut(d.tables[e])&&S(Vt,Vt)},L=n.onReadRange??(e=>{S(e.table,G)}),F=e=>{M(e.table),L(e)},k=(e,t,i)=>{t!==void 0&&(i===!0||t!==G)&&s?.recordRead(1),M(e),S(e,t,i)},pe=(e,t)=>{const i=e.row._id;k(e.tableName,typeof i=="string"?i:t,typeof i=="string")},te=n.onIndexUse??(()=>{}),ge=n.onWrite??(()=>{}),J=e=>{s?.recordWrite(e)},ye=async e=>{J(e.doc),await ge(e)},{cache:Ee}=n,me=n.clock??(()=>Date.now()),St=n.idGenerator??(()=>crypto.randomUUID()),vt=n.scheduler??On,$e=ei(n.globalDb,s),ce=n.auth??{identity:null,userId:null},_t=n.cdc??!1,Ze=vt,Cn=No({scheduler:typeof Ze.list=="function"&&typeof Ze.get=="function"?Ze:void 0,storage:n.storage}),Re=(e,t,i,l)=>{_t&&!Ut(d.tables[e])&&Vn(y,me(),e,t,i,l)},Tt=(e,t,i,l)=>{const w=d.tables[e];if(w?.dropStalePatchesMode!==!0||!_t)return!1;const p=r?.();if(p===void 0)return!1;const f=Jn(y,e,t,p);if(f===void 0)return!1;const h=yo(w,i);return Object.keys(Ke(i)).some(E=>!h.has(E)&&Pt(jt(f,E))!==Pt(jt(l,E)))},ae=e=>d.tables[e]?.shardMode?.kind==="global",At=(e,t)=>{if(ae(e)){if(!$e)throw new $("INTERNAL",`cross-backend ${t} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return $e}return O},et=e=>At(e,"cascade"),H=(e,t)=>{if(ae(e)){if(!$e)throw new $("INTERNAL",`${t} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return $e}},It=async(e,t,i,l,w)=>{w&&J(i);const p=await e.insert(t,i,l);return b({key:p,op:"insert",row:{...i,_id:p},table:t}),p},xt=(e,t)=>At(e,"relation load").findMany(e,t),bt=(e,t)=>(ae(e)&&k(e,G),xt(e,t)),Mn=e=>!ae(e.table),Ct=n.relationExistsPushDown??"auto",Mt=Ct!=="never",{maxRelationKeys:Dt}=n,De=(e,t,i)=>Bo(e,{fetcher:bt,maxRelationKeys:Dt,relationBaseWhere:i,schema:d,tableName:t}),Dn=async(e,t,i,l)=>{const w=H(e,"relation grouped count");if(w)return k(e,G),jo((R,P)=>w.count(R,P),e,t,i,l);const p=d.tables[e];if(!p)throw new $("INTERNAL",`unknown table: ${e}`);k(e,G);const f=Ae(p.softDeleteMode,void 0),h={[t]:{in:i}},E=Q(Q(h,l),f),A=await De(E,e,void 0),C=Z(A,ue),I=fe(t);let T=a`SELECT ${I} AS __fk__, COUNT(*) AS count FROM ${a.identifier(e)}`;C&&(T=a`${T} WHERE ${C}`),T=a`${T} GROUP BY ${I}`;const D=K(y,T).toArray();return new Map(D.map(R=>[R.__fk__,R.count]))},kt=new Set;for(const[e,t]of Object.entries(d.tables))for(const i of Object.values(t.triggerMap??{}))kt.add(`${e} ${i.timing} ${i.op}`);const ne=(e,t,i)=>kt.has(`${e} ${t} ${i}`),oe=async(e,t,i)=>{if(u.value+=1,u.value>tn)throw u.value-=1,new se(`trigger recursion exceeded ${String(tn)} levels on "${i.table}" — check for a self-triggering write`,"trigger");try{await Qo({ctx:Bn,event:i,op:t,schema:d,tableName:i.table,timing:e})}finally{u.value-=1}},{ensureBackfilledForTable:Se,ensureBackfilledIndex:tt,ensureRankBackfilled:nt,ensureRankBackfilledForTable:ve,syncAggregates:ke,syncCompanionsForInsert:Lt,syncGeo:Le,syncRanks:_e,syncSearch:Fe}=Xn({broadcast:b,indexKeysFor:(e,t)=>N(e,t),invalidateCache:(e,t,i)=>Ee?.invalidate(e,t,N(e,i)),recordCdc:Re,schema:d,sql:y,verified:n.companionMemo?.verified}),Ft=(e,t,i)=>{const{shardMode:l}=t;if(l?.kind==="shardBy"&&!(l.field!==void 0&&(i.partitionBy??[]).includes(l.field)))throw Object.assign(new Error(`rank index "${i.name}" on "${e}" partitions across shards (shard key "${l.field??"?"}" is not in partitionBy) — a shard-local rank()/rankPage() would be wrong; roll it up through the Query Coordinator instead`),{code:"CROSS_SHARD_RANK_UNSUPPORTED",name:"LunoraError",status:400})},Bt=e=>Object.entries(d.tables).filter(([,t])=>t.shardMode?.kind!=="global").map(([t])=>t).filter(t=>e===void 0||t===e),Te=e=>e===void 0||ae(e)?$e:void 0,ot=async(e,t,i,l,w)=>{for(let p=0;p<i.length;p+=1)J(void 0);if(w!==void 0&&e.deleteMany!==void 0)return e.deleteMany(t,i,w.options);for(const p of i)await e.delete(t,p,l);return{deleted:i.length}},re=(e,t)=>{const i=Bt(t);for(let l=0;l<i.length;l+=nn){const w=i.slice(l,l+nn),[p]=he(y,$r(w),...Rr(e,w)).toArray();if(!p)continue;const f=p.__t__,h=xe(p);if(typeof f!="string"||!h)return;const E=p[ie];return{docJson:typeof E=="string"?E:le(E??{}),row:h,tableName:f}}},Wt={assertRankPartitionLocal:Ft,ensureRankBackfilled:nt,onRead:k,rowToDocument:xe,schema:d,sql:y},kn=(e,t,i)=>{const l=Z(i,ue);return l===void 0||K(y,a`SELECT 1 FROM ${a.identifier(e)} WHERE ${a.identifier("id")} = ${t} AND ${l}`).toArray().length>0},Ln=(e,t,i,l)=>Tt(e,t,i,l)?(o?.({fields:Object.keys(Ke(i)),id:t,table:e}),!0):!1,Fn=async(e,t,i,l,w)=>{const p=re(t,e);if(!p)return{applied:!1,doc:null};if(k(e,t),!kn(e,t,i.where)||Ln(e,t,i.patch,p.row))return{applied:!1,doc:p.row};try{await w(i.patch)}catch(f){if(f instanceof se&&f.kind==="occ"&&l)return;throw f}return{applied:!0,doc:re(t,e)?.row??null}},qt=async(e,t,i,l)=>{const{fetchLimit:w,limit:p,orderKeys:f,predicate:h}=await Wo(t,i,{canPushExists:Mt?Mn:void 0,existsPushMode:Ct==="always"?"always":"auto",fetcher:bt,maxRelationKeys:Dt,schema:d,tableName:e}),E=Mt?Fr(l):Ye,A=Z(h,E,ze),C=vn(e,A,_n(f),w);return{limit:p,orderKeys:f,statement:C}},O={system:Cn,async aggregate(e,t){const i=H(e,"aggregate");if(i)return k(e,G),i.aggregate(e,t);const l=d.tables[e];if(!l)throw new $("INTERNAL",`unknown table: ${e}`);if(Pe(t.op),t.op==="count")return O.count(e,{baseWhere:t.baseWhere,relationBaseWhere:t.relationBaseWhere,restrictsCounts:t.restrictsCounts,where:t.where});if(!t.field)throw new $("INTERNAL",`aggregate(${e}, { op: "${t.op}" }): "field" is required for non-count reducers`);k(e,G);const w=Ae(l.softDeleteMode,void 0),p=Q(Q(t.baseWhere,t.where),w),f=await De(p,e,t.relationBaseWhere),h=f!==p;if(l.aggregateIndexes&&!t.baseWhere&&!h){const R=Kn(l.aggregateIndexes,t.op,t.field,t.where);if(R){tt(e,R.index);const P=it(R.index.by??[],R.key),Y=rt(e,R.index.name),X=K(y,a`SELECT ${Ue} AS value, ${at} AS count FROM ${a.identifier(Y)} WHERE ${Oe} = ${P}`).toArray()[0];return st(t.op,X)}}sn(l,t.field,`aggregate(${e}, { op: "${t.op}", field: "${t.field}" })`);const E=Z(f,ue),A=Pe(t.op),C=fe(t.field);let I=a`SELECT ${a.raw(A)}(${C}) AS value FROM ${a.identifier(e)}`;E&&(I=a`${I} WHERE ${E}`);const D=K(y,I).toArray()[0]?.value;return D??null},asId(e,t){const i=cn(d,e,t);if(i===null)throw new $("BAD_REQUEST",`asId("${e}", …): "${t}" is not a valid id for table "${e}"`,{status:400});return i},async count(e,t){const i=H(e,"count");if(i)return k(e,G),i.count(e,t);const l=d.tables[e];if(!l)throw new $("INTERNAL",`unknown table: ${e}`);const w=Gn(t);if(w.restrictsCounts)throw new ct(e);k(e,G);const p=Ae(l.softDeleteMode,void 0),f=Q(Q(w.baseWhere,w.where),p),h=await De(f,e,w.relationBaseWhere),E=h!==f;if(l.aggregateIndexes&&!w.baseWhere&&!E){const T=Hn(l.aggregateIndexes,w.where);if(T){tt(e,T.index);const D=it(T.index.by??[],T.key),R=rt(e,T.index.name),P=K(y,a`SELECT ${Ue} AS value FROM ${a.identifier(R)} WHERE ${Oe} = ${D}`).toArray();return P[0]===void 0?0:P[0].value??0}}const A=Z(h,ue);let C=a`SELECT COUNT(*) AS count FROM ${a.identifier(e)}`;return A&&(C=a`${C} WHERE ${A}`),K(y,C).one().count},async delete(e,t,i){_(e,"ctx.db.delete(table, id)");const l=re(t,e);if(!l){const T=Te(e);T&&await ot(T,e,[t],i);return}const{docJson:w,row:p,tableName:f}=l,h=d.tables[f],E=i?.hard===!0,A=!E&&h?.softDeleteMode?h:void 0,C=A?.softDeleteMode?.field;if(C&&p[C]!==null&&p[C]!==void 0)return;if(ne(f,"before","delete")&&await oe("before","delete",{id:t,op:"delete",previous:p,table:f}),i?.skipOnDelete!==!0&&await Go({deletedId:t,deletedReference:T=>p[T],findHolders:async(T,D,R,P)=>(await et(T).findMany(T,{...P,includeDeleted:E,where:{[D]:R}})).page,onCascade:(T,D)=>et(T).delete(T,D,i),onRestrict:T=>{throw new se(T,"restrict")},onSetNull:(T,D,R)=>et(T).patch(T,D,{[R]:null}),schema:d,tableName:f}),Se(f),ve(f),A&&C){const T={[C]:me()},D={...p,...ee(f),...T,_id:t};ut(A,T,D,ce),Ne(y,f,Zt(f),[le(D),t,w]),Fe(f,t,D,p),Le(f,t,void 0),ke(f,p,D),_e(f,t,p,void 0);const R=N(f,p,D);Ee?.invalidate(f,t,R),Re(f,t,"update",D),b({indexKeys:R,key:t,op:"update",row:D,table:f}),ne(f,"after","delete")&&await oe("after","delete",{id:t,op:"delete",previous:p,table:f}),await ye({id:t,op:"delete",table:f});return}Ne(y,f,yr(f),[t,w]),Fe(f,t,void 0),Le(f,t,void 0),ke(f,p,void 0),_e(f,t,p,void 0);const I=N(f,p);Ee?.invalidate(f,t,I),Re(f,t,"delete"),b({indexKeys:I,key:t,op:"delete",table:f}),ne(f,"after","delete")&&await oe("after","delete",{id:t,op:"delete",previous:p,table:f}),await ye({id:t,op:"delete",table:f})},async deleteAll(e,t){if(!d.tables[e])throw new $("INTERNAL",`unknown table: ${e}`);if(s!==void 0)return m().deleteAll(e,t);const i=Math.max(1,t?.chunkSize??$n),l=t?.hard===void 0?void 0:{hard:t.hard},w=H(e,"deleteAll");let p=0;for(;;){const h=(await O.findMany(e,{limit:i})).page.map(E=>String(E._id));if(h.length===0)break;for(const E of h)await(w===void 0?O.delete(e,E,l):ot(w,e,[E],l)),p+=1;if(h.length<i)break}return{deleted:p}},async deleteMany(e,t,i){_(e,"ctx.db.deleteMany(table, ids)"),He(t.length,i?.limit,"deleteMany");for(const l of t)await O.delete(e,l);return{deleted:t.length}},async deleteWhere(e,t,i){const l=H(e,"deleteWhere"),p=(await on(l??O,e,t,i?.limit,"deleteWhere")).map(f=>String(f._id));if(l)return ot(l,e,p,void 0,{options:i});if(O.deleteMany===void 0)throw new $("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return O.deleteMany(e,p,i)},async findFirst(e,t={}){return(await O.findMany(e,{...t,limit:1,omitContinueCursor:!0})).page[0]??null},async findFirstOrThrow(e,t={}){const i=await O.findFirst(e,t);if(i===null)throw new wo(`findFirstOrThrow: no "${e}" document matched`);return i},async findMany(e,t={}){const i=H(e,"findMany");if(i)return k(e,G),t.consistency==="primary"&&S(e,Zn),i.findMany(e,t);const l=d.tables[e];if(!l)throw new $("INTERNAL",`unknown table: ${e}`);const w=!t.where&&!t.baseWhere;w?k(e,G):k(e);const{limit:p,orderKeys:f,statement:h}=await qt(e,l,t,k),E=he(y,h.text,...h.params).toArray();w&&s?.recordRead(E.length);const A=[];for(const I of E){const T=xe(I);T&&(A.push(T),!w&&typeof T._id=="string"&&k(e,T._id))}const C=Fo(A,{endCursor:t.endCursor,limit:p,omitContinueCursor:t.omitContinueCursor,orderKeys:f});return t.with&&await Uo({fetcher:xt,groupedCounter:Dn,parents:C.page,...Oo(t),schema:d,tableName:e,with:t.with}),{...C,page:mn(C.page,t.select,t.with)}},async explain(e,t={}){const i=H(e,"explain");if(i)return i.explain(e,t);const l=d.tables[e];if(!l)throw new $("INTERNAL",`unknown table: ${e}`);const{statement:w}=await qt(e,l,t,()=>{}),p=he(y,`EXPLAIN QUERY PLAN ${w.text}`,...w.params).toArray();return{params:w.params,plan:p.map(f=>String(f.detail)),sql:w.text}},async get(e,t){_(e,"ctx.db.get(table, id)");const i=re(t,e);if(!i){const l=Te(e);return l?l.get(e,t):(M(e),S(e,t,!0),null)}return pe(i,t),i.row},async lookupById(e,t){const i=re(e,t);if(!i){for(const l of Bt(t))M(l),S(l,e,!0);return null}return pe(i,e),{row:i.row,tableName:i.tableName}},async groupBy(e,t){const i=H(e,"groupBy");if(i)return k(e,G),i.groupBy(e,t);const l=d.tables[e];if(!l)throw new $("INTERNAL",`unknown table: ${e}`);k(e,G);const w=t.agg??{op:"count"};if(Pe(w.op),w.op!=="count"&&!w.field)throw new $("INTERNAL",`groupBy(${e}, { agg: { op: "${w.op}" } }): "field" is required for non-count reducers`);const p=Ae(l.softDeleteMode,void 0),f=Q(Q(t.baseWhere,t.where),p),h=await De(f,e,t.relationBaseWhere),E=h!==f;if(l.aggregateIndexes&&!t.baseWhere&&!E){const R=jn(l.aggregateIndexes,w.op,w.field,t.by,t.where),P=R===void 0?0:Object.keys(R.partial).length,Y=R?.index.by?.length??0;if(R&&(P===0||P===Y)){tt(e,R.index);const X=rt(e,R.index.name),V=Object.keys(R.partial),de=[];if(V.length===(R.index.by??[]).length&&V.length>0){const Be=it(R.index.by??[],R.partial),We=K(y,a`SELECT ${Ue} AS value, ${at} AS count FROM ${a.identifier(X)} WHERE ${Oe} = ${Be}`).toArray();return We.length>0&&de.push({key:{...R.partial},value:st(w.op,We[0])}),de}const Wn=K(y,a`SELECT ${Oe} AS key, ${Ue} AS value, ${at} AS count FROM ${a.identifier(X)}`).toArray();for(const Be of Wn){const We=Un(JSON.parse(Be.key));de.push({key:We,value:st(w.op,Be)})}return de}}for(const R of[...t.by,w.field]){if(R===void 0)continue;const P=R===w.field?`groupBy(${e}, { agg: { op: "${w.op}", field: "${R}" } })`:`groupBy(${e}, { by: [..."${R}"] })`;sn(l,R,P)}const A=Z(h,ue),C=t.by.map(R=>a`${fe(R)} AS ${a.identifier(R)}`);if(w.op==="count")C.push(a`COUNT(*) AS value`);else{const{field:R}=w;if(R===void 0)throw new $("INTERNAL",`groupBy(${e}, { agg: { op: "${w.op}" } }): "field" is required for non-count reducers`);C.push(a`${a.raw(Pe(w.op))}(${fe(R)}) AS value`)}let I=a`SELECT ${a.join(C,a`, `)} FROM ${a.identifier(e)}`;A&&(I=a`${I} WHERE ${A}`),I=a`${I} GROUP BY ${a.join(t.by.map(R=>fe(R)),a`, `)}`;const T=K(y,I).toArray(),D=[];for(const R of T){const P={};for(const X of t.by)P[X]=no(l.shape[X],R[X]??null);const{value:Y}=R;D.push({key:P,value:Y==null?null:Number(Y)})}return D},async insert(e,t,i){const l=H(e,"insert");if(l)return It(l,e,t,i,!0);const w=d.tables[e];if(!w)throw new $("INTERNAL",`unknown table: ${e}`);const p=i?.allowExplicitId===!0,f=Ge(w,pt(w,t,ce),{supplied:t,trusted:p});let h;i?.clientId!==void 0?(vr(i.clientId),h=i.clientId):i?.allowExplicitId&&typeof f._id=="string"?(yt(f._id),h=f._id):h=St();const E=i?.allowExplicitId&&typeof f._creationTime=="number"?f._creationTime:me(),A={...f,...ee(e),_creationTime:E,_id:h};return ne(e,"before","insert")&&await oe("before","insert",{doc:{...A},id:h,op:"insert",table:e}),p||W(e,A),Se(e),ve(e),Et(y,e,pr(e),[h,E,le(A)]),Lt(e,h,A),ne(e,"after","insert")&&await oe("after","insert",{doc:A,id:h,op:"insert",table:e}),await ye({doc:A,id:h,op:"insert",table:e}),h},async insertManyUnsafe(e,t,i){if(He(t.length,i?.limit,"insertManyUnsafe"),t.length===0)return[];const l=H(e,"insert");if(l){const E=[];_r(d.tables[e],t,i?.allowExplicitId,ce);for(const A of t)J(A);for(const A of t){const C=await l.insert(e,A,{allowExplicitId:i?.allowExplicitId});b({key:C,op:"insert",row:{...A,_id:C},table:e}),E.push(C)}return E}const w=d.tables[e];if(!w)throw new $("INTERNAL",`unknown table: ${e}`);Se(e),ve(e);const p=[];for(let E=0;E<t.length;E+=je)p.push(ee(e));const f=i?.allowExplicitId===!0?void 0:Po(w),h=t.map((E,A)=>{const C=pt(w,E,ce),I=f===void 0?C:Ge(f,C,{supplied:E}),T=i?.allowExplicitId===!0&&typeof I._id=="string"?I._id:void 0;T!==void 0&&yt(T);const D=T??St(),R=i?.allowExplicitId===!0&&typeof I._creationTime=="number"?I._creationTime:me(),P={...I,...p[Math.floor(A/je)],_creationTime:R,_id:D};return{creationTime:R,document:P,id:D}});for(const E of h)J(E.document);for(let E=0;E<h.length;E+=je){const A=a.join(h.slice(E,E+je).map(I=>a`(${I.id}, ${I.creationTime}, ${le(I.document)})`),a`, `),C=gn("sqlite",a`INSERT INTO ${a.identifier(e)} (id, _creationTime, ${a.identifier(ie)}) VALUES ${A}`);Et(y,e,C.sql,C.params)}for(const{document:E,id:A}of h)Lt(e,A,E),await ge({doc:E,id:A,op:"insert",table:e});return h.map(E=>E.id)},async insertMany(e,t,i){He(t.length,i?.limit,"insertMany");const l=i?.skipDuplicates===!0,w=[],p=H(e,"insert");if(p)for(const h of t)J(h);const f=async h=>p?It(p,e,h,void 0,!1):O.insert(e,h);for(const h of t)try{w.push(await f(h))}catch(E){if(l&&E instanceof se&&E.kind==="unique")w.push(null);else throw E}return w},normalizeId(e,t){return cn(d,e,t)},async patch(e,t,i,l){_(e,"ctx.db.patch(table, id, values)");const w=re(t,e);if(!w){const D=Te(e);if(D){J(i),await D.patch(e,t,i,l);return}throw new $("NOT_FOUND",`document not found: ${t}`)}const{docJson:p,row:f,tableName:h}=w,E=d.tables[h];if(!E)throw new $("INTERNAL",`unknown table: ${h}`);if(k(h,t),dn("patch",i),Tt(h,t,i,f)){o?.({fields:Object.keys(Ke(i)),id:t,table:h});return}const A=po(E,i,f),C={...f,...Ke(A),...ee(h),_id:t};ut(E,A,C,ce);const I=Ge(E,C,{only:new Set(Object.keys(A)),previous:()=>f,tolerateStoredNull:!0});go(l,f,I),ne(h,"before","update")&&await oe("before","update",{doc:{...I},id:t,op:"update",previous:f,table:h}),W(h,I,f),Se(h),ve(h),Ne(y,h,Zt(h),[le(I),t,p]),Fe(h,t,I,f),Le(h,t,I),ke(h,f,I),_e(h,t,f,I);const T=N(h,f,I);Ee?.invalidate(h,t,T),Re(h,t,"update",I),b({indexKeys:T,key:t,op:"update",row:I,table:h}),ne(h,"after","update")&&await oe("after","update",{doc:I,id:t,op:"update",previous:f,table:h}),await ye({doc:I,id:t,op:"update",table:h})},async patchIf(e,t,i){const l=H(e,"patchIf");if(l){if(l.patchIf===void 0)throw new $("INTERNAL",`ctx.db.patchIf on global table '${e}' is unsupported: its backend has no conditional write`);return J(i.patch),l.patchIf(e,t,i)}if(!d.tables[e])throw new $("INTERNAL",`unknown table: ${e}`);for(let w=1;w<=an;w+=1){const p=await Fn(e,t,i,w<an,f=>O.patch(e,t,f,{verify:i.verify}));if(p!==void 0)return p}throw new se(`patchIf on "${e}" kept conflicting; the row changed on every attempt`,"occ")},async patchMany(e,t,i){_(e,"ctx.db.patchMany(table, patches)"),He(t.length,i?.limit,"patchMany");for(const l of t)await O.patch(e,l.id,l.patch);return{patched:t.length}},async patchWhere(e,t,i){const l=H(e,"patchWhere")??O,p=(await on(l,e,t.where,i?.limit,"patchWhere")).map(f=>({id:String(f._id),patch:t.patch}));if(O.patchMany===void 0)throw new $("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await O.patchMany(e,p,i),{patched:p.length}},async related(e,t){return Lo(O,v,e,t)},relationEdges:v,deleteRereadTables:B,inTransaction:j,softDeleteFields:U,relationWrites:q,query(e){const t=H(e,"query");return t?(k(e,G),t.query(e)):xn(y,d,e,te,i=>{i?F(i):k(e,G)},i=>{s?.recordRead(i)})},async rank(e,t,i){const l=H(e,"rank");if(l)return k(e,G),l.rank(e,t,i);te(e,t,"rank");const w=d.tables[e];if(!w)throw new $("INTERNAL",`unknown table: ${e}`);const p=w.rankIndexes?.find(V=>V.name===t);if(!p)throw new $("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(Ft(e,w,p),i.restrictsCounts)throw new ct(e);k(e,G),nt(e,p);const f=typeof i.row=="string"?i.row:i.row._id;if(!f)return null;const h=Nt(e,p.name),E=p.sortBy.map((V,de)=>Qt(de)),A=E.map(V=>Me(V)).join(", "),C=K(y,a`SELECT ${a.identifier("__partition__")}, ${a.raw(A)} FROM ${a.identifier(h)} WHERE ${a.identifier("__id__")} = ${f}`).toArray(),[I]=C;if(I===void 0)return null;let T=I.__partition__;const D=Q(i.baseWhere,i.where);dt(D,d,e,"rank");const R=vo(p,D);if(R){const V=_o(p.partitionBy??[],R);if(V!==T)return null;T=V}const P=E.map(V=>I[V]),{before:Y,total:X}=un(y,h,E,p.sortBy,T,P,f);return{position:Y+1,total:X}},async rankBefore(e,t,i){if(ae(e))throw new $("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const l=d.tables[e];if(!l)throw new $("INTERNAL",`unknown table: ${e}`);const w=l.rankIndexes?.find(E=>E.name===t);if(!w)throw new $("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(i.restrictsCounts)throw new ct(e);k(e,G),nt(e,w);const p=Nt(e,w.name),f=w.sortBy.map((E,A)=>Qt(A)),h=w.sortBy.map((E,A)=>Ce(i.sortValues[A]??null));return un(y,p,f,w.sortBy,i.partitionKey,h,i.rowId)},async rankPage(e,t,i={}){dt(Q(i.baseWhere,i.where),d,e,"rankPage");const l=H(e,"rankPage");if(l)return k(e,G),l.rankPage(e,t,i);te(e,t,"rank");const{continueCursor:w,hasMore:p,rows:f}=Ot(Wt,e,t,i);return{continueCursor:w,isDone:!p,page:f.map(h=>h.doc)}},async rankPageRows(e,t,i={}){dt(Q(i.baseWhere,i.where),d,e,"rankPage"),te(e,t,"rank");const{directions:l,hasMore:w,rows:p}=Ot(Wt,e,t,i);return{directions:l,hasMore:w,rows:p}},async restore(e,t){_(e,"ctx.db.restore(table, id)");const i=re(t,e);if(!i){const p=Te(e);if(p?.restore){await p.restore(e,t);return}throw new $("NOT_FOUND",`document not found: ${t}`)}const l=d.tables[i.tableName]?.softDeleteMode?.field;if(!l)throw new $("INTERNAL",`ctx.db.restore: table "${i.tableName}" is not a .softDelete() table`);const w=i.row[l]!==null&&i.row[l]!==void 0;await O.patch(e,t,{[l]:null}),w&&_e(i.tableName,t,void 0,i.row)},async replace(e,t,i,l){_(e,"ctx.db.replace(table, id, document)");const w=re(t,e);if(!w){const P=Te(e);if(P){J(i),await P.replace(e,t,i,l);return}throw new $("NOT_FOUND",`document not found: ${t}`)}const{docJson:p,row:f,tableName:h}=w,E=d.tables[h];if(!E)throw new $("INTERNAL",`unknown table: ${h}`);dn("replace",i);const A=l?.allowExplicitId&&typeof i._creationTime=="number"?i._creationTime:void 0,C=typeof f._creationTime=="number"?f._creationTime:void 0,I=A??C??me(),T={...i,...ee(h),_creationTime:I,_id:t};ut(E,i,T,ce);const D=l?.allowExplicitId===!0,R=Ge(E,T,{previous:()=>f,supplied:i,trusted:D});ne(h,"before","update")&&await oe("before","update",{doc:{...R},id:t,op:"update",previous:f,table:h}),D||W(h,R,f),Se(h),ve(h),Ne(y,h,gr(h),[I,le(R),t,p]),Fe(h,t,R,f),Le(h,t,R),ke(h,f,R),_e(h,t,f,R),Ee?.invalidate(h,t,N(h,f,R)),Re(h,t,"update",R),b({indexKeys:N(h,f,R),key:t,op:"update",row:R,table:h}),ne(h,"after","update")&&await oe("after","update",{doc:R,id:t,op:"update",previous:f,table:h}),await ye({doc:R,id:t,op:"update",table:h})},async wipeShard(e){const t=new Set(e?.exclude),i=e?.tables,l=Object.entries(d.tables).filter(([h,E])=>t.has(h)||i!==void 0&&!i.includes(h)?!1:E.shardMode?.kind!=="global").map(([h])=>h);if(i!==void 0){for(const h of i)if(!d.tables[h])throw new $("INTERNAL",`wipeShard: unknown table: ${h}`)}const w={};let p=0;const{deleteAll:f}=O;if(f===void 0)throw new $("INTERNAL","wipeShard: this writer has no deleteAll");for(const h of l){const E=await f(h,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});w[h]=E.deleted,p+=E.deleted}return{deleted:p,tables:w}}},Bn={db:O,scheduler:vt};return n.enforceRls===!0?Ho(O,d,(e,t)=>re(e,t)?.tableName,v):O};export{Qi as CDC_LOG_TABLE,ps as IDEMPOTENCY_TABLE,Br as NotUniqueError,us as advanceClientWatermark,Vi as applyCdcChanges,dn as assertNoExplicitUndefined,yt as assertStorableRowId,vr as assertValidClientId,ji as backfillAggregateIndexes,Hi as backfillRankIndexes,Ki as backfillSearchIndexes,Ji as bumpCdcEpoch,zi as cdcCanVouchFor,Yi as cdcForkedError,Xi as cdcSeqLeavingRows,Zi as cdcTouchesTables,es as cdcTrimmedError,ts as compactCdcDocs,ti as createShardCtxDb,ns as cursorBelowRetainedFloor,Qr as meterReadBytes,fs as migrateClientWatermark,os as minCdcReplayableSeq,rs as minCdcSeq,cn as normalizeIdStructurally,is as readCdcChangeKeys,ss as readCdcChanges,cs as readCdcCursor,as as readCdcEpoch,hs as readClientWatermark,gs as readIdempotent,$s as runShardMigrations,Ss as selectShapeMembers,vs as selectShapeRows,Ke as stripReservedPatchFields,ds as trimCdcChanges,ys as trimIdempotent,Es as writeIdempotent};
@@ -1 +0,0 @@
1
- import{LunoraError as h}from"@lunora/errors";import{mergeWhere as I}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{decodeCursor as S,CURSOR_PREFIX as v,toBase64 as B}from"./CURSOR_PREFIX-6offuG6M.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}},j=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},U=t=>v+B(JSON.stringify([t])),M=t=>{const[n]=S(t);if(typeof n!="number"||!Number.isInteger(n)||n<0)throw new h("BAD_REQUEST","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},N=(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]:[]},A=async(t,n,r,e)=>{const s=await t.findMany(n,{limit:e.limit,omitContinueCursor:!0,where:I(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 A(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}},V=async(t,n,r,e={})=>{const s=k(e.depth,C,O,"depth"),o=k(e.limit,L,$,"limit"),a=e.cursor?M(e.cursor):0,l=e.direction??"both",u=N(n,e.edges),{id:f,table:m}=await H(t,r),[c]=await A(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:U(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,j as deriveRelationEdges,V as findRelated};