palgres 0.54.0 → 0.56.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/chunks/JPYKRUNF.js +5 -0
- package/dist/chunks/LQHZIV3S.js +2 -0
- package/dist/chunks/YTA5WUZJ.js +309 -0
- package/dist/dsl.js +2 -2
- package/dist/index.js +2 -2
- package/dist/testing.js +2 -2
- package/package.json +1 -1
- package/types/access/src/apply.d.ts +2 -0
- package/types/palgres/src/query/access.d.ts +30 -1
- package/types/palgres/src/query/surface.d.ts +2 -1
- package/types/palgres/src/testing/access.d.ts +17 -0
- package/types/palgres/src/testing/fake.d.ts +13 -1
- package/types/palgres/src/testing/index.d.ts +2 -1
- package/dist/chunks/DMGBXJWT.js +0 -309
- package/dist/chunks/MMDAYJKI.js +0 -2
- package/dist/chunks/Q7U5AW6L.js +0 -5
package/dist/testing.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palgres 0.
|
|
2
|
-
import{P as U,Q as fn,R as Y,V as Z,W as V,X as z,Y as dn,_ as P,ga as _,la as wn,ma as $n,n as cn,p as ln}from"./chunks/Q7U5AW6L.js";import"./chunks/DMGBXJWT.js";import{randomUUID as Rn}from"node:crypto";var On=/^\d{4}-\d{2}-\d{2}([T ]\d{2}:\d{2}(:\d{2}(\.\d+)?)?)?(Z|[+-]\d{2}(:?\d{2})?)?$/,bn=/^([+-]?)(\d*)(?:\.(\d*))?$/;function q(e){if(e instanceof Date)return e.getTime();if(typeof e=="string"&&On.test(e)){let t=Date.parse(e);return Number.isNaN(t)?null:t}return null}function B(e){if(typeof e=="number")return Number.isFinite(e)?B(String(e)):null;if(typeof e!="string"||/e/i.test(e))return null;let t=bn.exec(e.trim());if(t===null||t[2]===""&&(t[3]??"")==="")return null;let a=t[3]??"";return{unit:BigInt(`${t[1]==="-"?"-":""}${t[2]===""?"0":t[2]}${a}`),scale:a.length}}function K(e,t){return e.unit*10n**BigInt(t-e.scale)}function tn(e,t){if(e==null||t===null||t===void 0)return null;let a=q(e),c=q(t);if(a!==null&&c!==null)return Math.sign(a-c);let w=B(e),f=B(t);if(w!==null&&f!==null){let d=Math.max(w.scale,f.scale),h=K(w,d)-K(f,d);return h===0n?0:h<0n?-1:1}return typeof e==typeof t&&(typeof e=="string"||typeof e=="boolean"||typeof e=="number")?e<t?-1:e>t?1:0:null}function N(e,t){return e==null||t===null||t===void 0?!1:e instanceof Date||t instanceof Date?q(e)!==null&&q(e)===q(t):Array.isArray(e)&&Array.isArray(t)?e.length===t.length&&e.every((a,c)=>N(a,t[c])):e===t}function H(e){let t=((e?.days??0)*86400+(e?.hours??0)*3600+(e?.minutes??0)*60+(e?.seconds??0))*1e3;return new Date(Date.now()-t).toISOString()}function v(e,t,a){if(e==null)return null;if(typeof e=="number"&&typeof t=="number")return e+a*t;let c=B(e),w=B(t);if(c===null||w===null)throw new Error(`increment()/decrement() on a value that is not a number (${JSON.stringify(e)}): Postgres refuses it ("operator does not exist")`);let f=Math.max(c.scale,w.scale),d=K(c,f)+BigInt(a)*K(w,f);if(f===0)return typeof e=="number"?Number(d):d.toString();let h=d<0n,R=(h?-d:d).toString().padStart(f+1,"0"),k=`${h?"-":""}${R.slice(0,-f)}.${R.slice(-f)}`;return typeof e=="number"?Number(k):k}function kn(e,t){let a=A=>{let C=(A.unit<0n?-A.unit:A.unit).toString().padStart(A.scale+1,"0"),J=C.slice(0,C.length-A.scale),n=C.slice(C.length-A.scale),r=J.padStart(Math.ceil(J.length/4)*4,"0").match(/.{4}/g)??[],s=n.padEnd(Math.ceil(n.length/4)*4,"0").match(/.{4}/g)??[],i=[...r.map((u,l)=>[r.length-1-l,Number(u)]),...s.map((u,l)=>[-1-l,Number(u)])].find(([,u])=>u!==0);return i?[i[0],i[1]]:[0,0]},[c,w]=a(e),[f,d]=a(t),h=c-f-(w<=d?1:0),R=Math.min(Math.max(16-h*4,e.scale,t.scale,0),1e3),k=e.unit*10n**BigInt(R+t.scale),E=t.unit*10n**BigInt(e.scale),T=k/E,x=k%E;2n*(x<0n?-x:x)>=(E<0n?-E:E)&&(T+=k<0n!=E<0n?-1n:1n);let I=T<0n,W=(I?-T:T).toString().padStart(R+1,"0");return`${I?"-":""}${R===0?W:`${W.slice(0,-R)}.${W.slice(-R)}`}`}var $=e=>structuredClone(e);function rn(e,t,a){if(fn(a))throw new Error(`${e}(${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(!(a===null||typeof a!="object"))for(let[c,w]of Object.entries(a))if(c==="OR"||c==="AND")for(let f of Array.isArray(w)?w:[])rn(e,t,f);else c==="NOT"&&rn(e,t,w)}function D(e,t,a){return cn(new ln({fields:[{field:t,message:a}]},`${e}: ${t} ${a}`))}function on(e,t,a="where"){for(let[c,w]of Object.entries(t))if(c==="OR"||c==="AND"){let f=w;if(c==="AND"&&f.length===0)throw D(e,`${a}.AND`,"is an empty list \u2014 no condition at all. Leave it out, or name a condition in it.");f.forEach((d,h)=>{if(Object.keys(d).length===0)throw D(e,`${a}.${c}[${h}]`,"holds no condition \u2014 a branch that matches every row. Name a condition in it, or leave it out.");on(e,d,`${a}.${c}[${h}]`)})}else if(c==="NOT"){if(Array.isArray(w))throw D(e,`${a}.NOT`,"is a list \u2014 NOT takes one filter object. For several conditions, NOT: { AND: [...] } or NOT: { OR: [...] }.");if(Object.keys(w).length===0)throw D(e,`${a}.NOT`,"holds no condition \u2014 NOT of nothing is not a filter. Name the condition to exclude.");on(e,w,`${a}.NOT`)}else if(c==="has"&&Object.keys(w??{}).length===0)throw D(e,`${a}.has`,"names no relation \u2014 no condition. Name one: has: { <relation>: { \u2026 } }.")}function F(e,t){if(Object.keys(t).length===0)throw D(e,"where",`holds no condition, so ${e} would reach EVERY row of the table. Name a condition.`)}function sn(e){let t=!1;for(let a of e){if(a===!1)return!1;a===null&&(t=!0)}return t?null:!0}function mn(e){let t=!1;for(let a of e){if(a===!0)return!0;a===null&&(t=!0)}return t?null:!1}var j=e=>e==null;function L(e,t,a,c){return sn(Object.entries(c).map(([w,f])=>{if(w==="OR")return mn(f.map(d=>L(e,t,a,d)));if(w==="AND")return sn(f.map(d=>L(e,t,a,d)));if(w==="NOT"){let d=L(e,t,a,f);return d===null?null:!d}if(w==="has")throw new Error(`${e}(${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 xn(e,t,a,w,f)}))}var gn=["neq","gt","gte","lt","lte"];function Q(e,t){return j(e)||j(t)?null:N(e,t)}function xn(e,t,a,c,w){let f=a[c];return w===null?j(f):U(w)?Q(f,a[w.$col]):V(w)?Q(f,H(_(w)?.minus)):typeof w=="object"&&!Array.isArray(w)&&!(w instanceof Date)?sn(Object.entries(w).map(([d,h])=>{if(V(h)){if(!gn.includes(d))throw new Error(`${e}(${t}): where.${c}.${d} cannot take now()`);return G(d,f,H(_(h)?.minus))}if(Z(h))throw new Error(`${e}(${t}): where.${c}.${d} was given increment()/decrement() \u2014 a write, not a value to compare with`);if(U(h)){if(!gn.includes(d))throw new Error(`${e}(${t}): where.${c}.${d} cannot take col()`);return G(d,f,a[h.$col])}switch(d){case"in":{if(!Array.isArray(h))throw new Error(`${e}(${t}): where.${c}.in is a list`);return mn(h.map(R=>Q(f,R)))}case"neq":return h===null?!j(f):G(d,f,h);case"gt":case"gte":case"lt":case"lte":return G(d,f,h);case"isNull":if(typeof h!="boolean")throw new Error(`${e}(${t}): where.${c}.isNull is true or false`);return h?j(f):!j(f);case"overlaps":if(!Array.isArray(h))throw new Error(`${e}(${t}): where.${c}.overlaps is a list`);if(f!=null&&!Array.isArray(f))throw new Error(`${e}(${t}): where.${c}: "overlaps" is an array column's operator`);return j(f)?null:h.some(R=>f.some(k=>N(R,k)));case"contains":case"icontains":case"startsWith":case"endsWith":{if(d==="contains"&&Array.isArray(h))return j(f)?null:Array.isArray(f)&&h.every(R=>f.some(k=>N(R,k)));if(typeof h!="string")throw new Error(`${e}(${t}): where.${c}.${d} is text`);return j(f)?null:typeof f!="string"?!1:d==="contains"?f.includes(h):d==="icontains"?f.toLowerCase().includes(h.toLowerCase()):d==="startsWith"?f.startsWith(h):f.endsWith(h)}default:throw new Error(`${e}(${t}): where.${c} has no operator "${d}"`)}})):Q(f,w)}function G(e,t,a){if(j(t)||j(a))return null;if(e==="neq")return!N(t,a);let c=tn(t,a);return c===null?!1:e==="gt"?c>0:e==="gte"?c>=0:e==="lt"?c<0:c<=0}function En(){let e=new Map,t=new Map,a=new Map,c=new Map,w=[],f=n=>{let r=e.get(n);return r||e.set(n,r=[]),r},d=(n,r,s)=>{let o=n.get(r);o?o.push(s):n.set(r,[s])},h=n=>n.id===void 0?{id:Rn(),...n}:{...n},R=()=>{let n={store:new Map([...e].map(([r,s])=>[r,s.map($)])),inserted:hn(t),updated:hn(a),deleted:new Map([...c].map(([r,s])=>[r,[...s]]))};return()=>{e=n.store,t=n.inserted,a=n.updated,c=n.deleted}};function k(n,r,s){let o={};for(let[i,u]of Object.entries(s)){let l=_(u);if(l!==null&&l.fn==="now")o[i]=H(l.minus);else{if(l!==null)throw new Error(`${n}(${r}): "${i}" was given ${l.fn==="inc"?"increment()":"decrement()"} \u2014 the row does not exist yet, so there is no current value to change`);o[i]=u}}return P(n,r,Object.keys(o),o),z(n,r,Object.keys(o),o),o}function E(n,r,s,o){P(n,r,Object.keys(o),o);let i={};for(let[u,l]of Object.entries(o)){let g=_(l);g!==null&&g.fn==="now"?i[u]=H(g.minus):g!==null?i[u]=v(s[u],g.by,g.fn==="inc"?1:-1):i[u]=l}return z(n,r,Object.keys(i),i),i}function T(n,r,s){let o=h(k(n,r,s));return f(r).push(o),d(t,r,$(o)),$(o)}function x(n,r,s){return dn(n,r,s),rn(n,r,s),s!==void 0&&on(n,s),(e.get(r)??[]).filter(o=>s===void 0||L(n,r,o,s)===!0)}let I={diagnostics:()=>null,async query(n,r=[]){return w.push({sql:n,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(n){throw new Error(`search(${n}): the fake database has neither embeddings nor full text \u2014 test search against Postgres`)},async findById(n,r){let s=(e.get(n)??[]).find(o=>o.id===r);return s?$(s):null},async findMany(n,r,s){let{limit:o,offset:i}=s??{};if(o!==void 0&&(!Number.isInteger(o)||o<0))throw new Error(`findMany(${n}): limit is a whole number, 0 or more (got ${String(o)})`);if(i!==void 0){if(!Number.isInteger(i)||i<0)throw new Error(`findMany(${n}): offset is a whole number, 0 or more (got ${String(i)})`);if(o===void 0)throw new Error(`findMany(${n}): 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(${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 u=x("findMany",n,r),l=s?.orderBy===void 0?[]:Array.isArray(s.orderBy)?s.orderBy:[s.orderBy];l.length>0&&(u=[...u].sort((y,p)=>{for(let O of l){let b=O.direction==="desc"?-1:1,M=y[O.column],S=p[O.column],X=M==null,an=S==null;if(X||an){if(X&&an)continue;let pn=O.nulls===void 0?b===-1:O.nulls==="first";return(X?1:-1)*(pn?-1:1)}let un=tn(M,S)??(String(M)<String(S)?-1:String(M)>String(S)?1:0);if(un!==0)return un*b}return 0}));let g=o===void 0?u:u.slice(i??0,(i??0)+o),m=s?.select;return g.map(y=>m===void 0||m.length===0?$(y):Object.fromEntries(m.map(p=>[p,structuredClone(y[p])])))},async count(n,r={}){return x("count",n,r).length},async aggregate(n,r){let s=x("aggregate",n,r.where),o=r.groupBy??[],i=l=>{let g={},m=y=>l.map(p=>p[y]).filter(p=>p!=null);for(let y of r.sum??[]){let p=m(y);(g.sum??={})[y]=p.length===0?null:String(p.reduce((O,b)=>v(O,b,1),"0"))}for(let y of r.avg??[]){let p=m(y),O=p.some(b=>typeof b=="number"&&!Number.isInteger(b));(g.avg??={})[y]=p.length===0?null:O?p.reduce((b,M)=>b+M,0)/p.length:kn(B(p.reduce((b,M)=>v(b,M,1),"0")),{unit:BigInt(p.length),scale:0})}for(let[y,p]of[["min",-1],["max",1]])for(let O of r[y]??[]){let b=m(O);(g[y]??={})[O]=b.length===0?null:b.reduce((M,S)=>(tn(S,M)??0)*p>0?S:M)}return r.count===!0?g.count=l.length:r.count!==void 0&&r.count!==!1&&(g.count=Object.fromEntries(Object.entries(r.count).map(([y,p])=>[y,l.filter(O=>L("aggregate",n,O,p)===!0).length]))),g};if(o.length===0)return i(s);let u=new Map;for(let l of s){let g=JSON.stringify(o.map(m=>l[m]));u.set(g,[...u.get(g)??[],l])}return[...u.values()].map(l=>({...i(l),...Object.fromEntries(o.map(g=>[g,l[0][g]]))}))},async insert(n,r){return T("insert",n,r)},insertMany:(async(n,r,s)=>{if(wn(s),s?.onConflict?.length||s?.action!==void 0)throw new Error(`insertMany(${n}): 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,l)=>{let g=o.filter(y=>!(y in u)),m=Object.keys(u).filter(y=>!o.includes(y));if(g.length>0||m.length>0)throw new Error(`insertMany(${n}): row ${l} has not the first row's columns${g.length?` (missing ${g.join(", ")})`:""}${m.length?` (extra ${m.join(", ")})`:""} \u2014 write null for an empty one, or insert rows of another shape in a call of their own`)});let i=r.map(u=>T("insertMany",n,u));return s?.returning===!1?i.length:i}),async put(n,r,s){if(!s?.onConflict?.length)throw new Error(`put(${n}): onConflict names at least one column`);let o=k("put",n,r),i=f(n).find(u=>s.onConflict.every(l=>N(u[l],o[l])));if(!i)return T("put",n,r);for(let[u,l]of Object.entries(o))s.onConflict.includes(u)||(i[u]=l);return d(a,n,$(i)),$(i)},async update(n,r,s){let o=e.get(n)??[],i=o.findIndex(u=>u.id===r);return i<0?(P("update",n,Object.keys(s),s),null):(o[i]={...o[i],...E("update",n,o[i],s)},d(a,n,$(o[i])),$(o[i]))},async updateMany(n,r,s,o){F("updateMany",r);let i=x("updateMany",n,r),u=f(n),l=[];for(let g of i){let m=u.indexOf(g);u[m]={...g,...E("updateMany",n,g,s)},d(a,n,$(u[m])),l.push($(u[m]))}return i.length===0&&P("updateMany",n,Object.keys(s),s),o?.returning===!1?l.length:l},async delete(n,r){let s=e.get(n)??[],o=s.findIndex(i=>i.id===r);o<0||(s.splice(o,1),d(c,n,r))},async deleteMany(n,r){F("deleteMany",r);let s=x("deleteMany",n,r);e.set(n,(e.get(n)??[]).filter(o=>!s.includes(o)));for(let o of s)d(c,n,String(o.id));return s.length},async claim(n,r,s={}){let o=Object.keys(r);if(o.length===0)throw new Error(`claim(${n}): no unique field \u2014 claim takes a key; without one, insert(${n}, \u2026)`);P("claim",n,o,r);let i=(e.get(n)??[]).find(u=>o.every(l=>N(u[l],r[l])));return i?{inserted:!1,row:$(i)}:{inserted:!0,row:T("claim",n,{...r,...s})}},async lockRows(n,r){if(r.length===0)return;let s=e.get(n)??[],o=[...new Set(r)].filter(i=>!s.some(u=>u.id===i));if(o.length>0&&s.length>0)throw new Error(`lockRows(${n}): no row with id ${o.join(", ")}`)},async lockRowsWhere(n,r,s){let o=s?.mode??"update";if(!["update","share","noKeyUpdate"].includes(o))throw new Error(`lockRowsWhere(${n}): mode is "update", "share" or "noKeyUpdate" (got "${String(o)}")`);F("lockRowsWhere",r),x("lockRowsWhere",n,r)},async advisoryXactLock(){}};function W(n){let r=R(),s=[];try{for(let o of n.ops){let i=A(o,s);s.push(i);let u=Tn(o.guard,i.rows.length);if(u)throw u}}catch(o){throw r(),o}return{results:s}}function A(n,r){let s=i=>Object.fromEntries(Object.entries(i??{}).map(([u,l])=>[u,yn(l,r)])),o=`transaction plan ${n.op}`;switch(n.op){case"insert":return nn(T(o,n.table,s(n.values)));case"insertMany":{let i=(n.rows??[]).map(g=>s(g)),u=n.onConflict??[];if(n.action!==void 0&&u.length===0)throw new Error(`${o}(${n.table}): the fake database knows no unique key to collide with \u2014 name onConflict columns, or test this against Postgres`);let l=[];for(let g of i){let m=u.length>0?f(n.table).find(y=>u.every(p=>N(y[p],g[p]))):void 0;if(!(m&&n.action==="ignore")){if(m&&n.action==="update"){Object.assign(m,E(o,n.table,m,Object.fromEntries(Object.entries(g).filter(([y])=>!u.includes(y))))),d(a,n.table,$(m)),l.push($(m));continue}l.push(T(o,n.table,g))}}return{rows:l,rows_affected:l.length}}case"upsert":{let i=s(n.values),u=n.onConflict??[];if(Object.keys(i).length===0||u.length===0)throw Object.assign(new Error(`put on ${n.table} needs columns and onConflict`),{error_code:"tx_bad_upsert"});let l=f(n.table).find(g=>u.every(m=>N(g[m],i[m])));return l?(Object.assign(l,E(o,n.table,l,Object.fromEntries(Object.entries(i).filter(([g])=>!u.includes(g))))),d(a,n.table,$(l)),nn($(l))):nn(T(o,n.table,i))}case"update":{let i=s(n.set);if(Object.keys(i).length===0)throw new Error(`update ${n.table}: nothing to set`);let u=en(n.where,r);F(o,u);let l=f(n.table),g=[];for(let m of x(o,n.table,u)){let y=l.indexOf(m);l[y]={...m,...E(o,n.table,m,i)},d(a,n.table,$(l[y])),g.push($(l[y]))}return{rows:g,rows_affected:g.length}}case"delete":{let i=en(n.where,r);F(o,i);let u=x(o,n.table,i);e.set(n.table,f(n.table).filter(l=>!u.includes(l)));for(let l of u)d(c,n.table,String(l.id));return{rows:u.map($),rows_affected:u.length}}case"select":{let i=x(o,n.table,en(n.where,r));return n.limit!==void 0&&(i=i.slice(0,n.limit)),{rows:i.map($),rows_affected:i.length}}default:throw new Error(`unknown operation "${String(n.op)}" in a transaction plan`)}}let C={...I,async txPlan(n){return W(n)},async attempt(n){let r=R();try{return await n(I)}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{...C,asService:()=>C,inserted:n=>(t.get(n)??[]).map($),updated:n=>(a.get(n)??[]).map($),deleted:n=>[...c.get(n)??[]],seed(n,r){e.set(n,r.map($))},queries:w}}function hn(e){return new Map([...e].map(([t,a])=>[t,a.map($)]))}function nn(e){return{rows:[e],rows_affected:1}}function yn(e,t){if(!Y(e))return e;let a=t[e.$ref.op]?.rows[0];if(!a)throw Object.assign(new Error(`transaction plan: operation ${e.$ref.op} produced no row to reference`),{error_code:"tx_ref_unresolved"});return a[e.$ref.field]}function en(e,t){let a=c=>{if(Y(c)){let w=yn(c,t);if(w==null)throw Object.assign(new Error(`transaction plan: a filter's reference to operation ${c.$ref.op}'s "${c.$ref.field}" is NULL`),{error_code:"tx_ref_null"});return w}return Array.isArray(c)?c.map(a):c!==null&&typeof c=="object"&&!U(c)&&!Z(c)&&!V(c)&&!(c instanceof Date)?Object.fromEntries(Object.entries(c).map(([w,f])=>[w,a(f)])):c};return a(e??{})}function Tn(e,t){return e?(e.kind==="one"?t===1:e.kind==="none"?t===0:e.kind==="atLeast"?t>=e.n:t<=e.n)?null:Object.assign(new Error(`transaction expectation failed: ${e.kind} (${t} row(s))`),{error_code:"tx_guard_failed",slot:e.slot}):null}export{En as createFakeClient,$n as typedDatabase};
|
|
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};
|
package/package.json
CHANGED
|
@@ -47,6 +47,8 @@ export interface Before {
|
|
|
47
47
|
/** What relationships are kept, by (type, relation, kind of subject), and which compiled schema is active. */
|
|
48
48
|
export interface Kept {
|
|
49
49
|
active: string | null;
|
|
50
|
+
/** The engine that compiled the schema in force (base.ts ENGINE); absent when none is, or read by an older reader. */
|
|
51
|
+
engine?: string | null;
|
|
50
52
|
relationships: {
|
|
51
53
|
object_type: string;
|
|
52
54
|
relation: string;
|
|
@@ -130,11 +130,40 @@ interface Asks {
|
|
|
130
130
|
}
|
|
131
131
|
/** Whose transaction asks: nobody's (no one is signed in), a signed-in user's, or the service role's. */
|
|
132
132
|
export type AccessAsker = 'anon' | 'authenticated' | 'service';
|
|
133
|
+
/** A filter as the database is asked it: the columns named, each with the value it must have. */
|
|
134
|
+
export interface AccessWhere {
|
|
135
|
+
object_type?: string;
|
|
136
|
+
object_id?: string;
|
|
137
|
+
relation?: string;
|
|
138
|
+
subject_type?: string;
|
|
139
|
+
subject_id?: string;
|
|
140
|
+
}
|
|
141
|
+
/**
|
|
142
|
+
* The questions answered without a database (palgres/testing's database in memory): the same operations, after the
|
|
143
|
+
* same checks of what was asked, with the schema's second evaluator in the database's place. What it refuses, it
|
|
144
|
+
* refuses as AccessRefused, with the database's codes.
|
|
145
|
+
*/
|
|
146
|
+
export interface AccessVia {
|
|
147
|
+
/** Whom `can`, `objects` and `held` are about; undefined when nobody is signed in. */
|
|
148
|
+
caller(): string | undefined;
|
|
149
|
+
check(subject: string, name: string, type: string, id: string): boolean;
|
|
150
|
+
objects(subject: string, name: string, type: string): string[];
|
|
151
|
+
subjects(name: string, type: string, id: string): string[];
|
|
152
|
+
change(fn: 'grant' | 'revoke', object: {
|
|
153
|
+
type: string;
|
|
154
|
+
id: string;
|
|
155
|
+
}, relation: string, subject: {
|
|
156
|
+
type: string;
|
|
157
|
+
id: string;
|
|
158
|
+
}, by: string | undefined): boolean;
|
|
159
|
+
relationships(where: AccessWhere, limit: number): AccessRelationship[];
|
|
160
|
+
history(where: AccessWhere, limit: number): AccessHistoryEntry[];
|
|
161
|
+
}
|
|
133
162
|
/**
|
|
134
163
|
* The access operations over what asks (`raw`: the transaction current when each is called), for the version whose
|
|
135
164
|
* access schema `names` are — undefined when the app declares none: every operation then says so. `as` is whose
|
|
136
165
|
* transaction it is: nobody (anon) holds nothing and is not the database's to ask, and only the service role's
|
|
137
166
|
* names a subject or changes who holds what — said here, since the database's refusal would end the transaction.
|
|
138
167
|
*/
|
|
139
|
-
export declare function accessOps(raw: () => Asks, names: AccessNames | undefined, as: AccessAsker, unanswered?: string): AccessOps;
|
|
168
|
+
export declare function accessOps(raw: () => Asks, names: AccessNames | undefined, as: AccessAsker, unanswered?: string, via?: AccessVia): AccessOps;
|
|
140
169
|
export {};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { type AccessAsker, type AccessNames } from './access.js';
|
|
1
|
+
import { type AccessAsker, type AccessNames, type AccessVia } from './access.js';
|
|
2
2
|
import type { DBClient } from './client.js';
|
|
3
3
|
import type { EnvTypedDatabase } from './typed.js';
|
|
4
4
|
/**
|
|
@@ -11,4 +11,5 @@ export declare function typedDatabase<T, S, A = unknown>(client: DBClient, optio
|
|
|
11
11
|
access?: AccessNames;
|
|
12
12
|
as?: AccessAsker;
|
|
13
13
|
unanswered?: string;
|
|
14
|
+
via?: AccessVia;
|
|
14
15
|
}): EnvTypedDatabase<T, S, A>;
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { type AccessNames, type AccessVia } from '../query/access.js';
|
|
2
|
+
type Row = Record<string, unknown>;
|
|
3
|
+
/** What the access in memory reads of the fake: a table's rows now, and the rows deleted from it so far. */
|
|
4
|
+
export interface AccessHost {
|
|
5
|
+
rows(table: string): Row[];
|
|
6
|
+
deleted(table: string): Row[];
|
|
7
|
+
}
|
|
8
|
+
export interface MemoryAccess {
|
|
9
|
+
names: AccessNames;
|
|
10
|
+
via: AccessVia;
|
|
11
|
+
/** Who the caller is from now on: `can`, `objects` and `held` are about them. Undefined: nobody is signed in. */
|
|
12
|
+
signedInAs(user: string | undefined): void;
|
|
13
|
+
/** Everything as it is now, to be put back (a savepoint's way back, with the rows'). */
|
|
14
|
+
snapshot(): () => void;
|
|
15
|
+
}
|
|
16
|
+
export declare function memoryAccess(text: string, host: AccessHost): MemoryAccess;
|
|
17
|
+
export {};
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { DBClient } from '../query/client.js';
|
|
2
|
+
import { type MemoryAccess } from './access.js';
|
|
2
3
|
type Row = Record<string, unknown>;
|
|
3
4
|
/** One raw SQL call, as it was made. */
|
|
4
5
|
export interface RecordedQuery {
|
|
@@ -16,7 +17,18 @@ export interface FakeClient extends DBClient {
|
|
|
16
17
|
seed(table: string, rows: Row[]): void;
|
|
17
18
|
/** Every raw SQL call, through any handle — the request's, $asService(), a savepoint's. */
|
|
18
19
|
readonly queries: readonly RecordedQuery[];
|
|
20
|
+
/** The access schema it was made with, asked in memory; none when it was made without one. */
|
|
21
|
+
readonly access?: MemoryAccess;
|
|
22
|
+
}
|
|
23
|
+
export interface FakeClientOptions {
|
|
24
|
+
/**
|
|
25
|
+
* The app's access schema, as text: `$access` is then answered in memory — the relationships a test gives, the
|
|
26
|
+
* rows it wrote, the schema's second evaluator (testing/access.ts says how that differs from Postgres).
|
|
27
|
+
*/
|
|
28
|
+
access?: string;
|
|
29
|
+
/** Whom `can`, `objects` and `held` are about, until `access.signedInAs` says another; none: nobody is signed in. */
|
|
30
|
+
user?: string;
|
|
19
31
|
}
|
|
20
32
|
/** A DBClient in memory: see the top of this file. */
|
|
21
|
-
export declare function createFakeClient(): FakeClient;
|
|
33
|
+
export declare function createFakeClient(options?: FakeClientOptions): FakeClient;
|
|
22
34
|
export {};
|
|
@@ -1,2 +1,3 @@
|
|
|
1
|
-
export { createFakeClient, type FakeClient, type RecordedQuery } from './fake.js';
|
|
1
|
+
export { createFakeClient, type FakeClient, type FakeClientOptions, type RecordedQuery } from './fake.js';
|
|
2
|
+
export type { MemoryAccess } from './access.js';
|
|
2
3
|
export { typedDatabase } from '../query/surface.js';
|