@lunora/server 1.0.0-alpha.142 → 1.0.0-alpha.144
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 +17 -0
- package/dist/index.d.ts +17 -0
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/{ACTION_CACHE_DEFAULT_TTL_MS-DznN8R6L.mjs → ACTION_CACHE_DEFAULT_TTL_MS-zqB8Qi2c.mjs} +1 -1
- package/dist/packem_shared/{DOCUMENT_HISTORY_REDACTED_FIELDS-DTWvHJax.mjs → DOCUMENT_HISTORY_REDACTED_FIELDS-B08eqNw4.mjs} +1 -1
- package/dist/packem_shared/{PRESENCE_DEFAULT_TTL_MS-BjHdghSv.mjs → PRESENCE_DEFAULT_TTL_MS-Ch-Y_Qns.mjs} +1 -1
- package/dist/packem_shared/{assertShapesDeclareReadPolicies-CjJWccLg.mjs → assertShapesDeclareReadPolicies--Kig94YV.mjs} +1 -1
- package/dist/packem_shared/{composePluginMiddleware-BLFb77u3.mjs → composePluginMiddleware-BoQZn0Di.mjs} +1 -1
- package/dist/packem_shared/{defineAggregateIndex-xNXpPxnE.mjs → defineAggregateIndex-DuGyF9Yd.mjs} +1 -1
- package/dist/packem_shared/{defineShape-Be5u-Whf.mjs → defineShape-sfO9V2A0.mjs} +1 -1
- package/dist/packem_shared/{mask-DsL8pZvt.mjs → mask-oCJ4GOob.mjs} +1 -1
- package/dist/packem_shared/middleware-Buo4tz8M.mjs +1 -0
- package/dist/packem_shared/plugin-C5XIUmql.mjs +1 -0
- package/dist/packem_shared/{rls-JwUA2QIB.mjs → rls-DB8SVGQm.mjs} +1 -1
- package/dist/packem_shared/{storageRules-DLH8uzGB.mjs → storageRules-Y8wQKzX5.mjs} +1 -1
- package/dist/rls/testing.mjs +1 -1
- package/dist/types.d.mts +4 -0
- package/dist/types.d.ts +4 -0
- package/package.json +3 -3
- package/dist/packem_shared/middleware-CgYaL-lL.mjs +0 -1
- package/dist/packem_shared/plugin-BQ2GySyZ.mjs +0 -1
package/dist/index.d.mts
CHANGED
|
@@ -563,6 +563,14 @@ interface VectorizeOptions<Shape extends Record<string, Validator> = Record<stri
|
|
|
563
563
|
/** Fields mirrored into Vectorize metadata for filtering. */
|
|
564
564
|
metadata?: ReadonlyArray<keyof Shape & string>;
|
|
565
565
|
metric: VectorMetric;
|
|
566
|
+
/**
|
|
567
|
+
* Identifier of the model `embed` calls, e.g. `"@cf/baai/bge-base-en-v1.5"`.
|
|
568
|
+
* `embed` is a function Lunora cannot inspect, so this string is how a model
|
|
569
|
+
* swap becomes visible: the `backfillVectors` admin op records it and
|
|
570
|
+
* re-embeds the table when it changes. Omit it and a model change goes
|
|
571
|
+
* unnoticed until the backfill is run with `restart: true`.
|
|
572
|
+
*/
|
|
573
|
+
model?: string;
|
|
566
574
|
}
|
|
567
575
|
/** A `one` (many-to-one) relation descriptor; phantom `Target` carries the target table name. */
|
|
568
576
|
interface OneRelation<Target extends string = string> extends RelationDefinition {
|
|
@@ -864,6 +872,15 @@ interface VectorIndexOptions {
|
|
|
864
872
|
/** Optional projection of the source row into Vectorize metadata. */
|
|
865
873
|
metadata?: (row: Record<string, unknown>) => Record<string, unknown>;
|
|
866
874
|
metric: VectorMetric;
|
|
875
|
+
/**
|
|
876
|
+
* Identifier of the model `embed` calls, e.g. `"@cf/baai/bge-base-en-v1.5"`.
|
|
877
|
+
* `embed` is a function Lunora cannot inspect, so this string is how a model
|
|
878
|
+
* swap becomes visible: the `backfillVectors` admin op records it and
|
|
879
|
+
* re-embeds the table when it changes. Omit it and a model change goes
|
|
880
|
+
* unnoticed, as does a change to `select` or `metadata`, until the backfill
|
|
881
|
+
* is run with `restart: true`.
|
|
882
|
+
*/
|
|
883
|
+
model?: string;
|
|
867
884
|
/** The vector source: which table, and how to derive the embedded text. */
|
|
868
885
|
source: {
|
|
869
886
|
select: (row: Record<string, unknown>) => string;
|
package/dist/index.d.ts
CHANGED
|
@@ -563,6 +563,14 @@ interface VectorizeOptions<Shape extends Record<string, Validator> = Record<stri
|
|
|
563
563
|
/** Fields mirrored into Vectorize metadata for filtering. */
|
|
564
564
|
metadata?: ReadonlyArray<keyof Shape & string>;
|
|
565
565
|
metric: VectorMetric;
|
|
566
|
+
/**
|
|
567
|
+
* Identifier of the model `embed` calls, e.g. `"@cf/baai/bge-base-en-v1.5"`.
|
|
568
|
+
* `embed` is a function Lunora cannot inspect, so this string is how a model
|
|
569
|
+
* swap becomes visible: the `backfillVectors` admin op records it and
|
|
570
|
+
* re-embeds the table when it changes. Omit it and a model change goes
|
|
571
|
+
* unnoticed until the backfill is run with `restart: true`.
|
|
572
|
+
*/
|
|
573
|
+
model?: string;
|
|
566
574
|
}
|
|
567
575
|
/** A `one` (many-to-one) relation descriptor; phantom `Target` carries the target table name. */
|
|
568
576
|
interface OneRelation<Target extends string = string> extends RelationDefinition {
|
|
@@ -864,6 +872,15 @@ interface VectorIndexOptions {
|
|
|
864
872
|
/** Optional projection of the source row into Vectorize metadata. */
|
|
865
873
|
metadata?: (row: Record<string, unknown>) => Record<string, unknown>;
|
|
866
874
|
metric: VectorMetric;
|
|
875
|
+
/**
|
|
876
|
+
* Identifier of the model `embed` calls, e.g. `"@cf/baai/bge-base-en-v1.5"`.
|
|
877
|
+
* `embed` is a function Lunora cannot inspect, so this string is how a model
|
|
878
|
+
* swap becomes visible: the `backfillVectors` admin op records it and
|
|
879
|
+
* re-embeds the table when it changes. Omit it and a model change goes
|
|
880
|
+
* unnoticed, as does a change to `select` or `metadata`, until the backfill
|
|
881
|
+
* is run with `restart: true`.
|
|
882
|
+
*/
|
|
883
|
+
model?: string;
|
|
867
884
|
/** The vector source: which table, and how to derive the embedded text. */
|
|
868
885
|
source: {
|
|
869
886
|
select: (row: Record<string, unknown>) => string;
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ACTION_CACHE_DEFAULT_TTL_MS as t,ACTION_CACHE_TABLE as n,actionCacheExtension as i,cacheKeyFor as a,defineActionCache as f}from"./packem_shared/ACTION_CACHE_DEFAULT_TTL_MS-
|
|
1
|
+
import{ACTION_CACHE_DEFAULT_TTL_MS as t,ACTION_CACHE_TABLE as n,actionCacheExtension as i,cacheKeyFor as a,defineActionCache as f}from"./packem_shared/ACTION_CACHE_DEFAULT_TTL_MS-zqB8Qi2c.mjs";import{initLunora as d}from"./packem_shared/initLunora-DAbEYdSo.mjs";import{isPerDispatchMiddleware as m,tagPerDispatchMiddleware as x}from"./packem_shared/isPerDispatchMiddleware-DDQPatSm.mjs";import{createSecrets as l}from"./packem_shared/createSecrets-D6rLB42U.mjs";import{beginDeferredDeletes as h,flushDeferredDeletes as S,withDeferredDeletes as u}from"./packem_shared/beginDeferredDeletes-DhwFBbvs.mjs";import{beginDeferredSchedules as T,withDeferredSchedules as g}from"./packem_shared/beginDeferredSchedules-CIhFddA2.mjs";import{DOCUMENT_HISTORY_REDACTED_FIELDS as R,DOCUMENT_HISTORY_TABLE as _,defineDocumentHistory as L,documentHistoryExtension as C}from"./packem_shared/DOCUMENT_HISTORY_REDACTED_FIELDS-B08eqNw4.mjs";import{LunoraEnvError as P,defineEnv as M,redactSecrets as b}from"./packem_shared/LunoraEnvError-A5I-PzMh.mjs";import{bindOrm as F,bindTableFacade as O}from"./packem_shared/bindOrm-D_hFUjmr.mjs";import{httpAction as N,httpRoute as w,httpRouter as U,isSafeHeaderValue as k}from"./packem_shared/httpAction-DFVhrm8u.mjs";import{serveStorageObject as B}from"./packem_shared/serveStorageObject-9mdw0nyU.mjs";import{defineIdentity as W}from"./packem_shared/defineIdentity-DwkNKwYa.mjs";import{onConnect as Y,onDisconnect as J,onShardInit as K}from"./packem_shared/onConnect-BLRoOpv2.mjs";import{DEFAULT_LIMIT as X,DEFAULT_MAX_LIMIT as q,clampLimit as z,defineListArgs as G}from"./packem_shared/DEFAULT_LIMIT-vNtdsa5y.mjs";import{defineMigration as $}from"./packem_shared/defineMigration-CXOS0Bvq.mjs";import{defineMutator as re}from"./packem_shared/defineMutator-DKy8UtbB.mjs";import{c as te,d as ne,a as ie,b as ae,e as fe,f as se,g as de,h as pe,i as me,j as xe,k as ce,m as le}from"./packem_shared/plugin-C5XIUmql.mjs";import{PRESENCE_DEFAULT_TTL_MS as he,PRESENCE_TABLE as Se,definePresence as ue,presenceExtension as De}from"./packem_shared/PRESENCE_DEFAULT_TTL_MS-Ch-Y_Qns.mjs";import{protectPublic as ge}from"./packem_shared/protectPublic-BUYCMZZB.mjs";import{onQueryChange as Re}from"./packem_shared/onQueryChange-CatdYnH5.mjs";import{defineShape as Le}from"./packem_shared/defineShape-sfO9V2A0.mjs";import{anyApi as Ie}from"./types.mjs";import{onWhisper as Me}from"./packem_shared/onWhisper-CfDbFLQh.mjs";import{LunoraError as ye}from"@lunora/errors";import{cronJobs as Oe}from"@lunora/scheduler";import{ValidationError as Ne,v as we}from"@lunora/values";import{allowAll as ke,deny as ve,isDeny as Be,toWhereInput as Ve}from"./packem_shared/allowAll-DkRAgItV.mjs";import{asBucketStorage as je}from"./packem_shared/asBucketStorage-DoGYOjq3.mjs";import{assertShapesDeclareReadPolicies as Je,buildRlsReadRegistry as Ke,composeShapeReadWhere as Qe}from"./packem_shared/assertShapesDeclareReadPolicies--Kig94YV.mjs";import{buildMaskRegistry as qe}from"./packem_shared/buildMaskRegistry-DpWMtalG.mjs";import{createPolicyDsl as Ge,definePermission as Ze,definePolicies as $e,definePolicy as er,defineRole as rr}from"./packem_shared/createPolicyDsl-BZa6SqLJ.mjs";import{defineStorageRule as tr,defineStorageRules as nr}from"./packem_shared/defineStorageRule-Dv4nJE0H.mjs";import{mask as ar}from"./packem_shared/mask-oCJ4GOob.mjs";import{r as sr}from"./packem_shared/middleware-Buo4tz8M.mjs";import{storageRules as pr}from"./packem_shared/storageRules-Y8wQKzX5.mjs";const e="0.0.0";export{t as ACTION_CACHE_DEFAULT_TTL_MS,n as ACTION_CACHE_TABLE,X as DEFAULT_LIMIT,q as DEFAULT_MAX_LIMIT,R as DOCUMENT_HISTORY_REDACTED_FIELDS,_ as DOCUMENT_HISTORY_TABLE,P as LunoraEnvError,ye as LunoraError,he as PRESENCE_DEFAULT_TTL_MS,Se as PRESENCE_TABLE,e as VERSION,Ne as ValidationError,i as actionCacheExtension,ke as allowAll,Ie as anyApi,je as asBucketStorage,Je as assertShapesDeclareReadPolicies,h as beginDeferredDeletes,T as beginDeferredSchedules,F as bindOrm,O as bindTableFacade,qe as buildMaskRegistry,Ke as buildRlsReadRegistry,a as cacheKeyFor,z as clampLimit,te as composePluginMiddleware,Qe as composeShapeReadWhere,Ge as createPolicyDsl,l as createSecrets,Oe as cronJobs,f as defineActionCache,ne as defineAggregateIndex,ie as defineComponent,L as defineDocumentHistory,M as defineEnv,W as defineIdentity,G as defineListArgs,$ as defineMigration,re as defineMutator,Ze as definePermission,ae as definePlugin,$e as definePolicies,er as definePolicy,ue as definePresence,fe as defineRankIndex,rr as defineRole,se as defineSchema,de as defineSchemaExtension,Le as defineShape,tr as defineStorageRule,nr as defineStorageRules,pe as defineTable,me as defineVectorIndex,ve as deny,C as documentHistoryExtension,S as flushDeferredDeletes,N as httpAction,w as httpRoute,U as httpRouter,xe as indexFieldsFromSchema,d as initLunora,ce as installPlugins,Be as isDeny,m as isPerDispatchMiddleware,k as isSafeHeaderValue,ar as mask,le as mergeSchemaExtension,Y as onConnect,J as onDisconnect,Re as onQueryChange,K as onShardInit,Me as onWhisper,De as presenceExtension,ge as protectPublic,b as redactSecrets,sr as rls,B as serveStorageObject,pr as storageRules,x as tagPerDispatchMiddleware,Ve as toWhereInput,we as v,u as withDeferredDeletes,g as withDeferredSchedules};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{isLunoraError as S}from"@lunora/errors";import{v as d}from"@lunora/values";import{a as f,d as U}from"./wire-codec-BTOxkE1j.mjs";import{s as D}from"./stable-key-B_BlboiY.mjs";import{initLunora as F}from"./initLunora-DAbEYdSo.mjs";import{g as k,h as q,a as B}from"./plugin-
|
|
1
|
+
import{isLunoraError as S}from"@lunora/errors";import{v as d}from"@lunora/values";import{a as f,d as U}from"./wire-codec-BTOxkE1j.mjs";import{s as D}from"./stable-key-B_BlboiY.mjs";import{initLunora as F}from"./initLunora-DAbEYdSo.mjs";import{g as k,h as q,a as B}from"./plugin-C5XIUmql.mjs";const P=i=>D(f(i)),R=3600*1e3,H=512*1024,V=8,b=64,K=64,W=256,$=4096,u="actionCache",h="entries",c=`${u}_${h}`,T=i=>i===void 0?"":P(i),x=async(i,m)=>{const A=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(`${i}\0${m}`));return[...new Uint8Array(A)].map(y=>y.toString(16).padStart(2,"0")).join("")},G=k(u,{tables:{[h]:q({expiresAt:d.number(),key:d.string(),name:d.string(),value:d.string()}).index("byKey",["key"],{unique:!0}).index("byName",["name"]).index("byExpiresAt",["expiresAt"])}}),{internalMutation:J}=F.dataModel().create(),te=(i={})=>{const m=i.ttlMs!==void 0&&Number.isFinite(i.ttlMs)?Math.max(1,Math.floor(i.ttlMs)):R,A=i.maxValueBytes!==void 0&&Number.isFinite(i.maxValueBytes)?Math.max(1,Math.floor(i.maxValueBytes)):H,y=async(e,t)=>{const n=(await e.db.query(c).withIndex("byExpiresAt").order("asc").take(V)).filter(r=>r.expiresAt<=t);await Promise.all(n.map(async r=>e.db.delete(r._id)))},C=async(e,t)=>e.db.query(c).withIndex("byKey",a=>a.eq("key",t)).first(),N=new Set(["CONFLICT","NOT_FOUND","NOT_UNIQUE"]),I=async(e,t,a)=>{try{await(t?e.db.patch(t._id,{expiresAt:a.expiresAt,value:a.value}):e.db.insert(c,a))}catch(n){if(S(n)&&N.has(n.code))return;throw n}},M=async(e,t,a,n)=>{const r=T(a),s=await x(t,r),l=Date.now(),o=await C(e,s);if(o&&o.expiresAt>l)return U(JSON.parse(o.value)).v;const p=await n(),w=JSON.stringify(f({v:p})),E=Date.now(),O=E+m;return new TextEncoder().encode(w).length<=A?await I(e,o,{expiresAt:O,key:s,name:t,value:w}):o&&await e.db.delete(o._id),await y(e,E),p},L=async(e,t,a)=>{const n=await x(t,T(a)),r=await e.db.query(c).withIndex("byKey",s=>s.eq("key",n)).take(b);await Promise.all(r.map(async s=>e.db.delete(s._id)))},_=async(e,t,a,n)=>{if(n>=K)return{complete:!1,deleted:a};const r=await e.db.query(c).withIndex("byName",s=>s.eq("name",t)).take(b);return r.length===0?{complete:!0,deleted:a}:(await Promise.all(r.map(async s=>e.db.delete(s._id))),_(e,t,a+r.length,n+1))},g=async(e,t)=>_(e,t,0,0),v=J.input({limit:d.optional(d.number())}).mutation(async({args:e,ctx:t})=>{const a=Date.now(),n=e.limit!==void 0&&Number.isFinite(e.limit)?Math.min($,Math.max(1,Math.floor(e.limit))):W,s=(await t.db.query(c).withIndex("byExpiresAt").order("asc").take(n)).filter(l=>l.expiresAt<=a);return await Promise.all(s.map(async l=>t.db.delete(l._id))),{deleted:s.length}});return{...B(u,{extension:G,functions:{purgeExpired:v}}),invalidate:L,invalidateAll:g,wrap:M}};export{R as ACTION_CACHE_DEFAULT_TTL_MS,c as ACTION_CACHE_TABLE,G as actionCacheExtension,x as cacheKeyFor,te as defineActionCache};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{v as r}from"@lunora/values";import{d as E,a as h}from"./wire-codec-BTOxkE1j.mjs";import{initLunora as x}from"./initLunora-DAbEYdSo.mjs";import{g as v,h as R,a as U}from"./plugin-
|
|
1
|
+
import{v as r}from"@lunora/values";import{d as E,a as h}from"./wire-codec-BTOxkE1j.mjs";import{initLunora as x}from"./initLunora-DAbEYdSo.mjs";import{g as v,h as R,a as U}from"./plugin-C5XIUmql.mjs";const H=2160*60*60*1e3,L=64*1024,I=200,q=1e3,C=64,F=512,u=16,B=["_commitSeq","seq"],w=["accessToken","apiKey","backupCodes","clientSecret","hashedPassword","password","privateKey","refreshToken","secret","totpSecret"],f="documentHistory",y="versions",p=`${f}_${y}`,P=v(f,{tables:{[y]:R({doc:r.optional(r.string()),documentId:r.string(),op:r.union(r.literal("delete"),r.literal("insert"),r.literal("update")),previous:r.optional(r.string()),recordedAt:r.number(),seq:r.number(),tableName:r.string(),truncated:r.optional(r.boolean())}).commitOrdered().index("byDocumentRecordedAt",["documentId","recordedAt","seq"]).index("byRecordedAt",["recordedAt"])}}),{internalMutation:Y,internalQuery:g}=x.dataModel().create(),V=(d={})=>{const T=d.retentionMs!==void 0&&Number.isFinite(d.retentionMs)?Math.max(1,Math.floor(d.retentionMs)):H,_=d.maxSnapshotBytes!==void 0&&Number.isFinite(d.maxSnapshotBytes)?Math.max(1,Math.floor(d.maxSnapshotBytes)):L,b=new Set([...w,...d.redact??[]]);let A=0;const S=()=>(A+=1,A),a=(e,o=0)=>{if(Array.isArray(e))return o>=u?void 0:e.map(t=>a(t,o+1));if(typeof e!="object"||e===null)return e;if(e instanceof Map)return o>=u?void 0:new Map([...e.entries()].filter(([t])=>typeof t!="string"||!b.has(t)).map(([t,i])=>[t,a(i,o+1)]));if(e instanceof Set)return o>=u?void 0:new Set([...e].map(t=>a(t,o+1)));if(Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null)return e;if(!(o>=u))return Object.fromEntries(Object.entries(e).filter(([t])=>!b.has(t)).map(([t,i])=>[t,a(i,o+1)]))},M=e=>{if(e===void 0)return;const o=JSON.stringify(h(a(e)));return new TextEncoder().encode(o).length>_?void 0:o},l=async(e,o)=>{const t=M(o.doc),i=M(o.previous),n=o.doc!==void 0&&t===void 0||o.previous!==void 0&&i===void 0;await e.db.insert(p,{documentId:o.documentId,op:o.op,recordedAt:Date.now(),seq:S(),tableName:o.tableName,...n?{truncated:!0}:{},...t===void 0?{}:{doc:t},...i===void 0?{}:{previous:i}})},D=e=>({documentHistoryDelete:e.afterDelete(async(o,t)=>l(o,{documentId:t.id,op:"delete",previous:t.previous,tableName:t.table})),documentHistoryInsert:e.afterInsert(async(o,t)=>l(o,{doc:t.doc,documentId:t.id,op:"insert",tableName:t.table})),documentHistoryUpdate:e.afterUpdate(async(o,t)=>l(o,{doc:t.doc,documentId:t.id,op:"update",previous:t.previous,tableName:t.table}))}),N=g.input({before:r.optional(r.number()),documentId:r.string(),limit:r.optional(r.number())}).query(async({args:e,ctx:o})=>{const t=e.limit!==void 0&&Number.isFinite(e.limit)?Math.min(q,Math.max(1,Math.floor(e.limit))):I,i=await o.db.query(p).withIndex("byDocumentRecordedAt",n=>e.before===void 0?n.eq("documentId",e.documentId):n.eq("documentId",e.documentId).lte("recordedAt",e.before)).order("desc").take(t);return i.sort((n,m)=>{for(const c of B){const s=(m[c]??0)-(n[c]??0);if(s!==0)return s}return 0}),i.map(n=>({documentId:n.documentId,op:n.op,recordedAt:n.recordedAt,tableName:n.tableName,...n.doc===void 0?{}:{doc:E(JSON.parse(n.doc))},...n.previous===void 0?{}:{previous:E(JSON.parse(n.previous))},...n.truncated===!0?{truncated:!0}:{}}))}),O=Y.input({limit:r.optional(r.number())}).mutation(async({args:e,ctx:o})=>{const t=Date.now()-T,i=e.limit!==void 0&&Number.isFinite(e.limit)?Math.max(1,Math.floor(e.limit)):F;let n=0;for(let m=0;m<C&&n<i;m+=1){const c=await o.db.query(p).withIndex("byRecordedAt",s=>s.lt("recordedAt",t)).order("asc").take(Math.min(I,i-n));if(c.length===0)return{deleted:n};await Promise.all(c.map(async s=>o.db.delete(s._id))),n+=c.length}return{deleted:n}});return{...U(f,{extension:P,functions:{listForDocument:N,vacuum:O}}),record:D}};export{w as DOCUMENT_HISTORY_REDACTED_FIELDS,p as DOCUMENT_HISTORY_TABLE,V as defineDocumentHistory,P as documentHistoryExtension};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as b}from"@lunora/errors";import{v as t}from"@lunora/values";import{initLunora as M}from"./initLunora-DAbEYdSo.mjs";import{onDisconnect as T}from"./onConnect-BLRoOpv2.mjs";import{g as v,h as A,a as L}from"./plugin-
|
|
1
|
+
import{LunoraError as b}from"@lunora/errors";import{v as t}from"@lunora/values";import{initLunora as M}from"./initLunora-DAbEYdSo.mjs";import{onDisconnect as T}from"./onConnect-BLRoOpv2.mjs";import{g as v,h as A,a as L}from"./plugin-C5XIUmql.mjs";const D=3e4,g=1024,P=8,p=4096,w="presence",h="present",l=`${w}_${h}`,N=v(w,{tables:{[h]:A({data:t.optional(t.record(t.string(),t.any())),lastSeen:t.number(),roomId:t.string(),sessionId:t.string(),userId:t.optional(t.string())}).index("byRoomSession",["roomId","sessionId"]).index("byRoom",["roomId"]).index("byRoomLastSeen",["roomId","lastSeen"])}}),{mutation:E,query:B}=M.dataModel().create(),G=(u={})=>{const m=u.ttlMs??D,f=Math.max(0,Math.min(u.disconnectGraceMs??0,m)),S=u.maxSessions,y=S!==void 0&&Number.isFinite(S)?Math.max(1,Math.floor(S)):g,_=E.input({data:t.optional(t.record(t.string(),t.any())),roomId:t.string(),sessionId:t.string()}).mutation(async({args:o,ctx:s})=>{const r=Date.now(),d=s.auth.userId??void 0;if(o.data!==void 0&&new TextEncoder().encode(JSON.stringify(o.data)).length>p)throw new b("BAD_REQUEST",`presence data exceeds the ${String(p)}-byte limit`);const e=await s.db.query(l).withIndex("byRoomSession",i=>i.eq("roomId",o.roomId).eq("sessionId",o.sessionId)).first();if(e&&(e.userId??void 0)!==d)throw new b("FORBIDDEN","presence heartbeat denied: this (roomId, sessionId) is held by another identity");const a={lastSeen:r,roomId:o.roomId,sessionId:o.sessionId,...o.data===void 0?{}:{data:o.data},...d===void 0?{}:{userId:d}};await(e?s.db.patch(e._id,a):s.db.insert(l,a));const I=r-m-Math.max(f,m),c=(await s.db.query(l).withIndex("byRoomLastSeen",i=>i.eq("roomId",o.roomId)).order("asc").take(P)).filter(i=>i.lastSeen<=I);return await Promise.all(c.map(i=>s.db.delete(i._id))),{lastSeen:r}}),x=B.input({roomId:t.string()}).query(async({args:o,ctx:s})=>{const r=Date.now()-m,e=(await s.db.query(l).withIndex("byRoomLastSeen",n=>n.eq("roomId",o.roomId)).order("desc").take(y)).filter(n=>n.lastSeen>r),a=new Set,I=[];for(const n of e){const c=n.userId;if(c!==void 0){if(a.has(c))continue;a.add(c)}const i={lastSeen:n.lastSeen,roomId:n.roomId};c!==void 0&&(i.userId=c),n.data!==void 0&&(i.data=n.data),I.push(i)}return I}),R={...E.input({roomId:t.string()}).mutation(async({args:o,ctx:s})=>{const r=Date.now()-m,d=await s.db.query(l).withIndex("byRoom",e=>e.eq("roomId",o.roomId)).filter(e=>e.lastSeen<=r).collect();return await Promise.all(d.map(e=>s.db.delete(e._id))),{deleted:d.length}}),visibility:"internal"},q=T(async(o,s)=>{const r=s.context?.roomId,d=s.context?.sessionId;if(typeof r!="string"||typeof d!="string")return;const e=await o.db.query(l).withIndex("byRoomSession",n=>n.eq("roomId",r).eq("sessionId",d)).first();if(!e)return;const a=s.userId??void 0;if((e.userId??void 0)!==a)return;if(f===0){await o.db.delete(e._id);return}const I=Math.min(e.lastSeen,Date.now()+f-m);await o.db.patch(e._id,{lastSeen:I})});return L(w,{extension:N,functions:{disconnect:q,heartbeat:_,listPresent:x,sweep:R}})};export{D as PRESENCE_DEFAULT_TTL_MS,l as PRESENCE_TABLE,G as definePresence,N as presenceExtension};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as c}from"@lunora/errors";import{i as p,d as g,f as b,e as y}from"./middleware-
|
|
1
|
+
import{LunoraError as c}from"@lunora/errors";import{i as p,d as g,f as b,e as y}from"./middleware-Buo4tz8M.mjs";import{r as w}from"./policy-tag-V0lqFzgS.mjs";import{deny as m}from"./allowAll-DkRAgItV.mjs";const h=m(),v=t=>{const e=t?.rls?.tags;return e||w(t)},R=(t,e)=>{const r=p(e.roles),o=new Map,n=new Map;for(const s of e.policies){if(s.on!=="read")continue;const a=o.get(s.table)??new Set;if(a.has(s.when))continue;a.add(s.when),o.set(s.table,a);const l=n.get(s.table)??[];l.push(s),n.set(s.table,l)}for(const[s,a]of n){const l=t.get(s)??[];l.push({policies:a,rolePermissions:r}),t.set(s,l)}},d=t=>{const e=t.OR;return Array.isArray(e)&&e.length===0&&Object.keys(t).length===1},T=(t,e)=>!t||Object.keys(t).length===0?e:d(t)||Object.keys(e).length===0?t:{AND:[t,e]},S=(t,e)=>{const r=g(e.identity);return b(t.policies,{auth:{can:y(r,t.rolePermissions),identity:e.identity,roles:r,userId:e.userId},ctx:e.ctx})},A=(t,e)=>{const r=t.byTable.get(e.table);if(!r||r.length===0)return e.rlsRequired&&!e.tablePublic?h:void 0;const o=[];for(const n of r){const s=S(n,e);if(s===void 0)return;d(s)||o.push(s)}return o.length===0?h:o.length===1?o[0]:{OR:o}},O=t=>{const e=new Map,r=new Set;for(const o of t)for(const n of v(o))r.has(n)||(r.add(n),R(e,n));return{byTable:e}},W=(t,e,r)=>{if(r)return;const o=new Set(e),n=Object.entries(t).filter(([,i])=>o.has(i.table)),s=i=>i.map(([u,f])=>`"${u}" (table "${f.table}")`).join(", "),a=n.filter(([,i])=>i.use===void 0);if(a.length>0)throw new c("INTERNAL",`defineShape ${s(a)} replicate${a.length===1?"s":""} a table this project's rls() read policies restrict, but declare${a.length===1?"s":""} no \`use\` — a shape runs no procedure, so those policies never reach it and every subscriber would replicate every row the shape's own \`where\` admits. Name the guards the equivalent query lists: \`defineShape({ use: [<the rls() guard>], ... })\`. If the shape really is meant to be ungoverned (its own \`where\` is the whole filter), say so with \`use: []\`.`);const l=n.filter(([,i])=>i.use!==void 0&&i.use.length>0&&!i.rlsRegistry.byTable.has(i.table));if(l.length>0)throw new c("INTERNAL",`defineShape ${s(l)} name \`use\` guards that declare no \`on: "read"\` policy for that table, so nothing governs what replicates and the shape's own \`where\` is the whole filter — the same gap a missing \`use\` leaves, on a table this project's rls() read policies restrict. A guard for a different table, or a middleware carrying no rls() policies at all, does not count: name the same rls() guard the equivalent query lists. If the shape really is meant to be ungoverned, say so with \`use: []\`.`)},$=(t,e)=>T(A(t,e),e.shapeWhere);export{W as assertShapesDeclareReadPolicies,O as buildRlsReadRegistry,$ as composeShapeReadWhere};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import"./compose-middleware-DNvrHMHx.mjs";import{c as i,a as s,b as o,g as m,k as l,m as t}from"./plugin-
|
|
1
|
+
import"./compose-middleware-DNvrHMHx.mjs";import{c as i,a as s,b as o,g as m,k as l,m as t}from"./plugin-C5XIUmql.mjs";export{i as composePluginMiddleware,s as defineComponent,o as definePlugin,m as defineSchemaExtension,l as installPlugins,t as mergeSchemaExtension};
|
package/dist/packem_shared/{defineAggregateIndex-xNXpPxnE.mjs → defineAggregateIndex-DuGyF9Yd.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{d,e as i,f as n,h as s,i as l,j as f,v as o,l as r}from"./plugin-
|
|
1
|
+
import{d,e as i,f as n,h as s,i as l,j as f,v as o,l as r}from"./plugin-C5XIUmql.mjs";export{d as defineAggregateIndex,i as defineRankIndex,n as defineSchema,s as defineTable,l as defineVectorIndex,f as indexFieldsFromSchema,o as validateGlobalVectors,r as validateIndexFields};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as r}from"@lunora/errors";import{c as p}from"./context-identity-B2XYGA0B.mjs";import{v as u}from"./functions-B2-H4PQT.mjs";import{toWhereInput as m,deny as d}from"./allowAll-DkRAgItV.mjs";import{buildRlsReadRegistry as c}from"./assertShapesDeclareReadPolicies
|
|
1
|
+
import{LunoraError as r}from"@lunora/errors";import{c as p}from"./context-identity-B2XYGA0B.mjs";import{v as u}from"./functions-B2-H4PQT.mjs";import{toWhereInput as m,deny as d}from"./allowAll-DkRAgItV.mjs";import{buildRlsReadRegistry as c}from"./assertShapesDeclareReadPolicies--Kig94YV.mjs";const I=e=>{if(e.table.trim()==="")throw new r("INTERNAL","defineShape: `table` must be a non-empty string");if(e.columns?.length===0)throw new r("INTERNAL","defineShape: `columns` must list at least one column when provided");if(!e.where&&e.owner===void 0)throw new r("INTERNAL",`defineShape: shape on table "${e.table}" needs a \`where\` predicate or an \`owner\` (\`owner: true\` uses the table's .ownedBy(field), \`owner: "field"\` names the column) — a shape with neither would replicate the whole table`);return{__lunoraShape:!0,...e,compileWhere:(a,l,n)=>{const w=u(e.args??{},l),o=e.where?m(e.where(a,w)):void 0;if(e.owner===void 0)return o;const t=e.owner===!0?n?.ownerField:e.owner;if(t===void 0||t==="")throw new r("INTERNAL",`defineShape: shape on table "${e.table}" declares \`owner: true\` but the table has no \`.ownedBy(field)\` — add it to the table, or name the column directly with \`owner: "field"\``);const s=p(a);if(s===void 0)return d();const h={[t]:s};return o===void 0?h:{AND:[h,o]}},rlsRegistry:c(e.use??[])}};export{I as defineShape};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as S}from"@lunora/errors";import{f as U}from"./fnv1a-D3ueNTWB.mjs";import{i as L,a as z,o as _,b as G,c as C}from"./middleware-
|
|
1
|
+
import{LunoraError as S}from"@lunora/errors";import{f as U}from"./fnv1a-D3ueNTWB.mjs";import{i as L,a as z,o as _,b as G,c as C}from"./middleware-Buo4tz8M.mjs";import{bindTableFacade as H,bindOrm as J}from"./bindOrm-D_hFUjmr.mjs";import{tagMaskMiddleware as Q}from"./buildMaskRegistry-DpWMtalG.mjs";const V=(e,i,a)=>{try{return e==="redact"?null:e==="hash"?i==null?i:typeof i=="bigint"?U(i.toString()):U(typeof i=="string"?i:JSON.stringify(i)):e(i,a)}catch{return null}},d=(e,i,a)=>{const u={...e};for(const[y,g]of Object.entries(i))y in u&&(u[y]=V(g,e[y],{...a,column:y,row:e}));return u},j=(e,i,a)=>({...e,page:e.page.map(u=>d(u,i,a))}),D=(e,i,a,u)=>{if(typeof e!="function")return;const y=new Set,g=()=>new Proxy({},{get:()=>w=>(typeof w=="string"&&y.add(w),g())});e(g());for(const w of y)if(w in i)throw new S("MASK_UNSUPPORTED",`${u}() filtering "${a}" by masked column "${w}" is not supported`)},X=(e,i,a,u)=>{const y=e.rankBefore,g=e.rankPageRows,w=(r,n)=>{const t=i.get(r);return t?n.map(o=>d(o,t,a)):n},k=r=>{const n=r?.relationMask;return{...r,relationMask:n===void 0?w:(t,o)=>n(t,w(t,o))}},p=(r,n,t,o)=>{const s=i.get(r);if(!s)return;const c=u?.[r]?.[o]?.[n];if(!c)return;const f=c.find(E=>E in s);if(f!==void 0)throw new S("MASK_UNSUPPORTED",`${t}() reading "${r}" via index "${n}" would order rows by masked column "${f}" — use an index whose declared fields are all unmasked, or unmask the column`)},l=(r,n,t)=>({async*[Symbol.asyncIterator](){for await(const o of{[Symbol.asyncIterator]:()=>r[Symbol.asyncIterator]()})yield d(o,n,a)},collect:async()=>(await r.collect()).map(s=>d(s,n,a)),collectWithScores:async()=>(await r.collectWithScores()).map(s=>{const c=d(s.document,n,a);return"distanceMeters"in s?{distanceMeters:null,document:c}:{document:c,score:s.score}}),filter:o=>l(r.filter(s=>o(d(s,n,a))),n,t),first:async()=>{const o=await r.first();return o?d(o,n,a):null},order:o=>l(r.order(o),n,t),paginate:async o=>j(await r.paginate(o),n,a),take:async o=>(await r.take(o)).map(c=>d(c,n,a)),unique:async()=>{const o=await r.unique();return o?d(o,n,a):null},withIndex:(o,s)=>(p(t,o,"withIndex","index"),D(s,n,t,"withIndex"),l(r.withIndex(o,s),n,t)),withSearchIndex:(o,s)=>(D(s,n,t,"withSearchIndex"),l(r.withSearchIndex(o,s),n,t)),withGeoIndex:(o,s)=>(p(t,o,"withGeoIndex","geo"),l(r.withGeoIndex(o,s),n,t))}),O=async(r,n)=>{if(e.lookupById){const f=await e.lookupById(r,n);if(f)return{row:f.row,tableName:i.has(f.tableName)?f.tableName:void 0}}const t=await e.get(r,n);if(!t)return{row:null,tableName:void 0};const o=n!==void 0&&i.has(n)?[n]:[],s=n===void 0?[...i.keys()]:o,c=await Promise.all(s.map(async f=>(await e.findFirst(f,{limit:1,where:{_id:r}}))?._id===r?f:void 0));return{row:t,tableName:c.find(f=>f!==void 0)}},P=(r,n,t)=>{const o=i.get(r);if(!o)return;const s=n.find(c=>typeof c=="string"&&c in o);if(s!==void 0)throw new S("MASK_UNSUPPORTED",`${t}() over masked column "${s}" on "${r}" is not supported`)},A=new Set;for(const r of i.values())for(const n of Object.keys(r))A.add(n);const R=(r,n,t,o)=>{if(!(!r||typeof r!="object"||Array.isArray(r)))for(const[s,c]of Object.entries(r))K(s,c,n,t,o)},K=(r,n,t,o,s)=>{if(r==="AND"||r==="OR"){for(const c of Array.isArray(n)?n:[])R(c,t,o,s);return}if(r==="NOT"){R(n,t,o,s);return}if(!r.startsWith("__")){if(t.has(r))throw new S("MASK_UNSUPPORTED",`${s}() filtering "${o}" by masked column "${r}" is not supported`);if(C(n))for(const c of Object.values(n))R(c,A,`${o}.${r}`,s)}},B=r=>{const n=i.get(r);return n?new Set(Object.keys(n)):new Set},h=(r,n,t)=>{A.size===0||n===void 0||R(n,B(r),r,t)},F=(r,n,t,o)=>{if(Array.isArray(n)){for(const s of n)if(!(!s||typeof s!="object"||Array.isArray(s))){for(const c of Object.keys(s))if(t.has(c))throw new S("MASK_UNSUPPORTED",`${o}() ordering "${r}" by masked column "${c}" is not supported`)}}},$=(r,n,t)=>{if(!(A.size===0||!n||typeof n!="object"||Array.isArray(n)))for(const[o,s]of Object.entries(n)){if(o==="_count"||!s||typeof s!="object"||Array.isArray(s))continue;const c=s,f=`${r}.${o}`;R(c.where,A,f,t),F(f,c.orderBy,A,t),$(f,c.with,t)}},W=(r,n,t)=>{h(r,n?.where,t),h(r,n?.baseWhere,t),F(r,n?.orderBy,B(r),t),$(r,n?.with,t)},v=r=>r&&typeof r=="object"&&!Array.isArray(r)?r:void 0,M=(r,n,t)=>{const o=v(n);h(r,o?.where,t),h(r,o?.baseWhere,t),$(r,o?.with,t)},I={...e,async deleteWhere(r,n,t){if(h(r,n,"deleteMany({ where })"),e.deleteWhere===void 0)throw new S("INTERNAL",`ctx.db.${r}.deleteMany({ where }) is unavailable: this writer has no where-based delete`);return e.deleteWhere(r,n,t)},async patchWhere(r,n,t){if(h(r,n.where,"patchMany({ where })"),e.patchWhere===void 0)throw new S("INTERNAL",`ctx.db.${r}.patchMany({ where }) is unavailable: this writer has no where-based patch`);return e.patchWhere(r,n,t)},aggregate(r,n){return P(r,[n.field],"aggregate"),h(r,n.where,"aggregate"),e.aggregate(r,n)},count(r,n){const t=v(n),o=t&&("where"in t||"baseWhere"in t||"restrictsCounts"in t)?t.where:n;return h(r,o,"count"),t&&h(r,t.baseWhere,"count"),e.count(r,n)},async findFirst(r,n){W(r,n,"findFirst");const t=await e.findFirst(r,k(n)),o=i.get(r);return t&&o?d(t,o,a):t},async findFirstOrThrow(r,n){W(r,n,"findFirstOrThrow");const t=await e.findFirstOrThrow(r,k(n)),o=i.get(r);return o?d(t,o,a):t},async findMany(r,n){W(r,n,"findMany");const t=await e.findMany(r,k(n)),o=i.get(r);return o?j(t,o,a):t},async get(r,n){const{row:t,tableName:o}=await O(r,n),s=o===void 0?void 0:i.get(o);return!t||!s?t:d(t,s,a)},related:e.related?async(r,n)=>await e.related(r,k(n)):void 0,async lookupById(r,n){const t=await e.lookupById?.(r,n);if(!t)return null;const o=i.get(t.tableName);return{row:o?d(t.row,o,a):t.row,tableName:t.tableName}},groupBy(r,n){return P(r,[...n.by,n.agg?.field],"groupBy"),h(r,n.where,"groupBy"),e.groupBy(r,n)},query(r){const n=e.query(r),t=i.get(r);return t?l(n,t,r):n},async rank(r,n,t){return M(r,t,"rank"),p(r,n,"rank","rank"),e.rank(r,n,t)},async rankPage(r,n,t){M(r,t,"rankPage"),p(r,n,"rankPage","rank");const o=await e.rankPage(r,n,t),s=i.get(r);return s?j(o,s,a):o},..._("rankBefore",y,r=>(n,t,o)=>(M(n,o,"rankBefore"),p(n,t,"rankBefore","rank"),r(n,t,o))),..._("rankPageRows",g,r=>async(n,t,o)=>{M(n,o,"rankPageRows"),p(n,t,"rankPageRows","rank");const s=await r(n,t,o),c=i.get(n);return c?{...s,rows:s.rows.map(f=>({...f,doc:d(f.doc,c,a)}))}:s})},q=I;if(A.size>0)for(const[r,n]of Object.entries(e))G(n)&&(q[r]=H(I,r));return I},b=(e,i={})=>{const a=new Map(Object.entries(e)),u=L(i.roles),y=async({ctx:w,next:k})=>{const p={auth:await z(w.auth??{},u),ctx:w};if(i.bypass?.(p)===!0)return k();const l=X(w.db,a,p,i.indexFields),O={db:l},{orm:P}=w;return P!==null&&typeof P=="object"&&(O.orm=J(l)),k({ctx:O})},g=new Map;for(const[w,k]of a)g.set(w,new Set(Object.keys(k)));return Q(y,{columns:g})};export{b as mask};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as W}from"@lunora/errors";import{findRelated as V,whereFilter as ee}from"@lunora/shard-engine";import{i as j}from"./wire-codec-BTOxkE1j.mjs";import{bindTableFacade as te,bindOrm as re}from"./bindOrm-D_hFUjmr.mjs";import{t as ne}from"./policy-tag-V0lqFzgS.mjs";import{deny as se}from"./allowAll-DkRAgItV.mjs";const oe=["every","is","isNot","none","some"],ie=new Set(oe),ae=e=>{if(e===null||typeof e!="object"||Array.isArray(e))return!1;const r=Object.keys(e);return r.length>0&&r.every(n=>ie.has(n))},q=(e,r,n)=>r?{[e]:n(r)}:{},ce=["contains","eq","gt","gte","in","isNull","lt","lte","ne","notIn"],B=-1,v=0,b=1,T=e=>e?b:B,p=(e,r)=>e<r?e:r,le=(e,r)=>e>r?e:r,z=e=>e===v?v:T(e===B),Y=e=>{const r=typeof e;return r==="number"||r==="string"||r==="bigint"},S=e=>e==null,M=(e,r,n)=>{if(n===void 0)throw new W("BAD_REQUEST",`\`${r}\` on "${e}" received undefined; a comparison needs a value`)},fe={gt:(e,r)=>e>r,gte:(e,r)=>e>=r,lt:(e,r)=>e<r,lte:(e,r)=>e<=r},de=(e,r,n)=>{let i=b;for(const c of["gt","gte","lt","lte"]){if(!(c in n))continue;const h=n[c];if(M(e,c,h),!Y(h))i=p(i,B);else if(S(r))i=p(i,v);else{const f=fe[c];i=p(i,T(Y(r)&&f(r,h)))}}return i},K=(e,r,n)=>{if(!Array.isArray(n))throw new W("BAD_REQUEST",`\`${r}\` on "${e}" expects an array of values, received ${n===null?"null":typeof n}`);if(n.includes(void 0))throw new W("BAD_REQUEST",`\`${r}\` on "${e}" received undefined inside its list; a comparison needs a value`);return n},Q=(e,r)=>r.length===0?B:S(e)?v:r.includes(e)?b:r.some(n=>S(n))?v:B,ue=(e,r,n)=>{let i=b;if("in"in n&&(i=p(i,Q(r,K(e,"in",n.in)))),"notIn"in n&&(i=p(i,z(Q(r,K(e,"notIn",n.notIn))))),"contains"in n){const c=n.contains;M(e,"contains",c),i=S(r)?p(i,v):p(i,T(typeof r=="string"&&typeof c=="string"&&r.includes(c)))}return"isNull"in n&&(i=p(i,T(n.isNull===!0===S(r)))),i},F=(e,r,n)=>r===null?T(n===S(e)):S(e)?v:T(n===(e===r)),he=(e,r,n)=>{let i=b;return"eq"in n&&(M(e,"eq",n.eq),i=p(i,F(r,n.eq,!0))),"ne"in n&&(M(e,"ne",n.ne),i=p(i,F(r,n.ne,!1))),i},ye=(e,r,n)=>p(he(e,r,n),p(ue(e,r,n),de(e,r,n))),we=(e,r,n,i)=>{if(r==="NOT")return z(i(e,n??{}));if(!Array.isArray(n))return B;let c=r==="AND"?b:B;for(const h of n){const f=i(e,h);c=r==="AND"?p(c,f):le(c,f)}return c},H=e=>e==="AND"||e==="OR"||e==="NOT",pe=e=>j(e)&&Object.keys(e).every(r=>ce.includes(r)),C=e=>Object.keys(e).some(r=>{const n=e[r];return H(r)?r==="NOT"?C(n??{}):Array.isArray(n)&&n.some(i=>C(i??{})):ae(n)}),G=(e,r)=>{let n=b;for(const i of Object.keys(r)){const c=r[i];if(H(i)){n=p(n,we(e,i,c,G));continue}const h=e[i];if(pe(c)){n=p(n,ye(i,h,c));continue}M(i,"eq",c),n=p(n,F(h,c,!0))}return n},L=(e,r)=>G(e,r)===b,X=500,I=(e,r,n)=>{const i=r??X;if(e>i)throw new W("BATCH_LIMIT_EXCEEDED",`${n}: batch of ${String(e)} exceeds the limit of ${String(i)} (raise options.limit or chunk the call)`,{status:400})},ge=se(),We=Symbol.for("lunora.ctxdb.rls-unwrap"),J=Symbol.for("lunora.rls.wrapped-chain"),Oe=e=>e[J],Re=e=>{const r=new Map;for(const n of e){const i=r.get(n.table)??[];i.push(n),r.set(n.table,i)}return r},be=(e,r)=>{const n=[];let i=!1;for(const c of e){if(c.on!=="read")continue;const h=c.when(r);if(h!==void 0){if(h===!0){i=!0;break}h!==!1&&n.push(h)}}if(!i)return n.length===0?ge:n.length===1?n[0]:{OR:n}},Ae=(e,r,n)=>{const i=e.when({...r,row:n});if(i===void 0||i===!0)return!0;if(i===!1)return!1;if(C(i))throw new W("RELATION_PREDICATE_UNSUPPORTED","relation predicates are not supported in write policies; use a read policy or a flat column check");return L(n,i)},Ee=(e,r,n)=>{const i=e.when(r);if(i===void 0||i===!0)return n===void 0||Ae(e,r,n);if(i===!1)return!1;if(C(i))throw new W("RELATION_PREDICATE_UNSUPPORTED","relation predicates are not supported in write policies; use a read policy or a flat column check");return!r.row||!L(r.row,i)?!1:n===void 0||L(n,i)},Be=(e,r,n,i)=>{let c=!1;for(const h of e)if(h.on===r&&(c=!0,!Ee(h,n,i)))return!1;return c},ve=new Set(["baseWhere","relationBaseWhere","restrictsCounts","where"]),Se=(e,r)=>r===void 0?!0:e==="restrictsCounts"?typeof r=="boolean":e==="relationBaseWhere"?typeof r=="function":j(r),_e=e=>{const r=Object.keys(e);return r.length===0?!1:r.every(n=>ve.has(n)&&Se(n,e[n]))},ke=e=>e===void 0?{}:j(e)&&_e(e)?e:{where:e},$=e=>e!==void 0&&Object.keys(e).length>0,Ie=e=>{if(e.length!==0)return e.length===1?e[0]:{AND:e}},R=(e,r)=>$(r)?!e||Object.keys(e).length===0?r:{AND:[r,e]}:e,Te=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return!1;const r=e;return typeof r.findMany=="function"&&typeof r.withSearchIndex=="function"},Me=(e,r,n)=>{const[i]=n,c=n.length===1&&i!==void 0?i.perTable:new Set(n.flatMap(t=>[...t.perTable.keys()])),h=new Map,f=t=>{const s=h.get(t);if(s)return s;const o=[];let a=!1;for(const y of n){const u=y.perTable.get(t);if(!u||u.length===0||!u.some(m=>m.on==="read"))continue;a=!0;const d=be(u,y.context);d!==void 0&&o.push(d)}const l={baseWhere:Ie(o),restricts:a};return h.set(t,l),l},_=(t,s,o,a)=>{for(const l of n){const y=l.perTable.get(t);if(y&&!Be(y,s,{...l.context,row:o},a))return!1}return!0},w=t=>f(t).restricts?r:e,g=t=>f(t).baseWhere,A=async(t,s,o)=>{if(r.lookupById){const d=await r.lookupById(t,s);if(d)return{row:d.row,tableName:c.has(d.tableName)?d.tableName:void 0}}const a=await r.get(t,s);if(!a)return{row:null,tableName:void 0};const l=s??o,y=l===void 0?[...c.keys()]:[l].filter(d=>c.has(d)),u=await Promise.all(y.map(async d=>(await r.findFirst(d,{limit:1,where:{_id:t}}))?._id===t?d:void 0));return{row:a,tableName:u.find(d=>d!==void 0)}},U=async(t,s,o)=>{const a=await A(t,s,o);return a.row&&a.tableName!==void 0?{row:a.row,tableName:a.tableName}:void 0},O=async(t,s,o,a,l,y)=>{const u=await U(t,l,y);if(!u)return o(e);const d=a?a(u.row):void 0;if(!_(u.tableName,s,u.row,d))throw new W("FORBIDDEN",`${s} denied by policy`);return o(r)},E=(t,s)=>{const{baseWhere:o}=f(t);if($(o))throw new W("COUNT_RLS_UNSUPPORTED",`${s}() is not supported on "${t}" inside an RLS-restricted context`)},D=e.rankBefore,P=e.rankPageRows,{relationEdges:N}=e,k={...e,async count(t,s){const{baseWhere:o}=f(t),a=ke(s);return w(t).count(t,{...a,baseWhere:R(a.baseWhere,o),relationBaseWhere:g,restrictsCounts:(a.restrictsCounts??!1)||$(o)})},delete:(t,s,o)=>O(t,"delete",a=>a.delete(t,s,o),void 0,s),async deleteAll(t,s){const o=Math.max(1,s?.chunkSize??X),{baseWhere:a}=f(t);let l=0;for(;;){const u=(await w(t).findMany(t,{baseWhere:a,limit:o,relationBaseWhere:g})).page.map(d=>String(d._id));if(u.length===0)break;for(const d of u)await O(d,"delete",m=>m.delete(d,void 0,s?.hard===void 0?void 0:{hard:s.hard}),void 0,void 0,t),l+=1;if(u.length<o)break}return{deleted:l}},async deleteMany(t,s,o){I(t.length,s?.limit,"deleteMany");for(const a of t)await O(a,"delete",l=>l.delete(a,o),void 0,o);return{deleted:t.length}},async deleteWhere(t,s,o){const{baseWhere:a}=f(t),y=(await w(t).findMany(t,{baseWhere:R(s,a),relationBaseWhere:g})).page.map(u=>String(u._id));I(y.length,o?.limit,"deleteWhere");for(const u of y)await O(u,"delete",d=>d.delete(u),void 0,void 0,t);return{deleted:y.length}},async findFirst(t,s){const{baseWhere:o}=f(t);return w(t).findFirst(t,{...s,baseWhere:R(s?.baseWhere,o),relationBaseWhere:g})},async findFirstOrThrow(t,s){const{baseWhere:o}=f(t);return w(t).findFirstOrThrow(t,{...s,baseWhere:R(s?.baseWhere,o),relationBaseWhere:g})},async findMany(t,s){const{baseWhere:o}=f(t);return w(t).findMany(t,{...s,baseWhere:R(s?.baseWhere,o),relationBaseWhere:g})},async get(t,s){const o=await A(t,s);if(!o.row)return null;if(o.tableName===void 0)return e.get(t,s);const{baseWhere:a,restricts:l}=f(o.tableName);if(!l)return e.get(t,s);if(!a)return o.row;const y=await r.findFirst(o.tableName,{baseWhere:a,limit:1,where:{_id:t}});return y?._id===t?y:null},async lookupById(t,s){const o=await A(t,s);if(!o.row)return null;if(o.tableName===void 0||!f(o.tableName).restricts)return await e.lookupById?.(t,s)??null;const{baseWhere:a}=f(o.tableName);if(!a)return{row:o.row,tableName:o.tableName};const l=await r.findFirst(o.tableName,{baseWhere:a,limit:1,where:{_id:t}});return l?._id===t?{row:l,tableName:o.tableName}:null},async insert(t,s){if(c.has(t)){if(!_(t,"insert",s))throw new W("FORBIDDEN",`insert on "${t}" denied by policy`);return r.insert(t,s)}return e.insert(t,s)},async insertMany(t,s,o){if(I(s.length,o?.limit,"insertMany"),c.has(t)){for(const a of s)if(!_(t,"insert",a))throw new W("FORBIDDEN",`insert on "${t}" denied by policy`);return r.insertMany(t,s,o)}return e.insertMany(t,s,o)},async insertManyUnsafe(t,s,o){if(I(s.length,o?.limit,"insertManyUnsafe"),c.has(t)){for(const a of s)if(!_(t,"insert",a))throw new W("FORBIDDEN",`insert on "${t}" denied by policy`);return r.insertManyUnsafe(t,s,o)}return e.insertManyUnsafe(t,s,o)},patch:(t,s,o)=>O(t,"update",a=>a.patch(t,s,o),a=>({...a,...s}),o),async patchMany(t,s,o){I(t.length,s?.limit,"patchMany");for(const a of t)await O(a.id,"update",l=>l.patch(a.id,a.patch,o),l=>({...l,...a.patch}),o);return{patched:t.length}},async patchWhere(t,s,o){const{baseWhere:a}=f(t),y=(await w(t).findMany(t,{baseWhere:R(s.where,a),relationBaseWhere:g})).page.map(u=>({id:String(u._id),patch:s.patch}));return I(y.length,o?.limit,"patchWhere"),k.patchMany(y,o)},query(t){const{baseWhere:s}=f(t),o=w(t).query(t);return s?o.filter(ee(s,a=>L(a,s))):o},related:N===void 0?void 0:async(t,s)=>V({findMany:async(o,a)=>k.findMany(o,a),lookupById:async o=>r.lookupById?.(o)},N,t,{cursor:s?.cursor,depth:s?.depth,direction:s?.direction,edges:s?.edges,limit:s?.limit,relationMask:s?.relationMask}),restore:(t,s)=>O(t,"update",async o=>{const a=o.restore??r.restore;if(!a)throw new W("BAD_REQUEST","restore is not supported by this writer");await a(t,s)},void 0,s),replace:(t,s,o)=>O(t,"update",a=>a.replace(t,s,o),a=>({...s,_creationTime:s._creationTime??a._creationTime,_id:a._id}),o),aggregate(t,s){const{baseWhere:o}=f(t);return w(t).aggregate(t,{...s,baseWhere:R(s.baseWhere,o),relationBaseWhere:g})},groupBy(t,s){const{baseWhere:o}=f(t);return w(t).groupBy(t,{...s,baseWhere:R(s.baseWhere,o),relationBaseWhere:g})},rank(t,s,o){return E(t,"rank"),w(t).rank(t,s,o)},rankPage(t,s,o){return E(t,"rankPage"),w(t).rankPage(t,s,o)},wipeShard(){throw new W("FORBIDDEN","ctx.db.wipeShard() is unavailable under rls(): a whole-shard erase can't be policy-gated per row, and erasing only policy-visible rows would silently leave data behind. Run it from an internalMutation, or use ctx.db.deleteAll(table) per table.",{status:403})},...q("rankBefore",D,t=>(s,o,a)=>(E(s,"rankBefore"),(w(s).rankBefore??t)(s,o,a))),...q("rankPageRows",P,t=>(s,o,a)=>(E(s,"rankPageRows"),(w(s).rankPageRows??t)(s,o,a)))},x=k;if(c.size>0)for(const[t,s]of Object.entries(e))Te(s)&&(x[t]=te(k,t));return Object.defineProperty(k,J,{configurable:!0,enumerable:!1,value:{base:e,raw:r,steps:n},writable:!1}),k},Z=e=>typeof e=="string"?e:e.name,De=e=>{const r=new Map;for(const n of e??[])r.set(n.name,new Set((n.permissions??[]).map(i=>Z(i))));return r},Pe=(e,r)=>{const n=new Set;for(const i of e)for(const c of r.get(i)??[])n.add(c);return i=>n.has(Z(i))},me=["roles","role"],Ce=e=>{for(const r of me){const n=e?.[r];if(typeof n=="string"){const i=n.split(",").map(c=>c.trim()).filter(c=>c.length>0);if(i.length>0)return i}if(Array.isArray(n)){const i=n.filter(c=>typeof c=="string"&&c.length>0);if(i.length>0)return i}}return[]},Le=async(e,r)=>{const n=await e.getIdentity?.()??null,i=[...new Set([...Ce(n),...e.roles??[]])];return{can:Pe(i,r),identity:n,roles:i,userId:e.userId??null}},Ye=(e,r={})=>{const n=e,i=Re(n),c=De(r.roles);return ne(async({ctx:f,next:_})=>{const w={auth:await Le(f.auth??{},c),ctx:f},g=f.db,A=Oe(g),U=A?.base??g,O=A?.raw??g[We]??g,E=Me(U,O,[...A?.steps??[],{context:w,perTable:i}]),D={db:E},{orm:P}=f;return P!==null&&typeof P=="object"&&(D.orm=re(E)),_({ctx:D})},[{policies:n,roles:r.roles??[]}])};export{Le as a,Te as b,ae as c,Ce as d,Pe as e,be as f,Be as g,De as i,L as m,q as o,Z as p,Ye as r};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as s}from"@lunora/errors";import{c as Q}from"./compose-middleware-DNvrHMHx.mjs";import{v as B}from"@lunora/values";const q=["de","en","es","fr","it","nl","none","pt"],F=["native","portable"],V=e=>F.includes(e),X=e=>q.includes(e),U=e=>{const{value:t}=e._meta??{};if(t===null)return"null";switch(typeof t){case"bigint":case"boolean":case"number":case"string":return typeof t;default:return e.kind}},P=e=>{if(e.kind==="literal")return U(e);if(e.kind!=="optional")return e.kind;const t=e._meta?.inner;return t?P(t):e.kind},G=(e,t)=>`table "${e}" is .global() and declares vector index "${t}". Vector sync runs on the shard write path, which a global (D1/Hyperdrive) table's writes never take — the index would stay empty. Drop .global(), or keep the index yourself with ctx.vectors.upsert/deleteByIds.`,j=16,Y={many:(e,t)=>({field:t.field,kind:"many",references:t.references??"_id",table:e}),one:(e,t)=>({field:t.field,kind:"one",onDelete:t.onDelete,references:t.references??"_id",table:e})},g=(e,t,n)=>({handler:n,op:t,timing:e}),J=()=>({afterDelete:e=>g("after","delete",e),afterInsert:e=>g("after","insert",e),afterUpdate:e=>g("after","update",e),beforeDelete:e=>g("before","delete",e),beforeInsert:e=>g("before","insert",e),beforeUpdate:e=>g("before","update",e)}),C=(e,t)=>{if(!t||t.length===0)throw new s("INTERNAL",`rankIndex "${e}": "sortBy" is required and must list at least one key`);return t.map(n=>({direction:n.direction??"asc",field:n.field}))},ge=e=>{const t={...e},n=[],r=[],a=[],d=[],u={},c=[],h={},f=J(),b=[];let w={kind:"root"},E=!1,$=!1,p=!1,T=!1,M=!1,L,A,O,R;const D=i=>{if(w.kind!=="root"&&w.kind!==i.kind)throw new s("INTERNAL","shardBy/global: a table cannot be both .shardBy(key) and .global() — pick one. .shardBy(key) puts the rows in one Durable Object per key (isolation, poke-live reactivity); .global() puts them in a single replicated backend read from the edge.");w=i},l={aggregateIndex(i,o){const m=o?.op??"count";if(m!=="count"&&!o?.field)throw new s("INTERNAL",`aggregateIndex "${i}": op "${m}" requires a "field"`);return n.push({by:o?.by,field:o?.field,name:i,on:"",op:m,where:o?.where}),l},get aggregateIndexes(){return n},get externalSource(){return R},commitOrdered(){return E=!0,l},get commitOrderedMode(){return E},dropStalePatches(){return $=!0,l},get dropStalePatchesMode(){return $},externallyManaged(){return p=!0,l},geoIndex(i,o){return r.push({field:o.field,name:i,precision:o.precision}),l},get geoIndexes(){return r},global(i){return D({backend:i?.backend??"d1",kind:"global"}),l},get isExternallyManaged(){return p},get isPublic(){return M},index(i,o,m){return a.push({fields:o,name:i,unique:m?.unique??!1}),l},get indexes(){return a},memory(){return T=!0,l},get memoryMode(){return T},ownedBy(i){return L=i,l},get ownerField(){return L},public(){return M=!0,l},rankIndex(i,o){return d.push({name:i,on:"",partitionBy:o.partitionBy,sortBy:C(i,o.sortBy),where:o.where}),l},get rankIndexes(){return d},get relationMap(){return u},relations(i){return Object.assign(u,i(Y)),l},searchIndex(i,o){if(o.filterFields&&o.filterFields.length>j)throw new s("INTERNAL",`searchIndex "${i}": at most ${String(j)} filterFields are supported (got ${String(o.filterFields.length)})`);const{language:m}=o;if(m!==void 0&&!X(m))throw new s("INTERNAL",`searchIndex "${i}": unknown language "${m}" (supported: ${q.join(", ")})`);const{strategy:N}=o;if(N!==void 0&&!V(N))throw new s("INTERNAL",`searchIndex "${i}": unknown strategy "${N}" (supported: ${F.join(", ")})`);return c.push({field:o.field,filterFields:o.filterFields,language:o.language,name:i,staged:o.staged,strategy:o.strategy}),l},get searchIndexes(){return c},shape:t,shardBy(i){return D({field:i,kind:"shardBy"}),l},get shardMode(){return w},get softDeleteMode(){return A},source(i){if(!i.binding)throw new s("INTERNAL","source: `binding` is required (the wrangler Hyperdrive binding name)");if(!i.query)throw new s("INTERNAL","source: `query` is required (the tenant-membership SQL)");return R=i,p=!0,l},softDelete(i){const o=i?.field??"deletedAt";return A={field:o},o in t||(t[o]=B.optional(B.number().nullable())),l},get triggerMap(){return h},triggers(i){return Object.assign(h,i(f)),l},ttl(i,o){return O={after:o?.after,field:i},l},get ttlPolicy(){return O},get vectorIndexes(){return b},vectorize(i,o){return b.push({dimensions:o.dimensions,embed:o.embed,field:i,metadata:o.metadata,metric:o.metric,model:o.model,name:o.index}),l}};return l},be=e=>({dimensions:e.dimensions,embed:e.embed,kind:"vectorIndex",metadata:e.metadata,metric:e.metric,model:e.model,select:e.source.select,table:e.source.table}),we=(e,t)=>{const n=t.op??"count";if(n!=="count"&&!t.field)throw new s("INTERNAL",`aggregateIndex "${e}": op "${n}" requires a "field"`);return{by:t.by,field:t.field,name:e,on:t.on,op:n,where:t.where}},xe=(e,t)=>({name:e,on:t.table,partitionBy:t.partitionBy,sortBy:C(e,t.sortBy),where:t.where}),y=e=>({...e,extend(t){return y(z(e,t))},jurisdiction(t){return y(e)},rls(t){return y({...e,rlsMode:t})}}),W=e=>{for(const[t,n]of Object.entries(e))for(const r of[...n.aggregateIndexes,...n.rankIndexes])r.on===""&&(r.on=t)},Z=(e,t,n)=>{for(const r of Object.values(t)){const a=e[r.on];if(!a)throw new s("INTERNAL",`defineAggregateIndex "${r.name}": unknown table "${r.on}"`);a.aggregateIndexes.push(r)}for(const r of Object.values(n)){const a=e[r.on];if(!a)throw new s("INTERNAL",`defineRankIndex "${r.name}": unknown table "${r.on}"`);a.rankIndexes.push(r)}},ee=e=>{if(e.cursor)return"cursor";if(e.reconcileEveryMs!==void 0)return"reconcileEveryMs";if(e.softDeleteColumn!==void 0)return"softDeleteColumn"},te=(e,t)=>{const n=t.mode==="incremental";if(t.mode!==void 0&&t.mode!=="full-pull"&&!n)throw new s("INTERNAL",`defineSchema: table "${e}" uses \`mode: ${JSON.stringify(t.mode)}\` — supported modes are "full-pull" (default) and "incremental".`);if(!n){const r=ee(t);if(r)throw new s("INTERNAL",`defineSchema: table "${e}" sets \`${r}\` but is not \`mode: "incremental"\` — that knob only applies to incremental ingest. Set \`mode: "incremental"\` or remove \`${r}\`.`);return}if(!t.cursor?.column||!t.cursor.query)throw new s("INTERNAL",`defineSchema: table "${e}" is \`mode: "incremental"\` but has no \`cursor\` — add \`cursor: { column: "updated_at", query: "… WHERE … > $N" }\` binding the watermark as the trailing parameter.`);if(t.reconcileEveryMs===void 0&&t.softDeleteColumn===void 0)throw new s("INTERNAL",`defineSchema: table "${e}" is \`mode: "incremental"\` with no delete-visibility path — an incremental pull never sees upstream deletes, so it would accumulate phantom rows. Add \`reconcileEveryMs\` (a periodic full-pull sweep) or \`softDeleteColumn\` (an upstream tombstone column).`)},ne=e=>{for(const[t,n]of Object.entries(e)){const r=n.externalSource;if(r){if(n.shardMode.kind==="global")throw new s("INTERNAL",`defineSchema: table "${t}" cannot be both .source() and .global() — a sourced table materializes into a shard DO's SQLite, a global table lives in the external tier`);if(n.shardMode.kind==="shardBy"&&!r.tenantBy)throw new s("INTERNAL",`defineSchema: sourced + .shardBy() table "${t}" needs a \`tenantBy\` mapper — without it every tenant's DO would run the same unscoped query and replicate the whole multitenant table (a cross-tenant leak). Add \`tenantBy: (shardKey) => [shardKey]\` binding the shard key into the query's parameters.`);te(t,r)}}},re=["_commitSeq","_creationTime","_id"],_="_commitSeq",ae=new Set(re),x=(e,t,n,r)=>{if(!(ae.has(n)||n in r.shape))throw new s("INTERNAL",`defineSchema: table "${e}" index "${t}" names column "${n}" which is not in the table's shape`)},v=(e,t,n,r)=>{const a=new Set;for(const d of n){if(a.has(d.name))throw new s("INTERNAL",`defineSchema: table "${e}" declares ${t} "${d.name}" more than once`);a.add(d.name),r(d)}},K=e=>{for(const[t,n]of Object.entries(e))v(t,"index",n.indexes,r=>{for(const a of r.fields)x(t,r.name,a,n)}),v(t,"rank index",n.rankIndexes,r=>{for(const a of r.sortBy)x(t,r.name,a.field,n);for(const a of r.partitionBy??[])x(t,r.name,a,n)}),v(t,"geo index",n.geoIndexes,r=>{x(t,r.name,r.field,n)})},S=(e,t,n)=>{if(e.length===0)return;const r={};for(const a of e)r[t(a)]=n(a);return r},oe=e=>{const t=new Set(e.sortBy.map(n=>n.field));for(const n of e.partitionBy??[])t.add(n);return[...t]},ye=e=>{const t={};for(const[n,r]of Object.entries(e.tables)){const a=S(r.geoIndexes,c=>c.name,c=>[c.field]),d=S(r.indexes,c=>c.name,c=>c.fields),u=S(r.rankIndexes,c=>c.name,oe);(a||d||u)&&(t[n]={...a?{geo:a}:{},...d?{index:d}:{},...u?{rank:u}:{}})}return t},ie=e=>{for(const[t,n]of Object.entries(e)){if(!n.memoryMode)continue;const a=[[n.shardMode.kind==="global",".global() — those rows live in D1, which this shard does not own and cannot clear"],[n.commitOrderedMode===!0,".commitOrdered() — the counter resets with the table, so the sequence would restart and a consumer's cursor would silently skip everything after it"],[n.externalSource!==void 0,".source() — the table is materialized by the ingest loop, so wiping it on every eviction would fight the puller"],[n.searchIndexes.length>0,".searchIndex() — the FTS shadow is a separate table that clearing the rows would leave stale"],[n.geoIndexes.length>0,".geoIndex() — the geohash companion is a separate table that clearing the rows would leave stale"],[n.aggregateIndexes.length>0,".aggregateIndex() — the counter companion is a separate table that clearing the rows would leave stale"],[n.rankIndexes.length>0,".rankIndex() — the rank companion is a separate table that clearing the rows would leave stale"],[n.vectorIndexes.length>0,".vectorize() — vectors live in an external index that a shard restart cannot clear"]].find(([d])=>d)?.[1];if(a!==void 0)throw new s("INTERNAL",`defineSchema: table "${t}" is both .memory() and ${a}. Plain .index() is supported; SQLite maintains it through the DELETE.`)}},se=e=>{for(const[t,n]of Object.entries(e))if(n.shardMode.kind==="global"){for(const[r,a]of Object.entries(n.shape))if(P(a)==="bigint")throw new s("INTERNAL",`defineSchema: table "${t}" is .global() and column "${r}" is v.bigint(). A global (D1/Hyperdrive) table stores a bigint as decimal TEXT, which SQL compares lexicographically — "100" sorts before "25" — so \`orderBy\`, range filters and \`aggregate\` on this column would silently return wrong results. Use v.number() if the value fits a double, or v.string() if you only need equality.`)}},de=e=>{for(const[t,n]of Object.entries(e))if(n.dropStalePatchesMode===!0&&n.shardMode.kind==="global")throw new s("INTERNAL",`defineSchema: table "${t}" is both .global() and .dropStalePatches(). The stale check reads the caller's baseline out of the shard's \`__cdc_log\`, which a global (D1/Hyperdrive) table has no entries in — so every patch would read as "no baseline" and apply unchanged. Drop one of the two.`)},H=(e,t)=>{const n=[...Object.entries(e).flatMap(([r,a])=>a.vectorIndexes.map(d=>[r,d.name])),...Object.entries(t).map(([r,a])=>[a.table,r])];for(const[r,a]of n)if(e[r]?.shardMode.kind==="global")throw new s("INTERNAL",`defineSchema: ${G(r,a)}`)},le=e=>{for(const[t,n]of Object.entries(e)){if(n.commitOrderedMode){if(n.shardMode.kind==="global")throw new s("INTERNAL",`defineSchema: table "${t}" is both .global() and .commitOrdered(). \`_commitSeq\` is allocated inside the shard's write transaction, which a global (D1/Hyperdrive) table does not share — so the stamp would carry no commit-ordering guarantee. Drop one of the two.`);continue}for(const r of n.indexes)if(r.fields.includes(_))throw new s("INTERNAL",`defineSchema: table "${t}" index "${r.name}" names "${_}", but the table is not .commitOrdered() — no row carries that field, so the index would never match. Add .commitOrdered(), or drop the column from the index.`)}},Ie=(e,t={},n={},r={})=>(W(e),Z(e,n,r),ne(e),le(e),de(e),se(e),H(e,t),ie(e),K(e),y({tables:e,vectorIndexes:t})),I=(e,t)=>`${e}_${t}`,k=(e,t,n)=>n.has(e)?I(t,e):e,ce=(e,t,n,r)=>{const a=I(t,r),d=f=>f===""?a:k(f,t,n),u={};for(const[f,b]of Object.entries(e.relationMap))u[f]={...b,table:k(b.table,t,n)};const c=e.aggregateIndexes.map(f=>({...f,on:d(f.on)})),h=e.rankIndexes.map(f=>({...f,on:d(f.on)}));return{...e,aggregateIndexes:c,rankIndexes:h,relationMap:u}},pe=(e,t)=>{if(!e)throw new s("INTERNAL","defineSchemaExtension: `key` is required and must be a non-empty string");return{key:e,tables:t.tables,...t.vectorIndexes?{vectorIndexes:t.vectorIndexes}:{}}},ue=((e,t)=>{if(!e)throw new s("INTERNAL","definePlugin: `key` is required and must be a non-empty string");if(t.extension&&t.extension.key!==e)throw new s("INTERNAL",`definePlugin("${e}"): extension key "${t.extension.key}" does not match plugin key`);return{key:e,...t.extension?{extension:t.extension}:{},...t.middleware?{middleware:t.middleware}:{}}}),Ne=(e,t)=>({...ue(e,{...t.extension?{extension:t.extension}:{},...t.middleware?{middleware:t.middleware}:{}}),functions:t.functions??{}}),z=(e,t)=>{const{key:n}=t,r=new Set(Object.keys(t.tables)),a={...e.tables};for(const[u,c]of Object.entries(t.tables)){const h=I(n,u);if(Object.hasOwn(a,h))throw new s("INTERNAL",`defineSchema(...).extend("${n}"): table "${h}" already exists in the base schema — another extension with the same key already contributed it`);a[h]=ce(c,n,r,u)}const d={...e.vectorIndexes};if(t.vectorIndexes)for(const[u,c]of Object.entries(t.vectorIndexes)){const h=I(n,u);if(Object.hasOwn(d,h))throw new s("INTERNAL",`defineSchema(...).extend("${n}"): vector index "${h}" already exists in the base schema — another extension with the same key already contributed it`);d[h]={...c,table:k(c.table,n,r)}}return K(a),H(a,d),{rlsMode:e.rlsMode,tables:a,vectorIndexes:d}},ve=(e,t)=>{let n=e;for(const r of t)r.extension&&(n=z(n,r.extension));return n},Se=e=>{const t=e.map(n=>n.middleware).filter(n=>n!==void 0);return Q(t)};export{Ne as a,ue as b,Se as c,we as d,xe as e,Ie as f,pe as g,ge as h,be as i,ye as j,ve as k,K as l,z as m,H as v};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import"./wire-codec-BTOxkE1j.mjs";import"./bindOrm-D_hFUjmr.mjs";import{f as t,g as m,i as p,b as l,m as d,p as n,d as c,e as h,a as u,r as v}from"./middleware-
|
|
1
|
+
import"./wire-codec-BTOxkE1j.mjs";import"./bindOrm-D_hFUjmr.mjs";import{f as t,g as m,i as p,b as l,m as d,p as n,d as c,e as h,a as u,r as v}from"./middleware-Buo4tz8M.mjs";import"./policy-tag-V0lqFzgS.mjs";import"./allowAll-DkRAgItV.mjs";export{t as computeReadBaseWhere,m as evaluateWrite,p as indexRolePermissions,l as isFacadeEntry,d as matchesWhere,n as permissionName,c as readIdentityRoles,h as resolveCan,u as resolvePolicyAuth,v as rls};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as A}from"@lunora/errors";import{i as U,a as $}from"./middleware-
|
|
1
|
+
import{LunoraError as A}from"@lunora/errors";import{i as U,a as $}from"./middleware-Buo4tz8M.mjs";const N=(e,t,o)=>{const a=s=>o.isAllowed("list",s,t)&&o.isAllowed("read",s,t),{get:r,query:b}=e,l={...e},w=s=>s.filter(n=>typeof n.key=="string"&&a(n.key));return typeof r=="function"&&(l.get=async(s,n)=>(s==="_storage"&&o.assertAllowed("read",n,t),r(s,n))),typeof b=="function"&&(l.query=s=>{const n=b(s),{collect:p}=n;return s!=="_storage"||typeof p!="function"?n:{...n,collect:async()=>w(await p())}}),l},S=(e,t)=>{if(e===void 0)return!0;const o=e.endsWith("/")?e.slice(0,-1):e;return o===""||t===o||t.startsWith(`${o}/`)},D=e=>{const t=e[1],o=typeof t=="object"&&t!==null?t.method:void 0;return typeof o=="string"&&o.toUpperCase()==="PUT"?"write":"read"},E=[["delete","delete"],["deleteAfterCommit","delete"],["download","read"],["generateUploadUrl","write"],["getMetadata","read"],["getSignedUrl",D],["getUrl","read"],["head","read"],["store","write"]],M=(e,t)=>{try{return e(t).bucketName===t}catch{return!1}},P=(e,t)=>{const o=e.bucketName??"default",{bucket:a}=e;for(const r of new Set(t))if(!(r===o||typeof a=="function"&&M(a,r)))throw new A("INTERNAL",`storageRules: rule for bucket "${r}" governs nothing — this request's storage cannot address that bucket (the accessor is "${o}", and selecting "${r}" does not reach a bucket of that name). A rule on an unaddressable bucket leaves the operation it was written to gate wide open. Match the rule's \`bucket\` to the name the binding is registered under in \`.storage({ bucket, buckets })\`.`)},C=(e,t={})=>{const o=U(t.roles);return async({ctx:a,next:r})=>{const b=await $(a.auth??{},o),l=(c,u,d)=>{const h=e.filter(i=>i.on===c&&i.bucket===d);if(h.length===0)return!0;const f={auth:b,ctx:a,key:u};return h.some(i=>S(i.prefix,u)&&i.when(f)===!0)},w=(c,u,d)=>{if(!l(c,u,d))throw new A("FORBIDDEN",`storage ${c} on "${u}" in bucket "${d}" denied by access rule`)},s=c=>{const u=c.bucketName??"default",d={bucketName:u};for(const[f,i]of E){const k=c[f];typeof k=="function"&&(d[f]=(...y)=>{const R=typeof y[0]=="string"?y[0]:"",v=typeof i=="function"?i(y):i;return w(v,R,u),k(...y)})}const{bucket:h}=c;return typeof h=="function"&&(d.bucket=f=>s(h(f))),d},n=a.storage;if(n===void 0)return r();P(n,e.map(c=>c.bucket));const p={storage:s(n)},g=a.db,m=g?.system;return g!==void 0&&m!==void 0&&typeof m=="object"&&(p.db={...g,system:N(m,n.bucketName??"default",{assertAllowed:w,isAllowed:l})}),r({ctx:p})}};export{C as storageRules};
|
package/dist/rls/testing.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{i as y,d as P,e as W,f as v,m as I,g as R}from"../packem_shared/middleware-
|
|
1
|
+
import{i as y,d as P,e as W,f as v,m as I,g as R}from"../packem_shared/middleware-Buo4tz8M.mjs";const p=(m,o={})=>{const h=y(o.roles),x=o.ctx??{};return{as:f=>{const c=f??{},i=c.identity??null,l=P(i),u={auth:{can:W(l,h),identity:i,roles:l,userId:c.userId??null},ctx:x},d=(e,r,t,a)=>{const s=m.filter(n=>n.table===r);if(s.length===0)return!0;if(e==="read"){if(!s.some(b=>b.on==="read"))return!0;const n=v(s,u);return n===void 0||I(t??{},n)}return R(s,e,{...u,row:t},a)};return{can:d,cannot:(e,r,t,a)=>!d(e,r,t,a)}}}};export{p as expectPolicy};
|
package/dist/types.d.mts
CHANGED
|
@@ -348,6 +348,8 @@ interface TableVectorIndex {
|
|
|
348
348
|
field: string;
|
|
349
349
|
metadata?: ReadonlyArray<string>;
|
|
350
350
|
metric: VectorMetric;
|
|
351
|
+
/** Declared embedding model; see `VectorizeOptions.model`. */
|
|
352
|
+
model?: string;
|
|
351
353
|
name: string;
|
|
352
354
|
}
|
|
353
355
|
interface TableDefinition<Shape extends Record<string, Validator> = Record<string, Validator>> {
|
|
@@ -485,6 +487,8 @@ interface VectorIndexDefinition {
|
|
|
485
487
|
readonly kind: "vectorIndex";
|
|
486
488
|
readonly metadata?: (row: Record<string, unknown>) => Record<string, unknown>;
|
|
487
489
|
readonly metric: VectorMetric;
|
|
490
|
+
/** Declared embedding model; see `VectorIndexOptions.model`. */
|
|
491
|
+
readonly model?: string;
|
|
488
492
|
readonly select: (row: Record<string, unknown>) => string;
|
|
489
493
|
readonly table: string;
|
|
490
494
|
}
|
package/dist/types.d.ts
CHANGED
|
@@ -348,6 +348,8 @@ interface TableVectorIndex {
|
|
|
348
348
|
field: string;
|
|
349
349
|
metadata?: ReadonlyArray<string>;
|
|
350
350
|
metric: VectorMetric;
|
|
351
|
+
/** Declared embedding model; see `VectorizeOptions.model`. */
|
|
352
|
+
model?: string;
|
|
351
353
|
name: string;
|
|
352
354
|
}
|
|
353
355
|
interface TableDefinition<Shape extends Record<string, Validator> = Record<string, Validator>> {
|
|
@@ -485,6 +487,8 @@ interface VectorIndexDefinition {
|
|
|
485
487
|
readonly kind: "vectorIndex";
|
|
486
488
|
readonly metadata?: (row: Record<string, unknown>) => Record<string, unknown>;
|
|
487
489
|
readonly metric: VectorMetric;
|
|
490
|
+
/** Declared embedding model; see `VectorIndexOptions.model`. */
|
|
491
|
+
readonly model?: string;
|
|
488
492
|
readonly select: (row: Record<string, unknown>) => string;
|
|
489
493
|
readonly table: string;
|
|
490
494
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/server",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.144",
|
|
4
4
|
"description": "Server primitives for Lunora: defineSchema, defineTable, query, mutation, and action",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"backend",
|
|
@@ -67,8 +67,8 @@
|
|
|
67
67
|
},
|
|
68
68
|
"dependencies": {
|
|
69
69
|
"@lunora/errors": "1.0.0-alpha.41",
|
|
70
|
-
"@lunora/scheduler": "1.0.0-alpha.
|
|
71
|
-
"@lunora/shard-engine": "1.0.0-alpha.
|
|
70
|
+
"@lunora/scheduler": "1.0.0-alpha.85",
|
|
71
|
+
"@lunora/shard-engine": "1.0.0-alpha.84",
|
|
72
72
|
"@lunora/values": "1.0.0-alpha.51",
|
|
73
73
|
"drizzle-orm": "^0.45.2",
|
|
74
74
|
"hono": "^4.13.7"
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as W}from"@lunora/errors";import{findRelated as V}from"@lunora/shard-engine";import{i as j}from"./wire-codec-BTOxkE1j.mjs";import{bindTableFacade as ee,bindOrm as te}from"./bindOrm-D_hFUjmr.mjs";import{t as re}from"./policy-tag-V0lqFzgS.mjs";import{deny as ne}from"./allowAll-DkRAgItV.mjs";const se=["every","is","isNot","none","some"],oe=new Set(se),ie=e=>{if(e===null||typeof e!="object"||Array.isArray(e))return!1;const r=Object.keys(e);return r.length>0&&r.every(n=>oe.has(n))},q=(e,r,n)=>r?{[e]:n(r)}:{},ae=["contains","eq","gt","gte","in","isNull","lt","lte","ne","notIn"],B=-1,v=0,b=1,T=e=>e?b:B,p=(e,r)=>e<r?e:r,ce=(e,r)=>e>r?e:r,z=e=>e===v?v:T(e===B),Y=e=>{const r=typeof e;return r==="number"||r==="string"||r==="bigint"},S=e=>e==null,M=(e,r,n)=>{if(n===void 0)throw new W("BAD_REQUEST",`\`${r}\` on "${e}" received undefined; a comparison needs a value`)},le={gt:(e,r)=>e>r,gte:(e,r)=>e>=r,lt:(e,r)=>e<r,lte:(e,r)=>e<=r},fe=(e,r,n)=>{let i=b;for(const c of["gt","gte","lt","lte"]){if(!(c in n))continue;const h=n[c];if(M(e,c,h),!Y(h))i=p(i,B);else if(S(r))i=p(i,v);else{const f=le[c];i=p(i,T(Y(r)&&f(r,h)))}}return i},K=(e,r,n)=>{if(!Array.isArray(n))throw new W("BAD_REQUEST",`\`${r}\` on "${e}" expects an array of values, received ${n===null?"null":typeof n}`);if(n.includes(void 0))throw new W("BAD_REQUEST",`\`${r}\` on "${e}" received undefined inside its list; a comparison needs a value`);return n},Q=(e,r)=>r.length===0?B:S(e)?v:r.includes(e)?b:r.some(n=>S(n))?v:B,de=(e,r,n)=>{let i=b;if("in"in n&&(i=p(i,Q(r,K(e,"in",n.in)))),"notIn"in n&&(i=p(i,z(Q(r,K(e,"notIn",n.notIn))))),"contains"in n){const c=n.contains;M(e,"contains",c),i=S(r)?p(i,v):p(i,T(typeof r=="string"&&typeof c=="string"&&r.includes(c)))}return"isNull"in n&&(i=p(i,T(n.isNull===!0===S(r)))),i},F=(e,r,n)=>r===null?T(n===S(e)):S(e)?v:T(n===(e===r)),ue=(e,r,n)=>{let i=b;return"eq"in n&&(M(e,"eq",n.eq),i=p(i,F(r,n.eq,!0))),"ne"in n&&(M(e,"ne",n.ne),i=p(i,F(r,n.ne,!1))),i},he=(e,r,n)=>p(ue(e,r,n),p(de(e,r,n),fe(e,r,n))),ye=(e,r,n,i)=>{if(r==="NOT")return z(i(e,n??{}));if(!Array.isArray(n))return B;let c=r==="AND"?b:B;for(const h of n){const f=i(e,h);c=r==="AND"?p(c,f):ce(c,f)}return c},H=e=>e==="AND"||e==="OR"||e==="NOT",we=e=>j(e)&&Object.keys(e).every(r=>ae.includes(r)),C=e=>Object.keys(e).some(r=>{const n=e[r];return H(r)?r==="NOT"?C(n??{}):Array.isArray(n)&&n.some(i=>C(i??{})):ie(n)}),G=(e,r)=>{let n=b;for(const i of Object.keys(r)){const c=r[i];if(H(i)){n=p(n,ye(e,i,c,G));continue}const h=e[i];if(we(c)){n=p(n,he(i,h,c));continue}M(i,"eq",c),n=p(n,F(h,c,!0))}return n},L=(e,r)=>G(e,r)===b,X=500,I=(e,r,n)=>{const i=r??X;if(e>i)throw new W("BATCH_LIMIT_EXCEEDED",`${n}: batch of ${String(e)} exceeds the limit of ${String(i)} (raise options.limit or chunk the call)`,{status:400})},pe=ne(),ge=Symbol.for("lunora.ctxdb.rls-unwrap"),J=Symbol.for("lunora.rls.wrapped-chain"),We=e=>e[J],Oe=e=>{const r=new Map;for(const n of e){const i=r.get(n.table)??[];i.push(n),r.set(n.table,i)}return r},Re=(e,r)=>{const n=[];let i=!1;for(const c of e){if(c.on!=="read")continue;const h=c.when(r);if(h!==void 0){if(h===!0){i=!0;break}h!==!1&&n.push(h)}}if(!i)return n.length===0?pe:n.length===1?n[0]:{OR:n}},be=(e,r,n)=>{const i=e.when({...r,row:n});if(i===void 0||i===!0)return!0;if(i===!1)return!1;if(C(i))throw new W("RELATION_PREDICATE_UNSUPPORTED","relation predicates are not supported in write policies; use a read policy or a flat column check");return L(n,i)},Ae=(e,r,n)=>{const i=e.when(r);if(i===void 0||i===!0)return n===void 0||be(e,r,n);if(i===!1)return!1;if(C(i))throw new W("RELATION_PREDICATE_UNSUPPORTED","relation predicates are not supported in write policies; use a read policy or a flat column check");return!r.row||!L(r.row,i)?!1:n===void 0||L(n,i)},Ee=(e,r,n,i)=>{let c=!1;for(const h of e)if(h.on===r&&(c=!0,!Ae(h,n,i)))return!1;return c},Be=new Set(["baseWhere","relationBaseWhere","restrictsCounts","where"]),ve=(e,r)=>r===void 0?!0:e==="restrictsCounts"?typeof r=="boolean":e==="relationBaseWhere"?typeof r=="function":j(r),Se=e=>{const r=Object.keys(e);return r.length===0?!1:r.every(n=>Be.has(n)&&ve(n,e[n]))},_e=e=>e===void 0?{}:j(e)&&Se(e)?e:{where:e},$=e=>e!==void 0&&Object.keys(e).length>0,ke=e=>{if(e.length!==0)return e.length===1?e[0]:{AND:e}},R=(e,r)=>$(r)?!e||Object.keys(e).length===0?r:{AND:[r,e]}:e,Ie=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return!1;const r=e;return typeof r.findMany=="function"&&typeof r.withSearchIndex=="function"},Te=(e,r,n)=>{const[i]=n,c=n.length===1&&i!==void 0?i.perTable:new Set(n.flatMap(t=>[...t.perTable.keys()])),h=new Map,f=t=>{const s=h.get(t);if(s)return s;const o=[];let a=!1;for(const y of n){const u=y.perTable.get(t);if(!u||u.length===0||!u.some(m=>m.on==="read"))continue;a=!0;const d=Re(u,y.context);d!==void 0&&o.push(d)}const l={baseWhere:ke(o),restricts:a};return h.set(t,l),l},_=(t,s,o,a)=>{for(const l of n){const y=l.perTable.get(t);if(y&&!Ee(y,s,{...l.context,row:o},a))return!1}return!0},w=t=>f(t).restricts?r:e,g=t=>f(t).baseWhere,A=async(t,s,o)=>{if(r.lookupById){const d=await r.lookupById(t,s);if(d)return{row:d.row,tableName:c.has(d.tableName)?d.tableName:void 0}}const a=await r.get(t,s);if(!a)return{row:null,tableName:void 0};const l=s??o,y=l===void 0?[...c.keys()]:[l].filter(d=>c.has(d)),u=await Promise.all(y.map(async d=>(await r.findFirst(d,{limit:1,where:{_id:t}}))?._id===t?d:void 0));return{row:a,tableName:u.find(d=>d!==void 0)}},U=async(t,s,o)=>{const a=await A(t,s,o);return a.row&&a.tableName!==void 0?{row:a.row,tableName:a.tableName}:void 0},O=async(t,s,o,a,l,y)=>{const u=await U(t,l,y);if(!u)return o(e);const d=a?a(u.row):void 0;if(!_(u.tableName,s,u.row,d))throw new W("FORBIDDEN",`${s} denied by policy`);return o(r)},E=(t,s)=>{const{baseWhere:o}=f(t);if($(o))throw new W("COUNT_RLS_UNSUPPORTED",`${s}() is not supported on "${t}" inside an RLS-restricted context`)},D=e.rankBefore,P=e.rankPageRows,{relationEdges:N}=e,k={...e,async count(t,s){const{baseWhere:o}=f(t),a=_e(s);return w(t).count(t,{...a,baseWhere:R(a.baseWhere,o),relationBaseWhere:g,restrictsCounts:(a.restrictsCounts??!1)||$(o)})},delete:(t,s,o)=>O(t,"delete",a=>a.delete(t,s,o),void 0,s),async deleteAll(t,s){const o=Math.max(1,s?.chunkSize??X),{baseWhere:a}=f(t);let l=0;for(;;){const u=(await w(t).findMany(t,{baseWhere:a,limit:o,relationBaseWhere:g})).page.map(d=>String(d._id));if(u.length===0)break;for(const d of u)await O(d,"delete",m=>m.delete(d,void 0,s?.hard===void 0?void 0:{hard:s.hard}),void 0,void 0,t),l+=1;if(u.length<o)break}return{deleted:l}},async deleteMany(t,s,o){I(t.length,s?.limit,"deleteMany");for(const a of t)await O(a,"delete",l=>l.delete(a,o),void 0,o);return{deleted:t.length}},async deleteWhere(t,s,o){const{baseWhere:a}=f(t),y=(await w(t).findMany(t,{baseWhere:R(s,a),relationBaseWhere:g})).page.map(u=>String(u._id));I(y.length,o?.limit,"deleteWhere");for(const u of y)await O(u,"delete",d=>d.delete(u),void 0,void 0,t);return{deleted:y.length}},async findFirst(t,s){const{baseWhere:o}=f(t);return w(t).findFirst(t,{...s,baseWhere:R(s?.baseWhere,o),relationBaseWhere:g})},async findFirstOrThrow(t,s){const{baseWhere:o}=f(t);return w(t).findFirstOrThrow(t,{...s,baseWhere:R(s?.baseWhere,o),relationBaseWhere:g})},async findMany(t,s){const{baseWhere:o}=f(t);return w(t).findMany(t,{...s,baseWhere:R(s?.baseWhere,o),relationBaseWhere:g})},async get(t,s){const o=await A(t,s);if(!o.row)return null;if(o.tableName===void 0)return e.get(t,s);const{baseWhere:a,restricts:l}=f(o.tableName);if(!l)return e.get(t,s);if(!a)return o.row;const y=await r.findFirst(o.tableName,{baseWhere:a,limit:1,where:{_id:t}});return y?._id===t?y:null},async lookupById(t,s){const o=await A(t,s);if(!o.row)return null;if(o.tableName===void 0||!f(o.tableName).restricts)return await e.lookupById?.(t,s)??null;const{baseWhere:a}=f(o.tableName);if(!a)return{row:o.row,tableName:o.tableName};const l=await r.findFirst(o.tableName,{baseWhere:a,limit:1,where:{_id:t}});return l?._id===t?{row:l,tableName:o.tableName}:null},async insert(t,s){if(c.has(t)){if(!_(t,"insert",s))throw new W("FORBIDDEN",`insert on "${t}" denied by policy`);return r.insert(t,s)}return e.insert(t,s)},async insertMany(t,s,o){if(I(s.length,o?.limit,"insertMany"),c.has(t)){for(const a of s)if(!_(t,"insert",a))throw new W("FORBIDDEN",`insert on "${t}" denied by policy`);return r.insertMany(t,s,o)}return e.insertMany(t,s,o)},async insertManyUnsafe(t,s,o){if(I(s.length,o?.limit,"insertManyUnsafe"),c.has(t)){for(const a of s)if(!_(t,"insert",a))throw new W("FORBIDDEN",`insert on "${t}" denied by policy`);return r.insertManyUnsafe(t,s,o)}return e.insertManyUnsafe(t,s,o)},patch:(t,s,o)=>O(t,"update",a=>a.patch(t,s,o),a=>({...a,...s}),o),async patchMany(t,s,o){I(t.length,s?.limit,"patchMany");for(const a of t)await O(a.id,"update",l=>l.patch(a.id,a.patch,o),l=>({...l,...a.patch}),o);return{patched:t.length}},async patchWhere(t,s,o){const{baseWhere:a}=f(t),y=(await w(t).findMany(t,{baseWhere:R(s.where,a),relationBaseWhere:g})).page.map(u=>({id:String(u._id),patch:s.patch}));return I(y.length,o?.limit,"patchWhere"),k.patchMany(y,o)},query(t){const{baseWhere:s}=f(t),o=w(t).query(t);return s?o.filter(a=>L(a,s)):o},related:N===void 0?void 0:async(t,s)=>V({findMany:async(o,a)=>k.findMany(o,a),lookupById:async o=>r.lookupById?.(o)},N,t,{cursor:s?.cursor,depth:s?.depth,direction:s?.direction,edges:s?.edges,limit:s?.limit,relationMask:s?.relationMask}),restore:(t,s)=>O(t,"update",async o=>{const a=o.restore??r.restore;if(!a)throw new W("BAD_REQUEST","restore is not supported by this writer");await a(t,s)},void 0,s),replace:(t,s,o)=>O(t,"update",a=>a.replace(t,s,o),a=>({...s,_creationTime:s._creationTime??a._creationTime,_id:a._id}),o),aggregate(t,s){const{baseWhere:o}=f(t);return w(t).aggregate(t,{...s,baseWhere:R(s.baseWhere,o),relationBaseWhere:g})},groupBy(t,s){const{baseWhere:o}=f(t);return w(t).groupBy(t,{...s,baseWhere:R(s.baseWhere,o),relationBaseWhere:g})},rank(t,s,o){return E(t,"rank"),w(t).rank(t,s,o)},rankPage(t,s,o){return E(t,"rankPage"),w(t).rankPage(t,s,o)},wipeShard(){throw new W("FORBIDDEN","ctx.db.wipeShard() is unavailable under rls(): a whole-shard erase can't be policy-gated per row, and erasing only policy-visible rows would silently leave data behind. Run it from an internalMutation, or use ctx.db.deleteAll(table) per table.",{status:403})},...q("rankBefore",D,t=>(s,o,a)=>(E(s,"rankBefore"),(w(s).rankBefore??t)(s,o,a))),...q("rankPageRows",P,t=>(s,o,a)=>(E(s,"rankPageRows"),(w(s).rankPageRows??t)(s,o,a)))},x=k;if(c.size>0)for(const[t,s]of Object.entries(e))Ie(s)&&(x[t]=ee(k,t));return Object.defineProperty(k,J,{configurable:!0,enumerable:!1,value:{base:e,raw:r,steps:n},writable:!1}),k},Z=e=>typeof e=="string"?e:e.name,Me=e=>{const r=new Map;for(const n of e??[])r.set(n.name,new Set((n.permissions??[]).map(i=>Z(i))));return r},De=(e,r)=>{const n=new Set;for(const i of e)for(const c of r.get(i)??[])n.add(c);return i=>n.has(Z(i))},Pe=["roles","role"],me=e=>{for(const r of Pe){const n=e?.[r];if(typeof n=="string"){const i=n.split(",").map(c=>c.trim()).filter(c=>c.length>0);if(i.length>0)return i}if(Array.isArray(n)){const i=n.filter(c=>typeof c=="string"&&c.length>0);if(i.length>0)return i}}return[]},Ce=async(e,r)=>{const n=await e.getIdentity?.()??null,i=[...new Set([...me(n),...e.roles??[]])];return{can:De(i,r),identity:n,roles:i,userId:e.userId??null}},qe=(e,r={})=>{const n=e,i=Oe(n),c=Me(r.roles);return re(async({ctx:f,next:_})=>{const w={auth:await Ce(f.auth??{},c),ctx:f},g=f.db,A=We(g),U=A?.base??g,O=A?.raw??g[ge]??g,E=Te(U,O,[...A?.steps??[],{context:w,perTable:i}]),D={db:E},{orm:P}=f;return P!==null&&typeof P=="object"&&(D.orm=te(E)),_({ctx:D})},[{policies:n,roles:r.roles??[]}])};export{Ce as a,Ie as b,ie as c,me as d,De as e,Re as f,Ee as g,Me as i,L as m,q as o,Z as p,qe as r};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as s}from"@lunora/errors";import{c as Q}from"./compose-middleware-DNvrHMHx.mjs";import{v as B}from"@lunora/values";const q=["de","en","es","fr","it","nl","none","pt"],F=["native","portable"],V=e=>F.includes(e),X=e=>q.includes(e),U=e=>{const{value:t}=e._meta??{};if(t===null)return"null";switch(typeof t){case"bigint":case"boolean":case"number":case"string":return typeof t;default:return e.kind}},P=e=>{if(e.kind==="literal")return U(e);if(e.kind!=="optional")return e.kind;const t=e._meta?.inner;return t?P(t):e.kind},G=(e,t)=>`table "${e}" is .global() and declares vector index "${t}". Vector sync runs on the shard write path, which a global (D1/Hyperdrive) table's writes never take — the index would stay empty. Drop .global(), or keep the index yourself with ctx.vectors.upsert/deleteByIds.`,j=16,Y={many:(e,t)=>({field:t.field,kind:"many",references:t.references??"_id",table:e}),one:(e,t)=>({field:t.field,kind:"one",onDelete:t.onDelete,references:t.references??"_id",table:e})},g=(e,t,n)=>({handler:n,op:t,timing:e}),J=()=>({afterDelete:e=>g("after","delete",e),afterInsert:e=>g("after","insert",e),afterUpdate:e=>g("after","update",e),beforeDelete:e=>g("before","delete",e),beforeInsert:e=>g("before","insert",e),beforeUpdate:e=>g("before","update",e)}),C=(e,t)=>{if(!t||t.length===0)throw new s("INTERNAL",`rankIndex "${e}": "sortBy" is required and must list at least one key`);return t.map(n=>({direction:n.direction??"asc",field:n.field}))},ge=e=>{const t={...e},n=[],r=[],a=[],d=[],u={},c=[],h={},f=J(),b=[];let w={kind:"root"},E=!1,$=!1,p=!1,T=!1,M=!1,L,A,O,R;const D=o=>{if(w.kind!=="root"&&w.kind!==o.kind)throw new s("INTERNAL","shardBy/global: a table cannot be both .shardBy(key) and .global() — pick one. .shardBy(key) puts the rows in one Durable Object per key (isolation, poke-live reactivity); .global() puts them in a single replicated backend read from the edge.");w=o},l={aggregateIndex(o,i){const m=i?.op??"count";if(m!=="count"&&!i?.field)throw new s("INTERNAL",`aggregateIndex "${o}": op "${m}" requires a "field"`);return n.push({by:i?.by,field:i?.field,name:o,on:"",op:m,where:i?.where}),l},get aggregateIndexes(){return n},get externalSource(){return R},commitOrdered(){return E=!0,l},get commitOrderedMode(){return E},dropStalePatches(){return $=!0,l},get dropStalePatchesMode(){return $},externallyManaged(){return p=!0,l},geoIndex(o,i){return r.push({field:i.field,name:o,precision:i.precision}),l},get geoIndexes(){return r},global(o){return D({backend:o?.backend??"d1",kind:"global"}),l},get isExternallyManaged(){return p},get isPublic(){return M},index(o,i,m){return a.push({fields:i,name:o,unique:m?.unique??!1}),l},get indexes(){return a},memory(){return T=!0,l},get memoryMode(){return T},ownedBy(o){return L=o,l},get ownerField(){return L},public(){return M=!0,l},rankIndex(o,i){return d.push({name:o,on:"",partitionBy:i.partitionBy,sortBy:C(o,i.sortBy),where:i.where}),l},get rankIndexes(){return d},get relationMap(){return u},relations(o){return Object.assign(u,o(Y)),l},searchIndex(o,i){if(i.filterFields&&i.filterFields.length>j)throw new s("INTERNAL",`searchIndex "${o}": at most ${String(j)} filterFields are supported (got ${String(i.filterFields.length)})`);const{language:m}=i;if(m!==void 0&&!X(m))throw new s("INTERNAL",`searchIndex "${o}": unknown language "${m}" (supported: ${q.join(", ")})`);const{strategy:N}=i;if(N!==void 0&&!V(N))throw new s("INTERNAL",`searchIndex "${o}": unknown strategy "${N}" (supported: ${F.join(", ")})`);return c.push({field:i.field,filterFields:i.filterFields,language:i.language,name:o,staged:i.staged,strategy:i.strategy}),l},get searchIndexes(){return c},shape:t,shardBy(o){return D({field:o,kind:"shardBy"}),l},get shardMode(){return w},get softDeleteMode(){return A},source(o){if(!o.binding)throw new s("INTERNAL","source: `binding` is required (the wrangler Hyperdrive binding name)");if(!o.query)throw new s("INTERNAL","source: `query` is required (the tenant-membership SQL)");return R=o,p=!0,l},softDelete(o){const i=o?.field??"deletedAt";return A={field:i},i in t||(t[i]=B.optional(B.number().nullable())),l},get triggerMap(){return h},triggers(o){return Object.assign(h,o(f)),l},ttl(o,i){return O={after:i?.after,field:o},l},get ttlPolicy(){return O},get vectorIndexes(){return b},vectorize(o,i){return b.push({dimensions:i.dimensions,embed:i.embed,field:o,metadata:i.metadata,metric:i.metric,name:i.index}),l}};return l},be=e=>({dimensions:e.dimensions,embed:e.embed,kind:"vectorIndex",metadata:e.metadata,metric:e.metric,select:e.source.select,table:e.source.table}),we=(e,t)=>{const n=t.op??"count";if(n!=="count"&&!t.field)throw new s("INTERNAL",`aggregateIndex "${e}": op "${n}" requires a "field"`);return{by:t.by,field:t.field,name:e,on:t.on,op:n,where:t.where}},xe=(e,t)=>({name:e,on:t.table,partitionBy:t.partitionBy,sortBy:C(e,t.sortBy),where:t.where}),y=e=>({...e,extend(t){return y(z(e,t))},jurisdiction(t){return y(e)},rls(t){return y({...e,rlsMode:t})}}),W=e=>{for(const[t,n]of Object.entries(e))for(const r of[...n.aggregateIndexes,...n.rankIndexes])r.on===""&&(r.on=t)},Z=(e,t,n)=>{for(const r of Object.values(t)){const a=e[r.on];if(!a)throw new s("INTERNAL",`defineAggregateIndex "${r.name}": unknown table "${r.on}"`);a.aggregateIndexes.push(r)}for(const r of Object.values(n)){const a=e[r.on];if(!a)throw new s("INTERNAL",`defineRankIndex "${r.name}": unknown table "${r.on}"`);a.rankIndexes.push(r)}},ee=e=>{if(e.cursor)return"cursor";if(e.reconcileEveryMs!==void 0)return"reconcileEveryMs";if(e.softDeleteColumn!==void 0)return"softDeleteColumn"},te=(e,t)=>{const n=t.mode==="incremental";if(t.mode!==void 0&&t.mode!=="full-pull"&&!n)throw new s("INTERNAL",`defineSchema: table "${e}" uses \`mode: ${JSON.stringify(t.mode)}\` — supported modes are "full-pull" (default) and "incremental".`);if(!n){const r=ee(t);if(r)throw new s("INTERNAL",`defineSchema: table "${e}" sets \`${r}\` but is not \`mode: "incremental"\` — that knob only applies to incremental ingest. Set \`mode: "incremental"\` or remove \`${r}\`.`);return}if(!t.cursor?.column||!t.cursor.query)throw new s("INTERNAL",`defineSchema: table "${e}" is \`mode: "incremental"\` but has no \`cursor\` — add \`cursor: { column: "updated_at", query: "… WHERE … > $N" }\` binding the watermark as the trailing parameter.`);if(t.reconcileEveryMs===void 0&&t.softDeleteColumn===void 0)throw new s("INTERNAL",`defineSchema: table "${e}" is \`mode: "incremental"\` with no delete-visibility path — an incremental pull never sees upstream deletes, so it would accumulate phantom rows. Add \`reconcileEveryMs\` (a periodic full-pull sweep) or \`softDeleteColumn\` (an upstream tombstone column).`)},ne=e=>{for(const[t,n]of Object.entries(e)){const r=n.externalSource;if(r){if(n.shardMode.kind==="global")throw new s("INTERNAL",`defineSchema: table "${t}" cannot be both .source() and .global() — a sourced table materializes into a shard DO's SQLite, a global table lives in the external tier`);if(n.shardMode.kind==="shardBy"&&!r.tenantBy)throw new s("INTERNAL",`defineSchema: sourced + .shardBy() table "${t}" needs a \`tenantBy\` mapper — without it every tenant's DO would run the same unscoped query and replicate the whole multitenant table (a cross-tenant leak). Add \`tenantBy: (shardKey) => [shardKey]\` binding the shard key into the query's parameters.`);te(t,r)}}},re=["_commitSeq","_creationTime","_id"],_="_commitSeq",ae=new Set(re),x=(e,t,n,r)=>{if(!(ae.has(n)||n in r.shape))throw new s("INTERNAL",`defineSchema: table "${e}" index "${t}" names column "${n}" which is not in the table's shape`)},v=(e,t,n,r)=>{const a=new Set;for(const d of n){if(a.has(d.name))throw new s("INTERNAL",`defineSchema: table "${e}" declares ${t} "${d.name}" more than once`);a.add(d.name),r(d)}},K=e=>{for(const[t,n]of Object.entries(e))v(t,"index",n.indexes,r=>{for(const a of r.fields)x(t,r.name,a,n)}),v(t,"rank index",n.rankIndexes,r=>{for(const a of r.sortBy)x(t,r.name,a.field,n);for(const a of r.partitionBy??[])x(t,r.name,a,n)}),v(t,"geo index",n.geoIndexes,r=>{x(t,r.name,r.field,n)})},S=(e,t,n)=>{if(e.length===0)return;const r={};for(const a of e)r[t(a)]=n(a);return r},oe=e=>{const t=new Set(e.sortBy.map(n=>n.field));for(const n of e.partitionBy??[])t.add(n);return[...t]},ye=e=>{const t={};for(const[n,r]of Object.entries(e.tables)){const a=S(r.geoIndexes,c=>c.name,c=>[c.field]),d=S(r.indexes,c=>c.name,c=>c.fields),u=S(r.rankIndexes,c=>c.name,oe);(a||d||u)&&(t[n]={...a?{geo:a}:{},...d?{index:d}:{},...u?{rank:u}:{}})}return t},ie=e=>{for(const[t,n]of Object.entries(e)){if(!n.memoryMode)continue;const a=[[n.shardMode.kind==="global",".global() — those rows live in D1, which this shard does not own and cannot clear"],[n.commitOrderedMode===!0,".commitOrdered() — the counter resets with the table, so the sequence would restart and a consumer's cursor would silently skip everything after it"],[n.externalSource!==void 0,".source() — the table is materialized by the ingest loop, so wiping it on every eviction would fight the puller"],[n.searchIndexes.length>0,".searchIndex() — the FTS shadow is a separate table that clearing the rows would leave stale"],[n.geoIndexes.length>0,".geoIndex() — the geohash companion is a separate table that clearing the rows would leave stale"],[n.aggregateIndexes.length>0,".aggregateIndex() — the counter companion is a separate table that clearing the rows would leave stale"],[n.rankIndexes.length>0,".rankIndex() — the rank companion is a separate table that clearing the rows would leave stale"],[n.vectorIndexes.length>0,".vectorize() — vectors live in an external index that a shard restart cannot clear"]].find(([d])=>d)?.[1];if(a!==void 0)throw new s("INTERNAL",`defineSchema: table "${t}" is both .memory() and ${a}. Plain .index() is supported; SQLite maintains it through the DELETE.`)}},se=e=>{for(const[t,n]of Object.entries(e))if(n.shardMode.kind==="global"){for(const[r,a]of Object.entries(n.shape))if(P(a)==="bigint")throw new s("INTERNAL",`defineSchema: table "${t}" is .global() and column "${r}" is v.bigint(). A global (D1/Hyperdrive) table stores a bigint as decimal TEXT, which SQL compares lexicographically — "100" sorts before "25" — so \`orderBy\`, range filters and \`aggregate\` on this column would silently return wrong results. Use v.number() if the value fits a double, or v.string() if you only need equality.`)}},de=e=>{for(const[t,n]of Object.entries(e))if(n.dropStalePatchesMode===!0&&n.shardMode.kind==="global")throw new s("INTERNAL",`defineSchema: table "${t}" is both .global() and .dropStalePatches(). The stale check reads the caller's baseline out of the shard's \`__cdc_log\`, which a global (D1/Hyperdrive) table has no entries in — so every patch would read as "no baseline" and apply unchanged. Drop one of the two.`)},H=(e,t)=>{const n=[...Object.entries(e).flatMap(([r,a])=>a.vectorIndexes.map(d=>[r,d.name])),...Object.entries(t).map(([r,a])=>[a.table,r])];for(const[r,a]of n)if(e[r]?.shardMode.kind==="global")throw new s("INTERNAL",`defineSchema: ${G(r,a)}`)},le=e=>{for(const[t,n]of Object.entries(e)){if(n.commitOrderedMode){if(n.shardMode.kind==="global")throw new s("INTERNAL",`defineSchema: table "${t}" is both .global() and .commitOrdered(). \`_commitSeq\` is allocated inside the shard's write transaction, which a global (D1/Hyperdrive) table does not share — so the stamp would carry no commit-ordering guarantee. Drop one of the two.`);continue}for(const r of n.indexes)if(r.fields.includes(_))throw new s("INTERNAL",`defineSchema: table "${t}" index "${r.name}" names "${_}", but the table is not .commitOrdered() — no row carries that field, so the index would never match. Add .commitOrdered(), or drop the column from the index.`)}},Ie=(e,t={},n={},r={})=>(W(e),Z(e,n,r),ne(e),le(e),de(e),se(e),H(e,t),ie(e),K(e),y({tables:e,vectorIndexes:t})),I=(e,t)=>`${e}_${t}`,k=(e,t,n)=>n.has(e)?I(t,e):e,ce=(e,t,n,r)=>{const a=I(t,r),d=f=>f===""?a:k(f,t,n),u={};for(const[f,b]of Object.entries(e.relationMap))u[f]={...b,table:k(b.table,t,n)};const c=e.aggregateIndexes.map(f=>({...f,on:d(f.on)})),h=e.rankIndexes.map(f=>({...f,on:d(f.on)}));return{...e,aggregateIndexes:c,rankIndexes:h,relationMap:u}},pe=(e,t)=>{if(!e)throw new s("INTERNAL","defineSchemaExtension: `key` is required and must be a non-empty string");return{key:e,tables:t.tables,...t.vectorIndexes?{vectorIndexes:t.vectorIndexes}:{}}},ue=((e,t)=>{if(!e)throw new s("INTERNAL","definePlugin: `key` is required and must be a non-empty string");if(t.extension&&t.extension.key!==e)throw new s("INTERNAL",`definePlugin("${e}"): extension key "${t.extension.key}" does not match plugin key`);return{key:e,...t.extension?{extension:t.extension}:{},...t.middleware?{middleware:t.middleware}:{}}}),Ne=(e,t)=>({...ue(e,{...t.extension?{extension:t.extension}:{},...t.middleware?{middleware:t.middleware}:{}}),functions:t.functions??{}}),z=(e,t)=>{const{key:n}=t,r=new Set(Object.keys(t.tables)),a={...e.tables};for(const[u,c]of Object.entries(t.tables)){const h=I(n,u);if(Object.hasOwn(a,h))throw new s("INTERNAL",`defineSchema(...).extend("${n}"): table "${h}" already exists in the base schema — another extension with the same key already contributed it`);a[h]=ce(c,n,r,u)}const d={...e.vectorIndexes};if(t.vectorIndexes)for(const[u,c]of Object.entries(t.vectorIndexes)){const h=I(n,u);if(Object.hasOwn(d,h))throw new s("INTERNAL",`defineSchema(...).extend("${n}"): vector index "${h}" already exists in the base schema — another extension with the same key already contributed it`);d[h]={...c,table:k(c.table,n,r)}}return K(a),H(a,d),{rlsMode:e.rlsMode,tables:a,vectorIndexes:d}},ve=(e,t)=>{let n=e;for(const r of t)r.extension&&(n=z(n,r.extension));return n},Se=e=>{const t=e.map(n=>n.middleware).filter(n=>n!==void 0);return Q(t)};export{Ne as a,ue as b,Se as c,we as d,xe as e,Ie as f,pe as g,ge as h,be as i,ye as j,ve as k,K as l,z as m,H as v};
|