@lunora/shard-engine 1.0.0-alpha.94 → 1.0.0-alpha.96

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/dist/conformance/index.mjs +1 -1
  2. package/dist/index.d.mts +27 -33
  3. package/dist/index.d.ts +27 -33
  4. package/dist/index.mjs +1 -1
  5. package/dist/packem_shared/{ADMIN_FUNCTIONS-DE3r3jrY.mjs → ADMIN_FUNCTIONS-D5mzmLFo.mjs} +1 -1
  6. package/dist/packem_shared/{AGG_COUNT-DaRHrce8.mjs → AGG_COUNT-DNnEXtyM.mjs} +1 -1
  7. package/dist/packem_shared/{AUDIT_LOG_TABLE-CMhmmmgR.mjs → AUDIT_LOG_TABLE-CZNxCRLv.mjs} +1 -1
  8. package/dist/packem_shared/{CDC_LOG_TABLE-Bkv7JskR.mjs → CDC_LOG_TABLE-QaBxSIZM.mjs} +1 -1
  9. package/dist/packem_shared/{CLIENT_WATERMARK_TABLE-DPY-NtOH.mjs → CLIENT_WATERMARK_TABLE-vLjfNhBR.mjs} +1 -1
  10. package/dist/packem_shared/{COMMIT_SEQ_FIELD-6lGDFLgk.mjs → COMMIT_SEQ_FIELD-BY_vc9bw.mjs} +1 -1
  11. package/dist/packem_shared/{CURSOR_PREFIX-Bn8SFoGd.mjs → CURSOR_PREFIX-BX8jkMJa.mjs} +1 -1
  12. package/dist/packem_shared/{DATA_MIGRATION_STATE_TABLE-mUH4b2lA.mjs → DATA_MIGRATION_STATE_TABLE-BMbxLEaN.mjs} +1 -1
  13. package/dist/packem_shared/{DEFAULT_MAX_RELATION_KEYS-B1zeutIo.mjs → DEFAULT_MAX_RELATION_KEYS-CYPZfQH9.mjs} +1 -1
  14. package/dist/packem_shared/{DEFAULT_MAX_RELAYS-CSb6oGUZ.mjs → DEFAULT_MAX_RELAYS-hdowkC2x.mjs} +1 -1
  15. package/dist/packem_shared/{DEFAULT_PROMOTION_THRESHOLDS-Bfx7KakS.mjs → DEFAULT_PROMOTION_THRESHOLDS-91RH_llq.mjs} +1 -1
  16. package/dist/packem_shared/{DurableStreamRunner-k4x__lMt.mjs → DurableStreamRunner-Dk9Pn-B8.mjs} +1 -1
  17. package/dist/packem_shared/{GLOBAL_SHAPE_SNAPSHOT_TABLE-BpFE-qYL.mjs → GLOBAL_SHAPE_SNAPSHOT_TABLE-pMxZ-obU.mjs} +1 -1
  18. package/dist/packem_shared/{IDEMPOTENCY_TABLE-CUc9L-o_.mjs → IDEMPOTENCY_TABLE-AOJCuq5U.mjs} +1 -1
  19. package/dist/packem_shared/{MAIL_RETENTION-kYNWpCbY.mjs → MAIL_RETENTION-BxAGL3hK.mjs} +1 -1
  20. package/dist/packem_shared/NotUniqueError-D4EV8EzO.mjs +1 -0
  21. package/dist/packem_shared/{QUEUE_TABLE-D-5_s2hl.mjs → QUEUE_TABLE-DKANxmEZ.mjs} +1 -1
  22. package/dist/packem_shared/{REACTOR_STATE_TABLE-XAIYdVL0.mjs → REACTOR_STATE_TABLE-B8IehLv8.mjs} +1 -1
  23. package/dist/packem_shared/{RELATED_DEFAULT_LIMIT-B9PH28Pn.mjs → RELATED_DEFAULT_LIMIT-CBYQQIrZ.mjs} +1 -1
  24. package/dist/packem_shared/{RLS_UNWRAP_SYMBOL-BwwTbz3Q.mjs → RLS_UNWRAP_SYMBOL-rSxYzw-G.mjs} +1 -1
  25. package/dist/packem_shared/{SCHEDULE_OUTBOX_TABLE-wAAIitt2.mjs → SCHEDULE_OUTBOX_TABLE-CgLvGxpY.mjs} +1 -1
  26. package/dist/packem_shared/{SCHEMA_HISTORY_MAX_VERSIONS-CYVBglZe.mjs → SCHEMA_HISTORY_MAX_VERSIONS-BMcUIqBY.mjs} +1 -1
  27. package/dist/packem_shared/{SEARCH_STATE_TABLE-BlVsBsix.mjs → SEARCH_STATE_TABLE-wgl-SePe.mjs} +1 -1
  28. package/dist/packem_shared/{SHAPE_POKE_CURSOR_TABLE-BVskv7ei.mjs → SHAPE_POKE_CURSOR_TABLE-cn0stGAL.mjs} +1 -1
  29. package/dist/packem_shared/{VECTOR_BACKFILL_MAX_PAGES-TviV2Xnr.mjs → VECTOR_BACKFILL_MAX_PAGES-B2ZWxshy.mjs} +1 -1
  30. package/dist/packem_shared/WORKERD_SQLITE_LIMITS-DBH23L_S.mjs +1 -0
  31. package/dist/packem_shared/appendStreamChunk-7ZyAZGg_.mjs +17 -0
  32. package/dist/packem_shared/{applyOnDelete-7JZ4vR9r.mjs → applyOnDelete-DJsOG8tz.mjs} +1 -1
  33. package/dist/packem_shared/{archiveCdcSegment-CMAVUCck.mjs → archiveCdcSegment-BON69Nug.mjs} +1 -1
  34. package/dist/packem_shared/{backfillAggregateIndexes-DBY2H269.mjs → backfillAggregateIndexes-B_3xdOgV.mjs} +1 -1
  35. package/dist/packem_shared/{buildReprojectionMigration-Do3UTuDO.mjs → buildReprojectionMigration-IMrfRdvU.mjs} +1 -1
  36. package/dist/packem_shared/{buildSettings-DC3VeQ0H.mjs → buildSettings-BRkZd6_E.mjs} +1 -1
  37. package/dist/packem_shared/{buildShapeDiff-B5YzZbjX.mjs → buildShapeDiff-D-J_GmC1.mjs} +1 -1
  38. package/dist/packem_shared/{clearMemoryTables-BCDG0X9P.mjs → clearMemoryTables-CogAvVHR.mjs} +1 -1
  39. package/dist/packem_shared/compileWhereSql-DLfUbHc-.mjs +1 -0
  40. package/dist/packem_shared/{computeRankPage-BEyDlhws.mjs → computeRankPage-3AiKfT8q.mjs} +1 -1
  41. package/dist/packem_shared/{createCompanionSync-uTsHTJWE.mjs → createCompanionSync-Rjn0lsT6.mjs} +1 -1
  42. package/dist/packem_shared/createReplicaLink-Z82FMxvY.mjs +7 -0
  43. package/dist/packem_shared/{ctx-db-relay-shapes-DBRHlvNu.mjs → ctx-db-relay-shapes-DuqhDLw8.mjs} +1 -1
  44. package/dist/packem_shared/{ctx-db-search-state-z0OqNIGe.mjs → ctx-db-search-state-DVCp4JQf.mjs} +1 -1
  45. package/dist/packem_shared/{defineEngineContractSuite-Dsx4iWIy.mjs → defineEngineContractSuite-BkVGn8QW.mjs} +1 -1
  46. package/dist/packem_shared/{do-sql-DpyjVz_6.mjs → do-sql-BEFrJUds.mjs} +1 -1
  47. package/dist/packem_shared/{exportShardRows-BFpaZI99.mjs → exportShardRows-CTDgQEF8.mjs} +1 -1
  48. package/dist/packem_shared/{fts-companion-DcGBHZiM.mjs → fts-companion-pUdD6kF-.mjs} +1 -1
  49. package/dist/packem_shared/{ftsCompanionDdl-BaLv81YG.mjs → ftsCompanionDdl-Co6WSyCB.mjs} +1 -1
  50. package/dist/packem_shared/{isSoftDeleted-LAXWNkhC.mjs → isSoftDeleted-sGRSPPQq.mjs} +1 -1
  51. package/dist/packem_shared/{materializeExternalRows-CTCrmga8.mjs → materializeExternalRows-DhINQHwd.mjs} +1 -1
  52. package/dist/packem_shared/{runDrizzle-BlpM0R9P.mjs → runDrizzle-Du5HLitO.mjs} +1 -1
  53. package/dist/packem_shared/{runShardMigrations-BtAyuuJb.mjs → runShardMigrations-MXioI81k.mjs} +1 -1
  54. package/dist/packem_shared/{selectExpiredIds-BVZtw3Wb.mjs → selectExpiredIds-DQg6v5Uf.mjs} +1 -1
  55. package/dist/packem_shared/{selectShapeMembers-DTA3YUf4.mjs → selectShapeMembers-BXhvEt4X.mjs} +1 -1
  56. package/dist/packem_shared/where-sql-DFs8Zw7-.mjs +1 -0
  57. package/package.json +2 -2
  58. package/dist/packem_shared/NotUniqueError-Cnw4ctAu.mjs +0 -1
  59. package/dist/packem_shared/WORKERD_SQLITE_LIMITS-DlozcSQu.mjs +0 -1
  60. package/dist/packem_shared/appendStreamChunk-BRwBOTEN.mjs +0 -19
  61. package/dist/packem_shared/compileWhereSql-Bi04r4ut.mjs +0 -1
  62. package/dist/packem_shared/createReplicaLink-D_kkf5IG.mjs +0 -7
  63. package/dist/packem_shared/where-sql-BV8Kg4_B.mjs +0 -1
@@ -1 +1 @@
1
- import{LunoraError as u}from"@lunora/errors";import{i as v,R as N}from"./relation-operators-BEg-CvCH.mjs";import{isMemoryTable as y}from"./clearMemoryTables-BCDG0X9P.mjs";import{distinctValues as $}from"./applyOnDelete-7JZ4vR9r.mjs";import{RELATION_EXISTS_KEY as j}from"./RELATION_EXISTS_KEY-CFUhnZSZ.mjs";const E={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}},O=e=>N.has(e)?e:void 0,R=e=>{const t=O(e),r=t===void 0?void 0:E[t];if(!r)throw new u("INTERNAL",`unknown relation operator "${e}"`);return r},S=e=>e.kind==="one"?{clause:e.field,project:e.references}:{clause:e.references,project:e.field},M=5e3,h=Symbol("relation-key-overflow"),m=e=>Array.isArray(e)?e.map(t=>t??{}):[],w=e=>{if(e.length===1){const[t]=e;return t??{}}return e.length===0?{}:{AND:e}},b=e=>v(e),l=(e,t,r)=>{const n=t.tables[r]?.relationMap??{};return Object.keys(e).some(s=>{const a=e[s];return s==="AND"||s==="OR"?m(a).some(o=>l(o,t,r)):s==="NOT"?l(a??{},t,r):!!n[s]&&b(a)})},H=(e,t,r,n)=>{if(e&&l(e,t,r))throw new u("INTERNAL",`relation-crossing predicates are not supported in ${n}() — use them in findMany/findFirst or an RLS read policy`)},L=async(e,t,r,n,s)=>{const a=await d(t,e.table,n),{page:o}=await n.fetcher(e.table,{baseWhere:n.relationBaseWhere?.(e.table),relationBaseWhere:n.relationBaseWhere,where:a}),i=$(o,r);if(i.length>n.maxRelationKeys){if(s)return h;throw new u("INTERNAL",`relation predicate on "${e.table}" matched ${String(i.length)} rows, exceeding the ${String(n.maxRelationKeys)}-key limit; narrow the predicate (a same-shard EXISTS push-down lifts this cap)`)}return i},P=async(e,t,r,n,s)=>{const a=R(e),{clause:o,project:i}=S(t),c=await L(t,a.negateChild?{NOT:r}:r,i,n,s);return c===h?h:a.negated?a.nullDisjunct?{OR:[{[o]:{notIn:c}},{[o]:{isNull:!0}}]}:{[o]:{notIn:c}}:{[o]:{in:c}}},p=async(e,t,r,n,s)=>{const a=R(e),o=s.relationBaseWhere?.(t.table),i=a.negateChild?{NOT:r}:r,T={childWhere:await d(o?{AND:[o,i]}:i,t.table,s),negated:a.negated,parentTable:n,relation:t};return{[j]:T}},_=(e,t,r)=>{const n=O(e),s=n===void 0?void 0:E[n];if(s&&s.kind!==r.kind)throw new u("INTERNAL",`relation operator "${e}" requires a to-${s.kind} relation, but "${t}" is to-${r.kind}`)},k=async(e,t,r,n,s)=>{const a=[];for(const o of Object.keys(r)){_(o,e,t);const i=r[o]??{},c=s.canPushExists?.(t)??!1;if(c&&s.existsPushMode==="always"){a.push(await p(o,t,i,n,s));continue}const f=await P(o,t,i,s,c);f===h?a.push(await p(o,t,i,n,s)):a.push(f)}return w(a)},I=async(e,t,r,n)=>{if(e==="AND"||e==="OR"){const a=[];for(const o of m(t))a.push(await d(o,r,n));return{[e]:a}}if(e==="NOT")return{NOT:await d(t??{},r,n)};const s=n.schema.tables[r]?.relationMap?.[e];return s&&b(t)?k(e,s,t,r,n):{[e]:t}},d=async(e,t,r)=>{const n=[];for(const s of Object.keys(e))n.push(await I(s,e[s],t,r));return w(n)},Y=async(e,t)=>!e||!l(e,t.schema,t.tableName)?e:d(e,t.tableName,{canPushExists:t.canPushExists,existsPushMode:t.existsPushMode??"auto",fetcher:t.fetcher,maxRelationKeys:t.maxRelationKeys??M,relationBaseWhere:t.relationBaseWhere,schema:t.schema}),g=(e,t,r)=>{for(const n of e){const s=A(n,t,r);if(s)return s}},D=(e,t,r,n)=>{if(e==="AND"||e==="OR")return g(m(t),r,n);if(e==="NOT")return g([t??{}],r,n);const s=r.tables[n]?.relationMap?.[e];if(!(!s||!b(t)))return r.tables[s.table]?.shardMode?.kind==="shardBy"?{kind:"shard",relation:e,target:s.table}:y(r.tables[s.table])?{kind:"memory",relation:e,target:s.table}:g(Object.values(t),r,s.table)},A=(e,t,r)=>{for(const n of Object.keys(e)){const s=D(n,e[n],t,r);if(s)return s}},q=(e,t,r)=>{if(y(t.tables[r]))throw Object.assign(new Error(`shape on "${r}" replicates from the changelog, which never records a .memory() table — the shape would seed once and never update again. Fix it by (a) dropping .memory() from "${r}" so its writes reach the changelog, or (b) reading it through a live query (\`useQuery\`), which refreshes off the changed-table set rather than the log.`),{code:"SHAPE_MEMORY_TABLE",name:"LunoraError",status:400});if(!e)return;const n=A(e,t,r);if(n)throw n.kind==="memory"?Object.assign(new Error(`shape on "${r}" joins the .memory() table "${n.target}" via relation "${n.relation}" — writes to a .memory() table never reach the changelog, so the shape is never told its membership changed and would serve stale rows indefinitely. Fix it by (a) dropping .memory() from "${n.target}", or (b) reading it through a live query (\`useQuery\`), which refreshes off the changed-table set rather than the log.`),{code:"SHAPE_MEMORY_TABLE",name:"LunoraError",status:400}):Object.assign(new Error(`shape on "${r}" joins the sharded table "${n.target}" via relation "${n.relation}" — a live shape cannot replicate rows that live in another shard's Durable Object. Fix it by (a) denormalizing the joined columns into "${r}", or (b) moving "${n.target}" to .global() so it is served through the latency-tiered D1 shape tier.`),{code:"SHAPE_CROSS_SHARD_JOIN",name:"LunoraError",status:400})};export{M as DEFAULT_MAX_RELATION_KEYS,H as assertFlatPredicate,q as assertShapeShardable,l as containsRelationPredicate,b as isRelationPredicate,Y as resolveRelationPredicates};
1
+ import{LunoraError as u}from"@lunora/errors";import{i as v,R as N}from"./relation-operators-BEg-CvCH.mjs";import{isMemoryTable as y}from"./clearMemoryTables-CogAvVHR.mjs";import{distinctValues as $}from"./applyOnDelete-DJsOG8tz.mjs";import{RELATION_EXISTS_KEY as j}from"./RELATION_EXISTS_KEY-CFUhnZSZ.mjs";const E={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}},O=e=>N.has(e)?e:void 0,R=e=>{const t=O(e),r=t===void 0?void 0:E[t];if(!r)throw new u("INTERNAL",`unknown relation operator "${e}"`);return r},S=e=>e.kind==="one"?{clause:e.field,project:e.references}:{clause:e.references,project:e.field},M=5e3,h=Symbol("relation-key-overflow"),m=e=>Array.isArray(e)?e.map(t=>t??{}):[],w=e=>{if(e.length===1){const[t]=e;return t??{}}return e.length===0?{}:{AND:e}},b=e=>v(e),l=(e,t,r)=>{const n=t.tables[r]?.relationMap??{};return Object.keys(e).some(s=>{const a=e[s];return s==="AND"||s==="OR"?m(a).some(o=>l(o,t,r)):s==="NOT"?l(a??{},t,r):!!n[s]&&b(a)})},H=(e,t,r,n)=>{if(e&&l(e,t,r))throw new u("INTERNAL",`relation-crossing predicates are not supported in ${n}() — use them in findMany/findFirst or an RLS read policy`)},L=async(e,t,r,n,s)=>{const a=await d(t,e.table,n),{page:o}=await n.fetcher(e.table,{baseWhere:n.relationBaseWhere?.(e.table),relationBaseWhere:n.relationBaseWhere,where:a}),i=$(o,r);if(i.length>n.maxRelationKeys){if(s)return h;throw new u("INTERNAL",`relation predicate on "${e.table}" matched ${String(i.length)} rows, exceeding the ${String(n.maxRelationKeys)}-key limit; narrow the predicate (a same-shard EXISTS push-down lifts this cap)`)}return i},P=async(e,t,r,n,s)=>{const a=R(e),{clause:o,project:i}=S(t),c=await L(t,a.negateChild?{NOT:r}:r,i,n,s);return c===h?h:a.negated?a.nullDisjunct?{OR:[{[o]:{notIn:c}},{[o]:{isNull:!0}}]}:{[o]:{notIn:c}}:{[o]:{in:c}}},p=async(e,t,r,n,s)=>{const a=R(e),o=s.relationBaseWhere?.(t.table),i=a.negateChild?{NOT:r}:r,T={childWhere:await d(o?{AND:[o,i]}:i,t.table,s),negated:a.negated,parentTable:n,relation:t};return{[j]:T}},_=(e,t,r)=>{const n=O(e),s=n===void 0?void 0:E[n];if(s&&s.kind!==r.kind)throw new u("INTERNAL",`relation operator "${e}" requires a to-${s.kind} relation, but "${t}" is to-${r.kind}`)},k=async(e,t,r,n,s)=>{const a=[];for(const o of Object.keys(r)){_(o,e,t);const i=r[o]??{},c=s.canPushExists?.(t)??!1;if(c&&s.existsPushMode==="always"){a.push(await p(o,t,i,n,s));continue}const f=await P(o,t,i,s,c);f===h?a.push(await p(o,t,i,n,s)):a.push(f)}return w(a)},I=async(e,t,r,n)=>{if(e==="AND"||e==="OR"){const a=[];for(const o of m(t))a.push(await d(o,r,n));return{[e]:a}}if(e==="NOT")return{NOT:await d(t??{},r,n)};const s=n.schema.tables[r]?.relationMap?.[e];return s&&b(t)?k(e,s,t,r,n):{[e]:t}},d=async(e,t,r)=>{const n=[];for(const s of Object.keys(e))n.push(await I(s,e[s],t,r));return w(n)},Y=async(e,t)=>!e||!l(e,t.schema,t.tableName)?e:d(e,t.tableName,{canPushExists:t.canPushExists,existsPushMode:t.existsPushMode??"auto",fetcher:t.fetcher,maxRelationKeys:t.maxRelationKeys??M,relationBaseWhere:t.relationBaseWhere,schema:t.schema}),g=(e,t,r)=>{for(const n of e){const s=A(n,t,r);if(s)return s}},D=(e,t,r,n)=>{if(e==="AND"||e==="OR")return g(m(t),r,n);if(e==="NOT")return g([t??{}],r,n);const s=r.tables[n]?.relationMap?.[e];if(!(!s||!b(t)))return r.tables[s.table]?.shardMode?.kind==="shardBy"?{kind:"shard",relation:e,target:s.table}:y(r.tables[s.table])?{kind:"memory",relation:e,target:s.table}:g(Object.values(t),r,s.table)},A=(e,t,r)=>{for(const n of Object.keys(e)){const s=D(n,e[n],t,r);if(s)return s}},q=(e,t,r)=>{if(y(t.tables[r]))throw Object.assign(new Error(`shape on "${r}" replicates from the changelog, which never records a .memory() table — the shape would seed once and never update again. Fix it by (a) dropping .memory() from "${r}" so its writes reach the changelog, or (b) reading it through a live query (\`useQuery\`), which refreshes off the changed-table set rather than the log.`),{code:"SHAPE_MEMORY_TABLE",name:"LunoraError",status:400});if(!e)return;const n=A(e,t,r);if(n)throw n.kind==="memory"?Object.assign(new Error(`shape on "${r}" joins the .memory() table "${n.target}" via relation "${n.relation}" — writes to a .memory() table never reach the changelog, so the shape is never told its membership changed and would serve stale rows indefinitely. Fix it by (a) dropping .memory() from "${n.target}", or (b) reading it through a live query (\`useQuery\`), which refreshes off the changed-table set rather than the log.`),{code:"SHAPE_MEMORY_TABLE",name:"LunoraError",status:400}):Object.assign(new Error(`shape on "${r}" joins the sharded table "${n.target}" via relation "${n.relation}" — a live shape cannot replicate rows that live in another shard's Durable Object. Fix it by (a) denormalizing the joined columns into "${r}", or (b) moving "${n.target}" to .global() so it is served through the latency-tiered D1 shape tier.`),{code:"SHAPE_CROSS_SHARD_JOIN",name:"LunoraError",status:400})};export{M as DEFAULT_MAX_RELATION_KEYS,H as assertFlatPredicate,q as assertShapeShardable,l as containsRelationPredicate,b as isRelationPredicate,Y as resolveRelationPredicates};
@@ -1,4 +1,4 @@
1
- import{toErrorBody as k,LunoraError as D}from"@lunora/errors";import{e as N,d as v}from"./wire-codec-C-FpWm52.mjs";import{sql as y}from"drizzle-orm";import{runDrizzle as m}from"./runDrizzle-BlpM0R9P.mjs";import{WORKERD_SQLITE_LIMITS as F}from"./WORKERD_SQLITE_LIMITS-DlozcSQu.mjs";import{d as U,w,a as A,m as $,r as K,b as Y,c as W}from"./ctx-db-relay-shapes-DBRHlvNu.mjs";import{envPositiveInt as g}from"./envOptionalPositiveInt-D2pY-c64.mjs";import{relayName as R,DEFAULT_PROMOTION_THRESHOLDS as T,nextPromotionState as B,shapeRoutingKey as _,relayProxyKey as M,parseRelayName as H,clampPromotionThresholds as q}from"./DEFAULT_PROMOTION_THRESHOLDS-Bfx7KakS.mjs";import{encodeRowsPatch as X,buildPokeFrames as O}from"./buildPokeFrames-BBE6J91z.mjs";import{v as j,R as L,s as z,a as G,b as J}from"./sibling-channel-BkL5cTCc.mjs";import{awaitWsDrain as V,trySendFrame as x}from"./awaitWsDrain-apizgmKY.mjs";import{stableWireKey as b}from"./stableWireKey-D2US4k_J.mjs";const f="__lunora_relay_memos",Q=i=>{m(i,y`CREATE TABLE IF NOT EXISTS ${y.identifier(f)} (
1
+ import{toErrorBody as k,LunoraError as D}from"@lunora/errors";import{e as N,d as v}from"./wire-codec-C-FpWm52.mjs";import{sql as y}from"drizzle-orm";import{runDrizzle as m}from"./runDrizzle-Du5HLitO.mjs";import{WORKERD_SQLITE_LIMITS as F}from"./WORKERD_SQLITE_LIMITS-DBH23L_S.mjs";import{d as U,w,a as A,m as $,r as K,b as Y,c as W}from"./ctx-db-relay-shapes-DuqhDLw8.mjs";import{envPositiveInt as g}from"./envOptionalPositiveInt-D2pY-c64.mjs";import{relayName as R,DEFAULT_PROMOTION_THRESHOLDS as T,nextPromotionState as B,shapeRoutingKey as _,relayProxyKey as M,parseRelayName as H,clampPromotionThresholds as q}from"./DEFAULT_PROMOTION_THRESHOLDS-91RH_llq.mjs";import{encodeRowsPatch as X,buildPokeFrames as O}from"./buildPokeFrames-BBE6J91z.mjs";import{v as j,R as L,s as z,a as G,b as J}from"./sibling-channel-BkL5cTCc.mjs";import{awaitWsDrain as V,trySendFrame as x}from"./awaitWsDrain-apizgmKY.mjs";import{stableWireKey as b}from"./stableWireKey-D2US4k_J.mjs";const f="__lunora_relay_memos",Q=i=>{m(i,y`CREATE TABLE IF NOT EXISTS ${y.identifier(f)} (
2
2
  connection_id TEXT NOT NULL,
3
3
  sub_id TEXT NOT NULL,
4
4
  cursor INTEGER NOT NULL,
@@ -1 +1 @@
1
- import{LunoraError as m}from"@lunora/errors";import{stableWireKey as a}from"./stableWireKey-D2US4k_J.mjs";const i="::relay::",w=(t,n)=>`${t}${i}${String(n)}`,f=t=>{const n=t.lastIndexOf(i);if(n===-1)return;const o=t.slice(0,n),e=t.slice(n+i.length),r=Number(e);if(!(o.length===0||!Number.isInteger(r)||r<0||String(r)!==e))return{ownerKey:o,relayIndex:r}},l=(t,n)=>a({args:n??{},name:t}),d=(t,n,o)=>`${String(t)}:${n}:${o}`,c={tDown:4e3,tUp:8e3},g=(t,n,o=c)=>{if(o.tDown>=o.tUp)throw new m("INTERNAL",`invalid promotion thresholds: tDown (${String(o.tDown)}) must be < tUp (${String(o.tUp)})`);return t==="owned"?n>=o.tUp?"promoted":"owned":n<o.tDown?"owned":"promoted"},x=(t,n)=>n<t?{tDown:n,tUp:t}:{tDown:Math.min(Math.max(1,Math.floor(t/2)),t-1),tUp:t},N=(t,n,o)=>{if(t<=n||n<=0)return 0;const e=t-n,r=Math.ceil(e/n);return Math.min(r,Math.max(0,o))};export{c as DEFAULT_PROMOTION_THRESHOLDS,i as RELAY_NAME_INFIX,x as clampPromotionThresholds,g as nextPromotionState,f as parseRelayName,N as relayCountFor,w as relayName,d as relayProxyKey,l as shapeRoutingKey};
1
+ import{LunoraError as m}from"@lunora/errors";import{stableWireKey as a}from"./stableWireKey-D2US4k_J.mjs";const i="::relay::",w=(t,n)=>`${t}${i}${String(n)}`,f=t=>{const n=t.lastIndexOf(i);if(n===-1)return;const o=t.slice(0,n),e=t.slice(n+i.length),r=Number(e);if(!(o.length===0||!Number.isInteger(r)||r<0||String(r)!==e))return{ownerKey:o,relayIndex:r}},l=(t,n)=>a({args:n??{},name:t}),d=(t,n,o)=>`${String(t)}:${n}:${o}`,c={tDown:4e3,tUp:8e3},g=(t,n,o=c)=>{if(o.tDown>=o.tUp)throw new m("INTERNAL",`invalid promotion thresholds: tDown (${String(o.tDown)}) must be < tUp (${String(o.tUp)})`);return t==="owned"?n>=o.tUp?"promoted":"owned":n<o.tDown?"owned":"promoted"},x=(t,n)=>n<t?{tDown:n,tUp:t}:{tDown:Math.min(Math.max(1,Math.floor(t/2)),t-1),tUp:t},N=(t,n,o)=>{if(t<=n||n<=0)return 0;const e=t-n,r=Math.ceil(e/n);return Math.min(r,Math.max(0,o))};export{c as DEFAULT_PROMOTION_THRESHOLDS,x as clampPromotionThresholds,g as nextPromotionState,f as parseRelayName,N as relayCountFor,w as relayName,d as relayProxyKey,l as shapeRoutingKey};
@@ -1 +1 @@
1
- import{toErrorBody as R,LunoraError as k}from"@lunora/errors";import{e as A}from"./wire-codec-C-FpWm52.mjs";import{readStreamRun as T,deleteStreamRun as w,claimStreamRun as _,appendStreamChunk as y,finishStreamRun as E,trimStreamRuns as b,readStreamChunks as v}from"./appendStreamChunk-BRwBOTEN.mjs";const p=5e4,S=64*1024*1024,M=864e5,N=36e5,L=(i,e)=>{const r=i?.startedAt??e.live?.generation;return e.resuming&&e.generation!==void 0&&r!==void 0&&e.generation!==r?"interrupted":e.live!==void 0?"attach":i===void 0?e.resuming?"interrupted":"attach":i.status==="complete"||i.status==="error"?e.resuming?"replay-terminal":"reclaim":e.resuming?"interrupted":"reclaim"},O=(i,e,r)=>{(i||r())&&e.fail({code:"STREAM_INTERRUPTED",message:i?"the run this durable stream resumed from no longer exists; start a new run":"the producer for this durable stream did not survive; start a new run"})};class I{lastTrimAt=0;runs=new Map;sql;waitUntil;constructor(e){this.sql=e.sql,this.waitUntil=e.waitUntil}async attach(e){try{await this.attachOrThrow(e)}catch(r){const{body:t,redacted:o}=R(r,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"internal error"});o&&console.error("[@lunora/shard-engine] durable stream attach failed:",r),e.sink.fail({code:t.code,message:t.message})}finally{this.trim(this.sql())}}detach(e,r){this.runs.get(e)?.sinks.delete(r)}isLive(e){return this.runs.has(e)}async attachOrThrow(e){const r=this.sql(),{runKey:t,sinceChunk:o,sink:c}=e,s=T(r,t),u=o>0,n=this.runs.get(t),a=s?.startedAt??n?.generation,l=L(s,{generation:e.generation,live:n,resuming:u}),d=()=>{for(const g of v(r,t,o))if(!c.chunk({data:JSON.parse(g.dataJson),generation:a,seq:g.seq}))return!1;return!0};if(l==="replay-terminal"){d()&&(s?.status==="error"?c.fail({code:s.errorCode??"INTERNAL_SERVER_ERROR",message:s.error??"stream failed"}):c.complete());return}if(l==="interrupted"){O(e.generation!==void 0&&a!==void 0&&e.generation!==a,c,d);return}if(n){d()&&n.sinks.add(c);return}l==="reclaim"&&w(r,t);const m=Math.max(Date.now(),s===void 0?0:s.startedAt+1);_(r,t,m,e.ttlMs??M);const h={generation:m,sinks:new Set([c])};this.runs.set(t,h);const f=this.produce(t,e.iterator,h);this.waitUntil?.(f),await f}async produce(e,r,t){const o=this.sql(),c=new AbortController;let s=0,u=0;try{for await(const n of r(c.signal)){const a=A(n),l=JSON.stringify(a);if(s+=1,u+=l.length,s>p||u>S)throw new k("STREAM_TOO_LONG",`durable stream exceeded its ceiling (${String(p)} chunks / ${String(S)} bytes); yield less, or drop \`durable\``,{status:507});y(o,e,s,l);for(const d of t.sinks)d.chunk({data:a,generation:t.generation,seq:s})||t.sinks.delete(d)}E(o,e,"complete",s);for(const n of t.sinks)n.complete()}catch(n){const{body:a,redacted:l}=R(n,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"internal error"});l&&console.error("[@lunora/shard-engine] unhandled durable stream error:",n),E(o,e,"error",s,{code:a.code,message:a.message});for(const d of t.sinks)d.fail({code:a.code,message:a.message})}finally{this.runs.delete(e)}}trim(e){const r=Date.now();if(!(r-this.lastTrimAt<=N)){this.lastTrimAt=r;try{b(e,r)}catch{}}}}export{I as DurableStreamRunner,S as MAX_DURABLE_STREAM_BYTES,p as MAX_DURABLE_STREAM_CHUNKS,L as decideDurableAttach};
1
+ import{toErrorBody as R,LunoraError as k}from"@lunora/errors";import{e as A}from"./wire-codec-C-FpWm52.mjs";import{readStreamRun as w,deleteStreamRun as T,claimStreamRun as _,appendStreamChunk as y,finishStreamRun as E,trimStreamRuns as b,readStreamChunks as v}from"./appendStreamChunk-7ZyAZGg_.mjs";const S=5e4,p=64*1024*1024,M=864e5,N=36e5,L=(i,e)=>{const r=i?.startedAt??e.live?.generation;return e.resuming&&e.generation!==void 0&&r!==void 0&&e.generation!==r?"interrupted":e.live!==void 0?"attach":i===void 0?e.resuming?"interrupted":"attach":i.status==="complete"||i.status==="error"?e.resuming?"replay-terminal":"reclaim":e.resuming?"interrupted":"reclaim"},O=(i,e,r)=>{(i||r())&&e.fail({code:"STREAM_INTERRUPTED",message:i?"the run this durable stream resumed from no longer exists; start a new run":"the producer for this durable stream did not survive; start a new run"})};class I{lastTrimAt=0;runs=new Map;sql;waitUntil;constructor(e){this.sql=e.sql,this.waitUntil=e.waitUntil}async attach(e){try{await this.attachOrThrow(e)}catch(r){const{body:t,redacted:o}=R(r,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"internal error"});o&&console.error("[@lunora/shard-engine] durable stream attach failed:",r),e.sink.fail({code:t.code,message:t.message})}finally{this.trim(this.sql())}}detach(e,r){this.runs.get(e)?.sinks.delete(r)}isLive(e){return this.runs.has(e)}async attachOrThrow(e){const r=this.sql(),{runKey:t,sinceChunk:o,sink:c}=e,s=w(r,t),u=o>0,n=this.runs.get(t),a=s?.startedAt??n?.generation,l=L(s,{generation:e.generation,live:n,resuming:u}),d=()=>{for(const g of v(r,t,o))if(!c.chunk({data:JSON.parse(g.dataJson),generation:a,seq:g.seq}))return!1;return!0};if(l==="replay-terminal"){d()&&(s?.status==="error"?c.fail({code:s.errorCode??"INTERNAL_SERVER_ERROR",message:s.error??"stream failed"}):c.complete());return}if(l==="interrupted"){O(e.generation!==void 0&&a!==void 0&&e.generation!==a,c,d);return}if(n){d()&&n.sinks.add(c);return}l==="reclaim"&&T(r,t);const m=Math.max(Date.now(),s===void 0?0:s.startedAt+1);_(r,t,m,e.ttlMs??M);const h={generation:m,sinks:new Set([c])};this.runs.set(t,h);const f=this.produce(t,e.iterator,h);this.waitUntil?.(f),await f}async produce(e,r,t){const o=this.sql(),c=new AbortController;let s=0,u=0;try{for await(const n of r(c.signal)){const a=A(n),l=JSON.stringify(a);if(s+=1,u+=l.length,s>S||u>p)throw new k("STREAM_TOO_LONG",`durable stream exceeded its ceiling (${String(S)} chunks / ${String(p)} bytes); yield less, or drop \`durable\``,{status:507});y(o,e,s,l);for(const d of t.sinks)d.chunk({data:a,generation:t.generation,seq:s})||t.sinks.delete(d)}E(o,e,"complete",s);for(const n of t.sinks)n.complete()}catch(n){const{body:a,redacted:l}=R(n,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"internal error"});l&&console.error("[@lunora/shard-engine] unhandled durable stream error:",n),E(o,e,"error",s,{code:a.code,message:a.message});for(const d of t.sinks)d.fail({code:a.code,message:a.message})}finally{this.runs.delete(e)}}trim(e){const r=Date.now();if(!(r-this.lastTrimAt<=N)){this.lastTrimAt=r;try{b(e,r,new Set(this.runs.keys()))}catch{}}}}export{I as DurableStreamRunner,p as MAX_DURABLE_STREAM_BYTES,S as MAX_DURABLE_STREAM_CHUNKS,L as decideDurableAttach};
@@ -1,4 +1,4 @@
1
- import{LunoraError as p}from"@lunora/errors";import{sql as e}from"drizzle-orm";import{runDrizzle as i}from"./runDrizzle-BlpM0R9P.mjs";const s="__global_shape_snapshot",E=1e6,T=n=>{i(n,e`CREATE TABLE IF NOT EXISTS ${e.identifier(s)} (
1
+ import{LunoraError as p}from"@lunora/errors";import{sql as e}from"drizzle-orm";import{runDrizzle as i}from"./runDrizzle-Du5HLitO.mjs";const s="__global_shape_snapshot",E=1e6,T=n=>{i(n,e`CREATE TABLE IF NOT EXISTS ${e.identifier(s)} (
2
2
  connection_id TEXT NOT NULL,
3
3
  sub_id TEXT NOT NULL,
4
4
  members TEXT NOT NULL,
@@ -1,4 +1,4 @@
1
- import{sql as t}from"drizzle-orm";import{runDrizzle as n}from"./runDrizzle-BlpM0R9P.mjs";const r="__idempotency",m=i=>{n(i,t`CREATE TABLE IF NOT EXISTS ${t.identifier(r)} (
1
+ import{sql as t}from"drizzle-orm";import{runDrizzle as n}from"./runDrizzle-Du5HLitO.mjs";const r="__idempotency",m=i=>{n(i,t`CREATE TABLE IF NOT EXISTS ${t.identifier(r)} (
2
2
  identity TEXT NOT NULL,
3
3
  mutation_id TEXT NOT NULL,
4
4
  result_json TEXT NOT NULL,
@@ -1,4 +1,4 @@
1
- import{runSql as c,decodeJsonColumn as a,orNull as o}from"./runDrizzle-BlpM0R9P.mjs";const e="__lunora_mail",l=500,i=256*1024,n=t=>t!==void 0&&t.length>i?`${t.slice(0,i)}
1
+ import{runSql as c,decodeJsonColumn as a,orNull as o}from"./runDrizzle-Du5HLitO.mjs";const e="__lunora_mail",l=500,i=256*1024,n=t=>t!==void 0&&t.length>i?`${t.slice(0,i)}
2
2
  … [truncated by the dev mail catcher]`:t,s=t=>t===void 0?null:JSON.stringify(t),_=t=>{c(t,`CREATE TABLE IF NOT EXISTS "${e}" (
3
3
  id TEXT PRIMARY KEY,
4
4
  captured_at INTEGER NOT NULL,
@@ -0,0 +1 @@
1
+ import{LunoraError as $}from"@lunora/errors";import{D as ut}from"./MAX_TOKEN_LENGTH-BakL9FUy-B3VwYY8C.mjs";import{S as En,l as qe,h as Sn}from"./fts-companion-pUdD6kF-.mjs";import{sql as c}from"drizzle-orm";import{d as _n}from"./wire-codec-C-FpWm52.mjs";import{stableWireKey as It}from"./stableWireKey-D2US4k_J.mjs";import{throwingScheduler as Rn,aggregateSqlFunction as We,normalizeCountArgument as vn}from"./AGGREGATE_SQL_FUNCTION-DDEoMnJR.mjs";import{aggregateTableName as Xe,encodeAggregateKey as Ze,readAggregateValue as et}from"./aggregateTableName-C7o-gpms.mjs";import{mergeWhere as N,CountRlsUnsupportedError as tt,selectIndexForGroupBy as Tn,selectIndexForCount as An,selectIndexForAggregate as In}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{backfillSearchIndexesForTable as Cn,searchIndexCoversTable as xn}from"./backfillAggregateIndexes-B_3xdOgV.mjs";import{backfillAggregateIndexes as Gr,backfillRankIndexes as Nr,backfillSearchIndexes as jr}from"./backfillAggregateIndexes-B_3xdOgV.mjs";import{appendCdcChange as bn,readCdcDocAtOrBefore as Mn}from"./CDC_LOG_TABLE-QaBxSIZM.mjs";import{CDC_LOG_TABLE as Qr,applyCdcChanges as Vr,bumpCdcEpoch as zr,cdcCanVouchFor as Jr,cdcForkedError as Yr,cdcSeqLeavingRows as Xr,cdcTouchesTables as Zr,cdcTrimmedError as ei,compactCdcDocs as ti,cursorBelowRetainedFloor as ni,minCdcReplayableSeq as oi,minCdcSeq as ri,readCdcChangeKeys as ii,readCdcChanges as si,readCdcCursor as ci,readCdcEpoch as ai,trimCdcChanges as di}from"./CDC_LOG_TABLE-QaBxSIZM.mjs";import{allocateCommitSeq as Dn,COMMIT_SEQ_FIELD as kn}from"./COMMIT_SEQ_FIELD-BY_vc9bw.mjs";import{createCompanionSync as Fn}from"./createCompanionSync-Rjn0lsT6.mjs";import{isMemoryTable as Ct}from"./clearMemoryTables-CogAvVHR.mjs";import{computeRankPage as xt}from"./computeRankPage-3AiKfT8q.mjs";import{SCAN_DEP as G}from"./SCAN_DEP-D7qE3iUe.mjs";import{runSql as ve,runDrizzle as j}from"./runDrizzle-Du5HLitO.mjs";import{j as Oe,D as oe,r as Se,k as de,b as Be,A as nt,a as Pe,e as ce,o as Ln,t as Zt,q as bt,i as qn,h as en,g as Wn}from"./do-sql-BEFrJUds.mjs";import{renderSql as tn,unionAll as ft,WORKERD_SQLITE_LIMITS as nn,sqliteInList as Bn}from"./WORKERD_SQLITE_LIMITS-DBH23L_S.mjs";import{coveringGeohashes as Pn,boundingBoxGeohashes as Un,haversineMeters as Hn,pointInBoundingBox as On}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{NotFoundError as Gn}from"./NotFoundError-BhF7FeFr.mjs";import{tiebreakDirectionFor as Nn,encodeCursor as Ge,normalizeOrderKeys as ct,uniqueIndexFields as on,buildSeekWhere as rn,decodeCursor as at,buildSeekBeforeWhere as jn,softDeleteScope as ue,equalityPinnedFields as Kn,applySelect as Mt}from"./CURSOR_PREFIX-BX8jkMJa.mjs";import{rankTableName as Dt,sortColumnName as kt,resolveRankPartition as Qn,encodePartitionKey as Vn,RANK_TIEBREAK as zn,rankPivotConditionSql as Jn}from"./RANK_TIEBREAK-B0_x8iev.mjs";import{UNVOUCHABLE_DEP as Ft}from"./UNVOUCHABLE_DEP-C68htACn.mjs";import{indexKeysForRow as Yn,buildIndexRange as Xn}from"./buildIndexRange-6nIZDf4m.mjs";import{r as Ne,j as _e,c as te,t as je,i as Lt}from"./where-sql-DFs8Zw7-.mjs";import{serializeSqlValue as ae}from"./serializeSqlValue-BbZ5hKM7.mjs";import{quoteIdentifier as Te}from"./quoteIdentifier-CObIFRhb.mjs";import{whereOfFilter as Zn,isPushableWhere as eo}from"./isPushableWhere-BeYAOjUb.mjs";import{deriveRelationEdges as to,findRelated as no}from"./RELATED_DEFAULT_LIMIT-CBYQQIrZ.mjs";import{assertFlatPredicate as ot,resolveRelationPredicates as qt}from"./DEFAULT_MAX_RELATION_KEYS-CYPZfQH9.mjs";import{runRowValidators as rt,resolveWith as Wt,relationHooks as Bt,applyOnDelete as oo,fanOutScalarCounts as ro}from"./applyOnDelete-DJsOG8tz.mjs";import{guardWriter as io}from"./RLS_UNWRAP_SYMBOL-rSxYzw-G.mjs";import{mayHoldProjectedValue as so}from"./BIGINT_KEY_DIGITS-C9a7Ix7k.mjs";import{createSystemReader as co}from"./createSystemReader-DcDLFfC-.mjs";import{ConflictError as Re}from"./ConflictError-C8GtJmjS.mjs";import{runTriggers as ao}from"./hasTrigger-CjlwI4le.mjs";import{advanceClientWatermark as ui,migrateClientWatermark as fi,readClientWatermark as hi}from"./CLIENT_WATERMARK_TABLE-vLjfNhBR.mjs";import{IDEMPOTENCY_TABLE as pi,readIdempotent as gi,trimIdempotent as yi,writeIdempotent as $i}from"./IDEMPOTENCY_TABLE-AOJCuq5U.mjs";import{runShardMigrations as Ei}from"./runShardMigrations-MXioI81k.mjs";import{selectShapeMembers as _i,selectShapeRows as Ri}from"./selectShapeMembers-BXhvEt4X.mjs";const lo=n=>{const r=atob(n),o=Uint8Array.from(r,d=>d.codePointAt(0)??0);return new TextDecoder().decode(o)},uo=()=>new $("BAD_REQUEST","invalid cursor"),Pt=16,Ut=8,z=1024,ht=(n,r)=>r.query(n),fo=(n,r)=>{if(n.length===0)return 0;let o=0;for(const[d,i]of r.entries()){const w=d===r.length-1;let _=0;for(const E of n)(w?E.startsWith(i):E===i)&&(_+=1);if(_===0)return 0;o+=_}return o},ho=(n,r)=>{if(!r)return{exact:!0,lower:n,upper:n};const o=[...n].at(-1)??"",d=(o.codePointAt(0)??0)+1;if(d>=55296&&d<=57343||d>1114111)return{exact:!0,lower:n,upper:n};const i=n.slice(0,n.length-o.length);return{exact:!1,lower:n,upper:i+String.fromCodePoint(d)}},wo=(n,r,o)=>{const d={eq:(i,w)=>{if(!n.definition.filterFields?.includes(i))throw new $("INTERNAL",`field "${i}" is not a filter field of search index "${n.indexName}" on table "${r}"`);if(n.filters.length>=Ut)throw new $("BAD_REQUEST",`search index "${n.indexName}" on table "${r}": at most ${String(Ut)} .eq() filters are supported per search query`);return n.filters.push({field:i,value:w}),d},search:(i,w)=>{const _=n;if(i!==_.definition.field)throw new $("INTERNAL",`search index "${_.indexName}" on table "${r}" indexes "${_.definition.field}", not "${i}"`);const E=ht(w,o).length;if(E>Pt)throw new $("BAD_REQUEST",`search index "${_.indexName}" on table "${r}": at most ${String(Pt)} search terms are supported (got ${String(E)})`);return _.field=i,_.query=w,_.hasQuery=!0,d}};return d},po=n=>{if(n.length>z)throw new $("BAD_REQUEST",`more than ${String(z)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},go=n=>Math.min(n.offset+n.numItems+1,z),yo=n=>btoa(`search:${String(n)}`),$o=n=>{let r;try{r=lo(n)}catch{return}if(!r.startsWith("search:"))return;const o=Number(r.slice(7));return Number.isInteger(o)&&o>=0?o:void 0},mo=n=>{if(typeof n.endCursor=="string")throw new $("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");if(!Number.isFinite(n.numItems))throw new $("BAD_REQUEST",`search pagination needs a finite numItems, got ${String(n.numItems)}`);const r=Math.max(0,Math.floor(n.numItems)),o=n.cursor?$o(n.cursor):0;if(o===void 0)throw uo();if(o+r>=z)throw new $("BAD_REQUEST",`search pagination reaches the ${String(z)}-document limit (offset ${String(o)} + ${String(r)} requested) — a page must end below the cap so the probe row that answers \`hasMore\` still fits: retry with numItems ${String(Math.max(1,z-o-1))} or fewer, or narrow the query or the filters instead`);return{numItems:r,offset:o}},Eo=(n,r)=>{const o=r.offset+r.numItems,d=r.numItems>0&&n.length>o;return{continueCursor:d?yo(o):null,isDone:!d,page:n.slice(r.offset,o)}},So=n=>{if(n===void 0)return z+1;if(!Number.isFinite(n))return z;const r=Math.max(0,Math.floor(n));if(r>z)throw new $("BAD_REQUEST",`search returns at most ${String(z)} documents (asked for ${String(r)}) — narrow the query or paginate instead`);return r},_o=32,Ro=1024,sn=(n,r,o,d)=>{const i=`SELECT id, _creationTime, ${Te(oe)} FROM ${Te(n)}`,w=`ORDER BY ${o}${d===void 0?"":` LIMIT ${String(d)}`}`;return r===void 0?Ne(`${i} ${w}`):_e(`${i} WHERE `,r,` ${w}`)},wt={fieldRef:n=>Ne(Oe(n)),serialize:ae},cn=n=>{const r=n.map(o=>`${Oe(o.field)} ${o.direction==="desc"?"DESC":"ASC"}`);return n.some(o=>o.field==="_id"||o.field==="id")||r.push(`${Oe("id")} ${Nn(n)==="desc"?"DESC":"ASC"}`),r.join(", ")},vo={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},an=n=>new Set(n.sqlConditions.filter(r=>r.comparator==="=").map(r=>r.field)),To=n=>{const r=an(n);let o=0;for(;o<n.indexFields.length&&r.has(n.indexFields[o]??"");)o+=1;return n.indexFields.slice(o)},Ao=(n,r)=>{const o=n.order,d=To(n),{shape:i}=r;return d.length>0?ct(d.map(w=>({[w]:o})),i,{pinned:an(n),uniqueBy:on(r.indexes,i)}):ct([{_creationTime:o}],i)},Io=(n,r,o,d)=>{const i=n.sqlConditions.map(w=>({[w.field]:{[vo[w.comparator]??"eq"]:w.value}}));if(o&&i.push(rn(r,at(o))),d&&i.push(jn(r,at(d))),i.length!==0)return i.length===1?i[0]:{AND:i}},Co=n=>{if(n.want!==void 0)return n.selective?Math.max(n.want,_o):n.want},dt=(n,r,o,d,i,w,_)=>{const E=Ao(d,o),x=cn(E),g=[],{filters:b,want:T}=w;let R=w.cursor??void 0,M=Co(w);if(T===0)return{documents:g,orderKeys:E};for(;;){const q=te(Io(d,E,R,w.endCursor),wt,je),W=sn(r,i&&q?_e(q," AND ",i):i??q,x,M),L=ve(n,W.text,...W.params).toArray();let P={};_(L.length);for(const C of L)if(P=Se(C),b.every(ne=>ne(P))&&g.push(P)===T)return{documents:g,orderKeys:E};if(M===void 0||L.length<M)return{documents:g,orderKeys:E};R=Ge(P,E),M=Math.max(M,Math.min(M*2,Ro))}},xo=(n,r,o,d,i,w,_,E)=>{const x=Math.max(0,Math.floor(i.numItems));if(typeof i.endCursor=="string"){const{documents:q,orderKeys:W}=dt(n,r,o,d,w,{cursor:i.cursor,endCursor:i.endCursor,filters:_.all,selective:_.selective,want:void 0},E),L=q.length>=2?q[Math.floor(q.length/2)-1]:void 0;return{continueCursor:i.endCursor,isDone:!0,page:q,splitCursor:L?Ge(L,W):null}}const{documents:g,orderKeys:b}=dt(n,r,o,d,w,{cursor:i.cursor,filters:_.all,selective:_.selective,want:x+1},E),T=g.length>x,R=T?g.slice(0,x):g,M=R.at(-1);return{continueCursor:T&&M?Ge(M,b):null,isDone:!T,page:R}},Ke=n=>{const r=new Map;return o=>{const d=r.get(o);if(d!==void 0)return d;const i=n(Te(o));return r.set(o,i),i}},fe=Te(oe),bo=Ke(n=>`INSERT INTO ${n} (id, _creationTime, ${fe}) VALUES (?, ?, ?)`),Ht=Ke(n=>`UPDATE ${n} SET ${fe} = ? WHERE id = ? AND ${fe} = ?`),Mo=Ke(n=>`UPDATE ${n} SET _creationTime = ?, ${fe} = ? WHERE id = ? AND ${fe} = ?`),Do=Ke(n=>`DELETE FROM ${n} WHERE id = ? AND ${fe} = ?`),ko="SELECT changes() AS changed",Ot=new Map,Fo="",Lo=n=>{const r=JSON.stringify(n),o=Ot.get(r);if(o!==void 0)return o;const d=n.map(w=>c`SELECT ${c.raw(`'${w.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${c.identifier(oe)} FROM ${c.identifier(w)} WHERE id = ${Fo}`),{sql:i}=tn("sqlite",c`${ft(d)} LIMIT 1`);return Ot.set(r,i),i},qo=(n,r)=>r.map(()=>n),Wo=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,Bo=n=>{if(!Wo.test(n))throw new $("INTERNAL",`invalid clientId ${JSON.stringify(n)}: a client-supplied row id must be a UUID`)},Gt=50,dn=500,Ue=Math.floor(nn.boundParams/3),me=nn.boundParams,Po=128,le=(n,r,o)=>{const d=r??dn;if(n>d)throw new $("BATCH_LIMIT_EXCEEDED",`${o}: batch of ${String(n)} exceeds the limit of ${String(d)} (raise options.limit or chunk the call)`,{status:400})},Uo=n=>{const r={eq:(o,d)=>(n.sqlConditions.push({comparator:"=",field:o,value:d}),r),gt:(o,d)=>(n.sqlConditions.push({comparator:">",field:o,value:d}),r),gte:(o,d)=>(n.sqlConditions.push({comparator:">=",field:o,value:d}),r),lt:(o,d)=>(n.sqlConditions.push({comparator:"<",field:o,value:d}),r),lte:(o,d)=>(n.sqlConditions.push({comparator:"<=",field:o,value:d}),r)};return r},Ho=n=>Math.max(n,z),ln=(n,r)=>{const o=n.filters.map(d=>c`${ce(d.field)} = ${ae(d.value)}`);return r&&o.push(r),o},Oo=(n,r,o,d,i)=>{const w=ht(o.query,ut(o.definition.language));if(w.length===0)return[];const _=En(r,o.indexName),E=`${_}__vocab`,x=w.length-1,g=w.map((W,L)=>{const P=ho(W,L===x),C=P.exact?c`${c.identifier("term")} = ${P.lower}`:c`${c.identifier("term")} >= ${P.lower} AND ${c.identifier("term")} < ${P.upper}`;return c`SELECT ${c.identifier("doc")}, ${c.raw(String(L))} AS ${c.identifier("__term__")}, COUNT(*) AS ${c.identifier("__n__")} FROM ${c.identifier(E)} WHERE ${C} GROUP BY ${c.identifier("doc")}`}),b=w.map((W,L)=>c`SUM(CASE WHEN u.${c.identifier("__term__")} = ${c.raw(String(L))} THEN u.${c.identifier("__n__")} ELSE 0 END)`),T=c`SELECT f.${c.identifier(qe)} AS ${c.identifier(qe)}, ${c.join(b,c` + `)} AS ${c.identifier("__score__")} FROM (${ft(g)}) u JOIN ${c.identifier(_)} f ON f.rowid = u.${c.identifier("doc")} GROUP BY f.${c.identifier(qe)} HAVING ${c.join(b.map(W=>c`${W} > 0`),c` AND `)}`,R=ln(o,i);let M=c`SELECT m.id, m._creationTime, m.${c.identifier(oe)}, s.${c.identifier("__score__")} AS ${c.identifier("__score__")} FROM (${T}) s JOIN ${c.identifier(r)} m ON m.id = s.${c.identifier(qe)}`;R.length>0&&(M=c`${M} WHERE ${c.join(R,c` AND `)}`),M=c`${M} ORDER BY s.${c.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${c.raw(String(d))}`;const q=[];for(const W of j(n,M)){const L=en(W);if(L){const P=W.__score__;q.push({document:L,score:typeof P=="number"?P:Number(P??0)})}}return q},Go=(n,r,o,d,i)=>{const w=ut(o.definition.language),_=ht(o.query,w);if(_.length===0)return[];const E=ln(o,i);let x=c`SELECT id, _creationTime, ${c.identifier(oe)} FROM ${c.identifier(r)}`;E.length>0&&(x=c`${x} WHERE ${c.join(E,c` AND `)}`),x=c`${x} ORDER BY _creationTime DESC, id ASC LIMIT ${c.raw(String(Ho(d)))}`;const g=j(n,x).toArray(),b=[];for(const T of g){const R=en(T);if(!R)continue;const M=fo(Sn(R,o.definition),_);M>0&&b.push({creationTime:typeof R._creationTime=="number"?R._creationTime:0,doc:R,id:typeof R._id=="string"?R._id:"",score:M})}return b.sort((T,R)=>R.score-T.score||R.creationTime-T.creationTime||T.id.localeCompare(R.id)),b.slice(0,d).map(T=>({document:T.doc,score:T.score}))},it=(n,r,o,d)=>{if(!Number.isFinite(n.lat)||n.lat<-90||n.lat>90||!Number.isFinite(n.lng)||n.lng<-180||n.lng>180)throw new $("BAD_REQUEST",`geo index "${d}" on table "${o}": ${r} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},No=(n,r)=>{const o=n,d={near:(i,w)=>{if(o.within)throw new $("INTERNAL",`geo index "${o.indexName}" on table "${r}": call .near() or .within(), not both`);if(it(i,".near() point",r,o.indexName),!Number.isFinite(w)||w<=0)throw new $("BAD_REQUEST",`geo index "${o.indexName}" on table "${r}": .near() radiusMeters must be a finite number > 0, got ${String(w)}`);return o.near={point:{lat:i.lat,lng:i.lng},radiusMeters:w},d},within:i=>{if(o.near)throw new $("INTERNAL",`geo index "${o.indexName}" on table "${r}": call .near() or .within(), not both`);if(it(i.sw,".within() sw corner",r,o.indexName),it(i.ne,".within() ne corner",r,o.indexName),i.sw.lat>i.ne.lat)throw new $("BAD_REQUEST",`geo index "${o.indexName}" on table "${r}": .within() corners are transposed (sw.lat > ne.lat)`);if(i.sw.lng>i.ne.lng)throw new $("BAD_REQUEST",`geo index "${o.indexName}" on table "${r}": .within() box crosses the antimeridian (sw.lng > ne.lng), which is not supported — split it into two boxes at ±180 and union the results`);return o.within={ne:{lat:i.ne.lat,lng:i.ne.lng},sw:{lat:i.sw.lat,lng:i.sw.lng}},d}};return d},jo=(n,r)=>{const o=n[r];if(o===null||typeof o!="object")return;const{lat:d,lng:i}=o;return typeof d=="number"&&typeof i=="number"?{lat:d,lng:i}:void 0},Ko=(n,r)=>{const o=jo(n,r.definition.field);if(!o)return;const d=typeof n._creationTime=="number"?n._creationTime:0;if(r.near){const i=Hn(r.near.point,o);return i<=r.near.radiusMeters?{creationTime:d,distance:i}:void 0}return On(o,r.within)?{creationTime:d,distance:0}:void 0},Qo=(n,r,o,d)=>{if(!o.near&&!o.within)throw new $("INTERNAL",`geo index "${o.indexName}" on table "${r}": call .near(point, radius) or .within(box)`);const i=o.near?Pn(o.near.point,o.near.radiusMeters):Un(o.within),w=Wn(r,o.indexName),_=i.map(T=>c`(g.${c.identifier("__geohash__")} >= ${T} AND g.${c.identifier("__geohash__")} < ${`${T}{`})`),E=[c`(${c.join(_,c` OR `)})`];d&&E.push(d);const x=c`SELECT m.id, m._creationTime, m.${c.identifier(oe)} FROM ${c.identifier(w)} g JOIN ${c.identifier(r)} m ON m.id = g.${c.identifier("__id__")} WHERE ${c.join(E,c` AND `)}`,g=j(n,x).toArray(),b=[];for(const T of g){const R=Se(T),M=R?Ko(R,o):void 0;R&&M&&b.push({creationTime:M.creationTime,distance:M.distance,doc:R})}return b.sort((T,R)=>T.distance-R.distance||R.creationTime-T.creationTime),b},un=(n,r,o,d)=>{const i=[];for(const w of n)if(r.every(_=>_(d(w)))&&(i.push(w),typeof o=="number"&&i.length>=o))break;return i},Vo=(n,r,o,d,i,w=()=>{})=>{const _=o.within!==void 0,E=Qo(n,r,o,i).map(x=>({distanceMeters:_?null:x.distance,document:x.doc}));return w(E.length),typeof d=="number"?E.slice(0,Math.max(0,Math.floor(d))):E},Nt=(n,r,o,d,i,w,_=()=>{})=>{const{geo:E}=o;if(!E)throw new $("INTERNAL","runGeoTerminalScored called without a staged geo query");const x=i.length>0,g=Vo(n,r,E,x?void 0:w,d,_);return x?un(g,i,w,b=>b.document):g},Ee={fieldRef:ce,serialize:ae},fn=(n,r)=>{const o=r===void 0?void 0:n.shape[r];return o!==void 0&&so(o)},jt=(n,r)=>r.some(o=>fn(n,o)),Kt=(n,r,o)=>{if(fn(n,r))throw new $("BAD_REQUEST",`${o}: "${r}" may hold an order-preserving key rather than a value SQL can reduce or group — declare an aggregateIndex covering this (by, field, op) so the maintained companion answers it instead (its running total is a REAL, so it stays exact only while the total is inside 2^53)`)},zo=n=>{let r=0;const o=[],d={fieldRef:i=>Ne(Oe(i)),relationExists:i=>{const{childWhere:w,negated:_,parentTable:E,relation:x}=i,g=`__rel_${String(r)}`,b=o.at(-1)??E;r+=1,n(x.table,G);const T=x.kind==="one"?x.field:x.references,R=x.kind==="one"?x.references:x.field,M=Ne(`${bt(g,R)} = ${bt(b,T)}`);o.push(g);const q=te(w,d,je);o.pop();const W=q===void 0?M:_e(M," AND ",q),L=_e("EXISTS (SELECT 1 FROM ",Lt(x.table)," AS ",Lt(g)," WHERE ",W,")");return _?_e("NOT ",L):L},serialize:ae};return d};class Jo extends ${constructor(r="unique() found more than one matching document"){super("NOT_UNIQUE",r,{name:"NotUniqueError"})}}const Yo=/\s/u,Xo=String.fromCodePoint(0),Qt=(n,r,o)=>{if(!n.tables[r])throw new $("INTERNAL",`unknown table: ${r}`);return typeof o!="string"||o.length===0||Yo.test(o)||o.includes(Xo)?null:o},hn=(n,r,o,d=()=>{},i=()=>{},w=()=>{},_)=>{const E=r.tables[o];if(!E)throw new $("INTERNAL",`unknown table: ${o}`);const x=ue(E.softDeleteMode,void 0),g=_??{indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[],verifyFilters:[]},b=()=>{const y=N(x,g.pushedWhere);return y?te(y,Ee):void 0},T=()=>{const y=N(x,g.pushedWhere);return y?te(y,wt,je):void 0},R=()=>[...g.inMemoryFilters,...g.verifyFilters];let M=0;const q=y=>{const{search:A}=g;if(!A)throw new $("INTERNAL","runSearchFetch called without a staged search");Cn(n,o,E);const D=g.inMemoryFilters.length>0,F=So(D?void 0:y),X=qn(n);if(X&&!xn(n,o,A.definition))throw new $("SEARCH_INDEX_BUILDING",`search index "${A.indexName}" on table "${o}" is still backfilling and currently covers only part of the table — retry once it finishes, or run the backfillSearch admin operation to complete it now`);const he=b(),J=X?Oo(n,o,A,F,he):Go(n,o,A,F,he);!D&&y===void 0&&po(J);const re=R();return M=J.length,re.length>0?un(J,re,y,Ae=>Ae.document):J},W=y=>q(y).map(A=>A.document),L=y=>{const A=mo(y);return Eo(W(go(A)),A)},P=()=>{if(g.search||g.geo||g.indexName===void 0){i(void 0);return}i(Xn(o,g.indexName,g.indexFields,g.sqlConditions,ae))},C=y=>{P();let A=0;const D=(()=>{if(g.search){const F=W(y);return A=M,F}return g.geo?Nt(n,o,g,b(),R(),y,F=>{A=F}).map(F=>F.document):dt(n,o,E,g,T(),{filters:R(),selective:g.inMemoryFilters.length>0,want:y===void 0?void 0:Math.max(0,Math.floor(y))},F=>{A+=F}).documents})();return w(Math.max(A,D.length)),D},ne=()=>{if(!g.search&&!g.geo)throw new $("INTERNAL",`ctx.db.query("${o}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);P();let y=0;const A=(()=>{if(g.search){const D=q(void 0);return y=M,D}return Nt(n,o,g,b(),R(),void 0,D=>{y=D})})();return w(Math.max(y,A.length)),A},Y={async*[Symbol.asyncIterator](){const y=hn(n,r,o,d,i,w,{...g,indexFields:[...g.indexFields],inMemoryFilters:[...g.inMemoryFilters],sqlConditions:[...g.sqlConditions],verifyFilters:[...g.verifyFilters]});if(g.search){yield*await y.collect();return}let A;for(;;){const D=await y.paginate({cursor:A??null,numItems:Po});if(yield*D.page,D.isDone||D.continueCursor===null)return;A=D.continueCursor}},async collect(){return C(void 0)},async collectWithScores(){return ne()},filter(y){const A=Zn(y);return A!==void 0&&eo(A,E.shape)?(g.pushedWhere=N(g.pushedWhere,A),g.verifyFilters.push(y)):g.inMemoryFilters.push(y),Y},async first(){return C(1)[0]??null},order(y){return g.order=y==="desc"?"desc":"asc",Y},async paginate(y){let A=0;if(P(),g.search){const F=L(y);return w(F.page.length),F}if(g.geo)throw new $("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const D=xo(n,o,E,g,y,T(),{all:R(),selective:g.inMemoryFilters.length>0},F=>{A+=F});return w(Math.max(A,D.page.length)),D},async take(y){return C(y)},async unique(){const y=C(2);if(y.length>1)throw new Jo(`unique() on table "${o}" matched ${String(y.length)} documents; expected at most one`);return y[0]??null},withGeoIndex(y,A){const D=(E.geoIndexes??[]).find(X=>X.name===y);if(!D)throw new $("INTERNAL",`unknown geo index "${y}" on table "${o}"`);d(o,y,"geo");const F={definition:D,indexName:y};if(g.geo=F,A(No(F,o)),!F.near&&!F.within)throw new $("INTERNAL",`geo index "${y}" on table "${o}" requires a .near(point, radius) or .within(box) call`);return Y},withIndex(y,A){const D=E.indexes.find(F=>F.name===y);if(!D)throw new $("INTERNAL",`unknown index "${y}" on table "${o}"`);return d(o,y,"index"),g.indexName=y,g.indexFields=D.fields,A&&A(Uo(g)),Y},withSearchIndex(y,A){const D=(E.searchIndexes??[]).find(X=>X.name===y);if(!D)throw new $("INTERNAL",`unknown search index "${y}" on table "${o}"`);d(o,y,"search");const F={definition:D,field:D.field,filters:[],hasQuery:!1,indexName:y,query:""};if(g.search=F,A(wo(F,o,ut(D.language))),!F.hasQuery)throw new $("INTERNAL",`search index "${y}" on table "${o}" requires a .search(field, query) call`);return Y}};return Y},Vt=(n,r,o)=>{const d={...r};for(const[i,w]of Zt(n)){if(w.serverDefault){d[i]=w.serverDefault({auth:o});continue}d[i]===void 0&&(w.defaultFn?d[i]=w.defaultFn():"defaultValue"in w&&(d[i]=w.defaultValue))}return d},zt=(n,r,o,d)=>{const i=o;for(const[w,_]of Zt(n)){if(_.serverDefault){w in r&&(i[w]=_.serverDefault({auth:d}));continue}_.onUpdateFn&&!(w in r)&&(i[w]=_.onUpdateFn())}},Jt=(n,r)=>{for(const o of Object.keys(r))if(r[o]===void 0)throw new $("INTERNAL",`Cannot ${n} field '${o}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},Yt=["_commitSeq","_creationTime","_id"],st=n=>Yt.some(r=>r in n)?Object.fromEntries(Object.entries(n).filter(([r])=>!Yt.includes(r))):n,Zo=/unique constraint failed/i,er=n=>n instanceof Error&&Zo.test(n.message),tr=/string or blob too big/iu,nr=(n,r)=>{if(!(!(n instanceof Error)||!tr.test(n.message)))throw new $("PAYLOAD_TOO_LARGE",`document is too large to store in "${r}": a single row cannot exceed the storage engine's per-row ceiling (2 MB on a Durable Object's SQLite). The limit is on the STORED bytes, which are UTF-8, and v.bytes()/v.bigint() columns are stored twice on a shard-local table. Keep the payload in R2 (ctx.storage) and store a reference on the row.`)},lt=(n,r,o,d)=>{try{ve(n,o,...d)}catch(i){throw er(i)?new Re(`unique constraint violation on "${r}"`,"unique"):(nr(i,r),i)}},He=(n,r,o,d)=>{if(lt(n,r,o,d),ve(n,ko).one().changed===0)throw new Re(`optimistic concurrency conflict on "${r}" — the row changed during this mutation; refetch and retry`,"occ")},Xt=(n,r,o,d,i,w,_)=>{const E=[];for(let T=0;T<o.length+1;T+=1){const R=o[T],M=d[T],q=M?.direction==="desc"?"desc":"asc",W=R===void 0||M===void 0?c`${c.identifier(zn)} < ${_}`:Jn(R,w[T],q,!1);if(W===void 0)continue;const L=[];for(let C=0;C<T;C+=1)L.push(c`${c.identifier(o[C])} IS ${w[C]}`);L.push(W);const[P]=L;E.push(L.length===1&&P!==void 0?P:c`(${c.join(L,c` AND `)})`)}const x=E.length>0?c.join(E,c` OR `):c`1 = 0`,g=j(n,c`SELECT COUNT(*) AS c FROM ${c.identifier(r)} WHERE ${c.identifier("__partition__")} = ${i} AND (${x})`).one(),b=j(n,c`SELECT COUNT(*) AS c FROM ${c.identifier(r)} WHERE ${c.identifier("__partition__")} = ${i}`).one();return{before:g.c,total:b.c}},Ur=n=>{const{baselineSeq:r,onStalePatchDropped:o}=n,{sql:d}=n,{schema:i}=n,w=n.broadcast??(()=>{}),_=to(i);let E;const x=()=>n.inTransaction?.()===!0,g=e=>i.tables[e]?.commitOrderedMode!==!0?{}:((E===void 0||!x())&&(E=Dn(d)),{[kn]:E}),b=(e,...t)=>{const s=i.tables[e]?.indexes;if(!s||s.length===0)return;const f=[];for(const h of t)h&&f.push(...Yn(s,h,ae));return f.length>0?f:void 0},{headroom:T}=n;let R=!1;const M=async e=>{const t=R;R=!0;try{return await e()}finally{R=t}},q=n.onRead??(()=>{}),W=e=>{Ct(i.tables[e])&&q(Ft,Ft)},L=n.onReadRange??(e=>{q(e.table,G)}),P=e=>{W(e.table),L(e)},C=(e,t)=>{t!==void 0&&t!==G&&!R&&T?.recordRead(1),W(e),q(e,t)},ne=n.onIndexUse??(()=>{}),Y=n.onWrite??(()=>{}),y=e=>{R||T?.recordWrite(e)},A=async e=>{y(e.doc),await Y(e)},{cache:D}=n,F=n.clock??(()=>Date.now()),X=n.idGenerator??(()=>crypto.randomUUID()),he=n.scheduler??Rn,{globalDb:J}=n,re=n.auth??{identity:null,userId:null},Ae=n.cdc??!1,Qe=he,wn=co({scheduler:typeof Qe.list=="function"&&typeof Qe.get=="function"?Qe:void 0,storage:n.storage}),we=(e,t,s,f)=>{Ae&&!Ct(i.tables[e])&&bn(d,F(),e,t,s,f)},pn=(e,t,s,f)=>{if(i.tables[e]?.dropStalePatchesMode!==!0||!Ae)return!1;const h=r?.();if(h===void 0)return!1;const l=Mn(d,e,t,h);return l===void 0?!1:Object.keys(st(s)).some(a=>It(l[a])!==It(f[a]))},ie=e=>i.tables[e]?.shardMode?.kind==="global",pt=(e,t)=>{if(ie(e)){if(!J)throw new $("INTERNAL",`cross-backend ${t} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return J}return H},Ve=e=>pt(e,"cascade"),Q=(e,t)=>{if(ie(e)){if(!J)throw new $("INTERNAL",`${t} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return J}},gt=async(e,t,s,f,h)=>{h&&y(s);const l=await e.insert(t,s,f);return w({key:l,op:"insert",row:{...s,_id:l},table:t}),l},ze=(e,t)=>pt(e,"relation load").findMany(e,t),yt=(e,t)=>(ie(e)&&C(e,G),ze(e,t)),gn=e=>!ie(e.table),$t=n.relationExistsPushDown??"auto",mt=$t!=="never",{maxRelationKeys:Et}=n,Ie=(e,t,s)=>qt(e,{fetcher:yt,maxRelationKeys:Et,relationBaseWhere:s,schema:i,tableName:t}),St=async(e,t,s,f)=>{const h=Q(e,"relation grouped count");if(h)return C(e,G),ro((U,I)=>h.count(U,I),e,t,s,f);const l=i.tables[e];if(!l)throw new $("INTERNAL",`unknown table: ${e}`);C(e,G);const a=ue(l.softDeleteMode,void 0),u={[t]:{in:s}},p=N(N(u,f),a),v=await Ie(p,e,void 0),m=te(v,Ee),k=ce(t);let S=c`SELECT ${k} AS __fk__, COUNT(*) AS count FROM ${c.identifier(e)}`;m&&(S=c`${S} WHERE ${m}`),S=c`${S} GROUP BY ${k}`;const B=j(d,S).toArray();return new Map(B.map(U=>[U.__fk__,U.count]))};let Ce=0;const _t=new Set;for(const[e,t]of Object.entries(i.tables))for(const s of Object.values(t.triggerMap??{}))_t.add(`${e} ${s.timing} ${s.op}`);const Z=(e,t,s)=>_t.has(`${e} ${t} ${s}`),ee=async(e,t,s)=>{if(Ce+=1,Ce>Gt)throw Ce-=1,new Re(`trigger recursion exceeded ${String(Gt)} levels on "${s.table}" — check for a self-triggering write`,"trigger");try{await ao({ctx:$n,event:s,op:t,schema:i,tableName:s.table,timing:e})}finally{Ce-=1}},{ensureBackfilledForTable:pe,ensureBackfilledIndex:Je,ensureRankBackfilled:Ye,ensureRankBackfilledForTable:ge,syncAggregates:xe,syncCompanionsForInsert:Rt,syncGeo:be,syncRanks:ye,syncSearch:Me}=Fn({broadcast:w,indexKeysFor:(e,t)=>b(e,t),invalidateCache:(e,t,s)=>D?.invalidate(e,t,b(e,s)),recordCdc:we,schema:i,sql:d}),vt=(e,t,s)=>{const{shardMode:f}=t;if(f?.kind==="shardBy"&&!(f.field!==void 0&&(s.partitionBy??[]).includes(f.field)))throw Object.assign(new Error(`rank index "${s.name}" on "${e}" partitions across shards (shard key "${f.field??"?"}" is not in partitionBy) — a shard-local rank()/rankPage() would be wrong; roll it up through the Query Coordinator instead`),{code:"CROSS_SHARD_RANK_UNSUPPORTED",name:"LunoraError",status:400})},Tt=e=>Object.entries(i.tables).filter(([,t])=>t.shardMode?.kind!=="global").map(([t])=>t).filter(t=>e===void 0||t===e),$e=e=>e===void 0||ie(e)?J:void 0,se=(e,t)=>{const s=Tt(t);for(let f=0;f<s.length;f+=me){const h=s.slice(f,f+me),[l]=ve(d,Lo(h),...qo(e,h)).toArray();if(!l)continue;const a=l.__t__,u=Se(l);if(typeof a!="string"||!u)return;const p=l[oe];return{docJson:typeof p=="string"?p:de(p??{}),row:u,tableName:a}}},yn=(e,t)=>{const s=[...new Set(e)],f=new Map;if(s.length===0)return f;const h=Tt(t);for(let l=0;l<h.length;l+=me){const a=h.slice(l,l+me),u=Math.floor(me/a.length),p=Bn(c`${c.identifier("id")}`,s,!1,u),v=a.map(m=>c`SELECT ${c.raw(`'${m.replaceAll("'","''")}'`)} AS __t__, id FROM ${c.identifier(m)} WHERE ${p}`);for(const m of j(d,ft(v))){const{id:k,__t__:S}=m;typeof S=="string"&&typeof k=="string"&&f.set(k,S)}}return f},At={assertRankPartitionLocal:vt,ensureRankBackfilled:Ye,onRead:C,rowToDocument:Se,schema:i,sql:d},H={system:wn,async aggregate(e,t){const s=Q(e,"aggregate");if(s)return C(e,G),s.aggregate(e,t);const f=i.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);if(We(t.op),t.op==="count")return H.count(e,{baseWhere:t.baseWhere,relationBaseWhere:t.relationBaseWhere,restrictsCounts:t.restrictsCounts,where:t.where});if(!t.field)throw new $("INTERNAL",`aggregate(${e}, { op: "${t.op}" }): "field" is required for non-count reducers`);C(e,G);const h=ue(f.softDeleteMode,void 0),l=N(N(t.baseWhere,t.where),h),a=await Ie(l,e,t.relationBaseWhere),u=a!==l;if(f.aggregateIndexes&&!t.baseWhere&&!u&&(!h||jt(f,[t.field]))){const U=In(f.aggregateIndexes,t.op,t.field,t.where);if(U){Je(e,U.index);const I=Ze(U.index.by??[],U.key),K=Xe(e,U.index.name),V=j(d,c`SELECT ${Be} AS value, ${nt} AS count FROM ${c.identifier(K)} WHERE ${Pe} = ${I}`).toArray()[0];return et(t.op,V)}}Kt(f,t.field,`aggregate(${e}, { op: "${t.op}", field: "${t.field}" })`);const p=te(a,Ee),v=We(t.op),m=ce(t.field);let k=c`SELECT ${c.raw(v)}(${m}) AS value FROM ${c.identifier(e)}`;p&&(k=c`${k} WHERE ${p}`);const B=j(d,k).toArray()[0]?.value;return B??null},asId(e,t){const s=Qt(i,e,t);if(s===null)throw new $("BAD_REQUEST",`asId("${e}", …): "${t}" is not a valid id for table "${e}"`,{status:400});return s},async count(e,t){const s=Q(e,"count");if(s)return C(e,G),s.count(e,t);const f=i.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);const h=vn(t);if(h.restrictsCounts)throw new tt(e);C(e,G);const l=ue(f.softDeleteMode,void 0),a=N(N(h.baseWhere,h.where),l),u=await Ie(a,e,h.relationBaseWhere),p=u!==a;if(f.aggregateIndexes&&!h.baseWhere&&!p&&!l){const S=An(f.aggregateIndexes,h.where);if(S){Je(e,S.index);const B=Ze(S.index.by??[],S.key),U=Xe(e,S.index.name),I=j(d,c`SELECT ${Be} AS value FROM ${c.identifier(U)} WHERE ${Pe} = ${B}`).toArray();return I[0]===void 0?0:I[0].value??0}}const v=te(u,Ee);let m=c`SELECT COUNT(*) AS count FROM ${c.identifier(e)}`;return v&&(m=c`${m} WHERE ${v}`),j(d,m).one().count},async delete(e,t,s){const f=se(e,t);if(!f){const m=$e(t);m&&(y(void 0),await m.delete(e,t,s));return}const{docJson:h,row:l,tableName:a}=f,u=i.tables[a],p=s?.hard===!0,v=!p&&u?.softDeleteMode?u.softDeleteMode.field:void 0;if(!(v&&l[v]!==null&&l[v]!==void 0)){if(Z(a,"before","delete")&&await ee("before","delete",{id:e,op:"delete",previous:l,table:a}),await oo({deletedId:e,deletedReference:m=>l[m],findHolders:async(m,k,S)=>(await Ve(m).findMany(m,{includeDeleted:p,where:{[k]:S}})).page,onCascade:(m,k)=>Ve(m).delete(k,void 0,s),onRestrict:m=>{throw new Re(m,"restrict")},onSetNull:(m,k,S)=>Ve(m).patch(k,{[S]:null}),schema:i,tableName:a}),pe(a),ge(a),v){const m={...l,...g(a),[v]:F(),_id:e};He(d,a,Ht(a),[de(m),e,h]),Me(a,e,m,l),be(a,e,void 0),xe(a,l,m),ye(a,e,l,void 0),D?.invalidate(a,e,b(a,l,m)),we(a,e,"update",m),w({indexKeys:b(a,l,m),key:e,op:"update",row:m,table:a}),Z(a,"after","delete")&&await ee("after","delete",{id:e,op:"delete",previous:l,table:a}),await A({id:e,op:"delete",table:a});return}He(d,a,Do(a),[e,h]),Me(a,e,void 0),be(a,e,void 0),xe(a,l,void 0),ye(a,e,l,void 0),D?.invalidate(a,e,b(a,l)),we(a,e,"delete"),w({indexKeys:b(a,l),key:e,op:"delete",table:a}),Z(a,"after","delete")&&await ee("after","delete",{id:e,op:"delete",previous:l,table:a}),await A({id:e,op:"delete",table:a})}},async deleteAll(e,t){if(!i.tables[e])throw new $("INTERNAL",`unknown table: ${e}`);const s=Math.max(1,t?.chunkSize??dn),f=t?.hard===void 0?void 0:{hard:t.hard},h=ie(e)?void 0:e;let l=0;return await M(async()=>{for(;;){const u=(await H.findMany(e,{limit:s})).page.map(p=>String(p._id));if(u.length===0)break;for(const p of u)await H.delete(p,h,f),l+=1;if(u.length<s)break}}),{deleted:l}},async deleteMany(e,t,s){le(e.length,t?.limit,"deleteMany");for(const f of e)await H.delete(f,s);return{deleted:e.length}},async deleteWhere(e,t,s){const l=(await(Q(e,"deleteWhere")??H).findMany(e,{where:t})).page.map(a=>String(a._id));if(le(l.length,s?.limit,"deleteWhere"),H.deleteMany===void 0)throw new $("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return H.deleteMany(l,s)},async findFirst(e,t={}){return(await H.findMany(e,{...t,limit:1,omitContinueCursor:!0})).page[0]??null},async findFirstOrThrow(e,t={}){const s=await H.findFirst(e,t);if(s===null)throw new Gn(`findFirstOrThrow: no "${e}" document matched`);return s},async findMany(e,t={}){const s=Q(e,"findMany");if(s)return C(e,G),s.findMany(e,t);const f=i.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);const h=!t.where&&!t.baseWhere;h?C(e,G):C(e);const l=ct(t.orderBy,f.shape,{pinned:Kn(t.where),uniqueBy:on(f.indexes,f.shape)}),a=t.cursor?rn(l,at(t.cursor)):void 0;let u=N(t.baseWhere,t.where);u=N(u,ue(f.softDeleteMode,t.includeDeleted)),u=await qt(u,{canPushExists:mt?gn:void 0,existsPushMode:$t==="always"?"always":"auto",fetcher:yt,maxRelationKeys:Et,relationBaseWhere:t.relationBaseWhere,schema:i,tableName:e}),a&&(u=u?{AND:[u,a]}:a);const p=mt?zo(C):wt,v=te(u,p,je),m=typeof t.limit=="number"?Math.max(0,Math.floor(t.limit)):void 0,k=sn(e,v,cn(l),m===void 0?void 0:m+1),S=ve(d,k.text,...k.params).toArray();h&&!R&&T?.recordRead(S.length);const B=[];for(const V of S){const O=Se(V);O&&(B.push(O),!h&&typeof O._id=="string"&&C(e,O._id))}if(m===void 0)return t.with&&await Wt({groupedCounter:St,fetcher:ze,parents:B,...Bt(t),schema:i,tableName:e,with:t.with}),{continueCursor:null,isDone:!0,page:Mt(B,t.select,t.with)};const U=B.length>m,I=U?B.slice(0,m):B,K=I.at(-1);return t.with&&await Wt({fetcher:ze,groupedCounter:St,parents:I,...Bt(t),schema:i,tableName:e,with:t.with}),{continueCursor:U&&K&&t.omitContinueCursor!==!0?Ge(K,l):null,isDone:!U,page:Mt(I,t.select,t.with)}},async get(e,t){const s=se(e,t);if(!s){const f=$e(t);return f?f.get(e,t):null}return C(s.tableName,e),s.row},async lookupById(e,t){const s=se(e,t);return s?(C(s.tableName,e),{row:s.row,tableName:s.tableName}):null},async groupBy(e,t){const s=Q(e,"groupBy");if(s)return C(e,G),s.groupBy(e,t);const f=i.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);C(e,G);const h=t.agg??{op:"count"};if(We(h.op),h.op!=="count"&&!h.field)throw new $("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);const l=ue(f.softDeleteMode,void 0),a=N(N(t.baseWhere,t.where),l),u=await Ie(a,e,t.relationBaseWhere),p=u!==a,v=[...t.by,h.field];if(f.aggregateIndexes&&!t.baseWhere&&!p&&(!l||jt(f,v))){const I=Tn(f.aggregateIndexes,h.op,h.field,t.by,t.where),K=I===void 0?0:Object.keys(I.partial).length,V=I?.index.by?.length??0;if(I&&(K===0||K===V)){Je(e,I.index);const O=Xe(e,I.index.name),De=Object.keys(I.partial),ke=[];if(De.length===(I.index.by??[]).length&&De.length>0){const Fe=Ze(I.index.by??[],I.partial),Le=j(d,c`SELECT ${Be} AS value, ${nt} AS count FROM ${c.identifier(O)} WHERE ${Pe} = ${Fe}`).toArray();return Le.length>0&&ke.push({key:{...I.partial},value:et(h.op,Le[0])}),ke}const mn=j(d,c`SELECT ${Pe} AS key, ${Be} AS value, ${nt} AS count FROM ${c.identifier(O)}`).toArray();for(const Fe of mn){const Le=_n(JSON.parse(Fe.key));ke.push({key:Le,value:et(h.op,Fe)})}return ke}}for(const I of v){if(I===void 0)continue;const K=I===h.field?`groupBy(${e}, { agg: { op: "${h.op}", field: "${I}" } })`:`groupBy(${e}, { by: [..."${I}"] })`;Kt(f,I,K)}const m=te(u,Ee),k=t.by.map(I=>c`${ce(I)} AS ${c.identifier(I)}`);if(h.op==="count")k.push(c`COUNT(*) AS value`);else{const{field:I}=h;if(I===void 0)throw new $("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);k.push(c`${c.raw(We(h.op))}(${ce(I)}) AS value`)}let S=c`SELECT ${c.join(k,c`, `)} FROM ${c.identifier(e)}`;m&&(S=c`${S} WHERE ${m}`),S=c`${S} GROUP BY ${c.join(t.by.map(I=>ce(I)),c`, `)}`;const B=j(d,S).toArray(),U=[];for(const I of B){const K={};for(const O of t.by)K[O]=Ln(f.shape[O],I[O]??null);const{value:V}=I;U.push({key:K,value:V==null?null:Number(V)})}return U},async insert(e,t,s){const f=Q(e,"insert");if(f)return gt(f,e,t,s,!0);const h=i.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);const l=Vt(h,t,re);rt(h,l);let a;s?.clientId!==void 0?(Bo(s.clientId),a=s.clientId):s?.allowExplicitId&&typeof l._id=="string"?a=l._id:a=X();const u=s?.allowExplicitId&&typeof l._creationTime=="number"?l._creationTime:F(),p={...l,...g(e),_creationTime:u,_id:a};return Z(e,"before","insert")&&await ee("before","insert",{doc:{...p},id:a,op:"insert",table:e}),pe(e),ge(e),lt(d,e,bo(e),[a,u,de(p)]),Rt(e,a,p),Z(e,"after","insert")&&await ee("after","insert",{doc:p,id:a,op:"insert",table:e}),await A({doc:p,id:a,op:"insert",table:e}),a},async insertManyUnsafe(e,t,s){if(le(t.length,s?.limit,"insertManyUnsafe"),t.length===0)return[];const f=Q(e,"insert");if(f){const u=[];for(const p of t)y(p);for(const p of t){const v=await f.insert(e,p,{allowExplicitId:s?.allowExplicitId});w({key:v,op:"insert",row:{...p,_id:v},table:e}),u.push(v)}return u}const h=i.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);pe(e),ge(e);const l=[];for(let u=0;u<t.length;u+=Ue)l.push(g(e));const a=t.map((u,p)=>{const v=Vt(h,u,re),m=s?.allowExplicitId===!0&&typeof v._id=="string"?v._id:X(),k=s?.allowExplicitId===!0&&typeof v._creationTime=="number"?v._creationTime:F(),S={...v,...l[Math.floor(p/Ue)],_creationTime:k,_id:m};return{creationTime:k,document:S,id:m}});for(const u of a)y(u.document);for(let u=0;u<a.length;u+=Ue){const p=c.join(a.slice(u,u+Ue).map(m=>c`(${m.id}, ${m.creationTime}, ${de(m.document)})`),c`, `),v=tn("sqlite",c`INSERT INTO ${c.identifier(e)} (id, _creationTime, ${c.identifier(oe)}) VALUES ${p}`);lt(d,e,v.sql,v.params)}for(const{document:u,id:p}of a)Rt(e,p,u),await Y({doc:u,id:p,op:"insert",table:e});return a.map(u=>u.id)},async insertMany(e,t,s){le(t.length,s?.limit,"insertMany");const f=s?.skipDuplicates===!0,h=[],l=Q(e,"insert");if(l)for(const u of t)y(u);const a=async u=>l?gt(l,e,u,void 0,!1):H.insert(e,u);for(const u of t)try{h.push(await a(u))}catch(p){if(f&&p instanceof Re&&p.kind==="unique")h.push(null);else throw p}return h},normalizeId(e,t){return Qt(i,e,t)},async patch(e,t,s){const f=se(e,s);if(!f){const v=$e(s);if(v){y(t),await v.patch(e,t,s);return}throw new $("NOT_FOUND",`document not found: ${e}`)}const{docJson:h,row:l,tableName:a}=f,u=i.tables[a];if(!u)throw new $("INTERNAL",`unknown table: ${a}`);if(C(a,e),Jt("patch",t),pn(a,e,t,l)){o?.({fields:Object.keys(st(t)),id:e,table:a});return}const p={...l,...st(t),...g(a),_id:e};zt(u,t,p,re),rt(u,p,!0),Z(a,"before","update")&&await ee("before","update",{doc:{...p},id:e,op:"update",previous:l,table:a}),pe(a),ge(a),He(d,a,Ht(a),[de(p),e,h]),Me(a,e,p,l),be(a,e,p),xe(a,l,p),ye(a,e,l,p),D?.invalidate(a,e,b(a,l,p)),we(a,e,"update",p),w({indexKeys:b(a,l,p),key:e,op:"update",row:p,table:a}),Z(a,"after","update")&&await ee("after","update",{doc:p,id:e,op:"update",previous:l,table:a}),await A({doc:p,id:e,op:"update",table:a})},async patchMany(e,t,s){le(e.length,t?.limit,"patchMany");for(const f of e)await H.patch(f.id,f.patch,s);return{patched:e.length}},async patchWhere(e,t,s){const l=(await(Q(e,"patchWhere")??H).findMany(e,{where:t.where})).page.map(a=>({id:String(a._id),patch:t.patch}));if(le(l.length,s?.limit,"patchWhere"),H.patchMany===void 0)throw new $("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await H.patchMany(l,s),{patched:l.length}},async related(e,t){return no(H,_,e,t)},relationEdges:_,query(e){const t=Q(e,"query");return t?(C(e,G),t.query(e)):hn(d,i,e,ne,s=>{s?P(s):C(e,G)},s=>{R||T?.recordRead(s)})},async rank(e,t,s){const f=Q(e,"rank");if(f)return C(e,G),f.rank(e,t,s);ne(e,t,"rank");const h=i.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);const l=h.rankIndexes?.find(O=>O.name===t);if(!l)throw new $("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(vt(e,h,l),s.restrictsCounts)throw new tt(e);C(e,G),Ye(e,l);const a=typeof s.row=="string"?s.row:s.row._id;if(!a)return null;const u=Dt(e,l.name),p=l.sortBy.map((O,De)=>kt(De)),v=p.map(O=>Te(O)).join(", "),m=j(d,c`SELECT ${c.identifier("__partition__")}, ${c.raw(v)} FROM ${c.identifier(u)} WHERE ${c.identifier("__id__")} = ${a}`).toArray(),[k]=m;if(k===void 0)return null;let S=k.__partition__;const B=N(s.baseWhere,s.where);ot(B,i,e,"rank");const U=Qn(l,B);if(U){const O=Vn(l.partitionBy??[],U);if(O!==S)return null;S=O}const I=p.map(O=>k[O]),{before:K,total:V}=Xt(d,u,p,l.sortBy,S,I,a);return{position:K+1,total:V}},async rankBefore(e,t,s){if(ie(e))throw new $("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const f=i.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);const h=f.rankIndexes?.find(p=>p.name===t);if(!h)throw new $("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(s.restrictsCounts)throw new tt(e);C(e,G),Ye(e,h);const l=Dt(e,h.name),a=h.sortBy.map((p,v)=>kt(v)),u=h.sortBy.map((p,v)=>ae(s.sortValues[v]??null));return Xt(d,l,a,h.sortBy,s.partitionKey,u,s.rowId)},async rankPage(e,t,s={}){ot(N(s.baseWhere,s.where),i,e,"rankPage");const f=Q(e,"rankPage");if(f)return C(e,G),f.rankPage(e,t,s);ne(e,t,"rank");const{continueCursor:h,hasMore:l,rows:a}=xt(At,e,t,s);return{continueCursor:h,isDone:!l,page:a.map(u=>u.doc)}},async rankPageRows(e,t,s={}){ot(N(s.baseWhere,s.where),i,e,"rankPage"),ne(e,t,"rank");const{directions:f,hasMore:h,rows:l}=xt(At,e,t,s);return{directions:f,hasMore:h,rows:l}},async restore(e,t){const s=se(e,t);if(!s){const l=$e(t);if(l?.restore){await l.restore(e,t);return}throw new $("NOT_FOUND",`document not found: ${e}`)}const f=i.tables[s.tableName]?.softDeleteMode?.field;if(!f)throw new $("INTERNAL",`ctx.db.restore: table "${s.tableName}" is not a .softDelete() table`);const h=s.row[f]!==null&&s.row[f]!==void 0;await H.patch(e,{[f]:null},t),h&&ye(s.tableName,e,void 0,s.row)},async replace(e,t,s,f){const h=se(e,s);if(!h){const B=$e(s);if(B){y(t),await B.replace(e,t,s,f);return}throw new $("NOT_FOUND",`document not found: ${e}`)}const{docJson:l,row:a,tableName:u}=h,p=i.tables[u];if(!p)throw new $("INTERNAL",`unknown table: ${u}`);Jt("replace",t);const v=f?.allowExplicitId&&typeof t._creationTime=="number"?t._creationTime:void 0,m=typeof a._creationTime=="number"?a._creationTime:void 0,k=v??m??F(),S={...t,...g(u),_creationTime:k,_id:e};zt(p,t,S,re),rt(p,S),Z(u,"before","update")&&await ee("before","update",{doc:{...S},id:e,op:"update",previous:a,table:u}),pe(u),ge(u),He(d,u,Mo(u),[k,de(S),e,l]),Me(u,e,S,a),be(u,e,S),xe(u,a,S),ye(u,e,a,S),D?.invalidate(u,e,b(u,a,S)),we(u,e,"update",S),w({indexKeys:b(u,a,S),key:e,op:"update",row:S,table:u}),Z(u,"after","update")&&await ee("after","update",{doc:S,id:e,op:"update",previous:a,table:u}),await A({doc:S,id:e,op:"update",table:u})},async wipeShard(e){const t=new Set(e?.exclude),s=e?.tables,f=Object.entries(i.tables).filter(([u,p])=>t.has(u)||s!==void 0&&!s.includes(u)?!1:p.shardMode?.kind!=="global").map(([u])=>u);if(s!==void 0){for(const u of s)if(!i.tables[u])throw new $("INTERNAL",`wipeShard: unknown table: ${u}`)}const h={};let l=0;const{deleteAll:a}=H;if(a===void 0)throw new $("INTERNAL","wipeShard: this writer has no deleteAll");for(const u of f){const p=await a(u,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});h[u]=p.deleted,l+=p.deleted}return{deleted:l,tables:h}}},$n={db:H,scheduler:he};return n.enforceRls===!0?io(H,i,(e,t)=>se(e,t)?.tableName,(e,t)=>yn(e,t),_):H};export{Qr as CDC_LOG_TABLE,pi as IDEMPOTENCY_TABLE,Jo as NotUniqueError,ui as advanceClientWatermark,Vr as applyCdcChanges,Jt as assertNoExplicitUndefined,Bo as assertValidClientId,Gr as backfillAggregateIndexes,Nr as backfillRankIndexes,jr as backfillSearchIndexes,zr as bumpCdcEpoch,Jr as cdcCanVouchFor,Yr as cdcForkedError,Xr as cdcSeqLeavingRows,Zr as cdcTouchesTables,ei as cdcTrimmedError,ti as compactCdcDocs,Ur as createShardCtxDb,ni as cursorBelowRetainedFloor,fi as migrateClientWatermark,oi as minCdcReplayableSeq,ri as minCdcSeq,Qt as normalizeIdStructurally,ii as readCdcChangeKeys,si as readCdcChanges,ci as readCdcCursor,ai as readCdcEpoch,hi as readClientWatermark,gi as readIdempotent,Ei as runShardMigrations,_i as selectShapeMembers,Ri as selectShapeRows,st as stripReservedPatchFields,di as trimCdcChanges,yi as trimIdempotent,$i as writeIdempotent};
@@ -1,4 +1,4 @@
1
- import{runSql as o,orNull as a,decodeJsonColumn as _}from"./runDrizzle-BlpM0R9P.mjs";const s="__lunora_queue_messages",n=500,E=128*1024,T="… [truncated by the dev queue catcher]",c="[unserializable message body]",R=e=>{if(e===void 0)return"null";try{const r=JSON.stringify(e);return r.length>E?JSON.stringify(`${r.slice(0,E)}${T}`):r}catch{return JSON.stringify(c)}},g=e=>typeof e=="string"&&(e===c||e.endsWith(T)),u=e=>{o(e,`CREATE TABLE IF NOT EXISTS "${s}" (
1
+ import{runSql as o,orNull as a,decodeJsonColumn as _}from"./runDrizzle-Du5HLitO.mjs";const s="__lunora_queue_messages",n=500,E=128*1024,T="… [truncated by the dev queue catcher]",c="[unserializable message body]",R=e=>{if(e===void 0)return"null";try{const r=JSON.stringify(e);return r.length>E?JSON.stringify(`${r.slice(0,E)}${T}`):r}catch{return JSON.stringify(c)}},g=e=>typeof e=="string"&&(e===c||e.endsWith(T)),u=e=>{o(e,`CREATE TABLE IF NOT EXISTS "${s}" (
2
2
  id TEXT PRIMARY KEY,
3
3
  captured_at INTEGER NOT NULL,
4
4
  message_id TEXT NOT NULL,
@@ -1,4 +1,4 @@
1
- import{sql as t}from"drizzle-orm";import{runDrizzle as o}from"./runDrizzle-BlpM0R9P.mjs";const a="__reactor_state",c=[["runs","runs INTEGER NOT NULL DEFAULT 0"],["suppressed","suppressed INTEGER NOT NULL DEFAULT 0"],["errors","errors INTEGER NOT NULL DEFAULT 0"],["last_ran_at","last_ran_at INTEGER NOT NULL DEFAULT 0"],["last_error","last_error TEXT"]],O=r=>{o(r,t`CREATE TABLE IF NOT EXISTS ${t.identifier(a)} (
1
+ import{sql as t}from"drizzle-orm";import{runDrizzle as o}from"./runDrizzle-Du5HLitO.mjs";const a="__reactor_state",c=[["runs","runs INTEGER NOT NULL DEFAULT 0"],["suppressed","suppressed INTEGER NOT NULL DEFAULT 0"],["errors","errors INTEGER NOT NULL DEFAULT 0"],["last_ran_at","last_ran_at INTEGER NOT NULL DEFAULT 0"],["last_error","last_error TEXT"]],O=r=>{o(r,t`CREATE TABLE IF NOT EXISTS ${t.identifier(a)} (
2
2
  path TEXT PRIMARY KEY,
3
3
  digest TEXT NOT NULL,
4
4
  tables TEXT NOT NULL,
@@ -1 +1 @@
1
- import{LunoraError as h}from"@lunora/errors";import{mergeWhere as I}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{decodeCursor as S,CURSOR_PREFIX as v,toBase64 as B}from"./CURSOR_PREFIX-Bn8SFoGd.mjs";const O=4,C=1,L=50,$=200,T=1e4,x=.5,D=t=>{if(t.kind==="id"){const e=t._meta?.tableName;return typeof e=="string"&&e.length>0?{array:!1,targetTable:e}:void 0}if(t.kind!=="array"&&t.kind!=="optional")return;const n=t._meta?.inner,r=n===void 0?void 0:D(n);if(r!==void 0)return{array:r.array||t.kind==="array",targetTable:r.targetTable}},j=t=>{const n=[];for(const[r,e]of Object.entries(t.tables))for(const[s,o]of Object.entries(e.shape)){const a=D(o);a===void 0||t.tables[a.targetTable]===void 0||n.push({array:a.array,column:s,name:`${r}.${s}`,sourceTable:r,targetTable:a.targetTable})}return n},U=t=>v+B(JSON.stringify([t])),M=t=>{const[n]=S(t);if(typeof n!="number"||!Number.isInteger(n)||n<0)throw new h("BAD_REQUEST","invalid cursor");if(n>T)throw new h("BAD_REQUEST",`ctx.db.related: cursor offset ${String(n)} exceeds the maximum of ${String(T)} — narrow the walk with \`edges\` or \`direction\` instead of paging past it`);return n},k=(t,n,r,e)=>{if(t===void 0)return n;if(!Number.isInteger(t)||t<1||t>r)throw new h("BAD_REQUEST",`ctx.db.related: \`${e}\` must be an integer between 1 and ${String(r)}, got ${String(t)}`);return t},N=(t,n)=>{if(n===void 0)return[...t];const r=new Set(t.map(o=>o.name)),e=n.filter(o=>!r.has(o));if(e.length>0)throw new h("BAD_REQUEST",`ctx.db.related: unknown edge ${e.length===1?"name":"names"}: ${e.join(", ")}`);const s=new Set(n);return t.filter(o=>s.has(o.name))},W=(t,n)=>{const r=t[n.column];return n.array?Array.isArray(r)?r.filter(e=>typeof e=="string"&&e.length>0):[]:typeof r=="string"&&r.length>0?[r]:[]},A=async(t,n,r,e)=>{const s=await t.findMany(n,{limit:e.limit,omitContinueCursor:!0,where:I(r,e.relationBaseWhere?.(n))??r});return e.mask?.(n,s.page)??s.page},F={in:{keyColumn:t=>t.column,keysOf:(t,n)=>n.array||t.table!==n.targetTable?[]:[t.id],skipVisitedKeys:!1,table:t=>t.sourceTable},out:{keyColumn:()=>"_id",keysOf:(t,n)=>t.table===n.sourceTable?W(t.document,n):[],skipVisitedKeys:!0,table:t=>t.targetTable}},_=async(t,n,r,e,s)=>{const o=F[s],a=o.keyColumn(r),l=o.table(r),u=new Map;for(const c of n)for(const i of o.keysOf(c,r))!u.has(i)&&!(o.skipVisitedKeys&&e.visited.has(i))&&u.set(i,c);if(u.size===0)return[];const f=await A(t,l,{[a]:{in:[...u.keys()]}},e),m=[];for(const c of f){const i=c._id,g=c[a],d=typeof g=="string"?u.get(g):void 0;typeof i!="string"||d===void 0||e.visited.has(i)||(e.visited.add(i),m.push({document:c,id:i,path:[...d.path,r.name],pathIds:[...d.pathIds,i],table:l}))}return m},Q=async(t,n,r,e)=>{const s=[],o=()=>e.budget-s.length,a=()=>({limit:o(),mask:e.mask,relationBaseWhere:e.relationBaseWhere,visited:e.visited});for(const l of r)e.direction!=="in"&&o()>0&&s.push(...await _(t,n,l,a(),"out")),e.direction!=="out"&&o()>0&&s.push(...await _(t,n,l,a(),"in"));return s},H=async(t,n)=>{const r=n._id;if(typeof r=="string"&&r.length>0){const o=await t.lookupById?.(r);if(!o)throw new h("BAD_REQUEST","ctx.db.related: could not resolve the start document's table from its `_id` — pass `{ table, id }` instead");return{id:r,table:o.tableName}}const{id:e,table:s}=n;if(typeof s!="string"||s.length===0||typeof e!="string"||e.length===0)throw new h("BAD_REQUEST","ctx.db.related: `start` must be a loaded document or `{ table, id }`");return{id:e,table:s}},V=async(t,n,r,e={})=>{const s=k(e.depth,C,O,"depth"),o=k(e.limit,L,$,"limit"),a=e.cursor?M(e.cursor):0,l=e.direction??"both",u=N(n,e.edges),{id:f,table:m}=await H(t,r),[c]=await A(t,m,{_id:f},{limit:1,mask:e.relationMask,relationBaseWhere:e.relationBaseWhere,visited:new Set});if(c===void 0)throw new h("NOT_FOUND",`ctx.db.related: no "${m}" row with id ${f}`);const i=a+o+1,g=new Set([f]),d=[];let w=[{document:c,id:f,path:[],pathIds:[f],table:m}];for(let b=1;b<=s&&w.length>0&&d.length<i;b+=1){const p=await Q(t,w,u,{budget:i-d.length,direction:l,mask:e.relationMask,relationBaseWhere:e.relationBaseWhere,visited:g}),R=x**(b-1);for(const y of p)d.push({depth:b,document:y.document,path:y.path,pathIds:y.pathIds,score:R,table:y.table});w=p}const E=d.length<=a+o;return{continueCursor:E?null:U(a+o),isDone:E,nodes:d.slice(a,a+o)}};export{L as RELATED_DEFAULT_LIMIT,x as RELATED_DEPTH_DECAY,O as RELATED_MAX_DEPTH,$ as RELATED_MAX_LIMIT,T as RELATED_MAX_OFFSET,j as deriveRelationEdges,V as findRelated};
1
+ import{LunoraError as h}from"@lunora/errors";import{mergeWhere as I}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{decodeCursor as S,CURSOR_PREFIX as v,toBase64 as B}from"./CURSOR_PREFIX-BX8jkMJa.mjs";const O=4,C=1,L=50,$=200,T=1e4,x=.5,D=t=>{if(t.kind==="id"){const e=t._meta?.tableName;return typeof e=="string"&&e.length>0?{array:!1,targetTable:e}:void 0}if(t.kind!=="array"&&t.kind!=="optional")return;const n=t._meta?.inner,r=n===void 0?void 0:D(n);if(r!==void 0)return{array:r.array||t.kind==="array",targetTable:r.targetTable}},j=t=>{const n=[];for(const[r,e]of Object.entries(t.tables))for(const[s,o]of Object.entries(e.shape)){const a=D(o);a===void 0||t.tables[a.targetTable]===void 0||n.push({array:a.array,column:s,name:`${r}.${s}`,sourceTable:r,targetTable:a.targetTable})}return n},U=t=>v+B(JSON.stringify([t])),M=t=>{const[n]=S(t);if(typeof n!="number"||!Number.isInteger(n)||n<0)throw new h("BAD_REQUEST","invalid cursor");if(n>T)throw new h("BAD_REQUEST",`ctx.db.related: cursor offset ${String(n)} exceeds the maximum of ${String(T)} — narrow the walk with \`edges\` or \`direction\` instead of paging past it`);return n},k=(t,n,r,e)=>{if(t===void 0)return n;if(!Number.isInteger(t)||t<1||t>r)throw new h("BAD_REQUEST",`ctx.db.related: \`${e}\` must be an integer between 1 and ${String(r)}, got ${String(t)}`);return t},N=(t,n)=>{if(n===void 0)return[...t];const r=new Set(t.map(o=>o.name)),e=n.filter(o=>!r.has(o));if(e.length>0)throw new h("BAD_REQUEST",`ctx.db.related: unknown edge ${e.length===1?"name":"names"}: ${e.join(", ")}`);const s=new Set(n);return t.filter(o=>s.has(o.name))},W=(t,n)=>{const r=t[n.column];return n.array?Array.isArray(r)?r.filter(e=>typeof e=="string"&&e.length>0):[]:typeof r=="string"&&r.length>0?[r]:[]},A=async(t,n,r,e)=>{const s=await t.findMany(n,{limit:e.limit,omitContinueCursor:!0,where:I(r,e.relationBaseWhere?.(n))??r});return e.mask?.(n,s.page)??s.page},F={in:{keyColumn:t=>t.column,keysOf:(t,n)=>n.array||t.table!==n.targetTable?[]:[t.id],skipVisitedKeys:!1,table:t=>t.sourceTable},out:{keyColumn:()=>"_id",keysOf:(t,n)=>t.table===n.sourceTable?W(t.document,n):[],skipVisitedKeys:!0,table:t=>t.targetTable}},_=async(t,n,r,e,s)=>{const o=F[s],a=o.keyColumn(r),l=o.table(r),u=new Map;for(const c of n)for(const i of o.keysOf(c,r))!u.has(i)&&!(o.skipVisitedKeys&&e.visited.has(i))&&u.set(i,c);if(u.size===0)return[];const f=await A(t,l,{[a]:{in:[...u.keys()]}},e),m=[];for(const c of f){const i=c._id,g=c[a],d=typeof g=="string"?u.get(g):void 0;typeof i!="string"||d===void 0||e.visited.has(i)||(e.visited.add(i),m.push({document:c,id:i,path:[...d.path,r.name],pathIds:[...d.pathIds,i],table:l}))}return m},Q=async(t,n,r,e)=>{const s=[],o=()=>e.budget-s.length,a=()=>({limit:o(),mask:e.mask,relationBaseWhere:e.relationBaseWhere,visited:e.visited});for(const l of r)e.direction!=="in"&&o()>0&&s.push(...await _(t,n,l,a(),"out")),e.direction!=="out"&&o()>0&&s.push(...await _(t,n,l,a(),"in"));return s},H=async(t,n)=>{const r=n._id;if(typeof r=="string"&&r.length>0){const o=await t.lookupById?.(r);if(!o)throw new h("BAD_REQUEST","ctx.db.related: could not resolve the start document's table from its `_id` — pass `{ table, id }` instead");return{id:r,table:o.tableName}}const{id:e,table:s}=n;if(typeof s!="string"||s.length===0||typeof e!="string"||e.length===0)throw new h("BAD_REQUEST","ctx.db.related: `start` must be a loaded document or `{ table, id }`");return{id:e,table:s}},V=async(t,n,r,e={})=>{const s=k(e.depth,C,O,"depth"),o=k(e.limit,L,$,"limit"),a=e.cursor?M(e.cursor):0,l=e.direction??"both",u=N(n,e.edges),{id:f,table:m}=await H(t,r),[c]=await A(t,m,{_id:f},{limit:1,mask:e.relationMask,relationBaseWhere:e.relationBaseWhere,visited:new Set});if(c===void 0)throw new h("NOT_FOUND",`ctx.db.related: no "${m}" row with id ${f}`);const i=a+o+1,g=new Set([f]),d=[];let w=[{document:c,id:f,path:[],pathIds:[f],table:m}];for(let b=1;b<=s&&w.length>0&&d.length<i;b+=1){const p=await Q(t,w,u,{budget:i-d.length,direction:l,mask:e.relationMask,relationBaseWhere:e.relationBaseWhere,visited:g}),R=x**(b-1);for(const y of p)d.push({depth:b,document:y.document,path:y.path,pathIds:y.pathIds,score:R,table:y.table});w=p}const E=d.length<=a+o;return{continueCursor:E?null:U(a+o),isDone:E,nodes:d.slice(a,a+o)}};export{L as RELATED_DEFAULT_LIMIT,x as RELATED_DEPTH_DECAY,O as RELATED_MAX_DEPTH,$ as RELATED_MAX_LIMIT,T as RELATED_MAX_OFFSET,j as deriveRelationEdges,V as findRelated};
@@ -1 +1 @@
1
- import{LunoraError as R}from"@lunora/errors";import{findRelated as m}from"./RELATED_DEFAULT_LIMIT-B9PH28Pn.mjs";const M=Symbol.for("lunora.ctxdb.rls-unwrap");class S extends R{table;constructor(n){super("RLS_REQUIRED",`ctx.db access to "${n}" is denied: the schema is marked .rls("required"), so this table is protected. Apply RLS with .use(rls(policies)) in the procedure, or mark the table .public() to opt it out.`,{name:"RlsRequiredError"}),this.table=n}}const b=a=>Object.entries(a.tables).filter(([,n])=>n.shardMode?.kind!=="global").map(([n])=>n),E=(a,n,l)=>{const d=n?.tables,u=new Set(n?.exclude);for(const o of a)(d===void 0||d.includes(o))&&!u.has(o)&&l(o)},y={aggregate:"loop-gated",asId:"ungated",cdcChangedTables:"ungated",count:"loop-gated",delete:"id-gated",deleteAll:"loop-gated",deleteMany:"id-gated",deleteWhere:"inline-table-gated",findFirst:"loop-gated",findFirstOrThrow:"loop-gated",findMany:"loop-gated",get:"id-gated",groupBy:"loop-gated",insert:"loop-gated",insertMany:"loop-gated",insertManyUnsafe:"loop-gated",lookupById:"id-gated",normalizeId:"ungated",patch:"id-gated",patchMany:"id-gated",patchWhere:"inline-table-gated",query:"loop-gated",rank:"loop-gated",rankBefore:"loop-gated",rankPage:"loop-gated",rankPageRows:"loop-gated",related:"rebound",relationEdges:"ungated",replace:"id-gated",restore:"id-gated",system:"ungated",wipeShard:"sweep-gated"},O=Object.entries(y).filter(([,a])=>a==="loop-gated").map(([a])=>a),W={related:(a,n)=>(...l)=>{const[d,u]=l;return m(a,n,d,u)}},k=Object.entries(y).filter(([,a])=>a==="rebound").map(([a])=>a),v=(a,n,l)=>{for(const d of k)typeof n[d]=="function"&&(a[d]=W[d](a,l))},_=(a,n,l,d,u=[])=>{if(n.rlsMode!=="required")return a;const o=a,p=e=>{const t=n.tables[e];return t!==void 0&&t.isPublic!==!0},i=e=>{if(p(e))throw new S(e)},c=async(e,t)=>{if(t!==void 0){i(t);return}const r=await l(e);r!==void 0&&i(r)},f=async(e,t)=>{if(t!==void 0){i(t);return}if(!d){for(const s of e)await c(s,t);return}const r=await d([...new Set(e)],t);for(const s of e){const h=r.get(s);h!==void 0&&i(h)}},g={...a,delete:async(e,t,r)=>(await c(e,t),o.delete(e,t,r)),deleteMany:async(e,t,r)=>(await f(e,r),o.deleteMany(e,t,r)),deleteWhere:o.deleteWhere?async(e,t,r)=>(i(e),await o.deleteWhere?.(e,t,r)):void 0,get:async(e,t)=>(await c(e,t),o.get(e,t)),lookupById:async(e,t)=>(await c(e,t),o.lookupById?.(e,t)??null),patch:async(e,t,r)=>(await c(e,r),o.patch(e,t,r)),patchMany:async(e,t,r)=>(await f(e.map(s=>s.id),r),o.patchMany(e,t,r)),patchWhere:o.patchWhere?async(e,t,r)=>(i(e),await o.patchWhere?.(e,t,r)):void 0,replace:async(e,t,r,s)=>(await c(e,r),o.replace(e,t,r,s)),restore:async(e,t)=>(await c(e,t),o.restore?.(e,t))},w=o;for(const e of O){const t=w[e];typeof t=="function"&&(g[e]=(r,...s)=>(i(r),t.call(o,r,...s)))}if(v(g,o,u),o.wipeShard){const{wipeShard:e}=o;g.wipeShard=t=>(E(b(n),t,i),e.call(o,t))}return Object.defineProperty(g,M,{configurable:!0,enumerable:!1,value:a,writable:!1}),g};export{O as LOOP_GATED_METHODS,M as RLS_UNWRAP_SYMBOL,S as RlsRequiredError,y as WRITER_METHOD_GATING,_ as guardWriter};
1
+ import{LunoraError as R}from"@lunora/errors";import{findRelated as m}from"./RELATED_DEFAULT_LIMIT-CBYQQIrZ.mjs";const M=Symbol.for("lunora.ctxdb.rls-unwrap");class S extends R{table;constructor(n){super("RLS_REQUIRED",`ctx.db access to "${n}" is denied: the schema is marked .rls("required"), so this table is protected. Apply RLS with .use(rls(policies)) in the procedure, or mark the table .public() to opt it out.`,{name:"RlsRequiredError"}),this.table=n}}const b=a=>Object.entries(a.tables).filter(([,n])=>n.shardMode?.kind!=="global").map(([n])=>n),E=(a,n,l)=>{const d=n?.tables,u=new Set(n?.exclude);for(const o of a)(d===void 0||d.includes(o))&&!u.has(o)&&l(o)},y={aggregate:"loop-gated",asId:"ungated",cdcChangedTables:"ungated",count:"loop-gated",delete:"id-gated",deleteAll:"loop-gated",deleteMany:"id-gated",deleteWhere:"inline-table-gated",findFirst:"loop-gated",findFirstOrThrow:"loop-gated",findMany:"loop-gated",get:"id-gated",groupBy:"loop-gated",insert:"loop-gated",insertMany:"loop-gated",insertManyUnsafe:"loop-gated",lookupById:"id-gated",normalizeId:"ungated",patch:"id-gated",patchMany:"id-gated",patchWhere:"inline-table-gated",query:"loop-gated",rank:"loop-gated",rankBefore:"loop-gated",rankPage:"loop-gated",rankPageRows:"loop-gated",related:"rebound",relationEdges:"ungated",replace:"id-gated",restore:"id-gated",system:"ungated",wipeShard:"sweep-gated"},O=Object.entries(y).filter(([,a])=>a==="loop-gated").map(([a])=>a),W={related:(a,n)=>(...l)=>{const[d,u]=l;return m(a,n,d,u)}},k=Object.entries(y).filter(([,a])=>a==="rebound").map(([a])=>a),v=(a,n,l)=>{for(const d of k)typeof n[d]=="function"&&(a[d]=W[d](a,l))},_=(a,n,l,d,u=[])=>{if(n.rlsMode!=="required")return a;const o=a,p=e=>{const t=n.tables[e];return t!==void 0&&t.isPublic!==!0},i=e=>{if(p(e))throw new S(e)},c=async(e,t)=>{if(t!==void 0){i(t);return}const r=await l(e);r!==void 0&&i(r)},f=async(e,t)=>{if(t!==void 0){i(t);return}if(!d){for(const s of e)await c(s,t);return}const r=await d([...new Set(e)],t);for(const s of e){const h=r.get(s);h!==void 0&&i(h)}},g={...a,delete:async(e,t,r)=>(await c(e,t),o.delete(e,t,r)),deleteMany:async(e,t,r)=>(await f(e,r),o.deleteMany(e,t,r)),deleteWhere:o.deleteWhere?async(e,t,r)=>(i(e),await o.deleteWhere?.(e,t,r)):void 0,get:async(e,t)=>(await c(e,t),o.get(e,t)),lookupById:async(e,t)=>(await c(e,t),o.lookupById?.(e,t)??null),patch:async(e,t,r)=>(await c(e,r),o.patch(e,t,r)),patchMany:async(e,t,r)=>(await f(e.map(s=>s.id),r),o.patchMany(e,t,r)),patchWhere:o.patchWhere?async(e,t,r)=>(i(e),await o.patchWhere?.(e,t,r)):void 0,replace:async(e,t,r,s)=>(await c(e,r),o.replace(e,t,r,s)),restore:async(e,t)=>(await c(e,t),o.restore?.(e,t))},w=o;for(const e of O){const t=w[e];typeof t=="function"&&(g[e]=(r,...s)=>(i(r),t.call(o,r,...s)))}if(v(g,o,u),o.wipeShard){const{wipeShard:e}=o;g.wipeShard=t=>(E(b(n),t,i),e.call(o,t))}return Object.defineProperty(g,M,{configurable:!0,enumerable:!1,value:a,writable:!1}),g};export{O as LOOP_GATED_METHODS,M as RLS_UNWRAP_SYMBOL,S as RlsRequiredError,y as WRITER_METHOD_GATING,_ as guardWriter};
@@ -1,4 +1,4 @@
1
- import{sql as t}from"drizzle-orm";import{runDrizzle as a}from"./runDrizzle-BlpM0R9P.mjs";const o="__schedule_outbox",_=e=>{a(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(o)} (
1
+ import{sql as t}from"drizzle-orm";import{runDrizzle as a}from"./runDrizzle-Du5HLitO.mjs";const o="__schedule_outbox",_=e=>{a(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(o)} (
2
2
  id TEXT PRIMARY KEY,
3
3
  envelope_json TEXT NOT NULL,
4
4
  attempts INTEGER NOT NULL,
@@ -1,4 +1,4 @@
1
- import{quoteIdentifier as i}from"./quoteIdentifier-CObIFRhb.mjs";import{runSql as n}from"./runDrizzle-BlpM0R9P.mjs";const p="__lunora_schema_history",c=50,e=i(p),E=t=>({appliedAt:typeof t.applied_at=="number"?t.applied_at:0,hash:typeof t.hash=="string"?t.hash:"",seq:typeof t.seq=="number"?t.seq:0}),a=t=>{n(t,`CREATE TABLE IF NOT EXISTS ${e} (
1
+ import{quoteIdentifier as i}from"./quoteIdentifier-CObIFRhb.mjs";import{runSql as n}from"./runDrizzle-Du5HLitO.mjs";const p="__lunora_schema_history",c=50,e=i(p),E=t=>({appliedAt:typeof t.applied_at=="number"?t.applied_at:0,hash:typeof t.hash=="string"?t.hash:"",seq:typeof t.seq=="number"?t.seq:0}),a=t=>{n(t,`CREATE TABLE IF NOT EXISTS ${e} (
2
2
  hash TEXT PRIMARY KEY,
3
3
  seq INTEGER NOT NULL,
4
4
  snapshot_json TEXT NOT NULL,
@@ -1 +1 @@
1
- import{S as t,m as S,b as c,r as i,a as l,w as s}from"./ctx-db-search-state-z0OqNIGe.mjs";import"./runDrizzle-BlpM0R9P.mjs";export{t as SEARCH_STATE_TABLE,S as migrateSearchState,c as readBackfillState,i as readSearchBackfillState,l as readSearchIndexCoverage,s as writeSearchBackfillState};
1
+ import{S as t,m as S,b as c,r as i,a as l,w as s}from"./ctx-db-search-state-DVCp4JQf.mjs";import"./runDrizzle-Du5HLitO.mjs";export{t as SEARCH_STATE_TABLE,S as migrateSearchState,c as readBackfillState,i as readSearchBackfillState,l as readSearchIndexCoverage,s as writeSearchBackfillState};
@@ -1,4 +1,4 @@
1
- import{sql as o}from"drizzle-orm";import{runDrizzle as s}from"./runDrizzle-BlpM0R9P.mjs";import{WORKERD_SQLITE_LIMITS as d}from"./WORKERD_SQLITE_LIMITS-DlozcSQu.mjs";const c="__shape_poke_cursor",L=r=>{s(r,o`CREATE TABLE IF NOT EXISTS ${o.identifier(c)} (
1
+ import{sql as o}from"drizzle-orm";import{runDrizzle as s}from"./runDrizzle-Du5HLitO.mjs";import{WORKERD_SQLITE_LIMITS as d}from"./WORKERD_SQLITE_LIMITS-DBH23L_S.mjs";const c="__shape_poke_cursor",L=r=>{s(r,o`CREATE TABLE IF NOT EXISTS ${o.identifier(c)} (
2
2
  connection_id TEXT NOT NULL,
3
3
  sub_id TEXT NOT NULL,
4
4
  cursor INTEGER NOT NULL,
@@ -1 +1 @@
1
- import{isLunoraError as S}from"@lunora/errors";import{l as R,b as L}from"./ctx-db-search-state-z0OqNIGe.mjs";import{sql as e}from"drizzle-orm";import{readKeysetPage as _}from"./backfillAggregateIndexes-DBY2H269.mjs";import{runDrizzle as p}from"./runDrizzle-BlpM0R9P.mjs";import{h}from"./do-sql-DpyjVz_6.mjs";const u="__lunora_vector_backfill",m=50,k=20,w=20,N=3,O=i=>{p(i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(u)} (${e.identifier("companion")} TEXT PRIMARY KEY, ${e.identifier("cursor")} TEXT, ${e.identifier("done")} INTEGER NOT NULL DEFAULT 0, ${e.identifier("profile")} TEXT, ${e.identifier("strikes")} INTEGER NOT NULL DEFAULT 0)`);try{p(i,e`ALTER TABLE ${e.identifier(u)} ADD COLUMN ${e.identifier("strikes")} INTEGER NOT NULL DEFAULT 0`)}catch{}},C=(i,o)=>{const[s]=p(i,e`SELECT ${e.identifier("strikes")} FROM ${e.identifier(u)} WHERE ${e.identifier("companion")} = ${o}`).toArray();return s?.strikes??0},$=(i,o,s,d,t,r=0)=>{const n=s??null;p(i,e`INSERT INTO ${e.identifier(u)} (${e.identifier("companion")}, ${e.identifier("cursor")}, ${e.identifier("done")}, ${e.identifier("profile")}, ${e.identifier("strikes")}) VALUES (${o}, ${n}, ${d?1:0}, ${t}, ${r}) ON CONFLICT (${e.identifier("companion")}) DO UPDATE SET ${e.identifier("cursor")} = excluded.${e.identifier("cursor")}, ${e.identifier("done")} = excluded.${e.identifier("done")}, ${e.identifier("profile")} = excluded.${e.identifier("profile")}, ${e.identifier("strikes")} = excluded.${e.identifier("strikes")}`)},A=(i,o,s)=>{const d=_(i,o,s,m+1),t={documents:[],lastId:s,more:d.length>m,unparseable:[]};for(const r of d.slice(0,m)){if(typeof r.id!="string")continue;t.lastId=r.id;const n=h(r);n?t.documents.push({doc:n,id:t.lastId}):t.unparseable.push(t.lastId)}return t},D=(i,o,s,d,t)=>{const r=t instanceof Error?t.message:String(t),n=L(i,u,o),a=n.profile===d&&n.cursor===s?C(i,o):0;if(S(t)&&t.code==="SERVICE_UNAVAILABLE")return a>0&&$(i,o,s,!1,d,0),{error:r};const f=a+1;if(f<N)return $(i,o,s,!1,d,f),{error:r};const c=A(i,o,s),l=[...c.documents.map(E=>E.id),...c.unparseable];return console.warn(`[@lunora/shard-engine] vector backfill: a page of "${o}" failed ${String(f)} times in a row; its ${String(l.length)} row(s) are recorded as failed:`,t),{failedIds:l,page:c}},F=async(i,o,s,d,t)=>{const{profile:r,table:n}=o;try{const{failures:a,page:f}=await t(()=>A(i,n,s),async c=>({failures:await d(n,c.documents),page:c}));return a.length>0&&console.warn(`[@lunora/shard-engine] vector backfill: ${String(a.length)} row(s) of "${n}" could not be indexed:`,a),{failedIds:[...f.unparseable,...a.map(c=>c.id)],page:f}}catch(a){return D(i,n,s,r,a)}},y=async(i,o,s,d)=>{if(O(i),d.restart===!0)for(const{profile:n,table:a}of o)$(i,a,void 0,!1,n);const t=Math.min(d.maxPages??1,k),r={done:!1,failed:0,failedIds:[],pages:0,rows:0};for(const{profile:n,table:a}of o){const f=R(L(i,u,a),n);let{cursor:c}=f,l=f.finished;for(;!l;){if(r.pages>=t)return r;const E=await F(i,{profile:n,table:a},c,s,d.ordered);if("error"in E)return{...r,error:E.error};const{failedIds:g,page:T}=E,I=T.documents.length+T.unparseable.length;r.pages+=I>0?1:0,r.rows+=I,r.failed+=g.length,r.failedIds=[...r.failedIds,...g].slice(0,w),c=T.lastId,l=!T.more,$(i,a,c,l,n)}}return{...r,done:!0}};export{k as VECTOR_BACKFILL_MAX_PAGES,m as VECTOR_BACKFILL_PAGE_ROWS,y as backfillVectorIndexes};
1
+ import{isLunoraError as S}from"@lunora/errors";import{l as R,b as L}from"./ctx-db-search-state-DVCp4JQf.mjs";import{sql as e}from"drizzle-orm";import{readKeysetPage as _}from"./backfillAggregateIndexes-B_3xdOgV.mjs";import{runDrizzle as p}from"./runDrizzle-Du5HLitO.mjs";import{h}from"./do-sql-BEFrJUds.mjs";const u="__lunora_vector_backfill",m=50,k=20,w=20,N=3,O=i=>{p(i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(u)} (${e.identifier("companion")} TEXT PRIMARY KEY, ${e.identifier("cursor")} TEXT, ${e.identifier("done")} INTEGER NOT NULL DEFAULT 0, ${e.identifier("profile")} TEXT, ${e.identifier("strikes")} INTEGER NOT NULL DEFAULT 0)`);try{p(i,e`ALTER TABLE ${e.identifier(u)} ADD COLUMN ${e.identifier("strikes")} INTEGER NOT NULL DEFAULT 0`)}catch{}},C=(i,o)=>{const[s]=p(i,e`SELECT ${e.identifier("strikes")} FROM ${e.identifier(u)} WHERE ${e.identifier("companion")} = ${o}`).toArray();return s?.strikes??0},$=(i,o,s,d,t,r=0)=>{const n=s??null;p(i,e`INSERT INTO ${e.identifier(u)} (${e.identifier("companion")}, ${e.identifier("cursor")}, ${e.identifier("done")}, ${e.identifier("profile")}, ${e.identifier("strikes")}) VALUES (${o}, ${n}, ${d?1:0}, ${t}, ${r}) ON CONFLICT (${e.identifier("companion")}) DO UPDATE SET ${e.identifier("cursor")} = excluded.${e.identifier("cursor")}, ${e.identifier("done")} = excluded.${e.identifier("done")}, ${e.identifier("profile")} = excluded.${e.identifier("profile")}, ${e.identifier("strikes")} = excluded.${e.identifier("strikes")}`)},A=(i,o,s)=>{const d=_(i,o,s,m+1),t={documents:[],lastId:s,more:d.length>m,unparseable:[]};for(const r of d.slice(0,m)){if(typeof r.id!="string")continue;t.lastId=r.id;const n=h(r);n?t.documents.push({doc:n,id:t.lastId}):t.unparseable.push(t.lastId)}return t},D=(i,o,s,d,t)=>{const r=t instanceof Error?t.message:String(t),n=L(i,u,o),a=n.profile===d&&n.cursor===s?C(i,o):0;if(S(t)&&t.code==="SERVICE_UNAVAILABLE")return a>0&&$(i,o,s,!1,d,0),{error:r};const f=a+1;if(f<N)return $(i,o,s,!1,d,f),{error:r};const c=A(i,o,s),l=[...c.documents.map(E=>E.id),...c.unparseable];return console.warn(`[@lunora/shard-engine] vector backfill: a page of "${o}" failed ${String(f)} times in a row; its ${String(l.length)} row(s) are recorded as failed:`,t),{failedIds:l,page:c}},F=async(i,o,s,d,t)=>{const{profile:r,table:n}=o;try{const{failures:a,page:f}=await t(()=>A(i,n,s),async c=>({failures:await d(n,c.documents),page:c}));return a.length>0&&console.warn(`[@lunora/shard-engine] vector backfill: ${String(a.length)} row(s) of "${n}" could not be indexed:`,a),{failedIds:[...f.unparseable,...a.map(c=>c.id)],page:f}}catch(a){return D(i,n,s,r,a)}},y=async(i,o,s,d)=>{if(O(i),d.restart===!0)for(const{profile:n,table:a}of o)$(i,a,void 0,!1,n);const t=Math.min(d.maxPages??1,k),r={done:!1,failed:0,failedIds:[],pages:0,rows:0};for(const{profile:n,table:a}of o){const f=R(L(i,u,a),n);let{cursor:c}=f,l=f.finished;for(;!l;){if(r.pages>=t)return r;const E=await F(i,{profile:n,table:a},c,s,d.ordered);if("error"in E)return{...r,error:E.error};const{failedIds:g,page:T}=E,I=T.documents.length+T.unparseable.length;r.pages+=I>0?1:0,r.rows+=I,r.failed+=g.length,r.failedIds=[...r.failedIds,...g].slice(0,w),c=T.lastId,l=!T.more,$(i,a,c,l,n)}}return{...r,done:!0}};export{k as VECTOR_BACKFILL_MAX_PAGES,m as VECTOR_BACKFILL_PAGE_ROWS,y as backfillVectorIndexes};
@@ -0,0 +1 @@
1
+ import{LunoraError as f}from"@lunora/errors";import{sql as e}from"drizzle-orm";import{MySqlDialect as u}from"drizzle-orm/mysql-core";import{PgDialect as S}from"drizzle-orm/pg-core";import{SQLiteSyncDialect as p}from"drizzle-orm/sqlite-core";const d=new S,h=new u,m=new p,L={mysql:h,postgres:d,sqlite:m},i={boundParams:100,compoundSelect:5,likePattern:50,sqlTextLength:1e5},E=i.boundParams/2,$=t=>t===null||typeof t=="boolean"?!0:typeof t=="number"?Number.isFinite(t):typeof t=="string"&&t.isWellFormed(),g=t=>{const n=[];for(const r of t){if(!(r instanceof Uint8Array))return;n.push(Array.from(r,o=>o.toString(16).padStart(2,"0")).join(""))}return JSON.stringify(n)},D=(t,n)=>{const{params:r,sql:o}=L[t].sqlToQuery(n);return{params:r,sql:o}},y=t=>e`${t}`,w=t=>{if(t.length===0)throw new Error("unionAll: expected at least one branch");let n=[...t];for(;n.length>i.compoundSelect;){const r=[];for(let o=0;o<n.length;o+=i.compoundSelect){const s=e.join(n.slice(o,o+i.compoundSelect),e` UNION ALL `);r.push(e`SELECT * FROM (${s}) ${e.identifier("__u__")}`)}n=r}return e.join(n,e` UNION ALL `)},O=(t,n,r,o=E)=>{const s=r?e` NOT IN `:e` IN `,a=n.every(l=>$(l)),c=n.length>o&&!a?g(n):void 0;if(c!==void 0)return e`${t}${s}(SELECT unhex(${e.identifier("value")}) FROM json_each(${c}))`;if(n.length>o&&!a)throw new f("BAD_REQUEST",`an "in" list of ${String(n.length)} values holds a value JSON cannot carry (bytes, a non-finite number, or malformed text), so it cannot be bound as one parameter — and ${String(n.length)} placeholders exceed SQLite's per-statement cap of 100 on Durable Objects and D1. Narrow the list to ${String(o)} values or fewer.`);return n.length<=o?e`${t}${s}(${e.join(n.map(l=>y(l)),e`, `)})`:e`${t}${s}(SELECT ${e.identifier("value")} FROM json_each(${JSON.stringify(n)}))`};export{i as WORKERD_SQLITE_LIMITS,g as bytesAsHexJson,$ as isJsonSafe,y as param,D as renderSql,O as sqliteInList,w as unionAll};
@@ -0,0 +1,17 @@
1
+ import{sql as t}from"drizzle-orm";import{runDrizzle as o}from"./runDrizzle-Du5HLitO.mjs";const E="__stream_runs",i="__stream_chunks",N=r=>{o(r,t`CREATE TABLE IF NOT EXISTS ${t.identifier(E)} (
2
+ run_key TEXT PRIMARY KEY,
3
+ status TEXT NOT NULL,
4
+ last_seq INTEGER NOT NULL DEFAULT 0,
5
+ error_code TEXT,
6
+ error TEXT,
7
+ started_at REAL NOT NULL,
8
+ ttl_ms REAL NOT NULL
9
+ )`),o(r,t`CREATE TABLE IF NOT EXISTS ${t.identifier(i)} (
10
+ run_key TEXT NOT NULL,
11
+ seq INTEGER NOT NULL,
12
+ data_json TEXT NOT NULL,
13
+ PRIMARY KEY (run_key, seq)
14
+ )`)},_=(r,e)=>{const s=o(r,t`SELECT status, last_seq, error_code, error, started_at FROM ${t.identifier(E)} WHERE run_key = ${e} LIMIT 1`).toArray()[0];if(s!==void 0)return{...s.error===null?{}:{error:s.error},...s.error_code===null?{}:{errorCode:s.error_code},lastSeq:s.last_seq,startedAt:s.started_at,status:s.status}},T=(r,e)=>{o(r,t`DELETE FROM ${t.identifier(i)} WHERE run_key = ${e}`)},c=(r,e,n,s)=>_(r,e)!==void 0?!1:(T(r,e),o(r,t`INSERT INTO ${t.identifier(E)} (run_key, status, last_seq, started_at, ttl_ms)
15
+ VALUES (${e}, ${"running"}, 0, ${n}, ${s})`),!0),R=(r,e)=>{T(r,e),o(r,t`DELETE FROM ${t.identifier(E)} WHERE run_key = ${e}`)},m=(r,e,n,s)=>{o(r,t`INSERT OR IGNORE INTO ${t.identifier(i)} (run_key, seq, data_json) VALUES (${e}, ${n}, ${s})`)},A=(r,e,n)=>o(r,t`SELECT seq, data_json FROM ${t.identifier(i)} WHERE run_key = ${e} AND seq > ${n} ORDER BY seq ASC`).toArray().map(s=>({dataJson:s.data_json,seq:s.seq})),$=(r,e,n,s,a)=>{if(_(r,e)===void 0){T(r,e);return}const d=a?.code??null,u=a?.message??null;o(r,t`UPDATE ${t.identifier(E)}
16
+ SET status = ${n}, last_seq = ${s}, error_code = ${d}, error = ${u}
17
+ WHERE run_key = ${e}`)},f=(r,e,n)=>{const s=o(r,t`SELECT run_key FROM ${t.identifier(E)} WHERE started_at + ttl_ms < ${e}`).toArray();for(const{run_key:a}of s)n.has(a)||R(r,a)};export{m as appendStreamChunk,c as claimStreamRun,R as deleteStreamRun,$ as finishStreamRun,N as migrateDurableStreams,A as readStreamChunks,_ as readStreamRun,f as trimStreamRuns};
@@ -1 +1 @@
1
- import{LunoraError as D}from"@lunora/errors";import{applySelect as I}from"./CURSOR_PREFIX-Bn8SFoGd.mjs";const W=Symbol.for("lunora.relations.fanOutBudget"),U=o=>({fanOutBudget:o[W],relationBaseWhere:o.relationBaseWhere,relationMask:o.relationMask}),A=(o,n)=>n.select?I(o,n.select,n.with):o,x=async(o,n,r,a,t)=>{const l=await Promise.all(a.map(async i=>{const h=t?{AND:[{[r]:i},t]}:{[r]:i};return[i,await o(n,h)]}));return new Map(l)},S=32,C=(o,n,r)=>{const a=new Map;for(const t of o)for(const l of r(t)){const i=l[n],h=a.get(i);h?h.push(l):a.set(i,[l])}return a},_=(o,n)=>({...o,[W]:n}),B=(o,n)=>{const r=new Set;for(const a of o){const t=a[n];t!=null&&r.add(t)}return[...r]},H=async o=>{const{groupedCounter:n,fanOutBudget:r,fetcher:a,parents:t,relationBaseWhere:l,relationMask:i,schema:h,tableName:m,with:v}=o,w=r??{remaining:S},k=(c,e)=>i?.(c,e)??e;if(t.length===0)return;const N=h.tables[m];if(!N)throw new D("INTERNAL",`unknown table: ${m}`);const O=N.relationMap??{},R=c=>{const e=O[c];if(!e)throw new D("INTERNAL",`unknown relation "${c}" on table "${m}"`);return e},V=async(c,e,s)=>{const u=B(t,e.field);if(u.length===0){for(const d of t)d[c]=null;return}const{page:p}=await a(e.table,_({baseWhere:l?.(e.table),relationBaseWhere:l,relationMask:i,where:{[e.references]:{in:u}},with:s.with},w)),b=new Map;for(const d of k(e.table,p))b.set(d[e.references],d);for(const d of t){const y=b.get(d[e.field]);d[c]=y?A([y],s)[0]??null:null}},$=async(c,e,s)=>{const u=B(t,e.references);if(u.length===0){for(const f of t)f[c]=[];return}const p=typeof s.limit=="number"?Math.max(0,Math.floor(s.limit)):void 0,b=async(f,g)=>{const{page:E}=await a(e.table,_({baseWhere:l?.(e.table),limit:g,orderBy:s.orderBy,relationBaseWhere:l,relationMask:i,where:s.where?{AND:[s.where,f]}:f,with:s.with},w));return E};if(p===0){for(const f of t)f[c]=[];return}const d=p!==void 0&&u.length<=w.remaining;d&&(w.remaining-=u.length);const y=d?await Promise.all(u.map(async f=>b({[e.field]:f},p))):[await b({[e.field]:{in:u}},void 0)],M=C(y,e.field,f=>k(e.table,f));for(const f of t){const g=M.get(f[e.references])??[];f[c]=A(p===void 0?g:g.slice(0,p),s)}},j=async c=>{for(const e of Object.keys(c)){const s=R(e),[u,p]=s.kind==="many"?[s.field,s.references]:[s.references,s.field],b=l?.(s.table),d=B(t,p),y=d.length===0?new Map:await n(s.table,u,d,b);for(const M of t){const f=M._count??{},g=M[p];f[e]=g==null?0:y.get(g)??0,M._count=f}}};for(const[c,e]of Object.entries(v)){if(e===void 0||e===!1)continue;if(c==="_count"){await j(e);continue}const s=R(c),u=e===!0?{}:e;await(s.kind==="one"?V(c,s,u):$(c,s,u))}},F=async(o,n,r)=>{const{deletedId:a,deletedReference:t,findHolders:l,onCascade:i,onRestrict:h,onSetNull:m,tableName:v}=o,w=r.references==="_id"?a:t(r.references);if(w==null)return;const k=await l(n,r.field,w);if(k.length!==0){r.onDelete==="restrict"&&h(`cannot delete "${v}" row: "${n}.${r.field}" still references it`);for(const N of k){const O=N._id;typeof O=="string"&&await(r.onDelete==="cascade"?i(n,O):m(n,O,r.field))}}},P=async o=>{const{schema:n,tableName:r}=o;if(!n.tables[r])throw new D("INTERNAL",`unknown table: ${r}`);for(const[a,t]of Object.entries(n.tables)){const l=t.relationMap;if(l)for(const i of Object.values(l))i.kind!=="one"||i.table!==r||!i.onDelete||await F(o,a,i)}},q=(o,n,r=!1)=>{for(const[a,t]of Object.entries(o.shape))a in n&&typeof t.parse=="function"&&(r&&n[a]===null&&t.kind==="optional"||t.parse(n[a]))};export{P as applyOnDelete,B as distinctValues,x as fanOutScalarCounts,U as relationHooks,H as resolveWith,q as runRowValidators};
1
+ import{LunoraError as D}from"@lunora/errors";import{applySelect as I}from"./CURSOR_PREFIX-BX8jkMJa.mjs";const W=Symbol.for("lunora.relations.fanOutBudget"),U=o=>({fanOutBudget:o[W],relationBaseWhere:o.relationBaseWhere,relationMask:o.relationMask}),A=(o,n)=>n.select?I(o,n.select,n.with):o,x=async(o,n,r,a,t)=>{const l=await Promise.all(a.map(async i=>{const h=t?{AND:[{[r]:i},t]}:{[r]:i};return[i,await o(n,h)]}));return new Map(l)},S=32,C=(o,n,r)=>{const a=new Map;for(const t of o)for(const l of r(t)){const i=l[n],h=a.get(i);h?h.push(l):a.set(i,[l])}return a},_=(o,n)=>({...o,[W]:n}),B=(o,n)=>{const r=new Set;for(const a of o){const t=a[n];t!=null&&r.add(t)}return[...r]},H=async o=>{const{groupedCounter:n,fanOutBudget:r,fetcher:a,parents:t,relationBaseWhere:l,relationMask:i,schema:h,tableName:m,with:v}=o,w=r??{remaining:S},k=(c,e)=>i?.(c,e)??e;if(t.length===0)return;const N=h.tables[m];if(!N)throw new D("INTERNAL",`unknown table: ${m}`);const O=N.relationMap??{},R=c=>{const e=O[c];if(!e)throw new D("INTERNAL",`unknown relation "${c}" on table "${m}"`);return e},V=async(c,e,s)=>{const u=B(t,e.field);if(u.length===0){for(const d of t)d[c]=null;return}const{page:p}=await a(e.table,_({baseWhere:l?.(e.table),relationBaseWhere:l,relationMask:i,where:{[e.references]:{in:u}},with:s.with},w)),b=new Map;for(const d of k(e.table,p))b.set(d[e.references],d);for(const d of t){const y=b.get(d[e.field]);d[c]=y?A([y],s)[0]??null:null}},$=async(c,e,s)=>{const u=B(t,e.references);if(u.length===0){for(const f of t)f[c]=[];return}const p=typeof s.limit=="number"?Math.max(0,Math.floor(s.limit)):void 0,b=async(f,g)=>{const{page:E}=await a(e.table,_({baseWhere:l?.(e.table),limit:g,orderBy:s.orderBy,relationBaseWhere:l,relationMask:i,where:s.where?{AND:[s.where,f]}:f,with:s.with},w));return E};if(p===0){for(const f of t)f[c]=[];return}const d=p!==void 0&&u.length<=w.remaining;d&&(w.remaining-=u.length);const y=d?await Promise.all(u.map(async f=>b({[e.field]:f},p))):[await b({[e.field]:{in:u}},void 0)],M=C(y,e.field,f=>k(e.table,f));for(const f of t){const g=M.get(f[e.references])??[];f[c]=A(p===void 0?g:g.slice(0,p),s)}},j=async c=>{for(const e of Object.keys(c)){const s=R(e),[u,p]=s.kind==="many"?[s.field,s.references]:[s.references,s.field],b=l?.(s.table),d=B(t,p),y=d.length===0?new Map:await n(s.table,u,d,b);for(const M of t){const f=M._count??{},g=M[p];f[e]=g==null?0:y.get(g)??0,M._count=f}}};for(const[c,e]of Object.entries(v)){if(e===void 0||e===!1)continue;if(c==="_count"){await j(e);continue}const s=R(c),u=e===!0?{}:e;await(s.kind==="one"?V(c,s,u):$(c,s,u))}},F=async(o,n,r)=>{const{deletedId:a,deletedReference:t,findHolders:l,onCascade:i,onRestrict:h,onSetNull:m,tableName:v}=o,w=r.references==="_id"?a:t(r.references);if(w==null)return;const k=await l(n,r.field,w);if(k.length!==0){r.onDelete==="restrict"&&h(`cannot delete "${v}" row: "${n}.${r.field}" still references it`);for(const N of k){const O=N._id;typeof O=="string"&&await(r.onDelete==="cascade"?i(n,O):m(n,O,r.field))}}},P=async o=>{const{schema:n,tableName:r}=o;if(!n.tables[r])throw new D("INTERNAL",`unknown table: ${r}`);for(const[a,t]of Object.entries(n.tables)){const l=t.relationMap;if(l)for(const i of Object.values(l))i.kind!=="one"||i.table!==r||!i.onDelete||await F(o,a,i)}},q=(o,n,r=!1)=>{for(const[a,t]of Object.entries(o.shape))a in n&&typeof t.parse=="function"&&(r&&n[a]===null&&t.kind==="optional"||t.parse(n[a]))};export{P as applyOnDelete,B as distinctValues,x as fanOutScalarCounts,U as relationHooks,H as resolveWith,q as runRowValidators};
@@ -1,4 +1,4 @@
1
- import{sql as s}from"drizzle-orm";import{runDrizzle as d}from"./runDrizzle-BlpM0R9P.mjs";const C=16,T=32,v=1e4,R=1e3,h=t=>String(t).padStart(C,"0"),f=t=>`cdc/${encodeURIComponent(t.shard)}/${encodeURIComponent(t.epoch)}/`,y=(t,n)=>`${f(t)}${h(n)}.json`,E="__cdc_archive",g=t=>{d(t,s`CREATE TABLE IF NOT EXISTS ${s.identifier(E)} (
1
+ import{sql as s}from"drizzle-orm";import{runDrizzle as d}from"./runDrizzle-Du5HLitO.mjs";const C=16,T=32,v=1e4,R=1e3,h=t=>String(t).padStart(C,"0"),f=t=>`cdc/${encodeURIComponent(t.shard)}/${encodeURIComponent(t.epoch)}/`,y=(t,n)=>`${f(t)}${h(n)}.json`,E="__cdc_archive",g=t=>{d(t,s`CREATE TABLE IF NOT EXISTS ${s.identifier(E)} (
2
2
  id INTEGER PRIMARY KEY CHECK (id = 1),
3
3
  seq INTEGER NOT NULL
4
4
  )`)},$=t=>(g(t),d(t,s`SELECT seq FROM ${s.identifier(E)} WHERE id = 1`).toArray()[0]?.seq??0),w=(t,n)=>{g(t),d(t,s`INSERT INTO ${s.identifier(E)} (id, seq) VALUES (1, ${n}) ON CONFLICT (id) DO UPDATE SET seq = ${n}`)},L=async(t,n,e)=>{const o=e[0]?.seq,r=e.at(-1)?.seq;o===void 0||r===void 0||await t.put(y(n,r),JSON.stringify({changes:e,from:o,to:r}),{httpMetadata:{contentType:"application/json"}})},j=async(t,n,e)=>{const o=f(n);return(await t.list({limit:1,prefix:o,startAfter:`${o}${h(e)}.json`})).objects.length>0},S=t=>{let n;try{n=JSON.parse(t)}catch{return}if(typeof n!="object"||n===null)return;const e=n;return typeof e.from=="number"&&typeof e.to=="number"&&Array.isArray(e.changes)?e:void 0},_=(t,n)=>{const e=[];for(const o of t.changes)if(!(o.seq<=n)){if(o.op!=="delete"&&o.doc===void 0)break;e.push(o)}return e},I=(t,n,e)=>{let o=e;for(const r of n){if(r.seq!==o+1)break;t.push(r),o=r.seq}return o},b=async(t,n)=>{const e=await t.get(n);return e===null?void 0:S(await e.text())},q=async(t,n,e,o)=>{const r=f(n),p=Math.max(1,Math.min(o??R,v)),A=await t.list({limit:T,prefix:r,startAfter:`${r}${h(e)}.json`}),c=[];let i=e;for(const l of A.objects){const a=await b(t,l.key);if(a===void 0)break;const m=_(a,i);if(i=I(c,m,i),c.length>=p||i!==a.to)break}if(c[0]?.seq!==e+1)return;const u=c.slice(0,p);return{changes:u,cursor:u.at(-1)?.seq??e}};export{L as archiveCdcSegment,j as cdcArchiveRewound,q as readArchivedCdcChanges,$ as readCdcArchivedThrough,w as writeCdcArchivedThrough};
@@ -1 +1 @@
1
- import{m as x,c as T,l as R,r as E,a as P,w as D}from"./ctx-db-search-state-z0OqNIGe.mjs";import{S,c as U,g as v,d as A,e as k,a as b}from"./fts-companion-DcGBHZiM.mjs";import{sql as s}from"drizzle-orm";import{matchesStaticWhere as G}from"./AGGREGATE_SQL_FUNCTION-DDEoMnJR.mjs";import{aggregateTableName as W,encodeAggregateKey as B,foldAggregateTally as H}from"./aggregateTableName-C7o-gpms.mjs";import{rankColumnsSql as N,insertRankRow as K}from"./createCompanionSync-uTsHTJWE.mjs";import{runDrizzle as l,runAll as $}from"./runDrizzle-BlpM0R9P.mjs";import{i as C,h as O,D as p,r as M,a as Y,b as j,A as z}from"./do-sql-DpyjVz_6.mjs";import{sqliteInList as V}from"./WORKERD_SQLITE_LIMITS-DlozcSQu.mjs";import{isLiveForCompanion as J}from"./CURSOR_PREFIX-Bn8SFoGd.mjs";import{rankTableName as Q,matchesRankStaticWhere as X}from"./RANK_TIEBREAK-B0_x8iev.mjs";const L=(e,o)=>l(e,s`SELECT COUNT(*) AS count FROM ${s.identifier(o)}`).one().count>0,Z=(e,o)=>l(e,s`SELECT 1 FROM ${s.identifier(o)} LIMIT 1`).toArray().length>0,_=(e,o)=>l(e,s`SELECT id, _creationTime, ${s.identifier(p)} FROM ${s.identifier(o)}`).toArray(),q=(e,o,r,n)=>{const t=W(o,r.name);if(L(e,t))return;const a=r.by??[],c=new Map,i=_(e,o);for(const d of i){const f=M(d);if(!f||!J(f,n)||r.where&&!G(f,r.where))continue;const g=B(a,f);H(c,g,r,f)}for(const[d,f]of c)l(e,s`INSERT INTO ${s.identifier(t)} (${Y}, ${j}, ${z}) VALUES (${d}, ${f.value}, ${f.count})`)},pe=(e,o)=>{for(const[r,n]of Object.entries(o.tables))if(!(n.shardMode?.kind==="global"||!n.aggregateIndexes))for(const t of n.aggregateIndexes)q(e,r,t,n.softDeleteMode?.field)},ee=(e,o,r)=>{const n=Q(o,r.name);if(L(e,n))return;const t=N(r),a=_(e,o);for(const c of a){const i=M(c);!i||r.where&&!X(i,r.where)||K(e,n,r,t,i._id,i)}},Se=(e,o)=>{for(const[r,n]of Object.entries(o.tables))if(!(n.shardMode?.kind==="global"||!n.rankIndexes))for(const t of n.rankIndexes)ee(e,r,t)},oe=(e,o,r,n)=>l(e,r===void 0?s`SELECT id, _creationTime, ${s.identifier(p)} FROM ${s.identifier(o)} ORDER BY id ASC LIMIT ${s.raw(String(n))}`:s`SELECT id, _creationTime, ${s.identifier(p)} FROM ${s.identifier(o)} WHERE id > ${r} ORDER BY id ASC LIMIT ${s.raw(String(n))}`).toArray(),h=500,y=(e,o,r)=>{const n=S(o,r.name),t=T(r),a=R(E(e,n),t);if(a.finished)return{done:!0,rows:0};const{cursor:c}=a,i=oe(e,o,c,h);let d=c;for(const g of i){const{id:u}=g;if(typeof u!="string")continue;d=u;const I=O(g);$(e,I?A(n,u,k(I,r)):b(n,u))}const f=i.length<h;return D(e,n,d,f,t),{done:f,rows:i.length}},m=(e,o)=>s`${s.identifier(e)}.${s.identifier(o)}`,w=500,F=(e,o,r)=>{const n=S(o,r.name),t=l(e,U(n,w)).toArray(),a=v(t);if(a.size===0)return!0;const c=new Map;for(const i of l(e,s`SELECT ${m(o,"id")}, ${m(o,"_creationTime")}, ${m(o,p)} FROM ${s.identifier(o)} WHERE ${V(m(o,"id"),[...a.keys()],!1)}`))c.set(String(i.id),i);for(const[i,d]of a){const f=c.get(i),g=f?O(f):void 0;$(e,g?A(n,i,k(g,r),{unmappedRowids:d}):b(n,i,{unmappedRowids:d}))}return t.length<w},ne=(e,o,r,n)=>{let t=0;for(;t<n&&!F(e,o,r);)t+=1;return t},Ie=(e,o,r)=>{const n=S(o,r.name),t=T(r);return R(E(e,n),t).finished?!0:P(e,n)},he=(e,o,r)=>{if(C(e))for(const n of r.searchIndexes??[])F(e,o,n),!(n.staged&&Z(e,o))&&y(e,o,n)},re=(e,o,r,n)=>{let t=0;for(;;){if(t>=n)return{done:!1,pages:t};const a=y(e,o,r);if(a.rows>0&&(t+=1),a.done)return{done:!0,pages:t}}},we=(e,o,r={})=>{if(!C(e))return{done:!0,pages:0};x(e);const n=r.maxPages??Number.POSITIVE_INFINITY;let t=0;for(const[a,c]of Object.entries(o.tables))if(!(c.shardMode?.kind==="global"||!c.searchIndexes))for(const i of c.searchIndexes){if(t+=ne(e,a,i,n-t),t>=n)return{done:!1,pages:t};const d=re(e,a,i,n-t);if(t+=d.pages,!d.done)return{done:!1,pages:t}}return{done:!0,pages:t}};export{pe as backfillAggregateIndexes,Se as backfillRankIndexes,we as backfillSearchIndexes,he as backfillSearchIndexesForTable,F as drainUnmappedFtsRows,oe as readKeysetPage,Ie as searchIndexCoversTable};
1
+ import{m as x,c as T,l as R,r as E,a as P,w as D}from"./ctx-db-search-state-DVCp4JQf.mjs";import{S,c as U,g as v,d as A,e as k,a as b}from"./fts-companion-pUdD6kF-.mjs";import{sql as s}from"drizzle-orm";import{matchesStaticWhere as G}from"./AGGREGATE_SQL_FUNCTION-DDEoMnJR.mjs";import{aggregateTableName as W,encodeAggregateKey as B,foldAggregateTally as H}from"./aggregateTableName-C7o-gpms.mjs";import{rankColumnsSql as N,insertRankRow as K}from"./createCompanionSync-Rjn0lsT6.mjs";import{runDrizzle as l,runAll as $}from"./runDrizzle-Du5HLitO.mjs";import{i as C,D as p,r as O,a as Y,b as j,A as z,h as M}from"./do-sql-BEFrJUds.mjs";import{sqliteInList as V}from"./WORKERD_SQLITE_LIMITS-DBH23L_S.mjs";import{isLiveForCompanion as J}from"./CURSOR_PREFIX-BX8jkMJa.mjs";import{rankTableName as Q,matchesRankStaticWhere as X}from"./RANK_TIEBREAK-B0_x8iev.mjs";const L=(e,o)=>l(e,s`SELECT COUNT(*) AS count FROM ${s.identifier(o)}`).one().count>0,Z=(e,o)=>l(e,s`SELECT 1 FROM ${s.identifier(o)} LIMIT 1`).toArray().length>0,_=(e,o)=>l(e,s`SELECT id, _creationTime, ${s.identifier(p)} FROM ${s.identifier(o)}`).toArray(),q=(e,o,r,n)=>{const t=W(o,r.name);if(L(e,t))return;const a=r.by??[],c=new Map,i=_(e,o);for(const d of i){const f=O(d);if(!f||!J(f,n)||r.where&&!G(f,r.where))continue;const g=B(a,f);H(c,g,r,f)}for(const[d,f]of c)l(e,s`INSERT INTO ${s.identifier(t)} (${Y}, ${j}, ${z}) VALUES (${d}, ${f.value}, ${f.count})`)},pe=(e,o)=>{for(const[r,n]of Object.entries(o.tables))if(!(n.shardMode?.kind==="global"||!n.aggregateIndexes))for(const t of n.aggregateIndexes)q(e,r,t,n.softDeleteMode?.field)},ee=(e,o,r)=>{const n=Q(o,r.name);if(L(e,n))return;const t=N(r),a=_(e,o);for(const c of a){const i=O(c);!i||r.where&&!X(i,r.where)||K(e,n,r,t,i._id,i)}},Se=(e,o)=>{for(const[r,n]of Object.entries(o.tables))if(!(n.shardMode?.kind==="global"||!n.rankIndexes))for(const t of n.rankIndexes)ee(e,r,t)},oe=(e,o,r,n)=>l(e,r===void 0?s`SELECT id, _creationTime, ${s.identifier(p)} FROM ${s.identifier(o)} ORDER BY id ASC LIMIT ${s.raw(String(n))}`:s`SELECT id, _creationTime, ${s.identifier(p)} FROM ${s.identifier(o)} WHERE id > ${r} ORDER BY id ASC LIMIT ${s.raw(String(n))}`).toArray(),h=500,y=(e,o,r)=>{const n=S(o,r.name),t=T(r),a=R(E(e,n),t);if(a.finished)return{done:!0,rows:0};const{cursor:c}=a,i=oe(e,o,c,h);let d=c;for(const g of i){const{id:u}=g;if(typeof u!="string")continue;d=u;const I=M(g);$(e,I?A(n,u,k(I,r)):b(n,u))}const f=i.length<h;return D(e,n,d,f,t),{done:f,rows:i.length}},m=(e,o)=>s`${s.identifier(e)}.${s.identifier(o)}`,w=500,F=(e,o,r)=>{const n=S(o,r.name),t=l(e,U(n,w)).toArray(),a=v(t);if(a.size===0)return!0;const c=new Map;for(const i of l(e,s`SELECT ${m(o,"id")}, ${m(o,"_creationTime")}, ${m(o,p)} FROM ${s.identifier(o)} WHERE ${V(m(o,"id"),[...a.keys()],!1)}`))c.set(String(i.id),i);for(const[i,d]of a){const f=c.get(i),g=f?M(f):void 0;$(e,g?A(n,i,k(g,r),{unmappedRowids:d}):b(n,i,{unmappedRowids:d}))}return t.length<w},ne=(e,o,r,n)=>{let t=0;for(;t<n&&!F(e,o,r);)t+=1;return t},Ie=(e,o,r)=>{const n=S(o,r.name),t=T(r);return R(E(e,n),t).finished?!0:P(e,n)},he=(e,o,r)=>{if(C(e))for(const n of r.searchIndexes??[])F(e,o,n),!(n.staged&&Z(e,o))&&y(e,o,n)},re=(e,o,r,n)=>{let t=0;for(;;){if(t>=n)return{done:!1,pages:t};const a=y(e,o,r);if(a.rows>0&&(t+=1),a.done)return{done:!0,pages:t}}},we=(e,o,r={})=>{if(!C(e))return{done:!0,pages:0};x(e);const n=r.maxPages??Number.POSITIVE_INFINITY;let t=0;for(const[a,c]of Object.entries(o.tables))if(!(c.shardMode?.kind==="global"||!c.searchIndexes))for(const i of c.searchIndexes){if(t+=ne(e,a,i,n-t),t>=n)return{done:!1,pages:t};const d=re(e,a,i,n-t);if(t+=d.pages,!d.done)return{done:!1,pages:t}}return{done:!0,pages:t}};export{pe as backfillAggregateIndexes,Se as backfillRankIndexes,we as backfillSearchIndexes,he as backfillSearchIndexesForTable,oe as readKeysetPage,Ie as searchIndexCoversTable};
@@ -1 +1 @@
1
- import{quoteIdentifier as l}from"./quoteIdentifier-CObIFRhb.mjs";import{reprojectionMigrationTable as u}from"./REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{REPROJECTION_MIGRATION_PREFIX as v,reprojectionMigrationId as w}from"./REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{e as d}from"./wire-codec-C-FpWm52.mjs";import{runSql as p}from"./runDrizzle-BlpM0R9P.mjs";import{k as m,D as E}from"./do-sql-DpyjVz_6.mjs";import{mayHoldProjectedValue as g}from"./BIGINT_KEY_DIGITS-C9a7Ix7k.mjs";const b=d(0n)[0],_=e=>e.shardMode?.kind==="global"?[]:Object.entries(e.shape).filter(([,r])=>g(r)).map(([r])=>r),M=e=>Object.entries(e.tables).filter(([,r])=>_(r).length>0).map(([r])=>r),f=e=>{const r=`json_each(${l(E)}) AS __f__`;return{params:[JSON.stringify(e),b,"bigint","bytes"],sql:`EXISTS (SELECT 1 FROM ${r} WHERE __f__.type = 'array' AND __f__.key IN (SELECT value FROM json_each(?)) AND json_extract(__f__.value, '$[0]') = ? AND json_extract(__f__.value, '$[1]') IN (?, ?))`}},N=(e,r,o)=>{if(o.length===0)return 0;const{params:t,sql:n}=f(o);return p(e,`SELECT COUNT(*) AS count FROM ${l(r)} WHERE ${n}`,...t).toArray()[0]?.count??0},R=(e,r,o,t)=>{const{params:n,sql:i}=f(o);return p(e,`SELECT 1 FROM ${l(r)} WHERE id = ? AND (${i}) LIMIT 1`,t,...n).toArray().length>0},S=(e,r,o)=>{const t=u(e);if(t===void 0)return;const n=r.tables[t];if(!n)return;const i=_(n);if(i.length!==0)return{id:e,table:t,up:s=>{const a=s._id;if(!(typeof a!="string"||!R(o,t,i,a))){try{m(s)}catch(c){console.warn(`${e}: skipping row ${a} — it cannot be re-projected: ${c instanceof Error?c.message:String(c)}`);return}return s}}}};export{v as REPROJECTION_MIGRATION_PREFIX,S as buildReprojectionMigration,N as countLegacyRows,_ as reprojectableFields,w as reprojectionMigrationId,M as reprojectionTables};
1
+ import{quoteIdentifier as l}from"./quoteIdentifier-CObIFRhb.mjs";import{reprojectionMigrationTable as u}from"./REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{REPROJECTION_MIGRATION_PREFIX as v,reprojectionMigrationId as w}from"./REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{e as d}from"./wire-codec-C-FpWm52.mjs";import{runSql as p}from"./runDrizzle-Du5HLitO.mjs";import{k as m,D as E}from"./do-sql-BEFrJUds.mjs";import{mayHoldProjectedValue as g}from"./BIGINT_KEY_DIGITS-C9a7Ix7k.mjs";const b=d(0n)[0],_=e=>e.shardMode?.kind==="global"?[]:Object.entries(e.shape).filter(([,r])=>g(r)).map(([r])=>r),M=e=>Object.entries(e.tables).filter(([,r])=>_(r).length>0).map(([r])=>r),f=e=>{const r=`json_each(${l(E)}) AS __f__`;return{params:[JSON.stringify(e),b,"bigint","bytes"],sql:`EXISTS (SELECT 1 FROM ${r} WHERE __f__.type = 'array' AND __f__.key IN (SELECT value FROM json_each(?)) AND json_extract(__f__.value, '$[0]') = ? AND json_extract(__f__.value, '$[1]') IN (?, ?))`}},N=(e,r,o)=>{if(o.length===0)return 0;const{params:t,sql:n}=f(o);return p(e,`SELECT COUNT(*) AS count FROM ${l(r)} WHERE ${n}`,...t).toArray()[0]?.count??0},R=(e,r,o,t)=>{const{params:n,sql:i}=f(o);return p(e,`SELECT 1 FROM ${l(r)} WHERE id = ? AND (${i}) LIMIT 1`,t,...n).toArray().length>0},S=(e,r,o)=>{const t=u(e);if(t===void 0)return;const n=r.tables[t];if(!n)return;const i=_(n);if(i.length!==0)return{id:e,table:t,up:s=>{const a=s._id;if(!(typeof a!="string"||!R(o,t,i,a))){try{m(s)}catch(c){console.warn(`${e}: skipping row ${a} — it cannot be re-projected: ${c instanceof Error?c.message:String(c)}`);return}return s}}}};export{v as REPROJECTION_MIGRATION_PREFIX,S as buildReprojectionMigration,N as countLegacyRows,_ as reprojectableFields,w as reprojectionMigrationId,M as reprojectionTables};
@@ -1 +1 @@
1
- const f=/key|secret|token|password|passwd|credential|private|auth|bearer|session|cookie|salt|signature|dsn|webhook/iu,l=new Set(["LUNORA_ADMIN_TOKEN","LUNORA_WS_BEARER"]),d=["CF_PAGES_URL","WORKER_URL","LUNORA_WORKER_URL"],u=["CF_ENV","ENVIRONMENT","WORKER_ENV","NODE_ENV"],p=n=>n.length<=4?"••••":`${n.slice(0,4)}${"•".repeat(Math.min(8,n.length-4))}`,R=n=>f.test(n),E=n=>{const e=o=>typeof n[o]=="function";return e("idFromName")||e("idFromString")?"durable-object":e("createMultipartUpload")||e("put")&&e("get")&&e("list")&&e("head")?"r2":e("getWithMetadata")?"kv":e("prepare")&&e("dump")?"d1":e("send")&&e("sendBatch")?"queue":e("fetch")&&!e("get")?"service":"object"},N=n=>{if(typeof n!="object"||n===null)return{};const e=n,o=i=>i.map(c=>e[c]).find(c=>typeof c=="string"&&c!==""),t={},r=o(d),s=o(u);r!==void 0&&(t.workerUrl=r),s!==void 0&&(t.environment=s);const a=e.CF_VERSION_METADATA;if(a!==null&&typeof a=="object"){const i=a;typeof i.id=="string"&&(t.deploymentId=i.id),typeof i.tag=="string"&&(t.versionTag=i.tag)}return t},_=/^(?:dev(?:elopment)?|local(?:host)?|test)$/iu,g=n=>{const e=n??{};for(const o of u){const t=e[o];if(typeof t=="string"&&_.test(t))return!0}return!1},v=n=>{const e=n??{},o=[];for(const[t,r]of Object.entries(e))if(!l.has(t)){if(typeof r=="string"){const s=R(t);o.push({kind:s?"secret":"var",name:t,value:p(r)});continue}if(typeof r=="number"||typeof r=="boolean"){o.push({kind:"var",name:t,value:String(r)});continue}if(r!==null&&typeof r=="object"){o.push({bindingType:E(r),kind:"binding",name:t,value:null});continue}o.push({kind:"var",name:t,value:null})}return o.sort((t,r)=>t.name.localeCompare(r.name)),{deploy:N(e),settings:o}};export{E as bindingType,v as buildSettings,g as isDevEnvironment,R as looksSecret,N as readDeployInfo,p as redact};
1
+ const f=/key|secret|token|password|passwd|credential|private|auth|bearer|session|cookie|salt|signature|dsn|webhook/iu,l=new Set(["LUNORA_ADMIN_TOKEN","LUNORA_WS_BEARER"]),d=["CF_PAGES_URL","WORKER_URL","LUNORA_WORKER_URL"],u=["CF_ENV","ENVIRONMENT","WORKER_ENV","NODE_ENV"],p=n=>n.length<=4?"••••":`${n.slice(0,4)}${"•".repeat(Math.min(8,n.length-4))}`,R=n=>f.test(n),E=n=>{const e=o=>typeof n[o]=="function";return e("idFromName")||e("idFromString")?"durable-object":e("createMultipartUpload")||e("put")&&e("get")&&e("list")&&e("head")?"r2":e("getWithMetadata")?"kv":e("prepare")&&e("dump")?"d1":e("send")&&e("sendBatch")?"queue":e("fetch")&&!e("get")?"service":"object"},N=n=>{if(typeof n!="object"||n===null)return{};const e=n,o=i=>i.map(c=>e[c]).find(c=>typeof c=="string"&&c!==""),t={},r=o(d),s=o(u);r!==void 0&&(t.workerUrl=r),s!==void 0&&(t.environment=s);const a=e.CF_VERSION_METADATA;if(a!==null&&typeof a=="object"){const i=a;typeof i.id=="string"&&(t.deploymentId=i.id),typeof i.tag=="string"&&(t.versionTag=i.tag)}return t},_=/^(?:dev(?:elopment)?|local(?:host)?|test)$/iu,g=n=>{const e=n??{};for(const o of u){const t=e[o];if(typeof t=="string"&&_.test(t))return!0}return!1},v=n=>{const e=n??{},o=[];for(const[t,r]of Object.entries(e))if(!l.has(t)){if(typeof r=="string"){const s=R(t);o.push({kind:s?"secret":"var",name:t,value:p(r)});continue}if(typeof r=="number"||typeof r=="boolean"){o.push({kind:"var",name:t,value:String(r)});continue}if(r!==null&&typeof r=="object"){o.push({bindingType:E(r),kind:"binding",name:t,value:null});continue}o.push({kind:"var",name:t,value:null})}return o.sort((t,r)=>t.name.localeCompare(r.name)),{deploy:N(e),settings:o}};export{v as buildSettings,g as isDevEnvironment,N as readDeployInfo};
@@ -1 +1 @@
1
- import{readCdcChangeKeys as s}from"./CDC_LOG_TABLE-Bkv7JskR.mjs";import{selectShapeMembers as h}from"./selectShapeMembers-DTA3YUf4.mjs";import{shapeRangeKey as u}from"./ShapeDiffCache-gdaILV5E.mjs";import{projectColumns as g}from"./buildPokeFrames-BBE6J91z.mjs";const C=(m,e,a,i,p,f=s)=>{const r=u(e.table,a,i),n=p.changedKeys(r,()=>f(m,e.table,a,i));if(n.length===0)return[];const b=p.members(e,r,()=>h(m,e.table,e.effectiveWhere,n.map(t=>t.id))),o=[];for(const t of n){const c=b.get(t.id);if(c===void 0){t.op!=="insert"&&o.push({key:t.id,op:"delete",table:e.table});continue}o.push({key:t.id,op:t.op,table:e.table,value:g(c,e.columns)})}return o};export{C as buildShapeDiff};
1
+ import{readCdcChangeKeys as s}from"./CDC_LOG_TABLE-QaBxSIZM.mjs";import{selectShapeMembers as h}from"./selectShapeMembers-BXhvEt4X.mjs";import{shapeRangeKey as u}from"./ShapeDiffCache-gdaILV5E.mjs";import{projectColumns as g}from"./buildPokeFrames-BBE6J91z.mjs";const C=(m,e,a,i,p,f=s)=>{const r=u(e.table,a,i),n=p.changedKeys(r,()=>f(m,e.table,a,i));if(n.length===0)return[];const b=p.members(e,r,()=>h(m,e.table,e.effectiveWhere,n.map(t=>t.id))),o=[];for(const t of n){const c=b.get(t.id);if(c===void 0){t.op!=="insert"&&o.push({key:t.id,op:"delete",table:e.table});continue}o.push({key:t.id,op:t.op,table:e.table,value:g(c,e.columns)})}return o};export{C as buildShapeDiff};
@@ -1 +1 @@
1
- import{sql as t}from"drizzle-orm";import{runDrizzle as s}from"./runDrizzle-BlpM0R9P.mjs";const a=r=>r?.memoryMode===!0,l=r=>Object.entries(r.tables).filter(([,e])=>a(e)&&e.shardMode?.kind!=="global").map(([e])=>e),i=(r,e)=>{const o=l(e);for(const m of o)s(r,t`DELETE FROM ${t.identifier(m)}`);return o.length};export{i as clearMemoryTables,a as isMemoryTable,l as memoryTableNames};
1
+ import{sql as t}from"drizzle-orm";import{runDrizzle as s}from"./runDrizzle-Du5HLitO.mjs";const a=r=>r?.memoryMode===!0,l=r=>Object.entries(r.tables).filter(([,e])=>a(e)&&e.shardMode?.kind!=="global").map(([e])=>e),i=(r,e)=>{const o=l(e);for(const m of o)s(r,t`DELETE FROM ${t.identifier(m)}`);return o.length};export{i as clearMemoryTables,a as isMemoryTable,l as memoryTableNames};
@@ -0,0 +1 @@
1
+ import"./WORKERD_SQLITE_LIMITS-DBH23L_S.mjs";import{c as i,s as m}from"./where-sql-DFs8Zw7-.mjs";import"./RELATION_EXISTS_KEY-CFUhnZSZ.mjs";export{i as compileWhereSql,m as serverInList};
@@ -1 +1 @@
1
- import{LunoraError as g}from"@lunora/errors";import{sql as o}from"drizzle-orm";import{mergeWhere as b}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{SCAN_DEP as j}from"./SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as A}from"./runDrizzle-BlpM0R9P.mjs";import{sqliteInList as O}from"./WORKERD_SQLITE_LIMITS-DlozcSQu.mjs";import{decodeCursor as F,CURSOR_PREFIX as P,toBase64 as U}from"./CURSOR_PREFIX-Bn8SFoGd.mjs";import{rankTableName as V,sortColumnName as z,resolveRankPartition as H,RANK_TIEBREAK as _,encodePartitionKey as J,rankPivotConditionSql as X}from"./RANK_TIEBREAK-B0_x8iev.mjs";const Y="__doc__",G=n=>P+U(JSON.stringify(n)),Q=n=>n.after?[n.after.partitionKey,...n.after.sortValues,n.after.rowId]:n.cursor?F(n.cursor):void 0,Z=(n,r,f)=>{if(n?.length!==1+r.length+1)return;const t=[{column:"__partition__",direction:"asc"}];for(const[c,u]of r.entries())t.push({column:u,direction:f[c]?.direction??"asc"});t.push({column:_,direction:"asc"});const e=[];for(const[c,u]of t.entries()){const d=X(u.column,n[c],u.direction,!0);if(d===void 0)continue;const s=[];for(const[m,l]of t.slice(0,c).entries())s.push(o`${o.identifier(l.column)} IS ${n[m]}`);s.push(d);const[i]=s;e.push(s.length===1&&i!==void 0?i:o`(${o.join(s,o` AND `)})`)}return e.length===0?o`(1 = 0)`:o`(${o.join(e,o` OR `)})`},v=null,oo=(n,r)=>{if(n===void 0)return v;const f=[n.__partition__,...r.map(t=>n[t]),n[_]];return G(f)},no=(n,r,f)=>{const t=[];for(const e of n){const c=e[_];if(typeof c!="string")continue;const u=r.get(c);if(!u)continue;const d=typeof e.__partition__=="string"?e.__partition__:"",s=f.map(i=>e[i]??null);t.push({doc:u,key:{partitionKey:d,rowId:c,sortValues:s}})}return t},to=o`${o.identifier("id")}`,ro=(n,r,f)=>{const{rowToDocument:t}=n,e=new Map;if(f.length===0)return e;const c=A(n.sql,o`SELECT id, _creationTime, ${o.identifier(Y)} FROM ${o.identifier(r)} WHERE ${O(to,f,!1)}`).toArray();for(const u of c){const d=t(u),s=u.id;d&&typeof s=="string"&&e.set(s,d)}return e},_o=(n,r,f,t)=>{const{assertRankPartitionLocal:e,ensureRankBackfilled:c,onRead:u,schema:d}=n,s=d.tables[r];if(!s)throw new g("INTERNAL",`unknown table: ${r}`);const i=s.rankIndexes?.find(a=>a.name===f);if(!i)throw new g("INTERNAL",`unknown rankIndex "${f}" on table "${r}"`);e(r,s,i),u(r,j),c(r,i);const m=V(r,i.name),l=i.sortBy.map((a,w)=>z(w)),h=Math.max(1,Math.min(1e3,Math.floor(t.take??100))),T=b(t.baseWhere,t.where),k=H(i,T),R=[o`${o.identifier("__partition__")} ASC`];for(const[a,w]of l.entries()){const W=i.sortBy[a]?.direction;R.push(o`${o.identifier(w)} ${o.raw(W==="desc"?"DESC":"ASC")}`)}R.push(o`${o.identifier(_)} ASC`);const p=[];typeof t.partitionKey=="string"?p.push(o`${o.identifier("__partition__")} = ${t.partitionKey}`):k&&p.push(o`${o.identifier("__partition__")} = ${J(i.partitionBy??[],k)}`);const B=Q(t),E=Z(B,l,i.sortBy);E&&p.push(E);const I=o.identifier(_),S=o.identifier("__partition__"),D=p.length>0?o` WHERE ${o.join(p,o` AND `)}`:o``,L=l.length>0?o`${I}, ${S}, ${o.join(l.map(a=>o.identifier(a)),o`, `)}`:o`${I}, ${S}`,M=o`SELECT ${L} FROM ${o.identifier(m)}${D} ORDER BY ${o.join(R,o`, `)} LIMIT ${o.raw(String(h+1))}`,$=A(n.sql,M).toArray(),C=$.length>h,y=C?$.slice(0,h):$,K=y.map(a=>a[_]),q=no(y,ro(n,r,K),l),x=C?oo(y.at(-1),l):v,N=i.sortBy.map(a=>a.direction==="desc"?"desc":"asc");return{continueCursor:x,directions:N,hasMore:C,rows:q}};export{_o as computeRankPage,Q as resolveRankSeekTuple};
1
+ import{LunoraError as g}from"@lunora/errors";import{sql as o}from"drizzle-orm";import{mergeWhere as b}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{SCAN_DEP as j}from"./SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as A}from"./runDrizzle-Du5HLitO.mjs";import{sqliteInList as O}from"./WORKERD_SQLITE_LIMITS-DBH23L_S.mjs";import{decodeCursor as F,CURSOR_PREFIX as P,toBase64 as U}from"./CURSOR_PREFIX-BX8jkMJa.mjs";import{rankTableName as V,sortColumnName as z,resolveRankPartition as H,RANK_TIEBREAK as _,encodePartitionKey as J,rankPivotConditionSql as X}from"./RANK_TIEBREAK-B0_x8iev.mjs";const Y="__doc__",G=n=>P+U(JSON.stringify(n)),Q=n=>n.after?[n.after.partitionKey,...n.after.sortValues,n.after.rowId]:n.cursor?F(n.cursor):void 0,Z=(n,r,f)=>{if(n?.length!==1+r.length+1)return;const t=[{column:"__partition__",direction:"asc"}];for(const[c,u]of r.entries())t.push({column:u,direction:f[c]?.direction??"asc"});t.push({column:_,direction:"asc"});const e=[];for(const[c,u]of t.entries()){const d=X(u.column,n[c],u.direction,!0);if(d===void 0)continue;const s=[];for(const[m,l]of t.slice(0,c).entries())s.push(o`${o.identifier(l.column)} IS ${n[m]}`);s.push(d);const[i]=s;e.push(s.length===1&&i!==void 0?i:o`(${o.join(s,o` AND `)})`)}return e.length===0?o`(1 = 0)`:o`(${o.join(e,o` OR `)})`},v=null,oo=(n,r)=>{if(n===void 0)return v;const f=[n.__partition__,...r.map(t=>n[t]),n[_]];return G(f)},no=(n,r,f)=>{const t=[];for(const e of n){const c=e[_];if(typeof c!="string")continue;const u=r.get(c);if(!u)continue;const d=typeof e.__partition__=="string"?e.__partition__:"",s=f.map(i=>e[i]??null);t.push({doc:u,key:{partitionKey:d,rowId:c,sortValues:s}})}return t},to=o`${o.identifier("id")}`,ro=(n,r,f)=>{const{rowToDocument:t}=n,e=new Map;if(f.length===0)return e;const c=A(n.sql,o`SELECT id, _creationTime, ${o.identifier(Y)} FROM ${o.identifier(r)} WHERE ${O(to,f,!1)}`).toArray();for(const u of c){const d=t(u),s=u.id;d&&typeof s=="string"&&e.set(s,d)}return e},_o=(n,r,f,t)=>{const{assertRankPartitionLocal:e,ensureRankBackfilled:c,onRead:u,schema:d}=n,s=d.tables[r];if(!s)throw new g("INTERNAL",`unknown table: ${r}`);const i=s.rankIndexes?.find(a=>a.name===f);if(!i)throw new g("INTERNAL",`unknown rankIndex "${f}" on table "${r}"`);e(r,s,i),u(r,j),c(r,i);const m=V(r,i.name),l=i.sortBy.map((a,w)=>z(w)),h=Math.max(1,Math.min(1e3,Math.floor(t.take??100))),T=b(t.baseWhere,t.where),k=H(i,T),R=[o`${o.identifier("__partition__")} ASC`];for(const[a,w]of l.entries()){const W=i.sortBy[a]?.direction;R.push(o`${o.identifier(w)} ${o.raw(W==="desc"?"DESC":"ASC")}`)}R.push(o`${o.identifier(_)} ASC`);const p=[];typeof t.partitionKey=="string"?p.push(o`${o.identifier("__partition__")} = ${t.partitionKey}`):k&&p.push(o`${o.identifier("__partition__")} = ${J(i.partitionBy??[],k)}`);const B=Q(t),E=Z(B,l,i.sortBy);E&&p.push(E);const I=o.identifier(_),S=o.identifier("__partition__"),D=p.length>0?o` WHERE ${o.join(p,o` AND `)}`:o``,L=l.length>0?o`${I}, ${S}, ${o.join(l.map(a=>o.identifier(a)),o`, `)}`:o`${I}, ${S}`,M=o`SELECT ${L} FROM ${o.identifier(m)}${D} ORDER BY ${o.join(R,o`, `)} LIMIT ${o.raw(String(h+1))}`,$=A(n.sql,M).toArray(),C=$.length>h,y=C?$.slice(0,h):$,K=y.map(a=>a[_]),q=no(y,ro(n,r,K),l),x=C?oo(y.at(-1),l):v,N=i.sortBy.map(a=>a.direction==="desc"?"desc":"asc");return{continueCursor:x,directions:N,hasMore:C,rows:q}};export{_o as computeRankPage,Q as resolveRankSeekTuple};
@@ -1 +1 @@
1
- import{N as re,S as se,d as ie,e as ce,a as ae}from"./fts-companion-DcGBHZiM.mjs";import{sql as e}from"drizzle-orm";import{matchesStaticWhere as V,aggregateSqlFunction as fe}from"./AGGREGATE_SQL_FUNCTION-DDEoMnJR.mjs";import{aggregateTableName as P,encodeAggregateKey as v,foldAggregateTally as z,coerceAggregateNumber as D}from"./aggregateTableName-C7o-gpms.mjs";import{runDrizzle as $,runAll as le}from"./runDrizzle-BlpM0R9P.mjs";import{i as $e,g as de,D as b,r as q,a as O,b as m,A as g,c as M,e as W}from"./do-sql-DpyjVz_6.mjs";import{param as ue,WORKERD_SQLITE_LIMITS as Ee}from"./WORKERD_SQLITE_LIMITS-DlozcSQu.mjs";import{encodeGeohash as ge,GEO_DEFAULT_PRECISION as pe}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{isLiveForCompanion as Q}from"./CURSOR_PREFIX-Bn8SFoGd.mjs";import{encodePartitionKey as ye,sortColumnName as _e,rankTableName as X,matchesRankStaticWhere as Y}from"./RANK_TIEBREAK-B0_x8iev.mjs";import{mayHoldProjectedValue as me}from"./BIGINT_KEY_DIGITS-C9a7Ix7k.mjs";import{serializeSqlValue as J}from"./serializeSqlValue-BbZ5hKM7.mjs";const he=(_,R,p)=>[..._.partitionBy??[],..._.sortBy.map(h=>h.field),..._.where?Object.keys(_.where):[]].every(h=>R[h]===p[h]),Z=_=>e.join(["__id__","__partition__",..._.sortBy.map((R,p)=>_e(p))].map(R=>e.identifier(R)),e`, `),N=(_,R,p,F,h,u)=>{const s=ye(p.partitionBy??[],u),C=p.sortBy.map(I=>J(u[I.field]??null)),L=e.join([h,s,...C].map(I=>ue(I)),e`, `);$(_,e`INSERT INTO ${e.identifier(R)} (${F}) VALUES (${L})`)},Te=(_,R,p,F,h,u)=>{if(h&&u&&he(p,h,u))return;const s=X(R,p.name);h&&$(_,e`DELETE FROM ${e.identifier(s)} WHERE ${e.identifier("__id__")} = ${F}`),!(!u||p.where&&!Y(u,p.where))&&N(_,s,p,Z(p),F,u)},be=_=>{const{broadcast:R,indexKeysFor:p,invalidateCache:F,recordCdc:h,schema:u,sql:s}=_,C=new Set,L=n=>u.tables[n]?.softDeleteMode?.field,I=new Set,U=(n,o)=>{const r=`${n}::${o.name}`;if(C.has(r))return;const c=P(n,o.name),a=o.by??[],f=L(n),d=new Map,y=$(s,e`SELECT id, _creationTime, ${e.identifier(b)} FROM ${e.identifier(n)}`).toArray();for(const T of y){const l=q(T);if(!l||!Q(l,f)||o.where&&!V(l,o.where))continue;const S=v(a,l);z(d,S,o,l)}$(s,e`DELETE FROM ${e.identifier(c)}`);const A=Math.floor(Ee.boundParams/3),w=[...d];for(let T=0;T<w.length;T+=A){const l=w.slice(T,T+A),S=e.join(l.map(([t,i])=>e`(${t}, ${i.value}, ${i.count})`),e`, `);$(s,e`INSERT INTO ${e.identifier(c)} (${O}, ${m}, ${g}) VALUES ${S}`)}C.add(r)},x=(n,o,r)=>{const c=o.by??[],a=o.field??"",f=[],d=(t,i)=>{const E=J(i);E===null?f.push(e`${W(t)} IS NULL`):f.push(e`${W(t)} = ${E}`)};for(const t of c)d(t,r[t]??null);const y=L(n);y!==void 0&&d(y,null);for(const[t,i]of Object.entries(o.where??{}))d(t,i!==null&&typeof i=="object"&&!Array.isArray(i)?i.eq:i);const A=f.length>0?e` WHERE ${e.join(f,e` AND `)}`:e``,w=u.tables[n]?.shape[a];if(w&&me(w)){const t=$(s,e`SELECT id, _creationTime, ${e.identifier(b)} FROM ${e.identifier(n)}${A}`).toArray(),i=new Map;for(const E of t){const k=q(E);k&&z(i,"",o,k)}return{value:i.get("")?.value??null}}const T=fe(o.op),l=W(a);return{value:$(s,e`SELECT ${e.raw(T)}(${l}) AS value FROM ${e.identifier(n)}${A}`).one().value??null}},ee=(n,o,r,c)=>{const a=P(n,o.name),{op:f}=o,d=o.field??"",y=t=>{$(s,e`DELETE FROM ${e.identifier(a)} WHERE ${O} = ${t} AND ${g} <= 0`)},A=L(n),w=t=>!o.where||V(t,o.where),T=t=>Q(t,A)&&w(t);c!==void 0&&f!=="count"&&w(c)&&D(c[d]);const l=r&&T(r)?r:void 0,S=c&&T(c)?c:void 0;if(!(!l&&!S)){if(f==="count"){for(const[t,i]of[[l,-1],[S,1]]){if(!t)continue;const E=v(o.by??[],t);$(s,M(a,E,i,i,e`${m} = ${m} + excluded.${m}, ${g} = ${g} + excluded.${g}`))}l&&y(v(o.by??[],l));return}if(f==="sum"||f==="avg"){for(const[t,i]of[[l,-1],[S,1]]){if(!t)continue;const E=D(t[d]);if(E===void 0)continue;const k=v(o.by??[],t);$(s,M(a,k,i*E,i,e`${m} = COALESCE(${m}, 0) + excluded.${m}, ${g} = ${g} + excluded.${g}`))}l&&y(v(o.by??[],l));return}if(l){const t=v(o.by??[],l),i=D(l[d]),E=$(s,e`SELECT ${m} AS value, ${g} AS count FROM ${e.identifier(a)} WHERE ${O} = ${t}`).toArray()[0],k=(E?.count??0)-1;if(k<=0)$(s,e`DELETE FROM ${e.identifier(a)} WHERE ${O} = ${t}`);else if(E&&i!==void 0&&E.value!==null&&i===E.value){const te=x(n,o,l);$(s,e`UPDATE ${e.identifier(a)} SET ${m} = ${te.value}, ${g} = ${k} WHERE ${O} = ${t}`)}else $(s,e`UPDATE ${e.identifier(a)} SET ${g} = ${g} - 1 WHERE ${O} = ${t}`)}if(S){const t=v(o.by??[],S),i=D(S[d]);if(i===void 0)$(s,M(a,t,null,1,e`${g} = ${g} + 1`));else{const E=f==="min"?"MIN":"MAX";$(s,M(a,t,i,1,e`${m} = ${e.raw(E)}(COALESCE(${m}, excluded.${m}), excluded.${m}), ${g} = ${g} + 1`))}}}},oe=n=>{for(const o of u.tables[n]?.aggregateIndexes??[])U(n,o)},j=(n,o,r)=>{for(const c of u.tables[n]?.aggregateIndexes??[])ee(n,c,o,r)},B=(n,o)=>{const r=`${n}::rank::${o.name}`;if(I.has(r))return;const c=X(n,o.name),a=$(s,e`SELECT id, _creationTime, ${e.identifier(b)} FROM ${e.identifier(n)}`).toArray();$(s,e`DELETE FROM ${e.identifier(c)}`);const f=Z(o);for(const d of a){const y=q(d);!y||o.where&&!Y(y,o.where)||N(s,c,o,f,y._id,y)}I.add(r)},ne=n=>{for(const o of u.tables[n]?.rankIndexes??[])B(n,o)},H=(n,o,r,c)=>{for(const a of u.tables[n]?.rankIndexes??[])Te(s,n,a,o,r,c)},K=(n,o,r,c)=>{const a=u.tables[n]?.searchIndexes??[];if(!(a.length===0||!$e(s)))for(const f of a){if(re(c,r,f))continue;const d=se(n,f.name);le(s,r?ie(d,o,ce(r,f)):ae(d,o))}},G=(n,o,r)=>{for(const c of u.tables[n]?.geoIndexes??[]){const a=de(n,c.name);$(s,e`DELETE FROM ${e.identifier(a)} WHERE ${e.identifier("__id__")} = ${o}`);const f=r?.[c.field];if(f!==null&&typeof f=="object"&&typeof f.lat=="number"&&typeof f.lng=="number"){const{lat:d,lng:y}=f,A=ge({lat:d,lng:y},c.precision??pe);$(s,e`INSERT INTO ${e.identifier(a)} (${e.identifier("__id__")}, ${e.identifier("__geohash__")}, ${e.identifier("__lat__")}, ${e.identifier("__lng__")}) VALUES (${o}, ${A}, ${d}, ${y})`)}}};return{ensureBackfilledForTable:oe,ensureBackfilledIndex:U,ensureRankBackfilled:B,ensureRankBackfilledForTable:ne,syncAggregates:j,syncCompanionsForInsert:(n,o,r)=>{K(n,o,r),G(n,o,r),j(n,void 0,r),H(n,o,void 0,r),F(n,o,r),h(n,o,"insert",r),R({indexKeys:p(n,r),key:o,op:"insert",row:r,table:n})},syncGeo:G,syncRanks:H,syncSearch:K}};export{be as createCompanionSync,N as insertRankRow,Z as rankColumnsSql};
1
+ import{N as re,S as se,d as ie,e as ce,a as ae}from"./fts-companion-pUdD6kF-.mjs";import{sql as e}from"drizzle-orm";import{matchesStaticWhere as V,aggregateSqlFunction as fe}from"./AGGREGATE_SQL_FUNCTION-DDEoMnJR.mjs";import{aggregateTableName as P,encodeAggregateKey as v,foldAggregateTally as z,coerceAggregateNumber as D}from"./aggregateTableName-C7o-gpms.mjs";import{runDrizzle as $,runAll as le}from"./runDrizzle-Du5HLitO.mjs";import{i as $e,g as de,D as b,r as q,a as O,b as m,A as g,c as M,e as W}from"./do-sql-BEFrJUds.mjs";import{param as ue,WORKERD_SQLITE_LIMITS as Ee}from"./WORKERD_SQLITE_LIMITS-DBH23L_S.mjs";import{encodeGeohash as ge,GEO_DEFAULT_PRECISION as pe}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{isLiveForCompanion as Q}from"./CURSOR_PREFIX-BX8jkMJa.mjs";import{encodePartitionKey as ye,sortColumnName as _e,rankTableName as X,matchesRankStaticWhere as Y}from"./RANK_TIEBREAK-B0_x8iev.mjs";import{mayHoldProjectedValue as me}from"./BIGINT_KEY_DIGITS-C9a7Ix7k.mjs";import{serializeSqlValue as J}from"./serializeSqlValue-BbZ5hKM7.mjs";const he=(_,R,p)=>[..._.partitionBy??[],..._.sortBy.map(h=>h.field),..._.where?Object.keys(_.where):[]].every(h=>R[h]===p[h]),Z=_=>e.join(["__id__","__partition__",..._.sortBy.map((R,p)=>_e(p))].map(R=>e.identifier(R)),e`, `),N=(_,R,p,F,h,u)=>{const s=ye(p.partitionBy??[],u),C=p.sortBy.map(I=>J(u[I.field]??null)),L=e.join([h,s,...C].map(I=>ue(I)),e`, `);$(_,e`INSERT INTO ${e.identifier(R)} (${F}) VALUES (${L})`)},Te=(_,R,p,F,h,u)=>{if(h&&u&&he(p,h,u))return;const s=X(R,p.name);h&&$(_,e`DELETE FROM ${e.identifier(s)} WHERE ${e.identifier("__id__")} = ${F}`),!(!u||p.where&&!Y(u,p.where))&&N(_,s,p,Z(p),F,u)},be=_=>{const{broadcast:R,indexKeysFor:p,invalidateCache:F,recordCdc:h,schema:u,sql:s}=_,C=new Set,L=n=>u.tables[n]?.softDeleteMode?.field,I=new Set,U=(n,o)=>{const r=`${n}::${o.name}`;if(C.has(r))return;const c=P(n,o.name),a=o.by??[],f=L(n),d=new Map,y=$(s,e`SELECT id, _creationTime, ${e.identifier(b)} FROM ${e.identifier(n)}`).toArray();for(const T of y){const l=q(T);if(!l||!Q(l,f)||o.where&&!V(l,o.where))continue;const S=v(a,l);z(d,S,o,l)}$(s,e`DELETE FROM ${e.identifier(c)}`);const A=Math.floor(Ee.boundParams/3),w=[...d];for(let T=0;T<w.length;T+=A){const l=w.slice(T,T+A),S=e.join(l.map(([t,i])=>e`(${t}, ${i.value}, ${i.count})`),e`, `);$(s,e`INSERT INTO ${e.identifier(c)} (${O}, ${m}, ${g}) VALUES ${S}`)}C.add(r)},x=(n,o,r)=>{const c=o.by??[],a=o.field??"",f=[],d=(t,i)=>{const E=J(i);E===null?f.push(e`${W(t)} IS NULL`):f.push(e`${W(t)} = ${E}`)};for(const t of c)d(t,r[t]??null);const y=L(n);y!==void 0&&d(y,null);for(const[t,i]of Object.entries(o.where??{}))d(t,i!==null&&typeof i=="object"&&!Array.isArray(i)?i.eq:i);const A=f.length>0?e` WHERE ${e.join(f,e` AND `)}`:e``,w=u.tables[n]?.shape[a];if(w&&me(w)){const t=$(s,e`SELECT id, _creationTime, ${e.identifier(b)} FROM ${e.identifier(n)}${A}`).toArray(),i=new Map;for(const E of t){const k=q(E);k&&z(i,"",o,k)}return{value:i.get("")?.value??null}}const T=fe(o.op),l=W(a);return{value:$(s,e`SELECT ${e.raw(T)}(${l}) AS value FROM ${e.identifier(n)}${A}`).one().value??null}},ee=(n,o,r,c)=>{const a=P(n,o.name),{op:f}=o,d=o.field??"",y=t=>{$(s,e`DELETE FROM ${e.identifier(a)} WHERE ${O} = ${t} AND ${g} <= 0`)},A=L(n),w=t=>!o.where||V(t,o.where),T=t=>Q(t,A)&&w(t);c!==void 0&&f!=="count"&&w(c)&&D(c[d]);const l=r&&T(r)?r:void 0,S=c&&T(c)?c:void 0;if(!(!l&&!S)){if(f==="count"){for(const[t,i]of[[l,-1],[S,1]]){if(!t)continue;const E=v(o.by??[],t);$(s,M(a,E,i,i,e`${m} = ${m} + excluded.${m}, ${g} = ${g} + excluded.${g}`))}l&&y(v(o.by??[],l));return}if(f==="sum"||f==="avg"){for(const[t,i]of[[l,-1],[S,1]]){if(!t)continue;const E=D(t[d]);if(E===void 0)continue;const k=v(o.by??[],t);$(s,M(a,k,i*E,i,e`${m} = COALESCE(${m}, 0) + excluded.${m}, ${g} = ${g} + excluded.${g}`))}l&&y(v(o.by??[],l));return}if(l){const t=v(o.by??[],l),i=D(l[d]),E=$(s,e`SELECT ${m} AS value, ${g} AS count FROM ${e.identifier(a)} WHERE ${O} = ${t}`).toArray()[0],k=(E?.count??0)-1;if(k<=0)$(s,e`DELETE FROM ${e.identifier(a)} WHERE ${O} = ${t}`);else if(E&&i!==void 0&&E.value!==null&&i===E.value){const te=x(n,o,l);$(s,e`UPDATE ${e.identifier(a)} SET ${m} = ${te.value}, ${g} = ${k} WHERE ${O} = ${t}`)}else $(s,e`UPDATE ${e.identifier(a)} SET ${g} = ${g} - 1 WHERE ${O} = ${t}`)}if(S){const t=v(o.by??[],S),i=D(S[d]);if(i===void 0)$(s,M(a,t,null,1,e`${g} = ${g} + 1`));else{const E=f==="min"?"MIN":"MAX";$(s,M(a,t,i,1,e`${m} = ${e.raw(E)}(COALESCE(${m}, excluded.${m}), excluded.${m}), ${g} = ${g} + 1`))}}}},oe=n=>{for(const o of u.tables[n]?.aggregateIndexes??[])U(n,o)},j=(n,o,r)=>{for(const c of u.tables[n]?.aggregateIndexes??[])ee(n,c,o,r)},B=(n,o)=>{const r=`${n}::rank::${o.name}`;if(I.has(r))return;const c=X(n,o.name),a=$(s,e`SELECT id, _creationTime, ${e.identifier(b)} FROM ${e.identifier(n)}`).toArray();$(s,e`DELETE FROM ${e.identifier(c)}`);const f=Z(o);for(const d of a){const y=q(d);!y||o.where&&!Y(y,o.where)||N(s,c,o,f,y._id,y)}I.add(r)},ne=n=>{for(const o of u.tables[n]?.rankIndexes??[])B(n,o)},H=(n,o,r,c)=>{for(const a of u.tables[n]?.rankIndexes??[])Te(s,n,a,o,r,c)},K=(n,o,r,c)=>{const a=u.tables[n]?.searchIndexes??[];if(!(a.length===0||!$e(s)))for(const f of a){if(re(c,r,f))continue;const d=se(n,f.name);le(s,r?ie(d,o,ce(r,f)):ae(d,o))}},G=(n,o,r)=>{for(const c of u.tables[n]?.geoIndexes??[]){const a=de(n,c.name);$(s,e`DELETE FROM ${e.identifier(a)} WHERE ${e.identifier("__id__")} = ${o}`);const f=r?.[c.field];if(f!==null&&typeof f=="object"&&typeof f.lat=="number"&&typeof f.lng=="number"){const{lat:d,lng:y}=f,A=ge({lat:d,lng:y},c.precision??pe);$(s,e`INSERT INTO ${e.identifier(a)} (${e.identifier("__id__")}, ${e.identifier("__geohash__")}, ${e.identifier("__lat__")}, ${e.identifier("__lng__")}) VALUES (${o}, ${A}, ${d}, ${y})`)}}};return{ensureBackfilledForTable:oe,ensureBackfilledIndex:U,ensureRankBackfilled:B,ensureRankBackfilledForTable:ne,syncAggregates:j,syncCompanionsForInsert:(n,o,r)=>{K(n,o,r),G(n,o,r),j(n,void 0,r),H(n,o,void 0,r),F(n,o,r),h(n,o,"insert",r),R({indexKeys:p(n,r),key:o,op:"insert",row:r,table:n})},syncGeo:G,syncRanks:H,syncSearch:K}};export{be as createCompanionSync,N as insertRankRow,Z as rankColumnsSql};
@@ -0,0 +1,7 @@
1
+ import{d as p,e as S}from"./wire-codec-C-FpWm52.mjs";import{cursorBelowRetainedFloor as y}from"./CDC_LOG_TABLE-QaBxSIZM.mjs";import{envPositiveInt as v}from"./envOptionalPositiveInt-D2pY-c64.mjs";import{v as A,R as g,s as N,a as E,b as T}from"./sibling-channel-BkL5cTCc.mjs";const L=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"],O=new Set(L),b=s=>typeof s=="string"&&O.has(s),h="::replica::",R=s=>{const e=s.lastIndexOf(h);if(e===-1)return;const t=s.slice(0,e),r=s.slice(e+h.length);if(!(t.length===0||!b(r)))return{ownerKey:t,region:r}},I=s=>{if(s==null||!/^\d+$/.test(s))return;const e=Number.parseInt(s,10);return Number.isSafeInteger(e)&&e>0?e:void 0},m=1e3,w=1e3,C=10,U=5e4,F=s=>v(s,"LUNORA_REPLICA_MAX_BOOTSTRAP_ROWS",U),d="__replica_state",l=new WeakSet,_=s=>{l.has(s)||(s.exec(`CREATE TABLE IF NOT EXISTS ${d} (
2
+ id INTEGER PRIMARY KEY CHECK (id = 1),
3
+ epoch TEXT NOT NULL,
4
+ applied_seq INTEGER NOT NULL,
5
+ synced_at REAL NOT NULL
6
+ )`),l.add(s))},c=s=>(_(s),s.exec(`SELECT epoch, applied_seq AS appliedSeq, synced_at AS syncedAtMs FROM ${d} WHERE id = 1`).toArray()[0]),f=(s,e)=>{_(s),s.exec(`INSERT INTO ${d} (id, epoch, applied_seq, synced_at) VALUES (1, ?, ?, ?)
7
+ ON CONFLICT(id) DO UPDATE SET epoch = excluded.epoch, applied_seq = excluded.applied_seq, synced_at = excluded.synced_at`,e.epoch,e.appliedSeq,e.syncedAtMs)},q=s=>{const e=s.doName();if(e!==void 0&&R(e)!==void 0)return new Response("replica cannot serve replicas",{status:409});if(s.ownerEpoch()===void 0)return new Response("shard has no changelog to replicate",{status:409});if(E(s.env())===void 0)return new Response("replica control requires LUNORA_RELAY_SECRET",{status:403})},a=s=>Response.json(S(s)),P=async(s,e)=>{if(s.rowCount()>F(s.env()))return a({cursor:0,epoch:e,rows:[],truncated:!0});const t=s.ownerCursor()??0,r=await s.exportRows();return a({cursor:t,epoch:e,rows:r})},M=(s,e,t)=>{const r=s.ownerFloor();if(y(r,t))return a({changes:[],cursor:s.ownerCursor()??t,epoch:e,floor:r});const n=s.ownerCursor()??0;if(t>n)return a({changes:[],cursor:n,epoch:e,...r===void 0?{}:{floor:r}});const{changes:o,cursor:i}=s.readChanges(t,w);return a({changes:o,cursor:i,epoch:e,...r===void 0?{}:{floor:r}})},K=async(s,e)=>{const t=q(s);if(t!==void 0)return t;const r=s.ownerEpoch();let n;try{n=await e.text()}catch{return new Response("bad request",{status:400})}if(!await A(s.env(),e.headers.get(g),n))return new Response("forbidden",{status:403});let o;try{o=JSON.parse(n)}catch{return new Response("bad request",{status:400})}if(o.type==="replica_bootstrap")return P(s,r);if(o.type==="replica_pull"){const i=typeof o.sinceSeq=="number"&&Number.isInteger(o.sinceSeq)&&o.sinceSeq>=0?o.sinceSeq:0;return M(s,r,i)}return new Response("unknown replica frame",{status:400})};class x{constructor(e,t,r){this.host=e,this.ownerKey=t,this.region=r}host;ownerKey;region;divergent=!1;inFlight;async ensureFresh(e){if(this.divergent)return"unavailable";if(this.isCaughtUp(e))return"fresh";this.inFlight??=this.advance(e).finally(()=>{this.inFlight=void 0});const t=await this.inFlight;return t==="fresh"&&!this.isCaughtUp(e)?"stale":t}appliedSeq(){return c(this.host.sql())?.appliedSeq??0}isDivergent(){return this.divergent}async advance(e){let t=c(this.host.sql());if(t===void 0){const r=await this.bootstrap();if(r===void 0)return"unavailable";t=r}return this.catchUp(t,e)}isCaughtUp(e){const t=c(this.host.sql());return t!==void 0&&this.isFreshEnough(t,e)}async catchUp(e,t){let r=e;for(let n=0;n<C;n+=1){const o=await this.pull(r.appliedSeq);if(o===void 0)return t===void 0&&this.isFreshEnough(r,void 0)?"fresh":"unavailable";if(this.hasDiverged(r,o))return"unavailable";const i=o.changes.length<w;if(r=await this.applyPage(o,r,i),i||this.isFreshEnough(r,t))return this.isFreshEnough(r,t)?"fresh":"stale"}return this.isFreshEnough(r,t)?"fresh":"stale"}async applyPage(e,t,r){e.changes.length>0&&await this.host.applyChanges(e.changes);const n={appliedSeq:e.cursor,epoch:e.epoch,syncedAtMs:r?Date.now():t.syncedAtMs};return f(this.host.sql(),n),n}hasDiverged(e,t){const r=t.changes.length===0&&t.cursor>e.appliedSeq,n=t.floor??(r?t.cursor:0),o=n>0&&n>e.appliedSeq+1,i=t.cursor<e.appliedSeq;return t.epoch===e.epoch&&!o&&!i?!1:(this.divergent=!0,!0)}async bootstrap(){const e=await this.request({type:"replica_bootstrap"});if(e===void 0)return;const t=p(await e.json());if(t.truncated===!0){this.divergent=!0;return}const{errors:r}=await this.host.importRows(t.rows);if(r.length>0){this.divergent=!0;return}const n={appliedSeq:t.cursor,epoch:t.epoch,syncedAtMs:Date.now()};return f(this.host.sql(),n),n}isFreshEnough(e,t){return t!==void 0?e.appliedSeq>=t:Date.now()-e.syncedAtMs<=v(this.host.env(),"LUNORA_REPLICA_MAX_STALENESS_MS",m)}async pull(e){const t=await this.request({sinceSeq:e,type:"replica_pull"});return t===void 0?void 0:p(await t.json())}async request(e){const t=this.host.shardBinding(),r=N(this.host.env(),t,this.ownerKey,this.host.shardJurisdiction());if(r===void 0)return;const n=JSON.stringify(e),o={"content-type":"application/json","x-lunora-shard-binding":t??""},i=E(this.host.env());i!==void 0&&(o[g]=await T(i,n));try{const u=await r.fetch("https://replica.internal/_lunora/replica",{body:n,headers:o,method:"POST"});return u.ok?u:void 0}catch{return}}}const j=s=>{const e=s.doName();if(e===void 0)return;const t=R(e);return t===void 0?void 0:new x(s,t.ownerKey,t.region)},G=async(s,e,t)=>{if(e.headers.get("x-lunora-replica-read")!=="1")return Response.json({error:{code:"REPLICA_READ_ONLY",message:`"${t}" is a write and cannot run on a read replica`}},{status:421});const r=await s.ensureFresh(I(e.headers.get("x-lunora-min-seq")));if(r!=="fresh")return Response.json({error:{code:"REPLICA_NOT_READY",message:`replica is ${r} for this read`}},{headers:{"x-lunora-replica-fallback":r},status:421})};export{j as createReplicaLink,G as gateReplicaDispatch,K as handleReplicaControl};
@@ -1,4 +1,4 @@
1
- import{sql as i}from"drizzle-orm";import{e as l,d as E}from"./wire-codec-C-FpWm52.mjs";import{runDrizzle as a}from"./runDrizzle-BlpM0R9P.mjs";import{relayProxyKey as T}from"./DEFAULT_PROMOTION_THRESHOLDS-Bfx7KakS.mjs";const t="__lunora_relay_shapes",o=null,R=e=>{a(e,i`CREATE TABLE IF NOT EXISTS ${i.identifier(t)} (
1
+ import{sql as i}from"drizzle-orm";import{e as l,d as E}from"./wire-codec-C-FpWm52.mjs";import{runDrizzle as a}from"./runDrizzle-Du5HLitO.mjs";import{relayProxyKey as T}from"./DEFAULT_PROMOTION_THRESHOLDS-91RH_llq.mjs";const t="__lunora_relay_shapes",o=null,R=e=>{a(e,i`CREATE TABLE IF NOT EXISTS ${i.identifier(t)} (
2
2
  key TEXT PRIMARY KEY,
3
3
  relay_idx INTEGER,
4
4
  connection_id TEXT,
@@ -1 +1 @@
1
- import{D as E}from"./MAX_TOKEN_LENGTH-BakL9FUy-B3VwYY8C.mjs";import{sql as e}from"drizzle-orm";import{runDrizzle as t}from"./runDrizzle-BlpM0R9P.mjs";const S=i=>`${E(i.language).profile}:${i.field}`,c=i=>{const r=i.slice(i.indexOf(":")+1),o=r.lastIndexOf("/");return o===-1?r:r.slice(0,o)},N=(i,r)=>i.profile!==r?{cursor:void 0,finished:!1,wipe:i.cursor!==void 0||i.done}:{cursor:i.cursor,finished:i.done,wipe:!1},T=(i,r)=>typeof i=="string"&&c(i)===c(r),n="__lunora_search_state",R=i=>{t(i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(n)} (${e.identifier("companion")} TEXT PRIMARY KEY, ${e.identifier("cursor")} TEXT, ${e.identifier("done")} INTEGER NOT NULL DEFAULT 0, ${e.identifier("profile")} TEXT, ${e.identifier("covered")} INTEGER NOT NULL DEFAULT 0)`);try{t(i,e`ALTER TABLE ${e.identifier(n)} ADD COLUMN ${e.identifier("profile")} TEXT`)}catch{}try{t(i,e`ALTER TABLE ${e.identifier(n)} ADD COLUMN ${e.identifier("covered")} INTEGER NOT NULL DEFAULT 0`)}catch{}t(i,e`UPDATE ${e.identifier(n)} SET ${e.identifier("covered")} = 1 WHERE ${e.identifier("done")} = 1 AND ${e.identifier("covered")} = 0`)},s=i=>i===1||i===!0||i==="1",O=(i,r)=>{const o=t(i,e`SELECT ${e.identifier("covered")} FROM ${e.identifier(n)} WHERE ${e.identifier("companion")} = ${r}`).toArray();return s(o[0]?.covered)},l=(i,r,o)=>{const d=t(i,e`SELECT ${e.identifier("cursor")}, ${e.identifier("done")}, ${e.identifier("profile")} FROM ${e.identifier(r)} WHERE ${e.identifier("companion")} = ${o}`).toArray()[0];return d?{cursor:d.cursor??void 0,done:s(d.done),profile:d.profile??void 0}:{cursor:void 0,done:!1,profile:void 0}},u=(i,r)=>l(i,n,r),D=(i,r,o,f,d)=>{const $=o??null,a=T(u(i,r).profile,d)?e`MAX(${e.identifier(n)}.${e.identifier("covered")}, excluded.${e.identifier("covered")})`:e`excluded.${e.identifier("covered")}`;t(i,e`INSERT INTO ${e.identifier(n)} (${e.identifier("companion")}, ${e.identifier("cursor")}, ${e.identifier("done")}, ${e.identifier("profile")}, ${e.identifier("covered")}) VALUES (${r}, ${$}, ${f?1:0}, ${d}, ${f?1:0}) ON CONFLICT (${e.identifier("companion")}) DO UPDATE SET ${e.identifier("cursor")} = excluded.${e.identifier("cursor")}, ${e.identifier("done")} = excluded.${e.identifier("done")}, ${e.identifier("profile")} = excluded.${e.identifier("profile")}, ${e.identifier("covered")} = ${a}`)};export{n as S,O as a,l as b,S as c,N as l,R as m,u as r,D as w};
1
+ import{D as E}from"./MAX_TOKEN_LENGTH-BakL9FUy-B3VwYY8C.mjs";import{sql as e}from"drizzle-orm";import{runDrizzle as t}from"./runDrizzle-Du5HLitO.mjs";const S=i=>`${E(i.language).profile}:${i.field}`,c=i=>{const r=i.slice(i.indexOf(":")+1),o=r.lastIndexOf("/");return o===-1?r:r.slice(0,o)},N=(i,r)=>i.profile!==r?{cursor:void 0,finished:!1,wipe:i.cursor!==void 0||i.done}:{cursor:i.cursor,finished:i.done,wipe:!1},T=(i,r)=>typeof i=="string"&&c(i)===c(r),n="__lunora_search_state",R=i=>{t(i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(n)} (${e.identifier("companion")} TEXT PRIMARY KEY, ${e.identifier("cursor")} TEXT, ${e.identifier("done")} INTEGER NOT NULL DEFAULT 0, ${e.identifier("profile")} TEXT, ${e.identifier("covered")} INTEGER NOT NULL DEFAULT 0)`);try{t(i,e`ALTER TABLE ${e.identifier(n)} ADD COLUMN ${e.identifier("profile")} TEXT`)}catch{}try{t(i,e`ALTER TABLE ${e.identifier(n)} ADD COLUMN ${e.identifier("covered")} INTEGER NOT NULL DEFAULT 0`)}catch{}t(i,e`UPDATE ${e.identifier(n)} SET ${e.identifier("covered")} = 1 WHERE ${e.identifier("done")} = 1 AND ${e.identifier("covered")} = 0`)},s=i=>i===1||i===!0||i==="1",O=(i,r)=>{const o=t(i,e`SELECT ${e.identifier("covered")} FROM ${e.identifier(n)} WHERE ${e.identifier("companion")} = ${r}`).toArray();return s(o[0]?.covered)},l=(i,r,o)=>{const d=t(i,e`SELECT ${e.identifier("cursor")}, ${e.identifier("done")}, ${e.identifier("profile")} FROM ${e.identifier(r)} WHERE ${e.identifier("companion")} = ${o}`).toArray()[0];return d?{cursor:d.cursor??void 0,done:s(d.done),profile:d.profile??void 0}:{cursor:void 0,done:!1,profile:void 0}},u=(i,r)=>l(i,n,r),D=(i,r,o,f,d)=>{const $=o??null,a=T(u(i,r).profile,d)?e`MAX(${e.identifier(n)}.${e.identifier("covered")}, excluded.${e.identifier("covered")})`:e`excluded.${e.identifier("covered")}`;t(i,e`INSERT INTO ${e.identifier(n)} (${e.identifier("companion")}, ${e.identifier("cursor")}, ${e.identifier("done")}, ${e.identifier("profile")}, ${e.identifier("covered")}) VALUES (${r}, ${$}, ${f?1:0}, ${d}, ${f?1:0}) ON CONFLICT (${e.identifier("companion")}) DO UPDATE SET ${e.identifier("cursor")} = excluded.${e.identifier("cursor")}, ${e.identifier("done")} = excluded.${e.identifier("done")}, ${e.identifier("profile")} = excluded.${e.identifier("profile")}, ${e.identifier("covered")} = ${a}`)};export{n as S,O as a,l as b,S as c,N as l,R as m,u as r,D as w};