@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
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/shard-engine",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.71",
|
|
4
4
|
"description": "Host-neutral reactive engine for Lunora: per-shard state, OCC, CDC, reactive subscriptions, and the poke protocol. Consumes @lunora/platform host contracts and can be mounted on any platform host.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cloudflare",
|
|
@@ -48,8 +48,8 @@
|
|
|
48
48
|
"access": "public"
|
|
49
49
|
},
|
|
50
50
|
"dependencies": {
|
|
51
|
-
"@lunora/errors": "1.0.0-alpha.
|
|
52
|
-
"@lunora/platform": "1.0.0-alpha.
|
|
51
|
+
"@lunora/errors": "1.0.0-alpha.38",
|
|
52
|
+
"@lunora/platform": "1.0.0-alpha.32",
|
|
53
53
|
"drizzle-orm": "^0.45.2"
|
|
54
54
|
},
|
|
55
55
|
"engines": {
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as h}from"@lunora/errors";import{q as d}from"./quote-identifier-CGiYFBvY.mjs";const K="__lunora_admin__:",X="__lunora_relation__:",Y="__lunora_flags__:",z={applyCdc:"__lunora_admin__:applyCdc",aiAvailable:"__lunora_admin__:aiAvailable",aiChartConfig:"__lunora_admin__:aiChartConfig",aiGenerateSql:"__lunora_admin__:aiGenerateSql",aiTableFilter:"__lunora_admin__:aiTableFilter",assignIssue:"__lunora_admin__:assignIssue",backRelationCounts:"__lunora_admin__:backRelationCounts",cdcSync:"__lunora_admin__:cdcSync",clearCapturedMail:"__lunora_admin__:clearCapturedMail",clearQueueMessages:"__lunora_admin__:clearQueueMessages",clearTable:"__lunora_admin__:clearTable",createWorkflowInstance:"__lunora_admin__:createWorkflowInstance",deleteRows:"__lunora_admin__:deleteRows",describeTable:"__lunora_admin__:describeTable",describeTables:"__lunora_admin__:describeTables",explainIssue:"__lunora_admin__:explainIssue",exportShard:"__lunora_admin__:exportShard",facetColumn:"__lunora_admin__:facetColumn",getAdvisories:"__lunora_admin__:getAdvisories",getAdvisorProcedures:"__lunora_admin__:getAdvisorProcedures",getAuditLog:"__lunora_admin__:getAuditLog",getAuthMetrics:"__lunora_admin__:getAuthMetrics",getCapturedMail:"__lunora_admin__:getCapturedMail",getFanoutMetrics:"__lunora_admin__:getFanoutMetrics",getFunctionStats:"__lunora_admin__:getFunctionStats",getIssues:"__lunora_admin__:getIssues",getMetricHistory:"__lunora_admin__:getMetricHistory",getMetricSeries:"__lunora_admin__:getMetricSeries",listSubscriptions:"__lunora_admin__:listSubscriptions",listTableIndexes:"__lunora_admin__:listTableIndexes",listTablesIndexes:"__lunora_admin__:listTablesIndexes",getLogs:"__lunora_admin__:getLogs",getMetrics:"__lunora_admin__:getMetrics",getPitrBookmark:"__lunora_admin__:getPitrBookmark",getQueryInsights:"__lunora_admin__:getQueryInsights",getQueueMessages:"__lunora_admin__:getQueueMessages",getRequestLog:"__lunora_admin__:getRequestLog",getSecurityAudit:"__lunora_admin__:getSecurityAudit",getSettings:"__lunora_admin__:getSettings",getTraces:"__lunora_admin__:getTraces",getWorkflowInstanceStatus:"__lunora_admin__:getWorkflowInstanceStatus",ignoreIssue:"__lunora_admin__:ignoreIssue",importShard:"__lunora_admin__:importShard",listFlags:"__lunora_admin__:listFlags",listQueues:"__lunora_admin__:listQueues",lintSql:"__lunora_admin__:lintSql",listTables:"__lunora_admin__:listTables",listWorkflows:"__lunora_admin__:listWorkflows",maskPolicies:"__lunora_admin__:maskPolicies",migrationStatus:"__lunora_admin__:migrationStatus",pitrRestore:"__lunora_admin__:pitrRestore",rankBefore:"__lunora_admin__:rankBefore",rankPage:"__lunora_admin__:rankPage",readTablePage:"__lunora_admin__:readTablePage",recordAuthEvent:"__lunora_admin__:recordAuthEvent",recordContainerEvent:"__lunora_admin__:recordContainerEvent",recordMail:"__lunora_admin__:recordMail",recordQueueMessage:"__lunora_admin__:recordQueueMessage",replayQueueMessage:"__lunora_admin__:replayQueueMessage",resolveIssue:"__lunora_admin__:resolveIssue",rlsPolicies:"__lunora_admin__:rlsPolicies",schemaHistory:"__lunora_admin__:schemaHistory",schemaVersion:"__lunora_admin__:schemaVersion",runAs:"__lunora_admin__:runAs",runMigration:"__lunora_admin__:runMigration",runSql:"__lunora_admin__:runSql",sendQueueMessage:"__lunora_admin__:sendQueueMessage",sendTestMail:"__lunora_admin__:sendTestMail",setIssueSeverity:"__lunora_admin__:setIssueSeverity",storageOrphans:"__lunora_admin__:storageOrphans",storageReferences:"__lunora_admin__:storageReferences",storageRules:"__lunora_admin__:storageRules",studioFeatures:"__lunora_admin__:studioFeatures",writeRow:"__lunora_admin__:writeRow"},N=50,M=500,x=30,F=200,m="__doc__",w=e=>{try{const a=JSON.parse(e);return a!==null&&typeof a=="object"&&!Array.isArray(a)?a:void 0}catch{return}},L=(e,a)=>{if(!e.includes(m))return{columns:e,rows:a};const r=[];for(const s of a){const _=s[m],i=typeof _=="string"?w(_):void 0;if(i===void 0)return{columns:e,rows:a};const u=Object.fromEntries(Object.entries(s).filter(([l])=>l!==m));r.push({...u,...i})}const t=e.filter(s=>s!==m),n=[],o=new Set(t);for(const s of r)for(const _ of Object.keys(s))o.has(_)||(o.add(_),n.push(_));return{columns:[...t,...n],rows:r}},O=e=>e.replaceAll(/[\\%_]/g,a=>`\\${a}`),S=e=>e.startsWith("sqlite_")||e.startsWith("_cf_")||e.startsWith("__miniflare")||e.startsWith("__lunora")||e.includes("__fts_"),C=(e,a,r)=>Math.min(Math.max(e,a),r),k=(e,a)=>{const r=e.exec(`SELECT COUNT(*) AS c FROM ${a}`).one();return Number(r.c)},V=e=>{const a=e.exec("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name").toArray(),r=[];for(const{name:t}of a)S(t)||r.push({name:t,rowCount:k(e,d(t))});return r},A=(e,a)=>e.exec("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ? LIMIT 1",a).toArray().length>0,P={eq:"=",gt:">",gte:">=",lt:"<",lte:"<=",ne:"<>"},U=e=>typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):"",T=(e,a)=>{const r=a.includes(e),t=a.includes(m);if(!(!r&&!t))return r?{expression:d(e),params:[]}:{expression:`json_extract(${d(m)}, ?)`,params:[`$."${e.replaceAll('"','""')}"`]}},W=(e,a)=>{const r=T(e.column,a);if(r===void 0)return;const{expression:t,params:n}=r;return e.operator==="contains"?{params:[...n,`%${O(U(e.value))}%`],sql:String.raw`CAST(${t} AS TEXT) LIKE ? ESCAPE '\'`}:{params:[...n,e.value],sql:`${t} ${P[e.operator]} ?`}},D=/^(\d{4})(?:-(\d{2}))?(?:-(\d{2}))?$/u,q=e=>{const a=D.exec(e.trim());if(a===null)return;const r=Number(a[1]),t=a[2]===void 0?void 0:Number(a[2]),n=a[3]===void 0?void 0:Number(a[3]);if(t!==void 0&&(t<1||t>12)||n!==void 0&&(n<1||n>31)||r<100)return;const o=Date.UTC(r,(t??1)-1,n??1);if(n!==void 0&&new Date(o).getUTCDate()!==n)return;let s;return n!==void 0?s=Date.UTC(r,t===void 0?0:t-1,n+1):t===void 0?s=Date.UTC(r+1,0,1):s=Date.UTC(r,t,1),{from:o,to:s}},v=(e,a,r)=>{const t=[],n=[];if(a!==""&&e.length>0){const o=`%${O(a)}%`,s=e.map(i=>String.raw`CAST(${d(i)} AS TEXT) LIKE ? ESCAPE '\'`);n.push(...e.map(()=>o));const _=q(a);if(_!==void 0)for(const i of e)s.push(`(${d(i)} >= ? AND ${d(i)} < ?)`),n.push(_.from,_.to);t.push(`(${s.join(" OR ")})`)}for(const o of r??[]){const s=W(o,e);s!==void 0&&(t.push(`(${s.sql})`),n.push(...s.params))}return t.length===0?void 0:{parameters:n,where:t.join(" AND ")}},Q=(e,a)=>{if(e===void 0)return;const r=T(e.column,a);if(r===void 0)return;const t=e.direction==="desc"?"DESC":"ASC";return{params:r.params,sql:`${r.expression} ${t}`}},J=(e,a)=>{const{table:r}=a;if(S(r)||!A(e,r))throw new h("UNKNOWN_TABLE",`unknown table: ${r}`,{status:404});const t=C(Math.trunc(a.limit??N),1,M),n=Math.max(0,Math.trunc(a.offset??0)),o=d(r),s=e.exec(`PRAGMA table_info(${o})`).toArray().map(b=>b.name),_=a.search?.trim()??"",i=b=>{if(a.refs===void 0)return b;const I={};for(const R of b.columns){const $=a.refs[R];$!==void 0&&(I[R]=$)}return Object.keys(I).length>0?{...b,refs:I}:b},u=v(s,_,a.filters),l=Q(a.orderBy,s),c=u===void 0?"":` WHERE ${u.where}`,f=l===void 0?"":` ORDER BY ${l.sql}`,g=u?.parameters??[],E=l?.params??[];let p;a.skipCount||(p=u===void 0?k(e,o):Number(e.exec(`SELECT COUNT(*) AS c FROM ${o}${c}`,...g).one().c));const y=e.exec(`SELECT * FROM ${o}${c}${f} LIMIT ? OFFSET ?`,...g,...E,t,n).toArray();return i({...L(s,y),total:p})},Z=(e,a)=>{const{table:r}=a;if(S(r)||!A(e,r))throw new h("UNKNOWN_TABLE",`unknown table: ${r}`,{status:404});const t=C(Math.trunc(a.limit??M),1,M),n=d(r),o=e.exec(`PRAGMA table_info(${n})`).toArray().map(c=>c.name),s=a.search?.trim()??"",_=v(o,s,a.filters),i=_===void 0?e.exec(`SELECT id FROM ${n} LIMIT ?`,t+1).toArray():e.exec(`SELECT id FROM ${n} WHERE ${_.where} LIMIT ?`,..._.parameters,t+1).toArray(),u=i.length>t,l=(u?i.slice(0,t):i).map(c=>c.id);return{hasMore:u,ids:l}},j=(e,a,r)=>{const t=new Set(r.filter(o=>o!==m));if(!r.includes(m))return t;const n=e.exec(`SELECT ${d(m)} AS doc FROM ${a} LIMIT ?`,M).toArray();for(const{doc:o}of n){const s=typeof o=="string"?w(o):void 0;if(s!==void 0)for(const _ of Object.keys(s))t.add(_)}return t},ee=(e,a)=>{const{column:r,table:t}=a;if(S(t)||!A(e,t))throw new h("UNKNOWN_TABLE",`unknown table: ${t}`,{status:404});const n=d(t),o=e.exec(`PRAGMA table_info(${n})`).toArray().map(p=>p.name);if(!j(e,n,o).has(r))throw new h("UNKNOWN_COLUMN",`unknown column: ${r}`,{status:404});const s=T(r,o);if(s===void 0)throw new h("UNKNOWN_COLUMN",`unknown column: ${r}`,{status:404});const _=C(Math.trunc(a.limit??x),1,F),i=a.search?.trim()??"",u=v(o,i,a.filters),l=u===void 0?"":` WHERE ${u.where}`,c=u?.parameters??[],f=e.exec(`SELECT ${s.expression} AS value, COUNT(*) AS count FROM ${n}${l} GROUP BY ${s.expression} ORDER BY count DESC LIMIT ?`,...s.params,...c,...s.params,_+1).toArray(),g=f.length>_,E=g?f.slice(0,_):f;return{truncated:g,values:E.map(p=>({count:Number(p.count),value:p.value}))}},ae=(e,a,r)=>{const t={},n=r.slice(0,M);for(const s of n)t[s]=[];if(n.length===0)return{references:t,storageColumns:a};const o=n.map(()=>"?").join(", ");for(const[s,_]of Object.entries(a)){if(S(s)||!A(e,s))continue;const i=d(s),u=e.exec(`PRAGMA table_info(${i})`).toArray().map(l=>l.name);for(const l of _){const c=T(l,u);if(c===void 0)continue;const f=e.exec(`SELECT id, ${c.expression} AS ref FROM ${i} WHERE ${c.expression} IN (${o})`,...c.params,...c.params,...n).toArray();for(const g of f)t[g.ref]?.push({column:l,id:g.id,table:s})}}return{references:t,storageColumns:a}},te=e=>{const a=e.map((t,n)=>{const o=Object.values(t.subs??{}).map(s=>({args:s.args,functionPath:s.functionPath,table:s.table}));return{admin:t.admin===!0,id:n,subscriptions:o}}),r=a.reduce((t,n)=>t+n.subscriptions.length,0);return{connections:a,totalConnections:a.length,totalSubscriptions:r}},B=20,re=()=>({maxMs:0,passes:0,peakSocketsIterated:0,socketsDelivered:0,socketsIterated:0,totalMs:0}),se=(e,a,r,t)=>({maxMs:Math.max(e.maxMs,t),passes:e.passes+1,peakSocketsIterated:Math.max(e.peakSocketsIterated,a),socketsDelivered:e.socketsDelivered+r,socketsIterated:e.socketsIterated+a,totalMs:e.totalMs+t}),ne=(e,a=B)=>{const r=new Map,t=new Map;for(const o of e){for(const s of Object.values(o.shapes??{})){const _=s.name??"(unknown shape)";r.set(_,(r.get(_)??0)+1)}for(const s of o.whispers??[])t.set(s,(t.get(s)??0)+1)}const n=[...[...r].map(([o,s])=>({kind:"shape",subscribers:s,topic:o})),...[...t].map(([o,s])=>({kind:"whisper",subscribers:s,topic:o}))];return n.sort((o,s)=>s.subscribers-o.subscribers||o.topic.localeCompare(s.topic)),{peakSubscribers:n[0]?.subscribers??0,topics:n.slice(0,a),totalConnections:e.length}};export{z as ADMIN_FUNCTIONS,K as ADMIN_FUNCTION_PREFIX,B as DEFAULT_FANOUT_TOPIC_LIMIT,Y as FLAGS_FUNCTION_PREFIX,M as MAX_PAGE_SIZE,X as RELATION_FUNCTION_PREFIX,re as createFanoutCounters,q as datePrefixRange,ee as facetColumn,ae as findStorageReferences,V as listTables,J as readTablePage,se as recordFanoutPass,Z as selectMatchingIds,ne as summarizeFanoutTopics,te as summarizeSubscriptions};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as o}from"@lunora/errors";const i=new Set(["baseWhere","relationBaseWhere","restrictsCounts","where"]),f=(e,r)=>{for(const[n,t]of Object.entries(r)){const s=e[n];if(t!==null&&typeof t=="object"&&!Array.isArray(t)){const c=Object.keys(t);if(c.length===1&&c[0]==="eq"){if(s!==t.eq)return!1;continue}return!1}if(s!==t)return!1}return!0},h=e=>{if(e===void 0)return{};if(typeof e!="object"||Array.isArray(e))return{where:e};const r=Object.keys(e);return r.length===0?{}:r.every(n=>i.has(n))?e:{where:e}},u={avg:"AVG",count:"COUNT",max:"MAX",min:"MIN",sum:"SUM"},g=e=>{const r=u[e];if(r===void 0)throw new o("INTERNAL",`unknown aggregate op "${e}": expected one of ${Object.keys(u).join(", ")}`);return r},l={runAfter:()=>{throw new o("INTERNAL","ctx.scheduler: no scheduler configured for triggers. Pass `scheduler` to the ctx-db factory.")},runAt:()=>{throw new o("INTERNAL","ctx.scheduler: no scheduler configured for triggers. Pass `scheduler` to the ctx-db factory.")}};export{u as AGGREGATE_SQL_FUNCTION,g as aggregateSqlFunction,f as matchesStaticWhere,h as normalizeCountArgument,l as throwingScheduler};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{sql as i}from"drizzle-orm";import{runDrizzle as n}from"./runDrizzle-GKR3y97k.mjs";import{serializeSqlValue as q}from"./serializeSqlValue-DnpyaLcw.mjs";const s="__doc__",E=(e,t)=>`${e}__geo_${t}`,c=e=>`"${e.replaceAll('"','""')}"`,f=e=>e==="_id"||e==="id"?"id":e==="_creationTime"?"_creationTime":`json_extract(${s}, '$.${e.replaceAll("'","''")}')`,S=e=>i.raw(f(e)),$=(e,t)=>{const r=c(e);return t==="_id"||t==="id"?`${r}.id`:t==="_creationTime"?`${r}._creationTime`:`json_extract(${r}.${s}, '$.${t.replaceAll("'","''")}')`},A=(e,t)=>i.raw($(e,t)),I=(e,t,r,a)=>i`CREATE ${a?i`UNIQUE `:i``}INDEX IF NOT EXISTS ${i.identifier(e)} ON ${i.identifier(t)} (${r})`,_=i.identifier("__key__"),T=i.identifier("__value__"),u=i.identifier("__count__"),N=(e,t,r,a,o)=>i`INSERT INTO ${i.identifier(e)} (${_}, ${T}, ${u}) VALUES (${t}, ${r}, ${a}) ON CONFLICT(${_}) DO UPDATE SET ${o}`,O=e=>{const t=[];for(const[r,a]of Object.entries(e.shape)){const o=a._meta?.column;o&&t.push([r,o])}return t},d=e=>{if(!e)return;const t=e[s];let r;typeof t=="string"?r=JSON.parse(t):t&&typeof t=="object"?r=t:r={};const{id:a}=e;typeof a=="string"&&(r._id=a);const o=e._creationTime;return typeof o=="number"&&(r._creationTime=o),r},y=e=>{try{return d(e)}catch{return}},l=new WeakMap,U=e=>{const t=l.get(e);if(t!==void 0)return t;let r;try{n(e,i`CREATE VIRTUAL TABLE IF NOT EXISTS ${i.identifier("__lunora_fts_probe")} USING fts5(x)`),r=!0}catch{r=!1}finally{try{n(e,i`DROP TABLE IF EXISTS ${i.identifier("__lunora_fts_probe")}`)}catch{}}return l.set(e,r),r};export{u as AGG_COUNT,_ as AGG_KEY,T as AGG_VALUE,s as DOC_COLUMN,N as aggUpsertSql,I as createIndexSql,E as geoTableName,U as isFtsAvailable,f as jsonPath,S as jsonPathSql,$ as qualifiedJsonPath,A as qualifiedJsonPathSql,c as quoteIdentifier,d as rowToDocument,q as serializeSqlValue,O as tableColumns,y as tryRowToDocument};
|
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
const E="__lunora_audit__",i=(t,l,...s)=>t.exec.call(t,l,...s),T=t=>{i(t,`CREATE TABLE IF NOT EXISTS "${E}" (
|
|
2
|
-
seq INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
3
|
-
ts REAL NOT NULL,
|
|
4
|
-
op TEXT NOT NULL,
|
|
5
|
-
"table" TEXT,
|
|
6
|
-
id TEXT,
|
|
7
|
-
detail TEXT
|
|
8
|
-
)`)},o=(t,l)=>{T(t),i(t,`INSERT INTO "${E}" (ts, op, "table", id, detail) VALUES (?, ?, ?, ?, ?)`,l.ts,l.op,l.table??null,l.id??null,l.detail===void 0?null:JSON.stringify(l.detail)),i(t,`DELETE FROM "${E}" WHERE seq <= (SELECT MAX(seq) - ? FROM "${E}")`,1e3)},u=(t,l={})=>{T(t);const s=l.sinceSeq??0,d=Math.max(1,Math.min(l.limit??1e3,1e4));return i(t,`SELECT seq, ts, op, "table", id, detail FROM "${E}" WHERE seq > ? ORDER BY seq DESC LIMIT ?`,s,d).toArray().map(a=>{const e={op:a.op,seq:a.seq,ts:a.ts};return a.table!==null&&(e.table=a.table),a.id!==null&&(e.id=a.id),a.detail!==null&&(e.detail=JSON.parse(a.detail)),e})};export{E as AUDIT_LOG_TABLE,o as appendAuditEntry,T as ensureAuditTable,u as readAuditLog};
|
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
import{sql as e}from"drizzle-orm";import{runDrizzle as a}from"./runDrizzle-GKR3y97k.mjs";import{ConflictError as l}from"./ConflictError-C8GtJmjS.mjs";const o="__cdc_log",$=t=>{a(t,e`CREATE TABLE IF NOT EXISTS ${e.identifier(o)} (
|
|
2
|
-
seq INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
3
|
-
ts REAL NOT NULL,
|
|
4
|
-
${e.identifier("table")} TEXT NOT NULL,
|
|
5
|
-
id TEXT NOT NULL,
|
|
6
|
-
op TEXT NOT NULL,
|
|
7
|
-
doc TEXT
|
|
8
|
-
)`)},R=(t,i,s,E,c,d)=>{const r=d===void 0?null:JSON.stringify(d);a(t,e`INSERT INTO ${e.identifier(o)} (ts, ${e.identifier("table")}, id, op, doc) VALUES (${i}, ${s}, ${E}, ${c}, ${r})`)},A=(t,i={})=>{const s=i.sinceSeq??0,E=Math.max(1,Math.min(i.limit??1e3,1e4)),c=i.tables&&i.tables.size>0?e` AND ${e.identifier("table")} IN (${e.join([...i.tables].map(r=>e`${r}`),e`, `)})`:e``,d=a(t,e`SELECT seq, ts, ${e.identifier("table")}, id, op, doc FROM ${e.identifier(o)} WHERE seq > ${s}${c} ORDER BY seq ASC LIMIT ${E}`).toArray().map(r=>{const T={id:r.id,op:r.op,seq:r.seq,table:r.table,ts:r.ts};return r.doc===null?T:{...T,doc:JSON.parse(r.doc)}});return{changes:d,cursor:d.at(-1)?.seq??s}},O=(t,i)=>{a(t,e`DELETE FROM ${e.identifier(o)} WHERE seq <= ${i}`)},I=t=>{const i=a(t,e`SELECT seq FROM sqlite_sequence WHERE name = ${o}`).toArray()[0]?.seq;return typeof i=="number"?i:a(t,e`SELECT MAX(seq) AS seq FROM ${e.identifier(o)}`).toArray()[0]?.seq??0},S=t=>a(t,e`SELECT MIN(seq) AS seq FROM ${e.identifier(o)}`).toArray()[0]?.seq??void 0,n="__cdc_meta",p=t=>{a(t,e`CREATE TABLE IF NOT EXISTS ${e.identifier(n)} (id INTEGER PRIMARY KEY CHECK (id = 1), epoch TEXT NOT NULL)`)},m=t=>{p(t);const i=a(t,e`SELECT epoch FROM ${e.identifier(n)} WHERE id = 1`).toArray()[0]?.epoch;if(typeof i=="string"&&i.length>0)return i;const s=crypto.randomUUID();return a(t,e`INSERT INTO ${e.identifier(n)} (id, epoch) VALUES (1, ${s})`),s},q=t=>{p(t);const i=crypto.randomUUID();return a(t,e`INSERT INTO ${e.identifier(n)} (id, epoch) VALUES (1, ${i}) ON CONFLICT(id) DO UPDATE SET epoch = excluded.epoch`),i},C=async(t,i)=>{if(i.op==="delete"){await t.delete(i.id,i.table);return}const s=i.doc??{};try{await t.insert(i.table,s,{allowExplicitId:!0})}catch(E){if(!(E instanceof l))throw E;const c={};for(const[d,r]of Object.entries(s))d!=="_id"&&(c[d]=r);await t.replace(i.id,c,void 0,{allowExplicitId:!0})}},h=async(t,i)=>{for(const s of i)await C(t,s)};export{o as CDC_LOG_TABLE,n as CDC_META_TABLE,R as appendCdcChange,h as applyCdcChanges,q as bumpCdcEpoch,$ as migrateCdcLog,p as migrateCdcMeta,S as minCdcSeq,A as readCdcChanges,I as readCdcCursor,m as readCdcEpoch,O as trimCdcChanges};
|
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
import{sql as t}from"drizzle-orm";import{runDrizzle as n}from"./runDrizzle-GKR3y97k.mjs";const _="__client_watermark",l=i=>{n(i,t`CREATE TABLE IF NOT EXISTS ${t.identifier(_)} (
|
|
2
|
-
identity TEXT NOT NULL,
|
|
3
|
-
client_id TEXT NOT NULL,
|
|
4
|
-
last_mutation_id INTEGER NOT NULL,
|
|
5
|
-
PRIMARY KEY (identity, client_id)
|
|
6
|
-
)`)},E=(i,e,a)=>n(i,t`SELECT last_mutation_id FROM ${t.identifier(_)} WHERE identity = ${e} AND client_id = ${a} LIMIT 1`).toArray()[0]?.last_mutation_id??0,m=(i,e,a,d)=>{n(i,t`INSERT INTO ${t.identifier(_)} (identity, client_id, last_mutation_id) VALUES (${e}, ${a}, ${d})
|
|
7
|
-
ON CONFLICT(identity, client_id) DO UPDATE SET last_mutation_id = MAX(last_mutation_id, excluded.last_mutation_id)`)};export{_ as CLIENT_WATERMARK_TABLE,m as advanceClientWatermark,l as migrateClientWatermark,E as readClientWatermark};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as y}from"@lunora/errors";class A extends y{constructor(e){super("COUNT_RLS_UNSUPPORTED",e===void 0?"count() is not supported in an RLS-restricted context":`count() is not supported on table "${e}" inside an RLS-restricted context`)}}const R=(t,e)=>t?e?{AND:[t,e]}:t:e,g=new Set(["AND","NOT","OR"]),f=Symbol("not-eq"),x=t=>{if(t!==null&&typeof t=="object"&&!Array.isArray(t)){const e=Object.keys(t);return e.length===1&&e[0]==="eq"?t.eq:f}return t},d=(t,e)=>{const s={};for(const[o,n]of Object.entries(t)){if(g.has(o)||!e(o))return;const r=x(n);if(r===f)return;s[o]=r}return s},a=(t,e,s,o)=>{const n={...e};if(!t)return n;for(const[r,i]of Object.entries(t))if(r in n){if(n[r]!==i)return}else if(o&&r in s){if(s[r]!==i)return}else n[r]=i;return n},b=(t,e)=>{const s=t.by??[],o=e??{},n=d(o,r=>s.includes(r));if(n!==void 0){for(const r of s)if(!(r in n))return;return a(t.where,n,o,!0)}},h=(t,e,s)=>{const o=d(e??{},n=>s.has(n));if(o!==void 0)return a(t.where,o,{},!1)},l=(t,e,s,o)=>{let n;for(const r of t){if(r.op!==e||e!=="count"&&r.field!==s)continue;const i=b(r,o);i&&(!n||(r.by?.length??0)>(n.index.by?.length??0))&&(n={index:r,key:i})}return n},S=(t,e)=>l(t,"count",void 0,e),v=(t,e,s,o)=>l(t,e,s,o),L=(t,e,s,o,n)=>{const r=new Set(o);for(const i of t){if(i.op!==e||e!=="count"&&i.field!==s)continue;const c=i.by??[];if(c.length!==r.size||!c.every(p=>r.has(p)))continue;const u=h(i,n,r);if(u!==void 0)return{index:i,partial:u}}};export{A as CountRlsUnsupportedError,R as mergeWhere,b as planAggregateLookup,v as selectIndexForAggregate,S as selectIndexForCount,L as selectIndexForGroupBy};
|
|
@@ -1,31 +0,0 @@
|
|
|
1
|
-
import{LunoraError as O}from"@lunora/errors";const o="__lunora_migrations",y=100,D=3e4,$=1e4,c=(r,t,...e)=>r.exec.call(r,t,...e),w=r=>{c(r,`CREATE TABLE IF NOT EXISTS "${o}" (
|
|
2
|
-
id TEXT PRIMARY KEY,
|
|
3
|
-
direction TEXT NOT NULL,
|
|
4
|
-
status TEXT NOT NULL,
|
|
5
|
-
cursor TEXT,
|
|
6
|
-
processed INTEGER NOT NULL DEFAULT 0,
|
|
7
|
-
changed INTEGER NOT NULL DEFAULT 0,
|
|
8
|
-
started_at REAL,
|
|
9
|
-
updated_at REAL,
|
|
10
|
-
error TEXT
|
|
11
|
-
)`)},N=(r,t)=>{const e=c(r,`SELECT * FROM "${o}" WHERE id = ?`,t).toArray()[0];if(e)return{changed:e.changed,cursor:typeof e.cursor=="string"?e.cursor:null,direction:e.direction==="down"?"down":"up",processed:e.processed,startedAt:typeof e.started_at=="number"?e.started_at:void 0,status:e.status==="completed"||e.status==="failed"?e.status:"in_progress"}},U=(r,t)=>{c(r,`DELETE FROM "${o}" WHERE id = ?`,t)},R=(r,t)=>{c(r,`INSERT INTO "${o}"
|
|
12
|
-
(id, direction, status, cursor, processed, changed, started_at, updated_at, error)
|
|
13
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
14
|
-
ON CONFLICT(id) DO UPDATE SET
|
|
15
|
-
direction = excluded.direction,
|
|
16
|
-
status = excluded.status,
|
|
17
|
-
cursor = excluded.cursor,
|
|
18
|
-
processed = excluded.processed,
|
|
19
|
-
changed = excluded.changed,
|
|
20
|
-
updated_at = excluded.updated_at,
|
|
21
|
-
error = excluded.error`,t.id,t.direction,t.status,t.cursor,t.processed,t.changed,t.startedAt,t.updatedAt,t.error)},b=(r,t,e,a)=>(c(r,`INSERT INTO "${o}"
|
|
22
|
-
(id, direction, status, cursor, processed, changed, started_at, updated_at, error)
|
|
23
|
-
VALUES (?, ?, 'in_progress', NULL, 0, 0, ?, ?, NULL)
|
|
24
|
-
ON CONFLICT(id) DO UPDATE SET
|
|
25
|
-
status = 'in_progress',
|
|
26
|
-
updated_at = excluded.updated_at
|
|
27
|
-
WHERE
|
|
28
|
-
"${o}".direction <> excluded.direction
|
|
29
|
-
OR "${o}".status <> 'in_progress'
|
|
30
|
-
OR "${o}".updated_at IS NULL
|
|
31
|
-
OR "${o}".updated_at <= excluded.updated_at - ${String(D)}`,t,e,a,a),c(r,"SELECT changes() AS changed").one().changed>0),x=(r,t)=>{c(r,`UPDATE "${o}" SET updated_at = 0 WHERE id = ? AND status = 'in_progress'`,t)},M=(r,t,e)=>{c(r,`UPDATE "${o}" SET updated_at = ? WHERE id = ? AND status = 'in_progress'`,e,t)},F=(r,t)=>{if(c(r,"SELECT name FROM sqlite_master WHERE type = 'table' AND name = ? LIMIT 1",o).toArray().length===0)return[];const e=t===void 0?" ORDER BY id":" WHERE id = ?",a=t===void 0?[]:[t];return c(r,`SELECT * FROM "${o}"${e}`,...a).toArray().map(d=>({changed:d.changed,cursor:typeof d.cursor=="string"?d.cursor:null,direction:d.direction==="down"?"down":"up",error:typeof d.error=="string"?d.error:null,id:d.id,processed:d.processed,startedAt:typeof d.started_at=="number"?d.started_at:null,status:d.status==="completed"||d.status==="failed"?d.status:"in_progress",updatedAt:typeof d.updated_at=="number"?d.updated_at:null}))},H=async r=>{const{migration:t,sql:e,writer:a}=r,d=r.direction??"up",n=r.dryRun??!1,g=r.clock??(()=>Date.now()),m=r.maxBatches??Number.POSITIVE_INFINITY,S=r.batchSize??t.batchSize??y,L=d==="up"?t.up:t.down;if(!L)throw new O("INTERNAL",`data migration "${t.id}" has no \`${d}\` transform`);const I={db:{count:a.count.bind(a),findFirst:a.findFirst.bind(a),findMany:a.findMany.bind(a),get:a.get.bind(a)}};let u=null,l=0,T=0,_=g();if(!n){w(e);const s=N(e,t.id);if(s?.direction===d&&s.status==="completed")return{changed:s.changed,cursor:null,direction:d,dryRun:n,id:t.id,processed:s.processed,status:"completed"};if(s&&s.direction!==d&&U(e,t.id),!b(e,t.id,d,g())){const E=N(e,t.id);return{changed:E?.changed??0,cursor:E?.cursor??u,direction:d,dryRun:n,id:t.id,processed:E?.processed??0,status:E?.status??"in_progress"}}const i=s?.direction===d?s:void 0;i&&(u=i.cursor,l=i.processed,T=i.changed,_=i.startedAt??_)}let p=!1,A=0,h=_;try{for(;!p&&A<m;){const s=await a.findMany(t.table,{cursor:u,limit:S});for(const i of s.page){l+=1;const E=await L(i,I);if(E!==void 0&&(T+=1,n||await a.replace(String(i._id),{...E,_creationTime:i._creationTime,_id:i._id},void 0,{allowExplicitId:!0})),!n){const f=g();f-h>=$&&(M(e,t.id,f),h=f)}}if(u=s.continueCursor,p=s.isDone,A+=1,!n){const i=g();R(e,{changed:T,cursor:p?null:u,direction:d,error:null,id:t.id,processed:l,startedAt:_,status:p?"completed":"in_progress",updatedAt:i}),h=i;try{await r.onBatch?.({batches:A,changed:T,processed:l})}catch{}}}}catch(s){throw n||R(e,{changed:T,cursor:u,direction:d,error:s instanceof Error?s.message:String(s),id:t.id,processed:l,startedAt:_,status:"failed",updatedAt:g()}),s}if(!n&&!p)try{x(e,t.id)}catch(s){console.warn(`data migration "${t.id}": releaseClaim failed`,s)}return{changed:T,cursor:p?null:u,direction:d,dryRun:n,id:t.id,processed:l,status:p?"completed":"in_progress"}};export{o as DATA_MIGRATION_STATE_TABLE,F as readMigrationStatus,H as runDataMigration};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as h}from"@lunora/errors";import{distinctValues as O}from"./applyOnDelete-uFRC5p1d.mjs";import{RELATION_EXISTS_KEY as R}from"./RELATION_EXISTS_KEY-BaqSIFU1.mjs";const f={every:{kind:"many",negateChild:!0,negated:!0},is:{kind:"one",negated:!1},isNot:{kind:"one",negated:!0,nullDisjunct:!0},none:{kind:"many",negated:!0},some:{kind:"many",negated:!1}},k=new Set(Object.keys(f)),A=e=>e.kind==="one"?{clause:e.field,project:e.references}:{clause:e.references,project:e.field},E=5e3,u=Symbol("relation-key-overflow"),b=e=>Array.isArray(e)?e.map(t=>t??{}):[],g=e=>{if(e.length===1){const[t]=e;return t??{}}return e.length===0?{}:{AND:e}},p=e=>{if(e===null||typeof e!="object"||Array.isArray(e))return!1;const t=Object.keys(e);return t.length>0&&t.every(n=>k.has(n))},d=(e,t,n)=>{const a=t.tables[n]?.relationMap??{};return Object.keys(e).some(r=>{const s=e[r];return r==="AND"||r==="OR"?b(s).some(o=>d(o,t,n)):r==="NOT"?d(s??{},t,n):!!a[r]&&p(s)})},v=(e,t,n,a)=>{if(e&&d(e,t,n))throw new h("INTERNAL",`relation-crossing predicates are not supported in ${a}() — use them in findMany/findFirst or an RLS read policy`)},T=async(e,t,n,a,r)=>{const s=await c(t,e.table,a),{page:o}=await a.fetcher(e.table,{baseWhere:a.relationBaseWhere?.(e.table),relationBaseWhere:a.relationBaseWhere,where:s}),i=O(o,n);if(i.length>a.maxRelationKeys){if(r)return u;throw new h("INTERNAL",`relation predicate on "${e.table}" matched ${String(i.length)} rows, exceeding the ${String(a.maxRelationKeys)}-key limit; narrow the predicate (a same-shard EXISTS push-down lifts this cap)`)}return i},j=async(e,t,n,a,r)=>{const s=f[e];if(!s)throw new h("INTERNAL",`unknown relation operator "${e}"`);const{clause:o,project:i}=A(t),l=await T(t,s.negateChild?{NOT:n}:n,i,a,r);return l===u?u:s.negated?s.nullDisjunct?{OR:[{[o]:{notIn:l}},{[o]:{isNull:!0}}]}:{[o]:{notIn:l}}:{[o]:{in:l}}},w=async(e,t,n,a,r)=>{const s=f[e];if(!s)throw new h("INTERNAL",`unknown relation operator "${e}"`);const o=r.relationBaseWhere?.(t.table),i=s.negateChild?{NOT:n}:n,l={childWhere:await c(o?{AND:[o,i]}:i,t.table,r),negated:s.negated,parentTable:a,relation:t};return{[R]:l}},S=(e,t,n)=>{const a=f[e];if(a&&a.kind!==n.kind)throw new h("INTERNAL",`relation operator "${e}" requires a to-${a.kind} relation, but "${t}" is to-${n.kind}`)},$=async(e,t,n,a,r)=>{const s=[];for(const o of Object.keys(n)){S(o,e,t);const i=n[o]??{},l=r.canPushExists?.(t)??!1;if(l&&r.existsPushMode==="always"){s.push(await w(o,t,i,a,r));continue}const m=await j(o,t,i,r,l);m===u?s.push(await w(o,t,i,a,r)):s.push(m)}return g(s)},x=async(e,t,n,a)=>{if(e==="AND"||e==="OR"){const s=[];for(const o of b(t))s.push(await c(o,n,a));return{[e]:s}}if(e==="NOT")return{NOT:await c(t??{},n,a)};const r=a.schema.tables[n]?.relationMap?.[e];return r&&p(t)?$(e,r,t,n,a):{[e]:t}},c=async(e,t,n)=>{const a=[];for(const r of Object.keys(e))a.push(await x(r,e[r],t,n));return g(a)},M=async(e,t)=>!e||!d(e,t.schema,t.tableName)?e:c(e,t.tableName,{canPushExists:t.canPushExists,existsPushMode:t.existsPushMode??"auto",fetcher:t.fetcher,maxRelationKeys:t.maxRelationKeys??E,relationBaseWhere:t.relationBaseWhere,schema:t.schema}),y=(e,t,n)=>{for(const a of e){const r=N(a,t,n);if(r)return r}},I=(e,t,n,a)=>{if(e==="AND"||e==="OR")return y(b(t),n,a);if(e==="NOT")return y([t??{}],n,a);const r=n.tables[a]?.relationMap?.[e];if(!(!r||!p(t)))return n.tables[r.table]?.shardMode?.kind==="shardBy"?{relation:e,target:r.table}:y(Object.values(t),n,r.table)},N=(e,t,n)=>{for(const a of Object.keys(e)){const r=I(a,e[a],t,n);if(r)return r}},W=(e,t,n)=>{if(!e)return;const a=N(e,t,n);if(a)throw Object.assign(new Error(`shape on "${n}" joins the sharded table "${a.target}" via relation "${a.relation}" — a live shape cannot replicate rows that live in another shard's Durable Object. Fix it by (a) denormalizing the joined columns into "${n}", or (b) moving "${a.target}" to .global() so it is served through the latency-tiered D1 shape tier.`),{code:"SHAPE_CROSS_SHARD_JOIN",name:"LunoraError",status:400})};export{E as DEFAULT_MAX_RELATION_KEYS,v as assertFlatPredicate,W as assertShapeShardable,d as containsRelationPredicate,p as isRelationPredicate,M as resolveRelationPredicates};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{toErrorBody as k,LunoraError as N}from"@lunora/errors";import{f as g,c as R}from"./wire-codec-Ctnni0h6.mjs";import{relayName as p,nextPromotionState as L,shapeRoutingKey as f,parseRelayName as C,clampPromotionThresholds as O,DEFAULT_PROMOTION_THRESHOLDS as w}from"./DEFAULT_PROMOTION_THRESHOLDS-Dteg0sZF.mjs";import{encodeRowsPatch as b,buildPokeFrames as v}from"./buildPokeFrames-DaPpm5Ss.mjs";import{awaitWsDrain as T,trySendFrame as I}from"./awaitWsDrain-CCZ-8wjm.mjs";import{stableWireKey as u}from"./stableWireKey-YEHLaX6X.mjs";const D=(i,e)=>{const t=Math.max(i.length,e.length);let s=i.length^e.length;for(let r=0;r<t;r+=1){const a=r<i.length?i.charCodeAt(r):0,o=r<e.length?e.charCodeAt(r):0;s|=a^o}return s===0},F=2,x=8,$="LUNORA_RELAY_SECRET",_="x-lunora-relay-sig",E=i=>{const e=i?.[$];return typeof e=="string"&&e.length>0?e:void 0},A=async(i,e)=>{const t=new TextEncoder,s=await crypto.subtle.importKey("raw",t.encode(i),{hash:"SHA-256",name:"HMAC"},!1,["sign"]),r=await crypto.subtle.sign("HMAC",s,t.encode(e));return[...new Uint8Array(r)].map(a=>a.toString(16).padStart(2,"0")).join("")},y=(i,e,t)=>{const s=i?.[e];let r=Number.NaN;return typeof s=="string"?r=Number.parseInt(s,10):typeof s=="number"&&(r=s),Number.isInteger(r)&&r>0?r:t},S={},U=i=>{throw new N("INTERNAL",`unhandled relay frame: ${JSON.stringify(i)}`)},K=i=>{if(i===null||typeof i!="object")return;const e=i;return typeof e.idFromName=="function"&&typeof e.get=="function"?e:void 0},W=i=>Response.json(i,{headers:{"content-type":"application/json"}}),m=()=>new Response(null,{status:204});class P{constructor(e,t){this.host=e,this.roleId=t}host;roleId;async handleControl(e){let t;try{t=await e.text()}catch{return new Response("bad request",{status:400})}const s=E(this.host.env());if(s!==void 0){const a=e.headers.get(_),o=await A(s,t);if(a===null||!D(a,o))return new Response("forbidden",{status:403})}let r;try{r=JSON.parse(t)}catch{return new Response("bad request",{status:400})}switch(r.type){case"relay_attach":return this.onAttach(r.relayIndex),m();case"relay_detach":return this.onDetach(r.relayIndex),m();case"relay_frame":return this.host.deliverWhisperLocal(r.topic,r.frame,void 0),await this.onWhisperFrame(r),m();case"relay_shape_poke":{const a=this.host.getWebSockets().length,o=Date.now(),n=this.onShapePoke({...r,args:R(r.args)});return this.host.recordShapePokeFanout(a,n,Date.now()-o),m()}case"relay_shape_subscribe":return W(this.onShapeSubscribe({...r,args:R(r.args)}));default:return U(r)}}maxRelays(){return y(this.host.env(),"LUNORA_MAX_RELAYS",x)}canAddressSiblings(){return this.relayNamespace()!==void 0}relayNamespace(){const e=this.host.shardBinding();if(e!==void 0)return K(this.host.env()?.[e])}async postRelayMessage(e,t){await this.requestRelayMessage(e,t)}async requestRelayMessage(e,t){const s=this.relayNamespace();if(s===void 0)return;const r=typeof s.getByName=="function"?s.getByName(e):s.get(s.idFromName(e)),a=JSON.stringify(t),o={"content-type":"application/json","x-lunora-shard-binding":this.host.shardBinding()??""},n=E(this.host.env());n!==void 0&&(o[_]=await A(n,a));try{return await r.fetch("https://relay.internal/_lunora/relay",{body:a,headers:o,method:"POST"})}catch{return}}}class q extends P{shapeUniformCache=new Map;relaySetCache;relayShapeRegistry=new Map;relayShapeProxies=new Map;promotionState="owned";constructor(e,t){super(e,{ownerKey:t})}async forwardWhisper(e,t){if(!this.canAddressSiblings())return;const s=this.ownerRelaySet();s.size!==0&&await Promise.all([...s].map(r=>this.postRelayMessage(p(this.roleId.ownerKey,r),{frame:t,topic:e,type:"relay_frame"})))}async onFlush(e,t){await Promise.all([this.multicastShapePokes(e,t),this.proxyShapePokes(e,t)])}seedRelayShape(){return Promise.resolve(void 0)}announce(){return Promise.resolve()}announceDrain(){return Promise.resolve()}relayCount(){const e=this.host.getWebSockets().length,t=y(this.host.env(),"LUNORA_RELAY_THRESHOLD",w.tUp),s=y(this.host.env(),"LUNORA_RELAY_COLLAPSE_THRESHOLD",w.tDown);if(this.promotionState=L(this.promotionState,e,O(t,s)),this.promotionState==="owned")return 0;const r=y(this.host.env(),"LUNORA_MAX_RELAYS",x),a=y(this.host.env(),"LUNORA_RELAY_FAN",F);return Math.min(r,Math.max(1,a))}isShapeRelayUniform(e,t){const s=f(e,t),r=this.shapeUniformCache.get(s);if(r!==void 0)return r;const a=this.probeShapeRelayUniform(e,t);return this.shapeUniformCache.set(s,a),a}onAttach(e){this.addRelayToSet(e)}onDetach(e){this.removeRelayFromSet(e)}async onWhisperFrame(e){await Promise.all([...this.ownerRelaySet()].filter(t=>t!==e.originRelay).map(t=>this.postRelayMessage(p(this.roleId.ownerKey,t),{frame:e.frame,topic:e.topic,type:"relay_frame"})))}onShapeSubscribe(e){return this.buildShapeSeedFrames(e)}onShapePoke(){return 0}async multicastShapePokes(e,t){if(this.relayShapeRegistry.size===0)return;const s=this.ownerRelaySet();if(s.size===0)return;const r=this.host.currentCdcEpoch(),a=[];for(const o of this.relayShapeRegistry.values()){let n;try{n=this.host.resolveShape(o.name,o.args,S)}catch{continue}if(n===void 0||n.global===!0||!e.has(n.table))continue;const h=o.cursor,l=this.host.buildShapeDiff(n,h,t);if(l.length===0)continue;o.cursor=t;const d={args:g(o.args),checkpoint:t,epoch:r,fromCursor:h,name:o.name,rowsPatch:b(l),type:"relay_shape_poke"};for(const c of s)a.push(this.postRelayMessage(p(this.roleId.ownerKey,c),d))}await Promise.all(a)}async proxyShapePokes(e,t){if(this.relayShapeProxies.size===0)return;const s=this.host.currentCdcEpoch(),r=[];for(const a of this.relayShapeProxies.values()){let o;try{o=this.host.resolveShape(a.name,a.args,a.identity)}catch{continue}if(o===void 0||o.global===!0||!e.has(o.table))continue;const n=a.cursor,h=this.host.buildShapeDiff(o,n,t);if(h.length===0)continue;a.cursor=t;const l={args:g(a.args),checkpoint:t,epoch:s,fromCursor:n,name:a.name,rowsPatch:b(h),targetConnectionId:a.connectionId,type:"relay_shape_poke"};r.push(this.postRelayMessage(p(this.roleId.ownerKey,a.relayIndex),l))}await Promise.all(r)}buildShapeSeedFrames(e){const t={identity:e.identity,userId:e.userId};let s;try{s=this.host.resolveShape(e.name,e.args,t)}catch(d){const{body:c}=k(d,{fallbackCode:"SHAPE_RESOLVE_FAILED",redactedMessage:"shape resolution failed"});return{error:{code:c.code,message:c.message}}}if(s===void 0||s.global===!0)return{error:{code:"SHAPE_NOT_FOUND",message:`shape not relayable: ${e.name}`}};e.relayIndex!==void 0&&this.addRelayToSet(e.relayIndex);const{baseCheckpoint:r,cursor:a,epoch:o,rowsPatch:n}=this.host.computeOpLogShapeSeed({args:e.args,name:e.name,sinceEpoch:e.sinceEpoch,sinceSeq:e.sinceSeq},s);let h=a;if(this.isShapeRelayUniform(e.name,e.args)){const d=f(e.name,e.args);let c=this.relayShapeRegistry.get(d);c===void 0&&(c={args:e.args,cursor:a,name:e.name},this.relayShapeRegistry.set(d,c)),h=c.cursor}else e.relayIndex!==void 0&&e.connectionId!==void 0&&this.relayShapeProxies.set(`${String(e.relayIndex)}:${e.connectionId}:${e.subId}`,{args:e.args,connectionId:e.connectionId,cursor:a,epoch:o,identity:t,name:e.name,relayIndex:e.relayIndex,subId:e.subId});const l=v([{rowsPatch:n,shapeId:e.subId}],{baseCheckpoint:r,checkpoint:a,epoch:o,lastMutationId:void 0,pokeId:this.host.nextPokeId()});return{cursor:h,epoch:o,frames:l}}ensureRelayTable(){this.host.sql().exec("CREATE TABLE IF NOT EXISTS __lunora_relays (idx INTEGER PRIMARY KEY)")}ownerRelaySet(){if(this.relaySetCache===void 0){this.ensureRelayTable();const e=this.host.sql().exec("SELECT idx FROM __lunora_relays").toArray();this.relaySetCache=new Set(e.map(t=>Number(t.idx)))}return this.relaySetCache}addRelayToSet(e){this.ensureRelayTable(),this.host.sql().exec("INSERT OR IGNORE INTO __lunora_relays (idx) VALUES (?)",e),this.ownerRelaySet().add(e)}removeRelayFromSet(e){this.ensureRelayTable(),this.host.sql().exec("DELETE FROM __lunora_relays WHERE idx = ?",e);const t=this.ownerRelaySet();t.delete(e);for(const[s,r]of this.relayShapeProxies)r.relayIndex===e&&this.relayShapeProxies.delete(s);t.size===0&&(this.relayShapeRegistry.clear(),this.shapeUniformCache.clear())}probeShapeRelayUniform(e,t){let s;try{s=this.host.resolveShape(e,t,S)}catch{return!1}if(s===void 0||s.global===!0||this.host.rlsMetadata().policies.some(h=>h.on==="read"&&h.table===s.table)||this.tableHasAnyMask(s.table))return!1;const r=u(s.effectiveWhere),a=u(s.columns);let o=!1;const n=h=>{const l={groups:[`grp_${h}`],roles:[h],sub:`__lunora_probe_${h}__`};return{identity:new Proxy(l,{get:(d,c)=>typeof c=="symbol"||c in d?Reflect.get(d,c):`${h}:${c}`,getOwnPropertyDescriptor:(d,c)=>(o=!0,Reflect.getOwnPropertyDescriptor(d,c)),has:(d,c)=>typeof c=="symbol"?Reflect.has(d,c):!0,ownKeys:d=>(o=!0,Reflect.ownKeys(d))}),userId:`__lunora_probe_${h}__`}};return[S,n("a"),n("b")].every(h=>{let l;try{l=this.host.resolveShape(e,t,h)}catch{return!1}return l!==void 0&&l.global!==!0&&l.table===s.table&&u(l.effectiveWhere)===r&&u(l.columns)===a})&&!o}tableHasAnyMask(e){return this.host.maskMetadata().columns.some(t=>t.table===e)}}class H extends P{relayAnnounced=!1;shapeRelayMemos=new WeakMap;constructor(e,t,s){super(e,{ownerKey:t,relayIndex:s})}async forwardWhisper(e,t){this.canAddressSiblings()&&await this.postRelayMessage(this.roleId.ownerKey,{frame:t,originRelay:this.roleId.relayIndex,topic:e,type:"relay_frame"})}onFlush(){return Promise.resolve()}async seedRelayShape(e,t,s,r){if(!this.canAddressSiblings())return{code:"RELAY_MISCONFIGURED",message:"relay cannot address its owner"};await this.announce();const a={args:g(s.args??{}),connectionId:this.host.readAttachment(e).connectionId,identity:r.identity,name:s.name,relayIndex:this.roleId.relayIndex,sinceEpoch:s.sinceEpoch,sinceSeq:s.sinceSeq,subId:t,type:"relay_shape_subscribe",userId:r.userId},o=await this.requestRelayMessage(this.roleId.ownerKey,a);if(o===void 0)return{code:"RELAY_SEED_FAILED",message:"owner did not answer the shape seed"};let n;try{n=await o.json()}catch{return{code:"RELAY_SEED_FAILED",message:"malformed shape seed from owner"}}if(n.error!==void 0)return n.error;if(n.frames===void 0)return{code:"RELAY_SEED_FAILED",message:"owner returned no shape frames"};await T(e);for(const h of n.frames)I(e,h);return this.recordRelayShapeMemo(e,t,n.cursor??0,n.epoch),"ok"}async announce(){this.relayAnnounced||!this.canAddressSiblings()||(this.relayAnnounced=!0,(await this.requestRelayMessage(this.roleId.ownerKey,{relayIndex:this.roleId.relayIndex,type:"relay_attach"}))?.ok||(this.relayAnnounced=!1))}async announceDrain(e){this.canAddressSiblings()&&(this.host.getWebSockets().some(t=>t!==e)||(this.relayAnnounced=!1,await this.postRelayMessage(this.roleId.ownerKey,{relayIndex:this.roleId.relayIndex,type:"relay_detach"})))}relayCount(){return 0}isShapeRelayUniform(){return!1}onAttach(){}onDetach(){}onWhisperFrame(){return Promise.resolve()}onShapeSubscribe(){return{error:{code:"RELAY_CANNOT_SEED",message:"a relay has no op-log to seed from"}}}onShapePoke(e){return this.deliverShapePoke(e)}recordRelayShapeMemo(e,t,s,r){let a=this.shapeRelayMemos.get(e);a===void 0&&(a=new Map,this.shapeRelayMemos.set(e,a)),a.set(t,{cursor:s,epoch:r})}deliverShapePoke(e){const t=f(e.name,e.args);let s=0;for(const r of this.host.getWebSockets()){const a=this.host.readAttachment(r),{shapes:o}=a,n=this.shapeRelayMemos.get(r);if(!(o===void 0||n===void 0)&&!(e.targetConnectionId!==void 0&&a.connectionId!==e.targetConnectionId))for(const[h,l]of Object.entries(o)){const d=n.get(h);if(d?.cursor!==e.fromCursor||d.epoch!==e.epoch||f(l.name,l.args)!==t)continue;const c=v([{rowsPatch:e.rowsPatch,shapeId:h}],{baseCheckpoint:void 0,checkpoint:e.checkpoint,epoch:e.epoch,lastMutationId:void 0,pokeId:this.host.nextPokeId()},{preEncoded:!0});for(const M of c)I(r,M);n.set(h,{cursor:e.checkpoint,epoch:e.epoch}),s+=1}}return s}}const J=i=>{const e=i.doName();if(e===void 0)return;const t=C(e);return t===void 0?new q(i,e):new H(i,t.ownerKey,t.relayIndex)};export{x as DEFAULT_MAX_RELAYS,q as OwnerRelay,H as RelayMember,J as createRelayLink};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as s}from"@lunora/errors";import{stableWireKey as i}from"./stableWireKey-YEHLaX6X.mjs";const a="::relay::",h=(t,o)=>`${t}${a}${String(o)}`,w=t=>{const o=t.lastIndexOf(a);if(o===-1)return;const r=t.slice(0,o),n=t.slice(o+a.length),e=Number(n);if(!(r.length===0||!Number.isInteger(e)||e<0||String(e)!==n))return{ownerKey:r,relayIndex:e}},d=(t,o)=>i({args:o??{},name:t}),m={tDown:4e3,tUp:8e3},u=(t,o,r=m)=>{if(r.tDown>=r.tUp)throw new s("INTERNAL",`invalid promotion thresholds: tDown (${String(r.tDown)}) must be < tUp (${String(r.tUp)})`);return t==="owned"?o>=r.tUp?"promoted":"owned":o<r.tDown?"owned":"promoted"},c=(t,o)=>o<t?{tDown:o,tUp:t}:{tDown:Math.min(Math.max(1,Math.floor(t/2)),t-1),tUp:t},g=(t,o,r)=>{if(t<=o||o<=0)return 0;const n=t-o,e=Math.ceil(n/o);return Math.min(e,Math.max(0,r))};export{m as DEFAULT_PROMOTION_THRESHOLDS,a as RELAY_NAME_INFIX,c as clampPromotionThresholds,u as nextPromotionState,w as parseRelayName,g as relayCountFor,h as relayName,d as shapeRoutingKey};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as i}from"@lunora/errors";import{t as e}from"./estimate-bytes-DwQON1Ky.mjs";const r={maxReadRows:1e5,maxWrittenBytes:32*1024*1024,maxWrittenRows:5e4};class w{readRows=0;writtenRows=0;writtenBytes=0;limits;constructor(t={}){this.limits={...r,...t}}recordRead(t){if(this.readRows+=t,this.readRows>this.limits.maxReadRows)throw new i("TRANSACTION_LIMIT_EXCEEDED",`this transaction read ${String(this.readRows)} documents, over the ${String(this.limits.maxReadRows)}-document limit`)}recordWrite(t){this.writtenRows+=1;const s=e(t);if(s===void 0)throw new i("BAD_REQUEST","this document is not JSON-serializable (cyclic or non-JSON value); it cannot be written");if(this.writtenBytes+=s,this.writtenRows>this.limits.maxWrittenRows)throw new i("TRANSACTION_LIMIT_EXCEEDED",`this transaction wrote ${String(this.writtenRows)} documents, over the ${String(this.limits.maxWrittenRows)}-document limit`);if(this.writtenBytes>this.limits.maxWrittenBytes)throw new i("TRANSACTION_LIMIT_EXCEEDED",`this transaction wrote ${String(this.writtenBytes)} bytes, over the ${String(this.limits.maxWrittenBytes)}-byte limit`)}headroom(){return{readRows:this.readRows,remainingReadRows:Math.max(0,this.limits.maxReadRows-this.readRows),remainingWrittenBytes:Math.max(0,this.limits.maxWrittenBytes-this.writtenBytes),remainingWrittenRows:Math.max(0,this.limits.maxWrittenRows-this.writtenRows),writtenBytes:this.writtenBytes,writtenRows:this.writtenRows}}}export{r as DEFAULT_TRANSACTION_LIMITS,w as TransactionHeadroomTracker};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
const b=["de","en","es","fr","it","nl","none","pt"],g=e=>b.includes(e),v="a an and are as at be but by for if in into is it no not of on or such that the their then there these they this to was will with",y="aber als am an auch auf aus bei bin bis bist da dass der den des dem die das denn dir du ein eine für hat ich im in ist mit nicht noch nur oder sich sie sind über und von vor war wie wir zu zum zur",w="a al como con de del el en es la las lo los mas no o para pero por que se su sus un una uno y ya",j="au aux avec ce ces dans de des du elle en et eux il je la le les leur lui ma mais me même mes moi mon ne nos notre nous on ou par pas pour qu que qui sa se ses son sur ta te tes toi ton tu un une vos votre vous y",_="a ai al alla anche che chi ci coi col come con da dal degli dei del della di do e ed gli ha hai hanno i il in la le lo ma mi ne nei nel non o per più quale quanto se si sono su sul tra un una uno vi",q="aan al als bij dan dat de der deze die dit door een en er het hij ij in is je kan me men met mij na naar niet nog nu of om ons ook op over te tot uit van voor was wat we wij zij zijn zo",z="a ao aos as até com como da das de do dos e em entre era essa esse esta este eu foi há isso já mais mas me mesmo meu na nas no nos num numa o os ou para pela pelo por qual que quem se sem seu só sua também te tem um uma você",$=/[\u0300-\u036F]/gu,p=e=>e.normalize("NFD").replaceAll($,"").normalize("NFC").toLowerCase(),a=e=>new Set(p(e).split(" ")),S={de:a(y),en:a(v),es:a(w),fr:a(j),it:a(_),nl:a(q),none:new Set,pt:a(z)},x=2,N=256,f=new Map,A=e=>{const n=e!==void 0&&g(e)?e:"none",o=f.get(n);if(o)return o;const i=S[n],m=u=>{const s=(p(u).match(/[\p{L}\p{N}]+/gu)??[]).filter(t=>t.length<=N);return i.size===0?s:s.filter(t=>!i.has(t))},c={document:m,profile:`${n}-v${String(x)}`,query:u=>{const s=m(u),t=new Set,h=[];for(let r=s.length-1;r>=0;r-=1){const l=s[r];t.has(l)||(t.add(l),h.unshift(l))}return h}};return f.set(n,c),c},F=(e,n)=>{if(!n.includes("."))return e[n];let o=e;for(const i of n.split(".")){if(o===null||typeof o!="object"||Array.isArray(o))return;o=o[i]}return o},D=(e,n)=>`${e}__fts_${n}`,J="__text__",M="__id__",k=1e3,C=(e,n)=>n.document(e),d=(e,n)=>F(e,n),L=e=>typeof e=="string"?e:e==null?"":typeof e=="number"||typeof e=="bigint"||typeof e=="boolean"?String(e):JSON.stringify(e)??"",O=(e,n,o)=>e!==void 0&&n!==void 0&&d(e,o.field)===d(n,o.field),T=(e,n)=>C(L(d(e,n.field)),A(n.language)).slice(0,k).join(" ");export{A,M as T,D as c,J as l,C as n,O as u,T as y};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
const b="0123456789bcdefghjkmnpqrstuvwxyz",L=9,p=63710088e-1,g=Math.PI/180,w=[Number.POSITIVE_INFINITY,5009400,1252300,156500,39100,4900,1200,152.9,38.2,4.77,1.19,.149,.037],q=w.map((t,n)=>n%2===0?t/2:t),v=.01,I=Math.acos(v)/g,k=2,x=t=>t/p/g,B=t=>{const n=5*t;return{latBands:2**Math.floor(n/2),lngSectors:2**Math.ceil(n/2)}},S=t=>Math.min(Math.max(Math.trunc(t),1),12),z=(t,n)=>{const a=S(n);let o=-90,e=90,s=-180,r=180,u="",i=0,h=0,M=!0;for(;u.length<a;){if(M){const c=(s+r)/2;t.lng>=c?(h=h*2+1,s=c):(h*=2,r=c)}else{const c=(o+e)/2;t.lat>=c?(h=h*2+1,o=c):(h*=2,e=c)}M=!M,i<4?i+=1:(u+=b[h]??"0",i=0,h=0)}return u},E=(t,n)=>{const a=(n.lat-t.lat)*g,o=(n.lng-t.lng)*g,e=t.lat*g,s=n.lat*g,r=Math.sin(a/2)**2+Math.cos(e)*Math.cos(s)*Math.sin(o/2)**2;return 2*p*Math.asin(Math.min(1,Math.sqrt(r)))},G=(t,n)=>{const a=Math.min(90,Math.abs(n)+x(t)),o=Math.max(Math.cos(a*g),v);for(let e=w.length-1;e>=1;e-=1){const s=w[e],r=q[e];if(s!==void 0&&r!==void 0&&s*o>=t&&r>=t)return e}return 1},C={east:["bc01fg45238967deuvhjyznpkmstqrwx","p0r21436x8zb9dcf5h7kjnmqesgutwvy"],north:["p0r21436x8zb9dcf5h7kjnmqesgutwvy","bc01fg45238967deuvhjyznpkmstqrwx"],south:["14365h7k9dcfesgujnmqp0r2twvyx8zb","238967debc01fg45kmstqrwxuvhjyznp"],west:["238967debc01fg45kmstqrwxuvhjyznp","14365h7k9dcfesgujnmqp0r2twvyx8zb"]},N={east:["bcfguvyz","prxz"],north:["prxz","bcfguvyz"],south:["028b","0145hjnp"],west:["0145hjnp","028b"]},l=(t,n)=>{const a=t.toLowerCase(),o=a.at(-1)??"";let e=a.slice(0,-1);const s=a.length%2===0?0:1;return N[n][s].includes(o)&&e!==""&&(e=l(e,n)),e+(b[C[n][s].indexOf(o)]??"")},O=(t,n,a)=>{const o=Math.min(a,k),{latBands:e,lngSectors:s}=B(o),r=180/e,u=360/s,i=x(n),h=Math.max(-90,t.lat-i),M=Math.min(90,t.lat+i),c=new Set;for(let d=0;d<e;d+=1){const m=-90+d*r;if(m+r<h||m>M)continue;const y=m+r/2;for(let f=0;f<s;f+=1){const j=-180+(f+.5)*u;c.add(z({lat:y,lng:j},o))}}return[...c]},P=(t,n)=>{const a=Math.max(n,1),o=G(a,t.lat);if(Math.min(90,Math.abs(t.lat)+x(a))>=I)return O(t,a,o);const e=z(t,o),s=l(e,"north"),r=l(e,"south"),u=[e,s,r,l(e,"east"),l(e,"west"),l(s,"east"),l(s,"west"),l(r,"east"),l(r,"west")];return[...new Set(u)]},T=(t,n)=>t.lat>=n.sw.lat&&t.lat<=n.ne.lat&&t.lng>=n.sw.lng&&t.lng<=n.ne.lng,_=t=>({lat:(t.sw.lat+t.ne.lat)/2,lng:(t.sw.lng+t.ne.lng)/2}),F=t=>{const n=_(t);return P(n,Math.max(E(n,t.ne),1))};export{L as GEO_DEFAULT_PRECISION,_ as boundingBoxCenter,F as boundingBoxGeohashes,P as coveringGeohashes,z as encodeGeohash,E as haversineMeters,T as pointInBoundingBox};
|
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
import{sql as e}from"drizzle-orm";import{runDrizzle as r}from"./runDrizzle-GKR3y97k.mjs";const s="__global_shape_snapshot",d=n=>{r(n,e`CREATE TABLE IF NOT EXISTS ${e.identifier(s)} (
|
|
2
|
-
connection_id TEXT NOT NULL,
|
|
3
|
-
sub_id TEXT NOT NULL,
|
|
4
|
-
members TEXT NOT NULL,
|
|
5
|
-
PRIMARY KEY (connection_id, sub_id)
|
|
6
|
-
)`)},T=(n,i,o)=>{const a=r(n,e`SELECT members FROM ${e.identifier(s)} WHERE connection_id = ${i} AND sub_id = ${o} LIMIT 1`).toArray()[0]?.members;if(a===void 0)return new Map;try{const t=JSON.parse(a);return t===null||typeof t!="object"?new Map:new Map(Object.entries(t))}catch{return new Map}},p=(n,i,o,a)=>{const t=JSON.stringify(Object.fromEntries(a));r(n,e`INSERT INTO ${e.identifier(s)} (connection_id, sub_id, members) VALUES (${i}, ${o}, ${t})
|
|
7
|
-
ON CONFLICT(connection_id, sub_id) DO UPDATE SET members = excluded.members`)},S=(n,i,o)=>{r(n,e`DELETE FROM ${e.identifier(s)} WHERE connection_id = ${i} AND sub_id = ${o}`)},b=(n,i)=>{r(n,e`DELETE FROM ${e.identifier(s)} WHERE connection_id = ${i}`)};export{s as GLOBAL_SHAPE_SNAPSHOT_TABLE,S as deleteGlobalShapeSnapshot,b as deleteGlobalShapeSnapshotsForConnection,d as migrateGlobalShapeSnapshot,T as readGlobalShapeSnapshot,p as writeGlobalShapeSnapshot};
|
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
import{sql as t}from"drizzle-orm";import{runDrizzle as r}from"./runDrizzle-GKR3y97k.mjs";const E="__idempotency",m=i=>{r(i,t`CREATE TABLE IF NOT EXISTS ${t.identifier(E)} (
|
|
2
|
-
identity TEXT NOT NULL,
|
|
3
|
-
mutation_id TEXT NOT NULL,
|
|
4
|
-
result_json TEXT NOT NULL,
|
|
5
|
-
ts REAL NOT NULL,
|
|
6
|
-
PRIMARY KEY (identity, mutation_id)
|
|
7
|
-
)`)},L=(i,e,o)=>{const n=r(i,t`SELECT result_json, ts FROM ${t.identifier(E)} WHERE identity = ${e} AND mutation_id = ${o} LIMIT 1`).toArray()[0];return n===void 0?void 0:{resultJson:n.result_json,ts:n.ts}},N=(i,e,o,n,s)=>{r(i,t`INSERT OR IGNORE INTO ${t.identifier(E)} (identity, mutation_id, result_json, ts) VALUES (${e}, ${o}, ${n}, ${s})`)},I=(i,e)=>{r(i,t`DELETE FROM ${t.identifier(E)} WHERE ts < ${e}`)};export{E as IDEMPOTENCY_TABLE,m as migrateIdempotency,L as readIdempotent,I as trimIdempotent,N as writeIdempotent};
|
|
@@ -1,18 +0,0 @@
|
|
|
1
|
-
const t="__lunora_mail",l=500,_=262144,i=d=>d!==void 0&&d.length>262144?`${d.slice(0,262144)}
|
|
2
|
-
… [truncated by the dev mail catcher]`:d,c=(d,e,...r)=>d.exec.call(d,e,...r),T=d=>d??null,s=d=>d===void 0?null:JSON.stringify(d),E=d=>{if(!(d==null||d===""))try{return JSON.parse(d)}catch{return}},o=d=>{c(d,`CREATE TABLE IF NOT EXISTS "${t}" (
|
|
3
|
-
id TEXT PRIMARY KEY,
|
|
4
|
-
captured_at INTEGER NOT NULL,
|
|
5
|
-
from_addr TEXT,
|
|
6
|
-
to_addrs TEXT NOT NULL,
|
|
7
|
-
cc_addrs TEXT,
|
|
8
|
-
bcc_addrs TEXT,
|
|
9
|
-
reply_to TEXT,
|
|
10
|
-
subject TEXT NOT NULL,
|
|
11
|
-
html TEXT,
|
|
12
|
-
body_text TEXT,
|
|
13
|
-
headers TEXT
|
|
14
|
-
)`)},u=(d,e,r)=>{o(d);const a=crypto.randomUUID();return c(d,`INSERT INTO "${t}" (id, captured_at, from_addr, to_addrs, cc_addrs, bcc_addrs, reply_to, subject, html, body_text, headers)
|
|
15
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,a,r,T(e.from),JSON.stringify(e.to),s(e.cc),s(e.bcc),T(e.replyTo),e.subject,T(i(e.html)),T(i(e.text)),s(e.headers)),c(d,`DELETE FROM "${t}"
|
|
16
|
-
WHERE id NOT IN (
|
|
17
|
-
SELECT id FROM "${t}" ORDER BY captured_at DESC, id DESC LIMIT ?
|
|
18
|
-
)`,500),{id:a}},p=(d,e={})=>{o(d);const r=Math.min(Math.max(e.limit??50,1),500);return{entries:c(d,`SELECT * FROM "${t}" ORDER BY captured_at DESC, id DESC LIMIT ?`,r).toArray().map(a=>({bcc:E(a.bcc_addrs),capturedAt:a.captured_at,cc:E(a.cc_addrs),from:a.from_addr??void 0,headers:E(a.headers),html:a.html??void 0,id:a.id,replyTo:a.reply_to??void 0,subject:a.subject,text:a.body_text??void 0,to:E(a.to_addrs)??a.to_addrs}))}},m=d=>(o(d),c(d,`DELETE FROM "${t}"`),{cleared:!0});export{l as MAIL_RETENTION,t as MAIL_TABLE,_ as MAX_BODY_CHARS,m as clearCapturedMail,o as ensureMailTable,p as readCapturedMail,u as recordCapturedMail};
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{LunoraError as f}from"@lunora/errors";const d=/^(?:explain\s+(?:query\s+plan\s+)?)?(?:select|with)\b/iu,g=/\b(?:alter|attach|create|delete|detach|drop|insert|pragma|reindex|replace|truncate|update|vacuum)\b/iu,h=/^\w+/u,y=/;\s*$/u,m=/\s/u,p=(s,e)=>{let t=e+2;for(;t<s.length&&s[t]!==`
|
|
2
|
-
`;)t+=1;return t},S=(s,e)=>{const t=s.indexOf("*/",e+2);return t===-1?-1:t+2},E=s=>{let e=0;for(;e<s.length;){const t=s[e];if(t!==void 0&&m.test(t))e+=1;else if(t==="-"&&s[e+1]==="-")e=p(s,e);else if(t==="/"&&s[e+1]==="*"){const r=S(s,e);if(r===-1)break;e=r}else break}return e},u=s=>{const e=E(s),t=s.slice(e).trimEnd();if(t==="")return{code:"SQL_EMPTY",message:"the query is empty"};const r=t.replace(y,""),l=r.indexOf(";");if(l!==-1)return{code:"SQL_MULTIPLE_STATEMENTS",length:1,message:"only a single statement may be run",offset:e+l};const c="the SQL editor is read-only — only SELECT / WITH / EXPLAIN queries are allowed";if(!d.test(r))return{code:"SQL_NOT_READONLY",length:h.exec(r)?.[0].length??1,message:c,offset:e};const n=g.exec(r);if(n!==null)return{code:"SQL_NOT_READONLY",length:n[0].length,message:`${c} (\`${n[0].toUpperCase()}\` is not allowed)`,offset:e+n.index}},i=1e3,L=s=>{const e=u(s);if(e!==void 0)throw new f(e.code,e.message,{status:400})},N=(s,e)=>{L(e);const t=s.exec(e).toArray(),r=t.length>i?t.slice(0,i):t;return{columns:r.length>0?Object.keys(r[0]):[],rowCount:t.length,rows:r,truncated:t.length>i}},x=/near "([^"]*)": syntax error/iu,T=/^SCAN (?:TABLE )?(?!CONSTANT\b|SUBQUERY\b)([^\s(]+)/u,A=(s,e)=>{if(e==="")return{};const t=s.indexOf(e);return t===-1?{}:{length:e.length,offset:t}},b=(s,e)=>{const t=u(e);if(t!==void 0)return{diagnostics:t.code==="SQL_EMPTY"?[]:[{length:t.length,message:t.message,offset:t.offset,severity:"error",source:"gate"}],plan:[]};let r;try{r=s.exec(`EXPLAIN QUERY PLAN ${e}`).toArray().map(n=>{const{detail:o}=n;return typeof o=="string"?o:""}).filter(n=>n!=="")}catch(n){const o=n instanceof Error?n.message:String(n),a=x.exec(o);return{diagnostics:[{...a?A(e,a[1]??""):{},message:o,severity:"error",source:"syntax"}],plan:[]}}const l=[],c=new Set;for(const n of r){const o=T.exec(n);if(o){const a=o[1]??"";c.has(a)||(c.add(a),l.push({message:`full table scan on \`${a}\` — this query reads every row`,severity:"warning",source:"plan"}))}}return{diagnostics:l,plan:r}};export{i as MAX_SQL_ROWS,L as assertReadonly,b as lintReadonlySql,N as runReadonlySql};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as b}from"@lunora/errors";import{n as St,A as Pe,T as Se,y as Tt,c as _t}from"./FTS_COUNT_COLUMN-D1gY3wwZ-CZHdaRrd.mjs";import{sql as n}from"drizzle-orm";import{aggregateSqlFunction as Te,normalizeCountArgument as Rt,throwingScheduler as At}from"./AGGREGATE_SQL_FUNCTION-QYaiuty4.mjs";import{encodeAggregateKey as Me,readAggregateValue as Ce,aggregateTableName as ke}from"./aggregateTableName-G-eXyjcz.mjs";import{mergeWhere as Q,CountRlsUnsupportedError as Le,selectIndexForGroupBy as xt,selectIndexForCount as vt,selectIndexForAggregate as It}from"./CountRlsUnsupportedError-B2WKJD9v.mjs";import{backfillSearchIndexesForTable as Mt}from"./backfillAggregateIndexes-BHiewuB-.mjs";import{backfillAggregateIndexes as mr,backfillRankIndexes as $r,backfillSearchIndexes as gr}from"./backfillAggregateIndexes-BHiewuB-.mjs";import{appendCdcChange as Ct}from"./CDC_LOG_TABLE-BnqlH2eZ.mjs";import{CDC_LOG_TABLE as yr,applyCdcChanges as Er,bumpCdcEpoch as Nr,minCdcSeq as Sr,readCdcChanges as Tr,readCdcCursor as _r,readCdcEpoch as Rr,trimCdcChanges as Ar}from"./CDC_LOG_TABLE-BnqlH2eZ.mjs";import{createCompanionSync as kt}from"./createCompanionSync-DWK0Vlg1.mjs";import{computeRankPage as Ze}from"./computeRankPage-IUSS-zIB.mjs";import{SCAN_DEP as B}from"./SCAN_DEP-D_yR9EeV.mjs";import{runDrizzle as F}from"./runDrizzle-GKR3y97k.mjs";import{DOC_COLUMN as P,quoteIdentifier as Lt,AGG_VALUE as _e,AGG_COUNT as De,AGG_KEY as Re,jsonPathSql as z,rowToDocument as de,tableColumns as pt,isFtsAvailable as Dt,tryRowToDocument as wt,geoTableName as Ot,qualifiedJsonPathSql as et}from"./AGG_COUNT-BWXe3gtQ.mjs";import{coveringGeohashes as Wt,boundingBoxGeohashes as Ft,pointInBoundingBox as qt,haversineMeters as Bt}from"./GEO_DEFAULT_PRECISION-okRCkZ6r.mjs";import{NotFoundError as Ut}from"./NotFoundError-BhF7FeFr.mjs";import{normalizeOrderKeys as Pt,buildSeekWhere as mt,decodeCursor as qe,applySelect as tt,encodeCursor as Be,softDeleteScope as le,buildSeekBeforeWhere as jt}from"./applySelect-B0CF8T7y.mjs";import{sortColumnName as nt,resolveRankPartition as Ht,encodePartitionKey as Gt,RANK_TIEBREAK as Kt,rankTableName as rt}from"./RANK_TIEBREAK-9NU5s_mi.mjs";import{indexKeysForRow as Qt,buildIndexRange as zt}from"./buildIndexRange-DFsdtPjD.mjs";import{assertFlatPredicate as Oe,resolveRelationPredicates as it}from"./DEFAULT_MAX_RELATION_KEYS-bq00btqV.mjs";import{runRowValidators as We,resolveWith as ot,applyOnDelete as Jt,fanOutScalarCounts as Yt}from"./applyOnDelete-uFRC5p1d.mjs";import{guardWriter as Vt}from"./RLS_UNWRAP_SYMBOL-CBYPlYBb.mjs";import{createSystemReader as Xt}from"./createSystemReader-DcDcrtM3.mjs";import{ConflictError as me}from"./ConflictError-C8GtJmjS.mjs";import{runTriggers as Zt}from"./hasTrigger-CbkOHExZ.mjs";import{compileWhereSql as ne}from"./compileWhereSql-BLcfs4QW.mjs";import{CLIENT_WATERMARK_TABLE as vr,advanceClientWatermark as Ir,migrateClientWatermark as Mr,readClientWatermark as Cr}from"./CLIENT_WATERMARK_TABLE-CXsSLU8D.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as Lr,deleteGlobalShapeSnapshot as Dr,deleteGlobalShapeSnapshotsForConnection as Or,migrateGlobalShapeSnapshot as Wr,readGlobalShapeSnapshot as Fr,writeGlobalShapeSnapshot as qr}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-DX-6-gBP.mjs";import{IDEMPOTENCY_TABLE as Ur,readIdempotent as Pr,trimIdempotent as jr,writeIdempotent as Hr}from"./IDEMPOTENCY_TABLE-DjkEMp6w.mjs";import{runShardMigrations as Kr}from"./runShardMigrations-CPxqCh3O.mjs";import{SEARCH_STATE_TABLE as zr}from"./SEARCH_STATE_TABLE-eLN8U5tz.mjs";import{selectShapeMemberIds as Yr,selectShapeRows as Vr}from"./selectShapeMemberIds-DvE7K6zG.mjs";import{serializeSqlValue as re}from"./serializeSqlValue-DnpyaLcw.mjs";const en=i=>{const o=new TextEncoder().encode(i);let t="";for(const l of o)t+=String.fromCodePoint(l);return btoa(t)},tn=i=>{const o=atob(i),t=Uint8Array.from(o,l=>l.codePointAt(0)??0);return new TextDecoder().decode(t)},nn=()=>new b("BAD_REQUEST","invalid cursor"),at=16,st=8,Z=1024,je=(i,o)=>o.query(i),rn=(i,o,t)=>{const l=St(i,t);if(l.length===0)return 0;let c=0;for(const[p,m]of o.entries()){const R=p===o.length-1;let S=0;for(const $ of l)(R?$.startsWith(m):$===m)&&(S+=1);if(S===0)return 0;c+=S}return c},on=(i,o)=>{if(!o)return{exact:!0,lower:i,upper:i};const t=[...i].at(-1)??"",l=(t.codePointAt(0)??0)+1;if(l>=55296&&l<=57343||l>1114111)return{exact:!0,lower:i,upper:i};const c=i.slice(0,i.length-t.length);return{exact:!1,lower:i,upper:c+String.fromCodePoint(l)}},an=(i,o,t)=>{const l={eq:(c,p)=>{if(!i.definition.filterFields?.includes(c))throw new b("INTERNAL",`field "${c}" is not a filter field of search index "${i.indexName}" on table "${o}"`);if(i.filters.length>=st)throw new b("BAD_REQUEST",`search index "${i.indexName}" on table "${o}": at most ${String(st)} .eq() filters are supported per search query`);return i.filters.push({field:c,value:p}),l},search:(c,p)=>{const m=i;if(c!==m.definition.field)throw new b("INTERNAL",`search index "${m.indexName}" on table "${o}" indexes "${m.definition.field}", not "${c}"`);const R=je(p,t).length;if(R>at)throw new b("BAD_REQUEST",`search index "${m.indexName}" on table "${o}": at most ${String(at)} search terms are supported (got ${String(R)})`);return m.field=c,m.query=p,m.hasQuery=!0,l}};return l},sn=i=>{if(i.length>Z)throw new b("BAD_REQUEST",`more than ${String(Z)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},ln=i=>Math.min(i.offset+i.numItems+1,Z),dn=i=>en(`search:${String(i)}`),cn=i=>{let o;try{o=tn(i)}catch{return}if(!o.startsWith("search:"))return;const t=Number(o.slice(7));return Number.isInteger(t)&&t>=0?t:void 0},un=i=>{if(typeof i.endCursor=="string")throw new b("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");const o=Math.max(0,Math.floor(i.numItems)),t=i.cursor?cn(i.cursor):0;if(t===void 0)throw nn();if(t+o>Z)throw new b("BAD_REQUEST",`search pagination reaches past the ${String(Z)}-document limit (offset ${String(t)} + ${String(o)} requested) — narrow the query or the filters instead`);return{numItems:o,offset:t}},fn=(i,o)=>{const t=o.offset+o.numItems,l=o.numItems>0&&i.length>t;return{continueCursor:l?dn(t):null,isDone:!l,page:i.slice(o.offset,t)}},hn=i=>{if(i===void 0)return Z+1;if(!Number.isFinite(i))return Z;const o=Math.max(0,Math.floor(i));if(o>Z)throw new b("BAD_REQUEST",`search returns at most ${String(Z)} documents (asked for ${String(o)}) — narrow the query or paginate instead`);return o},pn=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,wn=i=>{if(!pn.test(i))throw new b("INTERNAL",`invalid clientId ${JSON.stringify(i)}: a client-supplied row id must be a UUID`)},lt=50,$t=500,mn=128,se=(i,o,t)=>{const l=o??$t;if(i>l)throw new b("BATCH_LIMIT_EXCEEDED",`${t}: batch of ${String(i)} exceeds the limit of ${String(l)} (raise options.limit or chunk the call)`,{status:400})},$n=i=>{const o={eq:(t,l)=>(i.sqlConditions.push({comparator:"=",field:t,value:l}),o),gt:(t,l)=>(i.sqlConditions.push({comparator:">",field:t,value:l}),o),gte:(t,l)=>(i.sqlConditions.push({comparator:">=",field:t,value:l}),o),lt:(t,l)=>(i.sqlConditions.push({comparator:"<",field:t,value:l}),o),lte:(t,l)=>(i.sqlConditions.push({comparator:"<=",field:t,value:l}),o)};return o},gn=i=>Math.max(i,Z),bn=(i,o,t,l,c)=>{const p=je(t.query,Pe(t.definition.language));if(p.length===0)return[];const m=_t(o,t.indexName),R=`${m}__vocab`,S=p.length-1,$=p.map((C,L)=>{const j=on(C,L===S),U=j.exact?n`${n.identifier("term")} = ${j.lower}`:n`${n.identifier("term")} >= ${j.lower} AND ${n.identifier("term")} < ${j.upper}`;return n`SELECT ${n.identifier("doc")}, ${n.raw(String(L))} AS ${n.identifier("__term__")}, COUNT(*) AS ${n.identifier("__n__")} FROM ${n.identifier(R)} WHERE ${U} GROUP BY ${n.identifier("doc")}`}),y=p.map((C,L)=>n`SUM(CASE WHEN u.${n.identifier("__term__")} = ${n.raw(String(L))} THEN u.${n.identifier("__n__")} ELSE 0 END)`),E=n`SELECT f.${n.identifier(Se)} AS ${n.identifier(Se)}, ${n.join(y,n` + `)} AS ${n.identifier("__score__")} FROM (${n.join($,n` UNION ALL `)}) u JOIN ${n.identifier(m)} f ON f.rowid = u.${n.identifier("doc")} GROUP BY f.${n.identifier(Se)} HAVING ${n.join(y.map(C=>n`${C} > 0`),n` AND `)}`,_=[];for(const C of t.filters)_.push(n`${z(C.field)} = ${re(C.value)}`);c&&_.push(c);let M=n`SELECT m.id, m._creationTime, m.${n.identifier(P)}, s.${n.identifier("__score__")} AS ${n.identifier("__score__")} FROM (${E}) s JOIN ${n.identifier(o)} m ON m.id = s.${n.identifier(Se)}`;_.length>0&&(M=n`${M} WHERE ${n.join(_,n` AND `)}`),M=n`${M} ORDER BY s.${n.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${n.raw(String(l))}`;const O=[];for(const C of F(i,M)){const L=wt(C);if(L){const j=C.__score__;O.push({document:L,score:typeof j=="number"?j:Number(j??0)})}}return O},yn=(i,o,t,l,c)=>{const p=Pe(t.definition.language),m=je(t.query,p);if(m.length===0)return[];const R=[];for(const E of t.filters)R.push(n`${z(E.field)} = ${re(E.value)}`);c&&R.push(c);let S=n`SELECT id, _creationTime, ${n.identifier(P)} FROM ${n.identifier(o)}`;R.length>0&&(S=n`${S} WHERE ${n.join(R,n` AND `)}`),S=n`${S} ORDER BY _creationTime DESC, id ASC LIMIT ${n.raw(String(gn(l)))}`;const $=F(i,S).toArray(),y=[];for(const E of $){const _=wt(E);if(!_)continue;const M=rn(Tt(_,t.definition),m,p);M>0&&y.push({creationTime:typeof _._creationTime=="number"?_._creationTime:0,doc:_,id:typeof _._id=="string"?_._id:"",score:M})}return y.sort((E,_)=>_.score-E.score||_.creationTime-E.creationTime||E.id.localeCompare(_.id)),y.slice(0,l).map(E=>({document:E.doc,score:E.score}))},Fe=(i,o,t,l)=>{if(!Number.isFinite(i.lat)||i.lat<-90||i.lat>90||!Number.isFinite(i.lng)||i.lng<-180||i.lng>180)throw new b("BAD_REQUEST",`geo index "${l}" on table "${t}": ${o} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},En=(i,o)=>{const t=i,l={near:(c,p)=>{if(t.within)throw new b("INTERNAL",`geo index "${t.indexName}" on table "${o}": call .near() or .within(), not both`);if(Fe(c,".near() point",o,t.indexName),!Number.isFinite(p)||p<=0)throw new b("BAD_REQUEST",`geo index "${t.indexName}" on table "${o}": .near() radiusMeters must be a finite number > 0, got ${String(p)}`);return t.near={point:{lat:c.lat,lng:c.lng},radiusMeters:p},l},within:c=>{if(t.near)throw new b("INTERNAL",`geo index "${t.indexName}" on table "${o}": call .near() or .within(), not both`);if(Fe(c.sw,".within() sw corner",o,t.indexName),Fe(c.ne,".within() ne corner",o,t.indexName),c.sw.lat>c.ne.lat)throw new b("BAD_REQUEST",`geo index "${t.indexName}" on table "${o}": .within() corners are transposed (sw.lat > ne.lat)`);if(c.sw.lng>c.ne.lng)throw new b("BAD_REQUEST",`geo index "${t.indexName}" on table "${o}": .within() box crosses the antimeridian (sw.lng > ne.lng), which is not supported — split it into two boxes at ±180 and union the results`);return t.within={ne:{lat:c.ne.lat,lng:c.ne.lng},sw:{lat:c.sw.lat,lng:c.sw.lng}},l}};return l},Nn=(i,o)=>{const t=i[o];if(t===null||typeof t!="object")return;const{lat:l,lng:c}=t;return typeof l=="number"&&typeof c=="number"?{lat:l,lng:c}:void 0},Sn=(i,o)=>{const t=Nn(i,o.definition.field);if(!t)return;const l=typeof i._creationTime=="number"?i._creationTime:0;if(o.near){const c=Bt(o.near.point,t);return c<=o.near.radiusMeters?{creationTime:l,distance:c}:void 0}return qt(t,o.within)?{creationTime:l,distance:0}:void 0},gt=(i,o,t,l)=>{if(!t.near&&!t.within)throw new b("INTERNAL",`geo index "${t.indexName}" on table "${o}": call .near(point, radius) or .within(box)`);const c=t.near?Wt(t.near.point,t.near.radiusMeters):Ft(t.within),p=Ot(o,t.indexName),m=c.map(E=>n`(g.${n.identifier("__geohash__")} >= ${E} AND g.${n.identifier("__geohash__")} < ${`${E}{`})`),R=[n`(${n.join(m,n` OR `)})`];l&&R.push(l);const S=n`SELECT m.id, m._creationTime, m.${n.identifier(P)} FROM ${n.identifier(p)} g JOIN ${n.identifier(o)} m ON m.id = g.${n.identifier("__id__")} WHERE ${n.join(R,n` AND `)}`,$=F(i,S).toArray(),y=[];for(const E of $){const _=de(E),M=_?Sn(_,t):void 0;_&&M&&y.push({creationTime:M.creationTime,distance:M.distance,doc:_})}return y.sort((E,_)=>E.distance-_.distance||_.creationTime-E.creationTime),y},Tn=(i,o,t,l,c,p=()=>{})=>{const m=gt(i,o,t,c).map(R=>R.doc);return p(m.length),typeof l=="number"?m.slice(0,Math.max(0,Math.floor(l))):m},_n=(i,o,t,l,c,p=()=>{})=>{const m=t.within!==void 0,R=gt(i,o,t,c).map(S=>({distanceMeters:m?null:S.distance,document:S.doc}));return p(R.length),R},Rn=(i,o,t,l,c,p=()=>{})=>{const{geo:m}=t;if(!m)throw new b("INTERNAL","runGeoTerminal called without a staged geo query");const R=t.inMemoryFilters.length>0,S=Tn(i,o,m,R?void 0:c,l,p);if(!R)return S;const $=[];for(const y of S)if(t.inMemoryFilters.every(E=>E(y))&&($.push(y),typeof c=="number"&&$.length>=c))break;return $},An=(i,o,t,l,c,p=()=>{})=>{const{geo:m}=t;if(!m)throw new b("INTERNAL","runGeoTerminalScored called without a staged geo query");const R=t.inMemoryFilters.length>0,S=_n(i,o,m,R?void 0:c,l,p);if(!R)return S;const $=[];for(const y of S)t.inMemoryFilters.every(E=>E(y.document))&&$.push(y);return $},xn=(i,o,t,l,c,p,m=()=>{})=>{const R=[];for(const E of t.sqlConditions)R.push(n`${z(E.field)} ${n.raw(E.comparator)} ${re(E.value)}`);l&&R.push(l);let S=n`SELECT id, _creationTime, ${n.identifier(P)} FROM ${n.identifier(o)}`;R.length>0&&(S=n`${S} WHERE ${n.join(R,n` AND `)}`),S=n`${S} ORDER BY ${c}`,typeof p=="number"&&t.inMemoryFilters.length===0&&(S=n`${S} LIMIT ${n.raw(String(Math.max(0,Math.floor(p))))}`);const $=F(i,S).toArray();m($.length);const y=[];for(const E of $){const _=de(E);if(_&&t.inMemoryFilters.every(M=>M(_))&&(y.push(_),typeof p=="number"&&y.length>=p))break}return y},oe={fieldRef:z,serialize:re},vn=i=>{let o=0;const t=[],l={fieldRef:z,relationExists:c=>{const{childWhere:p,negated:m,parentTable:R,relation:S}=c,$=`__rel_${String(o)}`,y=t.at(-1)??R;o+=1,i(S.table,B);const E=S.kind==="one"?S.field:S.references,_=S.kind==="one"?S.references:S.field,M=n`${et($,_)} = ${et(y,E)}`;t.push($);const O=ne(p,l);t.pop();const C=O?n`${M} AND ${O}`:M,L=n`EXISTS (SELECT 1 FROM ${n.identifier(S.table)} AS ${n.identifier($)} WHERE ${C})`;return m?n`NOT ${L}`:L},serialize:re};return l},bt=i=>{const o=i.map(t=>n`${z(t.field)} ${n.raw(t.direction==="desc"?"DESC":"ASC")}`);return i.some(t=>t.field==="_id"||t.field==="id")||o.push(n`${z("id")} ASC`),n.join(o,n`, `)},In={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},Mn=i=>{const o=i.order;return i.indexFields.length>0?i.indexFields.map(t=>({direction:o,field:t})):[{direction:o,field:"_creationTime"}]},Cn=(i,o,t,l)=>{const c=i.sqlConditions.map(p=>({[p.field]:{[In[p.comparator]??"eq"]:p.value}}));if(t&&c.push(mt(o,qe(t))),l&&c.push(jt(o,qe(l))),c.length!==0)return c.length===1?c[0]:{AND:c}},kn=(i,o,t)=>{const l=[];for(const c of i){const p=de(c);if(p&&o.every(m=>m(p))&&(l.push(p),t!==void 0&&l.length>t))break}return l},Ln=(i,o,t,l,c,p=()=>{})=>{const m=Math.max(0,Math.floor(l.numItems)),R=Mn(t),S=typeof l.endCursor=="string",$=ne(Cn(t,R,l.cursor,l.endCursor),oe),y=c&&$?n`${$} AND ${c}`:c??$;let E=n`SELECT id, _creationTime, ${n.identifier(P)} FROM ${n.identifier(o)}`;y&&(E=n`${E} WHERE ${y}`),E=n`${E} ORDER BY ${bt(R)}`;const _=t.inMemoryFilters.length>0;!_&&!S&&(E=n`${E} LIMIT ${n.raw(String(m+1))}`);const M=F(i,E).toArray();p(M.length);const O=kn(M,t.inMemoryFilters,_||S?void 0:m);if(S){const U=O.length>=2?O[Math.floor(O.length/2)-1]:void 0;return{continueCursor:l.endCursor??null,isDone:!0,page:O,splitCursor:U?Be(U,R):null}}const C=O.length>m,L=C?O.slice(0,m):O,j=L.at(-1);return{continueCursor:C&&j?Be(j,R):null,isDone:!C,page:L}};class Dn extends b{constructor(o="unique() found more than one matching document"){super("NOT_UNIQUE",o,{name:"NotUniqueError"})}}const On=/\s/u,Wn=String.fromCodePoint(0),dt=(i,o,t)=>{if(!i.tables[o])throw new b("INTERNAL",`unknown table: ${o}`);return typeof t!="string"||t.length===0||On.test(t)||t.includes(Wn)?null:t},Fn=(i,o,t,l=()=>{},c=()=>{},p=()=>{})=>{const m=o.tables[t];if(!m)throw new b("INTERNAL",`unknown table: ${t}`);const R=le(m.softDeleteMode,void 0),S=R?ne(R,oe):void 0,$={indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[]};let y=0;const E=N=>{const{search:I}=$;if(!I)throw new b("INTERNAL","runSearchFetch called without a staged search");Mt(i,t,m);const v=$.inMemoryFilters.length>0,k=hn(v?void 0:N),H=Dt(i)?bn(i,t,I,k,S):yn(i,t,I,k,S);if(!v)return N===void 0&&sn(H),H;const X=[];y=H.length;for(const ce of H)if($.inMemoryFilters.every(ue=>ue(ce.document))&&(X.push(ce),typeof N=="number"&&X.length>=N))break;return X},_=N=>E(N).map(I=>I.document),M=N=>{const I=un(N);return fn(_(ln(I)),I)},O=()=>{const N=$.indexFields.length>0?$.indexFields:["_creationTime"],I=$.order==="desc"?"DESC":"ASC";return n.join(N.map(v=>n`${z(v)} ${n.raw(I)}`),n`, `)},C=()=>{if($.search||$.geo||$.indexName===void 0){c(void 0);return}c(zt(t,$.indexName,$.indexFields,$.sqlConditions,re))},L=N=>{C();let I=0;const v=(()=>{if($.search){const k=_(N);return I=y,k}return $.geo?Rn(i,t,$,S,N,k=>{I=k}):xn(i,t,$,S,O(),N,k=>{I=k})})();return p(Math.max(I,v.length)),v},j=()=>{if(!$.search&&!$.geo)throw new b("INTERNAL",`ctx.db.query("${t}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);C();let N=0;const I=(()=>{if($.search){const v=E(void 0);return N=y,v}return An(i,t,$,S,void 0,v=>{N=v})})();return p(Math.max(N,I.length)),I},U={async*[Symbol.asyncIterator](){const N=[...$.inMemoryFilters];let I;$.inMemoryFilters=[];try{for(;;){const v=await U.paginate({cursor:I??null,numItems:mn});for(const k of v.page)N.every(H=>H(k))&&(yield k);if(v.isDone||v.continueCursor===null)return;I=v.continueCursor}}finally{$.inMemoryFilters=N}},async collect(){return L(void 0)},async collectWithScores(){return j()},filter(N){return $.inMemoryFilters.push(N),U},async first(){return L($.inMemoryFilters.length>0?void 0:1)[0]??null},order(N){return $.order=N==="desc"?"desc":"asc",U},async paginate(N){let I=0;if(C(),$.search){const k=M(N);return p(k.page.length),k}if($.geo)throw new b("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const v=Ln(i,t,$,N,S,k=>{I=k});return p(Math.max(I,v.page.length)),v},async take(N){return L(N)},async unique(){const N=L($.inMemoryFilters.length>0?void 0:2);if(N.length>1)throw new Dn(`unique() on table "${t}" matched ${String(N.length)} documents; expected at most one`);return N[0]??null},withGeoIndex(N,I){const v=(m.geoIndexes??[]).find(H=>H.name===N);if(!v)throw new b("INTERNAL",`unknown geo index "${N}" on table "${t}"`);l(t,N,"geo");const k={definition:v,indexName:N};if($.geo=k,I(En(k,t)),!k.near&&!k.within)throw new b("INTERNAL",`geo index "${N}" on table "${t}" requires a .near(point, radius) or .within(box) call`);return U},withIndex(N,I){const v=m.indexes.find(k=>k.name===N);if(!v)throw new b("INTERNAL",`unknown index "${N}" on table "${t}"`);return l(t,N,"index"),$.indexName=N,$.indexFields=v.fields,I&&I($n($)),U},withSearchIndex(N,I){const v=(m.searchIndexes??[]).find(H=>H.name===N);if(!v)throw new b("INTERNAL",`unknown search index "${N}" on table "${t}"`);l(t,N,"search");const k={definition:v,field:v.field,filters:[],hasQuery:!1,indexName:N,query:""};if($.search=k,I(an(k,t,Pe(v.language))),!k.hasQuery)throw new b("INTERNAL",`search index "${N}" on table "${t}" requires a .search(field, query) call`);return U}};return U},ct=(i,o,t)=>{const l={...o};for(const[c,p]of pt(i)){if(p.serverDefault){l[c]=p.serverDefault({auth:t});continue}l[c]===void 0&&(p.defaultFn?l[c]=p.defaultFn():"defaultValue"in p&&(l[c]=p.defaultValue))}return l},ut=(i,o,t,l)=>{const c=t;for(const[p,m]of pt(i)){if(m.serverDefault){p in o&&(c[p]=m.serverDefault({auth:l}));continue}m.onUpdateFn&&!(p in o)&&(c[p]=m.onUpdateFn())}},ft=(i,o)=>{for(const t of Object.keys(o))if(o[t]===void 0)throw new b("INTERNAL",`Cannot ${i} field '${t}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},qn=/unique constraint failed/i,Bn=i=>i instanceof Error&&qn.test(i.message),Ue=(i,o,t)=>{try{F(i,t)}catch(l){throw Bn(l)?new me(`unique constraint violation on "${o}"`,"unique"):l}},Ae=(i,o,t)=>{if(Ue(i,o,t),F(i,n`SELECT changes() AS changed`).one().changed===0)throw new me(`optimistic concurrency conflict on "${o}" — the row changed during this mutation; refetch and retry`,"occ")},ht=(i,o,t,l,c,p,m)=>{const R=[];for(let E=0;E<t.length+1;E+=1){const _=[];for(let L=0;L<E;L+=1)_.push(n`${n.identifier(t[L])} IS ${p[L]}`);const M=t[E],O=l[E];if(M!==void 0&&O!==void 0){const L=O.direction==="desc"?">":"<";_.push(n`${n.identifier(M)} ${n.raw(L)} ${p[E]}`)}else _.push(n`${n.identifier(Kt)} < ${m}`);const[C]=_;R.push(_.length===1&&C!==void 0?C:n`(${n.join(_,n` AND `)})`)}const S=n.join(R,n` OR `),$=F(i,n`SELECT COUNT(*) AS c FROM ${n.identifier(o)} WHERE ${n.identifier("__partition__")} = ${c} AND (${S})`).one(),y=F(i,n`SELECT COUNT(*) AS c FROM ${n.identifier(o)} WHERE ${n.identifier("__partition__")} = ${c}`).one();return{before:$.c,total:y.c}},hr=i=>{const{sql:o}=i,{schema:t}=i,l=i.broadcast??(()=>{}),c=(e,...r)=>{const a=t.tables[e]?.indexes;if(!a||a.length===0)return;const h=[];for(const f of r)f&&h.push(...Qt(a,f,re));return h.length>0?h:void 0},{headroom:p}=i;let m=!1;const R=async e=>{const r=m;m=!0;try{return await e()}finally{m=r}},S=i.onRead??(()=>{}),$=i.onReadRange??(e=>{S(e.table,B)}),y=(e,r)=>{r!==void 0&&r!==B&&!m&&p?.recordRead(1),S(e,r)},E=i.onIndexUse??(()=>{}),_=i.onWrite??(()=>{}),M=async e=>{m||p?.recordWrite(e.doc),await _(e)},{cache:O}=i,C=i.clock??(()=>Date.now()),L=i.idGenerator??(()=>crypto.randomUUID()),j=i.scheduler??At,{globalDb:U}=i,N=i.auth??{identity:null,userId:null},I=i.cdc??!1,v=j,k=Xt({scheduler:typeof v.list=="function"&&typeof v.get=="function"?v:void 0,storage:i.storage}),H=(e,r,a,h)=>{I&&Ct(o,C(),e,r,a,h)},X=e=>t.tables[e]?.shardMode?.kind==="global",ce=(e,r)=>{if(X(e)){if(!U)throw new b("INTERNAL",`cross-backend ${r} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return U}return q},ue=e=>ce(e,"cascade"),J=(e,r)=>{if(X(e)){if(!U)throw new b("INTERNAL",`${r} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return U}},fe=()=>U,xe=(e,r)=>ce(e,"relation load").findMany(e,r),He=(e,r)=>(X(e)&&y(e,B),xe(e,r)),yt=e=>!X(e.table),Ge=i.relationExistsPushDown??"auto",Ke=Ge!=="never",{maxRelationKeys:Qe}=i,$e=(e,r,a)=>it(e,{fetcher:He,maxRelationKeys:Qe,relationBaseWhere:a,schema:t,tableName:r}),ze=async(e,r,a,h)=>{const f=J(e,"relation grouped count");if(f)return y(e,B),Yt((x,K)=>f.count(x,K),e,r,a,h);const d=t.tables[e];if(!d)throw new b("INTERNAL",`unknown table: ${e}`);y(e,B);const s=le(d.softDeleteMode,void 0),u={[r]:{in:a}},w=Q(Q(u,h),s),T=await $e(w,e,void 0),g=ne(T,oe),A=z(r);let W=n`SELECT ${A} AS __fk__, COUNT(*) AS count FROM ${n.identifier(e)}`;g&&(W=n`${W} WHERE ${g}`),W=n`${W} GROUP BY ${A}`;const D=F(o,W).toArray();return new Map(D.map(x=>[x.__fk__,x.count]))};let ge=0;const Je=new Set;for(const[e,r]of Object.entries(t.tables))for(const a of Object.values(r.triggerMap??{}))Je.add(`${e} ${a.timing} ${a.op}`);const ee=(e,r,a)=>Je.has(`${e} ${r} ${a}`),te=async(e,r,a)=>{if(ge+=1,ge>lt)throw ge-=1,new me(`trigger recursion exceeded ${String(lt)} levels on "${a.table}" — check for a self-triggering write`,"trigger");try{await Zt({ctx:Nt,event:a,op:r,schema:t,tableName:a.table,timing:e})}finally{ge-=1}},{ensureBackfilledForTable:he,ensureBackfilledIndex:ve,ensureRankBackfilled:Ie,ensureRankBackfilledForTable:pe,syncAggregates:be,syncCompanionsForInsert:Ye,syncGeo:ye,syncRanks:we,syncSearch:Ee}=kt({broadcast:l,indexKeysFor:(e,r)=>c(e,r),invalidateCache:(e,r,a)=>O?.invalidate(e,r,c(e,a)),recordCdc:H,schema:t,sql:o}),Ve=(e,r,a)=>{const{shardMode:h}=r;if(h?.kind==="shardBy"&&!(h.field!==void 0&&(a.partitionBy??[]).includes(h.field)))throw Object.assign(new Error(`rank index "${a.name}" on "${e}" partitions across shards (shard key "${h.field??"?"}" is not in partitionBy) — a shard-local rank()/rankPage() would be wrong; roll it up through the Query Coordinator instead`),{code:"CROSS_SHARD_RANK_UNSUPPORTED",name:"LunoraError",status:400})},ie=(e,r)=>{const a=Object.entries(t.tables).filter(([,T])=>T.shardMode?.kind!=="global").map(([T])=>T).filter(T=>r===void 0||T===r);if(a.length===0)return;const h=a.map(T=>n`SELECT ${n.raw(`'${T.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${n.identifier(P)} FROM ${n.identifier(T)} WHERE id = ${e}`),f=n`${n.join(h,n` UNION ALL `)} LIMIT 1`,[d]=F(o,f).toArray();if(!d)return;const s=d.__t__,u=de(d);if(typeof s!="string"||!u)return;const w=d[P];return{docJson:typeof w=="string"?w:JSON.stringify(w??{}),row:u,tableName:s}},Et=(e,r)=>{const a=[...new Set(e)],h=new Map;if(a.length===0)return h;const f=Object.entries(t.tables).filter(([,s])=>s.shardMode?.kind!=="global").map(([s])=>s).filter(s=>r===void 0||s===r);if(f.length===0)return h;const d=Math.max(1,Math.floor(900/f.length));for(let s=0;s<a.length;s+=d){const u=a.slice(s,s+d),w=n.join(u.map(A=>n`${A}`),n`, `),T=f.map(A=>n`SELECT ${n.raw(`'${A.replaceAll("'","''")}'`)} AS __t__, id FROM ${n.identifier(A)} WHERE id IN (${w})`),g=n.join(T,n` UNION ALL `);for(const A of F(o,g)){const{id:W,__t__:D}=A;typeof D=="string"&&typeof W=="string"&&h.set(W,D)}}return h},Xe={assertRankPartitionLocal:Ve,ensureRankBackfilled:Ie,onRead:y,rowToDocument:de,schema:t,sql:o},q={system:k,async aggregate(e,r){const a=J(e,"aggregate");if(a)return y(e,B),a.aggregate(e,r);const h=t.tables[e];if(!h)throw new b("INTERNAL",`unknown table: ${e}`);if(Te(r.op),r.op==="count")return q.count(e,{baseWhere:r.baseWhere,relationBaseWhere:r.relationBaseWhere,restrictsCounts:r.restrictsCounts,where:r.where});if(!r.field)throw new b("INTERNAL",`aggregate(${e}, { op: "${r.op}" }): "field" is required for non-count reducers`);y(e,B);const f=le(h.softDeleteMode,void 0),d=Q(Q(r.baseWhere,r.where),f),s=await $e(d,e,r.relationBaseWhere),u=s!==d;if(h.aggregateIndexes&&!r.baseWhere&&!u&&!f){const D=It(h.aggregateIndexes,r.op,r.field,r.where);if(D){ve(e,D.index);const x=Me(D.index.by??[],D.key),K=ke(e,D.index.name),Y=F(o,n`SELECT ${_e} AS value, ${De} AS count FROM ${n.identifier(K)} WHERE ${Re} = ${x}`).toArray()[0];return Ce(r.op,Y)}}const w=ne(s,oe),T=Te(r.op),g=z(r.field);let A=n`SELECT ${n.raw(T)}(${g}) AS value FROM ${n.identifier(e)}`;return w&&(A=n`${A} WHERE ${w}`),F(o,A).toArray()[0]?.value??null},asId(e,r){const a=dt(t,e,r);if(a===null)throw new b("BAD_REQUEST",`asId("${e}", …): "${r}" is not a valid id for table "${e}"`,{status:400});return a},async count(e,r){const a=J(e,"count");if(a)return y(e,B),a.count(e,r);const h=t.tables[e];if(!h)throw new b("INTERNAL",`unknown table: ${e}`);const f=Rt(r);if(f.restrictsCounts)throw new Le(e);y(e,B);const d=le(h.softDeleteMode,void 0),s=Q(Q(f.baseWhere,f.where),d),u=await $e(s,e,f.relationBaseWhere),w=u!==s;if(h.aggregateIndexes&&!f.baseWhere&&!w&&!d){const A=vt(h.aggregateIndexes,f.where);if(A){ve(e,A.index);const W=Me(A.index.by??[],A.key),D=ke(e,A.index.name),x=F(o,n`SELECT ${_e} AS value FROM ${n.identifier(D)} WHERE ${Re} = ${W}`).toArray();return x[0]===void 0?0:x[0].value??0}}const T=ne(u,oe);let g=n`SELECT COUNT(*) AS count FROM ${n.identifier(e)}`;return T&&(g=n`${g} WHERE ${T}`),F(o,g).one().count},async delete(e,r,a){const h=ie(e,r);if(!h){const g=r===void 0?fe():void 0;g&&await g.delete(e,void 0,a);return}const{docJson:f,row:d,tableName:s}=h,u=t.tables[s],w=a?.hard===!0,T=!w&&u?.softDeleteMode?u.softDeleteMode.field:void 0;if(!(T&&d[T]!==null&&d[T]!==void 0)){if(ee(s,"before","delete")&&await te("before","delete",{id:e,op:"delete",previous:d,table:s}),await Jt({deletedId:e,deletedReference:g=>d[g],findHolders:async(g,A,W)=>(await ue(g).findMany(g,{includeDeleted:w,where:{[A]:W}})).page,onCascade:(g,A)=>ue(g).delete(A,void 0,a),onRestrict:g=>{throw new me(g,"restrict")},onSetNull:(g,A,W)=>ue(g).patch(A,{[W]:null}),schema:t,tableName:s}),he(s),pe(s),T){const g={...d,[T]:C(),_id:e};Ae(o,s,n`UPDATE ${n.identifier(s)} SET ${n.identifier(P)} = ${JSON.stringify(g)} WHERE id = ${e} AND ${n.identifier(P)} = ${f}`),Ee(s,e,g,d),ye(s,e,void 0),be(s,d,g),we(s,e,d,void 0),O?.invalidate(s,e,c(s,d,g)),H(s,e,"update",g),l({indexKeys:c(s,d,g),key:e,op:"update",row:g,table:s}),ee(s,"after","delete")&&await te("after","delete",{id:e,op:"delete",previous:d,table:s}),await M({id:e,op:"delete",table:s});return}Ae(o,s,n`DELETE FROM ${n.identifier(s)} WHERE id = ${e} AND ${n.identifier(P)} = ${f}`),Ee(s,e,void 0),ye(s,e,void 0),be(s,d,void 0),we(s,e,d,void 0),O?.invalidate(s,e,c(s,d)),H(s,e,"delete"),l({indexKeys:c(s,d),key:e,op:"delete",table:s}),ee(s,"after","delete")&&await te("after","delete",{id:e,op:"delete",previous:d,table:s}),await M({id:e,op:"delete",table:s})}},async deleteAll(e,r){if(!t.tables[e])throw new b("INTERNAL",`unknown table: ${e}`);const a=Math.max(1,r?.chunkSize??$t),h=r?.hard===void 0?void 0:{hard:r.hard},f=X(e)?void 0:e;let d=0;return await R(async()=>{for(;;){const s=(await q.findMany(e,{limit:a})).page.map(u=>String(u._id));if(s.length===0)break;for(const u of s)await q.delete(u,f,h),d+=1;if(s.length<a)break}}),{deleted:d}},async deleteMany(e,r,a){se(e.length,r?.limit,"deleteMany");for(const h of e)await q.delete(h,a);return{deleted:e.length}},async deleteWhere(e,r,a){const h=J(e,"deleteWhere");let f;if(h)f=(await h.findMany(e,{where:r})).page.map(d=>String(d._id));else{if(!t.tables[e])throw new b("INTERNAL",`unknown table: ${e}`);f=(await q.findMany(e,{where:r})).page.map(d=>String(d._id))}if(se(f.length,a?.limit,"deleteWhere"),q.deleteMany===void 0)throw new b("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return q.deleteMany(f,a)},async findFirst(e,r={}){return(await q.findMany(e,{...r,limit:1})).page[0]??null},async findFirstOrThrow(e,r={}){const a=await q.findFirst(e,r);if(a===null)throw new Ut(`findFirstOrThrow: no "${e}" document matched`);return a},async findMany(e,r={}){const a=J(e,"findMany");if(a)return y(e,B),a.findMany(e,r);const h=t.tables[e];if(!h)throw new b("INTERNAL",`unknown table: ${e}`);const f=!r.where&&!r.baseWhere;f?y(e,B):y(e);const d=Pt(r.orderBy),s=r.cursor?mt(d,qe(r.cursor)):void 0;let u=Q(r.baseWhere,r.where);u=Q(u,le(h.softDeleteMode,r.includeDeleted)),u=await it(u,{canPushExists:Ke?yt:void 0,existsPushMode:Ge==="always"?"always":"auto",fetcher:He,maxRelationKeys:Qe,relationBaseWhere:r.relationBaseWhere,schema:t,tableName:e}),s&&(u=u?{AND:[u,s]}:s);const w=Ke?vn(y):oe,T=ne(u,w);let g=n`SELECT id, _creationTime, ${n.identifier(P)} FROM ${n.identifier(e)}`;T&&(g=n`${g} WHERE ${T}`),g=n`${g} ORDER BY ${bt(d)}`;const A=typeof r.limit=="number"?Math.max(0,Math.floor(r.limit)):void 0;A!==void 0&&(g=n`${g} LIMIT ${n.raw(String(A+1))}`);const W=F(o,g).toArray();f&&!m&&p?.recordRead(W.length);const D=[];for(const V of W){const G=de(V);G&&(D.push(G),!f&&typeof G._id=="string"&&y(e,G._id))}if(A===void 0)return r.with&&await ot({groupedCounter:ze,fetcher:xe,parents:D,relationBaseWhere:r.relationBaseWhere,schema:t,tableName:e,with:r.with}),{continueCursor:null,isDone:!0,page:tt(D,r.select,r.with)};const x=D.length>A,K=x?D.slice(0,A):D,Y=K.at(-1);return r.with&&await ot({fetcher:xe,groupedCounter:ze,parents:K,relationBaseWhere:r.relationBaseWhere,schema:t,tableName:e,with:r.with}),{continueCursor:x&&Y?Be(Y,d):null,isDone:!x,page:tt(K,r.select,r.with)}},async get(e,r){const a=ie(e,r);if(!a){const h=r===void 0?fe():void 0;return h?h.get(e):null}return y(a.tableName,e),a.row},async lookupById(e,r){const a=ie(e,r);return a?(y(a.tableName,e),{row:a.row,tableName:a.tableName}):null},async groupBy(e,r){const a=J(e,"groupBy");if(a)return y(e,B),a.groupBy(e,r);const h=t.tables[e];if(!h)throw new b("INTERNAL",`unknown table: ${e}`);y(e,B);const f=r.agg??{op:"count"};if(Te(f.op),f.op!=="count"&&!f.field)throw new b("INTERNAL",`groupBy(${e}, { agg: { op: "${f.op}" } }): "field" is required for non-count reducers`);const d=le(h.softDeleteMode,void 0),s=Q(Q(r.baseWhere,r.where),d),u=await $e(s,e,r.relationBaseWhere),w=u!==s;if(h.aggregateIndexes&&!r.baseWhere&&!w&&!d){const x=xt(h.aggregateIndexes,f.op,f.field,r.by,r.where);if(x){ve(e,x.index);const K=ke(e,x.index.name),Y=Object.keys(x.partial),V=[];if(Y.length===(x.index.by??[]).length&&Y.length>0){const ae=Me(x.index.by??[],x.partial),Ne=F(o,n`SELECT ${_e} AS value, ${De} AS count FROM ${n.identifier(K)} WHERE ${Re} = ${ae}`).toArray();return Ne.length>0&&V.push({key:{...x.partial},value:Ce(f.op,Ne[0])}),V}const G=F(o,n`SELECT ${Re} AS key, ${_e} AS value, ${De} AS count FROM ${n.identifier(K)}`).toArray();for(const ae of G){const Ne=JSON.parse(ae.key);V.push({key:Ne,value:Ce(f.op,ae)})}return V}}const T=ne(u,oe),g=r.by.map(x=>n`${z(x)} AS ${n.identifier(x)}`);if(f.op==="count")g.push(n`COUNT(*) AS value`);else{const{field:x}=f;if(x===void 0)throw new b("INTERNAL",`groupBy(${e}, { agg: { op: "${f.op}" } }): "field" is required for non-count reducers`);g.push(n`${n.raw(Te(f.op))}(${z(x)}) AS value`)}let A=n`SELECT ${n.join(g,n`, `)} FROM ${n.identifier(e)}`;T&&(A=n`${A} WHERE ${T}`),A=n`${A} GROUP BY ${n.join(r.by.map(x=>z(x)),n`, `)}`;const W=F(o,A).toArray(),D=[];for(const x of W){const K={};for(const V of r.by)K[V]=x[V]??null;const{value:Y}=x;D.push({key:K,value:Y==null?null:Number(Y)})}return D},async insert(e,r,a){const h=J(e,"insert");if(h){const T=await h.insert(e,r,a);return m||p?.recordWrite(r),l({key:T,op:"insert",row:{...r,_id:T},table:e}),T}const f=t.tables[e];if(!f)throw new b("INTERNAL",`unknown table: ${e}`);const d=ct(f,r,N);We(f,d);let s;a?.clientId!==void 0?(wn(a.clientId),s=a.clientId):a?.allowExplicitId&&typeof d._id=="string"?s=d._id:s=L();const u=a?.allowExplicitId&&typeof d._creationTime=="number"?d._creationTime:C(),w={...d,_creationTime:u,_id:s};return ee(e,"before","insert")&&await te("before","insert",{doc:{...w},id:s,op:"insert",table:e}),he(e),pe(e),Ue(o,e,n`INSERT INTO ${n.identifier(e)} (id, _creationTime, ${n.identifier(P)}) VALUES (${s}, ${u}, ${JSON.stringify(w)})`),Ye(e,s,w),ee(e,"after","insert")&&await te("after","insert",{doc:w,id:s,op:"insert",table:e}),await M({doc:w,id:s,op:"insert",table:e}),s},async insertManyUnsafe(e,r,a){if(se(r.length,a?.limit,"insertManyUnsafe"),r.length===0)return[];const h=J(e,"insert");if(h){const u=[];for(const w of r){const T=await h.insert(e,w,{allowExplicitId:a?.allowExplicitId});m||p?.recordWrite(w),l({key:T,op:"insert",row:{...w,_id:T},table:e}),u.push(T)}return u}const f=t.tables[e];if(!f)throw new b("INTERNAL",`unknown table: ${e}`);he(e),pe(e);const d=r.map(u=>{const w=ct(f,u,N),T=a?.allowExplicitId===!0&&typeof w._id=="string"?w._id:L(),g=a?.allowExplicitId===!0&&typeof w._creationTime=="number"?w._creationTime:C();return{creationTime:g,document:{...w,_creationTime:g,_id:T},id:T}});if(!m)for(const u of d)p?.recordWrite(u.document);const s=n.join(d.map(u=>n`(${u.id}, ${u.creationTime}, ${JSON.stringify(u.document)})`),n`, `);Ue(o,e,n`INSERT INTO ${n.identifier(e)} (id, _creationTime, ${n.identifier(P)}) VALUES ${s}`);for(const{document:u,id:w}of d)Ye(e,w,u),await _({doc:u,id:w,op:"insert",table:e});return d.map(u=>u.id)},async insertMany(e,r,a){se(r.length,a?.limit,"insertMany");const h=a?.skipDuplicates===!0,f=[];for(const d of r)try{f.push(await q.insert(e,d))}catch(s){if(h&&s instanceof me&&s.kind==="unique")f.push(null);else throw s}return f},normalizeId(e,r){return dt(t,e,r)},async patch(e,r,a){const h=ie(e,a);if(!h){const T=a===void 0?fe():void 0;if(T){await T.patch(e,r);return}throw new b("INTERNAL",`document not found: ${e}`)}const{docJson:f,row:d,tableName:s}=h,u=t.tables[s];if(!u)throw new b("INTERNAL",`unknown table: ${s}`);y(s,e),ft("patch",r);const w={...d,...r,_id:e};ut(u,r,w,N),We(u,w,!0),ee(s,"before","update")&&await te("before","update",{doc:{...w},id:e,op:"update",previous:d,table:s}),he(s),pe(s),Ae(o,s,n`UPDATE ${n.identifier(s)} SET ${n.identifier(P)} = ${JSON.stringify(w)} WHERE id = ${e} AND ${n.identifier(P)} = ${f}`),Ee(s,e,w,d),ye(s,e,w),be(s,d,w),we(s,e,d,w),O?.invalidate(s,e,c(s,d,w)),H(s,e,"update",w),l({indexKeys:c(s,d,w),key:e,op:"update",row:w,table:s}),ee(s,"after","update")&&await te("after","update",{doc:w,id:e,op:"update",previous:d,table:s}),await M({doc:w,id:e,op:"update",table:s})},async patchMany(e,r,a){se(e.length,r?.limit,"patchMany");for(const h of e)await q.patch(h.id,h.patch,a);return{patched:e.length}},async patchWhere(e,r,a){const h=J(e,"patchWhere");let f;if(h)f=(await h.findMany(e,{where:r.where})).page.map(d=>({id:String(d._id),patch:r.patch}));else{if(!t.tables[e])throw new b("INTERNAL",`unknown table: ${e}`);f=(await q.findMany(e,{where:r.where})).page.map(d=>({id:String(d._id),patch:r.patch}))}if(se(f.length,a?.limit,"patchWhere"),q.patchMany===void 0)throw new b("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await q.patchMany(f,a),{patched:f.length}},query(e){const r=J(e,"query");return r?(y(e,B),r.query(e)):Fn(o,t,e,E,a=>{a?$(a):y(e,B)},a=>{m||p?.recordRead(a)})},async rank(e,r,a){const h=J(e,"rank");if(h)return y(e,B),h.rank(e,r,a);E(e,r,"rank");const f=t.tables[e];if(!f)throw new b("INTERNAL",`unknown table: ${e}`);const d=f.rankIndexes?.find(G=>G.name===r);if(!d)throw new b("INTERNAL",`unknown rankIndex "${r}" on table "${e}"`);if(Ve(e,f,d),a.restrictsCounts)throw new Le(e);y(e,B),Ie(e,d);const s=typeof a.row=="string"?a.row:a.row._id;if(!s)return null;const u=rt(e,d.name),w=d.sortBy.map((G,ae)=>nt(ae)),T=w.map(G=>Lt(G)).join(", "),g=F(o,n`SELECT ${n.identifier("__partition__")}, ${n.raw(T)} FROM ${n.identifier(u)} WHERE ${n.identifier("__id__")} = ${s}`).toArray(),[A]=g;if(A===void 0)return null;let W=A.__partition__;const D=Q(a.baseWhere,a.where);Oe(D,t,e,"rank");const x=Ht(d,D);if(x){const G=Gt(d.partitionBy??[],x);if(G!==W)return null;W=G}const K=w.map(G=>A[G]),{before:Y,total:V}=ht(o,u,w,d.sortBy,W,K,s);return{position:Y+1,total:V}},async rankBefore(e,r,a){if(X(e))throw new b("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const h=t.tables[e];if(!h)throw new b("INTERNAL",`unknown table: ${e}`);const f=h.rankIndexes?.find(w=>w.name===r);if(!f)throw new b("INTERNAL",`unknown rankIndex "${r}" on table "${e}"`);if(a.restrictsCounts)throw new Le(e);y(e,B),Ie(e,f);const d=rt(e,f.name),s=f.sortBy.map((w,T)=>nt(T)),u=f.sortBy.map((w,T)=>re(a.sortValues[T]??null));return ht(o,d,s,f.sortBy,a.partitionKey,u,a.rowId)},async rankPage(e,r,a={}){Oe(Q(a.baseWhere,a.where),t,e,"rankPage");const h=J(e,"rankPage");if(h)return y(e,B),h.rankPage(e,r,a);E(e,r,"rank");const{continueCursor:f,hasMore:d,rows:s}=Ze(Xe,e,r,a);return{continueCursor:f,isDone:!d,page:s.map(u=>u.doc)}},async rankPageRows(e,r,a={}){Oe(Q(a.baseWhere,a.where),t,e,"rankPage"),E(e,r,"rank");const{directions:h,hasMore:f,rows:d}=Ze(Xe,e,r,a);return{directions:h,hasMore:f,rows:d}},async restore(e,r){const a=ie(e,r);if(!a){const d=r===void 0?fe():void 0;if(d?.restore){await d.restore(e);return}throw new b("INTERNAL",`document not found: ${e}`)}const h=t.tables[a.tableName]?.softDeleteMode?.field;if(!h)throw new b("INTERNAL",`ctx.db.restore: table "${a.tableName}" is not a .softDelete() table`);const f=a.row[h]!==null&&a.row[h]!==void 0;await q.patch(e,{[h]:null},r),f&&we(a.tableName,e,void 0,a.row)},async replace(e,r,a,h){const f=ie(e,a);if(!f){const A=a===void 0?fe():void 0;if(A){await A.replace(e,r,void 0,h);return}throw new b("INTERNAL",`document not found: ${e}`)}const{docJson:d,row:s,tableName:u}=f,w=t.tables[u];if(!w)throw new b("INTERNAL",`unknown table: ${u}`);ft("replace",r);const T=h?.allowExplicitId&&typeof r._creationTime=="number"?r._creationTime:C(),g={...r,_creationTime:T,_id:e};ut(w,r,g,N),We(w,g),ee(u,"before","update")&&await te("before","update",{doc:{...g},id:e,op:"update",previous:s,table:u}),he(u),pe(u),Ae(o,u,n`UPDATE ${n.identifier(u)} SET _creationTime = ${T}, ${n.identifier(P)} = ${JSON.stringify(g)} WHERE id = ${e} AND ${n.identifier(P)} = ${d}`),Ee(u,e,g,s),ye(u,e,g),be(u,s,g),we(u,e,s,g),O?.invalidate(u,e,c(u,s,g)),H(u,e,"update",g),l({indexKeys:c(u,s,g),key:e,op:"update",row:g,table:u}),ee(u,"after","update")&&await te("after","update",{doc:g,id:e,op:"update",previous:s,table:u}),await M({doc:g,id:e,op:"update",table:u})},async wipeShard(e){const r=new Set(e?.exclude),a=e?.tables,h=Object.entries(t.tables).filter(([u,w])=>r.has(u)||a!==void 0&&!a.includes(u)?!1:w.shardMode?.kind!=="global").map(([u])=>u);if(a!==void 0){for(const u of a)if(!t.tables[u])throw new b("INTERNAL",`wipeShard: unknown table: ${u}`)}const f={};let d=0;const{deleteAll:s}=q;if(s===void 0)throw new b("INTERNAL","wipeShard: this writer has no deleteAll");for(const u of h){const w=await s(u,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});f[u]=w.deleted,d+=w.deleted}return{deleted:d,tables:f}}},Nt={db:q,scheduler:j};return i.enforceRls===!0?Vt(q,t,(e,r)=>ie(e,r)?.tableName,(e,r)=>Et(e,r)):q};export{yr as CDC_LOG_TABLE,vr as CLIENT_WATERMARK_TABLE,Lr as GLOBAL_SHAPE_SNAPSHOT_TABLE,Ur as IDEMPOTENCY_TABLE,Dn as NotUniqueError,zr as SEARCH_STATE_TABLE,Ir as advanceClientWatermark,Er as applyCdcChanges,wn as assertValidClientId,mr as backfillAggregateIndexes,$r as backfillRankIndexes,gr as backfillSearchIndexes,Nr as bumpCdcEpoch,hr as createShardCtxDb,Dr as deleteGlobalShapeSnapshot,Or as deleteGlobalShapeSnapshotsForConnection,Mr as migrateClientWatermark,Wr as migrateGlobalShapeSnapshot,Sr as minCdcSeq,dt as normalizeIdStructurally,Tr as readCdcChanges,_r as readCdcCursor,Rr as readCdcEpoch,Cr as readClientWatermark,Fr as readGlobalShapeSnapshot,Pr as readIdempotent,Kr as runShardMigrations,Yr as selectShapeMemberIds,Vr as selectShapeRows,Ar as trimCdcChanges,jr as trimIdempotent,qr as writeGlobalShapeSnapshot,Hr as writeIdempotent};
|
|
@@ -1,17 +0,0 @@
|
|
|
1
|
-
const s="__lunora_queue_messages",_=500,p=131072,d=(e,t,...a)=>e.exec.call(e,t,...a),o=e=>e??null,E="… [truncated by the dev queue catcher]",T="[unserializable message body]",n=e=>{if(e===void 0)return"null";try{const t=JSON.stringify(e);return t.length>131072?JSON.stringify(`${t.slice(0,131072)}${E}`):t}catch{return JSON.stringify(T)}},O=e=>typeof e=="string"&&(e===T||e.endsWith(E)),L=e=>{if(!(e==null||e===""))try{return JSON.parse(e)}catch{return}},u=e=>{d(e,`CREATE TABLE IF NOT EXISTS "${s}" (
|
|
2
|
-
id TEXT PRIMARY KEY,
|
|
3
|
-
captured_at INTEGER NOT NULL,
|
|
4
|
-
message_id TEXT NOT NULL,
|
|
5
|
-
queue TEXT NOT NULL,
|
|
6
|
-
export_name TEXT,
|
|
7
|
-
body TEXT NOT NULL,
|
|
8
|
-
attempts INTEGER NOT NULL,
|
|
9
|
-
outcome TEXT NOT NULL,
|
|
10
|
-
error TEXT,
|
|
11
|
-
dead_lettered INTEGER NOT NULL,
|
|
12
|
-
message_ts INTEGER NOT NULL
|
|
13
|
-
)`)},l=(e,t,a)=>{u(e);for(const r of t)d(e,`INSERT INTO "${s}" (id, captured_at, message_id, queue, export_name, body, attempts, outcome, error, dead_lettered, message_ts)
|
|
14
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,crypto.randomUUID(),a,r.messageId,r.queue,o(r.exportName),n(r.body),r.attempts,r.outcome,o(r.error),r.deadLettered===!0?1:0,r.timestamp);return d(e,`DELETE FROM "${s}"
|
|
15
|
-
WHERE id NOT IN (
|
|
16
|
-
SELECT id FROM "${s}" ORDER BY captured_at DESC, id DESC LIMIT ?
|
|
17
|
-
)`,500),{recorded:t.length}},i=e=>({attempts:e.attempts,body:L(e.body),capturedAt:e.captured_at,deadLettered:e.dead_lettered===1,error:e.error??void 0,exportName:e.export_name??void 0,id:e.id,messageId:e.message_id,outcome:e.outcome,queue:e.queue,timestamp:e.message_ts}),R=(e,t={})=>{u(e);const a=Math.min(Math.max(t.limit??100,1),500),r=typeof t.queue=="string"&&t.queue.length>0?t.queue:void 0,m=r===void 0?"":"WHERE queue = ?",N=r===void 0?[a]:[r,a];return{entries:d(e,`SELECT * FROM "${s}" ${m} ORDER BY captured_at DESC, id DESC LIMIT ?`,...N).toArray().map(c=>i(c))}},g=(e,t)=>{u(e);const a=d(e,`SELECT * FROM "${s}" WHERE id = ? LIMIT 1`,t).toArray()[0];return a===void 0?void 0:i(a)},I=e=>(u(e),d(e,`DELETE FROM "${s}"`),{cleared:!0});export{p as MAX_BODY_CHARS,_ as QUEUE_RETENTION,s as QUEUE_TABLE,I as clearQueueMessages,u as ensureQueueTable,O as isLossyBody,g as readQueueMessageById,R as readQueueMessages,l as recordQueueMessages};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{serializeSqlValue as l}from"./serializeSqlValue-DnpyaLcw.mjs";const f=(r,e)=>r<e?-1:r>e?1:0,a=Symbol("not-resolvable"),c=r=>{if(r!==null&&typeof r=="object"&&!Array.isArray(r)){const e=Object.keys(r);return e.length===1&&e[0]==="eq"?r.eq:a}return r},u=(r,e)=>{if(r.length===0)return"";const s={};for(const t of[...r].toSorted(f))s[t]=e[t]??null;return JSON.stringify(s)},_="__id__",k=r=>`__sort_k${String(r)}__`,b=(r,e)=>{for(const[s,t]of Object.entries(e)){const n=r[s];if(t!==null&&typeof t=="object"&&!Array.isArray(t)){const o=Object.keys(t);if(o.length===1&&o[0]==="eq"){if(n!==t.eq)return!1;continue}return!1}if(n!==t)return!1}return!0},m=(r,e)=>{const s=r.partitionBy??[],t=e??{};for(const o of Object.keys(t))if(o==="AND"||o==="OR"||o==="NOT")return;const n={};for(const o of s)if(o in t){const i=c(t[o]);if(i===a)return;n[o]=i}else if(r.where&&o in r.where)n[o]=r.where[o];else return;return n},p=(r,e)=>`${r}__rank_${e}`,h=(r,e)=>({partitionKey:u(r.partitionBy??[],e),rowId:e._id,sortValues:r.sortBy.map(s=>l(e[s.field]??null))});export{_ as RANK_TIEBREAK,u as encodePartitionKey,b as matchesRankStaticWhere,h as rankKeyFromDoc,p as rankTableName,m as resolveRankPartition,k as sortColumnName};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
const s="__relationExists";export{s as RELATION_EXISTS_KEY};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as g}from"@lunora/errors";const b=Symbol.for("lunora.ctxdb.rls-unwrap");class k extends g{table;constructor(i){super("RLS_REQUIRED",`ctx.db access to "${i}" 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=i}}const M=o=>Object.entries(o.tables).filter(([,i])=>i.shardMode?.kind!=="global").map(([i])=>i),R=(o,i,u)=>{const n=i?.tables,r=new Set(i?.exclude);for(const d of o)(n===void 0||n.includes(d))&&!r.has(d)&&u(d)},m=(o,i,u)=>{const n={},{deleteAll:r,wipeShard:d}=o;return r&&(n.deleteAll=(s,c)=>(u(s),r(s,c))),d&&(n.wipeShard=s=>(R(M(i),s,u),d(s))),n},v=(o,i,u,n)=>{if(i.rlsMode!=="required")return o;const r=o,d=e=>{const t=i.tables[e];return t!==void 0&&t.isPublic!==!0},s=e=>{if(d(e))throw new k(e)},c=async(e,t)=>{if(t!==void 0){s(t);return}const a=await u(e);a!==void 0&&s(a)},p=async(e,t)=>{if(t!==void 0){s(t);return}if(!n){for(const l of e)await c(l,t);return}const a=await n([...new Set(e)],t);for(const l of e){const f=a.get(l);f!==void 0&&s(f)}},h=r.rankBefore,w=r.rankPageRows,y={...o,...m(r,i,s),[b]:o,aggregate:(e,t)=>(s(e),r.aggregate(e,t)),count:(e,t)=>(s(e),r.count(e,t)),delete:async(e,t,a)=>(await c(e,t),r.delete(e,t,a)),deleteMany:async(e,t,a)=>(await p(e,a),r.deleteMany(e,t,a)),deleteWhere:r.deleteWhere?async(e,t,a)=>(s(e),await r.deleteWhere?.(e,t,a)):void 0,findFirst:(e,t)=>(s(e),r.findFirst(e,t)),findFirstOrThrow:(e,t)=>(s(e),r.findFirstOrThrow(e,t)),findMany:(e,t)=>(s(e),r.findMany(e,t)),get:async(e,t)=>(await c(e,t),r.get(e,t)),groupBy:(e,t)=>(s(e),r.groupBy(e,t)),insert:(e,t,a)=>(s(e),r.insert(e,t,a)),insertMany:(e,t,a)=>(s(e),r.insertMany(e,t,a)),insertManyUnsafe:(e,t,a)=>(s(e),r.insertManyUnsafe(e,t,a)),lookupById:async(e,t)=>(await c(e,t),r.lookupById?.(e,t)??null),patch:async(e,t,a)=>(await c(e,a),r.patch(e,t,a)),patchMany:async(e,t,a)=>(await p(e.map(l=>l.id),a),r.patchMany(e,t,a)),patchWhere:r.patchWhere?async(e,t,a)=>(s(e),await r.patchWhere?.(e,t,a)):void 0,query:e=>(s(e),r.query(e)),rank:(e,t,a)=>(s(e),r.rank(e,t,a)),rankPage:(e,t,a)=>(s(e),r.rankPage(e,t,a)),replace:async(e,t,a,l)=>(await c(e,a),r.replace(e,t,a,l)),restore:async(e,t)=>(await c(e,t),r.restore?.(e,t))};return h&&(y.rankBefore=(e,t,a)=>(s(e),h(e,t,a))),w&&(y.rankPageRows=(e,t,a)=>(s(e),w(e,t,a))),y};export{b as RLS_UNWRAP_SYMBOL,k as RlsRequiredError,v as guardWriter};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{stableWireKey as g}from"./stableWireKey-YEHLaX6X.mjs";import{depKey as b,SCAN_DEP as p}from"./SCAN_DEP-D_yR9EeV.mjs";import{t as y}from"./estimate-bytes-DwQON1Ky.mjs";import{keysTouchRanges as x}from"./buildIndexRange-DFsdtPjD.mjs";import{stableStringify as R}from"./stableStringify-BjLh4gvA.mjs";const m=1e3,u=4*1024*1024;class z{entries=new Map;tableIndex=new Map;rangeIndex=new Map;totalBytes=0;hits=0;misses=0;evictions=0;maxEntries;maxBytes;now;monotonic=0;constructor(t={}){this.maxEntries=t.maxEntries??m,this.maxBytes=t.maxBytes??u,this.now=t.now??(()=>(this.monotonic+=1,this.monotonic))}async run(t,s,i,e=()=>[]){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 h=await i(),o=y(h);if(o===void 0)return h;const c=e(),f={bytes:o,deps:s,ranges:c,lastUsed:this.now(),result:h,subscribers:new Set};this.entries.set(t,f),this.totalBytes+=o;for(const a of s){let r=this.tableIndex.get(a);r||(r=new Set,this.tableIndex.set(a,r)),r.add(t)}for(const a of c){let r=this.rangeIndex.get(a.table);r||(r=new Map,this.rangeIndex.set(a.table,r));let l=r.get(a);l||(l=new Set,r.set(a,l)),l.add(t)}return this.evict(),h}invalidate(t,s,i){const e=[];return this.collectAndDrop(b(t,s),e),this.collectAndDrop(b(t,p),e),this.dropRangeDeps(t,i,e),e}invalidateTable(t){const s=[],i=`${t}:`;for(const e of this.tableIndex.keys())e.startsWith(i)&&this.collectAndDrop(e,s);return this.dropRangeDeps(t,void 0,s),s}subscribe(t,s){const i=this.entries.get(t);i&&i.subscribers.add(s)}unsubscribe(t,s){const i=this.entries.get(t);i&&i.subscribers.delete(s)}size(){return{bytes:this.totalBytes,entries:this.entries.size}}clear(){this.entries.clear(),this.tableIndex.clear(),this.rangeIndex.clear(),this.totalBytes=0}subscribers(t){const s=this.entries.get(t);return s?[...s.subscribers]:[]}stats(){return{bytes:this.totalBytes,entries:this.entries.size,evictions:this.evictions,hits:this.hits,misses:this.misses}}dropRangeDeps(t,s,i){const e=this.rangeIndex.get(t);if(!(!e||e.size===0)){for(const[n,h]of e)if(x([n],s))for(const o of h){const c=this.entries.get(o);c&&(this.dropEntry(o,c),i.push(o))}}}collectAndDrop(t,s){const i=this.tableIndex.get(t);if(i)for(const e of i){const n=this.entries.get(e);n&&(this.dropEntry(e,n),s.push(e))}}dropEntry(t,s){this.entries.delete(t),this.totalBytes-=s.bytes;for(const i of s.deps){const e=this.tableIndex.get(i);e&&(e.delete(t),e.size===0&&this.tableIndex.delete(i))}for(const i of s.ranges){const e=this.rangeIndex.get(i.table),n=e?.get(i);n?.delete(t),e&&n?.size===0&&(e.delete(i),e.size===0&&this.rangeIndex.delete(i.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 E=(d,t,s)=>`${s??"\0anon"}\0${d}:${g(t)}`;export{z as ReactiveCache,E as reactiveCacheKey,R as stableStringify,g as stableWireKey};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
const t="*scan",n=(e,r)=>`${e}:${r}`,d=e=>{const r=e.indexOf(":");return r===-1?e:e.slice(0,r)},o=()=>{const e=new Set;return{collect(){return e},recordRead(r,c){e.add(n(r,c))}}};export{t as SCAN_DEP,o as createDependencyTracker,n as depKey,d as tableFromDepKey};
|
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
import{q as n}from"./quote-identifier-CGiYFBvY.mjs";const T="__lunora_schema_history",i=50,r=(s,a,...e)=>s.exec(a,...e),t=n(T),h=s=>{r(s,`CREATE TABLE IF NOT EXISTS ${t} (
|
|
2
|
-
hash TEXT PRIMARY KEY,
|
|
3
|
-
seq INTEGER NOT NULL,
|
|
4
|
-
snapshot_json TEXT NOT NULL,
|
|
5
|
-
applied_at INTEGER NOT NULL
|
|
6
|
-
)`)},R=s=>{r(s,`DELETE FROM ${t} WHERE hash NOT IN (SELECT hash FROM ${t} ORDER BY seq DESC LIMIT ?)`,i)},S=(s,a,e,E=Date.now())=>{if(a===""||e==="")return!1;try{if(h(s),r(s,`SELECT hash FROM ${t} WHERE hash = ? LIMIT 1`,a).toArray().length>0)return!1;const[o]=r(s,`SELECT COALESCE(MAX(seq), 0) + 1 AS next FROM ${t}`).toArray(),p=typeof o?.next=="number"?o.next:1;return r(s,`INSERT INTO ${t} (hash, seq, snapshot_json, applied_at) VALUES (?, ?, ?, ?) ON CONFLICT(hash) DO NOTHING`,a,p,e,E),R(s),!0}catch{return!1}},_=s=>{try{return h(s),r(s,`SELECT hash, seq, applied_at FROM ${t} ORDER BY seq DESC`).toArray().map(a=>({appliedAt:typeof a.applied_at=="number"?a.applied_at:0,hash:typeof a.hash=="string"?a.hash:"",seq:typeof a.seq=="number"?a.seq:0}))}catch{return[]}},I=(s,a)=>{try{h(s);const[e]=r(s,`SELECT hash, seq, applied_at, snapshot_json FROM ${t} WHERE hash = ? LIMIT 1`,a).toArray();return e===void 0?void 0:{appliedAt:typeof e.applied_at=="number"?e.applied_at:0,hash:typeof e.hash=="string"?e.hash:"",seq:typeof e.seq=="number"?e.seq:0,snapshotJson:typeof e.snapshot_json=="string"?e.snapshot_json:""}}catch{return}};export{i as SCHEMA_HISTORY_MAX_VERSIONS,_ as readSchemaHistory,I as readSchemaVersion,S as recordSchemaVersion};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{sql as i}from"drizzle-orm";import{runDrizzle as o}from"./runDrizzle-GKR3y97k.mjs";const t="__lunora_search_state",E=e=>{const n=()=>{try{o(e,i`ALTER TABLE ${i.identifier(t)} ADD COLUMN ${i.identifier("profile")} TEXT`)}catch{}};o(e,i`CREATE TABLE IF NOT EXISTS ${i.identifier(t)} (${i.identifier("companion")} TEXT PRIMARY KEY, ${i.identifier("cursor")} TEXT, ${i.identifier("done")} INTEGER NOT NULL DEFAULT 0, ${i.identifier("profile")} TEXT)`),n()},c=e=>e===1||e===!0||e==="1",l=(e,n)=>{const r=o(e,i`SELECT ${i.identifier("cursor")}, ${i.identifier("done")}, ${i.identifier("profile")} FROM ${i.identifier(t)} WHERE ${i.identifier("companion")} = ${n}`).toArray()[0];return r?{cursor:r.cursor??void 0,done:c(r.done),profile:r.profile??void 0}:{cursor:void 0,done:!1,profile:void 0}},s=(e,n,r,d,f)=>{const $=r??null;o(e,i`INSERT INTO ${i.identifier(t)} (${i.identifier("companion")}, ${i.identifier("cursor")}, ${i.identifier("done")}, ${i.identifier("profile")}) VALUES (${n}, ${$}, ${d?1:0}, ${f}) ON CONFLICT (${i.identifier("companion")}) DO UPDATE SET ${i.identifier("cursor")} = excluded.${i.identifier("cursor")}, ${i.identifier("done")} = excluded.${i.identifier("done")}, ${i.identifier("profile")} = excluded.${i.identifier("profile")}`)};export{t as SEARCH_STATE_TABLE,E as migrateSearchState,l as readSearchBackfillState,s as writeSearchBackfillState};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
class r{shardHost;socketHost;options;constructor(s,t,e={}){this.shardHost=s,this.socketHost=t,this.options=e}get shardKey(){return this.shardHost.shardKey}socketFor(s){return this.socketHost.handleFor(s)??s}sockets(s){return this.socketHost.getSockets(s)}background(s){return this.shardHost.waitUntil===void 0?!1:(this.shardHost.waitUntil(s),!0)}async runInTransaction(s){return this.shardHost.runSerialized(async()=>this.shardHost.transaction(s))}async handleFetch(s){return this.options.handlers?.handleFetch?this.options.handlers.handleFetch(s):new Response("Not implemented",{status:501})}async handleAlarm(){this.options.handlers?.handleAlarm&&await this.options.handlers.handleAlarm()}}export{r as ShardRunner};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
const g=(e,t)=>e<t?-1:e>t?1:0,r=(e,t)=>`${e}__agg_${t}`,n=e=>{if(typeof e=="number")return Number.isFinite(e)?e:void 0},c=(e,t,l,a)=>{const u=e.get(t)??{count:0,value:null};if(l.op==="count"){u.count+=1,u.value=u.count,e.set(t,u);return}const o=n(a[l.field??""]);if(l.op==="sum"||l.op==="avg"){o!==void 0&&(u.value=(u.value??0)+o,u.count+=1),e.set(t,u);return}u.count+=1,o!==void 0&&(u.value===null?u.value=o:u.value=l.op==="min"?Math.min(u.value,o):Math.max(u.value,o)),e.set(t,u)},v=(e,t)=>e==="count"?t?.value??0:!t||t.count===0?null:e==="avg"?t.value===null?null:t.value/t.count:t.value,i=(e,t)=>{if(e.length===0)return"";const l={};for(const a of[...e].toSorted(g))l[a]=t[a]??null;return JSON.stringify(l)};export{r as aggregateTableName,n as coerceAggregateNumber,i as encodeAggregateKey,c as foldAggregateTally,v as readAggregateValue};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as W}from"@lunora/errors";import{applySelect as j}from"./applySelect-B0CF8T7y.mjs";const A=(s,o)=>o.select?j(s,o.select,o.with):s,L=async(s,o,t,r,a)=>{const w=await Promise.all(r.map(async i=>{const m=a?{AND:[{[t]:i},a]}:{[t]:i};return[i,await s(o,m)]}));return new Map(w)},R=(s,o)=>{const t=new Set;for(const r of s){const a=r[o];a!=null&&t.add(a)}return[...t]},_=async s=>{const{groupedCounter:o,fetcher:t,parents:r,relationBaseWhere:a,schema:w,tableName:i,with:m}=s;if(r.length===0)return;const k=w.tables[i];if(!k)throw new W("INTERNAL",`unknown table: ${i}`);const M=k.relationMap??{},g=l=>{const e=M[l];if(!e)throw new W("INTERNAL",`unknown relation "${l}" on table "${i}"`);return e},D=async(l,e,n)=>{const u=R(r,e.field);if(u.length===0){for(const c of r)c[l]=null;return}const{page:p}=await t(e.table,{baseWhere:a?.(e.table),relationBaseWhere:a,where:{[e.references]:{in:u}},with:n.with}),b=new Map;for(const c of p)b.set(c[e.references],c);for(const c of r){const d=b.get(c[e.field]);c[l]=d?A([d],n)[0]??null:null}},O=async(l,e,n)=>{const u=R(r,e.references);if(u.length===0){for(const f of r)f[l]=[];return}const p={[e.field]:{in:u}},b=n.where?{AND:[n.where,p]}:p,{page:c}=await t(e.table,{baseWhere:a?.(e.table),orderBy:n.orderBy,relationBaseWhere:a,where:b,with:n.with}),d=new Map;for(const f of c){const h=f[e.field],$=d.get(h);$?$.push(f):d.set(h,[f])}const y=typeof n.limit=="number"?Math.max(0,Math.floor(n.limit)):void 0;for(const f of r){const h=d.get(f[e.references])??[];f[l]=A(y===void 0?h:h.slice(0,y),n)}},N=async l=>{for(const e of Object.keys(l)){const n=g(e),[u,p]=n.kind==="many"?[n.field,n.references]:[n.references,n.field],b=a?.(n.table),c=R(r,p),d=c.length===0?new Map:await o(n.table,u,c,b);for(const y of r){const f=y._count??{},h=y[p];f[e]=h==null?0:d.get(h)??0,y._count=f}}};for(const[l,e]of Object.entries(m)){if(e===void 0||e===!1)continue;if(l==="_count"){await N(e);continue}const n=g(l),u=e===!0?{}:e;await(n.kind==="one"?D(l,n,u):O(l,n,u))}},v=async(s,o,t)=>{const{deletedId:r,deletedReference:a,findHolders:w,onCascade:i,onRestrict:m,onSetNull:k,tableName:M}=s,g=t.references==="_id"?r:a(t.references);if(g==null)return;const D=await w(o,t.field,g);if(D.length!==0){t.onDelete==="restrict"&&m(`cannot delete "${M}" row: "${o}.${t.field}" still references it`);for(const O of D){const N=O._id;typeof N=="string"&&await(t.onDelete==="cascade"?i(o,N):k(o,N,t.field))}}},E=async s=>{const{schema:o,tableName:t}=s;if(!o.tables[t])throw new W("INTERNAL",`unknown table: ${t}`);for(const[r,a]of Object.entries(o.tables)){const w=a.relationMap;if(w)for(const i of Object.values(w))i.kind!=="one"||i.table!==t||!i.onDelete||await v(s,r,i)}},S=(s,o,t=!1)=>{for(const[r,a]of Object.entries(s.shape))r in o&&typeof a.parse=="function"&&(t&&o[r]===null&&a.kind==="optional"||a.parse(o[r]))};export{E as applyOnDelete,R as distinctValues,L as fanOutScalarCounts,_ as resolveWith,S as runRowValidators};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as m}from"@lunora/errors";const u="id",h=new Set(["_id","id"]),b=t=>{const e=[];for(const r of t??[])for(const[o,s]of Object.entries(r))e.push({direction:s,field:o});return e.length===0?[{direction:"asc",field:"_creationTime"}]:e},S=t=>{const e=new TextEncoder().encode(t);let r="";for(const o of e)r+=String.fromCodePoint(o);return btoa(r)},g=t=>{const e=atob(t),r=Uint8Array.from(e,o=>o.codePointAt(0)??0);return new TextDecoder().decode(r)},A=(t,e)=>{const r=e.map(o=>t[o.field]);return r.push(t._id),S(JSON.stringify(r))},l=()=>new m("BAD_REQUEST","invalid cursor"),D=t=>{let e;try{e=JSON.parse(g(t))}catch{throw l()}if(!Array.isArray(e))throw l();return e},_=(t,e)=>{const r=t.some(s=>h.has(s.field))?t:[...t,{direction:"asc",field:u}],o=[];for(const[s,n]of r.entries()){const i=[];for(const[d,a]of r.slice(0,s).entries())i.push({[a.field]:{eq:e[d]}});const f=n.direction==="desc"?"lt":"gt";i.push({[n.field]:{[f]:e[s]}});const[c]=i;o.push(i.length===1&&c!==void 0?c:{AND:i})}return{OR:o}},y=(t,e)=>t==="desc"?e?"gte":"gt":e?"lte":"lt",v=(t,e)=>{const r=t.some(s=>h.has(s.field))?t:[...t,{direction:"asc",field:u}],o=[];for(const[s,n]of r.entries()){const i=[];for(const[a,p]of r.slice(0,s).entries())i.push({[p.field]:{eq:e[a]}});const f=s===r.length-1,c=y(n.direction,f);i.push({[n.field]:{[c]:e[s]}});const[d]=i;o.push(i.length===1&&d!==void 0?d:{AND:i})}return{OR:o}},w=["_id","_creationTime"],E=(t,e,r)=>{if(!e)return t;const o=new Set([...e,...w,...r?Object.keys(r):[]]);return t.map(s=>{const n={};for(const i of o)i in s&&(n[i]=s[i]);return n})},N=(t,e)=>t&&e!==!0?{[t.field]:{isNull:!0}}:void 0;export{E as applySelect,v as buildSeekBeforeWhere,_ as buildSeekWhere,D as decodeCursor,A as encodeCursor,g as fromBase64,l as invalidCursor,b as normalizeOrderKeys,N as softDeleteScope,S as toBase64};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{f as l}from"./wire-codec-Ctnni0h6.mjs";const c="_id",p="__lunora__",b=r=>{if(typeof r!="object"||r===null||Array.isArray(r))return;const t=r[c];return typeof t=="string"?t:void 0},y=r=>{const t=new Map,o=[];for(const s of r){const e=b(s);if(e===void 0||t.has(e))return;t.set(e,s),o.push(e)}return{byId:t,order:o}},g=(r,t)=>{const o=r.order.filter(e=>t.byId.has(e)),s=t.order.filter(e=>r.byId.has(e));return o.length!==s.length?!1:o.every((e,n)=>s[n]===e)},h=(r,t,o,s)=>{const e=[];for(const n of r.order)t.byId.has(n)||e.push({delta:{key:n,op:"delete",table:o},frame:`{"key":${JSON.stringify(n)},"op":"delete","table":${s}}`});return e},m=(r,t,o,s)=>{const e=[];for(const n of t.order){const i=t.byId.get(n),a=r.byId.get(n),f=JSON.stringify(l(i)),d=a===void 0?void 0:JSON.stringify(a);if(d===f)continue;const u=d===void 0?"insert":"update";e.push({delta:{key:n,op:u,row:i,table:o},frame:`{"key":${JSON.stringify(n)},"op":"${u}","row":${f},"table":${s}}`})}return e},S=(r,t,o,s)=>{let e;try{e=JSON.parse(r)}catch{return}if(!Array.isArray(e)||!Array.isArray(t))return;const n=y(e),i=y(t);if(n===void 0||i===void 0||!g(n,i))return;const a=o===""?p:o,f=JSON.stringify(a),d=[...h(n,i,a,f),...m(n,i,a,f)];if(!(d.length>i.order.length)){if(s!==void 0)for(const{frame:u}of d)s.push(u);return d.map(({delta:u})=>u)}},$=(r,t)=>{try{return r.send(t),!0}catch{return!1}},I=(r,t,o,s,e)=>{const n=JSON.stringify(t),i=e===void 0?"":`,"lastMutationId":${String(e)}`;let a=!0;for(const f of o)$(r,`{"type":"delta","id":${n},"delta":${f}${i}${s}}`)||(a=!1);return a},w=async r=>{let t=0;for(;t<100;){t+=1;const{bufferedAmount:o}=r;if(typeof o!="number"||o<1048576)return;await new Promise(s=>{setTimeout(s,20)})}};export{w as awaitWsDrain,I as sendDeltaFrames,S as subscriptionListDeltas,$ as trySendFrame};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{A as R,T as S,l as O,y as I,c as b}from"./FTS_COUNT_COLUMN-D1gY3wwZ-CZHdaRrd.mjs";import"@lunora/errors";import{sql as e}from"drizzle-orm";import{matchesStaticWhere as A}from"./AGGREGATE_SQL_FUNCTION-QYaiuty4.mjs";import{encodeAggregateKey as _,foldAggregateTally as L,aggregateTableName as M}from"./aggregateTableName-G-eXyjcz.mjs";import{migrateSearchState as k,readSearchBackfillState as C,writeSearchBackfillState as N}from"./SEARCH_STATE_TABLE-eLN8U5tz.mjs";import{runDrizzle as c}from"./runDrizzle-GKR3y97k.mjs";import{isFtsAvailable as u,DOC_COLUMN as g,rowToDocument as p,AGG_KEY as w,AGG_VALUE as y,AGG_COUNT as x,tryRowToDocument as F}from"./AGG_COUNT-BWXe3gtQ.mjs";import{param as D}from"./param-B5lF5Jd9.mjs";import{sortColumnName as U,matchesRankStaticWhere as B,encodePartitionKey as G,rankTableName as j}from"./RANK_TIEBREAK-9NU5s_mi.mjs";import{serializeSqlValue as v}from"./serializeSqlValue-DnpyaLcw.mjs";const V=(i,t)=>i.profile!==t?{cursor:void 0,finished:!1,wipe:i.cursor!==void 0||i.done}:{cursor:i.cursor,finished:i.done,wipe:!1},W=(i,t,r)=>{const o=M(t,r.name);if(c(i,e`SELECT COUNT(*) AS count FROM ${e.identifier(o)}`).one().count>0)return;const n=r.by??[],s=new Map,d=c(i,e`SELECT id, _creationTime, ${e.identifier(g)} FROM ${e.identifier(t)}`).toArray();for(const f of d){const a=p(f);if(!a||r.where&&!A(a,r.where))continue;const m=_(n,a);L(s,m,r,a)}for(const[f,a]of s)c(i,e`INSERT INTO ${e.identifier(o)} (${w}, ${y}, ${x}) VALUES (${f}, ${a.value}, ${a.count})`)},oe=(i,t)=>{for(const[r,o]of Object.entries(t.tables))if(!(o.shardMode?.kind==="global"||!o.aggregateIndexes))for(const n of o.aggregateIndexes)W(i,r,n)},z=(i,t,r)=>{const o=j(t,r.name);if(c(i,e`SELECT COUNT(*) AS count FROM ${e.identifier(o)}`).one().count>0)return;const n=r.sortBy.map((f,a)=>U(a)),s=e.join(["__id__","__partition__",...n].map(f=>e.identifier(f)),e`, `),d=c(i,e`SELECT id, _creationTime, ${e.identifier(g)} FROM ${e.identifier(t)}`).toArray();for(const f of d){const a=p(f);if(!a||r.where&&!B(a,r.where))continue;const m=G(r.partitionBy??[],a),E=r.sortBy.map($=>v(a[$.field]??null)),l=e.join([a._id,m,...E].map($=>D($)),e`, `);c(i,e`INSERT INTO ${e.identifier(o)} (${s}) VALUES (${l})`)}},re=(i,t)=>{for(const[r,o]of Object.entries(t.tables))if(!(o.shardMode?.kind==="global"||!o.rankIndexes))for(const n of o.rankIndexes)z(i,r,n)},T=500,h=(i,t,r)=>{const o=b(t,r.name),{profile:n}=R(r.language),s=V(C(i,o),n);if(s.finished)return!0;s.wipe&&c(i,e`DELETE FROM ${e.identifier(o)}`);const{cursor:d}=s,f=c(i,d===void 0?e`SELECT id, _creationTime, ${e.identifier(g)} FROM ${e.identifier(t)} ORDER BY id ASC LIMIT ${e.raw(String(T))}`:e`SELECT id, _creationTime, ${e.identifier(g)} FROM ${e.identifier(t)} WHERE id > ${d} ORDER BY id ASC LIMIT ${e.raw(String(T))}`).toArray();let a=d;for(const E of f){const{id:l}=E;if(typeof l!="string")continue;a=l;const $=F(E);if(!$){c(i,e`DELETE FROM ${e.identifier(o)} WHERE ${e.identifier(S)} = ${l}`);continue}c(i,e`DELETE FROM ${e.identifier(o)} WHERE ${e.identifier(S)} = ${l}`),c(i,e`INSERT INTO ${e.identifier(o)} (${e.identifier(O)}, ${e.identifier(S)}) VALUES (${I($,r)}, ${l})`)}const m=f.length<T;return N(i,o,a,m,n),m},te=(i,t,r)=>{if(u(i))for(const o of r.searchIndexes??[])o.staged||h(i,t,o)},ae=(i,t)=>{if(u(i)){k(i);for(const[r,o]of Object.entries(t.tables))if(!(o.shardMode?.kind==="global"||!o.searchIndexes))for(const n of o.searchIndexes){let s=!1;for(;!s;)s=h(i,r,n)}}};export{oe as backfillAggregateIndexes,re as backfillRankIndexes,ae as backfillSearchIndexes,te as backfillSearchIndexesForTable};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
const v=t=>{const o=new DataView(new ArrayBuffer(8));o.setFloat64(0,t,!1);let r=o.getUint32(0,!1),e=o.getUint32(4,!1);return(r&2147483648)===0?r=(r^2147483648)>>>0:(r=~r>>>0,e=~e>>>0),r.toString(16).padStart(8,"0")+e.toString(16).padStart(8,"0")},g=t=>{const o=new TextEncoder().encode(t);let r="";for(const e of o)r+=e.toString(16).padStart(2,"0");return r},c=t=>{if(t===null)return"0";if(typeof t=="number")return Number.isFinite(t)?`1${v(t===0?0:t)}`:void 0;if(typeof t=="string")return`2${g(t)}`},d=t=>{const o=[];for(const r of t){const e=c(r);if(e===void 0)return;o.push(e)}return o.join("!")};const p=new Set([">",">="]),x=new Set(["<","<="]),h=(t,o,r,e)=>{const i=o.comparator==="=",n=p.has(o.comparator)||x.has(o.comparator);return!i&&!n||t.indexOf(o.field)!==r?!1:e===void 0?!0:!i&&e===o.field},w=(t,o,r)=>{const e={equalities:[],lowerExclusive:!1,upperExclusive:!1};let i;for(const n of o){const s=n.comparator==="=",a=p.has(n.comparator);if(!h(t,n,e.equalities.length,i))return;if(s){e.equalities.push(r(n.value));continue}if(i=n.field,a){if(e.lower!==void 0)return;e.lower=r(n.value),e.lowerExclusive=n.comparator===">"}else{if(e.upper!==void 0)return;e.upper=r(n.value),e.upperExclusive=n.comparator==="<"}}return e},f=(t,o)=>{const r=c(o);if(r!==void 0)return t===""?r:t+"!"+r},y=(t,o,r,e,i)=>{if(r.length===0)return;const n=w(r,e,i);if(!n)return;const s=d(n.equalities);if(s===void 0)return;let a=s,l=s+"";if(n.lower!==void 0){const u=f(s,n.lower);if(u===void 0)return;a=n.lowerExclusive?u+"!":u}if(n.upper!==void 0){const u=f(s,n.upper);if(u===void 0)return;l=n.upperExclusive?u:u+""}if(!(a>=l))return{hi:l,index:o,lo:a,table:t}},E=(t,o,r)=>{const e=[];for(const i of t){const n=d(i.fields.map(s=>r(o[s])));n!==void 0&&e.push({index:i.name,key:n})}return e},m=(t,o)=>t.index===o.index&&o.key>=t.lo&&o.key<t.hi,S=(t,o)=>{if(!t||t.length===0||!o||o.length===0)return!0;const r=new Map;for(const e of o){const i=r.get(e.index);i?i.push(e):r.set(e.index,[e])}return t.some(e=>{const i=r.get(e.index);return!i||i.length===0?!0:i.some(n=>m(e,n))})};export{y as buildIndexRange,E as indexKeysForRow,S as keysTouchRanges,m as rangeContains};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{f as u}from"./wire-codec-Ctnni0h6.mjs";const l=(t,o)=>{if(!o)return t;const r=Object.create(null);for(const a of["_id","_creationTime",...o])Object.hasOwn(t,a)&&(r[a]=t[a]);return r},b=(t,o,r)=>{const{columns:a,table:i}=r,n=new Map,p=[];for(const{doc:e,id:s}of t){const c=l(e,a),d=JSON.stringify(u(c));n.set(s,d);const h=o.get(s);h===void 0?p.push({key:s,op:"insert",table:i,value:c}):h!==d&&p.push({key:s,op:"update",table:i,value:c})}for(const e of o.keys())n.has(e)||p.push({key:e,op:"delete",table:i});return{next:n,rowsPatch:p}},f=t=>t.map(o=>o.value===void 0?o:{...o,value:u(o.value)}),y=(t,o,r={})=>{const{baseCheckpoint:a,checkpoint:i,epoch:n,lastMutationId:p,pokeId:e}=o,s=[JSON.stringify({baseCheckpoint:a,epoch:n,pokeId:e,type:"pokeStart"})];for(const c of t){const d=r.preEncoded?c.rowsPatch:f(c.rowsPatch);s.push(JSON.stringify({pokeId:e,rowsPatch:d,shapeId:c.shapeId,type:"pokePart",...p===void 0?{}:{lastMutationId:p}}))}return s.push(JSON.stringify({checkpoint:i,epoch:n,pokeId:e,type:"pokeEnd"})),s};export{y as buildPokeFrames,b as diffGlobalMembership,f as encodeRowsPatch,l as projectColumns};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
const a=/key|secret|token|password|passwd|credential|private|auth|bearer|session|cookie|salt|signature|dsn|webhook/iu,c=new Set(["LUNORA_ADMIN_TOKEN","LUNORA_WS_BEARER"]),l=["CF_PAGES_URL","WORKER_URL","LUNORA_WORKER_URL"],s=["CF_ENV","ENVIRONMENT","WORKER_ENV","NODE_ENV"],u=n=>n.length<=4?"••••":`${n.slice(0,4)}${"•".repeat(Math.min(8,n.length-4))}`,p=n=>a.test(n),f=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"},d=n=>{const e={};for(const t of l)if(typeof n[t]=="string"&&n[t]!==""){e.workerUrl=n[t];break}for(const t of s)if(typeof n[t]=="string"&&n[t]!==""){e.environment=n[t];break}const o=n.CF_VERSION_METADATA;if(o!==null&&typeof o=="object"){const t=o;typeof t.id=="string"&&(e.deploymentId=t.id),typeof t.tag=="string"&&(e.versionTag=t.tag)}return e},g=/^(?:dev(?:elopment)?|local(?:host)?|test)$/iu,m=n=>{const e=n??{};for(const o of s){const t=e[o];if(typeof t=="string"&&g.test(t))return!0}return!1},y=n=>{const e=n??{},o=[];for(const[t,r]of Object.entries(e))if(!c.has(t)){if(typeof r=="string"){const i=p(t);o.push({kind:i?"secret":"var",name:t,value:u(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:f(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:d(e),settings:o}};export{f as bindingType,y as buildSettings,m as isDevEnvironment,p as looksSecret,d as readDeployInfo,u as redact};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as $}from"@lunora/errors";import{sql as i}from"drizzle-orm";const c="__relationExists",N=["eq","ne","lt","lte","gt","gte","in","notIn","isNull","contains"],h=new Set(N),p={eq:"=",gt:">",gte:">=",lt:"<",lte:"<=",ne:"<>"},I=r=>{if(r===null||typeof r!="object"||Array.isArray(r))return!1;const e=Object.keys(r);return e.length>0&&e.every(t=>h.has(t))},g=r=>typeof r=="string"?r.replaceAll(/[\\%_]/g,e=>`\\${e}`):r,L=(r,e,t)=>{const s=i`${t.serialize(g(e))}`;return t.likeContains?t.likeContains(r,s):i`${r} LIKE '%' || ${s} || '%' ESCAPE '\\'`},O=(r,e,t,s,o)=>s===null?e==="ne"?i`${r} IS NOT NULL`:i`${r} IS NULL`:i`${r} ${i.raw(t)} ${o.serialize(s)}`,y=(r,e,t,s)=>{const o=Array.isArray(t)?t:[];if(o.length===0)return e==="IN"?i`0 = 1`:i`1 = 1`;const n=i.join(o.map(l=>i`${s.serialize(l)}`),i`, `);return e==="IN"?i`${r} IN (${n})`:i`${r} NOT IN (${n})`},S=(r,e,t)=>{const s=e,o=[];for(const n of N){if(!(n in s))continue;const l=s[n],u=p[n];u?o.push(O(r,n,u,l,t)):n==="isNull"?o.push(l?i`${r} IS NULL`:i`${r} IS NOT NULL`):n==="contains"?o.push(L(r,l,t)):o.push(y(r,n==="in"?"IN":"NOT IN",l,t))}return o},A=(r,e,t)=>{const s=t.fieldRef(r);return I(e)?S(s,e,t):e===null?[i`${s} IS NULL`]:[i`${s} = ${t.serialize(e)}`]},f=(r,e)=>{if(r.length!==0)return r.length===1?r[0]:i.join(r.map(t=>i`(${t})`),i` ${i.raw(e)} `)},E=(r,e,t)=>{const s=Array.isArray(r)?r:[],o=[];for(const n of s){const l=a(n??{},t);l&&o.push(l)}return o.length===0?e==="OR"?i`0 = 1`:void 0:f(o,e)},m=new Set(["AND","NOT","OR",c]),T=(r,e,t)=>{if(r===c){if(!t.relationExists)throw new $("INTERNAL","encountered a relation EXISTS marker without a relationExists strategy hook");return t.relationExists(e)}if(r==="NOT"){const s=a(e??{},t);return s?i`NOT (${s})`:void 0}return E(e,r,t)},a=(r,e)=>{const t=[];for(const[s,o]of Object.entries(r))if(m.has(s)){const n=T(s,o,e);n&&t.push(n)}else t.push(...A(s,o,e));return f(t,"AND")},j=(r,e)=>{if(!(!r||Object.keys(r).length===0))return a(r,e)};export{j as compileWhereSql};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as A}from"@lunora/errors";import{sql as t}from"drizzle-orm";import{mergeWhere as O}from"./CountRlsUnsupportedError-B2WKJD9v.mjs";import{SCAN_DEP as q}from"./SCAN_DEP-D_yR9EeV.mjs";import{runDrizzle as C}from"./runDrizzle-GKR3y97k.mjs";import{param as v}from"./param-B5lF5Jd9.mjs";import{decodeCursor as W}from"./applySelect-B0CF8T7y.mjs";import{sortColumnName as z,resolveRankPartition as F,RANK_TIEBREAK as m,encodePartitionKey as H,rankTableName as J}from"./RANK_TIEBREAK-9NU5s_mi.mjs";const V="__doc__",Y=o=>{const i=JSON.stringify(o),a=new TextEncoder().encode(i);let n="";for(const e of a)n+=String.fromCodePoint(e);return btoa(n)},G=o=>o.after?[o.after.partitionKey,...o.after.sortValues,o.after.rowId]:o.cursor?W(o.cursor):void 0,U=(o,i,a)=>{if(o?.length!==1+i.length+1)return;const n=[{column:"__partition__",direction:"asc"}];for(const[c,f]of i.entries())n.push({column:f,direction:a[c]?.direction??"asc"});n.push({column:m,direction:"asc"});const e=[];for(const[c,f]of n.entries()){const s=[];for(const[r,$]of n.slice(0,c).entries())s.push(t`${t.identifier($.column)} IS ${o[r]}`);s.push(t`${t.identifier(f.column)} ${t.raw(f.direction==="desc"?"<":">")} ${o[c]}`);const[d]=s;e.push(s.length===1&&d!==void 0?d:t`(${t.join(s,t` AND `)})`)}return t`(${t.join(e,t` OR `)})`},S=null,X=(o,i)=>{if(o===void 0)return S;const a=[o.__partition__,...i.map(n=>o[n]),o[m]];return Y(a)},Z=(o,i,a)=>{const n=[];for(const e of o){const c=e[m];if(typeof c!="string")continue;const f=i.get(c);if(!f)continue;const s=typeof e.__partition__=="string"?e.__partition__:"",d=a.map(r=>e[r]??null);n.push({doc:f,key:{partitionKey:s,rowId:c,sortValues:d}})}return n},Q=(o,i,a)=>{const{rowToDocument:n}=o,e=new Map;if(a.length===0)return e;const c=t.join(a.map(s=>v(s)),t`, `),f=C(o.sql,t`SELECT id, _creationTime, ${t.identifier(V)} FROM ${t.identifier(i)} WHERE id IN (${c})`).toArray();for(const s of f){const d=n(s),r=s.id;d&&typeof r=="string"&&e.set(r,d)}return e},ct=(o,i,a,n)=>{const{assertRankPartitionLocal:e,ensureRankBackfilled:c,onRead:f,schema:s}=o,d=s.tables[i];if(!d)throw new A("INTERNAL",`unknown table: ${i}`);const r=d.rankIndexes?.find(p=>p.name===a);if(!r)throw new A("INTERNAL",`unknown rankIndex "${a}" on table "${i}"`);e(i,d,r),f(i,q),c(i,r);const $=J(i,r.name),u=r.sortBy.map((p,E)=>z(E)),l=Math.max(1,Math.min(1e3,Math.floor(n.take??100))),T=O(n.baseWhere,n.where),R=F(r,T),h=[t`${t.identifier("__partition__")} ASC`];for(const[p,E]of u.entries()){const x=r.sortBy[p]?.direction;h.push(t`${t.identifier(E)} ${t.raw(x==="desc"?"DESC":"ASC")}`)}h.push(t`${t.identifier(m)} ASC`);const _=[];typeof n.partitionKey=="string"?_.push(t`${t.identifier("__partition__")} = ${n.partitionKey}`):R&&_.push(t`${t.identifier("__partition__")} = ${H(r.partitionBy??[],R)}`);const B=G(n),k=U(B,u,r.sortBy);k&&_.push(k);const I=t.identifier(m),N=t.identifier("__partition__"),M=_.length>0?t` WHERE ${t.join(_,t` AND `)}`:t``,D=u.length>0?t`${I}, ${N}, ${t.join(u.map(p=>t.identifier(p)),t`, `)}`:t`${I}, ${N}`,K=t`SELECT ${D} FROM ${t.identifier($)}${M} ORDER BY ${t.join(h,t`, `)} LIMIT ${t.raw(String(l+1))}`,y=C(o.sql,K).toArray(),g=y.length>l,w=g?y.slice(0,l):y,L=w.map(p=>p[m]),b=Z(w,Q(o,i,L),u),j=g?X(w.at(-1),u):S,P=r.sortBy.map(p=>p.direction==="desc"?"desc":"asc");return{continueCursor:j,directions:P,hasMore:g,rows:b}};export{ct as computeRankPage,Q as hydrateDocsById};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{u as ee,T as G,l as ne,y as ie,c as oe}from"./FTS_COUNT_COLUMN-D1gY3wwZ-CZHdaRrd.mjs";import"@lunora/errors";import{sql as e}from"drizzle-orm";import{matchesStaticWhere as U,aggregateSqlFunction as te}from"./AGGREGATE_SQL_FUNCTION-QYaiuty4.mjs";import{encodeAggregateKey as b,foldAggregateTally as re,aggregateTableName as H,coerceAggregateNumber as B}from"./aggregateTableName-G-eXyjcz.mjs";import{runDrizzle as l}from"./runDrizzle-GKR3y97k.mjs";import{isFtsAvailable as ae,DOC_COLUMN as V,rowToDocument as K,AGG_KEY as R,AGG_VALUE as g,AGG_COUNT as m,geoTableName as se,aggUpsertSql as x,jsonPathSql as O}from"./AGG_COUNT-BWXe3gtQ.mjs";import{param as P}from"./param-B5lF5Jd9.mjs";import{encodeGeohash as $e,GEO_DEFAULT_PRECISION as ce}from"./GEO_DEFAULT_PRECISION-okRCkZ6r.mjs";import{sortColumnName as z,matchesRankStaticWhere as J,encodePartitionKey as X,rankTableName as Y}from"./RANK_TIEBREAK-9NU5s_mi.mjs";import{serializeSqlValue as M}from"./serializeSqlValue-DnpyaLcw.mjs";const fe=(y,I,h)=>[...y.partitionBy??[],...y.sortBy.map(T=>T.field),...y.where?Object.keys(y.where):[]].every(T=>I[T]===h[T]),le=(y,I,h,T,L,_)=>{if(L&&_&&fe(h,L,_))return;const s=Y(I,h.name);if(L&&l(y,e`DELETE FROM ${e.identifier(s)} WHERE ${e.identifier("__id__")} = ${T}`),!_||h.where&&!J(_,h.where))return;const N=h.sortBy.map((S,F)=>z(F)),v=e.join(["__id__","__partition__",...N].map(S=>e.identifier(S)),e`, `),C=X(h.partitionBy??[],_),w=h.sortBy.map(S=>M(_[S.field]??null)),D=e.join([T,C,...w].map(S=>P(S)),e`, `);l(y,e`INSERT INTO ${e.identifier(s)} (${v}) VALUES (${D})`)},Ae=y=>{const{broadcast:I,indexKeysFor:h,invalidateCache:T,recordCdc:L,schema:_,sql:s}=y,N=new Set,v=new Set,C=(i,n)=>{const o=`${i}::${n.name}`;if(N.has(o))return;const c=H(i,n.name),r=n.by??[],d=new Map,f=l(s,e`SELECT id, _creationTime, ${e.identifier(V)} FROM ${e.identifier(i)}`).toArray();for(const $ of f){const t=K($);if(!t||n.where&&!U(t,n.where))continue;const E=b(r,t);re(d,E,n,t)}l(s,e`DELETE FROM ${e.identifier(c)}`);const p=32,a=[...d];for(let $=0;$<a.length;$+=p){const t=a.slice($,$+p),E=e.join(t.map(([u,A])=>e`(${u}, ${A.value}, ${A.count})`),e`, `);l(s,e`INSERT INTO ${e.identifier(c)} (${R}, ${g}, ${m}) VALUES ${E}`)}N.add(o)},w=(i,n,o)=>{const c=n.by??[],r=te(n.op),d=n.field??"",f=[];for(const $ of c){const t=M(o[$]??null);t===null?f.push(e`${O($)} IS NULL`):f.push(e`${O($)} = ${t}`)}for(const[$,t]of Object.entries(n.where??{})){const E=t!==null&&typeof t=="object"&&!Array.isArray(t)?t.eq:t,u=M(E);u===null?f.push(e`${O($)} IS NULL`):f.push(e`${O($)} = ${u}`)}const p=f.length>0?e` WHERE ${e.join(f,e` AND `)}`:e``,a=O(d);return{value:l(s,e`SELECT ${e.raw(r)}(${a}) AS value FROM ${e.identifier(i)}${p}`).one().value??null}},D=(i,n,o,c)=>{const r=H(i,n.name),{op:d}=n,f=n.field??"",p=t=>{l(s,e`DELETE FROM ${e.identifier(r)} WHERE ${R} = ${t} AND ${m} <= 0`)},a=o&&(!n.where||U(o,n.where))?o:void 0,$=c&&(!n.where||U(c,n.where))?c:void 0;if(!(!a&&!$)){if(d==="count"){for(const[t,E]of[[a,-1],[$,1]]){if(!t)continue;const u=b(n.by??[],t);l(s,x(r,u,E,E,e`${g} = ${g} + excluded.${g}, ${m} = ${m} + excluded.${m}`))}a&&p(b(n.by??[],a));return}if(d==="sum"||d==="avg"){for(const[t,E]of[[a,-1],[$,1]]){if(!t)continue;const u=B(t[f]);if(u===void 0)continue;const A=b(n.by??[],t);l(s,x(r,A,E*u,E,e`${g} = COALESCE(${g}, 0) + excluded.${g}, ${m} = ${m} + excluded.${m}`))}a&&p(b(n.by??[],a));return}if(a){const t=b(n.by??[],a),E=B(a[f]),u=l(s,e`SELECT ${g} AS value, ${m} AS count FROM ${e.identifier(r)} WHERE ${R} = ${t}`).toArray()[0],A=(u?.count??0)-1;if(A<=0)l(s,e`DELETE FROM ${e.identifier(r)} WHERE ${R} = ${t}`);else if(u&&E!==void 0&&u.value!==null&&E===u.value){const Q=w(i,n,a);l(s,e`UPDATE ${e.identifier(r)} SET ${g} = ${Q.value}, ${m} = ${A} WHERE ${R} = ${t}`)}else l(s,e`UPDATE ${e.identifier(r)} SET ${m} = ${m} - 1 WHERE ${R} = ${t}`)}if($){const t=b(n.by??[],$),E=B($[f]);if(E===void 0)l(s,x(r,t,null,1,e`${m} = ${m} + 1`));else{const u=d==="min"?"MIN":"MAX";l(s,x(r,t,E,1,e`${g} = ${e.raw(u)}(COALESCE(${g}, excluded.${g}), excluded.${g}), ${m} = ${m} + 1`))}}}},S=i=>{const n=_.tables[i]?.aggregateIndexes;if(!(!n||n.length===0))for(const o of n)C(i,o)},F=(i,n,o)=>{const c=_.tables[i]?.aggregateIndexes;if(!(!c||c.length===0))for(const r of c)D(i,r,n,o)},j=(i,n)=>{const o=`${i}::rank::${n.name}`;if(v.has(o))return;const c=Y(i,n.name),r=l(s,e`SELECT id, _creationTime, ${e.identifier(V)} FROM ${e.identifier(i)}`).toArray();l(s,e`DELETE FROM ${e.identifier(c)}`);const d=n.sortBy.map((p,a)=>z(a)),f=e.join(["__id__","__partition__",...d].map(p=>e.identifier(p)),e`, `);for(const p of r){const a=K(p);if(!a||n.where&&!J(a,n.where))continue;const $=X(n.partitionBy??[],a),t=n.sortBy.map(u=>M(a[u.field]??null)),E=e.join([a._id,$,...t].map(u=>P(u)),e`, `);l(s,e`INSERT INTO ${e.identifier(c)} (${f}) VALUES (${E})`)}v.add(o)},Z=i=>{const n=_.tables[i]?.rankIndexes;if(!(!n||n.length===0))for(const o of n)j(i,o)},W=(i,n,o,c)=>{const r=_.tables[i]?.rankIndexes;if(!(!r||r.length===0))for(const d of r)le(s,i,d,n,o,c)},k=(i,n,o,c)=>{const r=_.tables[i]?.searchIndexes;if(!(!r||r.length===0||!ae(s)))for(const d of r){if(ee(c,o,d))continue;const f=oe(i,d.name);l(s,e`DELETE FROM ${e.identifier(f)} WHERE ${e.identifier(G)} = ${n}`),o&&l(s,e`INSERT INTO ${e.identifier(f)} (${e.identifier(ne)}, ${e.identifier(G)}) VALUES (${ie(o,d)}, ${n})`)}},q=(i,n,o)=>{const c=_.tables[i]?.geoIndexes;if(!(!c||c.length===0))for(const r of c){const d=se(i,r.name);l(s,e`DELETE FROM ${e.identifier(d)} WHERE ${e.identifier("__id__")} = ${n}`);const f=o?.[r.field];if(f!==null&&typeof f=="object"&&typeof f.lat=="number"&&typeof f.lng=="number"){const{lat:p,lng:a}=f,$=$e({lat:p,lng:a},r.precision??ce);l(s,e`INSERT INTO ${e.identifier(d)} (${e.identifier("__id__")}, ${e.identifier("__geohash__")}, ${e.identifier("__lat__")}, ${e.identifier("__lng__")}) VALUES (${n}, ${$}, ${p}, ${a})`)}}};return{ensureBackfilledForTable:S,ensureBackfilledIndex:C,ensureRankBackfilled:j,ensureRankBackfilledForTable:Z,syncAggregates:F,syncCompanionsForInsert:(i,n,o)=>{k(i,n,o),q(i,n,o),F(i,void 0,o),W(i,n,void 0,o),T(i,n,o),L(i,n,"insert",o),I({indexKeys:h(i,o),key:n,op:"insert",row:o,table:i})},syncGeo:q,syncRanks:W,syncSearch:k}};export{Ae as createCompanionSync};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
const d=()=>{const a=new Set,t=new Map,n=new Set;return{onRead(e){a.add(e),n.add(e)},onReadRange(e){a.add(e.table);const o=t.get(e.table);o?o.push(e):t.set(e.table,[e])},ranges(){for(const e of n)t.delete(e);return t.size>0?t:void 0},tables:a}};export{d as createReadFootprint};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as c}from"@lunora/errors";const d=t=>{const e={args:t.args??{},enqueuedAt:typeof t.enqueuedAt=="number"?t.enqueuedAt:0,functionPath:typeof t.functionPath=="string"?t.functionPath:"",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.shardKey=="string"&&(e.shardKey=t.shardKey),e},i=t=>{const e={key:typeof t.key=="string"?t.key:"",size:typeof t.size=="number"?t.size:0},s=t.httpMetadata?.contentType??t.contentType;typeof s=="string"&&(e.contentType=s),t.customMetadata&&typeof t.customMetadata=="object"&&(e.customMetadata=t.customMetadata),typeof t.sha256=="string"&&(e.sha256=t.sha256);const{uploaded:r}=t;return typeof r=="number"?e.uploaded=r:r instanceof Date&&(e.uploaded=r.getTime()),e},f=(t={})=>{const e=()=>{if(!t.scheduler)throw new c("INTERNAL",'ctx.db.system.query("_scheduled_functions"): no scheduler configured. Pass `scheduler` to createShardDO().');return t.scheduler},s=()=>{if(!t.storage)throw new c("INTERNAL",'ctx.db.system.query("_storage"): no storage configured. Pass `storage` to createShardDO().');return t.storage},r=async()=>(await e().list()).map(a=>d(a)),y=async()=>{const{objects:a}=await s().list();return a.map(n=>i(n))};return{get:(async(a,n)=>{if(a==="_scheduled_functions"){const u=await e().get(n);return u?d(u):null}const o=await s().getMetadata(n);return o?i(o):null}),query:(a=>a==="_scheduled_functions"?{collect:r}:{collect:y})}};export{f as createSystemReader};
|