@lunora/shard-engine 1.0.0-alpha.15 → 1.0.0-alpha.151

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.
Files changed (158) hide show
  1. package/README.md +1 -1
  2. package/dist/conformance/index.mjs +1 -1
  3. package/dist/index.d.mts +861 -173
  4. package/dist/index.d.ts +861 -173
  5. package/dist/index.mjs +1 -1
  6. package/dist/packem_shared/ADMIN_FUNCTIONS-Cug8Z4jD.mjs +1 -0
  7. package/dist/packem_shared/AGGREGATE_SQL_FUNCTION-C_ZipS9R.mjs +1 -0
  8. package/dist/packem_shared/AGG_COUNT-Ctb5Pnyl.mjs +1 -0
  9. package/dist/packem_shared/AUDIT_LOG_TABLE-BFJ65SRS.mjs +8 -0
  10. package/dist/packem_shared/BIGINT_KEY_DIGITS-DE6yshOt.mjs +1 -0
  11. package/dist/packem_shared/CDC_LOG_TABLE-C7o2xrt1.mjs +18 -0
  12. package/dist/packem_shared/CLIENT_WATERMARK_TABLE-De7z_OHV.mjs +7 -0
  13. package/dist/packem_shared/COMMIT_SEQ_FIELD-Da1DjGqo.mjs +4 -0
  14. package/dist/packem_shared/CURSOR_PREFIX-6offuG6M.mjs +1 -0
  15. package/dist/packem_shared/CountRlsUnsupportedError-BvsDqfO2.mjs +1 -0
  16. package/dist/packem_shared/DATA_MIGRATION_STATE_TABLE-D1FtktFp.mjs +31 -0
  17. package/dist/packem_shared/DEFAULT_MAX_RELATION_KEYS-BeTWZQ4X.mjs +1 -0
  18. package/dist/packem_shared/DEFAULT_MAX_RELAYS-CrsP5Ldh.mjs +8 -0
  19. package/dist/packem_shared/DEFAULT_PROMOTION_THRESHOLDS-B3pRMuqb.mjs +1 -0
  20. package/dist/packem_shared/DEFAULT_TRANSACTION_LIMITS-Dmj5VBrV.mjs +1 -0
  21. package/dist/packem_shared/DurableStreamRunner-MMlV5qKQ.mjs +1 -0
  22. package/dist/packem_shared/GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs +1 -0
  23. package/dist/packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-Bb6-aZuH.mjs +7 -0
  24. package/dist/packem_shared/GlobalPollTick-BNK4o-XT.mjs +1 -0
  25. package/dist/packem_shared/IDEMPOTENCY_TABLE-COrgeP3O.mjs +7 -0
  26. package/dist/packem_shared/MAIL_RETENTION-DMolrLYt.mjs +18 -0
  27. package/dist/packem_shared/MAX_SQL_ROWS-eRignWyO.mjs +4 -0
  28. package/dist/packem_shared/MAX_TOKEN_LENGTH-BakL9FUy-B3VwYY8C.mjs +1 -0
  29. package/dist/packem_shared/NotUniqueError-BR7jasrr.mjs +1 -0
  30. package/dist/packem_shared/QUEUE_TABLE-C-goXtGd.mjs +17 -0
  31. package/dist/packem_shared/RANK_TIEBREAK-D3ye2GsL.mjs +1 -0
  32. package/dist/packem_shared/REACTOR_STATE_TABLE-D2Mn204f.mjs +28 -0
  33. package/dist/packem_shared/RELATED_DEFAULT_LIMIT-CVqN4JEu.mjs +1 -0
  34. package/dist/packem_shared/RELATION_EXISTS_KEY-wxgj6rSL.mjs +1 -0
  35. package/dist/packem_shared/RELAY_SIGNATURE_HEADER-C_P73AOx.mjs +1 -0
  36. package/dist/packem_shared/REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs +1 -0
  37. package/dist/packem_shared/RLS_UNWRAP_SYMBOL-J1tiBtRj.mjs +1 -0
  38. package/dist/packem_shared/ReactiveCache-DHhhLJtN.mjs +1 -0
  39. package/dist/packem_shared/SCAN_DEP-D7qE3iUe.mjs +1 -0
  40. package/dist/packem_shared/SCHEDULE_OUTBOX_TABLE-DcZI7Yhl.mjs +11 -0
  41. package/dist/packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-CEwFjj-O.mjs +6 -0
  42. package/dist/packem_shared/SEARCH_STATE_TABLE-nYN2eKs_.mjs +1 -0
  43. package/dist/packem_shared/SHAPE_POKE_CURSOR_TABLE-BGvY3sFI.mjs +8 -0
  44. package/dist/packem_shared/ShapeDiffCache-iNO-hUiy.mjs +1 -0
  45. package/dist/packem_shared/ShardRunner-CrveaPId.mjs +1 -0
  46. package/dist/packem_shared/UNVOUCHABLE_DEP-C68htACn.mjs +1 -0
  47. package/dist/packem_shared/VECTOR_BACKFILL_MAX_PAGES-zxItOlPE.mjs +1 -0
  48. package/dist/packem_shared/WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs +1 -0
  49. package/dist/packem_shared/accepts-null-D1zmJbyR.mjs +1 -0
  50. package/dist/packem_shared/aggregateTableName-B_CtIQCS.mjs +1 -0
  51. package/dist/packem_shared/appendStreamChunk-BZYgGE9Y.mjs +17 -0
  52. package/dist/packem_shared/applyInsertDefaults-vVfUyiJ2.mjs +1 -0
  53. package/dist/packem_shared/archiveCdcSegment-Cr8oGLfB.mjs +4 -0
  54. package/dist/packem_shared/{armRestore-BNzdvQ_o.mjs → armRestore-Bu1_8SUa.mjs} +1 -1
  55. package/dist/packem_shared/assertPatchAllowed-CA_H466g.mjs +1 -0
  56. package/dist/packem_shared/awaitWsDrain-N-oR29RI.mjs +1 -0
  57. package/dist/packem_shared/backfillAggregateIndexes-DSplGrR_.mjs +1 -0
  58. package/dist/packem_shared/buildIndexRange-DQ3eWAGd.mjs +1 -0
  59. package/dist/packem_shared/buildPokeFrames-WR-hp0mX.mjs +1 -0
  60. package/dist/packem_shared/buildReprojectionMigration-Ds2JaFo7.mjs +1 -0
  61. package/dist/packem_shared/buildSettings-BRkZd6_E.mjs +1 -0
  62. package/dist/packem_shared/buildShapeDiff-Dc9TOdHq.mjs +1 -0
  63. package/dist/packem_shared/clearCompanionSignatures-3MlVqWZD.mjs +1 -0
  64. package/dist/packem_shared/clearMemoryTables-aMRERF0w.mjs +1 -0
  65. package/dist/packem_shared/compileWhereSql-TgKZIvWM.mjs +1 -0
  66. package/dist/packem_shared/computeRankPage-BZIpATcs.mjs +1 -0
  67. package/dist/packem_shared/createCompanionSync-BMS8yYTx.mjs +1 -0
  68. package/dist/packem_shared/createReplicaLink-CSbJvezn.mjs +7 -0
  69. package/dist/packem_shared/createSystemReader-DcDLFfC-.mjs +1 -0
  70. package/dist/packem_shared/ctx-db-relay-shapes-DV0VO4HG.mjs +17 -0
  71. package/dist/packem_shared/ctx-db-search-state-FjgzTFok.mjs +1 -0
  72. package/dist/packem_shared/defineEngineContractSuite-BiXyk2gE.mjs +1 -0
  73. package/dist/packem_shared/describeRelationWrites-omar6-u9.mjs +1 -0
  74. package/dist/packem_shared/diffExternalSource-B0FZlDoL.mjs +1 -0
  75. package/dist/packem_shared/do-sql-BWrJQAOh.mjs +1 -0
  76. package/dist/packem_shared/effective-kind-BmG_zCAy.mjs +1 -0
  77. package/dist/packem_shared/envOptionalPositiveInt-D2pY-c64.mjs +1 -0
  78. package/dist/packem_shared/estimate-bytes-_k74s6LZ.mjs +1 -0
  79. package/dist/packem_shared/exportShardRows-b0pfdTXz.mjs +1 -0
  80. package/dist/packem_shared/fts-companion-CA8mLJWq.mjs +1 -0
  81. package/dist/packem_shared/ftsCompanionDdl-0y8d4YvE.mjs +1 -0
  82. package/dist/packem_shared/hasTrigger-CjlwI4le.mjs +1 -0
  83. package/dist/packem_shared/isInternalTableName-BoljO2tP.mjs +1 -0
  84. package/dist/packem_shared/isPushableWhere-BeYAOjUb.mjs +1 -0
  85. package/dist/packem_shared/isSoftDeleted-DXANkomm.mjs +9 -0
  86. package/dist/packem_shared/json-field-path-DeJW4U9z.mjs +1 -0
  87. package/dist/packem_shared/liftSourceId-CA3ENhXj.mjs +1 -0
  88. package/dist/packem_shared/materializeExternalRows-rYWz87LR.mjs +1 -0
  89. package/dist/packem_shared/mergeChangedKeys-CF2mjYuy.mjs +1 -0
  90. package/dist/packem_shared/relation-operators-BEg-CvCH.mjs +1 -0
  91. package/dist/packem_shared/runDrizzle-RC09zZrh.mjs +1 -0
  92. package/dist/packem_shared/runShardMigrations-CEZTl9LV.mjs +5 -0
  93. package/dist/packem_shared/runSocketPool-CZJ2X9cF.mjs +1 -0
  94. package/dist/packem_shared/selectExpiredIds-DDQyqbLk.mjs +1 -0
  95. package/dist/packem_shared/selectShapeMembers-BCfKypfN.mjs +1 -0
  96. package/dist/packem_shared/serializeSqlValue-DeoBMpZ2.mjs +1 -0
  97. package/dist/packem_shared/where-sql-BjY4rnqb.mjs +1 -0
  98. package/package.json +5 -4
  99. package/dist/packem_shared/ADMIN_FUNCTIONS-xKxYOiRC.mjs +0 -1
  100. package/dist/packem_shared/AGGREGATE_SQL_FUNCTION-CTo0-9iZ.mjs +0 -1
  101. package/dist/packem_shared/AGG_COUNT-B0Pb1nQZ.mjs +0 -1
  102. package/dist/packem_shared/AUDIT_LOG_TABLE-C6nwXFPd.mjs +0 -8
  103. package/dist/packem_shared/CDC_LOG_TABLE-D__2M4gX.mjs +0 -8
  104. package/dist/packem_shared/CLIENT_WATERMARK_TABLE-CzApRlyv.mjs +0 -7
  105. package/dist/packem_shared/CountRlsUnsupportedError-8BqPYQoP.mjs +0 -1
  106. package/dist/packem_shared/DATA_MIGRATION_STATE_TABLE-BrpAGtXf.mjs +0 -31
  107. package/dist/packem_shared/DEFAULT_MAX_RELATION_KEYS-DOox9BFi.mjs +0 -1
  108. package/dist/packem_shared/DEFAULT_MAX_RELAYS-AcHLNxha.mjs +0 -1
  109. package/dist/packem_shared/DEFAULT_PROMOTION_THRESHOLDS-BdmnUGLO.mjs +0 -1
  110. package/dist/packem_shared/DEFAULT_TRANSACTION_LIMITS-BH5q0Ror.mjs +0 -1
  111. package/dist/packem_shared/GEO_DEFAULT_PRECISION-DyI5zggj.mjs +0 -1
  112. package/dist/packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-soMJDSBs.mjs +0 -7
  113. package/dist/packem_shared/IDEMPOTENCY_TABLE-Bvu9JkiL.mjs +0 -7
  114. package/dist/packem_shared/MAIL_RETENTION-BefR9Sei.mjs +0 -18
  115. package/dist/packem_shared/MAX_SQL_ROWS-nMwkxv5f.mjs +0 -2
  116. package/dist/packem_shared/NotUniqueError-C32BFrv1.mjs +0 -1
  117. package/dist/packem_shared/QUEUE_TABLE-DgBqWrXX.mjs +0 -17
  118. package/dist/packem_shared/RANK_TIEBREAK-D541BOFR.mjs +0 -1
  119. package/dist/packem_shared/RELATION_EXISTS_KEY-BaqSIFU1.mjs +0 -1
  120. package/dist/packem_shared/RLS_UNWRAP_SYMBOL-DcqORh2s.mjs +0 -1
  121. package/dist/packem_shared/ReactiveCache-iWA9VRqk.mjs +0 -1
  122. package/dist/packem_shared/SCAN_DEP-D_yR9EeV.mjs +0 -1
  123. package/dist/packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-BEU0CuW5.mjs +0 -6
  124. package/dist/packem_shared/SEARCH_STATE_TABLE-BZ_fxI5l.mjs +0 -1
  125. package/dist/packem_shared/ShardRunner-DIqVdWtk.mjs +0 -1
  126. package/dist/packem_shared/aggregateTableName-DKo6dwBP.mjs +0 -1
  127. package/dist/packem_shared/applyOnDelete-fMu_5DR5.mjs +0 -1
  128. package/dist/packem_shared/applySelect-BjgwvZmI.mjs +0 -1
  129. package/dist/packem_shared/awaitWsDrain-DKycCSBS.mjs +0 -1
  130. package/dist/packem_shared/backfillAggregateIndexes-BVNrfFcI.mjs +0 -1
  131. package/dist/packem_shared/buildIndexRange-DFsdtPjD.mjs +0 -1
  132. package/dist/packem_shared/buildPokeFrames-CCxYXd2V.mjs +0 -1
  133. package/dist/packem_shared/buildSettings-COIJsw7a.mjs +0 -1
  134. package/dist/packem_shared/compileWhereSql-B4rPariq.mjs +0 -1
  135. package/dist/packem_shared/computeRankPage-B7U6t1fW.mjs +0 -1
  136. package/dist/packem_shared/createCompanionSync-Dym8huD9.mjs +0 -1
  137. package/dist/packem_shared/createReadFootprint-DIrrxRTE.mjs +0 -1
  138. package/dist/packem_shared/createSystemReader-DcDcrtM3.mjs +0 -1
  139. package/dist/packem_shared/ctx-db-companions-7fIu-E2H.mjs +0 -1
  140. package/dist/packem_shared/defineEngineContractSuite-LKRHlQwE.mjs +0 -1
  141. package/dist/packem_shared/diffExternalSource-DMpkJta1.mjs +0 -1
  142. package/dist/packem_shared/estimate-bytes-DwQON1Ky.mjs +0 -1
  143. package/dist/packem_shared/exportShardRows-Bbi_JGfn.mjs +0 -1
  144. package/dist/packem_shared/hasTrigger-CbkOHExZ.mjs +0 -1
  145. package/dist/packem_shared/isSoftDeleted-doD_8AwX.mjs +0 -9
  146. package/dist/packem_shared/liftSourceId-DApAbu7Q.mjs +0 -1
  147. package/dist/packem_shared/materializeExternalRows-BR8MvZTz.mjs +0 -1
  148. package/dist/packem_shared/mergeChangedKeys-BXtUgIPW.mjs +0 -1
  149. package/dist/packem_shared/param-B5lF5Jd9.mjs +0 -1
  150. package/dist/packem_shared/runDrizzle-B6rnz3so.mjs +0 -1
  151. package/dist/packem_shared/runShardMigrations-DhZLG0bn.mjs +0 -5
  152. package/dist/packem_shared/runSocketPool-DPQLVyWF.mjs +0 -1
  153. package/dist/packem_shared/selectExpiredIds-DxFEwNlT.mjs +0 -1
  154. package/dist/packem_shared/selectShapeMemberIds-BD3JiZn-.mjs +0 -1
  155. package/dist/packem_shared/serializeSqlValue-DnpyaLcw.mjs +0 -1
  156. package/dist/packem_shared/stableStringify-BjLh4gvA.mjs +0 -1
  157. package/dist/packem_shared/stableWireKey-C4JfdJ_e.mjs +0 -1
  158. package/dist/packem_shared/wire-codec-D_fiax9d.mjs +0 -1
@@ -0,0 +1 @@
1
+ import{LunoraError as y}from"@lunora/errors";import{D as ft}from"./MAX_TOKEN_LENGTH-BakL9FUy-B3VwYY8C.mjs";import{S as vn,l as We,h as In}from"./fts-companion-CA8mLJWq.mjs";import{decodeWire as An,stableWireKey as Dt}from"@lunora/wire";import{sql as a}from"drizzle-orm";import{throwingScheduler as Cn,aggregateSqlFunction as Be,normalizeCountArgument as xn}from"./AGGREGATE_SQL_FUNCTION-C_ZipS9R.mjs";import{aggregateTableName as tt,encodeAggregateKey as nt,readAggregateValue as ot}from"./aggregateTableName-B_CtIQCS.mjs";import{mergeWhere as K,CountRlsUnsupportedError as rt,selectIndexForGroupBy as bn,selectIndexForCount as Mn,selectIndexForAggregate as Dn}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{backfillSearchIndexesForTable as kn,searchIndexCoversTable as Ln}from"./backfillAggregateIndexes-DSplGrR_.mjs";import{backfillAggregateIndexes as di,backfillRankIndexes as li,backfillSearchIndexes as ui}from"./backfillAggregateIndexes-DSplGrR_.mjs";import{appendCdcChange as Fn,readCdcDocAtOrBefore as qn}from"./CDC_LOG_TABLE-C7o2xrt1.mjs";import{CDC_LOG_TABLE as hi,applyCdcChanges as wi,bumpCdcEpoch as pi,cdcCanVouchFor as gi,cdcForkedError as yi,cdcSeqLeavingRows as $i,cdcTouchesTables as Ei,cdcTrimmedError as mi,compactCdcDocs as Si,cursorBelowRetainedFloor as Ri,minCdcReplayableSeq as Ti,minCdcSeq as _i,readCdcChangeKeys as vi,readCdcChanges as Ii,readCdcCursor as Ai,readCdcEpoch as Ci,trimCdcChanges as xi}from"./CDC_LOG_TABLE-C7o2xrt1.mjs";import{allocateCommitSeq as Wn,COMMIT_SEQ_FIELD as Bn}from"./COMMIT_SEQ_FIELD-Da1DjGqo.mjs";import{createCompanionSync as Pn}from"./createCompanionSync-BMS8yYTx.mjs";import{isMemoryTable as kt}from"./clearMemoryTables-aMRERF0w.mjs";import{computeRankPage as Lt}from"./computeRankPage-BZIpATcs.mjs";import{SCAN_DEP as U}from"./SCAN_DEP-D7qE3iUe.mjs";import{runSql as pe,runDrizzle as H}from"./runDrizzle-RC09zZrh.mjs";import{p as Un,j as dt,D as ie,r as Ie,k as ue,b as Pe,A as it,a as Ue,m as he,e as we,s as On,t as Hn,i as Gn,q as Ft,h as cn,g as jn}from"./do-sql-BWrJQAOh.mjs";import{renderSql as an,unionAll as ht,WORKERD_SQLITE_LIMITS as dn,sqliteInList as Kn}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{coveringGeohashes as Nn,boundingBoxGeohashes as Qn,haversineMeters as Vn,pointInBoundingBox as Jn}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{NotFoundError as zn}from"./NotFoundError-BhF7FeFr.mjs";import{resolvePatch as Yn,assertPatchAllowed as Xn,operatorFields as Zn,readPatchField as qt}from"./assertPatchAllowed-CA_H466g.mjs";import{tiebreakDirectionFor as eo,encodeCursor as Ke,nullsOrderSuffix as to,normalizeOrderKeys as Wt,uniqueIndexFields as no,buildSeekWhere as oo,decodeCursor as Bt,buildSeekBeforeWhere as ro,softDeleteScope as ve,applySelect as Pt}from"./CURSOR_PREFIX-6offuG6M.mjs";import{rankTableName as Ut,sortColumnName as Ot,resolveRankPartition as io,encodePartitionKey as so,RANK_TIEBREAK as co,rankPivotConditionSql as ao}from"./RANK_TIEBREAK-D3ye2GsL.mjs";import{UNVOUCHABLE_DEP as Ht}from"./UNVOUCHABLE_DEP-C68htACn.mjs";import{indexKeysForRow as lo,buildIndexRange as uo}from"./buildIndexRange-DQ3eWAGd.mjs";import{r as Ne,j as Ae,c as Y,t as Qe,i as Gt}from"./where-sql-BjY4rnqb.mjs";import{serializeSqlValue as Ce}from"./serializeSqlValue-DeoBMpZ2.mjs";import{quoteIdentifier as xe}from"./quoteIdentifier-CObIFRhb.mjs";import{whereOfFilter as fo,isPushableWhere as ho}from"./isPushableWhere-BeYAOjUb.mjs";import{deriveRelationEdges as wo,findRelated as po}from"./RELATED_DEFAULT_LIMIT-CVqN4JEu.mjs";import{assertFlatPredicate as st,resolveRelationPredicates as go,composeReadPredicate as yo}from"./DEFAULT_MAX_RELATION_KEYS-BeTWZQ4X.mjs";import{describeRelationWrites as $o}from"./describeRelationWrites-omar6-u9.mjs";import{runRowValidators as Oe,transformOnlyDefinition as Eo,applyInsertDefaults as jt,resolveWith as Kt,relationHooks as Nt,applyOnDelete as mo,fanOutScalarCounts as So}from"./applyInsertDefaults-vVfUyiJ2.mjs";import{guardWriter as Ro}from"./RLS_UNWRAP_SYMBOL-J1tiBtRj.mjs";import{mayHoldProjectedValue as To}from"./BIGINT_KEY_DIGITS-DE6yshOt.mjs";import{createSystemReader as _o}from"./createSystemReader-DcDLFfC-.mjs";import{ConflictError as de}from"./ConflictError-C8GtJmjS.mjs";import{hasTrigger as Qt,runTriggers as vo}from"./hasTrigger-CjlwI4le.mjs";import{advanceClientWatermark as Mi,migrateClientWatermark as Di,readClientWatermark as ki}from"./CLIENT_WATERMARK_TABLE-De7z_OHV.mjs";import{IDEMPOTENCY_TABLE as Fi,readIdempotent as qi,trimIdempotent as Wi,writeIdempotent as Bi}from"./IDEMPOTENCY_TABLE-COrgeP3O.mjs";import{runShardMigrations as Ui}from"./runShardMigrations-CEZTl9LV.mjs";import{selectShapeMembers as Hi,selectShapeRows as Gi}from"./selectShapeMembers-BCfKypfN.mjs";const Io=n=>{const i=atob(n),o=Uint8Array.from(i,c=>c.codePointAt(0)??0);return new TextDecoder().decode(o)},Ao=()=>new y("BAD_REQUEST","invalid cursor"),Vt=16,Jt=8,V=1024,wt=(n,i)=>i.query(n),Co=(n,i)=>{if(n.length===0)return 0;let o=0;for(const[c,s]of i.entries()){const w=c===i.length-1;let _=0;for(const S of n)(w?S.startsWith(s):S===s)&&(_+=1);if(_===0)return 0;o+=_}return o},xo=(n,i)=>{if(!i)return{exact:!0,lower:n,upper:n};const o=[...n].at(-1)??"",c=(o.codePointAt(0)??0)+1;if(c>=55296&&c<=57343||c>1114111)return{exact:!0,lower:n,upper:n};const s=n.slice(0,n.length-o.length);return{exact:!1,lower:n,upper:s+String.fromCodePoint(c)}},bo=(n,i,o)=>{const c={eq:(s,w)=>{if(!n.definition.filterFields?.includes(s))throw new y("INTERNAL",`field "${s}" is not a filter field of search index "${n.indexName}" on table "${i}"`);if(n.filters.length>=Jt)throw new y("BAD_REQUEST",`search index "${n.indexName}" on table "${i}": at most ${String(Jt)} .eq() filters are supported per search query`);return n.filters.push({field:s,value:w}),c},search:(s,w)=>{const _=n;if(s!==_.definition.field)throw new y("INTERNAL",`search index "${_.indexName}" on table "${i}" indexes "${_.definition.field}", not "${s}"`);const S=wt(w,o).length;if(S>Vt)throw new y("BAD_REQUEST",`search index "${_.indexName}" on table "${i}": at most ${String(Vt)} search terms are supported (got ${String(S)})`);return _.field=s,_.query=w,_.hasQuery=!0,c}};return c},Mo=n=>{if(n.length>V)throw new y("BAD_REQUEST",`more than ${String(V)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},Do=n=>Math.min(n.offset+n.numItems+1,V),ko=n=>btoa(`search:${String(n)}`),Lo=n=>{let i;try{i=Io(n)}catch{return}if(!i.startsWith("search:"))return;const o=Number(i.slice(7));return Number.isInteger(o)&&o>=0?o:void 0},Fo=n=>{if(typeof n.endCursor=="string")throw new y("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");if(!Number.isFinite(n.numItems))throw new y("BAD_REQUEST",`search pagination needs a finite numItems, got ${String(n.numItems)}`);const i=Math.max(0,Math.floor(n.numItems)),o=n.cursor?Lo(n.cursor):0;if(o===void 0)throw Ao();if(o+i>=V)throw new y("BAD_REQUEST",`search pagination reaches the ${String(V)}-document limit (offset ${String(o)} + ${String(i)} requested) — a page must end below the cap so the probe row that answers \`hasMore\` still fits: retry with numItems ${String(Math.max(1,V-o-1))} or fewer, or narrow the query or the filters instead`);return{numItems:i,offset:o}},qo=(n,i)=>{const o=i.offset+i.numItems,c=i.numItems>0&&n.length>o;return{continueCursor:c?ko(o):null,isDone:!c,page:n.slice(i.offset,o)}},Wo=n=>{if(n===void 0)return V+1;if(!Number.isFinite(n))return V;const i=Math.max(0,Math.floor(n));if(i>V)throw new y("BAD_REQUEST",`search returns at most ${String(V)} documents (asked for ${String(i)}) — narrow the query or paginate instead`);return i},Bo=32,Po=1024,ln=(n,i,o,c)=>{const s=`SELECT id, _creationTime, ${xe(ie)} FROM ${xe(n)}`,w=`ORDER BY ${o}${c===void 0?"":` LIMIT ${String(c)}`}`;return i===void 0?Ne(`${s} ${w}`):Ae(`${s} WHERE `,i,` ${w}`)},Ve={fieldRef:n=>Ne(dt(n)),rangeTypeGuard:(n,i)=>Ne(Un(n,i)),serialize:Ce},Uo=n=>n===void 0?"":to(n==="first"),un=n=>{const i=n.map(o=>`${dt(o.field)} ${o.direction==="desc"?"DESC":"ASC"}${Uo(o.nulls)}`);return n.some(o=>o.field==="_id"||o.field==="id")||i.push(`${dt("id")} ${eo(n)==="desc"?"DESC":"ASC"}`),i.join(", ")},Oo={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},fn=n=>new Set(n.sqlConditions.filter(i=>i.comparator==="=").map(i=>i.field)),Ho=n=>{const i=fn(n);let o=0;for(;o<n.indexFields.length&&i.has(n.indexFields[o]??"");)o+=1;return n.indexFields.slice(o)},Go=(n,i)=>{const o=n.order,c=Ho(n),{shape:s}=i;return c.length>0?Wt(c.map(w=>({[w]:o})),s,{pinned:fn(n),uniqueBy:no(i.indexes,s)}):Wt([{_creationTime:o}],s)},jo=(n,i,o,c)=>{const s=n.sqlConditions.map(w=>({[w.field]:{[Oo[w.comparator]??"eq"]:w.value}}));if(o&&s.push(oo(i,Bt(o))),c&&s.push(ro(i,Bt(c))),s.length!==0)return s.length===1?s[0]:{AND:s}},Ko=n=>{if(n.want!==void 0)return n.selective?Math.max(n.want,Bo):n.want},lt=(n,i,o,c,s,w,_)=>{const S=Go(c,o),C=un(S),$=[],{filters:q,want:x}=w;let A=w.cursor??void 0,M=Ko(w);if(x===0)return{documents:$,orderKeys:S};for(;;){const W=Y(jo(c,S,A,w.endCursor),Ve,Qe),D=ln(i,s&&W?Ae(W," AND ",s):s??W,C,M),L=pe(n,D.text,...D.params).toArray();let F={};_(L.length);for(const G of L)if(F=Ie(G),q.every(se=>se(F))&&$.push(F)===x)return{documents:$,orderKeys:S};if(M===void 0||L.length<M)return{documents:$,orderKeys:S};A=Ke(F,S),M=Math.max(M,Math.min(M*2,Po))}},No=(n,i,o,c,s,w,_,S)=>{const C=Math.max(0,Math.floor(s.numItems));if(typeof s.endCursor=="string"){const{documents:W,orderKeys:D}=lt(n,i,o,c,w,{cursor:s.cursor,endCursor:s.endCursor,filters:_.all,selective:_.selective,want:void 0},S),L=W.length>=2?W[Math.floor(W.length/2)-1]:void 0;return{continueCursor:s.endCursor,isDone:!0,page:W,splitCursor:L?Ke(L,D):null}}const{documents:$,orderKeys:q}=lt(n,i,o,c,w,{cursor:s.cursor,filters:_.all,selective:_.selective,want:C+1},S),x=$.length>C,A=x?$.slice(0,C):$,M=A.at(-1);return{continueCursor:x&&M?Ke(M,q):null,isDone:!x,page:A}},Je=n=>{const i=new Map;return o=>{const c=i.get(o);if(c!==void 0)return c;const s=n(xe(o));return i.set(o,s),s}},ge=xe(ie),Qo=Je(n=>`INSERT INTO ${n} (id, _creationTime, ${ge}) VALUES (?, ?, ?)`),zt=Je(n=>`UPDATE ${n} SET ${ge} = ? WHERE id = ? AND ${ge} = ?`),Vo=Je(n=>`UPDATE ${n} SET _creationTime = ?, ${ge} = ? WHERE id = ? AND ${ge} = ?`),Jo=Je(n=>`DELETE FROM ${n} WHERE id = ? AND ${ge} = ?`),zo="SELECT changes() AS changed",Yt=new Map,Yo="",Xo=n=>{const i=JSON.stringify(n),o=Yt.get(i);if(o!==void 0)return o;const c=n.map(w=>a`SELECT ${a.raw(`'${w.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${a.identifier(ie)} FROM ${a.identifier(w)} WHERE id = ${Yo}`),{sql:s}=an("sqlite",a`${ht(c)} LIMIT 1`);return Yt.set(i,s),s},Zo=(n,i)=>i.map(()=>n),er=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,tr=n=>{if(!er.test(n))throw new y("INTERNAL",`invalid clientId ${JSON.stringify(n)}: a client-supplied row id must be a UUID`)},Xt=50,hn=500,He=Math.floor(dn.boundParams/3),_e=dn.boundParams,nr=128,fe=(n,i,o)=>{const c=i??hn;if(n>c)throw new y("BATCH_LIMIT_EXCEEDED",`${o}: batch of ${String(n)} exceeds the limit of ${String(c)} (raise options.limit or chunk the call)`,{status:400})},or=n=>{const i={eq:(o,c)=>(n.sqlConditions.push({comparator:"=",field:o,value:c}),i),gt:(o,c)=>(n.sqlConditions.push({comparator:">",field:o,value:c}),i),gte:(o,c)=>(n.sqlConditions.push({comparator:">=",field:o,value:c}),i),lt:(o,c)=>(n.sqlConditions.push({comparator:"<",field:o,value:c}),i),lte:(o,c)=>(n.sqlConditions.push({comparator:"<=",field:o,value:c}),i)};return i},rr=n=>Math.max(n,V),wn=(n,i)=>{const o=n.filters.map(c=>a`${we(c.field)} = ${Ce(c.value)}`);return i&&o.push(i),o},ir=(n,i,o,c,s)=>{const w=wt(o.query,ft(o.definition.language));if(w.length===0)return[];const _=vn(i,o.indexName),S=`${_}__vocab`,C=w.length-1,$=w.map((D,L)=>{const F=xo(D,L===C),G=F.exact?a`${a.identifier("term")} = ${F.lower}`:a`${a.identifier("term")} >= ${F.lower} AND ${a.identifier("term")} < ${F.upper}`;return a`SELECT ${a.identifier("doc")}, ${a.raw(String(L))} AS ${a.identifier("__term__")}, COUNT(*) AS ${a.identifier("__n__")} FROM ${a.identifier(S)} WHERE ${G} GROUP BY ${a.identifier("doc")}`}),q=w.map((D,L)=>a`SUM(CASE WHEN u.${a.identifier("__term__")} = ${a.raw(String(L))} THEN u.${a.identifier("__n__")} ELSE 0 END)`),x=a`SELECT f.${a.identifier(We)} AS ${a.identifier(We)}, ${a.join(q,a` + `)} AS ${a.identifier("__score__")} FROM (${ht($)}) u JOIN ${a.identifier(_)} f ON f.rowid = u.${a.identifier("doc")} GROUP BY f.${a.identifier(We)} HAVING ${a.join(q.map(D=>a`${D} > 0`),a` AND `)}`,A=wn(o,s);let M=a`SELECT m.id, m._creationTime, m.${a.identifier(ie)}, s.${a.identifier("__score__")} AS ${a.identifier("__score__")} FROM (${x}) s JOIN ${a.identifier(i)} m ON m.id = s.${a.identifier(We)}`;A.length>0&&(M=a`${M} WHERE ${a.join(A,a` AND `)}`),M=a`${M} ORDER BY s.${a.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${a.raw(String(c))}`;const W=[];for(const D of H(n,M)){const L=cn(D);if(L){const F=D.__score__;W.push({document:L,score:typeof F=="number"?F:Number(F??0)})}}return W},sr=(n,i,o,c,s)=>{const w=ft(o.definition.language),_=wt(o.query,w);if(_.length===0)return[];const S=wn(o,s);let C=a`SELECT id, _creationTime, ${a.identifier(ie)} FROM ${a.identifier(i)}`;S.length>0&&(C=a`${C} WHERE ${a.join(S,a` AND `)}`),C=a`${C} ORDER BY _creationTime DESC, id ASC LIMIT ${a.raw(String(rr(c)))}`;const $=H(n,C).toArray(),q=[];for(const x of $){const A=cn(x);if(!A)continue;const M=Co(In(A,o.definition),_);M>0&&q.push({creationTime:typeof A._creationTime=="number"?A._creationTime:0,doc:A,id:typeof A._id=="string"?A._id:"",score:M})}return q.sort((x,A)=>A.score-x.score||A.creationTime-x.creationTime||x.id.localeCompare(A.id)),q.slice(0,c).map(x=>({document:x.doc,score:x.score}))},ct=(n,i,o,c)=>{if(!Number.isFinite(n.lat)||n.lat<-90||n.lat>90||!Number.isFinite(n.lng)||n.lng<-180||n.lng>180)throw new y("BAD_REQUEST",`geo index "${c}" on table "${o}": ${i} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},cr=(n,i)=>{const o=n,c={near:(s,w)=>{if(o.within)throw new y("INTERNAL",`geo index "${o.indexName}" on table "${i}": call .near() or .within(), not both`);if(ct(s,".near() point",i,o.indexName),!Number.isFinite(w)||w<=0)throw new y("BAD_REQUEST",`geo index "${o.indexName}" on table "${i}": .near() radiusMeters must be a finite number > 0, got ${String(w)}`);return o.near={point:{lat:s.lat,lng:s.lng},radiusMeters:w},c},within:s=>{if(o.near)throw new y("INTERNAL",`geo index "${o.indexName}" on table "${i}": call .near() or .within(), not both`);if(ct(s.sw,".within() sw corner",i,o.indexName),ct(s.ne,".within() ne corner",i,o.indexName),s.sw.lat>s.ne.lat)throw new y("BAD_REQUEST",`geo index "${o.indexName}" on table "${i}": .within() corners are transposed (sw.lat > ne.lat)`);if(s.sw.lng>s.ne.lng)throw new y("BAD_REQUEST",`geo index "${o.indexName}" on table "${i}": .within() box crosses the antimeridian (sw.lng > ne.lng), which is not supported — split it into two boxes at ±180 and union the results`);return o.within={ne:{lat:s.ne.lat,lng:s.ne.lng},sw:{lat:s.sw.lat,lng:s.sw.lng}},c}};return c},ar=(n,i)=>{const o=n[i];if(o===null||typeof o!="object")return;const{lat:c,lng:s}=o;return typeof c=="number"&&typeof s=="number"?{lat:c,lng:s}:void 0},dr=(n,i)=>{const o=ar(n,i.definition.field);if(!o)return;const c=typeof n._creationTime=="number"?n._creationTime:0;if(i.near){const s=Vn(i.near.point,o);return s<=i.near.radiusMeters?{creationTime:c,distance:s}:void 0}return Jn(o,i.within)?{creationTime:c,distance:0}:void 0},lr=(n,i,o,c)=>{if(!o.near&&!o.within)throw new y("INTERNAL",`geo index "${o.indexName}" on table "${i}": call .near(point, radius) or .within(box)`);const s=o.near?Nn(o.near.point,o.near.radiusMeters):Qn(o.within),w=jn(i,o.indexName),_=s.map(x=>a`(g.${a.identifier("__geohash__")} >= ${x} AND g.${a.identifier("__geohash__")} < ${`${x}{`})`),S=[a`(${a.join(_,a` OR `)})`];c&&S.push(c);const C=a`SELECT m.id, m._creationTime, m.${a.identifier(ie)} FROM ${a.identifier(w)} g JOIN ${a.identifier(i)} m ON m.id = g.${a.identifier("__id__")} WHERE ${a.join(S,a` AND `)}`,$=H(n,C).toArray(),q=[];for(const x of $){const A=Ie(x),M=A?dr(A,o):void 0;A&&M&&q.push({creationTime:M.creationTime,distance:M.distance,doc:A})}return q.sort((x,A)=>x.distance-A.distance||A.creationTime-x.creationTime),q},pn=(n,i,o,c)=>{const s=[];for(const w of n)if(i.every(_=>_(c(w)))&&(s.push(w),typeof o=="number"&&s.length>=o))break;return s},ur=(n,i,o,c,s,w=()=>{})=>{const _=o.within!==void 0,S=lr(n,i,o,s).map(C=>({distanceMeters:_?null:C.distance,document:C.doc}));return w(S.length),typeof c=="number"?S.slice(0,Math.max(0,Math.floor(c))):S},Zt=(n,i,o,c,s,w,_=()=>{})=>{const{geo:S}=o;if(!S)throw new y("INTERNAL","runGeoTerminalScored called without a staged geo query");const C=s.length>0,$=ur(n,i,S,C?void 0:w,c,_);return C?pn($,s,w,q=>q.document):$},en=(n,i,o)=>{const c=n.shape[i];if(c!==void 0&&To(c))throw new y("BAD_REQUEST",`${o}: "${i}" may hold an order-preserving key rather than a value SQL can reduce or group — declare an aggregateIndex covering this (by, field, op) so the maintained companion answers it instead (its running total is a REAL, so it stays exact only while the total is inside 2^53)`)},fr=n=>{let i=0;const o=[],c={...Ve,relationExists:s=>{const{childWhere:w,negated:_,parentTable:S,relation:C}=s,$=`__rel_${String(i)}`,q=o.at(-1)??S;i+=1,n(C.table,U);const x=C.kind==="one"?C.field:C.references,A=C.kind==="one"?C.references:C.field,M=Ne(`${Ft($,A)} = ${Ft(q,x)}`);o.push($);const W=Y(w,c,Qe);o.pop();const D=W===void 0?M:Ae(M," AND ",W),L=Ae("EXISTS (SELECT 1 FROM ",Gt(C.table)," AS ",Gt($)," WHERE ",D,")");return _?Ae("NOT ",L):L}};return c};class hr extends y{constructor(i="unique() found more than one matching document"){super("NOT_UNIQUE",i,{name:"NotUniqueError"})}}const wr=/\s/u,pr=String.fromCodePoint(0),tn=(n,i,o)=>{if(!n.tables[i])throw new y("INTERNAL",`unknown table: ${i}`);return typeof o!="string"||o.length===0||wr.test(o)||o.includes(pr)?null:o},gn=(n,i,o,c=()=>{},s=()=>{},w=()=>{},_)=>{const S=i.tables[o];if(!S)throw new y("INTERNAL",`unknown table: ${o}`);const C=ve(S.softDeleteMode,void 0),$=_??{indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[],verifyFilters:[]},q=()=>{const m=K(C,$.pushedWhere);return m?Y(m,he):void 0},x=()=>{const m=K(C,$.pushedWhere);return m?Y(m,Ve,Qe):void 0},A=()=>[...$.inMemoryFilters,...$.verifyFilters];let M=0;const W=m=>{const{search:b}=$;if(!b)throw new y("INTERNAL","runSearchFetch called without a staged search");kn(n,o,S);const T=$.inMemoryFilters.length>0,k=Wo(T?void 0:m),Z=Gn(n);if(Z&&!Ln(n,o,b.definition))throw new y("SEARCH_INDEX_BUILDING",`search index "${b.indexName}" on table "${o}" is still backfilling and currently covers only part of the table — retry once it finishes, or run the backfillSearch admin operation to complete it now`);const N=q(),J=Z?ir(n,o,b,k,N):sr(n,o,b,k,N);!T&&m===void 0&&Mo(J);const re=A();return M=J.length,re.length>0?pn(J,re,m,ce=>ce.document):J},D=m=>W(m).map(b=>b.document),L=m=>{const b=Fo(m);return qo(D(Do(b)),b)},F=()=>{if($.search||$.geo||$.indexName===void 0){s(void 0);return}s(uo(o,$.indexName,$.indexFields,$.sqlConditions,Ce))},G=m=>{F();let b=0;const T=(()=>{if($.search){const k=D(m);return b=M,k}return $.geo?Zt(n,o,$,q(),A(),m,k=>{b=k}).map(k=>k.document):lt(n,o,S,$,x(),{filters:A(),selective:$.inMemoryFilters.length>0,want:m===void 0?void 0:Math.max(0,Math.floor(m))},k=>{b+=k}).documents})();return w(Math.max(b,T.length)),T},se=()=>{if(!$.search&&!$.geo)throw new y("INTERNAL",`ctx.db.query("${o}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);F();let m=0;const b=(()=>{if($.search){const T=W(void 0);return m=M,T}return Zt(n,o,$,q(),A(),void 0,T=>{m=T})})();return w(Math.max(m,b.length)),b},X={async*[Symbol.asyncIterator](){const m=gn(n,i,o,c,s,w,{...$,indexFields:[...$.indexFields],inMemoryFilters:[...$.inMemoryFilters],sqlConditions:[...$.sqlConditions],verifyFilters:[...$.verifyFilters]});if($.search){yield*await m.collect();return}let b;for(;;){const T=await m.paginate({cursor:b??null,numItems:nr});if(yield*T.page,T.isDone||T.continueCursor===null)return;b=T.continueCursor}},async collect(){return G(void 0)},async collectWithScores(){return se()},filter(m){const b=fo(m);return b!==void 0&&ho(b,S.shape)?($.pushedWhere=K($.pushedWhere,b),$.verifyFilters.push(m)):$.inMemoryFilters.push(m),X},async first(){return G(1)[0]??null},order(m){return $.order=m==="desc"?"desc":"asc",X},async paginate(m){let b=0;if(F(),$.search){const k=L(m);return w(k.page.length),k}if($.geo)throw new y("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const T=No(n,o,S,$,m,x(),{all:A(),selective:$.inMemoryFilters.length>0},k=>{b+=k});return w(Math.max(b,T.page.length)),T},async take(m){return G(m)},async unique(){const m=G(2);if(m.length>1)throw new hr(`unique() on table "${o}" matched ${String(m.length)} documents; expected at most one`);return m[0]??null},withGeoIndex(m,b){const T=(S.geoIndexes??[]).find(Z=>Z.name===m);if(!T)throw new y("INTERNAL",`unknown geo index "${m}" on table "${o}"`);c(o,m,"geo");const k={definition:T,indexName:m};if($.geo=k,b(cr(k,o)),!k.near&&!k.within)throw new y("INTERNAL",`geo index "${m}" on table "${o}" requires a .near(point, radius) or .within(box) call`);return X},withIndex(m,b){const T=S.indexes.find(k=>k.name===m);if(!T)throw new y("INTERNAL",`unknown index "${m}" on table "${o}"`);return c(o,m,"index"),$.indexName=m,$.indexFields=T.fields,b&&b(or($)),X},withSearchIndex(m,b){const T=(S.searchIndexes??[]).find(Z=>Z.name===m);if(!T)throw new y("INTERNAL",`unknown search index "${m}" on table "${o}"`);c(o,m,"search");const k={definition:T,field:T.field,filters:[],hasQuery:!1,indexName:m,query:""};if($.search=k,b(bo(k,o,ft(T.language))),!k.hasQuery)throw new y("INTERNAL",`search index "${m}" on table "${o}" requires a .search(field, query) call`);return X}};return X},at=(n,i,o,c)=>{const s=o;for(const[w,_]of Hn(n)){if(_.serverDefault){w in i&&(s[w]=_.serverDefault({auth:c}));continue}_.onUpdateFn&&!(w in i)&&(s[w]=_.onUpdateFn())}},nn=5,on=(n,i)=>{for(const o of Object.keys(i))if(i[o]===void 0)throw new y("INTERNAL",`Cannot ${n} field '${o}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},rn=["_commitSeq","_creationTime","_id"],Ge=n=>rn.some(i=>i in n)?Object.fromEntries(Object.entries(n).filter(([i])=>!rn.includes(i))):n,gr=/unique constraint failed/i,yr=n=>n instanceof Error&&gr.test(n.message),$r=/string or blob too big/iu,Er=(n,i)=>{if(!(!(n instanceof Error)||!$r.test(n.message)))throw new y("PAYLOAD_TOO_LARGE",`document is too large to store in "${i}": a single row cannot exceed the storage engine's per-row ceiling (2 MB on a Durable Object's SQLite). The limit is on the STORED bytes, which are UTF-8, and v.bytes()/v.bigint() columns are stored twice on a shard-local table. Keep the payload in R2 (ctx.storage) and store a reference on the row.`)},ut=(n,i,o,c)=>{try{pe(n,o,...c)}catch(s){throw yr(s)?new de(`unique constraint violation on "${i}"`,"unique"):(Er(s,i),s)}},je=(n,i,o,c)=>{if(ut(n,i,o,c),pe(n,zo).one().changed===0)throw new de(`optimistic concurrency conflict on "${i}" — the row changed during this mutation; refetch and retry`,"occ")},sn=(n,i,o,c,s,w,_)=>{const S=[];for(let x=0;x<o.length+1;x+=1){const A=o[x],M=c[x],W=M?.direction==="desc"?"desc":"asc",D=A===void 0||M===void 0?a`${a.identifier(co)} < ${_}`:ao(A,w[x],W,!1);if(D===void 0)continue;const L=[];for(let G=0;G<x;G+=1)L.push(a`${a.identifier(o[G])} IS ${w[G]}`);L.push(D);const[F]=L;S.push(L.length===1&&F!==void 0?F:a`(${a.join(L,a` AND `)})`)}const C=S.length>0?a.join(S,a` OR `):a`1 = 0`,$=H(n,a`SELECT COUNT(*) AS c FROM ${a.identifier(i)} WHERE ${a.identifier("__partition__")} = ${s} AND (${C})`).one(),q=H(n,a`SELECT COUNT(*) AS c FROM ${a.identifier(i)} WHERE ${a.identifier("__partition__")} = ${s}`).one();return{before:$.c,total:q.c}},mr=n=>{const i=new Map;for(const[c,s]of Object.entries(n.tables))for(const w of Object.values(s.relationMap??{}))w.kind==="one"&&(w.onDelete==="cascade"||w.onDelete==="set null")&&i.set(w.table,[...i.get(w.table)??[],{holder:c,op:w.onDelete==="cascade"?"delete":"update"}]);const o=c=>{const s=new Set,w=[c];for(let _=w.pop();_!==void 0;_=w.pop())for(const{holder:S,op:C}of i.get(_)??[]){if(S===c||Qt(n,S,C))return!0;s.has(S)||(s.add(S),w.push(S))}return!1};return new Set(Object.entries(n.tables).filter(([c,s])=>s.shardMode?.kind==="global"||Qt(n,c,"delete")||o(c)).map(([c])=>c))},Sr=n=>{const i=new Map;for(const[o,c]of Object.entries(n.tables))c.softDeleteMode&&i.set(o,c.softDeleteMode.field);return i},si=n=>{const{baselineSeq:i,onStalePatchDropped:o}=n,{sql:c}=n,{schema:s}=n,w=n.broadcast??(()=>{}),_=wo(s),S=new Map;for(const e of _){const t=r=>(s.tables[r]?.shardMode?.kind??"root")==="root";!e.array&&t(e.sourceTable)&&t(e.targetTable)&&S.set(e.sourceTable,[...S.get(e.sourceTable)??[],e])}const C=(e,t,r)=>{for(const u of S.get(e)??[]){const f=t[u.column];if(typeof f!="string"||r?.[u.column]===f||u.targetTable===e&&t._id===f)continue;if(H(c,a`SELECT 1 FROM ${a.identifier(u.targetTable)} WHERE id = ${f} LIMIT 1`).toArray().length===0)throw new y("VALIDATION_ERROR",`${u.name} references ${u.targetTable} row "${f}", which does not exist`)}},$=$o(s,n.inTransaction),q=mr(s),x=Sr(s);let A;const M=()=>n.inTransaction?.()===!0,W=e=>s.tables[e]?.commitOrderedMode!==!0?{}:((A===void 0||!M())&&(A=Wn(c)),{[Bn]:A}),D=(e,...t)=>{const r=s.tables[e]?.indexes;if(!r||r.length===0)return;const u=[];for(const f of t)f&&u.push(...lo(r,f,Ce));return u.length>0?u:void 0},{headroom:L}=n;let F=!1;const G=async e=>{const t=F;F=!0;try{return await e()}finally{F=t}},se=n.onRead??(()=>{}),X=e=>{kt(s.tables[e])&&se(Ht,Ht)},m=n.onReadRange??(e=>{se(e.table,U)}),b=e=>{X(e.table),m(e)},T=(e,t)=>{t!==void 0&&t!==U&&!F&&L?.recordRead(1),X(e),se(e,t)},k=n.onIndexUse??(()=>{}),Z=n.onWrite??(()=>{}),N=e=>{F||L?.recordWrite(e)},J=async e=>{N(e.doc),await Z(e)},{cache:re}=n,ce=n.clock??(()=>Date.now()),pt=n.idGenerator??(()=>crypto.randomUUID()),gt=n.scheduler??Cn,{globalDb:ye}=n,$e=n.auth??{identity:null,userId:null},yt=n.cdc??!1,ze=gt,yn=_o({scheduler:typeof ze.list=="function"&&typeof ze.get=="function"?ze:void 0,storage:n.storage}),Ee=(e,t,r,u)=>{yt&&!kt(s.tables[e])&&Fn(c,ce(),e,t,r,u)},$t=(e,t,r,u)=>{const f=s.tables[e];if(f?.dropStalePatchesMode!==!0||!yt)return!1;const h=i?.();if(h===void 0)return!1;const d=qn(c,e,t,h);if(d===void 0)return!1;const l=Zn(f,r);return Object.keys(Ge(r)).some(p=>!l.has(p)&&Dt(qt(d,p))!==Dt(qt(u,p)))},ae=e=>s.tables[e]?.shardMode?.kind==="global",Et=(e,t)=>{if(ae(e)){if(!ye)throw new y("INTERNAL",`cross-backend ${t} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return ye}return P},Ye=e=>Et(e,"cascade"),j=(e,t)=>{if(ae(e)){if(!ye)throw new y("INTERNAL",`${t} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return ye}},mt=async(e,t,r,u,f)=>{f&&N(r);const h=await e.insert(t,r,u);return w({key:h,op:"insert",row:{...r,_id:h},table:t}),h},Xe=(e,t)=>Et(e,"relation load").findMany(e,t),St=(e,t)=>(ae(e)&&T(e,U),Xe(e,t)),$n=e=>!ae(e.table),Rt=n.relationExistsPushDown??"auto",Tt=Rt!=="never",{maxRelationKeys:_t}=n,be=(e,t,r)=>go(e,{fetcher:St,maxRelationKeys:_t,relationBaseWhere:r,schema:s,tableName:t}),vt=async(e,t,r,u)=>{const f=j(e,"relation grouped count");if(f)return T(e,U),So((E,O)=>f.count(E,O),e,t,r,u);const h=s.tables[e];if(!h)throw new y("INTERNAL",`unknown table: ${e}`);T(e,U);const d=ve(h.softDeleteMode,void 0),l={[t]:{in:r}},p=K(K(l,u),d),R=await be(p,e,void 0),I=Y(R,he),g=we(t);let v=a`SELECT ${g} AS __fk__, COUNT(*) AS count FROM ${a.identifier(e)}`;I&&(v=a`${v} WHERE ${I}`),v=a`${v} GROUP BY ${g}`;const B=H(c,v).toArray();return new Map(B.map(E=>[E.__fk__,E.count]))};let Me=0;const It=new Set;for(const[e,t]of Object.entries(s.tables))for(const r of Object.values(t.triggerMap??{}))It.add(`${e} ${r.timing} ${r.op}`);const ee=(e,t,r)=>It.has(`${e} ${t} ${r}`),te=async(e,t,r)=>{if(Me+=1,Me>Xt)throw Me-=1,new de(`trigger recursion exceeded ${String(Xt)} levels on "${r.table}" — check for a self-triggering write`,"trigger");try{await vo({ctx:Tn,event:r,op:t,schema:s,tableName:r.table,timing:e})}finally{Me-=1}},{ensureBackfilledForTable:me,ensureBackfilledIndex:Ze,ensureRankBackfilled:et,ensureRankBackfilledForTable:Se,syncAggregates:De,syncCompanionsForInsert:At,syncGeo:ke,syncRanks:Re,syncSearch:Le}=Pn({broadcast:w,indexKeysFor:(e,t)=>D(e,t),invalidateCache:(e,t,r)=>re?.invalidate(e,t,D(e,r)),recordCdc:Ee,schema:s,sql:c}),Ct=(e,t,r)=>{const{shardMode:u}=t;if(u?.kind==="shardBy"&&!(u.field!==void 0&&(r.partitionBy??[]).includes(u.field)))throw Object.assign(new Error(`rank index "${r.name}" on "${e}" partitions across shards (shard key "${u.field??"?"}" is not in partitionBy) — a shard-local rank()/rankPage() would be wrong; roll it up through the Query Coordinator instead`),{code:"CROSS_SHARD_RANK_UNSUPPORTED",name:"LunoraError",status:400})},xt=e=>Object.entries(s.tables).filter(([,t])=>t.shardMode?.kind!=="global").map(([t])=>t).filter(t=>e===void 0||t===e),Te=e=>e===void 0||ae(e)?ye:void 0,ne=(e,t)=>{const r=xt(t);for(let u=0;u<r.length;u+=_e){const f=r.slice(u,u+_e),[h]=pe(c,Xo(f),...Zo(e,f)).toArray();if(!h)continue;const d=h.__t__,l=Ie(h);if(typeof d!="string"||!l)return;const p=h[ie];return{docJson:typeof p=="string"?p:ue(p??{}),row:l,tableName:d}}},En=(e,t)=>{const r=[...new Set(e)],u=new Map;if(r.length===0)return u;const f=xt(t);for(let h=0;h<f.length;h+=_e){const d=f.slice(h,h+_e),l=Math.floor(_e/d.length),p=Kn(a`${a.identifier("id")}`,r,!1,l),R=d.map(I=>a`SELECT ${a.raw(`'${I.replaceAll("'","''")}'`)} AS __t__, id FROM ${a.identifier(I)} WHERE ${p}`);for(const I of H(c,ht(R))){const{id:g,__t__:v}=I;typeof v=="string"&&typeof g=="string"&&u.set(g,v)}}return u},bt={assertRankPartitionLocal:Ct,ensureRankBackfilled:et,onRead:T,rowToDocument:Ie,schema:s,sql:c},mn=(e,t,r)=>{const u=Y(r,he);return u===void 0||H(c,a`SELECT 1 FROM ${a.identifier(e)} WHERE ${a.identifier("id")} = ${t} AND ${u}`).toArray().length>0},Sn=(e,t,r,u)=>$t(e,t,r,u)?(o?.({fields:Object.keys(Ge(r)),id:t,table:e}),!0):!1,Rn=async(e,t,r,u,f)=>{const h=ne(t,e);if(!h)return{applied:!1,doc:null};if(T(e,t),!mn(e,t,r.where)||Sn(e,t,r.patch,h.row))return{applied:!1,doc:h.row};try{await f(r.patch)}catch(d){if(d instanceof de&&d.kind==="occ"&&u)return;throw d}return{applied:!0,doc:ne(t,e)?.row??null}},Mt=async(e,t,r,u)=>{const{fetchLimit:f,limit:h,orderKeys:d,predicate:l}=await yo(t,r,{canPushExists:Tt?$n:void 0,existsPushMode:Rt==="always"?"always":"auto",fetcher:St,maxRelationKeys:_t,schema:s,tableName:e}),p=Tt?fr(u):Ve,R=Y(l,p,Qe),I=ln(e,R,un(d),f);return{limit:h,orderKeys:d,statement:I}},P={system:yn,async aggregate(e,t){const r=j(e,"aggregate");if(r)return T(e,U),r.aggregate(e,t);const u=s.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);if(Be(t.op),t.op==="count")return P.count(e,{baseWhere:t.baseWhere,relationBaseWhere:t.relationBaseWhere,restrictsCounts:t.restrictsCounts,where:t.where});if(!t.field)throw new y("INTERNAL",`aggregate(${e}, { op: "${t.op}" }): "field" is required for non-count reducers`);T(e,U);const f=ve(u.softDeleteMode,void 0),h=K(K(t.baseWhere,t.where),f),d=await be(h,e,t.relationBaseWhere),l=d!==h;if(u.aggregateIndexes&&!t.baseWhere&&!l){const E=Dn(u.aggregateIndexes,t.op,t.field,t.where);if(E){Ze(e,E.index);const O=nt(E.index.by??[],E.key),oe=tt(e,E.index.name),z=H(c,a`SELECT ${Pe} AS value, ${it} AS count FROM ${a.identifier(oe)} WHERE ${Ue} = ${O}`).toArray()[0];return ot(t.op,z)}}en(u,t.field,`aggregate(${e}, { op: "${t.op}", field: "${t.field}" })`);const p=Y(d,he),R=Be(t.op),I=we(t.field);let g=a`SELECT ${a.raw(R)}(${I}) AS value FROM ${a.identifier(e)}`;p&&(g=a`${g} WHERE ${p}`);const B=H(c,g).toArray()[0]?.value;return B??null},asId(e,t){const r=tn(s,e,t);if(r===null)throw new y("BAD_REQUEST",`asId("${e}", …): "${t}" is not a valid id for table "${e}"`,{status:400});return r},async count(e,t){const r=j(e,"count");if(r)return T(e,U),r.count(e,t);const u=s.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);const f=xn(t);if(f.restrictsCounts)throw new rt(e);T(e,U);const h=ve(u.softDeleteMode,void 0),d=K(K(f.baseWhere,f.where),h),l=await be(d,e,f.relationBaseWhere),p=l!==d;if(u.aggregateIndexes&&!f.baseWhere&&!p){const v=Mn(u.aggregateIndexes,f.where);if(v){Ze(e,v.index);const B=nt(v.index.by??[],v.key),E=tt(e,v.index.name),O=H(c,a`SELECT ${Pe} AS value FROM ${a.identifier(E)} WHERE ${Ue} = ${B}`).toArray();return O[0]===void 0?0:O[0].value??0}}const R=Y(l,he);let I=a`SELECT COUNT(*) AS count FROM ${a.identifier(e)}`;return R&&(I=a`${I} WHERE ${R}`),H(c,I).one().count},async delete(e,t,r){const u=ne(e,t);if(!u){const g=Te(t);g&&(N(void 0),await g.delete(e,t,r));return}const{docJson:f,row:h,tableName:d}=u,l=s.tables[d],p=r?.hard===!0,R=!p&&l?.softDeleteMode?l:void 0,I=R?.softDeleteMode?.field;if(!(I&&h[I]!==null&&h[I]!==void 0)){if(ee(d,"before","delete")&&await te("before","delete",{id:e,op:"delete",previous:h,table:d}),await mo({deletedId:e,deletedReference:g=>h[g],findHolders:async(g,v,B)=>(await Ye(g).findMany(g,{includeDeleted:p,where:{[v]:B}})).page,onCascade:(g,v)=>Ye(g).delete(v,void 0,r),onRestrict:g=>{throw new de(g,"restrict")},onSetNull:(g,v,B)=>Ye(g).patch(v,{[B]:null}),schema:s,tableName:d}),me(d),Se(d),R&&I){const g={[I]:ce()},v={...h,...W(d),...g,_id:e};at(R,g,v,$e),je(c,d,zt(d),[ue(v),e,f]),Le(d,e,v,h),ke(d,e,void 0),De(d,h,v),Re(d,e,h,void 0),re?.invalidate(d,e,D(d,h,v)),Ee(d,e,"update",v),w({indexKeys:D(d,h,v),key:e,op:"update",row:v,table:d}),ee(d,"after","delete")&&await te("after","delete",{id:e,op:"delete",previous:h,table:d}),await J({id:e,op:"delete",table:d});return}je(c,d,Jo(d),[e,f]),Le(d,e,void 0),ke(d,e,void 0),De(d,h,void 0),Re(d,e,h,void 0),re?.invalidate(d,e,D(d,h)),Ee(d,e,"delete"),w({indexKeys:D(d,h),key:e,op:"delete",table:d}),ee(d,"after","delete")&&await te("after","delete",{id:e,op:"delete",previous:h,table:d}),await J({id:e,op:"delete",table:d})}},async deleteAll(e,t){if(!s.tables[e])throw new y("INTERNAL",`unknown table: ${e}`);const r=Math.max(1,t?.chunkSize??hn),u=t?.hard===void 0?void 0:{hard:t.hard},f=ae(e)?void 0:e;let h=0;return await G(async()=>{for(;;){const l=(await P.findMany(e,{limit:r})).page.map(p=>String(p._id));if(l.length===0)break;for(const p of l)await P.delete(p,f,u),h+=1;if(l.length<r)break}}),{deleted:h}},async deleteMany(e,t,r){fe(e.length,t?.limit,"deleteMany");for(const u of e)await P.delete(u,r);return{deleted:e.length}},async deleteWhere(e,t,r){const h=(await(j(e,"deleteWhere")??P).findMany(e,{where:t})).page.map(d=>String(d._id));if(fe(h.length,r?.limit,"deleteWhere"),P.deleteMany===void 0)throw new y("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return P.deleteMany(h,r)},async findFirst(e,t={}){return(await P.findMany(e,{...t,limit:1,omitContinueCursor:!0})).page[0]??null},async findFirstOrThrow(e,t={}){const r=await P.findFirst(e,t);if(r===null)throw new zn(`findFirstOrThrow: no "${e}" document matched`);return r},async findMany(e,t={}){const r=j(e,"findMany");if(r)return T(e,U),r.findMany(e,t);const u=s.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);const f=!t.where&&!t.baseWhere;f?T(e,U):T(e);const{limit:h,orderKeys:d,statement:l}=await Mt(e,u,t,T),p=pe(c,l.text,...l.params).toArray();f&&!F&&L?.recordRead(p.length);const R=[];for(const B of p){const E=Ie(B);E&&(R.push(E),!f&&typeof E._id=="string"&&T(e,E._id))}if(h===void 0)return t.with&&await Kt({groupedCounter:vt,fetcher:Xe,parents:R,...Nt(t),schema:s,tableName:e,with:t.with}),{continueCursor:null,isDone:!0,page:Pt(R,t.select,t.with)};const I=R.length>h,g=I?R.slice(0,h):R,v=g.at(-1);return t.with&&await Kt({fetcher:Xe,groupedCounter:vt,parents:g,...Nt(t),schema:s,tableName:e,with:t.with}),{continueCursor:I&&v&&t.omitContinueCursor!==!0?Ke(v,d):null,isDone:!I,page:Pt(g,t.select,t.with)}},async explain(e,t={}){const r=j(e,"explain");if(r)return r.explain(e,t);const u=s.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);const{statement:f}=await Mt(e,u,t,()=>{}),h=pe(c,`EXPLAIN QUERY PLAN ${f.text}`,...f.params).toArray();return{params:f.params,plan:h.map(d=>String(d.detail)),sql:f.text}},async get(e,t){const r=ne(e,t);if(!r){const u=Te(t);return u?u.get(e,t):null}return T(r.tableName,e),r.row},async lookupById(e,t){const r=ne(e,t);return r?(T(r.tableName,e),{row:r.row,tableName:r.tableName}):null},async groupBy(e,t){const r=j(e,"groupBy");if(r)return T(e,U),r.groupBy(e,t);const u=s.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);T(e,U);const f=t.agg??{op:"count"};if(Be(f.op),f.op!=="count"&&!f.field)throw new y("INTERNAL",`groupBy(${e}, { agg: { op: "${f.op}" } }): "field" is required for non-count reducers`);const h=ve(u.softDeleteMode,void 0),d=K(K(t.baseWhere,t.where),h),l=await be(d,e,t.relationBaseWhere),p=l!==d;if(u.aggregateIndexes&&!t.baseWhere&&!p){const E=bn(u.aggregateIndexes,f.op,f.field,t.by,t.where),O=E===void 0?0:Object.keys(E.partial).length,oe=E?.index.by?.length??0;if(E&&(O===0||O===oe)){Ze(e,E.index);const z=tt(e,E.index.name),Q=Object.keys(E.partial),le=[];if(Q.length===(E.index.by??[]).length&&Q.length>0){const Fe=nt(E.index.by??[],E.partial),qe=H(c,a`SELECT ${Pe} AS value, ${it} AS count FROM ${a.identifier(z)} WHERE ${Ue} = ${Fe}`).toArray();return qe.length>0&&le.push({key:{...E.partial},value:ot(f.op,qe[0])}),le}const _n=H(c,a`SELECT ${Ue} AS key, ${Pe} AS value, ${it} AS count FROM ${a.identifier(z)}`).toArray();for(const Fe of _n){const qe=An(JSON.parse(Fe.key));le.push({key:qe,value:ot(f.op,Fe)})}return le}}for(const E of[...t.by,f.field]){if(E===void 0)continue;const O=E===f.field?`groupBy(${e}, { agg: { op: "${f.op}", field: "${E}" } })`:`groupBy(${e}, { by: [..."${E}"] })`;en(u,E,O)}const R=Y(l,he),I=t.by.map(E=>a`${we(E)} AS ${a.identifier(E)}`);if(f.op==="count")I.push(a`COUNT(*) AS value`);else{const{field:E}=f;if(E===void 0)throw new y("INTERNAL",`groupBy(${e}, { agg: { op: "${f.op}" } }): "field" is required for non-count reducers`);I.push(a`${a.raw(Be(f.op))}(${we(E)}) AS value`)}let g=a`SELECT ${a.join(I,a`, `)} FROM ${a.identifier(e)}`;R&&(g=a`${g} WHERE ${R}`),g=a`${g} GROUP BY ${a.join(t.by.map(E=>we(E)),a`, `)}`;const v=H(c,g).toArray(),B=[];for(const E of v){const O={};for(const z of t.by)O[z]=On(u.shape[z],E[z]??null);const{value:oe}=E;B.push({key:O,value:oe==null?null:Number(oe)})}return B},async insert(e,t,r){const u=j(e,"insert");if(u)return mt(u,e,t,r,!0);const f=s.tables[e];if(!f)throw new y("INTERNAL",`unknown table: ${e}`);const h=r?.allowExplicitId===!0,d=Oe(f,jt(f,t,$e),{supplied:t,trusted:h});let l;r?.clientId!==void 0?(tr(r.clientId),l=r.clientId):r?.allowExplicitId&&typeof d._id=="string"?l=d._id:l=pt();const p=r?.allowExplicitId&&typeof d._creationTime=="number"?d._creationTime:ce(),R={...d,...W(e),_creationTime:p,_id:l};return ee(e,"before","insert")&&await te("before","insert",{doc:{...R},id:l,op:"insert",table:e}),h||C(e,R),me(e),Se(e),ut(c,e,Qo(e),[l,p,ue(R)]),At(e,l,R),ee(e,"after","insert")&&await te("after","insert",{doc:R,id:l,op:"insert",table:e}),await J({doc:R,id:l,op:"insert",table:e}),l},async insertManyUnsafe(e,t,r){if(fe(t.length,r?.limit,"insertManyUnsafe"),t.length===0)return[];const u=j(e,"insert");if(u){const p=[];for(const R of t)N(R);for(const R of t){const I=await u.insert(e,R,{allowExplicitId:r?.allowExplicitId});w({key:I,op:"insert",row:{...R,_id:I},table:e}),p.push(I)}return p}const f=s.tables[e];if(!f)throw new y("INTERNAL",`unknown table: ${e}`);me(e),Se(e);const h=[];for(let p=0;p<t.length;p+=He)h.push(W(e));const d=r?.allowExplicitId===!0?void 0:Eo(f),l=t.map((p,R)=>{const I=jt(f,p,$e),g=d===void 0?I:Oe(d,I,{supplied:p}),v=r?.allowExplicitId===!0&&typeof g._id=="string"?g._id:pt(),B=r?.allowExplicitId===!0&&typeof g._creationTime=="number"?g._creationTime:ce(),E={...g,...h[Math.floor(R/He)],_creationTime:B,_id:v};return{creationTime:B,document:E,id:v}});for(const p of l)N(p.document);for(let p=0;p<l.length;p+=He){const R=a.join(l.slice(p,p+He).map(g=>a`(${g.id}, ${g.creationTime}, ${ue(g.document)})`),a`, `),I=an("sqlite",a`INSERT INTO ${a.identifier(e)} (id, _creationTime, ${a.identifier(ie)}) VALUES ${R}`);ut(c,e,I.sql,I.params)}for(const{document:p,id:R}of l)At(e,R,p),await Z({doc:p,id:R,op:"insert",table:e});return l.map(p=>p.id)},async insertMany(e,t,r){fe(t.length,r?.limit,"insertMany");const u=r?.skipDuplicates===!0,f=[],h=j(e,"insert");if(h)for(const l of t)N(l);const d=async l=>h?mt(h,e,l,void 0,!1):P.insert(e,l);for(const l of t)try{f.push(await d(l))}catch(p){if(u&&p instanceof de&&p.kind==="unique")f.push(null);else throw p}return f},normalizeId(e,t){return tn(s,e,t)},async patch(e,t,r,u){const f=ne(e,r);if(!f){const v=Te(r);if(v){N(t),await v.patch(e,t,r,u);return}throw new y("NOT_FOUND",`document not found: ${e}`)}const{docJson:h,row:d,tableName:l}=f,p=s.tables[l];if(!p)throw new y("INTERNAL",`unknown table: ${l}`);if(T(l,e),on("patch",t),$t(l,e,t,d)){o?.({fields:Object.keys(Ge(t)),id:e,table:l});return}const R=Yn(p,t,d),I={...d,...Ge(R),...W(l),_id:e};at(p,R,I,$e);const g=Oe(p,I,{only:new Set(Object.keys(R)),previous:()=>d,tolerateStoredNull:!0});Xn(u,d,g),ee(l,"before","update")&&await te("before","update",{doc:{...g},id:e,op:"update",previous:d,table:l}),C(l,g,d),me(l),Se(l),je(c,l,zt(l),[ue(g),e,h]),Le(l,e,g,d),ke(l,e,g),De(l,d,g),Re(l,e,d,g),re?.invalidate(l,e,D(l,d,g)),Ee(l,e,"update",g),w({indexKeys:D(l,d,g),key:e,op:"update",row:g,table:l}),ee(l,"after","update")&&await te("after","update",{doc:g,id:e,op:"update",previous:d,table:l}),await J({doc:g,id:e,op:"update",table:l})},async patchIf(e,t,r){const u=j(e,"patchIf");if(u){if(u.patchIf===void 0)throw new y("INTERNAL",`ctx.db.patchIf on global table '${e}' is unsupported: its backend has no conditional write`);return N(r.patch),u.patchIf(e,t,r)}if(!s.tables[e])throw new y("INTERNAL",`unknown table: ${e}`);for(let f=1;f<=nn;f+=1){const h=await Rn(e,t,r,f<nn,d=>P.patch(t,d,e,{verify:r.verify}));if(h!==void 0)return h}throw new de(`patchIf on "${e}" kept conflicting; the row changed on every attempt`,"occ")},async patchMany(e,t,r){fe(e.length,t?.limit,"patchMany");for(const u of e)await P.patch(u.id,u.patch,r);return{patched:e.length}},async patchWhere(e,t,r){const h=(await(j(e,"patchWhere")??P).findMany(e,{where:t.where})).page.map(d=>({id:String(d._id),patch:t.patch}));if(fe(h.length,r?.limit,"patchWhere"),P.patchMany===void 0)throw new y("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await P.patchMany(h,r),{patched:h.length}},async related(e,t){return po(P,_,e,t)},relationEdges:_,deleteRereadTables:q,inTransaction:M,softDeleteFields:x,relationWrites:$,query(e){const t=j(e,"query");return t?(T(e,U),t.query(e)):gn(c,s,e,k,r=>{r?b(r):T(e,U)},r=>{F||L?.recordRead(r)})},async rank(e,t,r){const u=j(e,"rank");if(u)return T(e,U),u.rank(e,t,r);k(e,t,"rank");const f=s.tables[e];if(!f)throw new y("INTERNAL",`unknown table: ${e}`);const h=f.rankIndexes?.find(Q=>Q.name===t);if(!h)throw new y("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(Ct(e,f,h),r.restrictsCounts)throw new rt(e);T(e,U),et(e,h);const d=typeof r.row=="string"?r.row:r.row._id;if(!d)return null;const l=Ut(e,h.name),p=h.sortBy.map((Q,le)=>Ot(le)),R=p.map(Q=>xe(Q)).join(", "),I=H(c,a`SELECT ${a.identifier("__partition__")}, ${a.raw(R)} FROM ${a.identifier(l)} WHERE ${a.identifier("__id__")} = ${d}`).toArray(),[g]=I;if(g===void 0)return null;let v=g.__partition__;const B=K(r.baseWhere,r.where);st(B,s,e,"rank");const E=io(h,B);if(E){const Q=so(h.partitionBy??[],E);if(Q!==v)return null;v=Q}const O=p.map(Q=>g[Q]),{before:oe,total:z}=sn(c,l,p,h.sortBy,v,O,d);return{position:oe+1,total:z}},async rankBefore(e,t,r){if(ae(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 u=s.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);const f=u.rankIndexes?.find(p=>p.name===t);if(!f)throw new y("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(r.restrictsCounts)throw new rt(e);T(e,U),et(e,f);const h=Ut(e,f.name),d=f.sortBy.map((p,R)=>Ot(R)),l=f.sortBy.map((p,R)=>Ce(r.sortValues[R]??null));return sn(c,h,d,f.sortBy,r.partitionKey,l,r.rowId)},async rankPage(e,t,r={}){st(K(r.baseWhere,r.where),s,e,"rankPage");const u=j(e,"rankPage");if(u)return T(e,U),u.rankPage(e,t,r);k(e,t,"rank");const{continueCursor:f,hasMore:h,rows:d}=Lt(bt,e,t,r);return{continueCursor:f,isDone:!h,page:d.map(l=>l.doc)}},async rankPageRows(e,t,r={}){st(K(r.baseWhere,r.where),s,e,"rankPage"),k(e,t,"rank");const{directions:u,hasMore:f,rows:h}=Lt(bt,e,t,r);return{directions:u,hasMore:f,rows:h}},async restore(e,t){const r=ne(e,t);if(!r){const h=Te(t);if(h?.restore){await h.restore(e,t);return}throw new y("NOT_FOUND",`document not found: ${e}`)}const u=s.tables[r.tableName]?.softDeleteMode?.field;if(!u)throw new y("INTERNAL",`ctx.db.restore: table "${r.tableName}" is not a .softDelete() table`);const f=r.row[u]!==null&&r.row[u]!==void 0;await P.patch(e,{[u]:null},t),f&&Re(r.tableName,e,void 0,r.row)},async replace(e,t,r,u){const f=ne(e,r);if(!f){const O=Te(r);if(O){N(t),await O.replace(e,t,r,u);return}throw new y("NOT_FOUND",`document not found: ${e}`)}const{docJson:h,row:d,tableName:l}=f,p=s.tables[l];if(!p)throw new y("INTERNAL",`unknown table: ${l}`);on("replace",t);const R=u?.allowExplicitId&&typeof t._creationTime=="number"?t._creationTime:void 0,I=typeof d._creationTime=="number"?d._creationTime:void 0,g=R??I??ce(),v={...t,...W(l),_creationTime:g,_id:e};at(p,t,v,$e);const B=u?.allowExplicitId===!0,E=Oe(p,v,{previous:()=>d,supplied:t,trusted:B});ee(l,"before","update")&&await te("before","update",{doc:{...E},id:e,op:"update",previous:d,table:l}),B||C(l,E,d),me(l),Se(l),je(c,l,Vo(l),[g,ue(E),e,h]),Le(l,e,E,d),ke(l,e,E),De(l,d,E),Re(l,e,d,E),re?.invalidate(l,e,D(l,d,E)),Ee(l,e,"update",E),w({indexKeys:D(l,d,E),key:e,op:"update",row:E,table:l}),ee(l,"after","update")&&await te("after","update",{doc:E,id:e,op:"update",previous:d,table:l}),await J({doc:E,id:e,op:"update",table:l})},async wipeShard(e){const t=new Set(e?.exclude),r=e?.tables,u=Object.entries(s.tables).filter(([l,p])=>t.has(l)||r!==void 0&&!r.includes(l)?!1:p.shardMode?.kind!=="global").map(([l])=>l);if(r!==void 0){for(const l of r)if(!s.tables[l])throw new y("INTERNAL",`wipeShard: unknown table: ${l}`)}const f={};let h=0;const{deleteAll:d}=P;if(d===void 0)throw new y("INTERNAL","wipeShard: this writer has no deleteAll");for(const l of u){const p=await d(l,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});f[l]=p.deleted,h+=p.deleted}return{deleted:h,tables:f}}},Tn={db:P,scheduler:gt};return n.enforceRls===!0?Ro(P,s,(e,t)=>ne(e,t)?.tableName,(e,t)=>En(e,t),_):P};export{hi as CDC_LOG_TABLE,Fi as IDEMPOTENCY_TABLE,hr as NotUniqueError,Mi as advanceClientWatermark,wi as applyCdcChanges,on as assertNoExplicitUndefined,tr as assertValidClientId,di as backfillAggregateIndexes,li as backfillRankIndexes,ui as backfillSearchIndexes,pi as bumpCdcEpoch,gi as cdcCanVouchFor,yi as cdcForkedError,$i as cdcSeqLeavingRows,Ei as cdcTouchesTables,mi as cdcTrimmedError,Si as compactCdcDocs,si as createShardCtxDb,Ri as cursorBelowRetainedFloor,Di as migrateClientWatermark,Ti as minCdcReplayableSeq,_i as minCdcSeq,tn as normalizeIdStructurally,vi as readCdcChangeKeys,Ii as readCdcChanges,Ai as readCdcCursor,Ci as readCdcEpoch,ki as readClientWatermark,qi as readIdempotent,Ui as runShardMigrations,Hi as selectShapeMembers,Gi as selectShapeRows,Ge as stripReservedPatchFields,xi as trimCdcChanges,Wi as trimIdempotent,Bi as writeIdempotent};
@@ -0,0 +1,17 @@
1
+ import{runSql as o,orNull as a,decodeJsonColumn as _}from"./runDrizzle-RC09zZrh.mjs";const s="__lunora_queue_messages",n=500,E=128*1024,T="… [truncated by the dev queue catcher]",c="[unserializable message body]",R=e=>{if(e===void 0)return"null";try{const r=JSON.stringify(e);return r.length>E?JSON.stringify(`${r.slice(0,E)}${T}`):r}catch{return JSON.stringify(c)}},g=e=>typeof e=="string"&&(e===c||e.endsWith(T)),u=e=>{o(e,`CREATE TABLE IF NOT EXISTS "${s}" (
2
+ id TEXT PRIMARY KEY,
3
+ captured_at INTEGER NOT NULL,
4
+ message_id TEXT NOT NULL,
5
+ queue TEXT NOT NULL,
6
+ export_name TEXT,
7
+ body TEXT NOT NULL,
8
+ attempts INTEGER NOT NULL,
9
+ outcome TEXT NOT NULL,
10
+ error TEXT,
11
+ dead_lettered INTEGER NOT NULL,
12
+ message_ts INTEGER NOT NULL
13
+ )`)},p=(e,r,d)=>{u(e);for(const t of r)o(e,`INSERT INTO "${s}" (id, captured_at, message_id, queue, export_name, body, attempts, outcome, error, dead_lettered, message_ts)
14
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,crypto.randomUUID(),d,t.messageId,t.queue,a(t.exportName),R(t.body),t.attempts,t.outcome,a(t.error),t.deadLettered===!0?1:0,t.timestamp);return o(e,`DELETE FROM "${s}"
15
+ WHERE id NOT IN (
16
+ SELECT id FROM "${s}" ORDER BY captured_at DESC, id DESC LIMIT ?
17
+ )`,n),{recorded:r.length}},i=e=>({attempts:e.attempts,body:_(e.body),capturedAt:e.captured_at,deadLettered:e.dead_lettered===1,error:e.error??void 0,exportName:e.export_name??void 0,id:e.id,messageId:e.message_id,outcome:e.outcome,queue:e.queue,timestamp:e.message_ts}),y=(e,r={})=>{u(e);const d=Math.min(Math.max(r.limit??100,1),n),t=typeof r.queue=="string"&&r.queue.length>0?r.queue:void 0,m=t===void 0?"":"WHERE queue = ?",N=t===void 0?[d]:[t,d];return{entries:o(e,`SELECT * FROM "${s}" ${m} ORDER BY captured_at DESC, id DESC LIMIT ?`,...N).toArray().map(L=>i(L))}},S=(e,r)=>{u(e);const t=o(e,`SELECT * FROM "${s}" WHERE id = ? LIMIT 1`,r).toArray()[0];return t===void 0?void 0:i(t)},U=e=>(u(e),o(e,`DELETE FROM "${s}"`),{cleared:!0});export{E as MAX_BODY_CHARS,n as QUEUE_RETENTION,s as QUEUE_TABLE,U as clearQueueMessages,u as ensureQueueTable,g as isLossyBody,S as readQueueMessageById,y as readQueueMessages,p as recordQueueMessages};
@@ -0,0 +1 @@
1
+ import{sql as s}from"drizzle-orm";import{matchesStaticWhere as f}from"./AGGREGATE_SQL_FUNCTION-C_ZipS9R.mjs";import{compareStrings as l}from"./aggregateTableName-B_CtIQCS.mjs";import{serializeSqlValue as d}from"./serializeSqlValue-DeoBMpZ2.mjs";const a=Symbol("not-resolvable"),m=r=>{if(r!==null&&typeof r=="object"&&!Array.isArray(r)){const t=Object.keys(r);return t.length===1&&t[0]==="eq"?r.eq:a}return r},y=(r,t)=>{if(r.length===0)return"";const e={};for(const n of r.toSorted(l))e[n]=t[n]??null;return JSON.stringify(e)},k="__id__",N=r=>`__sort_k${String(r)}__`,h=(r,t)=>{const e=r.partitionBy??[],n=t??{};for(const o of Object.keys(n))if(o==="AND"||o==="OR"||o==="NOT")return;const i={};for(const o of e)if(o in n){const c=m(n[o]);if(c===a)return;i[o]=c}else if(r.where&&o in r.where)i[o]=r.where[o];else return;return i},O=(r,t)=>`${r}__rank_${t}`,$=(r,t)=>({partitionKey:y(r.partitionBy??[],t),rowId:t._id,sortValues:r.sortBy.map(e=>d(t[e.field]??null))}),K=(r,t,e,n)=>{const i=e!=="desc"===n;if(t==null)return i?s`${s.identifier(r)} IS NOT NULL`:void 0;const o=s`${s.identifier(r)} ${s.raw(i?">":"<")} ${t}`;return i?o:s`(${o} OR ${s.identifier(r)} IS NULL)`},R=f;export{k as RANK_TIEBREAK,y as encodePartitionKey,R as matchesRankStaticWhere,$ as rankKeyFromDoc,K as rankPivotConditionSql,O as rankTableName,h as resolveRankPartition,N as sortColumnName};
@@ -0,0 +1,28 @@
1
+ import{sql as t}from"drizzle-orm";import{runDrizzle as o}from"./runDrizzle-RC09zZrh.mjs";const a="__reactor_state",c=[["runs","runs INTEGER NOT NULL DEFAULT 0"],["suppressed","suppressed INTEGER NOT NULL DEFAULT 0"],["errors","errors INTEGER NOT NULL DEFAULT 0"],["last_ran_at","last_ran_at INTEGER NOT NULL DEFAULT 0"],["last_error","last_error TEXT"]],O=r=>{o(r,t`CREATE TABLE IF NOT EXISTS ${t.identifier(a)} (
2
+ path TEXT PRIMARY KEY,
3
+ digest TEXT NOT NULL,
4
+ tables TEXT NOT NULL,
5
+ runs INTEGER NOT NULL DEFAULT 0,
6
+ suppressed INTEGER NOT NULL DEFAULT 0,
7
+ errors INTEGER NOT NULL DEFAULT 0,
8
+ last_ran_at INTEGER NOT NULL DEFAULT 0,
9
+ last_error TEXT
10
+ )`);const e=new Set(o(r,t`PRAGMA table_info(${t.identifier(a)})`).toArray().map(s=>s.name));for(const[s,i]of c)e.has(s)||o(r,t`ALTER TABLE ${t.identifier(a)} ADD COLUMN ${t.raw(i)}`)},R=r=>{if(typeof r=="string")try{const e=JSON.parse(r);return Array.isArray(e)&&e.every(s=>typeof s=="string")?e:void 0}catch{return}},T=r=>typeof r=="number"&&Number.isFinite(r)?r:0,d=r=>({digest:r.digest,...typeof r.last_error=="string"&&r.last_error.length>0?{lastError:r.last_error}:{},lastRanAt:T(r.last_ran_at),stats:{errors:T(r.errors),runs:T(r.runs),suppressed:T(r.suppressed)},tables:R(r.tables)}),l="path, digest, tables, runs, suppressed, errors, last_ran_at, last_error",f=(r,e)=>{const[s]=o(r,t`SELECT ${t.raw(l)} FROM ${t.identifier(a)} WHERE path = ${e}`);if(!(s===void 0||typeof s.digest!="string"))return d(s)},U=r=>o(r,t`SELECT ${t.raw(l)} FROM ${t.identifier(a)} ORDER BY path`).toArray().filter(e=>typeof e.digest=="string").map(e=>({path:e.path,state:d(e)})),g=(r,e,s)=>{const{digest:i,error:p,now:u,result:n,tables:E}=s,L=i??"",N=E===void 0?"":JSON.stringify([...E]),_=p??null;o(r,t`INSERT INTO ${t.identifier(a)} (path, digest, tables, runs, suppressed, errors, last_ran_at, last_error)
11
+ VALUES (
12
+ ${e},
13
+ ${L},
14
+ ${N},
15
+ ${n==="ran"?1:0},
16
+ ${n==="suppressed"?1:0},
17
+ ${n==="error"?1:0},
18
+ ${u},
19
+ ${_}
20
+ )
21
+ ON CONFLICT(path) DO UPDATE SET
22
+ digest = ${i===void 0?t.raw(`${a}.digest`):t`excluded.digest`},
23
+ tables = ${E===void 0?t.raw(`${a}.tables`):t`excluded.tables`},
24
+ runs = ${t.raw(`${a}.runs`)} + ${n==="ran"?1:0},
25
+ suppressed = ${t.raw(`${a}.suppressed`)} + ${n==="suppressed"?1:0},
26
+ errors = ${t.raw(`${a}.errors`)} + ${n==="error"?1:0},
27
+ last_ran_at = excluded.last_ran_at,
28
+ last_error = ${n==="error"?t`excluded.last_error`:t.raw("NULL")}`)},S=(r,e)=>r?.tables===void 0?!0:r.tables.some(s=>e.has(s));export{a as REACTOR_STATE_TABLE,U as listReactorStates,O as migrateReactorState,S as reactorNeedsRun,f as readReactorState,g as writeReactorState};
@@ -0,0 +1 @@
1
+ import{LunoraError as h}from"@lunora/errors";import{mergeWhere as I}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{decodeCursor as S,CURSOR_PREFIX as v,toBase64 as B}from"./CURSOR_PREFIX-6offuG6M.mjs";const O=4,C=1,L=50,$=200,T=1e4,x=.5,D=t=>{if(t.kind==="id"){const e=t._meta?.tableName;return typeof e=="string"&&e.length>0?{array:!1,targetTable:e}:void 0}if(t.kind!=="array"&&t.kind!=="optional")return;const n=t._meta?.inner,r=n===void 0?void 0:D(n);if(r!==void 0)return{array:r.array||t.kind==="array",targetTable:r.targetTable}},j=t=>{const n=[];for(const[r,e]of Object.entries(t.tables))for(const[s,o]of Object.entries(e.shape)){const a=D(o);a===void 0||t.tables[a.targetTable]===void 0||n.push({array:a.array,column:s,name:`${r}.${s}`,sourceTable:r,targetTable:a.targetTable})}return n},U=t=>v+B(JSON.stringify([t])),M=t=>{const[n]=S(t);if(typeof n!="number"||!Number.isInteger(n)||n<0)throw new h("BAD_REQUEST","invalid cursor");if(n>T)throw new h("BAD_REQUEST",`ctx.db.related: cursor offset ${String(n)} exceeds the maximum of ${String(T)} — narrow the walk with \`edges\` or \`direction\` instead of paging past it`);return n},k=(t,n,r,e)=>{if(t===void 0)return n;if(!Number.isInteger(t)||t<1||t>r)throw new h("BAD_REQUEST",`ctx.db.related: \`${e}\` must be an integer between 1 and ${String(r)}, got ${String(t)}`);return t},N=(t,n)=>{if(n===void 0)return[...t];const r=new Set(t.map(o=>o.name)),e=n.filter(o=>!r.has(o));if(e.length>0)throw new h("BAD_REQUEST",`ctx.db.related: unknown edge ${e.length===1?"name":"names"}: ${e.join(", ")}`);const s=new Set(n);return t.filter(o=>s.has(o.name))},W=(t,n)=>{const r=t[n.column];return n.array?Array.isArray(r)?r.filter(e=>typeof e=="string"&&e.length>0):[]:typeof r=="string"&&r.length>0?[r]:[]},A=async(t,n,r,e)=>{const s=await t.findMany(n,{limit:e.limit,omitContinueCursor:!0,where:I(r,e.relationBaseWhere?.(n))??r});return e.mask?.(n,s.page)??s.page},F={in:{keyColumn:t=>t.column,keysOf:(t,n)=>n.array||t.table!==n.targetTable?[]:[t.id],skipVisitedKeys:!1,table:t=>t.sourceTable},out:{keyColumn:()=>"_id",keysOf:(t,n)=>t.table===n.sourceTable?W(t.document,n):[],skipVisitedKeys:!0,table:t=>t.targetTable}},_=async(t,n,r,e,s)=>{const o=F[s],a=o.keyColumn(r),l=o.table(r),u=new Map;for(const c of n)for(const i of o.keysOf(c,r))!u.has(i)&&!(o.skipVisitedKeys&&e.visited.has(i))&&u.set(i,c);if(u.size===0)return[];const f=await A(t,l,{[a]:{in:[...u.keys()]}},e),m=[];for(const c of f){const i=c._id,g=c[a],d=typeof g=="string"?u.get(g):void 0;typeof i!="string"||d===void 0||e.visited.has(i)||(e.visited.add(i),m.push({document:c,id:i,path:[...d.path,r.name],pathIds:[...d.pathIds,i],table:l}))}return m},Q=async(t,n,r,e)=>{const s=[],o=()=>e.budget-s.length,a=()=>({limit:o(),mask:e.mask,relationBaseWhere:e.relationBaseWhere,visited:e.visited});for(const l of r)e.direction!=="in"&&o()>0&&s.push(...await _(t,n,l,a(),"out")),e.direction!=="out"&&o()>0&&s.push(...await _(t,n,l,a(),"in"));return s},H=async(t,n)=>{const r=n._id;if(typeof r=="string"&&r.length>0){const o=await t.lookupById?.(r);if(!o)throw new h("BAD_REQUEST","ctx.db.related: could not resolve the start document's table from its `_id` — pass `{ table, id }` instead");return{id:r,table:o.tableName}}const{id:e,table:s}=n;if(typeof s!="string"||s.length===0||typeof e!="string"||e.length===0)throw new h("BAD_REQUEST","ctx.db.related: `start` must be a loaded document or `{ table, id }`");return{id:e,table:s}},V=async(t,n,r,e={})=>{const s=k(e.depth,C,O,"depth"),o=k(e.limit,L,$,"limit"),a=e.cursor?M(e.cursor):0,l=e.direction??"both",u=N(n,e.edges),{id:f,table:m}=await H(t,r),[c]=await A(t,m,{_id:f},{limit:1,mask:e.relationMask,relationBaseWhere:e.relationBaseWhere,visited:new Set});if(c===void 0)throw new h("NOT_FOUND",`ctx.db.related: no "${m}" row with id ${f}`);const i=a+o+1,g=new Set([f]),d=[];let w=[{document:c,id:f,path:[],pathIds:[f],table:m}];for(let b=1;b<=s&&w.length>0&&d.length<i;b+=1){const p=await Q(t,w,u,{budget:i-d.length,direction:l,mask:e.relationMask,relationBaseWhere:e.relationBaseWhere,visited:g}),R=x**(b-1);for(const y of p)d.push({depth:b,document:y.document,path:y.path,pathIds:y.pathIds,score:R,table:y.table});w=p}const E=d.length<=a+o;return{continueCursor:E?null:U(a+o),isDone:E,nodes:d.slice(a,a+o)}};export{L as RELATED_DEFAULT_LIMIT,x as RELATED_DEPTH_DECAY,O as RELATED_MAX_DEPTH,$ as RELATED_MAX_LIMIT,T as RELATED_MAX_OFFSET,j as deriveRelationEdges,V as findRelated};
@@ -0,0 +1 @@
1
+ const E=Symbol("lunora.seekRange"),o="__relationExists";export{o as RELATION_EXISTS_KEY,E as SEEK_RANGE};
@@ -0,0 +1 @@
1
+ const a=(n,t)=>{const r=Math.max(n.length,t.length);let o=n.length^t.length;for(let e=0;e<r;e+=1){const i=e<n.length?n.charCodeAt(e):0,s=e<t.length?t.charCodeAt(e):0;o|=i^s}return o===0},d="LUNORA_RELAY_SECRET",f="x-lunora-relay-sig",l=n=>{const t=n?.[d];return typeof t=="string"&&t.length>0?t:void 0},u=async(n,t)=>{const r=new TextEncoder,o=await crypto.subtle.importKey("raw",r.encode(n),{hash:"SHA-256",name:"HMAC"},!1,["sign"]),e=await crypto.subtle.sign("HMAC",o,r.encode(t));return[...new Uint8Array(e)].map(i=>i.toString(16).padStart(2,"0")).join("")},y=async(n,t,r)=>{const o=l(n);return o===void 0?!0:t===null?!1:a(t,await u(o,r))},c=n=>{if(n===null||typeof n!="object")return;const t=n;return typeof t.idFromName=="function"&&typeof t.get=="function"?t:void 0},g=(n,t,r)=>{const o=c(n);if(o===void 0)return;const e=r===void 0?o:c(o.jurisdiction?.(r));if(e!==void 0)return typeof e.getByName=="function"?e.getByName(t):e.get(e.idFromName(t))},h=(n,t,r,o)=>t===void 0?void 0:g(n?.[t],r,o);export{f as RELAY_SIGNATURE_HEADER,l as siblingSecretOf,h as siblingStub,u as signSiblingBody,g as stubByName,y as verifySiblingBody};
@@ -0,0 +1 @@
1
+ const o="__lunora_reproject__",e=t=>`${o}${t}`,n=t=>{if(!t.startsWith(o))return;const r=t.slice(o.length);return r===""?void 0:r};export{o as REPROJECTION_MIGRATION_PREFIX,e as reprojectionMigrationId,n as reprojectionMigrationTable};
@@ -0,0 +1 @@
1
+ import{LunoraError as R}from"@lunora/errors";import{findRelated as m}from"./RELATED_DEFAULT_LIMIT-CVqN4JEu.mjs";const M=Symbol.for("lunora.ctxdb.rls-unwrap");class S extends R{table;constructor(n){super("RLS_REQUIRED",`ctx.db access to "${n}" 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=n}}const b=o=>Object.entries(o.tables).filter(([,n])=>n.shardMode?.kind!=="global").map(([n])=>n),E=(o,n,c)=>{const d=n?.tables,u=new Set(n?.exclude);for(const r of o)(d===void 0||d.includes(r))&&!u.has(r)&&c(r)},y={aggregate:"loop-gated",asId:"ungated",assertPatchAllowed:"id-gated",cdcChangedTables:"ungated",count:"loop-gated",delete:"id-gated",deleteAll:"loop-gated",deleteMany:"id-gated",deleteWhere:"inline-table-gated",explain:"loop-gated",findFirst:"loop-gated",findFirstOrThrow:"loop-gated",findMany:"loop-gated",get:"id-gated",groupBy:"loop-gated",insert:"loop-gated",insertMany:"loop-gated",insertManyUnsafe:"loop-gated",inTransaction:"ungated",lookupById:"id-gated",normalizeId:"ungated",patch:"id-gated",patchIf:"loop-gated",patchMany:"id-gated",patchWhere:"inline-table-gated",query:"loop-gated",rank:"loop-gated",rankBefore:"loop-gated",rankPage:"loop-gated",rankPageRows:"loop-gated",related:"rebound",relationEdges:"ungated",deleteRereadTables:"ungated",relationWrites:"ungated",softDeleteFields:"ungated",replace:"id-gated",restore:"id-gated",system:"ungated",wipeShard:"sweep-gated"},W=Object.entries(y).filter(([,o])=>o==="loop-gated").map(([o])=>o),I={related:(o,n)=>(...c)=>{const[d,u]=c;return m(o,n,d,u)}},O=Object.entries(y).filter(([,o])=>o==="rebound").map(([o])=>o),k=(o,n,c)=>{for(const d of O)typeof n[d]=="function"&&(o[d]=I[d](o,c))},P=(o,n,c,d,u=[])=>{if(n.rlsMode!=="required")return o;const r=o,p=e=>{const t=n.tables[e];return t!==void 0&&t.isPublic!==!0},i=e=>{if(p(e))throw new S(e)},l=async(e,t)=>{if(t!==void 0){i(t);return}const a=await c(e);a!==void 0&&i(a)},f=async(e,t)=>{if(t!==void 0){i(t);return}if(!d){for(const s of e)await l(s,t);return}const a=await d([...new Set(e)],t);for(const s of e){const h=a.get(s);h!==void 0&&i(h)}},g={...o,delete:async(e,t,a)=>(await l(e,t),r.delete(e,t,a)),deleteMany:async(e,t,a)=>(await f(e,a),r.deleteMany(e,t,a)),deleteWhere:r.deleteWhere?async(e,t,a)=>(i(e),await r.deleteWhere?.(e,t,a)):void 0,get:async(e,t)=>(await l(e,t),r.get(e,t)),lookupById:async(e,t)=>(await l(e,t),r.lookupById?.(e,t)??null),patch:async(e,t,a,s)=>(await l(e,a),r.patch(e,t,a,s)),patchMany:async(e,t,a)=>(await f(e.map(s=>s.id),a),r.patchMany(e,t,a)),assertPatchAllowed:async(e,t)=>(await l(e,t),r.assertPatchAllowed?.(e,t)),patchWhere:r.patchWhere?async(e,t,a)=>(i(e),await r.patchWhere?.(e,t,a)):void 0,replace:async(e,t,a,s)=>(await l(e,a),r.replace(e,t,a,s)),restore:async(e,t)=>(await l(e,t),r.restore?.(e,t))},w=r;for(const e of W){const t=w[e];typeof t=="function"&&(g[e]=(a,...s)=>(i(a),t.call(r,a,...s)))}if(k(g,r,u),r.wipeShard){const{wipeShard:e}=r;g.wipeShard=t=>(E(b(n),t,i),e.call(r,t))}return Object.defineProperty(g,M,{configurable:!0,enumerable:!1,value:o,writable:!1}),g};export{W as LOOP_GATED_METHODS,M as RLS_UNWRAP_SYMBOL,S as RlsRequiredError,y as WRITER_METHOD_GATING,P as guardWriter};
@@ -0,0 +1 @@
1
+ import{stableWireKey as y}from"@lunora/wire";import{stableStringify as S,stableWireKey as M}from"@lunora/wire";import{depKey as u,SCAN_DEP as p}from"./SCAN_DEP-D7qE3iUe.mjs";import{e as m}from"./estimate-bytes-_k74s6LZ.mjs";import{keysTouchRanges as x}from"./buildIndexRange-DQ3eWAGd.mjs";const l=(o,e,s)=>{let t=o.get(e);return t===void 0&&(t=s(),o.set(e,t)),t},v=1e3,E=4*1024*1024;class A{entries=new Map;tableIndex=new Map;rangeIndex=new Map;totalBytes=0;hits=0;misses=0;evictions=0;maxEntries;maxBytes;now;monotonic=0;generation=0;constructor(e={}){this.maxEntries=e.maxEntries??v,this.maxBytes=e.maxBytes??E,this.now=e.now??(()=>(this.monotonic+=1,this.monotonic))}async run(e,s,t,i=()=>[]){const n=this.entries.get(e);if(n)return this.hits+=1,n.lastUsed=this.now(),this.entries.delete(e),this.entries.set(e,n),n.result;this.misses+=1;const c=this.generation,a=await t();if(this.generation!==c)return a;const h=m(a);if(h===void 0)return a;const f=i(),b={bytes:h,deps:s,ranges:f,lastUsed:this.now(),result:a,subscribers:new Set},d=this.entries.get(e);if(d){this.dropEntry(e,d);for(const r of d.subscribers)b.subscribers.add(r)}this.entries.set(e,b),this.totalBytes+=h;for(const r of s)l(this.tableIndex,r,()=>new Set).add(e);for(const r of f){const g=l(this.rangeIndex,r.table,()=>new Map);l(g,r,()=>new Set).add(e)}return this.evict(),a}invalidate(e,s,t){this.generation+=1;const i=[];return this.collectAndDrop(u(e,s),i),this.collectAndDrop(u(e,p),i),this.dropRangeDeps(e,t,i),i}invalidateTable(e){this.generation+=1;const s=[],t=`${e}:`;for(const i of this.tableIndex.keys())i.startsWith(t)&&this.collectAndDrop(i,s);return this.dropRangeDeps(e,void 0,s),s}subscribe(e,s){const t=this.entries.get(e);t&&t.subscribers.add(s)}unsubscribe(e,s){const t=this.entries.get(e);t&&t.subscribers.delete(s)}size(){return{bytes:this.totalBytes,entries:this.entries.size}}clear(){this.generation+=1,this.entries.clear(),this.tableIndex.clear(),this.rangeIndex.clear(),this.totalBytes=0}subscribers(e){const s=this.entries.get(e);return s?[...s.subscribers]:[]}stats(){return{bytes:this.totalBytes,entries:this.entries.size,evictions:this.evictions,hits:this.hits,misses:this.misses}}dropRangeDeps(e,s,t){const i=this.rangeIndex.get(e);if(!(!i||i.size===0))for(const[n,c]of i)x([n],s)&&this.dropKeys(c,t)}collectAndDrop(e,s){const t=this.tableIndex.get(e);t&&this.dropKeys(t,s)}dropKeys(e,s){for(const t of e){const i=this.entries.get(t);i&&(this.dropEntry(t,i),s.push(t))}}dropEntry(e,s){this.entries.delete(e),this.totalBytes-=s.bytes;for(const t of s.deps){const i=this.tableIndex.get(t);i&&(i.delete(e),i.size===0&&this.tableIndex.delete(t))}for(const t of s.ranges){const i=this.rangeIndex.get(t.table),n=i?.get(t);n?.delete(e),i&&n?.size===0&&(i.delete(t),i.size===0&&this.rangeIndex.delete(t.table))}}evict(){if(!(this.entries.size<=this.maxEntries&&this.totalBytes<=this.maxBytes))for(const[e,s]of this.entries){if(this.entries.size<=this.maxEntries&&this.totalBytes<=this.maxBytes)return;s.subscribers.size>0||(this.dropEntry(e,s),this.evictions+=1)}}}const D=(o,e,s)=>`${s??"\0anon"}\0${o}:${y(e)}`;export{A as ReactiveCache,D as reactiveCacheKey,S as stableStringify,M as stableWireKey};
@@ -0,0 +1 @@
1
+ const r="*scan",t=(e,c)=>`${e}:${c}`,o=e=>{const c=e.indexOf(":");return c===-1?e:e.slice(0,c)},s=()=>{const e=new Set;return{collect(){return e},recordRead(c,n){e.add(t(c,n))}}};export{r as SCAN_DEP,s as createDependencyTracker,t as depKey,o as tableFromDepKey};
@@ -0,0 +1,11 @@
1
+ import{sql as t}from"drizzle-orm";import{runDrizzle as a}from"./runDrizzle-RC09zZrh.mjs";const o="__schedule_outbox",_=e=>{a(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(o)} (
2
+ id TEXT PRIMARY KEY,
3
+ envelope_json TEXT NOT NULL,
4
+ attempts INTEGER NOT NULL,
5
+ next_attempt_at REAL NOT NULL,
6
+ created_at REAL NOT NULL,
7
+ dead INTEGER NOT NULL DEFAULT 0
8
+ )`),a(e,t`CREATE INDEX IF NOT EXISTS ${t.identifier(`${o}_due`)} ON ${t.identifier(o)} (dead, next_attempt_at)`)},p=(e,d,E,n)=>{a(e,t`INSERT OR REPLACE INTO ${t.identifier(o)} (id, envelope_json, attempts, next_attempt_at, created_at, dead)
9
+ VALUES (${d}, ${E}, 0, ${n}, ${n}, 0)`)},s=(e,d)=>{a(e,t`DELETE FROM ${t.identifier(o)} WHERE id = ${d}`)},u=(e,d,E)=>a(e,t`SELECT id, envelope_json, attempts, next_attempt_at FROM ${t.identifier(o)}
10
+ WHERE dead = 0 AND next_attempt_at <= ${d}
11
+ ORDER BY next_attempt_at ASC LIMIT ${E}`).toArray().map(i=>({attempts:i.attempts,envelopeJson:i.envelope_json,id:i.id,nextAttemptAt:i.next_attempt_at})),c=(e,d,E,n)=>{a(e,t`UPDATE ${t.identifier(o)} SET attempts = ${E}, next_attempt_at = ${n} WHERE id = ${d}`)},O=(e,d,E)=>{a(e,t`UPDATE ${t.identifier(o)} SET attempts = ${E}, dead = 1 WHERE id = ${d}`)},N=e=>{const E=a(e,t`SELECT MIN(CASE WHEN dead = 0 THEN next_attempt_at END) AS due, COUNT(*) AS total FROM ${t.identifier(o)}`).toArray()[0];return{dueAt:E?.due??void 0,populated:(E?.total??0)>0}},m=(e,d)=>{a(e,t`DELETE FROM ${t.identifier(o)} WHERE dead = 1 AND created_at < ${d}`)};export{o as SCHEDULE_OUTBOX_TABLE,c as deferScheduleOutbox,s as forgetScheduleOutbox,_ as migrateScheduleOutbox,O as parkScheduleOutbox,N as probeScheduleOutbox,u as readDueScheduleOutbox,p as recordScheduleOutbox,m as trimScheduleOutbox};
@@ -0,0 +1,6 @@
1
+ import{quoteIdentifier as i}from"./quoteIdentifier-CObIFRhb.mjs";import{runSql as n}from"./runDrizzle-RC09zZrh.mjs";const p="__lunora_schema_history",c=50,e=i(p),E=t=>({appliedAt:typeof t.applied_at=="number"?t.applied_at:0,hash:typeof t.hash=="string"?t.hash:"",seq:typeof t.seq=="number"?t.seq:0}),a=t=>{n(t,`CREATE TABLE IF NOT EXISTS ${e} (
2
+ hash TEXT PRIMARY KEY,
3
+ seq INTEGER NOT NULL,
4
+ snapshot_json TEXT NOT NULL,
5
+ applied_at INTEGER NOT NULL
6
+ )`)},S=t=>{n(t,`DELETE FROM ${e} WHERE hash NOT IN (SELECT hash FROM ${e} ORDER BY seq DESC LIMIT ?)`,c)},I=(t,s,r,h=Date.now())=>{if(s===""||r==="")return!1;try{if(a(t),n(t,`SELECT hash FROM ${e} WHERE hash = ? LIMIT 1`,s).toArray().length>0)return!1;const[o]=n(t,`SELECT COALESCE(MAX(seq), 0) + 1 AS next FROM ${e}`).toArray(),T=typeof o?.next=="number"?o.next:1;return n(t,`INSERT INTO ${e} (hash, seq, snapshot_json, applied_at) VALUES (?, ?, ?, ?) ON CONFLICT(hash) DO NOTHING`,s,T,r,h),S(t),!0}catch{return!1}},_=t=>{try{return a(t),n(t,`SELECT hash, seq, applied_at FROM ${e} ORDER BY seq DESC`).toArray().map(s=>E(s))}catch{return[]}},u=(t,s)=>{try{a(t);const[r]=n(t,`SELECT hash, seq, applied_at, snapshot_json FROM ${e} WHERE hash = ? LIMIT 1`,s).toArray();return r===void 0?void 0:{...E(r),snapshotJson:typeof r.snapshot_json=="string"?r.snapshot_json:""}}catch{return}};export{c as SCHEMA_HISTORY_MAX_VERSIONS,_ as readSchemaHistory,u as readSchemaVersion,I as recordSchemaVersion};
@@ -0,0 +1 @@
1
+ import{S as t,m as S,b as c,r as i,a as l,w as s}from"./ctx-db-search-state-FjgzTFok.mjs";import"./runDrizzle-RC09zZrh.mjs";export{t as SEARCH_STATE_TABLE,S as migrateSearchState,c as readBackfillState,i as readSearchBackfillState,l as readSearchIndexCoverage,s as writeSearchBackfillState};
@@ -0,0 +1,8 @@
1
+ import{sql as o}from"drizzle-orm";import{runDrizzle as s}from"./runDrizzle-RC09zZrh.mjs";import{WORKERD_SQLITE_LIMITS as d}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";const c="__shape_poke_cursor",L=r=>{s(r,o`CREATE TABLE IF NOT EXISTS ${o.identifier(c)} (
2
+ connection_id TEXT NOT NULL,
3
+ sub_id TEXT NOT NULL,
4
+ cursor INTEGER NOT NULL,
5
+ PRIMARY KEY (connection_id, sub_id)
6
+ )`)},N=(r,e,n)=>s(r,o`SELECT cursor FROM ${o.identifier(c)} WHERE connection_id = ${e} AND sub_id = ${n} LIMIT 1`).toArray()[0]?.cursor,a=(r,e,n,i)=>{s(r,o`INSERT INTO ${o.identifier(c)} (connection_id, sub_id, cursor) VALUES (${e}, ${n}, ${i})
7
+ ON CONFLICT(connection_id, sub_id) DO UPDATE SET cursor = excluded.cursor`)},T=3,R=(r,e)=>{const n=Math.floor(d.boundParams/T);for(let i=0;i<e.length;i+=n){const E=e.slice(i,i+n),u=o.join(E.map(t=>o`(${t.connectionId}, ${t.subId}, ${t.cursor})`),o`, `);s(r,o`INSERT INTO ${o.identifier(c)} (connection_id, sub_id, cursor) VALUES ${u}
8
+ ON CONFLICT(connection_id, sub_id) DO UPDATE SET cursor = excluded.cursor`)}},$=r=>s(r,o`SELECT MIN(cursor) AS cursor FROM ${o.identifier(c)}`).toArray()[0]?.cursor??void 0,C=(r,e,n)=>{s(r,o`DELETE FROM ${o.identifier(c)} WHERE connection_id = ${e} AND sub_id = ${n}`)},I=(r,e)=>{s(r,o`DELETE FROM ${o.identifier(c)} WHERE connection_id = ${e}`)};export{c as SHAPE_POKE_CURSOR_TABLE,C as deleteShapePokeCursor,I as deleteShapePokeCursorsForConnection,L as migrateShapePokeCursor,$ as minShapePokeCursor,N as readShapePokeCursor,a as writeShapePokeCursor,R as writeShapePokeCursors};
@@ -0,0 +1 @@
1
+ import{stableWireKey as o}from"@lunora/wire";const s=r=>r.map(e=>`${String(e.length)}:${e}`).join(""),c=r=>o(r.effectiveWhere??null),g=(r,e,t)=>s([r,String(e),String(t)]),h=(r,e)=>{try{return s([c(r),e])}catch{return}};class d{keyScans=new Map;memberProbes=new Map;run=0;served=0;get probesRun(){return this.run}get probesServed(){return this.served}changedKeys(e,t){return this.getOrLoad(this.keyScans,e,t)}members(e,t,n){return this.getOrLoad(this.memberProbes,h(e,t),n)}getOrLoad(e,t,n){if(t!==void 0){const a=e.get(t);if(a!==void 0)return this.served+=1,a}this.run+=1;const i=n();return t!==void 0&&e.set(t,i),i}}const p=()=>new d,b=(r,e)=>{try{return s([r.table,c(r),o({identity:e.identity,userId:e.userId})])}catch{return}};export{d as ShapeDiffCache,p as createShapeDiffCache,b as globalShapeReadKey,g as shapeRangeKey};
@@ -0,0 +1 @@
1
+ class n{shardHost;socketHost;options;constructor(t,s,r={}){this.shardHost=t,this.socketHost=s,this.options=r}get shardKey(){return this.shardHost.shardKey}socketFor(t){return this.socketHost.handleFor(t)??t}sockets(t){return this.socketHost.getSockets(t)}background(t){return this.shardHost.waitUntil===void 0?!1:(this.shardHost.waitUntil(t),!0)}async runInTransaction(t,s){return this.shardHost.runSerialized(async()=>{const r=await this.shardHost.transaction(t);return s?.(),r})}async handleFetch(t){return this.options.handlers?.handleFetch?this.options.handlers.handleFetch(t):new Response("Not implemented",{status:501})}async handleAlarm(){this.options.handlers?.handleAlarm&&await this.options.handlers.handleAlarm()}}export{n as ShardRunner};
@@ -0,0 +1 @@
1
+ const d=()=>{const n=new Set,t=new Map,s=new Set;return{onRead(e){n.add(e),s.add(e)},onReadRange(e){n.add(e.table);const o=t.get(e.table);o?o.push(e):t.set(e.table,[e])},ranges(){for(const e of s)t.delete(e);return t.size>0?t:void 0},tables:n}},u="!unvouchable",i=(n,t,s)=>{if(!t)return n;const e=new Set(s);return new Proxy(n,{get(o,a,r){const c=Reflect.get(o,a,r);return typeof c!="function"||typeof a!="string"||!e.has(a)?c:(...l)=>(t(u),Reflect.apply(c,o,l))}})};export{u as UNVOUCHABLE_DEP,d as createReadFootprint,i as markUnvouchableReads};
@@ -0,0 +1 @@
1
+ import{isLunoraError as S}from"@lunora/errors";import{l as R,b as L}from"./ctx-db-search-state-FjgzTFok.mjs";import{sql as e}from"drizzle-orm";import{readKeysetPage as _}from"./backfillAggregateIndexes-DSplGrR_.mjs";import{runDrizzle as p}from"./runDrizzle-RC09zZrh.mjs";import{h}from"./do-sql-BWrJQAOh.mjs";const u="__lunora_vector_backfill",m=50,k=20,w=20,N=3,O=i=>{p(i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(u)} (${e.identifier("companion")} TEXT PRIMARY KEY, ${e.identifier("cursor")} TEXT, ${e.identifier("done")} INTEGER NOT NULL DEFAULT 0, ${e.identifier("profile")} TEXT, ${e.identifier("strikes")} INTEGER NOT NULL DEFAULT 0)`);try{p(i,e`ALTER TABLE ${e.identifier(u)} ADD COLUMN ${e.identifier("strikes")} INTEGER NOT NULL DEFAULT 0`)}catch{}},C=(i,o)=>{const[s]=p(i,e`SELECT ${e.identifier("strikes")} FROM ${e.identifier(u)} WHERE ${e.identifier("companion")} = ${o}`).toArray();return s?.strikes??0},$=(i,o,s,d,t,r=0)=>{const n=s??null;p(i,e`INSERT INTO ${e.identifier(u)} (${e.identifier("companion")}, ${e.identifier("cursor")}, ${e.identifier("done")}, ${e.identifier("profile")}, ${e.identifier("strikes")}) VALUES (${o}, ${n}, ${d?1:0}, ${t}, ${r}) ON CONFLICT (${e.identifier("companion")}) DO UPDATE SET ${e.identifier("cursor")} = excluded.${e.identifier("cursor")}, ${e.identifier("done")} = excluded.${e.identifier("done")}, ${e.identifier("profile")} = excluded.${e.identifier("profile")}, ${e.identifier("strikes")} = excluded.${e.identifier("strikes")}`)},A=(i,o,s)=>{const d=_(i,o,s,m+1),t={documents:[],lastId:s,more:d.length>m,unparseable:[]};for(const r of d.slice(0,m)){if(typeof r.id!="string")continue;t.lastId=r.id;const n=h(r);n?t.documents.push({doc:n,id:t.lastId}):t.unparseable.push(t.lastId)}return t},D=(i,o,s,d,t)=>{const r=t instanceof Error?t.message:String(t),n=L(i,u,o),a=n.profile===d&&n.cursor===s?C(i,o):0;if(S(t)&&t.code==="SERVICE_UNAVAILABLE")return a>0&&$(i,o,s,!1,d,0),{error:r};const f=a+1;if(f<N)return $(i,o,s,!1,d,f),{error:r};const c=A(i,o,s),l=[...c.documents.map(E=>E.id),...c.unparseable];return console.warn(`[@lunora/shard-engine] vector backfill: a page of "${o}" failed ${String(f)} times in a row; its ${String(l.length)} row(s) are recorded as failed:`,t),{failedIds:l,page:c}},F=async(i,o,s,d,t)=>{const{profile:r,table:n}=o;try{const{failures:a,page:f}=await t(()=>A(i,n,s),async c=>({failures:await d(n,c.documents),page:c}));return a.length>0&&console.warn(`[@lunora/shard-engine] vector backfill: ${String(a.length)} row(s) of "${n}" could not be indexed:`,a),{failedIds:[...f.unparseable,...a.map(c=>c.id)],page:f}}catch(a){return D(i,n,s,r,a)}},y=async(i,o,s,d)=>{if(O(i),d.restart===!0)for(const{profile:n,table:a}of o)$(i,a,void 0,!1,n);const t=Math.min(d.maxPages??1,k),r={done:!1,failed:0,failedIds:[],pages:0,rows:0};for(const{profile:n,table:a}of o){const f=R(L(i,u,a),n);let{cursor:c}=f,l=f.finished;for(;!l;){if(r.pages>=t)return r;const E=await F(i,{profile:n,table:a},c,s,d.ordered);if("error"in E)return{...r,error:E.error};const{failedIds:g,page:T}=E,I=T.documents.length+T.unparseable.length;r.pages+=I>0?1:0,r.rows+=I,r.failed+=g.length,r.failedIds=[...r.failedIds,...g].slice(0,w),c=T.lastId,l=!T.more,$(i,a,c,l,n)}}return{...r,done:!0}};export{k as VECTOR_BACKFILL_MAX_PAGES,m as VECTOR_BACKFILL_PAGE_ROWS,y as backfillVectorIndexes};
@@ -0,0 +1 @@
1
+ import{LunoraError as f}from"@lunora/errors";import{sql as t}from"drizzle-orm";import{SQLiteDialect as u}from"drizzle-orm/sqlite-core";const S=new u,s={boundParams:100,compoundSelect:5,likePattern:50,sqlTextLength:1e5},d=s.boundParams/2,h=n=>n===null||typeof n=="boolean"?!0:typeof n=="number"?Number.isFinite(n):typeof n=="string"&&n.isWellFormed(),p=n=>{const e=[];for(const r of n){if(!(r instanceof Uint8Array))return;e.push(Array.from(r,o=>o.toString(16).padStart(2,"0")).join(""))}return JSON.stringify(e)},N=(n,e)=>{if(n!=="sqlite")throw new f("INTERNAL",`renderSql only renders SQLite; use SqlDialect.render for "${n}"`);const{params:r,sql:o}=S.sqlToQuery(e);return{params:r,sql:o}},L=n=>t`${n}`,y=n=>{if(n.length===0)throw new Error("unionAll: expected at least one branch");let e=[...n];for(;e.length>s.compoundSelect;){const r=[];for(let o=0;o<e.length;o+=s.compoundSelect){const i=t.join(e.slice(o,o+s.compoundSelect),t` UNION ALL `);r.push(t`SELECT * FROM (${i}) ${t.identifier("__u__")}`)}e=r}return t.join(e,t` UNION ALL `)},T=(n,e,r,o=d)=>{const i=r?t` NOT IN `:t` IN `,a=e.every(l=>h(l)),c=e.length>o&&!a?p(e):void 0;if(c!==void 0)return t`${n}${i}(SELECT unhex(${t.identifier("value")}) FROM json_each(${c}))`;if(e.length>o&&!a)throw new f("BAD_REQUEST",`an "in" list of ${String(e.length)} values holds a value JSON cannot carry (bytes, a non-finite number, or malformed text), so it cannot be bound as one parameter — and ${String(e.length)} placeholders exceed SQLite's per-statement cap of 100 on Durable Objects and D1. Narrow the list to ${String(o)} values or fewer.`);return e.length<=o?t`${n}${i}(${t.join(e.map(l=>L(l)),t`, `)})`:t`${n}${i}(SELECT ${t.identifier("value")} FROM json_each(${JSON.stringify(e)}))`};export{s as WORKERD_SQLITE_LIMITS,p as bytesAsHexJson,h as isJsonSafe,L as param,N as renderSql,T as sqliteInList,y as unionAll};
@@ -0,0 +1 @@
1
+ import{e as o}from"./effective-kind-BmG_zCAy.mjs";const a=new Set(["any","null"]),s=(t,n)=>{const l=n.kindOf(t);return l!==void 0&&a.has(l)||n.nullableOf(t)?!0:l==="union"&&(n.membersOf(t)??[]).some(i=>s(i,n))},e=t=>{const n=t._meta?.inner;return t.kind==="optional"&&n?e(n):t},u=t=>s(t,{kindOf:o,membersOf:n=>e(n)._meta?.members,nullableOf:n=>e(n)._meta?.column?.notNull===!1});export{u as v};
@@ -0,0 +1 @@
1
+ import{LunoraError as g}from"@lunora/errors";import{encodeWire as i}from"@lunora/wire";const a=BigInt(Number.MAX_SAFE_INTEGER),c=(e,t)=>e<t?-1:e>t?1:0,s=(e,t)=>`${e}__agg_${t}`,l=e=>{if(typeof e=="bigint"){if(e>a||e<-a)throw new g("BAD_REQUEST",`bigint ${e.toString()} exceeds Number.MAX_SAFE_INTEGER, so an aggregateIndex declared over this column cannot tally it exactly (the companion's value column is a REAL) — drop the aggregateIndex, aggregate a narrower column, or read the rows and reduce them in the handler`);return Number(e)}if(typeof e=="number")return Number.isFinite(e)?e:void 0},v=(e,t,n,u)=>{const r=e.get(t)??{count:0,value:null};if(n.op==="count"){r.count+=1,r.value=r.count,e.set(t,r);return}const o=l(u[n.field??""]);if(n.op==="sum"||n.op==="avg"){o!==void 0&&(r.value=(r.value??0)+o,r.count+=1),e.set(t,r);return}r.count+=1,o!==void 0&&(r.value===null?r.value=o:r.value=n.op==="min"?Math.min(r.value,o):Math.max(r.value,o)),e.set(t,r)},d=(e,t)=>e==="count"?t?.value??0:!t||t.count===0?null:e==="avg"?t.value===null?null:t.value/t.count:t.value,A=(e,t)=>{if(e.length===0)return"";const n={};for(const u of e.toSorted(c))n[u]=t[u]??null;return JSON.stringify(i(n))};export{s as aggregateTableName,l as coerceAggregateNumber,c as compareStrings,A as encodeAggregateKey,v as foldAggregateTally,d as readAggregateValue};
@@ -0,0 +1,17 @@
1
+ import{sql as t}from"drizzle-orm";import{runDrizzle as o}from"./runDrizzle-RC09zZrh.mjs";const E="__stream_runs",i="__stream_chunks",N=r=>{o(r,t`CREATE TABLE IF NOT EXISTS ${t.identifier(E)} (
2
+ run_key TEXT PRIMARY KEY,
3
+ status TEXT NOT NULL,
4
+ last_seq INTEGER NOT NULL DEFAULT 0,
5
+ error_code TEXT,
6
+ error TEXT,
7
+ started_at REAL NOT NULL,
8
+ ttl_ms REAL NOT NULL
9
+ )`),o(r,t`CREATE TABLE IF NOT EXISTS ${t.identifier(i)} (
10
+ run_key TEXT NOT NULL,
11
+ seq INTEGER NOT NULL,
12
+ data_json TEXT NOT NULL,
13
+ PRIMARY KEY (run_key, seq)
14
+ )`)},_=(r,e)=>{const s=o(r,t`SELECT status, last_seq, error_code, error, started_at FROM ${t.identifier(E)} WHERE run_key = ${e} LIMIT 1`).toArray()[0];if(s!==void 0)return{...s.error===null?{}:{error:s.error},...s.error_code===null?{}:{errorCode:s.error_code},lastSeq:s.last_seq,startedAt:s.started_at,status:s.status}},T=(r,e)=>{o(r,t`DELETE FROM ${t.identifier(i)} WHERE run_key = ${e}`)},c=(r,e,n,s)=>_(r,e)!==void 0?!1:(T(r,e),o(r,t`INSERT INTO ${t.identifier(E)} (run_key, status, last_seq, started_at, ttl_ms)
15
+ VALUES (${e}, ${"running"}, 0, ${n}, ${s})`),!0),R=(r,e)=>{T(r,e),o(r,t`DELETE FROM ${t.identifier(E)} WHERE run_key = ${e}`)},m=(r,e,n,s)=>{o(r,t`INSERT OR IGNORE INTO ${t.identifier(i)} (run_key, seq, data_json) VALUES (${e}, ${n}, ${s})`)},A=(r,e,n)=>o(r,t`SELECT seq, data_json FROM ${t.identifier(i)} WHERE run_key = ${e} AND seq > ${n} ORDER BY seq ASC`).toArray().map(s=>({dataJson:s.data_json,seq:s.seq})),$=(r,e,n,s,a)=>{if(_(r,e)===void 0){T(r,e);return}const d=a?.code??null,u=a?.message??null;o(r,t`UPDATE ${t.identifier(E)}
16
+ SET status = ${n}, last_seq = ${s}, error_code = ${d}, error = ${u}
17
+ WHERE run_key = ${e}`)},f=(r,e,n)=>{const s=o(r,t`SELECT run_key FROM ${t.identifier(E)} WHERE started_at + ttl_ms < ${e}`).toArray();for(const{run_key:a}of s)n.has(a)||R(r,a)};export{m as appendStreamChunk,c as claimStreamRun,R as deleteStreamRun,$ as finishStreamRun,N as migrateDurableStreams,A as readStreamChunks,_ as readStreamRun,f as trimStreamRuns};
@@ -0,0 +1 @@
1
+ import{LunoraError as D}from"@lunora/errors";import{t as P}from"./do-sql-BWrJQAOh.mjs";import{applySelect as J}from"./CURSOR_PREFIX-6offuG6M.mjs";const U=Symbol.for("lunora.relations.fanOutBudget"),ce=e=>({fanOutBudget:e[U],relationBaseWhere:e.relationBaseWhere,relationMask:e.relationMask}),$=(e,t)=>t.select?J(e,t.select,t.with):e,ae=async(e,t,n,i,s)=>{const c=await Promise.all(i.map(async l=>{const d=s?{AND:[{[n]:l},s]}:{[n]:l};return[l,await e(t,d)]}));return new Map(c)},Q=32,B=1e4,Y=(e,t,n)=>{const i=new Map;for(const s of e)for(const c of n(s)){const l=c[t],d=i.get(l);d?d.push(c):i.set(l,[c])}return i},E=(e,t)=>({...e,[U]:t}),Z=(e,t)=>{const n=new Map;for(const[s,c]of e)for(const l of c){const d=n.get(l);d?d.push(s):n.set(l,[s])}const i=new Map;for(const s of t)for(const c of n.get(s._id)??[]){const l=i.get(c);l?l.push(s):i.set(c,[s])}return i},_=(e,t)=>{const n=new Set;for(const i of e){const s=i[t];s!=null&&n.add(s)}return[...n]},fe=async e=>{const{groupedCounter:t,fanOutBudget:n,fetcher:i,parents:s,relationBaseWhere:c,relationMask:l,schema:d,tableName:g,with:A}=e,b=n??{remaining:Q},k=(a,o)=>l?.(a,o)??o;if(s.length===0)return;const v=d.tables[g];if(!v)throw new D("INTERNAL",`unknown table: ${g}`);const j=v.relationMap??{},z=(a,o)=>{const r=u=>d.tables[u]?.shardMode?.kind??"root";return r(a)===r(o)&&r(a)!=="shardBy"},I=a=>{const o=j[a];if(!o)throw new D("INTERNAL",`unknown relation "${a}" on table "${g}"`);return o},x=async(a,o,r)=>{const u=_(s,o.field);if(u.length===0){for(const h of s)h[a]=null;return}const{page:f}=await i(o.table,E({baseWhere:c?.(o.table),relationBaseWhere:c,relationMask:l,where:{[o.references]:{in:u}},with:r.with},b)),p=new Map;for(const h of k(o.table,f))p.set(h[o.references],h);for(const h of s){const m=p.get(h[o.field]);h[a]=m?$([m],r)[0]??null:null}},S=async(a,o,r,u)=>{const{page:f}=await i(a,E({baseWhere:c?.(a),limit:u,orderBy:o.orderBy,relationBaseWhere:c,relationMask:l,where:o.where?{AND:[o.where,r]}:r,with:o.with},b));return f},T=(a,o,r,u,f)=>{for(const p of s){const h=f.get(p[u])??[];p[a]=$(r===void 0?h:h.slice(0,r),o)}},G=async(a,o,r)=>{const u=_(s,o.references);if(u.length===0){for(const w of s)w[a]=[];return}const f=typeof r.limit=="number"?Math.max(0,Math.floor(r.limit)):void 0,p=(w,O)=>S(o.table,r,w,O);if(f===0){for(const w of s)w[a]=[];return}const h=f!==void 0&&u.length<=b.remaining;h&&(b.remaining-=u.length);const m=h?await Promise.all(u.map(async w=>p({[o.field]:w},f))):[await p({[o.field]:{in:u}},void 0)],y=Y(m,o.field,w=>k(o.table,w));T(a,r,f,o.references,y)},W=async a=>{const{from:o,table:r,to:u}=a.through,f=new Map,p=_(s,"_id");if(p.length===0)return f;const h=await S(r,{},{[o]:{in:p}},B+1);if(h.length>B)throw new D("INTERNAL",`loading "${g}" relations through "${r}" read more than ${String(B)} join rows for one page; load fewer ${g} rows at a time`);for(const m of k(r,h)){const y=m[o],w=m[u];if(y==null||w===null||w===void 0)continue;const O=f.get(y);O?O.add(w):f.set(y,new Set([w]))}return f},H=async(a,o,r)=>{const u=typeof r.limit=="number"?Math.max(0,Math.floor(r.limit)):void 0,f=u===0?new Map:await W(o),p=(m,y)=>S(o.table,r,{_id:{in:[...m]}},y);let h=new Map;if(f.size>0&&u!==void 0&&f.size<=b.remaining){b.remaining-=f.size;const m=[...f.keys()],y=await Promise.all([...f.values()].map(async w=>p(w,u)));h=new Map(m.map((w,O)=>[w,k(o.table,y[O]??[])]))}else if(f.size>0){const m=new Set([...f.values()].flatMap(y=>[...y]));h=Z(f,k(o.table,await p(m,void 0)))}T(a,r,u,"_id",h)},K=async(a,o)=>{const r=[...o];if(r.length===0)return new Set;if(z(g,a)){const f=await t(a,"_id",r,c?.(a));return new Set(r.filter(p=>(f.get(p)??0)>0))}const u=await S(a,{},{_id:{in:r}},void 0);return new Set(u.map(f=>f._id))},X=async(a,o)=>{const r=await W(o),u=await K(o.table,new Set([...r.values()].flatMap(f=>[...f])));for(const f of s){const p=f._count??{};p[a]=[...r.get(f._id)??[]].filter(h=>u.has(h)).length,f._count=p}},q=async a=>{for(const o of Object.keys(a)){const r=I(o);if(r.through!==void 0){await X(o,r);continue}const[u,f]=r.kind==="many"?[r.field,r.references]:[r.references,r.field],p=c?.(r.table),h=_(s,f),m=h.length===0?new Map:await t(r.table,u,h,p);for(const y of s){const w=y._count??{},O=y[f];w[o]=O==null?0:m.get(O)??0,y._count=w}}};for(const[a,o]of Object.entries(A)){if(o===void 0||o===!1)continue;if(a==="_count"){await q(o);continue}const r=I(a),u=o===!0?{}:o;r.through===void 0?await(r.kind==="one"?x(a,r,u):G(a,r,u)):await H(a,r,u)}},ee=async(e,t,n)=>{const{deletedId:i,deletedReference:s,findHolders:c,onCascade:l,onRestrict:d,onSetNull:g,tableName:A}=e,b=n.references==="_id"?i:s(n.references);if(b==null)return;const k=await c(t,n.field,b);if(k.length!==0){n.onDelete==="restrict"&&d(`cannot delete "${A}" row: "${t}.${n.field}" still references it`);for(const v of k){const j=v._id;typeof j=="string"&&await(n.onDelete==="cascade"?l(t,j):g(t,j,n.field))}}},le=async e=>{const{schema:t,tableName:n}=e;if(!t.tables[n])throw new D("INTERNAL",`unknown table: ${n}`);for(const[i,s]of Object.entries(t.tables)){const c=s.relationMap;if(c)for(const l of Object.values(c))l.kind!=="one"||l.table!==n||!l.onDelete||await ee(e,i,l)}},L=new WeakMap,C=e=>{const t=L.get(e);if(t!==void 0)return t;const n=e._meta,i=[n?.inner,n?.keyValidator,n?.valueValidator,...n?.members??[],...Object.values(n?.shape??{})],s=e.kind==="from"||i.some(c=>c!==void 0&&C(c));return L.set(e,s),s},V=e=>{const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},F=e=>e instanceof ArrayBuffer?new Uint8Array(e):ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):void 0,R=(e,t)=>{if(Object.is(e,t))return!0;if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();const n=F(e),i=F(t);if(n!==void 0||i!==void 0)return n!==void 0&&i!==void 0&&Object.getPrototypeOf(e)===Object.getPrototypeOf(t)&&n.length===i.length&&n.every((d,g)=>d===i[g]);if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((d,g)=>R(d,t[g]));if(typeof e!="object"||typeof t!="object"||e===null||t===null||!V(e)||!V(t))return!1;const s=e,c=t,l=Object.keys(s);return l.length===Object.keys(c).length&&l.every(d=>d in c&&R(s[d],c[d]))},N=new WeakMap,ue=e=>{if(N.has(e))return N.get(e);const t=Object.fromEntries(Object.entries(e.shape).filter(([,i])=>C(i))),n=Object.keys(t).length>0?{...e,shape:t}:void 0;return N.set(e,n),n},te=e=>{let t;return(n,i)=>e===void 0?!1:(t??=e()??{},n in t&&R(i,t[n]))},ne=(e,t)=>{const n=new Set(Object.keys(t).filter(i=>t[i]!==void 0));for(const[i,s]of P(e))s.serverDefault&&n.delete(i);return n},oe=(e,t,n,i,s)=>n.trusted===!0||i!==void 0&&!i.has(e)||s(e,t),M=e=>typeof e!="object"||e===null?e:e instanceof Date?new Date(e):e instanceof ArrayBuffer||ArrayBuffer.isView(e)?structuredClone(e):Array.isArray(e)?e.map(t=>M(t)):e instanceof Map?new Map([...e].map(([t,n])=>[M(t),M(n)])):e instanceof Set?new Set([...e].map(t=>M(t))):V(e)?Object.fromEntries(Object.entries(e).map(([t,n])=>[t,M(n)])):e,de=(e,t,n)=>{const i={...t};for(const[s,c]of P(e)){if(c.serverDefault){i[s]=c.serverDefault({auth:n});continue}if(i[s]===void 0){if(c.defaultFn)i[s]=c.defaultFn();else if("defaultValue"in c){const{defaultValue:l}=c;i[s]=M(l)}}}return i},he=(e,t,n={})=>{let i;const s=te(n.previous),c=n.only??(n.supplied===void 0?void 0:ne(e,n.supplied));for(const[l,d]of Object.entries(e.shape)){if(!(l in t)||typeof d.parse!="function")continue;const g=C(d);if(g&&oe(l,t[l],n,c,s)||n.tolerateStoredNull===!0&&t[l]===null&&d.kind==="optional")continue;const A=d.parse(t[l]);g&&(i??={...t},i[l]=A)}return i??t};export{B as MAX_LINK_ROWS,de as applyInsertDefaults,le as applyOnDelete,_ as distinctValues,ae as fanOutScalarCounts,ce as relationHooks,fe as resolveWith,he as runRowValidators,ue as transformOnlyDefinition};
@@ -0,0 +1,4 @@
1
+ import{sql as s}from"drizzle-orm";import{runDrizzle as d}from"./runDrizzle-RC09zZrh.mjs";const C=16,T=32,v=1e4,R=1e3,h=t=>String(t).padStart(C,"0"),f=t=>`cdc/${encodeURIComponent(t.shard)}/${encodeURIComponent(t.epoch)}/`,y=(t,n)=>`${f(t)}${h(n)}.json`,E="__cdc_archive",g=t=>{d(t,s`CREATE TABLE IF NOT EXISTS ${s.identifier(E)} (
2
+ id INTEGER PRIMARY KEY CHECK (id = 1),
3
+ seq INTEGER NOT NULL
4
+ )`)},$=t=>(g(t),d(t,s`SELECT seq FROM ${s.identifier(E)} WHERE id = 1`).toArray()[0]?.seq??0),w=(t,n)=>{g(t),d(t,s`INSERT INTO ${s.identifier(E)} (id, seq) VALUES (1, ${n}) ON CONFLICT (id) DO UPDATE SET seq = ${n}`)},L=async(t,n,e)=>{const o=e[0]?.seq,r=e.at(-1)?.seq;o===void 0||r===void 0||await t.put(y(n,r),JSON.stringify({changes:e,from:o,to:r}),{httpMetadata:{contentType:"application/json"}})},j=async(t,n,e)=>{const o=f(n);return(await t.list({limit:1,prefix:o,startAfter:`${o}${h(e)}.json`})).objects.length>0},S=t=>{let n;try{n=JSON.parse(t)}catch{return}if(typeof n!="object"||n===null)return;const e=n;return typeof e.from=="number"&&typeof e.to=="number"&&Array.isArray(e.changes)?e:void 0},_=(t,n)=>{const e=[];for(const o of t.changes)if(!(o.seq<=n)){if(o.op!=="delete"&&o.doc===void 0)break;e.push(o)}return e},I=(t,n,e)=>{let o=e;for(const r of n){if(r.seq!==o+1)break;t.push(r),o=r.seq}return o},b=async(t,n)=>{const e=await t.get(n);return e===null?void 0:S(await e.text())},q=async(t,n,e,o)=>{const r=f(n),p=Math.max(1,Math.min(o??R,v)),A=await t.list({limit:T,prefix:r,startAfter:`${r}${h(e)}.json`}),c=[];let i=e;for(const l of A.objects){const a=await b(t,l.key);if(a===void 0)break;const m=_(a,i);if(i=I(c,m,i),c.length>=p||i!==a.to)break}if(c[0]?.seq!==e+1)return;const u=c.slice(0,p);return{changes:u,cursor:u.at(-1)?.seq??e}};export{L as archiveCdcSegment,j as cdcArchiveRewound,q as readArchivedCdcChanges,$ as readCdcArchivedThrough,w as writeCdcArchivedThrough};
@@ -1 +1 @@
1
- import{LunoraError as a}from"@lunora/errors";const t=()=>Object.assign(new Error("native PITR is unavailable here (local dev or a non-SQLite Durable Object); use `lunora backup restore` for off-platform recovery"),{code:"PITR_UNAVAILABLE",name:"LunoraError",status:409}),i=o=>{if(typeof o=="number")return o;const r=Date.parse(o);if(Number.isNaN(r))throw new a("BAD_REQUEST",`pitr: invalid time "${o}" — expected epoch-ms or an ISO timestamp`);return r},s=async(o,r)=>{if(!o.getCurrentBookmark)throw t();const e=await o.getCurrentBookmark();return r===void 0||!o.getBookmarkForTime?{current:e}:{current:e,forTime:await o.getBookmarkForTime(i(r))}},k=async(o,r)=>{if(!o.onNextSessionRestoreBookmark)throw t();let e=r.bookmark;if(e===void 0){if(r.time===void 0)throw new a("BAD_REQUEST","pitrRestore: provide a `bookmark` or a `time` to restore to");if(!o.getBookmarkForTime)throw t();e=await o.getBookmarkForTime(i(r.time))}const n=await o.onNextSessionRestoreBookmark(e);return{restoredTo:e,undoBookmark:n}};export{k as armRestore,s as readBookmark};
1
+ import{LunoraError as a}from"@lunora/errors";const t=()=>Object.assign(new Error("native PITR is unavailable here (local dev or a non-SQLite Durable Object); use `lunora backup restore` for off-platform recovery"),{code:"PITR_UNAVAILABLE",name:"LunoraError",status:409}),i=o=>{if(typeof o=="number")return o;const r=Date.parse(o);if(Number.isNaN(r))throw new a("BAD_REQUEST",`pitr: invalid time "${o}" — expected epoch-ms or an ISO timestamp`);return r},k=async(o,r)=>{if(!o.getCurrentBookmark)throw t();const e=await o.getCurrentBookmark();return r===void 0||!o.getBookmarkForTime?{current:e}:{current:e,forTime:await o.getBookmarkForTime(i(r))}},s=async(o,r)=>{if(!o.onNextSessionRestoreBookmark)throw t();let e=r.bookmark;if(e===void 0){if(r.time===void 0)throw new a("BAD_REQUEST","pitrRestore: provide a `bookmark` or a `time` to restore to");if(!o.getBookmarkForTime)throw t();e=await o.getBookmarkForTime(i(r.time))}const n=await o.onNextSessionRestoreBookmark(e);return{restoredTo:e,undoBookmark:n}};export{s as armRestore,k as readBookmark};
@@ -0,0 +1 @@
1
+ import{LunoraError as a}from"@lunora/errors";import{e as u}from"./effective-kind-BmG_zCAy.mjs";import{a as k,i as m,r as $,F as g,e as R,s as F}from"./json-field-path-DeJW4U9z.mjs";const d={decrement:{apply:(e,t)=>e-t,kind:"number"},divide:{apply:(e,t)=>e/t,kind:"number"},increment:{apply:(e,t)=>e+t,kind:"number"},multiply:{apply:(e,t)=>e*t,kind:"number"},toggle:{kind:"boolean"}};class s extends Error{}const w=e=>{if(!k(e))return;const t=Object.keys(e),[n]=t;if(!(t.length!==1||n===void 0||!Object.hasOwn(d,n)))return{operand:e[n],operator:n}},b=e=>w(e)!==void 0,P=(e,t,n,o)=>{const r=d[t];if(r.apply===void 0){if(n!==!0)throw new s(`patch: use { toggle: true } on "${e}".`);if(typeof o!="boolean")throw new s(`patch: cannot toggle "${e}" — its current value is ${String(o)}; set a boolean first.`);return!o}if(typeof n!="number"||!Number.isFinite(n))throw new s(`patch: "${t}" on "${e}" needs a finite number, got ${String(n)}.`);if(typeof o!="number"||!Number.isFinite(o))throw new s(`patch: cannot ${t} "${e}" — its current value is ${String(o)}; set a number first.`);if(t==="divide"&&n===0)throw new s(`patch: cannot divide "${e}" by zero.`);const i=r.apply(o,n);if(!Number.isFinite(i))throw new s(`patch: "${t}" on "${e}" overflows to ${String(i)}.`);return i},v=(e,t)=>{const n=new Set;for(const[o,r]of Object.entries(e))t(o)!==void 0&&b(r)&&n.add(o);return n},E=(e,t,n)=>{let o;for(const r of v(e,n)){const{operand:i,operator:c}=w(e[r]),f=n(r);if(d[c].kind!==f)throw new s(`patch: "${c}" does not apply to the ${String(f)} column "${r}".`);o??={...e},o[r]=P(r,c,i,t[r])}return o??e},j=new Set(["date","number","timestamp"]),l=e=>e.kind==="optional"&&e._meta?.inner!==void 0?l(e._meta.inner):e,p=e=>{const t=l(e);if(t.kind!==void 0&&j.has(t.kind))return"number";if(t.kind==="boolean")return"boolean";if(t.kind!=="union")return;const n=new Set((t._meta?.members??[]).filter(r=>u(r)!=="null").map(r=>p(r))),[o]=n;return n.size===1?o:void 0},O=e=>t=>{const n=Object.hasOwn(e.shape,t)?e.shape[t]:void 0;return n===void 0?void 0:p(n)},A=(e,t)=>v(t,O(e)),I=(e,t,n)=>{try{return E(t,n,O(e))}catch(o){throw o instanceof s?new a("VALIDATION_ERROR",o.message):o}},h=e=>{throw e instanceof g?new a("VALIDATION_ERROR",e.message):e},y=e=>{if(e===void 0)return;const t=l(e);if(t.kind==="object")return t._meta?.shape;if(t.kind!=="union")return;const n=(t._meta?.members??[]).filter(o=>u(o)!=="null");return n.length===1?y(n[0]):void 0},N=(e,t)=>{let n=e.shape[t[0]??""];for(const o of t.slice(1)){const r=y(n);n=r!==void 0&&Object.hasOwn(r,o)?r[o]:void 0}return n},_=(e,t,n)=>{let o=[];try{o=F(t)}catch(i){h(i)}const r=N(e,o);if(r===void 0)throw new a("VALIDATION_ERROR",`patch: "${t}" is not a path into an object column of this table`);if(p(r)!==void 0&&b(n))throw new a("VALIDATION_ERROR",`patch: "${t}" is nested inside a column; operators like increment apply to a top-level column only`);if(typeof r.parse=="function")try{r.parse(n)}catch(i){throw new a("VALIDATION_ERROR",`patch: "${t}" ${i instanceof Error?i.message:"is invalid"}`)}},S=(e,t,n)=>{for(const[o,r]of Object.entries(t))m(o)&&_(e,o,r);try{return R(t,n)}catch(o){return h(o)}},V=(e,t,n)=>S(e,I(e,t,n),n),x=(e,t)=>A(e,t).size>0||Object.keys(t).some(n=>m(n)),z=(e,t,n)=>{if(e?.verify!==void 0&&!e.verify(t,n))throw new a("FORBIDDEN","update denied by policy")},K=(e,t)=>{try{return $(e,t)}catch(n){return h(n)}};export{z as assertPatchAllowed,A as operatorFields,x as patchDependsOnRow,K as readPatchField,V as resolvePatch};
@@ -0,0 +1 @@
1
+ import{isPlainObject as m,stableStringify as A,encodeWire as w,needsWireEncoding as J}from"@lunora/wire";const D="_id",p="_creationTime",y="page",_=e=>{let t;for(const s of e){const o=s[p];if(typeof o=="number"){if(t!==void 0){if(o<t)return!0;if(o>t)return!1}t=o}}return!1},F=(e,t)=>{const s=t[p];if(typeof s!="number")return e.length;const o=_(e);for(const[n,r]of e.entries()){const i=r[p];if(typeof i=="number"&&(o?i<s:i>s))return n}return e.length},L="__lunora__",E=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return;const t=e[D];return typeof t=="string"?t:void 0},I=e=>{const t=new Map,s=[];for(const o of e){const n=E(o);if(n===void 0||t.has(n))return;t.set(n,o),s.push(n)}return{byId:t,order:s}},N=(e,t)=>{const s=e.order.filter(n=>t.byId.has(n)),o=t.order.filter(n=>e.byId.has(n));return s.length!==o.length?!1:s.every((n,r)=>o[r]===n)},R=(e,t,s,o)=>{const n=[];for(const r of e.order)t.byId.has(r)||n.push({delta:{key:r,op:"delete",table:s},frame:`{"key":${JSON.stringify(r)},"op":"delete","table":${o}}`});return n},P=(e,t,s,o)=>{const n=[];for(const r of t.order){const i=t.byId.get(r),c=e.byId.get(r),d=JSON.stringify(J(i)?w(i):i),a=c===void 0?void 0:JSON.stringify(c);if(a===d)continue;const f=a===void 0?"insert":"update";n.push({delta:{key:r,op:f,row:i,table:s},frame:`{"key":${JSON.stringify(r)},"op":"${f}","row":${d},"table":${o}}`})}return n},T=(e,t)=>{if(Array.isArray(e)&&Array.isArray(t))return{next:t,previous:e};if(!m(e)||!m(t))return;const s=e[y],o=t[y];if(!Array.isArray(s)||!Array.isArray(o))return;const n=r=>Object.fromEntries(Object.entries(r).filter(([i])=>i!==y));if(A(n(e))===A(w(n(t))))return{next:o,previous:s}},k=(e,t,s)=>{const o=s.filter(({delta:r})=>r.op==="insert");if(o.length===0)return!0;const n=e.order.filter(r=>t.byId.has(r)).map(r=>e.byId.get(r));for(const{delta:r}of o){const i=r.row;n.splice(F(n,i),0,i)}return n.length===t.order.length&&n.every((r,i)=>r[D]===t.order[i])},O=(e,t,s)=>{let o;try{o=JSON.parse(e)}catch{return}const n=T(o,t);if(n===void 0)return;const r=I(n.previous),i=I(n.next);if(r===void 0||i===void 0||!N(r,i))return;const c=s===""?L:s,d=JSON.stringify(c),a=[...R(r,i,c,d),...P(r,i,c,d)];return k(r,i,a)?a:void 0},B=(e,t,s,o)=>{const n=O(e,t,s);if(n!==void 0){if(o!==void 0)for(const{frame:r}of n)o.push(r);return n.map(({delta:r})=>r)}},W=(e,t)=>{try{return e.send(t),!0}catch{return!1}},C=e=>{const{cursorSuffix:t,lastMutationId:s,nextResult:o,pageDeltas:n,previousJson:r,snapshotJson:i,subId:c,table:d}=e,a=JSON.stringify(c),f=s===void 0?"":`,"lastMutationId":${String(s)}`,g=f+t,l=`{"type":"data","id":${a},"data":${i}${g}}`,u=r!==void 0&&(n===!0||Array.isArray(o))?O(r,o,d):void 0;if(u===void 0||u.length===0)return[l];const v=[];let b=0;for(const[$,{frame:x}]of u.entries()){const S=$===u.length-1,h=`{"type":"delta","id":${a},"delta":${x}${S?g:f}}`;if(b+=h.length,b>=l.length)return[l];v.push(h)}return v},K=async e=>{let t=0;for(;t<100;){t+=1;const{bufferedAmount:s}=e;if(typeof s!="number"||s<1048576)return;await new Promise(o=>{setTimeout(o,20)})}};export{K as awaitWsDrain,C as subscriptionFrames,B as subscriptionListDeltas,W as trySendFrame};
@@ -0,0 +1 @@
1
+ import{m as P,c as E,l as w,r as T,a as D,w as F}from"./ctx-db-search-state-FjgzTFok.mjs";import{S as I,c as L,g as _,d as x,e as b,a as k}from"./fts-companion-CA8mLJWq.mjs";import{sql as i}from"drizzle-orm";import{ensureAggregateCompanion as y,ensureRankCompanion as B}from"./createCompanionSync-BMS8yYTx.mjs";import{runDrizzle as p,runAll as C}from"./runDrizzle-RC09zZrh.mjs";import{i as M,D as m,h as A}from"./do-sql-BWrJQAOh.mjs";import{sqliteInList as U}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";const v=(e,o)=>p(e,i`SELECT 1 FROM ${i.identifier(o)} LIMIT 1`).toArray().length>0,Q=(e,o)=>{for(const[r,n]of Object.entries(o.tables))if(n.shardMode?.kind!=="global")for(const t of n.aggregateIndexes??[])y(e,r,t,n.softDeleteMode?.field)},X=(e,o)=>{for(const[r,n]of Object.entries(o.tables))if(n.shardMode?.kind!=="global")for(const t of n.rankIndexes??[])B(e,r,t,n.softDeleteMode?.field)},H=(e,o,r,n)=>p(e,r===void 0?i`SELECT id, _creationTime, ${i.identifier(m)} FROM ${i.identifier(o)} ORDER BY id ASC LIMIT ${i.raw(String(n))}`:i`SELECT id, _creationTime, ${i.identifier(m)} FROM ${i.identifier(o)} WHERE id > ${r} ORDER BY id ASC LIMIT ${i.raw(String(n))}`).toArray(),h=500,O=(e,o,r)=>{const n=I(o,r.name),t=E(r),a=w(T(e,n),t);if(a.finished)return{done:!0,rows:0};const{cursor:c}=a,s=H(e,o,c,h);let f=c;for(const g of s){const{id:u}=g;if(typeof u!="string")continue;f=u;const S=A(g);C(e,S?x(n,u,b(S,r)):k(n,u))}const d=s.length<h;return F(e,n,f,d,t),{done:d,rows:s.length}},l=(e,o)=>i`${i.identifier(e)}.${i.identifier(o)}`,R=500,$=(e,o,r)=>{const n=I(o,r.name),t=p(e,L(n,R)).toArray(),a=_(t);if(a.size===0)return!0;const c=new Map;for(const s of p(e,i`SELECT ${l(o,"id")}, ${l(o,"_creationTime")}, ${l(o,m)} FROM ${i.identifier(o)} WHERE ${U(l(o,"id"),[...a.keys()],!1)}`))c.set(String(s.id),s);for(const[s,f]of a){const d=c.get(s),g=d?A(d):void 0;C(e,g?x(n,s,b(g,r),{unmappedRowids:f}):k(n,s,{unmappedRowids:f}))}return t.length<R},W=(e,o,r,n)=>{let t=0;for(;t<n&&!$(e,o,r);)t+=1;return t},Z=(e,o,r)=>{const n=I(o,r.name),t=E(r);return w(T(e,n),t).finished?!0:D(e,n)},q=(e,o,r)=>{if(M(e))for(const n of r.searchIndexes??[])$(e,o,n),!(n.staged&&v(e,o))&&O(e,o,n)},j=(e,o,r,n)=>{let t=0;for(;;){if(t>=n)return{done:!1,pages:t};const a=O(e,o,r);if(a.rows>0&&(t+=1),a.done)return{done:!0,pages:t}}},ee=(e,o,r={})=>{if(!M(e))return{done:!0,pages:0};P(e);const n=r.maxPages??Number.POSITIVE_INFINITY;let t=0;for(const[a,c]of Object.entries(o.tables))if(!(c.shardMode?.kind==="global"||!c.searchIndexes))for(const s of c.searchIndexes){if(t+=W(e,a,s,n-t),t>=n)return{done:!1,pages:t};const f=j(e,a,s,n-t);if(t+=f.pages,!f.done)return{done:!1,pages:t}}return{done:!0,pages:t}};export{Q as backfillAggregateIndexes,X as backfillRankIndexes,ee as backfillSearchIndexes,q as backfillSearchIndexesForTable,H as readKeysetPage,Z as searchIndexCoversTable};
@@ -0,0 +1 @@
1
+ import{float64SqlKey as m}from"./BIGINT_KEY_DIGITS-DE6yshOt.mjs";const a="!",l="￿",d=void 0,w=t=>{const o=new TextEncoder().encode(t);let r="";for(const e of o)r+=e.toString(16).padStart(2,"0");return r},v=t=>t===null?"0":typeof t=="number"?Number.isFinite(t)?`1${m(t)}`:d:typeof t=="string"?`2${w(t)}`:d,x=t=>{const o=[];for(const r of t){const e=v(r);if(e===d)return d;o.push(e)}return o.join(a)},E="=",h=new Set([">",">="]),y=new Set(["<","<="]),g=(t,o,r,e)=>{const i=o.comparator===E,n=h.has(o.comparator)||y.has(o.comparator);return!i&&!n||t.indexOf(o.field)!==r?!1:e===void 0?!0:!i&&e===o.field},S=(t,o,r)=>{const e={equalities:[],lowerExclusive:!1,upperExclusive:!1};let i;for(const n of o){const s=n.comparator===E,c=h.has(n.comparator);if(!g(t,n,e.equalities.length,i))return;if(s){e.equalities.push(r(n.value));continue}if(i=n.field,c){if(e.lower!==void 0)return;e.lower=r(n.value),e.lowerExclusive=n.comparator===">"}else{if(e.upper!==void 0)return;e.upper=r(n.value),e.upperExclusive=n.comparator==="<"}}return e},p=(t,o)=>{const r=v(o);if(r!==void 0)return t===""?r:t+a+r},q=(t,o,r,e,i)=>{if(r.length===0)return;const n=S(r,e,i);if(!n)return;const s=x(n.equalities);if(s===void 0)return;let c=s,f=s+l;if(n.lower!==void 0){const u=p(s,n.lower);if(u===void 0)return;c=n.lowerExclusive?u+a+l:u}if(n.upper!==void 0){const u=p(s,n.upper);if(u===void 0)return;f=n.upperExclusive?u:u+l}if(!(c>=f))return{hi:f,index:o,lo:c,table:t}},R=(t,o,r)=>{const e=[];for(const i of t){const n=x(i.fields.map(s=>r(o[s])));n!==void 0&&e.push({index:i.name,key:n})}return e},b=(t,o)=>t.index===o.index&&o.key>=t.lo&&o.key<t.hi,T=(t,o)=>{if(!t||t.length===0||!o||o.length===0)return!0;const r=new Map;for(const e of o){const i=r.get(e.index);i?i.push(e):r.set(e.index,[e])}return t.some(e=>{const i=r.get(e.index);return!i||i.length===0?!0:i.some(n=>b(e,n))})};export{q as buildIndexRange,R as indexKeysForRow,T as keysTouchRanges,b as rangeContains};
@@ -0,0 +1 @@
1
+ import{encodeWire as h}from"@lunora/wire";const u=(t,e)=>{if(!e)return t;const a=Object.create(null);for(const s of["_id","_creationTime",...e])Object.hasOwn(t,s)&&(a[s]=t[s]);return a},y=(t,e,a)=>{const{columns:s,table:p}=a,i=new Map,c=[];for(const{doc:n,id:r}of t){const o=u(n,s),d=JSON.stringify(h(o));i.set(r,d);const f=e.get(r);f===void 0?c.push({key:r,op:"insert",table:p,value:o}):f!==d&&c.push({key:r,op:"update",table:p,value:o})}for(const n of e.keys())i.has(n)||c.push({key:n,op:"delete",table:p});return{next:i,rowsPatch:c}},k=t=>t.map(e=>e.value===void 0?e:{...e,value:h(e.value)}),b=(t,e,a={})=>{const{baseCheckpoint:s,checkpoint:p,epoch:i,lastMutationId:c,pokeId:n}=e,r=[JSON.stringify({baseCheckpoint:s,epoch:i,pokeId:n,type:"pokeStart"})];for(const o of t){const d=a.preEncoded?o.rowsPatch:k(o.rowsPatch),f=o.baseCheckpoint??s;r.push(JSON.stringify({pokeId:n,rowsPatch:d,shapeId:o.shapeId,type:"pokePart",...c===void 0?{}:{lastMutationId:c},...f===void 0?{}:{baseCheckpoint:f},...o.reset===!0?{reset:!0}:{}}))}return r.push(JSON.stringify({checkpoint:p,epoch:i,pokeId:n,type:"pokeEnd"})),r};export{b as buildPokeFrames,y as diffGlobalMembership,k as encodeRowsPatch,u as projectColumns};
@@ -0,0 +1 @@
1
+ import{encodeWire as u}from"@lunora/wire";import{quoteIdentifier as l}from"./quoteIdentifier-CObIFRhb.mjs";import{reprojectionMigrationTable as d}from"./REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{REPROJECTION_MIGRATION_PREFIX as v,reprojectionMigrationId as w}from"./REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{runSql as p}from"./runDrizzle-RC09zZrh.mjs";import{k as m,D as E}from"./do-sql-BWrJQAOh.mjs";import{mayHoldProjectedValue as g}from"./BIGINT_KEY_DIGITS-DE6yshOt.mjs";const b=u(0n)[0],_=e=>e.shardMode?.kind==="global"?[]:Object.entries(e.shape).filter(([,r])=>g(r)).map(([r])=>r),M=e=>Object.entries(e.tables).filter(([,r])=>_(r).length>0).map(([r])=>r),f=e=>{const r=`json_each(${l(E)}) AS __f__`;return{params:[JSON.stringify(e),b,"bigint","bytes"],sql:`EXISTS (SELECT 1 FROM ${r} WHERE __f__.type = 'array' AND __f__.key IN (SELECT value FROM json_each(?)) AND json_extract(__f__.value, '$[0]') = ? AND json_extract(__f__.value, '$[1]') IN (?, ?))`}},N=(e,r,o)=>{if(o.length===0)return 0;const{params:t,sql:n}=f(o);return p(e,`SELECT COUNT(*) AS count FROM ${l(r)} WHERE ${n}`,...t).toArray()[0]?.count??0},R=(e,r,o,t)=>{const{params:n,sql:i}=f(o);return p(e,`SELECT 1 FROM ${l(r)} WHERE id = ? AND (${i}) LIMIT 1`,t,...n).toArray().length>0},S=(e,r,o)=>{const t=d(e);if(t===void 0)return;const n=r.tables[t];if(!n)return;const i=_(n);if(i.length!==0)return{id:e,table:t,up:s=>{const a=s._id;if(!(typeof a!="string"||!R(o,t,i,a))){try{m(s)}catch(c){console.warn(`${e}: skipping row ${a} — it cannot be re-projected: ${c instanceof Error?c.message:String(c)}`);return}return s}}}};export{v as REPROJECTION_MIGRATION_PREFIX,S as buildReprojectionMigration,N as countLegacyRows,_ as reprojectableFields,w as reprojectionMigrationId,M as reprojectionTables};
@@ -0,0 +1 @@
1
+ const f=/key|secret|token|password|passwd|credential|private|auth|bearer|session|cookie|salt|signature|dsn|webhook/iu,l=new Set(["LUNORA_ADMIN_TOKEN","LUNORA_WS_BEARER"]),d=["CF_PAGES_URL","WORKER_URL","LUNORA_WORKER_URL"],u=["CF_ENV","ENVIRONMENT","WORKER_ENV","NODE_ENV"],p=n=>n.length<=4?"••••":`${n.slice(0,4)}${"•".repeat(Math.min(8,n.length-4))}`,R=n=>f.test(n),E=n=>{const e=o=>typeof n[o]=="function";return e("idFromName")||e("idFromString")?"durable-object":e("createMultipartUpload")||e("put")&&e("get")&&e("list")&&e("head")?"r2":e("getWithMetadata")?"kv":e("prepare")&&e("dump")?"d1":e("send")&&e("sendBatch")?"queue":e("fetch")&&!e("get")?"service":"object"},N=n=>{if(typeof n!="object"||n===null)return{};const e=n,o=i=>i.map(c=>e[c]).find(c=>typeof c=="string"&&c!==""),t={},r=o(d),s=o(u);r!==void 0&&(t.workerUrl=r),s!==void 0&&(t.environment=s);const a=e.CF_VERSION_METADATA;if(a!==null&&typeof a=="object"){const i=a;typeof i.id=="string"&&(t.deploymentId=i.id),typeof i.tag=="string"&&(t.versionTag=i.tag)}return t},_=/^(?:dev(?:elopment)?|local(?:host)?|test)$/iu,g=n=>{const e=n??{};for(const o of u){const t=e[o];if(typeof t=="string"&&_.test(t))return!0}return!1},v=n=>{const e=n??{},o=[];for(const[t,r]of Object.entries(e))if(!l.has(t)){if(typeof r=="string"){const s=R(t);o.push({kind:s?"secret":"var",name:t,value:p(r)});continue}if(typeof r=="number"||typeof r=="boolean"){o.push({kind:"var",name:t,value:String(r)});continue}if(r!==null&&typeof r=="object"){o.push({bindingType:E(r),kind:"binding",name:t,value:null});continue}o.push({kind:"var",name:t,value:null})}return o.sort((t,r)=>t.name.localeCompare(r.name)),{deploy:N(e),settings:o}};export{v as buildSettings,g as isDevEnvironment,N as readDeployInfo};
@@ -0,0 +1 @@
1
+ import{readCdcChangeKeys as s}from"./CDC_LOG_TABLE-C7o2xrt1.mjs";import{selectShapeMembers as h}from"./selectShapeMembers-BCfKypfN.mjs";import{shapeRangeKey as u}from"./ShapeDiffCache-iNO-hUiy.mjs";import{projectColumns as g}from"./buildPokeFrames-WR-hp0mX.mjs";const C=(m,e,a,i,p,f=s)=>{const r=u(e.table,a,i),n=p.changedKeys(r,()=>f(m,e.table,a,i));if(n.length===0)return[];const b=p.members(e,r,()=>h(m,e.table,e.effectiveWhere,n.map(t=>t.id))),o=[];for(const t of n){const c=b.get(t.id);if(c===void 0){t.op!=="insert"&&o.push({key:t.id,op:"delete",table:e.table});continue}o.push({key:t.id,op:t.op,table:e.table,value:g(c,e.columns)})}return o};export{C as buildShapeDiff};
@@ -0,0 +1 @@
1
+ import{sql as t}from"drizzle-orm";import{compareStrings as a,encodeAggregateKey as T}from"./aggregateTableName-B_CtIQCS.mjs";import{runDrizzle as r}from"./runDrizzle-RC09zZrh.mjs";import{sqliteInList as f}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";const n="__lunora_companion_state",g=1,c=1,E=i=>i?T(Object.keys(i),i):"",$=(i,e)=>JSON.stringify([g,(i.by??[]).toSorted(a),i.field??"",i.op,E(i.where),e??""]),d=(i,e)=>JSON.stringify([c,(i.partitionBy??[]).toSorted(a),i.sortBy.map(o=>o.field),E(i.where),e??""]),s=i=>{r(i,t`CREATE TABLE IF NOT EXISTS ${t.identifier(n)} (${t.identifier("companion")} TEXT PRIMARY KEY, ${t.identifier("signature")} TEXT NOT NULL)`)},u=(i,e)=>{s(i),r(i,e.length===0?t`DELETE FROM ${t.identifier(n)}`:t`DELETE FROM ${t.identifier(n)} WHERE ${f(t.raw('"companion"'),e,!0)}`)},R=(i,e)=>r(i,t`SELECT ${t.identifier("signature")} FROM ${t.identifier(n)} WHERE ${t.identifier("companion")} = ${e}`).toArray()[0]?.signature,A=(i,e,o)=>{r(i,t`INSERT INTO ${t.identifier(n)} (${t.identifier("companion")}, ${t.identifier("signature")}) VALUES (${e}, ${o}) ON CONFLICT (${t.identifier("companion")}) DO UPDATE SET ${t.identifier("signature")} = excluded.${t.identifier("signature")}`)},N=i=>{s(i),r(i,t`DELETE FROM ${t.identifier(n)}`)};export{$ as aggregateSignature,N as clearCompanionSignatures,u as migrateCompanionState,d as rankSignature,R as readCompanionSignature,A as writeCompanionSignature};
@@ -0,0 +1 @@
1
+ import{sql as t}from"drizzle-orm";import{runDrizzle as s}from"./runDrizzle-RC09zZrh.mjs";const a=r=>r?.memoryMode===!0,l=r=>Object.entries(r.tables).filter(([,e])=>a(e)&&e.shardMode?.kind!=="global").map(([e])=>e),i=(r,e)=>{const o=l(e);for(const m of o)s(r,t`DELETE FROM ${t.identifier(m)}`);return o.length};export{i as clearMemoryTables,a as isMemoryTable,l as memoryTableNames};
@@ -0,0 +1 @@
1
+ import"./json-field-path-DeJW4U9z.mjs";import"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{c as p,s}from"./where-sql-BjY4rnqb.mjs";import"./RELATION_EXISTS_KEY-wxgj6rSL.mjs";export{p as compileWhereSql,s as serverInList};
@@ -0,0 +1 @@
1
+ import{LunoraError as g}from"@lunora/errors";import{sql as o}from"drizzle-orm";import{mergeWhere as b}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{SCAN_DEP as j}from"./SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as A}from"./runDrizzle-RC09zZrh.mjs";import{sqliteInList as O}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{decodeCursor as F,CURSOR_PREFIX as P,toBase64 as U}from"./CURSOR_PREFIX-6offuG6M.mjs";import{rankTableName as V,sortColumnName as z,resolveRankPartition as H,RANK_TIEBREAK as _,encodePartitionKey as J,rankPivotConditionSql as X}from"./RANK_TIEBREAK-D3ye2GsL.mjs";const Y="__doc__",G=n=>P+U(JSON.stringify(n)),Q=n=>n.after?[n.after.partitionKey,...n.after.sortValues,n.after.rowId]:n.cursor?F(n.cursor):void 0,Z=(n,r,f)=>{if(n?.length!==1+r.length+1)return;const t=[{column:"__partition__",direction:"asc"}];for(const[c,u]of r.entries())t.push({column:u,direction:f[c]?.direction??"asc"});t.push({column:_,direction:"asc"});const e=[];for(const[c,u]of t.entries()){const d=X(u.column,n[c],u.direction,!0);if(d===void 0)continue;const s=[];for(const[m,l]of t.slice(0,c).entries())s.push(o`${o.identifier(l.column)} IS ${n[m]}`);s.push(d);const[i]=s;e.push(s.length===1&&i!==void 0?i:o`(${o.join(s,o` AND `)})`)}return e.length===0?o`(1 = 0)`:o`(${o.join(e,o` OR `)})`},v=null,oo=(n,r)=>{if(n===void 0)return v;const f=[n.__partition__,...r.map(t=>n[t]),n[_]];return G(f)},no=(n,r,f)=>{const t=[];for(const e of n){const c=e[_];if(typeof c!="string")continue;const u=r.get(c);if(!u)continue;const d=typeof e.__partition__=="string"?e.__partition__:"",s=f.map(i=>e[i]??null);t.push({doc:u,key:{partitionKey:d,rowId:c,sortValues:s}})}return t},to=o`${o.identifier("id")}`,ro=(n,r,f)=>{const{rowToDocument:t}=n,e=new Map;if(f.length===0)return e;const c=A(n.sql,o`SELECT id, _creationTime, ${o.identifier(Y)} FROM ${o.identifier(r)} WHERE ${O(to,f,!1)}`).toArray();for(const u of c){const d=t(u),s=u.id;d&&typeof s=="string"&&e.set(s,d)}return e},_o=(n,r,f,t)=>{const{assertRankPartitionLocal:e,ensureRankBackfilled:c,onRead:u,schema:d}=n,s=d.tables[r];if(!s)throw new g("INTERNAL",`unknown table: ${r}`);const i=s.rankIndexes?.find(a=>a.name===f);if(!i)throw new g("INTERNAL",`unknown rankIndex "${f}" on table "${r}"`);e(r,s,i),u(r,j),c(r,i);const m=V(r,i.name),l=i.sortBy.map((a,w)=>z(w)),h=Math.max(1,Math.min(1e3,Math.floor(t.take??100))),T=b(t.baseWhere,t.where),k=H(i,T),R=[o`${o.identifier("__partition__")} ASC`];for(const[a,w]of l.entries()){const W=i.sortBy[a]?.direction;R.push(o`${o.identifier(w)} ${o.raw(W==="desc"?"DESC":"ASC")}`)}R.push(o`${o.identifier(_)} ASC`);const p=[];typeof t.partitionKey=="string"?p.push(o`${o.identifier("__partition__")} = ${t.partitionKey}`):k&&p.push(o`${o.identifier("__partition__")} = ${J(i.partitionBy??[],k)}`);const B=Q(t),E=Z(B,l,i.sortBy);E&&p.push(E);const I=o.identifier(_),S=o.identifier("__partition__"),D=p.length>0?o` WHERE ${o.join(p,o` AND `)}`:o``,L=l.length>0?o`${I}, ${S}, ${o.join(l.map(a=>o.identifier(a)),o`, `)}`:o`${I}, ${S}`,M=o`SELECT ${L} FROM ${o.identifier(m)}${D} ORDER BY ${o.join(R,o`, `)} LIMIT ${o.raw(String(h+1))}`,$=A(n.sql,M).toArray(),C=$.length>h,y=C?$.slice(0,h):$,K=y.map(a=>a[_]),q=no(y,ro(n,r,K),l),x=C?oo(y.at(-1),l):v,N=i.sortBy.map(a=>a.direction==="desc"?"desc":"asc");return{continueCursor:x,directions:N,hasMore:C,rows:q}};export{_o as computeRankPage,Q as resolveRankSeekTuple};
@@ -0,0 +1 @@
1
+ import{N as co,S as ao,d as fo,e as lo,a as uo}from"./fts-companion-CA8mLJWq.mjs";import{sql as o}from"drizzle-orm";import{r as z}from"./json-field-path-DeJW4U9z.mjs";import{matchesStaticWhere as Q,aggregateSqlFunction as $o}from"./AGGREGATE_SQL_FUNCTION-C_ZipS9R.mjs";import{aggregateTableName as H,foldAggregateTally as X,encodeAggregateKey as k,coerceAggregateNumber as U}from"./aggregateTableName-B_CtIQCS.mjs";import{aggregateSignature as Eo,readCompanionSignature as Y,rankSignature as go,writeCompanionSignature as J}from"./clearCompanionSignatures-3MlVqWZD.mjs";import{runAll as po,runDrizzle as g}from"./runDrizzle-RC09zZrh.mjs";import{i as mo,g as _o,a as O,b as T,A as _,c as j,D as Z,r as N,e as P}from"./do-sql-BWrJQAOh.mjs";import{WORKERD_SQLITE_LIMITS as yo,param as ho}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{encodeGeohash as So,GEO_DEFAULT_PRECISION as To}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{isLiveForCompanion as x}from"./CURSOR_PREFIX-6offuG6M.mjs";import{rankTableName as B,matchesRankStaticWhere as oo,sortColumnName as Ro,encodePartitionKey as Ao}from"./RANK_TIEBREAK-D3ye2GsL.mjs";import{mayHoldProjectedValue as wo}from"./BIGINT_KEY_DIGITS-DE6yshOt.mjs";import{serializeSqlValue as eo}from"./serializeSqlValue-DeoBMpZ2.mjs";const Co=(s,l,r)=>[...s.partitionBy??[],...s.sortBy.map(f=>f.field),...s.where?Object.keys(s.where):[]].every(f=>z(l,f)===z(r,f)),no=s=>o.join(["__id__","__partition__",...s.sortBy.map((l,r)=>Ro(r))].map(l=>o.identifier(l)),o`, `),ro=(s,l,r,E,f,a)=>{const t=Ao(r.partitionBy??[],a),R=r.sortBy.map(A=>eo(a[A.field]??null)),y=o.join([f,t,...R].map(A=>ho(A)),o`, `);g(s,o`INSERT INTO ${o.identifier(l)} (${E}) VALUES (${y})`)},to=(s,l,r,E)=>{const f=[];for(const a of g(s,o`SELECT id, _creationTime, ${o.identifier(Z)} FROM ${o.identifier(l)}`)){const t=N(a);t&&x(t,r)&&E(t)&&f.push(t)}return f},vo=(s,l,r,E,f)=>{const a=H(l,r.name),t=r.by??[],R=new Map;for(const w of to(s,l,E,L=>!r.where||Q(L,r.where)))X(R,k(t,w),r,w);g(s,o`DELETE FROM ${o.identifier(a)}`);const y=Math.floor(yo.boundParams/3),A=[...R];for(let w=0;w<A.length;w+=y){const L=A.slice(w,w+y),G=o.join(L.map(([b,D])=>o`(${b}, ${D.value}, ${D.count})`),o`, `);g(s,o`INSERT INTO ${o.identifier(a)} (${O}, ${T}, ${_}) VALUES ${G}`)}J(s,a,f)},Io=(s,l,r,E)=>{const f=Eo(r,E);Y(s,H(l,r.name))!==f&&vo(s,l,r,E,f)},ko=(s,l,r,E,f)=>{const a=B(l,r.name),t=no(r),R=to(s,l,E,y=>!r.where||oo(y,r.where));g(s,o`DELETE FROM ${o.identifier(a)}`);for(const y of R)ro(s,a,r,t,y._id,y);J(s,a,f)},Fo=(s,l,r,E)=>{const f=go(r,E);Y(s,B(l,r.name))!==f&&ko(s,l,r,E,f)},Oo=(s,l,r,E,f,a)=>{if(f&&a&&Co(r,f,a))return;const t=B(l,r.name);f&&g(s,o`DELETE FROM ${o.identifier(t)} WHERE ${o.identifier("__id__")} = ${E}`),!(!a||r.where&&!oo(a,r.where))&&ro(s,t,r,no(r),E,a)},Qo=s=>{const{broadcast:l,indexKeysFor:r,invalidateCache:E,recordCdc:f,schema:a,sql:t}=s,R=new Set,y=e=>a.tables[e]?.softDeleteMode?.field,A=(e,n)=>{const c=H(e,n.name);R.has(c)||(Io(t,e,n,y(e)),R.add(c))},w=(e,n,c)=>{const p=n.by??[],d=n.field??"",$=[],h=(i,u)=>{const m=eo(u);m===null?$.push(o`${P(i)} IS NULL`):$.push(o`${P(i)} = ${m}`)};for(const i of p)h(i,c[i]??null);const C=y(e);C!==void 0&&h(C,null);for(const[i,u]of Object.entries(n.where??{}))h(i,u!==null&&typeof u=="object"&&!Array.isArray(u)?u.eq:u);const F=$.length>0?o` WHERE ${o.join($,o` AND `)}`:o``,M=a.tables[e]?.shape[d];if(M&&wo(M)){const i=g(t,o`SELECT id, _creationTime, ${o.identifier(Z)} FROM ${o.identifier(e)}${F}`).toArray(),u=new Map;for(const m of i){const I=N(m);I&&X(u,"",n,I)}return{value:u.get("")?.value??null}}const W=$o(n.op),S=P(d);return{value:g(t,o`SELECT ${o.raw(W)}(${S}) AS value FROM ${o.identifier(e)}${F}`).one().value??null}},L=(e,n,c,p)=>{const d=H(e,n.name),{op:$}=n,h=n.field??"",C=i=>{g(t,o`DELETE FROM ${o.identifier(d)} WHERE ${O} = ${i} AND ${_} <= 0`)},F=y(e),M=i=>!n.where||Q(i,n.where),W=i=>x(i,F)&&M(i);p!==void 0&&$!=="count"&&M(p)&&U(p[h]);const S=c&&W(c)?c:void 0,v=p&&W(p)?p:void 0;if(!(!S&&!v)){if($==="count"){for(const[i,u]of[[S,-1],[v,1]]){if(!i)continue;const m=k(n.by??[],i);g(t,j(d,m,u,u,o`${T} = ${T} + excluded.${T}, ${_} = ${_} + excluded.${_}`))}S&&C(k(n.by??[],S));return}if($==="sum"||$==="avg"){for(const[i,u]of[[S,-1],[v,1]]){if(!i)continue;const m=U(i[h]);if(m===void 0)continue;const I=k(n.by??[],i);g(t,j(d,I,u*m,u,o`${T} = COALESCE(${T}, 0) + excluded.${T}, ${_} = ${_} + excluded.${_}`))}S&&C(k(n.by??[],S));return}if(S){const i=k(n.by??[],S),u=U(S[h]),m=g(t,o`SELECT ${T} AS value, ${_} AS count FROM ${o.identifier(d)} WHERE ${O} = ${i}`).toArray()[0],I=(m?.count??0)-1;if(I<=0)g(t,o`DELETE FROM ${o.identifier(d)} WHERE ${O} = ${i}`);else if(m&&u!==void 0&&m.value!==null&&u===m.value){const io=w(e,n,S);g(t,o`UPDATE ${o.identifier(d)} SET ${T} = ${io.value}, ${_} = ${I} WHERE ${O} = ${i}`)}else g(t,o`UPDATE ${o.identifier(d)} SET ${_} = ${_} - 1 WHERE ${O} = ${i}`)}if(v){const i=k(n.by??[],v),u=U(v[h]);if(u===void 0)g(t,j(d,i,null,1,o`${_} = ${_} + 1`));else{const m=$==="min"?"MIN":"MAX";g(t,j(d,i,u,1,o`${T} = ${o.raw(m)}(COALESCE(${T}, excluded.${T}), excluded.${T}), ${_} = ${_} + 1`))}}}},G=e=>{for(const n of a.tables[e]?.aggregateIndexes??[])A(e,n)},b=(e,n,c)=>{for(const p of a.tables[e]?.aggregateIndexes??[])L(e,p,n,c)},D=(e,n)=>{const c=B(e,n.name);R.has(c)||(Fo(t,e,n,y(e)),R.add(c))},so=e=>{for(const n of a.tables[e]?.rankIndexes??[])D(e,n)},V=(e,n,c,p)=>{for(const d of a.tables[e]?.rankIndexes??[])Oo(t,e,d,n,c,p)},K=(e,n,c,p)=>{const d=a.tables[e]?.searchIndexes??[];if(!(d.length===0||!mo(t)))for(const $ of d){if(co(p,c,$))continue;const h=ao(e,$.name);po(t,c?fo(h,n,lo(c,$)):uo(h,n))}},q=(e,n,c)=>{for(const p of a.tables[e]?.geoIndexes??[]){const d=_o(e,p.name);g(t,o`DELETE FROM ${o.identifier(d)} WHERE ${o.identifier("__id__")} = ${n}`);const $=c?.[p.field];if($!==null&&typeof $=="object"&&typeof $.lat=="number"&&typeof $.lng=="number"){const{lat:h,lng:C}=$,F=So({lat:h,lng:C},p.precision??To);g(t,o`INSERT INTO ${o.identifier(d)} (${o.identifier("__id__")}, ${o.identifier("__geohash__")}, ${o.identifier("__lat__")}, ${o.identifier("__lng__")}) VALUES (${n}, ${F}, ${h}, ${C})`)}}};return{ensureBackfilledForTable:G,ensureBackfilledIndex:A,ensureRankBackfilled:D,ensureRankBackfilledForTable:so,syncAggregates:b,syncCompanionsForInsert:(e,n,c)=>{K(e,n,c),q(e,n,c),b(e,void 0,c),V(e,n,void 0,c),E(e,n,c),f(e,n,"insert",c),l({indexKeys:r(e,c),key:n,op:"insert",row:c,table:e})},syncGeo:q,syncRanks:V,syncSearch:K}};export{Qo as createCompanionSync,Io as ensureAggregateCompanion,Fo as ensureRankCompanion};
@@ -0,0 +1,7 @@
1
+ import{LunoraError as m}from"@lunora/errors";import{decodeWire as v,encodeWire as N}from"@lunora/wire";import{cursorBelowRetainedFloor as b}from"./CDC_LOG_TABLE-C7o2xrt1.mjs";import{envPositiveInt as E}from"./envOptionalPositiveInt-D2pY-c64.mjs";import{e as I}from"./estimate-bytes-_k74s6LZ.mjs";import{verifySiblingBody as L,RELAY_SIGNATURE_HEADER as S,siblingStub as O,siblingSecretOf as R,signSiblingBody as C}from"./RELAY_SIGNATURE_HEADER-C_P73AOx.mjs";import{DEFAULT_TRANSACTION_LIMITS as U}from"./DEFAULT_TRANSACTION_LIMITS-Dmj5VBrV.mjs";const q=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"],x=new Set(q),F=r=>typeof r=="string"&&x.has(r),w="::replica::",_=r=>{const e=r.lastIndexOf(w);if(e===-1)return;const t=r.slice(0,e),s=r.slice(e+w.length);if(!(t.length===0||!F(s)))return{ownerKey:t,region:s}},M=r=>{if(r==null||!/^\d+$/.test(r))return;const e=Number.parseInt(r,10);return Number.isSafeInteger(e)&&e>0?e:void 0},P=1e3,A=1e3,B=10,D=5e4,W=r=>E(r,"LUNORA_REPLICA_MAX_BOOTSTRAP_ROWS",D),f="__replica_state",g=new WeakSet,T=r=>{g.has(r)||(r.exec(`CREATE TABLE IF NOT EXISTS ${f} (
2
+ id INTEGER PRIMARY KEY CHECK (id = 1),
3
+ epoch TEXT NOT NULL,
4
+ applied_seq INTEGER NOT NULL,
5
+ synced_at REAL NOT NULL
6
+ )`),g.add(r))},h=r=>(T(r),r.exec(`SELECT epoch, applied_seq AS appliedSeq, synced_at AS syncedAtMs FROM ${f} WHERE id = 1`).toArray()[0]),l=(r,e)=>{T(r),r.exec(`INSERT INTO ${f} (id, epoch, applied_seq, synced_at) VALUES (1, ?, ?, ?)
7
+ ON CONFLICT(id) DO UPDATE SET epoch = excluded.epoch, applied_seq = excluded.applied_seq, synced_at = excluded.synced_at`,e.epoch,e.appliedSeq,e.syncedAtMs)},$=r=>{const e=r.doName();if(e!==void 0&&_(e)!==void 0)return new Response("replica cannot serve replicas",{status:409});if(r.ownerEpoch()===void 0)return new Response("shard has no changelog to replicate",{status:409});if(R(r.env())===void 0)return new Response("replica control requires LUNORA_RELAY_SECRET",{status:403})},p=r=>Response.json(N(r)),X=async(r,e)=>{if(r.rowCount()>W(r.env()))return p({cursor:0,epoch:e,rows:[],truncated:!0});const t=r.ownerCursor()??0,s=await r.exportRows();return p({cursor:t,epoch:e,rows:s})},k=(r,e,t)=>{const s=r.ownerFloor();if(b(s,t))return p({changes:[],cursor:r.ownerCursor()??t,epoch:e,floor:s});const n=r.ownerCursor()??0;if(t>n)return p({changes:[],cursor:n,epoch:e,...s===void 0?{}:{floor:s}});const{changes:o,cursor:i}=r.readChanges(t,A);return p({changes:o,cursor:i,epoch:e,...s===void 0?{}:{floor:s}})},ee=async(r,e)=>{const t=$(r);if(t!==void 0)return t;const s=r.ownerEpoch();let n;try{n=await e.text()}catch{return new Response("bad request",{status:400})}if(!await L(r.env(),e.headers.get(S),n))return new Response("forbidden",{status:403});let o;try{o=JSON.parse(n)}catch{return new Response("bad request",{status:400})}if(o.type==="replica_bootstrap")return X(r,s);if(o.type==="replica_pull"){const i=typeof o.sinceSeq=="number"&&Number.isInteger(o.sinceSeq)&&o.sinceSeq>=0?o.sinceSeq:0;return k(r,s,i)}return new Response("unknown replica frame",{status:400})},K=r=>{const e=r;return typeof r=="object"&&(e?.retryable===!0||e?.overloaded===!0)},j=(r,e)=>{const t=e.changes.length===0&&e.cursor>r.appliedSeq,s=e.floor??(t?e.cursor:0),n=s>0&&s>r.appliedSeq+1,o=e.cursor<r.appliedSeq;return e.epoch!==r.epoch||o?"fork":n?"compacted":void 0},y=(r,e)=>`${r}\0${e}`;class H{constructor(e,t,s){this.host=e,this.ownerKey=t,this.region=s}host;ownerKey;region;divergent=!1;inFlight;async ensureFresh(e){if(this.divergent)return"unavailable";if(this.isCaughtUp(e))return"fresh";this.inFlight??=this.advance(e).finally(()=>{this.inFlight=void 0});const t=await this.inFlight;return t==="fresh"&&!this.isCaughtUp(e)?"stale":t}appliedSeq(){return h(this.host.sql())?.appliedSeq??0}isDivergent(){return this.divergent}async advance(e){let t=h(this.host.sql());if(t===void 0){const s=await this.bootstrap();if(s===void 0)return"unavailable";t=s}return this.catchUp(t,e)}isCaughtUp(e){const t=h(this.host.sql());return t!==void 0&&this.isFreshEnough(t,e)}async catchUp(e,t){let s=e,n=!1;for(let o=0;o<B;o+=1){const i=await this.pull(s.appliedSeq);if(i===void 0)return this.whenOwnerUnreachable(s,t);const c=j(s,i);if(c!==void 0){const a=await this.recover(s,c,n);if(typeof a=="string")return a;n=!0,s=a;continue}const d=i.changes.length<A,u=await this.applyPage(i,s,d);if(u===void 0)return"unavailable";if(s=u,d||this.isFreshEnough(s,t))return this.verdict(s,t)}return this.verdict(s,t)}verdict(e,t){return this.isFreshEnough(e,t)?"fresh":"stale"}async recover(e,t,s){return t==="fork"?(this.divergent=!0,"unavailable"):s?"unavailable":await this.resnapshot(e)??"unavailable"}whenOwnerUnreachable(e,t){return t===void 0&&this.isFreshEnough(e,void 0)?"fresh":"unavailable"}async applyPage(e,t,s){if(!await this.applyAtomically("replica.applyPage",e.changes))return;const n={appliedSeq:e.cursor,epoch:e.epoch,syncedAtMs:s?Date.now():t.syncedAtMs};return l(this.host.sql(),n),n}async applyAtomically(e,t){if(t.length===0)return!0;try{return await this.host.applyChanges(t),!0}catch(s){return K(s)||(this.divergent=!0),this.host.reportError?.(e,s),!1}}async fetchSnapshot(){const e=await this.request({type:"replica_bootstrap"});if(e===void 0)return;const t=v(await e.json());if(t.truncated===!0){this.divergent=!0;return}return t}async resnapshot(e){const t=await this.fetchSnapshot();if(t===void 0)return;const s={...U,...this.host.transactionLimits()},n=[],o=new Set;let i=0;for(const{doc:d,table:u}of t.rows){const a=String(d._id);o.add(y(u,a)),i+=I(d)??Number.POSITIVE_INFINITY,n.push({doc:d,id:a,op:"insert",seq:t.cursor,table:u,ts:0})}if(this.overWriteBudget(n.length,i,s))return;for(const{doc:d,table:u}of await this.host.exportRows()){const a=String(d._id);o.has(y(u,a))||n.push({id:a,op:"delete",seq:t.cursor,table:u,ts:0})}if(this.overWriteBudget(n.length,i,s)||!await this.applyAtomically("replica.resnapshot",n))return;const c={appliedSeq:t.cursor,epoch:t.epoch,syncedAtMs:e.syncedAtMs};return l(this.host.sql(),c),c}overWriteBudget(e,t,s){return e<=s.maxWrittenRows&&t<=s.maxWrittenBytes?!1:(this.host.reportError?.("replica.resnapshot",new m("TRANSACTION_LIMIT_EXCEEDED",`a re-snapshot would write ${String(e)} documents and ${String(t)} bytes, over the ${String(s.maxWrittenRows)}-document / ${String(s.maxWrittenBytes)}-byte transaction limit`)),!0)}async bootstrap(){const e=await this.fetchSnapshot();if(e===void 0)return;const{errors:t}=await this.host.importRows(e.rows);if(t.length>0){this.divergent=!0;return}const s={appliedSeq:e.cursor,epoch:e.epoch,syncedAtMs:Date.now()};return l(this.host.sql(),s),s}isFreshEnough(e,t){return t!==void 0?e.appliedSeq>=t:Date.now()-e.syncedAtMs<=E(this.host.env(),"LUNORA_REPLICA_MAX_STALENESS_MS",P)}async pull(e){const t=await this.request({sinceSeq:e,type:"replica_pull"});return t===void 0?void 0:v(await t.json())}async request(e){const t=this.host.shardBinding(),s=O(this.host.env(),t,this.ownerKey,this.host.shardJurisdiction());if(s===void 0)return;const n=JSON.stringify(e),o={"content-type":"application/json","x-lunora-shard-binding":t??""},i=R(this.host.env());i!==void 0&&(o[S]=await C(i,n));try{const c=await s.fetch("https://replica.internal/_lunora/replica",{body:n,headers:o,method:"POST"});return c.ok?c:void 0}catch{return}}}const te=r=>{const e=r.doName();if(e===void 0)return;const t=_(e);return t===void 0?void 0:new H(r,t.ownerKey,t.region)},re=async(r,e,t)=>{if(e.headers.get("x-lunora-replica-read")!=="1")return Response.json({error:{code:"REPLICA_READ_ONLY",message:`"${t}" is a write and cannot run on a read replica`}},{status:421});const s=await r.ensureFresh(M(e.headers.get("x-lunora-min-seq")));if(s!=="fresh")return Response.json({error:{code:"REPLICA_NOT_READY",message:`replica is ${s} for this read`}},{headers:{"x-lunora-replica-fallback":s},status:421})};export{te as createReplicaLink,re as gateReplicaDispatch,ee as handleReplicaControl};
@@ -0,0 +1 @@
1
+ import{LunoraError as i}from"@lunora/errors";const c=t=>{const e={args:t.args??{},enqueuedAt:typeof t.enqueuedAt=="number"?t.enqueuedAt:0,id:typeof t.id=="string"?t.id:"",scheduledFor:typeof t.scheduledFor=="number"?t.scheduledFor:0};return typeof t.attempts=="number"&&(e.attempts=t.attempts),typeof t.functionPath=="string"&&(e.functionPath=t.functionPath),typeof t.pool=="string"&&(e.pool=t.pool),typeof t.shardKey=="string"&&(e.shardKey=t.shardKey),typeof t.workflow=="string"&&(e.workflow=t.workflow),e},f=t=>{const e={key:typeof t.key=="string"?t.key:"",size:typeof t.size=="number"?t.size:0},o=t.httpMetadata?.contentType??t.contentType;typeof o=="string"&&(e.contentType=o),t.customMetadata&&typeof t.customMetadata=="object"&&(e.customMetadata=t.customMetadata),typeof t.sha256=="string"&&(e.sha256=t.sha256);const{uploaded:n}=t;return typeof n=="number"?e.uploaded=n:n instanceof Date&&(e.uploaded=n.getTime()),e},p=(t={})=>{const e=()=>{if(!t.scheduler)throw new i("INTERNAL",'ctx.db.system.query("_scheduled_functions"): no scheduler configured. Pass `scheduler` to createShardDO().');return t.scheduler},o=()=>{if(!t.storage)throw new i("INTERNAL",'ctx.db.system.query("_storage"): no storage configured. Pass `storage` to createShardDO().');return t.storage},n=async()=>(await e().list()).map(a=>c(a)),d=async()=>{const{objects:s}=await o().list();return s.map(a=>f(a))};return{get:(async(s,a)=>{if(s==="_scheduled_functions"){const u=await e().get(a);return u?c(u):null}const r=await o().getMetadata(a);return r?f(r):null}),query:(s=>s==="_scheduled_functions"?{collect:n}:{collect:d})}};export{p as createSystemReader};
@@ -0,0 +1,17 @@
1
+ import{encodeWire as l,decodeWire as E}from"@lunora/wire";import{sql as i}from"drizzle-orm";import{runDrizzle as t}from"./runDrizzle-RC09zZrh.mjs";import{relayProxyKey as T}from"./DEFAULT_PROMOTION_THRESHOLDS-B3pRMuqb.mjs";const a="__lunora_relay_shapes",o=null,R=e=>{t(e,i`CREATE TABLE IF NOT EXISTS ${i.identifier(a)} (
2
+ key TEXT PRIMARY KEY,
3
+ relay_idx INTEGER,
4
+ connection_id TEXT,
5
+ name TEXT NOT NULL,
6
+ args TEXT NOT NULL,
7
+ identity TEXT NOT NULL,
8
+ cursor INTEGER NOT NULL
9
+ )`)},c=e=>JSON.stringify(l(e)),s=e=>E(JSON.parse(e)),$=e=>t(e,i`SELECT key, relay_idx, connection_id, name, args, identity, cursor FROM ${i.identifier(a)}`).toArray().map(r=>({args:s(r.args),connectionId:r.connection_id??void 0,cursor:Number(r.cursor),identity:s(r.identity),key:r.key,name:r.name,relayIndex:r.relay_idx===null?void 0:Number(r.relay_idx)})),L=(e,n)=>{t(e,i`INSERT INTO ${i.identifier(a)} (key, relay_idx, connection_id, name, args, identity, cursor)
10
+ VALUES (${n.key}, ${n.relayIndex??o}, ${n.connectionId??o}, ${n.name}, ${c(n.args)}, ${c(n.identity??{})}, ${n.cursor})
11
+ ON CONFLICT(key) DO UPDATE SET
12
+ relay_idx = excluded.relay_idx,
13
+ connection_id = excluded.connection_id,
14
+ name = excluded.name,
15
+ args = excluded.args,
16
+ identity = excluded.identity,
17
+ cursor = excluded.cursor`)},S=(e,n,r)=>{t(e,i`UPDATE ${i.identifier(a)} SET cursor = ${r} WHERE key = ${n}`)},x=(e,n,r,d)=>{const y=d===void 0?i``:i` AND key = ${T(n,r,d)}`;t(e,i`DELETE FROM ${i.identifier(a)} WHERE relay_idx = ${n} AND connection_id = ${r}${y}`)},p=(e,n)=>{t(e,i`DELETE FROM ${i.identifier(a)} WHERE relay_idx = ${n}`)},O=e=>{t(e,i`DELETE FROM ${i.identifier(a)}`)};export{L as a,p as b,O as c,x as d,R as m,$ as r,S as w};
@@ -0,0 +1 @@
1
+ import{D as E}from"./MAX_TOKEN_LENGTH-BakL9FUy-B3VwYY8C.mjs";import{sql as e}from"drizzle-orm";import{runDrizzle as t}from"./runDrizzle-RC09zZrh.mjs";const S=i=>`${E(i.language).profile}:${i.field}`,c=i=>{const r=i.slice(i.indexOf(":")+1),o=r.lastIndexOf("/");return o===-1?r:r.slice(0,o)},N=(i,r)=>i.profile!==r?{cursor:void 0,finished:!1,wipe:i.cursor!==void 0||i.done}:{cursor:i.cursor,finished:i.done,wipe:!1},T=(i,r)=>typeof i=="string"&&c(i)===c(r),n="__lunora_search_state",R=i=>{t(i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(n)} (${e.identifier("companion")} TEXT PRIMARY KEY, ${e.identifier("cursor")} TEXT, ${e.identifier("done")} INTEGER NOT NULL DEFAULT 0, ${e.identifier("profile")} TEXT, ${e.identifier("covered")} INTEGER NOT NULL DEFAULT 0)`);try{t(i,e`ALTER TABLE ${e.identifier(n)} ADD COLUMN ${e.identifier("profile")} TEXT`)}catch{}try{t(i,e`ALTER TABLE ${e.identifier(n)} ADD COLUMN ${e.identifier("covered")} INTEGER NOT NULL DEFAULT 0`)}catch{}t(i,e`UPDATE ${e.identifier(n)} SET ${e.identifier("covered")} = 1 WHERE ${e.identifier("done")} = 1 AND ${e.identifier("covered")} = 0`)},s=i=>i===1||i===!0||i==="1",O=(i,r)=>{const o=t(i,e`SELECT ${e.identifier("covered")} FROM ${e.identifier(n)} WHERE ${e.identifier("companion")} = ${r}`).toArray();return s(o[0]?.covered)},l=(i,r,o)=>{const d=t(i,e`SELECT ${e.identifier("cursor")}, ${e.identifier("done")}, ${e.identifier("profile")} FROM ${e.identifier(r)} WHERE ${e.identifier("companion")} = ${o}`).toArray()[0];return d?{cursor:d.cursor??void 0,done:s(d.done),profile:d.profile??void 0}:{cursor:void 0,done:!1,profile:void 0}},u=(i,r)=>l(i,n,r),D=(i,r,o,f,d)=>{const $=o??null,a=T(u(i,r).profile,d)?e`MAX(${e.identifier(n)}.${e.identifier("covered")}, excluded.${e.identifier("covered")})`:e`excluded.${e.identifier("covered")}`;t(i,e`INSERT INTO ${e.identifier(n)} (${e.identifier("companion")}, ${e.identifier("cursor")}, ${e.identifier("done")}, ${e.identifier("profile")}, ${e.identifier("covered")}) VALUES (${r}, ${$}, ${f?1:0}, ${d}, ${f?1:0}) ON CONFLICT (${e.identifier("companion")}) DO UPDATE SET ${e.identifier("cursor")} = excluded.${e.identifier("cursor")}, ${e.identifier("done")} = excluded.${e.identifier("done")}, ${e.identifier("profile")} = excluded.${e.identifier("profile")}, ${e.identifier("covered")} = ${a}`)};export{n as S,O as a,l as b,S as c,N as l,R as m,u as r,D as w};