@lunora/server 1.0.0-alpha.274 → 1.0.0-alpha.276

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
@@ -2324,8 +2324,10 @@ interface StorageServeAuthzContext {
2324
2324
  * **403**; a throwing gate is a denial too, never a 500 (fail closed, mirroring
2325
2325
  * `@lunora/storage`'s `createUploadHandler`).
2326
2326
  *
2327
- * For a signed-URL topology this is where `verifySignedUrl` goes:
2328
- * `async ({ request }) => (await verifySignedUrl(new URL(request.url), secret)).valid`.
2327
+ * For a signed-URL topology this is where `authorizeSignedGet` goes:
2328
+ * `authorizeSignedGet(secret, { bucketName })` from `@lunora/storage`. A bare
2329
+ * `verifySignedUrl(...).valid` check admits an upload URL, another bucket or
2330
+ * another key.
2329
2331
  */
2330
2332
  type StorageServeAuthorizer = (context: StorageServeAuthzContext) => boolean | Promise<boolean>;
2331
2333
  /**
@@ -2339,7 +2341,7 @@ type StorageServeAuthorizer = (context: StorageServeAuthzContext) => boolean | P
2339
2341
  * `authorize` runs FIRST and is mandatory: this helper reads bytes out of a
2340
2342
  * bucket and hands them to whoever asked, so without a gate every mounted route
2341
2343
  * is an open object store. It does not verify signed URLs by itself — pass
2342
- * `verifySignedUrl` (or a session check) as the gate.
2344
+ * `authorizeSignedGet` (or a session check) as the gate.
2343
2345
  *
2344
2346
  * Every response carries `x-content-type-options: nosniff`, and any object whose
2345
2347
  * content type is not a raster image or media file also carries
package/dist/index.d.ts CHANGED
@@ -2324,8 +2324,10 @@ interface StorageServeAuthzContext {
2324
2324
  * **403**; a throwing gate is a denial too, never a 500 (fail closed, mirroring
2325
2325
  * `@lunora/storage`'s `createUploadHandler`).
2326
2326
  *
2327
- * For a signed-URL topology this is where `verifySignedUrl` goes:
2328
- * `async ({ request }) => (await verifySignedUrl(new URL(request.url), secret)).valid`.
2327
+ * For a signed-URL topology this is where `authorizeSignedGet` goes:
2328
+ * `authorizeSignedGet(secret, { bucketName })` from `@lunora/storage`. A bare
2329
+ * `verifySignedUrl(...).valid` check admits an upload URL, another bucket or
2330
+ * another key.
2329
2331
  */
2330
2332
  type StorageServeAuthorizer = (context: StorageServeAuthzContext) => boolean | Promise<boolean>;
2331
2333
  /**
@@ -2339,7 +2341,7 @@ type StorageServeAuthorizer = (context: StorageServeAuthzContext) => boolean | P
2339
2341
  * `authorize` runs FIRST and is mandatory: this helper reads bytes out of a
2340
2342
  * bucket and hands them to whoever asked, so without a gate every mounted route
2341
2343
  * is an open object store. It does not verify signed URLs by itself — pass
2342
- * `verifySignedUrl` (or a session check) as the gate.
2344
+ * `authorizeSignedGet` (or a session check) as the gate.
2343
2345
  *
2344
2346
  * Every response carries `x-content-type-options: nosniff`, and any object whose
2345
2347
  * content type is not a raster image or media file also carries
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{ACTION_CACHE_DEFAULT_TTL_MS as t,ACTION_CACHE_TABLE as i,actionCacheExtension as n,cacheKeyFor as f,defineActionCache as a}from"./packem_shared/ACTION_CACHE_DEFAULT_TTL_MS-DMYtb827.mjs";import{initLunora as s}from"./packem_shared/initLunora-DcvCGLL_.mjs";import{isPerDispatchMiddleware as p,tagPerDispatchMiddleware as x}from"./packem_shared/isPerDispatchMiddleware-DDQPatSm.mjs";import{createSecrets as l}from"./packem_shared/createSecrets-D6rLB42U.mjs";import{beginDeferredDeletes as u,flushDeferredDeletes as S,withDeferredDeletes as D}from"./packem_shared/beginDeferredDeletes-DhwFBbvs.mjs";import{beginDeferredSchedules as T,withDeferredSchedules as R}from"./packem_shared/beginDeferredSchedules--FVDtp-M.mjs";import{DOCUMENT_HISTORY_REDACTED_FIELDS as g,DOCUMENT_HISTORY_TABLE as L,defineDocumentHistory as _,documentHistoryExtension as I}from"./packem_shared/DOCUMENT_HISTORY_REDACTED_FIELDS-MUPXbAHR.mjs";import{LunoraEnvError as M,defineEnv as P}from"./packem_shared/LunoraEnvError-06_Zc4yc.mjs";import{bindOrm as y,bindTableFacade as O,defineLazyFacade as F}from"./packem_shared/bindOrm-D5mVDvbi.mjs";import{httpAction as N,httpRoute as U,httpRouter as H,lastEventId as k,sseEvent as w}from"./packem_shared/httpAction-Bfw3qwLG.mjs";import{serveStorageObject as V}from"./packem_shared/serveStorageObject-CLz3qhNI.mjs";import{defineIdentity as j}from"./packem_shared/defineIdentity-DwkNKwYa.mjs";import{default as z}from"./packem_shared/defineIdentityGuard-Bt8N65Zs.mjs";import{onConnect as J,onDisconnect as K,onShardInit as Q}from"./packem_shared/onConnect-BLRoOpv2.mjs";import{DEFAULT_LIMIT as q,DEFAULT_MAX_LIMIT as Z,clampLimit as $,defineListArgs as ee}from"./packem_shared/DEFAULT_LIMIT-pT_tV8R0.mjs";import{defineLiveStream as oe,liveStreamRouter as te}from"./packem_shared/defineLiveStream-q9yO3wl6.mjs";import{defineMigration as ne}from"./packem_shared/defineMigration-CXOS0Bvq.mjs";import{defineModule as ae}from"./packem_shared/defineModule-OecXWM3U.mjs";import{defineMutator as se}from"./packem_shared/defineMutator-DlLFSWbO.mjs";import{platformAdmin as pe}from"./packem_shared/platformAdmin-kczXQme8.mjs";import{c as ce,d as le,a as Ee,b as ue,e as Se,f as De,g as he,h as Te,i as Re,j as Ae,k as ge,m as Le}from"./packem_shared/plugin-D0ogWCbA.mjs";import{PRESENCE_DEFAULT_TTL_MS as Ie,PRESENCE_TABLE as Ce,definePresence as Me,presenceExtension as Pe}from"./packem_shared/PRESENCE_DEFAULT_TTL_MS-CKPKoWy_.mjs";import{PROCEDURE_META as ye,UNLOADED_META as Oe,procedureMeta as Fe}from"./packem_shared/PROCEDURE_META-DVzrXpfa.mjs";import{protectPublic as Ne}from"./packem_shared/protectPublic-Bi5_95aP.mjs";import{onQueryChange as He}from"./packem_shared/onQueryChange-iuLzmyPs.mjs";import{defineRoom as we}from"./packem_shared/defineRoom-CoGi-xwm.mjs";import{createServices as Ve}from"./packem_shared/createServices-IJvoqi0e.mjs";import{defineShape as je}from"./packem_shared/defineShape-CAIsX21I.mjs";import{defineWebSocket as ze}from"./packem_shared/defineWebSocket-BHoy6_ox.mjs";import{onWhisper as Je}from"./packem_shared/onWhisper-CfDbFLQh.mjs";import{LunoraError as Qe}from"@lunora/errors";import{cronJobs as qe}from"@lunora/scheduler";import{ValidationError as $e,v as er}from"@lunora/values";import{allowAll as or,deny as tr,isDeny as ir,toWhereInput as nr}from"./packem_shared/allowAll-DkRAgItV.mjs";import{asBucketStorage as ar}from"./packem_shared/asBucketStorage-DoGYOjq3.mjs";import{assertShapesDeclareReadPolicies as sr,buildRlsReadRegistry as mr,composeShapeReadWhere as pr}from"./packem_shared/assertShapesDeclareReadPolicies-CWrMYcqw.mjs";import{buildMaskRegistry as cr}from"./packem_shared/buildMaskRegistry-DpWMtalG.mjs";import{createPolicyDsl as Er,definePermission as ur,definePolicies as Sr,definePolicy as Dr,defineRole as hr}from"./packem_shared/createPolicyDsl-BZa6SqLJ.mjs";import{defineStorageRule as Rr,defineStorageRules as Ar}from"./packem_shared/defineStorageRule-Dv4nJE0H.mjs";import{isSafeHeaderValue as Lr}from"./packem_shared/isSafeHeaderValue-DswDADFy.mjs";import{mask as Ir}from"./packem_shared/mask--ZXtzCj7.mjs";import{r as Mr}from"./packem_shared/redact-secrets-BpatNz48.mjs";import{r as br}from"./packem_shared/middleware-CdoC33P7.mjs";import{storageRules as Or}from"./packem_shared/storageRules-BZgB67oS.mjs";const e="0.0.0";export{t as ACTION_CACHE_DEFAULT_TTL_MS,i as ACTION_CACHE_TABLE,q as DEFAULT_LIMIT,Z as DEFAULT_MAX_LIMIT,g as DOCUMENT_HISTORY_REDACTED_FIELDS,L as DOCUMENT_HISTORY_TABLE,M as LunoraEnvError,Qe as LunoraError,Ie as PRESENCE_DEFAULT_TTL_MS,Ce as PRESENCE_TABLE,ye as PROCEDURE_META,Oe as UNLOADED_META,e as VERSION,$e as ValidationError,n as actionCacheExtension,or as allowAll,ar as asBucketStorage,sr as assertShapesDeclareReadPolicies,u as beginDeferredDeletes,T as beginDeferredSchedules,y as bindOrm,O as bindTableFacade,cr as buildMaskRegistry,mr as buildRlsReadRegistry,f as cacheKeyFor,$ as clampLimit,ce as composePluginMiddleware,pr as composeShapeReadWhere,Er as createPolicyDsl,l as createSecrets,Ve as createServices,qe as cronJobs,a as defineActionCache,le as defineAggregateIndex,Ee as defineComponent,_ as defineDocumentHistory,P as defineEnv,j as defineIdentity,z as defineIdentityGuard,F as defineLazyFacade,ee as defineListArgs,oe as defineLiveStream,ne as defineMigration,ae as defineModule,se as defineMutator,ur as definePermission,ue as definePlugin,Sr as definePolicies,Dr as definePolicy,Me as definePresence,Se as defineRankIndex,hr as defineRole,we as defineRoom,De as defineSchema,he as defineSchemaExtension,je as defineShape,Rr as defineStorageRule,Ar as defineStorageRules,Te as defineTable,Re as defineVectorIndex,ze as defineWebSocket,tr as deny,I as documentHistoryExtension,S as flushDeferredDeletes,N as httpAction,U as httpRoute,H as httpRouter,Ae as indexFieldsFromSchema,s as initLunora,ge as installPlugins,ir as isDeny,p as isPerDispatchMiddleware,Lr as isSafeHeaderValue,k as lastEventId,te as liveStreamRouter,Ir as mask,Le as mergeSchemaExtension,J as onConnect,K as onDisconnect,He as onQueryChange,Q as onShardInit,Je as onWhisper,pe as platformAdmin,Pe as presenceExtension,Fe as procedureMeta,Ne as protectPublic,Mr as redactSecrets,br as rls,V as serveStorageObject,w as sseEvent,Or as storageRules,x as tagPerDispatchMiddleware,nr as toWhereInput,er as v,D as withDeferredDeletes,R as withDeferredSchedules};
1
+ import{ACTION_CACHE_DEFAULT_TTL_MS as t,ACTION_CACHE_TABLE as i,actionCacheExtension as n,cacheKeyFor as f,defineActionCache as a}from"./packem_shared/ACTION_CACHE_DEFAULT_TTL_MS-Dv4DKrj0.mjs";import{initLunora as s}from"./packem_shared/initLunora-DcvCGLL_.mjs";import{isPerDispatchMiddleware as p,tagPerDispatchMiddleware as x}from"./packem_shared/isPerDispatchMiddleware-DDQPatSm.mjs";import{createSecrets as l}from"./packem_shared/createSecrets-D6rLB42U.mjs";import{beginDeferredDeletes as u,flushDeferredDeletes as S,withDeferredDeletes as D}from"./packem_shared/beginDeferredDeletes-DhwFBbvs.mjs";import{beginDeferredSchedules as T,withDeferredSchedules as R}from"./packem_shared/beginDeferredSchedules--FVDtp-M.mjs";import{DOCUMENT_HISTORY_REDACTED_FIELDS as g,DOCUMENT_HISTORY_TABLE as L,defineDocumentHistory as _,documentHistoryExtension as I}from"./packem_shared/DOCUMENT_HISTORY_REDACTED_FIELDS-BCa6sLSJ.mjs";import{LunoraEnvError as M,defineEnv as P}from"./packem_shared/LunoraEnvError-06_Zc4yc.mjs";import{bindOrm as y,bindTableFacade as O,defineLazyFacade as F}from"./packem_shared/bindOrm-D5mVDvbi.mjs";import{httpAction as N,httpRoute as U,httpRouter as H,lastEventId as k,sseEvent as w}from"./packem_shared/httpAction-Bfw3qwLG.mjs";import{serveStorageObject as V}from"./packem_shared/serveStorageObject-CLz3qhNI.mjs";import{defineIdentity as j}from"./packem_shared/defineIdentity-DwkNKwYa.mjs";import{default as z}from"./packem_shared/defineIdentityGuard-Bt8N65Zs.mjs";import{onConnect as J,onDisconnect as K,onShardInit as Q}from"./packem_shared/onConnect-BLRoOpv2.mjs";import{DEFAULT_LIMIT as q,DEFAULT_MAX_LIMIT as Z,clampLimit as $,defineListArgs as ee}from"./packem_shared/DEFAULT_LIMIT-pT_tV8R0.mjs";import{defineLiveStream as oe,liveStreamRouter as te}from"./packem_shared/defineLiveStream-q9yO3wl6.mjs";import{defineMigration as ne}from"./packem_shared/defineMigration-CXOS0Bvq.mjs";import{defineModule as ae}from"./packem_shared/defineModule-OecXWM3U.mjs";import{defineMutator as se}from"./packem_shared/defineMutator-DlLFSWbO.mjs";import{platformAdmin as pe}from"./packem_shared/platformAdmin-kczXQme8.mjs";import{c as ce,d as le,a as Ee,b as ue,e as Se,f as De,g as he,h as Te,i as Re,j as Ae,k as ge,m as Le}from"./packem_shared/plugin-CyLqvCB9.mjs";import{PRESENCE_DEFAULT_TTL_MS as Ie,PRESENCE_TABLE as Ce,definePresence as Me,presenceExtension as Pe}from"./packem_shared/PRESENCE_DEFAULT_TTL_MS-TXTxGfEA.mjs";import{PROCEDURE_META as ye,UNLOADED_META as Oe,procedureMeta as Fe}from"./packem_shared/PROCEDURE_META-DVzrXpfa.mjs";import{protectPublic as Ne}from"./packem_shared/protectPublic-Bi5_95aP.mjs";import{onQueryChange as He}from"./packem_shared/onQueryChange-iuLzmyPs.mjs";import{defineRoom as we}from"./packem_shared/defineRoom-CoGi-xwm.mjs";import{createServices as Ve}from"./packem_shared/createServices-IJvoqi0e.mjs";import{defineShape as je}from"./packem_shared/defineShape-CAIsX21I.mjs";import{defineWebSocket as ze}from"./packem_shared/defineWebSocket-BHoy6_ox.mjs";import{onWhisper as Je}from"./packem_shared/onWhisper-CfDbFLQh.mjs";import{LunoraError as Qe}from"@lunora/errors";import{cronJobs as qe}from"@lunora/scheduler";import{ValidationError as $e,v as er}from"@lunora/values";import{allowAll as or,deny as tr,isDeny as ir,toWhereInput as nr}from"./packem_shared/allowAll-DkRAgItV.mjs";import{asBucketStorage as ar}from"./packem_shared/asBucketStorage-DoGYOjq3.mjs";import{assertShapesDeclareReadPolicies as sr,buildRlsReadRegistry as mr,composeShapeReadWhere as pr}from"./packem_shared/assertShapesDeclareReadPolicies-CWrMYcqw.mjs";import{buildMaskRegistry as cr}from"./packem_shared/buildMaskRegistry-DpWMtalG.mjs";import{createPolicyDsl as Er,definePermission as ur,definePolicies as Sr,definePolicy as Dr,defineRole as hr}from"./packem_shared/createPolicyDsl-BZa6SqLJ.mjs";import{defineStorageRule as Rr,defineStorageRules as Ar}from"./packem_shared/defineStorageRule-Dv4nJE0H.mjs";import{isSafeHeaderValue as Lr}from"./packem_shared/isSafeHeaderValue-DswDADFy.mjs";import{mask as Ir}from"./packem_shared/mask--ZXtzCj7.mjs";import{r as Mr}from"./packem_shared/redact-secrets-BpatNz48.mjs";import{r as br}from"./packem_shared/middleware-CdoC33P7.mjs";import{storageRules as Or}from"./packem_shared/storageRules-BZgB67oS.mjs";const e="0.0.0";export{t as ACTION_CACHE_DEFAULT_TTL_MS,i as ACTION_CACHE_TABLE,q as DEFAULT_LIMIT,Z as DEFAULT_MAX_LIMIT,g as DOCUMENT_HISTORY_REDACTED_FIELDS,L as DOCUMENT_HISTORY_TABLE,M as LunoraEnvError,Qe as LunoraError,Ie as PRESENCE_DEFAULT_TTL_MS,Ce as PRESENCE_TABLE,ye as PROCEDURE_META,Oe as UNLOADED_META,e as VERSION,$e as ValidationError,n as actionCacheExtension,or as allowAll,ar as asBucketStorage,sr as assertShapesDeclareReadPolicies,u as beginDeferredDeletes,T as beginDeferredSchedules,y as bindOrm,O as bindTableFacade,cr as buildMaskRegistry,mr as buildRlsReadRegistry,f as cacheKeyFor,$ as clampLimit,ce as composePluginMiddleware,pr as composeShapeReadWhere,Er as createPolicyDsl,l as createSecrets,Ve as createServices,qe as cronJobs,a as defineActionCache,le as defineAggregateIndex,Ee as defineComponent,_ as defineDocumentHistory,P as defineEnv,j as defineIdentity,z as defineIdentityGuard,F as defineLazyFacade,ee as defineListArgs,oe as defineLiveStream,ne as defineMigration,ae as defineModule,se as defineMutator,ur as definePermission,ue as definePlugin,Sr as definePolicies,Dr as definePolicy,Me as definePresence,Se as defineRankIndex,hr as defineRole,we as defineRoom,De as defineSchema,he as defineSchemaExtension,je as defineShape,Rr as defineStorageRule,Ar as defineStorageRules,Te as defineTable,Re as defineVectorIndex,ze as defineWebSocket,tr as deny,I as documentHistoryExtension,S as flushDeferredDeletes,N as httpAction,U as httpRoute,H as httpRouter,Ae as indexFieldsFromSchema,s as initLunora,ge as installPlugins,ir as isDeny,p as isPerDispatchMiddleware,Lr as isSafeHeaderValue,k as lastEventId,te as liveStreamRouter,Ir as mask,Le as mergeSchemaExtension,J as onConnect,K as onDisconnect,He as onQueryChange,Q as onShardInit,Je as onWhisper,pe as platformAdmin,Pe as presenceExtension,Fe as procedureMeta,Ne as protectPublic,Mr as redactSecrets,br as rls,V as serveStorageObject,w as sseEvent,Or as storageRules,x as tagPerDispatchMiddleware,nr as toWhereInput,er as v,D as withDeferredDeletes,R as withDeferredSchedules};
@@ -1 +1 @@
1
- import{isLunoraError as O}from"@lunora/errors";import{v as d}from"@lunora/values";import{parseWire as U,encodeWire as D,stableWireKey as F}from"@lunora/wire";import{initLunora as S}from"./initLunora-DcvCGLL_.mjs";import{g as k,h as q,a as B}from"./plugin-D0ogWCbA.mjs";const P=3600*1e3,R=512*1024,H=8,b=64,V=64,K=256,W=4096,u="actionCache",h="entries",r=`${u}_${h}`,T=o=>o===void 0?"":F(o),x=async(o,m)=>{const A=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(`${o}\0${m}`));return[...new Uint8Array(A)].map(y=>y.toString(16).padStart(2,"0")).join("")},$=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:G}=S.dataModel().create(),Z=(o={})=>{const m=o.ttlMs!==void 0&&Number.isFinite(o.ttlMs)?Math.max(1,Math.floor(o.ttlMs)):P,A=o.maxValueBytes!==void 0&&Number.isFinite(o.maxValueBytes)?Math.max(1,Math.floor(o.maxValueBytes)):R,y=async(e,t)=>{const n=(await e.db.query(r).withIndex("byExpiresAt").order("asc").take(H)).filter(s=>s.expiresAt<=t);await Promise.all(n.map(async s=>e.db.delete(r,s._id)))},C=async(e,t)=>e.db.query(r).withIndex("byKey",a=>a.eq("key",t)).first(),f=new Set(["CONFLICT","NOT_FOUND","NOT_UNIQUE"]),N=async(e,t,a)=>{try{await(t?e.db.patch(r,t._id,{expiresAt:a.expiresAt,value:a.value}):e.db.insert(r,a))}catch(n){if(O(n)&&f.has(n.code))return;throw n}},I=async(e,t,a,n)=>{const s=T(a),i=await x(t,s),l=Date.now(),c=await C(e,i);if(c&&c.expiresAt>l)return U(c.value).v;const p=await n(),w=JSON.stringify(D({v:p})),E=Date.now(),g=E+m;return new TextEncoder().encode(w).length<=A?await N(e,c,{expiresAt:g,key:i,name:t,value:w}):c&&await e.db.delete(r,c._id),await y(e,E),p},M=async(e,t,a)=>{const n=await x(t,T(a)),s=await e.db.query(r).withIndex("byKey",i=>i.eq("key",n)).take(b);await Promise.all(s.map(async i=>e.db.delete(r,i._id)))},_=async(e,t,a,n)=>{if(n>=V)return{complete:!1,deleted:a};const s=await e.db.query(r).withIndex("byName",i=>i.eq("name",t)).take(b);return s.length===0?{complete:!0,deleted:a}:(await Promise.all(s.map(async i=>e.db.delete(r,i._id))),_(e,t,a+s.length,n+1))},L=async(e,t)=>_(e,t,0,0),v=G.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(W,Math.max(1,Math.floor(e.limit))):K,i=(await t.db.query(r).withIndex("byExpiresAt").order("asc").take(n)).filter(l=>l.expiresAt<=a);return await Promise.all(i.map(async l=>t.db.delete(r,l._id))),{deleted:i.length}});return{...B(u,{extension:$,functions:{purgeExpired:v}}),invalidate:M,invalidateAll:L,wrap:I}};export{P as ACTION_CACHE_DEFAULT_TTL_MS,r as ACTION_CACHE_TABLE,$ as actionCacheExtension,x as cacheKeyFor,Z as defineActionCache};
1
+ import{isLunoraError as O}from"@lunora/errors";import{v as d}from"@lunora/values";import{parseWire as U,encodeWire as D,stableWireKey as F}from"@lunora/wire";import{initLunora as S}from"./initLunora-DcvCGLL_.mjs";import{g as k,h as q,a as B}from"./plugin-CyLqvCB9.mjs";const P=3600*1e3,R=512*1024,H=8,b=64,V=64,K=256,W=4096,u="actionCache",h="entries",r=`${u}_${h}`,T=o=>o===void 0?"":F(o),x=async(o,m)=>{const A=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(`${o}\0${m}`));return[...new Uint8Array(A)].map(y=>y.toString(16).padStart(2,"0")).join("")},$=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:G}=S.dataModel().create(),Z=(o={})=>{const m=o.ttlMs!==void 0&&Number.isFinite(o.ttlMs)?Math.max(1,Math.floor(o.ttlMs)):P,A=o.maxValueBytes!==void 0&&Number.isFinite(o.maxValueBytes)?Math.max(1,Math.floor(o.maxValueBytes)):R,y=async(e,t)=>{const n=(await e.db.query(r).withIndex("byExpiresAt").order("asc").take(H)).filter(s=>s.expiresAt<=t);await Promise.all(n.map(async s=>e.db.delete(r,s._id)))},C=async(e,t)=>e.db.query(r).withIndex("byKey",a=>a.eq("key",t)).first(),f=new Set(["CONFLICT","NOT_FOUND","NOT_UNIQUE"]),N=async(e,t,a)=>{try{await(t?e.db.patch(r,t._id,{expiresAt:a.expiresAt,value:a.value}):e.db.insert(r,a))}catch(n){if(O(n)&&f.has(n.code))return;throw n}},I=async(e,t,a,n)=>{const s=T(a),i=await x(t,s),l=Date.now(),c=await C(e,i);if(c&&c.expiresAt>l)return U(c.value).v;const p=await n(),w=JSON.stringify(D({v:p})),E=Date.now(),g=E+m;return new TextEncoder().encode(w).length<=A?await N(e,c,{expiresAt:g,key:i,name:t,value:w}):c&&await e.db.delete(r,c._id),await y(e,E),p},M=async(e,t,a)=>{const n=await x(t,T(a)),s=await e.db.query(r).withIndex("byKey",i=>i.eq("key",n)).take(b);await Promise.all(s.map(async i=>e.db.delete(r,i._id)))},_=async(e,t,a,n)=>{if(n>=V)return{complete:!1,deleted:a};const s=await e.db.query(r).withIndex("byName",i=>i.eq("name",t)).take(b);return s.length===0?{complete:!0,deleted:a}:(await Promise.all(s.map(async i=>e.db.delete(r,i._id))),_(e,t,a+s.length,n+1))},L=async(e,t)=>_(e,t,0,0),v=G.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(W,Math.max(1,Math.floor(e.limit))):K,i=(await t.db.query(r).withIndex("byExpiresAt").order("asc").take(n)).filter(l=>l.expiresAt<=a);return await Promise.all(i.map(async l=>t.db.delete(r,l._id))),{deleted:i.length}});return{...B(u,{extension:$,functions:{purgeExpired:v}}),invalidate:M,invalidateAll:L,wrap:I}};export{P as ACTION_CACHE_DEFAULT_TTL_MS,r as ACTION_CACHE_TABLE,$ as actionCacheExtension,x as cacheKeyFor,Z as defineActionCache};
@@ -1 +1 @@
1
- import{v as r}from"@lunora/values";import{parseWire as I,encodeWire as O}from"@lunora/wire";import{initLunora as x}from"./initLunora-DcvCGLL_.mjs";import{g as v,h as R,a as U}from"./plugin-D0ogWCbA.mjs";const H=2160*60*60*1e3,L=64*1024,y=200,q=1e3,C=64,F=512,u=16,g=["_commitSeq","seq"],B=["accessToken","apiKey","backupCodes","clientSecret","hashedPassword","password","privateKey","refreshToken","secret","totpSecret"],b="documentHistory",T="versions",l=`${b}_${T}`,w=v(b,{tables:{[T]: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:P,internalQuery:Y}=x.dataModel().create(),V=(d={})=>{const _=d.retentionMs!==void 0&&Number.isFinite(d.retentionMs)?Math.max(1,Math.floor(d.retentionMs)):H,p=d.maxSnapshotBytes!==void 0&&Number.isFinite(d.maxSnapshotBytes)?Math.max(1,Math.floor(d.maxSnapshotBytes)):L,A=new Set([...B,...d.redact??[]]);let M=0;const D=()=>(M+=1,M),a=(e,t=0)=>{if(Array.isArray(e))return t>=u?void 0:e.map(o=>a(o,t+1));if(typeof e!="object"||e===null)return e;if(e instanceof Map)return t>=u?void 0:new Map([...e.entries()].filter(([o])=>typeof o!="string"||!A.has(o)).map(([o,i])=>[o,a(i,t+1)]));if(e instanceof Set)return t>=u?void 0:new Set([...e].map(o=>a(o,t+1)));if(Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null)return e;if(!(t>=u))return Object.fromEntries(Object.entries(e).filter(([o])=>!A.has(o)).map(([o,i])=>[o,a(i,t+1)]))},E=e=>{if(e===void 0)return;const t=JSON.stringify(O(a(e)));if(!(t.length>p))return 3*t.length<=p?t:new TextEncoder().encode(t).length>p?void 0:t},f=async(e,t)=>{const o=E(t.doc),i=E(t.previous),n=t.doc!==void 0&&o===void 0||t.previous!==void 0&&i===void 0;await e.db.insert(l,{documentId:t.documentId,op:t.op,recordedAt:Date.now(),seq:D(),tableName:t.tableName,...n?{truncated:!0}:{},...o===void 0?{}:{doc:o},...i===void 0?{}:{previous:i}})},S=e=>({documentHistoryDelete:e.afterDelete(async(t,o)=>f(t,{documentId:o.id,op:"delete",previous:o.previous,tableName:o.table})),documentHistoryInsert:e.afterInsert(async(t,o)=>f(t,{doc:o.doc,documentId:o.id,op:"insert",tableName:o.table})),documentHistoryUpdate:e.afterUpdate(async(t,o)=>f(t,{doc:o.doc,documentId:o.id,op:"update",previous:o.previous,tableName:o.table}))}),h=Y.input({before:r.optional(r.number()),documentId:r.string(),limit:r.optional(r.number())}).query(async({args:e,ctx:t})=>{const o=e.limit!==void 0&&Number.isFinite(e.limit)?Math.min(q,Math.max(1,Math.floor(e.limit))):y,i=await t.db.query(l).withIndex("byDocumentRecordedAt",n=>e.before===void 0?n.eq("documentId",e.documentId):n.eq("documentId",e.documentId).lte("recordedAt",e.before)).order("desc").take(o);return i.sort((n,m)=>{for(const c of g){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:I(n.doc)},...n.previous===void 0?{}:{previous:I(n.previous)},...n.truncated===!0?{truncated:!0}:{}}))}),N=P.input({limit:r.optional(r.number())}).mutation(async({args:e,ctx:t})=>{const o=Date.now()-_,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 t.db.query(l).withIndex("byRecordedAt",s=>s.lt("recordedAt",o)).order("asc").take(Math.min(y,i-n));if(c.length===0)return{deleted:n};await Promise.all(c.map(async s=>t.db.delete(l,s._id))),n+=c.length}return{deleted:n}});return{...U(b,{extension:w,functions:{listForDocument:h,vacuum:N}}),record:S}};export{B as DOCUMENT_HISTORY_REDACTED_FIELDS,l as DOCUMENT_HISTORY_TABLE,V as defineDocumentHistory,w as documentHistoryExtension};
1
+ import{v as r}from"@lunora/values";import{parseWire as I,encodeWire as O}from"@lunora/wire";import{initLunora as x}from"./initLunora-DcvCGLL_.mjs";import{g as v,h as R,a as U}from"./plugin-CyLqvCB9.mjs";const H=2160*60*60*1e3,L=64*1024,y=200,q=1e3,C=64,F=512,u=16,g=["_commitSeq","seq"],B=["accessToken","apiKey","backupCodes","clientSecret","hashedPassword","password","privateKey","refreshToken","secret","totpSecret"],b="documentHistory",T="versions",l=`${b}_${T}`,w=v(b,{tables:{[T]: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:P,internalQuery:Y}=x.dataModel().create(),V=(d={})=>{const _=d.retentionMs!==void 0&&Number.isFinite(d.retentionMs)?Math.max(1,Math.floor(d.retentionMs)):H,p=d.maxSnapshotBytes!==void 0&&Number.isFinite(d.maxSnapshotBytes)?Math.max(1,Math.floor(d.maxSnapshotBytes)):L,A=new Set([...B,...d.redact??[]]);let M=0;const D=()=>(M+=1,M),a=(e,t=0)=>{if(Array.isArray(e))return t>=u?void 0:e.map(o=>a(o,t+1));if(typeof e!="object"||e===null)return e;if(e instanceof Map)return t>=u?void 0:new Map([...e.entries()].filter(([o])=>typeof o!="string"||!A.has(o)).map(([o,i])=>[o,a(i,t+1)]));if(e instanceof Set)return t>=u?void 0:new Set([...e].map(o=>a(o,t+1)));if(Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null)return e;if(!(t>=u))return Object.fromEntries(Object.entries(e).filter(([o])=>!A.has(o)).map(([o,i])=>[o,a(i,t+1)]))},E=e=>{if(e===void 0)return;const t=JSON.stringify(O(a(e)));if(!(t.length>p))return 3*t.length<=p?t:new TextEncoder().encode(t).length>p?void 0:t},f=async(e,t)=>{const o=E(t.doc),i=E(t.previous),n=t.doc!==void 0&&o===void 0||t.previous!==void 0&&i===void 0;await e.db.insert(l,{documentId:t.documentId,op:t.op,recordedAt:Date.now(),seq:D(),tableName:t.tableName,...n?{truncated:!0}:{},...o===void 0?{}:{doc:o},...i===void 0?{}:{previous:i}})},S=e=>({documentHistoryDelete:e.afterDelete(async(t,o)=>f(t,{documentId:o.id,op:"delete",previous:o.previous,tableName:o.table})),documentHistoryInsert:e.afterInsert(async(t,o)=>f(t,{doc:o.doc,documentId:o.id,op:"insert",tableName:o.table})),documentHistoryUpdate:e.afterUpdate(async(t,o)=>f(t,{doc:o.doc,documentId:o.id,op:"update",previous:o.previous,tableName:o.table}))}),h=Y.input({before:r.optional(r.number()),documentId:r.string(),limit:r.optional(r.number())}).query(async({args:e,ctx:t})=>{const o=e.limit!==void 0&&Number.isFinite(e.limit)?Math.min(q,Math.max(1,Math.floor(e.limit))):y,i=await t.db.query(l).withIndex("byDocumentRecordedAt",n=>e.before===void 0?n.eq("documentId",e.documentId):n.eq("documentId",e.documentId).lte("recordedAt",e.before)).order("desc").take(o);return i.sort((n,m)=>{for(const c of g){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:I(n.doc)},...n.previous===void 0?{}:{previous:I(n.previous)},...n.truncated===!0?{truncated:!0}:{}}))}),N=P.input({limit:r.optional(r.number())}).mutation(async({args:e,ctx:t})=>{const o=Date.now()-_,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 t.db.query(l).withIndex("byRecordedAt",s=>s.lt("recordedAt",o)).order("asc").take(Math.min(y,i-n));if(c.length===0)return{deleted:n};await Promise.all(c.map(async s=>t.db.delete(l,s._id))),n+=c.length}return{deleted:n}});return{...U(b,{extension:w,functions:{listForDocument:h,vacuum:N}}),record:S}};export{B as DOCUMENT_HISTORY_REDACTED_FIELDS,l as DOCUMENT_HISTORY_TABLE,V as defineDocumentHistory,w as documentHistoryExtension};
@@ -1 +1 @@
1
- import{LunoraError as E}from"@lunora/errors";import{v as e}from"@lunora/values";import{initLunora as x}from"./initLunora-DcvCGLL_.mjs";import{onDisconnect as R}from"./onConnect-BLRoOpv2.mjs";import{g as L,h as A,a as v}from"./plugin-D0ogWCbA.mjs";const D=3e4,P=1024,N=8,b=4096,y="presence",p="present",r=`${y}_${p}`,B=l=>{const I=l?.orgId;return typeof I=="string"?I:""},C=L(y,{tables:{[p]:A({data:e.optional(e.record(e.string(),e.any())),lastSeen:e.number(),roomId:e.string(),sessionId:e.string(),tenantId:e.string(),userId:e.optional(e.string())}).index("byTenantRoomSession",["tenantId","roomId","sessionId"]).index("byTenantRoomLastSeen",["tenantId","roomId","lastSeen"])}}),{internalMutation:U,mutation:F,query:O}=x.dataModel().create(),H=(l={})=>{const I=l.ttlMs??D,S=l.tenant??B,w=Math.max(0,Math.min(l.disconnectGraceMs??0,I)),h=l.maxSessions,T=h!==void 0&&Number.isFinite(h)?Math.max(1,Math.floor(h)):P,_=F.input({data:e.optional(e.record(e.string(),e.any())),roomId:e.string(),sessionId:e.string()}).mutation(async({args:t,ctx:n})=>{const c=Date.now(),d=n.auth.userId??void 0,o=S(await n.auth.getIdentity());if(t.data!==void 0&&new TextEncoder().encode(JSON.stringify(t.data)).length>b)throw new E("BAD_REQUEST",`presence data exceeds the ${String(b)}-byte limit`);const s=await n.db.query(r).withIndex("byTenantRoomSession",i=>i.eq("tenantId",o).eq("roomId",t.roomId).eq("sessionId",t.sessionId)).first();if(s&&(s.userId??void 0)!==d)throw new E("FORBIDDEN","presence heartbeat denied: this (roomId, sessionId) is held by another identity");const m={lastSeen:c,roomId:t.roomId,sessionId:t.sessionId,tenantId:o,...t.data===void 0?{}:{data:t.data},...d===void 0?{}:{userId:d}};await(s?n.db.patch(r,s._id,m):n.db.insert(r,m));const f=c-I-Math.max(w,I),u=(await n.db.query(r).withIndex("byTenantRoomLastSeen",i=>i.eq("tenantId",o).eq("roomId",t.roomId)).order("asc").take(N)).filter(i=>i.lastSeen<=f);return await Promise.all(u.map(i=>n.db.delete(r,i._id))),{lastSeen:c}}),q=O.input({roomId:e.string()}).query(async({args:t,ctx:n})=>{const c=Date.now()-I,d=S(await n.auth.getIdentity()),s=(await n.db.query(r).withIndex("byTenantRoomLastSeen",a=>a.eq("tenantId",d).eq("roomId",t.roomId)).order("desc").take(T)).filter(a=>a.lastSeen>c),m=new Set,f=[];for(const a of s){const u=a.userId;if(u!==void 0){if(m.has(u))continue;m.add(u)}const i={lastSeen:a.lastSeen,roomId:a.roomId};u!==void 0&&(i.userId=u),a.data!==void 0&&(i.data=a.data),f.push(i)}return f}),g=U.input({roomId:e.string(),tenantId:e.string()}).mutation(async({args:t,ctx:n})=>{const c=Date.now()-I,d=await n.db.query(r).withIndex("byTenantRoomLastSeen",o=>o.eq("tenantId",t.tenantId).eq("roomId",t.roomId)).filter(o=>o.lastSeen<=c).collect();return await Promise.all(d.map(o=>n.db.delete(r,o._id))),{deleted:d.length}}),M=R(async(t,n)=>{const c=n.context?.roomId,d=n.context?.sessionId;if(typeof c!="string"||typeof d!="string")return;const o=S(await t.auth.getIdentity()),s=await t.db.query(r).withIndex("byTenantRoomSession",a=>a.eq("tenantId",o).eq("roomId",c).eq("sessionId",d)).first();if(!s)return;const m=n.userId??void 0;if((s.userId??void 0)!==m)return;if(w===0){await t.db.delete(r,s._id);return}const f=Math.min(s.lastSeen,Date.now()+w-I);await t.db.patch(r,s._id,{lastSeen:f})});return v(y,{extension:C,functions:{disconnect:M,heartbeat:_,listPresent:q,sweep:g}})};export{D as PRESENCE_DEFAULT_TTL_MS,r as PRESENCE_TABLE,H as definePresence,C as presenceExtension};
1
+ import{LunoraError as E}from"@lunora/errors";import{v as e}from"@lunora/values";import{initLunora as x}from"./initLunora-DcvCGLL_.mjs";import{onDisconnect as R}from"./onConnect-BLRoOpv2.mjs";import{g as L,h as A,a as v}from"./plugin-CyLqvCB9.mjs";const D=3e4,P=1024,N=8,b=4096,y="presence",p="present",r=`${y}_${p}`,B=l=>{const I=l?.orgId;return typeof I=="string"?I:""},C=L(y,{tables:{[p]:A({data:e.optional(e.record(e.string(),e.any())),lastSeen:e.number(),roomId:e.string(),sessionId:e.string(),tenantId:e.string(),userId:e.optional(e.string())}).index("byTenantRoomSession",["tenantId","roomId","sessionId"]).index("byTenantRoomLastSeen",["tenantId","roomId","lastSeen"])}}),{internalMutation:U,mutation:F,query:O}=x.dataModel().create(),H=(l={})=>{const I=l.ttlMs??D,S=l.tenant??B,w=Math.max(0,Math.min(l.disconnectGraceMs??0,I)),h=l.maxSessions,T=h!==void 0&&Number.isFinite(h)?Math.max(1,Math.floor(h)):P,_=F.input({data:e.optional(e.record(e.string(),e.any())),roomId:e.string(),sessionId:e.string()}).mutation(async({args:t,ctx:n})=>{const c=Date.now(),d=n.auth.userId??void 0,o=S(await n.auth.getIdentity());if(t.data!==void 0&&new TextEncoder().encode(JSON.stringify(t.data)).length>b)throw new E("BAD_REQUEST",`presence data exceeds the ${String(b)}-byte limit`);const s=await n.db.query(r).withIndex("byTenantRoomSession",i=>i.eq("tenantId",o).eq("roomId",t.roomId).eq("sessionId",t.sessionId)).first();if(s&&(s.userId??void 0)!==d)throw new E("FORBIDDEN","presence heartbeat denied: this (roomId, sessionId) is held by another identity");const m={lastSeen:c,roomId:t.roomId,sessionId:t.sessionId,tenantId:o,...t.data===void 0?{}:{data:t.data},...d===void 0?{}:{userId:d}};await(s?n.db.patch(r,s._id,m):n.db.insert(r,m));const f=c-I-Math.max(w,I),u=(await n.db.query(r).withIndex("byTenantRoomLastSeen",i=>i.eq("tenantId",o).eq("roomId",t.roomId)).order("asc").take(N)).filter(i=>i.lastSeen<=f);return await Promise.all(u.map(i=>n.db.delete(r,i._id))),{lastSeen:c}}),q=O.input({roomId:e.string()}).query(async({args:t,ctx:n})=>{const c=Date.now()-I,d=S(await n.auth.getIdentity()),s=(await n.db.query(r).withIndex("byTenantRoomLastSeen",a=>a.eq("tenantId",d).eq("roomId",t.roomId)).order("desc").take(T)).filter(a=>a.lastSeen>c),m=new Set,f=[];for(const a of s){const u=a.userId;if(u!==void 0){if(m.has(u))continue;m.add(u)}const i={lastSeen:a.lastSeen,roomId:a.roomId};u!==void 0&&(i.userId=u),a.data!==void 0&&(i.data=a.data),f.push(i)}return f}),g=U.input({roomId:e.string(),tenantId:e.string()}).mutation(async({args:t,ctx:n})=>{const c=Date.now()-I,d=await n.db.query(r).withIndex("byTenantRoomLastSeen",o=>o.eq("tenantId",t.tenantId).eq("roomId",t.roomId)).filter(o=>o.lastSeen<=c).collect();return await Promise.all(d.map(o=>n.db.delete(r,o._id))),{deleted:d.length}}),M=R(async(t,n)=>{const c=n.context?.roomId,d=n.context?.sessionId;if(typeof c!="string"||typeof d!="string")return;const o=S(await t.auth.getIdentity()),s=await t.db.query(r).withIndex("byTenantRoomSession",a=>a.eq("tenantId",o).eq("roomId",c).eq("sessionId",d)).first();if(!s)return;const m=n.userId??void 0;if((s.userId??void 0)!==m)return;if(w===0){await t.db.delete(r,s._id);return}const f=Math.min(s.lastSeen,Date.now()+w-I);await t.db.patch(r,s._id,{lastSeen:f})});return v(y,{extension:C,functions:{disconnect:M,heartbeat:_,listPresent:q,sweep:g}})};export{D as PRESENCE_DEFAULT_TTL_MS,r as PRESENCE_TABLE,H as definePresence,C as presenceExtension};
@@ -1 +1 @@
1
- import"./compose-middleware-BK9FlblN.mjs";import{c as i,a as s,b as o,g as m,k as l,m as t}from"./plugin-D0ogWCbA.mjs";export{i as composePluginMiddleware,s as defineComponent,o as definePlugin,m as defineSchemaExtension,l as installPlugins,t as mergeSchemaExtension};
1
+ import"./compose-middleware-BK9FlblN.mjs";import{c as i,a as s,b as o,g as m,k as l,m as t}from"./plugin-CyLqvCB9.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 s,f as i,h as n,i as l,j as f,v as o,l as t,n as r}from"./plugin-D0ogWCbA.mjs";export{d as defineAggregateIndex,s as defineRankIndex,i as defineSchema,n as defineTable,l as defineVectorIndex,f as indexFieldsFromSchema,o as validateGlobalVectors,t as validateIndexFields,r as validateTableModes};
1
+ import{d,e as s,f as i,h as n,i as l,j as f,v as o,l as t,n as r}from"./plugin-CyLqvCB9.mjs";export{d as defineAggregateIndex,s as defineRankIndex,i as defineSchema,n as defineTable,l as defineVectorIndex,f as indexFieldsFromSchema,o as validateGlobalVectors,t as validateIndexFields,r as validateTableModes};
@@ -0,0 +1 @@
1
+ import{LunoraError as s}from"@lunora/errors";import{c as W}from"./compose-middleware-BK9FlblN.mjs";import{v as S}from"@lunora/values";const C=["de","en","es","fr","it","nl","none","pt"],H=["native","portable"],Y=e=>H.includes(e),Z=e=>C.includes(e),ee=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}},K=e=>{if(e.kind==="literal")return ee(e);if(e.kind!=="optional")return e.kind;const t=e._meta?.inner;return t?K(t):e.kind},te=e=>`table "${e}" is both .global() and .ttl(). The TTL sweep is a shard's alarm deleting from that shard's own SQLite, and a global (D1/Hyperdrive) table's rows live outside every shard — so expired rows would never be deleted. Drop .ttl() and expire the rows from a cron, or keep the table shard-local.`,ne=(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.`,re=(e,t,n)=>e.some(r=>r.unique===!0&&r.fields.length===2&&r.fields.includes(t)&&r.fields.includes(n)),ae=e=>{const t=e?.kind==="id"?e._meta?.tableName:void 0;return typeof t=="string"?t:void 0},oe=(e,t,n,r)=>{const{from:a,table:c,to:d}=r.through,l=`defineSchema: relation "${n}" on table "${t}" (through "${c}")`,f=e[c];if(f===void 0)throw new s("INTERNAL",`${l} names a join table that is not declared`);if(e[r.table]===void 0)throw new s("INTERNAL",`${l} targets "${r.table}", which is not declared`);if(a===d)throw new s("INTERNAL",`${l}: "from" and "to" both name "${a}"; a link needs two different columns`);for(const[p,h]of[[a,t],[d,r.table]])if(ae(f.shape[p])!==h)throw new s("INTERNAL",`${l}: "${c}.${p}" must be a required v.id("${h}") column`);if(!re(f.indexes,a,d))throw new s("INTERNAL",`${l} needs a unique index over ("${a}", "${d}") on "${c}": ${JSON.stringify(`.index("by_${a}_${d}", ["${a}", "${d}"], { unique: true })`)}. Without it a repeated connect stores the same link twice.`);if(f.softDeleteMode!==void 0)throw new s("INTERNAL",`${l}: the join table is .softDelete(), so a disconnected pair could never be linked again (the unique index still holds the soft-deleted row). Hard-delete the soft-deleted rows of "${c}" first, or those links come back, then remove .softDelete() from it.`)},U=e=>{for(const[t,n]of Object.entries(e))for(const[r,a]of Object.entries(n.relationMap))a.through!==void 0&&oe(e,t,r,a)},F=16;function ie(e,t){return"through"in t?{kind:"many",table:e,through:{...t.through}}:{field:t.field,kind:"many",references:t.references??"_id",table:e}}const se={many:ie,one:(e,t)=>({field:t.field,kind:"one",onDelete:t.onDelete,references:t.references??"_id",table:e})},x=(e,t,n)=>({handler:n,op:t,timing:e}),de=()=>({afterDelete:e=>x("after","delete",e),afterInsert:e=>x("after","insert",e),afterUpdate:e=>x("after","update",e),beforeDelete:e=>x("before","delete",e),beforeInsert:e=>x("before","insert",e),beforeUpdate:e=>x("before","update",e)}),Q=(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}))},Te=e=>{const t={...e},n=[],r=[],a=[],c=[],d={},l=[],f={},p=de(),h=[];let m={kind:"root"},g=!1,R=!1,k=!1,M=!1,O=!1,D,T,I;const j=(i,o)=>{i in t||(t[i]=o)};let _,B;const q=i=>{if(m.kind!=="root"&&m.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.");m=i},u={aggregateIndex(i,o){const b=o?.op??"count";if(b!=="count"&&!o?.field)throw new s("INTERNAL",`aggregateIndex "${i}": op "${b}" requires a "field"`);return n.push({by:o?.by,field:o?.field,name:i,on:"",op:b,where:o?.where}),u},get aggregateIndexes(){return n},get externalSource(){return B},commitOrdered(){return g=!0,u},get commitOrderedMode(){return g},dropStalePatches(){return R=!0,u},get dropStalePatchesMode(){return R},externallyManaged(){return k=!0,u},geoIndex(i,o){return r.push({field:o.field,name:i,precision:o.precision}),u},get geoIndexes(){return r},global(i){return q({backend:i?.backend??"d1",kind:"global"}),u},get isExternallyManaged(){return k},get isPublic(){return O},index(i,o,b){return a.push({fields:o,name:i,unique:b?.unique??!1}),u},get indexes(){return a},memory(){return M=!0,u},get memoryMode(){return M},ownedBy(i){return D=i,u},get ownerField(){return D},public(){return O=!0,u},rankIndex(i,o){return c.push({name:i,on:"",partitionBy:o.partitionBy,sortBy:Q(i,o.sortBy),where:o.where}),u},get rankIndexes(){return c},get relationMap(){return d},relations(i){return Object.assign(d,i(se)),u},searchIndex(i,o){if(o.filterFields&&o.filterFields.length>F)throw new s("INTERNAL",`searchIndex "${i}": at most ${String(F)} filterFields are supported (got ${String(o.filterFields.length)})`);const{language:b}=o;if(b!==void 0&&!Z(b))throw new s("INTERNAL",`searchIndex "${i}": unknown language "${b}" (supported: ${C.join(", ")})`);const{strategy:w}=o;if(w!==void 0&&!Y(w))throw new s("INTERNAL",`searchIndex "${i}": unknown strategy "${w}" (supported: ${H.join(", ")})`);return l.push({field:o.field,filterFields:o.filterFields,language:o.language,name:i,staged:o.staged,strategy:o.strategy}),u},get searchIndexes(){return l},shape:t,shardBy(i){return q({field:i,kind:"shardBy"}),u},get shardMode(){return m},get softDeleteMode(){return T},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 B=i,k=!0,u},softDelete(i){const o=i?.field??"deletedAt";if(T={field:o},o===I)throw new s("INTERNAL",`defineTable: .softDelete() and .timestamps() both use "${o}"; give one of them another field`);return j(o,S.optional(S.number().nullable())),u},timestamps(i){const o=i?.field??"updatedAt";if(I!==void 0)throw new s("INTERNAL",`defineTable: .timestamps() was called twice ("${I}" and "${o}"); one table tracks one last-change column`);if(o===T?.field)throw new s("INTERNAL",`defineTable: .softDelete() and .timestamps() both use "${o}"; give one of them another field`);const b=t[o],w=b?._meta?.column;if(b!==void 0&&(b.kind!=="timestamp"||w?.onUpdateFn===void 0||w.defaultFn===void 0&&w.defaultValue===void 0))throw new s("INTERNAL",`defineTable: .timestamps() would add "${o}", but the table already declares it as something other than v.timestamp().defaultNow().$onUpdateFn(() => Date.now()); remove the column or declare it that way`);return I=o,j(o,S.timestamp().defaultNow().$onUpdateFn(()=>Date.now())),u},get triggerMap(){return f},triggers(i){return Object.assign(f,i(p)),u},ttl(i,o){return _={after:o?.after,field:i},u},get ttlPolicy(){return _},get vectorIndexes(){return h},vectorize(i,o){return h.push({dimensions:o.dimensions,embed:o.embed,field:i,metadata:o.metadata,metric:o.metric,model:o.model,name:o.index}),u}};return u},Se=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}),Le=(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}},Ae=(e,t)=>({name:e,on:t.table,partitionBy:t.partitionBy,sortBy:Q(e,t.sortBy),where:t.where}),v=e=>({...e,extend(t){return v(J(e,t))},jurisdiction(t,n){return v(e)},rls(t){return v({...e,rlsMode:t})}}),le=e=>{for(const[t,n]of Object.entries(e))for(const r of[...n.aggregateIndexes,...n.rankIndexes])r.on===""&&(r.on=t)},ce=(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)}},ue=e=>{if(e.cursor)return"cursor";if(e.reconcileEveryMs!==void 0)return"reconcileEveryMs";if(e.softDeleteColumn!==void 0)return"softDeleteColumn"},he=(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=ue(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).`)},fe=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.`);he(t,r)}}},me=["_commitSeq","_creationTime","_id"],P="_commitSeq",be=new Set(me),N=(e,t,n,r)=>{if(!(be.has(n)||n in r.shape))throw n.includes(".")?new s("INDEX_FIELD_NESTED_PATH",`defineSchema: table "${e}" index "${t}" indexes the nested path ${JSON.stringify(n)}, but indexes cover top-level columns only. Denormalise the value into its own column and index that instead.`):new s("INTERNAL",`defineSchema: table "${e}" index "${t}" names column "${n}" which is not in the table's shape`)},L=(e,t,n,r)=>{const a=new Set;for(const c of n){if(a.has(c.name))throw new s("INTERNAL",`defineSchema: table "${e}" declares ${t} "${c.name}" more than once`);a.add(c.name),r(c)}},z=e=>{for(const[t,n]of Object.entries(e))L(t,"index",n.indexes,r=>{for(const a of r.fields)N(t,r.name,a,n)}),L(t,"rank index",n.rankIndexes,r=>{for(const a of r.sortBy)N(t,r.name,a.field,n);for(const a of r.partitionBy??[])N(t,r.name,a,n)}),L(t,"geo index",n.geoIndexes,r=>{N(t,r.name,r.field,n)})},A=(e,t,n)=>{if(e.length===0)return;const r={};for(const a of e)r[t(a)]=n(a);return r},ge=e=>{const t=new Set(e.sortBy.map(n=>n.field));for(const n of e.partitionBy??[])t.add(n);return[...t]},Re=e=>{const t={};for(const[n,r]of Object.entries(e.tables)){const a=A(r.geoIndexes,l=>l.name,l=>[l.field]),c=A(r.indexes,l=>l.name,l=>l.fields),d=A(r.rankIndexes,l=>l.name,ge);(a||c||d)&&(t[n]={...a?{geo:a}:{},...c?{index:c}:{},...d?{rank:d}:{}})}return t},we=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(([c])=>c)?.[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.`)}},pe=e=>{for(const[t,n]of Object.entries(e))if(n.shardMode.kind==="global"){for(const[r,a]of Object.entries(n.shape))if(K(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.`)}},xe=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.`)},ye=e=>{for(const[t,n]of Object.entries(e))if(n.ttlPolicy!==void 0&&n.shardMode.kind==="global")throw new s("INTERNAL",`defineSchema: ${te(t)}`)},X=(e,t)=>{const n=[...Object.entries(e).flatMap(([r,a])=>a.vectorIndexes.map(c=>[r,c.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: ${ne(r,a)}`)},Ie=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(P))throw new s("INTERNAL",`defineSchema: table "${t}" index "${r.name}" names "${P}", 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.`)}},G=e=>{Ie(e),xe(e),pe(e),ye(e),we(e)},Me=(e,t={},n={},r={})=>(le(e),ce(e,n,r),fe(e),G(e),X(e,t),z(e),U(e),v({tables:e,vectorIndexes:t})),E=(e,t)=>`${e}_${t}`,y=(e,t,n)=>n.has(e)?E(t,e):e,V=(e,t)=>({...e,_meta:t}),$=(e,t)=>{const n=e._meta;if(n===void 0)return e;if(e.kind==="id"&&n.tableName!==void 0){const d=t(n.tableName);return d===n.tableName?e:V(e,{...n,tableName:d})}const r=d=>d===void 0?void 0:$(d,t),a={...n,...n.inner&&{inner:r(n.inner)},...n.keyValidator&&{keyValidator:r(n.keyValidator)},...n.valueValidator&&{valueValidator:r(n.valueValidator)},...n.members&&{members:n.members.map(d=>$(d,t))},...n.shape&&{shape:Object.fromEntries(Object.entries(n.shape).map(([d,l])=>[d,$(l,t)]))}};return a.inner===n.inner&&a.keyValidator===n.keyValidator&&a.valueValidator===n.valueValidator&&(a.members??[]).every((d,l)=>d===n.members?.[l])&&Object.entries(a.shape??{}).every(([d,l])=>l===n.shape?.[d])?e:V(e,a)},Ne=(e,t,n,r)=>{const a=E(t,r),c=h=>h===""?a:y(h,t,n),d={};for(const[h,m]of Object.entries(e.relationMap)){const g=y(m.table,t,n);d[h]=m.through===void 0?{...m,table:g}:{...m,table:g,through:{...m.through,table:y(m.through.table,t,n)}}}const l=e.aggregateIndexes.map(h=>({...h,on:c(h.on)})),f=e.rankIndexes.map(h=>({...h,on:c(h.on)})),p=Object.fromEntries(Object.entries(e.shape).map(([h,m])=>[h,$(m,g=>y(g,t,n))]));return{...e,aggregateIndexes:l,rankIndexes:f,relationMap:d,shape:p}},Oe=(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}:{}}},ve=((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}:{}}}),De=(e,t)=>({...ve(e,{...t.extension?{extension:t.extension}:{},...t.middleware?{middleware:t.middleware}:{}}),functions:t.functions??{}}),J=(e,t)=>{const{key:n}=t,r=new Set(Object.keys(t.tables)),a={...e.tables};for(const[d,l]of Object.entries(t.tables)){const f=E(n,d);if(Object.hasOwn(a,f))throw new s("INTERNAL",`defineSchema(...).extend("${n}"): table "${f}" already exists in the base schema — another extension with the same key already contributed it`);a[f]=Ne(l,n,r,d)}const c={...e.vectorIndexes};if(t.vectorIndexes)for(const[d,l]of Object.entries(t.vectorIndexes)){const f=E(n,d);if(Object.hasOwn(c,f))throw new s("INTERNAL",`defineSchema(...).extend("${n}"): vector index "${f}" already exists in the base schema — another extension with the same key already contributed it`);c[f]={...l,table:y(l.table,n,r)}}return z(a),G(a),X(a,c),U(a),{rlsMode:e.rlsMode,tables:a,vectorIndexes:c}},je=(e,t)=>{let n=e;for(const r of t)r.extension&&(n=J(n,r.extension));return n},_e=e=>{const t=e.map(n=>n.middleware).filter(n=>n!==void 0);return W(t)};export{De as a,ve as b,_e as c,Le as d,Ae as e,Me as f,Oe as g,Te as h,Se as i,Re as j,je as k,z as l,J as m,G as n,X as v};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/server",
3
- "version": "1.0.0-alpha.274",
3
+ "version": "1.0.0-alpha.276",
4
4
  "description": "Server primitives for Lunora: defineSchema, defineTable, query, mutation, and action",
5
5
  "keywords": [
6
6
  "backend",
@@ -73,7 +73,7 @@
73
73
  },
74
74
  "dependencies": {
75
75
  "@lunora/errors": ">=1.0.0-alpha.77 <2.0.0-0",
76
- "@lunora/scheduler": "^1.0.0-alpha.169",
76
+ "@lunora/scheduler": "^1.0.0-alpha.170",
77
77
  "@lunora/shard-engine": "^1.0.0-alpha.191",
78
78
  "@lunora/values": "^1.0.0-alpha.95",
79
79
  "@lunora/wire": "1.0.0-alpha.6",
@@ -1 +0,0 @@
1
- import{LunoraError as s}from"@lunora/errors";import{c as W}from"./compose-middleware-BK9FlblN.mjs";import{v as S}from"@lunora/values";const C=["de","en","es","fr","it","nl","none","pt"],H=["native","portable"],Y=e=>H.includes(e),Z=e=>C.includes(e),ee=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}},K=e=>{if(e.kind==="literal")return ee(e);if(e.kind!=="optional")return e.kind;const t=e._meta?.inner;return t?K(t):e.kind},te=e=>`table "${e}" is both .global() and .ttl(). The TTL sweep is a shard's alarm deleting from that shard's own SQLite, and a global (D1/Hyperdrive) table's rows live outside every shard — so expired rows would never be deleted. Drop .ttl() and expire the rows from a cron, or keep the table shard-local.`,ne=(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.`,re=(e,t,n)=>e.some(r=>r.unique===!0&&r.fields.length===2&&r.fields.includes(t)&&r.fields.includes(n)),ae=e=>{const t=e?.kind==="id"?e._meta?.tableName:void 0;return typeof t=="string"?t:void 0},oe=(e,t,n,r)=>{const{from:a,table:c,to:d}=r.through,l=`defineSchema: relation "${n}" on table "${t}" (through "${c}")`,f=e[c];if(f===void 0)throw new s("INTERNAL",`${l} names a join table that is not declared`);if(e[r.table]===void 0)throw new s("INTERNAL",`${l} targets "${r.table}", which is not declared`);if(a===d)throw new s("INTERNAL",`${l}: "from" and "to" both name "${a}"; a link needs two different columns`);for(const[p,h]of[[a,t],[d,r.table]])if(ae(f.shape[p])!==h)throw new s("INTERNAL",`${l}: "${c}.${p}" must be a required v.id("${h}") column`);if(!re(f.indexes,a,d))throw new s("INTERNAL",`${l} needs a unique index over ("${a}", "${d}") on "${c}": ${JSON.stringify(`.index("by_${a}_${d}", ["${a}", "${d}"], { unique: true })`)}. Without it a repeated connect stores the same link twice.`)},U=e=>{for(const[t,n]of Object.entries(e))for(const[r,a]of Object.entries(n.relationMap))a.through!==void 0&&oe(e,t,r,a)},F=16;function ie(e,t){return"through"in t?{kind:"many",table:e,through:{...t.through}}:{field:t.field,kind:"many",references:t.references??"_id",table:e}}const se={many:ie,one:(e,t)=>({field:t.field,kind:"one",onDelete:t.onDelete,references:t.references??"_id",table:e})},x=(e,t,n)=>({handler:n,op:t,timing:e}),de=()=>({afterDelete:e=>x("after","delete",e),afterInsert:e=>x("after","insert",e),afterUpdate:e=>x("after","update",e),beforeDelete:e=>x("before","delete",e),beforeInsert:e=>x("before","insert",e),beforeUpdate:e=>x("before","update",e)}),Q=(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}))},Te=e=>{const t={...e},n=[],r=[],a=[],c=[],d={},l=[],f={},p=de(),h=[];let m={kind:"root"},g=!1,R=!1,k=!1,M=!1,O=!1,D,T,I;const j=(i,o)=>{i in t||(t[i]=o)};let _,B;const q=i=>{if(m.kind!=="root"&&m.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.");m=i},u={aggregateIndex(i,o){const b=o?.op??"count";if(b!=="count"&&!o?.field)throw new s("INTERNAL",`aggregateIndex "${i}": op "${b}" requires a "field"`);return n.push({by:o?.by,field:o?.field,name:i,on:"",op:b,where:o?.where}),u},get aggregateIndexes(){return n},get externalSource(){return B},commitOrdered(){return g=!0,u},get commitOrderedMode(){return g},dropStalePatches(){return R=!0,u},get dropStalePatchesMode(){return R},externallyManaged(){return k=!0,u},geoIndex(i,o){return r.push({field:o.field,name:i,precision:o.precision}),u},get geoIndexes(){return r},global(i){return q({backend:i?.backend??"d1",kind:"global"}),u},get isExternallyManaged(){return k},get isPublic(){return O},index(i,o,b){return a.push({fields:o,name:i,unique:b?.unique??!1}),u},get indexes(){return a},memory(){return M=!0,u},get memoryMode(){return M},ownedBy(i){return D=i,u},get ownerField(){return D},public(){return O=!0,u},rankIndex(i,o){return c.push({name:i,on:"",partitionBy:o.partitionBy,sortBy:Q(i,o.sortBy),where:o.where}),u},get rankIndexes(){return c},get relationMap(){return d},relations(i){return Object.assign(d,i(se)),u},searchIndex(i,o){if(o.filterFields&&o.filterFields.length>F)throw new s("INTERNAL",`searchIndex "${i}": at most ${String(F)} filterFields are supported (got ${String(o.filterFields.length)})`);const{language:b}=o;if(b!==void 0&&!Z(b))throw new s("INTERNAL",`searchIndex "${i}": unknown language "${b}" (supported: ${C.join(", ")})`);const{strategy:w}=o;if(w!==void 0&&!Y(w))throw new s("INTERNAL",`searchIndex "${i}": unknown strategy "${w}" (supported: ${H.join(", ")})`);return l.push({field:o.field,filterFields:o.filterFields,language:o.language,name:i,staged:o.staged,strategy:o.strategy}),u},get searchIndexes(){return l},shape:t,shardBy(i){return q({field:i,kind:"shardBy"}),u},get shardMode(){return m},get softDeleteMode(){return T},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 B=i,k=!0,u},softDelete(i){const o=i?.field??"deletedAt";if(T={field:o},o===I)throw new s("INTERNAL",`defineTable: .softDelete() and .timestamps() both use "${o}"; give one of them another field`);return j(o,S.optional(S.number().nullable())),u},timestamps(i){const o=i?.field??"updatedAt";if(I!==void 0)throw new s("INTERNAL",`defineTable: .timestamps() was called twice ("${I}" and "${o}"); one table tracks one last-change column`);if(o===T?.field)throw new s("INTERNAL",`defineTable: .softDelete() and .timestamps() both use "${o}"; give one of them another field`);const b=t[o],w=b?._meta?.column;if(b!==void 0&&(b.kind!=="timestamp"||w?.onUpdateFn===void 0||w.defaultFn===void 0&&w.defaultValue===void 0))throw new s("INTERNAL",`defineTable: .timestamps() would add "${o}", but the table already declares it as something other than v.timestamp().defaultNow().$onUpdateFn(() => Date.now()); remove the column or declare it that way`);return I=o,j(o,S.timestamp().defaultNow().$onUpdateFn(()=>Date.now())),u},get triggerMap(){return f},triggers(i){return Object.assign(f,i(p)),u},ttl(i,o){return _={after:o?.after,field:i},u},get ttlPolicy(){return _},get vectorIndexes(){return h},vectorize(i,o){return h.push({dimensions:o.dimensions,embed:o.embed,field:i,metadata:o.metadata,metric:o.metric,model:o.model,name:o.index}),u}};return u},Se=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}),Le=(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}},Ae=(e,t)=>({name:e,on:t.table,partitionBy:t.partitionBy,sortBy:Q(e,t.sortBy),where:t.where}),v=e=>({...e,extend(t){return v(J(e,t))},jurisdiction(t,n){return v(e)},rls(t){return v({...e,rlsMode:t})}}),le=e=>{for(const[t,n]of Object.entries(e))for(const r of[...n.aggregateIndexes,...n.rankIndexes])r.on===""&&(r.on=t)},ce=(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)}},ue=e=>{if(e.cursor)return"cursor";if(e.reconcileEveryMs!==void 0)return"reconcileEveryMs";if(e.softDeleteColumn!==void 0)return"softDeleteColumn"},he=(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=ue(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).`)},fe=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.`);he(t,r)}}},me=["_commitSeq","_creationTime","_id"],P="_commitSeq",be=new Set(me),N=(e,t,n,r)=>{if(!(be.has(n)||n in r.shape))throw n.includes(".")?new s("INDEX_FIELD_NESTED_PATH",`defineSchema: table "${e}" index "${t}" indexes the nested path ${JSON.stringify(n)}, but indexes cover top-level columns only. Denormalise the value into its own column and index that instead.`):new s("INTERNAL",`defineSchema: table "${e}" index "${t}" names column "${n}" which is not in the table's shape`)},L=(e,t,n,r)=>{const a=new Set;for(const c of n){if(a.has(c.name))throw new s("INTERNAL",`defineSchema: table "${e}" declares ${t} "${c.name}" more than once`);a.add(c.name),r(c)}},z=e=>{for(const[t,n]of Object.entries(e))L(t,"index",n.indexes,r=>{for(const a of r.fields)N(t,r.name,a,n)}),L(t,"rank index",n.rankIndexes,r=>{for(const a of r.sortBy)N(t,r.name,a.field,n);for(const a of r.partitionBy??[])N(t,r.name,a,n)}),L(t,"geo index",n.geoIndexes,r=>{N(t,r.name,r.field,n)})},A=(e,t,n)=>{if(e.length===0)return;const r={};for(const a of e)r[t(a)]=n(a);return r},ge=e=>{const t=new Set(e.sortBy.map(n=>n.field));for(const n of e.partitionBy??[])t.add(n);return[...t]},Re=e=>{const t={};for(const[n,r]of Object.entries(e.tables)){const a=A(r.geoIndexes,l=>l.name,l=>[l.field]),c=A(r.indexes,l=>l.name,l=>l.fields),d=A(r.rankIndexes,l=>l.name,ge);(a||c||d)&&(t[n]={...a?{geo:a}:{},...c?{index:c}:{},...d?{rank:d}:{}})}return t},we=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(([c])=>c)?.[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.`)}},pe=e=>{for(const[t,n]of Object.entries(e))if(n.shardMode.kind==="global"){for(const[r,a]of Object.entries(n.shape))if(K(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.`)}},xe=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.`)},ye=e=>{for(const[t,n]of Object.entries(e))if(n.ttlPolicy!==void 0&&n.shardMode.kind==="global")throw new s("INTERNAL",`defineSchema: ${te(t)}`)},X=(e,t)=>{const n=[...Object.entries(e).flatMap(([r,a])=>a.vectorIndexes.map(c=>[r,c.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: ${ne(r,a)}`)},Ie=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(P))throw new s("INTERNAL",`defineSchema: table "${t}" index "${r.name}" names "${P}", 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.`)}},G=e=>{Ie(e),xe(e),pe(e),ye(e),we(e)},Me=(e,t={},n={},r={})=>(le(e),ce(e,n,r),fe(e),G(e),X(e,t),z(e),U(e),v({tables:e,vectorIndexes:t})),E=(e,t)=>`${e}_${t}`,y=(e,t,n)=>n.has(e)?E(t,e):e,V=(e,t)=>({...e,_meta:t}),$=(e,t)=>{const n=e._meta;if(n===void 0)return e;if(e.kind==="id"&&n.tableName!==void 0){const d=t(n.tableName);return d===n.tableName?e:V(e,{...n,tableName:d})}const r=d=>d===void 0?void 0:$(d,t),a={...n,...n.inner&&{inner:r(n.inner)},...n.keyValidator&&{keyValidator:r(n.keyValidator)},...n.valueValidator&&{valueValidator:r(n.valueValidator)},...n.members&&{members:n.members.map(d=>$(d,t))},...n.shape&&{shape:Object.fromEntries(Object.entries(n.shape).map(([d,l])=>[d,$(l,t)]))}};return a.inner===n.inner&&a.keyValidator===n.keyValidator&&a.valueValidator===n.valueValidator&&(a.members??[]).every((d,l)=>d===n.members?.[l])&&Object.entries(a.shape??{}).every(([d,l])=>l===n.shape?.[d])?e:V(e,a)},Ne=(e,t,n,r)=>{const a=E(t,r),c=h=>h===""?a:y(h,t,n),d={};for(const[h,m]of Object.entries(e.relationMap)){const g=y(m.table,t,n);d[h]=m.through===void 0?{...m,table:g}:{...m,table:g,through:{...m.through,table:y(m.through.table,t,n)}}}const l=e.aggregateIndexes.map(h=>({...h,on:c(h.on)})),f=e.rankIndexes.map(h=>({...h,on:c(h.on)})),p=Object.fromEntries(Object.entries(e.shape).map(([h,m])=>[h,$(m,g=>y(g,t,n))]));return{...e,aggregateIndexes:l,rankIndexes:f,relationMap:d,shape:p}},Oe=(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}:{}}},ve=((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}:{}}}),De=(e,t)=>({...ve(e,{...t.extension?{extension:t.extension}:{},...t.middleware?{middleware:t.middleware}:{}}),functions:t.functions??{}}),J=(e,t)=>{const{key:n}=t,r=new Set(Object.keys(t.tables)),a={...e.tables};for(const[d,l]of Object.entries(t.tables)){const f=E(n,d);if(Object.hasOwn(a,f))throw new s("INTERNAL",`defineSchema(...).extend("${n}"): table "${f}" already exists in the base schema — another extension with the same key already contributed it`);a[f]=Ne(l,n,r,d)}const c={...e.vectorIndexes};if(t.vectorIndexes)for(const[d,l]of Object.entries(t.vectorIndexes)){const f=E(n,d);if(Object.hasOwn(c,f))throw new s("INTERNAL",`defineSchema(...).extend("${n}"): vector index "${f}" already exists in the base schema — another extension with the same key already contributed it`);c[f]={...l,table:y(l.table,n,r)}}return z(a),G(a),X(a,c),U(a),{rlsMode:e.rlsMode,tables:a,vectorIndexes:c}},je=(e,t)=>{let n=e;for(const r of t)r.extension&&(n=J(n,r.extension));return n},_e=e=>{const t=e.map(n=>n.middleware).filter(n=>n!==void 0);return W(t)};export{De as a,ve as b,_e as c,Le as d,Ae as e,Me as f,Oe as g,Te as h,Se as i,Re as j,je as k,z as l,J as m,G as n,X as v};