palgres 0.76.0 → 0.77.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.
@@ -1,2 +1,2 @@
1
- /*! palgres 0.76.0 — Palbase SDK License (see LICENSE) */
2
- import{L as x,N as _,a as h,b as q,ca as b,f as v,g as w,k as C,n as D,q as A,u as T}from"./FV6FUUSQ.js";var R={uuid:"uuid",text:"text",integer:"integer",bigint:"bigint",numeric:"numeric",boolean:"boolean",timestamp:"timestamp with time zone",date:"date",jsonb:"jsonb"};function Y(e,n={}){let u=Array.isArray(e)?e:[e],t={tables:[],enums:[],extensions:[],raw:[]},c=new Map;for(let o of u){for(let r of Object.values(o.tables))t.tables.push(N(o.name,r,c));t.extensions.push(...o.extensions);for(let r of o.raw??[])t.raw.push({name:r.name,schema:o.name,sql:r.up,...r.drop!==void 0?{drop:r.drop}:{},...r.before===!0?{before:!0}:{}})}t.enums=[...c.values()];for(let o of u)for(let r of Object.values(o.tables))for(let s of r.raw??[])t.raw.push({name:s.name,table:`${o.name}.${r.name}`,sql:s.up});return n.access!==void 0&&(I(t,n.access),t.access={text:n.access,compiled:_(C(t),n.access,n.roles??{authenticated:"authenticated",service:"service_role"})}),t}function I(e,n){let u;try{u=T(A(n))}catch(t){if(t instanceof D)return;throw t}for(let t of u.types.values()){let c=t.table;if(!c)continue;let o=e.tables.find(s=>s.schema===c.schema&&s.name===c.name);if(!o||o.ignored)continue;let r=O.get(o);if(o.policies.some(s=>!r?.unindexedPolicies.has(s.name)&&(x(s.using)||x(s.withCheck))))for(let s of t.relations.values())s.kind==="column"&&U(o,s.column,r?.rawNames??new Set)}}var O=new WeakMap;function U(e,n,u){let t=new Set,c=s=>s[0]!==void 0&&t.add(s[0]);c(e.primaryKey);for(let s of e.uniques)c(s.columns);for(let s of e.indexes){let l=s.keys[0];l&&"column"in l&&s.where===void 0&&t.add(l.column)}let o=e.columns.find(s=>s.name===n);if(t.has(n)||!o||o.ignored)return;let r=`${e.name}_${n}_idx`;Buffer.byteLength(r)>63||e.indexes.some(s=>s.name===r)||u.has(r)||e.indexes.push({name:r,keys:[{column:n}],unique:!1})}function j(e,n){return!n&&q(e.onDelete,e.onUpdate)?{...e,deferrable:!0}:e}function F(e){return e._def}function N(e,n,u){let t=[],c=i=>{let y=n.columns[i];return y!==void 0&&F(y).encrypted?.lookup?h(i):i},o=(n.unique??[]).map(i=>({name:i.name,columns:i.columns.map(c)})),r=[],s=[],l=new Set,f=[];for(let[i,y]of Object.entries(n.columns)){let a=F(y),d={name:i,type:P(e,i,n.name,a,u),nullable:a.nullable},S=L(a);S!==void 0&&(d.default=S),a.renamedFrom!==void 0&&(d.renamedFrom=a.renamedFrom),a.ignored&&(d.ignored=!0),a.fill!==void 0&&(d.fill=a.fill),a.identity!==void 0&&(d.identity=a.identity==="always"?"always":"by default"),a.generated!==void 0&&(d.generated={...a.generated}),a.user!==void 0&&(d.user={...a.user}),a.primaryKey&&s.push(i);let m=a.encrypted?.lookup?h(i):void 0;if(a.encrypted!==void 0&&(d.encrypted=m?{lookup:m}:{}),a.unique&&o.push(m?{name:`${n.name}_${m}_key`,columns:[m]}:{name:`${n.name}_${i}_key`,columns:[i]}),a.references!==void 0){let[g,E]=K(a.references.table);r.push(j({name:`${z(e,n.name)}_${i}_fkey`,columns:[i],refSchema:g,refTable:E,refColumns:[a.references.column],onDelete:a.onDeleteAction??"no action",onUpdate:a.onUpdateAction??"no action"},a.deferrable===!1)),a.index===!1&&l.add(i)}if(t.push(d),m){let g={name:m,type:"text",nullable:!0,lookupOf:i};a.renamedFrom!==void 0&&(g.renamedFrom=h(a.renamedFrom)),a.ignored&&(g.ignored=!0),t.push(g),a.unique||f.push({name:`${n.name}_${m}_idx`,keys:[{column:m}],unique:!1})}}for(let i of n.foreignKeys??[]){i.index===!1&&i.columns.length===1&&l.add(i.columns[0]);let[y,a]=K(i.refTable);r.push(j({name:i.name,columns:[...i.columns],refSchema:y,refTable:a,refColumns:[...i.refColumns],onDelete:i.onDelete??"no action",onUpdate:i.onUpdate??"no action",...i.match==="full"?{match:"full"}:{}},i.deferrable===!1))}let p={schema:e,name:n.name,columns:t,primaryKey:n.primaryKey!==void 0?[...n.primaryKey]:s,uniques:o,indexes:[...(n.indexes??[]).map(M),...f],checks:(n.checks??[]).map(i=>({name:i.name,expr:i.expr})),foreignKeys:r,rls:n.rls,policies:n.policies.map(B)};n.ignored&&(p.ignored=!0),n.search!==void 0&&(p.search={...n.search,from:[...n.search.from]}),p.uniques=J(p.uniques);let $=new Set((n.raw??[]).map(i=>i.name)),k=new Set(n.policies.filter(i=>i.indexes===!1).map(i=>i.name));return V(p,l,$,k),O.set(p,{rawNames:$,unindexedPolicies:k}),p}function P(e,n,u,t,c){let o=t.type;if(o==="enum"||o==="enum[]"){let r=t.enumName,s=`${e}.${r}`,l=t.enumValues??[],f=c.get(s);if(f&&f.values.join()!==l.join())throw new Error(`enum ${s} is declared with different values by ${u}.${n}: (${f.values.join(", ")}) and (${l.join(", ")}) \u2014 one type has one list`);return c.set(s,{schema:e,name:r,values:[...l]}),o==="enum[]"?`${w(e,r)}[]`:w(e,r)}return o==="sql"?v(t.sqlType):o==="numeric"&&t.precision!==void 0?`numeric(${t.precision},${t.scale??0})`:o.endsWith("[]")?`${R[o.slice(0,-2)]??o.slice(0,-2)}[]`:R[o]??o}function L(e){if(e.defaultSql!==void 0)return e.defaultSql;if(e.defaultRandom)return"gen_random_uuid()";if(e.defaultNow)return e.type==="date"?"CURRENT_DATE":"now()";let n=e.defaultValue;if(n!==void 0){if(Array.isArray(n)&&n.length===0&&e.type.endsWith("[]"))return"'{}'";if(typeof n=="string")return`'${n.replace(/'/g,"''")}'`;if(typeof n=="boolean")return n?"true":"false";if(typeof n=="number"){if(!Number.isFinite(n))throw new Error(`default ${n} is not a number Postgres can store`);return String(n)}return n===null?"NULL":`'${JSON.stringify(n).replace(/'/g,"''")}'::jsonb`}}function M(e){let n=e.expression!==void 0?[{expr:e.expression}]:(e.columns??[]).map(c=>({column:c}));for(let c of n)e.sort==="desc"&&(c.desc=!0),e.nulls!==void 0&&(c.nulls=e.nulls);let u={name:e.name,keys:n,unique:e.unique===!0},t=e.where===void 0?void 0:b(e.where);return t!==void 0&&(u.where=t),e.include?.length&&(u.include=[...e.include]),u}function B(e){let n={name:e.name,for:e.command,to:e.roles.length===0?["public"]:[...e.roles]},u=b(e.using),t=b(e.withCheck);return u!==void 0&&(n.using=u),t!==void 0&&(n.withCheck=t),e.permissive||(n.restrictive=!0),n}function V(e,n,u,t){let c=new Set,o=s=>s[0]!==void 0&&c.add(s[0]);o(e.primaryKey);for(let s of e.uniques)o(s.columns);for(let s of e.indexes){let l=s.keys[0];l&&"column"in l&&s.where===void 0&&c.add(l.column)}let r=s=>{if(c.has(s)||e.columns.find(f=>f.name===s)?.ignored)return;let l=`${e.name}_${s}_idx`;Buffer.byteLength(l)>63||e.indexes.some(f=>f.name===l)||u.has(l)||(e.indexes.push({name:l,keys:[{column:s}],unique:!1}),c.add(s))};for(let s of e.foreignKeys)s.columns.length===1&&!n.has(s.columns[0])&&r(s.columns[0]);for(let s of e.policies)if(!t.has(s.name))for(let l of W(e,s))r(l)}function W(e,n){let u=[];for(let t of[n.using,n.withCheck])if(t!==void 0)for(let c of t.matchAll(/(?<![.\w"])"((?:[^"]|"")+)"(?!\s*\.)/g)){let o=c[1].replace(/""/g,'"');e.columns.some(r=>r.name===o)&&!u.includes(o)&&u.push(o)}return u}function K(e){let n=e.indexOf(".");return n<0?["public",e]:[e.slice(0,n),e.slice(n+1)]}function z(e,n){return e==="public"?n:`${e}_${n}`}function J(e){let n=new Map;return e.filter(u=>{let t=n.get(u.name);if(t===void 0)return n.set(u.name,u),!0;if(t.columns.join()!==u.columns.join())throw new Error(`palgres: unique ${u.name} is declared over (${t.columns.join(", ")}) and over (${u.columns.join(", ")}): give one of them another name`);return!1})}export{Y as a,W as b};
1
+ /*! palgres 0.77.0 — Palbase SDK License (see LICENSE) */
2
+ import{L as x,N as _,a as h,b as q,ca as b,f as v,g as w,k as C,n as D,q as A,u as T}from"./SFRNKLRS.js";var R={uuid:"uuid",text:"text",integer:"integer",bigint:"bigint",numeric:"numeric",boolean:"boolean",timestamp:"timestamp with time zone",date:"date",jsonb:"jsonb"};function Y(e,n={}){let u=Array.isArray(e)?e:[e],t={tables:[],enums:[],extensions:[],raw:[]},c=new Map;for(let o of u){for(let r of Object.values(o.tables))t.tables.push(N(o.name,r,c));t.extensions.push(...o.extensions);for(let r of o.raw??[])t.raw.push({name:r.name,schema:o.name,sql:r.up,...r.drop!==void 0?{drop:r.drop}:{},...r.before===!0?{before:!0}:{}})}t.enums=[...c.values()];for(let o of u)for(let r of Object.values(o.tables))for(let s of r.raw??[])t.raw.push({name:s.name,table:`${o.name}.${r.name}`,sql:s.up});return n.access!==void 0&&(I(t,n.access),t.access={text:n.access,compiled:_(C(t),n.access,n.roles??{authenticated:"authenticated",service:"service_role"})}),t}function I(e,n){let u;try{u=T(A(n))}catch(t){if(t instanceof D)return;throw t}for(let t of u.types.values()){let c=t.table;if(!c)continue;let o=e.tables.find(s=>s.schema===c.schema&&s.name===c.name);if(!o||o.ignored)continue;let r=O.get(o);if(o.policies.some(s=>!r?.unindexedPolicies.has(s.name)&&(x(s.using)||x(s.withCheck))))for(let s of t.relations.values())s.kind==="column"&&U(o,s.column,r?.rawNames??new Set)}}var O=new WeakMap;function U(e,n,u){let t=new Set,c=s=>s[0]!==void 0&&t.add(s[0]);c(e.primaryKey);for(let s of e.uniques)c(s.columns);for(let s of e.indexes){let l=s.keys[0];l&&"column"in l&&s.where===void 0&&t.add(l.column)}let o=e.columns.find(s=>s.name===n);if(t.has(n)||!o||o.ignored)return;let r=`${e.name}_${n}_idx`;Buffer.byteLength(r)>63||e.indexes.some(s=>s.name===r)||u.has(r)||e.indexes.push({name:r,keys:[{column:n}],unique:!1})}function j(e,n){return!n&&q(e.onDelete,e.onUpdate)?{...e,deferrable:!0}:e}function F(e){return e._def}function N(e,n,u){let t=[],c=i=>{let y=n.columns[i];return y!==void 0&&F(y).encrypted?.lookup?h(i):i},o=(n.unique??[]).map(i=>({name:i.name,columns:i.columns.map(c)})),r=[],s=[],l=new Set,f=[];for(let[i,y]of Object.entries(n.columns)){let a=F(y),d={name:i,type:P(e,i,n.name,a,u),nullable:a.nullable},S=L(a);S!==void 0&&(d.default=S),a.renamedFrom!==void 0&&(d.renamedFrom=a.renamedFrom),a.ignored&&(d.ignored=!0),a.fill!==void 0&&(d.fill=a.fill),a.identity!==void 0&&(d.identity=a.identity==="always"?"always":"by default"),a.generated!==void 0&&(d.generated={...a.generated}),a.user!==void 0&&(d.user={...a.user}),a.primaryKey&&s.push(i);let m=a.encrypted?.lookup?h(i):void 0;if(a.encrypted!==void 0&&(d.encrypted=m?{lookup:m}:{}),a.unique&&o.push(m?{name:`${n.name}_${m}_key`,columns:[m]}:{name:`${n.name}_${i}_key`,columns:[i]}),a.references!==void 0){let[g,E]=K(a.references.table);r.push(j({name:`${z(e,n.name)}_${i}_fkey`,columns:[i],refSchema:g,refTable:E,refColumns:[a.references.column],onDelete:a.onDeleteAction??"no action",onUpdate:a.onUpdateAction??"no action"},a.deferrable===!1)),a.index===!1&&l.add(i)}if(t.push(d),m){let g={name:m,type:"text",nullable:!0,lookupOf:i};a.renamedFrom!==void 0&&(g.renamedFrom=h(a.renamedFrom)),a.ignored&&(g.ignored=!0),t.push(g),a.unique||f.push({name:`${n.name}_${m}_idx`,keys:[{column:m}],unique:!1})}}for(let i of n.foreignKeys??[]){i.index===!1&&i.columns.length===1&&l.add(i.columns[0]);let[y,a]=K(i.refTable);r.push(j({name:i.name,columns:[...i.columns],refSchema:y,refTable:a,refColumns:[...i.refColumns],onDelete:i.onDelete??"no action",onUpdate:i.onUpdate??"no action",...i.match==="full"?{match:"full"}:{}},i.deferrable===!1))}let p={schema:e,name:n.name,columns:t,primaryKey:n.primaryKey!==void 0?[...n.primaryKey]:s,uniques:o,indexes:[...(n.indexes??[]).map(M),...f],checks:(n.checks??[]).map(i=>({name:i.name,expr:i.expr})),foreignKeys:r,rls:n.rls,policies:n.policies.map(B)};n.ignored&&(p.ignored=!0),n.search!==void 0&&(p.search={...n.search,from:[...n.search.from]}),p.uniques=J(p.uniques);let $=new Set((n.raw??[]).map(i=>i.name)),k=new Set(n.policies.filter(i=>i.indexes===!1).map(i=>i.name));return V(p,l,$,k),O.set(p,{rawNames:$,unindexedPolicies:k}),p}function P(e,n,u,t,c){let o=t.type;if(o==="enum"||o==="enum[]"){let r=t.enumName,s=`${e}.${r}`,l=t.enumValues??[],f=c.get(s);if(f&&f.values.join()!==l.join())throw new Error(`enum ${s} is declared with different values by ${u}.${n}: (${f.values.join(", ")}) and (${l.join(", ")}) \u2014 one type has one list`);return c.set(s,{schema:e,name:r,values:[...l]}),o==="enum[]"?`${w(e,r)}[]`:w(e,r)}return o==="sql"?v(t.sqlType):o==="numeric"&&t.precision!==void 0?`numeric(${t.precision},${t.scale??0})`:o.endsWith("[]")?`${R[o.slice(0,-2)]??o.slice(0,-2)}[]`:R[o]??o}function L(e){if(e.defaultSql!==void 0)return e.defaultSql;if(e.defaultRandom)return"gen_random_uuid()";if(e.defaultNow)return e.type==="date"?"CURRENT_DATE":"now()";let n=e.defaultValue;if(n!==void 0){if(Array.isArray(n)&&n.length===0&&e.type.endsWith("[]"))return"'{}'";if(typeof n=="string")return`'${n.replace(/'/g,"''")}'`;if(typeof n=="boolean")return n?"true":"false";if(typeof n=="number"){if(!Number.isFinite(n))throw new Error(`default ${n} is not a number Postgres can store`);return String(n)}return n===null?"NULL":`'${JSON.stringify(n).replace(/'/g,"''")}'::jsonb`}}function M(e){let n=e.expression!==void 0?[{expr:e.expression}]:(e.columns??[]).map(c=>({column:c}));for(let c of n)e.sort==="desc"&&(c.desc=!0),e.nulls!==void 0&&(c.nulls=e.nulls);let u={name:e.name,keys:n,unique:e.unique===!0},t=e.where===void 0?void 0:b(e.where);return t!==void 0&&(u.where=t),e.include?.length&&(u.include=[...e.include]),u}function B(e){let n={name:e.name,for:e.command,to:e.roles.length===0?["public"]:[...e.roles]},u=b(e.using),t=b(e.withCheck);return u!==void 0&&(n.using=u),t!==void 0&&(n.withCheck=t),e.permissive||(n.restrictive=!0),n}function V(e,n,u,t){let c=new Set,o=s=>s[0]!==void 0&&c.add(s[0]);o(e.primaryKey);for(let s of e.uniques)o(s.columns);for(let s of e.indexes){let l=s.keys[0];l&&"column"in l&&s.where===void 0&&c.add(l.column)}let r=s=>{if(c.has(s)||e.columns.find(f=>f.name===s)?.ignored)return;let l=`${e.name}_${s}_idx`;Buffer.byteLength(l)>63||e.indexes.some(f=>f.name===l)||u.has(l)||(e.indexes.push({name:l,keys:[{column:s}],unique:!1}),c.add(s))};for(let s of e.foreignKeys)s.columns.length===1&&!n.has(s.columns[0])&&r(s.columns[0]);for(let s of e.policies)if(!t.has(s.name))for(let l of W(e,s))r(l)}function W(e,n){let u=[];for(let t of[n.using,n.withCheck])if(t!==void 0)for(let c of t.matchAll(/(?<![.\w"])"((?:[^"]|"")+)"(?!\s*\.)/g)){let o=c[1].replace(/""/g,'"');e.columns.some(r=>r.name===o)&&!u.includes(o)&&u.push(o)}return u}function K(e){let n=e.indexOf(".");return n<0?["public",e]:[e.slice(0,n),e.slice(n+1)]}function z(e,n){return e==="public"?n:`${e}_${n}`}function J(e){let n=new Map;return e.filter(u=>{let t=n.get(u.name);if(t===void 0)return n.set(u.name,u),!0;if(t.columns.join()!==u.columns.join())throw new Error(`palgres: unique ${u.name} is declared over (${t.columns.join(", ")}) and over (${u.columns.join(", ")}): give one of them another name`);return!1})}export{Y as a,W as b};
@@ -1,5 +1,5 @@
1
- /*! palgres 0.76.0 — Palbase SDK License (see LICENSE) */
2
- import{b as Lt}from"./J57ZAYFW.js";import{B as It,a as T,b as L,c as A,e as ee,f as wt,g as ne,h as J,i as we,y as $e}from"./DQNIJVL2.js";import{A as $t,C as Tt,D as Nt,E as Xe,F as St,L as ae,M as yt,O as Rt,P as At,Q as Ot,b as ue,c as rt,d as ct,e as b,f as Y,g as Ee,h as lt,i as mt,j as dt,k as re,l as pt,m as Ae,n as ht,q as ut,u as gt,v as ft,w as Be,x as Oe,y as Et,z as Ge}from"./FV6FUUSQ.js";function kt(a){return typeof a=="function"?a():Promise.resolve(a)}var bt="pbe1.";function je(a,e,t){return a==="public"?`${e}.${t}`:`${a}.${e}.${t}`}var ie="palgres.sealing",Nn=5e3,_t=3*Nn,Ct=class{going=new Map;get(e){return this.going.get(e)}get size(){return this.going.size}async read(e){let t;try{t=await e(`SELECT address, direction, phase FROM ${ie}`)}catch(n){let s=n.code??n.errno;if(s!=="42P01"&&s!=="3F000")throw n;t=[]}this.going=new Map(t.map(n=>[n.address,{direction:n.direction,phase:n.phase}]))}},Te=a=>`"${a.replace(/"/g,'""')}"`;function Dt(a,e){let t=Te(a.column);return a.direction==="open"?{sql:`${t} LIKE 'pbe1.%'`,params:[]}:{sql:`(${t} NOT LIKE $1${a.lookup?` OR ${Te(a.lookup)} IS NULL`:""})`,params:[`pbe1.${e.currentKey()}.%`]}}async function Ft(a,e,t,n,s){let i=Dt(e,t),o=Te(e.column),c=n===null?"":` AND ctid > $${i.params.length+1}::tid`,r=await a(`SELECT ctid::text AS at, ${o} AS value FROM ${e.table} WHERE ${o} IS NOT NULL AND ${i.sql}${c} ORDER BY ctid LIMIT ${s}`,n===null?i.params:[...i.params,n]);if(r.length===0)return{done:0,last:null};let l=[],h=r.map(g=>{let f=Sn(t,e.address,g.value),R=[g.at,g.value,e.direction==="seal"?t.encrypt(e.address,f):f,...e.lookup?[t.lookup(e.address,f)]:[]],I=l.length+1;return l.push(...R),`(${R.map((p,m)=>`$${I+m}::text`).join(", ")})`}),N=[`${o} = v.next`,...e.lookup?[`${Te(e.lookup)} = v.lookup`]:[]],u=await a(`WITH done AS (UPDATE ${e.table} AS t SET ${N.join(", ")} FROM (VALUES ${h.join(", ")}) AS v(at, old, next${e.lookup?", lookup":""}) WHERE t.ctid = v.at::tid AND t.${o} = v.old RETURNING 1) SELECT count(*)::int AS n FROM done`,l);return{done:Number(u[0]?.n??0),last:r.length<s?null:r[r.length-1].at}}function Sn(a,e,t){if(!a.isEncrypted(t))return t;try{return a.decrypt(e,t)}catch{return t}}function os(a,e){if(typeof e=="string"&&e.startsWith(bt))throw new TypeError(`${a} is going over between plain and encrypted: a value beginning ${bt} would read as an encrypted one \u2014 it is written once the migration completes`)}async function xt(a,e,t){let n=Dt(e,t);return(await a(`SELECT 1 FROM ${e.table} WHERE ${Te(e.column)} IS NOT NULL AND ${n.sql} LIMIT 1`,n.params)).length>0}import{createHash as Ke}from"node:crypto";var K="palgres_search",Ie=(a,e)=>a.model===e.model&&a.dimensions===e.dimensions&&a.metric===e.metric&&a.from.length===e.from.length&&a.from.every((t,n)=>t===e.from[n]),vt=48;function Ve(a,e){let t=a.replaceAll(".","__");return`${t.length<=vt?t:`${t.slice(0,32)}_${Ke("md5").update(t).digest("hex").slice(0,12)}`}__g${e}`}var Ut=a=>({insert:`_palgres_search_g${a}_ins`,update:`_palgres_search_g${a}_upd`});function Le(a,e){let t=Ke("sha256").update(JSON.stringify([a.schema,a.name,e])).digest("hex").slice(0,8),n=`_palgres_search_${a.name}_${t}`;return Buffer.byteLength(n)<=63?n:`_palgres_search_${Ke("sha256").update(`${a.schema}.${a.name}`).digest("hex").slice(0,16)}_${t}`}function yn(a,e){let t=e===void 0?"":`${T(e)}.`;return a.map(n=>`coalesce(${t}${T(n)}::text, '')`).join(" || ' ' || ")}var Mt=(a,e)=>`to_tsvector('simple', ${yn(a,e)})`;function Rn(a,e){let t=a>lt?"halfvec":"vector",n={cosine:["cosine","<=>"],euclidean:["l2","<->"],inner_product:["ip","<#>"]}[e];return{type:t,opclass:`${t}_${n[0]}_ops`,operator:n[1]}}function Pt(a){let e=`${a.table.schema}.${a.table.name}`,t=L(a.table.schema,a.table.name),n=Ve(e,a.gen),s=L(K,n),i=Rn(a.search.dimensions,a.search.metric),o=T(a.pk.name),c=[a.roles.anon,a.roles.authenticated].map(T).join(", ");return[`INSERT INTO ${K}.generations (table_key, gen, model, dimensions, metric, from_columns, status, promoted_at) VALUES (${A(e)}, ${a.gen}, ${A(a.search.model)}, ${a.search.dimensions}, ${A(a.search.metric)}, ARRAY[${a.search.from.map(A).join(", ")}]::text[], ${A(a.status)}, ${a.status==="active"?"now()":"NULL"})`,`CREATE TABLE ${s} (
1
+ /*! palgres 0.77.0 — Palbase SDK License (see LICENSE) */
2
+ import{b as Lt}from"./4PM3K5J6.js";import{B as It,a as T,b as L,c as A,e as ee,f as wt,g as ne,h as J,i as we,y as $e}from"./LM4G2SEB.js";import{A as $t,C as Tt,D as Nt,E as Xe,F as St,L as ae,M as yt,O as Rt,P as At,Q as Ot,b as ue,c as rt,d as ct,e as b,f as Y,g as Ee,h as lt,i as mt,j as dt,k as re,l as pt,m as Ae,n as ht,q as ut,u as gt,v as ft,w as Be,x as Oe,y as Et,z as Ge}from"./SFRNKLRS.js";function kt(a){return typeof a=="function"?a():Promise.resolve(a)}var bt="pbe1.";function je(a,e,t){return a==="public"?`${e}.${t}`:`${a}.${e}.${t}`}var ie="palgres.sealing",Nn=5e3,_t=3*Nn,Ct=class{going=new Map;get(e){return this.going.get(e)}get size(){return this.going.size}async read(e){let t;try{t=await e(`SELECT address, direction, phase FROM ${ie}`)}catch(n){let s=n.code??n.errno;if(s!=="42P01"&&s!=="3F000")throw n;t=[]}this.going=new Map(t.map(n=>[n.address,{direction:n.direction,phase:n.phase}]))}},Te=a=>`"${a.replace(/"/g,'""')}"`;function Dt(a,e){let t=Te(a.column);return a.direction==="open"?{sql:`${t} LIKE 'pbe1.%'`,params:[]}:{sql:`(${t} NOT LIKE $1${a.lookup?` OR ${Te(a.lookup)} IS NULL`:""})`,params:[`pbe1.${e.currentKey()}.%`]}}async function Ft(a,e,t,n,s){let i=Dt(e,t),o=Te(e.column),c=n===null?"":` AND ctid > $${i.params.length+1}::tid`,r=await a(`SELECT ctid::text AS at, ${o} AS value FROM ${e.table} WHERE ${o} IS NOT NULL AND ${i.sql}${c} ORDER BY ctid LIMIT ${s}`,n===null?i.params:[...i.params,n]);if(r.length===0)return{done:0,last:null};let l=[],h=r.map(g=>{let f=Sn(t,e.address,g.value),R=[g.at,g.value,e.direction==="seal"?t.encrypt(e.address,f):f,...e.lookup?[t.lookup(e.address,f)]:[]],I=l.length+1;return l.push(...R),`(${R.map((p,m)=>`$${I+m}::text`).join(", ")})`}),N=[`${o} = v.next`,...e.lookup?[`${Te(e.lookup)} = v.lookup`]:[]],u=await a(`WITH done AS (UPDATE ${e.table} AS t SET ${N.join(", ")} FROM (VALUES ${h.join(", ")}) AS v(at, old, next${e.lookup?", lookup":""}) WHERE t.ctid = v.at::tid AND t.${o} = v.old RETURNING 1) SELECT count(*)::int AS n FROM done`,l);return{done:Number(u[0]?.n??0),last:r.length<s?null:r[r.length-1].at}}function Sn(a,e,t){if(!a.isEncrypted(t))return t;try{return a.decrypt(e,t)}catch{return t}}function os(a,e){if(typeof e=="string"&&e.startsWith(bt))throw new TypeError(`${a} is going over between plain and encrypted: a value beginning ${bt} would read as an encrypted one \u2014 it is written once the migration completes`)}async function xt(a,e,t){let n=Dt(e,t);return(await a(`SELECT 1 FROM ${e.table} WHERE ${Te(e.column)} IS NOT NULL AND ${n.sql} LIMIT 1`,n.params)).length>0}import{createHash as Ke}from"node:crypto";var K="palgres_search",Ie=(a,e)=>a.model===e.model&&a.dimensions===e.dimensions&&a.metric===e.metric&&a.from.length===e.from.length&&a.from.every((t,n)=>t===e.from[n]),vt=48;function Ve(a,e){let t=a.replaceAll(".","__");return`${t.length<=vt?t:`${t.slice(0,32)}_${Ke("md5").update(t).digest("hex").slice(0,12)}`}__g${e}`}var Ut=a=>({insert:`_palgres_search_g${a}_ins`,update:`_palgres_search_g${a}_upd`});function Le(a,e){let t=Ke("sha256").update(JSON.stringify([a.schema,a.name,e])).digest("hex").slice(0,8),n=`_palgres_search_${a.name}_${t}`;return Buffer.byteLength(n)<=63?n:`_palgres_search_${Ke("sha256").update(`${a.schema}.${a.name}`).digest("hex").slice(0,16)}_${t}`}function yn(a,e){let t=e===void 0?"":`${T(e)}.`;return a.map(n=>`coalesce(${t}${T(n)}::text, '')`).join(" || ' ' || ")}var Mt=(a,e)=>`to_tsvector('simple', ${yn(a,e)})`;function Rn(a,e){let t=a>lt?"halfvec":"vector",n={cosine:["cosine","<=>"],euclidean:["l2","<->"],inner_product:["ip","<#>"]}[e];return{type:t,opclass:`${t}_${n[0]}_ops`,operator:n[1]}}function Pt(a){let e=`${a.table.schema}.${a.table.name}`,t=L(a.table.schema,a.table.name),n=Ve(e,a.gen),s=L(K,n),i=Rn(a.search.dimensions,a.search.metric),o=T(a.pk.name),c=[a.roles.anon,a.roles.authenticated].map(T).join(", ");return[`INSERT INTO ${K}.generations (table_key, gen, model, dimensions, metric, from_columns, status, promoted_at) VALUES (${A(e)}, ${a.gen}, ${A(a.search.model)}, ${a.search.dimensions}, ${A(a.search.metric)}, ARRAY[${a.search.from.map(A).join(", ")}]::text[], ${A(a.status)}, ${a.status==="active"?"now()":"NULL"})`,`CREATE TABLE ${s} (
3
3
  id ${a.pk.type} PRIMARY KEY REFERENCES ${t} (${o}) ON DELETE CASCADE,
4
4
  embedding ${T(a.types)}.${i.type}(${a.search.dimensions}) NOT NULL,
5
5
  model text NOT NULL,
@@ -1,3 +1,3 @@
1
- /*! palgres 0.76.0 — Palbase SDK License (see LICENSE) */
2
- import{a as $,n as ke,p as $e,y as Re}from"./DQNIJVL2.js";import{B as S,T as oe,o as te,p as re,q as be,r as O,s as A,t as me,u as xe}from"./FV6FUUSQ.js";var g=class extends Error{code;constructor(n,t,o){super(t,o),this.name="AccessRefused",this.code=n}};function He(e,n){let t=xe(be(e)),o=new Map;for(let r of t.types.values()){let i=new Set,s=new Map;for(let a of r.relations.values())me(a)&&i.add(a.name),a.kind==="stored"&&s.set(a.name,new Set(a.subjects));for(let a of r.permissions.keys())i.add(a);o.set(r.name,{names:i,open:new Set([...i].filter(a=>t.open(r.name,a))),kept:s})}return{schema:`access_${n}`,types:o}}function mn(e,n){let t=He(e,""),o=r=>{let i=[...r].sort();return i.length===0?"never":i.map(s=>JSON.stringify(s)).join(" | ")};return[...t.types].map(([r,i])=>{let s=[...i.kept].sort(([a],[f])=>a<f?-1:a>f?1:0).map(([a,f])=>`${JSON.stringify(a)}: ${o(f)}`);return`${n}${r}: { names: ${o(i.names)}; relations: {${s.length===0?"":` ${s.join("; ")} `}} };`}).join(`
1
+ /*! palgres 0.77.0 — Palbase SDK License (see LICENSE) */
2
+ import{a as $,n as ke,p as $e,y as Re}from"./LM4G2SEB.js";import{B as S,T as oe,o as te,p as re,q as be,r as O,s as A,t as me,u as xe}from"./SFRNKLRS.js";var g=class extends Error{code;constructor(n,t,o){super(t,o),this.name="AccessRefused",this.code=n}};function He(e,n){let t=xe(be(e)),o=new Map;for(let r of t.types.values()){let i=new Set,s=new Map;for(let a of r.relations.values())me(a)&&i.add(a.name),a.kind==="stored"&&s.set(a.name,new Set(a.subjects));for(let a of r.permissions.keys())i.add(a);o.set(r.name,{names:i,open:new Set([...i].filter(a=>t.open(r.name,a))),kept:s})}return{schema:`access_${n}`,types:o}}function mn(e,n){let t=He(e,""),o=r=>{let i=[...r].sort();return i.length===0?"never":i.map(s=>JSON.stringify(s)).join(" | ")};return[...t.types].map(([r,i])=>{let s=[...i.kept].sort(([a],[f])=>a<f?-1:a>f?1:0).map(([a,f])=>`${JSON.stringify(a)}: ${o(f)}`);return`${n}${r}: { names: ${o(i.names)}; relations: {${s.length===0?"":` ${s.join("; ")} `}} };`}).join(`
3
3
  `)}var Ye="names a subject or changes who holds what: it is the service role's \u2014 Database.$asService().$access",ze={PA002:"no_object",PA008:"cycle",PA009:"too_deep",PA010:"too_many_parents"},Ge={PA001:"unknown_name",PA003:"bad_id",PA004:"too_many",PA005:"not_kept",PA006:"not_the_service",PA007:"bad_time",...ze};function _(e,n){let t=typeof n=="string"?n:typeof n=="bigint"||typeof n=="number"&&Number.isSafeInteger(n)?String(n):void 0;if(t===void 0)throw new g("bad_id",`Database.$access: ${e} is a string or a whole number, not ${typeof n=="number"?String(n):typeof n}`);if(t===""||t.length>S)throw new g("bad_id",`Database.$access: ${e} is empty or longer than ${S} characters`);return t}function Ae(e,n,t,o,r){let i=t==="anon",s=()=>{if(!n)throw new g("no_schema",`Database.$access: ${o??"the app declares no access schema \u2014 PalbaseFactory.create(\u2026, { db: { schemas, access } })"}`);return n},a=(l,u)=>{let c=typeof u=="string"?l.types.get(u):void 0;if(!c)throw new g("unknown_type",`Database.$access: the access schema has no type ${JSON.stringify(u)} \u2014 it has ${[...l.types.keys()].join(", ")||"none"}`);return c},f=(l,u,c)=>{let d=a(l,u);if(typeof c!="string"||!d.names.has(c))throw new g("unknown_name",`Database.$access: type ${String(u)} has no relation or permission ${JSON.stringify(c)} a user can hold \u2014 it has ${[...d.names].sort().join(", ")||"none"}`)},b=(l,u)=>{let c=u;if(c===null||typeof c!="object")throw new g("bad_id","Database.$access: an object is { type, id }");return a(l,c.type),{type:c.type,id:_(`the id of a ${String(c.type)}`,c.id)}},X=l=>{if(typeof l!="string")throw new g("bad_id","Database.$access: a subject is a user's id, a string");return _("a subject's id",l)},ye=(l,u)=>{let c=()=>new g("bad_id",`Database.$access: "*" is nobody's id \u2014 every signed-in user is { everyUser: true }, everyone is { public: true }`);if(u===A)throw c();if(typeof u=="string")return{type:O,id:_("a subject's id",u)};let d=u;if(d!==null&&typeof d=="object"&&"public"in d){if(d.public!==!0)throw new g("bad_id","Database.$access: everyone is { public: true }");return{type:re,id:A}}if(d!==null&&typeof d=="object"&&"everyUser"in d){if(d.everyUser!==!0)throw new g("bad_id","Database.$access: every signed-in user is { everyUser: true }");return{type:O,id:A}}if(d!==null&&typeof d=="object"&&"user"in d){let p=X(d.user);if(p===A)throw c();return{type:O,id:p}}let w=b(l,u);if(w.id===A)throw c();return w},Z=l=>l.type===O&&l.id===A?te:l.type,Ve=(l,u,c,d)=>{let w=typeof c=="string"?a(l,u.type).kept.get(c):void 0;if(!w){let h=[...a(l,u.type).kept.keys()].sort().join(", ");throw new g("not_kept",`Database.$access: type ${u.type} keeps no relation ${JSON.stringify(c)} \u2014 ${h===""?"it keeps none: its relations are read from its table":`it keeps ${h}`}`)}let p=Z(d);if(!w.has(p))throw new g("not_kept",`Database.$access: ${u.type}.${String(c)} takes ${[...w].sort().join(" or ")}, not ${p===te?"every signed-in user (user:*)":p===re?"the public":p}`)},m=async(l,u)=>{try{return await e().query(l,u)}catch(c){let d=Re(c),w=d===void 0?void 0:Ge[d],p=c instanceof Error?c.message:String(c);throw w!==void 0?new g(w,`Database.$access: ${p}`,{cause:c}):d==="42501"?new g("not_the_service",`Database.$access: ${p} \u2014 what names a subject or changes who holds what is the service role's: Database.$asService().$access`,{cause:c}):c}},R=l=>{if(t!=="service")throw new g("not_the_service",`Database.$access.${l} ${Ye}`)},Q=(l,u)=>u(l.caller()??null),ee=(l,u,c)=>i&&!a(l,u).open.has(c),Fe=l=>{if(l===void 0)return;let u=l instanceof Date?l.getTime():typeof l=="string"?Date.parse(l):Number.NaN;if(Number.isNaN(u))throw new g("bad_time","Database.$access: until is the moment a relationship ends \u2014 a Date, or ISO 8601 text (2026-12-01T00:00:00Z)");if(u<=Date.now())throw new g("bad_time",`Database.$access: a relationship is given until a moment still to come: ${new Date(u).toISOString()} has passed`);return u},ge=(l,u)=>{let c=[],d=[],w={},p=(x,k)=>{d.push(k),c.push(`${x} = $${d.length}`),w[x]=k};if(u?.object!==void 0&&(a(l,u.object.type),p("object_type",u.object.type),u.object.id!==void 0&&p("object_id",_(`the id of a ${u.object.type}`,u.object.id))),u?.relation!==void 0){if(typeof u.relation!="string")throw new g("not_kept","Database.$access: a relation is its name");p("relation",u.relation)}if(u?.subject!==void 0){let x=ye(l,u.subject);p("subject_type",x.type),p("subject_id",x.id)}let h=u?.limit??100;if(!Number.isSafeInteger(h)||h<1||h>1e3)throw new g("bad_id","Database.$access: limit is a whole number from 1 to 1000");return{sql:c.length===0?"":`WHERE ${c.join(" AND ")}`,params:d,limit:h,columns:w}},P=l=>`to_char(${l} AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"')`,he=l=>async(u,c,d,w)=>{let p=s();R(l);let h=b(p,u),x=ye(p,d);Ve(p,h,c,x);let k=w?.by;if(k!==void 0&&(typeof k!="string"||k===""||k.length>S))throw new g("bad_id",`Database.$access: by is who did it \u2014 a string of at most ${S} characters`);if(l==="revoke"&&w?.until!==void 0)throw new g("bad_time","Database.$access: until is a grant's \u2014 a relationship is taken at once");let ne=l==="grant"?Fe(w?.until):void 0;return r?r.change(l,h,c,x,k,ne):(l==="grant"?await m(`SELECT ${$(p.schema)}.grant($1, $2, $3, $4, $5, $6, $7::timestamptz) AS v`,[h.type,h.id,c,Z(x),x.id,k??null,ne===void 0?null:new Date(ne).toISOString()]):await m(`SELECT ${$(p.schema)}.revoke($1, $2, $3, $4, $5, $6) AS v`,[h.type,h.id,c,Z(x),x.id,k??null]))[0]?.v===!0};return{async can(l,u){let c=s(),d=b(c,u);return f(c,d.type,l),ee(c,d.type,l)?!1:r?Q(r,p=>r.check(p,l,d.type,d.id)):(await m(`SELECT ${$(c.schema)}.can($1, $2, $3) AS v`,[l,d.type,d.id]))[0]?.v===!0},async objects(l,u){let c=s();return f(c,u,l),ee(c,u,l)?[]:r?Q(r,w=>r.objects(w,l,u)):(await m(`SELECT o AS id FROM ${$(c.schema)}.my_objects($1, $2) AS o ORDER BY 1`,[l,u])).map(w=>w.id)},async held(l){let u=s(),c=b(u,l),d=[...a(u,c.type).names].filter(p=>!ee(u,c.type,p)).sort();return d.length===0?[]:r?Q(r,p=>d.filter(h=>r.check(p,h,c.type,c.id))):(await m(`SELECT name FROM unnest($1::text[]) AS name WHERE ${$(u.schema)}.can(name, $2, $3) ORDER BY 1`,[d,c.type,c.id])).map(p=>p.name)},async check(l,u,c){let d=s();R("check");let w=X(l),p=b(d,c);return f(d,p.type,u),r?r.check(w,u,p.type,p.id):(await m(`SELECT ${$(d.schema)}.check($1, $2, $3, $4) AS v`,[w,u,p.type,p.id]))[0]?.v===!0},async objectsOf(l,u,c){let d=s();R("objectsOf");let w=X(l);return f(d,c,u),r?r.objects(w,u,c):(await m(`SELECT o AS id FROM ${$(d.schema)}.objects($1, $2, $3) AS o ORDER BY 1`,[w,u,c])).map(h=>h.id)},async subjects(l,u){let c=s();R("subjects");let d=b(c,u);return f(c,d.type,l),r?r.subjects(l,d.type,d.id):(await m(`SELECT s AS id FROM ${$(c.schema)}.subjects($1, $2, $3) AS s ORDER BY 1`,[l,d.type,d.id])).map(p=>p.id)},async openTo(l,u){let c=s();R("openTo");let d=b(c,u);return f(c,d.type,l),r?r.open(l,d.type,d.id):(await m(`SELECT ${$(c.schema)}.open($1, $2, $3) AS v`,[l,d.type,d.id]))[0]?.v??null},async sweep(l){s(),R("sweep");let u=l?.limit??1e4;if(!Number.isSafeInteger(u)||u<1||u>1e4)throw new g("bad_id","Database.$access: limit is a whole number from 1 to 10,000");if(r)return r.sweep(u);let c=await m("SELECT access.sweep($1::int)::text AS v",[u]);return Number(c[0]?.v??0)},grant:he("grant"),revoke:he("revoke"),async relationships(l){let u=s();R("relationships");let c=ge(u,l);if(r)return r.relationships(c.columns,c.limit);let d="(expires_at IS NULL OR expires_at > pg_catalog.statement_timestamp())";return(await m(`SELECT object_type, object_id, relation, subject_type, subject_id, ${P("created_at")} AS since, ${P("expires_at")} AS until FROM access.relationships ${c.sql===""?`WHERE ${d}`:`${c.sql} AND ${d}`} ORDER BY object_type, object_id, relation, subject_type, subject_id LIMIT ${c.limit}`,c.params)).map(p=>({object:{type:p.object_type,id:p.object_id},relation:p.relation,subject:{type:p.subject_type,id:p.subject_id},since:p.since,until:p.until}))},async history(l){let u=s();R("history");let c=ge(u,l);return r?r.history(c.columns,c.limit):(await m(`SELECT ${P("at")} AS at, action, object_type, object_id, relation, subject_type, subject_id, actor, ${P("expires_at")} AS until FROM access.past ${c.sql} ORDER BY past.at DESC, id DESC NULLS FIRST LIMIT ${c.limit}`,c.params)).map(w=>({at:w.at,action:w.action,object:{type:w.object_type,id:w.object_id},relation:w.relation,subject:{type:w.subject_type,id:w.subject_id},by:w.actor,until:w.until}))}}}var Je=Symbol.for("palbase.data"),Xe=globalThis,v=Xe[Je]??=new WeakSet;function Te(e){return e instanceof Date||ArrayBuffer.isView(e)||e instanceof ArrayBuffer}function je(e){let n=[e];for(;n.length>0;){let t=n.pop();if(!(typeof t!="object"||t===null||v.has(t)||Te(t))){v.add(t);for(let o of Array.isArray(t)?t:Object.values(t))n.push(o)}}return e}function N(e){return typeof e=="object"&&e!==null&&v.has(e)}function Ze(e){if(!Array.isArray(e))return e;for(let n of e)if(!(typeof n!="object"||n===null))for(let t of Object.values(n))typeof t=="object"&&t!==null&&je(t);return e}function E(e,n){return N(e)&&v.add(n),n}function An(e,n,t){if(!N(e))return;let o=`is data \u2014 sent by a request or read from a row \u2014 and ${t} is written in code: data gives values. Build it in code around the values you checked.`;throw ke(new $e({fields:[{field:n,message:o}]},`${n} ${o}`))}var se=Symbol.for("palbase.db.ref"),Pe=Symbol.for("palbase.tx.expr");function D(e,n){return Object.defineProperty(e,se,{value:n,enumerable:!1}),e}function j(e){if(!(typeof e!="object"||e===null))return Object.hasOwn(e,se)?e[se]:void 0}function W(e){return j(e)==="col"&&typeof e.$col=="string"}function T(e){if(j(e)!=="sql")return!1;let n=e.$sql;return n!==void 0&&Array.isArray(n.text)&&Array.isArray(n.values)}function On(e){if(j(e)!=="ref")return!1;let n=e.$ref;return n!==void 0&&typeof n.op=="number"&&typeof n.field=="string"}function Sn(e){if(j(e)!=="expr")return!1;let n=e.$expr;return n!==void 0&&(n.fn==="inc"||n.fn==="dec"||n.fn==="now")}function En(e){if(typeof e!="object"||e===null||j(e)!==void 0)return!1;let n=e.$ref;return n!==void 0&&typeof n=="object"&&n!==null}function Pn(e){if(typeof e!="object"||e===null||j(e)!==void 0||ie(e))return null;let n=e;return typeof n.$col=="string"?"col":n.$sql!==void 0&&typeof n.$sql=="object"&&n.$sql!==null?"sql":n.$expr!==void 0&&typeof n.$expr=="object"&&n.$expr!==null?"expr":null}function ie(e){if(typeof e!="object"&&typeof e!="function"||e===null)return!1;try{return e[Pe]!==void 0}catch{return!1}}function M(e){if(!ie(e))return!1;try{let n=e[Pe];return typeof n=="object"&&n!==null&&n.fn==="now"}catch{return!1}}function _n(e,n,t,o){for(let r of t){let i=o[r];if(M(i))throw new Error(`${e}(${n}): "${r}" got now() where a value is expected. To write the server's time when a row is inserted, declare the column defaultNow(); to stamp an existing row, updateMany({ where, set: { ${r}: now() } }) or, in $transaction, tx.public.${n}.updateWhere(where, { ${r}: now() }).`);if(ie(i))throw new Error(`${e}(${n}): "${r}" got an expression handle (increment()/decrement()) where a value is expected. To add to a counter use updateMany({ where, set: { ${r}: increment(n) } }) or, in $transaction, tx.public.${n}.updateWhere(where, { ${r}: increment(n) }).`);if(W(i))throw new Error(`${e}(${n}): "${r}" got a col(). A column reference stands only in a filter; to write one column's value into another, use $query.`)}}var Qe=new Set(["gt","gte","lt","lte","neq","in","contains","icontains","startsWith","endsWith","isNull","overlaps"]),Oe={eq:'equality is written bare: { <column>: <value> } (or { <column>: col("\u2026") } to compare with a column)'};function Se(e,n,t){if(t&&!T(t))for(let[o,r]of Object.entries(t)){if(o==="OR"||o==="AND"||o==="NOT"){let s=o==="NOT"?[r]:r;if(!Array.isArray(s))throw new Error(`${e}(${n}): where.${o} must be an array`);for(let a of s){if(a===null||typeof a!="object")throw new Error(`${e}(${n}): the branches of where.${o} must be filter objects`);Se(e,n,a)}continue}if(o==="has"){if(r===null||typeof r!="object"||Array.isArray(r))throw new Error(`${e}(${n}): where.has must be a map of relations ({ <relation>: { \u2026 } })`);for(let[s,a]of Object.entries(r)){if(a===null||typeof a!="object"||Array.isArray(a))throw new Error(`${e}(${n}): where.has.${s} must be a filter object`);Se(e,n,a)}continue}if(r===void 0)throw new Error(`${e}(${n}): where.${o} is undefined \u2014 not a filter value. Bound, it is NULL, and '= NULL' matches no row, so the query would answer nothing and say nothing. Leave the key out when there is no value.`);if(r===null||typeof r!="object"||Array.isArray(r)||W(r)||M(r))continue;let i=Object.entries(r);if(i.length===0)throw new Error(`${e}(${n}): where.${o} is an empty operator object ({}) \u2014 it produces no condition, so the column would silently drop out of the filter. Leave the key out when there is no condition.`);for(let[s,a]of i){if(s==="in"){if(!Array.isArray(a))throw new Error(`${e}(${n}): where.${o}.in must be an array`);if(a.some(f=>f===void 0))throw new Error(`${e}(${n}): where.${o}.in holds undefined \u2014 bound as NULL it matches no row. Drop it when building the list.`);continue}if(Oe[s]!==void 0)throw new Error(`${e}(${n}): where.${o}.${s} is not in this filter language \u2014 ${Oe[s]}`);if(!Qe.has(s))throw new Error(`${e}(${n}): where.${o} has an unknown operator "${s}" (gt/gte/lt/lte/neq/in/contains/icontains/startsWith/endsWith/isNull/overlaps)`);if(a===void 0)throw new Error(`${e}(${n}): where.${o}.${s} is undefined \u2014 the comparison's right side would be NULL and match no row. Leave the condition out.`)}}}var en=["days","hours","minutes","seconds"],nn=2147483647,Ee=e=>typeof e=="number"||typeof e=="boolean"||e===null||e===void 0?String(e):typeof e=="string"?JSON.stringify(e.slice(0,40)):typeof e;function ae(e){if(e===null||typeof e!="object"||Array.isArray(e))return{refused:"takes a span: { days?, hours?, minutes?, seconds? }"};let n={};for(let t of Object.keys(e)){if(!en.includes(t))return{refused:`${Ee(t)} is not a unit of the span \u2014 days, hours, minutes or seconds`};let o=e[t];if(typeof o!="number"||!Number.isSafeInteger(o)||o<0||o>nn)return{refused:`${t} is a whole number, 0 or more, got ${Ee(o)}${o===void 0?" \u2014 leave the unit out instead":""}`};n[t]=o}return Object.keys(n).length===0?{refused:"was given no span \u2014 ago({}) would be now(); name days, hours, minutes or seconds, or write now()"}:{span:Object.freeze(n)}}function vn(e,n,t,o){for(let r of t)if(o[r]===void 0)throw new Error(`${e}(${n}): "${r}" is undefined \u2014 not a value to write. Write null to empty the column; leave the key out to leave the column as it is (a missing request field used to write NULL silently).`)}function _e(e,n){let o=(n!==null&&typeof n=="object"?Object.keys(n):[]).filter(i=>i!=="id");if(o.length>0)throw new Error(`update(${e}): where takes the row's id alone, not ${o.map(i=>`"${i}"`).join(", ")} \u2014 a condition beside the id would be dropped. To update the rows a filter matches, updateMany({ where, set }).`);let r=n?.id;if(typeof r!="string"&&typeof r!="number"&&typeof r!="bigint")throw new Error(`update(${e}): where needs the row's id, one value \u2014 { where: { id }, set }. To update the rows a filter matches, updateMany({ where, set }).`);return String(r)}var U=class extends Error{constructor(n){super(n),this.name="TxRefError"}},y=class extends Error{constructor(n){super(n),this.name="TxPlanError"}},I=Symbol.for("palbase.tx.expr"),K=Symbol.for("palbase.tx.ref"),L=Symbol.for("palbase.tx.row"),Me=Symbol.for("palbase.tx.rows"),le=["then","valueOf","toString","toJSON",Symbol.toPrimitive];function de(e,n,t){let o=typeof e=="symbol"?e.description??String(e):e;throw new U(`${n} was used as a value (via \`${o}\`). Nothing in a transaction callback has run yet, so there is no value to read. ${t}`)}function Mn(){return H({fn:"now"})}function Cn(e){let n=ae(e);if("refused"in n)throw new y(`ago() ${n.refused}`);return H(Object.freeze({fn:"now",minus:n.span}))}function Ce(e,n){if(e.fn!=="now"||e.minus===void 0)return;let t=ae(e.minus);if("refused"in t)throw new y(`\`${n}\`: ago() ${t.refused}`)}function In(e){return Ie(e,"increment"),H({fn:"inc",by:e})}function Kn(e){return Ie(e,"decrement"),H({fn:"dec",by:e})}function Ie(e,n){if(typeof e=="string"){if(!/^-?\d+(\.\d+)?$/.test(e))throw new y(`${n}() takes a decimal number as text, got "${e}" \u2014 "12", "12.50"`)}else if(typeof e!="number"||!Number.isFinite(e))throw new y(`${n}() needs a finite number, got ${String(e)}`);if(typeof e=="string"?e.trimStart().startsWith("-"):e<0){let o=n==="increment"?"decrement":"increment";throw new y(`${n}() takes no negative amount ("${String(e)}"). Use ${o}() for the other direction \u2014 a sign kept in the amount is seen by no code that reads the direction.`)}}function Ln(e){return G(e)}function H(e){return new Proxy({[I]:e},{get(n,t){if(t===I)return n[I];le.includes(t)&&de(t,"A plan expression","Write it into an operation instead.")}})}function tn(e,n){let t={[K]:{op:e,field:n}};return new Proxy(t,{get(o,r){if(r===K)return o[K];le.includes(r)&&de(r,`\`${n}\` of a row this transaction has not written yet`,"Pass it to another operation in the same plan, or return it from the callback and read it after `$transaction` resolves.")}})}function rn(e){let n={[L]:e};return new Proxy(n,{get(t,o){if(o===L)return t[L];if(le.includes(o)&&de(o,"A row this transaction has not written yet","Read one of its columns to reference it, or return the row from the callback and read it after `$transaction` resolves."),typeof o!="symbol")return tn(e,o)}})}function Y(e){if(typeof e!="object"||e===null)return null;let n=e[K];return typeof n=="object"&&n!==null&&typeof n.op=="number"&&typeof n.field=="string"?n:null}function z(e){if(typeof e!="object"||e===null)return null;let n=e[L];return typeof n=="number"?n:null}function G(e){if(typeof e!="object"||e===null)return null;let n=e[I];return typeof n=="object"&&n!==null?n:null}function J(e){return typeof e=="object"&&e!==null&&e[Me]!==void 0}function on(e,n,t){let o=Y(e);if(o)return D({$ref:{op:o.op,field:o.field}},"ref");let r=G(e);if(r){if(r.fn!=="now"&&!t)throw new y(`\`${n}\`: ${r.fn}() reads the column's current value, so it is only valid in updateWhere(where, set).`);return Ce(r,n),D({$expr:r},"expr")}if(z(e)!==null)throw new y(`\`${n}\`: a row handle is not a value. Read the column you meant (e.g. \`row.id\`).`);if(J(e))throw new y(`\`${n}\`: an operation result is not a value. Declare an expectation first (\`.expectOne(err)\`) and read a column from the row.`);return Ke(e,n),e}function ue(e,n){let t=Y(e);if(t)return D({$ref:{op:t.op,field:t.field}},"ref");let o=G(e);if(o&&o.fn!=="now")throw new y(`\`${n}\`: ${o.fn}() is a WRITE expression, not a comparison \u2014 it cannot stand in a filter. Compare the column with a value or a col().`);if(M(e))return o&&Ce(o,n),e;if(z(e)!==null)throw new y(`\`${n}\`: a row handle is not a value. Read the column you meant (e.g. \`row.id\`).`);if(J(e))throw new y(`\`${n}\`: an operation result is not a value. Declare an expectation first (\`.expectOne(err)\`) and read a column from the row.`);if(Array.isArray(e))return E(e,e.map(r=>ue(r,n)));if(e!==null&&typeof e=="object"&&!(e instanceof Date)&&!W(e)&&!T(e)){let r=E(e,{});for(let[i,s]of Object.entries(e))r[i]=ue(s,n);return r}return e}function ce(e){if(T(e))return e;let n=E(e,{});for(let t of Object.keys(e).sort()){let o=e[t];if(o===void 0)throw new y(`where.${t} is undefined \u2014 not a filter value. Dropped, the condition would silently go and the filter match more rows than it reads (a missing request field looks like this). Leave the key out when there is no condition; write null for IS NULL.`);n[t]=ue(o,t)}return n}function Ke(e,n){if(!(typeof e!="object"||e===null||e instanceof Date)){if(Y(e)||G(e)||z(e)!==null||J(e))throw new y(`\`${n}\`: a plan handle is nested inside a value. It would be stored as literal JSON, not resolved. Put the reference directly in the column.`);for(let t of Array.isArray(e)?e:Object.values(e))Ke(t,n)}}function C(e,n){let t={};for(let o of Object.keys(e).sort()){let r=e[o];if(r===void 0)throw new y(`${o} is undefined \u2014 not a value to write. The key is there but its value is not, so the column would silently not be written (a missing request field looks like this). Leave the key out for the column default; write null for NULL.`);t[o]=on(r,o,n)}return t}var B=-1,q=class{[Me]=!0;guarded=!1;builder;opIndex;what;constructor(n,t,o){this.builder=n,this.opIndex=t,this.what=o}then(){throw new U(`${this.what} cannot be awaited: a transaction callback builds a plan, it does not run statements. Remove the \`await\`.`)}expectOne(n){if(this.declareGuard("one",1,n),this.opIndex===B)throw n;return rn(this.opIndex)}expectNone(n){this.declareGuard("none",0,n)}expectAtLeast(n,t){if(ve(n,"expectAtLeast"),this.declareGuard("atLeast",n,t),this.opIndex===B&&n>0)throw t}expectAtMost(n,t){ve(n,"expectAtMost"),this.declareGuard("atMost",n,t)}declareGuard(n,t,o){if(!(o instanceof Error))throw new y(`${this.what}: an expectation needs the Error to throw when it does not hold (e.g. \`.expect\u2026(new Conflict("already accepted"))\`).`);if(this.guarded)throw new y(`${this.what} already has an expectation. One operation carries one expectation; declare the second on its own operation.`);this.guarded=!0,this.opIndex!==B&&this.builder.attachGuard(this.opIndex,n,t,o)}};function ve(e,n){if(!Number.isInteger(e)||e<0)throw new y(`${n}(n) needs a non-negative integer, got ${String(e)}`)}var Ne=1e3,De=5e3,V=class{ops=[];slots=[];table(n){return{insert:t=>{let o=C(t,!1);if(Object.keys(o).length===0)throw new y(`${n}.insert() needs at least one column`);return this.push({op:"insert",table:n,values:o},`${n}.insert()`)},put:(t,o)=>{let r=C(t,!1);if(Object.keys(r).length===0)throw new y(`${n}.put() needs at least one column`);if(o.onConflict.length===0)throw new y(`${n}.put() needs at least one onConflict column`);return this.push({op:"upsert",table:n,values:r,onConflict:o.onConflict},`${n}.put()`)},insertMany:(t,o)=>{if(t.length===0)return new q(this,B,`${n}.insertMany()`);if(t.length>De)throw new y(`${n}.insertMany() has ${t.length} rows; the limit is ${De}. Split the write.`);let r=t.map(i=>C(i,!1));return cn(r,n),this.push({op:"insertMany",table:n,rows:r,...an(o,n)},`${n}.insertMany()`)},updateWhere:(t,o)=>{let r=ce(t),i=C(o,!0);if(Object.keys(r).length===0&&!T(r))throw new y(`${n}.updateWhere() needs a filter. An update with no filter rewrites the whole table.`);if(Object.keys(i).length===0)throw new y(`${n}.updateWhere() needs at least one column to set`);return this.push({op:"update",table:n,set:i,where:r},`${n}.updateWhere()`)},deleteWhere:t=>{let o=ce(t);if(Object.keys(o).length===0&&!T(o))throw new y(`${n}.deleteWhere() needs a filter. A delete with no filter empties the table.`);return this.push({op:"delete",table:n,where:o},`${n}.deleteWhere()`)},select:(t,o)=>{let r={op:"select",table:n},i=ce(t??{});if((Object.keys(i).length>0||T(i))&&(r.where=i),o?.limit!==void 0){if(!Number.isInteger(o.limit)||o.limit<0)throw new y(`${n}.select(): limit needs a non-negative integer, got ${String(o.limit)}`);r.limit=o.limit}return o?.lock!==void 0&&(r.lock=o.lock),this.push(r,`${n}.select()`)}}}push(n,t){if(this.ops.length>=Ne)throw new y(`this transaction has ${Ne} operations, the limit. Use insertMany() for bulk writes, or split the work.`);let o=this.ops.length;return this.ops.push(n),new q(this,o,t)}attachGuard(n,t,o,r){let i=this.ops[n];if(!i)throw new y(`internal: expectation on unknown operation ${n}`);let s=this.slots.length;this.slots.push(r),i.guard={kind:t,n:o,slot:s}}body(){return{ops:this.ops}}errorForSlot(n){return this.slots[n]??null}},sn=e=>typeof e=="string"?JSON.stringify(e.slice(0,40)):typeof e;function an(e,n){if(e===void 0)return{};if(e.action!==void 0&&e.action!=="ignore"&&e.action!=="update")throw new y(`${n}.insertMany(): a conflict's action is "ignore" or "update", not ${sn(e.action)}.`);if(e.onConflict===void 0){if(e.action!=="ignore")throw new y(`${n}.insertMany() was given a conflict action with no onConflict columns. An overwrite is matched on columns: name them \u2014 action "ignore" alone skips a collision with any unique key.`);return{action:"ignore"}}if(e.onConflict.length===0)throw new y(`${n}.insertMany() was given an empty onConflict list. A collision is matched on columns: name them, or leave onConflict out with action "ignore" to skip a collision with any unique key.`);return{onConflict:e.onConflict,action:e.action??"ignore"}}function cn(e,n){let t=e[0];if(!t)return;let o=Object.keys(t),r=o.join(",");for(let i=1;i<e.length;i++){let s=Object.keys(e[i]);if(s.join(",")!==r)throw new y(`${n}.insertMany(): every row must set the same columns. Row 0 sets [${o.join(", ")}] but row ${i} sets [${s.join(", ")}]. (A property set to \`undefined\` counts as absent \u2014 use \`null\`.)`)}}function F(e,n){let t=Y(e);if(t){let r=We(n,t.op,`\`${t.field}\``);if(!(t.field in r))throw new y(`the transaction's operation ${t.op} returned no column \`${t.field}\`.`);return r[t.field]}let o=z(e);if(o!==null)return We(n,o,"a row");if(J(e))throw new y("an operation result cannot be returned from a transaction callback: its row count is not known until the plan runs. Declare an expectation (`.expectOne(err)`) and return the row, or a column of it.");if(Array.isArray(e))return e.map(r=>F(r,n));if(un(e)){let r={};for(let[i,s]of Object.entries(e))r[i]=F(s,n);return r}return e}function We(e,n,t){let o=e[n];if(!o)throw new y(`the transaction returned no result for operation ${n}, so ${t} cannot be read.`);let r=o.rows[0];if(!r)throw new y(`the transaction's operation ${n} returned no row, so ${t} cannot be read.`);return r}function un(e){if(typeof e!="object"||e===null)return!1;let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}async function Le(e,n,t,o){let r=o(n),i=t.body();if(i.ops.length===0)return F(r,[]);let s;try{s=await e.txPlan(i)}catch(a){throw ln(a,t)}return F(r,s.results)}function ln(e,n){if(typeof e!="object"||e===null)return e;let t=e;return t.error_code!=="tx_guard_failed"||typeof t.slot!="number"?e:n.errorForSlot(t.slot)??e}import{AsyncLocalStorage as dn}from"node:async_hooks";function Be(e){let n=e??0;if(!Number.isInteger(n)||n<0||n>10)throw new Error("transaction retry must be an integer between 0 and 10");return n}function Un(e){if(Be(e.retry),e.isolation!==void 0&&!["read committed","repeatable read","serializable"].includes(e.isolation))throw new Error("transaction isolation must be read committed, repeatable read or serializable");if(e.readOnly!==void 0&&typeof e.readOnly!="boolean")throw new Error("transaction readOnly must be a boolean");for(let n of["lockTimeoutMs","statementTimeoutMs","timeoutMs"]){let t=e[n];if(t!==void 0&&(!Number.isInteger(t)||t<1||t>2147483647))throw new Error(`transaction ${n} must be a positive integer in milliseconds`)}if(e.signal!==void 0&&(typeof e.signal.aborted!="boolean"||typeof e.signal.addEventListener!="function"))throw new Error("transaction signal must be an AbortSignal")}function Ue(e){if(Be(e?.retry)!==0)throw new Error("Database.$transaction is a savepoint plan on the request transaction and cannot retry its snapshot or COMMIT. Use Database.$atomic(async tx => { ... }, { retry, isolation }) and put all decision reads and writes inside that callback.")}function qn(e){if(e){if(e.returning!==void 0&&typeof e.returning!="boolean")throw new Error("insertMany returning must be a boolean");if(e.action!==void 0&&e.action!=="ignore"&&e.action!=="update")throw new Error("insertMany action must be ignore or update");if(e.onConflict!==void 0&&(!Array.isArray(e.onConflict)||e.onConflict.some(n=>typeof n!="string"||n.length===0)))throw new Error("insertMany onConflict must be an array of column names");if(e.action==="update"&&!e.onConflict?.length)throw new Error('insertMany action "update" overwrites the row a collision is matched on: name its columns in onConflict');if(e.action==="ignore"&&e.onConflict!==void 0&&e.onConflict.length===0)throw new Error('insertMany onConflict is an empty list: name the columns a collision is matched on, or leave it out \u2014 action "ignore" alone skips a collision with any unique key')}}function fn(e,n){return new Proxy({},{get(t,o){if(typeof o!="string")return;let r=`${n}${o}`;return{insert:i=>e().insert(r,i),insertMany:(i,s)=>e().insertMany(r,i,s),aggregate:i=>e().aggregate(r,i),update:i=>e().update(r,_e(r,i.where),i.set),delete:i=>e().delete(r,i),findById:i=>e().findById(r,i),findUnique:i=>e().findUnique(r,i.where,{select:i.select,with:i.with,lock:i.lock}),page:i=>{let{where:s,...a}=i??{};return e().page(r,s,a)},findMany:i=>{let{where:s,...a}=i??{};return e().findMany(r,s,a)},put:i=>e().put(r,i.data,{onConflict:i.onConflict}),updateMany:i=>e().updateMany(r,i.where,i.set,i.returning===void 0?void 0:{returning:i.returning}),deleteMany:i=>e().deleteMany(r,i.where),count:i=>e().count(r,i?.where),claim:(i,s)=>e().claim(r,i,s),search:(i,s)=>e().search(r,i,s)}}})}function qe(e,n=""){return new Proxy({},{get(t,o){if(typeof o=="string")return e.table(n+o)}})}function pn(e){let n=qe(e);return new Proxy({},{get(t,o){if(typeof o=="string")return o==="public"?n:qe(e,oe(o,""))}})}function we(e,n,t,o={}){let i=Object.assign({$query:(s,a)=>e().query(s,a),$diagnostics:()=>e().diagnostics(),$insert:(s,a)=>e().insert(s,a),$insertMany:((s,a,f)=>e().insertMany(s,a,f)),$update:(s,a,f)=>e().update(s,a,f),$delete:(s,a)=>e().delete(s,a),$findById:(s,a)=>e().findById(s,a),$findUnique:(s,a,f)=>e().findUnique(s,a,f),$page:(s,a,f)=>e().page(s,a,f),$findMany:(s,a,f)=>e().findMany(s,a,f),$put:(s,a,f)=>e().put(s,a,f),$updateMany:(s,a,f,b)=>e().updateMany(s,a,f,b),$deleteMany:(s,a)=>e().deleteMany(s,a),$count:(s,a)=>e().count(s,a),$search:(s,a,f)=>e().search(s,a,f),$aggregate:(s,a)=>e().aggregate(s,a),$claim:(s,a,f)=>e().claim(s,a,f),$lockRows:(s,a)=>e().lockRows(s,a),$lockRowsWhere:(s,a,f)=>e().lockRowsWhere(s,a,f),$advisoryXactLock:s=>e().advisoryXactLock(s)},o,{$access:Ae(e,t.names,t.as,t.unanswered,t.via),$atomic(s,a){let f=e();if(typeof f.atomic!="function")throw new Error("Database.$atomic owns one transaction and identity; nested roots and $asService are not allowed");return f.atomic(b=>n(b,()=>s(we(()=>b,n,t))),a)},$attempt:s=>e().attempt(s),$transaction(s,a){Ue(a);let f=new V;return Le(e(),pn(f),f,s)}});return new Proxy(i,{get(s,a,f){return typeof a=="string"&&!a.startsWith("$")&&!(a in s)?fn(e,oe(a,"")):Reflect.get(s,a,f)}})}var fe=new dn,pe=()=>{throw new Error("Database.$atomic owns one transaction and identity; nested roots and $asService are not allowed")};function Xn(e,n={}){let t={names:n.access,as:n.as??"service",...n.unanswered===void 0?{}:{unanswered:n.unanswered},...n.via===void 0?{}:{via:n.via}},o={},r=()=>{let f=fe.getStore();return f?.owner===o?f.tx:e},i=(f,b)=>fe.run({owner:o,tx:Object.assign(Object.create(null),f,{atomic:pe,asService:pe})},b),s=new Proxy(Object.create(null),{get:()=>()=>{throw new Error("Database inside $asService().$atomic: the shared Database would bypass the caller's row-level security there \u2014 use the handle the callback is given")}}),a=(f,b)=>fe.run({owner:o,tx:s},b);return we(r,i,t,{$asService(){let f=r();if(typeof f.asService!="function")return pe();let b=f.asService();return we(()=>b,a,{...t,as:"service"})}})}export{g as a,He as b,mn as c,ze as d,Te as e,je as f,N as g,Ze as h,E as i,An as j,D as k,W as l,T as m,On as n,Sn as o,En as p,Pn as q,ie as r,M as s,_n as t,Se as u,ae as v,vn as w,U as x,y,Mn as z,Cn as A,In as B,Kn as C,Ln as D,Be as E,Un as F,qn as G,Xn as H};
@@ -1,4 +1,4 @@
1
- /*! palgres 0.76.0 — Palbase SDK License (see LICENSE) */
1
+ /*! palgres 0.77.0 — Palbase SDK License (see LICENSE) */
2
2
  var R=Symbol.for("palbase.backend.httpError"),b=Symbol.for("palbase.backend.engineRaised"),a=Object.freeze({uniqueViolation:"23505",foreignKeyViolation:"23503",serializationFailure:"40001",deadlockDetected:"40P01",queryCancelled:"57014",lockNotAvailable:"55P03",inFailedTransaction:"25P02",insufficientPrivilege:"42501"}),i=class extends Error{[R]=!0;status;error;errorDescription;data;retryAfter;constructor(t,o,n,r,s){super(n),this.name="HttpError",this.status=t,this.error=o,this.errorDescription=n,r!==void 0&&(this.data=r),s!==void 0&&(this.retryAfter=s)}};function O(e){return e[b]=!0,e}function q(e){return typeof e=="object"&&e!==null&&e[b]===!0}function c(e){let t=e.replace(/([a-z0-9])([A-Z])/g,"$1 $2");return t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()}var g=class extends i{constructor(t,o){super(400,"bad_request",o??c("BadRequest"),t),this.name="BadRequest"}},E=class extends i{constructor(t,o,n){super(404,o??"not_found",t??c("NotFound"),n),this.name="NotFound"}},l=class extends i{constructor(t,o,n){super(409,o??"conflict",t??c("Conflict"),n),this.name="Conflict"}},p=class extends l{constraint;sqlstate=a.uniqueViolation;static is(t){return typeof t=="object"&&t!==null&&t.name==="UniqueViolation"&&typeof t.constraint=="string"}constructor(t,o,n,r){super(o??"Unique constraint violated",n??"unique_violation",r),this.name="UniqueViolation",this.constraint=t}};function x(e){if(typeof e!="object"||e===null||e.retryable!==!0)return!1;let t=e.sqlstate;return t===a.serializationFailure||t===a.deadlockDetected}var y=class extends l{retryable=!0;sqlstate;static is(t){return typeof t=="object"&&t!==null&&t.name==="SerializationFailure"}constructor(t=a.serializationFailure,o,n){super(o??"the transaction could not be serialized with a concurrent one \u2014 run it again from the start (put the reads a decision rests on and its writes in $atomic, with { retry: n })","serialization_failure",n),this.name="SerializationFailure",this.sqlstate=t}},m=class extends l{retryable=!0;sqlstate;static is(t){return typeof t=="object"&&t!==null&&t.name==="DeadlockDetected"}constructor(t=a.deadlockDetected,o,n){super(o??"deadlock: two transactions waited on each other's locks and this one was cancelled \u2014 take locks in one order: Database.$lockRows(table, ids) when you have the ids, Database.$lockRowsWhere(table, filter) when you have a filter","deadlock_detected",n),this.name="DeadlockDetected",this.sqlstate=t}},w=class extends Error{sqlstate=a.inFailedTransaction;static is(t){return typeof t=="object"&&t!==null&&t.name==="TransactionAborted"}constructor(t,o){super(t,{cause:o}),this.name="TransactionAborted"}},k=class extends i{constructor(t,o){super(429,"too_many_requests",o??c("TooManyRequests"),t,t.retryAfter),this.name="TooManyRequests"}};function h(e){let t=e,o=n=>typeof n=="string"&&/^[0-9A-Z]{5}$/.test(n);if(o(t?.code))return t.code;if(o(t?.errno))return t.errno}var _=new Set(["57P03","53300","08001","08004","ERR_POSTGRES_CONNECTION_REFUSED","ERR_POSTGRES_CONNECTION_FAILED","ERR_POSTGRES_CONNECTION_TIMEOUT","ECONNREFUSED","CONNECT_TIMEOUT"]),N=new Set(["57P01","57P02","08000","08003","08006","08007","08P01","ERR_POSTGRES_CONNECTION_CLOSED","CONNECTION_CLOSED","CONNECTION_DESTROYED","ECONNRESET","ETIMEDOUT","EPIPE"]);function D(e){let t=e;for(let o=0;o<4&&typeof t=="object"&&t!==null;o++){let n=h(t),r=t.code,s=f=>n!==void 0&&f.has(n)||typeof r=="string"&&f.has(r);if(s(N))return"lost";if(s(_))return"never";t=t.cause}}function C(e){let t=e;for(let o=0;o<4&&typeof t=="object"&&t!==null;o++){let n=t.sqlstate,r=h(t)??(typeof n=="string"?n:void 0);if(r!==void 0)return!r.startsWith("08")&&!/^57P0[123]$/.test(r);t=t.cause}return!1}function A(e){let t=e,o=t?.constraint??t?.constraint_name;if(typeof o=="string"&&o.length>0)return o;let n=String(e?.message??"");return/violates unique constraint "([^"]+)"/.exec(n)?.[1]??""}var u=e=>`"${e.replace(/"/g,'""')}"`,L=(e,t)=>`${u(e)}.${u(t)}`,P=e=>`'${e.replace(/'/g,"''")}'`;function $(e){if(e.includes("\0"))throw new TypeError("a NUL character cannot be sent to Postgres");return`E'${e.replace(/\\/g,"\\\\").replace(/'/g,"''")}'`}var F=e=>e.map(u).join(", "),T=new Set(["now","current_timestamp","current_date","current_time","localtimestamp","localtime","transaction_timestamp","statement_timestamp"]);function z(e){return[...d(e)].some(t=>t.call&&!T.has(t.name.toLowerCase()))}function*d(e){let t=0;for(;t<e.length;){let o=e[t];if(o==="'"){for(t++;t<e.length;)if(e[t]==="'"&&e[t+1]==="'")t+=2;else{if(e[t]==="'")break;t++}t++;continue}if(o==="$"){let n=/^\$[A-Za-z_]*\$/.exec(e.slice(t));if(n){let r=e.indexOf(n[0],t+n[0].length);t=r<0?e.length:r+n[0].length;continue}}if(o==='"'){let n=t+1,r="";for(;n<e.length;)if(e[n]==='"'&&e[n+1]==='"')r+='"',n+=2;else{if(e[n]==='"')break;r+=e[n++]}let s=n+1;yield{start:t,end:s,name:r,quoted:!0,call:/^\s*\(/.test(e.slice(s))},t=s;continue}if(/[A-Za-z_]/.test(o)&&(t===0||!/[A-Za-z0-9_$]/.test(e[t-1]))){let n=/^[A-Za-z_][A-Za-z0-9_$]*/.exec(e.slice(t)),r=t+n[0].length;yield{start:t,end:r,name:n[0],quoted:!1,call:/^\s*\(/.test(e.slice(r))},t=r;continue}t++}}function M(e,t){for(let o of d(e))if(!o.call&&(o.quoted?o.name===t:o.name.toLowerCase()===t.toLowerCase()))return!0;return!1}function j(e,t){if(t.size===0)return e;let o="",n=0;for(let r of d(e)){if(r.call)continue;let s=t.get(r.quoted?r.name:S(t,r.name)??"");s!==void 0&&(o+=e.slice(n,r.start)+u(s),n=r.end)}return o+e.slice(n)}function S(e,t){if(e.has(t))return t;let o=t.toLowerCase();for(let n of e.keys())if(n.toLowerCase()===o)return n}var U=e=>`(NOT EXISTS (SELECT 1 FROM unnest(i.indclass::oid[]) AS oc(oid) JOIN pg_catalog.pg_opclass o ON o.oid = oc.oid WHERE NOT o.opcdefault)
3
3
  AND NOT i.indnullsnotdistinct AND ${e}.reloptions IS NULL
4
4
  AND NOT EXISTS (SELECT 1 FROM unnest(i.indcollation::oid[], i.indkey::int2[]) AS x(coll, att) JOIN pg_catalog.pg_attribute a ON a.attrelid = i.indrelid AND a.attnum = x.att WHERE x.att > 0 AND x.coll <> a.attcollation))`;export{u as a,L as b,P as c,$ as d,F as e,z as f,M as g,j as h,U as i,R as j,b as k,a as l,i as m,O as n,q as o,g as p,E as q,l as r,p as s,x as t,y as u,m as v,w,k as x,h as y,_ as z,N as A,D as B,C,A as D};
@@ -1,4 +1,4 @@
1
- /*! palgres 0.76.0 — Palbase SDK License (see LICENSE) */
1
+ /*! palgres 0.77.0 — Palbase SDK License (see LICENSE) */
2
2
  import{createHash as Zn}from"node:crypto";function Js(t){return`${t}_lookup`}function zs(t,e){let n=o=>o==="cascade"||o==="set null"||o==="set default";return n(t)||n(e)}var pn=class extends Error{problems;constructor(e){super(`the schema is not valid:
3
3
  - ${e.join(`
4
4
  - `)}`),this.name="SchemaError",this.problems=e}},Qs=()=>({tables:[],enums:[],extensions:[],raw:[]}),_e=t=>`${t.schema}.${t.name}`,es={int:"integer",int4:"integer",int2:"smallint",int8:"bigint",float4:"real",float8:"double precision",bool:"boolean",timestamptz:"timestamp with time zone",timestamp:"timestamp without time zone","timestamp without time zone":"timestamp without time zone",timetz:"time with time zone",time:"time without time zone",varchar:"character varying",char:"character",decimal:"numeric"};function St(t){let e=t.trim().replace(/\s+/g," "),n="";for(;e.endsWith("[]");)n+="[]",e=e.slice(0,-2).trim();let o=/^((?:"(?:[^"]|"")+"|[A-Za-z_][A-Za-z0-9_ ]*?)(?:\.(?:"(?:[^"]|"")+"|[A-Za-z_][A-Za-z0-9_]*))?)\s*(\(.*\))?$/.exec(e);if(!o)return t.trim()+n;let a=o[2]?o[2].replace(/\s+/g,""):"",i=ts(o[1]);return i===void 0?t.trim()+n:i.length===1&&i[0].quoted?`"${i[0].name.replace(/"/g,'""')}"${a}${n}`:i.length===1?`${es[i[0].name]??i[0].name}${a}${n}`:`${i.map(d=>Ot(d.name)).join(".")}${a}${n}`}var Ot=t=>/^[a-z_][a-z0-9_$]*$/.test(t)?t:`"${t.replace(/"/g,'""')}"`,Zs=(t,e)=>`${Ot(t)}.${Ot(e)}`;function ts(t){let e=[],n=0;for(;n<t.length;){if(t[n]==='"'){let o=n+1,a="";for(;;){if(o>=t.length)return;if(t[o]==='"'){if(t[o+1]==='"'){a+='"',o+=2;continue}break}a+=t[o++]}e.push({name:a,quoted:!0}),n=o+1}else{let o=/^[A-Za-z_][A-Za-z0-9_ ]*/.exec(t.slice(n));if(!o)return;e.push({name:o[0].trim().toLowerCase(),quoted:!1}),n+=o[0].length}if(n<t.length){if(t[n]!==".")return;n++}}return e}var ns=/^[A-Za-z_][A-Za-z0-9_$]*$/,ss=63;function ye(t,e,n=!1){if(typeof e!="string"||e==="")return`${t} has no name`;if(n?e.includes("\0"):!ns.test(e))return`${t} "${e}": a name is letters, digits and _ (starting with a letter or _)`;if(Buffer.byteLength(e)>ss)return`${t} "${e}": longer than Postgres' 63 bytes, it would be cut`;if(e.startsWith("palgres_")||e.startsWith("_palgres"))return`${t} "${e}": names starting with palgres_ are Palgres' own`}var os="vector",un=["cosine","euclidean","inner_product"],It=1536,rs=2e3,wt=4e3,is=/^(text|citext|public\.citext|character varying(\(\d+\))?)$/;function Ct(t,e,n){let o=[];e.primaryKey.length!==1&&o.push(`${t} declares search and has ${e.primaryKey.length===0?"no primary key":`a primary key of ${e.primaryKey.length} columns`}: a row's vector is kept by its key \u2014 give the table a single-column primary key (uuid().primaryKey())`),(!Array.isArray(n.from)||n.from.length===0)&&o.push(`${t}: search.from is empty \u2014 name the text columns a row is found by (search: { from: ['title', 'body'], model })`);let a=new Set;for(let i of Array.isArray(n.from)?n.from:[]){a.has(i)&&o.push(`${t}: search.from names "${i}" twice \u2014 name each column once`),a.add(i);let d=e.columns.find(p=>p.name===i);d?d.ignored?o.push(`${t}: search.from names "${i}", which is ignored \u2014 take it out of search.from, or keep the column`):is.test(St(d.type))?d.generated&&o.push(`${t}: search.from names "${i}", a generated column \u2014 no write names it, so nothing would say when to embed the row again: name the columns it is computed from`):o.push(`${t}: search.from names "${i}", which is ${d.type} \u2014 search reads text (text, varchar, citext): name a text column, or keep the text in one`):o.push(`${t}: search.from names "${i}", which the table does not have \u2014 name its text columns`)}return(typeof n.model!="string"||n.model.trim()==="")&&o.push(`${t}: search.model is empty \u2014 name the embedding model (search: { from, model: 'embedding' })`),un.includes(n.metric)||o.push(`${t}: search.metric is ${JSON.stringify(n.metric)} \u2014 it is ${un.map(i=>`'${i}'`).join(", ")}`),(!Number.isInteger(n.dimensions)||n.dimensions<1||n.dimensions>wt)&&o.push(`${t}: search.dimensions is ${String(n.dimensions)} \u2014 it is 1 to ${wt}: pgvector indexes a vector of at most ${rs} dimensions and a half-precision one of at most ${wt}; ask the model for fewer (search: { dimensions: ${It} })`),n.staleness!=="null"&&n.staleness!=="keep"&&o.push(`${t}: search.staleness is ${JSON.stringify(n.staleness)} \u2014 it is 'null' (a changed row is not found by its old meaning) or 'keep' (it is, until embedded again)`),e.columns.some(i=>i.name==="_score"&&!i.ignored)&&o.push(`${t} declares search and has a column "_score": search() answers each row with its _score \u2014 rename the column`),o}function eo(t){let e=[],n=p=>p&&e.push(p),o=new Map,a=new Map,i=(p,u,b)=>{let D=`${p}.${u}`,W=a.get(D);W?e.push(`${b} "${u}" has the name of ${W} in schema ${p}`):a.set(D,b)};for(let p of t.enums)n(ye("an enum",p.name)),p.values.length===0&&e.push(`enum ${p.schema}.${p.name} has no values`),new Set(p.values).size!==p.values.length&&e.push(`enum ${p.schema}.${p.name} names a value twice`);for(let p of t.tables){let u=_e(p);n(ye("a schema",p.schema)),n(ye("a table",p.name)),o.has(u)&&e.push(`table ${u} is declared twice`),o.set(u,p),i(p.schema,p.name,`table ${u}`);let b=new Map,D=(N,G)=>{let te=b.get(N);te?e.push(`${G} "${N}" has the name of a ${te} of table ${u}`):b.set(N,G)},W=new Map;for(let N of p.columns)n(ye(`column ${u}.${N.name}`,N.name)),W.has(N.name)&&e.push(`column ${u}.${N.name} is declared twice`),W.set(N.name,N),N.identity&&N.default!==void 0&&e.push(`column ${u}.${N.name}: an identity column has no default`),N.generated&&(N.default!==void 0||N.identity||N.fill!==void 0)&&e.push(`column ${u}.${N.name}: a generated column has no default, identity or fill`),N.generated&&!N.generated.expr.trim()&&e.push(`column ${u}.${N.name}: a generated column's expression is empty`),N.identity&&!["smallint","integer","bigint"].includes(St(N.type))&&e.push(`column ${u}.${N.name}: an identity column is smallint, integer or bigint`),N.identity&&N.nullable&&e.push(`column ${u}.${N.name}: an identity column is NOT NULL`);let H=(N,G)=>{let te=W.get(N);te?te.ignored&&e.push(`${G} names column "${N}", which is ignored`):e.push(`${G} names column "${N}", which ${u} does not have`)};for(let N of p.primaryKey)H(N,`the primary key of ${u}`);for(let N of p.primaryKey)W.get(N)?.nullable&&e.push(`column ${u}.${N} is in the primary key, so it is not nullable`);for(let N of p.uniques){n(ye(`a unique constraint of ${u}`,N.name,!0)),i(p.schema,N.name,`unique constraint ${u}.${N.name}`),D(N.name,"unique constraint"),N.columns.length===0&&e.push(`unique constraint ${N.name} names no column`);for(let G of N.columns)H(G,`unique constraint ${N.name}`)}for(let N of p.indexes){n(ye(`an index of ${u}`,N.name,!0)),i(p.schema,N.name,`index ${u}.${N.name}`),N.keys.length===0&&e.push(`index ${N.name} has no key`);for(let G of N.keys)"column"in G&&H(G.column,`index ${N.name}`);for(let G of N.include??[])H(G,`index ${N.name}`)}for(let N of p.checks)n(ye(`a check of ${u}`,N.name,!0)),D(N.name,"check"),N.expr.trim()||e.push(`check ${N.name} has no expression`);for(let N of p.foreignKeys){n(ye(`a foreign key of ${u}`,N.name,!0)),D(N.name,"foreign key"),(N.columns.length===0||N.columns.length!==N.refColumns.length)&&e.push(`foreign key ${N.name} names ${N.columns.length} column(s) and references ${N.refColumns.length}`);for(let G of N.columns)H(G,`foreign key ${N.name}`)}let Z=new Set;for(let N of p.policies)n(ye(`a policy of ${u}`,N.name,!0)),Z.has(N.name)&&e.push(`policy ${u}.${N.name} is declared twice`),Z.add(N.name),N.to.length===0&&e.push(`policy ${u}.${N.name} names no role`),N.for==="insert"&&N.using!==void 0&&e.push(`policy ${u}.${N.name}: an insert policy has only withCheck`),(N.for==="select"||N.for==="delete")&&N.withCheck!==void 0&&e.push(`policy ${u}.${N.name}: a ${N.for} policy has only using`);p.policies.length>0&&!p.rls&&e.push(`table ${u} has policies but row-level security off: they would do nothing`),p.search!==void 0&&e.push(...Ct(`table ${u}`,p,p.search))}for(let p of t.tables)for(let u of p.foreignKeys){let b=o.get(`${u.refSchema}.${u.refTable}`);if(!b){e.push(`foreign key ${u.name} of ${_e(p)} references ${u.refSchema}.${u.refTable}, which is not declared`);continue}b.ignored&&e.push(`foreign key ${u.name} of ${_e(p)} references ${_e(b)}, which is ignored`);for(let D of u.refColumns)b.columns.some(W=>W.name===D&&!W.ignored)||e.push(`foreign key ${u.name} references ${_e(b)}.${D}, which it does not have`)}let d=new Set;for(let p of t.raw)n(ye("a raw unit",p.name)),d.has(p.name)&&e.push(`raw unit ${p.name} is declared twice`),d.add(p.name),p.sql.trim()||e.push(`raw unit ${p.name} has no SQL`),p.before&&p.table!==void 0&&e.push(`raw unit ${p.name}: before is for a schema's unit, not a table's \u2014 a table's is made after its table`);return e}function dn(t){let e=n=>[...n].sort((o,a)=>o.name<a.name?-1:o.name>a.name?1:0);return{tables:[...t.tables].map(n=>({...n,schema:n.schema||"public",columns:n.columns.map(o=>({...o,type:St(o.type)})),uniques:e(n.uniques),indexes:e(n.indexes),checks:e(n.checks),foreignKeys:e(n.foreignKeys),policies:e(n.policies).map(o=>({...o,to:[...o.to].sort()}))})).sort((n,o)=>_e(n)<_e(o)?-1:_e(n)>_e(o)?1:0),enums:[...t.enums].sort((n,o)=>`${n.schema}.${n.name}`<`${o.schema}.${o.name}`?-1:1),extensions:[...new Set([...t.extensions,...t.tables.some(n=>n.search!==void 0)?[os]:[]])].sort(),raw:e(t.raw),...t.access!==void 0?{access:t.access}:{}}}function to(t){let e=dn(t),n=new Map(t.raw.map((o,a)=>[o.name,a]));return e.raw.sort((o,a)=>(n.get(o.name)??0)-(n.get(a.name)??0)),e}function xt(t){return Array.isArray(t)?`[${t.map(xt).join(",")}]`:t&&typeof t=="object"?`{${Object.entries(t).filter(([,n])=>n!==void 0).sort(([n],[o])=>n<o?-1:1).map(([n,o])=>`${JSON.stringify(n)}:${xt(o)}`).join(",")}}`:JSON.stringify(t)}function no(t){return Zn("sha256").update(xt(dn(t))).digest("hex").slice(0,32)}var Lt=Symbol.for("palbase.table.meta"),ke=Symbol.for("palbase.ref.target"),ut=class{_def;constructor(e){if(e.trim()==="")throw new Error("foreignKey(name): a foreign key's name cannot be empty \u2014 Palbase reconciles constraints by name.");this._def={name:e,columns:[],refTable:"",refColumns:[]}}on(...e){return this._def.columns=e.map(n=>{let o=n.expr;if(o.kind!=="col")throw new Error(`foreignKey(${this._def.name}).on(): takes column references only \u2014 an expression cannot be part of a foreign key.`);return o.name}),this}references(e,...n){if(n.length===0)throw new Error(`foreignKey(${this._def.name}).references(): needs at least one target column.`);return this._def.refColumns=[...n],typeof e=="function"?(Object.defineProperty(this._def,ke,{value:()=>e()[Lt],enumerable:!1,configurable:!0}),this):(this._def.refTable=e[Lt].name,Object.defineProperty(this._def,ke,{value:e[Lt],enumerable:!1,configurable:!0}),this)}onUpdate(e){return this._def.onUpdate=e,this}onDelete(e){return this._def.onDelete=e,this}match(e){return this._def.match=e,this}index(e){if(e!==!1)throw new Error(`foreignKey(${this._def.name}).index(): only index(false) \u2014 an index is made unasked`);return this._def.index=!1,this}deferrable(e){if(e!==!1)throw new Error(`foreignKey(${this._def.name}).deferrable(): only deferrable(false) \u2014 a key with an action is deferrable unasked`);return this._def.deferrable=!1,this}};function as(t){return new ut(t)}function mn(t){let e=t instanceof ut?t._def:t;if(e.columns.length===0)throw new Error(`foreignKey(${e.name}): needs at least one local column \u2014 call .on(...).`);let n=typeof e[ke]=="function";if(e.refColumns.length===0||e.refTable===""&&!n)throw new Error(`foreignKey(${e.name}): needs the target table and its columns \u2014 call .references(...).`);if(e.columns.length!==e.refColumns.length)throw new Error(`foreignKey(${e.name}): ${e.columns.length} local column(s) (${e.columns.join(", ")}) but ${e.refColumns.length} target column(s) (${e.refColumns.join(", ")}) \u2014 the two lists must be the same length.`);return e}var w=class extends Error{code;line;constructor(e,n,o=0){super(o>0?`line ${o}: ${n}`:n),this.name="AccessError",this.code=e,this.line=o}};var re="user:*",ie="public",cs=["->","!=","<=",">=","<>",":",",","=","<",">","+","&","-","(",")",".","|","*"],En=256*1024,fn=256,gn=32;function ls(t){if(t.length>En)throw new w("too_large",`the schema is ${t.length} characters; at most ${En}`);let e=[],n=0,o=1,a=i=>{throw new w("syntax",i,o)};for(;n<t.length;){let i=t[n];if(i===`
@@ -1,2 +1,2 @@
1
- /*! palgres 0.76.0 — Palbase SDK License (see LICENSE) */
1
+ /*! palgres 0.77.0 — Palbase SDK License (see LICENSE) */
2
2
  var i=new Set(["uuid","text","integer","bigint","numeric","boolean","timestamp","date","enum"]),u={number:{fromDb:e=>e==null?e:Number(e),toDb:e=>{if(e==null||typeof e!="number")return e==null?e:String(e);if(!Number.isFinite(e))throw new Error(`asNumber() cannot write ${e}: it is not a finite number, and the column holds one.`);if(Number.isInteger(e)&&!Number.isSafeInteger(e))throw new Error(`asNumber() cannot write ${e}: it is outside the safe integer range and would be stored as a different number. Declare .asDecimal() and hand this column a string.`);return String(e)},tsType:"number"},decimal:{fromDb:e=>e==null?e:String(e),toDb:e=>e==null?e:String(e),tsType:"string"}},r=class e{_def;constructor(n,t){this._def=t??{type:n,nullable:!1,primaryKey:!1}}primaryKey(){return this._def.primaryKey=!0,new e(this._def.type,this._def)}notNull(){return this._def.nullable=!1,new e(this._def.type,this._def)}nullable(){if(this._def.identity!==void 0)throw new Error(".nullable() on an identity column: an identity is always NOT NULL");return this._def.nullable=!0,new e(this._def.type,this._def)}default(n){return this._def.defaultValue=n,new e(this._def.type,this._def)}defaultRandom(){return this._def.defaultRandom=!0,new e(this._def.type,this._def)}defaultNow(){return this._def.defaultNow=!0,new e(this._def.type,this._def)}defaultSql(n){if(typeof n!="string"||n.trim()==="")throw new Error("defaultSql() takes the SQL of the default");return this._def.defaultSql=n,new e(this._def.type,this._def)}dbAssigned(){return this._def.dbAssigned=!0,new e(this._def.type,this._def)}array(){let n=this._def.type;if(!i.has(n))throw new Error(`${n} column: .array() is available on uuid(), text(), integer(), bigint(), numeric(), boolean(), timestamp(), date() and enumType()`);if(this._def.defaultValue!==void 0||this._def.defaultNow||this._def.defaultRandom||this._def.defaultSql!==void 0)throw new Error(`.array() comes before the default \u2014 write ${n}().array().default([])`);if(this._def.codec!==void 0||this._def.transform!==void 0)throw new Error(".array() cannot follow a codec or a transform \u2014 they convert one value, not a list of them");let t=`${n}[]`;return new e(t,{...this._def,type:t})}identity(n){if(this._def.type!=="integer"&&this._def.type!=="bigint"&&!(this._def.type==="sql"&&this._def.sqlType==="smallint"))throw new Error(`${this._def.type} column: .identity() is for integer(), bigint() and sqlType('smallint') columns`);if(this._def.defaultValue!==void 0||this._def.defaultNow||this._def.defaultRandom||this._def.defaultSql!==void 0||this._def.fill!==void 0)throw new Error(".identity() is the column's value \u2014 it cannot also have a default or a fill");let t=n?.always===!1?"byDefault":"always";return new e(this._def.type,{...this._def,nullable:!1,identity:t})}generated(n,t={}){if(typeof n!="string"||n.trim()==="")throw new Error(".generated() takes the SQL expression the column is");if(this._def.defaultValue!==void 0||this._def.defaultNow||this._def.defaultRandom||this._def.defaultSql!==void 0||this._def.fill!==void 0||this._def.identity!==void 0)throw new Error(".generated() is the column's value \u2014 it cannot also have a default, a fill or an identity");return new e(this._def.type,{...this._def,generated:{expr:n,stored:t.stored===!0}})}fillWith(n){return new e(this._def.type,{...this._def,fill:n})}renamedFrom(n){return this._def.renamedFrom=n,this}ignored(){return new e(this._def.type,{...this._def,ignored:!0})}encrypted(n={}){if(this._def.type!=="text")throw new Error(`.encrypted() is for a text() column \u2014 a ${this._def.type} column's value is not text to seal; keep it in a text() column (JSON.stringify it)`);return new e("text",{...this._def,encrypted:{lookup:n.lookup===!0}})}references(n,t){if(typeof n!="function")throw new Error('references(...) takes a callback: write references(() => otherTable.column). The two-string form references("table", "column") is gone \u2014 a string cannot be type-checked and cannot point at a table that does not exist yet.');return this._def.referencesThunk=n,t?.as!==void 0&&(this._def.refAs=t.as),t?.reverseAs!==void 0&&(this._def.reverseAs=t.reverseAs),t?.onDelete!==void 0&&(this._def.onDeleteAction=t.onDelete),t?.onUpdate!==void 0&&(this._def.onUpdateAction=t.onUpdate),t?.index===!1&&(this._def.index=!1),t?.deferrable===!1&&(this._def.deferrable=!1),new e(this._def.type,this._def)}selfReferences(n,t){return this._def.selfRefColumn=n,t?.as!==void 0&&(this._def.refAs=t.as),t?.onDelete!==void 0&&(this._def.onDeleteAction=t.onDelete),new e(this._def.type,this._def)}onDelete(n){return this._def.onDeleteAction=n,new e(this._def.type,this._def)}unique(){return this._def.unique=!0,new e(this._def.type,this._def)}asNumber(){return this.withCodec("number","asNumber")}asDecimal(){return this.withCodec("decimal","asDecimal")}withCodec(n,t){if(this._def.type!=="bigint"&&this._def.type!=="numeric")throw new Error(`${this._def.type} column: .${t}() is only available on bigint()/numeric() \u2014 those are the exact-precision types that surface as string.`);if(this._def.transform!==void 0)throw new Error(`.${t}() and .transform() are two ways to say the same thing on one column \u2014 keep .${t}().`);if(this._def.codec!==void 0)throw new Error(`column already declares .as${this._def.codec==="number"?"Number":"Decimal"}(); a column has ONE codec.`);return new e(this._def.type,{...this._def,codec:n})}transform(n){if(this._def.codec!==void 0)throw new Error("column already declares a named codec; .transform() and .as*() are two ways to say the same thing \u2014 keep the codec.");return new e(this._def.type,{...this._def,transform:n})}};function s(){return new r("uuid")}function a(){return new r("text")}function d(){return new r("integer")}function f(){return new r("bigint")}function m(e){if(e===void 0)return new r("numeric");let{precision:n,scale:t=0}=e;if(!Number.isInteger(n)||n<1||n>1e3)throw new Error(`numeric({ precision: ${n} }): precision is a whole number from 1 to 1000`);if(!Number.isInteger(t)||t<0||t>n)throw new Error(`numeric({ precision: ${n}, scale: ${t} }): scale is a whole number from 0 to the precision`);return new r("numeric",{type:"numeric",nullable:!1,primaryKey:!1,precision:n,scale:t})}function c(){return new r("date")}var o={uuid:"uuid()",text:"text()",integer:"integer()",int:"integer()",int4:"integer()",bigint:"bigint()",int8:"bigint()",numeric:"numeric()",decimal:"numeric()",boolean:"boolean()",bool:"boolean()",timestamptz:"timestamp()","timestamp with time zone":"timestamp()",date:"date()",jsonb:"jsonb()"};function y(e){let n=typeof e=="string"?e.trim():"";if(n==="")throw new Error('sqlType() takes the Postgres type, e.g. sqlType("inet")');let t=n.toLowerCase().replace(/\[\]$/,""),l=o[t];if(l!==void 0&&!(n.endsWith("[]")&&!i.has(l.slice(0,-2))))throw new Error(`sqlType(${JSON.stringify(n)}): the DSL has this type \u2014 declare it as ${l}${n.endsWith("[]")?".array()":""}`);return new r("sql",{type:"sql",nullable:!1,primaryKey:!1,sqlType:n})}var h=new Set(["smallint","real","double precision"]),p=new Set(["json"]);function b(){return new r("boolean")}function w(){return new r("timestamp")}function _(){return new r("jsonb")}function g(e,n){let t=new r("enum");return t._def.enumName=e,t._def.enumValues=[...n],t}function E(){let e=new r("text");return e._def.nullable=!1,e._def.user={onDelete:"cascade",owns:!0},e}function T(e){let n=new r("text");return n._def.user={onDelete:e.onDelete,owns:!1},e.as!==void 0&&(n._def.refAs=e.as),n}export{u as a,r as b,s as c,a as d,d as e,f,m as g,c as h,y as i,h as j,p as k,b as l,w as m,_ as n,g as o,E as p,T as q};
package/dist/cli.js CHANGED
@@ -1,2 +1,2 @@
1
- /*! palgres 0.76.0 — Palbase SDK License (see LICENSE) */
2
- import{E as f,s as p,y as d}from"./chunks/KGQ4WG5C.js";import"./chunks/J57ZAYFW.js";import"./chunks/DQNIJVL2.js";import"./chunks/FV6FUUSQ.js";import{mkdirSync as w,writeFileSync as E}from"node:fs";import{join as c}from"node:path";async function S(t){let[e,s="."]=t,o=process.env.PALGRES_DATABASE_URL;if(e!=="pull"||t.length>2)return console.error("usage: PALGRES_DATABASE_URL=\u2026 palgres pull [directory]"),1;if(!o)return console.error("palgres pull: PALGRES_DATABASE_URL is the database to read"),1;let r=globalThis.Bun;if(!r)return console.error("palgres pull runs under Bun (use `palbase db:pull`)"),1;let a;try{a=new r.SQL({url:o,prepare:!1,max:2});let u=(await a.unsafe("SELECT nspname AS name FROM pg_namespace WHERE nspname NOT LIKE 'pg\\_%' AND nspname NOT IN ('information_schema', 'palgres', 'auth') AND nspname NOT LIKE 'palgres\\_%' ORDER BY 1")).map(n=>n.name),i=await p(a,u,d),{files:g,notes:m}=f(i.schema,{unmanaged:i.unmanaged,units:i.units});for(let[n,l]of g)w(c(s,"db"),{recursive:!0}),E(c(s,n),l),console.log(`wrote ${c(s,n)}`);let h=n=>n.replace(/[\u0000-\u001f\u007f-\u009f]/g,l=>`\\u${l.charCodeAt(0).toString(16).padStart(4,"0")}`);(await a.unsafe("SELECT 1 FROM pg_namespace WHERE nspname = 'auth'")).length>0&&m.push("schema auth: not pulled \u2014 it is the platform's (auth.users, auth.uid()); a schema of your own named auth would need another name");for(let n of[...m,...i.unmanaged])console.log(` ${h(n)}`);return 0}catch(u){return console.error(`palgres pull: ${A(u)}`),1}finally{await a?.close().catch(()=>{})}}function A(t){let e=t,s=[e?.code,e?.errno].find(r=>typeof r=="string"&&/^[0-9A-Z]{5}$/.test(r));if(s!==void 0&&typeof e?.message=="string")return`${e.message} (${s})`;let o=[e?.code,e?.errno].find(r=>typeof r=="string");return`${typeof e?.name=="string"?e.name:"Error"}${o?` ${o}`:""}: the database could not be read (its address is not repeated here)`}process.exitCode=await S(process.argv.slice(2));
1
+ /*! palgres 0.77.0 — Palbase SDK License (see LICENSE) */
2
+ import{E as f,s as p,y as d}from"./chunks/GQPNHBQG.js";import"./chunks/4PM3K5J6.js";import"./chunks/LM4G2SEB.js";import"./chunks/SFRNKLRS.js";import{mkdirSync as w,writeFileSync as E}from"node:fs";import{join as c}from"node:path";async function S(t){let[e,s="."]=t,o=process.env.PALGRES_DATABASE_URL;if(e!=="pull"||t.length>2)return console.error("usage: PALGRES_DATABASE_URL=\u2026 palgres pull [directory]"),1;if(!o)return console.error("palgres pull: PALGRES_DATABASE_URL is the database to read"),1;let r=globalThis.Bun;if(!r)return console.error("palgres pull runs under Bun (use `palbase db:pull`)"),1;let a;try{a=new r.SQL({url:o,prepare:!1,max:2});let u=(await a.unsafe("SELECT nspname AS name FROM pg_namespace WHERE nspname NOT LIKE 'pg\\_%' AND nspname NOT IN ('information_schema', 'palgres', 'auth') AND nspname NOT LIKE 'palgres\\_%' ORDER BY 1")).map(n=>n.name),i=await p(a,u,d),{files:g,notes:m}=f(i.schema,{unmanaged:i.unmanaged,units:i.units});for(let[n,l]of g)w(c(s,"db"),{recursive:!0}),E(c(s,n),l),console.log(`wrote ${c(s,n)}`);let h=n=>n.replace(/[\u0000-\u001f\u007f-\u009f]/g,l=>`\\u${l.charCodeAt(0).toString(16).padStart(4,"0")}`);(await a.unsafe("SELECT 1 FROM pg_namespace WHERE nspname = 'auth'")).length>0&&m.push("schema auth: not pulled \u2014 it is the platform's (auth.users, auth.uid()); a schema of your own named auth would need another name");for(let n of[...m,...i.unmanaged])console.log(` ${h(n)}`);return 0}catch(u){return console.error(`palgres pull: ${A(u)}`),1}finally{await a?.close().catch(()=>{})}}function A(t){let e=t,s=[e?.code,e?.errno].find(r=>typeof r=="string"&&/^[0-9A-Z]{5}$/.test(r));if(s!==void 0&&typeof e?.message=="string")return`${e.message} (${s})`;let o=[e?.code,e?.errno].find(r=>typeof r=="string");return`${typeof e?.name=="string"?e.name:"Error"}${o?` ${o}`:""}: the database could not be read (its address is not repeated here)`}process.exitCode=await S(process.argv.slice(2));
package/dist/dsl.js CHANGED
@@ -1,2 +1,2 @@
1
- /*! palgres 0.76.0 — Palbase SDK License (see LICENSE) */
2
- import{b as g,c as C,d as w,e as R,f as T,g as P,h,i as A,l as U,m as B,n as E,o as K,p as k,q as I}from"./chunks/P42XRWFN.js";import{a as b}from"./chunks/J57ZAYFW.js";import{$ as c,R as n,S as i,T as f,U as a,V as l,W as p,X as u,Y as m,Z as s,_ as y,aa as d,ba as x,ca as D}from"./chunks/FV6FUUSQ.js";function M(o,t,e){if(e===void 0)return{name:o,up:t};let r={name:o,up:t};return e.drop!==void 0&&(r.drop=e.drop),e.before===!0&&(r.before=!0),r}export{g as ColumnBuilder,n as ForeignKeyBuilder,a as IndexBuilder,c as PolicyBuilder,s as PolicyExprRef,p as TABLE_META,T as bigint,U as boolean,x as check,h as date,m as defineSchema,u as defineTable,K as enumType,y as exprCtx,i as foreignKey,l as index,R as integer,E as jsonb,P as numeric,k as ownedByUser,d as policy,D as policySQL,f as qualifiedTableKey,M as raw,A as sqlType,w as text,B as timestamp,b as toModel,I as userRef,C as uuid};
1
+ /*! palgres 0.77.0 — Palbase SDK License (see LICENSE) */
2
+ import{b as g,c as C,d as w,e as R,f as T,g as P,h,i as A,l as U,m as B,n as E,o as K,p as k,q as I}from"./chunks/WUHOS3VC.js";import{a as b}from"./chunks/4PM3K5J6.js";import{$ as c,R as n,S as i,T as f,U as a,V as l,W as p,X as u,Y as m,Z as s,_ as y,aa as d,ba as x,ca as D}from"./chunks/SFRNKLRS.js";function M(o,t,e){if(e===void 0)return{name:o,up:t};let r={name:o,up:t};return e.drop!==void 0&&(r.drop=e.drop),e.before===!0&&(r.before=!0),r}export{g as ColumnBuilder,n as ForeignKeyBuilder,a as IndexBuilder,c as PolicyBuilder,s as PolicyExprRef,p as TABLE_META,T as bigint,U as boolean,x as check,h as date,m as defineSchema,u as defineTable,K as enumType,y as exprCtx,i as foreignKey,l as index,R as integer,E as jsonb,P as numeric,k as ownedByUser,d as policy,D as policySQL,f as qualifiedTableKey,M as raw,A as sqlType,w as text,B as timestamp,b as toModel,I as userRef,C as uuid};
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
- /*! palgres 0.76.0 — Palbase SDK License (see LICENSE) */
2
- import{a as Ae,j as fn,k as mn}from"./chunks/P42XRWFN.js";import{A as Ao,B as Po,C as No,D as Ve,E as hn,F as yn,G as jt,H as Kt,a as $o,b as Un,c as Vn,e as Ct,f as So,g as ko,h as Pe,i as Fe,j as U,k as Hn,l as he,m as Ne,n as pn,o as _t,p as It,q as Lt,r as gn,s as wn,t as zn,u as Mt,v as Bt,w as Ue,x as vo,y as xo,z as Oo}from"./chunks/TPGFMGK2.js";import{A as Eo,B as Dt,C as Fn,D as Ro,E as To,a as vt,b as qn,c as Cn,d as _n,e as so,f as In,g as xt,h as an,i as $e,j as je,k as Ln,l as At,m as cn,n as un,o as Mn,p as io,q as ao,r as lo,s as co,t as go,u as wo,v as ho,w as yo,x as bo,y as We,z as Wn}from"./chunks/KGQ4WG5C.js";import{a as qt}from"./chunks/J57ZAYFW.js";import{A as Nt,B as we,C as dn,D as Ke,a as ae,b as Ot,c as ln,d as J,j as uo,k as fo,l as Z,m as te,n as me,o as mo,p as pe,q as Bn,r as po,s as ve,t as xe,u as jn,v as Kn,w as Oe,x as ge,y as le,z as Pt}from"./chunks/DQNIJVL2.js";import{T as be,a as kt,c as Be,d as to,f as ro,j as oo,k as sn,m as Dn}from"./chunks/FV6FUUSQ.js";function Do(e){return{...e,pooled:!0}}function qo(e){return`SELECT set_config('application_name', ${J(e.applicationName)}, false)`}function Ft(e,n,t,r){return{...t!==void 0?{access:t}:{},...t!==void 0&&r!==void 0?{accessText:r}:{},version:e,direct:n,searchPath:n?`${ae("public")}, ${Dt}, pg_temp`:Fn(e),applicationName:Wn(e),schema:o=>n?o:Mn(e,o)}}var bn=class extends Error{digest;constructor(n){super(`palgres: this schema (${n}) has no version in the database yet \u2014 the deploy migrates it before the app serves (PALBASE_DB_MIGRATE=start)`),this.name="VersionNotMigrated",this.digest=n}};async function Co(e,n,t={}){let r=Dn(n),o=Date.now()+(t.waitMs??0);for(;;){let s;try{s=await e.unsafe("SELECT n, direct FROM palgres.versions WHERE digest = $1 AND state = 'active'",[r])}catch(i){let a=le(i);if(a!=="42P01"&&a!=="3F000"){if(we(i)===void 0||Date.now()>=o)throw i;t.onUnreachable?.(i),await new Promise(p=>setTimeout(p,1e3));continue}s=[]}if(s.length>0)return Ft(Number(s[0].n),s[0].direct===!0,n.access?.compiled,n.access?.text);if(Date.now()>=o)throw new bn(r);await new Promise(i=>setTimeout(i,500))}}function He(e,n,t){let r=Wt.get(e);r||Wt.set(e,r=new Map);let o=r.get(n);return o===void 0&&(o=`SELECT set_config('role', ${J(n)}, true), set_config('search_path', ${J(e.searchPath)}, true), set_config('application_name', ${J(e.applicationName)}, ${e.pooled===!0}), set_config('palgres.version', ${J(String(e.version))}, true), set_config('request.jwt.claims', `,r.set(n,o)),`${o}${J(JSON.stringify(t))}, true)`}var Wt=new WeakMap;async function _o(e,n,t,r,o="service_role"){let s=Vt(n,t,r),i=t.access!==void 0;return s.length===0&&!i?{deleted:0,detached:0}:e.begin(async a=>{await a.unsafe(He(n,o,{role:o})),await a.unsafe("SET CONSTRAINTS ALL DEFERRED");let p={query:(d,g)=>a.unsafe(d,g)},c=await Ht(p,s,r);return i?{...c,relationships:await Ut(p,r)}:c})}async function Io(e,n,t,r){let o=Vt(n,t,r),s=t.access!==void 0;if(o.length===0&&!s)return{deleted:0,detached:0};let i=[...new Set(sn(t).tables.flatMap(p=>p.foreignKeys.filter(c=>c.deferrable).map(c=>`${p.schema}.${c.name}`)))].sort(),a=`ARRAY[${i.map(ln).join(", ")}]::text[]`;return e.attempt(async p=>{i.length>0&&await p.query(`SELECT palgres.defer_keys(${a}, true)`);let c=await Ht(p,o,r);return i.length>0&&await p.query(`SELECT palgres.defer_keys(${a}, false)`),s?{...c,relationships:await Ut(p,r)}:c})}async function Ut(e,n){let t=await e.query("SELECT access.forget_subject($1)::int AS n",[n]);return Number(t[0].n)}function Vt(e,n,t){if(typeof t!="string"||t==="")throw new TypeError("forgetUser: the user id is a non-empty string");let r=[];for(let o of sn(n).tables)for(let s of o.columns){if(!s.user)continue;let i=o.ignored===!0||s.ignored===!0;r.push({view:Ot(i?o.schema:e.schema(o.schema),o.name),column:s.name,onDelete:s.user.onDelete})}return r}async function Ht(e,n,t){let r=0,o=0;for(let s of n.filter(i=>i.onDelete==="set null")){let i=await e.query(`WITH t AS (UPDATE ${s.view} SET ${ae(s.column)} = NULL WHERE ${ae(s.column)} = $1 RETURNING 1) SELECT count(*)::int AS n FROM t`,[t]);o+=Number(i[0].n)}for(let s of n.filter(i=>i.onDelete==="cascade")){let i=await e.query(`WITH t AS (DELETE FROM ${s.view} WHERE ${ae(s.column)} = $1 RETURNING 1) SELECT count(*)::int AS n FROM t`,[t]);r+=Number(i[0].n)}return{deleted:r,detached:o}}function Jt(e,n){let t=e.prepare===void 0?void 0:Promise.resolve(n(e.prepare)),r=Promise.resolve(n(e.execute));r.catch(()=>{});let o=()=>r.catch(s=>{throw e.failed(s,!1),s});return t===void 0?o():t.then(o,s=>{throw e.failed(s,!0),s})}function De(e){if(e==null)return null;switch(typeof e){case"string":return e;case"number":case"bigint":return String(e);case"boolean":return e?"true":"false";case"symbol":case"function":throw new TypeError(`a ${typeof e} is not a database value`)}return e instanceof Date?Lo(e):e instanceof Uint8Array?`\\x${Buffer.from(e).toString("hex")}`:Array.isArray(e)&&Qt(e)?Qe(e):JSON.stringify(e)}function Qt(e){return e.every(n=>n==null||typeof n!="object"&&typeof n!="function"&&typeof n!="symbol"||n instanceof Date||n instanceof Uint8Array||Array.isArray(n)&&Qt(n))}function Qe(e){let n=t=>t==null?"NULL":Array.isArray(t)?Qe(t):`"${String(De(t)).replace(/(["\\])/g,"\\$1")}"`;return`{${e.map(n).join(",")}}`}function Lo(e){if(Number.isNaN(e.getTime()))throw new TypeError("an invalid Date is not a database value");return e.toISOString()}var Mo={json:{to:114,from:[114,3802],serialize:e=>e,parse:e=>JSON.parse(e)},boolean:{to:16,from:[16],serialize:e=>e,parse:e=>e==="t"},date:{to:1184,from:[1082,1114,1184],serialize:e=>e,parse:e=>new Date(e)},bytea:{to:17,from:[17],serialize:e=>e,parse:e=>Buffer.from(e.slice(2),"hex")}};function Bo(e){let n=e;return n.length>0&&Array.isArray(n[n.length-1])?n[n.length-1]:n}var Gt=/^[A-Za-z0-9:_-]{1,80}$/;function Yt(e,n){let t=new Array(n.length).fill(!1),r="",o=0,s=0;for(;s<e.length;){let i=e.charCodeAt(s);if(i===39||i===34){let a=s+1;for(;;){if(a>=e.length||e.charCodeAt(a)===92)return;if(e.charCodeAt(a)===i){if(e.charCodeAt(a+1)!==i)break;a+=2}else a++}s=a+1;continue}if(i===36){let a=s+1,p=0;for(;a<e.length&&e.charCodeAt(a)>=48&&e.charCodeAt(a)<=57&&a-s<=6;)p=p*10+(e.charCodeAt(a++)-48);if(a===s+1||p<1||p>n.length||t[p-1])return;t[p-1]=!0;let c=n[p-1];if(c!==null&&typeof c!="string"||c!==null&&c.includes("\0"))return;r+=e.slice(o,s)+(c===null?"NULL":J(c)),o=s=a;continue}if(i===59||i===92||i===45&&e.charCodeAt(s+1)===45||i===47&&e.charCodeAt(s+1)===42)return;s++}for(let i of t)if(!i)return;return r+e.slice(o)}function zt(e){return dn(e)?Object.assign(new Error("current transaction is aborted, commands ignored until end of transaction block",{cause:e}),{errno:"25P02",code:"ERR_POSTGRES_SERVER_ERROR"}):e}var ze=10,Je=2;function Xt(e,n){let t={unsafe:(r,o)=>t.begin(s=>Promise.resolve(s.unsafe(r,o))),async begin(r,o){if(o?.tag!==void 0&&!Gt.test(o.tag))throw new Error(`palgres: an opening's tag is letters, digits, ":", "_" and "-"`);let s=`${o?.tag===void 0?"":`/* ${o.tag} */ `}BEGIN${o===void 0?"":`; ${o.sql}`}`,i;for(let b=1;;b++)try{i=await e.reserve();break}catch(R){let T=we(R);if(T===void 0||b>=(T==="never"?Je:ze))throw R}let a=!0,p=!1,c=!1,d=null,g,l=!1,m=0,f=b=>(d=(async()=>{for(let R=1;;R++)try{a||(i=await e.reserve(),a=!0),p=!0;let T=await i.unsafe(b===void 0?s:`${s}; ${b}`).simple();if((T.length>0&&Array.isArray(T[0])?T[0]:T).command!=="BEGIN")throw new Error("palgres: the round trip that opens the transaction did not begin one");return o?.opened?.(T[T.length-(b===void 0?1:2)]),c=!0,b===void 0?void 0:T[T.length-1]}catch(T){let O=we(T);if(l||O===void 0||R>=(O==="never"?Je:ze))throw g={error:T},T;a&&(await Promise.resolve(i.close()).catch(()=>{}),i.release(),a=!1,p=!1)}})(),d.catch(()=>{}),d),u=()=>(d===null&&f(),d.then(()=>{},()=>{throw zt(g.error)})),w={unsafe(b,R,T){if(g!==void 0)return Promise.reject(zt(g.error));let O=T?.prepared,D=()=>O===void 0?i.unsafe(b,R):Jt(O,A=>i.unsafe(A).simple());if(c)return D();if(d===null&&T?.inline===!0&&O===void 0){let A=Yt(b,R??[]);if(A!==void 0)return f(A)}return u().then(D)},async savepoint(b){await u();let R=`palgres_sp_${++m}`;await i.unsafe(`SAVEPOINT ${R}`).simple();let T;try{T=await b(w)}catch(O){throw await Promise.resolve(i.unsafe(`ROLLBACK TO SAVEPOINT ${R}; RELEASE SAVEPOINT ${R}`).simple()).catch(()=>{}),O}return await i.unsafe(`RELEASE SAVEPOINT ${R}`).simple(),T},abandon(){l||(l=!0,Promise.resolve(i.close({timeout:0})).catch(()=>{}))}},h=async b=>{let R=await i.unsafe(b).simple();if(p=!1,b==="COMMIT"&&R.command==="ROLLBACK")throw new Error("palgres: COMMIT was answered with ROLLBACK \u2014 a statement of the transaction had failed")};try{let b;try{if(b=await r(w),await d?.catch(()=>{}),g!==void 0)throw g.error}catch(R){throw await d?.catch(()=>{}),p&&!l&&await h("ROLLBACK").catch(()=>{}),R}if(!p)return b;try{await h("COMMIT")}catch(R){throw p&&await h("ROLLBACK").catch(()=>{}),R}return b}finally{a&&(p&&!l&&await Promise.resolve(i.close()).catch(()=>{}),i.release())}}};if(n!==void 0){let r=Xt(n);t.cancelBackend=Jn(r),t.cancelOpening=Zt(r)}return t}function Zt(e){return async n=>{if(!Gt.test(n))throw new Error(`palgres: an opening's tag is letters, digits, ":", "_" and "-"`);let t=`/* ${n} */`;return(await e.unsafe(`SELECT pg_cancel_backend(pid) AS cancelled FROM pg_stat_activity
1
+ /*! palgres 0.77.0 — Palbase SDK License (see LICENSE) */
2
+ import{a as Ae,j as fn,k as mn}from"./chunks/WUHOS3VC.js";import{A as Ao,B as Po,C as No,D as Ve,E as hn,F as yn,G as jt,H as Kt,a as $o,b as Un,c as Vn,e as Ct,f as So,g as ko,h as Pe,i as Fe,j as U,k as Hn,l as he,m as Ne,n as pn,o as _t,p as It,q as Lt,r as gn,s as wn,t as zn,u as Mt,v as Bt,w as Ue,x as vo,y as xo,z as Oo}from"./chunks/JGRLNWJZ.js";import{A as Eo,B as Dt,C as Fn,D as Ro,E as To,a as vt,b as qn,c as Cn,d as _n,e as so,f as In,g as xt,h as an,i as $e,j as je,k as Ln,l as At,m as cn,n as un,o as Mn,p as io,q as ao,r as lo,s as co,t as go,u as wo,v as ho,w as yo,x as bo,y as We,z as Wn}from"./chunks/GQPNHBQG.js";import{a as qt}from"./chunks/4PM3K5J6.js";import{A as Nt,B as we,C as dn,D as Ke,a as ae,b as Ot,c as ln,d as J,j as uo,k as fo,l as Z,m as te,n as me,o as mo,p as pe,q as Bn,r as po,s as ve,t as xe,u as jn,v as Kn,w as Oe,x as ge,y as le,z as Pt}from"./chunks/LM4G2SEB.js";import{T as be,a as kt,c as Be,d as to,f as ro,j as oo,k as sn,m as Dn}from"./chunks/SFRNKLRS.js";function Do(e){return{...e,pooled:!0}}function qo(e){return`SELECT set_config('application_name', ${J(e.applicationName)}, false)`}function Ft(e,n,t,r){return{...t!==void 0?{access:t}:{},...t!==void 0&&r!==void 0?{accessText:r}:{},version:e,direct:n,searchPath:n?`${ae("public")}, ${Dt}, pg_temp`:Fn(e),applicationName:Wn(e),schema:o=>n?o:Mn(e,o)}}var bn=class extends Error{digest;constructor(n){super(`palgres: this schema (${n}) has no version in the database yet \u2014 the deploy migrates it before the app serves (PALBASE_DB_MIGRATE=start)`),this.name="VersionNotMigrated",this.digest=n}};async function Co(e,n,t={}){let r=Dn(n),o=Date.now()+(t.waitMs??0);for(;;){let s;try{s=await e.unsafe("SELECT n, direct FROM palgres.versions WHERE digest = $1 AND state = 'active'",[r])}catch(i){let a=le(i);if(a!=="42P01"&&a!=="3F000"){if(we(i)===void 0||Date.now()>=o)throw i;t.onUnreachable?.(i),await new Promise(p=>setTimeout(p,1e3));continue}s=[]}if(s.length>0)return Ft(Number(s[0].n),s[0].direct===!0,n.access?.compiled,n.access?.text);if(Date.now()>=o)throw new bn(r);await new Promise(i=>setTimeout(i,500))}}function He(e,n,t){let r=Wt.get(e);r||Wt.set(e,r=new Map);let o=r.get(n);return o===void 0&&(o=`SELECT set_config('role', ${J(n)}, true), set_config('search_path', ${J(e.searchPath)}, true), set_config('application_name', ${J(e.applicationName)}, ${e.pooled===!0}), set_config('palgres.version', ${J(String(e.version))}, true), set_config('request.jwt.claims', `,r.set(n,o)),`${o}${J(JSON.stringify(t))}, true)`}var Wt=new WeakMap;async function _o(e,n,t,r,o="service_role"){let s=Vt(n,t,r),i=t.access!==void 0;return s.length===0&&!i?{deleted:0,detached:0}:e.begin(async a=>{await a.unsafe(He(n,o,{role:o})),await a.unsafe("SET CONSTRAINTS ALL DEFERRED");let p={query:(d,g)=>a.unsafe(d,g)},c=await Ht(p,s,r);return i?{...c,relationships:await Ut(p,r)}:c})}async function Io(e,n,t,r){let o=Vt(n,t,r),s=t.access!==void 0;if(o.length===0&&!s)return{deleted:0,detached:0};let i=[...new Set(sn(t).tables.flatMap(p=>p.foreignKeys.filter(c=>c.deferrable).map(c=>`${p.schema}.${c.name}`)))].sort(),a=`ARRAY[${i.map(ln).join(", ")}]::text[]`;return e.attempt(async p=>{i.length>0&&await p.query(`SELECT palgres.defer_keys(${a}, true)`);let c=await Ht(p,o,r);return i.length>0&&await p.query(`SELECT palgres.defer_keys(${a}, false)`),s?{...c,relationships:await Ut(p,r)}:c})}async function Ut(e,n){let t=await e.query("SELECT access.forget_subject($1)::int AS n",[n]);return Number(t[0].n)}function Vt(e,n,t){if(typeof t!="string"||t==="")throw new TypeError("forgetUser: the user id is a non-empty string");let r=[];for(let o of sn(n).tables)for(let s of o.columns){if(!s.user)continue;let i=o.ignored===!0||s.ignored===!0;r.push({view:Ot(i?o.schema:e.schema(o.schema),o.name),column:s.name,onDelete:s.user.onDelete})}return r}async function Ht(e,n,t){let r=0,o=0;for(let s of n.filter(i=>i.onDelete==="set null")){let i=await e.query(`WITH t AS (UPDATE ${s.view} SET ${ae(s.column)} = NULL WHERE ${ae(s.column)} = $1 RETURNING 1) SELECT count(*)::int AS n FROM t`,[t]);o+=Number(i[0].n)}for(let s of n.filter(i=>i.onDelete==="cascade")){let i=await e.query(`WITH t AS (DELETE FROM ${s.view} WHERE ${ae(s.column)} = $1 RETURNING 1) SELECT count(*)::int AS n FROM t`,[t]);r+=Number(i[0].n)}return{deleted:r,detached:o}}function Jt(e,n){let t=e.prepare===void 0?void 0:Promise.resolve(n(e.prepare)),r=Promise.resolve(n(e.execute));r.catch(()=>{});let o=()=>r.catch(s=>{throw e.failed(s,!1),s});return t===void 0?o():t.then(o,s=>{throw e.failed(s,!0),s})}function De(e){if(e==null)return null;switch(typeof e){case"string":return e;case"number":case"bigint":return String(e);case"boolean":return e?"true":"false";case"symbol":case"function":throw new TypeError(`a ${typeof e} is not a database value`)}return e instanceof Date?Lo(e):e instanceof Uint8Array?`\\x${Buffer.from(e).toString("hex")}`:Array.isArray(e)&&Qt(e)?Qe(e):JSON.stringify(e)}function Qt(e){return e.every(n=>n==null||typeof n!="object"&&typeof n!="function"&&typeof n!="symbol"||n instanceof Date||n instanceof Uint8Array||Array.isArray(n)&&Qt(n))}function Qe(e){let n=t=>t==null?"NULL":Array.isArray(t)?Qe(t):`"${String(De(t)).replace(/(["\\])/g,"\\$1")}"`;return`{${e.map(n).join(",")}}`}function Lo(e){if(Number.isNaN(e.getTime()))throw new TypeError("an invalid Date is not a database value");return e.toISOString()}var Mo={json:{to:114,from:[114,3802],serialize:e=>e,parse:e=>JSON.parse(e)},boolean:{to:16,from:[16],serialize:e=>e,parse:e=>e==="t"},date:{to:1184,from:[1082,1114,1184],serialize:e=>e,parse:e=>new Date(e)},bytea:{to:17,from:[17],serialize:e=>e,parse:e=>Buffer.from(e.slice(2),"hex")}};function Bo(e){let n=e;return n.length>0&&Array.isArray(n[n.length-1])?n[n.length-1]:n}var Gt=/^[A-Za-z0-9:_-]{1,80}$/;function Yt(e,n){let t=new Array(n.length).fill(!1),r="",o=0,s=0;for(;s<e.length;){let i=e.charCodeAt(s);if(i===39||i===34){let a=s+1;for(;;){if(a>=e.length||e.charCodeAt(a)===92)return;if(e.charCodeAt(a)===i){if(e.charCodeAt(a+1)!==i)break;a+=2}else a++}s=a+1;continue}if(i===36){let a=s+1,p=0;for(;a<e.length&&e.charCodeAt(a)>=48&&e.charCodeAt(a)<=57&&a-s<=6;)p=p*10+(e.charCodeAt(a++)-48);if(a===s+1||p<1||p>n.length||t[p-1])return;t[p-1]=!0;let c=n[p-1];if(c!==null&&typeof c!="string"||c!==null&&c.includes("\0"))return;r+=e.slice(o,s)+(c===null?"NULL":J(c)),o=s=a;continue}if(i===59||i===92||i===45&&e.charCodeAt(s+1)===45||i===47&&e.charCodeAt(s+1)===42)return;s++}for(let i of t)if(!i)return;return r+e.slice(o)}function zt(e){return dn(e)?Object.assign(new Error("current transaction is aborted, commands ignored until end of transaction block",{cause:e}),{errno:"25P02",code:"ERR_POSTGRES_SERVER_ERROR"}):e}var ze=10,Je=2;function Xt(e,n){let t={unsafe:(r,o)=>t.begin(s=>Promise.resolve(s.unsafe(r,o))),async begin(r,o){if(o?.tag!==void 0&&!Gt.test(o.tag))throw new Error(`palgres: an opening's tag is letters, digits, ":", "_" and "-"`);let s=`${o?.tag===void 0?"":`/* ${o.tag} */ `}BEGIN${o===void 0?"":`; ${o.sql}`}`,i;for(let b=1;;b++)try{i=await e.reserve();break}catch(R){let T=we(R);if(T===void 0||b>=(T==="never"?Je:ze))throw R}let a=!0,p=!1,c=!1,d=null,g,l=!1,m=0,f=b=>(d=(async()=>{for(let R=1;;R++)try{a||(i=await e.reserve(),a=!0),p=!0;let T=await i.unsafe(b===void 0?s:`${s}; ${b}`).simple();if((T.length>0&&Array.isArray(T[0])?T[0]:T).command!=="BEGIN")throw new Error("palgres: the round trip that opens the transaction did not begin one");return o?.opened?.(T[T.length-(b===void 0?1:2)]),c=!0,b===void 0?void 0:T[T.length-1]}catch(T){let O=we(T);if(l||O===void 0||R>=(O==="never"?Je:ze))throw g={error:T},T;a&&(await Promise.resolve(i.close()).catch(()=>{}),i.release(),a=!1,p=!1)}})(),d.catch(()=>{}),d),u=()=>(d===null&&f(),d.then(()=>{},()=>{throw zt(g.error)})),w={unsafe(b,R,T){if(g!==void 0)return Promise.reject(zt(g.error));let O=T?.prepared,D=()=>O===void 0?i.unsafe(b,R):Jt(O,A=>i.unsafe(A).simple());if(c)return D();if(d===null&&T?.inline===!0&&O===void 0){let A=Yt(b,R??[]);if(A!==void 0)return f(A)}return u().then(D)},async savepoint(b){await u();let R=`palgres_sp_${++m}`;await i.unsafe(`SAVEPOINT ${R}`).simple();let T;try{T=await b(w)}catch(O){throw await Promise.resolve(i.unsafe(`ROLLBACK TO SAVEPOINT ${R}; RELEASE SAVEPOINT ${R}`).simple()).catch(()=>{}),O}return await i.unsafe(`RELEASE SAVEPOINT ${R}`).simple(),T},abandon(){l||(l=!0,Promise.resolve(i.close({timeout:0})).catch(()=>{}))}},h=async b=>{let R=await i.unsafe(b).simple();if(p=!1,b==="COMMIT"&&R.command==="ROLLBACK")throw new Error("palgres: COMMIT was answered with ROLLBACK \u2014 a statement of the transaction had failed")};try{let b;try{if(b=await r(w),await d?.catch(()=>{}),g!==void 0)throw g.error}catch(R){throw await d?.catch(()=>{}),p&&!l&&await h("ROLLBACK").catch(()=>{}),R}if(!p)return b;try{await h("COMMIT")}catch(R){throw p&&await h("ROLLBACK").catch(()=>{}),R}return b}finally{a&&(p&&!l&&await Promise.resolve(i.close()).catch(()=>{}),i.release())}}};if(n!==void 0){let r=Xt(n);t.cancelBackend=Jn(r),t.cancelOpening=Zt(r)}return t}function Zt(e){return async n=>{if(!Gt.test(n))throw new Error(`palgres: an opening's tag is letters, digits, ":", "_" and "-"`);let t=`/* ${n} */`;return(await e.unsafe(`SELECT pg_cancel_backend(pid) AS cancelled FROM pg_stat_activity
3
3
  WHERE state = 'active' AND left(query, $1::integer) = $2
4
4
  AND usename = session_user AND datname = current_database() AND backend_type = 'client backend'`,[String(t.length),t])).length>0}}function Jn(e){return async(n,t,r)=>{await e.unsafe(`SELECT pg_cancel_backend(pid) FROM pg_stat_activity
5
5
  WHERE pid = $1::integer AND backend_start = $2::timestamptz AND xact_start = $3::timestamptz
package/dist/testing.js CHANGED
@@ -1,2 +1,2 @@
1
- /*! palgres 0.76.0 — Palbase SDK License (see LICENSE) */
2
- import{D as J,G as Se,H as Ue,a as ae,b as Ee,d as Me,l as ee,m as Ie,n as ue,r as le,s as ne,t as fe,u as Ne,w as H}from"./chunks/TPGFMGK2.js";import{n as Te,p as Ae}from"./chunks/DQNIJVL2.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/FV6FUUSQ.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};
1
+ /*! palgres 0.77.0 — Palbase SDK License (see LICENSE) */
2
+ import{D as J,G as Se,H as Ue,a as ae,b as Ee,d as Me,l as ee,m as Ie,n as ue,r as le,s as ne,t as fe,u as Ne,w as H}from"./chunks/JGRLNWJZ.js";import{n as Te,p as Ae}from"./chunks/LM4G2SEB.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/SFRNKLRS.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.76.0",
3
+ "version": "0.77.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",