@lunora/server 1.0.0-alpha.61 → 1.0.0-alpha.63
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/data-model.d.mts +10 -10
- package/dist/data-model.d.ts +10 -10
- package/dist/index.d.mts +281 -293
- package/dist/index.d.ts +281 -293
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/{PRESENCE_DEFAULT_TTL_MS-DmnVChTY.mjs → PRESENCE_DEFAULT_TTL_MS-Dyb1szd2.mjs} +1 -1
- package/dist/packem_shared/buildRlsReadRegistry-CE5k6akj.mjs +1 -0
- package/dist/packem_shared/{composePluginMiddleware-B9NyOR1k.mjs → composePluginMiddleware-ByhCqIGt.mjs} +1 -1
- package/dist/packem_shared/{defineAggregateIndex-C3CMy5jn.mjs → defineAggregateIndex-BoiwhUKL.mjs} +1 -1
- package/dist/packem_shared/httpAction-BpEJYwzV.mjs +5 -0
- package/dist/packem_shared/initLunora-BadfSfpJ.mjs +1 -0
- package/dist/packem_shared/mask-Chnz8Z0H.mjs +1 -0
- package/dist/packem_shared/middleware-D9_39C5C.mjs +1 -0
- package/dist/packem_shared/plugin-184MITA3.mjs +1 -0
- package/dist/packem_shared/rls-CI2149Ve.mjs +1 -0
- package/dist/packem_shared/storageRules-6_G8JpCv.mjs +1 -0
- package/dist/packem_shared/{types.d-C4CMJK8x.d.mts → types.d-B-pIn8rE.d.mts} +2 -2
- package/dist/packem_shared/{types.d-DdYF8E18.d.ts → types.d-CdPDEjhz.d.ts} +2 -2
- package/dist/rls/testing.d.mts +1 -1
- package/dist/rls/testing.d.ts +1 -1
- package/dist/rls/testing.mjs +1 -1
- package/dist/types.d.mts +21 -21
- package/dist/types.d.ts +21 -21
- package/package.json +4 -4
- package/dist/packem_shared/buildRlsReadRegistry-CA-aUi7I.mjs +0 -1
- package/dist/packem_shared/httpAction-C14NuF3V.mjs +0 -4
- package/dist/packem_shared/initLunora-DXCOVntr.mjs +0 -1
- package/dist/packem_shared/mask-DF7mtxQe.mjs +0 -1
- package/dist/packem_shared/optional-writer-override-CXXO30sZ.mjs +0 -1
- package/dist/packem_shared/plugin-CDBMGCeQ.mjs +0 -1
- package/dist/packem_shared/rls-tRDkICWZ.mjs +0 -1
- package/dist/packem_shared/storageRules-BptPZbi8.mjs +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as i}from"@lunora/errors";import{l as z}from"./run-middleware-BeEEqmdE.mjs";import{v as B}from"@lunora/values";const T=["de","en","es","fr","it","nl","none","pt"],O=["native","portable"],F=e=>O.includes(e),C=e=>T.includes(e),P="a an and are as at be but by for if in into is it no not of on or such that the their then there these they this to was will with",_="aber als am an auch auf aus bei bin bis bist da dass der den des dem die das denn dir du ein eine für hat ich im in ist mit nicht noch nur oder sich sie sind über und von vor war wie wir zu zum zur",H="a al como con de del el en es la las lo los mas no o para pero por que se su sus un una uno y ya",K="au aux avec ce ces dans de des du elle en et eux il je la le les leur lui ma mais me même mes moi mon ne nos notre nous on ou par pas pour qu que qui sa se ses son sur ta te tes toi ton tu un une vos votre vous y",Q="a ai al alla anche che chi ci coi col come con da dal degli dei del della di do e ed gli ha hai hanno i il in la le lo ma mi ne nei nel non o per più quale quanto se si sono su sul tra un una uno vi",U="aan al als bij dan dat de der deze die dit door een en er het hij ij in is je kan me men met mij na naar niet nog nu of om ons ook op over te tot uit van voor was wat we wij zij zijn zo",J="a ao aos as até com como da das de do dos e em entre era essa esse esta este eu foi há isso já mais mas me mesmo meu na nas no nos num numa o os ou para pela pelo por qual que quem se sem seu só sua também te tem um uma você",W=/[\u0300-\u036F]/gu,G=e=>e.normalize("NFD").replaceAll(W,"").normalize("NFC").toLowerCase(),g=e=>new Set(G(e).split(" "));g(_),g(P),g(H),g(K),g(Q),g(U),g(J);const R=16,X={many:(e,n)=>({field:n.field,kind:"many",references:n.references??"_id",table:e}),one:(e,n)=>({field:n.field,kind:"one",onDelete:n.onDelete,references:n.references??"_id",table:e})},w=(e,n,t)=>({handler:t,op:n,timing:e}),Y=()=>({afterDelete:e=>w("after","delete",e),afterInsert:e=>w("after","insert",e),afterUpdate:e=>w("after","update",e),beforeDelete:e=>w("before","delete",e),beforeInsert:e=>w("before","insert",e),beforeUpdate:e=>w("before","update",e)}),ce=e=>{const n={...e},t=[],r=[],s=[],l=[],c={},d=[],m={},f=Y(),p=[];let $={kind:"root"},N=!1,j=!1,A,L,S,q;const u={aggregateIndex(a,o){const h=o?.op??"count";if(h!=="count"&&!o?.field)throw new i("INTERNAL",`aggregateIndex "${a}": op "${h}" requires a "field"`);return t.push({by:o?.by,field:o?.field,name:a,on:"",op:h,where:o?.where}),u},get aggregateIndexes(){return t},get externalSource(){return q},externallyManaged(){return N=!0,u},geoIndex(a,o){return r.push({field:o.field,name:a,precision:o.precision}),u},get geoIndexes(){return r},global(a){return $={backend:a?.backend??"d1",kind:"global"},u},get isExternallyManaged(){return N},get isPublic(){return j},index(a,o,h){return s.push({fields:o,name:a,unique:h?.unique??!1}),u},get indexes(){return s},ownedBy(a){return A=a,u},get ownerField(){return A},public(){return j=!0,u},rankIndex(a,o){if(!o.sortBy||o.sortBy.length===0)throw new i("INTERNAL",`rankIndex "${a}": "sortBy" is required and must list at least one key`);const h=o.sortBy.map(b=>({direction:b.direction??"asc",field:b.field}));return l.push({name:a,on:"",partitionBy:o.partitionBy,sortBy:h,where:o.where}),u},get rankIndexes(){return l},get relationMap(){return c},relations(a){return Object.assign(c,a(X)),u},searchIndex(a,o){if(o.filterFields&&o.filterFields.length>R)throw new i("INTERNAL",`searchIndex "${a}": at most ${String(R)} filterFields are supported (got ${String(o.filterFields.length)})`);const{language:h}=o;if(h!==void 0&&!C(h))throw new i("INTERNAL",`searchIndex "${a}": unknown language "${h}" (supported: ${T.join(", ")})`);const{strategy:b}=o;if(b!==void 0&&!F(b))throw new i("INTERNAL",`searchIndex "${a}": unknown strategy "${b}" (supported: ${O.join(", ")})`);return d.push({field:o.field,filterFields:o.filterFields,language:o.language,name:a,staged:o.staged,strategy:o.strategy}),u},get searchIndexes(){return d},shape:n,shardBy(a){return $={field:a,kind:"shardBy"},u},get shardMode(){return $},get softDeleteMode(){return L},source(a){if(!a.binding)throw new i("INTERNAL","source: `binding` is required (the wrangler Hyperdrive binding name)");if(!a.query)throw new i("INTERNAL","source: `query` is required (the tenant-membership SQL)");return q=a,N=!0,u},softDelete(a){const o=a?.field??"deletedAt";return L={field:o},o in n||(n[o]=B.optional(B.number().nullable())),u},get triggerMap(){return m},triggers(a){return Object.assign(m,a(f)),u},ttl(a,o){return S={after:o?.after,field:a},u},get ttlPolicy(){return S},get vectorIndexes(){return p},vectorize(a,o){return p.push({dimensions:o.dimensions,embed:o.embed,field:a,metadata:o.metadata,metric:o.metric,name:o.index}),u}};return u},me=e=>({dimensions:e.dimensions,embed:e.embed,kind:"vectorIndex",metadata:e.metadata,metric:e.metric,select:e.source.select,table:e.source.table}),fe=(e,n)=>{const t=n.op??"count";if(t!=="count"&&!n.field)throw new i("INTERNAL",`aggregateIndex "${e}": op "${t}" requires a "field"`);return{by:n.by,field:n.field,name:e,on:n.on,op:t,where:n.where}},he=(e,n)=>{if(!n.sortBy||n.sortBy.length===0)throw new i("INTERNAL",`rankIndex "${e}": "sortBy" is required and must list at least one key`);const t=n.sortBy.map(r=>({direction:r.direction??"asc",field:r.field}));return{name:e,on:n.table,partitionBy:n.partitionBy,sortBy:t,where:n.where}},y=e=>({...e,extend(n){return y(D(e,n))},jurisdiction(n){return y(e)},rls(n){return y({...e,rlsMode:n})}}),V=e=>{for(const[n,t]of Object.entries(e)){for(const r of t.aggregateIndexes)r.on===""&&(r.on=n);for(const r of t.rankIndexes)r.on===""&&(r.on=n)}},Z=(e,n,t)=>{for(const r of Object.values(n)){const s=e[r.on];if(!s)throw new i("INTERNAL",`defineAggregateIndex "${r.name}": unknown table "${r.on}"`);s.aggregateIndexes.push(r)}for(const r of Object.values(t)){const s=e[r.on];if(!s)throw new i("INTERNAL",`defineRankIndex "${r.name}": unknown table "${r.on}"`);s.rankIndexes.push(r)}},ee=e=>{if(e.cursor)return"cursor";if(e.reconcileEveryMs!==void 0)return"reconcileEveryMs";if(e.softDeleteColumn!==void 0)return"softDeleteColumn"},ne=(e,n)=>{const t=n.mode==="incremental";if(n.mode!==void 0&&n.mode!=="full-pull"&&!t)throw new i("INTERNAL",`defineSchema: table "${e}" uses \`mode: ${JSON.stringify(n.mode)}\` — supported modes are "full-pull" (default) and "incremental".`);if(!t){const r=ee(n);if(r)throw new i("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(!n.cursor?.column||!n.cursor.query)throw new i("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(n.reconcileEveryMs===void 0&&n.softDeleteColumn===void 0)throw new i("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).`)},te=e=>{for(const[n,t]of Object.entries(e)){const r=t.externalSource;if(r){if(t.shardMode.kind==="global")throw new i("INTERNAL",`defineSchema: table "${n}" 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(t.shardMode.kind==="shardBy"&&!r.tenantBy)throw new i("INTERNAL",`defineSchema: sourced + .shardBy() table "${n}" 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.`);ne(n,r)}}},re=["_creationTime","_id"],oe=new Set(re),x=(e,n,t,r)=>{if(!(oe.has(t)||t in r.shape))throw new i("INTERNAL",`defineSchema: table "${e}" index "${n}" names column "${t}" which is not in the table's shape`)},k=(e,n,t,r)=>{const s=new Set;for(const l of t){if(s.has(l.name))throw new i("INTERNAL",`defineSchema: table "${e}" declares ${n} "${l.name}" more than once`);s.add(l.name),r(l)}},M=e=>{for(const[n,t]of Object.entries(e))k(n,"index",t.indexes,r=>{for(const s of r.fields)x(n,r.name,s,t)}),k(n,"rank index",t.rankIndexes,r=>{for(const s of r.sortBy)x(n,r.name,s.field,t);for(const s of r.partitionBy??[])x(n,r.name,s,t)}),k(n,"geo index",t.geoIndexes,r=>{x(n,r.name,r.field,t)})},v=(e,n,t)=>{if(e.length===0)return;const r={};for(const s of e)r[n(s)]=t(s);return r},ae=e=>{const n=new Set(e.sortBy.map(t=>t.field));for(const t of e.partitionBy??[])n.add(t);return[...n]},ge=e=>{const n={};for(const[t,r]of Object.entries(e.tables)){const s=v(r.geoIndexes,d=>d.name,d=>[d.field]),l=v(r.indexes,d=>d.name,d=>d.fields),c=v(r.rankIndexes,d=>d.name,ae);(s||l||c)&&(n[t]={...s?{geo:s}:{},...l?{index:l}:{},...c?{rank:c}:{}})}return n},be=(e,n={},t={},r={})=>(V(e),Z(e,t,r),te(e),M(e),y({tables:e,vectorIndexes:n})),I=(e,n)=>`${e}_${n}`,E=(e,n,t)=>t.has(e)?I(n,e):e,se=(e,n,t,r)=>{const s=I(n,r),l=f=>f===""?s:E(f,n,t),c={};for(const[f,p]of Object.entries(e.relationMap))c[f]={...p,table:E(p.table,n,t)};const d=e.aggregateIndexes.map(f=>({...f,on:l(f.on)})),m=e.rankIndexes.map(f=>({...f,on:l(f.on)}));return{...e,aggregateIndexes:d,rankIndexes:m,relationMap:c}},we=(e,n)=>{if(!e)throw new i("INTERNAL","defineSchemaExtension: `key` is required and must be a non-empty string");return{key:e,tables:n.tables,...n.vectorIndexes?{vectorIndexes:n.vectorIndexes}:{}}},ie=((e,n)=>{if(!e)throw new i("INTERNAL","definePlugin: `key` is required and must be a non-empty string");if(n.extension&&n.extension.key!==e)throw new i("INTERNAL",`definePlugin("${e}"): extension key "${n.extension.key}" does not match plugin key`);return{key:e,...n.extension?{extension:n.extension}:{},...n.middleware?{middleware:n.middleware}:{}}}),pe=(e,n)=>({...ie(e,{...n.extension?{extension:n.extension}:{},...n.middleware?{middleware:n.middleware}:{}}),functions:n.functions??{}}),D=(e,n)=>{const{key:t}=n,r=new Set(Object.keys(n.tables)),s={...e.tables};for(const[c,d]of Object.entries(n.tables)){const m=I(t,c);if(Object.hasOwn(s,m))throw new i("INTERNAL",`defineSchema(...).extend("${t}"): table "${m}" already exists in the base schema — another extension with the same key already contributed it`);s[m]=se(d,t,r,c)}const l={...e.vectorIndexes};if(n.vectorIndexes)for(const[c,d]of Object.entries(n.vectorIndexes)){const m=I(t,c);if(Object.hasOwn(l,m))throw new i("INTERNAL",`defineSchema(...).extend("${t}"): vector index "${m}" already exists in the base schema — another extension with the same key already contributed it`);l[m]={...d,table:E(d.table,t,r)}}return M(s),{rlsMode:e.rlsMode,tables:s,vectorIndexes:l}},xe=(e,n)=>{let t=e;for(const r of n)r.extension&&(t=D(t,r.extension));return t},ye=e=>{const n=e.map(t=>t.middleware).filter(t=>t!==void 0);return(async({ctx:t,next:r})=>z(n,t,s=>r({ctx:s})))};export{he as H,fe as K,M as N,ge as Q,be as W,ie as a,we as b,ye as c,pe as d,xe as i,ce as j,D as m,me as q};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as w}from"./LunoraError-LVhdU0Lo.mjs";import{bindOrm as F,bindTableFacade as U}from"./bindOrm-Bp9hsM2q.mjs";import{o as E}from"./optional-writer-override-CXXO30sZ.mjs";import{r as j}from"./policy-tag-Dprt9JWo.mjs";import{deny as $}from"./allowAll-BnyNbJZT.mjs";const T=500,k=(r,t,s)=>{const i=t??T;if(r>i)throw new w("BAD_REQUEST",`${s}: batch of ${String(r)} exceeds the limit of ${String(i)} (raise options.limit or chunk the call)`)},C=$(),L=Symbol.for("lunora.ctxdb.rls-unwrap"),q=r=>{const t=new Map;for(const s of r){const i=t.get(s.table)??[];i.push(s),t.set(s.table,i)}return t},z=(r,t)=>{const s=[];let i=!1;for(const u of r){if(u.on!=="read")continue;const c=u.when(t);if(c!==void 0){if(c===!0){i=!0;break}c!==!1&&s.push(c)}}if(!i)return s.length===0?C:s.length===1?s[0]:{OR:s}},I=r=>typeof r=="object"&&r!==null&&!Array.isArray(r),Q=["contains","eq","gt","gte","in","isNull","lt","lte","ne","notIn"],W=r=>{const t=typeof r;return t==="number"||t==="string"||t==="bigint"},G=(r,t)=>!("lt"in t&&(!W(r)||!W(t.lt)||r>=t.lt)||"lte"in t&&(!W(r)||!W(t.lte)||r>t.lte)||"gt"in t&&(!W(r)||!W(t.gt)||r<=t.gt)||"gte"in t&&(!W(r)||!W(t.gte)||r<t.gte)),H=(r,t)=>{if("in"in t){const s=t.in;if(!Array.isArray(s)||!s.includes(r))return!1}if("notIn"in t){const s=t.notIn;if(Array.isArray(s)&&s.includes(r))return!1}if("contains"in t){const s=t.contains;if(typeof r!="string"||typeof s!="string"||!r.includes(s))return!1}return!("isNull"in t&&t.isNull===!0!=(r==null))},J=(r,t)=>"eq"in t&&r!==t.eq||"ne"in t&&r===t.ne?!1:H(r,t)&&G(r,t),K=(r,t,s,i)=>t==="AND"?Array.isArray(s)&&s.every(u=>i(r,u)):t==="OR"?Array.isArray(s)&&s.some(u=>i(r,u)):!i(r,s??{}),P=r=>r==="AND"||r==="OR"||r==="NOT",V=r=>I(r)&&Object.keys(r).every(t=>Q.includes(t)),X=["every","is","isNot","none","some"],Y=r=>I(r)&&Object.keys(r).length>0&&Object.keys(r).every(t=>X.includes(t)),R=r=>Object.keys(r).some(t=>{const s=r[t];return P(t)?t==="NOT"?R(s??{}):Array.isArray(s)&&s.some(i=>R(i??{})):Y(s)}),v=(r,t)=>{for(const s of Object.keys(t)){const i=t[s];if(P(s)){if(!K(r,s,i,v))return!1;continue}const u=r[s];if(V(i)){if(!J(u,i))return!1;continue}if(u!==i)return!1}return!0},Z=(r,t,s)=>{const i=r.when({...t,row:s});if(i===void 0||i===!0)return!0;if(i===!1)return!1;if(R(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 v(s,i)},ee=(r,t,s)=>{const i=r.when(t);if(i===void 0||i===!0)return s===void 0||Z(r,t,s);if(i===!1)return!1;if(R(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!t.row||!v(t.row,i)?!1:s===void 0||v(s,i)},M=(r,t,s,i)=>{let u=!1;for(const c of r)if(c.on===t&&(u=!0,!ee(c,s,i)))return!1;return u},S=r=>r??{},re=new Set(["baseWhere","relationBaseWhere","restrictsCounts","where"]),te=(r,t)=>t===void 0?!0:r==="restrictsCounts"?typeof t=="boolean":r==="relationBaseWhere"?typeof t=="function":I(t),ae=r=>{const t=Object.keys(r);return t.length===0?!1:t.every(s=>re.has(s)&&te(s,r[s]))},ne=r=>r===void 0?{}:I(r)&&ae(r)?r:{where:r},b=(r,t)=>!t||Object.keys(t).length===0?r:!r||Object.keys(r).length===0?t:{AND:[t,r]},se=r=>{if(typeof r!="object"||r===null||Array.isArray(r))return!1;const t=r;return typeof t.findMany=="function"&&typeof t.withSearchIndex=="function"},oe=(r,t,s,i)=>{const u=new Map,c=e=>{const a=u.get(e);if(a)return a;const n=s.get(e);if(!n||n.length===0||!n.some(l=>l.on==="read")){const l={baseWhere:void 0,restricts:!1};return u.set(e,l),l}const o={baseWhere:z(n,i),restricts:!0};return u.set(e,o),o},f=e=>c(e).restricts?t:r,y=e=>c(e).baseWhere,N=async(e,a)=>{if(t.lookupById){const h=await t.lookupById(e,a);return h?{row:h.row,tableName:s.has(h.tableName)?h.tableName:void 0}:{row:null,tableName:void 0}}const n=await t.get(e,a);if(!n)return{row:null,tableName:void 0};const o=a!==void 0&&s.has(a)?[a]:[],l=a===void 0?[...s.keys()]:o,d=await Promise.all(l.map(async h=>(await t.findFirst(h,{limit:1,where:{_id:e}}))?._id===e?h:void 0));return{row:n,tableName:d.find(h=>h!==void 0)}},B=async(e,a)=>{const n=await N(e,a);return n.row&&n.tableName!==void 0?{row:n.row,tableName:n.tableName}:void 0},p=async(e,a,n,o,l)=>{const d=await B(e,l);if(!d)return n(r);const h=s.get(d.tableName);if(h){const D=o?o(d.row):void 0;if(!M(h,a,{...i,row:d.row},D))throw new w("FORBIDDEN",`${a} denied by policy`)}return n(t)},m=(e,a)=>{const{baseWhere:n,restricts:o}=c(e);if(o)throw new w("COUNT_RLS_UNSUPPORTED",`${a}() is not supported on "${e}" inside an RLS-restricted context`);return n},_=r.rankBefore,O=r.rankPageRows,g={...r,async count(e,a){const{baseWhere:n,restricts:o}=c(e),l=ne(a);return f(e).count(e,{...l,baseWhere:b(l.baseWhere,n),relationBaseWhere:y,restrictsCounts:(l.restrictsCounts??!1)||o})},delete:(e,a,n)=>p(e,"delete",o=>o.delete(e,a,n),void 0,a),async deleteAll(e,a){const n=Math.max(1,a?.chunkSize??T),{baseWhere:o}=c(e);let l=0;for(;;){const d=(await f(e).findMany(e,{baseWhere:o,limit:n,relationBaseWhere:y})).page.map(h=>String(h._id));if(d.length===0)break;for(const h of d)await p(h,"delete",D=>D.delete(h,void 0,a?.hard===void 0?void 0:{hard:a.hard})),l+=1;if(d.length<n)break}return{deleted:l}},async deleteMany(e,a,n){k(e.length,a?.limit,"deleteMany");for(const o of e)await p(o,"delete",l=>l.delete(o,n),void 0,n);return{deleted:e.length}},async deleteWhere(e,a,n){const{baseWhere:o}=c(e),l=(await f(e).findMany(e,{baseWhere:b(a,o),relationBaseWhere:y})).page.map(d=>String(d._id));return k(l.length,n?.limit,"deleteWhere"),g.deleteMany(l,n)},async findFirst(e,a){const{baseWhere:n}=c(e);return f(e).findFirst(e,{...S(a),baseWhere:b(a?.baseWhere,n),relationBaseWhere:y})},async findFirstOrThrow(e,a){const{baseWhere:n}=c(e);return f(e).findFirstOrThrow(e,{...S(a),baseWhere:b(a?.baseWhere,n),relationBaseWhere:y})},async findMany(e,a){const{baseWhere:n}=c(e);return f(e).findMany(e,{...S(a),baseWhere:b(a?.baseWhere,n),relationBaseWhere:y})},async get(e,a){const n=await N(e,a);if(!n.row)return null;if(n.tableName===void 0)return r.get(e,a);const{baseWhere:o,restricts:l}=c(n.tableName);if(!l)return r.get(e,a);if(!o)return n.row;const d=await t.findFirst(n.tableName,{baseWhere:o,limit:1,where:{_id:e}});return d?._id===e?d:null},async lookupById(e,a){const n=await N(e,a);if(!n.row)return null;if(n.tableName===void 0||!c(n.tableName).restricts)return await r.lookupById?.(e,a)??null;const{baseWhere:o}=c(n.tableName);if(!o)return{row:n.row,tableName:n.tableName};const l=await t.findFirst(n.tableName,{baseWhere:o,limit:1,where:{_id:e}});return l?._id===e?{row:l,tableName:n.tableName}:null},async insert(e,a){const n=s.get(e);if(n){if(!M(n,"insert",{...i,row:a}))throw new w("FORBIDDEN",`insert on "${e}" denied by policy`);return t.insert(e,a)}return r.insert(e,a)},async insertMany(e,a,n){k(a.length,n?.limit,"insertMany");const o=s.get(e);if(o){for(const l of a)if(!M(o,"insert",{...i,row:l}))throw new w("FORBIDDEN",`insert on "${e}" denied by policy`);return t.insertMany(e,a,n)}return r.insertMany(e,a,n)},async insertManyUnsafe(e,a,n){k(a.length,n?.limit,"insertManyUnsafe");const o=s.get(e);if(o){for(const l of a)if(!M(o,"insert",{...i,row:l}))throw new w("FORBIDDEN",`insert on "${e}" denied by policy`);return t.insertManyUnsafe(e,a,n)}return r.insertManyUnsafe(e,a,n)},patch:(e,a,n)=>p(e,"update",o=>o.patch(e,a,n),o=>({...o,...a}),n),async patchMany(e,a,n){k(e.length,a?.limit,"patchMany");for(const o of e)await p(o.id,"update",l=>l.patch(o.id,o.patch,n),l=>({...l,...o.patch}),n);return{patched:e.length}},async patchWhere(e,a,n){const{baseWhere:o}=c(e),l=(await f(e).findMany(e,{baseWhere:b(a.where,o),relationBaseWhere:y})).page.map(d=>({id:String(d._id),patch:a.patch}));return k(l.length,n?.limit,"patchWhere"),g.patchMany(l,n)},query(e){const{baseWhere:a}=c(e),n=f(e).query(e);return a?n.filter(o=>v(o,a)):n},restore:(e,a)=>p(e,"update",async n=>{const o=n.restore??t.restore;if(!o)throw new w("BAD_REQUEST","restore is not supported by this writer");await o(e,a)},void 0,a),replace:(e,a,n)=>p(e,"update",o=>o.replace(e,a,n),o=>({...a,_creationTime:a._creationTime??o._creationTime,_id:o._id}),n),aggregate(e,a){const{baseWhere:n}=c(e);return f(e).aggregate(e,{...a,baseWhere:b(a.baseWhere,n),relationBaseWhere:y})},groupBy(e,a){const{baseWhere:n}=c(e);return f(e).groupBy(e,{...a,baseWhere:b(a.baseWhere,n),relationBaseWhere:y})},rank(e,a,n){const o=m(e,"rank");return f(e).rank(e,a,{...n,baseWhere:b(n.baseWhere,o)})},rankPage(e,a,n){const o=m(e,"rankPage");return f(e).rankPage(e,a,{...n,baseWhere:b(n?.baseWhere,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})},...E("rankBefore",_,e=>(a,n,o)=>(m(a,"rankBefore"),(f(a).rankBefore??e)(a,n,o))),...E("rankPageRows",O,e=>(a,n,o)=>{const l=m(a,"rankPageRows");return(f(a).rankPageRows??e)(a,n,{...o,baseWhere:b(o?.baseWhere,l)})})},A=g;for(const e of s.keys())se(r[e])&&(A[e]=U(g,e));return g},x=r=>typeof r=="string"?r:r.name,ie=r=>{const t=new Map;for(const s of r??[])t.set(s.name,new Set((s.permissions??[]).map(i=>x(i))));return t},he=(r,t={})=>{const s=q(r),i=ie(t.roles);return j(async({ctx:u,next:c})=>{const f=u.auth??{},y=await f.getIdentity?.()??null,N=f.roles??[],B=new Set;for(const e of N)for(const a of i.get(e)??[])B.add(a);const p={auth:{can:e=>B.has(x(e)),identity:y,roles:N,userId:f.userId??null},ctx:u},m=u.db,_=m[L]??m,O=oe(m,_,s,p),g={db:O},{orm:A}=u;return A!==null&&typeof A=="object"&&(g.orm=F(O)),c({ctx:g})},{policies:r,roles:t.roles??[]})};export{z as computeReadBaseWhere,M as evaluateWrite,ie as indexRolePermissions,v as matchesWhere,x as permissionName,he as rls};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as S}from"./LunoraError-LVhdU0Lo.mjs";const b=t=>typeof t=="string"?t:t.name,v=(t=[])=>{const e=new Map;for(const s of t){const a=new Set;for(const i of s.permissions??[])a.add(b(i));e.set(s.name,a)}return e},N=(t,e)=>t===void 0||e.startsWith(t),R=t=>{const e=t[1],s=typeof e=="object"&&e!==null?e.method:void 0;return typeof s=="string"&&s.toUpperCase()==="PUT"?"write":"read"},$=[["delete","delete"],["download","read"],["generateUploadUrl","write"],["getMetadata","read"],["getSignedUrl",R],["getUrl","read"],["store","write"]],E=(t,e={})=>{const s=v(e.roles);return async({ctx:a,next:i})=>{const l=a.auth??{},h=await l.getIdentity?.()??null,g=l.roles??[],y=new Set;for(const o of g)for(const r of s.get(o)??[])y.add(r);const k={can:o=>y.has(b(o)),identity:h,roles:g,userId:l.userId??null},x=(o,r,c)=>{const f=t.filter(n=>n.on===o&&n.bucket===c);if(f.length===0)return;const u={auth:k,ctx:a,key:r};if(!f.some(n=>N(n.prefix,r)&&n.when(u)===!0))throw new S("FORBIDDEN",`storage ${o} on "${r}" in bucket "${c}" denied by access rule`)},p=o=>{const r=o.bucketName??"default",c={bucketName:r};for(const[u,n]of $){const m=o[u];typeof m=="function"&&(c[u]=(...d)=>{const U=typeof d[0]=="string"?d[0]:"",I=typeof n=="function"?n(d):n;return x(I,U,r),m(...d)})}const{bucket:f}=o;return typeof f=="function"&&(c.bucket=u=>p(f(u))),c},w=a.storage;return w===void 0?i():i({ctx:{storage:p(w)}})}};export{E as storageRules};
|