@lunora/do 1.0.0-alpha.48 → 1.0.0-alpha.49

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -3981,8 +3981,13 @@ declare const encodeGeohash: (point: GeoPoint, precision: number) => string;
3981
3981
  declare const haversineMeters: (a: GeoPoint, b: GeoPoint) => number;
3982
3982
  /**
3983
3983
  * The center cell plus its eight neighbours at a precision chosen so each cell is
3984
- * at least `radiusMeters` wide the geohash prefixes to range-scan for a
3985
- * proximity query. Deduplicated (near a pole neighbours can collapse).
3984
+ * at least `radiusMeters` in both its north-south height and its latitude-adjusted
3985
+ * east-west width, so the 3×3 neighbourhood covers the circle. When the query
3986
+ * circle's poleward extent reaches the {@link LAT_CAP_DEGREES pole-cap latitude} —
3987
+ * where the {@link MIN_LATITUDE_COSINE} clamp would let the circle out-reach the 3×3
3988
+ * east-west — the result is instead a complete {@link poleCapCovering polar band}.
3989
+ * These are the geohash prefixes to range-scan for a proximity query. Deduplicated
3990
+ * (near a pole neighbours can collapse).
3986
3991
  */
3987
3992
  declare const coveringGeohashes: (center: GeoPoint, radiusMeters: number) => string[];
3988
3993
  /** Whether `point` falls inside `box` (inclusive edges). */
package/dist/index.d.ts CHANGED
@@ -3981,8 +3981,13 @@ declare const encodeGeohash: (point: GeoPoint, precision: number) => string;
3981
3981
  declare const haversineMeters: (a: GeoPoint, b: GeoPoint) => number;
3982
3982
  /**
3983
3983
  * The center cell plus its eight neighbours at a precision chosen so each cell is
3984
- * at least `radiusMeters` wide the geohash prefixes to range-scan for a
3985
- * proximity query. Deduplicated (near a pole neighbours can collapse).
3984
+ * at least `radiusMeters` in both its north-south height and its latitude-adjusted
3985
+ * east-west width, so the 3×3 neighbourhood covers the circle. When the query
3986
+ * circle's poleward extent reaches the {@link LAT_CAP_DEGREES pole-cap latitude} —
3987
+ * where the {@link MIN_LATITUDE_COSINE} clamp would let the circle out-reach the 3×3
3988
+ * east-west — the result is instead a complete {@link poleCapCovering polar band}.
3989
+ * These are the geohash prefixes to range-scan for a proximity query. Deduplicated
3990
+ * (near a pole neighbours can collapse).
3986
3991
  */
3987
3992
  declare const coveringGeohashes: (center: GeoPoint, radiusMeters: number) => string[];
3988
3993
  /** Whether `point` falls inside `box` (inclusive edges). */
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{exportShardRows as o,exportShardTable as t,importShardRows as a,parseExportShardArgs as n,parseImportShardArgs as i,selectExportTables as s,validateImportRow as l}from"./packem_shared/exportShardRows-kt42wijd.mjs";import{AGGREGATE_SQL_FUNCTION as T,aggregateSqlFunction as d,matchesStaticWhere as p,normalizeCountArgument as E,throwingScheduler as S}from"./packem_shared/AGGREGATE_SQL_FUNCTION-QYaiuty4.mjs";import{aggregateTableName as _,coerceAggregateNumber as u,encodeAggregateKey as x,foldAggregateTally as f,readAggregateValue as I}from"./packem_shared/aggregateTableName-G-eXyjcz.mjs";import{CountRlsUnsupportedError as A,mergeWhere as N,planAggregateLookup as g,selectIndexForAggregate as C,selectIndexForCount as M,selectIndexForGroupBy as h}from"./packem_shared/CountRlsUnsupportedError-Cl8XpYDL.mjs";import{AUTH_METRICS_BUCKETS_TABLE as F,AUTH_METRICS_BUCKET_MS as D,AUTH_METRICS_BUCKET_RETENTION as L,AUTH_METRICS_TABLE as U,ensureAuthMetricsTables as B,readAuthMetrics as b,recordAuthEvent as y}from"./packem_shared/AUTH_METRICS_BUCKETS_TABLE-D0wNaez7.mjs";import{c as K,a as G,d as P}from"./packem_shared/context-telemetry-BQoMfXLz.mjs";import{NotUniqueError as v,assertValidClientId as H,createShardCtxDb as w,normalizeIdStructurally as q}from"./packem_shared/NotUniqueError-BcP6GOem.mjs";import{DATA_MIGRATION_STATE_TABLE as X,readMigrationStatus as Y,runDataMigration as V}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-CaO6L0Ee.mjs";import{SCAN_DEP as Z,createDependencyTracker as j,depKey as J}from"./packem_shared/SCAN_DEP-D_yR9EeV.mjs";import{renderSql as ee}from"./packem_shared/renderSql-B5lF5Jd9.mjs";import{diffExternalSource as oe}from"./packem_shared/diffExternalSource-DMpkJta1.mjs";import{materializeExternalRows as ae,materializeExternalRowsIncremental as ne,readExternalSourceBaseline as ie,runExternalSourceTick as se}from"./packem_shared/materializeExternalRows-BFmT9gsw.mjs";import{isSoftDeleted as ce,isSourceDue as Te,liftSourceId as de,pullExternalSourceIncrementalTick as pe,pullExternalSourceTick as Ee}from"./packem_shared/isSoftDeleted-BvhQov04.mjs";import{FUNCTION_METRICS_BUCKETS_TABLE as me,FUNCTION_METRICS_BUCKET_MS as _e,FUNCTION_METRICS_BUCKET_RETENTION as ue,FUNCTION_METRICS_INDEX_TABLE as xe,FUNCTION_METRICS_TABLE as fe,ensureFunctionMetricsTables as Ie,readFunctionMetricBuckets as Re,readFunctionMetricIndexHits as Ae,readFunctionMetrics as Ne,readFunctionMetricsTotals as ge,recordFunctionMetric as Ce}from"./packem_shared/FUNCTION_METRICS_BUCKETS_TABLE-BPPeqM11.mjs";import{GEO_DEFAULT_PRECISION as he,boundingBoxGeohashes as Oe,coveringGeohashes as Fe,encodeGeohash as De,haversineMeters as Le,pointInBoundingBox as Ue}from"./packem_shared/GEO_DEFAULT_PRECISION-CWAm_oYY.mjs";import{ADMIN_FUNCTIONS as be,ADMIN_FUNCTION_PREFIX as ye,FLAGS_FUNCTION_PREFIX as ke,RELATION_FUNCTION_PREFIX as Ke,facetColumn as Ge,listTables as Pe,readTablePage as We,selectMatchingIds as ve}from"./packem_shared/ADMIN_FUNCTIONS-PxZ8Lr9e.mjs";import{LogBuffer as we}from"./packem_shared/LogBuffer-bIvCelI-.mjs";import{MAIL_RETENTION as ze,MAIL_TABLE as Xe,clearCapturedMail as Ye,ensureMailTable as Ve,readCapturedMail as Qe,recordCapturedMail as Ze}from"./packem_shared/MAIL_RETENTION-KmozO2NQ.mjs";import{default as Je}from"./packem_shared/NotFoundError-J3tjf4Uo.mjs";import{armRestore as er,readBookmark as rr}from"./packem_shared/armRestore-BNzdvQ_o.mjs";import{applySelect as tr,buildSeekWhere as ar,decodeCursor as nr,encodeCursor as ir,normalizeOrderKeys as sr,softDeleteScope as lr}from"./packem_shared/applySelect-Bq2KOrkL.mjs";import{RANK_TIEBREAK as Tr,encodePartitionKey as dr,matchesRankStaticWhere as pr,rankTableName as Er,resolveRankPartition as Sr,sortColumnName as mr}from"./packem_shared/RANK_TIEBREAK-DtX8zQyc.mjs";import{ReactiveCache as ur,reactiveCacheKey as xr}from"./packem_shared/ReactiveCache-1_9Rs7J_.mjs";import{serveRelationFanout as Ir}from"./packem_shared/serveRelationFanout-Ct5D2Tbk.mjs";import{DEFAULT_MAX_RELATION_KEYS as Ar,assertFlatPredicate as Nr,assertShapeShardable as gr,containsRelationPredicate as Cr,isRelationPredicate as Mr,resolveRelationPredicates as hr}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-BRdmX7WW.mjs";import{applyOnDelete as Fr,fanOutScalarCounts as Dr,resolveWith as Lr,runRowValidators as Ur}from"./packem_shared/applyOnDelete-BvQN7pDL.mjs";import{RLS_UNWRAP_SYMBOL as br,RlsRequiredError as yr,guardWriter as kr}from"./packem_shared/RLS_UNWRAP_SYMBOL-C6_WX3dG.mjs";import{buildFtsMatch as Gr,ftsTableName as Pr,scoreDocument as Wr,stringifySearchText as vr,tokenizeSearch as Hr}from"./packem_shared/buildFtsMatch-CV0Z7PWv.mjs";import{o as qr,c as zr,_ as Xr}from"./packem_shared/security-audit-BKUOgE0x.mjs";import{SESSION_DO_TTL_DEFAULT as Vr,SessionDO as Qr}from"./packem_shared/SESSION_DO_TTL_DEFAULT-GvBy_DBz.mjs";import{ROOT_DO_SIZE_WARN_BYTES as jr,ROOT_SHARD_NAME as Jr,ShardDO as $r}from"./packem_shared/ROOT_DO_SIZE_WARN_BYTES-DqqGF-jB.mjs";import{SHARD_REGISTRY_DO_NAME as ro,ShardRegistryDO as oo}from"./packem_shared/SHARD_REGISTRY_DO_NAME-Caa0fR4N.mjs";import{MAX_SQL_ROWS as ao,assertReadonly as no,runReadonlySql as io}from"./packem_shared/MAX_SQL_ROWS-Bdu25ASB.mjs";import{createSystemReader as lo}from"./packem_shared/createSystemReader-DcDcrtM3.mjs";import{ConflictError as To}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{hasTrigger as Eo,runTriggers as So}from"./packem_shared/hasTrigger-_rexbWMO.mjs";import{selectExpiredIds as _o}from"./packem_shared/selectExpiredIds-BGVP3d8-.mjs";import{compileWhereSql as xo}from"./packem_shared/compileWhereSql-BLcfs4QW.mjs";import{CDC_LOG_TABLE as Io,applyCdcChanges as Ro,readCdcChanges as Ao,trimCdcChanges as No}from"./packem_shared/CDC_LOG_TABLE-E_J5LPoK.mjs";import{backfillAggregateIndexes as Co,backfillRankIndexes as Mo}from"./packem_shared/backfillAggregateIndexes-BAQ3Fwwh.mjs";import{runShardMigrations as Oo}from"./packem_shared/runShardMigrations-bxOHpfID.mjs";import{stableStringify as Do}from"./packem_shared/stableStringify-BjLh4gvA.mjs";import{stableWireKey as Uo}from"./packem_shared/stableWireKey-YEHLaX6X.mjs";import{subscriptionListDeltas as bo}from"./packem_shared/subscriptionListDeltas-Bs69JbA8.mjs";export{be as ADMIN_FUNCTIONS,ye as ADMIN_FUNCTION_PREFIX,T as AGGREGATE_SQL_FUNCTION,F as AUTH_METRICS_BUCKETS_TABLE,D as AUTH_METRICS_BUCKET_MS,L as AUTH_METRICS_BUCKET_RETENTION,U as AUTH_METRICS_TABLE,Io as CDC_LOG_TABLE,To as ConflictError,A as CountRlsUnsupportedError,X as DATA_MIGRATION_STATE_TABLE,Ar as DEFAULT_MAX_RELATION_KEYS,ke as FLAGS_FUNCTION_PREFIX,me as FUNCTION_METRICS_BUCKETS_TABLE,_e as FUNCTION_METRICS_BUCKET_MS,ue as FUNCTION_METRICS_BUCKET_RETENTION,xe as FUNCTION_METRICS_INDEX_TABLE,fe as FUNCTION_METRICS_TABLE,he as GEO_DEFAULT_PRECISION,we as LogBuffer,ze as MAIL_RETENTION,Xe as MAIL_TABLE,ao as MAX_SQL_ROWS,qr as MIN_ADMIN_TOKEN_LENGTH,zr as MIN_AUTH_SECRET_LENGTH,Je as NotFoundError,v as NotUniqueError,Tr as RANK_TIEBREAK,Ke as RELATION_FUNCTION_PREFIX,br as RLS_UNWRAP_SYMBOL,jr as ROOT_DO_SIZE_WARN_BYTES,Jr as ROOT_SHARD_NAME,ur as ReactiveCache,yr as RlsRequiredError,Z as SCAN_DEP,Vr as SESSION_DO_TTL_DEFAULT,ro as SHARD_REGISTRY_DO_NAME,Qr as SessionDO,$r as ShardDO,oo as ShardRegistryDO,d as aggregateSqlFunction,_ as aggregateTableName,Ro as applyCdcChanges,Fr as applyOnDelete,tr as applySelect,er as armRestore,Nr as assertFlatPredicate,no as assertReadonly,gr as assertShapeShardable,H as assertValidClientId,Co as backfillAggregateIndexes,Mo as backfillRankIndexes,Oe as boundingBoxGeohashes,Gr as buildFtsMatch,Xr as buildSecurityAudit,ar as buildSeekWhere,Ye as clearCapturedMail,u as coerceAggregateNumber,xo as compileWhereSql,Cr as containsRelationPredicate,Fe as coveringGeohashes,j as createDependencyTracker,K as createMetrics,w as createShardCtxDb,lo as createSystemReader,G as createTracer,nr as decodeCursor,J as depKey,oe as diffExternalSource,P as dispatchRootSpan,x as encodeAggregateKey,ir as encodeCursor,De as encodeGeohash,dr as encodePartitionKey,B as ensureAuthMetricsTables,Ie as ensureFunctionMetricsTables,Ve as ensureMailTable,o as exportShardRows,t as exportShardTable,Ge as facetColumn,Dr as fanOutScalarCounts,f as foldAggregateTally,Pr as ftsTableName,kr as guardWriter,Eo as hasTrigger,Le as haversineMeters,a as importShardRows,Mr as isRelationPredicate,ce as isSoftDeleted,Te as isSourceDue,de as liftSourceId,Pe as listTables,pr as matchesRankStaticWhere,p as matchesStaticWhere,ae as materializeExternalRows,ne as materializeExternalRowsIncremental,N as mergeWhere,E as normalizeCountArgument,q as normalizeIdStructurally,sr as normalizeOrderKeys,n as parseExportShardArgs,i as parseImportShardArgs,g as planAggregateLookup,Ue as pointInBoundingBox,pe as pullExternalSourceIncrementalTick,Ee as pullExternalSourceTick,Er as rankTableName,xr as reactiveCacheKey,I as readAggregateValue,b as readAuthMetrics,rr as readBookmark,Qe as readCapturedMail,Ao as readCdcChanges,ie as readExternalSourceBaseline,Re as readFunctionMetricBuckets,Ae as readFunctionMetricIndexHits,Ne as readFunctionMetrics,ge as readFunctionMetricsTotals,Y as readMigrationStatus,We as readTablePage,y as recordAuthEvent,Ze as recordCapturedMail,Ce as recordFunctionMetric,ee as renderSql,Sr as resolveRankPartition,hr as resolveRelationPredicates,Lr as resolveWith,V as runDataMigration,se as runExternalSourceTick,io as runReadonlySql,Ur as runRowValidators,Oo as runShardMigrations,So as runTriggers,Wr as scoreDocument,_o as selectExpiredIds,s as selectExportTables,C as selectIndexForAggregate,M as selectIndexForCount,h as selectIndexForGroupBy,ve as selectMatchingIds,Ir as serveRelationFanout,lr as softDeleteScope,mr as sortColumnName,Do as stableStringify,Uo as stableWireKey,vr as stringifySearchText,bo as subscriptionListDeltas,S as throwingScheduler,Hr as tokenizeSearch,No as trimCdcChanges,l as validateImportRow};
1
+ import{exportShardRows as o,exportShardTable as t,importShardRows as a,parseExportShardArgs as n,parseImportShardArgs as i,selectExportTables as s,validateImportRow as l}from"./packem_shared/exportShardRows-kt42wijd.mjs";import{AGGREGATE_SQL_FUNCTION as T,aggregateSqlFunction as d,matchesStaticWhere as p,normalizeCountArgument as E,throwingScheduler as S}from"./packem_shared/AGGREGATE_SQL_FUNCTION-QYaiuty4.mjs";import{aggregateTableName as _,coerceAggregateNumber as u,encodeAggregateKey as x,foldAggregateTally as f,readAggregateValue as I}from"./packem_shared/aggregateTableName-G-eXyjcz.mjs";import{CountRlsUnsupportedError as A,mergeWhere as N,planAggregateLookup as g,selectIndexForAggregate as C,selectIndexForCount as M,selectIndexForGroupBy as h}from"./packem_shared/CountRlsUnsupportedError-Cl8XpYDL.mjs";import{AUTH_METRICS_BUCKETS_TABLE as F,AUTH_METRICS_BUCKET_MS as D,AUTH_METRICS_BUCKET_RETENTION as L,AUTH_METRICS_TABLE as U,ensureAuthMetricsTables as B,readAuthMetrics as b,recordAuthEvent as y}from"./packem_shared/AUTH_METRICS_BUCKETS_TABLE-D0wNaez7.mjs";import{c as K,a as G,d as P}from"./packem_shared/context-telemetry-BQoMfXLz.mjs";import{NotUniqueError as v,assertValidClientId as H,createShardCtxDb as w,normalizeIdStructurally as q}from"./packem_shared/NotUniqueError-GI79LNJB.mjs";import{DATA_MIGRATION_STATE_TABLE as X,readMigrationStatus as Y,runDataMigration as V}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-CaO6L0Ee.mjs";import{SCAN_DEP as Z,createDependencyTracker as j,depKey as J}from"./packem_shared/SCAN_DEP-D_yR9EeV.mjs";import{renderSql as ee}from"./packem_shared/renderSql-B5lF5Jd9.mjs";import{diffExternalSource as oe}from"./packem_shared/diffExternalSource-DMpkJta1.mjs";import{materializeExternalRows as ae,materializeExternalRowsIncremental as ne,readExternalSourceBaseline as ie,runExternalSourceTick as se}from"./packem_shared/materializeExternalRows-BFmT9gsw.mjs";import{isSoftDeleted as ce,isSourceDue as Te,liftSourceId as de,pullExternalSourceIncrementalTick as pe,pullExternalSourceTick as Ee}from"./packem_shared/isSoftDeleted-BvhQov04.mjs";import{FUNCTION_METRICS_BUCKETS_TABLE as me,FUNCTION_METRICS_BUCKET_MS as _e,FUNCTION_METRICS_BUCKET_RETENTION as ue,FUNCTION_METRICS_INDEX_TABLE as xe,FUNCTION_METRICS_TABLE as fe,ensureFunctionMetricsTables as Ie,readFunctionMetricBuckets as Re,readFunctionMetricIndexHits as Ae,readFunctionMetrics as Ne,readFunctionMetricsTotals as ge,recordFunctionMetric as Ce}from"./packem_shared/FUNCTION_METRICS_BUCKETS_TABLE-BPPeqM11.mjs";import{GEO_DEFAULT_PRECISION as he,boundingBoxGeohashes as Oe,coveringGeohashes as Fe,encodeGeohash as De,haversineMeters as Le,pointInBoundingBox as Ue}from"./packem_shared/GEO_DEFAULT_PRECISION-okRCkZ6r.mjs";import{ADMIN_FUNCTIONS as be,ADMIN_FUNCTION_PREFIX as ye,FLAGS_FUNCTION_PREFIX as ke,RELATION_FUNCTION_PREFIX as Ke,facetColumn as Ge,listTables as Pe,readTablePage as We,selectMatchingIds as ve}from"./packem_shared/ADMIN_FUNCTIONS-PxZ8Lr9e.mjs";import{LogBuffer as we}from"./packem_shared/LogBuffer-bIvCelI-.mjs";import{MAIL_RETENTION as ze,MAIL_TABLE as Xe,clearCapturedMail as Ye,ensureMailTable as Ve,readCapturedMail as Qe,recordCapturedMail as Ze}from"./packem_shared/MAIL_RETENTION-KmozO2NQ.mjs";import{default as Je}from"./packem_shared/NotFoundError-J3tjf4Uo.mjs";import{armRestore as er,readBookmark as rr}from"./packem_shared/armRestore-BNzdvQ_o.mjs";import{applySelect as tr,buildSeekWhere as ar,decodeCursor as nr,encodeCursor as ir,normalizeOrderKeys as sr,softDeleteScope as lr}from"./packem_shared/applySelect-Bq2KOrkL.mjs";import{RANK_TIEBREAK as Tr,encodePartitionKey as dr,matchesRankStaticWhere as pr,rankTableName as Er,resolveRankPartition as Sr,sortColumnName as mr}from"./packem_shared/RANK_TIEBREAK-DtX8zQyc.mjs";import{ReactiveCache as ur,reactiveCacheKey as xr}from"./packem_shared/ReactiveCache-1_9Rs7J_.mjs";import{serveRelationFanout as Ir}from"./packem_shared/serveRelationFanout-Ct5D2Tbk.mjs";import{DEFAULT_MAX_RELATION_KEYS as Ar,assertFlatPredicate as Nr,assertShapeShardable as gr,containsRelationPredicate as Cr,isRelationPredicate as Mr,resolveRelationPredicates as hr}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-BRdmX7WW.mjs";import{applyOnDelete as Fr,fanOutScalarCounts as Dr,resolveWith as Lr,runRowValidators as Ur}from"./packem_shared/applyOnDelete-BvQN7pDL.mjs";import{RLS_UNWRAP_SYMBOL as br,RlsRequiredError as yr,guardWriter as kr}from"./packem_shared/RLS_UNWRAP_SYMBOL-C6_WX3dG.mjs";import{buildFtsMatch as Gr,ftsTableName as Pr,scoreDocument as Wr,stringifySearchText as vr,tokenizeSearch as Hr}from"./packem_shared/buildFtsMatch-CV0Z7PWv.mjs";import{o as qr,c as zr,_ as Xr}from"./packem_shared/security-audit-BKUOgE0x.mjs";import{SESSION_DO_TTL_DEFAULT as Vr,SessionDO as Qr}from"./packem_shared/SESSION_DO_TTL_DEFAULT-GvBy_DBz.mjs";import{ROOT_DO_SIZE_WARN_BYTES as jr,ROOT_SHARD_NAME as Jr,ShardDO as $r}from"./packem_shared/ROOT_DO_SIZE_WARN_BYTES-DqqGF-jB.mjs";import{SHARD_REGISTRY_DO_NAME as ro,ShardRegistryDO as oo}from"./packem_shared/SHARD_REGISTRY_DO_NAME-Caa0fR4N.mjs";import{MAX_SQL_ROWS as ao,assertReadonly as no,runReadonlySql as io}from"./packem_shared/MAX_SQL_ROWS-Bdu25ASB.mjs";import{createSystemReader as lo}from"./packem_shared/createSystemReader-DcDcrtM3.mjs";import{ConflictError as To}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{hasTrigger as Eo,runTriggers as So}from"./packem_shared/hasTrigger-_rexbWMO.mjs";import{selectExpiredIds as _o}from"./packem_shared/selectExpiredIds-BGVP3d8-.mjs";import{compileWhereSql as xo}from"./packem_shared/compileWhereSql-BLcfs4QW.mjs";import{CDC_LOG_TABLE as Io,applyCdcChanges as Ro,readCdcChanges as Ao,trimCdcChanges as No}from"./packem_shared/CDC_LOG_TABLE-E_J5LPoK.mjs";import{backfillAggregateIndexes as Co,backfillRankIndexes as Mo}from"./packem_shared/backfillAggregateIndexes-BAQ3Fwwh.mjs";import{runShardMigrations as Oo}from"./packem_shared/runShardMigrations-bxOHpfID.mjs";import{stableStringify as Do}from"./packem_shared/stableStringify-BjLh4gvA.mjs";import{stableWireKey as Uo}from"./packem_shared/stableWireKey-YEHLaX6X.mjs";import{subscriptionListDeltas as bo}from"./packem_shared/subscriptionListDeltas-Bs69JbA8.mjs";export{be as ADMIN_FUNCTIONS,ye as ADMIN_FUNCTION_PREFIX,T as AGGREGATE_SQL_FUNCTION,F as AUTH_METRICS_BUCKETS_TABLE,D as AUTH_METRICS_BUCKET_MS,L as AUTH_METRICS_BUCKET_RETENTION,U as AUTH_METRICS_TABLE,Io as CDC_LOG_TABLE,To as ConflictError,A as CountRlsUnsupportedError,X as DATA_MIGRATION_STATE_TABLE,Ar as DEFAULT_MAX_RELATION_KEYS,ke as FLAGS_FUNCTION_PREFIX,me as FUNCTION_METRICS_BUCKETS_TABLE,_e as FUNCTION_METRICS_BUCKET_MS,ue as FUNCTION_METRICS_BUCKET_RETENTION,xe as FUNCTION_METRICS_INDEX_TABLE,fe as FUNCTION_METRICS_TABLE,he as GEO_DEFAULT_PRECISION,we as LogBuffer,ze as MAIL_RETENTION,Xe as MAIL_TABLE,ao as MAX_SQL_ROWS,qr as MIN_ADMIN_TOKEN_LENGTH,zr as MIN_AUTH_SECRET_LENGTH,Je as NotFoundError,v as NotUniqueError,Tr as RANK_TIEBREAK,Ke as RELATION_FUNCTION_PREFIX,br as RLS_UNWRAP_SYMBOL,jr as ROOT_DO_SIZE_WARN_BYTES,Jr as ROOT_SHARD_NAME,ur as ReactiveCache,yr as RlsRequiredError,Z as SCAN_DEP,Vr as SESSION_DO_TTL_DEFAULT,ro as SHARD_REGISTRY_DO_NAME,Qr as SessionDO,$r as ShardDO,oo as ShardRegistryDO,d as aggregateSqlFunction,_ as aggregateTableName,Ro as applyCdcChanges,Fr as applyOnDelete,tr as applySelect,er as armRestore,Nr as assertFlatPredicate,no as assertReadonly,gr as assertShapeShardable,H as assertValidClientId,Co as backfillAggregateIndexes,Mo as backfillRankIndexes,Oe as boundingBoxGeohashes,Gr as buildFtsMatch,Xr as buildSecurityAudit,ar as buildSeekWhere,Ye as clearCapturedMail,u as coerceAggregateNumber,xo as compileWhereSql,Cr as containsRelationPredicate,Fe as coveringGeohashes,j as createDependencyTracker,K as createMetrics,w as createShardCtxDb,lo as createSystemReader,G as createTracer,nr as decodeCursor,J as depKey,oe as diffExternalSource,P as dispatchRootSpan,x as encodeAggregateKey,ir as encodeCursor,De as encodeGeohash,dr as encodePartitionKey,B as ensureAuthMetricsTables,Ie as ensureFunctionMetricsTables,Ve as ensureMailTable,o as exportShardRows,t as exportShardTable,Ge as facetColumn,Dr as fanOutScalarCounts,f as foldAggregateTally,Pr as ftsTableName,kr as guardWriter,Eo as hasTrigger,Le as haversineMeters,a as importShardRows,Mr as isRelationPredicate,ce as isSoftDeleted,Te as isSourceDue,de as liftSourceId,Pe as listTables,pr as matchesRankStaticWhere,p as matchesStaticWhere,ae as materializeExternalRows,ne as materializeExternalRowsIncremental,N as mergeWhere,E as normalizeCountArgument,q as normalizeIdStructurally,sr as normalizeOrderKeys,n as parseExportShardArgs,i as parseImportShardArgs,g as planAggregateLookup,Ue as pointInBoundingBox,pe as pullExternalSourceIncrementalTick,Ee as pullExternalSourceTick,Er as rankTableName,xr as reactiveCacheKey,I as readAggregateValue,b as readAuthMetrics,rr as readBookmark,Qe as readCapturedMail,Ao as readCdcChanges,ie as readExternalSourceBaseline,Re as readFunctionMetricBuckets,Ae as readFunctionMetricIndexHits,Ne as readFunctionMetrics,ge as readFunctionMetricsTotals,Y as readMigrationStatus,We as readTablePage,y as recordAuthEvent,Ze as recordCapturedMail,Ce as recordFunctionMetric,ee as renderSql,Sr as resolveRankPartition,hr as resolveRelationPredicates,Lr as resolveWith,V as runDataMigration,se as runExternalSourceTick,io as runReadonlySql,Ur as runRowValidators,Oo as runShardMigrations,So as runTriggers,Wr as scoreDocument,_o as selectExpiredIds,s as selectExportTables,C as selectIndexForAggregate,M as selectIndexForCount,h as selectIndexForGroupBy,ve as selectMatchingIds,Ir as serveRelationFanout,lr as softDeleteScope,mr as sortColumnName,Do as stableStringify,Uo as stableWireKey,vr as stringifySearchText,bo as subscriptionListDeltas,S as throwingScheduler,Hr as tokenizeSearch,No as trimCdcChanges,l as validateImportRow};
@@ -0,0 +1 @@
1
+ const b="0123456789bcdefghjkmnpqrstuvwxyz",L=9,p=63710088e-1,g=Math.PI/180,w=[Number.POSITIVE_INFINITY,5009400,1252300,156500,39100,4900,1200,152.9,38.2,4.77,1.19,.149,.037],q=w.map((t,n)=>n%2===0?t/2:t),v=.01,I=Math.acos(v)/g,k=2,x=t=>t/p/g,B=t=>{const n=5*t;return{latBands:2**Math.floor(n/2),lngSectors:2**Math.ceil(n/2)}},S=t=>Math.min(Math.max(Math.trunc(t),1),12),z=(t,n)=>{const a=S(n);let o=-90,e=90,s=-180,r=180,u="",i=0,h=0,M=!0;for(;u.length<a;){if(M){const c=(s+r)/2;t.lng>=c?(h=h*2+1,s=c):(h*=2,r=c)}else{const c=(o+e)/2;t.lat>=c?(h=h*2+1,o=c):(h*=2,e=c)}M=!M,i<4?i+=1:(u+=b[h]??"0",i=0,h=0)}return u},E=(t,n)=>{const a=(n.lat-t.lat)*g,o=(n.lng-t.lng)*g,e=t.lat*g,s=n.lat*g,r=Math.sin(a/2)**2+Math.cos(e)*Math.cos(s)*Math.sin(o/2)**2;return 2*p*Math.asin(Math.min(1,Math.sqrt(r)))},G=(t,n)=>{const a=Math.min(90,Math.abs(n)+x(t)),o=Math.max(Math.cos(a*g),v);for(let e=w.length-1;e>=1;e-=1){const s=w[e],r=q[e];if(s!==void 0&&r!==void 0&&s*o>=t&&r>=t)return e}return 1},C={east:["bc01fg45238967deuvhjyznpkmstqrwx","p0r21436x8zb9dcf5h7kjnmqesgutwvy"],north:["p0r21436x8zb9dcf5h7kjnmqesgutwvy","bc01fg45238967deuvhjyznpkmstqrwx"],south:["14365h7k9dcfesgujnmqp0r2twvyx8zb","238967debc01fg45kmstqrwxuvhjyznp"],west:["238967debc01fg45kmstqrwxuvhjyznp","14365h7k9dcfesgujnmqp0r2twvyx8zb"]},N={east:["bcfguvyz","prxz"],north:["prxz","bcfguvyz"],south:["028b","0145hjnp"],west:["0145hjnp","028b"]},l=(t,n)=>{const a=t.toLowerCase(),o=a.at(-1)??"";let e=a.slice(0,-1);const s=a.length%2===0?0:1;return N[n][s].includes(o)&&e!==""&&(e=l(e,n)),e+(b[C[n][s].indexOf(o)]??"")},O=(t,n,a)=>{const o=Math.min(a,k),{latBands:e,lngSectors:s}=B(o),r=180/e,u=360/s,i=x(n),h=Math.max(-90,t.lat-i),M=Math.min(90,t.lat+i),c=new Set;for(let d=0;d<e;d+=1){const m=-90+d*r;if(m+r<h||m>M)continue;const y=m+r/2;for(let f=0;f<s;f+=1){const j=-180+(f+.5)*u;c.add(z({lat:y,lng:j},o))}}return[...c]},P=(t,n)=>{const a=Math.max(n,1),o=G(a,t.lat);if(Math.min(90,Math.abs(t.lat)+x(a))>=I)return O(t,a,o);const e=z(t,o),s=l(e,"north"),r=l(e,"south"),u=[e,s,r,l(e,"east"),l(e,"west"),l(s,"east"),l(s,"west"),l(r,"east"),l(r,"west")];return[...new Set(u)]},T=(t,n)=>t.lat>=n.sw.lat&&t.lat<=n.ne.lat&&t.lng>=n.sw.lng&&t.lng<=n.ne.lng,_=t=>({lat:(t.sw.lat+t.ne.lat)/2,lng:(t.sw.lng+t.ne.lng)/2}),F=t=>{const n=_(t);return P(n,Math.max(E(n,t.ne),1))};export{L as GEO_DEFAULT_PRECISION,_ as boundingBoxCenter,F as boundingBoxGeohashes,P as coveringGeohashes,z as encodeGeohash,E as haversineMeters,T as pointInBoundingBox};
@@ -1 +1 @@
1
- import{LunoraError as N}from"@lunora/errors";import{sql as t}from"drizzle-orm";import{matchesStaticWhere as Be,aggregateSqlFunction as Ne,normalizeCountArgument as bt,throwingScheduler as yt}from"./AGGREGATE_SQL_FUNCTION-QYaiuty4.mjs";import{encodeAggregateKey as de,foldAggregateTally as _t,aggregateTableName as Te,coerceAggregateNumber as Fe,readAggregateValue as qe}from"./aggregateTableName-G-eXyjcz.mjs";import{mergeWhere as oe,CountRlsUnsupportedError as Ue,selectIndexForGroupBy as Nt,selectIndexForCount as Tt,selectIndexForAggregate as Rt}from"./CountRlsUnsupportedError-Cl8XpYDL.mjs";import{appendCdcChange as St}from"./CDC_LOG_TABLE-E_J5LPoK.mjs";import{CDC_LOG_TABLE as Qn,applyCdcChanges as Xn,bumpCdcEpoch as Zn,minCdcSeq as er,readCdcChanges as tr,readCdcCursor as nr,readCdcEpoch as rr,trimCdcChanges as ir}from"./CDC_LOG_TABLE-E_J5LPoK.mjs";import{r as v}from"./do-exec-BLe9lLrN.mjs";import{N as st,s as X,L as fe,a as ce,d as te,m as Q,g as lt,p as Le,T as ee,u as At,E as dt,$ as Ye}from"./do-sql-BYIQTG3z.mjs";import{param as Ke}from"./renderSql-B5lF5Jd9.mjs";import{encodeGeohash as It,GEO_DEFAULT_PRECISION as vt,coveringGeohashes as kt,boundingBoxGeohashes as Mt,pointInBoundingBox as Lt,haversineMeters as xt}from"./GEO_DEFAULT_PRECISION-CWAm_oYY.mjs";import{sortColumnName as Se,matchesRankStaticWhere as ct,encodePartitionKey as De,rankTableName as Ae,resolveRankPartition as ft,RANK_TIEBREAK as we}from"./RANK_TIEBREAK-DtX8zQyc.mjs";import{stringifySearchText as ut,ftsTableName as ht,tokenizeSearch as $t,buildFtsMatch as Ct,scoreDocument as Dt}from"./buildFtsMatch-CV0Z7PWv.mjs";import{t as ue}from"./serialize-sql-DiRzL7A4.mjs";import{SCAN_DEP as Y}from"./SCAN_DEP-D_yR9EeV.mjs";import{decodeCursor as Ce,normalizeOrderKeys as Ot,buildSeekWhere as pt,applySelect as Qe,encodeCursor as Pe,softDeleteScope as Ee,buildSeekBeforeWhere as Wt}from"./applySelect-Bq2KOrkL.mjs";import Bt from"./NotFoundError-J3tjf4Uo.mjs";import{assertFlatPredicate as je,resolveRelationPredicates as Xe}from"./DEFAULT_MAX_RELATION_KEYS-BRdmX7WW.mjs";import{runRowValidators as He,resolveWith as Ze,applyOnDelete as Ft,fanOutScalarCounts as qt}from"./applyOnDelete-BvQN7pDL.mjs";import{guardWriter as Ut}from"./RLS_UNWRAP_SYMBOL-C6_WX3dG.mjs";import{createSystemReader as jt}from"./createSystemReader-DcDcrtM3.mjs";import{ConflictError as Re}from"./ConflictError-C8GtJmjS.mjs";import{runTriggers as Ht}from"./hasTrigger-_rexbWMO.mjs";import{compileWhereSql as he}from"./compileWhereSql-BLcfs4QW.mjs";import{backfillAggregateIndexes as ar,backfillRankIndexes as sr}from"./backfillAggregateIndexes-BAQ3Fwwh.mjs";import{e as dr,t as cr,r as fr,o as ur,l as hr,p as $r,_ as pr,a as wr,b as mr,d as gr,m as Er,u as br,S as yr,T as _r}from"./ctx-db-idempotency-wiVoGnpQ.mjs";import{runShardMigrations as Tr}from"./runShardMigrations-bxOHpfID.mjs";import{a as Sr,s as Ar}from"./ctx-db-shapes-DzX_H5q8.mjs";const Pt=(i,o,n)=>[...i.partitionBy??[],...i.sortBy.map(s=>s.field),...i.where?Object.keys(i.where):[]].every(s=>o[s]===n[s]),Gt=(i,o,n,s,l,c)=>{if(l&&c&&Pt(n,l,c))return;const E=Ae(o,n.name);if(l&&v(i,t`DELETE FROM ${t.identifier(E)} WHERE ${t.identifier("__id__")} = ${s}`),!c||n.where&&!ct(c,n.where))return;const w=n.sortBy.map((u,S)=>Se(S)),_=t.join(["__id__","__partition__",...w].map(u=>t.identifier(u)),t`, `),T=De(n.partitionBy??[],c),k=n.sortBy.map(u=>ue(c[u.field]??null)),b=t.join([s,T,...k].map(u=>Ke(u)),t`, `);v(i,t`INSERT INTO ${t.identifier(E)} (${_}) VALUES (${b})`)},Kt=i=>{const{broadcast:o,invalidateCache:n,recordCdc:s,schema:l,sql:c}=i,E=new Set,w=new Set,_=(A,m)=>{const I=`${A}::${m.name}`;if(E.has(I))return;const F=Te(A,m.name),W=m.by??[],H=new Map,j=v(c,t`SELECT id, _creationTime, ${t.identifier(X)} FROM ${t.identifier(A)}`).toArray();for(const q of j){const L=fe(q);if(!L||m.where&&!Be(L,m.where))continue;const P=de(W,L);_t(H,P,m,L)}v(c,t`DELETE FROM ${t.identifier(F)}`);const G=32,B=[...H];for(let q=0;q<B.length;q+=G){const L=B.slice(q,q+G),P=t.join(L.map(([U,V])=>t`(${U}, ${V.value}, ${V.count})`),t`, `);v(c,t`INSERT INTO ${t.identifier(F)} (${ce}, ${te}, ${Q}) VALUES ${P}`)}E.add(I)},T=(A,m,I)=>{const F=m.by??[],W=Ne(m.op),H=m.field??"",j=[];for(const q of F){const L=ue(I[q]??null);L===null?j.push(t`${ee(q)} IS NULL`):j.push(t`${ee(q)} = ${L}`)}for(const[q,L]of Object.entries(m.where??{})){const P=L!==null&&typeof L=="object"&&!Array.isArray(L)?L.eq:L,U=ue(P);U===null?j.push(t`${ee(q)} IS NULL`):j.push(t`${ee(q)} = ${U}`)}const G=j.length>0?t` WHERE ${t.join(j,t` AND `)}`:t``,B=ee(H);return{value:v(c,t`SELECT ${t.raw(W)}(${B}) AS value FROM ${t.identifier(A)}${G}`).one().value??null}},k=(A,m,I,F)=>{const W=Te(A,m.name),{op:H}=m,j=m.field??"",G=L=>{v(c,t`DELETE FROM ${t.identifier(W)} WHERE ${ce} = ${L} AND ${Q} <= 0`)},B=I&&(!m.where||Be(I,m.where))?I:void 0,q=F&&(!m.where||Be(F,m.where))?F:void 0;if(!(!B&&!q)){if(H==="count"){for(const[L,P]of[[B,-1],[q,1]]){if(!L)continue;const U=de(m.by??[],L);v(c,Le(W,U,P,P,t`${te} = ${te} + excluded.${te}, ${Q} = ${Q} + excluded.${Q}`))}B&&G(de(m.by??[],B));return}if(H==="sum"||H==="avg"){for(const[L,P]of[[B,-1],[q,1]]){if(!L)continue;const U=Fe(L[j]);if(U===void 0)continue;const V=de(m.by??[],L);v(c,Le(W,V,P*U,P,t`${te} = COALESCE(${te}, 0) + excluded.${te}, ${Q} = ${Q} + excluded.${Q}`))}B&&G(de(m.by??[],B));return}if(B){const L=de(m.by??[],B),P=Fe(B[j]),U=v(c,t`SELECT ${te} AS value, ${Q} AS count FROM ${t.identifier(W)} WHERE ${ce} = ${L}`).toArray()[0],V=(U?.count??0)-1;if(V<=0)v(c,t`DELETE FROM ${t.identifier(W)} WHERE ${ce} = ${L}`);else if(U&&P!==void 0&&U.value!==null&&P===U.value){const re=T(A,m,B);v(c,t`UPDATE ${t.identifier(W)} SET ${te} = ${re.value}, ${Q} = ${V} WHERE ${ce} = ${L}`)}else v(c,t`UPDATE ${t.identifier(W)} SET ${Q} = ${Q} - 1 WHERE ${ce} = ${L}`)}if(q){const L=de(m.by??[],q),P=Fe(q[j]);if(P===void 0)v(c,Le(W,L,null,1,t`${Q} = ${Q} + 1`));else{const U=H==="min"?"MIN":"MAX";v(c,Le(W,L,P,1,t`${te} = ${t.raw(U)}(COALESCE(${te}, excluded.${te}), excluded.${te}), ${Q} = ${Q} + 1`))}}}},b=A=>{const m=l.tables[A]?.aggregateIndexes;if(!(!m||m.length===0))for(const I of m)_(A,I)},u=(A,m,I)=>{const F=l.tables[A]?.aggregateIndexes;if(!(!F||F.length===0))for(const W of F)k(A,W,m,I)},S=(A,m)=>{const I=`${A}::rank::${m.name}`;if(w.has(I))return;const F=Ae(A,m.name),W=v(c,t`SELECT id, _creationTime, ${t.identifier(X)} FROM ${t.identifier(A)}`).toArray();v(c,t`DELETE FROM ${t.identifier(F)}`);const H=m.sortBy.map((G,B)=>Se(B)),j=t.join(["__id__","__partition__",...H].map(G=>t.identifier(G)),t`, `);for(const G of W){const B=fe(G);if(!B||m.where&&!ct(B,m.where))continue;const q=De(m.partitionBy??[],B),L=m.sortBy.map(U=>ue(B[U.field]??null)),P=t.join([B._id,q,...L].map(U=>Ke(U)),t`, `);v(c,t`INSERT INTO ${t.identifier(F)} (${j}) VALUES (${P})`)}w.add(I)},M=A=>{const m=l.tables[A]?.rankIndexes;if(!(!m||m.length===0))for(const I of m)S(A,I)},D=(A,m,I,F)=>{const W=l.tables[A]?.rankIndexes;if(!(!W||W.length===0))for(const H of W)Gt(c,A,H,m,I,F)},O=(A,m,I)=>{const F=l.tables[A]?.searchIndexes;if(!(!F||F.length===0||!st(c)))for(const W of F){const H=ht(A,W.name);v(c,t`DELETE FROM ${t.identifier(H)} WHERE ${t.identifier("__id__")} = ${m}`),I&&v(c,t`INSERT INTO ${t.identifier(H)} (${t.identifier("__text__")}, ${t.identifier("__id__")}) VALUES (${ut(I[W.field])}, ${m})`)}},Z=(A,m,I)=>{const F=l.tables[A]?.geoIndexes;if(!(!F||F.length===0))for(const W of F){const H=lt(A,W.name);v(c,t`DELETE FROM ${t.identifier(H)} WHERE ${t.identifier("__id__")} = ${m}`);const j=I?.[W.field];if(j!==null&&typeof j=="object"&&typeof j.lat=="number"&&typeof j.lng=="number"){const{lat:G,lng:B}=j,q=It({lat:G,lng:B},W.precision??vt);v(c,t`INSERT INTO ${t.identifier(H)} (${t.identifier("__id__")}, ${t.identifier("__geohash__")}, ${t.identifier("__lat__")}, ${t.identifier("__lng__")}) VALUES (${m}, ${q}, ${G}, ${B})`)}}};return{ensureBackfilledForTable:b,ensureBackfilledIndex:_,ensureRankBackfilled:S,ensureRankBackfilledForTable:M,syncAggregates:u,syncCompanionsForInsert:(A,m,I)=>{O(A,m,I),Z(A,m,I),u(A,void 0,I),D(A,m,void 0,I),n(A,m),s(A,m,"insert",I),o({key:m,op:"insert",row:I,table:A})},syncGeo:Z,syncRanks:D,syncSearch:O}},Vt="__doc__",Jt=i=>{const o=JSON.stringify(i),n=new TextEncoder().encode(o);let s="";for(const l of n)s+=String.fromCodePoint(l);return btoa(s)},zt=i=>i.after?[i.after.partitionKey,...i.after.sortValues,i.after.rowId]:i.cursor?Ce(i.cursor):void 0,Yt=(i,o,n)=>{if(i?.length!==1+o.length+1)return;const s=[{column:"__partition__",direction:"asc"}];for(const[c,E]of o.entries())s.push({column:E,direction:n[c]?.direction??"asc"});s.push({column:we,direction:"asc"});const l=[];for(const[c,E]of s.entries()){const w=[];for(const[T,k]of s.slice(0,c).entries())w.push(t`${t.identifier(k.column)} IS ${i[T]}`);w.push(t`${t.identifier(E.column)} ${t.raw(E.direction==="desc"?"<":">")} ${i[c]}`);const[_]=w;l.push(w.length===1&&_!==void 0?_:t`(${t.join(w,t` AND `)})`)}return t`(${t.join(l,t` OR `)})`},wt=null,Qt=(i,o)=>{if(i===void 0)return wt;const n=[i.__partition__,...o.map(s=>i[s]),i[we]];return Jt(n)},Xt=(i,o,n)=>{const s=[];for(const l of i){const c=l[we];if(typeof c!="string")continue;const E=o.get(c);if(!E)continue;const w=typeof l.__partition__=="string"?l.__partition__:"",_=n.map(T=>l[T]??null);s.push({doc:E,key:{partitionKey:w,rowId:c,sortValues:_}})}return s},Zt=(i,o,n)=>{const{rowToDocument:s}=i,l=new Map;if(n.length===0)return l;const c=t.join(n.map(w=>Ke(w)),t`, `),E=v(i.sql,t`SELECT id, _creationTime, ${t.identifier(Vt)} FROM ${t.identifier(o)} WHERE id IN (${c})`).toArray();for(const w of E){const _=s(w),T=w.id;_&&typeof T=="string"&&l.set(T,_)}return l},et=(i,o,n,s)=>{const{assertRankPartitionLocal:l,ensureRankBackfilled:c,onRead:E,schema:w}=i,_=w.tables[o];if(!_)throw new N("INTERNAL",`unknown table: ${o}`);const T=_.rankIndexes?.find(V=>V.name===n);if(!T)throw new N("INTERNAL",`unknown rankIndex "${n}" on table "${o}"`);l(o,_,T),E(o,Y),c(o,T);const k=Ae(o,T.name),b=T.sortBy.map((V,re)=>Se(re)),u=Math.max(1,Math.min(1e3,Math.floor(s.take??100))),S=oe(s.baseWhere,s.where),M=ft(T,S),D=[t`${t.identifier("__partition__")} ASC`];for(const[V,re]of b.entries()){const se=T.sortBy[V]?.direction;D.push(t`${t.identifier(re)} ${t.raw(se==="desc"?"DESC":"ASC")}`)}D.push(t`${t.identifier(we)} ASC`);const O=[];typeof s.partitionKey=="string"?O.push(t`${t.identifier("__partition__")} = ${s.partitionKey}`):M&&O.push(t`${t.identifier("__partition__")} = ${De(T.partitionBy??[],M)}`);const Z=zt(s),A=Yt(Z,b,T.sortBy);A&&O.push(A);const m=t.identifier(we),I=t.identifier("__partition__"),F=O.length>0?t` WHERE ${t.join(O,t` AND `)}`:t``,W=b.length>0?t`${m}, ${I}, ${t.join(b.map(V=>t.identifier(V)),t`, `)}`:t`${m}, ${I}`,H=t`SELECT ${W} FROM ${t.identifier(k)}${F} ORDER BY ${t.join(D,t`, `)} LIMIT ${t.raw(String(u+1))}`,j=v(i.sql,H).toArray(),G=j.length>u,B=G?j.slice(0,u):j,q=B.map(V=>V[we]),L=Xt(B,Zt(i,o,q),b),P=G?Qt(B.at(-1),b):wt,U=T.sortBy.map(V=>V.direction==="desc"?"desc":"asc");return{continueCursor:P,directions:U,hasMore:G,rows:L}},en=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,tn=i=>{if(!en.test(i))throw new N("INTERNAL",`invalid clientId ${JSON.stringify(i)}: a client-supplied row id must be a UUID`)},tt=50,mt=500,ge=(i,o,n)=>{const s=o??mt;if(i>s)throw new N("BATCH_LIMIT_EXCEEDED",`${n}: batch of ${String(i)} exceeds the limit of ${String(s)} (raise options.limit or chunk the call)`,{status:400})},nn=i=>{const o={eq:(n,s)=>(i.sqlConditions.push({comparator:"=",field:n,value:s}),o),gt:(n,s)=>(i.sqlConditions.push({comparator:">",field:n,value:s}),o),gte:(n,s)=>(i.sqlConditions.push({comparator:">=",field:n,value:s}),o),lt:(n,s)=>(i.sqlConditions.push({comparator:"<",field:n,value:s}),o),lte:(n,s)=>(i.sqlConditions.push({comparator:"<=",field:n,value:s}),o)};return o},rn=(i,o)=>{const n={eq:(s,l)=>{if(!i.definition.filterFields?.includes(s))throw new N("INTERNAL",`field "${s}" is not a filter field of search index "${i.indexName}" on table "${o}"`);return i.filters.push({field:s,value:l}),n},search:(s,l)=>{if(s!==i.definition.field)throw new N("INTERNAL",`search index "${i.indexName}" on table "${o}" indexes "${i.definition.field}", not "${s}"`);const c=i;return c.field=s,c.query=l,c.hasQuery=!0,n}};return n},on=(i,o,n,s,l)=>{const c=$t(n.query);if(c.length===0)return[];const E=ht(o,n.indexName),w=[t`f.${t.identifier("__text__")} MATCH ${Ct(c)}`];for(const b of n.filters)w.push(t`${ee(b.field)} = ${ue(b.value)}`);l&&w.push(l);let _=t`SELECT m.id, m._creationTime, m.${t.identifier(X)} FROM ${t.identifier(E)} f JOIN ${t.identifier(o)} m ON m.id = f.${t.identifier("__id__")} WHERE ${t.join(w,t` AND `)} ORDER BY f.rank, m._creationTime DESC`;typeof s=="number"&&(_=t`${_} LIMIT ${t.raw(String(Math.max(0,Math.floor(s))))}`);const T=v(i,_).toArray(),k=[];for(const b of T){const u=fe(b);u&&k.push(u)}return k},an=(i,o,n,s,l)=>{const c=$t(n.query);if(c.length===0)return[];const E=[];for(const b of n.filters)E.push(t`${ee(b.field)} = ${ue(b.value)}`);l&&E.push(l);let w=t`SELECT id, _creationTime, ${t.identifier(X)} FROM ${t.identifier(o)}`;E.length>0&&(w=t`${w} WHERE ${t.join(E,t` AND `)}`);const _=v(i,w).toArray(),T=[];for(const b of _){const u=fe(b);if(!u)continue;const S=Dt(ut(u[n.field]),c);S>0&&T.push({creationTime:typeof u._creationTime=="number"?u._creationTime:0,doc:u,score:S})}T.sort((b,u)=>u.score-b.score||u.creationTime-b.creationTime);const k=T.map(b=>b.doc);return typeof s=="number"?k.slice(0,Math.max(0,Math.floor(s))):k},sn=(i,o)=>{const n=i,s={near:(l,c)=>{if(n.within)throw new N("INTERNAL",`geo index "${n.indexName}" on table "${o}": call .near() or .within(), not both`);return n.near={point:{lat:l.lat,lng:l.lng},radiusMeters:c},s},within:l=>{if(n.near)throw new N("INTERNAL",`geo index "${n.indexName}" on table "${o}": call .near() or .within(), not both`);return n.within={ne:{lat:l.ne.lat,lng:l.ne.lng},sw:{lat:l.sw.lat,lng:l.sw.lng}},s}};return s},ln=(i,o)=>{const n=i[o];if(n===null||typeof n!="object")return;const{lat:s,lng:l}=n;return typeof s=="number"&&typeof l=="number"?{lat:s,lng:l}:void 0},dn=(i,o)=>{const n=ln(i,o.definition.field);if(!n)return;const s=typeof i._creationTime=="number"?i._creationTime:0;if(o.near){const l=xt(o.near.point,n);return l<=o.near.radiusMeters?{creationTime:s,distance:l}:void 0}return Lt(n,o.within)?{creationTime:s,distance:0}:void 0},cn=(i,o,n,s,l)=>{if(!n.near&&!n.within)throw new N("INTERNAL",`geo index "${n.indexName}" on table "${o}": call .near(point, radius) or .within(box)`);const c=n.near?kt(n.near.point,n.near.radiusMeters):Mt(n.within),E=lt(o,n.indexName),w=c.map(S=>t`(g.${t.identifier("__geohash__")} >= ${S} AND g.${t.identifier("__geohash__")} < ${`${S}{`})`),_=[t`(${t.join(w,t` OR `)})`];l&&_.push(l);const T=t`SELECT m.id, m._creationTime, m.${t.identifier(X)} FROM ${t.identifier(E)} g JOIN ${t.identifier(o)} m ON m.id = g.${t.identifier("__id__")} WHERE ${t.join(_,t` AND `)}`,k=v(i,T).toArray(),b=[];for(const S of k){const M=fe(S),D=M?dn(M,n):void 0;M&&D&&b.push({creationTime:D.creationTime,distance:D.distance,doc:M})}b.sort((S,M)=>S.distance-M.distance||M.creationTime-S.creationTime);const u=b.map(S=>S.doc);return typeof s=="number"?u.slice(0,Math.max(0,Math.floor(s))):u},fn=(i,o,n,s,l)=>{const{geo:c}=n;if(!c)throw new N("INTERNAL","runGeoTerminal called without a staged geo query");const E=n.inMemoryFilters.length>0,w=cn(i,o,c,E?void 0:l,s);if(!E)return w;const _=[];for(const T of w)if(n.inMemoryFilters.every(k=>k(T))&&(_.push(T),typeof l=="number"&&_.length>=l))break;return _},un=(i,o,n,s,l,c)=>{const E=[];for(const k of n.sqlConditions)E.push(t`${ee(k.field)} ${t.raw(k.comparator)} ${ue(k.value)}`);s&&E.push(s);let w=t`SELECT id, _creationTime, ${t.identifier(X)} FROM ${t.identifier(o)}`;E.length>0&&(w=t`${w} WHERE ${t.join(E,t` AND `)}`),w=t`${w} ORDER BY ${l}`,typeof c=="number"&&n.inMemoryFilters.length===0&&(w=t`${w} LIMIT ${t.raw(String(Math.max(0,Math.floor(c))))}`);const _=v(i,w).toArray(),T=[];for(const k of _){const b=fe(k);if(b&&n.inMemoryFilters.every(u=>u(b))&&(T.push(b),typeof c=="number"&&T.length>=c))break}return T},pe={fieldRef:ee,serialize:ue},hn=i=>{let o=0;const n=[],s={fieldRef:ee,relationExists:l=>{const{childWhere:c,negated:E,parentTable:w,relation:_}=l,T=`__rel_${String(o)}`,k=n.at(-1)??w;o+=1,i(_.table,Y);const b=_.kind==="one"?_.field:_.references,u=_.kind==="one"?_.references:_.field,S=t`${Ye(T,u)} = ${Ye(k,b)}`;n.push(T);const M=he(c,s);n.pop();const D=M?t`${S} AND ${M}`:S,O=t`EXISTS (SELECT 1 FROM ${t.identifier(_.table)} AS ${t.identifier(T)} WHERE ${D})`;return E?t`NOT ${O}`:O},serialize:ue};return s},gt=i=>{const o=i.map(n=>t`${ee(n.field)} ${t.raw(n.direction==="desc"?"DESC":"ASC")}`);return i.some(n=>n.field==="_id"||n.field==="id")||o.push(t`${ee("id")} ASC`),t.join(o,t`, `)},$n={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},pn=i=>{const o=i.order;return i.indexFields.length>0?i.indexFields.map(n=>({direction:o,field:n})):[{direction:o,field:"_creationTime"}]},wn=(i,o,n,s)=>{const l=i.sqlConditions.map(c=>({[c.field]:{[$n[c.comparator]??"eq"]:c.value}}));if(n&&l.push(pt(o,Ce(n))),s&&l.push(Wt(o,Ce(s))),l.length!==0)return l.length===1?l[0]:{AND:l}},mn=(i,o,n)=>{const s=[];for(const l of i){const c=fe(l);if(c&&o.every(E=>E(c))&&(s.push(c),n!==void 0&&s.length>n))break}return s},gn=(i,o,n,s,l)=>{const c=Math.max(0,Math.floor(s.numItems)),E=pn(n),w=typeof s.endCursor=="string",_=he(wn(n,E,s.cursor,s.endCursor),pe),T=l&&_?t`${_} AND ${l}`:l??_;let k=t`SELECT id, _creationTime, ${t.identifier(X)} FROM ${t.identifier(o)}`;T&&(k=t`${k} WHERE ${T}`),k=t`${k} ORDER BY ${gt(E)}`;const b=n.inMemoryFilters.length>0;!b&&!w&&(k=t`${k} LIMIT ${t.raw(String(c+1))}`);const u=v(i,k).toArray(),S=mn(u,n.inMemoryFilters,b||w?void 0:c);if(w){const Z=S.length>=2?S[Math.floor(S.length/2)-1]:void 0;return{continueCursor:s.endCursor??null,isDone:!0,page:S,splitCursor:Z?Pe(Z,E):null}}const M=S.length>c,D=M?S.slice(0,c):S,O=D.at(-1);return{continueCursor:M&&O?Pe(O,E):null,isDone:!M,page:D}};class En extends N{constructor(o="unique() found more than one matching document"){super("NOT_UNIQUE",o,{name:"NotUniqueError"})}}const bn=/\s/u,yn=String.fromCodePoint(0),nt=(i,o,n)=>{if(!i.tables[o])throw new N("INTERNAL",`unknown table: ${o}`);return typeof n!="string"||n.length===0||bn.test(n)||n.includes(yn)?null:n},_n=(i,o,n,s=()=>{})=>{const l=o.tables[n];if(!l)throw new N("INTERNAL",`unknown table: ${n}`);const c=Ee(l.softDeleteMode,void 0),E=c?he(c,pe):void 0,w={indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[]},_=u=>{const{search:S}=w;if(!S)throw new N("INTERNAL","runSearchFetch called without a staged search");const M=w.inMemoryFilters.length>0,D=M?void 0:u,O=st(i)?on(i,n,S,D,E):an(i,n,S,D,E);if(!M)return O;const Z=[];for(const A of O)if(w.inMemoryFilters.every(m=>m(A))&&(Z.push(A),typeof u=="number"&&Z.length>=u))break;return Z},T=()=>{const u=w.indexFields.length>0?w.indexFields:["_creationTime"],S=w.order==="desc"?"DESC":"ASC";return t.join(u.map(M=>t`${ee(M)} ${t.raw(S)}`),t`, `)},k=u=>w.search?_(u):w.geo?fn(i,n,w,E,u):un(i,n,w,E,T(),u),b={async collect(){return k(void 0)},filter(u){return w.inMemoryFilters.push(u),b},async first(){return k(w.inMemoryFilters.length>0?void 0:1)[0]??null},order(u){return w.order=u==="desc"?"desc":"asc",b},async paginate(u){if(w.search)throw new N("INTERNAL","pagination is not supported on search queries; use .take(n) or .collect()");if(w.geo)throw new N("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");return gn(i,n,w,u,E)},async take(u){return k(u)},async unique(){const u=k(w.inMemoryFilters.length>0?void 0:2);if(u.length>1)throw new En(`unique() on table "${n}" matched ${String(u.length)} documents; expected at most one`);return u[0]??null},withGeoIndex(u,S){const M=(l.geoIndexes??[]).find(O=>O.name===u);if(!M)throw new N("INTERNAL",`unknown geo index "${u}" on table "${n}"`);s(n,u,"geo");const D={definition:M,indexName:u};if(w.geo=D,S(sn(D,n)),!D.near&&!D.within)throw new N("INTERNAL",`geo index "${u}" on table "${n}" requires a .near(point, radius) or .within(box) call`);return b},withIndex(u,S){const M=l.indexes.find(D=>D.name===u);if(!M)throw new N("INTERNAL",`unknown index "${u}" on table "${n}"`);return s(n,u,"index"),w.indexName=u,w.indexFields=M.fields,S&&S(nn(w)),b},withSearchIndex(u,S){const M=(l.searchIndexes??[]).find(O=>O.name===u);if(!M)throw new N("INTERNAL",`unknown search index "${u}" on table "${n}"`);s(n,u,"search");const D={definition:M,field:M.field,filters:[],hasQuery:!1,indexName:u,query:""};if(w.search=D,S(rn(D,n)),!D.hasQuery)throw new N("INTERNAL",`search index "${u}" on table "${n}" requires a .search(field, query) call`);return b}};return b},rt=(i,o,n)=>{const s={...o};for(const[l,c]of dt(i)){if(c.serverDefault){s[l]=c.serverDefault({auth:n});continue}s[l]===void 0&&(c.defaultFn?s[l]=c.defaultFn():"defaultValue"in c&&(s[l]=c.defaultValue))}return s},it=(i,o,n,s)=>{const l=n;for(const[c,E]of dt(i)){if(E.serverDefault){c in o&&(l[c]=E.serverDefault({auth:s}));continue}E.onUpdateFn&&!(c in o)&&(l[c]=E.onUpdateFn())}},ot=(i,o)=>{for(const n of Object.keys(o))if(o[n]===void 0)throw new N("INTERNAL",`Cannot ${i} field '${n}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},Nn=/unique constraint failed/i,Tn=i=>i instanceof Error&&Nn.test(i.message),Ge=(i,o,n)=>{try{v(i,n)}catch(s){throw Tn(s)?new Re(`unique constraint violation on "${o}"`,"unique"):s}},xe=(i,o,n)=>{if(Ge(i,o,n),v(i,t`SELECT changes() AS changed`).one().changed===0)throw new Re(`optimistic concurrency conflict on "${o}" — the row changed during this mutation; refetch and retry`,"occ")},at=(i,o,n,s,l,c,E)=>{const w=[];for(let b=0;b<n.length+1;b+=1){const u=[];for(let O=0;O<b;O+=1)u.push(t`${t.identifier(n[O])} IS ${c[O]}`);const S=n[b],M=s[b];if(S!==void 0&&M!==void 0){const O=M.direction==="desc"?">":"<";u.push(t`${t.identifier(S)} ${t.raw(O)} ${c[b]}`)}else u.push(t`${t.identifier(we)} < ${E}`);const[D]=u;w.push(u.length===1&&D!==void 0?D:t`(${t.join(u,t` AND `)})`)}const _=t.join(w,t` OR `),T=v(i,t`SELECT COUNT(*) AS c FROM ${t.identifier(o)} WHERE ${t.identifier("__partition__")} = ${l} AND (${_})`).one(),k=v(i,t`SELECT COUNT(*) AS c FROM ${t.identifier(o)} WHERE ${t.identifier("__partition__")} = ${l}`).one();return{before:T.c,total:k.c}},Jn=i=>{const{sql:o}=i,{schema:n}=i,s=i.broadcast??(()=>{}),l=i.onRead??(()=>{}),c=i.onIndexUse??(()=>{}),E=i.onWrite??(()=>{}),{cache:w}=i,_=i.clock??(()=>Date.now()),T=i.idGenerator??(()=>crypto.randomUUID()),k=i.scheduler??yt,{globalDb:b}=i,u=i.auth??{identity:null,userId:null},S=i.cdc??!1,M=k,D=jt({scheduler:typeof M.list=="function"&&typeof M.get=="function"?M:void 0,storage:i.storage}),O=(e,r,a,p)=>{S&&St(o,_(),e,r,a,p)},Z=e=>n.tables[e]?.shardMode?.kind==="global",A=(e,r)=>{if(Z(e)){if(!b)throw new N("INTERNAL",`cross-backend ${r} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return b}return J},m=e=>A(e,"cascade"),I=(e,r)=>{if(Z(e)){if(!b)throw new N("INTERNAL",`${r} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return b}},F=()=>b,W=(e,r)=>A(e,"relation load").findMany(e,r),H=(e,r)=>(Z(e)&&l(e,Y),W(e,r)),j=e=>!Z(e.table),G=i.relationExistsPushDown??"auto",B=G!=="never",{maxRelationKeys:q}=i,L=(e,r,a)=>Xe(e,{fetcher:H,maxRelationKeys:q,relationBaseWhere:a,schema:n,tableName:r}),P=async(e,r,a,p)=>{const $=I(e,"relation grouped count");if($)return l(e,Y),qt((C,ie)=>$.count(C,ie),e,r,a,p);const h=n.tables[e];if(!h)throw new N("INTERNAL",`unknown table: ${e}`);l(e,Y);const d=Ee(h.softDeleteMode,void 0),f={[r]:{in:a}},g=oe(oe(f,p),d),R=await L(g,e,void 0),y=he(R,pe),x=ee(r);let z=t`SELECT ${x} AS __fk__, COUNT(*) AS count FROM ${t.identifier(e)}`;y&&(z=t`${z} WHERE ${y}`),z=t`${z} GROUP BY ${x}`;const K=v(o,z).toArray();return new Map(K.map(C=>[C.__fk__,C.count]))};let U=0;const V=new Set;for(const[e,r]of Object.entries(n.tables))for(const a of Object.values(r.triggerMap??{}))V.add(`${e} ${a.timing} ${a.op}`);const re=(e,r,a)=>V.has(`${e} ${r} ${a}`),se=async(e,r,a)=>{if(U+=1,U>tt)throw U-=1,new Re(`trigger recursion exceeded ${String(tt)} levels on "${a.table}" — check for a self-triggering write`,"trigger");try{await Ht({ctx:Et,event:a,op:r,schema:n,tableName:a.table,timing:e})}finally{U-=1}},{ensureBackfilledForTable:be,ensureBackfilledIndex:Oe,ensureRankBackfilled:We,ensureRankBackfilledForTable:ye,syncAggregates:Ie,syncCompanionsForInsert:Ve,syncGeo:ve,syncRanks:_e,syncSearch:ke}=Kt({broadcast:s,invalidateCache:(e,r)=>w?.invalidate(e,r),recordCdc:O,schema:n,sql:o}),Je=(e,r,a)=>{const{shardMode:p}=r;if(p?.kind==="shardBy"&&!(p.field!==void 0&&(a.partitionBy??[]).includes(p.field)))throw Object.assign(new Error(`rank index "${a.name}" on "${e}" partitions across shards (shard key "${p.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})},$e=(e,r)=>{const a=Object.entries(n.tables).filter(([,R])=>R.shardMode?.kind!=="global").map(([R])=>R).filter(R=>r===void 0||R===r);if(a.length===0)return;const p=a.map(R=>t`SELECT ${t.raw(`'${R.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${t.identifier(X)} FROM ${t.identifier(R)} WHERE id = ${e}`),$=t`${t.join(p,t` UNION ALL `)} LIMIT 1`,[h]=v(o,$).toArray();if(!h)return;const d=h.__t__,f=fe(h);if(typeof d!="string"||!f)return;const g=h[X];return{docJson:typeof g=="string"?g:JSON.stringify(g??{}),row:f,tableName:d}},ze={assertRankPartitionLocal:Je,ensureRankBackfilled:We,onRead:l,rowToDocument:fe,schema:n,sql:o},J={system:D,async aggregate(e,r){const a=I(e,"aggregate");if(a)return l(e,Y),a.aggregate(e,r);const p=n.tables[e];if(!p)throw new N("INTERNAL",`unknown table: ${e}`);if(Ne(r.op),r.op==="count")return J.count(e,{baseWhere:r.baseWhere,relationBaseWhere:r.relationBaseWhere,restrictsCounts:r.restrictsCounts,where:r.where});if(!r.field)throw new N("INTERNAL",`aggregate(${e}, { op: "${r.op}" }): "field" is required for non-count reducers`);l(e,Y);const $=Ee(p.softDeleteMode,void 0),h=oe(oe(r.baseWhere,r.where),$),d=await L(h,e,r.relationBaseWhere),f=d!==h;if(p.aggregateIndexes&&!r.baseWhere&&!f&&!$){const K=Rt(p.aggregateIndexes,r.op,r.field,r.where);if(K){Oe(e,K.index);const C=de(K.index.by??[],K.key),ie=Te(e,K.index.name),ae=v(o,t`SELECT ${te} AS value, ${Q} AS count FROM ${t.identifier(ie)} WHERE ${ce} = ${C}`).toArray()[0];return qe(r.op,ae)}}const g=he(d,pe),R=Ne(r.op),y=ee(r.field);let x=t`SELECT ${t.raw(R)}(${y}) AS value FROM ${t.identifier(e)}`;return g&&(x=t`${x} WHERE ${g}`),v(o,x).toArray()[0]?.value??null},asId(e,r){const a=nt(n,e,r);if(a===null)throw new N("BAD_REQUEST",`asId("${e}", …): "${r}" is not a valid id for table "${e}"`,{status:400});return a},async count(e,r){const a=I(e,"count");if(a)return l(e,Y),a.count(e,r);const p=n.tables[e];if(!p)throw new N("INTERNAL",`unknown table: ${e}`);const $=bt(r);if($.restrictsCounts)throw new Ue(e);l(e,Y);const h=Ee(p.softDeleteMode,void 0),d=oe(oe($.baseWhere,$.where),h),f=await L(d,e,$.relationBaseWhere),g=f!==d;if(p.aggregateIndexes&&!$.baseWhere&&!g&&!h){const x=Tt(p.aggregateIndexes,$.where);if(x){Oe(e,x.index);const z=de(x.index.by??[],x.key),K=Te(e,x.index.name),C=v(o,t`SELECT ${te} AS value FROM ${t.identifier(K)} WHERE ${ce} = ${z}`).toArray();return C[0]===void 0?0:C[0].value??0}}const R=he(f,pe);let y=t`SELECT COUNT(*) AS count FROM ${t.identifier(e)}`;return R&&(y=t`${y} WHERE ${R}`),v(o,y).one().count},async delete(e,r,a){const p=$e(e,r);if(!p){const y=r===void 0?F():void 0;y&&await y.delete(e,void 0,a);return}const{docJson:$,row:h,tableName:d}=p,f=n.tables[d],g=a?.hard===!0,R=!g&&f?.softDeleteMode?f.softDeleteMode.field:void 0;if(!(R&&h[R]!==null&&h[R]!==void 0)){if(re(d,"before","delete")&&await se("before","delete",{id:e,op:"delete",previous:h,table:d}),await Ft({deletedId:e,deletedReference:y=>h[y],findHolders:async(y,x,z)=>(await m(y).findMany(y,{includeDeleted:g,where:{[x]:z}})).page,onCascade:(y,x)=>m(y).delete(x,void 0,a),onRestrict:y=>{throw new Re(y,"restrict")},onSetNull:(y,x,z)=>m(y).patch(x,{[z]:null}),schema:n,tableName:d}),be(d),ye(d),R){const y={...h,[R]:_(),_id:e};xe(o,d,t`UPDATE ${t.identifier(d)} SET ${t.identifier(X)} = ${JSON.stringify(y)} WHERE id = ${e} AND ${t.identifier(X)} = ${$}`),ke(d,e,y),ve(d,e,void 0),Ie(d,h,y),_e(d,e,h,void 0),w?.invalidate(d,e),O(d,e,"update",y),s({key:e,op:"update",row:y,table:d}),re(d,"after","delete")&&await se("after","delete",{id:e,op:"delete",previous:h,table:d}),await E({id:e,op:"delete",table:d});return}xe(o,d,t`DELETE FROM ${t.identifier(d)} WHERE id = ${e} AND ${t.identifier(X)} = ${$}`),ke(d,e,void 0),ve(d,e,void 0),Ie(d,h,void 0),_e(d,e,h,void 0),w?.invalidate(d,e),O(d,e,"delete"),s({key:e,op:"delete",table:d}),re(d,"after","delete")&&await se("after","delete",{id:e,op:"delete",previous:h,table:d}),await E({id:e,op:"delete",table:d})}},async deleteAll(e,r){if(!n.tables[e])throw new N("INTERNAL",`unknown table: ${e}`);const a=Math.max(1,r?.chunkSize??mt),p=r?.hard===void 0?void 0:{hard:r.hard},$=Z(e)?void 0:e;let h=0;for(;;){const d=(await J.findMany(e,{limit:a})).page.map(f=>String(f._id));if(d.length===0)break;for(const f of d)await J.delete(f,$,p),h+=1;if(d.length<a)break}return{deleted:h}},async deleteMany(e,r,a){ge(e.length,r?.limit,"deleteMany");for(const p of e)await J.delete(p,a);return{deleted:e.length}},async deleteWhere(e,r,a){const p=I(e,"deleteWhere");let $;if(p)$=(await p.findMany(e,{where:r})).page.map(h=>String(h._id));else{if(!n.tables[e])throw new N("INTERNAL",`unknown table: ${e}`);$=(await J.findMany(e,{where:r})).page.map(h=>String(h._id))}if(ge($.length,a?.limit,"deleteWhere"),J.deleteMany===void 0)throw new N("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return J.deleteMany($,a)},async findFirst(e,r={}){return(await J.findMany(e,{...r,limit:1})).page[0]??null},async findFirstOrThrow(e,r={}){const a=await J.findFirst(e,r);if(a===null)throw new Bt(`findFirstOrThrow: no "${e}" document matched`);return a},async findMany(e,r={}){const a=I(e,"findMany");if(a)return l(e,Y),a.findMany(e,r);const p=n.tables[e];if(!p)throw new N("INTERNAL",`unknown table: ${e}`);const $=!r.where&&!r.baseWhere;$?l(e,Y):l(e);const h=Ot(r.orderBy),d=r.cursor?pt(h,Ce(r.cursor)):void 0;let f=oe(r.baseWhere,r.where);f=oe(f,Ee(p.softDeleteMode,r.includeDeleted)),f=await Xe(f,{canPushExists:B?j:void 0,existsPushMode:G==="always"?"always":"auto",fetcher:H,maxRelationKeys:q,relationBaseWhere:r.relationBaseWhere,schema:n,tableName:e}),d&&(f=f?{AND:[f,d]}:d);const g=B?hn(l):pe,R=he(f,g);let y=t`SELECT id, _creationTime, ${t.identifier(X)} FROM ${t.identifier(e)}`;R&&(y=t`${y} WHERE ${R}`),y=t`${y} ORDER BY ${gt(h)}`;const x=typeof r.limit=="number"?Math.max(0,Math.floor(r.limit)):void 0;x!==void 0&&(y=t`${y} LIMIT ${t.raw(String(x+1))}`);const z=v(o,y).toArray(),K=[];for(const le of z){const ne=fe(le);ne&&(K.push(ne),!$&&typeof ne._id=="string"&&l(e,ne._id))}if(x===void 0)return r.with&&await Ze({groupedCounter:P,fetcher:W,parents:K,relationBaseWhere:r.relationBaseWhere,schema:n,tableName:e,with:r.with}),{continueCursor:null,isDone:!0,page:Qe(K,r.select,r.with)};const C=K.length>x,ie=C?K.slice(0,x):K,ae=ie.at(-1);return r.with&&await Ze({fetcher:W,groupedCounter:P,parents:ie,relationBaseWhere:r.relationBaseWhere,schema:n,tableName:e,with:r.with}),{continueCursor:C&&ae?Pe(ae,h):null,isDone:!C,page:Qe(ie,r.select,r.with)}},async get(e,r){const a=$e(e,r);if(!a){const p=r===void 0?F():void 0;return p?p.get(e):null}return l(a.tableName,e),a.row},async lookupById(e,r){const a=$e(e,r);return a?(l(a.tableName,e),{row:a.row,tableName:a.tableName}):null},async groupBy(e,r){const a=I(e,"groupBy");if(a)return l(e,Y),a.groupBy(e,r);const p=n.tables[e];if(!p)throw new N("INTERNAL",`unknown table: ${e}`);l(e,Y);const $=r.agg??{op:"count"};if(Ne($.op),$.op!=="count"&&!$.field)throw new N("INTERNAL",`groupBy(${e}, { agg: { op: "${$.op}" } }): "field" is required for non-count reducers`);const h=Ee(p.softDeleteMode,void 0),d=oe(oe(r.baseWhere,r.where),h),f=await L(d,e,r.relationBaseWhere),g=f!==d;if(p.aggregateIndexes&&!r.baseWhere&&!g&&!h){const C=Nt(p.aggregateIndexes,$.op,$.field,r.by,r.where);if(C){Oe(e,C.index);const ie=Te(e,C.index.name),ae=Object.keys(C.partial),le=[];if(ae.length===(C.index.by??[]).length&&ae.length>0){const me=de(C.index.by??[],C.partial),Me=v(o,t`SELECT ${te} AS value, ${Q} AS count FROM ${t.identifier(ie)} WHERE ${ce} = ${me}`).toArray();return Me.length>0&&le.push({key:{...C.partial},value:qe($.op,Me[0])}),le}const ne=v(o,t`SELECT ${ce} AS key, ${te} AS value, ${Q} AS count FROM ${t.identifier(ie)}`).toArray();for(const me of ne){const Me=JSON.parse(me.key);le.push({key:Me,value:qe($.op,me)})}return le}}const R=he(f,pe),y=r.by.map(C=>t`${ee(C)} AS ${t.identifier(C)}`);if($.op==="count")y.push(t`COUNT(*) AS value`);else{const{field:C}=$;if(C===void 0)throw new N("INTERNAL",`groupBy(${e}, { agg: { op: "${$.op}" } }): "field" is required for non-count reducers`);y.push(t`${t.raw(Ne($.op))}(${ee(C)}) AS value`)}let x=t`SELECT ${t.join(y,t`, `)} FROM ${t.identifier(e)}`;R&&(x=t`${x} WHERE ${R}`),x=t`${x} GROUP BY ${t.join(r.by.map(C=>ee(C)),t`, `)}`;const z=v(o,x).toArray(),K=[];for(const C of z){const ie={};for(const le of r.by)ie[le]=C[le]??null;const{value:ae}=C;K.push({key:ie,value:ae==null?null:Number(ae)})}return K},async insert(e,r,a){const p=I(e,"insert");if(p){const R=await p.insert(e,r,a);return s({key:R,op:"insert",row:{...r,_id:R},table:e}),R}const $=n.tables[e];if(!$)throw new N("INTERNAL",`unknown table: ${e}`);const h=rt($,r,u);He($,h);let d;a?.clientId!==void 0?(tn(a.clientId),d=a.clientId):a?.allowExplicitId&&typeof h._id=="string"?d=h._id:d=T();const f=a?.allowExplicitId&&typeof h._creationTime=="number"?h._creationTime:_(),g={...h,_creationTime:f,_id:d};return re(e,"before","insert")&&await se("before","insert",{doc:{...g},id:d,op:"insert",table:e}),be(e),ye(e),Ge(o,e,t`INSERT INTO ${t.identifier(e)} (id, _creationTime, ${t.identifier(X)}) VALUES (${d}, ${f}, ${JSON.stringify(g)})`),Ve(e,d,g),re(e,"after","insert")&&await se("after","insert",{doc:g,id:d,op:"insert",table:e}),await E({doc:g,id:d,op:"insert",table:e}),d},async insertManyUnsafe(e,r,a){if(ge(r.length,a?.limit,"insertManyUnsafe"),r.length===0)return[];const p=I(e,"insert");if(p){const f=[];for(const g of r){const R=await p.insert(e,g,{allowExplicitId:a?.allowExplicitId});s({key:R,op:"insert",row:{...g,_id:R},table:e}),f.push(R)}return f}const $=n.tables[e];if(!$)throw new N("INTERNAL",`unknown table: ${e}`);be(e),ye(e);const h=r.map(f=>{const g=rt($,f,u),R=a?.allowExplicitId===!0&&typeof g._id=="string"?g._id:T(),y=a?.allowExplicitId===!0&&typeof g._creationTime=="number"?g._creationTime:_();return{creationTime:y,document:{...g,_creationTime:y,_id:R},id:R}}),d=t.join(h.map(f=>t`(${f.id}, ${f.creationTime}, ${JSON.stringify(f.document)})`),t`, `);Ge(o,e,t`INSERT INTO ${t.identifier(e)} (id, _creationTime, ${t.identifier(X)}) VALUES ${d}`);for(const{document:f,id:g}of h)Ve(e,g,f),await E({doc:f,id:g,op:"insert",table:e});return h.map(f=>f.id)},async insertMany(e,r,a){ge(r.length,a?.limit,"insertMany");const p=a?.skipDuplicates===!0,$=[];for(const h of r)try{$.push(await J.insert(e,h))}catch(d){if(p&&d instanceof Re&&d.kind==="unique")$.push(null);else throw d}return $},normalizeId(e,r){return nt(n,e,r)},async patch(e,r,a){const p=$e(e,a);if(!p){const R=a===void 0?F():void 0;if(R){await R.patch(e,r);return}throw new N("INTERNAL",`document not found: ${e}`)}const{docJson:$,row:h,tableName:d}=p,f=n.tables[d];if(!f)throw new N("INTERNAL",`unknown table: ${d}`);l(d,e),ot("patch",r);const g={...h,...r,_id:e};it(f,r,g,u),He(f,g),re(d,"before","update")&&await se("before","update",{doc:{...g},id:e,op:"update",previous:h,table:d}),be(d),ye(d),xe(o,d,t`UPDATE ${t.identifier(d)} SET ${t.identifier(X)} = ${JSON.stringify(g)} WHERE id = ${e} AND ${t.identifier(X)} = ${$}`),ke(d,e,g),ve(d,e,g),Ie(d,h,g),_e(d,e,h,g),w?.invalidate(d,e),O(d,e,"update",g),s({key:e,op:"update",row:g,table:d}),re(d,"after","update")&&await se("after","update",{doc:g,id:e,op:"update",previous:h,table:d}),await E({doc:g,id:e,op:"update",table:d})},async patchMany(e,r,a){ge(e.length,r?.limit,"patchMany");for(const p of e)await J.patch(p.id,p.patch,a);return{patched:e.length}},async patchWhere(e,r,a){const p=I(e,"patchWhere");let $;if(p)$=(await p.findMany(e,{where:r.where})).page.map(h=>({id:String(h._id),patch:r.patch}));else{if(!n.tables[e])throw new N("INTERNAL",`unknown table: ${e}`);$=(await J.findMany(e,{where:r.where})).page.map(h=>({id:String(h._id),patch:r.patch}))}if(ge($.length,a?.limit,"patchWhere"),J.patchMany===void 0)throw new N("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await J.patchMany($,a),{patched:$.length}},query(e){const r=I(e,"query");return r?(l(e,Y),r.query(e)):(l(e,Y),_n(o,n,e,c))},async rank(e,r,a){const p=I(e,"rank");if(p)return l(e,Y),p.rank(e,r,a);c(e,r,"rank");const $=n.tables[e];if(!$)throw new N("INTERNAL",`unknown table: ${e}`);const h=$.rankIndexes?.find(ne=>ne.name===r);if(!h)throw new N("INTERNAL",`unknown rankIndex "${r}" on table "${e}"`);if(Je(e,$,h),a.restrictsCounts)throw new Ue(e);l(e,Y),We(e,h);const d=typeof a.row=="string"?a.row:a.row._id;if(!d)return null;const f=Ae(e,h.name),g=h.sortBy.map((ne,me)=>Se(me)),R=g.map(ne=>At(ne)).join(", "),y=v(o,t`SELECT ${t.identifier("__partition__")}, ${t.raw(R)} FROM ${t.identifier(f)} WHERE ${t.identifier("__id__")} = ${d}`).toArray(),[x]=y;if(x===void 0)return null;let z=x.__partition__;const K=oe(a.baseWhere,a.where);je(K,n,e,"rank");const C=ft(h,K);if(C){const ne=De(h.partitionBy??[],C);if(ne!==z)return null;z=ne}const ie=g.map(ne=>x[ne]),{before:ae,total:le}=at(o,f,g,h.sortBy,z,ie,d);return{position:ae+1,total:le}},async rankBefore(e,r,a){if(Z(e))throw new N("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const p=n.tables[e];if(!p)throw new N("INTERNAL",`unknown table: ${e}`);const $=p.rankIndexes?.find(g=>g.name===r);if(!$)throw new N("INTERNAL",`unknown rankIndex "${r}" on table "${e}"`);if(a.restrictsCounts)throw new Ue(e);l(e,Y),We(e,$);const h=Ae(e,$.name),d=$.sortBy.map((g,R)=>Se(R)),f=$.sortBy.map((g,R)=>ue(a.sortValues[R]??null));return at(o,h,d,$.sortBy,a.partitionKey,f,a.rowId)},async rankPage(e,r,a={}){je(oe(a.baseWhere,a.where),n,e,"rankPage");const p=I(e,"rankPage");if(p)return l(e,Y),p.rankPage(e,r,a);c(e,r,"rank");const{continueCursor:$,hasMore:h,rows:d}=et(ze,e,r,a);return{continueCursor:$,isDone:!h,page:d.map(f=>f.doc)}},async rankPageRows(e,r,a={}){je(oe(a.baseWhere,a.where),n,e,"rankPage"),c(e,r,"rank");const{directions:p,hasMore:$,rows:h}=et(ze,e,r,a);return{directions:p,hasMore:$,rows:h}},async restore(e,r){const a=$e(e,r);if(!a){const h=r===void 0?F():void 0;if(h?.restore){await h.restore(e);return}throw new N("INTERNAL",`document not found: ${e}`)}const p=n.tables[a.tableName]?.softDeleteMode?.field;if(!p)throw new N("INTERNAL",`ctx.db.restore: table "${a.tableName}" is not a .softDelete() table`);const $=a.row[p]!==null&&a.row[p]!==void 0;await J.patch(e,{[p]:null},r),$&&_e(a.tableName,e,void 0,a.row)},async replace(e,r,a,p){const $=$e(e,a);if(!$){const x=a===void 0?F():void 0;if(x){await x.replace(e,r,void 0,p);return}throw new N("INTERNAL",`document not found: ${e}`)}const{docJson:h,row:d,tableName:f}=$,g=n.tables[f];if(!g)throw new N("INTERNAL",`unknown table: ${f}`);ot("replace",r);const R=p?.allowExplicitId&&typeof r._creationTime=="number"?r._creationTime:_(),y={...r,_creationTime:R,_id:e};it(g,r,y,u),He(g,y),re(f,"before","update")&&await se("before","update",{doc:{...y},id:e,op:"update",previous:d,table:f}),be(f),ye(f),xe(o,f,t`UPDATE ${t.identifier(f)} SET _creationTime = ${R}, ${t.identifier(X)} = ${JSON.stringify(y)} WHERE id = ${e} AND ${t.identifier(X)} = ${h}`),ke(f,e,y),ve(f,e,y),Ie(f,d,y),_e(f,e,d,y),w?.invalidate(f,e),O(f,e,"update",y),s({key:e,op:"update",row:y,table:f}),re(f,"after","update")&&await se("after","update",{doc:y,id:e,op:"update",previous:d,table:f}),await E({doc:y,id:e,op:"update",table:f})},async wipeShard(e){const r=new Set(e?.exclude),a=e?.tables,p=Object.entries(n.tables).filter(([f,g])=>r.has(f)||a!==void 0&&!a.includes(f)?!1:g.shardMode?.kind!=="global").map(([f])=>f);if(a!==void 0){for(const f of a)if(!n.tables[f])throw new N("INTERNAL",`wipeShard: unknown table: ${f}`)}const $={};let h=0;const{deleteAll:d}=J;if(d===void 0)throw new N("INTERNAL","wipeShard: this writer has no deleteAll");for(const f of p){const g=await d(f,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});$[f]=g.deleted,h+=g.deleted}return{deleted:h,tables:$}}},Et={db:J,scheduler:k};return i.enforceRls===!0?Ut(J,n,(e,r)=>$e(e,r)?.tableName):J};export{Qn as CDC_LOG_TABLE,dr as CLIENT_WATERMARK_TABLE,cr as GLOBAL_SHAPE_SNAPSHOT_TABLE,fr as IDEMPOTENCY_TABLE,En as NotUniqueError,ur as advanceClientWatermark,Xn as applyCdcChanges,tn as assertValidClientId,ar as backfillAggregateIndexes,sr as backfillRankIndexes,Zn as bumpCdcEpoch,Jn as createShardCtxDb,hr as deleteGlobalShapeSnapshot,$r as deleteGlobalShapeSnapshotsForConnection,pr as migrateClientWatermark,wr as migrateGlobalShapeSnapshot,er as minCdcSeq,nt as normalizeIdStructurally,tr as readCdcChanges,nr as readCdcCursor,rr as readCdcEpoch,mr as readClientWatermark,gr as readGlobalShapeSnapshot,Er as readIdempotent,Tr as runShardMigrations,Sr as selectShapeMemberIds,Ar as selectShapeRows,ir as trimCdcChanges,br as trimIdempotent,yr as writeGlobalShapeSnapshot,_r as writeIdempotent};
1
+ import{LunoraError as N}from"@lunora/errors";import{sql as t}from"drizzle-orm";import{matchesStaticWhere as Be,aggregateSqlFunction as Ne,normalizeCountArgument as bt,throwingScheduler as yt}from"./AGGREGATE_SQL_FUNCTION-QYaiuty4.mjs";import{encodeAggregateKey as de,foldAggregateTally as _t,aggregateTableName as Te,coerceAggregateNumber as Fe,readAggregateValue as qe}from"./aggregateTableName-G-eXyjcz.mjs";import{mergeWhere as oe,CountRlsUnsupportedError as Ue,selectIndexForGroupBy as Nt,selectIndexForCount as Tt,selectIndexForAggregate as Rt}from"./CountRlsUnsupportedError-Cl8XpYDL.mjs";import{appendCdcChange as St}from"./CDC_LOG_TABLE-E_J5LPoK.mjs";import{CDC_LOG_TABLE as Qn,applyCdcChanges as Xn,bumpCdcEpoch as Zn,minCdcSeq as er,readCdcChanges as tr,readCdcCursor as nr,readCdcEpoch as rr,trimCdcChanges as ir}from"./CDC_LOG_TABLE-E_J5LPoK.mjs";import{r as v}from"./do-exec-BLe9lLrN.mjs";import{N as st,s as X,L as fe,a as ce,d as te,m as Q,g as lt,p as Le,T as ee,u as At,E as dt,$ as Ye}from"./do-sql-BYIQTG3z.mjs";import{param as Ke}from"./renderSql-B5lF5Jd9.mjs";import{encodeGeohash as It,GEO_DEFAULT_PRECISION as vt,coveringGeohashes as kt,boundingBoxGeohashes as Mt,pointInBoundingBox as Lt,haversineMeters as xt}from"./GEO_DEFAULT_PRECISION-okRCkZ6r.mjs";import{sortColumnName as Se,matchesRankStaticWhere as ct,encodePartitionKey as De,rankTableName as Ae,resolveRankPartition as ft,RANK_TIEBREAK as we}from"./RANK_TIEBREAK-DtX8zQyc.mjs";import{stringifySearchText as ut,ftsTableName as ht,tokenizeSearch as $t,buildFtsMatch as Ct,scoreDocument as Dt}from"./buildFtsMatch-CV0Z7PWv.mjs";import{t as ue}from"./serialize-sql-DiRzL7A4.mjs";import{SCAN_DEP as Y}from"./SCAN_DEP-D_yR9EeV.mjs";import{decodeCursor as Ce,normalizeOrderKeys as Ot,buildSeekWhere as pt,applySelect as Qe,encodeCursor as Pe,softDeleteScope as Ee,buildSeekBeforeWhere as Wt}from"./applySelect-Bq2KOrkL.mjs";import Bt from"./NotFoundError-J3tjf4Uo.mjs";import{assertFlatPredicate as je,resolveRelationPredicates as Xe}from"./DEFAULT_MAX_RELATION_KEYS-BRdmX7WW.mjs";import{runRowValidators as He,resolveWith as Ze,applyOnDelete as Ft,fanOutScalarCounts as qt}from"./applyOnDelete-BvQN7pDL.mjs";import{guardWriter as Ut}from"./RLS_UNWRAP_SYMBOL-C6_WX3dG.mjs";import{createSystemReader as jt}from"./createSystemReader-DcDcrtM3.mjs";import{ConflictError as Re}from"./ConflictError-C8GtJmjS.mjs";import{runTriggers as Ht}from"./hasTrigger-_rexbWMO.mjs";import{compileWhereSql as he}from"./compileWhereSql-BLcfs4QW.mjs";import{backfillAggregateIndexes as ar,backfillRankIndexes as sr}from"./backfillAggregateIndexes-BAQ3Fwwh.mjs";import{e as dr,t as cr,r as fr,o as ur,l as hr,p as $r,_ as pr,a as wr,b as mr,d as gr,m as Er,u as br,S as yr,T as _r}from"./ctx-db-idempotency-wiVoGnpQ.mjs";import{runShardMigrations as Tr}from"./runShardMigrations-bxOHpfID.mjs";import{a as Sr,s as Ar}from"./ctx-db-shapes-DzX_H5q8.mjs";const Pt=(i,o,n)=>[...i.partitionBy??[],...i.sortBy.map(s=>s.field),...i.where?Object.keys(i.where):[]].every(s=>o[s]===n[s]),Gt=(i,o,n,s,l,c)=>{if(l&&c&&Pt(n,l,c))return;const E=Ae(o,n.name);if(l&&v(i,t`DELETE FROM ${t.identifier(E)} WHERE ${t.identifier("__id__")} = ${s}`),!c||n.where&&!ct(c,n.where))return;const w=n.sortBy.map((u,S)=>Se(S)),_=t.join(["__id__","__partition__",...w].map(u=>t.identifier(u)),t`, `),T=De(n.partitionBy??[],c),k=n.sortBy.map(u=>ue(c[u.field]??null)),b=t.join([s,T,...k].map(u=>Ke(u)),t`, `);v(i,t`INSERT INTO ${t.identifier(E)} (${_}) VALUES (${b})`)},Kt=i=>{const{broadcast:o,invalidateCache:n,recordCdc:s,schema:l,sql:c}=i,E=new Set,w=new Set,_=(A,m)=>{const I=`${A}::${m.name}`;if(E.has(I))return;const F=Te(A,m.name),W=m.by??[],H=new Map,j=v(c,t`SELECT id, _creationTime, ${t.identifier(X)} FROM ${t.identifier(A)}`).toArray();for(const q of j){const L=fe(q);if(!L||m.where&&!Be(L,m.where))continue;const P=de(W,L);_t(H,P,m,L)}v(c,t`DELETE FROM ${t.identifier(F)}`);const G=32,B=[...H];for(let q=0;q<B.length;q+=G){const L=B.slice(q,q+G),P=t.join(L.map(([U,V])=>t`(${U}, ${V.value}, ${V.count})`),t`, `);v(c,t`INSERT INTO ${t.identifier(F)} (${ce}, ${te}, ${Q}) VALUES ${P}`)}E.add(I)},T=(A,m,I)=>{const F=m.by??[],W=Ne(m.op),H=m.field??"",j=[];for(const q of F){const L=ue(I[q]??null);L===null?j.push(t`${ee(q)} IS NULL`):j.push(t`${ee(q)} = ${L}`)}for(const[q,L]of Object.entries(m.where??{})){const P=L!==null&&typeof L=="object"&&!Array.isArray(L)?L.eq:L,U=ue(P);U===null?j.push(t`${ee(q)} IS NULL`):j.push(t`${ee(q)} = ${U}`)}const G=j.length>0?t` WHERE ${t.join(j,t` AND `)}`:t``,B=ee(H);return{value:v(c,t`SELECT ${t.raw(W)}(${B}) AS value FROM ${t.identifier(A)}${G}`).one().value??null}},k=(A,m,I,F)=>{const W=Te(A,m.name),{op:H}=m,j=m.field??"",G=L=>{v(c,t`DELETE FROM ${t.identifier(W)} WHERE ${ce} = ${L} AND ${Q} <= 0`)},B=I&&(!m.where||Be(I,m.where))?I:void 0,q=F&&(!m.where||Be(F,m.where))?F:void 0;if(!(!B&&!q)){if(H==="count"){for(const[L,P]of[[B,-1],[q,1]]){if(!L)continue;const U=de(m.by??[],L);v(c,Le(W,U,P,P,t`${te} = ${te} + excluded.${te}, ${Q} = ${Q} + excluded.${Q}`))}B&&G(de(m.by??[],B));return}if(H==="sum"||H==="avg"){for(const[L,P]of[[B,-1],[q,1]]){if(!L)continue;const U=Fe(L[j]);if(U===void 0)continue;const V=de(m.by??[],L);v(c,Le(W,V,P*U,P,t`${te} = COALESCE(${te}, 0) + excluded.${te}, ${Q} = ${Q} + excluded.${Q}`))}B&&G(de(m.by??[],B));return}if(B){const L=de(m.by??[],B),P=Fe(B[j]),U=v(c,t`SELECT ${te} AS value, ${Q} AS count FROM ${t.identifier(W)} WHERE ${ce} = ${L}`).toArray()[0],V=(U?.count??0)-1;if(V<=0)v(c,t`DELETE FROM ${t.identifier(W)} WHERE ${ce} = ${L}`);else if(U&&P!==void 0&&U.value!==null&&P===U.value){const re=T(A,m,B);v(c,t`UPDATE ${t.identifier(W)} SET ${te} = ${re.value}, ${Q} = ${V} WHERE ${ce} = ${L}`)}else v(c,t`UPDATE ${t.identifier(W)} SET ${Q} = ${Q} - 1 WHERE ${ce} = ${L}`)}if(q){const L=de(m.by??[],q),P=Fe(q[j]);if(P===void 0)v(c,Le(W,L,null,1,t`${Q} = ${Q} + 1`));else{const U=H==="min"?"MIN":"MAX";v(c,Le(W,L,P,1,t`${te} = ${t.raw(U)}(COALESCE(${te}, excluded.${te}), excluded.${te}), ${Q} = ${Q} + 1`))}}}},b=A=>{const m=l.tables[A]?.aggregateIndexes;if(!(!m||m.length===0))for(const I of m)_(A,I)},u=(A,m,I)=>{const F=l.tables[A]?.aggregateIndexes;if(!(!F||F.length===0))for(const W of F)k(A,W,m,I)},S=(A,m)=>{const I=`${A}::rank::${m.name}`;if(w.has(I))return;const F=Ae(A,m.name),W=v(c,t`SELECT id, _creationTime, ${t.identifier(X)} FROM ${t.identifier(A)}`).toArray();v(c,t`DELETE FROM ${t.identifier(F)}`);const H=m.sortBy.map((G,B)=>Se(B)),j=t.join(["__id__","__partition__",...H].map(G=>t.identifier(G)),t`, `);for(const G of W){const B=fe(G);if(!B||m.where&&!ct(B,m.where))continue;const q=De(m.partitionBy??[],B),L=m.sortBy.map(U=>ue(B[U.field]??null)),P=t.join([B._id,q,...L].map(U=>Ke(U)),t`, `);v(c,t`INSERT INTO ${t.identifier(F)} (${j}) VALUES (${P})`)}w.add(I)},M=A=>{const m=l.tables[A]?.rankIndexes;if(!(!m||m.length===0))for(const I of m)S(A,I)},D=(A,m,I,F)=>{const W=l.tables[A]?.rankIndexes;if(!(!W||W.length===0))for(const H of W)Gt(c,A,H,m,I,F)},O=(A,m,I)=>{const F=l.tables[A]?.searchIndexes;if(!(!F||F.length===0||!st(c)))for(const W of F){const H=ht(A,W.name);v(c,t`DELETE FROM ${t.identifier(H)} WHERE ${t.identifier("__id__")} = ${m}`),I&&v(c,t`INSERT INTO ${t.identifier(H)} (${t.identifier("__text__")}, ${t.identifier("__id__")}) VALUES (${ut(I[W.field])}, ${m})`)}},Z=(A,m,I)=>{const F=l.tables[A]?.geoIndexes;if(!(!F||F.length===0))for(const W of F){const H=lt(A,W.name);v(c,t`DELETE FROM ${t.identifier(H)} WHERE ${t.identifier("__id__")} = ${m}`);const j=I?.[W.field];if(j!==null&&typeof j=="object"&&typeof j.lat=="number"&&typeof j.lng=="number"){const{lat:G,lng:B}=j,q=It({lat:G,lng:B},W.precision??vt);v(c,t`INSERT INTO ${t.identifier(H)} (${t.identifier("__id__")}, ${t.identifier("__geohash__")}, ${t.identifier("__lat__")}, ${t.identifier("__lng__")}) VALUES (${m}, ${q}, ${G}, ${B})`)}}};return{ensureBackfilledForTable:b,ensureBackfilledIndex:_,ensureRankBackfilled:S,ensureRankBackfilledForTable:M,syncAggregates:u,syncCompanionsForInsert:(A,m,I)=>{O(A,m,I),Z(A,m,I),u(A,void 0,I),D(A,m,void 0,I),n(A,m),s(A,m,"insert",I),o({key:m,op:"insert",row:I,table:A})},syncGeo:Z,syncRanks:D,syncSearch:O}},Vt="__doc__",Jt=i=>{const o=JSON.stringify(i),n=new TextEncoder().encode(o);let s="";for(const l of n)s+=String.fromCodePoint(l);return btoa(s)},zt=i=>i.after?[i.after.partitionKey,...i.after.sortValues,i.after.rowId]:i.cursor?Ce(i.cursor):void 0,Yt=(i,o,n)=>{if(i?.length!==1+o.length+1)return;const s=[{column:"__partition__",direction:"asc"}];for(const[c,E]of o.entries())s.push({column:E,direction:n[c]?.direction??"asc"});s.push({column:we,direction:"asc"});const l=[];for(const[c,E]of s.entries()){const w=[];for(const[T,k]of s.slice(0,c).entries())w.push(t`${t.identifier(k.column)} IS ${i[T]}`);w.push(t`${t.identifier(E.column)} ${t.raw(E.direction==="desc"?"<":">")} ${i[c]}`);const[_]=w;l.push(w.length===1&&_!==void 0?_:t`(${t.join(w,t` AND `)})`)}return t`(${t.join(l,t` OR `)})`},wt=null,Qt=(i,o)=>{if(i===void 0)return wt;const n=[i.__partition__,...o.map(s=>i[s]),i[we]];return Jt(n)},Xt=(i,o,n)=>{const s=[];for(const l of i){const c=l[we];if(typeof c!="string")continue;const E=o.get(c);if(!E)continue;const w=typeof l.__partition__=="string"?l.__partition__:"",_=n.map(T=>l[T]??null);s.push({doc:E,key:{partitionKey:w,rowId:c,sortValues:_}})}return s},Zt=(i,o,n)=>{const{rowToDocument:s}=i,l=new Map;if(n.length===0)return l;const c=t.join(n.map(w=>Ke(w)),t`, `),E=v(i.sql,t`SELECT id, _creationTime, ${t.identifier(Vt)} FROM ${t.identifier(o)} WHERE id IN (${c})`).toArray();for(const w of E){const _=s(w),T=w.id;_&&typeof T=="string"&&l.set(T,_)}return l},et=(i,o,n,s)=>{const{assertRankPartitionLocal:l,ensureRankBackfilled:c,onRead:E,schema:w}=i,_=w.tables[o];if(!_)throw new N("INTERNAL",`unknown table: ${o}`);const T=_.rankIndexes?.find(V=>V.name===n);if(!T)throw new N("INTERNAL",`unknown rankIndex "${n}" on table "${o}"`);l(o,_,T),E(o,Y),c(o,T);const k=Ae(o,T.name),b=T.sortBy.map((V,re)=>Se(re)),u=Math.max(1,Math.min(1e3,Math.floor(s.take??100))),S=oe(s.baseWhere,s.where),M=ft(T,S),D=[t`${t.identifier("__partition__")} ASC`];for(const[V,re]of b.entries()){const se=T.sortBy[V]?.direction;D.push(t`${t.identifier(re)} ${t.raw(se==="desc"?"DESC":"ASC")}`)}D.push(t`${t.identifier(we)} ASC`);const O=[];typeof s.partitionKey=="string"?O.push(t`${t.identifier("__partition__")} = ${s.partitionKey}`):M&&O.push(t`${t.identifier("__partition__")} = ${De(T.partitionBy??[],M)}`);const Z=zt(s),A=Yt(Z,b,T.sortBy);A&&O.push(A);const m=t.identifier(we),I=t.identifier("__partition__"),F=O.length>0?t` WHERE ${t.join(O,t` AND `)}`:t``,W=b.length>0?t`${m}, ${I}, ${t.join(b.map(V=>t.identifier(V)),t`, `)}`:t`${m}, ${I}`,H=t`SELECT ${W} FROM ${t.identifier(k)}${F} ORDER BY ${t.join(D,t`, `)} LIMIT ${t.raw(String(u+1))}`,j=v(i.sql,H).toArray(),G=j.length>u,B=G?j.slice(0,u):j,q=B.map(V=>V[we]),L=Xt(B,Zt(i,o,q),b),P=G?Qt(B.at(-1),b):wt,U=T.sortBy.map(V=>V.direction==="desc"?"desc":"asc");return{continueCursor:P,directions:U,hasMore:G,rows:L}},en=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,tn=i=>{if(!en.test(i))throw new N("INTERNAL",`invalid clientId ${JSON.stringify(i)}: a client-supplied row id must be a UUID`)},tt=50,mt=500,ge=(i,o,n)=>{const s=o??mt;if(i>s)throw new N("BATCH_LIMIT_EXCEEDED",`${n}: batch of ${String(i)} exceeds the limit of ${String(s)} (raise options.limit or chunk the call)`,{status:400})},nn=i=>{const o={eq:(n,s)=>(i.sqlConditions.push({comparator:"=",field:n,value:s}),o),gt:(n,s)=>(i.sqlConditions.push({comparator:">",field:n,value:s}),o),gte:(n,s)=>(i.sqlConditions.push({comparator:">=",field:n,value:s}),o),lt:(n,s)=>(i.sqlConditions.push({comparator:"<",field:n,value:s}),o),lte:(n,s)=>(i.sqlConditions.push({comparator:"<=",field:n,value:s}),o)};return o},rn=(i,o)=>{const n={eq:(s,l)=>{if(!i.definition.filterFields?.includes(s))throw new N("INTERNAL",`field "${s}" is not a filter field of search index "${i.indexName}" on table "${o}"`);return i.filters.push({field:s,value:l}),n},search:(s,l)=>{if(s!==i.definition.field)throw new N("INTERNAL",`search index "${i.indexName}" on table "${o}" indexes "${i.definition.field}", not "${s}"`);const c=i;return c.field=s,c.query=l,c.hasQuery=!0,n}};return n},on=(i,o,n,s,l)=>{const c=$t(n.query);if(c.length===0)return[];const E=ht(o,n.indexName),w=[t`f.${t.identifier("__text__")} MATCH ${Ct(c)}`];for(const b of n.filters)w.push(t`${ee(b.field)} = ${ue(b.value)}`);l&&w.push(l);let _=t`SELECT m.id, m._creationTime, m.${t.identifier(X)} FROM ${t.identifier(E)} f JOIN ${t.identifier(o)} m ON m.id = f.${t.identifier("__id__")} WHERE ${t.join(w,t` AND `)} ORDER BY f.rank, m._creationTime DESC`;typeof s=="number"&&(_=t`${_} LIMIT ${t.raw(String(Math.max(0,Math.floor(s))))}`);const T=v(i,_).toArray(),k=[];for(const b of T){const u=fe(b);u&&k.push(u)}return k},an=(i,o,n,s,l)=>{const c=$t(n.query);if(c.length===0)return[];const E=[];for(const b of n.filters)E.push(t`${ee(b.field)} = ${ue(b.value)}`);l&&E.push(l);let w=t`SELECT id, _creationTime, ${t.identifier(X)} FROM ${t.identifier(o)}`;E.length>0&&(w=t`${w} WHERE ${t.join(E,t` AND `)}`);const _=v(i,w).toArray(),T=[];for(const b of _){const u=fe(b);if(!u)continue;const S=Dt(ut(u[n.field]),c);S>0&&T.push({creationTime:typeof u._creationTime=="number"?u._creationTime:0,doc:u,score:S})}T.sort((b,u)=>u.score-b.score||u.creationTime-b.creationTime);const k=T.map(b=>b.doc);return typeof s=="number"?k.slice(0,Math.max(0,Math.floor(s))):k},sn=(i,o)=>{const n=i,s={near:(l,c)=>{if(n.within)throw new N("INTERNAL",`geo index "${n.indexName}" on table "${o}": call .near() or .within(), not both`);return n.near={point:{lat:l.lat,lng:l.lng},radiusMeters:c},s},within:l=>{if(n.near)throw new N("INTERNAL",`geo index "${n.indexName}" on table "${o}": call .near() or .within(), not both`);return n.within={ne:{lat:l.ne.lat,lng:l.ne.lng},sw:{lat:l.sw.lat,lng:l.sw.lng}},s}};return s},ln=(i,o)=>{const n=i[o];if(n===null||typeof n!="object")return;const{lat:s,lng:l}=n;return typeof s=="number"&&typeof l=="number"?{lat:s,lng:l}:void 0},dn=(i,o)=>{const n=ln(i,o.definition.field);if(!n)return;const s=typeof i._creationTime=="number"?i._creationTime:0;if(o.near){const l=xt(o.near.point,n);return l<=o.near.radiusMeters?{creationTime:s,distance:l}:void 0}return Lt(n,o.within)?{creationTime:s,distance:0}:void 0},cn=(i,o,n,s,l)=>{if(!n.near&&!n.within)throw new N("INTERNAL",`geo index "${n.indexName}" on table "${o}": call .near(point, radius) or .within(box)`);const c=n.near?kt(n.near.point,n.near.radiusMeters):Mt(n.within),E=lt(o,n.indexName),w=c.map(S=>t`(g.${t.identifier("__geohash__")} >= ${S} AND g.${t.identifier("__geohash__")} < ${`${S}{`})`),_=[t`(${t.join(w,t` OR `)})`];l&&_.push(l);const T=t`SELECT m.id, m._creationTime, m.${t.identifier(X)} FROM ${t.identifier(E)} g JOIN ${t.identifier(o)} m ON m.id = g.${t.identifier("__id__")} WHERE ${t.join(_,t` AND `)}`,k=v(i,T).toArray(),b=[];for(const S of k){const M=fe(S),D=M?dn(M,n):void 0;M&&D&&b.push({creationTime:D.creationTime,distance:D.distance,doc:M})}b.sort((S,M)=>S.distance-M.distance||M.creationTime-S.creationTime);const u=b.map(S=>S.doc);return typeof s=="number"?u.slice(0,Math.max(0,Math.floor(s))):u},fn=(i,o,n,s,l)=>{const{geo:c}=n;if(!c)throw new N("INTERNAL","runGeoTerminal called without a staged geo query");const E=n.inMemoryFilters.length>0,w=cn(i,o,c,E?void 0:l,s);if(!E)return w;const _=[];for(const T of w)if(n.inMemoryFilters.every(k=>k(T))&&(_.push(T),typeof l=="number"&&_.length>=l))break;return _},un=(i,o,n,s,l,c)=>{const E=[];for(const k of n.sqlConditions)E.push(t`${ee(k.field)} ${t.raw(k.comparator)} ${ue(k.value)}`);s&&E.push(s);let w=t`SELECT id, _creationTime, ${t.identifier(X)} FROM ${t.identifier(o)}`;E.length>0&&(w=t`${w} WHERE ${t.join(E,t` AND `)}`),w=t`${w} ORDER BY ${l}`,typeof c=="number"&&n.inMemoryFilters.length===0&&(w=t`${w} LIMIT ${t.raw(String(Math.max(0,Math.floor(c))))}`);const _=v(i,w).toArray(),T=[];for(const k of _){const b=fe(k);if(b&&n.inMemoryFilters.every(u=>u(b))&&(T.push(b),typeof c=="number"&&T.length>=c))break}return T},pe={fieldRef:ee,serialize:ue},hn=i=>{let o=0;const n=[],s={fieldRef:ee,relationExists:l=>{const{childWhere:c,negated:E,parentTable:w,relation:_}=l,T=`__rel_${String(o)}`,k=n.at(-1)??w;o+=1,i(_.table,Y);const b=_.kind==="one"?_.field:_.references,u=_.kind==="one"?_.references:_.field,S=t`${Ye(T,u)} = ${Ye(k,b)}`;n.push(T);const M=he(c,s);n.pop();const D=M?t`${S} AND ${M}`:S,O=t`EXISTS (SELECT 1 FROM ${t.identifier(_.table)} AS ${t.identifier(T)} WHERE ${D})`;return E?t`NOT ${O}`:O},serialize:ue};return s},gt=i=>{const o=i.map(n=>t`${ee(n.field)} ${t.raw(n.direction==="desc"?"DESC":"ASC")}`);return i.some(n=>n.field==="_id"||n.field==="id")||o.push(t`${ee("id")} ASC`),t.join(o,t`, `)},$n={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},pn=i=>{const o=i.order;return i.indexFields.length>0?i.indexFields.map(n=>({direction:o,field:n})):[{direction:o,field:"_creationTime"}]},wn=(i,o,n,s)=>{const l=i.sqlConditions.map(c=>({[c.field]:{[$n[c.comparator]??"eq"]:c.value}}));if(n&&l.push(pt(o,Ce(n))),s&&l.push(Wt(o,Ce(s))),l.length!==0)return l.length===1?l[0]:{AND:l}},mn=(i,o,n)=>{const s=[];for(const l of i){const c=fe(l);if(c&&o.every(E=>E(c))&&(s.push(c),n!==void 0&&s.length>n))break}return s},gn=(i,o,n,s,l)=>{const c=Math.max(0,Math.floor(s.numItems)),E=pn(n),w=typeof s.endCursor=="string",_=he(wn(n,E,s.cursor,s.endCursor),pe),T=l&&_?t`${_} AND ${l}`:l??_;let k=t`SELECT id, _creationTime, ${t.identifier(X)} FROM ${t.identifier(o)}`;T&&(k=t`${k} WHERE ${T}`),k=t`${k} ORDER BY ${gt(E)}`;const b=n.inMemoryFilters.length>0;!b&&!w&&(k=t`${k} LIMIT ${t.raw(String(c+1))}`);const u=v(i,k).toArray(),S=mn(u,n.inMemoryFilters,b||w?void 0:c);if(w){const Z=S.length>=2?S[Math.floor(S.length/2)-1]:void 0;return{continueCursor:s.endCursor??null,isDone:!0,page:S,splitCursor:Z?Pe(Z,E):null}}const M=S.length>c,D=M?S.slice(0,c):S,O=D.at(-1);return{continueCursor:M&&O?Pe(O,E):null,isDone:!M,page:D}};class En extends N{constructor(o="unique() found more than one matching document"){super("NOT_UNIQUE",o,{name:"NotUniqueError"})}}const bn=/\s/u,yn=String.fromCodePoint(0),nt=(i,o,n)=>{if(!i.tables[o])throw new N("INTERNAL",`unknown table: ${o}`);return typeof n!="string"||n.length===0||bn.test(n)||n.includes(yn)?null:n},_n=(i,o,n,s=()=>{})=>{const l=o.tables[n];if(!l)throw new N("INTERNAL",`unknown table: ${n}`);const c=Ee(l.softDeleteMode,void 0),E=c?he(c,pe):void 0,w={indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[]},_=u=>{const{search:S}=w;if(!S)throw new N("INTERNAL","runSearchFetch called without a staged search");const M=w.inMemoryFilters.length>0,D=M?void 0:u,O=st(i)?on(i,n,S,D,E):an(i,n,S,D,E);if(!M)return O;const Z=[];for(const A of O)if(w.inMemoryFilters.every(m=>m(A))&&(Z.push(A),typeof u=="number"&&Z.length>=u))break;return Z},T=()=>{const u=w.indexFields.length>0?w.indexFields:["_creationTime"],S=w.order==="desc"?"DESC":"ASC";return t.join(u.map(M=>t`${ee(M)} ${t.raw(S)}`),t`, `)},k=u=>w.search?_(u):w.geo?fn(i,n,w,E,u):un(i,n,w,E,T(),u),b={async collect(){return k(void 0)},filter(u){return w.inMemoryFilters.push(u),b},async first(){return k(w.inMemoryFilters.length>0?void 0:1)[0]??null},order(u){return w.order=u==="desc"?"desc":"asc",b},async paginate(u){if(w.search)throw new N("INTERNAL","pagination is not supported on search queries; use .take(n) or .collect()");if(w.geo)throw new N("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");return gn(i,n,w,u,E)},async take(u){return k(u)},async unique(){const u=k(w.inMemoryFilters.length>0?void 0:2);if(u.length>1)throw new En(`unique() on table "${n}" matched ${String(u.length)} documents; expected at most one`);return u[0]??null},withGeoIndex(u,S){const M=(l.geoIndexes??[]).find(O=>O.name===u);if(!M)throw new N("INTERNAL",`unknown geo index "${u}" on table "${n}"`);s(n,u,"geo");const D={definition:M,indexName:u};if(w.geo=D,S(sn(D,n)),!D.near&&!D.within)throw new N("INTERNAL",`geo index "${u}" on table "${n}" requires a .near(point, radius) or .within(box) call`);return b},withIndex(u,S){const M=l.indexes.find(D=>D.name===u);if(!M)throw new N("INTERNAL",`unknown index "${u}" on table "${n}"`);return s(n,u,"index"),w.indexName=u,w.indexFields=M.fields,S&&S(nn(w)),b},withSearchIndex(u,S){const M=(l.searchIndexes??[]).find(O=>O.name===u);if(!M)throw new N("INTERNAL",`unknown search index "${u}" on table "${n}"`);s(n,u,"search");const D={definition:M,field:M.field,filters:[],hasQuery:!1,indexName:u,query:""};if(w.search=D,S(rn(D,n)),!D.hasQuery)throw new N("INTERNAL",`search index "${u}" on table "${n}" requires a .search(field, query) call`);return b}};return b},rt=(i,o,n)=>{const s={...o};for(const[l,c]of dt(i)){if(c.serverDefault){s[l]=c.serverDefault({auth:n});continue}s[l]===void 0&&(c.defaultFn?s[l]=c.defaultFn():"defaultValue"in c&&(s[l]=c.defaultValue))}return s},it=(i,o,n,s)=>{const l=n;for(const[c,E]of dt(i)){if(E.serverDefault){c in o&&(l[c]=E.serverDefault({auth:s}));continue}E.onUpdateFn&&!(c in o)&&(l[c]=E.onUpdateFn())}},ot=(i,o)=>{for(const n of Object.keys(o))if(o[n]===void 0)throw new N("INTERNAL",`Cannot ${i} field '${n}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},Nn=/unique constraint failed/i,Tn=i=>i instanceof Error&&Nn.test(i.message),Ge=(i,o,n)=>{try{v(i,n)}catch(s){throw Tn(s)?new Re(`unique constraint violation on "${o}"`,"unique"):s}},xe=(i,o,n)=>{if(Ge(i,o,n),v(i,t`SELECT changes() AS changed`).one().changed===0)throw new Re(`optimistic concurrency conflict on "${o}" — the row changed during this mutation; refetch and retry`,"occ")},at=(i,o,n,s,l,c,E)=>{const w=[];for(let b=0;b<n.length+1;b+=1){const u=[];for(let O=0;O<b;O+=1)u.push(t`${t.identifier(n[O])} IS ${c[O]}`);const S=n[b],M=s[b];if(S!==void 0&&M!==void 0){const O=M.direction==="desc"?">":"<";u.push(t`${t.identifier(S)} ${t.raw(O)} ${c[b]}`)}else u.push(t`${t.identifier(we)} < ${E}`);const[D]=u;w.push(u.length===1&&D!==void 0?D:t`(${t.join(u,t` AND `)})`)}const _=t.join(w,t` OR `),T=v(i,t`SELECT COUNT(*) AS c FROM ${t.identifier(o)} WHERE ${t.identifier("__partition__")} = ${l} AND (${_})`).one(),k=v(i,t`SELECT COUNT(*) AS c FROM ${t.identifier(o)} WHERE ${t.identifier("__partition__")} = ${l}`).one();return{before:T.c,total:k.c}},Jn=i=>{const{sql:o}=i,{schema:n}=i,s=i.broadcast??(()=>{}),l=i.onRead??(()=>{}),c=i.onIndexUse??(()=>{}),E=i.onWrite??(()=>{}),{cache:w}=i,_=i.clock??(()=>Date.now()),T=i.idGenerator??(()=>crypto.randomUUID()),k=i.scheduler??yt,{globalDb:b}=i,u=i.auth??{identity:null,userId:null},S=i.cdc??!1,M=k,D=jt({scheduler:typeof M.list=="function"&&typeof M.get=="function"?M:void 0,storage:i.storage}),O=(e,r,a,p)=>{S&&St(o,_(),e,r,a,p)},Z=e=>n.tables[e]?.shardMode?.kind==="global",A=(e,r)=>{if(Z(e)){if(!b)throw new N("INTERNAL",`cross-backend ${r} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return b}return J},m=e=>A(e,"cascade"),I=(e,r)=>{if(Z(e)){if(!b)throw new N("INTERNAL",`${r} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return b}},F=()=>b,W=(e,r)=>A(e,"relation load").findMany(e,r),H=(e,r)=>(Z(e)&&l(e,Y),W(e,r)),j=e=>!Z(e.table),G=i.relationExistsPushDown??"auto",B=G!=="never",{maxRelationKeys:q}=i,L=(e,r,a)=>Xe(e,{fetcher:H,maxRelationKeys:q,relationBaseWhere:a,schema:n,tableName:r}),P=async(e,r,a,p)=>{const $=I(e,"relation grouped count");if($)return l(e,Y),qt((C,ie)=>$.count(C,ie),e,r,a,p);const h=n.tables[e];if(!h)throw new N("INTERNAL",`unknown table: ${e}`);l(e,Y);const d=Ee(h.softDeleteMode,void 0),f={[r]:{in:a}},g=oe(oe(f,p),d),R=await L(g,e,void 0),y=he(R,pe),x=ee(r);let z=t`SELECT ${x} AS __fk__, COUNT(*) AS count FROM ${t.identifier(e)}`;y&&(z=t`${z} WHERE ${y}`),z=t`${z} GROUP BY ${x}`;const K=v(o,z).toArray();return new Map(K.map(C=>[C.__fk__,C.count]))};let U=0;const V=new Set;for(const[e,r]of Object.entries(n.tables))for(const a of Object.values(r.triggerMap??{}))V.add(`${e} ${a.timing} ${a.op}`);const re=(e,r,a)=>V.has(`${e} ${r} ${a}`),se=async(e,r,a)=>{if(U+=1,U>tt)throw U-=1,new Re(`trigger recursion exceeded ${String(tt)} levels on "${a.table}" — check for a self-triggering write`,"trigger");try{await Ht({ctx:Et,event:a,op:r,schema:n,tableName:a.table,timing:e})}finally{U-=1}},{ensureBackfilledForTable:be,ensureBackfilledIndex:Oe,ensureRankBackfilled:We,ensureRankBackfilledForTable:ye,syncAggregates:Ie,syncCompanionsForInsert:Ve,syncGeo:ve,syncRanks:_e,syncSearch:ke}=Kt({broadcast:s,invalidateCache:(e,r)=>w?.invalidate(e,r),recordCdc:O,schema:n,sql:o}),Je=(e,r,a)=>{const{shardMode:p}=r;if(p?.kind==="shardBy"&&!(p.field!==void 0&&(a.partitionBy??[]).includes(p.field)))throw Object.assign(new Error(`rank index "${a.name}" on "${e}" partitions across shards (shard key "${p.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})},$e=(e,r)=>{const a=Object.entries(n.tables).filter(([,R])=>R.shardMode?.kind!=="global").map(([R])=>R).filter(R=>r===void 0||R===r);if(a.length===0)return;const p=a.map(R=>t`SELECT ${t.raw(`'${R.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${t.identifier(X)} FROM ${t.identifier(R)} WHERE id = ${e}`),$=t`${t.join(p,t` UNION ALL `)} LIMIT 1`,[h]=v(o,$).toArray();if(!h)return;const d=h.__t__,f=fe(h);if(typeof d!="string"||!f)return;const g=h[X];return{docJson:typeof g=="string"?g:JSON.stringify(g??{}),row:f,tableName:d}},ze={assertRankPartitionLocal:Je,ensureRankBackfilled:We,onRead:l,rowToDocument:fe,schema:n,sql:o},J={system:D,async aggregate(e,r){const a=I(e,"aggregate");if(a)return l(e,Y),a.aggregate(e,r);const p=n.tables[e];if(!p)throw new N("INTERNAL",`unknown table: ${e}`);if(Ne(r.op),r.op==="count")return J.count(e,{baseWhere:r.baseWhere,relationBaseWhere:r.relationBaseWhere,restrictsCounts:r.restrictsCounts,where:r.where});if(!r.field)throw new N("INTERNAL",`aggregate(${e}, { op: "${r.op}" }): "field" is required for non-count reducers`);l(e,Y);const $=Ee(p.softDeleteMode,void 0),h=oe(oe(r.baseWhere,r.where),$),d=await L(h,e,r.relationBaseWhere),f=d!==h;if(p.aggregateIndexes&&!r.baseWhere&&!f&&!$){const K=Rt(p.aggregateIndexes,r.op,r.field,r.where);if(K){Oe(e,K.index);const C=de(K.index.by??[],K.key),ie=Te(e,K.index.name),ae=v(o,t`SELECT ${te} AS value, ${Q} AS count FROM ${t.identifier(ie)} WHERE ${ce} = ${C}`).toArray()[0];return qe(r.op,ae)}}const g=he(d,pe),R=Ne(r.op),y=ee(r.field);let x=t`SELECT ${t.raw(R)}(${y}) AS value FROM ${t.identifier(e)}`;return g&&(x=t`${x} WHERE ${g}`),v(o,x).toArray()[0]?.value??null},asId(e,r){const a=nt(n,e,r);if(a===null)throw new N("BAD_REQUEST",`asId("${e}", …): "${r}" is not a valid id for table "${e}"`,{status:400});return a},async count(e,r){const a=I(e,"count");if(a)return l(e,Y),a.count(e,r);const p=n.tables[e];if(!p)throw new N("INTERNAL",`unknown table: ${e}`);const $=bt(r);if($.restrictsCounts)throw new Ue(e);l(e,Y);const h=Ee(p.softDeleteMode,void 0),d=oe(oe($.baseWhere,$.where),h),f=await L(d,e,$.relationBaseWhere),g=f!==d;if(p.aggregateIndexes&&!$.baseWhere&&!g&&!h){const x=Tt(p.aggregateIndexes,$.where);if(x){Oe(e,x.index);const z=de(x.index.by??[],x.key),K=Te(e,x.index.name),C=v(o,t`SELECT ${te} AS value FROM ${t.identifier(K)} WHERE ${ce} = ${z}`).toArray();return C[0]===void 0?0:C[0].value??0}}const R=he(f,pe);let y=t`SELECT COUNT(*) AS count FROM ${t.identifier(e)}`;return R&&(y=t`${y} WHERE ${R}`),v(o,y).one().count},async delete(e,r,a){const p=$e(e,r);if(!p){const y=r===void 0?F():void 0;y&&await y.delete(e,void 0,a);return}const{docJson:$,row:h,tableName:d}=p,f=n.tables[d],g=a?.hard===!0,R=!g&&f?.softDeleteMode?f.softDeleteMode.field:void 0;if(!(R&&h[R]!==null&&h[R]!==void 0)){if(re(d,"before","delete")&&await se("before","delete",{id:e,op:"delete",previous:h,table:d}),await Ft({deletedId:e,deletedReference:y=>h[y],findHolders:async(y,x,z)=>(await m(y).findMany(y,{includeDeleted:g,where:{[x]:z}})).page,onCascade:(y,x)=>m(y).delete(x,void 0,a),onRestrict:y=>{throw new Re(y,"restrict")},onSetNull:(y,x,z)=>m(y).patch(x,{[z]:null}),schema:n,tableName:d}),be(d),ye(d),R){const y={...h,[R]:_(),_id:e};xe(o,d,t`UPDATE ${t.identifier(d)} SET ${t.identifier(X)} = ${JSON.stringify(y)} WHERE id = ${e} AND ${t.identifier(X)} = ${$}`),ke(d,e,y),ve(d,e,void 0),Ie(d,h,y),_e(d,e,h,void 0),w?.invalidate(d,e),O(d,e,"update",y),s({key:e,op:"update",row:y,table:d}),re(d,"after","delete")&&await se("after","delete",{id:e,op:"delete",previous:h,table:d}),await E({id:e,op:"delete",table:d});return}xe(o,d,t`DELETE FROM ${t.identifier(d)} WHERE id = ${e} AND ${t.identifier(X)} = ${$}`),ke(d,e,void 0),ve(d,e,void 0),Ie(d,h,void 0),_e(d,e,h,void 0),w?.invalidate(d,e),O(d,e,"delete"),s({key:e,op:"delete",table:d}),re(d,"after","delete")&&await se("after","delete",{id:e,op:"delete",previous:h,table:d}),await E({id:e,op:"delete",table:d})}},async deleteAll(e,r){if(!n.tables[e])throw new N("INTERNAL",`unknown table: ${e}`);const a=Math.max(1,r?.chunkSize??mt),p=r?.hard===void 0?void 0:{hard:r.hard},$=Z(e)?void 0:e;let h=0;for(;;){const d=(await J.findMany(e,{limit:a})).page.map(f=>String(f._id));if(d.length===0)break;for(const f of d)await J.delete(f,$,p),h+=1;if(d.length<a)break}return{deleted:h}},async deleteMany(e,r,a){ge(e.length,r?.limit,"deleteMany");for(const p of e)await J.delete(p,a);return{deleted:e.length}},async deleteWhere(e,r,a){const p=I(e,"deleteWhere");let $;if(p)$=(await p.findMany(e,{where:r})).page.map(h=>String(h._id));else{if(!n.tables[e])throw new N("INTERNAL",`unknown table: ${e}`);$=(await J.findMany(e,{where:r})).page.map(h=>String(h._id))}if(ge($.length,a?.limit,"deleteWhere"),J.deleteMany===void 0)throw new N("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return J.deleteMany($,a)},async findFirst(e,r={}){return(await J.findMany(e,{...r,limit:1})).page[0]??null},async findFirstOrThrow(e,r={}){const a=await J.findFirst(e,r);if(a===null)throw new Bt(`findFirstOrThrow: no "${e}" document matched`);return a},async findMany(e,r={}){const a=I(e,"findMany");if(a)return l(e,Y),a.findMany(e,r);const p=n.tables[e];if(!p)throw new N("INTERNAL",`unknown table: ${e}`);const $=!r.where&&!r.baseWhere;$?l(e,Y):l(e);const h=Ot(r.orderBy),d=r.cursor?pt(h,Ce(r.cursor)):void 0;let f=oe(r.baseWhere,r.where);f=oe(f,Ee(p.softDeleteMode,r.includeDeleted)),f=await Xe(f,{canPushExists:B?j:void 0,existsPushMode:G==="always"?"always":"auto",fetcher:H,maxRelationKeys:q,relationBaseWhere:r.relationBaseWhere,schema:n,tableName:e}),d&&(f=f?{AND:[f,d]}:d);const g=B?hn(l):pe,R=he(f,g);let y=t`SELECT id, _creationTime, ${t.identifier(X)} FROM ${t.identifier(e)}`;R&&(y=t`${y} WHERE ${R}`),y=t`${y} ORDER BY ${gt(h)}`;const x=typeof r.limit=="number"?Math.max(0,Math.floor(r.limit)):void 0;x!==void 0&&(y=t`${y} LIMIT ${t.raw(String(x+1))}`);const z=v(o,y).toArray(),K=[];for(const le of z){const ne=fe(le);ne&&(K.push(ne),!$&&typeof ne._id=="string"&&l(e,ne._id))}if(x===void 0)return r.with&&await Ze({groupedCounter:P,fetcher:W,parents:K,relationBaseWhere:r.relationBaseWhere,schema:n,tableName:e,with:r.with}),{continueCursor:null,isDone:!0,page:Qe(K,r.select,r.with)};const C=K.length>x,ie=C?K.slice(0,x):K,ae=ie.at(-1);return r.with&&await Ze({fetcher:W,groupedCounter:P,parents:ie,relationBaseWhere:r.relationBaseWhere,schema:n,tableName:e,with:r.with}),{continueCursor:C&&ae?Pe(ae,h):null,isDone:!C,page:Qe(ie,r.select,r.with)}},async get(e,r){const a=$e(e,r);if(!a){const p=r===void 0?F():void 0;return p?p.get(e):null}return l(a.tableName,e),a.row},async lookupById(e,r){const a=$e(e,r);return a?(l(a.tableName,e),{row:a.row,tableName:a.tableName}):null},async groupBy(e,r){const a=I(e,"groupBy");if(a)return l(e,Y),a.groupBy(e,r);const p=n.tables[e];if(!p)throw new N("INTERNAL",`unknown table: ${e}`);l(e,Y);const $=r.agg??{op:"count"};if(Ne($.op),$.op!=="count"&&!$.field)throw new N("INTERNAL",`groupBy(${e}, { agg: { op: "${$.op}" } }): "field" is required for non-count reducers`);const h=Ee(p.softDeleteMode,void 0),d=oe(oe(r.baseWhere,r.where),h),f=await L(d,e,r.relationBaseWhere),g=f!==d;if(p.aggregateIndexes&&!r.baseWhere&&!g&&!h){const C=Nt(p.aggregateIndexes,$.op,$.field,r.by,r.where);if(C){Oe(e,C.index);const ie=Te(e,C.index.name),ae=Object.keys(C.partial),le=[];if(ae.length===(C.index.by??[]).length&&ae.length>0){const me=de(C.index.by??[],C.partial),Me=v(o,t`SELECT ${te} AS value, ${Q} AS count FROM ${t.identifier(ie)} WHERE ${ce} = ${me}`).toArray();return Me.length>0&&le.push({key:{...C.partial},value:qe($.op,Me[0])}),le}const ne=v(o,t`SELECT ${ce} AS key, ${te} AS value, ${Q} AS count FROM ${t.identifier(ie)}`).toArray();for(const me of ne){const Me=JSON.parse(me.key);le.push({key:Me,value:qe($.op,me)})}return le}}const R=he(f,pe),y=r.by.map(C=>t`${ee(C)} AS ${t.identifier(C)}`);if($.op==="count")y.push(t`COUNT(*) AS value`);else{const{field:C}=$;if(C===void 0)throw new N("INTERNAL",`groupBy(${e}, { agg: { op: "${$.op}" } }): "field" is required for non-count reducers`);y.push(t`${t.raw(Ne($.op))}(${ee(C)}) AS value`)}let x=t`SELECT ${t.join(y,t`, `)} FROM ${t.identifier(e)}`;R&&(x=t`${x} WHERE ${R}`),x=t`${x} GROUP BY ${t.join(r.by.map(C=>ee(C)),t`, `)}`;const z=v(o,x).toArray(),K=[];for(const C of z){const ie={};for(const le of r.by)ie[le]=C[le]??null;const{value:ae}=C;K.push({key:ie,value:ae==null?null:Number(ae)})}return K},async insert(e,r,a){const p=I(e,"insert");if(p){const R=await p.insert(e,r,a);return s({key:R,op:"insert",row:{...r,_id:R},table:e}),R}const $=n.tables[e];if(!$)throw new N("INTERNAL",`unknown table: ${e}`);const h=rt($,r,u);He($,h);let d;a?.clientId!==void 0?(tn(a.clientId),d=a.clientId):a?.allowExplicitId&&typeof h._id=="string"?d=h._id:d=T();const f=a?.allowExplicitId&&typeof h._creationTime=="number"?h._creationTime:_(),g={...h,_creationTime:f,_id:d};return re(e,"before","insert")&&await se("before","insert",{doc:{...g},id:d,op:"insert",table:e}),be(e),ye(e),Ge(o,e,t`INSERT INTO ${t.identifier(e)} (id, _creationTime, ${t.identifier(X)}) VALUES (${d}, ${f}, ${JSON.stringify(g)})`),Ve(e,d,g),re(e,"after","insert")&&await se("after","insert",{doc:g,id:d,op:"insert",table:e}),await E({doc:g,id:d,op:"insert",table:e}),d},async insertManyUnsafe(e,r,a){if(ge(r.length,a?.limit,"insertManyUnsafe"),r.length===0)return[];const p=I(e,"insert");if(p){const f=[];for(const g of r){const R=await p.insert(e,g,{allowExplicitId:a?.allowExplicitId});s({key:R,op:"insert",row:{...g,_id:R},table:e}),f.push(R)}return f}const $=n.tables[e];if(!$)throw new N("INTERNAL",`unknown table: ${e}`);be(e),ye(e);const h=r.map(f=>{const g=rt($,f,u),R=a?.allowExplicitId===!0&&typeof g._id=="string"?g._id:T(),y=a?.allowExplicitId===!0&&typeof g._creationTime=="number"?g._creationTime:_();return{creationTime:y,document:{...g,_creationTime:y,_id:R},id:R}}),d=t.join(h.map(f=>t`(${f.id}, ${f.creationTime}, ${JSON.stringify(f.document)})`),t`, `);Ge(o,e,t`INSERT INTO ${t.identifier(e)} (id, _creationTime, ${t.identifier(X)}) VALUES ${d}`);for(const{document:f,id:g}of h)Ve(e,g,f),await E({doc:f,id:g,op:"insert",table:e});return h.map(f=>f.id)},async insertMany(e,r,a){ge(r.length,a?.limit,"insertMany");const p=a?.skipDuplicates===!0,$=[];for(const h of r)try{$.push(await J.insert(e,h))}catch(d){if(p&&d instanceof Re&&d.kind==="unique")$.push(null);else throw d}return $},normalizeId(e,r){return nt(n,e,r)},async patch(e,r,a){const p=$e(e,a);if(!p){const R=a===void 0?F():void 0;if(R){await R.patch(e,r);return}throw new N("INTERNAL",`document not found: ${e}`)}const{docJson:$,row:h,tableName:d}=p,f=n.tables[d];if(!f)throw new N("INTERNAL",`unknown table: ${d}`);l(d,e),ot("patch",r);const g={...h,...r,_id:e};it(f,r,g,u),He(f,g),re(d,"before","update")&&await se("before","update",{doc:{...g},id:e,op:"update",previous:h,table:d}),be(d),ye(d),xe(o,d,t`UPDATE ${t.identifier(d)} SET ${t.identifier(X)} = ${JSON.stringify(g)} WHERE id = ${e} AND ${t.identifier(X)} = ${$}`),ke(d,e,g),ve(d,e,g),Ie(d,h,g),_e(d,e,h,g),w?.invalidate(d,e),O(d,e,"update",g),s({key:e,op:"update",row:g,table:d}),re(d,"after","update")&&await se("after","update",{doc:g,id:e,op:"update",previous:h,table:d}),await E({doc:g,id:e,op:"update",table:d})},async patchMany(e,r,a){ge(e.length,r?.limit,"patchMany");for(const p of e)await J.patch(p.id,p.patch,a);return{patched:e.length}},async patchWhere(e,r,a){const p=I(e,"patchWhere");let $;if(p)$=(await p.findMany(e,{where:r.where})).page.map(h=>({id:String(h._id),patch:r.patch}));else{if(!n.tables[e])throw new N("INTERNAL",`unknown table: ${e}`);$=(await J.findMany(e,{where:r.where})).page.map(h=>({id:String(h._id),patch:r.patch}))}if(ge($.length,a?.limit,"patchWhere"),J.patchMany===void 0)throw new N("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await J.patchMany($,a),{patched:$.length}},query(e){const r=I(e,"query");return r?(l(e,Y),r.query(e)):(l(e,Y),_n(o,n,e,c))},async rank(e,r,a){const p=I(e,"rank");if(p)return l(e,Y),p.rank(e,r,a);c(e,r,"rank");const $=n.tables[e];if(!$)throw new N("INTERNAL",`unknown table: ${e}`);const h=$.rankIndexes?.find(ne=>ne.name===r);if(!h)throw new N("INTERNAL",`unknown rankIndex "${r}" on table "${e}"`);if(Je(e,$,h),a.restrictsCounts)throw new Ue(e);l(e,Y),We(e,h);const d=typeof a.row=="string"?a.row:a.row._id;if(!d)return null;const f=Ae(e,h.name),g=h.sortBy.map((ne,me)=>Se(me)),R=g.map(ne=>At(ne)).join(", "),y=v(o,t`SELECT ${t.identifier("__partition__")}, ${t.raw(R)} FROM ${t.identifier(f)} WHERE ${t.identifier("__id__")} = ${d}`).toArray(),[x]=y;if(x===void 0)return null;let z=x.__partition__;const K=oe(a.baseWhere,a.where);je(K,n,e,"rank");const C=ft(h,K);if(C){const ne=De(h.partitionBy??[],C);if(ne!==z)return null;z=ne}const ie=g.map(ne=>x[ne]),{before:ae,total:le}=at(o,f,g,h.sortBy,z,ie,d);return{position:ae+1,total:le}},async rankBefore(e,r,a){if(Z(e))throw new N("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const p=n.tables[e];if(!p)throw new N("INTERNAL",`unknown table: ${e}`);const $=p.rankIndexes?.find(g=>g.name===r);if(!$)throw new N("INTERNAL",`unknown rankIndex "${r}" on table "${e}"`);if(a.restrictsCounts)throw new Ue(e);l(e,Y),We(e,$);const h=Ae(e,$.name),d=$.sortBy.map((g,R)=>Se(R)),f=$.sortBy.map((g,R)=>ue(a.sortValues[R]??null));return at(o,h,d,$.sortBy,a.partitionKey,f,a.rowId)},async rankPage(e,r,a={}){je(oe(a.baseWhere,a.where),n,e,"rankPage");const p=I(e,"rankPage");if(p)return l(e,Y),p.rankPage(e,r,a);c(e,r,"rank");const{continueCursor:$,hasMore:h,rows:d}=et(ze,e,r,a);return{continueCursor:$,isDone:!h,page:d.map(f=>f.doc)}},async rankPageRows(e,r,a={}){je(oe(a.baseWhere,a.where),n,e,"rankPage"),c(e,r,"rank");const{directions:p,hasMore:$,rows:h}=et(ze,e,r,a);return{directions:p,hasMore:$,rows:h}},async restore(e,r){const a=$e(e,r);if(!a){const h=r===void 0?F():void 0;if(h?.restore){await h.restore(e);return}throw new N("INTERNAL",`document not found: ${e}`)}const p=n.tables[a.tableName]?.softDeleteMode?.field;if(!p)throw new N("INTERNAL",`ctx.db.restore: table "${a.tableName}" is not a .softDelete() table`);const $=a.row[p]!==null&&a.row[p]!==void 0;await J.patch(e,{[p]:null},r),$&&_e(a.tableName,e,void 0,a.row)},async replace(e,r,a,p){const $=$e(e,a);if(!$){const x=a===void 0?F():void 0;if(x){await x.replace(e,r,void 0,p);return}throw new N("INTERNAL",`document not found: ${e}`)}const{docJson:h,row:d,tableName:f}=$,g=n.tables[f];if(!g)throw new N("INTERNAL",`unknown table: ${f}`);ot("replace",r);const R=p?.allowExplicitId&&typeof r._creationTime=="number"?r._creationTime:_(),y={...r,_creationTime:R,_id:e};it(g,r,y,u),He(g,y),re(f,"before","update")&&await se("before","update",{doc:{...y},id:e,op:"update",previous:d,table:f}),be(f),ye(f),xe(o,f,t`UPDATE ${t.identifier(f)} SET _creationTime = ${R}, ${t.identifier(X)} = ${JSON.stringify(y)} WHERE id = ${e} AND ${t.identifier(X)} = ${h}`),ke(f,e,y),ve(f,e,y),Ie(f,d,y),_e(f,e,d,y),w?.invalidate(f,e),O(f,e,"update",y),s({key:e,op:"update",row:y,table:f}),re(f,"after","update")&&await se("after","update",{doc:y,id:e,op:"update",previous:d,table:f}),await E({doc:y,id:e,op:"update",table:f})},async wipeShard(e){const r=new Set(e?.exclude),a=e?.tables,p=Object.entries(n.tables).filter(([f,g])=>r.has(f)||a!==void 0&&!a.includes(f)?!1:g.shardMode?.kind!=="global").map(([f])=>f);if(a!==void 0){for(const f of a)if(!n.tables[f])throw new N("INTERNAL",`wipeShard: unknown table: ${f}`)}const $={};let h=0;const{deleteAll:d}=J;if(d===void 0)throw new N("INTERNAL","wipeShard: this writer has no deleteAll");for(const f of p){const g=await d(f,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});$[f]=g.deleted,h+=g.deleted}return{deleted:h,tables:$}}},Et={db:J,scheduler:k};return i.enforceRls===!0?Ut(J,n,(e,r)=>$e(e,r)?.tableName):J};export{Qn as CDC_LOG_TABLE,dr as CLIENT_WATERMARK_TABLE,cr as GLOBAL_SHAPE_SNAPSHOT_TABLE,fr as IDEMPOTENCY_TABLE,En as NotUniqueError,ur as advanceClientWatermark,Xn as applyCdcChanges,tn as assertValidClientId,ar as backfillAggregateIndexes,sr as backfillRankIndexes,Zn as bumpCdcEpoch,Jn as createShardCtxDb,hr as deleteGlobalShapeSnapshot,$r as deleteGlobalShapeSnapshotsForConnection,pr as migrateClientWatermark,wr as migrateGlobalShapeSnapshot,er as minCdcSeq,nt as normalizeIdStructurally,tr as readCdcChanges,nr as readCdcCursor,rr as readCdcEpoch,mr as readClientWatermark,gr as readGlobalShapeSnapshot,Er as readIdempotent,Tr as runShardMigrations,Sr as selectShapeMemberIds,Ar as selectShapeRows,ir as trimCdcChanges,br as trimIdempotent,yr as writeGlobalShapeSnapshot,_r as writeIdempotent};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/do",
3
- "version": "1.0.0-alpha.48",
3
+ "version": "1.0.0-alpha.49",
4
4
  "description": "Lunora Durable Objects: ShardDO (SQLite, OCC, hibernated WebSocket subscriptions) and SessionDO",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -1 +0,0 @@
1
- const x="0123456789bcdefghjkmnpqrstuvwxyz",y=9,b=63710088e-1,i=[Number.POSITIVE_INFINITY,5009400,1252300,156500,39100,4900,1200,152.9,38.2,4.77,1.19,.149,.037],d=t=>Math.min(Math.max(Math.trunc(t),1),12),f=(t,n)=>{const e=d(n);let s=-90,o=90,r=-180,l=180,g="",u=0,a=0,w=!0;for(;g.length<e;){if(w){const c=(r+l)/2;t.lng>=c?(a=a*2+1,r=c):(a*=2,l=c)}else{const c=(s+o)/2;t.lat>=c?(a=a*2+1,s=c):(a*=2,o=c)}w=!w,u<4?u+=1:(g+=x[a]??"0",u=0,a=0)}return g},m=(t,n)=>{const e=u=>u*Math.PI/180,s=e(n.lat-t.lat),o=e(n.lng-t.lng),r=e(t.lat),l=e(n.lat),g=Math.sin(s/2)**2+Math.cos(r)*Math.cos(l)*Math.sin(o/2)**2;return 2*b*Math.asin(Math.min(1,Math.sqrt(g)))},p=t=>{for(let n=i.length-1;n>=1;n-=1){const e=i[n];if(e!==void 0&&e>=t)return n}return 1},v={east:["bc01fg45238967deuvhjyznpkmstqrwx","bc01fg45238967deuvhjyznpkmstqrwx"],north:["p0r21436x8zb9dcf5h7kjnmqesgutwvy","bc01fg45238967deuvhjyznpkmstqrwx"],south:["14365h7k9dcfesgujnmqp0r2twvyx8zb","238967debc01fg45kmstqrwxuvhjyznp"],west:["238967debc01fg45kmstqrwxuvhjyznp","238967debc01fg45kmstqrwxuvhjyznp"]},M={east:["bcfguvyz","prxz"],north:["prxz","bcfguvyz"],south:["028b","0145hjnp"],west:["0145hjnp","028b"]},h=(t,n)=>{const e=t.toLowerCase(),s=e.at(-1)??"";let o=e.slice(0,-1);const r=e.length%2===0?0:1;return M[n][r].includes(s)&&o!==""&&(o=h(o,n)),o+(x[v[n][r].indexOf(s)]??"")},z=(t,n)=>{const e=p(Math.max(n,1)),s=f(t,e),o=h(s,"north"),r=h(s,"south"),l=[s,o,r,h(s,"east"),h(s,"west"),h(o,"east"),h(o,"west"),h(r,"east"),h(r,"west")];return[...new Set(l)]},q=(t,n)=>t.lat>=n.sw.lat&&t.lat<=n.ne.lat&&t.lng>=n.sw.lng&&t.lng<=n.ne.lng,j=t=>({lat:(t.sw.lat+t.ne.lat)/2,lng:(t.sw.lng+t.ne.lng)/2}),k=t=>{const n=j(t);return z(n,Math.max(m(n,t.ne),1))};export{y as GEO_DEFAULT_PRECISION,j as boundingBoxCenter,k as boundingBoxGeohashes,z as coveringGeohashes,f as encodeGeohash,m as haversineMeters,q as pointInBoundingBox};