@lunora/shard-engine 1.0.0-alpha.14 → 1.0.0-alpha.140
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/README.md +1 -1
- package/dist/conformance/index.mjs +1 -1
- package/dist/index.d.mts +824 -163
- package/dist/index.d.ts +824 -163
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/ADMIN_FUNCTIONS-B0QCN3HM.mjs +1 -0
- package/dist/packem_shared/AGGREGATE_SQL_FUNCTION-C_ZipS9R.mjs +1 -0
- package/dist/packem_shared/AGG_COUNT-CBe5drFS.mjs +1 -0
- package/dist/packem_shared/AUDIT_LOG_TABLE-CuIP7PJ0.mjs +8 -0
- package/dist/packem_shared/BIGINT_KEY_DIGITS-DE6yshOt.mjs +1 -0
- package/dist/packem_shared/CDC_LOG_TABLE-DsCz-DAV.mjs +18 -0
- package/dist/packem_shared/CLIENT_WATERMARK_TABLE-_CkdMnT2.mjs +7 -0
- package/dist/packem_shared/COMMIT_SEQ_FIELD-BcUO15fR.mjs +4 -0
- package/dist/packem_shared/CURSOR_PREFIX-6offuG6M.mjs +1 -0
- package/dist/packem_shared/CountRlsUnsupportedError-BvsDqfO2.mjs +1 -0
- package/dist/packem_shared/DATA_MIGRATION_STATE_TABLE-CmsAKy5V.mjs +31 -0
- package/dist/packem_shared/DEFAULT_MAX_RELATION_KEYS-BYfAkNAH.mjs +1 -0
- package/dist/packem_shared/DEFAULT_MAX_RELAYS-B5CxBHmO.mjs +8 -0
- package/dist/packem_shared/DEFAULT_PROMOTION_THRESHOLDS-B3pRMuqb.mjs +1 -0
- package/dist/packem_shared/DEFAULT_TRANSACTION_LIMITS-Dmj5VBrV.mjs +1 -0
- package/dist/packem_shared/DurableStreamRunner-Dzge_ywD.mjs +1 -0
- package/dist/packem_shared/GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs +1 -0
- package/dist/packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-Du0PbPdS.mjs +7 -0
- package/dist/packem_shared/GlobalPollTick-BNK4o-XT.mjs +1 -0
- package/dist/packem_shared/IDEMPOTENCY_TABLE-CymJf4r0.mjs +7 -0
- package/dist/packem_shared/MAIL_RETENTION-BP1GSXQ0.mjs +18 -0
- package/dist/packem_shared/MAX_SQL_ROWS-Dh_Ty0Zo.mjs +4 -0
- package/dist/packem_shared/MAX_TOKEN_LENGTH-BakL9FUy-B3VwYY8C.mjs +1 -0
- package/dist/packem_shared/NotUniqueError-CNXsYOSU.mjs +1 -0
- package/dist/packem_shared/QUEUE_TABLE-jEc6-2wm.mjs +17 -0
- package/dist/packem_shared/RANK_TIEBREAK-D3ye2GsL.mjs +1 -0
- package/dist/packem_shared/REACTOR_STATE_TABLE-DHaBP_vb.mjs +28 -0
- package/dist/packem_shared/RELATED_DEFAULT_LIMIT-CVqN4JEu.mjs +1 -0
- package/dist/packem_shared/RELATION_EXISTS_KEY-wxgj6rSL.mjs +1 -0
- package/dist/packem_shared/RELAY_SIGNATURE_HEADER-C_P73AOx.mjs +1 -0
- package/dist/packem_shared/REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs +1 -0
- package/dist/packem_shared/RLS_UNWRAP_SYMBOL-J1tiBtRj.mjs +1 -0
- package/dist/packem_shared/ReactiveCache-DHhhLJtN.mjs +1 -0
- package/dist/packem_shared/SCAN_DEP-D7qE3iUe.mjs +1 -0
- package/dist/packem_shared/SCHEDULE_OUTBOX_TABLE-C_Me442c.mjs +11 -0
- package/dist/packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-SQVxBlum.mjs +6 -0
- package/dist/packem_shared/SEARCH_STATE_TABLE-BThmEiED.mjs +1 -0
- package/dist/packem_shared/SHAPE_POKE_CURSOR_TABLE-B6MXBH-p.mjs +8 -0
- package/dist/packem_shared/ShapeDiffCache-iNO-hUiy.mjs +1 -0
- package/dist/packem_shared/ShardRunner-CrveaPId.mjs +1 -0
- package/dist/packem_shared/UNVOUCHABLE_DEP-C68htACn.mjs +1 -0
- package/dist/packem_shared/VECTOR_BACKFILL_MAX_PAGES-DY_3FYts.mjs +1 -0
- package/dist/packem_shared/WORKERD_SQLITE_LIMITS-BdNnnMj0.mjs +1 -0
- package/dist/packem_shared/accepts-null-D1zmJbyR.mjs +1 -0
- package/dist/packem_shared/aggregateTableName-B_CtIQCS.mjs +1 -0
- package/dist/packem_shared/appendStreamChunk-DF_Jrgpy.mjs +17 -0
- package/dist/packem_shared/applyOnDelete-BwxDC4lU.mjs +1 -0
- package/dist/packem_shared/archiveCdcSegment-CIiYU1FU.mjs +4 -0
- package/dist/packem_shared/{armRestore-BNzdvQ_o.mjs → armRestore-Bu1_8SUa.mjs} +1 -1
- package/dist/packem_shared/assertPatchAllowed-CA_H466g.mjs +1 -0
- package/dist/packem_shared/awaitWsDrain-N-oR29RI.mjs +1 -0
- package/dist/packem_shared/backfillAggregateIndexes-Dw4Azd33.mjs +1 -0
- package/dist/packem_shared/buildIndexRange-DQ3eWAGd.mjs +1 -0
- package/dist/packem_shared/buildPokeFrames-WR-hp0mX.mjs +1 -0
- package/dist/packem_shared/buildReprojectionMigration-DQV0q3w9.mjs +1 -0
- package/dist/packem_shared/buildSettings-BRkZd6_E.mjs +1 -0
- package/dist/packem_shared/buildShapeDiff-BHr3i1m6.mjs +1 -0
- package/dist/packem_shared/clearCompanionSignatures-8uVX84aT.mjs +1 -0
- package/dist/packem_shared/clearMemoryTables-Lu0S2GOb.mjs +1 -0
- package/dist/packem_shared/compileWhereSql-CKoO19by.mjs +1 -0
- package/dist/packem_shared/computeRankPage-DLSi_oBt.mjs +1 -0
- package/dist/packem_shared/createCompanionSync-DhYLePyV.mjs +1 -0
- package/dist/packem_shared/createReplicaLink-BqNxWyzF.mjs +7 -0
- package/dist/packem_shared/createSystemReader-DcDLFfC-.mjs +1 -0
- package/dist/packem_shared/ctx-db-relay-shapes-CPwELrMf.mjs +17 -0
- package/dist/packem_shared/ctx-db-search-state-CrTLPmFN.mjs +1 -0
- package/dist/packem_shared/defineEngineContractSuite-DHnbaiVb.mjs +1 -0
- package/dist/packem_shared/describeRelationWrites-omar6-u9.mjs +1 -0
- package/dist/packem_shared/diffExternalSource-B0FZlDoL.mjs +1 -0
- package/dist/packem_shared/do-sql-DqU-17Fs.mjs +1 -0
- package/dist/packem_shared/effective-kind-BmG_zCAy.mjs +1 -0
- package/dist/packem_shared/envOptionalPositiveInt-D2pY-c64.mjs +1 -0
- package/dist/packem_shared/estimate-bytes-_k74s6LZ.mjs +1 -0
- package/dist/packem_shared/exportShardRows-yxw7vFf9.mjs +1 -0
- package/dist/packem_shared/fts-companion-DzfEHonU.mjs +1 -0
- package/dist/packem_shared/ftsCompanionDdl-Cka6_-Fm.mjs +1 -0
- package/dist/packem_shared/hasTrigger-CjlwI4le.mjs +1 -0
- package/dist/packem_shared/isInternalTableName-BoljO2tP.mjs +1 -0
- package/dist/packem_shared/isPushableWhere-BeYAOjUb.mjs +1 -0
- package/dist/packem_shared/isSoftDeleted-D5MeQSk0.mjs +9 -0
- package/dist/packem_shared/json-field-path-DeJW4U9z.mjs +1 -0
- package/dist/packem_shared/liftSourceId-CA3ENhXj.mjs +1 -0
- package/dist/packem_shared/materializeExternalRows-D2zEvCAa.mjs +1 -0
- package/dist/packem_shared/mergeChangedKeys-CF2mjYuy.mjs +1 -0
- package/dist/packem_shared/relation-operators-BEg-CvCH.mjs +1 -0
- package/dist/packem_shared/runDrizzle-B2GG3IJa.mjs +1 -0
- package/dist/packem_shared/runShardMigrations-BeqUbznb.mjs +5 -0
- package/dist/packem_shared/runSocketPool-CZJ2X9cF.mjs +1 -0
- package/dist/packem_shared/selectExpiredIds-B8PxwbIr.mjs +1 -0
- package/dist/packem_shared/selectShapeMembers-B1MIaRkE.mjs +1 -0
- package/dist/packem_shared/serializeSqlValue-DeoBMpZ2.mjs +1 -0
- package/dist/packem_shared/where-sql-DO1vOrhc.mjs +1 -0
- package/package.json +5 -4
- package/dist/packem_shared/ADMIN_FUNCTIONS-xKxYOiRC.mjs +0 -1
- package/dist/packem_shared/AGGREGATE_SQL_FUNCTION-CTo0-9iZ.mjs +0 -1
- package/dist/packem_shared/AGG_COUNT-B0Pb1nQZ.mjs +0 -1
- package/dist/packem_shared/AUDIT_LOG_TABLE-C6nwXFPd.mjs +0 -8
- package/dist/packem_shared/CDC_LOG_TABLE-D__2M4gX.mjs +0 -8
- package/dist/packem_shared/CLIENT_WATERMARK_TABLE-CzApRlyv.mjs +0 -7
- package/dist/packem_shared/CountRlsUnsupportedError-8BqPYQoP.mjs +0 -1
- package/dist/packem_shared/DATA_MIGRATION_STATE_TABLE-BrpAGtXf.mjs +0 -31
- package/dist/packem_shared/DEFAULT_MAX_RELATION_KEYS-C7Iky4H5.mjs +0 -1
- package/dist/packem_shared/DEFAULT_MAX_RELAYS-AcHLNxha.mjs +0 -1
- package/dist/packem_shared/DEFAULT_PROMOTION_THRESHOLDS-BdmnUGLO.mjs +0 -1
- package/dist/packem_shared/DEFAULT_TRANSACTION_LIMITS-BH5q0Ror.mjs +0 -1
- package/dist/packem_shared/GEO_DEFAULT_PRECISION-DyI5zggj.mjs +0 -1
- package/dist/packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-soMJDSBs.mjs +0 -7
- package/dist/packem_shared/IDEMPOTENCY_TABLE-Bvu9JkiL.mjs +0 -7
- package/dist/packem_shared/MAIL_RETENTION-BefR9Sei.mjs +0 -18
- package/dist/packem_shared/MAX_SQL_ROWS-nMwkxv5f.mjs +0 -2
- package/dist/packem_shared/NotUniqueError-GHJiYnzm.mjs +0 -1
- package/dist/packem_shared/QUEUE_TABLE-DgBqWrXX.mjs +0 -17
- package/dist/packem_shared/RANK_TIEBREAK-D541BOFR.mjs +0 -1
- package/dist/packem_shared/RELATION_EXISTS_KEY-BaqSIFU1.mjs +0 -1
- package/dist/packem_shared/RLS_UNWRAP_SYMBOL-DcqORh2s.mjs +0 -1
- package/dist/packem_shared/ReactiveCache-iWA9VRqk.mjs +0 -1
- package/dist/packem_shared/SCAN_DEP-D_yR9EeV.mjs +0 -1
- package/dist/packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-BEU0CuW5.mjs +0 -6
- package/dist/packem_shared/SEARCH_STATE_TABLE-BZ_fxI5l.mjs +0 -1
- package/dist/packem_shared/ShardRunner-DIqVdWtk.mjs +0 -1
- package/dist/packem_shared/aggregateTableName-DKo6dwBP.mjs +0 -1
- package/dist/packem_shared/applyOnDelete-CxpItW0j.mjs +0 -1
- package/dist/packem_shared/applySelect-BjgwvZmI.mjs +0 -1
- package/dist/packem_shared/awaitWsDrain-DKycCSBS.mjs +0 -1
- package/dist/packem_shared/backfillAggregateIndexes-BVNrfFcI.mjs +0 -1
- package/dist/packem_shared/buildIndexRange-DFsdtPjD.mjs +0 -1
- package/dist/packem_shared/buildPokeFrames-CCxYXd2V.mjs +0 -1
- package/dist/packem_shared/buildSettings-COIJsw7a.mjs +0 -1
- package/dist/packem_shared/compileWhereSql-B4rPariq.mjs +0 -1
- package/dist/packem_shared/computeRankPage-B7U6t1fW.mjs +0 -1
- package/dist/packem_shared/createCompanionSync-Dym8huD9.mjs +0 -1
- package/dist/packem_shared/createReadFootprint-DIrrxRTE.mjs +0 -1
- package/dist/packem_shared/createSystemReader-DcDcrtM3.mjs +0 -1
- package/dist/packem_shared/ctx-db-companions-7fIu-E2H.mjs +0 -1
- package/dist/packem_shared/defineEngineContractSuite-Zg5xN9h4.mjs +0 -1
- package/dist/packem_shared/diffExternalSource-DMpkJta1.mjs +0 -1
- package/dist/packem_shared/estimate-bytes-DwQON1Ky.mjs +0 -1
- package/dist/packem_shared/exportShardRows-Bbi_JGfn.mjs +0 -1
- package/dist/packem_shared/hasTrigger-CbkOHExZ.mjs +0 -1
- package/dist/packem_shared/isSoftDeleted-doD_8AwX.mjs +0 -9
- package/dist/packem_shared/liftSourceId-DApAbu7Q.mjs +0 -1
- package/dist/packem_shared/materializeExternalRows-BR8MvZTz.mjs +0 -1
- package/dist/packem_shared/mergeChangedKeys-BXtUgIPW.mjs +0 -1
- package/dist/packem_shared/param-B5lF5Jd9.mjs +0 -1
- package/dist/packem_shared/runDrizzle-B6rnz3so.mjs +0 -1
- package/dist/packem_shared/runShardMigrations-DhZLG0bn.mjs +0 -5
- package/dist/packem_shared/runSocketPool-DPQLVyWF.mjs +0 -1
- package/dist/packem_shared/selectExpiredIds-DxFEwNlT.mjs +0 -1
- package/dist/packem_shared/selectShapeMemberIds-BD3JiZn-.mjs +0 -1
- package/dist/packem_shared/serializeSqlValue-DnpyaLcw.mjs +0 -1
- package/dist/packem_shared/stableStringify-BjLh4gvA.mjs +0 -1
- package/dist/packem_shared/stableWireKey-C4JfdJ_e.mjs +0 -1
- package/dist/packem_shared/wire-codec-D_fiax9d.mjs +0 -1
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{exportShardRows as o,exportShardTable as a,importShardRows as t,parseExportShardArgs as n,parseImportShardArgs as l,selectExportTables as s,validateImportRow as i}from"./packem_shared/exportShardRows-Bbi_JGfn.mjs";import{AGGREGATE_SQL_FUNCTION as d,aggregateSqlFunction as p,matchesStaticWhere as c,normalizeCountArgument as S,throwingScheduler as u}from"./packem_shared/AGGREGATE_SQL_FUNCTION-CTo0-9iZ.mjs";import{aggregateTableName as f,coerceAggregateNumber as T,encodeAggregateKey as g,foldAggregateTally as h,readAggregateValue as A}from"./packem_shared/aggregateTableName-DKo6dwBP.mjs";import{CountRlsUnsupportedError as C,mergeWhere as I,planAggregateLookup as _,selectIndexForAggregate as R,selectIndexForCount as L,selectIndexForGroupBy as b}from"./packem_shared/CountRlsUnsupportedError-8BqPYQoP.mjs";import{AUDIT_LOG_TABLE as N,appendAuditEntry as M,ensureAuditTable as F,readAuditLog as O}from"./packem_shared/AUDIT_LOG_TABLE-C6nwXFPd.mjs";import{NotUniqueError as k,assertValidClientId as P,createShardCtxDb as B,normalizeIdStructurally as G}from"./packem_shared/NotUniqueError-GHJiYnzm.mjs";import{backfillAggregateIndexes as w,backfillRankIndexes as K,backfillSearchIndexes as q,backfillSearchIndexesForTable as W}from"./packem_shared/backfillAggregateIndexes-BVNrfFcI.mjs";import{CDC_LOG_TABLE as z,CDC_META_TABLE as V,appendCdcChange as H,applyCdcChanges as X,bumpCdcEpoch as Q,migrateCdcLog as Y,migrateCdcMeta as j,minCdcSeq as J,readCdcChanges as Z,readCdcCursor as $,readCdcEpoch as ee,trimCdcChanges as re}from"./packem_shared/CDC_LOG_TABLE-D__2M4gX.mjs";import{CLIENT_WATERMARK_TABLE as ae,advanceClientWatermark as te,migrateClientWatermark as ne,readClientWatermark as le}from"./packem_shared/CLIENT_WATERMARK_TABLE-CzApRlyv.mjs";import{k as ie}from"./packem_shared/ctx-db-companions-7fIu-E2H.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as de,deleteGlobalShapeSnapshot as pe,deleteGlobalShapeSnapshotsForConnection as ce,migrateGlobalShapeSnapshot as Se,readGlobalShapeSnapshot as ue,writeGlobalShapeSnapshot as xe}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-soMJDSBs.mjs";import{IDEMPOTENCY_TABLE as Te,migrateIdempotency as ge,readIdempotent as he,trimIdempotent as Ae,writeIdempotent as Ee}from"./packem_shared/IDEMPOTENCY_TABLE-Bvu9JkiL.mjs";import{computeRankPage as Ie,hydrateDocsById as _e}from"./packem_shared/computeRankPage-B7U6t1fW.mjs";import{SEARCH_STATE_TABLE as Le,migrateSearchState as be,readSearchBackfillState as ye,writeSearchBackfillState as Ne}from"./packem_shared/SEARCH_STATE_TABLE-BZ_fxI5l.mjs";import{selectShapeMemberIds as Fe,selectShapeRows as Oe}from"./packem_shared/selectShapeMemberIds-BD3JiZn-.mjs";import{DATA_MIGRATION_STATE_TABLE as ke,readMigrationStatus as Pe,runDataMigration as Be}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-BrpAGtXf.mjs";import{SCAN_DEP as Ue,createDependencyTracker as we,depKey as Ke,tableFromDepKey as qe}from"./packem_shared/SCAN_DEP-D_yR9EeV.mjs";import{runDrizzle as ve,runSql as ze}from"./packem_shared/runDrizzle-B6rnz3so.mjs";import{AGG_COUNT as He,AGG_KEY as Xe,AGG_VALUE as Qe,DOC_COLUMN as Ye,aggUpsertSql as je,createIndexSql as Je,geoTableName as Ze,isFtsAvailable as $e,jsonPath as er,jsonPathSql as rr,qualifiedJsonPath as or,qualifiedJsonPathSql as ar,rowToDocument as tr,tableColumns as nr,tryRowToDocument as lr}from"./packem_shared/AGG_COUNT-B0Pb1nQZ.mjs";import{param as ir,renderSql as mr}from"./packem_shared/param-B5lF5Jd9.mjs";import{diffExternalSource as pr}from"./packem_shared/diffExternalSource-DMpkJta1.mjs";import{liftSourceId as Sr,normalizeSourceDocument as ur,normalizeSourceValue as xr}from"./packem_shared/liftSourceId-DApAbu7Q.mjs";import{materializeExternalRows as Tr,materializeExternalRowsIncremental as gr,readExternalSourceBaseline as hr,runExternalSourceTick as Ar}from"./packem_shared/materializeExternalRows-BR8MvZTz.mjs";import{isSoftDeleted as Cr,isSourceDue as Ir,pullExternalSourceIncrementalTick as _r,pullExternalSourceTick as Rr}from"./packem_shared/isSoftDeleted-doD_8AwX.mjs";import{GEO_DEFAULT_PRECISION as br,boundingBoxCenter as yr,boundingBoxGeohashes as Nr,coveringGeohashes as Mr,encodeGeohash as Fr,haversineMeters as Or,pointInBoundingBox as Dr}from"./packem_shared/GEO_DEFAULT_PRECISION-DyI5zggj.mjs";import{ADMIN_FUNCTIONS as Pr,ADMIN_FUNCTION_PREFIX as Br,DEFAULT_FANOUT_TOPIC_LIMIT as Gr,FLAGS_FUNCTION_PREFIX as Ur,MAX_PAGE_SIZE as wr,RELATION_FUNCTION_PREFIX as Kr,createFanoutCounters as qr,facetColumn as Wr,findStorageReferences as vr,listTables as zr,readTablePage as Vr,recordFanoutPass as Hr,selectMatchingIds as Xr,summarizeFanoutTopics as Qr,summarizeSubscriptions as Yr}from"./packem_shared/ADMIN_FUNCTIONS-xKxYOiRC.mjs";import{MAIL_RETENTION as Jr,MAIL_TABLE as Zr,clearCapturedMail as $r,ensureMailTable as eo,readCapturedMail as ro,recordCapturedMail as oo}from"./packem_shared/MAIL_RETENTION-BefR9Sei.mjs";import{NotFoundError as to}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{armRestore as lo,readBookmark as so}from"./packem_shared/armRestore-BNzdvQ_o.mjs";import{applySelect as mo,buildSeekBeforeWhere as po,buildSeekWhere as co,decodeCursor as So,encodeCursor as uo,normalizeOrderKeys as xo,softDeleteScope as fo}from"./packem_shared/applySelect-BjgwvZmI.mjs";import{QUEUE_TABLE as go,clearQueueMessages as ho,isLossyBody as Ao,readQueueMessageById as Eo,readQueueMessages as Co,recordQueueMessages as Io}from"./packem_shared/QUEUE_TABLE-DgBqWrXX.mjs";import{RANK_TIEBREAK as Ro,encodePartitionKey as Lo,matchesRankStaticWhere as bo,rankKeyFromDoc as yo,rankTableName as No,resolveRankPartition as Mo,sortColumnName as Fo}from"./packem_shared/RANK_TIEBREAK-D541BOFR.mjs";import{ReactiveCache as Do,reactiveCacheKey as ko}from"./packem_shared/ReactiveCache-iWA9VRqk.mjs";import{createReadFootprint as Bo}from"./packem_shared/createReadFootprint-DIrrxRTE.mjs";import{buildIndexRange as Uo,indexKeysForRow as wo,keysTouchRanges as Ko}from"./packem_shared/buildIndexRange-DFsdtPjD.mjs";import{DEFAULT_MAX_RELATION_KEYS as Wo,assertFlatPredicate as vo,assertShapeShardable as zo,containsRelationPredicate as Vo,isRelationPredicate as Ho,resolveRelationPredicates as Xo}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-C7Iky4H5.mjs";import{applyOnDelete as Yo,distinctValues as jo,fanOutScalarCounts as Jo,resolveWith as Zo,runRowValidators as $o}from"./packem_shared/applyOnDelete-CxpItW0j.mjs";import{DEFAULT_PROMOTION_THRESHOLDS as ra,clampPromotionThresholds as oa,nextPromotionState as aa,relayCountFor as ta,shapeRoutingKey as na}from"./packem_shared/DEFAULT_PROMOTION_THRESHOLDS-BdmnUGLO.mjs";import{DEFAULT_MAX_RELAYS as sa,OwnerRelay as ia,RelayMember as ma,createRelayLink as da}from"./packem_shared/DEFAULT_MAX_RELAYS-AcHLNxha.mjs";import{RLS_UNWRAP_SYMBOL as ca,RlsRequiredError as Sa,guardWriter as ua}from"./packem_shared/RLS_UNWRAP_SYMBOL-DcqORh2s.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as fa,readSchemaHistory as Ta,readSchemaVersion as ga,recordSchemaVersion as ha}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-BEU0CuW5.mjs";import{serializeSqlValue as Ea}from"./packem_shared/serializeSqlValue-DnpyaLcw.mjs";import{buildSettings as Ia,isDevEnvironment as _a}from"./packem_shared/buildSettings-COIJsw7a.mjs";import{buildPokeFrames as La,diffGlobalMembership as ba,encodeRowsPatch as ya,projectColumns as Na}from"./packem_shared/buildPokeFrames-CCxYXd2V.mjs";import{ShardRunner as Fa}from"./packem_shared/ShardRunner-DIqVdWtk.mjs";import{runSocketPool as Da}from"./packem_shared/runSocketPool-DPQLVyWF.mjs";import{MAX_SQL_ROWS as Pa,assertReadonly as Ba,lintReadonlySql as Ga,runReadonlySql as Ua}from"./packem_shared/MAX_SQL_ROWS-nMwkxv5f.mjs";import{awaitWsDrain as Ka,sendDeltaFrames as qa,subscriptionListDeltas as Wa,trySendFrame as va}from"./packem_shared/awaitWsDrain-DKycCSBS.mjs";import{mergeChangedKeys as Va,recordChangedKeys as Ha,writeTouchesMemo as Xa}from"./packem_shared/mergeChangedKeys-BXtUgIPW.mjs";import{createSystemReader as Ya}from"./packem_shared/createSystemReader-DcDcrtM3.mjs";import{ConflictError as Ja}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as $a,TransactionHeadroomTracker as et}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS-BH5q0Ror.mjs";import{hasTrigger as ot,runTriggers as at}from"./packem_shared/hasTrigger-CbkOHExZ.mjs";import{selectExpiredIds as nt}from"./packem_shared/selectExpiredIds-DxFEwNlT.mjs";import{compileWhereSql as st}from"./packem_shared/compileWhereSql-B4rPariq.mjs";import{RELATION_EXISTS_KEY as mt}from"./packem_shared/RELATION_EXISTS_KEY-BaqSIFU1.mjs";import{quoteIdentifier as pt}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as St}from"./packem_shared/runShardMigrations-DhZLG0bn.mjs";import{stableStringify as xt}from"./packem_shared/stableStringify-BjLh4gvA.mjs";import{stableWireKey as Tt}from"./packem_shared/stableWireKey-C4JfdJ_e.mjs";export{Pr as ADMIN_FUNCTIONS,Br as ADMIN_FUNCTION_PREFIX,d as AGGREGATE_SQL_FUNCTION,He as AGG_COUNT,Xe as AGG_KEY,Qe as AGG_VALUE,N as AUDIT_LOG_TABLE,z as CDC_LOG_TABLE,V as CDC_META_TABLE,ae as CLIENT_WATERMARK_TABLE,Ja as ConflictError,C as CountRlsUnsupportedError,ke as DATA_MIGRATION_STATE_TABLE,Gr as DEFAULT_FANOUT_TOPIC_LIMIT,Wo as DEFAULT_MAX_RELATION_KEYS,sa as DEFAULT_MAX_RELAYS,ra as DEFAULT_PROMOTION_THRESHOLDS,$a as DEFAULT_TRANSACTION_LIMITS,Ye as DOC_COLUMN,Ur as FLAGS_FUNCTION_PREFIX,br as GEO_DEFAULT_PRECISION,de as GLOBAL_SHAPE_SNAPSHOT_TABLE,Te as IDEMPOTENCY_TABLE,Jr as MAIL_RETENTION,Zr as MAIL_TABLE,wr as MAX_PAGE_SIZE,Pa as MAX_SQL_ROWS,to as NotFoundError,k as NotUniqueError,ia as OwnerRelay,go as QUEUE_TABLE,Ro as RANK_TIEBREAK,mt as RELATION_EXISTS_KEY,Kr as RELATION_FUNCTION_PREFIX,ca as RLS_UNWRAP_SYMBOL,Do as ReactiveCache,ma as RelayMember,Sa as RlsRequiredError,Ue as SCAN_DEP,fa as SCHEMA_HISTORY_MAX_VERSIONS,Le as SEARCH_STATE_TABLE,Fa as ShardRunner,et as TransactionHeadroomTracker,te as advanceClientWatermark,je as aggUpsertSql,p as aggregateSqlFunction,f as aggregateTableName,M as appendAuditEntry,H as appendCdcChange,X as applyCdcChanges,Yo as applyOnDelete,mo as applySelect,lo as armRestore,vo as assertFlatPredicate,Ba as assertReadonly,zo as assertShapeShardable,P as assertValidClientId,Ka as awaitWsDrain,w as backfillAggregateIndexes,K as backfillRankIndexes,q as backfillSearchIndexes,W as backfillSearchIndexesForTable,yr as boundingBoxCenter,Nr as boundingBoxGeohashes,Uo as buildIndexRange,La as buildPokeFrames,po as buildSeekBeforeWhere,co as buildSeekWhere,Ia as buildSettings,Q as bumpCdcEpoch,oa as clampPromotionThresholds,$r as clearCapturedMail,ho as clearQueueMessages,T as coerceAggregateNumber,st as compileWhereSql,Ie as computeRankPage,Vo as containsRelationPredicate,Mr as coveringGeohashes,ie as createCompanionSync,we as createDependencyTracker,qr as createFanoutCounters,Je as createIndexSql,Bo as createReadFootprint,da as createRelayLink,B as createShardCtxDb,Ya as createSystemReader,So as decodeCursor,pe as deleteGlobalShapeSnapshot,ce as deleteGlobalShapeSnapshotsForConnection,Ke as depKey,pr as diffExternalSource,ba as diffGlobalMembership,jo as distinctValues,g as encodeAggregateKey,uo as encodeCursor,Fr as encodeGeohash,Lo as encodePartitionKey,ya as encodeRowsPatch,F as ensureAuditTable,eo as ensureMailTable,o as exportShardRows,a as exportShardTable,Wr as facetColumn,Jo as fanOutScalarCounts,vr as findStorageReferences,h as foldAggregateTally,Ze as geoTableName,ua as guardWriter,ot as hasTrigger,Or as haversineMeters,_e as hydrateDocsById,t as importShardRows,wo as indexKeysForRow,_a as isDevEnvironment,$e as isFtsAvailable,Ao as isLossyBody,Ho as isRelationPredicate,Cr as isSoftDeleted,Ir as isSourceDue,er as jsonPath,rr as jsonPathSql,Ko as keysTouchRanges,Sr as liftSourceId,Ga as lintReadonlySql,zr as listTables,bo as matchesRankStaticWhere,c as matchesStaticWhere,Tr as materializeExternalRows,gr as materializeExternalRowsIncremental,Va as mergeChangedKeys,I as mergeWhere,Y as migrateCdcLog,j as migrateCdcMeta,ne as migrateClientWatermark,Se as migrateGlobalShapeSnapshot,ge as migrateIdempotency,be as migrateSearchState,J as minCdcSeq,aa as nextPromotionState,S as normalizeCountArgument,G as normalizeIdStructurally,xo as normalizeOrderKeys,ur as normalizeSourceDocument,xr as normalizeSourceValue,ir as param,n as parseExportShardArgs,l as parseImportShardArgs,_ as planAggregateLookup,Dr as pointInBoundingBox,Na as projectColumns,_r as pullExternalSourceIncrementalTick,Rr as pullExternalSourceTick,or as qualifiedJsonPath,ar as qualifiedJsonPathSql,pt as quoteIdentifier,yo as rankKeyFromDoc,No as rankTableName,ko as reactiveCacheKey,A as readAggregateValue,O as readAuditLog,so as readBookmark,ro as readCapturedMail,Z as readCdcChanges,$ as readCdcCursor,ee as readCdcEpoch,le as readClientWatermark,hr as readExternalSourceBaseline,ue as readGlobalShapeSnapshot,he as readIdempotent,Pe as readMigrationStatus,Eo as readQueueMessageById,Co as readQueueMessages,Ta as readSchemaHistory,ga as readSchemaVersion,ye as readSearchBackfillState,Vr as readTablePage,oo as recordCapturedMail,Ha as recordChangedKeys,Hr as recordFanoutPass,Io as recordQueueMessages,ha as recordSchemaVersion,ta as relayCountFor,mr as renderSql,Mo as resolveRankPartition,Xo as resolveRelationPredicates,Zo as resolveWith,tr as rowToDocument,Be as runDataMigration,ve as runDrizzle,Ar as runExternalSourceTick,Ua as runReadonlySql,$o as runRowValidators,St as runShardMigrations,Da as runSocketPool,ze as runSql,at as runTriggers,nt as selectExpiredIds,s as selectExportTables,R as selectIndexForAggregate,L as selectIndexForCount,b as selectIndexForGroupBy,Xr as selectMatchingIds,Fe as selectShapeMemberIds,Oe as selectShapeRows,qa as sendDeltaFrames,Ea as serializeSqlValue,na as shapeRoutingKey,fo as softDeleteScope,Fo as sortColumnName,xt as stableStringify,Tt as stableWireKey,Wa as subscriptionListDeltas,Qr as summarizeFanoutTopics,Yr as summarizeSubscriptions,nr as tableColumns,qe as tableFromDepKey,u as throwingScheduler,re as trimCdcChanges,Ae as trimIdempotent,lr as tryRowToDocument,va as trySendFrame,i as validateImportRow,xe as writeGlobalShapeSnapshot,Ee as writeIdempotent,Ne as writeSearchBackfillState,Xa as writeTouchesMemo};
|
|
1
|
+
import{exportShardRows as o,importShardRows as a,parseExportShardArgs as t,parseImportShardArgs as i,selectExportTables as s,validateImportRow as l}from"./packem_shared/exportShardRows-yxw7vFf9.mjs";import{AGGREGATE_SQL_FUNCTION as d,aggregateSqlFunction as c,matchesStaticWhere as m,normalizeCountArgument as p,throwingScheduler as S}from"./packem_shared/AGGREGATE_SQL_FUNCTION-C_ZipS9R.mjs";import{aggregateTableName as f,coerceAggregateNumber as E,encodeAggregateKey as h,foldAggregateTally as x,readAggregateValue as T}from"./packem_shared/aggregateTableName-B_CtIQCS.mjs";import{CountRlsUnsupportedError as A,mergeWhere as C,planAggregateLookup as g,selectIndexForAggregate as _,selectIndexForCount as I,selectIndexForGroupBy as b}from"./packem_shared/CountRlsUnsupportedError-BvsDqfO2.mjs";import{AUDIT_LOG_TABLE as D,appendAuditEntry as P,ensureAuditTable as O,readAuditLog as F}from"./packem_shared/AUDIT_LOG_TABLE-CuIP7PJ0.mjs";import{NotUniqueError as y,assertNoExplicitUndefined as N,assertValidClientId as k,createShardCtxDb as B,normalizeIdStructurally as U,stripReservedPatchFields as G}from"./packem_shared/NotUniqueError-CNXsYOSU.mjs";import{backfillAggregateIndexes as q,backfillRankIndexes as v,backfillSearchIndexes as K,backfillSearchIndexesForTable as W}from"./packem_shared/backfillAggregateIndexes-Dw4Azd33.mjs";import{CDC_LOG_TABLE as H,CDC_LOG_TABLE_SEQ_INDEX as V,CDC_META_TABLE as z,appendCdcChange as Q,applyCdcChanges as Y,bumpCdcEpoch as j,cdcCanVouchFor as J,cdcForkedError as Z,cdcSeqLeavingRows as $,cdcTouchesTables as ee,cdcTrimmedError as re,compactCdcDocs as oe,cursorBelowRetainedFloor as ae,migrateCdcLog as te,migrateCdcMeta as ie,minCdcReplayableSeq as se,minCdcSeq as le,readCdcChangeKeys as ne,readCdcChanges as de,readCdcCursor as ce,readCdcEpoch as me,trimCdcChanges as pe}from"./packem_shared/CDC_LOG_TABLE-DsCz-DAV.mjs";import{archiveCdcSegment as ue,cdcArchiveRewound as fe,readArchivedCdcChanges as Ee,readCdcArchivedThrough as he,writeCdcArchivedThrough as xe}from"./packem_shared/archiveCdcSegment-CIiYU1FU.mjs";import{CLIENT_WATERMARK_TABLE as Re,advanceClientWatermark as Ae,migrateClientWatermark as Ce,readClientWatermark as ge}from"./packem_shared/CLIENT_WATERMARK_TABLE-_CkdMnT2.mjs";import{COMMIT_SEQ_FIELD as Ie,COMMIT_SEQ_TABLE as be,allocateCommitSeq as Le,migrateCommitSeq as De,readCommitSeq as Pe}from"./packem_shared/COMMIT_SEQ_FIELD-BcUO15fR.mjs";import{clearCompanionSignatures as Fe}from"./packem_shared/clearCompanionSignatures-8uVX84aT.mjs";import{createCompanionSync as ye}from"./packem_shared/createCompanionSync-DhYLePyV.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as ke,deleteGlobalShapeSnapshot as Be,deleteGlobalShapeSnapshotsForConnection as Ue,migrateGlobalShapeSnapshot as Ge,readGlobalShapeSnapshot as we,writeGlobalShapeSnapshot as qe}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-Du0PbPdS.mjs";import{IDEMPOTENCY_TABLE as Ke,migrateIdempotency as We,readIdempotent as Xe,trimIdempotent as He,writeIdempotent as Ve}from"./packem_shared/IDEMPOTENCY_TABLE-CymJf4r0.mjs";import{clearMemoryTables as Qe,isMemoryTable as Ye,memoryTableNames as je}from"./packem_shared/clearMemoryTables-Lu0S2GOb.mjs";import{computeRankPage as Ze,resolveRankSeekTuple as $e}from"./packem_shared/computeRankPage-DLSi_oBt.mjs";import{SCHEDULE_OUTBOX_TABLE as rr,deferScheduleOutbox as or,forgetScheduleOutbox as ar,migrateScheduleOutbox as tr,parkScheduleOutbox as ir,probeScheduleOutbox as sr,readDueScheduleOutbox as lr,recordScheduleOutbox as nr,trimScheduleOutbox as dr}from"./packem_shared/SCHEDULE_OUTBOX_TABLE-C_Me442c.mjs";import{S as mr,m as pr,r as Sr,w as ur}from"./packem_shared/ctx-db-search-state-CrTLPmFN.mjs";import{SHAPE_POKE_CURSOR_TABLE as Er,deleteShapePokeCursor as hr,deleteShapePokeCursorsForConnection as xr,migrateShapePokeCursor as Tr,minShapePokeCursor as Rr,readShapePokeCursor as Ar,writeShapePokeCursor as Cr,writeShapePokeCursors as gr}from"./packem_shared/SHAPE_POKE_CURSOR_TABLE-B6MXBH-p.mjs";import{selectShapeMembers as Ir,selectShapeRows as br}from"./packem_shared/selectShapeMembers-B1MIaRkE.mjs";import{DATA_MIGRATION_STATE_TABLE as Dr,readMigrationStatus as Pr,runDataMigration as Or}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-CmsAKy5V.mjs";import{SCAN_DEP as Mr,createDependencyTracker as yr,depKey as Nr,tableFromDepKey as kr}from"./packem_shared/SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as Ur,runSql as Gr}from"./packem_shared/runDrizzle-B2GG3IJa.mjs";import{A as qr,a as vr,b as Kr,D as Wr,c as Xr,d as Hr,g as Vr,i as zr,j as Qr,e as Yr,q as jr,f as Jr,r as Zr,t as $r,h as eo}from"./packem_shared/do-sql-DqU-17Fs.mjs";import{WORKERD_SQLITE_LIMITS as oo,param as ao,renderSql as to,sqliteInList as io,unionAll as so}from"./packem_shared/WORKERD_SQLITE_LIMITS-BdNnnMj0.mjs";import{appendStreamChunk as no,claimStreamRun as co,deleteStreamRun as mo,finishStreamRun as po,migrateDurableStreams as So,readStreamChunks as uo,readStreamRun as fo,trimStreamRuns as Eo}from"./packem_shared/appendStreamChunk-DF_Jrgpy.mjs";import{DurableStreamRunner as xo,MAX_DURABLE_STREAM_BYTES as To,MAX_DURABLE_STREAM_CHUNKS as Ro,decideDurableAttach as Ao}from"./packem_shared/DurableStreamRunner-Dzge_ywD.mjs";import{envOptionalPositiveInt as go,envPositiveInt as _o}from"./packem_shared/envOptionalPositiveInt-D2pY-c64.mjs";import{diffExternalSource as bo}from"./packem_shared/diffExternalSource-B0FZlDoL.mjs";import{liftSourceId as Do,normalizeSourceDocument as Po,normalizeSourceValue as Oo}from"./packem_shared/liftSourceId-CA3ENhXj.mjs";import{materializeExternalRows as Mo,materializeExternalRowsIncremental as yo,readExternalSourceBaseline as No,runExternalSourceTick as ko}from"./packem_shared/materializeExternalRows-D2zEvCAa.mjs";import{isSoftDeleted as Uo,isSourceDue as Go,pullExternalSourceIncrementalTick as wo,pullExternalSourceTick as qo}from"./packem_shared/isSoftDeleted-D5MeQSk0.mjs";import{f as Ko,a as Wo,b as Xo,c as Ho,d as Vo,g as zo}from"./packem_shared/fts-companion-DzfEHonU.mjs";import{GEO_DEFAULT_PRECISION as Yo,boundingBoxCenter as jo,boundingBoxGeohashes as Jo,coveringGeohashes as Zo,encodeGeohash as $o,haversineMeters as ea,pointInBoundingBox as ra}from"./packem_shared/GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{default as aa}from"./packem_shared/GlobalPollTick-BNK4o-XT.mjs";import{ADMIN_FUNCTIONS as ia,ADMIN_FUNCTION_PREFIX as sa,DEFAULT_FANOUT_TOPIC_LIMIT as la,FLAGS_FUNCTION_PREFIX as na,MAX_PAGE_SIZE as da,RELATION_FUNCTION_PREFIX as ca,createFanoutCounters as ma,createGlobalPollCounters as pa,createShapeProbeCounters as Sa,facetColumn as ua,findStorageReferences as fa,isVacuousFilterClause as Ea,listTables as ha,readTablePage as xa,recordFanoutPass as Ta,recordGlobalPollPass as Ra,recordShapeProbePass as Aa,selectMatchingIds as Ca,summarizeFanoutTopics as ga,summarizeSubscriptions as _a}from"./packem_shared/ADMIN_FUNCTIONS-B0QCN3HM.mjs";import{MAIL_RETENTION as ba,MAIL_TABLE as La,clearCapturedMail as Da,ensureMailTable as Pa,readCapturedMail as Oa,recordCapturedMail as Fa}from"./packem_shared/MAIL_RETENTION-BP1GSXQ0.mjs";import{NotFoundError as ya}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{assertPatchAllowed as ka,operatorFields as Ba,patchDependsOnRow as Ua,readPatchField as Ga,resolvePatch as wa}from"./packem_shared/assertPatchAllowed-CA_H466g.mjs";import{armRestore as va,readBookmark as Ka}from"./packem_shared/armRestore-Bu1_8SUa.mjs";import{CURSOR_PREFIX as Xa,applySelect as Ha,buildSeekBeforeWhere as Va,buildSeekWhere as za,decodeCursor as Qa,encodeCursor as Ya,equalityPinnedFields as ja,normalizeOrderKeys as Ja,nullsFirstOf as Za,nullsOrderSuffix as $a,softDeleteScope as et,tiebreakDirectionFor as rt,uniqueIndexFields as ot}from"./packem_shared/CURSOR_PREFIX-6offuG6M.mjs";import{QUEUE_TABLE as tt,clearQueueMessages as it,isLossyBody as st,readQueueMessageById as lt,readQueueMessages as nt,recordQueueMessages as dt}from"./packem_shared/QUEUE_TABLE-jEc6-2wm.mjs";import{RANK_TIEBREAK as mt,encodePartitionKey as pt,matchesRankStaticWhere as St,rankKeyFromDoc as ut,rankPivotConditionSql as ft,rankTableName as Et,resolveRankPartition as ht,sortColumnName as xt}from"./packem_shared/RANK_TIEBREAK-D3ye2GsL.mjs";import{ReactiveCache as Rt,reactiveCacheKey as At}from"./packem_shared/ReactiveCache-DHhhLJtN.mjs";import{REACTOR_STATE_TABLE as gt,listReactorStates as _t,migrateReactorState as It,reactorNeedsRun as bt,readReactorState as Lt,writeReactorState as Dt}from"./packem_shared/REACTOR_STATE_TABLE-DHaBP_vb.mjs";import{UNVOUCHABLE_DEP as Ot,createReadFootprint as Ft,markUnvouchableReads as Mt}from"./packem_shared/UNVOUCHABLE_DEP-C68htACn.mjs";import{buildIndexRange as Nt,indexKeysForRow as kt,keysTouchRanges as Bt}from"./packem_shared/buildIndexRange-DQ3eWAGd.mjs";import{isPushableWhere as Gt,whereFilter as wt,whereOfFilter as qt}from"./packem_shared/isPushableWhere-BeYAOjUb.mjs";import{RELATED_DEFAULT_LIMIT as Kt,RELATED_DEPTH_DECAY as Wt,RELATED_MAX_DEPTH as Xt,RELATED_MAX_LIMIT as Ht,deriveRelationEdges as Vt,findRelated as zt}from"./packem_shared/RELATED_DEFAULT_LIMIT-CVqN4JEu.mjs";import{DEFAULT_MAX_RELATION_KEYS as Yt,assertFlatPredicate as jt,assertShapeShardable as Jt,composeReadPredicate as Zt,containsRelationPredicate as $t,isRelationPredicate as ei,resolveRelationPredicates as ri}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-BYfAkNAH.mjs";import{describeRelationWrites as ai}from"./packem_shared/describeRelationWrites-omar6-u9.mjs";import{applyOnDelete as ii,distinctValues as si,fanOutScalarCounts as li,relationHooks as ni,resolveWith as di,runRowValidators as ci}from"./packem_shared/applyOnDelete-BwxDC4lU.mjs";import{DEFAULT_PROMOTION_THRESHOLDS as pi,clampPromotionThresholds as Si,nextPromotionState as ui,relayCountFor as fi,shapeRoutingKey as Ei}from"./packem_shared/DEFAULT_PROMOTION_THRESHOLDS-B3pRMuqb.mjs";import{DEFAULT_MAX_RELAYS as xi,OwnerRelay as Ti,RelayMember as Ri,createRelayLink as Ai}from"./packem_shared/DEFAULT_MAX_RELAYS-B5CxBHmO.mjs";import{createReplicaLink as gi,gateReplicaDispatch as _i,handleReplicaControl as Ii}from"./packem_shared/createReplicaLink-BqNxWyzF.mjs";import{buildReprojectionMigration as Li,countLegacyRows as Di,reprojectableFields as Pi,reprojectionTables as Oi}from"./packem_shared/buildReprojectionMigration-DQV0q3w9.mjs";import{RLS_UNWRAP_SYMBOL as Mi,RlsRequiredError as yi,guardWriter as Ni}from"./packem_shared/RLS_UNWRAP_SYMBOL-J1tiBtRj.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as Bi,readSchemaHistory as Ui,readSchemaVersion as Gi,recordSchemaVersion as wi}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-SQVxBlum.mjs";import{serializeSqlValue as vi}from"./packem_shared/serializeSqlValue-DeoBMpZ2.mjs";import{buildSettings as Wi,isDevEnvironment as Xi,readDeployInfo as Hi}from"./packem_shared/buildSettings-BRkZd6_E.mjs";import{buildShapeDiff as zi}from"./packem_shared/buildShapeDiff-BHr3i1m6.mjs";import{ShapeDiffCache as Yi,createShapeDiffCache as ji,globalShapeReadKey as Ji}from"./packem_shared/ShapeDiffCache-iNO-hUiy.mjs";import{buildPokeFrames as $i,diffGlobalMembership as es,encodeRowsPatch as rs,projectColumns as os}from"./packem_shared/buildPokeFrames-WR-hp0mX.mjs";import{ShardRunner as ts}from"./packem_shared/ShardRunner-CrveaPId.mjs";import{RELAY_SIGNATURE_HEADER as ss,siblingSecretOf as ls,signSiblingBody as ns,stubByName as ds,verifySiblingBody as cs}from"./packem_shared/RELAY_SIGNATURE_HEADER-C_P73AOx.mjs";import{runSocketPool as ps}from"./packem_shared/runSocketPool-CZJ2X9cF.mjs";import{MAX_SQL_ROWS as us,assertReadonly as fs,lintReadonlySql as Es,runReadonlySql as hs}from"./packem_shared/MAX_SQL_ROWS-Dh_Ty0Zo.mjs";import{BIGINT_KEY_DIGITS as Ts,bigintSqlKey as Rs,decodeBigintSqlKey as As,decodeFloat64SqlKey as Cs,float64SqlKey as gs}from"./packem_shared/BIGINT_KEY_DIGITS-DE6yshOt.mjs";import{awaitWsDrain as Is,subscriptionFrames as bs,subscriptionListDeltas as Ls,trySendFrame as Ds}from"./packem_shared/awaitWsDrain-N-oR29RI.mjs";import{mergeChangedKeys as Os,recordChangedKeys as Fs,writeTouchesMemo as Ms}from"./packem_shared/mergeChangedKeys-CF2mjYuy.mjs";import{createSystemReader as Ns}from"./packem_shared/createSystemReader-DcDLFfC-.mjs";import{ConflictError as Bs}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as Gs,TransactionHeadroomTracker as ws}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS-Dmj5VBrV.mjs";import{hasTrigger as vs,runTriggers as Ks}from"./packem_shared/hasTrigger-CjlwI4le.mjs";import{selectExpiredIds as Xs}from"./packem_shared/selectExpiredIds-B8PxwbIr.mjs";import{VECTOR_BACKFILL_MAX_PAGES as Vs,backfillVectorIndexes as zs}from"./packem_shared/VECTOR_BACKFILL_MAX_PAGES-DY_3FYts.mjs";import{c as Ys,s as js}from"./packem_shared/where-sql-DO1vOrhc.mjs";import{RELATION_EXISTS_KEY as Zs}from"./packem_shared/RELATION_EXISTS_KEY-wxgj6rSL.mjs";import{REPROJECTION_MIGRATION_PREFIX as el,reprojectionMigrationId as rl}from"./packem_shared/REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{isInternalTableName as al}from"./packem_shared/isInternalTableName-BoljO2tP.mjs";import{quoteIdentifier as il}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as ll}from"./packem_shared/runShardMigrations-BeqUbznb.mjs";import{stableStringify as dl,stableWireKey as cl}from"@lunora/wire";export{ia as ADMIN_FUNCTIONS,sa as ADMIN_FUNCTION_PREFIX,d as AGGREGATE_SQL_FUNCTION,qr as AGG_COUNT,vr as AGG_KEY,Kr as AGG_VALUE,D as AUDIT_LOG_TABLE,Ts as BIGINT_KEY_DIGITS,H as CDC_LOG_TABLE,V as CDC_LOG_TABLE_SEQ_INDEX,z as CDC_META_TABLE,Re as CLIENT_WATERMARK_TABLE,Ie as COMMIT_SEQ_FIELD,be as COMMIT_SEQ_TABLE,Xa as CURSOR_PREFIX,Bs as ConflictError,A as CountRlsUnsupportedError,Dr as DATA_MIGRATION_STATE_TABLE,la as DEFAULT_FANOUT_TOPIC_LIMIT,Yt as DEFAULT_MAX_RELATION_KEYS,xi as DEFAULT_MAX_RELAYS,pi as DEFAULT_PROMOTION_THRESHOLDS,Gs as DEFAULT_TRANSACTION_LIMITS,Wr as DOC_COLUMN,xo as DurableStreamRunner,na as FLAGS_FUNCTION_PREFIX,Yo as GEO_DEFAULT_PRECISION,ke as GLOBAL_SHAPE_SNAPSHOT_TABLE,aa as GlobalPollTick,Ke as IDEMPOTENCY_TABLE,ba as MAIL_RETENTION,La as MAIL_TABLE,To as MAX_DURABLE_STREAM_BYTES,Ro as MAX_DURABLE_STREAM_CHUNKS,da as MAX_PAGE_SIZE,us as MAX_SQL_ROWS,ya as NotFoundError,y as NotUniqueError,Ti as OwnerRelay,tt as QUEUE_TABLE,mt as RANK_TIEBREAK,gt as REACTOR_STATE_TABLE,Kt as RELATED_DEFAULT_LIMIT,Wt as RELATED_DEPTH_DECAY,Xt as RELATED_MAX_DEPTH,Ht as RELATED_MAX_LIMIT,Zs as RELATION_EXISTS_KEY,ca as RELATION_FUNCTION_PREFIX,ss as RELAY_SIGNATURE_HEADER,el as REPROJECTION_MIGRATION_PREFIX,Mi as RLS_UNWRAP_SYMBOL,Rt as ReactiveCache,Ri as RelayMember,yi as RlsRequiredError,Mr as SCAN_DEP,rr as SCHEDULE_OUTBOX_TABLE,Bi as SCHEMA_HISTORY_MAX_VERSIONS,mr as SEARCH_STATE_TABLE,Er as SHAPE_POKE_CURSOR_TABLE,Yi as ShapeDiffCache,ts as ShardRunner,ws as TransactionHeadroomTracker,Ot as UNVOUCHABLE_DEP,Vs as VECTOR_BACKFILL_MAX_PAGES,oo as WORKERD_SQLITE_LIMITS,Ae as advanceClientWatermark,Xr as aggUpsertSql,c as aggregateSqlFunction,f as aggregateTableName,Le as allocateCommitSeq,P as appendAuditEntry,Q as appendCdcChange,no as appendStreamChunk,Y as applyCdcChanges,ii as applyOnDelete,Ha as applySelect,ue as archiveCdcSegment,va as armRestore,jt as assertFlatPredicate,N as assertNoExplicitUndefined,ka as assertPatchAllowed,fs as assertReadonly,Jt as assertShapeShardable,k as assertValidClientId,Is as awaitWsDrain,q as backfillAggregateIndexes,v as backfillRankIndexes,K as backfillSearchIndexes,W as backfillSearchIndexesForTable,zs as backfillVectorIndexes,Rs as bigintSqlKey,jo as boundingBoxCenter,Jo as boundingBoxGeohashes,Nt as buildIndexRange,$i as buildPokeFrames,Li as buildReprojectionMigration,Va as buildSeekBeforeWhere,za as buildSeekWhere,Wi as buildSettings,zi as buildShapeDiff,j as bumpCdcEpoch,fe as cdcArchiveRewound,J as cdcCanVouchFor,Z as cdcForkedError,$ as cdcSeqLeavingRows,ee as cdcTouchesTables,re as cdcTrimmedError,co as claimStreamRun,Si as clampPromotionThresholds,Da as clearCapturedMail,Fe as clearCompanionSignatures,Qe as clearMemoryTables,it as clearQueueMessages,E as coerceAggregateNumber,oe as compactCdcDocs,Ys as compileWhereSql,Zt as composeReadPredicate,Ze as computeRankPage,$t as containsRelationPredicate,Di as countLegacyRows,Zo as coveringGeohashes,ye as createCompanionSync,yr as createDependencyTracker,ma as createFanoutCounters,pa as createGlobalPollCounters,Hr as createIndexSql,Ft as createReadFootprint,Ai as createRelayLink,gi as createReplicaLink,ji as createShapeDiffCache,Sa as createShapeProbeCounters,B as createShardCtxDb,Ns as createSystemReader,ae as cursorBelowRetainedFloor,Ao as decideDurableAttach,As as decodeBigintSqlKey,Qa as decodeCursor,Cs as decodeFloat64SqlKey,or as deferScheduleOutbox,Be as deleteGlobalShapeSnapshot,Ue as deleteGlobalShapeSnapshotsForConnection,hr as deleteShapePokeCursor,xr as deleteShapePokeCursorsForConnection,mo as deleteStreamRun,Nr as depKey,Vt as deriveRelationEdges,ai as describeRelationWrites,bo as diffExternalSource,es as diffGlobalMembership,si as distinctValues,h as encodeAggregateKey,Ya as encodeCursor,$o as encodeGeohash,pt as encodePartitionKey,rs as encodeRowsPatch,O as ensureAuditTable,Pa as ensureMailTable,go as envOptionalPositiveInt,_o as envPositiveInt,ja as equalityPinnedFields,o as exportShardRows,ua as facetColumn,li as fanOutScalarCounts,zt as findRelated,fa as findStorageReferences,po as finishStreamRun,gs as float64SqlKey,x as foldAggregateTally,ar as forgetScheduleOutbox,Ko as ftsCompanionDdl,Wo as ftsPurgeDocument,Xo as ftsRowidMapName,Ho as ftsUnmappedPage,Vo as ftsWriteDocument,_i as gateReplicaDispatch,Vr as geoTableName,Ji as globalShapeReadKey,zo as groupUnmappedRows,Ni as guardWriter,Ii as handleReplicaControl,vs as hasTrigger,ea as haversineMeters,a as importShardRows,kt as indexKeysForRow,Xi as isDevEnvironment,zr as isFtsAvailable,al as isInternalTableName,st as isLossyBody,Ye as isMemoryTable,Gt as isPushableWhere,ei as isRelationPredicate,Uo as isSoftDeleted,Go as isSourceDue,Ea as isVacuousFilterClause,Qr as jsonPath,Yr as jsonPathSql,Bt as keysTouchRanges,Do as liftSourceId,Es as lintReadonlySql,_t as listReactorStates,ha as listTables,Mt as markUnvouchableReads,St as matchesRankStaticWhere,m as matchesStaticWhere,Mo as materializeExternalRows,yo as materializeExternalRowsIncremental,je as memoryTableNames,Os as mergeChangedKeys,C as mergeWhere,te as migrateCdcLog,ie as migrateCdcMeta,Ce as migrateClientWatermark,De as migrateCommitSeq,So as migrateDurableStreams,Ge as migrateGlobalShapeSnapshot,We as migrateIdempotency,It as migrateReactorState,tr as migrateScheduleOutbox,pr as migrateSearchState,Tr as migrateShapePokeCursor,se as minCdcReplayableSeq,le as minCdcSeq,Rr as minShapePokeCursor,ui as nextPromotionState,p as normalizeCountArgument,U as normalizeIdStructurally,Ja as normalizeOrderKeys,Po as normalizeSourceDocument,Oo as normalizeSourceValue,Za as nullsFirstOf,$a as nullsOrderSuffix,Ba as operatorFields,ao as param,ir as parkScheduleOutbox,t as parseExportShardArgs,i as parseImportShardArgs,Ua as patchDependsOnRow,g as planAggregateLookup,ra as pointInBoundingBox,sr as probeScheduleOutbox,os as projectColumns,wo as pullExternalSourceIncrementalTick,qo as pullExternalSourceTick,jr as qualifiedJsonPath,Jr as qualifiedJsonPathSql,il as quoteIdentifier,ut as rankKeyFromDoc,ft as rankPivotConditionSql,Et as rankTableName,At as reactiveCacheKey,bt as reactorNeedsRun,T as readAggregateValue,Ee as readArchivedCdcChanges,F as readAuditLog,Ka as readBookmark,Oa as readCapturedMail,he as readCdcArchivedThrough,ne as readCdcChangeKeys,de as readCdcChanges,ce as readCdcCursor,me as readCdcEpoch,ge as readClientWatermark,Pe as readCommitSeq,Hi as readDeployInfo,lr as readDueScheduleOutbox,No as readExternalSourceBaseline,we as readGlobalShapeSnapshot,Xe as readIdempotent,Pr as readMigrationStatus,Ga as readPatchField,lt as readQueueMessageById,nt as readQueueMessages,Lt as readReactorState,Ui as readSchemaHistory,Gi as readSchemaVersion,Sr as readSearchBackfillState,Ar as readShapePokeCursor,uo as readStreamChunks,fo as readStreamRun,xa as readTablePage,Fa as recordCapturedMail,Fs as recordChangedKeys,Ta as recordFanoutPass,Ra as recordGlobalPollPass,dt as recordQueueMessages,nr as recordScheduleOutbox,wi as recordSchemaVersion,Aa as recordShapeProbePass,ni as relationHooks,fi as relayCountFor,to as renderSql,Pi as reprojectableFields,rl as reprojectionMigrationId,Oi as reprojectionTables,wa as resolvePatch,ht as resolveRankPartition,$e as resolveRankSeekTuple,ri as resolveRelationPredicates,di as resolveWith,Zr as rowToDocument,Or as runDataMigration,Ur as runDrizzle,ko as runExternalSourceTick,hs as runReadonlySql,ci as runRowValidators,ll as runShardMigrations,ps as runSocketPool,Gr as runSql,Ks as runTriggers,Xs as selectExpiredIds,s as selectExportTables,_ as selectIndexForAggregate,I as selectIndexForCount,b as selectIndexForGroupBy,Ca as selectMatchingIds,Ir as selectShapeMembers,br as selectShapeRows,vi as serializeSqlValue,js as serverInList,Ei as shapeRoutingKey,ls as siblingSecretOf,ns as signSiblingBody,et as softDeleteScope,xt as sortColumnName,io as sqliteInList,dl as stableStringify,cl as stableWireKey,G as stripReservedPatchFields,ds as stubByName,bs as subscriptionFrames,Ls as subscriptionListDeltas,ga as summarizeFanoutTopics,_a as summarizeSubscriptions,$r as tableColumns,kr as tableFromDepKey,S as throwingScheduler,rt as tiebreakDirectionFor,pe as trimCdcChanges,He as trimIdempotent,dr as trimScheduleOutbox,Eo as trimStreamRuns,eo as tryRowToDocument,Ds as trySendFrame,so as unionAll,ot as uniqueIndexFields,l as validateImportRow,cs as verifySiblingBody,wt as whereFilter,qt as whereOfFilter,xe as writeCdcArchivedThrough,qe as writeGlobalShapeSnapshot,Ve as writeIdempotent,Dt as writeReactorState,ur as writeSearchBackfillState,Cr as writeShapePokeCursor,gr as writeShapePokeCursors,Ms as writeTouchesMemo};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as S}from"@lunora/errors";import{decodeWire as x}from"@lunora/wire";import{sql as j}from"drizzle-orm";import{isInternalTableName as M}from"./isInternalTableName-BoljO2tP.mjs";import{n as A,o as U}from"./do-sql-DqU-17Fs.mjs";import{quoteIdentifier as u}from"./quoteIdentifier-CObIFRhb.mjs";import{renderSql as q,sqliteInList as B}from"./WORKERD_SQLITE_LIMITS-BdNnnMj0.mjs";import{serializeSqlValue as k}from"./serializeSqlValue-DeoBMpZ2.mjs";import{decodeBigintSqlKey as Q}from"./BIGINT_KEY_DIGITS-DE6yshOt.mjs";const Te="__lunora_admin__:",Ae="__lunora_relation__:",Ie="__lunora_flags__:",Re={applyCdc:"__lunora_admin__:applyCdc",aiAvailable:"__lunora_admin__:aiAvailable",aiChartConfig:"__lunora_admin__:aiChartConfig",aiGenerateSql:"__lunora_admin__:aiGenerateSql",aiTableFilter:"__lunora_admin__:aiTableFilter",assignIssue:"__lunora_admin__:assignIssue",backfillSearch:"__lunora_admin__:backfillSearch",backfillVectors:"__lunora_admin__:backfillVectors",backRelationCounts:"__lunora_admin__:backRelationCounts",cdcSync:"__lunora_admin__:cdcSync",clearCapturedMail:"__lunora_admin__:clearCapturedMail",clearQueueMessages:"__lunora_admin__:clearQueueMessages",clearTable:"__lunora_admin__:clearTable",createWorkflowInstance:"__lunora_admin__:createWorkflowInstance",deleteRows:"__lunora_admin__:deleteRows",describeTable:"__lunora_admin__:describeTable",describeTables:"__lunora_admin__:describeTables",explainIssue:"__lunora_admin__:explainIssue",exportShard:"__lunora_admin__:exportShard",facetColumn:"__lunora_admin__:facetColumn",findRelated:"__lunora_admin__:findRelated",getAdvisories:"__lunora_admin__:getAdvisories",getAdvisorProcedures:"__lunora_admin__:getAdvisorProcedures",getAuditLog:"__lunora_admin__:getAuditLog",getAuthMetrics:"__lunora_admin__:getAuthMetrics",getCapturedMail:"__lunora_admin__:getCapturedMail",getFanoutMetrics:"__lunora_admin__:getFanoutMetrics",getFunctionStats:"__lunora_admin__:getFunctionStats",getIssues:"__lunora_admin__:getIssues",getMetricHistory:"__lunora_admin__:getMetricHistory",getMetricSeries:"__lunora_admin__:getMetricSeries",listSubscriptions:"__lunora_admin__:listSubscriptions",listTableIndexes:"__lunora_admin__:listTableIndexes",listTablesIndexes:"__lunora_admin__:listTablesIndexes",getLogs:"__lunora_admin__:getLogs",getMetrics:"__lunora_admin__:getMetrics",getPitrBookmark:"__lunora_admin__:getPitrBookmark",getQueryInsights:"__lunora_admin__:getQueryInsights",getQueueMessages:"__lunora_admin__:getQueueMessages",getRequestLog:"__lunora_admin__:getRequestLog",getSecurityAudit:"__lunora_admin__:getSecurityAudit",getSettings:"__lunora_admin__:getSettings",getTraces:"__lunora_admin__:getTraces",getWorkflowInstanceStatus:"__lunora_admin__:getWorkflowInstanceStatus",ignoreIssue:"__lunora_admin__:ignoreIssue",importShard:"__lunora_admin__:importShard",listFlags:"__lunora_admin__:listFlags",listReactors:"__lunora_admin__:listReactors",listQueues:"__lunora_admin__:listQueues",lintSql:"__lunora_admin__:lintSql",listTables:"__lunora_admin__:listTables",listWorkflows:"__lunora_admin__:listWorkflows",maskPolicies:"__lunora_admin__:maskPolicies",migrationStatus:"__lunora_admin__:migrationStatus",patchRows:"__lunora_admin__:patchRows",pitrRestore:"__lunora_admin__:pitrRestore",rankBefore:"__lunora_admin__:rankBefore",rankPage:"__lunora_admin__:rankPage",readTablePage:"__lunora_admin__:readTablePage",rebuildCompanions:"__lunora_admin__:rebuildCompanions",recordAuthEvent:"__lunora_admin__:recordAuthEvent",recordContainerEvent:"__lunora_admin__:recordContainerEvent",recordMail:"__lunora_admin__:recordMail",recordQueueMessage:"__lunora_admin__:recordQueueMessage",releaseShardRegistration:"__lunora_admin__:releaseShardRegistration",replayQueueMessage:"__lunora_admin__:replayQueueMessage",resolveIssue:"__lunora_admin__:resolveIssue",rlsPolicies:"__lunora_admin__:rlsPolicies",schemaHistory:"__lunora_admin__:schemaHistory",schemaVersion:"__lunora_admin__:schemaVersion",runAs:"__lunora_admin__:runAs",runMigration:"__lunora_admin__:runMigration",runSql:"__lunora_admin__:runSql",sendQueueMessage:"__lunora_admin__:sendQueueMessage",sendTestMail:"__lunora_admin__:sendTestMail",setIssueSeverity:"__lunora_admin__:setIssueSeverity",storageOrphans:"__lunora_admin__:storageOrphans",storageReferences:"__lunora_admin__:storageReferences",storageRules:"__lunora_admin__:storageRules",studioFeatures:"__lunora_admin__:studioFeatures",writeRow:"__lunora_admin__:writeRow"},W=50,b=500,H=30,G=200,d="__doc__",$=e=>{try{const t=JSON.parse(e);return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:void 0}catch{return}},K=e=>{const{[A]:t,...n}=e;return t===void 0?n:t===null||typeof t!="object"||Array.isArray(t)?{[A]:t,...n}:{...n,...x(t)}},X=(e,t)=>{if(!e.includes(d))return{columns:e,rows:t};const n=[];for(const o of t){const a=o[d],_=typeof a=="string"?$(a):void 0;if(_===void 0)return{columns:e,rows:t};const c=Object.fromEntries(Object.entries(o).filter(([l])=>l!==d));n.push({...c,...K(_)})}const r=e.filter(o=>o!==d),s=[],i=new Set(r);for(const o of n)for(const a of Object.keys(o))i.has(a)||(i.add(a),s.push(a));return{columns:[...r,...s],rows:n}},I=e=>`instr(lower(CAST(${e} AS TEXT)), lower(?)) > 0`,C=(e,t,n)=>Math.min(Math.max(e,t),n),D=(e,t)=>{const n=e.exec(`SELECT COUNT(*) AS c FROM ${t}`).one();return Number(n.c)},ve=e=>{const t=e.exec("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name").toArray(),n=[];for(const{name:r}of t)M(r)||n.push({name:r,rowCount:D(e,u(r))});return n},F=(e,t)=>e.exec("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ? LIMIT 1",t).toArray().length>0,w=(e,t)=>{if(M(t)||!F(e,t))throw new S("UNKNOWN_TABLE",`unknown table: ${t}`,{status:404})},R=(e,t)=>e.exec(`PRAGMA table_info(${t})`).toArray().map(n=>n.name),V={eq:"=",gt:">",gte:">=",lt:"<",lte:"<=",ne:"<>"},L=e=>typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):"",Y=new Set(["gt","gte","lt","lte"]),J=e=>e.operator==="contains"?L(e.value)==="":Y.has(e.operator)&&e.value==="",E=(e,t)=>{const n=t.includes(e),r=t.includes(d);if(!(!n&&!r))return n?{expression:u(e),params:[]}:{expression:`json_extract(${u(d)}, ?)`,params:[`$.${U(e)}`]}},z=/^-?\d+$/u,Z=(e,t)=>{const{value:n}=e;if(t==="bigint"&&(typeof n=="number"||typeof n=="string")){const r=typeof n=="number"&&Number.isInteger(n)?BigInt(n).toString():String(n).trim();if(!z.test(r))throw new S("BAD_REQUEST",`bigint column ${e.column} can only be filtered by an integer, got ${JSON.stringify(n)}`);return k(BigInt(r))}if(t==="bigint"&&typeof n!="bigint")throw new S("BAD_REQUEST",`bigint column ${e.column} can only be filtered by an integer, got ${JSON.stringify(n)}`);return k(n)},ee=(e,t)=>t==="bigint"&&typeof e=="string"?Q(e)??e:e,te=(e,t,n)=>{const r=E(e.column,t);if(r===void 0||J(e))return;const{expression:s,params:i}=r,o=t.includes(e.column)?void 0:n?.[e.column];if(e.operator==="contains"){if(o==="bigint")throw new S("BAD_REQUEST",`"contains" is not supported on bigint column ${e.column} — use =, <, > instead`);return{params:[...i,L(e.value)],sql:I(s)}}return e.value===null&&(e.operator==="eq"||e.operator==="ne")?{params:i,sql:`${s} IS ${e.operator==="ne"?"NOT ":""}NULL`}:{params:[...i,Z(e,o)],sql:`${s} ${V[e.operator]} ?`}},ne=new Set(["date","timestamp"]),re=[`$.${A}`,`$."${A}"`].map(e=>`substr(j.fullkey, 1, ${String(e.length+1)}) NOT IN ('${e}.', '${e}[')`).join(" AND "),oe=e=>`(${I(e)} AND EXISTS (SELECT 1 FROM json_tree(${e}) AS j WHERE j.type IN ('text', 'integer', 'real', 'true', 'false') AND ${I("CASE WHEN j.type IN ('true', 'false') THEN j.type ELSE j.value END")} AND ${re}))`,se=/["\\\u0000-\u001F]/u,ae=e=>se.test(e)?"":e,ie=/^(\d{4})(?:-(\d{2}))?(?:-(\d{2}))?$/u,_e=e=>{const t=ie.exec(e.trim());if(t===null)return;const n=Number(t[1]),r=t[2]===void 0?void 0:Number(t[2]),s=t[3]===void 0?void 0:Number(t[3]);if(r!==void 0&&(r<1||r>12)||s!==void 0&&(s<1||s>31)||n<100)return;const i=Date.UTC(n,(r??1)-1,s??1);if(s!==void 0&&new Date(i).getUTCDate()!==s)return;let o;return s!==void 0?o=Date.UTC(n,(r??1)-1,s+1):r===void 0?o=Date.UTC(n+1,0,1):o=Date.UTC(n,r,1),{from:i,to:o}},y=(e,t,n,r)=>{const s=[],i=[];if(t!==""&&e.length>0){const o=e.map(_=>_===d?oe(u(_)):I(u(_)));i.push(...e.flatMap(_=>_===d?[ae(t),t]:[t]));const a=_e(t);if(a!==void 0){for(const c of e)o.push(`(${u(c)} >= ? AND ${u(c)} < ?)`),i.push(a.from,a.to);const _=Object.keys(r??{}).filter(c=>!e.includes(c)&&ne.has(r?.[c]??""));_.length>0&&e.includes(d)&&(o.push(`EXISTS (SELECT 1 FROM json_each(${u(d)}) AS j WHERE j.key IN (SELECT value FROM json_each(?)) AND j.type IN ('integer', 'real') AND j.value >= ? AND j.value < ?)`),i.push(JSON.stringify(_),a.from,a.to))}s.push(`(${o.join(" OR ")})`)}for(const o of n??[]){const a=te(o,e,r);a!==void 0&&(s.push(`(${a.sql})`),i.push(...a.params))}return s.length===0?void 0:{parameters:i,where:s.join(" AND ")}},ce=(e,t)=>{if(e===void 0)return;const n=E(e.column,t);if(n===void 0)return;const r=e.direction==="desc"?"DESC":"ASC";return{params:n.params,sql:`${n.expression} ${r}`}},Me=(e,t)=>{const{table:n}=t;w(e,n);const r=C(Math.trunc(t.limit??W),1,b),s=Math.max(0,Math.trunc(t.offset??0)),i=u(n),o=R(e,i),a=t.search?.trim()??"",_=T=>{if(t.refs===void 0)return T;const v={};for(const N of T.columns){const O=t.refs[N];O!==void 0&&(v[N]=O)}return Object.keys(v).length>0?{...T,refs:v}:T},c=y(o,a,t.filters,t.columnKinds),l=ce(t.orderBy,o),f=c===void 0?"":` WHERE ${c.where}`,g=l===void 0?"":` ORDER BY ${l.sql}`,p=c?.parameters??[],h=l?.params??[];let m;t.skipCount||(m=c===void 0?D(e,i):Number(e.exec(`SELECT COUNT(*) AS c FROM ${i}${f}`,...p).one().c));const P=e.exec(`SELECT * FROM ${i}${f}${g} LIMIT ? OFFSET ?`,...p,...h,r,s).toArray();return _({...X(o,P),sqlColumns:o,total:m})},Ce=(e,t)=>{const{table:n}=t;w(e,n);const r=C(Math.trunc(t.limit??b),1,b),s=u(n),i=R(e,s),o=t.search?.trim()??"";for(const m of t.filters??[])if(E(m.column,i)===void 0)throw new S("BAD_REQUEST",`unknown column: ${m.column}`);const a=y(i,o,t.filters,t.columnKinds);if(a===void 0&&(t.filters?.length??0)>0)throw new S("BAD_REQUEST",`the filters on ${n} are all empty, so the predicate constrains no rows — refusing to select the whole table`);const _=[],c=[];a!==void 0&&(_.push(a.where),c.push(...a.parameters)),t.after!==void 0&&(_.push("id > ?"),c.push(t.after));const l=_.length===0?"":` WHERE ${_.join(" AND ")}`,f=t.after===void 0?"":" ORDER BY id",g=e.exec(`SELECT id FROM ${s}${l}${f} LIMIT ?`,...c,r+1).toArray(),p=g.length>r,h=g.slice(0,r).map(m=>m.id);return{hasMore:p,ids:h}},le=(e,t,n,r)=>{const s=new Set(n.filter(o=>o!==d));if(!n.includes(d))return s;for(const o of Object.keys(r??{}))s.add(o);const i=e.exec(`SELECT ${u(d)} AS doc FROM ${t} LIMIT ?`,b).toArray();for(const{doc:o}of i){const a=typeof o=="string"?$(o):void 0;if(a!==void 0)for(const _ of Object.keys(a))s.add(_)}return s},we=(e,t)=>{const{column:n,table:r}=t;w(e,r);const s=u(r),i=R(e,s);if(!le(e,s,i,t.columnKinds).has(n))throw new S("UNKNOWN_COLUMN",`unknown column: ${n}`,{status:404});const o=E(n,i);if(o===void 0)throw new S("UNKNOWN_COLUMN",`unknown column: ${n}`,{status:404});const a=C(Math.trunc(t.limit??H),1,G),_=t.search?.trim()??"",c=y(i,_,t.filters,t.columnKinds),l=c===void 0?"":` WHERE ${c.where}`,f=c?.parameters??[],g=e.exec(`SELECT ${o.expression} AS value, COUNT(*) AS count FROM ${s}${l} GROUP BY ${o.expression} ORDER BY count DESC LIMIT ?`,...o.params,...f,...o.params,a+1).toArray(),p=g.length>a,h=i.includes(n)?void 0:t.columnKinds?.[n];return{truncated:p,values:g.slice(0,a).map(m=>({count:Number(m.count),value:ee(m.value,h)}))}},ye=(e,t,n)=>{const r={},s=n.slice(0,b);for(const i of s)r[i]=[];if(s.length===0)return{references:r,storageColumns:t};for(const[i,o]of Object.entries(t)){if(M(i)||!F(e,i))continue;const a=u(i),_=R(e,a);for(const c of o){const l=E(c,_);if(l===void 0)continue;const f=q("sqlite",B(j.raw(l.expression),s,!1)),g=e.exec(`SELECT id, ${l.expression} AS ref FROM ${a} WHERE ${f.sql}`,...l.params,...l.params,...f.params).toArray();for(const p of g)r[p.ref]?.push({column:c,id:p.id,table:i})}}return{references:r,storageColumns:t}},Ne=e=>{const t=e.map((r,s)=>{const i=Object.values(r.subs??{}).map(o=>({args:o.args,functionPath:o.functionPath,table:o.table}));return{admin:r.admin===!0,id:s,subscriptions:i}}),n=t.reduce((r,s)=>r+s.subscriptions.length,0);return{connections:t,totalConnections:t.length,totalSubscriptions:n}},ue=20,Oe=()=>({maxMs:0,passes:0,peakSocketsIterated:0,socketsDelivered:0,socketsIterated:0,totalMs:0}),ke=()=>({run:0,served:0}),$e=()=>({drains:0,pairsSkipped:0}),De=(e,t,n)=>({drains:e.drains+t,pairsSkipped:e.pairsSkipped+n}),Fe=(e,t,n)=>({run:e.run+t,served:e.served+n}),Le=(e,t,n,r)=>({maxMs:Math.max(e.maxMs,r),passes:e.passes+1,peakSocketsIterated:Math.max(e.peakSocketsIterated,t),socketsDelivered:e.socketsDelivered+n,socketsIterated:e.socketsIterated+t,totalMs:e.totalMs+r}),Pe=(e,t=ue)=>{const n=new Map,r=new Map;for(const o of e){for(const a of Object.values(o.shapes??{})){const _=a.name??"(unknown shape)";n.set(_,(n.get(_)??0)+1)}for(const a of o.whispers??[])r.set(a,(r.get(a)??0)+1)}const s=[...[...n].map(([o,a])=>({kind:"shape",subscribers:a,topic:o})),...[...r].map(([o,a])=>({kind:"whisper",subscribers:a,topic:o}))];return s.sort((o,a)=>a.subscribers-o.subscribers||o.topic.localeCompare(a.topic)),{peakSubscribers:s[0]?.subscribers??0,topics:s.slice(0,t),totalConnections:e.length}};export{Re as ADMIN_FUNCTIONS,Te as ADMIN_FUNCTION_PREFIX,ue as DEFAULT_FANOUT_TOPIC_LIMIT,Ie as FLAGS_FUNCTION_PREFIX,b as MAX_PAGE_SIZE,Ae as RELATION_FUNCTION_PREFIX,Oe as createFanoutCounters,$e as createGlobalPollCounters,ke as createShapeProbeCounters,_e as datePrefixRange,we as facetColumn,ye as findStorageReferences,M as isInternalTableName,J as isVacuousFilterClause,ve as listTables,Me as readTablePage,Le as recordFanoutPass,De as recordGlobalPollPass,Fe as recordShapeProbePass,Ce as selectMatchingIds,Pe as summarizeFanoutTopics,Ne as summarizeSubscriptions};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as u}from"@lunora/errors";import{r as f}from"./json-field-path-DeJW4U9z.mjs";const a=new Set(["baseWhere","relationBaseWhere","restrictsCounts","where"]),c=()=>{throw new u("INTERNAL","ctx.scheduler: no scheduler configured for triggers. Pass `scheduler` to the ctx-db factory.")},d=(e,r)=>{for(const[n,t]of Object.entries(r)){const o=f(e,n)??null;if(t!==null&&typeof t=="object"&&!Array.isArray(t)){const s=Object.keys(t);if(s.length===1&&s[0]==="eq"){if(o!==(t.eq??null))return!1;continue}return!1}if(o!==t)return!1}return!0},y=e=>{if(e===void 0)return{};if(typeof e!="object"||Array.isArray(e))return{where:e};const r=Object.keys(e);return r.length===0?{}:r.every(n=>a.has(n))?e:{where:e}},i={avg:"AVG",count:"COUNT",max:"MAX",min:"MIN",sum:"SUM"},A=e=>{const r=i[e];if(r===void 0)throw new u("INTERNAL",`unknown aggregate op "${e}": expected one of ${Object.keys(i).join(", ")}`);return r},w={runAfter:c,runAt:c};export{i as AGGREGATE_SQL_FUNCTION,A as aggregateSqlFunction,d as matchesStaticWhere,y as normalizeCountArgument,w as throwingScheduler};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"./effective-kind-BmG_zCAy.mjs";import"./json-field-path-DeJW4U9z.mjs";import{A as l,a as i,b as n,D as d,n as m,c as p,d as u,l as q,s as G,m as c,k as S,g as f,i as A,j as D,e as h,p as T,u as _,q as g,f as j,r as y,t as C,h as O}from"./do-sql-DqU-17Fs.mjs";import{quoteIdentifier as x}from"./quoteIdentifier-CObIFRhb.mjs";import"./runDrizzle-B2GG3IJa.mjs";import{serializeSqlValue as J}from"./serializeSqlValue-DeoBMpZ2.mjs";import"./BIGINT_KEY_DIGITS-DE6yshOt.mjs";export{l as AGG_COUNT,i as AGG_KEY,n as AGG_VALUE,d as DOC_COLUMN,m as DOC_ORIGINALS_KEY,p as aggUpsertSql,u as createIndexSql,q as decodeDocJson,G as decodeGroupKeyValue,c as doWhereSqlStrategy,S as encodeDocJson,f as geoTableName,A as isFtsAvailable,D as jsonPath,h as jsonPathSql,T as jsonTypeGuard,_ as jsonTypeGuardSql,g as qualifiedJsonPath,j as qualifiedJsonPathSql,x as quoteIdentifier,y as rowToDocument,J as serializeSqlValue,C as tableColumns,O as tryRowToDocument};
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import{runSql as T}from"./runDrizzle-B2GG3IJa.mjs";const i="__lunora_audit__",a=1e3,s=E=>{T(E,`CREATE TABLE IF NOT EXISTS "${i}" (
|
|
2
|
+
seq INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
3
|
+
ts REAL NOT NULL,
|
|
4
|
+
op TEXT NOT NULL,
|
|
5
|
+
"table" TEXT,
|
|
6
|
+
id TEXT,
|
|
7
|
+
detail TEXT
|
|
8
|
+
)`)},R=(E,t)=>{s(E),T(E,`INSERT INTO "${i}" (ts, op, "table", id, detail) VALUES (?, ?, ?, ?, ?)`,t.ts,t.op,t.table??null,t.id??null,t.detail===void 0?null:JSON.stringify(t.detail)),T(E,`DELETE FROM "${i}" WHERE seq <= (SELECT MAX(seq) - ? FROM "${i}")`,a)},o=(E,t={})=>{s(E);const d=t.sinceSeq??0,n=Math.max(1,Math.min(t.limit??a,1e4));return T(E,`SELECT seq, ts, op, "table", id, detail FROM "${i}" WHERE seq > ? ORDER BY seq DESC LIMIT ?`,d,n).toArray().map(e=>{const l={op:e.op,seq:e.seq,ts:e.ts};return e.table!==null&&(l.table=e.table),e.id!==null&&(l.id=e.id),e.detail!==null&&(l.detail=JSON.parse(e.detail)),l})};export{i as AUDIT_LOG_TABLE,R as appendAuditEntry,s as ensureAuditTable,o as readAuditLog};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as g}from"@lunora/errors";import{e as s}from"./effective-kind-BmG_zCAy.mjs";const o=t=>{let n="";for(let r=0;r<t.length;r+=32768)n+=String.fromCharCode(...t.subarray(r,r+32768));return btoa(n)},i=39,f="0",c="1",a=t=>Array.from(t,n=>String(9-Number(n))).join(""),d=t=>{const n=t<0n,e=(n?-t:t).toString();if(e.length>i)throw new g("BAD_REQUEST",`bigint ${t.toString()} has ${String(e.length)} digits, over the ${String(i)}-digit limit for a queryable column`);const r=e.padStart(i,"0");return n?f+a(r):c+r},l=/^\d+$/u,h=t=>{if(t.length!==i+1)return;const n=t.slice(0,1),e=t.slice(1);if(l.test(e))return n===c?BigInt(e):n===f?-BigInt(a(e)):void 0},u=/^[\da-f]{16}$/u,b=t=>{const n=new DataView(new ArrayBuffer(8));n.setFloat64(0,t===0?0:t,!1);let e=n.getUint32(0,!1),r=n.getUint32(4,!1);return(e&2147483648)===0?e=(e^2147483648)>>>0:(e=~e>>>0,r=~r>>>0),e.toString(16).padStart(8,"0")+r.toString(16).padStart(8,"0")},I=t=>{if(!u.test(t))return;let n=Number.parseInt(t.slice(0,8),16),e=Number.parseInt(t.slice(8),16);(n&2147483648)===0?(n=~n>>>0,e=~e>>>0):n=(n^2147483648)>>>0;const r=new DataView(new ArrayBuffer(8));return r.setUint32(0,n,!1),r.setUint32(4,e,!1),r.getFloat64(0,!1)},p=t=>typeof t=="bigint"?d(t):t instanceof ArrayBuffer?o(new Uint8Array(t)):ArrayBuffer.isView(t)?o(new Uint8Array(t.buffer,t.byteOffset,t.byteLength)):void 0,y=t=>{const n=s(t);return n==="bigint"||n==="bytes"},E=t=>{const n=s(t);return y(t)||n==="any"||n==="union"||n==="from"};export{i as BIGINT_KEY_DIGITS,d as bigintSqlKey,h as decodeBigintSqlKey,I as decodeFloat64SqlKey,b as float64SqlKey,y as isProjectedKind,E as mayHoldProjectedValue,p as sqlComparableProjection};
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import{LunoraError as R}from"@lunora/errors";import{sql as t}from"drizzle-orm";import{quoteIdentifier as C}from"./quoteIdentifier-CObIFRhb.mjs";import{runSql as A,runDrizzle as n}from"./runDrizzle-B2GG3IJa.mjs";import{k as m,l as u}from"./do-sql-DqU-17Fs.mjs";import{ConflictError as I}from"./ConflictError-C8GtJmjS.mjs";const s="__cdc_log",p=`INSERT INTO ${C(s)} (ts, ${C("table")}, id, op, doc) VALUES (?, ?, ?, ?, ?)`,$="__cdc_log_table_seq",N="__cdc_log_table_id_seq",y=(e,o={})=>{n(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(s)} (
|
|
2
|
+
seq INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
3
|
+
ts REAL NOT NULL,
|
|
4
|
+
${t.identifier("table")} TEXT NOT NULL,
|
|
5
|
+
id TEXT NOT NULL,
|
|
6
|
+
op TEXT NOT NULL,
|
|
7
|
+
doc TEXT
|
|
8
|
+
)`);try{n(e,t`CREATE INDEX IF NOT EXISTS ${t.identifier($)} ON ${t.identifier(s)} (${t.identifier("table")}, seq)`)}catch{}if(o.rowHistoryIndex===!0)try{n(e,t`CREATE INDEX IF NOT EXISTS ${t.identifier(N)} ON ${t.identifier(s)} (${t.identifier("table")}, id, seq)`)}catch{}},F=(e,o,r,i,c,d)=>{const a=d===void 0?null:m(d);A(e,p,o,r,i,c,a)},f=90,q=e=>t` AND ${t.identifier("table")} IN (${t.join([...e].map(o=>t`${o}`),t`, `)})`,U=(e,o={})=>{const r=o.sinceSeq??0,i=Math.max(1,Math.min(o.limit??1e3,1e4)),d=n(e,t`SELECT seq, ts, ${t.identifier("table")}, id, op, doc FROM ${t.identifier(s)} WHERE seq > ${r} ORDER BY seq ASC LIMIT ${i}`).toArray().map(a=>{const T={id:a.id,op:a.op,seq:a.seq,table:a.table,ts:a.ts};return a.doc===null?T:{...T,doc:u(a.doc)}});return{changes:d,cursor:d.at(-1)?.seq??r}},X=(e,o,r)=>{if(r.size===0)return!1;const i=[...r];for(let c=0;c<i.length;c+=f){const d=new Set(i.slice(c,c+f));if(n(e,t`SELECT 1 AS hit FROM ${t.identifier(s)} WHERE seq > ${o}${q(d)} LIMIT 1`).toArray().length>0)return!0}return!1},l=new WeakMap,S=e=>new Set(n(e,t`SELECT name FROM sqlite_master WHERE type = 'table'`).toArray().map(o=>o.name)),v=(e,o)=>{if(o.size===0)return!1;let r=l.get(e),i=!1;r===void 0&&(r=S(e),i=!0,l.set(e,r));for(const c of o)if(!r.has(c)&&(i||(r=S(e),i=!0,l.set(e,r),!r.has(c))))return!1;return!0},B=(e,o,r,i)=>{const d=n(e,t`SELECT doc FROM ${t.identifier(s)}
|
|
9
|
+
WHERE ${t.identifier("table")} = ${o} AND id = ${r} AND seq <= ${i}
|
|
10
|
+
ORDER BY seq DESC
|
|
11
|
+
LIMIT 1`).toArray()[0]?.doc;return d==null?void 0:u(d)},H=(e,o,r,i)=>n(e,t`SELECT id, op, MAX(seq) AS maxSeq, COUNT(*) AS ops FROM ${t.identifier(s)}
|
|
12
|
+
WHERE ${t.identifier("table")} = ${o} AND seq > ${r} AND seq <= ${i}
|
|
13
|
+
GROUP BY id
|
|
14
|
+
ORDER BY maxSeq ASC`).toArray().map(d=>{const a=d.op;return{id:d.id,op:a==="insert"&&d.ops>1?"update":a,seq:d.maxSeq}}),x=(e,o,r)=>{n(e,t`DELETE FROM ${t.identifier(s)} WHERE seq IN (
|
|
15
|
+
SELECT seq FROM ${t.identifier(s)} WHERE seq <= ${o} ORDER BY seq ASC LIMIT ${r}
|
|
16
|
+
)`)},W=(e,o,r)=>{n(e,t`UPDATE ${t.identifier(s)} SET doc = NULL WHERE seq IN (
|
|
17
|
+
SELECT seq FROM ${t.identifier(s)} WHERE seq <= ${o} AND doc IS NOT NULL ORDER BY seq ASC LIMIT ${r}
|
|
18
|
+
)`)},Y=(e,o)=>{if(o<=0)return n(e,t`SELECT MAX(seq) AS seq FROM ${t.identifier(s)}`).toArray()[0]?.seq??void 0;const i=n(e,t`SELECT seq FROM ${t.identifier(s)} ORDER BY seq DESC LIMIT 1 OFFSET ${o-1}`).toArray()[0]?.seq;return i===void 0?void 0:i-1},G=e=>{const r=n(e,t`SELECT seq FROM sqlite_sequence WHERE name = ${s}`).toArray()[0]?.seq;return typeof r=="number"?r:n(e,t`SELECT MAX(seq) AS seq FROM ${t.identifier(s)}`).toArray()[0]?.seq??0},K=(e,o)=>e!==void 0&&e>o+1,P=(e,o,r)=>new R("CDC_LOG_TRIMMED",`${r==="global"?"global cdc":"cdc"} entries at or below seq ${String(e-1)} have been trimmed; resume from a snapshot (sinceSeq ${String(o)} is below the retained window)`,{status:409}),k=(e,o,r,i)=>new R("CDC_TIMELINE_FORKED",`${r==="global"?"global cdc":"cdc"} cursor ${String(o)} is above ${r==="global"?"the changelog's":"this shard's"} high-watermark ${String(e)}; the changelog rolled back (a point-in-time restore) and the changes you hold are on a timeline that no longer exists — resume from a snapshot${i===void 0?"":` at epoch ${i}`}`,{data:{cursor:e,...i===void 0?{}:{epoch:i}},status:409}),O=e=>n(e,t`SELECT MIN(seq) AS seq FROM ${t.identifier(s)}`).toArray()[0]?.seq??void 0,V=e=>{const r=n(e,t`SELECT MAX(seq) AS seq FROM ${t.identifier(s)} WHERE op <> 'delete' AND doc IS NULL`).toArray()[0]?.seq??void 0,i=O(e);return r===void 0?i:Math.max(r+1,i??0)},E="__cdc_meta",L=e=>{n(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(E)} (id INTEGER PRIMARY KEY CHECK (id = 1), epoch TEXT NOT NULL)`)},z=e=>{L(e);const r=n(e,t`SELECT epoch FROM ${t.identifier(E)} WHERE id = 1`).toArray()[0]?.epoch;if(typeof r=="string"&&r.length>0)return r;const i=crypto.randomUUID();return n(e,t`INSERT INTO ${t.identifier(E)} (id, epoch) VALUES (1, ${i})`),i},Q=e=>{L(e);const o=crypto.randomUUID();return n(e,t`INSERT INTO ${t.identifier(E)} (id, epoch) VALUES (1, ${o}) ON CONFLICT(id) DO UPDATE SET epoch = excluded.epoch`),o},h=async(e,o)=>{if(o.op==="delete"){await e.delete(o.id,o.table);return}const r=o.doc??{};try{await e.insert(o.table,r,{allowExplicitId:!0})}catch(i){if(!(i instanceof I))throw i;const c={...r};delete c._id,await e.replace(o.id,c,o.table,{allowExplicitId:!0})}},J=async(e,o)=>{for(const r of o)await h(e,r)};export{p as CDC_APPEND_SQL,s as CDC_LOG_TABLE,$ as CDC_LOG_TABLE_SEQ_INDEX,E as CDC_META_TABLE,F as appendCdcChange,J as applyCdcChanges,Q as bumpCdcEpoch,v as cdcCanVouchFor,k as cdcForkedError,Y as cdcSeqLeavingRows,X as cdcTouchesTables,P as cdcTrimmedError,W as compactCdcDocs,K as cursorBelowRetainedFloor,y as migrateCdcLog,L as migrateCdcMeta,V as minCdcReplayableSeq,O as minCdcSeq,H as readCdcChangeKeys,U as readCdcChanges,G as readCdcCursor,B as readCdcDocAtOrBefore,z as readCdcEpoch,x as trimCdcChanges};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import{sql as t}from"drizzle-orm";import{runDrizzle as a}from"./runDrizzle-B2GG3IJa.mjs";const r="__client_watermark",o=i=>{a(i,t`CREATE TABLE IF NOT EXISTS ${t.identifier(r)} (
|
|
2
|
+
identity TEXT NOT NULL,
|
|
3
|
+
client_id TEXT NOT NULL,
|
|
4
|
+
last_mutation_id INTEGER NOT NULL,
|
|
5
|
+
PRIMARY KEY (identity, client_id)
|
|
6
|
+
)`)},E=(i,e,n)=>a(i,t`SELECT last_mutation_id FROM ${t.identifier(r)} WHERE identity = ${e} AND client_id = ${n} LIMIT 1`).toArray()[0]?.last_mutation_id??0,l=(i,e,n,d)=>{a(i,t`INSERT INTO ${t.identifier(r)} (identity, client_id, last_mutation_id) VALUES (${e}, ${n}, ${d})
|
|
7
|
+
ON CONFLICT(identity, client_id) DO UPDATE SET last_mutation_id = MAX(last_mutation_id, excluded.last_mutation_id)`)};export{r as CLIENT_WATERMARK_TABLE,l as advanceClientWatermark,o as migrateClientWatermark,E as readClientWatermark};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import{sql as e}from"drizzle-orm";import{runDrizzle as E}from"./runDrizzle-B2GG3IJa.mjs";const t="__commit_seq",n="_commitSeq",S=i=>{E(i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(t)} (
|
|
2
|
+
id INTEGER PRIMARY KEY CHECK (id = 0),
|
|
3
|
+
value INTEGER NOT NULL
|
|
4
|
+
)`),E(i,e`INSERT OR IGNORE INTO ${e.identifier(t)} (id, value) VALUES (0, 0)`)},r=i=>{const[o]=E(i,e`SELECT value FROM ${e.identifier(t)} WHERE id = 0`);return typeof o?.value=="number"?o.value:0},a=i=>(E(i,e`UPDATE ${e.identifier(t)} SET value = value + 1 WHERE id = 0`),r(i));export{n as COMMIT_SEQ_FIELD,t as COMMIT_SEQ_TABLE,a as allocateCommitSeq,S as migrateCommitSeq,r as readCommitSeq};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as S}from"@lunora/errors";import{decodeWire as p,encodeWire as O}from"@lunora/wire";import{v as _}from"./accepts-null-D1zmJbyR.mjs";import{r as E}from"./json-field-path-DeJW4U9z.mjs";import{SEEK_RANGE as A}from"./RELATION_EXISTS_KEY-wxgj6rSL.mjs";const R="id",h=e=>e.at(-1)?.direction==="desc"?"desc":"asc",b=new Set(["_id","id"]),F=new Set(["_creationTime","_id","id"]),g=(e,t)=>{if(F.has(e))return!1;const n=t?.[e];return n===void 0?!0:n.kind==="optional"||n._meta?.column?.notNull===!1||_(n)},T=new Set(["AND","NOT","OR"]),U=e=>{const t=new Set;if(typeof e!="object"||Array.isArray(e))return t;for(const[n,r]of Object.entries(e)){if(T.has(n))continue;if(r===null||typeof r!="object"||Array.isArray(r)){t.add(n);continue}const o=Object.keys(r);o.length===1&&o[0]==="eq"&&t.add(n)}return t},x=(e,t)=>{const n=[];for(const r of e??[])r.unique===!0&&n.push(r.fields);for(const[r,o]of Object.entries(t??{}))o._meta?.column?.unique===!0&&n.push([r]);return n},I=(e,t)=>(t??[]).some(n=>n.length>0&&n.every(r=>e.has(r))),y=e=>e.nulls===void 0?e.direction!=="desc":e.nulls==="first",K=e=>e?" NULLS FIRST":" NULLS LAST",D=e=>{if(typeof e!="object"||e===null)return!1;const{nulls:t,sort:n}=e;return(n==="asc"||n==="desc")&&(t==="first"||t==="last")},L=(e,t,n)=>{if(t!=="asc"&&t!=="desc"&&!D(t))throw new S("VALIDATION_ERROR",`orderBy "${e}": expected "asc", "desc" or { sort: "asc" | "desc", nulls: "first" | "last" }`);const r=typeof t=="string"?t:t.sort,o=g(e,n);return typeof t=="string"||!o||y({direction:r})===(t.nulls==="first")?{direction:r,field:e,nullable:o}:{direction:r,field:e,nullable:o,nulls:t.nulls}},J=(e,t,n)=>{const r=[],o=new Set(n?.pinned);let l="asc";for(const i of e??[])for(const[c,s]of Object.entries(i)){const u=L(c,s,t),{direction:f}=u;l=f,o.add(c),!n?.pinned?.has(c)&&r.push(u)}return r.length===0?[{direction:l,field:"_creationTime",nullable:!1}]:(r.some(i=>b.has(i.field)||i.field==="_creationTime")||I(o,n?.uniqueBy)||r.push({direction:h(r),field:"_creationTime",nullable:!1}),r)},w=/[\u0080-\u{10FFFF}]/u,v=e=>{if(!w.test(e))return btoa(e);const t=new TextEncoder().encode(e);let n="";for(const r of t)n+=String.fromCodePoint(r);return btoa(n)},C=e=>{const t=atob(e),n=Uint8Array.from(t,r=>r.codePointAt(0)??0);return new TextDecoder().decode(n)},a="~4",z=(e,t)=>{const n=t.map(r=>E(e,r.field)??null);return n.push(e._id),a+v(JSON.stringify(O(n)))},d=()=>new S("BAD_REQUEST","invalid cursor"),G=e=>{if(!e.startsWith(a))throw d();let t;try{t=p(JSON.parse(C(e.slice(a.length))))}catch{throw d()}if(!Array.isArray(t))throw d();return t.map(n=>n??null)},m=(e,t,n,r)=>{const{field:o}=e,l=e.direction!=="desc"===n,i=y(e)===n;if(t===null)return i?r?{OR:[{[o]:{isNull:!1}},{[o]:{isNull:!0}}]}:{[o]:{isNull:!1}}:r?{[o]:{isNull:!0}}:{OR:[]};let c=l?"gt":"lt";r&&(c=l?"gte":"lte");const s={[o]:{[c]:t,[A]:!0}};return i||!e.nullable?s:{OR:[s,{[o]:{isNull:!0}}]}},N=(e,t,n,r)=>{const o=e.some(s=>b.has(s.field))?e:[...e,{direction:h(e),field:R,nullable:!1}];if(t.length<o.length)throw d();const l=s=>{const u=o[s];if(u===void 0)throw d();const f=m(u,t[s],n,r&&s===o.length-1);return s===o.length-1?f:{OR:[f,{AND:[{[u.field]:{eq:t[s]}},l(s+1)]}]}},i=l(0),[c]=o;return o.length<2||c===void 0||c.nullable||t[0]===null?i:{AND:[m(c,t[0],n,!0),i]}},H=(e,t)=>N(e,t,!0,!1),M=(e,t)=>N(e,t,!1,!0),j=["_id","_creationTime"],Q=(e,t,n)=>{if(!t)return e;const r=new Set([...t,...j,...n?Object.keys(n):[]]);return e.map(o=>{const l={};for(const i of r)i in o&&(l[i]=o[i]);return l})},X=(e,t)=>e&&t!==!0?{[e.field]:{isNull:!0}}:void 0,Y=(e,t)=>t===void 0||e[t]===null||e[t]===void 0;export{a as CURSOR_PREFIX,Q as applySelect,M as buildSeekBeforeWhere,H as buildSeekWhere,G as decodeCursor,z as encodeCursor,U as equalityPinnedFields,C as fromBase64,Y as isLiveForCompanion,J as normalizeOrderKeys,y as nullsFirstOf,K as nullsOrderSuffix,X as softDeleteScope,h as tiebreakDirectionFor,v as toBase64,x as uniqueIndexFields};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as v}from"@lunora/errors";class g extends v{constructor(t){super("COUNT_RLS_UNSUPPORTED",t===void 0?"count() is not supported in an RLS-restricted context":`count() is not supported on table "${t}" inside an RLS-restricted context`)}}const q=(e,t)=>e?t?{AND:[e,t]}:e:t,O=new Set(["AND","NOT","OR"]),d=Symbol("not-eq"),f=e=>{if(e!==null&&typeof e=="object"&&!Array.isArray(e)){const t=Object.keys(e);return t.length===1&&t[0]==="eq"?e.eq:d}return e},l=(e,t)=>{const o={};for(const[r,s]of Object.entries(e)){if(O.has(r)||!t(r))return;const n=f(s);if(n===d)return;o[r]=n}return o},a=(e,t)=>{if(!e)return!0;for(const[o,r]of Object.entries(e)){if(!(o in t))return!1;const s=f(r);if((t[o]??null)!==(s??null))return!1}return!0},b=(e,t)=>{const o=e.by??[],r=e.where,n=l(t??{},i=>o.includes(i)||r!==void 0&&i in r);if(n!==void 0){for(const i of o)if(!(i in n))return;return a(r,n)?n:void 0}},x=(e,t,o)=>{const r=e.where,s=l(t??{},n=>o.has(n)||r!==void 0&&n in r);if(!(s===void 0||!a(r,s)))return Object.fromEntries(Object.entries(s).filter(([n])=>o.has(n)))},p=(e,t,o,r)=>{let s;for(const n of e){if(n.op!==t||t!=="count"&&n.field!==o)continue;const i=b(n,r);i&&(!s||(n.by?.length??0)>(s.index.by?.length??0))&&(s={index:n,key:i})}return s},R=(e,t)=>p(e,"count",void 0,t),A=(e,t,o,r)=>p(e,t,o,r),E=(e,t,o,r,s)=>{const n=new Set(r);for(const i of e){if(i.op!==t||t!=="count"&&i.field!==o)continue;const c=i.by??[];if(c.length!==n.size||!c.every(y=>n.has(y)))continue;const u=x(i,s,n);if(u!==void 0)return{index:i,partial:u}}};export{g as CountRlsUnsupportedError,q as mergeWhere,b as planAggregateLookup,A as selectIndexForAggregate,R as selectIndexForCount,E as selectIndexForGroupBy};
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import{LunoraError as D}from"@lunora/errors";import{stableWireKey as S}from"@lunora/wire";import{runSql as E}from"./runDrizzle-B2GG3IJa.mjs";import{encodeCursor as w,CURSOR_PREFIX as C}from"./CURSOR_PREFIX-6offuG6M.mjs";import{ConflictError as x}from"./ConflictError-C8GtJmjS.mjs";const i="__lunora_migrations",M=100,y=3e4,U=1e4,$=e=>{E(e,`CREATE TABLE IF NOT EXISTS "${i}" (
|
|
2
|
+
id TEXT PRIMARY KEY,
|
|
3
|
+
direction TEXT NOT NULL,
|
|
4
|
+
status TEXT NOT NULL,
|
|
5
|
+
cursor TEXT,
|
|
6
|
+
processed INTEGER NOT NULL DEFAULT 0,
|
|
7
|
+
changed INTEGER NOT NULL DEFAULT 0,
|
|
8
|
+
started_at REAL,
|
|
9
|
+
updated_at REAL,
|
|
10
|
+
error TEXT
|
|
11
|
+
)`)},b=e=>({changed:e.changed,cursor:typeof e.cursor=="string"?e.cursor:null,direction:e.direction==="down"?"down":"up",processed:e.processed,status:e.status==="completed"||e.status==="failed"?e.status:"in_progress"}),I=(e,t)=>{const r=E(e,`SELECT * FROM "${i}" WHERE id = ?`,t).toArray()[0];if(r)return{...b(r),startedAt:typeof r.started_at=="number"?r.started_at:void 0}},F=(e,t,a)=>{E(e,`DELETE FROM "${i}"
|
|
12
|
+
WHERE id = ? AND (status <> 'in_progress' OR updated_at IS NULL OR updated_at <= ?)`,t,a)},O=(e,t)=>{E(e,`INSERT INTO "${i}"
|
|
13
|
+
(id, direction, status, cursor, processed, changed, started_at, updated_at, error)
|
|
14
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
15
|
+
ON CONFLICT(id) DO UPDATE SET
|
|
16
|
+
direction = excluded.direction,
|
|
17
|
+
status = excluded.status,
|
|
18
|
+
cursor = excluded.cursor,
|
|
19
|
+
processed = excluded.processed,
|
|
20
|
+
changed = excluded.changed,
|
|
21
|
+
updated_at = excluded.updated_at,
|
|
22
|
+
error = excluded.error`,t.id,t.direction,t.status,t.cursor,t.processed,t.changed,t.startedAt,t.updatedAt,t.error)},v=(e,t,a,r)=>(E(e,`INSERT INTO "${i}"
|
|
23
|
+
(id, direction, status, cursor, processed, changed, started_at, updated_at, error)
|
|
24
|
+
VALUES (?, ?, 'in_progress', NULL, 0, 0, ?, ?, NULL)
|
|
25
|
+
ON CONFLICT(id) DO UPDATE SET
|
|
26
|
+
status = 'in_progress',
|
|
27
|
+
updated_at = excluded.updated_at
|
|
28
|
+
WHERE
|
|
29
|
+
"${i}".status <> 'in_progress'
|
|
30
|
+
OR "${i}".updated_at IS NULL
|
|
31
|
+
OR "${i}".updated_at <= excluded.updated_at - ${String(y)}`,t,a,r,r),E(e,"SELECT changes() AS changed").one().changed>0),H=(e,t,a)=>{E(e,`UPDATE "${i}" SET updated_at = ? WHERE id = ? AND status = 'in_progress'`,a,t)},P=(e,t)=>{E(e,`UPDATE "${i}" SET updated_at = 0 WHERE id = ? AND status = 'in_progress'`,t)},j=(e,t)=>{if(E(e,"SELECT name FROM sqlite_master WHERE type = 'table' AND name = ? LIMIT 1",i).toArray().length===0)return[];const r=t===void 0?" ORDER BY id":" WHERE id = ?",d=t===void 0?[]:[t];return E(e,`SELECT * FROM "${i}"${r}`,...d).toArray().map(n=>({...b(n),error:typeof n.error=="string"?n.error:null,id:n.id,startedAt:typeof n.started_at=="number"?n.started_at:null,updatedAt:typeof n.updated_at=="number"?n.updated_at:null}))},W=[{direction:"asc",field:"_creationTime",nullable:!1}],X=/^~[23]/u,B=e=>{if(typeof e!="string")return e;const t=X.exec(e);return t===null?e:C+e.slice(t[0].length)},Y=async e=>{const{document:t,id:a,onSettled:r,previous:d,table:o,writer:n}=e;try{await n.replace(a,t,void 0,{allowExplicitId:!0})}catch(f){const p=await n.get(a,o);throw p!==null&&S(p)!==S(d)&&r("changed"),f}r("changed")},G=3,V=async e=>{const{context:t,document:a,dryRun:r,onSettled:d,table:o,transform:n,writer:f}=e,p=String(a._id);let T=a;for(let h=0;h<G;h+=1){const c=await n(T,t);if(c===void 0){d("unchanged");return}if(r){d("changed");return}const u=await f.get(p,o);if(u===null){d("unchanged");return}if(S(u)===S(T)){await Y({document:{...c,_creationTime:T._creationTime,_id:T._id},id:p,onSettled:d,previous:u,table:o,writer:f});return}T=u}throw new x(`data migration could not rewrite row ${p}: it was modified by concurrent traffic on every attempt`,"occ")},J=async e=>{const{migration:t,sql:a,writer:r}=e,d=e.direction??"up",o=e.dryRun??!1,n=e.clock??(()=>Date.now()),f=e.maxBatches??Number.POSITIVE_INFINITY,p=e.batchSize??t.batchSize??M,T=d==="up"?t.up:t.down;if(!T)throw new D("INTERNAL",`data migration "${t.id}" has no \`${d}\` transform`);const h={db:{count:r.count.bind(r),findFirst:r.findFirst.bind(r),findMany:r.findMany.bind(r),get:r.get.bind(r)}};let c=null,u=0,g=0,A=n();if(!o){$(a);const s=I(a,t.id);if(s?.direction===d&&s.status==="completed")return{changed:s.changed,cursor:null,direction:d,dryRun:o,id:t.id,processed:s.processed,status:"completed"};if(s&&s.direction!==d&&F(a,t.id,n()-y),!v(a,t.id,d,n())){const R=I(a,t.id);return{changed:R?.changed??0,cursor:R?.cursor??c,direction:R?.direction??d,dryRun:o,id:t.id,processed:R?.processed??0,status:R?.status??"in_progress"}}const l=s?.direction===d?s:void 0;l&&(c=B(l.cursor),u=l.processed,g=l.changed,A=l.startedAt??A)}let _=!1,L=0,N=A;try{for(;!_&&L<f;){const s=await r.findMany(t.table,{cursor:c,includeDeleted:!0,limit:p});for(const m of s.page)if(await V({context:h,document:m,dryRun:o,onSettled:l=>{l==="changed"&&(g+=1),u+=1,c=w(m,W)},table:t.table,transform:T,writer:r}),!o){const l=n();l-N>=U&&(H(a,t.id,l),N=l)}if(c=s.continueCursor,_=s.isDone,L+=1,!o){const m=n();O(a,{changed:g,cursor:_?null:c,direction:d,error:null,id:t.id,processed:u,startedAt:A,status:_?"completed":"in_progress",updatedAt:m}),N=m;try{await e.onBatch?.({batches:L,changed:g,processed:u})}catch{}}}}catch(s){throw o||O(a,{changed:g,cursor:c,direction:d,error:s instanceof Error?s.message:String(s),id:t.id,processed:u,startedAt:A,status:"failed",updatedAt:n()}),s}if(!o&&!_)try{P(a,t.id)}catch(s){console.warn(`data migration "${t.id}": releaseClaim failed`,s)}return{changed:g,cursor:_?null:c,direction:d,dryRun:o,id:t.id,processed:u,status:_?"completed":"in_progress"}};export{i as DATA_MIGRATION_STATE_TABLE,j as readMigrationStatus,J as runDataMigration};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as h}from"@lunora/errors";import{i as S,R as L}from"./relation-operators-BEg-CvCH.mjs";import{mergeWhere as w}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{isMemoryTable as R}from"./clearMemoryTables-Lu0S2GOb.mjs";import{normalizeOrderKeys as j,uniqueIndexFields as M,equalityPinnedFields as P,buildSeekWhere as k,decodeCursor as I,softDeleteScope as K}from"./CURSOR_PREFIX-6offuG6M.mjs";import{distinctValues as O}from"./applyOnDelete-BwxDC4lU.mjs";import{RELATION_EXISTS_KEY as _}from"./RELATION_EXISTS_KEY-wxgj6rSL.mjs";const v={every:{kind:"many",negateChild:!0,negated:!0},is:{kind:"one",negated:!1},isNot:{kind:"one",negated:!0,nullDisjunct:!0},none:{kind:"many",negated:!0},some:{kind:"many",negated:!1}},A=e=>L.has(e)?e:void 0,g=e=>{const t=A(e),r=t===void 0?void 0:v[t];if(!r)throw new h("INTERNAL",`unknown relation operator "${e}"`);return r},C=e=>e.kind==="one"?{clause:e.field,project:e.references}:{clause:e.references,project:e.field},D=5e3,f=Symbol("relation-key-overflow"),p=e=>Array.isArray(e)?e.map(t=>t??{}):[],N=e=>{if(e.length===1){const[t]=e;return t??{}}return e.length===0?{}:{AND:e}},y=e=>S(e),u=(e,t,r)=>{const n=t.tables[r]?.relationMap??{};return Object.keys(e).some(o=>{const a=e[o];return o==="AND"||o==="OR"?p(a).some(s=>u(s,t,r)):o==="NOT"?u(a??{},t,r):!!n[o]&&y(a)})},oe=(e,t,r,n)=>{if(e&&u(e,t,r))throw new h("INTERNAL",`relation-crossing predicates are not supported in ${n}() — use them in findMany/findFirst or an RLS read policy`)},B=async(e,t,r,n)=>{const o=await l(t,e.table,n),{page:a}=await n.fetcher(e.table,{baseWhere:n.relationBaseWhere?.(e.table),relationBaseWhere:n.relationBaseWhere,where:o});return O(a,r)},W=(e,t,r)=>{throw new h("INTERNAL",`relation predicate on "${e.table}" matched ${String(t)} rows, exceeding the ${String(r.maxRelationKeys)}-key limit; narrow the predicate (a same-shard EXISTS push-down lifts this cap)`)},F=(e,t,r)=>{throw new h("INTERNAL",`relation predicate on "${e.table}" matched at least ${String(t)} distinct keys, exceeding the ${String(r.maxRelationKeys)}-key limit; narrow the predicate`)},q=async(e,t,r,n,o)=>{const a=await B(e,t,r,n);return a.length<=n.maxRelationKeys?a:o?f:W(e,a.length,n)},b=async(e,t,r,n)=>{const o=await l(t,e.table,n),a=n.maxRelationKeys+1,s=new Set;let d;for(;;){const i=await n.fetcher(e.table,{baseWhere:n.relationBaseWhere?.(e.table),cursor:d,limit:a,relationBaseWhere:n.relationBaseWhere,where:o});if(i.page.length>a)throw new h("INTERNAL",`relation predicate on "${e.table}" read ${String(i.page.length)} rows for a page of at most ${String(a)}; the fetcher did not honour the page limit`);for(const c of O(i.page,r))s.add(c);if(s.size>n.maxRelationKeys&&F(e,s.size,n),i.isDone)return[...s];if(typeof i.continueCursor!="string")throw new h("INTERNAL",`relation predicate on "${e.table}" returned a page that is not final but has no cursor to continue from`);if(i.continueCursor===d)throw new h("INTERNAL",`relation predicate on "${e.table}" paged with a cursor that did not advance`);d=i.continueCursor}},H=async(e,t,r,n,o)=>{const a=g(e),{clause:s,project:d}=C(t),i=await q(t,a.negateChild?{NOT:r}:r,d,n,o);return i===f?f:a.negated?a.nullDisjunct?{OR:[{[s]:{notIn:i}},{[s]:{isNull:!0}}]}:{[s]:{notIn:i}}:{[s]:{in:i}}},z=async(e,t,r,n)=>{const o=g(e),{from:a,table:s,to:d}=t.through,i=await b(t,o.negateChild?{NOT:r}:r,"_id",n),c=i.length===0?[]:await b({table:s},{[d]:{in:i}},a,n);return{_id:o.negated?{notIn:c}:{in:c}}},E=async(e,t,r,n,o)=>{const a=g(e),s=o.relationBaseWhere?.(t.table),d=a.negateChild?{NOT:r}:r,$={childWhere:await l(s?{AND:[s,d]}:d,t.table,o),negated:a.negated,parentTable:n,relation:t};return{[_]:$}},Y=(e,t,r)=>{const n=A(e),o=n===void 0?void 0:v[n];if(o&&o.kind!==r.kind)throw new h("INTERNAL",`relation operator "${e}" requires a to-${o.kind} relation, but "${t}" is to-${r.kind}`)},x=async(e,t,r,n,o)=>{const a=[];for(const s of Object.keys(r)){Y(s,e,t);const d=r[s]??{};if(t.through!==void 0){a.push(await z(s,t,d,o));continue}const i=o.canPushExists?.(t)??!1;if(i&&o.existsPushMode==="always"){a.push(await E(s,t,d,n,o));continue}const c=await H(s,t,d,o,i);c===f?a.push(await E(s,t,d,n,o)):a.push(c)}return N(a)},Q=async(e,t,r,n)=>{if(e==="AND"||e==="OR"){const a=[];for(const s of p(t))a.push(await l(s,r,n));return{[e]:a}}if(e==="NOT")return{NOT:await l(t??{},r,n)};const o=n.schema.tables[r]?.relationMap?.[e];return o&&y(t)?x(e,o,t,r,n):{[e]:t}},l=async(e,t,r)=>{const n=[];for(const o of Object.keys(e))n.push(await Q(o,e[o],t,r));return N(n)},X=async(e,t)=>!e||!u(e,t.schema,t.tableName)?e:l(e,t.tableName,{canPushExists:t.canPushExists,existsPushMode:t.existsPushMode??"auto",fetcher:t.fetcher,maxRelationKeys:t.maxRelationKeys??D,relationBaseWhere:t.relationBaseWhere,schema:t.schema}),ae=async(e,t,r)=>{const n=j(t.orderBy,e.shape,{pinned:P(t.where),uniqueBy:M(e.indexes,e.shape)}),o=t.cursor?k(n,I(t.cursor)):void 0;let a=w(t.baseWhere,t.where);a=w(a,K(e.softDeleteMode,t.includeDeleted)),a=await X(a,{...r,relationBaseWhere:t.relationBaseWhere}),o&&(a=a?{AND:[a,o]}:o);const s=typeof t.limit=="number"?Math.max(0,Math.floor(t.limit)):void 0;return{fetchLimit:s===void 0?void 0:s+1,limit:s,orderKeys:n,predicate:a}},m=(e,t,r)=>{for(const n of e){const o=T(n,t,r);if(o)return o}},U=(e,t,r,n)=>{if(e==="AND"||e==="OR")return m(p(t),r,n);if(e==="NOT")return m([t??{}],r,n);const o=r.tables[n]?.relationMap?.[e];if(!o||!y(t))return;const a=o.through===void 0?[o.table]:[o.table,o.through.table],s=a.find(i=>r.tables[i]?.shardMode?.kind==="shardBy");if(s!==void 0)return{kind:"shard",relation:e,target:s};const d=a.find(i=>R(r.tables[i]));return d!==void 0?{kind:"memory",relation:e,target:d}:m(Object.values(t),r,o.table)},T=(e,t,r)=>{for(const n of Object.keys(e)){const o=U(n,e[n],t,r);if(o)return o}},V=(e,t,r)=>{if(!(t.tables[r]?.shardMode?.kind==="global"||!u(e,t,r)))throw Object.assign(new Error(`shape on "${r}" filters by a relation, which a shard-local shape cannot replicate: its seed and membership probe read "${r}" alone, so the relation never matches, and a write that only touches the related table never moves the shape. Fix it by (a) denormalizing the related columns into "${r}" and filtering on those, (b) moving "${r}" to .global() so it is served through the latency-tiered D1 shape tier, or (c) reading it through a live query (\`useQuery\`), which does resolve relations.`),{code:"SHAPE_RELATION_PREDICATE",name:"LunoraError",status:400})},se=(e,t,r)=>{if(R(t.tables[r]))throw Object.assign(new Error(`shape on "${r}" replicates from the changelog, which never records a .memory() table — the shape would seed once and never update again. Fix it by (a) dropping .memory() from "${r}" so its writes reach the changelog, or (b) reading it through a live query (\`useQuery\`), which refreshes off the changed-table set rather than the log.`),{code:"SHAPE_MEMORY_TABLE",name:"LunoraError",status:400});if(!e)return;const n=T(e,t,r);if(!n){V(e,t,r);return}throw n.kind==="memory"?Object.assign(new Error(`shape on "${r}" joins the .memory() table "${n.target}" via relation "${n.relation}" — writes to a .memory() table never reach the changelog, so the shape is never told its membership changed and would serve stale rows indefinitely. Fix it by (a) dropping .memory() from "${n.target}", or (b) reading it through a live query (\`useQuery\`), which refreshes off the changed-table set rather than the log.`),{code:"SHAPE_MEMORY_TABLE",name:"LunoraError",status:400}):Object.assign(new Error(`shape on "${r}" joins the sharded table "${n.target}" via relation "${n.relation}" — a live shape cannot replicate rows that live in another shard's Durable Object. Fix it by (a) denormalizing the joined columns into "${r}", or (b) moving "${n.target}" to .global() so it is served through the latency-tiered D1 shape tier.`),{code:"SHAPE_CROSS_SHARD_JOIN",name:"LunoraError",status:400})};export{D as DEFAULT_MAX_RELATION_KEYS,oe as assertFlatPredicate,se as assertShapeShardable,ae as composeReadPredicate,u as containsRelationPredicate,y as isRelationPredicate,X as resolveRelationPredicates};
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import{toErrorBody as F,LunoraError as U}from"@lunora/errors";import{encodeWire as N,stableWireKey as g,decodeWire as I}from"@lunora/wire";import{sql as y}from"drizzle-orm";import{runDrizzle as S}from"./runDrizzle-B2GG3IJa.mjs";import{WORKERD_SQLITE_LIMITS as K}from"./WORKERD_SQLITE_LIMITS-BdNnnMj0.mjs";import{d as Y,w,a as A,m as G,r as W,b as $,c as B}from"./ctx-db-relay-shapes-CPwELrMf.mjs";import{envPositiveInt as _}from"./envOptionalPositiveInt-D2pY-c64.mjs";import{relayName as m,DEFAULT_PROMOTION_THRESHOLDS as T,nextPromotionState as H,shapeRoutingKey as b,relayProxyKey as M,parseRelayName as q,clampPromotionThresholds as z}from"./DEFAULT_PROMOTION_THRESHOLDS-B3pRMuqb.mjs";import{encodeRowsPatch as X,buildPokeFrames as k}from"./buildPokeFrames-WR-hp0mX.mjs";import{verifySiblingBody as j,RELAY_SIGNATURE_HEADER as L,siblingStub as V,siblingSecretOf as J,signSiblingBody as Q}from"./RELAY_SIGNATURE_HEADER-C_P73AOx.mjs";import{awaitWsDrain as Z,trySendFrame as C}from"./awaitWsDrain-N-oR29RI.mjs";const R="__lunora_relay_memos",ee=a=>{S(a,y`CREATE TABLE IF NOT EXISTS ${y.identifier(R)} (
|
|
2
|
+
connection_id TEXT NOT NULL,
|
|
3
|
+
sub_id TEXT NOT NULL,
|
|
4
|
+
cursor INTEGER NOT NULL,
|
|
5
|
+
epoch TEXT,
|
|
6
|
+
PRIMARY KEY (connection_id, sub_id)
|
|
7
|
+
)`)},te=a=>{const e=S(a,y`SELECT connection_id, sub_id, cursor, epoch FROM ${y.identifier(R)}`).toArray(),s=new Map;for(const t of e){let r=s.get(t.connection_id);r===void 0&&(r=new Map,s.set(t.connection_id,r)),r.set(t.sub_id,{cursor:Number(t.cursor),epoch:t.epoch??void 0})}return s},se=4,x=(a,e)=>{const s=Math.floor(K.boundParams/se);for(let t=0;t<e.length;t+=s){const r=e.slice(t,t+s),o=y.join(r.map(n=>y`(${n.connectionId}, ${n.subId}, ${n.cursor}, ${n.epoch??null})`),y`, `);S(a,y`INSERT INTO ${y.identifier(R)} (connection_id, sub_id, cursor, epoch) VALUES ${o}
|
|
8
|
+
ON CONFLICT(connection_id, sub_id) DO UPDATE SET cursor = excluded.cursor, epoch = excluded.epoch`)}},re=(a,e,s)=>{S(a,y`DELETE FROM ${y.identifier(R)} WHERE connection_id = ${e} AND sub_id = ${s}`)},oe=(a,e)=>{S(a,y`DELETE FROM ${y.identifier(R)} WHERE connection_id = ${e}`)},ne=a=>{S(a,y`DELETE FROM ${y.identifier(R)}`)},ie=2,ae=8,ce=2e3,he=2e3,O=async a=>{let e;const s=new Promise(t=>{e=setTimeout(()=>{t(void 0)},he)});return Promise.race([a,s]).finally(()=>{clearTimeout(e)})},v={},le=a=>{throw new U("INTERNAL",`unhandled relay frame: ${JSON.stringify(a)}`)},de=(a,e)=>a===void 0||a.epoch!==e.epoch?!1:a.cursor>=e.fromCursor&&a.cursor<e.checkpoint,P=a=>Response.json(a,{headers:{"content-type":"application/json"}}),f=()=>new Response(null,{status:204});class D{constructor(e,s){this.host=e,this.roleId=s}host;roleId;async handleControl(e){let s;try{s=await e.text()}catch{return new Response("bad request",{status:400})}if(!await j(this.host.env(),e.headers.get(L),s))return new Response("forbidden",{status:403});let t;try{t=JSON.parse(s)}catch{return new Response("bad request",{status:400})}switch(t.type){case"relay_attach":return this.onAttach(t.relayIndex),f();case"relay_detach":return this.onDetach(t.relayIndex),f();case"relay_frame":{const{exceptConnectionId:r}=t,o=r===void 0?void 0:this.host.getWebSockets().find(n=>this.host.readAttachment(n).connectionId===r);return this.host.deliverWhisperLocal(t.topic,t.frame,o),await this.onWhisperFrame(t),f()}case"relay_live_control":return this.host.liveControl(t.control);case"relay_live_frame":return this.host.deliverLiveLocal(t.topic,t.key,t.frame),f();case"relay_room_event":return P(await this.host.relayRoomEvent(t));case"relay_shape_poke":{const r=this.host.getWebSockets().length,o=Date.now(),{delivered:n,matched:i}=this.onShapePoke({...t,args:I(t.args)});return this.host.recordShapePokeFanout(r,n,Date.now()-o),n<i?Response.json({delivered:n,matched:i},{status:503}):f()}case"relay_shape_subscribe":return P(this.onShapeSubscribe({...t,args:I(t.args)}));case"relay_shape_unsubscribe":return this.onShapeUnsubscribe(t),f();default:return le(t)}}maxRelays(){return _(this.host.env(),"LUNORA_MAX_RELAYS",ae)}canAddressSiblings(){return this.siblingStub(this.roleId.ownerKey)!==void 0}siblingStub(e){return V(this.host.env(),this.bindingName(),e,this.host.shardJurisdiction())}bindingName(){return this.host.shardBinding()}async postRelayMessage(e,s){await this.requestRelayMessage(e,s)}async requestRelayMessage(e,s){const t=this.siblingStub(e);if(t===void 0)return;const r=JSON.stringify(s),o={"content-type":"application/json","x-lunora-shard-binding":this.host.shardBinding()??""},n=J(this.host.env());n!==void 0&&(o[L]=await Q(n,r));try{return await t.fetch("https://relay.internal/_lunora/relay",{body:r,headers:o,method:"POST"})}catch{return}}}class ye extends D{shapeUniformCache=new Map;relaySetCache;liveGrantRelayCache;pendingSubscribeRelays=new Map;registryCache;recordedBinding;promotionState="owned";constructor(e,s){super(e,{ownerKey:s})}async forwardWhisper(e,s,t){if(!this.canAddressSiblings())return;const r=this.ownerRelaySet();r.size!==0&&await Promise.all([...r].map(o=>this.postRelayMessage(m(this.roleId.ownerKey,o),{exceptConnectionId:t,frame:s,topic:e,type:"relay_frame"})))}forwardLiveControl(e){if(!this.canAddressSiblings())return Promise.resolve(void 0);const s=e.action==="unsubscribe"?new Set([...this.liveGrantRelaySet(),...this.pendingSubscribeRelays.keys()]):this.ownerRelaySet();return s.size===0?Promise.resolve(void 0):Promise.any([...s].map(async t=>{const r=await this.liveControlAnswer(t,e);if(r===void 0||r.status===404)throw new Error("relay does not hold the socket");return r})).catch(()=>{})}async forwardLiveFrame(e,s,t){if(!this.canAddressSiblings())return;const r=this.liveGrantRelaySet();r.size!==0&&await Promise.all([...r].map(o=>this.postRelayMessage(m(this.roleId.ownerKey,o),{frame:t,key:s,topic:e,type:"relay_live_frame"})))}async onFlush(e,s){this.canAddressSiblings()&&await Promise.all([this.multicastShapePokes(e,s),this.proxyShapePokes(e,s)])}seedRelayShape(){return Promise.resolve(void 0)}announce(){return Promise.resolve(!0)}announceDrain(){return Promise.resolve()}releaseRelayShapes(){return Promise.resolve()}relayCount(){const e=this.host.getWebSockets().length,s=_(this.host.env(),"LUNORA_RELAY_THRESHOLD",T.tUp),t=_(this.host.env(),"LUNORA_RELAY_COLLAPSE_THRESHOLD",T.tDown);if(this.promotionState=H(this.promotionState,e,z(s,t)),this.promotionState==="owned")return 0;const r=_(this.host.env(),"LUNORA_RELAY_FAN",ie);return Math.min(this.maxRelays(),Math.max(1,r))}minShapeCursor(){const{cohort:e,proxies:s}=this.relayShapes();let t;for(const r of[...e.values(),...s.values()])t=t===void 0?r.cursor:Math.min(t,r.cursor);return t}isShapeRelayUniform(e,s){const t=b(e,s),r=this.shapeUniformCache.get(t);if(r!==void 0)return r;const o=this.probeShapeRelayUniform(e,s);return this.shapeUniformCache.set(t,o),o}onShapeUnsubscribe(e){const{proxies:s}=this.relayShapes(),t=e.subId===void 0?void 0:M(e.relayIndex,e.connectionId,e.subId);for(const[r,o]of s)o.relayIndex!==e.relayIndex||o.connectionId!==e.connectionId||(t===void 0||r===t)&&s.delete(r);Y(this.host.sql(),e.relayIndex,e.connectionId,e.subId)}onAttach(e){this.addRelayToSet(e)}onDetach(e){this.removeRelayFromSet(e)}async onWhisperFrame(e){await Promise.all([...this.ownerRelaySet()].filter(s=>s!==e.originRelay).map(s=>this.postRelayMessage(m(this.roleId.ownerKey,s),{frame:e.frame,topic:e.topic,type:"relay_frame"})))}onShapeSubscribe(e){return this.buildShapeSeedFrames(e)}onShapePoke(){return{delivered:0,matched:0}}buildShapePoke(e,s,t,r,o){let n;try{n=this.host.resolveShape(e.name,e.args,s)}catch{return}if(n===void 0||n.global===!0||!t.has(n.table))return;const i=e,h=i.cursor,c=this.host.buildShapeDiff(n,h,r);if(c.length!==0)return i.cursor=r,w(this.host.sql(),i.key,r),{args:N(e.args),checkpoint:r,epoch:o,fromCursor:h,name:e.name,rowsPatch:X(c),type:"relay_shape_poke"}}async multicastShapePokes(e,s){const t=this.ownerRelaySet();if(t.size===0)return;const{cohort:r}=this.relayShapes();if(r.size===0)return;const o=this.host.currentCdcEpoch(),n=[];for(const i of r.values()){const h=this.buildShapePoke(i,v,e,s,o);h&&n.push(this.multicastToRelays(t,h,i))}await Promise.all(n)}async multicastToRelays(e,s,t){(await Promise.all([...e].map(async o=>(await this.requestRelayMessage(m(this.roleId.ownerKey,o),s))?.ok===!0))).includes(!1)&&this.rewindShapeCursor(t,s.fromCursor)}async proxyShapePokes(e,s){if(this.ownerRelaySet().size===0)return;const{proxies:t}=this.relayShapes();if(t.size===0)return;const r=this.host.currentCdcEpoch(),o=[];for(const n of t.values()){const i=this.buildShapePoke(n,n.identity,e,s,r);i&&o.push(this.proxyToRelay(i,n))}await Promise.all(o)}async proxyToRelay(e,s){(await this.requestRelayMessage(m(this.roleId.ownerKey,s.relayIndex),{...e,targetConnectionId:s.connectionId}))?.ok!==!0&&this.rewindShapeCursor(s,e.fromCursor)}buildShapeSeedFrames(e){const s={identity:e.identity,userId:e.userId};let t;try{t=this.host.resolveShape(e.name,e.args,s)}catch(l){const{body:p}=F(l,{fallbackCode:"SHAPE_RESOLVE_FAILED",redactedMessage:"shape resolution failed"});return{error:{code:p.code,message:p.message}}}if(t===void 0||t.global===!0)return{error:{code:"SHAPE_NOT_FOUND",message:`shape not relayable: ${e.name}`}};e.relayIndex!==void 0&&this.addRelayToSet(e.relayIndex);const{baseCheckpoint:r,cursor:o,epoch:n,reset:i,rowsPatch:h}=this.host.computeOpLogShapeSeed({args:e.args,name:e.name,sinceEpoch:e.sinceEpoch,sinceSeq:e.sinceSeq},t);let c=o;const{cohort:d,proxies:E}=this.relayShapes();if(this.isShapeRelayUniform(e.name,e.args)){const l=b(e.name,e.args);let p=d.get(l);p===void 0&&(p={args:e.args,cursor:o,key:l,name:e.name},d.set(l,p),A(this.host.sql(),p)),c=p.cursor}else if(e.relayIndex!==void 0&&e.connectionId!==void 0){const l=M(e.relayIndex,e.connectionId,e.subId),p={args:e.args,connectionId:e.connectionId,cursor:o,identity:s,key:l,name:e.name,relayIndex:e.relayIndex};E.set(l,p),A(this.host.sql(),p)}else return{error:{code:"RELAY_SHAPE_UNROUTABLE",message:`shape ${e.name} is per-socket on a relay, but the subscribe carries no ${e.relayIndex===void 0?"relay index":"connection id"}`}};const u=k([{reset:i,rowsPatch:h,shapeId:e.subId}],{baseCheckpoint:r,checkpoint:c,epoch:n,lastMutationId:void 0,pokeId:this.host.nextPokeId()});return{cursor:c,epoch:n,frames:u}}ensureRelayTables(){this.host.sql().exec("CREATE TABLE IF NOT EXISTS __lunora_relays (idx INTEGER PRIMARY KEY)"),this.host.sql().exec("CREATE TABLE IF NOT EXISTS __lunora_relay_grants (idx INTEGER PRIMARY KEY)"),this.host.sql().exec("CREATE TABLE IF NOT EXISTS __lunora_relay_binding (id INTEGER PRIMARY KEY, binding TEXT NOT NULL)"),G(this.host.sql())}bindingName(){const e=this.host.shardBinding();if(e!==void 0&&e!=="")return e!==this.recordedBinding&&(this.recordedBinding=e,this.ensureRelayTables(),this.host.sql().exec("INSERT INTO __lunora_relay_binding (id, binding) VALUES (1, ?) ON CONFLICT(id) DO UPDATE SET binding = excluded.binding",e)),e;if(this.recordedBinding!==void 0)return this.recordedBinding;try{const s=this.host.sql().exec("SELECT binding FROM __lunora_relay_binding WHERE id = 1").toArray();this.recordedBinding=s[0]?.binding}catch{this.recordedBinding=void 0}return this.recordedBinding}relayShapes(){const e=this.registryCache;if(e!==void 0)return e;this.ensureRelayTables();const s={cohort:new Map,proxies:new Map};for(const t of W(this.host.sql()))t.relayIndex===void 0||t.connectionId===void 0?s.cohort.set(t.key,{args:t.args,cursor:t.cursor,key:t.key,name:t.name}):s.proxies.set(t.key,{args:t.args,connectionId:t.connectionId,cursor:t.cursor,identity:t.identity??{},key:t.key,name:t.name,relayIndex:t.relayIndex});return this.registryCache=s,s}rewindShapeCursor(e,s){const t=e;t.cursor<=s||(t.cursor=s,w(this.host.sql(),t.key,s))}ownerRelaySet(){if(this.relaySetCache===void 0){this.ensureRelayTables();const e=this.host.sql().exec("SELECT idx FROM __lunora_relays").toArray();this.relaySetCache=new Set(e.map(s=>Number(s.idx)))}return this.relaySetCache}liveGrantRelaySet(){if(this.liveGrantRelayCache===void 0){this.ensureRelayTables();const e=this.host.sql().exec("SELECT idx FROM __lunora_relay_grants").toArray();this.liveGrantRelayCache=new Set(e.map(s=>Number(s.idx)))}return this.liveGrantRelayCache}recordLiveGrantRelay(e){const s=this.liveGrantRelaySet();s.has(e)||(this.host.sql().exec("INSERT OR IGNORE INTO __lunora_relay_grants (idx) VALUES (?)",e),s.add(e))}addRelayToSet(e){this.ensureRelayTables(),this.host.sql().exec("INSERT OR IGNORE INTO __lunora_relays (idx) VALUES (?)",e),this.ownerRelaySet().add(e)}removeRelayFromSet(e){this.ensureRelayTables(),this.host.sql().exec("DELETE FROM __lunora_relays WHERE idx = ?",e);const s=this.ownerRelaySet();s.delete(e),this.host.sql().exec("DELETE FROM __lunora_relay_grants WHERE idx = ?",e),this.liveGrantRelaySet().delete(e);const{cohort:t,proxies:r}=this.relayShapes();for(const[o,n]of r)n.relayIndex===e&&r.delete(o);$(this.host.sql(),e),s.size===0&&(t.clear(),this.shapeUniformCache.clear(),B(this.host.sql()))}probeShapeRelayUniform(e,s){let t;try{t=this.host.resolveShape(e,s,v)}catch{return!1}if(t===void 0||t.global===!0||this.host.rlsMetadata().policies.some(c=>c.on==="read"&&c.table===t.table)||this.tableHasAnyMask(t.table))return!1;const r=g(t.effectiveWhere),o=g(t.columns);let n=!1;const i=c=>{const d={groups:[`grp_${c}`],roles:[c],sub:`__lunora_probe_${c}__`};return{identity:new Proxy(d,{get:(u,l)=>typeof l=="symbol"||l in u?Reflect.get(u,l):`${c}:${l}`,getOwnPropertyDescriptor:(u,l)=>(n=!0,Reflect.getOwnPropertyDescriptor(u,l)),has:(u,l)=>typeof l=="symbol"?Reflect.has(u,l):!0,ownKeys:u=>(n=!0,Reflect.ownKeys(u))}),ip:`__lunora_probe_${c}__`,userId:`__lunora_probe_${c}__`}};return[v,i("a"),i("b")].every(c=>{let d;try{d=this.host.resolveShape(e,s,c)}catch{return!1}return d!==void 0&&d.global!==!0&&d.table===t.table&&g(d.effectiveWhere)===r&&g(d.columns)===o})&&!n}tableHasAnyMask(e){return this.host.maskMetadata().columns.some(s=>s.table===e)}async liveControlAnswer(e,s){const t=s.action==="subscribe";t&&this.pendingSubscribeRelays.set(e,(this.pendingSubscribeRelays.get(e)??0)+1);const r=this.requestRelayMessage(m(this.roleId.ownerKey,e),{control:s,type:"relay_live_control"}).then(i=>(t&&i?.ok===!0&&this.recordLiveGrantRelay(e),i)).finally(()=>{if(!t)return;const i=(this.pendingSubscribeRelays.get(e)??1)-1;i===0?this.pendingSubscribeRelays.delete(e):this.pendingSubscribeRelays.set(e,i)});let o;const n=new Promise(i=>{o=setTimeout(()=>{i(void 0)},ce)});return Promise.race([r,n]).finally(()=>{clearTimeout(o)})}}class ue extends D{relayAnnounced=!1;pendingAnnounce;announceGeneration=0;pendingDetach;relayMemoCache;shapeControl=new Map;constructor(e,s,t){super(e,{ownerKey:s,relayIndex:t})}async forwardWhisper(e,s){this.canAddressSiblings()&&await this.postRelayMessage(this.roleId.ownerKey,{frame:s,originRelay:this.roleId.relayIndex,topic:e,type:"relay_frame"})}async forwardRoomEvent(e){const s=await this.requestRelayMessage(this.roleId.ownerKey,{...e,relayIndex:this.roleId.relayIndex,type:"relay_room_event"});if(!s?.ok)return!1;try{return(await s.json()).admitted}catch{return!1}}onFlush(){return Promise.resolve()}async seedRelayShape(e,s,t,r){if(!this.canAddressSiblings())return{code:"RELAY_MISCONFIGURED",message:"relay cannot address its owner"};const{connectionId:o}=this.host.readAttachment(e),n={args:N(t.args??{}),connectionId:o,identity:r.identity,name:t.name,relayIndex:this.roleId.relayIndex,sinceEpoch:t.sinceEpoch,sinceSeq:t.sinceSeq,subId:s,type:"relay_shape_subscribe",userId:r.userId},i=await this.queueShapeControl(o,async()=>(await this.announce(),this.requestRelayMessage(this.roleId.ownerKey,n)));if(i===void 0)return{code:"RELAY_SEED_FAILED",message:"owner did not answer the shape seed"};let h;try{h=await i.json()}catch{return{code:"RELAY_SEED_FAILED",message:"malformed shape seed from owner"}}if(h.error!==void 0)return h.error;if(h.frames===void 0)return{code:"RELAY_SEED_FAILED",message:"owner returned no shape frames"};await Z(e);for(const c of h.frames)C(e,c);return this.recordRelayShapeMemo(e,s,h.cursor??0,h.epoch),"ok"}announce(){if(this.relayAnnounced||!this.canAddressSiblings())return Promise.resolve(!0);if(this.pendingAnnounce===void 0){const e=this.announceGeneration;this.pendingAnnounce=(this.pendingDetach??Promise.resolve()).then(async()=>O(this.requestRelayMessage(this.roleId.ownerKey,{relayIndex:this.roleId.relayIndex,type:"relay_attach"}))).then(s=>{const t=s?.ok===!0;return e===this.announceGeneration&&(this.relayAnnounced=t),t}).finally(()=>{e===this.announceGeneration&&(this.pendingAnnounce=void 0)})}return this.pendingAnnounce}async announceDrain(e){if(this.host.getWebSockets().some(o=>o!==e)||(this.relayMemos().clear(),ne(this.host.sql()),!this.canAddressSiblings()))return;this.relayAnnounced=!1,this.announceGeneration+=1;const s=this.pendingAnnounce;this.pendingAnnounce=void 0;const t=this.pendingDetach,r=Promise.all([s?.catch(()=>!1),t]).then(async()=>O(this.postRelayMessage(this.roleId.ownerKey,{relayIndex:this.roleId.relayIndex,type:"relay_detach"}))).catch(()=>{}).finally(()=>{this.pendingDetach===r&&(this.pendingDetach=void 0)});this.pendingDetach=r,await r}async releaseRelayShapes(e,s){const{connectionId:t}=this.host.readAttachment(e);t!==void 0&&this.forgetRelayShapeMemos(t,s),!(t===void 0||!this.canAddressSiblings())&&await this.queueShapeControl(t,async()=>this.postRelayMessage(this.roleId.ownerKey,{connectionId:t,relayIndex:this.roleId.relayIndex,...s===void 0?{}:{subId:s},type:"relay_shape_unsubscribe"}))}relayCount(){return 0}isShapeRelayUniform(){return!1}minShapeCursor(){}onAttach(){}onDetach(){}onWhisperFrame(){return Promise.resolve()}onShapeSubscribe(){return{error:{code:"RELAY_CANNOT_SEED",message:"a relay has no op-log to seed from"}}}onShapeUnsubscribe(){}onShapePoke(e){return this.deliverShapePoke(e)}async queueShapeControl(e,s){if(e===void 0)return s();const t=(this.shapeControl.get(e)??Promise.resolve()).then(s,s),r={},o=()=>{this.shapeControl.get(e)===r.chain&&this.shapeControl.delete(e)},n=t.then(o,o);return r.chain=n,this.shapeControl.set(e,n),t}relayMemos(){return this.relayMemoCache===void 0&&(ee(this.host.sql()),this.relayMemoCache=te(this.host.sql())),this.relayMemoCache}connectionMemos(e){const s=this.relayMemos();let t=s.get(e);return t===void 0&&(t=new Map,s.set(e,t)),t}recordRelayShapeMemo(e,s,t,r){const{connectionId:o}=this.host.readAttachment(e);o!==void 0&&(this.connectionMemos(o).set(s,{cursor:t,epoch:r}),x(this.host.sql(),[{connectionId:o,cursor:t,epoch:r,subId:s}]))}forgetRelayShapeMemos(e,s){if(s===void 0){this.relayMemos().delete(e),oe(this.host.sql(),e);return}this.relayMemos().get(e)?.delete(s),re(this.host.sql(),e,s)}deliverShapePoke(e){const s=b(e.name,e.args),t=[];let r=0,o=0;for(const n of this.host.getWebSockets()){const{connectionId:i,shapes:h}=this.host.readAttachment(n);if(h===void 0||i===void 0||e.targetConnectionId!==void 0&&i!==e.targetConnectionId)continue;const c=this.pokeSocketShapes(n,h,this.connectionMemos(i),e,s);o+=c.matched.length,r+=c.sent;for(const d of c.matched)t.push({connectionId:i,cursor:e.checkpoint,epoch:e.epoch,subId:d})}return x(this.host.sql(),t),{delivered:r,matched:o}}pokeSocketShapes(e,s,t,r,o){const n=[];let i=0;for(const[h,c]of Object.entries(s)){const d=t.get(h);if(b(c.name,c.args)!==o||!de(d,r))continue;const u=k([{baseCheckpoint:d?.cursor,rowsPatch:r.rowsPatch,shapeId:h}],{baseCheckpoint:void 0,checkpoint:r.checkpoint,epoch:r.epoch,lastMutationId:void 0,pokeId:this.host.nextPokeId()},{preEncoded:!0}).map(l=>C(e,l)).every(Boolean);t.set(h,{cursor:r.checkpoint,epoch:r.epoch}),n.push(h),u&&(i+=1)}return{matched:n,sent:i}}}const we=a=>{const e=a.doName();if(e===void 0)return;const s=q(e);return s===void 0?new ye(a,e):new ue(a,s.ownerKey,s.relayIndex)};export{ae as DEFAULT_MAX_RELAYS,ye as OwnerRelay,ue as RelayMember,we as createRelayLink};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as m}from"@lunora/errors";import{stableWireKey as a}from"@lunora/wire";const i="::relay::",w=(t,n)=>`${t}${i}${String(n)}`,f=t=>{const n=t.lastIndexOf(i);if(n===-1)return;const o=t.slice(0,n),e=t.slice(n+i.length),r=Number(e);if(!(o.length===0||!Number.isInteger(r)||r<0||String(r)!==e))return{ownerKey:o,relayIndex:r}},l=(t,n)=>a({args:n??{},name:t}),d=(t,n,o)=>`${String(t)}:${n}:${o}`,c={tDown:4e3,tUp:8e3},g=(t,n,o=c)=>{if(o.tDown>=o.tUp)throw new m("INTERNAL",`invalid promotion thresholds: tDown (${String(o.tDown)}) must be < tUp (${String(o.tUp)})`);return t==="owned"?n>=o.tUp?"promoted":"owned":n<o.tDown?"owned":"promoted"},x=(t,n)=>n<t?{tDown:n,tUp:t}:{tDown:Math.min(Math.max(1,Math.floor(t/2)),t-1),tUp:t},N=(t,n,o)=>{if(t<=n||n<=0)return 0;const e=t-n,r=Math.ceil(e/n);return Math.min(r,Math.max(0,o))};export{c as DEFAULT_PROMOTION_THRESHOLDS,x as clampPromotionThresholds,g as nextPromotionState,f as parseRelayName,N as relayCountFor,w as relayName,d as relayProxyKey,l as shapeRoutingKey};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as i}from"@lunora/errors";import{e}from"./estimate-bytes-_k74s6LZ.mjs";const r={maxReadRows:1e5,maxWrittenBytes:32*1024*1024,maxWrittenRows:5e4};class w{readRows=0;writtenRows=0;writtenBytes=0;limits;constructor(t={}){this.limits={...r,...t}}recordRead(t){if(this.readRows+=t,this.readRows>this.limits.maxReadRows)throw new i("TRANSACTION_LIMIT_EXCEEDED",`this transaction read ${String(this.readRows)} documents, over the ${String(this.limits.maxReadRows)}-document limit`)}recordWrite(t){const s=e(t);if(s===void 0)throw new i("BAD_REQUEST","this document is not JSON-serializable (cyclic or non-JSON value); it cannot be written");if(this.writtenRows+=1,this.writtenBytes+=s,this.writtenRows>this.limits.maxWrittenRows)throw new i("TRANSACTION_LIMIT_EXCEEDED",`this transaction wrote ${String(this.writtenRows)} documents, over the ${String(this.limits.maxWrittenRows)}-document limit`);if(this.writtenBytes>this.limits.maxWrittenBytes)throw new i("TRANSACTION_LIMIT_EXCEEDED",`this transaction wrote ${String(this.writtenBytes)} bytes, over the ${String(this.limits.maxWrittenBytes)}-byte limit`)}headroom(){return{readRows:this.readRows,remainingReadRows:Math.max(0,this.limits.maxReadRows-this.readRows),remainingWrittenBytes:Math.max(0,this.limits.maxWrittenBytes-this.writtenBytes),remainingWrittenRows:Math.max(0,this.limits.maxWrittenRows-this.writtenRows),writtenBytes:this.writtenBytes,writtenRows:this.writtenRows}}}export{r as DEFAULT_TRANSACTION_LIMITS,w as TransactionHeadroomTracker};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{toErrorBody as R,LunoraError as k}from"@lunora/errors";import{encodeWire as A}from"@lunora/wire";import{readStreamRun as w,deleteStreamRun as T,claimStreamRun as _,appendStreamChunk as y,finishStreamRun as E,trimStreamRuns as b,readStreamChunks as v}from"./appendStreamChunk-DF_Jrgpy.mjs";const S=5e4,p=64*1024*1024,M=864e5,N=36e5,L=(i,e)=>{const r=i?.startedAt??e.live?.generation;return e.resuming&&e.generation!==void 0&&r!==void 0&&e.generation!==r?"interrupted":e.live!==void 0?"attach":i===void 0?e.resuming?"interrupted":"attach":i.status==="complete"||i.status==="error"?e.resuming?"replay-terminal":"reclaim":e.resuming?"interrupted":"reclaim"},O=(i,e,r)=>{(i||r())&&e.fail({code:"STREAM_INTERRUPTED",message:i?"the run this durable stream resumed from no longer exists; start a new run":"the producer for this durable stream did not survive; start a new run"})};class I{lastTrimAt=0;runs=new Map;sql;waitUntil;constructor(e){this.sql=e.sql,this.waitUntil=e.waitUntil}async attach(e){try{await this.attachOrThrow(e)}catch(r){const{body:t,redacted:o}=R(r,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"internal error"});o&&console.error("[@lunora/shard-engine] durable stream attach failed:",r),e.sink.fail({code:t.code,message:t.message})}finally{this.trim(this.sql())}}detach(e,r){this.runs.get(e)?.sinks.delete(r)}isLive(e){return this.runs.has(e)}async attachOrThrow(e){const r=this.sql(),{runKey:t,sinceChunk:o,sink:c}=e,s=w(r,t),u=o>0,n=this.runs.get(t),a=s?.startedAt??n?.generation,l=L(s,{generation:e.generation,live:n,resuming:u}),d=()=>{for(const g of v(r,t,o))if(!c.chunk({data:JSON.parse(g.dataJson),generation:a,seq:g.seq}))return!1;return!0};if(l==="replay-terminal"){d()&&(s?.status==="error"?c.fail({code:s.errorCode??"INTERNAL_SERVER_ERROR",message:s.error??"stream failed"}):c.complete());return}if(l==="interrupted"){O(e.generation!==void 0&&a!==void 0&&e.generation!==a,c,d);return}if(n){d()&&n.sinks.add(c);return}l==="reclaim"&&T(r,t);const m=Math.max(Date.now(),s===void 0?0:s.startedAt+1);_(r,t,m,e.ttlMs??M);const h={generation:m,sinks:new Set([c])};this.runs.set(t,h);const f=this.produce(t,e.iterator,h);this.waitUntil?.(f),await f}async produce(e,r,t){const o=this.sql(),c=new AbortController;let s=0,u=0;try{for await(const n of r(c.signal)){const a=A(n),l=JSON.stringify(a);if(s+=1,u+=l.length,s>S||u>p)throw new k("STREAM_TOO_LONG",`durable stream exceeded its ceiling (${String(S)} chunks / ${String(p)} bytes); yield less, or drop \`durable\``,{status:507});y(o,e,s,l);for(const d of t.sinks)d.chunk({data:a,generation:t.generation,seq:s})||t.sinks.delete(d)}E(o,e,"complete",s);for(const n of t.sinks)n.complete()}catch(n){const{body:a,redacted:l}=R(n,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"internal error"});l&&console.error("[@lunora/shard-engine] unhandled durable stream error:",n),E(o,e,"error",s,{code:a.code,message:a.message});for(const d of t.sinks)d.fail({code:a.code,message:a.message})}finally{this.runs.delete(e)}}trim(e){const r=Date.now();if(!(r-this.lastTrimAt<=N)){this.lastTrimAt=r;try{b(e,r,new Set(this.runs.keys()))}catch{}}}}export{I as DurableStreamRunner,p as MAX_DURABLE_STREAM_BYTES,S as MAX_DURABLE_STREAM_CHUNKS,L as decideDurableAttach};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const m="0123456789bcdefghjkmnpqrstuvwxyz",k=9,p=63710088e-1,d=Math.PI/180,f=[Number.POSITIVE_INFINITY,5009400,1252300,156500,39100,4900,1200,152.9,38.2,4.77,1.19,.149,.037],S=f.map((t,n)=>n%2===0?t/2:t),I=.01,C=Math.acos(I)/d,z=2,_=t=>t/p/d,R=t=>{const n=5*t;return{latBands:2**Math.floor(n/2),lngSectors:2**Math.ceil(n/2)}},T=t=>Math.min(Math.max(Math.trunc(t),1),12),b=(t,n)=>{const a=T(n);let s=-90,o=90,e=-180,c=180,r="",g=0,l=0,u=!0;for(;r.length<a;){if(u){const h=(e+c)/2;t.lng>=h?(l=l*2+1,e=h):(l*=2,c=h)}else{const h=(s+o)/2;t.lat>=h?(l=l*2+1,s=h):(l*=2,o=h)}u=!u,g<4?g+=1:(r+=m[l]??"0",g=0,l=0)}return r},v=(t,n)=>Math.min(90,Math.abs(t)+_(n)),j=(t,n)=>{const a=(n.lat-t.lat)*d,s=(n.lng-t.lng)*d,o=t.lat*d,e=n.lat*d,c=Math.sin(a/2)**2+Math.cos(o)*Math.cos(e)*Math.sin(s/2)**2;return 2*p*Math.asin(Math.min(1,Math.sqrt(c)))},y=(t,n)=>{const a=Math.max(Math.cos(v(n,t)*d),I);for(let s=f.length-1;s>=1;s-=1){const o=f[s],e=S[s];if(o!==void 0&&e!==void 0&&o*a>=t&&e>=t)return s}return 1},B={east:["bc01fg45238967deuvhjyznpkmstqrwx","p0r21436x8zb9dcf5h7kjnmqesgutwvy"],north:["p0r21436x8zb9dcf5h7kjnmqesgutwvy","bc01fg45238967deuvhjyznpkmstqrwx"],south:["14365h7k9dcfesgujnmqp0r2twvyx8zb","238967debc01fg45kmstqrwxuvhjyznp"],west:["238967debc01fg45kmstqrwxuvhjyznp","14365h7k9dcfesgujnmqp0r2twvyx8zb"]},P={east:["bcfguvyz","prxz"],north:["prxz","bcfguvyz"],south:["028b","0145hjnp"],west:["0145hjnp","028b"]},i=(t,n)=>{const a=t.toLowerCase(),s=a.at(-1)??"";let o=a.slice(0,-1);const e=a.length%2===0?0:1;return P[n][e].includes(s)&&o!==""&&(o=i(o,n)),o+(m[B[n][e].indexOf(s)]??"")},q=(t,n,a)=>{const s=Math.min(a,z),{latBands:o,lngSectors:e}=R(s),c=180/o,r=360/e,g=_(n),l=Math.max(-90,t.lat-g),u=Math.min(90,t.lat+g),h=new Set;for(let M=0;M<o;M+=1){const w=-90+M*c;if(w+c<l||w>u)continue;const x=w+c/2;for(let E=0;E<e;E+=1){const L=-180+(E+.5)*r;h.add(b({lat:x,lng:L},s))}}return[...h]},A=(t,n)=>{const a=Math.max(n,1),s=y(a,t.lat);if(v(t.lat,a)>=C)return q(t,a,s);const e=b(t,s),c=i(e,"north"),r=i(e,"south"),g=[e,c,r,i(e,"east"),i(e,"west"),i(c,"east"),i(c,"west"),i(r,"east"),i(r,"west")];return[...new Set(g)]},G=(t,n)=>t.lat>=n.sw.lat&&t.lat<=n.ne.lat&&t.lng>=n.sw.lng&&t.lng<=n.ne.lng,D=t=>({lat:(t.sw.lat+t.ne.lat)/2,lng:(t.sw.lng+t.ne.lng)/2}),H=t=>{const n=D(t);return A(n,Math.max(j(n,t.ne),1))};export{k as GEO_DEFAULT_PRECISION,D as boundingBoxCenter,H as boundingBoxGeohashes,A as coveringGeohashes,b as encodeGeohash,j as haversineMeters,G as pointInBoundingBox};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import{LunoraError as p}from"@lunora/errors";import{sql as e}from"drizzle-orm";import{runDrizzle as i}from"./runDrizzle-B2GG3IJa.mjs";const s="__global_shape_snapshot",E=1e6,T=n=>{i(n,e`CREATE TABLE IF NOT EXISTS ${e.identifier(s)} (
|
|
2
|
+
connection_id TEXT NOT NULL,
|
|
3
|
+
sub_id TEXT NOT NULL,
|
|
4
|
+
members TEXT NOT NULL,
|
|
5
|
+
PRIMARY KEY (connection_id, sub_id)
|
|
6
|
+
)`)},b=(n,o,r)=>{const t=i(n,e`SELECT members FROM ${e.identifier(s)} WHERE connection_id = ${o} AND sub_id = ${r} LIMIT 1`).toArray()[0]?.members;if(t!==void 0)try{const a=JSON.parse(t);return a===null||typeof a!="object"?new Map:new Map(Object.entries(a))}catch{return new Map}},_=(n,o,r,c)=>{const t=JSON.stringify(Object.fromEntries(c));if(t.length>E)throw new p("BAD_REQUEST",`global shape snapshot for subscription "${r}" is ${String(t.length)} characters, past the ${String(E)}-character cap for one durable baseline row; narrow the shape with a predicate or an RLS read policy`);i(n,e`INSERT INTO ${e.identifier(s)} (connection_id, sub_id, members) VALUES (${o}, ${r}, ${t})
|
|
7
|
+
ON CONFLICT(connection_id, sub_id) DO UPDATE SET members = excluded.members`)},h=(n,o,r)=>{i(n,e`DELETE FROM ${e.identifier(s)} WHERE connection_id = ${o} AND sub_id = ${r}`)},m=(n,o)=>{i(n,e`DELETE FROM ${e.identifier(s)} WHERE connection_id = ${o}`)};export{E as GLOBAL_SHAPE_SNAPSHOT_MAX_CHARS,s as GLOBAL_SHAPE_SNAPSHOT_TABLE,h as deleteGlobalShapeSnapshot,m as deleteGlobalShapeSnapshotsForConnection,T as migrateGlobalShapeSnapshot,b as readGlobalShapeSnapshot,_ as writeGlobalShapeSnapshot};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
class n{changedTables;reads=new Map;resync=!1;skippedCount=0;constructor(e){this.changedTables=e}get readCount(){return this.reads.size}get resyncRequested(){return this.resync}get skipped(){return this.skippedCount}requestResync(){this.resync=!0}async rows(e,s){if(e===void 0)return s();const t=this.reads.get(e)??s();return this.reads.set(e,t),t}shouldRead(e){return this.changedTables===void 0||this.changedTables.has(e)?!0:(this.skippedCount+=1,!1)}}export{n as default};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import{sql as t}from"drizzle-orm";import{runDrizzle as n}from"./runDrizzle-B2GG3IJa.mjs";const r="__idempotency",m=i=>{n(i,t`CREATE TABLE IF NOT EXISTS ${t.identifier(r)} (
|
|
2
|
+
identity TEXT NOT NULL,
|
|
3
|
+
mutation_id TEXT NOT NULL,
|
|
4
|
+
result_json TEXT NOT NULL,
|
|
5
|
+
ts REAL NOT NULL,
|
|
6
|
+
PRIMARY KEY (identity, mutation_id)
|
|
7
|
+
)`)},L=(i,e,s)=>{const o=n(i,t`SELECT result_json, ts FROM ${t.identifier(r)} WHERE identity = ${e} AND mutation_id = ${s} LIMIT 1`).toArray()[0];return o===void 0?void 0:{resultJson:o.result_json,ts:o.ts}},N=(i,e,s,E,o)=>{n(i,t`INSERT OR IGNORE INTO ${t.identifier(r)} (identity, mutation_id, result_json, ts) VALUES (${e}, ${s}, ${E}, ${o})`)},I=(i,e)=>{n(i,t`DELETE FROM ${t.identifier(r)} WHERE ts < ${e}`)};export{r as IDEMPOTENCY_TABLE,m as migrateIdempotency,L as readIdempotent,I as trimIdempotent,N as writeIdempotent};
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import{runSql as c,decodeJsonColumn as a,orNull as o}from"./runDrizzle-B2GG3IJa.mjs";const e="__lunora_mail",l=500,i=256*1024,n=t=>t!==void 0&&t.length>i?`${t.slice(0,i)}
|
|
2
|
+
… [truncated by the dev mail catcher]`:t,s=t=>t===void 0?null:JSON.stringify(t),_=t=>{c(t,`CREATE TABLE IF NOT EXISTS "${e}" (
|
|
3
|
+
id TEXT PRIMARY KEY,
|
|
4
|
+
captured_at INTEGER NOT NULL,
|
|
5
|
+
from_addr TEXT,
|
|
6
|
+
to_addrs TEXT NOT NULL,
|
|
7
|
+
cc_addrs TEXT,
|
|
8
|
+
bcc_addrs TEXT,
|
|
9
|
+
reply_to TEXT,
|
|
10
|
+
subject TEXT NOT NULL,
|
|
11
|
+
html TEXT,
|
|
12
|
+
body_text TEXT,
|
|
13
|
+
headers TEXT
|
|
14
|
+
)`)},N=(t,r,T)=>{_(t);const E=crypto.randomUUID();return c(t,`INSERT INTO "${e}" (id, captured_at, from_addr, to_addrs, cc_addrs, bcc_addrs, reply_to, subject, html, body_text, headers)
|
|
15
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,E,T,o(r.from),JSON.stringify(r.to),s(r.cc),s(r.bcc),o(r.replyTo),r.subject,o(n(r.html)),o(n(r.text)),s(r.headers)),c(t,`DELETE FROM "${e}"
|
|
16
|
+
WHERE id NOT IN (
|
|
17
|
+
SELECT id FROM "${e}" ORDER BY captured_at DESC, id DESC LIMIT ?
|
|
18
|
+
)`,l),{id:E}},u=(t,r={})=>{_(t);const T=Math.min(Math.max(r.limit??50,1),l);return{entries:c(t,`SELECT * FROM "${e}" ORDER BY captured_at DESC, id DESC LIMIT ?`,T).toArray().map(d=>({bcc:a(d.bcc_addrs),capturedAt:d.captured_at,cc:a(d.cc_addrs),from:d.from_addr??void 0,headers:a(d.headers),html:d.html??void 0,id:d.id,replyTo:d.reply_to??void 0,subject:d.subject,text:d.body_text??void 0,to:a(d.to_addrs)??d.to_addrs}))}},M=t=>(_(t),c(t,`DELETE FROM "${e}"`),{cleared:!0});export{l as MAIL_RETENTION,e as MAIL_TABLE,i as MAX_BODY_CHARS,M as clearCapturedMail,_ as ensureMailTable,u as readCapturedMail,N as recordCapturedMail};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import{LunoraError as E}from"@lunora/errors";const S="x",u=" ",p={'"':'"',"'":"'","[":"]","`":"`"},f=(n,t)=>{let e=t+2;for(;e<n.length&&n[e]!==`
|
|
2
|
+
`;)e+=1;return e},g=(n,t)=>{const e=n.indexOf("*/",t+2);return e===-1?-1:e+2},L=n=>{const t=n.split("");let e=0;for(;e<n.length;){const o=n[e]??"",i=p[o];if(o==="-"&&n[e+1]==="-"){const s=f(n,e);t.fill(u,e,s),e=s}else if(o==="/"&&n[e+1]==="*"){const s=g(n,e);if(s===-1)return;t.fill(u,e,s),e=s}else if(i!==void 0){let s=e+1;for(;s<n.length;)if(n[s]!==i)s+=1;else if(i!=="]"&&n[s+1]===i)s+=2;else break;if(s>=n.length)return;t.fill(S,e,s+1),e=s+1}else e+=1}for(let o=0;o<n.length;o+=1)n[o]===`
|
|
3
|
+
`&&(t[o]=`
|
|
4
|
+
`);return t.join("")},A=/^(?:explain\s+(?:query\s+plan\s+)?)?(?:select|with)\b/iu,N=/\b(?:alter|attach|create|delete|detach|drop|insert|pragma|reindex|truncate|update|vacuum)\b|\breplace\b(?!\s*\()/iu,w=/^\w+/u,x=/;\s*$/u,y=/\s/u,O=n=>{let t=0;for(;t<n.length;){const e=n[t];if(e!==void 0&&y.test(e))t+=1;else if(e==="-"&&n[t+1]==="-")t=f(n,t);else if(e==="/"&&n[t+1]==="*"){const o=g(n,t);if(o===-1)break;t=o}else break}return t},h=n=>{const t=O(n),e=n.slice(t).trimEnd();if(e==="")return{code:"SQL_EMPTY",message:"the query is empty"};const i=(L(e)??e).replace(x,""),s=e.slice(0,i.length),r=i.indexOf(";");if(r!==-1)return{code:"SQL_MULTIPLE_STATEMENTS",length:1,message:"only a single statement may be run",offset:t+r};const a="the SQL editor is read-only — only SELECT / WITH / EXPLAIN queries are allowed";if(!A.test(s))return{code:"SQL_NOT_READONLY",length:w.exec(s)?.[0].length??1,message:a,offset:t};const c=N.exec(s);if(c!==null)return{code:"SQL_NOT_READONLY",length:c[0].length,message:`${a} (\`${c[0].toUpperCase()}\` is not allowed)`,offset:t+c.index}},d=1e3,_=n=>{const t=new Map;return n.map(e=>{const o=(t.get(e)??0)+1;return t.set(e,o),o===1?e:`${e}:${String(o)}`})},T=n=>{const t=h(n);if(t!==void 0)throw new E(t.code,t.message,{status:400})},I=(n,t)=>{T(t);const e=n.exec(t),{columnNames:o,raw:i}=e;if(o===void 0||i===void 0){const c=e.toArray(),l=c.length>d?c.slice(0,d):c;return{columns:l.length>0?Object.keys(l[0]):[],rowCount:c.length,rows:l,truncated:c.length>d}}const s=_(o),r=[...i.call(e)],a=(r.length>d?r.slice(0,d):r).map(c=>Object.fromEntries(s.map((l,m)=>[l,c[m]])));return{columns:s,rowCount:r.length,rows:a,truncated:r.length>d}},R=/near "([^"]*)": syntax error/iu,b=/^SCAN (?:TABLE )?(?!CONSTANT\b|SUBQUERY\b)([^\s(]+)/u,C=(n,t)=>{if(t==="")return{};const e=n.indexOf(t);return e===-1?{}:{length:t.length,offset:e}},M=(n,t)=>{const e=h(t);if(e!==void 0)return{diagnostics:e.code==="SQL_EMPTY"?[]:[{length:e.length,message:e.message,offset:e.offset,severity:"error",source:"gate"}],plan:[]};let o;try{o=n.exec(`EXPLAIN QUERY PLAN ${t}`).toArray().map(r=>{const{detail:a}=r;return typeof a=="string"?a:""}).filter(r=>r!=="")}catch(r){const a=r instanceof Error?r.message:String(r),c=R.exec(a);return{diagnostics:[{...c?C(t,c[1]??""):{},message:a,severity:"error",source:"syntax"}],plan:[]}}const i=[],s=new Set;for(const r of o){const a=b.exec(r);if(a){const c=a[1]??"";s.has(c)||(s.add(c),i.push({message:`full table scan on \`${c}\` — this query reads every row`,severity:"warning",source:"plan"}))}}return{diagnostics:i,plan:o}};export{d as MAX_SQL_ROWS,T as assertReadonly,M as lintReadonlySql,I as runReadonlySql};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const f=["de","en","es","fr","it","nl","none","pt"],g=e=>f.includes(e),w="a an and are as at be but by for if in into is it no not of on or such that the their then there these they this to was will with",x="aber als am an auch auf aus bei bin bis bist da dass der den des dem die das denn dir du ein eine für hat ich im in ist mit nicht noch nur oder sich sie sind über und von vor war wie wir zu zum zur",S="a al como con de del el en es la las lo los mas no o para pero por que se su sus un una uno y ya",v="au aux avec ce ces dans de des du elle en et eux il je la le les leur lui ma mais me même mes moi mon ne nos notre nous on ou par pas pour qu que qui sa se ses son sur ta te tes toi ton tu un une vos votre vous y",b="a ai al alla anche che chi ci coi col come con da dal degli dei del della di do e ed gli ha hai hanno i il in la le lo ma mi ne nei nel non o per più quale quanto se si sono su sul tra un una uno vi",j="aan al als bij dan dat de der deze die dit door een en er het hij ij in is je kan me men met mij na naar niet nog nu of om ons ook op over te tot uit van voor was wat we wij zij zijn zo",z="a ao aos as até com como da das de do dos e em entre era essa esse esta este eu foi há isso já mais mas me mesmo meu na nas no nos num numa o os ou para pela pelo por qual que quem se sem seu só sua também te tem um uma você",q=new RegExp("(?<=\\p{Script=Cyrillic})[\\u0300-\\u0305\\u0307\\u0309-\\u036F]|(?<!\\p{Script=Cyrillic})[\\u0300-\\u036F]","gu"),E=/[\u0080-\u{10FFFF}]/u,_=/[\p{L}\p{N}]+/gu,y=/[\p{Script_Extensions=Han}\p{Script_Extensions=Hiragana}\p{Script_Extensions=Katakana}\p{Script_Extensions=Hangul}]+/gu,m=/[\p{Script_Extensions=Han}\p{Script_Extensions=Hiragana}\p{Script_Extensions=Katakana}\p{Script_Extensions=Hangul}]/u,F=e=>{if(!m.test(e))return[e];const n=[];let s=0;for(const o of e.matchAll(y)){const u=o.index,a=[...o[0]];if(u>s&&n.push(e.slice(s,u)),s=u+o[0].length,a.length===1){n.push(o[0]);continue}for(let t=0;t+1<a.length;t+=1)n.push(`${String(a[t])}${String(a[t+1])}`)}return s<e.length&&n.push(e.slice(s)),n},h=e=>E.test(e)?e.normalize("NFD").replaceAll(q,"").normalize("NFC").toLowerCase():e.toLowerCase(),i=e=>new Set(h(e).split(" ")),C={de:i(x),en:i(w),es:i(S),fr:i(v),it:i(b),nl:i(j),none:new Set,pt:i(z)},H=3,k=256,p=new Map,N=e=>{const n=e!==void 0&&g(e)?e:"none",s=p.get(n);if(s)return s;const o=C[n],u=t=>{const r=h(t),c=r.match(_)??[],d=(m.test(r)?c.flatMap(l=>F(l)):c).filter(l=>l.length<=k);return o.size===0?d:d.filter(l=>!o.has(l))},a={document:u,profile:`${n}-v${String(H)}`,query:t=>{const r=u(t);return r.filter((c,d)=>r.lastIndexOf(c)===d)}};return p.set(n,a),a};export{N as D};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as $}from"@lunora/errors";import{D as ft}from"./MAX_TOKEN_LENGTH-BakL9FUy-B3VwYY8C.mjs";import{S as Tn,l as We,h as vn}from"./fts-companion-DzfEHonU.mjs";import{decodeWire as An,stableWireKey as bt}from"@lunora/wire";import{sql as a}from"drizzle-orm";import{throwingScheduler as In,aggregateSqlFunction as Be,normalizeCountArgument as Cn}from"./AGGREGATE_SQL_FUNCTION-C_ZipS9R.mjs";import{aggregateTableName as et,encodeAggregateKey as tt,readAggregateValue as nt}from"./aggregateTableName-B_CtIQCS.mjs";import{mergeWhere as K,CountRlsUnsupportedError as ot,selectIndexForGroupBy as xn,selectIndexForCount as bn,selectIndexForAggregate as Mn}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{backfillSearchIndexesForTable as Dn,searchIndexCoversTable as kn}from"./backfillAggregateIndexes-Dw4Azd33.mjs";import{backfillAggregateIndexes as si,backfillRankIndexes as ci,backfillSearchIndexes as ai}from"./backfillAggregateIndexes-Dw4Azd33.mjs";import{appendCdcChange as Fn,readCdcDocAtOrBefore as Ln}from"./CDC_LOG_TABLE-DsCz-DAV.mjs";import{CDC_LOG_TABLE as li,applyCdcChanges as ui,bumpCdcEpoch as fi,cdcCanVouchFor as hi,cdcForkedError as wi,cdcSeqLeavingRows as pi,cdcTouchesTables as gi,cdcTrimmedError as yi,compactCdcDocs as $i,cursorBelowRetainedFloor as Ei,minCdcReplayableSeq as mi,minCdcSeq as Si,readCdcChangeKeys as _i,readCdcChanges as Ri,readCdcCursor as Ti,readCdcEpoch as vi,trimCdcChanges as Ai}from"./CDC_LOG_TABLE-DsCz-DAV.mjs";import{allocateCommitSeq as qn,COMMIT_SEQ_FIELD as Wn}from"./COMMIT_SEQ_FIELD-BcUO15fR.mjs";import{createCompanionSync as Bn}from"./createCompanionSync-DhYLePyV.mjs";import{isMemoryTable as Mt}from"./clearMemoryTables-Lu0S2GOb.mjs";import{computeRankPage as Dt}from"./computeRankPage-DLSi_oBt.mjs";import{SCAN_DEP as U}from"./SCAN_DEP-D7qE3iUe.mjs";import{runSql as fe,runDrizzle as G}from"./runDrizzle-B2GG3IJa.mjs";import{p as Pn,j as dt,D as re,r as ve,k as ae,b as Pe,A as rt,a as Ue,m as le,e as ue,s as Un,t as rn,i as On,q as kt,h as sn,g as Hn}from"./do-sql-DqU-17Fs.mjs";import{renderSql as cn,unionAll as ht,WORKERD_SQLITE_LIMITS as an,sqliteInList as Gn}from"./WORKERD_SQLITE_LIMITS-BdNnnMj0.mjs";import{coveringGeohashes as jn,boundingBoxGeohashes as Kn,haversineMeters as Nn,pointInBoundingBox as Qn}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{NotFoundError as Vn}from"./NotFoundError-BhF7FeFr.mjs";import{resolvePatch as Jn,assertPatchAllowed as zn,operatorFields as Yn,readPatchField as Ft}from"./assertPatchAllowed-CA_H466g.mjs";import{tiebreakDirectionFor as Xn,encodeCursor as je,nullsOrderSuffix as Zn,normalizeOrderKeys as Lt,uniqueIndexFields as eo,buildSeekWhere as to,decodeCursor as qt,buildSeekBeforeWhere as no,softDeleteScope as Te,applySelect as Wt}from"./CURSOR_PREFIX-6offuG6M.mjs";import{rankTableName as Bt,sortColumnName as Pt,resolveRankPartition as oo,encodePartitionKey as ro,RANK_TIEBREAK as io,rankPivotConditionSql as so}from"./RANK_TIEBREAK-D3ye2GsL.mjs";import{UNVOUCHABLE_DEP as Ut}from"./UNVOUCHABLE_DEP-C68htACn.mjs";import{indexKeysForRow as co,buildIndexRange as ao}from"./buildIndexRange-DQ3eWAGd.mjs";import{r as Ke,j as Ae,c as Y,t as Ne,i as Ot}from"./where-sql-DO1vOrhc.mjs";import{serializeSqlValue as Ie}from"./serializeSqlValue-DeoBMpZ2.mjs";import{quoteIdentifier as Ce}from"./quoteIdentifier-CObIFRhb.mjs";import{whereOfFilter as lo,isPushableWhere as uo}from"./isPushableWhere-BeYAOjUb.mjs";import{deriveRelationEdges as fo,findRelated as ho}from"./RELATED_DEFAULT_LIMIT-CVqN4JEu.mjs";import{assertFlatPredicate as it,resolveRelationPredicates as wo,composeReadPredicate as po}from"./DEFAULT_MAX_RELATION_KEYS-BYfAkNAH.mjs";import{describeRelationWrites as go}from"./describeRelationWrites-omar6-u9.mjs";import{runRowValidators as st,resolveWith as Ht,relationHooks as Gt,applyOnDelete as yo,fanOutScalarCounts as $o}from"./applyOnDelete-BwxDC4lU.mjs";import{guardWriter as Eo}from"./RLS_UNWRAP_SYMBOL-J1tiBtRj.mjs";import{mayHoldProjectedValue as mo}from"./BIGINT_KEY_DIGITS-DE6yshOt.mjs";import{createSystemReader as So}from"./createSystemReader-DcDLFfC-.mjs";import{ConflictError as se}from"./ConflictError-C8GtJmjS.mjs";import{hasTrigger as jt,runTriggers as _o}from"./hasTrigger-CjlwI4le.mjs";import{advanceClientWatermark as Ci,migrateClientWatermark as xi,readClientWatermark as bi}from"./CLIENT_WATERMARK_TABLE-_CkdMnT2.mjs";import{IDEMPOTENCY_TABLE as Di,readIdempotent as ki,trimIdempotent as Fi,writeIdempotent as Li}from"./IDEMPOTENCY_TABLE-CymJf4r0.mjs";import{runShardMigrations as Wi}from"./runShardMigrations-BeqUbznb.mjs";import{selectShapeMembers as Pi,selectShapeRows as Ui}from"./selectShapeMembers-B1MIaRkE.mjs";const Ro=n=>{const i=atob(n),o=Uint8Array.from(i,c=>c.codePointAt(0)??0);return new TextDecoder().decode(o)},To=()=>new $("BAD_REQUEST","invalid cursor"),Kt=16,Nt=8,V=1024,wt=(n,i)=>i.query(n),vo=(n,i)=>{if(n.length===0)return 0;let o=0;for(const[c,s]of i.entries()){const w=c===i.length-1;let _=0;for(const S of n)(w?S.startsWith(s):S===s)&&(_+=1);if(_===0)return 0;o+=_}return o},Ao=(n,i)=>{if(!i)return{exact:!0,lower:n,upper:n};const o=[...n].at(-1)??"",c=(o.codePointAt(0)??0)+1;if(c>=55296&&c<=57343||c>1114111)return{exact:!0,lower:n,upper:n};const s=n.slice(0,n.length-o.length);return{exact:!1,lower:n,upper:s+String.fromCodePoint(c)}},Io=(n,i,o)=>{const c={eq:(s,w)=>{if(!n.definition.filterFields?.includes(s))throw new $("INTERNAL",`field "${s}" is not a filter field of search index "${n.indexName}" on table "${i}"`);if(n.filters.length>=Nt)throw new $("BAD_REQUEST",`search index "${n.indexName}" on table "${i}": at most ${String(Nt)} .eq() filters are supported per search query`);return n.filters.push({field:s,value:w}),c},search:(s,w)=>{const _=n;if(s!==_.definition.field)throw new $("INTERNAL",`search index "${_.indexName}" on table "${i}" indexes "${_.definition.field}", not "${s}"`);const S=wt(w,o).length;if(S>Kt)throw new $("BAD_REQUEST",`search index "${_.indexName}" on table "${i}": at most ${String(Kt)} search terms are supported (got ${String(S)})`);return _.field=s,_.query=w,_.hasQuery=!0,c}};return c},Co=n=>{if(n.length>V)throw new $("BAD_REQUEST",`more than ${String(V)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},xo=n=>Math.min(n.offset+n.numItems+1,V),bo=n=>btoa(`search:${String(n)}`),Mo=n=>{let i;try{i=Ro(n)}catch{return}if(!i.startsWith("search:"))return;const o=Number(i.slice(7));return Number.isInteger(o)&&o>=0?o:void 0},Do=n=>{if(typeof n.endCursor=="string")throw new $("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");if(!Number.isFinite(n.numItems))throw new $("BAD_REQUEST",`search pagination needs a finite numItems, got ${String(n.numItems)}`);const i=Math.max(0,Math.floor(n.numItems)),o=n.cursor?Mo(n.cursor):0;if(o===void 0)throw To();if(o+i>=V)throw new $("BAD_REQUEST",`search pagination reaches the ${String(V)}-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,V-o-1))} or fewer, or narrow the query or the filters instead`);return{numItems:i,offset:o}},ko=(n,i)=>{const o=i.offset+i.numItems,c=i.numItems>0&&n.length>o;return{continueCursor:c?bo(o):null,isDone:!c,page:n.slice(i.offset,o)}},Fo=n=>{if(n===void 0)return V+1;if(!Number.isFinite(n))return V;const i=Math.max(0,Math.floor(n));if(i>V)throw new $("BAD_REQUEST",`search returns at most ${String(V)} documents (asked for ${String(i)}) — narrow the query or paginate instead`);return i},Lo=32,qo=1024,dn=(n,i,o,c)=>{const s=`SELECT id, _creationTime, ${Ce(re)} FROM ${Ce(n)}`,w=`ORDER BY ${o}${c===void 0?"":` LIMIT ${String(c)}`}`;return i===void 0?Ke(`${s} ${w}`):Ae(`${s} WHERE `,i,` ${w}`)},Qe={fieldRef:n=>Ke(dt(n)),rangeTypeGuard:(n,i)=>Ke(Pn(n,i)),serialize:Ie},Wo=n=>n===void 0?"":Zn(n==="first"),ln=n=>{const i=n.map(o=>`${dt(o.field)} ${o.direction==="desc"?"DESC":"ASC"}${Wo(o.nulls)}`);return n.some(o=>o.field==="_id"||o.field==="id")||i.push(`${dt("id")} ${Xn(n)==="desc"?"DESC":"ASC"}`),i.join(", ")},Bo={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},un=n=>new Set(n.sqlConditions.filter(i=>i.comparator==="=").map(i=>i.field)),Po=n=>{const i=un(n);let o=0;for(;o<n.indexFields.length&&i.has(n.indexFields[o]??"");)o+=1;return n.indexFields.slice(o)},Uo=(n,i)=>{const o=n.order,c=Po(n),{shape:s}=i;return c.length>0?Lt(c.map(w=>({[w]:o})),s,{pinned:un(n),uniqueBy:eo(i.indexes,s)}):Lt([{_creationTime:o}],s)},Oo=(n,i,o,c)=>{const s=n.sqlConditions.map(w=>({[w.field]:{[Bo[w.comparator]??"eq"]:w.value}}));if(o&&s.push(to(i,qt(o))),c&&s.push(no(i,qt(c))),s.length!==0)return s.length===1?s[0]:{AND:s}},Ho=n=>{if(n.want!==void 0)return n.selective?Math.max(n.want,Lo):n.want},lt=(n,i,o,c,s,w,_)=>{const S=Uo(c,o),b=ln(S),y=[],{filters:k,want:C}=w;let A=w.cursor??void 0,I=Ho(w);if(C===0)return{documents:y,orderKeys:S};for(;;){const q=Y(Oo(c,S,A,w.endCursor),Qe,Ne),F=dn(i,s&&q?Ae(q," AND ",s):s??q,b,I),L=fe(n,F.text,...F.params).toArray();let W={};_(L.length);for(const O of L)if(W=ve(O),k.every(we=>we(W))&&y.push(W)===C)return{documents:y,orderKeys:S};if(I===void 0||L.length<I)return{documents:y,orderKeys:S};A=je(W,S),I=Math.max(I,Math.min(I*2,qo))}},Go=(n,i,o,c,s,w,_,S)=>{const b=Math.max(0,Math.floor(s.numItems));if(typeof s.endCursor=="string"){const{documents:q,orderKeys:F}=lt(n,i,o,c,w,{cursor:s.cursor,endCursor:s.endCursor,filters:_.all,selective:_.selective,want:void 0},S),L=q.length>=2?q[Math.floor(q.length/2)-1]:void 0;return{continueCursor:s.endCursor,isDone:!0,page:q,splitCursor:L?je(L,F):null}}const{documents:y,orderKeys:k}=lt(n,i,o,c,w,{cursor:s.cursor,filters:_.all,selective:_.selective,want:b+1},S),C=y.length>b,A=C?y.slice(0,b):y,I=A.at(-1);return{continueCursor:C&&I?je(I,k):null,isDone:!C,page:A}},Ve=n=>{const i=new Map;return o=>{const c=i.get(o);if(c!==void 0)return c;const s=n(Ce(o));return i.set(o,s),s}},he=Ce(re),jo=Ve(n=>`INSERT INTO ${n} (id, _creationTime, ${he}) VALUES (?, ?, ?)`),Qt=Ve(n=>`UPDATE ${n} SET ${he} = ? WHERE id = ? AND ${he} = ?`),Ko=Ve(n=>`UPDATE ${n} SET _creationTime = ?, ${he} = ? WHERE id = ? AND ${he} = ?`),No=Ve(n=>`DELETE FROM ${n} WHERE id = ? AND ${he} = ?`),Qo="SELECT changes() AS changed",Vt=new Map,Vo="",Jo=n=>{const i=JSON.stringify(n),o=Vt.get(i);if(o!==void 0)return o;const c=n.map(w=>a`SELECT ${a.raw(`'${w.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${a.identifier(re)} FROM ${a.identifier(w)} WHERE id = ${Vo}`),{sql:s}=cn("sqlite",a`${ht(c)} LIMIT 1`);return Vt.set(i,s),s},zo=(n,i)=>i.map(()=>n),Yo=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,Xo=n=>{if(!Yo.test(n))throw new $("INTERNAL",`invalid clientId ${JSON.stringify(n)}: a client-supplied row id must be a UUID`)},Jt=50,fn=500,Oe=Math.floor(an.boundParams/3),Re=an.boundParams,Zo=128,de=(n,i,o)=>{const c=i??fn;if(n>c)throw new $("BATCH_LIMIT_EXCEEDED",`${o}: batch of ${String(n)} exceeds the limit of ${String(c)} (raise options.limit or chunk the call)`,{status:400})},er=n=>{const i={eq:(o,c)=>(n.sqlConditions.push({comparator:"=",field:o,value:c}),i),gt:(o,c)=>(n.sqlConditions.push({comparator:">",field:o,value:c}),i),gte:(o,c)=>(n.sqlConditions.push({comparator:">=",field:o,value:c}),i),lt:(o,c)=>(n.sqlConditions.push({comparator:"<",field:o,value:c}),i),lte:(o,c)=>(n.sqlConditions.push({comparator:"<=",field:o,value:c}),i)};return i},tr=n=>Math.max(n,V),hn=(n,i)=>{const o=n.filters.map(c=>a`${ue(c.field)} = ${Ie(c.value)}`);return i&&o.push(i),o},nr=(n,i,o,c,s)=>{const w=wt(o.query,ft(o.definition.language));if(w.length===0)return[];const _=Tn(i,o.indexName),S=`${_}__vocab`,b=w.length-1,y=w.map((F,L)=>{const W=Ao(F,L===b),O=W.exact?a`${a.identifier("term")} = ${W.lower}`:a`${a.identifier("term")} >= ${W.lower} AND ${a.identifier("term")} < ${W.upper}`;return a`SELECT ${a.identifier("doc")}, ${a.raw(String(L))} AS ${a.identifier("__term__")}, COUNT(*) AS ${a.identifier("__n__")} FROM ${a.identifier(S)} WHERE ${O} GROUP BY ${a.identifier("doc")}`}),k=w.map((F,L)=>a`SUM(CASE WHEN u.${a.identifier("__term__")} = ${a.raw(String(L))} THEN u.${a.identifier("__n__")} ELSE 0 END)`),C=a`SELECT f.${a.identifier(We)} AS ${a.identifier(We)}, ${a.join(k,a` + `)} AS ${a.identifier("__score__")} FROM (${ht(y)}) u JOIN ${a.identifier(_)} f ON f.rowid = u.${a.identifier("doc")} GROUP BY f.${a.identifier(We)} HAVING ${a.join(k.map(F=>a`${F} > 0`),a` AND `)}`,A=hn(o,s);let I=a`SELECT m.id, m._creationTime, m.${a.identifier(re)}, s.${a.identifier("__score__")} AS ${a.identifier("__score__")} FROM (${C}) s JOIN ${a.identifier(i)} m ON m.id = s.${a.identifier(We)}`;A.length>0&&(I=a`${I} WHERE ${a.join(A,a` AND `)}`),I=a`${I} ORDER BY s.${a.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${a.raw(String(c))}`;const q=[];for(const F of G(n,I)){const L=sn(F);if(L){const W=F.__score__;q.push({document:L,score:typeof W=="number"?W:Number(W??0)})}}return q},or=(n,i,o,c,s)=>{const w=ft(o.definition.language),_=wt(o.query,w);if(_.length===0)return[];const S=hn(o,s);let b=a`SELECT id, _creationTime, ${a.identifier(re)} FROM ${a.identifier(i)}`;S.length>0&&(b=a`${b} WHERE ${a.join(S,a` AND `)}`),b=a`${b} ORDER BY _creationTime DESC, id ASC LIMIT ${a.raw(String(tr(c)))}`;const y=G(n,b).toArray(),k=[];for(const C of y){const A=sn(C);if(!A)continue;const I=vo(vn(A,o.definition),_);I>0&&k.push({creationTime:typeof A._creationTime=="number"?A._creationTime:0,doc:A,id:typeof A._id=="string"?A._id:"",score:I})}return k.sort((C,A)=>A.score-C.score||A.creationTime-C.creationTime||C.id.localeCompare(A.id)),k.slice(0,c).map(C=>({document:C.doc,score:C.score}))},ct=(n,i,o,c)=>{if(!Number.isFinite(n.lat)||n.lat<-90||n.lat>90||!Number.isFinite(n.lng)||n.lng<-180||n.lng>180)throw new $("BAD_REQUEST",`geo index "${c}" on table "${o}": ${i} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},rr=(n,i)=>{const o=n,c={near:(s,w)=>{if(o.within)throw new $("INTERNAL",`geo index "${o.indexName}" on table "${i}": call .near() or .within(), not both`);if(ct(s,".near() point",i,o.indexName),!Number.isFinite(w)||w<=0)throw new $("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:s.lat,lng:s.lng},radiusMeters:w},c},within:s=>{if(o.near)throw new $("INTERNAL",`geo index "${o.indexName}" on table "${i}": call .near() or .within(), not both`);if(ct(s.sw,".within() sw corner",i,o.indexName),ct(s.ne,".within() ne corner",i,o.indexName),s.sw.lat>s.ne.lat)throw new $("BAD_REQUEST",`geo index "${o.indexName}" on table "${i}": .within() corners are transposed (sw.lat > ne.lat)`);if(s.sw.lng>s.ne.lng)throw new $("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:s.ne.lat,lng:s.ne.lng},sw:{lat:s.sw.lat,lng:s.sw.lng}},c}};return c},ir=(n,i)=>{const o=n[i];if(o===null||typeof o!="object")return;const{lat:c,lng:s}=o;return typeof c=="number"&&typeof s=="number"?{lat:c,lng:s}:void 0},sr=(n,i)=>{const o=ir(n,i.definition.field);if(!o)return;const c=typeof n._creationTime=="number"?n._creationTime:0;if(i.near){const s=Nn(i.near.point,o);return s<=i.near.radiusMeters?{creationTime:c,distance:s}:void 0}return Qn(o,i.within)?{creationTime:c,distance:0}:void 0},cr=(n,i,o,c)=>{if(!o.near&&!o.within)throw new $("INTERNAL",`geo index "${o.indexName}" on table "${i}": call .near(point, radius) or .within(box)`);const s=o.near?jn(o.near.point,o.near.radiusMeters):Kn(o.within),w=Hn(i,o.indexName),_=s.map(C=>a`(g.${a.identifier("__geohash__")} >= ${C} AND g.${a.identifier("__geohash__")} < ${`${C}{`})`),S=[a`(${a.join(_,a` OR `)})`];c&&S.push(c);const b=a`SELECT m.id, m._creationTime, m.${a.identifier(re)} FROM ${a.identifier(w)} g JOIN ${a.identifier(i)} m ON m.id = g.${a.identifier("__id__")} WHERE ${a.join(S,a` AND `)}`,y=G(n,b).toArray(),k=[];for(const C of y){const A=ve(C),I=A?sr(A,o):void 0;A&&I&&k.push({creationTime:I.creationTime,distance:I.distance,doc:A})}return k.sort((C,A)=>C.distance-A.distance||A.creationTime-C.creationTime),k},wn=(n,i,o,c)=>{const s=[];for(const w of n)if(i.every(_=>_(c(w)))&&(s.push(w),typeof o=="number"&&s.length>=o))break;return s},ar=(n,i,o,c,s,w=()=>{})=>{const _=o.within!==void 0,S=cr(n,i,o,s).map(b=>({distanceMeters:_?null:b.distance,document:b.doc}));return w(S.length),typeof c=="number"?S.slice(0,Math.max(0,Math.floor(c))):S},zt=(n,i,o,c,s,w,_=()=>{})=>{const{geo:S}=o;if(!S)throw new $("INTERNAL","runGeoTerminalScored called without a staged geo query");const b=s.length>0,y=ar(n,i,S,b?void 0:w,c,_);return b?wn(y,s,w,k=>k.document):y},Yt=(n,i,o)=>{const c=n.shape[i];if(c!==void 0&&mo(c))throw new $("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)`)},dr=n=>{let i=0;const o=[],c={...Qe,relationExists:s=>{const{childWhere:w,negated:_,parentTable:S,relation:b}=s,y=`__rel_${String(i)}`,k=o.at(-1)??S;i+=1,n(b.table,U);const C=b.kind==="one"?b.field:b.references,A=b.kind==="one"?b.references:b.field,I=Ke(`${kt(y,A)} = ${kt(k,C)}`);o.push(y);const q=Y(w,c,Ne);o.pop();const F=q===void 0?I:Ae(I," AND ",q),L=Ae("EXISTS (SELECT 1 FROM ",Ot(b.table)," AS ",Ot(y)," WHERE ",F,")");return _?Ae("NOT ",L):L}};return c};class lr extends ${constructor(i="unique() found more than one matching document"){super("NOT_UNIQUE",i,{name:"NotUniqueError"})}}const ur=/\s/u,fr=String.fromCodePoint(0),Xt=(n,i,o)=>{if(!n.tables[i])throw new $("INTERNAL",`unknown table: ${i}`);return typeof o!="string"||o.length===0||ur.test(o)||o.includes(fr)?null:o},pn=(n,i,o,c=()=>{},s=()=>{},w=()=>{},_)=>{const S=i.tables[o];if(!S)throw new $("INTERNAL",`unknown table: ${o}`);const b=Te(S.softDeleteMode,void 0),y=_??{indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[],verifyFilters:[]},k=()=>{const p=K(b,y.pushedWhere);return p?Y(p,le):void 0},C=()=>{const p=K(b,y.pushedWhere);return p?Y(p,Qe,Ne):void 0},A=()=>[...y.inMemoryFilters,...y.verifyFilters];let I=0;const q=p=>{const{search:x}=y;if(!x)throw new $("INTERNAL","runSearchFetch called without a staged search");Dn(n,o,S);const D=y.inMemoryFilters.length>0,M=Fo(D?void 0:p),N=On(n);if(N&&!kn(n,o,x.definition))throw new $("SEARCH_INDEX_BUILDING",`search index "${x.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 oe=k(),J=N?nr(n,o,x,M,oe):or(n,o,x,M,oe);!D&&p===void 0&&Co(J);const pe=A();return I=J.length,pe.length>0?wn(J,pe,p,xe=>xe.document):J},F=p=>q(p).map(x=>x.document),L=p=>{const x=Do(p);return ko(F(xo(x)),x)},W=()=>{if(y.search||y.geo||y.indexName===void 0){s(void 0);return}s(ao(o,y.indexName,y.indexFields,y.sqlConditions,Ie))},O=p=>{W();let x=0;const D=(()=>{if(y.search){const M=F(p);return x=I,M}return y.geo?zt(n,o,y,k(),A(),p,M=>{x=M}).map(M=>M.document):lt(n,o,S,y,C(),{filters:A(),selective:y.inMemoryFilters.length>0,want:p===void 0?void 0:Math.max(0,Math.floor(p))},M=>{x+=M}).documents})();return w(Math.max(x,D.length)),D},we=()=>{if(!y.search&&!y.geo)throw new $("INTERNAL",`ctx.db.query("${o}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);W();let p=0;const x=(()=>{if(y.search){const D=q(void 0);return p=I,D}return zt(n,o,y,k(),A(),void 0,D=>{p=D})})();return w(Math.max(p,x.length)),x},ne={async*[Symbol.asyncIterator](){const p=pn(n,i,o,c,s,w,{...y,indexFields:[...y.indexFields],inMemoryFilters:[...y.inMemoryFilters],sqlConditions:[...y.sqlConditions],verifyFilters:[...y.verifyFilters]});if(y.search){yield*await p.collect();return}let x;for(;;){const D=await p.paginate({cursor:x??null,numItems:Zo});if(yield*D.page,D.isDone||D.continueCursor===null)return;x=D.continueCursor}},async collect(){return O(void 0)},async collectWithScores(){return we()},filter(p){const x=lo(p);return x!==void 0&&uo(x,S.shape)?(y.pushedWhere=K(y.pushedWhere,x),y.verifyFilters.push(p)):y.inMemoryFilters.push(p),ne},async first(){return O(1)[0]??null},order(p){return y.order=p==="desc"?"desc":"asc",ne},async paginate(p){let x=0;if(W(),y.search){const M=L(p);return w(M.page.length),M}if(y.geo)throw new $("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const D=Go(n,o,S,y,p,C(),{all:A(),selective:y.inMemoryFilters.length>0},M=>{x+=M});return w(Math.max(x,D.page.length)),D},async take(p){return O(p)},async unique(){const p=O(2);if(p.length>1)throw new lr(`unique() on table "${o}" matched ${String(p.length)} documents; expected at most one`);return p[0]??null},withGeoIndex(p,x){const D=(S.geoIndexes??[]).find(N=>N.name===p);if(!D)throw new $("INTERNAL",`unknown geo index "${p}" on table "${o}"`);c(o,p,"geo");const M={definition:D,indexName:p};if(y.geo=M,x(rr(M,o)),!M.near&&!M.within)throw new $("INTERNAL",`geo index "${p}" on table "${o}" requires a .near(point, radius) or .within(box) call`);return ne},withIndex(p,x){const D=S.indexes.find(M=>M.name===p);if(!D)throw new $("INTERNAL",`unknown index "${p}" on table "${o}"`);return c(o,p,"index"),y.indexName=p,y.indexFields=D.fields,x&&x(er(y)),ne},withSearchIndex(p,x){const D=(S.searchIndexes??[]).find(N=>N.name===p);if(!D)throw new $("INTERNAL",`unknown search index "${p}" on table "${o}"`);c(o,p,"search");const M={definition:D,field:D.field,filters:[],hasQuery:!1,indexName:p,query:""};if(y.search=M,x(Io(M,o,ft(D.language))),!M.hasQuery)throw new $("INTERNAL",`search index "${p}" on table "${o}" requires a .search(field, query) call`);return ne}};return ne},Zt=(n,i,o)=>{const c={...i};for(const[s,w]of rn(n)){if(w.serverDefault){c[s]=w.serverDefault({auth:o});continue}c[s]===void 0&&(w.defaultFn?c[s]=w.defaultFn():"defaultValue"in w&&(c[s]=w.defaultValue))}return c},at=(n,i,o,c)=>{const s=o;for(const[w,_]of rn(n)){if(_.serverDefault){w in i&&(s[w]=_.serverDefault({auth:c}));continue}_.onUpdateFn&&!(w in i)&&(s[w]=_.onUpdateFn())}},en=5,tn=(n,i)=>{for(const o of Object.keys(i))if(i[o]===void 0)throw new $("INTERNAL",`Cannot ${n} field '${o}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},nn=["_commitSeq","_creationTime","_id"],He=n=>nn.some(i=>i in n)?Object.fromEntries(Object.entries(n).filter(([i])=>!nn.includes(i))):n,hr=/unique constraint failed/i,wr=n=>n instanceof Error&&hr.test(n.message),pr=/string or blob too big/iu,gr=(n,i)=>{if(!(!(n instanceof Error)||!pr.test(n.message)))throw new $("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.`)},ut=(n,i,o,c)=>{try{fe(n,o,...c)}catch(s){throw wr(s)?new se(`unique constraint violation on "${i}"`,"unique"):(gr(s,i),s)}},Ge=(n,i,o,c)=>{if(ut(n,i,o,c),fe(n,Qo).one().changed===0)throw new se(`optimistic concurrency conflict on "${i}" — the row changed during this mutation; refetch and retry`,"occ")},on=(n,i,o,c,s,w,_)=>{const S=[];for(let C=0;C<o.length+1;C+=1){const A=o[C],I=c[C],q=I?.direction==="desc"?"desc":"asc",F=A===void 0||I===void 0?a`${a.identifier(io)} < ${_}`:so(A,w[C],q,!1);if(F===void 0)continue;const L=[];for(let O=0;O<C;O+=1)L.push(a`${a.identifier(o[O])} IS ${w[O]}`);L.push(F);const[W]=L;S.push(L.length===1&&W!==void 0?W:a`(${a.join(L,a` AND `)})`)}const b=S.length>0?a.join(S,a` OR `):a`1 = 0`,y=G(n,a`SELECT COUNT(*) AS c FROM ${a.identifier(i)} WHERE ${a.identifier("__partition__")} = ${s} AND (${b})`).one(),k=G(n,a`SELECT COUNT(*) AS c FROM ${a.identifier(i)} WHERE ${a.identifier("__partition__")} = ${s}`).one();return{before:y.c,total:k.c}},yr=n=>{const i=new Map;for(const[c,s]of Object.entries(n.tables))for(const w of Object.values(s.relationMap??{}))w.kind==="one"&&(w.onDelete==="cascade"||w.onDelete==="set null")&&i.set(w.table,[...i.get(w.table)??[],{holder:c,op:w.onDelete==="cascade"?"delete":"update"}]);const o=c=>{const s=new Set,w=[c];for(let _=w.pop();_!==void 0;_=w.pop())for(const{holder:S,op:b}of i.get(_)??[]){if(S===c||jt(n,S,b))return!0;s.has(S)||(s.add(S),w.push(S))}return!1};return new Set(Object.entries(n.tables).filter(([c,s])=>s.shardMode?.kind==="global"||jt(n,c,"delete")||o(c)).map(([c])=>c))},$r=n=>{const i=new Map;for(const[o,c]of Object.entries(n.tables))c.softDeleteMode&&i.set(o,c.softDeleteMode.field);return i},oi=n=>{const{baselineSeq:i,onStalePatchDropped:o}=n,{sql:c}=n,{schema:s}=n,w=n.broadcast??(()=>{}),_=fo(s),S=go(s,n.inTransaction),b=yr(s),y=$r(s);let k;const C=()=>n.inTransaction?.()===!0,A=e=>s.tables[e]?.commitOrderedMode!==!0?{}:((k===void 0||!C())&&(k=qn(c)),{[Wn]:k}),I=(e,...t)=>{const r=s.tables[e]?.indexes;if(!r||r.length===0)return;const u=[];for(const h of t)h&&u.push(...co(r,h,Ie));return u.length>0?u:void 0},{headroom:q}=n;let F=!1;const L=async e=>{const t=F;F=!0;try{return await e()}finally{F=t}},W=n.onRead??(()=>{}),O=e=>{Mt(s.tables[e])&&W(Ut,Ut)},we=n.onReadRange??(e=>{W(e.table,U)}),ne=e=>{O(e.table),we(e)},p=(e,t)=>{t!==void 0&&t!==U&&!F&&q?.recordRead(1),O(e),W(e,t)},x=n.onIndexUse??(()=>{}),D=n.onWrite??(()=>{}),M=e=>{F||q?.recordWrite(e)},N=async e=>{M(e.doc),await D(e)},{cache:oe}=n,J=n.clock??(()=>Date.now()),pe=n.idGenerator??(()=>crypto.randomUUID()),xe=n.scheduler??In,{globalDb:ge}=n,ye=n.auth??{identity:null,userId:null},pt=n.cdc??!1,Je=xe,gn=So({scheduler:typeof Je.list=="function"&&typeof Je.get=="function"?Je:void 0,storage:n.storage}),$e=(e,t,r,u)=>{pt&&!Mt(s.tables[e])&&Fn(c,J(),e,t,r,u)},gt=(e,t,r,u)=>{const h=s.tables[e];if(h?.dropStalePatchesMode!==!0||!pt)return!1;const f=i?.();if(f===void 0)return!1;const d=Ln(c,e,t,f);if(d===void 0)return!1;const l=Yn(h,r);return Object.keys(He(r)).some(g=>!l.has(g)&&bt(Ft(d,g))!==bt(Ft(u,g)))},ie=e=>s.tables[e]?.shardMode?.kind==="global",yt=(e,t)=>{if(ie(e)){if(!ge)throw new $("INTERNAL",`cross-backend ${t} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return ge}return B},ze=e=>yt(e,"cascade"),j=(e,t)=>{if(ie(e)){if(!ge)throw new $("INTERNAL",`${t} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return ge}},$t=async(e,t,r,u,h)=>{h&&M(r);const f=await e.insert(t,r,u);return w({key:f,op:"insert",row:{...r,_id:f},table:t}),f},Ye=(e,t)=>yt(e,"relation load").findMany(e,t),Et=(e,t)=>(ie(e)&&p(e,U),Ye(e,t)),yn=e=>!ie(e.table),mt=n.relationExistsPushDown??"auto",St=mt!=="never",{maxRelationKeys:_t}=n,be=(e,t,r)=>wo(e,{fetcher:Et,maxRelationKeys:_t,relationBaseWhere:r,schema:s,tableName:t}),Rt=async(e,t,r,u)=>{const h=j(e,"relation grouped count");if(h)return p(e,U),$o((T,H)=>h.count(T,H),e,t,r,u);const f=s.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);p(e,U);const d=Te(f.softDeleteMode,void 0),l={[t]:{in:r}},g=K(K(l,u),d),v=await be(g,e,void 0),E=Y(v,le),R=ue(t);let m=a`SELECT ${R} AS __fk__, COUNT(*) AS count FROM ${a.identifier(e)}`;E&&(m=a`${m} WHERE ${E}`),m=a`${m} GROUP BY ${R}`;const P=G(c,m).toArray();return new Map(P.map(T=>[T.__fk__,T.count]))};let Me=0;const Tt=new Set;for(const[e,t]of Object.entries(s.tables))for(const r of Object.values(t.triggerMap??{}))Tt.add(`${e} ${r.timing} ${r.op}`);const X=(e,t,r)=>Tt.has(`${e} ${t} ${r}`),Z=async(e,t,r)=>{if(Me+=1,Me>Jt)throw Me-=1,new se(`trigger recursion exceeded ${String(Jt)} levels on "${r.table}" — check for a self-triggering write`,"trigger");try{await _o({ctx:_n,event:r,op:t,schema:s,tableName:r.table,timing:e})}finally{Me-=1}},{ensureBackfilledForTable:Ee,ensureBackfilledIndex:Xe,ensureRankBackfilled:Ze,ensureRankBackfilledForTable:me,syncAggregates:De,syncCompanionsForInsert:vt,syncGeo:ke,syncRanks:Se,syncSearch:Fe}=Bn({broadcast:w,indexKeysFor:(e,t)=>I(e,t),invalidateCache:(e,t,r)=>oe?.invalidate(e,t,I(e,r)),recordCdc:$e,schema:s,sql:c}),At=(e,t,r)=>{const{shardMode:u}=t;if(u?.kind==="shardBy"&&!(u.field!==void 0&&(r.partitionBy??[]).includes(u.field)))throw Object.assign(new Error(`rank index "${r.name}" on "${e}" partitions across shards (shard key "${u.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})},It=e=>Object.entries(s.tables).filter(([,t])=>t.shardMode?.kind!=="global").map(([t])=>t).filter(t=>e===void 0||t===e),_e=e=>e===void 0||ie(e)?ge:void 0,ee=(e,t)=>{const r=It(t);for(let u=0;u<r.length;u+=Re){const h=r.slice(u,u+Re),[f]=fe(c,Jo(h),...zo(e,h)).toArray();if(!f)continue;const d=f.__t__,l=ve(f);if(typeof d!="string"||!l)return;const g=f[re];return{docJson:typeof g=="string"?g:ae(g??{}),row:l,tableName:d}}},$n=(e,t)=>{const r=[...new Set(e)],u=new Map;if(r.length===0)return u;const h=It(t);for(let f=0;f<h.length;f+=Re){const d=h.slice(f,f+Re),l=Math.floor(Re/d.length),g=Gn(a`${a.identifier("id")}`,r,!1,l),v=d.map(E=>a`SELECT ${a.raw(`'${E.replaceAll("'","''")}'`)} AS __t__, id FROM ${a.identifier(E)} WHERE ${g}`);for(const E of G(c,ht(v))){const{id:R,__t__:m}=E;typeof m=="string"&&typeof R=="string"&&u.set(R,m)}}return u},Ct={assertRankPartitionLocal:At,ensureRankBackfilled:Ze,onRead:p,rowToDocument:ve,schema:s,sql:c},En=(e,t,r)=>{const u=Y(r,le);return u===void 0||G(c,a`SELECT 1 FROM ${a.identifier(e)} WHERE ${a.identifier("id")} = ${t} AND ${u}`).toArray().length>0},mn=(e,t,r,u)=>gt(e,t,r,u)?(o?.({fields:Object.keys(He(r)),id:t,table:e}),!0):!1,Sn=async(e,t,r,u,h)=>{const f=ee(t,e);if(!f)return{applied:!1,doc:null};if(p(e,t),!En(e,t,r.where)||mn(e,t,r.patch,f.row))return{applied:!1,doc:f.row};try{await h(r.patch)}catch(d){if(d instanceof se&&d.kind==="occ"&&u)return;throw d}return{applied:!0,doc:ee(t,e)?.row??null}},xt=async(e,t,r,u)=>{const{fetchLimit:h,limit:f,orderKeys:d,predicate:l}=await po(t,r,{canPushExists:St?yn:void 0,existsPushMode:mt==="always"?"always":"auto",fetcher:Et,maxRelationKeys:_t,schema:s,tableName:e}),g=St?dr(u):Qe,v=Y(l,g,Ne),E=dn(e,v,ln(d),h);return{limit:f,orderKeys:d,statement:E}},B={system:gn,async aggregate(e,t){const r=j(e,"aggregate");if(r)return p(e,U),r.aggregate(e,t);const u=s.tables[e];if(!u)throw new $("INTERNAL",`unknown table: ${e}`);if(Be(t.op),t.op==="count")return B.count(e,{baseWhere:t.baseWhere,relationBaseWhere:t.relationBaseWhere,restrictsCounts:t.restrictsCounts,where:t.where});if(!t.field)throw new $("INTERNAL",`aggregate(${e}, { op: "${t.op}" }): "field" is required for non-count reducers`);p(e,U);const h=Te(u.softDeleteMode,void 0),f=K(K(t.baseWhere,t.where),h),d=await be(f,e,t.relationBaseWhere),l=d!==f;if(u.aggregateIndexes&&!t.baseWhere&&!l){const T=Mn(u.aggregateIndexes,t.op,t.field,t.where);if(T){Xe(e,T.index);const H=tt(T.index.by??[],T.key),te=et(e,T.index.name),z=G(c,a`SELECT ${Pe} AS value, ${rt} AS count FROM ${a.identifier(te)} WHERE ${Ue} = ${H}`).toArray()[0];return nt(t.op,z)}}Yt(u,t.field,`aggregate(${e}, { op: "${t.op}", field: "${t.field}" })`);const g=Y(d,le),v=Be(t.op),E=ue(t.field);let R=a`SELECT ${a.raw(v)}(${E}) AS value FROM ${a.identifier(e)}`;g&&(R=a`${R} WHERE ${g}`);const P=G(c,R).toArray()[0]?.value;return P??null},asId(e,t){const r=Xt(s,e,t);if(r===null)throw new $("BAD_REQUEST",`asId("${e}", …): "${t}" is not a valid id for table "${e}"`,{status:400});return r},async count(e,t){const r=j(e,"count");if(r)return p(e,U),r.count(e,t);const u=s.tables[e];if(!u)throw new $("INTERNAL",`unknown table: ${e}`);const h=Cn(t);if(h.restrictsCounts)throw new ot(e);p(e,U);const f=Te(u.softDeleteMode,void 0),d=K(K(h.baseWhere,h.where),f),l=await be(d,e,h.relationBaseWhere),g=l!==d;if(u.aggregateIndexes&&!h.baseWhere&&!g){const m=bn(u.aggregateIndexes,h.where);if(m){Xe(e,m.index);const P=tt(m.index.by??[],m.key),T=et(e,m.index.name),H=G(c,a`SELECT ${Pe} AS value FROM ${a.identifier(T)} WHERE ${Ue} = ${P}`).toArray();return H[0]===void 0?0:H[0].value??0}}const v=Y(l,le);let E=a`SELECT COUNT(*) AS count FROM ${a.identifier(e)}`;return v&&(E=a`${E} WHERE ${v}`),G(c,E).one().count},async delete(e,t,r){const u=ee(e,t);if(!u){const R=_e(t);R&&(M(void 0),await R.delete(e,t,r));return}const{docJson:h,row:f,tableName:d}=u,l=s.tables[d],g=r?.hard===!0,v=!g&&l?.softDeleteMode?l:void 0,E=v?.softDeleteMode?.field;if(!(E&&f[E]!==null&&f[E]!==void 0)){if(X(d,"before","delete")&&await Z("before","delete",{id:e,op:"delete",previous:f,table:d}),await yo({deletedId:e,deletedReference:R=>f[R],findHolders:async(R,m,P)=>(await ze(R).findMany(R,{includeDeleted:g,where:{[m]:P}})).page,onCascade:(R,m)=>ze(R).delete(m,void 0,r),onRestrict:R=>{throw new se(R,"restrict")},onSetNull:(R,m,P)=>ze(R).patch(m,{[P]:null}),schema:s,tableName:d}),Ee(d),me(d),v&&E){const R={[E]:J()},m={...f,...A(d),...R,_id:e};at(v,R,m,ye),Ge(c,d,Qt(d),[ae(m),e,h]),Fe(d,e,m,f),ke(d,e,void 0),De(d,f,m),Se(d,e,f,void 0),oe?.invalidate(d,e,I(d,f,m)),$e(d,e,"update",m),w({indexKeys:I(d,f,m),key:e,op:"update",row:m,table:d}),X(d,"after","delete")&&await Z("after","delete",{id:e,op:"delete",previous:f,table:d}),await N({id:e,op:"delete",table:d});return}Ge(c,d,No(d),[e,h]),Fe(d,e,void 0),ke(d,e,void 0),De(d,f,void 0),Se(d,e,f,void 0),oe?.invalidate(d,e,I(d,f)),$e(d,e,"delete"),w({indexKeys:I(d,f),key:e,op:"delete",table:d}),X(d,"after","delete")&&await Z("after","delete",{id:e,op:"delete",previous:f,table:d}),await N({id:e,op:"delete",table:d})}},async deleteAll(e,t){if(!s.tables[e])throw new $("INTERNAL",`unknown table: ${e}`);const r=Math.max(1,t?.chunkSize??fn),u=t?.hard===void 0?void 0:{hard:t.hard},h=ie(e)?void 0:e;let f=0;return await L(async()=>{for(;;){const l=(await B.findMany(e,{limit:r})).page.map(g=>String(g._id));if(l.length===0)break;for(const g of l)await B.delete(g,h,u),f+=1;if(l.length<r)break}}),{deleted:f}},async deleteMany(e,t,r){de(e.length,t?.limit,"deleteMany");for(const u of e)await B.delete(u,r);return{deleted:e.length}},async deleteWhere(e,t,r){const f=(await(j(e,"deleteWhere")??B).findMany(e,{where:t})).page.map(d=>String(d._id));if(de(f.length,r?.limit,"deleteWhere"),B.deleteMany===void 0)throw new $("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return B.deleteMany(f,r)},async findFirst(e,t={}){return(await B.findMany(e,{...t,limit:1,omitContinueCursor:!0})).page[0]??null},async findFirstOrThrow(e,t={}){const r=await B.findFirst(e,t);if(r===null)throw new Vn(`findFirstOrThrow: no "${e}" document matched`);return r},async findMany(e,t={}){const r=j(e,"findMany");if(r)return p(e,U),r.findMany(e,t);const u=s.tables[e];if(!u)throw new $("INTERNAL",`unknown table: ${e}`);const h=!t.where&&!t.baseWhere;h?p(e,U):p(e);const{limit:f,orderKeys:d,statement:l}=await xt(e,u,t,p),g=fe(c,l.text,...l.params).toArray();h&&!F&&q?.recordRead(g.length);const v=[];for(const P of g){const T=ve(P);T&&(v.push(T),!h&&typeof T._id=="string"&&p(e,T._id))}if(f===void 0)return t.with&&await Ht({groupedCounter:Rt,fetcher:Ye,parents:v,...Gt(t),schema:s,tableName:e,with:t.with}),{continueCursor:null,isDone:!0,page:Wt(v,t.select,t.with)};const E=v.length>f,R=E?v.slice(0,f):v,m=R.at(-1);return t.with&&await Ht({fetcher:Ye,groupedCounter:Rt,parents:R,...Gt(t),schema:s,tableName:e,with:t.with}),{continueCursor:E&&m&&t.omitContinueCursor!==!0?je(m,d):null,isDone:!E,page:Wt(R,t.select,t.with)}},async explain(e,t={}){const r=j(e,"explain");if(r)return r.explain(e,t);const u=s.tables[e];if(!u)throw new $("INTERNAL",`unknown table: ${e}`);const{statement:h}=await xt(e,u,t,()=>{}),f=fe(c,`EXPLAIN QUERY PLAN ${h.text}`,...h.params).toArray();return{params:h.params,plan:f.map(d=>String(d.detail)),sql:h.text}},async get(e,t){const r=ee(e,t);if(!r){const u=_e(t);return u?u.get(e,t):null}return p(r.tableName,e),r.row},async lookupById(e,t){const r=ee(e,t);return r?(p(r.tableName,e),{row:r.row,tableName:r.tableName}):null},async groupBy(e,t){const r=j(e,"groupBy");if(r)return p(e,U),r.groupBy(e,t);const u=s.tables[e];if(!u)throw new $("INTERNAL",`unknown table: ${e}`);p(e,U);const h=t.agg??{op:"count"};if(Be(h.op),h.op!=="count"&&!h.field)throw new $("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);const f=Te(u.softDeleteMode,void 0),d=K(K(t.baseWhere,t.where),f),l=await be(d,e,t.relationBaseWhere),g=l!==d;if(u.aggregateIndexes&&!t.baseWhere&&!g){const T=xn(u.aggregateIndexes,h.op,h.field,t.by,t.where),H=T===void 0?0:Object.keys(T.partial).length,te=T?.index.by?.length??0;if(T&&(H===0||H===te)){Xe(e,T.index);const z=et(e,T.index.name),Q=Object.keys(T.partial),ce=[];if(Q.length===(T.index.by??[]).length&&Q.length>0){const Le=tt(T.index.by??[],T.partial),qe=G(c,a`SELECT ${Pe} AS value, ${rt} AS count FROM ${a.identifier(z)} WHERE ${Ue} = ${Le}`).toArray();return qe.length>0&&ce.push({key:{...T.partial},value:nt(h.op,qe[0])}),ce}const Rn=G(c,a`SELECT ${Ue} AS key, ${Pe} AS value, ${rt} AS count FROM ${a.identifier(z)}`).toArray();for(const Le of Rn){const qe=An(JSON.parse(Le.key));ce.push({key:qe,value:nt(h.op,Le)})}return ce}}for(const T of[...t.by,h.field]){if(T===void 0)continue;const H=T===h.field?`groupBy(${e}, { agg: { op: "${h.op}", field: "${T}" } })`:`groupBy(${e}, { by: [..."${T}"] })`;Yt(u,T,H)}const v=Y(l,le),E=t.by.map(T=>a`${ue(T)} AS ${a.identifier(T)}`);if(h.op==="count")E.push(a`COUNT(*) AS value`);else{const{field:T}=h;if(T===void 0)throw new $("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);E.push(a`${a.raw(Be(h.op))}(${ue(T)}) AS value`)}let R=a`SELECT ${a.join(E,a`, `)} FROM ${a.identifier(e)}`;v&&(R=a`${R} WHERE ${v}`),R=a`${R} GROUP BY ${a.join(t.by.map(T=>ue(T)),a`, `)}`;const m=G(c,R).toArray(),P=[];for(const T of m){const H={};for(const z of t.by)H[z]=Un(u.shape[z],T[z]??null);const{value:te}=T;P.push({key:H,value:te==null?null:Number(te)})}return P},async insert(e,t,r){const u=j(e,"insert");if(u)return $t(u,e,t,r,!0);const h=s.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);const f=Zt(h,t,ye);st(h,f);let d;r?.clientId!==void 0?(Xo(r.clientId),d=r.clientId):r?.allowExplicitId&&typeof f._id=="string"?d=f._id:d=pe();const l=r?.allowExplicitId&&typeof f._creationTime=="number"?f._creationTime:J(),g={...f,...A(e),_creationTime:l,_id:d};return X(e,"before","insert")&&await Z("before","insert",{doc:{...g},id:d,op:"insert",table:e}),Ee(e),me(e),ut(c,e,jo(e),[d,l,ae(g)]),vt(e,d,g),X(e,"after","insert")&&await Z("after","insert",{doc:g,id:d,op:"insert",table:e}),await N({doc:g,id:d,op:"insert",table:e}),d},async insertManyUnsafe(e,t,r){if(de(t.length,r?.limit,"insertManyUnsafe"),t.length===0)return[];const u=j(e,"insert");if(u){const l=[];for(const g of t)M(g);for(const g of t){const v=await u.insert(e,g,{allowExplicitId:r?.allowExplicitId});w({key:v,op:"insert",row:{...g,_id:v},table:e}),l.push(v)}return l}const h=s.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);Ee(e),me(e);const f=[];for(let l=0;l<t.length;l+=Oe)f.push(A(e));const d=t.map((l,g)=>{const v=Zt(h,l,ye),E=r?.allowExplicitId===!0&&typeof v._id=="string"?v._id:pe(),R=r?.allowExplicitId===!0&&typeof v._creationTime=="number"?v._creationTime:J(),m={...v,...f[Math.floor(g/Oe)],_creationTime:R,_id:E};return{creationTime:R,document:m,id:E}});for(const l of d)M(l.document);for(let l=0;l<d.length;l+=Oe){const g=a.join(d.slice(l,l+Oe).map(E=>a`(${E.id}, ${E.creationTime}, ${ae(E.document)})`),a`, `),v=cn("sqlite",a`INSERT INTO ${a.identifier(e)} (id, _creationTime, ${a.identifier(re)}) VALUES ${g}`);ut(c,e,v.sql,v.params)}for(const{document:l,id:g}of d)vt(e,g,l),await D({doc:l,id:g,op:"insert",table:e});return d.map(l=>l.id)},async insertMany(e,t,r){de(t.length,r?.limit,"insertMany");const u=r?.skipDuplicates===!0,h=[],f=j(e,"insert");if(f)for(const l of t)M(l);const d=async l=>f?$t(f,e,l,void 0,!1):B.insert(e,l);for(const l of t)try{h.push(await d(l))}catch(g){if(u&&g instanceof se&&g.kind==="unique")h.push(null);else throw g}return h},normalizeId(e,t){return Xt(s,e,t)},async patch(e,t,r,u){const h=ee(e,r);if(!h){const R=_e(r);if(R){M(t),await R.patch(e,t,r,u);return}throw new $("NOT_FOUND",`document not found: ${e}`)}const{docJson:f,row:d,tableName:l}=h,g=s.tables[l];if(!g)throw new $("INTERNAL",`unknown table: ${l}`);if(p(l,e),tn("patch",t),gt(l,e,t,d)){o?.({fields:Object.keys(He(t)),id:e,table:l});return}const v=Jn(g,t,d),E={...d,...He(v),...A(l),_id:e};at(g,v,E,ye),zn(u,d,E),st(g,E,!0),X(l,"before","update")&&await Z("before","update",{doc:{...E},id:e,op:"update",previous:d,table:l}),Ee(l),me(l),Ge(c,l,Qt(l),[ae(E),e,f]),Fe(l,e,E,d),ke(l,e,E),De(l,d,E),Se(l,e,d,E),oe?.invalidate(l,e,I(l,d,E)),$e(l,e,"update",E),w({indexKeys:I(l,d,E),key:e,op:"update",row:E,table:l}),X(l,"after","update")&&await Z("after","update",{doc:E,id:e,op:"update",previous:d,table:l}),await N({doc:E,id:e,op:"update",table:l})},async patchIf(e,t,r){const u=j(e,"patchIf");if(u){if(u.patchIf===void 0)throw new $("INTERNAL",`ctx.db.patchIf on global table '${e}' is unsupported: its backend has no conditional write`);return M(r.patch),u.patchIf(e,t,r)}if(!s.tables[e])throw new $("INTERNAL",`unknown table: ${e}`);for(let h=1;h<=en;h+=1){const f=await Sn(e,t,r,h<en,d=>B.patch(t,d,e,{verify:r.verify}));if(f!==void 0)return f}throw new se(`patchIf on "${e}" kept conflicting; the row changed on every attempt`,"occ")},async patchMany(e,t,r){de(e.length,t?.limit,"patchMany");for(const u of e)await B.patch(u.id,u.patch,r);return{patched:e.length}},async patchWhere(e,t,r){const f=(await(j(e,"patchWhere")??B).findMany(e,{where:t.where})).page.map(d=>({id:String(d._id),patch:t.patch}));if(de(f.length,r?.limit,"patchWhere"),B.patchMany===void 0)throw new $("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await B.patchMany(f,r),{patched:f.length}},async related(e,t){return ho(B,_,e,t)},relationEdges:_,deleteRereadTables:b,inTransaction:C,softDeleteFields:y,relationWrites:S,query(e){const t=j(e,"query");return t?(p(e,U),t.query(e)):pn(c,s,e,x,r=>{r?ne(r):p(e,U)},r=>{F||q?.recordRead(r)})},async rank(e,t,r){const u=j(e,"rank");if(u)return p(e,U),u.rank(e,t,r);x(e,t,"rank");const h=s.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);const f=h.rankIndexes?.find(Q=>Q.name===t);if(!f)throw new $("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(At(e,h,f),r.restrictsCounts)throw new ot(e);p(e,U),Ze(e,f);const d=typeof r.row=="string"?r.row:r.row._id;if(!d)return null;const l=Bt(e,f.name),g=f.sortBy.map((Q,ce)=>Pt(ce)),v=g.map(Q=>Ce(Q)).join(", "),E=G(c,a`SELECT ${a.identifier("__partition__")}, ${a.raw(v)} FROM ${a.identifier(l)} WHERE ${a.identifier("__id__")} = ${d}`).toArray(),[R]=E;if(R===void 0)return null;let m=R.__partition__;const P=K(r.baseWhere,r.where);it(P,s,e,"rank");const T=oo(f,P);if(T){const Q=ro(f.partitionBy??[],T);if(Q!==m)return null;m=Q}const H=g.map(Q=>R[Q]),{before:te,total:z}=on(c,l,g,f.sortBy,m,H,d);return{position:te+1,total:z}},async rankBefore(e,t,r){if(ie(e))throw new $("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const u=s.tables[e];if(!u)throw new $("INTERNAL",`unknown table: ${e}`);const h=u.rankIndexes?.find(g=>g.name===t);if(!h)throw new $("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(r.restrictsCounts)throw new ot(e);p(e,U),Ze(e,h);const f=Bt(e,h.name),d=h.sortBy.map((g,v)=>Pt(v)),l=h.sortBy.map((g,v)=>Ie(r.sortValues[v]??null));return on(c,f,d,h.sortBy,r.partitionKey,l,r.rowId)},async rankPage(e,t,r={}){it(K(r.baseWhere,r.where),s,e,"rankPage");const u=j(e,"rankPage");if(u)return p(e,U),u.rankPage(e,t,r);x(e,t,"rank");const{continueCursor:h,hasMore:f,rows:d}=Dt(Ct,e,t,r);return{continueCursor:h,isDone:!f,page:d.map(l=>l.doc)}},async rankPageRows(e,t,r={}){it(K(r.baseWhere,r.where),s,e,"rankPage"),x(e,t,"rank");const{directions:u,hasMore:h,rows:f}=Dt(Ct,e,t,r);return{directions:u,hasMore:h,rows:f}},async restore(e,t){const r=ee(e,t);if(!r){const f=_e(t);if(f?.restore){await f.restore(e,t);return}throw new $("NOT_FOUND",`document not found: ${e}`)}const u=s.tables[r.tableName]?.softDeleteMode?.field;if(!u)throw new $("INTERNAL",`ctx.db.restore: table "${r.tableName}" is not a .softDelete() table`);const h=r.row[u]!==null&&r.row[u]!==void 0;await B.patch(e,{[u]:null},t),h&&Se(r.tableName,e,void 0,r.row)},async replace(e,t,r,u){const h=ee(e,r);if(!h){const P=_e(r);if(P){M(t),await P.replace(e,t,r,u);return}throw new $("NOT_FOUND",`document not found: ${e}`)}const{docJson:f,row:d,tableName:l}=h,g=s.tables[l];if(!g)throw new $("INTERNAL",`unknown table: ${l}`);tn("replace",t);const v=u?.allowExplicitId&&typeof t._creationTime=="number"?t._creationTime:void 0,E=typeof d._creationTime=="number"?d._creationTime:void 0,R=v??E??J(),m={...t,...A(l),_creationTime:R,_id:e};at(g,t,m,ye),st(g,m),X(l,"before","update")&&await Z("before","update",{doc:{...m},id:e,op:"update",previous:d,table:l}),Ee(l),me(l),Ge(c,l,Ko(l),[R,ae(m),e,f]),Fe(l,e,m,d),ke(l,e,m),De(l,d,m),Se(l,e,d,m),oe?.invalidate(l,e,I(l,d,m)),$e(l,e,"update",m),w({indexKeys:I(l,d,m),key:e,op:"update",row:m,table:l}),X(l,"after","update")&&await Z("after","update",{doc:m,id:e,op:"update",previous:d,table:l}),await N({doc:m,id:e,op:"update",table:l})},async wipeShard(e){const t=new Set(e?.exclude),r=e?.tables,u=Object.entries(s.tables).filter(([l,g])=>t.has(l)||r!==void 0&&!r.includes(l)?!1:g.shardMode?.kind!=="global").map(([l])=>l);if(r!==void 0){for(const l of r)if(!s.tables[l])throw new $("INTERNAL",`wipeShard: unknown table: ${l}`)}const h={};let f=0;const{deleteAll:d}=B;if(d===void 0)throw new $("INTERNAL","wipeShard: this writer has no deleteAll");for(const l of u){const g=await d(l,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});h[l]=g.deleted,f+=g.deleted}return{deleted:f,tables:h}}},_n={db:B,scheduler:xe};return n.enforceRls===!0?Eo(B,s,(e,t)=>ee(e,t)?.tableName,(e,t)=>$n(e,t),_):B};export{li as CDC_LOG_TABLE,Di as IDEMPOTENCY_TABLE,lr as NotUniqueError,Ci as advanceClientWatermark,ui as applyCdcChanges,tn as assertNoExplicitUndefined,Xo as assertValidClientId,si as backfillAggregateIndexes,ci as backfillRankIndexes,ai as backfillSearchIndexes,fi as bumpCdcEpoch,hi as cdcCanVouchFor,wi as cdcForkedError,pi as cdcSeqLeavingRows,gi as cdcTouchesTables,yi as cdcTrimmedError,$i as compactCdcDocs,oi as createShardCtxDb,Ei as cursorBelowRetainedFloor,xi as migrateClientWatermark,mi as minCdcReplayableSeq,Si as minCdcSeq,Xt as normalizeIdStructurally,_i as readCdcChangeKeys,Ri as readCdcChanges,Ti as readCdcCursor,vi as readCdcEpoch,bi as readClientWatermark,ki as readIdempotent,Wi as runShardMigrations,Pi as selectShapeMembers,Ui as selectShapeRows,He as stripReservedPatchFields,Ai as trimCdcChanges,Fi as trimIdempotent,Li as writeIdempotent};
|