@lunora/server 1.0.0-alpha.193 → 1.0.0-alpha.195

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.
Files changed (28) hide show
  1. package/dist/data-model.d.mts +165 -14
  2. package/dist/data-model.d.ts +165 -14
  3. package/dist/in-process.mjs +1 -1
  4. package/dist/index.d.mts +100 -12
  5. package/dist/index.d.ts +100 -12
  6. package/dist/index.mjs +1 -1
  7. package/dist/packem_shared/{ACTION_CACHE_DEFAULT_TTL_MS-DITNUhX1.mjs → ACTION_CACHE_DEFAULT_TTL_MS-BFmhdKJG.mjs} +1 -1
  8. package/dist/packem_shared/{DOCUMENT_HISTORY_REDACTED_FIELDS-BYeHnULU.mjs → DOCUMENT_HISTORY_REDACTED_FIELDS-BeS7G0yM.mjs} +1 -1
  9. package/dist/packem_shared/{PRESENCE_DEFAULT_TTL_MS-Bvno49rr.mjs → PRESENCE_DEFAULT_TTL_MS-DFpy5J8G.mjs} +1 -1
  10. package/dist/packem_shared/{assertShapesDeclareReadPolicies-CUB_PC20.mjs → assertShapesDeclareReadPolicies-isd_Yupt.mjs} +1 -1
  11. package/dist/packem_shared/bindOrm-BHq_oUP2.mjs +1 -0
  12. package/dist/packem_shared/{composePluginMiddleware-bf3t7KZi.mjs → composePluginMiddleware-ZtDIkbvJ.mjs} +1 -1
  13. package/dist/packem_shared/{defineAggregateIndex--ttNAY7M.mjs → defineAggregateIndex-DF8NiKHr.mjs} +1 -1
  14. package/dist/packem_shared/{defineShape-raxlSVvO.mjs → defineShape-CX9Xs8AY.mjs} +1 -1
  15. package/dist/packem_shared/mask-BdULkLAu.mjs +1 -0
  16. package/dist/packem_shared/middleware-DbhB1jRk.mjs +1 -0
  17. package/dist/packem_shared/plugin-Bm9wIpiI.mjs +1 -0
  18. package/dist/packem_shared/rls-B3xf3YrN.mjs +1 -0
  19. package/dist/packem_shared/{storageRules-BQx91H4g.mjs → storageRules-CMfQu8yY.mjs} +1 -1
  20. package/dist/rls/testing.mjs +1 -1
  21. package/dist/types.d.mts +35 -7
  22. package/dist/types.d.ts +35 -7
  23. package/package.json +4 -4
  24. package/dist/packem_shared/bindOrm-D_hFUjmr.mjs +0 -1
  25. package/dist/packem_shared/mask-0D6SL3i5.mjs +0 -1
  26. package/dist/packem_shared/middleware-DAVx_tP1.mjs +0 -1
  27. package/dist/packem_shared/plugin-xbEqjwqP.mjs +0 -1
  28. package/dist/packem_shared/rls-CpSeGhdp.mjs +0 -1
@@ -0,0 +1 @@
1
+ import{LunoraError as p}from"@lunora/errors";import{i as M}from"./wire-codec-CZ4obM6q.mjs";const b=new Set(["connect","disconnect","set"]),y=500,I=(t,n,s)=>t!==void 0&&Object.hasOwn(t,n)&&M(s),v=t=>typeof t=="object"&&t!==null&&t.code==="CONFLICT"&&t.kind==="unique",u=(t,n)=>{throw new p(t,n)},O=(t,n)=>{if(!Array.isArray(t)||t.some(e=>typeof e!="string"))return u("VALIDATION_ERROR",`${n} must be an array of ids`);const s=[...new Set(t)];return s.length>y&&u("VALIDATION_ERROR",`${n} names ${String(s.length)} rows; at most ${String(y)} per list`),s},E=(t,n,s)=>{n.nullable||u("VALIDATION_ERROR",`${t}.${s}: "${n.field}" cannot be empty; make it optional or nullable to allow it`)},D=(t,n,s)=>{const{connect:e,disconnect:i,set:c}=s;return c!==void 0&&u("VALIDATION_ERROR",`${t} is a to-one relation: use connect or disconnect, not set`),e!==void 0&&i!==void 0&&u("VALIDATION_ERROR",`${t}: connect and disconnect together are ambiguous`),e!==void 0?(typeof e!="string"&&u("VALIDATION_ERROR",`${t}.connect must be an id`),{connect:e,info:n,name:t}):(i!==!0&&u("VALIDATION_ERROR",`${t}.disconnect must be true`),E(t,n,"disconnect"),{info:n,name:t})},A=(t,n,s)=>{n.through===void 0&&E(t,n,s)},k=(t,n,s)=>{const{connect:e,disconnect:i,set:c}=s;if(c!==void 0)return(e!==void 0||i!==void 0)&&u("VALIDATION_ERROR",`${t}: set replaces the whole list and cannot be combined with connect or disconnect`),A(t,n,"set"),{attach:[],info:n,name:t,release:[],replace:O(c,`${t}.set`)};i!==void 0&&A(t,n,"disconnect");const a=e===void 0?[]:O(e,`${t}.connect`),r=i===void 0?[]:O(i,`${t}.disconnect`),o=a.find(d=>r.includes(d));return o!==void 0&&u("VALIDATION_ERROR",`${t}: "${o}" is in both connect and disconnect, which is ambiguous`),{attach:a,info:n,name:t,release:r}},j=(t,n,s,e)=>{const i=Object.fromEntries(Object.entries(e).filter(([,r])=>r!==void 0)),c=Object.keys(i).find(r=>!b.has(r));if(c!==void 0&&u("VALIDATION_ERROR",`ctx.db.${t}: "${n}.${c}" is not a relation operator; use connect, disconnect or set`),Object.keys(i).length===0)return;const a=s.refusal??s.refusalNow?.();return a!==void 0&&u("UNPROCESSABLE",`ctx.db.${t}: relation "${n}" cannot be written: ${a}`),s.colocated||u("UNPROCESSABLE",`ctx.db.${t}: relation "${n}" crosses to "${s.table}" on another shard or backend, so a nested write cannot be applied atomically; write each side yourself`),s.kind==="one"?D(n,s,i):k(n,s,i)},W=t=>t.info.kind==="one",T=(t,n,s)=>{if(n===void 0)return{columns:s,manys:[],ones:[]};const e={},i=[],c=[];for(const[a,r]of Object.entries(s)){if(!I(n,a,r)){e[a]=r;continue}const o=j(t,a,n[a],r);o!==void 0&&(W(o)?c.push(o):i.push(o))}for(const{info:a,name:r}of c)Object.hasOwn(e,a.field)&&u("VALIDATION_ERROR",`ctx.db.${t}: ${r} and its key "${a.field}" are both set; set one or the other`);return{columns:e,manys:i,ones:c}},$=(t,n,s,e)=>{const i=Object.entries(s).find(([c,a])=>I(n,c,a))?.[0];i!==void 0&&u("VALIDATION_ERROR",`ctx.db.${t}.${e}: "${i}" is a relation write, which ${e} does not support; use insert or patch`)},R=async(t,n,s,e,i)=>{const c=await t.get(i,e);return c===null&&u("NOT_FOUND",`${n}.${s}: no "${e}" row with id "${i}"`),c},_=async(t,n)=>{const s={...n.columns};for(const{connect:e,info:i,name:c}of n.ones){let a=null;e!==void 0&&(a=(await R(t,c,"connect",i.table,e))[i.references]),s[i.field]=a}return s},F=async(t,{info:n,name:s},e,i)=>{(await R(t,s,"connect",n.table,e))[n.field]!==i&&await t.patch(e,{[n.field]:i},n.table)},U=async(t,{info:n},s,e)=>{s[n.field]===e&&await t.patch(String(s._id),{[n.field]:null},n.table)},V=async(t,{info:n,name:s},e)=>{const{page:i}=await t.findMany(n.table,{limit:y+1,where:{[n.field]:e}});return i.length>y&&u("VALIDATION_ERROR",`${s}.set: the relation already holds more than ${String(y)} rows; disconnect in batches first`),i},L=(t,n)=>{const s=new Set(t),e=new Set(n);return{attach:n.filter(i=>!s.has(i)),release:new Set(t.filter(i=>!e.has(i)))}},w=async(t,{name:n},{from:s,table:e,to:i},c,a)=>{const r=a===void 0?{[s]:c}:{[s]:c,[i]:{in:a}},{page:o}=await t.findMany(e,{limit:y+1,where:r});return o.length>y&&u("VALIDATION_ERROR",`${n}: the relation already holds more than ${String(y)} rows; disconnect in batches first`),o},C=async(t,n,s)=>{if(s.length===0)return new Set;const{page:e}=await t.findMany(n,{limit:s.length,where:{_id:{in:s}}});return new Set(e.map(i=>String(i._id)))},P=async(t,n,s)=>{const{info:e,name:i}=n,{from:c,table:a,to:r}=e.through;let o,d;if(n.replace===void 0){await Promise.all(n.release.map(l=>R(t,i,"disconnect",e.table,l))),d=n.release.length===0?[]:await w(t,n,e.through,s,n.release);const h=n.attach.length===0?[]:await w(t,n,e.through,s,n.attach),f=new Set(h.map(l=>String(l[r])));o=n.attach.filter(l=>!f.has(l))}else{const h=await w(t,n,e.through,s,void 0),f=L(h.map(g=>String(g[r])),n.replace),l=await C(t,e.table,[...f.release]);({attach:o}=f),d=h.filter(g=>f.release.has(String(g[r]))&&l.has(String(g[r])))}await Promise.all(o.map(h=>R(t,i,"connect",e.table,h)));for(const h of d)await t.delete(String(h._id),a);for(const h of o)try{await t.insert(a,{[c]:s,[r]:h})}catch(f){if(!v(f)||!e.pairIsOnlyUnique)throw f}},q=async(t,n,s)=>{let{attach:e}=n,i;if(n.replace===void 0)i=await Promise.all(n.release.map(c=>R(t,n.name,"disconnect",n.info.table,c)));else{const c=await V(t,n,s),a=L(c.map(r=>String(r._id)),n.replace);({attach:e}=a),i=c.filter(r=>a.release.has(String(r._id)))}for(const c of i)await U(t,n,c,s);for(const c of e)await F(t,n,c,s)},S=async(t,n,s,e)=>{for(const i of s.manys){const{info:c}=i,a=c.through===void 0?c.references:"_id",r=await e(a);if(r==null&&u("VALIDATION_ERROR",`ctx.db.${n}: ${i.name} is keyed on "${a}", which this row has no value for`),c.through!==void 0){await P(t,{...i,info:c},r);continue}await q(t,{...i,info:c},r)}},x=(t,n,s,e)=>async i=>i==="_id"?s:Object.hasOwn(e,i)?e[i]:(await t.get(s,n))?.[i],B=async(t,n,s,e,i)=>{const c=T(n,s,e);if(c.ones.length===0&&c.manys.length===0)return i(c.columns);const a=await _(t,c),r=await i(a);return r!==null&&await S(t,n,c,x(t,n,r,a)),r},m=async(t,n,s,e,i)=>{const c=T(n,s,i);if(c.ones.length===0&&c.manys.length===0){await t.patch(e,c.columns,n);return}const a=await _(t,c);if(Object.keys(a).length>0)await t.patch(e,a,n);else{if(await t.get(e,n)===null)throw new p("NOT_FOUND",`document not found: ${e}`);await t.assertPatchAllowed?.(e,n)}await S(t,n,c,x(t,n,e,a))},G=(t,n,s,e)=>{const i=typeof n=="string"?[n]:n;if(i.length===0)throw new p("INTERNAL",`ctx.db.${t}.upsert: "target" must name at least one field`);const c={};for(const a of i){if(!(a in s)){const r=Object.entries(e??{}).find(([o,d])=>d.kind==="one"&&d.field===a&&o in s)?.[0];throw r!==void 0?new p("VALIDATION_ERROR",`ctx.db.${t}.upsert: target field "${a}" is supplied by the "${r}" relation write; pass "${a}" itself so the existing row can be found`):new p("INTERNAL",`ctx.db.${t}.upsert: target field "${a}" is missing from the create document`)}c[a]=s[a]}return c},X=(t,n)=>{const s=async(o,d)=>{if(d?.skipDuplicates!==!0)return t.insert(n,o);try{return await t.insert(n,o)}catch(h){if(v(h))return null;throw h}},e=t.relationWrites?.[n],i=(o,d)=>B(t,n,e,o,h=>s(h,d)),c=(o,d)=>m(t,n,e,o,d),a=async o=>{const d=o??{},h=await t.findMany(n,{...d,limit:2});if(h.page.length>1)throw new p("NOT_UNIQUE",`ctx.db.${n}.findUnique matched more than one document; expected at most one`);return h.page[0]??null},r=async({create:o,target:d,update:h})=>{const f=G(n,d,o,e),l=await t.findFirst(n,{where:f});return l&&typeof l._id=="string"?(await c(l._id,h??o),{created:!1,id:l._id}):{created:!0,id:await i(o)}};return{aggregate:o=>t.aggregate(n,o),count:o=>t.count(n,o),delete:o=>t.delete(o,n),deleteMany:(o,d)=>{if(Array.isArray(o)){if(t.deleteMany===void 0)throw new p("INTERNAL",`ctx.db.${n}.deleteMany is unavailable: this writer has no batch delete`);return t.deleteMany(o,d,n)}if(t.deleteWhere===void 0)throw new p("INTERNAL",`ctx.db.${n}.deleteMany({ where }) is unavailable: this writer has no where-based delete`);const h=o;return t.deleteWhere(n,h.where,{limit:h.limit})},exists:async o=>await t.findFirst(n,o===void 0?void 0:{where:o})!==null,explain:o=>t.explain(n,o),findFirst:o=>t.findFirst(n,o),findFirstOrThrow:o=>t.findFirstOrThrow(n,o),findMany:o=>t.findMany(n,o),findUnique:a,get:o=>t.get(o,n),groupBy:o=>t.groupBy(n,o),hardDelete:o=>t.delete(o,n,{hard:!0}),insert:i,insertMany:(o,d)=>{for(const h of o)$(n,e,h,"insertMany");if(t.insertMany===void 0)throw new p("INTERNAL",`ctx.db.${n}.insertMany is unavailable: this writer has no batch insert`);return t.insertMany(n,o,d)},patch:c,patchMany:(o,d)=>{const h=Array.isArray(o)?o.map(l=>l.values):[o.values];for(const l of h)$(n,e,l,"patchMany");if(Array.isArray(o)){if(t.patchMany===void 0)throw new p("INTERNAL",`ctx.db.${n}.patchMany is unavailable: this writer has no batch patch`);return t.patchMany(o.map(l=>({id:l.id,patch:l.values})),d,n)}if(t.patchWhere===void 0)throw new p("INTERNAL",`ctx.db.${n}.patchMany({ where, values }) is unavailable: this writer has no where-based patch`);const f=o;return t.patchWhere(n,{patch:f.values,where:f.where},{limit:f.limit})},rank:(o,d)=>t.rank(n,o,d),rankPage:(o,d)=>t.rankPage(n,o,d),replace:(o,d)=>($(n,e,d,"replace"),t.replace(o,d,n)),restore:async o=>{if(!t.restore)throw new p("INTERNAL",`ctx.db.${n}.restore is unavailable: this writer has no restore (is the table .softDelete()?)`);await t.restore(o,n)},upsert:r,upsertMany:async({rows:o,target:d})=>{const h=[];for(const f of o)h.push(await r({create:f.create,target:d,update:f.update}));return h},withGeoIndex:(o,d)=>t.query(n).withGeoIndex(o,d),withSearchIndex:(o,d)=>t.query(n).withSearchIndex(o,d)}},z=t=>{const n=s=>{const e=t[s];if(!e)throw new p("INTERNAL",`unknown table: ${s}`);return e};return{delete:(s,e)=>n(s).delete(e),insert:s=>({values:e=>n(s).insert(e)}),query:t,replace:(s,e)=>({with:i=>n(s).replace(e,i)}),update:(s,e)=>({set:i=>n(s).patch(e,i)})}};export{z as bindOrm,X as bindTableFacade};
@@ -1 +1 @@
1
- import"./compose-middleware-BK9FlblN.mjs";import{c as i,a as s,b as o,g as m,k as l,m as t}from"./plugin-xbEqjwqP.mjs";export{i as composePluginMiddleware,s as defineComponent,o as definePlugin,m as defineSchemaExtension,l as installPlugins,t as mergeSchemaExtension};
1
+ import"./compose-middleware-BK9FlblN.mjs";import{c as i,a as s,b as o,g as m,k as l,m as t}from"./plugin-Bm9wIpiI.mjs";export{i as composePluginMiddleware,s as defineComponent,o as definePlugin,m as defineSchemaExtension,l as installPlugins,t as mergeSchemaExtension};
@@ -1 +1 @@
1
- import{d,e as s,f as i,h as n,i as l,j as f,v as o,l as t,n as r}from"./plugin-xbEqjwqP.mjs";export{d as defineAggregateIndex,s as defineRankIndex,i as defineSchema,n as defineTable,l as defineVectorIndex,f as indexFieldsFromSchema,o as validateGlobalVectors,t as validateIndexFields,r as validateTableModes};
1
+ import{d,e as s,f as i,h as n,i as l,j as f,v as o,l as t,n as r}from"./plugin-Bm9wIpiI.mjs";export{d as defineAggregateIndex,s as defineRankIndex,i as defineSchema,n as defineTable,l as defineVectorIndex,f as indexFieldsFromSchema,o as validateGlobalVectors,t as validateIndexFields,r as validateTableModes};
@@ -1 +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-CUB_PC20.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
+ 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-isd_Yupt.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};
@@ -0,0 +1 @@
1
+ import{LunoraError as A}from"@lunora/errors";import{f as D}from"./fnv1a-D3ueNTWB.mjs";import{i as G,a as C,o as K,b as H,c as J,d as m}from"./middleware-DbhB1jRk.mjs";import{bindTableFacade as Q,bindOrm as V}from"./bindOrm-BHq_oUP2.mjs";import{tagMaskMiddleware as X}from"./buildMaskRegistry-DpWMtalG.mjs";const Y=(s,i,c)=>{try{return s==="redact"?null:s==="hash"?i==null?i:typeof i=="bigint"?D(i.toString()):D(typeof i=="string"?i:JSON.stringify(i)):s(i,c)}catch{return null}},f=(s,i,c)=>{const w={...s};for(const[y,g]of Object.entries(i))y in w&&(w[y]=Y(g,s[y],{...c,column:y,row:s}));return w},F=(s,i,c)=>({...s,page:s.page.map(w=>f(w,i,c))}),I=(s,i)=>{const c=J(i);return s instanceof Set?s.has(c):Object.hasOwn(s,c)},L=(s,i,c,w)=>{if(typeof s!="function")return;const y=new Set,g=()=>new Proxy({},{get:()=>u=>(typeof u=="string"&&y.add(u),g())});s(g());for(const u of y)if(I(i,u))throw new A("MASK_UNSUPPORTED",`${w}() filtering "${c}" by masked column "${u}" is not supported`)},Z=(s,i,c,w)=>{const y=s.rankBefore,g=s.rankPageRows,u=(r,t)=>{const n=i.get(r);return n?t.map(o=>f(o,n,c)):t},l=r=>{const t=r?.relationMask;return{...r,relationMask:t===void 0?u:(n,o)=>t(n,u(n,o))}},p=(r,t,n,o)=>{const e=i.get(r);if(!e)return;const a=w?.[r]?.[o]?.[t];if(!a)return;const d=a.find(R=>I(e,R));if(d!==void 0)throw new A("MASK_UNSUPPORTED",`${n}() reading "${r}" via index "${t}" would order rows by masked column "${d}" — use an index whose declared fields are all unmasked, or unmask the column`)},k=(r,t,n)=>({async*[Symbol.asyncIterator](){for await(const o of{[Symbol.asyncIterator]:()=>r[Symbol.asyncIterator]()})yield f(o,t,c)},collect:async()=>(await r.collect()).map(e=>f(e,t,c)),collectWithScores:async()=>(await r.collectWithScores()).map(e=>{const a=f(e.document,t,c);return"distanceMeters"in e?{distanceMeters:null,document:a}:{document:a,score:e.score}}),filter:o=>k(r.filter(e=>o(f(e,t,c))),t,n),first:async()=>{const o=await r.first();return o?f(o,t,c):null},order:o=>k(r.order(o),t,n),paginate:async o=>F(await r.paginate(o),t,c),take:async o=>(await r.take(o)).map(a=>f(a,t,c)),unique:async()=>{const o=await r.unique();return o?f(o,t,c):null},withIndex:(o,e)=>(p(n,o,"withIndex","index"),L(e,t,n,"withIndex"),k(r.withIndex(o,e),t,n)),withSearchIndex:(o,e)=>(L(e,t,n,"withSearchIndex"),k(r.withSearchIndex(o,e),t,n)),withGeoIndex:(o,e)=>(p(n,o,"withGeoIndex","geo"),k(r.withGeoIndex(o,e),t,n))}),W=async(r,t)=>{if(s.lookupById){const d=await s.lookupById(r,t);if(d)return{row:d.row,tableName:i.has(d.tableName)?d.tableName:void 0}}const n=await s.get(r,t);if(!n)return{row:null,tableName:void 0};const o=t!==void 0&&i.has(t)?[t]:[],e=t===void 0?[...i.keys()]:o,a=await Promise.all(e.map(async d=>(await s.findFirst(d,{limit:1,where:{_id:r}}))?._id===r?d:void 0));return{row:n,tableName:a.find(d=>d!==void 0)}},S=(r,t,n)=>{const o=i.get(r);if(!o)return;const e=t.find(a=>typeof a=="string"&&I(o,a));if(e!==void 0)throw new A("MASK_UNSUPPORTED",`${n}() over masked column "${e}" on "${r}" is not supported`)},O=new Set;for(const r of i.values())for(const t of Object.keys(r))O.add(t);const P=(r,t,n,o)=>{if(!(!r||typeof r!="object"||Array.isArray(r)))for(const[e,a]of Object.entries(r))q(e,a,t,n,o)},q=(r,t,n,o,e)=>{if(r==="AND"||r==="OR"){for(const a of Array.isArray(t)?t:[])P(a,n,o,e);return}if(r==="NOT"){P(t,n,o,e);return}if(!r.startsWith("__")){if(I(n,r))throw new A("MASK_UNSUPPORTED",`${e}() filtering "${o}" by masked column "${r}" is not supported`);if(m(t))for(const a of Object.values(t))P(a,O,`${o}.${r}`,e)}},E=r=>{const t=i.get(r);return t?new Set(Object.keys(t)):new Set},h=(r,t,n)=>{O.size===0||t===void 0||P(t,E(r),r,n)},U=(r,t,n,o)=>{if(Array.isArray(t)){for(const e of t)if(!(!e||typeof e!="object"||Array.isArray(e))){for(const a of Object.keys(e))if(I(n,a))throw new A("MASK_UNSUPPORTED",`${o}() ordering "${r}" by masked column "${a}" is not supported`)}}},v=(r,t,n)=>{if(!(O.size===0||!t||typeof t!="object"||Array.isArray(t)))for(const[o,e]of Object.entries(t)){if(o==="_count"||!e||typeof e!="object"||Array.isArray(e))continue;const a=e,d=`${r}.${o}`;P(a.where,O,d,n),U(d,a.orderBy,O,n),v(d,a.with,n)}},$=(r,t,n)=>{h(r,t?.where,n),h(r,t?.baseWhere,n),U(r,t?.orderBy,E(r),n),v(r,t?.with,n)},_=r=>r&&typeof r=="object"&&!Array.isArray(r)?r:void 0,M=(r,t,n)=>{const o=_(t);h(r,o?.where,n),h(r,o?.baseWhere,n),v(r,o?.with,n)},j=(r,t)=>Object.hasOwn(i.get(r)??{},t)?t:void 0,B={...s,relationWrites:(()=>{if(s.relationWrites===void 0)return;const r={};for(const[t,n]of Object.entries(s.relationWrites))r[t]=Object.fromEntries(Object.entries(n).map(([o,e])=>{const[a,d]=e.kind==="one"?[t,e.table]:[e.table,t],R=e.through?j(e.through.table,e.through.from)??j(e.through.table,e.through.to):j(a,e.field)??j(d,e.references);return[o,R===void 0?e:{...e,refusal:`"${R}" is masked for this caller, so its stored value cannot be copied`}]}));return r})(),async deleteWhere(r,t,n){if(h(r,t,"deleteMany({ where })"),s.deleteWhere===void 0)throw new A("INTERNAL",`ctx.db.${r}.deleteMany({ where }) is unavailable: this writer has no where-based delete`);return s.deleteWhere(r,t,n)},async patchIf(r,t,n){if(h(r,n.where,"patchIf"),s.patchIf===void 0)throw new A("INTERNAL",`ctx.db.patchIf on "${r}" is unsupported: this writer has no conditional write`);const o=await s.patchIf(r,t,n),e=i.get(r);return o.doc&&e?{applied:o.applied,doc:f(o.doc,e,c)}:o},async patchWhere(r,t,n){if(h(r,t.where,"patchMany({ where })"),s.patchWhere===void 0)throw new A("INTERNAL",`ctx.db.${r}.patchMany({ where }) is unavailable: this writer has no where-based patch`);return s.patchWhere(r,t,n)},aggregate(r,t){return S(r,[t.field],"aggregate"),h(r,t.where,"aggregate"),s.aggregate(r,t)},count(r,t){const n=_(t),o=n&&("where"in n||"baseWhere"in n||"restrictsCounts"in n)?n.where:t;return h(r,o,"count"),n&&h(r,n.baseWhere,"count"),s.count(r,t)},async findFirst(r,t){$(r,t,"findFirst");const n=await s.findFirst(r,l(t)),o=i.get(r);return n&&o?f(n,o,c):n},async findFirstOrThrow(r,t){$(r,t,"findFirstOrThrow");const n=await s.findFirstOrThrow(r,l(t)),o=i.get(r);return o?f(n,o,c):n},async explain(r,t){return $(r,t,"explain"),s.explain(r,t)},async findMany(r,t){$(r,t,"findMany");const n=await s.findMany(r,l(t)),o=i.get(r);return o?F(n,o,c):n},async get(r,t){const{row:n,tableName:o}=await W(r,t),e=o===void 0?void 0:i.get(o);return!n||!e?n:f(n,e,c)},related:s.related?async(r,t)=>await s.related(r,l(t)):void 0,async lookupById(r,t){const n=await s.lookupById?.(r,t);if(!n)return null;const o=i.get(n.tableName);return{row:o?f(n.row,o,c):n.row,tableName:n.tableName}},groupBy(r,t){return S(r,[...t.by,t.agg?.field],"groupBy"),h(r,t.where,"groupBy"),s.groupBy(r,t)},query(r){const t=s.query(r),n=i.get(r);return n?k(t,n,r):t},async rank(r,t,n){return M(r,n,"rank"),p(r,t,"rank","rank"),s.rank(r,t,n)},async rankPage(r,t,n){M(r,n,"rankPage"),p(r,t,"rankPage","rank");const o=await s.rankPage(r,t,n),e=i.get(r);return e?F(o,e,c):o},...K("rankBefore",y,r=>(t,n,o)=>(M(t,o,"rankBefore"),p(t,n,"rankBefore","rank"),r(t,n,o))),...K("rankPageRows",g,r=>async(t,n,o)=>{M(t,o,"rankPageRows"),p(t,n,"rankPageRows","rank");const e=await r(t,n,o),a=i.get(t);return a?{...e,rows:e.rows.map(d=>({...d,doc:f(d.doc,a,c)}))}:e})},z=B;if(O.size>0)for(const[r,t]of Object.entries(s))H(t)&&(z[r]=Q(B,r));return B},nr=(s,i={})=>{const c=new Map(Object.entries(s)),w=G(i.roles),y=async({ctx:u,next:l})=>{const p={auth:await C(u.auth??{},w),ctx:u};if(i.bypass?.(p)===!0)return l();const k=Z(u.db,c,p,i.indexFields),W={db:k},{orm:S}=u;return S!==null&&typeof S=="object"&&(W.orm=V(k)),l({ctx:W})},g=new Map;for(const[u,l]of c)g.set(u,new Set(Object.keys(l)));return X(y,{columns:g})};export{nr as mask};
@@ -0,0 +1 @@
1
+ import{LunoraError as b,isLunoraError as le}from"@lunora/errors";import{findRelated as fe,whereFilter as de}from"@lunora/shard-engine";import{i as M}from"./wire-codec-CZ4obM6q.mjs";import{bindTableFacade as he,bindOrm as ue}from"./bindOrm-BHq_oUP2.mjs";import{t as ye}from"./policy-tag-V0lqFzgS.mjs";import{deny as pe}from"./allowAll-DkRAgItV.mjs";const K=4;class T extends Error{}const C=e=>e.includes("."),at=e=>{const t=e.indexOf(".");return t===-1?e:e.slice(0,t)},J=e=>{const t=e.split(".");if(t.length>K||t.includes(""))throw new T(`field path "${e}" must have 1 to ${String(K)} non-empty segments`);return t},we=(e,t)=>{if(!C(t))return e[t];let r=e;for(const s of J(t)){if(!M(r)||!Object.hasOwn(r,s))return;r=r[s]}return r},Z=(e,t,r,s)=>{const[a,...l]=t;if(a===void 0)throw new T(`field path "${s}" is empty`);if(e!=null&&!M(e))throw new T(`cannot set "${s}": "${a}" sits inside a value that is not an object`);const f=e??{};return{...f,[a]:l.length===0?r:Z(f[a],l,r,s)}},ge=(e,t)=>{const r=Object.keys(e).filter(a=>C(a));if(r.length===0)return e;for(const a of r){const l=r.find(f=>f!==a&&f.startsWith(`${a}.`));if(l!==void 0)throw new T(`patch sets both "${a}" and "${l}", which overlap; set one or the other`)}const s={};for(const[a,l]of Object.entries(e))C(a)||(s[a]=l);for(const a of r){const[l="",...f]=J(a);if(Object.hasOwn(e,l))throw new T(`patch sets both "${l}" and "${a}"; set one or the other`);s[l]=Z(Object.hasOwn(s,l)?s[l]:t[l],f,e[a],a)}return s},be=e=>{const t=typeof e;return t==="number"||t==="string"||t==="boolean"?t:void 0},ve=["every","is","isNot","none","some"],Oe=new Set(ve),We=e=>{if(e===null||typeof e!="object"||Array.isArray(e))return!1;const t=Object.keys(e);return t.length>0&&t.every(r=>Oe.has(r))},Q=(e,t,r)=>t?{[e]:r(t)}:{},x={decrement:{apply:(e,t)=>e-t,kind:"number"},divide:{apply:(e,t)=>e/t,kind:"number"},increment:{apply:(e,t)=>e+t,kind:"number"},multiply:{apply:(e,t)=>e*t,kind:"number"},toggle:{kind:"boolean"}};class R extends Error{}const V=e=>{if(!M(e))return;const t=Object.keys(e),[r]=t;if(!(t.length!==1||r===void 0||!Object.hasOwn(x,r)))return{operand:e[r],operator:r}},Re=e=>V(e)!==void 0,Ee=(e,t,r,s)=>{const a=x[t];if(a.apply===void 0){if(r!==!0)throw new R(`patch: use { toggle: true } on "${e}".`);if(typeof s!="boolean")throw new R(`patch: cannot toggle "${e}" — its current value is ${String(s)}; set a boolean first.`);return!s}if(typeof r!="number"||!Number.isFinite(r))throw new R(`patch: "${t}" on "${e}" needs a finite number, got ${String(r)}.`);if(typeof s!="number"||!Number.isFinite(s))throw new R(`patch: cannot ${t} "${e}" — its current value is ${String(s)}; set a number first.`);if(t==="divide"&&r===0)throw new R(`patch: cannot divide "${e}" by zero.`);const l=a.apply(s,r);if(!Number.isFinite(l))throw new R(`patch: "${t}" on "${e}" overflows to ${String(l)}.`);return l},ee=(e,t)=>{const r=new Set;for(const[s,a]of Object.entries(e))t(s)!==void 0&&Re(a)&&r.add(s);return r},Ae=(e,t,r)=>{let s;for(const a of ee(e,r)){const{operand:l,operator:f}=V(e[a]),v=r(a);if(x[f].kind!==v)throw new R(`patch: "${f}" does not apply to the ${String(v)} column "${a}".`);s??={...e},s[a]=Ee(a,f,l,t[a])}return s??e},ke=(e,t)=>{const r=a=>{const l=t[a];return typeof l=="number"||typeof l=="boolean"?typeof l:void 0},s={...e};for(const a of ee(e,r))try{Object.assign(s,Ae({[a]:e[a]},t,r))}catch(l){if(!(l instanceof R))throw l}try{return ge(s,t)}catch(a){if(a instanceof T)return s;throw a}},Se=["contains","eq","gt","gte","in","isNull","lt","lte","ne","notIn"],B=-1,P=0,E=1,$=e=>e?E:B,w=(e,t)=>e<t?e:t,me=(e,t)=>e>t?e:t,te=e=>e===P?P:$(e===B),z=e=>{const t=typeof e;return t==="number"||t==="string"||t==="bigint"},_=e=>e==null,D=(e,t,r)=>{if(r===void 0)throw new b("BAD_REQUEST",`\`${t}\` on "${e}" received undefined; a comparison needs a value`)},Be={gt:(e,t)=>e>t,gte:(e,t)=>e>=t,lt:(e,t)=>e<t,lte:(e,t)=>e<=t},Pe=(e,t,r)=>{let s=E;for(const a of["gt","gte","lt","lte"]){if(!(a in r))continue;const l=r[a];D(e,a,l);const f=C(e);if(f?be(l)===void 0:!z(l))s=w(s,B);else if(_(t))s=w(s,P);else{const v=Be[a],p=f?typeof t==typeof l:z(t);s=w(s,$(p&&v(t,l)))}}return s},X=(e,t,r)=>{if(!Array.isArray(r))throw new b("BAD_REQUEST",`\`${t}\` on "${e}" expects an array of values, received ${r===null?"null":typeof r}`);if(r.includes(void 0))throw new b("BAD_REQUEST",`\`${t}\` on "${e}" received undefined inside its list; a comparison needs a value`);return r},G=(e,t)=>t.length===0?B:_(e)?P:t.includes(e)?E:t.some(r=>_(r))?P:B,_e=(e,t,r)=>{let s=E;if("in"in r&&(s=w(s,G(t,X(e,"in",r.in)))),"notIn"in r&&(s=w(s,te(G(t,X(e,"notIn",r.notIn))))),"contains"in r){const a=r.contains;D(e,"contains",a),s=_(t)?w(s,P):w(s,$(typeof t=="string"&&typeof a=="string"&&t.includes(a)))}return"isNull"in r&&(s=w(s,$(r.isNull===!0===_(t)))),s},q=(e,t,r)=>t===null?$(r===_(e)):_(e)?P:$(r===(e===t)),Ie=(e,t,r)=>{let s=E;return"eq"in r&&(D(e,"eq",r.eq),s=w(s,q(t,r.eq,!0))),"ne"in r&&(D(e,"ne",r.ne),s=w(s,q(t,r.ne,!1))),s},Te=(e,t,r)=>w(Ie(e,t,r),w(_e(e,t,r),Pe(e,t,r))),$e=(e,t,r,s)=>{if(t==="NOT")return te(s(e,r??{}));if(!Array.isArray(r))return B;let a=t==="AND"?E:B;for(const l of r){const f=s(e,l);a=t==="AND"?w(a,f):me(a,f)}return a},ne=e=>e==="AND"||e==="OR"||e==="NOT",Me=e=>M(e)&&Object.keys(e).every(t=>Se.includes(t)),U=e=>Object.keys(e).some(t=>{const r=e[t];return ne(t)?t==="NOT"?U(r??{}):Array.isArray(r)&&r.some(s=>U(s??{})):We(r)}),re=(e,t)=>{let r=E;for(const s of Object.keys(t)){const a=t[s];if(ne(s)){r=w(r,$e(e,s,a,re));continue}const l=we(e,s);if(Me(a)){r=w(r,Te(s,l,a));continue}D(s,"eq",a),r=w(r,q(l,a,!0))}return r},j=(e,t)=>re(e,t)===E,oe=500,I=(e,t,r)=>{const s=t??oe;if(e>s)throw new b("BATCH_LIMIT_EXCEEDED",`${r}: batch of ${String(e)} exceeds the limit of ${String(s)} (raise options.limit or chunk the call)`,{status:400})},De=pe(),Fe=Symbol.for("lunora.ctxdb.rls-unwrap"),se=Symbol.for("lunora.rls.wrapped-chain"),Le=e=>e[se],Ce=e=>{const t=new Map;for(const r of e){const s=t.get(r.table)??[];s.push(r),t.set(r.table,s)}return t},Ue=(e,t)=>{const r=[];let s=!1;for(const a of e){if(a.on!=="read")continue;const l=a.when(t);if(l!==void 0){if(l===!0){s=!0;break}l!==!1&&r.push(l)}}if(!s)return r.length===0?De:r.length===1?r[0]:{OR:r}},je=(e,t,r)=>{const s=e.when({...t,row:r});if(s===void 0||s===!0)return!0;if(s===!1)return!1;if(U(s))throw new b("RELATION_PREDICATE_UNSUPPORTED","relation predicates are not supported in write policies; use a read policy or a flat column check");return j(r,s)},Ne=(e,t,r)=>{const s=e.when(t);if(s===void 0||s===!0)return r===void 0||je(e,t,r);if(s===!1)return!1;if(U(s))throw new b("RELATION_PREDICATE_UNSUPPORTED","relation predicates are not supported in write policies; use a read policy or a flat column check");return!t.row||!j(t.row,s)?!1:r===void 0||j(r,s)},qe=(e,t,r,s)=>{let a=!1;for(const l of e)if(l.on===t&&(a=!0,!Ne(l,r,s)))return!1;return a},Ye=new Set(["baseWhere","relationBaseWhere","restrictsCounts","where"]),xe=(e,t)=>t===void 0?!0:e==="restrictsCounts"?typeof t=="boolean":e==="relationBaseWhere"?typeof t=="function":M(t),He=e=>{const t=Object.keys(e);return t.length===0?!1:t.every(r=>Ye.has(r)&&xe(r,e[r]))},Ke=e=>e===void 0?{}:M(e)&&He(e)?e:{where:e},Y=e=>e!==void 0&&Object.keys(e).length>0,Qe=e=>{if(e.length!==0)return e.length===1?e[0]:{AND:e}},W=(e,t)=>Y(t)?!e||Object.keys(e).length===0?t:{AND:[t,e]}:e,ze=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return!1;const t=e;return typeof t.findMany=="function"&&typeof t.withSearchIndex=="function"},Xe=(e,t,r)=>{const[s]=r,a=r.length===1&&s!==void 0?s.perTable:new Set(r.flatMap(n=>[...n.perTable.keys()])),l=new Map,f=n=>{const o=l.get(n);if(o)return o;const i=[];let c=!1;for(const h of r){const u=h.perTable.get(n);if(!u||u.length===0||!u.some(L=>L.on==="read"))continue;c=!0;const y=Ue(u,h.context);y!==void 0&&i.push(y)}const d={baseWhere:Qe(i),restricts:c};return l.set(n,d),d},v=(n,o,i,c)=>{for(const d of r){const h=d.perTable.get(n);if(h&&!qe(h,o,{...d.context,row:i},c))return!1}return!0},p=n=>f(n).restricts?t:e,g=n=>f(n).baseWhere,A=async(n,o,i)=>{if(t.lookupById){const y=await t.lookupById(n,o);if(y)return{row:y.row,tableName:a.has(y.tableName)?y.tableName:void 0}}const c=await t.get(n,o);if(!c)return{row:null,tableName:void 0};const d=o??i,h=d===void 0?[...a.keys()]:[d].filter(y=>a.has(y)),u=await Promise.all(h.map(async y=>(await t.findFirst(y,{limit:1,where:{_id:n}}))?._id===n?y:void 0));return{row:c,tableName:u.find(y=>y!==void 0)}},N=async(n,o,i)=>{const c=await A(n,o,i);return c.row&&c.tableName!==void 0?{row:c.row,tableName:c.tableName}:void 0},O=async(n,o,i,c,d,h)=>{const u=await N(n,d,h);if(!u)return i(e);const y=c?c(u.row):void 0;if(!v(u.tableName,o,u.row,y))throw new b("FORBIDDEN",`${o} denied by policy`);return i(t,u.tableName)},k=(n,o,i,c)=>O(n,"update",(d,h)=>i(d,{verify:h===void 0?void 0:(u,y)=>v(h,"update",u,y)}),d=>({...d,...ke(o,d)}),c),S=(n,o)=>{const{baseWhere:i}=f(n);if(Y(i))throw new b("COUNT_RLS_UNSUPPORTED",`${o}() is not supported on "${n}" inside an RLS-restricted context`)},F=e.rankBefore,ae=e.rankPageRows,{relationEdges:H}=e,m={...e,async count(n,o){const{baseWhere:i}=f(n),c=Ke(o);return p(n).count(n,{...c,baseWhere:W(c.baseWhere,i),relationBaseWhere:g,restrictsCounts:(c.restrictsCounts??!1)||Y(i)})},delete:(n,o,i)=>O(n,"delete",c=>c.delete(n,o,i),void 0,o),async deleteAll(n,o){const i=Math.max(1,o?.chunkSize??oe),{baseWhere:c}=f(n);let d=0;for(;;){const u=(await p(n).findMany(n,{baseWhere:c,limit:i,relationBaseWhere:g})).page.map(y=>String(y._id));if(u.length===0)break;for(const y of u)await O(y,"delete",L=>L.delete(y,void 0,o?.hard===void 0?void 0:{hard:o.hard}),void 0,void 0,n),d+=1;if(u.length<i)break}return{deleted:d}},async deleteMany(n,o,i){I(n.length,o?.limit,"deleteMany");for(const c of n)await O(c,"delete",d=>d.delete(c,i),void 0,i);return{deleted:n.length}},async deleteWhere(n,o,i){const{baseWhere:c}=f(n),h=(await p(n).findMany(n,{baseWhere:W(o,c),relationBaseWhere:g})).page.map(u=>String(u._id));I(h.length,i?.limit,"deleteWhere");for(const u of h)await O(u,"delete",y=>y.delete(u),void 0,void 0,n);return{deleted:h.length}},async findFirst(n,o){const{baseWhere:i}=f(n);return p(n).findFirst(n,{...o,baseWhere:W(o?.baseWhere,i),relationBaseWhere:g})},async findFirstOrThrow(n,o){const{baseWhere:i}=f(n);return p(n).findFirstOrThrow(n,{...o,baseWhere:W(o?.baseWhere,i),relationBaseWhere:g})},async explain(n,o){const{baseWhere:i}=f(n);return p(n).explain(n,{...o,baseWhere:W(o?.baseWhere,i),relationBaseWhere:g})},async findMany(n,o){const{baseWhere:i}=f(n);return p(n).findMany(n,{...o,baseWhere:W(o?.baseWhere,i),relationBaseWhere:g})},async get(n,o){const i=await A(n,o);if(!i.row)return null;if(i.tableName===void 0)return e.get(n,o);const{baseWhere:c,restricts:d}=f(i.tableName);if(!d)return e.get(n,o);if(!c)return i.row;const h=await t.findFirst(i.tableName,{baseWhere:c,limit:1,where:{_id:n}});return h?._id===n?h:null},async lookupById(n,o){const i=await A(n,o);if(!i.row)return null;if(i.tableName===void 0||!f(i.tableName).restricts)return await e.lookupById?.(n,o)??null;const{baseWhere:c}=f(i.tableName);if(!c)return{row:i.row,tableName:i.tableName};const d=await t.findFirst(i.tableName,{baseWhere:c,limit:1,where:{_id:n}});return d?._id===n?{row:d,tableName:i.tableName}:null},async insert(n,o,i){if(a.has(n)){if(!v(n,"insert",o))throw new b("FORBIDDEN",`insert on "${n}" denied by policy`);return t.insert(n,o,i)}return e.insert(n,o,i)},async insertMany(n,o,i){if(I(o.length,i?.limit,"insertMany"),a.has(n)){for(const c of o)if(!v(n,"insert",c))throw new b("FORBIDDEN",`insert on "${n}" denied by policy`);return t.insertMany(n,o,i)}return e.insertMany(n,o,i)},async insertManyUnsafe(n,o,i){if(I(o.length,i?.limit,"insertManyUnsafe"),a.has(n)){for(const c of o)if(!v(n,"insert",c))throw new b("FORBIDDEN",`insert on "${n}" denied by policy`);return t.insertManyUnsafe(n,o,i)}return e.insertManyUnsafe(n,o,i)},patch:(n,o,i)=>k(n,o,(c,d)=>c.patch(n,o,i,d),i),assertPatchAllowed:(n,o)=>k(n,{},()=>Promise.resolve(),o),async patchIf(n,o,i){const c=await k(o,i.patch,async(h,u)=>{if(h.patchIf===void 0)throw new b("INTERNAL",`ctx.db.patchIf on "${n}" is unsupported: this writer has no conditional write`);return h.patchIf(n,o,{...i,verify:u.verify})},n);return c.doc===null||await m.get(o,n).then(h=>h!==null,h=>{if(le(h)&&h.code==="RLS_REQUIRED")return!1;throw h})?c:{applied:c.applied,doc:null}},async patchMany(n,o,i){I(n.length,o?.limit,"patchMany");for(const c of n)await k(c.id,c.patch,(d,h)=>d.patch(c.id,c.patch,i,h),i);return{patched:n.length}},async patchWhere(n,o,i){const{baseWhere:c}=f(n),h=(await p(n).findMany(n,{baseWhere:W(o.where,c),relationBaseWhere:g})).page.map(u=>({id:String(u._id),patch:o.patch}));return I(h.length,i?.limit,"patchWhere"),m.patchMany(h,i)},query(n){const{baseWhere:o}=f(n),i=p(n).query(n);return o?i.filter(de(o,c=>j(c,o))):i},related:H===void 0?void 0:async(n,o)=>fe({findMany:async(i,c)=>m.findMany(i,c),lookupById:async i=>t.lookupById?.(i)},H,n,{cursor:o?.cursor,depth:o?.depth,direction:o?.direction,edges:o?.edges,limit:o?.limit,relationMask:o?.relationMask}),restore:(n,o)=>O(n,"update",async i=>{const c=i.restore??t.restore;if(!c)throw new b("BAD_REQUEST","restore is not supported by this writer");await c(n,o)},void 0,o),replace:(n,o,i)=>O(n,"update",c=>c.replace(n,o,i),c=>({...o,_creationTime:o._creationTime??c._creationTime,_id:c._id}),i),aggregate(n,o){const{baseWhere:i}=f(n);return p(n).aggregate(n,{...o,baseWhere:W(o.baseWhere,i),relationBaseWhere:g})},groupBy(n,o){const{baseWhere:i}=f(n);return p(n).groupBy(n,{...o,baseWhere:W(o.baseWhere,i),relationBaseWhere:g})},rank(n,o,i){return S(n,"rank"),p(n).rank(n,o,i)},rankPage(n,o,i){return S(n,"rankPage"),p(n).rankPage(n,o,i)},wipeShard(){throw new b("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",F,n=>(o,i,c)=>(S(o,"rankBefore"),(p(o).rankBefore??n)(o,i,c))),...Q("rankPageRows",ae,n=>(o,i,c)=>(S(o,"rankPageRows"),(p(o).rankPageRows??n)(o,i,c)))},ce=m;if(a.size>0)for(const[n,o]of Object.entries(e))ze(o)&&(ce[n]=he(m,n));return Object.defineProperty(m,se,{configurable:!0,enumerable:!1,value:{base:e,raw:t,steps:r},writable:!1}),m},ie=e=>typeof e=="string"?e:e.name,Ge=e=>{const t=new Map;for(const r of e??[])t.set(r.name,new Set((r.permissions??[]).map(s=>ie(s))));return t},Je=(e,t)=>{const r=new Set;for(const s of e)for(const a of t.get(s)??[])r.add(a);return s=>r.has(ie(s))},Ze=["roles","role"],Ve=e=>{for(const t of Ze){const r=e?.[t];if(typeof r=="string"){const s=r.split(",").map(a=>a.trim()).filter(a=>a.length>0);if(s.length>0)return s}if(Array.isArray(r)){const s=r.filter(a=>typeof a=="string"&&a.length>0);if(s.length>0)return s}}return[]},et=async(e,t)=>{const r=await e.getIdentity?.()??null,s=[...new Set([...Ve(r),...e.roles??[]])];return{can:Je(s,t),identity:r,roles:s,userId:e.userId??null}},ct=(e,t={})=>{const r=e,s=Ce(r),a=Ge(t.roles);return ye(async({ctx:f,next:v})=>{const p={auth:await et(f.auth??{},a),ctx:f},g=f.db,A=Le(g),N=A?.base??g,O=A?.raw??g[Fe]??g,k=Xe(N,O,[...A?.steps??[],{context:p,perTable:s}]),S={db:k},{orm:F}=f;return F!==null&&typeof F=="object"&&(S.orm=ue(k)),v({ctx:S})},[{policies:r,roles:t.roles??[]}])};export{et as a,ze as b,at as c,We as d,Ve as e,Ue as f,Je as g,qe as h,Ge as i,j as m,Q as o,ct as r};
@@ -0,0 +1 @@
1
+ import{LunoraError as s}from"@lunora/errors";import{c as W}from"./compose-middleware-BK9FlblN.mjs";import{v as S}from"@lunora/values";const C=["de","en","es","fr","it","nl","none","pt"],K=["native","portable"],Y=e=>K.includes(e),Z=e=>C.includes(e),ee=e=>{const{value:t}=e._meta??{};if(t===null)return"null";switch(typeof t){case"bigint":case"boolean":case"number":case"string":return typeof t;default:return e.kind}},H=e=>{if(e.kind==="literal")return ee(e);if(e.kind!=="optional")return e.kind;const t=e._meta?.inner;return t?H(t):e.kind},te=e=>`table "${e}" is both .global() and .ttl(). The TTL sweep is a shard's alarm deleting from that shard's own SQLite, and a global (D1/Hyperdrive) table's rows live outside every shard — so expired rows would never be deleted. Drop .ttl() and expire the rows from a cron, or keep the table shard-local.`,ne=(e,t)=>`table "${e}" is .global() and declares vector index "${t}". Vector sync runs on the shard write path, which a global (D1/Hyperdrive) table's writes never take — the index would stay empty. Drop .global(), or keep the index yourself with ctx.vectors.upsert/deleteByIds.`,re=(e,t,n)=>e.some(r=>r.unique===!0&&r.fields.length===2&&r.fields.includes(t)&&r.fields.includes(n)),ae=e=>{const t=e?.kind==="id"?e._meta?.tableName:void 0;return typeof t=="string"?t:void 0},oe=(e,t,n,r)=>{const{from:a,table:c,to:d}=r.through,l=`defineSchema: relation "${n}" on table "${t}" (through "${c}")`,f=e[c];if(f===void 0)throw new s("INTERNAL",`${l} names a join table that is not declared`);if(e[r.table]===void 0)throw new s("INTERNAL",`${l} targets "${r.table}", which is not declared`);if(a===d)throw new s("INTERNAL",`${l}: "from" and "to" both name "${a}"; a link needs two different columns`);for(const[p,h]of[[a,t],[d,r.table]])if(ae(f.shape[p])!==h)throw new s("INTERNAL",`${l}: "${c}.${p}" must be a required v.id("${h}") column`);if(!re(f.indexes,a,d))throw new s("INTERNAL",`${l} needs a unique index over ("${a}", "${d}") on "${c}": ${JSON.stringify(`.index("by_${a}_${d}", ["${a}", "${d}"], { unique: true })`)}. Without it a repeated connect stores the same link twice.`)},U=e=>{for(const[t,n]of Object.entries(e))for(const[r,a]of Object.entries(n.relationMap))a.through!==void 0&&oe(e,t,r,a)},F=16;function ie(e,t){return"through"in t?{kind:"many",table:e,through:{...t.through}}:{field:t.field,kind:"many",references:t.references??"_id",table:e}}const se={many:ie,one:(e,t)=>({field:t.field,kind:"one",onDelete:t.onDelete,references:t.references??"_id",table:e})},x=(e,t,n)=>({handler:n,op:t,timing:e}),de=()=>({afterDelete:e=>x("after","delete",e),afterInsert:e=>x("after","insert",e),afterUpdate:e=>x("after","update",e),beforeDelete:e=>x("before","delete",e),beforeInsert:e=>x("before","insert",e),beforeUpdate:e=>x("before","update",e)}),Q=(e,t)=>{if(!t||t.length===0)throw new s("INTERNAL",`rankIndex "${e}": "sortBy" is required and must list at least one key`);return t.map(n=>({direction:n.direction??"asc",field:n.field}))},Te=e=>{const t={...e},n=[],r=[],a=[],c=[],d={},l=[],f={},p=de(),h=[];let m={kind:"root"},g=!1,A=!1,E=!1,M=!1,O=!1,j,T,I;const D=(i,o)=>{i in t||(t[i]=o)};let _,B;const q=i=>{if(m.kind!=="root"&&m.kind!==i.kind)throw new s("INTERNAL","shardBy/global: a table cannot be both .shardBy(key) and .global() — pick one. .shardBy(key) puts the rows in one Durable Object per key (isolation, poke-live reactivity); .global() puts them in a single replicated backend read from the edge.");m=i},u={aggregateIndex(i,o){const b=o?.op??"count";if(b!=="count"&&!o?.field)throw new s("INTERNAL",`aggregateIndex "${i}": op "${b}" requires a "field"`);return n.push({by:o?.by,field:o?.field,name:i,on:"",op:b,where:o?.where}),u},get aggregateIndexes(){return n},get externalSource(){return B},commitOrdered(){return g=!0,u},get commitOrderedMode(){return g},dropStalePatches(){return A=!0,u},get dropStalePatchesMode(){return A},externallyManaged(){return E=!0,u},geoIndex(i,o){return r.push({field:o.field,name:i,precision:o.precision}),u},get geoIndexes(){return r},global(i){return q({backend:i?.backend??"d1",kind:"global"}),u},get isExternallyManaged(){return E},get isPublic(){return O},index(i,o,b){return a.push({fields:o,name:i,unique:b?.unique??!1}),u},get indexes(){return a},memory(){return M=!0,u},get memoryMode(){return M},ownedBy(i){return j=i,u},get ownerField(){return j},public(){return O=!0,u},rankIndex(i,o){return c.push({name:i,on:"",partitionBy:o.partitionBy,sortBy:Q(i,o.sortBy),where:o.where}),u},get rankIndexes(){return c},get relationMap(){return d},relations(i){return Object.assign(d,i(se)),u},searchIndex(i,o){if(o.filterFields&&o.filterFields.length>F)throw new s("INTERNAL",`searchIndex "${i}": at most ${String(F)} filterFields are supported (got ${String(o.filterFields.length)})`);const{language:b}=o;if(b!==void 0&&!Z(b))throw new s("INTERNAL",`searchIndex "${i}": unknown language "${b}" (supported: ${C.join(", ")})`);const{strategy:w}=o;if(w!==void 0&&!Y(w))throw new s("INTERNAL",`searchIndex "${i}": unknown strategy "${w}" (supported: ${K.join(", ")})`);return l.push({field:o.field,filterFields:o.filterFields,language:o.language,name:i,staged:o.staged,strategy:o.strategy}),u},get searchIndexes(){return l},shape:t,shardBy(i){return q({field:i,kind:"shardBy"}),u},get shardMode(){return m},get softDeleteMode(){return T},source(i){if(!i.binding)throw new s("INTERNAL","source: `binding` is required (the wrangler Hyperdrive binding name)");if(!i.query)throw new s("INTERNAL","source: `query` is required (the tenant-membership SQL)");return B=i,E=!0,u},softDelete(i){const o=i?.field??"deletedAt";if(T={field:o},o===I)throw new s("INTERNAL",`defineTable: .softDelete() and .timestamps() both use "${o}"; give one of them another field`);return D(o,S.optional(S.number().nullable())),u},timestamps(i){const o=i?.field??"updatedAt";if(I!==void 0)throw new s("INTERNAL",`defineTable: .timestamps() was called twice ("${I}" and "${o}"); one table tracks one last-change column`);if(o===T?.field)throw new s("INTERNAL",`defineTable: .softDelete() and .timestamps() both use "${o}"; give one of them another field`);const b=t[o],w=b?._meta?.column;if(b!==void 0&&(b.kind!=="timestamp"||w?.onUpdateFn===void 0||w.defaultFn===void 0&&w.defaultValue===void 0))throw new s("INTERNAL",`defineTable: .timestamps() would add "${o}", but the table already declares it as something other than v.timestamp().defaultNow().$onUpdateFn(() => Date.now()); remove the column or declare it that way`);return I=o,D(o,S.timestamp().defaultNow().$onUpdateFn(()=>Date.now())),u},get triggerMap(){return f},triggers(i){return Object.assign(f,i(p)),u},ttl(i,o){return _={after:o?.after,field:i},u},get ttlPolicy(){return _},get vectorIndexes(){return h},vectorize(i,o){return h.push({dimensions:o.dimensions,embed:o.embed,field:i,metadata:o.metadata,metric:o.metric,model:o.model,name:o.index}),u}};return u},Se=e=>({dimensions:e.dimensions,embed:e.embed,kind:"vectorIndex",metadata:e.metadata,metric:e.metric,model:e.model,select:e.source.select,table:e.source.table}),Le=(e,t)=>{const n=t.op??"count";if(n!=="count"&&!t.field)throw new s("INTERNAL",`aggregateIndex "${e}": op "${n}" requires a "field"`);return{by:t.by,field:t.field,name:e,on:t.on,op:n,where:t.where}},Re=(e,t)=>({name:e,on:t.table,partitionBy:t.partitionBy,sortBy:Q(e,t.sortBy),where:t.where}),v=e=>({...e,extend(t){return v(J(e,t))},jurisdiction(t,n){return v(e)},rls(t){return v({...e,rlsMode:t})}}),le=e=>{for(const[t,n]of Object.entries(e))for(const r of[...n.aggregateIndexes,...n.rankIndexes])r.on===""&&(r.on=t)},ce=(e,t,n)=>{for(const r of Object.values(t)){const a=e[r.on];if(!a)throw new s("INTERNAL",`defineAggregateIndex "${r.name}": unknown table "${r.on}"`);a.aggregateIndexes.push(r)}for(const r of Object.values(n)){const a=e[r.on];if(!a)throw new s("INTERNAL",`defineRankIndex "${r.name}": unknown table "${r.on}"`);a.rankIndexes.push(r)}},ue=e=>{if(e.cursor)return"cursor";if(e.reconcileEveryMs!==void 0)return"reconcileEveryMs";if(e.softDeleteColumn!==void 0)return"softDeleteColumn"},he=(e,t)=>{const n=t.mode==="incremental";if(t.mode!==void 0&&t.mode!=="full-pull"&&!n)throw new s("INTERNAL",`defineSchema: table "${e}" uses \`mode: ${JSON.stringify(t.mode)}\` — supported modes are "full-pull" (default) and "incremental".`);if(!n){const r=ue(t);if(r)throw new s("INTERNAL",`defineSchema: table "${e}" sets \`${r}\` but is not \`mode: "incremental"\` — that knob only applies to incremental ingest. Set \`mode: "incremental"\` or remove \`${r}\`.`);return}if(!t.cursor?.column||!t.cursor.query)throw new s("INTERNAL",`defineSchema: table "${e}" is \`mode: "incremental"\` but has no \`cursor\` — add \`cursor: { column: "updated_at", query: "… WHERE … > $N" }\` binding the watermark as the trailing parameter.`);if(t.reconcileEveryMs===void 0&&t.softDeleteColumn===void 0)throw new s("INTERNAL",`defineSchema: table "${e}" is \`mode: "incremental"\` with no delete-visibility path — an incremental pull never sees upstream deletes, so it would accumulate phantom rows. Add \`reconcileEveryMs\` (a periodic full-pull sweep) or \`softDeleteColumn\` (an upstream tombstone column).`)},fe=e=>{for(const[t,n]of Object.entries(e)){const r=n.externalSource;if(r){if(n.shardMode.kind==="global")throw new s("INTERNAL",`defineSchema: table "${t}" cannot be both .source() and .global() — a sourced table materializes into a shard DO's SQLite, a global table lives in the external tier`);if(n.shardMode.kind==="shardBy"&&!r.tenantBy)throw new s("INTERNAL",`defineSchema: sourced + .shardBy() table "${t}" needs a \`tenantBy\` mapper — without it every tenant's DO would run the same unscoped query and replicate the whole multitenant table (a cross-tenant leak). Add \`tenantBy: (shardKey) => [shardKey]\` binding the shard key into the query's parameters.`);he(t,r)}}},me=["_commitSeq","_creationTime","_id"],P="_commitSeq",be=new Set(me),N=(e,t,n,r)=>{if(!(be.has(n)||n in r.shape))throw new s("INTERNAL",`defineSchema: table "${e}" index "${t}" names column "${n}" which is not in the table's shape`)},L=(e,t,n,r)=>{const a=new Set;for(const c of n){if(a.has(c.name))throw new s("INTERNAL",`defineSchema: table "${e}" declares ${t} "${c.name}" more than once`);a.add(c.name),r(c)}},z=e=>{for(const[t,n]of Object.entries(e))L(t,"index",n.indexes,r=>{for(const a of r.fields)N(t,r.name,a,n)}),L(t,"rank index",n.rankIndexes,r=>{for(const a of r.sortBy)N(t,r.name,a.field,n);for(const a of r.partitionBy??[])N(t,r.name,a,n)}),L(t,"geo index",n.geoIndexes,r=>{N(t,r.name,r.field,n)})},R=(e,t,n)=>{if(e.length===0)return;const r={};for(const a of e)r[t(a)]=n(a);return r},ge=e=>{const t=new Set(e.sortBy.map(n=>n.field));for(const n of e.partitionBy??[])t.add(n);return[...t]},Ae=e=>{const t={};for(const[n,r]of Object.entries(e.tables)){const a=R(r.geoIndexes,l=>l.name,l=>[l.field]),c=R(r.indexes,l=>l.name,l=>l.fields),d=R(r.rankIndexes,l=>l.name,ge);(a||c||d)&&(t[n]={...a?{geo:a}:{},...c?{index:c}:{},...d?{rank:d}:{}})}return t},we=e=>{for(const[t,n]of Object.entries(e)){if(!n.memoryMode)continue;const a=[[n.shardMode.kind==="global",".global() — those rows live in D1, which this shard does not own and cannot clear"],[n.commitOrderedMode===!0,".commitOrdered() — the counter resets with the table, so the sequence would restart and a consumer's cursor would silently skip everything after it"],[n.externalSource!==void 0,".source() — the table is materialized by the ingest loop, so wiping it on every eviction would fight the puller"],[n.searchIndexes.length>0,".searchIndex() — the FTS shadow is a separate table that clearing the rows would leave stale"],[n.geoIndexes.length>0,".geoIndex() — the geohash companion is a separate table that clearing the rows would leave stale"],[n.aggregateIndexes.length>0,".aggregateIndex() — the counter companion is a separate table that clearing the rows would leave stale"],[n.rankIndexes.length>0,".rankIndex() — the rank companion is a separate table that clearing the rows would leave stale"],[n.vectorIndexes.length>0,".vectorize() — vectors live in an external index that a shard restart cannot clear"]].find(([c])=>c)?.[1];if(a!==void 0)throw new s("INTERNAL",`defineSchema: table "${t}" is both .memory() and ${a}. Plain .index() is supported; SQLite maintains it through the DELETE.`)}},pe=e=>{for(const[t,n]of Object.entries(e))if(n.shardMode.kind==="global"){for(const[r,a]of Object.entries(n.shape))if(H(a)==="bigint")throw new s("INTERNAL",`defineSchema: table "${t}" is .global() and column "${r}" is v.bigint(). A global (D1/Hyperdrive) table stores a bigint as decimal TEXT, which SQL compares lexicographically — "100" sorts before "25" — so \`orderBy\`, range filters and \`aggregate\` on this column would silently return wrong results. Use v.number() if the value fits a double, or v.string() if you only need equality.`)}},xe=e=>{for(const[t,n]of Object.entries(e))if(n.dropStalePatchesMode===!0&&n.shardMode.kind==="global")throw new s("INTERNAL",`defineSchema: table "${t}" is both .global() and .dropStalePatches(). The stale check reads the caller's baseline out of the shard's \`__cdc_log\`, which a global (D1/Hyperdrive) table has no entries in — so every patch would read as "no baseline" and apply unchanged. Drop one of the two.`)},ye=e=>{for(const[t,n]of Object.entries(e))if(n.ttlPolicy!==void 0&&n.shardMode.kind==="global")throw new s("INTERNAL",`defineSchema: ${te(t)}`)},X=(e,t)=>{const n=[...Object.entries(e).flatMap(([r,a])=>a.vectorIndexes.map(c=>[r,c.name])),...Object.entries(t).map(([r,a])=>[a.table,r])];for(const[r,a]of n)if(e[r]?.shardMode.kind==="global")throw new s("INTERNAL",`defineSchema: ${ne(r,a)}`)},Ie=e=>{for(const[t,n]of Object.entries(e)){if(n.commitOrderedMode){if(n.shardMode.kind==="global")throw new s("INTERNAL",`defineSchema: table "${t}" is both .global() and .commitOrdered(). \`_commitSeq\` is allocated inside the shard's write transaction, which a global (D1/Hyperdrive) table does not share — so the stamp would carry no commit-ordering guarantee. Drop one of the two.`);continue}for(const r of n.indexes)if(r.fields.includes(P))throw new s("INTERNAL",`defineSchema: table "${t}" index "${r.name}" names "${P}", but the table is not .commitOrdered() — no row carries that field, so the index would never match. Add .commitOrdered(), or drop the column from the index.`)}},G=e=>{Ie(e),xe(e),pe(e),ye(e),we(e)},Me=(e,t={},n={},r={})=>(le(e),ce(e,n,r),fe(e),G(e),X(e,t),z(e),U(e),v({tables:e,vectorIndexes:t})),k=(e,t)=>`${e}_${t}`,y=(e,t,n)=>n.has(e)?k(t,e):e,V=(e,t)=>({...e,_meta:t}),$=(e,t)=>{const n=e._meta;if(n===void 0)return e;if(e.kind==="id"&&n.tableName!==void 0){const d=t(n.tableName);return d===n.tableName?e:V(e,{...n,tableName:d})}const r=d=>d===void 0?void 0:$(d,t),a={...n,...n.inner&&{inner:r(n.inner)},...n.keyValidator&&{keyValidator:r(n.keyValidator)},...n.valueValidator&&{valueValidator:r(n.valueValidator)},...n.members&&{members:n.members.map(d=>$(d,t))},...n.shape&&{shape:Object.fromEntries(Object.entries(n.shape).map(([d,l])=>[d,$(l,t)]))}};return a.inner===n.inner&&a.keyValidator===n.keyValidator&&a.valueValidator===n.valueValidator&&(a.members??[]).every((d,l)=>d===n.members?.[l])&&Object.entries(a.shape??{}).every(([d,l])=>l===n.shape?.[d])?e:V(e,a)},Ne=(e,t,n,r)=>{const a=k(t,r),c=h=>h===""?a:y(h,t,n),d={};for(const[h,m]of Object.entries(e.relationMap)){const g=y(m.table,t,n);d[h]=m.through===void 0?{...m,table:g}:{...m,table:g,through:{...m.through,table:y(m.through.table,t,n)}}}const l=e.aggregateIndexes.map(h=>({...h,on:c(h.on)})),f=e.rankIndexes.map(h=>({...h,on:c(h.on)})),p=Object.fromEntries(Object.entries(e.shape).map(([h,m])=>[h,$(m,g=>y(g,t,n))]));return{...e,aggregateIndexes:l,rankIndexes:f,relationMap:d,shape:p}},Oe=(e,t)=>{if(!e)throw new s("INTERNAL","defineSchemaExtension: `key` is required and must be a non-empty string");return{key:e,tables:t.tables,...t.vectorIndexes?{vectorIndexes:t.vectorIndexes}:{}}},ve=((e,t)=>{if(!e)throw new s("INTERNAL","definePlugin: `key` is required and must be a non-empty string");if(t.extension&&t.extension.key!==e)throw new s("INTERNAL",`definePlugin("${e}"): extension key "${t.extension.key}" does not match plugin key`);return{key:e,...t.extension?{extension:t.extension}:{},...t.middleware?{middleware:t.middleware}:{}}}),je=(e,t)=>({...ve(e,{...t.extension?{extension:t.extension}:{},...t.middleware?{middleware:t.middleware}:{}}),functions:t.functions??{}}),J=(e,t)=>{const{key:n}=t,r=new Set(Object.keys(t.tables)),a={...e.tables};for(const[d,l]of Object.entries(t.tables)){const f=k(n,d);if(Object.hasOwn(a,f))throw new s("INTERNAL",`defineSchema(...).extend("${n}"): table "${f}" already exists in the base schema — another extension with the same key already contributed it`);a[f]=Ne(l,n,r,d)}const c={...e.vectorIndexes};if(t.vectorIndexes)for(const[d,l]of Object.entries(t.vectorIndexes)){const f=k(n,d);if(Object.hasOwn(c,f))throw new s("INTERNAL",`defineSchema(...).extend("${n}"): vector index "${f}" already exists in the base schema — another extension with the same key already contributed it`);c[f]={...l,table:y(l.table,n,r)}}return z(a),G(a),X(a,c),U(a),{rlsMode:e.rlsMode,tables:a,vectorIndexes:c}},De=(e,t)=>{let n=e;for(const r of t)r.extension&&(n=J(n,r.extension));return n},_e=e=>{const t=e.map(n=>n.middleware).filter(n=>n!==void 0);return W(t)};export{je as a,ve as b,_e as c,Le as d,Re as e,Me as f,Oe as g,Te as h,Se as i,Ae as j,De as k,z as l,J as m,G as n,X as v};
@@ -0,0 +1 @@
1
+ import{f as i,h as m,i as l,b as p,m as d,e as h,g as n,a as c,r as u}from"./middleware-DbhB1jRk.mjs";import"./wire-codec-CZ4obM6q.mjs";import"./bindOrm-BHq_oUP2.mjs";import"./policy-tag-V0lqFzgS.mjs";import"./allowAll-DkRAgItV.mjs";export{i as computeReadBaseWhere,m as evaluateWrite,l as indexRolePermissions,p as isFacadeEntry,d as matchesWhere,h as readIdentityRoles,n as resolveCan,c as resolvePolicyAuth,u as rls};
@@ -1 +1 @@
1
- import{LunoraError as k}from"@lunora/errors";import{i as A,a as D}from"./middleware-DAVx_tP1.mjs";const E=(e,t,o)=>{const i=n=>o.isAllowed("list",n,t)&&o.isAllowed("read",n,t),{get:c,query:g}=e,f={...e},b=n=>n.filter(r=>typeof r.key=="string"&&i(r.key));return typeof c=="function"&&(f.get=async(n,r)=>(n==="_storage"&&o.assertAllowed("read",r,t),c(n,r))),typeof g=="function"&&(f.query=n=>{const r=g(n),{collect:p}=r;return n!=="_storage"||typeof p!="function"?r:{...r,collect:async()=>b(await p())}}),f},N=(e,t)=>{if(e===void 0)return!0;const o=e.endsWith("/")?e.slice(0,-1):e;return o===""||t===o||t.startsWith(`${o}/`)},S=e=>{const t=e[1],o=typeof t=="object"&&t!==null?t.method:void 0;return typeof o=="string"&&o.toUpperCase()==="PUT"?"write":"read"},M=[["createMultipartUpload","write"],["delete","delete"],["deleteAfterCommit","delete"],["download","read"],["generateUploadUrl","write"],["getMetadata","read"],["getSignedUrl",S],["getUrl","read"],["head","read"],["resumeMultipartUpload","write"],["store","write"],["upload","write"]],$=[["getPresignedUrl","ctx.storage.getPresignedUrl is not available under storageRules(...): a presigned URL reaches R2 directly, past every rule. Use getSignedUrl or generateUploadUrl, which route back through the Worker."],["list",'ctx.storage.list is not available under storageRules(...); enumerate via ctx.db.system.query("_storage"), which the rules filter.']],P=(e,t)=>{try{return e(t).bucketName===t}catch{return!1}},B=(e,t)=>{const o=e.bucketName??"default",{bucket:i}=e;for(const c of new Set(t))if(!(c===o||typeof i=="function"&&P(i,c)))throw new k("INTERNAL",`storageRules: rule for bucket "${c}" governs nothing — this request's storage cannot address that bucket (the accessor is "${o}", and selecting "${c}" 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 })\`.`)},_=(e,t={})=>{const o=A(t.roles);return async({ctx:i,next:c})=>{const g=await D(i.auth??{},o),f=(s,d,u)=>{const h=e.filter(a=>a.on===s&&a.bucket===u);if(h.length===0)return!0;const l={auth:g,ctx:i,key:d};return h.some(a=>N(a.prefix,d)&&a.when(l)===!0)},b=(s,d,u)=>{if(!f(s,d,u))throw new k("FORBIDDEN",`storage ${s} on "${d}" in bucket "${u}" denied by access rule`)},n=s=>{const d=s.bucketName??"default",u={bucketName:d};for(const[l,a]of M){const U=s[l];typeof U=="function"&&(u[l]=(...w)=>{const R=typeof w[0]=="string"?w[0]:"",v=typeof a=="function"?a(w):a;return b(v,R,d),U(...w)})}for(const[l,a]of $)typeof s[l]=="function"&&(u[l]=async()=>{throw new k("FORBIDDEN",a)});const{bucket:h}=s;return typeof h=="function"&&(u.bucket=l=>n(h(l))),u},r=i.storage;if(r===void 0)return c();B(r,e.map(s=>s.bucket));const p={storage:n(r)},y=i.db,m=y?.system;return y!==void 0&&m!==void 0&&typeof m=="object"&&(p.db={...y,system:E(m,r.bucketName??"default",{assertAllowed:b,isAllowed:f})}),c({ctx:p})}};export{_ as storageRules};
1
+ import{LunoraError as k}from"@lunora/errors";import{i as A,a as D}from"./middleware-DbhB1jRk.mjs";const E=(e,t,o)=>{const i=n=>o.isAllowed("list",n,t)&&o.isAllowed("read",n,t),{get:c,query:g}=e,f={...e},b=n=>n.filter(r=>typeof r.key=="string"&&i(r.key));return typeof c=="function"&&(f.get=async(n,r)=>(n==="_storage"&&o.assertAllowed("read",r,t),c(n,r))),typeof g=="function"&&(f.query=n=>{const r=g(n),{collect:p}=r;return n!=="_storage"||typeof p!="function"?r:{...r,collect:async()=>b(await p())}}),f},N=(e,t)=>{if(e===void 0)return!0;const o=e.endsWith("/")?e.slice(0,-1):e;return o===""||t===o||t.startsWith(`${o}/`)},S=e=>{const t=e[1],o=typeof t=="object"&&t!==null?t.method:void 0;return typeof o=="string"&&o.toUpperCase()==="PUT"?"write":"read"},M=[["createMultipartUpload","write"],["delete","delete"],["deleteAfterCommit","delete"],["download","read"],["generateUploadUrl","write"],["getMetadata","read"],["getSignedUrl",S],["getUrl","read"],["head","read"],["resumeMultipartUpload","write"],["store","write"],["upload","write"]],$=[["getPresignedUrl","ctx.storage.getPresignedUrl is not available under storageRules(...): a presigned URL reaches R2 directly, past every rule. Use getSignedUrl or generateUploadUrl, which route back through the Worker."],["list",'ctx.storage.list is not available under storageRules(...); enumerate via ctx.db.system.query("_storage"), which the rules filter.']],P=(e,t)=>{try{return e(t).bucketName===t}catch{return!1}},B=(e,t)=>{const o=e.bucketName??"default",{bucket:i}=e;for(const c of new Set(t))if(!(c===o||typeof i=="function"&&P(i,c)))throw new k("INTERNAL",`storageRules: rule for bucket "${c}" governs nothing — this request's storage cannot address that bucket (the accessor is "${o}", and selecting "${c}" 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 })\`.`)},_=(e,t={})=>{const o=A(t.roles);return async({ctx:i,next:c})=>{const g=await D(i.auth??{},o),f=(s,d,u)=>{const h=e.filter(a=>a.on===s&&a.bucket===u);if(h.length===0)return!0;const l={auth:g,ctx:i,key:d};return h.some(a=>N(a.prefix,d)&&a.when(l)===!0)},b=(s,d,u)=>{if(!f(s,d,u))throw new k("FORBIDDEN",`storage ${s} on "${d}" in bucket "${u}" denied by access rule`)},n=s=>{const d=s.bucketName??"default",u={bucketName:d};for(const[l,a]of M){const U=s[l];typeof U=="function"&&(u[l]=(...w)=>{const R=typeof w[0]=="string"?w[0]:"",v=typeof a=="function"?a(w):a;return b(v,R,d),U(...w)})}for(const[l,a]of $)typeof s[l]=="function"&&(u[l]=async()=>{throw new k("FORBIDDEN",a)});const{bucket:h}=s;return typeof h=="function"&&(u.bucket=l=>n(h(l))),u},r=i.storage;if(r===void 0)return c();B(r,e.map(s=>s.bucket));const p={storage:n(r)},y=i.db,m=y?.system;return y!==void 0&&m!==void 0&&typeof m=="object"&&(p.db={...y,system:E(m,r.bucketName??"default",{assertAllowed:b,isAllowed:f})}),c({ctx:p})}};export{_ as storageRules};
@@ -1 +1 @@
1
- import{i as y,d as P,f as W,e as v,m as I,g as R}from"../packem_shared/middleware-DAVx_tP1.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};
1
+ import{i as y,e as P,g as W,f as v,m as I,h as R}from"../packem_shared/middleware-DbhB1jRk.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
@@ -651,23 +651,51 @@ interface RankIndexDefinition {
651
651
  /** FK behavior when a referenced parent row is deleted (mirrors SQL `ON DELETE`). */
652
652
  type OnDeleteAction = "cascade" | "restrict" | "set null";
653
653
  /**
654
- * A declared relation between two tables, recorded by `.relations((r) => …)`.
654
+ * The join table behind a many-to-many relation, declared by
655
+ * `r.many(target, { through: { table, from, to } })`.
655
656
  *
656
- * - `one` (many-to-one): the FK column `field` lives on **this** table and
657
- * points at `table`.`references` (default `_id`). Loads a single doc.
658
- * - `many` (one-to-many): the FK column `field` lives on the **target** table
659
- * and points back at this table's `references` (default `_id`). Loads an array.
657
+ * - `table` — the join table, one row per linked pair.
658
+ * - `from` — the join table's `v.id` column pointing at the table that declares the relation.
659
+ * - `to` — the join table's `v.id` column pointing at the relation's target table.
660
+ */
661
+ interface RelationThrough {
662
+ from: string;
663
+ table: string;
664
+ to: string;
665
+ }
666
+ /**
667
+ * A relation backed by one foreign-key column: `one` (many-to-one) or `many` (one-to-many).
668
+ *
669
+ * - `one`: the FK column `field` lives on **this** table and points at
670
+ * `table`.`references` (default `_id`). Loads a single doc.
671
+ * - `many`: the FK column `field` lives on the **target** table and points back
672
+ * at this table's `references` (default `_id`). Loads an array.
660
673
  *
661
674
  * `onDelete` is meaningful only on `one`: it is the action applied to the
662
675
  * holder rows when the referenced parent row is deleted.
663
676
  */
664
- interface RelationDefinition {
677
+ interface KeyedRelationDefinition {
665
678
  field: string;
666
679
  kind: "many" | "one";
667
680
  onDelete?: OnDeleteAction;
668
681
  references: string;
669
682
  table: string;
683
+ through?: never;
684
+ }
685
+ /**
686
+ * A many-to-many relation: the link lives in the `through` join table, whose `from` column points at this
687
+ * table's `_id` and whose `to` column points at `table`'s `_id`. Loads an array of `table` rows.
688
+ *
689
+ * It has no `field`/`references`/`onDelete` of its own: the two foreign keys are the join table's, and a delete
690
+ * on either side cascades through the `onDelete` of the join table's own `r.one(...)` relations.
691
+ */
692
+ interface ThroughRelationDefinition {
693
+ kind: "many";
694
+ table: string;
695
+ through: RelationThrough;
670
696
  }
697
+ /** A declared relation between two tables, recorded by `.relations((r) => …)`: a single-key relation or a many-to-many one. */
698
+ type RelationDefinition = KeyedRelationDefinition | ThroughRelationDefinition;
671
699
  /** Distance metric used by a Vectorize index. */
672
700
  type VectorMetric = "cosine" | "dot-product" | "euclidean";
673
701
  /**
@@ -2809,4 +2837,4 @@ interface ActionCtx {
2809
2837
  /** Start / resume / inspect durable workflows; see {@link Workflows}. */
2810
2838
  readonly workflows: Workflows;
2811
2839
  }
2812
- export type { ActionCtx, AggregateIndexDefinition, AggregateOp, ArgsValidator, AuthState, CachePurge, DatabaseReader, DatabaseWriter, DurableObjectJurisdiction, DurableStreamOptions, ExposeConfig, ExternalSourceCursor, ExternalSourceDefinition, ExternalSourceMode, ExternalSourceRefresh, FunctionKind, FunctionVisibility, GeoBoundingBox, GeoFilterBuilder, GeoIndexDefinition, GeoPointInput, GlobalBackend, IndexDefinition, IndexRangeBuilder, InferArgs, LifecycleEvent, LifecycleEventKind, LogFields, LunoraLogMethod, LunoraLogger, LunoraMetrics, LunoraTracer, LunoraWideEvent, MutationCtx, MutationStorage, OnDeleteAction, PaginationOptions, PaginationResult, PatchIfResult, QueryCtx, RankIndexDefinition, RankSortKey, ReadOnlyStorage, RegisteredAction, RegisteredFunction, RegisteredLifecycleHook, RegisteredMutation, RegisteredQuery, RegisteredStream, RelatedDirection, RelatedNode, RelatedOptions, RelatedPage, RelatedStart, RelatedStartReference, RelationDefinition, RestCacheConfig, RetryPolicy, RunQueryOptions, ScheduledFunctionDoc, ScheduledJob, Scheduler, Schema, SearchFilterBuilder, SearchIndexDefinition, SearchLanguage, SearchStrategy, Secrets, SecretsStoreSecretLike, ShardInitEvent, ShardMode, SpanContextIds, SpanEvaluation, SpanHandle, SpanIdentity, SpanKind, SpanLink, SpanOptions, Storage, StorageListOptions, StorageListResult, StorageMetadata, StorageMultipartUpload, StorageMultipartUploadOptions, StorageObjectBody, StorageObjectHead, StorageRange, StorageUploadBody, StorageUploadOptions, StorageUploadResult, StorageUploadedPart, SystemDatabaseReader, SystemDoc, SystemQuery, SystemTableName, TableDefinition, TableReader, TableVectorIndex, TriggerAggregateOptions, TriggerBuilder, TriggerCtx, TriggerDatabase, TriggerDefinition, TriggerDeleteEvent, TriggerEvent, TriggerGroupByEntry, TriggerGroupByOptions, TriggerHandler, TriggerInsertEvent, TriggerOp, TriggerQueryArgs, TriggerQueryPage, TriggerRankOptions, TriggerRankPageOptions, TriggerRankResult, TriggerRow, TriggerTiming, TriggerUpdateEvent, TtlDefinition, VectorEmbedder, VectorIndexDefinition, VectorMatch, VectorMatches, VectorMetric, VectorQueryInput, VectorRecord, VectorSearch, VectorSearchReader, VectorUpsertInput, WhisperEvent, WorkflowCreateOptions, WorkflowEventDefinition, WorkflowHandle, WorkflowInstance, WorkflowInstanceEvent, WorkflowInstanceStatus, WorkflowStatusResult, Workflows, X402ProcedureConfig };
2840
+ export type { ActionCtx, AggregateIndexDefinition, AggregateOp, ArgsValidator, AuthState, CachePurge, DatabaseReader, DatabaseWriter, DurableObjectJurisdiction, DurableStreamOptions, ExposeConfig, ExternalSourceCursor, ExternalSourceDefinition, ExternalSourceMode, ExternalSourceRefresh, FunctionKind, FunctionVisibility, GeoBoundingBox, GeoFilterBuilder, GeoIndexDefinition, GeoPointInput, GlobalBackend, IndexDefinition, IndexRangeBuilder, InferArgs, KeyedRelationDefinition, LifecycleEvent, LifecycleEventKind, LogFields, LunoraLogMethod, LunoraLogger, LunoraMetrics, LunoraTracer, LunoraWideEvent, MutationCtx, MutationStorage, OnDeleteAction, PaginationOptions, PaginationResult, PatchIfResult, QueryCtx, RankIndexDefinition, RankSortKey, ReadOnlyStorage, RegisteredAction, RegisteredFunction, RegisteredLifecycleHook, RegisteredMutation, RegisteredQuery, RegisteredStream, RelatedDirection, RelatedNode, RelatedOptions, RelatedPage, RelatedStart, RelatedStartReference, RelationDefinition, RelationThrough, RestCacheConfig, RetryPolicy, RunQueryOptions, ScheduledFunctionDoc, ScheduledJob, Scheduler, Schema, SearchFilterBuilder, SearchIndexDefinition, SearchLanguage, SearchStrategy, Secrets, SecretsStoreSecretLike, ShardInitEvent, ShardMode, SpanContextIds, SpanEvaluation, SpanHandle, SpanIdentity, SpanKind, SpanLink, SpanOptions, Storage, StorageListOptions, StorageListResult, StorageMetadata, StorageMultipartUpload, StorageMultipartUploadOptions, StorageObjectBody, StorageObjectHead, StorageRange, StorageUploadBody, StorageUploadOptions, StorageUploadResult, StorageUploadedPart, SystemDatabaseReader, SystemDoc, SystemQuery, SystemTableName, TableDefinition, TableReader, TableVectorIndex, ThroughRelationDefinition, TriggerAggregateOptions, TriggerBuilder, TriggerCtx, TriggerDatabase, TriggerDefinition, TriggerDeleteEvent, TriggerEvent, TriggerGroupByEntry, TriggerGroupByOptions, TriggerHandler, TriggerInsertEvent, TriggerOp, TriggerQueryArgs, TriggerQueryPage, TriggerRankOptions, TriggerRankPageOptions, TriggerRankResult, TriggerRow, TriggerTiming, TriggerUpdateEvent, TtlDefinition, VectorEmbedder, VectorIndexDefinition, VectorMatch, VectorMatches, VectorMetric, VectorQueryInput, VectorRecord, VectorSearch, VectorSearchReader, VectorUpsertInput, WhisperEvent, WorkflowCreateOptions, WorkflowEventDefinition, WorkflowHandle, WorkflowInstance, WorkflowInstanceEvent, WorkflowInstanceStatus, WorkflowStatusResult, Workflows, X402ProcedureConfig };
package/dist/types.d.ts CHANGED
@@ -651,23 +651,51 @@ interface RankIndexDefinition {
651
651
  /** FK behavior when a referenced parent row is deleted (mirrors SQL `ON DELETE`). */
652
652
  type OnDeleteAction = "cascade" | "restrict" | "set null";
653
653
  /**
654
- * A declared relation between two tables, recorded by `.relations((r) => …)`.
654
+ * The join table behind a many-to-many relation, declared by
655
+ * `r.many(target, { through: { table, from, to } })`.
655
656
  *
656
- * - `one` (many-to-one): the FK column `field` lives on **this** table and
657
- * points at `table`.`references` (default `_id`). Loads a single doc.
658
- * - `many` (one-to-many): the FK column `field` lives on the **target** table
659
- * and points back at this table's `references` (default `_id`). Loads an array.
657
+ * - `table` — the join table, one row per linked pair.
658
+ * - `from` — the join table's `v.id` column pointing at the table that declares the relation.
659
+ * - `to` — the join table's `v.id` column pointing at the relation's target table.
660
+ */
661
+ interface RelationThrough {
662
+ from: string;
663
+ table: string;
664
+ to: string;
665
+ }
666
+ /**
667
+ * A relation backed by one foreign-key column: `one` (many-to-one) or `many` (one-to-many).
668
+ *
669
+ * - `one`: the FK column `field` lives on **this** table and points at
670
+ * `table`.`references` (default `_id`). Loads a single doc.
671
+ * - `many`: the FK column `field` lives on the **target** table and points back
672
+ * at this table's `references` (default `_id`). Loads an array.
660
673
  *
661
674
  * `onDelete` is meaningful only on `one`: it is the action applied to the
662
675
  * holder rows when the referenced parent row is deleted.
663
676
  */
664
- interface RelationDefinition {
677
+ interface KeyedRelationDefinition {
665
678
  field: string;
666
679
  kind: "many" | "one";
667
680
  onDelete?: OnDeleteAction;
668
681
  references: string;
669
682
  table: string;
683
+ through?: never;
684
+ }
685
+ /**
686
+ * A many-to-many relation: the link lives in the `through` join table, whose `from` column points at this
687
+ * table's `_id` and whose `to` column points at `table`'s `_id`. Loads an array of `table` rows.
688
+ *
689
+ * It has no `field`/`references`/`onDelete` of its own: the two foreign keys are the join table's, and a delete
690
+ * on either side cascades through the `onDelete` of the join table's own `r.one(...)` relations.
691
+ */
692
+ interface ThroughRelationDefinition {
693
+ kind: "many";
694
+ table: string;
695
+ through: RelationThrough;
670
696
  }
697
+ /** A declared relation between two tables, recorded by `.relations((r) => …)`: a single-key relation or a many-to-many one. */
698
+ type RelationDefinition = KeyedRelationDefinition | ThroughRelationDefinition;
671
699
  /** Distance metric used by a Vectorize index. */
672
700
  type VectorMetric = "cosine" | "dot-product" | "euclidean";
673
701
  /**
@@ -2809,4 +2837,4 @@ interface ActionCtx {
2809
2837
  /** Start / resume / inspect durable workflows; see {@link Workflows}. */
2810
2838
  readonly workflows: Workflows;
2811
2839
  }
2812
- export type { ActionCtx, AggregateIndexDefinition, AggregateOp, ArgsValidator, AuthState, CachePurge, DatabaseReader, DatabaseWriter, DurableObjectJurisdiction, DurableStreamOptions, ExposeConfig, ExternalSourceCursor, ExternalSourceDefinition, ExternalSourceMode, ExternalSourceRefresh, FunctionKind, FunctionVisibility, GeoBoundingBox, GeoFilterBuilder, GeoIndexDefinition, GeoPointInput, GlobalBackend, IndexDefinition, IndexRangeBuilder, InferArgs, LifecycleEvent, LifecycleEventKind, LogFields, LunoraLogMethod, LunoraLogger, LunoraMetrics, LunoraTracer, LunoraWideEvent, MutationCtx, MutationStorage, OnDeleteAction, PaginationOptions, PaginationResult, PatchIfResult, QueryCtx, RankIndexDefinition, RankSortKey, ReadOnlyStorage, RegisteredAction, RegisteredFunction, RegisteredLifecycleHook, RegisteredMutation, RegisteredQuery, RegisteredStream, RelatedDirection, RelatedNode, RelatedOptions, RelatedPage, RelatedStart, RelatedStartReference, RelationDefinition, RestCacheConfig, RetryPolicy, RunQueryOptions, ScheduledFunctionDoc, ScheduledJob, Scheduler, Schema, SearchFilterBuilder, SearchIndexDefinition, SearchLanguage, SearchStrategy, Secrets, SecretsStoreSecretLike, ShardInitEvent, ShardMode, SpanContextIds, SpanEvaluation, SpanHandle, SpanIdentity, SpanKind, SpanLink, SpanOptions, Storage, StorageListOptions, StorageListResult, StorageMetadata, StorageMultipartUpload, StorageMultipartUploadOptions, StorageObjectBody, StorageObjectHead, StorageRange, StorageUploadBody, StorageUploadOptions, StorageUploadResult, StorageUploadedPart, SystemDatabaseReader, SystemDoc, SystemQuery, SystemTableName, TableDefinition, TableReader, TableVectorIndex, TriggerAggregateOptions, TriggerBuilder, TriggerCtx, TriggerDatabase, TriggerDefinition, TriggerDeleteEvent, TriggerEvent, TriggerGroupByEntry, TriggerGroupByOptions, TriggerHandler, TriggerInsertEvent, TriggerOp, TriggerQueryArgs, TriggerQueryPage, TriggerRankOptions, TriggerRankPageOptions, TriggerRankResult, TriggerRow, TriggerTiming, TriggerUpdateEvent, TtlDefinition, VectorEmbedder, VectorIndexDefinition, VectorMatch, VectorMatches, VectorMetric, VectorQueryInput, VectorRecord, VectorSearch, VectorSearchReader, VectorUpsertInput, WhisperEvent, WorkflowCreateOptions, WorkflowEventDefinition, WorkflowHandle, WorkflowInstance, WorkflowInstanceEvent, WorkflowInstanceStatus, WorkflowStatusResult, Workflows, X402ProcedureConfig };
2840
+ export type { ActionCtx, AggregateIndexDefinition, AggregateOp, ArgsValidator, AuthState, CachePurge, DatabaseReader, DatabaseWriter, DurableObjectJurisdiction, DurableStreamOptions, ExposeConfig, ExternalSourceCursor, ExternalSourceDefinition, ExternalSourceMode, ExternalSourceRefresh, FunctionKind, FunctionVisibility, GeoBoundingBox, GeoFilterBuilder, GeoIndexDefinition, GeoPointInput, GlobalBackend, IndexDefinition, IndexRangeBuilder, InferArgs, KeyedRelationDefinition, LifecycleEvent, LifecycleEventKind, LogFields, LunoraLogMethod, LunoraLogger, LunoraMetrics, LunoraTracer, LunoraWideEvent, MutationCtx, MutationStorage, OnDeleteAction, PaginationOptions, PaginationResult, PatchIfResult, QueryCtx, RankIndexDefinition, RankSortKey, ReadOnlyStorage, RegisteredAction, RegisteredFunction, RegisteredLifecycleHook, RegisteredMutation, RegisteredQuery, RegisteredStream, RelatedDirection, RelatedNode, RelatedOptions, RelatedPage, RelatedStart, RelatedStartReference, RelationDefinition, RelationThrough, RestCacheConfig, RetryPolicy, RunQueryOptions, ScheduledFunctionDoc, ScheduledJob, Scheduler, Schema, SearchFilterBuilder, SearchIndexDefinition, SearchLanguage, SearchStrategy, Secrets, SecretsStoreSecretLike, ShardInitEvent, ShardMode, SpanContextIds, SpanEvaluation, SpanHandle, SpanIdentity, SpanKind, SpanLink, SpanOptions, Storage, StorageListOptions, StorageListResult, StorageMetadata, StorageMultipartUpload, StorageMultipartUploadOptions, StorageObjectBody, StorageObjectHead, StorageRange, StorageUploadBody, StorageUploadOptions, StorageUploadResult, StorageUploadedPart, SystemDatabaseReader, SystemDoc, SystemQuery, SystemTableName, TableDefinition, TableReader, TableVectorIndex, ThroughRelationDefinition, TriggerAggregateOptions, TriggerBuilder, TriggerCtx, TriggerDatabase, TriggerDefinition, TriggerDeleteEvent, TriggerEvent, TriggerGroupByEntry, TriggerGroupByOptions, TriggerHandler, TriggerInsertEvent, TriggerOp, TriggerQueryArgs, TriggerQueryPage, TriggerRankOptions, TriggerRankPageOptions, TriggerRankResult, TriggerRow, TriggerTiming, TriggerUpdateEvent, TtlDefinition, VectorEmbedder, VectorIndexDefinition, VectorMatch, VectorMatches, VectorMetric, VectorQueryInput, VectorRecord, VectorSearch, VectorSearchReader, VectorUpsertInput, WhisperEvent, WorkflowCreateOptions, WorkflowEventDefinition, WorkflowHandle, WorkflowInstance, WorkflowInstanceEvent, WorkflowInstanceStatus, WorkflowStatusResult, Workflows, X402ProcedureConfig };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/server",
3
- "version": "1.0.0-alpha.193",
3
+ "version": "1.0.0-alpha.195",
4
4
  "description": "Server primitives for Lunora: defineSchema, defineTable, query, mutation, and action",
5
5
  "keywords": [
6
6
  "backend",
@@ -71,9 +71,9 @@
71
71
  },
72
72
  "dependencies": {
73
73
  "@lunora/errors": ">=1.0.0-alpha.51 <2.0.0-0",
74
- "@lunora/scheduler": "1.0.0-alpha.119",
75
- "@lunora/shard-engine": "1.0.0-alpha.122",
76
- "@lunora/values": "1.0.0-alpha.63",
74
+ "@lunora/scheduler": "1.0.0-alpha.121",
75
+ "@lunora/shard-engine": "1.0.0-alpha.124",
76
+ "@lunora/values": "1.0.0-alpha.64",
77
77
  "drizzle-orm": "^0.45.3",
78
78
  "hono": "^4.13.13"
79
79
  },
@@ -1 +0,0 @@
1
- import{LunoraError as d}from"@lunora/errors";const a=e=>typeof e=="object"&&e!==null&&e.code==="CONFLICT"&&e.kind==="unique",p=(e,t,r)=>{const o=typeof t=="string"?[t]:t;if(o.length===0)throw new d("INTERNAL",`ctx.db.${e}.upsert: "target" must name at least one field`);const h={};for(const n of o){if(!(n in r))throw new d("INTERNAL",`ctx.db.${e}.upsert: target field "${n}" is missing from the create document`);h[n]=r[n]}return h},l=(e,t)=>{const r=async(n,s)=>{if(s?.skipDuplicates!==!0)return e.insert(t,n);try{return await e.insert(t,n)}catch(i){if(a(i))return null;throw i}},o=async n=>{const s=n??{},i=await e.findMany(t,{...s,limit:2});if(i.page.length>1)throw new d("NOT_UNIQUE",`ctx.db.${t}.findUnique matched more than one document; expected at most one`);return i.page[0]??null},h=async({create:n,target:s,update:i})=>{const c=p(t,s,n),u=await e.findFirst(t,{where:c});return u&&typeof u._id=="string"?(await e.patch(u._id,i??n,t),{created:!1,id:u._id}):{created:!0,id:await e.insert(t,n)}};return{aggregate:n=>e.aggregate(t,n),count:n=>e.count(t,n),delete:n=>e.delete(n,t),deleteMany:(n,s)=>{if(Array.isArray(n)){if(e.deleteMany===void 0)throw new d("INTERNAL",`ctx.db.${t}.deleteMany is unavailable: this writer has no batch delete`);return e.deleteMany(n,s,t)}if(e.deleteWhere===void 0)throw new d("INTERNAL",`ctx.db.${t}.deleteMany({ where }) is unavailable: this writer has no where-based delete`);const i=n;return e.deleteWhere(t,i.where,{limit:i.limit})},exists:async n=>await e.findFirst(t,n===void 0?void 0:{where:n})!==null,findFirst:n=>e.findFirst(t,n),findFirstOrThrow:n=>e.findFirstOrThrow(t,n),findMany:n=>e.findMany(t,n),findUnique:o,get:n=>e.get(n,t),groupBy:n=>e.groupBy(t,n),hardDelete:n=>e.delete(n,t,{hard:!0}),insert:r,insertMany:(n,s)=>{if(e.insertMany===void 0)throw new d("INTERNAL",`ctx.db.${t}.insertMany is unavailable: this writer has no batch insert`);return e.insertMany(t,n,s)},patch:(n,s)=>e.patch(n,s,t),patchMany:(n,s)=>{if(Array.isArray(n)){if(e.patchMany===void 0)throw new d("INTERNAL",`ctx.db.${t}.patchMany is unavailable: this writer has no batch patch`);return e.patchMany(n.map(c=>({id:c.id,patch:c.values})),s,t)}if(e.patchWhere===void 0)throw new d("INTERNAL",`ctx.db.${t}.patchMany({ where, values }) is unavailable: this writer has no where-based patch`);const i=n;return e.patchWhere(t,{patch:i.values,where:i.where},{limit:i.limit})},rank:(n,s)=>e.rank(t,n,s),rankPage:(n,s)=>e.rankPage(t,n,s),replace:(n,s)=>e.replace(n,s,t),restore:async n=>{if(!e.restore)throw new d("INTERNAL",`ctx.db.${t}.restore is unavailable: this writer has no restore (is the table .softDelete()?)`);await e.restore(n,t)},upsert:h,upsertMany:async({rows:n,target:s})=>{const i=[];for(const c of n)i.push(await h({create:c.create,target:s,update:c.update}));return i},withGeoIndex:(n,s)=>e.query(t).withGeoIndex(n,s),withSearchIndex:(n,s)=>e.query(t).withSearchIndex(n,s)}},g=e=>{const t=r=>{const o=e[r];if(!o)throw new d("INTERNAL",`unknown table: ${r}`);return o};return{delete:(r,o)=>t(r).delete(o),insert:r=>({values:o=>t(r).insert(o)}),query:e,replace:(r,o)=>({with:h=>t(r).replace(o,h)}),update:(r,o)=>({set:h=>t(r).patch(o,h)})}};export{g as bindOrm,l as bindTableFacade};
@@ -1 +0,0 @@
1
- import{LunoraError as A}from"@lunora/errors";import{f as U}from"./fnv1a-D3ueNTWB.mjs";import{i as q,a as z,o as _,b as G,c as C}from"./middleware-DAVx_tP1.mjs";import{bindTableFacade as H,bindOrm as J}from"./bindOrm-D_hFUjmr.mjs";import{tagMaskMiddleware as Q}from"./buildMaskRegistry-DpWMtalG.mjs";const V=(i,e,c)=>{try{return i==="redact"?null:i==="hash"?e==null?e:typeof e=="bigint"?U(e.toString()):U(typeof e=="string"?e:JSON.stringify(e)):i(e,c)}catch{return null}},w=(i,e,c)=>{const u={...i};for(const[y,g]of Object.entries(e))y in u&&(u[y]=V(g,i[y],{...c,column:y,row:i}));return u},j=(i,e,c)=>({...i,page:i.page.map(u=>w(u,e,c))}),D=(i,e,c,u)=>{if(typeof i!="function")return;const y=new Set,g=()=>new Proxy({},{get:()=>d=>(typeof d=="string"&&y.add(d),g())});i(g());for(const d of y)if(d in e)throw new A("MASK_UNSUPPORTED",`${u}() filtering "${c}" by masked column "${d}" is not supported`)},X=(i,e,c,u)=>{const y=i.rankBefore,g=i.rankPageRows,d=(r,n)=>{const t=e.get(r);return t?n.map(o=>w(o,t,c)):n},p=r=>{const n=r?.relationMask;return{...r,relationMask:n===void 0?d:(t,o)=>n(t,d(t,o))}},k=(r,n,t,o)=>{const s=e.get(r);if(!s)return;const f=u?.[r]?.[o]?.[n];if(!f)return;const a=f.find(E=>E in s);if(a!==void 0)throw new A("MASK_UNSUPPORTED",`${t}() reading "${r}" via index "${n}" would order rows by masked column "${a}" — 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 w(o,n,c)},collect:async()=>(await r.collect()).map(s=>w(s,n,c)),collectWithScores:async()=>(await r.collectWithScores()).map(s=>{const f=w(s.document,n,c);return"distanceMeters"in s?{distanceMeters:null,document:f}:{document:f,score:s.score}}),filter:o=>l(r.filter(s=>o(w(s,n,c))),n,t),first:async()=>{const o=await r.first();return o?w(o,n,c):null},order:o=>l(r.order(o),n,t),paginate:async o=>j(await r.paginate(o),n,c),take:async o=>(await r.take(o)).map(f=>w(f,n,c)),unique:async()=>{const o=await r.unique();return o?w(o,n,c):null},withIndex:(o,s)=>(k(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)=>(k(t,o,"withGeoIndex","geo"),l(r.withGeoIndex(o,s),n,t))}),I=async(r,n)=>{if(i.lookupById){const a=await i.lookupById(r,n);if(a)return{row:a.row,tableName:e.has(a.tableName)?a.tableName:void 0}}const t=await i.get(r,n);if(!t)return{row:null,tableName:void 0};const o=n!==void 0&&e.has(n)?[n]:[],s=n===void 0?[...e.keys()]:o,f=await Promise.all(s.map(async a=>(await i.findFirst(a,{limit:1,where:{_id:r}}))?._id===r?a:void 0));return{row:t,tableName:f.find(a=>a!==void 0)}},P=(r,n,t)=>{const o=e.get(r);if(!o)return;const s=n.find(f=>typeof f=="string"&&f in o);if(s!==void 0)throw new A("MASK_UNSUPPORTED",`${t}() over masked column "${s}" on "${r}" is not supported`)},S=new Set;for(const r of e.values())for(const n of Object.keys(r))S.add(n);const R=(r,n,t,o)=>{if(!(!r||typeof r!="object"||Array.isArray(r)))for(const[s,f]of Object.entries(r))K(s,f,n,t,o)},K=(r,n,t,o,s)=>{if(r==="AND"||r==="OR"){for(const f of Array.isArray(n)?n:[])R(f,t,o,s);return}if(r==="NOT"){R(n,t,o,s);return}if(!r.startsWith("__")){if(t.has(r))throw new A("MASK_UNSUPPORTED",`${s}() filtering "${o}" by masked column "${r}" is not supported`);if(C(n))for(const f of Object.values(n))R(f,S,`${o}.${r}`,s)}},B=r=>{const n=e.get(r);return n?new Set(Object.keys(n)):new Set},h=(r,n,t)=>{S.size===0||n===void 0||R(n,B(r),r,t)},v=(r,n,t,o)=>{if(Array.isArray(n)){for(const s of n)if(!(!s||typeof s!="object"||Array.isArray(s))){for(const f of Object.keys(s))if(t.has(f))throw new A("MASK_UNSUPPORTED",`${o}() ordering "${r}" by masked column "${f}" is not supported`)}}},$=(r,n,t)=>{if(!(S.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 f=s,a=`${r}.${o}`;R(f.where,S,a,t),v(a,f.orderBy,S,t),$(a,f.with,t)}},M=(r,n,t)=>{h(r,n?.where,t),h(r,n?.baseWhere,t),v(r,n?.orderBy,B(r),t),$(r,n?.with,t)},F=r=>r&&typeof r=="object"&&!Array.isArray(r)?r:void 0,O=(r,n,t)=>{const o=F(n);h(r,o?.where,t),h(r,o?.baseWhere,t),$(r,o?.with,t)},W={...i,async deleteWhere(r,n,t){if(h(r,n,"deleteMany({ where })"),i.deleteWhere===void 0)throw new A("INTERNAL",`ctx.db.${r}.deleteMany({ where }) is unavailable: this writer has no where-based delete`);return i.deleteWhere(r,n,t)},async patchIf(r,n,t){if(h(r,t.where,"patchIf"),i.patchIf===void 0)throw new A("INTERNAL",`ctx.db.patchIf on "${r}" is unsupported: this writer has no conditional write`);const o=await i.patchIf(r,n,t),s=e.get(r);return o.doc&&s?{applied:o.applied,doc:w(o.doc,s,c)}:o},async patchWhere(r,n,t){if(h(r,n.where,"patchMany({ where })"),i.patchWhere===void 0)throw new A("INTERNAL",`ctx.db.${r}.patchMany({ where }) is unavailable: this writer has no where-based patch`);return i.patchWhere(r,n,t)},aggregate(r,n){return P(r,[n.field],"aggregate"),h(r,n.where,"aggregate"),i.aggregate(r,n)},count(r,n){const t=F(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"),i.count(r,n)},async findFirst(r,n){M(r,n,"findFirst");const t=await i.findFirst(r,p(n)),o=e.get(r);return t&&o?w(t,o,c):t},async findFirstOrThrow(r,n){M(r,n,"findFirstOrThrow");const t=await i.findFirstOrThrow(r,p(n)),o=e.get(r);return o?w(t,o,c):t},async findMany(r,n){M(r,n,"findMany");const t=await i.findMany(r,p(n)),o=e.get(r);return o?j(t,o,c):t},async get(r,n){const{row:t,tableName:o}=await I(r,n),s=o===void 0?void 0:e.get(o);return!t||!s?t:w(t,s,c)},related:i.related?async(r,n)=>await i.related(r,p(n)):void 0,async lookupById(r,n){const t=await i.lookupById?.(r,n);if(!t)return null;const o=e.get(t.tableName);return{row:o?w(t.row,o,c):t.row,tableName:t.tableName}},groupBy(r,n){return P(r,[...n.by,n.agg?.field],"groupBy"),h(r,n.where,"groupBy"),i.groupBy(r,n)},query(r){const n=i.query(r),t=e.get(r);return t?l(n,t,r):n},async rank(r,n,t){return O(r,t,"rank"),k(r,n,"rank","rank"),i.rank(r,n,t)},async rankPage(r,n,t){O(r,t,"rankPage"),k(r,n,"rankPage","rank");const o=await i.rankPage(r,n,t),s=e.get(r);return s?j(o,s,c):o},..._("rankBefore",y,r=>(n,t,o)=>(O(n,o,"rankBefore"),k(n,t,"rankBefore","rank"),r(n,t,o))),..._("rankPageRows",g,r=>async(n,t,o)=>{O(n,o,"rankPageRows"),k(n,t,"rankPageRows","rank");const s=await r(n,t,o),f=e.get(n);return f?{...s,rows:s.rows.map(a=>({...a,doc:w(a.doc,f,c)}))}:s})},L=W;if(S.size>0)for(const[r,n]of Object.entries(i))G(n)&&(L[r]=H(W,r));return W},N=(i,e={})=>{const c=new Map(Object.entries(i)),u=q(e.roles),y=async({ctx:d,next:p})=>{const k={auth:await z(d.auth??{},u),ctx:d};if(e.bypass?.(k)===!0)return p();const l=X(d.db,c,k,e.indexFields),I={db:l},{orm:P}=d;return P!==null&&typeof P=="object"&&(I.orm=J(l)),p({ctx:I})},g=new Map;for(const[d,p]of c)g.set(d,new Set(Object.keys(p)));return Q(y,{columns:g})};export{N as mask};
@@ -1 +0,0 @@
1
- import{LunoraError as R,isLunoraError as V}from"@lunora/errors";import{findRelated as ee,whereFilter as te}from"@lunora/shard-engine";import{i as j}from"./wire-codec-CZ4obM6q.mjs";import{bindTableFacade as ne,bindOrm as re}from"./bindOrm-D_hFUjmr.mjs";import{t as se}from"./policy-tag-V0lqFzgS.mjs";import{deny as oe}from"./allowAll-DkRAgItV.mjs";const ie=["every","is","isNot","none","some"],ae=new Set(ie),ce=e=>{if(e===null||typeof e!="object"||Array.isArray(e))return!1;const n=Object.keys(e);return n.length>0&&n.every(s=>ae.has(s))},q=(e,n,s)=>n?{[e]:s(n)}:{},le=["contains","eq","gt","gte","in","isNull","lt","lte","ne","notIn"],B=-1,I=0,b=1,T=e=>e?b:B,p=(e,n)=>e<n?e:n,fe=(e,n)=>e>n?e:n,z=e=>e===I?I:T(e===B),Y=e=>{const n=typeof e;return n==="number"||n==="string"||n==="bigint"},S=e=>e==null,M=(e,n,s)=>{if(s===void 0)throw new R("BAD_REQUEST",`\`${n}\` on "${e}" received undefined; a comparison needs a value`)},de={gt:(e,n)=>e>n,gte:(e,n)=>e>=n,lt:(e,n)=>e<n,lte:(e,n)=>e<=n},ue=(e,n,s)=>{let i=b;for(const c of["gt","gte","lt","lte"]){if(!(c in s))continue;const y=s[c];if(M(e,c,y),!Y(y))i=p(i,B);else if(S(n))i=p(i,I);else{const d=de[c];i=p(i,T(Y(n)&&d(n,y)))}}return i},K=(e,n,s)=>{if(!Array.isArray(s))throw new R("BAD_REQUEST",`\`${n}\` on "${e}" expects an array of values, received ${s===null?"null":typeof s}`);if(s.includes(void 0))throw new R("BAD_REQUEST",`\`${n}\` on "${e}" received undefined inside its list; a comparison needs a value`);return s},Q=(e,n)=>n.length===0?B:S(e)?I:n.includes(e)?b:n.some(s=>S(s))?I:B,he=(e,n,s)=>{let i=b;if("in"in s&&(i=p(i,Q(n,K(e,"in",s.in)))),"notIn"in s&&(i=p(i,z(Q(n,K(e,"notIn",s.notIn))))),"contains"in s){const c=s.contains;M(e,"contains",c),i=S(n)?p(i,I):p(i,T(typeof n=="string"&&typeof c=="string"&&n.includes(c)))}return"isNull"in s&&(i=p(i,T(s.isNull===!0===S(n)))),i},F=(e,n,s)=>n===null?T(s===S(e)):S(e)?I:T(s===(e===n)),ye=(e,n,s)=>{let i=b;return"eq"in s&&(M(e,"eq",s.eq),i=p(i,F(n,s.eq,!0))),"ne"in s&&(M(e,"ne",s.ne),i=p(i,F(n,s.ne,!1))),i},we=(e,n,s)=>p(ye(e,n,s),p(he(e,n,s),ue(e,n,s))),pe=(e,n,s,i)=>{if(n==="NOT")return z(i(e,s??{}));if(!Array.isArray(s))return B;let c=n==="AND"?b:B;for(const y of s){const d=i(e,y);c=n==="AND"?p(c,d):fe(c,d)}return c},H=e=>e==="AND"||e==="OR"||e==="NOT",ge=e=>j(e)&&Object.keys(e).every(n=>le.includes(n)),L=e=>Object.keys(e).some(n=>{const s=e[n];return H(n)?n==="NOT"?L(s??{}):Array.isArray(s)&&s.some(i=>L(i??{})):ce(s)}),G=(e,n)=>{let s=b;for(const i of Object.keys(n)){const c=n[i];if(H(i)){s=p(s,pe(e,i,c,G));continue}const y=e[i];if(ge(c)){s=p(s,we(i,y,c));continue}M(i,"eq",c),s=p(s,F(y,c,!0))}return s},C=(e,n)=>G(e,n)===b,X=500,k=(e,n,s)=>{const i=n??X;if(e>i)throw new R("BATCH_LIMIT_EXCEEDED",`${s}: batch of ${String(e)} exceeds the limit of ${String(i)} (raise options.limit or chunk the call)`,{status:400})},Re=oe(),We=Symbol.for("lunora.ctxdb.rls-unwrap"),J=Symbol.for("lunora.rls.wrapped-chain"),Oe=e=>e[J],be=e=>{const n=new Map;for(const s of e){const i=n.get(s.table)??[];i.push(s),n.set(s.table,i)}return n},Ee=(e,n)=>{const s=[];let i=!1;for(const c of e){if(c.on!=="read")continue;const y=c.when(n);if(y!==void 0){if(y===!0){i=!0;break}y!==!1&&s.push(y)}}if(!i)return s.length===0?Re:s.length===1?s[0]:{OR:s}},ve=(e,n,s)=>{const i=e.when({...n,row:s});if(i===void 0||i===!0)return!0;if(i===!1)return!1;if(L(i))throw new R("RELATION_PREDICATE_UNSUPPORTED","relation predicates are not supported in write policies; use a read policy or a flat column check");return C(s,i)},Ae=(e,n,s)=>{const i=e.when(n);if(i===void 0||i===!0)return s===void 0||ve(e,n,s);if(i===!1)return!1;if(L(i))throw new R("RELATION_PREDICATE_UNSUPPORTED","relation predicates are not supported in write policies; use a read policy or a flat column check");return!n.row||!C(n.row,i)?!1:s===void 0||C(s,i)},Be=(e,n,s,i)=>{let c=!1;for(const y of e)if(y.on===n&&(c=!0,!Ae(y,s,i)))return!1;return c},Ie=new Set(["baseWhere","relationBaseWhere","restrictsCounts","where"]),Se=(e,n)=>n===void 0?!0:e==="restrictsCounts"?typeof n=="boolean":e==="relationBaseWhere"?typeof n=="function":j(n),_e=e=>{const n=Object.keys(e);return n.length===0?!1:n.every(s=>Ie.has(s)&&Se(s,e[s]))},ke=e=>e===void 0?{}:j(e)&&_e(e)?e:{where:e},$=e=>e!==void 0&&Object.keys(e).length>0,Te=e=>{if(e.length!==0)return e.length===1?e[0]:{AND:e}},O=(e,n)=>$(n)?!e||Object.keys(e).length===0?n:{AND:[n,e]}:e,Me=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return!1;const n=e;return typeof n.findMany=="function"&&typeof n.withSearchIndex=="function"},De=(e,n,s)=>{const[i]=s,c=s.length===1&&i!==void 0?i.perTable:new Set(s.flatMap(t=>[...t.perTable.keys()])),y=new Map,d=t=>{const r=y.get(t);if(r)return r;const o=[];let a=!1;for(const l of s){const h=l.perTable.get(t);if(!h||h.length===0||!h.some(m=>m.on==="read"))continue;a=!0;const u=Ee(h,l.context);u!==void 0&&o.push(u)}const f={baseWhere:Te(o),restricts:a};return y.set(t,f),f},_=(t,r,o,a)=>{for(const f of s){const l=f.perTable.get(t);if(l&&!Be(l,r,{...f.context,row:o},a))return!1}return!0},w=t=>d(t).restricts?n:e,g=t=>d(t).baseWhere,E=async(t,r,o)=>{if(n.lookupById){const u=await n.lookupById(t,r);if(u)return{row:u.row,tableName:c.has(u.tableName)?u.tableName:void 0}}const a=await n.get(t,r);if(!a)return{row:null,tableName:void 0};const f=r??o,l=f===void 0?[...c.keys()]:[f].filter(u=>c.has(u)),h=await Promise.all(l.map(async u=>(await n.findFirst(u,{limit:1,where:{_id:t}}))?._id===t?u:void 0));return{row:a,tableName:h.find(u=>u!==void 0)}},U=async(t,r,o)=>{const a=await E(t,r,o);return a.row&&a.tableName!==void 0?{row:a.row,tableName:a.tableName}:void 0},W=async(t,r,o,a,f,l)=>{const h=await U(t,f,l);if(!h)return o(e);const u=a?a(h.row):void 0;if(!_(h.tableName,r,h.row,u))throw new R("FORBIDDEN",`${r} denied by policy`);return o(n)},v=(t,r)=>{const{baseWhere:o}=d(t);if($(o))throw new R("COUNT_RLS_UNSUPPORTED",`${r}() is not supported on "${t}" inside an RLS-restricted context`)},D=e.rankBefore,P=e.rankPageRows,{relationEdges:N}=e,A={...e,async count(t,r){const{baseWhere:o}=d(t),a=ke(r);return w(t).count(t,{...a,baseWhere:O(a.baseWhere,o),relationBaseWhere:g,restrictsCounts:(a.restrictsCounts??!1)||$(o)})},delete:(t,r,o)=>W(t,"delete",a=>a.delete(t,r,o),void 0,r),async deleteAll(t,r){const o=Math.max(1,r?.chunkSize??X),{baseWhere:a}=d(t);let f=0;for(;;){const h=(await w(t).findMany(t,{baseWhere:a,limit:o,relationBaseWhere:g})).page.map(u=>String(u._id));if(h.length===0)break;for(const u of h)await W(u,"delete",m=>m.delete(u,void 0,r?.hard===void 0?void 0:{hard:r.hard}),void 0,void 0,t),f+=1;if(h.length<o)break}return{deleted:f}},async deleteMany(t,r,o){k(t.length,r?.limit,"deleteMany");for(const a of t)await W(a,"delete",f=>f.delete(a,o),void 0,o);return{deleted:t.length}},async deleteWhere(t,r,o){const{baseWhere:a}=d(t),l=(await w(t).findMany(t,{baseWhere:O(r,a),relationBaseWhere:g})).page.map(h=>String(h._id));k(l.length,o?.limit,"deleteWhere");for(const h of l)await W(h,"delete",u=>u.delete(h),void 0,void 0,t);return{deleted:l.length}},async findFirst(t,r){const{baseWhere:o}=d(t);return w(t).findFirst(t,{...r,baseWhere:O(r?.baseWhere,o),relationBaseWhere:g})},async findFirstOrThrow(t,r){const{baseWhere:o}=d(t);return w(t).findFirstOrThrow(t,{...r,baseWhere:O(r?.baseWhere,o),relationBaseWhere:g})},async findMany(t,r){const{baseWhere:o}=d(t);return w(t).findMany(t,{...r,baseWhere:O(r?.baseWhere,o),relationBaseWhere:g})},async get(t,r){const o=await E(t,r);if(!o.row)return null;if(o.tableName===void 0)return e.get(t,r);const{baseWhere:a,restricts:f}=d(o.tableName);if(!f)return e.get(t,r);if(!a)return o.row;const l=await n.findFirst(o.tableName,{baseWhere:a,limit:1,where:{_id:t}});return l?._id===t?l:null},async lookupById(t,r){const o=await E(t,r);if(!o.row)return null;if(o.tableName===void 0||!d(o.tableName).restricts)return await e.lookupById?.(t,r)??null;const{baseWhere:a}=d(o.tableName);if(!a)return{row:o.row,tableName:o.tableName};const f=await n.findFirst(o.tableName,{baseWhere:a,limit:1,where:{_id:t}});return f?._id===t?{row:f,tableName:o.tableName}:null},async insert(t,r,o){if(c.has(t)){if(!_(t,"insert",r))throw new R("FORBIDDEN",`insert on "${t}" denied by policy`);return n.insert(t,r,o)}return e.insert(t,r,o)},async insertMany(t,r,o){if(k(r.length,o?.limit,"insertMany"),c.has(t)){for(const a of r)if(!_(t,"insert",a))throw new R("FORBIDDEN",`insert on "${t}" denied by policy`);return n.insertMany(t,r,o)}return e.insertMany(t,r,o)},async insertManyUnsafe(t,r,o){if(k(r.length,o?.limit,"insertManyUnsafe"),c.has(t)){for(const a of r)if(!_(t,"insert",a))throw new R("FORBIDDEN",`insert on "${t}" denied by policy`);return n.insertManyUnsafe(t,r,o)}return e.insertManyUnsafe(t,r,o)},patch:(t,r,o)=>W(t,"update",a=>a.patch(t,r,o),a=>({...a,...r}),o),async patchIf(t,r,o){const a=await W(r,"update",async l=>{if(l.patchIf===void 0)throw new R("INTERNAL",`ctx.db.patchIf on "${t}" is unsupported: this writer has no conditional write`);return l.patchIf(t,r,o)},l=>({...l,...o.patch}),t);return a.doc===null||await A.get(r,t).then(l=>l!==null,l=>{if(V(l)&&l.code==="RLS_REQUIRED")return!1;throw l})?a:{applied:a.applied,doc:null}},async patchMany(t,r,o){k(t.length,r?.limit,"patchMany");for(const a of t)await W(a.id,"update",f=>f.patch(a.id,a.patch,o),f=>({...f,...a.patch}),o);return{patched:t.length}},async patchWhere(t,r,o){const{baseWhere:a}=d(t),l=(await w(t).findMany(t,{baseWhere:O(r.where,a),relationBaseWhere:g})).page.map(h=>({id:String(h._id),patch:r.patch}));return k(l.length,o?.limit,"patchWhere"),A.patchMany(l,o)},query(t){const{baseWhere:r}=d(t),o=w(t).query(t);return r?o.filter(te(r,a=>C(a,r))):o},related:N===void 0?void 0:async(t,r)=>ee({findMany:async(o,a)=>A.findMany(o,a),lookupById:async o=>n.lookupById?.(o)},N,t,{cursor:r?.cursor,depth:r?.depth,direction:r?.direction,edges:r?.edges,limit:r?.limit,relationMask:r?.relationMask}),restore:(t,r)=>W(t,"update",async o=>{const a=o.restore??n.restore;if(!a)throw new R("BAD_REQUEST","restore is not supported by this writer");await a(t,r)},void 0,r),replace:(t,r,o)=>W(t,"update",a=>a.replace(t,r,o),a=>({...r,_creationTime:r._creationTime??a._creationTime,_id:a._id}),o),aggregate(t,r){const{baseWhere:o}=d(t);return w(t).aggregate(t,{...r,baseWhere:O(r.baseWhere,o),relationBaseWhere:g})},groupBy(t,r){const{baseWhere:o}=d(t);return w(t).groupBy(t,{...r,baseWhere:O(r.baseWhere,o),relationBaseWhere:g})},rank(t,r,o){return v(t,"rank"),w(t).rank(t,r,o)},rankPage(t,r,o){return v(t,"rankPage"),w(t).rankPage(t,r,o)},wipeShard(){throw new R("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=>(r,o,a)=>(v(r,"rankBefore"),(w(r).rankBefore??t)(r,o,a))),...q("rankPageRows",P,t=>(r,o,a)=>(v(r,"rankPageRows"),(w(r).rankPageRows??t)(r,o,a)))},x=A;if(c.size>0)for(const[t,r]of Object.entries(e))Me(r)&&(x[t]=ne(A,t));return Object.defineProperty(A,J,{configurable:!0,enumerable:!1,value:{base:e,raw:n,steps:s},writable:!1}),A},Z=e=>typeof e=="string"?e:e.name,Pe=e=>{const n=new Map;for(const s of e??[])n.set(s.name,new Set((s.permissions??[]).map(i=>Z(i))));return n},me=(e,n)=>{const s=new Set;for(const i of e)for(const c of n.get(i)??[])s.add(c);return i=>s.has(Z(i))},Le=["roles","role"],Ce=e=>{for(const n of Le){const s=e?.[n];if(typeof s=="string"){const i=s.split(",").map(c=>c.trim()).filter(c=>c.length>0);if(i.length>0)return i}if(Array.isArray(s)){const i=s.filter(c=>typeof c=="string"&&c.length>0);if(i.length>0)return i}}return[]},Ue=async(e,n)=>{const s=await e.getIdentity?.()??null,i=[...new Set([...Ce(s),...e.roles??[]])];return{can:me(i,n),identity:s,roles:i,userId:e.userId??null}},Ke=(e,n={})=>{const s=e,i=be(s),c=Pe(n.roles);return se(async({ctx:d,next:_})=>{const w={auth:await Ue(d.auth??{},c),ctx:d},g=d.db,E=Oe(g),U=E?.base??g,W=E?.raw??g[We]??g,v=De(U,W,[...E?.steps??[],{context:w,perTable:i}]),D={db:v},{orm:P}=d;return P!==null&&typeof P=="object"&&(D.orm=re(v)),_({ctx:D})},[{policies:s,roles:n.roles??[]}])};export{Ue as a,Me as b,ce as c,Ce as d,Ee as e,me as f,Be as g,Pe as i,C as m,q as o,Ke as r};
@@ -1 +0,0 @@
1
- import{LunoraError as i}from"@lunora/errors";import{c as V}from"./compose-middleware-BK9FlblN.mjs";import{v as B}from"@lunora/values";const q=["de","en","es","fr","it","nl","none","pt"],F=["native","portable"],X=e=>F.includes(e),G=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},Y=e=>`table "${e}" is both .global() and .ttl(). The TTL sweep is a shard's alarm deleting from that shard's own SQLite, and a global (D1/Hyperdrive) table's rows live outside every shard — so expired rows would never be deleted. Drop .ttl() and expire the rows from a cron, or keep the table shard-local.`,J=(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,W={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}),Z=()=>({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 i("INTERNAL",`rankIndex "${e}": "sortBy" is required and must list at least one key`);return t.map(n=>({direction:n.direction??"asc",field:n.field}))},xe=e=>{const t={...e},n=[],r=[],a=[],d=[],u={},c=[],h={},f=Z(),b=[];let w={kind:"root"},E=!1,$=!1,p=!1,T=!1,M=!1,L,A,O,R;const D=s=>{if(w.kind!=="root"&&w.kind!==s.kind)throw new i("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=s},l={aggregateIndex(s,o){const m=o?.op??"count";if(m!=="count"&&!o?.field)throw new i("INTERNAL",`aggregateIndex "${s}": op "${m}" requires a "field"`);return n.push({by:o?.by,field:o?.field,name:s,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(s,o){return r.push({field:o.field,name:s,precision:o.precision}),l},get geoIndexes(){return r},global(s){return D({backend:s?.backend??"d1",kind:"global"}),l},get isExternallyManaged(){return p},get isPublic(){return M},index(s,o,m){return a.push({fields:o,name:s,unique:m?.unique??!1}),l},get indexes(){return a},memory(){return T=!0,l},get memoryMode(){return T},ownedBy(s){return L=s,l},get ownerField(){return L},public(){return M=!0,l},rankIndex(s,o){return d.push({name:s,on:"",partitionBy:o.partitionBy,sortBy:C(s,o.sortBy),where:o.where}),l},get rankIndexes(){return d},get relationMap(){return u},relations(s){return Object.assign(u,s(W)),l},searchIndex(s,o){if(o.filterFields&&o.filterFields.length>j)throw new i("INTERNAL",`searchIndex "${s}": at most ${String(j)} filterFields are supported (got ${String(o.filterFields.length)})`);const{language:m}=o;if(m!==void 0&&!G(m))throw new i("INTERNAL",`searchIndex "${s}": unknown language "${m}" (supported: ${q.join(", ")})`);const{strategy:N}=o;if(N!==void 0&&!X(N))throw new i("INTERNAL",`searchIndex "${s}": unknown strategy "${N}" (supported: ${F.join(", ")})`);return c.push({field:o.field,filterFields:o.filterFields,language:o.language,name:s,staged:o.staged,strategy:o.strategy}),l},get searchIndexes(){return c},shape:t,shardBy(s){return D({field:s,kind:"shardBy"}),l},get shardMode(){return w},get softDeleteMode(){return A},source(s){if(!s.binding)throw new i("INTERNAL","source: `binding` is required (the wrangler Hyperdrive binding name)");if(!s.query)throw new i("INTERNAL","source: `query` is required (the tenant-membership SQL)");return R=s,p=!0,l},softDelete(s){const o=s?.field??"deletedAt";return A={field:o},o in t||(t[o]=B.optional(B.number().nullable())),l},get triggerMap(){return h},triggers(s){return Object.assign(h,s(f)),l},ttl(s,o){return O={after:o?.after,field:s},l},get ttlPolicy(){return O},get vectorIndexes(){return b},vectorize(s,o){return b.push({dimensions:o.dimensions,embed:o.embed,field:s,metadata:o.metadata,metric:o.metric,model:o.model,name:o.index}),l}};return l},ye=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}),Ie=(e,t)=>{const n=t.op??"count";if(n!=="count"&&!t.field)throw new i("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}},pe=(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,n){return y(e)},rls(t){return y({...e,rlsMode:t})}}),ee=e=>{for(const[t,n]of Object.entries(e))for(const r of[...n.aggregateIndexes,...n.rankIndexes])r.on===""&&(r.on=t)},te=(e,t,n)=>{for(const r of Object.values(t)){const a=e[r.on];if(!a)throw new i("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 i("INTERNAL",`defineRankIndex "${r.name}": unknown table "${r.on}"`);a.rankIndexes.push(r)}},ne=e=>{if(e.cursor)return"cursor";if(e.reconcileEveryMs!==void 0)return"reconcileEveryMs";if(e.softDeleteColumn!==void 0)return"softDeleteColumn"},re=(e,t)=>{const n=t.mode==="incremental";if(t.mode!==void 0&&t.mode!=="full-pull"&&!n)throw new i("INTERNAL",`defineSchema: table "${e}" uses \`mode: ${JSON.stringify(t.mode)}\` — supported modes are "full-pull" (default) and "incremental".`);if(!n){const r=ne(t);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(!t.cursor?.column||!t.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(t.reconcileEveryMs===void 0&&t.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).`)},ae=e=>{for(const[t,n]of Object.entries(e)){const r=n.externalSource;if(r){if(n.shardMode.kind==="global")throw new i("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 i("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.`);re(t,r)}}},oe=["_commitSeq","_creationTime","_id"],_="_commitSeq",se=new Set(oe),x=(e,t,n,r)=>{if(!(se.has(n)||n in r.shape))throw new i("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 i("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},ie=e=>{const t=new Set(e.sortBy.map(n=>n.field));for(const n of e.partitionBy??[])t.add(n);return[...t]},Ne=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,ie);(a||d||u)&&(t[n]={...a?{geo:a}:{},...d?{index:d}:{},...u?{rank:u}:{}})}return t},de=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 i("INTERNAL",`defineSchema: table "${t}" is both .memory() and ${a}. Plain .index() is supported; SQLite maintains it through the DELETE.`)}},le=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 i("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.`)}},ce=e=>{for(const[t,n]of Object.entries(e))if(n.dropStalePatchesMode===!0&&n.shardMode.kind==="global")throw new i("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.`)},ue=e=>{for(const[t,n]of Object.entries(e))if(n.ttlPolicy!==void 0&&n.shardMode.kind==="global")throw new i("INTERNAL",`defineSchema: ${Y(t)}`)},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 i("INTERNAL",`defineSchema: ${J(r,a)}`)},he=e=>{for(const[t,n]of Object.entries(e)){if(n.commitOrderedMode){if(n.shardMode.kind==="global")throw new i("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 i("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.`)}},Q=e=>{he(e),ce(e),le(e),ue(e),de(e)},ve=(e,t={},n={},r={})=>(ee(e),te(e,n,r),ae(e),Q(e),H(e,t),K(e),y({tables:e,vectorIndexes:t})),I=(e,t)=>`${e}_${t}`,k=(e,t,n)=>n.has(e)?I(t,e):e,fe=(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}},Se=(e,t)=>{if(!e)throw new i("INTERNAL","defineSchemaExtension: `key` is required and must be a non-empty string");return{key:e,tables:t.tables,...t.vectorIndexes?{vectorIndexes:t.vectorIndexes}:{}}},me=((e,t)=>{if(!e)throw new i("INTERNAL","definePlugin: `key` is required and must be a non-empty string");if(t.extension&&t.extension.key!==e)throw new i("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}:{}}}),ke=(e,t)=>({...me(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 i("INTERNAL",`defineSchema(...).extend("${n}"): table "${h}" already exists in the base schema — another extension with the same key already contributed it`);a[h]=fe(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 i("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),Q(a),H(a,d),{rlsMode:e.rlsMode,tables:a,vectorIndexes:d}},Ee=(e,t)=>{let n=e;for(const r of t)r.extension&&(n=z(n,r.extension));return n},$e=e=>{const t=e.map(n=>n.middleware).filter(n=>n!==void 0);return V(t)};export{ke as a,me as b,$e as c,Ie as d,pe as e,ve as f,Se as g,xe as h,ye as i,Ne as j,Ee as k,K as l,z as m,Q as n,H as v};
@@ -1 +0,0 @@
1
- import"./wire-codec-CZ4obM6q.mjs";import"./bindOrm-D_hFUjmr.mjs";import{e as i,g as m,i as l,b as d,m as p,d as n,f as c,a as h,r as u}from"./middleware-DAVx_tP1.mjs";import"./policy-tag-V0lqFzgS.mjs";import"./allowAll-DkRAgItV.mjs";export{i as computeReadBaseWhere,m as evaluateWrite,l as indexRolePermissions,d as isFacadeEntry,p as matchesWhere,n as readIdentityRoles,c as resolveCan,h as resolvePolicyAuth,u as rls};