@lunora/shard-engine 1.0.0-alpha.150 → 1.0.0-alpha.152
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.mjs +1 -1
- package/dist/packem_shared/{ADMIN_FUNCTIONS-B0QCN3HM.mjs → ADMIN_FUNCTIONS-Cug8Z4jD.mjs} +1 -1
- package/dist/packem_shared/{AGG_COUNT-CBe5drFS.mjs → AGG_COUNT-Ctb5Pnyl.mjs} +1 -1
- package/dist/packem_shared/{AUDIT_LOG_TABLE-CuIP7PJ0.mjs → AUDIT_LOG_TABLE-BFJ65SRS.mjs} +1 -1
- package/dist/packem_shared/{CDC_LOG_TABLE-DsCz-DAV.mjs → CDC_LOG_TABLE-C7o2xrt1.mjs} +1 -1
- package/dist/packem_shared/{CLIENT_WATERMARK_TABLE-_CkdMnT2.mjs → CLIENT_WATERMARK_TABLE-De7z_OHV.mjs} +1 -1
- package/dist/packem_shared/{COMMIT_SEQ_FIELD-BcUO15fR.mjs → COMMIT_SEQ_FIELD-Da1DjGqo.mjs} +1 -1
- package/dist/packem_shared/{DATA_MIGRATION_STATE_TABLE-CmsAKy5V.mjs → DATA_MIGRATION_STATE_TABLE-D1FtktFp.mjs} +1 -1
- package/dist/packem_shared/{DEFAULT_MAX_RELATION_KEYS-CHqKygxx.mjs → DEFAULT_MAX_RELATION_KEYS-BeTWZQ4X.mjs} +1 -1
- package/dist/packem_shared/{DEFAULT_MAX_RELAYS-B44xKIiR.mjs → DEFAULT_MAX_RELAYS-CrsP5Ldh.mjs} +1 -1
- package/dist/packem_shared/{DurableStreamRunner-Dzge_ywD.mjs → DurableStreamRunner-MMlV5qKQ.mjs} +1 -1
- package/dist/packem_shared/{GLOBAL_SHAPE_SNAPSHOT_TABLE-Du0PbPdS.mjs → GLOBAL_SHAPE_SNAPSHOT_TABLE-Bb6-aZuH.mjs} +1 -1
- package/dist/packem_shared/{IDEMPOTENCY_TABLE-CymJf4r0.mjs → IDEMPOTENCY_TABLE-COrgeP3O.mjs} +1 -1
- package/dist/packem_shared/{MAIL_RETENTION-BP1GSXQ0.mjs → MAIL_RETENTION-DMolrLYt.mjs} +1 -1
- package/dist/packem_shared/{NotUniqueError-CStpuQeL.mjs → NotUniqueError-BR7jasrr.mjs} +1 -1
- package/dist/packem_shared/{QUEUE_TABLE-jEc6-2wm.mjs → QUEUE_TABLE-C-goXtGd.mjs} +1 -1
- package/dist/packem_shared/{REACTOR_STATE_TABLE-DHaBP_vb.mjs → REACTOR_STATE_TABLE-D2Mn204f.mjs} +1 -1
- package/dist/packem_shared/{SCHEDULE_OUTBOX_TABLE-C_Me442c.mjs → SCHEDULE_OUTBOX_TABLE-DcZI7Yhl.mjs} +1 -1
- package/dist/packem_shared/{SCHEMA_HISTORY_MAX_VERSIONS-SQVxBlum.mjs → SCHEMA_HISTORY_MAX_VERSIONS-CEwFjj-O.mjs} +1 -1
- package/dist/packem_shared/{SEARCH_STATE_TABLE-BThmEiED.mjs → SEARCH_STATE_TABLE-nYN2eKs_.mjs} +1 -1
- package/dist/packem_shared/{SHAPE_POKE_CURSOR_TABLE-B6MXBH-p.mjs → SHAPE_POKE_CURSOR_TABLE-BGvY3sFI.mjs} +1 -1
- package/dist/packem_shared/{VECTOR_BACKFILL_MAX_PAGES-DY_3FYts.mjs → VECTOR_BACKFILL_MAX_PAGES-zxItOlPE.mjs} +1 -1
- package/dist/packem_shared/WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs +1 -0
- package/dist/packem_shared/{appendStreamChunk-DF_Jrgpy.mjs → appendStreamChunk-BZYgGE9Y.mjs} +1 -1
- package/dist/packem_shared/{applyInsertDefaults-D6AdJUd1.mjs → applyInsertDefaults-vVfUyiJ2.mjs} +1 -1
- package/dist/packem_shared/{archiveCdcSegment-CIiYU1FU.mjs → archiveCdcSegment-Cr8oGLfB.mjs} +1 -1
- package/dist/packem_shared/{backfillAggregateIndexes-Dw4Azd33.mjs → backfillAggregateIndexes-DSplGrR_.mjs} +1 -1
- package/dist/packem_shared/{buildReprojectionMigration-DQV0q3w9.mjs → buildReprojectionMigration-Ds2JaFo7.mjs} +1 -1
- package/dist/packem_shared/{buildShapeDiff-BHr3i1m6.mjs → buildShapeDiff-Dc9TOdHq.mjs} +1 -1
- package/dist/packem_shared/{clearCompanionSignatures-8uVX84aT.mjs → clearCompanionSignatures-3MlVqWZD.mjs} +1 -1
- package/dist/packem_shared/{clearMemoryTables-Lu0S2GOb.mjs → clearMemoryTables-aMRERF0w.mjs} +1 -1
- package/dist/packem_shared/{compileWhereSql-CKoO19by.mjs → compileWhereSql-TgKZIvWM.mjs} +1 -1
- package/dist/packem_shared/{computeRankPage-DLSi_oBt.mjs → computeRankPage-BZIpATcs.mjs} +1 -1
- package/dist/packem_shared/{createCompanionSync-DhYLePyV.mjs → createCompanionSync-BMS8yYTx.mjs} +1 -1
- package/dist/packem_shared/{createReplicaLink-CNRM7GCm.mjs → createReplicaLink-CSbJvezn.mjs} +1 -1
- package/dist/packem_shared/{ctx-db-relay-shapes-CPwELrMf.mjs → ctx-db-relay-shapes-DV0VO4HG.mjs} +1 -1
- package/dist/packem_shared/{ctx-db-search-state-CrTLPmFN.mjs → ctx-db-search-state-FjgzTFok.mjs} +1 -1
- package/dist/packem_shared/{defineEngineContractSuite-CjF5FMMQ.mjs → defineEngineContractSuite-BiXyk2gE.mjs} +1 -1
- package/dist/packem_shared/{do-sql-DqU-17Fs.mjs → do-sql-BWrJQAOh.mjs} +1 -1
- package/dist/packem_shared/{exportShardRows-yxw7vFf9.mjs → exportShardRows-b0pfdTXz.mjs} +1 -1
- package/dist/packem_shared/{fts-companion-DzfEHonU.mjs → fts-companion-CA8mLJWq.mjs} +1 -1
- package/dist/packem_shared/{ftsCompanionDdl-Cka6_-Fm.mjs → ftsCompanionDdl-0y8d4YvE.mjs} +1 -1
- package/dist/packem_shared/{isSoftDeleted-D5MeQSk0.mjs → isSoftDeleted-DXANkomm.mjs} +1 -1
- package/dist/packem_shared/{materializeExternalRows-D2zEvCAa.mjs → materializeExternalRows-rYWz87LR.mjs} +1 -1
- package/dist/packem_shared/{runDrizzle-B2GG3IJa.mjs → runDrizzle-RC09zZrh.mjs} +1 -1
- package/dist/packem_shared/{runShardMigrations-CQou1YrO.mjs → runShardMigrations-CEZTl9LV.mjs} +1 -1
- package/dist/packem_shared/{selectExpiredIds-B8PxwbIr.mjs → selectExpiredIds-DDQyqbLk.mjs} +1 -1
- package/dist/packem_shared/{selectShapeMembers-B1MIaRkE.mjs → selectShapeMembers-BCfKypfN.mjs} +1 -1
- package/dist/packem_shared/{where-sql-DO1vOrhc.mjs → where-sql-BjY4rnqb.mjs} +1 -1
- package/package.json +3 -3
- package/dist/packem_shared/WORKERD_SQLITE_LIMITS-BdNnnMj0.mjs +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createShardCtxDb as _}from"./NotUniqueError-
|
|
1
|
+
import{createShardCtxDb as _}from"./NotUniqueError-BR7jasrr.mjs";import{createRelayLink as I}from"./DEFAULT_MAX_RELAYS-CrsP5Ldh.mjs";import{ConflictError as q}from"./ConflictError-C8GtJmjS.mjs";import{runShardMigrations as E}from"./runShardMigrations-CEZTl9LV.mjs";import{relayName as F}from"./DEFAULT_PROMOTION_THRESHOLDS-B3pRMuqb.mjs";const S=(O,m={})=>({_meta:{column:{notNull:!0,...m}},kind:O}),A=(O,m,x)=>{const{describe:v,expect:d,it:b}=x;v(`engine contract: ${O}`,()=>{v("optimistic concurrency",()=>{const w=u=>({tables:{items:{indexes:[],shape:{title:S("string"),version:S("number",{notNull:!1})},triggerMap:{clobber:{handler:()=>{u.exec(`UPDATE "items" SET "__doc__" = json_set("__doc__", '$.version', 99) WHERE "id" = 'i1'`)},op:"update",timing:"before"}}}}});b("raises a CONFLICT of kind `occ` when a write's snapshot is clobbered",async()=>{const{close:u,host:h}=m();try{const c=h.sql,p=w(c);E(c,p);const s=_({schema:p,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0}),await d(s.patch("i1",{title:"second"})).rejects.toBeInstanceOf(q)}finally{u?.()}}),b("reports the conflict as CONFLICT/409 rather than retrying it away",async()=>{const{close:u,host:h}=m();try{const c=h.sql,p=w(c);E(c,p);const s=_({schema:p,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let a;try{await s.patch("i1",{title:"second"})}catch(t){a=t}const e=a;d(e.code).toBe("CONFLICT"),d(e.kind).toBe("occ")}finally{u?.()}}),b("leaves the row readable and unchanged after a conflict",async()=>{const{close:u,host:h}=m();try{const c=h.sql,p=w(c);E(c,p);const s=_({schema:p,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});try{await s.patch("i1",{title:"second"})}catch{}const a=await s.get("i1");d(a?.title).toBe("first"),d(a?.version).toBe(99)}finally{u?.()}}),b("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 c=h.sql,p={tables:{items:{indexes:[],shape:{title:S("string"),version:S("number",{notNull:!1})},triggerMap:{recurse:{handler:async(t,o)=>{await t.db.patch(o.doc._id,{version:99})},op:"update",timing:"before"}}}}};E(c,p);const s=_({schema:p,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let a;try{await s.patch("i1",{title:"second"})}catch(t){a=t}const e=a;d(e).toBeInstanceOf(q),d(e.code).toBe("CONFLICT"),d(e.kind).toBe("trigger")}finally{u?.()}})}),v("shape-poke ordering",()=>{const w="shard-a",u={args:{},name:"messages"},h=(e,t,o,n)=>e.accept(t?.()??{},{connectionId:o,shapes:{[n]:u}}),c=(e,t,o)=>{let n=0,l=0;const r=k=>()=>{throw new Error(`the relay poke path must not reach RelayHost.${k}`)},i={fetch:(k,C)=>{if(JSON.parse(C?.body??"{}").type!=="relay_shape_subscribe")return Promise.resolve(new Response(void 0,{status:204}));const N=o[l];if(l+=1,N===void 0)throw new Error("the relay asked for more seeds than this fixture supplies");return Promise.resolve(Response.json(N))}},f={get:()=>i,getByName:()=>i,idFromName:k=>k},g={buildShapeDiff:r("buildShapeDiff"),computeOpLogShapeSeed:r("computeOpLogShapeSeed"),currentCdcEpoch:r("currentCdcEpoch"),deliverWhisperLocal:r("deliverWhisperLocal"),doName:()=>F(w,0),env:()=>({SHARD:f}),getWebSockets:()=>e.getSockets(),maskMetadata:r("maskMetadata"),nextPokeId:()=>(n+=1,`poke-${String(n)}`),readAttachment:k=>k.deserializeAttachment?.(),recordShapePokeFanout:()=>{},resolveShape:r("resolveShape"),rlsMetadata:r("rlsMetadata"),shardBinding:()=>"SHARD",shardJurisdiction:()=>{},sql:()=>t},y=I(g);if(y===void 0)throw new Error("expected a relay link for a `…::relay::N` name");return y},p=e=>new Request("https://relay.internal/_lunora/relay",{body:JSON.stringify(e),headers:{"content-type":"application/json"},method:"POST"}),s=async(e,t,o)=>{const n=await e.seedRelayShape(t,o,u,{identity:void 0,userId:void 0});if(n!=="ok")throw new Error(`seed failed: ${JSON.stringify(n)}`)},a=(e={})=>p({...u,checkpoint:20,epoch:"e1",fromCursor:10,rowsPatch:[{id:"r1",op:"upsert",value:{title:"hello"}}],type:"relay_shape_poke",...e});b("frames a poke as pokeStart → pokePart per shape → pokeEnd, under one poke id",async()=>{const{close:e,createSocket:t,host:o,readFrames:n,sockets:l}=m();try{const r=c(l,o.sql,[{cursor:10,epoch:"e1",frames:[]}]),i=h(l,t,"c-alice","s1");await s(r,i,"s1"),await r.handleControl(a());const g=(await n(i)).map(y=>JSON.parse(y));d(g.map(y=>y.type)).toStrictEqual(["pokeStart","pokePart","pokeEnd"]),d(new Set(g.map(y=>y.pokeId)).size).toBe(1),d(g[1]?.shapeId).toBe("s1"),d(g[2]?.checkpoint).toBe(20)}finally{e?.()}}),b("delivers a poke only to sockets whose cursor matches, and advances them past it",async()=>{const{close:e,createSocket:t,host:o,readFrames:n,sockets:l}=m();try{const r=c(l,o.sql,[{cursor:10,epoch:"e1",frames:[]},{cursor:7,epoch:"e1",frames:[]}]),i=h(l,t,"c-alice","s1"),f=h(l,t,"c-bob","s2");await s(r,i,"s1"),await s(r,f,"s2"),await r.handleControl(a());const g=await n(i);d(g.length).toBe(3);const y=await n(f);d(y.length).toBe(0),await r.handleControl(a());const k=await n(i);d(k.length).toBe(3)}finally{e?.()}}),b("skips a socket whose cursor matches under a different CDC epoch",async()=>{const{close:e,createSocket:t,host:o,readFrames:n,sockets:l}=m();try{const r=c(l,o.sql,[{cursor:10,epoch:"e1",frames:[]}]),i=h(l,t,"c-alice","s1");await s(r,i,"s1"),await r.handleControl(a({epoch:"e2"}));const f=await n(i);d(f.length).toBe(0),await r.handleControl(a());const g=await n(i);d(g.length).toBe(3)}finally{e?.()}})}),v("orderBy null placement",()=>{const w=[["a",void 0],["b",3],["c",void 0],["d",1],["e",void 0],["f",3],["g",2],["h",void 0]],u=[{nulls:"first",sort:"asc"},{nulls:"last",sort:"asc"},{nulls:"first",sort:"desc"},{nulls:"last",sort:"desc"}],h=({nulls:p,sort:s})=>{const a=new Map(w.map(([t],o)=>[t,o])),e=s==="asc"?1:-1;return w.toSorted(([t,o],[n,l])=>o!==l?o===void 0?p==="first"?-1:1:l===void 0?p==="first"?1:-1:(o-l)*e:((a.get(t)??0)-(a.get(n)??0))*e).map(([t])=>t)},c=p=>p.map(s=>String(s.label));b("pages every placement in threes with no row skipped or repeated",async()=>{const{close:p,host:s}=m();try{const a=s.sql,e=u.map((r,i)=>`items_${String(i)}`),t={label:S("string"),score:S("number",{notNull:!1})},o={tables:Object.fromEntries(e.map(r=>[r,{indexes:[{fields:["score"],name:"by_score"}],shape:t}]))};E(a,o);let n=17e11;const l=_({clock:()=>(n+=1e3,n),schema:o,sql:a});for(const r of e)for(const[i,f]of w)await l.insert(r,f===void 0?{label:i}:{label:i,score:f});for(const[r,i]of u.entries()){const f=e[r]??"",g=await l.findMany(f,{orderBy:[{score:i}]});d(c(g.page)).toStrictEqual(h(i));const y=[];let k;for(let C=0;C<w.length+2;C+=1){const B=await l.findMany(f,{cursor:k,limit:3,orderBy:[{score:i}]});if(y.push(...c(B.page)),B.isDone)break;k=B.continueCursor}d(y).toStrictEqual(h(i))}}finally{p?.()}})}),v("RLS identity under live subscription",()=>{const w="shard-a",u={args:{},name:"lobby-messages"},h={args:{},name:"my-orders"},c=s=>{const a=[],e=[],t={fetch:(l,r)=>(a.push(JSON.parse(r?.body??"{}")),Promise.resolve(new Response(void 0,{status:204})))},n=I({buildShapeDiff:()=>[{id:"r1",op:"upsert",value:{}}],computeOpLogShapeSeed:()=>({baseCheckpoint:void 0,cursor:10,epoch:"e1",reset:!0,rowsPatch:[]}),currentCdcEpoch:()=>"e1",deliverWhisperLocal:()=>0,doName:()=>w,env:()=>({SHARD:{get:()=>t,getByName:()=>t,idFromName:l=>l}}),getWebSockets:()=>[],maskMetadata:()=>({columns:[]}),nextPokeId:()=>"poke-1",readAttachment:()=>({}),recordShapePokeFanout:()=>{},resolveShape:(l,r,i)=>(e.push(i),l===h.name?{columns:["id"],effectiveWhere:{org:i?.identity?.org??"anonymous"},global:!1,table:"orders"}:{columns:["id"],effectiveWhere:{room:"lobby"},global:!1,table:"messages"}),rlsMetadata:()=>({policies:[]}),shardBinding:()=>"SHARD",shardJurisdiction:()=>{},sql:()=>s});if(n===void 0)throw new Error("expected an owner link for an un-suffixed DO name");return{owner:n,posts:a,resolvedUnder:e}},p=async(s,a)=>{await s.handleControl(new Request("https://owner.internal/_lunora/relay",{body:JSON.stringify({...a,connectionId:"c-alice",identity:{org:"acme"},relayIndex:0,subId:"s1",type:"relay_shape_subscribe",userId:"u1"}),headers:{"content-type":"application/json"},method:"POST"}))};b("seeds a subscriber under its own forwarded identity, never the anonymous one",async()=>{const{close:s,host:a}=m();try{const{owner:e,resolvedUnder:t}=c(a.sql);await p(e,h),d(t.some(o=>o?.userId==="u1"&&o.identity?.org==="acme")).toBe(!0)}finally{s?.()}}),b("routes an identity-scoped shape to a per-socket poke, not the cohort multicast",async()=>{const{close:s,host:a}=m();try{const{owner:e,posts:t}=c(a.sql);await p(e,h),t.length=0,await e.onFlush(new Set(["orders"]),20);const o=t.filter(n=>n.type==="relay_shape_poke");d(o.length).toBe(1),d(o[0]?.targetConnectionId).toBe("c-alice")}finally{s?.()}}),b("still multicasts an identity-blind shape to the whole cohort",async()=>{const{close:s,host:a}=m();try{const{owner:e,posts:t}=c(a.sql);await p(e,u),t.length=0,await e.onFlush(new Set(["messages"]),20);const o=t.filter(n=>n.type==="relay_shape_poke");d(o.length).toBe(1),d(o[0]?.targetConnectionId).toBeUndefined()}finally{s?.()}})})})};export{A as defineEngineContractSuite};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as c}from"@lunora/errors";import{decodeWire as T,needsWireEncoding as h,encodeWire as A}from"@lunora/wire";import{sql as o}from"drizzle-orm";import{e as $}from"./effective-kind-BmG_zCAy.mjs";import{S as O,i as g,s as y,F as N}from"./json-field-path-DeJW4U9z.mjs";import{quoteIdentifier as b}from"./quoteIdentifier-CObIFRhb.mjs";import{runDrizzle as f}from"./runDrizzle-
|
|
1
|
+
import{LunoraError as c}from"@lunora/errors";import{decodeWire as T,needsWireEncoding as h,encodeWire as A}from"@lunora/wire";import{sql as o}from"drizzle-orm";import{e as $}from"./effective-kind-BmG_zCAy.mjs";import{S as O,i as g,s as y,F as N}from"./json-field-path-DeJW4U9z.mjs";import{quoteIdentifier as b}from"./quoteIdentifier-CObIFRhb.mjs";import{runDrizzle as f}from"./runDrizzle-RC09zZrh.mjs";import{serializeSqlValue as I}from"./serializeSqlValue-DeoBMpZ2.mjs";import{sqlComparableProjection as j}from"./BIGINT_KEY_DIGITS-DE6yshOt.mjs";const L=/^[A-Za-z_$][\w$]*$/u,d=e=>L.test(e)?e:`"${e.replaceAll("\\",String.raw`\\`).replaceAll('"',String.raw`\"`)}"`,l="__doc__",i="__originals__",X=e=>{if(Object.hasOwn(e,i))throw new c("BAD_REQUEST",`"${i}" is reserved by the row store's document encoding and cannot be used as a field name — rename the field`);let t,r;for(const[s,a]of Object.entries(e)){const _=j(a);_!==void 0&&(t??={...e},r??=Object.create(null),t[s]=_,r[s]=a)}t&&r&&(t[i]=r);const n=t??e;try{return h(n)?JSON.stringify(A(n)):JSON.stringify(n)}catch(s){throw new c("BAD_REQUEST",`this document cannot be stored: ${s instanceof Error?s.message:String(s)}`)}},w=e=>{const t=T(JSON.parse(e)),r=t[i];if(r===null||typeof r!="object"||Array.isArray(r))return t;const n={...t};return delete n[i],{...n,...r}},Y=(e,t)=>`${e}__geo_${t}`,D=e=>{try{return y(e)}catch(t){throw t instanceof N?new c("VALIDATION_ERROR",t.message):t}},S=e=>`'$.${(g(e)?D(e).map(r=>d(r)).join("."):d(e)).replaceAll("'","''")}'`,E=(e,t)=>t==="_id"||t==="id"?`${e}id`:t==="_creationTime"?`${e}_creationTime`:`json_extract(${e}${l}, ${S(t)})`,P=e=>E("",e),C=(e,t)=>`NULLIF(json_type(${l}, ${S(e)}), 'null') IN (${O[t]})`,R=e=>o.raw(P(e)),U=(e,t)=>o.raw(C(e,t)),G=(e,t)=>E(`${b(e)}.`,t),x=(e,t)=>o.raw(G(e,t)),H=(e,t,r,n)=>o`CREATE ${n?o`UNIQUE `:o``}INDEX IF NOT EXISTS ${o.identifier(e)} ON ${o.identifier(t)} (${r})`,u=o.identifier("__key__"),q=o.identifier("__value__"),v=o.identifier("__count__"),Z=(e,t,r,n,s)=>o`INSERT INTO ${o.identifier(e)} (${u}, ${q}, ${v}) VALUES (${t}, ${r}, ${n}) ON CONFLICT(${u}) DO UPDATE SET ${s}`,ee=(e,t)=>e===void 0||t!==0&&t!==1||$(e)!=="boolean"?t:t===1,m=new WeakMap,te=e=>{const t=m.get(e);if(t!==void 0)return t;const r=[];for(const[n,s]of Object.entries(e.shape)){const a=s._meta?.column;a&&r.push(Object.freeze([n,a]))}return Object.freeze(r),m.set(e,r),r},F=e=>{if(!e)return;const t=e[l];let r;typeof t=="string"?r=w(t):t&&typeof t=="object"?r=t:r={};const{id:n}=e;typeof n=="string"&&(r._id=n);const s=e._creationTime;return typeof s=="number"&&(r._creationTime=s),r},re=e=>{try{return F(e)}catch{return}},p=new WeakMap,oe=e=>{const t=p.get(e);if(t!==void 0)return t;let r;try{f(e,o`CREATE VIRTUAL TABLE IF NOT EXISTS ${o.identifier("__lunora_fts_probe")} USING fts5(x)`),r=!0}catch{r=!1}finally{try{f(e,o`DROP TABLE IF EXISTS ${o.identifier("__lunora_fts_probe")}`)}catch{}}return p.set(e,r),r},ne={fieldRef:R,rangeTypeGuard:U,serialize:I};export{v as A,l as D,u as a,q as b,Z as c,H as d,R as e,x as f,Y as g,re as h,oe as i,P as j,X as k,w as l,ne as m,i as n,d as o,C as p,G as q,F as r,ee as s,te as t,U as u};
|
|
@@ -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-Da1DjGqo.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-B_4w7tzY.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-CA8mLJWq.mjs";import"./WORKERD_SQLITE_LIMITS-B_4w7tzY.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-RC09zZrh.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-rYWz87LR.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-C7o2xrt1.mjs";import{selectShapeRows as m}from"./selectShapeMembers-BCfKypfN.mjs";import{diffExternalSource as g,projectExternalSourceRow as l}from"./diffExternalSource-B0FZlDoL.mjs";import{stableStringify as d}from"@lunora/wire";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-B_4w7tzY.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-CQou1YrO.mjs → runShardMigrations-CEZTl9LV.mjs}
RENAMED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{LunoraError as U}from"@lunora/errors";import{f as M,S as F}from"./fts-companion-
|
|
1
|
+
import{LunoraError as U}from"@lunora/errors";import{f as M,S as F}from"./fts-companion-CA8mLJWq.mjs";import{sql as t}from"drizzle-orm";import{aggregateTableName as h}from"./aggregateTableName-B_CtIQCS.mjs";import{backfillSearchIndexesForTable as X}from"./backfillAggregateIndexes-DSplGrR_.mjs";import{migrateCdcLog as y,migrateCdcMeta as k}from"./CDC_LOG_TABLE-C7o2xrt1.mjs";import{migrateClientWatermark as w}from"./CLIENT_WATERMARK_TABLE-De7z_OHV.mjs";import{migrateCommitSeq as B}from"./COMMIT_SEQ_FIELD-Da1DjGqo.mjs";import{migrateCompanionState as G}from"./clearCompanionSignatures-3MlVqWZD.mjs";import{migrateGlobalShapeSnapshot as P}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-Bb6-aZuH.mjs";import{migrateIdempotency as Y}from"./IDEMPOTENCY_TABLE-COrgeP3O.mjs";import{m as j}from"./ctx-db-relay-shapes-DV0VO4HG.mjs";import{migrateScheduleOutbox as v}from"./SCHEDULE_OUTBOX_TABLE-DcZI7Yhl.mjs";import{m as W}from"./ctx-db-search-state-FjgzTFok.mjs";import{migrateShapePokeCursor as H}from"./SHAPE_POKE_CURSOR_TABLE-BGvY3sFI.mjs";import{runDrizzle as d,runAll as K}from"./runDrizzle-RC09zZrh.mjs";import{D as V,d as L,e as g,t as z,i as Z,g as J,a as Q,b as q,A as O}from"./do-sql-BWrJQAOh.mjs";import{renderSql as R}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{migrateDurableStreams as ee}from"./appendStreamChunk-BZYgGE9Y.mjs";import{rankTableName as N,sortColumnName as te}from"./RANK_TIEBREAK-D3ye2GsL.mjs";import{migrateReactorState as re}from"./REACTOR_STATE_TABLE-D2Mn204f.mjs";import{recordSchemaVersion as ne}from"./SCHEMA_HISTORY_MAX_VERSIONS-CEwFjj-O.mjs";const u=t`_creationTime, id`,x="__by_creation",oe=`, ${R("sqlite",u).sql})`,I="__lunora_framework_indexes",A=e=>e.replaceAll(/[A-Z]/gu,r=>r.toLowerCase());class D extends U{}const $=(e,r,n,a,i,o)=>{const s=t.join(i.map(m=>t`${m} IS NOT NULL`),t` AND `);if(d(e,t`SELECT 1 FROM ${t.identifier(n)} WHERE ${s} GROUP BY ${a} HAVING COUNT(*) > 1 LIMIT 1`).toArray().length>0)throw new D("INTERNAL",`unique index "${r}" on "${n}" ${o}: existing rows are duplicates under it. De-duplicate the table with a data migration first; the previous index is left in place.`)},l=(e,r,n,a,i,o)=>{const c=d(e,t`SELECT sql FROM sqlite_master WHERE type = 'index' AND name = ${r} COLLATE NOCASE AND tbl_name = ${n} COLLATE NOCASE`).toArray()[0]?.sql;if(c==null)return;const m=f=>{const T=f.indexOf("(");return T===-1?void 0:f.slice(T,f.lastIndexOf(")")+1)},E=m(R("sqlite",L(r,n,a,i)).sql),_=m(c);E===void 0||_===void 0||E===_||(i&&$(e,r,n,a,o,"cannot be re-created with its new column list"),d(e,t`DROP INDEX IF EXISTS ${t.identifier(r)}`))},ie=(e,r,n)=>d(e,t`SELECT 1 FROM sqlite_master WHERE type = 'index' AND name = ${r} COLLATE NOCASE AND tbl_name = ${n} COLLATE NOCASE LIMIT 1`).toArray().length>0,p=(e,r,n,a,i,o)=>{i&&!ie(e,r,n)&&$(e,r,n,a,o,"cannot be created"),d(e,L(r,n,a,i))},C=(e,r)=>{try{r()}catch(n){if(e===void 0||!(n instanceof D))throw n;e.push(n.message)}},ae=(e,r,n)=>A(r).startsWith(`${A(e)}_`)&&A(r)!==A(`${e}${x}`)&&n!==null&&(n.includes("json_extract(")||n.trimEnd().endsWith(oe)),S=(e,r,n)=>{d(e,t`INSERT OR IGNORE INTO ${t.identifier(I)} (name, table_name) VALUES (${r}, ${n})`)},se=(e,r)=>{const n=d(e,t`SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ${I} COLLATE NOCASE`).toArray().length>0;if(d(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(I)} (name TEXT PRIMARY KEY COLLATE NOCASE, table_name TEXT NOT NULL)`),!n)for(const a of r){const i=d(e,t`SELECT name, sql FROM sqlite_master WHERE type = 'index' AND tbl_name = ${a} COLLATE NOCASE AND sql IS NOT NULL`).toArray();for(const{name:o,sql:s}of i)ae(a,o,s)&&S(e,o,a)}},de=(e,r,n)=>{const a=new Set([...n].map(o=>A(o))),i=d(e,t`SELECT "l"."name" FROM ${t.identifier(I)} AS "l" WHERE "l"."table_name" = ${r} COLLATE NOCASE`).toArray();for(const{name:o}of i)a.has(A(o))||(d(e,t`DROP INDEX IF EXISTS ${t.identifier(o)}`),d(e,t`DELETE FROM ${t.identifier(I)} WHERE ${t.identifier(I)}."name" = ${o}`))},ce=(e,r,n,a)=>{const i=new Set;for(const o of n.indexes){const s=`${r}_${o.name}`,c=o.unique??!1,m=o.fields.map(f=>g(f)),E=t.join(m,t`, `),_=c?E:t`${E}, ${u}`;i.add(s),C(a,()=>{l(e,s,r,_,c,m),p(e,s,r,_,c,m),S(e,s,r)})}for(const[o,s]of z(n)){if(!s.unique)continue;const c=g(o),m=`${r}_unique_${o}`;i.add(m),C(a,()=>{l(e,m,r,c,!0,[c]),p(e,m,r,c,!0,[c]),S(e,m,r)})}de(e,r,i)},me=(e,r,n)=>{if(!(!n.searchIndexes||n.searchIndexes.length===0||!Z(e))){for(const a of n.searchIndexes)K(e,M(F(r,a.name)));X(e,r,n)}},fe=(e,r,n)=>{if(n.geoIndexes)for(const a of n.geoIndexes){const i=J(r,a.name);d(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(i)} (${t.identifier("__id__")} TEXT PRIMARY KEY, ${t.identifier("__geohash__")} TEXT NOT NULL, ${t.identifier("__lat__")} REAL NOT NULL, ${t.identifier("__lng__")} REAL NOT NULL)`);const o=`${r}__geo_${a.name}__btree`;d(e,L(o,i,t`${t.identifier("__geohash__")} ASC, ${t.identifier("__id__")} ASC`,!1))}},Ee=(e,r,n)=>{if(n.aggregateIndexes)for(const a of n.aggregateIndexes){const i=h(r,a.name);d(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(i)} (${Q} TEXT PRIMARY KEY, ${q} REAL, ${O} INTEGER NOT NULL DEFAULT 0)`),d(e,t`PRAGMA table_info(${t.identifier(i)})`).toArray().some(s=>s.name==="__count__")||d(e,t`ALTER TABLE ${t.identifier(i)} ADD COLUMN ${O} INTEGER NOT NULL DEFAULT 0`)}},_e=(e,r,n)=>{const a=d(e,t`PRAGMA table_info(${t.identifier(r)})`).toArray().map(i=>i.name).filter(i=>i.startsWith("__sort_k"));a.length>0&&(a.length!==n.length||a.some((i,o)=>i!==n[o]))&&d(e,t`DROP TABLE ${t.identifier(r)}`)},Te=(e,r,n)=>{if(n.rankIndexes)for(const a of n.rankIndexes){const i=N(r,a.name),o=a.sortBy.map((f,T)=>te(T)),s=o.map(f=>t`${t.identifier(f)} BLOB`),c=s.length>0?t`, ${t.join(s,t`, `)}`:t``;_e(e,i,o),d(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(i)} (${t.identifier("__id__")} TEXT PRIMARY KEY, ${t.identifier("__partition__")} TEXT NOT NULL${c})`);const m=[t`${t.identifier("__partition__")} ASC`];for(const[f,T]of o.entries()){const b=a.sortBy[f]?.direction;m.push(t`${t.identifier(T)} ${t.raw(b==="desc"?"DESC":"ASC")}`)}m.push(t`${t.identifier("__id__")} ASC`);const E=`${r}__rank_${a.name}__btree`,_=t.join(m,t`, `);l(e,E,i,_,!1,[]),d(e,L(E,i,_,!1))}},ke=(e,r,n={})=>{const a=n.deferBlockedUniqueIndexes?[]:void 0;n.schemaSnapshot!==void 0&&ne(e,n.schemaSnapshot.hash,n.schemaSnapshot.json),W(e),se(e,Object.entries(r.tables).filter(([,o])=>o.shardMode?.kind!=="global").map(([o])=>o));const i=[];for(const[o,s]of Object.entries(r.tables))s.shardMode?.kind!=="global"&&(d(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(o)} (
|
|
2
2
|
id TEXT PRIMARY KEY,
|
|
3
3
|
_creationTime REAL NOT NULL,
|
|
4
4
|
${t.identifier(V)} 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-RC09zZrh.mjs";import{e}from"./do-sql-BWrJQAOh.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-B1MIaRkE.mjs → selectShapeMembers-BCfKypfN.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{sql as e}from"drizzle-orm";import{runDrizzle as l}from"./runDrizzle-
|
|
1
|
+
import{sql as e}from"drizzle-orm";import{runDrizzle as l}from"./runDrizzle-RC09zZrh.mjs";import{D as p,r as a,m as h}from"./do-sql-BWrJQAOh.mjs";import{sqliteInList as w}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{c as $}from"./where-sql-BjY4rnqb.mjs";const C=o=>{if(o.length!==0)return w(e`${e.identifier("id")}`,o,!1)},u=(o,i)=>{const r=[];i&&r.push(i);const t=$(o,h);return t&&r.push(t),r.length===0?e``:e` WHERE ${e.join(r,e` AND `)}`},M=(o,i,r)=>{const t=u(r,void 0),n=l(o,e`SELECT id, _creationTime, ${e.identifier(p)} FROM ${e.identifier(i)}${t}`).toArray(),f=[];for(const m of n){const s=a(m),{id:c}=m;s!==void 0&&typeof c=="string"&&f.push({doc:s,id:c})}return f},T=(o,i,r,t)=>{const n=new Map;if(t.length===0)return n;const f=u(r,C(t)),m=l(o,e`SELECT id, _creationTime, ${e.identifier(p)} FROM ${e.identifier(i)}${f}`).toArray();for(const s of m){const c=a(s),{id:d}=s;c!==void 0&&typeof d=="string"&&n.set(d,c)}return n};export{T as selectShapeMembers,M as selectShapeRows};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as S}from"@lunora/errors";import{sql as c}from"drizzle-orm";import{i as T,b as y}from"./json-field-path-DeJW4U9z.mjs";import{sqliteInList as x,isJsonSafe as O,bytesAsHexJson as C,WORKERD_SQLITE_LIMITS as L}from"./WORKERD_SQLITE_LIMITS-
|
|
1
|
+
import{LunoraError as S}from"@lunora/errors";import{sql as c}from"drizzle-orm";import{i as T,b as y}from"./json-field-path-DeJW4U9z.mjs";import{sqliteInList as x,isJsonSafe as O,bytesAsHexJson as C,WORKERD_SQLITE_LIMITS as L}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{quoteIdentifier as w}from"./quoteIdentifier-CObIFRhb.mjs";import{RELATION_EXISTS_KEY as b,SEEK_RANGE as j}from"./RELATION_EXISTS_KEY-wxgj6rSL.mjs";const U={binary:(t,n,s)=>c`${t} ${c.raw(n)} ${s}`,constant:t=>t?c`1 = 1`:c`0 = 1`,connect:(t,n,s)=>c`(${t}) ${c.raw(s)} (${n})`,contains:(t,n)=>c`instr(lower(${t}), lower(${n})) > 0`,inList:(t,n,s,o)=>x(t,n,s,o),negate:t=>c`NOT (${t})`,nullCheck:(t,n)=>n?c`${t} IS NOT NULL`:c`${t} IS NULL`,value:t=>c`${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}},E=t=>({params:[t],text:"?"}),A=t=>({params:[],text:t}),nt=t=>A(w(t)),st={binary:(t,n,s)=>h(t," ".concat(n," "),E(s)),constant:t=>A(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 ",e=n.every(l=>O(l)),r=n.length>o&&!e?C(n):void 0;if(r!==void 0)return h(t,i,'(SELECT unhex("value") FROM json_each(',E(r),"))");if(n.length>o&&!e)throw new S("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(E(u));return l.push(")"),h(...l)}return h(t,i,'(SELECT "value" FROM json_each(',E(JSON.stringify(n)),"))")},negate:t=>h("NOT (",t,")"),nullCheck:(t,n)=>h(t,n?" IS NOT NULL":" IS NULL"),value:E},v=L.boundParams/2,I=["eq","ne","lt","lte","gt","gte","in","notIn","isNull","contains"],M=new Set(I),R=new Set(["gt","gte","lt","lte"]),D={eq:"=",gt:">",gte:">=",lt:"<",lte:"<=",ne:"<>"},d=t=>{if(t===null||typeof t!="object"||Array.isArray(t))return!1;const n=Object.keys(t);return n.length>0&&n.every(s=>M.has(s))},P=(t,n,s,o,i)=>{const e=i.value(o.serialize(s,t));return o.containsExpr?o.containsExpr(n,e):i.contains(n,e)},g=(t,n,s,o,i)=>{const e=y(s);return e===void 0?i.constant(!1):i.connect(n,o.rangeTypeGuard(t,e),"AND")},k=(t,n,s,o,i,e,r,l)=>{if(i===null)return s==="eq"||s==="ne"?r.nullCheck(n,s==="ne"):r.constant(!1);const a=r.binary(n,o,e.serialize(i,t));return!l&&R.has(s)&&T(t)?g(t,a,i,e,r):a},F=(t,n,s,o,i,e)=>{if(!Array.isArray(o))throw new S("BAD_REQUEST",`\`${s==="IN"?"in":"notIn"}\` on "${t}" expects an array of values, received ${o===null?"null":typeof o}`);const r=o;if(r.length===0)return e.constant(s==="NOT IN");const l=r.map(u=>i.serialize(u,t)),a=s==="NOT IN";return i.inList?i.inList(n,l,a):e.inList(n,l,a,v)},$=L.boundParams/2,G=6e4,B=(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"&&O(o))s.numbers.push(o);else if(typeof o=="string"&&O(o))s.strings.push(o);else throw new S("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},q=(t,n,s)=>{const o=[],i=c.identifier("v"),e=c.identifier("__in__"),r=a=>c`jsonb_array_elements_text(CAST(CAST(${JSON.stringify(a)} AS text) AS jsonb))`,l=(a,u)=>c`JSON_TABLE(${JSON.stringify(a)}, '$[*]' COLUMNS (${i} ${c.raw(u)} PATH '$')) ${e}`;return s.strings.length>0&&o.push(t==="postgres"?c`${n} IN (SELECT ${r(s.strings)})`:c`${n} IN (SELECT CONVERT(${i} USING utf8mb4) FROM ${l(s.strings,"LONGTEXT")})`),s.numbers.length>0&&o.push(t==="postgres"?c`${n} IN (SELECT CAST(${r(s.numbers)} AS double precision))`:c`${n} IN (SELECT ${i} FROM ${l(s.numbers,"DOUBLE")})`),s.bytes.length>0&&o.push(t==="postgres"?c`${n} IN (SELECT decode(${r(s.bytes)}, 'hex'))`:c`${n} IN (SELECT UNHEX(${i}) FROM ${l(s.bytes,"LONGTEXT")})`),o},ot=t=>(n,s,o,i=$)=>{const e=Math.floor(G*i/$);if(s.length<=e){const u=c.join(s.map(p=>c`${p}`),c`, `);return o?c`${n} NOT IN (${u})`:c`${n} IN (${u})`}const r=B(s,e);if(o&&r.hasNull)return c`1 = 0`;const l=q(t,n,r);if(l.length===0)return c`1 = 0`;const a=l.length===1?l[0]:c`(${c.join(l,c` OR `)})`;return o?c`NOT (${a})`:a},K=(t,n,s,o,i)=>{const e=s,r=[];for(const l of I){if(!(l in e))continue;const a=e[l],u=D[l];u?r.push(k(t,n,l,u,a,o,i,s[j]===!0)):l==="isNull"?r.push(i.nullCheck(n,!a)):l==="contains"?r.push(P(t,n,a,o,i)):r.push(F(t,n,l==="in"?"IN":"NOT IN",a,o,i))}return r},z=(t,n,s,o)=>{const i=s.fieldRef(t);return d(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)},J=(t,n,s,o)=>{const i=Array.isArray(t)?t:[],e=[];for(const r of i){const l=f(r??{},s,o);if(l!==void 0)e.push(l);else if(n==="OR")return}return e.length===0?n==="OR"?o.constant(!1):void 0:N(e,n,o)},Y=new Set(["AND","NOT","OR",b]),Q=(t,n,s,o)=>{if(t===b){if(!s.relationExists)throw new S("INTERNAL","encountered a relation EXISTS marker without a relationExists strategy hook");return s.relationExists(n)}if(t==="NOT"){const i=f(n??{},s,o);return i===void 0?o.constant(!1):o.negate(i)}return J(n,t,s,o)},f=(t,n,s)=>{const o=[];for(const[i,e]of Object.entries(t))if(Y.has(i)){const r=Q(i,e,n,s);r!==void 0&&o.push(r)}else o.push(...z(i,e,n,s));return N(o,"AND",s)},m=t=>{let n=0,s=0;const o=i=>{const e=m(i);n+=e.lists,s+=e.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,e]of Object.entries(t))i==="in"||i==="notIn"?n+=1:i==="AND"||i==="NOT"||i==="OR"||d(e)?(o(e),T(i)&&(s+=1+Object.keys(e).filter(r=>R.has(r)).length)):s+=T(i)?2:1;return{lists:n,scalars:s}},it=(t,n,s=U,o=0)=>{if(!t||Object.keys(t).length===0)return;const{lists:i,scalars:e}=m(t);if(i===0)return f(t,n,s);const r=Math.max(1,Math.floor(Math.min($,L.boundParams-e-o)/i)),l=n.inList??((a,u,p,_)=>s.inList(a,u,p,_??r));return f(t,{...n,inList:(a,u,p)=>l(a,u,p,r)},s)};export{it as c,nt as i,h as j,A as r,ot as s,st 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.152",
|
|
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",
|
|
@@ -49,9 +49,9 @@
|
|
|
49
49
|
},
|
|
50
50
|
"dependencies": {
|
|
51
51
|
"@lunora/errors": ">=1.0.0-alpha.51 <2.0.0-0",
|
|
52
|
-
"@lunora/platform": "1.0.0-alpha.
|
|
52
|
+
"@lunora/platform": "1.0.0-alpha.74",
|
|
53
53
|
"@lunora/wire": "1.0.0-alpha.2",
|
|
54
|
-
"drizzle-orm": "
|
|
54
|
+
"drizzle-orm": "1.0.0-rc.5"
|
|
55
55
|
},
|
|
56
56
|
"engines": {
|
|
57
57
|
"node": "^22.15.0 || >=24.11.0"
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as f}from"@lunora/errors";import{sql as t}from"drizzle-orm";import{SQLiteSyncDialect as u}from"drizzle-orm/sqlite-core";const S=new u,s={boundParams:100,compoundSelect:5,likePattern:50,sqlTextLength:1e5},d=s.boundParams/2,h=n=>n===null||typeof n=="boolean"?!0:typeof n=="number"?Number.isFinite(n):typeof n=="string"&&n.isWellFormed(),p=n=>{const e=[];for(const r of n){if(!(r instanceof Uint8Array))return;e.push(Array.from(r,o=>o.toString(16).padStart(2,"0")).join(""))}return JSON.stringify(e)},y=(n,e)=>{if(n!=="sqlite")throw new f("INTERNAL",`renderSql only renders SQLite; use SqlDialect.render for "${n}"`);const{params:r,sql:o}=S.sqlToQuery(e);return{params:r,sql:o}},L=n=>t`${n}`,N=n=>{if(n.length===0)throw new Error("unionAll: expected at least one branch");let e=[...n];for(;e.length>s.compoundSelect;){const r=[];for(let o=0;o<e.length;o+=s.compoundSelect){const i=t.join(e.slice(o,o+s.compoundSelect),t` UNION ALL `);r.push(t`SELECT * FROM (${i}) ${t.identifier("__u__")}`)}e=r}return t.join(e,t` UNION ALL `)},T=(n,e,r,o=d)=>{const i=r?t` NOT IN `:t` IN `,a=e.every(l=>h(l)),c=e.length>o&&!a?p(e):void 0;if(c!==void 0)return t`${n}${i}(SELECT unhex(${t.identifier("value")}) FROM json_each(${c}))`;if(e.length>o&&!a)throw new f("BAD_REQUEST",`an "in" list of ${String(e.length)} values holds a value JSON cannot carry (bytes, a non-finite number, or malformed text), so it cannot be bound as one parameter — and ${String(e.length)} placeholders exceed SQLite's per-statement cap of 100 on Durable Objects and D1. Narrow the list to ${String(o)} values or fewer.`);return e.length<=o?t`${n}${i}(${t.join(e.map(l=>L(l)),t`, `)})`:t`${n}${i}(SELECT ${t.identifier("value")} FROM json_each(${JSON.stringify(e)}))`};export{s as WORKERD_SQLITE_LIMITS,p as bytesAsHexJson,h as isJsonSafe,L as param,y as renderSql,T as sqliteInList,N as unionAll};
|