@lunora/shard-engine 1.0.0-alpha.3 → 1.0.0-alpha.30
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/conformance/index.mjs +1 -1
- package/dist/index.d.mts +191 -20
- package/dist/index.d.ts +191 -20
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/ADMIN_FUNCTIONS-Ddr79XHG.mjs +1 -0
- package/dist/packem_shared/AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs +1 -0
- package/dist/packem_shared/AGG_COUNT-DOlqqroz.mjs +1 -0
- package/dist/packem_shared/AUDIT_LOG_TABLE-uNVU9O1W.mjs +8 -0
- package/dist/packem_shared/CDC_LOG_TABLE-B58N8NQO.mjs +8 -0
- package/dist/packem_shared/CLIENT_WATERMARK_TABLE-BoS1HEqz.mjs +7 -0
- package/dist/packem_shared/CountRlsUnsupportedError-Bdfupt3g.mjs +1 -0
- package/dist/packem_shared/DATA_MIGRATION_STATE_TABLE-4l6aU1Vc.mjs +31 -0
- package/dist/packem_shared/DEFAULT_MAX_RELATION_KEYS-BAWGIEvC.mjs +1 -0
- package/dist/packem_shared/DEFAULT_MAX_RELAYS-DeVcEXBh.mjs +1 -0
- package/dist/packem_shared/DEFAULT_PROMOTION_THRESHOLDS-DVTD9iu0.mjs +1 -0
- package/dist/packem_shared/DEFAULT_TRANSACTION_LIMITS-Bcoi7Bvf.mjs +1 -0
- package/dist/packem_shared/DurableStreamRunner-Bm6KDMBU.mjs +1 -0
- package/dist/packem_shared/GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs +1 -0
- package/dist/packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-NWaL77m5.mjs +7 -0
- package/dist/packem_shared/IDEMPOTENCY_TABLE-DKVe2Ohf.mjs +7 -0
- package/dist/packem_shared/MAIL_RETENTION-Cig9Dmc8.mjs +18 -0
- package/dist/packem_shared/MAX_SQL_ROWS-DnDyeZph.mjs +2 -0
- package/dist/packem_shared/NotUniqueError-BixDiv4O.mjs +1 -0
- package/dist/packem_shared/QUEUE_TABLE-zj9Tt6tk.mjs +17 -0
- package/dist/packem_shared/RANK_TIEBREAK-ci3MaM65.mjs +1 -0
- package/dist/packem_shared/RELATION_EXISTS_KEY-CFUhnZSZ.mjs +1 -0
- package/dist/packem_shared/REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs +1 -0
- package/dist/packem_shared/RLS_UNWRAP_SYMBOL-BWloGsd3.mjs +1 -0
- package/dist/packem_shared/ReactiveCache-DfyeaJOA.mjs +1 -0
- package/dist/packem_shared/SCAN_DEP-D7qE3iUe.mjs +1 -0
- package/dist/packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-DsycDXWm.mjs +6 -0
- package/dist/packem_shared/SEARCH_STATE_TABLE-Dju8ebbU.mjs +1 -0
- package/dist/packem_shared/SHAPE_POKE_CURSOR_TABLE-Dh4HfSdC.mjs +7 -0
- package/dist/packem_shared/ShardRunner-C9p5DVOx.mjs +1 -0
- package/dist/packem_shared/aggregateTableName-Cy5e03oz.mjs +1 -0
- package/dist/packem_shared/appendStreamChunk-CH4e4nJn.mjs +19 -0
- package/dist/packem_shared/applyOnDelete-BlcwKjuO.mjs +1 -0
- package/dist/packem_shared/applySelect-BQbHyo-W.mjs +1 -0
- package/dist/packem_shared/{armRestore-BNzdvQ_o.mjs → armRestore-Bu1_8SUa.mjs} +1 -1
- package/dist/packem_shared/awaitWsDrain-kSGvAfw1.mjs +1 -0
- package/dist/packem_shared/backfillAggregateIndexes-DVQ2sVuV.mjs +1 -0
- package/dist/packem_shared/base64-DfpzS4o_.mjs +1 -0
- package/dist/packem_shared/buildIndexRange-CBKQmHSS.mjs +1 -0
- package/dist/packem_shared/buildPokeFrames-BXejpiII.mjs +1 -0
- package/dist/packem_shared/buildReprojectionMigration-8nVn8Qwb.mjs +1 -0
- package/dist/packem_shared/buildSettings-B4igo4rJ.mjs +1 -0
- package/dist/packem_shared/compileWhereSql-JBpSfQm9.mjs +1 -0
- package/dist/packem_shared/computeRankPage-Bby1Npkd.mjs +1 -0
- package/dist/packem_shared/createCompanionSync-zCwaB6wj.mjs +1 -0
- package/dist/packem_shared/createReadFootprint-MRH1If3F.mjs +1 -0
- package/dist/packem_shared/createReplicaLink-C1JuP_DN.mjs +7 -0
- package/dist/packem_shared/createSystemReader-BtYeSMDb.mjs +1 -0
- package/dist/packem_shared/ctx-db-companions-lTt-rvKG.mjs +1 -0
- package/dist/packem_shared/defineEngineContractSuite-0XtjRA7F.mjs +1 -0
- package/dist/packem_shared/diffExternalSource-pozJ4UdZ.mjs +1 -0
- package/dist/packem_shared/do-sql-Dk_DJxn4.mjs +1 -0
- package/dist/packem_shared/estimate-bytes-CzG5x1f8.mjs +1 -0
- package/dist/packem_shared/exportShardRows-Cgt3ITwH.mjs +1 -0
- package/dist/packem_shared/hasTrigger-CjlwI4le.mjs +1 -0
- package/dist/packem_shared/isSoftDeleted-DcGB0pov.mjs +9 -0
- package/dist/packem_shared/liftSourceId-CA3ENhXj.mjs +1 -0
- package/dist/packem_shared/materializeExternalRows-Drn0FGdb.mjs +1 -0
- package/dist/packem_shared/mergeChangedKeys-D1T-TPUb.mjs +1 -0
- package/dist/packem_shared/param-Ib8WHnrF.mjs +1 -0
- package/dist/packem_shared/quoteIdentifier-CObIFRhb.mjs +1 -0
- package/dist/packem_shared/runDrizzle-it6rL9bR.mjs +1 -0
- package/dist/packem_shared/runShardMigrations-Crppyq1f.mjs +5 -0
- package/dist/packem_shared/runSocketPool-CZJ2X9cF.mjs +1 -0
- package/dist/packem_shared/selectExpiredIds-_5514W_v.mjs +1 -0
- package/dist/packem_shared/selectShapeMemberIds-B-pQJHAu.mjs +1 -0
- package/dist/packem_shared/serializeSqlValue-DbI1VQYM.mjs +1 -0
- package/dist/packem_shared/sibling-channel-BRZpLiDA.mjs +1 -0
- package/dist/packem_shared/sql-projection-BqmxFxQU.mjs +1 -0
- package/dist/packem_shared/stableStringify-CujpENIO.mjs +1 -0
- package/dist/packem_shared/stableWireKey-BYB5GQJa.mjs +1 -0
- package/dist/packem_shared/wire-codec-BU9T2xJ7.mjs +1 -0
- package/package.json +3 -3
- package/dist/packem_shared/ADMIN_FUNCTIONS-B0xlQJ4w.mjs +0 -1
- package/dist/packem_shared/AGGREGATE_SQL_FUNCTION-QYaiuty4.mjs +0 -1
- package/dist/packem_shared/AGG_COUNT-BWXe3gtQ.mjs +0 -1
- package/dist/packem_shared/AUDIT_LOG_TABLE-CaA0jL0L.mjs +0 -8
- package/dist/packem_shared/CDC_LOG_TABLE-BnqlH2eZ.mjs +0 -8
- package/dist/packem_shared/CLIENT_WATERMARK_TABLE-CXsSLU8D.mjs +0 -7
- package/dist/packem_shared/CountRlsUnsupportedError-B2WKJD9v.mjs +0 -1
- package/dist/packem_shared/DATA_MIGRATION_STATE_TABLE-CaO6L0Ee.mjs +0 -31
- package/dist/packem_shared/DEFAULT_MAX_RELATION_KEYS-bq00btqV.mjs +0 -1
- package/dist/packem_shared/DEFAULT_MAX_RELAYS-CnCyh6oX.mjs +0 -1
- package/dist/packem_shared/DEFAULT_PROMOTION_THRESHOLDS-Dteg0sZF.mjs +0 -1
- package/dist/packem_shared/DEFAULT_TRANSACTION_LIMITS--TtB8Gpo.mjs +0 -1
- package/dist/packem_shared/FTS_COUNT_COLUMN-D1gY3wwZ-CZHdaRrd.mjs +0 -1
- package/dist/packem_shared/GEO_DEFAULT_PRECISION-okRCkZ6r.mjs +0 -1
- package/dist/packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-DX-6-gBP.mjs +0 -7
- package/dist/packem_shared/IDEMPOTENCY_TABLE-DjkEMp6w.mjs +0 -7
- package/dist/packem_shared/MAIL_RETENTION-KmozO2NQ.mjs +0 -18
- package/dist/packem_shared/MAX_SQL_ROWS-nMwkxv5f.mjs +0 -2
- package/dist/packem_shared/NotUniqueError-iGKd9wRR.mjs +0 -1
- package/dist/packem_shared/QUEUE_TABLE-DYCDvzTG.mjs +0 -17
- package/dist/packem_shared/RANK_TIEBREAK-9NU5s_mi.mjs +0 -1
- package/dist/packem_shared/RELATION_EXISTS_KEY-BaqSIFU1.mjs +0 -1
- package/dist/packem_shared/RLS_UNWRAP_SYMBOL-C6_WX3dG.mjs +0 -1
- package/dist/packem_shared/ReactiveCache-CF21t8IB.mjs +0 -1
- package/dist/packem_shared/SCAN_DEP-D_yR9EeV.mjs +0 -1
- package/dist/packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-CHXz6p_z.mjs +0 -6
- package/dist/packem_shared/SEARCH_STATE_TABLE-eLN8U5tz.mjs +0 -1
- package/dist/packem_shared/ShardRunner-DIqVdWtk.mjs +0 -1
- package/dist/packem_shared/aggregateTableName-G-eXyjcz.mjs +0 -1
- package/dist/packem_shared/applyOnDelete-uFRC5p1d.mjs +0 -1
- package/dist/packem_shared/applySelect-B0CF8T7y.mjs +0 -1
- package/dist/packem_shared/awaitWsDrain-Dk50ISgE.mjs +0 -1
- package/dist/packem_shared/backfillAggregateIndexes-BHiewuB-.mjs +0 -1
- package/dist/packem_shared/buildIndexRange-DIjFVgeO.mjs +0 -1
- package/dist/packem_shared/buildPokeFrames-DaPpm5Ss.mjs +0 -1
- package/dist/packem_shared/buildSettings-DT18_DkX.mjs +0 -1
- package/dist/packem_shared/compileWhereSql-BLcfs4QW.mjs +0 -1
- package/dist/packem_shared/computeRankPage-IUSS-zIB.mjs +0 -1
- package/dist/packem_shared/createCompanionSync-DWK0Vlg1.mjs +0 -1
- package/dist/packem_shared/createReadFootprint-DIrrxRTE.mjs +0 -1
- package/dist/packem_shared/createSystemReader-DcDcrtM3.mjs +0 -1
- package/dist/packem_shared/defineEngineContractSuite-BefTibvY.mjs +0 -1
- package/dist/packem_shared/diffExternalSource-DMpkJta1.mjs +0 -1
- package/dist/packem_shared/estimate-bytes-DzD3PdCc.mjs +0 -1
- package/dist/packem_shared/exportShardRows-kt42wijd.mjs +0 -1
- package/dist/packem_shared/hasTrigger-CbkOHExZ.mjs +0 -1
- package/dist/packem_shared/isSoftDeleted-B-SXkGUo.mjs +0 -9
- package/dist/packem_shared/liftSourceId-DApAbu7Q.mjs +0 -1
- package/dist/packem_shared/materializeExternalRows-DOQJV9p2.mjs +0 -1
- package/dist/packem_shared/mergeChangedKeys-CvSHlkv-.mjs +0 -1
- package/dist/packem_shared/param-B5lF5Jd9.mjs +0 -1
- package/dist/packem_shared/quote-identifier-CGiYFBvY.mjs +0 -1
- package/dist/packem_shared/runDrizzle-GKR3y97k.mjs +0 -1
- package/dist/packem_shared/runShardMigrations-CPxqCh3O.mjs +0 -5
- package/dist/packem_shared/runSocketPool-DPQLVyWF.mjs +0 -1
- package/dist/packem_shared/selectExpiredIds-FzhIEeG1.mjs +0 -1
- package/dist/packem_shared/selectShapeMemberIds-DvE7K6zG.mjs +0 -1
- package/dist/packem_shared/serializeSqlValue-DnpyaLcw.mjs +0 -1
- package/dist/packem_shared/stableStringify-BjLh4gvA.mjs +0 -1
- package/dist/packem_shared/stableWireKey-YEHLaX6X.mjs +0 -1
- package/dist/packem_shared/wire-codec-Ctnni0h6.mjs +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as h}from"@lunora/errors";import{distinctValues as w}from"./applyOnDelete-BlcwKjuO.mjs";import{RELATION_EXISTS_KEY as N}from"./RELATION_EXISTS_KEY-CFUhnZSZ.mjs";const g={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}},T=new Set(Object.keys(g)),p=e=>{const t=g[e];if(!t)throw new h("INTERNAL",`unknown relation operator "${e}"`);return t},j=e=>e.kind==="one"?{clause:e.field,project:e.references}:{clause:e.references,project:e.field},S=5e3,l=Symbol("relation-key-overflow"),b=e=>Array.isArray(e)?e.map(t=>t??{}):[],R=e=>{if(e.length===1){const[t]=e;return t??{}}return e.length===0?{}:{AND:e}},y=e=>{if(e===null||typeof e!="object"||Array.isArray(e))return!1;const t=Object.keys(e);return t.length>0&&t.every(n=>T.has(n))},u=(e,t,n)=>{const r=t.tables[n]?.relationMap??{};return Object.keys(e).some(s=>{const a=e[s];return s==="AND"||s==="OR"?b(a).some(o=>u(o,t,n)):s==="NOT"?u(a??{},t,n):!!r[s]&&y(a)})},K=(e,t,n,r)=>{if(e&&u(e,t,n))throw new h("INTERNAL",`relation-crossing predicates are not supported in ${r}() — use them in findMany/findFirst or an RLS read policy`)},P=async(e,t,n,r,s)=>{const a=await d(t,e.table,r),{page:o}=await r.fetcher(e.table,{baseWhere:r.relationBaseWhere?.(e.table),relationBaseWhere:r.relationBaseWhere,where:a}),i=w(o,n);if(i.length>r.maxRelationKeys){if(s)return l;throw new h("INTERNAL",`relation predicate on "${e.table}" matched ${String(i.length)} rows, exceeding the ${String(r.maxRelationKeys)}-key limit; narrow the predicate (a same-shard EXISTS push-down lifts this cap)`)}return i},$=async(e,t,n,r,s)=>{const a=p(e),{clause:o,project:i}=j(t),c=await P(t,a.negateChild?{NOT:n}:n,i,r,s);return c===l?l:a.negated?a.nullDisjunct?{OR:[{[o]:{notIn:c}},{[o]:{isNull:!0}}]}:{[o]:{notIn:c}}:{[o]:{in:c}}},m=async(e,t,n,r,s)=>{const a=p(e),o=s.relationBaseWhere?.(t.table),i=a.negateChild?{NOT:n}:n,A={childWhere:await d(o?{AND:[o,i]}:i,t.table,s),negated:a.negated,parentTable:r,relation:t};return{[N]:A}},k=(e,t,n)=>{const r=g[e];if(r&&r.kind!==n.kind)throw new h("INTERNAL",`relation operator "${e}" requires a to-${r.kind} relation, but "${t}" is to-${n.kind}`)},I=async(e,t,n,r,s)=>{const a=[];for(const o of Object.keys(n)){k(o,e,t);const i=n[o]??{},c=s.canPushExists?.(t)??!1;if(c&&s.existsPushMode==="always"){a.push(await m(o,t,i,r,s));continue}const f=await $(o,t,i,s,c);f===l?a.push(await m(o,t,i,r,s)):a.push(f)}return R(a)},L=async(e,t,n,r)=>{if(e==="AND"||e==="OR"){const a=[];for(const o of b(t))a.push(await d(o,n,r));return{[e]:a}}if(e==="NOT")return{NOT:await d(t??{},n,r)};const s=r.schema.tables[n]?.relationMap?.[e];return s&&y(t)?I(e,s,t,n,r):{[e]:t}},d=async(e,t,n)=>{const r=[];for(const s of Object.keys(e))r.push(await L(s,e[s],t,n));return R(r)},v=async(e,t)=>!e||!u(e,t.schema,t.tableName)?e:d(e,t.tableName,{canPushExists:t.canPushExists,existsPushMode:t.existsPushMode??"auto",fetcher:t.fetcher,maxRelationKeys:t.maxRelationKeys??S,relationBaseWhere:t.relationBaseWhere,schema:t.schema}),O=(e,t,n)=>{for(const r of e){const s=E(r,t,n);if(s)return s}},M=(e,t,n,r)=>{if(e==="AND"||e==="OR")return O(b(t),n,r);if(e==="NOT")return O([t??{}],n,r);const s=n.tables[r]?.relationMap?.[e];if(!(!s||!y(t)))return n.tables[s.table]?.shardMode?.kind==="shardBy"?{relation:e,target:s.table}:O(Object.values(t),n,s.table)},E=(e,t,n)=>{for(const r of Object.keys(e)){const s=M(r,e[r],t,n);if(s)return s}},B=(e,t,n)=>{if(!e)return;const r=E(e,t,n);if(r)throw Object.assign(new Error(`shape on "${n}" joins the sharded table "${r.target}" via relation "${r.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 "${r.target}" to .global() so it is served through the latency-tiered D1 shape tier.`),{code:"SHAPE_CROSS_SHARD_JOIN",name:"LunoraError",status:400})};export{S as DEFAULT_MAX_RELATION_KEYS,K as assertFlatPredicate,B as assertShapeShardable,u as containsRelationPredicate,y as isRelationPredicate,v as resolveRelationPredicates};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{toErrorBody as P,LunoraError as x}from"@lunora/errors";import{e as v,d as b}from"./wire-codec-BU9T2xJ7.mjs";import{e as S,v as L,R as I,s as M,a as T,b as D}from"./sibling-channel-BRZpLiDA.mjs";import{relayName as u,DEFAULT_PROMOTION_THRESHOLDS as w,nextPromotionState as O,shapeRoutingKey as R,parseRelayName as k,clampPromotionThresholds as N}from"./DEFAULT_PROMOTION_THRESHOLDS-DVTD9iu0.mjs";import{encodeRowsPatch as C,buildPokeFrames as E}from"./buildPokeFrames-BXejpiII.mjs";import{awaitWsDrain as F,trySendFrame as _}from"./awaitWsDrain-kSGvAfw1.mjs";import{stableWireKey as m}from"./stableWireKey-BYB5GQJa.mjs";const U=2,W=8,g={},K=l=>{throw new x("INTERNAL",`unhandled relay frame: ${JSON.stringify(l)}`)},Y=l=>Response.json(l,{headers:{"content-type":"application/json"}}),f=()=>new Response(null,{status:204});class A{constructor(e,t){this.host=e,this.roleId=t}host;roleId;async handleControl(e){let t;try{t=await e.text()}catch{return new Response("bad request",{status:400})}if(!await L(this.host.env(),e.headers.get(I),t))return new Response("forbidden",{status:403});let s;try{s=JSON.parse(t)}catch{return new Response("bad request",{status:400})}switch(s.type){case"relay_attach":return this.onAttach(s.relayIndex),f();case"relay_detach":return this.onDetach(s.relayIndex),f();case"relay_frame":return this.host.deliverWhisperLocal(s.topic,s.frame,void 0),await this.onWhisperFrame(s),f();case"relay_shape_poke":{const r=this.host.getWebSockets().length,o=Date.now(),a=this.onShapePoke({...s,args:b(s.args)});return this.host.recordShapePokeFanout(r,a,Date.now()-o),f()}case"relay_shape_subscribe":return Y(this.onShapeSubscribe({...s,args:b(s.args)}));default:return K(s)}}maxRelays(){return S(this.host.env(),"LUNORA_MAX_RELAYS",W)}canAddressSiblings(){return this.siblingStub(this.roleId.ownerKey)!==void 0}siblingStub(e){return M(this.host.env(),this.host.shardBinding(),e)}async postRelayMessage(e,t){await this.requestRelayMessage(e,t)}async requestRelayMessage(e,t){const s=this.siblingStub(e);if(s===void 0)return;const r=JSON.stringify(t),o={"content-type":"application/json","x-lunora-shard-binding":this.host.shardBinding()??""},a=T(this.host.env());a!==void 0&&(o[I]=await D(a,r));try{return await s.fetch("https://relay.internal/_lunora/relay",{body:r,headers:o,method:"POST"})}catch{return}}}class H extends A{shapeUniformCache=new Map;relaySetCache;relayShapeRegistry=new Map;relayShapeProxies=new Map;promotionState="owned";constructor(e,t){super(e,{ownerKey:t})}async forwardWhisper(e,t){if(!this.canAddressSiblings())return;const s=this.ownerRelaySet();s.size!==0&&await Promise.all([...s].map(r=>this.postRelayMessage(u(this.roleId.ownerKey,r),{frame:t,topic:e,type:"relay_frame"})))}async onFlush(e,t){await Promise.all([this.multicastShapePokes(e,t),this.proxyShapePokes(e,t)])}seedRelayShape(){return Promise.resolve(void 0)}announce(){return Promise.resolve()}announceDrain(){return Promise.resolve()}relayCount(){const e=this.host.getWebSockets().length,t=S(this.host.env(),"LUNORA_RELAY_THRESHOLD",w.tUp),s=S(this.host.env(),"LUNORA_RELAY_COLLAPSE_THRESHOLD",w.tDown);if(this.promotionState=O(this.promotionState,e,N(t,s)),this.promotionState==="owned")return 0;const r=S(this.host.env(),"LUNORA_RELAY_FAN",U);return Math.min(this.maxRelays(),Math.max(1,r))}isShapeRelayUniform(e,t){const s=R(e,t),r=this.shapeUniformCache.get(s);if(r!==void 0)return r;const o=this.probeShapeRelayUniform(e,t);return this.shapeUniformCache.set(s,o),o}onAttach(e){this.addRelayToSet(e)}onDetach(e){this.removeRelayFromSet(e)}async onWhisperFrame(e){await Promise.all([...this.ownerRelaySet()].filter(t=>t!==e.originRelay).map(t=>this.postRelayMessage(u(this.roleId.ownerKey,t),{frame:e.frame,topic:e.topic,type:"relay_frame"})))}onShapeSubscribe(e){return this.buildShapeSeedFrames(e)}onShapePoke(){return 0}buildShapePoke(e,t,s,r,o){let a;try{a=this.host.resolveShape(e.name,e.args,t)}catch{return}if(a===void 0||a.global===!0||!s.has(a.table))return;const n=e,c=n.cursor,i=this.host.buildShapeDiff(a,c,r);if(i.length!==0)return n.cursor=r,{args:v(e.args),checkpoint:r,epoch:o,fromCursor:c,name:e.name,rowsPatch:C(i),type:"relay_shape_poke"}}async multicastShapePokes(e,t){if(this.relayShapeRegistry.size===0)return;const s=this.ownerRelaySet();if(s.size===0)return;const r=this.host.currentCdcEpoch(),o=[];for(const a of this.relayShapeRegistry.values()){const n=this.buildShapePoke(a,g,e,t,r);if(n)for(const c of s)o.push(this.postRelayMessage(u(this.roleId.ownerKey,c),n))}await Promise.all(o)}async proxyShapePokes(e,t){if(this.relayShapeProxies.size===0)return;const s=this.host.currentCdcEpoch(),r=[];for(const o of this.relayShapeProxies.values()){const a=this.buildShapePoke(o,o.identity,e,t,s);a&&r.push(this.postRelayMessage(u(this.roleId.ownerKey,o.relayIndex),{...a,targetConnectionId:o.connectionId}))}await Promise.all(r)}buildShapeSeedFrames(e){const t={identity:e.identity,userId:e.userId};let s;try{s=this.host.resolveShape(e.name,e.args,t)}catch(h){const{body:d}=P(h,{fallbackCode:"SHAPE_RESOLVE_FAILED",redactedMessage:"shape resolution failed"});return{error:{code:d.code,message:d.message}}}if(s===void 0||s.global===!0)return{error:{code:"SHAPE_NOT_FOUND",message:`shape not relayable: ${e.name}`}};e.relayIndex!==void 0&&this.addRelayToSet(e.relayIndex);const{baseCheckpoint:r,cursor:o,epoch:a,rowsPatch:n}=this.host.computeOpLogShapeSeed({args:e.args,name:e.name,sinceEpoch:e.sinceEpoch,sinceSeq:e.sinceSeq},s);let c=o;if(this.isShapeRelayUniform(e.name,e.args)){const h=R(e.name,e.args);let d=this.relayShapeRegistry.get(h);d===void 0&&(d={args:e.args,cursor:o,name:e.name},this.relayShapeRegistry.set(h,d)),c=d.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:o,epoch:a,identity:t,name:e.name,relayIndex:e.relayIndex,subId:e.subId});const i=E([{rowsPatch:n,shapeId:e.subId}],{baseCheckpoint:r,checkpoint:o,epoch:a,lastMutationId:void 0,pokeId:this.host.nextPokeId()});return{cursor:c,epoch:a,frames:i}}ensureRelayTable(){this.host.sql().exec("CREATE TABLE IF NOT EXISTS __lunora_relays (idx INTEGER PRIMARY KEY)")}ownerRelaySet(){if(this.relaySetCache===void 0){this.ensureRelayTable();const e=this.host.sql().exec("SELECT idx FROM __lunora_relays").toArray();this.relaySetCache=new Set(e.map(t=>Number(t.idx)))}return this.relaySetCache}addRelayToSet(e){this.ensureRelayTable(),this.host.sql().exec("INSERT OR IGNORE INTO __lunora_relays (idx) VALUES (?)",e),this.ownerRelaySet().add(e)}removeRelayFromSet(e){this.ensureRelayTable(),this.host.sql().exec("DELETE FROM __lunora_relays WHERE idx = ?",e);const t=this.ownerRelaySet();t.delete(e);for(const[s,r]of this.relayShapeProxies)r.relayIndex===e&&this.relayShapeProxies.delete(s);t.size===0&&(this.relayShapeRegistry.clear(),this.shapeUniformCache.clear())}probeShapeRelayUniform(e,t){let s;try{s=this.host.resolveShape(e,t,g)}catch{return!1}if(s===void 0||s.global===!0||this.host.rlsMetadata().policies.some(i=>i.on==="read"&&i.table===s.table)||this.tableHasAnyMask(s.table))return!1;const r=m(s.effectiveWhere),o=m(s.columns);let a=!1;const n=i=>{const h={groups:[`grp_${i}`],roles:[i],sub:`__lunora_probe_${i}__`};return{identity:new Proxy(h,{get:(y,p)=>typeof p=="symbol"||p in y?Reflect.get(y,p):`${i}:${p}`,getOwnPropertyDescriptor:(y,p)=>(a=!0,Reflect.getOwnPropertyDescriptor(y,p)),has:(y,p)=>typeof p=="symbol"?Reflect.has(y,p):!0,ownKeys:y=>(a=!0,Reflect.ownKeys(y))}),userId:`__lunora_probe_${i}__`}};return[g,n("a"),n("b")].every(i=>{let h;try{h=this.host.resolveShape(e,t,i)}catch{return!1}return h!==void 0&&h.global!==!0&&h.table===s.table&&m(h.effectiveWhere)===r&&m(h.columns)===o})&&!a}tableHasAnyMask(e){return this.host.maskMetadata().columns.some(t=>t.table===e)}}class $ extends A{relayAnnounced=!1;shapeRelayMemos=new WeakMap;constructor(e,t,s){super(e,{ownerKey:t,relayIndex:s})}async forwardWhisper(e,t){this.canAddressSiblings()&&await this.postRelayMessage(this.roleId.ownerKey,{frame:t,originRelay:this.roleId.relayIndex,topic:e,type:"relay_frame"})}onFlush(){return Promise.resolve()}async seedRelayShape(e,t,s,r){if(!this.canAddressSiblings())return{code:"RELAY_MISCONFIGURED",message:"relay cannot address its owner"};await this.announce();const o={args:v(s.args??{}),connectionId:this.host.readAttachment(e).connectionId,identity:r.identity,name:s.name,relayIndex:this.roleId.relayIndex,sinceEpoch:s.sinceEpoch,sinceSeq:s.sinceSeq,subId:t,type:"relay_shape_subscribe",userId:r.userId},a=await this.requestRelayMessage(this.roleId.ownerKey,o);if(a===void 0)return{code:"RELAY_SEED_FAILED",message:"owner did not answer the shape seed"};let n;try{n=await a.json()}catch{return{code:"RELAY_SEED_FAILED",message:"malformed shape seed from owner"}}if(n.error!==void 0)return n.error;if(n.frames===void 0)return{code:"RELAY_SEED_FAILED",message:"owner returned no shape frames"};await F(e);for(const c of n.frames)_(e,c);return this.recordRelayShapeMemo(e,t,n.cursor??0,n.epoch),"ok"}async announce(){if(this.relayAnnounced||!this.canAddressSiblings())return;this.relayAnnounced=!0,(await this.requestRelayMessage(this.roleId.ownerKey,{relayIndex:this.roleId.relayIndex,type:"relay_attach"}))?.ok||(this.relayAnnounced=!1)}async announceDrain(e){this.canAddressSiblings()&&(this.host.getWebSockets().some(t=>t!==e)||(this.relayAnnounced=!1,await this.postRelayMessage(this.roleId.ownerKey,{relayIndex:this.roleId.relayIndex,type:"relay_detach"})))}relayCount(){return 0}isShapeRelayUniform(){return!1}onAttach(){}onDetach(){}onWhisperFrame(){return Promise.resolve()}onShapeSubscribe(){return{error:{code:"RELAY_CANNOT_SEED",message:"a relay has no op-log to seed from"}}}onShapePoke(e){return this.deliverShapePoke(e)}recordRelayShapeMemo(e,t,s,r){let o=this.shapeRelayMemos.get(e);o===void 0&&(o=new Map,this.shapeRelayMemos.set(e,o)),o.set(t,{cursor:s,epoch:r})}deliverShapePoke(e){const t=R(e.name,e.args);let s=0;for(const r of this.host.getWebSockets()){const o=this.host.readAttachment(r),{shapes:a}=o,n=this.shapeRelayMemos.get(r);if(!(a===void 0||n===void 0)&&!(e.targetConnectionId!==void 0&&o.connectionId!==e.targetConnectionId))for(const[c,i]of Object.entries(a)){const h=n.get(c);if(h?.cursor!==e.fromCursor||h.epoch!==e.epoch||R(i.name,i.args)!==t)continue;const d=E([{rowsPatch:e.rowsPatch,shapeId:c}],{baseCheckpoint:void 0,checkpoint:e.checkpoint,epoch:e.epoch,lastMutationId:void 0,pokeId:this.host.nextPokeId()},{preEncoded:!0});for(const y of d)_(r,y);n.set(c,{cursor:e.checkpoint,epoch:e.epoch}),s+=1}}return s}}const Q=l=>{const e=l.doName();if(e===void 0)return;const t=k(e);return t===void 0?new H(l,e):new $(l,t.ownerKey,t.relayIndex)};export{W as DEFAULT_MAX_RELAYS,H as OwnerRelay,$ as RelayMember,Q as createRelayLink};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as m}from"@lunora/errors";import{stableWireKey as a}from"./stableWireKey-BYB5GQJa.mjs";const i="::relay::",f=(t,n)=>`${t}${i}${String(n)}`,s=t=>{const n=t.lastIndexOf(i);if(n===-1)return;const o=t.slice(0,n),e=t.slice(n+i.length),r=Number(e);if(!(o.length===0||!Number.isInteger(r)||r<0||String(r)!==e))return{ownerKey:o,relayIndex:r}},d=(t,n)=>a({args:n??{},name:t}),c={tDown:4e3,tUp:8e3},l=(t,n,o=c)=>{if(o.tDown>=o.tUp)throw new m("INTERNAL",`invalid promotion thresholds: tDown (${String(o.tDown)}) must be < tUp (${String(o.tUp)})`);return t==="owned"?n>=o.tUp?"promoted":"owned":n<o.tDown?"owned":"promoted"},g=(t,n)=>n<t?{tDown:n,tUp:t}:{tDown:Math.min(Math.max(1,Math.floor(t/2)),t-1),tUp:t},N=(t,n,o)=>{if(t<=n||n<=0)return 0;const e=t-n,r=Math.ceil(e/n);return Math.min(r,Math.max(0,o))};export{c as DEFAULT_PROMOTION_THRESHOLDS,i as RELAY_NAME_INFIX,g as clampPromotionThresholds,l as nextPromotionState,s as parseRelayName,N as relayCountFor,f as relayName,d as shapeRoutingKey};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as i}from"@lunora/errors";import{e}from"./estimate-bytes-CzG5x1f8.mjs";const r={maxReadRows:1e5,maxWrittenBytes:32*1024*1024,maxWrittenRows:5e4};class w{readRows=0;writtenRows=0;writtenBytes=0;limits;constructor(t={}){this.limits={...r,...t}}recordRead(t){if(this.readRows+=t,this.readRows>this.limits.maxReadRows)throw new i("TRANSACTION_LIMIT_EXCEEDED",`this transaction read ${String(this.readRows)} documents, over the ${String(this.limits.maxReadRows)}-document limit`)}recordWrite(t){const s=e(t);if(s===void 0)throw new i("BAD_REQUEST","this document is not JSON-serializable (cyclic or non-JSON value); it cannot be written");if(this.writtenRows+=1,this.writtenBytes+=s,this.writtenRows>this.limits.maxWrittenRows)throw new i("TRANSACTION_LIMIT_EXCEEDED",`this transaction wrote ${String(this.writtenRows)} documents, over the ${String(this.limits.maxWrittenRows)}-document limit`);if(this.writtenBytes>this.limits.maxWrittenBytes)throw new i("TRANSACTION_LIMIT_EXCEEDED",`this transaction wrote ${String(this.writtenBytes)} bytes, over the ${String(this.limits.maxWrittenBytes)}-byte limit`)}headroom(){return{readRows:this.readRows,remainingReadRows:Math.max(0,this.limits.maxReadRows-this.readRows),remainingWrittenBytes:Math.max(0,this.limits.maxWrittenBytes-this.writtenBytes),remainingWrittenRows:Math.max(0,this.limits.maxWrittenRows-this.writtenRows),writtenBytes:this.writtenBytes,writtenRows:this.writtenRows}}}export{r as DEFAULT_TRANSACTION_LIMITS,w as TransactionHeadroomTracker};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{toErrorBody as f,LunoraError as S}from"@lunora/errors";import{e as k}from"./wire-codec-BU9T2xJ7.mjs";import{readStreamRun as p,deleteStreamRun as T,claimStreamRun as _,appendStreamChunk as w,finishStreamRun as R,trimStreamRuns as A,readStreamChunks as y}from"./appendStreamChunk-CH4e4nJn.mjs";const E=5e4,g=64*1024*1024,b=864e5,M=36e5,N=(d,e)=>d===void 0||e.live?"attach":d.status==="complete"||d.status==="error"?e.resuming?"replay-terminal":"reclaim":e.resuming?"interrupted":"reclaim";class U{lastTrimAt=0;runs=new Map;sql;waitUntil;constructor(e){this.sql=e.sql,this.waitUntil=e.waitUntil}async attach(e){try{await this.attachOrThrow(e)}catch(r){const{body:t,redacted:i}=f(r,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"internal error"});i&&console.error("[@lunora/shard-engine] durable stream attach failed:",r),e.sink.fail({code:t.code,message:t.message})}}detach(e,r){this.runs.get(e)?.sinks.delete(r)}isLive(e){return this.runs.has(e)}async attachOrThrow(e){const r=this.sql(),{runKey:t,sinceChunk:i,sink:o}=e,s=p(r,t),u=i>0,a=this.runs.get(t),n=N(s,{live:a!==void 0,resuming:u}),c=()=>{for(const h of y(r,t,i))if(!o.chunk({data:JSON.parse(h.dataJson),seq:h.seq}))return!1;return!0};if(n==="replay-terminal"){c()&&(s?.status==="error"?o.fail({code:s.errorCode??"INTERNAL_SERVER_ERROR",message:s.error??"stream failed"}):o.complete());return}if(n==="interrupted"){c()&&o.fail({code:"STREAM_INTERRUPTED",message:"the producer for this durable stream did not survive; start a new run"});return}if(a){c()&&a.sinks.add(o);return}n==="reclaim"&&T(r,t),this.trim(r),_(r,t,Date.now(),e.ttlMs??b);const l={sinks:new Set([o])};this.runs.set(t,l);const m=this.produce(t,e.iterator,l);this.waitUntil?.(m),await m}async produce(e,r,t){const i=this.sql(),o=new AbortController;let s=0,u=0;try{for await(const a of r(o.signal)){const n=k(a),c=JSON.stringify(n);if(s+=1,u+=c.length,s>E||u>g)throw new S("STREAM_TOO_LONG",`durable stream exceeded its ceiling (${String(E)} chunks / ${String(g)} bytes); yield less, or drop \`durable\``,{status:507});w(i,e,s,c);for(const l of t.sinks)l.chunk({data:n,seq:s})||t.sinks.delete(l)}R(i,e,"complete",s);for(const a of t.sinks)a.complete()}catch(a){const{body:n,redacted:c}=f(a,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"internal error"});c&&console.error("[@lunora/shard-engine] unhandled durable stream error:",a),R(i,e,"error",s,{code:n.code,message:n.message});for(const l of t.sinks)l.fail({code:n.code,message:n.message})}finally{this.runs.delete(e)}}trim(e){const r=Date.now();if(!(r-this.lastTrimAt<=M)){this.lastTrimAt=r;try{A(e,r)}catch{}}}}export{U as DurableStreamRunner,g as MAX_DURABLE_STREAM_BYTES,E as MAX_DURABLE_STREAM_CHUNKS,N as decideDurableAttach};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const m="0123456789bcdefghjkmnpqrstuvwxyz",k=9,p=63710088e-1,d=Math.PI/180,f=[Number.POSITIVE_INFINITY,5009400,1252300,156500,39100,4900,1200,152.9,38.2,4.77,1.19,.149,.037],S=f.map((t,n)=>n%2===0?t/2:t),I=.01,C=Math.acos(I)/d,z=2,_=t=>t/p/d,R=t=>{const n=5*t;return{latBands:2**Math.floor(n/2),lngSectors:2**Math.ceil(n/2)}},T=t=>Math.min(Math.max(Math.trunc(t),1),12),b=(t,n)=>{const a=T(n);let s=-90,o=90,e=-180,c=180,r="",g=0,l=0,u=!0;for(;r.length<a;){if(u){const h=(e+c)/2;t.lng>=h?(l=l*2+1,e=h):(l*=2,c=h)}else{const h=(s+o)/2;t.lat>=h?(l=l*2+1,s=h):(l*=2,o=h)}u=!u,g<4?g+=1:(r+=m[l]??"0",g=0,l=0)}return r},v=(t,n)=>Math.min(90,Math.abs(t)+_(n)),j=(t,n)=>{const a=(n.lat-t.lat)*d,s=(n.lng-t.lng)*d,o=t.lat*d,e=n.lat*d,c=Math.sin(a/2)**2+Math.cos(o)*Math.cos(e)*Math.sin(s/2)**2;return 2*p*Math.asin(Math.min(1,Math.sqrt(c)))},y=(t,n)=>{const a=Math.max(Math.cos(v(n,t)*d),I);for(let s=f.length-1;s>=1;s-=1){const o=f[s],e=S[s];if(o!==void 0&&e!==void 0&&o*a>=t&&e>=t)return s}return 1},B={east:["bc01fg45238967deuvhjyznpkmstqrwx","p0r21436x8zb9dcf5h7kjnmqesgutwvy"],north:["p0r21436x8zb9dcf5h7kjnmqesgutwvy","bc01fg45238967deuvhjyznpkmstqrwx"],south:["14365h7k9dcfesgujnmqp0r2twvyx8zb","238967debc01fg45kmstqrwxuvhjyznp"],west:["238967debc01fg45kmstqrwxuvhjyznp","14365h7k9dcfesgujnmqp0r2twvyx8zb"]},P={east:["bcfguvyz","prxz"],north:["prxz","bcfguvyz"],south:["028b","0145hjnp"],west:["0145hjnp","028b"]},i=(t,n)=>{const a=t.toLowerCase(),s=a.at(-1)??"";let o=a.slice(0,-1);const e=a.length%2===0?0:1;return P[n][e].includes(s)&&o!==""&&(o=i(o,n)),o+(m[B[n][e].indexOf(s)]??"")},q=(t,n,a)=>{const s=Math.min(a,z),{latBands:o,lngSectors:e}=R(s),c=180/o,r=360/e,g=_(n),l=Math.max(-90,t.lat-g),u=Math.min(90,t.lat+g),h=new Set;for(let M=0;M<o;M+=1){const w=-90+M*c;if(w+c<l||w>u)continue;const x=w+c/2;for(let E=0;E<e;E+=1){const L=-180+(E+.5)*r;h.add(b({lat:x,lng:L},s))}}return[...h]},A=(t,n)=>{const a=Math.max(n,1),s=y(a,t.lat);if(v(t.lat,a)>=C)return q(t,a,s);const e=b(t,s),c=i(e,"north"),r=i(e,"south"),g=[e,c,r,i(e,"east"),i(e,"west"),i(c,"east"),i(c,"west"),i(r,"east"),i(r,"west")];return[...new Set(g)]},G=(t,n)=>t.lat>=n.sw.lat&&t.lat<=n.ne.lat&&t.lng>=n.sw.lng&&t.lng<=n.ne.lng,D=t=>({lat:(t.sw.lat+t.ne.lat)/2,lng:(t.sw.lng+t.ne.lng)/2}),H=t=>{const n=D(t);return A(n,Math.max(j(n,t.ne),1))};export{k as GEO_DEFAULT_PRECISION,D as boundingBoxCenter,H as boundingBoxGeohashes,A as coveringGeohashes,b as encodeGeohash,j as haversineMeters,G as pointInBoundingBox};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import{sql as e}from"drizzle-orm";import{runDrizzle as i}from"./runDrizzle-it6rL9bR.mjs";const r="__global_shape_snapshot",T=n=>{i(n,e`CREATE TABLE IF NOT EXISTS ${e.identifier(r)} (
|
|
2
|
+
connection_id TEXT NOT NULL,
|
|
3
|
+
sub_id TEXT NOT NULL,
|
|
4
|
+
members TEXT NOT NULL,
|
|
5
|
+
PRIMARY KEY (connection_id, sub_id)
|
|
6
|
+
)`)},b=(n,o,t)=>{const s=i(n,e`SELECT members FROM ${e.identifier(r)} WHERE connection_id = ${o} AND sub_id = ${t} LIMIT 1`).toArray()[0]?.members;if(s===void 0)return new Map;try{const c=JSON.parse(s);return c===null||typeof c!="object"?new Map:new Map(Object.entries(c))}catch{return new Map}},p=(n,o,t,a)=>{const s=JSON.stringify(Object.fromEntries(a));i(n,e`INSERT INTO ${e.identifier(r)} (connection_id, sub_id, members) VALUES (${o}, ${t}, ${s})
|
|
7
|
+
ON CONFLICT(connection_id, sub_id) DO UPDATE SET members = excluded.members`)},S=(n,o,t)=>{i(n,e`DELETE FROM ${e.identifier(r)} WHERE connection_id = ${o} AND sub_id = ${t}`)},m=(n,o)=>{i(n,e`DELETE FROM ${e.identifier(r)} WHERE connection_id = ${o}`)};export{r as GLOBAL_SHAPE_SNAPSHOT_TABLE,S as deleteGlobalShapeSnapshot,m as deleteGlobalShapeSnapshotsForConnection,T as migrateGlobalShapeSnapshot,b as readGlobalShapeSnapshot,p as writeGlobalShapeSnapshot};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import{sql as t}from"drizzle-orm";import{runDrizzle as n}from"./runDrizzle-it6rL9bR.mjs";const r="__idempotency",m=i=>{n(i,t`CREATE TABLE IF NOT EXISTS ${t.identifier(r)} (
|
|
2
|
+
identity TEXT NOT NULL,
|
|
3
|
+
mutation_id TEXT NOT NULL,
|
|
4
|
+
result_json TEXT NOT NULL,
|
|
5
|
+
ts REAL NOT NULL,
|
|
6
|
+
PRIMARY KEY (identity, mutation_id)
|
|
7
|
+
)`)},L=(i,e,s)=>{const o=n(i,t`SELECT result_json, ts FROM ${t.identifier(r)} WHERE identity = ${e} AND mutation_id = ${s} LIMIT 1`).toArray()[0];return o===void 0?void 0:{resultJson:o.result_json,ts:o.ts}},N=(i,e,s,E,o)=>{n(i,t`INSERT OR IGNORE INTO ${t.identifier(r)} (identity, mutation_id, result_json, ts) VALUES (${e}, ${s}, ${E}, ${o})`)},I=(i,e)=>{n(i,t`DELETE FROM ${t.identifier(r)} WHERE ts < ${e}`)};export{r as IDEMPOTENCY_TABLE,m as migrateIdempotency,L as readIdempotent,I as trimIdempotent,N as writeIdempotent};
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import{runSql as c,decodeJsonColumn as a,orNull as o}from"./runDrizzle-it6rL9bR.mjs";const e="__lunora_mail",l=500,i=256*1024,n=t=>t!==void 0&&t.length>i?`${t.slice(0,i)}
|
|
2
|
+
… [truncated by the dev mail catcher]`:t,s=t=>t===void 0?null:JSON.stringify(t),_=t=>{c(t,`CREATE TABLE IF NOT EXISTS "${e}" (
|
|
3
|
+
id TEXT PRIMARY KEY,
|
|
4
|
+
captured_at INTEGER NOT NULL,
|
|
5
|
+
from_addr TEXT,
|
|
6
|
+
to_addrs TEXT NOT NULL,
|
|
7
|
+
cc_addrs TEXT,
|
|
8
|
+
bcc_addrs TEXT,
|
|
9
|
+
reply_to TEXT,
|
|
10
|
+
subject TEXT NOT NULL,
|
|
11
|
+
html TEXT,
|
|
12
|
+
body_text TEXT,
|
|
13
|
+
headers TEXT
|
|
14
|
+
)`)},N=(t,r,T)=>{_(t);const E=crypto.randomUUID();return c(t,`INSERT INTO "${e}" (id, captured_at, from_addr, to_addrs, cc_addrs, bcc_addrs, reply_to, subject, html, body_text, headers)
|
|
15
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,E,T,o(r.from),JSON.stringify(r.to),s(r.cc),s(r.bcc),o(r.replyTo),r.subject,o(n(r.html)),o(n(r.text)),s(r.headers)),c(t,`DELETE FROM "${e}"
|
|
16
|
+
WHERE id NOT IN (
|
|
17
|
+
SELECT id FROM "${e}" ORDER BY captured_at DESC, id DESC LIMIT ?
|
|
18
|
+
)`,l),{id:E}},u=(t,r={})=>{_(t);const T=Math.min(Math.max(r.limit??50,1),l);return{entries:c(t,`SELECT * FROM "${e}" ORDER BY captured_at DESC, id DESC LIMIT ?`,T).toArray().map(d=>({bcc:a(d.bcc_addrs),capturedAt:d.captured_at,cc:a(d.cc_addrs),from:d.from_addr??void 0,headers:a(d.headers),html:d.html??void 0,id:d.id,replyTo:d.reply_to??void 0,subject:d.subject,text:d.body_text??void 0,to:a(d.to_addrs)??d.to_addrs}))}},M=t=>(_(t),c(t,`DELETE FROM "${e}"`),{cleared:!0});export{l as MAIL_RETENTION,e as MAIL_TABLE,i as MAX_BODY_CHARS,M as clearCapturedMail,_ as ensureMailTable,u as readCapturedMail,N as recordCapturedMail};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{LunoraError as u}from"@lunora/errors";const g=/^(?:explain\s+(?:query\s+plan\s+)?)?(?:select|with)\b/iu,f=/\b(?:alter|attach|create|delete|detach|drop|insert|pragma|reindex|replace|truncate|update|vacuum)\b/iu,h=/^\w+/u,m=/;\s*$/u,E=/\s/u,L=(n,e)=>{let t=e+2;for(;t<n.length&&n[t]!==`
|
|
2
|
+
`;)t+=1;return t},S=(n,e)=>{const t=n.indexOf("*/",e+2);return t===-1?-1:t+2},p=n=>{let e=0;for(;e<n.length;){const t=n[e];if(t!==void 0&&E.test(t))e+=1;else if(t==="-"&&n[e+1]==="-")e=L(n,e);else if(t==="/"&&n[e+1]==="*"){const s=S(n,e);if(s===-1)break;e=s}else break}return e},d=n=>{const e=p(n),t=n.slice(e).trimEnd();if(t==="")return{code:"SQL_EMPTY",message:"the query is empty"};const s=t.replace(m,""),c=s.indexOf(";");if(c!==-1)return{code:"SQL_MULTIPLE_STATEMENTS",length:1,message:"only a single statement may be run",offset:e+c};const i="the SQL editor is read-only — only SELECT / WITH / EXPLAIN queries are allowed";if(!g.test(s))return{code:"SQL_NOT_READONLY",length:h.exec(s)?.[0].length??1,message:i,offset:e};const o=f.exec(s);if(o!==null)return{code:"SQL_NOT_READONLY",length:o[0].length,message:`${i} (\`${o[0].toUpperCase()}\` is not allowed)`,offset:e+o.index}},l=1e3,A=n=>{const e=d(n);if(e!==void 0)throw new u(e.code,e.message,{status:400})},O=(n,e)=>{A(e);const t=n.exec(e).toArray(),s=t.length>l?t.slice(0,l):t;return{columns:s.length>0?Object.keys(s[0]):[],rowCount:t.length,rows:s,truncated:t.length>l}},y=/near "([^"]*)": syntax error/iu,N=/^SCAN (?:TABLE )?(?!CONSTANT\b|SUBQUERY\b)([^\s(]+)/u,x=(n,e)=>{if(e==="")return{};const t=n.indexOf(e);return t===-1?{}:{length:e.length,offset:t}},_=(n,e)=>{const t=d(e);if(t!==void 0)return{diagnostics:t.code==="SQL_EMPTY"?[]:[{length:t.length,message:t.message,offset:t.offset,severity:"error",source:"gate"}],plan:[]};let s;try{s=n.exec(`EXPLAIN QUERY PLAN ${e}`).toArray().map(o=>{const{detail:r}=o;return typeof r=="string"?r:""}).filter(o=>o!=="")}catch(o){const r=o instanceof Error?o.message:String(o),a=y.exec(r);return{diagnostics:[{...a?x(e,a[1]??""):{},message:r,severity:"error",source:"syntax"}],plan:[]}}const c=[],i=new Set;for(const o of s){const r=N.exec(o);if(r){const a=r[1]??"";i.has(a)||(i.add(a),c.push({message:`full table scan on \`${a}\` — this query reads every row`,severity:"warning",source:"plan"}))}}return{diagnostics:c,plan:s}};export{l as MAX_SQL_ROWS,A as assertReadonly,_ as lintReadonlySql,O as runReadonlySql};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as E}from"@lunora/errors";import{s as Ut,c as Pt,j as Oe,a as Gt,y as Ae,h as Ht}from"./ctx-db-companions-lTt-rvKG.mjs";import{sql as r}from"drizzle-orm";import{d as Nt}from"./wire-codec-BU9T2xJ7.mjs";import{throwingScheduler as jt,aggregateSqlFunction as ve,normalizeCountArgument as Kt}from"./AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs";import{aggregateTableName as Le,encodeAggregateKey as Fe,readAggregateValue as We}from"./aggregateTableName-Cy5e03oz.mjs";import{mergeWhere as z,CountRlsUnsupportedError as Be,selectIndexForGroupBy as Ot,selectIndexForCount as Qt,selectIndexForAggregate as zt}from"./CountRlsUnsupportedError-Bdfupt3g.mjs";import{backfillSearchIndexesForTable as Jt}from"./backfillAggregateIndexes-DVQ2sVuV.mjs";import{backfillAggregateIndexes as Br,backfillRankIndexes as qr,backfillSearchIndexes as Ur}from"./backfillAggregateIndexes-DVQ2sVuV.mjs";import{appendCdcChange as Vt}from"./CDC_LOG_TABLE-B58N8NQO.mjs";import{CDC_LOG_TABLE as Gr,applyCdcChanges as Hr,bumpCdcEpoch as Nr,minCdcSeq as jr,readCdcChanges as Kr,readCdcCursor as Or,readCdcEpoch as Qr,trimCdcChanges as zr}from"./CDC_LOG_TABLE-B58N8NQO.mjs";import{computeRankPage as st}from"./computeRankPage-Bby1Npkd.mjs";import{SCAN_DEP as H}from"./SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as q}from"./runDrizzle-it6rL9bR.mjs";import{D as N,k as ce,r as le,b as Ie,A as qe,a as Ce,e as V,t as At,f as ct,i as Yt,h as vt,g as Xt}from"./do-sql-Dk_DJxn4.mjs";import{WORKERD_SQLITE_LIMITS as It,unionAll as He,sqliteInList as Zt}from"./param-Ib8WHnrF.mjs";import{coveringGeohashes as en,boundingBoxGeohashes as tn,haversineMeters as nn,pointInBoundingBox as rn}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{NotFoundError as on}from"./NotFoundError-BhF7FeFr.mjs";import{softDeleteScope as de,normalizeOrderKeys as sn,buildSeekWhere as Ct,decodeCursor as Ne,applySelect as at,encodeCursor as je,buildSeekBeforeWhere as cn}from"./applySelect-BQbHyo-W.mjs";import{rankTableName as dt,sortColumnName as lt,resolveRankPartition as an,encodePartitionKey as dn,RANK_TIEBREAK as ln}from"./RANK_TIEBREAK-ci3MaM65.mjs";import{indexKeysForRow as un,buildIndexRange as fn}from"./buildIndexRange-CBKQmHSS.mjs";import{assertFlatPredicate as Ue,resolveRelationPredicates as ut}from"./DEFAULT_MAX_RELATION_KEYS-BAWGIEvC.mjs";import{runRowValidators as Pe,resolveWith as ft,relationHooks as ht,applyOnDelete as hn,fanOutScalarCounts as wn}from"./applyOnDelete-BlcwKjuO.mjs";import{guardWriter as pn}from"./RLS_UNWRAP_SYMBOL-BWloGsd3.mjs";import{i as gn}from"./sql-projection-BqmxFxQU.mjs";import{createSystemReader as $n}from"./createSystemReader-BtYeSMDb.mjs";import{ConflictError as pe}from"./ConflictError-C8GtJmjS.mjs";import{runTriggers as yn}from"./hasTrigger-CjlwI4le.mjs";import{compileWhereSql as te}from"./compileWhereSql-JBpSfQm9.mjs";import{CLIENT_WATERMARK_TABLE as Vr,advanceClientWatermark as Yr,migrateClientWatermark as Xr,readClientWatermark as Zr}from"./CLIENT_WATERMARK_TABLE-BoS1HEqz.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as to,deleteGlobalShapeSnapshot as no,deleteGlobalShapeSnapshotsForConnection as ro,migrateGlobalShapeSnapshot as oo,readGlobalShapeSnapshot as io,writeGlobalShapeSnapshot as so}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-NWaL77m5.mjs";import{IDEMPOTENCY_TABLE as ao,readIdempotent as lo,trimIdempotent as uo,writeIdempotent as fo}from"./IDEMPOTENCY_TABLE-DKVe2Ohf.mjs";import{runShardMigrations as wo}from"./runShardMigrations-Crppyq1f.mjs";import{SEARCH_STATE_TABLE as go}from"./SEARCH_STATE_TABLE-Dju8ebbU.mjs";import{selectShapeMemberIds as yo,selectShapeRows as Eo}from"./selectShapeMemberIds-B-pQJHAu.mjs";import{serializeSqlValue as ie}from"./serializeSqlValue-DbI1VQYM.mjs";import{quoteIdentifier as En}from"./quoteIdentifier-CObIFRhb.mjs";const mn=o=>{const i=new TextEncoder().encode(o);let t="";for(const a of i)t+=String.fromCodePoint(a);return btoa(t)},Sn=o=>{const i=atob(o),t=Uint8Array.from(i,a=>a.codePointAt(0)??0);return new TextDecoder().decode(t)},_n=()=>new E("BAD_REQUEST","invalid cursor"),wt=16,pt=8,X=1024,Qe=(o,i)=>i.query(o),Rn=(o,i,t)=>{const a=Ut(o,t);if(a.length===0)return 0;let f=0;for(const[p,m]of i.entries()){const v=p===i.length-1;let S=0;for(const $ of a)(v?$.startsWith(m):$===m)&&(S+=1);if(S===0)return 0;f+=S}return f},Tn=(o,i)=>{if(!i)return{exact:!0,lower:o,upper:o};const t=[...o].at(-1)??"",a=(t.codePointAt(0)??0)+1;if(a>=55296&&a<=57343||a>1114111)return{exact:!0,lower:o,upper:o};const f=o.slice(0,o.length-t.length);return{exact:!1,lower:o,upper:f+String.fromCodePoint(a)}},An=(o,i,t)=>{const a={eq:(f,p)=>{if(!o.definition.filterFields?.includes(f))throw new E("INTERNAL",`field "${f}" is not a filter field of search index "${o.indexName}" on table "${i}"`);if(o.filters.length>=pt)throw new E("BAD_REQUEST",`search index "${o.indexName}" on table "${i}": at most ${String(pt)} .eq() filters are supported per search query`);return o.filters.push({field:f,value:p}),a},search:(f,p)=>{const m=o;if(f!==m.definition.field)throw new E("INTERNAL",`search index "${m.indexName}" on table "${i}" indexes "${m.definition.field}", not "${f}"`);const v=Qe(p,t).length;if(v>wt)throw new E("BAD_REQUEST",`search index "${m.indexName}" on table "${i}": at most ${String(wt)} search terms are supported (got ${String(v)})`);return m.field=f,m.query=p,m.hasQuery=!0,a}};return a},vn=o=>{if(o.length>X)throw new E("BAD_REQUEST",`more than ${String(X)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},In=o=>Math.min(o.offset+o.numItems+1,X),Cn=o=>mn(`search:${String(o)}`),xn=o=>{let i;try{i=Sn(o)}catch{return}if(!i.startsWith("search:"))return;const t=Number(i.slice(7));return Number.isInteger(t)&&t>=0?t:void 0},Mn=o=>{if(typeof o.endCursor=="string")throw new E("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");const i=Math.max(0,Math.floor(o.numItems)),t=o.cursor?xn(o.cursor):0;if(t===void 0)throw _n();if(t+i>X)throw new E("BAD_REQUEST",`search pagination reaches past the ${String(X)}-document limit (offset ${String(t)} + ${String(i)} requested) — narrow the query or the filters instead`);return{numItems:i,offset:t}},bn=(o,i)=>{const t=i.offset+i.numItems,a=i.numItems>0&&o.length>t;return{continueCursor:a?Cn(t):null,isDone:!a,page:o.slice(i.offset,t)}},Dn=o=>{if(o===void 0)return X+1;if(!Number.isFinite(o))return X;const i=Math.max(0,Math.floor(o));if(i>X)throw new E("BAD_REQUEST",`search returns at most ${String(X)} documents (asked for ${String(i)}) — narrow the query or paginate instead`);return i},kn=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,Ln=o=>{if(!kn.test(o))throw new E("INTERNAL",`invalid clientId ${JSON.stringify(o)}: a client-supplied row id must be a UUID`)},gt=50,xt=500,$t=Math.floor(It.boundParams/3),we=It.boundParams,Fn=128,ae=(o,i,t)=>{const a=i??xt;if(o>a)throw new E("BATCH_LIMIT_EXCEEDED",`${t}: batch of ${String(o)} exceeds the limit of ${String(a)} (raise options.limit or chunk the call)`,{status:400})},Wn=o=>{const i={eq:(t,a)=>(o.sqlConditions.push({comparator:"=",field:t,value:a}),i),gt:(t,a)=>(o.sqlConditions.push({comparator:">",field:t,value:a}),i),gte:(t,a)=>(o.sqlConditions.push({comparator:">=",field:t,value:a}),i),lt:(t,a)=>(o.sqlConditions.push({comparator:"<",field:t,value:a}),i),lte:(t,a)=>(o.sqlConditions.push({comparator:"<=",field:t,value:a}),i)};return i},Bn=o=>Math.max(o,X),Mt=(o,i)=>{const t=o.filters.map(a=>r`${V(a.field)} = ${ie(a.value)}`);return i&&t.push(i),t},qn=(o,i,t,a,f)=>{const p=Qe(t.query,Oe(t.definition.language));if(p.length===0)return[];const m=Gt(i,t.indexName),v=`${m}__vocab`,S=p.length-1,$=p.map((F,k)=>{const j=Tn(F,k===S),K=j.exact?r`${r.identifier("term")} = ${j.lower}`:r`${r.identifier("term")} >= ${j.lower} AND ${r.identifier("term")} < ${j.upper}`;return r`SELECT ${r.identifier("doc")}, ${r.raw(String(k))} AS ${r.identifier("__term__")}, COUNT(*) AS ${r.identifier("__n__")} FROM ${r.identifier(v)} WHERE ${K} GROUP BY ${r.identifier("doc")}`}),_=p.map((F,k)=>r`SUM(CASE WHEN u.${r.identifier("__term__")} = ${r.raw(String(k))} THEN u.${r.identifier("__n__")} ELSE 0 END)`),R=r`SELECT f.${r.identifier(Ae)} AS ${r.identifier(Ae)}, ${r.join(_,r` + `)} AS ${r.identifier("__score__")} FROM (${He($)}) u JOIN ${r.identifier(m)} f ON f.rowid = u.${r.identifier("doc")} GROUP BY f.${r.identifier(Ae)} HAVING ${r.join(_.map(F=>r`${F} > 0`),r` AND `)}`,T=Mt(t,f);let x=r`SELECT m.id, m._creationTime, m.${r.identifier(N)}, s.${r.identifier("__score__")} AS ${r.identifier("__score__")} FROM (${R}) s JOIN ${r.identifier(i)} m ON m.id = s.${r.identifier(Ae)}`;T.length>0&&(x=r`${x} WHERE ${r.join(T,r` AND `)}`),x=r`${x} ORDER BY s.${r.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${r.raw(String(a))}`;const W=[];for(const F of q(o,x)){const k=vt(F);if(k){const j=F.__score__;W.push({document:k,score:typeof j=="number"?j:Number(j??0)})}}return W},Un=(o,i,t,a,f)=>{const p=Oe(t.definition.language),m=Qe(t.query,p);if(m.length===0)return[];const v=Mt(t,f);let S=r`SELECT id, _creationTime, ${r.identifier(N)} FROM ${r.identifier(i)}`;v.length>0&&(S=r`${S} WHERE ${r.join(v,r` AND `)}`),S=r`${S} ORDER BY _creationTime DESC, id ASC LIMIT ${r.raw(String(Bn(a)))}`;const $=q(o,S).toArray(),_=[];for(const R of $){const T=vt(R);if(!T)continue;const x=Rn(Ht(T,t.definition),m,p);x>0&&_.push({creationTime:typeof T._creationTime=="number"?T._creationTime:0,doc:T,id:typeof T._id=="string"?T._id:"",score:x})}return _.sort((R,T)=>T.score-R.score||T.creationTime-R.creationTime||R.id.localeCompare(T.id)),_.slice(0,a).map(R=>({document:R.doc,score:R.score}))},Ge=(o,i,t,a)=>{if(!Number.isFinite(o.lat)||o.lat<-90||o.lat>90||!Number.isFinite(o.lng)||o.lng<-180||o.lng>180)throw new E("BAD_REQUEST",`geo index "${a}" on table "${t}": ${i} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},Pn=(o,i)=>{const t=o,a={near:(f,p)=>{if(t.within)throw new E("INTERNAL",`geo index "${t.indexName}" on table "${i}": call .near() or .within(), not both`);if(Ge(f,".near() point",i,t.indexName),!Number.isFinite(p)||p<=0)throw new E("BAD_REQUEST",`geo index "${t.indexName}" on table "${i}": .near() radiusMeters must be a finite number > 0, got ${String(p)}`);return t.near={point:{lat:f.lat,lng:f.lng},radiusMeters:p},a},within:f=>{if(t.near)throw new E("INTERNAL",`geo index "${t.indexName}" on table "${i}": call .near() or .within(), not both`);if(Ge(f.sw,".within() sw corner",i,t.indexName),Ge(f.ne,".within() ne corner",i,t.indexName),f.sw.lat>f.ne.lat)throw new E("BAD_REQUEST",`geo index "${t.indexName}" on table "${i}": .within() corners are transposed (sw.lat > ne.lat)`);if(f.sw.lng>f.ne.lng)throw new E("BAD_REQUEST",`geo index "${t.indexName}" on table "${i}": .within() box crosses the antimeridian (sw.lng > ne.lng), which is not supported — split it into two boxes at ±180 and union the results`);return t.within={ne:{lat:f.ne.lat,lng:f.ne.lng},sw:{lat:f.sw.lat,lng:f.sw.lng}},a}};return a},Gn=(o,i)=>{const t=o[i];if(t===null||typeof t!="object")return;const{lat:a,lng:f}=t;return typeof a=="number"&&typeof f=="number"?{lat:a,lng:f}:void 0},Hn=(o,i)=>{const t=Gn(o,i.definition.field);if(!t)return;const a=typeof o._creationTime=="number"?o._creationTime:0;if(i.near){const f=nn(i.near.point,t);return f<=i.near.radiusMeters?{creationTime:a,distance:f}:void 0}return rn(t,i.within)?{creationTime:a,distance:0}:void 0},Nn=(o,i,t,a)=>{if(!t.near&&!t.within)throw new E("INTERNAL",`geo index "${t.indexName}" on table "${i}": call .near(point, radius) or .within(box)`);const f=t.near?en(t.near.point,t.near.radiusMeters):tn(t.within),p=Xt(i,t.indexName),m=f.map(R=>r`(g.${r.identifier("__geohash__")} >= ${R} AND g.${r.identifier("__geohash__")} < ${`${R}{`})`),v=[r`(${r.join(m,r` OR `)})`];a&&v.push(a);const S=r`SELECT m.id, m._creationTime, m.${r.identifier(N)} FROM ${r.identifier(p)} g JOIN ${r.identifier(i)} m ON m.id = g.${r.identifier("__id__")} WHERE ${r.join(v,r` AND `)}`,$=q(o,S).toArray(),_=[];for(const R of $){const T=le(R),x=T?Hn(T,t):void 0;T&&x&&_.push({creationTime:x.creationTime,distance:x.distance,doc:T})}return _.sort((R,T)=>R.distance-T.distance||T.creationTime-R.creationTime),_},bt=(o,i,t,a)=>{const f=[];for(const p of o)if(i.every(m=>m(a(p)))&&(f.push(p),typeof t=="number"&&f.length>=t))break;return f},jn=(o,i,t,a,f,p=()=>{})=>{const m=t.within!==void 0,v=Nn(o,i,t,f).map(S=>({distanceMeters:m?null:S.distance,document:S.doc}));return p(v.length),typeof a=="number"?v.slice(0,Math.max(0,Math.floor(a))):v},Dt=(o,i,t,a,f,p=()=>{})=>{const{geo:m}=t;if(!m)throw new E("INTERNAL","runGeoTerminalScored called without a staged geo query");const v=t.inMemoryFilters.length>0,S=jn(o,i,m,v?void 0:f,a,p);return v?bt(S,t.inMemoryFilters,f,$=>$.document):S},Kn=(o,i,t,a,f,p=()=>{})=>Dt(o,i,t,a,f,p).map(m=>m.document),On=(o,i,t,a,f,p,m=()=>{})=>{const v=[];for(const R of t.sqlConditions)v.push(r`${V(R.field)} ${r.raw(R.comparator)} ${ie(R.value)}`);a&&v.push(a);let S=r`SELECT id, _creationTime, ${r.identifier(N)} FROM ${r.identifier(i)}`;v.length>0&&(S=r`${S} WHERE ${r.join(v,r` AND `)}`),S=r`${S} ORDER BY ${f}`,typeof p=="number"&&t.inMemoryFilters.length===0&&(S=r`${S} LIMIT ${r.raw(String(Math.max(0,Math.floor(p))))}`);const $=q(o,S).toArray();m($.length);const _=[];for(const R of $){const T=le(R);if(T&&t.inMemoryFilters.every(x=>x(T))&&(_.push(T),typeof p=="number"&&_.length>=p))break}return _},oe={fieldRef:V,serialize:ie},kt=(o,i)=>{const t=i===void 0?void 0:o.shape[i];return t!==void 0&&gn(t)},yt=(o,i)=>i.some(t=>kt(o,t)),Et=(o,i,t)=>{if(kt(o,i))throw new E("BAD_REQUEST",`${t}: "${i}" 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=o=>{let i=0;const t=[],a={fieldRef:V,relationExists:f=>{const{childWhere:p,negated:m,parentTable:v,relation:S}=f,$=`__rel_${String(i)}`,_=t.at(-1)??v;i+=1,o(S.table,H);const R=S.kind==="one"?S.field:S.references,T=S.kind==="one"?S.references:S.field,x=r`${ct($,T)} = ${ct(_,R)}`;t.push($);const W=te(p,a);t.pop();const F=W?r`${x} AND ${W}`:x,k=r`EXISTS (SELECT 1 FROM ${r.identifier(S.table)} AS ${r.identifier($)} WHERE ${F})`;return m?r`NOT ${k}`:k},serialize:ie};return a},Lt=o=>{const i=o.map(t=>r`${V(t.field)} ${r.raw(t.direction==="desc"?"DESC":"ASC")}`);return o.some(t=>t.field==="_id"||t.field==="id")||i.push(r`${V("id")} ASC`),r.join(i,r`, `)},zn={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},Jn=o=>{const i=o.order;return o.indexFields.length>0?o.indexFields.map(t=>({direction:i,field:t})):[{direction:i,field:"_creationTime"}]},Vn=(o,i,t,a)=>{const f=o.sqlConditions.map(p=>({[p.field]:{[zn[p.comparator]??"eq"]:p.value}}));if(t&&f.push(Ct(i,Ne(t))),a&&f.push(cn(i,Ne(a))),f.length!==0)return f.length===1?f[0]:{AND:f}},Yn=(o,i,t)=>{const a=[];for(const f of o){const p=le(f);if(p&&i.every(m=>m(p))&&(a.push(p),t!==void 0&&a.length>t))break}return a},Xn=(o,i,t,a,f,p=()=>{})=>{const m=Math.max(0,Math.floor(a.numItems)),v=Jn(t),S=typeof a.endCursor=="string",$=te(Vn(t,v,a.cursor,a.endCursor),oe),_=f&&$?r`${$} AND ${f}`:f??$;let R=r`SELECT id, _creationTime, ${r.identifier(N)} FROM ${r.identifier(i)}`;_&&(R=r`${R} WHERE ${_}`),R=r`${R} ORDER BY ${Lt(v)}`;const T=t.inMemoryFilters.length>0;!T&&!S&&(R=r`${R} LIMIT ${r.raw(String(m+1))}`);const x=q(o,R).toArray();p(x.length);const W=Yn(x,t.inMemoryFilters,T||S?void 0:m);if(S){const K=W.length>=2?W[Math.floor(W.length/2)-1]:void 0;return{continueCursor:a.endCursor??null,isDone:!0,page:W,splitCursor:K?je(K,v):null}}const F=W.length>m,k=F?W.slice(0,m):W,j=k.at(-1);return{continueCursor:F&&j?je(j,v):null,isDone:!F,page:k}};class Zn extends E{constructor(i="unique() found more than one matching document"){super("NOT_UNIQUE",i,{name:"NotUniqueError"})}}const er=/\s/u,tr=String.fromCodePoint(0),mt=(o,i,t)=>{if(!o.tables[i])throw new E("INTERNAL",`unknown table: ${i}`);return typeof t!="string"||t.length===0||er.test(t)||t.includes(tr)?null:t},nr=(o,i,t,a=()=>{},f=()=>{},p=()=>{})=>{const m=i.tables[t];if(!m)throw new E("INTERNAL",`unknown table: ${t}`);const v=de(m.softDeleteMode,void 0),S=v?te(v,oe):void 0,$={indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[]};let _=0;const R=y=>{const{search:I}=$;if(!I)throw new E("INTERNAL","runSearchFetch called without a staged search");Jt(o,t,m);const b=$.inMemoryFilters.length>0,L=Dn(b?void 0:y),J=Yt(o)?qn(o,t,I,L,S):Un(o,t,I,L,S);return b?(_=J.length,bt(J,$.inMemoryFilters,y,ne=>ne.document)):(y===void 0&&vn(J),J)},T=y=>R(y).map(I=>I.document),x=y=>{const I=Mn(y);return bn(T(In(I)),I)},W=()=>{const y=$.indexFields.length>0?$.indexFields:["_creationTime"],I=$.order==="desc"?"DESC":"ASC";return r.join(y.map(b=>r`${V(b)} ${r.raw(I)}`),r`, `)},F=()=>{if($.search||$.geo||$.indexName===void 0){f(void 0);return}f(fn(t,$.indexName,$.indexFields,$.sqlConditions,ie))},k=y=>{F();let I=0;const b=(()=>{if($.search){const L=T(y);return I=_,L}return $.geo?Kn(o,t,$,S,y,L=>{I=L}):On(o,t,$,S,W(),y,L=>{I=L})})();return p(Math.max(I,b.length)),b},j=()=>{if(!$.search&&!$.geo)throw new E("INTERNAL",`ctx.db.query("${t}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);F();let y=0;const I=(()=>{if($.search){const b=R(void 0);return y=_,b}return Dt(o,t,$,S,void 0,b=>{y=b})})();return p(Math.max(y,I.length)),I},K={async*[Symbol.asyncIterator](){const y=[...$.inMemoryFilters];let I;$.inMemoryFilters=[];try{for(;;){const b=await K.paginate({cursor:I??null,numItems:Fn});for(const L of b.page)y.every(J=>J(L))&&(yield L);if(b.isDone||b.continueCursor===null)return;I=b.continueCursor}}finally{$.inMemoryFilters=y}},async collect(){return k(void 0)},async collectWithScores(){return j()},filter(y){return $.inMemoryFilters.push(y),K},async first(){return k($.inMemoryFilters.length>0?void 0:1)[0]??null},order(y){return $.order=y==="desc"?"desc":"asc",K},async paginate(y){let I=0;if(F(),$.search){const L=x(y);return p(L.page.length),L}if($.geo)throw new E("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const b=Xn(o,t,$,y,S,L=>{I=L});return p(Math.max(I,b.page.length)),b},async take(y){return k(y)},async unique(){const y=k($.inMemoryFilters.length>0?void 0:2);if(y.length>1)throw new Zn(`unique() on table "${t}" matched ${String(y.length)} documents; expected at most one`);return y[0]??null},withGeoIndex(y,I){const b=(m.geoIndexes??[]).find(J=>J.name===y);if(!b)throw new E("INTERNAL",`unknown geo index "${y}" on table "${t}"`);a(t,y,"geo");const L={definition:b,indexName:y};if($.geo=L,I(Pn(L,t)),!L.near&&!L.within)throw new E("INTERNAL",`geo index "${y}" on table "${t}" requires a .near(point, radius) or .within(box) call`);return K},withIndex(y,I){const b=m.indexes.find(L=>L.name===y);if(!b)throw new E("INTERNAL",`unknown index "${y}" on table "${t}"`);return a(t,y,"index"),$.indexName=y,$.indexFields=b.fields,I&&I(Wn($)),K},withSearchIndex(y,I){const b=(m.searchIndexes??[]).find(J=>J.name===y);if(!b)throw new E("INTERNAL",`unknown search index "${y}" on table "${t}"`);a(t,y,"search");const L={definition:b,field:b.field,filters:[],hasQuery:!1,indexName:y,query:""};if($.search=L,I(An(L,t,Oe(b.language))),!L.hasQuery)throw new E("INTERNAL",`search index "${y}" on table "${t}" requires a .search(field, query) call`);return K}};return K},St=(o,i,t)=>{const a={...i};for(const[f,p]of At(o)){if(p.serverDefault){a[f]=p.serverDefault({auth:t});continue}a[f]===void 0&&(p.defaultFn?a[f]=p.defaultFn():"defaultValue"in p&&(a[f]=p.defaultValue))}return a},_t=(o,i,t,a)=>{const f=t;for(const[p,m]of At(o)){if(m.serverDefault){p in i&&(f[p]=m.serverDefault({auth:a}));continue}m.onUpdateFn&&!(p in i)&&(f[p]=m.onUpdateFn())}},Rt=(o,i)=>{for(const t of Object.keys(i))if(i[t]===void 0)throw new E("INTERNAL",`Cannot ${o} field '${t}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},rr=/unique constraint failed/i,or=o=>o instanceof Error&&rr.test(o.message),Ke=(o,i,t)=>{try{q(o,t)}catch(a){throw or(a)?new pe(`unique constraint violation on "${i}"`,"unique"):a}},xe=(o,i,t)=>{if(Ke(o,i,t),q(o,r`SELECT changes() AS changed`).one().changed===0)throw new pe(`optimistic concurrency conflict on "${i}" — the row changed during this mutation; refetch and retry`,"occ")},Tt=(o,i,t,a,f,p,m)=>{const v=[];for(let R=0;R<t.length+1;R+=1){const T=[];for(let k=0;k<R;k+=1)T.push(r`${r.identifier(t[k])} IS ${p[k]}`);const x=t[R],W=a[R];if(x!==void 0&&W!==void 0){const k=W.direction==="desc"?">":"<";T.push(r`${r.identifier(x)} ${r.raw(k)} ${p[R]}`)}else T.push(r`${r.identifier(ln)} < ${m}`);const[F]=T;v.push(T.length===1&&F!==void 0?F:r`(${r.join(T,r` AND `)})`)}const S=r.join(v,r` OR `),$=q(o,r`SELECT COUNT(*) AS c FROM ${r.identifier(i)} WHERE ${r.identifier("__partition__")} = ${f} AND (${S})`).one(),_=q(o,r`SELECT COUNT(*) AS c FROM ${r.identifier(i)} WHERE ${r.identifier("__partition__")} = ${f}`).one();return{before:$.c,total:_.c}},Lr=o=>{const{sql:i}=o,{schema:t}=o,a=o.broadcast??(()=>{}),f=(e,...n)=>{const s=t.tables[e]?.indexes;if(!s||s.length===0)return;const u=[];for(const h of n)h&&u.push(...un(s,h,ie));return u.length>0?u:void 0},{headroom:p}=o;let m=!1;const v=async e=>{const n=m;m=!0;try{return await e()}finally{m=n}},S=o.onRead??(()=>{}),$=o.onReadRange??(e=>{S(e.table,H)}),_=(e,n)=>{n!==void 0&&n!==H&&!m&&p?.recordRead(1),S(e,n)},R=o.onIndexUse??(()=>{}),T=o.onWrite??(()=>{}),x=e=>{m||p?.recordWrite(e)},W=async e=>{x(e.doc),await T(e)},{cache:F}=o,k=o.clock??(()=>Date.now()),j=o.idGenerator??(()=>crypto.randomUUID()),K=o.scheduler??jt,{globalDb:y}=o,I=o.auth??{identity:null,userId:null},b=o.cdc??!1,L=K,J=$n({scheduler:typeof L.list=="function"&&typeof L.get=="function"?L:void 0,storage:o.storage}),ne=(e,n,s,u)=>{b&&Vt(i,k(),e,n,s,u)},se=e=>t.tables[e]?.shardMode?.kind==="global",ze=(e,n)=>{if(se(e)){if(!y)throw new E("INTERNAL",`cross-backend ${n} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return y}return U},Me=e=>ze(e,"cascade"),Q=(e,n)=>{if(se(e)){if(!y)throw new E("INTERNAL",`${n} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return y}},Je=async(e,n,s,u,h)=>{h&&x(s);const d=await e.insert(n,s,u);return a({key:d,op:"insert",row:{...s,_id:d},table:n}),d},be=(e,n)=>ze(e,"relation load").findMany(e,n),Ve=(e,n)=>(se(e)&&_(e,H),be(e,n)),Ft=e=>!se(e.table),Ye=o.relationExistsPushDown??"auto",Xe=Ye!=="never",{maxRelationKeys:Ze}=o,ge=(e,n,s)=>ut(e,{fetcher:Ve,maxRelationKeys:Ze,relationBaseWhere:s,schema:t,tableName:n}),et=async(e,n,s,u)=>{const h=Q(e,"relation grouped count");if(h)return _(e,H),wn((B,A)=>h.count(B,A),e,n,s,u);const d=t.tables[e];if(!d)throw new E("INTERNAL",`unknown table: ${e}`);_(e,H);const c=de(d.softDeleteMode,void 0),l={[n]:{in:s}},w=z(z(l,u),c),C=await ge(w,e,void 0),g=te(C,oe),M=V(n);let D=r`SELECT ${M} AS __fk__, COUNT(*) AS count FROM ${r.identifier(e)}`;g&&(D=r`${D} WHERE ${g}`),D=r`${D} GROUP BY ${M}`;const P=q(i,D).toArray();return new Map(P.map(B=>[B.__fk__,B.count]))};let $e=0;const tt=new Set;for(const[e,n]of Object.entries(t.tables))for(const s of Object.values(n.triggerMap??{}))tt.add(`${e} ${s.timing} ${s.op}`);const Z=(e,n,s)=>tt.has(`${e} ${n} ${s}`),ee=async(e,n,s)=>{if($e+=1,$e>gt)throw $e-=1,new pe(`trigger recursion exceeded ${String(gt)} levels on "${s.table}" — check for a self-triggering write`,"trigger");try{await yn({ctx:Bt,event:s,op:n,schema:t,tableName:s.table,timing:e})}finally{$e-=1}},{ensureBackfilledForTable:ue,ensureBackfilledIndex:De,ensureRankBackfilled:ke,ensureRankBackfilledForTable:fe,syncAggregates:ye,syncCompanionsForInsert:nt,syncGeo:Ee,syncRanks:he,syncSearch:me}=Pt({broadcast:a,indexKeysFor:(e,n)=>f(e,n),invalidateCache:(e,n,s)=>F?.invalidate(e,n,f(e,s)),recordCdc:ne,schema:t,sql:i}),rt=(e,n,s)=>{const{shardMode:u}=n;if(u?.kind==="shardBy"&&!(u.field!==void 0&&(s.partitionBy??[]).includes(u.field)))throw Object.assign(new Error(`rank index "${s.name}" on "${e}" partitions across shards (shard key "${u.field??"?"}" is not in partitionBy) — a shard-local rank()/rankPage() would be wrong; roll it up through the Query Coordinator instead`),{code:"CROSS_SHARD_RANK_UNSUPPORTED",name:"LunoraError",status:400})},ot=e=>Object.entries(t.tables).filter(([,n])=>n.shardMode?.kind!=="global").map(([n])=>n).filter(n=>e===void 0||n===e),re=(e,n)=>{const s=ot(n);for(let u=0;u<s.length;u+=we){const h=s.slice(u,u+we).map(g=>r`SELECT ${r.raw(`'${g.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${r.identifier(N)} FROM ${r.identifier(g)} WHERE id = ${e}`),[d]=q(i,r`${He(h)} LIMIT 1`).toArray();if(!d)continue;const c=d.__t__,l=le(d);if(typeof c!="string"||!l)return;const w=d[N];return{docJson:typeof w=="string"?w:ce(w??{}),row:l,tableName:c}}},Wt=(e,n)=>{const s=[...new Set(e)],u=new Map;if(s.length===0)return u;const h=ot(n);for(let d=0;d<h.length;d+=we){const c=h.slice(d,d+we),l=Math.floor(we/c.length),w=Zt(r`${r.identifier("id")}`,s,!1,l),C=c.map(g=>r`SELECT ${r.raw(`'${g.replaceAll("'","''")}'`)} AS __t__, id FROM ${r.identifier(g)} WHERE ${w}`);for(const g of q(i,He(C))){const{id:M,__t__:D}=g;typeof D=="string"&&typeof M=="string"&&u.set(M,D)}}return u},it={assertRankPartitionLocal:rt,ensureRankBackfilled:ke,onRead:_,rowToDocument:le,schema:t,sql:i},U={system:J,async aggregate(e,n){const s=Q(e,"aggregate");if(s)return _(e,H),s.aggregate(e,n);const u=t.tables[e];if(!u)throw new E("INTERNAL",`unknown table: ${e}`);if(ve(n.op),n.op==="count")return U.count(e,{baseWhere:n.baseWhere,relationBaseWhere:n.relationBaseWhere,restrictsCounts:n.restrictsCounts,where:n.where});if(!n.field)throw new E("INTERNAL",`aggregate(${e}, { op: "${n.op}" }): "field" is required for non-count reducers`);_(e,H);const h=de(u.softDeleteMode,void 0),d=z(z(n.baseWhere,n.where),h),c=await ge(d,e,n.relationBaseWhere),l=c!==d;if(u.aggregateIndexes&&!n.baseWhere&&!l&&(!h||yt(u,[n.field]))){const B=zt(u.aggregateIndexes,n.op,n.field,n.where);if(B){De(e,B.index);const A=Fe(B.index.by??[],B.key),O=Le(e,B.index.name),Y=q(i,r`SELECT ${Ie} AS value, ${qe} AS count FROM ${r.identifier(O)} WHERE ${Ce} = ${A}`).toArray()[0];return We(n.op,Y)}}Et(u,n.field,`aggregate(${e}, { op: "${n.op}", field: "${n.field}" })`);const w=te(c,oe),C=ve(n.op),g=V(n.field);let M=r`SELECT ${r.raw(C)}(${g}) AS value FROM ${r.identifier(e)}`;w&&(M=r`${M} WHERE ${w}`);const P=q(i,M).toArray()[0]?.value;return P??null},asId(e,n){const s=mt(t,e,n);if(s===null)throw new E("BAD_REQUEST",`asId("${e}", …): "${n}" is not a valid id for table "${e}"`,{status:400});return s},async count(e,n){const s=Q(e,"count");if(s)return _(e,H),s.count(e,n);const u=t.tables[e];if(!u)throw new E("INTERNAL",`unknown table: ${e}`);const h=Kt(n);if(h.restrictsCounts)throw new Be(e);_(e,H);const d=de(u.softDeleteMode,void 0),c=z(z(h.baseWhere,h.where),d),l=await ge(c,e,h.relationBaseWhere),w=l!==c;if(u.aggregateIndexes&&!h.baseWhere&&!w&&!d){const D=Qt(u.aggregateIndexes,h.where);if(D){De(e,D.index);const P=Fe(D.index.by??[],D.key),B=Le(e,D.index.name),A=q(i,r`SELECT ${Ie} AS value FROM ${r.identifier(B)} WHERE ${Ce} = ${P}`).toArray();return A[0]===void 0?0:A[0].value??0}}const C=te(l,oe);let g=r`SELECT COUNT(*) AS count FROM ${r.identifier(e)}`;return C&&(g=r`${g} WHERE ${C}`),q(i,g).one().count},async delete(e,n,s){const u=re(e,n);if(!u){const g=n===void 0?y:void 0;g&&(x(void 0),await g.delete(e,void 0,s));return}const{docJson:h,row:d,tableName:c}=u,l=t.tables[c],w=s?.hard===!0,C=!w&&l?.softDeleteMode?l.softDeleteMode.field:void 0;if(!(C&&d[C]!==null&&d[C]!==void 0)){if(Z(c,"before","delete")&&await ee("before","delete",{id:e,op:"delete",previous:d,table:c}),await hn({deletedId:e,deletedReference:g=>d[g],findHolders:async(g,M,D)=>(await Me(g).findMany(g,{includeDeleted:w,where:{[M]:D}})).page,onCascade:(g,M)=>Me(g).delete(M,void 0,s),onRestrict:g=>{throw new pe(g,"restrict")},onSetNull:(g,M,D)=>Me(g).patch(M,{[D]:null}),schema:t,tableName:c}),ue(c),fe(c),C){const g={...d,[C]:k(),_id:e};xe(i,c,r`UPDATE ${r.identifier(c)} SET ${r.identifier(N)} = ${ce(g)} WHERE id = ${e} AND ${r.identifier(N)} = ${h}`),me(c,e,g,d),Ee(c,e,void 0),ye(c,d,g),he(c,e,d,void 0),F?.invalidate(c,e,f(c,d,g)),ne(c,e,"update",g),a({indexKeys:f(c,d,g),key:e,op:"update",row:g,table:c}),Z(c,"after","delete")&&await ee("after","delete",{id:e,op:"delete",previous:d,table:c}),await W({id:e,op:"delete",table:c});return}xe(i,c,r`DELETE FROM ${r.identifier(c)} WHERE id = ${e} AND ${r.identifier(N)} = ${h}`),me(c,e,void 0),Ee(c,e,void 0),ye(c,d,void 0),he(c,e,d,void 0),F?.invalidate(c,e,f(c,d)),ne(c,e,"delete"),a({indexKeys:f(c,d),key:e,op:"delete",table:c}),Z(c,"after","delete")&&await ee("after","delete",{id:e,op:"delete",previous:d,table:c}),await W({id:e,op:"delete",table:c})}},async deleteAll(e,n){if(!t.tables[e])throw new E("INTERNAL",`unknown table: ${e}`);const s=Math.max(1,n?.chunkSize??xt),u=n?.hard===void 0?void 0:{hard:n.hard},h=se(e)?void 0:e;let d=0;return await v(async()=>{for(;;){const l=(await U.findMany(e,{limit:s})).page.map(w=>String(w._id));if(l.length===0)break;for(const w of l)await U.delete(w,h,u),d+=1;if(l.length<s)break}}),{deleted:d}},async deleteMany(e,n,s){ae(e.length,n?.limit,"deleteMany");for(const u of e)await U.delete(u,s);return{deleted:e.length}},async deleteWhere(e,n,s){const d=(await(Q(e,"deleteWhere")??U).findMany(e,{where:n})).page.map(c=>String(c._id));if(ae(d.length,s?.limit,"deleteWhere"),U.deleteMany===void 0)throw new E("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return U.deleteMany(d,s)},async findFirst(e,n={}){return(await U.findMany(e,{...n,limit:1})).page[0]??null},async findFirstOrThrow(e,n={}){const s=await U.findFirst(e,n);if(s===null)throw new on(`findFirstOrThrow: no "${e}" document matched`);return s},async findMany(e,n={}){const s=Q(e,"findMany");if(s)return _(e,H),s.findMany(e,n);const u=t.tables[e];if(!u)throw new E("INTERNAL",`unknown table: ${e}`);const h=!n.where&&!n.baseWhere;h?_(e,H):_(e);const d=sn(n.orderBy),c=n.cursor?Ct(d,Ne(n.cursor)):void 0;let l=z(n.baseWhere,n.where);l=z(l,de(u.softDeleteMode,n.includeDeleted)),l=await ut(l,{canPushExists:Xe?Ft:void 0,existsPushMode:Ye==="always"?"always":"auto",fetcher:Ve,maxRelationKeys:Ze,relationBaseWhere:n.relationBaseWhere,schema:t,tableName:e}),c&&(l=l?{AND:[l,c]}:c);const w=Xe?Qn(_):oe,C=te(l,w);let g=r`SELECT id, _creationTime, ${r.identifier(N)} FROM ${r.identifier(e)}`;C&&(g=r`${g} WHERE ${C}`),g=r`${g} ORDER BY ${Lt(d)}`;const M=typeof n.limit=="number"?Math.max(0,Math.floor(n.limit)):void 0;M!==void 0&&(g=r`${g} LIMIT ${r.raw(String(M+1))}`);const D=q(i,g).toArray();h&&!m&&p?.recordRead(D.length);const P=[];for(const Y of D){const G=le(Y);G&&(P.push(G),!h&&typeof G._id=="string"&&_(e,G._id))}if(M===void 0)return n.with&&await ft({groupedCounter:et,fetcher:be,parents:P,...ht(n),schema:t,tableName:e,with:n.with}),{continueCursor:null,isDone:!0,page:at(P,n.select,n.with)};const B=P.length>M,A=B?P.slice(0,M):P,O=A.at(-1);return n.with&&await ft({fetcher:be,groupedCounter:et,parents:A,...ht(n),schema:t,tableName:e,with:n.with}),{continueCursor:B&&O?je(O,d):null,isDone:!B,page:at(A,n.select,n.with)}},async get(e,n){const s=re(e,n);if(!s){const u=n===void 0?y:void 0;return u?u.get(e):null}return _(s.tableName,e),s.row},async lookupById(e,n){const s=re(e,n);return s?(_(s.tableName,e),{row:s.row,tableName:s.tableName}):null},async groupBy(e,n){const s=Q(e,"groupBy");if(s)return _(e,H),s.groupBy(e,n);const u=t.tables[e];if(!u)throw new E("INTERNAL",`unknown table: ${e}`);_(e,H);const h=n.agg??{op:"count"};if(ve(h.op),h.op!=="count"&&!h.field)throw new E("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);const d=de(u.softDeleteMode,void 0),c=z(z(n.baseWhere,n.where),d),l=await ge(c,e,n.relationBaseWhere),w=l!==c,C=[...n.by,h.field];if(u.aggregateIndexes&&!n.baseWhere&&!w&&(!d||yt(u,C))){const A=Ot(u.aggregateIndexes,h.op,h.field,n.by,n.where),O=A===void 0?0:Object.keys(A.partial).length,Y=A?.index.by?.length??0;if(A&&(O===0||O===Y)){De(e,A.index);const G=Le(e,A.index.name),Se=Object.keys(A.partial),_e=[];if(Se.length===(A.index.by??[]).length&&Se.length>0){const Re=Fe(A.index.by??[],A.partial),Te=q(i,r`SELECT ${Ie} AS value, ${qe} AS count FROM ${r.identifier(G)} WHERE ${Ce} = ${Re}`).toArray();return Te.length>0&&_e.push({key:{...A.partial},value:We(h.op,Te[0])}),_e}const qt=q(i,r`SELECT ${Ce} AS key, ${Ie} AS value, ${qe} AS count FROM ${r.identifier(G)}`).toArray();for(const Re of qt){const Te=Nt(JSON.parse(Re.key));_e.push({key:Te,value:We(h.op,Re)})}return _e}}for(const A of C){if(A===void 0)continue;const O=A===h.field?`groupBy(${e}, { agg: { op: "${h.op}", field: "${A}" } })`:`groupBy(${e}, { by: [..."${A}"] })`;Et(u,A,O)}const g=te(l,oe),M=n.by.map(A=>r`${V(A)} AS ${r.identifier(A)}`);if(h.op==="count")M.push(r`COUNT(*) AS value`);else{const{field:A}=h;if(A===void 0)throw new E("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);M.push(r`${r.raw(ve(h.op))}(${V(A)}) AS value`)}let D=r`SELECT ${r.join(M,r`, `)} FROM ${r.identifier(e)}`;g&&(D=r`${D} WHERE ${g}`),D=r`${D} GROUP BY ${r.join(n.by.map(A=>V(A)),r`, `)}`;const P=q(i,D).toArray(),B=[];for(const A of P){const O={};for(const G of n.by)O[G]=A[G]??null;const{value:Y}=A;B.push({key:O,value:Y==null?null:Number(Y)})}return B},async insert(e,n,s){const u=Q(e,"insert");if(u)return Je(u,e,n,s,!0);const h=t.tables[e];if(!h)throw new E("INTERNAL",`unknown table: ${e}`);const d=St(h,n,I);Pe(h,d);let c;s?.clientId!==void 0?(Ln(s.clientId),c=s.clientId):s?.allowExplicitId&&typeof d._id=="string"?c=d._id:c=j();const l=s?.allowExplicitId&&typeof d._creationTime=="number"?d._creationTime:k(),w={...d,_creationTime:l,_id:c};return Z(e,"before","insert")&&await ee("before","insert",{doc:{...w},id:c,op:"insert",table:e}),ue(e),fe(e),Ke(i,e,r`INSERT INTO ${r.identifier(e)} (id, _creationTime, ${r.identifier(N)}) VALUES (${c}, ${l}, ${ce(w)})`),nt(e,c,w),Z(e,"after","insert")&&await ee("after","insert",{doc:w,id:c,op:"insert",table:e}),await W({doc:w,id:c,op:"insert",table:e}),c},async insertManyUnsafe(e,n,s){if(ae(n.length,s?.limit,"insertManyUnsafe"),n.length===0)return[];const u=Q(e,"insert");if(u){const c=[];for(const l of n)x(l);for(const l of n){const w=await u.insert(e,l,{allowExplicitId:s?.allowExplicitId});a({key:w,op:"insert",row:{...l,_id:w},table:e}),c.push(w)}return c}const h=t.tables[e];if(!h)throw new E("INTERNAL",`unknown table: ${e}`);ue(e),fe(e);const d=n.map(c=>{const l=St(h,c,I),w=s?.allowExplicitId===!0&&typeof l._id=="string"?l._id:j(),C=s?.allowExplicitId===!0&&typeof l._creationTime=="number"?l._creationTime:k();return{creationTime:C,document:{...l,_creationTime:C,_id:w},id:w}});for(const c of d)x(c.document);for(let c=0;c<d.length;c+=$t){const l=r.join(d.slice(c,c+$t).map(w=>r`(${w.id}, ${w.creationTime}, ${ce(w.document)})`),r`, `);Ke(i,e,r`INSERT INTO ${r.identifier(e)} (id, _creationTime, ${r.identifier(N)}) VALUES ${l}`)}for(const{document:c,id:l}of d)nt(e,l,c),await T({doc:c,id:l,op:"insert",table:e});return d.map(c=>c.id)},async insertMany(e,n,s){ae(n.length,s?.limit,"insertMany");const u=s?.skipDuplicates===!0,h=[],d=Q(e,"insert");if(d)for(const l of n)x(l);const c=async l=>d?Je(d,e,l,void 0,!1):U.insert(e,l);for(const l of n)try{h.push(await c(l))}catch(w){if(u&&w instanceof pe&&w.kind==="unique")h.push(null);else throw w}return h},normalizeId(e,n){return mt(t,e,n)},async patch(e,n,s){const u=re(e,s);if(!u){const C=s===void 0?y:void 0;if(C){x(n),await C.patch(e,n);return}throw new E("INTERNAL",`document not found: ${e}`)}const{docJson:h,row:d,tableName:c}=u,l=t.tables[c];if(!l)throw new E("INTERNAL",`unknown table: ${c}`);_(c,e),Rt("patch",n);const w={...d,...n,_id:e};_t(l,n,w,I),Pe(l,w,!0),Z(c,"before","update")&&await ee("before","update",{doc:{...w},id:e,op:"update",previous:d,table:c}),ue(c),fe(c),xe(i,c,r`UPDATE ${r.identifier(c)} SET ${r.identifier(N)} = ${ce(w)} WHERE id = ${e} AND ${r.identifier(N)} = ${h}`),me(c,e,w,d),Ee(c,e,w),ye(c,d,w),he(c,e,d,w),F?.invalidate(c,e,f(c,d,w)),ne(c,e,"update",w),a({indexKeys:f(c,d,w),key:e,op:"update",row:w,table:c}),Z(c,"after","update")&&await ee("after","update",{doc:w,id:e,op:"update",previous:d,table:c}),await W({doc:w,id:e,op:"update",table:c})},async patchMany(e,n,s){ae(e.length,n?.limit,"patchMany");for(const u of e)await U.patch(u.id,u.patch,s);return{patched:e.length}},async patchWhere(e,n,s){const d=(await(Q(e,"patchWhere")??U).findMany(e,{where:n.where})).page.map(c=>({id:String(c._id),patch:n.patch}));if(ae(d.length,s?.limit,"patchWhere"),U.patchMany===void 0)throw new E("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await U.patchMany(d,s),{patched:d.length}},query(e){const n=Q(e,"query");return n?(_(e,H),n.query(e)):nr(i,t,e,R,s=>{s?$(s):_(e,H)},s=>{m||p?.recordRead(s)})},async rank(e,n,s){const u=Q(e,"rank");if(u)return _(e,H),u.rank(e,n,s);R(e,n,"rank");const h=t.tables[e];if(!h)throw new E("INTERNAL",`unknown table: ${e}`);const d=h.rankIndexes?.find(G=>G.name===n);if(!d)throw new E("INTERNAL",`unknown rankIndex "${n}" on table "${e}"`);if(rt(e,h,d),s.restrictsCounts)throw new Be(e);_(e,H),ke(e,d);const c=typeof s.row=="string"?s.row:s.row._id;if(!c)return null;const l=dt(e,d.name),w=d.sortBy.map((G,Se)=>lt(Se)),C=w.map(G=>En(G)).join(", "),g=q(i,r`SELECT ${r.identifier("__partition__")}, ${r.raw(C)} FROM ${r.identifier(l)} WHERE ${r.identifier("__id__")} = ${c}`).toArray(),[M]=g;if(M===void 0)return null;let D=M.__partition__;const P=z(s.baseWhere,s.where);Ue(P,t,e,"rank");const B=an(d,P);if(B){const G=dn(d.partitionBy??[],B);if(G!==D)return null;D=G}const A=w.map(G=>M[G]),{before:O,total:Y}=Tt(i,l,w,d.sortBy,D,A,c);return{position:O+1,total:Y}},async rankBefore(e,n,s){if(se(e))throw new E("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const u=t.tables[e];if(!u)throw new E("INTERNAL",`unknown table: ${e}`);const h=u.rankIndexes?.find(w=>w.name===n);if(!h)throw new E("INTERNAL",`unknown rankIndex "${n}" on table "${e}"`);if(s.restrictsCounts)throw new Be(e);_(e,H),ke(e,h);const d=dt(e,h.name),c=h.sortBy.map((w,C)=>lt(C)),l=h.sortBy.map((w,C)=>ie(s.sortValues[C]??null));return Tt(i,d,c,h.sortBy,s.partitionKey,l,s.rowId)},async rankPage(e,n,s={}){Ue(z(s.baseWhere,s.where),t,e,"rankPage");const u=Q(e,"rankPage");if(u)return _(e,H),u.rankPage(e,n,s);R(e,n,"rank");const{continueCursor:h,hasMore:d,rows:c}=st(it,e,n,s);return{continueCursor:h,isDone:!d,page:c.map(l=>l.doc)}},async rankPageRows(e,n,s={}){Ue(z(s.baseWhere,s.where),t,e,"rankPage"),R(e,n,"rank");const{directions:u,hasMore:h,rows:d}=st(it,e,n,s);return{directions:u,hasMore:h,rows:d}},async restore(e,n){const s=re(e,n);if(!s){const d=n===void 0?y:void 0;if(d?.restore){await d.restore(e);return}throw new E("INTERNAL",`document not found: ${e}`)}const u=t.tables[s.tableName]?.softDeleteMode?.field;if(!u)throw new E("INTERNAL",`ctx.db.restore: table "${s.tableName}" is not a .softDelete() table`);const h=s.row[u]!==null&&s.row[u]!==void 0;await U.patch(e,{[u]:null},n),h&&he(s.tableName,e,void 0,s.row)},async replace(e,n,s,u){const h=re(e,s);if(!h){const M=s===void 0?y:void 0;if(M){x(n),await M.replace(e,n,void 0,u);return}throw new E("INTERNAL",`document not found: ${e}`)}const{docJson:d,row:c,tableName:l}=h,w=t.tables[l];if(!w)throw new E("INTERNAL",`unknown table: ${l}`);Rt("replace",n);const C=u?.allowExplicitId&&typeof n._creationTime=="number"?n._creationTime:k(),g={...n,_creationTime:C,_id:e};_t(w,n,g,I),Pe(w,g),Z(l,"before","update")&&await ee("before","update",{doc:{...g},id:e,op:"update",previous:c,table:l}),ue(l),fe(l),xe(i,l,r`UPDATE ${r.identifier(l)} SET _creationTime = ${C}, ${r.identifier(N)} = ${ce(g)} WHERE id = ${e} AND ${r.identifier(N)} = ${d}`),me(l,e,g,c),Ee(l,e,g),ye(l,c,g),he(l,e,c,g),F?.invalidate(l,e,f(l,c,g)),ne(l,e,"update",g),a({indexKeys:f(l,c,g),key:e,op:"update",row:g,table:l}),Z(l,"after","update")&&await ee("after","update",{doc:g,id:e,op:"update",previous:c,table:l}),await W({doc:g,id:e,op:"update",table:l})},async wipeShard(e){const n=new Set(e?.exclude),s=e?.tables,u=Object.entries(t.tables).filter(([l,w])=>n.has(l)||s!==void 0&&!s.includes(l)?!1:w.shardMode?.kind!=="global").map(([l])=>l);if(s!==void 0){for(const l of s)if(!t.tables[l])throw new E("INTERNAL",`wipeShard: unknown table: ${l}`)}const h={};let d=0;const{deleteAll:c}=U;if(c===void 0)throw new E("INTERNAL","wipeShard: this writer has no deleteAll");for(const l of u){const w=await c(l,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});h[l]=w.deleted,d+=w.deleted}return{deleted:d,tables:h}}},Bt={db:U,scheduler:K};return o.enforceRls===!0?pn(U,t,(e,n)=>re(e,n)?.tableName,(e,n)=>Wt(e,n)):U};export{Gr as CDC_LOG_TABLE,Vr as CLIENT_WATERMARK_TABLE,to as GLOBAL_SHAPE_SNAPSHOT_TABLE,ao as IDEMPOTENCY_TABLE,Zn as NotUniqueError,go as SEARCH_STATE_TABLE,Yr as advanceClientWatermark,Hr as applyCdcChanges,Ln as assertValidClientId,Br as backfillAggregateIndexes,qr as backfillRankIndexes,Ur as backfillSearchIndexes,Nr as bumpCdcEpoch,Lr as createShardCtxDb,no as deleteGlobalShapeSnapshot,ro as deleteGlobalShapeSnapshotsForConnection,Xr as migrateClientWatermark,oo as migrateGlobalShapeSnapshot,jr as minCdcSeq,mt as normalizeIdStructurally,Kr as readCdcChanges,Or as readCdcCursor,Qr as readCdcEpoch,Zr as readClientWatermark,io as readGlobalShapeSnapshot,lo as readIdempotent,wo as runShardMigrations,yo as selectShapeMemberIds,Eo as selectShapeRows,zr as trimCdcChanges,uo as trimIdempotent,so as writeGlobalShapeSnapshot,fo as writeIdempotent};
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import{runSql as o,orNull as a,decodeJsonColumn as _}from"./runDrizzle-it6rL9bR.mjs";const s="__lunora_queue_messages",n=500,E=128*1024,T="… [truncated by the dev queue catcher]",c="[unserializable message body]",R=e=>{if(e===void 0)return"null";try{const r=JSON.stringify(e);return r.length>E?JSON.stringify(`${r.slice(0,E)}${T}`):r}catch{return JSON.stringify(c)}},g=e=>typeof e=="string"&&(e===c||e.endsWith(T)),u=e=>{o(e,`CREATE TABLE IF NOT EXISTS "${s}" (
|
|
2
|
+
id TEXT PRIMARY KEY,
|
|
3
|
+
captured_at INTEGER NOT NULL,
|
|
4
|
+
message_id TEXT NOT NULL,
|
|
5
|
+
queue TEXT NOT NULL,
|
|
6
|
+
export_name TEXT,
|
|
7
|
+
body TEXT NOT NULL,
|
|
8
|
+
attempts INTEGER NOT NULL,
|
|
9
|
+
outcome TEXT NOT NULL,
|
|
10
|
+
error TEXT,
|
|
11
|
+
dead_lettered INTEGER NOT NULL,
|
|
12
|
+
message_ts INTEGER NOT NULL
|
|
13
|
+
)`)},p=(e,r,d)=>{u(e);for(const t of r)o(e,`INSERT INTO "${s}" (id, captured_at, message_id, queue, export_name, body, attempts, outcome, error, dead_lettered, message_ts)
|
|
14
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,crypto.randomUUID(),d,t.messageId,t.queue,a(t.exportName),R(t.body),t.attempts,t.outcome,a(t.error),t.deadLettered===!0?1:0,t.timestamp);return o(e,`DELETE FROM "${s}"
|
|
15
|
+
WHERE id NOT IN (
|
|
16
|
+
SELECT id FROM "${s}" ORDER BY captured_at DESC, id DESC LIMIT ?
|
|
17
|
+
)`,n),{recorded:r.length}},i=e=>({attempts:e.attempts,body:_(e.body),capturedAt:e.captured_at,deadLettered:e.dead_lettered===1,error:e.error??void 0,exportName:e.export_name??void 0,id:e.id,messageId:e.message_id,outcome:e.outcome,queue:e.queue,timestamp:e.message_ts}),y=(e,r={})=>{u(e);const d=Math.min(Math.max(r.limit??100,1),n),t=typeof r.queue=="string"&&r.queue.length>0?r.queue:void 0,m=t===void 0?"":"WHERE queue = ?",N=t===void 0?[d]:[t,d];return{entries:o(e,`SELECT * FROM "${s}" ${m} ORDER BY captured_at DESC, id DESC LIMIT ?`,...N).toArray().map(L=>i(L))}},S=(e,r)=>{u(e);const t=o(e,`SELECT * FROM "${s}" WHERE id = ? LIMIT 1`,r).toArray()[0];return t===void 0?void 0:i(t)},U=e=>(u(e),o(e,`DELETE FROM "${s}"`),{cleared:!0});export{E as MAX_BODY_CHARS,n as QUEUE_RETENTION,s as QUEUE_TABLE,U as clearQueueMessages,u as ensureQueueTable,g as isLossyBody,S as readQueueMessageById,y as readQueueMessages,p as recordQueueMessages};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{matchesStaticWhere as a}from"./AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs";import{compareStrings as l}from"./aggregateTableName-Cy5e03oz.mjs";import{serializeSqlValue as f}from"./serializeSqlValue-DbI1VQYM.mjs";const c=Symbol("not-resolvable"),y=r=>{if(r!==null&&typeof r=="object"&&!Array.isArray(r)){const t=Object.keys(r);return t.length===1&&t[0]==="eq"?r.eq:c}return r},m=(r,t)=>{if(r.length===0)return"";const o={};for(const n of r.toSorted(l))o[n]=t[n]??null;return JSON.stringify(o)},k="__id__",d=r=>`__sort_k${String(r)}__`,h=(r,t)=>{const o=r.partitionBy??[],n=t??{};for(const e of Object.keys(n))if(e==="AND"||e==="OR"||e==="NOT")return;const s={};for(const e of o)if(e in n){const i=y(n[e]);if(i===c)return;s[e]=i}else if(r.where&&e in r.where)s[e]=r.where[e];else return;return s},S=(r,t)=>`${r}__rank_${t}`,K=(r,t)=>({partitionKey:m(r.partitionBy??[],t),rowId:t._id,sortValues:r.sortBy.map(o=>f(t[o.field]??null))}),N=a;export{k as RANK_TIEBREAK,m as encodePartitionKey,N as matchesRankStaticWhere,K as rankKeyFromDoc,S as rankTableName,h as resolveRankPartition,d as sortColumnName};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const t="__relationExists";export{t as RELATION_EXISTS_KEY};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const o="__lunora_reproject__",e=t=>`${o}${t}`,n=t=>{if(!t.startsWith(o))return;const r=t.slice(o.length);return r===""?void 0:r};export{o as REPROJECTION_MIGRATION_PREFIX,e as reprojectionMigrationId,n as reprojectionMigrationTable};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as g}from"@lunora/errors";const p=Symbol.for("lunora.ctxdb.rls-unwrap");class R extends g{table;constructor(a){super("RLS_REQUIRED",`ctx.db access to "${a}" 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=a}}const S=o=>Object.entries(o.tables).filter(([,a])=>a.shardMode?.kind!=="global").map(([a])=>a),M=(o,a,l)=>{const u=a?.tables,n=new Set(a?.exclude);for(const d of o)(u===void 0||u.includes(d))&&!n.has(d)&&l(d)},m=["aggregate","count","deleteAll","findFirst","findFirstOrThrow","findMany","groupBy","insert","insertMany","insertManyUnsafe","query","rank","rankBefore","rankPage","rankPageRows"],v=(o,a,l,u)=>{if(a.rlsMode!=="required")return o;const n=o,d=r=>{const t=a.tables[r];return t!==void 0&&t.isPublic!==!0},s=r=>{if(d(r))throw new R(r)},c=async(r,t)=>{if(t!==void 0){s(t);return}const e=await l(r);e!==void 0&&s(e)},h=async(r,t)=>{if(t!==void 0){s(t);return}if(!u){for(const i of r)await c(i,t);return}const e=await u([...new Set(r)],t);for(const i of r){const y=e.get(i);y!==void 0&&s(y)}},f={...o,[p]:o,delete:async(r,t,e)=>(await c(r,t),n.delete(r,t,e)),deleteMany:async(r,t,e)=>(await h(r,e),n.deleteMany(r,t,e)),deleteWhere:n.deleteWhere?async(r,t,e)=>(s(r),await n.deleteWhere?.(r,t,e)):void 0,get:async(r,t)=>(await c(r,t),n.get(r,t)),lookupById:async(r,t)=>(await c(r,t),n.lookupById?.(r,t)??null),patch:async(r,t,e)=>(await c(r,e),n.patch(r,t,e)),patchMany:async(r,t,e)=>(await h(r.map(i=>i.id),e),n.patchMany(r,t,e)),patchWhere:n.patchWhere?async(r,t,e)=>(s(r),await n.patchWhere?.(r,t,e)):void 0,replace:async(r,t,e,i)=>(await c(r,e),n.replace(r,t,e,i)),restore:async(r,t)=>(await c(r,t),n.restore?.(r,t))},w=n;for(const r of m){const t=w[r];typeof t=="function"&&(f[r]=(e,...i)=>(s(e),t.call(n,e,...i)))}if(n.wipeShard){const{wipeShard:r}=n;f.wipeShard=t=>(M(S(a),t,s),r.call(n,t))}return f};export{p as RLS_UNWRAP_SYMBOL,R as RlsRequiredError,v as guardWriter};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{stableWireKey as b}from"./stableWireKey-BYB5GQJa.mjs";import{depKey as l,SCAN_DEP as y}from"./SCAN_DEP-D7qE3iUe.mjs";import{e as g}from"./estimate-bytes-CzG5x1f8.mjs";import{keysTouchRanges as p}from"./buildIndexRange-CBKQmHSS.mjs";import{stableStringify as A}from"./stableStringify-CujpENIO.mjs";const h=(o,t,s)=>{let e=o.get(t);return e===void 0&&(e=s(),o.set(t,e)),e},m=1e3,x=4*1024*1024;class w{entries=new Map;tableIndex=new Map;rangeIndex=new Map;totalBytes=0;hits=0;misses=0;evictions=0;maxEntries;maxBytes;now;monotonic=0;constructor(t={}){this.maxEntries=t.maxEntries??m,this.maxBytes=t.maxBytes??x,this.now=t.now??(()=>(this.monotonic+=1,this.monotonic))}async run(t,s,e,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 e(),c=g(r);if(c===void 0)return r;const d=i(),f={bytes:c,deps:s,ranges:d,lastUsed:this.now(),result:r,subscribers:new Set};this.entries.set(t,f),this.totalBytes+=c;for(const a of s)h(this.tableIndex,a,()=>new Set).add(t);for(const a of d){const u=h(this.rangeIndex,a.table,()=>new Map);h(u,a,()=>new Set).add(t)}return this.evict(),r}invalidate(t,s,e){const i=[];return this.collectAndDrop(l(t,s),i),this.collectAndDrop(l(t,y),i),this.dropRangeDeps(t,e,i),i}invalidateTable(t){const s=[],e=`${t}:`;for(const i of this.tableIndex.keys())i.startsWith(e)&&this.collectAndDrop(i,s);return this.dropRangeDeps(t,void 0,s),s}subscribe(t,s){const e=this.entries.get(t);e&&e.subscribers.add(s)}unsubscribe(t,s){const e=this.entries.get(t);e&&e.subscribers.delete(s)}size(){return{bytes:this.totalBytes,entries:this.entries.size}}clear(){this.entries.clear(),this.tableIndex.clear(),this.rangeIndex.clear(),this.totalBytes=0}subscribers(t){const s=this.entries.get(t);return s?[...s.subscribers]:[]}stats(){return{bytes:this.totalBytes,entries:this.entries.size,evictions:this.evictions,hits:this.hits,misses:this.misses}}dropRangeDeps(t,s,e){const i=this.rangeIndex.get(t);if(!(!i||i.size===0))for(const[n,r]of i)p([n],s)&&this.dropKeys(r,e)}collectAndDrop(t,s){const e=this.tableIndex.get(t);e&&this.dropKeys(e,s)}dropKeys(t,s){for(const e of t){const i=this.entries.get(e);i&&(this.dropEntry(e,i),s.push(e))}}dropEntry(t,s){this.entries.delete(t),this.totalBytes-=s.bytes;for(const e of s.deps){const i=this.tableIndex.get(e);i&&(i.delete(t),i.size===0&&this.tableIndex.delete(e))}for(const e of s.ranges){const i=this.rangeIndex.get(e.table),n=i?.get(e);n?.delete(t),i&&n?.size===0&&(i.delete(e),i.size===0&&this.rangeIndex.delete(e.table))}}evict(){if(!(this.entries.size<=this.maxEntries&&this.totalBytes<=this.maxBytes))for(const[t,s]of this.entries){if(this.entries.size<=this.maxEntries&&this.totalBytes<=this.maxBytes)return;s.subscribers.size>0||(this.dropEntry(t,s),this.evictions+=1)}}}const z=(o,t,s)=>`${s??"\0anon"}\0${o}:${b(t)}`;export{w as ReactiveCache,z as reactiveCacheKey,A as stableStringify,b as stableWireKey};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const r="*scan",t=(e,c)=>`${e}:${c}`,o=e=>{const c=e.indexOf(":");return c===-1?e:e.slice(0,c)},s=()=>{const e=new Set;return{collect(){return e},recordRead(c,n){e.add(t(c,n))}}};export{r as SCAN_DEP,s as createDependencyTracker,t as depKey,o as tableFromDepKey};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import{quoteIdentifier as i}from"./quoteIdentifier-CObIFRhb.mjs";import{runSql as n}from"./runDrizzle-it6rL9bR.mjs";const p="__lunora_schema_history",c=50,e=i(p),E=t=>({appliedAt:typeof t.applied_at=="number"?t.applied_at:0,hash:typeof t.hash=="string"?t.hash:"",seq:typeof t.seq=="number"?t.seq:0}),a=t=>{n(t,`CREATE TABLE IF NOT EXISTS ${e} (
|
|
2
|
+
hash TEXT PRIMARY KEY,
|
|
3
|
+
seq INTEGER NOT NULL,
|
|
4
|
+
snapshot_json TEXT NOT NULL,
|
|
5
|
+
applied_at INTEGER NOT NULL
|
|
6
|
+
)`)},S=t=>{n(t,`DELETE FROM ${e} WHERE hash NOT IN (SELECT hash FROM ${e} ORDER BY seq DESC LIMIT ?)`,c)},I=(t,s,r,h=Date.now())=>{if(s===""||r==="")return!1;try{if(a(t),n(t,`SELECT hash FROM ${e} WHERE hash = ? LIMIT 1`,s).toArray().length>0)return!1;const[o]=n(t,`SELECT COALESCE(MAX(seq), 0) + 1 AS next FROM ${e}`).toArray(),T=typeof o?.next=="number"?o.next:1;return n(t,`INSERT INTO ${e} (hash, seq, snapshot_json, applied_at) VALUES (?, ?, ?, ?) ON CONFLICT(hash) DO NOTHING`,s,T,r,h),S(t),!0}catch{return!1}},_=t=>{try{return a(t),n(t,`SELECT hash, seq, applied_at FROM ${e} ORDER BY seq DESC`).toArray().map(s=>E(s))}catch{return[]}},u=(t,s)=>{try{a(t);const[r]=n(t,`SELECT hash, seq, applied_at, snapshot_json FROM ${e} WHERE hash = ? LIMIT 1`,s).toArray();return r===void 0?void 0:{...E(r),snapshotJson:typeof r.snapshot_json=="string"?r.snapshot_json:""}}catch{return}};export{c as SCHEMA_HISTORY_MAX_VERSIONS,_ as readSchemaHistory,u as readSchemaVersion,I as recordSchemaVersion};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{sql as i}from"drizzle-orm";import{runDrizzle as o}from"./runDrizzle-it6rL9bR.mjs";const n="__lunora_search_state",s=e=>{o(e,i`CREATE TABLE IF NOT EXISTS ${i.identifier(n)} (${i.identifier("companion")} TEXT PRIMARY KEY, ${i.identifier("cursor")} TEXT, ${i.identifier("done")} INTEGER NOT NULL DEFAULT 0, ${i.identifier("profile")} TEXT)`);try{o(e,i`ALTER TABLE ${i.identifier(n)} ADD COLUMN ${i.identifier("profile")} TEXT`)}catch{}},$=e=>e===1||e===!0||e==="1",l=(e,t)=>{const r=o(e,i`SELECT ${i.identifier("cursor")}, ${i.identifier("done")}, ${i.identifier("profile")} FROM ${i.identifier(n)} WHERE ${i.identifier("companion")} = ${t}`).toArray()[0];return r?{cursor:r.cursor??void 0,done:$(r.done),profile:r.profile??void 0}:{cursor:void 0,done:!1,profile:void 0}},a=(e,t,d,r,f)=>{const c=d??null;o(e,i`INSERT INTO ${i.identifier(n)} (${i.identifier("companion")}, ${i.identifier("cursor")}, ${i.identifier("done")}, ${i.identifier("profile")}) VALUES (${t}, ${c}, ${r?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{n as SEARCH_STATE_TABLE,s as migrateSearchState,l as readSearchBackfillState,a as writeSearchBackfillState};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import{sql as o}from"drizzle-orm";import{runDrizzle as n}from"./runDrizzle-it6rL9bR.mjs";const c="__shape_poke_cursor",d=r=>{n(r,o`CREATE TABLE IF NOT EXISTS ${o.identifier(c)} (
|
|
2
|
+
connection_id TEXT NOT NULL,
|
|
3
|
+
sub_id TEXT NOT NULL,
|
|
4
|
+
cursor INTEGER NOT NULL,
|
|
5
|
+
PRIMARY KEY (connection_id, sub_id)
|
|
6
|
+
)`)},T=(r,e,i)=>n(r,o`SELECT cursor FROM ${o.identifier(c)} WHERE connection_id = ${e} AND sub_id = ${i} LIMIT 1`).toArray()[0]?.cursor,u=(r,e,i,s)=>{n(r,o`INSERT INTO ${o.identifier(c)} (connection_id, sub_id, cursor) VALUES (${e}, ${i}, ${s})
|
|
7
|
+
ON CONFLICT(connection_id, sub_id) DO UPDATE SET cursor = excluded.cursor`)},_=(r,e,i)=>{n(r,o`DELETE FROM ${o.identifier(c)} WHERE connection_id = ${e} AND sub_id = ${i}`)},L=(r,e)=>{n(r,o`DELETE FROM ${o.identifier(c)} WHERE connection_id = ${e}`)};export{c as SHAPE_POKE_CURSOR_TABLE,_ as deleteShapePokeCursor,L as deleteShapePokeCursorsForConnection,d as migrateShapePokeCursor,T as readShapePokeCursor,u as writeShapePokeCursor};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
class r{shardHost;socketHost;options;constructor(t,s,e={}){this.shardHost=t,this.socketHost=s,this.options=e}get shardKey(){return this.shardHost.shardKey}socketFor(t){return this.socketHost.handleFor(t)??t}sockets(t){return this.socketHost.getSockets(t)}background(t){return this.shardHost.waitUntil===void 0?!1:(this.shardHost.waitUntil(t),!0)}async runInTransaction(t){return this.shardHost.runSerialized(async()=>this.shardHost.transaction(t))}async handleFetch(t){return this.options.handlers?.handleFetch?this.options.handlers.handleFetch(t):new Response("Not implemented",{status:501})}async handleAlarm(){this.options.handlers?.handleAlarm&&await this.options.handlers.handleAlarm()}}export{r as ShardRunner};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as g}from"@lunora/errors";import{e as i}from"./wire-codec-BU9T2xJ7.mjs";const a=BigInt(Number.MAX_SAFE_INTEGER),c=(e,t)=>e<t?-1:e>t?1:0,m=(e,t)=>`${e}__agg_${t}`,l=e=>{if(typeof e=="bigint"){if(e>a||e<-a)throw new g("BAD_REQUEST",`bigint ${e.toString()} exceeds Number.MAX_SAFE_INTEGER, so an aggregateIndex declared over this column cannot tally it exactly (the companion's value column is a REAL) — drop the aggregateIndex, aggregate a narrower column, or read the rows and reduce them in the handler`);return Number(e)}if(typeof e=="number")return Number.isFinite(e)?e:void 0},v=(e,t,n,u)=>{const r=e.get(t)??{count:0,value:null};if(n.op==="count"){r.count+=1,r.value=r.count,e.set(t,r);return}const o=l(u[n.field??""]);if(n.op==="sum"||n.op==="avg"){o!==void 0&&(r.value=(r.value??0)+o,r.count+=1),e.set(t,r);return}r.count+=1,o!==void 0&&(r.value===null?r.value=o:r.value=n.op==="min"?Math.min(r.value,o):Math.max(r.value,o)),e.set(t,r)},d=(e,t)=>e==="count"?t?.value??0:!t||t.count===0?null:e==="avg"?t.value===null?null:t.value/t.count:t.value,A=(e,t)=>{if(e.length===0)return"";const n={};for(const u of e.toSorted(c))n[u]=t[u]??null;return JSON.stringify(i(n))};export{m as aggregateTableName,l as coerceAggregateNumber,c as compareStrings,A as encodeAggregateKey,v as foldAggregateTally,d as readAggregateValue};
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import{sql as r}from"drizzle-orm";import{runDrizzle as E}from"./runDrizzle-it6rL9bR.mjs";const a="__stream_runs",o="__stream_chunks",L=e=>{E(e,r`CREATE TABLE IF NOT EXISTS ${r.identifier(a)} (
|
|
2
|
+
run_key TEXT PRIMARY KEY,
|
|
3
|
+
status TEXT NOT NULL,
|
|
4
|
+
last_seq INTEGER NOT NULL DEFAULT 0,
|
|
5
|
+
error_code TEXT,
|
|
6
|
+
error TEXT,
|
|
7
|
+
started_at REAL NOT NULL,
|
|
8
|
+
ttl_ms REAL NOT NULL
|
|
9
|
+
)`),E(e,r`CREATE TABLE IF NOT EXISTS ${r.identifier(o)} (
|
|
10
|
+
run_key TEXT NOT NULL,
|
|
11
|
+
seq INTEGER NOT NULL,
|
|
12
|
+
data_json TEXT NOT NULL,
|
|
13
|
+
PRIMARY KEY (run_key, seq)
|
|
14
|
+
)`)},d=(e,s)=>{const t=E(e,r`SELECT status, last_seq, error_code, error, started_at FROM ${r.identifier(a)} WHERE run_key = ${s} LIMIT 1`).toArray()[0];if(t!==void 0)return{...t.error===null?{}:{error:t.error},...t.error_code===null?{}:{errorCode:t.error_code},lastSeq:t.last_seq,startedAt:t.started_at,status:t.status}},N=(e,s,n,t)=>d(e,s)!==void 0?!1:(E(e,r`INSERT INTO ${r.identifier(a)} (run_key, status, last_seq, started_at, ttl_ms)
|
|
15
|
+
VALUES (${s}, ${"running"}, 0, ${n}, ${t})`),!0),$=(e,s)=>{E(e,r`DELETE FROM ${r.identifier(o)} WHERE run_key = ${s}`),E(e,r`DELETE FROM ${r.identifier(a)} WHERE run_key = ${s}`)},S=(e,s,n,t)=>{E(e,r`INSERT OR IGNORE INTO ${r.identifier(o)} (run_key, seq, data_json) VALUES (${s}, ${n}, ${t})`)},m=(e,s,n)=>E(e,r`SELECT seq, data_json FROM ${r.identifier(o)} WHERE run_key = ${s} AND seq > ${n} ORDER BY seq ASC`).toArray().map(t=>({dataJson:t.data_json,seq:t.seq})),c=(e,s,n,t,i)=>{const T=i?.code??null,_=i?.message??null;E(e,r`UPDATE ${r.identifier(a)}
|
|
16
|
+
SET status = ${n}, last_seq = ${t}, error_code = ${T}, error = ${_}
|
|
17
|
+
WHERE run_key = ${s}`)},A=(e,s)=>{E(e,r`DELETE FROM ${r.identifier(o)} WHERE run_key IN (
|
|
18
|
+
SELECT run_key FROM ${r.identifier(a)} WHERE started_at + ttl_ms < ${s}
|
|
19
|
+
)`),E(e,r`DELETE FROM ${r.identifier(a)} WHERE started_at + ttl_ms < ${s}`)};export{o as STREAM_CHUNKS_TABLE,a as STREAM_RUNS_TABLE,S as appendStreamChunk,N as claimStreamRun,$ as deleteStreamRun,c as finishStreamRun,L as migrateDurableStreams,m as readStreamChunks,d as readStreamRun,A as trimStreamRuns};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as R}from"@lunora/errors";import{applySelect as B}from"./applySelect-BQbHyo-W.mjs";const _=c=>({relationBaseWhere:c.relationBaseWhere,relationMask:c.relationMask}),W=(c,o)=>o.select?B(c,o.select,o.with):c,E=async(c,o,t,r,s)=>{const u=await Promise.all(r.map(async i=>{const w=s?{AND:[{[t]:i},s]}:{[t]:i};return[i,await c(o,w)]}));return new Map(u)},O=(c,o)=>{const t=new Set;for(const r of c){const s=r[o];s!=null&&t.add(s)}return[...t]},L=async c=>{const{groupedCounter:o,fetcher:t,parents:r,relationBaseWhere:s,relationMask:u,schema:i,tableName:w,with:D}=c,M=(a,e)=>u?.(a,e)??e;if(r.length===0)return;const y=i.tables[w];if(!y)throw new R("INTERNAL",`unknown table: ${w}`);const N=y.relationMap??{},v=a=>{const e=N[a];if(!e)throw new R("INTERNAL",`unknown relation "${a}" on table "${w}"`);return e},m=async(a,e,n)=>{const p=O(r,e.field);if(p.length===0){for(const l of r)l[a]=null;return}const{page:b}=await t(e.table,{baseWhere:s?.(e.table),relationBaseWhere:s,relationMask:u,where:{[e.references]:{in:p}},with:n.with}),k=new Map;for(const l of M(e.table,b))k.set(l[e.references],l);for(const l of r){const h=k.get(l[e.field]);l[a]=h?W([h],n)[0]??null:null}},$=async(a,e,n)=>{const p=O(r,e.references);if(p.length===0){for(const f of r)f[a]=[];return}const b={[e.field]:{in:p}},k=n.where?{AND:[n.where,b]}:b,{page:l}=await t(e.table,{baseWhere:s?.(e.table),orderBy:n.orderBy,relationBaseWhere:s,relationMask:u,where:k,with:n.with}),h=new Map;for(const f of M(e.table,l)){const d=f[e.field],V=h.get(d);V?V.push(f):h.set(d,[f])}const g=typeof n.limit=="number"?Math.max(0,Math.floor(n.limit)):void 0;for(const f of r){const d=h.get(f[e.references])??[];f[a]=W(g===void 0?d:d.slice(0,g),n)}},j=async a=>{for(const e of Object.keys(a)){const n=v(e),[p,b]=n.kind==="many"?[n.field,n.references]:[n.references,n.field],k=s?.(n.table),l=O(r,b),h=l.length===0?new Map:await o(n.table,p,l,k);for(const g of r){const f=g._count??{},d=g[b];f[e]=d==null?0:h.get(d)??0,g._count=f}}};for(const[a,e]of Object.entries(D)){if(e===void 0||e===!1)continue;if(a==="_count"){await j(e);continue}const n=v(a),p=e===!0?{}:e;await(n.kind==="one"?m(a,n,p):$(a,n,p))}},I=async(c,o,t)=>{const{deletedId:r,deletedReference:s,findHolders:u,onCascade:i,onRestrict:w,onSetNull:D,tableName:M}=c,y=t.references==="_id"?r:s(t.references);if(y==null)return;const N=await u(o,t.field,y);if(N.length!==0){t.onDelete==="restrict"&&w(`cannot delete "${M}" row: "${o}.${t.field}" still references it`);for(const v of N){const m=v._id;typeof m=="string"&&await(t.onDelete==="cascade"?i(o,m):D(o,m,t.field))}}},S=async c=>{const{schema:o,tableName:t}=c;if(!o.tables[t])throw new R("INTERNAL",`unknown table: ${t}`);for(const[r,s]of Object.entries(o.tables)){const u=s.relationMap;if(u)for(const i of Object.values(u))i.kind!=="one"||i.table!==t||!i.onDelete||await I(c,r,i)}},x=(c,o,t=!1)=>{for(const[r,s]of Object.entries(c.shape))r in o&&typeof s.parse=="function"&&(t&&o[r]===null&&s.kind==="optional"||s.parse(o[r]))};export{S as applyOnDelete,O as distinctValues,E as fanOutScalarCounts,_ as relationHooks,L as resolveWith,x as runRowValidators};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as S}from"@lunora/errors";import{d as m,e as h}from"./wire-codec-BU9T2xJ7.mjs";const y="id",b=new Set(["_id","id"]),A=o=>{const e=[];for(const t of o??[])for(const[r,s]of Object.entries(t))e.push({direction:s,field:r});return e.length===0?[{direction:"asc",field:"_creationTime"}]:e},E=o=>{const e=new TextEncoder().encode(o);let t="";for(const r of e)t+=String.fromCodePoint(r);return btoa(t)},v=o=>{const e=atob(o),t=Uint8Array.from(e,r=>r.codePointAt(0)??0);return new TextDecoder().decode(t)},D=(o,e)=>{const t=e.map(r=>o[r.field]);return t.push(o._id),E(JSON.stringify(h(t)))},f=()=>new S("BAD_REQUEST","invalid cursor"),O=o=>{let e;try{e=m(JSON.parse(v(o)))}catch{throw f()}if(!Array.isArray(e))throw f();return e},l=(o,e,t)=>{const r=o.some(n=>b.has(n.field))?o:[...o,{direction:"asc",field:y}],s=[];for(const[n,i]of r.entries()){const c=[];for(const[a,p]of r.slice(0,n).entries())c.push({[p.field]:{eq:e[a]}});const u=t(i.direction,n===r.length-1);c.push({[i.field]:{[u]:e[n]}});const[d]=c;s.push(c.length===1&&d!==void 0?d:{AND:c})}return{OR:s}},k=(o,e)=>l(o,e,t=>t==="desc"?"lt":"gt"),_=(o,e)=>o==="desc"?e?"gte":"gt":e?"lte":"lt",w=(o,e)=>l(o,e,_),C=["_id","_creationTime"],B=(o,e,t)=>{if(!e)return o;const r=new Set([...e,...C,...t?Object.keys(t):[]]);return o.map(s=>{const n={};for(const i of r)i in s&&(n[i]=s[i]);return n})},L=(o,e)=>o&&e!==!0?{[o.field]:{isNull:!0}}:void 0,x=(o,e)=>e===void 0||o[e]===null||o[e]===void 0;export{B as applySelect,w as buildSeekBeforeWhere,k as buildSeekWhere,O as decodeCursor,D as encodeCursor,v as fromBase64,f as invalidCursor,x as isLiveForCompanion,A as normalizeOrderKeys,L as softDeleteScope,E as toBase64};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as a}from"@lunora/errors";const t=()=>Object.assign(new Error("native PITR is unavailable here (local dev or a non-SQLite Durable Object); use `lunora backup restore` for off-platform recovery"),{code:"PITR_UNAVAILABLE",name:"LunoraError",status:409}),i=o=>{if(typeof o=="number")return o;const r=Date.parse(o);if(Number.isNaN(r))throw new a("BAD_REQUEST",`pitr: invalid time "${o}" — expected epoch-ms or an ISO timestamp`);return r},
|
|
1
|
+
import{LunoraError as a}from"@lunora/errors";const t=()=>Object.assign(new Error("native PITR is unavailable here (local dev or a non-SQLite Durable Object); use `lunora backup restore` for off-platform recovery"),{code:"PITR_UNAVAILABLE",name:"LunoraError",status:409}),i=o=>{if(typeof o=="number")return o;const r=Date.parse(o);if(Number.isNaN(r))throw new a("BAD_REQUEST",`pitr: invalid time "${o}" — expected epoch-ms or an ISO timestamp`);return r},k=async(o,r)=>{if(!o.getCurrentBookmark)throw t();const e=await o.getCurrentBookmark();return r===void 0||!o.getBookmarkForTime?{current:e}:{current:e,forTime:await o.getBookmarkForTime(i(r))}},s=async(o,r)=>{if(!o.onNextSessionRestoreBookmark)throw t();let e=r.bookmark;if(e===void 0){if(r.time===void 0)throw new a("BAD_REQUEST","pitrRestore: provide a `bookmark` or a `time` to restore to");if(!o.getBookmarkForTime)throw t();e=await o.getBookmarkForTime(i(r.time))}const n=await o.onNextSessionRestoreBookmark(e);return{restoredTo:e,undoBookmark:n}};export{s as armRestore,k as readBookmark};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{stableStringify as h}from"./stableStringify-CujpENIO.mjs";import{i as m,e as I}from"./wire-codec-BU9T2xJ7.mjs";const w="_id",p="_creationTime",y="page",$=e=>{let t;for(const s of e){const n=s[p];if(typeof n=="number"){if(t!==void 0){if(n<t)return!0;if(n>t)return!1}t=n}}return!1},J=(e,t)=>{const s=t[p];if(typeof s!="number")return e.length;const n=$(e);for(const[o,r]of e.entries()){const i=r[p];if(typeof i=="number"&&(n?i<s:i>s))return o}return e.length},S="__lunora__",_=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return;const t=e[w];return typeof t=="string"?t:void 0},A=e=>{const t=new Map,s=[];for(const n of e){const o=_(n);if(o===void 0||t.has(o))return;t.set(o,n),s.push(o)}return{byId:t,order:s}},x=(e,t)=>{const s=e.order.filter(o=>t.byId.has(o)),n=t.order.filter(o=>e.byId.has(o));return s.length!==n.length?!1:s.every((o,r)=>n[r]===o)},F=(e,t,s,n)=>{const o=[];for(const r of e.order)t.byId.has(r)||o.push({delta:{key:r,op:"delete",table:s},frame:`{"key":${JSON.stringify(r)},"op":"delete","table":${n}}`});return o},L=(e,t,s,n)=>{const o=[];for(const r of t.order){const i=t.byId.get(r),c=e.byId.get(r),d=JSON.stringify(I(i)),a=c===void 0?void 0:JSON.stringify(c);if(a===d)continue;const f=a===void 0?"insert":"update";o.push({delta:{key:r,op:f,row:i,table:s},frame:`{"key":${JSON.stringify(r)},"op":"${f}","row":${d},"table":${n}}`})}return o},N=(e,t)=>{if(Array.isArray(e)&&Array.isArray(t))return{next:t,previous:e};if(!m(e)||!m(t))return;const s=e[y],n=t[y];if(!Array.isArray(s)||!Array.isArray(n))return;const o=r=>Object.fromEntries(Object.entries(r).filter(([i])=>i!==y));if(h(o(e))===h(I(o(t))))return{next:n,previous:s}},E=(e,t,s)=>{const n=s.filter(({delta:r})=>r.op==="insert");if(n.length===0)return!0;const o=e.order.filter(r=>t.byId.has(r)).map(r=>e.byId.get(r));for(const{delta:r}of n){const i=r.row;o.splice(J(o,i),0,i)}return o.length===t.order.length&&o.every((r,i)=>r[w]===t.order[i])},D=(e,t,s)=>{let n;try{n=JSON.parse(e)}catch{return}const o=N(n,t);if(o===void 0)return;const r=A(o.previous),i=A(o.next);if(r===void 0||i===void 0||!x(r,i))return;const c=s===""?S:s,d=JSON.stringify(c),a=[...F(r,i,c,d),...L(r,i,c,d)];return E(r,i,a)?a:void 0},j=(e,t,s,n)=>{const o=D(e,t,s);if(o!==void 0){if(n!==void 0)for(const{frame:r}of o)n.push(r);return o.map(({delta:r})=>r)}},k=(e,t)=>{try{return e.send(t),!0}catch{return!1}},M=e=>{const{cursorSuffix:t,lastMutationId:s,nextResult:n,pageDeltas:o,previousJson:r,snapshotJson:i,subId:c,table:d}=e,a=JSON.stringify(c),f=(s===void 0?"":`,"lastMutationId":${String(s)}`)+t,u=`{"type":"data","id":${a},"data":${i}${f}}`,l=r!==void 0&&(o===!0||Array.isArray(n))?D(r,n,d):void 0;if(l===void 0||l.length===0)return[u];const g=[];let v=0;for(const{frame:O}of l){const b=`{"type":"delta","id":${a},"delta":${O}${f}}`;if(v+=b.length,v>=u.length)return[u];g.push(b)}return g},B=async e=>{let t=0;for(;t<100;){t+=1;const{bufferedAmount:s}=e;if(typeof s!="number"||s<1048576)return;await new Promise(n=>{setTimeout(n,20)})}};export{B as awaitWsDrain,M as subscriptionFrames,j as subscriptionListDeltas,k as trySendFrame};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{r as k,i as A,a as p,j as $,y as E,S as O,h as C}from"./ctx-db-companions-lTt-rvKG.mjs";import{sql as n}from"drizzle-orm";import{matchesStaticWhere as L}from"./AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs";import{aggregateTableName as M,encodeAggregateKey as _,foldAggregateTally as y}from"./aggregateTableName-Cy5e03oz.mjs";import{migrateSearchState as D,readSearchBackfillState as F,writeSearchBackfillState as x}from"./SEARCH_STATE_TABLE-Dju8ebbU.mjs";import{runDrizzle as d}from"./runDrizzle-it6rL9bR.mjs";import{i as T,r as b,a as N,b as v,A as B,D as S,h as G}from"./do-sql-Dk_DJxn4.mjs";import{isLiveForCompanion as U}from"./applySelect-BQbHyo-W.mjs";import{rankTableName as W,matchesRankStaticWhere as j}from"./RANK_TIEBREAK-ci3MaM65.mjs";const H=(e,i)=>e.profile!==i?{cursor:void 0,finished:!1,wipe:e.cursor!==void 0||e.done}:{cursor:e.cursor,finished:e.done,wipe:!1},I=(e,i)=>d(e,n`SELECT COUNT(*) AS count FROM ${n.identifier(i)}`).one().count>0,R=(e,i)=>d(e,n`SELECT id, _creationTime, ${n.identifier(S)} FROM ${n.identifier(i)}`).toArray(),K=(e,i,t,o)=>{const r=M(i,t.name);if(I(e,r))return;const c=t.by??[],f=new Map,s=R(e,i);for(const l of s){const a=b(l);if(!a||!U(a,o)||t.where&&!L(a,t.where))continue;const g=_(c,a);y(f,g,t,a)}for(const[l,a]of f)d(e,n`INSERT INTO ${n.identifier(r)} (${N}, ${v}, ${B}) VALUES (${l}, ${a.value}, ${a.count})`)},oe=(e,i)=>{for(const[t,o]of Object.entries(i.tables))if(!(o.shardMode?.kind==="global"||!o.aggregateIndexes))for(const r of o.aggregateIndexes)K(e,t,r,o.softDeleteMode?.field)},V=(e,i,t)=>{const o=W(i,t.name);if(I(e,o))return;const r=k(t),c=R(e,i);for(const f of c){const s=b(f);!s||t.where&&!j(s,t.where)||A(e,o,t,r,s._id,s)}},ne=(e,i)=>{for(const[t,o]of Object.entries(i.tables))if(!(o.shardMode?.kind==="global"||!o.rankIndexes))for(const r of o.rankIndexes)V(e,t,r)},u=500,w=(e,i,t)=>{const o=p(i,t.name),{profile:r}=$(t.language),c=H(F(e,o),r);if(c.finished)return!0;c.wipe&&d(e,n`DELETE FROM ${n.identifier(o)}`);const{cursor:f}=c,s=d(e,f===void 0?n`SELECT id, _creationTime, ${n.identifier(S)} FROM ${n.identifier(i)} ORDER BY id ASC LIMIT ${n.raw(String(u))}`:n`SELECT id, _creationTime, ${n.identifier(S)} FROM ${n.identifier(i)} WHERE id > ${f} ORDER BY id ASC LIMIT ${n.raw(String(u))}`).toArray();let l=f;for(const g of s){const{id:m}=g;if(typeof m!="string")continue;l=m,d(e,n`DELETE FROM ${n.identifier(o)} WHERE ${n.identifier(E)} = ${m}`);const h=G(g);h&&d(e,n`INSERT INTO ${n.identifier(o)} (${n.identifier(O)}, ${n.identifier(E)}) VALUES (${C(h,t)}, ${m})`)}const a=s.length<u;return x(e,o,l,a,r),a},ie=(e,i,t)=>{if(T(e))for(const o of t.searchIndexes??[])o.staged||w(e,i,o)},te=(e,i)=>{if(T(e)){D(e);for(const[t,o]of Object.entries(i.tables))if(!(o.shardMode?.kind==="global"||!o.searchIndexes))for(const r of o.searchIndexes){let c=!1;for(;!c;)c=w(e,t,r)}}};export{oe as backfillAggregateIndexes,ne as backfillRankIndexes,te as backfillSearchIndexes,ie as backfillSearchIndexesForTable};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const o=r=>{let n="";for(let t=0;t<r.length;t+=32768)n+=String.fromCharCode(...r.subarray(t,t+32768));return btoa(n)},a=r=>{const n=atob(r),e=new Uint8Array(n.length);for(let t=0;t<n.length;t+=1)e[t]=n.codePointAt(t)??0;return e};export{a as f,o as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const E=t=>{const o=new DataView(new ArrayBuffer(8));o.setFloat64(0,t,!1);let n=o.getUint32(0,!1),e=o.getUint32(4,!1);return(n&2147483648)===0?n=(n^2147483648)>>>0:(n=~n>>>0,e=~e>>>0),n.toString(16).padStart(8,"0")+e.toString(16).padStart(8,"0")},v=t=>{const o=new TextEncoder().encode(t);let n="";for(const e of o)n+=e.toString(16).padStart(2,"0");return n},a=t=>{if(t===null)return"0";if(typeof t=="number")return Number.isFinite(t)?`1${E(t===0?0:t)}`:void 0;if(typeof t=="string")return`2${v(t)}`},l=t=>{const o=[];for(const n of t){const e=a(n);if(e===void 0)return;o.push(e)}return o.join("!")};const p=new Set([">",">="]),x=new Set(["<","<="]),A=(t,o,n,e)=>{const i=o.comparator==="=",r=p.has(o.comparator)||x.has(o.comparator);return!i&&!r||t.indexOf(o.field)!==n?!1:e===void 0?!0:!i&&e===o.field},h=(t,o,n)=>{const e={equalities:[],lowerExclusive:!1,upperExclusive:!1};let i;for(const r of o){const s=r.comparator==="=",c=p.has(r.comparator);if(!A(t,r,e.equalities.length,i))return;if(s){e.equalities.push(n(r.value));continue}if(i=r.field,c){if(e.lower!==void 0)return;e.lower=n(r.value),e.lowerExclusive=r.comparator===">"}else{if(e.upper!==void 0)return;e.upper=n(r.value),e.upperExclusive=r.comparator==="<"}}return e},f=(t,o)=>{const n=a(o);if(n!==void 0)return t===""?n:t+"!"+n},g=(t,o,n,e,i)=>{if(n.length===0)return;const r=h(n,e,i);if(!r)return;const s=l(r.equalities);if(s===void 0)return;let c=s,d=s+"";if(r.lower!==void 0){const u=f(s,r.lower);if(u===void 0)return;c=r.lowerExclusive?u+"!":u}if(r.upper!==void 0){const u=f(s,r.upper);if(u===void 0)return;d=r.upperExclusive?u:u+""}if(!(c>=d))return{hi:d,index:o,lo:c,table:t}},m=(t,o,n)=>{const e=[];for(const i of t){const r=l(i.fields.map(s=>n(o[s])));r!==void 0&&e.push({index:i.name,key:r})}return e},w=(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 n=new Map;for(const e of o){const i=n.get(e.index);i?i.push(e):n.set(e.index,[e])}return t.some(e=>{const i=n.get(e.index);return!i||i.length===0?!0:i.some(r=>w(e,r))})};export{g as buildIndexRange,m as indexKeysForRow,S as keysTouchRanges,w as rangeContains};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{e as h}from"./wire-codec-BU9T2xJ7.mjs";const u=(t,e)=>{if(!e)return t;const a=Object.create(null);for(const n of["_id","_creationTime",...e])Object.hasOwn(t,n)&&(a[n]=t[n]);return a},y=(t,e,a)=>{const{columns:n,table:p}=a,i=new Map,r=[];for(const{doc:o,id:s}of t){const c=u(o,n),f=JSON.stringify(h(c));i.set(s,f);const d=e.get(s);d===void 0?r.push({key:s,op:"insert",table:p,value:c}):d!==f&&r.push({key:s,op:"update",table:p,value:c})}for(const o of e.keys())i.has(o)||r.push({key:o,op:"delete",table:p});return{next:i,rowsPatch:r}},l=t=>t.map(e=>e.value===void 0?e:{...e,value:h(e.value)}),b=(t,e,a={})=>{const{baseCheckpoint:n,checkpoint:p,epoch:i,lastMutationId:r,pokeId:o}=e,s=[JSON.stringify({baseCheckpoint:n,epoch:i,pokeId:o,type:"pokeStart"})];for(const c of t){const f=a.preEncoded?c.rowsPatch:l(c.rowsPatch);s.push(JSON.stringify({pokeId:o,rowsPatch:f,shapeId:c.shapeId,type:"pokePart",...r===void 0?{}:{lastMutationId:r}}))}return s.push(JSON.stringify({checkpoint:p,epoch:i,pokeId:o,type:"pokeEnd"})),s};export{b as buildPokeFrames,y as diffGlobalMembership,l as encodeRowsPatch,u as projectColumns};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{quoteIdentifier as l}from"./quoteIdentifier-CObIFRhb.mjs";import{reprojectionMigrationTable as u}from"./REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{REPROJECTION_MIGRATION_PREFIX as v,reprojectionMigrationId as w}from"./REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{e as m}from"./wire-codec-BU9T2xJ7.mjs";import{runSql as p}from"./runDrizzle-it6rL9bR.mjs";import{k as d,D as E}from"./do-sql-Dk_DJxn4.mjs";import{m as g}from"./sql-projection-BqmxFxQU.mjs";const b=m(0n)[0],_=e=>e.shardMode?.kind==="global"?[]:Object.entries(e.shape).filter(([,r])=>g(r)).map(([r])=>r),M=e=>Object.entries(e.tables).filter(([,r])=>_(r).length>0).map(([r])=>r),f=e=>{const r=`json_each(${l(E)}) AS __f__`;return{params:[JSON.stringify(e),b,"bigint","bytes"],sql:`EXISTS (SELECT 1 FROM ${r} WHERE __f__.type = 'array' AND __f__.key IN (SELECT value FROM json_each(?)) AND json_extract(__f__.value, '$[0]') = ? AND json_extract(__f__.value, '$[1]') IN (?, ?))`}},N=(e,r,o)=>{if(o.length===0)return 0;const{params:t,sql:n}=f(o);return p(e,`SELECT COUNT(*) AS count FROM ${l(r)} WHERE ${n}`,...t).toArray()[0]?.count??0},R=(e,r,o,t)=>{const{params:n,sql:i}=f(o);return p(e,`SELECT 1 FROM ${l(r)} WHERE id = ? AND (${i}) LIMIT 1`,t,...n).toArray().length>0},S=(e,r,o)=>{const t=u(e);if(t===void 0)return;const n=r.tables[t];if(!n)return;const i=_(n);if(i.length!==0)return{id:e,table:t,up:s=>{const a=s._id;if(!(typeof a!="string"||!R(o,t,i,a))){try{d(s)}catch(c){console.warn(`${e}: skipping row ${a} — it cannot be re-projected: ${c instanceof Error?c.message:String(c)}`);return}return s}}}};export{v as REPROJECTION_MIGRATION_PREFIX,S as buildReprojectionMigration,N as countLegacyRows,_ as reprojectableFields,w as reprojectionMigrationId,M as reprojectionTables};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const u=/key|secret|token|password|passwd|credential|private|auth|bearer|session|cookie|salt|signature|dsn|webhook/iu,f=new Set(["LUNORA_ADMIN_TOKEN","LUNORA_WS_BEARER"]),l=["CF_PAGES_URL","WORKER_URL","LUNORA_WORKER_URL"],c=["CF_ENV","ENVIRONMENT","WORKER_ENV","NODE_ENV"],d=n=>n.length<=4?"••••":`${n.slice(0,4)}${"•".repeat(Math.min(8,n.length-4))}`,p=n=>u.test(n),R=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"},E=n=>{const e=i=>i.map(a=>n[a]).find(a=>typeof a=="string"&&a!==""),t={},o=e(l),r=e(c);o!==void 0&&(t.workerUrl=o),r!==void 0&&(t.environment=r);const s=n.CF_VERSION_METADATA;if(s!==null&&typeof s=="object"){const i=s;typeof i.id=="string"&&(t.deploymentId=i.id),typeof i.tag=="string"&&(t.versionTag=i.tag)}return t},N=/^(?:dev(?:elopment)?|local(?:host)?|test)$/iu,_=n=>{const e=n??{};for(const t of c){const o=e[t];if(typeof o=="string"&&N.test(o))return!0}return!1},g=n=>{const e=n??{},t=[];for(const[o,r]of Object.entries(e))if(!f.has(o)){if(typeof r=="string"){const s=p(o);t.push({kind:s?"secret":"var",name:o,value:d(r)});continue}if(typeof r=="number"||typeof r=="boolean"){t.push({kind:"var",name:o,value:String(r)});continue}if(r!==null&&typeof r=="object"){t.push({bindingType:R(r),kind:"binding",name:o,value:null});continue}t.push({kind:"var",name:o,value:null})}return t.sort((o,r)=>o.name.localeCompare(r.name)),{deploy:E(e),settings:t}};export{R as bindingType,g as buildSettings,_ as isDevEnvironment,p as looksSecret,E as readDeployInfo,d as redact};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as L}from"@lunora/errors";import{sql as s}from"drizzle-orm";import{sqliteInList as a,WORKERD_SQLITE_LIMITS as I}from"./param-Ib8WHnrF.mjs";import{RELATION_EXISTS_KEY as N}from"./RELATION_EXISTS_KEY-CFUhnZSZ.mjs";const m=["eq","ne","lt","lte","gt","gte","in","notIn","isNull","contains"],T=new Set(m),E={eq:"=",gt:">",gte:">=",lt:"<",lte:"<=",ne:"<>"},O=t=>{if(t===null||typeof t!="object"||Array.isArray(t))return!1;const o=Object.keys(t);return o.length>0&&o.every(n=>T.has(n))},$=(t,o,n)=>{const i=s`${n.serialize(o)}`;return n.containsExpr?n.containsExpr(t,i):s`instr(lower(${t}), lower(${i})) > 0`},A=(t,o,n,i,r)=>i===null?o==="ne"?s`${t} IS NOT NULL`:s`${t} IS NULL`:s`${t} ${s.raw(n)} ${r.serialize(i)}`,S=(t,o,n,i)=>{const r=Array.isArray(n)?n:[];if(r.length===0)return o==="IN"?s`0 = 1`:s`1 = 1`;const e=r.map(l=>i.serialize(l)),c=o==="NOT IN";return(i.inList??a)(t,e,c)},M=(t,o,n)=>{const i=s.join(o.map(r=>s`${r}`),s`, `);return n?s`${t} NOT IN (${i})`:s`${t} IN (${i})`},h=(t,o,n)=>{const i=o,r=[];for(const e of m){if(!(e in i))continue;const c=i[e],l=E[e];l?r.push(A(t,e,l,c,n)):e==="isNull"?r.push(c?s`${t} IS NULL`:s`${t} IS NOT NULL`):e==="contains"?r.push($(t,c,n)):r.push(S(t,e==="in"?"IN":"NOT IN",c,n))}return r},R=(t,o,n)=>{const i=n.fieldRef(t);return O(o)?h(i,o,n):o===null?[s`${i} IS NULL`]:[s`${i} = ${n.serialize(o)}`]},p=(t,o)=>{if(t.length<=1)return t[0];const n=Math.floor(t.length/2);return s`(${p(t.slice(0,n),o)}) ${s.raw(o)} (${p(t.slice(n),o)})`},d=(t,o,n)=>{const i=Array.isArray(t)?t:[],r=[];for(const e of i){const c=f(e??{},n);c&&r.push(c)}return r.length===0?o==="OR"?s`0 = 1`:void 0:p(r,o)},_=new Set(["AND","NOT","OR",N]),b=(t,o,n)=>{if(t===N){if(!n.relationExists)throw new L("INTERNAL","encountered a relation EXISTS marker without a relationExists strategy hook");return n.relationExists(o)}if(t==="NOT"){const i=f(o??{},n);return i?s`NOT (${i})`:void 0}return d(o,t,n)},f=(t,o)=>{const n=[];for(const[i,r]of Object.entries(t))if(_.has(i)){const e=b(i,r,o);e&&n.push(e)}else n.push(...R(i,r,o));return p(n,"AND")},j=I.boundParams/2,u=t=>{if(Array.isArray(t))return t.reduce((n,i)=>n+u(i),0);if(t===null||typeof t!="object")return 0;let o=0;for(const[n,i]of Object.entries(t))n==="in"||n==="notIn"?o+=1:(n==="AND"||n==="NOT"||n==="OR"||O(i))&&(o+=u(i));return o},q=(t,o)=>{if(!t||Object.keys(t).length===0)return;const n=o.inList??a,i=u(t);if(i===0)return f(t,o);const r=Math.max(1,Math.floor(j/i));return f(t,{...o,inList:(e,c,l)=>n(e,c,l,r)})};export{q as compileWhereSql,M as literalInList};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as A}from"@lunora/errors";import{sql as o}from"drizzle-orm";import{mergeWhere as j}from"./CountRlsUnsupportedError-Bdfupt3g.mjs";import{SCAN_DEP as q}from"./SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as S}from"./runDrizzle-it6rL9bR.mjs";import{sqliteInList as O}from"./param-Ib8WHnrF.mjs";import{decodeCursor as F,toBase64 as V}from"./applySelect-BQbHyo-W.mjs";import{rankTableName as z,sortColumnName as H,resolveRankPartition as U,RANK_TIEBREAK as _,encodePartitionKey as J}from"./RANK_TIEBREAK-ci3MaM65.mjs";const P="__doc__",Y=n=>V(JSON.stringify(n)),G=n=>n.after?[n.after.partitionKey,...n.after.sortValues,n.after.rowId]:n.cursor?F(n.cursor):void 0,Q=(n,r,a)=>{if(n?.length!==1+r.length+1)return;const t=[{column:"__partition__",direction:"asc"}];for(const[s,c]of r.entries())t.push({column:c,direction:a[s]?.direction??"asc"});t.push({column:_,direction:"asc"});const e=[];for(const[s,c]of t.entries()){const u=[];for(const[i,p]of t.slice(0,s).entries())u.push(o`${o.identifier(p.column)} IS ${n[i]}`);u.push(o`${o.identifier(c.column)} ${o.raw(c.direction==="desc"?"<":">")} ${n[s]}`);const[f]=u;e.push(u.length===1&&f!==void 0?f:o`(${o.join(u,o` AND `)})`)}return o`(${o.join(e,o` OR `)})`},T=null,X=(n,r)=>{if(n===void 0)return T;const a=[n.__partition__,...r.map(t=>n[t]),n[_]];return Y(a)},Z=(n,r,a)=>{const t=[];for(const e of n){const s=e[_];if(typeof s!="string")continue;const c=r.get(s);if(!c)continue;const u=typeof e.__partition__=="string"?e.__partition__:"",f=a.map(i=>e[i]??null);t.push({doc:c,key:{partitionKey:u,rowId:s,sortValues:f}})}return t},oo=o`${o.identifier("id")}`,no=(n,r,a)=>{const{rowToDocument:t}=n,e=new Map;if(a.length===0)return e;const s=S(n.sql,o`SELECT id, _creationTime, ${o.identifier(P)} FROM ${o.identifier(r)} WHERE ${O(oo,a,!1)}`).toArray();for(const c of s){const u=t(c),f=c.id;u&&typeof f=="string"&&e.set(f,u)}return e},fo=(n,r,a,t)=>{const{assertRankPartitionLocal:e,ensureRankBackfilled:s,onRead:c,schema:u}=n,f=u.tables[r];if(!f)throw new A("INTERNAL",`unknown table: ${r}`);const i=f.rankIndexes?.find(d=>d.name===a);if(!i)throw new A("INTERNAL",`unknown rankIndex "${a}" on table "${r}"`);e(r,f,i),c(r,q),s(r,i);const p=z(r,i.name),l=i.sortBy.map((d,w)=>H(w)),h=Math.max(1,Math.min(1e3,Math.floor(t.take??100))),B=j(t.baseWhere,t.where),k=U(i,B),$=[o`${o.identifier("__partition__")} ASC`];for(const[d,w]of l.entries()){const b=i.sortBy[d]?.direction;$.push(o`${o.identifier(w)} ${o.raw(b==="desc"?"DESC":"ASC")}`)}$.push(o`${o.identifier(_)} ASC`);const m=[];typeof t.partitionKey=="string"?m.push(o`${o.identifier("__partition__")} = ${t.partitionKey}`):k&&m.push(o`${o.identifier("__partition__")} = ${J(i.partitionBy??[],k)}`);const D=G(t),E=Q(D,l,i.sortBy);E&&m.push(E);const I=o.identifier(_),g=o.identifier("__partition__"),L=m.length>0?o` WHERE ${o.join(m,o` AND `)}`:o``,M=l.length>0?o`${I}, ${g}, ${o.join(l.map(d=>o.identifier(d)),o`, `)}`:o`${I}, ${g}`,v=o`SELECT ${M} FROM ${o.identifier(p)}${L} ORDER BY ${o.join($,o`, `)} LIMIT ${o.raw(String(h+1))}`,R=S(n.sql,v).toArray(),C=R.length>h,y=C?R.slice(0,h):R,K=y.map(d=>d[_]),x=Z(y,no(n,r,K),l),N=C?X(y.at(-1),l):T,W=i.sortBy.map(d=>d.direction==="desc"?"desc":"asc");return{continueCursor:N,directions:W,hasMore:C,rows:x}};export{fo as computeRankPage,no as hydrateDocsById};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{c as l,i as C,r as R}from"./ctx-db-companions-lTt-rvKG.mjs";import"./AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs";import"./aggregateTableName-Cy5e03oz.mjs";import"./runDrizzle-it6rL9bR.mjs";import"./do-sql-Dk_DJxn4.mjs";import"./param-Ib8WHnrF.mjs";import"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import"./applySelect-BQbHyo-W.mjs";import"./RANK_TIEBREAK-ci3MaM65.mjs";import"./sql-projection-BqmxFxQU.mjs";import"./serializeSqlValue-DbI1VQYM.mjs";export{l as createCompanionSync,C as insertRankRow,R as rankColumnsSql};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const s=()=>{const n=new Set,t=new Map,o=new Set;return{onRead(e){n.add(e),o.add(e)},onReadRange(e){n.add(e.table);const a=t.get(e.table);a?a.push(e):t.set(e.table,[e])},ranges(){for(const e of o)t.delete(e);return t.size>0?t:void 0},tables:n}};export{s as createReadFootprint};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import{v as w,R as v,e as f,s as y,a as g,b as A}from"./sibling-channel-BRZpLiDA.mjs";const N=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"],T=new Set(N),L=s=>typeof s=="string"&&T.has(s),h="::replica::",E=s=>{const e=s.lastIndexOf(h);if(e===-1)return;const t=s.slice(0,e),n=s.slice(e+h.length);if(!(t.length===0||!L(n)))return{ownerKey:t,region:n}},O=s=>{if(s==null||!/^\d+$/.test(s))return;const e=Number.parseInt(s,10);return Number.isSafeInteger(e)&&e>0?e:void 0},b=1e3,R=1e3,I=10,C=5e4,q=s=>f(s,"LUNORA_REPLICA_MAX_BOOTSTRAP_ROWS",C),d="__replica_state",u=new WeakSet,S=s=>{u.has(s)||(s.exec(`CREATE TABLE IF NOT EXISTS ${d} (
|
|
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
|
+
)`),u.add(s))},c=s=>(S(s),s.exec(`SELECT epoch, applied_seq AS appliedSeq, synced_at AS syncedAtMs FROM ${d} WHERE id = 1`).toArray()[0]),l=(s,e)=>{S(s),s.exec(`INSERT INTO ${d} (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)},m=s=>{const e=s.doName();if(e!==void 0&&E(e)!==void 0)return new Response("replica cannot serve replicas",{status:409});if(s.ownerEpoch()===void 0)return new Response("shard has no changelog to replicate",{status:409});if(g(s.env())===void 0)return new Response("replica control requires LUNORA_RELAY_SECRET",{status:403})},P=async(s,e)=>{const t=m(s);if(t!==void 0)return t;const n=s.ownerEpoch();let i;try{i=await e.text()}catch{return new Response("bad request",{status:400})}if(!await w(s.env(),e.headers.get(v),i))return new Response("forbidden",{status:403});let r;try{r=JSON.parse(i)}catch{return new Response("bad request",{status:400})}if(r.type==="replica_bootstrap"){if(s.rowCount()>q(s.env()))return Response.json({cursor:0,epoch:n,rows:[],truncated:!0});const o=s.ownerCursor()??0,a=await s.exportRows();return Response.json({cursor:o,epoch:n,rows:a})}if(r.type==="replica_pull"){const o=typeof r.sinceSeq=="number"&&Number.isInteger(r.sinceSeq)&&r.sinceSeq>=0?r.sinceSeq:0,{changes:a,cursor:_}=s.readChanges(o,R),p=s.ownerFloor();return Response.json({changes:a,cursor:_,epoch:n,...p===void 0?{}:{floor:p}})}return new Response("unknown replica frame",{status:400})};class U{constructor(e,t,n){this.host=e,this.ownerKey=t,this.region=n}host;ownerKey;region;divergent=!1;inFlight;async ensureFresh(e){if(this.divergent)return"unavailable";if(this.isCaughtUp(e))return"fresh";this.inFlight??=this.advance(e).finally(()=>{this.inFlight=void 0});const t=await this.inFlight;return t==="fresh"&&!this.isCaughtUp(e)?"stale":t}appliedSeq(){return c(this.host.sql())?.appliedSeq??0}isDivergent(){return this.divergent}async advance(e){let t=c(this.host.sql());if(t===void 0){const n=await this.bootstrap();if(n===void 0)return"unavailable";t=n}return this.catchUp(t,e)}isCaughtUp(e){const t=c(this.host.sql());return t!==void 0&&this.isFreshEnough(t,e)}async catchUp(e,t){let n=e;for(let i=0;i<I;i+=1){const r=await this.pull(n.appliedSeq);if(r===void 0)return t===void 0&&this.isFreshEnough(n,void 0)?"fresh":"unavailable";if(this.hasDiverged(n,r))return"unavailable";const o=r.changes.length<R;if(n=await this.applyPage(r),o||this.isFreshEnough(n,t))return this.isFreshEnough(n,t)?"fresh":"stale"}return this.isFreshEnough(n,t)?"fresh":"stale"}async applyPage(e){e.changes.length>0&&await this.host.applyChanges(e.changes);const t={appliedSeq:e.cursor,epoch:e.epoch,syncedAtMs:Date.now()};return l(this.host.sql(),t),t}hasDiverged(e,t){const n=t.changes.length===0&&t.cursor>e.appliedSeq,i=t.floor??(n?t.cursor:0),r=i>0&&i>e.appliedSeq+1;return t.epoch===e.epoch&&!r?!1:(this.divergent=!0,!0)}async bootstrap(){const e=await this.request({type:"replica_bootstrap"});if(e===void 0)return;const t=await e.json();if(t.truncated===!0){this.divergent=!0;return}const{errors:n}=await this.host.importRows(t.rows);if(n.length>0){this.divergent=!0;return}const i={appliedSeq:t.cursor,epoch:t.epoch,syncedAtMs:Date.now()};return l(this.host.sql(),i),i}isFreshEnough(e,t){return t!==void 0?e.appliedSeq>=t:Date.now()-e.syncedAtMs<=f(this.host.env(),"LUNORA_REPLICA_MAX_STALENESS_MS",b)}async pull(e){const t=await this.request({sinceSeq:e,type:"replica_pull"});return t===void 0?void 0:await t.json()}async request(e){const t=this.host.shardBinding(),n=y(this.host.env(),t,this.ownerKey);if(n===void 0)return;const i=JSON.stringify(e),r={"content-type":"application/json","x-lunora-shard-binding":t??""},o=g(this.host.env());o!==void 0&&(r[v]=await A(o,i));try{const a=await n.fetch("https://replica.internal/_lunora/replica",{body:i,headers:r,method:"POST"});return a.ok?a:void 0}catch{return}}}const x=s=>{const e=s.doName();if(e===void 0)return;const t=E(e);return t===void 0?void 0:new U(s,t.ownerKey,t.region)},M=async(s,e,t)=>{if(e.headers.get("x-lunora-replica-read")!=="1")return Response.json({error:{code:"REPLICA_READ_ONLY",message:`"${t}" is a write and cannot run on a read replica`}},{status:421});const n=await s.ensureFresh(O(e.headers.get("x-lunora-min-seq")));if(n!=="fresh")return Response.json({error:{code:"REPLICA_NOT_READY",message:`replica is ${n} for this read`}},{headers:{"x-lunora-replica-fallback":n},status:421})};export{x as createReplicaLink,M as gateReplicaDispatch,P as handleReplicaControl};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as c}from"@lunora/errors";const d=e=>{const t={args:e.args??{},enqueuedAt:typeof e.enqueuedAt=="number"?e.enqueuedAt:0,functionPath:typeof e.functionPath=="string"?e.functionPath:"",id:typeof e.id=="string"?e.id:"",scheduledFor:typeof e.scheduledFor=="number"?e.scheduledFor:0};return typeof e.attempts=="number"&&(t.attempts=e.attempts),typeof e.shardKey=="string"&&(t.shardKey=e.shardKey),t},i=e=>{const t={key:typeof e.key=="string"?e.key:"",size:typeof e.size=="number"?e.size:0},r=e.httpMetadata?.contentType??e.contentType;typeof r=="string"&&(t.contentType=r),e.customMetadata&&typeof e.customMetadata=="object"&&(t.customMetadata=e.customMetadata),typeof e.sha256=="string"&&(t.sha256=e.sha256);const{uploaded:a}=e;return typeof a=="number"?t.uploaded=a:a instanceof Date&&(t.uploaded=a.getTime()),t},h=(e={})=>{const t=()=>{if(!e.scheduler)throw new c("INTERNAL",'ctx.db.system.query("_scheduled_functions"): no scheduler configured. Pass `scheduler` to createShardDO().');return e.scheduler},r=()=>{if(!e.storage)throw new c("INTERNAL",'ctx.db.system.query("_storage"): no storage configured. Pass `storage` to createShardDO().');return e.storage},a=async()=>(await t().list()).map(s=>d(s)),f=async()=>{const{objects:n}=await r().list();return n.map(s=>i(s))};return{get:(async(n,s)=>{if(n==="_scheduled_functions"){const o=await t().get(s);return o?d(o):null}const u=await r().getMetadata(s);return u?i(u):null}),query:(n=>n==="_scheduled_functions"?{collect:a}:{collect:f})}};export{h as createSystemReader};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{sql as e}from"drizzle-orm";import{matchesStaticWhere as P,aggregateSqlFunction as le}from"./AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs";import{aggregateTableName as N,encodeAggregateKey as L,foldAggregateTally as J,coerceAggregateNumber as C}from"./aggregateTableName-Cy5e03oz.mjs";import{runDrizzle as $}from"./runDrizzle-it6rL9bR.mjs";import{i as fe,g as ue,D,r as M,a as q,b as S,A as g,c as j,e as z}from"./do-sql-Dk_DJxn4.mjs";import{param as de,WORKERD_SQLITE_LIMITS as $e}from"./param-Ib8WHnrF.mjs";import{encodeGeohash as me,GEO_DEFAULT_PRECISION as Ee}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{isLiveForCompanion as Q}from"./applySelect-BQbHyo-W.mjs";import{encodePartitionKey as pe,sortColumnName as he,rankTableName as Z,matchesRankStaticWhere as x}from"./RANK_TIEBREAK-ci3MaM65.mjs";import{m as ge}from"./sql-projection-BqmxFxQU.mjs";import{serializeSqlValue as ee}from"./serializeSqlValue-DbI1VQYM.mjs";const ye=["de","en","es","fr","it","nl","none","pt"],_e=n=>ye.includes(n),Se="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",we="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",Te="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",ve="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",Re="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",Ae="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",be="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ê",Fe=/[\u0300-\u036F]/gu,oe=n=>n.normalize("NFD").replaceAll(Fe,"").normalize("NFC").toLowerCase(),k=n=>new Set(oe(n).split(" ")),Oe={de:k(we),en:k(Se),es:k(Te),fr:k(ve),it:k(Re),nl:k(Ae),none:new Set,pt:k(be)},Ie=2,Le=256,X=new Map,ke=n=>{const r=n!==void 0&&_e(n)?n:"none",c=X.get(r);if(c)return c;const w=Oe[r],y=i=>{const A=(oe(i).match(/[\p{L}\p{N}]+/gu)??[]).filter(T=>T.length<=Le);return w.size===0?A:A.filter(T=>!w.has(T))},E={document:y,profile:`${r}-v${String(Ie)}`,query:i=>{const A=y(i);return A.filter((T,F)=>A.lastIndexOf(T)===F)}};return X.set(r,E),E},qe=(n,r)=>{if(!r.includes("."))return n[r];let c=n;for(const w of r.split(".")){if(c===null||typeof c!="object"||Array.isArray(c))return;c=c[w]}return c},Ce=(n,r)=>`${n}__fts_${r}`,je="__text__",Y="__id__",De=1e3,Me=(n,r)=>r.document(n),U=(n,r)=>qe(n,r),ze=n=>typeof n=="string"?n:n==null?"":typeof n=="number"||typeof n=="bigint"||typeof n=="boolean"?String(n):JSON.stringify(n)??"",Ue=(n,r,c)=>n!==void 0&&r!==void 0&&U(n,c.field)===U(r,c.field),We=(n,r)=>Me(ze(U(n,r.field)),ke(r.language)).slice(0,De).join(" "),He=(n,r,c)=>[...n.partitionBy??[],...n.sortBy.map(y=>y.field),...n.where?Object.keys(n.where):[]].every(y=>r[y]===c[y]),ne=n=>e.join(["__id__","__partition__",...n.sortBy.map((r,c)=>he(c))].map(r=>e.identifier(r)),e`, `),te=(n,r,c,w,y,E)=>{const i=pe(c.partitionBy??[],E),A=c.sortBy.map(F=>ee(E[F.field]??null)),T=e.join([y,i,...A].map(F=>de(F)),e`, `);$(n,e`INSERT INTO ${e.identifier(r)} (${w}) VALUES (${T})`)},Be=(n,r,c,w,y,E)=>{if(y&&E&&He(c,y,E))return;const i=Z(r,c.name);y&&$(n,e`DELETE FROM ${e.identifier(i)} WHERE ${e.identifier("__id__")} = ${w}`),!(!E||c.where&&!x(E,c.where))&&te(n,i,c,ne(c),w,E)},oo=n=>{const{broadcast:r,indexKeysFor:c,invalidateCache:w,recordCdc:y,schema:E,sql:i}=n,A=new Set,T=t=>E.tables[t]?.softDeleteMode?.field,F=new Set,W=(t,o)=>{const a=`${t}::${o.name}`;if(A.has(a))return;const f=N(t,o.name),u=o.by??[],d=T(t),p=new Map,_=$(i,e`SELECT id, _creationTime, ${e.identifier(D)} FROM ${e.identifier(t)}`).toArray();for(const v of _){const m=M(v);if(!m||!Q(m,d)||o.where&&!P(m,o.where))continue;const R=L(u,m);J(p,R,o,m)}$(i,e`DELETE FROM ${e.identifier(f)}`);const b=Math.floor($e.boundParams/3),O=[...p];for(let v=0;v<O.length;v+=b){const m=O.slice(v,v+b),R=e.join(m.map(([s,l])=>e`(${s}, ${l.value}, ${l.count})`),e`, `);$(i,e`INSERT INTO ${e.identifier(f)} (${q}, ${S}, ${g}) VALUES ${R}`)}A.add(a)},se=(t,o,a)=>{const f=o.by??[],u=o.field??"",d=[],p=(s,l)=>{const h=ee(l);h===null?d.push(e`${z(s)} IS NULL`):d.push(e`${z(s)} = ${h}`)};for(const s of f)p(s,a[s]??null);const _=T(t);_!==void 0&&p(_,null);for(const[s,l]of Object.entries(o.where??{}))p(s,l!==null&&typeof l=="object"&&!Array.isArray(l)?l.eq:l);const b=d.length>0?e` WHERE ${e.join(d,e` AND `)}`:e``,O=E.tables[t]?.shape[u];if(O&&ge(O)){const s=$(i,e`SELECT id, _creationTime, ${e.identifier(D)} FROM ${e.identifier(t)}${b}`).toArray(),l=new Map;for(const h of s){const I=M(h);I&&J(l,"",o,I)}return{value:l.get("")?.value??null}}const v=le(o.op),m=z(u);return{value:$(i,e`SELECT ${e.raw(v)}(${m}) AS value FROM ${e.identifier(t)}${b}`).one().value??null}},ie=(t,o,a,f)=>{const u=N(t,o.name),{op:d}=o,p=o.field??"",_=s=>{$(i,e`DELETE FROM ${e.identifier(u)} WHERE ${q} = ${s} AND ${g} <= 0`)},b=T(t),O=s=>!o.where||P(s,o.where),v=s=>Q(s,b)&&O(s);f!==void 0&&d!=="count"&&O(f)&&C(f[p]);const m=a&&v(a)?a:void 0,R=f&&v(f)?f:void 0;if(!(!m&&!R)){if(d==="count"){for(const[s,l]of[[m,-1],[R,1]]){if(!s)continue;const h=L(o.by??[],s);$(i,j(u,h,l,l,e`${S} = ${S} + excluded.${S}, ${g} = ${g} + excluded.${g}`))}m&&_(L(o.by??[],m));return}if(d==="sum"||d==="avg"){for(const[s,l]of[[m,-1],[R,1]]){if(!s)continue;const h=C(s[p]);if(h===void 0)continue;const I=L(o.by??[],s);$(i,j(u,I,l*h,l,e`${S} = COALESCE(${S}, 0) + excluded.${S}, ${g} = ${g} + excluded.${g}`))}m&&_(L(o.by??[],m));return}if(m){const s=L(o.by??[],m),l=C(m[p]),h=$(i,e`SELECT ${S} AS value, ${g} AS count FROM ${e.identifier(u)} WHERE ${q} = ${s}`).toArray()[0],I=(h?.count??0)-1;if(I<=0)$(i,e`DELETE FROM ${e.identifier(u)} WHERE ${q} = ${s}`);else if(h&&l!==void 0&&h.value!==null&&l===h.value){const ce=se(t,o,m);$(i,e`UPDATE ${e.identifier(u)} SET ${S} = ${ce.value}, ${g} = ${I} WHERE ${q} = ${s}`)}else $(i,e`UPDATE ${e.identifier(u)} SET ${g} = ${g} - 1 WHERE ${q} = ${s}`)}if(R){const s=L(o.by??[],R),l=C(R[p]);if(l===void 0)$(i,j(u,s,null,1,e`${g} = ${g} + 1`));else{const h=d==="min"?"MIN":"MAX";$(i,j(u,s,l,1,e`${S} = ${e.raw(h)}(COALESCE(${S}, excluded.${S}), excluded.${S}), ${g} = ${g} + 1`))}}}},re=t=>{for(const o of E.tables[t]?.aggregateIndexes??[])W(t,o)},H=(t,o,a)=>{for(const f of E.tables[t]?.aggregateIndexes??[])ie(t,f,o,a)},B=(t,o)=>{const a=`${t}::rank::${o.name}`;if(F.has(a))return;const f=Z(t,o.name),u=$(i,e`SELECT id, _creationTime, ${e.identifier(D)} FROM ${e.identifier(t)}`).toArray();$(i,e`DELETE FROM ${e.identifier(f)}`);const d=ne(o);for(const p of u){const _=M(p);!_||o.where&&!x(_,o.where)||te(i,f,o,d,_._id,_)}F.add(a)},ae=t=>{for(const o of E.tables[t]?.rankIndexes??[])B(t,o)},K=(t,o,a,f)=>{for(const u of E.tables[t]?.rankIndexes??[])Be(i,t,u,o,a,f)},V=(t,o,a,f)=>{const u=E.tables[t]?.searchIndexes??[];if(!(u.length===0||!fe(i)))for(const d of u){if(Ue(f,a,d))continue;const p=Ce(t,d.name);$(i,e`DELETE FROM ${e.identifier(p)} WHERE ${e.identifier(Y)} = ${o}`),a&&$(i,e`INSERT INTO ${e.identifier(p)} (${e.identifier(je)}, ${e.identifier(Y)}) VALUES (${We(a,d)}, ${o})`)}},G=(t,o,a)=>{for(const f of E.tables[t]?.geoIndexes??[]){const u=ue(t,f.name);$(i,e`DELETE FROM ${e.identifier(u)} WHERE ${e.identifier("__id__")} = ${o}`);const d=a?.[f.field];if(d!==null&&typeof d=="object"&&typeof d.lat=="number"&&typeof d.lng=="number"){const{lat:p,lng:_}=d,b=me({lat:p,lng:_},f.precision??Ee);$(i,e`INSERT INTO ${e.identifier(u)} (${e.identifier("__id__")}, ${e.identifier("__geohash__")}, ${e.identifier("__lat__")}, ${e.identifier("__lng__")}) VALUES (${o}, ${b}, ${p}, ${_})`)}}};return{ensureBackfilledForTable:re,ensureBackfilledIndex:W,ensureRankBackfilled:B,ensureRankBackfilledForTable:ae,syncAggregates:H,syncCompanionsForInsert:(t,o,a)=>{V(t,o,a),G(t,o,a),H(t,void 0,a),K(t,o,void 0,a),w(t,o,a),y(t,o,"insert",a),r({indexKeys:c(t,a),key:o,op:"insert",row:a,table:t})},syncGeo:G,syncRanks:K,syncSearch:V}};export{je as S,Ce as a,oo as c,We as h,te as i,ke as j,ne as r,Me as s,Y as y};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createShardCtxDb as S}from"./NotUniqueError-BixDiv4O.mjs";import{createRelayLink as B}from"./DEFAULT_MAX_RELAYS-DeVcEXBh.mjs";import{ConflictError as I}from"./ConflictError-C8GtJmjS.mjs";import{runShardMigrations as v}from"./runShardMigrations-Crppyq1f.mjs";import{relayName as F}from"./DEFAULT_PROMOTION_THRESHOLDS-DVTD9iu0.mjs";const _=(E,u={})=>({_meta:{column:{notNull:!0,...u}},kind:E}),D=(E,u,N)=>{const{describe:k,expect:i,it:m}=N;k(`engine contract: ${E}`,()=>{k("optimistic concurrency",()=>{const b=h=>({tables:{items:{indexes:[],shape:{title:_("string"),version:_("number",{notNull:!1})},triggerMap:{clobber:{handler:()=>{h.exec(`UPDATE "items" SET "__doc__" = json_set("__doc__", '$.version', 99) WHERE "id" = 'i1'`)},op:"update",timing:"before"}}}}});m("raises a CONFLICT of kind `occ` when a write's snapshot is clobbered",async()=>{const{close:h,host:d}=u();try{const c=d.sql,l=b(c);v(c,l);const s=S({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(I)}finally{h?.()}}),m("reports the conflict as CONFLICT/409 rather than retrying it away",async()=>{const{close:h,host:d}=u();try{const c=d.sql,l=b(c);v(c,l);const s=S({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let a;try{await s.patch("i1",{title:"second"})}catch(t){a=t}const e=a;i(e.code).toBe("CONFLICT"),i(e.kind).toBe("occ")}finally{h?.()}}),m("leaves the row readable and unchanged after a conflict",async()=>{const{close:h,host:d}=u();try{const c=d.sql,l=b(c);v(c,l);const s=S({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 a=await s.get("i1");i(a?.title).toBe("first"),i(a?.version).toBe(99)}finally{h?.()}}),m("raises a CONFLICT of kind `trigger` when a trigger writes its own row through the db",async()=>{const{close:h,host:d}=u();try{const c=d.sql,l={tables:{items:{indexes:[],shape:{title:_("string"),version:_("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=S({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let a;try{await s.patch("i1",{title:"second"})}catch(t){a=t}const e=a;i(e).toBeInstanceOf(I),i(e.code).toBe("CONFLICT"),i(e.kind).toBe("trigger")}finally{h?.()}})}),k("shape-poke ordering",()=>{const b="shard-a",h={args:{},name:"messages"},d=(e,t,o,n)=>e.accept(t?.()??{},{connectionId:o,shapes:{[n]:h}}),c=(e,t)=>{let o=0,n=0;const r=g=>()=>{throw new Error(`the relay poke path must not reach RelayHost.${g}`)},p={fetch:(g,O)=>{if(JSON.parse(O?.body??"{}").type!=="relay_shape_subscribe")return Promise.resolve(new Response(void 0,{status:204}));const C=t[n];if(n+=1,C===void 0)throw new Error("the relay asked for more seeds than this fixture supplies");return Promise.resolve(Response.json(C))}},y={get:()=>p,getByName:()=>p,idFromName:g=>g},w={buildShapeDiff:r("buildShapeDiff"),computeOpLogShapeSeed:r("computeOpLogShapeSeed"),currentCdcEpoch:r("currentCdcEpoch"),deliverWhisperLocal:r("deliverWhisperLocal"),doName:()=>F(b,0),env:()=>({SHARD:y}),getWebSockets:()=>e.getSockets(),maskMetadata:r("maskMetadata"),nextPokeId:()=>(o+=1,`poke-${String(o)}`),readAttachment:g=>g.deserializeAttachment?.(),recordShapePokeFanout:()=>{},resolveShape:r("resolveShape"),rlsMetadata:r("rlsMetadata"),shardBinding:()=>"SHARD",sql:r("sql")},f=B(w);if(f===void 0)throw new Error("expected a relay link for a `…::relay::N` name");return f},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 n=await e.seedRelayShape(t,o,h,{identity:void 0,userId:void 0});if(n!=="ok")throw new Error(`seed failed: ${JSON.stringify(n)}`)},a=(e={})=>l({...h,checkpoint:20,epoch:"e1",fromCursor:10,rowsPatch:[{id:"r1",op:"upsert",value:{title:"hello"}}],type:"relay_shape_poke",...e});m("frames a poke as pokeStart → pokePart per shape → pokeEnd, under one poke id",async()=>{const{close:e,createSocket:t,readFrames:o,sockets:n}=u();try{const r=c(n,[{cursor:10,epoch:"e1",frames:[]}]),p=d(n,t,"c-alice","s1");await s(r,p,"s1"),await r.handleControl(a());const w=(await o(p)).map(f=>JSON.parse(f));i(w.map(f=>f.type)).toStrictEqual(["pokeStart","pokePart","pokeEnd"]),i(new Set(w.map(f=>f.pokeId)).size).toBe(1),i(w[1]?.shapeId).toBe("s1"),i(w[2]?.checkpoint).toBe(20)}finally{e?.()}}),m("delivers a poke only to sockets whose cursor matches, and advances them past it",async()=>{const{close:e,createSocket:t,readFrames:o,sockets:n}=u();try{const r=c(n,[{cursor:10,epoch:"e1",frames:[]},{cursor:7,epoch:"e1",frames:[]}]),p=d(n,t,"c-alice","s1"),y=d(n,t,"c-bob","s2");await s(r,p,"s1"),await s(r,y,"s2"),await r.handleControl(a());const w=await o(p);i(w.length).toBe(3);const f=await o(y);i(f.length).toBe(0),await r.handleControl(a());const g=await o(p);i(g.length).toBe(3)}finally{e?.()}}),m("skips a socket whose cursor matches under a different CDC epoch",async()=>{const{close:e,createSocket:t,readFrames:o,sockets:n}=u();try{const r=c(n,[{cursor:10,epoch:"e1",frames:[]}]),p=d(n,t,"c-alice","s1");await s(r,p,"s1"),await r.handleControl(a({epoch:"e2"}));const y=await o(p);i(y.length).toBe(0),await r.handleControl(a());const w=await o(p);i(w.length).toBe(3)}finally{e?.()}})}),k("RLS identity under live subscription",()=>{const b="shard-a",h={args:{},name:"lobby-messages"},d={args:{},name:"my-orders"},c=s=>{const a=[],e=[],t={fetch:(r,p)=>(a.push(JSON.parse(p?.body??"{}")),Promise.resolve(new Response(void 0,{status:204})))},n=B({buildShapeDiff:()=>[{id:"r1",op:"upsert",value:{}}],computeOpLogShapeSeed:()=>({baseCheckpoint:void 0,cursor:10,epoch:"e1",rowsPatch:[]}),currentCdcEpoch:()=>"e1",deliverWhisperLocal:()=>0,doName:()=>b,env:()=>({SHARD:{get:()=>t,getByName:()=>t,idFromName:r=>r}}),getWebSockets:()=>[],maskMetadata:()=>({columns:[]}),nextPokeId:()=>"poke-1",readAttachment:()=>({}),recordShapePokeFanout:()=>{},resolveShape:(r,p,y)=>(e.push(y),r===d.name?{columns:["id"],effectiveWhere:{org:y?.identity?.org??"anonymous"},global:!1,table:"orders"}:{columns:["id"],effectiveWhere:{room:"lobby"},global:!1,table:"messages"}),rlsMetadata:()=>({policies:[]}),shardBinding:()=>"SHARD",sql:()=>s});if(n===void 0)throw new Error("expected an owner link for an un-suffixed DO name");return{owner:n,posts:a,resolvedUnder:e}},l=async(s,a)=>{await s.handleControl(new Request("https://owner.internal/_lunora/relay",{body:JSON.stringify({...a,connectionId:"c-alice",identity:{org:"acme"},relayIndex:0,subId:"s1",type:"relay_shape_subscribe",userId:"u1"}),headers:{"content-type":"application/json"},method:"POST"}))};m("seeds a subscriber under its own forwarded identity, never the anonymous one",async()=>{const{close:s,host:a}=u();try{const{owner:e,resolvedUnder:t}=c(a.sql);await l(e,d),i(t.some(o=>o?.userId==="u1"&&o.identity?.org==="acme")).toBe(!0)}finally{s?.()}}),m("routes an identity-scoped shape to a per-socket poke, not the cohort multicast",async()=>{const{close:s,host:a}=u();try{const{owner:e,posts:t}=c(a.sql);await l(e,d),t.length=0,await e.onFlush(new Set(["orders"]),20);const o=t.filter(n=>n.type==="relay_shape_poke");i(o.length).toBe(1),i(o[0]?.targetConnectionId).toBe("c-alice")}finally{s?.()}}),m("still multicasts an identity-blind shape to the whole cohort",async()=>{const{close:s,host:a}=u();try{const{owner:e,posts:t}=c(a.sql);await l(e,h),t.length=0,await e.onFlush(new Set(["messages"]),20);const o=t.filter(n=>n.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{stableStringify as u}from"./stableStringify-CujpENIO.mjs";const l=(t,s)=>{const o={_id:t._id};if(s){for(const e of s)Object.hasOwn(t,e)&&(o[e]=t[e]);return o}for(const[e,n]of Object.entries(t))e!=="_id"&&e!=="_creationTime"&&(o[e]=n);return o},j=(t,s,o)=>{const{columns:e,table:n}=o,c=[],d=new Map;for(const r of t){const i=l(r,e),f=String(i._id),a=u(i);d.set(f,a);const p=s.get(f);p===void 0?c.push({doc:i,id:f,op:"insert",seq:0,table:n,ts:0}):p!==a&&c.push({doc:i,id:f,op:"update",seq:0,table:n,ts:0})}for(const r of s.keys())d.has(r)||c.push({id:r,op:"delete",seq:0,table:n,ts:0});return{changes:c,nextBaseline:d}};export{j as diffExternalSource,l as projectExternalSourceRow};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as c}from"@lunora/errors";import{sql as n}from"drizzle-orm";import{quoteIdentifier as m}from"./quoteIdentifier-CObIFRhb.mjs";import{d as T,e as $}from"./wire-codec-BU9T2xJ7.mjs";import{runDrizzle as l}from"./runDrizzle-it6rL9bR.mjs";import{s as A}from"./sql-projection-BqmxFxQU.mjs";import"./serializeSqlValue-DbI1VQYM.mjs";const E=/^[A-Za-z_$][\w$]*$/u,p=e=>E.test(e)?e:`"${e.replaceAll("\\",String.raw`\\`).replaceAll('"',String.raw`\"`)}"`,d="__doc__",i="__originals__",C=e=>{if(Object.hasOwn(e,i))throw new c("BAD_REQUEST",`"${i}" is reserved by the row store's document encoding and cannot be used as a field name — rename the field`);let t,o;for(const[r,s]of Object.entries(e)){const a=A(s);a!==void 0&&(t??={...e},o??=Object.create(null),t[r]=a,o[r]=s)}t&&o&&(t[i]=o);try{return JSON.stringify($(t??e))}catch(r){throw new c("BAD_REQUEST",`this document cannot be stored: ${r instanceof Error?r.message:String(r)}`)}},S=e=>{const t=T(JSON.parse(e)),{[i]:o,...r}=t;return o===null||typeof o!="object"||Array.isArray(o)?t:{...r,...o}},L=(e,t)=>`${e}__geo_${t}`,u=(e,t)=>t==="_id"||t==="id"?`${e}id`:t==="_creationTime"?`${e}_creationTime`:`json_extract(${e}${d}, '$.${p(t).replaceAll("'","''")}')`,h=e=>u("",e),P=e=>n.raw(h(e)),O=(e,t)=>u(`${m(e)}.`,t),R=(e,t)=>n.raw(O(e,t)),G=(e,t,o,r)=>n`CREATE ${r?n`UNIQUE `:n``}INDEX IF NOT EXISTS ${n.identifier(e)} ON ${n.identifier(t)} (${o})`,_=n.identifier("__key__"),b=n.identifier("__value__"),g=n.identifier("__count__"),q=(e,t,o,r,s)=>n`INSERT INTO ${n.identifier(e)} (${_}, ${b}, ${g}) VALUES (${t}, ${o}, ${r}) ON CONFLICT(${_}) DO UPDATE SET ${s}`,J=e=>{const t=[];for(const[o,r]of Object.entries(e.shape)){const s=r._meta?.column;s&&t.push([o,s])}return t},y=e=>{if(!e)return;const t=e[d];let o;typeof t=="string"?o=S(t):t&&typeof t=="object"?o=t:o={};const{id:r}=e;typeof r=="string"&&(o._id=r);const s=e._creationTime;return typeof s=="number"&&(o._creationTime=s),o},B=e=>{try{return y(e)}catch{return}},f=new WeakMap,F=e=>{const t=f.get(e);if(t!==void 0)return t;let o;try{l(e,n`CREATE VIRTUAL TABLE IF NOT EXISTS ${n.identifier("__lunora_fts_probe")} USING fts5(x)`),o=!0}catch{o=!1}finally{try{l(e,n`DROP TABLE IF EXISTS ${n.identifier("__lunora_fts_probe")}`)}catch{}}return f.set(e,o),o};export{g as A,d as D,_ as a,b,q as c,G as d,P as e,R as f,L as g,B as h,F as i,h as j,C as k,S as l,p as m,i as n,O as q,y as r,J as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{B as s}from"./sql-projection-BqmxFxQU.mjs";const n=40,f=i=>{let e=0;const o=(r,t)=>typeof t=="bigint"?(e+=s+1+n,t.toString()):t instanceof ArrayBuffer||ArrayBuffer.isView(t)?(e+=2*Math.ceil(t.byteLength/3)*4+n,""):t;try{const r=JSON.stringify(i,o);return(r===void 0?0:r.length)+e}catch{return}};export{f as e};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{toErrorBody as f}from"@lunora/errors";const l=200,b=(r,n)=>{const i=e=>{const o=r.tables[e];return o!==void 0&&o.shardMode?.kind!=="global"};return(n&&n.length>0?[...n]:Object.keys(r.tables)).filter(e=>i(e))},p=async function*(r,n,i=l){let e=null,o=!1;for(;!o;){const t=await r.findMany(n,{cursor:e,limit:i});for(const s of t.page)yield{doc:s,table:n};e=t.continueCursor,o=t.isDone||e===null}},A=async function*(r,n,i){const e=b(n,i.tables),o=i.batchSize??l;for(const t of e)yield*p(r,t,o)},u=new Set(["_creationTime","_id"]),y=(r,n)=>{for(const[i,e]of Object.entries(r.shape)){const o=n[i];if(o===void 0&&e.kind==="optional")continue;const t=e.parse;if(typeof t=="function")try{t(o)}catch(s){const c=s instanceof Error?s.message:String(s);return`field "${i}": ${c}`}}},h=(r,n,i)=>{const e=r.tables[n];if(!e)return`unknown table: ${n}`;if(e.shardMode?.kind==="global")return`table "${n}" is a global (.global()) table and is not importable through the shard import path`;const o=Object.fromEntries(Object.entries(i).filter(([t])=>!u.has(t)));for(const t of Object.keys(o))if(!(t in e.shape))return`unexpected field "${t}": not declared in table "${n}"`;return y(e,o)},m=async(r,n)=>{try{return await r.get(n)!==null}catch{return!1}},g=async(r,n,i,e)=>{const{doc:o,table:t}=i;if(typeof t!="string"||t.length===0)return{error:{code:"BAD_ROW",line:e,message:"row is missing `table`",table:t},kind:"error"};if(!o||typeof o!="object"||Array.isArray(o))return{error:{code:"BAD_ROW",line:e,message:"row is missing or malformed `doc`",table:t},kind:"error"};const s=h(n,t,o);if(s!==void 0)return{error:{code:"VALIDATION_ERROR",line:e,message:s,table:t},kind:"error"};const c=typeof o._id=="string"?o._id:void 0;if(c!==void 0&&await m(r,c))return{kind:"conflict"};try{return await r.insert(t,o,{allowExplicitId:!0}),{kind:"inserted",table:t}}catch(a){const{body:d}=f(a,{fallbackCode:"INSERT_FAILED"});return{error:{code:d.code,line:e,message:d.message,table:t},kind:"error"}}},S=async(r,n,i)=>{const e=[],o={};let t=0,s=(i.startLine??1)-1;for(const c of i.rows){s+=1;const a=await g(r,n,c,s);a.kind==="error"?e.push(a.error):a.kind==="conflict"?t+=1:o[a.table]=(o[a.table]??0)+1}return{conflicts:t,errors:e,inserted:o}},k=r=>{const n=Array.isArray(r.tables)?r.tables.filter(e=>typeof e=="string"):void 0;return{batchSize:typeof r.batchSize=="number"?r.batchSize:void 0,tables:n}},E=r=>{const n=Array.isArray(r.rows)?r.rows:[],i=[];for(const o of n){if(!o||typeof o!="object")continue;const t=o;if(typeof t.table!="string"||!t.doc||typeof t.doc!="object"||Array.isArray(t.doc)){i.push({doc:t.doc??{},table:typeof t.table=="string"?t.table:""});continue}i.push({doc:t.doc,table:t.table})}const e=typeof r.startLine=="number"?r.startLine:void 0;return{rows:i,startLine:e}};export{A as exportShardRows,p as exportShardTable,S as importShardRows,k as parseExportShardArgs,E as parseImportShardArgs,b as selectExportTables,h as validateImportRow};
|