palgres 0.56.0 → 0.58.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/testing.js CHANGED
@@ -1,2 +1,2 @@
1
- /*! palgres 0.56.0 — Palbase SDK License (see LICENSE) */
2
- import{F as pe,G as be,P as G,Q as Re,R as ne,V as te,W as J,X as re,Y as $e,_ as B,ga as U,la as Oe,ma as Ie,n as he,p as me}from"./chunks/JPYKRUNF.js";import{o as we,r as ye,y as K,z as Q}from"./chunks/YTA5WUZJ.js";import{randomUUID as De}from"node:crypto";var Te=/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/,ke="user";function Se(n){let t=n.filter(i=>i!=null);return t.length===0?"text":t.every(i=>typeof i=="boolean")?"bool":t.every(i=>typeof i=="bigint"||typeof i=="number"&&Number.isInteger(i))?"int":t.every(i=>typeof i=="bigint"||typeof i=="number"&&Number.isFinite(i))?"numeric":t.every(i=>typeof i=="string"&&Te.test(i))?"uuid":"text"}function Ce(n,t){return t==null?null:n==="bool"||n==="int"||n==="numeric"||typeof t=="string"?t:String(t)}var je=n=>n.schema==="public"?n.name:`${n.schema}.${n.name}`;function xe(n,t){let i=ye(we(n)),l=be(n,"memory"),g,f=[],m=[],p=new Map,O=[...i.types.values()].filter(y=>y.table),k=y=>{let d=i.types.get(y),w=new Set;if(!d?.table)return[];w.add(d.table.key??"id");let e=r=>{let s=r;s.parts?s.parts.forEach(e):s.part?e(s.part):s.column&&w.add(s.column)};for(let r of d.relations.values())r.kind==="column"&&(w.add(r.column),r.where&&e(r.where));return[...w]},S=()=>{let y=new Map;for(let d of O){let w=d.table,e=t.rows(je(w)),r=w.key??"id",s={};for(let a of k(d.name))s[a]=Se(e.map(u=>u[a]));let o={key:r,columns:s};y.set(d.name,{shape:o,rows:e.map(a=>Object.fromEntries(Object.entries(s).map(([u,c])=>[u,Ce(c,a[u])])))})}return{tables:y,relationships:f}},N=(y,d,w)=>{let e=y.tables.get(d);if(!e)return w;let r=e.shape.columns[e.shape.key],s=K(r,w);return s===null?null:e.rows.some(a=>{let u=a[e.shape.key];return u!==null&&K(r,String(u))===s})?s:void 0},M=()=>{for(let d of O){let w=d.table,e=je(w),r=w.key??"id",s=t.deleted(e),o=Math.min(p.get(e)??0,s.length),a=c=>Te.test(c)?c.toLowerCase():c,u=new Set(s.slice(o).map(c=>c[r]).filter(c=>c!=null).map(c=>a(String(c))));p.set(e,s.length),u.size>0&&C(d.name,c=>u.has(a(c)),"access: row deleted")}let y=S();for(let d of O)C(d.name,w=>N(y,d.name,w)===void 0,"access: row deleted");return S()},C=(y,d,w)=>{let e=[];for(let r of f)r.objectType===y&&d(r.objectId)||r.subjectType===y&&d(r.subjectId)?E("revoke",r,w):e.push(r);f=e},E=(y,d,w)=>{m.unshift({at:new Date().toISOString(),action:y,object:{type:d.objectType,id:d.objectId},relation:d.relation,subject:{type:d.subjectType,id:d.subjectId},by:w})},T=(y,d)=>(y.object_type===void 0||y.object_type===d.objectType)&&(y.object_id===void 0||y.object_id===d.objectId)&&(y.relation===void 0||y.relation===d.relation)&&(y.subject_type===void 0||y.subject_type===d.subjectType)&&(y.subject_id===void 0||y.subject_id===d.subjectId),D=(y,d)=>{for(let w of["objectType","objectId","relation","subjectType","subjectId"])if(y[w]!==d[w])return y[w]<d[w]?-1:1;return 0};return{names:l,via:{caller:()=>g,check(y,d,w,e){let r=M(),s=N(r,w,e);return s==null?!1:Q(i,r).check(y,w,s,d)},objects:(y,d,w)=>Q(i,M()).objects(y,w,d),subjects(y,d,w){let e=M(),r=N(e,d,w);return r==null?[]:Q(i,e).subjects(d,r,y)},change(y,d,w,e,r){let s=M(),o=(u,c,h)=>{if(c===ke)return h;let b=N(s,c,h);if(b==null)throw new pe("no_object",`Database.$access: there is no ${c} ${JSON.stringify(h)} (${u}) \u2014 a relationship is given on an object that exists`);return b};if(y==="revoke"){let u=($,A)=>{let x=$===ke?void 0:s.tables.get($);return x?K(x.shape.columns[x.shape.key],A):A},c=u(d.type,d.id),h=u(e.type,e.id);if(c===null||h===null)return!1;let b={objectType:d.type,objectId:c,relation:w,subjectType:e.type,subjectId:h},R=f.findIndex($=>D($,b)===0);return R<0?!1:(f.splice(R,1),E("revoke",b,r??g??null),!0)}let a={objectType:d.type,objectId:o("the object",d.type,d.id),relation:w,subjectType:e.type,subjectId:o("the subject",e.type,e.id)};return f.some(u=>D(u,a)===0)?!1:(f.push({...a,since:new Date().toISOString()}),E("grant",a,r??g??null),!0)},relationships(y,d){return M(),f.filter(w=>T(y,w)).sort(D).slice(0,d).map(w=>({object:{type:w.objectType,id:w.objectId},relation:w.relation,subject:{type:w.subjectType,id:w.subjectId},since:w.since}))},history(y,d){return M(),m.filter(w=>T(y,{objectType:w.object.type,objectId:w.object.id,relation:w.relation,subjectType:w.subject.type,subjectId:w.subject.id})).slice(0,d).map(w=>({...w,object:{...w.object},subject:{...w.subject}}))}},signedInAs(y){g=y},snapshot(){let y={relationships:f.map(d=>({...d})),history:m.map(d=>({...d})),seen:new Map(p),user:g};return()=>{f=y.relationships,m=y.history,p=y.seen,g=y.user}}}}var Fe=/^\d{4}-\d{2}-\d{2}([T ]\d{2}:\d{2}(:\d{2}(\.\d+)?)?)?(Z|[+-]\d{2}(:?\d{2})?)?$/,Pe=/^([+-]?)(\d*)(?:\.(\d*))?$/;function v(n){if(n instanceof Date)return n.getTime();if(typeof n=="string"&&Fe.test(n)){let t=Date.parse(n);return Number.isNaN(t)?null:t}return null}function V(n){if(typeof n=="number")return Number.isFinite(n)?V(String(n)):null;if(typeof n!="string"||/e/i.test(n))return null;let t=Pe.exec(n.trim());if(t===null||t[2]===""&&(t[3]??"")==="")return null;let i=t[3]??"";return{unit:BigInt(`${t[1]==="-"?"-":""}${t[2]===""?"0":t[2]}${i}`),scale:i.length}}function Y(n,t){return n.unit*10n**BigInt(t-n.scale)}function ce(n,t){if(n==null||t===null||t===void 0)return null;let i=v(n),l=v(t);if(i!==null&&l!==null)return Math.sign(i-l);let g=V(n),f=V(t);if(g!==null&&f!==null){let m=Math.max(g.scale,f.scale),p=Y(g,m)-Y(f,m);return p===0n?0:p<0n?-1:1}return typeof n==typeof t&&(typeof n=="string"||typeof n=="boolean"||typeof n=="number")?n<t?-1:n>t?1:0:null}function P(n,t){return n==null||t===null||t===void 0?!1:n instanceof Date||t instanceof Date?v(n)!==null&&v(n)===v(t):Array.isArray(n)&&Array.isArray(t)?n.length===t.length&&n.every((i,l)=>P(i,t[l])):n===t}function Z(n){let t=((n?.days??0)*86400+(n?.hours??0)*3600+(n?.minutes??0)*60+(n?.seconds??0))*1e3;return new Date(Date.now()-t).toISOString()}function se(n,t,i){if(n==null)return null;if(typeof n=="number"&&typeof t=="number")return n+i*t;let l=V(n),g=V(t);if(l===null||g===null)throw new Error(`increment()/decrement() on a value that is not a number (${JSON.stringify(n)}): Postgres refuses it ("operator does not exist")`);let f=Math.max(l.scale,g.scale),m=Y(l,f)+BigInt(i)*Y(g,f);if(f===0)return typeof n=="number"?Number(m):m.toString();let p=m<0n,O=(p?-m:m).toString().padStart(f+1,"0"),k=`${p?"-":""}${O.slice(0,-f)}.${O.slice(-f)}`;return typeof n=="number"?Number(k):k}function _e(n,t){let i=T=>{let D=(T.unit<0n?-T.unit:T.unit).toString().padStart(T.scale+1,"0"),q=D.slice(0,D.length-T.scale),y=D.slice(D.length-T.scale),d=q.padStart(Math.ceil(q.length/4)*4,"0").match(/.{4}/g)??[],w=y.padEnd(Math.ceil(y.length/4)*4,"0").match(/.{4}/g)??[],r=[...d.map((s,o)=>[d.length-1-o,Number(s)]),...w.map((s,o)=>[-1-o,Number(s)])].find(([,s])=>s!==0);return r?[r[0],r[1]]:[0,0]},[l,g]=i(n),[f,m]=i(t),p=l-f-(g<=m?1:0),O=Math.min(Math.max(16-p*4,n.scale,t.scale,0),1e3),k=n.unit*10n**BigInt(O+t.scale),S=t.unit*10n**BigInt(n.scale),N=k/S,M=k%S;2n*(M<0n?-M:M)>=(S<0n?-S:S)&&(N+=k<0n!=S<0n?-1n:1n);let C=N<0n,E=(C?-N:N).toString().padStart(O+1,"0");return`${C?"-":""}${O===0?E:`${E.slice(0,-O)}.${E.slice(-O)}`}`}var j=n=>structuredClone(n);function ue(n,t,i){if(Re(i))throw new Error(`${n}(${t}): the fake database runs no SQL, so a sqlFragment cannot be evaluated \u2014 write the filter in the filter language (gt, gte, lt, lte, neq, in, contains, isNull, OR, AND, NOT), or test this against Postgres`);if(!(i===null||typeof i!="object"))for(let[l,g]of Object.entries(i))if(l==="OR"||l==="AND")for(let f of Array.isArray(g)?g:[])ue(n,t,f);else l==="NOT"&&ue(n,t,g)}function W(n,t,i){return he(new me({fields:[{field:t,message:i}]},`${n}: ${t} ${i}`))}function le(n,t,i="where"){for(let[l,g]of Object.entries(t))if(l==="OR"||l==="AND"){let f=g;if(l==="AND"&&f.length===0)throw W(n,`${i}.AND`,"is an empty list \u2014 no condition at all. Leave it out, or name a condition in it.");f.forEach((m,p)=>{if(Object.keys(m).length===0)throw W(n,`${i}.${l}[${p}]`,"holds no condition \u2014 a branch that matches every row. Name a condition in it, or leave it out.");le(n,m,`${i}.${l}[${p}]`)})}else if(l==="NOT"){if(Array.isArray(g))throw W(n,`${i}.NOT`,"is a list \u2014 NOT takes one filter object. For several conditions, NOT: { AND: [...] } or NOT: { OR: [...] }.");if(Object.keys(g).length===0)throw W(n,`${i}.NOT`,"holds no condition \u2014 NOT of nothing is not a filter. Name the condition to exclude.");le(n,g,`${i}.NOT`)}else if(l==="has"&&Object.keys(g??{}).length===0)throw W(n,`${i}.has`,"names no relation \u2014 no condition. Name one: has: { <relation>: { \u2026 } }.")}function L(n,t){if(Object.keys(t).length===0)throw W(n,"where",`holds no condition, so ${n} would reach EVERY row of the table. Name a condition.`)}function fe(n){let t=!1;for(let i of n){if(i===!1)return!1;i===null&&(t=!0)}return t?null:!0}function Ee(n){let t=!1;for(let i of n){if(i===!0)return!0;i===null&&(t=!0)}return t?null:!1}var F=n=>n==null;function H(n,t,i,l){return fe(Object.entries(l).map(([g,f])=>{if(g==="OR")return Ee(f.map(m=>H(n,t,i,m)));if(g==="AND")return fe(f.map(m=>H(n,t,i,m)));if(g==="NOT"){let m=H(n,t,i,f);return m===null?null:!m}if(g==="has")throw new Error(`${n}(${t}): the fake database has no relations, so a \`has\` filter cannot be decided for a row \u2014 read the related table first and filter by its ids ({ id: { in: [\u2026] } }), or test this against Postgres`);return Be(n,t,i,g,f)}))}var Ae=["neq","gt","gte","lt","lte"];function z(n,t){return F(n)||F(t)?null:P(n,t)}function Be(n,t,i,l,g){let f=i[l];return g===null?F(f):G(g)?z(f,i[g.$col]):J(g)?z(f,Z(U(g)?.minus)):typeof g=="object"&&!Array.isArray(g)&&!(g instanceof Date)?fe(Object.entries(g).map(([m,p])=>{if(J(p)){if(!Ae.includes(m))throw new Error(`${n}(${t}): where.${l}.${m} cannot take now()`);return X(m,f,Z(U(p)?.minus))}if(te(p))throw new Error(`${n}(${t}): where.${l}.${m} was given increment()/decrement() \u2014 a write, not a value to compare with`);if(G(p)){if(!Ae.includes(m))throw new Error(`${n}(${t}): where.${l}.${m} cannot take col()`);return X(m,f,i[p.$col])}switch(m){case"in":{if(!Array.isArray(p))throw new Error(`${n}(${t}): where.${l}.in is a list`);return Ee(p.map(O=>z(f,O)))}case"neq":return p===null?!F(f):X(m,f,p);case"gt":case"gte":case"lt":case"lte":return X(m,f,p);case"isNull":if(typeof p!="boolean")throw new Error(`${n}(${t}): where.${l}.isNull is true or false`);return p?F(f):!F(f);case"overlaps":if(!Array.isArray(p))throw new Error(`${n}(${t}): where.${l}.overlaps is a list`);if(f!=null&&!Array.isArray(f))throw new Error(`${n}(${t}): where.${l}: "overlaps" is an array column's operator`);return F(f)?null:p.some(O=>f.some(k=>P(O,k)));case"contains":case"icontains":case"startsWith":case"endsWith":{if(m==="contains"&&Array.isArray(p))return F(f)?null:Array.isArray(f)&&p.every(O=>f.some(k=>P(O,k)));if(typeof p!="string")throw new Error(`${n}(${t}): where.${l}.${m} is text`);return F(f)?null:typeof f!="string"?!1:m==="contains"?f.includes(p):m==="icontains"?f.toLowerCase().includes(p.toLowerCase()):m==="startsWith"?f.startsWith(p):f.endsWith(p)}default:throw new Error(`${n}(${t}): where.${l} has no operator "${m}"`)}})):z(f,g)}function X(n,t,i){if(F(t)||F(i))return null;if(n==="neq")return!P(t,i);let l=ce(t,i);return l===null?!1:n==="gt"?l>0:n==="gte"?l>=0:n==="lt"?l<0:l<=0}function We(n={}){let t=new Map,i=new Map,l=new Map,g=new Map,f=new Map,m=[],p=n.access===void 0?void 0:xe(n.access,{rows:e=>t.get(e)??[],deleted:e=>f.get(e)??[]});p?.signedInAs(n.user);let O=e=>{let r=t.get(e);return r||t.set(e,r=[]),r},k=(e,r,s)=>{let o=e.get(r);o?o.push(s):e.set(r,[s])},S=e=>e.id===void 0?{id:De(),...e}:{...e},N=()=>{let e={store:new Map([...t].map(([s,o])=>[s,o.map(j)])),inserted:oe(i),updated:oe(l),deleted:new Map([...g].map(([s,o])=>[s,[...o]])),removed:oe(f)},r=p?.snapshot();return()=>{t=e.store,i=e.inserted,l=e.updated,g=e.deleted,f=e.removed,r?.()}};function M(e,r,s){let o={};for(let[a,u]of Object.entries(s)){let c=U(u);if(c!==null&&c.fn==="now")o[a]=Z(c.minus);else{if(c!==null)throw new Error(`${e}(${r}): "${a}" was given ${c.fn==="inc"?"increment()":"decrement()"} \u2014 the row does not exist yet, so there is no current value to change`);o[a]=u}}return B(e,r,Object.keys(o),o),re(e,r,Object.keys(o),o),o}function C(e,r,s,o){B(e,r,Object.keys(o),o);let a={};for(let[u,c]of Object.entries(o)){let h=U(c);h!==null&&h.fn==="now"?a[u]=Z(h.minus):h!==null?a[u]=se(s[u],h.by,h.fn==="inc"?1:-1):a[u]=c}return re(e,r,Object.keys(a),a),a}function E(e,r,s){let o=S(M(e,r,s));return O(r).push(o),k(i,r,j(o)),j(o)}function T(e,r,s){return $e(e,r,s),ue(e,r,s),s!==void 0&&le(e,s),(t.get(r)??[]).filter(o=>s===void 0||H(e,r,o,s)===!0)}let D={diagnostics:()=>null,async query(e,r=[]){return m.push({sql:e,params:r}),[]},async findUnique(){throw new Error("the fake database knows no table's declared unique keys \u2014 find the row with findMany, or test this against Postgres")},async page(){throw new Error("the fake database cannot reproduce Postgres' cursor ordering, collation or row-level security \u2014 test pagination against Postgres")},async search(e){throw new Error(`search(${e}): the fake database has neither embeddings nor full text \u2014 test search against Postgres`)},async findById(e,r){let s=(t.get(e)??[]).find(o=>o.id===r);return s?j(s):null},async findMany(e,r,s){let{limit:o,offset:a}=s??{};if(o!==void 0&&(!Number.isInteger(o)||o<0))throw new Error(`findMany(${e}): limit is a whole number, 0 or more (got ${String(o)})`);if(a!==void 0){if(!Number.isInteger(a)||a<0)throw new Error(`findMany(${e}): offset is a whole number, 0 or more (got ${String(a)})`);if(o===void 0)throw new Error(`findMany(${e}): offset comes with limit \u2014 an offset into an unbounded result is not a page`)}if(s?.with!==void 0&&Object.keys(s.with).length>0)throw new Error(`findMany(${e}): the fake database has no relations, so \`with\` cannot be read \u2014 seed and query the related table on its own, or test this against Postgres`);let u=T("findMany",e,r),c=s?.orderBy===void 0?[]:Array.isArray(s.orderBy)?s.orderBy:[s.orderBy];c.length>0&&(u=[...u].sort((R,$)=>{for(let A of c){let x=A.direction==="desc"?-1:1,I=R[A.column],_=$[A.column],ee=I==null,de=_==null;if(ee||de){if(ee&&de)continue;let Ne=A.nulls===void 0?x===-1:A.nulls==="first";return(ee?1:-1)*(Ne?-1:1)}let ge=ce(I,_)??(String(I)<String(_)?-1:String(I)>String(_)?1:0);if(ge!==0)return ge*x}return 0}));let h=o===void 0?u:u.slice(a??0,(a??0)+o),b=s?.select;return h.map(R=>b===void 0||b.length===0?j(R):Object.fromEntries(b.map($=>[$,structuredClone(R[$])])))},async count(e,r={}){return T("count",e,r).length},async aggregate(e,r){let s=T("aggregate",e,r.where),o=r.groupBy??[],a=c=>{let h={},b=R=>c.map($=>$[R]).filter($=>$!=null);for(let R of r.sum??[]){let $=b(R);(h.sum??={})[R]=$.length===0?null:String($.reduce((A,x)=>se(A,x,1),"0"))}for(let R of r.avg??[]){let $=b(R),A=$.some(x=>typeof x=="number"&&!Number.isInteger(x));(h.avg??={})[R]=$.length===0?null:A?$.reduce((x,I)=>x+I,0)/$.length:_e(V($.reduce((x,I)=>se(x,I,1),"0")),{unit:BigInt($.length),scale:0})}for(let[R,$]of[["min",-1],["max",1]])for(let A of r[R]??[]){let x=b(A);(h[R]??={})[A]=x.length===0?null:x.reduce((I,_)=>(ce(_,I)??0)*$>0?_:I)}return r.count===!0?h.count=c.length:r.count!==void 0&&r.count!==!1&&(h.count=Object.fromEntries(Object.entries(r.count).map(([R,$])=>[R,c.filter(A=>H("aggregate",e,A,$)===!0).length]))),h};if(o.length===0)return a(s);let u=new Map;for(let c of s){let h=JSON.stringify(o.map(b=>c[b]));u.set(h,[...u.get(h)??[],c])}return[...u.values()].map(c=>({...a(c),...Object.fromEntries(o.map(h=>[h,c[0][h]]))}))},async insert(e,r){return E("insert",e,r)},insertMany:(async(e,r,s)=>{if(Oe(s),s?.onConflict?.length||s?.action!==void 0)throw new Error(`insertMany(${e}): the fake database knows no unique constraint to collide with \u2014 test onConflict against Postgres`);if(r.length===0)return s?.returning===!1?0:[];let o=Object.keys(r[0]);r.forEach((u,c)=>{let h=o.filter(R=>!(R in u)),b=Object.keys(u).filter(R=>!o.includes(R));if(h.length>0||b.length>0)throw new Error(`insertMany(${e}): row ${c} has not the first row's columns${h.length?` (missing ${h.join(", ")})`:""}${b.length?` (extra ${b.join(", ")})`:""} \u2014 write null for an empty one, or insert rows of another shape in a call of their own`)});let a=r.map(u=>E("insertMany",e,u));return s?.returning===!1?a.length:a}),async put(e,r,s){if(!s?.onConflict?.length)throw new Error(`put(${e}): onConflict names at least one column`);let o=M("put",e,r),a=O(e).find(u=>s.onConflict.every(c=>P(u[c],o[c])));if(!a)return E("put",e,r);for(let[u,c]of Object.entries(o))s.onConflict.includes(u)||(a[u]=c);return k(l,e,j(a)),j(a)},async update(e,r,s){let o=t.get(e)??[],a=o.findIndex(u=>u.id===r);return a<0?(B("update",e,Object.keys(s),s),null):(o[a]={...o[a],...C("update",e,o[a],s)},k(l,e,j(o[a])),j(o[a]))},async updateMany(e,r,s,o){L("updateMany",r);let a=T("updateMany",e,r),u=O(e),c=[];for(let h of a){let b=u.indexOf(h);u[b]={...h,...C("updateMany",e,h,s)},k(l,e,j(u[b])),c.push(j(u[b]))}return a.length===0&&B("updateMany",e,Object.keys(s),s),o?.returning===!1?c.length:c},async delete(e,r){let s=t.get(e)??[],o=s.findIndex(u=>u.id===r);if(o<0)return;let[a]=s.splice(o,1);k(g,e,r),k(f,e,a)},async deleteMany(e,r){L("deleteMany",r);let s=T("deleteMany",e,r);t.set(e,(t.get(e)??[]).filter(o=>!s.includes(o)));for(let o of s)k(g,e,String(o.id)),k(f,e,o);return s.length},async claim(e,r,s={}){let o=Object.keys(r);if(o.length===0)throw new Error(`claim(${e}): no unique field \u2014 claim takes a key; without one, insert(${e}, \u2026)`);B("claim",e,o,r);let a=(t.get(e)??[]).find(u=>o.every(c=>P(u[c],r[c])));return a?{inserted:!1,row:j(a)}:{inserted:!0,row:E("claim",e,{...r,...s})}},async lockRows(e,r){if(r.length===0)return;let s=t.get(e)??[],o=[...new Set(r)].filter(a=>!s.some(u=>u.id===a));if(o.length>0&&s.length>0)throw new Error(`lockRows(${e}): no row with id ${o.join(", ")}`)},async lockRowsWhere(e,r,s){let o=s?.mode??"update";if(!["update","share","noKeyUpdate"].includes(o))throw new Error(`lockRowsWhere(${e}): mode is "update", "share" or "noKeyUpdate" (got "${String(o)}")`);L("lockRowsWhere",r),T("lockRowsWhere",e,r)},async advisoryXactLock(){}};function q(e){let r=N(),s=[];try{for(let o of e.ops){let a=y(o,s);s.push(a);let u=Ve(o.guard,a.rows.length);if(u)throw u}}catch(o){throw r(),o}return{results:s}}function y(e,r){let s=a=>Object.fromEntries(Object.entries(a??{}).map(([u,c])=>[u,Me(c,r)])),o=`transaction plan ${e.op}`;switch(e.op){case"insert":return ie(E(o,e.table,s(e.values)));case"insertMany":{let a=(e.rows??[]).map(h=>s(h)),u=e.onConflict??[];if(e.action!==void 0&&u.length===0)throw new Error(`${o}(${e.table}): the fake database knows no unique key to collide with \u2014 name onConflict columns, or test this against Postgres`);let c=[];for(let h of a){let b=u.length>0?O(e.table).find(R=>u.every($=>P(R[$],h[$]))):void 0;if(!(b&&e.action==="ignore")){if(b&&e.action==="update"){Object.assign(b,C(o,e.table,b,Object.fromEntries(Object.entries(h).filter(([R])=>!u.includes(R))))),k(l,e.table,j(b)),c.push(j(b));continue}c.push(E(o,e.table,h))}}return{rows:c,rows_affected:c.length}}case"upsert":{let a=s(e.values),u=e.onConflict??[];if(Object.keys(a).length===0||u.length===0)throw Object.assign(new Error(`put on ${e.table} needs columns and onConflict`),{error_code:"tx_bad_upsert"});let c=O(e.table).find(h=>u.every(b=>P(h[b],a[b])));return c?(Object.assign(c,C(o,e.table,c,Object.fromEntries(Object.entries(a).filter(([h])=>!u.includes(h))))),k(l,e.table,j(c)),ie(j(c))):ie(E(o,e.table,a))}case"update":{let a=s(e.set);if(Object.keys(a).length===0)throw new Error(`update ${e.table}: nothing to set`);let u=ae(e.where,r);L(o,u);let c=O(e.table),h=[];for(let b of T(o,e.table,u)){let R=c.indexOf(b);c[R]={...b,...C(o,e.table,b,a)},k(l,e.table,j(c[R])),h.push(j(c[R]))}return{rows:h,rows_affected:h.length}}case"delete":{let a=ae(e.where,r);L(o,a);let u=T(o,e.table,a);t.set(e.table,O(e.table).filter(c=>!u.includes(c)));for(let c of u)k(g,e.table,String(c.id)),k(f,e.table,c);return{rows:u.map(j),rows_affected:u.length}}case"select":{let a=T(o,e.table,ae(e.where,r));return e.limit!==void 0&&(a=a.slice(0,e.limit)),{rows:a.map(j),rows_affected:a.length}}default:throw new Error(`unknown operation "${String(e.op)}" in a transaction plan`)}}let d={...D,async txPlan(e){return q(e)},async attempt(e){let r=N();try{return await e(D)}catch(s){throw r(),s}},async atomic(){throw new Error("the fake database cannot reproduce a transaction's isolation, COMMIT or retry \u2014 test $atomic against Postgres")}};return{...d,asService:()=>d,inserted:e=>(i.get(e)??[]).map(j),updated:e=>(l.get(e)??[]).map(j),deleted:e=>[...g.get(e)??[]],seed(e,r){t.set(e,r.map(j))},queries:m,...p===void 0?{}:{access:p}}}function oe(n){return new Map([...n].map(([t,i])=>[t,i.map(j)]))}function ie(n){return{rows:[n],rows_affected:1}}function Me(n,t){if(!ne(n))return n;let i=t[n.$ref.op]?.rows[0];if(!i)throw Object.assign(new Error(`transaction plan: operation ${n.$ref.op} produced no row to reference`),{error_code:"tx_ref_unresolved"});return i[n.$ref.field]}function ae(n,t){let i=l=>{if(ne(l)){let g=Me(l,t);if(g==null)throw Object.assign(new Error(`transaction plan: a filter's reference to operation ${l.$ref.op}'s "${l.$ref.field}" is NULL`),{error_code:"tx_ref_null"});return g}return Array.isArray(l)?l.map(i):l!==null&&typeof l=="object"&&!G(l)&&!te(l)&&!J(l)&&!(l instanceof Date)?Object.fromEntries(Object.entries(l).map(([g,f])=>[g,i(f)])):l};return i(n??{})}function Ve(n,t){return n?(n.kind==="one"?t===1:n.kind==="none"?t===0:n.kind==="atLeast"?t>=n.n:t<=n.n)?null:Object.assign(new Error(`transaction expectation failed: ${n.kind} (${t} row(s))`),{error_code:"tx_guard_failed",slot:n.slot}):null}export{We as createFakeClient,Ie as typedDatabase};
1
+ /*! palgres 0.58.0 — Palbase SDK License (see LICENSE) */
2
+ import{$ as H,F as ae,G as Ee,I as Me,Q as ee,R as Ie,S as ue,W as le,X as ne,Y as fe,Z as Ne,ha as J,ma as Se,n as Te,na as Ue,p as Ae}from"./chunks/YBTR6MHQ.js";import{G as Q,H as G,I as Oe,J as ce,K as xe,q as $e,u as ke}from"./chunks/FW3D6LUC.js";import{randomUUID as He}from"node:crypto";var Pe=/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/,De="access: its time passed",Ce="user";function Fe(t){let o=t.filter(u=>u!=null);return o.length===0?"text":o.every(u=>typeof u=="boolean")?"bool":o.every(u=>typeof u=="bigint"||typeof u=="number"&&Number.isInteger(u))?"int":o.every(u=>typeof u=="bigint"||typeof u=="number"&&Number.isFinite(u))?"numeric":o.every(u=>typeof u=="string"&&Pe.test(u))?"uuid":"text"}function Le(t,o){return o==null?null:t==="bool"||t==="int"||t==="numeric"||typeof o=="string"?o:String(o)}var de=t=>t.schema==="public"?t.name:`${t.schema}.${t.name}`;function _e(t,o){let u=ke($e(t)),d=Ee(t,"memory"),p,f=[],w=[],m=0,O=new Map,k=[...u.types.values()].filter(e=>e.table),_=e=>{let r=u.types.get(e),i=new Set;if(!r?.table)return[];i.add(r.table.key??"id");let s=a=>{let g=a;g.parts?g.parts.forEach(s):g.part?s(g.part):g.column&&i.add(g.column)};for(let a of r.relations.values())a.kind!=="stored"&&(a.kind==="column"&&i.add(a.column),a.where&&s(a.where));return[...i]},F=()=>{let e=new Map;for(let r of k){let i=r.table,s=o.rows(de(i)),a=i.key??"id",g={};for(let b of _(r.name))g[b]=Fe(s.map(y=>y[b]));let h={key:a,columns:g};e.set(r.name,{shape:h,rows:s.map(b=>Object.fromEntries(Object.entries(g).map(([y,j])=>[y,Le(j,b[y])])))})}return{tables:e,relationships:f,now:Date.now()}},C=(e,r,i)=>{let s=e.tables.get(r);if(!s)return i;let a=s.shape.columns[s.shape.key],g=Q(a,i);return g===null?null:s.rows.some(b=>{let y=b[s.shape.key];return y!==null&&Q(a,String(y))===g})?g:void 0},M=()=>{for(let r of k){let i=r.table,s=de(i),a=i.key??"id",g=o.deleted(s),h=Math.min(O.get(s)??0,g.length),b=j=>Pe.test(j)?j.toLowerCase():j,y=new Set(g.slice(h).map(j=>j[a]).filter(j=>j!=null).map(j=>b(String(j))));O.set(s,g.length),y.size>0&&V(r.name,j=>y.has(b(j)),"access: row deleted")}let e=F();for(let r of k)V(r.name,i=>C(e,r.name,i)===void 0,"access: row deleted");return F()},T=e=>e.expiresAt!==void 0&&e.expiresAt!==null&&e.expiresAt<=Date.now(),E=(e,r)=>T(e)?W("expire",e,De,e.expiresAt):W("revoke",e,r),N=(e,r)=>{let i=[],s=0;for(let a of f)e(a)?(E(a,r),s++):i.push(a);return f=i,s},V=(e,r,i)=>{N(s=>s.objectType===e&&r(s.objectId)||s.subjectType===e&&r(s.subjectId),i)},U=e=>new Date(e).toISOString().replace("Z","000Z"),B=e=>e==null?null:U(e),W=(e,r,i,s)=>{w.push({seq:++m,at:U(s??Date.now()),action:e,object:{type:r.objectType,id:r.objectId},relation:r.relation,subject:{type:r.subjectType,id:r.subjectId},by:i,until:B(r.expiresAt)})},X=(e,r)=>(e.object_type===void 0||e.object_type===r.objectType)&&(e.object_id===void 0||e.object_id===r.objectId)&&(e.relation===void 0||e.relation===r.relation)&&(e.subject_type===void 0||e.subject_type===r.subjectType)&&(e.subject_id===void 0||e.subject_id===r.subjectId),n=(e,r)=>{for(let i of["objectType","objectId","relation","subjectType","subjectId"])if(e[i]!==r[i])return e[i]<r[i]?-1:1;return 0},c={caller:()=>p,check(e,r,i,s){let a=M(),g=C(a,i,s);return g==null?!1:G(u,a).check(e,i,g,r)},objects:(e,r,i)=>G(u,M()).objects(e,i,r),subjects(e,r,i){let s=M(),a=C(s,r,i);return a==null?[]:G(u,s).subjects(r,a,e)},open(e,r,i){let s=M(),a=C(s,r,i);return a==null?null:G(u,s).open(r,a,e)},change(e,r,i,s,a,g){let h=M(),b=(R,I,S)=>{if(I===Ce)return S;let A=C(h,I,S);if(A==null)throw new ae("no_object",`Database.$access: there is no ${I} ${JSON.stringify(S)} (${R}) \u2014 a relationship is given on an object that exists`);return A};if(e==="revoke"){let R=(L,je)=>{let ie=L===Ce?void 0:h.tables.get(L);return ie?Q(ie.shape.columns[ie.shape.key],je):je},I=R(r.type,r.id),S=R(s.type,s.id);if(I===null||S===null)return!1;let A={objectType:r.type,objectId:I,relation:i,subjectType:s.type,subjectId:S},D=f.find(L=>n(L,A)===0);if(!D)return!1;let Ve=!T(D);return N(L=>L===D,a??p??null),Ve}let y={objectType:r.type,objectId:b("the object",r.type,r.id),relation:i,subjectType:s.type,subjectId:b("the subject",s.type,s.id),expiresAt:g??null},j=u.trees.find(R=>R.type===y.objectType&&R.relation===y.relation&&u.types.get(R.type)?.relations.get(R.relation)?.kind==="stored");if(j&&y.subjectType===y.objectType){let R=Date.now(),I=f.filter(A=>A.objectType===j.type&&A.relation===j.relation&&A.subjectType===j.type&&!T(A)),S=xe(j,I,y.objectId,y.subjectId,R)??ce(j.type,j.depth,y.objectId,y.subjectId,A=>I.filter(D=>D.objectId===A).map(D=>D.subjectId),A=>I.filter(D=>D.subjectId===A).map(D=>D.objectId));if(S)throw new ae(Me[S.code],`Database.$access: ${S.message}`)}N(R=>R.objectType===y.objectType&&R.objectId===y.objectId&&T(R),null);let $=f.find(R=>n(R,y)===0);return $?(($.expiresAt??null)!==(y.expiresAt??null)&&($.expiresAt=y.expiresAt,W("grant",y,a??p??null)),!1):(f.push({...y,since:U(Date.now())}),W("grant",y,a??p??null),!0)},sweep(e){M();let r=f.filter(T).sort((i,s)=>i.expiresAt-s.expiresAt).slice(0,e);return N(i=>r.includes(i),null)},relationships(e,r){return M(),f.filter(i=>!T(i)&&X(e,i)).sort(n).slice(0,r).map(i=>({object:{type:i.objectType,id:i.objectId},relation:i.relation,subject:{type:i.subjectType,id:i.subjectId},since:i.since,until:B(i.expiresAt)}))},history(e,r){M();let i=f.filter(T).map(s=>({seq:Number.POSITIVE_INFINITY,at:B(s.expiresAt),action:"expire",object:{type:s.objectType,id:s.objectId},relation:s.relation,subject:{type:s.subjectType,id:s.subjectId},by:De,until:B(s.expiresAt)}));return[...w,...i].filter(s=>X(e,{objectType:s.object.type,objectId:s.object.id,relation:s.relation,subjectType:s.subject.type,subjectId:s.subject.id})).sort((s,a)=>s.at!==a.at?s.at<a.at?1:-1:a.seq===s.seq?0:a.seq>s.seq?1:-1).slice(0,r).map(({seq:s,...a})=>({...a,object:{...a.object},subject:{...a.subject}}))}},l=e=>{let r=k.find(i=>de(i.table)===e);return r?u.trees.flatMap(i=>{let s=i.type===r.name?r.relations.get(i.relation):void 0;return s?.kind==="column"?[{type:r.name,key:r.table?.key??"id",column:s.column,depth:i.depth}]:[]}):[]};return{names:d,via:c,nested:e=>l(e).length>0,misplaced(e,r,i){for(let s of l(e)){let a=Fe(i.map($=>$[s.key])),g=$=>$==null?null:Q(a,String($)),h=new Map;for(let $ of i){let R=g($[s.key]);R!==null&&h.set(R,g($[s.column]))}let b=new Map;for(let $ of r){let R=g($[s.key]);R!==null&&b.set(R,g($[s.column]))}let y=$=>[...h].filter(([,R])=>R===$).map(([R])=>R),j=$=>$!==null&&h.has($)?$:null;for(let[$,R]of h){if(b.has($)&&b.get($)===R||R===null&&y($).length===0)continue;if(R!==null&&!h.has(R))return Oe(s.type,$,R);let I=ce(s.type,s.depth,$,j(R),S=>[j(h.get(S)??null)].filter(A=>A!==null),y);if(I)return I}}return null},signedInAs(e){p=e},snapshot(){let e={relationships:f.map(r=>({...r})),history:w.map(r=>({...r})),written:m,seen:new Map(O),user:p};return()=>{f=e.relationships,w=e.history,m=e.written,O=e.seen,p=e.user}}}}var Ke=/^\d{4}-\d{2}-\d{2}([T ]\d{2}:\d{2}(:\d{2}(\.\d+)?)?)?(Z|[+-]\d{2}(:?\d{2})?)?$/,ve=/^([+-]?)(\d*)(?:\.(\d*))?$/;function Z(t){if(t instanceof Date)return t.getTime();if(typeof t=="string"&&Ke.test(t)){let o=Date.parse(t);return Number.isNaN(o)?null:o}return null}function v(t){if(typeof t=="number")return Number.isFinite(t)?v(String(t)):null;if(typeof t!="string"||/e/i.test(t))return null;let o=ve.exec(t.trim());if(o===null||o[2]===""&&(o[3]??"")==="")return null;let u=o[3]??"";return{unit:BigInt(`${o[1]==="-"?"-":""}${o[2]===""?"0":o[2]}${u}`),scale:u.length}}function se(t,o){return t.unit*10n**BigInt(o-t.scale)}function ye(t,o){if(t==null||o===null||o===void 0)return null;let u=Z(t),d=Z(o);if(u!==null&&d!==null)return Math.sign(u-d);let p=v(t),f=v(o);if(p!==null&&f!==null){let w=Math.max(p.scale,f.scale),m=se(p,w)-se(f,w);return m===0n?0:m<0n?-1:1}return typeof t==typeof o&&(typeof t=="string"||typeof t=="boolean"||typeof t=="number")?t<o?-1:t>o?1:0:null}function q(t,o){return t==null||o===null||o===void 0?!1:t instanceof Date||o instanceof Date?Z(t)!==null&&Z(t)===Z(o):Array.isArray(t)&&Array.isArray(o)?t.length===o.length&&t.every((u,d)=>q(u,o[d])):t===o}function oe(t){let o=((t?.days??0)*86400+(t?.hours??0)*3600+(t?.minutes??0)*60+(t?.seconds??0))*1e3;return new Date(Date.now()-o).toISOString()}function ge(t,o,u){if(t==null)return null;if(typeof t=="number"&&typeof o=="number")return t+u*o;let d=v(t),p=v(o);if(d===null||p===null)throw new Error(`increment()/decrement() on a value that is not a number (${JSON.stringify(t)}): Postgres refuses it ("operator does not exist")`);let f=Math.max(d.scale,p.scale),w=se(d,f)+BigInt(u)*se(p,f);if(f===0)return typeof t=="number"?Number(w):w.toString();let m=w<0n,O=(m?-w:w).toString().padStart(f+1,"0"),k=`${m?"-":""}${O.slice(0,-f)}.${O.slice(-f)}`;return typeof t=="number"?Number(k):k}function Qe(t,o){let u=E=>{let N=(E.unit<0n?-E.unit:E.unit).toString().padStart(E.scale+1,"0"),V=N.slice(0,N.length-E.scale),U=N.slice(N.length-E.scale),B=V.padStart(Math.ceil(V.length/4)*4,"0").match(/.{4}/g)??[],W=U.padEnd(Math.ceil(U.length/4)*4,"0").match(/.{4}/g)??[],n=[...B.map((c,l)=>[B.length-1-l,Number(c)]),...W.map((c,l)=>[-1-l,Number(c)])].find(([,c])=>c!==0);return n?[n[0],n[1]]:[0,0]},[d,p]=u(t),[f,w]=u(o),m=d-f-(p<=w?1:0),O=Math.min(Math.max(16-m*4,t.scale,o.scale,0),1e3),k=t.unit*10n**BigInt(O+o.scale),_=o.unit*10n**BigInt(t.scale),F=k/_,C=k%_;2n*(C<0n?-C:C)>=(_<0n?-_:_)&&(F+=k<0n!=_<0n?-1n:1n);let M=F<0n,T=(M?-F:F).toString().padStart(O+1,"0");return`${M?"-":""}${O===0?T:`${T.slice(0,-O)}.${T.slice(-O)}`}`}var x=t=>structuredClone(t);function he(t,o,u){if(Ie(u))throw new Error(`${t}(${o}): the fake database runs no SQL, so a sqlFragment cannot be evaluated \u2014 write the filter in the filter language (gt, gte, lt, lte, neq, in, contains, isNull, OR, AND, NOT), or test this against Postgres`);if(!(u===null||typeof u!="object"))for(let[d,p]of Object.entries(u))if(d==="OR"||d==="AND")for(let f of Array.isArray(p)?p:[])he(t,o,f);else d==="NOT"&&he(t,o,p)}function K(t,o,u){return Te(new Ae({fields:[{field:o,message:u}]},`${t}: ${o} ${u}`))}function be(t,o,u="where"){for(let[d,p]of Object.entries(o))if(d==="OR"||d==="AND"){let f=p;if(d==="AND"&&f.length===0)throw K(t,`${u}.AND`,"is an empty list \u2014 no condition at all. Leave it out, or name a condition in it.");f.forEach((w,m)=>{if(Object.keys(w).length===0)throw K(t,`${u}.${d}[${m}]`,"holds no condition \u2014 a branch that matches every row. Name a condition in it, or leave it out.");be(t,w,`${u}.${d}[${m}]`)})}else if(d==="NOT"){if(Array.isArray(p))throw K(t,`${u}.NOT`,"is a list \u2014 NOT takes one filter object. For several conditions, NOT: { AND: [...] } or NOT: { OR: [...] }.");if(Object.keys(p).length===0)throw K(t,`${u}.NOT`,"holds no condition \u2014 NOT of nothing is not a filter. Name the condition to exclude.");be(t,p,`${u}.NOT`)}else if(d==="has"&&Object.keys(p??{}).length===0)throw K(t,`${u}.has`,"names no relation \u2014 no condition. Name one: has: { <relation>: { \u2026 } }.")}function Y(t,o){if(Object.keys(o).length===0)throw K(t,"where",`holds no condition, so ${t} would reach EVERY row of the table. Name a condition.`)}function Re(t){let o=!1;for(let u of t){if(u===!1)return!1;u===null&&(o=!0)}return o?null:!0}function We(t){let o=!1;for(let u of t){if(u===!0)return!0;u===null&&(o=!0)}return o?null:!1}var P=t=>t==null;function z(t,o,u,d){return Re(Object.entries(d).map(([p,f])=>{if(p==="OR")return We(f.map(w=>z(t,o,u,w)));if(p==="AND")return Re(f.map(w=>z(t,o,u,w)));if(p==="NOT"){let w=z(t,o,u,f);return w===null?null:!w}if(p==="has")throw new Error(`${t}(${o}): the fake database has no relations, so a \`has\` filter cannot be decided for a row \u2014 read the related table first and filter by its ids ({ id: { in: [\u2026] } }), or test this against Postgres`);return Ge(t,o,u,p,f)}))}var Be=["neq","gt","gte","lt","lte"];function te(t,o){return P(t)||P(o)?null:q(t,o)}function Ge(t,o,u,d,p){let f=u[d];return p===null?P(f):ee(p)?te(f,u[p.$col]):ne(p)?te(f,oe(J(p)?.minus)):typeof p=="object"&&!Array.isArray(p)&&!(p instanceof Date)?Re(Object.entries(p).map(([w,m])=>{if(ne(m)){if(!Be.includes(w))throw new Error(`${t}(${o}): where.${d}.${w} cannot take now()`);return re(w,f,oe(J(m)?.minus))}if(le(m))throw new Error(`${t}(${o}): where.${d}.${w} was given increment()/decrement() \u2014 a write, not a value to compare with`);if(ee(m)){if(!Be.includes(w))throw new Error(`${t}(${o}): where.${d}.${w} cannot take col()`);return re(w,f,u[m.$col])}switch(w){case"in":{if(!Array.isArray(m))throw new Error(`${t}(${o}): where.${d}.in is a list`);return We(m.map(O=>te(f,O)))}case"neq":return m===null?!P(f):re(w,f,m);case"gt":case"gte":case"lt":case"lte":return re(w,f,m);case"isNull":if(typeof m!="boolean")throw new Error(`${t}(${o}): where.${d}.isNull is true or false`);return m?P(f):!P(f);case"overlaps":if(!Array.isArray(m))throw new Error(`${t}(${o}): where.${d}.overlaps is a list`);if(f!=null&&!Array.isArray(f))throw new Error(`${t}(${o}): where.${d}: "overlaps" is an array column's operator`);return P(f)?null:m.some(O=>f.some(k=>q(O,k)));case"contains":case"icontains":case"startsWith":case"endsWith":{if(w==="contains"&&Array.isArray(m))return P(f)?null:Array.isArray(f)&&m.every(O=>f.some(k=>q(O,k)));if(typeof m!="string")throw new Error(`${t}(${o}): where.${d}.${w} is text`);return P(f)?null:typeof f!="string"?!1:w==="contains"?f.includes(m):w==="icontains"?f.toLowerCase().includes(m.toLowerCase()):w==="startsWith"?f.startsWith(m):f.endsWith(m)}default:throw new Error(`${t}(${o}): where.${d} has no operator "${w}"`)}})):te(f,p)}function re(t,o,u){if(P(o)||P(u))return null;if(t==="neq")return!q(o,u);let d=ye(o,u);return d===null?!1:t==="gt"?d>0:t==="gte"?d>=0:t==="lt"?d<0:d<=0}function Je(t={}){let o=new Map,u=new Map,d=new Map,p=new Map,f=new Map,w=[],m=t.access===void 0?void 0:_e(t.access,{rows:n=>o.get(n)??[],deleted:n=>f.get(n)??[]});m?.signedInAs(t.user);let O=n=>{let c=o.get(n);return c||o.set(n,c=[]),c},k=(n,c,l)=>{let e=n.get(c);e?e.push(l):n.set(c,[l])},_=n=>n.id===void 0?{id:He(),...n}:{...n},F=()=>{let n={store:new Map([...o].map(([l,e])=>[l,e.map(x)])),inserted:pe(u),updated:pe(d),deleted:new Map([...p].map(([l,e])=>[l,[...e]])),removed:pe(f)},c=m?.snapshot();return()=>{o=n.store,u=n.inserted,d=n.updated,p=n.deleted,f=n.removed,c?.()}};function C(n,c,l){let e={};for(let[r,i]of Object.entries(l)){let s=J(i);if(s!==null&&s.fn==="now")e[r]=oe(s.minus);else{if(s!==null)throw new Error(`${n}(${c}): "${r}" was given ${s.fn==="inc"?"increment()":"decrement()"} \u2014 the row does not exist yet, so there is no current value to change`);e[r]=i}}return H(n,c,Object.keys(e),e),fe(n,c,Object.keys(e),e),e}function M(n,c,l,e){H(n,c,Object.keys(e),e);let r={};for(let[i,s]of Object.entries(e)){let a=J(s);a!==null&&a.fn==="now"?r[i]=oe(a.minus):a!==null?r[i]=ge(l[i],a.by,a.fn==="inc"?1:-1):r[i]=s}return fe(n,c,Object.keys(r),r),r}function T(n,c,l){let e=_(C(n,c,l));return O(c).push(e),k(u,c,x(e)),x(e)}function E(n,c,l){return Ne(n,c,l),he(n,c,l),l!==void 0&&be(n,l),(o.get(c)??[]).filter(e=>l===void 0||z(n,c,e,l)===!0)}let N=n=>async(c,...l)=>{if(!m?.nested(c))return n(c,...l);let e=(o.get(c)??[]).map(x),r=F(),i=await n(c,...l),s=m.misplaced(c,e,o.get(c)??[]);if(s)throw r(),Object.assign(new Error(s.message),{code:s.code});return i},V={diagnostics:()=>null,async query(n,c=[]){return w.push({sql:n,params:c}),[]},async findUnique(){throw new Error("the fake database knows no table's declared unique keys \u2014 find the row with findMany, or test this against Postgres")},async page(){throw new Error("the fake database cannot reproduce Postgres' cursor ordering, collation or row-level security \u2014 test pagination against Postgres")},async search(n){throw new Error(`search(${n}): the fake database has neither embeddings nor full text \u2014 test search against Postgres`)},async findById(n,c){let l=(o.get(n)??[]).find(e=>e.id===c);return l?x(l):null},async findMany(n,c,l){let{limit:e,offset:r}=l??{};if(e!==void 0&&(!Number.isInteger(e)||e<0))throw new Error(`findMany(${n}): limit is a whole number, 0 or more (got ${String(e)})`);if(r!==void 0){if(!Number.isInteger(r)||r<0)throw new Error(`findMany(${n}): offset is a whole number, 0 or more (got ${String(r)})`);if(e===void 0)throw new Error(`findMany(${n}): offset comes with limit \u2014 an offset into an unbounded result is not a page`)}if(l?.with!==void 0&&Object.keys(l.with).length>0)throw new Error(`findMany(${n}): the fake database has no relations, so \`with\` cannot be read \u2014 seed and query the related table on its own, or test this against Postgres`);let i=E("findMany",n,c),s=l?.orderBy===void 0?[]:Array.isArray(l.orderBy)?l.orderBy:[l.orderBy];s.length>0&&(i=[...i].sort((h,b)=>{for(let y of s){let j=y.direction==="desc"?-1:1,$=h[y.column],R=b[y.column],I=$==null,S=R==null;if(I||S){if(I&&S)continue;let D=y.nulls===void 0?j===-1:y.nulls==="first";return(I?1:-1)*(D?-1:1)}let A=ye($,R)??(String($)<String(R)?-1:String($)>String(R)?1:0);if(A!==0)return A*j}return 0}));let a=e===void 0?i:i.slice(r??0,(r??0)+e),g=l?.select;return a.map(h=>g===void 0||g.length===0?x(h):Object.fromEntries(g.map(b=>[b,structuredClone(h[b])])))},async count(n,c={}){return E("count",n,c).length},async aggregate(n,c){let l=E("aggregate",n,c.where),e=c.groupBy??[],r=s=>{let a={},g=h=>s.map(b=>b[h]).filter(b=>b!=null);for(let h of c.sum??[]){let b=g(h);(a.sum??={})[h]=b.length===0?null:String(b.reduce((y,j)=>ge(y,j,1),"0"))}for(let h of c.avg??[]){let b=g(h),y=b.some(j=>typeof j=="number"&&!Number.isInteger(j));(a.avg??={})[h]=b.length===0?null:y?b.reduce((j,$)=>j+$,0)/b.length:Qe(v(b.reduce((j,$)=>ge(j,$,1),"0")),{unit:BigInt(b.length),scale:0})}for(let[h,b]of[["min",-1],["max",1]])for(let y of c[h]??[]){let j=g(y);(a[h]??={})[y]=j.length===0?null:j.reduce(($,R)=>(ye(R,$)??0)*b>0?R:$)}return c.count===!0?a.count=s.length:c.count!==void 0&&c.count!==!1&&(a.count=Object.fromEntries(Object.entries(c.count).map(([h,b])=>[h,s.filter(y=>z("aggregate",n,y,b)===!0).length]))),a};if(e.length===0)return r(l);let i=new Map;for(let s of l){let a=JSON.stringify(e.map(g=>s[g]));i.set(a,[...i.get(a)??[],s])}return[...i.values()].map(s=>({...r(s),...Object.fromEntries(e.map(a=>[a,s[0][a]]))}))},insert:N(async(n,c)=>T("insert",n,c)),insertMany:N(async(n,c,l)=>{if(Se(l),l?.onConflict?.length||l?.action!==void 0)throw new Error(`insertMany(${n}): the fake database knows no unique constraint to collide with \u2014 test onConflict against Postgres`);if(c.length===0)return l?.returning===!1?0:[];let e=Object.keys(c[0]);c.forEach((i,s)=>{let a=e.filter(h=>!(h in i)),g=Object.keys(i).filter(h=>!e.includes(h));if(a.length>0||g.length>0)throw new Error(`insertMany(${n}): row ${s} has not the first row's columns${a.length?` (missing ${a.join(", ")})`:""}${g.length?` (extra ${g.join(", ")})`:""} \u2014 write null for an empty one, or insert rows of another shape in a call of their own`)});let r=c.map(i=>T("insertMany",n,i));return l?.returning===!1?r.length:r}),put:N(async(n,c,l)=>{if(!l?.onConflict?.length)throw new Error(`put(${n}): onConflict names at least one column`);let e=C("put",n,c),r=O(n).find(i=>l.onConflict.every(s=>q(i[s],e[s])));if(!r)return T("put",n,c);for(let[i,s]of Object.entries(e))l.onConflict.includes(i)||(r[i]=s);return k(d,n,x(r)),x(r)}),update:N(async(n,c,l)=>{let e=o.get(n)??[],r=e.findIndex(i=>i.id===c);return r<0?(H("update",n,Object.keys(l),l),null):(e[r]={...e[r],...M("update",n,e[r],l)},k(d,n,x(e[r])),x(e[r]))}),updateMany:N(async(n,c,l,e)=>{Y("updateMany",c);let r=E("updateMany",n,c),i=O(n),s=[];for(let a of r){let g=i.indexOf(a);i[g]={...a,...M("updateMany",n,a,l)},k(d,n,x(i[g])),s.push(x(i[g]))}return r.length===0&&H("updateMany",n,Object.keys(l),l),e?.returning===!1?s.length:s}),async delete(n,c){let l=o.get(n)??[],e=l.findIndex(i=>i.id===c);if(e<0)return;let[r]=l.splice(e,1);k(p,n,c),k(f,n,r)},async deleteMany(n,c){Y("deleteMany",c);let l=E("deleteMany",n,c);o.set(n,(o.get(n)??[]).filter(e=>!l.includes(e)));for(let e of l)k(p,n,String(e.id)),k(f,n,e);return l.length},claim:N(async(n,c,l={})=>{let e=Object.keys(c);if(e.length===0)throw new Error(`claim(${n}): no unique field \u2014 claim takes a key; without one, insert(${n}, \u2026)`);H("claim",n,e,c);let r=(o.get(n)??[]).find(i=>e.every(s=>q(i[s],c[s])));return r?{inserted:!1,row:x(r)}:{inserted:!0,row:T("claim",n,{...c,...l})}}),async lockRows(n,c){if(c.length===0)return;let l=o.get(n)??[],e=[...new Set(c)].filter(r=>!l.some(i=>i.id===r));if(e.length>0&&l.length>0)throw new Error(`lockRows(${n}): no row with id ${e.join(", ")}`)},async lockRowsWhere(n,c,l){let e=l?.mode??"update";if(!["update","share","noKeyUpdate"].includes(e))throw new Error(`lockRowsWhere(${n}): mode is "update", "share" or "noKeyUpdate" (got "${String(e)}")`);Y("lockRowsWhere",c),E("lockRowsWhere",n,c)},async advisoryXactLock(){}};function U(n){let c=F(),l=[];try{for(let e of n.ops){let r=m?.nested(e.table)?(o.get(e.table)??[]).map(x):null,i=B(e,l),s=r===null?null:m?.misplaced(e.table,r,o.get(e.table)??[])??null;if(s)throw Object.assign(new Error(s.message),{code:s.code});l.push(i);let a=Ye(e.guard,i.rows.length);if(a)throw a}}catch(e){throw c(),e}return{results:l}}function B(n,c){let l=r=>Object.fromEntries(Object.entries(r??{}).map(([i,s])=>[i,qe(s,c)])),e=`transaction plan ${n.op}`;switch(n.op){case"insert":return we(T(e,n.table,l(n.values)));case"insertMany":{let r=(n.rows??[]).map(a=>l(a)),i=n.onConflict??[];if(n.action!==void 0&&i.length===0)throw new Error(`${e}(${n.table}): the fake database knows no unique key to collide with \u2014 name onConflict columns, or test this against Postgres`);let s=[];for(let a of r){let g=i.length>0?O(n.table).find(h=>i.every(b=>q(h[b],a[b]))):void 0;if(!(g&&n.action==="ignore")){if(g&&n.action==="update"){Object.assign(g,M(e,n.table,g,Object.fromEntries(Object.entries(a).filter(([h])=>!i.includes(h))))),k(d,n.table,x(g)),s.push(x(g));continue}s.push(T(e,n.table,a))}}return{rows:s,rows_affected:s.length}}case"upsert":{let r=l(n.values),i=n.onConflict??[];if(Object.keys(r).length===0||i.length===0)throw Object.assign(new Error(`put on ${n.table} needs columns and onConflict`),{error_code:"tx_bad_upsert"});let s=O(n.table).find(a=>i.every(g=>q(a[g],r[g])));return s?(Object.assign(s,M(e,n.table,s,Object.fromEntries(Object.entries(r).filter(([a])=>!i.includes(a))))),k(d,n.table,x(s)),we(x(s))):we(T(e,n.table,r))}case"update":{let r=l(n.set);if(Object.keys(r).length===0)throw new Error(`update ${n.table}: nothing to set`);let i=me(n.where,c);Y(e,i);let s=O(n.table),a=[];for(let g of E(e,n.table,i)){let h=s.indexOf(g);s[h]={...g,...M(e,n.table,g,r)},k(d,n.table,x(s[h])),a.push(x(s[h]))}return{rows:a,rows_affected:a.length}}case"delete":{let r=me(n.where,c);Y(e,r);let i=E(e,n.table,r);o.set(n.table,O(n.table).filter(s=>!i.includes(s)));for(let s of i)k(p,n.table,String(s.id)),k(f,n.table,s);return{rows:i.map(x),rows_affected:i.length}}case"select":{let r=E(e,n.table,me(n.where,c));return n.limit!==void 0&&(r=r.slice(0,n.limit)),{rows:r.map(x),rows_affected:r.length}}default:throw new Error(`unknown operation "${String(n.op)}" in a transaction plan`)}}let W={...V,async txPlan(n){return U(n)},async attempt(n){let c=F();try{return await n(V)}catch(l){throw c(),l}},async atomic(){throw new Error("the fake database cannot reproduce a transaction's isolation, COMMIT or retry \u2014 test $atomic against Postgres")}};return{...W,asService:()=>W,inserted:n=>(u.get(n)??[]).map(x),updated:n=>(d.get(n)??[]).map(x),deleted:n=>[...p.get(n)??[]],seed(n,c){o.set(n,c.map(x))},queries:w,...m===void 0?{}:{access:m}}}function pe(t){return new Map([...t].map(([o,u])=>[o,u.map(x)]))}function we(t){return{rows:[t],rows_affected:1}}function qe(t,o){if(!ue(t))return t;let u=o[t.$ref.op]?.rows[0];if(!u)throw Object.assign(new Error(`transaction plan: operation ${t.$ref.op} produced no row to reference`),{error_code:"tx_ref_unresolved"});return u[t.$ref.field]}function me(t,o){let u=d=>{if(ue(d)){let p=qe(d,o);if(p==null)throw Object.assign(new Error(`transaction plan: a filter's reference to operation ${d.$ref.op}'s "${d.$ref.field}" is NULL`),{error_code:"tx_ref_null"});return p}return Array.isArray(d)?d.map(u):d!==null&&typeof d=="object"&&!ee(d)&&!le(d)&&!ne(d)&&!(d instanceof Date)?Object.fromEntries(Object.entries(d).map(([p,f])=>[p,u(f)])):d};return u(t??{})}function Ye(t,o){return t?(t.kind==="one"?o===1:t.kind==="none"?o===0:t.kind==="atLeast"?o>=t.n:o<=t.n)?null:Object.assign(new Error(`transaction expectation failed: ${t.kind} (${o} row(s))`),{error_code:"tx_guard_failed",slot:t.slot}):null}export{Je as createFakeClient,Ue as typedDatabase};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "palgres",
3
- "version": "0.56.0",
3
+ "version": "0.58.0",
4
4
  "description": "Palgres: the typed Postgres layer of Palbase's DB machines — schema, migrations and queries.",
5
5
  "license": "SEE LICENSE IN LICENSE",
6
6
  "homepage": "https://palbase.studio",
@@ -42,6 +42,8 @@ export interface Before {
42
42
  schema: string;
43
43
  table: string;
44
44
  }[];
45
+ /** The database's roles, by name (its own, not the server's built-in ones): whether the visitor's is among them. */
46
+ roles?: string[];
45
47
  catalog: unknown;
46
48
  }
47
49
  /** What relationships are kept, by (type, relation, kind of subject), and which compiled schema is active. */
@@ -49,6 +51,11 @@ export interface Kept {
49
51
  active: string | null;
50
52
  /** The engine that compiled the schema in force (base.ts ENGINE); absent when none is, or read by an older reader. */
51
53
  engine?: string | null;
54
+ /**
55
+ * The relationships that hold, counted by what a schema would call them: `subject_type` is the kind of subject as
56
+ * a schema writes it (`user`, `user:*`, `public`, a type). One whose time has passed is not among them: nothing
57
+ * reads it, and it is in no schema's way.
58
+ */
52
59
  relationships: {
53
60
  object_type: string;
54
61
  relation: string;
@@ -2,8 +2,8 @@
2
2
  export declare const ACCESS = "access";
3
3
  /** Written on the schema: how a database's `access` is known to be Palbase's. */
4
4
  export declare const MARK = "palbase access";
5
- /** The engine's generation: a database compiled by another is compiled again. */
6
- export declare const ENGINE = "2";
5
+ /** The engine's generation: a database compiled by another is compiled again. (4: a type's objects nested in each other.) */
6
+ export declare const ENGINE = "4";
7
7
  /**
8
8
  * The triggers a type's table carries, by name: a row made, a row deleted, a row's key changed, the table emptied. A
9
9
  * table that lacks one, or has one off (or on for replicas alone), has not been watched. Each is a row's own, so
@@ -12,6 +12,12 @@ export declare const ENGINE = "2";
12
12
  * changes another row's key acts after access has followed this one.
13
13
  */
14
14
  export declare const TRIGGERS: readonly ['!access_fresh', '!access_forget', '!access_move', '!access_empty'];
15
+ /**
16
+ * The trigger a type's table carries when a permission of it is derived from itself through a column (a folder in a
17
+ * folder): it refuses a row put inside itself, or more levels deep than the type's depth. It decides nothing of a
18
+ * row's relationships, so it is no part of what watches a table (TRIGGERS), nor of the order those fire in.
19
+ */
20
+ export declare const NEST_TRIGGER = "!access_nest";
15
21
  /** The last of them in the order triggers of one event fire (their names', byte by byte). */
16
22
  export declare const LAST_TRIGGER: string;
17
23
  /**
@@ -24,8 +30,30 @@ export interface Roles {
24
30
  authenticated: string;
25
31
  /** The role the app's own work takes: it asks for anyone, and gives and takes relationships. */
26
32
  service: string;
33
+ /**
34
+ * The role a request takes when nobody has signed in: it holds what is the public's, and nothing else. A database
35
+ * need not have it — a schema that opens nothing to the public asks nothing of it.
36
+ */
37
+ visitor: string;
27
38
  }
28
39
  export declare const DEFAULT_ROLES: Roles;
40
+ /** The id a relationship kept for every signed-in user ('user', '*'), or for the public ('public', '*'), is written under. */
41
+ export declare const ANY_ID = "*";
42
+ /** A relationship that counts: it has no end, or its end is still to come (the statement's own moment). */
43
+ export declare const LIVE: (r: string) => string;
44
+ /** LIVE, for a statement that may meet relationships an earlier engine made: no end is kept there, and every row holds. */
45
+ export declare const LIVE_OF_ANY_ENGINE: (r: string) => string;
46
+ /**
47
+ * The kind of subject a kept relationship has, as a schema writes it: `user`, `user:*` (every signed-in user — kept
48
+ * under the id nobody has), `public`, or a type. What a schema keeps is compared with what the database holds by this.
49
+ */
50
+ export declare const KIND: (r: string) => string;
51
+ /**
52
+ * Until engine 3 "*" was an id like any other, and a relationship could be given to a user called that. Read by
53
+ * this engine it would be every signed-in user's — an object opened by a row nobody meant to open it with. The
54
+ * schema is not put in over such a row: it is taken first (the earlier engine's own revoke takes it).
55
+ */
56
+ export declare function starGuard(): string;
29
57
  /** An id as an integer, or null when its text is not one: at most 18 digits, so none overflows. */
30
58
  export declare const INT_TEXT = "^-?[0-9]{1,18}$";
31
59
  /** A uuid's hyphenated form, either case. */
@@ -45,5 +73,15 @@ export declare const REFUSED: {
45
73
  readonly notTaken: 'PA005';
46
74
  /** The role asks for itself alone: it cannot name another subject. */
47
75
  readonly notAllowed: 'PA006';
76
+ /** A relationship's end that is not still to come. */
77
+ readonly badTime: 'PA007';
78
+ /** A write that would put an object inside itself (a folder in a folder in itself). */
79
+ readonly cycle: 'PA008';
80
+ /** A write that would nest objects more levels deep than their type's depth. */
81
+ readonly tooDeep: 'PA009';
82
+ /** One parent more than an object nested by relationships may have (MAX_PARENTS). */
83
+ readonly tooManyParents: 'PA010';
48
84
  };
85
+ /** How many objects of its own type one object nested by relationships may be in (a team in teams). */
86
+ export declare const MAX_PARENTS = 32;
49
87
  export declare function baseStatements(roles?: Roles): string[];
@@ -27,6 +27,11 @@ export declare const MAX_PLANNING_KB: number;
27
27
  export declare const MAX_PLANNING_MS = 100;
28
28
  export interface CompileOptions {
29
29
  roles?: Partial<Roles>;
30
+ /**
31
+ * Whether the database has the visitor's role (Roles.visitor). A schema that opens a name to the public is asked
32
+ * by that role, and is refused where there is none: it would say "the public" and open nothing.
33
+ */
34
+ visitor?: boolean;
30
35
  /** false: the schema's `rows` rules make no policy (whoever compiles writes the tables' policies itself). */
31
36
  rows?: boolean;
32
37
  /** The names whose predicate (Compiled.predicates) the caller puts in a row policy of its own: what they read is opened to a request's role. */
@@ -88,12 +93,29 @@ export interface Compiled {
88
93
  */
89
94
  recheck: string[];
90
95
  tables: CompiledTable[];
91
- /** Every (type, name) a subject can hold, the view `access` shows it as, and the type of its `id` (as pg_type names it). */
96
+ /** The tables whose rows are kept a tree by NEST_TRIGGER (a folder in a folder), with what it is made with. */
97
+ nests: {
98
+ schema: string;
99
+ table: string;
100
+ args: string[];
101
+ }[];
102
+ /** The types nested by relationships (a team in teams), with the relation and how deep: what its grant holds them to. */
103
+ kept: {
104
+ type: string;
105
+ relation: string;
106
+ depth: number;
107
+ }[];
108
+ /**
109
+ * Every (type, name) a subject can hold, the view `access` shows it as, the type of its `id` (as pg_type names
110
+ * it), and whether a visitor can hold it (it is read through a relation the public holds): those alone are the
111
+ * visitor's role's to ask.
112
+ */
92
113
  names: {
93
114
  type: string;
94
115
  name: string;
95
116
  view: string;
96
117
  idType: string;
118
+ open: boolean;
97
119
  }[];
98
120
  /** The policies the schema's `rows` rules make, by table. */
99
121
  policies: {
@@ -1,4 +1,4 @@
1
- export type AccessErrorCode = 'syntax' | 'invalid_name' | 'duplicate' | 'unknown_name' | 'unknown_type' | 'not_a_holder' | 'not_an_object_relation' | 'needs_table' | 'cycle' | 'too_deep' | 'too_large' | 'not_supported' | 'unknown_table' | 'unknown_column' | 'key_not_supported' | 'type_mismatch' | 'forced_row_security' | 'not_palbase_access' | 'relationships_in_the_way';
1
+ export type AccessErrorCode = 'syntax' | 'invalid_name' | 'duplicate' | 'unknown_name' | 'unknown_type' | 'not_a_holder' | 'not_an_object_relation' | 'needs_table' | 'needs_role' | 'cycle' | 'too_deep' | 'too_large' | 'not_supported' | 'unknown_table' | 'unknown_column' | 'key_not_supported' | 'type_mismatch' | 'forced_row_security' | 'not_palbase_access' | 'relationships_in_the_way';
2
2
  export declare class AccessError extends Error {
3
3
  readonly code: AccessErrorCode;
4
4
  /** The line of the schema's text it is about, from 1; 0 when it is about no one line. */
@@ -1,10 +1,11 @@
1
1
  export { AccessError, type AccessErrorCode } from './errors.js';
2
2
  export { parse, type Condition, type Expr, type Literal, type RowCommand, type SchemaAst } from './text.js';
3
- export { validate, mangle, heldByUsers, objectTargets, MAX_DEPTH, USER, type Model, type Relation, type TypeModel } from './model.js';
3
+ export { validate, mangle, heldByUsers, heldByPublic, objectTargets, takesOpen, takesUsers, ANY, DEFAULT_NESTING, EVERY_USER, MAX_DEPTH, MAX_NESTING, PUBLIC, USER, type Model, type Nesting, type Relation, type Tree, type TypeModel } from './model.js';
4
4
  export { catalogFrom, catalogOf, catalogQuery, type Catalog, type ColumnFamily, type TableInfo } from './catalog.js';
5
- export { ACCESS, baseStatements, DEFAULT_ROLES, ENGINE, MARK, MAX_ID, REFUSED, TRIGGERS, type Roles } from './base.js';
5
+ export { ACCESS, baseStatements, DEFAULT_ROLES, ENGINE, KIND, LIVE_OF_ANY_ENGINE, MARK, MAX_ID, MAX_PARENTS, NEST_TRIGGER, REFUSED, starGuard, TRIGGERS, type Roles } from './base.js';
6
6
  export { compile, readColumns, MAX_SUBJECTS, type Compiled, type CompiledTable, type CompileOptions, type Guard } from './compile.js';
7
7
  export { apply, beforeQuery, dropCompiled, keptQuery, plan, unpoint, type ApplyOptions, type Before, type Kept, type Planned, type Run } from './apply.js';
8
- export { reference, type Reference } from './reference.js';
8
+ export { reference, type Asker, type Reference } from './reference.js';
9
9
  export { canonicalId, idOf, type Family, type Relationship, type TableShape, type Value, type World } from './world.js';
10
10
  export { runValidation, schemaPathOf, ValidationFileError, type ValidationFailure, type ValidationResult } from './validation.js';
11
+ export { edges, notThere, placed, tooManyParents, treeProblem, type Misplaced } from './tree.js';
@@ -1,7 +1,14 @@
1
- import type { ColumnRelationAst, Condition, PermissionAst, RelationAst, RowCommand, SchemaAst, StoredRelationAst } from './text.js';
1
+ import { EVERY_USER, PUBLIC } from './text.js';
2
+ import type { ColumnRelationAst, Condition, PermissionAst, RelationAst, RowCommand, RowRelationAst, SchemaAst, StoredRelationAst } from './text.js';
3
+ export { EVERY_USER, PUBLIC };
2
4
  export declare const USER = "user";
5
+ /** The id a relationship kept for every signed-in user, or for the public, is written under. No subject is called this. */
6
+ export declare const ANY = "*";
3
7
  /** How long a chain of permissions derived from one another may be. A schema past it is refused when declared. */
4
8
  export declare const MAX_DEPTH = 16;
9
+ /** How many levels a type's objects may be nested in one another (a folder in a folder): when the schema says none, and at most. */
10
+ export declare const DEFAULT_NESTING = 16;
11
+ export declare const MAX_NESTING = 32;
5
12
  export declare const MAX_TYPES = 200;
6
13
  export declare const MAX_NAMES = 100;
7
14
  export declare const MAX_EXPR_NODES = 200;
@@ -51,6 +58,7 @@ export interface TableRef {
51
58
  }
52
59
  export type StoredRelation = StoredRelationAst;
53
60
  export type ColumnRelation = ColumnRelationAst;
61
+ export type RowRelation = RowRelationAst;
54
62
  export type Relation = RelationAst;
55
63
  export type Permission = PermissionAst;
56
64
  export interface RowsRule {
@@ -60,13 +68,32 @@ export interface RowsRule {
60
68
  export interface TypeModel {
61
69
  name: string;
62
70
  table: TableRef | null;
71
+ /** How many levels its objects may be nested in one another (`depth`; DEFAULT_NESTING when it is not said). */
72
+ depth: number;
63
73
  relations: Map<string, Relation>;
64
74
  permissions: Map<string, Permission>;
65
75
  rows: RowsRule[];
66
76
  }
77
+ /** A permission derived from itself through a relation to its own type: the relation, and how many levels deep. */
78
+ export interface Nesting {
79
+ type: string;
80
+ name: string;
81
+ relation: string;
82
+ depth: number;
83
+ }
84
+ /** A relation of a type to its own type that a permission is derived from itself through: its objects make a tree. */
85
+ export interface Tree {
86
+ type: string;
87
+ relation: string;
88
+ depth: number;
89
+ }
67
90
  export interface Model {
68
91
  /** In the order the schema declares them. */
69
92
  types: Map<string, TypeModel>;
93
+ /** The permission (type, name) is derived from itself through a relation to its own type: which, and how deep. */
94
+ nesting(type: string, name: string): Nesting | null;
95
+ /** Each relation some permission of its type is derived from itself through, once: the objects it leads to make a tree. */
96
+ trees: Tree[];
70
97
  /** Every (type, name), each after everything its meaning reads: the order to build them in. */
71
98
  order: {
72
99
  type: string;
@@ -74,6 +101,8 @@ export interface Model {
74
101
  }[];
75
102
  /** How many lookups the database plans for a (type, name) (MAX_PLANNED). */
76
103
  planned(type: string, name: string): number;
104
+ /** Whether somebody who has not signed in can hold a (type, name): it is read through a relation the public holds. */
105
+ open(type: string, name: string): boolean;
77
106
  }
78
107
  /** A name as an SQL identifier's part: the one dot a name may carry becomes two underscores, which no name has. */
79
108
  export declare const mangle: (name: string) => string;
@@ -81,6 +110,18 @@ export declare const mangle: (name: string) => string;
81
110
  export declare const heldByUsers: (r: Relation) => boolean;
82
111
  /** The types a relation leads to. */
83
112
  export declare const objectTargets: (r: Relation) => string[];
113
+ /** Whether a stored relation is given to one subject by id (`user`). */
114
+ export declare const takesUsers: (r: Relation) => boolean;
115
+ /** The open subjects a stored relation takes: every signed-in user, the public. */
116
+ /**
117
+ * How many lookups a relation is, held directly: one — and, for a kept relation, one for each way it can be held:
118
+ * by a user's own id, by every signed-in user, by the public (each is a lookup of its own in what is compiled).
119
+ * One read from a column or from the row counts its condition's terms with it.
120
+ */
121
+ export declare const lookupsOf: (r: Relation | undefined) => number;
122
+ export declare const takesOpen: (r: Relation) => ("public" | "user:*")[];
123
+ /** Whether a relation holds for somebody who has not signed in: kept for the public, or read from the row for it. */
124
+ export declare const heldByPublic: (r: Relation) => boolean;
84
125
  /** The columns of the type's table a condition reads. */
85
126
  export declare function columnsOf(c: Condition | null): string[];
86
127
  /** Checks a schema read from text and answers the model. Throws AccessError naming what does not hold together. */
@@ -1,12 +1,16 @@
1
1
  import type { Model } from './model.js';
2
2
  import type { World } from './world.js';
3
+ /** Who asks: a subject's id, '*' (somebody signed in, nothing else known of them), or null (a visitor). */
4
+ export type Asker = string | null;
3
5
  export interface Reference {
4
6
  /** holds(subject, type, id, name). */
5
- check(subject: string, type: string, id: string, name: string): boolean;
7
+ check(subject: Asker, type: string, id: string, name: string): boolean;
6
8
  /** The ids (as the key's type writes them — canonical) of the objects of `type` the subject holds `name` on, sorted. */
7
- objects(subject: string, type: string, name: string): string[];
8
- /** The subjects that hold `name` on (type, id), sorted. */
9
+ objects(subject: Asker, type: string, name: string): string[];
10
+ /** The subjects that hold `name` on (type, id), sorted: each one named by a relationship — never '*'. */
9
11
  subjects(type: string, id: string, name: string): string[];
12
+ /** How wide `name` is open on (type, id): to everyone, to every signed-in user, or to nobody but those it names. */
13
+ open(type: string, id: string, name: string): 'public' | 'users' | 'visitors' | null;
10
14
  }
11
15
  /** Answers a schema's three questions from the facts of one world. */
12
16
  export declare function reference(model: Model, world: World): Reference;
@@ -45,11 +45,15 @@ export type Expr = {
45
45
  base: Expr;
46
46
  minus: Expr;
47
47
  };
48
+ /** Every signed-in user, as a relation's subject: whoever asks holds it, as long as somebody is signed in. */
49
+ export declare const EVERY_USER = "user:*";
50
+ /** Everyone, signed in or not, as a relation's subject. */
51
+ export declare const PUBLIC = "public";
48
52
  /** A relationship kept in Palbase's table: given and taken through the API. */
49
53
  export interface StoredRelationAst {
50
54
  kind: 'stored';
51
55
  name: string;
52
- /** 'user', or the names of types. */
56
+ /** 'user', 'user:*', 'public', or the names of types. */
53
57
  subjects: string[];
54
58
  line: number;
55
59
  }
@@ -63,7 +67,15 @@ export interface ColumnRelationAst {
63
67
  where: Condition | null;
64
68
  line: number;
65
69
  }
66
- export type RelationAst = StoredRelationAst | ColumnRelationAst;
70
+ /** A relationship read from the row itself: every signed-in user, or the public, holds it where the condition is true. */
71
+ export interface RowRelationAst {
72
+ kind: 'row';
73
+ name: string;
74
+ subject: typeof EVERY_USER | typeof PUBLIC;
75
+ where: Condition;
76
+ line: number;
77
+ }
78
+ export type RelationAst = StoredRelationAst | ColumnRelationAst | RowRelationAst;
67
79
  export interface PermissionAst {
68
80
  name: string;
69
81
  expr: Expr;
@@ -86,6 +98,11 @@ export interface TableAst {
86
98
  export interface TypeAst {
87
99
  name: string;
88
100
  table: TableAst | null;
101
+ /** `depth N`: how many levels its objects may be nested in one another; null when it is not said. */
102
+ depth: {
103
+ levels: number;
104
+ line: number;
105
+ } | null;
89
106
  relations: RelationAst[];
90
107
  permissions: PermissionAst[];
91
108
  rows: RowsAst[];
@@ -0,0 +1,22 @@
1
+ import { REFUSED } from './base.js';
2
+ import type { Model, Tree } from './model.js';
3
+ import { type Relationship, type World } from './world.js';
4
+ /** What is wrong with where an object would be: its code (the database's SQLSTATE) and what the database says. */
5
+ export interface Misplaced {
6
+ code: typeof REFUSED.cycle | typeof REFUSED.tooDeep | typeof REFUSED.tooManyParents | typeof REFUSED.noObject;
7
+ message: string;
8
+ }
9
+ /** A row put in one that is not there (nested by a column): refused, as a foreign key would. */
10
+ export declare const notThere: (type: string, id: string, parent: string) => Misplaced;
11
+ /**
12
+ * Where `id` would be, put in `parent` (or in none), in a tree whose objects' parents `parentsOf` says and whose
13
+ * objects' children `childrenOf` says, as the write would leave them: inside itself, or too deep — or fine (null).
14
+ * Up a level at a time, every way there is (each object once a level); down along the longest way.
15
+ */
16
+ export declare function placed(type: string, depth: number, id: string, parent: string | null, parentsOf: (id: string) => string[], childrenOf: (id: string) => string[]): Misplaced | null;
17
+ /** Whether an object nested by relationships is in as many others already, `parent` aside, as one may be. */
18
+ export declare function tooManyParents(tree: Tree, relationships: Relationship[], id: string, parent: string, now?: number): Misplaced | null;
19
+ /** A tree's edges as they are in a world: child → parents, by the column of its type's table or by its relationships. */
20
+ export declare function edges(model: Model, world: World, tree: Tree): Map<string, string[]>;
21
+ /** What is wrong with a world's tree as the database checks it when a schema is put in: the first object that is not where it may be. */
22
+ export declare function treeProblem(model: Model, world: World, tree: Tree): Misplaced | null;
@@ -16,13 +16,18 @@ export interface TableShape {
16
16
  }
17
17
  /** A column's value. An integer is a number or a bigint; a uuid and a text are strings. */
18
18
  export type Value = string | number | bigint | boolean | null;
19
- /** One stored relationship: `subjectType` is 'user' or a type's name. */
19
+ /**
20
+ * One stored relationship: `subjectType` is 'user' or a type's name, with the subject's or the object's id — or it
21
+ * names nobody in particular: ('user', '*') is every signed-in user, ('public', '*') is everyone.
22
+ */
20
23
  export interface Relationship {
21
24
  objectType: string;
22
25
  objectId: string;
23
26
  relation: string;
24
27
  subjectType: string;
25
28
  subjectId: string;
29
+ /** The moment it stops counting, in milliseconds since the epoch; absent or null: it does not end. */
30
+ expiresAt?: number | null;
26
31
  }
27
32
  export interface World {
28
33
  /** By type name, for each type that names a table. */
@@ -31,6 +36,8 @@ export interface World {
31
36
  rows: Record<string, Value>[];
32
37
  }>;
33
38
  relationships: Relationship[];
39
+ /** The moment the questions are asked at (milliseconds since the epoch); absent: now. */
40
+ now?: number;
34
41
  }
35
42
  /**
36
43
  * An id as its type writes it, or null when the text is no value of that type: an integer's digits without a sign's
@@ -33,10 +33,24 @@ export interface RecordedAccess {
33
33
  }[];
34
34
  /** The relations whose relationships are kept, each with the kinds of subject it takes: type, relation, subject. */
35
35
  stored: [string, string, string][];
36
+ /** The tables whose rows are kept a tree, with what their trigger is made with (none: compiled before nesting). */
37
+ nests?: {
38
+ schema: string;
39
+ table: string;
40
+ args: string[];
41
+ }[];
42
+ /** The types nested by relationships its grant holds to a tree, and how deep (none: compiled before nesting). */
43
+ kept?: {
44
+ type: string;
45
+ relation: string;
46
+ depth: number;
47
+ }[];
36
48
  }
37
49
  export interface AccessRoles {
38
50
  authenticated: string;
39
51
  service: string;
52
+ /** The role a request takes when nobody has signed in (anon, when left out): what is the public's is its to ask. */
53
+ visitor?: string;
40
54
  }
41
55
  /**
42
56
  * The model's access schema, compiled against the model's own tables; null when it has none. Throws AccessError when
@@ -49,6 +63,14 @@ export declare function compileAccess(schema: Schema, roles: AccessRoles, aliase
49
63
  /** The digest a model's access schema compiles to: what the model carries, so that a compiler that writes it otherwise is another version. */
50
64
  export declare function accessDigest(schema: Omit<Schema, 'access'>, text: string, roles: AccessRoles): string;
51
65
  export declare function recordAccess(c: Compiled, text: string): RecordedAccess;
66
+ /**
67
+ * The names a policy reads that a visitor cannot hold on a row of the table (nothing can open them to the public):
68
+ * none, when the policy can be the visitor's role's too. Null when it cannot be said — the table is no type's.
69
+ */
70
+ export declare function closedToVisitors(texts: (string | undefined)[], table: {
71
+ schema: string;
72
+ name: string;
73
+ }, compiled: Pick<Compiled, 'tables' | 'names'> | null): string[] | null;
52
74
  /**
53
75
  * A policy's text with each name it reads replaced by that name's predicate on the table's rows. Answers what is
54
76
  * wrong instead when the table is no type's, or the type has no such name.