@lunora/shard-engine 1.0.0-alpha.182 → 1.0.0-alpha.183
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/conformance/index.mjs +1 -1
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/NotUniqueError-BjwNIte8.mjs +1 -0
- package/dist/packem_shared/{defineEngineContractSuite-C4w7jbyk.mjs → defineEngineContractSuite-yYnqIVh3.mjs} +1 -1
- package/package.json +1 -1
- package/dist/packem_shared/NotUniqueError-CO-HgL4c.mjs +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite-
|
|
1
|
+
import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite-yYnqIVh3.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 s,selectExportTables as i,validateImportRow as l}from"./packem_shared/exportShardRows-CZh4wrvI.mjs";import{AGGREGATE_SQL_FUNCTION as d,aggregateSqlFunction as c,matchesStaticWhere as m,normalizeCountArgument as p,throwingScheduler as u}from"./packem_shared/AGGREGATE_SQL_FUNCTION-C_ZipS9R.mjs";import{aggregateTableName as f,coerceAggregateNumber as x,encodeAggregateKey as h,foldAggregateTally as E,readAggregateValue as T}from"./packem_shared/aggregateTableName-B_CtIQCS.mjs";import{CountRlsUnsupportedError as A,mergeWhere as C,planAggregateLookup as g,selectIndexForAggregate as _,selectIndexForCount as I,selectIndexForGroupBy as b}from"./packem_shared/CountRlsUnsupportedError-BvsDqfO2.mjs";import{AUDIT_LOG_TABLE as O,appendAuditEntry as D,ensureAuditTable as P,readAuditLog as y}from"./packem_shared/AUDIT_LOG_TABLE-BFJ65SRS.mjs";import{NotUniqueError as F,assertNoExplicitUndefined as N,assertStorableRowId as k,assertValidClientId as B,createShardCtxDb as U,normalizeIdStructurally as G,stripReservedPatchFields as w}from"./packem_shared/NotUniqueError-CO-HgL4c.mjs";import{backfillAggregateIndexes as v,backfillRankIndexes as K,backfillSearchIndexes as W,backfillSearchIndexesForTable as X}from"./packem_shared/backfillAggregateIndexes-Pk0KLrfk.mjs";import{CDC_LOG_TABLE as V,CDC_LOG_TABLE_SEQ_INDEX as z,CDC_META_TABLE as Q,appendCdcChange as Y,applyCdcChanges as j,bumpCdcEpoch as J,cdcCanVouchFor as Z,cdcForkedError as $,cdcSeqLeavingRows as ee,cdcTouchesTables as re,cdcTrimmedError as oe,compactCdcDocs as ae,cursorBelowRetainedFloor as te,migrateCdcLog as se,migrateCdcMeta as ie,minCdcReplayableSeq as le,minCdcSeq as ne,readCdcChangeKeys as de,readCdcChanges as ce,readCdcCursor as me,readCdcEpoch as pe,trimCdcChanges as ue}from"./packem_shared/CDC_LOG_TABLE-BFGgqai8.mjs";import{archiveCdcSegment as fe,cdcArchiveRewound as xe,readArchivedCdcChanges as he,readCdcArchivedThrough as Ee,writeCdcArchivedThrough as Te}from"./packem_shared/archiveCdcSegment-Cr8oGLfB.mjs";import{CLIENT_WATERMARK_TABLE as Ae,advanceClientWatermark as Ce,migrateClientWatermark as ge,readClientWatermark as _e}from"./packem_shared/CLIENT_WATERMARK_TABLE-De7z_OHV.mjs";import{COMMIT_SEQ_FIELD as be,COMMIT_SEQ_TABLE as Le,allocateCommitSeq as Oe,migrateCommitSeq as De,readCommitSeq as Pe}from"./packem_shared/COMMIT_SEQ_FIELD-Da1DjGqo.mjs";import{CompanionMemo as Me,clearCompanionSignatures as Fe}from"./packem_shared/CompanionMemo-BXU5vfak.mjs";import{createCompanionSync as ke}from"./packem_shared/createCompanionSync-CEht4hXX.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as Ue,deleteGlobalShapeSnapshot as Ge,deleteGlobalShapeSnapshotsForConnection as we,migrateGlobalShapeSnapshot as qe,readGlobalShapeSnapshot as ve,writeGlobalShapeSnapshot as Ke}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-Bb6-aZuH.mjs";import{IDEMPOTENCY_TABLE as Xe,migrateIdempotency as He,readIdempotent as Ve,trimIdempotent as ze,writeIdempotent as Qe}from"./packem_shared/IDEMPOTENCY_TABLE-COrgeP3O.mjs";import{clearMemoryTables as je,isMemoryTable as Je,memoryTableNames as Ze}from"./packem_shared/clearMemoryTables-aMRERF0w.mjs";import{computeRankPage as er,resolveRankSeekTuple as rr}from"./packem_shared/computeRankPage-BZIpATcs.mjs";import{SCHEDULE_OUTBOX_TABLE as ar,deferScheduleOutbox as tr,dropScheduleOutbox as sr,forgetScheduleOutbox as ir,hasScheduleOutboxEntry as lr,migrateScheduleOutbox as nr,parkScheduleOutbox as dr,probeScheduleOutbox as cr,readDueScheduleOutbox as mr,readDueScheduleOutboxEntry as pr,readScheduleOutbox as ur,readScheduleOutboxState as Sr,recordScheduleOutbox as fr,requeueScheduleOutbox as xr,trimScheduleOutbox as hr}from"./packem_shared/SCHEDULE_OUTBOX_TABLE-iyyiSjsO.mjs";import{S as Tr,m as Rr,r as Ar,w as Cr}from"./packem_shared/ctx-db-search-state-CPKPy8N6.mjs";import{SHAPE_POKE_CURSOR_TABLE as _r,deleteShapePokeCursor as Ir,deleteShapePokeCursorsForConnection as br,migrateShapePokeCursor as Lr,minShapePokeCursor as Or,readShapePokeCursor as Dr,writeShapePokeCursor as Pr,writeShapePokeCursors as yr}from"./packem_shared/SHAPE_POKE_CURSOR_TABLE-BGvY3sFI.mjs";import{selectShapeMembers as Fr,selectShapeRows as Nr}from"./packem_shared/selectShapeMembers-Dqx_m7BF.mjs";import{DATA_MIGRATION_STATE_TABLE as Br,readMigrationStatus as Ur,runDataMigration as Gr}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-CFvBS9-M.mjs";import{SCAN_DEP as qr,createDependencyTracker as vr,depKey as Kr,tableFromDepKey as Wr}from"./packem_shared/SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as Hr,runSql as Vr}from"./packem_shared/runDrizzle-RC09zZrh.mjs";import{A as Qr,a as Yr,b as jr,D as Jr,c as Zr,d as $r,g as eo,i as ro,j as oo,e as ao,q as to,f as so,r as io,t as lo,h as no}from"./packem_shared/do-sql-105TONaE.mjs";import{WORKERD_SQLITE_LIMITS as mo,param as po,renderSql as uo,sqliteInList as So,unionAll as fo}from"./packem_shared/WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{appendStreamChunk as ho,claimStreamRun as Eo,deleteStreamRun as To,finishStreamRun as Ro,migrateDurableStreams as Ao,readStreamChunks as Co,readStreamRun as go,trimStreamRuns as _o}from"./packem_shared/appendStreamChunk-BZYgGE9Y.mjs";import{DurableStreamRunner as bo,MAX_DURABLE_STREAM_BYTES as Lo,MAX_DURABLE_STREAM_CHUNKS as Oo,decideDurableAttach as Do}from"./packem_shared/DurableStreamRunner-MMlV5qKQ.mjs";import{envOptionalPositiveInt as yo,envPositiveInt as Mo}from"./packem_shared/envOptionalPositiveInt-D2pY-c64.mjs";import{diffExternalSource as No}from"./packem_shared/diffExternalSource-B0FZlDoL.mjs";import{liftSourceId as Bo,normalizeSourceDocument as Uo,normalizeSourceValue as Go}from"./packem_shared/liftSourceId-CA3ENhXj.mjs";import{materializeExternalRows as qo,materializeExternalRowsIncremental as vo,readExternalSourceBaseline as Ko,runExternalSourceTick as Wo}from"./packem_shared/materializeExternalRows-CHPRx8fu.mjs";import{isSoftDeleted as Ho,isSourceDue as Vo,pullExternalSourceIncrementalTick as zo,pullExternalSourceTick as Qo}from"./packem_shared/isSoftDeleted-BBWKE0Sm.mjs";import{f as jo,a as Jo,b as Zo,c as $o,d as ea,g as ra}from"./packem_shared/fts-companion-CE3EmIjk.mjs";import{GEO_DEFAULT_PRECISION as aa,boundingBoxCenter as ta,boundingBoxGeohashes as sa,coveringGeohashes as ia,encodeGeohash as la,haversineMeters as na,pointInBoundingBox as da}from"./packem_shared/GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{default as ma}from"./packem_shared/GlobalPollTick-BNK4o-XT.mjs";import{ADMIN_FUNCTIONS as ua,ADMIN_FUNCTION_PREFIX as Sa,DEFAULT_FANOUT_TOPIC_LIMIT as fa,FLAGS_FUNCTION_PREFIX as xa,MAX_PAGE_SIZE as ha,RELATION_FUNCTION_PREFIX as Ea,createFanoutCounters as Ta,createGlobalPollCounters as Ra,createShapeProbeCounters as Aa,facetColumn as Ca,findStorageReferences as ga,isVacuousFilterClause as _a,listTables as Ia,readTablePage as ba,recordFanoutPass as La,recordGlobalPollPass as Oa,recordShapeProbePass as Da,selectMatchingIds as Pa,summarizeFanoutTopics as ya,summarizeSubscriptions as Ma}from"./packem_shared/ADMIN_FUNCTIONS-BMBnudzO.mjs";import{MAIL_RETENTION as Na,MAIL_TABLE as ka,clearCapturedMail as Ba,ensureMailTable as Ua,readCapturedMail as Ga,recordCapturedMail as wa}from"./packem_shared/MAIL_RETENTION-DMolrLYt.mjs";import{NotFoundError as va}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{assertPatchAllowed as Wa,operatorFields as Xa,patchDependsOnRow as Ha,readPatchField as Va,resolvePatch as za}from"./packem_shared/assertPatchAllowed-CA_H466g.mjs";import{armRestore as Ya,readBookmark as ja}from"./packem_shared/armRestore-Bu1_8SUa.mjs";import{CURSOR_PREFIX as Za,applySelect as $a,buildSeekBeforeWhere as et,buildSeekWhere as rt,decodeCursor as ot,encodeCursor as at,equalityPinnedFields as tt,normalizeOrderKeys as st,nullsFirstOf as it,nullsOrderSuffix as lt,softDeleteScope as nt,tiebreakDirectionFor as dt,uniqueIndexFields as ct}from"./packem_shared/CURSOR_PREFIX-6offuG6M.mjs";import{QUEUE_TABLE as pt,clearQueueMessages as ut,isLossyBody as St,readQueueMessageById as ft,readQueueMessages as xt,recordQueueMessages as ht}from"./packem_shared/QUEUE_TABLE-C-goXtGd.mjs";import{RANK_TIEBREAK as Tt,encodePartitionKey as Rt,matchesRankStaticWhere as At,rankKeyFromDoc as Ct,rankPivotConditionSql as gt,rankTableName as _t,resolveRankPartition as It,sortColumnName as bt}from"./packem_shared/RANK_TIEBREAK-D3ye2GsL.mjs";import{ReactiveCache as Ot,reactiveCacheKey as Dt}from"./packem_shared/ReactiveCache-5XPk8qfW.mjs";import{REACTOR_STATE_TABLE as yt,listReactorStates as Mt,migrateReactorState as Ft,reactorNeedsRun as Nt,readReactorState as kt,writeReactorState as Bt}from"./packem_shared/REACTOR_STATE_TABLE-D2Mn204f.mjs";import{UNVOUCHABLE_DEP as Gt,createReadFootprint as wt,markUnvouchableReads as qt}from"./packem_shared/UNVOUCHABLE_DEP-Ds9gxVqs.mjs";import{buildIndexRange as Kt,indexKeysForRow as Wt,keysTouchRanges as Xt}from"./packem_shared/buildIndexRange-BTChxh3k.mjs";import{isPushableWhere as Vt,whereFilter as zt,whereOfFilter as Qt}from"./packem_shared/isPushableWhere-BeYAOjUb.mjs";import{RELATED_DEFAULT_LIMIT as jt,RELATED_DEPTH_DECAY as Jt,RELATED_MAX_DEPTH as Zt,RELATED_MAX_LIMIT as $t,deriveRelationEdges as es,findRelated as rs}from"./packem_shared/RELATED_DEFAULT_LIMIT-CVqN4JEu.mjs";import{DEFAULT_MAX_RELATION_KEYS as as,assertFlatPredicate as ts,assertShapeShardable as ss,composeReadPredicate as is,containsRelationPredicate as ls,isRelationPredicate as ns,resolveRelationPredicates as ds}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-DfrMi_eE.mjs";import{describeRelationWrites as ms}from"./packem_shared/describeRelationWrites-omar6-u9.mjs";import{applyInsertDefaults as us,applyOnDelete as Ss,distinctValues as fs,fanOutScalarCounts as xs,relationHooks as hs,resolveWith as Es,runRowValidators as Ts}from"./packem_shared/applyInsertDefaults-CVukTkQ5.mjs";import{D as As,c as Cs,n as gs,r as _s,s as Is}from"./packem_shared/relay-CKEdfUjH.mjs";import{DEFAULT_MAX_RELAYS as Ls,OwnerRelay as Os,RelayMember as Ds,createRelayLink as Ps}from"./packem_shared/DEFAULT_MAX_RELAYS-B66neS_B.mjs";import{createReplicaLink as Ms,gateReplicaDispatch as Fs,handleReplicaControl as Ns}from"./packem_shared/createReplicaLink-DVXW9rR6.mjs";import{buildReprojectionMigration as Bs,countLegacyRows as Us,reprojectableFields as Gs,reprojectionTables as ws}from"./packem_shared/buildReprojectionMigration-B8aEpETD.mjs";import{RLS_UNWRAP_SYMBOL as vs,RlsRequiredError as Ks,guardWriter as Ws}from"./packem_shared/RLS_UNWRAP_SYMBOL-H6J96vgK.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as Hs,readSchemaHistory as Vs,readSchemaVersion as zs,recordSchemaVersion as Qs}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-CEwFjj-O.mjs";import{serializeSqlValue as js}from"./packem_shared/serializeSqlValue-DeoBMpZ2.mjs";import{buildSettings as Zs,isDevEnvironment as $s,readDeployInfo as ei}from"./packem_shared/buildSettings-BRkZd6_E.mjs";import{buildShapeDiff as oi}from"./packem_shared/buildShapeDiff-CdLJTijm.mjs";import{ShapeDiffCache as ti,createShapeDiffCache as si,globalShapeReadKey as ii}from"./packem_shared/ShapeDiffCache-iNO-hUiy.mjs";import{buildPokeFrames as ni,diffGlobalMembership as di,encodeRowsPatch as ci,projectColumns as mi}from"./packem_shared/buildPokeFrames-WR-hp0mX.mjs";import{ShardRunner as ui}from"./packem_shared/ShardRunner-CrveaPId.mjs";import{stubByName as fi}from"./packem_shared/stubByName-B8cFYipA.mjs";import{runSocketPool as hi}from"./packem_shared/runSocketPool-CZJ2X9cF.mjs";import{MAX_SQL_ROWS as Ti,assertReadonly as Ri,lintReadonlySql as Ai,runReadonlySql as Ci}from"./packem_shared/MAX_SQL_ROWS-eRignWyO.mjs";import{BIGINT_KEY_DIGITS as _i,bigintSqlKey as Ii,decodeBigintSqlKey as bi,decodeFloat64SqlKey as Li,float64SqlKey as Oi}from"./packem_shared/BIGINT_KEY_DIGITS-DE6yshOt.mjs";import{awaitWsDrain as Pi,subscriptionFrames as yi,subscriptionListDeltas as Mi,trySendFrame as Fi}from"./packem_shared/awaitWsDrain-DMcWBQ7I.mjs";import{mergeChangedKeys as ki,recordChangedKeys as Bi,writeTouchesMemo as Ui}from"./packem_shared/mergeChangedKeys-DPKhen6e.mjs";import{createSystemReader as wi}from"./packem_shared/createSystemReader-BSCxr8Qs.mjs";import{ConflictError as vi}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as Wi,TransactionHeadroomTracker as Xi}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS-D7p7Ys0M.mjs";import{hasTrigger as Vi,runTriggers as zi}from"./packem_shared/hasTrigger-CjlwI4le.mjs";import{isTtlExpired as Yi,nextTtlExpiry as ji,selectExpiredIds as Ji}from"./packem_shared/isTtlExpired-DNxmZA6e.mjs";import{VECTOR_BACKFILL_MAX_PAGES as $i,backfillVectorIndexes as el}from"./packem_shared/VECTOR_BACKFILL_MAX_PAGES-DcQpf83n.mjs";import{c as ol,s as al}from"./packem_shared/where-sql-BjY4rnqb.mjs";import{RELATION_EXISTS_KEY as sl}from"./packem_shared/RELATION_EXISTS_KEY-wxgj6rSL.mjs";import{RELAY_SIGNATURE_HEADER as ll,siblingSecretOf as nl,signSiblingBody as dl,verifySiblingBody as cl}from"./packem_shared/RELAY_SIGNATURE_HEADER-DP0glzE_.mjs";import{REPROJECTION_MIGRATION_PREFIX as pl,reprojectionMigrationId as ul}from"./packem_shared/REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{isInternalTableName as fl}from"./packem_shared/isInternalTableName-BoljO2tP.mjs";import{quoteIdentifier as hl}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as Tl}from"./packem_shared/runShardMigrations-xu993yo2.mjs";import{stableStringify as Al,stableWireKey as Cl}from"@lunora/wire";export{ua as ADMIN_FUNCTIONS,Sa as ADMIN_FUNCTION_PREFIX,d as AGGREGATE_SQL_FUNCTION,Qr as AGG_COUNT,Yr as AGG_KEY,jr as AGG_VALUE,O as AUDIT_LOG_TABLE,_i as BIGINT_KEY_DIGITS,V as CDC_LOG_TABLE,z as CDC_LOG_TABLE_SEQ_INDEX,Q as CDC_META_TABLE,Ae as CLIENT_WATERMARK_TABLE,be as COMMIT_SEQ_FIELD,Le as COMMIT_SEQ_TABLE,Za as CURSOR_PREFIX,Me as CompanionMemo,vi as ConflictError,A as CountRlsUnsupportedError,Br as DATA_MIGRATION_STATE_TABLE,fa as DEFAULT_FANOUT_TOPIC_LIMIT,as as DEFAULT_MAX_RELATION_KEYS,Ls as DEFAULT_MAX_RELAYS,As as DEFAULT_PROMOTION_THRESHOLDS,Wi as DEFAULT_TRANSACTION_LIMITS,Jr as DOC_COLUMN,bo as DurableStreamRunner,xa as FLAGS_FUNCTION_PREFIX,aa as GEO_DEFAULT_PRECISION,Ue as GLOBAL_SHAPE_SNAPSHOT_TABLE,ma as GlobalPollTick,Xe as IDEMPOTENCY_TABLE,Na as MAIL_RETENTION,ka as MAIL_TABLE,Lo as MAX_DURABLE_STREAM_BYTES,Oo as MAX_DURABLE_STREAM_CHUNKS,ha as MAX_PAGE_SIZE,Ti as MAX_SQL_ROWS,va as NotFoundError,F as NotUniqueError,Os as OwnerRelay,pt as QUEUE_TABLE,Tt as RANK_TIEBREAK,yt as REACTOR_STATE_TABLE,jt as RELATED_DEFAULT_LIMIT,Jt as RELATED_DEPTH_DECAY,Zt as RELATED_MAX_DEPTH,$t as RELATED_MAX_LIMIT,sl as RELATION_EXISTS_KEY,Ea as RELATION_FUNCTION_PREFIX,ll as RELAY_SIGNATURE_HEADER,pl as REPROJECTION_MIGRATION_PREFIX,vs as RLS_UNWRAP_SYMBOL,Ot as ReactiveCache,Ds as RelayMember,Ks as RlsRequiredError,qr as SCAN_DEP,ar as SCHEDULE_OUTBOX_TABLE,Hs as SCHEMA_HISTORY_MAX_VERSIONS,Tr as SEARCH_STATE_TABLE,_r as SHAPE_POKE_CURSOR_TABLE,ti as ShapeDiffCache,ui as ShardRunner,Xi as TransactionHeadroomTracker,Gt as UNVOUCHABLE_DEP,$i as VECTOR_BACKFILL_MAX_PAGES,mo as WORKERD_SQLITE_LIMITS,Ce as advanceClientWatermark,Zr as aggUpsertSql,c as aggregateSqlFunction,f as aggregateTableName,Oe as allocateCommitSeq,D as appendAuditEntry,Y as appendCdcChange,ho as appendStreamChunk,j as applyCdcChanges,us as applyInsertDefaults,Ss as applyOnDelete,$a as applySelect,fe as archiveCdcSegment,Ya as armRestore,ts as assertFlatPredicate,N as assertNoExplicitUndefined,Wa as assertPatchAllowed,Ri as assertReadonly,ss as assertShapeShardable,k as assertStorableRowId,B as assertValidClientId,Pi as awaitWsDrain,v as backfillAggregateIndexes,K as backfillRankIndexes,W as backfillSearchIndexes,X as backfillSearchIndexesForTable,el as backfillVectorIndexes,Ii as bigintSqlKey,ta as boundingBoxCenter,sa as boundingBoxGeohashes,Kt as buildIndexRange,ni as buildPokeFrames,Bs as buildReprojectionMigration,et as buildSeekBeforeWhere,rt as buildSeekWhere,Zs as buildSettings,oi as buildShapeDiff,J as bumpCdcEpoch,xe as cdcArchiveRewound,Z as cdcCanVouchFor,$ as cdcForkedError,ee as cdcSeqLeavingRows,re as cdcTouchesTables,oe as cdcTrimmedError,Eo as claimStreamRun,Cs as clampPromotionThresholds,Ba as clearCapturedMail,Fe as clearCompanionSignatures,je as clearMemoryTables,ut as clearQueueMessages,x as coerceAggregateNumber,ae as compactCdcDocs,ol as compileWhereSql,is as composeReadPredicate,er as computeRankPage,ls as containsRelationPredicate,Us as countLegacyRows,ia as coveringGeohashes,ke as createCompanionSync,vr as createDependencyTracker,Ta as createFanoutCounters,Ra as createGlobalPollCounters,$r as createIndexSql,wt as createReadFootprint,Ps as createRelayLink,Ms as createReplicaLink,si as createShapeDiffCache,Aa as createShapeProbeCounters,U as createShardCtxDb,wi as createSystemReader,te as cursorBelowRetainedFloor,Do as decideDurableAttach,bi as decodeBigintSqlKey,ot as decodeCursor,Li as decodeFloat64SqlKey,tr as deferScheduleOutbox,Ge as deleteGlobalShapeSnapshot,we as deleteGlobalShapeSnapshotsForConnection,Ir as deleteShapePokeCursor,br as deleteShapePokeCursorsForConnection,To as deleteStreamRun,Kr as depKey,es as deriveRelationEdges,ms as describeRelationWrites,No as diffExternalSource,di as diffGlobalMembership,fs as distinctValues,sr as dropScheduleOutbox,h as encodeAggregateKey,at as encodeCursor,la as encodeGeohash,Rt as encodePartitionKey,ci as encodeRowsPatch,P as ensureAuditTable,Ua as ensureMailTable,yo as envOptionalPositiveInt,Mo as envPositiveInt,tt as equalityPinnedFields,o as exportShardRows,Ca as facetColumn,xs as fanOutScalarCounts,rs as findRelated,ga as findStorageReferences,Ro as finishStreamRun,Oi as float64SqlKey,E as foldAggregateTally,ir as forgetScheduleOutbox,jo as ftsCompanionDdl,Jo as ftsPurgeDocument,Zo as ftsRowidMapName,$o as ftsUnmappedPage,ea as ftsWriteDocument,Fs as gateReplicaDispatch,eo as geoTableName,ii as globalShapeReadKey,ra as groupUnmappedRows,Ws as guardWriter,Ns as handleReplicaControl,lr as hasScheduleOutboxEntry,Vi as hasTrigger,na as haversineMeters,a as importShardRows,Wt as indexKeysForRow,$s as isDevEnvironment,ro as isFtsAvailable,fl as isInternalTableName,St as isLossyBody,Je as isMemoryTable,Vt as isPushableWhere,ns as isRelationPredicate,Ho as isSoftDeleted,Vo as isSourceDue,Yi as isTtlExpired,_a as isVacuousFilterClause,oo as jsonPath,ao as jsonPathSql,Xt as keysTouchRanges,Bo as liftSourceId,Ai as lintReadonlySql,Mt as listReactorStates,Ia as listTables,qt as markUnvouchableReads,At as matchesRankStaticWhere,m as matchesStaticWhere,qo as materializeExternalRows,vo as materializeExternalRowsIncremental,Ze as memoryTableNames,ki as mergeChangedKeys,C as mergeWhere,se as migrateCdcLog,ie as migrateCdcMeta,ge as migrateClientWatermark,De as migrateCommitSeq,Ao as migrateDurableStreams,qe as migrateGlobalShapeSnapshot,He as migrateIdempotency,Ft as migrateReactorState,nr as migrateScheduleOutbox,Rr as migrateSearchState,Lr as migrateShapePokeCursor,le as minCdcReplayableSeq,ne as minCdcSeq,Or as minShapePokeCursor,gs as nextPromotionState,ji as nextTtlExpiry,p as normalizeCountArgument,G as normalizeIdStructurally,st as normalizeOrderKeys,Uo as normalizeSourceDocument,Go as normalizeSourceValue,it as nullsFirstOf,lt as nullsOrderSuffix,Xa as operatorFields,po as param,dr as parkScheduleOutbox,t as parseExportShardArgs,s as parseImportShardArgs,Ha as patchDependsOnRow,g as planAggregateLookup,da as pointInBoundingBox,cr as probeScheduleOutbox,mi as projectColumns,zo as pullExternalSourceIncrementalTick,Qo as pullExternalSourceTick,to as qualifiedJsonPath,so as qualifiedJsonPathSql,hl as quoteIdentifier,Ct as rankKeyFromDoc,gt as rankPivotConditionSql,_t as rankTableName,Dt as reactiveCacheKey,Nt as reactorNeedsRun,T as readAggregateValue,he as readArchivedCdcChanges,y as readAuditLog,ja as readBookmark,Ga as readCapturedMail,Ee as readCdcArchivedThrough,de as readCdcChangeKeys,ce as readCdcChanges,me as readCdcCursor,pe as readCdcEpoch,_e as readClientWatermark,Pe as readCommitSeq,ei as readDeployInfo,mr as readDueScheduleOutbox,pr as readDueScheduleOutboxEntry,Ko as readExternalSourceBaseline,ve as readGlobalShapeSnapshot,Ve as readIdempotent,Ur as readMigrationStatus,Va as readPatchField,ft as readQueueMessageById,xt as readQueueMessages,kt as readReactorState,ur as readScheduleOutbox,Sr as readScheduleOutboxState,Vs as readSchemaHistory,zs as readSchemaVersion,Ar as readSearchBackfillState,Dr as readShapePokeCursor,Co as readStreamChunks,go as readStreamRun,ba as readTablePage,wa as recordCapturedMail,Bi as recordChangedKeys,La as recordFanoutPass,Oa as recordGlobalPollPass,ht as recordQueueMessages,fr as recordScheduleOutbox,Qs as recordSchemaVersion,Da as recordShapeProbePass,hs as relationHooks,_s as relayCountFor,uo as renderSql,Gs as reprojectableFields,ul as reprojectionMigrationId,ws as reprojectionTables,xr as requeueScheduleOutbox,za as resolvePatch,It as resolveRankPartition,rr as resolveRankSeekTuple,ds as resolveRelationPredicates,Es as resolveWith,io as rowToDocument,Gr as runDataMigration,Hr as runDrizzle,Wo as runExternalSourceTick,Ci as runReadonlySql,Ts as runRowValidators,Tl as runShardMigrations,hi as runSocketPool,Vr as runSql,zi as runTriggers,Ji as selectExpiredIds,i as selectExportTables,_ as selectIndexForAggregate,I as selectIndexForCount,b as selectIndexForGroupBy,Pa as selectMatchingIds,Fr as selectShapeMembers,Nr as selectShapeRows,js as serializeSqlValue,al as serverInList,Is as shapeRoutingKey,nl as siblingSecretOf,dl as signSiblingBody,nt as softDeleteScope,bt as sortColumnName,So as sqliteInList,Al as stableStringify,Cl as stableWireKey,w as stripReservedPatchFields,fi as stubByName,yi as subscriptionFrames,Mi as subscriptionListDeltas,ya as summarizeFanoutTopics,Ma as summarizeSubscriptions,lo as tableColumns,Wr as tableFromDepKey,u as throwingScheduler,dt as tiebreakDirectionFor,ue as trimCdcChanges,ze as trimIdempotent,hr as trimScheduleOutbox,_o as trimStreamRuns,no as tryRowToDocument,Fi as trySendFrame,fo as unionAll,ct as uniqueIndexFields,l as validateImportRow,cl as verifySiblingBody,zt as whereFilter,Qt as whereOfFilter,Te as writeCdcArchivedThrough,Ke as writeGlobalShapeSnapshot,Qe as writeIdempotent,Bt as writeReactorState,Cr as writeSearchBackfillState,Pr as writeShapePokeCursor,yr as writeShapePokeCursors,Ui as writeTouchesMemo};
|
|
1
|
+
import{exportShardRows as o,importShardRows as a,parseExportShardArgs as t,parseImportShardArgs as s,selectExportTables as i,validateImportRow as l}from"./packem_shared/exportShardRows-CZh4wrvI.mjs";import{AGGREGATE_SQL_FUNCTION as d,aggregateSqlFunction as c,matchesStaticWhere as m,normalizeCountArgument as p,throwingScheduler as u}from"./packem_shared/AGGREGATE_SQL_FUNCTION-C_ZipS9R.mjs";import{aggregateTableName as f,coerceAggregateNumber as x,encodeAggregateKey as h,foldAggregateTally as E,readAggregateValue as T}from"./packem_shared/aggregateTableName-B_CtIQCS.mjs";import{CountRlsUnsupportedError as A,mergeWhere as C,planAggregateLookup as g,selectIndexForAggregate as _,selectIndexForCount as I,selectIndexForGroupBy as b}from"./packem_shared/CountRlsUnsupportedError-BvsDqfO2.mjs";import{AUDIT_LOG_TABLE as O,appendAuditEntry as D,ensureAuditTable as P,readAuditLog as y}from"./packem_shared/AUDIT_LOG_TABLE-BFJ65SRS.mjs";import{NotUniqueError as F,assertNoExplicitUndefined as N,assertStorableRowId as k,assertValidClientId as B,createShardCtxDb as U,normalizeIdStructurally as G,stripReservedPatchFields as w}from"./packem_shared/NotUniqueError-BjwNIte8.mjs";import{backfillAggregateIndexes as v,backfillRankIndexes as K,backfillSearchIndexes as W,backfillSearchIndexesForTable as X}from"./packem_shared/backfillAggregateIndexes-Pk0KLrfk.mjs";import{CDC_LOG_TABLE as V,CDC_LOG_TABLE_SEQ_INDEX as z,CDC_META_TABLE as Q,appendCdcChange as Y,applyCdcChanges as j,bumpCdcEpoch as J,cdcCanVouchFor as Z,cdcForkedError as $,cdcSeqLeavingRows as ee,cdcTouchesTables as re,cdcTrimmedError as oe,compactCdcDocs as ae,cursorBelowRetainedFloor as te,migrateCdcLog as se,migrateCdcMeta as ie,minCdcReplayableSeq as le,minCdcSeq as ne,readCdcChangeKeys as de,readCdcChanges as ce,readCdcCursor as me,readCdcEpoch as pe,trimCdcChanges as ue}from"./packem_shared/CDC_LOG_TABLE-BFGgqai8.mjs";import{archiveCdcSegment as fe,cdcArchiveRewound as xe,readArchivedCdcChanges as he,readCdcArchivedThrough as Ee,writeCdcArchivedThrough as Te}from"./packem_shared/archiveCdcSegment-Cr8oGLfB.mjs";import{CLIENT_WATERMARK_TABLE as Ae,advanceClientWatermark as Ce,migrateClientWatermark as ge,readClientWatermark as _e}from"./packem_shared/CLIENT_WATERMARK_TABLE-De7z_OHV.mjs";import{COMMIT_SEQ_FIELD as be,COMMIT_SEQ_TABLE as Le,allocateCommitSeq as Oe,migrateCommitSeq as De,readCommitSeq as Pe}from"./packem_shared/COMMIT_SEQ_FIELD-Da1DjGqo.mjs";import{CompanionMemo as Me,clearCompanionSignatures as Fe}from"./packem_shared/CompanionMemo-BXU5vfak.mjs";import{createCompanionSync as ke}from"./packem_shared/createCompanionSync-CEht4hXX.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as Ue,deleteGlobalShapeSnapshot as Ge,deleteGlobalShapeSnapshotsForConnection as we,migrateGlobalShapeSnapshot as qe,readGlobalShapeSnapshot as ve,writeGlobalShapeSnapshot as Ke}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-Bb6-aZuH.mjs";import{IDEMPOTENCY_TABLE as Xe,migrateIdempotency as He,readIdempotent as Ve,trimIdempotent as ze,writeIdempotent as Qe}from"./packem_shared/IDEMPOTENCY_TABLE-COrgeP3O.mjs";import{clearMemoryTables as je,isMemoryTable as Je,memoryTableNames as Ze}from"./packem_shared/clearMemoryTables-aMRERF0w.mjs";import{computeRankPage as er,resolveRankSeekTuple as rr}from"./packem_shared/computeRankPage-BZIpATcs.mjs";import{SCHEDULE_OUTBOX_TABLE as ar,deferScheduleOutbox as tr,dropScheduleOutbox as sr,forgetScheduleOutbox as ir,hasScheduleOutboxEntry as lr,migrateScheduleOutbox as nr,parkScheduleOutbox as dr,probeScheduleOutbox as cr,readDueScheduleOutbox as mr,readDueScheduleOutboxEntry as pr,readScheduleOutbox as ur,readScheduleOutboxState as Sr,recordScheduleOutbox as fr,requeueScheduleOutbox as xr,trimScheduleOutbox as hr}from"./packem_shared/SCHEDULE_OUTBOX_TABLE-iyyiSjsO.mjs";import{S as Tr,m as Rr,r as Ar,w as Cr}from"./packem_shared/ctx-db-search-state-CPKPy8N6.mjs";import{SHAPE_POKE_CURSOR_TABLE as _r,deleteShapePokeCursor as Ir,deleteShapePokeCursorsForConnection as br,migrateShapePokeCursor as Lr,minShapePokeCursor as Or,readShapePokeCursor as Dr,writeShapePokeCursor as Pr,writeShapePokeCursors as yr}from"./packem_shared/SHAPE_POKE_CURSOR_TABLE-BGvY3sFI.mjs";import{selectShapeMembers as Fr,selectShapeRows as Nr}from"./packem_shared/selectShapeMembers-Dqx_m7BF.mjs";import{DATA_MIGRATION_STATE_TABLE as Br,readMigrationStatus as Ur,runDataMigration as Gr}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-CFvBS9-M.mjs";import{SCAN_DEP as qr,createDependencyTracker as vr,depKey as Kr,tableFromDepKey as Wr}from"./packem_shared/SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as Hr,runSql as Vr}from"./packem_shared/runDrizzle-RC09zZrh.mjs";import{A as Qr,a as Yr,b as jr,D as Jr,c as Zr,d as $r,g as eo,i as ro,j as oo,e as ao,q as to,f as so,r as io,t as lo,h as no}from"./packem_shared/do-sql-105TONaE.mjs";import{WORKERD_SQLITE_LIMITS as mo,param as po,renderSql as uo,sqliteInList as So,unionAll as fo}from"./packem_shared/WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{appendStreamChunk as ho,claimStreamRun as Eo,deleteStreamRun as To,finishStreamRun as Ro,migrateDurableStreams as Ao,readStreamChunks as Co,readStreamRun as go,trimStreamRuns as _o}from"./packem_shared/appendStreamChunk-BZYgGE9Y.mjs";import{DurableStreamRunner as bo,MAX_DURABLE_STREAM_BYTES as Lo,MAX_DURABLE_STREAM_CHUNKS as Oo,decideDurableAttach as Do}from"./packem_shared/DurableStreamRunner-MMlV5qKQ.mjs";import{envOptionalPositiveInt as yo,envPositiveInt as Mo}from"./packem_shared/envOptionalPositiveInt-D2pY-c64.mjs";import{diffExternalSource as No}from"./packem_shared/diffExternalSource-B0FZlDoL.mjs";import{liftSourceId as Bo,normalizeSourceDocument as Uo,normalizeSourceValue as Go}from"./packem_shared/liftSourceId-CA3ENhXj.mjs";import{materializeExternalRows as qo,materializeExternalRowsIncremental as vo,readExternalSourceBaseline as Ko,runExternalSourceTick as Wo}from"./packem_shared/materializeExternalRows-CHPRx8fu.mjs";import{isSoftDeleted as Ho,isSourceDue as Vo,pullExternalSourceIncrementalTick as zo,pullExternalSourceTick as Qo}from"./packem_shared/isSoftDeleted-BBWKE0Sm.mjs";import{f as jo,a as Jo,b as Zo,c as $o,d as ea,g as ra}from"./packem_shared/fts-companion-CE3EmIjk.mjs";import{GEO_DEFAULT_PRECISION as aa,boundingBoxCenter as ta,boundingBoxGeohashes as sa,coveringGeohashes as ia,encodeGeohash as la,haversineMeters as na,pointInBoundingBox as da}from"./packem_shared/GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{default as ma}from"./packem_shared/GlobalPollTick-BNK4o-XT.mjs";import{ADMIN_FUNCTIONS as ua,ADMIN_FUNCTION_PREFIX as Sa,DEFAULT_FANOUT_TOPIC_LIMIT as fa,FLAGS_FUNCTION_PREFIX as xa,MAX_PAGE_SIZE as ha,RELATION_FUNCTION_PREFIX as Ea,createFanoutCounters as Ta,createGlobalPollCounters as Ra,createShapeProbeCounters as Aa,facetColumn as Ca,findStorageReferences as ga,isVacuousFilterClause as _a,listTables as Ia,readTablePage as ba,recordFanoutPass as La,recordGlobalPollPass as Oa,recordShapeProbePass as Da,selectMatchingIds as Pa,summarizeFanoutTopics as ya,summarizeSubscriptions as Ma}from"./packem_shared/ADMIN_FUNCTIONS-BMBnudzO.mjs";import{MAIL_RETENTION as Na,MAIL_TABLE as ka,clearCapturedMail as Ba,ensureMailTable as Ua,readCapturedMail as Ga,recordCapturedMail as wa}from"./packem_shared/MAIL_RETENTION-DMolrLYt.mjs";import{NotFoundError as va}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{assertPatchAllowed as Wa,operatorFields as Xa,patchDependsOnRow as Ha,readPatchField as Va,resolvePatch as za}from"./packem_shared/assertPatchAllowed-CA_H466g.mjs";import{armRestore as Ya,readBookmark as ja}from"./packem_shared/armRestore-Bu1_8SUa.mjs";import{CURSOR_PREFIX as Za,applySelect as $a,buildSeekBeforeWhere as et,buildSeekWhere as rt,decodeCursor as ot,encodeCursor as at,equalityPinnedFields as tt,normalizeOrderKeys as st,nullsFirstOf as it,nullsOrderSuffix as lt,softDeleteScope as nt,tiebreakDirectionFor as dt,uniqueIndexFields as ct}from"./packem_shared/CURSOR_PREFIX-6offuG6M.mjs";import{QUEUE_TABLE as pt,clearQueueMessages as ut,isLossyBody as St,readQueueMessageById as ft,readQueueMessages as xt,recordQueueMessages as ht}from"./packem_shared/QUEUE_TABLE-C-goXtGd.mjs";import{RANK_TIEBREAK as Tt,encodePartitionKey as Rt,matchesRankStaticWhere as At,rankKeyFromDoc as Ct,rankPivotConditionSql as gt,rankTableName as _t,resolveRankPartition as It,sortColumnName as bt}from"./packem_shared/RANK_TIEBREAK-D3ye2GsL.mjs";import{ReactiveCache as Ot,reactiveCacheKey as Dt}from"./packem_shared/ReactiveCache-5XPk8qfW.mjs";import{REACTOR_STATE_TABLE as yt,listReactorStates as Mt,migrateReactorState as Ft,reactorNeedsRun as Nt,readReactorState as kt,writeReactorState as Bt}from"./packem_shared/REACTOR_STATE_TABLE-D2Mn204f.mjs";import{UNVOUCHABLE_DEP as Gt,createReadFootprint as wt,markUnvouchableReads as qt}from"./packem_shared/UNVOUCHABLE_DEP-Ds9gxVqs.mjs";import{buildIndexRange as Kt,indexKeysForRow as Wt,keysTouchRanges as Xt}from"./packem_shared/buildIndexRange-BTChxh3k.mjs";import{isPushableWhere as Vt,whereFilter as zt,whereOfFilter as Qt}from"./packem_shared/isPushableWhere-BeYAOjUb.mjs";import{RELATED_DEFAULT_LIMIT as jt,RELATED_DEPTH_DECAY as Jt,RELATED_MAX_DEPTH as Zt,RELATED_MAX_LIMIT as $t,deriveRelationEdges as es,findRelated as rs}from"./packem_shared/RELATED_DEFAULT_LIMIT-CVqN4JEu.mjs";import{DEFAULT_MAX_RELATION_KEYS as as,assertFlatPredicate as ts,assertShapeShardable as ss,composeReadPredicate as is,containsRelationPredicate as ls,isRelationPredicate as ns,resolveRelationPredicates as ds}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-DfrMi_eE.mjs";import{describeRelationWrites as ms}from"./packem_shared/describeRelationWrites-omar6-u9.mjs";import{applyInsertDefaults as us,applyOnDelete as Ss,distinctValues as fs,fanOutScalarCounts as xs,relationHooks as hs,resolveWith as Es,runRowValidators as Ts}from"./packem_shared/applyInsertDefaults-CVukTkQ5.mjs";import{D as As,c as Cs,n as gs,r as _s,s as Is}from"./packem_shared/relay-CKEdfUjH.mjs";import{DEFAULT_MAX_RELAYS as Ls,OwnerRelay as Os,RelayMember as Ds,createRelayLink as Ps}from"./packem_shared/DEFAULT_MAX_RELAYS-B66neS_B.mjs";import{createReplicaLink as Ms,gateReplicaDispatch as Fs,handleReplicaControl as Ns}from"./packem_shared/createReplicaLink-DVXW9rR6.mjs";import{buildReprojectionMigration as Bs,countLegacyRows as Us,reprojectableFields as Gs,reprojectionTables as ws}from"./packem_shared/buildReprojectionMigration-B8aEpETD.mjs";import{RLS_UNWRAP_SYMBOL as vs,RlsRequiredError as Ks,guardWriter as Ws}from"./packem_shared/RLS_UNWRAP_SYMBOL-H6J96vgK.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as Hs,readSchemaHistory as Vs,readSchemaVersion as zs,recordSchemaVersion as Qs}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-CEwFjj-O.mjs";import{serializeSqlValue as js}from"./packem_shared/serializeSqlValue-DeoBMpZ2.mjs";import{buildSettings as Zs,isDevEnvironment as $s,readDeployInfo as ei}from"./packem_shared/buildSettings-BRkZd6_E.mjs";import{buildShapeDiff as oi}from"./packem_shared/buildShapeDiff-CdLJTijm.mjs";import{ShapeDiffCache as ti,createShapeDiffCache as si,globalShapeReadKey as ii}from"./packem_shared/ShapeDiffCache-iNO-hUiy.mjs";import{buildPokeFrames as ni,diffGlobalMembership as di,encodeRowsPatch as ci,projectColumns as mi}from"./packem_shared/buildPokeFrames-WR-hp0mX.mjs";import{ShardRunner as ui}from"./packem_shared/ShardRunner-CrveaPId.mjs";import{stubByName as fi}from"./packem_shared/stubByName-B8cFYipA.mjs";import{runSocketPool as hi}from"./packem_shared/runSocketPool-CZJ2X9cF.mjs";import{MAX_SQL_ROWS as Ti,assertReadonly as Ri,lintReadonlySql as Ai,runReadonlySql as Ci}from"./packem_shared/MAX_SQL_ROWS-eRignWyO.mjs";import{BIGINT_KEY_DIGITS as _i,bigintSqlKey as Ii,decodeBigintSqlKey as bi,decodeFloat64SqlKey as Li,float64SqlKey as Oi}from"./packem_shared/BIGINT_KEY_DIGITS-DE6yshOt.mjs";import{awaitWsDrain as Pi,subscriptionFrames as yi,subscriptionListDeltas as Mi,trySendFrame as Fi}from"./packem_shared/awaitWsDrain-DMcWBQ7I.mjs";import{mergeChangedKeys as ki,recordChangedKeys as Bi,writeTouchesMemo as Ui}from"./packem_shared/mergeChangedKeys-DPKhen6e.mjs";import{createSystemReader as wi}from"./packem_shared/createSystemReader-BSCxr8Qs.mjs";import{ConflictError as vi}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as Wi,TransactionHeadroomTracker as Xi}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS-D7p7Ys0M.mjs";import{hasTrigger as Vi,runTriggers as zi}from"./packem_shared/hasTrigger-CjlwI4le.mjs";import{isTtlExpired as Yi,nextTtlExpiry as ji,selectExpiredIds as Ji}from"./packem_shared/isTtlExpired-DNxmZA6e.mjs";import{VECTOR_BACKFILL_MAX_PAGES as $i,backfillVectorIndexes as el}from"./packem_shared/VECTOR_BACKFILL_MAX_PAGES-DcQpf83n.mjs";import{c as ol,s as al}from"./packem_shared/where-sql-BjY4rnqb.mjs";import{RELATION_EXISTS_KEY as sl}from"./packem_shared/RELATION_EXISTS_KEY-wxgj6rSL.mjs";import{RELAY_SIGNATURE_HEADER as ll,siblingSecretOf as nl,signSiblingBody as dl,verifySiblingBody as cl}from"./packem_shared/RELAY_SIGNATURE_HEADER-DP0glzE_.mjs";import{REPROJECTION_MIGRATION_PREFIX as pl,reprojectionMigrationId as ul}from"./packem_shared/REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{isInternalTableName as fl}from"./packem_shared/isInternalTableName-BoljO2tP.mjs";import{quoteIdentifier as hl}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as Tl}from"./packem_shared/runShardMigrations-xu993yo2.mjs";import{stableStringify as Al,stableWireKey as Cl}from"@lunora/wire";export{ua as ADMIN_FUNCTIONS,Sa as ADMIN_FUNCTION_PREFIX,d as AGGREGATE_SQL_FUNCTION,Qr as AGG_COUNT,Yr as AGG_KEY,jr as AGG_VALUE,O as AUDIT_LOG_TABLE,_i as BIGINT_KEY_DIGITS,V as CDC_LOG_TABLE,z as CDC_LOG_TABLE_SEQ_INDEX,Q as CDC_META_TABLE,Ae as CLIENT_WATERMARK_TABLE,be as COMMIT_SEQ_FIELD,Le as COMMIT_SEQ_TABLE,Za as CURSOR_PREFIX,Me as CompanionMemo,vi as ConflictError,A as CountRlsUnsupportedError,Br as DATA_MIGRATION_STATE_TABLE,fa as DEFAULT_FANOUT_TOPIC_LIMIT,as as DEFAULT_MAX_RELATION_KEYS,Ls as DEFAULT_MAX_RELAYS,As as DEFAULT_PROMOTION_THRESHOLDS,Wi as DEFAULT_TRANSACTION_LIMITS,Jr as DOC_COLUMN,bo as DurableStreamRunner,xa as FLAGS_FUNCTION_PREFIX,aa as GEO_DEFAULT_PRECISION,Ue as GLOBAL_SHAPE_SNAPSHOT_TABLE,ma as GlobalPollTick,Xe as IDEMPOTENCY_TABLE,Na as MAIL_RETENTION,ka as MAIL_TABLE,Lo as MAX_DURABLE_STREAM_BYTES,Oo as MAX_DURABLE_STREAM_CHUNKS,ha as MAX_PAGE_SIZE,Ti as MAX_SQL_ROWS,va as NotFoundError,F as NotUniqueError,Os as OwnerRelay,pt as QUEUE_TABLE,Tt as RANK_TIEBREAK,yt as REACTOR_STATE_TABLE,jt as RELATED_DEFAULT_LIMIT,Jt as RELATED_DEPTH_DECAY,Zt as RELATED_MAX_DEPTH,$t as RELATED_MAX_LIMIT,sl as RELATION_EXISTS_KEY,Ea as RELATION_FUNCTION_PREFIX,ll as RELAY_SIGNATURE_HEADER,pl as REPROJECTION_MIGRATION_PREFIX,vs as RLS_UNWRAP_SYMBOL,Ot as ReactiveCache,Ds as RelayMember,Ks as RlsRequiredError,qr as SCAN_DEP,ar as SCHEDULE_OUTBOX_TABLE,Hs as SCHEMA_HISTORY_MAX_VERSIONS,Tr as SEARCH_STATE_TABLE,_r as SHAPE_POKE_CURSOR_TABLE,ti as ShapeDiffCache,ui as ShardRunner,Xi as TransactionHeadroomTracker,Gt as UNVOUCHABLE_DEP,$i as VECTOR_BACKFILL_MAX_PAGES,mo as WORKERD_SQLITE_LIMITS,Ce as advanceClientWatermark,Zr as aggUpsertSql,c as aggregateSqlFunction,f as aggregateTableName,Oe as allocateCommitSeq,D as appendAuditEntry,Y as appendCdcChange,ho as appendStreamChunk,j as applyCdcChanges,us as applyInsertDefaults,Ss as applyOnDelete,$a as applySelect,fe as archiveCdcSegment,Ya as armRestore,ts as assertFlatPredicate,N as assertNoExplicitUndefined,Wa as assertPatchAllowed,Ri as assertReadonly,ss as assertShapeShardable,k as assertStorableRowId,B as assertValidClientId,Pi as awaitWsDrain,v as backfillAggregateIndexes,K as backfillRankIndexes,W as backfillSearchIndexes,X as backfillSearchIndexesForTable,el as backfillVectorIndexes,Ii as bigintSqlKey,ta as boundingBoxCenter,sa as boundingBoxGeohashes,Kt as buildIndexRange,ni as buildPokeFrames,Bs as buildReprojectionMigration,et as buildSeekBeforeWhere,rt as buildSeekWhere,Zs as buildSettings,oi as buildShapeDiff,J as bumpCdcEpoch,xe as cdcArchiveRewound,Z as cdcCanVouchFor,$ as cdcForkedError,ee as cdcSeqLeavingRows,re as cdcTouchesTables,oe as cdcTrimmedError,Eo as claimStreamRun,Cs as clampPromotionThresholds,Ba as clearCapturedMail,Fe as clearCompanionSignatures,je as clearMemoryTables,ut as clearQueueMessages,x as coerceAggregateNumber,ae as compactCdcDocs,ol as compileWhereSql,is as composeReadPredicate,er as computeRankPage,ls as containsRelationPredicate,Us as countLegacyRows,ia as coveringGeohashes,ke as createCompanionSync,vr as createDependencyTracker,Ta as createFanoutCounters,Ra as createGlobalPollCounters,$r as createIndexSql,wt as createReadFootprint,Ps as createRelayLink,Ms as createReplicaLink,si as createShapeDiffCache,Aa as createShapeProbeCounters,U as createShardCtxDb,wi as createSystemReader,te as cursorBelowRetainedFloor,Do as decideDurableAttach,bi as decodeBigintSqlKey,ot as decodeCursor,Li as decodeFloat64SqlKey,tr as deferScheduleOutbox,Ge as deleteGlobalShapeSnapshot,we as deleteGlobalShapeSnapshotsForConnection,Ir as deleteShapePokeCursor,br as deleteShapePokeCursorsForConnection,To as deleteStreamRun,Kr as depKey,es as deriveRelationEdges,ms as describeRelationWrites,No as diffExternalSource,di as diffGlobalMembership,fs as distinctValues,sr as dropScheduleOutbox,h as encodeAggregateKey,at as encodeCursor,la as encodeGeohash,Rt as encodePartitionKey,ci as encodeRowsPatch,P as ensureAuditTable,Ua as ensureMailTable,yo as envOptionalPositiveInt,Mo as envPositiveInt,tt as equalityPinnedFields,o as exportShardRows,Ca as facetColumn,xs as fanOutScalarCounts,rs as findRelated,ga as findStorageReferences,Ro as finishStreamRun,Oi as float64SqlKey,E as foldAggregateTally,ir as forgetScheduleOutbox,jo as ftsCompanionDdl,Jo as ftsPurgeDocument,Zo as ftsRowidMapName,$o as ftsUnmappedPage,ea as ftsWriteDocument,Fs as gateReplicaDispatch,eo as geoTableName,ii as globalShapeReadKey,ra as groupUnmappedRows,Ws as guardWriter,Ns as handleReplicaControl,lr as hasScheduleOutboxEntry,Vi as hasTrigger,na as haversineMeters,a as importShardRows,Wt as indexKeysForRow,$s as isDevEnvironment,ro as isFtsAvailable,fl as isInternalTableName,St as isLossyBody,Je as isMemoryTable,Vt as isPushableWhere,ns as isRelationPredicate,Ho as isSoftDeleted,Vo as isSourceDue,Yi as isTtlExpired,_a as isVacuousFilterClause,oo as jsonPath,ao as jsonPathSql,Xt as keysTouchRanges,Bo as liftSourceId,Ai as lintReadonlySql,Mt as listReactorStates,Ia as listTables,qt as markUnvouchableReads,At as matchesRankStaticWhere,m as matchesStaticWhere,qo as materializeExternalRows,vo as materializeExternalRowsIncremental,Ze as memoryTableNames,ki as mergeChangedKeys,C as mergeWhere,se as migrateCdcLog,ie as migrateCdcMeta,ge as migrateClientWatermark,De as migrateCommitSeq,Ao as migrateDurableStreams,qe as migrateGlobalShapeSnapshot,He as migrateIdempotency,Ft as migrateReactorState,nr as migrateScheduleOutbox,Rr as migrateSearchState,Lr as migrateShapePokeCursor,le as minCdcReplayableSeq,ne as minCdcSeq,Or as minShapePokeCursor,gs as nextPromotionState,ji as nextTtlExpiry,p as normalizeCountArgument,G as normalizeIdStructurally,st as normalizeOrderKeys,Uo as normalizeSourceDocument,Go as normalizeSourceValue,it as nullsFirstOf,lt as nullsOrderSuffix,Xa as operatorFields,po as param,dr as parkScheduleOutbox,t as parseExportShardArgs,s as parseImportShardArgs,Ha as patchDependsOnRow,g as planAggregateLookup,da as pointInBoundingBox,cr as probeScheduleOutbox,mi as projectColumns,zo as pullExternalSourceIncrementalTick,Qo as pullExternalSourceTick,to as qualifiedJsonPath,so as qualifiedJsonPathSql,hl as quoteIdentifier,Ct as rankKeyFromDoc,gt as rankPivotConditionSql,_t as rankTableName,Dt as reactiveCacheKey,Nt as reactorNeedsRun,T as readAggregateValue,he as readArchivedCdcChanges,y as readAuditLog,ja as readBookmark,Ga as readCapturedMail,Ee as readCdcArchivedThrough,de as readCdcChangeKeys,ce as readCdcChanges,me as readCdcCursor,pe as readCdcEpoch,_e as readClientWatermark,Pe as readCommitSeq,ei as readDeployInfo,mr as readDueScheduleOutbox,pr as readDueScheduleOutboxEntry,Ko as readExternalSourceBaseline,ve as readGlobalShapeSnapshot,Ve as readIdempotent,Ur as readMigrationStatus,Va as readPatchField,ft as readQueueMessageById,xt as readQueueMessages,kt as readReactorState,ur as readScheduleOutbox,Sr as readScheduleOutboxState,Vs as readSchemaHistory,zs as readSchemaVersion,Ar as readSearchBackfillState,Dr as readShapePokeCursor,Co as readStreamChunks,go as readStreamRun,ba as readTablePage,wa as recordCapturedMail,Bi as recordChangedKeys,La as recordFanoutPass,Oa as recordGlobalPollPass,ht as recordQueueMessages,fr as recordScheduleOutbox,Qs as recordSchemaVersion,Da as recordShapeProbePass,hs as relationHooks,_s as relayCountFor,uo as renderSql,Gs as reprojectableFields,ul as reprojectionMigrationId,ws as reprojectionTables,xr as requeueScheduleOutbox,za as resolvePatch,It as resolveRankPartition,rr as resolveRankSeekTuple,ds as resolveRelationPredicates,Es as resolveWith,io as rowToDocument,Gr as runDataMigration,Hr as runDrizzle,Wo as runExternalSourceTick,Ci as runReadonlySql,Ts as runRowValidators,Tl as runShardMigrations,hi as runSocketPool,Vr as runSql,zi as runTriggers,Ji as selectExpiredIds,i as selectExportTables,_ as selectIndexForAggregate,I as selectIndexForCount,b as selectIndexForGroupBy,Pa as selectMatchingIds,Fr as selectShapeMembers,Nr as selectShapeRows,js as serializeSqlValue,al as serverInList,Is as shapeRoutingKey,nl as siblingSecretOf,dl as signSiblingBody,nt as softDeleteScope,bt as sortColumnName,So as sqliteInList,Al as stableStringify,Cl as stableWireKey,w as stripReservedPatchFields,fi as stubByName,yi as subscriptionFrames,Mi as subscriptionListDeltas,ya as summarizeFanoutTopics,Ma as summarizeSubscriptions,lo as tableColumns,Wr as tableFromDepKey,u as throwingScheduler,dt as tiebreakDirectionFor,ue as trimCdcChanges,ze as trimIdempotent,hr as trimScheduleOutbox,_o as trimStreamRuns,no as tryRowToDocument,Fi as trySendFrame,fo as unionAll,ct as uniqueIndexFields,l as validateImportRow,cl as verifySiblingBody,zt as whereFilter,Qt as whereOfFilter,Te as writeCdcArchivedThrough,Ke as writeGlobalShapeSnapshot,Qe as writeIdempotent,Bt as writeReactorState,Cr as writeSearchBackfillState,Pr as writeShapePokeCursor,yr as writeShapePokeCursors,Ui as writeTouchesMemo};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as S}from"@lunora/errors";import{q as St}from"./MAX_TOKEN_LENGTH-iFEGEcDL-DBPC6ZWl.mjs";import{S as Un,l as qe,s as On}from"./fts-companion-CE3EmIjk.mjs";import{decodeWire as Gn,stableWireKey as Ut}from"@lunora/wire";import{sql as d}from"drizzle-orm";import{throwingScheduler as jn,aggregateSqlFunction as Pe,normalizeCountArgument as Hn}from"./AGGREGATE_SQL_FUNCTION-C_ZipS9R.mjs";import{aggregateTableName as st,encodeAggregateKey as ct,readAggregateValue as at}from"./aggregateTableName-B_CtIQCS.mjs";import{mergeWhere as Q,CountRlsUnsupportedError as dt,selectIndexForGroupBy as Kn,selectIndexForCount as Nn,selectIndexForAggregate as Qn}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{backfillSearchIndexesForTable as Vn,searchIndexCoversTable as Jn}from"./backfillAggregateIndexes-Pk0KLrfk.mjs";import{backfillAggregateIndexes as Oi,backfillRankIndexes as Gi,backfillSearchIndexes as ji}from"./backfillAggregateIndexes-Pk0KLrfk.mjs";import{appendCdcChange as zn,readCdcDocAtOrBefore as Yn}from"./CDC_LOG_TABLE-BFGgqai8.mjs";import{CDC_LOG_TABLE as Ki,applyCdcChanges as Ni,bumpCdcEpoch as Qi,cdcCanVouchFor as Vi,cdcForkedError as Ji,cdcSeqLeavingRows as zi,cdcTouchesTables as Yi,cdcTrimmedError as Xi,compactCdcDocs as Zi,cursorBelowRetainedFloor as es,minCdcReplayableSeq as ts,minCdcSeq as ns,readCdcChangeKeys as os,readCdcChanges as rs,readCdcCursor as is,readCdcEpoch as ss,trimCdcChanges as cs}from"./CDC_LOG_TABLE-BFGgqai8.mjs";import{allocateCommitSeq as Xn,COMMIT_SEQ_FIELD as Zn}from"./COMMIT_SEQ_FIELD-Da1DjGqo.mjs";import{createCompanionSync as eo}from"./createCompanionSync-CEht4hXX.mjs";import{isMemoryTable as Ot}from"./clearMemoryTables-aMRERF0w.mjs";import{computeRankPage as Gt}from"./computeRankPage-BZIpATcs.mjs";import{SCAN_DEP as G}from"./SCAN_DEP-D7qE3iUe.mjs";import{runSql as he,runDrizzle as K}from"./runDrizzle-RC09zZrh.mjs";import{p as to,j as pt,D as ie,r as xe,W as no,k as le,b as Ue,A as lt,a as Oe,m as ue,e as fe,s as oo,t as ro,u as io,i as so,q as jt,h as $n,g as co}from"./do-sql-105TONaE.mjs";import{renderSql as mn,unionAll as Sn,WORKERD_SQLITE_LIMITS as Rn}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{a as ao,u as lo}from"./estimate-bytes-C-C35VXL.mjs";import{coveringGeohashes as uo,boundingBoxGeohashes as fo,haversineMeters as ho,pointInBoundingBox as wo}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{NotFoundError as po}from"./NotFoundError-BhF7FeFr.mjs";import{resolvePatch as go,assertPatchAllowed as yo,operatorFields as Eo,readPatchField as Ht}from"./assertPatchAllowed-CA_H466g.mjs";import{tiebreakDirectionFor as $o,encodeCursor as Qe,nullsOrderSuffix as mo,normalizeOrderKeys as Kt,uniqueIndexFields as So,buildSeekWhere as Ro,decodeCursor as Nt,buildSeekBeforeWhere as vo,softDeleteScope as Ae,applySelect as gt}from"./CURSOR_PREFIX-6offuG6M.mjs";import{rankTableName as Qt,sortColumnName as Vt,resolveRankPartition as _o,encodePartitionKey as To,RANK_TIEBREAK as Ao,rankPivotConditionSql as Io}from"./RANK_TIEBREAK-D3ye2GsL.mjs";import{UNVOUCHABLE_DEP as Jt}from"./UNVOUCHABLE_DEP-Ds9gxVqs.mjs";import{idIndexKey as xo,withUnknownIndexKeys as bo,indexKeysForRow as Co,buildIndexRange as Mo}from"./buildIndexRange-BTChxh3k.mjs";import{r as Ve,j as be,c as Z,t as Ye,i as zt}from"./where-sql-BjY4rnqb.mjs";import{serializeSqlValue as Ce}from"./serializeSqlValue-DeoBMpZ2.mjs";import{quoteIdentifier as Me}from"./quoteIdentifier-CObIFRhb.mjs";import{whereOfFilter as Do,isPushableWhere as ko}from"./isPushableWhere-BeYAOjUb.mjs";import{deriveRelationEdges as Lo,findRelated as Fo}from"./RELATED_DEFAULT_LIMIT-CVqN4JEu.mjs";import{assertFlatPredicate as ut,resolveRelationPredicates as Bo,composeReadPredicate as Wo}from"./DEFAULT_MAX_RELATION_KEYS-DfrMi_eE.mjs";import{describeRelationWrites as qo}from"./describeRelationWrites-omar6-u9.mjs";import{runRowValidators as Ge,transformOnlyDefinition as Po,applyInsertDefaults as yt,resolveWith as Yt,relationHooks as Xt,applyOnDelete as Uo,fanOutScalarCounts as Oo}from"./applyInsertDefaults-CVukTkQ5.mjs";import{guardWriter as Go}from"./RLS_UNWRAP_SYMBOL-H6J96vgK.mjs";import{mayHoldProjectedValue as jo}from"./BIGINT_KEY_DIGITS-DE6yshOt.mjs";import{createSystemReader as Ho}from"./createSystemReader-BSCxr8Qs.mjs";import{ConflictError as se}from"./ConflictError-C8GtJmjS.mjs";import{hasTrigger as Zt,runTriggers as Ko}from"./hasTrigger-CjlwI4le.mjs";import{advanceClientWatermark as ds,migrateClientWatermark as ls,readClientWatermark as us}from"./CLIENT_WATERMARK_TABLE-De7z_OHV.mjs";import{IDEMPOTENCY_TABLE as hs,readIdempotent as ws,trimIdempotent as ps,writeIdempotent as gs}from"./IDEMPOTENCY_TABLE-COrgeP3O.mjs";import{runShardMigrations as Es}from"./runShardMigrations-xu993yo2.mjs";import{selectShapeMembers as ms,selectShapeRows as Ss}from"./selectShapeMembers-Dqx_m7BF.mjs";const No=n=>{const r=atob(n),o=Uint8Array.from(r,s=>s.codePointAt(0)??0);return new TextDecoder().decode(o)},Qo=()=>new S("BAD_REQUEST","invalid cursor"),en=16,tn=8,z=1024,Rt=(n,r)=>r.query(n),Vo=(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 $ of n)(u?$.startsWith(c):$===c)&&(g+=1);if(g===0)return 0;o+=g}return o},Jo=(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)}},zo=(n,r,o)=>{const s={eq:(c,u)=>{if(!n.definition.filterFields?.includes(c))throw new S("INTERNAL",`field "${c}" is not a filter field of search index "${n.indexName}" on table "${r}"`);if(n.filters.length>=tn)throw new S("BAD_REQUEST",`search index "${n.indexName}" on table "${r}": at most ${String(tn)} .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 S("INTERNAL",`search index "${g.indexName}" on table "${r}" indexes "${g.definition.field}", not "${c}"`);const $=Rt(u,o).length;if($>en)throw new S("BAD_REQUEST",`search index "${g.indexName}" on table "${r}": at most ${String(en)} search terms are supported (got ${String($)})`);return g.field=c,g.query=u,g.hasQuery=!0,s}};return s},Yo=n=>{if(n.length>z)throw new S("BAD_REQUEST",`more than ${String(z)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},Xo=n=>Math.min(n.offset+n.numItems+1,z),Zo=n=>btoa(`search:${String(n)}`),er=n=>{let r;try{r=No(n)}catch{return}if(!r.startsWith("search:"))return;const o=Number(r.slice(7));return Number.isInteger(o)&&o>=0?o:void 0},tr=n=>{if(typeof n.endCursor=="string")throw new S("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 S("BAD_REQUEST",`search pagination needs a finite numItems, got ${String(n.numItems)}`);const r=Math.max(0,Math.floor(n.numItems)),o=n.cursor?er(n.cursor):0;if(o===void 0)throw Qo();if(o+r>=z)throw new S("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}},nr=(n,r)=>{const o=r.offset+r.numItems,s=r.numItems>0&&n.length>o;return{continueCursor:s?Zo(o):null,isDone:!s,page:n.slice(r.offset,o)}},or=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 S("BAD_REQUEST",`search returns at most ${String(z)} documents (asked for ${String(r)}) — narrow the query or paginate instead`);return r},vn=500,_n=(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??vn},Tn=(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)`)},rr=32,ir=1024,An=(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?Ve(`${c} ${u}`):be(`${c} WHERE `,r,` ${u}`)},Xe={fieldRef:n=>Ve(pt(n)),rangeTypeGuard:(n,r)=>Ve(to(n,r)),serialize:Ce},sr=n=>n===void 0?"":mo(n==="first"),In=n=>{const r=n.map(o=>`${pt(o.field)} ${o.direction==="desc"?"DESC":"ASC"}${sr(o.nulls)}`);return n.some(o=>o.field==="_id"||o.field==="id")||r.push(`${pt("id")} ${$o(n)==="desc"?"DESC":"ASC"}`),r.join(", ")},cr={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},xn=n=>new Set(n.sqlConditions.filter(r=>r.comparator==="=").map(r=>r.field)),ar=n=>{const r=xn(n);let o=0;for(;o<n.indexFields.length&&r.has(n.indexFields[o]??"");)o+=1;return n.indexFields.slice(o)},dr=(n,r)=>{const o=n.order,s=ar(n),{shape:c}=r;return s.length>0?Kt(s.map(u=>({[u]:o})),c,{pinned:xn(n),uniqueBy:So(r.indexes,c)}):Kt([{_creationTime:o}],c)},lr=(n,r,o,s)=>{const c=n.sqlConditions.map(u=>({[u.field]:{[cr[u.comparator]??"eq"]:u.value}}));if(o&&c.push(Ro(r,Nt(o))),s&&c.push(vo(r,Nt(s))),c.length!==0)return c.length===1?c[0]:{AND:c}},ur=n=>{if(n.want!==void 0)return n.selective?Math.max(n.want,rr):n.want},Et=(n,r,o,s,c,u,g)=>{const $=dr(s,o),y=In($),a=[],{filters:M,want:T}=u;let v=u.cursor??void 0,x=ur(u);if(T===0)return{documents:a,orderKeys:$};for(;;){const W=Z(lr(s,$,v,u.endCursor),Xe,Ye),P=An(r,c&&W?be(W," AND ",c):c??W,y,x),B=he(n,P.text,...P.params).toArray();let U={};g(B.length);for(const j of B)if(U=xe(j),M.every(ee=>ee(U))&&a.push(U)===T)return{documents:a,orderKeys:$};if(x===void 0||B.length<x)return{documents:a,orderKeys:$};v=Qe(U,$),x=Math.max(x,Math.min(x*2,ir))}},fr=(n,r,o,s,c,u,g,$)=>{const y=Math.max(0,Math.floor(c.numItems));if(typeof c.endCursor=="string"){const{documents:W,orderKeys:P}=Et(n,r,o,s,u,{cursor:c.cursor,endCursor:c.endCursor,filters:g.all,selective:g.selective,want:void 0},$),B=W.length>=2?W[Math.floor(W.length/2)-1]:void 0;return{continueCursor:c.endCursor,isDone:!0,page:W,splitCursor:B?Qe(B,P):null}}const{documents:a,orderKeys:M}=Et(n,r,o,s,u,{cursor:c.cursor,filters:g.all,selective:g.selective,want:y+1},$),T=a.length>y,v=T?a.slice(0,y):a,x=v.at(-1);return{continueCursor:T&&x?Qe(x,M):null,isDone:!T,page:v}},Ze=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),hr=Ze(n=>`INSERT INTO ${n} (id, _creationTime, ${we}) VALUES (?, ?, ?)`),nn=Ze(n=>`UPDATE ${n} SET ${we} = ? WHERE id = ? AND ${we} = ?`),wr=Ze(n=>`UPDATE ${n} SET _creationTime = ?, ${we} = ? WHERE id = ? AND ${we} = ?`),pr=Ze(n=>`DELETE FROM ${n} WHERE id = ? AND ${we} = ?`),gr="SELECT changes() AS changed",on=new Map,yr="",Er=n=>{const r=JSON.stringify(n),o=on.get(r);if(o!==void 0)return o;const s=n.map(u=>d`SELECT ${d.raw(`'${u.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${d.identifier(ie)} FROM ${d.identifier(u)} WHERE id = ${yr}`),{sql:c}=mn("sqlite",d`${Sn(s)} LIMIT 1`);return on.set(r,c),c},$r=(n,r)=>r.map(()=>n),mr=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,Sr=n=>{if(!mr.test(n))throw new S("INTERNAL",`invalid clientId ${JSON.stringify(n)}: a client-supplied row id must be a UUID`)},$t=n=>{if(n.includes("\0"))throw new S("BAD_REQUEST",`invalid row id ${JSON.stringify(n)}: a row id cannot hold a NUL character (U+0000)`)},Rr=(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?yt(n,u,s)._id:u._id;typeof g=="string"&&$t(g)}},rn=50,je=Math.floor(Rn.boundParams/3),sn=Rn.boundParams,vr=128,Je=n=>new S("BATCH_LIMIT_EXCEEDED",n,{status:400}),He=(n,r,o)=>{Tn(n,_n(r,o,Je),o,Je)},cn=async(n,r,o,s,c)=>{const u=_n(s,c,Je),{page:g}=await n.findMany(r,Number.isFinite(u)?{limit:u+1,omitContinueCursor:!0,where:o}:{where:o});return g.length>u&&Tn(Math.max(await n.count(r,{where:o}),g.length),u,c,Je),g},_r=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},Tr=n=>Math.max(n,z),bn=(n,r)=>{const o=n.filters.map(s=>d`${fe(s.field)} = ${Ce(s.value)}`);return r&&o.push(r),o},Ar=(n,r,o,s,c)=>{const u=Rt(o.query,St(o.definition.language));if(u.length===0)return[];const g=Un(r,o.indexName),$=`${g}__vocab`,y=u.length-1,a=u.map((P,B)=>{const U=Jo(P,B===y),j=U.exact?d`${d.identifier("term")} = ${U.lower}`:d`${d.identifier("term")} >= ${U.lower} AND ${d.identifier("term")} < ${U.upper}`;return d`SELECT ${d.identifier("doc")}, ${d.raw(String(B))} AS ${d.identifier("__term__")}, COUNT(*) AS ${d.identifier("__n__")} FROM ${d.identifier($)} WHERE ${j} GROUP BY ${d.identifier("doc")}`}),M=u.map((P,B)=>d`SUM(CASE WHEN u.${d.identifier("__term__")} = ${d.raw(String(B))} THEN u.${d.identifier("__n__")} ELSE 0 END)`),T=d`SELECT f.${d.identifier(qe)} AS ${d.identifier(qe)}, ${d.join(M,d` + `)} AS ${d.identifier("__score__")} FROM (${Sn(a)}) u JOIN ${d.identifier(g)} f ON f.rowid = u.${d.identifier("doc")} GROUP BY f.${d.identifier(qe)} HAVING ${d.join(M.map(P=>d`${P} > 0`),d` AND `)}`,v=bn(o,c);let x=d`SELECT m.id, m._creationTime, m.${d.identifier(ie)}, s.${d.identifier("__score__")} AS ${d.identifier("__score__")} FROM (${T}) s JOIN ${d.identifier(r)} m ON m.id = s.${d.identifier(qe)}`;v.length>0&&(x=d`${x} WHERE ${d.join(v,d` AND `)}`),x=d`${x} ORDER BY s.${d.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${d.raw(String(s))}`;const W=[];for(const P of K(n,x)){const B=$n(P);if(B){const U=P.__score__;W.push({document:B,score:typeof U=="number"?U:Number(U??0)})}}return W},Ir=(n,r,o,s,c)=>{const u=St(o.definition.language),g=Rt(o.query,u);if(g.length===0)return[];const $=bn(o,c);let y=d`SELECT id, _creationTime, ${d.identifier(ie)} FROM ${d.identifier(r)}`;$.length>0&&(y=d`${y} WHERE ${d.join($,d` AND `)}`),y=d`${y} ORDER BY _creationTime DESC, id ASC LIMIT ${d.raw(String(Tr(s)))}`;const a=K(n,y).toArray(),M=[];for(const T of a){const v=$n(T);if(!v)continue;const x=Vo(On(v,o.definition),g);x>0&&M.push({creationTime:typeof v._creationTime=="number"?v._creationTime:0,doc:v,id:typeof v._id=="string"?v._id:"",score:x})}return M.sort((T,v)=>v.score-T.score||v.creationTime-T.creationTime||T.id.localeCompare(v.id)),M.slice(0,s).map(T=>({document:T.doc,score:T.score}))},ft=(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 S("BAD_REQUEST",`geo index "${s}" on table "${o}": ${r} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},xr=(n,r)=>{const o=n,s={near:(c,u)=>{if(o.within)throw new S("INTERNAL",`geo index "${o.indexName}" on table "${r}": call .near() or .within(), not both`);if(ft(c,".near() point",r,o.indexName),!Number.isFinite(u)||u<=0)throw new S("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 S("INTERNAL",`geo index "${o.indexName}" on table "${r}": call .near() or .within(), not both`);if(ft(c.sw,".within() sw corner",r,o.indexName),ft(c.ne,".within() ne corner",r,o.indexName),c.sw.lat>c.ne.lat)throw new S("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 S("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},br=(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},Cr=(n,r)=>{const o=br(n,r.definition.field);if(!o)return;const s=typeof n._creationTime=="number"?n._creationTime:0;if(r.near){const c=ho(r.near.point,o);return c<=r.near.radiusMeters?{creationTime:s,distance:c}:void 0}return wo(o,r.within)?{creationTime:s,distance:0}:void 0},Mr=(n,r,o,s)=>{if(!o.near&&!o.within)throw new S("INTERNAL",`geo index "${o.indexName}" on table "${r}": call .near(point, radius) or .within(box)`);const c=o.near?uo(o.near.point,o.near.radiusMeters):fo(o.within),u=co(r,o.indexName),g=c.map(T=>d`(g.${d.identifier("__geohash__")} >= ${T} AND g.${d.identifier("__geohash__")} < ${`${T}{`})`),$=[d`(${d.join(g,d` OR `)})`];s&&$.push(s);const y=d`SELECT m.id, m._creationTime, m.${d.identifier(ie)} FROM ${d.identifier(u)} g JOIN ${d.identifier(r)} m ON m.id = g.${d.identifier("__id__")} WHERE ${d.join($,d` AND `)}`,a=K(n,y).toArray(),M=[];for(const T of a){const v=xe(T),x=v?Cr(v,o):void 0;v&&x&&M.push({creationTime:x.creationTime,distance:x.distance,doc:v})}return M.sort((T,v)=>T.distance-v.distance||v.creationTime-T.creationTime),M},Cn=(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},Dr=(n,r,o,s,c,u=()=>{})=>{const g=o.within!==void 0,$=Mr(n,r,o,c).map(y=>({distanceMeters:g?null:y.distance,document:y.doc}));return u($.length),typeof s=="number"?$.slice(0,Math.max(0,Math.floor(s))):$},an=(n,r,o,s,c,u,g=()=>{})=>{const{geo:$}=o;if(!$)throw new S("INTERNAL","runGeoTerminalScored called without a staged geo query");const y=c.length>0,a=Dr(n,r,$,y?void 0:u,s,g);return y?Cn(a,c,u,M=>M.document):a},dn=(n,r,o)=>{const s=n.shape[r];if(s!==void 0&&jo(s))throw new S("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)`)},kr=n=>{let r=0;const o=[],s={...Xe,relationExists:c=>{const{childWhere:u,negated:g,parentTable:$,relation:y}=c,a=`__rel_${String(r)}`,M=o.at(-1)??$;r+=1,n(y.table,G);const T=y.kind==="one"?y.field:y.references,v=y.kind==="one"?y.references:y.field,x=Ve(`${jt(a,v)} = ${jt(M,T)}`);o.push(a);const W=Z(u,s,Ye);o.pop();const P=W===void 0?x:be(x," AND ",W),B=be("EXISTS (SELECT 1 FROM ",zt(y.table)," AS ",zt(a)," WHERE ",P,")");return g?be("NOT ",B):B}};return s};class Lr extends S{constructor(r="unique() found more than one matching document"){super("NOT_UNIQUE",r,{name:"NotUniqueError"})}}const Fr=/\s/u,Br=String.fromCodePoint(0),ln=(n,r,o)=>{if(!n.tables[r])throw new S("INTERNAL",`unknown table: ${r}`);return typeof o!="string"||o.length===0||Fr.test(o)||o.includes(Br)?null:o},Mn=(n,r,o,s=()=>{},c=()=>{},u=()=>{},g)=>{const $=r.tables[o];if(!$)throw new S("INTERNAL",`unknown table: ${o}`);const y=Ae($.softDeleteMode,void 0),a=g??{indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[],verifyFilters:[]},M=()=>{const R=Q(y,a.pushedWhere);return R?Z(R,ue):void 0},T=()=>{const R=Q(y,a.pushedWhere);return R?Z(R,Xe,Ye):void 0},v=()=>[...a.inMemoryFilters,...a.verifyFilters];let x=0;const W=R=>{const{search:C}=a;if(!C)throw new S("INTERNAL","runSearchFetch called without a staged search");Vn(io(n),o,$);const L=a.inMemoryFilters.length>0,F=or(L?void 0:R),k=so(n);if(k&&!Jn(n,o,C.definition))throw new S("SEARCH_INDEX_BUILDING",`search index "${C.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=M(),te=k?Ar(n,o,C,F,pe):Ir(n,o,C,F,pe);!L&&R===void 0&&Yo(te);const ge=v();return x=te.length,ge.length>0?Cn(te,ge,R,J=>J.document):te},P=R=>W(R).map(C=>C.document),B=R=>{const C=tr(R);return nr(P(Xo(C)),C)},U=()=>{if(a.search||a.geo||a.indexName===void 0){c(void 0);return}c(Mo(o,a.indexName,a.indexFields,a.sqlConditions,Ce))},j=R=>{U();let C=0;const L=(()=>{if(a.search){const F=P(R);return C=x,F}return a.geo?an(n,o,a,M(),v(),R,F=>{C=F}).map(F=>F.document):Et(n,o,$,a,T(),{filters:v(),selective:a.inMemoryFilters.length>0,want:R===void 0?void 0:Math.max(0,Math.floor(R))},F=>{C+=F}).documents})();return u(Math.max(C,L.length)),L},ee=()=>{if(!a.search&&!a.geo)throw new S("INTERNAL",`ctx.db.query("${o}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);U();let R=0;const C=(()=>{if(a.search){const L=W(void 0);return R=x,L}return an(n,o,a,M(),v(),void 0,L=>{R=L})})();return u(Math.max(R,C.length)),C},N={async*[Symbol.asyncIterator](){const R=Mn(n,r,o,s,c,u,{...a,indexFields:[...a.indexFields],inMemoryFilters:[...a.inMemoryFilters],sqlConditions:[...a.sqlConditions],verifyFilters:[...a.verifyFilters]});if(a.search){yield*await R.collect();return}let C;for(;;){const L=await R.paginate({cursor:C??null,numItems:vr});if(yield*L.page,L.isDone||L.continueCursor===null)return;C=L.continueCursor}},async collect(){return j(void 0)},async collectWithScores(){return ee()},filter(R){const C=Do(R);return C!==void 0&&ko(C,$.shape)?(a.pushedWhere=Q(a.pushedWhere,C),a.verifyFilters.push(R)):a.inMemoryFilters.push(R),N},async first(){return j(1)[0]??null},order(R){return a.order=R==="desc"?"desc":"asc",N},async paginate(R){let C=0;if(U(),a.search){const F=B(R);return u(F.page.length),F}if(a.geo)throw new S("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const L=fr(n,o,$,a,R,T(),{all:v(),selective:a.inMemoryFilters.length>0},F=>{C+=F});return u(Math.max(C,L.page.length)),L},async take(R){return j(R)},async unique(){const R=j(2);if(R.length>1)throw new Lr(`unique() on table "${o}" matched ${String(R.length)} documents; expected at most one`);return R[0]??null},withGeoIndex(R,C){const L=($.geoIndexes??[]).find(k=>k.name===R);if(!L)throw new S("INTERNAL",`unknown geo index "${R}" on table "${o}"`);s(o,R,"geo");const F={definition:L,indexName:R};if(a.geo=F,C(xr(F,o)),!F.near&&!F.within)throw new S("INTERNAL",`geo index "${R}" on table "${o}" requires a .near(point, radius) or .within(box) call`);return N},withIndex(R,C){const L=$.indexes.find(F=>F.name===R);if(!L)throw new S("INTERNAL",`unknown index "${R}" on table "${o}"`);return s(o,R,"index"),a.indexName=R,a.indexFields=L.fields,C&&C(_r(a)),N},withSearchIndex(R,C){const L=($.searchIndexes??[]).find(k=>k.name===R);if(!L)throw new S("INTERNAL",`unknown search index "${R}" on table "${o}"`);s(o,R,"search");const F={definition:L,field:L.field,filters:[],hasQuery:!1,indexName:R,query:""};if(a.search=F,C(zo(F,o,St(L.language))),!F.hasQuery)throw new S("INTERNAL",`search index "${R}" on table "${o}" requires a .search(field, query) call`);return N}};return N},ht=(n,r,o,s)=>{const c=o;for(const[u,g]of ro(n)){if(g.serverDefault){u in r&&(c[u]=g.serverDefault({auth:s}));continue}g.onUpdateFn&&!(u in r)&&(c[u]=g.onUpdateFn())}},un=5,fn=(n,r)=>{for(const o of Object.keys(r))if(r[o]===void 0)throw new S("INTERNAL",`Cannot ${n} field '${o}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},hn=["_commitSeq","_creationTime","_id"],Ke=n=>hn.some(r=>r in n)?Object.fromEntries(Object.entries(n).filter(([r])=>!hn.includes(r))):n,Wr=/unique constraint failed/i,qr=n=>n instanceof Error&&Wr.test(n.message),Pr=/string or blob too big/iu,Ur=(n,r)=>{if(!(!(n instanceof Error)||!Pr.test(n.message)))throw new S("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 qr(c)?new se(`unique constraint violation on "${r}"`,"unique"):(Ur(c,r),c)}},Ne=(n,r,o,s)=>{if(mt(n,r,o,s),he(n,gr).one().changed===0)throw new se(`optimistic concurrency conflict on "${r}" — the row changed during this mutation; refetch and retry`,"occ")},wn=(n,r,o,s,c,u,g)=>{const $=[];for(let T=0;T<o.length+1;T+=1){const v=o[T],x=s[T],W=x?.direction==="desc"?"desc":"asc",P=v===void 0||x===void 0?d`${d.identifier(Ao)} < ${g}`:Io(v,u[T],W,!1);if(P===void 0)continue;const B=[];for(let j=0;j<T;j+=1)B.push(d`${d.identifier(o[j])} IS ${u[j]}`);B.push(P);const[U]=B;$.push(B.length===1&&U!==void 0?U:d`(${d.join(B,d` AND `)})`)}const y=$.length>0?d.join($,d` OR `):d`1 = 0`,a=K(n,d`SELECT COUNT(*) AS c FROM ${d.identifier(r)} WHERE ${d.identifier("__partition__")} = ${c} AND (${y})`).one(),M=K(n,d`SELECT COUNT(*) AS c FROM ${d.identifier(r)} WHERE ${d.identifier("__partition__")} = ${c}`).one();return{before:a.c,total:M.c}},Or=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:$,op:y}of r.get(g)??[]){if($===s||Zt(n,$,y))return!0;c.has($)||(c.add($),u.push($))}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))},Gr=n=>{const r=new Map;for(const[o,s]of Object.entries(n.tables))s.softDeleteMode&&r.set(o,s.softDeleteMode.field);return r},wt=new WeakMap,jr=(n,r)=>{let o=wt.get(r.tables);if(!wt.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"),wt.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},Hr=(n,r,o)=>{for(const s of n){const c=s,u=c?.[ie];if(typeof u=="string"){const g=c?.id,$=lo(u);typeof g!="string"?r.recordReadBytes($):o===void 0?r.recordDocumentRead(`${g}\0${String($)}`,$):r.recordDocumentRead(`${o}\0${g}`,$)}}},Kr=(n,r,o)=>{if(r===void 0)return n;const s=(c,...u)=>{const g=n.exec(c,...u),$=g.one.bind(g),y=g[Symbol.iterator].bind(g),a=o===void 0?void 0:jr(c,o);let M=!1;const T=v=>{Hr(v,r,a)};return g.toArray=()=>{const v=[];for(const x of{[Symbol.iterator]:y})T([x]),v.push(x);return v},g.one=()=>{M=!0;try{const v=$();return T([v]),v}finally{M=!1}},g[Symbol.iterator]=function*(){for(const x of{[Symbol.iterator]:y})M||T([x]),yield x},g};return new Proxy(n,{get:(c,u)=>u==="exec"?s:u===no?c:Reflect.get(c,u,c)})},Nr=new Map([["findFirst","rows"],["findFirstOrThrow","rows"],["findMany","page"],["get","rows"],["lookupById","lookup"],["rankPage","page"]]),Qr=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=ao(n);if(s===void 0)return;const c=n._id;typeof c=="string"?o.recordDocumentRead(`global\0${r}\0${c}`,s):o.recordReadBytes(s)},ze=(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)}},Dn=(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=Qr.get(c);return(...$)=>{const y=Reflect.apply(u,s,$);return g!==void 0?Promise.resolve(y).then(a=>(ze(a,g,r,o),a)):typeof y=="object"&&y!==null&&!(y instanceof Promise)?Dn(y,r,o):y}}}),Vr=new Set(["findFirst","findFirstOrThrow","findMany"]),Jr=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=>gt(g,o,c);return{args:[n[0],s,...n.slice(2)],project:(g,$)=>typeof g!="object"||g===null?g:$==="page"?{...g,page:u(g.page)}:u([g])[0]}},pn=256,gn=4096,zr=1024*1024,Yr=async(n,r,o,s)=>{const c=r[1]??{},u=[];let{cursor:g}=c,$=pn,y=0;for(;;){const a=await n([r[0],{...c,cursor:g,limit:$},...r.slice(2)]);if(Array.isArray(a))return ze(a,"rows",o,s),[...u,...a];const M=s.headroom().readBytes;if(ze(a,"page",o,s),u.push(...a.page),a.isDone||typeof a.continueCursor!="string")return{continueCursor:null,isDone:!0,page:u};g=a.continueCursor,y+=s.headroom().readBytes-M,$=y>0?Math.min(gn,Math.max(pn,Math.floor(zr*u.length/y))):gn}},Xr=(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)=>Dn(Reflect.apply(c,o,g),String(g[0]),r);const u=Nr.get(s);return u===void 0?c:async(...g)=>{const $=Vr.has(s)?Jr(g):void 0,y=$?.args??g,a=String(g[0]);if(s==="findMany"&&typeof y[1]?.limit!="number"){const v=await Yr(x=>Reflect.apply(c,o,x),y,a,r);return $===void 0?v:$.project(v,u)}const T=await Reflect.apply(c,o,y);return ze(T,u,a,r),$===void 0?T:$.project(T,u)}}}),yn=new WeakMap,En=new WeakMap,Zr=n=>{const{baselineSeq:r,onStalePatchDropped:o}=n,{headroom:s}=n,c=yn.get(n)??{value:void 0},u=En.get(n)??{value:0};let g;const $=()=>{if(g===void 0){const e={...n,enforceRls:!1,headroom:void 0};yn.set(e,c),En.set(e,u),g=Zr(e)}return g},y=Kr(n.sql,s,n.schema),{schema:a}=n,M=n.broadcast??(()=>{}),T=(e,t)=>{if(!Object.hasOwn(a.tables,e))throw new S("BAD_REQUEST",`${t}: "${e}" is not a table in this schema`)},v=Lo(a),x=new Map;for(const e of v){const t=i=>(a.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,d`SELECT 1 FROM ${d.identifier(l.targetTable)} WHERE id = ${w} LIMIT 1`).toArray().length===0)throw new S("VALIDATION_ERROR",`${l.name} references ${l.targetTable} row "${w}", which does not exist`)}},P=qo(a,n.inTransaction),B=Or(a),U=Gr(a),j=()=>n.inTransaction?.()===!0,ee=e=>a.tables[e]?.commitOrderedMode!==!0?{}:((c.value===void 0||!j())&&(c.value=Xn(y)),{[Zn]:c.value}),N=(e,...t)=>{const i=a.tables[e]?.indexes??[],l=[];let w;for(const p of t)p&&(typeof p._id=="string"&&p._id!==w&&(w=p._id,l.push(xo(w))),l.push(...bo(i,Co(i,p,Ce))));return l.length>0?l:void 0},R=n.onRead??(()=>{}),C=e=>{Ot(a.tables[e])&&R(Jt,Jt)},L=n.onReadRange??(e=>{R(e.table,G)}),F=e=>{C(e.table),L(e)},k=(e,t,i)=>{t!==void 0&&t!==G&&s?.recordRead(1),C(e),R(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,$e=n.clock??(()=>Date.now()),vt=n.idGenerator??(()=>crypto.randomUUID()),_t=n.scheduler??jn,me=Xr(n.globalDb,s),ce=n.auth??{identity:null,userId:null},Tt=n.cdc??!1,et=_t,kn=Ho({scheduler:typeof et.list=="function"&&typeof et.get=="function"?et:void 0,storage:n.storage}),Se=(e,t,i,l)=>{Tt&&!Ot(a.tables[e])&&zn(y,$e(),e,t,i,l)},At=(e,t,i,l)=>{const w=a.tables[e];if(w?.dropStalePatchesMode!==!0||!Tt)return!1;const p=r?.();if(p===void 0)return!1;const f=Yn(y,e,t,p);if(f===void 0)return!1;const h=Eo(w,i);return Object.keys(Ke(i)).some(E=>!h.has(E)&&Ut(Ht(f,E))!==Ut(Ht(l,E)))},ae=e=>a.tables[e]?.shardMode?.kind==="global",It=(e,t)=>{if(ae(e)){if(!me)throw new S("INTERNAL",`cross-backend ${t} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return me}return O},tt=e=>It(e,"cascade"),H=(e,t)=>{if(ae(e)){if(!me)throw new S("INTERNAL",`${t} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return me}},xt=async(e,t,i,l,w)=>{w&&J(i);const p=await e.insert(t,i,l);return M({key:p,op:"insert",row:{...i,_id:p},table:t}),p},nt=(e,t)=>It(e,"relation load").findMany(e,t),bt=(e,t)=>(ae(e)&&k(e,G),nt(e,t)),Ln=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:a,tableName:t}),kt=async(e,t,i,l)=>{const w=H(e,"relation grouped count");if(w)return k(e,G),Oo((m,q)=>w.count(m,q),e,t,i,l);const p=a.tables[e];if(!p)throw new S("INTERNAL",`unknown table: ${e}`);k(e,G);const f=Ae(p.softDeleteMode,void 0),h={[t]:{in:i}},E=Q(Q(h,l),f),_=await De(E,e,void 0),b=Z(_,ue),A=fe(t);let I=d`SELECT ${A} AS __fk__, COUNT(*) AS count FROM ${d.identifier(e)}`;b&&(I=d`${I} WHERE ${b}`),I=d`${I} GROUP BY ${A}`;const D=K(y,I).toArray();return new Map(D.map(m=>[m.__fk__,m.count]))},Lt=new Set;for(const[e,t]of Object.entries(a.tables))for(const i of Object.values(t.triggerMap??{}))Lt.add(`${e} ${i.timing} ${i.op}`);const ne=(e,t,i)=>Lt.has(`${e} ${t} ${i}`),oe=async(e,t,i)=>{if(u.value+=1,u.value>rn)throw u.value-=1,new se(`trigger recursion exceeded ${String(rn)} levels on "${i.table}" — check for a self-triggering write`,"trigger");try{await Ko({ctx:qn,event:i,op:t,schema:a,tableName:i.table,timing:e})}finally{u.value-=1}},{ensureBackfilledForTable:Re,ensureBackfilledIndex:ot,ensureRankBackfilled:rt,ensureRankBackfilledForTable:ve,syncAggregates:ke,syncCompanionsForInsert:Ft,syncGeo:Le,syncRanks:_e,syncSearch:Fe}=eo({broadcast:M,indexKeysFor:(e,t)=>N(e,t),invalidateCache:(e,t,i)=>Ee?.invalidate(e,t,N(e,i)),recordCdc:Se,schema:a,sql:y,verified:n.companionMemo?.verified}),Bt=(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})},Wt=e=>Object.entries(a.tables).filter(([,t])=>t.shardMode?.kind!=="global").map(([t])=>t).filter(t=>e===void 0||t===e),Te=e=>e===void 0||ae(e)?me:void 0,it=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=Wt(t);for(let l=0;l<i.length;l+=sn){const w=i.slice(l,l+sn),[p]=he(y,Er(w),...$r(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}}},qt={assertRankPartitionLocal:Bt,ensureRankBackfilled:rt,onRead:k,rowToDocument:xe,schema:a,sql:y},Fn=(e,t,i)=>{const l=Z(i,ue);return l===void 0||K(y,d`SELECT 1 FROM ${d.identifier(e)} WHERE ${d.identifier("id")} = ${t} AND ${l}`).toArray().length>0},Bn=(e,t,i,l)=>At(e,t,i,l)?(o?.({fields:Object.keys(Ke(i)),id:t,table:e}),!0):!1,Wn=async(e,t,i,l,w)=>{const p=re(t,e);if(!p)return{applied:!1,doc:null};if(k(e,t),!Fn(e,t,i.where)||Bn(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}},Pt=async(e,t,i,l)=>{const{fetchLimit:w,limit:p,orderKeys:f,predicate:h}=await Wo(t,i,{canPushExists:Mt?Ln:void 0,existsPushMode:Ct==="always"?"always":"auto",fetcher:bt,maxRelationKeys:Dt,schema:a,tableName:e}),E=Mt?kr(l):Xe,_=Z(h,E,Ye),b=An(e,_,In(f),w);return{limit:p,orderKeys:f,statement:b}},O={system:kn,async aggregate(e,t){const i=H(e,"aggregate");if(i)return k(e,G),i.aggregate(e,t);const l=a.tables[e];if(!l)throw new S("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 S("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 m=Qn(l.aggregateIndexes,t.op,t.field,t.where);if(m){ot(e,m.index);const q=ct(m.index.by??[],m.key),Y=st(e,m.index.name),X=K(y,d`SELECT ${Ue} AS value, ${lt} AS count FROM ${d.identifier(Y)} WHERE ${Oe} = ${q}`).toArray()[0];return at(t.op,X)}}dn(l,t.field,`aggregate(${e}, { op: "${t.op}", field: "${t.field}" })`);const E=Z(f,ue),_=Pe(t.op),b=fe(t.field);let A=d`SELECT ${d.raw(_)}(${b}) AS value FROM ${d.identifier(e)}`;E&&(A=d`${A} WHERE ${E}`);const D=K(y,A).toArray()[0]?.value;return D??null},asId(e,t){const i=ln(a,e,t);if(i===null)throw new S("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=a.tables[e];if(!l)throw new S("INTERNAL",`unknown table: ${e}`);const w=Hn(t);if(w.restrictsCounts)throw new dt(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 I=Nn(l.aggregateIndexes,w.where);if(I){ot(e,I.index);const D=ct(I.index.by??[],I.key),m=st(e,I.index.name),q=K(y,d`SELECT ${Ue} AS value FROM ${d.identifier(m)} WHERE ${Oe} = ${D}`).toArray();return q[0]===void 0?0:q[0].value??0}}const _=Z(h,ue);let b=d`SELECT COUNT(*) AS count FROM ${d.identifier(e)}`;return _&&(b=d`${b} WHERE ${_}`),K(y,b).one().count},async delete(e,t,i){T(e,"ctx.db.delete(table, id)");const l=re(t,e);if(!l){const I=Te(e);I&&await it(I,e,[t],i);return}const{docJson:w,row:p,tableName:f}=l,h=a.tables[f],E=i?.hard===!0,_=!E&&h?.softDeleteMode?h:void 0,b=_?.softDeleteMode?.field;if(b&&p[b]!==null&&p[b]!==void 0)return;if(ne(f,"before","delete")&&await oe("before","delete",{id:t,op:"delete",previous:p,table:f}),i?.skipOnDelete!==!0&&await Uo({deletedId:t,deletedReference:I=>p[I],findHolders:async(I,D,m,q)=>(await tt(I).findMany(I,{...q,includeDeleted:E,where:{[D]:m}})).page,onCascade:(I,D)=>tt(I).delete(I,D,i),onRestrict:I=>{throw new se(I,"restrict")},onSetNull:(I,D,m)=>tt(I).patch(I,D,{[m]:null}),schema:a,tableName:f}),Re(f),ve(f),_&&b){const I={[b]:$e()},D={...p,...ee(f),...I,_id:t};ht(_,I,D,ce),Ne(y,f,nn(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 m=N(f,p,D);Ee?.invalidate(f,t,m),Se(f,t,"update",D),M({indexKeys:m,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,pr(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 A=N(f,p);Ee?.invalidate(f,t,A),Se(f,t,"delete"),M({indexKeys:A,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(!a.tables[e])throw new S("INTERNAL",`unknown table: ${e}`);if(s!==void 0)return $().deleteAll(e,t);const i=Math.max(1,t?.chunkSize??vn),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):it(w,e,[E],l)),p+=1;if(h.length<i)break}return{deleted:p}},async deleteMany(e,t,i){T(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 cn(l??O,e,t,i?.limit,"deleteWhere")).map(f=>String(f._id));if(l)return it(l,e,p,void 0,{options:i});if(O.deleteMany===void 0)throw new S("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 po(`findFirstOrThrow: no "${e}" document matched`);return i},async findMany(e,t={}){const i=H(e,"findMany");if(i)return k(e,G),i.findMany(e,t);const l=a.tables[e];if(!l)throw new S("INTERNAL",`unknown table: ${e}`);const w=!t.where&&!t.baseWhere;w?k(e,G):k(e);const{limit:p,orderKeys:f,statement:h}=await Pt(e,l,t,k),E=he(y,h.text,...h.params).toArray();w&&s?.recordRead(E.length);const _=[];for(const D of E){const m=xe(D);m&&(_.push(m),!w&&typeof m._id=="string"&&k(e,m._id))}if(p===void 0)return t.with&&await Yt({groupedCounter:kt,fetcher:nt,parents:_,...Xt(t),schema:a,tableName:e,with:t.with}),{continueCursor:null,isDone:!0,page:gt(_,t.select,t.with)};const b=_.length>p,A=b?_.slice(0,p):_,I=A.at(-1);return t.with&&await Yt({fetcher:nt,groupedCounter:kt,parents:A,...Xt(t),schema:a,tableName:e,with:t.with}),{continueCursor:b&&I&&t.omitContinueCursor!==!0?Qe(I,f):null,isDone:!b,page:gt(A,t.select,t.with)}},async explain(e,t={}){const i=H(e,"explain");if(i)return i.explain(e,t);const l=a.tables[e];if(!l)throw new S("INTERNAL",`unknown table: ${e}`);const{statement:w}=await Pt(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){T(e,"ctx.db.get(table, id)");const i=re(t,e);if(!i){const l=Te(e);return l?l.get(e,t):(C(e),R(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 Wt(t))C(l),R(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=a.tables[e];if(!l)throw new S("INTERNAL",`unknown table: ${e}`);k(e,G);const w=t.agg??{op:"count"};if(Pe(w.op),w.op!=="count"&&!w.field)throw new S("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 m=Kn(l.aggregateIndexes,w.op,w.field,t.by,t.where),q=m===void 0?0:Object.keys(m.partial).length,Y=m?.index.by?.length??0;if(m&&(q===0||q===Y)){ot(e,m.index);const X=st(e,m.index.name),V=Object.keys(m.partial),de=[];if(V.length===(m.index.by??[]).length&&V.length>0){const Be=ct(m.index.by??[],m.partial),We=K(y,d`SELECT ${Ue} AS value, ${lt} AS count FROM ${d.identifier(X)} WHERE ${Oe} = ${Be}`).toArray();return We.length>0&&de.push({key:{...m.partial},value:at(w.op,We[0])}),de}const Pn=K(y,d`SELECT ${Oe} AS key, ${Ue} AS value, ${lt} AS count FROM ${d.identifier(X)}`).toArray();for(const Be of Pn){const We=Gn(JSON.parse(Be.key));de.push({key:We,value:at(w.op,Be)})}return de}}for(const m of[...t.by,w.field]){if(m===void 0)continue;const q=m===w.field?`groupBy(${e}, { agg: { op: "${w.op}", field: "${m}" } })`:`groupBy(${e}, { by: [..."${m}"] })`;dn(l,m,q)}const _=Z(h,ue),b=t.by.map(m=>d`${fe(m)} AS ${d.identifier(m)}`);if(w.op==="count")b.push(d`COUNT(*) AS value`);else{const{field:m}=w;if(m===void 0)throw new S("INTERNAL",`groupBy(${e}, { agg: { op: "${w.op}" } }): "field" is required for non-count reducers`);b.push(d`${d.raw(Pe(w.op))}(${fe(m)}) AS value`)}let A=d`SELECT ${d.join(b,d`, `)} FROM ${d.identifier(e)}`;_&&(A=d`${A} WHERE ${_}`),A=d`${A} GROUP BY ${d.join(t.by.map(m=>fe(m)),d`, `)}`;const I=K(y,A).toArray(),D=[];for(const m of I){const q={};for(const X of t.by)q[X]=oo(l.shape[X],m[X]??null);const{value:Y}=m;D.push({key:q,value:Y==null?null:Number(Y)})}return D},async insert(e,t,i){const l=H(e,"insert");if(l)return xt(l,e,t,i,!0);const w=a.tables[e];if(!w)throw new S("INTERNAL",`unknown table: ${e}`);const p=i?.allowExplicitId===!0,f=Ge(w,yt(w,t,ce),{supplied:t,trusted:p});let h;i?.clientId!==void 0?(Sr(i.clientId),h=i.clientId):i?.allowExplicitId&&typeof f._id=="string"?($t(f._id),h=f._id):h=vt();const E=i?.allowExplicitId&&typeof f._creationTime=="number"?f._creationTime:$e(),_={...f,...ee(e),_creationTime:E,_id:h};return ne(e,"before","insert")&&await oe("before","insert",{doc:{..._},id:h,op:"insert",table:e}),p||W(e,_),Re(e),ve(e),mt(y,e,hr(e),[h,E,le(_)]),Ft(e,h,_),ne(e,"after","insert")&&await oe("after","insert",{doc:_,id:h,op:"insert",table:e}),await ye({doc:_,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=[];Rr(a.tables[e],t,i?.allowExplicitId,ce);for(const _ of t)J(_);for(const _ of t){const b=await l.insert(e,_,{allowExplicitId:i?.allowExplicitId});M({key:b,op:"insert",row:{..._,_id:b},table:e}),E.push(b)}return E}const w=a.tables[e];if(!w)throw new S("INTERNAL",`unknown table: ${e}`);Re(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,_)=>{const b=yt(w,E,ce),A=f===void 0?b:Ge(f,b,{supplied:E}),I=i?.allowExplicitId===!0&&typeof A._id=="string"?A._id:void 0;I!==void 0&&$t(I);const D=I??vt(),m=i?.allowExplicitId===!0&&typeof A._creationTime=="number"?A._creationTime:$e(),q={...A,...p[Math.floor(_/je)],_creationTime:m,_id:D};return{creationTime:m,document:q,id:D}});for(const E of h)J(E.document);for(let E=0;E<h.length;E+=je){const _=d.join(h.slice(E,E+je).map(A=>d`(${A.id}, ${A.creationTime}, ${le(A.document)})`),d`, `),b=mn("sqlite",d`INSERT INTO ${d.identifier(e)} (id, _creationTime, ${d.identifier(ie)}) VALUES ${_}`);mt(y,e,b.sql,b.params)}for(const{document:E,id:_}of h)Ft(e,_,E),await ge({doc:E,id:_,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?xt(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 ln(a,e,t)},async patch(e,t,i,l){T(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 S("NOT_FOUND",`document not found: ${t}`)}const{docJson:p,row:f,tableName:h}=w,E=a.tables[h];if(!E)throw new S("INTERNAL",`unknown table: ${h}`);if(k(h,t),fn("patch",i),At(h,t,i,f)){o?.({fields:Object.keys(Ke(i)),id:t,table:h});return}const _=go(E,i,f),b={...f,...Ke(_),...ee(h),_id:t};ht(E,_,b,ce);const A=Ge(E,b,{only:new Set(Object.keys(_)),previous:()=>f,tolerateStoredNull:!0});yo(l,f,A),ne(h,"before","update")&&await oe("before","update",{doc:{...A},id:t,op:"update",previous:f,table:h}),W(h,A,f),Re(h),ve(h),Ne(y,h,nn(h),[le(A),t,p]),Fe(h,t,A,f),Le(h,t,A),ke(h,f,A),_e(h,t,f,A);const I=N(h,f,A);Ee?.invalidate(h,t,I),Se(h,t,"update",A),M({indexKeys:I,key:t,op:"update",row:A,table:h}),ne(h,"after","update")&&await oe("after","update",{doc:A,id:t,op:"update",previous:f,table:h}),await ye({doc:A,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 S("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(!a.tables[e])throw new S("INTERNAL",`unknown table: ${e}`);for(let w=1;w<=un;w+=1){const p=await Wn(e,t,i,w<un,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){T(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 cn(l,e,t.where,i?.limit,"patchWhere")).map(f=>({id:String(f._id),patch:t.patch}));if(O.patchMany===void 0)throw new S("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 Fo(O,v,e,t)},relationEdges:v,deleteRereadTables:B,inTransaction:j,softDeleteFields:U,relationWrites:P,query(e){const t=H(e,"query");return t?(k(e,G),t.query(e)):Mn(y,a,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=a.tables[e];if(!w)throw new S("INTERNAL",`unknown table: ${e}`);const p=w.rankIndexes?.find(V=>V.name===t);if(!p)throw new S("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(Bt(e,w,p),i.restrictsCounts)throw new dt(e);k(e,G),rt(e,p);const f=typeof i.row=="string"?i.row:i.row._id;if(!f)return null;const h=Qt(e,p.name),E=p.sortBy.map((V,de)=>Vt(de)),_=E.map(V=>Me(V)).join(", "),b=K(y,d`SELECT ${d.identifier("__partition__")}, ${d.raw(_)} FROM ${d.identifier(h)} WHERE ${d.identifier("__id__")} = ${f}`).toArray(),[A]=b;if(A===void 0)return null;let I=A.__partition__;const D=Q(i.baseWhere,i.where);ut(D,a,e,"rank");const m=_o(p,D);if(m){const V=To(p.partitionBy??[],m);if(V!==I)return null;I=V}const q=E.map(V=>A[V]),{before:Y,total:X}=wn(y,h,E,p.sortBy,I,q,f);return{position:Y+1,total:X}},async rankBefore(e,t,i){if(ae(e))throw new S("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const l=a.tables[e];if(!l)throw new S("INTERNAL",`unknown table: ${e}`);const w=l.rankIndexes?.find(E=>E.name===t);if(!w)throw new S("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(i.restrictsCounts)throw new dt(e);k(e,G),rt(e,w);const p=Qt(e,w.name),f=w.sortBy.map((E,_)=>Vt(_)),h=w.sortBy.map((E,_)=>Ce(i.sortValues[_]??null));return wn(y,p,f,w.sortBy,i.partitionKey,h,i.rowId)},async rankPage(e,t,i={}){ut(Q(i.baseWhere,i.where),a,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}=Gt(qt,e,t,i);return{continueCursor:w,isDone:!p,page:f.map(h=>h.doc)}},async rankPageRows(e,t,i={}){ut(Q(i.baseWhere,i.where),a,e,"rankPage"),te(e,t,"rank");const{directions:l,hasMore:w,rows:p}=Gt(qt,e,t,i);return{directions:l,hasMore:w,rows:p}},async restore(e,t){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 S("NOT_FOUND",`document not found: ${t}`)}const l=a.tables[i.tableName]?.softDeleteMode?.field;if(!l)throw new S("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){T(e,"ctx.db.replace(table, id, document)");const w=re(t,e);if(!w){const q=Te(e);if(q){J(i),await q.replace(e,t,i,l);return}throw new S("NOT_FOUND",`document not found: ${t}`)}const{docJson:p,row:f,tableName:h}=w,E=a.tables[h];if(!E)throw new S("INTERNAL",`unknown table: ${h}`);fn("replace",i);const _=l?.allowExplicitId&&typeof i._creationTime=="number"?i._creationTime:void 0,b=typeof f._creationTime=="number"?f._creationTime:void 0,A=_??b??$e(),I={...i,...ee(h),_creationTime:A,_id:t};ht(E,i,I,ce);const D=l?.allowExplicitId===!0,m=Ge(E,I,{previous:()=>f,supplied:i,trusted:D});ne(h,"before","update")&&await oe("before","update",{doc:{...m},id:t,op:"update",previous:f,table:h}),D||W(h,m,f),Re(h),ve(h),Ne(y,h,wr(h),[A,le(m),t,p]),Fe(h,t,m,f),Le(h,t,m),ke(h,f,m),_e(h,t,f,m),Ee?.invalidate(h,t,N(h,f,m)),Se(h,t,"update",m),M({indexKeys:N(h,f,m),key:t,op:"update",row:m,table:h}),ne(h,"after","update")&&await oe("after","update",{doc:m,id:t,op:"update",previous:f,table:h}),await ye({doc:m,id:t,op:"update",table:h})},async wipeShard(e){const t=new Set(e?.exclude),i=e?.tables,l=Object.entries(a.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(!a.tables[h])throw new S("INTERNAL",`wipeShard: unknown table: ${h}`)}const w={};let p=0;const{deleteAll:f}=O;if(f===void 0)throw new S("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}}},qn={db:O,scheduler:_t};return n.enforceRls===!0?Go(O,a,(e,t)=>re(e,t)?.tableName,v):O};export{Ki as CDC_LOG_TABLE,hs as IDEMPOTENCY_TABLE,Lr as NotUniqueError,ds as advanceClientWatermark,Ni as applyCdcChanges,fn as assertNoExplicitUndefined,$t as assertStorableRowId,Sr as assertValidClientId,Oi as backfillAggregateIndexes,Gi as backfillRankIndexes,ji as backfillSearchIndexes,Qi as bumpCdcEpoch,Vi as cdcCanVouchFor,Ji as cdcForkedError,zi as cdcSeqLeavingRows,Yi as cdcTouchesTables,Xi as cdcTrimmedError,Zi as compactCdcDocs,Zr as createShardCtxDb,es as cursorBelowRetainedFloor,Kr as meterReadBytes,ls as migrateClientWatermark,ts as minCdcReplayableSeq,ns as minCdcSeq,ln as normalizeIdStructurally,os as readCdcChangeKeys,rs as readCdcChanges,is as readCdcCursor,ss as readCdcEpoch,us as readClientWatermark,ws as readIdempotent,Es as runShardMigrations,ms as selectShapeMembers,Ss as selectShapeRows,Ke as stripReservedPatchFields,cs as trimCdcChanges,ps as trimIdempotent,gs as writeIdempotent};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createShardCtxDb as C}from"./NotUniqueError-
|
|
1
|
+
import{createShardCtxDb as C}from"./NotUniqueError-BjwNIte8.mjs";import{createRelayLink as N}from"./DEFAULT_MAX_RELAYS-B66neS_B.mjs";import{ConflictError as q}from"./ConflictError-C8GtJmjS.mjs";import{runShardMigrations as B}from"./runShardMigrations-xu993yo2.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};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/shard-engine",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.183",
|
|
4
4
|
"description": "Host-neutral reactive engine for Lunora: per-shard state, OCC, CDC, reactive subscriptions, and the poke protocol. Consumes @lunora/platform host contracts and can be mounted on any platform host.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cloudflare",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as S}from"@lunora/errors";import{q as mt}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 jn}from"./AGGREGATE_SQL_FUNCTION-C_ZipS9R.mjs";import{aggregateTableName as it,encodeAggregateKey as st,readAggregateValue as ct}from"./aggregateTableName-B_CtIQCS.mjs";import{mergeWhere as Q,CountRlsUnsupportedError as at,selectIndexForGroupBy as Gn,selectIndexForCount as Hn,selectIndexForAggregate as Kn}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{backfillSearchIndexesForTable as Nn,searchIndexCoversTable as Qn}from"./backfillAggregateIndexes-Pk0KLrfk.mjs";import{backfillAggregateIndexes as Bi,backfillRankIndexes as qi,backfillSearchIndexes as Pi}from"./backfillAggregateIndexes-Pk0KLrfk.mjs";import{appendCdcChange as Vn,readCdcDocAtOrBefore as Jn}from"./CDC_LOG_TABLE-BFGgqai8.mjs";import{CDC_LOG_TABLE as Oi,applyCdcChanges as ji,bumpCdcEpoch as Gi,cdcCanVouchFor as Hi,cdcForkedError as Ki,cdcSeqLeavingRows as Ni,cdcTouchesTables as Qi,cdcTrimmedError as Vi,compactCdcDocs as Ji,cursorBelowRetainedFloor as zi,minCdcReplayableSeq as Yi,minCdcSeq as Xi,readCdcChangeKeys as Zi,readCdcChanges as es,readCdcCursor as ts,readCdcEpoch as ns,trimCdcChanges as os}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-BZIpATcs.mjs";import{SCAN_DEP as j}from"./SCAN_DEP-D7qE3iUe.mjs";import{runSql as he,runDrizzle as K}from"./runDrizzle-RC09zZrh.mjs";import{p as Zn,j as wt,D as ie,r as xe,W as eo,k as le,b as Ue,A as dt,a as Oe,m as ue,e as fe,s as to,t as no,u as oo,i as ro,q as jt,h as gn,g as io}from"./do-sql-105TONaE.mjs";import{renderSql as yn,unionAll as $n,WORKERD_SQLITE_LIMITS as En}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{a as so,u as co}from"./estimate-bytes-C-C35VXL.mjs";import{coveringGeohashes as ao,boundingBoxGeohashes as lo,haversineMeters as uo,pointInBoundingBox as fo}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{NotFoundError as ho}from"./NotFoundError-BhF7FeFr.mjs";import{resolvePatch as wo,assertPatchAllowed as po,operatorFields as go,readPatchField as Gt}from"./assertPatchAllowed-CA_H466g.mjs";import{tiebreakDirectionFor as yo,encodeCursor as Qe,nullsOrderSuffix as $o,normalizeOrderKeys as Ht,uniqueIndexFields as Eo,buildSeekWhere as mo,decodeCursor as Kt,buildSeekBeforeWhere as So,softDeleteScope as Ae,applySelect as pt}from"./CURSOR_PREFIX-6offuG6M.mjs";import{rankTableName as Nt,sortColumnName as Qt,resolveRankPartition as Ro,encodePartitionKey as vo,RANK_TIEBREAK as To,rankPivotConditionSql as _o}from"./RANK_TIEBREAK-D3ye2GsL.mjs";import{UNVOUCHABLE_DEP as Vt}from"./UNVOUCHABLE_DEP-Ds9gxVqs.mjs";import{idIndexKey as Ao,withUnknownIndexKeys as Io,indexKeysForRow as xo,buildIndexRange as bo}from"./buildIndexRange-BTChxh3k.mjs";import{r as Ve,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 Co,isPushableWhere as Mo}from"./isPushableWhere-BeYAOjUb.mjs";import{deriveRelationEdges as Do,findRelated as ko}from"./RELATED_DEFAULT_LIMIT-CVqN4JEu.mjs";import{assertFlatPredicate as lt,resolveRelationPredicates as Lo,composeReadPredicate as Fo}from"./DEFAULT_MAX_RELATION_KEYS-DfrMi_eE.mjs";import{describeRelationWrites as Wo}from"./describeRelationWrites-omar6-u9.mjs";import{runRowValidators as je,transformOnlyDefinition as Bo,applyInsertDefaults as gt,resolveWith as zt,relationHooks as Yt,applyOnDelete as qo,fanOutScalarCounts as Po}from"./applyInsertDefaults-CVukTkQ5.mjs";import{guardWriter as Uo}from"./RLS_UNWRAP_SYMBOL-H6J96vgK.mjs";import{mayHoldProjectedValue as Oo}from"./BIGINT_KEY_DIGITS-DE6yshOt.mjs";import{createSystemReader as jo}from"./createSystemReader-BSCxr8Qs.mjs";import{ConflictError as se}from"./ConflictError-C8GtJmjS.mjs";import{hasTrigger as Xt,runTriggers as Go}from"./hasTrigger-CjlwI4le.mjs";import{advanceClientWatermark as is,migrateClientWatermark as ss,readClientWatermark as cs}from"./CLIENT_WATERMARK_TABLE-De7z_OHV.mjs";import{IDEMPOTENCY_TABLE as ds,readIdempotent as ls,trimIdempotent as us,writeIdempotent as fs}from"./IDEMPOTENCY_TABLE-COrgeP3O.mjs";import{runShardMigrations as ws}from"./runShardMigrations-xu993yo2.mjs";import{selectShapeMembers as gs,selectShapeRows as ys}from"./selectShapeMembers-Dqx_m7BF.mjs";const Ho=n=>{const r=atob(n),o=Uint8Array.from(r,s=>s.codePointAt(0)??0);return new TextDecoder().decode(o)},Ko=()=>new S("BAD_REQUEST","invalid cursor"),Zt=16,en=8,z=1024,St=(n,r)=>r.query(n),No=(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},Qo=(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)}},Vo=(n,r,o)=>{const s={eq:(c,u)=>{if(!n.definition.filterFields?.includes(c))throw new S("INTERNAL",`field "${c}" is not a filter field of search index "${n.indexName}" on table "${r}"`);if(n.filters.length>=en)throw new S("BAD_REQUEST",`search index "${n.indexName}" on table "${r}": at most ${String(en)} .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 S("INTERNAL",`search index "${g.indexName}" on table "${r}" indexes "${g.definition.field}", not "${c}"`);const m=St(u,o).length;if(m>Zt)throw new S("BAD_REQUEST",`search index "${g.indexName}" on table "${r}": at most ${String(Zt)} search terms are supported (got ${String(m)})`);return g.field=c,g.query=u,g.hasQuery=!0,s}};return s},Jo=n=>{if(n.length>z)throw new S("BAD_REQUEST",`more than ${String(z)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},zo=n=>Math.min(n.offset+n.numItems+1,z),Yo=n=>btoa(`search:${String(n)}`),Xo=n=>{let r;try{r=Ho(n)}catch{return}if(!r.startsWith("search:"))return;const o=Number(r.slice(7));return Number.isInteger(o)&&o>=0?o:void 0},Zo=n=>{if(typeof n.endCursor=="string")throw new S("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 S("BAD_REQUEST",`search pagination needs a finite numItems, got ${String(n.numItems)}`);const r=Math.max(0,Math.floor(n.numItems)),o=n.cursor?Xo(n.cursor):0;if(o===void 0)throw Ko();if(o+r>=z)throw new S("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}},er=(n,r)=>{const o=r.offset+r.numItems,s=r.numItems>0&&n.length>o;return{continueCursor:s?Yo(o):null,isDone:!s,page:n.slice(r.offset,o)}},tr=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 S("BAD_REQUEST",`search returns at most ${String(z)} documents (asked for ${String(r)}) — narrow the query or paginate instead`);return r},mn=500,Sn=(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??mn},Rn=(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)`)},nr=32,or=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?Ve(`${c} ${u}`):be(`${c} WHERE `,r,` ${u}`)},Ye={fieldRef:n=>Ve(wt(n)),rangeTypeGuard:(n,r)=>Ve(Zn(n,r)),serialize:Ce},rr=n=>n===void 0?"":$o(n==="first"),Tn=n=>{const r=n.map(o=>`${wt(o.field)} ${o.direction==="desc"?"DESC":"ASC"}${rr(o.nulls)}`);return n.some(o=>o.field==="_id"||o.field==="id")||r.push(`${wt("id")} ${yo(n)==="desc"?"DESC":"ASC"}`),r.join(", ")},ir={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},_n=n=>new Set(n.sqlConditions.filter(r=>r.comparator==="=").map(r=>r.field)),sr=n=>{const r=_n(n);let o=0;for(;o<n.indexFields.length&&r.has(n.indexFields[o]??"");)o+=1;return n.indexFields.slice(o)},cr=(n,r)=>{const o=n.order,s=sr(n),{shape:c}=r;return s.length>0?Ht(s.map(u=>({[u]:o})),c,{pinned:_n(n),uniqueBy:Eo(r.indexes,c)}):Ht([{_creationTime:o}],c)},ar=(n,r,o,s)=>{const c=n.sqlConditions.map(u=>({[u.field]:{[ir[u.comparator]??"eq"]:u.value}}));if(o&&c.push(mo(r,Kt(o))),s&&c.push(So(r,Kt(s))),c.length!==0)return c.length===1?c[0]:{AND:c}},dr=n=>{if(n.want!==void 0)return n.selective?Math.max(n.want,nr):n.want},yt=(n,r,o,s,c,u,g)=>{const m=cr(s,o),y=Tn(m),l=[],{filters:D,want:I}=u;let T=u.cursor??void 0,x=dr(u);if(I===0)return{documents:l,orderKeys:m};for(;;){const B=Z(ar(s,m,T,u.endCursor),Ye,ze),P=vn(r,c&&B?be(B," AND ",c):c??B,y,x),W=he(n,P.text,...P.params).toArray();let U={};g(W.length);for(const G of W)if(U=xe(G),D.every(ee=>ee(U))&&l.push(U)===I)return{documents:l,orderKeys:m};if(x===void 0||W.length<x)return{documents:l,orderKeys:m};T=Qe(U,m),x=Math.max(x,Math.min(x*2,or))}},lr=(n,r,o,s,c,u,g,m)=>{const y=Math.max(0,Math.floor(c.numItems));if(typeof c.endCursor=="string"){const{documents:B,orderKeys:P}=yt(n,r,o,s,u,{cursor:c.cursor,endCursor:c.endCursor,filters:g.all,selective:g.selective,want:void 0},m),W=B.length>=2?B[Math.floor(B.length/2)-1]:void 0;return{continueCursor:c.endCursor,isDone:!0,page:B,splitCursor:W?Qe(W,P):null}}const{documents:l,orderKeys:D}=yt(n,r,o,s,u,{cursor:c.cursor,filters:g.all,selective:g.selective,want:y+1},m),I=l.length>y,T=I?l.slice(0,y):l,x=T.at(-1);return{continueCursor:I&&x?Qe(x,D):null,isDone:!I,page:T}},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),ur=Xe(n=>`INSERT INTO ${n} (id, _creationTime, ${we}) VALUES (?, ?, ?)`),tn=Xe(n=>`UPDATE ${n} SET ${we} = ? WHERE id = ? AND ${we} = ?`),fr=Xe(n=>`UPDATE ${n} SET _creationTime = ?, ${we} = ? WHERE id = ? AND ${we} = ?`),hr=Xe(n=>`DELETE FROM ${n} WHERE id = ? AND ${we} = ?`),wr="SELECT changes() AS changed",nn=new Map,pr="",gr=n=>{const r=JSON.stringify(n),o=nn.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 = ${pr}`),{sql:c}=yn("sqlite",a`${$n(s)} LIMIT 1`);return nn.set(r,c),c},yr=(n,r)=>r.map(()=>n),$r=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,Er=n=>{if(!$r.test(n))throw new S("INTERNAL",`invalid clientId ${JSON.stringify(n)}: a client-supplied row id must be a UUID`)},$t=n=>{if(n.includes("\0"))throw new S("BAD_REQUEST",`invalid row id ${JSON.stringify(n)}: a row id cannot hold a NUL character (U+0000)`)},mr=(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?gt(n,u,s)._id:u._id;typeof g=="string"&&$t(g)}},on=50,Ge=Math.floor(En.boundParams/3),rn=En.boundParams,Sr=128,Je=n=>new S("BATCH_LIMIT_EXCEEDED",n,{status:400}),He=(n,r,o)=>{Rn(n,Sn(r,o,Je),o,Je)},sn=async(n,r,o,s,c)=>{const u=Sn(s,c,Je),{page:g}=await n.findMany(r,Number.isFinite(u)?{limit:u+1,omitContinueCursor:!0,where:o}:{where:o});return g.length>u&&Rn(Math.max(await n.count(r,{where:o}),g.length),u,c,Je),g},Rr=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},vr=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},Tr=(n,r,o,s,c)=>{const u=St(o.query,mt(o.definition.language));if(u.length===0)return[];const g=qn(r,o.indexName),m=`${g}__vocab`,y=u.length-1,l=u.map((P,W)=>{const U=Qo(P,W===y),G=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(W))} AS ${a.identifier("__term__")}, COUNT(*) AS ${a.identifier("__n__")} FROM ${a.identifier(m)} WHERE ${G} GROUP BY ${a.identifier("doc")}`}),D=u.map((P,W)=>a`SUM(CASE WHEN u.${a.identifier("__term__")} = ${a.raw(String(W))} THEN u.${a.identifier("__n__")} ELSE 0 END)`),I=a`SELECT f.${a.identifier(qe)} AS ${a.identifier(qe)}, ${a.join(D,a` + `)} AS ${a.identifier("__score__")} FROM (${$n(l)}) u JOIN ${a.identifier(g)} f ON f.rowid = u.${a.identifier("doc")} GROUP BY f.${a.identifier(qe)} HAVING ${a.join(D.map(P=>a`${P} > 0`),a` AND `)}`,T=An(o,c);let x=a`SELECT m.id, m._creationTime, m.${a.identifier(ie)}, s.${a.identifier("__score__")} AS ${a.identifier("__score__")} FROM (${I}) s JOIN ${a.identifier(r)} m ON m.id = s.${a.identifier(qe)}`;T.length>0&&(x=a`${x} WHERE ${a.join(T,a` AND `)}`),x=a`${x} ORDER BY s.${a.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${a.raw(String(s))}`;const B=[];for(const P of K(n,x)){const W=gn(P);if(W){const U=P.__score__;B.push({document:W,score:typeof U=="number"?U:Number(U??0)})}}return B},_r=(n,r,o,s,c)=>{const u=mt(o.definition.language),g=St(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(vr(s)))}`;const l=K(n,y).toArray(),D=[];for(const I of l){const T=gn(I);if(!T)continue;const x=No(Pn(T,o.definition),g);x>0&&D.push({creationTime:typeof T._creationTime=="number"?T._creationTime:0,doc:T,id:typeof T._id=="string"?T._id:"",score:x})}return D.sort((I,T)=>T.score-I.score||T.creationTime-I.creationTime||I.id.localeCompare(T.id)),D.slice(0,s).map(I=>({document:I.doc,score:I.score}))},ut=(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 S("BAD_REQUEST",`geo index "${s}" on table "${o}": ${r} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},Ar=(n,r)=>{const o=n,s={near:(c,u)=>{if(o.within)throw new S("INTERNAL",`geo index "${o.indexName}" on table "${r}": call .near() or .within(), not both`);if(ut(c,".near() point",r,o.indexName),!Number.isFinite(u)||u<=0)throw new S("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 S("INTERNAL",`geo index "${o.indexName}" on table "${r}": call .near() or .within(), not both`);if(ut(c.sw,".within() sw corner",r,o.indexName),ut(c.ne,".within() ne corner",r,o.indexName),c.sw.lat>c.ne.lat)throw new S("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 S("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},Ir=(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},xr=(n,r)=>{const o=Ir(n,r.definition.field);if(!o)return;const s=typeof n._creationTime=="number"?n._creationTime:0;if(r.near){const c=uo(r.near.point,o);return c<=r.near.radiusMeters?{creationTime:s,distance:c}:void 0}return fo(o,r.within)?{creationTime:s,distance:0}:void 0},br=(n,r,o,s)=>{if(!o.near&&!o.within)throw new S("INTERNAL",`geo index "${o.indexName}" on table "${r}": call .near(point, radius) or .within(box)`);const c=o.near?ao(o.near.point,o.near.radiusMeters):lo(o.within),u=io(r,o.indexName),g=c.map(I=>a`(g.${a.identifier("__geohash__")} >= ${I} AND g.${a.identifier("__geohash__")} < ${`${I}{`})`),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 `)}`,l=K(n,y).toArray(),D=[];for(const I of l){const T=xe(I),x=T?xr(T,o):void 0;T&&x&&D.push({creationTime:x.creationTime,distance:x.distance,doc:T})}return D.sort((I,T)=>I.distance-T.distance||T.creationTime-I.creationTime),D},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},Cr=(n,r,o,s,c,u=()=>{})=>{const g=o.within!==void 0,m=br(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},cn=(n,r,o,s,c,u,g=()=>{})=>{const{geo:m}=o;if(!m)throw new S("INTERNAL","runGeoTerminalScored called without a staged geo query");const y=c.length>0,l=Cr(n,r,m,y?void 0:u,s,g);return y?In(l,c,u,D=>D.document):l},an=(n,r,o)=>{const s=n.shape[r];if(s!==void 0&&Oo(s))throw new S("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)`)},Mr=n=>{let r=0;const o=[],s={...Ye,relationExists:c=>{const{childWhere:u,negated:g,parentTable:m,relation:y}=c,l=`__rel_${String(r)}`,D=o.at(-1)??m;r+=1,n(y.table,j);const I=y.kind==="one"?y.field:y.references,T=y.kind==="one"?y.references:y.field,x=Ve(`${jt(l,T)} = ${jt(D,I)}`);o.push(l);const B=Z(u,s,ze);o.pop();const P=B===void 0?x:be(x," AND ",B),W=be("EXISTS (SELECT 1 FROM ",Jt(y.table)," AS ",Jt(l)," WHERE ",P,")");return g?be("NOT ",W):W}};return s};class Dr extends S{constructor(r="unique() found more than one matching document"){super("NOT_UNIQUE",r,{name:"NotUniqueError"})}}const kr=/\s/u,Lr=String.fromCodePoint(0),dn=(n,r,o)=>{if(!n.tables[r])throw new S("INTERNAL",`unknown table: ${r}`);return typeof o!="string"||o.length===0||kr.test(o)||o.includes(Lr)?null:o},xn=(n,r,o,s=()=>{},c=()=>{},u=()=>{},g)=>{const m=r.tables[o];if(!m)throw new S("INTERNAL",`unknown table: ${o}`);const y=Ae(m.softDeleteMode,void 0),l=g??{indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[],verifyFilters:[]},D=()=>{const R=Q(y,l.pushedWhere);return R?Z(R,ue):void 0},I=()=>{const R=Q(y,l.pushedWhere);return R?Z(R,Ye,ze):void 0},T=()=>[...l.inMemoryFilters,...l.verifyFilters];let x=0;const B=R=>{const{search:C}=l;if(!C)throw new S("INTERNAL","runSearchFetch called without a staged search");Nn(oo(n),o,m);const L=l.inMemoryFilters.length>0,F=tr(L?void 0:R),k=ro(n);if(k&&!Qn(n,o,C.definition))throw new S("SEARCH_INDEX_BUILDING",`search index "${C.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=D(),te=k?Tr(n,o,C,F,pe):_r(n,o,C,F,pe);!L&&R===void 0&&Jo(te);const ge=T();return x=te.length,ge.length>0?In(te,ge,R,J=>J.document):te},P=R=>B(R).map(C=>C.document),W=R=>{const C=Zo(R);return er(P(zo(C)),C)},U=()=>{if(l.search||l.geo||l.indexName===void 0){c(void 0);return}c(bo(o,l.indexName,l.indexFields,l.sqlConditions,Ce))},G=R=>{U();let C=0;const L=(()=>{if(l.search){const F=P(R);return C=x,F}return l.geo?cn(n,o,l,D(),T(),R,F=>{C=F}).map(F=>F.document):yt(n,o,m,l,I(),{filters:T(),selective:l.inMemoryFilters.length>0,want:R===void 0?void 0:Math.max(0,Math.floor(R))},F=>{C+=F}).documents})();return u(Math.max(C,L.length)),L},ee=()=>{if(!l.search&&!l.geo)throw new S("INTERNAL",`ctx.db.query("${o}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);U();let R=0;const C=(()=>{if(l.search){const L=B(void 0);return R=x,L}return cn(n,o,l,D(),T(),void 0,L=>{R=L})})();return u(Math.max(R,C.length)),C},N={async*[Symbol.asyncIterator](){const R=xn(n,r,o,s,c,u,{...l,indexFields:[...l.indexFields],inMemoryFilters:[...l.inMemoryFilters],sqlConditions:[...l.sqlConditions],verifyFilters:[...l.verifyFilters]});if(l.search){yield*await R.collect();return}let C;for(;;){const L=await R.paginate({cursor:C??null,numItems:Sr});if(yield*L.page,L.isDone||L.continueCursor===null)return;C=L.continueCursor}},async collect(){return G(void 0)},async collectWithScores(){return ee()},filter(R){const C=Co(R);return C!==void 0&&Mo(C,m.shape)?(l.pushedWhere=Q(l.pushedWhere,C),l.verifyFilters.push(R)):l.inMemoryFilters.push(R),N},async first(){return G(1)[0]??null},order(R){return l.order=R==="desc"?"desc":"asc",N},async paginate(R){let C=0;if(U(),l.search){const F=W(R);return u(F.page.length),F}if(l.geo)throw new S("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const L=lr(n,o,m,l,R,I(),{all:T(),selective:l.inMemoryFilters.length>0},F=>{C+=F});return u(Math.max(C,L.page.length)),L},async take(R){return G(R)},async unique(){const R=G(2);if(R.length>1)throw new Dr(`unique() on table "${o}" matched ${String(R.length)} documents; expected at most one`);return R[0]??null},withGeoIndex(R,C){const L=(m.geoIndexes??[]).find(k=>k.name===R);if(!L)throw new S("INTERNAL",`unknown geo index "${R}" on table "${o}"`);s(o,R,"geo");const F={definition:L,indexName:R};if(l.geo=F,C(Ar(F,o)),!F.near&&!F.within)throw new S("INTERNAL",`geo index "${R}" on table "${o}" requires a .near(point, radius) or .within(box) call`);return N},withIndex(R,C){const L=m.indexes.find(F=>F.name===R);if(!L)throw new S("INTERNAL",`unknown index "${R}" on table "${o}"`);return s(o,R,"index"),l.indexName=R,l.indexFields=L.fields,C&&C(Rr(l)),N},withSearchIndex(R,C){const L=(m.searchIndexes??[]).find(k=>k.name===R);if(!L)throw new S("INTERNAL",`unknown search index "${R}" on table "${o}"`);s(o,R,"search");const F={definition:L,field:L.field,filters:[],hasQuery:!1,indexName:R,query:""};if(l.search=F,C(Vo(F,o,mt(L.language))),!F.hasQuery)throw new S("INTERNAL",`search index "${R}" on table "${o}" requires a .search(field, query) call`);return N}};return N},ft=(n,r,o,s)=>{const c=o;for(const[u,g]of no(n)){if(g.serverDefault){u in r&&(c[u]=g.serverDefault({auth:s}));continue}g.onUpdateFn&&!(u in r)&&(c[u]=g.onUpdateFn())}},ln=5,un=(n,r)=>{for(const o of Object.keys(r))if(r[o]===void 0)throw new S("INTERNAL",`Cannot ${n} field '${o}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},fn=["_commitSeq","_creationTime","_id"],Ke=n=>fn.some(r=>r in n)?Object.fromEntries(Object.entries(n).filter(([r])=>!fn.includes(r))):n,Fr=/unique constraint failed/i,Wr=n=>n instanceof Error&&Fr.test(n.message),Br=/string or blob too big/iu,qr=(n,r)=>{if(!(!(n instanceof Error)||!Br.test(n.message)))throw new S("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 Wr(c)?new se(`unique constraint violation on "${r}"`,"unique"):(qr(c,r),c)}},Ne=(n,r,o,s)=>{if(Et(n,r,o,s),he(n,wr).one().changed===0)throw new se(`optimistic concurrency conflict on "${r}" — the row changed during this mutation; refetch and retry`,"occ")},hn=(n,r,o,s,c,u,g)=>{const m=[];for(let I=0;I<o.length+1;I+=1){const T=o[I],x=s[I],B=x?.direction==="desc"?"desc":"asc",P=T===void 0||x===void 0?a`${a.identifier(To)} < ${g}`:_o(T,u[I],B,!1);if(P===void 0)continue;const W=[];for(let G=0;G<I;G+=1)W.push(a`${a.identifier(o[G])} IS ${u[G]}`);W.push(P);const[U]=W;m.push(W.length===1&&U!==void 0?U:a`(${a.join(W,a` AND `)})`)}const y=m.length>0?a.join(m,a` OR `):a`1 = 0`,l=K(n,a`SELECT COUNT(*) AS c FROM ${a.identifier(r)} WHERE ${a.identifier("__partition__")} = ${c} AND (${y})`).one(),D=K(n,a`SELECT COUNT(*) AS c FROM ${a.identifier(r)} WHERE ${a.identifier("__partition__")} = ${c}`).one();return{before:l.c,total:D.c}},Pr=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||Xt(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"||Xt(n,s,"delete")||o(s)).map(([s])=>s))},Ur=n=>{const r=new Map;for(const[o,s]of Object.entries(n.tables))s.softDeleteMode&&r.set(o,s.softDeleteMode.field);return r},ht=new WeakMap,Or=(n,r)=>{let o=ht.get(r.tables);if(!ht.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"),ht.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},jr=(n,r,o)=>{for(const s of n){const c=s,u=c?.[ie];if(typeof u=="string"){const g=c?.id,m=co(u);typeof g!="string"?r.recordReadBytes(m):o===void 0?r.recordDocumentRead(`${g}\0${String(m)}`,m):r.recordDocumentRead(`${o}\0${g}`,m)}}},Gr=(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),l=o===void 0?void 0:Or(c,o);let D=!1;const I=T=>{jr(T,r,l)};return g.toArray=()=>{const T=[];for(const x of{[Symbol.iterator]:y})I([x]),T.push(x);return T},g.one=()=>{D=!0;try{const T=m();return I([T]),T}finally{D=!1}},g[Symbol.iterator]=function*(){for(const x of{[Symbol.iterator]:y})D||I([x]),yield x},g};return new Proxy(n,{get:(c,u)=>u==="exec"?s:u===eo?c:Reflect.get(c,u,c)})},Hr=new Map([["findFirst","rows"],["findFirstOrThrow","rows"],["findMany","page"],["get","rows"],["lookupById","lookup"],["rankPage","page"]]),Kr=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=so(n);if(s===void 0)return;const c=n._id;typeof c=="string"?o.recordDocumentRead(`global\0${r}\0${c}`,s):o.recordReadBytes(s)},bn=(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)}},Cn=(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=Kr.get(c);return(...m)=>{const y=Reflect.apply(u,s,m);return g!==void 0?Promise.resolve(y).then(l=>(bn(l,g,r,o),l)):typeof y=="object"&&y!==null&&!(y instanceof Promise)?Cn(y,r,o):y}}}),Nr=new Set(["findFirst","findFirstOrThrow","findMany"]),Qr=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=>pt(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]}},Vr=(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)=>Cn(Reflect.apply(c,o,g),String(g[0]),r);const u=Hr.get(s);return u===void 0?c:async(...g)=>{const m=Nr.has(s)?Qr(g):void 0,y=await Reflect.apply(c,o,m?.args??g);return bn(y,u,String(g[0]),r),m===void 0?y:m.project(y,u)}}}),wn=new WeakMap,pn=new WeakMap,Jr=n=>{const{baselineSeq:r,onStalePatchDropped:o}=n,{headroom:s}=n,c=wn.get(n)??{value:void 0},u=pn.get(n)??{value:0};let g;const m=()=>{if(g===void 0){const e={...n,enforceRls:!1,headroom:void 0};wn.set(e,c),pn.set(e,u),g=Jr(e)}return g},y=Gr(n.sql,s,n.schema),{schema:l}=n,D=n.broadcast??(()=>{}),I=(e,t)=>{if(!Object.hasOwn(l.tables,e))throw new S("BAD_REQUEST",`${t}: "${e}" is not a table in this schema`)},T=Do(l),x=new Map;for(const e of T){const t=i=>(l.tables[i]?.shardMode?.kind??"root")==="root";!e.array&&t(e.sourceTable)&&t(e.targetTable)&&x.set(e.sourceTable,[...x.get(e.sourceTable)??[],e])}const B=(e,t,i)=>{for(const d of x.get(e)??[]){const w=t[d.column];if(typeof w!="string"||i?.[d.column]===w||d.targetTable===e&&t._id===w)continue;if(K(y,a`SELECT 1 FROM ${a.identifier(d.targetTable)} WHERE id = ${w} LIMIT 1`).toArray().length===0)throw new S("VALIDATION_ERROR",`${d.name} references ${d.targetTable} row "${w}", which does not exist`)}},P=Wo(l,n.inTransaction),W=Pr(l),U=Ur(l),G=()=>n.inTransaction?.()===!0,ee=e=>l.tables[e]?.commitOrderedMode!==!0?{}:((c.value===void 0||!G())&&(c.value=zn(y)),{[Yn]:c.value}),N=(e,...t)=>{const i=l.tables[e]?.indexes??[],d=[];let w;for(const p of t)p&&(typeof p._id=="string"&&p._id!==w&&(w=p._id,d.push(Ao(w))),d.push(...Io(i,xo(i,p,Ce))));return d.length>0?d:void 0},R=n.onRead??(()=>{}),C=e=>{Ut(l.tables[e])&&R(Vt,Vt)},L=n.onReadRange??(e=>{R(e.table,j)}),F=e=>{C(e.table),L(e)},k=(e,t,i)=>{t!==void 0&&t!==j&&s?.recordRead(1),C(e),R(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:$e}=n,Ee=n.clock??(()=>Date.now()),Rt=n.idGenerator??(()=>crypto.randomUUID()),vt=n.scheduler??On,me=Vr(n.globalDb,s),ce=n.auth??{identity:null,userId:null},Tt=n.cdc??!1,Ze=vt,Mn=jo({scheduler:typeof Ze.list=="function"&&typeof Ze.get=="function"?Ze:void 0,storage:n.storage}),Se=(e,t,i,d)=>{Tt&&!Ut(l.tables[e])&&Vn(y,Ee(),e,t,i,d)},_t=(e,t,i,d)=>{const w=l.tables[e];if(w?.dropStalePatchesMode!==!0||!Tt)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=go(w,i);return Object.keys(Ke(i)).some($=>!h.has($)&&Pt(Gt(f,$))!==Pt(Gt(d,$)))},ae=e=>l.tables[e]?.shardMode?.kind==="global",At=(e,t)=>{if(ae(e)){if(!me)throw new S("INTERNAL",`cross-backend ${t} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return me}return O},et=e=>At(e,"cascade"),H=(e,t)=>{if(ae(e)){if(!me)throw new S("INTERNAL",`${t} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return me}},It=async(e,t,i,d,w)=>{w&&J(i);const p=await e.insert(t,i,d);return D({key:p,op:"insert",row:{...i,_id:p},table:t}),p},tt=(e,t)=>At(e,"relation load").findMany(e,t),xt=(e,t)=>(ae(e)&&k(e,j),tt(e,t)),Dn=e=>!ae(e.table),bt=n.relationExistsPushDown??"auto",Ct=bt!=="never",{maxRelationKeys:Mt}=n,De=(e,t,i)=>Lo(e,{fetcher:xt,maxRelationKeys:Mt,relationBaseWhere:i,schema:l,tableName:t}),Dt=async(e,t,i,d)=>{const w=H(e,"relation grouped count");if(w)return k(e,j),Po((E,q)=>w.count(E,q),e,t,i,d);const p=l.tables[e];if(!p)throw new S("INTERNAL",`unknown table: ${e}`);k(e,j);const f=Ae(p.softDeleteMode,void 0),h={[t]:{in:i}},$=Q(Q(h,d),f),v=await De($,e,void 0),b=Z(v,ue),_=fe(t);let A=a`SELECT ${_} AS __fk__, COUNT(*) AS count FROM ${a.identifier(e)}`;b&&(A=a`${A} WHERE ${b}`),A=a`${A} GROUP BY ${_}`;const M=K(y,A).toArray();return new Map(M.map(E=>[E.__fk__,E.count]))},kt=new Set;for(const[e,t]of Object.entries(l.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>on)throw u.value-=1,new se(`trigger recursion exceeded ${String(on)} levels on "${i.table}" — check for a self-triggering write`,"trigger");try{await Go({ctx:Wn,event:i,op:t,schema:l,tableName:i.table,timing:e})}finally{u.value-=1}},{ensureBackfilledForTable:Re,ensureBackfilledIndex:nt,ensureRankBackfilled:ot,ensureRankBackfilledForTable:ve,syncAggregates:ke,syncCompanionsForInsert:Lt,syncGeo:Le,syncRanks:Te,syncSearch:Fe}=Xn({broadcast:D,indexKeysFor:(e,t)=>N(e,t),invalidateCache:(e,t,i)=>$e?.invalidate(e,t,N(e,i)),recordCdc:Se,schema:l,sql:y,verified:n.companionMemo?.verified}),Ft=(e,t,i)=>{const{shardMode:d}=t;if(d?.kind==="shardBy"&&!(d.field!==void 0&&(i.partitionBy??[]).includes(d.field)))throw Object.assign(new Error(`rank index "${i.name}" on "${e}" partitions across shards (shard key "${d.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})},Wt=e=>Object.entries(l.tables).filter(([,t])=>t.shardMode?.kind!=="global").map(([t])=>t).filter(t=>e===void 0||t===e),_e=e=>e===void 0||ae(e)?me:void 0,rt=async(e,t,i,d,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,d);return{deleted:i.length}},re=(e,t)=>{const i=Wt(t);for(let d=0;d<i.length;d+=rn){const w=i.slice(d,d+rn),[p]=he(y,gr(w),...yr(e,w)).toArray();if(!p)continue;const f=p.__t__,h=xe(p);if(typeof f!="string"||!h)return;const $=p[ie];return{docJson:typeof $=="string"?$:le($??{}),row:h,tableName:f}}},Bt={assertRankPartitionLocal:Ft,ensureRankBackfilled:ot,onRead:k,rowToDocument:xe,schema:l,sql:y},kn=(e,t,i)=>{const d=Z(i,ue);return d===void 0||K(y,a`SELECT 1 FROM ${a.identifier(e)} WHERE ${a.identifier("id")} = ${t} AND ${d}`).toArray().length>0},Ln=(e,t,i,d)=>_t(e,t,i,d)?(o?.({fields:Object.keys(Ke(i)),id:t,table:e}),!0):!1,Fn=async(e,t,i,d,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"&&d)return;throw f}return{applied:!0,doc:re(t,e)?.row??null}},qt=async(e,t,i,d)=>{const{fetchLimit:w,limit:p,orderKeys:f,predicate:h}=await Fo(t,i,{canPushExists:Ct?Dn:void 0,existsPushMode:bt==="always"?"always":"auto",fetcher:xt,maxRelationKeys:Mt,schema:l,tableName:e}),$=Ct?Mr(d):Ye,v=Z(h,$,ze),b=vn(e,v,Tn(f),w);return{limit:p,orderKeys:f,statement:b}},O={system:Mn,async aggregate(e,t){const i=H(e,"aggregate");if(i)return k(e,j),i.aggregate(e,t);const d=l.tables[e];if(!d)throw new S("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 S("INTERNAL",`aggregate(${e}, { op: "${t.op}" }): "field" is required for non-count reducers`);k(e,j);const w=Ae(d.softDeleteMode,void 0),p=Q(Q(t.baseWhere,t.where),w),f=await De(p,e,t.relationBaseWhere),h=f!==p;if(d.aggregateIndexes&&!t.baseWhere&&!h){const E=Kn(d.aggregateIndexes,t.op,t.field,t.where);if(E){nt(e,E.index);const q=st(E.index.by??[],E.key),Y=it(e,E.index.name),X=K(y,a`SELECT ${Ue} AS value, ${dt} AS count FROM ${a.identifier(Y)} WHERE ${Oe} = ${q}`).toArray()[0];return ct(t.op,X)}}an(d,t.field,`aggregate(${e}, { op: "${t.op}", field: "${t.field}" })`);const $=Z(f,ue),v=Pe(t.op),b=fe(t.field);let _=a`SELECT ${a.raw(v)}(${b}) AS value FROM ${a.identifier(e)}`;$&&(_=a`${_} WHERE ${$}`);const M=K(y,_).toArray()[0]?.value;return M??null},asId(e,t){const i=dn(l,e,t);if(i===null)throw new S("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,j),i.count(e,t);const d=l.tables[e];if(!d)throw new S("INTERNAL",`unknown table: ${e}`);const w=jn(t);if(w.restrictsCounts)throw new at(e);k(e,j);const p=Ae(d.softDeleteMode,void 0),f=Q(Q(w.baseWhere,w.where),p),h=await De(f,e,w.relationBaseWhere),$=h!==f;if(d.aggregateIndexes&&!w.baseWhere&&!$){const A=Hn(d.aggregateIndexes,w.where);if(A){nt(e,A.index);const M=st(A.index.by??[],A.key),E=it(e,A.index.name),q=K(y,a`SELECT ${Ue} AS value FROM ${a.identifier(E)} WHERE ${Oe} = ${M}`).toArray();return q[0]===void 0?0:q[0].value??0}}const v=Z(h,ue);let b=a`SELECT COUNT(*) AS count FROM ${a.identifier(e)}`;return v&&(b=a`${b} WHERE ${v}`),K(y,b).one().count},async delete(e,t,i){I(e,"ctx.db.delete(table, id)");const d=re(t,e);if(!d){const A=_e(e);A&&await rt(A,e,[t],i);return}const{docJson:w,row:p,tableName:f}=d,h=l.tables[f],$=i?.hard===!0,v=!$&&h?.softDeleteMode?h:void 0,b=v?.softDeleteMode?.field;if(b&&p[b]!==null&&p[b]!==void 0)return;if(ne(f,"before","delete")&&await oe("before","delete",{id:t,op:"delete",previous:p,table:f}),i?.skipOnDelete!==!0&&await qo({deletedId:t,deletedReference:A=>p[A],findHolders:async(A,M,E,q)=>(await et(A).findMany(A,{...q,includeDeleted:$,where:{[M]:E}})).page,onCascade:(A,M)=>et(A).delete(A,M,i),onRestrict:A=>{throw new se(A,"restrict")},onSetNull:(A,M,E)=>et(A).patch(A,M,{[E]:null}),schema:l,tableName:f}),Re(f),ve(f),v&&b){const A={[b]:Ee()},M={...p,...ee(f),...A,_id:t};ft(v,A,M,ce),Ne(y,f,tn(f),[le(M),t,w]),Fe(f,t,M,p),Le(f,t,void 0),ke(f,p,M),Te(f,t,p,void 0);const E=N(f,p,M);$e?.invalidate(f,t,E),Se(f,t,"update",M),D({indexKeys:E,key:t,op:"update",row:M,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,hr(f),[t,w]),Fe(f,t,void 0),Le(f,t,void 0),ke(f,p,void 0),Te(f,t,p,void 0);const _=N(f,p);$e?.invalidate(f,t,_),Se(f,t,"delete"),D({indexKeys:_,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(!l.tables[e])throw new S("INTERNAL",`unknown table: ${e}`);if(s!==void 0)return m().deleteAll(e,t);const i=Math.max(1,t?.chunkSize??mn),d=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($=>String($._id));if(h.length===0)break;for(const $ of h)await(w===void 0?O.delete(e,$,d):rt(w,e,[$],d)),p+=1;if(h.length<i)break}return{deleted:p}},async deleteMany(e,t,i){I(e,"ctx.db.deleteMany(table, ids)"),He(t.length,i?.limit,"deleteMany");for(const d of t)await O.delete(e,d);return{deleted:t.length}},async deleteWhere(e,t,i){const d=H(e,"deleteWhere"),p=(await sn(d??O,e,t,i?.limit,"deleteWhere")).map(f=>String(f._id));if(d)return rt(d,e,p,void 0,{options:i});if(O.deleteMany===void 0)throw new S("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 ho(`findFirstOrThrow: no "${e}" document matched`);return i},async findMany(e,t={}){const i=H(e,"findMany");if(i)return k(e,j),i.findMany(e,t);const d=l.tables[e];if(!d)throw new S("INTERNAL",`unknown table: ${e}`);const w=!t.where&&!t.baseWhere;w?k(e,j):k(e);const{limit:p,orderKeys:f,statement:h}=await qt(e,d,t,k),$=he(y,h.text,...h.params).toArray();w&&s?.recordRead($.length);const v=[];for(const M of $){const E=xe(M);E&&(v.push(E),!w&&typeof E._id=="string"&&k(e,E._id))}if(p===void 0)return t.with&&await zt({groupedCounter:Dt,fetcher:tt,parents:v,...Yt(t),schema:l,tableName:e,with:t.with}),{continueCursor:null,isDone:!0,page:pt(v,t.select,t.with)};const b=v.length>p,_=b?v.slice(0,p):v,A=_.at(-1);return t.with&&await zt({fetcher:tt,groupedCounter:Dt,parents:_,...Yt(t),schema:l,tableName:e,with:t.with}),{continueCursor:b&&A&&t.omitContinueCursor!==!0?Qe(A,f):null,isDone:!b,page:pt(_,t.select,t.with)}},async explain(e,t={}){const i=H(e,"explain");if(i)return i.explain(e,t);const d=l.tables[e];if(!d)throw new S("INTERNAL",`unknown table: ${e}`);const{statement:w}=await qt(e,d,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){I(e,"ctx.db.get(table, id)");const i=re(t,e);if(!i){const d=_e(e);return d?d.get(e,t):(C(e),R(e,t,!0),null)}return pe(i,t),i.row},async lookupById(e,t){const i=re(e,t);if(!i){for(const d of Wt(t))C(d),R(d,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,j),i.groupBy(e,t);const d=l.tables[e];if(!d)throw new S("INTERNAL",`unknown table: ${e}`);k(e,j);const w=t.agg??{op:"count"};if(Pe(w.op),w.op!=="count"&&!w.field)throw new S("INTERNAL",`groupBy(${e}, { agg: { op: "${w.op}" } }): "field" is required for non-count reducers`);const p=Ae(d.softDeleteMode,void 0),f=Q(Q(t.baseWhere,t.where),p),h=await De(f,e,t.relationBaseWhere),$=h!==f;if(d.aggregateIndexes&&!t.baseWhere&&!$){const E=Gn(d.aggregateIndexes,w.op,w.field,t.by,t.where),q=E===void 0?0:Object.keys(E.partial).length,Y=E?.index.by?.length??0;if(E&&(q===0||q===Y)){nt(e,E.index);const X=it(e,E.index.name),V=Object.keys(E.partial),de=[];if(V.length===(E.index.by??[]).length&&V.length>0){const We=st(E.index.by??[],E.partial),Be=K(y,a`SELECT ${Ue} AS value, ${dt} AS count FROM ${a.identifier(X)} WHERE ${Oe} = ${We}`).toArray();return Be.length>0&&de.push({key:{...E.partial},value:ct(w.op,Be[0])}),de}const Bn=K(y,a`SELECT ${Oe} AS key, ${Ue} AS value, ${dt} AS count FROM ${a.identifier(X)}`).toArray();for(const We of Bn){const Be=Un(JSON.parse(We.key));de.push({key:Be,value:ct(w.op,We)})}return de}}for(const E of[...t.by,w.field]){if(E===void 0)continue;const q=E===w.field?`groupBy(${e}, { agg: { op: "${w.op}", field: "${E}" } })`:`groupBy(${e}, { by: [..."${E}"] })`;an(d,E,q)}const v=Z(h,ue),b=t.by.map(E=>a`${fe(E)} AS ${a.identifier(E)}`);if(w.op==="count")b.push(a`COUNT(*) AS value`);else{const{field:E}=w;if(E===void 0)throw new S("INTERNAL",`groupBy(${e}, { agg: { op: "${w.op}" } }): "field" is required for non-count reducers`);b.push(a`${a.raw(Pe(w.op))}(${fe(E)}) AS value`)}let _=a`SELECT ${a.join(b,a`, `)} FROM ${a.identifier(e)}`;v&&(_=a`${_} WHERE ${v}`),_=a`${_} GROUP BY ${a.join(t.by.map(E=>fe(E)),a`, `)}`;const A=K(y,_).toArray(),M=[];for(const E of A){const q={};for(const X of t.by)q[X]=to(d.shape[X],E[X]??null);const{value:Y}=E;M.push({key:q,value:Y==null?null:Number(Y)})}return M},async insert(e,t,i){const d=H(e,"insert");if(d)return It(d,e,t,i,!0);const w=l.tables[e];if(!w)throw new S("INTERNAL",`unknown table: ${e}`);const p=i?.allowExplicitId===!0,f=je(w,gt(w,t,ce),{supplied:t,trusted:p});let h;i?.clientId!==void 0?(Er(i.clientId),h=i.clientId):i?.allowExplicitId&&typeof f._id=="string"?($t(f._id),h=f._id):h=Rt();const $=i?.allowExplicitId&&typeof f._creationTime=="number"?f._creationTime:Ee(),v={...f,...ee(e),_creationTime:$,_id:h};return ne(e,"before","insert")&&await oe("before","insert",{doc:{...v},id:h,op:"insert",table:e}),p||B(e,v),Re(e),ve(e),Et(y,e,ur(e),[h,$,le(v)]),Lt(e,h,v),ne(e,"after","insert")&&await oe("after","insert",{doc:v,id:h,op:"insert",table:e}),await ye({doc:v,id:h,op:"insert",table:e}),h},async insertManyUnsafe(e,t,i){if(He(t.length,i?.limit,"insertManyUnsafe"),t.length===0)return[];const d=H(e,"insert");if(d){const $=[];mr(l.tables[e],t,i?.allowExplicitId,ce);for(const v of t)J(v);for(const v of t){const b=await d.insert(e,v,{allowExplicitId:i?.allowExplicitId});D({key:b,op:"insert",row:{...v,_id:b},table:e}),$.push(b)}return $}const w=l.tables[e];if(!w)throw new S("INTERNAL",`unknown table: ${e}`);Re(e),ve(e);const p=[];for(let $=0;$<t.length;$+=Ge)p.push(ee(e));const f=i?.allowExplicitId===!0?void 0:Bo(w),h=t.map(($,v)=>{const b=gt(w,$,ce),_=f===void 0?b:je(f,b,{supplied:$}),A=i?.allowExplicitId===!0&&typeof _._id=="string"?_._id:void 0;A!==void 0&&$t(A);const M=A??Rt(),E=i?.allowExplicitId===!0&&typeof _._creationTime=="number"?_._creationTime:Ee(),q={..._,...p[Math.floor(v/Ge)],_creationTime:E,_id:M};return{creationTime:E,document:q,id:M}});for(const $ of h)J($.document);for(let $=0;$<h.length;$+=Ge){const v=a.join(h.slice($,$+Ge).map(_=>a`(${_.id}, ${_.creationTime}, ${le(_.document)})`),a`, `),b=yn("sqlite",a`INSERT INTO ${a.identifier(e)} (id, _creationTime, ${a.identifier(ie)}) VALUES ${v}`);Et(y,e,b.sql,b.params)}for(const{document:$,id:v}of h)Lt(e,v,$),await ge({doc:$,id:v,op:"insert",table:e});return h.map($=>$.id)},async insertMany(e,t,i){He(t.length,i?.limit,"insertMany");const d=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($){if(d&&$ instanceof se&&$.kind==="unique")w.push(null);else throw $}return w},normalizeId(e,t){return dn(l,e,t)},async patch(e,t,i,d){I(e,"ctx.db.patch(table, id, values)");const w=re(t,e);if(!w){const M=_e(e);if(M){J(i),await M.patch(e,t,i,d);return}throw new S("NOT_FOUND",`document not found: ${t}`)}const{docJson:p,row:f,tableName:h}=w,$=l.tables[h];if(!$)throw new S("INTERNAL",`unknown table: ${h}`);if(k(h,t),un("patch",i),_t(h,t,i,f)){o?.({fields:Object.keys(Ke(i)),id:t,table:h});return}const v=wo($,i,f),b={...f,...Ke(v),...ee(h),_id:t};ft($,v,b,ce);const _=je($,b,{only:new Set(Object.keys(v)),previous:()=>f,tolerateStoredNull:!0});po(d,f,_),ne(h,"before","update")&&await oe("before","update",{doc:{..._},id:t,op:"update",previous:f,table:h}),B(h,_,f),Re(h),ve(h),Ne(y,h,tn(h),[le(_),t,p]),Fe(h,t,_,f),Le(h,t,_),ke(h,f,_),Te(h,t,f,_);const A=N(h,f,_);$e?.invalidate(h,t,A),Se(h,t,"update",_),D({indexKeys:A,key:t,op:"update",row:_,table:h}),ne(h,"after","update")&&await oe("after","update",{doc:_,id:t,op:"update",previous:f,table:h}),await ye({doc:_,id:t,op:"update",table:h})},async patchIf(e,t,i){const d=H(e,"patchIf");if(d){if(d.patchIf===void 0)throw new S("INTERNAL",`ctx.db.patchIf on global table '${e}' is unsupported: its backend has no conditional write`);return J(i.patch),d.patchIf(e,t,i)}if(!l.tables[e])throw new S("INTERNAL",`unknown table: ${e}`);for(let w=1;w<=ln;w+=1){const p=await Fn(e,t,i,w<ln,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){I(e,"ctx.db.patchMany(table, patches)"),He(t.length,i?.limit,"patchMany");for(const d of t)await O.patch(e,d.id,d.patch);return{patched:t.length}},async patchWhere(e,t,i){const d=H(e,"patchWhere")??O,p=(await sn(d,e,t.where,i?.limit,"patchWhere")).map(f=>({id:String(f._id),patch:t.patch}));if(O.patchMany===void 0)throw new S("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 ko(O,T,e,t)},relationEdges:T,deleteRereadTables:W,inTransaction:G,softDeleteFields:U,relationWrites:P,query(e){const t=H(e,"query");return t?(k(e,j),t.query(e)):xn(y,l,e,te,i=>{i?F(i):k(e,j)},i=>{s?.recordRead(i)})},async rank(e,t,i){const d=H(e,"rank");if(d)return k(e,j),d.rank(e,t,i);te(e,t,"rank");const w=l.tables[e];if(!w)throw new S("INTERNAL",`unknown table: ${e}`);const p=w.rankIndexes?.find(V=>V.name===t);if(!p)throw new S("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(Ft(e,w,p),i.restrictsCounts)throw new at(e);k(e,j),ot(e,p);const f=typeof i.row=="string"?i.row:i.row._id;if(!f)return null;const h=Nt(e,p.name),$=p.sortBy.map((V,de)=>Qt(de)),v=$.map(V=>Me(V)).join(", "),b=K(y,a`SELECT ${a.identifier("__partition__")}, ${a.raw(v)} FROM ${a.identifier(h)} WHERE ${a.identifier("__id__")} = ${f}`).toArray(),[_]=b;if(_===void 0)return null;let A=_.__partition__;const M=Q(i.baseWhere,i.where);lt(M,l,e,"rank");const E=Ro(p,M);if(E){const V=vo(p.partitionBy??[],E);if(V!==A)return null;A=V}const q=$.map(V=>_[V]),{before:Y,total:X}=hn(y,h,$,p.sortBy,A,q,f);return{position:Y+1,total:X}},async rankBefore(e,t,i){if(ae(e))throw new S("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const d=l.tables[e];if(!d)throw new S("INTERNAL",`unknown table: ${e}`);const w=d.rankIndexes?.find($=>$.name===t);if(!w)throw new S("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(i.restrictsCounts)throw new at(e);k(e,j),ot(e,w);const p=Nt(e,w.name),f=w.sortBy.map(($,v)=>Qt(v)),h=w.sortBy.map(($,v)=>Ce(i.sortValues[v]??null));return hn(y,p,f,w.sortBy,i.partitionKey,h,i.rowId)},async rankPage(e,t,i={}){lt(Q(i.baseWhere,i.where),l,e,"rankPage");const d=H(e,"rankPage");if(d)return k(e,j),d.rankPage(e,t,i);te(e,t,"rank");const{continueCursor:w,hasMore:p,rows:f}=Ot(Bt,e,t,i);return{continueCursor:w,isDone:!p,page:f.map(h=>h.doc)}},async rankPageRows(e,t,i={}){lt(Q(i.baseWhere,i.where),l,e,"rankPage"),te(e,t,"rank");const{directions:d,hasMore:w,rows:p}=Ot(Bt,e,t,i);return{directions:d,hasMore:w,rows:p}},async restore(e,t){I(e,"ctx.db.restore(table, id)");const i=re(t,e);if(!i){const p=_e(e);if(p?.restore){await p.restore(e,t);return}throw new S("NOT_FOUND",`document not found: ${t}`)}const d=l.tables[i.tableName]?.softDeleteMode?.field;if(!d)throw new S("INTERNAL",`ctx.db.restore: table "${i.tableName}" is not a .softDelete() table`);const w=i.row[d]!==null&&i.row[d]!==void 0;await O.patch(e,t,{[d]:null}),w&&Te(i.tableName,t,void 0,i.row)},async replace(e,t,i,d){I(e,"ctx.db.replace(table, id, document)");const w=re(t,e);if(!w){const q=_e(e);if(q){J(i),await q.replace(e,t,i,d);return}throw new S("NOT_FOUND",`document not found: ${t}`)}const{docJson:p,row:f,tableName:h}=w,$=l.tables[h];if(!$)throw new S("INTERNAL",`unknown table: ${h}`);un("replace",i);const v=d?.allowExplicitId&&typeof i._creationTime=="number"?i._creationTime:void 0,b=typeof f._creationTime=="number"?f._creationTime:void 0,_=v??b??Ee(),A={...i,...ee(h),_creationTime:_,_id:t};ft($,i,A,ce);const M=d?.allowExplicitId===!0,E=je($,A,{previous:()=>f,supplied:i,trusted:M});ne(h,"before","update")&&await oe("before","update",{doc:{...E},id:t,op:"update",previous:f,table:h}),M||B(h,E,f),Re(h),ve(h),Ne(y,h,fr(h),[_,le(E),t,p]),Fe(h,t,E,f),Le(h,t,E),ke(h,f,E),Te(h,t,f,E),$e?.invalidate(h,t,N(h,f,E)),Se(h,t,"update",E),D({indexKeys:N(h,f,E),key:t,op:"update",row:E,table:h}),ne(h,"after","update")&&await oe("after","update",{doc:E,id:t,op:"update",previous:f,table:h}),await ye({doc:E,id:t,op:"update",table:h})},async wipeShard(e){const t=new Set(e?.exclude),i=e?.tables,d=Object.entries(l.tables).filter(([h,$])=>t.has(h)||i!==void 0&&!i.includes(h)?!1:$.shardMode?.kind!=="global").map(([h])=>h);if(i!==void 0){for(const h of i)if(!l.tables[h])throw new S("INTERNAL",`wipeShard: unknown table: ${h}`)}const w={};let p=0;const{deleteAll:f}=O;if(f===void 0)throw new S("INTERNAL","wipeShard: this writer has no deleteAll");for(const h of d){const $=await f(h,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});w[h]=$.deleted,p+=$.deleted}return{deleted:p,tables:w}}},Wn={db:O,scheduler:vt};return n.enforceRls===!0?Uo(O,l,(e,t)=>re(e,t)?.tableName,T):O};export{Oi as CDC_LOG_TABLE,ds as IDEMPOTENCY_TABLE,Dr as NotUniqueError,is as advanceClientWatermark,ji as applyCdcChanges,un as assertNoExplicitUndefined,$t as assertStorableRowId,Er as assertValidClientId,Bi as backfillAggregateIndexes,qi as backfillRankIndexes,Pi as backfillSearchIndexes,Gi as bumpCdcEpoch,Hi as cdcCanVouchFor,Ki as cdcForkedError,Ni as cdcSeqLeavingRows,Qi as cdcTouchesTables,Vi as cdcTrimmedError,Ji as compactCdcDocs,Jr as createShardCtxDb,zi as cursorBelowRetainedFloor,Gr as meterReadBytes,ss as migrateClientWatermark,Yi as minCdcReplayableSeq,Xi as minCdcSeq,dn as normalizeIdStructurally,Zi as readCdcChangeKeys,es as readCdcChanges,ts as readCdcCursor,ns as readCdcEpoch,cs as readClientWatermark,ls as readIdempotent,ws as runShardMigrations,gs as selectShapeMembers,ys as selectShapeRows,Ke as stripReservedPatchFields,os as trimCdcChanges,us as trimIdempotent,fs as writeIdempotent};
|