@lunora/server 1.0.0-alpha.93 → 1.0.0-alpha.94

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
@@ -85,8 +85,14 @@ interface QueryBuilder<Context, Args extends ArgsValidator, Output = undefined>
85
85
  * async generator (or any function returning an `AsyncIterable<R>`) that
86
86
  * yields one chunk per server-pushed frame. The third `signal` argument is
87
87
  * tripped when the client cancels — break out of the loop or check
88
- * `signal.aborted` between yields. `.output()` does not apply: per-chunk
89
- * validation is opt-in via the handler itself.
88
+ * `signal.aborted` between yields.
89
+ *
90
+ * **Unavailable after `.output()`, deliberately.** Chunks are yielded as-is —
91
+ * there is no per-chunk validation — so `.output(...).stream(...)` used to
92
+ * compile and quietly enforce nothing, which is worse than not offering the
93
+ * combination: the author asked for validation and was told yes. Declaring an
94
+ * output on a stream is now a type error rather than a false promise. Validate
95
+ * inside the handler, or return the whole payload from `.query()` instead.
90
96
  *
91
97
  * Pass `{ durable: true }` to make the run outlive the socket that opened
92
98
  * it: chunks are persisted as they are produced, so a reload resumes the
@@ -94,11 +100,11 @@ interface QueryBuilder<Context, Args extends ArgsValidator, Output = undefined>
94
100
  * second client with the same arguments attaches to the same transcript.
95
101
  * That is what an LLM response wants; a progress ticker does not need it.
96
102
  */
97
- stream: <R>(handler: (options: {
103
+ stream: [Output] extends [undefined] ? <R>(handler: (options: {
98
104
  args: InferArgs<Args>;
99
105
  ctx: Context;
100
106
  signal: AbortSignal;
101
- }) => AsyncGenerator<R, void, void> | AsyncIterable<R>, options?: StreamOptions) => RegisteredStream<Args, R>;
107
+ }) => AsyncGenerator<R, void, void> | AsyncIterable<R>, options?: StreamOptions) => RegisteredStream<Args, R> : never;
102
108
  use: <ContextOut>(middleware: Middleware<Context, ContextOut>) => QueryBuilder<ContextOut, Args, Output>;
103
109
  /**
104
110
  * Mark this query as paid. The origin worker answers an unpaid client RPC
package/dist/index.d.ts CHANGED
@@ -85,8 +85,14 @@ interface QueryBuilder<Context, Args extends ArgsValidator, Output = undefined>
85
85
  * async generator (or any function returning an `AsyncIterable<R>`) that
86
86
  * yields one chunk per server-pushed frame. The third `signal` argument is
87
87
  * tripped when the client cancels — break out of the loop or check
88
- * `signal.aborted` between yields. `.output()` does not apply: per-chunk
89
- * validation is opt-in via the handler itself.
88
+ * `signal.aborted` between yields.
89
+ *
90
+ * **Unavailable after `.output()`, deliberately.** Chunks are yielded as-is —
91
+ * there is no per-chunk validation — so `.output(...).stream(...)` used to
92
+ * compile and quietly enforce nothing, which is worse than not offering the
93
+ * combination: the author asked for validation and was told yes. Declaring an
94
+ * output on a stream is now a type error rather than a false promise. Validate
95
+ * inside the handler, or return the whole payload from `.query()` instead.
90
96
  *
91
97
  * Pass `{ durable: true }` to make the run outlive the socket that opened
92
98
  * it: chunks are persisted as they are produced, so a reload resumes the
@@ -94,11 +100,11 @@ interface QueryBuilder<Context, Args extends ArgsValidator, Output = undefined>
94
100
  * second client with the same arguments attaches to the same transcript.
95
101
  * That is what an LLM response wants; a progress ticker does not need it.
96
102
  */
97
- stream: <R>(handler: (options: {
103
+ stream: [Output] extends [undefined] ? <R>(handler: (options: {
98
104
  args: InferArgs<Args>;
99
105
  ctx: Context;
100
106
  signal: AbortSignal;
101
- }) => AsyncGenerator<R, void, void> | AsyncIterable<R>, options?: StreamOptions) => RegisteredStream<Args, R>;
107
+ }) => AsyncGenerator<R, void, void> | AsyncIterable<R>, options?: StreamOptions) => RegisteredStream<Args, R> : never;
102
108
  use: <ContextOut>(middleware: Middleware<Context, ContextOut>) => QueryBuilder<ContextOut, Args, Output>;
103
109
  /**
104
110
  * Mark this query as paid. The origin worker answers an unpaid client RPC
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-C16AYOi9.mjs";import{initLunora as m}from"./packem_shared/initLunora-B2sfmFJ6.mjs";import{createSecrets as p}from"./packem_shared/createSecrets-CyrEddTF.mjs";import{flushDeferredDeletes as c,withDeferredDeletes as l}from"./packem_shared/flushDeferredDeletes-DEJXlhop.mjs";import{DOCUMENT_HISTORY_REDACTED_FIELDS as u,DOCUMENT_HISTORY_TABLE as S,defineDocumentHistory as T,documentHistoryExtension as h}from"./packem_shared/DOCUMENT_HISTORY_REDACTED_FIELDS-BZxXxU_P.mjs";import{LunoraEnvError as g,defineEnv as R,redactSecrets as _}from"./packem_shared/LunoraEnvError-_BakoYQ3.mjs";import{LunoraError as L}from"./packem_shared/LunoraError-DcKdk9Ti.mjs";import{bindOrm as I,bindTableFacade as y}from"./packem_shared/bindOrm-lWdeDi9P.mjs";import{httpAction as P,httpRoute as b,httpRouter as F,isSafeHeaderValue as O,serveStorageObject as H}from"./packem_shared/httpAction-D3b9-YiY.mjs";import{defineIdentity as U}from"./packem_shared/defineIdentity-DwkNKwYa.mjs";import{onConnect as v,onDisconnect as B,onShardInit as V}from"./packem_shared/onConnect-BLRoOpv2.mjs";import{DEFAULT_LIMIT as j,DEFAULT_MAX_LIMIT as W,clampLimit as Y,defineListArgs as J}from"./packem_shared/DEFAULT_LIMIT-DC-M6faS.mjs";import{defineMigration as Q}from"./packem_shared/defineMigration-7GI9Qbtd.mjs";import{defineMutator as q}from"./packem_shared/defineMutator-DKy8UtbB.mjs";import{c as G,d as Z,a as $,b as ee,e as oe,f as re,g as te,h as ne,i as ie,j as ae,k as fe,m as se}from"./packem_shared/plugin-DfuRhJS1.mjs";import{PRESENCE_DEFAULT_TTL_MS as de,PRESENCE_TABLE as pe,definePresence as xe,presenceExtension as ce}from"./packem_shared/PRESENCE_DEFAULT_TTL_MS-B9-YC21L.mjs";import{protectPublic as Ee}from"./packem_shared/protectPublic-Bo4G9xaV.mjs";import{onQueryChange as Se}from"./packem_shared/onQueryChange-pRK6Dh3g.mjs";import{defineShape as he}from"./packem_shared/defineShape-DYxbNl5W.mjs";import{anyApi as ge}from"./types.mjs";import{cronJobs as _e}from"@lunora/scheduler";import{ValidationError as Le,v as Ce}from"@lunora/values";import{allowAll as ye,deny as Me,isDeny as Pe,toWhereInput as be}from"./packem_shared/allowAll-DkRAgItV.mjs";import{asBucketStorage as Oe}from"./packem_shared/asBucketStorage-BthCnWop.mjs";import{buildMaskRegistry as Ne}from"./packem_shared/buildMaskRegistry-72SL8fJn.mjs";import{buildRlsReadRegistry as ke,composeShapeReadWhere as ve}from"./packem_shared/buildRlsReadRegistry-Ct60PLD-.mjs";import{createPolicyDsl as Ve,definePermission as we,definePolicies as je,definePolicy as We,defineRole as Ye}from"./packem_shared/createPolicyDsl-DNfByAUX.mjs";import{defineStorageRule as Ke,defineStorageRules as Qe}from"./packem_shared/defineStorageRule-BvxHVq3b.mjs";import{mask as qe}from"./packem_shared/mask-NVloFLLY.mjs";import{r as Ge}from"./packem_shared/middleware-EloVU9X1.mjs";import{storageRules as $e}from"./packem_shared/storageRules-91NHMDL6.mjs";const e="0.0.0";export{t as ACTION_CACHE_DEFAULT_TTL_MS,n as ACTION_CACHE_TABLE,j as DEFAULT_LIMIT,W as DEFAULT_MAX_LIMIT,u as DOCUMENT_HISTORY_REDACTED_FIELDS,S as DOCUMENT_HISTORY_TABLE,g as LunoraEnvError,L as LunoraError,de as PRESENCE_DEFAULT_TTL_MS,pe as PRESENCE_TABLE,e as VERSION,Le as ValidationError,i as actionCacheExtension,ye as allowAll,ge as anyApi,Oe as asBucketStorage,I as bindOrm,y as bindTableFacade,Ne as buildMaskRegistry,ke as buildRlsReadRegistry,a as cacheKeyFor,Y as clampLimit,G as composePluginMiddleware,ve as composeShapeReadWhere,Ve as createPolicyDsl,p as createSecrets,_e as cronJobs,f as defineActionCache,Z as defineAggregateIndex,$ as defineComponent,T as defineDocumentHistory,R as defineEnv,U as defineIdentity,J as defineListArgs,Q as defineMigration,q as defineMutator,we as definePermission,ee as definePlugin,je as definePolicies,We as definePolicy,xe as definePresence,oe as defineRankIndex,Ye as defineRole,re as defineSchema,te as defineSchemaExtension,he as defineShape,Ke as defineStorageRule,Qe as defineStorageRules,ne as defineTable,ie as defineVectorIndex,Me as deny,h as documentHistoryExtension,c as flushDeferredDeletes,P as httpAction,b as httpRoute,F as httpRouter,ae as indexFieldsFromSchema,m as initLunora,fe as installPlugins,Pe as isDeny,O as isSafeHeaderValue,qe as mask,se as mergeSchemaExtension,v as onConnect,B as onDisconnect,Se as onQueryChange,V as onShardInit,ce as presenceExtension,Ee as protectPublic,_ as redactSecrets,Ge as rls,H as serveStorageObject,$e as storageRules,be as toWhereInput,Ce as v,l as withDeferredDeletes};
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-BG6A6rHA.mjs";import{initLunora as m}from"./packem_shared/initLunora-BxNkWYTz.mjs";import{createSecrets as p}from"./packem_shared/createSecrets-CyrEddTF.mjs";import{flushDeferredDeletes as c,withDeferredDeletes as l}from"./packem_shared/flushDeferredDeletes-DEJXlhop.mjs";import{DOCUMENT_HISTORY_REDACTED_FIELDS as u,DOCUMENT_HISTORY_TABLE as S,defineDocumentHistory as T,documentHistoryExtension as h}from"./packem_shared/DOCUMENT_HISTORY_REDACTED_FIELDS-CXOIUOBE.mjs";import{LunoraEnvError as g,defineEnv as R,redactSecrets as _}from"./packem_shared/LunoraEnvError-_BakoYQ3.mjs";import{LunoraError as L}from"./packem_shared/LunoraError-DcKdk9Ti.mjs";import{bindOrm as I,bindTableFacade as y}from"./packem_shared/bindOrm-lWdeDi9P.mjs";import{httpAction as P,httpRoute as b,httpRouter as F,isSafeHeaderValue as O,serveStorageObject as H}from"./packem_shared/httpAction-DEN_78Kj.mjs";import{defineIdentity as U}from"./packem_shared/defineIdentity-DwkNKwYa.mjs";import{onConnect as v,onDisconnect as B,onShardInit as V}from"./packem_shared/onConnect-BLRoOpv2.mjs";import{DEFAULT_LIMIT as j,DEFAULT_MAX_LIMIT as W,clampLimit as Y,defineListArgs as J}from"./packem_shared/DEFAULT_LIMIT-DC-M6faS.mjs";import{defineMigration as Q}from"./packem_shared/defineMigration-7GI9Qbtd.mjs";import{defineMutator as q}from"./packem_shared/defineMutator-DKy8UtbB.mjs";import{c as G,d as Z,a as $,b as ee,e as oe,f as re,g as te,h as ne,i as ie,j as ae,k as fe,m as se}from"./packem_shared/plugin-DfuRhJS1.mjs";import{PRESENCE_DEFAULT_TTL_MS as de,PRESENCE_TABLE as pe,definePresence as xe,presenceExtension as ce}from"./packem_shared/PRESENCE_DEFAULT_TTL_MS-B6z9BcPN.mjs";import{protectPublic as Ee}from"./packem_shared/protectPublic-Bo4G9xaV.mjs";import{onQueryChange as Se}from"./packem_shared/onQueryChange-pRK6Dh3g.mjs";import{defineShape as he}from"./packem_shared/defineShape-DYxbNl5W.mjs";import{anyApi as ge}from"./types.mjs";import{cronJobs as _e}from"@lunora/scheduler";import{ValidationError as Le,v as Ce}from"@lunora/values";import{allowAll as ye,deny as Me,isDeny as Pe,toWhereInput as be}from"./packem_shared/allowAll-DkRAgItV.mjs";import{asBucketStorage as Oe}from"./packem_shared/asBucketStorage-BthCnWop.mjs";import{buildMaskRegistry as Ne}from"./packem_shared/buildMaskRegistry-72SL8fJn.mjs";import{buildRlsReadRegistry as ke,composeShapeReadWhere as ve}from"./packem_shared/buildRlsReadRegistry-Ct60PLD-.mjs";import{createPolicyDsl as Ve,definePermission as we,definePolicies as je,definePolicy as We,defineRole as Ye}from"./packem_shared/createPolicyDsl-DNfByAUX.mjs";import{defineStorageRule as Ke,defineStorageRules as Qe}from"./packem_shared/defineStorageRule-BvxHVq3b.mjs";import{mask as qe}from"./packem_shared/mask-NVloFLLY.mjs";import{r as Ge}from"./packem_shared/middleware-EloVU9X1.mjs";import{storageRules as $e}from"./packem_shared/storageRules-91NHMDL6.mjs";const e="0.0.0";export{t as ACTION_CACHE_DEFAULT_TTL_MS,n as ACTION_CACHE_TABLE,j as DEFAULT_LIMIT,W as DEFAULT_MAX_LIMIT,u as DOCUMENT_HISTORY_REDACTED_FIELDS,S as DOCUMENT_HISTORY_TABLE,g as LunoraEnvError,L as LunoraError,de as PRESENCE_DEFAULT_TTL_MS,pe as PRESENCE_TABLE,e as VERSION,Le as ValidationError,i as actionCacheExtension,ye as allowAll,ge as anyApi,Oe as asBucketStorage,I as bindOrm,y as bindTableFacade,Ne as buildMaskRegistry,ke as buildRlsReadRegistry,a as cacheKeyFor,Y as clampLimit,G as composePluginMiddleware,ve as composeShapeReadWhere,Ve as createPolicyDsl,p as createSecrets,_e as cronJobs,f as defineActionCache,Z as defineAggregateIndex,$ as defineComponent,T as defineDocumentHistory,R as defineEnv,U as defineIdentity,J as defineListArgs,Q as defineMigration,q as defineMutator,we as definePermission,ee as definePlugin,je as definePolicies,We as definePolicy,xe as definePresence,oe as defineRankIndex,Ye as defineRole,re as defineSchema,te as defineSchemaExtension,he as defineShape,Ke as defineStorageRule,Qe as defineStorageRules,ne as defineTable,ie as defineVectorIndex,Me as deny,h as documentHistoryExtension,c as flushDeferredDeletes,P as httpAction,b as httpRoute,F as httpRouter,ae as indexFieldsFromSchema,m as initLunora,fe as installPlugins,Pe as isDeny,O as isSafeHeaderValue,qe as mask,se as mergeSchemaExtension,v as onConnect,B as onDisconnect,Se as onQueryChange,V as onShardInit,ce as presenceExtension,Ee as protectPublic,_ as redactSecrets,Ge as rls,H as serveStorageObject,$e as storageRules,be as toWhereInput,Ce as v,l as withDeferredDeletes};
@@ -1 +1 @@
1
- import{isLunoraError as S}from"@lunora/errors";import{v as d}from"@lunora/values";import{e as f,d as U}from"./wire-codec-hZHn-Ooo.mjs";import{s as D}from"./stable-key-B_BlboiY.mjs";import{initLunora as F}from"./initLunora-B2sfmFJ6.mjs";import{g as k,h as q,a as B}from"./plugin-DfuRhJS1.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{e as f,d as U}from"./wire-codec-hZHn-Ooo.mjs";import{s as D}from"./stable-key-B_BlboiY.mjs";import{initLunora as F}from"./initLunora-BxNkWYTz.mjs";import{g as k,h as q,a as B}from"./plugin-DfuRhJS1.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 A,e as h}from"./wire-codec-hZHn-Ooo.mjs";import{initLunora as v}from"./initLunora-B2sfmFJ6.mjs";import{g as x,h as R,a as U}from"./plugin-DfuRhJS1.mjs";const H=2160*60*60*1e3,q=64*1024,E=200,C=64,F=512,y=16,L=["_commitSeq","seq"],B=["accessToken","apiKey","backupCodes","clientSecret","hashedPassword","password","privateKey","refreshToken","secret","totpSecret"],p="documentHistory",I="versions",l=`${p}_${I}`,P=x(p,{tables:{[I]: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:j}=v.dataModel().create(),X=(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)):q,D=new Set([...B,...d.redact??[]]);let b=0;const M=()=>(b+=1,b),m=(e,t=0)=>{if(Array.isArray(e))return t>=y?void 0:e.map(o=>m(o,t+1));if(typeof e!="object"||e===null||Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null)return e;if(!(t>=y))return Object.fromEntries(Object.entries(e).filter(([o])=>!D.has(o)).map(([o,i])=>[o,m(i,t+1)]))},f=e=>{if(e===void 0)return;const t=JSON.stringify(h(m(e)));return new TextEncoder().encode(t).length>_?void 0:t},u=async(e,t)=>{const o=f(t.doc),i=f(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:M(),tableName:t.tableName,...n?{truncated:!0}:{},...o===void 0?{}:{doc:o},...i===void 0?{}:{previous:i}})},S=e=>({documentHistoryDelete:e.afterDelete(async(t,o)=>u(t,{documentId:o.id,op:"delete",previous:o.previous,tableName:o.table})),documentHistoryInsert:e.afterInsert(async(t,o)=>u(t,{doc:o.doc,documentId:o.id,op:"insert",tableName:o.table})),documentHistoryUpdate:e.afterUpdate(async(t,o)=>u(t,{doc:o.doc,documentId:o.id,op:"update",previous:o.previous,tableName:o.table}))}),N=j.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.max(1,Math.floor(e.limit)):E,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,a)=>{for(const c of L){const s=(a[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:A(JSON.parse(n.doc))},...n.previous===void 0?{}:{previous:A(JSON.parse(n.previous))},...n.truncated===!0?{truncated:!0}:{}}))}),O=Y.input({limit:r.optional(r.number())}).mutation(async({args:e,ctx:t})=>{const o=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 a=0;a<C&&n<i;a+=1){const c=await t.db.query(l).withIndex("byRecordedAt",s=>s.lt("recordedAt",o)).order("asc").take(Math.min(E,i-n));if(c.length===0)return{deleted:n};await Promise.all(c.map(async s=>t.db.delete(s._id))),n+=c.length}return{deleted:n}});return{...U(p,{extension:P,functions:{listForDocument:N,vacuum:O}}),record:S}};export{B as DOCUMENT_HISTORY_REDACTED_FIELDS,l as DOCUMENT_HISTORY_TABLE,X as defineDocumentHistory,P as documentHistoryExtension};
1
+ import{v as r}from"@lunora/values";import{d as A,e as h}from"./wire-codec-hZHn-Ooo.mjs";import{initLunora as v}from"./initLunora-BxNkWYTz.mjs";import{g as x,h as R,a as U}from"./plugin-DfuRhJS1.mjs";const H=2160*60*60*1e3,q=64*1024,E=200,C=64,F=512,y=16,L=["_commitSeq","seq"],B=["accessToken","apiKey","backupCodes","clientSecret","hashedPassword","password","privateKey","refreshToken","secret","totpSecret"],p="documentHistory",I="versions",l=`${p}_${I}`,P=x(p,{tables:{[I]: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:j}=v.dataModel().create(),X=(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)):q,D=new Set([...B,...d.redact??[]]);let b=0;const M=()=>(b+=1,b),m=(e,t=0)=>{if(Array.isArray(e))return t>=y?void 0:e.map(o=>m(o,t+1));if(typeof e!="object"||e===null||Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null)return e;if(!(t>=y))return Object.fromEntries(Object.entries(e).filter(([o])=>!D.has(o)).map(([o,i])=>[o,m(i,t+1)]))},f=e=>{if(e===void 0)return;const t=JSON.stringify(h(m(e)));return new TextEncoder().encode(t).length>_?void 0:t},u=async(e,t)=>{const o=f(t.doc),i=f(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:M(),tableName:t.tableName,...n?{truncated:!0}:{},...o===void 0?{}:{doc:o},...i===void 0?{}:{previous:i}})},S=e=>({documentHistoryDelete:e.afterDelete(async(t,o)=>u(t,{documentId:o.id,op:"delete",previous:o.previous,tableName:o.table})),documentHistoryInsert:e.afterInsert(async(t,o)=>u(t,{doc:o.doc,documentId:o.id,op:"insert",tableName:o.table})),documentHistoryUpdate:e.afterUpdate(async(t,o)=>u(t,{doc:o.doc,documentId:o.id,op:"update",previous:o.previous,tableName:o.table}))}),N=j.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.max(1,Math.floor(e.limit)):E,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,a)=>{for(const c of L){const s=(a[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:A(JSON.parse(n.doc))},...n.previous===void 0?{}:{previous:A(JSON.parse(n.previous))},...n.truncated===!0?{truncated:!0}:{}}))}),O=Y.input({limit:r.optional(r.number())}).mutation(async({args:e,ctx:t})=>{const o=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 a=0;a<C&&n<i;a+=1){const c=await t.db.query(l).withIndex("byRecordedAt",s=>s.lt("recordedAt",o)).order("asc").take(Math.min(E,i-n));if(c.length===0)return{deleted:n};await Promise.all(c.map(async s=>t.db.delete(s._id))),n+=c.length}return{deleted:n}});return{...U(p,{extension:P,functions:{listForDocument:N,vacuum:O}}),record:S}};export{B as DOCUMENT_HISTORY_REDACTED_FIELDS,l as DOCUMENT_HISTORY_TABLE,X as defineDocumentHistory,P as documentHistoryExtension};
@@ -1 +1 @@
1
- import{v as t}from"@lunora/values";import{initLunora as M}from"./initLunora-B2sfmFJ6.mjs";import{LunoraError as b}from"./LunoraError-DcKdk9Ti.mjs";import{onDisconnect as T}from"./onConnect-BLRoOpv2.mjs";import{g as v,h as A,a as L}from"./plugin-DfuRhJS1.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{v as t}from"@lunora/values";import{initLunora as M}from"./initLunora-BxNkWYTz.mjs";import{LunoraError as b}from"./LunoraError-DcKdk9Ti.mjs";import{onDisconnect as T}from"./onConnect-BLRoOpv2.mjs";import{g as v,h as A,a as L}from"./plugin-DfuRhJS1.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};
@@ -0,0 +1 @@
1
+ import{ValidationError as o}from"@lunora/values";import{LunoraError as a}from"./LunoraError-DcKdk9Ti.mjs";const p=(t,e)=>{try{return t.parse(e,{rejectUnknownKeys:!0})}catch(r){throw r instanceof o?new a("INTERNAL_SERVER_ERROR",`Response did not match the declared output schema: ${r.message}`):r}};export{p as a};
@@ -1,4 +1,4 @@
1
- import{toErrorBody as S}from"@lunora/errors";import{parseValidatorMap as R,ValidationError as A}from"@lunora/values";import{Hono as x}from"hono";import{a as q}from"./apply-output-BG8Bd0Ug.mjs";import{LunoraError as g}from"./LunoraError-DcKdk9Ti.mjs";const G=e=>async t=>e(t.get("lunora"),t.req.raw),J=()=>{const e=new x;return e.use("*",async(t,r)=>{const n=t.env.__lunoraCtx;if(!n)throw new g("INTERNAL_SERVER_ERROR","HttpActionCtx was not injected — mount httpRouter() on createWorker(), which supplies it per request.");t.set("lunora",n),await r()}),e},k=e=>e.kind==="optional"?e._meta?.inner??e:e,y=(e,t)=>{switch(e){case"bigint":try{return BigInt(t)}catch{return t}case"boolean":return t==="true"||t==="1"?!0:t==="false"||t==="0"?!1:t;case"number":return t===""?Number.NaN:Number(t);default:return t}},C=(e,t,r)=>{const n=k(e);if(n.kind==="array"){const o=t.req.queries(r);if(o===void 0)return;const s=n._meta?.inner;return o.map(c=>y(s?.kind??"string",c))}const a=t.req.query(r);return a===void 0?void 0:y(n.kind,a)},v=(e,t)=>{const r={};for(const n of Object.keys(e)){const a=e[n];a&&(r[n]=C(a,t,n))}return R(e,r,"searchParams")},N=(e,t)=>{const r=t.req.param(),n={};for(const a of Object.keys(e)){const o=e[a];if(!o)continue;const s=r[a];n[a]=s===void 0?void 0:y(k(o).kind,s)}return R(e,n,"params")},H=async(e,t)=>{let r;try{r=await t.req.json()}catch{throw new g("BAD_REQUEST","Invalid JSON body")}if(typeof r!="object"||r===null||Array.isArray(r))throw new g("BAD_REQUEST","Expected a JSON object body");return R(e,r,"body")},O=e=>{if(e instanceof A)return Response.json({code:"BAD_REQUEST",error:e.message},{status:400});if(e instanceof g){const{body:t,redacted:r,status:n}=S(e,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"Internal error"});return r&&console.error("[lunora] http action error (redacted on the wire):",e),Response.json({code:t.code,error:t.message},{status:n})}throw e},B=(e,t)=>async r=>{try{const n=r.get("lunora"),a=Object.keys(e.searchParams).length>0?v(e.searchParams,r):{},o=Object.keys(e.params).length>0?N(e.params,r):{},s=Object.keys(e.body).length>0?await H(e.body,r):{},c=await t({body:s,ctx:n,params:o,searchParams:a}),u=e.output?q(e.output,c):c,i={};e.cacheControl&&(i["cache-control"]=e.cacheControl),e.cacheTag&&(i["cache-tag"]=e.cacheTag),e.vary&&(i.vary=e.vary);const h=Object.keys(i).length>0;return u===void 0?new Response(null,{headers:h?i:void 0,status:204}):Response.json(u,{headers:h?i:void 0})}catch(n){return O(n)}},E={"cache-control":"no-cache, no-transform","content-type":"text/event-stream; charset=utf-8","x-accel-buffering":"no"},b=(e,t)=>{const r=JSON.stringify(e);return`${t?`event: ${t}
1
+ import{toErrorBody as S}from"@lunora/errors";import{parseValidatorMap as R,ValidationError as A}from"@lunora/values";import{Hono as x}from"hono";import{a as q}from"./apply-output-D7vpBeeu.mjs";import{LunoraError as g}from"./LunoraError-DcKdk9Ti.mjs";const G=e=>async t=>e(t.get("lunora"),t.req.raw),J=()=>{const e=new x;return e.use("*",async(t,r)=>{const n=t.env.__lunoraCtx;if(!n)throw new g("INTERNAL_SERVER_ERROR","HttpActionCtx was not injected — mount httpRouter() on createWorker(), which supplies it per request.");t.set("lunora",n),await r()}),e},k=e=>e.kind==="optional"?e._meta?.inner??e:e,y=(e,t)=>{switch(e){case"bigint":try{return BigInt(t)}catch{return t}case"boolean":return t==="true"||t==="1"?!0:t==="false"||t==="0"?!1:t;case"number":return t===""?Number.NaN:Number(t);default:return t}},C=(e,t,r)=>{const n=k(e);if(n.kind==="array"){const o=t.req.queries(r);if(o===void 0)return;const s=n._meta?.inner;return o.map(c=>y(s?.kind??"string",c))}const a=t.req.query(r);return a===void 0?void 0:y(n.kind,a)},v=(e,t)=>{const r={};for(const n of Object.keys(e)){const a=e[n];a&&(r[n]=C(a,t,n))}return R(e,r,"searchParams")},N=(e,t)=>{const r=t.req.param(),n={};for(const a of Object.keys(e)){const o=e[a];if(!o)continue;const s=r[a];n[a]=s===void 0?void 0:y(k(o).kind,s)}return R(e,n,"params")},H=async(e,t)=>{let r;try{r=await t.req.json()}catch{throw new g("BAD_REQUEST","Invalid JSON body")}if(typeof r!="object"||r===null||Array.isArray(r))throw new g("BAD_REQUEST","Expected a JSON object body");return R(e,r,"body")},O=e=>{if(e instanceof A)return Response.json({code:"BAD_REQUEST",error:e.message},{status:400});if(e instanceof g){const{body:t,redacted:r,status:n}=S(e,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"Internal error"});return r&&console.error("[lunora] http action error (redacted on the wire):",e),Response.json({code:t.code,error:t.message},{status:n})}throw e},B=(e,t)=>async r=>{try{const n=r.get("lunora"),a=Object.keys(e.searchParams).length>0?v(e.searchParams,r):{},o=Object.keys(e.params).length>0?N(e.params,r):{},s=Object.keys(e.body).length>0?await H(e.body,r):{},c=await t({body:s,ctx:n,params:o,searchParams:a}),u=e.output?q(e.output,c):c,i={};e.cacheControl&&(i["cache-control"]=e.cacheControl),e.cacheTag&&(i["cache-tag"]=e.cacheTag),e.vary&&(i.vary=e.vary);const h=Object.keys(i).length>0;return u===void 0?new Response(null,{headers:h?i:void 0,status:204}):Response.json(u,{headers:h?i:void 0})}catch(n){return O(n)}},E={"cache-control":"no-cache, no-transform","content-type":"text/event-stream; charset=utf-8","x-accel-buffering":"no"},b=(e,t)=>{const r=JSON.stringify(e);return`${t?`event: ${t}
2
2
  `:""}data: ${r}
3
3
 
4
4
  `},$=(e,t)=>(async r=>{let n,a;try{n=Object.keys(e.searchParams).length>0?v(e.searchParams,r):{},a=Object.keys(e.params).length>0?N(e.params,r):{}}catch(p){return O(p)}const o=r.get("lunora"),s=r.req.raw,c=new TextEncoder,u=new AbortController;if(s.signal.aborted)return u.abort(),new Response("",{headers:E});const i=()=>{u.abort()};s.signal.addEventListener("abort",i,{once:!0});const h=new ReadableStream({cancel(){s.signal.removeEventListener("abort",i),u.abort()},async start(p){try{const f=t({ctx:o,params:a,request:s,searchParams:n,signal:u.signal});for await(const m of f){if(u.signal.aborted)break;p.enqueue(c.encode(b(m)))}p.enqueue(c.encode(b({},"complete")))}catch(f){const{body:m,redacted:_}=S(f,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"Internal error"});_&&console.error("[lunora] unhandled stream handler error:",f),p.enqueue(c.encode(b({code:m.code,message:m.message},"error")))}finally{s.signal.removeEventListener("abort",i),p.close()}}});return new Response(h,{headers:E})}),d=e=>({body:t=>d({...e,body:{...e.body,...t}}),cacheControl:t=>d({...e,cacheControl:t}),cacheTag:t=>d({...e,cacheTag:t}),handler:t=>B(e,t),output:t=>d({...e,output:t}),params:t=>d({...e,params:{...e.params,...t}}),searchParams:t=>d({...e,searchParams:{...e.searchParams,...t}}),stream:t=>$(e,t),vary:t=>d({...e,vary:t})}),l=e=>t=>d({body:{},method:e,params:{},path:t,searchParams:{}}),Q={delete:l("DELETE"),get:l("GET"),head:l("HEAD"),options:l("OPTIONS"),patch:l("PATCH"),post:l("POST"),put:l("PUT")},I=/^bytes=(\d*)-(\d*)$/,T=e=>e.startsWith('"')||e.startsWith('W/"')?e:`"${e}"`,L=e=>!(e.includes("\r")||e.includes(`
@@ -1 +1 @@
1
- import{a as M}from"./apply-output-BG8Bd0Ug.mjs";import{v as f}from"./functions-B2-H4PQT.mjs";import{readMaskTag as h}from"./buildMaskRegistry-72SL8fJn.mjs";import{r as j}from"./policy-tag-D4RzgQnw.mjs";import{r as O}from"./run-middleware-B-JeGGp9.mjs";const x=(e,r)=>r===void 0||typeof e!="object"||e===null?e:Object.assign(Object.create(Object.getPrototypeOf(e)),e,{meta:r}),i=(e,r)=>O(e,r,o=>o),_=(e,r,o,a,n)=>async(s,u)=>{const t=f(e,u),l=await i(r,x(s,n)),c=await o({args:t,ctx:l});return a?M(a,c):c},q=(e,r,o,a)=>(n,s,u)=>{const t=f(e,s);return(async function*(){const c=await i(r,x(n,a)),m=o({args:t,ctx:c,signal:u})[Symbol.asyncIterator]();try{for(;;){if(u.aborted)return;const p=await m.next();if(p.done||u.aborted)return;yield p.value}}finally{await m.return?.()}})()},w=e=>{const r=e.map(o=>j(o)).filter(o=>o!==void 0);return r.length>0?{tags:r}:void 0},g=e=>{const r=new Map;for(const o of e){const a=h(o);if(a)for(const[n,s]of a.columns){const u=r.get(n)??new Set;for(const t of s)u.add(t);r.set(n,u)}}return r.size>0?r:void 0},d=(e,r,o)=>({__lunoraProcedure:e,...o?{__lunoraVisibility:o}:{},input:a=>d(e,{...r,args:{...r.args,...a}},o),[e]:a=>{const n=w(r.middlewares),s=g(r.middlewares);return{args:r.args,...r.expose?{expose:r.expose}:{},handler:_(r.args,r.middlewares,a,r.output,r.meta),kind:e,...s?{maskedTables:s}:{},...r.meta?{meta:r.meta}:{},...n?{rls:n}:{},...o?{visibility:o}:{},...r.x402?{x402:r.x402}:{}}},meta:a=>d(e,{...r,meta:Object.freeze({...r.meta,...a})},o),output:a=>d(e,{...r,output:a},o),...e==="query"?{stream:(a,n)=>{const s=w(r.middlewares),u=g(r.middlewares),t=n?.durable===!0?{}:n?.durable;return{args:r.args,...t?{durable:t}:{},...r.expose?{expose:r.expose}:{},handler:q(r.args,r.middlewares,a,r.meta),kind:"stream",...u?{maskedTables:u}:{},...r.meta?{meta:r.meta}:{},...s?{rls:s}:{},...o?{visibility:o}:{},...r.x402?{x402:r.x402}:{}}}}:{},use:a=>d(e,{...r,middlewares:[...r.middlewares,a]},o),...o?{}:{expose:a=>d(e,{...r,expose:a},o)},...o?{}:{x402:a=>d(e,{...r,x402:a},o)}}),A={dataModel:()=>({create:e=>({action:d("action",{args:{},middlewares:[]}),internalAction:d("action",{args:{},middlewares:[]},"internal"),internalMutation:d("mutation",{args:{},middlewares:[]},"internal"),internalQuery:d("query",{args:{},middlewares:[]},"internal"),mutation:d("mutation",{args:{},middlewares:[]}),query:d("query",{args:{},middlewares:[]})})})};export{A as initLunora};
1
+ import{a as M}from"./apply-output-D7vpBeeu.mjs";import{v as f}from"./functions-B2-H4PQT.mjs";import{readMaskTag as h}from"./buildMaskRegistry-72SL8fJn.mjs";import{r as j}from"./policy-tag-D4RzgQnw.mjs";import{r as O}from"./run-middleware-B-JeGGp9.mjs";const x=(e,r)=>r===void 0||typeof e!="object"||e===null?e:Object.assign(Object.create(Object.getPrototypeOf(e)),e,{meta:r}),i=(e,r)=>O(e,r,o=>o),_=(e,r,o,a,n)=>async(s,u)=>{const t=f(e,u),l=await i(r,x(s,n)),c=await o({args:t,ctx:l});return a?M(a,c):c},q=(e,r,o,a)=>(n,s,u)=>{const t=f(e,s);return(async function*(){const c=await i(r,x(n,a)),m=o({args:t,ctx:c,signal:u})[Symbol.asyncIterator]();try{for(;;){if(u.aborted)return;const p=await m.next();if(p.done||u.aborted)return;yield p.value}}finally{await m.return?.()}})()},w=e=>{const r=e.map(o=>j(o)).filter(o=>o!==void 0);return r.length>0?{tags:r}:void 0},g=e=>{const r=new Map;for(const o of e){const a=h(o);if(a)for(const[n,s]of a.columns){const u=r.get(n)??new Set;for(const t of s)u.add(t);r.set(n,u)}}return r.size>0?r:void 0},d=(e,r,o)=>({__lunoraProcedure:e,...o?{__lunoraVisibility:o}:{},input:a=>d(e,{...r,args:{...r.args,...a}},o),[e]:a=>{const n=w(r.middlewares),s=g(r.middlewares);return{args:r.args,...r.expose?{expose:r.expose}:{},handler:_(r.args,r.middlewares,a,r.output,r.meta),kind:e,...s?{maskedTables:s}:{},...r.meta?{meta:r.meta}:{},...n?{rls:n}:{},...o?{visibility:o}:{},...r.x402?{x402:r.x402}:{}}},meta:a=>d(e,{...r,meta:Object.freeze({...r.meta,...a})},o),output:a=>d(e,{...r,output:a},o),...e==="query"?{stream:(a,n)=>{const s=w(r.middlewares),u=g(r.middlewares),t=n?.durable===!0?{}:n?.durable;return{args:r.args,...t?{durable:t}:{},...r.expose?{expose:r.expose}:{},handler:q(r.args,r.middlewares,a,r.meta),kind:"stream",...u?{maskedTables:u}:{},...r.meta?{meta:r.meta}:{},...s?{rls:s}:{},...o?{visibility:o}:{},...r.x402?{x402:r.x402}:{}}}}:{},use:a=>d(e,{...r,middlewares:[...r.middlewares,a]},o),...o?{}:{expose:a=>d(e,{...r,expose:a},o)},...o?{}:{x402:a=>d(e,{...r,x402:a},o)}}),A={dataModel:()=>({create:e=>({action:d("action",{args:{},middlewares:[]}),internalAction:d("action",{args:{},middlewares:[]},"internal"),internalMutation:d("mutation",{args:{},middlewares:[]},"internal"),internalQuery:d("query",{args:{},middlewares:[]},"internal"),mutation:d("mutation",{args:{},middlewares:[]}),query:d("query",{args:{},middlewares:[]})})})};export{A as initLunora};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/server",
3
- "version": "1.0.0-alpha.93",
3
+ "version": "1.0.0-alpha.94",
4
4
  "description": "Server primitives for Lunora: defineSchema, defineTable, query, mutation, and action",
5
5
  "keywords": [
6
6
  "backend",
@@ -68,7 +68,7 @@
68
68
  "dependencies": {
69
69
  "@lunora/errors": "1.0.0-alpha.26",
70
70
  "@lunora/scheduler": "1.0.0-alpha.44",
71
- "@lunora/values": "1.0.0-alpha.33",
71
+ "@lunora/values": "1.0.0-alpha.34",
72
72
  "drizzle-orm": "^0.45.2",
73
73
  "hono": "^4.13.1"
74
74
  },
@@ -1 +0,0 @@
1
- import{ValidationError as e}from"@lunora/values";import{LunoraError as a}from"./LunoraError-DcKdk9Ti.mjs";const s=(t,o)=>{try{return t.parse(o)}catch(r){throw r instanceof e?new a("INTERNAL_SERVER_ERROR",`Response did not match the declared output schema: ${r.message}`):r}};export{s as a};