@lunora/shard-engine 1.0.0-alpha.2 → 1.0.0-alpha.21

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 (99) hide show
  1. package/dist/conformance/index.mjs +1 -1
  2. package/dist/index.d.mts +176 -22
  3. package/dist/index.d.ts +176 -22
  4. package/dist/index.mjs +1 -1
  5. package/dist/packem_shared/ADMIN_FUNCTIONS-OnYxyTXW.mjs +1 -0
  6. package/dist/packem_shared/AGGREGATE_SQL_FUNCTION-CTo0-9iZ.mjs +1 -0
  7. package/dist/packem_shared/AGG_COUNT-CqQLWpb4.mjs +1 -0
  8. package/dist/packem_shared/AUDIT_LOG_TABLE-C6nwXFPd.mjs +8 -0
  9. package/dist/packem_shared/CDC_LOG_TABLE-ZqcflEen.mjs +8 -0
  10. package/dist/packem_shared/{CLIENT_WATERMARK_TABLE-CXsSLU8D.mjs → CLIENT_WATERMARK_TABLE-CzApRlyv.mjs} +1 -1
  11. package/dist/packem_shared/CountRlsUnsupportedError-8BqPYQoP.mjs +1 -0
  12. package/dist/packem_shared/DATA_MIGRATION_STATE_TABLE-BrpAGtXf.mjs +31 -0
  13. package/dist/packem_shared/DEFAULT_MAX_RELATION_KEYS-DjKka36Z.mjs +1 -0
  14. package/dist/packem_shared/DEFAULT_MAX_RELAYS-B19vrJxP.mjs +1 -0
  15. package/dist/packem_shared/{DEFAULT_PROMOTION_THRESHOLDS-Dteg0sZF.mjs → DEFAULT_PROMOTION_THRESHOLDS-B2rUe1bg.mjs} +1 -1
  16. package/dist/packem_shared/DEFAULT_TRANSACTION_LIMITS-q7ouI3i0.mjs +1 -0
  17. package/dist/packem_shared/GEO_DEFAULT_PRECISION-DyI5zggj.mjs +1 -0
  18. package/dist/packem_shared/{GLOBAL_SHAPE_SNAPSHOT_TABLE-DX-6-gBP.mjs → GLOBAL_SHAPE_SNAPSHOT_TABLE-soMJDSBs.mjs} +1 -1
  19. package/dist/packem_shared/{IDEMPOTENCY_TABLE-DjkEMp6w.mjs → IDEMPOTENCY_TABLE-Bvu9JkiL.mjs} +1 -1
  20. package/dist/packem_shared/MAIL_RETENTION-BefR9Sei.mjs +18 -0
  21. package/dist/packem_shared/NotUniqueError-CVHdtVw6.mjs +1 -0
  22. package/dist/packem_shared/QUEUE_TABLE-DgBqWrXX.mjs +17 -0
  23. package/dist/packem_shared/RANK_TIEBREAK-DDtST3gN.mjs +1 -0
  24. package/dist/packem_shared/REPROJECTION_MIGRATION_PREFIX-D2dltRFC.mjs +1 -0
  25. package/dist/packem_shared/RLS_UNWRAP_SYMBOL-DcqORh2s.mjs +1 -0
  26. package/dist/packem_shared/ReactiveCache-Cu8IfE1M.mjs +1 -0
  27. package/dist/packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-BEU0CuW5.mjs +6 -0
  28. package/dist/packem_shared/SEARCH_STATE_TABLE-BZ_fxI5l.mjs +1 -0
  29. package/dist/packem_shared/aggregateTableName-DgYMC5tr.mjs +1 -0
  30. package/dist/packem_shared/applyOnDelete-By23GK-k.mjs +1 -0
  31. package/dist/packem_shared/applySelect-UY-o13Ia.mjs +1 -0
  32. package/dist/packem_shared/awaitWsDrain-Bp2jKzIb.mjs +1 -0
  33. package/dist/packem_shared/backfillAggregateIndexes-DmqOHg0U.mjs +1 -0
  34. package/dist/packem_shared/base64-fKomMf5D.mjs +1 -0
  35. package/dist/packem_shared/buildIndexRange-DFsdtPjD.mjs +1 -0
  36. package/dist/packem_shared/{buildPokeFrames-DaPpm5Ss.mjs → buildPokeFrames-CqxaN8_H.mjs} +1 -1
  37. package/dist/packem_shared/buildReprojectionMigration-Ctl4r84d.mjs +1 -0
  38. package/dist/packem_shared/buildSettings-COIJsw7a.mjs +1 -0
  39. package/dist/packem_shared/compileWhereSql-B4rPariq.mjs +1 -0
  40. package/dist/packem_shared/computeRankPage-QK8SeTZ-.mjs +1 -0
  41. package/dist/packem_shared/createCompanionSync-COw1Uy6a.mjs +1 -0
  42. package/dist/packem_shared/createReadFootprint-DIrrxRTE.mjs +1 -0
  43. package/dist/packem_shared/createReplicaLink-BMNW0SX6.mjs +7 -0
  44. package/dist/packem_shared/ctx-db-companions-BTi8DLUl.mjs +1 -0
  45. package/dist/packem_shared/{defineEngineContractSuite-ii3_DS_I.mjs → defineEngineContractSuite-B6nrsKSE.mjs} +1 -1
  46. package/dist/packem_shared/do-sql-1Yi1_Yq0.mjs +1 -0
  47. package/dist/packem_shared/estimate-bytes-Drp8rhPs.mjs +1 -0
  48. package/dist/packem_shared/exportShardRows-Bbi_JGfn.mjs +1 -0
  49. package/dist/packem_shared/{isSoftDeleted-B-SXkGUo.mjs → isSoftDeleted-Bo-y3DOe.mjs} +1 -1
  50. package/dist/packem_shared/{materializeExternalRows-DOQJV9p2.mjs → materializeExternalRows-DcCENzpV.mjs} +1 -1
  51. package/dist/packem_shared/mergeChangedKeys-BXtUgIPW.mjs +1 -0
  52. package/dist/packem_shared/quoteIdentifier-CObIFRhb.mjs +1 -0
  53. package/dist/packem_shared/runDrizzle-B6rnz3so.mjs +1 -0
  54. package/dist/packem_shared/runShardMigrations-BqO6HPtX.mjs +5 -0
  55. package/dist/packem_shared/selectExpiredIds-C6nQK7E2.mjs +1 -0
  56. package/dist/packem_shared/selectShapeMemberIds-BdBcbrUP.mjs +1 -0
  57. package/dist/packem_shared/serializeSqlValue-BR4UOWoP.mjs +1 -0
  58. package/dist/packem_shared/sibling-channel-bg9FBL5s.mjs +1 -0
  59. package/dist/packem_shared/sql-projection-jfoe331H.mjs +1 -0
  60. package/dist/packem_shared/stableWireKey-l3cjIt-9.mjs +1 -0
  61. package/dist/packem_shared/wire-codec-Dsy70M3Q.mjs +1 -0
  62. package/package.json +3 -3
  63. package/dist/packem_shared/ADMIN_FUNCTIONS-B0xlQJ4w.mjs +0 -1
  64. package/dist/packem_shared/AGGREGATE_SQL_FUNCTION-QYaiuty4.mjs +0 -1
  65. package/dist/packem_shared/AGG_COUNT-BWXe3gtQ.mjs +0 -1
  66. package/dist/packem_shared/AUDIT_LOG_TABLE-CaA0jL0L.mjs +0 -8
  67. package/dist/packem_shared/CDC_LOG_TABLE-BnqlH2eZ.mjs +0 -8
  68. package/dist/packem_shared/CountRlsUnsupportedError-B2WKJD9v.mjs +0 -1
  69. package/dist/packem_shared/DATA_MIGRATION_STATE_TABLE-CaO6L0Ee.mjs +0 -31
  70. package/dist/packem_shared/DEFAULT_MAX_RELATION_KEYS-bq00btqV.mjs +0 -1
  71. package/dist/packem_shared/DEFAULT_MAX_RELAYS-CnCyh6oX.mjs +0 -1
  72. package/dist/packem_shared/FTS_COUNT_COLUMN-D1gY3wwZ-CZHdaRrd.mjs +0 -1
  73. package/dist/packem_shared/GEO_DEFAULT_PRECISION-okRCkZ6r.mjs +0 -1
  74. package/dist/packem_shared/MAIL_RETENTION-KmozO2NQ.mjs +0 -18
  75. package/dist/packem_shared/NotUniqueError-Bw1Oh2FL.mjs +0 -1
  76. package/dist/packem_shared/QUEUE_TABLE-DYCDvzTG.mjs +0 -17
  77. package/dist/packem_shared/RANK_TIEBREAK-9NU5s_mi.mjs +0 -1
  78. package/dist/packem_shared/RLS_UNWRAP_SYMBOL-C6_WX3dG.mjs +0 -1
  79. package/dist/packem_shared/ReactiveCache-1_9Rs7J_.mjs +0 -1
  80. package/dist/packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-CHXz6p_z.mjs +0 -6
  81. package/dist/packem_shared/SEARCH_STATE_TABLE-eLN8U5tz.mjs +0 -1
  82. package/dist/packem_shared/aggregateTableName-G-eXyjcz.mjs +0 -1
  83. package/dist/packem_shared/applyOnDelete-uFRC5p1d.mjs +0 -1
  84. package/dist/packem_shared/applySelect-B0CF8T7y.mjs +0 -1
  85. package/dist/packem_shared/awaitWsDrain-Dk50ISgE.mjs +0 -1
  86. package/dist/packem_shared/backfillAggregateIndexes-BHiewuB-.mjs +0 -1
  87. package/dist/packem_shared/buildSettings-DT18_DkX.mjs +0 -1
  88. package/dist/packem_shared/compileWhereSql-BLcfs4QW.mjs +0 -1
  89. package/dist/packem_shared/computeRankPage-IUSS-zIB.mjs +0 -1
  90. package/dist/packem_shared/createCompanionSync-BCBUOnMk.mjs +0 -1
  91. package/dist/packem_shared/exportShardRows-kt42wijd.mjs +0 -1
  92. package/dist/packem_shared/quote-identifier-CGiYFBvY.mjs +0 -1
  93. package/dist/packem_shared/runDrizzle-GKR3y97k.mjs +0 -1
  94. package/dist/packem_shared/runShardMigrations-CPxqCh3O.mjs +0 -5
  95. package/dist/packem_shared/selectExpiredIds-FzhIEeG1.mjs +0 -1
  96. package/dist/packem_shared/selectShapeMemberIds-DvE7K6zG.mjs +0 -1
  97. package/dist/packem_shared/serializeSqlValue-DnpyaLcw.mjs +0 -1
  98. package/dist/packem_shared/stableWireKey-YEHLaX6X.mjs +0 -1
  99. package/dist/packem_shared/wire-codec-Ctnni0h6.mjs +0 -1
@@ -0,0 +1 @@
1
+ import{LunoraError as d}from"@lunora/errors";import{distinctValues as R}from"./applyOnDelete-By23GK-k.mjs";import{RELATION_EXISTS_KEY as k}from"./RELATION_EXISTS_KEY-BaqSIFU1.mjs";const y={every:{kind:"many",negateChild:!0,negated:!0},is:{kind:"one",negated:!1},isNot:{kind:"one",negated:!0,nullDisjunct:!0},none:{kind:"many",negated:!0},some:{kind:"many",negated:!1}},A=new Set(Object.keys(y)),w=e=>{const t=y[e];if(!t)throw new d("INTERNAL",`unknown relation operator "${e}"`);return t},E=e=>e.kind==="one"?{clause:e.field,project:e.references}:{clause:e.references,project:e.field},j=5e3,h=Symbol("relation-key-overflow"),b=e=>Array.isArray(e)?e.map(t=>t??{}):[],N=e=>{if(e.length===1){const[t]=e;return t??{}}return e.length===0?{}:{AND:e}},p=e=>{if(e===null||typeof e!="object"||Array.isArray(e))return!1;const t=Object.keys(e);return t.length>0&&t.every(n=>A.has(n))},u=(e,t,n)=>{const a=t.tables[n]?.relationMap??{};return Object.keys(e).some(r=>{const s=e[r];return r==="AND"||r==="OR"?b(s).some(o=>u(o,t,n)):r==="NOT"?u(s??{},t,n):!!a[r]&&p(s)})},M=(e,t,n,a)=>{if(e&&u(e,t,n))throw new d("INTERNAL",`relation-crossing predicates are not supported in ${a}() — use them in findMany/findFirst or an RLS read policy`)},S=async(e,t,n,a,r)=>{const s=await c(t,e.table,a),{page:o}=await a.fetcher(e.table,{baseWhere:a.relationBaseWhere?.(e.table),relationBaseWhere:a.relationBaseWhere,where:s}),i=R(o,n);if(i.length>a.maxRelationKeys){if(r)return h;throw new d("INTERNAL",`relation predicate on "${e.table}" matched ${String(i.length)} rows, exceeding the ${String(a.maxRelationKeys)}-key limit; narrow the predicate (a same-shard EXISTS push-down lifts this cap)`)}return i},T=async(e,t,n,a,r)=>{const s=w(e),{clause:o,project:i}=E(t),l=await S(t,s.negateChild?{NOT:n}:n,i,a,r);return l===h?h:s.negated?s.nullDisjunct?{OR:[{[o]:{notIn:l}},{[o]:{isNull:!0}}]}:{[o]:{notIn:l}}:{[o]:{in:l}}},g=async(e,t,n,a,r)=>{const s=w(e),o=r.relationBaseWhere?.(t.table),i=s.negateChild?{NOT:n}:n,l={childWhere:await c(o?{AND:[o,i]}:i,t.table,r),negated:s.negated,parentTable:a,relation:t};return{[k]:l}},$=(e,t,n)=>{const a=y[e];if(a&&a.kind!==n.kind)throw new d("INTERNAL",`relation operator "${e}" requires a to-${a.kind} relation, but "${t}" is to-${n.kind}`)},x=async(e,t,n,a,r)=>{const s=[];for(const o of Object.keys(n)){$(o,e,t);const i=n[o]??{},l=r.canPushExists?.(t)??!1;if(l&&r.existsPushMode==="always"){s.push(await g(o,t,i,a,r));continue}const m=await T(o,t,i,r,l);m===h?s.push(await g(o,t,i,a,r)):s.push(m)}return N(s)},D=async(e,t,n,a)=>{if(e==="AND"||e==="OR"){const s=[];for(const o of b(t))s.push(await c(o,n,a));return{[e]:s}}if(e==="NOT")return{NOT:await c(t??{},n,a)};const r=a.schema.tables[n]?.relationMap?.[e];return r&&p(t)?x(e,r,t,n,a):{[e]:t}},c=async(e,t,n)=>{const a=[];for(const r of Object.keys(e))a.push(await D(r,e[r],t,n));return N(a)},W=async(e,t)=>!e||!u(e,t.schema,t.tableName)?e:c(e,t.tableName,{canPushExists:t.canPushExists,existsPushMode:t.existsPushMode??"auto",fetcher:t.fetcher,maxRelationKeys:t.maxRelationKeys??j,relationBaseWhere:t.relationBaseWhere,schema:t.schema}),f=(e,t,n)=>{for(const a of e){const r=O(a,t,n);if(r)return r}},I=(e,t,n,a)=>{if(e==="AND"||e==="OR")return f(b(t),n,a);if(e==="NOT")return f([t??{}],n,a);const r=n.tables[a]?.relationMap?.[e];if(!(!r||!p(t)))return n.tables[r.table]?.shardMode?.kind==="shardBy"?{relation:e,target:r.table}:f(Object.values(t),n,r.table)},O=(e,t,n)=>{for(const a of Object.keys(e)){const r=I(a,e[a],t,n);if(r)return r}},_=(e,t,n)=>{if(!e)return;const a=O(e,t,n);if(a)throw Object.assign(new Error(`shape on "${n}" joins the sharded table "${a.target}" via relation "${a.relation}" — a live shape cannot replicate rows that live in another shard's Durable Object. Fix it by (a) denormalizing the joined columns into "${n}", or (b) moving "${a.target}" to .global() so it is served through the latency-tiered D1 shape tier.`),{code:"SHAPE_CROSS_SHARD_JOIN",name:"LunoraError",status:400})};export{j as DEFAULT_MAX_RELATION_KEYS,M as assertFlatPredicate,_ as assertShapeShardable,u as containsRelationPredicate,p as isRelationPredicate,W as resolveRelationPredicates};
@@ -0,0 +1 @@
1
+ import{toErrorBody as A,LunoraError as x}from"@lunora/errors";import{a as w,s as g}from"./wire-codec-Dsy70M3Q.mjs";import{u as m,f as P,g as R,l as k,s as M,o as L}from"./sibling-channel-bg9FBL5s.mjs";import{relayName as y,nextPromotionState as O,shapeRoutingKey as S,parseRelayName as D,clampPromotionThresholds as C,DEFAULT_PROMOTION_THRESHOLDS as b}from"./DEFAULT_PROMOTION_THRESHOLDS-B2rUe1bg.mjs";import{encodeRowsPatch as T,buildPokeFrames as _}from"./buildPokeFrames-CqxaN8_H.mjs";import{awaitWsDrain as N,trySendFrame as I}from"./awaitWsDrain-Bp2jKzIb.mjs";import{stableWireKey as p}from"./stableWireKey-l3cjIt-9.mjs";const $=2,F=8,f={},U=d=>{throw new x("INTERNAL",`unhandled relay frame: ${JSON.stringify(d)}`)},K=d=>Response.json(d,{headers:{"content-type":"application/json"}}),u=()=>new Response(null,{status:204});class E{constructor(e,s){this.host=e,this.roleId=s}host;roleId;async handleControl(e){let s;try{s=await e.text()}catch{return new Response("bad request",{status:400})}if(!await P(this.host.env(),e.headers.get(R),s))return new Response("forbidden",{status:403});let t;try{t=JSON.parse(s)}catch{return new Response("bad request",{status:400})}switch(t.type){case"relay_attach":return this.onAttach(t.relayIndex),u();case"relay_detach":return this.onDetach(t.relayIndex),u();case"relay_frame":return this.host.deliverWhisperLocal(t.topic,t.frame,void 0),await this.onWhisperFrame(t),u();case"relay_shape_poke":{const r=this.host.getWebSockets().length,a=Date.now(),o=this.onShapePoke({...t,args:g(t.args)});return this.host.recordShapePokeFanout(r,o,Date.now()-a),u()}case"relay_shape_subscribe":return K(this.onShapeSubscribe({...t,args:g(t.args)}));default:return U(t)}}maxRelays(){return m(this.host.env(),"LUNORA_MAX_RELAYS",F)}canAddressSiblings(){return this.siblingStub(this.roleId.ownerKey)!==void 0}siblingStub(e){return k(this.host.env(),this.host.shardBinding(),e)}async postRelayMessage(e,s){await this.requestRelayMessage(e,s)}async requestRelayMessage(e,s){const t=this.siblingStub(e);if(t===void 0)return;const r=JSON.stringify(s),a={"content-type":"application/json","x-lunora-shard-binding":this.host.shardBinding()??""},o=M(this.host.env());o!==void 0&&(a[R]=await L(o,r));try{return await t.fetch("https://relay.internal/_lunora/relay",{body:r,headers:a,method:"POST"})}catch{return}}}class W extends E{shapeUniformCache=new Map;relaySetCache;relayShapeRegistry=new Map;relayShapeProxies=new Map;promotionState="owned";constructor(e,s){super(e,{ownerKey:s})}async forwardWhisper(e,s){if(!this.canAddressSiblings())return;const t=this.ownerRelaySet();t.size!==0&&await Promise.all([...t].map(r=>this.postRelayMessage(y(this.roleId.ownerKey,r),{frame:s,topic:e,type:"relay_frame"})))}async onFlush(e,s){await Promise.all([this.multicastShapePokes(e,s),this.proxyShapePokes(e,s)])}seedRelayShape(){return Promise.resolve(void 0)}announce(){return Promise.resolve()}announceDrain(){return Promise.resolve()}relayCount(){const e=this.host.getWebSockets().length,s=m(this.host.env(),"LUNORA_RELAY_THRESHOLD",b.tUp),t=m(this.host.env(),"LUNORA_RELAY_COLLAPSE_THRESHOLD",b.tDown);if(this.promotionState=O(this.promotionState,e,C(s,t)),this.promotionState==="owned")return 0;const r=m(this.host.env(),"LUNORA_RELAY_FAN",$);return Math.min(this.maxRelays(),Math.max(1,r))}isShapeRelayUniform(e,s){const t=S(e,s),r=this.shapeUniformCache.get(t);if(r!==void 0)return r;const a=this.probeShapeRelayUniform(e,s);return this.shapeUniformCache.set(t,a),a}onAttach(e){this.addRelayToSet(e)}onDetach(e){this.removeRelayFromSet(e)}async onWhisperFrame(e){await Promise.all([...this.ownerRelaySet()].filter(s=>s!==e.originRelay).map(s=>this.postRelayMessage(y(this.roleId.ownerKey,s),{frame:e.frame,topic:e.topic,type:"relay_frame"})))}onShapeSubscribe(e){return this.buildShapeSeedFrames(e)}onShapePoke(){return 0}buildShapePoke(e,s,t,r,a){let o;try{o=this.host.resolveShape(e.name,e.args,s)}catch{return}if(o===void 0||o.global===!0||!t.has(o.table))return;const i=e,n=i.cursor,l=this.host.buildShapeDiff(o,n,r);if(l.length!==0)return i.cursor=r,{args:w(e.args),checkpoint:r,epoch:a,fromCursor:n,name:e.name,rowsPatch:T(l),type:"relay_shape_poke"}}async multicastShapePokes(e,s){if(this.relayShapeRegistry.size===0)return;const t=this.ownerRelaySet();if(t.size===0)return;const r=this.host.currentCdcEpoch(),a=[];for(const o of this.relayShapeRegistry.values()){const i=this.buildShapePoke(o,f,e,s,r);if(i)for(const n of t)a.push(this.postRelayMessage(y(this.roleId.ownerKey,n),i))}await Promise.all(a)}async proxyShapePokes(e,s){if(this.relayShapeProxies.size===0)return;const t=this.host.currentCdcEpoch(),r=[];for(const a of this.relayShapeProxies.values()){const o=this.buildShapePoke(a,a.identity,e,s,t);o&&r.push(this.postRelayMessage(y(this.roleId.ownerKey,a.relayIndex),{...o,targetConnectionId:a.connectionId}))}await Promise.all(r)}buildShapeSeedFrames(e){const s={identity:e.identity,userId:e.userId};let t;try{t=this.host.resolveShape(e.name,e.args,s)}catch(c){const{body:h}=A(c,{fallbackCode:"SHAPE_RESOLVE_FAILED",redactedMessage:"shape resolution failed"});return{error:{code:h.code,message:h.message}}}if(t===void 0||t.global===!0)return{error:{code:"SHAPE_NOT_FOUND",message:`shape not relayable: ${e.name}`}};e.relayIndex!==void 0&&this.addRelayToSet(e.relayIndex);const{baseCheckpoint:r,cursor:a,epoch:o,rowsPatch:i}=this.host.computeOpLogShapeSeed({args:e.args,name:e.name,sinceEpoch:e.sinceEpoch,sinceSeq:e.sinceSeq},t);let n=a;if(this.isShapeRelayUniform(e.name,e.args)){const c=S(e.name,e.args);let h=this.relayShapeRegistry.get(c);h===void 0&&(h={args:e.args,cursor:a,name:e.name},this.relayShapeRegistry.set(c,h)),n=h.cursor}else e.relayIndex!==void 0&&e.connectionId!==void 0&&this.relayShapeProxies.set(`${String(e.relayIndex)}:${e.connectionId}:${e.subId}`,{args:e.args,connectionId:e.connectionId,cursor:a,epoch:o,identity:s,name:e.name,relayIndex:e.relayIndex,subId:e.subId});const l=_([{rowsPatch:i,shapeId:e.subId}],{baseCheckpoint:r,checkpoint:a,epoch:o,lastMutationId:void 0,pokeId:this.host.nextPokeId()});return{cursor:n,epoch:o,frames:l}}ensureRelayTable(){this.host.sql().exec("CREATE TABLE IF NOT EXISTS __lunora_relays (idx INTEGER PRIMARY KEY)")}ownerRelaySet(){if(this.relaySetCache===void 0){this.ensureRelayTable();const e=this.host.sql().exec("SELECT idx FROM __lunora_relays").toArray();this.relaySetCache=new Set(e.map(s=>Number(s.idx)))}return this.relaySetCache}addRelayToSet(e){this.ensureRelayTable(),this.host.sql().exec("INSERT OR IGNORE INTO __lunora_relays (idx) VALUES (?)",e),this.ownerRelaySet().add(e)}removeRelayFromSet(e){this.ensureRelayTable(),this.host.sql().exec("DELETE FROM __lunora_relays WHERE idx = ?",e);const s=this.ownerRelaySet();s.delete(e);for(const[t,r]of this.relayShapeProxies)r.relayIndex===e&&this.relayShapeProxies.delete(t);s.size===0&&(this.relayShapeRegistry.clear(),this.shapeUniformCache.clear())}probeShapeRelayUniform(e,s){let t;try{t=this.host.resolveShape(e,s,f)}catch{return!1}if(t===void 0||t.global===!0||this.host.rlsMetadata().policies.some(n=>n.on==="read"&&n.table===t.table)||this.tableHasAnyMask(t.table))return!1;const r=p(t.effectiveWhere),a=p(t.columns);let o=!1;const i=n=>{const l={groups:[`grp_${n}`],roles:[n],sub:`__lunora_probe_${n}__`};return{identity:new Proxy(l,{get:(c,h)=>typeof h=="symbol"||h in c?Reflect.get(c,h):`${n}:${h}`,getOwnPropertyDescriptor:(c,h)=>(o=!0,Reflect.getOwnPropertyDescriptor(c,h)),has:(c,h)=>typeof h=="symbol"?Reflect.has(c,h):!0,ownKeys:c=>(o=!0,Reflect.ownKeys(c))}),userId:`__lunora_probe_${n}__`}};return[f,i("a"),i("b")].every(n=>{let l;try{l=this.host.resolveShape(e,s,n)}catch{return!1}return l!==void 0&&l.global!==!0&&l.table===t.table&&p(l.effectiveWhere)===r&&p(l.columns)===a})&&!o}tableHasAnyMask(e){return this.host.maskMetadata().columns.some(s=>s.table===e)}}class q extends E{relayAnnounced=!1;shapeRelayMemos=new WeakMap;constructor(e,s,t){super(e,{ownerKey:s,relayIndex:t})}async forwardWhisper(e,s){this.canAddressSiblings()&&await this.postRelayMessage(this.roleId.ownerKey,{frame:s,originRelay:this.roleId.relayIndex,topic:e,type:"relay_frame"})}onFlush(){return Promise.resolve()}async seedRelayShape(e,s,t,r){if(!this.canAddressSiblings())return{code:"RELAY_MISCONFIGURED",message:"relay cannot address its owner"};await this.announce();const a={args:w(t.args??{}),connectionId:this.host.readAttachment(e).connectionId,identity:r.identity,name:t.name,relayIndex:this.roleId.relayIndex,sinceEpoch:t.sinceEpoch,sinceSeq:t.sinceSeq,subId:s,type:"relay_shape_subscribe",userId:r.userId},o=await this.requestRelayMessage(this.roleId.ownerKey,a);if(o===void 0)return{code:"RELAY_SEED_FAILED",message:"owner did not answer the shape seed"};let i;try{i=await o.json()}catch{return{code:"RELAY_SEED_FAILED",message:"malformed shape seed from owner"}}if(i.error!==void 0)return i.error;if(i.frames===void 0)return{code:"RELAY_SEED_FAILED",message:"owner returned no shape frames"};await N(e);for(const n of i.frames)I(e,n);return this.recordRelayShapeMemo(e,s,i.cursor??0,i.epoch),"ok"}async announce(){this.relayAnnounced||!this.canAddressSiblings()||(this.relayAnnounced=!0,(await this.requestRelayMessage(this.roleId.ownerKey,{relayIndex:this.roleId.relayIndex,type:"relay_attach"}))?.ok||(this.relayAnnounced=!1))}async announceDrain(e){this.canAddressSiblings()&&(this.host.getWebSockets().some(s=>s!==e)||(this.relayAnnounced=!1,await this.postRelayMessage(this.roleId.ownerKey,{relayIndex:this.roleId.relayIndex,type:"relay_detach"})))}relayCount(){return 0}isShapeRelayUniform(){return!1}onAttach(){}onDetach(){}onWhisperFrame(){return Promise.resolve()}onShapeSubscribe(){return{error:{code:"RELAY_CANNOT_SEED",message:"a relay has no op-log to seed from"}}}onShapePoke(e){return this.deliverShapePoke(e)}recordRelayShapeMemo(e,s,t,r){let a=this.shapeRelayMemos.get(e);a===void 0&&(a=new Map,this.shapeRelayMemos.set(e,a)),a.set(s,{cursor:t,epoch:r})}deliverShapePoke(e){const s=S(e.name,e.args);let t=0;for(const r of this.host.getWebSockets()){const a=this.host.readAttachment(r),{shapes:o}=a,i=this.shapeRelayMemos.get(r);if(!(o===void 0||i===void 0)&&!(e.targetConnectionId!==void 0&&a.connectionId!==e.targetConnectionId))for(const[n,l]of Object.entries(o)){const c=i.get(n);if(c?.cursor!==e.fromCursor||c.epoch!==e.epoch||S(l.name,l.args)!==s)continue;const h=_([{rowsPatch:e.rowsPatch,shapeId:n}],{baseCheckpoint:void 0,checkpoint:e.checkpoint,epoch:e.epoch,lastMutationId:void 0,pokeId:this.host.nextPokeId()},{preEncoded:!0});for(const v of h)I(r,v);i.set(n,{cursor:e.checkpoint,epoch:e.epoch}),t+=1}}return t}}const X=d=>{const e=d.doName();if(e===void 0)return;const s=D(e);return s===void 0?new W(d,e):new q(d,s.ownerKey,s.relayIndex)};export{F as DEFAULT_MAX_RELAYS,W as OwnerRelay,q as RelayMember,X as createRelayLink};
@@ -1 +1 @@
1
- import{LunoraError as s}from"@lunora/errors";import{stableWireKey as i}from"./stableWireKey-YEHLaX6X.mjs";const a="::relay::",h=(t,o)=>`${t}${a}${String(o)}`,w=t=>{const o=t.lastIndexOf(a);if(o===-1)return;const r=t.slice(0,o),n=t.slice(o+a.length),e=Number(n);if(!(r.length===0||!Number.isInteger(e)||e<0||String(e)!==n))return{ownerKey:r,relayIndex:e}},d=(t,o)=>i({args:o??{},name:t}),m={tDown:4e3,tUp:8e3},u=(t,o,r=m)=>{if(r.tDown>=r.tUp)throw new s("INTERNAL",`invalid promotion thresholds: tDown (${String(r.tDown)}) must be < tUp (${String(r.tUp)})`);return t==="owned"?o>=r.tUp?"promoted":"owned":o<r.tDown?"owned":"promoted"},c=(t,o)=>o<t?{tDown:o,tUp:t}:{tDown:Math.min(Math.max(1,Math.floor(t/2)),t-1),tUp:t},g=(t,o,r)=>{if(t<=o||o<=0)return 0;const n=t-o,e=Math.ceil(n/o);return Math.min(e,Math.max(0,r))};export{m as DEFAULT_PROMOTION_THRESHOLDS,a as RELAY_NAME_INFIX,c as clampPromotionThresholds,u as nextPromotionState,w as parseRelayName,g as relayCountFor,h as relayName,d as shapeRoutingKey};
1
+ import{LunoraError as s}from"@lunora/errors";import{stableWireKey as i}from"./stableWireKey-l3cjIt-9.mjs";const a="::relay::",h=(t,o)=>`${t}${a}${String(o)}`,w=t=>{const o=t.lastIndexOf(a);if(o===-1)return;const r=t.slice(0,o),n=t.slice(o+a.length),e=Number(n);if(!(r.length===0||!Number.isInteger(e)||e<0||String(e)!==n))return{ownerKey:r,relayIndex:e}},d=(t,o)=>i({args:o??{},name:t}),m={tDown:4e3,tUp:8e3},u=(t,o,r=m)=>{if(r.tDown>=r.tUp)throw new s("INTERNAL",`invalid promotion thresholds: tDown (${String(r.tDown)}) must be < tUp (${String(r.tUp)})`);return t==="owned"?o>=r.tUp?"promoted":"owned":o<r.tDown?"owned":"promoted"},c=(t,o)=>o<t?{tDown:o,tUp:t}:{tDown:Math.min(Math.max(1,Math.floor(t/2)),t-1),tUp:t},g=(t,o,r)=>{if(t<=o||o<=0)return 0;const n=t-o,e=Math.ceil(n/o);return Math.min(e,Math.max(0,r))};export{m as DEFAULT_PROMOTION_THRESHOLDS,a as RELAY_NAME_INFIX,c as clampPromotionThresholds,u as nextPromotionState,w as parseRelayName,g as relayCountFor,h as relayName,d as shapeRoutingKey};
@@ -0,0 +1 @@
1
+ import{LunoraError as i}from"@lunora/errors";import{o as e}from"./estimate-bytes-Drp8rhPs.mjs";const r={maxReadRows:1e5,maxWrittenBytes:32*1024*1024,maxWrittenRows:5e4};class w{readRows=0;writtenRows=0;writtenBytes=0;limits;constructor(t={}){this.limits={...r,...t}}recordRead(t){if(this.readRows+=t,this.readRows>this.limits.maxReadRows)throw new i("TRANSACTION_LIMIT_EXCEEDED",`this transaction read ${String(this.readRows)} documents, over the ${String(this.limits.maxReadRows)}-document limit`)}recordWrite(t){this.writtenRows+=1;const s=e(t);if(s===void 0)throw new i("BAD_REQUEST","this document is not JSON-serializable (cyclic or non-JSON value); it cannot be written");if(this.writtenBytes+=s,this.writtenRows>this.limits.maxWrittenRows)throw new i("TRANSACTION_LIMIT_EXCEEDED",`this transaction wrote ${String(this.writtenRows)} documents, over the ${String(this.limits.maxWrittenRows)}-document limit`);if(this.writtenBytes>this.limits.maxWrittenBytes)throw new i("TRANSACTION_LIMIT_EXCEEDED",`this transaction wrote ${String(this.writtenBytes)} bytes, over the ${String(this.limits.maxWrittenBytes)}-byte limit`)}headroom(){return{readRows:this.readRows,remainingReadRows:Math.max(0,this.limits.maxReadRows-this.readRows),remainingWrittenBytes:Math.max(0,this.limits.maxWrittenBytes-this.writtenBytes),remainingWrittenRows:Math.max(0,this.limits.maxWrittenRows-this.writtenRows),writtenBytes:this.writtenBytes,writtenRows:this.writtenRows}}}export{r as DEFAULT_TRANSACTION_LIMITS,w as TransactionHeadroomTracker};
@@ -0,0 +1 @@
1
+ const x="0123456789bcdefghjkmnpqrstuvwxyz",T=9,b=63710088e-1,g=Math.PI/180,w=[Number.POSITIVE_INFINITY,5009400,1252300,156500,39100,4900,1200,152.9,38.2,4.77,1.19,.149,.037],I=w.map((t,n)=>n%2===0?t/2:t),p=.01,k=Math.acos(p)/g,B=2,v=t=>t/b/g,S=t=>{const n=5*t;return{latBands:2**Math.floor(n/2),lngSectors:2**Math.ceil(n/2)}},E=t=>Math.min(Math.max(Math.trunc(t),1),12),z=(t,n)=>{const o=E(n);let s=-90,e=90,a=-180,r=180,u="",i=0,h=0,M=!0;for(;u.length<o;){if(M){const c=(a+r)/2;t.lng>=c?(h=h*2+1,a=c):(h*=2,r=c)}else{const c=(s+e)/2;t.lat>=c?(h=h*2+1,s=c):(h*=2,e=c)}M=!M,i<4?i+=1:(u+=x[h]??"0",i=0,h=0)}return u},y=(t,n)=>Math.min(90,Math.abs(t)+v(n)),G=(t,n)=>{const o=(n.lat-t.lat)*g,s=(n.lng-t.lng)*g,e=t.lat*g,a=n.lat*g,r=Math.sin(o/2)**2+Math.cos(e)*Math.cos(a)*Math.sin(s/2)**2;return 2*b*Math.asin(Math.min(1,Math.sqrt(r)))},C=(t,n)=>{const o=Math.max(Math.cos(y(n,t)*g),p);for(let s=w.length-1;s>=1;s-=1){const e=w[s],a=I[s];if(e!==void 0&&a!==void 0&&e*o>=t&&a>=t)return s}return 1},N={east:["bc01fg45238967deuvhjyznpkmstqrwx","p0r21436x8zb9dcf5h7kjnmqesgutwvy"],north:["p0r21436x8zb9dcf5h7kjnmqesgutwvy","bc01fg45238967deuvhjyznpkmstqrwx"],south:["14365h7k9dcfesgujnmqp0r2twvyx8zb","238967debc01fg45kmstqrwxuvhjyznp"],west:["238967debc01fg45kmstqrwxuvhjyznp","14365h7k9dcfesgujnmqp0r2twvyx8zb"]},O={east:["bcfguvyz","prxz"],north:["prxz","bcfguvyz"],south:["028b","0145hjnp"],west:["0145hjnp","028b"]},l=(t,n)=>{const o=t.toLowerCase(),s=o.at(-1)??"";let e=o.slice(0,-1);const a=o.length%2===0?0:1;return O[n][a].includes(s)&&e!==""&&(e=l(e,n)),e+(x[N[n][a].indexOf(s)]??"")},P=(t,n,o)=>{const s=Math.min(o,B),{latBands:e,lngSectors:a}=S(s),r=180/e,u=360/a,i=v(n),h=Math.max(-90,t.lat-i),M=Math.min(90,t.lat+i),c=new Set;for(let d=0;d<e;d+=1){const f=-90+d*r;if(f+r<h||f>M)continue;const j=f+r/2;for(let m=0;m<a;m+=1){const q=-180+(m+.5)*u;c.add(z({lat:j,lng:q},s))}}return[...c]},_=(t,n)=>{const o=Math.max(n,1),s=C(o,t.lat);if(y(t.lat,o)>=k)return P(t,o,s);const e=z(t,s),a=l(e,"north"),r=l(e,"south"),u=[e,a,r,l(e,"east"),l(e,"west"),l(a,"east"),l(a,"west"),l(r,"east"),l(r,"west")];return[...new Set(u)]},F=(t,n)=>t.lat>=n.sw.lat&&t.lat<=n.ne.lat&&t.lng>=n.sw.lng&&t.lng<=n.ne.lng,L=t=>({lat:(t.sw.lat+t.ne.lat)/2,lng:(t.sw.lng+t.ne.lng)/2}),R=t=>{const n=L(t);return _(n,Math.max(G(n,t.ne),1))};export{T as GEO_DEFAULT_PRECISION,L as boundingBoxCenter,R as boundingBoxGeohashes,_ as coveringGeohashes,z as encodeGeohash,G as haversineMeters,F as pointInBoundingBox};
@@ -1,4 +1,4 @@
1
- import{sql as e}from"drizzle-orm";import{runDrizzle as r}from"./runDrizzle-GKR3y97k.mjs";const s="__global_shape_snapshot",d=n=>{r(n,e`CREATE TABLE IF NOT EXISTS ${e.identifier(s)} (
1
+ import{sql as e}from"drizzle-orm";import{runDrizzle as r}from"./runDrizzle-B6rnz3so.mjs";const s="__global_shape_snapshot",d=n=>{r(n,e`CREATE TABLE IF NOT EXISTS ${e.identifier(s)} (
2
2
  connection_id TEXT NOT NULL,
3
3
  sub_id TEXT NOT NULL,
4
4
  members TEXT NOT NULL,
@@ -1,4 +1,4 @@
1
- import{sql as t}from"drizzle-orm";import{runDrizzle as r}from"./runDrizzle-GKR3y97k.mjs";const E="__idempotency",m=i=>{r(i,t`CREATE TABLE IF NOT EXISTS ${t.identifier(E)} (
1
+ import{sql as t}from"drizzle-orm";import{runDrizzle as r}from"./runDrizzle-B6rnz3so.mjs";const E="__idempotency",m=i=>{r(i,t`CREATE TABLE IF NOT EXISTS ${t.identifier(E)} (
2
2
  identity TEXT NOT NULL,
3
3
  mutation_id TEXT NOT NULL,
4
4
  result_json TEXT NOT NULL,
@@ -0,0 +1,18 @@
1
+ import{runSql as e,decodeJsonColumn as c,orNull as T}from"./runDrizzle-B6rnz3so.mjs";const r="__lunora_mail",l=500,_=256*1024,i=d=>d!==void 0&&d.length>_?`${d.slice(0,_)}
2
+ … [truncated by the dev mail catcher]`:d,E=d=>d===void 0?null:JSON.stringify(d),s=d=>{e(d,`CREATE TABLE IF NOT EXISTS "${r}" (
3
+ id TEXT PRIMARY KEY,
4
+ captured_at INTEGER NOT NULL,
5
+ from_addr TEXT,
6
+ to_addrs TEXT NOT NULL,
7
+ cc_addrs TEXT,
8
+ bcc_addrs TEXT,
9
+ reply_to TEXT,
10
+ subject TEXT NOT NULL,
11
+ html TEXT,
12
+ body_text TEXT,
13
+ headers TEXT
14
+ )`)},m=(d,t,o)=>{s(d);const a=crypto.randomUUID();return e(d,`INSERT INTO "${r}" (id, captured_at, from_addr, to_addrs, cc_addrs, bcc_addrs, reply_to, subject, html, body_text, headers)
15
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,a,o,T(t.from),JSON.stringify(t.to),E(t.cc),E(t.bcc),T(t.replyTo),t.subject,T(i(t.html)),T(i(t.text)),E(t.headers)),e(d,`DELETE FROM "${r}"
16
+ WHERE id NOT IN (
17
+ SELECT id FROM "${r}" ORDER BY captured_at DESC, id DESC LIMIT ?
18
+ )`,l),{id:a}},n=(d,t={})=>{s(d);const o=Math.min(Math.max(t.limit??50,1),l);return{entries:e(d,`SELECT * FROM "${r}" ORDER BY captured_at DESC, id DESC LIMIT ?`,o).toArray().map(a=>({bcc:c(a.bcc_addrs),capturedAt:a.captured_at,cc:c(a.cc_addrs),from:a.from_addr??void 0,headers:c(a.headers),html:a.html??void 0,id:a.id,replyTo:a.reply_to??void 0,subject:a.subject,text:a.body_text??void 0,to:c(a.to_addrs)??a.to_addrs}))}},p=d=>(s(d),e(d,`DELETE FROM "${r}"`),{cleared:!0});export{l as MAIL_RETENTION,r as MAIL_TABLE,_ as MAX_BODY_CHARS,p as clearCapturedMail,s as ensureMailTable,n as readCapturedMail,m as recordCapturedMail};
@@ -0,0 +1 @@
1
+ import{LunoraError as b}from"@lunora/errors";import{n as kt,w as Lt,x as je,T as Te,y as Dt,c as Ot}from"./ctx-db-companions-BTi8DLUl.mjs";import{sql as n}from"drizzle-orm";import{s as Ft}from"./wire-codec-Dsy70M3Q.mjs";import{aggregateSqlFunction as Se,normalizeCountArgument as Wt,throwingScheduler as Bt}from"./AGGREGATE_SQL_FUNCTION-CTo0-9iZ.mjs";import{encodeAggregateKey as Me,readAggregateValue as ke,aggregateTableName as Le}from"./aggregateTableName-DgYMC5tr.mjs";import{mergeWhere as Y,CountRlsUnsupportedError as De,selectIndexForGroupBy as qt,selectIndexForCount as Ut,selectIndexForAggregate as Pt}from"./CountRlsUnsupportedError-8BqPYQoP.mjs";import{backfillSearchIndexesForTable as jt}from"./backfillAggregateIndexes-DmqOHg0U.mjs";import{backfillAggregateIndexes as Ir,backfillRankIndexes as vr,backfillSearchIndexes as Cr}from"./backfillAggregateIndexes-DmqOHg0U.mjs";import{appendCdcChange as Ht}from"./CDC_LOG_TABLE-ZqcflEen.mjs";import{CDC_LOG_TABLE as kr,applyCdcChanges as Lr,bumpCdcEpoch as Dr,minCdcSeq as Or,readCdcChanges as Fr,readCdcCursor as Wr,readCdcEpoch as Br,trimCdcChanges as qr}from"./CDC_LOG_TABLE-ZqcflEen.mjs";import{computeRankPage as nt}from"./computeRankPage-QK8SeTZ-.mjs";import{SCAN_DEP as P}from"./SCAN_DEP-D_yR9EeV.mjs";import{runDrizzle as B}from"./runDrizzle-B6rnz3so.mjs";import{a as H,L as ae,p as _e,T as Oe,c as Re,N as V,E as le,I as Et,C as Qt,D as yt,h as Gt,O as rt}from"./do-sql-1Yi1_Yq0.mjs";import{coveringGeohashes as Kt,boundingBoxGeohashes as Yt,pointInBoundingBox as zt,haversineMeters as Vt}from"./GEO_DEFAULT_PRECISION-DyI5zggj.mjs";import{NotFoundError as Jt}from"./NotFoundError-BhF7FeFr.mjs";import{normalizeOrderKeys as Xt,buildSeekWhere as Nt,decodeCursor as qe,applySelect as it,encodeCursor as Ue,softDeleteScope as de,buildSeekBeforeWhere as Zt}from"./applySelect-UY-o13Ia.mjs";import{sortColumnName as ot,resolveRankPartition as en,encodePartitionKey as tn,RANK_TIEBREAK as nn,rankTableName as at}from"./RANK_TIEBREAK-DDtST3gN.mjs";import{indexKeysForRow as rn,buildIndexRange as on}from"./buildIndexRange-DFsdtPjD.mjs";import{assertFlatPredicate as Fe,resolveRelationPredicates as st}from"./DEFAULT_MAX_RELATION_KEYS-DjKka36Z.mjs";import{runRowValidators as We,resolveWith as dt,relationHooks as lt,applyOnDelete as an,fanOutScalarCounts as sn}from"./applyOnDelete-By23GK-k.mjs";import{guardWriter as dn}from"./RLS_UNWRAP_SYMBOL-DcqORh2s.mjs";import{f as ln}from"./sql-projection-jfoe331H.mjs";import{createSystemReader as cn}from"./createSystemReader-DcDcrtM3.mjs";import{ConflictError as he}from"./ConflictError-C8GtJmjS.mjs";import{runTriggers as un}from"./hasTrigger-CbkOHExZ.mjs";import{compileWhereSql as ne}from"./compileWhereSql-B4rPariq.mjs";import{CLIENT_WATERMARK_TABLE as Pr,advanceClientWatermark as jr,migrateClientWatermark as Hr,readClientWatermark as Qr}from"./CLIENT_WATERMARK_TABLE-CzApRlyv.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as Kr,deleteGlobalShapeSnapshot as Yr,deleteGlobalShapeSnapshotsForConnection as zr,migrateGlobalShapeSnapshot as Vr,readGlobalShapeSnapshot as Jr,writeGlobalShapeSnapshot as Xr}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-soMJDSBs.mjs";import{IDEMPOTENCY_TABLE as ei,readIdempotent as ti,trimIdempotent as ni,writeIdempotent as ri}from"./IDEMPOTENCY_TABLE-Bvu9JkiL.mjs";import{runShardMigrations as oi}from"./runShardMigrations-BqO6HPtX.mjs";import{SEARCH_STATE_TABLE as si}from"./SEARCH_STATE_TABLE-BZ_fxI5l.mjs";import{selectShapeMemberIds as li,selectShapeRows as ci}from"./selectShapeMemberIds-BdBcbrUP.mjs";import{serializeSqlValue as oe}from"./serializeSqlValue-BR4UOWoP.mjs";import{quoteIdentifier as fn}from"./quoteIdentifier-CObIFRhb.mjs";const hn=i=>{const o=new TextEncoder().encode(i);let t="";for(const d of o)t+=String.fromCodePoint(d);return btoa(t)},pn=i=>{const o=atob(i),t=Uint8Array.from(o,d=>d.codePointAt(0)??0);return new TextDecoder().decode(t)},mn=()=>new b("BAD_REQUEST","invalid cursor"),ct=16,ut=8,J=1024,He=(i,o)=>o.query(i),$n=(i,o,t)=>{const d=kt(i,t);if(d.length===0)return 0;let c=0;for(const[p,$]of o.entries()){const A=p===o.length-1;let y=0;for(const g of d)(A?g.startsWith($):g===$)&&(y+=1);if(y===0)return 0;c+=y}return c},wn=(i,o)=>{if(!o)return{exact:!0,lower:i,upper:i};const t=[...i].at(-1)??"",d=(t.codePointAt(0)??0)+1;if(d>=55296&&d<=57343||d>1114111)return{exact:!0,lower:i,upper:i};const c=i.slice(0,i.length-t.length);return{exact:!1,lower:i,upper:c+String.fromCodePoint(d)}},gn=(i,o,t)=>{const d={eq:(c,p)=>{if(!i.definition.filterFields?.includes(c))throw new b("INTERNAL",`field "${c}" is not a filter field of search index "${i.indexName}" on table "${o}"`);if(i.filters.length>=ut)throw new b("BAD_REQUEST",`search index "${i.indexName}" on table "${o}": at most ${String(ut)} .eq() filters are supported per search query`);return i.filters.push({field:c,value:p}),d},search:(c,p)=>{const $=i;if(c!==$.definition.field)throw new b("INTERNAL",`search index "${$.indexName}" on table "${o}" indexes "${$.definition.field}", not "${c}"`);const A=He(p,t).length;if(A>ct)throw new b("BAD_REQUEST",`search index "${$.indexName}" on table "${o}": at most ${String(ct)} search terms are supported (got ${String(A)})`);return $.field=c,$.query=p,$.hasQuery=!0,d}};return d},bn=i=>{if(i.length>J)throw new b("BAD_REQUEST",`more than ${String(J)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},En=i=>Math.min(i.offset+i.numItems+1,J),yn=i=>hn(`search:${String(i)}`),Nn=i=>{let o;try{o=pn(i)}catch{return}if(!o.startsWith("search:"))return;const t=Number(o.slice(7));return Number.isInteger(t)&&t>=0?t:void 0},Tn=i=>{if(typeof i.endCursor=="string")throw new b("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");const o=Math.max(0,Math.floor(i.numItems)),t=i.cursor?Nn(i.cursor):0;if(t===void 0)throw mn();if(t+o>J)throw new b("BAD_REQUEST",`search pagination reaches past the ${String(J)}-document limit (offset ${String(t)} + ${String(o)} requested) — narrow the query or the filters instead`);return{numItems:o,offset:t}},Sn=(i,o)=>{const t=o.offset+o.numItems,d=o.numItems>0&&i.length>t;return{continueCursor:d?yn(t):null,isDone:!d,page:i.slice(o.offset,t)}},_n=i=>{if(i===void 0)return J+1;if(!Number.isFinite(i))return J;const o=Math.max(0,Math.floor(i));if(o>J)throw new b("BAD_REQUEST",`search returns at most ${String(J)} documents (asked for ${String(o)}) — narrow the query or paginate instead`);return o},Rn=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,An=i=>{if(!Rn.test(i))throw new b("INTERNAL",`invalid clientId ${JSON.stringify(i)}: a client-supplied row id must be a UUID`)},ft=50,Tt=500,xn=128,se=(i,o,t)=>{const d=o??Tt;if(i>d)throw new b("BATCH_LIMIT_EXCEEDED",`${t}: batch of ${String(i)} exceeds the limit of ${String(d)} (raise options.limit or chunk the call)`,{status:400})},In=i=>{const o={eq:(t,d)=>(i.sqlConditions.push({comparator:"=",field:t,value:d}),o),gt:(t,d)=>(i.sqlConditions.push({comparator:">",field:t,value:d}),o),gte:(t,d)=>(i.sqlConditions.push({comparator:">=",field:t,value:d}),o),lt:(t,d)=>(i.sqlConditions.push({comparator:"<",field:t,value:d}),o),lte:(t,d)=>(i.sqlConditions.push({comparator:"<=",field:t,value:d}),o)};return o},vn=i=>Math.max(i,J),St=(i,o)=>{const t=i.filters.map(d=>n`${V(d.field)} = ${oe(d.value)}`);return o&&t.push(o),t},Cn=(i,o,t,d,c)=>{const p=He(t.query,je(t.definition.language));if(p.length===0)return[];const $=Ot(o,t.indexName),A=`${$}__vocab`,y=p.length-1,g=p.map((D,k)=>{const Q=wn(D,k===y),W=Q.exact?n`${n.identifier("term")} = ${Q.lower}`:n`${n.identifier("term")} >= ${Q.lower} AND ${n.identifier("term")} < ${Q.upper}`;return n`SELECT ${n.identifier("doc")}, ${n.raw(String(k))} AS ${n.identifier("__term__")}, COUNT(*) AS ${n.identifier("__n__")} FROM ${n.identifier(A)} WHERE ${W} GROUP BY ${n.identifier("doc")}`}),N=p.map((D,k)=>n`SUM(CASE WHEN u.${n.identifier("__term__")} = ${n.raw(String(k))} THEN u.${n.identifier("__n__")} ELSE 0 END)`),T=n`SELECT f.${n.identifier(Te)} AS ${n.identifier(Te)}, ${n.join(N,n` + `)} AS ${n.identifier("__score__")} FROM (${n.join(g,n` UNION ALL `)}) u JOIN ${n.identifier($)} f ON f.rowid = u.${n.identifier("doc")} GROUP BY f.${n.identifier(Te)} HAVING ${n.join(N.map(D=>n`${D} > 0`),n` AND `)}`,_=St(t,c);let C=n`SELECT m.id, m._creationTime, m.${n.identifier(H)}, s.${n.identifier("__score__")} AS ${n.identifier("__score__")} FROM (${T}) s JOIN ${n.identifier(o)} m ON m.id = s.${n.identifier(Te)}`;_.length>0&&(C=n`${C} WHERE ${n.join(_,n` AND `)}`),C=n`${C} ORDER BY s.${n.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${n.raw(String(d))}`;const O=[];for(const D of B(i,C)){const k=yt(D);if(k){const Q=D.__score__;O.push({document:k,score:typeof Q=="number"?Q:Number(Q??0)})}}return O},Mn=(i,o,t,d,c)=>{const p=je(t.definition.language),$=He(t.query,p);if($.length===0)return[];const A=St(t,c);let y=n`SELECT id, _creationTime, ${n.identifier(H)} FROM ${n.identifier(o)}`;A.length>0&&(y=n`${y} WHERE ${n.join(A,n` AND `)}`),y=n`${y} ORDER BY _creationTime DESC, id ASC LIMIT ${n.raw(String(vn(d)))}`;const g=B(i,y).toArray(),N=[];for(const T of g){const _=yt(T);if(!_)continue;const C=$n(Dt(_,t.definition),$,p);C>0&&N.push({creationTime:typeof _._creationTime=="number"?_._creationTime:0,doc:_,id:typeof _._id=="string"?_._id:"",score:C})}return N.sort((T,_)=>_.score-T.score||_.creationTime-T.creationTime||T.id.localeCompare(_.id)),N.slice(0,d).map(T=>({document:T.doc,score:T.score}))},Be=(i,o,t,d)=>{if(!Number.isFinite(i.lat)||i.lat<-90||i.lat>90||!Number.isFinite(i.lng)||i.lng<-180||i.lng>180)throw new b("BAD_REQUEST",`geo index "${d}" on table "${t}": ${o} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},kn=(i,o)=>{const t=i,d={near:(c,p)=>{if(t.within)throw new b("INTERNAL",`geo index "${t.indexName}" on table "${o}": call .near() or .within(), not both`);if(Be(c,".near() point",o,t.indexName),!Number.isFinite(p)||p<=0)throw new b("BAD_REQUEST",`geo index "${t.indexName}" on table "${o}": .near() radiusMeters must be a finite number > 0, got ${String(p)}`);return t.near={point:{lat:c.lat,lng:c.lng},radiusMeters:p},d},within:c=>{if(t.near)throw new b("INTERNAL",`geo index "${t.indexName}" on table "${o}": call .near() or .within(), not both`);if(Be(c.sw,".within() sw corner",o,t.indexName),Be(c.ne,".within() ne corner",o,t.indexName),c.sw.lat>c.ne.lat)throw new b("BAD_REQUEST",`geo index "${t.indexName}" on table "${o}": .within() corners are transposed (sw.lat > ne.lat)`);if(c.sw.lng>c.ne.lng)throw new b("BAD_REQUEST",`geo index "${t.indexName}" on table "${o}": .within() box crosses the antimeridian (sw.lng > ne.lng), which is not supported — split it into two boxes at ±180 and union the results`);return t.within={ne:{lat:c.ne.lat,lng:c.ne.lng},sw:{lat:c.sw.lat,lng:c.sw.lng}},d}};return d},Ln=(i,o)=>{const t=i[o];if(t===null||typeof t!="object")return;const{lat:d,lng:c}=t;return typeof d=="number"&&typeof c=="number"?{lat:d,lng:c}:void 0},Dn=(i,o)=>{const t=Ln(i,o.definition.field);if(!t)return;const d=typeof i._creationTime=="number"?i._creationTime:0;if(o.near){const c=Vt(o.near.point,t);return c<=o.near.radiusMeters?{creationTime:d,distance:c}:void 0}return zt(t,o.within)?{creationTime:d,distance:0}:void 0},On=(i,o,t,d)=>{if(!t.near&&!t.within)throw new b("INTERNAL",`geo index "${t.indexName}" on table "${o}": call .near(point, radius) or .within(box)`);const c=t.near?Kt(t.near.point,t.near.radiusMeters):Yt(t.within),p=Gt(o,t.indexName),$=c.map(T=>n`(g.${n.identifier("__geohash__")} >= ${T} AND g.${n.identifier("__geohash__")} < ${`${T}{`})`),A=[n`(${n.join($,n` OR `)})`];d&&A.push(d);const y=n`SELECT m.id, m._creationTime, m.${n.identifier(H)} FROM ${n.identifier(p)} g JOIN ${n.identifier(o)} m ON m.id = g.${n.identifier("__id__")} WHERE ${n.join(A,n` AND `)}`,g=B(i,y).toArray(),N=[];for(const T of g){const _=le(T),C=_?Dn(_,t):void 0;_&&C&&N.push({creationTime:C.creationTime,distance:C.distance,doc:_})}return N.sort((T,_)=>T.distance-_.distance||_.creationTime-T.creationTime),N},_t=(i,o,t,d)=>{const c=[];for(const p of i)if(o.every($=>$(d(p)))&&(c.push(p),typeof t=="number"&&c.length>=t))break;return c},Fn=(i,o,t,d,c,p=()=>{})=>{const $=t.within!==void 0,A=On(i,o,t,c).map(y=>({distanceMeters:$?null:y.distance,document:y.doc}));return p(A.length),typeof d=="number"?A.slice(0,Math.max(0,Math.floor(d))):A},Rt=(i,o,t,d,c,p=()=>{})=>{const{geo:$}=t;if(!$)throw new b("INTERNAL","runGeoTerminalScored called without a staged geo query");const A=t.inMemoryFilters.length>0,y=Fn(i,o,$,A?void 0:c,d,p);return A?_t(y,t.inMemoryFilters,c,g=>g.document):y},Wn=(i,o,t,d,c,p=()=>{})=>Rt(i,o,t,d,c,p).map($=>$.document),Bn=(i,o,t,d,c,p,$=()=>{})=>{const A=[];for(const T of t.sqlConditions)A.push(n`${V(T.field)} ${n.raw(T.comparator)} ${oe(T.value)}`);d&&A.push(d);let y=n`SELECT id, _creationTime, ${n.identifier(H)} FROM ${n.identifier(o)}`;A.length>0&&(y=n`${y} WHERE ${n.join(A,n` AND `)}`),y=n`${y} ORDER BY ${c}`,typeof p=="number"&&t.inMemoryFilters.length===0&&(y=n`${y} LIMIT ${n.raw(String(Math.max(0,Math.floor(p))))}`);const g=B(i,y).toArray();$(g.length);const N=[];for(const T of g){const _=le(T);if(_&&t.inMemoryFilters.every(C=>C(_))&&(N.push(_),typeof p=="number"&&N.length>=p))break}return N},ie={fieldRef:V,serialize:oe},At=(i,o)=>{const t=o===void 0?void 0:i.shape[o];return t!==void 0&&ln(t)},ht=(i,o)=>o.some(t=>At(i,t)),pt=(i,o,t)=>{if(At(i,o))throw new b("BAD_REQUEST",`${t}: "${o}" is stored as an order-preserving key, which SQL cannot reduce or group — declare an aggregateIndex covering this (by, field, op) so the maintained companion answers it`)},qn=i=>{let o=0;const t=[],d={fieldRef:V,relationExists:c=>{const{childWhere:p,negated:$,parentTable:A,relation:y}=c,g=`__rel_${String(o)}`,N=t.at(-1)??A;o+=1,i(y.table,P);const T=y.kind==="one"?y.field:y.references,_=y.kind==="one"?y.references:y.field,C=n`${rt(g,_)} = ${rt(N,T)}`;t.push(g);const O=ne(p,d);t.pop();const D=O?n`${C} AND ${O}`:C,k=n`EXISTS (SELECT 1 FROM ${n.identifier(y.table)} AS ${n.identifier(g)} WHERE ${D})`;return $?n`NOT ${k}`:k},serialize:oe};return d},xt=i=>{const o=i.map(t=>n`${V(t.field)} ${n.raw(t.direction==="desc"?"DESC":"ASC")}`);return i.some(t=>t.field==="_id"||t.field==="id")||o.push(n`${V("id")} ASC`),n.join(o,n`, `)},Un={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},Pn=i=>{const o=i.order;return i.indexFields.length>0?i.indexFields.map(t=>({direction:o,field:t})):[{direction:o,field:"_creationTime"}]},jn=(i,o,t,d)=>{const c=i.sqlConditions.map(p=>({[p.field]:{[Un[p.comparator]??"eq"]:p.value}}));if(t&&c.push(Nt(o,qe(t))),d&&c.push(Zt(o,qe(d))),c.length!==0)return c.length===1?c[0]:{AND:c}},Hn=(i,o,t)=>{const d=[];for(const c of i){const p=le(c);if(p&&o.every($=>$(p))&&(d.push(p),t!==void 0&&d.length>t))break}return d},Qn=(i,o,t,d,c,p=()=>{})=>{const $=Math.max(0,Math.floor(d.numItems)),A=Pn(t),y=typeof d.endCursor=="string",g=ne(jn(t,A,d.cursor,d.endCursor),ie),N=c&&g?n`${g} AND ${c}`:c??g;let T=n`SELECT id, _creationTime, ${n.identifier(H)} FROM ${n.identifier(o)}`;N&&(T=n`${T} WHERE ${N}`),T=n`${T} ORDER BY ${xt(A)}`;const _=t.inMemoryFilters.length>0;!_&&!y&&(T=n`${T} LIMIT ${n.raw(String($+1))}`);const C=B(i,T).toArray();p(C.length);const O=Hn(C,t.inMemoryFilters,_||y?void 0:$);if(y){const W=O.length>=2?O[Math.floor(O.length/2)-1]:void 0;return{continueCursor:d.endCursor??null,isDone:!0,page:O,splitCursor:W?Ue(W,A):null}}const D=O.length>$,k=D?O.slice(0,$):O,Q=k.at(-1);return{continueCursor:D&&Q?Ue(Q,A):null,isDone:!D,page:k}};class Gn extends b{constructor(o="unique() found more than one matching document"){super("NOT_UNIQUE",o,{name:"NotUniqueError"})}}const Kn=/\s/u,Yn=String.fromCodePoint(0),mt=(i,o,t)=>{if(!i.tables[o])throw new b("INTERNAL",`unknown table: ${o}`);return typeof t!="string"||t.length===0||Kn.test(t)||t.includes(Yn)?null:t},zn=(i,o,t,d=()=>{},c=()=>{},p=()=>{})=>{const $=o.tables[t];if(!$)throw new b("INTERNAL",`unknown table: ${t}`);const A=de($.softDeleteMode,void 0),y=A?ne(A,ie):void 0,g={indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[]};let N=0;const T=E=>{const{search:v}=g;if(!v)throw new b("INTERNAL","runSearchFetch called without a staged search");jt(i,t,$);const I=g.inMemoryFilters.length>0,M=_n(I?void 0:E),G=Qt(i)?Cn(i,t,v,M,y):Mn(i,t,v,M,y);return I?(N=G.length,_t(G,g.inMemoryFilters,E,ee=>ee.document)):(E===void 0&&bn(G),G)},_=E=>T(E).map(v=>v.document),C=E=>{const v=Tn(E);return Sn(_(En(v)),v)},O=()=>{const E=g.indexFields.length>0?g.indexFields:["_creationTime"],v=g.order==="desc"?"DESC":"ASC";return n.join(E.map(I=>n`${V(I)} ${n.raw(v)}`),n`, `)},D=()=>{if(g.search||g.geo||g.indexName===void 0){c(void 0);return}c(on(t,g.indexName,g.indexFields,g.sqlConditions,oe))},k=E=>{D();let v=0;const I=(()=>{if(g.search){const M=_(E);return v=N,M}return g.geo?Wn(i,t,g,y,E,M=>{v=M}):Bn(i,t,g,y,O(),E,M=>{v=M})})();return p(Math.max(v,I.length)),I},Q=()=>{if(!g.search&&!g.geo)throw new b("INTERNAL",`ctx.db.query("${t}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);D();let E=0;const v=(()=>{if(g.search){const I=T(void 0);return E=N,I}return Rt(i,t,g,y,void 0,I=>{E=I})})();return p(Math.max(E,v.length)),v},W={async*[Symbol.asyncIterator](){const E=[...g.inMemoryFilters];let v;g.inMemoryFilters=[];try{for(;;){const I=await W.paginate({cursor:v??null,numItems:xn});for(const M of I.page)E.every(G=>G(M))&&(yield M);if(I.isDone||I.continueCursor===null)return;v=I.continueCursor}}finally{g.inMemoryFilters=E}},async collect(){return k(void 0)},async collectWithScores(){return Q()},filter(E){return g.inMemoryFilters.push(E),W},async first(){return k(g.inMemoryFilters.length>0?void 0:1)[0]??null},order(E){return g.order=E==="desc"?"desc":"asc",W},async paginate(E){let v=0;if(D(),g.search){const M=C(E);return p(M.page.length),M}if(g.geo)throw new b("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const I=Qn(i,t,g,E,y,M=>{v=M});return p(Math.max(v,I.page.length)),I},async take(E){return k(E)},async unique(){const E=k(g.inMemoryFilters.length>0?void 0:2);if(E.length>1)throw new Gn(`unique() on table "${t}" matched ${String(E.length)} documents; expected at most one`);return E[0]??null},withGeoIndex(E,v){const I=($.geoIndexes??[]).find(G=>G.name===E);if(!I)throw new b("INTERNAL",`unknown geo index "${E}" on table "${t}"`);d(t,E,"geo");const M={definition:I,indexName:E};if(g.geo=M,v(kn(M,t)),!M.near&&!M.within)throw new b("INTERNAL",`geo index "${E}" on table "${t}" requires a .near(point, radius) or .within(box) call`);return W},withIndex(E,v){const I=$.indexes.find(M=>M.name===E);if(!I)throw new b("INTERNAL",`unknown index "${E}" on table "${t}"`);return d(t,E,"index"),g.indexName=E,g.indexFields=I.fields,v&&v(In(g)),W},withSearchIndex(E,v){const I=($.searchIndexes??[]).find(G=>G.name===E);if(!I)throw new b("INTERNAL",`unknown search index "${E}" on table "${t}"`);d(t,E,"search");const M={definition:I,field:I.field,filters:[],hasQuery:!1,indexName:E,query:""};if(g.search=M,v(gn(M,t,je(I.language))),!M.hasQuery)throw new b("INTERNAL",`search index "${E}" on table "${t}" requires a .search(field, query) call`);return W}};return W},$t=(i,o,t)=>{const d={...o};for(const[c,p]of Et(i)){if(p.serverDefault){d[c]=p.serverDefault({auth:t});continue}d[c]===void 0&&(p.defaultFn?d[c]=p.defaultFn():"defaultValue"in p&&(d[c]=p.defaultValue))}return d},wt=(i,o,t,d)=>{const c=t;for(const[p,$]of Et(i)){if($.serverDefault){p in o&&(c[p]=$.serverDefault({auth:d}));continue}$.onUpdateFn&&!(p in o)&&(c[p]=$.onUpdateFn())}},gt=(i,o)=>{for(const t of Object.keys(o))if(o[t]===void 0)throw new b("INTERNAL",`Cannot ${i} field '${t}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},Vn=/unique constraint failed/i,Jn=i=>i instanceof Error&&Vn.test(i.message),Pe=(i,o,t)=>{try{B(i,t)}catch(d){throw Jn(d)?new he(`unique constraint violation on "${o}"`,"unique"):d}},Ae=(i,o,t)=>{if(Pe(i,o,t),B(i,n`SELECT changes() AS changed`).one().changed===0)throw new he(`optimistic concurrency conflict on "${o}" — the row changed during this mutation; refetch and retry`,"occ")},bt=(i,o,t,d,c,p,$)=>{const A=[];for(let T=0;T<t.length+1;T+=1){const _=[];for(let k=0;k<T;k+=1)_.push(n`${n.identifier(t[k])} IS ${p[k]}`);const C=t[T],O=d[T];if(C!==void 0&&O!==void 0){const k=O.direction==="desc"?">":"<";_.push(n`${n.identifier(C)} ${n.raw(k)} ${p[T]}`)}else _.push(n`${n.identifier(nn)} < ${$}`);const[D]=_;A.push(_.length===1&&D!==void 0?D:n`(${n.join(_,n` AND `)})`)}const y=n.join(A,n` OR `),g=B(i,n`SELECT COUNT(*) AS c FROM ${n.identifier(o)} WHERE ${n.identifier("__partition__")} = ${c} AND (${y})`).one(),N=B(i,n`SELECT COUNT(*) AS c FROM ${n.identifier(o)} WHERE ${n.identifier("__partition__")} = ${c}`).one();return{before:g.c,total:N.c}},Rr=i=>{const{sql:o}=i,{schema:t}=i,d=i.broadcast??(()=>{}),c=(e,...r)=>{const a=t.tables[e]?.indexes;if(!a||a.length===0)return;const l=[];for(const h of r)h&&l.push(...rn(a,h,oe));return l.length>0?l:void 0},{headroom:p}=i;let $=!1;const A=async e=>{const r=$;$=!0;try{return await e()}finally{$=r}},y=i.onRead??(()=>{}),g=i.onReadRange??(e=>{y(e.table,P)}),N=(e,r)=>{r!==void 0&&r!==P&&!$&&p?.recordRead(1),y(e,r)},T=i.onIndexUse??(()=>{}),_=i.onWrite??(()=>{}),C=async e=>{$||p?.recordWrite(e.doc),await _(e)},{cache:O}=i,D=i.clock??(()=>Date.now()),k=i.idGenerator??(()=>crypto.randomUUID()),Q=i.scheduler??Bt,{globalDb:W}=i,E=i.auth??{identity:null,userId:null},v=i.cdc??!1,I=Q,M=cn({scheduler:typeof I.list=="function"&&typeof I.get=="function"?I:void 0,storage:i.storage}),G=(e,r,a,l)=>{v&&Ht(o,D(),e,r,a,l)},ee=e=>t.tables[e]?.shardMode?.kind==="global",Qe=(e,r)=>{if(ee(e)){if(!W)throw new b("INTERNAL",`cross-backend ${r} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return W}return q},xe=e=>Qe(e,"cascade"),z=(e,r)=>{if(ee(e)){if(!W)throw new b("INTERNAL",`${r} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return W}},Ie=(e,r)=>Qe(e,"relation load").findMany(e,r),Ge=(e,r)=>(ee(e)&&N(e,P),Ie(e,r)),It=e=>!ee(e.table),Ke=i.relationExistsPushDown??"auto",Ye=Ke!=="never",{maxRelationKeys:ze}=i,pe=(e,r,a)=>st(e,{fetcher:Ge,maxRelationKeys:ze,relationBaseWhere:a,schema:t,tableName:r}),Ve=async(e,r,a,l)=>{const h=z(e,"relation grouped count");if(h)return N(e,P),sn((j,x)=>h.count(j,x),e,r,a,l);const f=t.tables[e];if(!f)throw new b("INTERNAL",`unknown table: ${e}`);N(e,P);const s=de(f.softDeleteMode,void 0),u={[r]:{in:a}},m=Y(Y(u,l),s),S=await pe(m,e,void 0),w=ne(S,ie),R=V(r);let L=n`SELECT ${R} AS __fk__, COUNT(*) AS count FROM ${n.identifier(e)}`;w&&(L=n`${L} WHERE ${w}`),L=n`${L} GROUP BY ${R}`;const F=B(o,L).toArray();return new Map(F.map(j=>[j.__fk__,j.count]))};let me=0;const Je=new Set;for(const[e,r]of Object.entries(t.tables))for(const a of Object.values(r.triggerMap??{}))Je.add(`${e} ${a.timing} ${a.op}`);const X=(e,r,a)=>Je.has(`${e} ${r} ${a}`),Z=async(e,r,a)=>{if(me+=1,me>ft)throw me-=1,new he(`trigger recursion exceeded ${String(ft)} levels on "${a.table}" — check for a self-triggering write`,"trigger");try{await un({ctx:Ct,event:a,op:r,schema:t,tableName:a.table,timing:e})}finally{me-=1}},{ensureBackfilledForTable:ce,ensureBackfilledIndex:ve,ensureRankBackfilled:Ce,ensureRankBackfilledForTable:ue,syncAggregates:$e,syncCompanionsForInsert:Xe,syncGeo:we,syncRanks:fe,syncSearch:ge}=Lt({broadcast:d,indexKeysFor:(e,r)=>c(e,r),invalidateCache:(e,r,a)=>O?.invalidate(e,r,c(e,a)),recordCdc:G,schema:t,sql:o}),Ze=(e,r,a)=>{const{shardMode:l}=r;if(l?.kind==="shardBy"&&!(l.field!==void 0&&(a.partitionBy??[]).includes(l.field)))throw Object.assign(new Error(`rank index "${a.name}" on "${e}" partitions across shards (shard key "${l.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})},et=e=>Object.entries(t.tables).filter(([,r])=>r.shardMode?.kind!=="global").map(([r])=>r).filter(r=>e===void 0||r===e),re=(e,r)=>{const a=et(r);if(a.length===0)return;const l=a.map(S=>n`SELECT ${n.raw(`'${S.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${n.identifier(H)} FROM ${n.identifier(S)} WHERE id = ${e}`),h=n`${n.join(l,n` UNION ALL `)} LIMIT 1`,[f]=B(o,h).toArray();if(!f)return;const s=f.__t__,u=le(f);if(typeof s!="string"||!u)return;const m=f[H];return{docJson:typeof m=="string"?m:ae(m??{}),row:u,tableName:s}},vt=(e,r)=>{const a=[...new Set(e)],l=new Map;if(a.length===0)return l;const h=et(r);if(h.length===0)return l;const f=Math.max(1,Math.floor(900/h.length));for(let s=0;s<a.length;s+=f){const u=a.slice(s,s+f),m=n.join(u.map(R=>n`${R}`),n`, `),S=h.map(R=>n`SELECT ${n.raw(`'${R.replaceAll("'","''")}'`)} AS __t__, id FROM ${n.identifier(R)} WHERE id IN (${m})`),w=n.join(S,n` UNION ALL `);for(const R of B(o,w)){const{id:L,__t__:F}=R;typeof F=="string"&&typeof L=="string"&&l.set(L,F)}}return l},tt={assertRankPartitionLocal:Ze,ensureRankBackfilled:Ce,onRead:N,rowToDocument:le,schema:t,sql:o},q={system:M,async aggregate(e,r){const a=z(e,"aggregate");if(a)return N(e,P),a.aggregate(e,r);const l=t.tables[e];if(!l)throw new b("INTERNAL",`unknown table: ${e}`);if(Se(r.op),r.op==="count")return q.count(e,{baseWhere:r.baseWhere,relationBaseWhere:r.relationBaseWhere,restrictsCounts:r.restrictsCounts,where:r.where});if(!r.field)throw new b("INTERNAL",`aggregate(${e}, { op: "${r.op}" }): "field" is required for non-count reducers`);N(e,P);const h=de(l.softDeleteMode,void 0),f=Y(Y(r.baseWhere,r.where),h),s=await pe(f,e,r.relationBaseWhere),u=s!==f;if(l.aggregateIndexes&&!r.baseWhere&&!u&&(!h||ht(l,[r.field]))){const F=Pt(l.aggregateIndexes,r.op,r.field,r.where);if(F){ve(e,F.index);const j=Me(F.index.by??[],F.key),x=Le(e,F.index.name),K=B(o,n`SELECT ${_e} AS value, ${Oe} AS count FROM ${n.identifier(x)} WHERE ${Re} = ${j}`).toArray()[0];return ke(r.op,K)}}pt(l,r.field,`aggregate(${e}, { op: "${r.op}", field: "${r.field}" })`);const m=ne(s,ie),S=Se(r.op),w=V(r.field);let R=n`SELECT ${n.raw(S)}(${w}) AS value FROM ${n.identifier(e)}`;return m&&(R=n`${R} WHERE ${m}`),B(o,R).toArray()[0]?.value??null},asId(e,r){const a=mt(t,e,r);if(a===null)throw new b("BAD_REQUEST",`asId("${e}", …): "${r}" is not a valid id for table "${e}"`,{status:400});return a},async count(e,r){const a=z(e,"count");if(a)return N(e,P),a.count(e,r);const l=t.tables[e];if(!l)throw new b("INTERNAL",`unknown table: ${e}`);const h=Wt(r);if(h.restrictsCounts)throw new De(e);N(e,P);const f=de(l.softDeleteMode,void 0),s=Y(Y(h.baseWhere,h.where),f),u=await pe(s,e,h.relationBaseWhere),m=u!==s;if(l.aggregateIndexes&&!h.baseWhere&&!m&&!f){const R=Ut(l.aggregateIndexes,h.where);if(R){ve(e,R.index);const L=Me(R.index.by??[],R.key),F=Le(e,R.index.name),j=B(o,n`SELECT ${_e} AS value FROM ${n.identifier(F)} WHERE ${Re} = ${L}`).toArray();return j[0]===void 0?0:j[0].value??0}}const S=ne(u,ie);let w=n`SELECT COUNT(*) AS count FROM ${n.identifier(e)}`;return S&&(w=n`${w} WHERE ${S}`),B(o,w).one().count},async delete(e,r,a){const l=re(e,r);if(!l){const w=r===void 0?W:void 0;w&&await w.delete(e,void 0,a);return}const{docJson:h,row:f,tableName:s}=l,u=t.tables[s],m=a?.hard===!0,S=!m&&u?.softDeleteMode?u.softDeleteMode.field:void 0;if(!(S&&f[S]!==null&&f[S]!==void 0)){if(X(s,"before","delete")&&await Z("before","delete",{id:e,op:"delete",previous:f,table:s}),await an({deletedId:e,deletedReference:w=>f[w],findHolders:async(w,R,L)=>(await xe(w).findMany(w,{includeDeleted:m,where:{[R]:L}})).page,onCascade:(w,R)=>xe(w).delete(R,void 0,a),onRestrict:w=>{throw new he(w,"restrict")},onSetNull:(w,R,L)=>xe(w).patch(R,{[L]:null}),schema:t,tableName:s}),ce(s),ue(s),S){const w={...f,[S]:D(),_id:e};Ae(o,s,n`UPDATE ${n.identifier(s)} SET ${n.identifier(H)} = ${ae(w)} WHERE id = ${e} AND ${n.identifier(H)} = ${h}`),ge(s,e,w,f),we(s,e,void 0),$e(s,f,w),fe(s,e,f,void 0),O?.invalidate(s,e,c(s,f,w)),G(s,e,"update",w),d({indexKeys:c(s,f,w),key:e,op:"update",row:w,table:s}),X(s,"after","delete")&&await Z("after","delete",{id:e,op:"delete",previous:f,table:s}),await C({id:e,op:"delete",table:s});return}Ae(o,s,n`DELETE FROM ${n.identifier(s)} WHERE id = ${e} AND ${n.identifier(H)} = ${h}`),ge(s,e,void 0),we(s,e,void 0),$e(s,f,void 0),fe(s,e,f,void 0),O?.invalidate(s,e,c(s,f)),G(s,e,"delete"),d({indexKeys:c(s,f),key:e,op:"delete",table:s}),X(s,"after","delete")&&await Z("after","delete",{id:e,op:"delete",previous:f,table:s}),await C({id:e,op:"delete",table:s})}},async deleteAll(e,r){if(!t.tables[e])throw new b("INTERNAL",`unknown table: ${e}`);const a=Math.max(1,r?.chunkSize??Tt),l=r?.hard===void 0?void 0:{hard:r.hard},h=ee(e)?void 0:e;let f=0;return await A(async()=>{for(;;){const s=(await q.findMany(e,{limit:a})).page.map(u=>String(u._id));if(s.length===0)break;for(const u of s)await q.delete(u,h,l),f+=1;if(s.length<a)break}}),{deleted:f}},async deleteMany(e,r,a){se(e.length,r?.limit,"deleteMany");for(const l of e)await q.delete(l,a);return{deleted:e.length}},async deleteWhere(e,r,a){const l=(await(z(e,"deleteWhere")??q).findMany(e,{where:r})).page.map(h=>String(h._id));if(se(l.length,a?.limit,"deleteWhere"),q.deleteMany===void 0)throw new b("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return q.deleteMany(l,a)},async findFirst(e,r={}){return(await q.findMany(e,{...r,limit:1})).page[0]??null},async findFirstOrThrow(e,r={}){const a=await q.findFirst(e,r);if(a===null)throw new Jt(`findFirstOrThrow: no "${e}" document matched`);return a},async findMany(e,r={}){const a=z(e,"findMany");if(a)return N(e,P),a.findMany(e,r);const l=t.tables[e];if(!l)throw new b("INTERNAL",`unknown table: ${e}`);const h=!r.where&&!r.baseWhere;h?N(e,P):N(e);const f=Xt(r.orderBy),s=r.cursor?Nt(f,qe(r.cursor)):void 0;let u=Y(r.baseWhere,r.where);u=Y(u,de(l.softDeleteMode,r.includeDeleted)),u=await st(u,{canPushExists:Ye?It:void 0,existsPushMode:Ke==="always"?"always":"auto",fetcher:Ge,maxRelationKeys:ze,relationBaseWhere:r.relationBaseWhere,schema:t,tableName:e}),s&&(u=u?{AND:[u,s]}:s);const m=Ye?qn(N):ie,S=ne(u,m);let w=n`SELECT id, _creationTime, ${n.identifier(H)} FROM ${n.identifier(e)}`;S&&(w=n`${w} WHERE ${S}`),w=n`${w} ORDER BY ${xt(f)}`;const R=typeof r.limit=="number"?Math.max(0,Math.floor(r.limit)):void 0;R!==void 0&&(w=n`${w} LIMIT ${n.raw(String(R+1))}`);const L=B(o,w).toArray();h&&!$&&p?.recordRead(L.length);const F=[];for(const te of L){const U=le(te);U&&(F.push(U),!h&&typeof U._id=="string"&&N(e,U._id))}if(R===void 0)return r.with&&await dt({groupedCounter:Ve,fetcher:Ie,parents:F,...lt(r),schema:t,tableName:e,with:r.with}),{continueCursor:null,isDone:!0,page:it(F,r.select,r.with)};const j=F.length>R,x=j?F.slice(0,R):F,K=x.at(-1);return r.with&&await dt({fetcher:Ie,groupedCounter:Ve,parents:x,...lt(r),schema:t,tableName:e,with:r.with}),{continueCursor:j&&K?Ue(K,f):null,isDone:!j,page:it(x,r.select,r.with)}},async get(e,r){const a=re(e,r);if(!a){const l=r===void 0?W:void 0;return l?l.get(e):null}return N(a.tableName,e),a.row},async lookupById(e,r){const a=re(e,r);return a?(N(a.tableName,e),{row:a.row,tableName:a.tableName}):null},async groupBy(e,r){const a=z(e,"groupBy");if(a)return N(e,P),a.groupBy(e,r);const l=t.tables[e];if(!l)throw new b("INTERNAL",`unknown table: ${e}`);N(e,P);const h=r.agg??{op:"count"};if(Se(h.op),h.op!=="count"&&!h.field)throw new b("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);const f=de(l.softDeleteMode,void 0),s=Y(Y(r.baseWhere,r.where),f),u=await pe(s,e,r.relationBaseWhere),m=u!==s,S=[...r.by,h.field];if(l.aggregateIndexes&&!r.baseWhere&&!m&&(!f||ht(l,S))){const x=qt(l.aggregateIndexes,h.op,h.field,r.by,r.where),K=x===void 0?0:Object.keys(x.partial).length,te=x?.index.by?.length??0;if(x&&(K===0||K===te)){ve(e,x.index);const U=Le(e,x.index.name),be=Object.keys(x.partial),Ee=[];if(be.length===(x.index.by??[]).length&&be.length>0){const ye=Me(x.index.by??[],x.partial),Ne=B(o,n`SELECT ${_e} AS value, ${Oe} AS count FROM ${n.identifier(U)} WHERE ${Re} = ${ye}`).toArray();return Ne.length>0&&Ee.push({key:{...x.partial},value:ke(h.op,Ne[0])}),Ee}const Mt=B(o,n`SELECT ${Re} AS key, ${_e} AS value, ${Oe} AS count FROM ${n.identifier(U)}`).toArray();for(const ye of Mt){const Ne=Ft(JSON.parse(ye.key));Ee.push({key:Ne,value:ke(h.op,ye)})}return Ee}}for(const x of S){if(x===void 0)continue;const K=x===h.field?`groupBy(${e}, { agg: { op: "${h.op}", field: "${x}" } })`:`groupBy(${e}, { by: [..."${x}"] })`;pt(l,x,K)}const w=ne(u,ie),R=r.by.map(x=>n`${V(x)} AS ${n.identifier(x)}`);if(h.op==="count")R.push(n`COUNT(*) AS value`);else{const{field:x}=h;if(x===void 0)throw new b("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);R.push(n`${n.raw(Se(h.op))}(${V(x)}) AS value`)}let L=n`SELECT ${n.join(R,n`, `)} FROM ${n.identifier(e)}`;w&&(L=n`${L} WHERE ${w}`),L=n`${L} GROUP BY ${n.join(r.by.map(x=>V(x)),n`, `)}`;const F=B(o,L).toArray(),j=[];for(const x of F){const K={};for(const U of r.by)K[U]=x[U]??null;const{value:te}=x;j.push({key:K,value:te==null?null:Number(te)})}return j},async insert(e,r,a){const l=z(e,"insert");if(l){const S=await l.insert(e,r,a);return $||p?.recordWrite(r),d({key:S,op:"insert",row:{...r,_id:S},table:e}),S}const h=t.tables[e];if(!h)throw new b("INTERNAL",`unknown table: ${e}`);const f=$t(h,r,E);We(h,f);let s;a?.clientId!==void 0?(An(a.clientId),s=a.clientId):a?.allowExplicitId&&typeof f._id=="string"?s=f._id:s=k();const u=a?.allowExplicitId&&typeof f._creationTime=="number"?f._creationTime:D(),m={...f,_creationTime:u,_id:s};return X(e,"before","insert")&&await Z("before","insert",{doc:{...m},id:s,op:"insert",table:e}),ce(e),ue(e),Pe(o,e,n`INSERT INTO ${n.identifier(e)} (id, _creationTime, ${n.identifier(H)}) VALUES (${s}, ${u}, ${ae(m)})`),Xe(e,s,m),X(e,"after","insert")&&await Z("after","insert",{doc:m,id:s,op:"insert",table:e}),await C({doc:m,id:s,op:"insert",table:e}),s},async insertManyUnsafe(e,r,a){if(se(r.length,a?.limit,"insertManyUnsafe"),r.length===0)return[];const l=z(e,"insert");if(l){const u=[];for(const m of r){const S=await l.insert(e,m,{allowExplicitId:a?.allowExplicitId});$||p?.recordWrite(m),d({key:S,op:"insert",row:{...m,_id:S},table:e}),u.push(S)}return u}const h=t.tables[e];if(!h)throw new b("INTERNAL",`unknown table: ${e}`);ce(e),ue(e);const f=r.map(u=>{const m=$t(h,u,E),S=a?.allowExplicitId===!0&&typeof m._id=="string"?m._id:k(),w=a?.allowExplicitId===!0&&typeof m._creationTime=="number"?m._creationTime:D();return{creationTime:w,document:{...m,_creationTime:w,_id:S},id:S}});if(!$)for(const u of f)p?.recordWrite(u.document);const s=n.join(f.map(u=>n`(${u.id}, ${u.creationTime}, ${ae(u.document)})`),n`, `);Pe(o,e,n`INSERT INTO ${n.identifier(e)} (id, _creationTime, ${n.identifier(H)}) VALUES ${s}`);for(const{document:u,id:m}of f)Xe(e,m,u),await _({doc:u,id:m,op:"insert",table:e});return f.map(u=>u.id)},async insertMany(e,r,a){se(r.length,a?.limit,"insertMany");const l=a?.skipDuplicates===!0,h=[];for(const f of r)try{h.push(await q.insert(e,f))}catch(s){if(l&&s instanceof he&&s.kind==="unique")h.push(null);else throw s}return h},normalizeId(e,r){return mt(t,e,r)},async patch(e,r,a){const l=re(e,a);if(!l){const S=a===void 0?W:void 0;if(S){await S.patch(e,r);return}throw new b("INTERNAL",`document not found: ${e}`)}const{docJson:h,row:f,tableName:s}=l,u=t.tables[s];if(!u)throw new b("INTERNAL",`unknown table: ${s}`);N(s,e),gt("patch",r);const m={...f,...r,_id:e};wt(u,r,m,E),We(u,m,!0),X(s,"before","update")&&await Z("before","update",{doc:{...m},id:e,op:"update",previous:f,table:s}),ce(s),ue(s),Ae(o,s,n`UPDATE ${n.identifier(s)} SET ${n.identifier(H)} = ${ae(m)} WHERE id = ${e} AND ${n.identifier(H)} = ${h}`),ge(s,e,m,f),we(s,e,m),$e(s,f,m),fe(s,e,f,m),O?.invalidate(s,e,c(s,f,m)),G(s,e,"update",m),d({indexKeys:c(s,f,m),key:e,op:"update",row:m,table:s}),X(s,"after","update")&&await Z("after","update",{doc:m,id:e,op:"update",previous:f,table:s}),await C({doc:m,id:e,op:"update",table:s})},async patchMany(e,r,a){se(e.length,r?.limit,"patchMany");for(const l of e)await q.patch(l.id,l.patch,a);return{patched:e.length}},async patchWhere(e,r,a){const l=(await(z(e,"patchWhere")??q).findMany(e,{where:r.where})).page.map(h=>({id:String(h._id),patch:r.patch}));if(se(l.length,a?.limit,"patchWhere"),q.patchMany===void 0)throw new b("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await q.patchMany(l,a),{patched:l.length}},query(e){const r=z(e,"query");return r?(N(e,P),r.query(e)):zn(o,t,e,T,a=>{a?g(a):N(e,P)},a=>{$||p?.recordRead(a)})},async rank(e,r,a){const l=z(e,"rank");if(l)return N(e,P),l.rank(e,r,a);T(e,r,"rank");const h=t.tables[e];if(!h)throw new b("INTERNAL",`unknown table: ${e}`);const f=h.rankIndexes?.find(U=>U.name===r);if(!f)throw new b("INTERNAL",`unknown rankIndex "${r}" on table "${e}"`);if(Ze(e,h,f),a.restrictsCounts)throw new De(e);N(e,P),Ce(e,f);const s=typeof a.row=="string"?a.row:a.row._id;if(!s)return null;const u=at(e,f.name),m=f.sortBy.map((U,be)=>ot(be)),S=m.map(U=>fn(U)).join(", "),w=B(o,n`SELECT ${n.identifier("__partition__")}, ${n.raw(S)} FROM ${n.identifier(u)} WHERE ${n.identifier("__id__")} = ${s}`).toArray(),[R]=w;if(R===void 0)return null;let L=R.__partition__;const F=Y(a.baseWhere,a.where);Fe(F,t,e,"rank");const j=en(f,F);if(j){const U=tn(f.partitionBy??[],j);if(U!==L)return null;L=U}const x=m.map(U=>R[U]),{before:K,total:te}=bt(o,u,m,f.sortBy,L,x,s);return{position:K+1,total:te}},async rankBefore(e,r,a){if(ee(e))throw new b("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const l=t.tables[e];if(!l)throw new b("INTERNAL",`unknown table: ${e}`);const h=l.rankIndexes?.find(m=>m.name===r);if(!h)throw new b("INTERNAL",`unknown rankIndex "${r}" on table "${e}"`);if(a.restrictsCounts)throw new De(e);N(e,P),Ce(e,h);const f=at(e,h.name),s=h.sortBy.map((m,S)=>ot(S)),u=h.sortBy.map((m,S)=>oe(a.sortValues[S]??null));return bt(o,f,s,h.sortBy,a.partitionKey,u,a.rowId)},async rankPage(e,r,a={}){Fe(Y(a.baseWhere,a.where),t,e,"rankPage");const l=z(e,"rankPage");if(l)return N(e,P),l.rankPage(e,r,a);T(e,r,"rank");const{continueCursor:h,hasMore:f,rows:s}=nt(tt,e,r,a);return{continueCursor:h,isDone:!f,page:s.map(u=>u.doc)}},async rankPageRows(e,r,a={}){Fe(Y(a.baseWhere,a.where),t,e,"rankPage"),T(e,r,"rank");const{directions:l,hasMore:h,rows:f}=nt(tt,e,r,a);return{directions:l,hasMore:h,rows:f}},async restore(e,r){const a=re(e,r);if(!a){const f=r===void 0?W:void 0;if(f?.restore){await f.restore(e);return}throw new b("INTERNAL",`document not found: ${e}`)}const l=t.tables[a.tableName]?.softDeleteMode?.field;if(!l)throw new b("INTERNAL",`ctx.db.restore: table "${a.tableName}" is not a .softDelete() table`);const h=a.row[l]!==null&&a.row[l]!==void 0;await q.patch(e,{[l]:null},r),h&&fe(a.tableName,e,void 0,a.row)},async replace(e,r,a,l){const h=re(e,a);if(!h){const R=a===void 0?W:void 0;if(R){await R.replace(e,r,void 0,l);return}throw new b("INTERNAL",`document not found: ${e}`)}const{docJson:f,row:s,tableName:u}=h,m=t.tables[u];if(!m)throw new b("INTERNAL",`unknown table: ${u}`);gt("replace",r);const S=l?.allowExplicitId&&typeof r._creationTime=="number"?r._creationTime:D(),w={...r,_creationTime:S,_id:e};wt(m,r,w,E),We(m,w),X(u,"before","update")&&await Z("before","update",{doc:{...w},id:e,op:"update",previous:s,table:u}),ce(u),ue(u),Ae(o,u,n`UPDATE ${n.identifier(u)} SET _creationTime = ${S}, ${n.identifier(H)} = ${ae(w)} WHERE id = ${e} AND ${n.identifier(H)} = ${f}`),ge(u,e,w,s),we(u,e,w),$e(u,s,w),fe(u,e,s,w),O?.invalidate(u,e,c(u,s,w)),G(u,e,"update",w),d({indexKeys:c(u,s,w),key:e,op:"update",row:w,table:u}),X(u,"after","update")&&await Z("after","update",{doc:w,id:e,op:"update",previous:s,table:u}),await C({doc:w,id:e,op:"update",table:u})},async wipeShard(e){const r=new Set(e?.exclude),a=e?.tables,l=Object.entries(t.tables).filter(([u,m])=>r.has(u)||a!==void 0&&!a.includes(u)?!1:m.shardMode?.kind!=="global").map(([u])=>u);if(a!==void 0){for(const u of a)if(!t.tables[u])throw new b("INTERNAL",`wipeShard: unknown table: ${u}`)}const h={};let f=0;const{deleteAll:s}=q;if(s===void 0)throw new b("INTERNAL","wipeShard: this writer has no deleteAll");for(const u of l){const m=await s(u,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});h[u]=m.deleted,f+=m.deleted}return{deleted:f,tables:h}}},Ct={db:q,scheduler:Q};return i.enforceRls===!0?dn(q,t,(e,r)=>re(e,r)?.tableName,(e,r)=>vt(e,r)):q};export{kr as CDC_LOG_TABLE,Pr as CLIENT_WATERMARK_TABLE,Kr as GLOBAL_SHAPE_SNAPSHOT_TABLE,ei as IDEMPOTENCY_TABLE,Gn as NotUniqueError,si as SEARCH_STATE_TABLE,jr as advanceClientWatermark,Lr as applyCdcChanges,An as assertValidClientId,Ir as backfillAggregateIndexes,vr as backfillRankIndexes,Cr as backfillSearchIndexes,Dr as bumpCdcEpoch,Rr as createShardCtxDb,Yr as deleteGlobalShapeSnapshot,zr as deleteGlobalShapeSnapshotsForConnection,Hr as migrateClientWatermark,Vr as migrateGlobalShapeSnapshot,Or as minCdcSeq,mt as normalizeIdStructurally,Fr as readCdcChanges,Wr as readCdcCursor,Br as readCdcEpoch,Qr as readClientWatermark,Jr as readGlobalShapeSnapshot,ti as readIdempotent,oi as runShardMigrations,li as selectShapeMemberIds,ci as selectShapeRows,qr as trimCdcChanges,ni as trimIdempotent,Xr as writeGlobalShapeSnapshot,ri as writeIdempotent};
@@ -0,0 +1,17 @@
1
+ import{runSql as d,orNull as u,decodeJsonColumn as _}from"./runDrizzle-B6rnz3so.mjs";const s="__lunora_queue_messages",T=500,E=128*1024,i="… [truncated by the dev queue catcher]",m="[unserializable message body]",p=e=>{if(e===void 0)return"null";try{const t=JSON.stringify(e);return t.length>E?JSON.stringify(`${t.slice(0,E)}${i}`):t}catch{return JSON.stringify(m)}},g=e=>typeof e=="string"&&(e===m||e.endsWith(i)),o=e=>{d(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
+ )`)},R=(e,t,a)=>{o(e);for(const r of t)d(e,`INSERT INTO "${s}" (id, captured_at, message_id, queue, export_name, body, attempts, outcome, error, dead_lettered, message_ts)
14
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,crypto.randomUUID(),a,r.messageId,r.queue,u(r.exportName),p(r.body),r.attempts,r.outcome,u(r.error),r.deadLettered===!0?1:0,r.timestamp);return d(e,`DELETE FROM "${s}"
15
+ WHERE id NOT IN (
16
+ SELECT id FROM "${s}" ORDER BY captured_at DESC, id DESC LIMIT ?
17
+ )`,T),{recorded:t.length}},n=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}),l=(e,t={})=>{o(e);const a=Math.min(Math.max(t.limit??100,1),T),r=typeof t.queue=="string"&&t.queue.length>0?t.queue:void 0,N=r===void 0?"":"WHERE queue = ?",L=r===void 0?[a]:[r,a];return{entries:d(e,`SELECT * FROM "${s}" ${N} ORDER BY captured_at DESC, id DESC LIMIT ?`,...L).toArray().map(c=>n(c))}},I=(e,t)=>{o(e);const a=d(e,`SELECT * FROM "${s}" WHERE id = ? LIMIT 1`,t).toArray()[0];return a===void 0?void 0:n(a)},y=e=>(o(e),d(e,`DELETE FROM "${s}"`),{cleared:!0});export{E as MAX_BODY_CHARS,T as QUEUE_RETENTION,s as QUEUE_TABLE,y as clearQueueMessages,o as ensureQueueTable,g as isLossyBody,I as readQueueMessageById,l as readQueueMessages,R as recordQueueMessages};
@@ -0,0 +1 @@
1
+ import{matchesStaticWhere as l}from"./AGGREGATE_SQL_FUNCTION-CTo0-9iZ.mjs";import{compareStrings as c}from"./aggregateTableName-DgYMC5tr.mjs";import{serializeSqlValue as f}from"./serializeSqlValue-BR4UOWoP.mjs";const n=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:n}return r},u=(r,t)=>{if(r.length===0)return"";const o={};for(const s of r.toSorted(c))o[s]=t[s]??null;return JSON.stringify(o)},h="__id__",k=r=>`__sort_k${String(r)}__`,S=(r,t)=>{const o=r.partitionBy??[],s=t??{};for(const e of Object.keys(s))if(e==="AND"||e==="OR"||e==="NOT")return;const i={};for(const e of o)if(e in s){const a=m(s[e]);if(a===n)return;i[e]=a}else if(r.where&&e in r.where)i[e]=r.where[e];else return;return i},d=(r,t)=>`${r}__rank_${t}`,b=(r,t)=>({partitionKey:u(r.partitionBy??[],t),rowId:t._id,sortValues:r.sortBy.map(o=>f(t[o.field]??null))}),g=l;export{h as RANK_TIEBREAK,u as encodePartitionKey,g as matchesRankStaticWhere,b as rankKeyFromDoc,d as rankTableName,S as resolveRankPartition,k as sortColumnName};
@@ -0,0 +1 @@
1
+ const t="__lunora_reproject__",o=r=>`${t}${r}`,i=r=>{if(!r.startsWith(t))return;const e=r.slice(t.length);return e===""?void 0:e};export{t as REPROJECTION_MIGRATION_PREFIX,o as reprojectionMigrationId,i as reprojectionMigrationTable};
@@ -0,0 +1 @@
1
+ import{LunoraError as w}from"@lunora/errors";const b=Symbol.for("lunora.ctxdb.rls-unwrap");class R extends w{table;constructor(s){super("RLS_REQUIRED",`ctx.db access to "${s}" 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=s}}const g=o=>Object.entries(o.tables).filter(([,s])=>s.shardMode?.kind!=="global").map(([s])=>s),k=(o,s,u)=>{const l=s?.tables,r=new Set(s?.exclude);for(const d of o)(l===void 0||l.includes(d))&&!r.has(d)&&u(d)},m=["aggregate","count","deleteAll","findFirst","findFirstOrThrow","findMany","groupBy","insert","insertMany","insertManyUnsafe","query","rank","rankBefore","rankPage","rankPageRows"],S=(o,s,u,l)=>{if(s.rlsMode!=="required")return o;const r=o,d=e=>{const t=s.tables[e];return t!==void 0&&t.isPublic!==!0},n=e=>{if(d(e))throw new R(e)},c=async(e,t)=>{if(t!==void 0){n(t);return}const a=await u(e);a!==void 0&&n(a)},h=async(e,t)=>{if(t!==void 0){n(t);return}if(!l){for(const i of e)await c(i,t);return}const a=await l([...new Set(e)],t);for(const i of e){const y=a.get(i);y!==void 0&&n(y)}},p={...o,[b]:o,delete:async(e,t,a)=>(await c(e,t),r.delete(e,t,a)),deleteMany:async(e,t,a)=>(await h(e,a),r.deleteMany(e,t,a)),deleteWhere:r.deleteWhere?async(e,t,a)=>(n(e),await r.deleteWhere?.(e,t,a)):void 0,get:async(e,t)=>(await c(e,t),r.get(e,t)),lookupById:async(e,t)=>(await c(e,t),r.lookupById?.(e,t)??null),patch:async(e,t,a)=>(await c(e,a),r.patch(e,t,a)),patchMany:async(e,t,a)=>(await h(e.map(i=>i.id),a),r.patchMany(e,t,a)),patchWhere:r.patchWhere?async(e,t,a)=>(n(e),await r.patchWhere?.(e,t,a)):void 0,replace:async(e,t,a,i)=>(await c(e,a),r.replace(e,t,a,i)),restore:async(e,t)=>(await c(e,t),r.restore?.(e,t))},f=r;for(const e of m){const t=f[e];typeof t=="function"&&(p[e]=(a,...i)=>(n(a),t.call(r,a,...i)))}if(r.wipeShard){const{wipeShard:e}=r;p.wipeShard=t=>(k(g(s),t,n),e.call(r,t))}return p};export{b as RLS_UNWRAP_SYMBOL,R as RlsRequiredError,S as guardWriter};
@@ -0,0 +1 @@
1
+ import{stableWireKey as p}from"./stableWireKey-l3cjIt-9.mjs";import{depKey as l,SCAN_DEP as f}from"./SCAN_DEP-D_yR9EeV.mjs";import{o as m}from"./estimate-bytes-Drp8rhPs.mjs";import{keysTouchRanges as u}from"./buildIndexRange-DFsdtPjD.mjs";import{stableStringify as A}from"./stableStringify-BjLh4gvA.mjs";const c=(o,t,e)=>{let s=o.get(t);return s===void 0&&(s=e(),o.set(t,s)),s},x=1e3,g=4*1024*1024;class z{entries=new Map;tableIndex=new Map;rangeIndex=new Map;totalBytes=0;hits=0;misses=0;evictions=0;maxEntries;maxBytes;now;monotonic=0;constructor(t={}){this.maxEntries=t.maxEntries??x,this.maxBytes=t.maxBytes??g,this.now=t.now??(()=>(this.monotonic+=1,this.monotonic))}async run(t,e,s,i=()=>[]){const n=this.entries.get(t);if(n)return this.hits+=1,n.lastUsed=this.now(),this.entries.delete(t),this.entries.set(t,n),n.result;this.misses+=1;const r=await s(),h=m(r);if(h===void 0)return r;const d=i(),b={bytes:h,deps:e,ranges:d,lastUsed:this.now(),result:r,subscribers:new Set};this.entries.set(t,b),this.totalBytes+=h;for(const a of e)c(this.tableIndex,a,()=>new Set).add(t);for(const a of d){const y=c(this.rangeIndex,a.table,()=>new Map);c(y,a,()=>new Set).add(t)}return this.evict(),r}invalidate(t,e,s){const i=[];return this.collectAndDrop(l(t,e),i),this.collectAndDrop(l(t,f),i),this.dropRangeDeps(t,s,i),i}invalidateTable(t){const e=[],s=`${t}:`;for(const i of this.tableIndex.keys())i.startsWith(s)&&this.collectAndDrop(i,e);return this.dropRangeDeps(t,void 0,e),e}subscribe(t,e){const s=this.entries.get(t);s&&s.subscribers.add(e)}unsubscribe(t,e){const s=this.entries.get(t);s&&s.subscribers.delete(e)}size(){return{bytes:this.totalBytes,entries:this.entries.size}}clear(){this.entries.clear(),this.tableIndex.clear(),this.rangeIndex.clear(),this.totalBytes=0}subscribers(t){const e=this.entries.get(t);return e?[...e.subscribers]:[]}stats(){return{bytes:this.totalBytes,entries:this.entries.size,evictions:this.evictions,hits:this.hits,misses:this.misses}}dropRangeDeps(t,e,s){const i=this.rangeIndex.get(t);if(!(!i||i.size===0))for(const[n,r]of i)u([n],e)&&this.dropKeys(r,s)}collectAndDrop(t,e){const s=this.tableIndex.get(t);s&&this.dropKeys(s,e)}dropKeys(t,e){for(const s of t){const i=this.entries.get(s);i&&(this.dropEntry(s,i),e.push(s))}}dropEntry(t,e){this.entries.delete(t),this.totalBytes-=e.bytes;for(const s of e.deps){const i=this.tableIndex.get(s);i&&(i.delete(t),i.size===0&&this.tableIndex.delete(s))}for(const s of e.ranges){const i=this.rangeIndex.get(s.table),n=i?.get(s);n?.delete(t),i&&n?.size===0&&(i.delete(s),i.size===0&&this.rangeIndex.delete(s.table))}}evict(){if(!(this.entries.size<=this.maxEntries&&this.totalBytes<=this.maxBytes))for(const[t,e]of this.entries){if(this.entries.size<=this.maxEntries&&this.totalBytes<=this.maxBytes)return;e.subscribers.size>0||(this.dropEntry(t,e),this.evictions+=1)}}}const E=(o,t,e)=>`${e??"\0anon"}\0${o}:${p(t)}`;export{z as ReactiveCache,E as reactiveCacheKey,A as stableStringify,p as stableWireKey};
@@ -0,0 +1,6 @@
1
+ import{quoteIdentifier as T}from"./quoteIdentifier-CObIFRhb.mjs";import{runSql as e}from"./runDrizzle-B6rnz3so.mjs";const i="__lunora_schema_history",R=50,a=T(i),n=s=>({appliedAt:typeof s.applied_at=="number"?s.applied_at:0,hash:typeof s.hash=="string"?s.hash:"",seq:typeof s.seq=="number"?s.seq:0}),h=s=>{e(s,`CREATE TABLE IF NOT EXISTS ${a} (
2
+ hash TEXT PRIMARY KEY,
3
+ seq INTEGER NOT NULL,
4
+ snapshot_json TEXT NOT NULL,
5
+ applied_at INTEGER NOT NULL
6
+ )`)},S=s=>{e(s,`DELETE FROM ${a} WHERE hash NOT IN (SELECT hash FROM ${a} ORDER BY seq DESC LIMIT ?)`,R)},L=(s,t,r,o=Date.now())=>{if(t===""||r==="")return!1;try{if(h(s),e(s,`SELECT hash FROM ${a} WHERE hash = ? LIMIT 1`,t).toArray().length>0)return!1;const[E]=e(s,`SELECT COALESCE(MAX(seq), 0) + 1 AS next FROM ${a}`).toArray(),p=typeof E?.next=="number"?E.next:1;return e(s,`INSERT INTO ${a} (hash, seq, snapshot_json, applied_at) VALUES (?, ?, ?, ?) ON CONFLICT(hash) DO NOTHING`,t,p,r,o),S(s),!0}catch{return!1}},N=s=>{try{return h(s),e(s,`SELECT hash, seq, applied_at FROM ${a} ORDER BY seq DESC`).toArray().map(t=>n(t))}catch{return[]}},_=(s,t)=>{try{h(s);const[r]=e(s,`SELECT hash, seq, applied_at, snapshot_json FROM ${a} WHERE hash = ? LIMIT 1`,t).toArray();return r===void 0?void 0:{...n(r),snapshotJson:typeof r.snapshot_json=="string"?r.snapshot_json:""}}catch{return}};export{R as SCHEMA_HISTORY_MAX_VERSIONS,N as readSchemaHistory,_ as readSchemaVersion,L as recordSchemaVersion};
@@ -0,0 +1 @@
1
+ import{sql as i}from"drizzle-orm";import{runDrizzle as n}from"./runDrizzle-B6rnz3so.mjs";const o="__lunora_search_state",a=e=>{n(e,i`CREATE TABLE IF NOT EXISTS ${i.identifier(o)} (${i.identifier("companion")} TEXT PRIMARY KEY, ${i.identifier("cursor")} TEXT, ${i.identifier("done")} INTEGER NOT NULL DEFAULT 0, ${i.identifier("profile")} TEXT)`);try{n(e,i`ALTER TABLE ${i.identifier(o)} ADD COLUMN ${i.identifier("profile")} TEXT`)}catch{}},c=e=>e===1||e===!0||e==="1",l=(e,t)=>{const r=n(e,i`SELECT ${i.identifier("cursor")}, ${i.identifier("done")}, ${i.identifier("profile")} FROM ${i.identifier(o)} WHERE ${i.identifier("companion")} = ${t}`).toArray()[0];return r?{cursor:r.cursor??void 0,done:c(r.done),profile:r.profile??void 0}:{cursor:void 0,done:!1,profile:void 0}},s=(e,t,r,d,f)=>{const $=r??null;n(e,i`INSERT INTO ${i.identifier(o)} (${i.identifier("companion")}, ${i.identifier("cursor")}, ${i.identifier("done")}, ${i.identifier("profile")}) VALUES (${t}, ${$}, ${d?1:0}, ${f}) ON CONFLICT (${i.identifier("companion")}) DO UPDATE SET ${i.identifier("cursor")} = excluded.${i.identifier("cursor")}, ${i.identifier("done")} = excluded.${i.identifier("done")}, ${i.identifier("profile")} = excluded.${i.identifier("profile")}`)};export{o as SEARCH_STATE_TABLE,a as migrateSearchState,l as readSearchBackfillState,s as writeSearchBackfillState};
@@ -0,0 +1 @@
1
+ import{LunoraError as l}from"@lunora/errors";import{a as g}from"./wire-codec-Dsy70M3Q.mjs";const n=BigInt(Number.MAX_SAFE_INTEGER),i=(e,t)=>e<t?-1:e>t?1:0,s=(e,t)=>`${e}__agg_${t}`,c=e=>{if(typeof e=="bigint"){if(e>n||e<-n)throw new l("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},d=(e,t,o,u)=>{const r=e.get(t)??{count:0,value:null};if(o.op==="count"){r.count+=1,r.value=r.count,e.set(t,r);return}const a=c(u[o.field??""]);if(o.op==="sum"||o.op==="avg"){a!==void 0&&(r.value=(r.value??0)+a,r.count+=1),e.set(t,r);return}r.count+=1,a!==void 0&&(r.value===null?r.value=a:r.value=o.op==="min"?Math.min(r.value,a):Math.max(r.value,a)),e.set(t,r)},f=(e,t)=>e==="count"?t?.value??0:!t||t.count===0?null:e==="avg"?t.value===null?null:t.value/t.count:t.value,p=(e,t)=>{if(e.length===0)return"";const o={};for(const u of e.toSorted(i))o[u]=t[u]??null;return JSON.stringify(g(o))};export{s as aggregateTableName,c as coerceAggregateNumber,i as compareStrings,p as encodeAggregateKey,d as foldAggregateTally,f as readAggregateValue};
@@ -0,0 +1 @@
1
+ import{LunoraError as B}from"@lunora/errors";import{applySelect as A}from"./applySelect-UY-o13Ia.mjs";const C=s=>({relationBaseWhere:s.relationBaseWhere,relationMask:s.relationMask}),$=(s,o)=>o.select?A(s,o.select,o.with):s,E=async(s,o,t,a,r)=>{const u=await Promise.all(a.map(async i=>{const p=r?{AND:[{[t]:i},r]}:{[t]:i};return[i,await s(o,p)]}));return new Map(u)},R=(s,o)=>{const t=new Set;for(const a of s){const r=a[o];r!=null&&t.add(r)}return[...t]},S=async s=>{const{groupedCounter:o,fetcher:t,parents:a,relationBaseWhere:r,relationMask:u,schema:i,tableName:p,with:O}=s,M=(l,e)=>u?.(l,e)??e;if(a.length===0)return;const g=i.tables[p];if(!g)throw new B("INTERNAL",`unknown table: ${p}`);const N=g.relationMap??{},W=l=>{const e=N[l];if(!e)throw new B("INTERNAL",`unknown relation "${l}" on table "${p}"`);return e},k=async(l,e,n)=>{const d=R(a,e.field);if(d.length===0){for(const c of a)c[l]=null;return}const{page:b}=await t(e.table,{baseWhere:r?.(e.table),relationBaseWhere:r,relationMask:u,where:{[e.references]:{in:d}},with:n.with}),y=new Map;for(const c of M(e.table,b))y.set(c[e.references],c);for(const c of a){const w=y.get(c[e.field]);c[l]=w?$([w],n)[0]??null:null}},j=async(l,e,n)=>{const d=R(a,e.references);if(d.length===0){for(const f of a)f[l]=[];return}const b={[e.field]:{in:d}},y=n.where?{AND:[n.where,b]}:b,{page:c}=await t(e.table,{baseWhere:r?.(e.table),orderBy:n.orderBy,relationBaseWhere:r,relationMask:u,where:y,with:n.with}),w=new Map;for(const f of M(e.table,c)){const h=f[e.field],D=w.get(h);D?D.push(f):w.set(h,[f])}const m=typeof n.limit=="number"?Math.max(0,Math.floor(n.limit)):void 0;for(const f of a){const h=w.get(f[e.references])??[];f[l]=$(m===void 0?h:h.slice(0,m),n)}},v=async l=>{for(const e of Object.keys(l)){const n=W(e),[d,b]=n.kind==="many"?[n.field,n.references]:[n.references,n.field],y=r?.(n.table),c=R(a,b),w=c.length===0?new Map:await o(n.table,d,c,y);for(const m of a){const f=m._count??{},h=m[b];f[e]=h==null?0:w.get(h)??0,m._count=f}}};for(const[l,e]of Object.entries(O)){if(e===void 0||e===!1)continue;if(l==="_count"){await v(e);continue}const n=W(l),d=e===!0?{}:e;await(n.kind==="one"?k(l,n,d):j(l,n,d))}},I=async(s,o,t)=>{const{deletedId:a,deletedReference:r,findHolders:u,onCascade:i,onRestrict:p,onSetNull:O,tableName:M}=s,g=t.references==="_id"?a:r(t.references);if(g==null)return;const N=await u(o,t.field,g);if(N.length!==0){t.onDelete==="restrict"&&p(`cannot delete "${M}" row: "${o}.${t.field}" still references it`);for(const W of N){const k=W._id;typeof k=="string"&&await(t.onDelete==="cascade"?i(o,k):O(o,k,t.field))}}},T=async s=>{const{schema:o,tableName:t}=s;if(!o.tables[t])throw new B("INTERNAL",`unknown table: ${t}`);for(const[a,r]of Object.entries(o.tables)){const u=r.relationMap;if(u)for(const i of Object.values(u))i.kind!=="one"||i.table!==t||!i.onDelete||await I(s,a,i)}},V=(s,o,t=!1)=>{for(const[a,r]of Object.entries(s.shape))a in o&&typeof r.parse=="function"&&(t&&o[a]===null&&r.kind==="optional"||r.parse(o[a]))};export{T as applyOnDelete,R as distinctValues,E as fanOutScalarCounts,C as relationHooks,S as resolveWith,V as runRowValidators};
@@ -0,0 +1 @@
1
+ import{LunoraError as h}from"@lunora/errors";import{s as m,a as S}from"./wire-codec-Dsy70M3Q.mjs";const g="id",y=new Set(["_id","id"]),C=r=>{const e=[];for(const o of r??[])for(const[t,i]of Object.entries(o))e.push({direction:i,field:t});return e.length===0?[{direction:"asc",field:"_creationTime"}]:e},w=r=>{const e=new TextEncoder().encode(r);let o="";for(const t of e)o+=String.fromCodePoint(t);return btoa(o)},b=r=>{const e=atob(r),o=Uint8Array.from(e,t=>t.codePointAt(0)??0);return new TextDecoder().decode(o)},D=(r,e)=>{const o=e.map(t=>r[t.field]);return o.push(r._id),w(JSON.stringify(S(o)))},a=()=>new h("BAD_REQUEST","invalid cursor"),E=r=>{let e;try{e=m(JSON.parse(b(r)))}catch{throw a()}if(!Array.isArray(e))throw a();return e},f=(r,e,o)=>{const t=r.some(s=>y.has(s.field))?r:[...r,{direction:"asc",field:g}],i=[];for(const[s,n]of t.entries()){const c=[];for(const[u,p]of t.slice(0,s).entries())c.push({[p.field]:{eq:e[u]}});const l=o(n.direction,s===t.length-1);c.push({[n.field]:{[l]:e[s]}});const[d]=c;i.push(c.length===1&&d!==void 0?d:{AND:c})}return{OR:i}},T=(r,e)=>f(r,e,o=>o==="desc"?"lt":"gt"),v=(r,e)=>r==="desc"?e?"gte":"gt":e?"lte":"lt",k=(r,e)=>f(r,e,v),A=["_id","_creationTime"],B=(r,e,o)=>{if(!e)return r;const t=new Set([...e,...A,...o?Object.keys(o):[]]);return r.map(i=>{const s={};for(const n of t)n in i&&(s[n]=i[n]);return s})},N=(r,e)=>r&&e!==!0?{[r.field]:{isNull:!0}}:void 0,x=(r,e)=>e===void 0||r[e]===null||r[e]===void 0;export{B as applySelect,k as buildSeekBeforeWhere,T as buildSeekWhere,E as decodeCursor,D as encodeCursor,b as fromBase64,a as invalidCursor,x as isLiveForCompanion,C as normalizeOrderKeys,N as softDeleteScope,w as toBase64};
@@ -0,0 +1 @@
1
+ import{a as l}from"./wire-codec-Dsy70M3Q.mjs";const c="_id",p="__lunora__",b=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return;const r=e[c];return typeof r=="string"?r:void 0},y=e=>{const r=new Map,o=[];for(const s of e){const t=b(s);if(t===void 0||r.has(t))return;r.set(t,s),o.push(t)}return{byId:r,order:o}},g=(e,r)=>{const o=e.order.filter(t=>r.byId.has(t)),s=r.order.filter(t=>e.byId.has(t));return o.length!==s.length?!1:o.every((t,n)=>s[n]===t)},h=(e,r,o,s)=>{const t=[];for(const n of e.order)r.byId.has(n)||t.push({delta:{key:n,op:"delete",table:o},frame:`{"key":${JSON.stringify(n)},"op":"delete","table":${s}}`});return t},m=(e,r,o,s)=>{const t=[];for(const n of r.order){const a=r.byId.get(n),i=e.byId.get(n),f=JSON.stringify(l(a)),d=i===void 0?void 0:JSON.stringify(i);if(d===f)continue;const u=d===void 0?"insert":"update";t.push({delta:{key:n,op:u,row:a,table:o},frame:`{"key":${JSON.stringify(n)},"op":"${u}","row":${f},"table":${s}}`})}return t},S=(e,r,o,s)=>{let t;try{t=JSON.parse(e)}catch{return}if(!Array.isArray(t)||!Array.isArray(r))return;const n=y(t),a=y(r);if(n===void 0||a===void 0||!g(n,a))return;const i=o===""?p:o,f=JSON.stringify(i),d=[...h(n,a,i,f),...m(n,a,i,f)];if(!(d.length>a.order.length)){if(s!==void 0)for(const{frame:u}of d)s.push(u);return d.map(({delta:u})=>u)}},$=(e,r)=>{try{return e.send(r),!0}catch{return!1}},I=(e,r,o,s,t)=>{const n=JSON.stringify(r),a=t===void 0?"":`,"lastMutationId":${String(t)}`;let i=!0;for(const f of o)$(e,`{"type":"delta","id":${n},"delta":${f}${a}${s}}`)||(i=!1);return i},w=async e=>{let r=0;for(;r<100;){r+=1;const{bufferedAmount:o}=e;if(typeof o!="number"||o<1048576)return;await new Promise(s=>{setTimeout(s,20)})}};export{w as awaitWsDrain,I as sendDeltaFrames,S as subscriptionListDeltas,$ as trySendFrame};
@@ -0,0 +1 @@
1
+ import{B as R,W as x,x as k,T as S,l as O,y as M,c as w}from"./ctx-db-companions-BTi8DLUl.mjs";import"@lunora/errors";import{sql as r}from"drizzle-orm";import{matchesStaticWhere as A}from"./AGGREGATE_SQL_FUNCTION-CTo0-9iZ.mjs";import{encodeAggregateKey as L,foldAggregateTally as C,aggregateTableName as F}from"./aggregateTableName-DgYMC5tr.mjs";import{migrateSearchState as y,readSearchBackfillState as D,writeSearchBackfillState as N}from"./SEARCH_STATE_TABLE-BZ_fxI5l.mjs";import{runDrizzle as d}from"./runDrizzle-B6rnz3so.mjs";import{C as T,E as p,c as v,p as B,T as W,a as E,D as j}from"./do-sql-1Yi1_Yq0.mjs";import{isLiveForCompanion as _}from"./applySelect-UY-o13Ia.mjs";import{matchesRankStaticWhere as U,rankTableName as V}from"./RANK_TIEBREAK-DDtST3gN.mjs";const Y=(e,o)=>e.profile!==o?{cursor:void 0,finished:!1,wipe:e.cursor!==void 0||e.done}:{cursor:e.cursor,finished:e.done,wipe:!1},u=(e,o)=>d(e,r`SELECT COUNT(*) AS count FROM ${r.identifier(o)}`).one().count>0,I=(e,o)=>d(e,r`SELECT id, _creationTime, ${r.identifier(E)} FROM ${r.identifier(o)}`).toArray(),q=(e,o,n,i)=>{const t=F(o,n.name);if(u(e,t))return;const s=n.by??[],c=new Map,f=I(e,o);for(const l of f){const a=p(l);if(!a||!_(a,i)||n.where&&!A(a,n.where))continue;const $=L(s,a);C(c,$,n,a)}for(const[l,a]of c)d(e,r`INSERT INTO ${r.identifier(t)} (${v}, ${B}, ${W}) VALUES (${l}, ${a.value}, ${a.count})`)},re=(e,o)=>{for(const[n,i]of Object.entries(o.tables))if(!(i.shardMode?.kind==="global"||!i.aggregateIndexes))for(const t of i.aggregateIndexes)q(e,n,t,i.softDeleteMode?.field)},z=(e,o,n)=>{const i=V(o,n.name);if(u(e,i))return;const t=R(n),s=I(e,o);for(const c of s){const f=p(c);!f||n.where&&!U(f,n.where)||x(e,i,n,t,f._id,f)}},oe=(e,o)=>{for(const[n,i]of Object.entries(o.tables))if(!(i.shardMode?.kind==="global"||!i.rankIndexes))for(const t of i.rankIndexes)z(e,n,t)},g=500,b=(e,o,n)=>{const i=w(o,n.name),{profile:t}=k(n.language),s=Y(D(e,i),t);if(s.finished)return!0;s.wipe&&d(e,r`DELETE FROM ${r.identifier(i)}`);const{cursor:c}=s,f=d(e,c===void 0?r`SELECT id, _creationTime, ${r.identifier(E)} FROM ${r.identifier(o)} ORDER BY id ASC LIMIT ${r.raw(String(g))}`:r`SELECT id, _creationTime, ${r.identifier(E)} FROM ${r.identifier(o)} WHERE id > ${c} ORDER BY id ASC LIMIT ${r.raw(String(g))}`).toArray();let l=c;for(const $ of f){const{id:m}=$;if(typeof m!="string")continue;l=m,d(e,r`DELETE FROM ${r.identifier(i)} WHERE ${r.identifier(S)} = ${m}`);const h=j($);h&&d(e,r`INSERT INTO ${r.identifier(i)} (${r.identifier(O)}, ${r.identifier(S)}) VALUES (${M(h,n)}, ${m})`)}const a=f.length<g;return N(e,i,l,a,t),a},ne=(e,o,n)=>{if(T(e))for(const i of n.searchIndexes??[])i.staged||b(e,o,i)},te=(e,o)=>{if(T(e)){y(e);for(const[n,i]of Object.entries(o.tables))if(!(i.shardMode?.kind==="global"||!i.searchIndexes))for(const t of i.searchIndexes){let s=!1;for(;!s;)s=b(e,n,t)}}};export{re as backfillAggregateIndexes,oe as backfillRankIndexes,te as backfillSearchIndexes,ne as backfillSearchIndexesForTable};
@@ -0,0 +1 @@
1
+ const e=n=>{let r="";for(let t=0;t<n.length;t+=32768)r+=String.fromCharCode(...n.subarray(t,t+32768));return btoa(r)},a=n=>{const r=atob(n),t=new Uint8Array(r.length);for(let o=0;o<r.length;o+=1)t[o]=r.codePointAt(o)??0;return t};export{e as a,a as o};
@@ -0,0 +1 @@
1
+ const v=t=>{const o=new DataView(new ArrayBuffer(8));o.setFloat64(0,t,!1);let r=o.getUint32(0,!1),e=o.getUint32(4,!1);return(r&2147483648)===0?r=(r^2147483648)>>>0:(r=~r>>>0,e=~e>>>0),r.toString(16).padStart(8,"0")+e.toString(16).padStart(8,"0")},g=t=>{const o=new TextEncoder().encode(t);let r="";for(const e of o)r+=e.toString(16).padStart(2,"0");return r},c=t=>{if(t===null)return"0";if(typeof t=="number")return Number.isFinite(t)?`1${v(t===0?0:t)}`:void 0;if(typeof t=="string")return`2${g(t)}`},d=t=>{const o=[];for(const r of t){const e=c(r);if(e===void 0)return;o.push(e)}return o.join("!")};const p=new Set([">",">="]),x=new Set(["<","<="]),h=(t,o,r,e)=>{const i=o.comparator==="=",n=p.has(o.comparator)||x.has(o.comparator);return!i&&!n||t.indexOf(o.field)!==r?!1:e===void 0?!0:!i&&e===o.field},w=(t,o,r)=>{const e={equalities:[],lowerExclusive:!1,upperExclusive:!1};let i;for(const n of o){const s=n.comparator==="=",a=p.has(n.comparator);if(!h(t,n,e.equalities.length,i))return;if(s){e.equalities.push(r(n.value));continue}if(i=n.field,a){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},f=(t,o)=>{const r=c(o);if(r!==void 0)return t===""?r:t+"!"+r},y=(t,o,r,e,i)=>{if(r.length===0)return;const n=w(r,e,i);if(!n)return;const s=d(n.equalities);if(s===void 0)return;let a=s,l=s+"￿";if(n.lower!==void 0){const u=f(s,n.lower);if(u===void 0)return;a=n.lowerExclusive?u+"!￿":u}if(n.upper!==void 0){const u=f(s,n.upper);if(u===void 0)return;l=n.upperExclusive?u:u+"￿"}if(!(a>=l))return{hi:l,index:o,lo:a,table:t}},E=(t,o,r)=>{const e=[];for(const i of t){const n=d(i.fields.map(s=>r(o[s])));n!==void 0&&e.push({index:i.name,key:n})}return e},m=(t,o)=>t.index===o.index&&o.key>=t.lo&&o.key<t.hi,S=(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=>m(e,n))})};export{y as buildIndexRange,E as indexKeysForRow,S as keysTouchRanges,m as rangeContains};
@@ -1 +1 @@
1
- import{f as u}from"./wire-codec-Ctnni0h6.mjs";const l=(t,o)=>{if(!o)return t;const r=Object.create(null);for(const a of["_id","_creationTime",...o])Object.hasOwn(t,a)&&(r[a]=t[a]);return r},b=(t,o,r)=>{const{columns:a,table:i}=r,n=new Map,p=[];for(const{doc:e,id:s}of t){const c=l(e,a),d=JSON.stringify(u(c));n.set(s,d);const h=o.get(s);h===void 0?p.push({key:s,op:"insert",table:i,value:c}):h!==d&&p.push({key:s,op:"update",table:i,value:c})}for(const e of o.keys())n.has(e)||p.push({key:e,op:"delete",table:i});return{next:n,rowsPatch:p}},f=t=>t.map(o=>o.value===void 0?o:{...o,value:u(o.value)}),y=(t,o,r={})=>{const{baseCheckpoint:a,checkpoint:i,epoch:n,lastMutationId:p,pokeId:e}=o,s=[JSON.stringify({baseCheckpoint:a,epoch:n,pokeId:e,type:"pokeStart"})];for(const c of t){const d=r.preEncoded?c.rowsPatch:f(c.rowsPatch);s.push(JSON.stringify({pokeId:e,rowsPatch:d,shapeId:c.shapeId,type:"pokePart",...p===void 0?{}:{lastMutationId:p}}))}return s.push(JSON.stringify({checkpoint:i,epoch:n,pokeId:e,type:"pokeEnd"})),s};export{y as buildPokeFrames,b as diffGlobalMembership,f as encodeRowsPatch,l as projectColumns};
1
+ import{a as u}from"./wire-codec-Dsy70M3Q.mjs";const l=(t,o)=>{if(!o)return t;const r=Object.create(null);for(const a of["_id","_creationTime",...o])Object.hasOwn(t,a)&&(r[a]=t[a]);return r},b=(t,o,r)=>{const{columns:a,table:i}=r,n=new Map,p=[];for(const{doc:e,id:s}of t){const c=l(e,a),d=JSON.stringify(u(c));n.set(s,d);const h=o.get(s);h===void 0?p.push({key:s,op:"insert",table:i,value:c}):h!==d&&p.push({key:s,op:"update",table:i,value:c})}for(const e of o.keys())n.has(e)||p.push({key:e,op:"delete",table:i});return{next:n,rowsPatch:p}},f=t=>t.map(o=>o.value===void 0?o:{...o,value:u(o.value)}),y=(t,o,r={})=>{const{baseCheckpoint:a,checkpoint:i,epoch:n,lastMutationId:p,pokeId:e}=o,s=[JSON.stringify({baseCheckpoint:a,epoch:n,pokeId:e,type:"pokeStart"})];for(const c of t){const d=r.preEncoded?c.rowsPatch:f(c.rowsPatch);s.push(JSON.stringify({pokeId:e,rowsPatch:d,shapeId:c.shapeId,type:"pokePart",...p===void 0?{}:{lastMutationId:p}}))}return s.push(JSON.stringify({checkpoint:i,epoch:n,pokeId:e,type:"pokeEnd"})),s};export{y as buildPokeFrames,b as diffGlobalMembership,f as encodeRowsPatch,l as projectColumns};
@@ -0,0 +1 @@
1
+ import{L as u,a as l,j as m}from"./do-sql-1Yi1_Yq0.mjs";import{quoteIdentifier as a}from"./quoteIdentifier-CObIFRhb.mjs";import{reprojectionMigrationTable as j}from"./REPROJECTION_MIGRATION_PREFIX-D2dltRFC.mjs";import{REPROJECTION_MIGRATION_PREFIX as _,reprojectionMigrationId as x}from"./REPROJECTION_MIGRATION_PREFIX-D2dltRFC.mjs";import{a as b}from"./wire-codec-Dsy70M3Q.mjs";import{runSql as f}from"./runDrizzle-B6rnz3so.mjs";import{y as d}from"./sql-projection-jfoe331H.mjs";const E=b(0n)[0],$=r=>r.shardMode?.kind==="global"?[]:Object.entries(r.shape).filter(([,t])=>d(t)).map(([t])=>t),L=r=>Object.entries(r.tables).filter(([,t])=>$(t).length>0).map(([t])=>t),g=r=>{const t=r.map(()=>`(json_extract(${a(l)}, ?) = ? AND json_extract(${a(l)}, ?) IN (?, ?))`);return{params:r.flatMap(o=>[`$.${m(o)}[0]`,E,`$.${m(o)}[1]`,"bigint","bytes"]),sql:t.join(" OR ")}},S=(r,t,o)=>{if(o.length===0)return 0;const{params:e,sql:n}=g(o);return f(r,`SELECT COUNT(*) AS count FROM ${a(t)} WHERE ${n}`,...e).toArray()[0]?.count??0},R=(r,t,o,e)=>{const{params:n,sql:i}=g(o);return f(r,`SELECT 1 FROM ${a(t)} WHERE id = ? AND (${i}) LIMIT 1`,e,...n).toArray().length>0},A=(r,t,o)=>{const e=j(r);if(e===void 0)return;const n=t.tables[e];if(!n)return;const i=$(n);if(i.length!==0)return{id:r,table:e,up:s=>{const c=s._id;if(!(typeof c!="string"||!R(o,e,i,c))){try{u(s)}catch(p){console.warn(`${r}: skipping row ${c} — it cannot be re-projected: ${p instanceof Error?p.message:String(p)}`);return}return s}}}};export{_ as REPROJECTION_MIGRATION_PREFIX,A as buildReprojectionMigration,S as countLegacyRows,$ as reprojectableFields,x as reprojectionMigrationId,L as reprojectionTables};
@@ -0,0 +1 @@
1
+ const u=/key|secret|token|password|passwd|credential|private|auth|bearer|session|cookie|salt|signature|dsn|webhook/iu,c=new Set(["LUNORA_ADMIN_TOKEN","LUNORA_WS_BEARER"]),d=["CF_PAGES_URL","WORKER_URL","LUNORA_WORKER_URL"],l=["CF_ENV","ENVIRONMENT","WORKER_ENV","NODE_ENV"],p=n=>n.length<=4?"••••":`${n.slice(0,4)}${"•".repeat(Math.min(8,n.length-4))}`,f=n=>u.test(n),g=n=>{const e=t=>typeof n[t]=="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"},m=n=>{const e=i=>i.map(a=>n[a]).find(a=>typeof a=="string"&&a!==""),t={},o=e(d),s=e(l);o!==void 0&&(t.workerUrl=o),s!==void 0&&(t.environment=s);const r=n.CF_VERSION_METADATA;if(r!==null&&typeof r=="object"){const i=r;typeof i.id=="string"&&(t.deploymentId=i.id),typeof i.tag=="string"&&(t.versionTag=i.tag)}return t},v=/^(?:dev(?:elopment)?|local(?:host)?|test)$/iu,y=n=>{const e=n??{};for(const t of l){const o=e[t];if(typeof o=="string"&&v.test(o))return!0}return!1},E=n=>{const e=n??{},t=[];for(const[o,s]of Object.entries(e))if(!c.has(o)){if(typeof s=="string"){const r=f(o);t.push({kind:r?"secret":"var",name:o,value:p(s)});continue}if(typeof s=="number"||typeof s=="boolean"){t.push({kind:"var",name:o,value:String(s)});continue}if(s!==null&&typeof s=="object"){t.push({bindingType:g(s),kind:"binding",name:o,value:null});continue}t.push({kind:"var",name:o,value:null})}return t.sort((o,s)=>o.name.localeCompare(s.name)),{deploy:m(e),settings:t}};export{g as bindingType,E as buildSettings,y as isDevEnvironment,f as looksSecret,m as readDeployInfo,p as redact};
@@ -0,0 +1 @@
1
+ import{LunoraError as $}from"@lunora/errors";import{sql as s}from"drizzle-orm";import{RELATION_EXISTS_KEY as c}from"./RELATION_EXISTS_KEY-BaqSIFU1.mjs";const N=["eq","ne","lt","lte","gt","gte","in","notIn","isNull","contains"],h=new Set(N),p={eq:"=",gt:">",gte:">=",lt:"<",lte:"<=",ne:"<>"},I=r=>{if(r===null||typeof r!="object"||Array.isArray(r))return!1;const e=Object.keys(r);return e.length>0&&e.every(t=>h.has(t))},L=r=>typeof r=="string"?r.replaceAll(/[\\%_]/g,e=>`\\${e}`):r,g=(r,e,t)=>{const o=s`${t.serialize(L(e))}`;return t.likeContains?t.likeContains(r,o):s`${r} LIKE '%' || ${o} || '%' ESCAPE '\\'`},O=(r,e,t,o,n)=>o===null?e==="ne"?s`${r} IS NOT NULL`:s`${r} IS NULL`:s`${r} ${s.raw(t)} ${n.serialize(o)}`,S=(r,e,t,o)=>{const n=Array.isArray(t)?t:[];if(n.length===0)return e==="IN"?s`0 = 1`:s`1 = 1`;const i=s.join(n.map(l=>s`${o.serialize(l)}`),s`, `);return e==="IN"?s`${r} IN (${i})`:s`${r} NOT IN (${i})`},A=(r,e,t)=>{const o=e,n=[];for(const i of N){if(!(i in o))continue;const l=o[i],u=p[i];u?n.push(O(r,i,u,l,t)):i==="isNull"?n.push(l?s`${r} IS NULL`:s`${r} IS NOT NULL`):i==="contains"?n.push(g(r,l,t)):n.push(S(r,i==="in"?"IN":"NOT IN",l,t))}return n},y=(r,e,t)=>{const o=t.fieldRef(r);return I(e)?A(o,e,t):e===null?[s`${o} IS NULL`]:[s`${o} = ${t.serialize(e)}`]},f=(r,e)=>{if(r.length!==0)return r.length===1?r[0]:s.join(r.map(t=>s`(${t})`),s` ${s.raw(e)} `)},E=(r,e,t)=>{const o=Array.isArray(r)?r:[],n=[];for(const i of o){const l=a(i??{},t);l&&n.push(l)}return n.length===0?e==="OR"?s`0 = 1`:void 0:f(n,e)},m=new Set(["AND","NOT","OR",c]),T=(r,e,t)=>{if(r===c){if(!t.relationExists)throw new $("INTERNAL","encountered a relation EXISTS marker without a relationExists strategy hook");return t.relationExists(e)}if(r==="NOT"){const o=a(e??{},t);return o?s`NOT (${o})`:void 0}return E(e,r,t)},a=(r,e)=>{const t=[];for(const[o,n]of Object.entries(r))if(m.has(o)){const i=T(o,n,e);i&&t.push(i)}else t.push(...y(o,n,e));return f(t,"AND")},R=(r,e)=>{if(!(!r||Object.keys(r).length===0))return a(r,e)};export{R as compileWhereSql};
@@ -0,0 +1 @@
1
+ import{LunoraError as A}from"@lunora/errors";import{sql as t}from"drizzle-orm";import{mergeWhere as x}from"./CountRlsUnsupportedError-8BqPYQoP.mjs";import{SCAN_DEP as O}from"./SCAN_DEP-D_yR9EeV.mjs";import{runDrizzle as B}from"./runDrizzle-B6rnz3so.mjs";import{param as q}from"./param-B5lF5Jd9.mjs";import{decodeCursor as W,toBase64 as z}from"./applySelect-UY-o13Ia.mjs";import{sortColumnName as F,resolveRankPartition as H,RANK_TIEBREAK as m,encodePartitionKey as J,rankTableName as V}from"./RANK_TIEBREAK-DDtST3gN.mjs";const Y="__doc__",G=n=>z(JSON.stringify(n)),X=n=>n.after?[n.after.partitionKey,...n.after.sortValues,n.after.rowId]:n.cursor?W(n.cursor):void 0,Z=(n,o,c)=>{if(n?.length!==1+o.length+1)return;const i=[{column:"__partition__",direction:"asc"}];for(const[a,f]of o.entries())i.push({column:f,direction:c[a]?.direction??"asc"});i.push({column:m,direction:"asc"});const s=[];for(const[a,f]of i.entries()){const e=[];for(const[r,$]of i.slice(0,a).entries())e.push(t`${t.identifier($.column)} IS ${n[r]}`);e.push(t`${t.identifier(f.column)} ${t.raw(f.direction==="desc"?"<":">")} ${n[a]}`);const[d]=e;s.push(e.length===1&&d!==void 0?d:t`(${t.join(e,t` AND `)})`)}return t`(${t.join(s,t` OR `)})`},C=null,Q=(n,o)=>{if(n===void 0)return C;const c=[n.__partition__,...o.map(i=>n[i]),n[m]];return G(c)},U=(n,o,c)=>{const i=[];for(const s of n){const a=s[m];if(typeof a!="string")continue;const f=o.get(a);if(!f)continue;const e=typeof s.__partition__=="string"?s.__partition__:"",d=c.map(r=>s[r]??null);i.push({doc:f,key:{partitionKey:e,rowId:a,sortValues:d}})}return i},tt=(n,o,c)=>{const{rowToDocument:i}=n,s=new Map;if(c.length===0)return s;const a=t.join(c.map(e=>q(e)),t`, `),f=B(n.sql,t`SELECT id, _creationTime, ${t.identifier(Y)} FROM ${t.identifier(o)} WHERE id IN (${a})`).toArray();for(const e of f){const d=i(e),r=e.id;d&&typeof r=="string"&&s.set(r,d)}return s},ft=(n,o,c,i)=>{const{assertRankPartitionLocal:s,ensureRankBackfilled:a,onRead:f,schema:e}=n,d=e.tables[o];if(!d)throw new A("INTERNAL",`unknown table: ${o}`);const r=d.rankIndexes?.find(p=>p.name===c);if(!r)throw new A("INTERNAL",`unknown rankIndex "${c}" on table "${o}"`);s(o,d,r),f(o,O),a(o,r);const $=V(o,r.name),u=r.sortBy.map((p,w)=>F(w)),l=Math.max(1,Math.min(1e3,Math.floor(i.take??100))),S=x(i.baseWhere,i.where),R=H(r,S),h=[t`${t.identifier("__partition__")} ASC`];for(const[p,w]of u.entries()){const v=r.sortBy[p]?.direction;h.push(t`${t.identifier(w)} ${t.raw(v==="desc"?"DESC":"ASC")}`)}h.push(t`${t.identifier(m)} ASC`);const _=[];typeof i.partitionKey=="string"?_.push(t`${t.identifier("__partition__")} = ${i.partitionKey}`):R&&_.push(t`${t.identifier("__partition__")} = ${J(r.partitionBy??[],R)}`);const T=X(i),k=Z(T,u,r.sortBy);k&&_.push(k);const I=t.identifier(m),N=t.identifier("__partition__"),M=_.length>0?t` WHERE ${t.join(_,t` AND `)}`:t``,D=u.length>0?t`${I}, ${N}, ${t.join(u.map(p=>t.identifier(p)),t`, `)}`:t`${I}, ${N}`,K=t`SELECT ${D} FROM ${t.identifier($)}${M} ORDER BY ${t.join(h,t`, `)} LIMIT ${t.raw(String(l+1))}`,y=B(n.sql,K).toArray(),g=y.length>l,E=g?y.slice(0,l):y,L=E.map(p=>p[m]),b=U(E,tt(n,o,L),u),j=g?Q(E.at(-1),u):C,P=r.sortBy.map(p=>p.direction==="desc"?"desc":"asc");return{continueCursor:j,directions:P,hasMore:g,rows:b}};export{ft as computeRankPage,tt as hydrateDocsById};
@@ -0,0 +1 @@
1
+ import{w as C,W as R,B as S}from"./ctx-db-companions-BTi8DLUl.mjs";import"@lunora/errors";import"drizzle-orm";import"./AGGREGATE_SQL_FUNCTION-CTo0-9iZ.mjs";import"./aggregateTableName-DgYMC5tr.mjs";import"./runDrizzle-B6rnz3so.mjs";import"./do-sql-1Yi1_Yq0.mjs";import"./param-B5lF5Jd9.mjs";import"./GEO_DEFAULT_PRECISION-DyI5zggj.mjs";import"./applySelect-UY-o13Ia.mjs";import"./RANK_TIEBREAK-DDtST3gN.mjs";import"./sql-projection-jfoe331H.mjs";import"./serializeSqlValue-BR4UOWoP.mjs";export{C as createCompanionSync,R as insertRankRow,S as rankColumnsSql};
@@ -0,0 +1 @@
1
+ const d=()=>{const a=new Set,t=new Map,n=new Set;return{onRead(e){a.add(e),n.add(e)},onReadRange(e){a.add(e.table);const o=t.get(e.table);o?o.push(e):t.set(e.table,[e])},ranges(){for(const e of n)t.delete(e);return t.size>0?t:void 0},tables:a}};export{d as createReadFootprint};
@@ -0,0 +1,7 @@
1
+ import{f as S,g,u as f,l as q,s as w,o as _}from"./sibling-channel-bg9FBL5s.mjs";const A=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"],N=new Set(A),T=t=>typeof t=="string"&&N.has(t),u="::replica::",v=t=>{const e=t.lastIndexOf(u);if(e===-1)return;const s=t.slice(0,e),r=t.slice(e+u.length);if(!(s.length===0||!T(r)))return{ownerKey:s,region:r}},L=t=>{if(t==null||!/^\d+$/.test(t))return;const e=Number.parseInt(t,10);return Number.isSafeInteger(e)&&e>0?e:void 0},O=1e3,y=1e3,C=10,m=5e4,b=t=>f(t,"LUNORA_REPLICA_MAX_BOOTSTRAP_ROWS",m),h="__replica_state",l=new WeakSet,E=t=>{l.has(t)||(t.exec(`CREATE TABLE IF NOT EXISTS ${h} (
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
+ )`),l.add(t))},c=t=>(E(t),t.exec(`SELECT epoch, applied_seq AS appliedSeq, synced_at AS syncedAtMs FROM ${h} WHERE id = 1`).toArray()[0]),d=(t,e)=>{E(t),t.exec(`INSERT INTO ${h} (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)},F=t=>{const e=t.doName();if(e!==void 0&&v(e)!==void 0)return new Response("replica cannot serve replicas",{status:409});if(t.ownerEpoch()===void 0)return new Response("shard has no changelog to replicate",{status:409});if(w(t.env())===void 0)return new Response("replica control requires LUNORA_RELAY_SECRET",{status:403})},U=async(t,e)=>{const s=F(t);if(s!==void 0)return s;const r=t.ownerEpoch();let i;try{i=await e.text()}catch{return new Response("bad request",{status:400})}if(!await S(t.env(),e.headers.get(g),i))return new Response("forbidden",{status:403});let n;try{n=JSON.parse(i)}catch{return new Response("bad request",{status:400})}if(n.type==="replica_bootstrap"){if(t.rowCount()>b(t.env()))return Response.json({cursor:0,epoch:r,rows:[],truncated:!0});const a=t.ownerCursor()??0,o=await t.exportRows();return Response.json({cursor:a,epoch:r,rows:o})}if(n.type==="replica_pull"){const a=typeof n.sinceSeq=="number"&&Number.isInteger(n.sinceSeq)&&n.sinceSeq>=0?n.sinceSeq:0,{changes:o,cursor:R}=t.readChanges(a,y),p=t.ownerFloor();return Response.json({changes:o,cursor:R,epoch:r,...p===void 0?{}:{floor:p}})}return new Response("unknown replica frame",{status:400})};class I{constructor(e,s,r){this.host=e,this.ownerKey=s,this.region=r}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 s=await this.inFlight;return s==="fresh"&&!this.isCaughtUp(e)?"stale":s}appliedSeq(){return c(this.host.sql())?.appliedSeq??0}isDivergent(){return this.divergent}async advance(e){let s=c(this.host.sql());if(s===void 0){const r=await this.bootstrap();if(r===void 0)return"unavailable";s=r}return this.catchUp(s,e)}isCaughtUp(e){const s=c(this.host.sql());return s!==void 0&&this.isFreshEnough(s,e)}async catchUp(e,s){let r=e;for(let i=0;i<C;i+=1){const n=await this.pull(r.appliedSeq);if(n===void 0)return s===void 0&&this.isFreshEnough(r,void 0)?"fresh":"unavailable";if(this.hasDiverged(r,n))return"unavailable";const a=n.changes.length<y;if(r=await this.applyPage(n),a||this.isFreshEnough(r,s))return this.isFreshEnough(r,s)?"fresh":"stale"}return this.isFreshEnough(r,s)?"fresh":"stale"}async applyPage(e){e.changes.length>0&&await this.host.applyChanges(e.changes);const s={appliedSeq:e.cursor,epoch:e.epoch,syncedAtMs:Date.now()};return d(this.host.sql(),s),s}hasDiverged(e,s){const r=s.changes.length===0&&s.cursor>e.appliedSeq,i=s.floor??(r?s.cursor:0),n=i>0&&i>e.appliedSeq+1;return s.epoch===e.epoch&&!n?!1:(this.divergent=!0,!0)}async bootstrap(){const e=await this.request({type:"replica_bootstrap"});if(e===void 0)return;const s=await e.json();if(s.truncated===!0){this.divergent=!0;return}const{errors:r}=await this.host.importRows(s.rows);if(r.length>0){this.divergent=!0;return}const i={appliedSeq:s.cursor,epoch:s.epoch,syncedAtMs:Date.now()};return d(this.host.sql(),i),i}isFreshEnough(e,s){return s!==void 0?e.appliedSeq>=s:Date.now()-e.syncedAtMs<=f(this.host.env(),"LUNORA_REPLICA_MAX_STALENESS_MS",O)}async pull(e){const s=await this.request({sinceSeq:e,type:"replica_pull"});return s===void 0?void 0:await s.json()}async request(e){const s=this.host.shardBinding(),r=q(this.host.env(),s,this.ownerKey);if(r===void 0)return;const i=JSON.stringify(e),n={"content-type":"application/json","x-lunora-shard-binding":s??""},a=w(this.host.env());a!==void 0&&(n[g]=await _(a,i));try{const o=await r.fetch("https://replica.internal/_lunora/replica",{body:i,headers:n,method:"POST"});return o.ok?o:void 0}catch{return}}}const $=t=>{const e=t.doName();if(e===void 0)return;const s=v(e);return s===void 0?void 0:new I(t,s.ownerKey,s.region)},D=async(t,e,s)=>{if(e.headers.get("x-lunora-replica-read")!=="1")return Response.json({error:{code:"REPLICA_READ_ONLY",message:`"${s}" is a write and cannot run on a read replica`}},{status:421});const r=await t.ensureFresh(L(e.headers.get("x-lunora-min-seq")));if(r!=="fresh")return Response.json({error:{code:"REPLICA_NOT_READY",message:`replica is ${r} for this read`}},{headers:{"x-lunora-replica-fallback":r},status:421})};export{$ as createReplicaLink,D as gateReplicaDispatch,U as handleReplicaControl};
@@ -0,0 +1 @@
1
+ import"@lunora/errors";import{sql as e}from"drizzle-orm";import{matchesStaticWhere as V,aggregateSqlFunction as de}from"./AGGREGATE_SQL_FUNCTION-CTo0-9iZ.mjs";import{encodeAggregateKey as O,foldAggregateTally as G,coerceAggregateNumber as I,aggregateTableName as P}from"./aggregateTableName-DgYMC5tr.mjs";import{runDrizzle as $}from"./runDrizzle-B6rnz3so.mjs";import{C as ce,a as M,E as k,c as x,p as v,T as y,h as fe,A as C,N as D}from"./do-sql-1Yi1_Yq0.mjs";import{param as $e}from"./param-B5lF5Jd9.mjs";import{encodeGeohash as ue,GEO_DEFAULT_PRECISION as me}from"./GEO_DEFAULT_PRECISION-DyI5zggj.mjs";import{isLiveForCompanion as J}from"./applySelect-UY-o13Ia.mjs";import{encodePartitionKey as Ee,sortColumnName as he,matchesRankStaticWhere as Y,rankTableName as Z}from"./RANK_TIEBREAK-DDtST3gN.mjs";import{y as pe}from"./sql-projection-jfoe331H.mjs";import{serializeSqlValue as ee}from"./serializeSqlValue-BR4UOWoP.mjs";const ge=["de","en","es","fr","it","nl","none","pt"],ye=o=>ge.includes(o),_e="a an and are as at be but by for if in into is it no not of on or such that the their then there these they this to was will with",be="aber als am an auch auf aus bei bin bis bist da dass der den des dem die das denn dir du ein eine für hat ich im in ist mit nicht noch nur oder sich sie sind über und von vor war wie wir zu zum zur",ve="a al como con de del el en es la las lo los mas no o para pero por que se su sus un una uno y ya",we="au aux avec ce ces dans de des du elle en et eux il je la le les leur lui ma mais me même mes moi mon ne nos notre nous on ou par pas pour qu que qui sa se ses son sur ta te tes toi ton tu un une vos votre vous y",Te="a ai al alla anche che chi ci coi col come con da dal degli dei del della di do e ed gli ha hai hanno i il in la le lo ma mi ne nei nel non o per più quale quanto se si sono su sul tra un una uno vi",Se="aan al als bij dan dat de der deze die dit door een en er het hij ij in is je kan me men met mij na naar niet nog nu of om ons ook op over te tot uit van voor was wat we wij zij zijn zo",Ae="a ao aos as até com como da das de do dos e em entre era essa esse esta este eu foi há isso já mais mas me mesmo meu na nas no nos num numa o os ou para pela pelo por qual que quem se sem seu só sua também te tem um uma você",Re=/[\u0300-\u036F]/gu,ne=o=>o.normalize("NFD").replaceAll(Re,"").normalize("NFC").toLowerCase(),j=o=>new Set(ne(o).split(" ")),Le={de:j(be),en:j(_e),es:j(ve),fr:j(we),it:j(Te),nl:j(Se),none:new Set,pt:j(Ae)},Ne=2,Oe=256,X=new Map,je=o=>{const a=o!==void 0&&ye(o)?o:"none",l=X.get(a);if(l)return l;const g=Le[a],S=r=>{const A=(ne(r).match(/[\p{L}\p{N}]+/gu)??[]).filter(w=>w.length<=Oe);return g.size===0?A:A.filter(w=>!g.has(w))},m={document:S,profile:`${a}-v${String(Ne)}`,query:r=>{const A=S(r);return A.filter((w,L)=>A.lastIndexOf(w)===L)}};return X.set(a,m),m},xe=(o,a)=>{if(!a.includes("."))return o[a];let l=o;for(const g of a.split(".")){if(l===null||typeof l!="object"||Array.isArray(l))return;l=l[g]}return l},Fe=(o,a)=>`${o}__fts_${a}`,Ie="__text__",Q="__id__",Ce=1e3,Me=(o,a)=>a.document(o),q=(o,a)=>xe(o,a),ke=o=>typeof o=="string"?o:o==null?"":typeof o=="number"||typeof o=="bigint"||typeof o=="boolean"?String(o):JSON.stringify(o)??"",De=(o,a,l)=>o!==void 0&&a!==void 0&&q(o,l.field)===q(a,l.field),qe=(o,a)=>Me(ke(q(o,a.field)),je(a.language)).slice(0,Ce).join(" "),ze=(o,a,l)=>[...o.partitionBy??[],...o.sortBy.map(g=>g.field),...o.where?Object.keys(o.where):[]].every(g=>a[g]===l[g]),oe=o=>e.join(["__id__","__partition__",...o.sortBy.map((a,l)=>he(l))].map(a=>e.identifier(a)),e`, `),ie=(o,a,l,g,S,m)=>{const r=Ee(l.partitionBy??[],m),A=l.sortBy.map(L=>ee(m[L.field]??null)),w=e.join([S,r,...A].map(L=>$e(L)),e`, `);$(o,e`INSERT INTO ${e.identifier(a)} (${g}) VALUES (${w})`)},We=(o,a,l,g,S,m)=>{if(S&&m&&ze(l,S,m))return;const r=Z(a,l.name);S&&$(o,e`DELETE FROM ${e.identifier(r)} WHERE ${e.identifier("__id__")} = ${g}`),!(!m||l.where&&!Y(m,l.where))&&ie(o,r,l,oe(l),g,m)},en=o=>{const{broadcast:a,indexKeysFor:l,invalidateCache:g,recordCdc:S,schema:m,sql:r}=o,A=new Set,w=i=>m.tables[i]?.softDeleteMode?.field,L=new Set,z=(i,n)=>{const s=`${i}::${n.name}`;if(A.has(s))return;const d=P(i,n.name),c=n.by??[],f=w(i),h=new Map,_=$(r,e`SELECT id, _creationTime, ${e.identifier(M)} FROM ${e.identifier(i)}`).toArray();for(const T of _){const u=k(T);if(!u||!J(u,f)||n.where&&!V(u,n.where))continue;const E=O(c,u);G(h,E,n,u)}$(r,e`DELETE FROM ${e.identifier(d)}`);const R=32,N=[...h];for(let T=0;T<N.length;T+=R){const u=N.slice(T,T+R),E=e.join(u.map(([t,p])=>e`(${t}, ${p.value}, ${p.count})`),e`, `);$(r,e`INSERT INTO ${e.identifier(d)} (${x}, ${v}, ${y}) VALUES ${E}`)}A.add(s)},te=(i,n,s)=>{const d=n.by??[],c=n.field??"",f=[],h=(E,t)=>{const p=ee(t);p===null?f.push(e`${D(E)} IS NULL`):f.push(e`${D(E)} = ${p}`)};for(const E of d)h(E,s[E]??null);const _=w(i);_!==void 0&&h(_,null);for(const[E,t]of Object.entries(n.where??{}))h(E,t!==null&&typeof t=="object"&&!Array.isArray(t)?t.eq:t);const R=f.length>0?e` WHERE ${e.join(f,e` AND `)}`:e``,N=m.tables[i]?.shape[c];if(N&&pe(N)){const E=$(r,e`SELECT id, _creationTime, ${e.identifier(M)} FROM ${e.identifier(i)}${R}`).toArray(),t=new Map;for(const p of E){const b=k(p);b&&G(t,"",n,b)}return{value:t.get("")?.value??null}}const T=de(n.op),u=D(c);return{value:$(r,e`SELECT ${e.raw(T)}(${u}) AS value FROM ${e.identifier(i)}${R}`).one().value??null}},re=(i,n,s,d)=>{const c=P(i,n.name),{op:f}=n,h=n.field??"",_=t=>{$(r,e`DELETE FROM ${e.identifier(c)} WHERE ${x} = ${t} AND ${y} <= 0`)},R=w(i),N=t=>!n.where||V(t,n.where),T=t=>J(t,R)&&N(t);d!==void 0&&f!=="count"&&N(d)&&I(d[h]);const u=s&&T(s)?s:void 0,E=d&&T(d)?d:void 0;if(!(!u&&!E)){if(f==="count"){for(const[t,p]of[[u,-1],[E,1]]){if(!t)continue;const b=O(n.by??[],t);$(r,C(c,b,p,p,e`${v} = ${v} + excluded.${v}, ${y} = ${y} + excluded.${y}`))}u&&_(O(n.by??[],u));return}if(f==="sum"||f==="avg"){for(const[t,p]of[[u,-1],[E,1]]){if(!t)continue;const b=I(t[h]);if(b===void 0)continue;const F=O(n.by??[],t);$(r,C(c,F,p*b,p,e`${v} = COALESCE(${v}, 0) + excluded.${v}, ${y} = ${y} + excluded.${y}`))}u&&_(O(n.by??[],u));return}if(u){const t=O(n.by??[],u),p=I(u[h]),b=$(r,e`SELECT ${v} AS value, ${y} AS count FROM ${e.identifier(c)} WHERE ${x} = ${t}`).toArray()[0],F=(b?.count??0)-1;if(F<=0)$(r,e`DELETE FROM ${e.identifier(c)} WHERE ${x} = ${t}`);else if(b&&p!==void 0&&b.value!==null&&p===b.value){const le=te(i,n,u);$(r,e`UPDATE ${e.identifier(c)} SET ${v} = ${le.value}, ${y} = ${F} WHERE ${x} = ${t}`)}else $(r,e`UPDATE ${e.identifier(c)} SET ${y} = ${y} - 1 WHERE ${x} = ${t}`)}if(E){const t=O(n.by??[],E),p=I(E[h]);if(p===void 0)$(r,C(c,t,null,1,e`${y} = ${y} + 1`));else{const b=f==="min"?"MIN":"MAX";$(r,C(c,t,p,1,e`${v} = ${e.raw(b)}(COALESCE(${v}, excluded.${v}), excluded.${v}), ${y} = ${y} + 1`))}}}},ae=i=>{for(const n of m.tables[i]?.aggregateIndexes??[])z(i,n)},W=(i,n,s)=>{for(const d of m.tables[i]?.aggregateIndexes??[])re(i,d,n,s)},B=(i,n)=>{const s=`${i}::rank::${n.name}`;if(L.has(s))return;const d=Z(i,n.name),c=$(r,e`SELECT id, _creationTime, ${e.identifier(M)} FROM ${e.identifier(i)}`).toArray();$(r,e`DELETE FROM ${e.identifier(d)}`);const f=oe(n);for(const h of c){const _=k(h);!_||n.where&&!Y(_,n.where)||ie(r,d,n,f,_._id,_)}L.add(s)},se=i=>{for(const n of m.tables[i]?.rankIndexes??[])B(i,n)},H=(i,n,s,d)=>{for(const c of m.tables[i]?.rankIndexes??[])We(r,i,c,n,s,d)},U=(i,n,s,d)=>{const c=m.tables[i]?.searchIndexes??[];if(!(c.length===0||!ce(r)))for(const f of c){if(De(d,s,f))continue;const h=Fe(i,f.name);$(r,e`DELETE FROM ${e.identifier(h)} WHERE ${e.identifier(Q)} = ${n}`),s&&$(r,e`INSERT INTO ${e.identifier(h)} (${e.identifier(Ie)}, ${e.identifier(Q)}) VALUES (${qe(s,f)}, ${n})`)}},K=(i,n,s)=>{for(const d of m.tables[i]?.geoIndexes??[]){const c=fe(i,d.name);$(r,e`DELETE FROM ${e.identifier(c)} WHERE ${e.identifier("__id__")} = ${n}`);const f=s?.[d.field];if(f!==null&&typeof f=="object"&&typeof f.lat=="number"&&typeof f.lng=="number"){const{lat:h,lng:_}=f,R=ue({lat:h,lng:_},d.precision??me);$(r,e`INSERT INTO ${e.identifier(c)} (${e.identifier("__id__")}, ${e.identifier("__geohash__")}, ${e.identifier("__lat__")}, ${e.identifier("__lng__")}) VALUES (${n}, ${R}, ${h}, ${_})`)}}};return{ensureBackfilledForTable:ae,ensureBackfilledIndex:z,ensureRankBackfilled:B,ensureRankBackfilledForTable:se,syncAggregates:W,syncCompanionsForInsert:(i,n,s)=>{U(i,n,s),K(i,n,s),W(i,void 0,s),H(i,n,void 0,s),g(i,n,s),S(i,n,"insert",s),a({indexKeys:l(i,s),key:n,op:"insert",row:s,table:i})},syncGeo:K,syncRanks:H,syncSearch:U}};export{oe as B,Q as T,ie as W,Fe as c,Ie as l,Me as n,en as w,je as x,qe as y};
@@ -1 +1 @@
1
- import{createShardCtxDb as b}from"./NotUniqueError-Bw1Oh2FL.mjs";import{createRelayLink as I}from"./DEFAULT_MAX_RELAYS-CnCyh6oX.mjs";import{ConflictError as N}from"./ConflictError-C8GtJmjS.mjs";import{runShardMigrations as v}from"./runShardMigrations-CPxqCh3O.mjs";import{relayName as q}from"./DEFAULT_PROMOTION_THRESHOLDS-Dteg0sZF.mjs";const C=(_,m={})=>({_meta:{column:{notNull:!0,...m}},kind:_}),D=(_,m,E)=>{const{describe:k,expect:i,it:f}=E;k(`engine contract: ${_}`,()=>{k("optimistic concurrency",()=>{const g=p=>({tables:{items:{indexes:[],shape:{title:C("string"),version:C("number",{notNull:!1})},triggerMap:{clobber:{handler:()=>{p.exec(`UPDATE "items" SET "__doc__" = json_set("__doc__", '$.version', 99) WHERE "id" = 'i1'`)},op:"update",timing:"before"}}}}});f("raises a CONFLICT of kind `occ` when a write's snapshot is clobbered",async()=>{const{close:p,host:d}=m();try{const c=d.sql,l=g(c);v(c,l);const s=b({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0}),await i(s.patch("i1",{title:"second"})).rejects.toBeInstanceOf(N)}finally{p?.()}}),f("reports the conflict as CONFLICT/409 rather than retrying it away",async()=>{const{close:p,host:d}=m();try{const c=d.sql,l=g(c);v(c,l);const s=b({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let r;try{await s.patch("i1",{title:"second"})}catch(t){r=t}const e=r;i(e.code).toBe("CONFLICT"),i(e.kind).toBe("occ")}finally{p?.()}}),f("leaves the row readable and unchanged after a conflict",async()=>{const{close:p,host:d}=m();try{const c=d.sql,l=g(c);v(c,l);const s=b({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});try{await s.patch("i1",{title:"second"})}catch{}const r=await s.get("i1");i(r?.title).toBe("first"),i(r?.version).toBe(99)}finally{p?.()}}),f("raises a CONFLICT of kind `trigger` when a trigger writes its own row through the db",async()=>{const{close:p,host:d}=m();try{const c=d.sql,l={tables:{items:{indexes:[],shape:{title:C("string"),version:C("number",{notNull:!1})},triggerMap:{recurse:{handler:async(t,o)=>{await t.db.patch(o.doc._id,{version:99})},op:"update",timing:"before"}}}}};v(c,l);const s=b({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let r;try{await s.patch("i1",{title:"second"})}catch(t){r=t}const e=r;i(e).toBeInstanceOf(N),i(e.code).toBe("CONFLICT"),i(e.kind).toBe("trigger")}finally{p?.()}})}),k("shape-poke ordering",()=>{const g="shard-a",p={args:{},name:"messages"},d=(e,t,o,a)=>e.accept(t?.()??{},{connectionId:o,shapes:{[a]:p}}),c=(e,t)=>{let o=0,a=0;const n=u=>()=>{throw new Error(`the relay poke path must not reach RelayHost.${u}`)},h={fetch:(u,O)=>{if(JSON.parse(O?.body??"{}").type!=="relay_shape_subscribe")return Promise.resolve(new Response(void 0,{status:204}));const B=t[a];if(a+=1,B===void 0)throw new Error("the relay asked for more seeds than this fixture supplies");return Promise.resolve(Response.json(B))}},y={get:()=>h,getByName:()=>h,idFromName:u=>u},w={buildShapeDiff:n("buildShapeDiff"),computeOpLogShapeSeed:n("computeOpLogShapeSeed"),currentCdcEpoch:n("currentCdcEpoch"),deliverWhisperLocal:n("deliverWhisperLocal"),doName:()=>q(g,0),env:()=>({SHARD:y}),getWebSockets:()=>e.getSockets(),maskMetadata:n("maskMetadata"),nextPokeId:()=>(o+=1,`poke-${String(o)}`),readAttachment:u=>u.deserializeAttachment?.(),recordShapePokeFanout:()=>{},resolveShape:n("resolveShape"),rlsMetadata:n("rlsMetadata"),shardBinding:()=>"SHARD",sql:n("sql")},S=I(w);if(S===void 0)throw new Error("expected a relay link for a `…::relay::N` name");return S},l=e=>new Request("https://relay.internal/_lunora/relay",{body:JSON.stringify(e),headers:{"content-type":"application/json"},method:"POST"}),s=async(e,t,o)=>{const a=await e.seedRelayShape(t,o,p,{identity:void 0,userId:void 0});if(a!=="ok")throw new Error(`seed failed: ${JSON.stringify(a)}`)},r=(e={})=>l({...p,checkpoint:20,epoch:"e1",fromCursor:10,rowsPatch:[{id:"r1",op:"upsert",value:{title:"hello"}}],type:"relay_shape_poke",...e});f("frames a poke as pokeStart → pokePart per shape → pokeEnd, under one poke id",async()=>{const{close:e,createSocket:t,readFrames:o,sockets:a}=m();try{const n=c(a,[{cursor:10,epoch:"e1",frames:[]}]),h=d(a,t,"c-alice","s1");await s(n,h,"s1"),await n.handleControl(r());const y=(await o(h)).map(w=>JSON.parse(w));i(y.map(w=>w.type)).toStrictEqual(["pokeStart","pokePart","pokeEnd"]),i(new Set(y.map(w=>w.pokeId)).size).toBe(1),i(y[1]?.shapeId).toBe("s1"),i(y[2]?.checkpoint).toBe(20)}finally{e?.()}}),f("delivers a poke only to sockets whose cursor matches, and advances them past it",async()=>{const{close:e,createSocket:t,readFrames:o,sockets:a}=m();try{const n=c(a,[{cursor:10,epoch:"e1",frames:[]},{cursor:7,epoch:"e1",frames:[]}]),h=d(a,t,"c-alice","s1"),y=d(a,t,"c-bob","s2");await s(n,h,"s1"),await s(n,y,"s2"),await n.handleControl(r());const w=await o(h);i(w.length).toBe(3);const S=await o(y);i(S.length).toBe(0),await n.handleControl(r());const u=await o(h);i(u.length).toBe(3)}finally{e?.()}}),f("skips a socket whose cursor matches under a different CDC epoch",async()=>{const{close:e,createSocket:t,readFrames:o,sockets:a}=m();try{const n=c(a,[{cursor:10,epoch:"e1",frames:[]}]),h=d(a,t,"c-alice","s1");await s(n,h,"s1"),await n.handleControl(r({epoch:"e2"}));const y=await o(h);i(y.length).toBe(0),await n.handleControl(r());const w=await o(h);i(w.length).toBe(3)}finally{e?.()}})}),k("RLS identity under live subscription",()=>{const g="shard-a",p={args:{},name:"lobby-messages"},d={args:{},name:"my-orders"},c=s=>{const r=[],e=[],t={fetch:(a,n)=>(r.push(JSON.parse(n?.body??"{}")),Promise.resolve(new Response(void 0,{status:204})))},o=I({buildShapeDiff:()=>[{id:"r1",op:"upsert",value:{}}],computeOpLogShapeSeed:()=>({baseCheckpoint:void 0,cursor:10,epoch:"e1",rowsPatch:[]}),currentCdcEpoch:()=>"e1",deliverWhisperLocal:()=>0,doName:()=>g,env:()=>({SHARD:{get:()=>t,getByName:()=>t,idFromName:a=>a}}),getWebSockets:()=>[],maskMetadata:()=>({columns:[]}),nextPokeId:()=>"poke-1",readAttachment:()=>({}),recordShapePokeFanout:()=>{},resolveShape:(a,n,h)=>(e.push(h),a===d.name?{columns:["id"],effectiveWhere:{org:h?.identity?.org??"anonymous"},global:!1,table:"orders"}:{columns:["id"],effectiveWhere:{room:"lobby"},global:!1,table:"messages"}),rlsMetadata:()=>({policies:[]}),shardBinding:()=>"SHARD",sql:()=>s});if(o===void 0)throw new Error("expected an owner link for an un-suffixed DO name");return{owner:o,posts:r,resolvedUnder:e}},l=async(s,r)=>{await s.handleControl(new Request("https://owner.internal/_lunora/relay",{body:JSON.stringify({...r,connectionId:"c-alice",identity:{org:"acme"},relayIndex:0,subId:"s1",type:"relay_shape_subscribe",userId:"u1"}),headers:{"content-type":"application/json"},method:"POST"}))};f("seeds a subscriber under its own forwarded identity, never the anonymous one",async()=>{const{close:s,host:r}=m();try{const{owner:e,resolvedUnder:t}=c(r.sql);await l(e,d),i(t.some(o=>o?.userId==="u1"&&o.identity?.org==="acme")).toBe(!0)}finally{s?.()}}),f("routes an identity-scoped shape to a per-socket poke, not the cohort multicast",async()=>{const{close:s,host:r}=m();try{const{owner:e,posts:t}=c(r.sql);await l(e,d),t.length=0,await e.onFlush(new Set(["orders"]),20);const o=t.filter(a=>a.type==="relay_shape_poke");i(o.length).toBe(1),i(o[0]?.targetConnectionId).toBe("c-alice")}finally{s?.()}}),f("still multicasts an identity-blind shape to the whole cohort",async()=>{const{close:s,host:r}=m();try{const{owner:e,posts:t}=c(r.sql);await l(e,p),t.length=0,await e.onFlush(new Set(["messages"]),20);const o=t.filter(a=>a.type==="relay_shape_poke");i(o.length).toBe(1),i(o[0]?.targetConnectionId).toBeUndefined()}finally{s?.()}})})})};export{D as defineEngineContractSuite};
1
+ import{createShardCtxDb as b}from"./NotUniqueError-CVHdtVw6.mjs";import{createRelayLink as I}from"./DEFAULT_MAX_RELAYS-B19vrJxP.mjs";import{ConflictError as N}from"./ConflictError-C8GtJmjS.mjs";import{runShardMigrations as v}from"./runShardMigrations-BqO6HPtX.mjs";import{relayName as q}from"./DEFAULT_PROMOTION_THRESHOLDS-B2rUe1bg.mjs";const C=(_,m={})=>({_meta:{column:{notNull:!0,...m}},kind:_}),D=(_,m,E)=>{const{describe:k,expect:i,it:f}=E;k(`engine contract: ${_}`,()=>{k("optimistic concurrency",()=>{const g=p=>({tables:{items:{indexes:[],shape:{title:C("string"),version:C("number",{notNull:!1})},triggerMap:{clobber:{handler:()=>{p.exec(`UPDATE "items" SET "__doc__" = json_set("__doc__", '$.version', 99) WHERE "id" = 'i1'`)},op:"update",timing:"before"}}}}});f("raises a CONFLICT of kind `occ` when a write's snapshot is clobbered",async()=>{const{close:p,host:d}=m();try{const c=d.sql,l=g(c);v(c,l);const s=b({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0}),await i(s.patch("i1",{title:"second"})).rejects.toBeInstanceOf(N)}finally{p?.()}}),f("reports the conflict as CONFLICT/409 rather than retrying it away",async()=>{const{close:p,host:d}=m();try{const c=d.sql,l=g(c);v(c,l);const s=b({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let r;try{await s.patch("i1",{title:"second"})}catch(t){r=t}const e=r;i(e.code).toBe("CONFLICT"),i(e.kind).toBe("occ")}finally{p?.()}}),f("leaves the row readable and unchanged after a conflict",async()=>{const{close:p,host:d}=m();try{const c=d.sql,l=g(c);v(c,l);const s=b({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});try{await s.patch("i1",{title:"second"})}catch{}const r=await s.get("i1");i(r?.title).toBe("first"),i(r?.version).toBe(99)}finally{p?.()}}),f("raises a CONFLICT of kind `trigger` when a trigger writes its own row through the db",async()=>{const{close:p,host:d}=m();try{const c=d.sql,l={tables:{items:{indexes:[],shape:{title:C("string"),version:C("number",{notNull:!1})},triggerMap:{recurse:{handler:async(t,o)=>{await t.db.patch(o.doc._id,{version:99})},op:"update",timing:"before"}}}}};v(c,l);const s=b({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let r;try{await s.patch("i1",{title:"second"})}catch(t){r=t}const e=r;i(e).toBeInstanceOf(N),i(e.code).toBe("CONFLICT"),i(e.kind).toBe("trigger")}finally{p?.()}})}),k("shape-poke ordering",()=>{const g="shard-a",p={args:{},name:"messages"},d=(e,t,o,a)=>e.accept(t?.()??{},{connectionId:o,shapes:{[a]:p}}),c=(e,t)=>{let o=0,a=0;const n=u=>()=>{throw new Error(`the relay poke path must not reach RelayHost.${u}`)},h={fetch:(u,O)=>{if(JSON.parse(O?.body??"{}").type!=="relay_shape_subscribe")return Promise.resolve(new Response(void 0,{status:204}));const B=t[a];if(a+=1,B===void 0)throw new Error("the relay asked for more seeds than this fixture supplies");return Promise.resolve(Response.json(B))}},y={get:()=>h,getByName:()=>h,idFromName:u=>u},w={buildShapeDiff:n("buildShapeDiff"),computeOpLogShapeSeed:n("computeOpLogShapeSeed"),currentCdcEpoch:n("currentCdcEpoch"),deliverWhisperLocal:n("deliverWhisperLocal"),doName:()=>q(g,0),env:()=>({SHARD:y}),getWebSockets:()=>e.getSockets(),maskMetadata:n("maskMetadata"),nextPokeId:()=>(o+=1,`poke-${String(o)}`),readAttachment:u=>u.deserializeAttachment?.(),recordShapePokeFanout:()=>{},resolveShape:n("resolveShape"),rlsMetadata:n("rlsMetadata"),shardBinding:()=>"SHARD",sql:n("sql")},S=I(w);if(S===void 0)throw new Error("expected a relay link for a `…::relay::N` name");return S},l=e=>new Request("https://relay.internal/_lunora/relay",{body:JSON.stringify(e),headers:{"content-type":"application/json"},method:"POST"}),s=async(e,t,o)=>{const a=await e.seedRelayShape(t,o,p,{identity:void 0,userId:void 0});if(a!=="ok")throw new Error(`seed failed: ${JSON.stringify(a)}`)},r=(e={})=>l({...p,checkpoint:20,epoch:"e1",fromCursor:10,rowsPatch:[{id:"r1",op:"upsert",value:{title:"hello"}}],type:"relay_shape_poke",...e});f("frames a poke as pokeStart → pokePart per shape → pokeEnd, under one poke id",async()=>{const{close:e,createSocket:t,readFrames:o,sockets:a}=m();try{const n=c(a,[{cursor:10,epoch:"e1",frames:[]}]),h=d(a,t,"c-alice","s1");await s(n,h,"s1"),await n.handleControl(r());const y=(await o(h)).map(w=>JSON.parse(w));i(y.map(w=>w.type)).toStrictEqual(["pokeStart","pokePart","pokeEnd"]),i(new Set(y.map(w=>w.pokeId)).size).toBe(1),i(y[1]?.shapeId).toBe("s1"),i(y[2]?.checkpoint).toBe(20)}finally{e?.()}}),f("delivers a poke only to sockets whose cursor matches, and advances them past it",async()=>{const{close:e,createSocket:t,readFrames:o,sockets:a}=m();try{const n=c(a,[{cursor:10,epoch:"e1",frames:[]},{cursor:7,epoch:"e1",frames:[]}]),h=d(a,t,"c-alice","s1"),y=d(a,t,"c-bob","s2");await s(n,h,"s1"),await s(n,y,"s2"),await n.handleControl(r());const w=await o(h);i(w.length).toBe(3);const S=await o(y);i(S.length).toBe(0),await n.handleControl(r());const u=await o(h);i(u.length).toBe(3)}finally{e?.()}}),f("skips a socket whose cursor matches under a different CDC epoch",async()=>{const{close:e,createSocket:t,readFrames:o,sockets:a}=m();try{const n=c(a,[{cursor:10,epoch:"e1",frames:[]}]),h=d(a,t,"c-alice","s1");await s(n,h,"s1"),await n.handleControl(r({epoch:"e2"}));const y=await o(h);i(y.length).toBe(0),await n.handleControl(r());const w=await o(h);i(w.length).toBe(3)}finally{e?.()}})}),k("RLS identity under live subscription",()=>{const g="shard-a",p={args:{},name:"lobby-messages"},d={args:{},name:"my-orders"},c=s=>{const r=[],e=[],t={fetch:(a,n)=>(r.push(JSON.parse(n?.body??"{}")),Promise.resolve(new Response(void 0,{status:204})))},o=I({buildShapeDiff:()=>[{id:"r1",op:"upsert",value:{}}],computeOpLogShapeSeed:()=>({baseCheckpoint:void 0,cursor:10,epoch:"e1",rowsPatch:[]}),currentCdcEpoch:()=>"e1",deliverWhisperLocal:()=>0,doName:()=>g,env:()=>({SHARD:{get:()=>t,getByName:()=>t,idFromName:a=>a}}),getWebSockets:()=>[],maskMetadata:()=>({columns:[]}),nextPokeId:()=>"poke-1",readAttachment:()=>({}),recordShapePokeFanout:()=>{},resolveShape:(a,n,h)=>(e.push(h),a===d.name?{columns:["id"],effectiveWhere:{org:h?.identity?.org??"anonymous"},global:!1,table:"orders"}:{columns:["id"],effectiveWhere:{room:"lobby"},global:!1,table:"messages"}),rlsMetadata:()=>({policies:[]}),shardBinding:()=>"SHARD",sql:()=>s});if(o===void 0)throw new Error("expected an owner link for an un-suffixed DO name");return{owner:o,posts:r,resolvedUnder:e}},l=async(s,r)=>{await s.handleControl(new Request("https://owner.internal/_lunora/relay",{body:JSON.stringify({...r,connectionId:"c-alice",identity:{org:"acme"},relayIndex:0,subId:"s1",type:"relay_shape_subscribe",userId:"u1"}),headers:{"content-type":"application/json"},method:"POST"}))};f("seeds a subscriber under its own forwarded identity, never the anonymous one",async()=>{const{close:s,host:r}=m();try{const{owner:e,resolvedUnder:t}=c(r.sql);await l(e,d),i(t.some(o=>o?.userId==="u1"&&o.identity?.org==="acme")).toBe(!0)}finally{s?.()}}),f("routes an identity-scoped shape to a per-socket poke, not the cohort multicast",async()=>{const{close:s,host:r}=m();try{const{owner:e,posts:t}=c(r.sql);await l(e,d),t.length=0,await e.onFlush(new Set(["orders"]),20);const o=t.filter(a=>a.type==="relay_shape_poke");i(o.length).toBe(1),i(o[0]?.targetConnectionId).toBe("c-alice")}finally{s?.()}}),f("still multicasts an identity-blind shape to the whole cohort",async()=>{const{close:s,host:r}=m();try{const{owner:e,posts:t}=c(r.sql);await l(e,p),t.length=0,await e.onFlush(new Set(["messages"]),20);const o=t.filter(a=>a.type==="relay_shape_poke");i(o.length).toBe(1),i(o[0]?.targetConnectionId).toBeUndefined()}finally{s?.()}})})})};export{D as defineEngineContractSuite};
@@ -0,0 +1 @@
1
+ import{LunoraError as c}from"@lunora/errors";import{sql as o}from"drizzle-orm";import{quoteIdentifier as m}from"./quoteIdentifier-CObIFRhb.mjs";import{s as u,a as p}from"./wire-codec-Dsy70M3Q.mjs";import{runDrizzle as _}from"./runDrizzle-B6rnz3so.mjs";import{b as E}from"./sql-projection-jfoe331H.mjs";import"./serializeSqlValue-BR4UOWoP.mjs";const T=/^[A-Za-z_$][\w$]*$/u,S=e=>T.test(e)?e:`"${e.replaceAll("\\",String.raw`\\`).replaceAll('"',String.raw`\"`)}"`,l="__doc__",s="__originals__",R=e=>{if(Object.hasOwn(e,s))throw new c("BAD_REQUEST",`"${s}" is reserved by the row store's document encoding and cannot be used as a field name — rename the field`);let t,r;for(const[i,n]of Object.entries(e)){const a=E(n);a!==void 0&&(t??={...e},r??=Object.create(null),t[i]=a,r[i]=n)}t&&r&&(t[s]=r);try{return JSON.stringify(p(t??e))}catch(i){throw new c("BAD_REQUEST",`this document cannot be stored: ${i instanceof Error?i.message:String(i)}`)}},y=e=>{const t=u(JSON.parse(e)),{[s]:r,...i}=t;return r===null||typeof r!="object"||Array.isArray(r)?t:{...i,...r}},C=(e,t)=>`${e}__geo_${t}`,d=(e,t)=>t==="_id"||t==="id"?`${e}id`:t==="_creationTime"?`${e}_creationTime`:`json_extract(${e}${l}, '$.${S(t).replaceAll("'","''")}')`,A=e=>d("",e),v=e=>o.raw(A(e)),O=(e,t)=>d(`${m(e)}.`,t),B=(e,t)=>o.raw(O(e,t)),F=(e,t,r,i)=>o`CREATE ${i?o`UNIQUE `:o``}INDEX IF NOT EXISTS ${o.identifier(e)} ON ${o.identifier(t)} (${r})`,f=o.identifier("__key__"),I=o.identifier("__value__"),h=o.identifier("__count__"),X=(e,t,r,i,n)=>o`INSERT INTO ${o.identifier(e)} (${f}, ${I}, ${h}) VALUES (${t}, ${r}, ${i}) ON CONFLICT(${f}) DO UPDATE SET ${n}`,x=e=>{const t=[];for(const[r,i]of Object.entries(e.shape)){const n=i._meta?.column;n&&t.push([r,n])}return t},b=e=>{if(!e)return;const t=e[l];let r;typeof t=="string"?r=y(t):t&&typeof t=="object"?r=t:r={};const{id:i}=e;typeof i=="string"&&(r._id=i);const n=e._creationTime;return typeof n=="number"&&(r._creationTime=n),r},z=e=>{try{return b(e)}catch{return}},$=new WeakMap,P=e=>{const t=$.get(e);if(t!==void 0)return t;let r;try{_(e,o`CREATE VIRTUAL TABLE IF NOT EXISTS ${o.identifier("__lunora_fts_probe")} USING fts5(x)`),r=!0}catch{r=!1}finally{try{_(e,o`DROP TABLE IF EXISTS ${o.identifier("__lunora_fts_probe")}`)}catch{}}return $.set(e,r),r};export{X as A,P as C,z as D,b as E,x as I,R as L,v as N,B as O,O as S,h as T,A as _,l as a,f as c,y as g,C as h,S as j,I as p,s,F as y};
@@ -0,0 +1 @@
1
+ import{r as c}from"./sql-projection-jfoe331H.mjs";const i=40,s=o=>{let r=0;const f=(e,t)=>typeof t=="bigint"?(r+=c+1+i,t.toString()):t instanceof ArrayBuffer||ArrayBuffer.isView(t)?(r+=2*Math.ceil(t.byteLength/3)*4+i,""):t;try{const e=JSON.stringify(o,f);return(e===void 0?0:e.length)+r}catch{return}};export{s as o};
@@ -0,0 +1 @@
1
+ import{toErrorBody as f}from"@lunora/errors";const d=200,b=(r,s)=>{const n=o=>{const e=r.tables[o];return e!==void 0&&e.shardMode?.kind!=="global"};return(s&&s.length>0?[...s]:Object.keys(r.tables)).filter(o=>n(o))},u=async function*(r,s,n=d){let o=null,e=!1;for(;!e;){const t=await r.findMany(s,{cursor:o,limit:n});for(const a of t.page)yield{doc:a,table:s};o=t.continueCursor,e=t.isDone||o===null}},k=async function*(r,s,n){const o=b(s,n.tables),e=n.batchSize??d;for(const t of o)yield*u(r,t,e)},p=new Set(["_creationTime","_id"]),y=(r,s)=>{for(const[n,o]of Object.entries(r.shape)){const e=s[n];if(e===void 0&&o.kind==="optional")continue;const t=o.parse;if(typeof t=="function")try{t(e)}catch(a){const c=a instanceof Error?a.message:String(a);return`field "${n}": ${c}`}}},h=(r,s,n)=>{const o=r.tables[s];if(!o)return`unknown table: ${s}`;if(o.shardMode?.kind==="global")return`table "${s}" is a global (.global()) table and is not importable through the shard import path`;const e=Object.fromEntries(Object.entries(n).filter(([t])=>!p.has(t)));for(const t of Object.keys(e))if(!(t in o.shape))return`unexpected field "${t}": not declared in table "${s}"`;return y(o,e)},g=async(r,s)=>{try{return await r.get(s)!==null}catch{return!1}},m=async(r,s,n,o)=>{const{doc:e,table:t}=n;if(typeof t!="string"||t.length===0)return{error:{code:"BAD_ROW",line:o,message:"row is missing `table`",table:t},kind:"error"};if(!e||typeof e!="object"||Array.isArray(e))return{error:{code:"BAD_ROW",line:o,message:"row is missing or malformed `doc`",table:t},kind:"error"};const a=h(s,t,e);if(a!==void 0)return{error:{code:"VALIDATION_ERROR",line:o,message:a,table:t},kind:"error"};const c=typeof e._id=="string"?e._id:void 0;if(c!==void 0&&await g(r,c))return{kind:"conflict"};try{return await r.insert(t,e,{allowExplicitId:!0}),{kind:"inserted",table:t}}catch(i){const{body:l}=f(i,{fallbackCode:"INSERT_FAILED"});return{error:{code:l.code,line:o,message:l.message,table:t},kind:"error"}}},A=async(r,s,n)=>{const o=[],e={};let t=0,a=(n.startLine??1)-1;for(const c of n.rows){a+=1;const i=await m(r,s,c,a);i.kind==="error"?o.push(i.error):i.kind==="conflict"?t+=1:e[i.table]=(e[i.table]??0)+1}return{conflicts:t,errors:o,inserted:e}},S=r=>{const s=Array.isArray(r.tables)?r.tables.filter(n=>typeof n=="string"):void 0;return{batchSize:typeof r.batchSize=="number"?r.batchSize:void 0,tables:s}},v=r=>{const s=Array.isArray(r.rows)?r.rows:[],n=[];for(const e of s){if(!e||typeof e!="object")continue;const t=e;if(typeof t.table!="string"||!t.doc||typeof t.doc!="object"||Array.isArray(t.doc)){n.push({doc:t.doc??{},table:typeof t.table=="string"?t.table:""});continue}n.push({doc:t.doc,table:t.table})}const o=typeof r.startLine=="number"?r.startLine:void 0;return{rows:n,startLine:o}};export{k as exportShardRows,u as exportShardTable,A as importShardRows,S as parseExportShardArgs,v as parseImportShardArgs,b as selectExportTables,h as validateImportRow};
@@ -1,4 +1,4 @@
1
- import{LunoraError as E}from"@lunora/errors";import{sql as m}from"drizzle-orm";import{runDrizzle as h}from"./runDrizzle-GKR3y97k.mjs";import{liftSourceId as x}from"./liftSourceId-DApAbu7Q.mjs";import{normalizeSourceValue as K}from"./liftSourceId-DApAbu7Q.mjs";import{runExternalSourceTick as v,materializeExternalRowsIncremental as M}from"./materializeExternalRows-DOQJV9p2.mjs";const _="__lunora_source_cursor",D=e=>e instanceof Date?`d:${e.toISOString()}`:typeof e=="bigint"?`b:${e.toString()}`:typeof e=="number"?`n:${e.toString()}`:`s:${e}`,R=e=>{const t=e.slice(2);switch(e[0]){case"b":return BigInt(t);case"d":return new Date(t);case"n":return Number(t);default:return t}},k=/^-?\d+$/,I=/^-?\d+(?:\.\d+)?$/,A=(e,t)=>e instanceof Date&&t instanceof Date?e.getTime()>t.getTime():typeof e=="bigint"&&typeof t=="bigint"||typeof e=="number"&&typeof t=="number"?e>t:typeof e=="string"&&typeof t=="string"&&I.test(e)&&I.test(t)?k.test(e)&&k.test(t)?BigInt(e)>BigInt(t):Number(e)>Number(t):String(e)>String(t),q=(e,t,a)=>{let n=a===null?void 0:R(a);for(const r of e){const s=r[t];if(s==null)continue;const i=s;(n===void 0||A(i,n))&&(n=i)}return n===void 0?null:D(n)},O=e=>{h(e,m`CREATE TABLE IF NOT EXISTS ${m.identifier(_)} (
1
+ import{LunoraError as E}from"@lunora/errors";import{sql as m}from"drizzle-orm";import{runDrizzle as h}from"./runDrizzle-B6rnz3so.mjs";import{liftSourceId as x}from"./liftSourceId-DApAbu7Q.mjs";import{normalizeSourceValue as K}from"./liftSourceId-DApAbu7Q.mjs";import{runExternalSourceTick as v,materializeExternalRowsIncremental as M}from"./materializeExternalRows-DcCENzpV.mjs";const _="__lunora_source_cursor",D=e=>e instanceof Date?`d:${e.toISOString()}`:typeof e=="bigint"?`b:${e.toString()}`:typeof e=="number"?`n:${e.toString()}`:`s:${e}`,R=e=>{const t=e.slice(2);switch(e[0]){case"b":return BigInt(t);case"d":return new Date(t);case"n":return Number(t);default:return t}},k=/^-?\d+$/,I=/^-?\d+(?:\.\d+)?$/,A=(e,t)=>e instanceof Date&&t instanceof Date?e.getTime()>t.getTime():typeof e=="bigint"&&typeof t=="bigint"||typeof e=="number"&&typeof t=="number"?e>t:typeof e=="string"&&typeof t=="string"&&I.test(e)&&I.test(t)?k.test(e)&&k.test(t)?BigInt(e)>BigInt(t):Number(e)>Number(t):String(e)>String(t),q=(e,t,a)=>{let n=a===null?void 0:R(a);for(const r of e){const s=r[t];if(s==null)continue;const i=s;(n===void 0||A(i,n))&&(n=i)}return n===void 0?null:D(n)},O=e=>{h(e,m`CREATE TABLE IF NOT EXISTS ${m.identifier(_)} (
2
2
  table_name TEXT NOT NULL,
3
3
  shard_key TEXT NOT NULL,
4
4
  watermark TEXT,
@@ -1 +1 @@
1
- import{applyCdcChanges as m}from"./CDC_LOG_TABLE-BnqlH2eZ.mjs";import{selectShapeRows as f}from"./selectShapeMemberIds-DvE7K6zG.mjs";import{diffExternalSource as g,projectExternalSourceRow as c}from"./diffExternalSource-DMpkJta1.mjs";import{stableStringify as p}from"./stableStringify-BjLh4gvA.mjs";const x=async(t,s,r,e)=>{const{changes:n,nextBaseline:a}=g(s,r,e);return await m(t,n),{applied:n.length,nextBaseline:a}},E=async(t,s,r)=>{const{columns:e,deletedIds:n,table:a}=r,i=[];for(const u of s){const l=c(u,e),o=String(l._id);if(n?.has(o)){await t.get(o,a)&&i.push({id:o,op:"delete",seq:0,table:a,ts:0});continue}const d=await t.get(o,a);d&&p(c({...d,_id:o},e))===p(l)||i.push({doc:l,id:o,op:"insert",seq:0,table:a,ts:0})}return await m(t,i),{applied:i.length}},w=(t,s,r)=>{const e=new Map;for(const{doc:n,id:a}of f(t,s,void 0))e.set(a,p(c({...n,_id:a},r)));return e},R=async(t,s,r,e)=>{const n=w(t,e.table,e.columns);return x(s,r,n,e)};export{x as materializeExternalRows,E as materializeExternalRowsIncremental,w as readExternalSourceBaseline,R as runExternalSourceTick};
1
+ import{applyCdcChanges as m}from"./CDC_LOG_TABLE-ZqcflEen.mjs";import{selectShapeRows as f}from"./selectShapeMemberIds-BdBcbrUP.mjs";import{diffExternalSource as g,projectExternalSourceRow as c}from"./diffExternalSource-DMpkJta1.mjs";import{stableStringify as p}from"./stableStringify-BjLh4gvA.mjs";const x=async(t,s,r,e)=>{const{changes:n,nextBaseline:a}=g(s,r,e);return await m(t,n),{applied:n.length,nextBaseline:a}},E=async(t,s,r)=>{const{columns:e,deletedIds:n,table:a}=r,i=[];for(const u of s){const l=c(u,e),o=String(l._id);if(n?.has(o)){await t.get(o,a)&&i.push({id:o,op:"delete",seq:0,table:a,ts:0});continue}const d=await t.get(o,a);d&&p(c({...d,_id:o},e))===p(l)||i.push({doc:l,id:o,op:"insert",seq:0,table:a,ts:0})}return await m(t,i),{applied:i.length}},h=(t,s,r)=>{const e=new Map;for(const{doc:n,id:a}of f(t,s,void 0))e.set(a,p(c({...n,_id:a},r)));return e},R=async(t,s,r,e)=>{const n=h(t,e.table,e.columns);return x(s,r,n,e)};export{x as materializeExternalRows,E as materializeExternalRowsIncremental,h as readExternalSourceBaseline,R as runExternalSourceTick};
@@ -0,0 +1 @@
1
+ import{keysTouchRanges as g}from"./buildIndexRange-DFsdtPjD.mjs";const c=(s,t,o)=>{const e=s??new Map;for(const n of o){const r=t?.get(n),a=e.get(n),i=e.has(n)&&a===void 0;if(!t?.has(n)||r===void 0||i){e.set(n,void 0);continue}e.set(n,a?[...a,...r]:r)}return e},f=(s,t,o)=>{const e=s??new Map;if(e.has(t)&&e.get(t)===void 0)return e;if(!o||o.length===0)return e.set(t,void 0),e;const n=e.get(t);return e.set(t,n?[...n,...o]:[...o]),e},h=(s,t,o)=>{if(!o)return!0;for(const e of t){if(!s.tables.has(e))continue;const n=s.ranges?.get(e);if(!n||n.length===0||g(n,o.get(e)))return!0}return!1};export{c as mergeChangedKeys,f as recordChangedKeys,h as writeTouchesMemo};
@@ -0,0 +1 @@
1
+ const t=e=>`"${e.replaceAll('"','""')}"`;export{t as quoteIdentifier};
@@ -0,0 +1 @@
1
+ import{renderSql as t}from"./param-B5lF5Jd9.mjs";const n=(r,e,...l)=>r.exec.call(r,e,...l),c=(r,e)=>{const{params:l,sql:o}=t("sqlite",e);return n(r,o,...l)},s=r=>r??null,a=r=>{if(!(r==null||r===""))try{return JSON.parse(r)}catch{return}};export{a as decodeJsonColumn,s as orNull,c as runDrizzle,n as runSql};
@@ -0,0 +1,5 @@
1
+ import{l as I,T as N,c as S}from"./ctx-db-companions-BTi8DLUl.mjs";import"@lunora/errors";import{sql as e}from"drizzle-orm";import{aggregateTableName as p}from"./aggregateTableName-DgYMC5tr.mjs";import{backfillSearchIndexesForTable as g}from"./backfillAggregateIndexes-DmqOHg0U.mjs";import{migrateCdcLog as h,migrateCdcMeta as l}from"./CDC_LOG_TABLE-ZqcflEen.mjs";import{migrateClientWatermark as R}from"./CLIENT_WATERMARK_TABLE-CzApRlyv.mjs";import{migrateGlobalShapeSnapshot as C}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-soMJDSBs.mjs";import{migrateIdempotency as O}from"./IDEMPOTENCY_TABLE-Bvu9JkiL.mjs";import{migrateSearchState as U}from"./SEARCH_STATE_TABLE-BZ_fxI5l.mjs";import{runDrizzle as a}from"./runDrizzle-B6rnz3so.mjs";import{a as u,N as E,y as _,I as X,C as b,c as x,p as B,T as c,h as F}from"./do-sql-1Yi1_Yq0.mjs";import{sortColumnName as M,rankTableName as Y}from"./RANK_TIEBREAK-DDtST3gN.mjs";import{recordSchemaVersion as D}from"./SCHEMA_HISTORY_MAX_VERSIONS-BEU0CuW5.mjs";const k=(r,t,o)=>{for(const i of o.indexes){const n=`${t}_${i.name}`,s=e.join(i.fields.map(f=>E(f)),e`, `);a(r,_(n,t,s,i.unique??!1))}for(const[i,n]of X(o)){if(!n.unique)continue;const s=`${t}_unique_${i}`;a(r,_(s,t,E(i),!0))}},y=(r,t,o)=>{if(!(!o.searchIndexes||o.searchIndexes.length===0||!b(r))){for(const i of o.searchIndexes){const n=S(t,i.name);a(r,e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(n)} USING fts5(${e.identifier(I)}, ${e.identifier(N)} UNINDEXED)`),a(r,e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(`${n}__vocab`)} USING fts5vocab(${e.identifier(n)}, ${e.raw("instance")})`)}g(r,t,o)}},j=(r,t,o)=>{if(o.geoIndexes)for(const i of o.geoIndexes){const n=F(t,i.name);a(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(n)} (${e.identifier("__id__")} TEXT PRIMARY KEY, ${e.identifier("__geohash__")} TEXT NOT NULL, ${e.identifier("__lat__")} REAL NOT NULL, ${e.identifier("__lng__")} REAL NOT NULL)`);const s=`${t}__geo_${i.name}__btree`;a(r,_(s,n,e`${e.identifier("__geohash__")} ASC, ${e.identifier("__id__")} ASC`,!1))}},q=(r,t,o)=>{if(o.aggregateIndexes)for(const i of o.aggregateIndexes){const n=p(t,i.name);a(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(n)} (${x} TEXT PRIMARY KEY, ${B} REAL, ${c} INTEGER NOT NULL DEFAULT 0)`),a(r,e`PRAGMA table_info(${e.identifier(n)})`).toArray().some(s=>s.name==="__count__")||a(r,e`ALTER TABLE ${e.identifier(n)} ADD COLUMN ${c} INTEGER NOT NULL DEFAULT 0`)}},G=(r,t,o)=>{if(o.rankIndexes)for(const i of o.rankIndexes){const n=Y(t,i.name),s=i.sortBy.map((T,d)=>M(d)),f=s.map(T=>e`${e.identifier(T)} BLOB`),$=f.length>0?e`, ${e.join(f,e`, `)}`:e``;a(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(n)} (${e.identifier("__id__")} TEXT PRIMARY KEY, ${e.identifier("__partition__")} TEXT NOT NULL${$})`);const m=[e`${e.identifier("__partition__")} ASC`];for(const[T,d]of s.entries()){const A=i.sortBy[T]?.direction;m.push(e`${e.identifier(d)} ${e.raw(A==="desc"?"DESC":"ASC")}`)}m.push(e`${e.identifier("__id__")} ASC`);const L=`${t}__rank_${i.name}__btree`;a(r,_(L,n,e.join(m,e`, `),!1))}},ne=(r,t,o={})=>{o.schemaSnapshot!==void 0&&D(r,o.schemaSnapshot.hash,o.schemaSnapshot.json),U(r);for(const[i,n]of Object.entries(t.tables))n.shardMode?.kind!=="global"&&(a(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(i)} (
2
+ id TEXT PRIMARY KEY,
3
+ _creationTime REAL NOT NULL,
4
+ ${e.identifier(u)} TEXT NOT NULL
5
+ )`),k(r,i,n),y(r,i,n),j(r,i,n),q(r,i,n),G(r,i,n));o.cdc&&(h(r),l(r),R(r)),O(r),C(r)};export{ne as runShardMigrations};
@@ -0,0 +1 @@
1
+ import{sql as e}from"drizzle-orm";import{runDrizzle as $}from"./runDrizzle-B6rnz3so.mjs";import{N as r}from"./do-sql-1Yi1_Yq0.mjs";const E=(d,i,s,o)=>{const f=s-(i.after??0),t=[e`${r(i.field)} IS NOT NULL`,e`${r(i.field)} < ${f}`];i.softDeleteField!==void 0&&t.push(e`${r(i.softDeleteField)} IS NULL`);const a=e`SELECT id FROM ${e.identifier(i.table)} WHERE ${e.join(t,e` AND `)} LIMIT ${e.raw(String(Math.max(0,Math.floor(o))+1))}`,l=$(d,a).toArray(),n=l.length>o,m=l.slice(0,o).map(p=>p.id);return{hasMore:n,ids:m}};export{E as selectExpiredIds};
@@ -0,0 +1 @@
1
+ import{sql as e}from"drizzle-orm";import{runDrizzle as l}from"./runDrizzle-B6rnz3so.mjs";import{a as c,E as a,N as u}from"./do-sql-1Yi1_Yq0.mjs";import{compileWhereSql as h}from"./compileWhereSql-B4rPariq.mjs";import{serializeSqlValue as S}from"./serializeSqlValue-BR4UOWoP.mjs";const $={fieldRef:u,serialize:S},E=i=>{if(i.length!==0)return e`id IN (${e.join(i.map(r=>e`${r}`),e`, `)})`},m=(i,r)=>{const o=[];r&&o.push(r);const t=h(i,$);return t&&o.push(t),o.length===0?e``:e` WHERE ${e.join(o,e` AND `)}`},y=(i,r,o)=>{const t=m(o,void 0),d=l(i,e`SELECT id, _creationTime, ${e.identifier(c)} FROM ${e.identifier(r)}${t}`).toArray(),n=[];for(const s of d){const f=a(s),{id:p}=s;f!==void 0&&typeof p=="string"&&n.push({doc:f,id:p})}return n},A=(i,r,o,t)=>{if(t.length===0)return new Set;const d=m(o,E(t)),n=l(i,e`SELECT id FROM ${e.identifier(r)}${d}`).toArray();return new Set(n.map(s=>s.id))};export{A as selectShapeMemberIds,y as selectShapeRows};
@@ -0,0 +1 @@
1
+ import{b as o}from"./sql-projection-jfoe331H.mjs";const t=e=>typeof e=="boolean"?e?1:0:e===null||typeof e=="string"||typeof e=="number"?e:o(e)??JSON.stringify(e);export{t as serializeSqlValue};