@lunora/shard-engine 1.0.0-alpha.205 → 1.0.0-alpha.207
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/{CompanionMemo-BXU5vfak.mjs → CompanionMemo-jmlDbPlr.mjs} +1 -1
- package/dist/packem_shared/NotUniqueError-oaot-97D.mjs +1 -0
- package/dist/packem_shared/{VECTOR_BACKFILL_MAX_PAGES-DJ6iD61G.mjs → VECTOR_BACKFILL_MAX_PAGES-CTKYW2J5.mjs} +1 -1
- package/dist/packem_shared/{backfillAggregateIndexes-BwCpPW7h.mjs → backfillAggregateIndexes-DNVOUEEW.mjs} +1 -1
- package/dist/packem_shared/createCompanionSync-C7nzg7f-.mjs +1 -0
- package/dist/packem_shared/{defineEngineContractSuite-RbBg22Du.mjs → defineEngineContractSuite-RRe7_XDm.mjs} +1 -1
- package/dist/packem_shared/{runShardMigrations-Bc7PsQhM.mjs → runShardMigrations-DBkimnd5.mjs} +1 -1
- package/package.json +1 -1
- package/dist/packem_shared/NotUniqueError-Yot9wmNo.mjs +0 -1
- package/dist/packem_shared/createCompanionSync-DO92CQek.mjs +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite-
|
|
1
|
+
import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite-RRe7_XDm.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,replaceRefusal as i,selectExportTables as n,validateImportRow as l}from"./packem_shared/exportShardRows-BEzRTBwD.mjs";import{adminTokenExists as m,createAdminTokenRecord as c,listAdminTokens as p,revokeAdminTokenRecord as S,verifyAdminTokenDigest as u}from"./packem_shared/adminTokenExists-CQ0qedmu.mjs";import{AGGREGATE_SQL_FUNCTION as T,aggregateSqlFunction as E,matchesStaticWhere as x,normalizeCountArgument as h,throwingScheduler as R}from"./packem_shared/AGGREGATE_SQL_FUNCTION-C_ZipS9R.mjs";import{aggregateTableName as I,coerceAggregateNumber as g,encodeAggregateKey as C,foldAggregateTally as _,readAggregateValue as b}from"./packem_shared/aggregateTableName-B_CtIQCS.mjs";import{CountRlsUnsupportedError as D,mergeWhere as O,planAggregateLookup as M,selectIndexForAggregate as P,selectIndexForCount as y,selectIndexForGroupBy as F}from"./packem_shared/CountRlsUnsupportedError-BvsDqfO2.mjs";import{AUDIT_LOG_TABLE as N,appendAuditEntry as B,ensureAuditTable as U,readAuditLog as w}from"./packem_shared/AUDIT_LOG_TABLE-BFJ65SRS.mjs";import{NotUniqueError as v,assertNoExplicitUndefined as q,assertStorableRowId as K,assertValidClientId as W,createShardCtxDb as H,normalizeIdStructurally as X,stripReservedPatchFields as V}from"./packem_shared/NotUniqueError-Yot9wmNo.mjs";import{backfillAggregateIndexes as Q,backfillRankIndexes as Y,backfillSearchIndexes as j,backfillSearchIndexesForTable as J}from"./packem_shared/backfillAggregateIndexes-BwCpPW7h.mjs";import{CDC_LOG_TABLE as $,CDC_LOG_TABLE_SEQ_INDEX as ee,CDC_META_TABLE as re,appendCdcChange as oe,applyCdcChanges as ae,bumpCdcEpoch as te,cdcCanVouchFor as se,cdcForkedError as ie,cdcSeqLeavingRows as ne,cdcTouchesTables as le,cdcTrimmedError as de,compactCdcDocs as me,cursorBelowRetainedFloor as ce,migrateCdcLog as pe,migrateCdcMeta as Se,minCdcReplayableSeq as ue,minCdcSeq as fe,readCdcChangeKeys as Te,readCdcChanges as Ee,readCdcCursor as xe,readCdcEpoch as he,trimCdcChanges as Re}from"./packem_shared/CDC_LOG_TABLE-BFGgqai8.mjs";import{archiveCdcSegment as Ie,cdcArchiveRewound as ge,readArchivedCdcChanges as Ce,readCdcArchivedThrough as _e,writeCdcArchivedThrough as be}from"./packem_shared/archiveCdcSegment-Cr8oGLfB.mjs";import{CLIENT_WATERMARK_TABLE as De,advanceClientWatermark as Oe,migrateClientWatermark as Me,readClientWatermark as Pe}from"./packem_shared/CLIENT_WATERMARK_TABLE-De7z_OHV.mjs";import{COMMIT_SEQ_FIELD as Fe,COMMIT_SEQ_TABLE as ke,allocateCommitSeq as Ne,migrateCommitSeq as Be,readCommitSeq as Ue}from"./packem_shared/COMMIT_SEQ_FIELD-Da1DjGqo.mjs";import{CompanionMemo as Ge,clearCompanionSignatures as ve}from"./packem_shared/CompanionMemo-BXU5vfak.mjs";import{createCompanionSync as Ke}from"./packem_shared/createCompanionSync-DO92CQek.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as He,deleteGlobalShapeSnapshot as Xe,deleteGlobalShapeSnapshotsForConnection as Ve,migrateGlobalShapeSnapshot as ze,readGlobalShapeSnapshot as Qe,writeGlobalShapeSnapshot as Ye}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-Bb6-aZuH.mjs";import{IDEMPOTENCY_TABLE as Je,migrateIdempotency as Ze,readIdempotent as $e,trimIdempotent as er,writeIdempotent as rr}from"./packem_shared/IDEMPOTENCY_TABLE-COrgeP3O.mjs";import{clearMemoryTables as ar,isMemoryTable as tr,memoryTableNames as sr}from"./packem_shared/clearMemoryTables-aMRERF0w.mjs";import{computeRankPage as nr,resolveRankSeekTuple as lr}from"./packem_shared/computeRankPage-B6umzbg4.mjs";import{SCHEDULE_OUTBOX_TABLE as mr,deferScheduleOutbox as cr,dropScheduleOutbox as pr,forgetScheduleOutbox as Sr,hasScheduleOutboxEntry as ur,migrateScheduleOutbox as fr,parkScheduleOutbox as Tr,probeScheduleOutbox as Er,readDueScheduleOutbox as xr,readDueScheduleOutboxEntry as hr,readScheduleOutbox as Rr,readScheduleOutboxState as Ar,recordScheduleOutbox as Ir,requeueScheduleOutbox as gr,trimScheduleOutbox as Cr}from"./packem_shared/SCHEDULE_OUTBOX_TABLE-iyyiSjsO.mjs";import{S as br,m as Lr,r as Dr,w as Or}from"./packem_shared/ctx-db-search-state-CPKPy8N6.mjs";import{SHAPE_POKE_CURSOR_TABLE as Pr,deleteShapePokeCursor as yr,deleteShapePokeCursorsForConnection as Fr,migrateShapePokeCursor as kr,minShapePokeCursor as Nr,readShapePokeCursor as Br,writeShapePokeCursor as Ur,writeShapePokeCursors as wr}from"./packem_shared/SHAPE_POKE_CURSOR_TABLE-BGvY3sFI.mjs";import{selectShapeMembers as vr,selectShapeRows as qr}from"./packem_shared/selectShapeMembers-Dqx_m7BF.mjs";import{DATA_MIGRATION_STATE_TABLE as Wr,readMigrationStatus as Hr,runDataMigration as Xr}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-CPWZjliE.mjs";import{SCAN_DEP as zr,createDependencyTracker as Qr,depKey as Yr,tableFromDepKey as jr}from"./packem_shared/SCAN_DEP-B4Uu4g7l.mjs";import{runDrizzle as Zr,runSql as $r}from"./packem_shared/runDrizzle-RC09zZrh.mjs";import{A as ro,a as oo,b as ao,D as to,c as so,d as io,g as no,i as lo,j as mo,e as co,q as po,f as So,r as uo,t as fo,h as To}from"./packem_shared/do-sql-105TONaE.mjs";import{WORKERD_SQLITE_LIMITS as xo,param as ho,renderSql as Ro,sqliteInList as Ao,unionAll as Io}from"./packem_shared/WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{appendStreamChunk as Co,claimStreamRun as _o,deleteStreamRun as bo,finishStreamRun as Lo,migrateDurableStreams as Do,readStreamChunks as Oo,readStreamRun as Mo,trimStreamRuns as Po}from"./packem_shared/appendStreamChunk-BZYgGE9Y.mjs";import{DurableStreamRunner as Fo,MAX_DURABLE_STREAM_BYTES as ko,MAX_DURABLE_STREAM_CHUNKS as No,decideDurableAttach as Bo}from"./packem_shared/DurableStreamRunner-MMlV5qKQ.mjs";import{envOptionalPositiveInt as wo,envPositiveInt as Go}from"./packem_shared/envOptionalPositiveInt-D2pY-c64.mjs";import{diffExternalSource as qo}from"./packem_shared/diffExternalSource-B0FZlDoL.mjs";import{liftSourceId as Wo,normalizeSourceDocument as Ho,normalizeSourceValue as Xo}from"./packem_shared/liftSourceId-CA3ENhXj.mjs";import{materializeExternalRows as zo,materializeExternalRowsIncremental as Qo,readExternalSourceBaseline as Yo,runExternalSourceTick as jo}from"./packem_shared/materializeExternalRows-CHPRx8fu.mjs";import{isSoftDeleted as Zo,isSourceDue as $o,pullExternalSourceIncrementalTick as ea,pullExternalSourceTick as ra}from"./packem_shared/isSoftDeleted-BBWKE0Sm.mjs";import{f as aa,a as ta,b as sa,c as ia,d as na,g as la}from"./packem_shared/fts-companion-CE3EmIjk.mjs";import{GEO_DEFAULT_PRECISION as ma,boundingBoxCenter as ca,boundingBoxGeohashes as pa,coveringGeohashes as Sa,encodeGeohash as ua,haversineMeters as fa,pointInBoundingBox as Ta}from"./packem_shared/GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{default as xa}from"./packem_shared/GlobalPollTick-BNK4o-XT.mjs";import{IMPORT_MANIFEST_TTL_MS as Ra,IMPORT_STAGE_TTL_MS as Aa,advanceImportManifest as Ia,assertImportSessionId as ga,dropImportManifest as Ca,dropImportSession as _a,markShardImportCommitted as ba,readImportManifest as La,readShardImportSession as Da,stageImportRows as Oa,stagedImportIds as Ma,stagedImportPage as Pa,sweepImportStaging as ya,touchImportManifest as Fa,touchShardImportSession as ka}from"./packem_shared/IMPORT_MANIFEST_TTL_MS-BrNT0vUO.mjs";import{ADMIN_FUNCTIONS as Ba,ADMIN_FUNCTION_PREFIX as Ua,DEFAULT_FANOUT_TOPIC_LIMIT as wa,FLAGS_FUNCTION_PREFIX as Ga,MAX_PAGE_SIZE as va,RELATION_FUNCTION_PREFIX as qa,createFanoutCounters as Ka,createGlobalPollCounters as Wa,createShapeProbeCounters as Ha,facetColumn as Xa,findStorageReferences as Va,isVacuousFilterClause as za,listTables as Qa,readTablePage as Ya,recordFanoutPass as ja,recordGlobalPollPass as Ja,recordShapeProbePass as Za,selectMatchingIds as $a,summarizeFanoutTopics as et,summarizeSubscriptions as rt}from"./packem_shared/ADMIN_FUNCTIONS-CfHGnLsC.mjs";import{MAIL_RETENTION as at,MAIL_TABLE as tt,clearCapturedMail as st,ensureMailTable as it,readCapturedMail as nt,recordCapturedMail as lt}from"./packem_shared/MAIL_RETENTION-DMolrLYt.mjs";import{NotFoundError as mt}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{assertPatchAllowed as pt,operatorFields as St,patchDependsOnRow as ut,readPatchField as ft,resolvePatch as Tt}from"./packem_shared/assertPatchAllowed-CA_H466g.mjs";import{armRestore as xt,readBookmark as ht}from"./packem_shared/armRestore-Bu1_8SUa.mjs";import{CURSOR_PREFIX as At,applySelect as It,buildSeekBeforeWhere as gt,buildSeekWhere as Ct,decodeCursor as _t,encodeCursor as bt,equalityPinnedFields as Lt,normalizeOrderKeys as Dt,nullsFirstOf as Ot,nullsOrderSuffix as Mt,softDeleteScope as Pt,tiebreakDirectionFor as yt,uniqueIndexFields as Ft}from"./packem_shared/CURSOR_PREFIX-rOdoinP8.mjs";import{QUEUE_TABLE as Nt,clearQueueMessages as Bt,isLossyBody as Ut,readQueueMessageById as wt,readQueueMessages as Gt,recordQueueMessages as vt}from"./packem_shared/QUEUE_TABLE-C-goXtGd.mjs";import{RANK_TIEBREAK as Kt,encodePartitionKey as Wt,matchesRankStaticWhere as Ht,rankKeyFromDoc as Xt,rankPivotConditionSql as Vt,rankTableName as zt,resolveRankPartition as Qt,sortColumnName as Yt}from"./packem_shared/RANK_TIEBREAK-D3ye2GsL.mjs";import{ReactiveCache as Jt,reactiveCacheKey as Zt}from"./packem_shared/ReactiveCache-BG9z3FE9.mjs";import{REACTOR_STATE_TABLE as es,listReactorStates as rs,migrateReactorState as os,reactorNeedsRun as as,readReactorState as ts,writeReactorState as ss}from"./packem_shared/REACTOR_STATE_TABLE-D2Mn204f.mjs";import{ADMIN_WILDCARD as ns,UNVOUCHABLE_DEP as ls,createReadFootprint as ds,markUnvouchableReads as ms}from"./packem_shared/ADMIN_WILDCARD-BUrgWQ3-.mjs";import{buildIndexRange as ps,indexKeysForRow as Ss,keysTouchRanges as us}from"./packem_shared/buildIndexRange-BTChxh3k.mjs";import{isPushableWhere as Ts,whereFilter as Es,whereOfFilter as xs}from"./packem_shared/isPushableWhere-BeYAOjUb.mjs";import{RELATED_DEFAULT_LIMIT as Rs,RELATED_DEPTH_DECAY as As,RELATED_MAX_DEPTH as Is,RELATED_MAX_LIMIT as gs,deriveRelationEdges as Cs,findRelated as _s}from"./packem_shared/RELATED_DEFAULT_LIMIT-CAh3WUMn.mjs";import{DEFAULT_MAX_RELATION_KEYS as Ls,assertFlatPredicate as Ds,assertShapeShardable as Os,composeReadPredicate as Ms,containsRelationPredicate as Ps,findManyPage as ys,isRelationPredicate as Fs,resolveRelationPredicates as ks}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-Crb9ZWeI.mjs";import{describeRelationWrites as Bs}from"./packem_shared/describeRelationWrites-omar6-u9.mjs";import{applyInsertDefaults as ws,applyOnDelete as Gs,distinctValues as vs,fanOutScalarCounts as qs,relationHooks as Ks,resolveWith as Ws,runRowValidators as Hs}from"./packem_shared/applyInsertDefaults-80S3Pm2_.mjs";import{D as Vs,c as zs,n as Qs,r as Ys,s as js}from"./packem_shared/relay-CKEdfUjH.mjs";import{DEFAULT_MAX_RELAYS as Zs,OwnerRelay as $s,RelayMember as ei,createRelayLink as ri}from"./packem_shared/DEFAULT_MAX_RELAYS-BZLpaaq1.mjs";import{createReplicaLink as ai,gateReplicaDispatch as ti,handleReplicaControl as si}from"./packem_shared/createReplicaLink-DtqXBi-0.mjs";import{buildReprojectionMigration as ni,countLegacyRows as li,reprojectableFields as di,reprojectionTables as mi}from"./packem_shared/buildReprojectionMigration-B8aEpETD.mjs";import{RLS_UNWRAP_SYMBOL as pi,RlsRequiredError as Si,guardWriter as ui}from"./packem_shared/RLS_UNWRAP_SYMBOL-CWo1Bk9y.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as Ti,readSchemaHistory as Ei,readSchemaVersion as xi,recordSchemaVersion as hi}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-CEwFjj-O.mjs";import{serializeSqlValue as Ai}from"./packem_shared/serializeSqlValue-DeoBMpZ2.mjs";import{buildSettings as gi,isDevEnvironment as Ci,readDeployInfo as _i}from"./packem_shared/buildSettings-CFkvTaHx.mjs";import{buildShapeDiff as Li}from"./packem_shared/buildShapeDiff-CdLJTijm.mjs";import{ShapeDiffCache as Oi,createShapeDiffCache as Mi,globalShapeReadKey as Pi}from"./packem_shared/ShapeDiffCache-iNO-hUiy.mjs";import{buildPokeFrames as Fi,diffGlobalMembership as ki,encodeRowsPatch as Ni,projectColumns as Bi}from"./packem_shared/buildPokeFrames-WR-hp0mX.mjs";import{ShardRunner as wi}from"./packem_shared/ShardRunner-CrveaPId.mjs";import{stubByName as vi}from"./packem_shared/stubByName-DQSivmvb.mjs";import{runSocketPool as Ki}from"./packem_shared/runSocketPool-CZJ2X9cF.mjs";import{MAX_SQL_ROWS as Hi,assertReadonly as Xi,lintReadonlySql as Vi,runReadonlySql as zi}from"./packem_shared/MAX_SQL_ROWS-B4WlVI-e.mjs";import{BIGINT_KEY_DIGITS as Yi,bigintSqlKey as ji,decodeBigintSqlKey as Ji,decodeFloat64SqlKey as Zi,float64SqlKey as $i}from"./packem_shared/BIGINT_KEY_DIGITS-DE6yshOt.mjs";import{DELTA_PLACEHOLDER_TABLE as rn,awaitWsDrain as on,deltaTableFor as an,subscriptionFrames as tn,subscriptionListDeltas as sn,trySendFrame as nn}from"./packem_shared/DELTA_PLACEHOLDER_TABLE-CHxtV9xh.mjs";import{mergeChangedKeys as dn,recordChangedKeys as mn,writeTouchesMemo as cn}from"./packem_shared/mergeChangedKeys-DPKhen6e.mjs";import{createSystemReader as Sn}from"./packem_shared/createSystemReader-BSCxr8Qs.mjs";import{ConflictError as fn}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as En,TransactionHeadroomTracker as xn}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS-D7p7Ys0M.mjs";import{hasTrigger as Rn,runTriggers as An}from"./packem_shared/hasTrigger-CjlwI4le.mjs";import{isTtlExpired as gn,nextTtlExpiry as Cn,selectExpiredIds as _n}from"./packem_shared/isTtlExpired-DNxmZA6e.mjs";import{VECTOR_BACKFILL_MAX_PAGES as Ln,backfillVectorIndexes as Dn}from"./packem_shared/VECTOR_BACKFILL_MAX_PAGES-DJ6iD61G.mjs";import{c as Mn,s as Pn}from"./packem_shared/where-sql-BjY4rnqb.mjs";import{RELATION_EXISTS_KEY as Fn}from"./packem_shared/RELATION_EXISTS_KEY-wxgj6rSL.mjs";import{ADMIN_TOKEN_TABLE as Nn}from"./packem_shared/ADMIN_TOKEN_TABLE-DfQ5osdI.mjs";import{RELAY_SIGNATURE_HEADER as Un,siblingSecretOf as wn,signSiblingBody as Gn,verifySiblingBody as vn}from"./packem_shared/RELAY_SIGNATURE_HEADER-CAfC4tqg.mjs";import{REPROJECTION_MIGRATION_PREFIX as Kn,reprojectionMigrationId as Wn}from"./packem_shared/REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{isInternalTableName as Xn}from"./packem_shared/isInternalTableName-BoljO2tP.mjs";import{quoteIdentifier as zn}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as Yn}from"./packem_shared/runShardMigrations-Bc7PsQhM.mjs";import{stableStringify as Jn,stableWireKey as Zn}from"@lunora/wire";export{Ba as ADMIN_FUNCTIONS,Ua as ADMIN_FUNCTION_PREFIX,Nn as ADMIN_TOKEN_TABLE,ns as ADMIN_WILDCARD,T as AGGREGATE_SQL_FUNCTION,ro as AGG_COUNT,oo as AGG_KEY,ao as AGG_VALUE,N as AUDIT_LOG_TABLE,Yi as BIGINT_KEY_DIGITS,$ as CDC_LOG_TABLE,ee as CDC_LOG_TABLE_SEQ_INDEX,re as CDC_META_TABLE,De as CLIENT_WATERMARK_TABLE,Fe as COMMIT_SEQ_FIELD,ke as COMMIT_SEQ_TABLE,At as CURSOR_PREFIX,Ge as CompanionMemo,fn as ConflictError,D as CountRlsUnsupportedError,Wr as DATA_MIGRATION_STATE_TABLE,wa as DEFAULT_FANOUT_TOPIC_LIMIT,Ls as DEFAULT_MAX_RELATION_KEYS,Zs as DEFAULT_MAX_RELAYS,Vs as DEFAULT_PROMOTION_THRESHOLDS,En as DEFAULT_TRANSACTION_LIMITS,rn as DELTA_PLACEHOLDER_TABLE,to as DOC_COLUMN,Fo as DurableStreamRunner,Ga as FLAGS_FUNCTION_PREFIX,ma as GEO_DEFAULT_PRECISION,He as GLOBAL_SHAPE_SNAPSHOT_TABLE,xa as GlobalPollTick,Je as IDEMPOTENCY_TABLE,Ra as IMPORT_MANIFEST_TTL_MS,Aa as IMPORT_STAGE_TTL_MS,at as MAIL_RETENTION,tt as MAIL_TABLE,ko as MAX_DURABLE_STREAM_BYTES,No as MAX_DURABLE_STREAM_CHUNKS,va as MAX_PAGE_SIZE,Hi as MAX_SQL_ROWS,mt as NotFoundError,v as NotUniqueError,$s as OwnerRelay,Nt as QUEUE_TABLE,Kt as RANK_TIEBREAK,es as REACTOR_STATE_TABLE,Rs as RELATED_DEFAULT_LIMIT,As as RELATED_DEPTH_DECAY,Is as RELATED_MAX_DEPTH,gs as RELATED_MAX_LIMIT,Fn as RELATION_EXISTS_KEY,qa as RELATION_FUNCTION_PREFIX,Un as RELAY_SIGNATURE_HEADER,Kn as REPROJECTION_MIGRATION_PREFIX,pi as RLS_UNWRAP_SYMBOL,Jt as ReactiveCache,ei as RelayMember,Si as RlsRequiredError,zr as SCAN_DEP,mr as SCHEDULE_OUTBOX_TABLE,Ti as SCHEMA_HISTORY_MAX_VERSIONS,br as SEARCH_STATE_TABLE,Pr as SHAPE_POKE_CURSOR_TABLE,Oi as ShapeDiffCache,wi as ShardRunner,xn as TransactionHeadroomTracker,ls as UNVOUCHABLE_DEP,Ln as VECTOR_BACKFILL_MAX_PAGES,xo as WORKERD_SQLITE_LIMITS,m as adminTokenExists,Oe as advanceClientWatermark,Ia as advanceImportManifest,so as aggUpsertSql,E as aggregateSqlFunction,I as aggregateTableName,Ne as allocateCommitSeq,B as appendAuditEntry,oe as appendCdcChange,Co as appendStreamChunk,ae as applyCdcChanges,ws as applyInsertDefaults,Gs as applyOnDelete,It as applySelect,Ie as archiveCdcSegment,xt as armRestore,Ds as assertFlatPredicate,ga as assertImportSessionId,q as assertNoExplicitUndefined,pt as assertPatchAllowed,Xi as assertReadonly,Os as assertShapeShardable,K as assertStorableRowId,W as assertValidClientId,on as awaitWsDrain,Q as backfillAggregateIndexes,Y as backfillRankIndexes,j as backfillSearchIndexes,J as backfillSearchIndexesForTable,Dn as backfillVectorIndexes,ji as bigintSqlKey,ca as boundingBoxCenter,pa as boundingBoxGeohashes,ps as buildIndexRange,Fi as buildPokeFrames,ni as buildReprojectionMigration,gt as buildSeekBeforeWhere,Ct as buildSeekWhere,gi as buildSettings,Li as buildShapeDiff,te as bumpCdcEpoch,ge as cdcArchiveRewound,se as cdcCanVouchFor,ie as cdcForkedError,ne as cdcSeqLeavingRows,le as cdcTouchesTables,de as cdcTrimmedError,_o as claimStreamRun,zs as clampPromotionThresholds,st as clearCapturedMail,ve as clearCompanionSignatures,ar as clearMemoryTables,Bt as clearQueueMessages,g as coerceAggregateNumber,me as compactCdcDocs,Mn as compileWhereSql,Ms as composeReadPredicate,nr as computeRankPage,Ps as containsRelationPredicate,li as countLegacyRows,Sa as coveringGeohashes,c as createAdminTokenRecord,Ke as createCompanionSync,Qr as createDependencyTracker,Ka as createFanoutCounters,Wa as createGlobalPollCounters,io as createIndexSql,ds as createReadFootprint,ri as createRelayLink,ai as createReplicaLink,Mi as createShapeDiffCache,Ha as createShapeProbeCounters,H as createShardCtxDb,Sn as createSystemReader,ce as cursorBelowRetainedFloor,Bo as decideDurableAttach,Ji as decodeBigintSqlKey,_t as decodeCursor,Zi as decodeFloat64SqlKey,cr as deferScheduleOutbox,Xe as deleteGlobalShapeSnapshot,Ve as deleteGlobalShapeSnapshotsForConnection,yr as deleteShapePokeCursor,Fr as deleteShapePokeCursorsForConnection,bo as deleteStreamRun,an as deltaTableFor,Yr as depKey,Cs as deriveRelationEdges,Bs as describeRelationWrites,qo as diffExternalSource,ki as diffGlobalMembership,vs as distinctValues,Ca as dropImportManifest,_a as dropImportSession,pr as dropScheduleOutbox,C as encodeAggregateKey,bt as encodeCursor,ua as encodeGeohash,Wt as encodePartitionKey,Ni as encodeRowsPatch,U as ensureAuditTable,it as ensureMailTable,wo as envOptionalPositiveInt,Go as envPositiveInt,Lt as equalityPinnedFields,o as exportShardRows,Xa as facetColumn,qs as fanOutScalarCounts,ys as findManyPage,_s as findRelated,Va as findStorageReferences,Lo as finishStreamRun,$i as float64SqlKey,_ as foldAggregateTally,Sr as forgetScheduleOutbox,aa as ftsCompanionDdl,ta as ftsPurgeDocument,sa as ftsRowidMapName,ia as ftsUnmappedPage,na as ftsWriteDocument,ti as gateReplicaDispatch,no as geoTableName,Pi as globalShapeReadKey,la as groupUnmappedRows,ui as guardWriter,si as handleReplicaControl,ur as hasScheduleOutboxEntry,Rn as hasTrigger,fa as haversineMeters,a as importShardRows,Ss as indexKeysForRow,Ci as isDevEnvironment,lo as isFtsAvailable,Xn as isInternalTableName,Ut as isLossyBody,tr as isMemoryTable,Ts as isPushableWhere,Fs as isRelationPredicate,Zo as isSoftDeleted,$o as isSourceDue,gn as isTtlExpired,za as isVacuousFilterClause,mo as jsonPath,co as jsonPathSql,us as keysTouchRanges,Wo as liftSourceId,Vi as lintReadonlySql,p as listAdminTokens,rs as listReactorStates,Qa as listTables,ba as markShardImportCommitted,ms as markUnvouchableReads,Ht as matchesRankStaticWhere,x as matchesStaticWhere,zo as materializeExternalRows,Qo as materializeExternalRowsIncremental,sr as memoryTableNames,dn as mergeChangedKeys,O as mergeWhere,pe as migrateCdcLog,Se as migrateCdcMeta,Me as migrateClientWatermark,Be as migrateCommitSeq,Do as migrateDurableStreams,ze as migrateGlobalShapeSnapshot,Ze as migrateIdempotency,os as migrateReactorState,fr as migrateScheduleOutbox,Lr as migrateSearchState,kr as migrateShapePokeCursor,ue as minCdcReplayableSeq,fe as minCdcSeq,Nr as minShapePokeCursor,Qs as nextPromotionState,Cn as nextTtlExpiry,h as normalizeCountArgument,X as normalizeIdStructurally,Dt as normalizeOrderKeys,Ho as normalizeSourceDocument,Xo as normalizeSourceValue,Ot as nullsFirstOf,Mt as nullsOrderSuffix,St as operatorFields,ho as param,Tr as parkScheduleOutbox,t as parseExportShardArgs,s as parseImportShardArgs,ut as patchDependsOnRow,M as planAggregateLookup,Ta as pointInBoundingBox,Er as probeScheduleOutbox,Bi as projectColumns,ea as pullExternalSourceIncrementalTick,ra as pullExternalSourceTick,po as qualifiedJsonPath,So as qualifiedJsonPathSql,zn as quoteIdentifier,Xt as rankKeyFromDoc,Vt as rankPivotConditionSql,zt as rankTableName,Zt as reactiveCacheKey,as as reactorNeedsRun,b as readAggregateValue,Ce as readArchivedCdcChanges,w as readAuditLog,ht as readBookmark,nt as readCapturedMail,_e as readCdcArchivedThrough,Te as readCdcChangeKeys,Ee as readCdcChanges,xe as readCdcCursor,he as readCdcEpoch,Pe as readClientWatermark,Ue as readCommitSeq,_i as readDeployInfo,xr as readDueScheduleOutbox,hr as readDueScheduleOutboxEntry,Yo as readExternalSourceBaseline,Qe as readGlobalShapeSnapshot,$e as readIdempotent,La as readImportManifest,Hr as readMigrationStatus,ft as readPatchField,wt as readQueueMessageById,Gt as readQueueMessages,ts as readReactorState,Rr as readScheduleOutbox,Ar as readScheduleOutboxState,Ei as readSchemaHistory,xi as readSchemaVersion,Dr as readSearchBackfillState,Br as readShapePokeCursor,Da as readShardImportSession,Oo as readStreamChunks,Mo as readStreamRun,Ya as readTablePage,lt as recordCapturedMail,mn as recordChangedKeys,ja as recordFanoutPass,Ja as recordGlobalPollPass,vt as recordQueueMessages,Ir as recordScheduleOutbox,hi as recordSchemaVersion,Za as recordShapeProbePass,Ks as relationHooks,Ys as relayCountFor,Ro as renderSql,i as replaceRefusal,di as reprojectableFields,Wn as reprojectionMigrationId,mi as reprojectionTables,gr as requeueScheduleOutbox,Tt as resolvePatch,Qt as resolveRankPartition,lr as resolveRankSeekTuple,ks as resolveRelationPredicates,Ws as resolveWith,S as revokeAdminTokenRecord,uo as rowToDocument,Xr as runDataMigration,Zr as runDrizzle,jo as runExternalSourceTick,zi as runReadonlySql,Hs as runRowValidators,Yn as runShardMigrations,Ki as runSocketPool,$r as runSql,An as runTriggers,_n as selectExpiredIds,n as selectExportTables,P as selectIndexForAggregate,y as selectIndexForCount,F as selectIndexForGroupBy,$a as selectMatchingIds,vr as selectShapeMembers,qr as selectShapeRows,Ai as serializeSqlValue,Pn as serverInList,js as shapeRoutingKey,wn as siblingSecretOf,Gn as signSiblingBody,Pt as softDeleteScope,Yt as sortColumnName,Ao as sqliteInList,Jn as stableStringify,Zn as stableWireKey,Oa as stageImportRows,Ma as stagedImportIds,Pa as stagedImportPage,V as stripReservedPatchFields,vi as stubByName,tn as subscriptionFrames,sn as subscriptionListDeltas,et as summarizeFanoutTopics,rt as summarizeSubscriptions,ya as sweepImportStaging,fo as tableColumns,jr as tableFromDepKey,R as throwingScheduler,yt as tiebreakDirectionFor,Fa as touchImportManifest,ka as touchShardImportSession,Re as trimCdcChanges,er as trimIdempotent,Cr as trimScheduleOutbox,Po as trimStreamRuns,To as tryRowToDocument,nn as trySendFrame,Io as unionAll,Ft as uniqueIndexFields,l as validateImportRow,u as verifyAdminTokenDigest,vn as verifySiblingBody,Es as whereFilter,xs as whereOfFilter,be as writeCdcArchivedThrough,Ye as writeGlobalShapeSnapshot,rr as writeIdempotent,ss as writeReactorState,Or as writeSearchBackfillState,Ur as writeShapePokeCursor,wr as writeShapePokeCursors,cn as writeTouchesMemo};
|
|
1
|
+
import{exportShardRows as o,importShardRows as a,parseExportShardArgs as t,parseImportShardArgs as s,replaceRefusal as i,selectExportTables as n,validateImportRow as l}from"./packem_shared/exportShardRows-BEzRTBwD.mjs";import{adminTokenExists as m,createAdminTokenRecord as c,listAdminTokens as p,revokeAdminTokenRecord as S,verifyAdminTokenDigest as u}from"./packem_shared/adminTokenExists-CQ0qedmu.mjs";import{AGGREGATE_SQL_FUNCTION as T,aggregateSqlFunction as E,matchesStaticWhere as x,normalizeCountArgument as h,throwingScheduler as R}from"./packem_shared/AGGREGATE_SQL_FUNCTION-C_ZipS9R.mjs";import{aggregateTableName as I,coerceAggregateNumber as g,encodeAggregateKey as C,foldAggregateTally as _,readAggregateValue as b}from"./packem_shared/aggregateTableName-B_CtIQCS.mjs";import{CountRlsUnsupportedError as D,mergeWhere as O,planAggregateLookup as M,selectIndexForAggregate as P,selectIndexForCount as y,selectIndexForGroupBy as F}from"./packem_shared/CountRlsUnsupportedError-BvsDqfO2.mjs";import{AUDIT_LOG_TABLE as N,appendAuditEntry as B,ensureAuditTable as U,readAuditLog as w}from"./packem_shared/AUDIT_LOG_TABLE-BFJ65SRS.mjs";import{NotUniqueError as v,assertNoExplicitUndefined as q,assertStorableRowId as K,assertValidClientId as W,createShardCtxDb as H,normalizeIdStructurally as X,stripReservedPatchFields as V}from"./packem_shared/NotUniqueError-oaot-97D.mjs";import{backfillAggregateIndexes as Q,backfillRankIndexes as Y,backfillSearchIndexes as j,backfillSearchIndexesForTable as J}from"./packem_shared/backfillAggregateIndexes-DNVOUEEW.mjs";import{CDC_LOG_TABLE as $,CDC_LOG_TABLE_SEQ_INDEX as ee,CDC_META_TABLE as re,appendCdcChange as oe,applyCdcChanges as ae,bumpCdcEpoch as te,cdcCanVouchFor as se,cdcForkedError as ie,cdcSeqLeavingRows as ne,cdcTouchesTables as le,cdcTrimmedError as de,compactCdcDocs as me,cursorBelowRetainedFloor as ce,migrateCdcLog as pe,migrateCdcMeta as Se,minCdcReplayableSeq as ue,minCdcSeq as fe,readCdcChangeKeys as Te,readCdcChanges as Ee,readCdcCursor as xe,readCdcEpoch as he,trimCdcChanges as Re}from"./packem_shared/CDC_LOG_TABLE-BFGgqai8.mjs";import{archiveCdcSegment as Ie,cdcArchiveRewound as ge,readArchivedCdcChanges as Ce,readCdcArchivedThrough as _e,writeCdcArchivedThrough as be}from"./packem_shared/archiveCdcSegment-Cr8oGLfB.mjs";import{CLIENT_WATERMARK_TABLE as De,advanceClientWatermark as Oe,migrateClientWatermark as Me,readClientWatermark as Pe}from"./packem_shared/CLIENT_WATERMARK_TABLE-De7z_OHV.mjs";import{COMMIT_SEQ_FIELD as Fe,COMMIT_SEQ_TABLE as ke,allocateCommitSeq as Ne,migrateCommitSeq as Be,readCommitSeq as Ue}from"./packem_shared/COMMIT_SEQ_FIELD-Da1DjGqo.mjs";import{CompanionMemo as Ge,clearCompanionSignatures as ve}from"./packem_shared/CompanionMemo-jmlDbPlr.mjs";import{createCompanionSync as Ke}from"./packem_shared/createCompanionSync-C7nzg7f-.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as He,deleteGlobalShapeSnapshot as Xe,deleteGlobalShapeSnapshotsForConnection as Ve,migrateGlobalShapeSnapshot as ze,readGlobalShapeSnapshot as Qe,writeGlobalShapeSnapshot as Ye}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-Bb6-aZuH.mjs";import{IDEMPOTENCY_TABLE as Je,migrateIdempotency as Ze,readIdempotent as $e,trimIdempotent as er,writeIdempotent as rr}from"./packem_shared/IDEMPOTENCY_TABLE-COrgeP3O.mjs";import{clearMemoryTables as ar,isMemoryTable as tr,memoryTableNames as sr}from"./packem_shared/clearMemoryTables-aMRERF0w.mjs";import{computeRankPage as nr,resolveRankSeekTuple as lr}from"./packem_shared/computeRankPage-B6umzbg4.mjs";import{SCHEDULE_OUTBOX_TABLE as mr,deferScheduleOutbox as cr,dropScheduleOutbox as pr,forgetScheduleOutbox as Sr,hasScheduleOutboxEntry as ur,migrateScheduleOutbox as fr,parkScheduleOutbox as Tr,probeScheduleOutbox as Er,readDueScheduleOutbox as xr,readDueScheduleOutboxEntry as hr,readScheduleOutbox as Rr,readScheduleOutboxState as Ar,recordScheduleOutbox as Ir,requeueScheduleOutbox as gr,trimScheduleOutbox as Cr}from"./packem_shared/SCHEDULE_OUTBOX_TABLE-iyyiSjsO.mjs";import{S as br,m as Lr,r as Dr,w as Or}from"./packem_shared/ctx-db-search-state-CPKPy8N6.mjs";import{SHAPE_POKE_CURSOR_TABLE as Pr,deleteShapePokeCursor as yr,deleteShapePokeCursorsForConnection as Fr,migrateShapePokeCursor as kr,minShapePokeCursor as Nr,readShapePokeCursor as Br,writeShapePokeCursor as Ur,writeShapePokeCursors as wr}from"./packem_shared/SHAPE_POKE_CURSOR_TABLE-BGvY3sFI.mjs";import{selectShapeMembers as vr,selectShapeRows as qr}from"./packem_shared/selectShapeMembers-Dqx_m7BF.mjs";import{DATA_MIGRATION_STATE_TABLE as Wr,readMigrationStatus as Hr,runDataMigration as Xr}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-CPWZjliE.mjs";import{SCAN_DEP as zr,createDependencyTracker as Qr,depKey as Yr,tableFromDepKey as jr}from"./packem_shared/SCAN_DEP-B4Uu4g7l.mjs";import{runDrizzle as Zr,runSql as $r}from"./packem_shared/runDrizzle-RC09zZrh.mjs";import{A as ro,a as oo,b as ao,D as to,c as so,d as io,g as no,i as lo,j as mo,e as co,q as po,f as So,r as uo,t as fo,h as To}from"./packem_shared/do-sql-105TONaE.mjs";import{WORKERD_SQLITE_LIMITS as xo,param as ho,renderSql as Ro,sqliteInList as Ao,unionAll as Io}from"./packem_shared/WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{appendStreamChunk as Co,claimStreamRun as _o,deleteStreamRun as bo,finishStreamRun as Lo,migrateDurableStreams as Do,readStreamChunks as Oo,readStreamRun as Mo,trimStreamRuns as Po}from"./packem_shared/appendStreamChunk-BZYgGE9Y.mjs";import{DurableStreamRunner as Fo,MAX_DURABLE_STREAM_BYTES as ko,MAX_DURABLE_STREAM_CHUNKS as No,decideDurableAttach as Bo}from"./packem_shared/DurableStreamRunner-MMlV5qKQ.mjs";import{envOptionalPositiveInt as wo,envPositiveInt as Go}from"./packem_shared/envOptionalPositiveInt-D2pY-c64.mjs";import{diffExternalSource as qo}from"./packem_shared/diffExternalSource-B0FZlDoL.mjs";import{liftSourceId as Wo,normalizeSourceDocument as Ho,normalizeSourceValue as Xo}from"./packem_shared/liftSourceId-CA3ENhXj.mjs";import{materializeExternalRows as zo,materializeExternalRowsIncremental as Qo,readExternalSourceBaseline as Yo,runExternalSourceTick as jo}from"./packem_shared/materializeExternalRows-CHPRx8fu.mjs";import{isSoftDeleted as Zo,isSourceDue as $o,pullExternalSourceIncrementalTick as ea,pullExternalSourceTick as ra}from"./packem_shared/isSoftDeleted-BBWKE0Sm.mjs";import{f as aa,a as ta,b as sa,c as ia,d as na,g as la}from"./packem_shared/fts-companion-CE3EmIjk.mjs";import{GEO_DEFAULT_PRECISION as ma,boundingBoxCenter as ca,boundingBoxGeohashes as pa,coveringGeohashes as Sa,encodeGeohash as ua,haversineMeters as fa,pointInBoundingBox as Ta}from"./packem_shared/GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{default as xa}from"./packem_shared/GlobalPollTick-BNK4o-XT.mjs";import{IMPORT_MANIFEST_TTL_MS as Ra,IMPORT_STAGE_TTL_MS as Aa,advanceImportManifest as Ia,assertImportSessionId as ga,dropImportManifest as Ca,dropImportSession as _a,markShardImportCommitted as ba,readImportManifest as La,readShardImportSession as Da,stageImportRows as Oa,stagedImportIds as Ma,stagedImportPage as Pa,sweepImportStaging as ya,touchImportManifest as Fa,touchShardImportSession as ka}from"./packem_shared/IMPORT_MANIFEST_TTL_MS-BrNT0vUO.mjs";import{ADMIN_FUNCTIONS as Ba,ADMIN_FUNCTION_PREFIX as Ua,DEFAULT_FANOUT_TOPIC_LIMIT as wa,FLAGS_FUNCTION_PREFIX as Ga,MAX_PAGE_SIZE as va,RELATION_FUNCTION_PREFIX as qa,createFanoutCounters as Ka,createGlobalPollCounters as Wa,createShapeProbeCounters as Ha,facetColumn as Xa,findStorageReferences as Va,isVacuousFilterClause as za,listTables as Qa,readTablePage as Ya,recordFanoutPass as ja,recordGlobalPollPass as Ja,recordShapeProbePass as Za,selectMatchingIds as $a,summarizeFanoutTopics as et,summarizeSubscriptions as rt}from"./packem_shared/ADMIN_FUNCTIONS-CfHGnLsC.mjs";import{MAIL_RETENTION as at,MAIL_TABLE as tt,clearCapturedMail as st,ensureMailTable as it,readCapturedMail as nt,recordCapturedMail as lt}from"./packem_shared/MAIL_RETENTION-DMolrLYt.mjs";import{NotFoundError as mt}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{assertPatchAllowed as pt,operatorFields as St,patchDependsOnRow as ut,readPatchField as ft,resolvePatch as Tt}from"./packem_shared/assertPatchAllowed-CA_H466g.mjs";import{armRestore as xt,readBookmark as ht}from"./packem_shared/armRestore-Bu1_8SUa.mjs";import{CURSOR_PREFIX as At,applySelect as It,buildSeekBeforeWhere as gt,buildSeekWhere as Ct,decodeCursor as _t,encodeCursor as bt,equalityPinnedFields as Lt,normalizeOrderKeys as Dt,nullsFirstOf as Ot,nullsOrderSuffix as Mt,softDeleteScope as Pt,tiebreakDirectionFor as yt,uniqueIndexFields as Ft}from"./packem_shared/CURSOR_PREFIX-rOdoinP8.mjs";import{QUEUE_TABLE as Nt,clearQueueMessages as Bt,isLossyBody as Ut,readQueueMessageById as wt,readQueueMessages as Gt,recordQueueMessages as vt}from"./packem_shared/QUEUE_TABLE-C-goXtGd.mjs";import{RANK_TIEBREAK as Kt,encodePartitionKey as Wt,matchesRankStaticWhere as Ht,rankKeyFromDoc as Xt,rankPivotConditionSql as Vt,rankTableName as zt,resolveRankPartition as Qt,sortColumnName as Yt}from"./packem_shared/RANK_TIEBREAK-D3ye2GsL.mjs";import{ReactiveCache as Jt,reactiveCacheKey as Zt}from"./packem_shared/ReactiveCache-BG9z3FE9.mjs";import{REACTOR_STATE_TABLE as es,listReactorStates as rs,migrateReactorState as os,reactorNeedsRun as as,readReactorState as ts,writeReactorState as ss}from"./packem_shared/REACTOR_STATE_TABLE-D2Mn204f.mjs";import{ADMIN_WILDCARD as ns,UNVOUCHABLE_DEP as ls,createReadFootprint as ds,markUnvouchableReads as ms}from"./packem_shared/ADMIN_WILDCARD-BUrgWQ3-.mjs";import{buildIndexRange as ps,indexKeysForRow as Ss,keysTouchRanges as us}from"./packem_shared/buildIndexRange-BTChxh3k.mjs";import{isPushableWhere as Ts,whereFilter as Es,whereOfFilter as xs}from"./packem_shared/isPushableWhere-BeYAOjUb.mjs";import{RELATED_DEFAULT_LIMIT as Rs,RELATED_DEPTH_DECAY as As,RELATED_MAX_DEPTH as Is,RELATED_MAX_LIMIT as gs,deriveRelationEdges as Cs,findRelated as _s}from"./packem_shared/RELATED_DEFAULT_LIMIT-CAh3WUMn.mjs";import{DEFAULT_MAX_RELATION_KEYS as Ls,assertFlatPredicate as Ds,assertShapeShardable as Os,composeReadPredicate as Ms,containsRelationPredicate as Ps,findManyPage as ys,isRelationPredicate as Fs,resolveRelationPredicates as ks}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-Crb9ZWeI.mjs";import{describeRelationWrites as Bs}from"./packem_shared/describeRelationWrites-omar6-u9.mjs";import{applyInsertDefaults as ws,applyOnDelete as Gs,distinctValues as vs,fanOutScalarCounts as qs,relationHooks as Ks,resolveWith as Ws,runRowValidators as Hs}from"./packem_shared/applyInsertDefaults-80S3Pm2_.mjs";import{D as Vs,c as zs,n as Qs,r as Ys,s as js}from"./packem_shared/relay-CKEdfUjH.mjs";import{DEFAULT_MAX_RELAYS as Zs,OwnerRelay as $s,RelayMember as ei,createRelayLink as ri}from"./packem_shared/DEFAULT_MAX_RELAYS-BZLpaaq1.mjs";import{createReplicaLink as ai,gateReplicaDispatch as ti,handleReplicaControl as si}from"./packem_shared/createReplicaLink-DtqXBi-0.mjs";import{buildReprojectionMigration as ni,countLegacyRows as li,reprojectableFields as di,reprojectionTables as mi}from"./packem_shared/buildReprojectionMigration-B8aEpETD.mjs";import{RLS_UNWRAP_SYMBOL as pi,RlsRequiredError as Si,guardWriter as ui}from"./packem_shared/RLS_UNWRAP_SYMBOL-CWo1Bk9y.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as Ti,readSchemaHistory as Ei,readSchemaVersion as xi,recordSchemaVersion as hi}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-CEwFjj-O.mjs";import{serializeSqlValue as Ai}from"./packem_shared/serializeSqlValue-DeoBMpZ2.mjs";import{buildSettings as gi,isDevEnvironment as Ci,readDeployInfo as _i}from"./packem_shared/buildSettings-CFkvTaHx.mjs";import{buildShapeDiff as Li}from"./packem_shared/buildShapeDiff-CdLJTijm.mjs";import{ShapeDiffCache as Oi,createShapeDiffCache as Mi,globalShapeReadKey as Pi}from"./packem_shared/ShapeDiffCache-iNO-hUiy.mjs";import{buildPokeFrames as Fi,diffGlobalMembership as ki,encodeRowsPatch as Ni,projectColumns as Bi}from"./packem_shared/buildPokeFrames-WR-hp0mX.mjs";import{ShardRunner as wi}from"./packem_shared/ShardRunner-CrveaPId.mjs";import{stubByName as vi}from"./packem_shared/stubByName-DQSivmvb.mjs";import{runSocketPool as Ki}from"./packem_shared/runSocketPool-CZJ2X9cF.mjs";import{MAX_SQL_ROWS as Hi,assertReadonly as Xi,lintReadonlySql as Vi,runReadonlySql as zi}from"./packem_shared/MAX_SQL_ROWS-B4WlVI-e.mjs";import{BIGINT_KEY_DIGITS as Yi,bigintSqlKey as ji,decodeBigintSqlKey as Ji,decodeFloat64SqlKey as Zi,float64SqlKey as $i}from"./packem_shared/BIGINT_KEY_DIGITS-DE6yshOt.mjs";import{DELTA_PLACEHOLDER_TABLE as rn,awaitWsDrain as on,deltaTableFor as an,subscriptionFrames as tn,subscriptionListDeltas as sn,trySendFrame as nn}from"./packem_shared/DELTA_PLACEHOLDER_TABLE-CHxtV9xh.mjs";import{mergeChangedKeys as dn,recordChangedKeys as mn,writeTouchesMemo as cn}from"./packem_shared/mergeChangedKeys-DPKhen6e.mjs";import{createSystemReader as Sn}from"./packem_shared/createSystemReader-BSCxr8Qs.mjs";import{ConflictError as fn}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as En,TransactionHeadroomTracker as xn}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS-D7p7Ys0M.mjs";import{hasTrigger as Rn,runTriggers as An}from"./packem_shared/hasTrigger-CjlwI4le.mjs";import{isTtlExpired as gn,nextTtlExpiry as Cn,selectExpiredIds as _n}from"./packem_shared/isTtlExpired-DNxmZA6e.mjs";import{VECTOR_BACKFILL_MAX_PAGES as Ln,backfillVectorIndexes as Dn}from"./packem_shared/VECTOR_BACKFILL_MAX_PAGES-CTKYW2J5.mjs";import{c as Mn,s as Pn}from"./packem_shared/where-sql-BjY4rnqb.mjs";import{RELATION_EXISTS_KEY as Fn}from"./packem_shared/RELATION_EXISTS_KEY-wxgj6rSL.mjs";import{ADMIN_TOKEN_TABLE as Nn}from"./packem_shared/ADMIN_TOKEN_TABLE-DfQ5osdI.mjs";import{RELAY_SIGNATURE_HEADER as Un,siblingSecretOf as wn,signSiblingBody as Gn,verifySiblingBody as vn}from"./packem_shared/RELAY_SIGNATURE_HEADER-CAfC4tqg.mjs";import{REPROJECTION_MIGRATION_PREFIX as Kn,reprojectionMigrationId as Wn}from"./packem_shared/REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{isInternalTableName as Xn}from"./packem_shared/isInternalTableName-BoljO2tP.mjs";import{quoteIdentifier as zn}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as Yn}from"./packem_shared/runShardMigrations-DBkimnd5.mjs";import{stableStringify as Jn,stableWireKey as Zn}from"@lunora/wire";export{Ba as ADMIN_FUNCTIONS,Ua as ADMIN_FUNCTION_PREFIX,Nn as ADMIN_TOKEN_TABLE,ns as ADMIN_WILDCARD,T as AGGREGATE_SQL_FUNCTION,ro as AGG_COUNT,oo as AGG_KEY,ao as AGG_VALUE,N as AUDIT_LOG_TABLE,Yi as BIGINT_KEY_DIGITS,$ as CDC_LOG_TABLE,ee as CDC_LOG_TABLE_SEQ_INDEX,re as CDC_META_TABLE,De as CLIENT_WATERMARK_TABLE,Fe as COMMIT_SEQ_FIELD,ke as COMMIT_SEQ_TABLE,At as CURSOR_PREFIX,Ge as CompanionMemo,fn as ConflictError,D as CountRlsUnsupportedError,Wr as DATA_MIGRATION_STATE_TABLE,wa as DEFAULT_FANOUT_TOPIC_LIMIT,Ls as DEFAULT_MAX_RELATION_KEYS,Zs as DEFAULT_MAX_RELAYS,Vs as DEFAULT_PROMOTION_THRESHOLDS,En as DEFAULT_TRANSACTION_LIMITS,rn as DELTA_PLACEHOLDER_TABLE,to as DOC_COLUMN,Fo as DurableStreamRunner,Ga as FLAGS_FUNCTION_PREFIX,ma as GEO_DEFAULT_PRECISION,He as GLOBAL_SHAPE_SNAPSHOT_TABLE,xa as GlobalPollTick,Je as IDEMPOTENCY_TABLE,Ra as IMPORT_MANIFEST_TTL_MS,Aa as IMPORT_STAGE_TTL_MS,at as MAIL_RETENTION,tt as MAIL_TABLE,ko as MAX_DURABLE_STREAM_BYTES,No as MAX_DURABLE_STREAM_CHUNKS,va as MAX_PAGE_SIZE,Hi as MAX_SQL_ROWS,mt as NotFoundError,v as NotUniqueError,$s as OwnerRelay,Nt as QUEUE_TABLE,Kt as RANK_TIEBREAK,es as REACTOR_STATE_TABLE,Rs as RELATED_DEFAULT_LIMIT,As as RELATED_DEPTH_DECAY,Is as RELATED_MAX_DEPTH,gs as RELATED_MAX_LIMIT,Fn as RELATION_EXISTS_KEY,qa as RELATION_FUNCTION_PREFIX,Un as RELAY_SIGNATURE_HEADER,Kn as REPROJECTION_MIGRATION_PREFIX,pi as RLS_UNWRAP_SYMBOL,Jt as ReactiveCache,ei as RelayMember,Si as RlsRequiredError,zr as SCAN_DEP,mr as SCHEDULE_OUTBOX_TABLE,Ti as SCHEMA_HISTORY_MAX_VERSIONS,br as SEARCH_STATE_TABLE,Pr as SHAPE_POKE_CURSOR_TABLE,Oi as ShapeDiffCache,wi as ShardRunner,xn as TransactionHeadroomTracker,ls as UNVOUCHABLE_DEP,Ln as VECTOR_BACKFILL_MAX_PAGES,xo as WORKERD_SQLITE_LIMITS,m as adminTokenExists,Oe as advanceClientWatermark,Ia as advanceImportManifest,so as aggUpsertSql,E as aggregateSqlFunction,I as aggregateTableName,Ne as allocateCommitSeq,B as appendAuditEntry,oe as appendCdcChange,Co as appendStreamChunk,ae as applyCdcChanges,ws as applyInsertDefaults,Gs as applyOnDelete,It as applySelect,Ie as archiveCdcSegment,xt as armRestore,Ds as assertFlatPredicate,ga as assertImportSessionId,q as assertNoExplicitUndefined,pt as assertPatchAllowed,Xi as assertReadonly,Os as assertShapeShardable,K as assertStorableRowId,W as assertValidClientId,on as awaitWsDrain,Q as backfillAggregateIndexes,Y as backfillRankIndexes,j as backfillSearchIndexes,J as backfillSearchIndexesForTable,Dn as backfillVectorIndexes,ji as bigintSqlKey,ca as boundingBoxCenter,pa as boundingBoxGeohashes,ps as buildIndexRange,Fi as buildPokeFrames,ni as buildReprojectionMigration,gt as buildSeekBeforeWhere,Ct as buildSeekWhere,gi as buildSettings,Li as buildShapeDiff,te as bumpCdcEpoch,ge as cdcArchiveRewound,se as cdcCanVouchFor,ie as cdcForkedError,ne as cdcSeqLeavingRows,le as cdcTouchesTables,de as cdcTrimmedError,_o as claimStreamRun,zs as clampPromotionThresholds,st as clearCapturedMail,ve as clearCompanionSignatures,ar as clearMemoryTables,Bt as clearQueueMessages,g as coerceAggregateNumber,me as compactCdcDocs,Mn as compileWhereSql,Ms as composeReadPredicate,nr as computeRankPage,Ps as containsRelationPredicate,li as countLegacyRows,Sa as coveringGeohashes,c as createAdminTokenRecord,Ke as createCompanionSync,Qr as createDependencyTracker,Ka as createFanoutCounters,Wa as createGlobalPollCounters,io as createIndexSql,ds as createReadFootprint,ri as createRelayLink,ai as createReplicaLink,Mi as createShapeDiffCache,Ha as createShapeProbeCounters,H as createShardCtxDb,Sn as createSystemReader,ce as cursorBelowRetainedFloor,Bo as decideDurableAttach,Ji as decodeBigintSqlKey,_t as decodeCursor,Zi as decodeFloat64SqlKey,cr as deferScheduleOutbox,Xe as deleteGlobalShapeSnapshot,Ve as deleteGlobalShapeSnapshotsForConnection,yr as deleteShapePokeCursor,Fr as deleteShapePokeCursorsForConnection,bo as deleteStreamRun,an as deltaTableFor,Yr as depKey,Cs as deriveRelationEdges,Bs as describeRelationWrites,qo as diffExternalSource,ki as diffGlobalMembership,vs as distinctValues,Ca as dropImportManifest,_a as dropImportSession,pr as dropScheduleOutbox,C as encodeAggregateKey,bt as encodeCursor,ua as encodeGeohash,Wt as encodePartitionKey,Ni as encodeRowsPatch,U as ensureAuditTable,it as ensureMailTable,wo as envOptionalPositiveInt,Go as envPositiveInt,Lt as equalityPinnedFields,o as exportShardRows,Xa as facetColumn,qs as fanOutScalarCounts,ys as findManyPage,_s as findRelated,Va as findStorageReferences,Lo as finishStreamRun,$i as float64SqlKey,_ as foldAggregateTally,Sr as forgetScheduleOutbox,aa as ftsCompanionDdl,ta as ftsPurgeDocument,sa as ftsRowidMapName,ia as ftsUnmappedPage,na as ftsWriteDocument,ti as gateReplicaDispatch,no as geoTableName,Pi as globalShapeReadKey,la as groupUnmappedRows,ui as guardWriter,si as handleReplicaControl,ur as hasScheduleOutboxEntry,Rn as hasTrigger,fa as haversineMeters,a as importShardRows,Ss as indexKeysForRow,Ci as isDevEnvironment,lo as isFtsAvailable,Xn as isInternalTableName,Ut as isLossyBody,tr as isMemoryTable,Ts as isPushableWhere,Fs as isRelationPredicate,Zo as isSoftDeleted,$o as isSourceDue,gn as isTtlExpired,za as isVacuousFilterClause,mo as jsonPath,co as jsonPathSql,us as keysTouchRanges,Wo as liftSourceId,Vi as lintReadonlySql,p as listAdminTokens,rs as listReactorStates,Qa as listTables,ba as markShardImportCommitted,ms as markUnvouchableReads,Ht as matchesRankStaticWhere,x as matchesStaticWhere,zo as materializeExternalRows,Qo as materializeExternalRowsIncremental,sr as memoryTableNames,dn as mergeChangedKeys,O as mergeWhere,pe as migrateCdcLog,Se as migrateCdcMeta,Me as migrateClientWatermark,Be as migrateCommitSeq,Do as migrateDurableStreams,ze as migrateGlobalShapeSnapshot,Ze as migrateIdempotency,os as migrateReactorState,fr as migrateScheduleOutbox,Lr as migrateSearchState,kr as migrateShapePokeCursor,ue as minCdcReplayableSeq,fe as minCdcSeq,Nr as minShapePokeCursor,Qs as nextPromotionState,Cn as nextTtlExpiry,h as normalizeCountArgument,X as normalizeIdStructurally,Dt as normalizeOrderKeys,Ho as normalizeSourceDocument,Xo as normalizeSourceValue,Ot as nullsFirstOf,Mt as nullsOrderSuffix,St as operatorFields,ho as param,Tr as parkScheduleOutbox,t as parseExportShardArgs,s as parseImportShardArgs,ut as patchDependsOnRow,M as planAggregateLookup,Ta as pointInBoundingBox,Er as probeScheduleOutbox,Bi as projectColumns,ea as pullExternalSourceIncrementalTick,ra as pullExternalSourceTick,po as qualifiedJsonPath,So as qualifiedJsonPathSql,zn as quoteIdentifier,Xt as rankKeyFromDoc,Vt as rankPivotConditionSql,zt as rankTableName,Zt as reactiveCacheKey,as as reactorNeedsRun,b as readAggregateValue,Ce as readArchivedCdcChanges,w as readAuditLog,ht as readBookmark,nt as readCapturedMail,_e as readCdcArchivedThrough,Te as readCdcChangeKeys,Ee as readCdcChanges,xe as readCdcCursor,he as readCdcEpoch,Pe as readClientWatermark,Ue as readCommitSeq,_i as readDeployInfo,xr as readDueScheduleOutbox,hr as readDueScheduleOutboxEntry,Yo as readExternalSourceBaseline,Qe as readGlobalShapeSnapshot,$e as readIdempotent,La as readImportManifest,Hr as readMigrationStatus,ft as readPatchField,wt as readQueueMessageById,Gt as readQueueMessages,ts as readReactorState,Rr as readScheduleOutbox,Ar as readScheduleOutboxState,Ei as readSchemaHistory,xi as readSchemaVersion,Dr as readSearchBackfillState,Br as readShapePokeCursor,Da as readShardImportSession,Oo as readStreamChunks,Mo as readStreamRun,Ya as readTablePage,lt as recordCapturedMail,mn as recordChangedKeys,ja as recordFanoutPass,Ja as recordGlobalPollPass,vt as recordQueueMessages,Ir as recordScheduleOutbox,hi as recordSchemaVersion,Za as recordShapeProbePass,Ks as relationHooks,Ys as relayCountFor,Ro as renderSql,i as replaceRefusal,di as reprojectableFields,Wn as reprojectionMigrationId,mi as reprojectionTables,gr as requeueScheduleOutbox,Tt as resolvePatch,Qt as resolveRankPartition,lr as resolveRankSeekTuple,ks as resolveRelationPredicates,Ws as resolveWith,S as revokeAdminTokenRecord,uo as rowToDocument,Xr as runDataMigration,Zr as runDrizzle,jo as runExternalSourceTick,zi as runReadonlySql,Hs as runRowValidators,Yn as runShardMigrations,Ki as runSocketPool,$r as runSql,An as runTriggers,_n as selectExpiredIds,n as selectExportTables,P as selectIndexForAggregate,y as selectIndexForCount,F as selectIndexForGroupBy,$a as selectMatchingIds,vr as selectShapeMembers,qr as selectShapeRows,Ai as serializeSqlValue,Pn as serverInList,js as shapeRoutingKey,wn as siblingSecretOf,Gn as signSiblingBody,Pt as softDeleteScope,Yt as sortColumnName,Ao as sqliteInList,Jn as stableStringify,Zn as stableWireKey,Oa as stageImportRows,Ma as stagedImportIds,Pa as stagedImportPage,V as stripReservedPatchFields,vi as stubByName,tn as subscriptionFrames,sn as subscriptionListDeltas,et as summarizeFanoutTopics,rt as summarizeSubscriptions,ya as sweepImportStaging,fo as tableColumns,jr as tableFromDepKey,R as throwingScheduler,yt as tiebreakDirectionFor,Fa as touchImportManifest,ka as touchShardImportSession,Re as trimCdcChanges,er as trimIdempotent,Cr as trimScheduleOutbox,Po as trimStreamRuns,To as tryRowToDocument,nn as trySendFrame,Io as unionAll,Ft as uniqueIndexFields,l as validateImportRow,u as verifyAdminTokenDigest,vn as verifySiblingBody,Es as whereFilter,xs as whereOfFilter,be as writeCdcArchivedThrough,Ye as writeGlobalShapeSnapshot,rr as writeIdempotent,ss as writeReactorState,Or as writeSearchBackfillState,Ur as writeShapePokeCursor,wr as writeShapePokeCursors,cn as writeTouchesMemo};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{sql as e}from"drizzle-orm";import{compareStrings as a,encodeAggregateKey as f}from"./aggregateTableName-B_CtIQCS.mjs";import{runDrizzle as r}from"./runDrizzle-RC09zZrh.mjs";import{sqliteInList as T}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";const n="__lunora_companion_state",c=1,g=
|
|
1
|
+
import{sql as e}from"drizzle-orm";import{compareStrings as a,encodeAggregateKey as f}from"./aggregateTableName-B_CtIQCS.mjs";import{runDrizzle as r}from"./runDrizzle-RC09zZrh.mjs";import{sqliteInList as T}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";const n="__lunora_companion_state",c=1,g=2,E=i=>i?f(Object.keys(i),i):"",O=(i,t)=>JSON.stringify([c,(i.by??[]).toSorted(a),i.field??"",i.op,E(i.where),t??""]),$=(i,t)=>JSON.stringify([g,(i.partitionBy??[]).toSorted(a),i.sortBy.map(o=>o.field),E(i.where),t??""]),s=i=>{r(i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(n)} (${e.identifier("companion")} TEXT PRIMARY KEY, ${e.identifier("signature")} TEXT NOT NULL)`)},u=(i,t)=>{s(i),r(i,t.length===0?e`DELETE FROM ${e.identifier(n)}`:e`DELETE FROM ${e.identifier(n)} WHERE ${T(e.raw('"companion"'),t,!0)}`)},R=(i,t)=>r(i,e`SELECT ${e.identifier("signature")} FROM ${e.identifier(n)} WHERE ${e.identifier("companion")} = ${t}`).toArray()[0]?.signature,A=(i,t,o)=>{r(i,e`INSERT INTO ${e.identifier(n)} (${e.identifier("companion")}, ${e.identifier("signature")}) VALUES (${t}, ${o}) ON CONFLICT (${e.identifier("companion")}) DO UPDATE SET ${e.identifier("signature")} = excluded.${e.identifier("signature")}`)},N=i=>{s(i),r(i,e`DELETE FROM ${e.identifier(n)}`)};class L{verified=new Set;invalidate(){this.verified.clear()}}export{L as CompanionMemo,O as aggregateSignature,N as clearCompanionSignatures,u as migrateCompanionState,$ as rankSignature,R as readCompanionSignature,A as writeCompanionSignature};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as R}from"@lunora/errors";import{q as _t}from"./MAX_TOKEN_LENGTH-iFEGEcDL-DBPC6ZWl.mjs";import{S as zn,l as Ue,s as Yn}from"./fts-companion-CE3EmIjk.mjs";import{decodeWire as Xn,stableWireKey as jt}from"@lunora/wire";import{sql as f}from"drizzle-orm";import{throwingScheduler as Zn,aggregateSqlFunction as Oe,normalizeCountArgument as Ht}from"./AGGREGATE_SQL_FUNCTION-C_ZipS9R.mjs";import{aggregateTableName as at,encodeAggregateKey as dt,readAggregateValue as lt}from"./aggregateTableName-B_CtIQCS.mjs";import{mergeWhere as Q,CountRlsUnsupportedError as ut,selectIndexForGroupBy as eo,selectIndexForCount as to,selectIndexForAggregate as no}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{backfillSearchIndexesForTable as oo,searchIndexCoversTable as ro}from"./backfillAggregateIndexes-DNVOUEEW.mjs";import{backfillAggregateIndexes as os,backfillRankIndexes as rs,backfillSearchIndexes as is}from"./backfillAggregateIndexes-DNVOUEEW.mjs";import{appendCdcChange as io,readCdcDocAtOrBefore as so}from"./CDC_LOG_TABLE-BFGgqai8.mjs";import{CDC_LOG_TABLE as cs,applyCdcChanges as as,bumpCdcEpoch as ds,cdcCanVouchFor as ls,cdcForkedError as us,cdcSeqLeavingRows as fs,cdcTouchesTables as hs,cdcTrimmedError as ws,compactCdcDocs as ps,cursorBelowRetainedFloor as gs,minCdcReplayableSeq as ys,minCdcSeq as $s,readCdcChangeKeys as Es,readCdcChanges as ms,readCdcCursor as Rs,readCdcEpoch as vs,trimCdcChanges as Ss}from"./CDC_LOG_TABLE-BFGgqai8.mjs";import{allocateCommitSeq as co,COMMIT_SEQ_FIELD as ao}from"./COMMIT_SEQ_FIELD-Da1DjGqo.mjs";import{createCompanionSync as lo}from"./createCompanionSync-C7nzg7f-.mjs";import{isMemoryTable as Kt}from"./clearMemoryTables-aMRERF0w.mjs";import{computeRankPage as Nt}from"./computeRankPage-B6umzbg4.mjs";import{SCAN_DEP as G,PRIMARY_READ as uo}from"./SCAN_DEP-B4Uu4g7l.mjs";import{runSql as ye,runDrizzle as K}from"./runDrizzle-RC09zZrh.mjs";import{p as fo,j as yt,D as ie,r as Ce,W as ho,k as ae,b as Ge,A as ft,a as je,m as pe,e as ge,s as wo,t as po,u as go,i as yo,q as Qt,h as mn,g as $o}from"./do-sql-105TONaE.mjs";import{renderSql as Rn,unionAll as vn,WORKERD_SQLITE_LIMITS as Sn}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{a as Eo,u as mo}from"./estimate-bytes-C-C35VXL.mjs";import{coveringGeohashes as Ro,boundingBoxGeohashes as vo,haversineMeters as So,pointInBoundingBox as _o}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{NotFoundError as To}from"./NotFoundError-BhF7FeFr.mjs";import{resolvePatch as Ao,assertPatchAllowed as Io,operatorFields as bo,readPatchField as Vt}from"./assertPatchAllowed-CA_H466g.mjs";import{tiebreakDirectionFor as xo,encodeCursor as $t,nullsOrderSuffix as Co,normalizeOrderKeys as Jt,uniqueIndexFields as Mo,buildSeekWhere as Do,decodeCursor as zt,buildSeekBeforeWhere as ko,softDeleteScope as be,applySelect as _n}from"./CURSOR_PREFIX-rOdoinP8.mjs";import{rankTableName as Yt,sortColumnName as Xt,resolveRankPartition as Lo,encodePartitionKey as Fo,RANK_TIEBREAK as Wo,rankPivotConditionSql as Bo}from"./RANK_TIEBREAK-D3ye2GsL.mjs";import{UNVOUCHABLE_DEP as Zt}from"./ADMIN_WILDCARD-BUrgWQ3-.mjs";import{idIndexKey as qo,withUnknownIndexKeys as Po,indexKeysForRow as Uo,buildIndexRange as Oo}from"./buildIndexRange-BTChxh3k.mjs";import{r as Je,j as Me,c as ee,t as Xe,i as en}from"./where-sql-BjY4rnqb.mjs";import{serializeSqlValue as De}from"./serializeSqlValue-DeoBMpZ2.mjs";import{quoteIdentifier as ke}from"./quoteIdentifier-CObIFRhb.mjs";import{whereOfFilter as Go,isPushableWhere as jo}from"./isPushableWhere-BeYAOjUb.mjs";import{deriveRelationEdges as Ho,findRelated as Ko}from"./RELATED_DEFAULT_LIMIT-CAh3WUMn.mjs";import{assertFlatPredicate as ht,findManyPage as No,relationPredicateTables as Qo,resolveRelationPredicates as Vo,composeReadPredicate as Jo}from"./DEFAULT_MAX_RELATION_KEYS-Crb9ZWeI.mjs";import{describeRelationWrites as zo}from"./describeRelationWrites-omar6-u9.mjs";import{runRowValidators as He,transformOnlyDefinition as Yo,applyInsertDefaults as Et,resolveWith as Xo,relationHooks as Zo,applyOnDelete as er,fanOutScalarCounts as tr,CASCADE_MAX_ROWS as nr}from"./applyInsertDefaults-80S3Pm2_.mjs";import{guardWriter as or}from"./RLS_UNWRAP_SYMBOL-CWo1Bk9y.mjs";import{mayHoldProjectedValue as rr}from"./BIGINT_KEY_DIGITS-DE6yshOt.mjs";import{createSystemReader as ir}from"./createSystemReader-BSCxr8Qs.mjs";import{ConflictError as de}from"./ConflictError-C8GtJmjS.mjs";import{hasTrigger as tn,runTriggers as sr}from"./hasTrigger-CjlwI4le.mjs";import{advanceClientWatermark as Ts,migrateClientWatermark as As,readClientWatermark as Is}from"./CLIENT_WATERMARK_TABLE-De7z_OHV.mjs";import{IDEMPOTENCY_TABLE as xs,readIdempotent as Cs,trimIdempotent as Ms,writeIdempotent as Ds}from"./IDEMPOTENCY_TABLE-COrgeP3O.mjs";import{runShardMigrations as Ls}from"./runShardMigrations-DBkimnd5.mjs";import{selectShapeMembers as Ws,selectShapeRows as Bs}from"./selectShapeMembers-Dqx_m7BF.mjs";const cr=n=>{const i=atob(n),o=Uint8Array.from(i,s=>s.codePointAt(0)??0);return new TextDecoder().decode(o)},ar=()=>new R("INVALID_CURSOR","invalid cursor"),nn=16,on=8,Z=1024,Tt=(n,i)=>i.query(n),dr=(n,i)=>{if(n.length===0)return 0;let o=0;for(const[s,a]of i.entries()){const w=s===i.length-1;let g=0;for(const E of n)(w?E.startsWith(a):E===a)&&(g+=1);if(g===0)return 0;o+=g}return o},lr=(n,i)=>{if(!i)return{exact:!0,lower:n,upper:n};const o=[...n].at(-1)??"",s=(o.codePointAt(0)??0)+1;if(s>=55296&&s<=57343||s>1114111)return{exact:!0,lower:n,upper:n};const a=n.slice(0,n.length-o.length);return{exact:!1,lower:n,upper:a+String.fromCodePoint(s)}},ur=(n,i,o)=>{const s={eq:(a,w)=>{if(!n.definition.filterFields?.includes(a))throw new R("INTERNAL",`field "${a}" is not a filter field of search index "${n.indexName}" on table "${i}"`);if(n.filters.length>=on)throw new R("BAD_REQUEST",`search index "${n.indexName}" on table "${i}": at most ${String(on)} .eq() filters are supported per search query`);return n.filters.push({field:a,value:w}),s},search:(a,w)=>{const g=n;if(a!==g.definition.field)throw new R("INTERNAL",`search index "${g.indexName}" on table "${i}" indexes "${g.definition.field}", not "${a}"`);const E=Tt(w,o).length;if(E>nn)throw new R("BAD_REQUEST",`search index "${g.indexName}" on table "${i}": at most ${String(nn)} search terms are supported (got ${String(E)})`);return g.field=a,g.query=w,g.hasQuery=!0,s}};return s},fr=n=>{if(n.length>Z)throw new R("BAD_REQUEST",`more than ${String(Z)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},hr=n=>Math.min(n.offset+n.numItems+1,Z),wr=n=>btoa(`search:${String(n)}`),pr=n=>{let i;try{i=cr(n)}catch{return}if(!i.startsWith("search:"))return;const o=Number(i.slice(7));return Number.isInteger(o)&&o>=0?o:void 0},gr=n=>{if(typeof n.endCursor=="string")throw new R("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");if(!Number.isFinite(n.numItems))throw new R("BAD_REQUEST",`search pagination needs a finite numItems, got ${String(n.numItems)}`);const i=Math.max(0,Math.floor(n.numItems)),o=n.cursor?pr(n.cursor):0;if(o===void 0)throw ar();if(o+i>=Z)throw new R("BAD_REQUEST",`search pagination reaches the ${String(Z)}-document limit (offset ${String(o)} + ${String(i)} requested) — a page must end below the cap so the probe row that answers \`hasMore\` still fits: retry with numItems ${String(Math.max(1,Z-o-1))} or fewer, or narrow the query or the filters instead`);return{numItems:i,offset:o}},yr=(n,i)=>{const o=i.offset+i.numItems,s=i.numItems>0&&n.length>o;return{continueCursor:s?wr(o):null,isDone:!s,page:n.slice(i.offset,o)}},$r=n=>{if(n===void 0)return Z+1;if(!Number.isFinite(n))return Z;const i=Math.max(0,Math.floor(n));if(i>Z)throw new R("BAD_REQUEST",`search returns at most ${String(Z)} documents (asked for ${String(i)}) — narrow the query or paginate instead`);return i},Tn=500,An=(n,i,o)=>{if(n!==void 0&&n!==Number.POSITIVE_INFINITY&&(!Number.isInteger(n)||n<0))throw o(`${i}: batch limit must be a non-negative integer`);return n??Tn},In=(n,i,o,s)=>{if(n>i)throw s(`${o}: batch of ${String(n)} exceeds the limit of ${String(i)} (raise options.limit or chunk the call)`)},Er=32,mr=1024,bn=(n,i,o,s)=>{const a=`SELECT id, _creationTime, ${ke(ie)} FROM ${ke(n)}`,w=`ORDER BY ${o}${s===void 0?"":` LIMIT ${String(s)}`}`;return i===void 0?Je(`${a} ${w}`):Me(`${a} WHERE `,i,` ${w}`)},Ze={fieldRef:n=>Je(yt(n)),rangeTypeGuard:(n,i)=>Je(fo(n,i)),serialize:De},Rr=n=>n===void 0?"":Co(n==="first"),xn=n=>{const i=n.map(o=>`${yt(o.field)} ${o.direction==="desc"?"DESC":"ASC"}${Rr(o.nulls)}`);return n.some(o=>o.field==="_id"||o.field==="id")||i.push(`${yt("id")} ${xo(n)==="desc"?"DESC":"ASC"}`),i.join(", ")},vr={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},Cn=n=>new Set(n.sqlConditions.filter(i=>i.comparator==="=").map(i=>i.field)),Sr=n=>{const i=Cn(n);let o=0;for(;o<n.indexFields.length&&i.has(n.indexFields[o]??"");)o+=1;return n.indexFields.slice(o)},_r=(n,i)=>{const o=n.order,s=Sr(n),{shape:a}=i;return s.length>0?Jt(s.map(w=>({[w]:o})),a,{pinned:Cn(n),uniqueBy:Mo(i.indexes,a)}):Jt([{_creationTime:o}],a)},Tr=(n,i,o,s)=>{const a=n.sqlConditions.map(w=>({[w.field]:{[vr[w.comparator]??"eq"]:w.value}}));if(o&&a.push(Do(i,zt(o))),s&&a.push(ko(i,zt(s))),a.length!==0)return a.length===1?a[0]:{AND:a}},Ar=n=>{if(n.want!==void 0)return n.selective?Math.max(n.want,Er):n.want},mt=(n,i,o,s,a,w,g)=>{const E=_r(s,o),y=xn(E),u=[],{filters:C,want:I}=w;let A=w.cursor??void 0,x=Ar(w);if(I===0)return{documents:u,orderKeys:E};for(;;){const q=ee(Tr(s,E,A,w.endCursor),Ze,Xe),P=bn(i,a&&q?Me(q," AND ",a):a??q,y,x),W=ye(n,P.text,...P.params).toArray();let U={};g(W.length);for(const j of W)if(U=Ce(j),C.every(te=>te(U))&&u.push(U)===I)return{documents:u,orderKeys:E};if(x===void 0||W.length<x)return{documents:u,orderKeys:E};A=$t(U,E),x=Math.max(x,Math.min(x*2,mr))}},Ir=(n,i,o,s,a,w,g,E)=>{const y=Math.max(0,Math.floor(a.numItems));if(typeof a.endCursor=="string"){const{documents:q,orderKeys:P}=mt(n,i,o,s,w,{cursor:a.cursor,endCursor:a.endCursor,filters:g.all,selective:g.selective,want:void 0},E),W=q.length>=2?q[Math.floor(q.length/2)-1]:void 0;return{continueCursor:a.endCursor,isDone:!0,page:q,splitCursor:W?$t(W,P):null}}const{documents:u,orderKeys:C}=mt(n,i,o,s,w,{cursor:a.cursor,filters:g.all,selective:g.selective,want:y+1},E),I=u.length>y,A=I?u.slice(0,y):u,x=A.at(-1);return{continueCursor:I&&x?$t(x,C):null,isDone:!I,page:A}},et=n=>{const i=new Map;return o=>{const s=i.get(o);if(s!==void 0)return s;const a=n(ke(o));return i.set(o,a),a}},$e=ke(ie),br=et(n=>`INSERT INTO ${n} (id, _creationTime, ${$e}) VALUES (?, ?, ?)`),rn=et(n=>`UPDATE ${n} SET ${$e} = ? WHERE id = ? AND ${$e} = ?`),xr=et(n=>`UPDATE ${n} SET _creationTime = ?, ${$e} = ? WHERE id = ? AND ${$e} = ?`),Cr=et(n=>`DELETE FROM ${n} WHERE id = ? AND ${$e} = ?`),Mr="SELECT changes() AS changed",sn=new Map,Dr="",kr=n=>{const i=JSON.stringify(n),o=sn.get(i);if(o!==void 0)return o;const s=n.map(w=>f`SELECT ${f.raw(`'${w.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${f.identifier(ie)} FROM ${f.identifier(w)} WHERE id = ${Dr}`),{sql:a}=Rn("sqlite",f`${vn(s)} LIMIT 1`);return sn.set(i,a),a},Lr=(n,i)=>i.map(()=>n),Fr=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,Wr=n=>{if(!Fr.test(n))throw new R("INTERNAL",`invalid clientId ${JSON.stringify(n)}: a client-supplied row id must be a UUID`)},Rt=n=>{if(n.includes("\0"))throw new R("BAD_REQUEST",`invalid row id ${JSON.stringify(n)}: a row id cannot hold a NUL character (U+0000)`)},Br=(n,i,o,s)=>{if(o!==!0)return;const a=n!==void 0&&"serverDefault"in(n.shape._id?._meta?.column??{});for(const w of i){const g=a?Et(n,w,s)._id:w._id;typeof g=="string"&&Rt(g)}},cn=50,Ke=Math.floor(Sn.boundParams/3),an=Sn.boundParams,qr=128,ze=n=>new R("BATCH_LIMIT_EXCEEDED",n,{status:400}),Ne=(n,i,o)=>{In(n,An(i,o,ze),o,ze)},dn=async(n,i,o,s,a)=>{const w=An(s,a,ze),{page:g}=await n.findMany(i,Number.isFinite(w)?{limit:w+1,omitContinueCursor:!0,where:o}:{where:o});return g.length>w&&In(Math.max(await n.count(i,{where:o}),g.length),w,a,ze),g},Pr=n=>{const i={eq:(o,s)=>(n.sqlConditions.push({comparator:"=",field:o,value:s}),i),gt:(o,s)=>(n.sqlConditions.push({comparator:">",field:o,value:s}),i),gte:(o,s)=>(n.sqlConditions.push({comparator:">=",field:o,value:s}),i),lt:(o,s)=>(n.sqlConditions.push({comparator:"<",field:o,value:s}),i),lte:(o,s)=>(n.sqlConditions.push({comparator:"<=",field:o,value:s}),i)};return i},Ur=n=>Math.max(n,Z),Mn=(n,i)=>{const o=n.filters.map(s=>f`${ge(s.field)} = ${De(s.value)}`);return i&&o.push(i),o},Or=(n,i,o,s,a)=>{const w=Tt(o.query,_t(o.definition.language));if(w.length===0)return[];const g=zn(i,o.indexName),E=`${g}__vocab`,y=w.length-1,u=w.map((P,W)=>{const U=lr(P,W===y),j=U.exact?f`${f.identifier("term")} = ${U.lower}`:f`${f.identifier("term")} >= ${U.lower} AND ${f.identifier("term")} < ${U.upper}`;return f`SELECT ${f.identifier("doc")}, ${f.raw(String(W))} AS ${f.identifier("__term__")}, COUNT(*) AS ${f.identifier("__n__")} FROM ${f.identifier(E)} WHERE ${j} GROUP BY ${f.identifier("doc")}`}),C=w.map((P,W)=>f`SUM(CASE WHEN u.${f.identifier("__term__")} = ${f.raw(String(W))} THEN u.${f.identifier("__n__")} ELSE 0 END)`),I=f`SELECT f.${f.identifier(Ue)} AS ${f.identifier(Ue)}, ${f.join(C,f` + `)} AS ${f.identifier("__score__")} FROM (${vn(u)}) u JOIN ${f.identifier(g)} f ON f.rowid = u.${f.identifier("doc")} GROUP BY f.${f.identifier(Ue)} HAVING ${f.join(C.map(P=>f`${P} > 0`),f` AND `)}`,A=Mn(o,a);let x=f`SELECT m.id, m._creationTime, m.${f.identifier(ie)}, s.${f.identifier("__score__")} AS ${f.identifier("__score__")} FROM (${I}) s JOIN ${f.identifier(i)} m ON m.id = s.${f.identifier(Ue)}`;A.length>0&&(x=f`${x} WHERE ${f.join(A,f` AND `)}`),x=f`${x} ORDER BY s.${f.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${f.raw(String(s))}`;const q=[];for(const P of K(n,x)){const W=mn(P);if(W){const U=P.__score__;q.push({document:W,score:typeof U=="number"?U:Number(U??0)})}}return q},Gr=(n,i,o,s,a)=>{const w=_t(o.definition.language),g=Tt(o.query,w);if(g.length===0)return[];const E=Mn(o,a);let y=f`SELECT id, _creationTime, ${f.identifier(ie)} FROM ${f.identifier(i)}`;E.length>0&&(y=f`${y} WHERE ${f.join(E,f` AND `)}`),y=f`${y} ORDER BY _creationTime DESC, id ASC LIMIT ${f.raw(String(Ur(s)))}`;const u=K(n,y).toArray(),C=[];for(const I of u){const A=mn(I);if(!A)continue;const x=dr(Yn(A,o.definition),g);x>0&&C.push({creationTime:typeof A._creationTime=="number"?A._creationTime:0,doc:A,id:typeof A._id=="string"?A._id:"",score:x})}return C.sort((I,A)=>A.score-I.score||A.creationTime-I.creationTime||I.id.localeCompare(A.id)),C.slice(0,s).map(I=>({document:I.doc,score:I.score}))},wt=(n,i,o,s)=>{if(!Number.isFinite(n.lat)||n.lat<-90||n.lat>90||!Number.isFinite(n.lng)||n.lng<-180||n.lng>180)throw new R("BAD_REQUEST",`geo index "${s}" on table "${o}": ${i} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},jr=(n,i)=>{const o=n,s={near:(a,w)=>{if(o.within)throw new R("INTERNAL",`geo index "${o.indexName}" on table "${i}": call .near() or .within(), not both`);if(wt(a,".near() point",i,o.indexName),!Number.isFinite(w)||w<=0)throw new R("BAD_REQUEST",`geo index "${o.indexName}" on table "${i}": .near() radiusMeters must be a finite number > 0, got ${String(w)}`);return o.near={point:{lat:a.lat,lng:a.lng},radiusMeters:w},s},within:a=>{if(o.near)throw new R("INTERNAL",`geo index "${o.indexName}" on table "${i}": call .near() or .within(), not both`);if(wt(a.sw,".within() sw corner",i,o.indexName),wt(a.ne,".within() ne corner",i,o.indexName),a.sw.lat>a.ne.lat)throw new R("BAD_REQUEST",`geo index "${o.indexName}" on table "${i}": .within() corners are transposed (sw.lat > ne.lat)`);if(a.sw.lng>a.ne.lng)throw new R("BAD_REQUEST",`geo index "${o.indexName}" on table "${i}": .within() box crosses the antimeridian (sw.lng > ne.lng), which is not supported — split it into two boxes at ±180 and union the results`);return o.within={ne:{lat:a.ne.lat,lng:a.ne.lng},sw:{lat:a.sw.lat,lng:a.sw.lng}},s}};return s},Hr=(n,i)=>{const o=n[i];if(o===null||typeof o!="object")return;const{lat:s,lng:a}=o;return typeof s=="number"&&typeof a=="number"?{lat:s,lng:a}:void 0},Kr=(n,i)=>{const o=Hr(n,i.definition.field);if(!o)return;const s=typeof n._creationTime=="number"?n._creationTime:0;if(i.near){const a=So(i.near.point,o);return a<=i.near.radiusMeters?{creationTime:s,distance:a}:void 0}return _o(o,i.within)?{creationTime:s,distance:0}:void 0},Nr=(n,i,o,s)=>{if(!o.near&&!o.within)throw new R("INTERNAL",`geo index "${o.indexName}" on table "${i}": call .near(point, radius) or .within(box)`);const a=o.near?Ro(o.near.point,o.near.radiusMeters):vo(o.within),w=$o(i,o.indexName),g=a.map(I=>f`(g.${f.identifier("__geohash__")} >= ${I} AND g.${f.identifier("__geohash__")} < ${`${I}{`})`),E=[f`(${f.join(g,f` OR `)})`];s&&E.push(s);const y=f`SELECT m.id, m._creationTime, m.${f.identifier(ie)} FROM ${f.identifier(w)} g JOIN ${f.identifier(i)} m ON m.id = g.${f.identifier("__id__")} WHERE ${f.join(E,f` AND `)}`,u=K(n,y).toArray(),C=[];for(const I of u){const A=Ce(I),x=A?Kr(A,o):void 0;A&&x&&C.push({creationTime:x.creationTime,distance:x.distance,doc:A})}return C.sort((I,A)=>I.distance-A.distance||A.creationTime-I.creationTime),C},Dn=(n,i,o,s)=>{const a=[];for(const w of n)if(i.every(g=>g(s(w)))&&(a.push(w),typeof o=="number"&&a.length>=o))break;return a},Qr=(n,i,o,s,a,w=()=>{})=>{const g=o.within!==void 0,E=Nr(n,i,o,a).map(y=>({distanceMeters:g?null:y.distance,document:y.doc}));return w(E.length),typeof s=="number"?E.slice(0,Math.max(0,Math.floor(s))):E},ln=(n,i,o,s,a,w,g=()=>{})=>{const{geo:E}=o;if(!E)throw new R("INTERNAL","runGeoTerminalScored called without a staged geo query");const y=a.length>0,u=Qr(n,i,E,y?void 0:w,s,g);return y?Dn(u,a,w,C=>C.document):u},un=(n,i,o)=>{const s=n.shape[i];if(s!==void 0&&rr(s))throw new R("BAD_REQUEST",`${o}: "${i}" may hold an order-preserving key rather than a value SQL can reduce or group — declare an aggregateIndex covering this (by, field, op) so the maintained companion answers it instead (its running total is a REAL, so it stays exact only while the total is inside 2^53)`)},Vr=n=>{let i=0;const o=[],s={...Ze,relationExists:a=>{const{childWhere:w,negated:g,parentTable:E,relation:y}=a,u=`__rel_${String(i)}`,C=o.at(-1)??E;i+=1,n(y.table,G);const I=y.kind==="one"?y.field:y.references,A=y.kind==="one"?y.references:y.field,x=Je(`${Qt(u,A)} = ${Qt(C,I)}`);o.push(u);const q=ee(w,s,Xe);o.pop();const P=q===void 0?x:Me(x," AND ",q),W=Me("EXISTS (SELECT 1 FROM ",en(y.table)," AS ",en(u)," WHERE ",P,")");return g?Me("NOT ",W):W}};return s};class Jr extends R{constructor(i="unique() found more than one matching document"){super("NOT_UNIQUE",i,{name:"NotUniqueError"})}}const zr=/\s/u,Yr=String.fromCodePoint(0),fn=(n,i,o)=>{if(!n.tables[i])throw new R("INTERNAL",`unknown table: ${i}`);return typeof o!="string"||o.length===0||zr.test(o)||o.includes(Yr)?null:o},kn=(n,i,o,s=()=>{},a=()=>{},w=()=>{},g)=>{const E=i.tables[o];if(!E)throw new R("INTERNAL",`unknown table: ${o}`);const y=be(E.softDeleteMode,void 0),u=g??{indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[],verifyFilters:[]},C=()=>{const v=Q(y,u.pushedWhere);return v?ee(v,pe):void 0},I=()=>{const v=Q(y,u.pushedWhere);return v?ee(v,Ze,Xe):void 0},A=()=>[...u.inMemoryFilters,...u.verifyFilters];let x=0;const q=v=>{const{search:D}=u;if(!D)throw new R("INTERNAL","runSearchFetch called without a staged search");oo(go(n),o,E);const k=u.inMemoryFilters.length>0,F=$r(k?void 0:v),L=yo(n);if(L&&!ro(n,o,D.definition))throw new R("SEARCH_INDEX_BUILDING",`search index "${D.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 Ee=C(),ne=L?Or(n,o,D,F,Ee):Gr(n,o,D,F,Ee);!k&&v===void 0&&fr(ne);const le=A();return x=ne.length,le.length>0?Dn(ne,le,v,Y=>Y.document):ne},P=v=>q(v).map(D=>D.document),W=v=>{const D=gr(v);return yr(P(hr(D)),D)},U=()=>{if(u.search||u.geo||u.indexName===void 0){a(void 0);return}a(Oo(o,u.indexName,u.indexFields,u.sqlConditions,De))},j=v=>{U();let D=0;const k=(()=>{if(u.search){const F=P(v);return D=x,F}return u.geo?ln(n,o,u,C(),A(),v,F=>{D=F}).map(F=>F.document):mt(n,o,E,u,I(),{filters:A(),selective:u.inMemoryFilters.length>0,want:v===void 0?void 0:Math.max(0,Math.floor(v))},F=>{D+=F}).documents})();return w(Math.max(D,k.length)),k},te=()=>{if(!u.search&&!u.geo)throw new R("INTERNAL",`ctx.db.query("${o}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);U();let v=0;const D=(()=>{if(u.search){const k=q(void 0);return v=x,k}return ln(n,o,u,C(),A(),void 0,k=>{v=k})})();return w(Math.max(v,D.length)),D},V={async*[Symbol.asyncIterator](){const v=kn(n,i,o,s,a,w,{...u,indexFields:[...u.indexFields],inMemoryFilters:[...u.inMemoryFilters],sqlConditions:[...u.sqlConditions],verifyFilters:[...u.verifyFilters]});if(u.search){yield*await v.collect();return}let D;for(;;){const k=await v.paginate({cursor:D??null,numItems:qr});if(yield*k.page,k.isDone||k.continueCursor===null)return;D=k.continueCursor}},async collect(){return j(void 0)},async collectWithScores(){return te()},filter(v){const D=Go(v);return D!==void 0&&jo(D,E.shape)?(u.pushedWhere=Q(u.pushedWhere,D),u.verifyFilters.push(v)):u.inMemoryFilters.push(v),V},async first(){return j(1)[0]??null},order(v){return u.order=v==="desc"?"desc":"asc",V},async paginate(v){let D=0;if(U(),u.search){const F=W(v);return w(F.page.length),F}if(u.geo)throw new R("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const k=Ir(n,o,E,u,v,I(),{all:A(),selective:u.inMemoryFilters.length>0},F=>{D+=F});return w(Math.max(D,k.page.length)),k},async take(v){return j(v)},async unique(){const v=j(2);if(v.length>1)throw new Jr(`unique() on table "${o}" matched ${String(v.length)} documents; expected at most one`);return v[0]??null},withGeoIndex(v,D){const k=(E.geoIndexes??[]).find(L=>L.name===v);if(!k)throw new R("INTERNAL",`unknown geo index "${v}" on table "${o}"`);s(o,v,"geo");const F={definition:k,indexName:v};if(u.geo=F,D(jr(F,o)),!F.near&&!F.within)throw new R("INTERNAL",`geo index "${v}" on table "${o}" requires a .near(point, radius) or .within(box) call`);return V},withIndex(v,D){const k=E.indexes.find(F=>F.name===v);if(!k)throw new R("INTERNAL",`unknown index "${v}" on table "${o}"`);return s(o,v,"index"),u.indexName=v,u.indexFields=k.fields,D&&D(Pr(u)),V},withSearchIndex(v,D){const k=(E.searchIndexes??[]).find(L=>L.name===v);if(!k)throw new R("INTERNAL",`unknown search index "${v}" on table "${o}"`);s(o,v,"search");const F={definition:k,field:k.field,filters:[],hasQuery:!1,indexName:v,query:""};if(u.search=F,D(ur(F,o,_t(k.language))),!F.hasQuery)throw new R("INTERNAL",`search index "${v}" on table "${o}" requires a .search(field, query) call`);return V}};return V},pt=(n,i,o,s)=>{const a=o;for(const[w,g]of po(n)){if(g.serverDefault){w in i&&(a[w]=g.serverDefault({auth:s}));continue}g.onUpdateFn&&!(w in i)&&(a[w]=g.onUpdateFn())}},hn=5,wn=(n,i)=>{for(const o of Object.keys(i))if(i[o]===void 0)throw new R("INTERNAL",`Cannot ${n} field '${o}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},pn=["_commitSeq","_creationTime","_id"],Qe=n=>pn.some(i=>i in n)?Object.fromEntries(Object.entries(n).filter(([i])=>!pn.includes(i))):n,Xr=/unique constraint failed/i,Zr=n=>n instanceof Error&&Xr.test(n.message),ei=/string or blob too big/iu,ti=(n,i)=>{if(!(!(n instanceof Error)||!ei.test(n.message)))throw new R("PAYLOAD_TOO_LARGE",`document is too large to store in "${i}": a single row cannot exceed the storage engine's per-row ceiling (2 MB on a Durable Object's SQLite). The limit is on the STORED bytes, which are UTF-8, and v.bytes()/v.bigint() columns are stored twice on a shard-local table. Keep the payload in R2 (ctx.storage) and store a reference on the row.`)},vt=(n,i,o,s)=>{try{ye(n,o,...s)}catch(a){throw Zr(a)?new de(`unique constraint violation on "${i}"`,"unique"):(ti(a,i),a)}},Ve=(n,i,o,s)=>{if(vt(n,i,o,s),ye(n,Mr).one().changed===0)throw new de(`optimistic concurrency conflict on "${i}" — the row changed during this mutation; refetch and retry`,"occ")},gn=(n,i,o,s,a,w,g)=>{const E=[];for(let I=0;I<o.length+1;I+=1){const A=o[I],x=s[I],q=x?.direction==="desc"?"desc":"asc",P=A===void 0||x===void 0?f`${f.identifier(Wo)} < ${g}`:Bo(A,w[I],q,!1);if(P===void 0)continue;const W=[];for(let j=0;j<I;j+=1)W.push(f`${f.identifier(o[j])} IS ${w[j]}`);W.push(P);const[U]=W;E.push(W.length===1&&U!==void 0?U:f`(${f.join(W,f` AND `)})`)}const y=E.length>0?f.join(E,f` OR `):f`1 = 0`,u=K(n,f`SELECT COUNT(*) AS c FROM ${f.identifier(i)} WHERE ${f.identifier("__partition__")} = ${a} AND (${y})`).one(),C=K(n,f`SELECT COUNT(*) AS c FROM ${f.identifier(i)} WHERE ${f.identifier("__partition__")} = ${a}`).one();return{before:u.c,total:C.c}},ni=n=>{const i=new Map;for(const[s,a]of Object.entries(n.tables))for(const w of Object.values(a.relationMap??{}))w.kind==="one"&&(w.onDelete==="cascade"||w.onDelete==="set null")&&i.set(w.table,[...i.get(w.table)??[],{holder:s,op:w.onDelete==="cascade"?"delete":"update"}]);const o=s=>{const a=new Set,w=[s];for(let g=w.pop();g!==void 0;g=w.pop())for(const{holder:E,op:y}of i.get(g)??[]){if(E===s||tn(n,E,y))return!0;a.has(E)||(a.add(E),w.push(E))}return!1};return new Set(Object.entries(n.tables).filter(([s,a])=>a.shardMode?.kind==="global"||tn(n,s,"delete")||o(s)).map(([s])=>s))},oi=n=>{const i=new Map;for(const[o,s]of Object.entries(n.tables))s.softDeleteMode&&i.set(o,s.softDeleteMode.field);return i},gt=new WeakMap,ri=(n,i)=>{let o=gt.get(i.tables);if(!gt.has(i.tables)){const a=Object.keys(i.tables).map(w=>w.replaceAll(/[$()*+.?[\\\]^{|}]/gu,String.raw`\$&`));o=a.length===0?void 0:new RegExp(`"(${a.join("|")})"`,"gu"),gt.set(i.tables,o)}if(o===void 0)return;const s=new Set;for(const a of n.matchAll(o))s.add(a[1]);return s.size===1?[...s][0]:void 0},ii=(n,i,o)=>{for(const s of n){const a=s,w=a?.[ie];if(typeof w=="string"){const g=a?.id,E=mo(w);typeof g!="string"?i.recordReadBytes(E):o===void 0?i.recordDocumentRead(`${g}\0${String(E)}`,E):i.recordDocumentRead(`${o}\0${g}`,E)}}},si=(n,i,o)=>{if(i===void 0)return n;const s=(a,...w)=>{const g=n.exec(a,...w),E=g.one.bind(g),y=g[Symbol.iterator].bind(g),u=o===void 0?void 0:ri(a,o);let C=!1;const I=A=>{ii(A,i,u)};return g.toArray=()=>{const A=[];for(const x of{[Symbol.iterator]:y})I([x]),A.push(x);return A},g.one=()=>{C=!0;try{const A=E();return I([A]),A}finally{C=!1}},g[Symbol.iterator]=function*(){for(const x of{[Symbol.iterator]:y})C||I([x]),yield x},g};return new Proxy(n,{get:(a,w)=>w==="exec"?s:w===ho?a:Reflect.get(a,w,a)})},ci=new Map([["findFirst","rows"],["findFirstOrThrow","rows"],["findMany","page"],["get","rows"],["lookupById","lookup"],["rankPage","page"]]),ai=new Map([["collect","rows"],["collectWithScores","scored"],["first","rows"],["paginate","page"],["take","rows"],["unique","rows"]]),xe=(n,i,o)=>{if(typeof n!="object"||n===null)return;const s=Eo(n);if(s===void 0)return;const a=n._id;typeof a=="string"?o.recordDocumentRead(`global\0${i}\0${a}`,s):o.recordReadBytes(s)},Ye=(n,i,o,s)=>{if(typeof n!="object"||n===null)return;const a=n;switch(i){case"lookup":{xe(a.row,typeof a.tableName=="string"?a.tableName:o,s);return}case"page":{for(const w of a.page??[])xe(w,o,s);return}case"rows":{for(const w of Array.isArray(n)?n:[n])xe(w,o,s);return}default:for(const w of Array.isArray(n)?n:[])xe(w.document,o,s)}},Ln=(n,i,o)=>new Proxy(n,{get:(s,a)=>{const w=Reflect.get(s,a,s);if(typeof w!="function")return w;if(a===Symbol.asyncIterator)return async function*(){for await(const y of Reflect.apply(w,s,[]))xe(y,i,o),yield y};const g=ai.get(a);return(...E)=>{const y=Reflect.apply(w,s,E);return g!==void 0?Promise.resolve(y).then(u=>(Ye(u,g,i,o),u)):typeof y=="object"&&y!==null&&!(y instanceof Promise)?Ln(y,i,o):y}}}),di=new Set(["findFirst","findFirstOrThrow","findMany"]),li=n=>{const i=n[1],o=i?.select;if(!Array.isArray(o))return;const s=Object.fromEntries(Object.entries(i).filter(([g])=>g!=="select")),a=s.with,w=g=>_n(g,o,a);return{args:[n[0],s,...n.slice(2)],project:(g,E)=>typeof g!="object"||g===null?g:E==="page"?{...g,page:w(g.page)}:w([g])[0]}},yn=256,St=4096,ui=1024*1024,fi=async(n,i,o,s)=>{const a=i[1]??{},w=[];let{cursor:g}=a,E=yn,y=0;for(;;){const u=await n([i[0],{...a,cursor:g,limit:E},...i.slice(2)]);if(Array.isArray(u))return Ye(u,"rows",o,s),[...w,...u];const C=s.headroom().readBytes;if(Ye(u,"page",o,s),w.push(...u.page),u.isDone||typeof u.continueCursor!="string")return{continueCursor:null,isDone:!0,page:w};g=u.continueCursor,y+=s.headroom().readBytes-C,E=y>0?Math.min(St,Math.max(yn,Math.floor(ui*w.length/y))):St}},hi=(n,i)=>n===void 0||i===void 0?n:new Proxy(n,{get:(o,s)=>{const a=Reflect.get(o,s,o);if(typeof a!="function")return a;if(s==="query")return(...g)=>Ln(Reflect.apply(a,o,g),String(g[0]),i);const w=ci.get(s);return w===void 0?a:async(...g)=>{const E=di.has(s)?li(g):void 0;let y=E?.args??g;const u=String(g[0]),C=y[1],I=s==="findMany"&&typeof C?.endCursor=="string",A=s==="findMany"&&typeof C?.limit!="number"&&!I;if(I&&typeof C.limit!="number"&&(y=[y[0],{...C,limit:St},...y.slice(2)]),A){const q=await fi(P=>Reflect.apply(a,o,P),y,u,i);return E===void 0?q:E.project(q,w)}const x=await Reflect.apply(a,o,y);return Ye(x,w,u,i),E===void 0?x:E.project(x,w)}}}),$n=new WeakMap,En=new WeakMap,wi=500,pi=n=>{const{baselineSeq:i,onStalePatchDropped:o}=n,{headroom:s}=n,a=$n.get(n)??{value:void 0},w=En.get(n)??{value:0};let g;const E=()=>{if(g===void 0){const e={...n,enforceRls:!1,headroom:void 0};$n.set(e,a),En.set(e,w),g=pi(e)}return g},y=si(n.sql,s,n.schema),{schema:u}=n,C=n.broadcast??(()=>{}),I=(e,t)=>{if(!Object.hasOwn(u.tables,e))throw new R("BAD_REQUEST",`${t}: "${e}" is not a table in this schema`)},A=Ho(u),x=new Map;for(const e of A){const t=r=>(u.tables[r]?.shardMode?.kind??"root")==="root";!e.array&&t(e.sourceTable)&&t(e.targetTable)&&x.set(e.sourceTable,[...x.get(e.sourceTable)??[],e])}const q=(e,t,r)=>{for(const c of x.get(e)??[]){const l=t[c.column];if(typeof l!="string"||r?.[c.column]===l||c.targetTable===e&&t._id===l)continue;if(K(y,f`SELECT 1 FROM ${f.identifier(c.targetTable)} WHERE id = ${l} LIMIT 1`).toArray().length===0)throw new R("VALIDATION_ERROR",`${c.name} references ${c.targetTable} row "${l}", which does not exist`)}},P=zo(u,n.inTransaction),W=ni(u),U=oi(u),j=()=>n.inTransaction?.()===!0,te=e=>u.tables[e]?.commitOrderedMode!==!0?{}:((a.value===void 0||!j())&&(a.value=co(y)),{[ao]:a.value}),V=(e,...t)=>{const r=u.tables[e]?.indexes??[],c=[];let l;for(const p of t)p&&(typeof p._id=="string"&&p._id!==l&&(l=p._id,c.push(qo(l))),c.push(...Po(r,Uo(r,p,De))));return c.length>0?c:void 0},v=n.onRead??(()=>{}),D=e=>{Kt(u.tables[e])&&v(Zt,Zt)},k=n.onReadRange??(e=>{v(e.table,G)}),F=e=>{D(e.table),k(e)},L=(e,t,r)=>{t!==void 0&&(r===!0||t!==G)&&s?.recordRead(1),D(e),v(e,t,r)},Ee=(e,t)=>{const r=e.row._id;L(e.tableName,typeof r=="string"?r:t,typeof r=="string")},ne=n.onIndexUse??(()=>{}),le=n.onWrite??(()=>{}),Y=e=>{s?.recordWrite(e)},me=async e=>{Y(e.doc),await le(e)},{cache:ue}=n,Re=n.clock??(()=>Date.now()),At=n.idGenerator??(()=>crypto.randomUUID()),It=n.scheduler??Zn,ve=hi(n.globalDb,s),fe=n.auth??{identity:null,userId:null},bt=n.cdc??!1,tt=It,Fn=ir({scheduler:typeof tt.list=="function"&&typeof tt.get=="function"?tt:void 0,storage:n.storage}),Se=(e,t,r,c)=>{bt&&!Kt(u.tables[e])&&io(y,Re(),e,t,r,c)},xt=(e,t,r,c)=>{const l=u.tables[e];if(l?.dropStalePatchesMode!==!0||!bt)return!1;const p=i?.();if(p===void 0)return!1;const d=so(y,e,t,p);if(d===void 0)return!1;const h=bo(l,r);return Object.keys(Qe(r)).some(m=>!h.has(m)&&jt(Vt(d,m))!==jt(Vt(c,m)))},se=e=>u.tables[e]?.shardMode?.kind==="global",Ct=(e,t)=>{if(se(e)){if(!ve)throw new R("INTERNAL",`cross-backend ${t} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return ve}return O},nt=e=>Ct(e,"cascade"),H=(e,t)=>{if(se(e)){if(!ve)throw new R("INTERNAL",`${t} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return ve}},_e=(e,t)=>{L(e,G);for(const r of Qo(Q(t.baseWhere,t.where),u,e,t.relationBaseWhere))L(r,G)},ce=(e,t,r)=>{ue?.invalidateTable(t),C({key:r,op:e,table:t})},Mt=async(e,t,r,c,l)=>{l&&Y(r);const p=await e.insert(t,r,c);return C({key:p,op:"insert",row:{...r,_id:p},table:t}),p},Wn=(e,t)=>Ct(e,"relation load").findMany(e,t),Bn=e=>e.through===void 0?[e.table]:[e.through.table,e.table],Dt=e=>{for(const t of e===void 0?[]:Bn(e))se(t)&&L(t,G)},kt=(e,t)=>{const r=u.tables[e]?.relationMap??{};for(const[c,l]of Object.entries(t??{})){if(c==="_count"){for(const d of Object.keys(typeof l=="object"?l:{}))Dt(r[d]);continue}const p=r[c];p===void 0||l===void 0||l===!1||(Dt(p),typeof l=="object"&&kt(p.table,l.with))}},ot=(e,t)=>(se(e)&&(L(e,G),kt(e,t.with)),Wn(e,t)),qn=e=>!se(e.table),Lt=n.relationExistsPushDown??"auto",Ft=Lt!=="never",{maxRelationKeys:Wt}=n,Le=(e,t,r)=>Vo(e,{fetcher:ot,maxRelationKeys:Wt,relationBaseWhere:r,schema:u,tableName:t}),Pn=async(e,t,r,c,l)=>{const p=H(e,"relation grouped count");if(p)return _e(e,{relationBaseWhere:l,where:c}),tr((B,N)=>p.count(B,{relationBaseWhere:l,where:N}),e,t,r,c);const d=u.tables[e];if(!d)throw new R("INTERNAL",`unknown table: ${e}`);L(e,G);const h=be(d.softDeleteMode,void 0),m={[t]:{in:r}},M=Q(Q(m,c),h),_=await Le(M,e,l),T=ee(_,pe),S=ge(t);let b=f`SELECT ${S} AS __fk__, COUNT(*) AS count FROM ${f.identifier(e)}`;T&&(b=f`${b} WHERE ${T}`),b=f`${b} GROUP BY ${S}`;const $=K(y,b).toArray();return new Map($.map(B=>[B.__fk__,B.count]))},Bt=new Set;for(const[e,t]of Object.entries(u.tables))for(const r of Object.values(t.triggerMap??{}))Bt.add(`${e} ${r.timing} ${r.op}`);const oe=(e,t,r)=>Bt.has(`${e} ${t} ${r}`),re=async(e,t,r)=>{if(w.value+=1,w.value>cn)throw w.value-=1,new de(`trigger recursion exceeded ${String(cn)} levels on "${r.table}" — check for a self-triggering write`,"trigger");try{await sr({ctx:Vn,event:r,op:t,schema:u,tableName:r.table,timing:e})}finally{w.value-=1}},{ensureBackfilledForTable:Te,ensureBackfilledIndex:rt,ensureRankBackfilled:it,ensureRankBackfilledForTable:Ae,syncAggregates:Fe,syncCompanionsForInsert:st,syncGeo:We,syncRanks:he,syncSearch:Be}=lo({broadcast:C,indexKeysFor:(e,t)=>V(e,t),invalidateCache:(e,t,r)=>ue?.invalidate(e,t,V(e,r)),recordCdc:Se,schema:u,sql:y,verified:n.companionMemo?.verified}),Un=async(e,t)=>{const r=t.filter(({document:c,id:l})=>{try{return st(e,l,c),!0}catch(p){return console.warn(`[@lunora/shard-engine] insertManyUnsafe: companions of committed row "${l}" in "${e}" could not be synced:`,p),!1}});for(const{document:c,id:l}of r)if(X(l,e)?.docJson===ae(c))try{await le({doc:c,id:l,op:"insert",table:e})}catch(p){console.warn(`[@lunora/shard-engine] insertManyUnsafe: write report of committed row "${l}" in "${e}" failed:`,p)}},qt=(e,t,r)=>{const{shardMode:c}=t;if(c?.kind==="shardBy"&&!(c.field!==void 0&&(r.partitionBy??[]).includes(c.field)))throw Object.assign(new Error(`rank index "${r.name}" on "${e}" partitions across shards (shard key "${c.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})},Pt=e=>Object.entries(u.tables).filter(([,t])=>t.shardMode?.kind!=="global").map(([t])=>t).filter(t=>e===void 0||t===e),Ie=e=>e===void 0||se(e)?ve:void 0,On=e=>Object.entries(u.tables).flatMap(([t,r])=>se(t)?Object.values(r.relationMap??{}).flatMap(c=>c.through!==void 0||c.kind!=="one"||c.table!==e?[]:c.onDelete!=="cascade"&&c.onDelete!=="set null"?[]:[{action:c.onDelete==="cascade"?"delete":"update",field:c.field,holderTable:t,references:c.references}]):[]),Gn=async(e,t,r,c)=>r==="_id"?c:(await e.get(t,c))?.[r],jn=async(e,t,r,c,l)=>{const p=[];let d;do{const h=await e.findMany(t,{cursor:d,includeDeleted:l,limit:wi,where:{[r]:c}});for(const m of h.page)p.push(String(m._id));d=h.isDone?void 0:h.continueCursor??void 0}while(d!==void 0&&p.length<=nr);return p},Hn=async(e,t,r,c,l,p)=>{const{action:d,field:h,holderTable:m,references:M}=r,_=await Gn(e,t,M,c);if(_==null)return{effects:[],toExpand:[]};const T=await jn(e,m,h,_,p),S=T.filter($=>!l.announced.has(`${d}:${m}:${$}`)),b=d==="delete"?T.filter($=>!l.expanded.has(`${m}:${$}`)):[];for(const $ of S)l.announced.add(`${d}:${m}:${$}`);for(const $ of b)l.expanded.add(`${m}:${$}`);return{effects:S.map($=>({id:$,op:d,table:m})),toExpand:b}},Ut=async(e,t,r,c,l)=>{const p=[];for(const d of On(t))for(const h of r){const m=await Hn(e,t,d,h,c,l);p.push(...m.effects),m.toExpand.length>0&&p.push(...await Ut(e,d.holderTable,m.toExpand,c,l))}return p},ct=async(e,t,r,c,l)=>{for(let d=0;d<r.length;d+=1)Y(void 0);const p=c?.skipOnDelete===!0?[]:await Ut(e,t,r,{announced:new Set,expanded:new Set},c?.hard===!0);try{if(l!==void 0&&e.deleteMany!==void 0)try{return await e.deleteMany(t,r,l.options)}finally{for(const d of r)ce("delete",t,d)}for(const d of r)try{await e.delete(t,d,c)}finally{ce("delete",t,d)}return{deleted:r.length}}finally{for(const d of p)ce(d.op,d.table,d.id)}},X=(e,t)=>{const r=Pt(t);for(let c=0;c<r.length;c+=an){const l=r.slice(c,c+an),[p]=ye(y,kr(l),...Lr(e,l)).toArray();if(!p)continue;const d=p.__t__,h=Ce(p);if(typeof d!="string"||!h)return;const m=p[ie];return{docJson:typeof m=="string"?m:ae(m??{}),row:h,tableName:d}}},Ot={assertRankPartitionLocal:qt,ensureRankBackfilled:it,onRead:L,rowToDocument:Ce,schema:u,sql:y},Kn=(e,t,r)=>{const c=ee(r,pe);return c===void 0||K(y,f`SELECT 1 FROM ${f.identifier(e)} WHERE ${f.identifier("id")} = ${t} AND ${c}`).toArray().length>0},Nn=(e,t,r,c)=>xt(e,t,r,c)?(o?.({fields:Object.keys(Qe(r)),id:t,table:e}),!0):!1,Qn=async(e,t,r,c,l)=>{const p=X(t,e);if(!p)return{applied:!1,doc:null};if(L(e,t),!Kn(e,t,r.where)||Nn(e,t,r.patch,p.row))return{applied:!1,doc:p.row};try{await l(r.patch)}catch(d){if(d instanceof de&&d.kind==="occ"&&c)return;throw d}return{applied:!0,doc:X(t,e)?.row??null}},Gt=async(e,t,r,c)=>{const{fetchLimit:l,limit:p,orderKeys:d,predicate:h}=await Jo(t,r,{canPushExists:Ft?qn:void 0,existsPushMode:Lt==="always"?"always":"auto",fetcher:ot,maxRelationKeys:Wt,schema:u,tableName:e}),m=Ft?Vr(c):Ze,M=ee(h,m,Xe),_=bn(e,M,xn(d),l);return{limit:p,orderKeys:d,statement:_}},O={system:Fn,async aggregate(e,t){const r=H(e,"aggregate");if(r)return _e(e,t),r.aggregate(e,t);const c=u.tables[e];if(!c)throw new R("INTERNAL",`unknown table: ${e}`);if(Oe(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 R("INTERNAL",`aggregate(${e}, { op: "${t.op}" }): "field" is required for non-count reducers`);L(e,G);const l=be(c.softDeleteMode,void 0),p=Q(Q(t.baseWhere,t.where),l),d=await Le(p,e,t.relationBaseWhere),h=d!==p;if(c.aggregateIndexes&&!t.baseWhere&&!h){const $=no(c.aggregateIndexes,t.op,t.field,t.where);if($){rt(e,$.index);const B=dt($.index.by??[],$.key),N=at(e,$.index.name),J=K(y,f`SELECT ${Ge} AS value, ${ft} AS count FROM ${f.identifier(N)} WHERE ${je} = ${B}`).toArray()[0];return lt(t.op,J)}}un(c,t.field,`aggregate(${e}, { op: "${t.op}", field: "${t.field}" })`);const m=ee(d,pe),M=Oe(t.op),_=ge(t.field);let T=f`SELECT ${f.raw(M)}(${_}) AS value FROM ${f.identifier(e)}`;m&&(T=f`${T} WHERE ${m}`);const b=K(y,T).toArray()[0]?.value;return b??null},asId(e,t){const r=fn(u,e,t);if(r===null)throw new R("BAD_REQUEST",`asId("${e}", …): "${t}" is not a valid id for table "${e}"`,{status:400});return r},async count(e,t){const r=H(e,"count");if(r)return _e(e,Ht(t)),r.count(e,t);const c=u.tables[e];if(!c)throw new R("INTERNAL",`unknown table: ${e}`);const l=Ht(t);if(l.restrictsCounts)throw new ut(e);L(e,G);const p=be(c.softDeleteMode,void 0),d=Q(Q(l.baseWhere,l.where),p),h=await Le(d,e,l.relationBaseWhere),m=h!==d;if(c.aggregateIndexes&&!l.baseWhere&&!m){const S=to(c.aggregateIndexes,l.where);if(S){rt(e,S.index);const b=dt(S.index.by??[],S.key),$=at(e,S.index.name),B=K(y,f`SELECT ${Ge} AS value FROM ${f.identifier($)} WHERE ${je} = ${b}`).toArray();return B[0]===void 0?0:B[0].value??0}}const M=ee(h,pe);let _=f`SELECT COUNT(*) AS count FROM ${f.identifier(e)}`;return M&&(_=f`${_} WHERE ${M}`),K(y,_).one().count},async delete(e,t,r){I(e,"ctx.db.delete(table, id)");const c=X(t,e);if(!c){const S=Ie(e);S&&await ct(S,e,[t],r);return}const{docJson:l,row:p,tableName:d}=c,h=u.tables[d],m=r?.hard===!0,M=!m&&h?.softDeleteMode?h:void 0,_=M?.softDeleteMode?.field;if(_&&p[_]!==null&&p[_]!==void 0)return;if(oe(d,"before","delete")&&await re("before","delete",{id:t,op:"delete",previous:p,table:d}),r?.skipOnDelete!==!0&&await er({deletedId:t,deletedReference:S=>p[S],findHolders:async(S,b,$,B)=>(await nt(S).findMany(S,{...B,includeDeleted:m,where:{[b]:$}})).page,onCascade:(S,b)=>nt(S).delete(S,b,r),onRestrict:S=>{throw new de(S,"restrict")},onSetNull:(S,b,$)=>nt(S).patch(S,b,{[$]:null}),schema:u,tableName:d}),Te(d),Ae(d),M&&_){const S={[_]:Re()},b={...p,...te(d),...S,_id:t};pt(M,S,b,fe),Ve(y,d,rn(d),[ae(b),t,l]),Be(d,t,b,p),We(d,t,void 0),Fe(d,p,b),he(d,t,p,void 0);const $=V(d,p,b);ue?.invalidate(d,t,$),Se(d,t,"update",b),C({indexKeys:$,key:t,op:"update",row:b,table:d}),oe(d,"after","delete")&&await re("after","delete",{id:t,op:"delete",previous:p,table:d}),await me({id:t,op:"delete",table:d});return}Ve(y,d,Cr(d),[t,l]),Be(d,t,void 0),We(d,t,void 0),Fe(d,p,void 0),he(d,t,p,void 0);const T=V(d,p);ue?.invalidate(d,t,T),Se(d,t,"delete"),C({indexKeys:T,key:t,op:"delete",table:d}),oe(d,"after","delete")&&await re("after","delete",{id:t,op:"delete",previous:p,table:d}),await me({id:t,op:"delete",table:d})},async deleteAll(e,t){if(!u.tables[e])throw new R("INTERNAL",`unknown table: ${e}`);if(s!==void 0)return E().deleteAll(e,t);const r=Math.max(1,t?.chunkSize??Tn),c=t?.hard===void 0?void 0:{hard:t.hard},l=H(e,"deleteAll");let p=0;for(;;){const h=(await O.findMany(e,{includeDeleted:t?.hard===!0,limit:r})).page.map(m=>String(m._id));if(h.length===0)break;for(const m of h)await(l===void 0?O.delete(e,m,c):ct(l,e,[m],c)),p+=1;if(h.length<r)break}return{deleted:p}},async deleteMany(e,t,r){I(e,"ctx.db.deleteMany(table, ids)"),Ne(t.length,r?.limit,"deleteMany");for(const c of t)await O.delete(e,c);return{deleted:t.length}},async deleteWhere(e,t,r){const c=H(e,"deleteWhere"),p=(await dn(c??O,e,t,r?.limit,"deleteWhere")).map(d=>String(d._id));if(c)return ct(c,e,p,void 0,{options:r});if(O.deleteMany===void 0)throw new R("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return O.deleteMany(e,p,r)},async findFirst(e,t={}){return(await O.findMany(e,{...t,limit:1,omitContinueCursor:!0})).page[0]??null},async findFirstOrThrow(e,t={}){const r=await O.findFirst(e,t);if(r===null)throw new To(`findFirstOrThrow: no "${e}" document matched`);return r},async findMany(e,t={}){const r=H(e,"findMany");if(r)return _e(e,t),t.consistency==="primary"&&v(e,uo),r.findMany(e,t);const c=u.tables[e];if(!c)throw new R("INTERNAL",`unknown table: ${e}`);const l=!t.where&&!t.baseWhere;l?L(e,G):L(e);const{limit:p,orderKeys:d,statement:h}=await Gt(e,c,t,L),m=ye(y,h.text,...h.params).toArray();l&&s?.recordRead(m.length);const M=[];for(const T of m){const S=Ce(T);S&&(M.push(S),!l&&typeof S._id=="string"&&L(e,S._id))}const _=No(M,{endCursor:t.endCursor,limit:p,omitContinueCursor:t.omitContinueCursor,orderKeys:d});return t.with&&await Xo({fetcher:ot,groupedCounter:Pn,parents:_.page,...Zo(t),schema:u,tableName:e,with:t.with}),{..._,page:_n(_.page,t.select,t.with)}},async explain(e,t={}){const r=H(e,"explain");if(r)return r.explain(e,t);const c=u.tables[e];if(!c)throw new R("INTERNAL",`unknown table: ${e}`);const{statement:l}=await Gt(e,c,t,()=>{}),p=ye(y,`EXPLAIN QUERY PLAN ${l.text}`,...l.params).toArray();return{params:l.params,plan:p.map(d=>String(d.detail)),sql:l.text}},async get(e,t){I(e,"ctx.db.get(table, id)");const r=X(t,e);if(!r){const c=Ie(e);return c?(v(e,t,!0),c.get(e,t)):(D(e),v(e,t,!0),null)}return Ee(r,t),r.row},async lookupById(e,t){const r=X(e,t);if(!r){for(const c of Pt(t))D(c),v(c,e,!0);return null}return Ee(r,e),{row:r.row,tableName:r.tableName}},async groupBy(e,t){const r=H(e,"groupBy");if(r)return _e(e,t),r.groupBy(e,t);const c=u.tables[e];if(!c)throw new R("INTERNAL",`unknown table: ${e}`);L(e,G);const l=t.agg??{op:"count"};if(Oe(l.op),l.op!=="count"&&!l.field)throw new R("INTERNAL",`groupBy(${e}, { agg: { op: "${l.op}" } }): "field" is required for non-count reducers`);const p=be(c.softDeleteMode,void 0),d=Q(Q(t.baseWhere,t.where),p),h=await Le(d,e,t.relationBaseWhere),m=h!==d;if(c.aggregateIndexes&&!t.baseWhere&&!m){const $=eo(c.aggregateIndexes,l.op,l.field,t.by,t.where),B=$===void 0?0:Object.keys($.partial).length,N=$?.index.by?.length??0;if($&&(B===0||B===N)){rt(e,$.index);const J=at(e,$.index.name),z=Object.keys($.partial),we=[];if(z.length===($.index.by??[]).length&&z.length>0){const qe=dt($.index.by??[],$.partial),Pe=K(y,f`SELECT ${Ge} AS value, ${ft} AS count FROM ${f.identifier(J)} WHERE ${je} = ${qe}`).toArray();return Pe.length>0&&we.push({key:{...$.partial},value:lt(l.op,Pe[0])}),we}const Jn=K(y,f`SELECT ${je} AS key, ${Ge} AS value, ${ft} AS count FROM ${f.identifier(J)}`).toArray();for(const qe of Jn){const Pe=Xn(JSON.parse(qe.key));we.push({key:Pe,value:lt(l.op,qe)})}return we}}for(const $ of[...t.by,l.field]){if($===void 0)continue;const B=$===l.field?`groupBy(${e}, { agg: { op: "${l.op}", field: "${$}" } })`:`groupBy(${e}, { by: [..."${$}"] })`;un(c,$,B)}const M=ee(h,pe),_=t.by.map($=>f`${ge($)} AS ${f.identifier($)}`);if(l.op==="count")_.push(f`COUNT(*) AS value`);else{const{field:$}=l;if($===void 0)throw new R("INTERNAL",`groupBy(${e}, { agg: { op: "${l.op}" } }): "field" is required for non-count reducers`);_.push(f`${f.raw(Oe(l.op))}(${ge($)}) AS value`)}let T=f`SELECT ${f.join(_,f`, `)} FROM ${f.identifier(e)}`;M&&(T=f`${T} WHERE ${M}`),T=f`${T} GROUP BY ${f.join(t.by.map($=>ge($)),f`, `)}`;const S=K(y,T).toArray(),b=[];for(const $ of S){const B={};for(const J of t.by)B[J]=wo(c.shape[J],$[J]??null);const{value:N}=$;b.push({key:B,value:N==null?null:Number(N)})}return b},async insert(e,t,r){const c=H(e,"insert");if(c)return Mt(c,e,t,r,!0);const l=u.tables[e];if(!l)throw new R("INTERNAL",`unknown table: ${e}`);const p=r?.allowExplicitId===!0,d=He(l,Et(l,t,fe),{supplied:t,trusted:p});let h;r?.clientId!==void 0?(Wr(r.clientId),h=r.clientId):r?.allowExplicitId&&typeof d._id=="string"?(Rt(d._id),h=d._id):h=At();const m=r?.allowExplicitId&&typeof d._creationTime=="number"?d._creationTime:Re(),M={...d,...te(e),_creationTime:m,_id:h};return oe(e,"before","insert")&&await re("before","insert",{doc:{...M},id:h,op:"insert",table:e}),p||q(e,M),Te(e),Ae(e),vt(y,e,br(e),[h,m,ae(M)]),st(e,h,M),oe(e,"after","insert")&&await re("after","insert",{doc:M,id:h,op:"insert",table:e}),await me({doc:M,id:h,op:"insert",table:e}),h},async insertManyUnsafe(e,t,r){if(Ne(t.length,r?.limit,"insertManyUnsafe"),t.length===0)return[];const c=H(e,"insert");if(c){const _=[];Br(u.tables[e],t,r?.allowExplicitId,fe);for(const T of t)Y(T);for(const T of t){const S=await c.insert(e,T,{allowExplicitId:r?.allowExplicitId});C({key:S,op:"insert",row:{...T,_id:S},table:e}),_.push(S)}return _}const l=u.tables[e];if(!l)throw new R("INTERNAL",`unknown table: ${e}`);Te(e),Ae(e);const p=[];for(let _=0;_<t.length;_+=Ke)p.push(te(e));const d=r?.allowExplicitId===!0?void 0:Yo(l),h=t.map((_,T)=>{const S=Et(l,_,fe),b=d===void 0?S:He(d,S,{supplied:_}),$=r?.allowExplicitId===!0&&typeof b._id=="string"?b._id:void 0;$!==void 0&&Rt($);const B=$??At(),N=r?.allowExplicitId===!0&&typeof b._creationTime=="number"?b._creationTime:Re(),J={...b,...p[Math.floor(T/Ke)],_creationTime:N,_id:B};return{creationTime:N,document:J,id:B}});for(const _ of h)Y(_.document);const m=async _=>{for(const{document:T,id:S}of _)st(e,S,T);for(const{document:T,id:S}of _)await le({doc:T,id:S,op:"insert",table:e})};let M=0;try{for(let _=0;_<h.length;_+=Ke){const T=h.slice(_,_+Ke),S=f.join(T.map($=>f`(${$.id}, ${$.creationTime}, ${ae($.document)})`),f`, `),b=Rn("sqlite",f`INSERT INTO ${f.identifier(e)} (id, _creationTime, ${f.identifier(ie)}) VALUES ${S}`);vt(y,e,b.sql,b.params),M=_+T.length}}catch(_){throw await Un(e,h.slice(0,M)),_}return await m(h),h.map(_=>_.id)},async insertMany(e,t,r){Ne(t.length,r?.limit,"insertMany");const c=r?.skipDuplicates===!0,l=[],p=H(e,"insert");if(p)for(const h of t)Y(h);const d=async h=>p?Mt(p,e,h,void 0,!1):O.insert(e,h);for(const h of t)try{l.push(await d(h))}catch(m){if(c&&m instanceof de&&m.kind==="unique")l.push(null);else throw m}return l},normalizeId(e,t){return fn(u,e,t)},async patch(e,t,r,c){I(e,"ctx.db.patch(table, id, values)");const l=X(t,e);if(!l){const b=Ie(e);if(b){Y(r);try{await b.patch(e,t,r,c)}finally{ce("update",e,t)}return}throw new R("NOT_FOUND",`document not found: ${t}`)}const{docJson:p,row:d,tableName:h}=l,m=u.tables[h];if(!m)throw new R("INTERNAL",`unknown table: ${h}`);if(L(h,t),wn("patch",r),xt(h,t,r,d)){o?.({fields:Object.keys(Qe(r)),id:t,table:h});return}const M=Ao(m,r,d),_={...d,...Qe(M),...te(h),_id:t};pt(m,M,_,fe);const T=He(m,_,{only:new Set(Object.keys(M)),previous:()=>d,tolerateStoredNull:!0});Io(c,d,T),oe(h,"before","update")&&await re("before","update",{doc:{...T},id:t,op:"update",previous:d,table:h}),q(h,T,d),Te(h),Ae(h),Ve(y,h,rn(h),[ae(T),t,p]),Be(h,t,T,d),We(h,t,T),Fe(h,d,T),he(h,t,d,T);const S=V(h,d,T);ue?.invalidate(h,t,S),Se(h,t,"update",T),C({indexKeys:S,key:t,op:"update",row:T,table:h}),oe(h,"after","update")&&await re("after","update",{doc:T,id:t,op:"update",previous:d,table:h}),await me({doc:T,id:t,op:"update",table:h})},async patchIf(e,t,r){const c=H(e,"patchIf");if(c){if(c.patchIf===void 0)throw new R("INTERNAL",`ctx.db.patchIf on global table '${e}' is unsupported: its backend has no conditional write`);Y(r.patch);let l;try{l=await c.patchIf(e,t,r)}catch(p){throw ce("update",e,t),p}return l.applied&&ce("update",e,t),l}if(!u.tables[e])throw new R("INTERNAL",`unknown table: ${e}`);for(let l=1;l<=hn;l+=1){const p=await Qn(e,t,r,l<hn,d=>O.patch(e,t,d,{verify:r.verify}));if(p!==void 0)return p}throw new de(`patchIf on "${e}" kept conflicting; the row changed on every attempt`,"occ")},async patchMany(e,t,r){I(e,"ctx.db.patchMany(table, patches)"),Ne(t.length,r?.limit,"patchMany");for(const c of t)await O.patch(e,c.id,c.patch);return{patched:t.length}},async patchWhere(e,t,r){const c=H(e,"patchWhere")??O,p=(await dn(c,e,t.where,r?.limit,"patchWhere")).map(d=>({id:String(d._id),patch:t.patch}));if(O.patchMany===void 0)throw new R("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await O.patchMany(e,p,r),{patched:p.length}},async related(e,t){return Ko(O,A,e,t)},relationEdges:A,deleteRereadTables:W,inTransaction:j,softDeleteFields:U,relationWrites:P,query(e){const t=H(e,"query");return t?(L(e,G),t.query(e)):kn(y,u,e,ne,r=>{r?F(r):L(e,G)},r=>{s?.recordRead(r)})},async rank(e,t,r){const c=H(e,"rank");if(ne(e,t,"rank"),c)return L(e,G),c.rank(e,t,r);const l=u.tables[e];if(!l)throw new R("INTERNAL",`unknown table: ${e}`);const p=l.rankIndexes?.find(z=>z.name===t);if(!p)throw new R("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(qt(e,l,p),r.restrictsCounts)throw new ut(e);L(e,G),it(e,p);const d=typeof r.row=="string"?r.row:r.row._id;if(!d)return null;const h=Yt(e,p.name),m=p.sortBy.map((z,we)=>Xt(we)),M=m.map(z=>ke(z)).join(", "),_=K(y,f`SELECT ${f.identifier("__partition__")}, ${f.raw(M)} FROM ${f.identifier(h)} WHERE ${f.identifier("__id__")} = ${d}`).toArray(),[T]=_;if(T===void 0)return null;let S=T.__partition__;const b=Q(r.baseWhere,r.where);ht(b,u,e,"rank");const $=Lo(p,b);if($){const z=Fo(p.partitionBy??[],$);if(z!==S)return null;S=z}const B=m.map(z=>T[z]),{before:N,total:J}=gn(y,h,m,p.sortBy,S,B,d);return{position:N+1,total:J}},async rankBefore(e,t,r){if(se(e))throw new R("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const c=u.tables[e];if(!c)throw new R("INTERNAL",`unknown table: ${e}`);const l=c.rankIndexes?.find(m=>m.name===t);if(!l)throw new R("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(r.restrictsCounts)throw new ut(e);L(e,G),it(e,l);const p=Yt(e,l.name),d=l.sortBy.map((m,M)=>Xt(M)),h=l.sortBy.map((m,M)=>De(r.sortValues[M]??null));return gn(y,p,d,l.sortBy,r.partitionKey,h,r.rowId)},async rankPage(e,t,r={}){ht(Q(r.baseWhere,r.where),u,e,"rankPage");const c=H(e,"rankPage");if(ne(e,t,"rank"),c)return L(e,G),c.rankPage(e,t,r);const{continueCursor:l,hasMore:p,rows:d}=Nt(Ot,e,t,r);return{continueCursor:l,isDone:!p,page:d.map(h=>h.doc)}},async rankPageRows(e,t,r={}){ht(Q(r.baseWhere,r.where),u,e,"rankPage"),ne(e,t,"rank");const{directions:c,hasMore:l,rows:p}=Nt(Ot,e,t,r);return{directions:c,hasMore:l,rows:p}},async restore(e,t){I(e,"ctx.db.restore(table, id)");const r=X(t,e);if(!r){const d=Ie(e);if(d?.restore){try{await d.restore(e,t)}finally{ce("update",e,t)}return}throw new R("NOT_FOUND",`document not found: ${t}`)}const c=u.tables[r.tableName]?.softDeleteMode?.field;if(!c)throw new R("INTERNAL",`ctx.db.restore: table "${r.tableName}" is not a .softDelete() table`);const l=r.row[c]!==null&&r.row[c]!==void 0;await O.patch(e,t,{[c]:null});const p=l?X(t,e)?.row:void 0;p&&(he(r.tableName,t,p,void 0),he(r.tableName,t,void 0,p))},async replace(e,t,r,c){I(e,"ctx.db.replace(table, id, document)");const l=X(t,e);if(!l){const B=Ie(e);if(B){Y(r);try{await B.replace(e,t,r,c)}finally{ce("update",e,t)}return}throw new R("NOT_FOUND",`document not found: ${t}`)}const{docJson:p,row:d,tableName:h}=l,m=u.tables[h];if(!m)throw new R("INTERNAL",`unknown table: ${h}`);wn("replace",r);const M=c?.allowExplicitId&&typeof r._creationTime=="number"?r._creationTime:void 0,_=typeof d._creationTime=="number"?d._creationTime:void 0,T=M??_??Re(),S={...r,...te(h),_creationTime:T,_id:t};pt(m,r,S,fe);const b=c?.allowExplicitId===!0,$=He(m,S,{previous:()=>d,supplied:r,trusted:b});oe(h,"before","update")&&await re("before","update",{doc:{...$},id:t,op:"update",previous:d,table:h}),b||q(h,$,d),Te(h),Ae(h),Ve(y,h,xr(h),[T,ae($),t,p]),Be(h,t,$,d),We(h,t,$),Fe(h,d,$),he(h,t,d,$),ue?.invalidate(h,t,V(h,d,$)),Se(h,t,"update",$),C({indexKeys:V(h,d,$),key:t,op:"update",row:$,table:h}),oe(h,"after","update")&&await re("after","update",{doc:$,id:t,op:"update",previous:d,table:h}),await me({doc:$,id:t,op:"update",table:h})},async wipeShard(e){const t=new Set(e?.exclude),r=e?.tables,c=Object.entries(u.tables).filter(([h,m])=>t.has(h)||r!==void 0&&!r.includes(h)?!1:m.shardMode?.kind!=="global").map(([h])=>h);if(r!==void 0){for(const h of r)if(!u.tables[h])throw new R("INTERNAL",`wipeShard: unknown table: ${h}`)}const l={};let p=0;const{deleteAll:d}=O;if(d===void 0)throw new R("INTERNAL","wipeShard: this writer has no deleteAll");for(const h of c){const m=await d(h,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});l[h]=m.deleted,p+=m.deleted}return{deleted:p,tables:l}}},Vn={db:O,scheduler:It};return n.enforceRls===!0?or(O,u,(e,t)=>X(e,t)?.tableName,A):O};export{cs as CDC_LOG_TABLE,xs as IDEMPOTENCY_TABLE,Jr as NotUniqueError,Ts as advanceClientWatermark,as as applyCdcChanges,wn as assertNoExplicitUndefined,Rt as assertStorableRowId,Wr as assertValidClientId,os as backfillAggregateIndexes,rs as backfillRankIndexes,is as backfillSearchIndexes,ds as bumpCdcEpoch,ls as cdcCanVouchFor,us as cdcForkedError,fs as cdcSeqLeavingRows,hs as cdcTouchesTables,ws as cdcTrimmedError,ps as compactCdcDocs,pi as createShardCtxDb,gs as cursorBelowRetainedFloor,si as meterReadBytes,As as migrateClientWatermark,ys as minCdcReplayableSeq,$s as minCdcSeq,fn as normalizeIdStructurally,Es as readCdcChangeKeys,ms as readCdcChanges,Rs as readCdcCursor,vs as readCdcEpoch,Is as readClientWatermark,Cs as readIdempotent,Ls as runShardMigrations,Ws as selectShapeMembers,Bs as selectShapeRows,Qe as stripReservedPatchFields,Ss as trimCdcChanges,Ms as trimIdempotent,Ds as writeIdempotent};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{isLunoraError as S}from"@lunora/errors";import{l as R,b as L}from"./ctx-db-search-state-CPKPy8N6.mjs";import{sql as e}from"drizzle-orm";import{readKeysetPage as _}from"./backfillAggregateIndexes-
|
|
1
|
+
import{isLunoraError as S}from"@lunora/errors";import{l as R,b as L}from"./ctx-db-search-state-CPKPy8N6.mjs";import{sql as e}from"drizzle-orm";import{readKeysetPage as _}from"./backfillAggregateIndexes-DNVOUEEW.mjs";import{runDrizzle as p}from"./runDrizzle-RC09zZrh.mjs";import{h}from"./do-sql-105TONaE.mjs";const u="__lunora_vector_backfill",m=50,k=20,w=20,N=3,O=i=>{p(i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(u)} (${e.identifier("companion")} TEXT PRIMARY KEY, ${e.identifier("cursor")} TEXT, ${e.identifier("done")} INTEGER NOT NULL DEFAULT 0, ${e.identifier("profile")} TEXT, ${e.identifier("strikes")} INTEGER NOT NULL DEFAULT 0)`);try{p(i,e`ALTER TABLE ${e.identifier(u)} ADD COLUMN ${e.identifier("strikes")} INTEGER NOT NULL DEFAULT 0`)}catch{}},C=(i,o)=>{const[s]=p(i,e`SELECT ${e.identifier("strikes")} FROM ${e.identifier(u)} WHERE ${e.identifier("companion")} = ${o}`).toArray();return s?.strikes??0},$=(i,o,s,d,t,r=0)=>{const n=s??null;p(i,e`INSERT INTO ${e.identifier(u)} (${e.identifier("companion")}, ${e.identifier("cursor")}, ${e.identifier("done")}, ${e.identifier("profile")}, ${e.identifier("strikes")}) VALUES (${o}, ${n}, ${d?1:0}, ${t}, ${r}) ON CONFLICT (${e.identifier("companion")}) DO UPDATE SET ${e.identifier("cursor")} = excluded.${e.identifier("cursor")}, ${e.identifier("done")} = excluded.${e.identifier("done")}, ${e.identifier("profile")} = excluded.${e.identifier("profile")}, ${e.identifier("strikes")} = excluded.${e.identifier("strikes")}`)},A=(i,o,s)=>{const d=_(i,o,s,m+1),t={documents:[],lastId:s,more:d.length>m,unparseable:[]};for(const r of d.slice(0,m)){if(typeof r.id!="string")continue;t.lastId=r.id;const n=h(r);n?t.documents.push({doc:n,id:t.lastId}):t.unparseable.push(t.lastId)}return t},D=(i,o,s,d,t)=>{const r=t instanceof Error?t.message:String(t),n=L(i,u,o),a=n.profile===d&&n.cursor===s?C(i,o):0;if(S(t)&&t.code==="SERVICE_UNAVAILABLE")return a>0&&$(i,o,s,!1,d,0),{error:r};const f=a+1;if(f<N)return $(i,o,s,!1,d,f),{error:r};const c=A(i,o,s),l=[...c.documents.map(E=>E.id),...c.unparseable];return console.warn(`[@lunora/shard-engine] vector backfill: a page of "${o}" failed ${String(f)} times in a row; its ${String(l.length)} row(s) are recorded as failed:`,t),{failedIds:l,page:c}},F=async(i,o,s,d,t)=>{const{profile:r,table:n}=o;try{const{failures:a,page:f}=await t(()=>A(i,n,s),async c=>({failures:await d(n,c.documents),page:c}));return a.length>0&&console.warn(`[@lunora/shard-engine] vector backfill: ${String(a.length)} row(s) of "${n}" could not be indexed:`,a),{failedIds:[...f.unparseable,...a.map(c=>c.id)],page:f}}catch(a){return D(i,n,s,r,a)}},y=async(i,o,s,d)=>{if(O(i),d.restart===!0)for(const{profile:n,table:a}of o)$(i,a,void 0,!1,n);const t=Math.min(d.maxPages??1,k),r={done:!1,failed:0,failedIds:[],pages:0,rows:0};for(const{profile:n,table:a}of o){const f=R(L(i,u,a),n);let{cursor:c}=f,l=f.finished;for(;!l;){if(r.pages>=t)return r;const E=await F(i,{profile:n,table:a},c,s,d.ordered);if("error"in E)return{...r,error:E.error};const{failedIds:g,page:T}=E,I=T.documents.length+T.unparseable.length;r.pages+=I>0?1:0,r.rows+=I,r.failed+=g.length,r.failedIds=[...r.failedIds,...g].slice(0,w),c=T.lastId,l=!T.more,$(i,a,c,l,n)}}return{...r,done:!0}};export{k as VECTOR_BACKFILL_MAX_PAGES,m as VECTOR_BACKFILL_PAGE_ROWS,y as backfillVectorIndexes};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{m as P,c as E,l as w,r as T,a as D,w as F}from"./ctx-db-search-state-CPKPy8N6.mjs";import{S as I,c as L,g as _,d as x,e as b,a as k}from"./fts-companion-CE3EmIjk.mjs";import{sql as i}from"drizzle-orm";import{ensureAggregateCompanion as y,ensureRankCompanion as B}from"./createCompanionSync-
|
|
1
|
+
import{m as P,c as E,l as w,r as T,a as D,w as F}from"./ctx-db-search-state-CPKPy8N6.mjs";import{S as I,c as L,g as _,d as x,e as b,a as k}from"./fts-companion-CE3EmIjk.mjs";import{sql as i}from"drizzle-orm";import{ensureAggregateCompanion as y,ensureRankCompanion as B}from"./createCompanionSync-C7nzg7f-.mjs";import{runDrizzle as p,runAll as C}from"./runDrizzle-RC09zZrh.mjs";import{i as M,D as m,h as A}from"./do-sql-105TONaE.mjs";import{sqliteInList as U}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";const v=(e,o)=>p(e,i`SELECT 1 FROM ${i.identifier(o)} LIMIT 1`).toArray().length>0,Q=(e,o)=>{for(const[r,n]of Object.entries(o.tables))if(n.shardMode?.kind!=="global")for(const t of n.aggregateIndexes??[])y(e,r,t,n.softDeleteMode?.field)},X=(e,o)=>{for(const[r,n]of Object.entries(o.tables))if(n.shardMode?.kind!=="global")for(const t of n.rankIndexes??[])B(e,r,t,n.softDeleteMode?.field)},H=(e,o,r,n)=>p(e,r===void 0?i`SELECT id, _creationTime, ${i.identifier(m)} FROM ${i.identifier(o)} ORDER BY id ASC LIMIT ${i.raw(String(n))}`:i`SELECT id, _creationTime, ${i.identifier(m)} FROM ${i.identifier(o)} WHERE id > ${r} ORDER BY id ASC LIMIT ${i.raw(String(n))}`).toArray(),h=500,O=(e,o,r)=>{const n=I(o,r.name),t=E(r),a=w(T(e,n),t);if(a.finished)return{done:!0,rows:0};const{cursor:c}=a,s=H(e,o,c,h);let f=c;for(const g of s){const{id:u}=g;if(typeof u!="string")continue;f=u;const S=A(g);C(e,S?x(n,u,b(S,r)):k(n,u))}const d=s.length<h;return F(e,n,f,d,t),{done:d,rows:s.length}},l=(e,o)=>i`${i.identifier(e)}.${i.identifier(o)}`,R=500,$=(e,o,r)=>{const n=I(o,r.name),t=p(e,L(n,R)).toArray(),a=_(t);if(a.size===0)return!0;const c=new Map;for(const s of p(e,i`SELECT ${l(o,"id")}, ${l(o,"_creationTime")}, ${l(o,m)} FROM ${i.identifier(o)} WHERE ${U(l(o,"id"),[...a.keys()],!1)}`))c.set(String(s.id),s);for(const[s,f]of a){const d=c.get(s),g=d?A(d):void 0;C(e,g?x(n,s,b(g,r),{unmappedRowids:f}):k(n,s,{unmappedRowids:f}))}return t.length<R},W=(e,o,r,n)=>{let t=0;for(;t<n&&!$(e,o,r);)t+=1;return t},Z=(e,o,r)=>{const n=I(o,r.name),t=E(r);return w(T(e,n),t).finished?!0:D(e,n)},q=(e,o,r)=>{if(M(e))for(const n of r.searchIndexes??[])$(e,o,n),!(n.staged&&v(e,o))&&O(e,o,n)},j=(e,o,r,n)=>{let t=0;for(;;){if(t>=n)return{done:!1,pages:t};const a=O(e,o,r);if(a.rows>0&&(t+=1),a.done)return{done:!0,pages:t}}},ee=(e,o,r={})=>{if(!M(e))return{done:!0,pages:0};P(e);const n=r.maxPages??Number.POSITIVE_INFINITY;let t=0;for(const[a,c]of Object.entries(o.tables))if(!(c.shardMode?.kind==="global"||!c.searchIndexes))for(const s of c.searchIndexes){if(t+=W(e,a,s,n-t),t>=n)return{done:!1,pages:t};const f=j(e,a,s,n-t);if(t+=f.pages,!f.done)return{done:!1,pages:t}}return{done:!0,pages:t}};export{Q as backfillAggregateIndexes,X as backfillRankIndexes,ee as backfillSearchIndexes,q as backfillSearchIndexesForTable,H as readKeysetPage,Z as searchIndexCoversTable};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{N as uo,S as $o,d as Eo,e as go,a as po}from"./fts-companion-CE3EmIjk.mjs";import{sql as o}from"drizzle-orm";import{r as Q}from"./json-field-path-DeJW4U9z.mjs";import{matchesStaticWhere as J,aggregateSqlFunction as mo}from"./AGGREGATE_SQL_FUNCTION-C_ZipS9R.mjs";import{aggregateTableName as B,foldAggregateTally as Z,encodeAggregateKey as v,coerceAggregateNumber as H}from"./aggregateTableName-B_CtIQCS.mjs";import{aggregateSignature as ho,readCompanionSignature as N,rankSignature as So,writeCompanionSignature as x}from"./CompanionMemo-jmlDbPlr.mjs";import{runAll as _o,runDrizzle as g}from"./runDrizzle-RC09zZrh.mjs";import{i as yo,g as Ro,a as D,b as A,A as _,c as j,D as oo,u as eo,r as no,e as q}from"./do-sql-105TONaE.mjs";import{WORKERD_SQLITE_LIMITS as to,param as G}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{encodeGeohash as To,GEO_DEFAULT_PRECISION as Ao}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{isLiveForCompanion as W}from"./CURSOR_PREFIX-rOdoinP8.mjs";import{rankTableName as P,matchesRankStaticWhere as ro,sortColumnName as wo,encodePartitionKey as Co}from"./RANK_TIEBREAK-D3ye2GsL.mjs";import{mayHoldProjectedValue as Io}from"./BIGINT_KEY_DIGITS-DE6yshOt.mjs";import{serializeSqlValue as so}from"./serializeSqlValue-DeoBMpZ2.mjs";const Oo=(s,f,t)=>[...s.partitionBy??[],...s.sortBy.map(l=>l.field),...s.where?Object.keys(s.where):[]].every(l=>Q(f,l)===Q(t,l)),io=s=>o.join(["__id__","__partition__",...s.sortBy.map((f,t)=>wo(t))].map(f=>o.identifier(f)),o`, `),co=(s,f,t)=>{const u=Co(s.partitionBy??[],t),l=s.sortBy.map(r=>so(t[r.field]??null)),a=o.join([f,u,...l].map(r=>G(r)),o`, `);return o`(${a})`},ko=(s,f,t,u,l,a)=>{g(s,o`INSERT INTO ${o.identifier(f)} (${u}) VALUES ${co(t,l,a)}`)},X=1e3,ao=function*(f,t,u,l){let a;for(;;){const r=a===void 0?o``:o` WHERE id > ${G(a)}`,m=[...g(eo(f),o`SELECT id, _creationTime, ${o.identifier(oo)} FROM ${o.identifier(t)}${r} ORDER BY id LIMIT ${G(X)}`)];for(const h of m){const R=no(h);R&&W(R,u)&&l(R)&&(yield R)}if(m.length<X)return;a=String(m.at(-1)?.id)}},vo=(s,f,t,u,l)=>{const a=B(f,t.name),r=t.by??[],m=new Map;for(const w of ao(s,f,u,I=>!t.where||J(I,t.where)))Z(m,v(r,w),t,w);g(s,o`DELETE FROM ${o.identifier(a)}`);const h=Math.floor(to.boundParams/3),R=[...m];for(let w=0;w<R.length;w+=h){const I=R.slice(w,w+h),V=o.join(I.map(([b,F])=>o`(${b}, ${F.value}, ${F.count})`),o`, `);g(s,o`INSERT INTO ${o.identifier(a)} (${D}, ${A}, ${_}) VALUES ${V}`)}x(s,a,l)},Lo=(s,f,t,u)=>{const l=ho(t,u);N(s,B(f,t.name))!==l&&vo(s,f,t,u,l)},Do=(s,f,t,u,l)=>{const a=P(f,t.name),r=io(t);g(s,o`DELETE FROM ${o.identifier(a)}`);const m=Math.max(1,Math.floor(to.boundParams/(2+t.sortBy.length)));let h=[];const R=()=>{h.length>0&&(g(s,o`INSERT INTO ${o.identifier(a)} (${r}) VALUES ${o.join(h,o`, `)}`),h=[])};for(const w of ao(s,f,u,I=>!t.where||ro(I,t.where)))h.push(co(t,w._id,w)),h.length>=m&&R();R(),x(s,a,l)},Fo=(s,f,t,u)=>{const l=So(t,u);N(s,P(f,t.name))!==l&&Do(s,f,t,u,l)},Mo=(s,f,t,u,l,a,r)=>{if(a&&r&&W(a,u)===W(r,u)&&Oo(t,a,r))return;const m=P(f,t.name);a&&g(s,o`DELETE FROM ${o.identifier(m)} WHERE ${o.identifier("__id__")} = ${l}`),!(!r||!W(r,u)||t.where&&!ro(r,t.where))&&ko(s,m,t,io(t),l,r)},Jo=s=>{const{broadcast:f,indexKeysFor:t,invalidateCache:u,recordCdc:l,schema:a,sql:r}=s,m=s.verified??new Set,h=e=>a.tables[e]?.softDeleteMode?.field,R=(e,n)=>{const c=B(e,n.name);m.has(c)||(Lo(r,e,n,h(e)),m.add(c))},w=(e,n,c)=>{const p=n.by??[],d=n.field??"",E=[],y=(i,$)=>{const S=so($);S===null?E.push(o`${q(i)} IS NULL`):E.push(o`${q(i)} = ${S}`)};for(const i of p)y(i,c[i]??null);const C=h(e);C!==void 0&&y(C,null);for(const[i,$]of Object.entries(n.where??{}))y(i,$!==null&&typeof $=="object"&&!Array.isArray($)?$.eq:$);const L=E.length>0?o` WHERE ${o.join(E,o` AND `)}`:o``,M=a.tables[e]?.shape[d];if(M&&Io(M)){const i=g(eo(r),o`SELECT id, _creationTime, ${o.identifier(oo)} FROM ${o.identifier(e)}${L}`).toArray(),$=new Map;for(const S of i){const k=no(S);k&&Z($,"",n,k)}return{value:$.get("")?.value??null}}const U=mo(n.op),T=q(d);return{value:g(r,o`SELECT ${o.raw(U)}(${T}) AS value FROM ${o.identifier(e)}${L}`).one().value??null}},I=(e,n,c,p)=>{const d=B(e,n.name),{op:E}=n,y=n.field??"",C=i=>{g(r,o`DELETE FROM ${o.identifier(d)} WHERE ${D} = ${i} AND ${_} <= 0`)},L=h(e),M=i=>!n.where||J(i,n.where),U=i=>W(i,L)&&M(i);p!==void 0&&E!=="count"&&M(p)&&H(p[y]);const T=c&&U(c)?c:void 0,O=p&&U(p)?p:void 0;if(!(!T&&!O)){if(E==="count"){for(const[i,$]of[[T,-1],[O,1]]){if(!i)continue;const S=v(n.by??[],i);g(r,j(d,S,$,$,o`${A} = ${A} + excluded.${A}, ${_} = ${_} + excluded.${_}`))}T&&C(v(n.by??[],T));return}if(E==="sum"||E==="avg"){for(const[i,$]of[[T,-1],[O,1]]){if(!i)continue;const S=H(i[y]);if(S===void 0)continue;const k=v(n.by??[],i);g(r,j(d,k,$*S,$,o`${A} = COALESCE(${A}, 0) + excluded.${A}, ${_} = ${_} + excluded.${_}`))}T&&C(v(n.by??[],T));return}if(T){const i=v(n.by??[],T),$=H(T[y]),S=g(r,o`SELECT ${A} AS value, ${_} AS count FROM ${o.identifier(d)} WHERE ${D} = ${i}`).toArray()[0],k=(S?.count??0)-1;if(k<=0)g(r,o`DELETE FROM ${o.identifier(d)} WHERE ${D} = ${i}`);else if(S&&$!==void 0&&S.value!==null&&$===S.value){const lo=w(e,n,T);g(r,o`UPDATE ${o.identifier(d)} SET ${A} = ${lo.value}, ${_} = ${k} WHERE ${D} = ${i}`)}else g(r,o`UPDATE ${o.identifier(d)} SET ${_} = ${_} - 1 WHERE ${D} = ${i}`)}if(O){const i=v(n.by??[],O),$=H(O[y]);if($===void 0)g(r,j(d,i,null,1,o`${_} = ${_} + 1`));else{const S=E==="min"?"MIN":"MAX";g(r,j(d,i,$,1,o`${A} = ${o.raw(S)}(COALESCE(${A}, excluded.${A}), excluded.${A}), ${_} = ${_} + 1`))}}}},V=e=>{for(const n of a.tables[e]?.aggregateIndexes??[])R(e,n)},b=(e,n,c)=>{for(const p of a.tables[e]?.aggregateIndexes??[])I(e,p,n,c)},F=(e,n)=>{const c=P(e,n.name);m.has(c)||(Fo(r,e,n,h(e)),m.add(c))},fo=e=>{for(const n of a.tables[e]?.rankIndexes??[])F(e,n)},K=(e,n,c,p)=>{for(const d of a.tables[e]?.rankIndexes??[])Mo(r,e,d,h(e),n,c,p)},z=(e,n,c,p)=>{const d=a.tables[e]?.searchIndexes??[];if(!(d.length===0||!yo(r)))for(const E of d){if(uo(p,c,E))continue;const y=$o(e,E.name);_o(r,c?Eo(y,n,go(c,E)):po(y,n))}},Y=(e,n,c)=>{for(const p of a.tables[e]?.geoIndexes??[]){const d=Ro(e,p.name);g(r,o`DELETE FROM ${o.identifier(d)} WHERE ${o.identifier("__id__")} = ${n}`);const E=c?.[p.field];if(E!==null&&typeof E=="object"&&typeof E.lat=="number"&&typeof E.lng=="number"){const{lat:y,lng:C}=E,L=To({lat:y,lng:C},p.precision??Ao);g(r,o`INSERT INTO ${o.identifier(d)} (${o.identifier("__id__")}, ${o.identifier("__geohash__")}, ${o.identifier("__lat__")}, ${o.identifier("__lng__")}) VALUES (${n}, ${L}, ${y}, ${C})`)}}};return{ensureBackfilledForTable:V,ensureBackfilledIndex:R,ensureRankBackfilled:F,ensureRankBackfilledForTable:fo,syncAggregates:b,syncCompanionsForInsert:(e,n,c)=>{z(e,n,c),Y(e,n,c),b(e,void 0,c),K(e,n,void 0,c),u(e,n,c),l(e,n,"insert",c),f({indexKeys:t(e,c),key:n,op:"insert",row:c,table:e})},syncGeo:Y,syncRanks:K,syncSearch:z}};export{Jo as createCompanionSync,Lo as ensureAggregateCompanion,Fo as ensureRankCompanion};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createShardCtxDb as C}from"./NotUniqueError-
|
|
1
|
+
import{createShardCtxDb as C}from"./NotUniqueError-oaot-97D.mjs";import{createRelayLink as N}from"./DEFAULT_MAX_RELAYS-BZLpaaq1.mjs";import{ConflictError as q}from"./ConflictError-C8GtJmjS.mjs";import{runShardMigrations as B}from"./runShardMigrations-DBkimnd5.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/dist/packem_shared/{runShardMigrations-Bc7PsQhM.mjs → runShardMigrations-DBkimnd5.mjs}
RENAMED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{LunoraError as $}from"@lunora/errors";import{f as y,S as k}from"./fts-companion-CE3EmIjk.mjs";import{sql as t}from"drizzle-orm";import{aggregateTableName as R}from"./aggregateTableName-B_CtIQCS.mjs";import{backfillSearchIndexesForTable as w}from"./backfillAggregateIndexes-
|
|
1
|
+
import{LunoraError as $}from"@lunora/errors";import{f as y,S as k}from"./fts-companion-CE3EmIjk.mjs";import{sql as t}from"drizzle-orm";import{aggregateTableName as R}from"./aggregateTableName-B_CtIQCS.mjs";import{backfillSearchIndexesForTable as w}from"./backfillAggregateIndexes-DNVOUEEW.mjs";import{migrateCdcLog as b,migrateCdcMeta as P}from"./CDC_LOG_TABLE-BFGgqai8.mjs";import{migrateClientWatermark as B}from"./CLIENT_WATERMARK_TABLE-De7z_OHV.mjs";import{migrateCommitSeq as G}from"./COMMIT_SEQ_FIELD-Da1DjGqo.mjs";import{migrateCompanionState as Y}from"./CompanionMemo-jmlDbPlr.mjs";import{migrateGlobalShapeSnapshot as v}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-Bb6-aZuH.mjs";import{migrateIdempotency as W}from"./IDEMPOTENCY_TABLE-COrgeP3O.mjs";import{m as j}from"./ctx-db-relay-shapes-DBobAek2.mjs";import{migrateScheduleOutbox as H}from"./SCHEDULE_OUTBOX_TABLE-iyyiSjsO.mjs";import{m as K}from"./ctx-db-search-state-CPKPy8N6.mjs";import{migrateShapePokeCursor as V}from"./SHAPE_POKE_CURSOR_TABLE-BGvY3sFI.mjs";import{runDrizzle as d,runAll as z}from"./runDrizzle-RC09zZrh.mjs";import{D as Q,d as L,e as p,t as Z,i as J,g as q,a as ee,b as te,A as O}from"./do-sql-105TONaE.mjs";import{renderSql as N}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{migrateDurableStreams as re}from"./appendStreamChunk-BZYgGE9Y.mjs";import{rankTableName as x,sortColumnName as ne}from"./RANK_TIEBREAK-D3ye2GsL.mjs";import{migrateReactorState as oe}from"./REACTOR_STATE_TABLE-D2Mn204f.mjs";import{recordSchemaVersion as ie}from"./SCHEMA_HISTORY_MAX_VERSIONS-CEwFjj-O.mjs";import{ttlIndexColumns as ae}from"./isTtlExpired-DNxmZA6e.mjs";const g=t`_creationTime, id`,D="__by_creation",se="__ttl",de=`, ${N("sqlite",g).sql})`,A="__lunora_framework_indexes",f=e=>e.replaceAll(/[A-Z]/gu,r=>r.toLowerCase());class F extends ${}const M=(e,r,n,a,i,o)=>{const s=t.join(i.map(m=>t`${m} IS NOT NULL`),t` AND `);if(d(e,t`SELECT 1 FROM ${t.identifier(n)} WHERE ${s} GROUP BY ${a} HAVING COUNT(*) > 1 LIMIT 1`).toArray().length>0)throw new F("UNIQUE_INDEX_DUPLICATES",`unique index "${r}" on "${n}" ${o}: existing rows are duplicates under it. De-duplicate the table with a data migration first; the previous index is left in place.`)},S=(e,r,n,a,i,o)=>{const c=d(e,t`SELECT sql FROM sqlite_master WHERE type = 'index' AND name = ${r} COLLATE NOCASE AND tbl_name = ${n} COLLATE NOCASE`).toArray()[0]?.sql;if(c==null)return;const m=E=>{const I=E.indexOf("(");return I===-1?void 0:E.slice(I,E.lastIndexOf(")")+1)},_=m(N("sqlite",L(r,n,a,i)).sql),T=m(c);_===void 0||T===void 0||_===T||(i&&M(e,r,n,a,o,"cannot be re-created with its new column list"),d(e,t`DROP INDEX IF EXISTS ${t.identifier(r)}`))},U=(e,r,n)=>d(e,t`SELECT 1 FROM sqlite_master WHERE type = 'index' AND name = ${r} COLLATE NOCASE AND tbl_name = ${n} COLLATE NOCASE LIMIT 1`).toArray().length>0,C=(e,r,n,a,i,o)=>{i&&!U(e,r,n)&&M(e,r,n,a,o,"cannot be created"),d(e,L(r,n,a,i))},h=(e,r)=>{try{r()}catch(n){if(e===void 0||!(n instanceof F))throw n;e.push(n.message)}},ce=(e,r,n)=>f(r).startsWith(`${f(e)}_`)&&f(r)!==f(`${e}${D}`)&&n!==null&&(n.includes("json_extract(")||n.trimEnd().endsWith(de)),l=new WeakMap,u=(e,r,n)=>{let a=l.get(e);a===void 0&&(a=new Set(d(e,t`SELECT name FROM ${t.identifier(A)}`).toArray().map(i=>f(i.name))),l.set(e,a)),!a.has(f(r))&&(d(e,t`INSERT OR IGNORE INTO ${t.identifier(A)} (name, table_name) VALUES (${r}, ${n})`),a.add(f(r)))},me=(e,r)=>d(e,t`SELECT 1 FROM ${t.identifier(A)} WHERE name = ${r} COLLATE NOCASE LIMIT 1`).toArray().length>0,fe=(e,r)=>{const n=d(e,t`SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ${A} COLLATE NOCASE`).toArray().length>0;if(d(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(A)} (name TEXT PRIMARY KEY COLLATE NOCASE, table_name TEXT NOT NULL)`),!n)for(const a of r){const i=d(e,t`SELECT name, sql FROM sqlite_master WHERE type = 'index' AND tbl_name = ${a} COLLATE NOCASE AND sql IS NOT NULL`).toArray();for(const{name:o,sql:s}of i)ce(a,o,s)&&u(e,o,a)}},Ee=(e,r,n)=>{const a=new Set([...n].map(o=>f(o))),i=d(e,t`SELECT "l"."name" FROM ${t.identifier(A)} AS "l" WHERE "l"."table_name" = ${r} COLLATE NOCASE`).toArray();for(const{name:o}of i)a.has(f(o))||(d(e,t`DROP INDEX IF EXISTS ${t.identifier(o)}`),d(e,t`DELETE FROM ${t.identifier(A)} WHERE ${t.identifier(A)}."name" = ${o}`),l.get(e)?.delete(f(o)))},_e=(e,r,n,a)=>{const i=`${r}${se}`,o=new Set([...a].map(c=>f(c)));if(n.ttlPolicy===void 0||o.has(f(i))||U(e,i,r)&&!me(e,i))return;const s=ae(n.ttlPolicy.field,n.softDeleteMode?.field);a.add(i);try{S(e,i,r,s,!1,[]),d(e,L(i,r,s,!1)),u(e,i,r)}catch{}},Te=(e,r,n,a)=>{const i=new Set;for(const o of n.indexes){const s=`${r}_${o.name}`,c=o.unique??!1,m=o.fields.map(E=>p(E)),_=t.join(m,t`, `),T=c?_:t`${_}, ${g}`;i.add(s),h(a,()=>{S(e,s,r,T,c,m),C(e,s,r,T,c,m),u(e,s,r)})}for(const[o,s]of Z(n)){if(!s.unique)continue;const c=p(o),m=`${r}_unique_${o}`;i.add(m),h(a,()=>{S(e,m,r,c,!0,[c]),C(e,m,r,c,!0,[c]),u(e,m,r)})}_e(e,r,n,i),Ee(e,r,i)},Ae=(e,r,n)=>{if(!(!n.searchIndexes||n.searchIndexes.length===0||!J(e))){for(const a of n.searchIndexes)z(e,y(k(r,a.name)));w(e,r,n)}},Ie=(e,r,n)=>{if(n.geoIndexes)for(const a of n.geoIndexes){const i=q(r,a.name);d(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(i)} (${t.identifier("__id__")} TEXT PRIMARY KEY, ${t.identifier("__geohash__")} TEXT NOT NULL, ${t.identifier("__lat__")} REAL NOT NULL, ${t.identifier("__lng__")} REAL NOT NULL)`);const o=`${r}__geo_${a.name}__btree`;d(e,L(o,i,t`${t.identifier("__geohash__")} ASC, ${t.identifier("__id__")} ASC`,!1))}},Le=(e,r,n)=>{if(n.aggregateIndexes)for(const a of n.aggregateIndexes){const i=R(r,a.name);d(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(i)} (${ee} TEXT PRIMARY KEY, ${te} REAL, ${O} INTEGER NOT NULL DEFAULT 0)`),d(e,t`PRAGMA table_info(${t.identifier(i)})`).toArray().some(s=>s.name==="__count__")||d(e,t`ALTER TABLE ${t.identifier(i)} ADD COLUMN ${O} INTEGER NOT NULL DEFAULT 0`)}},Se=(e,r,n)=>{const a=d(e,t`PRAGMA table_info(${t.identifier(r)})`).toArray().map(i=>i.name).filter(i=>i.startsWith("__sort_k"));a.length>0&&(a.length!==n.length||a.some((i,o)=>i!==n[o]))&&d(e,t`DROP TABLE ${t.identifier(r)}`)},le=(e,r,n)=>{if(n.rankIndexes)for(const a of n.rankIndexes){const i=x(r,a.name),o=a.sortBy.map((E,I)=>ne(I)),s=o.map(E=>t`${t.identifier(E)} BLOB`),c=s.length>0?t`, ${t.join(s,t`, `)}`:t``;Se(e,i,o),d(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(i)} (${t.identifier("__id__")} TEXT PRIMARY KEY, ${t.identifier("__partition__")} TEXT NOT NULL${c})`);const m=[t`${t.identifier("__partition__")} ASC`];for(const[E,I]of o.entries()){const X=a.sortBy[E]?.direction;m.push(t`${t.identifier(I)} ${t.raw(X==="desc"?"DESC":"ASC")}`)}m.push(t`${t.identifier("__id__")} ASC`);const _=`${r}__rank_${a.name}__btree`,T=t.join(m,t`, `);S(e,_,i,T,!1,[]),d(e,L(_,i,T,!1))}},ve=(e,r,n={})=>{const a=n.deferBlockedUniqueIndexes?[]:void 0;l.delete(e),n.schemaSnapshot!==void 0&&ie(e,n.schemaSnapshot.hash,n.schemaSnapshot.json),K(e),fe(e,Object.entries(r.tables).filter(([,o])=>o.shardMode?.kind!=="global").map(([o])=>o));const i=[];for(const[o,s]of Object.entries(r.tables))s.shardMode?.kind!=="global"&&(d(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(o)} (
|
|
2
2
|
id TEXT PRIMARY KEY,
|
|
3
3
|
_creationTime REAL NOT NULL,
|
|
4
4
|
${t.identifier(Q)} TEXT NOT NULL
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/shard-engine",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.207",
|
|
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 R}from"@lunora/errors";import{q as St}from"./MAX_TOKEN_LENGTH-iFEGEcDL-DBPC6ZWl.mjs";import{S as Qn,l as Pe,s as Vn}from"./fts-companion-CE3EmIjk.mjs";import{decodeWire as Jn,stableWireKey as Gt}from"@lunora/wire";import{sql as f}from"drizzle-orm";import{throwingScheduler as zn,aggregateSqlFunction as Oe,normalizeCountArgument as Yn}from"./AGGREGATE_SQL_FUNCTION-C_ZipS9R.mjs";import{aggregateTableName as st,encodeAggregateKey as ct,readAggregateValue as at}from"./aggregateTableName-B_CtIQCS.mjs";import{mergeWhere as Q,CountRlsUnsupportedError as dt,selectIndexForGroupBy as Xn,selectIndexForCount as Zn,selectIndexForAggregate as eo}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{backfillSearchIndexesForTable as to,searchIndexCoversTable as no}from"./backfillAggregateIndexes-BwCpPW7h.mjs";import{backfillAggregateIndexes as ts,backfillRankIndexes as ns,backfillSearchIndexes as os}from"./backfillAggregateIndexes-BwCpPW7h.mjs";import{appendCdcChange as oo,readCdcDocAtOrBefore as ro}from"./CDC_LOG_TABLE-BFGgqai8.mjs";import{CDC_LOG_TABLE as is,applyCdcChanges as ss,bumpCdcEpoch as cs,cdcCanVouchFor as as,cdcForkedError as ds,cdcSeqLeavingRows as ls,cdcTouchesTables as us,cdcTrimmedError as fs,compactCdcDocs as hs,cursorBelowRetainedFloor as ws,minCdcReplayableSeq as ps,minCdcSeq as gs,readCdcChangeKeys as ys,readCdcChanges as Es,readCdcCursor as $s,readCdcEpoch as ms,trimCdcChanges as Rs}from"./CDC_LOG_TABLE-BFGgqai8.mjs";import{allocateCommitSeq as io,COMMIT_SEQ_FIELD as so}from"./COMMIT_SEQ_FIELD-Da1DjGqo.mjs";import{createCompanionSync as co}from"./createCompanionSync-DO92CQek.mjs";import{isMemoryTable as jt}from"./clearMemoryTables-aMRERF0w.mjs";import{computeRankPage as Ht}from"./computeRankPage-B6umzbg4.mjs";import{SCAN_DEP as G,PRIMARY_READ as ao}from"./SCAN_DEP-B4Uu4g7l.mjs";import{runSql as pe,runDrizzle as K}from"./runDrizzle-RC09zZrh.mjs";import{p as lo,j as pt,D as ie,r as xe,W as uo,k as fe,b as Ue,A as lt,a as Ge,m as he,e as we,s as fo,t as ho,u as wo,i as po,q as Kt,h as En,g as go}from"./do-sql-105TONaE.mjs";import{renderSql as $n,unionAll as mn,WORKERD_SQLITE_LIMITS as Rn}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{a as yo,u as Eo}from"./estimate-bytes-C-C35VXL.mjs";import{coveringGeohashes as $o,boundingBoxGeohashes as mo,haversineMeters as Ro,pointInBoundingBox as So}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{NotFoundError as vo}from"./NotFoundError-BhF7FeFr.mjs";import{resolvePatch as _o,assertPatchAllowed as To,operatorFields as Ao,readPatchField as Nt}from"./assertPatchAllowed-CA_H466g.mjs";import{tiebreakDirectionFor as Io,encodeCursor as gt,nullsOrderSuffix as bo,normalizeOrderKeys as Qt,uniqueIndexFields as xo,buildSeekWhere as Co,decodeCursor as Vt,buildSeekBeforeWhere as Mo,softDeleteScope as Ie,applySelect as Sn}from"./CURSOR_PREFIX-rOdoinP8.mjs";import{rankTableName as Jt,sortColumnName as zt,resolveRankPartition as Do,encodePartitionKey as ko,RANK_TIEBREAK as Lo,rankPivotConditionSql as Fo}from"./RANK_TIEBREAK-D3ye2GsL.mjs";import{UNVOUCHABLE_DEP as Yt}from"./ADMIN_WILDCARD-BUrgWQ3-.mjs";import{idIndexKey as Bo,withUnknownIndexKeys as Wo,indexKeysForRow as qo,buildIndexRange as Po}from"./buildIndexRange-BTChxh3k.mjs";import{r as Ve,j as Ce,c as Z,t as Ye,i as Xt}from"./where-sql-BjY4rnqb.mjs";import{serializeSqlValue as Me}from"./serializeSqlValue-DeoBMpZ2.mjs";import{quoteIdentifier as De}from"./quoteIdentifier-CObIFRhb.mjs";import{whereOfFilter as Oo,isPushableWhere as Uo}from"./isPushableWhere-BeYAOjUb.mjs";import{deriveRelationEdges as Go,findRelated as jo}from"./RELATED_DEFAULT_LIMIT-CAh3WUMn.mjs";import{assertFlatPredicate as ut,findManyPage as Ho,resolveRelationPredicates as Ko,composeReadPredicate as No,relationPredicateTables as Qo}from"./DEFAULT_MAX_RELATION_KEYS-Crb9ZWeI.mjs";import{describeRelationWrites as Vo}from"./describeRelationWrites-omar6-u9.mjs";import{runRowValidators as je,transformOnlyDefinition as Jo,applyInsertDefaults as yt,resolveWith as zo,relationHooks as Yo,applyOnDelete as Xo,fanOutScalarCounts as Zo,CASCADE_MAX_ROWS as er}from"./applyInsertDefaults-80S3Pm2_.mjs";import{guardWriter as tr}from"./RLS_UNWRAP_SYMBOL-CWo1Bk9y.mjs";import{mayHoldProjectedValue as nr}from"./BIGINT_KEY_DIGITS-DE6yshOt.mjs";import{createSystemReader as or}from"./createSystemReader-BSCxr8Qs.mjs";import{ConflictError as ae}from"./ConflictError-C8GtJmjS.mjs";import{hasTrigger as Zt,runTriggers as rr}from"./hasTrigger-CjlwI4le.mjs";import{advanceClientWatermark as vs,migrateClientWatermark as _s,readClientWatermark as Ts}from"./CLIENT_WATERMARK_TABLE-De7z_OHV.mjs";import{IDEMPOTENCY_TABLE as Is,readIdempotent as bs,trimIdempotent as xs,writeIdempotent as Cs}from"./IDEMPOTENCY_TABLE-COrgeP3O.mjs";import{runShardMigrations as Ds}from"./runShardMigrations-Bc7PsQhM.mjs";import{selectShapeMembers as Ls,selectShapeRows as Fs}from"./selectShapeMembers-Dqx_m7BF.mjs";const ir=n=>{const i=atob(n),o=Uint8Array.from(i,s=>s.codePointAt(0)??0);return new TextDecoder().decode(o)},sr=()=>new R("INVALID_CURSOR","invalid cursor"),en=16,tn=8,Y=1024,vt=(n,i)=>i.query(n),cr=(n,i)=>{if(n.length===0)return 0;let o=0;for(const[s,c]of i.entries()){const h=s===i.length-1;let g=0;for(const $ of n)(h?$.startsWith(c):$===c)&&(g+=1);if(g===0)return 0;o+=g}return o},ar=(n,i)=>{if(!i)return{exact:!0,lower:n,upper:n};const o=[...n].at(-1)??"",s=(o.codePointAt(0)??0)+1;if(s>=55296&&s<=57343||s>1114111)return{exact:!0,lower:n,upper:n};const c=n.slice(0,n.length-o.length);return{exact:!1,lower:n,upper:c+String.fromCodePoint(s)}},dr=(n,i,o)=>{const s={eq:(c,h)=>{if(!n.definition.filterFields?.includes(c))throw new R("INTERNAL",`field "${c}" is not a filter field of search index "${n.indexName}" on table "${i}"`);if(n.filters.length>=tn)throw new R("BAD_REQUEST",`search index "${n.indexName}" on table "${i}": at most ${String(tn)} .eq() filters are supported per search query`);return n.filters.push({field:c,value:h}),s},search:(c,h)=>{const g=n;if(c!==g.definition.field)throw new R("INTERNAL",`search index "${g.indexName}" on table "${i}" indexes "${g.definition.field}", not "${c}"`);const $=vt(h,o).length;if($>en)throw new R("BAD_REQUEST",`search index "${g.indexName}" on table "${i}": at most ${String(en)} search terms are supported (got ${String($)})`);return g.field=c,g.query=h,g.hasQuery=!0,s}};return s},lr=n=>{if(n.length>Y)throw new R("BAD_REQUEST",`more than ${String(Y)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},ur=n=>Math.min(n.offset+n.numItems+1,Y),fr=n=>btoa(`search:${String(n)}`),hr=n=>{let i;try{i=ir(n)}catch{return}if(!i.startsWith("search:"))return;const o=Number(i.slice(7));return Number.isInteger(o)&&o>=0?o:void 0},wr=n=>{if(typeof n.endCursor=="string")throw new R("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");if(!Number.isFinite(n.numItems))throw new R("BAD_REQUEST",`search pagination needs a finite numItems, got ${String(n.numItems)}`);const i=Math.max(0,Math.floor(n.numItems)),o=n.cursor?hr(n.cursor):0;if(o===void 0)throw sr();if(o+i>=Y)throw new R("BAD_REQUEST",`search pagination reaches the ${String(Y)}-document limit (offset ${String(o)} + ${String(i)} requested) — a page must end below the cap so the probe row that answers \`hasMore\` still fits: retry with numItems ${String(Math.max(1,Y-o-1))} or fewer, or narrow the query or the filters instead`);return{numItems:i,offset:o}},pr=(n,i)=>{const o=i.offset+i.numItems,s=i.numItems>0&&n.length>o;return{continueCursor:s?fr(o):null,isDone:!s,page:n.slice(i.offset,o)}},gr=n=>{if(n===void 0)return Y+1;if(!Number.isFinite(n))return Y;const i=Math.max(0,Math.floor(n));if(i>Y)throw new R("BAD_REQUEST",`search returns at most ${String(Y)} documents (asked for ${String(i)}) — narrow the query or paginate instead`);return i},vn=500,_n=(n,i,o)=>{if(n!==void 0&&n!==Number.POSITIVE_INFINITY&&(!Number.isInteger(n)||n<0))throw o(`${i}: batch limit must be a non-negative integer`);return n??vn},Tn=(n,i,o,s)=>{if(n>i)throw s(`${o}: batch of ${String(n)} exceeds the limit of ${String(i)} (raise options.limit or chunk the call)`)},yr=32,Er=1024,An=(n,i,o,s)=>{const c=`SELECT id, _creationTime, ${De(ie)} FROM ${De(n)}`,h=`ORDER BY ${o}${s===void 0?"":` LIMIT ${String(s)}`}`;return i===void 0?Ve(`${c} ${h}`):Ce(`${c} WHERE `,i,` ${h}`)},Xe={fieldRef:n=>Ve(pt(n)),rangeTypeGuard:(n,i)=>Ve(lo(n,i)),serialize:Me},$r=n=>n===void 0?"":bo(n==="first"),In=n=>{const i=n.map(o=>`${pt(o.field)} ${o.direction==="desc"?"DESC":"ASC"}${$r(o.nulls)}`);return n.some(o=>o.field==="_id"||o.field==="id")||i.push(`${pt("id")} ${Io(n)==="desc"?"DESC":"ASC"}`),i.join(", ")},mr={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},bn=n=>new Set(n.sqlConditions.filter(i=>i.comparator==="=").map(i=>i.field)),Rr=n=>{const i=bn(n);let o=0;for(;o<n.indexFields.length&&i.has(n.indexFields[o]??"");)o+=1;return n.indexFields.slice(o)},Sr=(n,i)=>{const o=n.order,s=Rr(n),{shape:c}=i;return s.length>0?Qt(s.map(h=>({[h]:o})),c,{pinned:bn(n),uniqueBy:xo(i.indexes,c)}):Qt([{_creationTime:o}],c)},vr=(n,i,o,s)=>{const c=n.sqlConditions.map(h=>({[h.field]:{[mr[h.comparator]??"eq"]:h.value}}));if(o&&c.push(Co(i,Vt(o))),s&&c.push(Mo(i,Vt(s))),c.length!==0)return c.length===1?c[0]:{AND:c}},_r=n=>{if(n.want!==void 0)return n.selective?Math.max(n.want,yr):n.want},Et=(n,i,o,s,c,h,g)=>{const $=Sr(s,o),E=In($),u=[],{filters:x,want:_}=h;let v=h.cursor??void 0,b=_r(h);if(_===0)return{documents:u,orderKeys:$};for(;;){const q=Z(vr(s,$,v,h.endCursor),Xe,Ye),P=An(i,c&&q?Ce(q," AND ",c):c??q,E,b),W=pe(n,P.text,...P.params).toArray();let O={};g(W.length);for(const j of W)if(O=xe(j),x.every(ee=>ee(O))&&u.push(O)===_)return{documents:u,orderKeys:$};if(b===void 0||W.length<b)return{documents:u,orderKeys:$};v=gt(O,$),b=Math.max(b,Math.min(b*2,Er))}},Tr=(n,i,o,s,c,h,g,$)=>{const E=Math.max(0,Math.floor(c.numItems));if(typeof c.endCursor=="string"){const{documents:q,orderKeys:P}=Et(n,i,o,s,h,{cursor:c.cursor,endCursor:c.endCursor,filters:g.all,selective:g.selective,want:void 0},$),W=q.length>=2?q[Math.floor(q.length/2)-1]:void 0;return{continueCursor:c.endCursor,isDone:!0,page:q,splitCursor:W?gt(W,P):null}}const{documents:u,orderKeys:x}=Et(n,i,o,s,h,{cursor:c.cursor,filters:g.all,selective:g.selective,want:E+1},$),_=u.length>E,v=_?u.slice(0,E):u,b=v.at(-1);return{continueCursor:_&&b?gt(b,x):null,isDone:!_,page:v}},Ze=n=>{const i=new Map;return o=>{const s=i.get(o);if(s!==void 0)return s;const c=n(De(o));return i.set(o,c),c}},ge=De(ie),Ar=Ze(n=>`INSERT INTO ${n} (id, _creationTime, ${ge}) VALUES (?, ?, ?)`),nn=Ze(n=>`UPDATE ${n} SET ${ge} = ? WHERE id = ? AND ${ge} = ?`),Ir=Ze(n=>`UPDATE ${n} SET _creationTime = ?, ${ge} = ? WHERE id = ? AND ${ge} = ?`),br=Ze(n=>`DELETE FROM ${n} WHERE id = ? AND ${ge} = ?`),xr="SELECT changes() AS changed",on=new Map,Cr="",Mr=n=>{const i=JSON.stringify(n),o=on.get(i);if(o!==void 0)return o;const s=n.map(h=>f`SELECT ${f.raw(`'${h.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${f.identifier(ie)} FROM ${f.identifier(h)} WHERE id = ${Cr}`),{sql:c}=$n("sqlite",f`${mn(s)} LIMIT 1`);return on.set(i,c),c},Dr=(n,i)=>i.map(()=>n),kr=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,Lr=n=>{if(!kr.test(n))throw new R("INTERNAL",`invalid clientId ${JSON.stringify(n)}: a client-supplied row id must be a UUID`)},$t=n=>{if(n.includes("\0"))throw new R("BAD_REQUEST",`invalid row id ${JSON.stringify(n)}: a row id cannot hold a NUL character (U+0000)`)},Fr=(n,i,o,s)=>{if(o!==!0)return;const c=n!==void 0&&"serverDefault"in(n.shape._id?._meta?.column??{});for(const h of i){const g=c?yt(n,h,s)._id:h._id;typeof g=="string"&&$t(g)}},rn=50,He=Math.floor(Rn.boundParams/3),sn=Rn.boundParams,Br=128,Je=n=>new R("BATCH_LIMIT_EXCEEDED",n,{status:400}),Ke=(n,i,o)=>{Tn(n,_n(i,o,Je),o,Je)},cn=async(n,i,o,s,c)=>{const h=_n(s,c,Je),{page:g}=await n.findMany(i,Number.isFinite(h)?{limit:h+1,omitContinueCursor:!0,where:o}:{where:o});return g.length>h&&Tn(Math.max(await n.count(i,{where:o}),g.length),h,c,Je),g},Wr=n=>{const i={eq:(o,s)=>(n.sqlConditions.push({comparator:"=",field:o,value:s}),i),gt:(o,s)=>(n.sqlConditions.push({comparator:">",field:o,value:s}),i),gte:(o,s)=>(n.sqlConditions.push({comparator:">=",field:o,value:s}),i),lt:(o,s)=>(n.sqlConditions.push({comparator:"<",field:o,value:s}),i),lte:(o,s)=>(n.sqlConditions.push({comparator:"<=",field:o,value:s}),i)};return i},qr=n=>Math.max(n,Y),xn=(n,i)=>{const o=n.filters.map(s=>f`${we(s.field)} = ${Me(s.value)}`);return i&&o.push(i),o},Pr=(n,i,o,s,c)=>{const h=vt(o.query,St(o.definition.language));if(h.length===0)return[];const g=Qn(i,o.indexName),$=`${g}__vocab`,E=h.length-1,u=h.map((P,W)=>{const O=ar(P,W===E),j=O.exact?f`${f.identifier("term")} = ${O.lower}`:f`${f.identifier("term")} >= ${O.lower} AND ${f.identifier("term")} < ${O.upper}`;return f`SELECT ${f.identifier("doc")}, ${f.raw(String(W))} AS ${f.identifier("__term__")}, COUNT(*) AS ${f.identifier("__n__")} FROM ${f.identifier($)} WHERE ${j} GROUP BY ${f.identifier("doc")}`}),x=h.map((P,W)=>f`SUM(CASE WHEN u.${f.identifier("__term__")} = ${f.raw(String(W))} THEN u.${f.identifier("__n__")} ELSE 0 END)`),_=f`SELECT f.${f.identifier(Pe)} AS ${f.identifier(Pe)}, ${f.join(x,f` + `)} AS ${f.identifier("__score__")} FROM (${mn(u)}) u JOIN ${f.identifier(g)} f ON f.rowid = u.${f.identifier("doc")} GROUP BY f.${f.identifier(Pe)} HAVING ${f.join(x.map(P=>f`${P} > 0`),f` AND `)}`,v=xn(o,c);let b=f`SELECT m.id, m._creationTime, m.${f.identifier(ie)}, s.${f.identifier("__score__")} AS ${f.identifier("__score__")} FROM (${_}) s JOIN ${f.identifier(i)} m ON m.id = s.${f.identifier(Pe)}`;v.length>0&&(b=f`${b} WHERE ${f.join(v,f` AND `)}`),b=f`${b} ORDER BY s.${f.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${f.raw(String(s))}`;const q=[];for(const P of K(n,b)){const W=En(P);if(W){const O=P.__score__;q.push({document:W,score:typeof O=="number"?O:Number(O??0)})}}return q},Or=(n,i,o,s,c)=>{const h=St(o.definition.language),g=vt(o.query,h);if(g.length===0)return[];const $=xn(o,c);let E=f`SELECT id, _creationTime, ${f.identifier(ie)} FROM ${f.identifier(i)}`;$.length>0&&(E=f`${E} WHERE ${f.join($,f` AND `)}`),E=f`${E} ORDER BY _creationTime DESC, id ASC LIMIT ${f.raw(String(qr(s)))}`;const u=K(n,E).toArray(),x=[];for(const _ of u){const v=En(_);if(!v)continue;const b=cr(Vn(v,o.definition),g);b>0&&x.push({creationTime:typeof v._creationTime=="number"?v._creationTime:0,doc:v,id:typeof v._id=="string"?v._id:"",score:b})}return x.sort((_,v)=>v.score-_.score||v.creationTime-_.creationTime||_.id.localeCompare(v.id)),x.slice(0,s).map(_=>({document:_.doc,score:_.score}))},ft=(n,i,o,s)=>{if(!Number.isFinite(n.lat)||n.lat<-90||n.lat>90||!Number.isFinite(n.lng)||n.lng<-180||n.lng>180)throw new R("BAD_REQUEST",`geo index "${s}" on table "${o}": ${i} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},Ur=(n,i)=>{const o=n,s={near:(c,h)=>{if(o.within)throw new R("INTERNAL",`geo index "${o.indexName}" on table "${i}": call .near() or .within(), not both`);if(ft(c,".near() point",i,o.indexName),!Number.isFinite(h)||h<=0)throw new R("BAD_REQUEST",`geo index "${o.indexName}" on table "${i}": .near() radiusMeters must be a finite number > 0, got ${String(h)}`);return o.near={point:{lat:c.lat,lng:c.lng},radiusMeters:h},s},within:c=>{if(o.near)throw new R("INTERNAL",`geo index "${o.indexName}" on table "${i}": call .near() or .within(), not both`);if(ft(c.sw,".within() sw corner",i,o.indexName),ft(c.ne,".within() ne corner",i,o.indexName),c.sw.lat>c.ne.lat)throw new R("BAD_REQUEST",`geo index "${o.indexName}" on table "${i}": .within() corners are transposed (sw.lat > ne.lat)`);if(c.sw.lng>c.ne.lng)throw new R("BAD_REQUEST",`geo index "${o.indexName}" on table "${i}": .within() box crosses the antimeridian (sw.lng > ne.lng), which is not supported — split it into two boxes at ±180 and union the results`);return o.within={ne:{lat:c.ne.lat,lng:c.ne.lng},sw:{lat:c.sw.lat,lng:c.sw.lng}},s}};return s},Gr=(n,i)=>{const o=n[i];if(o===null||typeof o!="object")return;const{lat:s,lng:c}=o;return typeof s=="number"&&typeof c=="number"?{lat:s,lng:c}:void 0},jr=(n,i)=>{const o=Gr(n,i.definition.field);if(!o)return;const s=typeof n._creationTime=="number"?n._creationTime:0;if(i.near){const c=Ro(i.near.point,o);return c<=i.near.radiusMeters?{creationTime:s,distance:c}:void 0}return So(o,i.within)?{creationTime:s,distance:0}:void 0},Hr=(n,i,o,s)=>{if(!o.near&&!o.within)throw new R("INTERNAL",`geo index "${o.indexName}" on table "${i}": call .near(point, radius) or .within(box)`);const c=o.near?$o(o.near.point,o.near.radiusMeters):mo(o.within),h=go(i,o.indexName),g=c.map(_=>f`(g.${f.identifier("__geohash__")} >= ${_} AND g.${f.identifier("__geohash__")} < ${`${_}{`})`),$=[f`(${f.join(g,f` OR `)})`];s&&$.push(s);const E=f`SELECT m.id, m._creationTime, m.${f.identifier(ie)} FROM ${f.identifier(h)} g JOIN ${f.identifier(i)} m ON m.id = g.${f.identifier("__id__")} WHERE ${f.join($,f` AND `)}`,u=K(n,E).toArray(),x=[];for(const _ of u){const v=xe(_),b=v?jr(v,o):void 0;v&&b&&x.push({creationTime:b.creationTime,distance:b.distance,doc:v})}return x.sort((_,v)=>_.distance-v.distance||v.creationTime-_.creationTime),x},Cn=(n,i,o,s)=>{const c=[];for(const h of n)if(i.every(g=>g(s(h)))&&(c.push(h),typeof o=="number"&&c.length>=o))break;return c},Kr=(n,i,o,s,c,h=()=>{})=>{const g=o.within!==void 0,$=Hr(n,i,o,c).map(E=>({distanceMeters:g?null:E.distance,document:E.doc}));return h($.length),typeof s=="number"?$.slice(0,Math.max(0,Math.floor(s))):$},an=(n,i,o,s,c,h,g=()=>{})=>{const{geo:$}=o;if(!$)throw new R("INTERNAL","runGeoTerminalScored called without a staged geo query");const E=c.length>0,u=Kr(n,i,$,E?void 0:h,s,g);return E?Cn(u,c,h,x=>x.document):u},dn=(n,i,o)=>{const s=n.shape[i];if(s!==void 0&&nr(s))throw new R("BAD_REQUEST",`${o}: "${i}" may hold an order-preserving key rather than a value SQL can reduce or group — declare an aggregateIndex covering this (by, field, op) so the maintained companion answers it instead (its running total is a REAL, so it stays exact only while the total is inside 2^53)`)},Nr=n=>{let i=0;const o=[],s={...Xe,relationExists:c=>{const{childWhere:h,negated:g,parentTable:$,relation:E}=c,u=`__rel_${String(i)}`,x=o.at(-1)??$;i+=1,n(E.table,G);const _=E.kind==="one"?E.field:E.references,v=E.kind==="one"?E.references:E.field,b=Ve(`${Kt(u,v)} = ${Kt(x,_)}`);o.push(u);const q=Z(h,s,Ye);o.pop();const P=q===void 0?b:Ce(b," AND ",q),W=Ce("EXISTS (SELECT 1 FROM ",Xt(E.table)," AS ",Xt(u)," WHERE ",P,")");return g?Ce("NOT ",W):W}};return s};class Qr extends R{constructor(i="unique() found more than one matching document"){super("NOT_UNIQUE",i,{name:"NotUniqueError"})}}const Vr=/\s/u,Jr=String.fromCodePoint(0),ln=(n,i,o)=>{if(!n.tables[i])throw new R("INTERNAL",`unknown table: ${i}`);return typeof o!="string"||o.length===0||Vr.test(o)||o.includes(Jr)?null:o},Mn=(n,i,o,s=()=>{},c=()=>{},h=()=>{},g)=>{const $=i.tables[o];if(!$)throw new R("INTERNAL",`unknown table: ${o}`);const E=Ie($.softDeleteMode,void 0),u=g??{indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[],verifyFilters:[]},x=()=>{const S=Q(E,u.pushedWhere);return S?Z(S,he):void 0},_=()=>{const S=Q(E,u.pushedWhere);return S?Z(S,Xe,Ye):void 0},v=()=>[...u.inMemoryFilters,...u.verifyFilters];let b=0;const q=S=>{const{search:D}=u;if(!D)throw new R("INTERNAL","runSearchFetch called without a staged search");to(wo(n),o,$);const L=u.inMemoryFilters.length>0,F=gr(L?void 0:S),k=po(n);if(k&&!no(n,o,D.definition))throw new R("SEARCH_INDEX_BUILDING",`search index "${D.indexName}" on table "${o}" is still backfilling and currently covers only part of the table — retry once it finishes, or run the backfillSearch admin operation to complete it now`);const ye=x(),te=k?Pr(n,o,D,F,ye):Or(n,o,D,F,ye);!L&&S===void 0&&lr(te);const Ee=v();return b=te.length,Ee.length>0?Cn(te,Ee,S,z=>z.document):te},P=S=>q(S).map(D=>D.document),W=S=>{const D=wr(S);return pr(P(ur(D)),D)},O=()=>{if(u.search||u.geo||u.indexName===void 0){c(void 0);return}c(Po(o,u.indexName,u.indexFields,u.sqlConditions,Me))},j=S=>{O();let D=0;const L=(()=>{if(u.search){const F=P(S);return D=b,F}return u.geo?an(n,o,u,x(),v(),S,F=>{D=F}).map(F=>F.document):Et(n,o,$,u,_(),{filters:v(),selective:u.inMemoryFilters.length>0,want:S===void 0?void 0:Math.max(0,Math.floor(S))},F=>{D+=F}).documents})();return h(Math.max(D,L.length)),L},ee=()=>{if(!u.search&&!u.geo)throw new R("INTERNAL",`ctx.db.query("${o}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);O();let S=0;const D=(()=>{if(u.search){const L=q(void 0);return S=b,L}return an(n,o,u,x(),v(),void 0,L=>{S=L})})();return h(Math.max(S,D.length)),D},N={async*[Symbol.asyncIterator](){const S=Mn(n,i,o,s,c,h,{...u,indexFields:[...u.indexFields],inMemoryFilters:[...u.inMemoryFilters],sqlConditions:[...u.sqlConditions],verifyFilters:[...u.verifyFilters]});if(u.search){yield*await S.collect();return}let D;for(;;){const L=await S.paginate({cursor:D??null,numItems:Br});if(yield*L.page,L.isDone||L.continueCursor===null)return;D=L.continueCursor}},async collect(){return j(void 0)},async collectWithScores(){return ee()},filter(S){const D=Oo(S);return D!==void 0&&Uo(D,$.shape)?(u.pushedWhere=Q(u.pushedWhere,D),u.verifyFilters.push(S)):u.inMemoryFilters.push(S),N},async first(){return j(1)[0]??null},order(S){return u.order=S==="desc"?"desc":"asc",N},async paginate(S){let D=0;if(O(),u.search){const F=W(S);return h(F.page.length),F}if(u.geo)throw new R("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const L=Tr(n,o,$,u,S,_(),{all:v(),selective:u.inMemoryFilters.length>0},F=>{D+=F});return h(Math.max(D,L.page.length)),L},async take(S){return j(S)},async unique(){const S=j(2);if(S.length>1)throw new Qr(`unique() on table "${o}" matched ${String(S.length)} documents; expected at most one`);return S[0]??null},withGeoIndex(S,D){const L=($.geoIndexes??[]).find(k=>k.name===S);if(!L)throw new R("INTERNAL",`unknown geo index "${S}" on table "${o}"`);s(o,S,"geo");const F={definition:L,indexName:S};if(u.geo=F,D(Ur(F,o)),!F.near&&!F.within)throw new R("INTERNAL",`geo index "${S}" on table "${o}" requires a .near(point, radius) or .within(box) call`);return N},withIndex(S,D){const L=$.indexes.find(F=>F.name===S);if(!L)throw new R("INTERNAL",`unknown index "${S}" on table "${o}"`);return s(o,S,"index"),u.indexName=S,u.indexFields=L.fields,D&&D(Wr(u)),N},withSearchIndex(S,D){const L=($.searchIndexes??[]).find(k=>k.name===S);if(!L)throw new R("INTERNAL",`unknown search index "${S}" on table "${o}"`);s(o,S,"search");const F={definition:L,field:L.field,filters:[],hasQuery:!1,indexName:S,query:""};if(u.search=F,D(dr(F,o,St(L.language))),!F.hasQuery)throw new R("INTERNAL",`search index "${S}" on table "${o}" requires a .search(field, query) call`);return N}};return N},ht=(n,i,o,s)=>{const c=o;for(const[h,g]of ho(n)){if(g.serverDefault){h in i&&(c[h]=g.serverDefault({auth:s}));continue}g.onUpdateFn&&!(h in i)&&(c[h]=g.onUpdateFn())}},un=5,fn=(n,i)=>{for(const o of Object.keys(i))if(i[o]===void 0)throw new R("INTERNAL",`Cannot ${n} field '${o}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},hn=["_commitSeq","_creationTime","_id"],Ne=n=>hn.some(i=>i in n)?Object.fromEntries(Object.entries(n).filter(([i])=>!hn.includes(i))):n,zr=/unique constraint failed/i,Yr=n=>n instanceof Error&&zr.test(n.message),Xr=/string or blob too big/iu,Zr=(n,i)=>{if(!(!(n instanceof Error)||!Xr.test(n.message)))throw new R("PAYLOAD_TOO_LARGE",`document is too large to store in "${i}": a single row cannot exceed the storage engine's per-row ceiling (2 MB on a Durable Object's SQLite). The limit is on the STORED bytes, which are UTF-8, and v.bytes()/v.bigint() columns are stored twice on a shard-local table. Keep the payload in R2 (ctx.storage) and store a reference on the row.`)},mt=(n,i,o,s)=>{try{pe(n,o,...s)}catch(c){throw Yr(c)?new ae(`unique constraint violation on "${i}"`,"unique"):(Zr(c,i),c)}},Qe=(n,i,o,s)=>{if(mt(n,i,o,s),pe(n,xr).one().changed===0)throw new ae(`optimistic concurrency conflict on "${i}" — the row changed during this mutation; refetch and retry`,"occ")},wn=(n,i,o,s,c,h,g)=>{const $=[];for(let _=0;_<o.length+1;_+=1){const v=o[_],b=s[_],q=b?.direction==="desc"?"desc":"asc",P=v===void 0||b===void 0?f`${f.identifier(Lo)} < ${g}`:Fo(v,h[_],q,!1);if(P===void 0)continue;const W=[];for(let j=0;j<_;j+=1)W.push(f`${f.identifier(o[j])} IS ${h[j]}`);W.push(P);const[O]=W;$.push(W.length===1&&O!==void 0?O:f`(${f.join(W,f` AND `)})`)}const E=$.length>0?f.join($,f` OR `):f`1 = 0`,u=K(n,f`SELECT COUNT(*) AS c FROM ${f.identifier(i)} WHERE ${f.identifier("__partition__")} = ${c} AND (${E})`).one(),x=K(n,f`SELECT COUNT(*) AS c FROM ${f.identifier(i)} WHERE ${f.identifier("__partition__")} = ${c}`).one();return{before:u.c,total:x.c}},ei=n=>{const i=new Map;for(const[s,c]of Object.entries(n.tables))for(const h of Object.values(c.relationMap??{}))h.kind==="one"&&(h.onDelete==="cascade"||h.onDelete==="set null")&&i.set(h.table,[...i.get(h.table)??[],{holder:s,op:h.onDelete==="cascade"?"delete":"update"}]);const o=s=>{const c=new Set,h=[s];for(let g=h.pop();g!==void 0;g=h.pop())for(const{holder:$,op:E}of i.get(g)??[]){if($===s||Zt(n,$,E))return!0;c.has($)||(c.add($),h.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))},ti=n=>{const i=new Map;for(const[o,s]of Object.entries(n.tables))s.softDeleteMode&&i.set(o,s.softDeleteMode.field);return i},wt=new WeakMap,ni=(n,i)=>{let o=wt.get(i.tables);if(!wt.has(i.tables)){const c=Object.keys(i.tables).map(h=>h.replaceAll(/[$()*+.?[\\\]^{|}]/gu,String.raw`\$&`));o=c.length===0?void 0:new RegExp(`"(${c.join("|")})"`,"gu"),wt.set(i.tables,o)}if(o===void 0)return;const s=new Set;for(const c of n.matchAll(o))s.add(c[1]);return s.size===1?[...s][0]:void 0},oi=(n,i,o)=>{for(const s of n){const c=s,h=c?.[ie];if(typeof h=="string"){const g=c?.id,$=Eo(h);typeof g!="string"?i.recordReadBytes($):o===void 0?i.recordDocumentRead(`${g}\0${String($)}`,$):i.recordDocumentRead(`${o}\0${g}`,$)}}},ri=(n,i,o)=>{if(i===void 0)return n;const s=(c,...h)=>{const g=n.exec(c,...h),$=g.one.bind(g),E=g[Symbol.iterator].bind(g),u=o===void 0?void 0:ni(c,o);let x=!1;const _=v=>{oi(v,i,u)};return g.toArray=()=>{const v=[];for(const b of{[Symbol.iterator]:E})_([b]),v.push(b);return v},g.one=()=>{x=!0;try{const v=$();return _([v]),v}finally{x=!1}},g[Symbol.iterator]=function*(){for(const b of{[Symbol.iterator]:E})x||_([b]),yield b},g};return new Proxy(n,{get:(c,h)=>h==="exec"?s:h===uo?c:Reflect.get(c,h,c)})},ii=new Map([["findFirst","rows"],["findFirstOrThrow","rows"],["findMany","page"],["get","rows"],["lookupById","lookup"],["rankPage","page"]]),si=new Map([["collect","rows"],["collectWithScores","scored"],["first","rows"],["paginate","page"],["take","rows"],["unique","rows"]]),be=(n,i,o)=>{if(typeof n!="object"||n===null)return;const s=yo(n);if(s===void 0)return;const c=n._id;typeof c=="string"?o.recordDocumentRead(`global\0${i}\0${c}`,s):o.recordReadBytes(s)},ze=(n,i,o,s)=>{if(typeof n!="object"||n===null)return;const c=n;switch(i){case"lookup":{be(c.row,typeof c.tableName=="string"?c.tableName:o,s);return}case"page":{for(const h of c.page??[])be(h,o,s);return}case"rows":{for(const h of Array.isArray(n)?n:[n])be(h,o,s);return}default:for(const h of Array.isArray(n)?n:[])be(h.document,o,s)}},Dn=(n,i,o)=>new Proxy(n,{get:(s,c)=>{const h=Reflect.get(s,c,s);if(typeof h!="function")return h;if(c===Symbol.asyncIterator)return async function*(){for await(const E of Reflect.apply(h,s,[]))be(E,i,o),yield E};const g=si.get(c);return(...$)=>{const E=Reflect.apply(h,s,$);return g!==void 0?Promise.resolve(E).then(u=>(ze(u,g,i,o),u)):typeof E=="object"&&E!==null&&!(E instanceof Promise)?Dn(E,i,o):E}}}),ci=new Set(["findFirst","findFirstOrThrow","findMany"]),ai=n=>{const i=n[1],o=i?.select;if(!Array.isArray(o))return;const s=Object.fromEntries(Object.entries(i).filter(([g])=>g!=="select")),c=s.with,h=g=>Sn(g,o,c);return{args:[n[0],s,...n.slice(2)],project:(g,$)=>typeof g!="object"||g===null?g:$==="page"?{...g,page:h(g.page)}:h([g])[0]}},pn=256,Rt=4096,di=1024*1024,li=async(n,i,o,s)=>{const c=i[1]??{},h=[];let{cursor:g}=c,$=pn,E=0;for(;;){const u=await n([i[0],{...c,cursor:g,limit:$},...i.slice(2)]);if(Array.isArray(u))return ze(u,"rows",o,s),[...h,...u];const x=s.headroom().readBytes;if(ze(u,"page",o,s),h.push(...u.page),u.isDone||typeof u.continueCursor!="string")return{continueCursor:null,isDone:!0,page:h};g=u.continueCursor,E+=s.headroom().readBytes-x,$=E>0?Math.min(Rt,Math.max(pn,Math.floor(di*h.length/E))):Rt}},ui=(n,i)=>n===void 0||i===void 0?n:new Proxy(n,{get:(o,s)=>{const c=Reflect.get(o,s,o);if(typeof c!="function")return c;if(s==="query")return(...g)=>Dn(Reflect.apply(c,o,g),String(g[0]),i);const h=ii.get(s);return h===void 0?c:async(...g)=>{const $=ci.has(s)?ai(g):void 0;let E=$?.args??g;const u=String(g[0]),x=E[1],_=s==="findMany"&&typeof x?.endCursor=="string",v=s==="findMany"&&typeof x?.limit!="number"&&!_;if(_&&typeof x.limit!="number"&&(E=[E[0],{...x,limit:Rt},...E.slice(2)]),v){const q=await li(P=>Reflect.apply(c,o,P),E,u,i);return $===void 0?q:$.project(q,h)}const b=await Reflect.apply(c,o,E);return ze(b,h,u,i),$===void 0?b:$.project(b,h)}}}),gn=new WeakMap,yn=new WeakMap,fi=500,hi=n=>{const{baselineSeq:i,onStalePatchDropped:o}=n,{headroom:s}=n,c=gn.get(n)??{value:void 0},h=yn.get(n)??{value:0};let g;const $=()=>{if(g===void 0){const e={...n,enforceRls:!1,headroom:void 0};gn.set(e,c),yn.set(e,h),g=hi(e)}return g},E=ri(n.sql,s,n.schema),{schema:u}=n,x=n.broadcast??(()=>{}),_=(e,t)=>{if(!Object.hasOwn(u.tables,e))throw new R("BAD_REQUEST",`${t}: "${e}" is not a table in this schema`)},v=Go(u),b=new Map;for(const e of v){const t=r=>(u.tables[r]?.shardMode?.kind??"root")==="root";!e.array&&t(e.sourceTable)&&t(e.targetTable)&&b.set(e.sourceTable,[...b.get(e.sourceTable)??[],e])}const q=(e,t,r)=>{for(const a of b.get(e)??[]){const l=t[a.column];if(typeof l!="string"||r?.[a.column]===l||a.targetTable===e&&t._id===l)continue;if(K(E,f`SELECT 1 FROM ${f.identifier(a.targetTable)} WHERE id = ${l} LIMIT 1`).toArray().length===0)throw new R("VALIDATION_ERROR",`${a.name} references ${a.targetTable} row "${l}", which does not exist`)}},P=Vo(u,n.inTransaction),W=ei(u),O=ti(u),j=()=>n.inTransaction?.()===!0,ee=e=>u.tables[e]?.commitOrderedMode!==!0?{}:((c.value===void 0||!j())&&(c.value=io(E)),{[so]:c.value}),N=(e,...t)=>{const r=u.tables[e]?.indexes??[],a=[];let l;for(const p of t)p&&(typeof p._id=="string"&&p._id!==l&&(l=p._id,a.push(Bo(l))),a.push(...Wo(r,qo(r,p,Me))));return a.length>0?a:void 0},S=n.onRead??(()=>{}),D=e=>{jt(u.tables[e])&&S(Yt,Yt)},L=n.onReadRange??(e=>{S(e.table,G)}),F=e=>{D(e.table),L(e)},k=(e,t,r)=>{t!==void 0&&(r===!0||t!==G)&&s?.recordRead(1),D(e),S(e,t,r)},ye=(e,t)=>{const r=e.row._id;k(e.tableName,typeof r=="string"?r:t,typeof r=="string")},te=n.onIndexUse??(()=>{}),Ee=n.onWrite??(()=>{}),z=e=>{s?.recordWrite(e)},$e=async e=>{z(e.doc),await Ee(e)},{cache:de}=n,me=n.clock??(()=>Date.now()),_t=n.idGenerator??(()=>crypto.randomUUID()),Tt=n.scheduler??zn,Re=ui(n.globalDb,s),le=n.auth??{identity:null,userId:null},At=n.cdc??!1,et=Tt,kn=or({scheduler:typeof et.list=="function"&&typeof et.get=="function"?et:void 0,storage:n.storage}),Se=(e,t,r,a)=>{At&&!jt(u.tables[e])&&oo(E,me(),e,t,r,a)},It=(e,t,r,a)=>{const l=u.tables[e];if(l?.dropStalePatchesMode!==!0||!At)return!1;const p=i?.();if(p===void 0)return!1;const d=ro(E,e,t,p);if(d===void 0)return!1;const w=Ao(l,r);return Object.keys(Ne(r)).some(y=>!w.has(y)&&Gt(Nt(d,y))!==Gt(Nt(a,y)))},se=e=>u.tables[e]?.shardMode?.kind==="global",bt=(e,t)=>{if(se(e)){if(!Re)throw new R("INTERNAL",`cross-backend ${t} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return Re}return U},tt=e=>bt(e,"cascade"),H=(e,t)=>{if(se(e)){if(!Re)throw new R("INTERNAL",`${t} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return Re}},ce=(e,t,r)=>{de?.invalidateTable(t),x({key:r,op:e,table:t})},xt=async(e,t,r,a,l)=>{l&&z(r);const p=await e.insert(t,r,a);return x({key:p,op:"insert",row:{...r,_id:p},table:t}),p},Ln=(e,t)=>bt(e,"relation load").findMany(e,t),Fn=e=>e.through===void 0?[e.table]:[e.through.table,e.table],Ct=e=>{for(const t of e===void 0?[]:Fn(e))se(t)&&k(t,G)},Mt=(e,t)=>{const r=u.tables[e]?.relationMap??{};for(const[a,l]of Object.entries(t??{})){if(a==="_count"){for(const d of Object.keys(typeof l=="object"?l:{}))Ct(r[d]);continue}const p=r[a];p===void 0||l===void 0||l===!1||(Ct(p),typeof l=="object"&&Mt(p.table,l.with))}},nt=(e,t)=>(se(e)&&(k(e,G),Mt(e,t.with)),Ln(e,t)),Bn=e=>!se(e.table),Dt=n.relationExistsPushDown??"auto",kt=Dt!=="never",{maxRelationKeys:Lt}=n,ke=(e,t,r)=>Ko(e,{fetcher:nt,maxRelationKeys:Lt,relationBaseWhere:r,schema:u,tableName:t}),Wn=async(e,t,r,a,l)=>{const p=H(e,"relation grouped count");if(p){k(e,G);for(const B of Qo(a,u,e,l))k(B,G);return Zo((B,V)=>p.count(B,{relationBaseWhere:l,where:V}),e,t,r,a)}const d=u.tables[e];if(!d)throw new R("INTERNAL",`unknown table: ${e}`);k(e,G);const w=Ie(d.softDeleteMode,void 0),y={[t]:{in:r}},T=Q(Q(y,a),w),C=await ke(T,e,l),A=Z(C,he),I=we(t);let M=f`SELECT ${I} AS __fk__, COUNT(*) AS count FROM ${f.identifier(e)}`;A&&(M=f`${M} WHERE ${A}`),M=f`${M} GROUP BY ${I}`;const m=K(E,M).toArray();return new Map(m.map(B=>[B.__fk__,B.count]))},Ft=new Set;for(const[e,t]of Object.entries(u.tables))for(const r of Object.values(t.triggerMap??{}))Ft.add(`${e} ${r.timing} ${r.op}`);const ne=(e,t,r)=>Ft.has(`${e} ${t} ${r}`),oe=async(e,t,r)=>{if(h.value+=1,h.value>rn)throw h.value-=1,new ae(`trigger recursion exceeded ${String(rn)} levels on "${r.table}" — check for a self-triggering write`,"trigger");try{await rr({ctx:Kn,event:r,op:t,schema:u,tableName:r.table,timing:e})}finally{h.value-=1}},{ensureBackfilledForTable:ve,ensureBackfilledIndex:ot,ensureRankBackfilled:rt,ensureRankBackfilledForTable:_e,syncAggregates:Le,syncCompanionsForInsert:Bt,syncGeo:Fe,syncRanks:Te,syncSearch:Be}=co({broadcast:x,indexKeysFor:(e,t)=>N(e,t),invalidateCache:(e,t,r)=>de?.invalidate(e,t,N(e,r)),recordCdc:Se,schema:u,sql:E,verified:n.companionMemo?.verified}),Wt=(e,t,r)=>{const{shardMode:a}=t;if(a?.kind==="shardBy"&&!(a.field!==void 0&&(r.partitionBy??[]).includes(a.field)))throw Object.assign(new Error(`rank index "${r.name}" on "${e}" partitions across shards (shard key "${a.field??"?"}" is not in partitionBy) — a shard-local rank()/rankPage() would be wrong; roll it up through the Query Coordinator instead`),{code:"CROSS_SHARD_RANK_UNSUPPORTED",name:"LunoraError",status:400})},qt=e=>Object.entries(u.tables).filter(([,t])=>t.shardMode?.kind!=="global").map(([t])=>t).filter(t=>e===void 0||t===e),Ae=e=>e===void 0||se(e)?Re:void 0,qn=e=>Object.entries(u.tables).flatMap(([t,r])=>se(t)?Object.values(r.relationMap??{}).flatMap(a=>a.through!==void 0||a.kind!=="one"||a.table!==e?[]:a.onDelete!=="cascade"&&a.onDelete!=="set null"?[]:[{action:a.onDelete==="cascade"?"delete":"update",field:a.field,holderTable:t,references:a.references}]):[]),Pn=async(e,t,r,a)=>r==="_id"?a:(await e.get(t,a))?.[r],On=async(e,t,r,a,l)=>{const p=[];let d;do{const w=await e.findMany(t,{cursor:d,includeDeleted:l,limit:fi,where:{[r]:a}});for(const y of w.page)p.push(String(y._id));d=w.isDone?void 0:w.continueCursor??void 0}while(d!==void 0&&p.length<=er);return p},Un=async(e,t,r,a,l,p)=>{const{action:d,field:w,holderTable:y,references:T}=r,C=await Pn(e,t,T,a);if(C==null)return{effects:[],toExpand:[]};const A=await On(e,y,w,C,p),I=A.filter(m=>!l.announced.has(`${d}:${y}:${m}`)),M=d==="delete"?A.filter(m=>!l.expanded.has(`${y}:${m}`)):[];for(const m of I)l.announced.add(`${d}:${y}:${m}`);for(const m of M)l.expanded.add(`${y}:${m}`);return{effects:I.map(m=>({id:m,op:d,table:y})),toExpand:M}},Pt=async(e,t,r,a,l)=>{const p=[];for(const d of qn(t))for(const w of r){const y=await Un(e,t,d,w,a,l);p.push(...y.effects),y.toExpand.length>0&&p.push(...await Pt(e,d.holderTable,y.toExpand,a,l))}return p},it=async(e,t,r,a,l)=>{for(let d=0;d<r.length;d+=1)z(void 0);const p=a?.skipOnDelete===!0?[]:await Pt(e,t,r,{announced:new Set,expanded:new Set},a?.hard===!0);try{if(l!==void 0&&e.deleteMany!==void 0)try{return await e.deleteMany(t,r,l.options)}finally{for(const d of r)ce("delete",t,d)}for(const d of r)try{await e.delete(t,d,a)}finally{ce("delete",t,d)}return{deleted:r.length}}finally{for(const d of p)ce(d.op,d.table,d.id)}},re=(e,t)=>{const r=qt(t);for(let a=0;a<r.length;a+=sn){const l=r.slice(a,a+sn),[p]=pe(E,Mr(l),...Dr(e,l)).toArray();if(!p)continue;const d=p.__t__,w=xe(p);if(typeof d!="string"||!w)return;const y=p[ie];return{docJson:typeof y=="string"?y:fe(y??{}),row:w,tableName:d}}},Ot={assertRankPartitionLocal:Wt,ensureRankBackfilled:rt,onRead:k,rowToDocument:xe,schema:u,sql:E},Gn=(e,t,r)=>{const a=Z(r,he);return a===void 0||K(E,f`SELECT 1 FROM ${f.identifier(e)} WHERE ${f.identifier("id")} = ${t} AND ${a}`).toArray().length>0},jn=(e,t,r,a)=>It(e,t,r,a)?(o?.({fields:Object.keys(Ne(r)),id:t,table:e}),!0):!1,Hn=async(e,t,r,a,l)=>{const p=re(t,e);if(!p)return{applied:!1,doc:null};if(k(e,t),!Gn(e,t,r.where)||jn(e,t,r.patch,p.row))return{applied:!1,doc:p.row};try{await l(r.patch)}catch(d){if(d instanceof ae&&d.kind==="occ"&&a)return;throw d}return{applied:!0,doc:re(t,e)?.row??null}},Ut=async(e,t,r,a)=>{const{fetchLimit:l,limit:p,orderKeys:d,predicate:w}=await No(t,r,{canPushExists:kt?Bn:void 0,existsPushMode:Dt==="always"?"always":"auto",fetcher:nt,maxRelationKeys:Lt,schema:u,tableName:e}),y=kt?Nr(a):Xe,T=Z(w,y,Ye),C=An(e,T,In(d),l);return{limit:p,orderKeys:d,statement:C}},U={system:kn,async aggregate(e,t){const r=H(e,"aggregate");if(r)return k(e,G),r.aggregate(e,t);const a=u.tables[e];if(!a)throw new R("INTERNAL",`unknown table: ${e}`);if(Oe(t.op),t.op==="count")return U.count(e,{baseWhere:t.baseWhere,relationBaseWhere:t.relationBaseWhere,restrictsCounts:t.restrictsCounts,where:t.where});if(!t.field)throw new R("INTERNAL",`aggregate(${e}, { op: "${t.op}" }): "field" is required for non-count reducers`);k(e,G);const l=Ie(a.softDeleteMode,void 0),p=Q(Q(t.baseWhere,t.where),l),d=await ke(p,e,t.relationBaseWhere),w=d!==p;if(a.aggregateIndexes&&!t.baseWhere&&!w){const m=eo(a.aggregateIndexes,t.op,t.field,t.where);if(m){ot(e,m.index);const B=ct(m.index.by??[],m.key),V=st(e,m.index.name),X=K(E,f`SELECT ${Ue} AS value, ${lt} AS count FROM ${f.identifier(V)} WHERE ${Ge} = ${B}`).toArray()[0];return at(t.op,X)}}dn(a,t.field,`aggregate(${e}, { op: "${t.op}", field: "${t.field}" })`);const y=Z(d,he),T=Oe(t.op),C=we(t.field);let A=f`SELECT ${f.raw(T)}(${C}) AS value FROM ${f.identifier(e)}`;y&&(A=f`${A} WHERE ${y}`);const M=K(E,A).toArray()[0]?.value;return M??null},asId(e,t){const r=ln(u,e,t);if(r===null)throw new R("BAD_REQUEST",`asId("${e}", …): "${t}" is not a valid id for table "${e}"`,{status:400});return r},async count(e,t){const r=H(e,"count");if(r)return k(e,G),r.count(e,t);const a=u.tables[e];if(!a)throw new R("INTERNAL",`unknown table: ${e}`);const l=Yn(t);if(l.restrictsCounts)throw new dt(e);k(e,G);const p=Ie(a.softDeleteMode,void 0),d=Q(Q(l.baseWhere,l.where),p),w=await ke(d,e,l.relationBaseWhere),y=w!==d;if(a.aggregateIndexes&&!l.baseWhere&&!y){const I=Zn(a.aggregateIndexes,l.where);if(I){ot(e,I.index);const M=ct(I.index.by??[],I.key),m=st(e,I.index.name),B=K(E,f`SELECT ${Ue} AS value FROM ${f.identifier(m)} WHERE ${Ge} = ${M}`).toArray();return B[0]===void 0?0:B[0].value??0}}const T=Z(w,he);let C=f`SELECT COUNT(*) AS count FROM ${f.identifier(e)}`;return T&&(C=f`${C} WHERE ${T}`),K(E,C).one().count},async delete(e,t,r){_(e,"ctx.db.delete(table, id)");const a=re(t,e);if(!a){const I=Ae(e);I&&await it(I,e,[t],r);return}const{docJson:l,row:p,tableName:d}=a,w=u.tables[d],y=r?.hard===!0,T=!y&&w?.softDeleteMode?w:void 0,C=T?.softDeleteMode?.field;if(C&&p[C]!==null&&p[C]!==void 0)return;if(ne(d,"before","delete")&&await oe("before","delete",{id:t,op:"delete",previous:p,table:d}),r?.skipOnDelete!==!0&&await Xo({deletedId:t,deletedReference:I=>p[I],findHolders:async(I,M,m,B)=>(await tt(I).findMany(I,{...B,includeDeleted:y,where:{[M]:m}})).page,onCascade:(I,M)=>tt(I).delete(I,M,r),onRestrict:I=>{throw new ae(I,"restrict")},onSetNull:(I,M,m)=>tt(I).patch(I,M,{[m]:null}),schema:u,tableName:d}),ve(d),_e(d),T&&C){const I={[C]:me()},M={...p,...ee(d),...I,_id:t};ht(T,I,M,le),Qe(E,d,nn(d),[fe(M),t,l]),Be(d,t,M,p),Fe(d,t,void 0),Le(d,p,M),Te(d,t,p,void 0);const m=N(d,p,M);de?.invalidate(d,t,m),Se(d,t,"update",M),x({indexKeys:m,key:t,op:"update",row:M,table:d}),ne(d,"after","delete")&&await oe("after","delete",{id:t,op:"delete",previous:p,table:d}),await $e({id:t,op:"delete",table:d});return}Qe(E,d,br(d),[t,l]),Be(d,t,void 0),Fe(d,t,void 0),Le(d,p,void 0),Te(d,t,p,void 0);const A=N(d,p);de?.invalidate(d,t,A),Se(d,t,"delete"),x({indexKeys:A,key:t,op:"delete",table:d}),ne(d,"after","delete")&&await oe("after","delete",{id:t,op:"delete",previous:p,table:d}),await $e({id:t,op:"delete",table:d})},async deleteAll(e,t){if(!u.tables[e])throw new R("INTERNAL",`unknown table: ${e}`);if(s!==void 0)return $().deleteAll(e,t);const r=Math.max(1,t?.chunkSize??vn),a=t?.hard===void 0?void 0:{hard:t.hard},l=H(e,"deleteAll");let p=0;for(;;){const w=(await U.findMany(e,{includeDeleted:t?.hard===!0,limit:r})).page.map(y=>String(y._id));if(w.length===0)break;for(const y of w)await(l===void 0?U.delete(e,y,a):it(l,e,[y],a)),p+=1;if(w.length<r)break}return{deleted:p}},async deleteMany(e,t,r){_(e,"ctx.db.deleteMany(table, ids)"),Ke(t.length,r?.limit,"deleteMany");for(const a of t)await U.delete(e,a);return{deleted:t.length}},async deleteWhere(e,t,r){const a=H(e,"deleteWhere"),p=(await cn(a??U,e,t,r?.limit,"deleteWhere")).map(d=>String(d._id));if(a)return it(a,e,p,void 0,{options:r});if(U.deleteMany===void 0)throw new R("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return U.deleteMany(e,p,r)},async findFirst(e,t={}){return(await U.findMany(e,{...t,limit:1,omitContinueCursor:!0})).page[0]??null},async findFirstOrThrow(e,t={}){const r=await U.findFirst(e,t);if(r===null)throw new vo(`findFirstOrThrow: no "${e}" document matched`);return r},async findMany(e,t={}){const r=H(e,"findMany");if(r)return k(e,G),t.consistency==="primary"&&S(e,ao),r.findMany(e,t);const a=u.tables[e];if(!a)throw new R("INTERNAL",`unknown table: ${e}`);const l=!t.where&&!t.baseWhere;l?k(e,G):k(e);const{limit:p,orderKeys:d,statement:w}=await Ut(e,a,t,k),y=pe(E,w.text,...w.params).toArray();l&&s?.recordRead(y.length);const T=[];for(const A of y){const I=xe(A);I&&(T.push(I),!l&&typeof I._id=="string"&&k(e,I._id))}const C=Ho(T,{endCursor:t.endCursor,limit:p,omitContinueCursor:t.omitContinueCursor,orderKeys:d});return t.with&&await zo({fetcher:nt,groupedCounter:Wn,parents:C.page,...Yo(t),schema:u,tableName:e,with:t.with}),{...C,page:Sn(C.page,t.select,t.with)}},async explain(e,t={}){const r=H(e,"explain");if(r)return r.explain(e,t);const a=u.tables[e];if(!a)throw new R("INTERNAL",`unknown table: ${e}`);const{statement:l}=await Ut(e,a,t,()=>{}),p=pe(E,`EXPLAIN QUERY PLAN ${l.text}`,...l.params).toArray();return{params:l.params,plan:p.map(d=>String(d.detail)),sql:l.text}},async get(e,t){_(e,"ctx.db.get(table, id)");const r=re(t,e);if(!r){const a=Ae(e);return a?(S(e,t,!0),a.get(e,t)):(D(e),S(e,t,!0),null)}return ye(r,t),r.row},async lookupById(e,t){const r=re(e,t);if(!r){for(const a of qt(t))D(a),S(a,e,!0);return null}return ye(r,e),{row:r.row,tableName:r.tableName}},async groupBy(e,t){const r=H(e,"groupBy");if(r)return k(e,G),r.groupBy(e,t);const a=u.tables[e];if(!a)throw new R("INTERNAL",`unknown table: ${e}`);k(e,G);const l=t.agg??{op:"count"};if(Oe(l.op),l.op!=="count"&&!l.field)throw new R("INTERNAL",`groupBy(${e}, { agg: { op: "${l.op}" } }): "field" is required for non-count reducers`);const p=Ie(a.softDeleteMode,void 0),d=Q(Q(t.baseWhere,t.where),p),w=await ke(d,e,t.relationBaseWhere),y=w!==d;if(a.aggregateIndexes&&!t.baseWhere&&!y){const m=Xn(a.aggregateIndexes,l.op,l.field,t.by,t.where),B=m===void 0?0:Object.keys(m.partial).length,V=m?.index.by?.length??0;if(m&&(B===0||B===V)){ot(e,m.index);const X=st(e,m.index.name),J=Object.keys(m.partial),ue=[];if(J.length===(m.index.by??[]).length&&J.length>0){const We=ct(m.index.by??[],m.partial),qe=K(E,f`SELECT ${Ue} AS value, ${lt} AS count FROM ${f.identifier(X)} WHERE ${Ge} = ${We}`).toArray();return qe.length>0&&ue.push({key:{...m.partial},value:at(l.op,qe[0])}),ue}const Nn=K(E,f`SELECT ${Ge} AS key, ${Ue} AS value, ${lt} AS count FROM ${f.identifier(X)}`).toArray();for(const We of Nn){const qe=Jn(JSON.parse(We.key));ue.push({key:qe,value:at(l.op,We)})}return ue}}for(const m of[...t.by,l.field]){if(m===void 0)continue;const B=m===l.field?`groupBy(${e}, { agg: { op: "${l.op}", field: "${m}" } })`:`groupBy(${e}, { by: [..."${m}"] })`;dn(a,m,B)}const T=Z(w,he),C=t.by.map(m=>f`${we(m)} AS ${f.identifier(m)}`);if(l.op==="count")C.push(f`COUNT(*) AS value`);else{const{field:m}=l;if(m===void 0)throw new R("INTERNAL",`groupBy(${e}, { agg: { op: "${l.op}" } }): "field" is required for non-count reducers`);C.push(f`${f.raw(Oe(l.op))}(${we(m)}) AS value`)}let A=f`SELECT ${f.join(C,f`, `)} FROM ${f.identifier(e)}`;T&&(A=f`${A} WHERE ${T}`),A=f`${A} GROUP BY ${f.join(t.by.map(m=>we(m)),f`, `)}`;const I=K(E,A).toArray(),M=[];for(const m of I){const B={};for(const X of t.by)B[X]=fo(a.shape[X],m[X]??null);const{value:V}=m;M.push({key:B,value:V==null?null:Number(V)})}return M},async insert(e,t,r){const a=H(e,"insert");if(a)return xt(a,e,t,r,!0);const l=u.tables[e];if(!l)throw new R("INTERNAL",`unknown table: ${e}`);const p=r?.allowExplicitId===!0,d=je(l,yt(l,t,le),{supplied:t,trusted:p});let w;r?.clientId!==void 0?(Lr(r.clientId),w=r.clientId):r?.allowExplicitId&&typeof d._id=="string"?($t(d._id),w=d._id):w=_t();const y=r?.allowExplicitId&&typeof d._creationTime=="number"?d._creationTime:me(),T={...d,...ee(e),_creationTime:y,_id:w};return ne(e,"before","insert")&&await oe("before","insert",{doc:{...T},id:w,op:"insert",table:e}),p||q(e,T),ve(e),_e(e),mt(E,e,Ar(e),[w,y,fe(T)]),Bt(e,w,T),ne(e,"after","insert")&&await oe("after","insert",{doc:T,id:w,op:"insert",table:e}),await $e({doc:T,id:w,op:"insert",table:e}),w},async insertManyUnsafe(e,t,r){if(Ke(t.length,r?.limit,"insertManyUnsafe"),t.length===0)return[];const a=H(e,"insert");if(a){const y=[];Fr(u.tables[e],t,r?.allowExplicitId,le);for(const T of t)z(T);for(const T of t){const C=await a.insert(e,T,{allowExplicitId:r?.allowExplicitId});x({key:C,op:"insert",row:{...T,_id:C},table:e}),y.push(C)}return y}const l=u.tables[e];if(!l)throw new R("INTERNAL",`unknown table: ${e}`);ve(e),_e(e);const p=[];for(let y=0;y<t.length;y+=He)p.push(ee(e));const d=r?.allowExplicitId===!0?void 0:Jo(l),w=t.map((y,T)=>{const C=yt(l,y,le),A=d===void 0?C:je(d,C,{supplied:y}),I=r?.allowExplicitId===!0&&typeof A._id=="string"?A._id:void 0;I!==void 0&&$t(I);const M=I??_t(),m=r?.allowExplicitId===!0&&typeof A._creationTime=="number"?A._creationTime:me(),B={...A,...p[Math.floor(T/He)],_creationTime:m,_id:M};return{creationTime:m,document:B,id:M}});for(const y of w)z(y.document);for(let y=0;y<w.length;y+=He){const T=f.join(w.slice(y,y+He).map(A=>f`(${A.id}, ${A.creationTime}, ${fe(A.document)})`),f`, `),C=$n("sqlite",f`INSERT INTO ${f.identifier(e)} (id, _creationTime, ${f.identifier(ie)}) VALUES ${T}`);mt(E,e,C.sql,C.params)}for(const{document:y,id:T}of w)Bt(e,T,y),await Ee({doc:y,id:T,op:"insert",table:e});return w.map(y=>y.id)},async insertMany(e,t,r){Ke(t.length,r?.limit,"insertMany");const a=r?.skipDuplicates===!0,l=[],p=H(e,"insert");if(p)for(const w of t)z(w);const d=async w=>p?xt(p,e,w,void 0,!1):U.insert(e,w);for(const w of t)try{l.push(await d(w))}catch(y){if(a&&y instanceof ae&&y.kind==="unique")l.push(null);else throw y}return l},normalizeId(e,t){return ln(u,e,t)},async patch(e,t,r,a){_(e,"ctx.db.patch(table, id, values)");const l=re(t,e);if(!l){const M=Ae(e);if(M){z(r);try{await M.patch(e,t,r,a)}finally{ce("update",e,t)}return}throw new R("NOT_FOUND",`document not found: ${t}`)}const{docJson:p,row:d,tableName:w}=l,y=u.tables[w];if(!y)throw new R("INTERNAL",`unknown table: ${w}`);if(k(w,t),fn("patch",r),It(w,t,r,d)){o?.({fields:Object.keys(Ne(r)),id:t,table:w});return}const T=_o(y,r,d),C={...d,...Ne(T),...ee(w),_id:t};ht(y,T,C,le);const A=je(y,C,{only:new Set(Object.keys(T)),previous:()=>d,tolerateStoredNull:!0});To(a,d,A),ne(w,"before","update")&&await oe("before","update",{doc:{...A},id:t,op:"update",previous:d,table:w}),q(w,A,d),ve(w),_e(w),Qe(E,w,nn(w),[fe(A),t,p]),Be(w,t,A,d),Fe(w,t,A),Le(w,d,A),Te(w,t,d,A);const I=N(w,d,A);de?.invalidate(w,t,I),Se(w,t,"update",A),x({indexKeys:I,key:t,op:"update",row:A,table:w}),ne(w,"after","update")&&await oe("after","update",{doc:A,id:t,op:"update",previous:d,table:w}),await $e({doc:A,id:t,op:"update",table:w})},async patchIf(e,t,r){const a=H(e,"patchIf");if(a){if(a.patchIf===void 0)throw new R("INTERNAL",`ctx.db.patchIf on global table '${e}' is unsupported: its backend has no conditional write`);z(r.patch);let l;try{l=await a.patchIf(e,t,r)}catch(p){throw ce("update",e,t),p}return l.applied&&ce("update",e,t),l}if(!u.tables[e])throw new R("INTERNAL",`unknown table: ${e}`);for(let l=1;l<=un;l+=1){const p=await Hn(e,t,r,l<un,d=>U.patch(e,t,d,{verify:r.verify}));if(p!==void 0)return p}throw new ae(`patchIf on "${e}" kept conflicting; the row changed on every attempt`,"occ")},async patchMany(e,t,r){_(e,"ctx.db.patchMany(table, patches)"),Ke(t.length,r?.limit,"patchMany");for(const a of t)await U.patch(e,a.id,a.patch);return{patched:t.length}},async patchWhere(e,t,r){const a=H(e,"patchWhere")??U,p=(await cn(a,e,t.where,r?.limit,"patchWhere")).map(d=>({id:String(d._id),patch:t.patch}));if(U.patchMany===void 0)throw new R("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await U.patchMany(e,p,r),{patched:p.length}},async related(e,t){return jo(U,v,e,t)},relationEdges:v,deleteRereadTables:W,inTransaction:j,softDeleteFields:O,relationWrites:P,query(e){const t=H(e,"query");return t?(k(e,G),t.query(e)):Mn(E,u,e,te,r=>{r?F(r):k(e,G)},r=>{s?.recordRead(r)})},async rank(e,t,r){const a=H(e,"rank");if(te(e,t,"rank"),a)return k(e,G),a.rank(e,t,r);const l=u.tables[e];if(!l)throw new R("INTERNAL",`unknown table: ${e}`);const p=l.rankIndexes?.find(J=>J.name===t);if(!p)throw new R("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(Wt(e,l,p),r.restrictsCounts)throw new dt(e);k(e,G),rt(e,p);const d=typeof r.row=="string"?r.row:r.row._id;if(!d)return null;const w=Jt(e,p.name),y=p.sortBy.map((J,ue)=>zt(ue)),T=y.map(J=>De(J)).join(", "),C=K(E,f`SELECT ${f.identifier("__partition__")}, ${f.raw(T)} FROM ${f.identifier(w)} WHERE ${f.identifier("__id__")} = ${d}`).toArray(),[A]=C;if(A===void 0)return null;let I=A.__partition__;const M=Q(r.baseWhere,r.where);ut(M,u,e,"rank");const m=Do(p,M);if(m){const J=ko(p.partitionBy??[],m);if(J!==I)return null;I=J}const B=y.map(J=>A[J]),{before:V,total:X}=wn(E,w,y,p.sortBy,I,B,d);return{position:V+1,total:X}},async rankBefore(e,t,r){if(se(e))throw new R("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const a=u.tables[e];if(!a)throw new R("INTERNAL",`unknown table: ${e}`);const l=a.rankIndexes?.find(y=>y.name===t);if(!l)throw new R("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(r.restrictsCounts)throw new dt(e);k(e,G),rt(e,l);const p=Jt(e,l.name),d=l.sortBy.map((y,T)=>zt(T)),w=l.sortBy.map((y,T)=>Me(r.sortValues[T]??null));return wn(E,p,d,l.sortBy,r.partitionKey,w,r.rowId)},async rankPage(e,t,r={}){ut(Q(r.baseWhere,r.where),u,e,"rankPage");const a=H(e,"rankPage");if(te(e,t,"rank"),a)return k(e,G),a.rankPage(e,t,r);const{continueCursor:l,hasMore:p,rows:d}=Ht(Ot,e,t,r);return{continueCursor:l,isDone:!p,page:d.map(w=>w.doc)}},async rankPageRows(e,t,r={}){ut(Q(r.baseWhere,r.where),u,e,"rankPage"),te(e,t,"rank");const{directions:a,hasMore:l,rows:p}=Ht(Ot,e,t,r);return{directions:a,hasMore:l,rows:p}},async restore(e,t){_(e,"ctx.db.restore(table, id)");const r=re(t,e);if(!r){const p=Ae(e);if(p?.restore){try{await p.restore(e,t)}finally{ce("update",e,t)}return}throw new R("NOT_FOUND",`document not found: ${t}`)}const a=u.tables[r.tableName]?.softDeleteMode?.field;if(!a)throw new R("INTERNAL",`ctx.db.restore: table "${r.tableName}" is not a .softDelete() table`);const l=r.row[a]!==null&&r.row[a]!==void 0;await U.patch(e,t,{[a]:null}),l&&Te(r.tableName,t,void 0,r.row)},async replace(e,t,r,a){_(e,"ctx.db.replace(table, id, document)");const l=re(t,e);if(!l){const B=Ae(e);if(B){z(r);try{await B.replace(e,t,r,a)}finally{ce("update",e,t)}return}throw new R("NOT_FOUND",`document not found: ${t}`)}const{docJson:p,row:d,tableName:w}=l,y=u.tables[w];if(!y)throw new R("INTERNAL",`unknown table: ${w}`);fn("replace",r);const T=a?.allowExplicitId&&typeof r._creationTime=="number"?r._creationTime:void 0,C=typeof d._creationTime=="number"?d._creationTime:void 0,A=T??C??me(),I={...r,...ee(w),_creationTime:A,_id:t};ht(y,r,I,le);const M=a?.allowExplicitId===!0,m=je(y,I,{previous:()=>d,supplied:r,trusted:M});ne(w,"before","update")&&await oe("before","update",{doc:{...m},id:t,op:"update",previous:d,table:w}),M||q(w,m,d),ve(w),_e(w),Qe(E,w,Ir(w),[A,fe(m),t,p]),Be(w,t,m,d),Fe(w,t,m),Le(w,d,m),Te(w,t,d,m),de?.invalidate(w,t,N(w,d,m)),Se(w,t,"update",m),x({indexKeys:N(w,d,m),key:t,op:"update",row:m,table:w}),ne(w,"after","update")&&await oe("after","update",{doc:m,id:t,op:"update",previous:d,table:w}),await $e({doc:m,id:t,op:"update",table:w})},async wipeShard(e){const t=new Set(e?.exclude),r=e?.tables,a=Object.entries(u.tables).filter(([w,y])=>t.has(w)||r!==void 0&&!r.includes(w)?!1:y.shardMode?.kind!=="global").map(([w])=>w);if(r!==void 0){for(const w of r)if(!u.tables[w])throw new R("INTERNAL",`wipeShard: unknown table: ${w}`)}const l={};let p=0;const{deleteAll:d}=U;if(d===void 0)throw new R("INTERNAL","wipeShard: this writer has no deleteAll");for(const w of a){const y=await d(w,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});l[w]=y.deleted,p+=y.deleted}return{deleted:p,tables:l}}},Kn={db:U,scheduler:Tt};return n.enforceRls===!0?tr(U,u,(e,t)=>re(e,t)?.tableName,v):U};export{is as CDC_LOG_TABLE,Is as IDEMPOTENCY_TABLE,Qr as NotUniqueError,vs as advanceClientWatermark,ss as applyCdcChanges,fn as assertNoExplicitUndefined,$t as assertStorableRowId,Lr as assertValidClientId,ts as backfillAggregateIndexes,ns as backfillRankIndexes,os as backfillSearchIndexes,cs as bumpCdcEpoch,as as cdcCanVouchFor,ds as cdcForkedError,ls as cdcSeqLeavingRows,us as cdcTouchesTables,fs as cdcTrimmedError,hs as compactCdcDocs,hi as createShardCtxDb,ws as cursorBelowRetainedFloor,ri as meterReadBytes,_s as migrateClientWatermark,ps as minCdcReplayableSeq,gs as minCdcSeq,ln as normalizeIdStructurally,ys as readCdcChangeKeys,Es as readCdcChanges,$s as readCdcCursor,ms as readCdcEpoch,Ts as readClientWatermark,bs as readIdempotent,Ds as runShardMigrations,Ls as selectShapeMembers,Fs as selectShapeRows,Ne as stripReservedPatchFields,Rs as trimCdcChanges,xs as trimIdempotent,Cs as writeIdempotent};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{N as uo,S as $o,d as Eo,e as go,a as po}from"./fts-companion-CE3EmIjk.mjs";import{sql as o}from"drizzle-orm";import{r as Y}from"./json-field-path-DeJW4U9z.mjs";import{matchesStaticWhere as X,aggregateSqlFunction as mo}from"./AGGREGATE_SQL_FUNCTION-C_ZipS9R.mjs";import{aggregateTableName as j,foldAggregateTally as J,encodeAggregateKey as k,coerceAggregateNumber as U}from"./aggregateTableName-B_CtIQCS.mjs";import{aggregateSignature as ho,readCompanionSignature as Z,rankSignature as So,writeCompanionSignature as N}from"./CompanionMemo-BXU5vfak.mjs";import{runAll as _o,runDrizzle as g}from"./runDrizzle-RC09zZrh.mjs";import{i as yo,g as Ro,a as F,b as A,A as h,c as H,D as x,u as oo,r as eo,e as V}from"./do-sql-105TONaE.mjs";import{WORKERD_SQLITE_LIMITS as no,param as q}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{encodeGeohash as To,GEO_DEFAULT_PRECISION as Ao}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{isLiveForCompanion as to}from"./CURSOR_PREFIX-rOdoinP8.mjs";import{rankTableName as B,matchesRankStaticWhere as ro,sortColumnName as wo,encodePartitionKey as Co}from"./RANK_TIEBREAK-D3ye2GsL.mjs";import{mayHoldProjectedValue as Io}from"./BIGINT_KEY_DIGITS-DE6yshOt.mjs";import{serializeSqlValue as so}from"./serializeSqlValue-DeoBMpZ2.mjs";const Oo=(r,f,t)=>[...r.partitionBy??[],...r.sortBy.map(l=>l.field),...r.where?Object.keys(r.where):[]].every(l=>Y(f,l)===Y(t,l)),io=r=>o.join(["__id__","__partition__",...r.sortBy.map((f,t)=>wo(t))].map(f=>o.identifier(f)),o`, `),co=(r,f,t)=>{const $=Co(r.partitionBy??[],t),l=r.sortBy.map(s=>so(t[s.field]??null)),c=o.join([f,$,...l].map(s=>q(s)),o`, `);return o`(${c})`},vo=(r,f,t,$,l,c)=>{g(r,o`INSERT INTO ${o.identifier(f)} (${$}) VALUES ${co(t,l,c)}`)},Q=1e3,ao=function*(f,t,$,l){let c;for(;;){const s=c===void 0?o``:o` WHERE id > ${q(c)}`,y=[...g(oo(f),o`SELECT id, _creationTime, ${o.identifier(x)} FROM ${o.identifier(t)}${s} ORDER BY id LIMIT ${q(Q)}`)];for(const S of y){const R=eo(S);R&&to(R,$)&&l(R)&&(yield R)}if(y.length<Q)return;c=String(y.at(-1)?.id)}},ko=(r,f,t,$,l)=>{const c=j(f,t.name),s=t.by??[],y=new Map;for(const w of ao(r,f,$,I=>!t.where||X(I,t.where)))J(y,k(s,w),t,w);g(r,o`DELETE FROM ${o.identifier(c)}`);const S=Math.floor(no.boundParams/3),R=[...y];for(let w=0;w<R.length;w+=S){const I=R.slice(w,w+S),P=o.join(I.map(([b,D])=>o`(${b}, ${D.value}, ${D.count})`),o`, `);g(r,o`INSERT INTO ${o.identifier(c)} (${F}, ${A}, ${h}) VALUES ${P}`)}N(r,c,l)},Lo=(r,f,t,$)=>{const l=ho(t,$);Z(r,j(f,t.name))!==l&&ko(r,f,t,$,l)},Fo=(r,f,t,$,l)=>{const c=B(f,t.name),s=io(t);g(r,o`DELETE FROM ${o.identifier(c)}`);const y=Math.max(1,Math.floor(no.boundParams/(2+t.sortBy.length)));let S=[];const R=()=>{S.length>0&&(g(r,o`INSERT INTO ${o.identifier(c)} (${s}) VALUES ${o.join(S,o`, `)}`),S=[])};for(const w of ao(r,f,$,I=>!t.where||ro(I,t.where)))S.push(co(t,w._id,w)),S.length>=y&&R();R(),N(r,c,l)},Do=(r,f,t,$)=>{const l=So(t,$);Z(r,B(f,t.name))!==l&&Fo(r,f,t,$,l)},Mo=(r,f,t,$,l,c)=>{if(l&&c&&Oo(t,l,c))return;const s=B(f,t.name);l&&g(r,o`DELETE FROM ${o.identifier(s)} WHERE ${o.identifier("__id__")} = ${$}`),!(!c||t.where&&!ro(c,t.where))&&vo(r,s,t,io(t),$,c)},Jo=r=>{const{broadcast:f,indexKeysFor:t,invalidateCache:$,recordCdc:l,schema:c,sql:s}=r,y=r.verified??new Set,S=e=>c.tables[e]?.softDeleteMode?.field,R=(e,n)=>{const a=j(e,n.name);y.has(a)||(Lo(s,e,n,S(e)),y.add(a))},w=(e,n,a)=>{const p=n.by??[],d=n.field??"",E=[],_=(i,u)=>{const m=so(u);m===null?E.push(o`${V(i)} IS NULL`):E.push(o`${V(i)} = ${m}`)};for(const i of p)_(i,a[i]??null);const C=S(e);C!==void 0&&_(C,null);for(const[i,u]of Object.entries(n.where??{}))_(i,u!==null&&typeof u=="object"&&!Array.isArray(u)?u.eq:u);const L=E.length>0?o` WHERE ${o.join(E,o` AND `)}`:o``,M=c.tables[e]?.shape[d];if(M&&Io(M)){const i=g(oo(s),o`SELECT id, _creationTime, ${o.identifier(x)} FROM ${o.identifier(e)}${L}`).toArray(),u=new Map;for(const m of i){const v=eo(m);v&&J(u,"",n,v)}return{value:u.get("")?.value??null}}const W=mo(n.op),T=V(d);return{value:g(s,o`SELECT ${o.raw(W)}(${T}) AS value FROM ${o.identifier(e)}${L}`).one().value??null}},I=(e,n,a,p)=>{const d=j(e,n.name),{op:E}=n,_=n.field??"",C=i=>{g(s,o`DELETE FROM ${o.identifier(d)} WHERE ${F} = ${i} AND ${h} <= 0`)},L=S(e),M=i=>!n.where||X(i,n.where),W=i=>to(i,L)&&M(i);p!==void 0&&E!=="count"&&M(p)&&U(p[_]);const T=a&&W(a)?a:void 0,O=p&&W(p)?p:void 0;if(!(!T&&!O)){if(E==="count"){for(const[i,u]of[[T,-1],[O,1]]){if(!i)continue;const m=k(n.by??[],i);g(s,H(d,m,u,u,o`${A} = ${A} + excluded.${A}, ${h} = ${h} + excluded.${h}`))}T&&C(k(n.by??[],T));return}if(E==="sum"||E==="avg"){for(const[i,u]of[[T,-1],[O,1]]){if(!i)continue;const m=U(i[_]);if(m===void 0)continue;const v=k(n.by??[],i);g(s,H(d,v,u*m,u,o`${A} = COALESCE(${A}, 0) + excluded.${A}, ${h} = ${h} + excluded.${h}`))}T&&C(k(n.by??[],T));return}if(T){const i=k(n.by??[],T),u=U(T[_]),m=g(s,o`SELECT ${A} AS value, ${h} AS count FROM ${o.identifier(d)} WHERE ${F} = ${i}`).toArray()[0],v=(m?.count??0)-1;if(v<=0)g(s,o`DELETE FROM ${o.identifier(d)} WHERE ${F} = ${i}`);else if(m&&u!==void 0&&m.value!==null&&u===m.value){const lo=w(e,n,T);g(s,o`UPDATE ${o.identifier(d)} SET ${A} = ${lo.value}, ${h} = ${v} WHERE ${F} = ${i}`)}else g(s,o`UPDATE ${o.identifier(d)} SET ${h} = ${h} - 1 WHERE ${F} = ${i}`)}if(O){const i=k(n.by??[],O),u=U(O[_]);if(u===void 0)g(s,H(d,i,null,1,o`${h} = ${h} + 1`));else{const m=E==="min"?"MIN":"MAX";g(s,H(d,i,u,1,o`${A} = ${o.raw(m)}(COALESCE(${A}, excluded.${A}), excluded.${A}), ${h} = ${h} + 1`))}}}},P=e=>{for(const n of c.tables[e]?.aggregateIndexes??[])R(e,n)},b=(e,n,a)=>{for(const p of c.tables[e]?.aggregateIndexes??[])I(e,p,n,a)},D=(e,n)=>{const a=B(e,n.name);y.has(a)||(Do(s,e,n,S(e)),y.add(a))},fo=e=>{for(const n of c.tables[e]?.rankIndexes??[])D(e,n)},G=(e,n,a,p)=>{for(const d of c.tables[e]?.rankIndexes??[])Mo(s,e,d,n,a,p)},K=(e,n,a,p)=>{const d=c.tables[e]?.searchIndexes??[];if(!(d.length===0||!yo(s)))for(const E of d){if(uo(p,a,E))continue;const _=$o(e,E.name);_o(s,a?Eo(_,n,go(a,E)):po(_,n))}},z=(e,n,a)=>{for(const p of c.tables[e]?.geoIndexes??[]){const d=Ro(e,p.name);g(s,o`DELETE FROM ${o.identifier(d)} WHERE ${o.identifier("__id__")} = ${n}`);const E=a?.[p.field];if(E!==null&&typeof E=="object"&&typeof E.lat=="number"&&typeof E.lng=="number"){const{lat:_,lng:C}=E,L=To({lat:_,lng:C},p.precision??Ao);g(s,o`INSERT INTO ${o.identifier(d)} (${o.identifier("__id__")}, ${o.identifier("__geohash__")}, ${o.identifier("__lat__")}, ${o.identifier("__lng__")}) VALUES (${n}, ${L}, ${_}, ${C})`)}}};return{ensureBackfilledForTable:P,ensureBackfilledIndex:R,ensureRankBackfilled:D,ensureRankBackfilledForTable:fo,syncAggregates:b,syncCompanionsForInsert:(e,n,a)=>{K(e,n,a),z(e,n,a),b(e,void 0,a),G(e,n,void 0,a),$(e,n,a),l(e,n,"insert",a),f({indexKeys:t(e,a),key:n,op:"insert",row:a,table:e})},syncGeo:z,syncRanks:G,syncSearch:K}};export{Jo as createCompanionSync,Lo as ensureAggregateCompanion,Do as ensureRankCompanion};
|