@lunora/shard-engine 1.0.0-alpha.94 → 1.0.0-alpha.96
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 +27 -33
- package/dist/index.d.ts +27 -33
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/{ADMIN_FUNCTIONS-DE3r3jrY.mjs → ADMIN_FUNCTIONS-D5mzmLFo.mjs} +1 -1
- package/dist/packem_shared/{AGG_COUNT-DaRHrce8.mjs → AGG_COUNT-DNnEXtyM.mjs} +1 -1
- package/dist/packem_shared/{AUDIT_LOG_TABLE-CMhmmmgR.mjs → AUDIT_LOG_TABLE-CZNxCRLv.mjs} +1 -1
- package/dist/packem_shared/{CDC_LOG_TABLE-Bkv7JskR.mjs → CDC_LOG_TABLE-QaBxSIZM.mjs} +1 -1
- package/dist/packem_shared/{CLIENT_WATERMARK_TABLE-DPY-NtOH.mjs → CLIENT_WATERMARK_TABLE-vLjfNhBR.mjs} +1 -1
- package/dist/packem_shared/{COMMIT_SEQ_FIELD-6lGDFLgk.mjs → COMMIT_SEQ_FIELD-BY_vc9bw.mjs} +1 -1
- package/dist/packem_shared/{CURSOR_PREFIX-Bn8SFoGd.mjs → CURSOR_PREFIX-BX8jkMJa.mjs} +1 -1
- package/dist/packem_shared/{DATA_MIGRATION_STATE_TABLE-mUH4b2lA.mjs → DATA_MIGRATION_STATE_TABLE-BMbxLEaN.mjs} +1 -1
- package/dist/packem_shared/{DEFAULT_MAX_RELATION_KEYS-B1zeutIo.mjs → DEFAULT_MAX_RELATION_KEYS-CYPZfQH9.mjs} +1 -1
- package/dist/packem_shared/{DEFAULT_MAX_RELAYS-CSb6oGUZ.mjs → DEFAULT_MAX_RELAYS-hdowkC2x.mjs} +1 -1
- package/dist/packem_shared/{DEFAULT_PROMOTION_THRESHOLDS-Bfx7KakS.mjs → DEFAULT_PROMOTION_THRESHOLDS-91RH_llq.mjs} +1 -1
- package/dist/packem_shared/{DurableStreamRunner-k4x__lMt.mjs → DurableStreamRunner-Dk9Pn-B8.mjs} +1 -1
- package/dist/packem_shared/{GLOBAL_SHAPE_SNAPSHOT_TABLE-BpFE-qYL.mjs → GLOBAL_SHAPE_SNAPSHOT_TABLE-pMxZ-obU.mjs} +1 -1
- package/dist/packem_shared/{IDEMPOTENCY_TABLE-CUc9L-o_.mjs → IDEMPOTENCY_TABLE-AOJCuq5U.mjs} +1 -1
- package/dist/packem_shared/{MAIL_RETENTION-kYNWpCbY.mjs → MAIL_RETENTION-BxAGL3hK.mjs} +1 -1
- package/dist/packem_shared/NotUniqueError-D4EV8EzO.mjs +1 -0
- package/dist/packem_shared/{QUEUE_TABLE-D-5_s2hl.mjs → QUEUE_TABLE-DKANxmEZ.mjs} +1 -1
- package/dist/packem_shared/{REACTOR_STATE_TABLE-XAIYdVL0.mjs → REACTOR_STATE_TABLE-B8IehLv8.mjs} +1 -1
- package/dist/packem_shared/{RELATED_DEFAULT_LIMIT-B9PH28Pn.mjs → RELATED_DEFAULT_LIMIT-CBYQQIrZ.mjs} +1 -1
- package/dist/packem_shared/{RLS_UNWRAP_SYMBOL-BwwTbz3Q.mjs → RLS_UNWRAP_SYMBOL-rSxYzw-G.mjs} +1 -1
- package/dist/packem_shared/{SCHEDULE_OUTBOX_TABLE-wAAIitt2.mjs → SCHEDULE_OUTBOX_TABLE-CgLvGxpY.mjs} +1 -1
- package/dist/packem_shared/{SCHEMA_HISTORY_MAX_VERSIONS-CYVBglZe.mjs → SCHEMA_HISTORY_MAX_VERSIONS-BMcUIqBY.mjs} +1 -1
- package/dist/packem_shared/{SEARCH_STATE_TABLE-BlVsBsix.mjs → SEARCH_STATE_TABLE-wgl-SePe.mjs} +1 -1
- package/dist/packem_shared/{SHAPE_POKE_CURSOR_TABLE-BVskv7ei.mjs → SHAPE_POKE_CURSOR_TABLE-cn0stGAL.mjs} +1 -1
- package/dist/packem_shared/{VECTOR_BACKFILL_MAX_PAGES-TviV2Xnr.mjs → VECTOR_BACKFILL_MAX_PAGES-B2ZWxshy.mjs} +1 -1
- package/dist/packem_shared/WORKERD_SQLITE_LIMITS-DBH23L_S.mjs +1 -0
- package/dist/packem_shared/appendStreamChunk-7ZyAZGg_.mjs +17 -0
- package/dist/packem_shared/{applyOnDelete-7JZ4vR9r.mjs → applyOnDelete-DJsOG8tz.mjs} +1 -1
- package/dist/packem_shared/{archiveCdcSegment-CMAVUCck.mjs → archiveCdcSegment-BON69Nug.mjs} +1 -1
- package/dist/packem_shared/{backfillAggregateIndexes-DBY2H269.mjs → backfillAggregateIndexes-B_3xdOgV.mjs} +1 -1
- package/dist/packem_shared/{buildReprojectionMigration-Do3UTuDO.mjs → buildReprojectionMigration-IMrfRdvU.mjs} +1 -1
- package/dist/packem_shared/{buildSettings-DC3VeQ0H.mjs → buildSettings-BRkZd6_E.mjs} +1 -1
- package/dist/packem_shared/{buildShapeDiff-B5YzZbjX.mjs → buildShapeDiff-D-J_GmC1.mjs} +1 -1
- package/dist/packem_shared/{clearMemoryTables-BCDG0X9P.mjs → clearMemoryTables-CogAvVHR.mjs} +1 -1
- package/dist/packem_shared/compileWhereSql-DLfUbHc-.mjs +1 -0
- package/dist/packem_shared/{computeRankPage-BEyDlhws.mjs → computeRankPage-3AiKfT8q.mjs} +1 -1
- package/dist/packem_shared/{createCompanionSync-uTsHTJWE.mjs → createCompanionSync-Rjn0lsT6.mjs} +1 -1
- package/dist/packem_shared/createReplicaLink-Z82FMxvY.mjs +7 -0
- package/dist/packem_shared/{ctx-db-relay-shapes-DBRHlvNu.mjs → ctx-db-relay-shapes-DuqhDLw8.mjs} +1 -1
- package/dist/packem_shared/{ctx-db-search-state-z0OqNIGe.mjs → ctx-db-search-state-DVCp4JQf.mjs} +1 -1
- package/dist/packem_shared/{defineEngineContractSuite-Dsx4iWIy.mjs → defineEngineContractSuite-BkVGn8QW.mjs} +1 -1
- package/dist/packem_shared/{do-sql-DpyjVz_6.mjs → do-sql-BEFrJUds.mjs} +1 -1
- package/dist/packem_shared/{exportShardRows-BFpaZI99.mjs → exportShardRows-CTDgQEF8.mjs} +1 -1
- package/dist/packem_shared/{fts-companion-DcGBHZiM.mjs → fts-companion-pUdD6kF-.mjs} +1 -1
- package/dist/packem_shared/{ftsCompanionDdl-BaLv81YG.mjs → ftsCompanionDdl-Co6WSyCB.mjs} +1 -1
- package/dist/packem_shared/{isSoftDeleted-LAXWNkhC.mjs → isSoftDeleted-sGRSPPQq.mjs} +1 -1
- package/dist/packem_shared/{materializeExternalRows-CTCrmga8.mjs → materializeExternalRows-DhINQHwd.mjs} +1 -1
- package/dist/packem_shared/{runDrizzle-BlpM0R9P.mjs → runDrizzle-Du5HLitO.mjs} +1 -1
- package/dist/packem_shared/{runShardMigrations-BtAyuuJb.mjs → runShardMigrations-MXioI81k.mjs} +1 -1
- package/dist/packem_shared/{selectExpiredIds-BVZtw3Wb.mjs → selectExpiredIds-DQg6v5Uf.mjs} +1 -1
- package/dist/packem_shared/{selectShapeMembers-DTA3YUf4.mjs → selectShapeMembers-BXhvEt4X.mjs} +1 -1
- package/dist/packem_shared/where-sql-DFs8Zw7-.mjs +1 -0
- package/package.json +2 -2
- package/dist/packem_shared/NotUniqueError-Cnw4ctAu.mjs +0 -1
- package/dist/packem_shared/WORKERD_SQLITE_LIMITS-DlozcSQu.mjs +0 -1
- package/dist/packem_shared/appendStreamChunk-BRwBOTEN.mjs +0 -19
- package/dist/packem_shared/compileWhereSql-Bi04r4ut.mjs +0 -1
- package/dist/packem_shared/createReplicaLink-D_kkf5IG.mjs +0 -7
- package/dist/packem_shared/where-sql-BV8Kg4_B.mjs +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createShardCtxDb as v}from"./NotUniqueError-
|
|
1
|
+
import{createShardCtxDb as v}from"./NotUniqueError-D4EV8EzO.mjs";import{createRelayLink as I}from"./DEFAULT_MAX_RELAYS-hdowkC2x.mjs";import{ConflictError as N}from"./ConflictError-C8GtJmjS.mjs";import{runShardMigrations as _}from"./runShardMigrations-MXioI81k.mjs";import{relayName as F}from"./DEFAULT_PROMOTION_THRESHOLDS-91RH_llq.mjs";const E=(C,m={})=>({_meta:{column:{notNull:!0,...m}},kind:C}),W=(C,m,O)=>{const{describe:S,expect:n,it:y}=O;S(`engine contract: ${C}`,()=>{S("optimistic concurrency",()=>{const b=u=>({tables:{items:{indexes:[],shape:{title:E("string"),version:E("number",{notNull:!1})},triggerMap:{clobber:{handler:()=>{u.exec(`UPDATE "items" SET "__doc__" = json_set("__doc__", '$.version', 99) WHERE "id" = 'i1'`)},op:"update",timing:"before"}}}}});y("raises a CONFLICT of kind `occ` when a write's snapshot is clobbered",async()=>{const{close:u,host:h}=m();try{const i=h.sql,l=b(i);_(i,l);const s=v({schema:l,sql:i});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0}),await n(s.patch("i1",{title:"second"})).rejects.toBeInstanceOf(N)}finally{u?.()}}),y("reports the conflict as CONFLICT/409 rather than retrying it away",async()=>{const{close:u,host:h}=m();try{const i=h.sql,l=b(i);_(i,l);const s=v({schema:l,sql:i});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let o;try{await s.patch("i1",{title:"second"})}catch(t){o=t}const e=o;n(e.code).toBe("CONFLICT"),n(e.kind).toBe("occ")}finally{u?.()}}),y("leaves the row readable and unchanged after a conflict",async()=>{const{close:u,host:h}=m();try{const i=h.sql,l=b(i);_(i,l);const s=v({schema:l,sql:i});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});try{await s.patch("i1",{title:"second"})}catch{}const o=await s.get("i1");n(o?.title).toBe("first"),n(o?.version).toBe(99)}finally{u?.()}}),y("raises a CONFLICT of kind `trigger` when a trigger writes its own row through the db",async()=>{const{close:u,host:h}=m();try{const i=h.sql,l={tables:{items:{indexes:[],shape:{title:E("string"),version:E("number",{notNull:!1})},triggerMap:{recurse:{handler:async(t,a)=>{await t.db.patch(a.doc._id,{version:99})},op:"update",timing:"before"}}}}};_(i,l);const s=v({schema:l,sql:i});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let o;try{await s.patch("i1",{title:"second"})}catch(t){o=t}const e=o;n(e).toBeInstanceOf(N),n(e.code).toBe("CONFLICT"),n(e.kind).toBe("trigger")}finally{u?.()}})}),S("shape-poke ordering",()=>{const b="shard-a",u={args:{},name:"messages"},h=(e,t,a,r)=>e.accept(t?.()??{},{connectionId:a,shapes:{[r]:u}}),i=(e,t,a)=>{let r=0,d=0;const c=g=>()=>{throw new Error(`the relay poke path must not reach RelayHost.${g}`)},p={fetch:(g,q)=>{if(JSON.parse(q?.body??"{}").type!=="relay_shape_subscribe")return Promise.resolve(new Response(void 0,{status:204}));const B=a[d];if(d+=1,B===void 0)throw new Error("the relay asked for more seeds than this fixture supplies");return Promise.resolve(Response.json(B))}},k={get:()=>p,getByName:()=>p,idFromName:g=>g},w={buildShapeDiff:c("buildShapeDiff"),computeOpLogShapeSeed:c("computeOpLogShapeSeed"),currentCdcEpoch:c("currentCdcEpoch"),deliverWhisperLocal:c("deliverWhisperLocal"),doName:()=>F(b,0),env:()=>({SHARD:k}),getWebSockets:()=>e.getSockets(),maskMetadata:c("maskMetadata"),nextPokeId:()=>(r+=1,`poke-${String(r)}`),readAttachment:g=>g.deserializeAttachment?.(),recordShapePokeFanout:()=>{},resolveShape:c("resolveShape"),rlsMetadata:c("rlsMetadata"),shardBinding:()=>"SHARD",shardJurisdiction:()=>{},sql:()=>t},f=I(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,a)=>{const r=await e.seedRelayShape(t,a,u,{identity:void 0,userId:void 0});if(r!=="ok")throw new Error(`seed failed: ${JSON.stringify(r)}`)},o=(e={})=>l({...u,checkpoint:20,epoch:"e1",fromCursor:10,rowsPatch:[{id:"r1",op:"upsert",value:{title:"hello"}}],type:"relay_shape_poke",...e});y("frames a poke as pokeStart → pokePart per shape → pokeEnd, under one poke id",async()=>{const{close:e,createSocket:t,host:a,readFrames:r,sockets:d}=m();try{const c=i(d,a.sql,[{cursor:10,epoch:"e1",frames:[]}]),p=h(d,t,"c-alice","s1");await s(c,p,"s1"),await c.handleControl(o());const w=(await r(p)).map(f=>JSON.parse(f));n(w.map(f=>f.type)).toStrictEqual(["pokeStart","pokePart","pokeEnd"]),n(new Set(w.map(f=>f.pokeId)).size).toBe(1),n(w[1]?.shapeId).toBe("s1"),n(w[2]?.checkpoint).toBe(20)}finally{e?.()}}),y("delivers a poke only to sockets whose cursor matches, and advances them past it",async()=>{const{close:e,createSocket:t,host:a,readFrames:r,sockets:d}=m();try{const c=i(d,a.sql,[{cursor:10,epoch:"e1",frames:[]},{cursor:7,epoch:"e1",frames:[]}]),p=h(d,t,"c-alice","s1"),k=h(d,t,"c-bob","s2");await s(c,p,"s1"),await s(c,k,"s2"),await c.handleControl(o());const w=await r(p);n(w.length).toBe(3);const f=await r(k);n(f.length).toBe(0),await c.handleControl(o());const g=await r(p);n(g.length).toBe(3)}finally{e?.()}}),y("skips a socket whose cursor matches under a different CDC epoch",async()=>{const{close:e,createSocket:t,host:a,readFrames:r,sockets:d}=m();try{const c=i(d,a.sql,[{cursor:10,epoch:"e1",frames:[]}]),p=h(d,t,"c-alice","s1");await s(c,p,"s1"),await c.handleControl(o({epoch:"e2"}));const k=await r(p);n(k.length).toBe(0),await c.handleControl(o());const w=await r(p);n(w.length).toBe(3)}finally{e?.()}})}),S("RLS identity under live subscription",()=>{const b="shard-a",u={args:{},name:"lobby-messages"},h={args:{},name:"my-orders"},i=s=>{const o=[],e=[],t={fetch:(d,c)=>(o.push(JSON.parse(c?.body??"{}")),Promise.resolve(new Response(void 0,{status:204})))},r=I({buildShapeDiff:()=>[{id:"r1",op:"upsert",value:{}}],computeOpLogShapeSeed:()=>({baseCheckpoint:void 0,cursor:10,epoch:"e1",reset:!0,rowsPatch:[]}),currentCdcEpoch:()=>"e1",deliverWhisperLocal:()=>0,doName:()=>b,env:()=>({SHARD:{get:()=>t,getByName:()=>t,idFromName:d=>d}}),getWebSockets:()=>[],maskMetadata:()=>({columns:[]}),nextPokeId:()=>"poke-1",readAttachment:()=>({}),recordShapePokeFanout:()=>{},resolveShape:(d,c,p)=>(e.push(p),d===h.name?{columns:["id"],effectiveWhere:{org:p?.identity?.org??"anonymous"},global:!1,table:"orders"}:{columns:["id"],effectiveWhere:{room:"lobby"},global:!1,table:"messages"}),rlsMetadata:()=>({policies:[]}),shardBinding:()=>"SHARD",shardJurisdiction:()=>{},sql:()=>s});if(r===void 0)throw new Error("expected an owner link for an un-suffixed DO name");return{owner:r,posts:o,resolvedUnder:e}},l=async(s,o)=>{await s.handleControl(new Request("https://owner.internal/_lunora/relay",{body:JSON.stringify({...o,connectionId:"c-alice",identity:{org:"acme"},relayIndex:0,subId:"s1",type:"relay_shape_subscribe",userId:"u1"}),headers:{"content-type":"application/json"},method:"POST"}))};y("seeds a subscriber under its own forwarded identity, never the anonymous one",async()=>{const{close:s,host:o}=m();try{const{owner:e,resolvedUnder:t}=i(o.sql);await l(e,h),n(t.some(a=>a?.userId==="u1"&&a.identity?.org==="acme")).toBe(!0)}finally{s?.()}}),y("routes an identity-scoped shape to a per-socket poke, not the cohort multicast",async()=>{const{close:s,host:o}=m();try{const{owner:e,posts:t}=i(o.sql);await l(e,h),t.length=0,await e.onFlush(new Set(["orders"]),20);const a=t.filter(r=>r.type==="relay_shape_poke");n(a.length).toBe(1),n(a[0]?.targetConnectionId).toBe("c-alice")}finally{s?.()}}),y("still multicasts an identity-blind shape to the whole cohort",async()=>{const{close:s,host:o}=m();try{const{owner:e,posts:t}=i(o.sql);await l(e,u),t.length=0,await e.onFlush(new Set(["messages"]),20);const a=t.filter(r=>r.type==="relay_shape_poke");n(a.length).toBe(1),n(a[0]?.targetConnectionId).toBeUndefined()}finally{s?.()}})})})};export{W as defineEngineContractSuite};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as _}from"@lunora/errors";import{sql as r}from"drizzle-orm";import{e as p}from"./effective-kind-BmG_zCAy.mjs";import{quoteIdentifier as A}from"./quoteIdentifier-CObIFRhb.mjs";import{d as T,n as $,e as S}from"./wire-codec-C-FpWm52.mjs";import{runDrizzle as f}from"./runDrizzle-
|
|
1
|
+
import{LunoraError as _}from"@lunora/errors";import{sql as r}from"drizzle-orm";import{e as p}from"./effective-kind-BmG_zCAy.mjs";import{quoteIdentifier as A}from"./quoteIdentifier-CObIFRhb.mjs";import{d as T,n as $,e as S}from"./wire-codec-C-FpWm52.mjs";import{runDrizzle as f}from"./runDrizzle-Du5HLitO.mjs";import{sqlComparableProjection as O}from"./BIGINT_KEY_DIGITS-C9a7Ix7k.mjs";import"./serializeSqlValue-BbZ5hKM7.mjs";const b=/^[A-Za-z_$][\w$]*$/u,h=e=>b.test(e)?e:`"${e.replaceAll("\\",String.raw`\\`).replaceAll('"',String.raw`\"`)}"`,m="__doc__",a="__originals__",J=e=>{if(Object.hasOwn(e,a))throw new _("BAD_REQUEST",`"${a}" 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[s,i]of Object.entries(e)){const c=O(i);c!==void 0&&(t??={...e},o??=Object.create(null),t[s]=c,o[s]=i)}t&&o&&(t[a]=o);const n=t??e;try{return $(n)?JSON.stringify(S(n)):JSON.stringify(n)}catch(s){throw new _("BAD_REQUEST",`this document cannot be stored: ${s instanceof Error?s.message:String(s)}`)}},g=e=>{const t=T(JSON.parse(e)),o=t[a];if(o===null||typeof o!="object"||Array.isArray(o))return t;const n={...t};return delete n[a],{...n,...o}},q=(e,t)=>`${e}__geo_${t}`,E=(e,t)=>t==="_id"||t==="id"?`${e}id`:t==="_creationTime"?`${e}_creationTime`:`json_extract(${e}${m}, '$.${h(t).replaceAll("'","''")}')`,y=e=>E("",e),B=e=>r.raw(y(e)),N=(e,t)=>E(`${A(e)}.`,t),z=(e,t)=>r.raw(N(e,t)),F=(e,t,o,n)=>r`CREATE ${n?r`UNIQUE `:r``}INDEX IF NOT EXISTS ${r.identifier(e)} ON ${r.identifier(t)} (${o})`,l=r.identifier("__key__"),I=r.identifier("__value__"),j=r.identifier("__count__"),W=(e,t,o,n,s)=>r`INSERT INTO ${r.identifier(e)} (${l}, ${I}, ${j}) VALUES (${t}, ${o}, ${n}) ON CONFLICT(${l}) DO UPDATE SET ${s}`,k=(e,t)=>e===void 0||t!==0&&t!==1||p(e)!=="boolean"?t:t===1,d=new WeakMap,K=e=>{const t=d.get(e);if(t!==void 0)return t;const o=[];for(const[n,s]of Object.entries(e.shape)){const i=s._meta?.column;i&&o.push(Object.freeze([n,i]))}return Object.freeze(o),d.set(e,o),o},C=e=>{if(!e)return;const t=e[m];let o;typeof t=="string"?o=g(t):t&&typeof t=="object"?o=t:o={};const{id:n}=e;typeof n=="string"&&(o._id=n);const s=e._creationTime;return typeof s=="number"&&(o._creationTime=s),o},M=e=>{try{return C(e)}catch{return}},u=new WeakMap,V=e=>{const t=u.get(e);if(t!==void 0)return t;let o;try{f(e,r`CREATE VIRTUAL TABLE IF NOT EXISTS ${r.identifier("__lunora_fts_probe")} USING fts5(x)`),o=!0}catch{o=!1}finally{try{f(e,r`DROP TABLE IF EXISTS ${r.identifier("__lunora_fts_probe")}`)}catch{}}return u.set(e,o),o};export{j as A,m as D,l as a,I as b,W as c,F as d,B as e,z as f,q as g,M as h,V as i,y as j,J as k,g as l,a as m,h as n,k as o,N as q,C as r,K as t};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{toErrorBody as b}from"@lunora/errors";import{COMMIT_SEQ_FIELD as l}from"./COMMIT_SEQ_FIELD-
|
|
1
|
+
import{toErrorBody as b}from"@lunora/errors";import{COMMIT_SEQ_FIELD as l}from"./COMMIT_SEQ_FIELD-BY_vc9bw.mjs";const f=200,u=(o,n)=>{const i=r=>{const e=o.tables[r];return e!==void 0&&e.shardMode?.kind!=="global"};return(n&&n.length>0?[...n]:Object.keys(o.tables)).filter(r=>i(r))},p=async function*(o,n,i=f){let r=null,e=!1;for(;!e;){const t=await o.findMany(n,{cursor:r,includeDeleted:!0,limit:i});for(const s of t.page)yield{doc:s,table:n};r=t.continueCursor,e=t.isDone||r===null}},O=async function*(o,n,i){const r=u(n,i.tables),e=i.batchSize??f;for(const t of r)yield*p(o,t,e)},y=new Set(["_creationTime","_id"]),h=(o,n)=>{for(const[i,r]of Object.entries(o.shape)){const e=n[i];if(e===void 0&&r.kind==="optional")continue;const t=r.parse;if(typeof t=="function")try{t(e)}catch(s){const c=s instanceof Error?s.message:String(s);return`field "${i}": ${c}`}}},m=(o,n,i)=>{const r=o.tables[n];if(!r)return`unknown table: ${n}`;if(r.shardMode?.kind==="global")return`table "${n}" is a global (.global()) table and is not importable through the shard import path`;const e=Object.fromEntries(Object.entries(i).filter(([t])=>!y.has(t)));for(const t of Object.keys(e))if(!Object.hasOwn(r.shape,t))return`unexpected field "${t}": not declared in table "${n}"`;return h(r,e)},g=async(o,n,i)=>{try{if(o.lookupById){const r=await o.lookupById(i);return r===null?void 0:r.tableName}return await o.get(i,n)===null?void 0:n}catch{return}},w=o=>l in o?Object.fromEntries(Object.entries(o).filter(([n])=>n!==l)):o,S=async(o,n,i,r)=>{const{table:e}=i;let{doc:t}=i;if(typeof e!="string"||e.length===0)return{error:{code:"BAD_ROW",line:r,message:"row is missing `table`",table:e},kind:"error"};if(!t||typeof t!="object"||Array.isArray(t))return{error:{code:"BAD_ROW",line:r,message:"row is missing or malformed `doc`",table:e},kind:"error"};t=w(t);const s=m(n,e,t);if(s!==void 0)return{error:{code:"VALIDATION_ERROR",line:r,message:s,table:e},kind:"error"};const c=typeof t._id=="string"?t._id:void 0;if(c!==void 0){const a=await g(o,e,c);if(a===e)return{kind:"conflict"};if(a!==void 0)return{error:{code:"ID_COLLISION",line:r,message:`_id "${c}" already belongs to table "${a}"`,table:e},kind:"error"}}try{return await o.insert(e,t,{allowExplicitId:!0}),{kind:"inserted",table:e}}catch(a){const{body:d}=b(a,{fallbackCode:"INSERT_FAILED"});return{error:{code:d.code,line:r,message:d.message,table:e},kind:"error"}}},v=async(o,n,i)=>{const r=[],e={};let t=0,s=(i.startLine??1)-1;for(const c of i.rows){s+=1;const a=await S(o,n,c,s);a.kind==="error"?r.push(a.error):a.kind==="conflict"?t+=1:e[a.table]=(e[a.table]??0)+1}return{conflicts:t,errors:r,inserted:e}},E=o=>{const n=Array.isArray(o.tables)?o.tables.filter(r=>typeof r=="string"):void 0;return{batchSize:typeof o.batchSize=="number"?o.batchSize:void 0,tables:n}},I=o=>{const n=Array.isArray(o.rows)?o.rows:[],i=[];for(const e of n){if(!e||typeof e!="object")continue;const t=e;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 r=typeof o.startLine=="number"?o.startLine:void 0;return{rows:i,startLine:r}};export{O as exportShardRows,v as importShardRows,E as parseExportShardArgs,I as parseImportShardArgs,u as selectExportTables,m as validateImportRow};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{D as I}from"./MAX_TOKEN_LENGTH-BakL9FUy-B3VwYY8C.mjs";import{sql as e}from"drizzle-orm";import{sqliteInList as L}from"./WORKERD_SQLITE_LIMITS-
|
|
1
|
+
import{D as I}from"./MAX_TOKEN_LENGTH-BakL9FUy-B3VwYY8C.mjs";import{sql as e}from"drizzle-orm";import{sqliteInList as L}from"./WORKERD_SQLITE_LIMITS-DBH23L_S.mjs";const u=(i,t)=>{if(!t.includes("."))return i[t];let r=i;for(const $ of t.split(".")){if(r===null||typeof r!="object"||Array.isArray(r))return;r=r[$]}return r},D=(i,t)=>`${i}__fts_${t}`,o="__text__",s="__id__",A=1e3,O=(i,t)=>t.document(i),N=(i,t)=>u(i,t),_=i=>typeof i=="string"?i:i==null?"":typeof i=="number"||typeof i=="bigint"||typeof i=="boolean"?String(i):JSON.stringify(i)??"",w=(i,t,r)=>i!==void 0&&t!==void 0&&N(i,r.field)===N(t,r.field),c=(i,t)=>O(_(N(i,t.field)),I(t.language)).slice(0,A),M=(i,t)=>c(i,t).join(" "),a=50,n="__rowid__",T=i=>`${i}__ids`,E=(i,t)=>e`${e.identifier(i)}.${e.identifier(t)}`,S=(i,t,{guard:r,unmappedRowids:$})=>{const d=T(i),f=r===void 0?e``:e` AND ${r}`,R=$===void 0?e`${E(i,"rowid")} > 0`:L(E(i,"rowid"),$,!1,a);return[e`DELETE FROM ${e.identifier(i)} WHERE ${R} AND CAST(${E(i,s)} AS TEXT) = ${t}${f}`,e`DELETE FROM ${e.identifier(i)} WHERE ${E(i,"rowid")} = (SELECT ${E(d,n)} FROM ${e.identifier(d)} WHERE ${E(d,s)} = ${t}) AND ${E(i,s)} = ${t}${f}`]},U=i=>[e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(i)} USING fts5(${e.identifier(o)}, ${e.identifier(s)} UNINDEXED)`,e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(`${i}__vocab`)} USING fts5vocab(${e.identifier(i)}, ${e.raw("instance")})`,e`CREATE TABLE IF NOT EXISTS ${e.identifier(T(i))} (${e.identifier(n)} INTEGER PRIMARY KEY, ${e.identifier(s)} TEXT NOT NULL UNIQUE)`,e`INSERT INTO ${e.identifier(i)} (rowid, ${e.identifier(o)}, ${e.identifier(s)}) SELECT 0, '', '' WHERE NOT EXISTS (SELECT 1 FROM ${e.identifier(i)} WHERE ${E(i,"rowid")} = 0)`],F=(i,t,r,$={})=>{const d=T(i),f=$.guard===void 0?e``:e` AND ${$.guard}`,R=e`MIN(COALESCE((SELECT MIN(${E(d,n)}) FROM ${e.identifier(d)}), 0), 0) - 1`;return[...S(i,t,$),e`INSERT OR REPLACE INTO ${e.identifier(d)} (${e.identifier(n)}, ${e.identifier(s)}) SELECT ${R}, ${t} WHERE 1 = 1${f}`,e`INSERT OR REPLACE INTO ${e.identifier(i)} (rowid, ${e.identifier(o)}, ${e.identifier(s)}) SELECT ${E(d,n)}, ${r}, ${E(d,s)} FROM ${e.identifier(d)} WHERE ${E(d,s)} = ${t}${f}`]},y=(i,t,r={})=>{const $=T(i),d=r.guard===void 0?e``:e` AND ${r.guard}`;return[...S(i,t,r),e`DELETE FROM ${e.identifier($)} WHERE ${E($,s)} = ${t}${d}`]},W=(i,t,r=0)=>e`SELECT ${E(i,"rowid")} AS ${e.identifier("rowid")}, ${E(i,s)} AS ${e.identifier("id")} FROM ${e.identifier(i)} WHERE ${E(i,"rowid")} > ${e.param(Math.max(0,r))} AND ${E(i,s)} IS NOT NULL ORDER BY ${E(i,"rowid")} ASC LIMIT ${e.raw(String(t))}`,b=i=>{const t=new Map;for(const r of i){const $=String(r.id);t.set($,[...t.get($)??[],Number(r.rowid)])}return t};export{w as N,D as S,y as a,T as b,W as c,F as d,M as e,U as f,b as g,c as h,s as l};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{f as t,a as e,b as p,c as m,d as f,g as n}from"./fts-companion-
|
|
1
|
+
import{f as t,a as e,b as p,c as m,d as f,g as n}from"./fts-companion-pUdD6kF-.mjs";import"./WORKERD_SQLITE_LIMITS-DBH23L_S.mjs";export{t as ftsCompanionDdl,e as ftsPurgeDocument,p as ftsRowidMapName,m as ftsUnmappedPage,f as ftsWriteDocument,n as groupUnmappedRows};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{LunoraError as T}from"@lunora/errors";import{sql as m}from"drizzle-orm";import{runDrizzle as S}from"./runDrizzle-
|
|
1
|
+
import{LunoraError as T}from"@lunora/errors";import{sql as m}from"drizzle-orm";import{runDrizzle as S}from"./runDrizzle-Du5HLitO.mjs";import{liftSourceId as A}from"./liftSourceId-CA3ENhXj.mjs";import{normalizeSourceValue as W}from"./liftSourceId-CA3ENhXj.mjs";import{runExternalSourceTick as C,materializeExternalRowsIncremental as D}from"./materializeExternalRows-DhINQHwd.mjs";const p="__lunora_source_cursor",M=e=>e instanceof Date?`d:${e.toISOString()}`:typeof e=="bigint"?`b:${e.toString()}`:typeof e=="number"?`n:${e.toString()}`:`s:${e}`,v=e=>{const t=e.slice(2);switch(e[0]){case"b":return BigInt(t);case"d":return new Date(t);case"n":return Number(t);default:return t}},h=/^-?\d+$/,N=/^-?\d+(?:\.\d+)?$/,x=(e,t)=>e instanceof Date&&t instanceof Date?e.getTime()>t.getTime():typeof e=="bigint"&&typeof t=="bigint"||typeof e=="number"&&typeof t=="number"?e>t:typeof e=="string"&&typeof t=="string"&&N.test(e)&&N.test(t)?h.test(e)&&h.test(t)?BigInt(e)>BigInt(t):Number(e)>Number(t):String(e)>String(t),O=(e,t,o)=>{let n=o===null?void 0:v(o);for(const r of e){const c=r[t];if(c==null)continue;const a=c;(n===void 0||x(a,n))&&(n=a)}return n===void 0?null:M(n)},B=e=>{S(e,m`CREATE TABLE IF NOT EXISTS ${m.identifier(p)} (
|
|
2
2
|
table_name TEXT NOT NULL,
|
|
3
3
|
shard_key TEXT NOT NULL,
|
|
4
4
|
watermark TEXT,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{applyCdcChanges as p}from"./CDC_LOG_TABLE-
|
|
1
|
+
import{applyCdcChanges as p}from"./CDC_LOG_TABLE-QaBxSIZM.mjs";import{selectShapeRows as m}from"./selectShapeMembers-BXhvEt4X.mjs";import{diffExternalSource as g,projectExternalSourceRow as l}from"./diffExternalSource-DgDJhslq.mjs";import{stableStringify as d}from"./stableStringify-DibjylKD.mjs";const x=async(t,s,a,e)=>{const{changes:o,nextBaseline:n}=g(s,a,e);return await p(t,o),{applied:o.length,nextBaseline:n}},R=async(t,s,a)=>{const{columns:e,deletedIds:o,table:n}=a,r=[];for(const f of s){const i=l(f,e),c=String(i._id);if(o?.has(c)){await t.get(c,n)&&r.push({id:c,op:"delete",seq:0,table:n,ts:0});continue}const u=await t.get(c,n);u&&d(l({...u,_id:c},e))===d(i)||r.push({doc:i,id:c,op:"insert",seq:0,table:n,ts:0})}return await p(t,r),{applied:r.length}},h=(t,s,a)=>{const e=new Map;for(const{doc:o,id:n}of m(t,s,void 0))e.set(n,d(l({...o,_id:n},a)));return e},_=async(t,s,a,e)=>{const o=h(t,e.table,e.columns);return x(s,a,o,e)};export{x as materializeExternalRows,R as materializeExternalRowsIncremental,h as readExternalSourceBaseline,_ as runExternalSourceTick};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as i}from"@lunora/errors";import{renderSql as l,WORKERD_SQLITE_LIMITS as e}from"./WORKERD_SQLITE_LIMITS-
|
|
1
|
+
import{LunoraError as i}from"@lunora/errors";import{renderSql as l,WORKERD_SQLITE_LIMITS as e}from"./WORKERD_SQLITE_LIMITS-DBH23L_S.mjs";const c=(t,n,...r)=>{if(n.length*3>e.sqlTextLength){const s=new TextEncoder().encode(n).length;if(s>e.sqlTextLength)throw new i("INTERNAL",`SQL statement is ${String(s)} bytes, over this runtime's ${String(e.sqlTextLength)}-byte limit`)}if(r.length>e.boundParams)throw new i("INTERNAL",`SQL statement binds ${String(r.length)} parameters, over this runtime's limit of ${String(e.boundParams)}`);return t.exec.call(t,n,...r)},u=(t,n)=>{const{params:r,sql:o}=l("sqlite",n);return c(t,o,...r)},d=(t,n)=>{for(const r of n)u(t,r)},g=t=>t??null,S=t=>{if(!(t==null||t===""))try{return JSON.parse(t)}catch{return}};export{S as decodeJsonColumn,g as orNull,d as runAll,u as runDrizzle,c as runSql};
|
package/dist/packem_shared/{runShardMigrations-BtAyuuJb.mjs → runShardMigrations-MXioI81k.mjs}
RENAMED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{LunoraError as l}from"@lunora/errors";import{f as L,S as h}from"./fts-companion-
|
|
1
|
+
import{LunoraError as l}from"@lunora/errors";import{f as L,S as h}from"./fts-companion-pUdD6kF-.mjs";import{sql as r}from"drizzle-orm";import{aggregateTableName as O}from"./aggregateTableName-C7o-gpms.mjs";import{backfillSearchIndexesForTable as R}from"./backfillAggregateIndexes-B_3xdOgV.mjs";import{migrateCdcLog as x,migrateCdcMeta as N}from"./CDC_LOG_TABLE-QaBxSIZM.mjs";import{migrateClientWatermark as C}from"./CLIENT_WATERMARK_TABLE-vLjfNhBR.mjs";import{migrateCommitSeq as $}from"./COMMIT_SEQ_FIELD-BY_vc9bw.mjs";import{migrateGlobalShapeSnapshot as b}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-pMxZ-obU.mjs";import{migrateIdempotency as D}from"./IDEMPOTENCY_TABLE-AOJCuq5U.mjs";import{m as U}from"./ctx-db-relay-shapes-DuqhDLw8.mjs";import{migrateScheduleOutbox as M}from"./SCHEDULE_OUTBOX_TABLE-CgLvGxpY.mjs";import{m as G}from"./ctx-db-search-state-DVCp4JQf.mjs";import{migrateShapePokeCursor as X}from"./SHAPE_POKE_CURSOR_TABLE-cn0stGAL.mjs";import{runDrizzle as s,runAll as y}from"./runDrizzle-Du5HLitO.mjs";import{D as F,d as E,e as g,t as P,i as Y,g as k,a as B,b as j,A as p}from"./do-sql-BEFrJUds.mjs";import{renderSql as v}from"./WORKERD_SQLITE_LIMITS-DBH23L_S.mjs";import{migrateDurableStreams as w}from"./appendStreamChunk-7ZyAZGg_.mjs";import{rankTableName as H,sortColumnName as K}from"./RANK_TIEBREAK-B0_x8iev.mjs";import{migrateReactorState as W}from"./REACTOR_STATE_TABLE-B8IehLv8.mjs";import{recordSchemaVersion as V}from"./SCHEMA_HISTORY_MAX_VERSIONS-BMcUIqBY.mjs";const A=r`_creationTime, id`,S=(e,i,o,t,n,a)=>{const c=r.join(n.map(d=>r`${d} IS NOT NULL`),r` AND `);if(s(e,r`SELECT 1 FROM ${r.identifier(o)} WHERE ${c} GROUP BY ${t} HAVING COUNT(*) > 1 LIMIT 1`).toArray().length>0)throw new l("INTERNAL",`unique index "${i}" on "${o}" ${a}: existing rows are duplicates under it. De-duplicate the table with a data migration first; the previous index is left in place.`)},z=(e,i,o,t,n,a)=>{const m=s(e,r`SELECT sql FROM sqlite_master WHERE type = 'index' AND name = ${i} AND tbl_name = ${o}`).toArray()[0]?.sql;if(m==null)return;const d=_=>{const u=_.indexOf("(");return u===-1?void 0:_.slice(u,_.lastIndexOf(")")+1)},T=d(v("sqlite",E(i,o,t,n)).sql),f=d(m);T===void 0||f===void 0||T===f||(n&&S(e,i,o,t,a,"cannot be re-created with its new column list"),s(e,r`DROP INDEX IF EXISTS ${r.identifier(i)}`))},J=(e,i,o)=>s(e,r`SELECT 1 FROM sqlite_master WHERE type = 'index' AND name = ${i} AND tbl_name = ${o} LIMIT 1`).toArray().length>0,I=(e,i,o,t,n,a)=>{n&&!J(e,i,o)&&S(e,i,o,t,a,"cannot be created"),s(e,E(i,o,t,n))},Q=(e,i,o)=>{for(const t of o.indexes){const n=`${i}_${t.name}`,a=t.unique??!1,c=t.fields.map(T=>g(T)),m=r.join(c,r`, `),d=a?m:r`${m}, ${A}`;z(e,n,i,d,a,c),I(e,n,i,d,a,c)}for(const[t,n]of P(o)){if(!n.unique)continue;const a=g(t);I(e,`${i}_unique_${t}`,i,a,!0,[a])}},Z=(e,i,o)=>{if(!(!o.searchIndexes||o.searchIndexes.length===0||!Y(e))){for(const t of o.searchIndexes)y(e,L(h(i,t.name)));R(e,i,o)}},q=(e,i,o)=>{if(o.geoIndexes)for(const t of o.geoIndexes){const n=k(i,t.name);s(e,r`CREATE TABLE IF NOT EXISTS ${r.identifier(n)} (${r.identifier("__id__")} TEXT PRIMARY KEY, ${r.identifier("__geohash__")} TEXT NOT NULL, ${r.identifier("__lat__")} REAL NOT NULL, ${r.identifier("__lng__")} REAL NOT NULL)`);const a=`${i}__geo_${t.name}__btree`;s(e,E(a,n,r`${r.identifier("__geohash__")} ASC, ${r.identifier("__id__")} ASC`,!1))}},ee=(e,i,o)=>{if(o.aggregateIndexes)for(const t of o.aggregateIndexes){const n=O(i,t.name);s(e,r`CREATE TABLE IF NOT EXISTS ${r.identifier(n)} (${B} TEXT PRIMARY KEY, ${j} REAL, ${p} INTEGER NOT NULL DEFAULT 0)`),s(e,r`PRAGMA table_info(${r.identifier(n)})`).toArray().some(c=>c.name==="__count__")||s(e,r`ALTER TABLE ${r.identifier(n)} ADD COLUMN ${p} INTEGER NOT NULL DEFAULT 0`)}},re=(e,i,o)=>{if(o.rankIndexes)for(const t of o.rankIndexes){const n=H(i,t.name),a=t.sortBy.map((f,_)=>K(_)),c=a.map(f=>r`${r.identifier(f)} BLOB`),m=c.length>0?r`, ${r.join(c,r`, `)}`:r``;s(e,r`CREATE TABLE IF NOT EXISTS ${r.identifier(n)} (${r.identifier("__id__")} TEXT PRIMARY KEY, ${r.identifier("__partition__")} TEXT NOT NULL${m})`);const d=[r`${r.identifier("__partition__")} ASC`];for(const[f,_]of a.entries()){const u=t.sortBy[f]?.direction;d.push(r`${r.identifier(_)} ${r.raw(u==="desc"?"DESC":"ASC")}`)}d.push(r`${r.identifier("__id__")} ASC`);const T=`${i}__rank_${t.name}__btree`;s(e,E(T,n,r.join(d,r`, `),!1))}},he=(e,i,o={})=>{o.schemaSnapshot!==void 0&&V(e,o.schemaSnapshot.hash,o.schemaSnapshot.json),G(e);for(const[t,n]of Object.entries(i.tables))n.shardMode?.kind!=="global"&&(s(e,r`CREATE TABLE IF NOT EXISTS ${r.identifier(t)} (
|
|
2
2
|
id TEXT PRIMARY KEY,
|
|
3
3
|
_creationTime REAL NOT NULL,
|
|
4
4
|
${r.identifier(F)} TEXT NOT NULL
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{sql as o}from"drizzle-orm";import{runDrizzle as h}from"./runDrizzle-
|
|
1
|
+
import{sql as o}from"drizzle-orm";import{runDrizzle as h}from"./runDrizzle-Du5HLitO.mjs";import{e}from"./do-sql-BEFrJUds.mjs";const E=(s,t,f,r)=>{const d=f-(t.after??0),i=[o`${e(t.field)} IS NOT NULL`,o`${e(t.field)} < ${d}`];t.softDeleteField!==void 0&&i.push(o`${e(t.softDeleteField)} IS NULL`);const l=o`SELECT id FROM ${o.identifier(t.table)} WHERE ${o.join(i,o` AND `)} LIMIT ${o.raw(String(Math.max(0,Math.floor(r))+1))}`,n=h(s,l).toArray(),a=n.length>r,$=n.slice(0,r).map(c=>c.id);return{hasMore:a,ids:$}};export{E as selectExpiredIds};
|
package/dist/packem_shared/{selectShapeMembers-DTA3YUf4.mjs → selectShapeMembers-BXhvEt4X.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{sql as e}from"drizzle-orm";import{runDrizzle as m}from"./runDrizzle-
|
|
1
|
+
import{sql as e}from"drizzle-orm";import{runDrizzle as m}from"./runDrizzle-Du5HLitO.mjs";import{D as p,r as d,e as h}from"./do-sql-BEFrJUds.mjs";import{sqliteInList as w}from"./WORKERD_SQLITE_LIMITS-DBH23L_S.mjs";import{c as S}from"./where-sql-DFs8Zw7-.mjs";import{serializeSqlValue as $}from"./serializeSqlValue-BbZ5hKM7.mjs";const C={fieldRef:h,serialize:$},g=o=>{if(o.length!==0)return w(e`${e.identifier("id")}`,o,!1)},u=(o,i)=>{const r=[];i&&r.push(i);const t=S(o,C);return t&&r.push(t),r.length===0?e``:e` WHERE ${e.join(r,e` AND `)}`},v=(o,i,r)=>{const t=u(r,void 0),s=m(o,e`SELECT id, _creationTime, ${e.identifier(p)} FROM ${e.identifier(i)}${t}`).toArray(),f=[];for(const l of s){const n=d(l),{id:c}=l;n!==void 0&&typeof c=="string"&&f.push({doc:n,id:c})}return f},z=(o,i,r,t)=>{const s=new Map;if(t.length===0)return s;const f=u(r,g(t)),l=m(o,e`SELECT id, _creationTime, ${e.identifier(p)} FROM ${e.identifier(i)}${f}`).toArray();for(const n of l){const c=d(n),{id:a}=n;c!==void 0&&typeof a=="string"&&s.set(a,c)}return s};export{z as selectShapeMembers,v as selectShapeRows};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as T}from"@lunora/errors";import{sql as e}from"drizzle-orm";import{sqliteInList as d,isJsonSafe as E,bytesAsHexJson as _,WORKERD_SQLITE_LIMITS as $}from"./WORKERD_SQLITE_LIMITS-DBH23L_S.mjs";import{quoteIdentifier as x}from"./quoteIdentifier-CObIFRhb.mjs";import{RELATION_EXISTS_KEY as L}from"./RELATION_EXISTS_KEY-CFUhnZSZ.mjs";const y={binary:(t,n,s)=>e`${t} ${e.raw(n)} ${s}`,constant:t=>t?e`1 = 1`:e`0 = 1`,connect:(t,n,s)=>e`(${t}) ${e.raw(s)} (${n})`,contains:(t,n)=>e`instr(lower(${t}), lower(${n})) > 0`,inList:(t,n,s,o)=>d(t,n,s,o),negate:t=>e`NOT (${t})`,nullCheck:(t,n)=>n?e`${t} IS NOT NULL`:e`${t} IS NULL`,value:t=>e`${t}`},h=(...t)=>{let n="";const s=[];for(const o of t)typeof o=="string"?n+=o:(n+=o.text,s.push(...o.params));return{params:s,text:n}},f=t=>({params:[t],text:"?"}),b=t=>({params:[],text:t}),Y=t=>b(x(t)),H={binary:(t,n,s)=>h(t," ".concat(n," "),f(s)),constant:t=>b(t?"1 = 1":"0 = 1"),connect:(t,n,s)=>h("(",t,") ".concat(s," ("),n,")"),contains:(t,n)=>h("instr(lower(",t,"), lower(",n,")) > 0"),inList:(t,n,s,o)=>{const i=s?" NOT IN ":" IN ",r=n.every(l=>E(l)),c=n.length>o&&!r?_(n):void 0;if(c!==void 0)return h(t,i,'(SELECT unhex("value") FROM json_each(',f(c),"))");if(n.length>o&&!r)throw new T("BAD_REQUEST",`an "in" list of ${String(n.length)} values holds a value JSON cannot carry (bytes, a non-finite number, or malformed text), so it cannot be bound as one parameter — and ${String(n.length)} placeholders exceed SQLite's per-statement cap of 100 on Durable Objects and D1. Narrow the list to ${String(o)} values or fewer.`);if(n.length<=o){const l=[t,i,"("];for(const[a,u]of n.entries())a>0&&l.push(", "),l.push(f(u));return l.push(")"),h(...l)}return h(t,i,'(SELECT "value" FROM json_each(',f(JSON.stringify(n)),"))")},negate:t=>h("NOT (",t,")"),nullCheck:(t,n)=>h(t,n?" IS NOT NULL":" IS NULL"),value:f},C=$.boundParams/2,I=["eq","ne","lt","lte","gt","gte","in","notIn","isNull","contains"],w=new Set(I),j={eq:"=",gt:">",gte:">=",lt:"<",lte:"<=",ne:"<>"},A=t=>{if(t===null||typeof t!="object"||Array.isArray(t))return!1;const n=Object.keys(t);return n.length>0&&n.every(s=>w.has(s))},U=(t,n,s,o,i)=>{const r=i.value(o.serialize(s,t));return o.containsExpr?o.containsExpr(n,r):i.contains(n,r)},v=(t,n,s,o,i,r,c)=>i===null?s==="eq"||s==="ne"?c.nullCheck(n,s==="ne"):c.constant(!1):c.binary(n,o,r.serialize(i,t)),M=(t,n,s,o,i,r)=>{if(!Array.isArray(o))throw new T("BAD_REQUEST",`\`${s==="IN"?"in":"notIn"}\` on "${t}" expects an array of values, received ${o===null?"null":typeof o}`);const c=o;if(c.length===0)return r.constant(s==="NOT IN");const l=c.map(u=>i.serialize(u,t)),a=s==="NOT IN";return i.inList?i.inList(n,l,a):r.inList(n,l,a,C)},O=$.boundParams/2,D=6e4,F=(t,n)=>{const s={bytes:[],hasNull:!1,numbers:[],strings:[]};for(const o of t)if(o===null)s.hasNull=!0;else if(o instanceof Uint8Array)s.bytes.push(Array.from(o,i=>i.toString(16).padStart(2,"0")).join(""));else if(typeof o=="number"&&E(o))s.numbers.push(o);else if(typeof o=="string"&&E(o))s.strings.push(o);else throw new T("BAD_REQUEST",`an "in" list of ${String(t.length)} values holds a value that cannot be bound as one parameter (a non-finite number, or malformed text). Narrow the list to ${String(n)} values or fewer.`);return s},P=(t,n,s)=>{const o=[],i=e.identifier("v"),r=e.identifier("__in__"),c=a=>e`jsonb_array_elements_text(CAST(CAST(${JSON.stringify(a)} AS text) AS jsonb))`,l=(a,u)=>e`JSON_TABLE(${JSON.stringify(a)}, '$[*]' COLUMNS (${i} ${e.raw(u)} PATH '$')) ${r}`;return s.strings.length>0&&o.push(t==="postgres"?e`${n} IN (SELECT ${c(s.strings)})`:e`${n} IN (SELECT CONVERT(${i} USING utf8mb4) FROM ${l(s.strings,"LONGTEXT")})`),s.numbers.length>0&&o.push(t==="postgres"?e`${n} IN (SELECT CAST(${c(s.numbers)} AS double precision))`:e`${n} IN (SELECT ${i} FROM ${l(s.numbers,"DOUBLE")})`),s.bytes.length>0&&o.push(t==="postgres"?e`${n} IN (SELECT decode(${c(s.bytes)}, 'hex'))`:e`${n} IN (SELECT UNHEX(${i}) FROM ${l(s.bytes,"LONGTEXT")})`),o},W=t=>(n,s,o,i=O)=>{const r=Math.floor(D*i/O);if(s.length<=r){const u=e.join(s.map(p=>e`${p}`),e`, `);return o?e`${n} NOT IN (${u})`:e`${n} IN (${u})`}const c=F(s,r);if(o&&c.hasNull)return e`1 = 0`;const l=P(t,n,c);if(l.length===0)return e`1 = 0`;const a=l.length===1?l[0]:e`(${e.join(l,e` OR `)})`;return o?e`NOT (${a})`:a},k=(t,n,s,o,i)=>{const r=s,c=[];for(const l of I){if(!(l in r))continue;const a=r[l],u=j[l];u?c.push(v(t,n,l,u,a,o,i)):l==="isNull"?c.push(i.nullCheck(n,!a)):l==="contains"?c.push(U(t,n,a,o,i)):c.push(M(t,n,l==="in"?"IN":"NOT IN",a,o,i))}return c},B=(t,n,s,o)=>{const i=s.fieldRef(t);return A(n)?k(t,i,n,s,o):n===null?[o.nullCheck(i,!1)]:[o.binary(i,"=",s.serialize(n,t))]},N=(t,n,s)=>{if(t.length<=1)return t[0];const o=Math.floor(t.length/2);return s.connect(N(t.slice(0,o),n,s),N(t.slice(o),n,s),n)},g=(t,n,s,o)=>{const i=Array.isArray(t)?t:[],r=[];for(const c of i){const l=S(c??{},s,o);if(l!==void 0)r.push(l);else if(n==="OR")return}return r.length===0?n==="OR"?o.constant(!1):void 0:N(r,n,o)},q=new Set(["AND","NOT","OR",L]),z=(t,n,s,o)=>{if(t===L){if(!s.relationExists)throw new T("INTERNAL","encountered a relation EXISTS marker without a relationExists strategy hook");return s.relationExists(n)}if(t==="NOT"){const i=S(n??{},s,o);return i===void 0?o.constant(!1):o.negate(i)}return g(n,t,s,o)},S=(t,n,s)=>{const o=[];for(const[i,r]of Object.entries(t))if(q.has(i)){const c=z(i,r,n,s);c!==void 0&&o.push(c)}else o.push(...B(i,r,n,s));return N(o,"AND",s)},m=t=>{let n=0,s=0;const o=i=>{const r=m(i);n+=r.lists,s+=r.scalars};if(Array.isArray(t)){for(const i of t)o(i);return{lists:n,scalars:s}}if(t===null||typeof t!="object")return{lists:n,scalars:s};for(const[i,r]of Object.entries(t))i==="in"||i==="notIn"?n+=1:i==="AND"||i==="NOT"||i==="OR"||A(r)?o(r):s+=1;return{lists:n,scalars:s}},V=(t,n,s=y,o=0)=>{if(!t||Object.keys(t).length===0)return;const{lists:i,scalars:r}=m(t);if(i===0)return S(t,n,s);const c=Math.max(1,Math.floor(Math.min(O,$.boundParams-r-o)/i)),l=n.inList??((a,u,p,R)=>s.inList(a,u,p,R??c));return S(t,{...n,inList:(a,u,p)=>l(a,u,p,c)},s)};export{V as c,Y as i,h as j,b as r,W as s,H as t};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/shard-engine",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.96",
|
|
4
4
|
"description": "Host-neutral reactive engine for Lunora: per-shard state, OCC, CDC, reactive subscriptions, and the poke protocol. Consumes @lunora/platform host contracts and can be mounted on any platform host.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cloudflare",
|
|
@@ -48,7 +48,7 @@
|
|
|
48
48
|
"access": "public"
|
|
49
49
|
},
|
|
50
50
|
"dependencies": {
|
|
51
|
-
"@lunora/errors": "1.0.0-alpha.
|
|
51
|
+
"@lunora/errors": "1.0.0-alpha.46",
|
|
52
52
|
"@lunora/platform": "1.0.0-alpha.41",
|
|
53
53
|
"drizzle-orm": "^0.45.2"
|
|
54
54
|
},
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as $}from"@lunora/errors";import{D as ut}from"./MAX_TOKEN_LENGTH-BakL9FUy-B3VwYY8C.mjs";import{S as mn,l as qe,h as Sn}from"./fts-companion-DcGBHZiM.mjs";import{sql as c}from"drizzle-orm";import{d as _n}from"./wire-codec-C-FpWm52.mjs";import{stableWireKey as It}from"./stableWireKey-D2US4k_J.mjs";import{throwingScheduler as Rn,aggregateSqlFunction as Be,normalizeCountArgument as Tn}from"./AGGREGATE_SQL_FUNCTION-DDEoMnJR.mjs";import{aggregateTableName as Xe,encodeAggregateKey as Ze,readAggregateValue as et}from"./aggregateTableName-C7o-gpms.mjs";import{mergeWhere as N,CountRlsUnsupportedError as tt,selectIndexForGroupBy as vn,selectIndexForCount as An,selectIndexForAggregate as In}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{backfillSearchIndexesForTable as Cn,searchIndexCoversTable as xn}from"./backfillAggregateIndexes-DBY2H269.mjs";import{backfillAggregateIndexes as Or,backfillRankIndexes as Nr,backfillSearchIndexes as jr}from"./backfillAggregateIndexes-DBY2H269.mjs";import{appendCdcChange as bn,readCdcDocAtOrBefore as Mn}from"./CDC_LOG_TABLE-Bkv7JskR.mjs";import{CDC_LOG_TABLE as Qr,applyCdcChanges as Vr,bumpCdcEpoch as zr,cdcCanVouchFor as Jr,cdcForkedError as Yr,cdcSeqLeavingRows as Xr,cdcTouchesTables as Zr,cdcTrimmedError as ei,compactCdcDocs as ti,cursorBelowRetainedFloor as ni,minCdcReplayableSeq as oi,minCdcSeq as ri,readCdcChangeKeys as ii,readCdcChanges as si,readCdcCursor as ci,readCdcEpoch as ai,trimCdcChanges as di}from"./CDC_LOG_TABLE-Bkv7JskR.mjs";import{allocateCommitSeq as Dn,COMMIT_SEQ_FIELD as kn}from"./COMMIT_SEQ_FIELD-6lGDFLgk.mjs";import{createCompanionSync as Ln}from"./createCompanionSync-uTsHTJWE.mjs";import{isMemoryTable as Ct}from"./clearMemoryTables-BCDG0X9P.mjs";import{computeRankPage as xt}from"./computeRankPage-BEyDlhws.mjs";import{SCAN_DEP as O}from"./SCAN_DEP-D7qE3iUe.mjs";import{runSql as Te,runDrizzle as j}from"./runDrizzle-BlpM0R9P.mjs";import{j as He,D as oe,r as Se,k as de,b as We,A as nt,a as Pe,e as ce,o as Fn,t as Zt,q as bt,i as qn,h as en,g as Bn}from"./do-sql-DpyjVz_6.mjs";import{renderSql as tn,unionAll as ft,WORKERD_SQLITE_LIMITS as nn,sqliteInList as Wn}from"./WORKERD_SQLITE_LIMITS-DlozcSQu.mjs";import{coveringGeohashes as Pn,boundingBoxGeohashes as Un,haversineMeters as Gn,pointInBoundingBox as Hn}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{NotFoundError as On}from"./NotFoundError-BhF7FeFr.mjs";import{tiebreakDirectionFor as Nn,encodeCursor as Oe,normalizeOrderKeys as ct,uniqueIndexFields as on,buildSeekWhere as rn,decodeCursor as at,buildSeekBeforeWhere as jn,softDeleteScope as ue,equalityPinnedFields as Kn,applySelect as Mt}from"./CURSOR_PREFIX-Bn8SFoGd.mjs";import{rankTableName as Dt,sortColumnName as kt,resolveRankPartition as Qn,encodePartitionKey as Vn,RANK_TIEBREAK as zn,rankPivotConditionSql as Jn}from"./RANK_TIEBREAK-B0_x8iev.mjs";import{UNVOUCHABLE_DEP as Lt}from"./UNVOUCHABLE_DEP-C68htACn.mjs";import{indexKeysForRow as Yn,buildIndexRange as Xn}from"./buildIndexRange-6nIZDf4m.mjs";import{r as Ne,j as _e,c as te,t as je,i as Ft}from"./where-sql-BV8Kg4_B.mjs";import{serializeSqlValue as ae}from"./serializeSqlValue-BbZ5hKM7.mjs";import{quoteIdentifier as ve}from"./quoteIdentifier-CObIFRhb.mjs";import{whereOfFilter as Zn,isPushableWhere as eo}from"./isPushableWhere-BeYAOjUb.mjs";import{deriveRelationEdges as to,findRelated as no}from"./RELATED_DEFAULT_LIMIT-B9PH28Pn.mjs";import{assertFlatPredicate as ot,resolveRelationPredicates as qt}from"./DEFAULT_MAX_RELATION_KEYS-B1zeutIo.mjs";import{runRowValidators as rt,resolveWith as Bt,relationHooks as Wt,applyOnDelete as oo,fanOutScalarCounts as ro}from"./applyOnDelete-7JZ4vR9r.mjs";import{guardWriter as io}from"./RLS_UNWRAP_SYMBOL-BwwTbz3Q.mjs";import{mayHoldProjectedValue as so}from"./BIGINT_KEY_DIGITS-C9a7Ix7k.mjs";import{createSystemReader as co}from"./createSystemReader-DcDLFfC-.mjs";import{ConflictError as Re}from"./ConflictError-C8GtJmjS.mjs";import{runTriggers as ao}from"./hasTrigger-CjlwI4le.mjs";import{CLIENT_WATERMARK_TABLE as ui,advanceClientWatermark as fi,migrateClientWatermark as hi,readClientWatermark as wi}from"./CLIENT_WATERMARK_TABLE-DPY-NtOH.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as gi,deleteGlobalShapeSnapshot as yi,deleteGlobalShapeSnapshotsForConnection as $i,migrateGlobalShapeSnapshot as Ei,readGlobalShapeSnapshot as mi,writeGlobalShapeSnapshot as Si}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-BpFE-qYL.mjs";import{IDEMPOTENCY_TABLE as Ri,readIdempotent as Ti,trimIdempotent as vi,writeIdempotent as Ai}from"./IDEMPOTENCY_TABLE-CUc9L-o_.mjs";import{runShardMigrations as Ci}from"./runShardMigrations-BtAyuuJb.mjs";import{S as bi}from"./ctx-db-search-state-z0OqNIGe.mjs";import{selectShapeMembers as Di,selectShapeRows as ki}from"./selectShapeMembers-DTA3YUf4.mjs";const lo=n=>{const r=atob(n),o=Uint8Array.from(r,d=>d.codePointAt(0)??0);return new TextDecoder().decode(o)},uo=()=>new $("BAD_REQUEST","invalid cursor"),Pt=16,Ut=8,z=1024,ht=(n,r)=>r.query(n),fo=(n,r)=>{if(n.length===0)return 0;let o=0;for(const[d,i]of r.entries()){const w=d===r.length-1;let _=0;for(const m of n)(w?m.startsWith(i):m===i)&&(_+=1);if(_===0)return 0;o+=_}return o},ho=(n,r)=>{if(!r)return{exact:!0,lower:n,upper:n};const o=[...n].at(-1)??"",d=(o.codePointAt(0)??0)+1;if(d>=55296&&d<=57343||d>1114111)return{exact:!0,lower:n,upper:n};const i=n.slice(0,n.length-o.length);return{exact:!1,lower:n,upper:i+String.fromCodePoint(d)}},wo=(n,r,o)=>{const d={eq:(i,w)=>{if(!n.definition.filterFields?.includes(i))throw new $("INTERNAL",`field "${i}" is not a filter field of search index "${n.indexName}" on table "${r}"`);if(n.filters.length>=Ut)throw new $("BAD_REQUEST",`search index "${n.indexName}" on table "${r}": at most ${String(Ut)} .eq() filters are supported per search query`);return n.filters.push({field:i,value:w}),d},search:(i,w)=>{const _=n;if(i!==_.definition.field)throw new $("INTERNAL",`search index "${_.indexName}" on table "${r}" indexes "${_.definition.field}", not "${i}"`);const m=ht(w,o).length;if(m>Pt)throw new $("BAD_REQUEST",`search index "${_.indexName}" on table "${r}": at most ${String(Pt)} search terms are supported (got ${String(m)})`);return _.field=i,_.query=w,_.hasQuery=!0,d}};return d},po=n=>{if(n.length>z)throw new $("BAD_REQUEST",`more than ${String(z)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},go=n=>Math.min(n.offset+n.numItems+1,z),yo=n=>btoa(`search:${String(n)}`),$o=n=>{let r;try{r=lo(n)}catch{return}if(!r.startsWith("search:"))return;const o=Number(r.slice(7));return Number.isInteger(o)&&o>=0?o:void 0},Eo=n=>{if(typeof n.endCursor=="string")throw new $("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");if(!Number.isFinite(n.numItems))throw new $("BAD_REQUEST",`search pagination needs a finite numItems, got ${String(n.numItems)}`);const r=Math.max(0,Math.floor(n.numItems)),o=n.cursor?$o(n.cursor):0;if(o===void 0)throw uo();if(o+r>=z)throw new $("BAD_REQUEST",`search pagination reaches the ${String(z)}-document limit (offset ${String(o)} + ${String(r)} requested) — a page must end below the cap so the probe row that answers \`hasMore\` still fits: retry with numItems ${String(Math.max(1,z-o-1))} or fewer, or narrow the query or the filters instead`);return{numItems:r,offset:o}},mo=(n,r)=>{const o=r.offset+r.numItems,d=r.numItems>0&&n.length>o;return{continueCursor:d?yo(o):null,isDone:!d,page:n.slice(r.offset,o)}},So=n=>{if(n===void 0)return z+1;if(!Number.isFinite(n))return z;const r=Math.max(0,Math.floor(n));if(r>z)throw new $("BAD_REQUEST",`search returns at most ${String(z)} documents (asked for ${String(r)}) — narrow the query or paginate instead`);return r},_o=32,Ro=1024,sn=(n,r,o,d)=>{const i=`SELECT id, _creationTime, ${ve(oe)} FROM ${ve(n)}`,w=`ORDER BY ${o}${d===void 0?"":` LIMIT ${String(d)}`}`;return r===void 0?Ne(`${i} ${w}`):_e(`${i} WHERE `,r,` ${w}`)},wt={fieldRef:n=>Ne(He(n)),serialize:ae},cn=n=>{const r=n.map(o=>`${He(o.field)} ${o.direction==="desc"?"DESC":"ASC"}`);return n.some(o=>o.field==="_id"||o.field==="id")||r.push(`${He("id")} ${Nn(n)==="desc"?"DESC":"ASC"}`),r.join(", ")},To={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},an=n=>new Set(n.sqlConditions.filter(r=>r.comparator==="=").map(r=>r.field)),vo=n=>{const r=an(n);let o=0;for(;o<n.indexFields.length&&r.has(n.indexFields[o]??"");)o+=1;return n.indexFields.slice(o)},Ao=(n,r)=>{const o=n.order,d=vo(n),{shape:i}=r;return d.length>0?ct(d.map(w=>({[w]:o})),i,{pinned:an(n),uniqueBy:on(r.indexes,i)}):ct([{_creationTime:o}],i)},Io=(n,r,o,d)=>{const i=n.sqlConditions.map(w=>({[w.field]:{[To[w.comparator]??"eq"]:w.value}}));if(o&&i.push(rn(r,at(o))),d&&i.push(jn(r,at(d))),i.length!==0)return i.length===1?i[0]:{AND:i}},Co=n=>{if(n.want!==void 0)return n.selective?Math.max(n.want,_o):n.want},dt=(n,r,o,d,i,w,_)=>{const m=Ao(d,o),x=cn(m),g=[],{filters:b,want:v}=w;let R=w.cursor??void 0,M=Co(w);if(v===0)return{documents:g,orderKeys:m};for(;;){const q=te(Io(d,m,R,w.endCursor),wt,je),B=sn(r,i&&q?_e(q," AND ",i):i??q,x,M),F=Te(n,B.text,...B.params).toArray();let P={};_(F.length);for(const C of F)if(P=Se(C),b.every(ne=>ne(P))&&g.push(P)===v)return{documents:g,orderKeys:m};if(M===void 0||F.length<M)return{documents:g,orderKeys:m};R=Oe(P,m),M=Math.max(M,Math.min(M*2,Ro))}},xo=(n,r,o,d,i,w,_,m)=>{const x=Math.max(0,Math.floor(i.numItems));if(typeof i.endCursor=="string"){const{documents:q,orderKeys:B}=dt(n,r,o,d,w,{cursor:i.cursor,endCursor:i.endCursor,filters:_.all,selective:_.selective,want:void 0},m),F=q.length>=2?q[Math.floor(q.length/2)-1]:void 0;return{continueCursor:i.endCursor,isDone:!0,page:q,splitCursor:F?Oe(F,B):null}}const{documents:g,orderKeys:b}=dt(n,r,o,d,w,{cursor:i.cursor,filters:_.all,selective:_.selective,want:x+1},m),v=g.length>x,R=v?g.slice(0,x):g,M=R.at(-1);return{continueCursor:v&&M?Oe(M,b):null,isDone:!v,page:R}},Ke=n=>{const r=new Map;return o=>{const d=r.get(o);if(d!==void 0)return d;const i=n(ve(o));return r.set(o,i),i}},fe=ve(oe),bo=Ke(n=>`INSERT INTO ${n} (id, _creationTime, ${fe}) VALUES (?, ?, ?)`),Gt=Ke(n=>`UPDATE ${n} SET ${fe} = ? WHERE id = ? AND ${fe} = ?`),Mo=Ke(n=>`UPDATE ${n} SET _creationTime = ?, ${fe} = ? WHERE id = ? AND ${fe} = ?`),Do=Ke(n=>`DELETE FROM ${n} WHERE id = ? AND ${fe} = ?`),ko="SELECT changes() AS changed",Ht=new Map,Lo="",Fo=n=>{const r=JSON.stringify(n),o=Ht.get(r);if(o!==void 0)return o;const d=n.map(w=>c`SELECT ${c.raw(`'${w.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${c.identifier(oe)} FROM ${c.identifier(w)} WHERE id = ${Lo}`),{sql:i}=tn("sqlite",c`${ft(d)} LIMIT 1`);return Ht.set(r,i),i},qo=(n,r)=>r.map(()=>n),Bo=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,Wo=n=>{if(!Bo.test(n))throw new $("INTERNAL",`invalid clientId ${JSON.stringify(n)}: a client-supplied row id must be a UUID`)},Ot=50,dn=500,Ue=Math.floor(nn.boundParams/3),Ee=nn.boundParams,Po=128,le=(n,r,o)=>{const d=r??dn;if(n>d)throw new $("BATCH_LIMIT_EXCEEDED",`${o}: batch of ${String(n)} exceeds the limit of ${String(d)} (raise options.limit or chunk the call)`,{status:400})},Uo=n=>{const r={eq:(o,d)=>(n.sqlConditions.push({comparator:"=",field:o,value:d}),r),gt:(o,d)=>(n.sqlConditions.push({comparator:">",field:o,value:d}),r),gte:(o,d)=>(n.sqlConditions.push({comparator:">=",field:o,value:d}),r),lt:(o,d)=>(n.sqlConditions.push({comparator:"<",field:o,value:d}),r),lte:(o,d)=>(n.sqlConditions.push({comparator:"<=",field:o,value:d}),r)};return r},Go=n=>Math.max(n,z),ln=(n,r)=>{const o=n.filters.map(d=>c`${ce(d.field)} = ${ae(d.value)}`);return r&&o.push(r),o},Ho=(n,r,o,d,i)=>{const w=ht(o.query,ut(o.definition.language));if(w.length===0)return[];const _=mn(r,o.indexName),m=`${_}__vocab`,x=w.length-1,g=w.map((B,F)=>{const P=ho(B,F===x),C=P.exact?c`${c.identifier("term")} = ${P.lower}`:c`${c.identifier("term")} >= ${P.lower} AND ${c.identifier("term")} < ${P.upper}`;return c`SELECT ${c.identifier("doc")}, ${c.raw(String(F))} AS ${c.identifier("__term__")}, COUNT(*) AS ${c.identifier("__n__")} FROM ${c.identifier(m)} WHERE ${C} GROUP BY ${c.identifier("doc")}`}),b=w.map((B,F)=>c`SUM(CASE WHEN u.${c.identifier("__term__")} = ${c.raw(String(F))} THEN u.${c.identifier("__n__")} ELSE 0 END)`),v=c`SELECT f.${c.identifier(qe)} AS ${c.identifier(qe)}, ${c.join(b,c` + `)} AS ${c.identifier("__score__")} FROM (${ft(g)}) u JOIN ${c.identifier(_)} f ON f.rowid = u.${c.identifier("doc")} GROUP BY f.${c.identifier(qe)} HAVING ${c.join(b.map(B=>c`${B} > 0`),c` AND `)}`,R=ln(o,i);let M=c`SELECT m.id, m._creationTime, m.${c.identifier(oe)}, s.${c.identifier("__score__")} AS ${c.identifier("__score__")} FROM (${v}) s JOIN ${c.identifier(r)} m ON m.id = s.${c.identifier(qe)}`;R.length>0&&(M=c`${M} WHERE ${c.join(R,c` AND `)}`),M=c`${M} ORDER BY s.${c.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${c.raw(String(d))}`;const q=[];for(const B of j(n,M)){const F=en(B);if(F){const P=B.__score__;q.push({document:F,score:typeof P=="number"?P:Number(P??0)})}}return q},Oo=(n,r,o,d,i)=>{const w=ut(o.definition.language),_=ht(o.query,w);if(_.length===0)return[];const m=ln(o,i);let x=c`SELECT id, _creationTime, ${c.identifier(oe)} FROM ${c.identifier(r)}`;m.length>0&&(x=c`${x} WHERE ${c.join(m,c` AND `)}`),x=c`${x} ORDER BY _creationTime DESC, id ASC LIMIT ${c.raw(String(Go(d)))}`;const g=j(n,x).toArray(),b=[];for(const v of g){const R=en(v);if(!R)continue;const M=fo(Sn(R,o.definition),_);M>0&&b.push({creationTime:typeof R._creationTime=="number"?R._creationTime:0,doc:R,id:typeof R._id=="string"?R._id:"",score:M})}return b.sort((v,R)=>R.score-v.score||R.creationTime-v.creationTime||v.id.localeCompare(R.id)),b.slice(0,d).map(v=>({document:v.doc,score:v.score}))},it=(n,r,o,d)=>{if(!Number.isFinite(n.lat)||n.lat<-90||n.lat>90||!Number.isFinite(n.lng)||n.lng<-180||n.lng>180)throw new $("BAD_REQUEST",`geo index "${d}" on table "${o}": ${r} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},No=(n,r)=>{const o=n,d={near:(i,w)=>{if(o.within)throw new $("INTERNAL",`geo index "${o.indexName}" on table "${r}": call .near() or .within(), not both`);if(it(i,".near() point",r,o.indexName),!Number.isFinite(w)||w<=0)throw new $("BAD_REQUEST",`geo index "${o.indexName}" on table "${r}": .near() radiusMeters must be a finite number > 0, got ${String(w)}`);return o.near={point:{lat:i.lat,lng:i.lng},radiusMeters:w},d},within:i=>{if(o.near)throw new $("INTERNAL",`geo index "${o.indexName}" on table "${r}": call .near() or .within(), not both`);if(it(i.sw,".within() sw corner",r,o.indexName),it(i.ne,".within() ne corner",r,o.indexName),i.sw.lat>i.ne.lat)throw new $("BAD_REQUEST",`geo index "${o.indexName}" on table "${r}": .within() corners are transposed (sw.lat > ne.lat)`);if(i.sw.lng>i.ne.lng)throw new $("BAD_REQUEST",`geo index "${o.indexName}" on table "${r}": .within() box crosses the antimeridian (sw.lng > ne.lng), which is not supported — split it into two boxes at ±180 and union the results`);return o.within={ne:{lat:i.ne.lat,lng:i.ne.lng},sw:{lat:i.sw.lat,lng:i.sw.lng}},d}};return d},jo=(n,r)=>{const o=n[r];if(o===null||typeof o!="object")return;const{lat:d,lng:i}=o;return typeof d=="number"&&typeof i=="number"?{lat:d,lng:i}:void 0},Ko=(n,r)=>{const o=jo(n,r.definition.field);if(!o)return;const d=typeof n._creationTime=="number"?n._creationTime:0;if(r.near){const i=Gn(r.near.point,o);return i<=r.near.radiusMeters?{creationTime:d,distance:i}:void 0}return Hn(o,r.within)?{creationTime:d,distance:0}:void 0},Qo=(n,r,o,d)=>{if(!o.near&&!o.within)throw new $("INTERNAL",`geo index "${o.indexName}" on table "${r}": call .near(point, radius) or .within(box)`);const i=o.near?Pn(o.near.point,o.near.radiusMeters):Un(o.within),w=Bn(r,o.indexName),_=i.map(v=>c`(g.${c.identifier("__geohash__")} >= ${v} AND g.${c.identifier("__geohash__")} < ${`${v}{`})`),m=[c`(${c.join(_,c` OR `)})`];d&&m.push(d);const x=c`SELECT m.id, m._creationTime, m.${c.identifier(oe)} FROM ${c.identifier(w)} g JOIN ${c.identifier(r)} m ON m.id = g.${c.identifier("__id__")} WHERE ${c.join(m,c` AND `)}`,g=j(n,x).toArray(),b=[];for(const v of g){const R=Se(v),M=R?Ko(R,o):void 0;R&&M&&b.push({creationTime:M.creationTime,distance:M.distance,doc:R})}return b.sort((v,R)=>v.distance-R.distance||R.creationTime-v.creationTime),b},un=(n,r,o,d)=>{const i=[];for(const w of n)if(r.every(_=>_(d(w)))&&(i.push(w),typeof o=="number"&&i.length>=o))break;return i},Vo=(n,r,o,d,i,w=()=>{})=>{const _=o.within!==void 0,m=Qo(n,r,o,i).map(x=>({distanceMeters:_?null:x.distance,document:x.doc}));return w(m.length),typeof d=="number"?m.slice(0,Math.max(0,Math.floor(d))):m},Nt=(n,r,o,d,i,w,_=()=>{})=>{const{geo:m}=o;if(!m)throw new $("INTERNAL","runGeoTerminalScored called without a staged geo query");const x=i.length>0,g=Vo(n,r,m,x?void 0:w,d,_);return x?un(g,i,w,b=>b.document):g},me={fieldRef:ce,serialize:ae},fn=(n,r)=>{const o=r===void 0?void 0:n.shape[r];return o!==void 0&&so(o)},jt=(n,r)=>r.some(o=>fn(n,o)),Kt=(n,r,o)=>{if(fn(n,r))throw new $("BAD_REQUEST",`${o}: "${r}" may hold an order-preserving key rather than a value SQL can reduce or group — declare an aggregateIndex covering this (by, field, op) so the maintained companion answers it instead (its running total is a REAL, so it stays exact only while the total is inside 2^53)`)},zo=n=>{let r=0;const o=[],d={fieldRef:i=>Ne(He(i)),relationExists:i=>{const{childWhere:w,negated:_,parentTable:m,relation:x}=i,g=`__rel_${String(r)}`,b=o.at(-1)??m;r+=1,n(x.table,O);const v=x.kind==="one"?x.field:x.references,R=x.kind==="one"?x.references:x.field,M=Ne(`${bt(g,R)} = ${bt(b,v)}`);o.push(g);const q=te(w,d,je);o.pop();const B=q===void 0?M:_e(M," AND ",q),F=_e("EXISTS (SELECT 1 FROM ",Ft(x.table)," AS ",Ft(g)," WHERE ",B,")");return _?_e("NOT ",F):F},serialize:ae};return d};class Jo extends ${constructor(r="unique() found more than one matching document"){super("NOT_UNIQUE",r,{name:"NotUniqueError"})}}const Yo=/\s/u,Xo=String.fromCodePoint(0),Qt=(n,r,o)=>{if(!n.tables[r])throw new $("INTERNAL",`unknown table: ${r}`);return typeof o!="string"||o.length===0||Yo.test(o)||o.includes(Xo)?null:o},hn=(n,r,o,d=()=>{},i=()=>{},w=()=>{},_)=>{const m=r.tables[o];if(!m)throw new $("INTERNAL",`unknown table: ${o}`);const x=ue(m.softDeleteMode,void 0),g=_??{indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[],verifyFilters:[]},b=()=>{const y=N(x,g.pushedWhere);return y?te(y,me):void 0},v=()=>{const y=N(x,g.pushedWhere);return y?te(y,wt,je):void 0},R=()=>[...g.inMemoryFilters,...g.verifyFilters];let M=0;const q=y=>{const{search:A}=g;if(!A)throw new $("INTERNAL","runSearchFetch called without a staged search");Cn(n,o,m);const D=g.inMemoryFilters.length>0,L=So(D?void 0:y),X=qn(n);if(X&&!xn(n,o,A.definition))throw new $("SEARCH_INDEX_BUILDING",`search index "${A.indexName}" on table "${o}" is still backfilling and currently covers only part of the table — retry once it finishes, or run the backfillSearch admin operation to complete it now`);const he=b(),J=X?Ho(n,o,A,L,he):Oo(n,o,A,L,he);!D&&y===void 0&&po(J);const re=R();return M=J.length,re.length>0?un(J,re,y,Ae=>Ae.document):J},B=y=>q(y).map(A=>A.document),F=y=>{const A=Eo(y);return mo(B(go(A)),A)},P=()=>{if(g.search||g.geo||g.indexName===void 0){i(void 0);return}i(Xn(o,g.indexName,g.indexFields,g.sqlConditions,ae))},C=y=>{P();let A=0;const D=(()=>{if(g.search){const L=B(y);return A=M,L}return g.geo?Nt(n,o,g,b(),R(),y,L=>{A=L}).map(L=>L.document):dt(n,o,m,g,v(),{filters:R(),selective:g.inMemoryFilters.length>0,want:y===void 0?void 0:Math.max(0,Math.floor(y))},L=>{A+=L}).documents})();return w(Math.max(A,D.length)),D},ne=()=>{if(!g.search&&!g.geo)throw new $("INTERNAL",`ctx.db.query("${o}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);P();let y=0;const A=(()=>{if(g.search){const D=q(void 0);return y=M,D}return Nt(n,o,g,b(),R(),void 0,D=>{y=D})})();return w(Math.max(y,A.length)),A},Y={async*[Symbol.asyncIterator](){const y=hn(n,r,o,d,i,w,{...g,indexFields:[...g.indexFields],inMemoryFilters:[...g.inMemoryFilters],sqlConditions:[...g.sqlConditions],verifyFilters:[...g.verifyFilters]});if(g.search){yield*await y.collect();return}let A;for(;;){const D=await y.paginate({cursor:A??null,numItems:Po});if(yield*D.page,D.isDone||D.continueCursor===null)return;A=D.continueCursor}},async collect(){return C(void 0)},async collectWithScores(){return ne()},filter(y){const A=Zn(y);return A!==void 0&&eo(A,m.shape)?(g.pushedWhere=N(g.pushedWhere,A),g.verifyFilters.push(y)):g.inMemoryFilters.push(y),Y},async first(){return C(1)[0]??null},order(y){return g.order=y==="desc"?"desc":"asc",Y},async paginate(y){let A=0;if(P(),g.search){const L=F(y);return w(L.page.length),L}if(g.geo)throw new $("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const D=xo(n,o,m,g,y,v(),{all:R(),selective:g.inMemoryFilters.length>0},L=>{A+=L});return w(Math.max(A,D.page.length)),D},async take(y){return C(y)},async unique(){const y=C(2);if(y.length>1)throw new Jo(`unique() on table "${o}" matched ${String(y.length)} documents; expected at most one`);return y[0]??null},withGeoIndex(y,A){const D=(m.geoIndexes??[]).find(X=>X.name===y);if(!D)throw new $("INTERNAL",`unknown geo index "${y}" on table "${o}"`);d(o,y,"geo");const L={definition:D,indexName:y};if(g.geo=L,A(No(L,o)),!L.near&&!L.within)throw new $("INTERNAL",`geo index "${y}" on table "${o}" requires a .near(point, radius) or .within(box) call`);return Y},withIndex(y,A){const D=m.indexes.find(L=>L.name===y);if(!D)throw new $("INTERNAL",`unknown index "${y}" on table "${o}"`);return d(o,y,"index"),g.indexName=y,g.indexFields=D.fields,A&&A(Uo(g)),Y},withSearchIndex(y,A){const D=(m.searchIndexes??[]).find(X=>X.name===y);if(!D)throw new $("INTERNAL",`unknown search index "${y}" on table "${o}"`);d(o,y,"search");const L={definition:D,field:D.field,filters:[],hasQuery:!1,indexName:y,query:""};if(g.search=L,A(wo(L,o,ut(D.language))),!L.hasQuery)throw new $("INTERNAL",`search index "${y}" on table "${o}" requires a .search(field, query) call`);return Y}};return Y},Vt=(n,r,o)=>{const d={...r};for(const[i,w]of Zt(n)){if(w.serverDefault){d[i]=w.serverDefault({auth:o});continue}d[i]===void 0&&(w.defaultFn?d[i]=w.defaultFn():"defaultValue"in w&&(d[i]=w.defaultValue))}return d},zt=(n,r,o,d)=>{const i=o;for(const[w,_]of Zt(n)){if(_.serverDefault){w in r&&(i[w]=_.serverDefault({auth:d}));continue}_.onUpdateFn&&!(w in r)&&(i[w]=_.onUpdateFn())}},Jt=(n,r)=>{for(const o of Object.keys(r))if(r[o]===void 0)throw new $("INTERNAL",`Cannot ${n} field '${o}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},Yt=["_commitSeq","_creationTime","_id"],st=n=>Yt.some(r=>r in n)?Object.fromEntries(Object.entries(n).filter(([r])=>!Yt.includes(r))):n,Zo=/unique constraint failed/i,er=n=>n instanceof Error&&Zo.test(n.message),tr=/string or blob too big/iu,nr=(n,r)=>{if(!(!(n instanceof Error)||!tr.test(n.message)))throw new $("PAYLOAD_TOO_LARGE",`document is too large to store in "${r}": a single row cannot exceed the storage engine's per-row ceiling (2 MB on a Durable Object's SQLite). The limit is on the STORED bytes, which are UTF-8, and v.bytes()/v.bigint() columns are stored twice on a shard-local table. Keep the payload in R2 (ctx.storage) and store a reference on the row.`)},lt=(n,r,o,d)=>{try{Te(n,o,...d)}catch(i){throw er(i)?new Re(`unique constraint violation on "${r}"`,"unique"):(nr(i,r),i)}},Ge=(n,r,o,d)=>{if(lt(n,r,o,d),Te(n,ko).one().changed===0)throw new Re(`optimistic concurrency conflict on "${r}" — the row changed during this mutation; refetch and retry`,"occ")},Xt=(n,r,o,d,i,w,_)=>{const m=[];for(let v=0;v<o.length+1;v+=1){const R=o[v],M=d[v],q=M?.direction==="desc"?"desc":"asc",B=R===void 0||M===void 0?c`${c.identifier(zn)} < ${_}`:Jn(R,w[v],q,!1);if(B===void 0)continue;const F=[];for(let C=0;C<v;C+=1)F.push(c`${c.identifier(o[C])} IS ${w[C]}`);F.push(B);const[P]=F;m.push(F.length===1&&P!==void 0?P:c`(${c.join(F,c` AND `)})`)}const x=m.length>0?c.join(m,c` OR `):c`1 = 0`,g=j(n,c`SELECT COUNT(*) AS c FROM ${c.identifier(r)} WHERE ${c.identifier("__partition__")} = ${i} AND (${x})`).one(),b=j(n,c`SELECT COUNT(*) AS c FROM ${c.identifier(r)} WHERE ${c.identifier("__partition__")} = ${i}`).one();return{before:g.c,total:b.c}},Ur=n=>{const{baselineSeq:r,onStalePatchDropped:o}=n,{sql:d}=n,{schema:i}=n,w=n.broadcast??(()=>{}),_=to(i);let m;const x=()=>n.inTransaction?.()===!0,g=e=>i.tables[e]?.commitOrderedMode!==!0?{}:((m===void 0||!x())&&(m=Dn(d)),{[kn]:m}),b=(e,...t)=>{const s=i.tables[e]?.indexes;if(!s||s.length===0)return;const f=[];for(const h of t)h&&f.push(...Yn(s,h,ae));return f.length>0?f:void 0},{headroom:v}=n;let R=!1;const M=async e=>{const t=R;R=!0;try{return await e()}finally{R=t}},q=n.onRead??(()=>{}),B=e=>{Ct(i.tables[e])&&q(Lt,Lt)},F=n.onReadRange??(e=>{q(e.table,O)}),P=e=>{B(e.table),F(e)},C=(e,t)=>{t!==void 0&&t!==O&&!R&&v?.recordRead(1),B(e),q(e,t)},ne=n.onIndexUse??(()=>{}),Y=n.onWrite??(()=>{}),y=e=>{R||v?.recordWrite(e)},A=async e=>{y(e.doc),await Y(e)},{cache:D}=n,L=n.clock??(()=>Date.now()),X=n.idGenerator??(()=>crypto.randomUUID()),he=n.scheduler??Rn,{globalDb:J}=n,re=n.auth??{identity:null,userId:null},Ae=n.cdc??!1,Qe=he,wn=co({scheduler:typeof Qe.list=="function"&&typeof Qe.get=="function"?Qe:void 0,storage:n.storage}),we=(e,t,s,f)=>{Ae&&!Ct(i.tables[e])&&bn(d,L(),e,t,s,f)},pn=(e,t,s,f)=>{if(i.tables[e]?.dropStalePatchesMode!==!0||!Ae)return!1;const h=r?.();if(h===void 0)return!1;const l=Mn(d,e,t,h);return l===void 0?!1:Object.keys(st(s)).some(a=>It(l[a])!==It(f[a]))},ie=e=>i.tables[e]?.shardMode?.kind==="global",pt=(e,t)=>{if(ie(e)){if(!J)throw new $("INTERNAL",`cross-backend ${t} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return J}return G},Ve=e=>pt(e,"cascade"),Q=(e,t)=>{if(ie(e)){if(!J)throw new $("INTERNAL",`${t} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return J}},gt=async(e,t,s,f,h)=>{h&&y(s);const l=await e.insert(t,s,f);return w({key:l,op:"insert",row:{...s,_id:l},table:t}),l},ze=(e,t)=>pt(e,"relation load").findMany(e,t),yt=(e,t)=>(ie(e)&&C(e,O),ze(e,t)),gn=e=>!ie(e.table),$t=n.relationExistsPushDown??"auto",Et=$t!=="never",{maxRelationKeys:mt}=n,Ie=(e,t,s)=>qt(e,{fetcher:yt,maxRelationKeys:mt,relationBaseWhere:s,schema:i,tableName:t}),St=async(e,t,s,f)=>{const h=Q(e,"relation grouped count");if(h)return C(e,O),ro((U,I)=>h.count(U,I),e,t,s,f);const l=i.tables[e];if(!l)throw new $("INTERNAL",`unknown table: ${e}`);C(e,O);const a=ue(l.softDeleteMode,void 0),u={[t]:{in:s}},p=N(N(u,f),a),T=await Ie(p,e,void 0),E=te(T,me),k=ce(t);let S=c`SELECT ${k} AS __fk__, COUNT(*) AS count FROM ${c.identifier(e)}`;E&&(S=c`${S} WHERE ${E}`),S=c`${S} GROUP BY ${k}`;const W=j(d,S).toArray();return new Map(W.map(U=>[U.__fk__,U.count]))};let Ce=0;const _t=new Set;for(const[e,t]of Object.entries(i.tables))for(const s of Object.values(t.triggerMap??{}))_t.add(`${e} ${s.timing} ${s.op}`);const Z=(e,t,s)=>_t.has(`${e} ${t} ${s}`),ee=async(e,t,s)=>{if(Ce+=1,Ce>Ot)throw Ce-=1,new Re(`trigger recursion exceeded ${String(Ot)} levels on "${s.table}" — check for a self-triggering write`,"trigger");try{await ao({ctx:$n,event:s,op:t,schema:i,tableName:s.table,timing:e})}finally{Ce-=1}},{ensureBackfilledForTable:pe,ensureBackfilledIndex:Je,ensureRankBackfilled:Ye,ensureRankBackfilledForTable:ge,syncAggregates:xe,syncCompanionsForInsert:Rt,syncGeo:be,syncRanks:ye,syncSearch:Me}=Ln({broadcast:w,indexKeysFor:(e,t)=>b(e,t),invalidateCache:(e,t,s)=>D?.invalidate(e,t,b(e,s)),recordCdc:we,schema:i,sql:d}),Tt=(e,t,s)=>{const{shardMode:f}=t;if(f?.kind==="shardBy"&&!(f.field!==void 0&&(s.partitionBy??[]).includes(f.field)))throw Object.assign(new Error(`rank index "${s.name}" on "${e}" partitions across shards (shard key "${f.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})},vt=e=>Object.entries(i.tables).filter(([,t])=>t.shardMode?.kind!=="global").map(([t])=>t).filter(t=>e===void 0||t===e),$e=e=>e===void 0||ie(e)?J:void 0,se=(e,t)=>{const s=vt(t);for(let f=0;f<s.length;f+=Ee){const h=s.slice(f,f+Ee),[l]=Te(d,Fo(h),...qo(e,h)).toArray();if(!l)continue;const a=l.__t__,u=Se(l);if(typeof a!="string"||!u)return;const p=l[oe];return{docJson:typeof p=="string"?p:de(p??{}),row:u,tableName:a}}},yn=(e,t)=>{const s=[...new Set(e)],f=new Map;if(s.length===0)return f;const h=vt(t);for(let l=0;l<h.length;l+=Ee){const a=h.slice(l,l+Ee),u=Math.floor(Ee/a.length),p=Wn(c`${c.identifier("id")}`,s,!1,u),T=a.map(E=>c`SELECT ${c.raw(`'${E.replaceAll("'","''")}'`)} AS __t__, id FROM ${c.identifier(E)} WHERE ${p}`);for(const E of j(d,ft(T))){const{id:k,__t__:S}=E;typeof S=="string"&&typeof k=="string"&&f.set(k,S)}}return f},At={assertRankPartitionLocal:Tt,ensureRankBackfilled:Ye,onRead:C,rowToDocument:Se,schema:i,sql:d},G={system:wn,async aggregate(e,t){const s=Q(e,"aggregate");if(s)return C(e,O),s.aggregate(e,t);const f=i.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);if(Be(t.op),t.op==="count")return G.count(e,{baseWhere:t.baseWhere,relationBaseWhere:t.relationBaseWhere,restrictsCounts:t.restrictsCounts,where:t.where});if(!t.field)throw new $("INTERNAL",`aggregate(${e}, { op: "${t.op}" }): "field" is required for non-count reducers`);C(e,O);const h=ue(f.softDeleteMode,void 0),l=N(N(t.baseWhere,t.where),h),a=await Ie(l,e,t.relationBaseWhere),u=a!==l;if(f.aggregateIndexes&&!t.baseWhere&&!u&&(!h||jt(f,[t.field]))){const U=In(f.aggregateIndexes,t.op,t.field,t.where);if(U){Je(e,U.index);const I=Ze(U.index.by??[],U.key),K=Xe(e,U.index.name),V=j(d,c`SELECT ${We} AS value, ${nt} AS count FROM ${c.identifier(K)} WHERE ${Pe} = ${I}`).toArray()[0];return et(t.op,V)}}Kt(f,t.field,`aggregate(${e}, { op: "${t.op}", field: "${t.field}" })`);const p=te(a,me),T=Be(t.op),E=ce(t.field);let k=c`SELECT ${c.raw(T)}(${E}) AS value FROM ${c.identifier(e)}`;p&&(k=c`${k} WHERE ${p}`);const W=j(d,k).toArray()[0]?.value;return W??null},asId(e,t){const s=Qt(i,e,t);if(s===null)throw new $("BAD_REQUEST",`asId("${e}", …): "${t}" is not a valid id for table "${e}"`,{status:400});return s},async count(e,t){const s=Q(e,"count");if(s)return C(e,O),s.count(e,t);const f=i.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);const h=Tn(t);if(h.restrictsCounts)throw new tt(e);C(e,O);const l=ue(f.softDeleteMode,void 0),a=N(N(h.baseWhere,h.where),l),u=await Ie(a,e,h.relationBaseWhere),p=u!==a;if(f.aggregateIndexes&&!h.baseWhere&&!p&&!l){const S=An(f.aggregateIndexes,h.where);if(S){Je(e,S.index);const W=Ze(S.index.by??[],S.key),U=Xe(e,S.index.name),I=j(d,c`SELECT ${We} AS value FROM ${c.identifier(U)} WHERE ${Pe} = ${W}`).toArray();return I[0]===void 0?0:I[0].value??0}}const T=te(u,me);let E=c`SELECT COUNT(*) AS count FROM ${c.identifier(e)}`;return T&&(E=c`${E} WHERE ${T}`),j(d,E).one().count},async delete(e,t,s){const f=se(e,t);if(!f){const E=$e(t);E&&(y(void 0),await E.delete(e,t,s));return}const{docJson:h,row:l,tableName:a}=f,u=i.tables[a],p=s?.hard===!0,T=!p&&u?.softDeleteMode?u.softDeleteMode.field:void 0;if(!(T&&l[T]!==null&&l[T]!==void 0)){if(Z(a,"before","delete")&&await ee("before","delete",{id:e,op:"delete",previous:l,table:a}),await oo({deletedId:e,deletedReference:E=>l[E],findHolders:async(E,k,S)=>(await Ve(E).findMany(E,{includeDeleted:p,where:{[k]:S}})).page,onCascade:(E,k)=>Ve(E).delete(k,void 0,s),onRestrict:E=>{throw new Re(E,"restrict")},onSetNull:(E,k,S)=>Ve(E).patch(k,{[S]:null}),schema:i,tableName:a}),pe(a),ge(a),T){const E={...l,...g(a),[T]:L(),_id:e};Ge(d,a,Gt(a),[de(E),e,h]),Me(a,e,E,l),be(a,e,void 0),xe(a,l,E),ye(a,e,l,void 0),D?.invalidate(a,e,b(a,l,E)),we(a,e,"update",E),w({indexKeys:b(a,l,E),key:e,op:"update",row:E,table:a}),Z(a,"after","delete")&&await ee("after","delete",{id:e,op:"delete",previous:l,table:a}),await A({id:e,op:"delete",table:a});return}Ge(d,a,Do(a),[e,h]),Me(a,e,void 0),be(a,e,void 0),xe(a,l,void 0),ye(a,e,l,void 0),D?.invalidate(a,e,b(a,l)),we(a,e,"delete"),w({indexKeys:b(a,l),key:e,op:"delete",table:a}),Z(a,"after","delete")&&await ee("after","delete",{id:e,op:"delete",previous:l,table:a}),await A({id:e,op:"delete",table:a})}},async deleteAll(e,t){if(!i.tables[e])throw new $("INTERNAL",`unknown table: ${e}`);const s=Math.max(1,t?.chunkSize??dn),f=t?.hard===void 0?void 0:{hard:t.hard},h=ie(e)?void 0:e;let l=0;return await M(async()=>{for(;;){const u=(await G.findMany(e,{limit:s})).page.map(p=>String(p._id));if(u.length===0)break;for(const p of u)await G.delete(p,h,f),l+=1;if(u.length<s)break}}),{deleted:l}},async deleteMany(e,t,s){le(e.length,t?.limit,"deleteMany");for(const f of e)await G.delete(f,s);return{deleted:e.length}},async deleteWhere(e,t,s){const l=(await(Q(e,"deleteWhere")??G).findMany(e,{where:t})).page.map(a=>String(a._id));if(le(l.length,s?.limit,"deleteWhere"),G.deleteMany===void 0)throw new $("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return G.deleteMany(l,s)},async findFirst(e,t={}){return(await G.findMany(e,{...t,limit:1,omitContinueCursor:!0})).page[0]??null},async findFirstOrThrow(e,t={}){const s=await G.findFirst(e,t);if(s===null)throw new On(`findFirstOrThrow: no "${e}" document matched`);return s},async findMany(e,t={}){const s=Q(e,"findMany");if(s)return C(e,O),s.findMany(e,t);const f=i.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);const h=!t.where&&!t.baseWhere;h?C(e,O):C(e);const l=ct(t.orderBy,f.shape,{pinned:Kn(t.where),uniqueBy:on(f.indexes,f.shape)}),a=t.cursor?rn(l,at(t.cursor)):void 0;let u=N(t.baseWhere,t.where);u=N(u,ue(f.softDeleteMode,t.includeDeleted)),u=await qt(u,{canPushExists:Et?gn:void 0,existsPushMode:$t==="always"?"always":"auto",fetcher:yt,maxRelationKeys:mt,relationBaseWhere:t.relationBaseWhere,schema:i,tableName:e}),a&&(u=u?{AND:[u,a]}:a);const p=Et?zo(C):wt,T=te(u,p,je),E=typeof t.limit=="number"?Math.max(0,Math.floor(t.limit)):void 0,k=sn(e,T,cn(l),E===void 0?void 0:E+1),S=Te(d,k.text,...k.params).toArray();h&&!R&&v?.recordRead(S.length);const W=[];for(const V of S){const H=Se(V);H&&(W.push(H),!h&&typeof H._id=="string"&&C(e,H._id))}if(E===void 0)return t.with&&await Bt({groupedCounter:St,fetcher:ze,parents:W,...Wt(t),schema:i,tableName:e,with:t.with}),{continueCursor:null,isDone:!0,page:Mt(W,t.select,t.with)};const U=W.length>E,I=U?W.slice(0,E):W,K=I.at(-1);return t.with&&await Bt({fetcher:ze,groupedCounter:St,parents:I,...Wt(t),schema:i,tableName:e,with:t.with}),{continueCursor:U&&K&&t.omitContinueCursor!==!0?Oe(K,l):null,isDone:!U,page:Mt(I,t.select,t.with)}},async get(e,t){const s=se(e,t);if(!s){const f=$e(t);return f?f.get(e,t):null}return C(s.tableName,e),s.row},async lookupById(e,t){const s=se(e,t);return s?(C(s.tableName,e),{row:s.row,tableName:s.tableName}):null},async groupBy(e,t){const s=Q(e,"groupBy");if(s)return C(e,O),s.groupBy(e,t);const f=i.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);C(e,O);const h=t.agg??{op:"count"};if(Be(h.op),h.op!=="count"&&!h.field)throw new $("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);const l=ue(f.softDeleteMode,void 0),a=N(N(t.baseWhere,t.where),l),u=await Ie(a,e,t.relationBaseWhere),p=u!==a,T=[...t.by,h.field];if(f.aggregateIndexes&&!t.baseWhere&&!p&&(!l||jt(f,T))){const I=vn(f.aggregateIndexes,h.op,h.field,t.by,t.where),K=I===void 0?0:Object.keys(I.partial).length,V=I?.index.by?.length??0;if(I&&(K===0||K===V)){Je(e,I.index);const H=Xe(e,I.index.name),De=Object.keys(I.partial),ke=[];if(De.length===(I.index.by??[]).length&&De.length>0){const Le=Ze(I.index.by??[],I.partial),Fe=j(d,c`SELECT ${We} AS value, ${nt} AS count FROM ${c.identifier(H)} WHERE ${Pe} = ${Le}`).toArray();return Fe.length>0&&ke.push({key:{...I.partial},value:et(h.op,Fe[0])}),ke}const En=j(d,c`SELECT ${Pe} AS key, ${We} AS value, ${nt} AS count FROM ${c.identifier(H)}`).toArray();for(const Le of En){const Fe=_n(JSON.parse(Le.key));ke.push({key:Fe,value:et(h.op,Le)})}return ke}}for(const I of T){if(I===void 0)continue;const K=I===h.field?`groupBy(${e}, { agg: { op: "${h.op}", field: "${I}" } })`:`groupBy(${e}, { by: [..."${I}"] })`;Kt(f,I,K)}const E=te(u,me),k=t.by.map(I=>c`${ce(I)} AS ${c.identifier(I)}`);if(h.op==="count")k.push(c`COUNT(*) AS value`);else{const{field:I}=h;if(I===void 0)throw new $("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);k.push(c`${c.raw(Be(h.op))}(${ce(I)}) AS value`)}let S=c`SELECT ${c.join(k,c`, `)} FROM ${c.identifier(e)}`;E&&(S=c`${S} WHERE ${E}`),S=c`${S} GROUP BY ${c.join(t.by.map(I=>ce(I)),c`, `)}`;const W=j(d,S).toArray(),U=[];for(const I of W){const K={};for(const H of t.by)K[H]=Fn(f.shape[H],I[H]??null);const{value:V}=I;U.push({key:K,value:V==null?null:Number(V)})}return U},async insert(e,t,s){const f=Q(e,"insert");if(f)return gt(f,e,t,s,!0);const h=i.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);const l=Vt(h,t,re);rt(h,l);let a;s?.clientId!==void 0?(Wo(s.clientId),a=s.clientId):s?.allowExplicitId&&typeof l._id=="string"?a=l._id:a=X();const u=s?.allowExplicitId&&typeof l._creationTime=="number"?l._creationTime:L(),p={...l,...g(e),_creationTime:u,_id:a};return Z(e,"before","insert")&&await ee("before","insert",{doc:{...p},id:a,op:"insert",table:e}),pe(e),ge(e),lt(d,e,bo(e),[a,u,de(p)]),Rt(e,a,p),Z(e,"after","insert")&&await ee("after","insert",{doc:p,id:a,op:"insert",table:e}),await A({doc:p,id:a,op:"insert",table:e}),a},async insertManyUnsafe(e,t,s){if(le(t.length,s?.limit,"insertManyUnsafe"),t.length===0)return[];const f=Q(e,"insert");if(f){const u=[];for(const p of t)y(p);for(const p of t){const T=await f.insert(e,p,{allowExplicitId:s?.allowExplicitId});w({key:T,op:"insert",row:{...p,_id:T},table:e}),u.push(T)}return u}const h=i.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);pe(e),ge(e);const l=[];for(let u=0;u<t.length;u+=Ue)l.push(g(e));const a=t.map((u,p)=>{const T=Vt(h,u,re),E=s?.allowExplicitId===!0&&typeof T._id=="string"?T._id:X(),k=s?.allowExplicitId===!0&&typeof T._creationTime=="number"?T._creationTime:L(),S={...T,...l[Math.floor(p/Ue)],_creationTime:k,_id:E};return{creationTime:k,document:S,id:E}});for(const u of a)y(u.document);for(let u=0;u<a.length;u+=Ue){const p=c.join(a.slice(u,u+Ue).map(E=>c`(${E.id}, ${E.creationTime}, ${de(E.document)})`),c`, `),T=tn("sqlite",c`INSERT INTO ${c.identifier(e)} (id, _creationTime, ${c.identifier(oe)}) VALUES ${p}`);lt(d,e,T.sql,T.params)}for(const{document:u,id:p}of a)Rt(e,p,u),await Y({doc:u,id:p,op:"insert",table:e});return a.map(u=>u.id)},async insertMany(e,t,s){le(t.length,s?.limit,"insertMany");const f=s?.skipDuplicates===!0,h=[],l=Q(e,"insert");if(l)for(const u of t)y(u);const a=async u=>l?gt(l,e,u,void 0,!1):G.insert(e,u);for(const u of t)try{h.push(await a(u))}catch(p){if(f&&p instanceof Re&&p.kind==="unique")h.push(null);else throw p}return h},normalizeId(e,t){return Qt(i,e,t)},async patch(e,t,s){const f=se(e,s);if(!f){const T=$e(s);if(T){y(t),await T.patch(e,t,s);return}throw new $("NOT_FOUND",`document not found: ${e}`)}const{docJson:h,row:l,tableName:a}=f,u=i.tables[a];if(!u)throw new $("INTERNAL",`unknown table: ${a}`);if(C(a,e),Jt("patch",t),pn(a,e,t,l)){o?.({fields:Object.keys(st(t)),id:e,table:a});return}const p={...l,...st(t),...g(a),_id:e};zt(u,t,p,re),rt(u,p,!0),Z(a,"before","update")&&await ee("before","update",{doc:{...p},id:e,op:"update",previous:l,table:a}),pe(a),ge(a),Ge(d,a,Gt(a),[de(p),e,h]),Me(a,e,p,l),be(a,e,p),xe(a,l,p),ye(a,e,l,p),D?.invalidate(a,e,b(a,l,p)),we(a,e,"update",p),w({indexKeys:b(a,l,p),key:e,op:"update",row:p,table:a}),Z(a,"after","update")&&await ee("after","update",{doc:p,id:e,op:"update",previous:l,table:a}),await A({doc:p,id:e,op:"update",table:a})},async patchMany(e,t,s){le(e.length,t?.limit,"patchMany");for(const f of e)await G.patch(f.id,f.patch,s);return{patched:e.length}},async patchWhere(e,t,s){const l=(await(Q(e,"patchWhere")??G).findMany(e,{where:t.where})).page.map(a=>({id:String(a._id),patch:t.patch}));if(le(l.length,s?.limit,"patchWhere"),G.patchMany===void 0)throw new $("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await G.patchMany(l,s),{patched:l.length}},async related(e,t){return no(G,_,e,t)},relationEdges:_,query(e){const t=Q(e,"query");return t?(C(e,O),t.query(e)):hn(d,i,e,ne,s=>{s?P(s):C(e,O)},s=>{R||v?.recordRead(s)})},async rank(e,t,s){const f=Q(e,"rank");if(f)return C(e,O),f.rank(e,t,s);ne(e,t,"rank");const h=i.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);const l=h.rankIndexes?.find(H=>H.name===t);if(!l)throw new $("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(Tt(e,h,l),s.restrictsCounts)throw new tt(e);C(e,O),Ye(e,l);const a=typeof s.row=="string"?s.row:s.row._id;if(!a)return null;const u=Dt(e,l.name),p=l.sortBy.map((H,De)=>kt(De)),T=p.map(H=>ve(H)).join(", "),E=j(d,c`SELECT ${c.identifier("__partition__")}, ${c.raw(T)} FROM ${c.identifier(u)} WHERE ${c.identifier("__id__")} = ${a}`).toArray(),[k]=E;if(k===void 0)return null;let S=k.__partition__;const W=N(s.baseWhere,s.where);ot(W,i,e,"rank");const U=Qn(l,W);if(U){const H=Vn(l.partitionBy??[],U);if(H!==S)return null;S=H}const I=p.map(H=>k[H]),{before:K,total:V}=Xt(d,u,p,l.sortBy,S,I,a);return{position:K+1,total:V}},async rankBefore(e,t,s){if(ie(e))throw new $("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const f=i.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);const h=f.rankIndexes?.find(p=>p.name===t);if(!h)throw new $("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(s.restrictsCounts)throw new tt(e);C(e,O),Ye(e,h);const l=Dt(e,h.name),a=h.sortBy.map((p,T)=>kt(T)),u=h.sortBy.map((p,T)=>ae(s.sortValues[T]??null));return Xt(d,l,a,h.sortBy,s.partitionKey,u,s.rowId)},async rankPage(e,t,s={}){ot(N(s.baseWhere,s.where),i,e,"rankPage");const f=Q(e,"rankPage");if(f)return C(e,O),f.rankPage(e,t,s);ne(e,t,"rank");const{continueCursor:h,hasMore:l,rows:a}=xt(At,e,t,s);return{continueCursor:h,isDone:!l,page:a.map(u=>u.doc)}},async rankPageRows(e,t,s={}){ot(N(s.baseWhere,s.where),i,e,"rankPage"),ne(e,t,"rank");const{directions:f,hasMore:h,rows:l}=xt(At,e,t,s);return{directions:f,hasMore:h,rows:l}},async restore(e,t){const s=se(e,t);if(!s){const l=$e(t);if(l?.restore){await l.restore(e,t);return}throw new $("NOT_FOUND",`document not found: ${e}`)}const f=i.tables[s.tableName]?.softDeleteMode?.field;if(!f)throw new $("INTERNAL",`ctx.db.restore: table "${s.tableName}" is not a .softDelete() table`);const h=s.row[f]!==null&&s.row[f]!==void 0;await G.patch(e,{[f]:null},t),h&&ye(s.tableName,e,void 0,s.row)},async replace(e,t,s,f){const h=se(e,s);if(!h){const W=$e(s);if(W){y(t),await W.replace(e,t,s,f);return}throw new $("NOT_FOUND",`document not found: ${e}`)}const{docJson:l,row:a,tableName:u}=h,p=i.tables[u];if(!p)throw new $("INTERNAL",`unknown table: ${u}`);Jt("replace",t);const T=f?.allowExplicitId&&typeof t._creationTime=="number"?t._creationTime:void 0,E=typeof a._creationTime=="number"?a._creationTime:void 0,k=T??E??L(),S={...t,...g(u),_creationTime:k,_id:e};zt(p,t,S,re),rt(p,S),Z(u,"before","update")&&await ee("before","update",{doc:{...S},id:e,op:"update",previous:a,table:u}),pe(u),ge(u),Ge(d,u,Mo(u),[k,de(S),e,l]),Me(u,e,S,a),be(u,e,S),xe(u,a,S),ye(u,e,a,S),D?.invalidate(u,e,b(u,a,S)),we(u,e,"update",S),w({indexKeys:b(u,a,S),key:e,op:"update",row:S,table:u}),Z(u,"after","update")&&await ee("after","update",{doc:S,id:e,op:"update",previous:a,table:u}),await A({doc:S,id:e,op:"update",table:u})},async wipeShard(e){const t=new Set(e?.exclude),s=e?.tables,f=Object.entries(i.tables).filter(([u,p])=>t.has(u)||s!==void 0&&!s.includes(u)?!1:p.shardMode?.kind!=="global").map(([u])=>u);if(s!==void 0){for(const u of s)if(!i.tables[u])throw new $("INTERNAL",`wipeShard: unknown table: ${u}`)}const h={};let l=0;const{deleteAll:a}=G;if(a===void 0)throw new $("INTERNAL","wipeShard: this writer has no deleteAll");for(const u of f){const p=await a(u,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});h[u]=p.deleted,l+=p.deleted}return{deleted:l,tables:h}}},$n={db:G,scheduler:he};return n.enforceRls===!0?io(G,i,(e,t)=>se(e,t)?.tableName,(e,t)=>yn(e,t),_):G};export{Qr as CDC_LOG_TABLE,ui as CLIENT_WATERMARK_TABLE,gi as GLOBAL_SHAPE_SNAPSHOT_TABLE,Ri as IDEMPOTENCY_TABLE,Jo as NotUniqueError,bi as SEARCH_STATE_TABLE,fi as advanceClientWatermark,Vr as applyCdcChanges,Jt as assertNoExplicitUndefined,Wo as assertValidClientId,Or as backfillAggregateIndexes,Nr as backfillRankIndexes,jr as backfillSearchIndexes,zr as bumpCdcEpoch,Jr as cdcCanVouchFor,Yr as cdcForkedError,Xr as cdcSeqLeavingRows,Zr as cdcTouchesTables,ei as cdcTrimmedError,ti as compactCdcDocs,Ur as createShardCtxDb,ni as cursorBelowRetainedFloor,yi as deleteGlobalShapeSnapshot,$i as deleteGlobalShapeSnapshotsForConnection,hi as migrateClientWatermark,Ei as migrateGlobalShapeSnapshot,oi as minCdcReplayableSeq,ri as minCdcSeq,Qt as normalizeIdStructurally,ii as readCdcChangeKeys,si as readCdcChanges,ci as readCdcCursor,ai as readCdcEpoch,wi as readClientWatermark,mi as readGlobalShapeSnapshot,Ti as readIdempotent,Ci as runShardMigrations,Di as selectShapeMembers,ki as selectShapeRows,st as stripReservedPatchFields,di as trimCdcChanges,vi as trimIdempotent,Si as writeGlobalShapeSnapshot,Ai as writeIdempotent};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as c}from"@lunora/errors";import{sql as t}from"drizzle-orm";import{MySqlDialect as S}from"drizzle-orm/mysql-core";import{PgDialect as p}from"drizzle-orm/pg-core";import{SQLiteSyncDialect as u}from"drizzle-orm/sqlite-core";const f=new p,m=new S,L=new u,d={mysql:m,postgres:f,sqlite:L},l={boundParams:100,compoundSelect:5,likePattern:50,sqlTextLength:1e5},h=l.boundParams/2,E=e=>e===null||typeof e=="boolean"?!0:typeof e=="number"?Number.isFinite(e):typeof e=="string"&&e.isWellFormed(),D=(e,n)=>{const{params:r,sql:o}=d[e].sqlToQuery(n);return{params:r,sql:o}},I=e=>t`${e}`,N=e=>{if(e.length===0)throw new Error("unionAll: expected at least one branch");let n=[...e];for(;n.length>l.compoundSelect;){const r=[];for(let o=0;o<n.length;o+=l.compoundSelect){const s=t.join(n.slice(o,o+l.compoundSelect),t` UNION ALL `);r.push(t`SELECT * FROM (${s}) ${t.identifier("__u__")}`)}n=r}return t.join(n,t` UNION ALL `)},w=(e,n,r,o=h)=>{const s=r?t` NOT IN `:t` IN `,a=n.every(i=>E(i));if(n.length>o&&!a)throw new c("BAD_REQUEST",`an "in" list of ${String(n.length)} values holds a value JSON cannot carry (bytes, a non-finite number, or malformed text), so it cannot be bound as one parameter — and ${String(n.length)} placeholders exceed SQLite's per-statement cap of 100 on Durable Objects and D1. Narrow the list to ${String(o)} values or fewer.`);return n.length<=o?t`${e}${s}(${t.join(n.map(i=>I(i)),t`, `)})`:t`${e}${s}(SELECT ${t.identifier("value")} FROM json_each(${JSON.stringify(n)}))`};export{l as WORKERD_SQLITE_LIMITS,E as isJsonSafe,I as param,D as renderSql,w as sqliteInList,N as unionAll};
|
|
@@ -1,19 +0,0 @@
|
|
|
1
|
-
import{sql as e}from"drizzle-orm";import{runDrizzle as E}from"./runDrizzle-BlpM0R9P.mjs";const a="__stream_runs",o="__stream_chunks",N=r=>{E(r,e`CREATE TABLE IF NOT EXISTS ${e.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(r,e`CREATE TABLE IF NOT EXISTS ${e.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
|
-
)`)},_=(r,t)=>{const s=E(r,e`SELECT status, last_seq, error_code, error, started_at FROM ${e.identifier(a)} WHERE run_key = ${t} LIMIT 1`).toArray()[0];if(s!==void 0)return{...s.error===null?{}:{error:s.error},...s.error_code===null?{}:{errorCode:s.error_code},lastSeq:s.last_seq,startedAt:s.started_at,status:s.status}},i=(r,t)=>{E(r,e`DELETE FROM ${e.identifier(o)} WHERE run_key = ${t}`)},S=(r,t,n,s)=>_(r,t)!==void 0?!1:(i(r,t),E(r,e`INSERT INTO ${e.identifier(a)} (run_key, status, last_seq, started_at, ttl_ms)
|
|
15
|
-
VALUES (${t}, ${"running"}, 0, ${n}, ${s})`),!0),m=(r,t)=>{i(r,t),E(r,e`DELETE FROM ${e.identifier(a)} WHERE run_key = ${t}`)},$=(r,t,n,s)=>{E(r,e`INSERT OR IGNORE INTO ${e.identifier(o)} (run_key, seq, data_json) VALUES (${t}, ${n}, ${s})`)},c=(r,t,n)=>E(r,e`SELECT seq, data_json FROM ${e.identifier(o)} WHERE run_key = ${t} AND seq > ${n} ORDER BY seq ASC`).toArray().map(s=>({dataJson:s.data_json,seq:s.seq})),A=(r,t,n,s,T)=>{if(_(r,t)===void 0){i(r,t);return}const d=T?.code??null,R=T?.message??null;E(r,e`UPDATE ${e.identifier(a)}
|
|
16
|
-
SET status = ${n}, last_seq = ${s}, error_code = ${d}, error = ${R}
|
|
17
|
-
WHERE run_key = ${t}`)},O=(r,t)=>{E(r,e`DELETE FROM ${e.identifier(o)} WHERE run_key IN (
|
|
18
|
-
SELECT run_key FROM ${e.identifier(a)} WHERE started_at + ttl_ms < ${t}
|
|
19
|
-
)`),E(r,e`DELETE FROM ${e.identifier(a)} WHERE started_at + ttl_ms < ${t}`)};export{o as STREAM_CHUNKS_TABLE,a as STREAM_RUNS_TABLE,$ as appendStreamChunk,S as claimStreamRun,m as deleteStreamRun,A as finishStreamRun,N as migrateDurableStreams,c as readStreamChunks,_ as readStreamRun,O as trimStreamRuns};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import"./WORKERD_SQLITE_LIMITS-DlozcSQu.mjs";import{c as o,l as t}from"./where-sql-BV8Kg4_B.mjs";import"./RELATION_EXISTS_KEY-CFUhnZSZ.mjs";export{o as compileWhereSql,t as literalInList};
|
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
import{d as p,e as S}from"./wire-codec-C-FpWm52.mjs";import{cursorBelowRetainedFloor as y}from"./CDC_LOG_TABLE-Bkv7JskR.mjs";import{envPositiveInt as v}from"./envOptionalPositiveInt-D2pY-c64.mjs";import{v as A,R as g,s as N,a as E,b as T}from"./sibling-channel-BkL5cTCc.mjs";const L=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"],O=new Set(L),b=s=>typeof s=="string"&&O.has(s),h="::replica::",R=s=>{const e=s.lastIndexOf(h);if(e===-1)return;const t=s.slice(0,e),r=s.slice(e+h.length);if(!(t.length===0||!b(r)))return{ownerKey:t,region:r}},I=s=>{if(s==null||!/^\d+$/.test(s))return;const e=Number.parseInt(s,10);return Number.isSafeInteger(e)&&e>0?e:void 0},m=1e3,w=1e3,C=10,U=5e4,F=s=>v(s,"LUNORA_REPLICA_MAX_BOOTSTRAP_ROWS",U),d="__replica_state",l=new WeakSet,_=s=>{l.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
|
-
)`),l.add(s))},c=s=>(_(s),s.exec(`SELECT epoch, applied_seq AS appliedSeq, synced_at AS syncedAtMs FROM ${d} WHERE id = 1`).toArray()[0]),f=(s,e)=>{_(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)},q=s=>{const e=s.doName();if(e!==void 0&&R(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(E(s.env())===void 0)return new Response("replica control requires LUNORA_RELAY_SECRET",{status:403})},a=s=>Response.json(S(s)),P=async(s,e)=>{if(s.rowCount()>F(s.env()))return a({cursor:0,epoch:e,rows:[],truncated:!0});const t=s.ownerCursor()??0,r=await s.exportRows();return a({cursor:t,epoch:e,rows:r})},x=(s,e,t)=>{const r=s.ownerFloor();if(y(r,t))return a({changes:[],cursor:s.ownerCursor()??t,epoch:e,floor:r});const o=s.ownerCursor()??0;if(t>o)return a({changes:[],cursor:o,epoch:e,...r===void 0?{}:{floor:r}});const{changes:n,cursor:i}=s.readChanges(t,w);return a({changes:n,cursor:i,epoch:e,...r===void 0?{}:{floor:r}})},K=async(s,e)=>{const t=q(s);if(t!==void 0)return t;const r=s.ownerEpoch();let o;try{o=await e.text()}catch{return new Response("bad request",{status:400})}if(!await A(s.env(),e.headers.get(g),o))return new Response("forbidden",{status:403});let n;try{n=JSON.parse(o)}catch{return new Response("bad request",{status:400})}if(n.type==="replica_bootstrap")return P(s,r);if(n.type==="replica_pull"){const i=typeof n.sinceSeq=="number"&&Number.isInteger(n.sinceSeq)&&n.sinceSeq>=0?n.sinceSeq:0;return x(s,r,i)}return new Response("unknown replica frame",{status:400})};class M{constructor(e,t,r){this.host=e,this.ownerKey=t,this.region=r}host;ownerKey;region;divergent=!1;inFlight;async ensureFresh(e){if(this.divergent)return"unavailable";if(this.isCaughtUp(e))return"fresh";this.inFlight??=this.advance(e).finally(()=>{this.inFlight=void 0});const 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 r=await this.bootstrap();if(r===void 0)return"unavailable";t=r}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 r=e;for(let o=0;o<C;o+=1){const n=await this.pull(r.appliedSeq);if(n===void 0)return t===void 0&&this.isFreshEnough(r,void 0)?"fresh":"unavailable";if(this.hasDiverged(r,n))return"unavailable";const i=n.changes.length<w;if(r=await this.applyPage(n),i||this.isFreshEnough(r,t))return this.isFreshEnough(r,t)?"fresh":"stale"}return this.isFreshEnough(r,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 f(this.host.sql(),t),t}hasDiverged(e,t){const r=t.changes.length===0&&t.cursor>e.appliedSeq,o=t.floor??(r?t.cursor:0),n=o>0&&o>e.appliedSeq+1,i=t.cursor<e.appliedSeq;return t.epoch===e.epoch&&!n&&!i?!1:(this.divergent=!0,!0)}async bootstrap(){const e=await this.request({type:"replica_bootstrap"});if(e===void 0)return;const t=p(await e.json());if(t.truncated===!0){this.divergent=!0;return}const{errors:r}=await this.host.importRows(t.rows);if(r.length>0){this.divergent=!0;return}const o={appliedSeq:t.cursor,epoch:t.epoch,syncedAtMs:Date.now()};return f(this.host.sql(),o),o}isFreshEnough(e,t){return t!==void 0?e.appliedSeq>=t:Date.now()-e.syncedAtMs<=v(this.host.env(),"LUNORA_REPLICA_MAX_STALENESS_MS",m)}async pull(e){const t=await this.request({sinceSeq:e,type:"replica_pull"});return t===void 0?void 0:p(await t.json())}async request(e){const t=this.host.shardBinding(),r=N(this.host.env(),t,this.ownerKey,this.host.shardJurisdiction());if(r===void 0)return;const o=JSON.stringify(e),n={"content-type":"application/json","x-lunora-shard-binding":t??""},i=E(this.host.env());i!==void 0&&(n[g]=await T(i,o));try{const u=await r.fetch("https://replica.internal/_lunora/replica",{body:o,headers:n,method:"POST"});return u.ok?u:void 0}catch{return}}}const j=s=>{const e=s.doName();if(e===void 0)return;const t=R(e);return t===void 0?void 0:new M(s,t.ownerKey,t.region)},G=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 r=await s.ensureFresh(I(e.headers.get("x-lunora-min-seq")));if(r!=="fresh")return Response.json({error:{code:"REPLICA_NOT_READY",message:`replica is ${r} for this read`}},{headers:{"x-lunora-replica-fallback":r},status:421})};export{j as createReplicaLink,G as gateReplicaDispatch,K as handleReplicaControl};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as T}from"@lunora/errors";import{sql as l}from"drizzle-orm";import{sqliteInList as R,isJsonSafe as $,WORKERD_SQLITE_LIMITS as L}from"./WORKERD_SQLITE_LIMITS-DlozcSQu.mjs";import{quoteIdentifier as m}from"./quoteIdentifier-CObIFRhb.mjs";import{RELATION_EXISTS_KEY as I}from"./RELATION_EXISTS_KEY-CFUhnZSZ.mjs";const x={binary:(n,t,o)=>l`${n} ${l.raw(t)} ${o}`,constant:n=>n?l`1 = 1`:l`0 = 1`,connect:(n,t,o)=>l`(${n}) ${l.raw(o)} (${t})`,contains:(n,t)=>l`instr(lower(${n}), lower(${t})) > 0`,inList:(n,t,o,s)=>R(n,t,o,s),negate:n=>l`NOT (${n})`,nullCheck:(n,t)=>t?l`${n} IS NOT NULL`:l`${n} IS NULL`,value:n=>l`${n}`},p=(...n)=>{let t="";const o=[];for(const s of n)typeof s=="string"?t+=s:(t+=s.text,o.push(...s.params));return{params:o,text:t}},h=n=>({params:[n],text:"?"}),S=n=>({params:[],text:n}),Q=n=>S(m(n)),G={binary:(n,t,o)=>p(n," ".concat(t," "),h(o)),constant:n=>S(n?"1 = 1":"0 = 1"),connect:(n,t,o)=>p("(",n,") ".concat(o," ("),t,")"),contains:(n,t)=>p("instr(lower(",n,"), lower(",t,")) > 0"),inList:(n,t,o,s)=>{const i=o?" NOT IN ":" IN ";if(t.length>s&&!t.every(r=>$(r)))throw new T("BAD_REQUEST",`an "in" list of ${String(t.length)} values holds a value JSON cannot carry (bytes, a non-finite number, or malformed text), so it cannot be bound as one parameter — and ${String(t.length)} placeholders exceed SQLite's per-statement cap of 100 on Durable Objects and D1. Narrow the list to ${String(s)} values or fewer.`);if(t.length<=s){const r=[n,i,"("];for(const[e,c]of t.entries())e>0&&r.push(", "),r.push(h(c));return r.push(")"),p(...r)}return p(n,i,'(SELECT "value" FROM json_each(',h(JSON.stringify(t)),"))")},negate:n=>p("NOT (",n,")"),nullCheck:(n,t)=>p(n,t?" IS NOT NULL":" IS NULL"),value:h},_=L.boundParams/2,E=["eq","ne","lt","lte","gt","gte","in","notIn","isNull","contains"],j=new Set(E),w={eq:"=",gt:">",gte:">=",lt:"<",lte:"<=",ne:"<>"},b=n=>{if(n===null||typeof n!="object"||Array.isArray(n))return!1;const t=Object.keys(n);return t.length>0&&t.every(o=>j.has(o))},y=(n,t,o,s,i)=>{const r=i.value(s.serialize(o,n));return s.containsExpr?s.containsExpr(t,r):i.contains(t,r)},C=(n,t,o,s,i,r,e)=>i===null?o==="eq"||o==="ne"?e.nullCheck(t,o==="ne"):e.constant(!1):e.binary(t,s,r.serialize(i,n)),D=(n,t,o,s,i,r)=>{if(!Array.isArray(s))throw new T("BAD_REQUEST",`\`${o==="IN"?"in":"notIn"}\` on "${n}" expects an array of values, received ${s===null?"null":typeof s}`);const e=s;if(e.length===0)return r.constant(o==="NOT IN");const c=e.map(u=>i.serialize(u,n)),a=o==="NOT IN";return i.inList?i.inList(t,c,a):r.inList(t,c,a,_)},J=(n,t,o)=>{const s=l.join(t.map(i=>l`${i}`),l`, `);return o?l`${n} NOT IN (${s})`:l`${n} IN (${s})`},U=(n,t,o,s,i)=>{const r=o,e=[];for(const c of E){if(!(c in r))continue;const a=r[c],u=w[c];u?e.push(C(n,t,c,u,a,s,i)):c==="isNull"?e.push(i.nullCheck(t,!a)):c==="contains"?e.push(y(n,t,a,s,i)):e.push(D(n,t,c==="in"?"IN":"NOT IN",a,s,i))}return e},k=(n,t,o,s)=>{const i=o.fieldRef(n);return b(t)?U(n,i,t,o,s):t===null?[s.nullCheck(i,!1)]:[s.binary(i,"=",o.serialize(t,n))]},f=(n,t,o)=>{if(n.length<=1)return n[0];const s=Math.floor(n.length/2);return o.connect(f(n.slice(0,s),t,o),f(n.slice(s),t,o),t)},M=(n,t,o,s)=>{const i=Array.isArray(n)?n:[],r=[];for(const e of i){const c=N(e??{},o,s);if(c!==void 0)r.push(c);else if(t==="OR")return}return r.length===0?t==="OR"?s.constant(!1):void 0:f(r,t,s)},P=new Set(["AND","NOT","OR",I]),q=(n,t,o,s)=>{if(n===I){if(!o.relationExists)throw new T("INTERNAL","encountered a relation EXISTS marker without a relationExists strategy hook");return o.relationExists(t)}if(n==="NOT"){const i=N(t??{},o,s);return i===void 0?s.constant(!1):s.negate(i)}return M(t,n,o,s)},N=(n,t,o)=>{const s=[];for(const[i,r]of Object.entries(n))if(P.has(i)){const e=q(i,r,t,o);e!==void 0&&s.push(e)}else s.push(...k(i,r,t,o));return f(s,"AND",o)},v=L.boundParams/2,A=n=>{let t=0,o=0;const s=i=>{const r=A(i);t+=r.lists,o+=r.scalars};if(Array.isArray(n)){for(const i of n)s(i);return{lists:t,scalars:o}}if(n===null||typeof n!="object")return{lists:t,scalars:o};for(const[i,r]of Object.entries(n))i==="in"||i==="notIn"?t+=1:i==="AND"||i==="NOT"||i==="OR"||b(r)?s(r):o+=1;return{lists:t,scalars:o}},W=(n,t,o=x,s=0)=>{if(!n||Object.keys(n).length===0)return;const{lists:i,scalars:r}=A(n);if(i===0)return N(n,t,o);const e=Math.max(1,Math.floor(Math.min(v,L.boundParams-r-s)/i)),c=t.inList??((a,u,O,d)=>o.inList(a,u,O,d??e));return N(n,{...t,inList:(a,u,O)=>c(a,u,O,e)},o)};export{W as c,Q as i,p as j,J as l,S as r,G as t};
|