@lunora/shard-engine 1.0.0-alpha.7 → 1.0.0-alpha.71
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/README.md +1 -1
- package/dist/conformance/index.mjs +1 -1
- package/dist/index.d.mts +572 -119
- package/dist/index.d.ts +572 -119
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/ADMIN_FUNCTIONS-BjpFlIz5.mjs +1 -0
- package/dist/packem_shared/AGGREGATE_SQL_FUNCTION-DDEoMnJR.mjs +1 -0
- package/dist/packem_shared/AGG_COUNT-TzzFAsyw.mjs +1 -0
- package/dist/packem_shared/AUDIT_LOG_TABLE-ONxmEAIz.mjs +8 -0
- package/dist/packem_shared/BIGINT_KEY_DIGITS-Bnqj9CYQ.mjs +1 -0
- package/dist/packem_shared/CDC_LOG_TABLE-Bh7SB6Uw.mjs +15 -0
- package/dist/packem_shared/CLIENT_WATERMARK_TABLE-CRnrAnJ2.mjs +7 -0
- package/dist/packem_shared/COMMIT_SEQ_FIELD-BUdOMG5y.mjs +4 -0
- package/dist/packem_shared/CURSOR_PREFIX-Bn8SFoGd.mjs +1 -0
- package/dist/packem_shared/CountRlsUnsupportedError-BvsDqfO2.mjs +1 -0
- package/dist/packem_shared/DATA_MIGRATION_STATE_TABLE-BwFz6NTT.mjs +31 -0
- package/dist/packem_shared/DEFAULT_MAX_RELATION_KEYS-XESc7TiB.mjs +1 -0
- package/dist/packem_shared/DEFAULT_MAX_RELAYS-Ng4SyJ7k.mjs +8 -0
- package/dist/packem_shared/DEFAULT_PROMOTION_THRESHOLDS-Bfx7KakS.mjs +1 -0
- package/dist/packem_shared/DEFAULT_TRANSACTION_LIMITS-CTHQQgDC.mjs +1 -0
- package/dist/packem_shared/DurableStreamRunner-rTYp4v03.mjs +1 -0
- package/dist/packem_shared/GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs +1 -0
- package/dist/packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-DSA6mzyx.mjs +7 -0
- package/dist/packem_shared/GlobalPollTick-BNK4o-XT.mjs +1 -0
- package/dist/packem_shared/IDEMPOTENCY_TABLE-DOpm_oMF.mjs +7 -0
- package/dist/packem_shared/MAIL_RETENTION-DGAQTHHs.mjs +18 -0
- package/dist/packem_shared/MAX_SQL_ROWS-Dh_Ty0Zo.mjs +4 -0
- package/dist/packem_shared/MAX_TOKEN_LENGTH-BakL9FUy-B3VwYY8C.mjs +1 -0
- package/dist/packem_shared/NotUniqueError-Dfjj2n69.mjs +1 -0
- package/dist/packem_shared/QUEUE_TABLE-s7QJZvBz.mjs +17 -0
- package/dist/packem_shared/RANK_TIEBREAK-D5xNdzB3.mjs +1 -0
- package/dist/packem_shared/REACTOR_STATE_TABLE-QPRFyxMS.mjs +28 -0
- package/dist/packem_shared/RELATED_DEFAULT_LIMIT-B9PH28Pn.mjs +1 -0
- package/dist/packem_shared/RELATION_EXISTS_KEY-CFUhnZSZ.mjs +1 -0
- package/dist/packem_shared/REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs +1 -0
- package/dist/packem_shared/RLS_UNWRAP_SYMBOL-BwwTbz3Q.mjs +1 -0
- package/dist/packem_shared/ReactiveCache-CU_NoCMR.mjs +1 -0
- package/dist/packem_shared/SCAN_DEP-D7qE3iUe.mjs +1 -0
- package/dist/packem_shared/SCHEDULE_OUTBOX_TABLE-CD_UjYVx.mjs +11 -0
- package/dist/packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-BluIj2s-.mjs +6 -0
- package/dist/packem_shared/SEARCH_STATE_TABLE-D5mnK5kX.mjs +1 -0
- package/dist/packem_shared/SHAPE_POKE_CURSOR_TABLE-ByJVDHds.mjs +8 -0
- package/dist/packem_shared/ShapeDiffCache-gdaILV5E.mjs +1 -0
- package/dist/packem_shared/ShardRunner-C9p5DVOx.mjs +1 -0
- package/dist/packem_shared/UNVOUCHABLE_DEP-C68htACn.mjs +1 -0
- package/dist/packem_shared/aggregateTableName-C7o-gpms.mjs +1 -0
- package/dist/packem_shared/appendStreamChunk-C1Ok4b6J.mjs +19 -0
- package/dist/packem_shared/applyOnDelete-7JZ4vR9r.mjs +1 -0
- package/dist/packem_shared/archiveCdcSegment-DU4uzDFQ.mjs +4 -0
- package/dist/packem_shared/{armRestore-BNzdvQ_o.mjs → armRestore-Bu1_8SUa.mjs} +1 -1
- package/dist/packem_shared/awaitWsDrain-apizgmKY.mjs +1 -0
- package/dist/packem_shared/backfillAggregateIndexes-DTemznr7.mjs +1 -0
- package/dist/packem_shared/base64-DfpzS4o_.mjs +1 -0
- package/dist/packem_shared/buildIndexRange-DvN8Qj8e.mjs +1 -0
- package/dist/packem_shared/buildPokeFrames-BBE6J91z.mjs +1 -0
- package/dist/packem_shared/buildReprojectionMigration-DNjOe6AP.mjs +1 -0
- package/dist/packem_shared/buildSettings-DC3VeQ0H.mjs +1 -0
- package/dist/packem_shared/buildShapeDiff-BBDwwZOO.mjs +1 -0
- package/dist/packem_shared/clearMemoryTables-BGbmag2i.mjs +1 -0
- package/dist/packem_shared/compileWhereSql-B8tS0_nD.mjs +1 -0
- package/dist/packem_shared/computeRankPage-pTaG_r9F.mjs +1 -0
- package/dist/packem_shared/createCompanionSync-Cb567rkq.mjs +1 -0
- package/dist/packem_shared/createReplicaLink-B9PuaB8z.mjs +7 -0
- package/dist/packem_shared/createSystemReader-DcDLFfC-.mjs +1 -0
- package/dist/packem_shared/ctx-db-companions-DsNfXSbb.mjs +1 -0
- package/dist/packem_shared/ctx-db-relay-shapes-Bg5YYnmN.mjs +17 -0
- package/dist/packem_shared/ctx-db-search-state-ruTuCsxa.mjs +1 -0
- package/dist/packem_shared/defineEngineContractSuite-D-IRwGgA.mjs +1 -0
- package/dist/packem_shared/diffExternalSource-DgDJhslq.mjs +1 -0
- package/dist/packem_shared/do-sql-kpl5Kt1j.mjs +1 -0
- package/dist/packem_shared/envOptionalPositiveInt-D2pY-c64.mjs +1 -0
- package/dist/packem_shared/estimate-bytes-DM1UZj_m.mjs +1 -0
- package/dist/packem_shared/exportShardRows-1TkeNJI6.mjs +1 -0
- package/dist/packem_shared/hasTrigger-CjlwI4le.mjs +1 -0
- package/dist/packem_shared/isSoftDeleted-CxoKxv-h.mjs +9 -0
- package/dist/packem_shared/liftSourceId-CA3ENhXj.mjs +1 -0
- package/dist/packem_shared/materializeExternalRows-CgHTVGDJ.mjs +1 -0
- package/dist/packem_shared/mergeChangedKeys-BA3YxaLE.mjs +1 -0
- package/dist/packem_shared/param-DlozcSQu.mjs +1 -0
- package/dist/packem_shared/quoteIdentifier-CObIFRhb.mjs +1 -0
- package/dist/packem_shared/runDrizzle-2ULFQR_k.mjs +1 -0
- package/dist/packem_shared/runShardMigrations-Dp8Ld19a.mjs +5 -0
- package/dist/packem_shared/runSocketPool-CZJ2X9cF.mjs +1 -0
- package/dist/packem_shared/selectExpiredIds-D5DEpBbi.mjs +1 -0
- package/dist/packem_shared/selectShapeMembers-B8gTOeOB.mjs +1 -0
- package/dist/packem_shared/serializeSqlValue-BEMMYX1n.mjs +1 -0
- package/dist/packem_shared/sibling-channel-BkL5cTCc.mjs +1 -0
- package/dist/packem_shared/sql-projection-D3qdaItY.mjs +1 -0
- package/dist/packem_shared/stableStringify-DibjylKD.mjs +1 -0
- package/dist/packem_shared/stableWireKey-D2US4k_J.mjs +1 -0
- package/dist/packem_shared/where-sql-x1YKldcq.mjs +1 -0
- package/dist/packem_shared/wire-codec-C-FpWm52.mjs +1 -0
- package/package.json +3 -3
- package/dist/packem_shared/ADMIN_FUNCTIONS-vj2G8OR6.mjs +0 -1
- package/dist/packem_shared/AGGREGATE_SQL_FUNCTION-QYaiuty4.mjs +0 -1
- package/dist/packem_shared/AGG_COUNT-BWXe3gtQ.mjs +0 -1
- package/dist/packem_shared/AUDIT_LOG_TABLE-CaA0jL0L.mjs +0 -8
- package/dist/packem_shared/CDC_LOG_TABLE-BnqlH2eZ.mjs +0 -8
- package/dist/packem_shared/CLIENT_WATERMARK_TABLE-CXsSLU8D.mjs +0 -7
- package/dist/packem_shared/CountRlsUnsupportedError-B2WKJD9v.mjs +0 -1
- package/dist/packem_shared/DATA_MIGRATION_STATE_TABLE-BZMVrLcy.mjs +0 -31
- package/dist/packem_shared/DEFAULT_MAX_RELATION_KEYS-bq00btqV.mjs +0 -1
- package/dist/packem_shared/DEFAULT_MAX_RELAYS-D0oc40p6.mjs +0 -1
- package/dist/packem_shared/DEFAULT_PROMOTION_THRESHOLDS-Dteg0sZF.mjs +0 -1
- package/dist/packem_shared/DEFAULT_TRANSACTION_LIMITS-BH5q0Ror.mjs +0 -1
- package/dist/packem_shared/FTS_COUNT_COLUMN-D1gY3wwZ-CZHdaRrd.mjs +0 -1
- package/dist/packem_shared/GEO_DEFAULT_PRECISION-okRCkZ6r.mjs +0 -1
- package/dist/packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-DX-6-gBP.mjs +0 -7
- package/dist/packem_shared/IDEMPOTENCY_TABLE-DjkEMp6w.mjs +0 -7
- package/dist/packem_shared/MAIL_RETENTION-KmozO2NQ.mjs +0 -18
- package/dist/packem_shared/MAX_SQL_ROWS-nMwkxv5f.mjs +0 -2
- package/dist/packem_shared/NotUniqueError-Qrtwm7S6.mjs +0 -1
- package/dist/packem_shared/QUEUE_TABLE-DYCDvzTG.mjs +0 -17
- package/dist/packem_shared/RANK_TIEBREAK-9NU5s_mi.mjs +0 -1
- package/dist/packem_shared/RELATION_EXISTS_KEY-BaqSIFU1.mjs +0 -1
- package/dist/packem_shared/RLS_UNWRAP_SYMBOL-CBYPlYBb.mjs +0 -1
- package/dist/packem_shared/ReactiveCache-C6QAa7MG.mjs +0 -1
- package/dist/packem_shared/SCAN_DEP-D_yR9EeV.mjs +0 -1
- package/dist/packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-CHXz6p_z.mjs +0 -6
- package/dist/packem_shared/SEARCH_STATE_TABLE-eLN8U5tz.mjs +0 -1
- package/dist/packem_shared/ShardRunner-DIqVdWtk.mjs +0 -1
- package/dist/packem_shared/aggregateTableName-G-eXyjcz.mjs +0 -1
- package/dist/packem_shared/applyOnDelete-uFRC5p1d.mjs +0 -1
- package/dist/packem_shared/applySelect-B0CF8T7y.mjs +0 -1
- package/dist/packem_shared/awaitWsDrain-CCZ-8wjm.mjs +0 -1
- package/dist/packem_shared/backfillAggregateIndexes-BHiewuB-.mjs +0 -1
- package/dist/packem_shared/buildIndexRange-DFsdtPjD.mjs +0 -1
- package/dist/packem_shared/buildPokeFrames-DaPpm5Ss.mjs +0 -1
- package/dist/packem_shared/buildSettings-DT18_DkX.mjs +0 -1
- package/dist/packem_shared/compileWhereSql-BLcfs4QW.mjs +0 -1
- package/dist/packem_shared/computeRankPage-IUSS-zIB.mjs +0 -1
- package/dist/packem_shared/createCompanionSync-DWK0Vlg1.mjs +0 -1
- package/dist/packem_shared/createReadFootprint-DIrrxRTE.mjs +0 -1
- package/dist/packem_shared/createSystemReader-DcDcrtM3.mjs +0 -1
- package/dist/packem_shared/defineEngineContractSuite-1f7OcQND.mjs +0 -1
- package/dist/packem_shared/diffExternalSource-DMpkJta1.mjs +0 -1
- package/dist/packem_shared/estimate-bytes-DwQON1Ky.mjs +0 -1
- package/dist/packem_shared/exportShardRows-kt42wijd.mjs +0 -1
- package/dist/packem_shared/hasTrigger-CbkOHExZ.mjs +0 -1
- package/dist/packem_shared/isSoftDeleted-B-SXkGUo.mjs +0 -9
- package/dist/packem_shared/liftSourceId-DApAbu7Q.mjs +0 -1
- package/dist/packem_shared/materializeExternalRows-DOQJV9p2.mjs +0 -1
- package/dist/packem_shared/mergeChangedKeys-BXtUgIPW.mjs +0 -1
- package/dist/packem_shared/param-B5lF5Jd9.mjs +0 -1
- package/dist/packem_shared/quote-identifier-CGiYFBvY.mjs +0 -1
- package/dist/packem_shared/runDrizzle-GKR3y97k.mjs +0 -1
- package/dist/packem_shared/runShardMigrations-CPxqCh3O.mjs +0 -5
- package/dist/packem_shared/runSocketPool-DPQLVyWF.mjs +0 -1
- package/dist/packem_shared/selectExpiredIds-FzhIEeG1.mjs +0 -1
- package/dist/packem_shared/selectShapeMemberIds-DvE7K6zG.mjs +0 -1
- package/dist/packem_shared/serializeSqlValue-DnpyaLcw.mjs +0 -1
- package/dist/packem_shared/stableStringify-BjLh4gvA.mjs +0 -1
- package/dist/packem_shared/stableWireKey-YEHLaX6X.mjs +0 -1
- package/dist/packem_shared/wire-codec-Ctnni0h6.mjs +0 -1
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import{sql as t}from"drizzle-orm";import{runDrizzle as o}from"./runDrizzle-2ULFQR_k.mjs";const a="__reactor_state",c=[["runs","runs INTEGER NOT NULL DEFAULT 0"],["suppressed","suppressed INTEGER NOT NULL DEFAULT 0"],["errors","errors INTEGER NOT NULL DEFAULT 0"],["last_ran_at","last_ran_at INTEGER NOT NULL DEFAULT 0"],["last_error","last_error TEXT"]],O=r=>{o(r,t`CREATE TABLE IF NOT EXISTS ${t.identifier(a)} (
|
|
2
|
+
path TEXT PRIMARY KEY,
|
|
3
|
+
digest TEXT NOT NULL,
|
|
4
|
+
tables TEXT NOT NULL,
|
|
5
|
+
runs INTEGER NOT NULL DEFAULT 0,
|
|
6
|
+
suppressed INTEGER NOT NULL DEFAULT 0,
|
|
7
|
+
errors INTEGER NOT NULL DEFAULT 0,
|
|
8
|
+
last_ran_at INTEGER NOT NULL DEFAULT 0,
|
|
9
|
+
last_error TEXT
|
|
10
|
+
)`);const e=new Set(o(r,t`PRAGMA table_info(${t.identifier(a)})`).toArray().map(s=>s.name));for(const[s,i]of c)e.has(s)||o(r,t`ALTER TABLE ${t.identifier(a)} ADD COLUMN ${t.raw(i)}`)},R=r=>{if(typeof r=="string")try{const e=JSON.parse(r);return Array.isArray(e)&&e.every(s=>typeof s=="string")?e:void 0}catch{return}},T=r=>typeof r=="number"&&Number.isFinite(r)?r:0,d=r=>({digest:r.digest,...typeof r.last_error=="string"&&r.last_error.length>0?{lastError:r.last_error}:{},lastRanAt:T(r.last_ran_at),stats:{errors:T(r.errors),runs:T(r.runs),suppressed:T(r.suppressed)},tables:R(r.tables)}),l="path, digest, tables, runs, suppressed, errors, last_ran_at, last_error",f=(r,e)=>{const[s]=o(r,t`SELECT ${t.raw(l)} FROM ${t.identifier(a)} WHERE path = ${e}`);if(!(s===void 0||typeof s.digest!="string"))return d(s)},U=r=>o(r,t`SELECT ${t.raw(l)} FROM ${t.identifier(a)} ORDER BY path`).toArray().filter(e=>typeof e.digest=="string").map(e=>({path:e.path,state:d(e)})),g=(r,e,s)=>{const{digest:i,error:p,now:u,result:n,tables:E}=s,L=i??"",N=E===void 0?"":JSON.stringify([...E]),_=p??null;o(r,t`INSERT INTO ${t.identifier(a)} (path, digest, tables, runs, suppressed, errors, last_ran_at, last_error)
|
|
11
|
+
VALUES (
|
|
12
|
+
${e},
|
|
13
|
+
${L},
|
|
14
|
+
${N},
|
|
15
|
+
${n==="ran"?1:0},
|
|
16
|
+
${n==="suppressed"?1:0},
|
|
17
|
+
${n==="error"?1:0},
|
|
18
|
+
${u},
|
|
19
|
+
${_}
|
|
20
|
+
)
|
|
21
|
+
ON CONFLICT(path) DO UPDATE SET
|
|
22
|
+
digest = ${i===void 0?t.raw(`${a}.digest`):t`excluded.digest`},
|
|
23
|
+
tables = ${E===void 0?t.raw(`${a}.tables`):t`excluded.tables`},
|
|
24
|
+
runs = ${t.raw(`${a}.runs`)} + ${n==="ran"?1:0},
|
|
25
|
+
suppressed = ${t.raw(`${a}.suppressed`)} + ${n==="suppressed"?1:0},
|
|
26
|
+
errors = ${t.raw(`${a}.errors`)} + ${n==="error"?1:0},
|
|
27
|
+
last_ran_at = excluded.last_ran_at,
|
|
28
|
+
last_error = ${n==="error"?t`excluded.last_error`:t.raw("NULL")}`)},S=(r,e)=>r?.tables===void 0?!0:r.tables.some(s=>e.has(s));export{a as REACTOR_STATE_TABLE,U as listReactorStates,O as migrateReactorState,S as reactorNeedsRun,f as readReactorState,g as writeReactorState};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as h}from"@lunora/errors";import{mergeWhere as I}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{decodeCursor as S,CURSOR_PREFIX as v,toBase64 as B}from"./CURSOR_PREFIX-Bn8SFoGd.mjs";const O=4,C=1,L=50,$=200,T=1e4,x=.5,D=t=>{if(t.kind==="id"){const e=t._meta?.tableName;return typeof e=="string"&&e.length>0?{array:!1,targetTable:e}:void 0}if(t.kind!=="array"&&t.kind!=="optional")return;const n=t._meta?.inner,r=n===void 0?void 0:D(n);if(r!==void 0)return{array:r.array||t.kind==="array",targetTable:r.targetTable}},j=t=>{const n=[];for(const[r,e]of Object.entries(t.tables))for(const[s,o]of Object.entries(e.shape)){const a=D(o);a===void 0||t.tables[a.targetTable]===void 0||n.push({array:a.array,column:s,name:`${r}.${s}`,sourceTable:r,targetTable:a.targetTable})}return n},U=t=>v+B(JSON.stringify([t])),M=t=>{const[n]=S(t);if(typeof n!="number"||!Number.isInteger(n)||n<0)throw new h("BAD_REQUEST","invalid cursor");if(n>T)throw new h("BAD_REQUEST",`ctx.db.related: cursor offset ${String(n)} exceeds the maximum of ${String(T)} — narrow the walk with \`edges\` or \`direction\` instead of paging past it`);return n},k=(t,n,r,e)=>{if(t===void 0)return n;if(!Number.isInteger(t)||t<1||t>r)throw new h("BAD_REQUEST",`ctx.db.related: \`${e}\` must be an integer between 1 and ${String(r)}, got ${String(t)}`);return t},N=(t,n)=>{if(n===void 0)return[...t];const r=new Set(t.map(o=>o.name)),e=n.filter(o=>!r.has(o));if(e.length>0)throw new h("BAD_REQUEST",`ctx.db.related: unknown edge ${e.length===1?"name":"names"}: ${e.join(", ")}`);const s=new Set(n);return t.filter(o=>s.has(o.name))},W=(t,n)=>{const r=t[n.column];return n.array?Array.isArray(r)?r.filter(e=>typeof e=="string"&&e.length>0):[]:typeof r=="string"&&r.length>0?[r]:[]},A=async(t,n,r,e)=>{const s=await t.findMany(n,{limit:e.limit,omitContinueCursor:!0,where:I(r,e.relationBaseWhere?.(n))??r});return e.mask?.(n,s.page)??s.page},F={in:{keyColumn:t=>t.column,keysOf:(t,n)=>n.array||t.table!==n.targetTable?[]:[t.id],skipVisitedKeys:!1,table:t=>t.sourceTable},out:{keyColumn:()=>"_id",keysOf:(t,n)=>t.table===n.sourceTable?W(t.document,n):[],skipVisitedKeys:!0,table:t=>t.targetTable}},_=async(t,n,r,e,s)=>{const o=F[s],a=o.keyColumn(r),l=o.table(r),u=new Map;for(const c of n)for(const i of o.keysOf(c,r))!u.has(i)&&!(o.skipVisitedKeys&&e.visited.has(i))&&u.set(i,c);if(u.size===0)return[];const f=await A(t,l,{[a]:{in:[...u.keys()]}},e),m=[];for(const c of f){const i=c._id,g=c[a],d=typeof g=="string"?u.get(g):void 0;typeof i!="string"||d===void 0||e.visited.has(i)||(e.visited.add(i),m.push({document:c,id:i,path:[...d.path,r.name],pathIds:[...d.pathIds,i],table:l}))}return m},Q=async(t,n,r,e)=>{const s=[],o=()=>e.budget-s.length,a=()=>({limit:o(),mask:e.mask,relationBaseWhere:e.relationBaseWhere,visited:e.visited});for(const l of r)e.direction!=="in"&&o()>0&&s.push(...await _(t,n,l,a(),"out")),e.direction!=="out"&&o()>0&&s.push(...await _(t,n,l,a(),"in"));return s},H=async(t,n)=>{const r=n._id;if(typeof r=="string"&&r.length>0){const o=await t.lookupById?.(r);if(!o)throw new h("BAD_REQUEST","ctx.db.related: could not resolve the start document's table from its `_id` — pass `{ table, id }` instead");return{id:r,table:o.tableName}}const{id:e,table:s}=n;if(typeof s!="string"||s.length===0||typeof e!="string"||e.length===0)throw new h("BAD_REQUEST","ctx.db.related: `start` must be a loaded document or `{ table, id }`");return{id:e,table:s}},V=async(t,n,r,e={})=>{const s=k(e.depth,C,O,"depth"),o=k(e.limit,L,$,"limit"),a=e.cursor?M(e.cursor):0,l=e.direction??"both",u=N(n,e.edges),{id:f,table:m}=await H(t,r),[c]=await A(t,m,{_id:f},{limit:1,mask:e.relationMask,relationBaseWhere:e.relationBaseWhere,visited:new Set});if(c===void 0)throw new h("NOT_FOUND",`ctx.db.related: no "${m}" row with id ${f}`);const i=a+o+1,g=new Set([f]),d=[];let w=[{document:c,id:f,path:[],pathIds:[f],table:m}];for(let b=1;b<=s&&w.length>0&&d.length<i;b+=1){const p=await Q(t,w,u,{budget:i-d.length,direction:l,mask:e.relationMask,relationBaseWhere:e.relationBaseWhere,visited:g}),R=x**(b-1);for(const y of p)d.push({depth:b,document:y.document,path:y.path,pathIds:y.pathIds,score:R,table:y.table});w=p}const E=d.length<=a+o;return{continueCursor:E?null:U(a+o),isDone:E,nodes:d.slice(a,a+o)}};export{L as RELATED_DEFAULT_LIMIT,x as RELATED_DEPTH_DECAY,O as RELATED_MAX_DEPTH,$ as RELATED_MAX_LIMIT,T as RELATED_MAX_OFFSET,j as deriveRelationEdges,V as findRelated};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const t="__relationExists";export{t as RELATION_EXISTS_KEY};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const o="__lunora_reproject__",e=t=>`${o}${t}`,n=t=>{if(!t.startsWith(o))return;const r=t.slice(o.length);return r===""?void 0:r};export{o as REPROJECTION_MIGRATION_PREFIX,e as reprojectionMigrationId,n as reprojectionMigrationTable};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as R}from"@lunora/errors";import{findRelated as m}from"./RELATED_DEFAULT_LIMIT-B9PH28Pn.mjs";const M=Symbol.for("lunora.ctxdb.rls-unwrap");class S extends R{table;constructor(n){super("RLS_REQUIRED",`ctx.db access to "${n}" is denied: the schema is marked .rls("required"), so this table is protected. Apply RLS with .use(rls(policies)) in the procedure, or mark the table .public() to opt it out.`,{name:"RlsRequiredError"}),this.table=n}}const b=a=>Object.entries(a.tables).filter(([,n])=>n.shardMode?.kind!=="global").map(([n])=>n),E=(a,n,l)=>{const d=n?.tables,u=new Set(n?.exclude);for(const o of a)(d===void 0||d.includes(o))&&!u.has(o)&&l(o)},y={aggregate:"loop-gated",asId:"ungated",cdcChangedTables:"ungated",count:"loop-gated",delete:"id-gated",deleteAll:"loop-gated",deleteMany:"id-gated",deleteWhere:"inline-table-gated",findFirst:"loop-gated",findFirstOrThrow:"loop-gated",findMany:"loop-gated",get:"id-gated",groupBy:"loop-gated",insert:"loop-gated",insertMany:"loop-gated",insertManyUnsafe:"loop-gated",lookupById:"id-gated",normalizeId:"ungated",patch:"id-gated",patchMany:"id-gated",patchWhere:"inline-table-gated",query:"loop-gated",rank:"loop-gated",rankBefore:"loop-gated",rankPage:"loop-gated",rankPageRows:"loop-gated",related:"rebound",relationEdges:"ungated",replace:"id-gated",restore:"id-gated",system:"ungated",wipeShard:"sweep-gated"},O=Object.entries(y).filter(([,a])=>a==="loop-gated").map(([a])=>a),W={related:(a,n)=>(...l)=>{const[d,u]=l;return m(a,n,d,u)}},k=Object.entries(y).filter(([,a])=>a==="rebound").map(([a])=>a),v=(a,n,l)=>{for(const d of k)typeof n[d]=="function"&&(a[d]=W[d](a,l))},_=(a,n,l,d,u=[])=>{if(n.rlsMode!=="required")return a;const o=a,p=e=>{const t=n.tables[e];return t!==void 0&&t.isPublic!==!0},i=e=>{if(p(e))throw new S(e)},c=async(e,t)=>{if(t!==void 0){i(t);return}const r=await l(e);r!==void 0&&i(r)},f=async(e,t)=>{if(t!==void 0){i(t);return}if(!d){for(const s of e)await c(s,t);return}const r=await d([...new Set(e)],t);for(const s of e){const h=r.get(s);h!==void 0&&i(h)}},g={...a,delete:async(e,t,r)=>(await c(e,t),o.delete(e,t,r)),deleteMany:async(e,t,r)=>(await f(e,r),o.deleteMany(e,t,r)),deleteWhere:o.deleteWhere?async(e,t,r)=>(i(e),await o.deleteWhere?.(e,t,r)):void 0,get:async(e,t)=>(await c(e,t),o.get(e,t)),lookupById:async(e,t)=>(await c(e,t),o.lookupById?.(e,t)??null),patch:async(e,t,r)=>(await c(e,r),o.patch(e,t,r)),patchMany:async(e,t,r)=>(await f(e.map(s=>s.id),r),o.patchMany(e,t,r)),patchWhere:o.patchWhere?async(e,t,r)=>(i(e),await o.patchWhere?.(e,t,r)):void 0,replace:async(e,t,r,s)=>(await c(e,r),o.replace(e,t,r,s)),restore:async(e,t)=>(await c(e,t),o.restore?.(e,t))},w=o;for(const e of O){const t=w[e];typeof t=="function"&&(g[e]=(r,...s)=>(i(r),t.call(o,r,...s)))}if(v(g,o,u),o.wipeShard){const{wipeShard:e}=o;g.wipeShard=t=>(E(b(n),t,i),e.call(o,t))}return Object.defineProperty(g,M,{configurable:!0,enumerable:!1,value:a,writable:!1}),g};export{O as LOOP_GATED_METHODS,M as RLS_UNWRAP_SYMBOL,S as RlsRequiredError,y as WRITER_METHOD_GATING,_ as guardWriter};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{stableWireKey as y}from"./stableWireKey-D2US4k_J.mjs";import{depKey as b,SCAN_DEP as p}from"./SCAN_DEP-D7qE3iUe.mjs";import{e as m}from"./estimate-bytes-DM1UZj_m.mjs";import{keysTouchRanges as x}from"./buildIndexRange-DvN8Qj8e.mjs";import{stableStringify as K}from"./stableStringify-DibjylKD.mjs";const l=(o,t,s)=>{let e=o.get(t);return e===void 0&&(e=s(),o.set(t,e)),e},v=1e3,E=4*1024*1024;class A{entries=new Map;tableIndex=new Map;rangeIndex=new Map;totalBytes=0;hits=0;misses=0;evictions=0;maxEntries;maxBytes;now;monotonic=0;generation=0;constructor(t={}){this.maxEntries=t.maxEntries??v,this.maxBytes=t.maxBytes??E,this.now=t.now??(()=>(this.monotonic+=1,this.monotonic))}async run(t,s,e,i=()=>[]){const n=this.entries.get(t);if(n)return this.hits+=1,n.lastUsed=this.now(),this.entries.delete(t),this.entries.set(t,n),n.result;this.misses+=1;const c=this.generation,a=await e();if(this.generation!==c)return a;const h=m(a);if(h===void 0)return a;const f=i(),u={bytes:h,deps:s,ranges:f,lastUsed:this.now(),result:a,subscribers:new Set},d=this.entries.get(t);if(d){this.dropEntry(t,d);for(const r of d.subscribers)u.subscribers.add(r)}this.entries.set(t,u),this.totalBytes+=h;for(const r of s)l(this.tableIndex,r,()=>new Set).add(t);for(const r of f){const g=l(this.rangeIndex,r.table,()=>new Map);l(g,r,()=>new Set).add(t)}return this.evict(),a}invalidate(t,s,e){this.generation+=1;const i=[];return this.collectAndDrop(b(t,s),i),this.collectAndDrop(b(t,p),i),this.dropRangeDeps(t,e,i),i}invalidateTable(t){this.generation+=1;const s=[],e=`${t}:`;for(const i of this.tableIndex.keys())i.startsWith(e)&&this.collectAndDrop(i,s);return this.dropRangeDeps(t,void 0,s),s}subscribe(t,s){const e=this.entries.get(t);e&&e.subscribers.add(s)}unsubscribe(t,s){const e=this.entries.get(t);e&&e.subscribers.delete(s)}size(){return{bytes:this.totalBytes,entries:this.entries.size}}clear(){this.generation+=1,this.entries.clear(),this.tableIndex.clear(),this.rangeIndex.clear(),this.totalBytes=0}subscribers(t){const s=this.entries.get(t);return s?[...s.subscribers]:[]}stats(){return{bytes:this.totalBytes,entries:this.entries.size,evictions:this.evictions,hits:this.hits,misses:this.misses}}dropRangeDeps(t,s,e){const i=this.rangeIndex.get(t);if(!(!i||i.size===0))for(const[n,c]of i)x([n],s)&&this.dropKeys(c,e)}collectAndDrop(t,s){const e=this.tableIndex.get(t);e&&this.dropKeys(e,s)}dropKeys(t,s){for(const e of t){const i=this.entries.get(e);i&&(this.dropEntry(e,i),s.push(e))}}dropEntry(t,s){this.entries.delete(t),this.totalBytes-=s.bytes;for(const e of s.deps){const i=this.tableIndex.get(e);i&&(i.delete(t),i.size===0&&this.tableIndex.delete(e))}for(const e of s.ranges){const i=this.rangeIndex.get(e.table),n=i?.get(e);n?.delete(t),i&&n?.size===0&&(i.delete(e),i.size===0&&this.rangeIndex.delete(e.table))}}evict(){if(!(this.entries.size<=this.maxEntries&&this.totalBytes<=this.maxBytes))for(const[t,s]of this.entries){if(this.entries.size<=this.maxEntries&&this.totalBytes<=this.maxBytes)return;s.subscribers.size>0||(this.dropEntry(t,s),this.evictions+=1)}}}const D=(o,t,s)=>`${s??"\0anon"}\0${o}:${y(t)}`;export{A as ReactiveCache,D as reactiveCacheKey,K as stableStringify,y as stableWireKey};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const r="*scan",t=(e,c)=>`${e}:${c}`,o=e=>{const c=e.indexOf(":");return c===-1?e:e.slice(0,c)},s=()=>{const e=new Set;return{collect(){return e},recordRead(c,n){e.add(t(c,n))}}};export{r as SCAN_DEP,s as createDependencyTracker,t as depKey,o as tableFromDepKey};
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import{sql as t}from"drizzle-orm";import{runDrizzle as a}from"./runDrizzle-2ULFQR_k.mjs";const o="__schedule_outbox",_=e=>{a(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(o)} (
|
|
2
|
+
id TEXT PRIMARY KEY,
|
|
3
|
+
envelope_json TEXT NOT NULL,
|
|
4
|
+
attempts INTEGER NOT NULL,
|
|
5
|
+
next_attempt_at REAL NOT NULL,
|
|
6
|
+
created_at REAL NOT NULL,
|
|
7
|
+
dead INTEGER NOT NULL DEFAULT 0
|
|
8
|
+
)`),a(e,t`CREATE INDEX IF NOT EXISTS ${t.identifier(`${o}_due`)} ON ${t.identifier(o)} (dead, next_attempt_at)`)},p=(e,d,E,n)=>{a(e,t`INSERT OR REPLACE INTO ${t.identifier(o)} (id, envelope_json, attempts, next_attempt_at, created_at, dead)
|
|
9
|
+
VALUES (${d}, ${E}, 0, ${n}, ${n}, 0)`)},s=(e,d)=>{a(e,t`DELETE FROM ${t.identifier(o)} WHERE id = ${d}`)},u=(e,d,E)=>a(e,t`SELECT id, envelope_json, attempts, next_attempt_at FROM ${t.identifier(o)}
|
|
10
|
+
WHERE dead = 0 AND next_attempt_at <= ${d}
|
|
11
|
+
ORDER BY next_attempt_at ASC LIMIT ${E}`).toArray().map(i=>({attempts:i.attempts,envelopeJson:i.envelope_json,id:i.id,nextAttemptAt:i.next_attempt_at})),c=(e,d,E,n)=>{a(e,t`UPDATE ${t.identifier(o)} SET attempts = ${E}, next_attempt_at = ${n} WHERE id = ${d}`)},O=(e,d,E)=>{a(e,t`UPDATE ${t.identifier(o)} SET attempts = ${E}, dead = 1 WHERE id = ${d}`)},N=e=>{const E=a(e,t`SELECT MIN(CASE WHEN dead = 0 THEN next_attempt_at END) AS due, COUNT(*) AS total FROM ${t.identifier(o)}`).toArray()[0];return{dueAt:E?.due??void 0,populated:(E?.total??0)>0}},m=(e,d)=>{a(e,t`DELETE FROM ${t.identifier(o)} WHERE dead = 1 AND created_at < ${d}`)};export{o as SCHEDULE_OUTBOX_TABLE,c as deferScheduleOutbox,s as forgetScheduleOutbox,_ as migrateScheduleOutbox,O as parkScheduleOutbox,N as probeScheduleOutbox,u as readDueScheduleOutbox,p as recordScheduleOutbox,m as trimScheduleOutbox};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import{quoteIdentifier as i}from"./quoteIdentifier-CObIFRhb.mjs";import{runSql as n}from"./runDrizzle-2ULFQR_k.mjs";const p="__lunora_schema_history",c=50,e=i(p),E=t=>({appliedAt:typeof t.applied_at=="number"?t.applied_at:0,hash:typeof t.hash=="string"?t.hash:"",seq:typeof t.seq=="number"?t.seq:0}),a=t=>{n(t,`CREATE TABLE IF NOT EXISTS ${e} (
|
|
2
|
+
hash TEXT PRIMARY KEY,
|
|
3
|
+
seq INTEGER NOT NULL,
|
|
4
|
+
snapshot_json TEXT NOT NULL,
|
|
5
|
+
applied_at INTEGER NOT NULL
|
|
6
|
+
)`)},S=t=>{n(t,`DELETE FROM ${e} WHERE hash NOT IN (SELECT hash FROM ${e} ORDER BY seq DESC LIMIT ?)`,c)},I=(t,s,r,h=Date.now())=>{if(s===""||r==="")return!1;try{if(a(t),n(t,`SELECT hash FROM ${e} WHERE hash = ? LIMIT 1`,s).toArray().length>0)return!1;const[o]=n(t,`SELECT COALESCE(MAX(seq), 0) + 1 AS next FROM ${e}`).toArray(),T=typeof o?.next=="number"?o.next:1;return n(t,`INSERT INTO ${e} (hash, seq, snapshot_json, applied_at) VALUES (?, ?, ?, ?) ON CONFLICT(hash) DO NOTHING`,s,T,r,h),S(t),!0}catch{return!1}},_=t=>{try{return a(t),n(t,`SELECT hash, seq, applied_at FROM ${e} ORDER BY seq DESC`).toArray().map(s=>E(s))}catch{return[]}},u=(t,s)=>{try{a(t);const[r]=n(t,`SELECT hash, seq, applied_at, snapshot_json FROM ${e} WHERE hash = ? LIMIT 1`,s).toArray();return r===void 0?void 0:{...E(r),snapshotJson:typeof r.snapshot_json=="string"?r.snapshot_json:""}}catch{return}};export{c as SCHEMA_HISTORY_MAX_VERSIONS,_ as readSchemaHistory,u as readSchemaVersion,I as recordSchemaVersion};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{S as t,m as S,r as c,a as i,w as s}from"./ctx-db-search-state-ruTuCsxa.mjs";import"./runDrizzle-2ULFQR_k.mjs";export{t as SEARCH_STATE_TABLE,S as migrateSearchState,c as readSearchBackfillState,i as readSearchIndexCoverage,s as writeSearchBackfillState};
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import{sql as o}from"drizzle-orm";import{runDrizzle as s}from"./runDrizzle-2ULFQR_k.mjs";import{WORKERD_SQLITE_LIMITS as d}from"./param-DlozcSQu.mjs";const c="__shape_poke_cursor",L=r=>{s(r,o`CREATE TABLE IF NOT EXISTS ${o.identifier(c)} (
|
|
2
|
+
connection_id TEXT NOT NULL,
|
|
3
|
+
sub_id TEXT NOT NULL,
|
|
4
|
+
cursor INTEGER NOT NULL,
|
|
5
|
+
PRIMARY KEY (connection_id, sub_id)
|
|
6
|
+
)`)},N=(r,e,n)=>s(r,o`SELECT cursor FROM ${o.identifier(c)} WHERE connection_id = ${e} AND sub_id = ${n} LIMIT 1`).toArray()[0]?.cursor,a=(r,e,n,i)=>{s(r,o`INSERT INTO ${o.identifier(c)} (connection_id, sub_id, cursor) VALUES (${e}, ${n}, ${i})
|
|
7
|
+
ON CONFLICT(connection_id, sub_id) DO UPDATE SET cursor = excluded.cursor`)},T=3,R=(r,e)=>{const n=Math.floor(d.boundParams/T);for(let i=0;i<e.length;i+=n){const E=e.slice(i,i+n),u=o.join(E.map(t=>o`(${t.connectionId}, ${t.subId}, ${t.cursor})`),o`, `);s(r,o`INSERT INTO ${o.identifier(c)} (connection_id, sub_id, cursor) VALUES ${u}
|
|
8
|
+
ON CONFLICT(connection_id, sub_id) DO UPDATE SET cursor = excluded.cursor`)}},$=r=>s(r,o`SELECT MIN(cursor) AS cursor FROM ${o.identifier(c)}`).toArray()[0]?.cursor??void 0,C=(r,e,n)=>{s(r,o`DELETE FROM ${o.identifier(c)} WHERE connection_id = ${e} AND sub_id = ${n}`)},I=(r,e)=>{s(r,o`DELETE FROM ${o.identifier(c)} WHERE connection_id = ${e}`)};export{c as SHAPE_POKE_CURSOR_TABLE,C as deleteShapePokeCursor,I as deleteShapePokeCursorsForConnection,L as migrateShapePokeCursor,$ as minShapePokeCursor,N as readShapePokeCursor,a as writeShapePokeCursor,R as writeShapePokeCursors};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{stableWireKey as o}from"./stableWireKey-D2US4k_J.mjs";const s=r=>r.map(e=>`${String(e.length)}:${e}`).join(""),c=r=>o(r.effectiveWhere??null),g=(r,e,t)=>s([r,String(e),String(t)]),h=(r,e)=>{try{return s([c(r),e])}catch{return}};class d{keyScans=new Map;memberProbes=new Map;run=0;served=0;get probesRun(){return this.run}get probesServed(){return this.served}changedKeys(e,t){return this.getOrLoad(this.keyScans,e,t)}members(e,t,n){return this.getOrLoad(this.memberProbes,h(e,t),n)}getOrLoad(e,t,n){if(t!==void 0){const a=e.get(t);if(a!==void 0)return this.served+=1,a}this.run+=1;const i=n();return t!==void 0&&e.set(t,i),i}}const p=()=>new d,b=(r,e)=>{try{return s([r.table,c(r),o({identity:e.identity,userId:e.userId})])}catch{return}};export{d as ShapeDiffCache,p as createShapeDiffCache,b as globalShapeReadKey,g as shapeRangeKey};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
class r{shardHost;socketHost;options;constructor(t,s,e={}){this.shardHost=t,this.socketHost=s,this.options=e}get shardKey(){return this.shardHost.shardKey}socketFor(t){return this.socketHost.handleFor(t)??t}sockets(t){return this.socketHost.getSockets(t)}background(t){return this.shardHost.waitUntil===void 0?!1:(this.shardHost.waitUntil(t),!0)}async runInTransaction(t){return this.shardHost.runSerialized(async()=>this.shardHost.transaction(t))}async handleFetch(t){return this.options.handlers?.handleFetch?this.options.handlers.handleFetch(t):new Response("Not implemented",{status:501})}async handleAlarm(){this.options.handlers?.handleAlarm&&await this.options.handlers.handleAlarm()}}export{r as ShardRunner};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const d=()=>{const n=new Set,t=new Map,s=new Set;return{onRead(e){n.add(e),s.add(e)},onReadRange(e){n.add(e.table);const o=t.get(e.table);o?o.push(e):t.set(e.table,[e])},ranges(){for(const e of s)t.delete(e);return t.size>0?t:void 0},tables:n}},u="!unvouchable",i=(n,t,s)=>{if(!t)return n;const e=new Set(s);return new Proxy(n,{get(o,a,r){const c=Reflect.get(o,a,r);return typeof c!="function"||typeof a!="string"||!e.has(a)?c:(...l)=>(t(u),Reflect.apply(c,o,l))}})};export{u as UNVOUCHABLE_DEP,d as createReadFootprint,i as markUnvouchableReads};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as g}from"@lunora/errors";import{e as i}from"./wire-codec-C-FpWm52.mjs";const a=BigInt(Number.MAX_SAFE_INTEGER),c=(e,t)=>e<t?-1:e>t?1:0,m=(e,t)=>`${e}__agg_${t}`,l=e=>{if(typeof e=="bigint"){if(e>a||e<-a)throw new g("BAD_REQUEST",`bigint ${e.toString()} exceeds Number.MAX_SAFE_INTEGER, so an aggregateIndex declared over this column cannot tally it exactly (the companion's value column is a REAL) — drop the aggregateIndex, aggregate a narrower column, or read the rows and reduce them in the handler`);return Number(e)}if(typeof e=="number")return Number.isFinite(e)?e:void 0},v=(e,t,n,u)=>{const r=e.get(t)??{count:0,value:null};if(n.op==="count"){r.count+=1,r.value=r.count,e.set(t,r);return}const o=l(u[n.field??""]);if(n.op==="sum"||n.op==="avg"){o!==void 0&&(r.value=(r.value??0)+o,r.count+=1),e.set(t,r);return}r.count+=1,o!==void 0&&(r.value===null?r.value=o:r.value=n.op==="min"?Math.min(r.value,o):Math.max(r.value,o)),e.set(t,r)},d=(e,t)=>e==="count"?t?.value??0:!t||t.count===0?null:e==="avg"?t.value===null?null:t.value/t.count:t.value,A=(e,t)=>{if(e.length===0)return"";const n={};for(const u of e.toSorted(c))n[u]=t[u]??null;return JSON.stringify(i(n))};export{m as aggregateTableName,l as coerceAggregateNumber,c as compareStrings,A as encodeAggregateKey,v as foldAggregateTally,d as readAggregateValue};
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import{sql as e}from"drizzle-orm";import{runDrizzle as E}from"./runDrizzle-2ULFQR_k.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};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as D}from"@lunora/errors";import{applySelect as I}from"./CURSOR_PREFIX-Bn8SFoGd.mjs";const W=Symbol.for("lunora.relations.fanOutBudget"),U=o=>({fanOutBudget:o[W],relationBaseWhere:o.relationBaseWhere,relationMask:o.relationMask}),A=(o,n)=>n.select?I(o,n.select,n.with):o,x=async(o,n,r,a,t)=>{const l=await Promise.all(a.map(async i=>{const h=t?{AND:[{[r]:i},t]}:{[r]:i};return[i,await o(n,h)]}));return new Map(l)},S=32,C=(o,n,r)=>{const a=new Map;for(const t of o)for(const l of r(t)){const i=l[n],h=a.get(i);h?h.push(l):a.set(i,[l])}return a},_=(o,n)=>({...o,[W]:n}),B=(o,n)=>{const r=new Set;for(const a of o){const t=a[n];t!=null&&r.add(t)}return[...r]},H=async o=>{const{groupedCounter:n,fanOutBudget:r,fetcher:a,parents:t,relationBaseWhere:l,relationMask:i,schema:h,tableName:m,with:v}=o,w=r??{remaining:S},k=(c,e)=>i?.(c,e)??e;if(t.length===0)return;const N=h.tables[m];if(!N)throw new D("INTERNAL",`unknown table: ${m}`);const O=N.relationMap??{},R=c=>{const e=O[c];if(!e)throw new D("INTERNAL",`unknown relation "${c}" on table "${m}"`);return e},V=async(c,e,s)=>{const u=B(t,e.field);if(u.length===0){for(const d of t)d[c]=null;return}const{page:p}=await a(e.table,_({baseWhere:l?.(e.table),relationBaseWhere:l,relationMask:i,where:{[e.references]:{in:u}},with:s.with},w)),b=new Map;for(const d of k(e.table,p))b.set(d[e.references],d);for(const d of t){const y=b.get(d[e.field]);d[c]=y?A([y],s)[0]??null:null}},$=async(c,e,s)=>{const u=B(t,e.references);if(u.length===0){for(const f of t)f[c]=[];return}const p=typeof s.limit=="number"?Math.max(0,Math.floor(s.limit)):void 0,b=async(f,g)=>{const{page:E}=await a(e.table,_({baseWhere:l?.(e.table),limit:g,orderBy:s.orderBy,relationBaseWhere:l,relationMask:i,where:s.where?{AND:[s.where,f]}:f,with:s.with},w));return E};if(p===0){for(const f of t)f[c]=[];return}const d=p!==void 0&&u.length<=w.remaining;d&&(w.remaining-=u.length);const y=d?await Promise.all(u.map(async f=>b({[e.field]:f},p))):[await b({[e.field]:{in:u}},void 0)],M=C(y,e.field,f=>k(e.table,f));for(const f of t){const g=M.get(f[e.references])??[];f[c]=A(p===void 0?g:g.slice(0,p),s)}},j=async c=>{for(const e of Object.keys(c)){const s=R(e),[u,p]=s.kind==="many"?[s.field,s.references]:[s.references,s.field],b=l?.(s.table),d=B(t,p),y=d.length===0?new Map:await n(s.table,u,d,b);for(const M of t){const f=M._count??{},g=M[p];f[e]=g==null?0:y.get(g)??0,M._count=f}}};for(const[c,e]of Object.entries(v)){if(e===void 0||e===!1)continue;if(c==="_count"){await j(e);continue}const s=R(c),u=e===!0?{}:e;await(s.kind==="one"?V(c,s,u):$(c,s,u))}},F=async(o,n,r)=>{const{deletedId:a,deletedReference:t,findHolders:l,onCascade:i,onRestrict:h,onSetNull:m,tableName:v}=o,w=r.references==="_id"?a:t(r.references);if(w==null)return;const k=await l(n,r.field,w);if(k.length!==0){r.onDelete==="restrict"&&h(`cannot delete "${v}" row: "${n}.${r.field}" still references it`);for(const N of k){const O=N._id;typeof O=="string"&&await(r.onDelete==="cascade"?i(n,O):m(n,O,r.field))}}},P=async o=>{const{schema:n,tableName:r}=o;if(!n.tables[r])throw new D("INTERNAL",`unknown table: ${r}`);for(const[a,t]of Object.entries(n.tables)){const l=t.relationMap;if(l)for(const i of Object.values(l))i.kind!=="one"||i.table!==r||!i.onDelete||await F(o,a,i)}},q=(o,n,r=!1)=>{for(const[a,t]of Object.entries(o.shape))a in n&&typeof t.parse=="function"&&(r&&n[a]===null&&t.kind==="optional"||t.parse(n[a]))};export{P as applyOnDelete,B as distinctValues,x as fanOutScalarCounts,U as relationHooks,H as resolveWith,q as runRowValidators};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import{sql as s}from"drizzle-orm";import{runDrizzle as d}from"./runDrizzle-2ULFQR_k.mjs";const m=16,v=32,R=1e4,l=1e3,p=e=>String(e).padStart(m,"0"),u=e=>`cdc/${encodeURIComponent(e.shard)}/${encodeURIComponent(e.epoch)}/`,S=(e,o)=>`${u(e)}${p(o)}.json`,E="__cdc_archive",g=e=>{d(e,s`CREATE TABLE IF NOT EXISTS ${s.identifier(E)} (
|
|
2
|
+
id INTEGER PRIMARY KEY CHECK (id = 1),
|
|
3
|
+
seq INTEGER NOT NULL
|
|
4
|
+
)`)},L=e=>(g(e),d(e,s`SELECT seq FROM ${s.identifier(E)} WHERE id = 1`).toArray()[0]?.seq??0),$=(e,o)=>{g(e),d(e,s`INSERT INTO ${s.identifier(E)} (id, seq) VALUES (1, ${o}) ON CONFLICT (id) DO UPDATE SET seq = ${o}`)},q=async(e,o,t)=>{const n=t[0]?.seq,r=t.at(-1)?.seq;n===void 0||r===void 0||await e.put(S(o,r),JSON.stringify({changes:t,from:n,to:r}),{httpMetadata:{contentType:"application/json"}})},_=e=>{let o;try{o=JSON.parse(e)}catch{return}if(typeof o!="object"||o===null)return;const t=o;return typeof t.from=="number"&&typeof t.to=="number"&&Array.isArray(t.changes)?t:void 0},y=(e,o)=>{const t=[];for(const n of e.changes)if(!(n.seq<=o)){if(n.op!=="delete"&&n.doc===void 0)break;t.push(n)}return t},I=(e,o,t)=>{let n=t;for(const r of o){if(r.seq!==n+1)break;e.push(r),n=r.seq}return n},N=async(e,o)=>{const t=await e.get(o);return t===null?void 0:_(await t.text())},w=async(e,o,t,n)=>{const r=u(o),h=Math.max(1,Math.min(n??l,R)),A=await e.list({limit:v,prefix:r,startAfter:`${r}${p(t)}.json`}),c=[];let i=t;for(const C of A.objects){const a=await N(e,C.key);if(a===void 0)break;const T=y(a,i);if(i=I(c,T,i),c.length>=h||i!==a.to)break}if(c[0]?.seq!==t+1)return;const f=c.slice(0,h);return{changes:f,cursor:f.at(-1)?.seq??t}};export{q as archiveCdcSegment,w as readArchivedCdcChanges,L as readCdcArchivedThrough,$ as writeCdcArchivedThrough};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as a}from"@lunora/errors";const t=()=>Object.assign(new Error("native PITR is unavailable here (local dev or a non-SQLite Durable Object); use `lunora backup restore` for off-platform recovery"),{code:"PITR_UNAVAILABLE",name:"LunoraError",status:409}),i=o=>{if(typeof o=="number")return o;const r=Date.parse(o);if(Number.isNaN(r))throw new a("BAD_REQUEST",`pitr: invalid time "${o}" — expected epoch-ms or an ISO timestamp`);return r},
|
|
1
|
+
import{LunoraError as a}from"@lunora/errors";const t=()=>Object.assign(new Error("native PITR is unavailable here (local dev or a non-SQLite Durable Object); use `lunora backup restore` for off-platform recovery"),{code:"PITR_UNAVAILABLE",name:"LunoraError",status:409}),i=o=>{if(typeof o=="number")return o;const r=Date.parse(o);if(Number.isNaN(r))throw new a("BAD_REQUEST",`pitr: invalid time "${o}" — expected epoch-ms or an ISO timestamp`);return r},k=async(o,r)=>{if(!o.getCurrentBookmark)throw t();const e=await o.getCurrentBookmark();return r===void 0||!o.getBookmarkForTime?{current:e}:{current:e,forTime:await o.getBookmarkForTime(i(r))}},s=async(o,r)=>{if(!o.onNextSessionRestoreBookmark)throw t();let e=r.bookmark;if(e===void 0){if(r.time===void 0)throw new a("BAD_REQUEST","pitrRestore: provide a `bookmark` or a `time` to restore to");if(!o.getBookmarkForTime)throw t();e=await o.getBookmarkForTime(i(r.time))}const n=await o.onNextSessionRestoreBookmark(e);return{restoredTo:e,undoBookmark:n}};export{s as armRestore,k as readBookmark};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{stableStringify as m}from"./stableStringify-DibjylKD.mjs";import{i as A,e as w,n as J}from"./wire-codec-C-FpWm52.mjs";const D="_id",p="_creationTime",y="page",_=e=>{let t;for(const s of e){const o=s[p];if(typeof o=="number"){if(t!==void 0){if(o<t)return!0;if(o>t)return!1}t=o}}return!1},F=(e,t)=>{const s=t[p];if(typeof s!="number")return e.length;const o=_(e);for(const[n,r]of e.entries()){const i=r[p];if(typeof i=="number"&&(o?i<s:i>s))return n}return e.length},L="__lunora__",E=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return;const t=e[D];return typeof t=="string"?t:void 0},I=e=>{const t=new Map,s=[];for(const o of e){const n=E(o);if(n===void 0||t.has(n))return;t.set(n,o),s.push(n)}return{byId:t,order:s}},N=(e,t)=>{const s=e.order.filter(n=>t.byId.has(n)),o=t.order.filter(n=>e.byId.has(n));return s.length!==o.length?!1:s.every((n,r)=>o[r]===n)},R=(e,t,s,o)=>{const n=[];for(const r of e.order)t.byId.has(r)||n.push({delta:{key:r,op:"delete",table:s},frame:`{"key":${JSON.stringify(r)},"op":"delete","table":${o}}`});return n},P=(e,t,s,o)=>{const n=[];for(const r of t.order){const i=t.byId.get(r),a=e.byId.get(r),d=JSON.stringify(J(i)?w(i):i),c=a===void 0?void 0:JSON.stringify(a);if(c===d)continue;const f=c===void 0?"insert":"update";n.push({delta:{key:r,op:f,row:i,table:s},frame:`{"key":${JSON.stringify(r)},"op":"${f}","row":${d},"table":${o}}`})}return n},T=(e,t)=>{if(Array.isArray(e)&&Array.isArray(t))return{next:t,previous:e};if(!A(e)||!A(t))return;const s=e[y],o=t[y];if(!Array.isArray(s)||!Array.isArray(o))return;const n=r=>Object.fromEntries(Object.entries(r).filter(([i])=>i!==y));if(m(n(e))===m(w(n(t))))return{next:o,previous:s}},k=(e,t,s)=>{const o=s.filter(({delta:r})=>r.op==="insert");if(o.length===0)return!0;const n=e.order.filter(r=>t.byId.has(r)).map(r=>e.byId.get(r));for(const{delta:r}of o){const i=r.row;n.splice(F(n,i),0,i)}return n.length===t.order.length&&n.every((r,i)=>r[D]===t.order[i])},O=(e,t,s)=>{let o;try{o=JSON.parse(e)}catch{return}const n=T(o,t);if(n===void 0)return;const r=I(n.previous),i=I(n.next);if(r===void 0||i===void 0||!N(r,i))return;const a=s===""?L:s,d=JSON.stringify(a),c=[...R(r,i,a,d),...P(r,i,a,d)];return k(r,i,c)?c:void 0},W=(e,t,s,o)=>{const n=O(e,t,s);if(n!==void 0){if(o!==void 0)for(const{frame:r}of n)o.push(r);return n.map(({delta:r})=>r)}},C=(e,t)=>{try{return e.send(t),!0}catch{return!1}},K=e=>{const{cursorSuffix:t,lastMutationId:s,nextResult:o,pageDeltas:n,previousJson:r,snapshotJson:i,subId:a,table:d}=e,c=JSON.stringify(a),f=s===void 0?"":`,"lastMutationId":${String(s)}`,g=f+t,l=`{"type":"data","id":${c},"data":${i}${g}}`,u=r!==void 0&&(n===!0||Array.isArray(o))?O(r,o,d):void 0;if(u===void 0||u.length===0)return[l];const v=[];let b=0;for(const[$,{frame:x}]of u.entries()){const S=$===u.length-1,h=`{"type":"delta","id":${c},"delta":${x}${S?g:f}}`;if(b+=h.length,b>=l.length)return[l];v.push(h)}return v},G=async e=>{let t=0;for(;t<100;){t+=1;const{bufferedAmount:s}=e;if(typeof s!="number"||s<1048576)return;await new Promise(o=>{setTimeout(o,20)})}};export{G as awaitWsDrain,K as subscriptionFrames,W as subscriptionListDeltas,C as trySendFrame};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{m as O,c as T,l as b,r as E,a as C,w as L}from"./ctx-db-search-state-ruTuCsxa.mjs";import{S as R,r as M,i as x,l as h,y as _,d as y}from"./ctx-db-companions-DsNfXSbb.mjs";import{sql as t}from"drizzle-orm";import{matchesStaticWhere as F}from"./AGGREGATE_SQL_FUNCTION-DDEoMnJR.mjs";import{aggregateTableName as N,encodeAggregateKey as D,foldAggregateTally as v}from"./aggregateTableName-C7o-gpms.mjs";import{runDrizzle as l}from"./runDrizzle-2ULFQR_k.mjs";import{i as w,r as p,a as B,b as G,A as U,D as I,h as H}from"./do-sql-kpl5Kt1j.mjs";import{isLiveForCompanion as P}from"./CURSOR_PREFIX-Bn8SFoGd.mjs";import{rankTableName as W,matchesRankStaticWhere as V}from"./RANK_TIEBREAK-D5xNdzB3.mjs";const k=(e,o)=>l(e,t`SELECT COUNT(*) AS count FROM ${t.identifier(o)}`).one().count>0,Y=(e,o)=>l(e,t`SELECT 1 FROM ${t.identifier(o)} LIMIT 1`).toArray().length>0,A=(e,o)=>l(e,t`SELECT id, _creationTime, ${t.identifier(I)} FROM ${t.identifier(o)}`).toArray(),j=(e,o,n,r)=>{const i=N(o,n.name);if(k(e,i))return;const c=n.by??[],a=new Map,s=A(e,o);for(const d of s){const f=p(d);if(!f||!P(f,r)||n.where&&!F(f,n.where))continue;const g=D(c,f);v(a,g,n,f)}for(const[d,f]of a)l(e,t`INSERT INTO ${t.identifier(i)} (${B}, ${G}, ${U}) VALUES (${d}, ${f.value}, ${f.count})`)},te=(e,o)=>{for(const[n,r]of Object.entries(o.tables))if(!(r.shardMode?.kind==="global"||!r.aggregateIndexes))for(const i of r.aggregateIndexes)j(e,n,i,r.softDeleteMode?.field)},K=(e,o,n)=>{const r=W(o,n.name);if(k(e,r))return;const i=M(n),c=A(e,o);for(const a of c){const s=p(a);!s||n.where&&!V(s,n.where)||x(e,r,n,i,s._id,s)}},ie=(e,o)=>{for(const[n,r]of Object.entries(o.tables))if(!(r.shardMode?.kind==="global"||!r.rankIndexes))for(const i of r.rankIndexes)K(e,n,i)},u=500,$=(e,o,n)=>{const r=R(o,n.name),i=T(n),c=b(E(e,r),i);if(c.finished)return{done:!0,rows:0};const{cursor:a}=c,s=l(e,a===void 0?t`SELECT id, _creationTime, ${t.identifier(I)} FROM ${t.identifier(o)} ORDER BY id ASC LIMIT ${t.raw(String(u))}`:t`SELECT id, _creationTime, ${t.identifier(I)} FROM ${t.identifier(o)} WHERE id > ${a} ORDER BY id ASC LIMIT ${t.raw(String(u))}`).toArray();let d=a;for(const g of s){const{id:m}=g;if(typeof m!="string")continue;d=m,l(e,t`DELETE FROM ${t.identifier(r)} WHERE ${t.identifier(h)} = ${m}`);const S=H(g);S&&l(e,t`INSERT INTO ${t.identifier(r)} (${t.identifier(_)}, ${t.identifier(h)}) VALUES (${y(S,n)}, ${m})`)}const f=s.length<u;return L(e,r,d,f,i),{done:f,rows:s.length}},ae=(e,o,n)=>{const r=R(o,n.name),i=T(n);return b(E(e,r),i).finished?!0:C(e,r)},se=(e,o,n)=>{if(w(e))for(const r of n.searchIndexes??[])r.staged&&Y(e,o)||$(e,o,r)},z=(e,o,n,r)=>{let i=0;for(;;){if(i>=r)return{done:!1,pages:i};const c=$(e,o,n);if(c.rows>0&&(i+=1),c.done)return{done:!0,pages:i}}},ce=(e,o,n={})=>{if(!w(e))return{done:!0,pages:0};O(e);const r=n.maxPages??Number.POSITIVE_INFINITY;let i=0;for(const[c,a]of Object.entries(o.tables))if(!(a.shardMode?.kind==="global"||!a.searchIndexes))for(const s of a.searchIndexes){const d=z(e,c,s,r-i);if(i+=d.pages,!d.done)return{done:!1,pages:i}}return{done:!0,pages:i}};export{te as backfillAggregateIndexes,ie as backfillRankIndexes,ce as backfillSearchIndexes,se as backfillSearchIndexesForTable,ae as searchIndexCoversTable};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const o=r=>{let n="";for(let t=0;t<r.length;t+=32768)n+=String.fromCharCode(...r.subarray(t,t+32768));return btoa(n)},a=r=>{const n=atob(r),e=new Uint8Array(n.length);for(let t=0;t<n.length;t+=1)e[t]=n.codePointAt(t)??0;return e};export{a as f,o as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{f as m}from"./sql-projection-D3qdaItY.mjs";const a="!",l="",d=void 0,w=t=>{const o=new TextEncoder().encode(t);let r="";for(const e of o)r+=e.toString(16).padStart(2,"0");return r},v=t=>t===null?"0":typeof t=="number"?Number.isFinite(t)?`1${m(t)}`:d:typeof t=="string"?`2${w(t)}`:d,x=t=>{const o=[];for(const r of t){const e=v(r);if(e===d)return d;o.push(e)}return o.join(a)},E="=",h=new Set([">",">="]),y=new Set(["<","<="]),g=(t,o,r,e)=>{const i=o.comparator===E,n=h.has(o.comparator)||y.has(o.comparator);return!i&&!n||t.indexOf(o.field)!==r?!1:e===void 0?!0:!i&&e===o.field},S=(t,o,r)=>{const e={equalities:[],lowerExclusive:!1,upperExclusive:!1};let i;for(const n of o){const s=n.comparator===E,c=h.has(n.comparator);if(!g(t,n,e.equalities.length,i))return;if(s){e.equalities.push(r(n.value));continue}if(i=n.field,c){if(e.lower!==void 0)return;e.lower=r(n.value),e.lowerExclusive=n.comparator===">"}else{if(e.upper!==void 0)return;e.upper=r(n.value),e.upperExclusive=n.comparator==="<"}}return e},p=(t,o)=>{const r=v(o);if(r!==void 0)return t===""?r:t+a+r},q=(t,o,r,e,i)=>{if(r.length===0)return;const n=S(r,e,i);if(!n)return;const s=x(n.equalities);if(s===void 0)return;let c=s,f=s+l;if(n.lower!==void 0){const u=p(s,n.lower);if(u===void 0)return;c=n.lowerExclusive?u+a+l:u}if(n.upper!==void 0){const u=p(s,n.upper);if(u===void 0)return;f=n.upperExclusive?u:u+l}if(!(c>=f))return{hi:f,index:o,lo:c,table:t}},R=(t,o,r)=>{const e=[];for(const i of t){const n=x(i.fields.map(s=>r(o[s])));n!==void 0&&e.push({index:i.name,key:n})}return e},b=(t,o)=>t.index===o.index&&o.key>=t.lo&&o.key<t.hi,T=(t,o)=>{if(!t||t.length===0||!o||o.length===0)return!0;const r=new Map;for(const e of o){const i=r.get(e.index);i?i.push(e):r.set(e.index,[e])}return t.some(e=>{const i=r.get(e.index);return!i||i.length===0?!0:i.some(n=>b(e,n))})};export{q as buildIndexRange,R as indexKeysForRow,T as keysTouchRanges,b as rangeContains};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{e as h}from"./wire-codec-C-FpWm52.mjs";const u=(t,e)=>{if(!e)return t;const a=Object.create(null);for(const s of["_id","_creationTime",...e])Object.hasOwn(t,s)&&(a[s]=t[s]);return a},y=(t,e,a)=>{const{columns:s,table:p}=a,i=new Map,c=[];for(const{doc:n,id:r}of t){const o=u(n,s),d=JSON.stringify(h(o));i.set(r,d);const f=e.get(r);f===void 0?c.push({key:r,op:"insert",table:p,value:o}):f!==d&&c.push({key:r,op:"update",table:p,value:o})}for(const n of e.keys())i.has(n)||c.push({key:n,op:"delete",table:p});return{next:i,rowsPatch:c}},k=t=>t.map(e=>e.value===void 0?e:{...e,value:h(e.value)}),b=(t,e,a={})=>{const{baseCheckpoint:s,checkpoint:p,epoch:i,lastMutationId:c,pokeId:n}=e,r=[JSON.stringify({baseCheckpoint:s,epoch:i,pokeId:n,type:"pokeStart"})];for(const o of t){const d=a.preEncoded?o.rowsPatch:k(o.rowsPatch),f=o.baseCheckpoint??s;r.push(JSON.stringify({pokeId:n,rowsPatch:d,shapeId:o.shapeId,type:"pokePart",...c===void 0?{}:{lastMutationId:c},...f===void 0?{}:{baseCheckpoint:f},...o.reset===!0?{reset:!0}:{}}))}return r.push(JSON.stringify({checkpoint:p,epoch:i,pokeId:n,type:"pokeEnd"})),r};export{b as buildPokeFrames,y as diffGlobalMembership,k as encodeRowsPatch,u as projectColumns};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{quoteIdentifier as l}from"./quoteIdentifier-CObIFRhb.mjs";import{reprojectionMigrationTable as u}from"./REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{REPROJECTION_MIGRATION_PREFIX as v,reprojectionMigrationId as w}from"./REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{e as m}from"./wire-codec-C-FpWm52.mjs";import{runSql as p}from"./runDrizzle-2ULFQR_k.mjs";import{k as d,D as E}from"./do-sql-kpl5Kt1j.mjs";import{m as g}from"./sql-projection-D3qdaItY.mjs";const b=m(0n)[0],_=e=>e.shardMode?.kind==="global"?[]:Object.entries(e.shape).filter(([,r])=>g(r)).map(([r])=>r),M=e=>Object.entries(e.tables).filter(([,r])=>_(r).length>0).map(([r])=>r),f=e=>{const r=`json_each(${l(E)}) AS __f__`;return{params:[JSON.stringify(e),b,"bigint","bytes"],sql:`EXISTS (SELECT 1 FROM ${r} WHERE __f__.type = 'array' AND __f__.key IN (SELECT value FROM json_each(?)) AND json_extract(__f__.value, '$[0]') = ? AND json_extract(__f__.value, '$[1]') IN (?, ?))`}},N=(e,r,o)=>{if(o.length===0)return 0;const{params:t,sql:n}=f(o);return p(e,`SELECT COUNT(*) AS count FROM ${l(r)} WHERE ${n}`,...t).toArray()[0]?.count??0},R=(e,r,o,t)=>{const{params:n,sql:i}=f(o);return p(e,`SELECT 1 FROM ${l(r)} WHERE id = ? AND (${i}) LIMIT 1`,t,...n).toArray().length>0},S=(e,r,o)=>{const t=u(e);if(t===void 0)return;const n=r.tables[t];if(!n)return;const i=_(n);if(i.length!==0)return{id:e,table:t,up:s=>{const a=s._id;if(!(typeof a!="string"||!R(o,t,i,a))){try{d(s)}catch(c){console.warn(`${e}: skipping row ${a} — it cannot be re-projected: ${c instanceof Error?c.message:String(c)}`);return}return s}}}};export{v as REPROJECTION_MIGRATION_PREFIX,S as buildReprojectionMigration,N as countLegacyRows,_ as reprojectableFields,w as reprojectionMigrationId,M as reprojectionTables};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const f=/key|secret|token|password|passwd|credential|private|auth|bearer|session|cookie|salt|signature|dsn|webhook/iu,l=new Set(["LUNORA_ADMIN_TOKEN","LUNORA_WS_BEARER"]),d=["CF_PAGES_URL","WORKER_URL","LUNORA_WORKER_URL"],u=["CF_ENV","ENVIRONMENT","WORKER_ENV","NODE_ENV"],p=n=>n.length<=4?"••••":`${n.slice(0,4)}${"•".repeat(Math.min(8,n.length-4))}`,R=n=>f.test(n),E=n=>{const e=o=>typeof n[o]=="function";return e("idFromName")||e("idFromString")?"durable-object":e("createMultipartUpload")||e("put")&&e("get")&&e("list")&&e("head")?"r2":e("getWithMetadata")?"kv":e("prepare")&&e("dump")?"d1":e("send")&&e("sendBatch")?"queue":e("fetch")&&!e("get")?"service":"object"},N=n=>{if(typeof n!="object"||n===null)return{};const e=n,o=i=>i.map(c=>e[c]).find(c=>typeof c=="string"&&c!==""),t={},r=o(d),s=o(u);r!==void 0&&(t.workerUrl=r),s!==void 0&&(t.environment=s);const a=e.CF_VERSION_METADATA;if(a!==null&&typeof a=="object"){const i=a;typeof i.id=="string"&&(t.deploymentId=i.id),typeof i.tag=="string"&&(t.versionTag=i.tag)}return t},_=/^(?:dev(?:elopment)?|local(?:host)?|test)$/iu,g=n=>{const e=n??{};for(const o of u){const t=e[o];if(typeof t=="string"&&_.test(t))return!0}return!1},v=n=>{const e=n??{},o=[];for(const[t,r]of Object.entries(e))if(!l.has(t)){if(typeof r=="string"){const s=R(t);o.push({kind:s?"secret":"var",name:t,value:p(r)});continue}if(typeof r=="number"||typeof r=="boolean"){o.push({kind:"var",name:t,value:String(r)});continue}if(r!==null&&typeof r=="object"){o.push({bindingType:E(r),kind:"binding",name:t,value:null});continue}o.push({kind:"var",name:t,value:null})}return o.sort((t,r)=>t.name.localeCompare(r.name)),{deploy:N(e),settings:o}};export{E as bindingType,v as buildSettings,g as isDevEnvironment,R as looksSecret,N as readDeployInfo,p as redact};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{readCdcChangeKeys as s}from"./CDC_LOG_TABLE-Bh7SB6Uw.mjs";import{selectShapeMembers as h}from"./selectShapeMembers-B8gTOeOB.mjs";import{shapeRangeKey as u}from"./ShapeDiffCache-gdaILV5E.mjs";import{projectColumns as g}from"./buildPokeFrames-BBE6J91z.mjs";const C=(m,e,a,i,p,f=s)=>{const r=u(e.table,a,i),n=p.changedKeys(r,()=>f(m,e.table,a,i));if(n.length===0)return[];const b=p.members(e,r,()=>h(m,e.table,e.effectiveWhere,n.map(t=>t.id))),o=[];for(const t of n){const c=b.get(t.id);if(c===void 0){t.op!=="insert"&&o.push({key:t.id,op:"delete",table:e.table});continue}o.push({key:t.id,op:t.op,table:e.table,value:g(c,e.columns)})}return o};export{C as buildShapeDiff};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{sql as t}from"drizzle-orm";import{runDrizzle as s}from"./runDrizzle-2ULFQR_k.mjs";const a=r=>r?.memoryMode===!0,l=r=>Object.entries(r.tables).filter(([,e])=>a(e)&&e.shardMode?.kind!=="global").map(([e])=>e),i=(r,e)=>{const o=l(e);for(const m of o)s(r,t`DELETE FROM ${t.identifier(m)}`);return o.length};export{i as clearMemoryTables,a as isMemoryTable,l as memoryTableNames};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"./param-DlozcSQu.mjs";import{c as o,l as t}from"./where-sql-x1YKldcq.mjs";import"./RELATION_EXISTS_KEY-CFUhnZSZ.mjs";export{o as compileWhereSql,t as literalInList};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as g}from"@lunora/errors";import{sql as o}from"drizzle-orm";import{mergeWhere as b}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{SCAN_DEP as j}from"./SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as A}from"./runDrizzle-2ULFQR_k.mjs";import{sqliteInList as O}from"./param-DlozcSQu.mjs";import{decodeCursor as F,CURSOR_PREFIX as P,toBase64 as U}from"./CURSOR_PREFIX-Bn8SFoGd.mjs";import{rankTableName as V,sortColumnName as z,resolveRankPartition as H,RANK_TIEBREAK as _,encodePartitionKey as J,rankPivotConditionSql as X}from"./RANK_TIEBREAK-D5xNdzB3.mjs";const Y="__doc__",G=n=>P+U(JSON.stringify(n)),Q=n=>n.after?[n.after.partitionKey,...n.after.sortValues,n.after.rowId]:n.cursor?F(n.cursor):void 0,Z=(n,r,f)=>{if(n?.length!==1+r.length+1)return;const t=[{column:"__partition__",direction:"asc"}];for(const[c,u]of r.entries())t.push({column:u,direction:f[c]?.direction??"asc"});t.push({column:_,direction:"asc"});const e=[];for(const[c,u]of t.entries()){const d=X(u.column,n[c],u.direction,!0);if(d===void 0)continue;const s=[];for(const[m,l]of t.slice(0,c).entries())s.push(o`${o.identifier(l.column)} IS ${n[m]}`);s.push(d);const[i]=s;e.push(s.length===1&&i!==void 0?i:o`(${o.join(s,o` AND `)})`)}return e.length===0?o`(1 = 0)`:o`(${o.join(e,o` OR `)})`},v=null,oo=(n,r)=>{if(n===void 0)return v;const f=[n.__partition__,...r.map(t=>n[t]),n[_]];return G(f)},no=(n,r,f)=>{const t=[];for(const e of n){const c=e[_];if(typeof c!="string")continue;const u=r.get(c);if(!u)continue;const d=typeof e.__partition__=="string"?e.__partition__:"",s=f.map(i=>e[i]??null);t.push({doc:u,key:{partitionKey:d,rowId:c,sortValues:s}})}return t},to=o`${o.identifier("id")}`,ro=(n,r,f)=>{const{rowToDocument:t}=n,e=new Map;if(f.length===0)return e;const c=A(n.sql,o`SELECT id, _creationTime, ${o.identifier(Y)} FROM ${o.identifier(r)} WHERE ${O(to,f,!1)}`).toArray();for(const u of c){const d=t(u),s=u.id;d&&typeof s=="string"&&e.set(s,d)}return e},_o=(n,r,f,t)=>{const{assertRankPartitionLocal:e,ensureRankBackfilled:c,onRead:u,schema:d}=n,s=d.tables[r];if(!s)throw new g("INTERNAL",`unknown table: ${r}`);const i=s.rankIndexes?.find(a=>a.name===f);if(!i)throw new g("INTERNAL",`unknown rankIndex "${f}" on table "${r}"`);e(r,s,i),u(r,j),c(r,i);const m=V(r,i.name),l=i.sortBy.map((a,w)=>z(w)),h=Math.max(1,Math.min(1e3,Math.floor(t.take??100))),T=b(t.baseWhere,t.where),k=H(i,T),R=[o`${o.identifier("__partition__")} ASC`];for(const[a,w]of l.entries()){const W=i.sortBy[a]?.direction;R.push(o`${o.identifier(w)} ${o.raw(W==="desc"?"DESC":"ASC")}`)}R.push(o`${o.identifier(_)} ASC`);const p=[];typeof t.partitionKey=="string"?p.push(o`${o.identifier("__partition__")} = ${t.partitionKey}`):k&&p.push(o`${o.identifier("__partition__")} = ${J(i.partitionBy??[],k)}`);const B=Q(t),E=Z(B,l,i.sortBy);E&&p.push(E);const I=o.identifier(_),S=o.identifier("__partition__"),D=p.length>0?o` WHERE ${o.join(p,o` AND `)}`:o``,L=l.length>0?o`${I}, ${S}, ${o.join(l.map(a=>o.identifier(a)),o`, `)}`:o`${I}, ${S}`,M=o`SELECT ${L} FROM ${o.identifier(m)}${D} ORDER BY ${o.join(R,o`, `)} LIMIT ${o.raw(String(h+1))}`,$=A(n.sql,M).toArray(),C=$.length>h,y=C?$.slice(0,h):$,K=y.map(a=>a[_]),q=no(y,ro(n,r,K),l),x=C?oo(y.at(-1),l):v,N=i.sortBy.map(a=>a.direction==="desc"?"desc":"asc");return{continueCursor:x,directions:N,hasMore:C,rows:q}};export{_o as computeRankPage,Q as resolveRankSeekTuple};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{c as l,i as C,r as R}from"./ctx-db-companions-DsNfXSbb.mjs";import"./AGGREGATE_SQL_FUNCTION-DDEoMnJR.mjs";import"./aggregateTableName-C7o-gpms.mjs";import"./runDrizzle-2ULFQR_k.mjs";import"./do-sql-kpl5Kt1j.mjs";import"./param-DlozcSQu.mjs";import"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import"./CURSOR_PREFIX-Bn8SFoGd.mjs";import"./RANK_TIEBREAK-D5xNdzB3.mjs";import"./sql-projection-D3qdaItY.mjs";import"./serializeSqlValue-BEMMYX1n.mjs";export{l as createCompanionSync,C as insertRankRow,R as rankColumnsSql};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import{d as u,e as S}from"./wire-codec-C-FpWm52.mjs";import{cursorBelowRetainedFloor as y}from"./CDC_LOG_TABLE-Bh7SB6Uw.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,F=5e4,U=s=>v(s,"LUNORA_REPLICA_MAX_BOOTSTRAP_ROWS",F),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()>U(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{changes:i,cursor:n}=s.readChanges(t,w);return a({changes:i,cursor:n,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 i;try{i=await e.text()}catch{return new Response("bad request",{status:400})}if(!await A(s.env(),e.headers.get(g),i))return new Response("forbidden",{status:403});let n;try{n=JSON.parse(i)}catch{return new Response("bad request",{status:400})}if(n.type==="replica_bootstrap")return P(s,r);if(n.type==="replica_pull"){const o=typeof n.sinceSeq=="number"&&Number.isInteger(n.sinceSeq)&&n.sinceSeq>=0?n.sinceSeq:0;return x(s,r,o)}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 i=0;i<C;i+=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 o=n.changes.length<w;if(r=await this.applyPage(n),o||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,i=t.floor??(r?t.cursor:0),n=i>0&&i>e.appliedSeq+1;return t.epoch===e.epoch&&!n?!1:(this.divergent=!0,!0)}async bootstrap(){const e=await this.request({type:"replica_bootstrap"});if(e===void 0)return;const t=u(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 i={appliedSeq:t.cursor,epoch:t.epoch,syncedAtMs:Date.now()};return f(this.host.sql(),i),i}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:u(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 i=JSON.stringify(e),n={"content-type":"application/json","x-lunora-shard-binding":t??""},o=E(this.host.env());o!==void 0&&(n[g]=await T(o,i));try{const p=await r.fetch("https://replica.internal/_lunora/replica",{body:i,headers:n,method:"POST"});return p.ok?p: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};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as i}from"@lunora/errors";const c=t=>{const e={args:t.args??{},enqueuedAt:typeof t.enqueuedAt=="number"?t.enqueuedAt:0,id:typeof t.id=="string"?t.id:"",scheduledFor:typeof t.scheduledFor=="number"?t.scheduledFor:0};return typeof t.attempts=="number"&&(e.attempts=t.attempts),typeof t.functionPath=="string"&&(e.functionPath=t.functionPath),typeof t.pool=="string"&&(e.pool=t.pool),typeof t.shardKey=="string"&&(e.shardKey=t.shardKey),typeof t.workflow=="string"&&(e.workflow=t.workflow),e},f=t=>{const e={key:typeof t.key=="string"?t.key:"",size:typeof t.size=="number"?t.size:0},o=t.httpMetadata?.contentType??t.contentType;typeof o=="string"&&(e.contentType=o),t.customMetadata&&typeof t.customMetadata=="object"&&(e.customMetadata=t.customMetadata),typeof t.sha256=="string"&&(e.sha256=t.sha256);const{uploaded:n}=t;return typeof n=="number"?e.uploaded=n:n instanceof Date&&(e.uploaded=n.getTime()),e},p=(t={})=>{const e=()=>{if(!t.scheduler)throw new i("INTERNAL",'ctx.db.system.query("_scheduled_functions"): no scheduler configured. Pass `scheduler` to createShardDO().');return t.scheduler},o=()=>{if(!t.storage)throw new i("INTERNAL",'ctx.db.system.query("_storage"): no storage configured. Pass `storage` to createShardDO().');return t.storage},n=async()=>(await e().list()).map(a=>c(a)),d=async()=>{const{objects:s}=await o().list();return s.map(a=>f(a))};return{get:(async(s,a)=>{if(s==="_scheduled_functions"){const u=await e().get(a);return u?c(u):null}const r=await o().getMetadata(a);return r?f(r):null}),query:(s=>s==="_scheduled_functions"?{collect:n}:{collect:d})}};export{p as createSystemReader};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{D as ie}from"./MAX_TOKEN_LENGTH-BakL9FUy-B3VwYY8C.mjs";import{sql as e}from"drizzle-orm";import{matchesStaticWhere as P,aggregateSqlFunction as ce}from"./AGGREGATE_SQL_FUNCTION-DDEoMnJR.mjs";import{aggregateTableName as z,encodeAggregateKey as v,foldAggregateTally as J,coerceAggregateNumber as b}from"./aggregateTableName-C7o-gpms.mjs";import{runDrizzle as u}from"./runDrizzle-2ULFQR_k.mjs";import{i as fe,g as ae,D as M,r as q,a as L,b as h,A as p,c as D,e as U}from"./do-sql-kpl5Kt1j.mjs";import{param as le,WORKERD_SQLITE_LIMITS as $e}from"./param-DlozcSQu.mjs";import{encodeGeohash as de,GEO_DEFAULT_PRECISION as ue}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{isLiveForCompanion as N}from"./CURSOR_PREFIX-Bn8SFoGd.mjs";import{encodePartitionKey as Ee,sortColumnName as _e,rankTableName as X,matchesRankStaticWhere as Y}from"./RANK_TIEBREAK-D5xNdzB3.mjs";import{m as ye}from"./sql-projection-D3qdaItY.mjs";import{serializeSqlValue as Z}from"./serializeSqlValue-BEMMYX1n.mjs";const ge=(t,i)=>{if(!i.includes("."))return t[i];let f=t;for(const A of i.split(".")){if(f===null||typeof f!="object"||Array.isArray(f))return;f=f[A]}return f},pe=(t,i)=>`${t}__fts_${i}`,me="__text__",Q="__id__",he=1e3,Se=(t,i)=>i.document(t),W=(t,i)=>ge(t,i),Te=t=>typeof t=="string"?t:t==null?"":typeof t=="number"||typeof t=="bigint"||typeof t=="boolean"?String(t):JSON.stringify(t)??"",Re=(t,i,f)=>t!==void 0&&i!==void 0&&W(t,f.field)===W(i,f.field),Ae=(t,i)=>Se(Te(W(t,i.field)),ie(i.language)).slice(0,he),we=(t,i)=>Ae(t,i).join(" "),Fe=(t,i,f)=>[...t.partitionBy??[],...t.sortBy.map(S=>S.field),...t.where?Object.keys(t.where):[]].every(S=>i[S]===f[S]),x=t=>e.join(["__id__","__partition__",...t.sortBy.map((i,f)=>_e(f))].map(i=>e.identifier(i)),e`, `),ee=(t,i,f,A,S,y)=>{const c=Ee(f.partitionBy??[],y),C=f.sortBy.map(I=>Z(y[I.field]??null)),k=e.join([S,c,...C].map(I=>le(I)),e`, `);u(t,e`INSERT INTO ${e.identifier(i)} (${A}) VALUES (${k})`)},Oe=(t,i,f,A,S,y)=>{if(S&&y&&Fe(f,S,y))return;const c=X(i,f.name);S&&u(t,e`DELETE FROM ${e.identifier(c)} WHERE ${e.identifier("__id__")} = ${A}`),!(!y||f.where&&!Y(y,f.where))&&ee(t,c,f,x(f),A,y)},Be=t=>{const{broadcast:i,indexKeysFor:f,invalidateCache:A,recordCdc:S,schema:y,sql:c}=t,C=new Set,k=n=>y.tables[n]?.softDeleteMode?.field,I=new Set,j=(n,o)=>{const s=`${n}::${o.name}`;if(C.has(s))return;const l=z(n,o.name),$=o.by??[],d=k(n),_=new Map,m=u(c,e`SELECT id, _creationTime, ${e.identifier(M)} FROM ${e.identifier(n)}`).toArray();for(const T of m){const E=q(T);if(!E||!N(E,d)||o.where&&!P(E,o.where))continue;const R=v($,E);J(_,R,o,E)}u(c,e`DELETE FROM ${e.identifier(l)}`);const w=Math.floor($e.boundParams/3),F=[..._];for(let T=0;T<F.length;T+=w){const E=F.slice(T,T+w),R=e.join(E.map(([r,a])=>e`(${r}, ${a.value}, ${a.count})`),e`, `);u(c,e`INSERT INTO ${e.identifier(l)} (${L}, ${h}, ${p}) VALUES ${R}`)}C.add(s)},oe=(n,o,s)=>{const l=o.by??[],$=o.field??"",d=[],_=(r,a)=>{const g=Z(a);g===null?d.push(e`${U(r)} IS NULL`):d.push(e`${U(r)} = ${g}`)};for(const r of l)_(r,s[r]??null);const m=k(n);m!==void 0&&_(m,null);for(const[r,a]of Object.entries(o.where??{}))_(r,a!==null&&typeof a=="object"&&!Array.isArray(a)?a.eq:a);const w=d.length>0?e` WHERE ${e.join(d,e` AND `)}`:e``,F=y.tables[n]?.shape[$];if(F&&ye(F)){const r=u(c,e`SELECT id, _creationTime, ${e.identifier(M)} FROM ${e.identifier(n)}${w}`).toArray(),a=new Map;for(const g of r){const O=q(g);O&&J(a,"",o,O)}return{value:a.get("")?.value??null}}const T=ce(o.op),E=U($);return{value:u(c,e`SELECT ${e.raw(T)}(${E}) AS value FROM ${e.identifier(n)}${w}`).one().value??null}},ne=(n,o,s,l)=>{const $=z(n,o.name),{op:d}=o,_=o.field??"",m=r=>{u(c,e`DELETE FROM ${e.identifier($)} WHERE ${L} = ${r} AND ${p} <= 0`)},w=k(n),F=r=>!o.where||P(r,o.where),T=r=>N(r,w)&&F(r);l!==void 0&&d!=="count"&&F(l)&&b(l[_]);const E=s&&T(s)?s:void 0,R=l&&T(l)?l:void 0;if(!(!E&&!R)){if(d==="count"){for(const[r,a]of[[E,-1],[R,1]]){if(!r)continue;const g=v(o.by??[],r);u(c,D($,g,a,a,e`${h} = ${h} + excluded.${h}, ${p} = ${p} + excluded.${p}`))}E&&m(v(o.by??[],E));return}if(d==="sum"||d==="avg"){for(const[r,a]of[[E,-1],[R,1]]){if(!r)continue;const g=b(r[_]);if(g===void 0)continue;const O=v(o.by??[],r);u(c,D($,O,a*g,a,e`${h} = COALESCE(${h}, 0) + excluded.${h}, ${p} = ${p} + excluded.${p}`))}E&&m(v(o.by??[],E));return}if(E){const r=v(o.by??[],E),a=b(E[_]),g=u(c,e`SELECT ${h} AS value, ${p} AS count FROM ${e.identifier($)} WHERE ${L} = ${r}`).toArray()[0],O=(g?.count??0)-1;if(O<=0)u(c,e`DELETE FROM ${e.identifier($)} WHERE ${L} = ${r}`);else if(g&&a!==void 0&&g.value!==null&&a===g.value){const se=oe(n,o,E);u(c,e`UPDATE ${e.identifier($)} SET ${h} = ${se.value}, ${p} = ${O} WHERE ${L} = ${r}`)}else u(c,e`UPDATE ${e.identifier($)} SET ${p} = ${p} - 1 WHERE ${L} = ${r}`)}if(R){const r=v(o.by??[],R),a=b(R[_]);if(a===void 0)u(c,D($,r,null,1,e`${p} = ${p} + 1`));else{const g=d==="min"?"MIN":"MAX";u(c,D($,r,a,1,e`${h} = ${e.raw(g)}(COALESCE(${h}, excluded.${h}), excluded.${h}), ${p} = ${p} + 1`))}}}},te=n=>{for(const o of y.tables[n]?.aggregateIndexes??[])j(n,o)},H=(n,o,s)=>{for(const l of y.tables[n]?.aggregateIndexes??[])ne(n,l,o,s)},B=(n,o)=>{const s=`${n}::rank::${o.name}`;if(I.has(s))return;const l=X(n,o.name),$=u(c,e`SELECT id, _creationTime, ${e.identifier(M)} FROM ${e.identifier(n)}`).toArray();u(c,e`DELETE FROM ${e.identifier(l)}`);const d=x(o);for(const _ of $){const m=q(_);!m||o.where&&!Y(m,o.where)||ee(c,l,o,d,m._id,m)}I.add(s)},re=n=>{for(const o of y.tables[n]?.rankIndexes??[])B(n,o)},K=(n,o,s,l)=>{for(const $ of y.tables[n]?.rankIndexes??[])Oe(c,n,$,o,s,l)},V=(n,o,s,l)=>{const $=y.tables[n]?.searchIndexes??[];if(!($.length===0||!fe(c)))for(const d of $){if(Re(l,s,d))continue;const _=pe(n,d.name);u(c,e`DELETE FROM ${e.identifier(_)} WHERE ${e.identifier(Q)} = ${o}`),s&&u(c,e`INSERT INTO ${e.identifier(_)} (${e.identifier(me)}, ${e.identifier(Q)}) VALUES (${we(s,d)}, ${o})`)}},G=(n,o,s)=>{for(const l of y.tables[n]?.geoIndexes??[]){const $=ae(n,l.name);u(c,e`DELETE FROM ${e.identifier($)} WHERE ${e.identifier("__id__")} = ${o}`);const d=s?.[l.field];if(d!==null&&typeof d=="object"&&typeof d.lat=="number"&&typeof d.lng=="number"){const{lat:_,lng:m}=d,w=de({lat:_,lng:m},l.precision??ue);u(c,e`INSERT INTO ${e.identifier($)} (${e.identifier("__id__")}, ${e.identifier("__geohash__")}, ${e.identifier("__lat__")}, ${e.identifier("__lng__")}) VALUES (${o}, ${w}, ${_}, ${m})`)}}};return{ensureBackfilledForTable:te,ensureBackfilledIndex:j,ensureRankBackfilled:B,ensureRankBackfilledForTable:re,syncAggregates:H,syncCompanionsForInsert:(n,o,s)=>{V(n,o,s),G(n,o,s),H(n,void 0,s),K(n,o,void 0,s),A(n,o,s),S(n,o,"insert",s),i({indexKeys:f(n,s),key:o,op:"insert",row:s,table:n})},syncGeo:G,syncRanks:K,syncSearch:V}};export{pe as S,Ae as a,Be as c,we as d,ee as i,Q as l,x as r,me as y};
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import{sql as i}from"drizzle-orm";import{e as l,d as E}from"./wire-codec-C-FpWm52.mjs";import{runDrizzle as a}from"./runDrizzle-2ULFQR_k.mjs";import{relayProxyKey as T}from"./DEFAULT_PROMOTION_THRESHOLDS-Bfx7KakS.mjs";const t="__lunora_relay_shapes",o=null,R=e=>{a(e,i`CREATE TABLE IF NOT EXISTS ${i.identifier(t)} (
|
|
2
|
+
key TEXT PRIMARY KEY,
|
|
3
|
+
relay_idx INTEGER,
|
|
4
|
+
connection_id TEXT,
|
|
5
|
+
name TEXT NOT NULL,
|
|
6
|
+
args TEXT NOT NULL,
|
|
7
|
+
identity TEXT NOT NULL,
|
|
8
|
+
cursor INTEGER NOT NULL
|
|
9
|
+
)`)},s=e=>JSON.stringify(l(e)),c=e=>E(JSON.parse(e)),$=e=>a(e,i`SELECT key, relay_idx, connection_id, name, args, identity, cursor FROM ${i.identifier(t)}`).toArray().map(r=>({args:c(r.args),connectionId:r.connection_id??void 0,cursor:Number(r.cursor),identity:c(r.identity),key:r.key,name:r.name,relayIndex:r.relay_idx===null?void 0:Number(r.relay_idx)})),L=(e,n)=>{a(e,i`INSERT INTO ${i.identifier(t)} (key, relay_idx, connection_id, name, args, identity, cursor)
|
|
10
|
+
VALUES (${n.key}, ${n.relayIndex??o}, ${n.connectionId??o}, ${n.name}, ${s(n.args)}, ${s(n.identity??{})}, ${n.cursor})
|
|
11
|
+
ON CONFLICT(key) DO UPDATE SET
|
|
12
|
+
relay_idx = excluded.relay_idx,
|
|
13
|
+
connection_id = excluded.connection_id,
|
|
14
|
+
name = excluded.name,
|
|
15
|
+
args = excluded.args,
|
|
16
|
+
identity = excluded.identity,
|
|
17
|
+
cursor = excluded.cursor`)},S=(e,n,r)=>{a(e,i`UPDATE ${i.identifier(t)} SET cursor = ${r} WHERE key = ${n}`)},x=(e,n,r,d)=>{const y=d===void 0?i``:i` AND key = ${T(n,r,d)}`;a(e,i`DELETE FROM ${i.identifier(t)} WHERE relay_idx = ${n} AND connection_id = ${r}${y}`)},p=(e,n)=>{a(e,i`DELETE FROM ${i.identifier(t)} WHERE relay_idx = ${n}`)},O=e=>{a(e,i`DELETE FROM ${i.identifier(t)}`)};export{L as a,p as b,O as c,x as d,R as m,$ as r,S as w};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{D as T}from"./MAX_TOKEN_LENGTH-BakL9FUy-B3VwYY8C.mjs";import{sql as e}from"drizzle-orm";import{runDrizzle as t}from"./runDrizzle-2ULFQR_k.mjs";const v=i=>`${T(i.language).profile}:${i.field}`,c=i=>{const r=i.slice(i.indexOf(":")+1),n=r.lastIndexOf("/");return n===-1?r:r.slice(0,n)},S=(i,r)=>i.profile!==r?{cursor:void 0,finished:!1,wipe:i.cursor!==void 0||i.done}:{cursor:i.cursor,finished:i.done,wipe:!1},a=(i,r)=>typeof i=="string"&&c(i)===c(r),o="__lunora_search_state",N=i=>{t(i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(o)} (${e.identifier("companion")} TEXT PRIMARY KEY, ${e.identifier("cursor")} TEXT, ${e.identifier("done")} INTEGER NOT NULL DEFAULT 0, ${e.identifier("profile")} TEXT, ${e.identifier("covered")} INTEGER NOT NULL DEFAULT 0)`);try{t(i,e`ALTER TABLE ${e.identifier(o)} ADD COLUMN ${e.identifier("profile")} TEXT`)}catch{}try{t(i,e`ALTER TABLE ${e.identifier(o)} ADD COLUMN ${e.identifier("covered")} INTEGER NOT NULL DEFAULT 0`)}catch{}t(i,e`UPDATE ${e.identifier(o)} SET ${e.identifier("covered")} = 1 WHERE ${e.identifier("done")} = 1 AND ${e.identifier("covered")} = 0`)},s=i=>i===1||i===!0||i==="1",R=(i,r)=>{const n=t(i,e`SELECT ${e.identifier("covered")} FROM ${e.identifier(o)} WHERE ${e.identifier("companion")} = ${r}`).toArray();return s(n[0]?.covered)},l=(i,r)=>{const d=t(i,e`SELECT ${e.identifier("cursor")}, ${e.identifier("done")}, ${e.identifier("profile")} FROM ${e.identifier(o)} WHERE ${e.identifier("companion")} = ${r}`).toArray()[0];return d?{cursor:d.cursor??void 0,done:s(d.done),profile:d.profile??void 0}:{cursor:void 0,done:!1,profile:void 0}},O=(i,r,n,d,f)=>{const $=n??null,E=a(l(i,r).profile,f)?e`MAX(${e.identifier(o)}.${e.identifier("covered")}, excluded.${e.identifier("covered")})`:e`excluded.${e.identifier("covered")}`;t(i,e`INSERT INTO ${e.identifier(o)} (${e.identifier("companion")}, ${e.identifier("cursor")}, ${e.identifier("done")}, ${e.identifier("profile")}, ${e.identifier("covered")}) VALUES (${r}, ${$}, ${d?1:0}, ${f}, ${d?1:0}) ON CONFLICT (${e.identifier("companion")}) DO UPDATE SET ${e.identifier("cursor")} = excluded.${e.identifier("cursor")}, ${e.identifier("done")} = excluded.${e.identifier("done")}, ${e.identifier("profile")} = excluded.${e.identifier("profile")}, ${e.identifier("covered")} = ${E}`)};export{o as S,R as a,v as c,S as l,N as m,l as r,O as w};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createShardCtxDb as v}from"./NotUniqueError-Dfjj2n69.mjs";import{createRelayLink as I}from"./DEFAULT_MAX_RELAYS-Ng4SyJ7k.mjs";import{ConflictError as N}from"./ConflictError-C8GtJmjS.mjs";import{runShardMigrations as _}from"./runShardMigrations-Dp8Ld19a.mjs";import{relayName as F}from"./DEFAULT_PROMOTION_THRESHOLDS-Bfx7KakS.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};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{stableStringify as u}from"./stableStringify-DibjylKD.mjs";const l=(t,s)=>{const o={_id:t._id};if(s){for(const e of s)Object.hasOwn(t,e)&&(o[e]=t[e]);return o}for(const[e,n]of Object.entries(t))e!=="_id"&&e!=="_creationTime"&&(o[e]=n);return o},j=(t,s,o)=>{const{columns:e,table:n}=o,c=[],d=new Map;for(const r of t){const i=l(r,e),f=String(i._id),a=u(i);d.set(f,a);const p=s.get(f);p===void 0?c.push({doc:i,id:f,op:"insert",seq:0,table:n,ts:0}):p!==a&&c.push({doc:i,id:f,op:"update",seq:0,table:n,ts:0})}for(const r of s.keys())d.has(r)||c.push({id:r,op:"delete",seq:0,table:n,ts:0});return{changes:c,nextBaseline:d}};export{j as diffExternalSource,l as projectExternalSourceRow};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as _}from"@lunora/errors";import{sql as r}from"drizzle-orm";import{e as A,s as T}from"./sql-projection-D3qdaItY.mjs";import{quoteIdentifier as p}from"./quoteIdentifier-CObIFRhb.mjs";import{d as $,n as S,e as O}from"./wire-codec-C-FpWm52.mjs";import{runDrizzle as f}from"./runDrizzle-2ULFQR_k.mjs";import"./serializeSqlValue-BEMMYX1n.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__",G=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=T(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 S(n)?JSON.stringify(O(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=$(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}},J=(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),q=e=>r.raw(y(e)),N=(e,t)=>E(`${p(e)}.`,t),B=(e,t)=>r.raw(N(e,t)),z=(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__"),F=(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}`,W=(e,t)=>e===void 0||t!==0&&t!==1||A(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},K=e=>{try{return C(e)}catch{return}},u=new WeakMap,M=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,F as c,z as d,q as e,B as f,J as g,K as h,M as i,y as j,G as k,g as l,h as m,a as n,W as o,N as q,C as r,k as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const o=/^\d+$/,r=(e,n)=>{const t=e?.[n];let i=Number.NaN;return typeof t=="string"&&o.test(t.trim())?i=Number(t.trim()):typeof t=="number"&&(i=t),Number.isSafeInteger(i)&&i>0?i:void 0},s=(e,n,t)=>r(e,n)??t,N=(e,n)=>r(e,n);export{N as envOptionalPositiveInt,s as envPositiveInt};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{B as s}from"./sql-projection-D3qdaItY.mjs";const n=40,f=i=>{let e=0;const o=(r,t)=>typeof t=="bigint"?(e+=s+1+n,t.toString()):t instanceof ArrayBuffer||ArrayBuffer.isView(t)?(e+=2*Math.ceil(t.byteLength/3)*4+n,""):t;try{const r=JSON.stringify(i,o);return(r===void 0?0:r.length)+e}catch{return}};export{f as e};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{toErrorBody as b}from"@lunora/errors";import{COMMIT_SEQ_FIELD as l}from"./COMMIT_SEQ_FIELD-BUdOMG5y.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};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const n=async e=>{const r=e.schema.tables[e.tableName]?.triggerMap;if(r)for(const t of Object.values(r))t.timing===e.timing&&t.op===e.op&&await t.handler(e.ctx,e.event)},s=(e,r,t)=>{const i=e.tables[r]?.triggerMap;return i?Object.values(i).some(a=>a.op===t):!1};export{s as hasTrigger,n as runTriggers};
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import{LunoraError as T}from"@lunora/errors";import{sql as m}from"drizzle-orm";import{runDrizzle as S}from"./runDrizzle-2ULFQR_k.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-CgHTVGDJ.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
|
+
table_name TEXT NOT NULL,
|
|
3
|
+
shard_key TEXT NOT NULL,
|
|
4
|
+
watermark TEXT,
|
|
5
|
+
last_reconcile_ms INTEGER,
|
|
6
|
+
PRIMARY KEY (table_name, shard_key)
|
|
7
|
+
)`)},b=(e,t,o)=>{const r=S(e,m`SELECT watermark, last_reconcile_ms FROM ${m.identifier(p)} WHERE table_name = ${t} AND shard_key = ${o} LIMIT 1`).toArray()[0];return{lastReconcileMs:r?.last_reconcile_ms??null,watermark:r?.watermark??null}},q=(e,t,o,n)=>{S(e,m`INSERT INTO ${m.identifier(p)} (table_name, shard_key, watermark, last_reconcile_ms)
|
|
8
|
+
VALUES (${t}, ${o}, ${n.watermark}, ${n.lastReconcileMs})
|
|
9
|
+
ON CONFLICT(table_name, shard_key) DO UPDATE SET watermark = excluded.watermark, last_reconcile_ms = excluded.last_reconcile_ms`)},F=(e,t,o)=>e==="manual"?!1:e===void 0||t===void 0?!0:o-t>=e.everyMs,_=async(e,t,o,n)=>{const r=await e.query(t,o);return{documents:r.map(a=>A(a,{idColumn:n.idColumn,map:n.map})),rows:r}},P=async(e,t,o,n,r,c)=>{const a=r.tenantBy?r.tenantBy(c):[],{documents:i}=await _(o,r.query,a,r);return C(e,t,i,{columns:r.columns,table:n})},$=(e,t)=>{const o=e[t];return o!=null&&o!==!1&&o!==0},V=async(e,t,o,n,r,c,a)=>{const{cursor:i}=r;if(!i)throw new T("INTERNAL",`external-source: table "${n}" is mode "incremental" but has no \`cursor\` — this should have been rejected at defineSchema`);B(e);const u=b(e,n,c),g=r.tenantBy?r.tenantBy(c):[],k=r.reconcileEveryMs!==void 0&&(u.lastReconcileMs===null||a-u.lastReconcileMs>=r.reconcileEveryMs),f=u.watermark===null||k;let s,w;if(u.watermark===null||k){s=await _(o,r.query,g,r);const{softDeleteColumn:l}=r,y=l?s.documents.filter((R,E)=>{const d=s.rows[E];return!(d&&$(d,l))}):s.documents;({applied:w}=await C(e,t,y,{columns:r.columns,table:n}))}else{s=await _(o,i.query,[...g,v(u.watermark)],r);const{softDeleteColumn:l}=r,y=l?new Set(s.documents.flatMap((R,E)=>{const d=s.rows[E];return d&&$(d,l)?[String(R._id)]:[]})):void 0;({applied:w}=await D(t,s.documents,{columns:r.columns,deletedIds:y,table:n}))}const I=O(s.rows,i.column,u.watermark);if(f&&I===null&&s.rows.length>0)throw new T("INTERNAL",`external-source: table "${n}" (mode "incremental") pulled ${String(s.rows.length)} rows but none carry the cursor column "${i.column}" — the seed \`query\` must project it (matching \`cursor.query\`'s alias), or the watermark can never advance.`);const L=s.rows.length>0&&s.rows.every(l=>l[i.column]===null||l[i.column]===void 0);if(!f&&L)throw new T("INTERNAL",`external-source: table "${n}" (mode "incremental") pulled ${String(s.rows.length)} rows but none carry the cursor column "${i.column}" — \`cursor.query\` must project it (matching the seed \`query\`'s alias), or the watermark can never advance and every tick re-pulls the same stranded slice.`);return q(e,n,c,{lastReconcileMs:f?a:u.lastReconcileMs,watermark:I}),{applied:w}};export{$ as isSoftDeleted,F as isSourceDue,A as liftSourceId,W as normalizeSourceValue,V as pullExternalSourceIncrementalTick,P as pullExternalSourceTick};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as p}from"@lunora/errors";const u=r=>r instanceof Date?r.toISOString():typeof r=="bigint"?String(r):Array.isArray(r)?r.map(t=>u(t)):r!==null&&typeof r=="object"&&Object.getPrototypeOf(r)===Object.prototype?i(r):r,i=r=>{const t={};for(const[o,e]of Object.entries(r))t[o]=u(e);return t},d=(r,t={})=>{const{idColumn:o="id",map:e}=t,n=r[o];if(n==null)throw new p("INTERNAL",`external-source: row is missing id column "${o}"`);if(typeof n!="string"&&typeof n!="number"&&typeof n!="bigint")throw new TypeError(`external-source: id column "${o}" must be a string or number`);const c=String(n);if(e)return i({...e(r),_id:c});const s={};for(const[f,m]of Object.entries(r))f!==o&&(s[f]=m);return i({...s,_id:c})};export{d as liftSourceId,i as normalizeSourceDocument,u as normalizeSourceValue};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{applyCdcChanges as p}from"./CDC_LOG_TABLE-Bh7SB6Uw.mjs";import{selectShapeRows as m}from"./selectShapeMembers-B8gTOeOB.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};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{keysTouchRanges as i}from"./buildIndexRange-DvN8Qj8e.mjs";const f=(o,r,n)=>{const e=o??new Map;for(const t of n){const s=r?.get(t),u=e.get(t),c=e.has(t)&&u===void 0;if(!r?.has(t)||s===void 0||c){e.set(t,void 0);continue}e.set(t,u?[...u,...s]:s)}return e},a=(o,r,n)=>{const e=o??new Map;if(e.has(r)&&e.get(r)===void 0)return e;if(!n||n.length===0)return e.set(r,void 0),e;const t=e.get(r);return e.set(r,t?[...t,...n]:[...n]),e},h=(o,r,n)=>{if(!n)return!0;for(const e of r){if(!o.tables.has(e))continue;const t=o.ranges?.get(e);if(!t||t.length===0||i(t,n.get(e)))return!0}return!1};export{f as mergeChangedKeys,a as recordChangedKeys,h as writeTouchesMemo};
|
|
@@ -0,0 +1 @@
|
|
|
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};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const t=e=>`"${e.replaceAll('"','""')}"`;export{t as quoteIdentifier};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as s}from"@lunora/errors";import{renderSql as l,WORKERD_SQLITE_LIMITS as r}from"./param-DlozcSQu.mjs";const c=(t,n,...e)=>{if(n.length*3>r.sqlTextLength){const i=new TextEncoder().encode(n).length;if(i>r.sqlTextLength)throw new s("INTERNAL",`SQL statement is ${String(i)} bytes, over this runtime's ${String(r.sqlTextLength)}-byte limit`)}if(e.length>r.boundParams)throw new s("INTERNAL",`SQL statement binds ${String(e.length)} parameters, over this runtime's limit of ${String(r.boundParams)}`);return t.exec.call(t,n,...e)},h=(t,n)=>{const{params:e,sql:o}=l("sqlite",n);return c(t,o,...e)},d=t=>t??null,g=t=>{if(!(t==null||t===""))try{return JSON.parse(t)}catch{return}};export{g as decodeJsonColumn,d as orNull,h as runDrizzle,c as runSql};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import{LunoraError as L}from"@lunora/errors";import{S as h,y as l,l as N}from"./ctx-db-companions-DsNfXSbb.mjs";import{sql as e}from"drizzle-orm";import{aggregateTableName as R}from"./aggregateTableName-C7o-gpms.mjs";import{backfillSearchIndexesForTable as O}from"./backfillAggregateIndexes-DTemznr7.mjs";import{migrateCdcLog as x,migrateCdcMeta as C}from"./CDC_LOG_TABLE-Bh7SB6Uw.mjs";import{migrateClientWatermark as $}from"./CLIENT_WATERMARK_TABLE-CRnrAnJ2.mjs";import{migrateCommitSeq as U}from"./COMMIT_SEQ_FIELD-BUdOMG5y.mjs";import{migrateGlobalShapeSnapshot as D}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-DSA6mzyx.mjs";import{migrateIdempotency as b}from"./IDEMPOTENCY_TABLE-DOpm_oMF.mjs";import{m as X}from"./ctx-db-relay-shapes-Bg5YYnmN.mjs";import{migrateScheduleOutbox as G}from"./SCHEDULE_OUTBOX_TABLE-CD_UjYVx.mjs";import{m as M}from"./ctx-db-search-state-ruTuCsxa.mjs";import{migrateShapePokeCursor as F}from"./SHAPE_POKE_CURSOR_TABLE-ByJVDHds.mjs";import{runDrizzle as s}from"./runDrizzle-2ULFQR_k.mjs";import{D as y,d as E,e as g,t as B,i as Y,g as k,a as v,b as P,A}from"./do-sql-kpl5Kt1j.mjs";import{renderSql as w}from"./param-DlozcSQu.mjs";import{migrateDurableStreams as j}from"./appendStreamChunk-C1Ok4b6J.mjs";import{rankTableName as K,sortColumnName as H}from"./RANK_TIEBREAK-D5xNdzB3.mjs";import{migrateReactorState as V}from"./REACTOR_STATE_TABLE-QPRFyxMS.mjs";import{recordSchemaVersion as W}from"./SCHEMA_HISTORY_MAX_VERSIONS-BluIj2s-.mjs";const S=e`_creationTime, id`,p=(r,o,i,t,n,a)=>{const c=e.join(n.map(d=>e`${d} IS NOT NULL`),e` AND `);if(s(r,e`SELECT 1 FROM ${e.identifier(i)} WHERE ${c} GROUP BY ${t} HAVING COUNT(*) > 1 LIMIT 1`).toArray().length>0)throw new L("INTERNAL",`unique index "${o}" on "${i}" ${a}: existing rows are duplicates under it. De-duplicate the table with a data migration first; the previous index is left in place.`)},z=(r,o,i,t,n,a)=>{const m=s(r,e`SELECT sql FROM sqlite_master WHERE type = 'index' AND name = ${o} AND tbl_name = ${i}`).toArray()[0]?.sql;if(m==null)return;const d=_=>{const I=_.indexOf("(");return I===-1?void 0:_.slice(I,_.lastIndexOf(")")+1)},T=d(w("sqlite",E(o,i,t,n)).sql),f=d(m);T===void 0||f===void 0||T===f||(n&&p(r,o,i,t,a,"cannot be re-created with its new column list"),s(r,e`DROP INDEX IF EXISTS ${e.identifier(o)}`))},J=(r,o,i)=>s(r,e`SELECT 1 FROM sqlite_master WHERE type = 'index' AND name = ${o} AND tbl_name = ${i} LIMIT 1`).toArray().length>0,u=(r,o,i,t,n,a)=>{n&&!J(r,o,i)&&p(r,o,i,t,a,"cannot be created"),s(r,E(o,i,t,n))},Q=(r,o,i)=>{for(const t of i.indexes){const n=`${o}_${t.name}`,a=t.unique??!1,c=t.fields.map(T=>g(T)),m=e.join(c,e`, `),d=a?m:e`${m}, ${S}`;z(r,n,o,d,a,c),u(r,n,o,d,a,c)}for(const[t,n]of B(i)){if(!n.unique)continue;const a=g(t);u(r,`${o}_unique_${t}`,o,a,!0,[a])}},Z=(r,o,i)=>{if(!(!i.searchIndexes||i.searchIndexes.length===0||!Y(r))){for(const t of i.searchIndexes){const n=h(o,t.name);s(r,e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(n)} USING fts5(${e.identifier(l)}, ${e.identifier(N)} UNINDEXED)`),s(r,e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(`${n}__vocab`)} USING fts5vocab(${e.identifier(n)}, ${e.raw("instance")})`)}O(r,o,i)}},q=(r,o,i)=>{if(i.geoIndexes)for(const t of i.geoIndexes){const n=k(o,t.name);s(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(n)} (${e.identifier("__id__")} TEXT PRIMARY KEY, ${e.identifier("__geohash__")} TEXT NOT NULL, ${e.identifier("__lat__")} REAL NOT NULL, ${e.identifier("__lng__")} REAL NOT NULL)`);const a=`${o}__geo_${t.name}__btree`;s(r,E(a,n,e`${e.identifier("__geohash__")} ASC, ${e.identifier("__id__")} ASC`,!1))}},ee=(r,o,i)=>{if(i.aggregateIndexes)for(const t of i.aggregateIndexes){const n=R(o,t.name);s(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(n)} (${v} TEXT PRIMARY KEY, ${P} REAL, ${A} INTEGER NOT NULL DEFAULT 0)`),s(r,e`PRAGMA table_info(${e.identifier(n)})`).toArray().some(c=>c.name==="__count__")||s(r,e`ALTER TABLE ${e.identifier(n)} ADD COLUMN ${A} INTEGER NOT NULL DEFAULT 0`)}},re=(r,o,i)=>{if(i.rankIndexes)for(const t of i.rankIndexes){const n=K(o,t.name),a=t.sortBy.map((f,_)=>H(_)),c=a.map(f=>e`${e.identifier(f)} BLOB`),m=c.length>0?e`, ${e.join(c,e`, `)}`:e``;s(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(n)} (${e.identifier("__id__")} TEXT PRIMARY KEY, ${e.identifier("__partition__")} TEXT NOT NULL${m})`);const d=[e`${e.identifier("__partition__")} ASC`];for(const[f,_]of a.entries()){const I=t.sortBy[f]?.direction;d.push(e`${e.identifier(_)} ${e.raw(I==="desc"?"DESC":"ASC")}`)}d.push(e`${e.identifier("__id__")} ASC`);const T=`${o}__rank_${t.name}__btree`;s(r,E(T,n,e.join(d,e`, `),!1))}},le=(r,o,i={})=>{i.schemaSnapshot!==void 0&&W(r,i.schemaSnapshot.hash,i.schemaSnapshot.json),M(r);for(const[t,n]of Object.entries(o.tables))n.shardMode?.kind!=="global"&&(s(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(t)} (
|
|
2
|
+
id TEXT PRIMARY KEY,
|
|
3
|
+
_creationTime REAL NOT NULL,
|
|
4
|
+
${e.identifier(y)} TEXT NOT NULL
|
|
5
|
+
)`),s(r,E(`${t}__by_creation`,t,S,!1)),Q(r,t,n),Z(r,t,n),q(r,t,n),ee(r,t,n),re(r,t,n));i.cdc&&(x(r),C(r),$(r),F(r),X(r)),Object.values(o.tables).some(t=>t.commitOrderedMode===!0)&&U(r),V(r),b(r),G(r),D(r),j(r)};export{le as runShardMigrations};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const l=async(o,a,c=8)=>{let t=0;const e=async()=>{let r=o[t];for(t+=1;r!==void 0;){try{await a(r)}catch{}r=o[t],t+=1}};await Promise.all(Array.from({length:Math.min(c,o.length)},()=>e()))};export{l as runSocketPool};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{sql as o}from"drizzle-orm";import{runDrizzle as h}from"./runDrizzle-2ULFQR_k.mjs";import{e}from"./do-sql-kpl5Kt1j.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};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{sql as e}from"drizzle-orm";import{runDrizzle as m}from"./runDrizzle-2ULFQR_k.mjs";import{D as p,r as d,e as h}from"./do-sql-kpl5Kt1j.mjs";import{sqliteInList as w}from"./param-DlozcSQu.mjs";import{c as S}from"./where-sql-x1YKldcq.mjs";import{serializeSqlValue as $}from"./serializeSqlValue-BEMMYX1n.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{s as o}from"./sql-projection-D3qdaItY.mjs";const n=r=>typeof r=="boolean"?r?1:0:r===null||typeof r=="string"||typeof r=="number"?r:o(r)??JSON.stringify(r);export{n as serializeSqlValue};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const c=(n,t)=>{const r=Math.max(n.length,t.length);let o=n.length^t.length;for(let e=0;e<r;e+=1){const i=e<n.length?n.charCodeAt(e):0,a=e<t.length?t.charCodeAt(e):0;o|=i^a}return o===0},d="LUNORA_RELAY_SECRET",g="x-lunora-relay-sig",l=n=>{const t=n?.[d];return typeof t=="string"&&t.length>0?t:void 0},u=async(n,t)=>{const r=new TextEncoder,o=await crypto.subtle.importKey("raw",r.encode(n),{hash:"SHA-256",name:"HMAC"},!1,["sign"]),e=await crypto.subtle.sign("HMAC",o,r.encode(t));return[...new Uint8Array(e)].map(i=>i.toString(16).padStart(2,"0")).join("")},f=async(n,t,r)=>{const o=l(n);return o===void 0?!0:t===null?!1:c(t,await u(o,r))},s=n=>{if(n===null||typeof n!="object")return;const t=n;return typeof t.idFromName=="function"&&typeof t.get=="function"?t:void 0},y=(n,t,r,o)=>{if(t===void 0)return;const e=s(n?.[t]);if(e===void 0)return;const i=o===void 0?e:s(e.jurisdiction?.(o));if(i!==void 0)return typeof i.getByName=="function"?i.getByName(r):i.get(i.idFromName(r))};export{g as R,l as a,u as b,y as s,f as v};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as g}from"@lunora/errors";import{t as o}from"./base64-DfpzS4o_.mjs";const l=t=>{const{value:n}=t._meta??{};if(n===null)return"null";switch(typeof n){case"bigint":case"boolean":case"number":case"string":return typeof n;default:return t.kind}},s=t=>{if(t.kind==="literal")return l(t);if(t.kind!=="optional")return t.kind;const n=t._meta?.inner;return n?s(n):t.kind},r=39,f="0",c="1",a=t=>Array.from(t,n=>String(9-Number(n))).join(""),d=t=>{const n=t<0n,e=(n?-t:t).toString();if(e.length>r)throw new g("BAD_REQUEST",`bigint ${t.toString()} has ${String(e.length)} digits, over the ${String(r)}-digit limit for a queryable column`);const i=e.padStart(r,"0");return n?f+a(i):c+i},u=/^\d+$/u,p=t=>{if(t.length!==r+1)return;const n=t.slice(0,1),e=t.slice(1);if(u.test(e))return n===c?BigInt(e):n===f?-BigInt(a(e)):void 0},m=/^[\da-f]{16}$/u,I=t=>{const n=new DataView(new ArrayBuffer(8));n.setFloat64(0,t===0?0:t,!1);let e=n.getUint32(0,!1),i=n.getUint32(4,!1);return(e&2147483648)===0?e=(e^2147483648)>>>0:(e=~e>>>0,i=~i>>>0),e.toString(16).padStart(8,"0")+i.toString(16).padStart(8,"0")},h=t=>{if(!m.test(t))return;let n=Number.parseInt(t.slice(0,8),16),e=Number.parseInt(t.slice(8),16);(n&2147483648)===0?(n=~n>>>0,e=~e>>>0):n=(n^2147483648)>>>0;const i=new DataView(new ArrayBuffer(8));return i.setUint32(0,n,!1),i.setUint32(4,e,!1),i.getFloat64(0,!1)},w=t=>typeof t=="bigint"?d(t):t instanceof ArrayBuffer?o(new Uint8Array(t)):ArrayBuffer.isView(t)?o(new Uint8Array(t.buffer,t.byteOffset,t.byteLength)):void 0,y=t=>{const n=s(t);return n==="bigint"||n==="bytes"},B=t=>{const n=s(t);return y(t)||n==="any"||n==="union"||n==="from"};export{r as B,h as a,d as b,p as d,s as e,I as f,y as i,B as m,w as s};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const a=/["\\\u0000-\u001F\uD800-\uDFFF]/,f=t=>a.test(t)?JSON.stringify(t):`"${t}"`,y=t=>{if(t===void 0)return"null";if(typeof t=="bigint")throw new TypeError("stableStringify: cannot use a bigint in a stable JSON cache key — pass it as a string, or use stableWireKey");if(typeof t=="number"){if(Number.isNaN(t))return"nan";if(t===1/0)return"inf";if(t===-1/0)return"-inf";if(Object.is(t,-0))return"-0"}if(typeof t=="string")return f(t);if(t===null||typeof t!="object")return JSON.stringify(t);if(Array.isArray(t)){let r="[";for(let n=0;n<t.length;n++)n>0&&(r+=","),r+=y(t[n]);return r+"]"}const i=Object.getPrototypeOf(t);if(i!==null&&i!==Object.prototype){const r=t.constructor?.name??"value";throw new TypeError(`stableStringify: cannot use a ${r} in a stable JSON cache key — only plain objects, arrays, and JSON primitives are supported (wire-typed values key via stableWireKey)`)}const o=t,c=Object.keys(o).sort();let e="{",s=!0;for(const r of c){const n=o[r];n!==void 0&&(s?s=!1:e+=",",e+=f(r),e+=":",e+=y(n))}return e+"}"};export{y as stableStringify};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{stableStringify as r}from"./stableStringify-DibjylKD.mjs";import{e as o}from"./wire-codec-C-FpWm52.mjs";const m=e=>r(o(e));export{m as stableWireKey};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as T}from"@lunora/errors";import{sql as l}from"drizzle-orm";import{sqliteInList as d,isJsonSafe as $,WORKERD_SQLITE_LIMITS as O}from"./param-DlozcSQu.mjs";import{quoteIdentifier as m}from"./quoteIdentifier-CObIFRhb.mjs";import{RELATION_EXISTS_KEY as L}from"./RELATION_EXISTS_KEY-CFUhnZSZ.mjs";const R={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)=>d(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:"?"}),I=n=>({params:[],text:n}),Y=n=>I(m(n)),Q={binary:(n,t,o)=>p(n," ".concat(t," "),h(o)),constant:n=>I(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},x=O.boundParams/2,S=["eq","ne","lt","lte","gt","gte","in","notIn","isNull","contains"],_=new Set(S),j={eq:"=",gt:">",gte:">=",lt:"<",lte:"<=",ne:"<>"},E=n=>{if(n===null||typeof n!="object"||Array.isArray(n))return!1;const t=Object.keys(n);return t.length>0&&t.every(o=>_.has(o))},w=(n,t,o,s,i)=>{const r=i.value(s.serialize(o,n));return s.containsExpr?s.containsExpr(t,r):i.contains(t,r)},y=(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)),C=(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,x)},G=(n,t,o)=>{const s=l.join(t.map(i=>l`${i}`),l`, `);return o?l`${n} NOT IN (${s})`:l`${n} IN (${s})`},D=(n,t,o,s,i)=>{const r=o,e=[];for(const c of S){if(!(c in r))continue;const a=r[c],u=j[c];u?e.push(y(n,t,c,u,a,s,i)):c==="isNull"?e.push(i.nullCheck(t,!a)):c==="contains"?e.push(w(n,t,a,s,i)):e.push(C(n,t,c==="in"?"IN":"NOT IN",a,s,i))}return e},U=(n,t,o,s)=>{const i=o.fieldRef(n);return E(t)?D(n,i,t,o,s):t===null?[s.nullCheck(i,!1)]:[s.binary(i,"=",o.serialize(t,n))]},N=(n,t,o)=>{if(n.length<=1)return n[0];const s=Math.floor(n.length/2);return o.connect(N(n.slice(0,s),t,o),N(n.slice(s),t,o),t)},k=(n,t,o,s)=>{const i=Array.isArray(n)?n:[],r=[];for(const e of i){const c=f(e??{},o,s);c!==void 0&&r.push(c)}return r.length===0?t==="OR"?s.constant(!1):void 0:N(r,t,s)},M=new Set(["AND","NOT","OR",L]),P=(n,t,o,s)=>{if(n===L){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=f(t??{},o,s);return i===void 0?void 0:s.negate(i)}return k(t,n,o,s)},f=(n,t,o)=>{const s=[];for(const[i,r]of Object.entries(n))if(M.has(i)){const e=P(i,r,t,o);e!==void 0&&s.push(e)}else s.push(...U(i,r,t,o));return N(s,"AND",o)},q=O.boundParams/2,b=n=>{let t=0,o=0;const s=i=>{const r=b(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"||E(r)?s(r):o+=1;return{lists:t,scalars:o}},J=(n,t,o=R)=>{if(!n||Object.keys(n).length===0)return;const{lists:s,scalars:i}=b(n);if(s===0)return f(n,t,o);const r=Math.max(1,Math.floor(Math.min(q,O.boundParams-i)/s)),e=t.inList??((c,a,u,A)=>o.inList(c,a,u,A??r));return f(n,{...t,inList:(c,a,u)=>e(c,a,u,r)},o)};export{J as c,Y as i,p as j,G as l,I as r,Q as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{t as g,f as j}from"./base64-DfpzS4o_.mjs";const o="$lunora.wire$",d=64,p=1024,w="__proto__",A={BigInt64Array,BigUint64Array,Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array},l={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},O=e=>{if(e===null||typeof e!="object")return!1;const n=Object.getPrototypeOf(e);return n===null||n===Object.prototype},E=(e,n=0)=>{if(n>d)return!0;if(e===null)return!1;const f=typeof e;if(f==="string"||f==="boolean")return!1;if(f==="number")return!Number.isFinite(e);if(f!=="object")return!0;if(Array.isArray(e))return e.length>0&&e[0]===o?!0:e.some(a=>a===void 0||E(a,n+1));if(!O(e)||Object.hasOwn(e,w))return!0;for(const a of Object.keys(e)){const s=e[a];if(s!==void 0&&E(s,n+1))return!0}return!1},b=(e,n=0)=>{if(n>d)throw new RangeError(`wire-codec: value nesting exceeds the ${d}-level limit`);if(e===void 0)return[o,"undefined"];if(e===null)return null;const f=typeof e;if(f==="bigint")return[o,"bigint",e.toString()];if(f==="number"){const r=e;return Number.isNaN(r)?[o,"nan"]:r===1/0?[o,"inf"]:r===-1/0?[o,"-inf"]:r}if(f!=="object")return e;if(e instanceof Date)return[o,"date",b(e.getTime(),n+1)];if(e instanceof Error){const r=e,t={};for(const i of Object.keys(r)){if(r[i]===void 0)continue;const u=b(r[i],n+1);i===w?Object.defineProperty(t,i,{configurable:!0,enumerable:!0,value:u,writable:!0}):t[i]=u}const c=[o,"error",String(r.name),String(r.message),t];return r.cause!==void 0&&c.push(b(r.cause,n+1)),c}if(e instanceof URL)return[o,"url",e.href];if(e instanceof Map)return[o,"map",[...e.entries()].map(([r,t])=>[b(r,n+1),b(t,n+1)])];if(e instanceof Set)return[o,"set",[...e].map(r=>b(r,n+1))];if(e instanceof ArrayBuffer)return[o,"bytes",g(new Uint8Array(e)),"ArrayBuffer"];if(ArrayBuffer.isView(e)){const r=e,t=r.constructor.name,c=new Uint8Array(r.buffer,r.byteOffset,r.byteLength);return t==="Uint8Array"?[o,"bytes",g(c)]:[o,"bytes",g(c),t]}if(Array.isArray(e)){const r=e.map(t=>b(t,n+1));return r.length>0&&r[0]===o?[o,"arr",r]:r}if(!O(e)){const r=e.constructor?.name??"value";throw new TypeError(`wire-codec: cannot encode a ${r} over the Lunora wire — only plain objects, arrays, and the supported built-ins (Date, Error, URL, Map, Set, ArrayBuffer/typed arrays, bigint) round-trip`)}const a=e,s={};for(const r of Object.keys(a)){const t=a[r];if(t===void 0)continue;const c=b(t,n+1);r===w?Object.defineProperty(s,r,{configurable:!0,enumerable:!0,value:c,writable:!0}):s[r]=c}return s},y=(e,n=0)=>{if(n>d)throw new RangeError(`wire-codec: value nesting exceeds the ${d}-level limit`);if(e===null||typeof e!="object")return e;if(Array.isArray(e)){if(e[0]===o)switch(e[1]){case"-inf":return-1/0;case"arr":return e[2].map(r=>y(r,n+1));case"bigint":{const r=e[2];if(typeof r!="string"||r.length>p||!/^-?\d+$/.test(r))throw new RangeError(`wire-codec: invalid or over-long bigint (max ${p} digits)`);return BigInt(r)}case"date":{const r=y(e[2],n+1);if(typeof r!="number")throw new TypeError("wire-codec: malformed date — epoch must be a number");return new Date(r)}case"map":{const r=e[2];return new Map(r.map(t=>{if(!Array.isArray(t)||t.length!==2)throw new TypeError("wire-codec: malformed map entry — expected a [key, value] pair");return[y(t[0],n+1),y(t[1],n+1)]}))}case"set":return new Set(e[2].map(r=>y(r,n+1)));case"url":{const r=e[2];if(typeof r!="string")throw new TypeError("wire-codec: malformed url — href must be a string");return new URL(r)}case"error":{const r=e[2],t=e[3];if(typeof r!="string"||typeof t!="string")throw new TypeError("wire-codec: malformed error — name and message must be strings");const c=(Object.hasOwn(l,r)?l[r]:void 0)??Error,i=new c(t);i.name!==r&&Object.defineProperty(i,"name",{configurable:!0,value:r,writable:!0});const u=y(e[4],n+1);if(u===null||typeof u!="object"||Array.isArray(u))throw new TypeError("wire-codec: malformed error — props must be an object");for(const m of Object.keys(u))m===w?Object.defineProperty(i,m,{configurable:!0,enumerable:!0,value:u[m],writable:!0}):i[m]=u[m];return e.length>5&&Object.defineProperty(i,"cause",{configurable:!0,value:y(e[5],n+1),writable:!0}),i}case"bytes":{const r=e[2];if(typeof r!="string")throw new TypeError("wire-codec: malformed bytes — payload must be a base64 string");const t=j(r);if(g(t)!==r)throw new TypeError("wire-codec: malformed bytes — payload must be canonical padded base64");const c=e[3]??"Uint8Array";if(c==="ArrayBuffer")return t.buffer.byteLength===t.byteLength?t.buffer:t.slice().buffer;const i=Object.hasOwn(A,c)?A[c]:void 0;return i?new i(t.slice().buffer):t}case"inf":return 1/0;case"nan":return Number.NaN;case"undefined":return;default:return e.map(r=>y(r,n+1))}return e.map(s=>y(s,n+1))}const f=e,a={};for(const s of Object.keys(f)){const r=y(f[s],n+1);s===w?Object.defineProperty(a,s,{configurable:!0,enumerable:!0,value:r,writable:!0}):a[s]=r}return a};export{y as d,b as e,O as i,E as n};
|