@lunora/shard-engine 1.0.0-alpha.5 → 1.0.0-alpha.6

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.
@@ -1 +1 @@
1
- import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite--yaJW9mT.mjs";export{t as defineEngineContractSuite};
1
+ import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite-1f7OcQND.mjs";export{t as defineEngineContractSuite};
package/dist/index.d.mts CHANGED
@@ -1895,7 +1895,8 @@ interface GuardableSchema {
1895
1895
  }>;
1896
1896
  }
1897
1897
  type TableOfId = (id: string, expectedTable?: string) => Promise<string | undefined> | string | undefined;
1898
- declare const guardWriter: <W>(raw: W, schema: GuardableSchema, tableOfId: TableOfId) => W;
1898
+ type TablesOfIds = (ids: ReadonlyArray<string>, expectedTable?: string) => Promise<ReadonlyMap<string, string>> | ReadonlyMap<string, string>;
1899
+ declare const guardWriter: <W>(raw: W, schema: GuardableSchema, tableOfId: TableOfId, tablesOfIds?: TablesOfIds) => W;
1899
1900
  declare const SCHEMA_HISTORY_MAX_VERSIONS = 50;
1900
1901
  interface SchemaVersionRow {
1901
1902
  appliedAt: number;
@@ -1957,7 +1958,7 @@ interface DrainableSink {
1957
1958
  readonly bufferedAmount?: unknown;
1958
1959
  }
1959
1960
  declare const trySendFrame: (ws: FrameSink, frame: string) => boolean;
1960
- declare const sendDeltaFrames: (ws: FrameSink, subId: string, deltaFrames: ReadonlyArray<string>, cursorSuffix: string) => boolean;
1961
+ declare const sendDeltaFrames: (ws: FrameSink, subId: string, deltaFrames: ReadonlyArray<string>, cursorSuffix: string, lastMutationId?: number) => boolean;
1961
1962
  declare const awaitWsDrain: (ws: DrainableSink) => Promise<void>;
1962
1963
  interface SubscriptionReadFootprint {
1963
1964
  ranges?: Map<string, KeyRange[]>;
package/dist/index.d.ts CHANGED
@@ -1895,7 +1895,8 @@ interface GuardableSchema {
1895
1895
  }>;
1896
1896
  }
1897
1897
  type TableOfId = (id: string, expectedTable?: string) => Promise<string | undefined> | string | undefined;
1898
- declare const guardWriter: <W>(raw: W, schema: GuardableSchema, tableOfId: TableOfId) => W;
1898
+ type TablesOfIds = (ids: ReadonlyArray<string>, expectedTable?: string) => Promise<ReadonlyMap<string, string>> | ReadonlyMap<string, string>;
1899
+ declare const guardWriter: <W>(raw: W, schema: GuardableSchema, tableOfId: TableOfId, tablesOfIds?: TablesOfIds) => W;
1899
1900
  declare const SCHEMA_HISTORY_MAX_VERSIONS = 50;
1900
1901
  interface SchemaVersionRow {
1901
1902
  appliedAt: number;
@@ -1957,7 +1958,7 @@ interface DrainableSink {
1957
1958
  readonly bufferedAmount?: unknown;
1958
1959
  }
1959
1960
  declare const trySendFrame: (ws: FrameSink, frame: string) => boolean;
1960
- declare const sendDeltaFrames: (ws: FrameSink, subId: string, deltaFrames: ReadonlyArray<string>, cursorSuffix: string) => boolean;
1961
+ declare const sendDeltaFrames: (ws: FrameSink, subId: string, deltaFrames: ReadonlyArray<string>, cursorSuffix: string, lastMutationId?: number) => boolean;
1961
1962
  declare const awaitWsDrain: (ws: DrainableSink) => Promise<void>;
1962
1963
  interface SubscriptionReadFootprint {
1963
1964
  ranges?: Map<string, KeyRange[]>;
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{exportShardRows as o,exportShardTable as a,importShardRows as t,parseExportShardArgs as n,parseImportShardArgs as l,selectExportTables as i,validateImportRow as s}from"./packem_shared/exportShardRows-kt42wijd.mjs";import{AGGREGATE_SQL_FUNCTION as d,aggregateSqlFunction as p,matchesStaticWhere as c,normalizeCountArgument as S,throwingScheduler as u}from"./packem_shared/AGGREGATE_SQL_FUNCTION-QYaiuty4.mjs";import{aggregateTableName as f,coerceAggregateNumber as T,encodeAggregateKey as g,foldAggregateTally as h,readAggregateValue as A}from"./packem_shared/aggregateTableName-G-eXyjcz.mjs";import{CountRlsUnsupportedError as C,mergeWhere as I,planAggregateLookup as _,selectIndexForAggregate as R,selectIndexForCount as L,selectIndexForGroupBy as b}from"./packem_shared/CountRlsUnsupportedError-B2WKJD9v.mjs";import{AUDIT_LOG_TABLE as N,appendAuditEntry as M,ensureAuditTable as F,readAuditLog as O}from"./packem_shared/AUDIT_LOG_TABLE-CaA0jL0L.mjs";import{NotUniqueError as P,assertValidClientId as k,createShardCtxDb as B,normalizeIdStructurally as G}from"./packem_shared/NotUniqueError-C8DLoXSK.mjs";import{backfillAggregateIndexes as w,backfillRankIndexes as K,backfillSearchIndexes as q,backfillSearchIndexesForTable as W}from"./packem_shared/backfillAggregateIndexes-BHiewuB-.mjs";import{CDC_LOG_TABLE as z,CDC_META_TABLE as V,appendCdcChange as H,applyCdcChanges as X,bumpCdcEpoch as Q,migrateCdcLog as Y,migrateCdcMeta as j,minCdcSeq as J,readCdcChanges as Z,readCdcCursor as $,readCdcEpoch as ee,trimCdcChanges as re}from"./packem_shared/CDC_LOG_TABLE-BnqlH2eZ.mjs";import{CLIENT_WATERMARK_TABLE as ae,advanceClientWatermark as te,migrateClientWatermark as ne,readClientWatermark as le}from"./packem_shared/CLIENT_WATERMARK_TABLE-CXsSLU8D.mjs";import{createCompanionSync as se}from"./packem_shared/createCompanionSync-DWK0Vlg1.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as de,deleteGlobalShapeSnapshot as pe,deleteGlobalShapeSnapshotsForConnection as ce,migrateGlobalShapeSnapshot as Se,readGlobalShapeSnapshot as ue,writeGlobalShapeSnapshot as xe}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-DX-6-gBP.mjs";import{IDEMPOTENCY_TABLE as Te,migrateIdempotency as ge,readIdempotent as he,trimIdempotent as Ae,writeIdempotent as Ee}from"./packem_shared/IDEMPOTENCY_TABLE-DjkEMp6w.mjs";import{computeRankPage as Ie,hydrateDocsById as _e}from"./packem_shared/computeRankPage-IUSS-zIB.mjs";import{SEARCH_STATE_TABLE as Le,migrateSearchState as be,readSearchBackfillState as ye,writeSearchBackfillState as Ne}from"./packem_shared/SEARCH_STATE_TABLE-eLN8U5tz.mjs";import{selectShapeMemberIds as Fe,selectShapeRows as Oe}from"./packem_shared/selectShapeMemberIds-DvE7K6zG.mjs";import{DATA_MIGRATION_STATE_TABLE as Pe,readMigrationStatus as ke,runDataMigration as Be}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-BZMVrLcy.mjs";import{SCAN_DEP as Ue,createDependencyTracker as we,depKey as Ke,tableFromDepKey as qe}from"./packem_shared/SCAN_DEP-D_yR9EeV.mjs";import{runDrizzle as ve,runSql as ze}from"./packem_shared/runDrizzle-GKR3y97k.mjs";import{AGG_COUNT as He,AGG_KEY as Xe,AGG_VALUE as Qe,DOC_COLUMN as Ye,aggUpsertSql as je,createIndexSql as Je,geoTableName as Ze,isFtsAvailable as $e,jsonPath as er,jsonPathSql as rr,qualifiedJsonPath as or,qualifiedJsonPathSql as ar,quoteIdentifier as tr,rowToDocument as nr,tableColumns as lr,tryRowToDocument as ir}from"./packem_shared/AGG_COUNT-BWXe3gtQ.mjs";import{param as mr,renderSql as dr}from"./packem_shared/param-B5lF5Jd9.mjs";import{diffExternalSource as cr}from"./packem_shared/diffExternalSource-DMpkJta1.mjs";import{liftSourceId as ur,normalizeSourceDocument as xr,normalizeSourceValue as fr}from"./packem_shared/liftSourceId-DApAbu7Q.mjs";import{materializeExternalRows as gr,materializeExternalRowsIncremental as hr,readExternalSourceBaseline as Ar,runExternalSourceTick as Er}from"./packem_shared/materializeExternalRows-DOQJV9p2.mjs";import{isSoftDeleted as Ir,isSourceDue as _r,pullExternalSourceIncrementalTick as Rr,pullExternalSourceTick as Lr}from"./packem_shared/isSoftDeleted-B-SXkGUo.mjs";import{GEO_DEFAULT_PRECISION as yr,boundingBoxCenter as Nr,boundingBoxGeohashes as Mr,coveringGeohashes as Fr,encodeGeohash as Or,haversineMeters as Dr,pointInBoundingBox as Pr}from"./packem_shared/GEO_DEFAULT_PRECISION-okRCkZ6r.mjs";import{ADMIN_FUNCTIONS as Br,ADMIN_FUNCTION_PREFIX as Gr,DEFAULT_FANOUT_TOPIC_LIMIT as Ur,FLAGS_FUNCTION_PREFIX as wr,MAX_PAGE_SIZE as Kr,RELATION_FUNCTION_PREFIX as qr,createFanoutCounters as Wr,facetColumn as vr,findStorageReferences as zr,listTables as Vr,readTablePage as Hr,recordFanoutPass as Xr,selectMatchingIds as Qr,summarizeFanoutTopics as Yr,summarizeSubscriptions as jr}from"./packem_shared/ADMIN_FUNCTIONS-vj2G8OR6.mjs";import{MAIL_RETENTION as Zr,MAIL_TABLE as $r,clearCapturedMail as eo,ensureMailTable as ro,readCapturedMail as oo,recordCapturedMail as ao}from"./packem_shared/MAIL_RETENTION-KmozO2NQ.mjs";import{NotFoundError as no}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{armRestore as io,readBookmark as so}from"./packem_shared/armRestore-BNzdvQ_o.mjs";import{applySelect as po,buildSeekBeforeWhere as co,buildSeekWhere as So,decodeCursor as uo,encodeCursor as xo,normalizeOrderKeys as fo,softDeleteScope as To}from"./packem_shared/applySelect-B0CF8T7y.mjs";import{QUEUE_TABLE as ho,clearQueueMessages as Ao,isLossyBody as Eo,readQueueMessageById as Co,readQueueMessages as Io,recordQueueMessages as _o}from"./packem_shared/QUEUE_TABLE-DYCDvzTG.mjs";import{RANK_TIEBREAK as Lo,encodePartitionKey as bo,matchesRankStaticWhere as yo,rankKeyFromDoc as No,rankTableName as Mo,resolveRankPartition as Fo,sortColumnName as Oo}from"./packem_shared/RANK_TIEBREAK-9NU5s_mi.mjs";import{ReactiveCache as Po,reactiveCacheKey as ko}from"./packem_shared/ReactiveCache-DSGtSVGZ.mjs";import{createReadFootprint as Go}from"./packem_shared/createReadFootprint-DIrrxRTE.mjs";import{buildIndexRange as wo,indexKeysForRow as Ko,keysTouchRanges as qo}from"./packem_shared/buildIndexRange-DFsdtPjD.mjs";import{DEFAULT_MAX_RELATION_KEYS as vo,assertFlatPredicate as zo,assertShapeShardable as Vo,containsRelationPredicate as Ho,isRelationPredicate as Xo,resolveRelationPredicates as Qo}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-bq00btqV.mjs";import{applyOnDelete as jo,distinctValues as Jo,fanOutScalarCounts as Zo,resolveWith as $o,runRowValidators as ea}from"./packem_shared/applyOnDelete-uFRC5p1d.mjs";import{DEFAULT_PROMOTION_THRESHOLDS as oa,clampPromotionThresholds as aa,nextPromotionState as ta,relayCountFor as na,shapeRoutingKey as la}from"./packem_shared/DEFAULT_PROMOTION_THRESHOLDS-Dteg0sZF.mjs";import{DEFAULT_MAX_RELAYS as sa,OwnerRelay as ma,RelayMember as da,createRelayLink as pa}from"./packem_shared/DEFAULT_MAX_RELAYS-CnCyh6oX.mjs";import{RLS_UNWRAP_SYMBOL as Sa,RlsRequiredError as ua,guardWriter as xa}from"./packem_shared/RLS_UNWRAP_SYMBOL-C6_WX3dG.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as Ta,readSchemaHistory as ga,readSchemaVersion as ha,recordSchemaVersion as Aa}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-CHXz6p_z.mjs";import{serializeSqlValue as Ca}from"./packem_shared/serializeSqlValue-DnpyaLcw.mjs";import{buildSettings as _a,isDevEnvironment as Ra}from"./packem_shared/buildSettings-DT18_DkX.mjs";import{buildPokeFrames as ba,diffGlobalMembership as ya,encodeRowsPatch as Na,projectColumns as Ma}from"./packem_shared/buildPokeFrames-DaPpm5Ss.mjs";import{ShardRunner as Oa}from"./packem_shared/ShardRunner-DIqVdWtk.mjs";import{runSocketPool as Pa}from"./packem_shared/runSocketPool-DPQLVyWF.mjs";import{MAX_SQL_ROWS as Ba,assertReadonly as Ga,lintReadonlySql as Ua,runReadonlySql as wa}from"./packem_shared/MAX_SQL_ROWS-nMwkxv5f.mjs";import{awaitWsDrain as qa,sendDeltaFrames as Wa,subscriptionListDeltas as va,trySendFrame as za}from"./packem_shared/awaitWsDrain-Dk50ISgE.mjs";import{mergeChangedKeys as Ha,recordChangedKeys as Xa,writeTouchesMemo as Qa}from"./packem_shared/mergeChangedKeys-BXtUgIPW.mjs";import{createSystemReader as ja}from"./packem_shared/createSystemReader-DcDcrtM3.mjs";import{ConflictError as Za}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as et,TransactionHeadroomTracker as rt}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS--TtB8Gpo.mjs";import{hasTrigger as at,runTriggers as tt}from"./packem_shared/hasTrigger-CbkOHExZ.mjs";import{selectExpiredIds as lt}from"./packem_shared/selectExpiredIds-FzhIEeG1.mjs";import{compileWhereSql as st}from"./packem_shared/compileWhereSql-BLcfs4QW.mjs";import{RELATION_EXISTS_KEY as dt}from"./packem_shared/RELATION_EXISTS_KEY-BaqSIFU1.mjs";import{runShardMigrations as ct}from"./packem_shared/runShardMigrations-CPxqCh3O.mjs";import{stableStringify as ut}from"./packem_shared/stableStringify-BjLh4gvA.mjs";import{stableWireKey as ft}from"./packem_shared/stableWireKey-YEHLaX6X.mjs";export{Br as ADMIN_FUNCTIONS,Gr as ADMIN_FUNCTION_PREFIX,d as AGGREGATE_SQL_FUNCTION,He as AGG_COUNT,Xe as AGG_KEY,Qe as AGG_VALUE,N as AUDIT_LOG_TABLE,z as CDC_LOG_TABLE,V as CDC_META_TABLE,ae as CLIENT_WATERMARK_TABLE,Za as ConflictError,C as CountRlsUnsupportedError,Pe as DATA_MIGRATION_STATE_TABLE,Ur as DEFAULT_FANOUT_TOPIC_LIMIT,vo as DEFAULT_MAX_RELATION_KEYS,sa as DEFAULT_MAX_RELAYS,oa as DEFAULT_PROMOTION_THRESHOLDS,et as DEFAULT_TRANSACTION_LIMITS,Ye as DOC_COLUMN,wr as FLAGS_FUNCTION_PREFIX,yr as GEO_DEFAULT_PRECISION,de as GLOBAL_SHAPE_SNAPSHOT_TABLE,Te as IDEMPOTENCY_TABLE,Zr as MAIL_RETENTION,$r as MAIL_TABLE,Kr as MAX_PAGE_SIZE,Ba as MAX_SQL_ROWS,no as NotFoundError,P as NotUniqueError,ma as OwnerRelay,ho as QUEUE_TABLE,Lo as RANK_TIEBREAK,dt as RELATION_EXISTS_KEY,qr as RELATION_FUNCTION_PREFIX,Sa as RLS_UNWRAP_SYMBOL,Po as ReactiveCache,da as RelayMember,ua as RlsRequiredError,Ue as SCAN_DEP,Ta as SCHEMA_HISTORY_MAX_VERSIONS,Le as SEARCH_STATE_TABLE,Oa as ShardRunner,rt as TransactionHeadroomTracker,te as advanceClientWatermark,je as aggUpsertSql,p as aggregateSqlFunction,f as aggregateTableName,M as appendAuditEntry,H as appendCdcChange,X as applyCdcChanges,jo as applyOnDelete,po as applySelect,io as armRestore,zo as assertFlatPredicate,Ga as assertReadonly,Vo as assertShapeShardable,k as assertValidClientId,qa as awaitWsDrain,w as backfillAggregateIndexes,K as backfillRankIndexes,q as backfillSearchIndexes,W as backfillSearchIndexesForTable,Nr as boundingBoxCenter,Mr as boundingBoxGeohashes,wo as buildIndexRange,ba as buildPokeFrames,co as buildSeekBeforeWhere,So as buildSeekWhere,_a as buildSettings,Q as bumpCdcEpoch,aa as clampPromotionThresholds,eo as clearCapturedMail,Ao as clearQueueMessages,T as coerceAggregateNumber,st as compileWhereSql,Ie as computeRankPage,Ho as containsRelationPredicate,Fr as coveringGeohashes,se as createCompanionSync,we as createDependencyTracker,Wr as createFanoutCounters,Je as createIndexSql,Go as createReadFootprint,pa as createRelayLink,B as createShardCtxDb,ja as createSystemReader,uo as decodeCursor,pe as deleteGlobalShapeSnapshot,ce as deleteGlobalShapeSnapshotsForConnection,Ke as depKey,cr as diffExternalSource,ya as diffGlobalMembership,Jo as distinctValues,g as encodeAggregateKey,xo as encodeCursor,Or as encodeGeohash,bo as encodePartitionKey,Na as encodeRowsPatch,F as ensureAuditTable,ro as ensureMailTable,o as exportShardRows,a as exportShardTable,vr as facetColumn,Zo as fanOutScalarCounts,zr as findStorageReferences,h as foldAggregateTally,Ze as geoTableName,xa as guardWriter,at as hasTrigger,Dr as haversineMeters,_e as hydrateDocsById,t as importShardRows,Ko as indexKeysForRow,Ra as isDevEnvironment,$e as isFtsAvailable,Eo as isLossyBody,Xo as isRelationPredicate,Ir as isSoftDeleted,_r as isSourceDue,er as jsonPath,rr as jsonPathSql,qo as keysTouchRanges,ur as liftSourceId,Ua as lintReadonlySql,Vr as listTables,yo as matchesRankStaticWhere,c as matchesStaticWhere,gr as materializeExternalRows,hr as materializeExternalRowsIncremental,Ha as mergeChangedKeys,I as mergeWhere,Y as migrateCdcLog,j as migrateCdcMeta,ne as migrateClientWatermark,Se as migrateGlobalShapeSnapshot,ge as migrateIdempotency,be as migrateSearchState,J as minCdcSeq,ta as nextPromotionState,S as normalizeCountArgument,G as normalizeIdStructurally,fo as normalizeOrderKeys,xr as normalizeSourceDocument,fr as normalizeSourceValue,mr as param,n as parseExportShardArgs,l as parseImportShardArgs,_ as planAggregateLookup,Pr as pointInBoundingBox,Ma as projectColumns,Rr as pullExternalSourceIncrementalTick,Lr as pullExternalSourceTick,or as qualifiedJsonPath,ar as qualifiedJsonPathSql,tr as quoteIdentifier,No as rankKeyFromDoc,Mo as rankTableName,ko as reactiveCacheKey,A as readAggregateValue,O as readAuditLog,so as readBookmark,oo as readCapturedMail,Z as readCdcChanges,$ as readCdcCursor,ee as readCdcEpoch,le as readClientWatermark,Ar as readExternalSourceBaseline,ue as readGlobalShapeSnapshot,he as readIdempotent,ke as readMigrationStatus,Co as readQueueMessageById,Io as readQueueMessages,ga as readSchemaHistory,ha as readSchemaVersion,ye as readSearchBackfillState,Hr as readTablePage,ao as recordCapturedMail,Xa as recordChangedKeys,Xr as recordFanoutPass,_o as recordQueueMessages,Aa as recordSchemaVersion,na as relayCountFor,dr as renderSql,Fo as resolveRankPartition,Qo as resolveRelationPredicates,$o as resolveWith,nr as rowToDocument,Be as runDataMigration,ve as runDrizzle,Er as runExternalSourceTick,wa as runReadonlySql,ea as runRowValidators,ct as runShardMigrations,Pa as runSocketPool,ze as runSql,tt as runTriggers,lt as selectExpiredIds,i as selectExportTables,R as selectIndexForAggregate,L as selectIndexForCount,b as selectIndexForGroupBy,Qr as selectMatchingIds,Fe as selectShapeMemberIds,Oe as selectShapeRows,Wa as sendDeltaFrames,Ca as serializeSqlValue,la as shapeRoutingKey,To as softDeleteScope,Oo as sortColumnName,ut as stableStringify,ft as stableWireKey,va as subscriptionListDeltas,Yr as summarizeFanoutTopics,jr as summarizeSubscriptions,lr as tableColumns,qe as tableFromDepKey,u as throwingScheduler,re as trimCdcChanges,Ae as trimIdempotent,ir as tryRowToDocument,za as trySendFrame,s as validateImportRow,xe as writeGlobalShapeSnapshot,Ee as writeIdempotent,Ne as writeSearchBackfillState,Qa as writeTouchesMemo};
1
+ import{exportShardRows as o,exportShardTable as a,importShardRows as t,parseExportShardArgs as n,parseImportShardArgs as l,selectExportTables as i,validateImportRow as s}from"./packem_shared/exportShardRows-kt42wijd.mjs";import{AGGREGATE_SQL_FUNCTION as d,aggregateSqlFunction as p,matchesStaticWhere as c,normalizeCountArgument as S,throwingScheduler as u}from"./packem_shared/AGGREGATE_SQL_FUNCTION-QYaiuty4.mjs";import{aggregateTableName as f,coerceAggregateNumber as T,encodeAggregateKey as g,foldAggregateTally as h,readAggregateValue as A}from"./packem_shared/aggregateTableName-G-eXyjcz.mjs";import{CountRlsUnsupportedError as C,mergeWhere as I,planAggregateLookup as _,selectIndexForAggregate as R,selectIndexForCount as L,selectIndexForGroupBy as b}from"./packem_shared/CountRlsUnsupportedError-B2WKJD9v.mjs";import{AUDIT_LOG_TABLE as N,appendAuditEntry as M,ensureAuditTable as F,readAuditLog as O}from"./packem_shared/AUDIT_LOG_TABLE-CaA0jL0L.mjs";import{NotUniqueError as P,assertValidClientId as k,createShardCtxDb as B,normalizeIdStructurally as G}from"./packem_shared/NotUniqueError-Qrtwm7S6.mjs";import{backfillAggregateIndexes as w,backfillRankIndexes as K,backfillSearchIndexes as q,backfillSearchIndexesForTable as W}from"./packem_shared/backfillAggregateIndexes-BHiewuB-.mjs";import{CDC_LOG_TABLE as z,CDC_META_TABLE as V,appendCdcChange as H,applyCdcChanges as X,bumpCdcEpoch as Q,migrateCdcLog as Y,migrateCdcMeta as j,minCdcSeq as J,readCdcChanges as Z,readCdcCursor as $,readCdcEpoch as ee,trimCdcChanges as re}from"./packem_shared/CDC_LOG_TABLE-BnqlH2eZ.mjs";import{CLIENT_WATERMARK_TABLE as ae,advanceClientWatermark as te,migrateClientWatermark as ne,readClientWatermark as le}from"./packem_shared/CLIENT_WATERMARK_TABLE-CXsSLU8D.mjs";import{createCompanionSync as se}from"./packem_shared/createCompanionSync-DWK0Vlg1.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as de,deleteGlobalShapeSnapshot as pe,deleteGlobalShapeSnapshotsForConnection as ce,migrateGlobalShapeSnapshot as Se,readGlobalShapeSnapshot as ue,writeGlobalShapeSnapshot as xe}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-DX-6-gBP.mjs";import{IDEMPOTENCY_TABLE as Te,migrateIdempotency as ge,readIdempotent as he,trimIdempotent as Ae,writeIdempotent as Ee}from"./packem_shared/IDEMPOTENCY_TABLE-DjkEMp6w.mjs";import{computeRankPage as Ie,hydrateDocsById as _e}from"./packem_shared/computeRankPage-IUSS-zIB.mjs";import{SEARCH_STATE_TABLE as Le,migrateSearchState as be,readSearchBackfillState as ye,writeSearchBackfillState as Ne}from"./packem_shared/SEARCH_STATE_TABLE-eLN8U5tz.mjs";import{selectShapeMemberIds as Fe,selectShapeRows as Oe}from"./packem_shared/selectShapeMemberIds-DvE7K6zG.mjs";import{DATA_MIGRATION_STATE_TABLE as Pe,readMigrationStatus as ke,runDataMigration as Be}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-BZMVrLcy.mjs";import{SCAN_DEP as Ue,createDependencyTracker as we,depKey as Ke,tableFromDepKey as qe}from"./packem_shared/SCAN_DEP-D_yR9EeV.mjs";import{runDrizzle as ve,runSql as ze}from"./packem_shared/runDrizzle-GKR3y97k.mjs";import{AGG_COUNT as He,AGG_KEY as Xe,AGG_VALUE as Qe,DOC_COLUMN as Ye,aggUpsertSql as je,createIndexSql as Je,geoTableName as Ze,isFtsAvailable as $e,jsonPath as er,jsonPathSql as rr,qualifiedJsonPath as or,qualifiedJsonPathSql as ar,quoteIdentifier as tr,rowToDocument as nr,tableColumns as lr,tryRowToDocument as ir}from"./packem_shared/AGG_COUNT-BWXe3gtQ.mjs";import{param as mr,renderSql as dr}from"./packem_shared/param-B5lF5Jd9.mjs";import{diffExternalSource as cr}from"./packem_shared/diffExternalSource-DMpkJta1.mjs";import{liftSourceId as ur,normalizeSourceDocument as xr,normalizeSourceValue as fr}from"./packem_shared/liftSourceId-DApAbu7Q.mjs";import{materializeExternalRows as gr,materializeExternalRowsIncremental as hr,readExternalSourceBaseline as Ar,runExternalSourceTick as Er}from"./packem_shared/materializeExternalRows-DOQJV9p2.mjs";import{isSoftDeleted as Ir,isSourceDue as _r,pullExternalSourceIncrementalTick as Rr,pullExternalSourceTick as Lr}from"./packem_shared/isSoftDeleted-B-SXkGUo.mjs";import{GEO_DEFAULT_PRECISION as yr,boundingBoxCenter as Nr,boundingBoxGeohashes as Mr,coveringGeohashes as Fr,encodeGeohash as Or,haversineMeters as Dr,pointInBoundingBox as Pr}from"./packem_shared/GEO_DEFAULT_PRECISION-okRCkZ6r.mjs";import{ADMIN_FUNCTIONS as Br,ADMIN_FUNCTION_PREFIX as Gr,DEFAULT_FANOUT_TOPIC_LIMIT as Ur,FLAGS_FUNCTION_PREFIX as wr,MAX_PAGE_SIZE as Kr,RELATION_FUNCTION_PREFIX as qr,createFanoutCounters as Wr,facetColumn as vr,findStorageReferences as zr,listTables as Vr,readTablePage as Hr,recordFanoutPass as Xr,selectMatchingIds as Qr,summarizeFanoutTopics as Yr,summarizeSubscriptions as jr}from"./packem_shared/ADMIN_FUNCTIONS-vj2G8OR6.mjs";import{MAIL_RETENTION as Zr,MAIL_TABLE as $r,clearCapturedMail as eo,ensureMailTable as ro,readCapturedMail as oo,recordCapturedMail as ao}from"./packem_shared/MAIL_RETENTION-KmozO2NQ.mjs";import{NotFoundError as no}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{armRestore as io,readBookmark as so}from"./packem_shared/armRestore-BNzdvQ_o.mjs";import{applySelect as po,buildSeekBeforeWhere as co,buildSeekWhere as So,decodeCursor as uo,encodeCursor as xo,normalizeOrderKeys as fo,softDeleteScope as To}from"./packem_shared/applySelect-B0CF8T7y.mjs";import{QUEUE_TABLE as ho,clearQueueMessages as Ao,isLossyBody as Eo,readQueueMessageById as Co,readQueueMessages as Io,recordQueueMessages as _o}from"./packem_shared/QUEUE_TABLE-DYCDvzTG.mjs";import{RANK_TIEBREAK as Lo,encodePartitionKey as bo,matchesRankStaticWhere as yo,rankKeyFromDoc as No,rankTableName as Mo,resolveRankPartition as Fo,sortColumnName as Oo}from"./packem_shared/RANK_TIEBREAK-9NU5s_mi.mjs";import{ReactiveCache as Po,reactiveCacheKey as ko}from"./packem_shared/ReactiveCache-C6QAa7MG.mjs";import{createReadFootprint as Go}from"./packem_shared/createReadFootprint-DIrrxRTE.mjs";import{buildIndexRange as wo,indexKeysForRow as Ko,keysTouchRanges as qo}from"./packem_shared/buildIndexRange-DFsdtPjD.mjs";import{DEFAULT_MAX_RELATION_KEYS as vo,assertFlatPredicate as zo,assertShapeShardable as Vo,containsRelationPredicate as Ho,isRelationPredicate as Xo,resolveRelationPredicates as Qo}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-bq00btqV.mjs";import{applyOnDelete as jo,distinctValues as Jo,fanOutScalarCounts as Zo,resolveWith as $o,runRowValidators as ea}from"./packem_shared/applyOnDelete-uFRC5p1d.mjs";import{DEFAULT_PROMOTION_THRESHOLDS as oa,clampPromotionThresholds as aa,nextPromotionState as ta,relayCountFor as na,shapeRoutingKey as la}from"./packem_shared/DEFAULT_PROMOTION_THRESHOLDS-Dteg0sZF.mjs";import{DEFAULT_MAX_RELAYS as sa,OwnerRelay as ma,RelayMember as da,createRelayLink as pa}from"./packem_shared/DEFAULT_MAX_RELAYS-D0oc40p6.mjs";import{RLS_UNWRAP_SYMBOL as Sa,RlsRequiredError as ua,guardWriter as xa}from"./packem_shared/RLS_UNWRAP_SYMBOL-CBYPlYBb.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as Ta,readSchemaHistory as ga,readSchemaVersion as ha,recordSchemaVersion as Aa}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-CHXz6p_z.mjs";import{serializeSqlValue as Ca}from"./packem_shared/serializeSqlValue-DnpyaLcw.mjs";import{buildSettings as _a,isDevEnvironment as Ra}from"./packem_shared/buildSettings-DT18_DkX.mjs";import{buildPokeFrames as ba,diffGlobalMembership as ya,encodeRowsPatch as Na,projectColumns as Ma}from"./packem_shared/buildPokeFrames-DaPpm5Ss.mjs";import{ShardRunner as Oa}from"./packem_shared/ShardRunner-DIqVdWtk.mjs";import{runSocketPool as Pa}from"./packem_shared/runSocketPool-DPQLVyWF.mjs";import{MAX_SQL_ROWS as Ba,assertReadonly as Ga,lintReadonlySql as Ua,runReadonlySql as wa}from"./packem_shared/MAX_SQL_ROWS-nMwkxv5f.mjs";import{awaitWsDrain as qa,sendDeltaFrames as Wa,subscriptionListDeltas as va,trySendFrame as za}from"./packem_shared/awaitWsDrain-CCZ-8wjm.mjs";import{mergeChangedKeys as Ha,recordChangedKeys as Xa,writeTouchesMemo as Qa}from"./packem_shared/mergeChangedKeys-BXtUgIPW.mjs";import{createSystemReader as ja}from"./packem_shared/createSystemReader-DcDcrtM3.mjs";import{ConflictError as Za}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as et,TransactionHeadroomTracker as rt}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS-BH5q0Ror.mjs";import{hasTrigger as at,runTriggers as tt}from"./packem_shared/hasTrigger-CbkOHExZ.mjs";import{selectExpiredIds as lt}from"./packem_shared/selectExpiredIds-FzhIEeG1.mjs";import{compileWhereSql as st}from"./packem_shared/compileWhereSql-BLcfs4QW.mjs";import{RELATION_EXISTS_KEY as dt}from"./packem_shared/RELATION_EXISTS_KEY-BaqSIFU1.mjs";import{runShardMigrations as ct}from"./packem_shared/runShardMigrations-CPxqCh3O.mjs";import{stableStringify as ut}from"./packem_shared/stableStringify-BjLh4gvA.mjs";import{stableWireKey as ft}from"./packem_shared/stableWireKey-YEHLaX6X.mjs";export{Br as ADMIN_FUNCTIONS,Gr as ADMIN_FUNCTION_PREFIX,d as AGGREGATE_SQL_FUNCTION,He as AGG_COUNT,Xe as AGG_KEY,Qe as AGG_VALUE,N as AUDIT_LOG_TABLE,z as CDC_LOG_TABLE,V as CDC_META_TABLE,ae as CLIENT_WATERMARK_TABLE,Za as ConflictError,C as CountRlsUnsupportedError,Pe as DATA_MIGRATION_STATE_TABLE,Ur as DEFAULT_FANOUT_TOPIC_LIMIT,vo as DEFAULT_MAX_RELATION_KEYS,sa as DEFAULT_MAX_RELAYS,oa as DEFAULT_PROMOTION_THRESHOLDS,et as DEFAULT_TRANSACTION_LIMITS,Ye as DOC_COLUMN,wr as FLAGS_FUNCTION_PREFIX,yr as GEO_DEFAULT_PRECISION,de as GLOBAL_SHAPE_SNAPSHOT_TABLE,Te as IDEMPOTENCY_TABLE,Zr as MAIL_RETENTION,$r as MAIL_TABLE,Kr as MAX_PAGE_SIZE,Ba as MAX_SQL_ROWS,no as NotFoundError,P as NotUniqueError,ma as OwnerRelay,ho as QUEUE_TABLE,Lo as RANK_TIEBREAK,dt as RELATION_EXISTS_KEY,qr as RELATION_FUNCTION_PREFIX,Sa as RLS_UNWRAP_SYMBOL,Po as ReactiveCache,da as RelayMember,ua as RlsRequiredError,Ue as SCAN_DEP,Ta as SCHEMA_HISTORY_MAX_VERSIONS,Le as SEARCH_STATE_TABLE,Oa as ShardRunner,rt as TransactionHeadroomTracker,te as advanceClientWatermark,je as aggUpsertSql,p as aggregateSqlFunction,f as aggregateTableName,M as appendAuditEntry,H as appendCdcChange,X as applyCdcChanges,jo as applyOnDelete,po as applySelect,io as armRestore,zo as assertFlatPredicate,Ga as assertReadonly,Vo as assertShapeShardable,k as assertValidClientId,qa as awaitWsDrain,w as backfillAggregateIndexes,K as backfillRankIndexes,q as backfillSearchIndexes,W as backfillSearchIndexesForTable,Nr as boundingBoxCenter,Mr as boundingBoxGeohashes,wo as buildIndexRange,ba as buildPokeFrames,co as buildSeekBeforeWhere,So as buildSeekWhere,_a as buildSettings,Q as bumpCdcEpoch,aa as clampPromotionThresholds,eo as clearCapturedMail,Ao as clearQueueMessages,T as coerceAggregateNumber,st as compileWhereSql,Ie as computeRankPage,Ho as containsRelationPredicate,Fr as coveringGeohashes,se as createCompanionSync,we as createDependencyTracker,Wr as createFanoutCounters,Je as createIndexSql,Go as createReadFootprint,pa as createRelayLink,B as createShardCtxDb,ja as createSystemReader,uo as decodeCursor,pe as deleteGlobalShapeSnapshot,ce as deleteGlobalShapeSnapshotsForConnection,Ke as depKey,cr as diffExternalSource,ya as diffGlobalMembership,Jo as distinctValues,g as encodeAggregateKey,xo as encodeCursor,Or as encodeGeohash,bo as encodePartitionKey,Na as encodeRowsPatch,F as ensureAuditTable,ro as ensureMailTable,o as exportShardRows,a as exportShardTable,vr as facetColumn,Zo as fanOutScalarCounts,zr as findStorageReferences,h as foldAggregateTally,Ze as geoTableName,xa as guardWriter,at as hasTrigger,Dr as haversineMeters,_e as hydrateDocsById,t as importShardRows,Ko as indexKeysForRow,Ra as isDevEnvironment,$e as isFtsAvailable,Eo as isLossyBody,Xo as isRelationPredicate,Ir as isSoftDeleted,_r as isSourceDue,er as jsonPath,rr as jsonPathSql,qo as keysTouchRanges,ur as liftSourceId,Ua as lintReadonlySql,Vr as listTables,yo as matchesRankStaticWhere,c as matchesStaticWhere,gr as materializeExternalRows,hr as materializeExternalRowsIncremental,Ha as mergeChangedKeys,I as mergeWhere,Y as migrateCdcLog,j as migrateCdcMeta,ne as migrateClientWatermark,Se as migrateGlobalShapeSnapshot,ge as migrateIdempotency,be as migrateSearchState,J as minCdcSeq,ta as nextPromotionState,S as normalizeCountArgument,G as normalizeIdStructurally,fo as normalizeOrderKeys,xr as normalizeSourceDocument,fr as normalizeSourceValue,mr as param,n as parseExportShardArgs,l as parseImportShardArgs,_ as planAggregateLookup,Pr as pointInBoundingBox,Ma as projectColumns,Rr as pullExternalSourceIncrementalTick,Lr as pullExternalSourceTick,or as qualifiedJsonPath,ar as qualifiedJsonPathSql,tr as quoteIdentifier,No as rankKeyFromDoc,Mo as rankTableName,ko as reactiveCacheKey,A as readAggregateValue,O as readAuditLog,so as readBookmark,oo as readCapturedMail,Z as readCdcChanges,$ as readCdcCursor,ee as readCdcEpoch,le as readClientWatermark,Ar as readExternalSourceBaseline,ue as readGlobalShapeSnapshot,he as readIdempotent,ke as readMigrationStatus,Co as readQueueMessageById,Io as readQueueMessages,ga as readSchemaHistory,ha as readSchemaVersion,ye as readSearchBackfillState,Hr as readTablePage,ao as recordCapturedMail,Xa as recordChangedKeys,Xr as recordFanoutPass,_o as recordQueueMessages,Aa as recordSchemaVersion,na as relayCountFor,dr as renderSql,Fo as resolveRankPartition,Qo as resolveRelationPredicates,$o as resolveWith,nr as rowToDocument,Be as runDataMigration,ve as runDrizzle,Er as runExternalSourceTick,wa as runReadonlySql,ea as runRowValidators,ct as runShardMigrations,Pa as runSocketPool,ze as runSql,tt as runTriggers,lt as selectExpiredIds,i as selectExportTables,R as selectIndexForAggregate,L as selectIndexForCount,b as selectIndexForGroupBy,Qr as selectMatchingIds,Fe as selectShapeMemberIds,Oe as selectShapeRows,Wa as sendDeltaFrames,Ca as serializeSqlValue,la as shapeRoutingKey,To as softDeleteScope,Oo as sortColumnName,ut as stableStringify,ft as stableWireKey,va as subscriptionListDeltas,Yr as summarizeFanoutTopics,jr as summarizeSubscriptions,lr as tableColumns,qe as tableFromDepKey,u as throwingScheduler,re as trimCdcChanges,Ae as trimIdempotent,ir as tryRowToDocument,za as trySendFrame,s as validateImportRow,xe as writeGlobalShapeSnapshot,Ee as writeIdempotent,Ne as writeSearchBackfillState,Qa as writeTouchesMemo};
@@ -1 +1 @@
1
- import{toErrorBody as k,LunoraError as N}from"@lunora/errors";import{f as g,c as R}from"./wire-codec-Ctnni0h6.mjs";import{relayName as p,nextPromotionState as L,shapeRoutingKey as f,parseRelayName as C,clampPromotionThresholds as O,DEFAULT_PROMOTION_THRESHOLDS as w}from"./DEFAULT_PROMOTION_THRESHOLDS-Dteg0sZF.mjs";import{encodeRowsPatch as b,buildPokeFrames as v}from"./buildPokeFrames-DaPpm5Ss.mjs";import{awaitWsDrain as T,trySendFrame as I}from"./awaitWsDrain-Dk50ISgE.mjs";import{stableWireKey as u}from"./stableWireKey-YEHLaX6X.mjs";const D=(i,e)=>{const t=Math.max(i.length,e.length);let s=i.length^e.length;for(let r=0;r<t;r+=1){const a=r<i.length?i.charCodeAt(r):0,o=r<e.length?e.charCodeAt(r):0;s|=a^o}return s===0},F=2,x=8,$="LUNORA_RELAY_SECRET",_="x-lunora-relay-sig",E=i=>{const e=i?.[$];return typeof e=="string"&&e.length>0?e:void 0},A=async(i,e)=>{const t=new TextEncoder,s=await crypto.subtle.importKey("raw",t.encode(i),{hash:"SHA-256",name:"HMAC"},!1,["sign"]),r=await crypto.subtle.sign("HMAC",s,t.encode(e));return[...new Uint8Array(r)].map(a=>a.toString(16).padStart(2,"0")).join("")},y=(i,e,t)=>{const s=i?.[e];let r=Number.NaN;return typeof s=="string"?r=Number.parseInt(s,10):typeof s=="number"&&(r=s),Number.isInteger(r)&&r>0?r:t},S={},U=i=>{throw new N("INTERNAL",`unhandled relay frame: ${JSON.stringify(i)}`)},K=i=>{if(i===null||typeof i!="object")return;const e=i;return typeof e.idFromName=="function"&&typeof e.get=="function"?e:void 0},W=i=>Response.json(i,{headers:{"content-type":"application/json"}}),m=()=>new Response(null,{status:204});class P{constructor(e,t){this.host=e,this.roleId=t}host;roleId;async handleControl(e){let t;try{t=await e.text()}catch{return new Response("bad request",{status:400})}const s=E(this.host.env());if(s!==void 0){const a=e.headers.get(_),o=await A(s,t);if(a===null||!D(a,o))return new Response("forbidden",{status:403})}let r;try{r=JSON.parse(t)}catch{return new Response("bad request",{status:400})}switch(r.type){case"relay_attach":return this.onAttach(r.relayIndex),m();case"relay_detach":return this.onDetach(r.relayIndex),m();case"relay_frame":return this.host.deliverWhisperLocal(r.topic,r.frame,void 0),await this.onWhisperFrame(r),m();case"relay_shape_poke":{const a=this.host.getWebSockets().length,o=Date.now(),n=this.onShapePoke({...r,args:R(r.args)});return this.host.recordShapePokeFanout(a,n,Date.now()-o),m()}case"relay_shape_subscribe":return W(this.onShapeSubscribe({...r,args:R(r.args)}));default:return U(r)}}maxRelays(){return y(this.host.env(),"LUNORA_MAX_RELAYS",x)}canAddressSiblings(){return this.relayNamespace()!==void 0}relayNamespace(){const e=this.host.shardBinding();if(e!==void 0)return K(this.host.env()?.[e])}async postRelayMessage(e,t){await this.requestRelayMessage(e,t)}async requestRelayMessage(e,t){const s=this.relayNamespace();if(s===void 0)return;const r=typeof s.getByName=="function"?s.getByName(e):s.get(s.idFromName(e)),a=JSON.stringify(t),o={"content-type":"application/json","x-lunora-shard-binding":this.host.shardBinding()??""},n=E(this.host.env());n!==void 0&&(o[_]=await A(n,a));try{return await r.fetch("https://relay.internal/_lunora/relay",{body:a,headers:o,method:"POST"})}catch{return}}}class q extends P{shapeUniformCache=new Map;relaySetCache;relayShapeRegistry=new Map;relayShapeProxies=new Map;promotionState="owned";constructor(e,t){super(e,{ownerKey:t})}async forwardWhisper(e,t){if(!this.canAddressSiblings())return;const s=this.ownerRelaySet();s.size!==0&&await Promise.all([...s].map(r=>this.postRelayMessage(p(this.roleId.ownerKey,r),{frame:t,topic:e,type:"relay_frame"})))}async onFlush(e,t){await Promise.all([this.multicastShapePokes(e,t),this.proxyShapePokes(e,t)])}seedRelayShape(){return Promise.resolve(void 0)}announce(){return Promise.resolve()}announceDrain(){return Promise.resolve()}relayCount(){const e=this.host.getWebSockets().length,t=y(this.host.env(),"LUNORA_RELAY_THRESHOLD",w.tUp),s=y(this.host.env(),"LUNORA_RELAY_COLLAPSE_THRESHOLD",w.tDown);if(this.promotionState=L(this.promotionState,e,O(t,s)),this.promotionState==="owned")return 0;const r=y(this.host.env(),"LUNORA_MAX_RELAYS",x),a=y(this.host.env(),"LUNORA_RELAY_FAN",F);return Math.min(r,Math.max(1,a))}isShapeRelayUniform(e,t){const s=f(e,t),r=this.shapeUniformCache.get(s);if(r!==void 0)return r;const a=this.probeShapeRelayUniform(e,t);return this.shapeUniformCache.set(s,a),a}onAttach(e){this.addRelayToSet(e)}onDetach(e){this.removeRelayFromSet(e)}async onWhisperFrame(e){await Promise.all([...this.ownerRelaySet()].filter(t=>t!==e.originRelay).map(t=>this.postRelayMessage(p(this.roleId.ownerKey,t),{frame:e.frame,topic:e.topic,type:"relay_frame"})))}onShapeSubscribe(e){return this.buildShapeSeedFrames(e)}onShapePoke(){return 0}async multicastShapePokes(e,t){if(this.relayShapeRegistry.size===0)return;const s=this.ownerRelaySet();if(s.size===0)return;const r=this.host.currentCdcEpoch(),a=[];for(const o of this.relayShapeRegistry.values()){let n;try{n=this.host.resolveShape(o.name,o.args,S)}catch{continue}if(n===void 0||n.global===!0||!e.has(n.table))continue;const h=o.cursor,l=this.host.buildShapeDiff(n,h,t);if(l.length===0)continue;o.cursor=t;const d={args:g(o.args),checkpoint:t,epoch:r,fromCursor:h,name:o.name,rowsPatch:b(l),type:"relay_shape_poke"};for(const c of s)a.push(this.postRelayMessage(p(this.roleId.ownerKey,c),d))}await Promise.all(a)}async proxyShapePokes(e,t){if(this.relayShapeProxies.size===0)return;const s=this.host.currentCdcEpoch(),r=[];for(const a of this.relayShapeProxies.values()){let o;try{o=this.host.resolveShape(a.name,a.args,a.identity)}catch{continue}if(o===void 0||o.global===!0||!e.has(o.table))continue;const n=a.cursor,h=this.host.buildShapeDiff(o,n,t);if(h.length===0)continue;a.cursor=t;const l={args:g(a.args),checkpoint:t,epoch:s,fromCursor:n,name:a.name,rowsPatch:b(h),targetConnectionId:a.connectionId,type:"relay_shape_poke"};r.push(this.postRelayMessage(p(this.roleId.ownerKey,a.relayIndex),l))}await Promise.all(r)}buildShapeSeedFrames(e){const t={identity:e.identity,userId:e.userId};let s;try{s=this.host.resolveShape(e.name,e.args,t)}catch(d){const{body:c}=k(d,{fallbackCode:"SHAPE_RESOLVE_FAILED",redactedMessage:"shape resolution failed"});return{error:{code:c.code,message:c.message}}}if(s===void 0||s.global===!0)return{error:{code:"SHAPE_NOT_FOUND",message:`shape not relayable: ${e.name}`}};e.relayIndex!==void 0&&this.addRelayToSet(e.relayIndex);const{baseCheckpoint:r,cursor:a,epoch:o,rowsPatch:n}=this.host.computeOpLogShapeSeed({args:e.args,name:e.name,sinceEpoch:e.sinceEpoch,sinceSeq:e.sinceSeq},s);let h=a;if(this.isShapeRelayUniform(e.name,e.args)){const d=f(e.name,e.args);let c=this.relayShapeRegistry.get(d);c===void 0&&(c={args:e.args,cursor:a,name:e.name},this.relayShapeRegistry.set(d,c)),h=c.cursor}else e.relayIndex!==void 0&&e.connectionId!==void 0&&this.relayShapeProxies.set(`${String(e.relayIndex)}:${e.connectionId}:${e.subId}`,{args:e.args,connectionId:e.connectionId,cursor:a,epoch:o,identity:t,name:e.name,relayIndex:e.relayIndex,subId:e.subId});const l=v([{rowsPatch:n,shapeId:e.subId}],{baseCheckpoint:r,checkpoint:a,epoch:o,lastMutationId:void 0,pokeId:this.host.nextPokeId()});return{cursor:h,epoch:o,frames:l}}ensureRelayTable(){this.host.sql().exec("CREATE TABLE IF NOT EXISTS __lunora_relays (idx INTEGER PRIMARY KEY)")}ownerRelaySet(){if(this.relaySetCache===void 0){this.ensureRelayTable();const e=this.host.sql().exec("SELECT idx FROM __lunora_relays").toArray();this.relaySetCache=new Set(e.map(t=>Number(t.idx)))}return this.relaySetCache}addRelayToSet(e){this.ensureRelayTable(),this.host.sql().exec("INSERT OR IGNORE INTO __lunora_relays (idx) VALUES (?)",e),this.ownerRelaySet().add(e)}removeRelayFromSet(e){this.ensureRelayTable(),this.host.sql().exec("DELETE FROM __lunora_relays WHERE idx = ?",e);const t=this.ownerRelaySet();t.delete(e);for(const[s,r]of this.relayShapeProxies)r.relayIndex===e&&this.relayShapeProxies.delete(s);t.size===0&&(this.relayShapeRegistry.clear(),this.shapeUniformCache.clear())}probeShapeRelayUniform(e,t){let s;try{s=this.host.resolveShape(e,t,S)}catch{return!1}if(s===void 0||s.global===!0||this.host.rlsMetadata().policies.some(h=>h.on==="read"&&h.table===s.table)||this.tableHasAnyMask(s.table))return!1;const r=u(s.effectiveWhere),a=u(s.columns);let o=!1;const n=h=>{const l={groups:[`grp_${h}`],roles:[h],sub:`__lunora_probe_${h}__`};return{identity:new Proxy(l,{get:(d,c)=>typeof c=="symbol"||c in d?Reflect.get(d,c):`${h}:${c}`,getOwnPropertyDescriptor:(d,c)=>(o=!0,Reflect.getOwnPropertyDescriptor(d,c)),has:(d,c)=>typeof c=="symbol"?Reflect.has(d,c):!0,ownKeys:d=>(o=!0,Reflect.ownKeys(d))}),userId:`__lunora_probe_${h}__`}};return[S,n("a"),n("b")].every(h=>{let l;try{l=this.host.resolveShape(e,t,h)}catch{return!1}return l!==void 0&&l.global!==!0&&l.table===s.table&&u(l.effectiveWhere)===r&&u(l.columns)===a})&&!o}tableHasAnyMask(e){return this.host.maskMetadata().columns.some(t=>t.table===e)}}class H extends P{relayAnnounced=!1;shapeRelayMemos=new WeakMap;constructor(e,t,s){super(e,{ownerKey:t,relayIndex:s})}async forwardWhisper(e,t){this.canAddressSiblings()&&await this.postRelayMessage(this.roleId.ownerKey,{frame:t,originRelay:this.roleId.relayIndex,topic:e,type:"relay_frame"})}onFlush(){return Promise.resolve()}async seedRelayShape(e,t,s,r){if(!this.canAddressSiblings())return{code:"RELAY_MISCONFIGURED",message:"relay cannot address its owner"};await this.announce();const a={args:g(s.args??{}),connectionId:this.host.readAttachment(e).connectionId,identity:r.identity,name:s.name,relayIndex:this.roleId.relayIndex,sinceEpoch:s.sinceEpoch,sinceSeq:s.sinceSeq,subId:t,type:"relay_shape_subscribe",userId:r.userId},o=await this.requestRelayMessage(this.roleId.ownerKey,a);if(o===void 0)return{code:"RELAY_SEED_FAILED",message:"owner did not answer the shape seed"};let n;try{n=await o.json()}catch{return{code:"RELAY_SEED_FAILED",message:"malformed shape seed from owner"}}if(n.error!==void 0)return n.error;if(n.frames===void 0)return{code:"RELAY_SEED_FAILED",message:"owner returned no shape frames"};await T(e);for(const h of n.frames)I(e,h);return this.recordRelayShapeMemo(e,t,n.cursor??0,n.epoch),"ok"}async announce(){this.relayAnnounced||!this.canAddressSiblings()||(this.relayAnnounced=!0,(await this.requestRelayMessage(this.roleId.ownerKey,{relayIndex:this.roleId.relayIndex,type:"relay_attach"}))?.ok||(this.relayAnnounced=!1))}async announceDrain(e){this.canAddressSiblings()&&(this.host.getWebSockets().some(t=>t!==e)||(this.relayAnnounced=!1,await this.postRelayMessage(this.roleId.ownerKey,{relayIndex:this.roleId.relayIndex,type:"relay_detach"})))}relayCount(){return 0}isShapeRelayUniform(){return!1}onAttach(){}onDetach(){}onWhisperFrame(){return Promise.resolve()}onShapeSubscribe(){return{error:{code:"RELAY_CANNOT_SEED",message:"a relay has no op-log to seed from"}}}onShapePoke(e){return this.deliverShapePoke(e)}recordRelayShapeMemo(e,t,s,r){let a=this.shapeRelayMemos.get(e);a===void 0&&(a=new Map,this.shapeRelayMemos.set(e,a)),a.set(t,{cursor:s,epoch:r})}deliverShapePoke(e){const t=f(e.name,e.args);let s=0;for(const r of this.host.getWebSockets()){const a=this.host.readAttachment(r),{shapes:o}=a,n=this.shapeRelayMemos.get(r);if(!(o===void 0||n===void 0)&&!(e.targetConnectionId!==void 0&&a.connectionId!==e.targetConnectionId))for(const[h,l]of Object.entries(o)){const d=n.get(h);if(d?.cursor!==e.fromCursor||d.epoch!==e.epoch||f(l.name,l.args)!==t)continue;const c=v([{rowsPatch:e.rowsPatch,shapeId:h}],{baseCheckpoint:void 0,checkpoint:e.checkpoint,epoch:e.epoch,lastMutationId:void 0,pokeId:this.host.nextPokeId()},{preEncoded:!0});for(const M of c)I(r,M);n.set(h,{cursor:e.checkpoint,epoch:e.epoch}),s+=1}}return s}}const J=i=>{const e=i.doName();if(e===void 0)return;const t=C(e);return t===void 0?new q(i,e):new H(i,t.ownerKey,t.relayIndex)};export{x as DEFAULT_MAX_RELAYS,q as OwnerRelay,H as RelayMember,J as createRelayLink};
1
+ import{toErrorBody as k,LunoraError as N}from"@lunora/errors";import{f as g,c as R}from"./wire-codec-Ctnni0h6.mjs";import{relayName as p,nextPromotionState as L,shapeRoutingKey as f,parseRelayName as C,clampPromotionThresholds as O,DEFAULT_PROMOTION_THRESHOLDS as w}from"./DEFAULT_PROMOTION_THRESHOLDS-Dteg0sZF.mjs";import{encodeRowsPatch as b,buildPokeFrames as v}from"./buildPokeFrames-DaPpm5Ss.mjs";import{awaitWsDrain as T,trySendFrame as I}from"./awaitWsDrain-CCZ-8wjm.mjs";import{stableWireKey as u}from"./stableWireKey-YEHLaX6X.mjs";const D=(i,e)=>{const t=Math.max(i.length,e.length);let s=i.length^e.length;for(let r=0;r<t;r+=1){const a=r<i.length?i.charCodeAt(r):0,o=r<e.length?e.charCodeAt(r):0;s|=a^o}return s===0},F=2,x=8,$="LUNORA_RELAY_SECRET",_="x-lunora-relay-sig",E=i=>{const e=i?.[$];return typeof e=="string"&&e.length>0?e:void 0},A=async(i,e)=>{const t=new TextEncoder,s=await crypto.subtle.importKey("raw",t.encode(i),{hash:"SHA-256",name:"HMAC"},!1,["sign"]),r=await crypto.subtle.sign("HMAC",s,t.encode(e));return[...new Uint8Array(r)].map(a=>a.toString(16).padStart(2,"0")).join("")},y=(i,e,t)=>{const s=i?.[e];let r=Number.NaN;return typeof s=="string"?r=Number.parseInt(s,10):typeof s=="number"&&(r=s),Number.isInteger(r)&&r>0?r:t},S={},U=i=>{throw new N("INTERNAL",`unhandled relay frame: ${JSON.stringify(i)}`)},K=i=>{if(i===null||typeof i!="object")return;const e=i;return typeof e.idFromName=="function"&&typeof e.get=="function"?e:void 0},W=i=>Response.json(i,{headers:{"content-type":"application/json"}}),m=()=>new Response(null,{status:204});class P{constructor(e,t){this.host=e,this.roleId=t}host;roleId;async handleControl(e){let t;try{t=await e.text()}catch{return new Response("bad request",{status:400})}const s=E(this.host.env());if(s!==void 0){const a=e.headers.get(_),o=await A(s,t);if(a===null||!D(a,o))return new Response("forbidden",{status:403})}let r;try{r=JSON.parse(t)}catch{return new Response("bad request",{status:400})}switch(r.type){case"relay_attach":return this.onAttach(r.relayIndex),m();case"relay_detach":return this.onDetach(r.relayIndex),m();case"relay_frame":return this.host.deliverWhisperLocal(r.topic,r.frame,void 0),await this.onWhisperFrame(r),m();case"relay_shape_poke":{const a=this.host.getWebSockets().length,o=Date.now(),n=this.onShapePoke({...r,args:R(r.args)});return this.host.recordShapePokeFanout(a,n,Date.now()-o),m()}case"relay_shape_subscribe":return W(this.onShapeSubscribe({...r,args:R(r.args)}));default:return U(r)}}maxRelays(){return y(this.host.env(),"LUNORA_MAX_RELAYS",x)}canAddressSiblings(){return this.relayNamespace()!==void 0}relayNamespace(){const e=this.host.shardBinding();if(e!==void 0)return K(this.host.env()?.[e])}async postRelayMessage(e,t){await this.requestRelayMessage(e,t)}async requestRelayMessage(e,t){const s=this.relayNamespace();if(s===void 0)return;const r=typeof s.getByName=="function"?s.getByName(e):s.get(s.idFromName(e)),a=JSON.stringify(t),o={"content-type":"application/json","x-lunora-shard-binding":this.host.shardBinding()??""},n=E(this.host.env());n!==void 0&&(o[_]=await A(n,a));try{return await r.fetch("https://relay.internal/_lunora/relay",{body:a,headers:o,method:"POST"})}catch{return}}}class q extends P{shapeUniformCache=new Map;relaySetCache;relayShapeRegistry=new Map;relayShapeProxies=new Map;promotionState="owned";constructor(e,t){super(e,{ownerKey:t})}async forwardWhisper(e,t){if(!this.canAddressSiblings())return;const s=this.ownerRelaySet();s.size!==0&&await Promise.all([...s].map(r=>this.postRelayMessage(p(this.roleId.ownerKey,r),{frame:t,topic:e,type:"relay_frame"})))}async onFlush(e,t){await Promise.all([this.multicastShapePokes(e,t),this.proxyShapePokes(e,t)])}seedRelayShape(){return Promise.resolve(void 0)}announce(){return Promise.resolve()}announceDrain(){return Promise.resolve()}relayCount(){const e=this.host.getWebSockets().length,t=y(this.host.env(),"LUNORA_RELAY_THRESHOLD",w.tUp),s=y(this.host.env(),"LUNORA_RELAY_COLLAPSE_THRESHOLD",w.tDown);if(this.promotionState=L(this.promotionState,e,O(t,s)),this.promotionState==="owned")return 0;const r=y(this.host.env(),"LUNORA_MAX_RELAYS",x),a=y(this.host.env(),"LUNORA_RELAY_FAN",F);return Math.min(r,Math.max(1,a))}isShapeRelayUniform(e,t){const s=f(e,t),r=this.shapeUniformCache.get(s);if(r!==void 0)return r;const a=this.probeShapeRelayUniform(e,t);return this.shapeUniformCache.set(s,a),a}onAttach(e){this.addRelayToSet(e)}onDetach(e){this.removeRelayFromSet(e)}async onWhisperFrame(e){await Promise.all([...this.ownerRelaySet()].filter(t=>t!==e.originRelay).map(t=>this.postRelayMessage(p(this.roleId.ownerKey,t),{frame:e.frame,topic:e.topic,type:"relay_frame"})))}onShapeSubscribe(e){return this.buildShapeSeedFrames(e)}onShapePoke(){return 0}async multicastShapePokes(e,t){if(this.relayShapeRegistry.size===0)return;const s=this.ownerRelaySet();if(s.size===0)return;const r=this.host.currentCdcEpoch(),a=[];for(const o of this.relayShapeRegistry.values()){let n;try{n=this.host.resolveShape(o.name,o.args,S)}catch{continue}if(n===void 0||n.global===!0||!e.has(n.table))continue;const h=o.cursor,l=this.host.buildShapeDiff(n,h,t);if(l.length===0)continue;o.cursor=t;const d={args:g(o.args),checkpoint:t,epoch:r,fromCursor:h,name:o.name,rowsPatch:b(l),type:"relay_shape_poke"};for(const c of s)a.push(this.postRelayMessage(p(this.roleId.ownerKey,c),d))}await Promise.all(a)}async proxyShapePokes(e,t){if(this.relayShapeProxies.size===0)return;const s=this.host.currentCdcEpoch(),r=[];for(const a of this.relayShapeProxies.values()){let o;try{o=this.host.resolveShape(a.name,a.args,a.identity)}catch{continue}if(o===void 0||o.global===!0||!e.has(o.table))continue;const n=a.cursor,h=this.host.buildShapeDiff(o,n,t);if(h.length===0)continue;a.cursor=t;const l={args:g(a.args),checkpoint:t,epoch:s,fromCursor:n,name:a.name,rowsPatch:b(h),targetConnectionId:a.connectionId,type:"relay_shape_poke"};r.push(this.postRelayMessage(p(this.roleId.ownerKey,a.relayIndex),l))}await Promise.all(r)}buildShapeSeedFrames(e){const t={identity:e.identity,userId:e.userId};let s;try{s=this.host.resolveShape(e.name,e.args,t)}catch(d){const{body:c}=k(d,{fallbackCode:"SHAPE_RESOLVE_FAILED",redactedMessage:"shape resolution failed"});return{error:{code:c.code,message:c.message}}}if(s===void 0||s.global===!0)return{error:{code:"SHAPE_NOT_FOUND",message:`shape not relayable: ${e.name}`}};e.relayIndex!==void 0&&this.addRelayToSet(e.relayIndex);const{baseCheckpoint:r,cursor:a,epoch:o,rowsPatch:n}=this.host.computeOpLogShapeSeed({args:e.args,name:e.name,sinceEpoch:e.sinceEpoch,sinceSeq:e.sinceSeq},s);let h=a;if(this.isShapeRelayUniform(e.name,e.args)){const d=f(e.name,e.args);let c=this.relayShapeRegistry.get(d);c===void 0&&(c={args:e.args,cursor:a,name:e.name},this.relayShapeRegistry.set(d,c)),h=c.cursor}else e.relayIndex!==void 0&&e.connectionId!==void 0&&this.relayShapeProxies.set(`${String(e.relayIndex)}:${e.connectionId}:${e.subId}`,{args:e.args,connectionId:e.connectionId,cursor:a,epoch:o,identity:t,name:e.name,relayIndex:e.relayIndex,subId:e.subId});const l=v([{rowsPatch:n,shapeId:e.subId}],{baseCheckpoint:r,checkpoint:a,epoch:o,lastMutationId:void 0,pokeId:this.host.nextPokeId()});return{cursor:h,epoch:o,frames:l}}ensureRelayTable(){this.host.sql().exec("CREATE TABLE IF NOT EXISTS __lunora_relays (idx INTEGER PRIMARY KEY)")}ownerRelaySet(){if(this.relaySetCache===void 0){this.ensureRelayTable();const e=this.host.sql().exec("SELECT idx FROM __lunora_relays").toArray();this.relaySetCache=new Set(e.map(t=>Number(t.idx)))}return this.relaySetCache}addRelayToSet(e){this.ensureRelayTable(),this.host.sql().exec("INSERT OR IGNORE INTO __lunora_relays (idx) VALUES (?)",e),this.ownerRelaySet().add(e)}removeRelayFromSet(e){this.ensureRelayTable(),this.host.sql().exec("DELETE FROM __lunora_relays WHERE idx = ?",e);const t=this.ownerRelaySet();t.delete(e);for(const[s,r]of this.relayShapeProxies)r.relayIndex===e&&this.relayShapeProxies.delete(s);t.size===0&&(this.relayShapeRegistry.clear(),this.shapeUniformCache.clear())}probeShapeRelayUniform(e,t){let s;try{s=this.host.resolveShape(e,t,S)}catch{return!1}if(s===void 0||s.global===!0||this.host.rlsMetadata().policies.some(h=>h.on==="read"&&h.table===s.table)||this.tableHasAnyMask(s.table))return!1;const r=u(s.effectiveWhere),a=u(s.columns);let o=!1;const n=h=>{const l={groups:[`grp_${h}`],roles:[h],sub:`__lunora_probe_${h}__`};return{identity:new Proxy(l,{get:(d,c)=>typeof c=="symbol"||c in d?Reflect.get(d,c):`${h}:${c}`,getOwnPropertyDescriptor:(d,c)=>(o=!0,Reflect.getOwnPropertyDescriptor(d,c)),has:(d,c)=>typeof c=="symbol"?Reflect.has(d,c):!0,ownKeys:d=>(o=!0,Reflect.ownKeys(d))}),userId:`__lunora_probe_${h}__`}};return[S,n("a"),n("b")].every(h=>{let l;try{l=this.host.resolveShape(e,t,h)}catch{return!1}return l!==void 0&&l.global!==!0&&l.table===s.table&&u(l.effectiveWhere)===r&&u(l.columns)===a})&&!o}tableHasAnyMask(e){return this.host.maskMetadata().columns.some(t=>t.table===e)}}class H extends P{relayAnnounced=!1;shapeRelayMemos=new WeakMap;constructor(e,t,s){super(e,{ownerKey:t,relayIndex:s})}async forwardWhisper(e,t){this.canAddressSiblings()&&await this.postRelayMessage(this.roleId.ownerKey,{frame:t,originRelay:this.roleId.relayIndex,topic:e,type:"relay_frame"})}onFlush(){return Promise.resolve()}async seedRelayShape(e,t,s,r){if(!this.canAddressSiblings())return{code:"RELAY_MISCONFIGURED",message:"relay cannot address its owner"};await this.announce();const a={args:g(s.args??{}),connectionId:this.host.readAttachment(e).connectionId,identity:r.identity,name:s.name,relayIndex:this.roleId.relayIndex,sinceEpoch:s.sinceEpoch,sinceSeq:s.sinceSeq,subId:t,type:"relay_shape_subscribe",userId:r.userId},o=await this.requestRelayMessage(this.roleId.ownerKey,a);if(o===void 0)return{code:"RELAY_SEED_FAILED",message:"owner did not answer the shape seed"};let n;try{n=await o.json()}catch{return{code:"RELAY_SEED_FAILED",message:"malformed shape seed from owner"}}if(n.error!==void 0)return n.error;if(n.frames===void 0)return{code:"RELAY_SEED_FAILED",message:"owner returned no shape frames"};await T(e);for(const h of n.frames)I(e,h);return this.recordRelayShapeMemo(e,t,n.cursor??0,n.epoch),"ok"}async announce(){this.relayAnnounced||!this.canAddressSiblings()||(this.relayAnnounced=!0,(await this.requestRelayMessage(this.roleId.ownerKey,{relayIndex:this.roleId.relayIndex,type:"relay_attach"}))?.ok||(this.relayAnnounced=!1))}async announceDrain(e){this.canAddressSiblings()&&(this.host.getWebSockets().some(t=>t!==e)||(this.relayAnnounced=!1,await this.postRelayMessage(this.roleId.ownerKey,{relayIndex:this.roleId.relayIndex,type:"relay_detach"})))}relayCount(){return 0}isShapeRelayUniform(){return!1}onAttach(){}onDetach(){}onWhisperFrame(){return Promise.resolve()}onShapeSubscribe(){return{error:{code:"RELAY_CANNOT_SEED",message:"a relay has no op-log to seed from"}}}onShapePoke(e){return this.deliverShapePoke(e)}recordRelayShapeMemo(e,t,s,r){let a=this.shapeRelayMemos.get(e);a===void 0&&(a=new Map,this.shapeRelayMemos.set(e,a)),a.set(t,{cursor:s,epoch:r})}deliverShapePoke(e){const t=f(e.name,e.args);let s=0;for(const r of this.host.getWebSockets()){const a=this.host.readAttachment(r),{shapes:o}=a,n=this.shapeRelayMemos.get(r);if(!(o===void 0||n===void 0)&&!(e.targetConnectionId!==void 0&&a.connectionId!==e.targetConnectionId))for(const[h,l]of Object.entries(o)){const d=n.get(h);if(d?.cursor!==e.fromCursor||d.epoch!==e.epoch||f(l.name,l.args)!==t)continue;const c=v([{rowsPatch:e.rowsPatch,shapeId:h}],{baseCheckpoint:void 0,checkpoint:e.checkpoint,epoch:e.epoch,lastMutationId:void 0,pokeId:this.host.nextPokeId()},{preEncoded:!0});for(const M of c)I(r,M);n.set(h,{cursor:e.checkpoint,epoch:e.epoch}),s+=1}}return s}}const J=i=>{const e=i.doName();if(e===void 0)return;const t=C(e);return t===void 0?new q(i,e):new H(i,t.ownerKey,t.relayIndex)};export{x as DEFAULT_MAX_RELAYS,q as OwnerRelay,H as RelayMember,J as createRelayLink};
@@ -0,0 +1 @@
1
+ import{LunoraError as i}from"@lunora/errors";import{t as e}from"./estimate-bytes-DwQON1Ky.mjs";const r={maxReadRows:1e5,maxWrittenBytes:32*1024*1024,maxWrittenRows:5e4};class w{readRows=0;writtenRows=0;writtenBytes=0;limits;constructor(t={}){this.limits={...r,...t}}recordRead(t){if(this.readRows+=t,this.readRows>this.limits.maxReadRows)throw new i("TRANSACTION_LIMIT_EXCEEDED",`this transaction read ${String(this.readRows)} documents, over the ${String(this.limits.maxReadRows)}-document limit`)}recordWrite(t){this.writtenRows+=1;const s=e(t);if(s===void 0)throw new i("BAD_REQUEST","this document is not JSON-serializable (cyclic or non-JSON value); it cannot be written");if(this.writtenBytes+=s,this.writtenRows>this.limits.maxWrittenRows)throw new i("TRANSACTION_LIMIT_EXCEEDED",`this transaction wrote ${String(this.writtenRows)} documents, over the ${String(this.limits.maxWrittenRows)}-document limit`);if(this.writtenBytes>this.limits.maxWrittenBytes)throw new i("TRANSACTION_LIMIT_EXCEEDED",`this transaction wrote ${String(this.writtenBytes)} bytes, over the ${String(this.limits.maxWrittenBytes)}-byte limit`)}headroom(){return{readRows:this.readRows,remainingReadRows:Math.max(0,this.limits.maxReadRows-this.readRows),remainingWrittenBytes:Math.max(0,this.limits.maxWrittenBytes-this.writtenBytes),remainingWrittenRows:Math.max(0,this.limits.maxWrittenRows-this.writtenRows),writtenBytes:this.writtenBytes,writtenRows:this.writtenRows}}}export{r as DEFAULT_TRANSACTION_LIMITS,w as TransactionHeadroomTracker};
@@ -0,0 +1 @@
1
+ import{LunoraError as b}from"@lunora/errors";import{n as St,A as Pe,T as Se,y as Tt,c as _t}from"./FTS_COUNT_COLUMN-D1gY3wwZ-CZHdaRrd.mjs";import{sql as n}from"drizzle-orm";import{aggregateSqlFunction as Te,normalizeCountArgument as Rt,throwingScheduler as At}from"./AGGREGATE_SQL_FUNCTION-QYaiuty4.mjs";import{encodeAggregateKey as Me,readAggregateValue as Ce,aggregateTableName as ke}from"./aggregateTableName-G-eXyjcz.mjs";import{mergeWhere as Q,CountRlsUnsupportedError as Le,selectIndexForGroupBy as xt,selectIndexForCount as vt,selectIndexForAggregate as It}from"./CountRlsUnsupportedError-B2WKJD9v.mjs";import{backfillSearchIndexesForTable as Mt}from"./backfillAggregateIndexes-BHiewuB-.mjs";import{backfillAggregateIndexes as mr,backfillRankIndexes as $r,backfillSearchIndexes as gr}from"./backfillAggregateIndexes-BHiewuB-.mjs";import{appendCdcChange as Ct}from"./CDC_LOG_TABLE-BnqlH2eZ.mjs";import{CDC_LOG_TABLE as yr,applyCdcChanges as Er,bumpCdcEpoch as Nr,minCdcSeq as Sr,readCdcChanges as Tr,readCdcCursor as _r,readCdcEpoch as Rr,trimCdcChanges as Ar}from"./CDC_LOG_TABLE-BnqlH2eZ.mjs";import{createCompanionSync as kt}from"./createCompanionSync-DWK0Vlg1.mjs";import{computeRankPage as Ze}from"./computeRankPage-IUSS-zIB.mjs";import{SCAN_DEP as B}from"./SCAN_DEP-D_yR9EeV.mjs";import{runDrizzle as F}from"./runDrizzle-GKR3y97k.mjs";import{DOC_COLUMN as P,quoteIdentifier as Lt,AGG_VALUE as _e,AGG_COUNT as De,AGG_KEY as Re,jsonPathSql as z,rowToDocument as de,tableColumns as pt,isFtsAvailable as Dt,tryRowToDocument as wt,geoTableName as Ot,qualifiedJsonPathSql as et}from"./AGG_COUNT-BWXe3gtQ.mjs";import{coveringGeohashes as Wt,boundingBoxGeohashes as Ft,pointInBoundingBox as qt,haversineMeters as Bt}from"./GEO_DEFAULT_PRECISION-okRCkZ6r.mjs";import{NotFoundError as Ut}from"./NotFoundError-BhF7FeFr.mjs";import{normalizeOrderKeys as Pt,buildSeekWhere as mt,decodeCursor as qe,applySelect as tt,encodeCursor as Be,softDeleteScope as le,buildSeekBeforeWhere as jt}from"./applySelect-B0CF8T7y.mjs";import{sortColumnName as nt,resolveRankPartition as Ht,encodePartitionKey as Gt,RANK_TIEBREAK as Kt,rankTableName as rt}from"./RANK_TIEBREAK-9NU5s_mi.mjs";import{indexKeysForRow as Qt,buildIndexRange as zt}from"./buildIndexRange-DFsdtPjD.mjs";import{assertFlatPredicate as Oe,resolveRelationPredicates as it}from"./DEFAULT_MAX_RELATION_KEYS-bq00btqV.mjs";import{runRowValidators as We,resolveWith as ot,applyOnDelete as Jt,fanOutScalarCounts as Yt}from"./applyOnDelete-uFRC5p1d.mjs";import{guardWriter as Vt}from"./RLS_UNWRAP_SYMBOL-CBYPlYBb.mjs";import{createSystemReader as Xt}from"./createSystemReader-DcDcrtM3.mjs";import{ConflictError as me}from"./ConflictError-C8GtJmjS.mjs";import{runTriggers as Zt}from"./hasTrigger-CbkOHExZ.mjs";import{compileWhereSql as ne}from"./compileWhereSql-BLcfs4QW.mjs";import{CLIENT_WATERMARK_TABLE as vr,advanceClientWatermark as Ir,migrateClientWatermark as Mr,readClientWatermark as Cr}from"./CLIENT_WATERMARK_TABLE-CXsSLU8D.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as Lr,deleteGlobalShapeSnapshot as Dr,deleteGlobalShapeSnapshotsForConnection as Or,migrateGlobalShapeSnapshot as Wr,readGlobalShapeSnapshot as Fr,writeGlobalShapeSnapshot as qr}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-DX-6-gBP.mjs";import{IDEMPOTENCY_TABLE as Ur,readIdempotent as Pr,trimIdempotent as jr,writeIdempotent as Hr}from"./IDEMPOTENCY_TABLE-DjkEMp6w.mjs";import{runShardMigrations as Kr}from"./runShardMigrations-CPxqCh3O.mjs";import{SEARCH_STATE_TABLE as zr}from"./SEARCH_STATE_TABLE-eLN8U5tz.mjs";import{selectShapeMemberIds as Yr,selectShapeRows as Vr}from"./selectShapeMemberIds-DvE7K6zG.mjs";import{serializeSqlValue as re}from"./serializeSqlValue-DnpyaLcw.mjs";const en=i=>{const o=new TextEncoder().encode(i);let t="";for(const l of o)t+=String.fromCodePoint(l);return btoa(t)},tn=i=>{const o=atob(i),t=Uint8Array.from(o,l=>l.codePointAt(0)??0);return new TextDecoder().decode(t)},nn=()=>new b("BAD_REQUEST","invalid cursor"),at=16,st=8,Z=1024,je=(i,o)=>o.query(i),rn=(i,o,t)=>{const l=St(i,t);if(l.length===0)return 0;let c=0;for(const[p,m]of o.entries()){const R=p===o.length-1;let S=0;for(const $ of l)(R?$.startsWith(m):$===m)&&(S+=1);if(S===0)return 0;c+=S}return c},on=(i,o)=>{if(!o)return{exact:!0,lower:i,upper:i};const t=[...i].at(-1)??"",l=(t.codePointAt(0)??0)+1;if(l>=55296&&l<=57343||l>1114111)return{exact:!0,lower:i,upper:i};const c=i.slice(0,i.length-t.length);return{exact:!1,lower:i,upper:c+String.fromCodePoint(l)}},an=(i,o,t)=>{const l={eq:(c,p)=>{if(!i.definition.filterFields?.includes(c))throw new b("INTERNAL",`field "${c}" is not a filter field of search index "${i.indexName}" on table "${o}"`);if(i.filters.length>=st)throw new b("BAD_REQUEST",`search index "${i.indexName}" on table "${o}": at most ${String(st)} .eq() filters are supported per search query`);return i.filters.push({field:c,value:p}),l},search:(c,p)=>{const m=i;if(c!==m.definition.field)throw new b("INTERNAL",`search index "${m.indexName}" on table "${o}" indexes "${m.definition.field}", not "${c}"`);const R=je(p,t).length;if(R>at)throw new b("BAD_REQUEST",`search index "${m.indexName}" on table "${o}": at most ${String(at)} search terms are supported (got ${String(R)})`);return m.field=c,m.query=p,m.hasQuery=!0,l}};return l},sn=i=>{if(i.length>Z)throw new b("BAD_REQUEST",`more than ${String(Z)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},ln=i=>Math.min(i.offset+i.numItems+1,Z),dn=i=>en(`search:${String(i)}`),cn=i=>{let o;try{o=tn(i)}catch{return}if(!o.startsWith("search:"))return;const t=Number(o.slice(7));return Number.isInteger(t)&&t>=0?t:void 0},un=i=>{if(typeof i.endCursor=="string")throw new b("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");const o=Math.max(0,Math.floor(i.numItems)),t=i.cursor?cn(i.cursor):0;if(t===void 0)throw nn();if(t+o>Z)throw new b("BAD_REQUEST",`search pagination reaches past the ${String(Z)}-document limit (offset ${String(t)} + ${String(o)} requested) — narrow the query or the filters instead`);return{numItems:o,offset:t}},fn=(i,o)=>{const t=o.offset+o.numItems,l=o.numItems>0&&i.length>t;return{continueCursor:l?dn(t):null,isDone:!l,page:i.slice(o.offset,t)}},hn=i=>{if(i===void 0)return Z+1;if(!Number.isFinite(i))return Z;const o=Math.max(0,Math.floor(i));if(o>Z)throw new b("BAD_REQUEST",`search returns at most ${String(Z)} documents (asked for ${String(o)}) — narrow the query or paginate instead`);return o},pn=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,wn=i=>{if(!pn.test(i))throw new b("INTERNAL",`invalid clientId ${JSON.stringify(i)}: a client-supplied row id must be a UUID`)},lt=50,$t=500,mn=128,se=(i,o,t)=>{const l=o??$t;if(i>l)throw new b("BATCH_LIMIT_EXCEEDED",`${t}: batch of ${String(i)} exceeds the limit of ${String(l)} (raise options.limit or chunk the call)`,{status:400})},$n=i=>{const o={eq:(t,l)=>(i.sqlConditions.push({comparator:"=",field:t,value:l}),o),gt:(t,l)=>(i.sqlConditions.push({comparator:">",field:t,value:l}),o),gte:(t,l)=>(i.sqlConditions.push({comparator:">=",field:t,value:l}),o),lt:(t,l)=>(i.sqlConditions.push({comparator:"<",field:t,value:l}),o),lte:(t,l)=>(i.sqlConditions.push({comparator:"<=",field:t,value:l}),o)};return o},gn=i=>Math.max(i,Z),bn=(i,o,t,l,c)=>{const p=je(t.query,Pe(t.definition.language));if(p.length===0)return[];const m=_t(o,t.indexName),R=`${m}__vocab`,S=p.length-1,$=p.map((C,L)=>{const j=on(C,L===S),U=j.exact?n`${n.identifier("term")} = ${j.lower}`:n`${n.identifier("term")} >= ${j.lower} AND ${n.identifier("term")} < ${j.upper}`;return n`SELECT ${n.identifier("doc")}, ${n.raw(String(L))} AS ${n.identifier("__term__")}, COUNT(*) AS ${n.identifier("__n__")} FROM ${n.identifier(R)} WHERE ${U} GROUP BY ${n.identifier("doc")}`}),y=p.map((C,L)=>n`SUM(CASE WHEN u.${n.identifier("__term__")} = ${n.raw(String(L))} THEN u.${n.identifier("__n__")} ELSE 0 END)`),E=n`SELECT f.${n.identifier(Se)} AS ${n.identifier(Se)}, ${n.join(y,n` + `)} AS ${n.identifier("__score__")} FROM (${n.join($,n` UNION ALL `)}) u JOIN ${n.identifier(m)} f ON f.rowid = u.${n.identifier("doc")} GROUP BY f.${n.identifier(Se)} HAVING ${n.join(y.map(C=>n`${C} > 0`),n` AND `)}`,_=[];for(const C of t.filters)_.push(n`${z(C.field)} = ${re(C.value)}`);c&&_.push(c);let M=n`SELECT m.id, m._creationTime, m.${n.identifier(P)}, s.${n.identifier("__score__")} AS ${n.identifier("__score__")} FROM (${E}) s JOIN ${n.identifier(o)} m ON m.id = s.${n.identifier(Se)}`;_.length>0&&(M=n`${M} WHERE ${n.join(_,n` AND `)}`),M=n`${M} ORDER BY s.${n.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${n.raw(String(l))}`;const O=[];for(const C of F(i,M)){const L=wt(C);if(L){const j=C.__score__;O.push({document:L,score:typeof j=="number"?j:Number(j??0)})}}return O},yn=(i,o,t,l,c)=>{const p=Pe(t.definition.language),m=je(t.query,p);if(m.length===0)return[];const R=[];for(const E of t.filters)R.push(n`${z(E.field)} = ${re(E.value)}`);c&&R.push(c);let S=n`SELECT id, _creationTime, ${n.identifier(P)} FROM ${n.identifier(o)}`;R.length>0&&(S=n`${S} WHERE ${n.join(R,n` AND `)}`),S=n`${S} ORDER BY _creationTime DESC, id ASC LIMIT ${n.raw(String(gn(l)))}`;const $=F(i,S).toArray(),y=[];for(const E of $){const _=wt(E);if(!_)continue;const M=rn(Tt(_,t.definition),m,p);M>0&&y.push({creationTime:typeof _._creationTime=="number"?_._creationTime:0,doc:_,id:typeof _._id=="string"?_._id:"",score:M})}return y.sort((E,_)=>_.score-E.score||_.creationTime-E.creationTime||E.id.localeCompare(_.id)),y.slice(0,l).map(E=>({document:E.doc,score:E.score}))},Fe=(i,o,t,l)=>{if(!Number.isFinite(i.lat)||i.lat<-90||i.lat>90||!Number.isFinite(i.lng)||i.lng<-180||i.lng>180)throw new b("BAD_REQUEST",`geo index "${l}" on table "${t}": ${o} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},En=(i,o)=>{const t=i,l={near:(c,p)=>{if(t.within)throw new b("INTERNAL",`geo index "${t.indexName}" on table "${o}": call .near() or .within(), not both`);if(Fe(c,".near() point",o,t.indexName),!Number.isFinite(p)||p<=0)throw new b("BAD_REQUEST",`geo index "${t.indexName}" on table "${o}": .near() radiusMeters must be a finite number > 0, got ${String(p)}`);return t.near={point:{lat:c.lat,lng:c.lng},radiusMeters:p},l},within:c=>{if(t.near)throw new b("INTERNAL",`geo index "${t.indexName}" on table "${o}": call .near() or .within(), not both`);if(Fe(c.sw,".within() sw corner",o,t.indexName),Fe(c.ne,".within() ne corner",o,t.indexName),c.sw.lat>c.ne.lat)throw new b("BAD_REQUEST",`geo index "${t.indexName}" on table "${o}": .within() corners are transposed (sw.lat > ne.lat)`);if(c.sw.lng>c.ne.lng)throw new b("BAD_REQUEST",`geo index "${t.indexName}" on table "${o}": .within() box crosses the antimeridian (sw.lng > ne.lng), which is not supported — split it into two boxes at ±180 and union the results`);return t.within={ne:{lat:c.ne.lat,lng:c.ne.lng},sw:{lat:c.sw.lat,lng:c.sw.lng}},l}};return l},Nn=(i,o)=>{const t=i[o];if(t===null||typeof t!="object")return;const{lat:l,lng:c}=t;return typeof l=="number"&&typeof c=="number"?{lat:l,lng:c}:void 0},Sn=(i,o)=>{const t=Nn(i,o.definition.field);if(!t)return;const l=typeof i._creationTime=="number"?i._creationTime:0;if(o.near){const c=Bt(o.near.point,t);return c<=o.near.radiusMeters?{creationTime:l,distance:c}:void 0}return qt(t,o.within)?{creationTime:l,distance:0}:void 0},gt=(i,o,t,l)=>{if(!t.near&&!t.within)throw new b("INTERNAL",`geo index "${t.indexName}" on table "${o}": call .near(point, radius) or .within(box)`);const c=t.near?Wt(t.near.point,t.near.radiusMeters):Ft(t.within),p=Ot(o,t.indexName),m=c.map(E=>n`(g.${n.identifier("__geohash__")} >= ${E} AND g.${n.identifier("__geohash__")} < ${`${E}{`})`),R=[n`(${n.join(m,n` OR `)})`];l&&R.push(l);const S=n`SELECT m.id, m._creationTime, m.${n.identifier(P)} FROM ${n.identifier(p)} g JOIN ${n.identifier(o)} m ON m.id = g.${n.identifier("__id__")} WHERE ${n.join(R,n` AND `)}`,$=F(i,S).toArray(),y=[];for(const E of $){const _=de(E),M=_?Sn(_,t):void 0;_&&M&&y.push({creationTime:M.creationTime,distance:M.distance,doc:_})}return y.sort((E,_)=>E.distance-_.distance||_.creationTime-E.creationTime),y},Tn=(i,o,t,l,c,p=()=>{})=>{const m=gt(i,o,t,c).map(R=>R.doc);return p(m.length),typeof l=="number"?m.slice(0,Math.max(0,Math.floor(l))):m},_n=(i,o,t,l,c,p=()=>{})=>{const m=t.within!==void 0,R=gt(i,o,t,c).map(S=>({distanceMeters:m?null:S.distance,document:S.doc}));return p(R.length),R},Rn=(i,o,t,l,c,p=()=>{})=>{const{geo:m}=t;if(!m)throw new b("INTERNAL","runGeoTerminal called without a staged geo query");const R=t.inMemoryFilters.length>0,S=Tn(i,o,m,R?void 0:c,l,p);if(!R)return S;const $=[];for(const y of S)if(t.inMemoryFilters.every(E=>E(y))&&($.push(y),typeof c=="number"&&$.length>=c))break;return $},An=(i,o,t,l,c,p=()=>{})=>{const{geo:m}=t;if(!m)throw new b("INTERNAL","runGeoTerminalScored called without a staged geo query");const R=t.inMemoryFilters.length>0,S=_n(i,o,m,R?void 0:c,l,p);if(!R)return S;const $=[];for(const y of S)t.inMemoryFilters.every(E=>E(y.document))&&$.push(y);return $},xn=(i,o,t,l,c,p,m=()=>{})=>{const R=[];for(const E of t.sqlConditions)R.push(n`${z(E.field)} ${n.raw(E.comparator)} ${re(E.value)}`);l&&R.push(l);let S=n`SELECT id, _creationTime, ${n.identifier(P)} FROM ${n.identifier(o)}`;R.length>0&&(S=n`${S} WHERE ${n.join(R,n` AND `)}`),S=n`${S} ORDER BY ${c}`,typeof p=="number"&&t.inMemoryFilters.length===0&&(S=n`${S} LIMIT ${n.raw(String(Math.max(0,Math.floor(p))))}`);const $=F(i,S).toArray();m($.length);const y=[];for(const E of $){const _=de(E);if(_&&t.inMemoryFilters.every(M=>M(_))&&(y.push(_),typeof p=="number"&&y.length>=p))break}return y},oe={fieldRef:z,serialize:re},vn=i=>{let o=0;const t=[],l={fieldRef:z,relationExists:c=>{const{childWhere:p,negated:m,parentTable:R,relation:S}=c,$=`__rel_${String(o)}`,y=t.at(-1)??R;o+=1,i(S.table,B);const E=S.kind==="one"?S.field:S.references,_=S.kind==="one"?S.references:S.field,M=n`${et($,_)} = ${et(y,E)}`;t.push($);const O=ne(p,l);t.pop();const C=O?n`${M} AND ${O}`:M,L=n`EXISTS (SELECT 1 FROM ${n.identifier(S.table)} AS ${n.identifier($)} WHERE ${C})`;return m?n`NOT ${L}`:L},serialize:re};return l},bt=i=>{const o=i.map(t=>n`${z(t.field)} ${n.raw(t.direction==="desc"?"DESC":"ASC")}`);return i.some(t=>t.field==="_id"||t.field==="id")||o.push(n`${z("id")} ASC`),n.join(o,n`, `)},In={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},Mn=i=>{const o=i.order;return i.indexFields.length>0?i.indexFields.map(t=>({direction:o,field:t})):[{direction:o,field:"_creationTime"}]},Cn=(i,o,t,l)=>{const c=i.sqlConditions.map(p=>({[p.field]:{[In[p.comparator]??"eq"]:p.value}}));if(t&&c.push(mt(o,qe(t))),l&&c.push(jt(o,qe(l))),c.length!==0)return c.length===1?c[0]:{AND:c}},kn=(i,o,t)=>{const l=[];for(const c of i){const p=de(c);if(p&&o.every(m=>m(p))&&(l.push(p),t!==void 0&&l.length>t))break}return l},Ln=(i,o,t,l,c,p=()=>{})=>{const m=Math.max(0,Math.floor(l.numItems)),R=Mn(t),S=typeof l.endCursor=="string",$=ne(Cn(t,R,l.cursor,l.endCursor),oe),y=c&&$?n`${$} AND ${c}`:c??$;let E=n`SELECT id, _creationTime, ${n.identifier(P)} FROM ${n.identifier(o)}`;y&&(E=n`${E} WHERE ${y}`),E=n`${E} ORDER BY ${bt(R)}`;const _=t.inMemoryFilters.length>0;!_&&!S&&(E=n`${E} LIMIT ${n.raw(String(m+1))}`);const M=F(i,E).toArray();p(M.length);const O=kn(M,t.inMemoryFilters,_||S?void 0:m);if(S){const U=O.length>=2?O[Math.floor(O.length/2)-1]:void 0;return{continueCursor:l.endCursor??null,isDone:!0,page:O,splitCursor:U?Be(U,R):null}}const C=O.length>m,L=C?O.slice(0,m):O,j=L.at(-1);return{continueCursor:C&&j?Be(j,R):null,isDone:!C,page:L}};class Dn extends b{constructor(o="unique() found more than one matching document"){super("NOT_UNIQUE",o,{name:"NotUniqueError"})}}const On=/\s/u,Wn=String.fromCodePoint(0),dt=(i,o,t)=>{if(!i.tables[o])throw new b("INTERNAL",`unknown table: ${o}`);return typeof t!="string"||t.length===0||On.test(t)||t.includes(Wn)?null:t},Fn=(i,o,t,l=()=>{},c=()=>{},p=()=>{})=>{const m=o.tables[t];if(!m)throw new b("INTERNAL",`unknown table: ${t}`);const R=le(m.softDeleteMode,void 0),S=R?ne(R,oe):void 0,$={indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[]};let y=0;const E=N=>{const{search:I}=$;if(!I)throw new b("INTERNAL","runSearchFetch called without a staged search");Mt(i,t,m);const v=$.inMemoryFilters.length>0,k=hn(v?void 0:N),H=Dt(i)?bn(i,t,I,k,S):yn(i,t,I,k,S);if(!v)return N===void 0&&sn(H),H;const X=[];y=H.length;for(const ce of H)if($.inMemoryFilters.every(ue=>ue(ce.document))&&(X.push(ce),typeof N=="number"&&X.length>=N))break;return X},_=N=>E(N).map(I=>I.document),M=N=>{const I=un(N);return fn(_(ln(I)),I)},O=()=>{const N=$.indexFields.length>0?$.indexFields:["_creationTime"],I=$.order==="desc"?"DESC":"ASC";return n.join(N.map(v=>n`${z(v)} ${n.raw(I)}`),n`, `)},C=()=>{if($.search||$.geo||$.indexName===void 0){c(void 0);return}c(zt(t,$.indexName,$.indexFields,$.sqlConditions,re))},L=N=>{C();let I=0;const v=(()=>{if($.search){const k=_(N);return I=y,k}return $.geo?Rn(i,t,$,S,N,k=>{I=k}):xn(i,t,$,S,O(),N,k=>{I=k})})();return p(Math.max(I,v.length)),v},j=()=>{if(!$.search&&!$.geo)throw new b("INTERNAL",`ctx.db.query("${t}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);C();let N=0;const I=(()=>{if($.search){const v=E(void 0);return N=y,v}return An(i,t,$,S,void 0,v=>{N=v})})();return p(Math.max(N,I.length)),I},U={async*[Symbol.asyncIterator](){const N=[...$.inMemoryFilters];let I;$.inMemoryFilters=[];try{for(;;){const v=await U.paginate({cursor:I??null,numItems:mn});for(const k of v.page)N.every(H=>H(k))&&(yield k);if(v.isDone||v.continueCursor===null)return;I=v.continueCursor}}finally{$.inMemoryFilters=N}},async collect(){return L(void 0)},async collectWithScores(){return j()},filter(N){return $.inMemoryFilters.push(N),U},async first(){return L($.inMemoryFilters.length>0?void 0:1)[0]??null},order(N){return $.order=N==="desc"?"desc":"asc",U},async paginate(N){let I=0;if(C(),$.search){const k=M(N);return p(k.page.length),k}if($.geo)throw new b("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const v=Ln(i,t,$,N,S,k=>{I=k});return p(Math.max(I,v.page.length)),v},async take(N){return L(N)},async unique(){const N=L($.inMemoryFilters.length>0?void 0:2);if(N.length>1)throw new Dn(`unique() on table "${t}" matched ${String(N.length)} documents; expected at most one`);return N[0]??null},withGeoIndex(N,I){const v=(m.geoIndexes??[]).find(H=>H.name===N);if(!v)throw new b("INTERNAL",`unknown geo index "${N}" on table "${t}"`);l(t,N,"geo");const k={definition:v,indexName:N};if($.geo=k,I(En(k,t)),!k.near&&!k.within)throw new b("INTERNAL",`geo index "${N}" on table "${t}" requires a .near(point, radius) or .within(box) call`);return U},withIndex(N,I){const v=m.indexes.find(k=>k.name===N);if(!v)throw new b("INTERNAL",`unknown index "${N}" on table "${t}"`);return l(t,N,"index"),$.indexName=N,$.indexFields=v.fields,I&&I($n($)),U},withSearchIndex(N,I){const v=(m.searchIndexes??[]).find(H=>H.name===N);if(!v)throw new b("INTERNAL",`unknown search index "${N}" on table "${t}"`);l(t,N,"search");const k={definition:v,field:v.field,filters:[],hasQuery:!1,indexName:N,query:""};if($.search=k,I(an(k,t,Pe(v.language))),!k.hasQuery)throw new b("INTERNAL",`search index "${N}" on table "${t}" requires a .search(field, query) call`);return U}};return U},ct=(i,o,t)=>{const l={...o};for(const[c,p]of pt(i)){if(p.serverDefault){l[c]=p.serverDefault({auth:t});continue}l[c]===void 0&&(p.defaultFn?l[c]=p.defaultFn():"defaultValue"in p&&(l[c]=p.defaultValue))}return l},ut=(i,o,t,l)=>{const c=t;for(const[p,m]of pt(i)){if(m.serverDefault){p in o&&(c[p]=m.serverDefault({auth:l}));continue}m.onUpdateFn&&!(p in o)&&(c[p]=m.onUpdateFn())}},ft=(i,o)=>{for(const t of Object.keys(o))if(o[t]===void 0)throw new b("INTERNAL",`Cannot ${i} field '${t}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},qn=/unique constraint failed/i,Bn=i=>i instanceof Error&&qn.test(i.message),Ue=(i,o,t)=>{try{F(i,t)}catch(l){throw Bn(l)?new me(`unique constraint violation on "${o}"`,"unique"):l}},Ae=(i,o,t)=>{if(Ue(i,o,t),F(i,n`SELECT changes() AS changed`).one().changed===0)throw new me(`optimistic concurrency conflict on "${o}" — the row changed during this mutation; refetch and retry`,"occ")},ht=(i,o,t,l,c,p,m)=>{const R=[];for(let E=0;E<t.length+1;E+=1){const _=[];for(let L=0;L<E;L+=1)_.push(n`${n.identifier(t[L])} IS ${p[L]}`);const M=t[E],O=l[E];if(M!==void 0&&O!==void 0){const L=O.direction==="desc"?">":"<";_.push(n`${n.identifier(M)} ${n.raw(L)} ${p[E]}`)}else _.push(n`${n.identifier(Kt)} < ${m}`);const[C]=_;R.push(_.length===1&&C!==void 0?C:n`(${n.join(_,n` AND `)})`)}const S=n.join(R,n` OR `),$=F(i,n`SELECT COUNT(*) AS c FROM ${n.identifier(o)} WHERE ${n.identifier("__partition__")} = ${c} AND (${S})`).one(),y=F(i,n`SELECT COUNT(*) AS c FROM ${n.identifier(o)} WHERE ${n.identifier("__partition__")} = ${c}`).one();return{before:$.c,total:y.c}},hr=i=>{const{sql:o}=i,{schema:t}=i,l=i.broadcast??(()=>{}),c=(e,...r)=>{const a=t.tables[e]?.indexes;if(!a||a.length===0)return;const h=[];for(const f of r)f&&h.push(...Qt(a,f,re));return h.length>0?h:void 0},{headroom:p}=i;let m=!1;const R=async e=>{const r=m;m=!0;try{return await e()}finally{m=r}},S=i.onRead??(()=>{}),$=i.onReadRange??(e=>{S(e.table,B)}),y=(e,r)=>{r!==void 0&&r!==B&&!m&&p?.recordRead(1),S(e,r)},E=i.onIndexUse??(()=>{}),_=i.onWrite??(()=>{}),M=async e=>{m||p?.recordWrite(e.doc),await _(e)},{cache:O}=i,C=i.clock??(()=>Date.now()),L=i.idGenerator??(()=>crypto.randomUUID()),j=i.scheduler??At,{globalDb:U}=i,N=i.auth??{identity:null,userId:null},I=i.cdc??!1,v=j,k=Xt({scheduler:typeof v.list=="function"&&typeof v.get=="function"?v:void 0,storage:i.storage}),H=(e,r,a,h)=>{I&&Ct(o,C(),e,r,a,h)},X=e=>t.tables[e]?.shardMode?.kind==="global",ce=(e,r)=>{if(X(e)){if(!U)throw new b("INTERNAL",`cross-backend ${r} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return U}return q},ue=e=>ce(e,"cascade"),J=(e,r)=>{if(X(e)){if(!U)throw new b("INTERNAL",`${r} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return U}},fe=()=>U,xe=(e,r)=>ce(e,"relation load").findMany(e,r),He=(e,r)=>(X(e)&&y(e,B),xe(e,r)),yt=e=>!X(e.table),Ge=i.relationExistsPushDown??"auto",Ke=Ge!=="never",{maxRelationKeys:Qe}=i,$e=(e,r,a)=>it(e,{fetcher:He,maxRelationKeys:Qe,relationBaseWhere:a,schema:t,tableName:r}),ze=async(e,r,a,h)=>{const f=J(e,"relation grouped count");if(f)return y(e,B),Yt((x,K)=>f.count(x,K),e,r,a,h);const d=t.tables[e];if(!d)throw new b("INTERNAL",`unknown table: ${e}`);y(e,B);const s=le(d.softDeleteMode,void 0),u={[r]:{in:a}},w=Q(Q(u,h),s),T=await $e(w,e,void 0),g=ne(T,oe),A=z(r);let W=n`SELECT ${A} AS __fk__, COUNT(*) AS count FROM ${n.identifier(e)}`;g&&(W=n`${W} WHERE ${g}`),W=n`${W} GROUP BY ${A}`;const D=F(o,W).toArray();return new Map(D.map(x=>[x.__fk__,x.count]))};let ge=0;const Je=new Set;for(const[e,r]of Object.entries(t.tables))for(const a of Object.values(r.triggerMap??{}))Je.add(`${e} ${a.timing} ${a.op}`);const ee=(e,r,a)=>Je.has(`${e} ${r} ${a}`),te=async(e,r,a)=>{if(ge+=1,ge>lt)throw ge-=1,new me(`trigger recursion exceeded ${String(lt)} levels on "${a.table}" — check for a self-triggering write`,"trigger");try{await Zt({ctx:Nt,event:a,op:r,schema:t,tableName:a.table,timing:e})}finally{ge-=1}},{ensureBackfilledForTable:he,ensureBackfilledIndex:ve,ensureRankBackfilled:Ie,ensureRankBackfilledForTable:pe,syncAggregates:be,syncCompanionsForInsert:Ye,syncGeo:ye,syncRanks:we,syncSearch:Ee}=kt({broadcast:l,indexKeysFor:(e,r)=>c(e,r),invalidateCache:(e,r,a)=>O?.invalidate(e,r,c(e,a)),recordCdc:H,schema:t,sql:o}),Ve=(e,r,a)=>{const{shardMode:h}=r;if(h?.kind==="shardBy"&&!(h.field!==void 0&&(a.partitionBy??[]).includes(h.field)))throw Object.assign(new Error(`rank index "${a.name}" on "${e}" partitions across shards (shard key "${h.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})},ie=(e,r)=>{const a=Object.entries(t.tables).filter(([,T])=>T.shardMode?.kind!=="global").map(([T])=>T).filter(T=>r===void 0||T===r);if(a.length===0)return;const h=a.map(T=>n`SELECT ${n.raw(`'${T.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${n.identifier(P)} FROM ${n.identifier(T)} WHERE id = ${e}`),f=n`${n.join(h,n` UNION ALL `)} LIMIT 1`,[d]=F(o,f).toArray();if(!d)return;const s=d.__t__,u=de(d);if(typeof s!="string"||!u)return;const w=d[P];return{docJson:typeof w=="string"?w:JSON.stringify(w??{}),row:u,tableName:s}},Et=(e,r)=>{const a=[...new Set(e)],h=new Map;if(a.length===0)return h;const f=Object.entries(t.tables).filter(([,s])=>s.shardMode?.kind!=="global").map(([s])=>s).filter(s=>r===void 0||s===r);if(f.length===0)return h;const d=Math.max(1,Math.floor(900/f.length));for(let s=0;s<a.length;s+=d){const u=a.slice(s,s+d),w=n.join(u.map(A=>n`${A}`),n`, `),T=f.map(A=>n`SELECT ${n.raw(`'${A.replaceAll("'","''")}'`)} AS __t__, id FROM ${n.identifier(A)} WHERE id IN (${w})`),g=n.join(T,n` UNION ALL `);for(const A of F(o,g)){const{id:W,__t__:D}=A;typeof D=="string"&&typeof W=="string"&&h.set(W,D)}}return h},Xe={assertRankPartitionLocal:Ve,ensureRankBackfilled:Ie,onRead:y,rowToDocument:de,schema:t,sql:o},q={system:k,async aggregate(e,r){const a=J(e,"aggregate");if(a)return y(e,B),a.aggregate(e,r);const h=t.tables[e];if(!h)throw new b("INTERNAL",`unknown table: ${e}`);if(Te(r.op),r.op==="count")return q.count(e,{baseWhere:r.baseWhere,relationBaseWhere:r.relationBaseWhere,restrictsCounts:r.restrictsCounts,where:r.where});if(!r.field)throw new b("INTERNAL",`aggregate(${e}, { op: "${r.op}" }): "field" is required for non-count reducers`);y(e,B);const f=le(h.softDeleteMode,void 0),d=Q(Q(r.baseWhere,r.where),f),s=await $e(d,e,r.relationBaseWhere),u=s!==d;if(h.aggregateIndexes&&!r.baseWhere&&!u&&!f){const D=It(h.aggregateIndexes,r.op,r.field,r.where);if(D){ve(e,D.index);const x=Me(D.index.by??[],D.key),K=ke(e,D.index.name),Y=F(o,n`SELECT ${_e} AS value, ${De} AS count FROM ${n.identifier(K)} WHERE ${Re} = ${x}`).toArray()[0];return Ce(r.op,Y)}}const w=ne(s,oe),T=Te(r.op),g=z(r.field);let A=n`SELECT ${n.raw(T)}(${g}) AS value FROM ${n.identifier(e)}`;return w&&(A=n`${A} WHERE ${w}`),F(o,A).toArray()[0]?.value??null},asId(e,r){const a=dt(t,e,r);if(a===null)throw new b("BAD_REQUEST",`asId("${e}", …): "${r}" is not a valid id for table "${e}"`,{status:400});return a},async count(e,r){const a=J(e,"count");if(a)return y(e,B),a.count(e,r);const h=t.tables[e];if(!h)throw new b("INTERNAL",`unknown table: ${e}`);const f=Rt(r);if(f.restrictsCounts)throw new Le(e);y(e,B);const d=le(h.softDeleteMode,void 0),s=Q(Q(f.baseWhere,f.where),d),u=await $e(s,e,f.relationBaseWhere),w=u!==s;if(h.aggregateIndexes&&!f.baseWhere&&!w&&!d){const A=vt(h.aggregateIndexes,f.where);if(A){ve(e,A.index);const W=Me(A.index.by??[],A.key),D=ke(e,A.index.name),x=F(o,n`SELECT ${_e} AS value FROM ${n.identifier(D)} WHERE ${Re} = ${W}`).toArray();return x[0]===void 0?0:x[0].value??0}}const T=ne(u,oe);let g=n`SELECT COUNT(*) AS count FROM ${n.identifier(e)}`;return T&&(g=n`${g} WHERE ${T}`),F(o,g).one().count},async delete(e,r,a){const h=ie(e,r);if(!h){const g=r===void 0?fe():void 0;g&&await g.delete(e,void 0,a);return}const{docJson:f,row:d,tableName:s}=h,u=t.tables[s],w=a?.hard===!0,T=!w&&u?.softDeleteMode?u.softDeleteMode.field:void 0;if(!(T&&d[T]!==null&&d[T]!==void 0)){if(ee(s,"before","delete")&&await te("before","delete",{id:e,op:"delete",previous:d,table:s}),await Jt({deletedId:e,deletedReference:g=>d[g],findHolders:async(g,A,W)=>(await ue(g).findMany(g,{includeDeleted:w,where:{[A]:W}})).page,onCascade:(g,A)=>ue(g).delete(A,void 0,a),onRestrict:g=>{throw new me(g,"restrict")},onSetNull:(g,A,W)=>ue(g).patch(A,{[W]:null}),schema:t,tableName:s}),he(s),pe(s),T){const g={...d,[T]:C(),_id:e};Ae(o,s,n`UPDATE ${n.identifier(s)} SET ${n.identifier(P)} = ${JSON.stringify(g)} WHERE id = ${e} AND ${n.identifier(P)} = ${f}`),Ee(s,e,g,d),ye(s,e,void 0),be(s,d,g),we(s,e,d,void 0),O?.invalidate(s,e,c(s,d,g)),H(s,e,"update",g),l({indexKeys:c(s,d,g),key:e,op:"update",row:g,table:s}),ee(s,"after","delete")&&await te("after","delete",{id:e,op:"delete",previous:d,table:s}),await M({id:e,op:"delete",table:s});return}Ae(o,s,n`DELETE FROM ${n.identifier(s)} WHERE id = ${e} AND ${n.identifier(P)} = ${f}`),Ee(s,e,void 0),ye(s,e,void 0),be(s,d,void 0),we(s,e,d,void 0),O?.invalidate(s,e,c(s,d)),H(s,e,"delete"),l({indexKeys:c(s,d),key:e,op:"delete",table:s}),ee(s,"after","delete")&&await te("after","delete",{id:e,op:"delete",previous:d,table:s}),await M({id:e,op:"delete",table:s})}},async deleteAll(e,r){if(!t.tables[e])throw new b("INTERNAL",`unknown table: ${e}`);const a=Math.max(1,r?.chunkSize??$t),h=r?.hard===void 0?void 0:{hard:r.hard},f=X(e)?void 0:e;let d=0;return await R(async()=>{for(;;){const s=(await q.findMany(e,{limit:a})).page.map(u=>String(u._id));if(s.length===0)break;for(const u of s)await q.delete(u,f,h),d+=1;if(s.length<a)break}}),{deleted:d}},async deleteMany(e,r,a){se(e.length,r?.limit,"deleteMany");for(const h of e)await q.delete(h,a);return{deleted:e.length}},async deleteWhere(e,r,a){const h=J(e,"deleteWhere");let f;if(h)f=(await h.findMany(e,{where:r})).page.map(d=>String(d._id));else{if(!t.tables[e])throw new b("INTERNAL",`unknown table: ${e}`);f=(await q.findMany(e,{where:r})).page.map(d=>String(d._id))}if(se(f.length,a?.limit,"deleteWhere"),q.deleteMany===void 0)throw new b("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return q.deleteMany(f,a)},async findFirst(e,r={}){return(await q.findMany(e,{...r,limit:1})).page[0]??null},async findFirstOrThrow(e,r={}){const a=await q.findFirst(e,r);if(a===null)throw new Ut(`findFirstOrThrow: no "${e}" document matched`);return a},async findMany(e,r={}){const a=J(e,"findMany");if(a)return y(e,B),a.findMany(e,r);const h=t.tables[e];if(!h)throw new b("INTERNAL",`unknown table: ${e}`);const f=!r.where&&!r.baseWhere;f?y(e,B):y(e);const d=Pt(r.orderBy),s=r.cursor?mt(d,qe(r.cursor)):void 0;let u=Q(r.baseWhere,r.where);u=Q(u,le(h.softDeleteMode,r.includeDeleted)),u=await it(u,{canPushExists:Ke?yt:void 0,existsPushMode:Ge==="always"?"always":"auto",fetcher:He,maxRelationKeys:Qe,relationBaseWhere:r.relationBaseWhere,schema:t,tableName:e}),s&&(u=u?{AND:[u,s]}:s);const w=Ke?vn(y):oe,T=ne(u,w);let g=n`SELECT id, _creationTime, ${n.identifier(P)} FROM ${n.identifier(e)}`;T&&(g=n`${g} WHERE ${T}`),g=n`${g} ORDER BY ${bt(d)}`;const A=typeof r.limit=="number"?Math.max(0,Math.floor(r.limit)):void 0;A!==void 0&&(g=n`${g} LIMIT ${n.raw(String(A+1))}`);const W=F(o,g).toArray();f&&!m&&p?.recordRead(W.length);const D=[];for(const V of W){const G=de(V);G&&(D.push(G),!f&&typeof G._id=="string"&&y(e,G._id))}if(A===void 0)return r.with&&await ot({groupedCounter:ze,fetcher:xe,parents:D,relationBaseWhere:r.relationBaseWhere,schema:t,tableName:e,with:r.with}),{continueCursor:null,isDone:!0,page:tt(D,r.select,r.with)};const x=D.length>A,K=x?D.slice(0,A):D,Y=K.at(-1);return r.with&&await ot({fetcher:xe,groupedCounter:ze,parents:K,relationBaseWhere:r.relationBaseWhere,schema:t,tableName:e,with:r.with}),{continueCursor:x&&Y?Be(Y,d):null,isDone:!x,page:tt(K,r.select,r.with)}},async get(e,r){const a=ie(e,r);if(!a){const h=r===void 0?fe():void 0;return h?h.get(e):null}return y(a.tableName,e),a.row},async lookupById(e,r){const a=ie(e,r);return a?(y(a.tableName,e),{row:a.row,tableName:a.tableName}):null},async groupBy(e,r){const a=J(e,"groupBy");if(a)return y(e,B),a.groupBy(e,r);const h=t.tables[e];if(!h)throw new b("INTERNAL",`unknown table: ${e}`);y(e,B);const f=r.agg??{op:"count"};if(Te(f.op),f.op!=="count"&&!f.field)throw new b("INTERNAL",`groupBy(${e}, { agg: { op: "${f.op}" } }): "field" is required for non-count reducers`);const d=le(h.softDeleteMode,void 0),s=Q(Q(r.baseWhere,r.where),d),u=await $e(s,e,r.relationBaseWhere),w=u!==s;if(h.aggregateIndexes&&!r.baseWhere&&!w&&!d){const x=xt(h.aggregateIndexes,f.op,f.field,r.by,r.where);if(x){ve(e,x.index);const K=ke(e,x.index.name),Y=Object.keys(x.partial),V=[];if(Y.length===(x.index.by??[]).length&&Y.length>0){const ae=Me(x.index.by??[],x.partial),Ne=F(o,n`SELECT ${_e} AS value, ${De} AS count FROM ${n.identifier(K)} WHERE ${Re} = ${ae}`).toArray();return Ne.length>0&&V.push({key:{...x.partial},value:Ce(f.op,Ne[0])}),V}const G=F(o,n`SELECT ${Re} AS key, ${_e} AS value, ${De} AS count FROM ${n.identifier(K)}`).toArray();for(const ae of G){const Ne=JSON.parse(ae.key);V.push({key:Ne,value:Ce(f.op,ae)})}return V}}const T=ne(u,oe),g=r.by.map(x=>n`${z(x)} AS ${n.identifier(x)}`);if(f.op==="count")g.push(n`COUNT(*) AS value`);else{const{field:x}=f;if(x===void 0)throw new b("INTERNAL",`groupBy(${e}, { agg: { op: "${f.op}" } }): "field" is required for non-count reducers`);g.push(n`${n.raw(Te(f.op))}(${z(x)}) AS value`)}let A=n`SELECT ${n.join(g,n`, `)} FROM ${n.identifier(e)}`;T&&(A=n`${A} WHERE ${T}`),A=n`${A} GROUP BY ${n.join(r.by.map(x=>z(x)),n`, `)}`;const W=F(o,A).toArray(),D=[];for(const x of W){const K={};for(const V of r.by)K[V]=x[V]??null;const{value:Y}=x;D.push({key:K,value:Y==null?null:Number(Y)})}return D},async insert(e,r,a){const h=J(e,"insert");if(h){const T=await h.insert(e,r,a);return m||p?.recordWrite(r),l({key:T,op:"insert",row:{...r,_id:T},table:e}),T}const f=t.tables[e];if(!f)throw new b("INTERNAL",`unknown table: ${e}`);const d=ct(f,r,N);We(f,d);let s;a?.clientId!==void 0?(wn(a.clientId),s=a.clientId):a?.allowExplicitId&&typeof d._id=="string"?s=d._id:s=L();const u=a?.allowExplicitId&&typeof d._creationTime=="number"?d._creationTime:C(),w={...d,_creationTime:u,_id:s};return ee(e,"before","insert")&&await te("before","insert",{doc:{...w},id:s,op:"insert",table:e}),he(e),pe(e),Ue(o,e,n`INSERT INTO ${n.identifier(e)} (id, _creationTime, ${n.identifier(P)}) VALUES (${s}, ${u}, ${JSON.stringify(w)})`),Ye(e,s,w),ee(e,"after","insert")&&await te("after","insert",{doc:w,id:s,op:"insert",table:e}),await M({doc:w,id:s,op:"insert",table:e}),s},async insertManyUnsafe(e,r,a){if(se(r.length,a?.limit,"insertManyUnsafe"),r.length===0)return[];const h=J(e,"insert");if(h){const u=[];for(const w of r){const T=await h.insert(e,w,{allowExplicitId:a?.allowExplicitId});m||p?.recordWrite(w),l({key:T,op:"insert",row:{...w,_id:T},table:e}),u.push(T)}return u}const f=t.tables[e];if(!f)throw new b("INTERNAL",`unknown table: ${e}`);he(e),pe(e);const d=r.map(u=>{const w=ct(f,u,N),T=a?.allowExplicitId===!0&&typeof w._id=="string"?w._id:L(),g=a?.allowExplicitId===!0&&typeof w._creationTime=="number"?w._creationTime:C();return{creationTime:g,document:{...w,_creationTime:g,_id:T},id:T}});if(!m)for(const u of d)p?.recordWrite(u.document);const s=n.join(d.map(u=>n`(${u.id}, ${u.creationTime}, ${JSON.stringify(u.document)})`),n`, `);Ue(o,e,n`INSERT INTO ${n.identifier(e)} (id, _creationTime, ${n.identifier(P)}) VALUES ${s}`);for(const{document:u,id:w}of d)Ye(e,w,u),await _({doc:u,id:w,op:"insert",table:e});return d.map(u=>u.id)},async insertMany(e,r,a){se(r.length,a?.limit,"insertMany");const h=a?.skipDuplicates===!0,f=[];for(const d of r)try{f.push(await q.insert(e,d))}catch(s){if(h&&s instanceof me&&s.kind==="unique")f.push(null);else throw s}return f},normalizeId(e,r){return dt(t,e,r)},async patch(e,r,a){const h=ie(e,a);if(!h){const T=a===void 0?fe():void 0;if(T){await T.patch(e,r);return}throw new b("INTERNAL",`document not found: ${e}`)}const{docJson:f,row:d,tableName:s}=h,u=t.tables[s];if(!u)throw new b("INTERNAL",`unknown table: ${s}`);y(s,e),ft("patch",r);const w={...d,...r,_id:e};ut(u,r,w,N),We(u,w,!0),ee(s,"before","update")&&await te("before","update",{doc:{...w},id:e,op:"update",previous:d,table:s}),he(s),pe(s),Ae(o,s,n`UPDATE ${n.identifier(s)} SET ${n.identifier(P)} = ${JSON.stringify(w)} WHERE id = ${e} AND ${n.identifier(P)} = ${f}`),Ee(s,e,w,d),ye(s,e,w),be(s,d,w),we(s,e,d,w),O?.invalidate(s,e,c(s,d,w)),H(s,e,"update",w),l({indexKeys:c(s,d,w),key:e,op:"update",row:w,table:s}),ee(s,"after","update")&&await te("after","update",{doc:w,id:e,op:"update",previous:d,table:s}),await M({doc:w,id:e,op:"update",table:s})},async patchMany(e,r,a){se(e.length,r?.limit,"patchMany");for(const h of e)await q.patch(h.id,h.patch,a);return{patched:e.length}},async patchWhere(e,r,a){const h=J(e,"patchWhere");let f;if(h)f=(await h.findMany(e,{where:r.where})).page.map(d=>({id:String(d._id),patch:r.patch}));else{if(!t.tables[e])throw new b("INTERNAL",`unknown table: ${e}`);f=(await q.findMany(e,{where:r.where})).page.map(d=>({id:String(d._id),patch:r.patch}))}if(se(f.length,a?.limit,"patchWhere"),q.patchMany===void 0)throw new b("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await q.patchMany(f,a),{patched:f.length}},query(e){const r=J(e,"query");return r?(y(e,B),r.query(e)):Fn(o,t,e,E,a=>{a?$(a):y(e,B)},a=>{m||p?.recordRead(a)})},async rank(e,r,a){const h=J(e,"rank");if(h)return y(e,B),h.rank(e,r,a);E(e,r,"rank");const f=t.tables[e];if(!f)throw new b("INTERNAL",`unknown table: ${e}`);const d=f.rankIndexes?.find(G=>G.name===r);if(!d)throw new b("INTERNAL",`unknown rankIndex "${r}" on table "${e}"`);if(Ve(e,f,d),a.restrictsCounts)throw new Le(e);y(e,B),Ie(e,d);const s=typeof a.row=="string"?a.row:a.row._id;if(!s)return null;const u=rt(e,d.name),w=d.sortBy.map((G,ae)=>nt(ae)),T=w.map(G=>Lt(G)).join(", "),g=F(o,n`SELECT ${n.identifier("__partition__")}, ${n.raw(T)} FROM ${n.identifier(u)} WHERE ${n.identifier("__id__")} = ${s}`).toArray(),[A]=g;if(A===void 0)return null;let W=A.__partition__;const D=Q(a.baseWhere,a.where);Oe(D,t,e,"rank");const x=Ht(d,D);if(x){const G=Gt(d.partitionBy??[],x);if(G!==W)return null;W=G}const K=w.map(G=>A[G]),{before:Y,total:V}=ht(o,u,w,d.sortBy,W,K,s);return{position:Y+1,total:V}},async rankBefore(e,r,a){if(X(e))throw new b("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const h=t.tables[e];if(!h)throw new b("INTERNAL",`unknown table: ${e}`);const f=h.rankIndexes?.find(w=>w.name===r);if(!f)throw new b("INTERNAL",`unknown rankIndex "${r}" on table "${e}"`);if(a.restrictsCounts)throw new Le(e);y(e,B),Ie(e,f);const d=rt(e,f.name),s=f.sortBy.map((w,T)=>nt(T)),u=f.sortBy.map((w,T)=>re(a.sortValues[T]??null));return ht(o,d,s,f.sortBy,a.partitionKey,u,a.rowId)},async rankPage(e,r,a={}){Oe(Q(a.baseWhere,a.where),t,e,"rankPage");const h=J(e,"rankPage");if(h)return y(e,B),h.rankPage(e,r,a);E(e,r,"rank");const{continueCursor:f,hasMore:d,rows:s}=Ze(Xe,e,r,a);return{continueCursor:f,isDone:!d,page:s.map(u=>u.doc)}},async rankPageRows(e,r,a={}){Oe(Q(a.baseWhere,a.where),t,e,"rankPage"),E(e,r,"rank");const{directions:h,hasMore:f,rows:d}=Ze(Xe,e,r,a);return{directions:h,hasMore:f,rows:d}},async restore(e,r){const a=ie(e,r);if(!a){const d=r===void 0?fe():void 0;if(d?.restore){await d.restore(e);return}throw new b("INTERNAL",`document not found: ${e}`)}const h=t.tables[a.tableName]?.softDeleteMode?.field;if(!h)throw new b("INTERNAL",`ctx.db.restore: table "${a.tableName}" is not a .softDelete() table`);const f=a.row[h]!==null&&a.row[h]!==void 0;await q.patch(e,{[h]:null},r),f&&we(a.tableName,e,void 0,a.row)},async replace(e,r,a,h){const f=ie(e,a);if(!f){const A=a===void 0?fe():void 0;if(A){await A.replace(e,r,void 0,h);return}throw new b("INTERNAL",`document not found: ${e}`)}const{docJson:d,row:s,tableName:u}=f,w=t.tables[u];if(!w)throw new b("INTERNAL",`unknown table: ${u}`);ft("replace",r);const T=h?.allowExplicitId&&typeof r._creationTime=="number"?r._creationTime:C(),g={...r,_creationTime:T,_id:e};ut(w,r,g,N),We(w,g),ee(u,"before","update")&&await te("before","update",{doc:{...g},id:e,op:"update",previous:s,table:u}),he(u),pe(u),Ae(o,u,n`UPDATE ${n.identifier(u)} SET _creationTime = ${T}, ${n.identifier(P)} = ${JSON.stringify(g)} WHERE id = ${e} AND ${n.identifier(P)} = ${d}`),Ee(u,e,g,s),ye(u,e,g),be(u,s,g),we(u,e,s,g),O?.invalidate(u,e,c(u,s,g)),H(u,e,"update",g),l({indexKeys:c(u,s,g),key:e,op:"update",row:g,table:u}),ee(u,"after","update")&&await te("after","update",{doc:g,id:e,op:"update",previous:s,table:u}),await M({doc:g,id:e,op:"update",table:u})},async wipeShard(e){const r=new Set(e?.exclude),a=e?.tables,h=Object.entries(t.tables).filter(([u,w])=>r.has(u)||a!==void 0&&!a.includes(u)?!1:w.shardMode?.kind!=="global").map(([u])=>u);if(a!==void 0){for(const u of a)if(!t.tables[u])throw new b("INTERNAL",`wipeShard: unknown table: ${u}`)}const f={};let d=0;const{deleteAll:s}=q;if(s===void 0)throw new b("INTERNAL","wipeShard: this writer has no deleteAll");for(const u of h){const w=await s(u,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});f[u]=w.deleted,d+=w.deleted}return{deleted:d,tables:f}}},Nt={db:q,scheduler:j};return i.enforceRls===!0?Vt(q,t,(e,r)=>ie(e,r)?.tableName,(e,r)=>Et(e,r)):q};export{yr as CDC_LOG_TABLE,vr as CLIENT_WATERMARK_TABLE,Lr as GLOBAL_SHAPE_SNAPSHOT_TABLE,Ur as IDEMPOTENCY_TABLE,Dn as NotUniqueError,zr as SEARCH_STATE_TABLE,Ir as advanceClientWatermark,Er as applyCdcChanges,wn as assertValidClientId,mr as backfillAggregateIndexes,$r as backfillRankIndexes,gr as backfillSearchIndexes,Nr as bumpCdcEpoch,hr as createShardCtxDb,Dr as deleteGlobalShapeSnapshot,Or as deleteGlobalShapeSnapshotsForConnection,Mr as migrateClientWatermark,Wr as migrateGlobalShapeSnapshot,Sr as minCdcSeq,dt as normalizeIdStructurally,Tr as readCdcChanges,_r as readCdcCursor,Rr as readCdcEpoch,Cr as readClientWatermark,Fr as readGlobalShapeSnapshot,Pr as readIdempotent,Kr as runShardMigrations,Yr as selectShapeMemberIds,Vr as selectShapeRows,Ar as trimCdcChanges,jr as trimIdempotent,qr as writeGlobalShapeSnapshot,Hr as writeIdempotent};
@@ -0,0 +1 @@
1
+ import{LunoraError as g}from"@lunora/errors";const b=Symbol.for("lunora.ctxdb.rls-unwrap");class k extends g{table;constructor(i){super("RLS_REQUIRED",`ctx.db access to "${i}" is denied: the schema is marked .rls("required"), so this table is protected. Apply RLS with .use(rls(policies)) in the procedure, or mark the table .public() to opt it out.`,{name:"RlsRequiredError"}),this.table=i}}const M=o=>Object.entries(o.tables).filter(([,i])=>i.shardMode?.kind!=="global").map(([i])=>i),R=(o,i,u)=>{const n=i?.tables,r=new Set(i?.exclude);for(const d of o)(n===void 0||n.includes(d))&&!r.has(d)&&u(d)},m=(o,i,u)=>{const n={},{deleteAll:r,wipeShard:d}=o;return r&&(n.deleteAll=(s,c)=>(u(s),r(s,c))),d&&(n.wipeShard=s=>(R(M(i),s,u),d(s))),n},v=(o,i,u,n)=>{if(i.rlsMode!=="required")return o;const r=o,d=e=>{const t=i.tables[e];return t!==void 0&&t.isPublic!==!0},s=e=>{if(d(e))throw new k(e)},c=async(e,t)=>{if(t!==void 0){s(t);return}const a=await u(e);a!==void 0&&s(a)},p=async(e,t)=>{if(t!==void 0){s(t);return}if(!n){for(const l of e)await c(l,t);return}const a=await n([...new Set(e)],t);for(const l of e){const f=a.get(l);f!==void 0&&s(f)}},h=r.rankBefore,w=r.rankPageRows,y={...o,...m(r,i,s),[b]:o,aggregate:(e,t)=>(s(e),r.aggregate(e,t)),count:(e,t)=>(s(e),r.count(e,t)),delete:async(e,t,a)=>(await c(e,t),r.delete(e,t,a)),deleteMany:async(e,t,a)=>(await p(e,a),r.deleteMany(e,t,a)),deleteWhere:r.deleteWhere?async(e,t,a)=>(s(e),await r.deleteWhere?.(e,t,a)):void 0,findFirst:(e,t)=>(s(e),r.findFirst(e,t)),findFirstOrThrow:(e,t)=>(s(e),r.findFirstOrThrow(e,t)),findMany:(e,t)=>(s(e),r.findMany(e,t)),get:async(e,t)=>(await c(e,t),r.get(e,t)),groupBy:(e,t)=>(s(e),r.groupBy(e,t)),insert:(e,t,a)=>(s(e),r.insert(e,t,a)),insertMany:(e,t,a)=>(s(e),r.insertMany(e,t,a)),insertManyUnsafe:(e,t,a)=>(s(e),r.insertManyUnsafe(e,t,a)),lookupById:async(e,t)=>(await c(e,t),r.lookupById?.(e,t)??null),patch:async(e,t,a)=>(await c(e,a),r.patch(e,t,a)),patchMany:async(e,t,a)=>(await p(e.map(l=>l.id),a),r.patchMany(e,t,a)),patchWhere:r.patchWhere?async(e,t,a)=>(s(e),await r.patchWhere?.(e,t,a)):void 0,query:e=>(s(e),r.query(e)),rank:(e,t,a)=>(s(e),r.rank(e,t,a)),rankPage:(e,t,a)=>(s(e),r.rankPage(e,t,a)),replace:async(e,t,a,l)=>(await c(e,a),r.replace(e,t,a,l)),restore:async(e,t)=>(await c(e,t),r.restore?.(e,t))};return h&&(y.rankBefore=(e,t,a)=>(s(e),h(e,t,a))),w&&(y.rankPageRows=(e,t,a)=>(s(e),w(e,t,a))),y};export{b as RLS_UNWRAP_SYMBOL,k as RlsRequiredError,v as guardWriter};
@@ -0,0 +1 @@
1
+ import{stableWireKey as g}from"./stableWireKey-YEHLaX6X.mjs";import{depKey as b,SCAN_DEP as p}from"./SCAN_DEP-D_yR9EeV.mjs";import{t as y}from"./estimate-bytes-DwQON1Ky.mjs";import{keysTouchRanges as x}from"./buildIndexRange-DFsdtPjD.mjs";import{stableStringify as R}from"./stableStringify-BjLh4gvA.mjs";const m=1e3,u=4*1024*1024;class z{entries=new Map;tableIndex=new Map;rangeIndex=new Map;totalBytes=0;hits=0;misses=0;evictions=0;maxEntries;maxBytes;now;monotonic=0;constructor(t={}){this.maxEntries=t.maxEntries??m,this.maxBytes=t.maxBytes??u,this.now=t.now??(()=>(this.monotonic+=1,this.monotonic))}async run(t,s,i,e=()=>[]){const n=this.entries.get(t);if(n)return this.hits+=1,n.lastUsed=this.now(),this.entries.delete(t),this.entries.set(t,n),n.result;this.misses+=1;const h=await i(),o=y(h);if(o===void 0)return h;const c=e(),f={bytes:o,deps:s,ranges:c,lastUsed:this.now(),result:h,subscribers:new Set};this.entries.set(t,f),this.totalBytes+=o;for(const a of s){let r=this.tableIndex.get(a);r||(r=new Set,this.tableIndex.set(a,r)),r.add(t)}for(const a of c){let r=this.rangeIndex.get(a.table);r||(r=new Map,this.rangeIndex.set(a.table,r));let l=r.get(a);l||(l=new Set,r.set(a,l)),l.add(t)}return this.evict(),h}invalidate(t,s,i){const e=[];return this.collectAndDrop(b(t,s),e),this.collectAndDrop(b(t,p),e),this.dropRangeDeps(t,i,e),e}invalidateTable(t){const s=[],i=`${t}:`;for(const e of this.tableIndex.keys())e.startsWith(i)&&this.collectAndDrop(e,s);return this.dropRangeDeps(t,void 0,s),s}subscribe(t,s){const i=this.entries.get(t);i&&i.subscribers.add(s)}unsubscribe(t,s){const i=this.entries.get(t);i&&i.subscribers.delete(s)}size(){return{bytes:this.totalBytes,entries:this.entries.size}}clear(){this.entries.clear(),this.tableIndex.clear(),this.rangeIndex.clear(),this.totalBytes=0}subscribers(t){const s=this.entries.get(t);return s?[...s.subscribers]:[]}stats(){return{bytes:this.totalBytes,entries:this.entries.size,evictions:this.evictions,hits:this.hits,misses:this.misses}}dropRangeDeps(t,s,i){const e=this.rangeIndex.get(t);if(!(!e||e.size===0)){for(const[n,h]of e)if(x([n],s))for(const o of h){const c=this.entries.get(o);c&&(this.dropEntry(o,c),i.push(o))}}}collectAndDrop(t,s){const i=this.tableIndex.get(t);if(i)for(const e of i){const n=this.entries.get(e);n&&(this.dropEntry(e,n),s.push(e))}}dropEntry(t,s){this.entries.delete(t),this.totalBytes-=s.bytes;for(const i of s.deps){const e=this.tableIndex.get(i);e&&(e.delete(t),e.size===0&&this.tableIndex.delete(i))}for(const i of s.ranges){const e=this.rangeIndex.get(i.table),n=e?.get(i);n?.delete(t),e&&n?.size===0&&(e.delete(i),e.size===0&&this.rangeIndex.delete(i.table))}}evict(){if(!(this.entries.size<=this.maxEntries&&this.totalBytes<=this.maxBytes))for(const[t,s]of this.entries){if(this.entries.size<=this.maxEntries&&this.totalBytes<=this.maxBytes)return;s.subscribers.size>0||(this.dropEntry(t,s),this.evictions+=1)}}}const E=(d,t,s)=>`${s??"\0anon"}\0${d}:${g(t)}`;export{z as ReactiveCache,E as reactiveCacheKey,R as stableStringify,g as stableWireKey};
@@ -0,0 +1 @@
1
+ import{f as l}from"./wire-codec-Ctnni0h6.mjs";const c="_id",p="__lunora__",b=r=>{if(typeof r!="object"||r===null||Array.isArray(r))return;const t=r[c];return typeof t=="string"?t:void 0},y=r=>{const t=new Map,o=[];for(const s of r){const e=b(s);if(e===void 0||t.has(e))return;t.set(e,s),o.push(e)}return{byId:t,order:o}},g=(r,t)=>{const o=r.order.filter(e=>t.byId.has(e)),s=t.order.filter(e=>r.byId.has(e));return o.length!==s.length?!1:o.every((e,n)=>s[n]===e)},h=(r,t,o,s)=>{const e=[];for(const n of r.order)t.byId.has(n)||e.push({delta:{key:n,op:"delete",table:o},frame:`{"key":${JSON.stringify(n)},"op":"delete","table":${s}}`});return e},m=(r,t,o,s)=>{const e=[];for(const n of t.order){const i=t.byId.get(n),a=r.byId.get(n),f=JSON.stringify(l(i)),d=a===void 0?void 0:JSON.stringify(a);if(d===f)continue;const u=d===void 0?"insert":"update";e.push({delta:{key:n,op:u,row:i,table:o},frame:`{"key":${JSON.stringify(n)},"op":"${u}","row":${f},"table":${s}}`})}return e},S=(r,t,o,s)=>{let e;try{e=JSON.parse(r)}catch{return}if(!Array.isArray(e)||!Array.isArray(t))return;const n=y(e),i=y(t);if(n===void 0||i===void 0||!g(n,i))return;const a=o===""?p:o,f=JSON.stringify(a),d=[...h(n,i,a,f),...m(n,i,a,f)];if(!(d.length>i.order.length)){if(s!==void 0)for(const{frame:u}of d)s.push(u);return d.map(({delta:u})=>u)}},$=(r,t)=>{try{return r.send(t),!0}catch{return!1}},I=(r,t,o,s,e)=>{const n=JSON.stringify(t),i=e===void 0?"":`,"lastMutationId":${String(e)}`;let a=!0;for(const f of o)$(r,`{"type":"delta","id":${n},"delta":${f}${i}${s}}`)||(a=!1);return a},w=async r=>{let t=0;for(;t<100;){t+=1;const{bufferedAmount:o}=r;if(typeof o!="number"||o<1048576)return;await new Promise(s=>{setTimeout(s,20)})}};export{w as awaitWsDrain,I as sendDeltaFrames,S as subscriptionListDeltas,$ as trySendFrame};
@@ -1 +1 @@
1
- import{createShardCtxDb as b}from"./NotUniqueError-C8DLoXSK.mjs";import{createRelayLink as I}from"./DEFAULT_MAX_RELAYS-CnCyh6oX.mjs";import{ConflictError as N}from"./ConflictError-C8GtJmjS.mjs";import{runShardMigrations as v}from"./runShardMigrations-CPxqCh3O.mjs";import{relayName as q}from"./DEFAULT_PROMOTION_THRESHOLDS-Dteg0sZF.mjs";const C=(_,m={})=>({_meta:{column:{notNull:!0,...m}},kind:_}),D=(_,m,E)=>{const{describe:k,expect:i,it:f}=E;k(`engine contract: ${_}`,()=>{k("optimistic concurrency",()=>{const g=p=>({tables:{items:{indexes:[],shape:{title:C("string"),version:C("number",{notNull:!1})},triggerMap:{clobber:{handler:()=>{p.exec(`UPDATE "items" SET "__doc__" = json_set("__doc__", '$.version', 99) WHERE "id" = 'i1'`)},op:"update",timing:"before"}}}}});f("raises a CONFLICT of kind `occ` when a write's snapshot is clobbered",async()=>{const{close:p,host:d}=m();try{const c=d.sql,l=g(c);v(c,l);const s=b({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0}),await i(s.patch("i1",{title:"second"})).rejects.toBeInstanceOf(N)}finally{p?.()}}),f("reports the conflict as CONFLICT/409 rather than retrying it away",async()=>{const{close:p,host:d}=m();try{const c=d.sql,l=g(c);v(c,l);const s=b({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let r;try{await s.patch("i1",{title:"second"})}catch(t){r=t}const e=r;i(e.code).toBe("CONFLICT"),i(e.kind).toBe("occ")}finally{p?.()}}),f("leaves the row readable and unchanged after a conflict",async()=>{const{close:p,host:d}=m();try{const c=d.sql,l=g(c);v(c,l);const s=b({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});try{await s.patch("i1",{title:"second"})}catch{}const r=await s.get("i1");i(r?.title).toBe("first"),i(r?.version).toBe(99)}finally{p?.()}}),f("raises a CONFLICT of kind `trigger` when a trigger writes its own row through the db",async()=>{const{close:p,host:d}=m();try{const c=d.sql,l={tables:{items:{indexes:[],shape:{title:C("string"),version:C("number",{notNull:!1})},triggerMap:{recurse:{handler:async(t,o)=>{await t.db.patch(o.doc._id,{version:99})},op:"update",timing:"before"}}}}};v(c,l);const s=b({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let r;try{await s.patch("i1",{title:"second"})}catch(t){r=t}const e=r;i(e).toBeInstanceOf(N),i(e.code).toBe("CONFLICT"),i(e.kind).toBe("trigger")}finally{p?.()}})}),k("shape-poke ordering",()=>{const g="shard-a",p={args:{},name:"messages"},d=(e,t,o,a)=>e.accept(t?.()??{},{connectionId:o,shapes:{[a]:p}}),c=(e,t)=>{let o=0,a=0;const n=u=>()=>{throw new Error(`the relay poke path must not reach RelayHost.${u}`)},h={fetch:(u,O)=>{if(JSON.parse(O?.body??"{}").type!=="relay_shape_subscribe")return Promise.resolve(new Response(void 0,{status:204}));const B=t[a];if(a+=1,B===void 0)throw new Error("the relay asked for more seeds than this fixture supplies");return Promise.resolve(Response.json(B))}},y={get:()=>h,getByName:()=>h,idFromName:u=>u},w={buildShapeDiff:n("buildShapeDiff"),computeOpLogShapeSeed:n("computeOpLogShapeSeed"),currentCdcEpoch:n("currentCdcEpoch"),deliverWhisperLocal:n("deliverWhisperLocal"),doName:()=>q(g,0),env:()=>({SHARD:y}),getWebSockets:()=>e.getSockets(),maskMetadata:n("maskMetadata"),nextPokeId:()=>(o+=1,`poke-${String(o)}`),readAttachment:u=>u.deserializeAttachment?.(),recordShapePokeFanout:()=>{},resolveShape:n("resolveShape"),rlsMetadata:n("rlsMetadata"),shardBinding:()=>"SHARD",sql:n("sql")},S=I(w);if(S===void 0)throw new Error("expected a relay link for a `…::relay::N` name");return S},l=e=>new Request("https://relay.internal/_lunora/relay",{body:JSON.stringify(e),headers:{"content-type":"application/json"},method:"POST"}),s=async(e,t,o)=>{const a=await e.seedRelayShape(t,o,p,{identity:void 0,userId:void 0});if(a!=="ok")throw new Error(`seed failed: ${JSON.stringify(a)}`)},r=(e={})=>l({...p,checkpoint:20,epoch:"e1",fromCursor:10,rowsPatch:[{id:"r1",op:"upsert",value:{title:"hello"}}],type:"relay_shape_poke",...e});f("frames a poke as pokeStart → pokePart per shape → pokeEnd, under one poke id",async()=>{const{close:e,createSocket:t,readFrames:o,sockets:a}=m();try{const n=c(a,[{cursor:10,epoch:"e1",frames:[]}]),h=d(a,t,"c-alice","s1");await s(n,h,"s1"),await n.handleControl(r());const y=(await o(h)).map(w=>JSON.parse(w));i(y.map(w=>w.type)).toStrictEqual(["pokeStart","pokePart","pokeEnd"]),i(new Set(y.map(w=>w.pokeId)).size).toBe(1),i(y[1]?.shapeId).toBe("s1"),i(y[2]?.checkpoint).toBe(20)}finally{e?.()}}),f("delivers a poke only to sockets whose cursor matches, and advances them past it",async()=>{const{close:e,createSocket:t,readFrames:o,sockets:a}=m();try{const n=c(a,[{cursor:10,epoch:"e1",frames:[]},{cursor:7,epoch:"e1",frames:[]}]),h=d(a,t,"c-alice","s1"),y=d(a,t,"c-bob","s2");await s(n,h,"s1"),await s(n,y,"s2"),await n.handleControl(r());const w=await o(h);i(w.length).toBe(3);const S=await o(y);i(S.length).toBe(0),await n.handleControl(r());const u=await o(h);i(u.length).toBe(3)}finally{e?.()}}),f("skips a socket whose cursor matches under a different CDC epoch",async()=>{const{close:e,createSocket:t,readFrames:o,sockets:a}=m();try{const n=c(a,[{cursor:10,epoch:"e1",frames:[]}]),h=d(a,t,"c-alice","s1");await s(n,h,"s1"),await n.handleControl(r({epoch:"e2"}));const y=await o(h);i(y.length).toBe(0),await n.handleControl(r());const w=await o(h);i(w.length).toBe(3)}finally{e?.()}})}),k("RLS identity under live subscription",()=>{const g="shard-a",p={args:{},name:"lobby-messages"},d={args:{},name:"my-orders"},c=s=>{const r=[],e=[],t={fetch:(a,n)=>(r.push(JSON.parse(n?.body??"{}")),Promise.resolve(new Response(void 0,{status:204})))},o=I({buildShapeDiff:()=>[{id:"r1",op:"upsert",value:{}}],computeOpLogShapeSeed:()=>({baseCheckpoint:void 0,cursor:10,epoch:"e1",rowsPatch:[]}),currentCdcEpoch:()=>"e1",deliverWhisperLocal:()=>0,doName:()=>g,env:()=>({SHARD:{get:()=>t,getByName:()=>t,idFromName:a=>a}}),getWebSockets:()=>[],maskMetadata:()=>({columns:[]}),nextPokeId:()=>"poke-1",readAttachment:()=>({}),recordShapePokeFanout:()=>{},resolveShape:(a,n,h)=>(e.push(h),a===d.name?{columns:["id"],effectiveWhere:{org:h?.identity?.org??"anonymous"},global:!1,table:"orders"}:{columns:["id"],effectiveWhere:{room:"lobby"},global:!1,table:"messages"}),rlsMetadata:()=>({policies:[]}),shardBinding:()=>"SHARD",sql:()=>s});if(o===void 0)throw new Error("expected an owner link for an un-suffixed DO name");return{owner:o,posts:r,resolvedUnder:e}},l=async(s,r)=>{await s.handleControl(new Request("https://owner.internal/_lunora/relay",{body:JSON.stringify({...r,connectionId:"c-alice",identity:{org:"acme"},relayIndex:0,subId:"s1",type:"relay_shape_subscribe",userId:"u1"}),headers:{"content-type":"application/json"},method:"POST"}))};f("seeds a subscriber under its own forwarded identity, never the anonymous one",async()=>{const{close:s,host:r}=m();try{const{owner:e,resolvedUnder:t}=c(r.sql);await l(e,d),i(t.some(o=>o?.userId==="u1"&&o.identity?.org==="acme")).toBe(!0)}finally{s?.()}}),f("routes an identity-scoped shape to a per-socket poke, not the cohort multicast",async()=>{const{close:s,host:r}=m();try{const{owner:e,posts:t}=c(r.sql);await l(e,d),t.length=0,await e.onFlush(new Set(["orders"]),20);const o=t.filter(a=>a.type==="relay_shape_poke");i(o.length).toBe(1),i(o[0]?.targetConnectionId).toBe("c-alice")}finally{s?.()}}),f("still multicasts an identity-blind shape to the whole cohort",async()=>{const{close:s,host:r}=m();try{const{owner:e,posts:t}=c(r.sql);await l(e,p),t.length=0,await e.onFlush(new Set(["messages"]),20);const o=t.filter(a=>a.type==="relay_shape_poke");i(o.length).toBe(1),i(o[0]?.targetConnectionId).toBeUndefined()}finally{s?.()}})})})};export{D as defineEngineContractSuite};
1
+ import{createShardCtxDb as b}from"./NotUniqueError-Qrtwm7S6.mjs";import{createRelayLink as I}from"./DEFAULT_MAX_RELAYS-D0oc40p6.mjs";import{ConflictError as N}from"./ConflictError-C8GtJmjS.mjs";import{runShardMigrations as v}from"./runShardMigrations-CPxqCh3O.mjs";import{relayName as q}from"./DEFAULT_PROMOTION_THRESHOLDS-Dteg0sZF.mjs";const C=(_,m={})=>({_meta:{column:{notNull:!0,...m}},kind:_}),D=(_,m,E)=>{const{describe:k,expect:i,it:f}=E;k(`engine contract: ${_}`,()=>{k("optimistic concurrency",()=>{const g=p=>({tables:{items:{indexes:[],shape:{title:C("string"),version:C("number",{notNull:!1})},triggerMap:{clobber:{handler:()=>{p.exec(`UPDATE "items" SET "__doc__" = json_set("__doc__", '$.version', 99) WHERE "id" = 'i1'`)},op:"update",timing:"before"}}}}});f("raises a CONFLICT of kind `occ` when a write's snapshot is clobbered",async()=>{const{close:p,host:d}=m();try{const c=d.sql,l=g(c);v(c,l);const s=b({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0}),await i(s.patch("i1",{title:"second"})).rejects.toBeInstanceOf(N)}finally{p?.()}}),f("reports the conflict as CONFLICT/409 rather than retrying it away",async()=>{const{close:p,host:d}=m();try{const c=d.sql,l=g(c);v(c,l);const s=b({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let r;try{await s.patch("i1",{title:"second"})}catch(t){r=t}const e=r;i(e.code).toBe("CONFLICT"),i(e.kind).toBe("occ")}finally{p?.()}}),f("leaves the row readable and unchanged after a conflict",async()=>{const{close:p,host:d}=m();try{const c=d.sql,l=g(c);v(c,l);const s=b({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});try{await s.patch("i1",{title:"second"})}catch{}const r=await s.get("i1");i(r?.title).toBe("first"),i(r?.version).toBe(99)}finally{p?.()}}),f("raises a CONFLICT of kind `trigger` when a trigger writes its own row through the db",async()=>{const{close:p,host:d}=m();try{const c=d.sql,l={tables:{items:{indexes:[],shape:{title:C("string"),version:C("number",{notNull:!1})},triggerMap:{recurse:{handler:async(t,o)=>{await t.db.patch(o.doc._id,{version:99})},op:"update",timing:"before"}}}}};v(c,l);const s=b({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let r;try{await s.patch("i1",{title:"second"})}catch(t){r=t}const e=r;i(e).toBeInstanceOf(N),i(e.code).toBe("CONFLICT"),i(e.kind).toBe("trigger")}finally{p?.()}})}),k("shape-poke ordering",()=>{const g="shard-a",p={args:{},name:"messages"},d=(e,t,o,a)=>e.accept(t?.()??{},{connectionId:o,shapes:{[a]:p}}),c=(e,t)=>{let o=0,a=0;const n=u=>()=>{throw new Error(`the relay poke path must not reach RelayHost.${u}`)},h={fetch:(u,O)=>{if(JSON.parse(O?.body??"{}").type!=="relay_shape_subscribe")return Promise.resolve(new Response(void 0,{status:204}));const B=t[a];if(a+=1,B===void 0)throw new Error("the relay asked for more seeds than this fixture supplies");return Promise.resolve(Response.json(B))}},y={get:()=>h,getByName:()=>h,idFromName:u=>u},w={buildShapeDiff:n("buildShapeDiff"),computeOpLogShapeSeed:n("computeOpLogShapeSeed"),currentCdcEpoch:n("currentCdcEpoch"),deliverWhisperLocal:n("deliverWhisperLocal"),doName:()=>q(g,0),env:()=>({SHARD:y}),getWebSockets:()=>e.getSockets(),maskMetadata:n("maskMetadata"),nextPokeId:()=>(o+=1,`poke-${String(o)}`),readAttachment:u=>u.deserializeAttachment?.(),recordShapePokeFanout:()=>{},resolveShape:n("resolveShape"),rlsMetadata:n("rlsMetadata"),shardBinding:()=>"SHARD",sql:n("sql")},S=I(w);if(S===void 0)throw new Error("expected a relay link for a `…::relay::N` name");return S},l=e=>new Request("https://relay.internal/_lunora/relay",{body:JSON.stringify(e),headers:{"content-type":"application/json"},method:"POST"}),s=async(e,t,o)=>{const a=await e.seedRelayShape(t,o,p,{identity:void 0,userId:void 0});if(a!=="ok")throw new Error(`seed failed: ${JSON.stringify(a)}`)},r=(e={})=>l({...p,checkpoint:20,epoch:"e1",fromCursor:10,rowsPatch:[{id:"r1",op:"upsert",value:{title:"hello"}}],type:"relay_shape_poke",...e});f("frames a poke as pokeStart → pokePart per shape → pokeEnd, under one poke id",async()=>{const{close:e,createSocket:t,readFrames:o,sockets:a}=m();try{const n=c(a,[{cursor:10,epoch:"e1",frames:[]}]),h=d(a,t,"c-alice","s1");await s(n,h,"s1"),await n.handleControl(r());const y=(await o(h)).map(w=>JSON.parse(w));i(y.map(w=>w.type)).toStrictEqual(["pokeStart","pokePart","pokeEnd"]),i(new Set(y.map(w=>w.pokeId)).size).toBe(1),i(y[1]?.shapeId).toBe("s1"),i(y[2]?.checkpoint).toBe(20)}finally{e?.()}}),f("delivers a poke only to sockets whose cursor matches, and advances them past it",async()=>{const{close:e,createSocket:t,readFrames:o,sockets:a}=m();try{const n=c(a,[{cursor:10,epoch:"e1",frames:[]},{cursor:7,epoch:"e1",frames:[]}]),h=d(a,t,"c-alice","s1"),y=d(a,t,"c-bob","s2");await s(n,h,"s1"),await s(n,y,"s2"),await n.handleControl(r());const w=await o(h);i(w.length).toBe(3);const S=await o(y);i(S.length).toBe(0),await n.handleControl(r());const u=await o(h);i(u.length).toBe(3)}finally{e?.()}}),f("skips a socket whose cursor matches under a different CDC epoch",async()=>{const{close:e,createSocket:t,readFrames:o,sockets:a}=m();try{const n=c(a,[{cursor:10,epoch:"e1",frames:[]}]),h=d(a,t,"c-alice","s1");await s(n,h,"s1"),await n.handleControl(r({epoch:"e2"}));const y=await o(h);i(y.length).toBe(0),await n.handleControl(r());const w=await o(h);i(w.length).toBe(3)}finally{e?.()}})}),k("RLS identity under live subscription",()=>{const g="shard-a",p={args:{},name:"lobby-messages"},d={args:{},name:"my-orders"},c=s=>{const r=[],e=[],t={fetch:(a,n)=>(r.push(JSON.parse(n?.body??"{}")),Promise.resolve(new Response(void 0,{status:204})))},o=I({buildShapeDiff:()=>[{id:"r1",op:"upsert",value:{}}],computeOpLogShapeSeed:()=>({baseCheckpoint:void 0,cursor:10,epoch:"e1",rowsPatch:[]}),currentCdcEpoch:()=>"e1",deliverWhisperLocal:()=>0,doName:()=>g,env:()=>({SHARD:{get:()=>t,getByName:()=>t,idFromName:a=>a}}),getWebSockets:()=>[],maskMetadata:()=>({columns:[]}),nextPokeId:()=>"poke-1",readAttachment:()=>({}),recordShapePokeFanout:()=>{},resolveShape:(a,n,h)=>(e.push(h),a===d.name?{columns:["id"],effectiveWhere:{org:h?.identity?.org??"anonymous"},global:!1,table:"orders"}:{columns:["id"],effectiveWhere:{room:"lobby"},global:!1,table:"messages"}),rlsMetadata:()=>({policies:[]}),shardBinding:()=>"SHARD",sql:()=>s});if(o===void 0)throw new Error("expected an owner link for an un-suffixed DO name");return{owner:o,posts:r,resolvedUnder:e}},l=async(s,r)=>{await s.handleControl(new Request("https://owner.internal/_lunora/relay",{body:JSON.stringify({...r,connectionId:"c-alice",identity:{org:"acme"},relayIndex:0,subId:"s1",type:"relay_shape_subscribe",userId:"u1"}),headers:{"content-type":"application/json"},method:"POST"}))};f("seeds a subscriber under its own forwarded identity, never the anonymous one",async()=>{const{close:s,host:r}=m();try{const{owner:e,resolvedUnder:t}=c(r.sql);await l(e,d),i(t.some(o=>o?.userId==="u1"&&o.identity?.org==="acme")).toBe(!0)}finally{s?.()}}),f("routes an identity-scoped shape to a per-socket poke, not the cohort multicast",async()=>{const{close:s,host:r}=m();try{const{owner:e,posts:t}=c(r.sql);await l(e,d),t.length=0,await e.onFlush(new Set(["orders"]),20);const o=t.filter(a=>a.type==="relay_shape_poke");i(o.length).toBe(1),i(o[0]?.targetConnectionId).toBe("c-alice")}finally{s?.()}}),f("still multicasts an identity-blind shape to the whole cohort",async()=>{const{close:s,host:r}=m();try{const{owner:e,posts:t}=c(r.sql);await l(e,p),t.length=0,await e.onFlush(new Set(["messages"]),20);const o=t.filter(a=>a.type==="relay_shape_poke");i(o.length).toBe(1),i(o[0]?.targetConnectionId).toBeUndefined()}finally{s?.()}})})})};export{D as defineEngineContractSuite};
@@ -0,0 +1 @@
1
+ const r=n=>{try{const t=JSON.stringify(n);return t===void 0?0:t.length}catch{return}};export{r as t};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/shard-engine",
3
- "version": "1.0.0-alpha.5",
3
+ "version": "1.0.0-alpha.6",
4
4
  "description": "Host-neutral reactive engine for Lunora: per-shard state, OCC, CDC, reactive subscriptions, and the poke protocol. Consumes @lunora/platform host contracts and can be mounted on any platform host.",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -48,8 +48,8 @@
48
48
  "access": "public"
49
49
  },
50
50
  "dependencies": {
51
- "@lunora/errors": "1.0.0-alpha.11",
52
- "@lunora/platform": "1.0.0-alpha.2",
51
+ "@lunora/errors": "1.0.0-alpha.12",
52
+ "@lunora/platform": "1.0.0-alpha.3",
53
53
  "drizzle-orm": "^0.45.2"
54
54
  },
55
55
  "engines": {
@@ -1 +0,0 @@
1
- import{LunoraError as i}from"@lunora/errors";import{r as s}from"./estimate-bytes-DzD3PdCc.mjs";const e={maxReadRows:1e5,maxWrittenBytes:32*1024*1024,maxWrittenRows:5e4};class a{readRows=0;writtenRows=0;writtenBytes=0;limits;constructor(t={}){this.limits={...e,...t}}recordRead(t){if(this.readRows+=t,this.readRows>this.limits.maxReadRows)throw new i("TRANSACTION_LIMIT_EXCEEDED",`this transaction read ${String(this.readRows)} documents, over the ${String(this.limits.maxReadRows)}-document limit`)}recordWrite(t){if(this.writtenRows+=1,this.writtenBytes+=s(t,this.limits.maxWrittenBytes),this.writtenRows>this.limits.maxWrittenRows)throw new i("TRANSACTION_LIMIT_EXCEEDED",`this transaction wrote ${String(this.writtenRows)} documents, over the ${String(this.limits.maxWrittenRows)}-document limit`);if(this.writtenBytes>this.limits.maxWrittenBytes)throw new i("TRANSACTION_LIMIT_EXCEEDED",`this transaction wrote ${String(this.writtenBytes)} bytes, over the ${String(this.limits.maxWrittenBytes)}-byte limit`)}headroom(){return{readRows:this.readRows,remainingReadRows:Math.max(0,this.limits.maxReadRows-this.readRows),remainingWrittenBytes:Math.max(0,this.limits.maxWrittenBytes-this.writtenBytes),remainingWrittenRows:Math.max(0,this.limits.maxWrittenRows-this.writtenRows),writtenBytes:this.writtenBytes,writtenRows:this.writtenRows}}}export{e as DEFAULT_TRANSACTION_LIMITS,a as TransactionHeadroomTracker};
@@ -1 +0,0 @@
1
- import{LunoraError as y}from"@lunora/errors";import{n as Et,A as Ue,T as Se,y as Nt,c as St}from"./FTS_COUNT_COLUMN-D1gY3wwZ-CZHdaRrd.mjs";import{sql as n}from"drizzle-orm";import{aggregateSqlFunction as Te,normalizeCountArgument as Tt,throwingScheduler as _t}from"./AGGREGATE_SQL_FUNCTION-QYaiuty4.mjs";import{encodeAggregateKey as Ce,readAggregateValue as Me,aggregateTableName as Le}from"./aggregateTableName-G-eXyjcz.mjs";import{mergeWhere as J,CountRlsUnsupportedError as ke,selectIndexForGroupBy as Rt,selectIndexForCount as At,selectIndexForAggregate as vt}from"./CountRlsUnsupportedError-B2WKJD9v.mjs";import{backfillSearchIndexesForTable as It}from"./backfillAggregateIndexes-BHiewuB-.mjs";import{backfillAggregateIndexes as pr,backfillRankIndexes as mr,backfillSearchIndexes as wr}from"./backfillAggregateIndexes-BHiewuB-.mjs";import{appendCdcChange as xt}from"./CDC_LOG_TABLE-BnqlH2eZ.mjs";import{CDC_LOG_TABLE as $r,applyCdcChanges as yr,bumpCdcEpoch as br,minCdcSeq as Er,readCdcChanges as Nr,readCdcCursor as Sr,readCdcEpoch as Tr,trimCdcChanges as _r}from"./CDC_LOG_TABLE-BnqlH2eZ.mjs";import{createCompanionSync as Ct}from"./createCompanionSync-DWK0Vlg1.mjs";import{computeRankPage as Xe}from"./computeRankPage-IUSS-zIB.mjs";import{SCAN_DEP as q}from"./SCAN_DEP-D_yR9EeV.mjs";import{runDrizzle as B}from"./runDrizzle-GKR3y97k.mjs";import{DOC_COLUMN as P,quoteIdentifier as Mt,AGG_VALUE as _e,AGG_COUNT as De,AGG_KEY as Re,jsonPathSql as Q,rowToDocument as le,tableColumns as ht,isFtsAvailable as Lt,tryRowToDocument as pt,geoTableName as kt,qualifiedJsonPathSql as Ze}from"./AGG_COUNT-BWXe3gtQ.mjs";import{coveringGeohashes as Dt,boundingBoxGeohashes as Ot,pointInBoundingBox as Wt,haversineMeters as Ft}from"./GEO_DEFAULT_PRECISION-okRCkZ6r.mjs";import{NotFoundError as qt}from"./NotFoundError-BhF7FeFr.mjs";import{normalizeOrderKeys as Bt,buildSeekWhere as mt,decodeCursor as Fe,applySelect as et,encodeCursor as qe,softDeleteScope as de,buildSeekBeforeWhere as Ut}from"./applySelect-B0CF8T7y.mjs";import{sortColumnName as tt,resolveRankPartition as Pt,encodePartitionKey as Ht,RANK_TIEBREAK as jt,rankTableName as nt}from"./RANK_TIEBREAK-9NU5s_mi.mjs";import{indexKeysForRow as Gt,buildIndexRange as Kt}from"./buildIndexRange-DFsdtPjD.mjs";import{assertFlatPredicate as Oe,resolveRelationPredicates as rt}from"./DEFAULT_MAX_RELATION_KEYS-bq00btqV.mjs";import{runRowValidators as We,resolveWith as it,applyOnDelete as Jt,fanOutScalarCounts as Qt}from"./applyOnDelete-uFRC5p1d.mjs";import{guardWriter as zt}from"./RLS_UNWRAP_SYMBOL-C6_WX3dG.mjs";import{createSystemReader as Vt}from"./createSystemReader-DcDcrtM3.mjs";import{ConflictError as we}from"./ConflictError-C8GtJmjS.mjs";import{runTriggers as Yt}from"./hasTrigger-CbkOHExZ.mjs";import{compileWhereSql as ne}from"./compileWhereSql-BLcfs4QW.mjs";import{CLIENT_WATERMARK_TABLE as Ar,advanceClientWatermark as vr,migrateClientWatermark as Ir,readClientWatermark as xr}from"./CLIENT_WATERMARK_TABLE-CXsSLU8D.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as Mr,deleteGlobalShapeSnapshot as Lr,deleteGlobalShapeSnapshotsForConnection as kr,migrateGlobalShapeSnapshot as Dr,readGlobalShapeSnapshot as Or,writeGlobalShapeSnapshot as Wr}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-DX-6-gBP.mjs";import{IDEMPOTENCY_TABLE as qr,readIdempotent as Br,trimIdempotent as Ur,writeIdempotent as Pr}from"./IDEMPOTENCY_TABLE-DjkEMp6w.mjs";import{runShardMigrations as jr}from"./runShardMigrations-CPxqCh3O.mjs";import{SEARCH_STATE_TABLE as Kr}from"./SEARCH_STATE_TABLE-eLN8U5tz.mjs";import{selectShapeMemberIds as Qr,selectShapeRows as zr}from"./selectShapeMemberIds-DvE7K6zG.mjs";import{serializeSqlValue as re}from"./serializeSqlValue-DnpyaLcw.mjs";const Xt=i=>{const o=new TextEncoder().encode(i);let t="";for(const d of o)t+=String.fromCodePoint(d);return btoa(t)},Zt=i=>{const o=atob(i),t=Uint8Array.from(o,d=>d.codePointAt(0)??0);return new TextDecoder().decode(t)},en=()=>new y("BAD_REQUEST","invalid cursor"),ot=16,at=8,Z=1024,Pe=(i,o)=>o.query(i),tn=(i,o,t)=>{const d=Et(i,t);if(d.length===0)return 0;let f=0;for(const[p,w]of o.entries()){const R=p===o.length-1;let S=0;for(const g of d)(R?g.startsWith(w):g===w)&&(S+=1);if(S===0)return 0;f+=S}return f},nn=(i,o)=>{if(!o)return{exact:!0,lower:i,upper:i};const t=i.codePointAt(i.length-1)??0,d=i.slice(0,Math.max(0,i.length-String.fromCodePoint(t).length));return{exact:!1,lower:i,upper:d+String.fromCodePoint(t+1)}},rn=(i,o,t)=>{const d={eq:(f,p)=>{if(!i.definition.filterFields?.includes(f))throw new y("INTERNAL",`field "${f}" is not a filter field of search index "${i.indexName}" on table "${o}"`);if(i.filters.length>=at)throw new y("BAD_REQUEST",`search index "${i.indexName}" on table "${o}": at most ${String(at)} .eq() filters are supported per search query`);return i.filters.push({field:f,value:p}),d},search:(f,p)=>{const w=i;if(f!==w.definition.field)throw new y("INTERNAL",`search index "${w.indexName}" on table "${o}" indexes "${w.definition.field}", not "${f}"`);const R=Pe(p,t).length;if(R>ot)throw new y("BAD_REQUEST",`search index "${w.indexName}" on table "${o}": at most ${String(ot)} search terms are supported (got ${String(R)})`);return w.field=f,w.query=p,w.hasQuery=!0,d}};return d},on=i=>{if(i.length>Z)throw new y("BAD_REQUEST",`more than ${String(Z)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},an=i=>Math.min(i.offset+i.numItems+1,Z),sn=i=>Xt(`search:${String(i)}`),dn=i=>{let o;try{o=Zt(i)}catch{return}if(!o.startsWith("search:"))return;const t=Number(o.slice(7));return Number.isInteger(t)&&t>=0?t:void 0},ln=i=>{if(typeof i.endCursor=="string")throw new y("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");const o=Math.max(0,Math.floor(i.numItems)),t=i.cursor?dn(i.cursor):0;if(t===void 0)throw en();if(t+o>Z)throw new y("BAD_REQUEST",`search pagination reaches past the ${String(Z)}-document limit (offset ${String(t)} + ${String(o)} requested) — narrow the query or the filters instead`);return{numItems:o,offset:t}},cn=(i,o)=>{const t=o.offset+o.numItems,d=o.numItems>0&&i.length>t;return{continueCursor:d?sn(t):null,isDone:!d,page:i.slice(o.offset,t)}},un=i=>{if(i===void 0)return Z+1;if(!Number.isFinite(i))return Z;const o=Math.max(0,Math.floor(i));if(o>Z)throw new y("BAD_REQUEST",`search returns at most ${String(Z)} documents (asked for ${String(o)}) — narrow the query or paginate instead`);return o},fn=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,hn=i=>{if(!fn.test(i))throw new y("INTERNAL",`invalid clientId ${JSON.stringify(i)}: a client-supplied row id must be a UUID`)},st=50,wt=500,pn=128,se=(i,o,t)=>{const d=o??wt;if(i>d)throw new y("BATCH_LIMIT_EXCEEDED",`${t}: batch of ${String(i)} exceeds the limit of ${String(d)} (raise options.limit or chunk the call)`,{status:400})},mn=i=>{const o={eq:(t,d)=>(i.sqlConditions.push({comparator:"=",field:t,value:d}),o),gt:(t,d)=>(i.sqlConditions.push({comparator:">",field:t,value:d}),o),gte:(t,d)=>(i.sqlConditions.push({comparator:">=",field:t,value:d}),o),lt:(t,d)=>(i.sqlConditions.push({comparator:"<",field:t,value:d}),o),lte:(t,d)=>(i.sqlConditions.push({comparator:"<=",field:t,value:d}),o)};return o},wn=i=>Math.max(i,Z),gn=(i,o,t,d,f)=>{const p=Pe(t.query,Ue(t.definition.language));if(p.length===0)return[];const w=St(o,t.indexName),R=`${w}__vocab`,S=p.length-1,g=p.map((M,k)=>{const H=nn(M,k===S),U=H.exact?n`${n.identifier("term")} = ${H.lower}`:n`${n.identifier("term")} >= ${H.lower} AND ${n.identifier("term")} < ${H.upper}`;return n`SELECT ${n.identifier("doc")}, ${n.raw(String(k))} AS ${n.identifier("__term__")}, COUNT(*) AS ${n.identifier("__n__")} FROM ${n.identifier(R)} WHERE ${U} GROUP BY ${n.identifier("doc")}`}),b=p.map((M,k)=>n`SUM(CASE WHEN u.${n.identifier("__term__")} = ${n.raw(String(k))} THEN u.${n.identifier("__n__")} ELSE 0 END)`),E=n`SELECT f.${n.identifier(Se)} AS ${n.identifier(Se)}, ${n.join(b,n` + `)} AS ${n.identifier("__score__")} FROM (${n.join(g,n` UNION ALL `)}) u JOIN ${n.identifier(w)} f ON f.rowid = u.${n.identifier("doc")} GROUP BY f.${n.identifier(Se)} HAVING ${n.join(b.map(M=>n`${M} > 0`),n` AND `)}`,_=[];for(const M of t.filters)_.push(n`${Q(M.field)} = ${re(M.value)}`);f&&_.push(f);let C=n`SELECT m.id, m._creationTime, m.${n.identifier(P)}, s.${n.identifier("__score__")} AS ${n.identifier("__score__")} FROM (${E}) s JOIN ${n.identifier(o)} m ON m.id = s.${n.identifier(Se)}`;_.length>0&&(C=n`${C} WHERE ${n.join(_,n` AND `)}`),C=n`${C} ORDER BY s.${n.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${n.raw(String(d))}`;const D=[];for(const M of B(i,C)){const k=pt(M);if(k){const H=M.__score__;D.push({document:k,score:typeof H=="number"?H:Number(H??0)})}}return D},$n=(i,o,t,d,f)=>{const p=Ue(t.definition.language),w=Pe(t.query,p);if(w.length===0)return[];const R=[];for(const E of t.filters)R.push(n`${Q(E.field)} = ${re(E.value)}`);f&&R.push(f);let S=n`SELECT id, _creationTime, ${n.identifier(P)} FROM ${n.identifier(o)}`;R.length>0&&(S=n`${S} WHERE ${n.join(R,n` AND `)}`),S=n`${S} ORDER BY _creationTime DESC, id ASC LIMIT ${n.raw(String(wn(d)))}`;const g=B(i,S).toArray(),b=[];for(const E of g){const _=pt(E);if(!_)continue;const C=tn(Nt(_,t.definition),w,p);C>0&&b.push({creationTime:typeof _._creationTime=="number"?_._creationTime:0,doc:_,id:typeof _._id=="string"?_._id:"",score:C})}return b.sort((E,_)=>_.score-E.score||_.creationTime-E.creationTime||E.id.localeCompare(_.id)),b.slice(0,d).map(E=>({document:E.doc,score:E.score}))},yn=(i,o)=>{const t=i,d={near:(f,p)=>{if(t.within)throw new y("INTERNAL",`geo index "${t.indexName}" on table "${o}": call .near() or .within(), not both`);return t.near={point:{lat:f.lat,lng:f.lng},radiusMeters:p},d},within:f=>{if(t.near)throw new y("INTERNAL",`geo index "${t.indexName}" on table "${o}": call .near() or .within(), not both`);return t.within={ne:{lat:f.ne.lat,lng:f.ne.lng},sw:{lat:f.sw.lat,lng:f.sw.lng}},d}};return d},bn=(i,o)=>{const t=i[o];if(t===null||typeof t!="object")return;const{lat:d,lng:f}=t;return typeof d=="number"&&typeof f=="number"?{lat:d,lng:f}:void 0},En=(i,o)=>{const t=bn(i,o.definition.field);if(!t)return;const d=typeof i._creationTime=="number"?i._creationTime:0;if(o.near){const f=Ft(o.near.point,t);return f<=o.near.radiusMeters?{creationTime:d,distance:f}:void 0}return Wt(t,o.within)?{creationTime:d,distance:0}:void 0},gt=(i,o,t,d)=>{if(!t.near&&!t.within)throw new y("INTERNAL",`geo index "${t.indexName}" on table "${o}": call .near(point, radius) or .within(box)`);const f=t.near?Dt(t.near.point,t.near.radiusMeters):Ot(t.within),p=kt(o,t.indexName),w=f.map(E=>n`(g.${n.identifier("__geohash__")} >= ${E} AND g.${n.identifier("__geohash__")} < ${`${E}{`})`),R=[n`(${n.join(w,n` OR `)})`];d&&R.push(d);const S=n`SELECT m.id, m._creationTime, m.${n.identifier(P)} FROM ${n.identifier(p)} g JOIN ${n.identifier(o)} m ON m.id = g.${n.identifier("__id__")} WHERE ${n.join(R,n` AND `)}`,g=B(i,S).toArray(),b=[];for(const E of g){const _=le(E),C=_?En(_,t):void 0;_&&C&&b.push({creationTime:C.creationTime,distance:C.distance,doc:_})}return b.sort((E,_)=>E.distance-_.distance||_.creationTime-E.creationTime),b},Nn=(i,o,t,d,f,p=()=>{})=>{const w=gt(i,o,t,f).map(R=>R.doc);return p(w.length),typeof d=="number"?w.slice(0,Math.max(0,Math.floor(d))):w},Sn=(i,o,t,d,f,p=()=>{})=>{const w=t.within!==void 0,R=gt(i,o,t,f).map(S=>({distanceMeters:w?null:S.distance,document:S.doc}));return p(R.length),R},Tn=(i,o,t,d,f,p=()=>{})=>{const{geo:w}=t;if(!w)throw new y("INTERNAL","runGeoTerminal called without a staged geo query");const R=t.inMemoryFilters.length>0,S=Nn(i,o,w,R?void 0:f,d,p);if(!R)return S;const g=[];for(const b of S)if(t.inMemoryFilters.every(E=>E(b))&&(g.push(b),typeof f=="number"&&g.length>=f))break;return g},_n=(i,o,t,d,f,p=()=>{})=>{const{geo:w}=t;if(!w)throw new y("INTERNAL","runGeoTerminalScored called without a staged geo query");const R=t.inMemoryFilters.length>0,S=Sn(i,o,w,R?void 0:f,d,p);if(!R)return S;const g=[];for(const b of S)t.inMemoryFilters.every(E=>E(b.document))&&g.push(b);return g},Rn=(i,o,t,d,f,p,w=()=>{})=>{const R=[];for(const E of t.sqlConditions)R.push(n`${Q(E.field)} ${n.raw(E.comparator)} ${re(E.value)}`);d&&R.push(d);let S=n`SELECT id, _creationTime, ${n.identifier(P)} FROM ${n.identifier(o)}`;R.length>0&&(S=n`${S} WHERE ${n.join(R,n` AND `)}`),S=n`${S} ORDER BY ${f}`,typeof p=="number"&&t.inMemoryFilters.length===0&&(S=n`${S} LIMIT ${n.raw(String(Math.max(0,Math.floor(p))))}`);const g=B(i,S).toArray();w(g.length);const b=[];for(const E of g){const _=le(E);if(_&&t.inMemoryFilters.every(C=>C(_))&&(b.push(_),typeof p=="number"&&b.length>=p))break}return b},oe={fieldRef:Q,serialize:re},An=i=>{let o=0;const t=[],d={fieldRef:Q,relationExists:f=>{const{childWhere:p,negated:w,parentTable:R,relation:S}=f,g=`__rel_${String(o)}`,b=t.at(-1)??R;o+=1,i(S.table,q);const E=S.kind==="one"?S.field:S.references,_=S.kind==="one"?S.references:S.field,C=n`${Ze(g,_)} = ${Ze(b,E)}`;t.push(g);const D=ne(p,d);t.pop();const M=D?n`${C} AND ${D}`:C,k=n`EXISTS (SELECT 1 FROM ${n.identifier(S.table)} AS ${n.identifier(g)} WHERE ${M})`;return w?n`NOT ${k}`:k},serialize:re};return d},$t=i=>{const o=i.map(t=>n`${Q(t.field)} ${n.raw(t.direction==="desc"?"DESC":"ASC")}`);return i.some(t=>t.field==="_id"||t.field==="id")||o.push(n`${Q("id")} ASC`),n.join(o,n`, `)},vn={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},In=i=>{const o=i.order;return i.indexFields.length>0?i.indexFields.map(t=>({direction:o,field:t})):[{direction:o,field:"_creationTime"}]},xn=(i,o,t,d)=>{const f=i.sqlConditions.map(p=>({[p.field]:{[vn[p.comparator]??"eq"]:p.value}}));if(t&&f.push(mt(o,Fe(t))),d&&f.push(Ut(o,Fe(d))),f.length!==0)return f.length===1?f[0]:{AND:f}},Cn=(i,o,t)=>{const d=[];for(const f of i){const p=le(f);if(p&&o.every(w=>w(p))&&(d.push(p),t!==void 0&&d.length>t))break}return d},Mn=(i,o,t,d,f,p=()=>{})=>{const w=Math.max(0,Math.floor(d.numItems)),R=In(t),S=typeof d.endCursor=="string",g=ne(xn(t,R,d.cursor,d.endCursor),oe),b=f&&g?n`${g} AND ${f}`:f??g;let E=n`SELECT id, _creationTime, ${n.identifier(P)} FROM ${n.identifier(o)}`;b&&(E=n`${E} WHERE ${b}`),E=n`${E} ORDER BY ${$t(R)}`;const _=t.inMemoryFilters.length>0;!_&&!S&&(E=n`${E} LIMIT ${n.raw(String(w+1))}`);const C=B(i,E).toArray();p(C.length);const D=Cn(C,t.inMemoryFilters,_||S?void 0:w);if(S){const U=D.length>=2?D[Math.floor(D.length/2)-1]:void 0;return{continueCursor:d.endCursor??null,isDone:!0,page:D,splitCursor:U?qe(U,R):null}}const M=D.length>w,k=M?D.slice(0,w):D,H=k.at(-1);return{continueCursor:M&&H?qe(H,R):null,isDone:!M,page:k}};class Ln extends y{constructor(o="unique() found more than one matching document"){super("NOT_UNIQUE",o,{name:"NotUniqueError"})}}const kn=/\s/u,Dn=String.fromCodePoint(0),dt=(i,o,t)=>{if(!i.tables[o])throw new y("INTERNAL",`unknown table: ${o}`);return typeof t!="string"||t.length===0||kn.test(t)||t.includes(Dn)?null:t},On=(i,o,t,d=()=>{},f=()=>{},p=()=>{})=>{const w=o.tables[t];if(!w)throw new y("INTERNAL",`unknown table: ${t}`);const R=de(w.softDeleteMode,void 0),S=R?ne(R,oe):void 0,g={indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[]};let b=0;const E=N=>{const{search:x}=g;if(!x)throw new y("INTERNAL","runSearchFetch called without a staged search");It(i,t,w);const I=g.inMemoryFilters.length>0,L=un(I?void 0:N),j=Lt(i)?gn(i,t,x,L,S):$n(i,t,x,L,S);if(!I)return N===void 0&&on(j),j;const X=[];b=j.length;for(const ce of j)if(g.inMemoryFilters.every(ue=>ue(ce.document))&&(X.push(ce),typeof N=="number"&&X.length>=N))break;return X},_=N=>E(N).map(x=>x.document),C=N=>{const x=ln(N);return cn(_(an(x)),x)},D=()=>{const N=g.indexFields.length>0?g.indexFields:["_creationTime"],x=g.order==="desc"?"DESC":"ASC";return n.join(N.map(I=>n`${Q(I)} ${n.raw(x)}`),n`, `)},M=()=>{if(g.search||g.geo||g.indexName===void 0){f(void 0);return}f(Kt(t,g.indexName,g.indexFields,g.sqlConditions,re))},k=N=>{M();let x=0;const I=(()=>{if(g.search){const L=_(N);return x=b,L}return g.geo?Tn(i,t,g,S,N,L=>{x=L}):Rn(i,t,g,S,D(),N,L=>{x=L})})();return p(Math.max(x,I.length)),I},H=()=>{if(!g.search&&!g.geo)throw new y("INTERNAL",`ctx.db.query("${t}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);M();let N=0;const x=(()=>{if(g.search){const I=E(void 0);return N=b,I}return _n(i,t,g,S,void 0,I=>{N=I})})();return p(Math.max(N,x.length)),x},U={async*[Symbol.asyncIterator](){const N=[...g.inMemoryFilters];let x;g.inMemoryFilters=[];try{for(;;){const I=await U.paginate({cursor:x??null,numItems:pn});for(const L of I.page)N.every(j=>j(L))&&(yield L);if(I.isDone||I.continueCursor===null)return;x=I.continueCursor}}finally{g.inMemoryFilters=N}},async collect(){return k(void 0)},async collectWithScores(){return H()},filter(N){return g.inMemoryFilters.push(N),U},async first(){return k(g.inMemoryFilters.length>0?void 0:1)[0]??null},order(N){return g.order=N==="desc"?"desc":"asc",U},async paginate(N){let x=0;if(M(),g.search){const L=C(N);return p(L.page.length),L}if(g.geo)throw new y("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const I=Mn(i,t,g,N,S,L=>{x=L});return p(Math.max(x,I.page.length)),I},async take(N){return k(N)},async unique(){const N=k(g.inMemoryFilters.length>0?void 0:2);if(N.length>1)throw new Ln(`unique() on table "${t}" matched ${String(N.length)} documents; expected at most one`);return N[0]??null},withGeoIndex(N,x){const I=(w.geoIndexes??[]).find(j=>j.name===N);if(!I)throw new y("INTERNAL",`unknown geo index "${N}" on table "${t}"`);d(t,N,"geo");const L={definition:I,indexName:N};if(g.geo=L,x(yn(L,t)),!L.near&&!L.within)throw new y("INTERNAL",`geo index "${N}" on table "${t}" requires a .near(point, radius) or .within(box) call`);return U},withIndex(N,x){const I=w.indexes.find(L=>L.name===N);if(!I)throw new y("INTERNAL",`unknown index "${N}" on table "${t}"`);return d(t,N,"index"),g.indexName=N,g.indexFields=I.fields,x&&x(mn(g)),U},withSearchIndex(N,x){const I=(w.searchIndexes??[]).find(j=>j.name===N);if(!I)throw new y("INTERNAL",`unknown search index "${N}" on table "${t}"`);d(t,N,"search");const L={definition:I,field:I.field,filters:[],hasQuery:!1,indexName:N,query:""};if(g.search=L,x(rn(L,t,Ue(I.language))),!L.hasQuery)throw new y("INTERNAL",`search index "${N}" on table "${t}" requires a .search(field, query) call`);return U}};return U},lt=(i,o,t)=>{const d={...o};for(const[f,p]of ht(i)){if(p.serverDefault){d[f]=p.serverDefault({auth:t});continue}d[f]===void 0&&(p.defaultFn?d[f]=p.defaultFn():"defaultValue"in p&&(d[f]=p.defaultValue))}return d},ct=(i,o,t,d)=>{const f=t;for(const[p,w]of ht(i)){if(w.serverDefault){p in o&&(f[p]=w.serverDefault({auth:d}));continue}w.onUpdateFn&&!(p in o)&&(f[p]=w.onUpdateFn())}},ut=(i,o)=>{for(const t of Object.keys(o))if(o[t]===void 0)throw new y("INTERNAL",`Cannot ${i} field '${t}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},Wn=/unique constraint failed/i,Fn=i=>i instanceof Error&&Wn.test(i.message),Be=(i,o,t)=>{try{B(i,t)}catch(d){throw Fn(d)?new we(`unique constraint violation on "${o}"`,"unique"):d}},Ae=(i,o,t)=>{if(Be(i,o,t),B(i,n`SELECT changes() AS changed`).one().changed===0)throw new we(`optimistic concurrency conflict on "${o}" — the row changed during this mutation; refetch and retry`,"occ")},ft=(i,o,t,d,f,p,w)=>{const R=[];for(let E=0;E<t.length+1;E+=1){const _=[];for(let k=0;k<E;k+=1)_.push(n`${n.identifier(t[k])} IS ${p[k]}`);const C=t[E],D=d[E];if(C!==void 0&&D!==void 0){const k=D.direction==="desc"?">":"<";_.push(n`${n.identifier(C)} ${n.raw(k)} ${p[E]}`)}else _.push(n`${n.identifier(jt)} < ${w}`);const[M]=_;R.push(_.length===1&&M!==void 0?M:n`(${n.join(_,n` AND `)})`)}const S=n.join(R,n` OR `),g=B(i,n`SELECT COUNT(*) AS c FROM ${n.identifier(o)} WHERE ${n.identifier("__partition__")} = ${f} AND (${S})`).one(),b=B(i,n`SELECT COUNT(*) AS c FROM ${n.identifier(o)} WHERE ${n.identifier("__partition__")} = ${f}`).one();return{before:g.c,total:b.c}},ur=i=>{const{sql:o}=i,{schema:t}=i,d=i.broadcast??(()=>{}),f=(e,...r)=>{const a=t.tables[e]?.indexes;if(!a||a.length===0)return;const h=[];for(const u of r)u&&h.push(...Gt(a,u,re));return h.length>0?h:void 0},{headroom:p}=i;let w=!1;const R=async e=>{const r=w;w=!0;try{return await e()}finally{w=r}},S=i.onRead??(()=>{}),g=i.onReadRange??(e=>{S(e.table,q)}),b=(e,r)=>{r!==void 0&&r!==q&&!w&&p?.recordRead(1),S(e,r)},E=i.onIndexUse??(()=>{}),_=i.onWrite??(()=>{}),C=async e=>{w||p?.recordWrite(e.doc),await _(e)},{cache:D}=i,M=i.clock??(()=>Date.now()),k=i.idGenerator??(()=>crypto.randomUUID()),H=i.scheduler??_t,{globalDb:U}=i,N=i.auth??{identity:null,userId:null},x=i.cdc??!1,I=H,L=Vt({scheduler:typeof I.list=="function"&&typeof I.get=="function"?I:void 0,storage:i.storage}),j=(e,r,a,h)=>{x&&xt(o,M(),e,r,a,h)},X=e=>t.tables[e]?.shardMode?.kind==="global",ce=(e,r)=>{if(X(e)){if(!U)throw new y("INTERNAL",`cross-backend ${r} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return U}return F},ue=e=>ce(e,"cascade"),z=(e,r)=>{if(X(e)){if(!U)throw new y("INTERNAL",`${r} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return U}},fe=()=>U,ve=(e,r)=>ce(e,"relation load").findMany(e,r),He=(e,r)=>(X(e)&&b(e,q),ve(e,r)),yt=e=>!X(e.table),je=i.relationExistsPushDown??"auto",Ge=je!=="never",{maxRelationKeys:Ke}=i,ge=(e,r,a)=>rt(e,{fetcher:He,maxRelationKeys:Ke,relationBaseWhere:a,schema:t,tableName:r}),Je=async(e,r,a,h)=>{const u=z(e,"relation grouped count");if(u)return b(e,q),Qt((v,K)=>u.count(v,K),e,r,a,h);const l=t.tables[e];if(!l)throw new y("INTERNAL",`unknown table: ${e}`);b(e,q);const s=de(l.softDeleteMode,void 0),c={[r]:{in:a}},m=J(J(c,h),s),T=await ge(m,e,void 0),$=ne(T,oe),A=Q(r);let W=n`SELECT ${A} AS __fk__, COUNT(*) AS count FROM ${n.identifier(e)}`;$&&(W=n`${W} WHERE ${$}`),W=n`${W} GROUP BY ${A}`;const O=B(o,W).toArray();return new Map(O.map(v=>[v.__fk__,v.count]))};let $e=0;const Qe=new Set;for(const[e,r]of Object.entries(t.tables))for(const a of Object.values(r.triggerMap??{}))Qe.add(`${e} ${a.timing} ${a.op}`);const ee=(e,r,a)=>Qe.has(`${e} ${r} ${a}`),te=async(e,r,a)=>{if($e+=1,$e>st)throw $e-=1,new we(`trigger recursion exceeded ${String(st)} levels on "${a.table}" — check for a self-triggering write`,"trigger");try{await Yt({ctx:bt,event:a,op:r,schema:t,tableName:a.table,timing:e})}finally{$e-=1}},{ensureBackfilledForTable:he,ensureBackfilledIndex:Ie,ensureRankBackfilled:xe,ensureRankBackfilledForTable:pe,syncAggregates:ye,syncCompanionsForInsert:ze,syncGeo:be,syncRanks:me,syncSearch:Ee}=Ct({broadcast:d,indexKeysFor:(e,r)=>f(e,r),invalidateCache:(e,r,a)=>D?.invalidate(e,r,f(e,a)),recordCdc:j,schema:t,sql:o}),Ve=(e,r,a)=>{const{shardMode:h}=r;if(h?.kind==="shardBy"&&!(h.field!==void 0&&(a.partitionBy??[]).includes(h.field)))throw Object.assign(new Error(`rank index "${a.name}" on "${e}" partitions across shards (shard key "${h.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})},ie=(e,r)=>{const a=Object.entries(t.tables).filter(([,T])=>T.shardMode?.kind!=="global").map(([T])=>T).filter(T=>r===void 0||T===r);if(a.length===0)return;const h=a.map(T=>n`SELECT ${n.raw(`'${T.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${n.identifier(P)} FROM ${n.identifier(T)} WHERE id = ${e}`),u=n`${n.join(h,n` UNION ALL `)} LIMIT 1`,[l]=B(o,u).toArray();if(!l)return;const s=l.__t__,c=le(l);if(typeof s!="string"||!c)return;const m=l[P];return{docJson:typeof m=="string"?m:JSON.stringify(m??{}),row:c,tableName:s}},Ye={assertRankPartitionLocal:Ve,ensureRankBackfilled:xe,onRead:b,rowToDocument:le,schema:t,sql:o},F={system:L,async aggregate(e,r){const a=z(e,"aggregate");if(a)return b(e,q),a.aggregate(e,r);const h=t.tables[e];if(!h)throw new y("INTERNAL",`unknown table: ${e}`);if(Te(r.op),r.op==="count")return F.count(e,{baseWhere:r.baseWhere,relationBaseWhere:r.relationBaseWhere,restrictsCounts:r.restrictsCounts,where:r.where});if(!r.field)throw new y("INTERNAL",`aggregate(${e}, { op: "${r.op}" }): "field" is required for non-count reducers`);b(e,q);const u=de(h.softDeleteMode,void 0),l=J(J(r.baseWhere,r.where),u),s=await ge(l,e,r.relationBaseWhere),c=s!==l;if(h.aggregateIndexes&&!r.baseWhere&&!c&&!u){const O=vt(h.aggregateIndexes,r.op,r.field,r.where);if(O){Ie(e,O.index);const v=Ce(O.index.by??[],O.key),K=Le(e,O.index.name),V=B(o,n`SELECT ${_e} AS value, ${De} AS count FROM ${n.identifier(K)} WHERE ${Re} = ${v}`).toArray()[0];return Me(r.op,V)}}const m=ne(s,oe),T=Te(r.op),$=Q(r.field);let A=n`SELECT ${n.raw(T)}(${$}) AS value FROM ${n.identifier(e)}`;return m&&(A=n`${A} WHERE ${m}`),B(o,A).toArray()[0]?.value??null},asId(e,r){const a=dt(t,e,r);if(a===null)throw new y("BAD_REQUEST",`asId("${e}", …): "${r}" is not a valid id for table "${e}"`,{status:400});return a},async count(e,r){const a=z(e,"count");if(a)return b(e,q),a.count(e,r);const h=t.tables[e];if(!h)throw new y("INTERNAL",`unknown table: ${e}`);const u=Tt(r);if(u.restrictsCounts)throw new ke(e);b(e,q);const l=de(h.softDeleteMode,void 0),s=J(J(u.baseWhere,u.where),l),c=await ge(s,e,u.relationBaseWhere),m=c!==s;if(h.aggregateIndexes&&!u.baseWhere&&!m&&!l){const A=At(h.aggregateIndexes,u.where);if(A){Ie(e,A.index);const W=Ce(A.index.by??[],A.key),O=Le(e,A.index.name),v=B(o,n`SELECT ${_e} AS value FROM ${n.identifier(O)} WHERE ${Re} = ${W}`).toArray();return v[0]===void 0?0:v[0].value??0}}const T=ne(c,oe);let $=n`SELECT COUNT(*) AS count FROM ${n.identifier(e)}`;return T&&($=n`${$} WHERE ${T}`),B(o,$).one().count},async delete(e,r,a){const h=ie(e,r);if(!h){const $=r===void 0?fe():void 0;$&&await $.delete(e,void 0,a);return}const{docJson:u,row:l,tableName:s}=h,c=t.tables[s],m=a?.hard===!0,T=!m&&c?.softDeleteMode?c.softDeleteMode.field:void 0;if(!(T&&l[T]!==null&&l[T]!==void 0)){if(ee(s,"before","delete")&&await te("before","delete",{id:e,op:"delete",previous:l,table:s}),await Jt({deletedId:e,deletedReference:$=>l[$],findHolders:async($,A,W)=>(await ue($).findMany($,{includeDeleted:m,where:{[A]:W}})).page,onCascade:($,A)=>ue($).delete(A,void 0,a),onRestrict:$=>{throw new we($,"restrict")},onSetNull:($,A,W)=>ue($).patch(A,{[W]:null}),schema:t,tableName:s}),he(s),pe(s),T){const $={...l,[T]:M(),_id:e};Ae(o,s,n`UPDATE ${n.identifier(s)} SET ${n.identifier(P)} = ${JSON.stringify($)} WHERE id = ${e} AND ${n.identifier(P)} = ${u}`),Ee(s,e,$,l),be(s,e,void 0),ye(s,l,$),me(s,e,l,void 0),D?.invalidate(s,e,f(s,l,$)),j(s,e,"update",$),d({indexKeys:f(s,l,$),key:e,op:"update",row:$,table:s}),ee(s,"after","delete")&&await te("after","delete",{id:e,op:"delete",previous:l,table:s}),await C({id:e,op:"delete",table:s});return}Ae(o,s,n`DELETE FROM ${n.identifier(s)} WHERE id = ${e} AND ${n.identifier(P)} = ${u}`),Ee(s,e,void 0),be(s,e,void 0),ye(s,l,void 0),me(s,e,l,void 0),D?.invalidate(s,e,f(s,l)),j(s,e,"delete"),d({indexKeys:f(s,l),key:e,op:"delete",table:s}),ee(s,"after","delete")&&await te("after","delete",{id:e,op:"delete",previous:l,table:s}),await C({id:e,op:"delete",table:s})}},async deleteAll(e,r){if(!t.tables[e])throw new y("INTERNAL",`unknown table: ${e}`);const a=Math.max(1,r?.chunkSize??wt),h=r?.hard===void 0?void 0:{hard:r.hard},u=X(e)?void 0:e;let l=0;return await R(async()=>{for(;;){const s=(await F.findMany(e,{limit:a})).page.map(c=>String(c._id));if(s.length===0)break;for(const c of s)await F.delete(c,u,h),l+=1;if(s.length<a)break}}),{deleted:l}},async deleteMany(e,r,a){se(e.length,r?.limit,"deleteMany");for(const h of e)await F.delete(h,a);return{deleted:e.length}},async deleteWhere(e,r,a){const h=z(e,"deleteWhere");let u;if(h)u=(await h.findMany(e,{where:r})).page.map(l=>String(l._id));else{if(!t.tables[e])throw new y("INTERNAL",`unknown table: ${e}`);u=(await F.findMany(e,{where:r})).page.map(l=>String(l._id))}if(se(u.length,a?.limit,"deleteWhere"),F.deleteMany===void 0)throw new y("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return F.deleteMany(u,a)},async findFirst(e,r={}){return(await F.findMany(e,{...r,limit:1})).page[0]??null},async findFirstOrThrow(e,r={}){const a=await F.findFirst(e,r);if(a===null)throw new qt(`findFirstOrThrow: no "${e}" document matched`);return a},async findMany(e,r={}){const a=z(e,"findMany");if(a)return b(e,q),a.findMany(e,r);const h=t.tables[e];if(!h)throw new y("INTERNAL",`unknown table: ${e}`);const u=!r.where&&!r.baseWhere;u?b(e,q):b(e);const l=Bt(r.orderBy),s=r.cursor?mt(l,Fe(r.cursor)):void 0;let c=J(r.baseWhere,r.where);c=J(c,de(h.softDeleteMode,r.includeDeleted)),c=await rt(c,{canPushExists:Ge?yt:void 0,existsPushMode:je==="always"?"always":"auto",fetcher:He,maxRelationKeys:Ke,relationBaseWhere:r.relationBaseWhere,schema:t,tableName:e}),s&&(c=c?{AND:[c,s]}:s);const m=Ge?An(b):oe,T=ne(c,m);let $=n`SELECT id, _creationTime, ${n.identifier(P)} FROM ${n.identifier(e)}`;T&&($=n`${$} WHERE ${T}`),$=n`${$} ORDER BY ${$t(l)}`;const A=typeof r.limit=="number"?Math.max(0,Math.floor(r.limit)):void 0;A!==void 0&&($=n`${$} LIMIT ${n.raw(String(A+1))}`);const W=B(o,$).toArray();u&&!w&&p?.recordRead(W.length);const O=[];for(const Y of W){const G=le(Y);G&&(O.push(G),!u&&typeof G._id=="string"&&b(e,G._id))}if(A===void 0)return r.with&&await it({groupedCounter:Je,fetcher:ve,parents:O,relationBaseWhere:r.relationBaseWhere,schema:t,tableName:e,with:r.with}),{continueCursor:null,isDone:!0,page:et(O,r.select,r.with)};const v=O.length>A,K=v?O.slice(0,A):O,V=K.at(-1);return r.with&&await it({fetcher:ve,groupedCounter:Je,parents:K,relationBaseWhere:r.relationBaseWhere,schema:t,tableName:e,with:r.with}),{continueCursor:v&&V?qe(V,l):null,isDone:!v,page:et(K,r.select,r.with)}},async get(e,r){const a=ie(e,r);if(!a){const h=r===void 0?fe():void 0;return h?h.get(e):null}return b(a.tableName,e),a.row},async lookupById(e,r){const a=ie(e,r);return a?(b(a.tableName,e),{row:a.row,tableName:a.tableName}):null},async groupBy(e,r){const a=z(e,"groupBy");if(a)return b(e,q),a.groupBy(e,r);const h=t.tables[e];if(!h)throw new y("INTERNAL",`unknown table: ${e}`);b(e,q);const u=r.agg??{op:"count"};if(Te(u.op),u.op!=="count"&&!u.field)throw new y("INTERNAL",`groupBy(${e}, { agg: { op: "${u.op}" } }): "field" is required for non-count reducers`);const l=de(h.softDeleteMode,void 0),s=J(J(r.baseWhere,r.where),l),c=await ge(s,e,r.relationBaseWhere),m=c!==s;if(h.aggregateIndexes&&!r.baseWhere&&!m&&!l){const v=Rt(h.aggregateIndexes,u.op,u.field,r.by,r.where);if(v){Ie(e,v.index);const K=Le(e,v.index.name),V=Object.keys(v.partial),Y=[];if(V.length===(v.index.by??[]).length&&V.length>0){const ae=Ce(v.index.by??[],v.partial),Ne=B(o,n`SELECT ${_e} AS value, ${De} AS count FROM ${n.identifier(K)} WHERE ${Re} = ${ae}`).toArray();return Ne.length>0&&Y.push({key:{...v.partial},value:Me(u.op,Ne[0])}),Y}const G=B(o,n`SELECT ${Re} AS key, ${_e} AS value, ${De} AS count FROM ${n.identifier(K)}`).toArray();for(const ae of G){const Ne=JSON.parse(ae.key);Y.push({key:Ne,value:Me(u.op,ae)})}return Y}}const T=ne(c,oe),$=r.by.map(v=>n`${Q(v)} AS ${n.identifier(v)}`);if(u.op==="count")$.push(n`COUNT(*) AS value`);else{const{field:v}=u;if(v===void 0)throw new y("INTERNAL",`groupBy(${e}, { agg: { op: "${u.op}" } }): "field" is required for non-count reducers`);$.push(n`${n.raw(Te(u.op))}(${Q(v)}) AS value`)}let A=n`SELECT ${n.join($,n`, `)} FROM ${n.identifier(e)}`;T&&(A=n`${A} WHERE ${T}`),A=n`${A} GROUP BY ${n.join(r.by.map(v=>Q(v)),n`, `)}`;const W=B(o,A).toArray(),O=[];for(const v of W){const K={};for(const Y of r.by)K[Y]=v[Y]??null;const{value:V}=v;O.push({key:K,value:V==null?null:Number(V)})}return O},async insert(e,r,a){const h=z(e,"insert");if(h){const T=await h.insert(e,r,a);return w||p?.recordWrite(r),d({key:T,op:"insert",row:{...r,_id:T},table:e}),T}const u=t.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);const l=lt(u,r,N);We(u,l);let s;a?.clientId!==void 0?(hn(a.clientId),s=a.clientId):a?.allowExplicitId&&typeof l._id=="string"?s=l._id:s=k();const c=a?.allowExplicitId&&typeof l._creationTime=="number"?l._creationTime:M(),m={...l,_creationTime:c,_id:s};return ee(e,"before","insert")&&await te("before","insert",{doc:{...m},id:s,op:"insert",table:e}),he(e),pe(e),Be(o,e,n`INSERT INTO ${n.identifier(e)} (id, _creationTime, ${n.identifier(P)}) VALUES (${s}, ${c}, ${JSON.stringify(m)})`),ze(e,s,m),ee(e,"after","insert")&&await te("after","insert",{doc:m,id:s,op:"insert",table:e}),await C({doc:m,id:s,op:"insert",table:e}),s},async insertManyUnsafe(e,r,a){if(se(r.length,a?.limit,"insertManyUnsafe"),r.length===0)return[];const h=z(e,"insert");if(h){const c=[];for(const m of r){const T=await h.insert(e,m,{allowExplicitId:a?.allowExplicitId});w||p?.recordWrite(m),d({key:T,op:"insert",row:{...m,_id:T},table:e}),c.push(T)}return c}const u=t.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);he(e),pe(e);const l=r.map(c=>{const m=lt(u,c,N),T=a?.allowExplicitId===!0&&typeof m._id=="string"?m._id:k(),$=a?.allowExplicitId===!0&&typeof m._creationTime=="number"?m._creationTime:M();return{creationTime:$,document:{...m,_creationTime:$,_id:T},id:T}});if(!w)for(const c of l)p?.recordWrite(c.document);const s=n.join(l.map(c=>n`(${c.id}, ${c.creationTime}, ${JSON.stringify(c.document)})`),n`, `);Be(o,e,n`INSERT INTO ${n.identifier(e)} (id, _creationTime, ${n.identifier(P)}) VALUES ${s}`);for(const{document:c,id:m}of l)ze(e,m,c),await _({doc:c,id:m,op:"insert",table:e});return l.map(c=>c.id)},async insertMany(e,r,a){se(r.length,a?.limit,"insertMany");const h=a?.skipDuplicates===!0,u=[];for(const l of r)try{u.push(await F.insert(e,l))}catch(s){if(h&&s instanceof we&&s.kind==="unique")u.push(null);else throw s}return u},normalizeId(e,r){return dt(t,e,r)},async patch(e,r,a){const h=ie(e,a);if(!h){const T=a===void 0?fe():void 0;if(T){await T.patch(e,r);return}throw new y("INTERNAL",`document not found: ${e}`)}const{docJson:u,row:l,tableName:s}=h,c=t.tables[s];if(!c)throw new y("INTERNAL",`unknown table: ${s}`);b(s,e),ut("patch",r);const m={...l,...r,_id:e};ct(c,r,m,N),We(c,m,!0),ee(s,"before","update")&&await te("before","update",{doc:{...m},id:e,op:"update",previous:l,table:s}),he(s),pe(s),Ae(o,s,n`UPDATE ${n.identifier(s)} SET ${n.identifier(P)} = ${JSON.stringify(m)} WHERE id = ${e} AND ${n.identifier(P)} = ${u}`),Ee(s,e,m,l),be(s,e,m),ye(s,l,m),me(s,e,l,m),D?.invalidate(s,e,f(s,l,m)),j(s,e,"update",m),d({indexKeys:f(s,l,m),key:e,op:"update",row:m,table:s}),ee(s,"after","update")&&await te("after","update",{doc:m,id:e,op:"update",previous:l,table:s}),await C({doc:m,id:e,op:"update",table:s})},async patchMany(e,r,a){se(e.length,r?.limit,"patchMany");for(const h of e)await F.patch(h.id,h.patch,a);return{patched:e.length}},async patchWhere(e,r,a){const h=z(e,"patchWhere");let u;if(h)u=(await h.findMany(e,{where:r.where})).page.map(l=>({id:String(l._id),patch:r.patch}));else{if(!t.tables[e])throw new y("INTERNAL",`unknown table: ${e}`);u=(await F.findMany(e,{where:r.where})).page.map(l=>({id:String(l._id),patch:r.patch}))}if(se(u.length,a?.limit,"patchWhere"),F.patchMany===void 0)throw new y("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await F.patchMany(u,a),{patched:u.length}},query(e){const r=z(e,"query");return r?(b(e,q),r.query(e)):On(o,t,e,E,a=>{a?g(a):b(e,q)},a=>{w||p?.recordRead(a)})},async rank(e,r,a){const h=z(e,"rank");if(h)return b(e,q),h.rank(e,r,a);E(e,r,"rank");const u=t.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);const l=u.rankIndexes?.find(G=>G.name===r);if(!l)throw new y("INTERNAL",`unknown rankIndex "${r}" on table "${e}"`);if(Ve(e,u,l),a.restrictsCounts)throw new ke(e);b(e,q),xe(e,l);const s=typeof a.row=="string"?a.row:a.row._id;if(!s)return null;const c=nt(e,l.name),m=l.sortBy.map((G,ae)=>tt(ae)),T=m.map(G=>Mt(G)).join(", "),$=B(o,n`SELECT ${n.identifier("__partition__")}, ${n.raw(T)} FROM ${n.identifier(c)} WHERE ${n.identifier("__id__")} = ${s}`).toArray(),[A]=$;if(A===void 0)return null;let W=A.__partition__;const O=J(a.baseWhere,a.where);Oe(O,t,e,"rank");const v=Pt(l,O);if(v){const G=Ht(l.partitionBy??[],v);if(G!==W)return null;W=G}const K=m.map(G=>A[G]),{before:V,total:Y}=ft(o,c,m,l.sortBy,W,K,s);return{position:V+1,total:Y}},async rankBefore(e,r,a){if(X(e))throw new y("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const h=t.tables[e];if(!h)throw new y("INTERNAL",`unknown table: ${e}`);const u=h.rankIndexes?.find(m=>m.name===r);if(!u)throw new y("INTERNAL",`unknown rankIndex "${r}" on table "${e}"`);if(a.restrictsCounts)throw new ke(e);b(e,q),xe(e,u);const l=nt(e,u.name),s=u.sortBy.map((m,T)=>tt(T)),c=u.sortBy.map((m,T)=>re(a.sortValues[T]??null));return ft(o,l,s,u.sortBy,a.partitionKey,c,a.rowId)},async rankPage(e,r,a={}){Oe(J(a.baseWhere,a.where),t,e,"rankPage");const h=z(e,"rankPage");if(h)return b(e,q),h.rankPage(e,r,a);E(e,r,"rank");const{continueCursor:u,hasMore:l,rows:s}=Xe(Ye,e,r,a);return{continueCursor:u,isDone:!l,page:s.map(c=>c.doc)}},async rankPageRows(e,r,a={}){Oe(J(a.baseWhere,a.where),t,e,"rankPage"),E(e,r,"rank");const{directions:h,hasMore:u,rows:l}=Xe(Ye,e,r,a);return{directions:h,hasMore:u,rows:l}},async restore(e,r){const a=ie(e,r);if(!a){const l=r===void 0?fe():void 0;if(l?.restore){await l.restore(e);return}throw new y("INTERNAL",`document not found: ${e}`)}const h=t.tables[a.tableName]?.softDeleteMode?.field;if(!h)throw new y("INTERNAL",`ctx.db.restore: table "${a.tableName}" is not a .softDelete() table`);const u=a.row[h]!==null&&a.row[h]!==void 0;await F.patch(e,{[h]:null},r),u&&me(a.tableName,e,void 0,a.row)},async replace(e,r,a,h){const u=ie(e,a);if(!u){const A=a===void 0?fe():void 0;if(A){await A.replace(e,r,void 0,h);return}throw new y("INTERNAL",`document not found: ${e}`)}const{docJson:l,row:s,tableName:c}=u,m=t.tables[c];if(!m)throw new y("INTERNAL",`unknown table: ${c}`);ut("replace",r);const T=h?.allowExplicitId&&typeof r._creationTime=="number"?r._creationTime:M(),$={...r,_creationTime:T,_id:e};ct(m,r,$,N),We(m,$),ee(c,"before","update")&&await te("before","update",{doc:{...$},id:e,op:"update",previous:s,table:c}),he(c),pe(c),Ae(o,c,n`UPDATE ${n.identifier(c)} SET _creationTime = ${T}, ${n.identifier(P)} = ${JSON.stringify($)} WHERE id = ${e} AND ${n.identifier(P)} = ${l}`),Ee(c,e,$,s),be(c,e,$),ye(c,s,$),me(c,e,s,$),D?.invalidate(c,e,f(c,s,$)),j(c,e,"update",$),d({indexKeys:f(c,s,$),key:e,op:"update",row:$,table:c}),ee(c,"after","update")&&await te("after","update",{doc:$,id:e,op:"update",previous:s,table:c}),await C({doc:$,id:e,op:"update",table:c})},async wipeShard(e){const r=new Set(e?.exclude),a=e?.tables,h=Object.entries(t.tables).filter(([c,m])=>r.has(c)||a!==void 0&&!a.includes(c)?!1:m.shardMode?.kind!=="global").map(([c])=>c);if(a!==void 0){for(const c of a)if(!t.tables[c])throw new y("INTERNAL",`wipeShard: unknown table: ${c}`)}const u={};let l=0;const{deleteAll:s}=F;if(s===void 0)throw new y("INTERNAL","wipeShard: this writer has no deleteAll");for(const c of h){const m=await s(c,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});u[c]=m.deleted,l+=m.deleted}return{deleted:l,tables:u}}},bt={db:F,scheduler:H};return i.enforceRls===!0?zt(F,t,(e,r)=>ie(e,r)?.tableName):F};export{$r as CDC_LOG_TABLE,Ar as CLIENT_WATERMARK_TABLE,Mr as GLOBAL_SHAPE_SNAPSHOT_TABLE,qr as IDEMPOTENCY_TABLE,Ln as NotUniqueError,Kr as SEARCH_STATE_TABLE,vr as advanceClientWatermark,yr as applyCdcChanges,hn as assertValidClientId,pr as backfillAggregateIndexes,mr as backfillRankIndexes,wr as backfillSearchIndexes,br as bumpCdcEpoch,ur as createShardCtxDb,Lr as deleteGlobalShapeSnapshot,kr as deleteGlobalShapeSnapshotsForConnection,Ir as migrateClientWatermark,Dr as migrateGlobalShapeSnapshot,Er as minCdcSeq,dt as normalizeIdStructurally,Nr as readCdcChanges,Sr as readCdcCursor,Tr as readCdcEpoch,xr as readClientWatermark,Or as readGlobalShapeSnapshot,Br as readIdempotent,jr as runShardMigrations,Qr as selectShapeMemberIds,zr as selectShapeRows,_r as trimCdcChanges,Ur as trimIdempotent,Wr as writeGlobalShapeSnapshot,Pr as writeIdempotent};
@@ -1 +0,0 @@
1
- import{LunoraError as p}from"@lunora/errors";const y=Symbol.for("lunora.ctxdb.rls-unwrap");class f extends p{table;constructor(i){super("RLS_REQUIRED",`ctx.db access to "${i}" is denied: the schema is marked .rls("required"), so this table is protected. Apply RLS with .use(rls(policies)) in the procedure, or mark the table .public() to opt it out.`,{name:"RlsRequiredError"}),this.table=i}}const w=n=>Object.entries(n.tables).filter(([,i])=>i.shardMode?.kind!=="global").map(([i])=>i),g=(n,i,c)=>{const t=i?.tables,d=new Set(i?.exclude);for(const s of n)(t===void 0||t.includes(s))&&!d.has(s)&&c(s)},b=(n,i,c)=>{const t={},{deleteAll:d,wipeShard:s}=n;return d&&(t.deleteAll=(o,u)=>(c(o),d(o,u))),s&&(t.wipeShard=o=>(g(w(i),o,c),s(o))),t},k=(n,i,c)=>{if(i.rlsMode!=="required")return n;const t=n,d=e=>{const r=i.tables[e];return r!==void 0&&r.isPublic!==!0},s=e=>{if(d(e))throw new f(e)},o=async(e,r)=>{if(r!==void 0){s(r);return}const a=await c(e);a!==void 0&&s(a)},u=t.rankBefore,h={...n,...b(t,i,s),[y]:n,aggregate:(e,r)=>(s(e),t.aggregate(e,r)),count:(e,r)=>(s(e),t.count(e,r)),delete:async(e,r,a)=>(await o(e,r),t.delete(e,r,a)),deleteMany:async(e,r,a)=>{for(const l of e)await o(l,a);return t.deleteMany(e,r,a)},deleteWhere:t.deleteWhere?async(e,r,a)=>(s(e),await t.deleteWhere?.(e,r,a)):void 0,findFirst:(e,r)=>(s(e),t.findFirst(e,r)),findFirstOrThrow:(e,r)=>(s(e),t.findFirstOrThrow(e,r)),findMany:(e,r)=>(s(e),t.findMany(e,r)),get:async(e,r)=>(await o(e,r),t.get(e,r)),groupBy:(e,r)=>(s(e),t.groupBy(e,r)),insert:(e,r,a)=>(s(e),t.insert(e,r,a)),insertMany:(e,r,a)=>(s(e),t.insertMany(e,r,a)),insertManyUnsafe:(e,r,a)=>(s(e),t.insertManyUnsafe(e,r,a)),patch:async(e,r,a)=>(await o(e,a),t.patch(e,r,a)),patchMany:async(e,r,a)=>{for(const l of e)await o(l.id,a);return t.patchMany(e,r,a)},patchWhere:t.patchWhere?async(e,r,a)=>(s(e),await t.patchWhere?.(e,r,a)):void 0,query:e=>(s(e),t.query(e)),rank:(e,r,a)=>(s(e),t.rank(e,r,a)),rankPage:(e,r,a)=>(s(e),t.rankPage(e,r,a)),replace:async(e,r,a,l)=>(await o(e,a),t.replace(e,r,a,l)),restore:async(e,r)=>(await o(e,r),t.restore?.(e,r))};return u&&(h.rankBefore=(e,r,a)=>(s(e),u(e,r,a))),h};export{y as RLS_UNWRAP_SYMBOL,f as RlsRequiredError,k as guardWriter};
@@ -1 +0,0 @@
1
- import{stableWireKey as g}from"./stableWireKey-YEHLaX6X.mjs";import{depKey as b,SCAN_DEP as y}from"./SCAN_DEP-D_yR9EeV.mjs";import{r as p}from"./estimate-bytes-DzD3PdCc.mjs";import{keysTouchRanges as x}from"./buildIndexRange-DFsdtPjD.mjs";import{stableStringify as R}from"./stableStringify-BjLh4gvA.mjs";const m=1e3,u=4*1024*1024;class z{entries=new Map;tableIndex=new Map;rangeIndex=new Map;totalBytes=0;hits=0;misses=0;evictions=0;maxEntries;maxBytes;now;monotonic=0;constructor(t={}){this.maxEntries=t.maxEntries??m,this.maxBytes=t.maxBytes??u,this.now=t.now??(()=>(this.monotonic+=1,this.monotonic))}async run(t,s,i,e=()=>[]){const n=this.entries.get(t);if(n)return this.hits+=1,n.lastUsed=this.now(),this.entries.delete(t),this.entries.set(t,n),n.result;this.misses+=1;const h=await i(),a=e(),c=p(h,this.maxBytes),f={bytes:c,deps:s,ranges:a,lastUsed:this.now(),result:h,subscribers:new Set};this.entries.set(t,f),this.totalBytes+=c;for(const o of s){let r=this.tableIndex.get(o);r||(r=new Set,this.tableIndex.set(o,r)),r.add(t)}for(const o of a){let r=this.rangeIndex.get(o.table);r||(r=new Map,this.rangeIndex.set(o.table,r));let l=r.get(o);l||(l=new Set,r.set(o,l)),l.add(t)}return this.evict(),h}invalidate(t,s,i){const e=[];return this.collectAndDrop(b(t,s),e),this.collectAndDrop(b(t,y),e),this.dropRangeDeps(t,i,e),e}invalidateTable(t){const s=[],i=`${t}:`;for(const e of this.tableIndex.keys())e.startsWith(i)&&this.collectAndDrop(e,s);return this.dropRangeDeps(t,void 0,s),s}subscribe(t,s){const i=this.entries.get(t);i&&i.subscribers.add(s)}unsubscribe(t,s){const i=this.entries.get(t);i&&i.subscribers.delete(s)}size(){return{bytes:this.totalBytes,entries:this.entries.size}}clear(){this.entries.clear(),this.tableIndex.clear(),this.rangeIndex.clear(),this.totalBytes=0}subscribers(t){const s=this.entries.get(t);return s?[...s.subscribers]:[]}stats(){return{bytes:this.totalBytes,entries:this.entries.size,evictions:this.evictions,hits:this.hits,misses:this.misses}}dropRangeDeps(t,s,i){const e=this.rangeIndex.get(t);if(!(!e||e.size===0)){for(const[n,h]of e)if(x([n],s))for(const a of h){const c=this.entries.get(a);c&&(this.dropEntry(a,c),i.push(a))}}}collectAndDrop(t,s){const i=this.tableIndex.get(t);if(i)for(const e of i){const n=this.entries.get(e);n&&(this.dropEntry(e,n),s.push(e))}}dropEntry(t,s){this.entries.delete(t),this.totalBytes-=s.bytes;for(const i of s.deps){const e=this.tableIndex.get(i);e&&(e.delete(t),e.size===0&&this.tableIndex.delete(i))}for(const i of s.ranges){const e=this.rangeIndex.get(i.table),n=e?.get(i);n?.delete(t),e&&n?.size===0&&(e.delete(i),e.size===0&&this.rangeIndex.delete(i.table))}}evict(){if(!(this.entries.size<=this.maxEntries&&this.totalBytes<=this.maxBytes))for(const[t,s]of this.entries){if(this.entries.size<=this.maxEntries&&this.totalBytes<=this.maxBytes)return;s.subscribers.size>0||(this.dropEntry(t,s),this.evictions+=1)}}}const E=(d,t,s)=>`${s??"\0anon"}\0${d}:${g(t)}`;export{z as ReactiveCache,E as reactiveCacheKey,R as stableStringify,g as stableWireKey};
@@ -1 +0,0 @@
1
- import{f as l}from"./wire-codec-Ctnni0h6.mjs";const c="_id",p="__lunora__",b=r=>{if(typeof r!="object"||r===null||Array.isArray(r))return;const t=r[c];return typeof t=="string"?t:void 0},y=r=>{const t=new Map,s=[];for(const n of r){const e=b(n);if(e===void 0||t.has(e))return;t.set(e,n),s.push(e)}return{byId:t,order:s}},h=(r,t)=>{const s=r.order.filter(e=>t.byId.has(e)),n=t.order.filter(e=>r.byId.has(e));return s.length!==n.length?!1:s.every((e,o)=>n[o]===e)},g=(r,t,s,n)=>{const e=[];for(const o of r.order)t.byId.has(o)||e.push({delta:{key:o,op:"delete",table:s},frame:`{"key":${JSON.stringify(o)},"op":"delete","table":${n}}`});return e},m=(r,t,s,n)=>{const e=[];for(const o of t.order){const i=t.byId.get(o),a=r.byId.get(o),u=JSON.stringify(l(i)),f=a===void 0?void 0:JSON.stringify(a);if(f===u)continue;const d=f===void 0?"insert":"update";e.push({delta:{key:o,op:d,row:i,table:s},frame:`{"key":${JSON.stringify(o)},"op":"${d}","row":${u},"table":${n}}`})}return e},S=(r,t,s,n)=>{let e;try{e=JSON.parse(r)}catch{return}if(!Array.isArray(e)||!Array.isArray(t))return;const o=y(e),i=y(t);if(o===void 0||i===void 0||!h(o,i))return;const a=s===""?p:s,u=JSON.stringify(a),f=[...g(o,i,a,u),...m(o,i,a,u)];if(!(f.length>i.order.length)){if(n!==void 0)for(const{frame:d}of f)n.push(d);return f.map(({delta:d})=>d)}},$=(r,t)=>{try{return r.send(t),!0}catch{return!1}},w=(r,t,s,n)=>{const e=JSON.stringify(t);let o=!0;for(const i of s)$(r,`{"type":"delta","id":${e},"delta":${i}${n}}`)||(o=!1);return o},A=async r=>{let t=0;for(;t<100;){t+=1;const{bufferedAmount:s}=r;if(typeof s!="number"||s<1048576)return;await new Promise(n=>{setTimeout(n,20)})}};export{A as awaitWsDrain,w as sendDeltaFrames,S as subscriptionListDeltas,$ as trySendFrame};
@@ -1 +0,0 @@
1
- const c=(r,n)=>{try{const t=JSON.stringify(r);return t===void 0?0:t.length}catch{return n}};export{c as r};