@lunora/server 1.0.0-alpha.142 → 1.0.0-alpha.143

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -563,6 +563,14 @@ interface VectorizeOptions<Shape extends Record<string, Validator> = Record<stri
563
563
  /** Fields mirrored into Vectorize metadata for filtering. */
564
564
  metadata?: ReadonlyArray<keyof Shape & string>;
565
565
  metric: VectorMetric;
566
+ /**
567
+ * Identifier of the model `embed` calls, e.g. `"@cf/baai/bge-base-en-v1.5"`.
568
+ * `embed` is a function Lunora cannot inspect, so this string is how a model
569
+ * swap becomes visible: the `backfillVectors` admin op records it and
570
+ * re-embeds the table when it changes. Omit it and a model change goes
571
+ * unnoticed until the backfill is run with `restart: true`.
572
+ */
573
+ model?: string;
566
574
  }
567
575
  /** A `one` (many-to-one) relation descriptor; phantom `Target` carries the target table name. */
568
576
  interface OneRelation<Target extends string = string> extends RelationDefinition {
@@ -864,6 +872,15 @@ interface VectorIndexOptions {
864
872
  /** Optional projection of the source row into Vectorize metadata. */
865
873
  metadata?: (row: Record<string, unknown>) => Record<string, unknown>;
866
874
  metric: VectorMetric;
875
+ /**
876
+ * Identifier of the model `embed` calls, e.g. `"@cf/baai/bge-base-en-v1.5"`.
877
+ * `embed` is a function Lunora cannot inspect, so this string is how a model
878
+ * swap becomes visible: the `backfillVectors` admin op records it and
879
+ * re-embeds the table when it changes. Omit it and a model change goes
880
+ * unnoticed, as does a change to `select` or `metadata`, until the backfill
881
+ * is run with `restart: true`.
882
+ */
883
+ model?: string;
867
884
  /** The vector source: which table, and how to derive the embedded text. */
868
885
  source: {
869
886
  select: (row: Record<string, unknown>) => string;
package/dist/index.d.ts CHANGED
@@ -563,6 +563,14 @@ interface VectorizeOptions<Shape extends Record<string, Validator> = Record<stri
563
563
  /** Fields mirrored into Vectorize metadata for filtering. */
564
564
  metadata?: ReadonlyArray<keyof Shape & string>;
565
565
  metric: VectorMetric;
566
+ /**
567
+ * Identifier of the model `embed` calls, e.g. `"@cf/baai/bge-base-en-v1.5"`.
568
+ * `embed` is a function Lunora cannot inspect, so this string is how a model
569
+ * swap becomes visible: the `backfillVectors` admin op records it and
570
+ * re-embeds the table when it changes. Omit it and a model change goes
571
+ * unnoticed until the backfill is run with `restart: true`.
572
+ */
573
+ model?: string;
566
574
  }
567
575
  /** A `one` (many-to-one) relation descriptor; phantom `Target` carries the target table name. */
568
576
  interface OneRelation<Target extends string = string> extends RelationDefinition {
@@ -864,6 +872,15 @@ interface VectorIndexOptions {
864
872
  /** Optional projection of the source row into Vectorize metadata. */
865
873
  metadata?: (row: Record<string, unknown>) => Record<string, unknown>;
866
874
  metric: VectorMetric;
875
+ /**
876
+ * Identifier of the model `embed` calls, e.g. `"@cf/baai/bge-base-en-v1.5"`.
877
+ * `embed` is a function Lunora cannot inspect, so this string is how a model
878
+ * swap becomes visible: the `backfillVectors` admin op records it and
879
+ * re-embeds the table when it changes. Omit it and a model change goes
880
+ * unnoticed, as does a change to `select` or `metadata`, until the backfill
881
+ * is run with `restart: true`.
882
+ */
883
+ model?: string;
867
884
  /** The vector source: which table, and how to derive the embedded text. */
868
885
  source: {
869
886
  select: (row: Record<string, unknown>) => string;
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{ACTION_CACHE_DEFAULT_TTL_MS as t,ACTION_CACHE_TABLE as n,actionCacheExtension as i,cacheKeyFor as a,defineActionCache as f}from"./packem_shared/ACTION_CACHE_DEFAULT_TTL_MS-DznN8R6L.mjs";import{initLunora as d}from"./packem_shared/initLunora-DAbEYdSo.mjs";import{isPerDispatchMiddleware as m,tagPerDispatchMiddleware as x}from"./packem_shared/isPerDispatchMiddleware-DDQPatSm.mjs";import{createSecrets as l}from"./packem_shared/createSecrets-D6rLB42U.mjs";import{beginDeferredDeletes as h,flushDeferredDeletes as S,withDeferredDeletes as u}from"./packem_shared/beginDeferredDeletes-DhwFBbvs.mjs";import{beginDeferredSchedules as T,withDeferredSchedules as g}from"./packem_shared/beginDeferredSchedules-CIhFddA2.mjs";import{DOCUMENT_HISTORY_REDACTED_FIELDS as R,DOCUMENT_HISTORY_TABLE as _,defineDocumentHistory as L,documentHistoryExtension as C}from"./packem_shared/DOCUMENT_HISTORY_REDACTED_FIELDS-DTWvHJax.mjs";import{LunoraEnvError as P,defineEnv as M,redactSecrets as b}from"./packem_shared/LunoraEnvError-A5I-PzMh.mjs";import{bindOrm as F,bindTableFacade as O}from"./packem_shared/bindOrm-D_hFUjmr.mjs";import{httpAction as N,httpRoute as w,httpRouter as U,isSafeHeaderValue as k}from"./packem_shared/httpAction-DFVhrm8u.mjs";import{serveStorageObject as B}from"./packem_shared/serveStorageObject-9mdw0nyU.mjs";import{defineIdentity as W}from"./packem_shared/defineIdentity-DwkNKwYa.mjs";import{onConnect as Y,onDisconnect as J,onShardInit as K}from"./packem_shared/onConnect-BLRoOpv2.mjs";import{DEFAULT_LIMIT as X,DEFAULT_MAX_LIMIT as q,clampLimit as z,defineListArgs as G}from"./packem_shared/DEFAULT_LIMIT-vNtdsa5y.mjs";import{defineMigration as $}from"./packem_shared/defineMigration-CXOS0Bvq.mjs";import{defineMutator as re}from"./packem_shared/defineMutator-DKy8UtbB.mjs";import{c as te,d as ne,a as ie,b as ae,e as fe,f as se,g as de,h as pe,i as me,j as xe,k as ce,m as le}from"./packem_shared/plugin-BQ2GySyZ.mjs";import{PRESENCE_DEFAULT_TTL_MS as he,PRESENCE_TABLE as Se,definePresence as ue,presenceExtension as De}from"./packem_shared/PRESENCE_DEFAULT_TTL_MS-BjHdghSv.mjs";import{protectPublic as ge}from"./packem_shared/protectPublic-BUYCMZZB.mjs";import{onQueryChange as Re}from"./packem_shared/onQueryChange-CatdYnH5.mjs";import{defineShape as Le}from"./packem_shared/defineShape-Be5u-Whf.mjs";import{anyApi as Ie}from"./types.mjs";import{onWhisper as Me}from"./packem_shared/onWhisper-CfDbFLQh.mjs";import{LunoraError as ye}from"@lunora/errors";import{cronJobs as Oe}from"@lunora/scheduler";import{ValidationError as Ne,v as we}from"@lunora/values";import{allowAll as ke,deny as ve,isDeny as Be,toWhereInput as Ve}from"./packem_shared/allowAll-DkRAgItV.mjs";import{asBucketStorage as je}from"./packem_shared/asBucketStorage-DoGYOjq3.mjs";import{assertShapesDeclareReadPolicies as Je,buildRlsReadRegistry as Ke,composeShapeReadWhere as Qe}from"./packem_shared/assertShapesDeclareReadPolicies-CjJWccLg.mjs";import{buildMaskRegistry as qe}from"./packem_shared/buildMaskRegistry-DpWMtalG.mjs";import{createPolicyDsl as Ge,definePermission as Ze,definePolicies as $e,definePolicy as er,defineRole as rr}from"./packem_shared/createPolicyDsl-BZa6SqLJ.mjs";import{defineStorageRule as tr,defineStorageRules as nr}from"./packem_shared/defineStorageRule-Dv4nJE0H.mjs";import{mask as ar}from"./packem_shared/mask-DsL8pZvt.mjs";import{r as sr}from"./packem_shared/middleware-CgYaL-lL.mjs";import{storageRules as pr}from"./packem_shared/storageRules-DLH8uzGB.mjs";const e="0.0.0";export{t as ACTION_CACHE_DEFAULT_TTL_MS,n as ACTION_CACHE_TABLE,X as DEFAULT_LIMIT,q as DEFAULT_MAX_LIMIT,R as DOCUMENT_HISTORY_REDACTED_FIELDS,_ as DOCUMENT_HISTORY_TABLE,P as LunoraEnvError,ye as LunoraError,he as PRESENCE_DEFAULT_TTL_MS,Se as PRESENCE_TABLE,e as VERSION,Ne as ValidationError,i as actionCacheExtension,ke as allowAll,Ie as anyApi,je as asBucketStorage,Je as assertShapesDeclareReadPolicies,h as beginDeferredDeletes,T as beginDeferredSchedules,F as bindOrm,O as bindTableFacade,qe as buildMaskRegistry,Ke as buildRlsReadRegistry,a as cacheKeyFor,z as clampLimit,te as composePluginMiddleware,Qe as composeShapeReadWhere,Ge as createPolicyDsl,l as createSecrets,Oe as cronJobs,f as defineActionCache,ne as defineAggregateIndex,ie as defineComponent,L as defineDocumentHistory,M as defineEnv,W as defineIdentity,G as defineListArgs,$ as defineMigration,re as defineMutator,Ze as definePermission,ae as definePlugin,$e as definePolicies,er as definePolicy,ue as definePresence,fe as defineRankIndex,rr as defineRole,se as defineSchema,de as defineSchemaExtension,Le as defineShape,tr as defineStorageRule,nr as defineStorageRules,pe as defineTable,me as defineVectorIndex,ve as deny,C as documentHistoryExtension,S as flushDeferredDeletes,N as httpAction,w as httpRoute,U as httpRouter,xe as indexFieldsFromSchema,d as initLunora,ce as installPlugins,Be as isDeny,m as isPerDispatchMiddleware,k as isSafeHeaderValue,ar as mask,le as mergeSchemaExtension,Y as onConnect,J as onDisconnect,Re as onQueryChange,K as onShardInit,Me as onWhisper,De as presenceExtension,ge as protectPublic,b as redactSecrets,sr as rls,B as serveStorageObject,pr as storageRules,x as tagPerDispatchMiddleware,Ve as toWhereInput,we as v,u as withDeferredDeletes,g as withDeferredSchedules};
1
+ import{ACTION_CACHE_DEFAULT_TTL_MS as t,ACTION_CACHE_TABLE as n,actionCacheExtension as i,cacheKeyFor as a,defineActionCache as f}from"./packem_shared/ACTION_CACHE_DEFAULT_TTL_MS-zqB8Qi2c.mjs";import{initLunora as d}from"./packem_shared/initLunora-DAbEYdSo.mjs";import{isPerDispatchMiddleware as m,tagPerDispatchMiddleware as x}from"./packem_shared/isPerDispatchMiddleware-DDQPatSm.mjs";import{createSecrets as l}from"./packem_shared/createSecrets-D6rLB42U.mjs";import{beginDeferredDeletes as h,flushDeferredDeletes as S,withDeferredDeletes as u}from"./packem_shared/beginDeferredDeletes-DhwFBbvs.mjs";import{beginDeferredSchedules as T,withDeferredSchedules as g}from"./packem_shared/beginDeferredSchedules-CIhFddA2.mjs";import{DOCUMENT_HISTORY_REDACTED_FIELDS as R,DOCUMENT_HISTORY_TABLE as _,defineDocumentHistory as L,documentHistoryExtension as C}from"./packem_shared/DOCUMENT_HISTORY_REDACTED_FIELDS-B08eqNw4.mjs";import{LunoraEnvError as P,defineEnv as M,redactSecrets as b}from"./packem_shared/LunoraEnvError-A5I-PzMh.mjs";import{bindOrm as F,bindTableFacade as O}from"./packem_shared/bindOrm-D_hFUjmr.mjs";import{httpAction as N,httpRoute as w,httpRouter as U,isSafeHeaderValue as k}from"./packem_shared/httpAction-DFVhrm8u.mjs";import{serveStorageObject as B}from"./packem_shared/serveStorageObject-9mdw0nyU.mjs";import{defineIdentity as W}from"./packem_shared/defineIdentity-DwkNKwYa.mjs";import{onConnect as Y,onDisconnect as J,onShardInit as K}from"./packem_shared/onConnect-BLRoOpv2.mjs";import{DEFAULT_LIMIT as X,DEFAULT_MAX_LIMIT as q,clampLimit as z,defineListArgs as G}from"./packem_shared/DEFAULT_LIMIT-vNtdsa5y.mjs";import{defineMigration as $}from"./packem_shared/defineMigration-CXOS0Bvq.mjs";import{defineMutator as re}from"./packem_shared/defineMutator-DKy8UtbB.mjs";import{c as te,d as ne,a as ie,b as ae,e as fe,f as se,g as de,h as pe,i as me,j as xe,k as ce,m as le}from"./packem_shared/plugin-C5XIUmql.mjs";import{PRESENCE_DEFAULT_TTL_MS as he,PRESENCE_TABLE as Se,definePresence as ue,presenceExtension as De}from"./packem_shared/PRESENCE_DEFAULT_TTL_MS-Ch-Y_Qns.mjs";import{protectPublic as ge}from"./packem_shared/protectPublic-BUYCMZZB.mjs";import{onQueryChange as Re}from"./packem_shared/onQueryChange-CatdYnH5.mjs";import{defineShape as Le}from"./packem_shared/defineShape-Be5u-Whf.mjs";import{anyApi as Ie}from"./types.mjs";import{onWhisper as Me}from"./packem_shared/onWhisper-CfDbFLQh.mjs";import{LunoraError as ye}from"@lunora/errors";import{cronJobs as Oe}from"@lunora/scheduler";import{ValidationError as Ne,v as we}from"@lunora/values";import{allowAll as ke,deny as ve,isDeny as Be,toWhereInput as Ve}from"./packem_shared/allowAll-DkRAgItV.mjs";import{asBucketStorage as je}from"./packem_shared/asBucketStorage-DoGYOjq3.mjs";import{assertShapesDeclareReadPolicies as Je,buildRlsReadRegistry as Ke,composeShapeReadWhere as Qe}from"./packem_shared/assertShapesDeclareReadPolicies-CjJWccLg.mjs";import{buildMaskRegistry as qe}from"./packem_shared/buildMaskRegistry-DpWMtalG.mjs";import{createPolicyDsl as Ge,definePermission as Ze,definePolicies as $e,definePolicy as er,defineRole as rr}from"./packem_shared/createPolicyDsl-BZa6SqLJ.mjs";import{defineStorageRule as tr,defineStorageRules as nr}from"./packem_shared/defineStorageRule-Dv4nJE0H.mjs";import{mask as ar}from"./packem_shared/mask-DsL8pZvt.mjs";import{r as sr}from"./packem_shared/middleware-CgYaL-lL.mjs";import{storageRules as pr}from"./packem_shared/storageRules-DLH8uzGB.mjs";const e="0.0.0";export{t as ACTION_CACHE_DEFAULT_TTL_MS,n as ACTION_CACHE_TABLE,X as DEFAULT_LIMIT,q as DEFAULT_MAX_LIMIT,R as DOCUMENT_HISTORY_REDACTED_FIELDS,_ as DOCUMENT_HISTORY_TABLE,P as LunoraEnvError,ye as LunoraError,he as PRESENCE_DEFAULT_TTL_MS,Se as PRESENCE_TABLE,e as VERSION,Ne as ValidationError,i as actionCacheExtension,ke as allowAll,Ie as anyApi,je as asBucketStorage,Je as assertShapesDeclareReadPolicies,h as beginDeferredDeletes,T as beginDeferredSchedules,F as bindOrm,O as bindTableFacade,qe as buildMaskRegistry,Ke as buildRlsReadRegistry,a as cacheKeyFor,z as clampLimit,te as composePluginMiddleware,Qe as composeShapeReadWhere,Ge as createPolicyDsl,l as createSecrets,Oe as cronJobs,f as defineActionCache,ne as defineAggregateIndex,ie as defineComponent,L as defineDocumentHistory,M as defineEnv,W as defineIdentity,G as defineListArgs,$ as defineMigration,re as defineMutator,Ze as definePermission,ae as definePlugin,$e as definePolicies,er as definePolicy,ue as definePresence,fe as defineRankIndex,rr as defineRole,se as defineSchema,de as defineSchemaExtension,Le as defineShape,tr as defineStorageRule,nr as defineStorageRules,pe as defineTable,me as defineVectorIndex,ve as deny,C as documentHistoryExtension,S as flushDeferredDeletes,N as httpAction,w as httpRoute,U as httpRouter,xe as indexFieldsFromSchema,d as initLunora,ce as installPlugins,Be as isDeny,m as isPerDispatchMiddleware,k as isSafeHeaderValue,ar as mask,le as mergeSchemaExtension,Y as onConnect,J as onDisconnect,Re as onQueryChange,K as onShardInit,Me as onWhisper,De as presenceExtension,ge as protectPublic,b as redactSecrets,sr as rls,B as serveStorageObject,pr as storageRules,x as tagPerDispatchMiddleware,Ve as toWhereInput,we as v,u as withDeferredDeletes,g as withDeferredSchedules};
@@ -1 +1 @@
1
- import{isLunoraError as S}from"@lunora/errors";import{v as d}from"@lunora/values";import{a as f,d as U}from"./wire-codec-BTOxkE1j.mjs";import{s as D}from"./stable-key-B_BlboiY.mjs";import{initLunora as F}from"./initLunora-DAbEYdSo.mjs";import{g as k,h as q,a as B}from"./plugin-BQ2GySyZ.mjs";const P=i=>D(f(i)),R=3600*1e3,H=512*1024,V=8,b=64,K=64,W=256,$=4096,u="actionCache",h="entries",c=`${u}_${h}`,T=i=>i===void 0?"":P(i),x=async(i,m)=>{const A=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(`${i}\0${m}`));return[...new Uint8Array(A)].map(y=>y.toString(16).padStart(2,"0")).join("")},G=k(u,{tables:{[h]:q({expiresAt:d.number(),key:d.string(),name:d.string(),value:d.string()}).index("byKey",["key"],{unique:!0}).index("byName",["name"]).index("byExpiresAt",["expiresAt"])}}),{internalMutation:J}=F.dataModel().create(),te=(i={})=>{const m=i.ttlMs!==void 0&&Number.isFinite(i.ttlMs)?Math.max(1,Math.floor(i.ttlMs)):R,A=i.maxValueBytes!==void 0&&Number.isFinite(i.maxValueBytes)?Math.max(1,Math.floor(i.maxValueBytes)):H,y=async(e,t)=>{const n=(await e.db.query(c).withIndex("byExpiresAt").order("asc").take(V)).filter(r=>r.expiresAt<=t);await Promise.all(n.map(async r=>e.db.delete(r._id)))},C=async(e,t)=>e.db.query(c).withIndex("byKey",a=>a.eq("key",t)).first(),N=new Set(["CONFLICT","NOT_FOUND","NOT_UNIQUE"]),I=async(e,t,a)=>{try{await(t?e.db.patch(t._id,{expiresAt:a.expiresAt,value:a.value}):e.db.insert(c,a))}catch(n){if(S(n)&&N.has(n.code))return;throw n}},M=async(e,t,a,n)=>{const r=T(a),s=await x(t,r),l=Date.now(),o=await C(e,s);if(o&&o.expiresAt>l)return U(JSON.parse(o.value)).v;const p=await n(),w=JSON.stringify(f({v:p})),E=Date.now(),O=E+m;return new TextEncoder().encode(w).length<=A?await I(e,o,{expiresAt:O,key:s,name:t,value:w}):o&&await e.db.delete(o._id),await y(e,E),p},L=async(e,t,a)=>{const n=await x(t,T(a)),r=await e.db.query(c).withIndex("byKey",s=>s.eq("key",n)).take(b);await Promise.all(r.map(async s=>e.db.delete(s._id)))},_=async(e,t,a,n)=>{if(n>=K)return{complete:!1,deleted:a};const r=await e.db.query(c).withIndex("byName",s=>s.eq("name",t)).take(b);return r.length===0?{complete:!0,deleted:a}:(await Promise.all(r.map(async s=>e.db.delete(s._id))),_(e,t,a+r.length,n+1))},g=async(e,t)=>_(e,t,0,0),v=J.input({limit:d.optional(d.number())}).mutation(async({args:e,ctx:t})=>{const a=Date.now(),n=e.limit!==void 0&&Number.isFinite(e.limit)?Math.min($,Math.max(1,Math.floor(e.limit))):W,s=(await t.db.query(c).withIndex("byExpiresAt").order("asc").take(n)).filter(l=>l.expiresAt<=a);return await Promise.all(s.map(async l=>t.db.delete(l._id))),{deleted:s.length}});return{...B(u,{extension:G,functions:{purgeExpired:v}}),invalidate:L,invalidateAll:g,wrap:M}};export{R as ACTION_CACHE_DEFAULT_TTL_MS,c as ACTION_CACHE_TABLE,G as actionCacheExtension,x as cacheKeyFor,te as defineActionCache};
1
+ import{isLunoraError as S}from"@lunora/errors";import{v as d}from"@lunora/values";import{a as f,d as U}from"./wire-codec-BTOxkE1j.mjs";import{s as D}from"./stable-key-B_BlboiY.mjs";import{initLunora as F}from"./initLunora-DAbEYdSo.mjs";import{g as k,h as q,a as B}from"./plugin-C5XIUmql.mjs";const P=i=>D(f(i)),R=3600*1e3,H=512*1024,V=8,b=64,K=64,W=256,$=4096,u="actionCache",h="entries",c=`${u}_${h}`,T=i=>i===void 0?"":P(i),x=async(i,m)=>{const A=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(`${i}\0${m}`));return[...new Uint8Array(A)].map(y=>y.toString(16).padStart(2,"0")).join("")},G=k(u,{tables:{[h]:q({expiresAt:d.number(),key:d.string(),name:d.string(),value:d.string()}).index("byKey",["key"],{unique:!0}).index("byName",["name"]).index("byExpiresAt",["expiresAt"])}}),{internalMutation:J}=F.dataModel().create(),te=(i={})=>{const m=i.ttlMs!==void 0&&Number.isFinite(i.ttlMs)?Math.max(1,Math.floor(i.ttlMs)):R,A=i.maxValueBytes!==void 0&&Number.isFinite(i.maxValueBytes)?Math.max(1,Math.floor(i.maxValueBytes)):H,y=async(e,t)=>{const n=(await e.db.query(c).withIndex("byExpiresAt").order("asc").take(V)).filter(r=>r.expiresAt<=t);await Promise.all(n.map(async r=>e.db.delete(r._id)))},C=async(e,t)=>e.db.query(c).withIndex("byKey",a=>a.eq("key",t)).first(),N=new Set(["CONFLICT","NOT_FOUND","NOT_UNIQUE"]),I=async(e,t,a)=>{try{await(t?e.db.patch(t._id,{expiresAt:a.expiresAt,value:a.value}):e.db.insert(c,a))}catch(n){if(S(n)&&N.has(n.code))return;throw n}},M=async(e,t,a,n)=>{const r=T(a),s=await x(t,r),l=Date.now(),o=await C(e,s);if(o&&o.expiresAt>l)return U(JSON.parse(o.value)).v;const p=await n(),w=JSON.stringify(f({v:p})),E=Date.now(),O=E+m;return new TextEncoder().encode(w).length<=A?await I(e,o,{expiresAt:O,key:s,name:t,value:w}):o&&await e.db.delete(o._id),await y(e,E),p},L=async(e,t,a)=>{const n=await x(t,T(a)),r=await e.db.query(c).withIndex("byKey",s=>s.eq("key",n)).take(b);await Promise.all(r.map(async s=>e.db.delete(s._id)))},_=async(e,t,a,n)=>{if(n>=K)return{complete:!1,deleted:a};const r=await e.db.query(c).withIndex("byName",s=>s.eq("name",t)).take(b);return r.length===0?{complete:!0,deleted:a}:(await Promise.all(r.map(async s=>e.db.delete(s._id))),_(e,t,a+r.length,n+1))},g=async(e,t)=>_(e,t,0,0),v=J.input({limit:d.optional(d.number())}).mutation(async({args:e,ctx:t})=>{const a=Date.now(),n=e.limit!==void 0&&Number.isFinite(e.limit)?Math.min($,Math.max(1,Math.floor(e.limit))):W,s=(await t.db.query(c).withIndex("byExpiresAt").order("asc").take(n)).filter(l=>l.expiresAt<=a);return await Promise.all(s.map(async l=>t.db.delete(l._id))),{deleted:s.length}});return{...B(u,{extension:G,functions:{purgeExpired:v}}),invalidate:L,invalidateAll:g,wrap:M}};export{R as ACTION_CACHE_DEFAULT_TTL_MS,c as ACTION_CACHE_TABLE,G as actionCacheExtension,x as cacheKeyFor,te as defineActionCache};
@@ -1 +1 @@
1
- import{v as r}from"@lunora/values";import{d as E,a as h}from"./wire-codec-BTOxkE1j.mjs";import{initLunora as x}from"./initLunora-DAbEYdSo.mjs";import{g as v,h as R,a as U}from"./plugin-BQ2GySyZ.mjs";const H=2160*60*60*1e3,L=64*1024,I=200,q=1e3,C=64,F=512,u=16,B=["_commitSeq","seq"],w=["accessToken","apiKey","backupCodes","clientSecret","hashedPassword","password","privateKey","refreshToken","secret","totpSecret"],f="documentHistory",y="versions",p=`${f}_${y}`,P=v(f,{tables:{[y]:R({doc:r.optional(r.string()),documentId:r.string(),op:r.union(r.literal("delete"),r.literal("insert"),r.literal("update")),previous:r.optional(r.string()),recordedAt:r.number(),seq:r.number(),tableName:r.string(),truncated:r.optional(r.boolean())}).commitOrdered().index("byDocumentRecordedAt",["documentId","recordedAt","seq"]).index("byRecordedAt",["recordedAt"])}}),{internalMutation:Y,internalQuery:g}=x.dataModel().create(),V=(d={})=>{const T=d.retentionMs!==void 0&&Number.isFinite(d.retentionMs)?Math.max(1,Math.floor(d.retentionMs)):H,_=d.maxSnapshotBytes!==void 0&&Number.isFinite(d.maxSnapshotBytes)?Math.max(1,Math.floor(d.maxSnapshotBytes)):L,b=new Set([...w,...d.redact??[]]);let A=0;const S=()=>(A+=1,A),a=(e,o=0)=>{if(Array.isArray(e))return o>=u?void 0:e.map(t=>a(t,o+1));if(typeof e!="object"||e===null)return e;if(e instanceof Map)return o>=u?void 0:new Map([...e.entries()].filter(([t])=>typeof t!="string"||!b.has(t)).map(([t,i])=>[t,a(i,o+1)]));if(e instanceof Set)return o>=u?void 0:new Set([...e].map(t=>a(t,o+1)));if(Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null)return e;if(!(o>=u))return Object.fromEntries(Object.entries(e).filter(([t])=>!b.has(t)).map(([t,i])=>[t,a(i,o+1)]))},M=e=>{if(e===void 0)return;const o=JSON.stringify(h(a(e)));return new TextEncoder().encode(o).length>_?void 0:o},l=async(e,o)=>{const t=M(o.doc),i=M(o.previous),n=o.doc!==void 0&&t===void 0||o.previous!==void 0&&i===void 0;await e.db.insert(p,{documentId:o.documentId,op:o.op,recordedAt:Date.now(),seq:S(),tableName:o.tableName,...n?{truncated:!0}:{},...t===void 0?{}:{doc:t},...i===void 0?{}:{previous:i}})},D=e=>({documentHistoryDelete:e.afterDelete(async(o,t)=>l(o,{documentId:t.id,op:"delete",previous:t.previous,tableName:t.table})),documentHistoryInsert:e.afterInsert(async(o,t)=>l(o,{doc:t.doc,documentId:t.id,op:"insert",tableName:t.table})),documentHistoryUpdate:e.afterUpdate(async(o,t)=>l(o,{doc:t.doc,documentId:t.id,op:"update",previous:t.previous,tableName:t.table}))}),N=g.input({before:r.optional(r.number()),documentId:r.string(),limit:r.optional(r.number())}).query(async({args:e,ctx:o})=>{const t=e.limit!==void 0&&Number.isFinite(e.limit)?Math.min(q,Math.max(1,Math.floor(e.limit))):I,i=await o.db.query(p).withIndex("byDocumentRecordedAt",n=>e.before===void 0?n.eq("documentId",e.documentId):n.eq("documentId",e.documentId).lte("recordedAt",e.before)).order("desc").take(t);return i.sort((n,m)=>{for(const c of B){const s=(m[c]??0)-(n[c]??0);if(s!==0)return s}return 0}),i.map(n=>({documentId:n.documentId,op:n.op,recordedAt:n.recordedAt,tableName:n.tableName,...n.doc===void 0?{}:{doc:E(JSON.parse(n.doc))},...n.previous===void 0?{}:{previous:E(JSON.parse(n.previous))},...n.truncated===!0?{truncated:!0}:{}}))}),O=Y.input({limit:r.optional(r.number())}).mutation(async({args:e,ctx:o})=>{const t=Date.now()-T,i=e.limit!==void 0&&Number.isFinite(e.limit)?Math.max(1,Math.floor(e.limit)):F;let n=0;for(let m=0;m<C&&n<i;m+=1){const c=await o.db.query(p).withIndex("byRecordedAt",s=>s.lt("recordedAt",t)).order("asc").take(Math.min(I,i-n));if(c.length===0)return{deleted:n};await Promise.all(c.map(async s=>o.db.delete(s._id))),n+=c.length}return{deleted:n}});return{...U(f,{extension:P,functions:{listForDocument:N,vacuum:O}}),record:D}};export{w as DOCUMENT_HISTORY_REDACTED_FIELDS,p as DOCUMENT_HISTORY_TABLE,V as defineDocumentHistory,P as documentHistoryExtension};
1
+ import{v as r}from"@lunora/values";import{d as E,a as h}from"./wire-codec-BTOxkE1j.mjs";import{initLunora as x}from"./initLunora-DAbEYdSo.mjs";import{g as v,h as R,a as U}from"./plugin-C5XIUmql.mjs";const H=2160*60*60*1e3,L=64*1024,I=200,q=1e3,C=64,F=512,u=16,B=["_commitSeq","seq"],w=["accessToken","apiKey","backupCodes","clientSecret","hashedPassword","password","privateKey","refreshToken","secret","totpSecret"],f="documentHistory",y="versions",p=`${f}_${y}`,P=v(f,{tables:{[y]:R({doc:r.optional(r.string()),documentId:r.string(),op:r.union(r.literal("delete"),r.literal("insert"),r.literal("update")),previous:r.optional(r.string()),recordedAt:r.number(),seq:r.number(),tableName:r.string(),truncated:r.optional(r.boolean())}).commitOrdered().index("byDocumentRecordedAt",["documentId","recordedAt","seq"]).index("byRecordedAt",["recordedAt"])}}),{internalMutation:Y,internalQuery:g}=x.dataModel().create(),V=(d={})=>{const T=d.retentionMs!==void 0&&Number.isFinite(d.retentionMs)?Math.max(1,Math.floor(d.retentionMs)):H,_=d.maxSnapshotBytes!==void 0&&Number.isFinite(d.maxSnapshotBytes)?Math.max(1,Math.floor(d.maxSnapshotBytes)):L,b=new Set([...w,...d.redact??[]]);let A=0;const S=()=>(A+=1,A),a=(e,o=0)=>{if(Array.isArray(e))return o>=u?void 0:e.map(t=>a(t,o+1));if(typeof e!="object"||e===null)return e;if(e instanceof Map)return o>=u?void 0:new Map([...e.entries()].filter(([t])=>typeof t!="string"||!b.has(t)).map(([t,i])=>[t,a(i,o+1)]));if(e instanceof Set)return o>=u?void 0:new Set([...e].map(t=>a(t,o+1)));if(Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null)return e;if(!(o>=u))return Object.fromEntries(Object.entries(e).filter(([t])=>!b.has(t)).map(([t,i])=>[t,a(i,o+1)]))},M=e=>{if(e===void 0)return;const o=JSON.stringify(h(a(e)));return new TextEncoder().encode(o).length>_?void 0:o},l=async(e,o)=>{const t=M(o.doc),i=M(o.previous),n=o.doc!==void 0&&t===void 0||o.previous!==void 0&&i===void 0;await e.db.insert(p,{documentId:o.documentId,op:o.op,recordedAt:Date.now(),seq:S(),tableName:o.tableName,...n?{truncated:!0}:{},...t===void 0?{}:{doc:t},...i===void 0?{}:{previous:i}})},D=e=>({documentHistoryDelete:e.afterDelete(async(o,t)=>l(o,{documentId:t.id,op:"delete",previous:t.previous,tableName:t.table})),documentHistoryInsert:e.afterInsert(async(o,t)=>l(o,{doc:t.doc,documentId:t.id,op:"insert",tableName:t.table})),documentHistoryUpdate:e.afterUpdate(async(o,t)=>l(o,{doc:t.doc,documentId:t.id,op:"update",previous:t.previous,tableName:t.table}))}),N=g.input({before:r.optional(r.number()),documentId:r.string(),limit:r.optional(r.number())}).query(async({args:e,ctx:o})=>{const t=e.limit!==void 0&&Number.isFinite(e.limit)?Math.min(q,Math.max(1,Math.floor(e.limit))):I,i=await o.db.query(p).withIndex("byDocumentRecordedAt",n=>e.before===void 0?n.eq("documentId",e.documentId):n.eq("documentId",e.documentId).lte("recordedAt",e.before)).order("desc").take(t);return i.sort((n,m)=>{for(const c of B){const s=(m[c]??0)-(n[c]??0);if(s!==0)return s}return 0}),i.map(n=>({documentId:n.documentId,op:n.op,recordedAt:n.recordedAt,tableName:n.tableName,...n.doc===void 0?{}:{doc:E(JSON.parse(n.doc))},...n.previous===void 0?{}:{previous:E(JSON.parse(n.previous))},...n.truncated===!0?{truncated:!0}:{}}))}),O=Y.input({limit:r.optional(r.number())}).mutation(async({args:e,ctx:o})=>{const t=Date.now()-T,i=e.limit!==void 0&&Number.isFinite(e.limit)?Math.max(1,Math.floor(e.limit)):F;let n=0;for(let m=0;m<C&&n<i;m+=1){const c=await o.db.query(p).withIndex("byRecordedAt",s=>s.lt("recordedAt",t)).order("asc").take(Math.min(I,i-n));if(c.length===0)return{deleted:n};await Promise.all(c.map(async s=>o.db.delete(s._id))),n+=c.length}return{deleted:n}});return{...U(f,{extension:P,functions:{listForDocument:N,vacuum:O}}),record:D}};export{w as DOCUMENT_HISTORY_REDACTED_FIELDS,p as DOCUMENT_HISTORY_TABLE,V as defineDocumentHistory,P as documentHistoryExtension};
@@ -1 +1 @@
1
- import{LunoraError as b}from"@lunora/errors";import{v as t}from"@lunora/values";import{initLunora as M}from"./initLunora-DAbEYdSo.mjs";import{onDisconnect as T}from"./onConnect-BLRoOpv2.mjs";import{g as v,h as A,a as L}from"./plugin-BQ2GySyZ.mjs";const D=3e4,g=1024,P=8,p=4096,w="presence",h="present",l=`${w}_${h}`,N=v(w,{tables:{[h]:A({data:t.optional(t.record(t.string(),t.any())),lastSeen:t.number(),roomId:t.string(),sessionId:t.string(),userId:t.optional(t.string())}).index("byRoomSession",["roomId","sessionId"]).index("byRoom",["roomId"]).index("byRoomLastSeen",["roomId","lastSeen"])}}),{mutation:E,query:B}=M.dataModel().create(),G=(u={})=>{const m=u.ttlMs??D,f=Math.max(0,Math.min(u.disconnectGraceMs??0,m)),S=u.maxSessions,y=S!==void 0&&Number.isFinite(S)?Math.max(1,Math.floor(S)):g,_=E.input({data:t.optional(t.record(t.string(),t.any())),roomId:t.string(),sessionId:t.string()}).mutation(async({args:o,ctx:s})=>{const r=Date.now(),d=s.auth.userId??void 0;if(o.data!==void 0&&new TextEncoder().encode(JSON.stringify(o.data)).length>p)throw new b("BAD_REQUEST",`presence data exceeds the ${String(p)}-byte limit`);const e=await s.db.query(l).withIndex("byRoomSession",i=>i.eq("roomId",o.roomId).eq("sessionId",o.sessionId)).first();if(e&&(e.userId??void 0)!==d)throw new b("FORBIDDEN","presence heartbeat denied: this (roomId, sessionId) is held by another identity");const a={lastSeen:r,roomId:o.roomId,sessionId:o.sessionId,...o.data===void 0?{}:{data:o.data},...d===void 0?{}:{userId:d}};await(e?s.db.patch(e._id,a):s.db.insert(l,a));const I=r-m-Math.max(f,m),c=(await s.db.query(l).withIndex("byRoomLastSeen",i=>i.eq("roomId",o.roomId)).order("asc").take(P)).filter(i=>i.lastSeen<=I);return await Promise.all(c.map(i=>s.db.delete(i._id))),{lastSeen:r}}),x=B.input({roomId:t.string()}).query(async({args:o,ctx:s})=>{const r=Date.now()-m,e=(await s.db.query(l).withIndex("byRoomLastSeen",n=>n.eq("roomId",o.roomId)).order("desc").take(y)).filter(n=>n.lastSeen>r),a=new Set,I=[];for(const n of e){const c=n.userId;if(c!==void 0){if(a.has(c))continue;a.add(c)}const i={lastSeen:n.lastSeen,roomId:n.roomId};c!==void 0&&(i.userId=c),n.data!==void 0&&(i.data=n.data),I.push(i)}return I}),R={...E.input({roomId:t.string()}).mutation(async({args:o,ctx:s})=>{const r=Date.now()-m,d=await s.db.query(l).withIndex("byRoom",e=>e.eq("roomId",o.roomId)).filter(e=>e.lastSeen<=r).collect();return await Promise.all(d.map(e=>s.db.delete(e._id))),{deleted:d.length}}),visibility:"internal"},q=T(async(o,s)=>{const r=s.context?.roomId,d=s.context?.sessionId;if(typeof r!="string"||typeof d!="string")return;const e=await o.db.query(l).withIndex("byRoomSession",n=>n.eq("roomId",r).eq("sessionId",d)).first();if(!e)return;const a=s.userId??void 0;if((e.userId??void 0)!==a)return;if(f===0){await o.db.delete(e._id);return}const I=Math.min(e.lastSeen,Date.now()+f-m);await o.db.patch(e._id,{lastSeen:I})});return L(w,{extension:N,functions:{disconnect:q,heartbeat:_,listPresent:x,sweep:R}})};export{D as PRESENCE_DEFAULT_TTL_MS,l as PRESENCE_TABLE,G as definePresence,N as presenceExtension};
1
+ import{LunoraError as b}from"@lunora/errors";import{v as t}from"@lunora/values";import{initLunora as M}from"./initLunora-DAbEYdSo.mjs";import{onDisconnect as T}from"./onConnect-BLRoOpv2.mjs";import{g as v,h as A,a as L}from"./plugin-C5XIUmql.mjs";const D=3e4,g=1024,P=8,p=4096,w="presence",h="present",l=`${w}_${h}`,N=v(w,{tables:{[h]:A({data:t.optional(t.record(t.string(),t.any())),lastSeen:t.number(),roomId:t.string(),sessionId:t.string(),userId:t.optional(t.string())}).index("byRoomSession",["roomId","sessionId"]).index("byRoom",["roomId"]).index("byRoomLastSeen",["roomId","lastSeen"])}}),{mutation:E,query:B}=M.dataModel().create(),G=(u={})=>{const m=u.ttlMs??D,f=Math.max(0,Math.min(u.disconnectGraceMs??0,m)),S=u.maxSessions,y=S!==void 0&&Number.isFinite(S)?Math.max(1,Math.floor(S)):g,_=E.input({data:t.optional(t.record(t.string(),t.any())),roomId:t.string(),sessionId:t.string()}).mutation(async({args:o,ctx:s})=>{const r=Date.now(),d=s.auth.userId??void 0;if(o.data!==void 0&&new TextEncoder().encode(JSON.stringify(o.data)).length>p)throw new b("BAD_REQUEST",`presence data exceeds the ${String(p)}-byte limit`);const e=await s.db.query(l).withIndex("byRoomSession",i=>i.eq("roomId",o.roomId).eq("sessionId",o.sessionId)).first();if(e&&(e.userId??void 0)!==d)throw new b("FORBIDDEN","presence heartbeat denied: this (roomId, sessionId) is held by another identity");const a={lastSeen:r,roomId:o.roomId,sessionId:o.sessionId,...o.data===void 0?{}:{data:o.data},...d===void 0?{}:{userId:d}};await(e?s.db.patch(e._id,a):s.db.insert(l,a));const I=r-m-Math.max(f,m),c=(await s.db.query(l).withIndex("byRoomLastSeen",i=>i.eq("roomId",o.roomId)).order("asc").take(P)).filter(i=>i.lastSeen<=I);return await Promise.all(c.map(i=>s.db.delete(i._id))),{lastSeen:r}}),x=B.input({roomId:t.string()}).query(async({args:o,ctx:s})=>{const r=Date.now()-m,e=(await s.db.query(l).withIndex("byRoomLastSeen",n=>n.eq("roomId",o.roomId)).order("desc").take(y)).filter(n=>n.lastSeen>r),a=new Set,I=[];for(const n of e){const c=n.userId;if(c!==void 0){if(a.has(c))continue;a.add(c)}const i={lastSeen:n.lastSeen,roomId:n.roomId};c!==void 0&&(i.userId=c),n.data!==void 0&&(i.data=n.data),I.push(i)}return I}),R={...E.input({roomId:t.string()}).mutation(async({args:o,ctx:s})=>{const r=Date.now()-m,d=await s.db.query(l).withIndex("byRoom",e=>e.eq("roomId",o.roomId)).filter(e=>e.lastSeen<=r).collect();return await Promise.all(d.map(e=>s.db.delete(e._id))),{deleted:d.length}}),visibility:"internal"},q=T(async(o,s)=>{const r=s.context?.roomId,d=s.context?.sessionId;if(typeof r!="string"||typeof d!="string")return;const e=await o.db.query(l).withIndex("byRoomSession",n=>n.eq("roomId",r).eq("sessionId",d)).first();if(!e)return;const a=s.userId??void 0;if((e.userId??void 0)!==a)return;if(f===0){await o.db.delete(e._id);return}const I=Math.min(e.lastSeen,Date.now()+f-m);await o.db.patch(e._id,{lastSeen:I})});return L(w,{extension:N,functions:{disconnect:q,heartbeat:_,listPresent:x,sweep:R}})};export{D as PRESENCE_DEFAULT_TTL_MS,l as PRESENCE_TABLE,G as definePresence,N as presenceExtension};
@@ -1 +1 @@
1
- import"./compose-middleware-DNvrHMHx.mjs";import{c as i,a as s,b as o,g as m,k as l,m as t}from"./plugin-BQ2GySyZ.mjs";export{i as composePluginMiddleware,s as defineComponent,o as definePlugin,m as defineSchemaExtension,l as installPlugins,t as mergeSchemaExtension};
1
+ import"./compose-middleware-DNvrHMHx.mjs";import{c as i,a as s,b as o,g as m,k as l,m as t}from"./plugin-C5XIUmql.mjs";export{i as composePluginMiddleware,s as defineComponent,o as definePlugin,m as defineSchemaExtension,l as installPlugins,t as mergeSchemaExtension};
@@ -1 +1 @@
1
- import{d,e as i,f as n,h as s,i as l,j as f,v as o,l as r}from"./plugin-BQ2GySyZ.mjs";export{d as defineAggregateIndex,i as defineRankIndex,n as defineSchema,s as defineTable,l as defineVectorIndex,f as indexFieldsFromSchema,o as validateGlobalVectors,r as validateIndexFields};
1
+ import{d,e as i,f as n,h as s,i as l,j as f,v as o,l as r}from"./plugin-C5XIUmql.mjs";export{d as defineAggregateIndex,i as defineRankIndex,n as defineSchema,s as defineTable,l as defineVectorIndex,f as indexFieldsFromSchema,o as validateGlobalVectors,r as validateIndexFields};
@@ -0,0 +1 @@
1
+ import{LunoraError as s}from"@lunora/errors";import{c as Q}from"./compose-middleware-DNvrHMHx.mjs";import{v as B}from"@lunora/values";const q=["de","en","es","fr","it","nl","none","pt"],F=["native","portable"],V=e=>F.includes(e),X=e=>q.includes(e),U=e=>{const{value:t}=e._meta??{};if(t===null)return"null";switch(typeof t){case"bigint":case"boolean":case"number":case"string":return typeof t;default:return e.kind}},P=e=>{if(e.kind==="literal")return U(e);if(e.kind!=="optional")return e.kind;const t=e._meta?.inner;return t?P(t):e.kind},G=(e,t)=>`table "${e}" is .global() and declares vector index "${t}". Vector sync runs on the shard write path, which a global (D1/Hyperdrive) table's writes never take — the index would stay empty. Drop .global(), or keep the index yourself with ctx.vectors.upsert/deleteByIds.`,j=16,Y={many:(e,t)=>({field:t.field,kind:"many",references:t.references??"_id",table:e}),one:(e,t)=>({field:t.field,kind:"one",onDelete:t.onDelete,references:t.references??"_id",table:e})},g=(e,t,n)=>({handler:n,op:t,timing:e}),J=()=>({afterDelete:e=>g("after","delete",e),afterInsert:e=>g("after","insert",e),afterUpdate:e=>g("after","update",e),beforeDelete:e=>g("before","delete",e),beforeInsert:e=>g("before","insert",e),beforeUpdate:e=>g("before","update",e)}),C=(e,t)=>{if(!t||t.length===0)throw new s("INTERNAL",`rankIndex "${e}": "sortBy" is required and must list at least one key`);return t.map(n=>({direction:n.direction??"asc",field:n.field}))},ge=e=>{const t={...e},n=[],r=[],a=[],d=[],u={},c=[],h={},f=J(),b=[];let w={kind:"root"},E=!1,$=!1,p=!1,T=!1,M=!1,L,A,O,R;const D=i=>{if(w.kind!=="root"&&w.kind!==i.kind)throw new s("INTERNAL","shardBy/global: a table cannot be both .shardBy(key) and .global() — pick one. .shardBy(key) puts the rows in one Durable Object per key (isolation, poke-live reactivity); .global() puts them in a single replicated backend read from the edge.");w=i},l={aggregateIndex(i,o){const m=o?.op??"count";if(m!=="count"&&!o?.field)throw new s("INTERNAL",`aggregateIndex "${i}": op "${m}" requires a "field"`);return n.push({by:o?.by,field:o?.field,name:i,on:"",op:m,where:o?.where}),l},get aggregateIndexes(){return n},get externalSource(){return R},commitOrdered(){return E=!0,l},get commitOrderedMode(){return E},dropStalePatches(){return $=!0,l},get dropStalePatchesMode(){return $},externallyManaged(){return p=!0,l},geoIndex(i,o){return r.push({field:o.field,name:i,precision:o.precision}),l},get geoIndexes(){return r},global(i){return D({backend:i?.backend??"d1",kind:"global"}),l},get isExternallyManaged(){return p},get isPublic(){return M},index(i,o,m){return a.push({fields:o,name:i,unique:m?.unique??!1}),l},get indexes(){return a},memory(){return T=!0,l},get memoryMode(){return T},ownedBy(i){return L=i,l},get ownerField(){return L},public(){return M=!0,l},rankIndex(i,o){return d.push({name:i,on:"",partitionBy:o.partitionBy,sortBy:C(i,o.sortBy),where:o.where}),l},get rankIndexes(){return d},get relationMap(){return u},relations(i){return Object.assign(u,i(Y)),l},searchIndex(i,o){if(o.filterFields&&o.filterFields.length>j)throw new s("INTERNAL",`searchIndex "${i}": at most ${String(j)} filterFields are supported (got ${String(o.filterFields.length)})`);const{language:m}=o;if(m!==void 0&&!X(m))throw new s("INTERNAL",`searchIndex "${i}": unknown language "${m}" (supported: ${q.join(", ")})`);const{strategy:N}=o;if(N!==void 0&&!V(N))throw new s("INTERNAL",`searchIndex "${i}": unknown strategy "${N}" (supported: ${F.join(", ")})`);return c.push({field:o.field,filterFields:o.filterFields,language:o.language,name:i,staged:o.staged,strategy:o.strategy}),l},get searchIndexes(){return c},shape:t,shardBy(i){return D({field:i,kind:"shardBy"}),l},get shardMode(){return w},get softDeleteMode(){return A},source(i){if(!i.binding)throw new s("INTERNAL","source: `binding` is required (the wrangler Hyperdrive binding name)");if(!i.query)throw new s("INTERNAL","source: `query` is required (the tenant-membership SQL)");return R=i,p=!0,l},softDelete(i){const o=i?.field??"deletedAt";return A={field:o},o in t||(t[o]=B.optional(B.number().nullable())),l},get triggerMap(){return h},triggers(i){return Object.assign(h,i(f)),l},ttl(i,o){return O={after:o?.after,field:i},l},get ttlPolicy(){return O},get vectorIndexes(){return b},vectorize(i,o){return b.push({dimensions:o.dimensions,embed:o.embed,field:i,metadata:o.metadata,metric:o.metric,model:o.model,name:o.index}),l}};return l},be=e=>({dimensions:e.dimensions,embed:e.embed,kind:"vectorIndex",metadata:e.metadata,metric:e.metric,model:e.model,select:e.source.select,table:e.source.table}),we=(e,t)=>{const n=t.op??"count";if(n!=="count"&&!t.field)throw new s("INTERNAL",`aggregateIndex "${e}": op "${n}" requires a "field"`);return{by:t.by,field:t.field,name:e,on:t.on,op:n,where:t.where}},xe=(e,t)=>({name:e,on:t.table,partitionBy:t.partitionBy,sortBy:C(e,t.sortBy),where:t.where}),y=e=>({...e,extend(t){return y(z(e,t))},jurisdiction(t){return y(e)},rls(t){return y({...e,rlsMode:t})}}),W=e=>{for(const[t,n]of Object.entries(e))for(const r of[...n.aggregateIndexes,...n.rankIndexes])r.on===""&&(r.on=t)},Z=(e,t,n)=>{for(const r of Object.values(t)){const a=e[r.on];if(!a)throw new s("INTERNAL",`defineAggregateIndex "${r.name}": unknown table "${r.on}"`);a.aggregateIndexes.push(r)}for(const r of Object.values(n)){const a=e[r.on];if(!a)throw new s("INTERNAL",`defineRankIndex "${r.name}": unknown table "${r.on}"`);a.rankIndexes.push(r)}},ee=e=>{if(e.cursor)return"cursor";if(e.reconcileEveryMs!==void 0)return"reconcileEveryMs";if(e.softDeleteColumn!==void 0)return"softDeleteColumn"},te=(e,t)=>{const n=t.mode==="incremental";if(t.mode!==void 0&&t.mode!=="full-pull"&&!n)throw new s("INTERNAL",`defineSchema: table "${e}" uses \`mode: ${JSON.stringify(t.mode)}\` — supported modes are "full-pull" (default) and "incremental".`);if(!n){const r=ee(t);if(r)throw new s("INTERNAL",`defineSchema: table "${e}" sets \`${r}\` but is not \`mode: "incremental"\` — that knob only applies to incremental ingest. Set \`mode: "incremental"\` or remove \`${r}\`.`);return}if(!t.cursor?.column||!t.cursor.query)throw new s("INTERNAL",`defineSchema: table "${e}" is \`mode: "incremental"\` but has no \`cursor\` — add \`cursor: { column: "updated_at", query: "… WHERE … > $N" }\` binding the watermark as the trailing parameter.`);if(t.reconcileEveryMs===void 0&&t.softDeleteColumn===void 0)throw new s("INTERNAL",`defineSchema: table "${e}" is \`mode: "incremental"\` with no delete-visibility path — an incremental pull never sees upstream deletes, so it would accumulate phantom rows. Add \`reconcileEveryMs\` (a periodic full-pull sweep) or \`softDeleteColumn\` (an upstream tombstone column).`)},ne=e=>{for(const[t,n]of Object.entries(e)){const r=n.externalSource;if(r){if(n.shardMode.kind==="global")throw new s("INTERNAL",`defineSchema: table "${t}" cannot be both .source() and .global() — a sourced table materializes into a shard DO's SQLite, a global table lives in the external tier`);if(n.shardMode.kind==="shardBy"&&!r.tenantBy)throw new s("INTERNAL",`defineSchema: sourced + .shardBy() table "${t}" needs a \`tenantBy\` mapper — without it every tenant's DO would run the same unscoped query and replicate the whole multitenant table (a cross-tenant leak). Add \`tenantBy: (shardKey) => [shardKey]\` binding the shard key into the query's parameters.`);te(t,r)}}},re=["_commitSeq","_creationTime","_id"],_="_commitSeq",ae=new Set(re),x=(e,t,n,r)=>{if(!(ae.has(n)||n in r.shape))throw new s("INTERNAL",`defineSchema: table "${e}" index "${t}" names column "${n}" which is not in the table's shape`)},v=(e,t,n,r)=>{const a=new Set;for(const d of n){if(a.has(d.name))throw new s("INTERNAL",`defineSchema: table "${e}" declares ${t} "${d.name}" more than once`);a.add(d.name),r(d)}},K=e=>{for(const[t,n]of Object.entries(e))v(t,"index",n.indexes,r=>{for(const a of r.fields)x(t,r.name,a,n)}),v(t,"rank index",n.rankIndexes,r=>{for(const a of r.sortBy)x(t,r.name,a.field,n);for(const a of r.partitionBy??[])x(t,r.name,a,n)}),v(t,"geo index",n.geoIndexes,r=>{x(t,r.name,r.field,n)})},S=(e,t,n)=>{if(e.length===0)return;const r={};for(const a of e)r[t(a)]=n(a);return r},oe=e=>{const t=new Set(e.sortBy.map(n=>n.field));for(const n of e.partitionBy??[])t.add(n);return[...t]},ye=e=>{const t={};for(const[n,r]of Object.entries(e.tables)){const a=S(r.geoIndexes,c=>c.name,c=>[c.field]),d=S(r.indexes,c=>c.name,c=>c.fields),u=S(r.rankIndexes,c=>c.name,oe);(a||d||u)&&(t[n]={...a?{geo:a}:{},...d?{index:d}:{},...u?{rank:u}:{}})}return t},ie=e=>{for(const[t,n]of Object.entries(e)){if(!n.memoryMode)continue;const a=[[n.shardMode.kind==="global",".global() — those rows live in D1, which this shard does not own and cannot clear"],[n.commitOrderedMode===!0,".commitOrdered() — the counter resets with the table, so the sequence would restart and a consumer's cursor would silently skip everything after it"],[n.externalSource!==void 0,".source() — the table is materialized by the ingest loop, so wiping it on every eviction would fight the puller"],[n.searchIndexes.length>0,".searchIndex() — the FTS shadow is a separate table that clearing the rows would leave stale"],[n.geoIndexes.length>0,".geoIndex() — the geohash companion is a separate table that clearing the rows would leave stale"],[n.aggregateIndexes.length>0,".aggregateIndex() — the counter companion is a separate table that clearing the rows would leave stale"],[n.rankIndexes.length>0,".rankIndex() — the rank companion is a separate table that clearing the rows would leave stale"],[n.vectorIndexes.length>0,".vectorize() — vectors live in an external index that a shard restart cannot clear"]].find(([d])=>d)?.[1];if(a!==void 0)throw new s("INTERNAL",`defineSchema: table "${t}" is both .memory() and ${a}. Plain .index() is supported; SQLite maintains it through the DELETE.`)}},se=e=>{for(const[t,n]of Object.entries(e))if(n.shardMode.kind==="global"){for(const[r,a]of Object.entries(n.shape))if(P(a)==="bigint")throw new s("INTERNAL",`defineSchema: table "${t}" is .global() and column "${r}" is v.bigint(). A global (D1/Hyperdrive) table stores a bigint as decimal TEXT, which SQL compares lexicographically — "100" sorts before "25" — so \`orderBy\`, range filters and \`aggregate\` on this column would silently return wrong results. Use v.number() if the value fits a double, or v.string() if you only need equality.`)}},de=e=>{for(const[t,n]of Object.entries(e))if(n.dropStalePatchesMode===!0&&n.shardMode.kind==="global")throw new s("INTERNAL",`defineSchema: table "${t}" is both .global() and .dropStalePatches(). The stale check reads the caller's baseline out of the shard's \`__cdc_log\`, which a global (D1/Hyperdrive) table has no entries in — so every patch would read as "no baseline" and apply unchanged. Drop one of the two.`)},H=(e,t)=>{const n=[...Object.entries(e).flatMap(([r,a])=>a.vectorIndexes.map(d=>[r,d.name])),...Object.entries(t).map(([r,a])=>[a.table,r])];for(const[r,a]of n)if(e[r]?.shardMode.kind==="global")throw new s("INTERNAL",`defineSchema: ${G(r,a)}`)},le=e=>{for(const[t,n]of Object.entries(e)){if(n.commitOrderedMode){if(n.shardMode.kind==="global")throw new s("INTERNAL",`defineSchema: table "${t}" is both .global() and .commitOrdered(). \`_commitSeq\` is allocated inside the shard's write transaction, which a global (D1/Hyperdrive) table does not share — so the stamp would carry no commit-ordering guarantee. Drop one of the two.`);continue}for(const r of n.indexes)if(r.fields.includes(_))throw new s("INTERNAL",`defineSchema: table "${t}" index "${r.name}" names "${_}", but the table is not .commitOrdered() — no row carries that field, so the index would never match. Add .commitOrdered(), or drop the column from the index.`)}},Ie=(e,t={},n={},r={})=>(W(e),Z(e,n,r),ne(e),le(e),de(e),se(e),H(e,t),ie(e),K(e),y({tables:e,vectorIndexes:t})),I=(e,t)=>`${e}_${t}`,k=(e,t,n)=>n.has(e)?I(t,e):e,ce=(e,t,n,r)=>{const a=I(t,r),d=f=>f===""?a:k(f,t,n),u={};for(const[f,b]of Object.entries(e.relationMap))u[f]={...b,table:k(b.table,t,n)};const c=e.aggregateIndexes.map(f=>({...f,on:d(f.on)})),h=e.rankIndexes.map(f=>({...f,on:d(f.on)}));return{...e,aggregateIndexes:c,rankIndexes:h,relationMap:u}},pe=(e,t)=>{if(!e)throw new s("INTERNAL","defineSchemaExtension: `key` is required and must be a non-empty string");return{key:e,tables:t.tables,...t.vectorIndexes?{vectorIndexes:t.vectorIndexes}:{}}},ue=((e,t)=>{if(!e)throw new s("INTERNAL","definePlugin: `key` is required and must be a non-empty string");if(t.extension&&t.extension.key!==e)throw new s("INTERNAL",`definePlugin("${e}"): extension key "${t.extension.key}" does not match plugin key`);return{key:e,...t.extension?{extension:t.extension}:{},...t.middleware?{middleware:t.middleware}:{}}}),Ne=(e,t)=>({...ue(e,{...t.extension?{extension:t.extension}:{},...t.middleware?{middleware:t.middleware}:{}}),functions:t.functions??{}}),z=(e,t)=>{const{key:n}=t,r=new Set(Object.keys(t.tables)),a={...e.tables};for(const[u,c]of Object.entries(t.tables)){const h=I(n,u);if(Object.hasOwn(a,h))throw new s("INTERNAL",`defineSchema(...).extend("${n}"): table "${h}" already exists in the base schema — another extension with the same key already contributed it`);a[h]=ce(c,n,r,u)}const d={...e.vectorIndexes};if(t.vectorIndexes)for(const[u,c]of Object.entries(t.vectorIndexes)){const h=I(n,u);if(Object.hasOwn(d,h))throw new s("INTERNAL",`defineSchema(...).extend("${n}"): vector index "${h}" already exists in the base schema — another extension with the same key already contributed it`);d[h]={...c,table:k(c.table,n,r)}}return K(a),H(a,d),{rlsMode:e.rlsMode,tables:a,vectorIndexes:d}},ve=(e,t)=>{let n=e;for(const r of t)r.extension&&(n=z(n,r.extension));return n},Se=e=>{const t=e.map(n=>n.middleware).filter(n=>n!==void 0);return Q(t)};export{Ne as a,ue as b,Se as c,we as d,xe as e,Ie as f,pe as g,ge as h,be as i,ye as j,ve as k,K as l,z as m,H as v};
package/dist/types.d.mts CHANGED
@@ -348,6 +348,8 @@ interface TableVectorIndex {
348
348
  field: string;
349
349
  metadata?: ReadonlyArray<string>;
350
350
  metric: VectorMetric;
351
+ /** Declared embedding model; see `VectorizeOptions.model`. */
352
+ model?: string;
351
353
  name: string;
352
354
  }
353
355
  interface TableDefinition<Shape extends Record<string, Validator> = Record<string, Validator>> {
@@ -485,6 +487,8 @@ interface VectorIndexDefinition {
485
487
  readonly kind: "vectorIndex";
486
488
  readonly metadata?: (row: Record<string, unknown>) => Record<string, unknown>;
487
489
  readonly metric: VectorMetric;
490
+ /** Declared embedding model; see `VectorIndexOptions.model`. */
491
+ readonly model?: string;
488
492
  readonly select: (row: Record<string, unknown>) => string;
489
493
  readonly table: string;
490
494
  }
package/dist/types.d.ts CHANGED
@@ -348,6 +348,8 @@ interface TableVectorIndex {
348
348
  field: string;
349
349
  metadata?: ReadonlyArray<string>;
350
350
  metric: VectorMetric;
351
+ /** Declared embedding model; see `VectorizeOptions.model`. */
352
+ model?: string;
351
353
  name: string;
352
354
  }
353
355
  interface TableDefinition<Shape extends Record<string, Validator> = Record<string, Validator>> {
@@ -485,6 +487,8 @@ interface VectorIndexDefinition {
485
487
  readonly kind: "vectorIndex";
486
488
  readonly metadata?: (row: Record<string, unknown>) => Record<string, unknown>;
487
489
  readonly metric: VectorMetric;
490
+ /** Declared embedding model; see `VectorIndexOptions.model`. */
491
+ readonly model?: string;
488
492
  readonly select: (row: Record<string, unknown>) => string;
489
493
  readonly table: string;
490
494
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/server",
3
- "version": "1.0.0-alpha.142",
3
+ "version": "1.0.0-alpha.143",
4
4
  "description": "Server primitives for Lunora: defineSchema, defineTable, query, mutation, and action",
5
5
  "keywords": [
6
6
  "backend",
@@ -67,8 +67,8 @@
67
67
  },
68
68
  "dependencies": {
69
69
  "@lunora/errors": "1.0.0-alpha.41",
70
- "@lunora/scheduler": "1.0.0-alpha.84",
71
- "@lunora/shard-engine": "1.0.0-alpha.82",
70
+ "@lunora/scheduler": "1.0.0-alpha.85",
71
+ "@lunora/shard-engine": "1.0.0-alpha.83",
72
72
  "@lunora/values": "1.0.0-alpha.51",
73
73
  "drizzle-orm": "^0.45.2",
74
74
  "hono": "^4.13.7"
@@ -1 +0,0 @@
1
- import{LunoraError as s}from"@lunora/errors";import{c as Q}from"./compose-middleware-DNvrHMHx.mjs";import{v as B}from"@lunora/values";const q=["de","en","es","fr","it","nl","none","pt"],F=["native","portable"],V=e=>F.includes(e),X=e=>q.includes(e),U=e=>{const{value:t}=e._meta??{};if(t===null)return"null";switch(typeof t){case"bigint":case"boolean":case"number":case"string":return typeof t;default:return e.kind}},P=e=>{if(e.kind==="literal")return U(e);if(e.kind!=="optional")return e.kind;const t=e._meta?.inner;return t?P(t):e.kind},G=(e,t)=>`table "${e}" is .global() and declares vector index "${t}". Vector sync runs on the shard write path, which a global (D1/Hyperdrive) table's writes never take — the index would stay empty. Drop .global(), or keep the index yourself with ctx.vectors.upsert/deleteByIds.`,j=16,Y={many:(e,t)=>({field:t.field,kind:"many",references:t.references??"_id",table:e}),one:(e,t)=>({field:t.field,kind:"one",onDelete:t.onDelete,references:t.references??"_id",table:e})},g=(e,t,n)=>({handler:n,op:t,timing:e}),J=()=>({afterDelete:e=>g("after","delete",e),afterInsert:e=>g("after","insert",e),afterUpdate:e=>g("after","update",e),beforeDelete:e=>g("before","delete",e),beforeInsert:e=>g("before","insert",e),beforeUpdate:e=>g("before","update",e)}),C=(e,t)=>{if(!t||t.length===0)throw new s("INTERNAL",`rankIndex "${e}": "sortBy" is required and must list at least one key`);return t.map(n=>({direction:n.direction??"asc",field:n.field}))},ge=e=>{const t={...e},n=[],r=[],a=[],d=[],u={},c=[],h={},f=J(),b=[];let w={kind:"root"},E=!1,$=!1,p=!1,T=!1,M=!1,L,A,O,R;const D=o=>{if(w.kind!=="root"&&w.kind!==o.kind)throw new s("INTERNAL","shardBy/global: a table cannot be both .shardBy(key) and .global() — pick one. .shardBy(key) puts the rows in one Durable Object per key (isolation, poke-live reactivity); .global() puts them in a single replicated backend read from the edge.");w=o},l={aggregateIndex(o,i){const m=i?.op??"count";if(m!=="count"&&!i?.field)throw new s("INTERNAL",`aggregateIndex "${o}": op "${m}" requires a "field"`);return n.push({by:i?.by,field:i?.field,name:o,on:"",op:m,where:i?.where}),l},get aggregateIndexes(){return n},get externalSource(){return R},commitOrdered(){return E=!0,l},get commitOrderedMode(){return E},dropStalePatches(){return $=!0,l},get dropStalePatchesMode(){return $},externallyManaged(){return p=!0,l},geoIndex(o,i){return r.push({field:i.field,name:o,precision:i.precision}),l},get geoIndexes(){return r},global(o){return D({backend:o?.backend??"d1",kind:"global"}),l},get isExternallyManaged(){return p},get isPublic(){return M},index(o,i,m){return a.push({fields:i,name:o,unique:m?.unique??!1}),l},get indexes(){return a},memory(){return T=!0,l},get memoryMode(){return T},ownedBy(o){return L=o,l},get ownerField(){return L},public(){return M=!0,l},rankIndex(o,i){return d.push({name:o,on:"",partitionBy:i.partitionBy,sortBy:C(o,i.sortBy),where:i.where}),l},get rankIndexes(){return d},get relationMap(){return u},relations(o){return Object.assign(u,o(Y)),l},searchIndex(o,i){if(i.filterFields&&i.filterFields.length>j)throw new s("INTERNAL",`searchIndex "${o}": at most ${String(j)} filterFields are supported (got ${String(i.filterFields.length)})`);const{language:m}=i;if(m!==void 0&&!X(m))throw new s("INTERNAL",`searchIndex "${o}": unknown language "${m}" (supported: ${q.join(", ")})`);const{strategy:N}=i;if(N!==void 0&&!V(N))throw new s("INTERNAL",`searchIndex "${o}": unknown strategy "${N}" (supported: ${F.join(", ")})`);return c.push({field:i.field,filterFields:i.filterFields,language:i.language,name:o,staged:i.staged,strategy:i.strategy}),l},get searchIndexes(){return c},shape:t,shardBy(o){return D({field:o,kind:"shardBy"}),l},get shardMode(){return w},get softDeleteMode(){return A},source(o){if(!o.binding)throw new s("INTERNAL","source: `binding` is required (the wrangler Hyperdrive binding name)");if(!o.query)throw new s("INTERNAL","source: `query` is required (the tenant-membership SQL)");return R=o,p=!0,l},softDelete(o){const i=o?.field??"deletedAt";return A={field:i},i in t||(t[i]=B.optional(B.number().nullable())),l},get triggerMap(){return h},triggers(o){return Object.assign(h,o(f)),l},ttl(o,i){return O={after:i?.after,field:o},l},get ttlPolicy(){return O},get vectorIndexes(){return b},vectorize(o,i){return b.push({dimensions:i.dimensions,embed:i.embed,field:o,metadata:i.metadata,metric:i.metric,name:i.index}),l}};return l},be=e=>({dimensions:e.dimensions,embed:e.embed,kind:"vectorIndex",metadata:e.metadata,metric:e.metric,select:e.source.select,table:e.source.table}),we=(e,t)=>{const n=t.op??"count";if(n!=="count"&&!t.field)throw new s("INTERNAL",`aggregateIndex "${e}": op "${n}" requires a "field"`);return{by:t.by,field:t.field,name:e,on:t.on,op:n,where:t.where}},xe=(e,t)=>({name:e,on:t.table,partitionBy:t.partitionBy,sortBy:C(e,t.sortBy),where:t.where}),y=e=>({...e,extend(t){return y(z(e,t))},jurisdiction(t){return y(e)},rls(t){return y({...e,rlsMode:t})}}),W=e=>{for(const[t,n]of Object.entries(e))for(const r of[...n.aggregateIndexes,...n.rankIndexes])r.on===""&&(r.on=t)},Z=(e,t,n)=>{for(const r of Object.values(t)){const a=e[r.on];if(!a)throw new s("INTERNAL",`defineAggregateIndex "${r.name}": unknown table "${r.on}"`);a.aggregateIndexes.push(r)}for(const r of Object.values(n)){const a=e[r.on];if(!a)throw new s("INTERNAL",`defineRankIndex "${r.name}": unknown table "${r.on}"`);a.rankIndexes.push(r)}},ee=e=>{if(e.cursor)return"cursor";if(e.reconcileEveryMs!==void 0)return"reconcileEveryMs";if(e.softDeleteColumn!==void 0)return"softDeleteColumn"},te=(e,t)=>{const n=t.mode==="incremental";if(t.mode!==void 0&&t.mode!=="full-pull"&&!n)throw new s("INTERNAL",`defineSchema: table "${e}" uses \`mode: ${JSON.stringify(t.mode)}\` — supported modes are "full-pull" (default) and "incremental".`);if(!n){const r=ee(t);if(r)throw new s("INTERNAL",`defineSchema: table "${e}" sets \`${r}\` but is not \`mode: "incremental"\` — that knob only applies to incremental ingest. Set \`mode: "incremental"\` or remove \`${r}\`.`);return}if(!t.cursor?.column||!t.cursor.query)throw new s("INTERNAL",`defineSchema: table "${e}" is \`mode: "incremental"\` but has no \`cursor\` — add \`cursor: { column: "updated_at", query: "… WHERE … > $N" }\` binding the watermark as the trailing parameter.`);if(t.reconcileEveryMs===void 0&&t.softDeleteColumn===void 0)throw new s("INTERNAL",`defineSchema: table "${e}" is \`mode: "incremental"\` with no delete-visibility path — an incremental pull never sees upstream deletes, so it would accumulate phantom rows. Add \`reconcileEveryMs\` (a periodic full-pull sweep) or \`softDeleteColumn\` (an upstream tombstone column).`)},ne=e=>{for(const[t,n]of Object.entries(e)){const r=n.externalSource;if(r){if(n.shardMode.kind==="global")throw new s("INTERNAL",`defineSchema: table "${t}" cannot be both .source() and .global() — a sourced table materializes into a shard DO's SQLite, a global table lives in the external tier`);if(n.shardMode.kind==="shardBy"&&!r.tenantBy)throw new s("INTERNAL",`defineSchema: sourced + .shardBy() table "${t}" needs a \`tenantBy\` mapper — without it every tenant's DO would run the same unscoped query and replicate the whole multitenant table (a cross-tenant leak). Add \`tenantBy: (shardKey) => [shardKey]\` binding the shard key into the query's parameters.`);te(t,r)}}},re=["_commitSeq","_creationTime","_id"],_="_commitSeq",ae=new Set(re),x=(e,t,n,r)=>{if(!(ae.has(n)||n in r.shape))throw new s("INTERNAL",`defineSchema: table "${e}" index "${t}" names column "${n}" which is not in the table's shape`)},v=(e,t,n,r)=>{const a=new Set;for(const d of n){if(a.has(d.name))throw new s("INTERNAL",`defineSchema: table "${e}" declares ${t} "${d.name}" more than once`);a.add(d.name),r(d)}},K=e=>{for(const[t,n]of Object.entries(e))v(t,"index",n.indexes,r=>{for(const a of r.fields)x(t,r.name,a,n)}),v(t,"rank index",n.rankIndexes,r=>{for(const a of r.sortBy)x(t,r.name,a.field,n);for(const a of r.partitionBy??[])x(t,r.name,a,n)}),v(t,"geo index",n.geoIndexes,r=>{x(t,r.name,r.field,n)})},S=(e,t,n)=>{if(e.length===0)return;const r={};for(const a of e)r[t(a)]=n(a);return r},oe=e=>{const t=new Set(e.sortBy.map(n=>n.field));for(const n of e.partitionBy??[])t.add(n);return[...t]},ye=e=>{const t={};for(const[n,r]of Object.entries(e.tables)){const a=S(r.geoIndexes,c=>c.name,c=>[c.field]),d=S(r.indexes,c=>c.name,c=>c.fields),u=S(r.rankIndexes,c=>c.name,oe);(a||d||u)&&(t[n]={...a?{geo:a}:{},...d?{index:d}:{},...u?{rank:u}:{}})}return t},ie=e=>{for(const[t,n]of Object.entries(e)){if(!n.memoryMode)continue;const a=[[n.shardMode.kind==="global",".global() — those rows live in D1, which this shard does not own and cannot clear"],[n.commitOrderedMode===!0,".commitOrdered() — the counter resets with the table, so the sequence would restart and a consumer's cursor would silently skip everything after it"],[n.externalSource!==void 0,".source() — the table is materialized by the ingest loop, so wiping it on every eviction would fight the puller"],[n.searchIndexes.length>0,".searchIndex() — the FTS shadow is a separate table that clearing the rows would leave stale"],[n.geoIndexes.length>0,".geoIndex() — the geohash companion is a separate table that clearing the rows would leave stale"],[n.aggregateIndexes.length>0,".aggregateIndex() — the counter companion is a separate table that clearing the rows would leave stale"],[n.rankIndexes.length>0,".rankIndex() — the rank companion is a separate table that clearing the rows would leave stale"],[n.vectorIndexes.length>0,".vectorize() — vectors live in an external index that a shard restart cannot clear"]].find(([d])=>d)?.[1];if(a!==void 0)throw new s("INTERNAL",`defineSchema: table "${t}" is both .memory() and ${a}. Plain .index() is supported; SQLite maintains it through the DELETE.`)}},se=e=>{for(const[t,n]of Object.entries(e))if(n.shardMode.kind==="global"){for(const[r,a]of Object.entries(n.shape))if(P(a)==="bigint")throw new s("INTERNAL",`defineSchema: table "${t}" is .global() and column "${r}" is v.bigint(). A global (D1/Hyperdrive) table stores a bigint as decimal TEXT, which SQL compares lexicographically — "100" sorts before "25" — so \`orderBy\`, range filters and \`aggregate\` on this column would silently return wrong results. Use v.number() if the value fits a double, or v.string() if you only need equality.`)}},de=e=>{for(const[t,n]of Object.entries(e))if(n.dropStalePatchesMode===!0&&n.shardMode.kind==="global")throw new s("INTERNAL",`defineSchema: table "${t}" is both .global() and .dropStalePatches(). The stale check reads the caller's baseline out of the shard's \`__cdc_log\`, which a global (D1/Hyperdrive) table has no entries in — so every patch would read as "no baseline" and apply unchanged. Drop one of the two.`)},H=(e,t)=>{const n=[...Object.entries(e).flatMap(([r,a])=>a.vectorIndexes.map(d=>[r,d.name])),...Object.entries(t).map(([r,a])=>[a.table,r])];for(const[r,a]of n)if(e[r]?.shardMode.kind==="global")throw new s("INTERNAL",`defineSchema: ${G(r,a)}`)},le=e=>{for(const[t,n]of Object.entries(e)){if(n.commitOrderedMode){if(n.shardMode.kind==="global")throw new s("INTERNAL",`defineSchema: table "${t}" is both .global() and .commitOrdered(). \`_commitSeq\` is allocated inside the shard's write transaction, which a global (D1/Hyperdrive) table does not share — so the stamp would carry no commit-ordering guarantee. Drop one of the two.`);continue}for(const r of n.indexes)if(r.fields.includes(_))throw new s("INTERNAL",`defineSchema: table "${t}" index "${r.name}" names "${_}", but the table is not .commitOrdered() — no row carries that field, so the index would never match. Add .commitOrdered(), or drop the column from the index.`)}},Ie=(e,t={},n={},r={})=>(W(e),Z(e,n,r),ne(e),le(e),de(e),se(e),H(e,t),ie(e),K(e),y({tables:e,vectorIndexes:t})),I=(e,t)=>`${e}_${t}`,k=(e,t,n)=>n.has(e)?I(t,e):e,ce=(e,t,n,r)=>{const a=I(t,r),d=f=>f===""?a:k(f,t,n),u={};for(const[f,b]of Object.entries(e.relationMap))u[f]={...b,table:k(b.table,t,n)};const c=e.aggregateIndexes.map(f=>({...f,on:d(f.on)})),h=e.rankIndexes.map(f=>({...f,on:d(f.on)}));return{...e,aggregateIndexes:c,rankIndexes:h,relationMap:u}},pe=(e,t)=>{if(!e)throw new s("INTERNAL","defineSchemaExtension: `key` is required and must be a non-empty string");return{key:e,tables:t.tables,...t.vectorIndexes?{vectorIndexes:t.vectorIndexes}:{}}},ue=((e,t)=>{if(!e)throw new s("INTERNAL","definePlugin: `key` is required and must be a non-empty string");if(t.extension&&t.extension.key!==e)throw new s("INTERNAL",`definePlugin("${e}"): extension key "${t.extension.key}" does not match plugin key`);return{key:e,...t.extension?{extension:t.extension}:{},...t.middleware?{middleware:t.middleware}:{}}}),Ne=(e,t)=>({...ue(e,{...t.extension?{extension:t.extension}:{},...t.middleware?{middleware:t.middleware}:{}}),functions:t.functions??{}}),z=(e,t)=>{const{key:n}=t,r=new Set(Object.keys(t.tables)),a={...e.tables};for(const[u,c]of Object.entries(t.tables)){const h=I(n,u);if(Object.hasOwn(a,h))throw new s("INTERNAL",`defineSchema(...).extend("${n}"): table "${h}" already exists in the base schema — another extension with the same key already contributed it`);a[h]=ce(c,n,r,u)}const d={...e.vectorIndexes};if(t.vectorIndexes)for(const[u,c]of Object.entries(t.vectorIndexes)){const h=I(n,u);if(Object.hasOwn(d,h))throw new s("INTERNAL",`defineSchema(...).extend("${n}"): vector index "${h}" already exists in the base schema — another extension with the same key already contributed it`);d[h]={...c,table:k(c.table,n,r)}}return K(a),H(a,d),{rlsMode:e.rlsMode,tables:a,vectorIndexes:d}},ve=(e,t)=>{let n=e;for(const r of t)r.extension&&(n=z(n,r.extension));return n},Se=e=>{const t=e.map(n=>n.middleware).filter(n=>n!==void 0);return Q(t)};export{Ne as a,ue as b,Se as c,we as d,xe as e,Ie as f,pe as g,ge as h,be as i,ye as j,ve as k,K as l,z as m,H as v};