palgres 0.69.0 → 0.70.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunks/{25DMHMF5.js → 6MK3WL7T.js} +2 -2
- package/dist/chunks/{6F5KQCOH.js → B6QMGTC2.js} +2 -2
- package/dist/chunks/{YRG222AC.js → SAZT3J7S.js} +1 -1
- package/dist/chunks/{FHL5XTBG.js → V26AHA6W.js} +1 -1
- package/dist/chunks/{LOZ6YAC7.js → W6GXJWN3.js} +2 -2
- package/dist/chunks/{M32MCL6M.js → ZEQXUCWB.js} +1 -1
- package/dist/cli.js +2 -2
- package/dist/dsl.js +2 -2
- package/dist/index.js +34 -34
- package/dist/testing.js +2 -2
- package/package.json +1 -1
- package/types/palgres/src/query/driver.d.ts +16 -5
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palgres 0.
|
|
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"./
|
|
1
|
+
/*! palgres 0.70.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"./ZEQXUCWB.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.
|
|
2
|
-
import{b as Lt}from"./
|
|
1
|
+
/*! palgres 0.70.0 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{b as Lt}from"./6MK3WL7T.js";import{C 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"./V26AHA6W.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"./ZEQXUCWB.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,2 +1,2 @@
|
|
|
1
|
-
/*! palgres 0.
|
|
1
|
+
/*! palgres 0.70.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};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
/*! palgres 0.
|
|
1
|
+
/*! palgres 0.70.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(n,o,e,r,s){super(e),this.name="HttpError",this.status=n,this.error=o,this.errorDescription=e,r!==void 0&&(this.data=r),s!==void 0&&(this.retryAfter=s)}};function O(t){return t[b]=!0,t}function q(t){return typeof t=="object"&&t!==null&&t[b]===!0}function c(t){let n=t.replace(/([a-z0-9])([A-Z])/g,"$1 $2");return n.charAt(0).toUpperCase()+n.slice(1).toLowerCase()}var g=class extends i{constructor(n,o){super(400,"bad_request",o??c("BadRequest"),n),this.name="BadRequest"}},E=class extends i{constructor(n,o,e){super(404,o??"not_found",n??c("NotFound"),e),this.name="NotFound"}},l=class extends i{constructor(n,o,e){super(409,o??"conflict",n??c("Conflict"),e),this.name="Conflict"}},p=class extends l{constraint;sqlstate=a.uniqueViolation;static is(n){return typeof n=="object"&&n!==null&&n.name==="UniqueViolation"&&typeof n.constraint=="string"}constructor(n,o,e,r){super(o??"Unique constraint violated",e??"unique_violation",r),this.name="UniqueViolation",this.constraint=n}};function x(t){if(typeof t!="object"||t===null||t.retryable!==!0)return!1;let n=t.sqlstate;return n===a.serializationFailure||n===a.deadlockDetected}var m=class extends l{retryable=!0;sqlstate;static is(n){return typeof n=="object"&&n!==null&&n.name==="SerializationFailure"}constructor(n=a.serializationFailure,o,e){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",e),this.name="SerializationFailure",this.sqlstate=n}},y=class extends l{retryable=!0;sqlstate;static is(n){return typeof n=="object"&&n!==null&&n.name==="DeadlockDetected"}constructor(n=a.deadlockDetected,o,e){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",e),this.name="DeadlockDetected",this.sqlstate=n}},w=class extends Error{sqlstate=a.inFailedTransaction;static is(n){return typeof n=="object"&&n!==null&&n.name==="TransactionAborted"}constructor(n,o){super(n,{cause:o}),this.name="TransactionAborted"}},k=class extends i{constructor(n,o){super(429,"too_many_requests",o??c("TooManyRequests"),n,n.retryAfter),this.name="TooManyRequests"}};function h(t){let n=t,o=e=>typeof e=="string"&&/^[0-9A-Z]{5}$/.test(e);if(o(n?.code))return n.code;if(o(n?.errno))return n.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 C(t){return t instanceof Error&&t.code===void 0&&t.message==="connection must be a PostgresSQLConnection"}function D(t){let n=t;for(let o=0;o<4&&typeof n=="object"&&n!==null;o++){let e=h(n),r=n.code,s=f=>e!==void 0&&f.has(e)||typeof r=="string"&&f.has(r);if(s(N))return"lost";if(s(_))return"never";n=n.cause}}function A(t){let n=t;for(let o=0;o<4&&typeof n=="object"&&n!==null;o++){let e=n.sqlstate,r=h(n)??(typeof e=="string"?e:void 0);if(r!==void 0)return!r.startsWith("08")&&!/^57P0[123]$/.test(r);n=n.cause}return!1}function I(t){let n=t,o=n?.constraint??n?.constraint_name;if(typeof o=="string"&&o.length>0)return o;let e=String(t?.message??"");return/violates unique constraint "([^"]+)"/.exec(e)?.[1]??""}var u=t=>`"${t.replace(/"/g,'""')}"`,P=(t,n)=>`${u(t)}.${u(n)}`,$=t=>`'${t.replace(/'/g,"''")}'`;function F(t){if(t.includes("\0"))throw new TypeError("a NUL character cannot be sent to Postgres");return`E'${t.replace(/\\/g,"\\\\").replace(/'/g,"''")}'`}var z=t=>t.map(u).join(", "),T=new Set(["now","current_timestamp","current_date","current_time","localtimestamp","localtime","transaction_timestamp","statement_timestamp"]);function M(t){return[...d(t)].some(n=>n.call&&!T.has(n.name.toLowerCase()))}function*d(t){let n=0;for(;n<t.length;){let o=t[n];if(o==="'"){for(n++;n<t.length;)if(t[n]==="'"&&t[n+1]==="'")n+=2;else{if(t[n]==="'")break;n++}n++;continue}if(o==="$"){let e=/^\$[A-Za-z_]*\$/.exec(t.slice(n));if(e){let r=t.indexOf(e[0],n+e[0].length);n=r<0?t.length:r+e[0].length;continue}}if(o==='"'){let e=n+1,r="";for(;e<t.length;)if(t[e]==='"'&&t[e+1]==='"')r+='"',e+=2;else{if(t[e]==='"')break;r+=t[e++]}let s=e+1;yield{start:n,end:s,name:r,quoted:!0,call:/^\s*\(/.test(t.slice(s))},n=s;continue}if(/[A-Za-z_]/.test(o)&&(n===0||!/[A-Za-z0-9_$]/.test(t[n-1]))){let e=/^[A-Za-z_][A-Za-z0-9_$]*/.exec(t.slice(n)),r=n+e[0].length;yield{start:n,end:r,name:e[0],quoted:!1,call:/^\s*\(/.test(t.slice(r))},n=r;continue}n++}}function j(t,n){for(let o of d(t))if(!o.call&&(o.quoted?o.name===n:o.name.toLowerCase()===n.toLowerCase()))return!0;return!1}function U(t,n){if(n.size===0)return t;let o="",e=0;for(let r of d(t)){if(r.call)continue;let s=n.get(r.quoted?r.name:S(n,r.name)??"");s!==void 0&&(o+=t.slice(e,r.start)+u(s),e=r.end)}return o+t.slice(e)}function S(t,n){if(t.has(n))return n;let o=n.toLowerCase();for(let e of t.keys())if(e.toLowerCase()===o)return e}var v=t=>`(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 ${t}.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,P as b,$ as c,F as d,z as e,M as f,j as g,U as h,v 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,m as u,y as v,w,k as x,h as y,_ as z,N as A,C as B,D as C,A as D,I as E};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
/*! palgres 0.
|
|
2
|
-
import{a as $,n as ke,p as $e,y as Re}from"./
|
|
1
|
+
/*! palgres 0.70.0 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{a as $,n as ke,p as $e,y as Re}from"./V26AHA6W.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"./ZEQXUCWB.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.
|
|
1
|
+
/*! palgres 0.70.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===`
|
package/dist/cli.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palgres 0.
|
|
2
|
-
import{E as f,s as p,y as d}from"./chunks/
|
|
1
|
+
/*! palgres 0.70.0 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{E as f,s as p,y as d}from"./chunks/B6QMGTC2.js";import"./chunks/6MK3WL7T.js";import"./chunks/V26AHA6W.js";import"./chunks/ZEQXUCWB.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.
|
|
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/
|
|
1
|
+
/*! palgres 0.70.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/SAZT3J7S.js";import{a as b}from"./chunks/6MK3WL7T.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/ZEQXUCWB.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,35 +1,35 @@
|
|
|
1
|
-
/*! palgres 0.
|
|
2
|
-
import{a as Ae,j as un,k as dn}from"./chunks/YRG222AC.js";import{A as qo,B as _o,C as Lo,D as Ve,E as gn,F as wn,G as Wt,H as Ft,a as Oo,b as Un,c as Vn,e as Lt,f as Ao,g as Po,h as Pe,i as Fe,j as U,k as Hn,l as he,m as Ne,n as fn,o as It,p as Mt,q as Bt,r as mn,s as pn,t as zn,u as Kt,v as jt,w as Ue,x as No,y as Do,z as Co}from"./chunks/LOZ6YAC7.js";import{A as ko,B as qt,C as Fn,D as vo,E as xo,a as xt,b as Cn,c as qn,d as _n,e as uo,f as Ln,g as Ot,h as on,i as $e,j as Ke,k as In,l as Pt,m as an,n as ln,o as Mn,p as fo,q as mo,r as po,s as go,t as Eo,u as Ro,v as To,w as $o,x as So,y as We,z as Wn}from"./chunks/6F5KQCOH.js";import{a as _t}from"./chunks/25DMHMF5.js";import{A as Dt,B as Ct,C as ce,D as cn,E as je,a as ae,b as At,c as sn,d as J,j as wo,k as ho,l as Z,m as te,n as pe,o as yo,p as ge,q as Bn,r as bo,s as ve,t as xe,u as Kn,v as jn,w as Oe,x as we,y as le,z as Nt}from"./chunks/FHL5XTBG.js";import{T as be,a as vt,c as Be,d as ao,f as lo,j as co,k as rn,m as Dn}from"./chunks/M32MCL6M.js";function Io(e){return{...e,pooled:!0}}function Mo(e){return`SELECT set_config('application_name', ${J(e.applicationName)}, false)`}function Vt(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")}, ${qt}, pg_temp`:Fn(e),applicationName:Wn(e),schema:o=>n?o:Mn(e,o)}}var hn=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 Bo(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(ce(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 Vt(Number(s[0].n),s[0].direct===!0,n.access?.compiled,n.access?.text);if(Date.now()>=o)throw new hn(r);await new Promise(i=>setTimeout(i,500))}}function He(e,n,t){let r=Ut.get(e);r||Ut.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 Ut=new WeakMap;async function Ko(e,n,t,r,o="service_role"){let s=zt(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:(m,w)=>a.unsafe(m,w)},l=await Jt(p,s,r);return i?{...l,relationships:await Ht(p,r)}:l})}async function jo(e,n,t,r){let o=zt(n,t,r),s=t.access!==void 0;if(o.length===0&&!s)return{deleted:0,detached:0};let i=[...new Set(rn(t).tables.flatMap(p=>p.foreignKeys.filter(l=>l.deferrable).map(l=>`${p.schema}.${l.name}`)))].sort(),a=`ARRAY[${i.map(sn).join(", ")}]::text[]`;return e.attempt(async p=>{i.length>0&&await p.query(`SELECT palgres.defer_keys(${a}, true)`);let l=await Jt(p,o,r);return i.length>0&&await p.query(`SELECT palgres.defer_keys(${a}, false)`),s?{...l,relationships:await Ht(p,r)}:l})}async function Ht(e,n){let t=await e.query("SELECT access.forget_subject($1)::int AS n",[n]);return Number(t[0].n)}function zt(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 rn(n).tables)for(let s of o.columns){if(!s.user)continue;let i=o.ignored===!0||s.ignored===!0;r.push({view:At(i?o.schema:e.schema(o.schema),o.name),column:s.name,onDelete:s.user.onDelete})}return r}async function Jt(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 Xt(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?Wo(e):e instanceof Uint8Array?`\\x${Buffer.from(e).toString("hex")}`:Array.isArray(e)&&Zt(e)?ze(e):JSON.stringify(e)}function Zt(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)&&Zt(n))}function ze(e){let n=t=>t==null?"NULL":Array.isArray(t)?ze(t):`"${String(De(t)).replace(/(["\\])/g,"\\$1")}"`;return`{${e.map(n).join(",")}}`}function Wo(e){if(Number.isNaN(e.getTime()))throw new TypeError("an invalid Date is not a database value");return e.toISOString()}var Fo={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 Qt(e){let n=e;return n.length>0&&Array.isArray(n[n.length-1])?n[n.length-1]:n}var er=/^[A-Za-z0-9:_-]{1,80}$/;function nr(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 l=n[p-1];if(l!==null&&typeof l!="string"||l!==null&&l.includes("\0"))return;r+=e.slice(o,s)+(l===null?"NULL":J(l)),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 Gt(e){return cn(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 yn=10,bn=2;function tr(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&&!er.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=await e.reserve(),a=!0,p=!1,l=!1,m=null,w,c=!1,f=0,d=y=>(m=(async()=>{for(let E=1;;E++){p=!0;try{let R=await i.unsafe(y===void 0?s:`${s}; ${y}`).simple();if((R.length>0&&Array.isArray(R[0])?R[0]:R).command!=="BEGIN")throw new Error("palgres: the round trip that opens the transaction did not begin one");return o?.opened?.(R[R.length-(y===void 0?1:2)]),l=!0,y===void 0?void 0:R[R.length-1]}catch(R){let v=Ct(R);v&&(e.discard!==void 0?e.discard(i):Promise.resolve(i.close({timeout:0})).catch(()=>{}),a=!1,p=!1);let P=v?"unusable":ce(R);if(c||P===void 0||E>=(P==="never"?bn:yn))throw w={error:R},R;v||(await Promise.resolve(i.close()).catch(()=>{}),i.release(),a=!1,p=!1);try{i=await e.reserve()}catch(A){throw w={error:A},A}a=!0}}})(),m.catch(()=>{}),m),u=()=>(m===null&&d(),m.then(()=>{},()=>{throw Gt(w.error)})),g={unsafe(y,E,R){if(w!==void 0)return Promise.reject(Gt(w.error));let v=R?.prepared,P=()=>v===void 0?i.unsafe(y,E):Xt(v,A=>i.unsafe(A).simple());if(l)return P();if(m===null&&R?.inline===!0&&v===void 0){let A=nr(y,E??[]);if(A!==void 0)return d(A)}return u().then(P)},async savepoint(y){await u();let E=`palgres_sp_${++f}`;await i.unsafe(`SAVEPOINT ${E}`).simple();let R;try{R=await y(g)}catch(v){throw await Promise.resolve(i.unsafe(`ROLLBACK TO SAVEPOINT ${E}; RELEASE SAVEPOINT ${E}`).simple()).catch(()=>{}),v}return await i.unsafe(`RELEASE SAVEPOINT ${E}`).simple(),R},abandon(){c||(c=!0,Promise.resolve(i.close({timeout:0})).catch(()=>{}))}},h=async y=>{let E=await i.unsafe(y).simple();if(p=!1,y==="COMMIT"&&E.command==="ROLLBACK")throw new Error("palgres: COMMIT was answered with ROLLBACK \u2014 a statement of the transaction had failed")};try{let y;try{if(y=await r(g),await m?.catch(()=>{}),w!==void 0)throw w.error}catch(E){throw await m?.catch(()=>{}),p&&!c&&await h("ROLLBACK").catch(()=>{}),E}if(!p)return y;try{await h("COMMIT")}catch(E){throw p&&await h("ROLLBACK").catch(()=>{}),E}return y}finally{a&&(p&&!c&&await Promise.resolve(i.close()).catch(()=>{}),i.release())}}};if(n!==void 0){let r=tr(n);t.cancelBackend=Qn(r),t.cancelOpening=or(r)}return t}var Jn=1e3;async function rr(e,n){let t;try{await Promise.race([Promise.resolve(e.close({timeout:n})),new Promise(r=>{t=setTimeout(r,n*1e3+Jn)})])}finally{clearTimeout(t)}}function Uo(e){let n=e(),t=0,r=!1,o=new WeakMap,s=new Map;return{get current(){return n},get renewals(){return t},unsafe:(i,a)=>n.unsafe(i,a),async reserve(){let i=n,a=await i.reserve();return o.set(a,i),a},discard(i){let a=o.get(i);if(a===n&&!r){n=e(),t++;let p=Promise.resolve(a.close()).catch(()=>{});s.set(a,p),p.then(()=>s.delete(a))}i.release()},async close(i){r=!0;let a=i?.timeout??0,p;try{await Promise.all([rr(n,a),Promise.race([Promise.all(s.values()),new Promise(l=>{p=setTimeout(l,a*1e3+Jn)})])])}finally{clearTimeout(p)}}}}function or(e){return async n=>{if(!er.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.70.0 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{a as Ae,j as un,k as dn}from"./chunks/SAZT3J7S.js";import{A as Do,B as qo,C as Co,D as Ve,E as gn,F as wn,G as Wt,H as Ft,a as vo,b as Un,c as Vn,e as Lt,f as xo,g as Oo,h as Pe,i as Fe,j as U,k as Hn,l as we,m as Ne,n as fn,o as It,p as Mt,q as Bt,r as mn,s as pn,t as zn,u as jt,v as Kt,w as Ue,x as Ao,y as Po,z as No}from"./chunks/W6GXJWN3.js";import{A as $o,B as Ct,C as Fn,D as So,E as ko,a as xt,b as qn,c as Cn,d as _n,e as lo,f as Ln,g as Ot,h as on,i as $e,j as je,k as In,l as Pt,m as an,n as ln,o as Mn,p as co,q as uo,r as fo,s as mo,t as yo,u as bo,v as Eo,w as Ro,x as To,y as We,z as Wn}from"./chunks/B6QMGTC2.js";import{a as _t}from"./chunks/6MK3WL7T.js";import{A as Dt,B as qt,C as ye,D as cn,E as Ke,a as ae,b as At,c as sn,d as J,j as po,k as go,l as Z,m as te,n as me,o as wo,p as pe,q as Bn,r as ho,s as ve,t as xe,u as jn,v as Kn,w as Oe,x as ge,y as le,z as Nt}from"./chunks/V26AHA6W.js";import{T as be,a as vt,c as Be,d as so,f as io,j as ao,k as rn,m as Dn}from"./chunks/ZEQXUCWB.js";function _o(n){return{...n,pooled:!0}}function Lo(n){return`SELECT set_config('application_name', ${J(n.applicationName)}, false)`}function Vt(n,e,t,r){return{...t!==void 0?{access:t}:{},...t!==void 0&&r!==void 0?{accessText:r}:{},version:n,direct:e,searchPath:e?`${ae("public")}, ${Ct}, pg_temp`:Fn(n),applicationName:Wn(n),schema:o=>e?o:Mn(n,o)}}var hn=class extends Error{digest;constructor(e){super(`palgres: this schema (${e}) 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=e}};async function Io(n,e,t={}){let r=Dn(e),o=Date.now()+(t.waitMs??0);for(;;){let s;try{s=await n.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(ye(i)===void 0||Date.now()>=o)throw i;t.onUnreachable?.(i),await new Promise(f=>setTimeout(f,1e3));continue}s=[]}if(s.length>0)return Vt(Number(s[0].n),s[0].direct===!0,e.access?.compiled,e.access?.text);if(Date.now()>=o)throw new hn(r);await new Promise(i=>setTimeout(i,500))}}function He(n,e,t){let r=Ut.get(n);r||Ut.set(n,r=new Map);let o=r.get(e);return o===void 0&&(o=`SELECT set_config('role', ${J(e)}, true), set_config('search_path', ${J(n.searchPath)}, true), set_config('application_name', ${J(n.applicationName)}, ${n.pooled===!0}), set_config('palgres.version', ${J(String(n.version))}, true), set_config('request.jwt.claims', `,r.set(e,o)),`${o}${J(JSON.stringify(t))}, true)`}var Ut=new WeakMap;async function Mo(n,e,t,r,o="service_role"){let s=zt(e,t,r),i=t.access!==void 0;return s.length===0&&!i?{deleted:0,detached:0}:n.begin(async a=>{await a.unsafe(He(e,o,{role:o})),await a.unsafe("SET CONSTRAINTS ALL DEFERRED");let f={query:(d,g)=>a.unsafe(d,g)},l=await Jt(f,s,r);return i?{...l,relationships:await Ht(f,r)}:l})}async function Bo(n,e,t,r){let o=zt(e,t,r),s=t.access!==void 0;if(o.length===0&&!s)return{deleted:0,detached:0};let i=[...new Set(rn(t).tables.flatMap(f=>f.foreignKeys.filter(l=>l.deferrable).map(l=>`${f.schema}.${l.name}`)))].sort(),a=`ARRAY[${i.map(sn).join(", ")}]::text[]`;return n.attempt(async f=>{i.length>0&&await f.query(`SELECT palgres.defer_keys(${a}, true)`);let l=await Jt(f,o,r);return i.length>0&&await f.query(`SELECT palgres.defer_keys(${a}, false)`),s?{...l,relationships:await Ht(f,r)}:l})}async function Ht(n,e){let t=await n.query("SELECT access.forget_subject($1)::int AS n",[e]);return Number(t[0].n)}function zt(n,e,t){if(typeof t!="string"||t==="")throw new TypeError("forgetUser: the user id is a non-empty string");let r=[];for(let o of rn(e).tables)for(let s of o.columns){if(!s.user)continue;let i=o.ignored===!0||s.ignored===!0;r.push({view:At(i?o.schema:n.schema(o.schema),o.name),column:s.name,onDelete:s.user.onDelete})}return r}async function Jt(n,e,t){let r=0,o=0;for(let s of e.filter(i=>i.onDelete==="set null")){let i=await n.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 e.filter(i=>i.onDelete==="cascade")){let i=await n.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 Gt(n,e){let t=n.prepare===void 0?void 0:Promise.resolve(e(n.prepare)),r=Promise.resolve(e(n.execute));r.catch(()=>{});let o=()=>r.catch(s=>{throw n.failed(s,!1),s});return t===void 0?o():t.then(o,s=>{throw n.failed(s,!0),s})}function De(n){if(n==null)return null;switch(typeof n){case"string":return n;case"number":case"bigint":return String(n);case"boolean":return n?"true":"false";case"symbol":case"function":throw new TypeError(`a ${typeof n} is not a database value`)}return n instanceof Date?jo(n):n instanceof Uint8Array?`\\x${Buffer.from(n).toString("hex")}`:Array.isArray(n)&&Yt(n)?ze(n):JSON.stringify(n)}function Yt(n){return n.every(e=>e==null||typeof e!="object"&&typeof e!="function"&&typeof e!="symbol"||e instanceof Date||e instanceof Uint8Array||Array.isArray(e)&&Yt(e))}function ze(n){let e=t=>t==null?"NULL":Array.isArray(t)?ze(t):`"${String(De(t)).replace(/(["\\])/g,"\\$1")}"`;return`{${n.map(e).join(",")}}`}function jo(n){if(Number.isNaN(n.getTime()))throw new TypeError("an invalid Date is not a database value");return n.toISOString()}var Ko={json:{to:114,from:[114,3802],serialize:n=>n,parse:n=>JSON.parse(n)},boolean:{to:16,from:[16],serialize:n=>n,parse:n=>n==="t"},date:{to:1184,from:[1082,1114,1184],serialize:n=>n,parse:n=>new Date(n)},bytea:{to:17,from:[17],serialize:n=>n,parse:n=>Buffer.from(n.slice(2),"hex")}};function Wo(n){let e=n;return e.length>0&&Array.isArray(e[e.length-1])?e[e.length-1]:e}var Xt=/^[A-Za-z0-9:_-]{1,80}$/;function Zt(n,e){let t=new Array(e.length).fill(!1),r="",o=0,s=0;for(;s<n.length;){let i=n.charCodeAt(s);if(i===39||i===34){let a=s+1;for(;;){if(a>=n.length||n.charCodeAt(a)===92)return;if(n.charCodeAt(a)===i){if(n.charCodeAt(a+1)!==i)break;a+=2}else a++}s=a+1;continue}if(i===36){let a=s+1,f=0;for(;a<n.length&&n.charCodeAt(a)>=48&&n.charCodeAt(a)<=57&&a-s<=6;)f=f*10+(n.charCodeAt(a++)-48);if(a===s+1||f<1||f>e.length||t[f-1])return;t[f-1]=!0;let l=e[f-1];if(l!==null&&typeof l!="string"||l!==null&&l.includes("\0"))return;r+=n.slice(o,s)+(l===null?"NULL":J(l)),o=s=a;continue}if(i===59||i===92||i===45&&n.charCodeAt(s+1)===45||i===47&&n.charCodeAt(s+1)===42)return;s++}for(let i of t)if(!i)return;return r+n.slice(o)}function Qt(n){return cn(n)?Object.assign(new Error("current transaction is aborted, commands ignored until end of transaction block",{cause:n}),{errno:"25P02",code:"ERR_POSTGRES_SERVER_ERROR"}):n}var yn=10,bn=2;function er(n,e){let t={unsafe:(r,o)=>t.begin(s=>Promise.resolve(s.unsafe(r,o))),async begin(r,o){if(o?.tag!==void 0&&!Xt.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=await n.reserve(),a=!0,f=!1,l=!1,d=null,g,c=!1,p=0,m=b=>(d=(async()=>{for(let R=1;;R++){f=!0;try{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)]),l=!0,b===void 0?void 0:T[T.length-1]}catch(T){let O=qt(T);O&&(n.discard!==void 0?n.discard(i):Promise.resolve(i.close({timeout:0})).catch(()=>{}),a=!1,f=!1);let D=O?"unusable":ye(T);if(c||D===void 0||R>=(D==="never"?bn:yn))throw g={error:T},T;O||(await Promise.resolve(i.close()).catch(()=>{}),i.release(),a=!1,f=!1);try{i=await n.reserve()}catch(A){throw g={error:A},A}a=!0}}})(),d.catch(()=>{}),d),u=()=>(d===null&&m(),d.then(()=>{},()=>{throw Qt(g.error)})),w={unsafe(b,R,T){if(g!==void 0)return Promise.reject(Qt(g.error));let O=T?.prepared,D=()=>O===void 0?i.unsafe(b,R):Gt(O,A=>i.unsafe(A).simple());if(l)return D();if(d===null&&T?.inline===!0&&O===void 0){let A=Zt(b,R??[]);if(A!==void 0)return m(A)}return u().then(D)},async savepoint(b){await u();let R=`palgres_sp_${++p}`;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(){c||(c=!0,Promise.resolve(i.close({timeout:0})).catch(()=>{}))}},h=async b=>{let R=await i.unsafe(b).simple();if(f=!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(()=>{}),f&&!c&&await h("ROLLBACK").catch(()=>{}),R}if(!f)return b;try{await h("COMMIT")}catch(R){throw f&&await h("ROLLBACK").catch(()=>{}),R}return b}finally{a&&(f&&!c&&await Promise.resolve(i.close()).catch(()=>{}),i.release())}}};if(e!==void 0){let r=er(e);t.cancelBackend=Qn(r),t.cancelOpening=tr(r)}return t}var Jn=1e3;async function nr(n,e){let t;try{await Promise.race([Promise.resolve(n.close({timeout:e})),new Promise(r=>{t=setTimeout(r,e*1e3+Jn)})])}finally{clearTimeout(t)}}function Fo(n){let e=n(),t=0,r=!1,o=new WeakMap,s=new Map;return{get current(){return e},get renewals(){return t},unsafe:(i,a)=>e.unsafe(i,a),async reserve(){let i=e,a=await i.reserve();return o.set(a,i),a},discard(i){let a=o.get(i);if(a===e&&!r){e=n(),t++;let f=Promise.resolve(a.close()).catch(()=>{});s.set(a,f),f.then(()=>s.delete(a))}i.release()},async close(i){r=!0;let a=i?.timeout??0,f;try{await Promise.all([nr(e,a),Promise.race([Promise.all(s.values()),new Promise(l=>{f=setTimeout(l,a*1e3+Jn)})])])}finally{clearTimeout(f)}}}}function tr(n){return async e=>{if(!Xt.test(e))throw new Error(`palgres: an opening's tag is letters, digits, ":", "_" and "-"`);let t=`/* ${e} */`;return(await n.unsafe(`SELECT pg_cancel_backend(pid) AS cancelled FROM pg_stat_activity
|
|
3
3
|
WHERE state = 'active' AND left(query, $1::integer) = $2
|
|
4
|
-
AND usename = session_user AND datname = current_database() AND backend_type = 'client backend'`,[String(t.length),t])).length>0}}function Qn(
|
|
4
|
+
AND usename = session_user AND datname = current_database() AND backend_type = 'client backend'`,[String(t.length),t])).length>0}}function Qn(n){return async(e,t,r)=>{await n.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
|
|
6
|
-
AND usename = session_user AND datname = current_database() AND backend_type = 'client backend'`,[String(
|
|
7
|
-
UPDATE ${re}.queue q SET next_attempt_at = now() + interval '${
|
|
8
|
-
RETURNING q.id::text AS id, q.table_key, q.gen, q.row_id, q.enqueued_at::text AS enqueued_at`).then($=>$.map(
|
|
6
|
+
AND usename = session_user AND datname = current_database() AND backend_type = 'client backend'`,[String(e),t,r])}}var he=class extends Error{constructor(e){super(`palgres: the driver ${e}. The engine sends every parameter as the text Postgres reads, and the driver must send it as it is \u2014 build Bun.SQL with { prepare: false } (Bun 1.4.2 or later) through bunDriver(), postgres.js with { types: POSTGRES_JS_TYPES } through postgresJsDriver()`),this.name="DriverRefused"}};async function Gn(n){let t=(await n.unsafe("SELECT $1::jsonb AS j, $2::boolean AS b, $3::timestamptz = '2026-01-02 03:04:05.123456+00'::timestamptz AS t, array_length($4::int[], 1)::int AS a, $5::bytea = '\\x0102'::bytea AS y",['{"palgres":[1]}',"true","2026-01-02T03:04:05.123456Z","{1,2}","\\x0102"]))[0]??{},r=t.j;if(typeof r=="string"||!Array.isArray(r?.palgres))throw new he("re-encodes text bound for a jsonb parameter (JSON text became a JSON string)");if(t.b!==!0)throw new he("changes the text bound for a boolean ('true' was not read as true)");if(t.t!==!0)throw new he("changes the text bound for a timestamp (its microseconds did not arrive)");if(Number(t.a)!==2)throw new he("changes the text bound for an array (the literal {1,2} did not arrive)");if(t.y!==!0)throw new he("changes the text bound for a bytea");if((await n.begin(async s=>await s.unsafe("SELECT pg_catalog.current_setting('palgres.driver_opened', true) AS v"),{sql:"SELECT pg_catalog.set_config('palgres.driver_opened', 'yes', true)"}))[0]?.v!=="yes")throw new he("does not run the opening of a transaction (its role and its caller) before the work \u2014 every request would run as the login, no one's")}function Uo(n,e){let t=a=>Promise.resolve(a).then(f=>f),r=a=>({unsafe:(f,l,d)=>d?.prepared===void 0?t(a.unsafe(f,l??[])):Gt(d.prepared,g=>t(a.unsafe(g).simple())),savepoint:f=>a.savepoint(l=>f(r(l)))}),o=a=>async(f,l)=>{for(let d=1;;d++){let g=!1;try{return await a.begin(async c=>{if(l!==void 0){let p=Wo(await t(c.unsafe(l.sql).simple()));l.opened?.(p)}return g=!0,await f(r(c))})}catch(c){let p=ye(c);if(g||p===void 0||d>=(p==="lost"?yn:bn))throw c}}},s=o(n),i=o(e);return{unsafe:(a,f)=>s(l=>Promise.resolve(l.unsafe(a,f))),begin:s,cancelBackend:Qn({unsafe:(a,f)=>i(l=>Promise.resolve(l.unsafe(a,f)))})}}var rr=(n,e)=>({embed:n,serving:new Map,said:new Map,log:e}),Xn=3e4,Zn=`SELECT set_config('hnsw.iterative_scan', 'relaxed_order', true), set_config('hnsw.ef_search', '200', true), set_config('hnsw.max_scan_tuples', '200000', true), g.gen, g.model, g.dimensions, g.metric, (SELECT n.nspname FROM pg_catalog.pg_extension e JOIN pg_catalog.pg_namespace n ON n.oid = e.extnamespace WHERE e.extname = 'vector') AS types FROM (SELECT 1) one LEFT JOIN ${$e}.generations g ON g.table_key = $1 AND g.status = 'active' ORDER BY g.gen DESC LIMIT 1`;function et(n){if(!(n===void 0||n.gen===null||n.gen===void 0||typeof n.types!="string"))return{gen:Number(n.gen),model:String(n.model),dimensions:Number(n.dimensions),metric:n.metric,types:n.types}}var Vo=["hybrid","text","vector"],Yn=(n,e)=>me(new pe({fields:[{field:n,message:e}]},`search: ${n} ${e}`));function or(n,e,t){if(t===null||typeof t!="object")throw new TypeError(`search(${n}): its options are { limit, where, mode, minScore }`);if(typeof e!="string")throw new TypeError(`search(${n}): the query is the text searched for, not ${e===null?"null":typeof e}`);let r=e.trim().slice(0,Xn);if(r==="")throw Yn("query","is empty \u2014 say what to search for");let o=t.mode??"hybrid";if(typeof o!="string"||!Vo.includes(o))throw new TypeError(`search(${n}): mode is "hybrid", "text" or "vector", not ${typeof o=="string"?JSON.stringify(String(o).slice(0,40)):typeof o}`);let s=t.limit??20;if(typeof s!="number"||!Number.isFinite(s))throw Yn("limit","must be a number");if(t.minScore!==void 0&&(typeof t.minScore!="number"||!Number.isFinite(t.minScore)))throw Yn("minScore","must be a number");return{text:r,mode:o,limit:Math.min(Math.max(1,Math.trunc(s)),100),...t.minScore===void 0?{}:{minScore:t.minScore}}}function nt(n,e){if(!Array.isArray(n)||n.length!==e)throw new Error(`the embedder answered ${Array.isArray(n)?`a vector of ${n.length} dimensions`:"no vector"} where ${e} were asked for`);for(let t of n)if(typeof t!="number"||!Number.isFinite(t))throw new Error("the embedder answered a vector that holds what is not a number");return`[${n.join(",")}]`}async function sr(n,e,t){let r=await n({texts:[e],model:t.model,dimensions:t.dimensions,purpose:"query"});if(r===null||typeof r!="object"||!Array.isArray(r.vectors)||r.vectors.length!==1)throw new Error("the embedder answered no vector for the one text it was given");return nt(r.vectors[0],t.dimensions)}var ir=100,Ho="2 minutes",zo=8,Jo=256,Qo=25e4,ar=1e3,Go=15e3,Yo=3e4,Xo=5e3,re=$e,En=n=>(n instanceof Error?n.message:String(n)).slice(0,500);function Zo(n){let{sql:e,embed:t,log:r}=n,o={...We,...n.roles},s=`SELECT set_config('role', ${J(o.service)}, true), set_config('search_path', 'pg_catalog, pg_temp', true), set_config('datestyle', 'ISO, YMD', true), set_config('lock_timeout', '5s', true), set_config('statement_timeout', '60s', true)`,i=E=>e.begin($=>E(async(y,x=[])=>await $.unsafe(y,x.map(De))),{sql:s}),a=(E,$)=>i(y=>y(E,$)),f=!0,l=E=>a(`WITH due AS (SELECT id FROM ${re}.queue WHERE next_attempt_at <= now() ORDER BY enqueued_at, id LIMIT ${E} FOR UPDATE SKIP LOCKED)
|
|
7
|
+
UPDATE ${re}.queue q SET next_attempt_at = now() + interval '${Ho}' FROM due WHERE q.id = due.id
|
|
8
|
+
RETURNING q.id::text AS id, q.table_key, q.gen, q.row_id, q.enqueued_at::text AS enqueued_at`).then($=>$.map(y=>({id:String(y.id),table_key:String(y.table_key),gen:Number(y.gen),row_id:String(y.row_id),enqueued_at:String(y.enqueued_at)})));async function d(E,$){let[y]=await a(`SELECT g.model, g.dimensions, g.metric, g.from_columns, t.rel::text AS parent, a.attname AS pk, format_type(a.atttypid, a.atttypmod) AS pk_type,
|
|
9
9
|
(SELECT n.nspname FROM pg_extension e JOIN pg_namespace n ON n.oid = e.extnamespace WHERE e.extname = 'vector') AS types
|
|
10
10
|
FROM ${re}.generations g
|
|
11
11
|
CROSS JOIN LATERAL (SELECT to_regclass(format('%I.%I', split_part(g.table_key, '.', 1), substr(g.table_key, strpos(g.table_key, '.') + 1))) AS rel) t
|
|
12
12
|
JOIN pg_index i ON i.indrelid = t.rel AND i.indisprimary AND i.indnkeyatts = 1
|
|
13
13
|
JOIN pg_attribute a ON a.attrelid = i.indrelid AND a.attnum = i.indkey[0]
|
|
14
|
-
WHERE g.table_key = $1 AND g.gen = $2::integer AND g.status <> 'retired'`,[
|
|
15
|
-
next_attempt_at = CASE WHEN q.attempts + 1 >= ${
|
|
16
|
-
FROM ${
|
|
17
|
-
there AS (SELECT p.${
|
|
14
|
+
WHERE g.table_key = $1 AND g.gen = $2::integer AND g.status <> 'retired'`,[E,$]);if(y===void 0||typeof y.types!="string")return;let x=Number(y.dimensions),N=y.metric;return{model:String(y.model),dimensions:x,metric:N,from:y.from_columns.map(String),parent:String(y.parent),pk:ae(String(y.pk)),pkType:String(y.pk_type),vectors:`${re}.${ae(je(E,$))}`,vectorType:`${ae(y.types)}.${an(x,N).type}`}}let g="unnest($1::bigint[], $2::timestamptz[]) AS c(id, at) WHERE q.id = c.id AND q.enqueued_at = c.at",c=E=>[E.map($=>$.id),E.map($=>$.enqueued_at)],p=E=>a(`DELETE FROM ${re}.queue q USING ${g}`,c(E)),m=async(E,$)=>{E.length!==0&&(r?.(`palgres: search of ${E[0].table_key}: ${E.length} row(s) not embedded, tried again later (${En($)})`),await a(`UPDATE ${re}.queue q SET attempts = q.attempts + 1, last_error = $3,
|
|
15
|
+
next_attempt_at = CASE WHEN q.attempts + 1 >= ${zo} THEN 'infinity'::timestamptz ELSE now() + interval '1 minute' * power(4, least(q.attempts, 4)) END
|
|
16
|
+
FROM ${g}`,[...c(E),En($)]))};async function u(E,$,y,x){let N=[],q=[],C=0;for(let S of $){let M=Math.ceil(S.text.length/4);q.length>0&&(q.length>=Jo||C+M>Qo)&&(N.push(q),q=[],C=0),q.push(S),C+=M}q.length>0&&N.push(q);let _=(S,M)=>(x.failed+=S.length,m(S.map(L=>L.row),M)),P=async S=>{if(S.length===0)return;let M=Math.ceil(S.length/2);await k(S.slice(0,M)),M<S.length&&await k(S.slice(M))},k=async S=>{if(x.down)return _(S,new Error("the embedder is not answering"));let M,L;try{let I=await t({texts:S.map(K=>K.text),model:E.model,dimensions:E.dimensions,purpose:"document"});if(I===null||typeof I!="object"||!Array.isArray(I.vectors)||I.vectors.length!==S.length)throw new Error(`the embedder answered ${Array.isArray(I?.vectors)?I.vectors.length:"no"} vector(s) for ${S.length} text(s)`);M=I.vectors.map(K=>nt(K,E.dimensions)),L=typeof I.model=="string"&&I.model!==""?I.model:E.model}catch(I){return S.length===1?_(S,I):x.answered?P(S):(await k([S[0]]),await k([S[S.length-1]]),x.answered?P(S.slice(1,-1)):(x.down=!0,_(S.slice(1,-1),I)))}x.answered=!0,await y(S,L,M)};for(let S of N)await k(S)}async function w(E,$){let y=await d(E[0].table_key,E[0].gen);if(y===void 0)return await p(E),0;let x=new Map((await a(`SELECT p.${y.pk}::text AS id, ${In(y.from,"p")} AS text FROM ${y.parent} p WHERE p.${y.pk} = ANY($1::${y.pkType}[])`,[E.map(P=>P.row_id)])).map(P=>[String(P.id),String(P.text??"")])),N=E.filter(P=>!x.has(P.row_id));N.length>0&&await p(N);let q=E.filter(P=>x.has(P.row_id)&&x.get(P.row_id).trim()==="");q.length>0&&await a(`WITH done AS (DELETE FROM ${re}.queue q USING ${g} RETURNING q.row_id) DELETE FROM ${y.vectors} v USING done d WHERE v.id = d.row_id::${y.pkType}`,c(q));let C=E.filter(P=>(x.get(P.row_id)??"").trim()!=="").map(P=>({row:P,text:x.get(P.row_id).slice(0,Xn)})),_=0;return await u(y,C,async(P,k,S)=>{try{let[M]=await a(`WITH done AS (DELETE FROM ${re}.queue q USING ${g} RETURNING q.row_id),
|
|
17
|
+
there AS (SELECT p.${y.pk}::text AS id FROM ${y.parent} p WHERE p.${y.pk} = ANY($3::${y.pkType}[]) FOR KEY SHARE),
|
|
18
18
|
written AS (
|
|
19
|
-
INSERT INTO ${
|
|
20
|
-
SELECT s.id::${
|
|
19
|
+
INSERT INTO ${y.vectors} (id, embedding, model)
|
|
20
|
+
SELECT s.id::${y.pkType}, s.embedding::${y.vectorType}, $5::text
|
|
21
21
|
FROM unnest($6::text[], $4::text[]) AS s(id, embedding) JOIN done d ON d.row_id = s.id JOIN there ON there.id = s.id
|
|
22
22
|
ON CONFLICT (id) DO UPDATE SET embedding = EXCLUDED.embedding, model = EXCLUDED.model, embedded_at = now()
|
|
23
23
|
RETURNING 1)
|
|
24
|
-
SELECT count(*)::int AS n FROM written`,[...c(
|
|
24
|
+
SELECT count(*)::int AS n FROM written`,[...c(P.map(L=>L.row)),P.map(L=>L.row.row_id),S,k,P.map(L=>L.row.row_id)]);_+=Number(M?.n??0)}catch(M){$.failed+=P.length,await m(P.map(L=>L.row),M)}},$),_}async function h(E){let $=0,y=await a(`SELECT g.table_key, g.gen FROM ${re}.generations g WHERE g.status = 'filling' AND NOT EXISTS (SELECT 1 FROM ${re}.queue q WHERE q.table_key = g.table_key AND q.gen = g.gen) ORDER BY 1, 2`);for(let x of y){let N=String(x.table_key),q=Number(x.gen),C=await d(N,q);if(C===void 0)continue;let[_]=await a(`WITH missing AS (
|
|
25
25
|
INSERT INTO ${re}.queue (table_key, gen, row_id)
|
|
26
|
-
SELECT $1::text, $2::integer, p.${
|
|
27
|
-
WHERE btrim(${In(
|
|
26
|
+
SELECT $1::text, $2::integer, p.${C.pk}::text FROM ${C.parent} p
|
|
27
|
+
WHERE btrim(${In(C.from,"p")}) <> '' AND NOT EXISTS (SELECT 1 FROM ${C.vectors} v WHERE v.id = p.${C.pk})
|
|
28
28
|
ON CONFLICT ON CONSTRAINT queue_one_pending DO NOTHING RETURNING 1)
|
|
29
|
-
SELECT count(*)::int AS n FROM missing`,[D,C]);if(Number(_?.n??0)>0){$+=Number(_.n);continue}let[N]=await a(`SELECT ${re}.promote($1) AS gen`,[D]);N?.gen!==null&&N?.gen!==void 0&&(T.push(D),r?.(`palgres: search of ${D}: every row is embedded again \u2014 generation ${String(N.gen)} serves`))}return $}async function y(T={}){let $=T.timeoutMs===void 0?1/0:Date.now()+T.timeoutMs,b=[],O=0,D=()=>Date.now()<$&&(T.max===void 0||O<T.max)&&!(T.whileRunning===!0&&p);for(;;){for(;D();){let C=await l(T.max===void 0?lr:Math.min(lr,T.max-O));if(C.length===0)break;let q=new Map;for(let k of C){let S=`${k.table_key}\0${k.gen}`,M=q.get(S);M?M.push(k):q.set(S,[k])}let _={answered:!1,down:!1,failed:0},N=0;for(let k of q.values())try{N+=await g(k,_)}catch(S){_.failed+=k.length,await d(k,S).catch(()=>{})}if(O+=N,N===0&&_.failed>0)return{embedded:O,promoted:b}}if(!D()||await h(b)===0)break}return{embedded:O,promoted:b}}let E,R,v=!1,P,A=()=>{v=!0,R?.()};return{drain:T=>y(T),kick:A,start(){E===void 0&&(p=!1,P=ln.listen(A),E=(async()=>{await a(`UPDATE ${re}.queue SET attempts = 0, next_attempt_at = now(), last_error = NULL WHERE next_attempt_at = 'infinity'`).catch($=>r?.(`palgres: the search worker could not read its queue (${En($)})`));let T=cr;for(;!p;){v=!1;let $=!1;try{let b=await y({timeoutMs:es,whileRunning:!0});$=b.embedded>0||b.promoted.length>0}catch(b){r?.(`palgres: the search worker could not embed (${En(b)}); it looks again`)}T=$?cr:Math.min(Zo,T*2),!(p||v)&&(await new Promise(b=>{let O=setTimeout(b,T);O.unref?.(),R=()=>{clearTimeout(O),b()}}),R=void 0)}})())},async stop(){if(E===void 0)return;p=!0,P?.(),P=void 0,R?.();let T=E;E=void 0;let $;await Promise.race([T,new Promise(b=>$=setTimeout(b,ns))]),clearTimeout($)}}}var tt=class{options;active=0;queued=0;tenants=new Map;pending=new Map;lastTenant;accepted=0;rejected={full:0,timeout:0,cancelled:0};limit;timeout;nestedLimit;nestedActive=0;nestedPending=new Set;constructor(n){if(this.options=n,this.limit=n.queueLimit??Math.min(512,Math.max(32,n.concurrency*8)),this.timeout=n.queueTimeoutMs??1e3,this.nestedLimit=n.nestedConcurrency??n.concurrency*2,!Number.isSafeInteger(n.concurrency)||n.concurrency<1||!Number.isSafeInteger(this.nestedLimit)||this.nestedLimit<1||!Number.isSafeInteger(this.limit)||this.limit<0||this.limit>1e4||!Number.isSafeInteger(this.timeout)||this.timeout<1||this.timeout>6e4)throw new Error("Invalid database pool or queue deployment settings")}get queueTimeoutMs(){return this.timeout}get snapshot(){return{active:this.active,queued:this.queued,nested:{active:this.nestedActive,queued:this.nestedPending.size},tenants:this.tenants.size,accepted:this.accepted,rejected:{...this.rejected}}}nestedLease(n){this.nestedActive++;let t=!1;return{queueMs:performance.now()-n,release:()=>{if(t)return;t=!0,this.nestedActive--;let r=this.nestedPending.values().next().value;r&&(this.nestedPending.delete(r),r.cleanup(),r.grant(this.nestedLease(r.entered)))}}}acquireNested(n){let t=performance.now();return this.nestedActive<this.nestedLimit?Promise.resolve(this.nestedLease(t)):new Promise((r,o)=>{let s={grant:r,reject:o,entered:t,cleanup(){}},i=(l,m)=>{this.nestedPending.delete(s)&&(s.cleanup(),this.rejection(l),o(m))},a=()=>i("cancelled",n?.reason??new Error("Database admission cancelled")),p=setTimeout(()=>i("timeout",new we({retryAfter:1},"Database queue deadline exceeded")),this.timeout);s.cleanup=()=>{clearTimeout(p),n?.removeEventListener("abort",a)},this.nestedPending.add(s),n?.addEventListener("abort",a,{once:!0}),n?.aborted&&a()})}rejection(n){this.rejected[n]++;try{this.options.onReject?.({reason:n,active:this.active,queued:this.queued})}catch{}}take(n,t){this.active++,this.accepted++,this.lastTenant=n,this.tenants.set(n,(this.tenants.get(n)??0)+1);let r=!1;return{queueMs:performance.now()-t,release:()=>{if(r)return;r=!0,this.active--;let o=(this.tenants.get(n)??1)-1;o?this.tenants.set(n,o):this.tenants.delete(n),this.drain()}}}drain(){for(;this.active<this.options.concurrency&&this.queued;){let n=this.pending.keys().next().value;if(this.pending.size>1&&n===this.lastTenant){let o=this.pending.get(n);this.pending.delete(n),this.pending.set(n,o),n=this.pending.keys().next().value}let t=this.pending.get(n),r=t.values().next().value;t.delete(r),this.pending.delete(n),t.size&&this.pending.set(n,t),this.queued--,r.cleanup(),r.grant(this.take(n,r.entered))}}async acquire(n,t,r={}){if(t?.aborted)throw this.rejection("cancelled"),t.reason??new Error("Database admission cancelled");if(r.nested)return this.acquireNested(t);let o=this.options.tenantClaim?n[this.options.tenantClaim]:n.sub,s=typeof o=="string"&&o.length?o:"__anonymous__",i=performance.now();if(this.active<this.options.concurrency&&!this.queued)return this.take(s,i);if(!r.returning&&this.queued>=this.limit)throw this.rejection("full"),new we({retryAfter:1},"Database queue is full");return new Promise((a,p)=>{let l=this.pending.get(s)??new Set;this.pending.has(s)||this.pending.set(s,l);let m={grant:a,reject:p,entered:i,cleanup(){}},w=(d,u)=>{l.delete(m)&&(l.size||this.pending.delete(s),this.queued--,m.cleanup(),this.rejection(d),p(u),this.drain())},c=()=>w("cancelled",t?.reason??new Error("Database admission cancelled")),f=setTimeout(()=>w("timeout",new we({retryAfter:1},"Database queue deadline exceeded")),this.timeout);if(m.cleanup=()=>{clearTimeout(f),t?.removeEventListener("abort",c)},r.returning){m.returning=!0;let d=[...l];l.clear();for(let u of d)u.returning&&l.add(u);l.add(m);for(let u of d)u.returning||l.add(u)}else l.add(m);this.queued++,t?.addEventListener("abort",c,{once:!0}),t?.aborted?c():this.drain()})}},ur=new WeakMap;function dr(e,n={concurrency:10}){let t=ur.get(e);if(!t)return t=new tt(n),ur.set(e,t),t;for(let r of["concurrency","queueLimit","queueTimeoutMs","tenantClaim"])if(n[r]!==t.options[r])throw new Error("Database admission cannot be reconfigured while its pool is shared");return t}function rs(e){return e.endsWith("_id")?e.slice(0,-3):e}function fr(e){return e.direction==="forward"?`the foreign key "${e.table}.${e.column}"`:`the reverse of "${e.table}.${e.column}"`}function mr(e){return e.direction==="reverse"?'references(() => \u2026, { reverseAs: "\u2026" })':e.def.selfRefColumn!==void 0?'selfReferences("\u2026", { as: "\u2026" })':'references(() => \u2026, { as: "\u2026" })'}function Je(e){let n=new Map,t=new Map;for(let o of e)for(let s of Object.values(o.tables)){let i=be(o.name,s.name);n.set(i,[]),t.set(i,new Map)}let r=(o,s,i,a)=>{let p=t.get(o);if(p===void 0)return;let l=p.get(s);if(l!==void 0){let m=mr(l),w=mr(i),c=m===w?`rename one of them: ${m}`:`rename one of them \u2014 "${l.table}.${l.column}": ${m}; "${i.table}.${i.column}": ${w}`;throw new Be([`table "${o}": ${fr(l)} and ${fr(i)} both resolve to the relation name "${s}" \u2014 ${c}`])}p.set(s,i),n.get(o)?.push(a)};for(let o of e)for(let s of Object.values(o.tables)){let i=be(o.name,s.name);for(let[a,p]of Object.entries(s.columns)){let l=p._def;if(l.references===void 0)continue;let m=l.references.table,w=l.refAs??rs(a);if(r(i,w,{table:s.name,column:a,direction:"forward",def:l},{name:w,to:m,kind:"one",via:a}),!n.has(m)||m===i)continue;let c=l.reverseAs??s.name;r(m,c,{table:s.name,column:a,direction:"reverse",def:l},{name:c,to:i,kind:"many",via:a})}}return n}function os(e){let n=e.columns??{},t=[],r=[];for(let[i,a]of Object.entries(n)){let p=a&&typeof a=="object"&&"_def"in a?a._def:a;p?.primaryKey&&t.push(i),p?.unique&&r.push([i])}let o=e.primaryKey??t;o.length&&r.unshift([...o]);for(let i of e.unique??[])r.push([...i.columns]);let s=new Set;return r.filter(i=>{if(!i.length||new Set(i).size!==i.length||i.some(p=>!Object.hasOwn(n,p)))throw new Error("Unique lookup requires a nonempty declared key of distinct, known columns");let a=JSON.stringify([...i].sort());return s.has(a)?!1:(s.add(a),!0)})}function Rn(e){let n=Object.fromEntries(Object.entries(e.columns).filter(([,t])=>t?._def?.ignored!==!0));return os({columns:n,primaryKey:e.primaryKey,unique:e.unique})}function pr(e,n,t){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`findUnique(${e}): where must contain one declared unique key`);let r=Object.keys(t);if(!n.some(o=>o.length===r.length&&o.every(s=>Object.hasOwn(t,s))))throw new Error(`findUnique(${e}): supply exactly one declared unique key (${n.map(o=>o.join(" + ")).join("; ")||"none declared"}); use findMany for other filters`);for(let[o,s]of Object.entries(t))if(s==null||typeof s=="object"&&!(s instanceof Date)||typeof s=="function"||typeof s=="symbol")throw new Error(`findUnique(${e}): ${o} requires a non-null scalar equality value`)}var x=e=>`"${e.replace(/"/g,'""')}"`;function yr(e){return e.type==="sql"&&typeof e.sqlType=="string"?`sql:${e.sqlType}`:e.type}var Tn=class{version;tables=new Map;ignoredTables=new Set;schemas;deferrals;fields;constructor(n,t,r=null){this.version=t.version,this.schemas=n,this.fields=r;let o=Je(n);for(let s of n)for(let i of Object.values(s.tables)){let a=be(s.name,i.name);if(i.ignored){this.ignoredTables.add(a);continue}this.tables.set(a,is(s.name,i,a,t,o.get(a)??[],r))}}encryptedColumns(){return[...this.tables.values()].flatMap(n=>[...n.encrypted].map(([t,r])=>({table:n,column:t,encrypted:r})))}table(n,t){let r=this.tables.get(n);if(r)return r;throw this.ignoredTables.has(n)?new Error(`${t}(${n}): the table is .ignored() in this version \u2014 the version has promised not to name it, so the next one can drop it`):new Error(`${t}(${n}): no such table in this version's schema (a table outside public is "schema.table")`)}deferral(n){return this.deferrals??=ss(_t([...this.schemas])),this.deferrals.get(`${n.schema}.${n.name}`)??null}};function ss(e){let n=(s,i)=>`${s}.${i}`,t=new Map,r=new Map;for(let s of e.tables)for(let i of s.foreignKeys){let a=n(i.refSchema,i.refTable);i.onDelete==="cascade"&&t.set(a,[...t.get(a)??[],n(s.schema,s.name)]),i.deferrable&&r.set(a,[...r.get(a)??[],n(s.schema,i.name)])}let o=new Map;for(let s of e.tables){let i=new Set([n(s.schema,s.name)]);for(let l of i)for(let m of t.get(l)??[])i.add(m);let a=[...new Set([...i].flatMap(l=>r.get(l)??[]))].sort();if(a.length===0)continue;let p=`ARRAY[${a.map(sn).join(", ")}]::text[]`;o.set(n(s.schema,s.name),{defer:`SELECT palgres.defer_keys(${p}, true)`,check:`SELECT palgres.defer_keys(${p}, false)`})}return o}function is(e,n,t,r,o,s){let i=new Map,a=new Set,p=[],l=new Map,m=new Set,w=new Map;for(let[f,d]of Object.entries(n.columns)){let u=d._def;if(u.ignored){a.add(f);continue}i.set(f,u),u.primaryKey&&p.push(f);let g=Cn(e,n.name,f);if(u.encrypted!==void 0){if(s===null)throw new Error(`${t}.${f} is .encrypted(): the engine needs the project's fields to seal and open it \u2014 createDatabase({ fields }) (palbase/backend gives it)`);w.set(f,{address:g,lookup:u.encrypted.lookup?vt(f):null}),l.set(f,{fromDb:h=>as(s,g,h)});continue}if(s!==null&&u.type==="text"&&s.sealing.get(g)?.direction==="open"){l.set(f,{fromDb:h=>typeof h=="string"&&s.sealing.get(g)!==void 0&&s.cipher.isEncrypted(h)?s.cipher.decrypt(g,h):h,toDb:h=>(s.sealing.get(g)!==void 0&&on(g,h),h)});continue}if(typeof u.codec=="string"&&u.codec in Ae){let h=Ae[u.codec];l.set(f,{fromDb:h.fromDb,toDb:h.toDb})}else u.transform!==void 0&&l.set(f,u.transform);(u.identity==="always"||u.generated!==void 0)&&m.add(f)}let c=n.primaryKey??p;return{key:t,schema:e,name:n.name,sql:e==="public"?x(n.name):`${x(r.schema(e))}.${x(n.name)}`,columns:i,ignored:a,primaryKey:c,singleKey:c.length===1?c[0]:null,uniqueKeys:Rn(n),transforms:l,databaseOnly:m,relations:o,projections:new Map,...n.search!==void 0?{search:{key:`${e}.${n.name}`,from:[...n.search.from]}}:{},encrypted:w,fields:s}}function as(e,n,t){if(typeof t!="string")return t;if(e.sealing.get(n)===void 0)return e.cipher.decrypt(n,t);if(!e.cipher.isEncrypted(t))return t;try{return e.cipher.decrypt(n,t)}catch{return t}}function gr(e){return`CASE WHEN isfinite(${e}) AND extract(year FROM ${e} AT TIME ZONE 'UTC') BETWEEN 1 AND 9999 THEN to_char(${e} AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') ELSE ${e}::text END`}function wr(e){return`CASE WHEN isfinite(${e}) AND extract(year FROM ${e}) BETWEEN 1 AND 9999 THEN to_char(${e}, 'YYYY-MM-DD') ELSE ${e}::text END`}function hr(e,n){return`CASE WHEN ${e} IS NULL THEN NULL ELSE ARRAY(SELECT ${n("u.e")} FROM unnest(${e}) WITH ORDINALITY AS u(e, i) ORDER BY u.i) END`}function Se(e,n){if(e!==null&&e.startsWith("sql:")){let t=e.slice(4);return un.has(t)||dn.has(t)?null:`CASE WHEN ${n} IS NULL THEN NULL ELSE format('%s', ${n}) END`}switch(e){case"timestamp":return gr(n);case"date":return wr(n);case"bigint[]":case"numeric[]":case"uuid[]":case"enum[]":return`${n}::text[]`;case"date[]":return hr(n,wr);case"timestamp[]":return hr(n,gr)}return null}function br(e){return e==="jsonb"||e==="sql:json"}import{createCipheriv as ls,createDecipheriv as cs,createHash as Er,randomBytes as us}from"node:crypto";var se=(e,n="page")=>new ge({fields:[{field:n,message:e}]},e);function Rr(e){return Er("sha256").update("palbase:cursor:v1\0").update(e).digest()}function rt(e){let n=t=>typeof t=="bigint"?{$bigint:t.toString()}:t instanceof Date?{$date:t.toISOString()}:Array.isArray(t)?t.map(n):t&&typeof t=="object"?Object.fromEntries(Object.keys(t).sort().map(r=>[r,n(t[r])])):t;return Er("sha256").update(JSON.stringify(n(e))).digest("base64url")}function Tr(e,n){let{iat:t,exp:r,nbf:o,jti:s,...i}=n;return rt({role:e,authorization:i})}function $r(e,n,t){let r=us(12),o=ls("aes-256-gcm",e,r);o.setAAD(Buffer.from(n));let s=Buffer.concat([o.update(JSON.stringify(t),"utf8"),o.final()]),i=`p1.${Buffer.concat([r,o.getAuthTag(),s]).toString("base64url")}`;if(i.length>16384)throw se("page cursor values are too large; choose shorter ordering columns");return i}function Sr(e,n,t,r){try{if(typeof t!="string"||t.length>16384||!/^p1\.[\w-]+$/.test(t))throw new Error;let o=Buffer.from(t.slice(3),"base64url");if(o.length<30||o.toString("base64url")!==t.slice(3))throw new Error;let s=cs("aes-256-gcm",e,o.subarray(0,12));s.setAAD(Buffer.from(n)),s.setAuthTag(o.subarray(12,28));let i=JSON.parse(Buffer.concat([s.update(o.subarray(28)),s.final()]).toString("utf8"));if(!Array.isArray(i)||i.length!==r||i.some(a=>a!==null&&typeof a!="string"))throw new Error;return i}catch{throw se("Invalid cursor for this query or identity; restart from the first page","cursor")}}var ds=new Set(["uuid","text","integer","bigint","boolean","timestamp","numeric","enum"]);function kr(e,n,t){let r=t;if("limit"in r||"offset"in r)throw se("page uses first/after or last/before, not limit/offset");let o=t.last!==void 0||t.before!==void 0;if(o&&(t.first!==void 0||t.after!==void 0))throw se("Use first/after or last/before in one page request");let s=(o?t.last:t.first)??50;if(!Number.isInteger(s)||s<1||s>1e3)throw se("page size must be an integer between 1 and 1000");if(n.length===0)throw new Error("page requires a declared primary key for a unique, stable ordering");U(t.orderBy,"orderBy","the order");let i=t.orderBy===void 0?[]:Array.isArray(t.orderBy)?t.orderBy:[t.orderBy];if(i.length>16)throw se("page supports at most 16 ordering columns");let a=new Set,p=[],l=m=>{U(m,"orderBy","the order");let w=e[m?.column];if(!Object.hasOwn(e,m?.column)||!w)throw se(`page order column ${m?.column} is not declared`);if(!ds.has(w.type??""))throw se(`page cannot order ${m.column}: ${w.type??"unknown"} is not a supported scalar column`);if(a.has(m.column))throw se(`page order column ${m.column} is repeated`);if(m.direction!==void 0&&m.direction!=="asc"&&m.direction!=="desc")throw se("page direction must be asc or desc");if(m.nulls!==void 0&&m.nulls!=="first"&&m.nulls!=="last")throw se("page nulls must be first or last");let c=m.direction??"asc";a.add(m.column),p.push({column:m.column,direction:c,nulls:m.nulls??(c==="asc"?"last":"first"),nullable:w.nullable!==!1})};for(let m of i)l(m);for(let m of n)a.has(m)||l({column:m,direction:p.at(-1)?.direction??"asc"});return{order:p,size:s,backward:o,token:o?t.before:t.after}}function ot(e,n,t,r,o,s=!1){let i=n.map(l=>r(l));if(e.every(l=>!l.nullable&&l.direction===e[0].direction)&&n.every(l=>l!==null)){let l=e[0].direction==="asc"!==t;return`(${e.map(m=>o(m.column)).join(", ")}) ${l?">":"<"}${s?"=":""} (${i.join(", ")})`}let a=[],p=[];for(let l=0;l<e.length;l++){let m=e[l],w=o(m.column),c=i[l],f=m.nulls==="last"!==t,d=m.direction==="asc"!==t?">":"<",u=n[l]===null?f?"false":`${w} IS NOT NULL`:`(${w} ${d} ${c}${f?` OR ${w} IS NULL`:""})`;a.push(`(${[...p,u].join(" AND ")})`),p.push(`${w} IS NOT DISTINCT FROM ${c}`)}return s&&a.push(`(${p.join(" AND ")})`),`(${a.join(" OR ")})`}import{randomBytes as fs}from"node:crypto";var ms=16,ps=2,vr="force_custom_plan",gs=16384,ws=256,hs=2e3,ys=256,bs=/^\s*(?:\(\s*)*(?:select|insert|update|delete|merge|values|with|table)\b/i,Es=/\bdeallocate\b/i,Rs=/'\s*(?:now|today|tomorrow|yesterday)\s*'/i;function xr(e){return Es.test(e)}function Ts(e,n){if(e.length>gs||!bs.test(e)||Rs.test(e))return;let t=n?e:e.replace(/;\s*$/,"");if(!t.includes(";")&&!(!n&&t.includes("*")))return t}function Or(e,n,t){if(!(n.length===0||n.length>ws)){for(let r of n)if(r!==null&&(typeof r!="string"||r.includes("\0")))return;return Ts(e,t)}}var $s=0,Ss=0,Ar=fs(5).toString("hex"),$n=class{texts=new Map;sessions=new Map;mark(){return`${Ar}_${++Ss}`}on(n){let t=this.sessions.get(n);return t!==void 0?this.sessions.delete(n):t=new st(this),this.sessions.set(n,t),this.sessions.size>ys&&this.sessions.delete(this.sessions.keys().next().value),t}count(n,t,r){Or(n,t,r)!==void 0&&this.sent(n)}sent(n){let t=(this.texts.get(n)??0)+1;return this.texts.delete(n),this.texts.set(n,t),this.texts.size>hs&&this.texts.delete(this.texts.keys().next().value),t}},st=class{statements=new Map;refused=0;all;constructor(n){this.all=n}get size(){return this.statements.size+this.refused}run(n,t,r){let o=Or(n,t,r);if(o===void 0)return;let s=this.all.sent(n),i=this.statements.get(n),a;if(i===void 0){if(s<ps||this.size>=ms)return;i=`palgres_${Ar}_${++$s}`,a=`PREPARE ${i} (${t.map(()=>"unknown").join(", ")}) AS ${o}`,this.statements.set(n,i)}let p=i,l=o.includes("/*")||o.includes("*/")?"":`/* ${o} */ `;return{prepare:a,execute:`${l}EXECUTE ${i}(${t.map(m=>m===null?"NULL":J(m)).join(", ")})`,failed:(m,w)=>this.failed(n,p,m,w)}}forget(){this.statements.clear(),this.refused=0}failed(n,t,r,o){let s=le(r);if(s==="26000")return this.forget();this.statements.get(n)===t&&(o?this.statements.delete(n):s==="0A000"&&(this.statements.delete(n),this.refused++))}};import{AsyncResource as no}from"node:async_hooks";var ks=5e3,Sn=()=>new te(503,"database_deadline_exceeded","Database transaction exceeded its deadline"),Ce=class{deadline;controller=new AbortController;active=new Set;cancelBackend;cancellation=Promise.resolve();cancelledAt;timer;unlink;rejection;get signal(){return this.controller.signal}constructor(n,t){this.deadline=n===void 0?void 0:performance.now()+n,this.rejection=new Promise((o,s)=>{this.signal.addEventListener("abort",()=>{s(this.signal.reason),this.active.size&&this.cancelBackend&&this.cancel()},{once:!0})}),this.rejection.catch(()=>{});let r=()=>this.controller.abort(t?.reason??new DOMException("Database transaction cancelled","AbortError"));t?.addEventListener("abort",r,{once:!0}),this.unlink=()=>t?.removeEventListener("abort",r),t?.aborted&&r(),n!==void 0&&(this.timer=setTimeout(()=>this.controller.abort(Sn()),n))}check(){this.deadline!==void 0&&performance.now()>=this.deadline&&!this.signal.aborted&&this.controller.abort(Sn()),this.signal.throwIfAborted()}checkDeadline(){if(!(this.deadline===void 0||performance.now()<this.deadline))throw this.signal.aborted||this.controller.abort(Sn()),Sn()}remainingMs(){return this.check(),this.deadline===void 0?void 0:Math.max(1,Math.ceil(this.deadline-performance.now()))}race(n){return Promise.race([n,this.rejection])}bindBackend(n){this.cancelBackend=n}async drainCancellation(){let n=(async()=>(await this.cancellation,await Promise.allSettled([...this.active]),!0))();if(this.cancelledAt===void 0)return n;let t,r=new Promise(o=>{t=setTimeout(()=>o(!1),Math.max(0,this.cancelledAt+ks-performance.now()))});try{return await Promise.race([n,r])}finally{clearTimeout(t)}}async watch(n){this.active.add(n);try{return this.signal.aborted&&this.cancelBackend&&this.cancel(),await n}finally{this.active.delete(n)}}cancel(){this.cancelledAt??=performance.now(),this.cancellation=this.cancelBackend().catch(()=>{})}dispose(){this.timer!==void 0&&clearTimeout(this.timer),this.unlink()}};import{createHash as vs}from"node:crypto";var kn=class{start=performance.now();options;ended;failure;state;constructor(n){this.options=n;for(let t of["maxQueries","maxRows","maxBytes"]){let r=n[t];if(r!==void 0&&(!Number.isSafeInteger(r)||r<0))throw new Error(`database ${t} must be a nonnegative safe integer`)}this.state={endpoint:n.endpoint,requestId:n.requestId,outcome:"active",elapsedMs:0,queries:0,rows:0,bytes:0,queueMs:0,poolMs:0,setupMs:0,sqlMs:0,commitMs:0,rollbackMs:0,connectionMs:0,commits:0,commitFailures:0,rollbackRequests:0,retries:0,statements:[]}}check(){if(this.failure)throw this.failure}time(n,t){this.state[n]=(this.state[n]??0)+performance.now()-t}retry(){this.state.retries++}committed(){this.state.commits++}commitFailed(){this.state.commitFailures++}failed(){this.state.outcome="failed"}rolledBack(){this.state.rollbackRequests++}refuse(n){throw this.failure??=new te(500,"database_budget_exceeded",`Database ${n} budget exceeded${this.options.endpoint?` in ${this.options.endpoint}`:""}`),this.failure}emit(n,t){try{let r=n?.(t);r&&Promise.resolve(r).catch(()=>{})}catch{}}async query(n,t){this.check(),this.options.maxQueries!==void 0&&this.state.queries>=this.options.maxQueries&&this.refuse("query count");let o={ordinal:++this.state.queries,fingerprint:vs("sha256").update(n).digest("hex").slice(0,24),...this.options.includeSql?{sql:n.slice(0,4096)}:{},durationMs:0,rows:0,bytes:0};this.options.captureSource&&(o.source=new Error().stack?.split(`
|
|
29
|
+
SELECT count(*)::int AS n FROM missing`,[N,q]);if(Number(_?.n??0)>0){$+=Number(_.n);continue}let[P]=await a(`SELECT ${re}.promote($1) AS gen`,[N]);P?.gen!==null&&P?.gen!==void 0&&(E.push(N),r?.(`palgres: search of ${N}: every row is embedded again \u2014 generation ${String(P.gen)} serves`))}return $}async function b(E={}){let $=E.timeoutMs===void 0?1/0:Date.now()+E.timeoutMs,y=[],x=0,N=()=>Date.now()<$&&(E.max===void 0||x<E.max)&&!(E.whileRunning===!0&&f);for(;;){for(;N();){let q=await l(E.max===void 0?ir:Math.min(ir,E.max-x));if(q.length===0)break;let C=new Map;for(let k of q){let S=`${k.table_key}\0${k.gen}`,M=C.get(S);M?M.push(k):C.set(S,[k])}let _={answered:!1,down:!1,failed:0},P=0;for(let k of C.values())try{P+=await w(k,_)}catch(S){_.failed+=k.length,await m(k,S).catch(()=>{})}if(x+=P,P===0&&_.failed>0)return{embedded:x,promoted:y}}if(!N()||await h(y)===0)break}return{embedded:x,promoted:y}}let R,T,O=!1,D,A=()=>{O=!0,T?.()};return{drain:E=>b(E),kick:A,start(){R===void 0&&(f=!1,D=ln.listen(A),R=(async()=>{await a(`UPDATE ${re}.queue SET attempts = 0, next_attempt_at = now(), last_error = NULL WHERE next_attempt_at = 'infinity'`).catch($=>r?.(`palgres: the search worker could not read its queue (${En($)})`));let E=ar;for(;!f;){O=!1;let $=!1;try{let y=await b({timeoutMs:Yo,whileRunning:!0});$=y.embedded>0||y.promoted.length>0}catch(y){r?.(`palgres: the search worker could not embed (${En(y)}); it looks again`)}E=$?ar:Math.min(Go,E*2),!(f||O)&&(await new Promise(y=>{let x=setTimeout(y,E);x.unref?.(),T=()=>{clearTimeout(x),y()}}),T=void 0)}})())},async stop(){if(R===void 0)return;f=!0,D?.(),D=void 0,T?.();let E=R;R=void 0;let $;await Promise.race([E,new Promise(y=>$=setTimeout(y,Xo))]),clearTimeout($)}}}var tt=class{options;active=0;queued=0;tenants=new Map;pending=new Map;lastTenant;accepted=0;rejected={full:0,timeout:0,cancelled:0};limit;timeout;nestedLimit;nestedActive=0;nestedPending=new Set;constructor(e){if(this.options=e,this.limit=e.queueLimit??Math.min(512,Math.max(32,e.concurrency*8)),this.timeout=e.queueTimeoutMs??1e3,this.nestedLimit=e.nestedConcurrency??e.concurrency*2,!Number.isSafeInteger(e.concurrency)||e.concurrency<1||!Number.isSafeInteger(this.nestedLimit)||this.nestedLimit<1||!Number.isSafeInteger(this.limit)||this.limit<0||this.limit>1e4||!Number.isSafeInteger(this.timeout)||this.timeout<1||this.timeout>6e4)throw new Error("Invalid database pool or queue deployment settings")}get queueTimeoutMs(){return this.timeout}get snapshot(){return{active:this.active,queued:this.queued,nested:{active:this.nestedActive,queued:this.nestedPending.size},tenants:this.tenants.size,accepted:this.accepted,rejected:{...this.rejected}}}nestedLease(e){this.nestedActive++;let t=!1;return{queueMs:performance.now()-e,release:()=>{if(t)return;t=!0,this.nestedActive--;let r=this.nestedPending.values().next().value;r&&(this.nestedPending.delete(r),r.cleanup(),r.grant(this.nestedLease(r.entered)))}}}acquireNested(e){let t=performance.now();return this.nestedActive<this.nestedLimit?Promise.resolve(this.nestedLease(t)):new Promise((r,o)=>{let s={grant:r,reject:o,entered:t,cleanup(){}},i=(l,d)=>{this.nestedPending.delete(s)&&(s.cleanup(),this.rejection(l),o(d))},a=()=>i("cancelled",e?.reason??new Error("Database admission cancelled")),f=setTimeout(()=>i("timeout",new ge({retryAfter:1},"Database queue deadline exceeded")),this.timeout);s.cleanup=()=>{clearTimeout(f),e?.removeEventListener("abort",a)},this.nestedPending.add(s),e?.addEventListener("abort",a,{once:!0}),e?.aborted&&a()})}rejection(e){this.rejected[e]++;try{this.options.onReject?.({reason:e,active:this.active,queued:this.queued})}catch{}}take(e,t){this.active++,this.accepted++,this.lastTenant=e,this.tenants.set(e,(this.tenants.get(e)??0)+1);let r=!1;return{queueMs:performance.now()-t,release:()=>{if(r)return;r=!0,this.active--;let o=(this.tenants.get(e)??1)-1;o?this.tenants.set(e,o):this.tenants.delete(e),this.drain()}}}drain(){for(;this.active<this.options.concurrency&&this.queued;){let e=this.pending.keys().next().value;if(this.pending.size>1&&e===this.lastTenant){let o=this.pending.get(e);this.pending.delete(e),this.pending.set(e,o),e=this.pending.keys().next().value}let t=this.pending.get(e),r=t.values().next().value;t.delete(r),this.pending.delete(e),t.size&&this.pending.set(e,t),this.queued--,r.cleanup(),r.grant(this.take(e,r.entered))}}async acquire(e,t,r={}){if(t?.aborted)throw this.rejection("cancelled"),t.reason??new Error("Database admission cancelled");if(r.nested)return this.acquireNested(t);let o=this.options.tenantClaim?e[this.options.tenantClaim]:e.sub,s=typeof o=="string"&&o.length?o:"__anonymous__",i=performance.now();if(this.active<this.options.concurrency&&!this.queued)return this.take(s,i);if(!r.returning&&this.queued>=this.limit)throw this.rejection("full"),new ge({retryAfter:1},"Database queue is full");return new Promise((a,f)=>{let l=this.pending.get(s)??new Set;this.pending.has(s)||this.pending.set(s,l);let d={grant:a,reject:f,entered:i,cleanup(){}},g=(m,u)=>{l.delete(d)&&(l.size||this.pending.delete(s),this.queued--,d.cleanup(),this.rejection(m),f(u),this.drain())},c=()=>g("cancelled",t?.reason??new Error("Database admission cancelled")),p=setTimeout(()=>g("timeout",new ge({retryAfter:1},"Database queue deadline exceeded")),this.timeout);if(d.cleanup=()=>{clearTimeout(p),t?.removeEventListener("abort",c)},r.returning){d.returning=!0;let m=[...l];l.clear();for(let u of m)u.returning&&l.add(u);l.add(d);for(let u of m)u.returning||l.add(u)}else l.add(d);this.queued++,t?.addEventListener("abort",c,{once:!0}),t?.aborted?c():this.drain()})}},lr=new WeakMap;function cr(n,e={concurrency:10}){let t=lr.get(n);if(!t)return t=new tt(e),lr.set(n,t),t;for(let r of["concurrency","queueLimit","queueTimeoutMs","tenantClaim"])if(e[r]!==t.options[r])throw new Error("Database admission cannot be reconfigured while its pool is shared");return t}function es(n){return n.endsWith("_id")?n.slice(0,-3):n}function ur(n){return n.direction==="forward"?`the foreign key "${n.table}.${n.column}"`:`the reverse of "${n.table}.${n.column}"`}function dr(n){return n.direction==="reverse"?'references(() => \u2026, { reverseAs: "\u2026" })':n.def.selfRefColumn!==void 0?'selfReferences("\u2026", { as: "\u2026" })':'references(() => \u2026, { as: "\u2026" })'}function Je(n){let e=new Map,t=new Map;for(let o of n)for(let s of Object.values(o.tables)){let i=be(o.name,s.name);e.set(i,[]),t.set(i,new Map)}let r=(o,s,i,a)=>{let f=t.get(o);if(f===void 0)return;let l=f.get(s);if(l!==void 0){let d=dr(l),g=dr(i),c=d===g?`rename one of them: ${d}`:`rename one of them \u2014 "${l.table}.${l.column}": ${d}; "${i.table}.${i.column}": ${g}`;throw new Be([`table "${o}": ${ur(l)} and ${ur(i)} both resolve to the relation name "${s}" \u2014 ${c}`])}f.set(s,i),e.get(o)?.push(a)};for(let o of n)for(let s of Object.values(o.tables)){let i=be(o.name,s.name);for(let[a,f]of Object.entries(s.columns)){let l=f._def;if(l.references===void 0)continue;let d=l.references.table,g=l.refAs??es(a);if(r(i,g,{table:s.name,column:a,direction:"forward",def:l},{name:g,to:d,kind:"one",via:a}),!e.has(d)||d===i)continue;let c=l.reverseAs??s.name;r(d,c,{table:s.name,column:a,direction:"reverse",def:l},{name:c,to:i,kind:"many",via:a})}}return e}function ns(n){let e=n.columns??{},t=[],r=[];for(let[i,a]of Object.entries(e)){let f=a&&typeof a=="object"&&"_def"in a?a._def:a;f?.primaryKey&&t.push(i),f?.unique&&r.push([i])}let o=n.primaryKey??t;o.length&&r.unshift([...o]);for(let i of n.unique??[])r.push([...i.columns]);let s=new Set;return r.filter(i=>{if(!i.length||new Set(i).size!==i.length||i.some(f=>!Object.hasOwn(e,f)))throw new Error("Unique lookup requires a nonempty declared key of distinct, known columns");let a=JSON.stringify([...i].sort());return s.has(a)?!1:(s.add(a),!0)})}function Rn(n){let e=Object.fromEntries(Object.entries(n.columns).filter(([,t])=>t?._def?.ignored!==!0));return ns({columns:e,primaryKey:n.primaryKey,unique:n.unique})}function fr(n,e,t){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`findUnique(${n}): where must contain one declared unique key`);let r=Object.keys(t);if(!e.some(o=>o.length===r.length&&o.every(s=>Object.hasOwn(t,s))))throw new Error(`findUnique(${n}): supply exactly one declared unique key (${e.map(o=>o.join(" + ")).join("; ")||"none declared"}); use findMany for other filters`);for(let[o,s]of Object.entries(t))if(s==null||typeof s=="object"&&!(s instanceof Date)||typeof s=="function"||typeof s=="symbol")throw new Error(`findUnique(${n}): ${o} requires a non-null scalar equality value`)}var v=n=>`"${n.replace(/"/g,'""')}"`;function wr(n){return n.type==="sql"&&typeof n.sqlType=="string"?`sql:${n.sqlType}`:n.type}var Tn=class{version;tables=new Map;ignoredTables=new Set;schemas;deferrals;fields;constructor(e,t,r=null){this.version=t.version,this.schemas=e,this.fields=r;let o=Je(e);for(let s of e)for(let i of Object.values(s.tables)){let a=be(s.name,i.name);if(i.ignored){this.ignoredTables.add(a);continue}this.tables.set(a,rs(s.name,i,a,t,o.get(a)??[],r))}}encryptedColumns(){return[...this.tables.values()].flatMap(e=>[...e.encrypted].map(([t,r])=>({table:e,column:t,encrypted:r})))}table(e,t){let r=this.tables.get(e);if(r)return r;throw this.ignoredTables.has(e)?new Error(`${t}(${e}): the table is .ignored() in this version \u2014 the version has promised not to name it, so the next one can drop it`):new Error(`${t}(${e}): no such table in this version's schema (a table outside public is "schema.table")`)}deferral(e){return this.deferrals??=ts(_t([...this.schemas])),this.deferrals.get(`${e.schema}.${e.name}`)??null}};function ts(n){let e=(s,i)=>`${s}.${i}`,t=new Map,r=new Map;for(let s of n.tables)for(let i of s.foreignKeys){let a=e(i.refSchema,i.refTable);i.onDelete==="cascade"&&t.set(a,[...t.get(a)??[],e(s.schema,s.name)]),i.deferrable&&r.set(a,[...r.get(a)??[],e(s.schema,i.name)])}let o=new Map;for(let s of n.tables){let i=new Set([e(s.schema,s.name)]);for(let l of i)for(let d of t.get(l)??[])i.add(d);let a=[...new Set([...i].flatMap(l=>r.get(l)??[]))].sort();if(a.length===0)continue;let f=`ARRAY[${a.map(sn).join(", ")}]::text[]`;o.set(e(s.schema,s.name),{defer:`SELECT palgres.defer_keys(${f}, true)`,check:`SELECT palgres.defer_keys(${f}, false)`})}return o}function rs(n,e,t,r,o,s){let i=new Map,a=new Set,f=[],l=new Map,d=new Set,g=new Map;for(let[p,m]of Object.entries(e.columns)){let u=m._def;if(u.ignored){a.add(p);continue}i.set(p,u),u.primaryKey&&f.push(p);let w=qn(n,e.name,p);if(u.encrypted!==void 0){if(s===null)throw new Error(`${t}.${p} is .encrypted(): the engine needs the project's fields to seal and open it \u2014 createDatabase({ fields }) (palbase/backend gives it)`);g.set(p,{address:w,lookup:u.encrypted.lookup?vt(p):null}),l.set(p,{fromDb:h=>os(s,w,h)});continue}if(s!==null&&u.type==="text"&&s.sealing.get(w)?.direction==="open"){l.set(p,{fromDb:h=>typeof h=="string"&&s.sealing.get(w)!==void 0&&s.cipher.isEncrypted(h)?s.cipher.decrypt(w,h):h,toDb:h=>(s.sealing.get(w)!==void 0&&on(w,h),h)});continue}if(typeof u.codec=="string"&&u.codec in Ae){let h=Ae[u.codec];l.set(p,{fromDb:h.fromDb,toDb:h.toDb})}else u.transform!==void 0&&l.set(p,u.transform);(u.identity==="always"||u.generated!==void 0)&&d.add(p)}let c=e.primaryKey??f;return{key:t,schema:n,name:e.name,sql:n==="public"?v(e.name):`${v(r.schema(n))}.${v(e.name)}`,columns:i,ignored:a,primaryKey:c,singleKey:c.length===1?c[0]:null,uniqueKeys:Rn(e),transforms:l,databaseOnly:d,relations:o,projections:new Map,...e.search!==void 0?{search:{key:`${n}.${e.name}`,from:[...e.search.from]}}:{},encrypted:g,fields:s}}function os(n,e,t){if(typeof t!="string")return t;if(n.sealing.get(e)===void 0)return n.cipher.decrypt(e,t);if(!n.cipher.isEncrypted(t))return t;try{return n.cipher.decrypt(e,t)}catch{return t}}function mr(n){return`CASE WHEN isfinite(${n}) AND extract(year FROM ${n} AT TIME ZONE 'UTC') BETWEEN 1 AND 9999 THEN to_char(${n} AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') ELSE ${n}::text END`}function pr(n){return`CASE WHEN isfinite(${n}) AND extract(year FROM ${n}) BETWEEN 1 AND 9999 THEN to_char(${n}, 'YYYY-MM-DD') ELSE ${n}::text END`}function gr(n,e){return`CASE WHEN ${n} IS NULL THEN NULL ELSE ARRAY(SELECT ${e("u.e")} FROM unnest(${n}) WITH ORDINALITY AS u(e, i) ORDER BY u.i) END`}function Se(n,e){if(n!==null&&n.startsWith("sql:")){let t=n.slice(4);return un.has(t)||dn.has(t)?null:`CASE WHEN ${e} IS NULL THEN NULL ELSE format('%s', ${e}) END`}switch(n){case"timestamp":return mr(e);case"date":return pr(e);case"bigint[]":case"numeric[]":case"uuid[]":case"enum[]":return`${e}::text[]`;case"date[]":return gr(e,pr);case"timestamp[]":return gr(e,mr)}return null}function hr(n){return n==="jsonb"||n==="sql:json"}import{createCipheriv as ss,createDecipheriv as is,createHash as yr,randomBytes as as}from"node:crypto";var se=(n,e="page")=>new pe({fields:[{field:e,message:n}]},n);function br(n){return yr("sha256").update("palbase:cursor:v1\0").update(n).digest()}function rt(n){let e=t=>typeof t=="bigint"?{$bigint:t.toString()}:t instanceof Date?{$date:t.toISOString()}:Array.isArray(t)?t.map(e):t&&typeof t=="object"?Object.fromEntries(Object.keys(t).sort().map(r=>[r,e(t[r])])):t;return yr("sha256").update(JSON.stringify(e(n))).digest("base64url")}function Er(n,e){let{iat:t,exp:r,nbf:o,jti:s,...i}=e;return rt({role:n,authorization:i})}function Rr(n,e,t){let r=as(12),o=ss("aes-256-gcm",n,r);o.setAAD(Buffer.from(e));let s=Buffer.concat([o.update(JSON.stringify(t),"utf8"),o.final()]),i=`p1.${Buffer.concat([r,o.getAuthTag(),s]).toString("base64url")}`;if(i.length>16384)throw se("page cursor values are too large; choose shorter ordering columns");return i}function Tr(n,e,t,r){try{if(typeof t!="string"||t.length>16384||!/^p1\.[\w-]+$/.test(t))throw new Error;let o=Buffer.from(t.slice(3),"base64url");if(o.length<30||o.toString("base64url")!==t.slice(3))throw new Error;let s=is("aes-256-gcm",n,o.subarray(0,12));s.setAAD(Buffer.from(e)),s.setAuthTag(o.subarray(12,28));let i=JSON.parse(Buffer.concat([s.update(o.subarray(28)),s.final()]).toString("utf8"));if(!Array.isArray(i)||i.length!==r||i.some(a=>a!==null&&typeof a!="string"))throw new Error;return i}catch{throw se("Invalid cursor for this query or identity; restart from the first page","cursor")}}var ls=new Set(["uuid","text","integer","bigint","boolean","timestamp","numeric","enum"]);function $r(n,e,t){let r=t;if("limit"in r||"offset"in r)throw se("page uses first/after or last/before, not limit/offset");let o=t.last!==void 0||t.before!==void 0;if(o&&(t.first!==void 0||t.after!==void 0))throw se("Use first/after or last/before in one page request");let s=(o?t.last:t.first)??50;if(!Number.isInteger(s)||s<1||s>1e3)throw se("page size must be an integer between 1 and 1000");if(e.length===0)throw new Error("page requires a declared primary key for a unique, stable ordering");U(t.orderBy,"orderBy","the order");let i=t.orderBy===void 0?[]:Array.isArray(t.orderBy)?t.orderBy:[t.orderBy];if(i.length>16)throw se("page supports at most 16 ordering columns");let a=new Set,f=[],l=d=>{U(d,"orderBy","the order");let g=n[d?.column];if(!Object.hasOwn(n,d?.column)||!g)throw se(`page order column ${d?.column} is not declared`);if(!ls.has(g.type??""))throw se(`page cannot order ${d.column}: ${g.type??"unknown"} is not a supported scalar column`);if(a.has(d.column))throw se(`page order column ${d.column} is repeated`);if(d.direction!==void 0&&d.direction!=="asc"&&d.direction!=="desc")throw se("page direction must be asc or desc");if(d.nulls!==void 0&&d.nulls!=="first"&&d.nulls!=="last")throw se("page nulls must be first or last");let c=d.direction??"asc";a.add(d.column),f.push({column:d.column,direction:c,nulls:d.nulls??(c==="asc"?"last":"first"),nullable:g.nullable!==!1})};for(let d of i)l(d);for(let d of e)a.has(d)||l({column:d,direction:f.at(-1)?.direction??"asc"});return{order:f,size:s,backward:o,token:o?t.before:t.after}}function ot(n,e,t,r,o,s=!1){let i=e.map(l=>r(l));if(n.every(l=>!l.nullable&&l.direction===n[0].direction)&&e.every(l=>l!==null)){let l=n[0].direction==="asc"!==t;return`(${n.map(d=>o(d.column)).join(", ")}) ${l?">":"<"}${s?"=":""} (${i.join(", ")})`}let a=[],f=[];for(let l=0;l<n.length;l++){let d=n[l],g=o(d.column),c=i[l],p=d.nulls==="last"!==t,m=d.direction==="asc"!==t?">":"<",u=e[l]===null?p?"false":`${g} IS NOT NULL`:`(${g} ${m} ${c}${p?` OR ${g} IS NULL`:""})`;a.push(`(${[...f,u].join(" AND ")})`),f.push(`${g} IS NOT DISTINCT FROM ${c}`)}return s&&a.push(`(${f.join(" AND ")})`),`(${a.join(" OR ")})`}import{randomBytes as cs}from"node:crypto";var us=16,ds=2,Sr="force_custom_plan",fs=16384,ms=256,ps=2e3,gs=256,ws=/^\s*(?:\(\s*)*(?:select|insert|update|delete|merge|values|with|table)\b/i,hs=/\bdeallocate\b/i,ys=/'\s*(?:now|today|tomorrow|yesterday)\s*'/i;function kr(n){return hs.test(n)}function bs(n,e){if(n.length>fs||!ws.test(n)||ys.test(n))return;let t=e?n:n.replace(/;\s*$/,"");if(!t.includes(";")&&!(!e&&t.includes("*")))return t}function vr(n,e,t){if(!(e.length===0||e.length>ms)){for(let r of e)if(r!==null&&(typeof r!="string"||r.includes("\0")))return;return bs(n,t)}}var Es=0,Rs=0,xr=cs(5).toString("hex"),$n=class{texts=new Map;sessions=new Map;mark(){return`${xr}_${++Rs}`}on(e){let t=this.sessions.get(e);return t!==void 0?this.sessions.delete(e):t=new st(this),this.sessions.set(e,t),this.sessions.size>gs&&this.sessions.delete(this.sessions.keys().next().value),t}count(e,t,r){vr(e,t,r)!==void 0&&this.sent(e)}sent(e){let t=(this.texts.get(e)??0)+1;return this.texts.delete(e),this.texts.set(e,t),this.texts.size>ps&&this.texts.delete(this.texts.keys().next().value),t}},st=class{statements=new Map;refused=0;all;constructor(e){this.all=e}get size(){return this.statements.size+this.refused}run(e,t,r){let o=vr(e,t,r);if(o===void 0)return;let s=this.all.sent(e),i=this.statements.get(e),a;if(i===void 0){if(s<ds||this.size>=us)return;i=`palgres_${xr}_${++Es}`,a=`PREPARE ${i} (${t.map(()=>"unknown").join(", ")}) AS ${o}`,this.statements.set(e,i)}let f=i,l=o.includes("/*")||o.includes("*/")?"":`/* ${o} */ `;return{prepare:a,execute:`${l}EXECUTE ${i}(${t.map(d=>d===null?"NULL":J(d)).join(", ")})`,failed:(d,g)=>this.failed(e,f,d,g)}}forget(){this.statements.clear(),this.refused=0}failed(e,t,r,o){let s=le(r);if(s==="26000")return this.forget();this.statements.get(e)===t&&(o?this.statements.delete(e):s==="0A000"&&(this.statements.delete(e),this.refused++))}};import{AsyncResource as Zr}from"node:async_hooks";var Ts=5e3,Sn=()=>new te(503,"database_deadline_exceeded","Database transaction exceeded its deadline"),qe=class{deadline;controller=new AbortController;active=new Set;cancelBackend;cancellation=Promise.resolve();cancelledAt;timer;unlink;rejection;get signal(){return this.controller.signal}constructor(e,t){this.deadline=e===void 0?void 0:performance.now()+e,this.rejection=new Promise((o,s)=>{this.signal.addEventListener("abort",()=>{s(this.signal.reason),this.active.size&&this.cancelBackend&&this.cancel()},{once:!0})}),this.rejection.catch(()=>{});let r=()=>this.controller.abort(t?.reason??new DOMException("Database transaction cancelled","AbortError"));t?.addEventListener("abort",r,{once:!0}),this.unlink=()=>t?.removeEventListener("abort",r),t?.aborted&&r(),e!==void 0&&(this.timer=setTimeout(()=>this.controller.abort(Sn()),e))}check(){this.deadline!==void 0&&performance.now()>=this.deadline&&!this.signal.aborted&&this.controller.abort(Sn()),this.signal.throwIfAborted()}checkDeadline(){if(!(this.deadline===void 0||performance.now()<this.deadline))throw this.signal.aborted||this.controller.abort(Sn()),Sn()}remainingMs(){return this.check(),this.deadline===void 0?void 0:Math.max(1,Math.ceil(this.deadline-performance.now()))}race(e){return Promise.race([e,this.rejection])}bindBackend(e){this.cancelBackend=e}async drainCancellation(){let e=(async()=>(await this.cancellation,await Promise.allSettled([...this.active]),!0))();if(this.cancelledAt===void 0)return e;let t,r=new Promise(o=>{t=setTimeout(()=>o(!1),Math.max(0,this.cancelledAt+Ts-performance.now()))});try{return await Promise.race([e,r])}finally{clearTimeout(t)}}async watch(e){this.active.add(e);try{return this.signal.aborted&&this.cancelBackend&&this.cancel(),await e}finally{this.active.delete(e)}}cancel(){this.cancelledAt??=performance.now(),this.cancellation=this.cancelBackend().catch(()=>{})}dispose(){this.timer!==void 0&&clearTimeout(this.timer),this.unlink()}};import{createHash as $s}from"node:crypto";var kn=class{start=performance.now();options;ended;failure;state;constructor(e){this.options=e;for(let t of["maxQueries","maxRows","maxBytes"]){let r=e[t];if(r!==void 0&&(!Number.isSafeInteger(r)||r<0))throw new Error(`database ${t} must be a nonnegative safe integer`)}this.state={endpoint:e.endpoint,requestId:e.requestId,outcome:"active",elapsedMs:0,queries:0,rows:0,bytes:0,queueMs:0,poolMs:0,setupMs:0,sqlMs:0,commitMs:0,rollbackMs:0,connectionMs:0,commits:0,commitFailures:0,rollbackRequests:0,retries:0,statements:[]}}check(){if(this.failure)throw this.failure}time(e,t){this.state[e]=(this.state[e]??0)+performance.now()-t}retry(){this.state.retries++}committed(){this.state.commits++}commitFailed(){this.state.commitFailures++}failed(){this.state.outcome="failed"}rolledBack(){this.state.rollbackRequests++}refuse(e){throw this.failure??=new te(500,"database_budget_exceeded",`Database ${e} budget exceeded${this.options.endpoint?` in ${this.options.endpoint}`:""}`),this.failure}emit(e,t){try{let r=e?.(t);r&&Promise.resolve(r).catch(()=>{})}catch{}}async query(e,t){this.check(),this.options.maxQueries!==void 0&&this.state.queries>=this.options.maxQueries&&this.refuse("query count");let o={ordinal:++this.state.queries,fingerprint:$s("sha256").update(e).digest("hex").slice(0,24),...this.options.includeSql?{sql:e.slice(0,4096)}:{},durationMs:0,rows:0,bytes:0};this.options.captureSource&&(o.source=new Error().stack?.split(`
|
|
30
30
|
`).slice(1,9).join(`
|
|
31
|
-
`).slice(0,2500));let s=performance.now(),i=!1;try{let a=await t();return o.durationMs=performance.now()-s,i=!0,Array.isArray(a)&&(o.rows=a.length,o.bytes=Buffer.byteLength(JSON.stringify(a,(p,l)=>typeof l=="bigint"?l.toString():l))),this.state.rows+=o.rows,this.state.bytes+=o.bytes,this.options.maxRows!==void 0&&this.state.rows>this.options.maxRows&&this.refuse("returned rows"),this.options.maxBytes!==void 0&&this.state.bytes>this.options.maxBytes&&this.refuse("result bytes"),a}catch(a){let p=a;throw o.errorCode=String(p?.errno??p?.code??"query_failed").slice(0,80),a}finally{i||(o.durationMs=performance.now()-s),this.state.sqlMs+=o.durationMs;let a=Object.freeze(o);this.state.statements.length<200&&this.state.statements.push(a),this.emit(this.options.onQuery,a)}}get snapshot(){return Object.freeze({...this.state,elapsedMs:(this.ended??performance.now())-this.start,statements:Object.freeze([...this.state.statements].sort((n,t)=>n.ordinal-t.ordinal))})}complete(n){this.ended===void 0&&(this.ended=performance.now(),this.state.outcome=n,this.emit(this.options.onComplete,this.snapshot))}};var Cr=new WeakMap,qr=new WeakSet;function Q(e){let n=t=>`$${e.push(t)}`;return Cr.set(n,e),n}var lt=e=>qr.has(e);var _r=e=>`'${e.replace(/'/g,"''")}'`;function ue(e,n){let t=e.columns.get(n);return t?yr(t):null}function ee(e,n,t,r){if(!e.columns.has(n))throw e.ignored.has(n)?new Error(`${t}(${e.key}): ${r} "${n}" is .ignored() in this version \u2014 the version has promised not to name it, so the next one can drop it`):new Error(`${t}(${e.key}): ${r} "${n}" is not a column of the table`)}function de(e,n,t){if(e.encrypted.has(n))throw new Error(`palgres: ${e.key}.${n} is .encrypted() \u2014 its value is not bound as it is (an engine path that reached it without sealing it)`);if(t==null)return t;let r=e.transforms.get(n)?.toDb,o=r===void 0?t:r(t),s=ue(e,n);return s===null||o===null||o===void 0?o:s.endsWith("[]")&&Array.isArray(o)?ze(o):br(s)?JSON.stringify(o):o}function Lr(e,n){return n.flatMap(t=>{let r=e.encrypted.get(t)?.lookup;return r?[t,r]:[t]})}function Ee(e,n){return Lr(e,n).map(x).join(", ")}function xs(e,n,t){return n.map(r=>{let o=e.encrypted.get(r);if(o===void 0)return r;if(o.lookup===null)throw new Error(`${t}(${e.key}): onConflict names "${r}", which is .encrypted() without { lookup: true } \u2014 no key is kept on it`);return o.lookup})}function Ir(e,n,t,r,o,s){if(Ve(r)!==null)throw new Error(`${s}(${e.key}): "${n}" is .encrypted() \u2014 the database holds no value there to compute with; write the value`);if(r===null)return t.lookup?[o(null),o(null)]:[o(null)];if(typeof r!="string")throw new TypeError(`${s}(${e.key}): "${n}" is .encrypted(), a text column \u2014 got ${typeof r}`);let{cipher:i,sealing:a}=e.fields;a.get(t.address)?.direction==="seal"&&on(t.address,r);let p=o(i.encrypt(t.address,r)),l=a.get(t.address)?.direction==="seal"?`CASE WHEN EXISTS (SELECT 1 FROM ${qn} WHERE address = ${o(t.address)} AND phase = 'mixed') THEN ${o(r)}::text ELSE ${p}::text END`:p;return t.lookup?[l,o(i.lookup(t.address,r))]:[l]}function Mr(e,n,t,r,o){let s=e.encrypted.get(n);return s===void 0?null:Ir(e,n,s,t,r,o)}function Br(e,n,t,r,o){let s=e.encrypted.get(t);return s===void 0?[o(ct(e,n,t,r))]:(Ue(n,e.key,[t],r),zn(n,e.key,[t],r),Ir(e,t,s,r[t],o,n))}function xn(e,n,t,r){if(e.encrypted.has(n))throw new Error(`${t}(${e.key}): ${r} names "${n}", which is .encrypted() \u2014 the database holds its ciphertext, not its value, so nothing there orders, ranges, groups or matches it`)}function Kr(e,n,t){let r=t.find(o=>e.databaseOnly.has(o));if(r!==void 0)throw new Error(`${n}(${e.key}): "${r}" is written by the database (an ALWAYS .identity()) \u2014 leave it out of the write; Postgres refuses any value for it`)}function Le(e,n,t){for(let r of t)ee(e,r,n,"column");Kr(e,n,t)}function ct(e,n,t,r){return Ue(n,e.key,[t],r),zn(n,e.key,[t],r),de(e,t,r[t])}function ut(e,n,t){let r=`${t?`${x(t)}.`:""}${x(n)}`;return Se(ue(e,n),r)??r}function jr(e,n,t){let r=ut(e,n,t);return Se(ue(e,n),"x")!==null?`${r} AS ${x(n)}`:r}function H(e,n){let t=n??"",r=e.projections.get(t);return r===void 0&&(r=[...e.columns.keys()].map(o=>jr(e,o,n)).join(", "),e.projections.set(t,r)),r}function dt(e,n,t){if(U(n,"select","which columns a call reads"),n!==void 0&&n.length===0)throw new Error(`${t}(${e.key}): select got an empty list \u2014 that is not "all of them" but "none counted". Leave the key out for every column; name at least one otherwise.`);return n===void 0?H(e,"t"):n.map(r=>(ee(e,r,t,"select column"),jr(e,r,"t"))).join(", ")}function Wr(e,n,t,r="t"){if(n==null)return"";U(n,"orderBy","the order");let o=Array.isArray(n)?n:[n];return o.length===0?"":` ORDER BY ${o.map(i=>{U(i,"orderBy","the order"),ee(e,i.column,t,"orderBy column"),xn(e,i.column,t,"orderBy");let a=i.direction==="desc"?"DESC":"ASC",p=i.nulls==="first"?" NULLS FIRST":i.nulls==="last"?" NULLS LAST":"";return`${x(r)}.${x(i.column)} ${a}${p}`}).join(", ")}`}function at(e,n="findMany"){if(e===void 0)return"";if(!Number.isInteger(e)||e<0)throw new Error(`${n}: limit must be a non-negative integer (got ${String(e)})`);return` LIMIT ${e}`}function Os(e,n,t="findMany"){if(e===void 0)return"";if(!Number.isInteger(e)||e<0)throw new Error(`${t}: offset must be a non-negative integer (got ${String(e)})`);if(n===void 0)throw new Error(`${t}: offset is given only with limit \u2014 an offset without one is the shifted tail of an unbounded result, not a page`);return` OFFSET ${e}`}var qe={gt:">",gte:">=",lt:"<",lte:"<=",neq:"<>"},As=[["days","days","int"],["hours","hours","int"],["minutes","mins","int"],["seconds","secs","double precision"]];function _e(e,n){let t=e?.minus;if(t===void 0)return"now()";let r=jt(t);if("refused"in r)throw new TypeError(`palgres: ago() ${r.refused}`);return`(now() - make_interval(${As.filter(([s])=>r.span[s]!==void 0).map(([s,i,a])=>`${i} => ${n(r.span[s])}::${a}`).join(", ")}))`}var Pr=Object.freeze({update:"FOR UPDATE",share:"FOR SHARE",noKeyUpdate:"FOR NO KEY UPDATE"});function ft(e,n,t,r){if(typeof r=="string"&&Object.hasOwn(Pr,r))return Pr[r];let o=typeof r=="string"?JSON.stringify(r.slice(0,40)):typeof r;throw new TypeError(`${e}(${n}): unknown ${t} ${o} \u2014 "update" (FOR UPDATE), "share" (FOR SHARE) or "noKeyUpdate" (FOR NO KEY UPDATE).`)}var Nr=e=>Ve(e);function Dr(e,n,t,r){if(!e.columns.has(n.$col))throw new Error(`${t}(${e.key}): col("${n.$col}") is not a column of the table`);return`${x(r)}.${x(n.$col)}`}function Fr(e,n,t,r){let s=(t.kind==="many"?e.table(t.to,r):n).columns.get(t.via)?.references?.column??(t.kind==="many"?n.singleKey:e.table(t.to,r).singleKey);return t.kind==="many"?[s,t.via]:[t.via,s]}function ke(e,n,t){return pe(new ge({fields:[{field:n,message:t}]},`${e}: ${n} ${t}`))}function Ps(e,n){if(U(e,n,"a filter"),!(typeof e!="object"||e===null))for(let[t,r]of Object.entries(e))t==="OR"||t==="AND"||t==="NOT"||t==="has"?U(r,`${n}.${t}`,`a filter's ${t}`):r!==null&&typeof r=="object"&&!Array.isArray(r)&&U(r,`${n}.${t}`,"an operator")}function vn(e,n,t,r,o,s,i,a){let p=[];if(Ps(t,a),Kt(o,n.key,t),Ne(t)){let{text:l,values:m}=t.$sql,w=Cr.get(r);if(w===void 0)throw new Error("palgres: an sqlFragment was compiled outside binder()");if(qr.add(w),l.length!==m.length+1)throw new Error(`${o}(${n.key}): the sqlFragment's parts are broken (${l.length} texts, ${m.length} values) \u2014 only the template tag makes one`);let c=l[0]??"";for(let f=0;f<m.length;f++)c+=`${r(m[f])}${l[f+1]??""}`;if(c.trim()==="")throw ke(o,a,"is an empty sqlFragment \u2014 no condition. Write the condition in it, or leave it out.");return[`(${c})`]}for(let[l,m]of Object.entries(t)){if(l==="OR"||l==="AND"){let u=m;if(u.length===0){if(l==="AND")throw ke(o,`${a}.AND`,"is an empty list \u2014 no condition at all. Leave it out, or name a condition in it.");p.push("false");continue}let g=u.map((h,y)=>{let E=vn(e,n,h,r,o,s,i,`${a}.${l}[${y}]`);if(E.length===0)throw ke(o,`${a}.${l}[${y}]`,"holds no condition \u2014 a branch that matches every row. Name a condition in it, or leave it out.");return`(${E.join(" AND ")})`});p.push(`(${g.join(l==="OR"?" OR ":" AND ")})`);continue}if(l==="NOT"){if(Array.isArray(m))throw ke(o,`${a}.NOT`,"is a list \u2014 NOT takes one filter object. For several conditions, NOT: { AND: [...] } or NOT: { OR: [...] }.");let u=vn(e,n,m,r,o,s,i,`${a}.NOT`);if(u.length===0)throw ke(o,`${a}.NOT`,"holds no condition \u2014 NOT of nothing is not a filter. Name the condition to exclude.");p.push(`NOT (${u.join(" AND ")})`);continue}if(l==="has"){let u=Object.entries(m);if(u.length===0)throw ke(o,`${a}.has`,"names no relation \u2014 no condition. Name one: has: { <relation>: { \u2026 } }.");for(let[g,h]of u){let y=n.relations.find($=>$.name===g);if(y===void 0){let $=n.relations.map(b=>b.name).sort();throw new Error(`${o}(${n.key}): there is no relation has.${g}`+($.length>0?` (known: ${$.join(", ")}). Relations come from foreign keys; to rename one, references(..., { as, reverseAs }).`:". The table declares no foreign key, and relations come from them: references(() => <table>.<column>)."))}let[E,R]=Fr(e,n,y,o);if(E===null||R===null)throw new Error(`${o}(${n.key}): has.${g} cannot be built \u2014 "${E===null?n.key:y.to}" has no single-column primary key to correlate on; write the condition as an sqlFragment`);let v=e.table(y.to,o),P=`r${i+1}`,A=Ge(e,v,h??{},r,o,P,i+1,`${a}.has.${g}`),T=`${P}.${x(R)} = ${x(s)}.${x(E)}`;p.push(`EXISTS (SELECT 1 FROM ${v.sql} ${P} WHERE ${T}${A===""?"":` AND ${A}`})`)}continue}ee(n,l,o,"where column");let w=n.encrypted.get(l);if(w!==void 0){p.push(Ns(n,l,w,m,r,o,s,a));continue}let c=`${x(s)}.${x(l)}`,f=ue(n,l)?.endsWith("[]")===!0,d=u=>r(de(n,l,u));if(he(m)){p.push(`${c} = ${Dr(n,m,o,s)}`);continue}if(pn(m)){p.push(`${c} = ${_e(Nr(m),r)}`);continue}if(m!==null&&typeof m=="object"&&!Array.isArray(m))for(let[u,g]of Object.entries(m)){if(f&&(u==="contains"||u==="overlaps")){if(!Array.isArray(g))throw new Error(`${o}(${n.key}): where.${l}.${u} must be an array \u2014 ${l} is an array column`);p.push(`${c} ${u==="contains"?"@>":"&&"} ${d(g)}`);continue}if(!f&&(u==="contains"||u==="icontains"||u==="startsWith"||u==="endsWith")){if(typeof g!="string")throw new Error(`${o}(${n.key}): where.${l}.${u} must be a string`);let y=g.replace(/([\\%_])/g,"\\$1"),E=u==="startsWith"?`${y}%`:u==="endsWith"?`%${y}`:`%${y}%`;p.push(`${c} ${u==="icontains"?"ILIKE":"LIKE"} ${r(E)}`);continue}if(u==="isNull"){if(typeof g!="boolean")throw new Error(`${o}(${n.key}): where.${l}.isNull must be a boolean`);p.push(`${c} IS ${g?"NULL":"NOT NULL"}`);continue}if(u==="in"){if(!Array.isArray(g))throw new Error(`${o}(${n.key}): where.${l}.in must be an array`);if(g.some(he))throw new Error(`${o}(${n.key}): where.${l}.in takes values, not col() \u2014 compare with a column bare ({ ${l}: col("\u2026") }) or with gt/gte/lt/lte/neq`);if(g.length===0){p.push("false");continue}p.push(`${c} IN (${g.map(y=>d(y)).join(", ")})`);continue}if(pn(g)){if(!(u in qe))throw new Error(`${o}(${n.key}): where.${l}.${u} cannot take now() \u2014 for equality write it bare: { ${l}: now() }`);p.push(`${c} ${qe[u]} ${_e(Nr(g),r)}`);continue}if(mn(g))throw new Error(`${o}(${n.key}): where.${l}.${u} got a WRITE expression (increment/decrement), not a comparison value. For the server's time use now(); for a numeric threshold, the value.`);if(he(g)){if(!(u in qe))throw new Error(`${o}(${n.key}): where.${l}.${u} cannot take col() \u2014 for equality write it bare: { ${l}: col("\u2026") }`);p.push(`${c} ${qe[u]} ${Dr(n,g,o,s)}`);continue}let h=Bt(g);if(h!==null){let y=h==="col"?"col()":h==="sql"?"sqlFragment":"now()";throw new Error(`${o}(${n.key}): where.${l}.${u} got an imitation of ${y} \u2014 this object was not made by ${y} in this process. A filter from a request body cannot carry a handle; build the condition in your code.`)}if(u in qe){if(g===null&&u==="neq"){p.push(`${c} IS NOT NULL`);continue}p.push(`${c} ${qe[u]} ${d(g)}`);continue}throw new Error(`${o}(${n.key}): where.${l} has an unknown operator "${u}" (gt/gte/lt/lte/neq/in)`)}else m===null?p.push(`${c} IS NULL`):p.push(`${c} = ${d(m)}`)}return p}function Ns(e,n,t,r,o,s,i,a){let p=`${x(i)}.${x(n)}`;if(r===null)return`${p} IS NULL`;let l=u=>{throw new Error(`${s}(${e.key}): ${a}.${n} ${u} \u2014 "${n}" is .encrypted(): the database holds its ciphertext, so it is asked only isNull`+(t.lookup?", equality and in":" (equality needs .encrypted({ lookup: true }))"))};(he(r)||pn(r)||Ne(r))&&l("compares with an expression");let{cipher:m,sealing:w}=e.fields,c=w.get(t.address)!==void 0,f=u=>{if(t.lookup===null&&l("asks for equality"),u.some(R=>typeof R!="string")&&l("compares with a value that is not text"),u.length===0)return"false";let g=`${x(i)}.${x(t.lookup)}`,h=u.map(R=>o(m.lookup(t.address,R))),y=u.length===1?`${g} = ${h[0]}`:`${g} IN (${h.join(", ")})`;if(!c)return y;let E=u.map(R=>o(R));return`(${y} OR ${u.length===1?`${p} = ${E[0]}`:`${p} IN (${E.join(", ")})`})`};if(typeof r!="object"||Array.isArray(r))return f([r]);let d=[];for(let[u,g]of Object.entries(r))if(u==="isNull"){if(typeof g!="boolean")throw new Error(`${s}(${e.key}): where.${n}.isNull must be a boolean`);d.push(`${p} IS ${g?"NULL":"NOT NULL"}`)}else if(u==="in"){if(!Array.isArray(g))throw new Error(`${s}(${e.key}): where.${n}.in must be an array`);d.push(f(g))}else u==="neq"?d.push(g===null?`${p} IS NOT NULL`:`(${p} IS NOT NULL AND NOT ${f([g])})`):l(`asks ${u}`);return d.length===0&&l("holds no condition"),d.length===1?d[0]:`(${d.join(" AND ")})`}function Ge(e,n,t,r,o,s="t",i=0,a="where"){return vn(e,n,t,r,o,s,i,a).join(" AND ")}function fe(e,n,t,r,o){let s=vn(e,n,t,r,o,"t",0,"where");return{sql:s.length===0?"":` AND ${s.join(" AND ")}`,conditions:s.length}}function Ie(e,n){if(!(e.conditions>0))throw ke(n,"where",`holds no condition, so ${n} would reach EVERY row of the table. Name a condition.`)}function Ye(e,n,t,r,o){let s=Lr(e,n),i=xs(e,t,o);if(r!=="ignore"&&r!=="update")throw new TypeError(`palgres: a conflict's action is "ignore" or "update", not ${typeof r=="string"?JSON.stringify(String(r).slice(0,40)):typeof r}`);if(i.length===0){if(r==="ignore")return"ON CONFLICT DO NOTHING";throw new Error("palgres: ON CONFLICT DO UPDATE needs the columns a collision is matched on")}let a=`ON CONFLICT (${i.map(x).join(", ")})`;if(r==="ignore")return`${a} DO NOTHING`;let p=new Set(i),l=s.filter(m=>!p.has(m)).map(m=>`${x(m)} = EXCLUDED.${x(m)}`);return l.length?`${a} DO UPDATE SET ${l.join(", ")}`:`${a} DO UPDATE SET ${x(i[0])} = EXCLUDED.${x(i[0])}`}function mt(e,n,t,r,o){return Kr(e,o,n),n.map(s=>{let i=e.encrypted.get(s);if(i!==void 0){let[p,l]=Br(e,o,s,t,r);return`${x(s)} = ${p}${i.lookup?`, ${x(i.lookup)} = ${l}`:""}`}let a=Ve(t[s]);if(a!==null&&a.fn==="now")return`${x(s)} = ${_e(a,r)}`;if(a!==null){let p=e.transforms.get(s)?.toDb,l=p===void 0?a.by:p(a.by);return`${x(s)} = ${x(s)} ${a.fn==="inc"?"+":"-"} ${r(l)}`}return`${x(s)} = ${r(ct(e,o,s,t))}`}).join(", ")}function Xe(e,n,t,r,o){return n.map(s=>{if(e.encrypted.has(s))return Br(e,o,s,t,r).join(", ");let i=Ve(t[s]);if(i!==null&&i.fn==="now")return _e(i,r);if(i!==null){let a=i.fn==="inc"?"increment":"decrement";throw new Error(`${o}(${e.key}): "${s}" got ${a}() \u2014 the row does not exist yet, so there is no current value. Write the starting value; to change it once the row exists, updateMany({ where, set: { ${s}: ${a}(n) } }).`)}return r(ct(e,o,s,t))}).join(", ")}var Ds=new Set(["integer","bigint","numeric"]);function Ur(e){return e!==null&&Ds.has(e)}function Vr(e,n,t,r){xn(e,t,"aggregate",n);let o=`t.${x(t)}`,s=ue(e,t);if(n==="sum"||n==="avg")return`${n}(${o})::text AS ${x(r)}`;let i=s!==null&&!s.endsWith("[]")?Se(s,`${n}(${o})`):null;return i!==null?`${i} AS ${x(r)}`:s==="bigint"||s==="numeric"?`${n}(${o})::text AS ${x(r)}`:`${n}(${o}) AS ${x(r)}`}function Cs(e,n,t,r=[]){return`json_build_object(${[...n.map(s=>{let i=ue(e,s),a=`${t}.${x(s)}`,p=i==="numeric"||i==="bigint"?`${a}::text`:Se(i,a)??a;return`${_r(s)}, ${p}`}),...r].join(", ")})`}function On(e,n,t,r,o,s="t",i=0,a={value:0}){if(U(t,"with","which relations a call reads"),i>=3&&Object.values(t).some(Boolean))throw new Error(`${o}(${n.key}): with supports at most three relation levels`);let p=[],l=[],m=[];for(let[w,c]of Object.entries(t)){if(c===!1||c===void 0)continue;U(c,`with.${w}`,"which relations a call reads");let f=n.relations.find(N=>N.name===w);if(f===void 0){let N=n.relations.map(k=>k.name).sort();throw new Error(`${o}(${n.key}): there is no relation with.${w}`+(N.length>0?` (known: ${N.join(", ")})`:". The table declares no foreign key, and relations come from them")+". A relation is declared with references(() => <table>.<column>).")}let[d,u]=Fr(e,n,f,o);if(d===null||u===null)throw new Error(`${o}(${n.key}): with.${w} needs a single-column primary key at one end of the relation`);let g=e.table(f.to,o),h=typeof c=="object"&&c!==null?c:{},y=++a.value,E=`w${y}`;if(U(h.select,`with.${w}.select`,"which columns a call reads"),U(h.orderBy,`with.${w}.orderBy`,"the order"),h.select!==void 0&&(!Array.isArray(h.select)||h.select.length===0))throw new Error(`${o}(${n.key}): with.${w}.select must be a non-empty array of columns`);let R=Array.isArray(h.select)?h.select:[...g.columns.keys()];for(let N of R)ee(g,N,o,`with.${w}.select column`);let v=h.with;if(v!==void 0&&(v===null||typeof v!="object"||Array.isArray(v)))throw new Error(`${o}(${n.key}): with.${w}.with must be a relation object`);let P=v===void 0?{joins:[],jsonPairs:[]}:On(e,g,v,r,o,E,i+1,a),A=P.joins.length?` ${P.joins.join(" ")}`:"",T=Cs(g,R,E,P.jsonPairs),$=h.where!==void 0&&h.where!==null?Ge(e,g,h.where,r,o,E,y,`with.${w}.where`):"",b=`${E}.${x(u)} = ${x(s)}.${x(d)}`,O=$===""?b:`${b} AND ${$}`,D=h.limit;at(D,o);let C=f.kind==="many"?D:Math.min(1,D??1),q=Wr(g,h.orderBy,o,E)+at(C,o),_=`wj${y}`;f.kind==="many"?l.push(`LEFT JOIN LATERAL (SELECT coalesce(json_agg(x.o), '[]'::json) AS d FROM (SELECT ${T} AS o FROM ${g.sql} ${E}${A} WHERE ${O}${q}) x) ${x(_)} ON true`):l.push(`LEFT JOIN LATERAL (SELECT ${T} AS d FROM ${g.sql} ${E}${A} WHERE ${O}${q}) ${x(_)} ON true`),p.push(`${x(_)}."d" AS ${x(w)}`),m.push(`${_r(w)}, ${x(_)}."d"`)}return{select:p,joins:l,jsonPairs:m}}function pt(e,n,t,r){let o=[],s=Q(o),i=fe(e,n,t,s,"findMany").sql,a=Wr(n,r.orderBy,"findMany"),p=at(r.limit),l=Os(r.offset,r.limit),m=dt(n,r.select,"findMany"),w=r.with!==void 0&&Object.keys(r.with).length>0?On(e,n,r.with,s,"findMany"):{select:[],joins:[]},c=w.select.length>0?`${m}, ${w.select.join(", ")}`:m,f=w.joins.length>0?` ${w.joins.join(" ")}`:"",d=r.lock===void 0?"":` ${ft("findUnique",n.key,"lock",r.lock)} OF t`;return{sql:`SELECT ${c} FROM ${n.sql} t${f} WHERE true${i}${a}${p}${l}${d}`,params:o}}var it=50;function gt(e,n,t,r){if(n.search===void 0||n.singleKey===null)throw new Error(`search(${n.key}): the table declares no search`);if(t.text===void 0&&t.vector===void 0)throw new Error(`search(${n.key}): neither the query's words nor its vector to search by`);let o=[],s=Q(o),i=x(n.singleKey),a=fe(e,n,r.where??{},s,"search").sql,p=Math.max(r.limit*3,30),l=[];if(t.vector!==void 0){let w=`v."embedding" ${t.vector.operator} ${s(t.vector.literal)}::${t.vector.type}`;l.push(`sem AS (SELECT s."id", row_number() OVER (ORDER BY s."d", s."id") AS r FROM (SELECT t.${i} AS "id", ${w} AS "d" FROM ${t.vector.table} v JOIN ${n.sql} t ON t.${i} = v."id" WHERE true${a} ORDER BY ${w} LIMIT ${p}) s)`)}if(t.text!==void 0){let w=Pt(n.search.from,"t"),c=`websearch_to_tsquery('simple', ${s(t.text)})`;l.push(`kw AS (SELECT s."id", row_number() OVER (ORDER BY s."k" DESC, s."id") AS r FROM (SELECT t.${i} AS "id", ts_rank_cd(${w}, ${c}) AS "k" FROM ${n.sql} t WHERE ${w} @@ ${c}${a} ORDER BY "k" DESC LIMIT ${p}) s)`)}l.push(l.length===2?`fused AS (SELECT coalesce(sem."id", kw."id") AS "id", (coalesce(1.0 / (${it} + sem.r), 0) + coalesce(1.0 / (${it} + kw.r), 0))::float8 AS "score" FROM sem FULL OUTER JOIN kw ON sem."id" = kw."id")`:`fused AS (SELECT x."id", (1.0 / (${it} + x.r))::float8 AS "score" FROM ${t.vector!==void 0?"sem":"kw"} x)`);let m=r.minScore===void 0?"":` AND f."score" >= ${s(r.minScore)}`;return{sql:`WITH ${l.join(", ")} SELECT ${H(n,"t")}, f."score" AS "_score" FROM fused f JOIN ${n.sql} t ON t.${i} = f."id" WHERE true${m} ORDER BY f."score" DESC, t.${i} LIMIT ${qs(r.limit)}`,params:o}}function qs(e){if(!Number.isInteger(e)||e<1)throw new Error(`search: limit must be a positive integer (got ${String(e)})`);return e}function Hr(e){return e instanceof Date?e.toISOString():Array.isArray(e)?e.map(Hr):e}function wt(e){if(e===null||typeof e!="object")return e;let n={};for(let[t,r]of Object.entries(e))n[t]=Hr(r);return n}function _s(e,n){for(let[t,r]of n.transforms){if(r.fromDb===void 0)continue;let o=e[t];o!=null&&(e[t]=r.fromDb(o))}return e}function Qe(e,n,t,r){let o=t.map(s=>_s(wt(s),n));if(r)for(let s of n.relations){let i=r[s.name];if(!i)continue;let a=typeof i=="object"?i.with:void 0,p=e.table(s.to,"with");for(let l of o){let m=l[s.name];Array.isArray(m)?l[s.name]=Qe(e,p,m,a):m&&typeof m=="object"&&(l[s.name]=Qe(e,p,[m],a)[0])}}return Pe(o)}var Ls={inline:!0},ht={inline:!0,read:!0},Is=e=>le(e)===Z.uniqueViolation||ve.is(e);function zr(e,n){if(n===null)return!1;let t=Object.keys(e);if(t.length!==1||t[0]!==n)return!1;let r=e[n];return r!==null&&(typeof r!="object"||Array.isArray(r))}var Ms=6e4;function Ze(e,n){let{cat:t}=n,r=(c,f)=>t.table(c,f),o=(c,f)=>{let d=t.table(c,f);return d.search!==void 0&&n.searchable?.(),d},s=async(c,f=[],d=!1)=>await(await e()).unsafe(c,f,lt(f)?void 0:d?ht:Ls),i=(c,f=[])=>s(c,f,!0),a=async(c,f=[])=>await(await e()).unsafe(c,f),p=async(c,f)=>{let d=t.deferral(c);if(d===null)return f();await s(d.defer);let u=await f();return await s(d.check),u},l=(c,f,d)=>Qe(t,c,f,d),m=(c,f)=>Qe(t,c,[f])[0],w={diagnostics(){return n.trace?.snapshot??null},async query(c,f=[]){return Pe((await a(c,f)).map(d=>wt(d)))},async insert(c,f){let d=o(c,"insert"),u=Object.keys(f);if(u.length===0)throw new Error(`insert into ${c}: no columns given`);Le(d,"insert",u);let g=[],h=Xe(d,u,f,Q(g),"insert"),y=await s(`INSERT INTO ${d.sql} (${Ee(d,u)}) VALUES (${h}) RETURNING ${H(d)}`,g);if(!y[0])throw new Error(`insert into ${c} returned no row \u2014 the write was rejected (an RLS policy, most likely).`);return m(d,y[0])},insertMany:(async function(c,f,d){if(Wt(d),f.length===0)return d?.returning===!1?0:[];let u=o(c,"insertMany"),g=Object.keys(f[0]);if(g.length===0)throw new Error(`insertMany into ${c}: no columns given`);for(let A=1;A<f.length;A++){let T=g.filter(b=>!(b in f[A])),$=Object.keys(f[A]).filter(b=>!g.includes(b));if(T.length>0||$.length>0)throw new Error(`insertMany(${c}): row ${A} does not have the first row's columns`+(T.length>0?` (missing: ${T.join(", ")})`:"")+($.length>0?` (extra: ${$.join(", ")})`:"")+". One statement shares the column list: write null for a missing value, or insert differently shaped rows in calls of their own.")}Le(u,"insertMany",g),U(d?.onConflict,"onConflict","which columns a conflict is on");for(let A of d?.onConflict??[])ee(u,A,"insertMany","onConflict column");let h=[],y=Q(h),E=f.map(A=>`(${Xe(u,g,A,y,"insertMany")})`),R=d?.onConflict??[],v=R.length>0||d?.action==="ignore"?` ${Ye(u,g,R,d?.action??"ignore","insertMany")}`:"",P=await s(`INSERT INTO ${u.sql} (${Ee(u,g)}) VALUES ${E.join(", ")}${v}${d?.returning===!1?"":` RETURNING ${H(u)}`}`,h);if(d?.returning===!1){if(!Number.isSafeInteger(P.count)||P.count<0)throw new Error("insertMany returning:false requires a driver with an affected row count");return P.count}return l(u,P)}),async advisoryXactLock(c){await s("SELECT pg_advisory_xact_lock(hashtextextended($1, 0))",[c])},async lockRows(c,f){let d=[...new Set(f)].sort();if(d.length===0)return;let u=r(c,"lockRows");if(u.singleKey===null)throw new Error(`lockRows(${c}): no single-column primary key \u2014 the lock order needs one`);let g=x(u.singleKey),h=[],y=Q(h),E=d.map(R=>y(de(u,u.singleKey,R))).join(", ");await s(`SELECT t.${g} FROM ${u.sql} t WHERE t.${g} IN (${E}) ORDER BY t.${g} FOR NO KEY UPDATE`,h)},async lockRowsWhere(c,f,d){let u=ft("lockRowsWhere",c,"mode",d?.mode===void 0?"update":d.mode),g=r(c,"lockRowsWhere");if(g.singleKey===null)throw new Error(`lockRowsWhere(${c}): no single-column primary key \u2014 the lock order needs one`);let h=[],y=fe(t,g,f,Q(h),"lockRowsWhere");Ie(y,"lockRowsWhere");let E=x(g.singleKey);await s(`SELECT t.${E} FROM ${g.sql} t WHERE true${y.sql} ORDER BY t.${E} ${u}`,h)},async claim(c,f,d={}){let u=o(c,"claim");U(f,"unique","which key a claim is on");let g=Object.keys(f);if(g.length===0)throw new Error(`claim(${c}): no unique field given. claim takes ownership of a key; with none there is nothing to own \u2014 use insert(${c}, \u2026).`);Ue("claim",c,g,f);for(let v of g){let P=f[v];if(P===null||typeof P=="object"||typeof P=="function")throw new Error(`claim(${c}): the unique field "${v}" is ${P===null?"null":"an object"} \u2014 a key is one value (a string, number, bigint or boolean); NULL never equals a claimed row.`)}let h=Object.keys(d).filter(v=>Object.hasOwn(f,v));if(h.length>0)throw new Error(`claim(${c}): ${h.map(v=>`"${v}"`).join(", ")} is in both the unique fields and extra \u2014 say a key once, in the unique fields.`);let y={...f,...d},E=Object.keys(y);Le(u,"claim",E);let R=await e();try{return await R.savepoint(async v=>{let P=[],A=Xe(u,E,y,Q(P),"claim"),T=await v.unsafe(`INSERT INTO ${u.sql} (${Ee(u,E)}) VALUES (${A}) RETURNING ${H(u)}`,P);if(!T[0])throw new Error(`claim(${c}): the INSERT returned no row \u2014 the write was rejected (an RLS policy, most likely).`);return{inserted:!0,row:m(u,T[0])}})}catch(v){if(!Is(v))throw v;let P=[],A=Q(P),T=Ge(t,u,f,A,"claim"),$=await s(`SELECT ${H(u,"t")} FROM ${u.sql} t WHERE ${T} LIMIT 1`,P);if(!$[0]){let b=je(v);throw new Error(`claim(${c}): a unique violation${b?` (${b})`:""} was caught but no row has these ${g.join(", ")}. Either the violation is of ANOTHER unique constraint \u2014 claim() is the wrong tool for this call \u2014 or the row exists and an RLS policy hides it from this caller.`)}return{inserted:!1,row:m(u,$[0])}}},async put(c,f,d){let u=o(c,"put"),g=d.onConflict;if(g.length===0)throw new Error(`put into ${c}: onConflict needs at least one column`);let h=Object.keys(f);if(h.length===0)throw new Error(`put into ${c}: no columns given`);Le(u,"put",h),U(g,"onConflict","which columns a conflict is on");for(let v of g)ee(u,v,"put","onConflict column");let y=[],E=Xe(u,h,f,Q(y),"put"),R=await s(`INSERT INTO ${u.sql} (${Ee(u,h)}) VALUES (${E}) ${Ye(u,h,g,"update","put")} RETURNING ${H(u)}`,y);if(!R[0])throw new Error(`put into ${c} returned no row \u2014 the write was rejected (an RLS policy, most likely).`);return m(u,R[0])},async update(c,f,d){let u=o(c,"update");if(!u.columns.has("id"))throw new Error(`update(${c}): the table has no "id" column \u2014 update a row by its key with updateMany({ where, set })`);let g=Object.keys(d);if(g.length===0)return w.findById(c,f);for(let v of g)ee(u,v,"update","set column");let h=[],y=Q(h),E=mt(u,g,d,y,"update"),R=await s(`UPDATE ${u.sql} SET ${E} WHERE "id" = ${y(de(u,"id",f))} RETURNING ${H(u)}`,h);return R[0]?m(u,R[0]):null},async delete(c,f){let d=r(c,"delete");if(!d.columns.has("id"))throw new Error(`delete(${c}): the table has no "id" column \u2014 delete by its key with deleteMany({ where })`);let u=[de(d,"id",f)];await p(d,()=>s(`DELETE FROM ${d.sql} WHERE "id" = $1`,u))},async updateMany(c,f,d,u){let g=o(c,"updateMany"),h=Object.keys(d);if(h.length===0)throw new Error(`updateMany(${c}): nothing to set. An update with no columns is not a no-op worth pretending happened \u2014 pass the columns to write.`);for(let _ of h)ee(g,_,"updateMany","set column");let y=[],E=Q(y),R=mt(g,h,d,E,"updateMany"),v=fe(t,g,f,E,"updateMany");Ie(v,"updateMany");let P=v.sql,A=g.singleKey,T=u?.returning!==!1,$=A===null||zr(f,A),b=T?`RETURNING ${H(g,"t")}`:"RETURNING 1",O=$?`UPDATE ${g.sql} AS t SET ${R} WHERE true${P} ${b}`:`UPDATE ${g.sql} AS t SET ${R} FROM locked WHERE t.${x(A)} = locked."__pb_lock" ${b}`,D=$?"":`WITH locked AS (SELECT t.${x(A)} AS "__pb_lock" FROM ${g.sql} t WHERE true${P} ORDER BY t.${x(A)} FOR NO KEY UPDATE)`,C=T?`${D} ${O}`.trim():$?`WITH upd AS (${O}) SELECT count(*)::int AS n FROM upd`:`${D}, upd AS (${O}) SELECT count(*)::int AS n FROM upd`,q=await s(C,y);return T?l(g,q):Number(q[0]?.n??0)},async deleteMany(c,f){let d=r(c,"deleteMany"),u=[],g=fe(t,d,f,Q(u),"deleteMany");return Ie(g,"deleteMany"),(await p(d,()=>s(`DELETE FROM ${d.sql} AS t WHERE true${g.sql} RETURNING 1`,u))).length},async aggregate(c,f={}){let d=r(c,"aggregate");for(let b of["sum","avg","min","max","groupBy"])U(f[b],b,"which columns an aggregate reads");U(f.count,"count","which counts an aggregate takes");let u=[],g=Q(u),h=[],y=[];for(let b of["sum","avg","min","max"])for(let O of f[b]??[]){if(ee(d,O,"aggregate",`${b} column`),(b==="sum"||b==="avg")&&!Ur(ue(d,O)))throw new Error(`aggregate(${c}): ${b}("${O}") on a column that is not numeric \u2014 "${O}" is ${ue(d,O)}. Only integer, bigint and numeric sum; to count rows, count: true.`);let D=`${b}__${O}`;y.push({fn:b,col:O,alias:D}),h.push(Vr(d,b,O,D))}f.count===!0&&h.push('count(*) AS "_count"');let E=f.count!==null&&typeof f.count=="object"?Object.entries(f.count):[];if(f.count!==void 0&&typeof f.count!="boolean"&&(f.count===null||typeof f.count!="object"||Array.isArray(f.count)||E.length===0))throw new Error(`aggregate(${c}): count is true, or named filters \u2014 { <name>: <filter> }, at least one`);if(E.forEach(([b,O],D)=>{let C=Ge(t,d,O,g,"aggregate","t",0,`count.${b}`);h.push(`count(*) FILTER (WHERE ${C===""?"true":C}) AS ${x(`count__${D}`)}`)}),h.length===0)throw new Error(`aggregate(${c}): no aggregate asked for \u2014 the result would be an empty object. Name sum/avg/min/max columns or count: true.`);let R=f.groupBy??[];for(let b of R)ee(d,b,"aggregate","groupBy column"),xn(d,b,"aggregate","groupBy");let v=R.map(b=>`${ut(d,b,"t")} AS ${x(`g__${b}`)}`),P=fe(t,d,f.where??{},g,"aggregate").sql,A=R.length>0?` GROUP BY ${R.map(b=>`t.${x(b)}`).join(", ")}`:"",T=await i(`SELECT ${[...v,...h].join(", ")} FROM ${d.sql} t WHERE true${P}${A}`,u),$=b=>{let O={};for(let D of R)O[D]=b[`g__${D}`];for(let D of y){let C=O[D.fn]??={};C[D.col]=b[D.alias]??null}return f.count===!0&&(O.count=Number(b._count??0)),E.length>0&&(O.count=Object.fromEntries(E.map(([D],C)=>[D,Number(b[`count__${C}`]??0)]))),O};return R.length>0?T.map($):$(T[0]??{})},async count(c,f={}){let d=r(c,"count"),u=[],g=fe(t,d,f,Q(u),"count").sql,h=await i(`SELECT count(*) AS n FROM ${d.sql} t WHERE true${g}`,u);return Number(h[0]?.n??0)},async findUnique(c,f,d={}){let u=r(c,"findUnique");pr(c,u.uniqueKeys,f);let g={select:d.select===void 0?void 0:Fe(d.select,[...d.select]),with:d.with,limit:2},h;if(d.lock===void 0)h=await w.findMany(c,f,g);else{let y=pt(t,u,f,{...g,lock:d.lock});h=l(u,await s(y.sql,y.params),d.with)}if(h.length>1)throw new Error(`findUnique(${c}): the database's constraints disagree with the schema; more than one row matched`);return h[0]??null},async findById(c,f){let d=r(c,"findById");if(!d.columns.has("id"))throw new Error(`findById(${c}): the table has no "id" column \u2014 use findUnique({ where: <its key> })`);let u=await i(`SELECT ${H(d)} FROM ${d.sql} WHERE "id" = $1`,[de(d,"id",f)]);return u[0]?m(d,u[0]):null},async findMany(c,f={},d={}){let u=r(c,"findMany"),g=pt(t,u,f,d),h=d.lock!==void 0;return l(u,await(h?s:i)(g.sql,g.params),d.with)},async search(c,f,d={}){let u=r(c,"search"),g=u.search;if(g===void 0)throw new Error(`search(${c}): the table declares no search \u2014 defineTable(${JSON.stringify(u.name)}, { \u2026, search: { from: [<its text columns>], model } })`);let h=ir(c,f,d),y=n.search,E=$=>l(u,$),R=async()=>{let $=gt(t,u,{text:h.text},{where:d.where,limit:h.limit,minScore:h.minScore});return E(await i($.sql,$.params))};if(h.mode==="text")return R();let v=y.embed;if(v===void 0)throw new Error(`search(${c}): no embedder was given, and a search by meaning embeds its query \u2014 createDatabase({ embed }) (the backend's db.embed); mode: "text" searches by word alone`);let P=$=>($===void 0?y.serving.delete(g.key):y.serving.set(g.key,$),$),A=y.serving.get(g.key)??P(et((await i(Zn,[g.key]))[0])),T;for(let $=1;;$++){if(A===void 0){if(h.mode==="vector")throw new Error(`search(${c}): the database holds no vectors for this table \u2014 its schema is migrated before the app serves`);return R()}if(T===void 0||T.of.model!==A.model||T.of.dimensions!==A.dimensions)try{T={of:A,literal:await ar(v,h.text,A)}}catch(k){if(h.mode==="vector")throw k;let S=Date.now();return S-(y.said.get(g.key)??-1/0)>=Ms&&(y.said.set(g.key,S),y.log?.(`palgres: search(${c}) answered by word alone: its query could not be embedded (${k instanceof Error?k.message:String(k)})`)),R()}let b=an(A.dimensions,A.metric),O=x(A.types),D=gt(t,u,{...h.mode==="hybrid"?{text:h.text}:{},vector:{table:`${x($e)}.${x(Ke(g.key,A.gen))}`,literal:T.literal,type:`${O}.${b.type}`,operator:`OPERATOR(${O}.${b.operator})`}},{where:d.where,limit:h.limit,minScore:h.minScore}),C=await e(),[q,_]=await Promise.all([C.unsafe(Zn,[g.key],ht),C.unsafe(D.sql,D.params,lt(D.params)?void 0:ht)]),N=P(et(q[0]));if(N!==void 0&&N.gen===A.gen)return E(_);if($>=3)throw new Error(`search(${c}): the vectors that serve the table changed while it was searched, three times over`);A=N}},async page(c,f={},d={}){let u=r(c,"page");if(n.cursorKey===null)throw new Error("Database.page needs a cursor secret shared by every replica: createDatabase({ cursorSecret })");let g=n.cursorKey,h=Object.create(null);for(let[B,X]of u.columns)h[B]={type:X.type,nullable:X.nullable&&!u.primaryKey.includes(B)};let{order:y,size:E,backward:R,token:v}=kr(h,u.primaryKey,d),P=[],A=Q(P),T=fe(t,u,f,A,"page").sql,$=dt(u,d.select===void 0?void 0:Fe(d.select,[...d.select]),"page"),b=rt({table:c,version:t.version,columns:h,order:y,where:T,params:P,select:d.select,with:d.with,identity:n.cursorScope()}),O=v===void 0?void 0:Sr(g,b,v,y.length),D=B=>`t.${x(B)}`,C=O?` AND ${ot(y,O,R,A,D)}`:"",q=O?`EXISTS (SELECT 1 FROM ${u.sql} t WHERE true${T} AND ${ot(y,O,!R,A,D,!0)})`:"false",_="__pb_page_",N=[...u.columns.keys(),...Object.keys(d.with??{})];for(;N.some(B=>B.startsWith(_));)_+="_";let k=`${_}ordinal`,S=`${_}opposite`,M=y.map((B,X)=>`${_}${X}`),L=y.map((B,X)=>`${ue(u,B.column)==="timestamp"?Se("timestamp",D(B.column)):`${D(B.column)}::text`} AS ${x(M[X])}`),I=d.with&&Object.keys(d.with).length?On(t,u,d.with,A,"page"):{select:[],joins:[]},j=y.map(B=>`${D(B.column)} ${B.direction==="asc"!==R?"ASC":"DESC"} NULLS ${B.nulls==="first"!==R?"FIRST":"LAST"}`).join(", "),K=`SELECT ${[$,...I.select,...L,`row_number() OVER (ORDER BY ${j}) AS ${x(k)}`].join(", ")} FROM ${u.sql} t ${I.joins.join(" ")} WHERE true${T}${C} ORDER BY ${j} LIMIT ${E+1}`,W=`SELECT p.*, b.${x(S)} FROM (SELECT ${q} AS ${x(S)}) b LEFT JOIN LATERAL (${K}) p ON true ORDER BY p.${x(k)}`,z=await i(W,P),Y=z[0]?.[S]===!0,V=z.filter(B=>B[k]!==null&&B[k]!==void 0),me=V.length>E;V=V.slice(0,E),R&&V.reverse();let G=B=>B?$r(g,b,M.map(X=>B[X]===null?null:String(B[X]))):null,ie={startCursor:G(V[0]),endCursor:G(V.at(-1)),hasNextPage:R?Y:me,hasPreviousPage:R?me:Y};for(let B of V)for(let X of[...M,k,S])delete B[X];return{rows:l(u,V,d.with),pageInfo:ie}},async attempt(c){return(await e()).savepoint(d=>c(Ze(()=>Promise.resolve(d),n)))},async txPlan(c){return(await e()).savepoint(async d=>{let u=[];for(let g of c.ops){let h=g.op==="select"||g.op==="delete"?r(g.table,"transaction plan"):o(g.table,"transaction plan"),y=js(t,h,g,u),E=g.op==="delete"?t.deferral(h):null;y!==null&&E!==null&&await d.unsafe(E.defer,[]);let R=y===null?[]:l(h,await d.unsafe(y.sql,y.params));y!==null&&E!==null&&await d.unsafe(E.check,[]);let v={rows:R,rows_affected:R.length};u.push(v),Ws(g,v)}return{results:u}})}};return w}function Bs(e,n){let t;return e.op<0||e.op>=n.length?t=`transaction plan: a reference points at operation ${e.op}, but the plan has run ${n.length} (0\u2026${n.length-1}). A reference can only read an EARLIER operation's row.`:n[e.op].rows[0]?t=`transaction plan: operation ${e.op}'s row has no column "${e.field}" (its columns: ${Object.keys(n[e.op].rows[0]).join(", ")}).`:t=`transaction plan: operation ${e.op} returned NO ROW, so "${e.field}" cannot be read. A reference does not guarantee its row exists \u2014 declare the expectation first (\`.expectOne(err)\`).`,Object.assign(new Error(t),{error_code:"tx_ref_unresolved"})}function Et(e,n){if(Mt(e))throw new Error(`${n}: got an imitation of a plan reference ({ $ref: \u2026 }) \u2014 this object was not made by the plan's builder. A reference is built in your code from an earlier operation's row (insert(...).expectOne(err).id); a filter from a request body cannot carry one.`)}function Rt(e,n){let t=n[e.$ref.op]?.rows[0];if(!t||!(e.$ref.field in t))throw Bs(e.$ref,n);return t[e.$ref.field]}function An(e,n,t,r,o,s){return Et(n,`transaction plan (${t})`),Mr(e,t,fn(n)?Rt(n,o):n,r,s)??[Ks(e,n,t,r,o)]}function Ks(e,n,t,r,o){if(Et(n,`transaction plan (${t})`),fn(n))return r(de(e,t,Rt(n,o)));if(It(n)){let s=n.$expr;return s.fn==="now"?_e(s,r):`${x(t)} ${s.fn==="inc"?"+":"-"} ${r(de(e,t,s.by))}`}return r(de(e,t,n))}function bt(e,n){if(Et(e,"transaction plan filter"),fn(e)){let t=Rt(e,n);if(t==null)throw Object.assign(new Error(`transaction plan: a filter's reference to operation ${e.$ref.op}'s "${e.$ref.field}" is NULL. As a filter value NULL means IS NULL \u2014 every row with no value there, not the one the reference named. Write null in the filter when that is what you mean.`),{error_code:"tx_ref_null"});if(typeof t=="object"&&!Array.isArray(t)&&!Lt(t))throw Object.assign(new Error(`transaction plan: a filter's reference to operation ${e.$ref.op}'s "${e.$ref.field}" is an object. A filter compares a column with a value; an object there would be read as operators. Reference a scalar column.`),{error_code:"tx_ref_object"});return t}if(Array.isArray(e))return Fe(e,e.map(t=>bt(t,n)));if(e!==null&&typeof e=="object"&&!he(e)&&!Ne(e)&&!mn(e)&&!(e instanceof Date)){let t=Fe(e,{});for(let[r,o]of Object.entries(e))t[r]=bt(o,n);return t}return e}function yt(e,n,t,r,o,s){if(t===void 0||Object.keys(t).length===0&&!Ne(t))return{sql:"",conditions:0,resolved:{}};let i=bt(t,o);return{...fe(e,n,i,r,s),resolved:i}}function js(e,n,t,r){let o=[],s=Q(o),i=`transaction plan ${t.op}`,a=t.op==="insertMany"?[...new Set((t.rows??[]).flatMap(l=>Object.keys(l)))]:Object.keys(t.values??t.set??{});Le(n,i,a);let p;switch(t.op){case"insert":{let l=t.values??{},m=Object.keys(l),w=m.flatMap(c=>An(n,l[c],c,s,r,i));p=m.length?`INSERT INTO ${n.sql} (${Ee(n,m)}) VALUES (${w.join(", ")}) RETURNING ${H(n)}`:`INSERT INTO ${n.sql} DEFAULT VALUES RETURNING ${H(n)}`;break}case"upsert":{let l=t.values??{},m=Object.keys(l),w=t.onConflict??[];if(m.length===0||w.length===0)throw Object.assign(new Error(`put on ${t.table} needs columns and onConflict`),{error_code:"tx_bad_upsert"});U(t.onConflict,"onConflict","which columns a conflict is on");for(let f of w)ee(n,f,i,"onConflict column");let c=m.flatMap(f=>An(n,l[f],f,s,r,i));p=`INSERT INTO ${n.sql} (${Ee(n,m)}) VALUES (${c.join(", ")}) ${Ye(n,m,w,"update",i)} RETURNING ${H(n)}`;break}case"insertMany":{let l=t.rows??[];if(l.length===0)return null;let m=Object.keys(l[0]),w=l.map(d=>`(${m.flatMap(u=>An(n,d[u],u,s,r,i)).join(", ")})`),c=t.onConflict??[];U(t.onConflict,"onConflict","which columns a conflict is on");for(let d of c)ee(n,d,i,"onConflict column");if(t.action==="update"&&c.length===0)throw Object.assign(new Error(`insertMany on ${t.table}: an overwrite needs onConflict columns`),{error_code:"tx_bad_upsert"});let f=t.action!==void 0?` ${Ye(n,m,c,t.action,i)}`:"";p=`INSERT INTO ${n.sql} (${Ee(n,m)}) VALUES ${w.join(", ")}${f} RETURNING ${H(n)}`;break}case"update":{let l=t.set??{},m=Object.keys(l);if(m.length===0)throw new Error(`update ${t.table}: nothing to set`);let w=m.map(d=>{let[u,g]=An(n,l[d],d,s,r,i),h=n.encrypted.get(d)?.lookup;return`${x(d)} = ${u}${h?`, ${x(h)} = ${g}`:""}`}),c=yt(e,n,t.where,s,r,i);Ie(c,i);let f=n.singleKey;p=f===null||zr(c.resolved,f)?`UPDATE ${n.sql} AS t SET ${w.join(", ")} WHERE true${c.sql} RETURNING ${H(n,"t")}`:`WITH locked AS (SELECT t.${x(f)} AS "__pb_lock" FROM ${n.sql} t WHERE true${c.sql} ORDER BY t.${x(f)} FOR NO KEY UPDATE) UPDATE ${n.sql} AS t SET ${w.join(", ")} FROM locked WHERE t.${x(f)} = locked."__pb_lock" RETURNING ${H(n,"t")}`;break}case"delete":{let l=yt(e,n,t.where,s,r,i);Ie(l,i),p=`DELETE FROM ${n.sql} AS t WHERE true${l.sql} RETURNING ${H(n,"t")}`;break}case"select":{let l="";if(t.limit!==void 0){let w=Number(t.limit);if(!Number.isInteger(w)||w<0)throw new Error(`transaction plan (${t.table}): limit must be an integer, got "${String(t.limit)}"`);l=` LIMIT ${w}`}let m=t.lock==="update"?" FOR UPDATE":"";p=`SELECT ${H(n,"t")} FROM ${n.sql} t WHERE true${yt(e,n,t.where,s,r,i).sql}${l}${m}`;break}default:throw new Error(`unknown operation "${String(t.op)}" in a transaction plan`)}return{sql:p,params:o}}function Ws(e,n){let t=e.guard;if(!t)return;let r=n.rows.length;if(!(t.kind==="one"?r===1:t.kind==="none"?r===0:t.kind==="atLeast"?r>=t.n:r<=t.n))throw Object.assign(new Error(`transaction expectation failed: ${t.kind} (${r} row(s))`),{error_code:"tx_guard_failed",slot:t.slot})}import{AsyncLocalStorage as Gr}from"node:async_hooks";import{randomUUID as Fs}from"node:crypto";var Pn=new Gr,Jr=()=>({running:new Set}),Us=e=>String(e?.message??e);function Vs(e){return new Oe(`The transaction was rolled back, not committed: a statement in it failed (${Us(e)}) and the code went on. One failed statement aborts the whole transaction \u2014 Postgres refuses every later one and answers COMMIT with ROLLBACK. Wrap a write you expect to fail in \`Database.$attempt(async (tx) => \u2026)\` \u2014 it takes a SAVEPOINT, so only that write rolls back \u2014 or use \`Database.public.<t>.put({ data, onConflict: [...] })\` when what you brace for is a duplicate row.`,e)}async function Qr(e){for(;e.running.size;)await Promise.allSettled([...e.running])}function Yr(e,n){let t=n.bind;if(n.lockTimeout!==void 0&&(t+=`, set_config('lock_timeout', ${J(n.lockTimeout)}, true)`),n.statementTimeout!==void 0&&(t+=`, set_config('statement_timeout', ${J(n.statementTimeout)}, true)`),!/^select /i.test(t))throw new Error("palgres: the binding statement must be a SELECT list");t+=", pg_catalog.current_setting('transaction_isolation') AS palgres_isolation",n.prepared!==void 0&&(t+=`, pg_catalog.current_setting('palgres.session', true) AS palgres_session, CASE WHEN coalesce(pg_catalog.current_setting('palgres.session', true), '') = '' THEN pg_catalog.set_config('palgres.session', ${J(n.prepared.mark())}, false) END AS palgres_marked, pg_catalog.set_config('plan_cache_mode', ${J(vr)}, true) AS palgres_plans`);let r=null,o=null,s=null,i=null,a=!1,p=null,l=Jr(),m=!0,w,c=!1,f,d=async()=>!n.control||await n.control.drainCancellation()?!0:(f?.abandon?.(),!1),u,g=!1,h=(C,q,_,N)=>{if(n.prepared===void 0)return _;let k=_?.inline===!0;if(!k&&xr(C))return u===void 0?g=!0:u.forget(),_;if(u===void 0)return n.prepared.count(C,q,k),_;if(N.refused!==void 0)return _;let S=u.run(C,q,k);return S===void 0?_:{..._,prepared:S}},y=()=>{c=!0},E=()=>{if(a)throw new Error("Database transaction has settled; its handle cannot be used again");if(n.control?.check(),n.trace?.check(),Pn.getStore()!==n.scope)throw new Error("Database.$atomic cannot use a handle from another transaction or identity; use its tx argument")},R,v,P=new Set,A=0,T=!1,$=()=>r!==null&&!a&&c&&l.running.size===0&&P.size===0,b=(C,q,_=E,N,k=new Set)=>{let S=()=>{if(_(),v!==N||R?.getStore()!==N)throw new Error("Database connection belongs to another active savepoint; use its tx argument and await it before using the parent handle")};return{unsafe(M,L,I){try{S()}catch(W){return Promise.reject(W)}I?.read!==!0&&(m=!1);let j=(L??[]).map(De),K=()=>{let W=C.unsafe(M,j,h(M,j,I,q)),z=Promise.resolve(n.control?n.control.watch(W):W).catch(Y=>{throw cn(Y)&&(q.refused??={error:Y}),Y});return q.running.add(z),A++,z.catch(()=>{}).finally(()=>{q.running.delete(z),y(),--A===0&&!a&&n.onIdle?.()}),z};return n.trace?n.trace.query(M,K):K()},async savepoint(M){S(),m=!1;let L=Symbol("savepoint"),I=new Set,j=Jr();R??=new Gr,v=L;let K=(async()=>{try{return await C.savepoint(async W=>{let z=!1,Y=()=>{if(_(),z)throw new Error("Database savepoint has settled; its handle cannot be used again")};try{let V=R.run(L,()=>M(b(W,j,Y,L,I))),me=await(n.control?n.control.race(V):V);if(await Qr(j),j.refused)throw j.refused.error;return me}finally{I.size&&await Promise.allSettled([...I]),z=!0}})}finally{v=N}})();P.add(K),k.add(K);try{return await K}finally{P.delete(K),k.delete(K)}}}},O=async()=>(E(),r||(r=new Promise((C,q)=>{let _=new Promise((N,k)=>{o=N,s=k});_.catch(()=>{}),i=(async()=>{let N=performance.now(),k;try{k=await(n.acquire?n.acquire(n.control?.signal):n.admission.acquire(n.claims,n.control?.signal))}finally{n.trace?.time("queueMs",N)}let S=performance.now(),M,L=n.control!==void 0&&e.cancelBackend!==void 0,I=[];if(n.isolation!==void 0||n.readOnly!==void 0){let ne=n.isolation??"read committed";wn({isolation:ne,readOnly:n.readOnly}),I.push(`SET TRANSACTION ISOLATION LEVEL ${ne.toUpperCase()}${n.readOnly===void 0?"":n.readOnly?" READ ONLY":" READ WRITE"}`)}I.push(L?`WITH backend AS MATERIALIZED (SELECT pid, backend_start::text AS started, xact_start::text AS xact_started FROM pg_catalog.pg_stat_get_activity(pg_catalog.pg_backend_pid())) ${t}, backend.pid, backend.started, backend.xact_started FROM backend`:t);let j=L&&e.cancelOpening!==void 0?`palgres:${Fs()}`:void 0,K=!1,W=ne=>{c=!0;let F=ne[0];if(typeof F?.palgres_isolation=="string"&&(w=F.palgres_isolation),n.prepared!==void 0&&typeof F?.palgres_session=="string"&&F.palgres_session!==""&&(u=n.prepared.on(F.palgres_session),g&&u.forget()),!L)return;if(!Number.isInteger(F?.pid)||typeof F?.started!="string"||typeof F?.xact_started!="string"){let Te=new Error("Database cancellation cannot identify its own backend");throw l.refused??={error:Te},Te}let oe={pid:F.pid,started:F.started,xactStarted:F.xact_started};K=!0,n.control.bindBackend(()=>e.cancelBackend(oe.pid,oe.started,oe.xactStarted))},z=async()=>{for(let ne=0;ne<400&&!c&&!K;ne++){if(await e.cancelOpening(j))return;await new Promise(F=>setTimeout(F,5))}},Y=k.openWithin,V=!1,me,G,ie=()=>new we({retryAfter:1},"Database queue deadline exceeded"),B=Y===void 0?void 0:new Promise((ne,F)=>{G=setTimeout(()=>{c||(V=!0,me?.abandon?.(),F(ie()))},Y)});B?.catch(()=>{});let X=ne=>e.begin(async F=>{M=performance.now(),n.trace?.time("poolMs",S);let oe=n.trace?performance.now():0;if(n.control?.check(),a)throw new Error("Database transaction closed while waiting for its connection");if(V)throw ie();if(j!==void 0&&!K&&n.control.bindBackend(z),Y!==void 0&&!c){me=F;try{await F.unsafe("SELECT 1")}catch(Te){throw V?ie():Te}}clearTimeout(G),n.trace?.time("setupMs",oe),ne(),f=F,C(b(F,l)),await _},{sql:I.join("; "),opened:W,tag:j});try{if(n.control?.check(),a)throw new Error("Database transaction closed while waiting for admission");let ne=!1;for(let F=1;;F++)try{let oe=X(()=>{ne=!0});return B===void 0?await oe:(oe.catch(()=>{}),await Promise.race([oe,B]))}catch(oe){let Te=ce(oe);if(ne||a||Te===void 0||F>=(Te==="lost"?yn:bn))throw oe;n.control?.check()}}finally{clearTimeout(G),M!==void 0&&n.trace?.time("connectionMs",M),k.release()}})().catch(N=>{throw q(N),N}),i.catch(()=>{})}),r.then(void 0,()=>{T=!0,a||n.onIdle?.()}),r)),D=C=>p??=(async()=>{if(a=!0,!r)return;await d(),P.size&&await Promise.allSettled([...P]);let q=n.trace?performance.now():0;s(C),await i?.catch(()=>{}),n.trace?.time("rollbackMs",q),n.trace?.rolledBack()})();return{ensure:O,get opened(){return r!==null},get busy(){return r!==null&&!a&&!T&&(!c||A>0)},get failed(){return T},get releasable(){return $()&&m&&l.refused===void 0&&(w==="read committed"||w==="read uncommitted")},async commit(){if(P.size&&await Promise.allSettled([...P]),!r){n.trace?.check(),a=!0;return}await Qr(l);try{if(n.trace?.check(),n.control?.checkDeadline(),l.refused)throw Vs(l.refused.error)}catch(q){throw await D(q),q}if(a=!0,!await d()){let q=pe(new te(503,"database_unavailable","The database is temporarily unavailable",{retrySafe:!1},1));throw await D(q),q}let C=n.trace?performance.now():0;if(o(),m&&w!==void 0&&w!=="serializable"){i.then(()=>n.trace?.committed(),()=>n.trace?.commitFailed());return}try{await i,n.trace?.committed()}catch(q){throw n.trace?.commitFailed(),q}finally{n.trace?.time("commitMs",C)}},rollback:D}}var Hs="5s",zs="10s",Js=new Set(["22P02","22007","22008","22003","22001"]),Xr="55s",to=1,Qs=1e3,nn=new Set,en,Gs=new no("palgres.release");function Ys(e){nn.add(e),en===void 0&&(en=Gs.runInAsyncScope(()=>setInterval(()=>{let n=performance.now();for(let t of nn){let r=!0;try{r=t(n)}catch{r=!0}r&&nn.delete(t)}nn.size===0&&(clearInterval(en),en=void 0)},to)),en.unref?.())}function Xs(e,n){let t=[],r=m=>m!==null&&m.opened&&!m.failed,o=new Set,s,i=!1,a=()=>{for(let m of t)if(r(m.tx)&&m.tx.busy)return!0;for(let m of o)if(m.busy)return!0;return!1},p=no.bind(m=>{if(s===void 0||a())return!0;let w=o.size,c=o.size===0;for(let d of t)r(d.tx)&&(w++,d.tx.releasable||(c=!1));if(w===0)return!0;let f=m-s;if(c){if(f<to)return!1;for(let d of t){let u=d.tx;r(u)&&(d.tx=null,d.lease?.leave(),d.lease=void 0,u.commit().catch(()=>{}))}return s=void 0,!0}return n===void 0||i?!0:f<Qs?!1:(i=!0,n(Math.round(f)),!0)}),l=()=>{a()||(s=performance.now(),Ys(p))};return{onIdle:l,surface(m,w){let c={tx:null};t.push(c);let f=()=>{nn.delete(p);let d=c.tx;return c.tx=null,c.lease=void 0,d};return{ensure(){if(s!==void 0&&(s=performance.now()),c.tx===null){if(e())return Promise.reject(new Error("Database transaction has settled; its handle cannot be used again"));c.tx=m(l,d=>w(d).then(u=>(c.lease=u,u)))}return c.tx.ensure()},commit:()=>f()?.commit()??Promise.resolve(),rollback:d=>f()?.rollback(d)??Promise.resolve()}},atomic(m){return o.add(m),()=>{o.delete(m)&&l()}}}}function Zs(e){let n=le(e),t=e?.code,r=s=>n!==void 0&&s.has(n)||typeof t=="string"&&s.has(t),o;if(r(Nt))o=!0;else if(r(Dt))o=!1;else return;return Re(new te(503,"database_unavailable","The database is temporarily unavailable",{retrySafe:o},1),e)}var Me=e=>String(e?.message??e);function Re(e,n){return e.cause=n,pe(e)}function Tt(e,n,t){if(typeof e=="object"&&e!==null&&Zr.has(e))return e;let r=ei(e,n,t);return typeof r=="object"&&r!==null&&Zr.add(r),r}var Zr=new WeakSet,Nn=(e,n,t)=>Object.assign(new Error(e,{cause:n}),{sqlstate:t});function ei(e,n,t){if(Oe.is(e))return e;let r=le(e);if(r===Z.inFailedTransaction||/current transaction is aborted/i.test(Me(e)))return Nn(`This request cannot write any more: an earlier write in it failed, and a request runs in ONE Postgres transaction, so every statement after the failure is refused. Wrap a write you expect to fail in \`Database.$attempt(async (tx) => \u2026)\` \u2014 it takes a SAVEPOINT, so only that write rolls back \u2014 or use \`Database.public.<t>.put({ data, onConflict: [...] })\` when what you brace for is a duplicate row. (${Me(e)})`,e,Z.inFailedTransaction);if(ve.is(e))return e;if(r===Z.uniqueViolation)return Re(new ve(je(e)),e);if(r===Z.serializationFailure)return Re(new Kn(r),e);if(r===Z.deadlockDetected)return Re(new jn(r),e);if(r===Z.queryCancelled)return Re(Object.assign(new te(503,"database_query_cancelled","Database statement was cancelled"),{sqlstate:r}),e);let o=Zs(e);if(o)return o;if(n==="service"&&r===Z.foreignKeyViolation)return Nn(`Database.$asService() hit a foreign key with nothing to point at. It runs in its OWN transaction on its OWN connection, so a row this request wrote through \`Database.*\` is not visible to it until the request commits \u2014 and the request cannot commit until the handler returns. If the row it needs is one this request just created, do both writes on ONE surface. (${Me(e)})`,e,r);if(/lock timeout/i.test(Me(e))){let s;return n==="service"?s=Nn(`Database.$asService() waited too long for a row lock. It runs in its OWN transaction, so a row this request already wrote through Database.* is locked against it until the request commits \u2014 a wait that cannot end. Do that row's work on one surface or the other. (${Me(e)})`,e,r??Z.lockNotAvailable):s=Nn(`Database waited too long for a lock. Another transaction holds it: a concurrent one, or another of this request's own \u2014 Database.*, $asService() and $atomic each run in their OWN transaction, and a row one of them wrote stays locked against the others until it commits, a wait that cannot end while the handler runs. Do that row's work on one surface. (${Me(e)})`,e,r??Z.lockNotAvailable),Re(Object.assign(new te(503,"database_busy","The database waited too long for a lock",{retrySafe:!1},1),{sqlstate:r??Z.lockNotAvailable}),s)}return r!==void 0&&Js.has(r)?Re(Object.assign(new te(400,"invalid_value","A value is not one its column can take"),{sqlstate:r}),e):r===Z.insufficientPrivilege&&t!==null?Re(Object.assign(new te(t==="anon"?401:403,"permission_denied","The database does not allow this caller to do this"),{sqlstate:r}),e):(r!==void 0&&typeof e=="object"&&e!==null&&!Object.hasOwn(e,"sqlstate")&&Object.defineProperty(e,"sqlstate",{value:r,enumerable:!0,configurable:!0}),e)}function ni(e,n,t){let r=o=>({unsafe(s,i,a){let p;try{p=o.unsafe(s,i,a)}catch(l){return Promise.reject(Tt(l,n,t))}return Promise.resolve(p).then(Pe,l=>{throw Tt(l,n,t)})},savepoint:s=>o.savepoint(i=>s(r(i))),...o.abandon?{abandon:o.abandon.bind(o)}:{}});return{unsafe:(o,s)=>e.unsafe(o,s),begin:(o,s)=>e.begin(i=>o(r(i)),s).catch(i=>{throw Tt(i,n,t)}),...e.cancelBackend?{cancelBackend:e.cancelBackend.bind(e)}:{},...e.cancelOpening?{cancelOpening:e.cancelOpening.bind(e)}:{}}}var ti=2,eo={anon:"anon",authenticated:"authenticated",service:"service"};function ri(e,n){let t=Object.hasOwn(eo,n.role)?eo[n.role]:void 0;if(t===void 0)throw new Error(`palgres: a request is anon, authenticated or service, not "${String(n.role)}"`);return e[t]}function $t(e,n,t,r={}){let{signal:o}=r,s=r.diagnostics===void 0?void 0:new kn(r.diagnostics),i=o===void 0?void 0:new Ce(void 0,o),a=ri(n.roles,t),p=n.roles.service,l=t.role==="anon"||t.role==="authenticated"?t.role:null,m=t.claims,w=!1,c=!1,f=()=>{c&&ln.committed()},d=k=>{let S;return{cat:n.cat,trace:s,cursorKey:n.cursorKey,cursorScope:()=>S??=Tr(k,m),search:n.search,searchable:()=>{c=!0}}},u=d(a),g=d(p),h=new Set,y=null,E=!1,R=0,v=new Set,P=k=>new Promise((S,M)=>{let L=W=>{v.delete(I),clearTimeout(K),k?.removeEventListener("abort",j),W===void 0?S():M(W)},I=()=>L(),j=()=>L(k?.reason??new Error("Database admission cancelled")),K=setTimeout(()=>L(new we({retryAfter:1},"Database queue deadline exceeded")),n.admission.queueTimeoutMs);v.add(I),k?.addEventListener("abort",j,{once:!0}),k?.aborted&&j()}),A=async k=>{let S;for(;;){for(;h.size===0&&y!==null;)await y;let I=h.size>0;if(I){for(;R>=ti;)await P(k);R++}let j;try{let K=n.admission.acquire(m,k,{nested:I,returning:!I&&E}).then(W=>{if(I&&h.size===0)return W.release(),null;let z={nested:I,turn:W};return h.add(z),I||(E=!0),z});if(!I){let W=K.then(()=>{},()=>{});y=W,W.then(()=>{y===W&&(y=null)})}j=await K}catch(K){throw I&&T(),K}if(j!==null){S=j;break}T()}let M=!1,L=()=>{if(!M){if(M=!0,h.delete(S),S.nested){T();return}for(let I of h){[S.turn,I.turn]=[I.turn,S.turn],I.nested=!1,S.nested=!0,T();return}}};return{queueMs:S.turn.queueMs,leave:L,release:()=>{L(),S.turn.release()},...S.nested&&n.binding.pooled===!0?{openWithin:n.admission.queueTimeoutMs}:{}}},T=()=>{R--;let k=v.values().next().value;k?.()},$=Xs(()=>w,r.heldIdle),b=(k,S,M={})=>Yr(ni(e,S,S==="user"?l:null),{bind:He(n.binding,k,m),claims:m,admission:n.admission,acquire:A,trace:s,prepared:n.prepared,...M}),O=(k,S)=>async(M,L={})=>{if(wn(L),w)throw new Error("Database request has settled; it cannot open another transaction");if(Pn.getStore()!==void 0)throw new Error("Nested Database.$atomic is not supported; use tx.$attempt for a savepoint");let I=gn(L.retry),j=L.signal&&o?AbortSignal.any([L.signal,o]):L.signal??o,K=L.timeoutMs!==void 0||j!==void 0?new Ce(L.timeoutMs,j):void 0;try{K?.check();for(let W=0;;W++){K?.check();let z=[L.statementTimeoutMs,K?.remainingMs()].filter(G=>G!==void 0),Y=Symbol("atomic transaction"),V=b(k,S,{scope:Y,isolation:L.isolation,readOnly:L.readOnly,control:K,lockTimeout:`${L.lockTimeoutMs??5e3}ms`,statementTimeout:z.length===0?void 0:`${Math.min(...z)}ms`,onIdle:$.onIdle}),me=$.atomic(V);try{let G=Ze(()=>V.ensure(),S==="user"?u:g),ie=Pn.run(Y,()=>M(G)),B=await(K?K.race(ie):ie);return await V.commit(),f(),B}catch(G){await V.rollback(G);let ie=xe(G)||Oe.is(G)&&xe(G.cause);if(W>=I||!ie)throw G;s?.retry();let B=new Promise(X=>setTimeout(X,Math.min(100,2**W)));await(K?K.race(B):B)}finally{me()}}}finally{K?.dispose()}},D=$.surface((k,S)=>b(a,"user",{lockTimeout:zs,statementTimeout:Xr,control:i,onIdle:k,acquire:S}),A),C=null,q,_=null,N=()=>{if(_===null){if(w)throw new Error("Database request has settled; it cannot open another transaction");q=o===void 0?void 0:new Ce(void 0,o);let k=q,S=$.surface((M,L)=>b(p,"service",{lockTimeout:Hs,statementTimeout:Xr,control:k,onIdle:M,acquire:L}),A);C=S,_=Object.assign(Ze(()=>S.ensure(),g),{atomic:O(p,"service")})}return _};return{client:Object.assign(Ze(()=>D.ensure(),u),{asService:N,atomic:O(a,"user")}),async commit(){w=!0;try{try{s?.check()}catch(k){throw await D.rollback(k),await C?.rollback(k),k}try{await D.commit()}catch(k){throw await C?.rollback(k),k}await C?.commit(),f(),s?.complete("committed"),i?.dispose(),q?.dispose()}catch(k){throw s?.failed(),k}},async rollback(k){w=!0,await D.rollback(k),await C?.rollback(k),i?.dispose(),q?.dispose(),s?.complete("failed")}}}function oi(e){if(e.codec!==void 0&&e.codec in Ae)return Ae[e.codec].tsType;switch(e.type){case"uuid":case"text":case"timestamp":case"date":return"string";case"sql":return e.sqlType!==void 0&&un.has(e.sqlType)?"number":e.sqlType!==void 0&&dn.has(e.sqlType)?"Json":"string";case"integer[]":return"number[]";case"boolean[]":return"boolean[]";case"uuid[]":case"text[]":case"bigint[]":case"numeric[]":case"timestamp[]":case"date[]":return"string[]";case"integer":return"number";case"bigint":case"numeric":return"string";case"boolean":return"boolean";case"jsonb":return"Json";case"enum":{let n=e.enumValues??[];return n.length===0?"string":n.map(t=>JSON.stringify(t)).join(" | ")}case"enum[]":{let n=e.enumValues??[];return n.length===0?"string[]":`(${n.map(t=>JSON.stringify(t)).join(" | ")})[]`}default:{let n=e.type;throw new Error(`env-gen: the column type "${String(n)}" has no TypeScript type \u2014 add a case to baseTsType`)}}}function si(e){if(e.encrypted!==void 0)return e.encrypted.lookup?"encrypted:lookup":"encrypted";if(e.type==="enum"){let n=[...e.enumValues??[]].sort();return n.length===0?"enum":`enum:${n.join("|")}`}return e.type}function ro(e){let n=`Pg<${oi(e)}, ${JSON.stringify(si(e))}>`;return e.nullable?`${n} | null`:n}function ii(e){return e.nullable===!0||e.defaultRandom===!0||e.defaultNow===!0||e.defaultValue!==void 0||e.defaultSql!==void 0||e.dbAssigned===!0||e.identity!==void 0}function ai(e){return e.identity==="always"||e.generated!==void 0}var tn=e=>/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(e)?e:JSON.stringify(e);function oo(e,n,t){let r=Object.entries(e.columns).filter(([,a])=>a._def.ignored!==!0),o=r.map(([a,p])=>`${t} ${tn(a)}: ${ro(p._def)};`),s=r.filter(([,a])=>!ai(a._def)).map(([a,p])=>`${t} ${tn(a)}${ii(p._def)?"?":""}: ${ro(p._def)};`),i=n.map(a=>`${tn(a.name)}: { to: ${JSON.stringify(a.to)}; kind: ${JSON.stringify(a.kind)}; via: ${JSON.stringify(a.via)} }`).join("; ");return[`${t}${tn(e.name)}: {`,`${t} row: {`,...o,`${t} };`,`${t} insert: {`,...s,`${t} };`,`${t} relations: {${i===""?"":` ${i} `}};`,`${t} uniqueKeys: ${JSON.stringify(Rn(e))};`,...e.search!==void 0?[`${t} searchable: true;`]:[],`${t}};`].join(`
|
|
32
|
-
`)}function
|
|
31
|
+
`).slice(0,2500));let s=performance.now(),i=!1;try{let a=await t();return o.durationMs=performance.now()-s,i=!0,Array.isArray(a)&&(o.rows=a.length,o.bytes=Buffer.byteLength(JSON.stringify(a,(f,l)=>typeof l=="bigint"?l.toString():l))),this.state.rows+=o.rows,this.state.bytes+=o.bytes,this.options.maxRows!==void 0&&this.state.rows>this.options.maxRows&&this.refuse("returned rows"),this.options.maxBytes!==void 0&&this.state.bytes>this.options.maxBytes&&this.refuse("result bytes"),a}catch(a){let f=a;throw o.errorCode=String(f?.errno??f?.code??"query_failed").slice(0,80),a}finally{i||(o.durationMs=performance.now()-s),this.state.sqlMs+=o.durationMs;let a=Object.freeze(o);this.state.statements.length<200&&this.state.statements.push(a),this.emit(this.options.onQuery,a)}}get snapshot(){return Object.freeze({...this.state,elapsedMs:(this.ended??performance.now())-this.start,statements:Object.freeze([...this.state.statements].sort((e,t)=>e.ordinal-t.ordinal))})}complete(e){this.ended===void 0&&(this.ended=performance.now(),this.state.outcome=e,this.emit(this.options.onComplete,this.snapshot))}};var Nr=new WeakMap,Dr=new WeakSet;function Q(n){let e=t=>`$${n.push(t)}`;return Nr.set(e,n),e}var lt=n=>Dr.has(n);var qr=n=>`'${n.replace(/'/g,"''")}'`;function ce(n,e){let t=n.columns.get(e);return t?wr(t):null}function ee(n,e,t,r){if(!n.columns.has(e))throw n.ignored.has(e)?new Error(`${t}(${n.key}): ${r} "${e}" is .ignored() in this version \u2014 the version has promised not to name it, so the next one can drop it`):new Error(`${t}(${n.key}): ${r} "${e}" is not a column of the table`)}function ue(n,e,t){if(n.encrypted.has(e))throw new Error(`palgres: ${n.key}.${e} is .encrypted() \u2014 its value is not bound as it is (an engine path that reached it without sealing it)`);if(t==null)return t;let r=n.transforms.get(e)?.toDb,o=r===void 0?t:r(t),s=ce(n,e);return s===null||o===null||o===void 0?o:s.endsWith("[]")&&Array.isArray(o)?ze(o):hr(s)?JSON.stringify(o):o}function Cr(n,e){return e.flatMap(t=>{let r=n.encrypted.get(t)?.lookup;return r?[t,r]:[t]})}function Ee(n,e){return Cr(n,e).map(v).join(", ")}function Ss(n,e,t){return e.map(r=>{let o=n.encrypted.get(r);if(o===void 0)return r;if(o.lookup===null)throw new Error(`${t}(${n.key}): onConflict names "${r}", which is .encrypted() without { lookup: true } \u2014 no key is kept on it`);return o.lookup})}function _r(n,e,t,r,o,s){if(Ve(r)!==null)throw new Error(`${s}(${n.key}): "${e}" is .encrypted() \u2014 the database holds no value there to compute with; write the value`);if(r===null)return t.lookup?[o(null),o(null)]:[o(null)];if(typeof r!="string")throw new TypeError(`${s}(${n.key}): "${e}" is .encrypted(), a text column \u2014 got ${typeof r}`);let{cipher:i,sealing:a}=n.fields;a.get(t.address)?.direction==="seal"&&on(t.address,r);let f=o(i.encrypt(t.address,r)),l=a.get(t.address)?.direction==="seal"?`CASE WHEN EXISTS (SELECT 1 FROM ${Cn} WHERE address = ${o(t.address)} AND phase = 'mixed') THEN ${o(r)}::text ELSE ${f}::text END`:f;return t.lookup?[l,o(i.lookup(t.address,r))]:[l]}function Lr(n,e,t,r,o){let s=n.encrypted.get(e);return s===void 0?null:_r(n,e,s,t,r,o)}function Ir(n,e,t,r,o){let s=n.encrypted.get(t);return s===void 0?[o(ct(n,e,t,r))]:(Ue(e,n.key,[t],r),zn(e,n.key,[t],r),_r(n,t,s,r[t],o,e))}function xn(n,e,t,r){if(n.encrypted.has(e))throw new Error(`${t}(${n.key}): ${r} names "${e}", which is .encrypted() \u2014 the database holds its ciphertext, not its value, so nothing there orders, ranges, groups or matches it`)}function Mr(n,e,t){let r=t.find(o=>n.databaseOnly.has(o));if(r!==void 0)throw new Error(`${e}(${n.key}): "${r}" is written by the database (an ALWAYS .identity()) \u2014 leave it out of the write; Postgres refuses any value for it`)}function Le(n,e,t){for(let r of t)ee(n,r,e,"column");Mr(n,e,t)}function ct(n,e,t,r){return Ue(e,n.key,[t],r),zn(e,n.key,[t],r),ue(n,t,r[t])}function ut(n,e,t){let r=`${t?`${v(t)}.`:""}${v(e)}`;return Se(ce(n,e),r)??r}function Br(n,e,t){let r=ut(n,e,t);return Se(ce(n,e),"x")!==null?`${r} AS ${v(e)}`:r}function H(n,e){let t=e??"",r=n.projections.get(t);return r===void 0&&(r=[...n.columns.keys()].map(o=>Br(n,o,e)).join(", "),n.projections.set(t,r)),r}function dt(n,e,t){if(U(e,"select","which columns a call reads"),e!==void 0&&e.length===0)throw new Error(`${t}(${n.key}): select got an empty list \u2014 that is not "all of them" but "none counted". Leave the key out for every column; name at least one otherwise.`);return e===void 0?H(n,"t"):e.map(r=>(ee(n,r,t,"select column"),Br(n,r,"t"))).join(", ")}function jr(n,e,t,r="t"){if(e==null)return"";U(e,"orderBy","the order");let o=Array.isArray(e)?e:[e];return o.length===0?"":` ORDER BY ${o.map(i=>{U(i,"orderBy","the order"),ee(n,i.column,t,"orderBy column"),xn(n,i.column,t,"orderBy");let a=i.direction==="desc"?"DESC":"ASC",f=i.nulls==="first"?" NULLS FIRST":i.nulls==="last"?" NULLS LAST":"";return`${v(r)}.${v(i.column)} ${a}${f}`}).join(", ")}`}function at(n,e="findMany"){if(n===void 0)return"";if(!Number.isInteger(n)||n<0)throw new Error(`${e}: limit must be a non-negative integer (got ${String(n)})`);return` LIMIT ${n}`}function ks(n,e,t="findMany"){if(n===void 0)return"";if(!Number.isInteger(n)||n<0)throw new Error(`${t}: offset must be a non-negative integer (got ${String(n)})`);if(e===void 0)throw new Error(`${t}: offset is given only with limit \u2014 an offset without one is the shifted tail of an unbounded result, not a page`);return` OFFSET ${n}`}var Ce={gt:">",gte:">=",lt:"<",lte:"<=",neq:"<>"},vs=[["days","days","int"],["hours","hours","int"],["minutes","mins","int"],["seconds","secs","double precision"]];function _e(n,e){let t=n?.minus;if(t===void 0)return"now()";let r=Kt(t);if("refused"in r)throw new TypeError(`palgres: ago() ${r.refused}`);return`(now() - make_interval(${vs.filter(([s])=>r.span[s]!==void 0).map(([s,i,a])=>`${i} => ${e(r.span[s])}::${a}`).join(", ")}))`}var Or=Object.freeze({update:"FOR UPDATE",share:"FOR SHARE",noKeyUpdate:"FOR NO KEY UPDATE"});function ft(n,e,t,r){if(typeof r=="string"&&Object.hasOwn(Or,r))return Or[r];let o=typeof r=="string"?JSON.stringify(r.slice(0,40)):typeof r;throw new TypeError(`${n}(${e}): unknown ${t} ${o} \u2014 "update" (FOR UPDATE), "share" (FOR SHARE) or "noKeyUpdate" (FOR NO KEY UPDATE).`)}var Ar=n=>Ve(n);function Pr(n,e,t,r){if(!n.columns.has(e.$col))throw new Error(`${t}(${n.key}): col("${e.$col}") is not a column of the table`);return`${v(r)}.${v(e.$col)}`}function Kr(n,e,t,r){let s=(t.kind==="many"?n.table(t.to,r):e).columns.get(t.via)?.references?.column??(t.kind==="many"?e.singleKey:n.table(t.to,r).singleKey);return t.kind==="many"?[s,t.via]:[t.via,s]}function ke(n,e,t){return me(new pe({fields:[{field:e,message:t}]},`${n}: ${e} ${t}`))}function xs(n,e){if(U(n,e,"a filter"),!(typeof n!="object"||n===null))for(let[t,r]of Object.entries(n))t==="OR"||t==="AND"||t==="NOT"||t==="has"?U(r,`${e}.${t}`,`a filter's ${t}`):r!==null&&typeof r=="object"&&!Array.isArray(r)&&U(r,`${e}.${t}`,"an operator")}function vn(n,e,t,r,o,s,i,a){let f=[];if(xs(t,a),jt(o,e.key,t),Ne(t)){let{text:l,values:d}=t.$sql,g=Nr.get(r);if(g===void 0)throw new Error("palgres: an sqlFragment was compiled outside binder()");if(Dr.add(g),l.length!==d.length+1)throw new Error(`${o}(${e.key}): the sqlFragment's parts are broken (${l.length} texts, ${d.length} values) \u2014 only the template tag makes one`);let c=l[0]??"";for(let p=0;p<d.length;p++)c+=`${r(d[p])}${l[p+1]??""}`;if(c.trim()==="")throw ke(o,a,"is an empty sqlFragment \u2014 no condition. Write the condition in it, or leave it out.");return[`(${c})`]}for(let[l,d]of Object.entries(t)){if(l==="OR"||l==="AND"){let u=d;if(u.length===0){if(l==="AND")throw ke(o,`${a}.AND`,"is an empty list \u2014 no condition at all. Leave it out, or name a condition in it.");f.push("false");continue}let w=u.map((h,b)=>{let R=vn(n,e,h,r,o,s,i,`${a}.${l}[${b}]`);if(R.length===0)throw ke(o,`${a}.${l}[${b}]`,"holds no condition \u2014 a branch that matches every row. Name a condition in it, or leave it out.");return`(${R.join(" AND ")})`});f.push(`(${w.join(l==="OR"?" OR ":" AND ")})`);continue}if(l==="NOT"){if(Array.isArray(d))throw ke(o,`${a}.NOT`,"is a list \u2014 NOT takes one filter object. For several conditions, NOT: { AND: [...] } or NOT: { OR: [...] }.");let u=vn(n,e,d,r,o,s,i,`${a}.NOT`);if(u.length===0)throw ke(o,`${a}.NOT`,"holds no condition \u2014 NOT of nothing is not a filter. Name the condition to exclude.");f.push(`NOT (${u.join(" AND ")})`);continue}if(l==="has"){let u=Object.entries(d);if(u.length===0)throw ke(o,`${a}.has`,"names no relation \u2014 no condition. Name one: has: { <relation>: { \u2026 } }.");for(let[w,h]of u){let b=e.relations.find($=>$.name===w);if(b===void 0){let $=e.relations.map(y=>y.name).sort();throw new Error(`${o}(${e.key}): there is no relation has.${w}`+($.length>0?` (known: ${$.join(", ")}). Relations come from foreign keys; to rename one, references(..., { as, reverseAs }).`:". The table declares no foreign key, and relations come from them: references(() => <table>.<column>)."))}let[R,T]=Kr(n,e,b,o);if(R===null||T===null)throw new Error(`${o}(${e.key}): has.${w} cannot be built \u2014 "${R===null?e.key:b.to}" has no single-column primary key to correlate on; write the condition as an sqlFragment`);let O=n.table(b.to,o),D=`r${i+1}`,A=Ge(n,O,h??{},r,o,D,i+1,`${a}.has.${w}`),E=`${D}.${v(T)} = ${v(s)}.${v(R)}`;f.push(`EXISTS (SELECT 1 FROM ${O.sql} ${D} WHERE ${E}${A===""?"":` AND ${A}`})`)}continue}ee(e,l,o,"where column");let g=e.encrypted.get(l);if(g!==void 0){f.push(Os(e,l,g,d,r,o,s,a));continue}let c=`${v(s)}.${v(l)}`,p=ce(e,l)?.endsWith("[]")===!0,m=u=>r(ue(e,l,u));if(we(d)){f.push(`${c} = ${Pr(e,d,o,s)}`);continue}if(pn(d)){f.push(`${c} = ${_e(Ar(d),r)}`);continue}if(d!==null&&typeof d=="object"&&!Array.isArray(d))for(let[u,w]of Object.entries(d)){if(p&&(u==="contains"||u==="overlaps")){if(!Array.isArray(w))throw new Error(`${o}(${e.key}): where.${l}.${u} must be an array \u2014 ${l} is an array column`);f.push(`${c} ${u==="contains"?"@>":"&&"} ${m(w)}`);continue}if(!p&&(u==="contains"||u==="icontains"||u==="startsWith"||u==="endsWith")){if(typeof w!="string")throw new Error(`${o}(${e.key}): where.${l}.${u} must be a string`);let b=w.replace(/([\\%_])/g,"\\$1"),R=u==="startsWith"?`${b}%`:u==="endsWith"?`%${b}`:`%${b}%`;f.push(`${c} ${u==="icontains"?"ILIKE":"LIKE"} ${r(R)}`);continue}if(u==="isNull"){if(typeof w!="boolean")throw new Error(`${o}(${e.key}): where.${l}.isNull must be a boolean`);f.push(`${c} IS ${w?"NULL":"NOT NULL"}`);continue}if(u==="in"){if(!Array.isArray(w))throw new Error(`${o}(${e.key}): where.${l}.in must be an array`);if(w.some(we))throw new Error(`${o}(${e.key}): where.${l}.in takes values, not col() \u2014 compare with a column bare ({ ${l}: col("\u2026") }) or with gt/gte/lt/lte/neq`);if(w.length===0){f.push("false");continue}f.push(`${c} IN (${w.map(b=>m(b)).join(", ")})`);continue}if(pn(w)){if(!(u in Ce))throw new Error(`${o}(${e.key}): where.${l}.${u} cannot take now() \u2014 for equality write it bare: { ${l}: now() }`);f.push(`${c} ${Ce[u]} ${_e(Ar(w),r)}`);continue}if(mn(w))throw new Error(`${o}(${e.key}): where.${l}.${u} got a WRITE expression (increment/decrement), not a comparison value. For the server's time use now(); for a numeric threshold, the value.`);if(we(w)){if(!(u in Ce))throw new Error(`${o}(${e.key}): where.${l}.${u} cannot take col() \u2014 for equality write it bare: { ${l}: col("\u2026") }`);f.push(`${c} ${Ce[u]} ${Pr(e,w,o,s)}`);continue}let h=Bt(w);if(h!==null){let b=h==="col"?"col()":h==="sql"?"sqlFragment":"now()";throw new Error(`${o}(${e.key}): where.${l}.${u} got an imitation of ${b} \u2014 this object was not made by ${b} in this process. A filter from a request body cannot carry a handle; build the condition in your code.`)}if(u in Ce){if(w===null&&u==="neq"){f.push(`${c} IS NOT NULL`);continue}f.push(`${c} ${Ce[u]} ${m(w)}`);continue}throw new Error(`${o}(${e.key}): where.${l} has an unknown operator "${u}" (gt/gte/lt/lte/neq/in)`)}else d===null?f.push(`${c} IS NULL`):f.push(`${c} = ${m(d)}`)}return f}function Os(n,e,t,r,o,s,i,a){let f=`${v(i)}.${v(e)}`;if(r===null)return`${f} IS NULL`;let l=u=>{throw new Error(`${s}(${n.key}): ${a}.${e} ${u} \u2014 "${e}" is .encrypted(): the database holds its ciphertext, so it is asked only isNull`+(t.lookup?", equality and in":" (equality needs .encrypted({ lookup: true }))"))};(we(r)||pn(r)||Ne(r))&&l("compares with an expression");let{cipher:d,sealing:g}=n.fields,c=g.get(t.address)!==void 0,p=u=>{if(t.lookup===null&&l("asks for equality"),u.some(T=>typeof T!="string")&&l("compares with a value that is not text"),u.length===0)return"false";let w=`${v(i)}.${v(t.lookup)}`,h=u.map(T=>o(d.lookup(t.address,T))),b=u.length===1?`${w} = ${h[0]}`:`${w} IN (${h.join(", ")})`;if(!c)return b;let R=u.map(T=>o(T));return`(${b} OR ${u.length===1?`${f} = ${R[0]}`:`${f} IN (${R.join(", ")})`})`};if(typeof r!="object"||Array.isArray(r))return p([r]);let m=[];for(let[u,w]of Object.entries(r))if(u==="isNull"){if(typeof w!="boolean")throw new Error(`${s}(${n.key}): where.${e}.isNull must be a boolean`);m.push(`${f} IS ${w?"NULL":"NOT NULL"}`)}else if(u==="in"){if(!Array.isArray(w))throw new Error(`${s}(${n.key}): where.${e}.in must be an array`);m.push(p(w))}else u==="neq"?m.push(w===null?`${f} IS NOT NULL`:`(${f} IS NOT NULL AND NOT ${p([w])})`):l(`asks ${u}`);return m.length===0&&l("holds no condition"),m.length===1?m[0]:`(${m.join(" AND ")})`}function Ge(n,e,t,r,o,s="t",i=0,a="where"){return vn(n,e,t,r,o,s,i,a).join(" AND ")}function de(n,e,t,r,o){let s=vn(n,e,t,r,o,"t",0,"where");return{sql:s.length===0?"":` AND ${s.join(" AND ")}`,conditions:s.length}}function Ie(n,e){if(!(n.conditions>0))throw ke(e,"where",`holds no condition, so ${e} would reach EVERY row of the table. Name a condition.`)}function Ye(n,e,t,r,o){let s=Cr(n,e),i=Ss(n,t,o);if(r!=="ignore"&&r!=="update")throw new TypeError(`palgres: a conflict's action is "ignore" or "update", not ${typeof r=="string"?JSON.stringify(String(r).slice(0,40)):typeof r}`);if(i.length===0){if(r==="ignore")return"ON CONFLICT DO NOTHING";throw new Error("palgres: ON CONFLICT DO UPDATE needs the columns a collision is matched on")}let a=`ON CONFLICT (${i.map(v).join(", ")})`;if(r==="ignore")return`${a} DO NOTHING`;let f=new Set(i),l=s.filter(d=>!f.has(d)).map(d=>`${v(d)} = EXCLUDED.${v(d)}`);return l.length?`${a} DO UPDATE SET ${l.join(", ")}`:`${a} DO UPDATE SET ${v(i[0])} = EXCLUDED.${v(i[0])}`}function mt(n,e,t,r,o){return Mr(n,o,e),e.map(s=>{let i=n.encrypted.get(s);if(i!==void 0){let[f,l]=Ir(n,o,s,t,r);return`${v(s)} = ${f}${i.lookup?`, ${v(i.lookup)} = ${l}`:""}`}let a=Ve(t[s]);if(a!==null&&a.fn==="now")return`${v(s)} = ${_e(a,r)}`;if(a!==null){let f=n.transforms.get(s)?.toDb,l=f===void 0?a.by:f(a.by);return`${v(s)} = ${v(s)} ${a.fn==="inc"?"+":"-"} ${r(l)}`}return`${v(s)} = ${r(ct(n,o,s,t))}`}).join(", ")}function Xe(n,e,t,r,o){return e.map(s=>{if(n.encrypted.has(s))return Ir(n,o,s,t,r).join(", ");let i=Ve(t[s]);if(i!==null&&i.fn==="now")return _e(i,r);if(i!==null){let a=i.fn==="inc"?"increment":"decrement";throw new Error(`${o}(${n.key}): "${s}" got ${a}() \u2014 the row does not exist yet, so there is no current value. Write the starting value; to change it once the row exists, updateMany({ where, set: { ${s}: ${a}(n) } }).`)}return r(ct(n,o,s,t))}).join(", ")}var As=new Set(["integer","bigint","numeric"]);function Wr(n){return n!==null&&As.has(n)}function Fr(n,e,t,r){xn(n,t,"aggregate",e);let o=`t.${v(t)}`,s=ce(n,t);if(e==="sum"||e==="avg")return`${e}(${o})::text AS ${v(r)}`;let i=s!==null&&!s.endsWith("[]")?Se(s,`${e}(${o})`):null;return i!==null?`${i} AS ${v(r)}`:s==="bigint"||s==="numeric"?`${e}(${o})::text AS ${v(r)}`:`${e}(${o}) AS ${v(r)}`}function Ps(n,e,t,r=[]){return`json_build_object(${[...e.map(s=>{let i=ce(n,s),a=`${t}.${v(s)}`,f=i==="numeric"||i==="bigint"?`${a}::text`:Se(i,a)??a;return`${qr(s)}, ${f}`}),...r].join(", ")})`}function On(n,e,t,r,o,s="t",i=0,a={value:0}){if(U(t,"with","which relations a call reads"),i>=3&&Object.values(t).some(Boolean))throw new Error(`${o}(${e.key}): with supports at most three relation levels`);let f=[],l=[],d=[];for(let[g,c]of Object.entries(t)){if(c===!1||c===void 0)continue;U(c,`with.${g}`,"which relations a call reads");let p=e.relations.find(P=>P.name===g);if(p===void 0){let P=e.relations.map(k=>k.name).sort();throw new Error(`${o}(${e.key}): there is no relation with.${g}`+(P.length>0?` (known: ${P.join(", ")})`:". The table declares no foreign key, and relations come from them")+". A relation is declared with references(() => <table>.<column>).")}let[m,u]=Kr(n,e,p,o);if(m===null||u===null)throw new Error(`${o}(${e.key}): with.${g} needs a single-column primary key at one end of the relation`);let w=n.table(p.to,o),h=typeof c=="object"&&c!==null?c:{},b=++a.value,R=`w${b}`;if(U(h.select,`with.${g}.select`,"which columns a call reads"),U(h.orderBy,`with.${g}.orderBy`,"the order"),h.select!==void 0&&(!Array.isArray(h.select)||h.select.length===0))throw new Error(`${o}(${e.key}): with.${g}.select must be a non-empty array of columns`);let T=Array.isArray(h.select)?h.select:[...w.columns.keys()];for(let P of T)ee(w,P,o,`with.${g}.select column`);let O=h.with;if(O!==void 0&&(O===null||typeof O!="object"||Array.isArray(O)))throw new Error(`${o}(${e.key}): with.${g}.with must be a relation object`);let D=O===void 0?{joins:[],jsonPairs:[]}:On(n,w,O,r,o,R,i+1,a),A=D.joins.length?` ${D.joins.join(" ")}`:"",E=Ps(w,T,R,D.jsonPairs),$=h.where!==void 0&&h.where!==null?Ge(n,w,h.where,r,o,R,b,`with.${g}.where`):"",y=`${R}.${v(u)} = ${v(s)}.${v(m)}`,x=$===""?y:`${y} AND ${$}`,N=h.limit;at(N,o);let q=p.kind==="many"?N:Math.min(1,N??1),C=jr(w,h.orderBy,o,R)+at(q,o),_=`wj${b}`;p.kind==="many"?l.push(`LEFT JOIN LATERAL (SELECT coalesce(json_agg(x.o), '[]'::json) AS d FROM (SELECT ${E} AS o FROM ${w.sql} ${R}${A} WHERE ${x}${C}) x) ${v(_)} ON true`):l.push(`LEFT JOIN LATERAL (SELECT ${E} AS d FROM ${w.sql} ${R}${A} WHERE ${x}${C}) ${v(_)} ON true`),f.push(`${v(_)}."d" AS ${v(g)}`),d.push(`${qr(g)}, ${v(_)}."d"`)}return{select:f,joins:l,jsonPairs:d}}function pt(n,e,t,r){let o=[],s=Q(o),i=de(n,e,t,s,"findMany").sql,a=jr(e,r.orderBy,"findMany"),f=at(r.limit),l=ks(r.offset,r.limit),d=dt(e,r.select,"findMany"),g=r.with!==void 0&&Object.keys(r.with).length>0?On(n,e,r.with,s,"findMany"):{select:[],joins:[]},c=g.select.length>0?`${d}, ${g.select.join(", ")}`:d,p=g.joins.length>0?` ${g.joins.join(" ")}`:"",m=r.lock===void 0?"":` ${ft("findUnique",e.key,"lock",r.lock)} OF t`;return{sql:`SELECT ${c} FROM ${e.sql} t${p} WHERE true${i}${a}${f}${l}${m}`,params:o}}var it=50;function gt(n,e,t,r){if(e.search===void 0||e.singleKey===null)throw new Error(`search(${e.key}): the table declares no search`);if(t.text===void 0&&t.vector===void 0)throw new Error(`search(${e.key}): neither the query's words nor its vector to search by`);let o=[],s=Q(o),i=v(e.singleKey),a=de(n,e,r.where??{},s,"search").sql,f=Math.max(r.limit*3,30),l=[];if(t.vector!==void 0){let g=`v."embedding" ${t.vector.operator} ${s(t.vector.literal)}::${t.vector.type}`;l.push(`sem AS (SELECT s."id", row_number() OVER (ORDER BY s."d", s."id") AS r FROM (SELECT t.${i} AS "id", ${g} AS "d" FROM ${t.vector.table} v JOIN ${e.sql} t ON t.${i} = v."id" WHERE true${a} ORDER BY ${g} LIMIT ${f}) s)`)}if(t.text!==void 0){let g=Pt(e.search.from,"t"),c=`websearch_to_tsquery('simple', ${s(t.text)})`;l.push(`kw AS (SELECT s."id", row_number() OVER (ORDER BY s."k" DESC, s."id") AS r FROM (SELECT t.${i} AS "id", ts_rank_cd(${g}, ${c}) AS "k" FROM ${e.sql} t WHERE ${g} @@ ${c}${a} ORDER BY "k" DESC LIMIT ${f}) s)`)}l.push(l.length===2?`fused AS (SELECT coalesce(sem."id", kw."id") AS "id", (coalesce(1.0 / (${it} + sem.r), 0) + coalesce(1.0 / (${it} + kw.r), 0))::float8 AS "score" FROM sem FULL OUTER JOIN kw ON sem."id" = kw."id")`:`fused AS (SELECT x."id", (1.0 / (${it} + x.r))::float8 AS "score" FROM ${t.vector!==void 0?"sem":"kw"} x)`);let d=r.minScore===void 0?"":` AND f."score" >= ${s(r.minScore)}`;return{sql:`WITH ${l.join(", ")} SELECT ${H(e,"t")}, f."score" AS "_score" FROM fused f JOIN ${e.sql} t ON t.${i} = f."id" WHERE true${d} ORDER BY f."score" DESC, t.${i} LIMIT ${Ns(r.limit)}`,params:o}}function Ns(n){if(!Number.isInteger(n)||n<1)throw new Error(`search: limit must be a positive integer (got ${String(n)})`);return n}function Ur(n){return n instanceof Date?n.toISOString():Array.isArray(n)?n.map(Ur):n}function wt(n){if(n===null||typeof n!="object")return n;let e={};for(let[t,r]of Object.entries(n))e[t]=Ur(r);return e}function Ds(n,e){for(let[t,r]of e.transforms){if(r.fromDb===void 0)continue;let o=n[t];o!=null&&(n[t]=r.fromDb(o))}return n}function Qe(n,e,t,r){let o=t.map(s=>Ds(wt(s),e));if(r)for(let s of e.relations){let i=r[s.name];if(!i)continue;let a=typeof i=="object"?i.with:void 0,f=n.table(s.to,"with");for(let l of o){let d=l[s.name];Array.isArray(d)?l[s.name]=Qe(n,f,d,a):d&&typeof d=="object"&&(l[s.name]=Qe(n,f,[d],a)[0])}}return Pe(o)}var qs={inline:!0},ht={inline:!0,read:!0},Cs=n=>le(n)===Z.uniqueViolation||ve.is(n);function Vr(n,e){if(e===null)return!1;let t=Object.keys(n);if(t.length!==1||t[0]!==e)return!1;let r=n[e];return r!==null&&(typeof r!="object"||Array.isArray(r))}var _s=6e4;function Ze(n,e){let{cat:t}=e,r=(c,p)=>t.table(c,p),o=(c,p)=>{let m=t.table(c,p);return m.search!==void 0&&e.searchable?.(),m},s=async(c,p=[],m=!1)=>await(await n()).unsafe(c,p,lt(p)?void 0:m?ht:qs),i=(c,p=[])=>s(c,p,!0),a=async(c,p=[])=>await(await n()).unsafe(c,p),f=async(c,p)=>{let m=t.deferral(c);if(m===null)return p();await s(m.defer);let u=await p();return await s(m.check),u},l=(c,p,m)=>Qe(t,c,p,m),d=(c,p)=>Qe(t,c,[p])[0],g={diagnostics(){return e.trace?.snapshot??null},async query(c,p=[]){return Pe((await a(c,p)).map(m=>wt(m)))},async insert(c,p){let m=o(c,"insert"),u=Object.keys(p);if(u.length===0)throw new Error(`insert into ${c}: no columns given`);Le(m,"insert",u);let w=[],h=Xe(m,u,p,Q(w),"insert"),b=await s(`INSERT INTO ${m.sql} (${Ee(m,u)}) VALUES (${h}) RETURNING ${H(m)}`,w);if(!b[0])throw new Error(`insert into ${c} returned no row \u2014 the write was rejected (an RLS policy, most likely).`);return d(m,b[0])},insertMany:(async function(c,p,m){if(Wt(m),p.length===0)return m?.returning===!1?0:[];let u=o(c,"insertMany"),w=Object.keys(p[0]);if(w.length===0)throw new Error(`insertMany into ${c}: no columns given`);for(let A=1;A<p.length;A++){let E=w.filter(y=>!(y in p[A])),$=Object.keys(p[A]).filter(y=>!w.includes(y));if(E.length>0||$.length>0)throw new Error(`insertMany(${c}): row ${A} does not have the first row's columns`+(E.length>0?` (missing: ${E.join(", ")})`:"")+($.length>0?` (extra: ${$.join(", ")})`:"")+". One statement shares the column list: write null for a missing value, or insert differently shaped rows in calls of their own.")}Le(u,"insertMany",w),U(m?.onConflict,"onConflict","which columns a conflict is on");for(let A of m?.onConflict??[])ee(u,A,"insertMany","onConflict column");let h=[],b=Q(h),R=p.map(A=>`(${Xe(u,w,A,b,"insertMany")})`),T=m?.onConflict??[],O=T.length>0||m?.action==="ignore"?` ${Ye(u,w,T,m?.action??"ignore","insertMany")}`:"",D=await s(`INSERT INTO ${u.sql} (${Ee(u,w)}) VALUES ${R.join(", ")}${O}${m?.returning===!1?"":` RETURNING ${H(u)}`}`,h);if(m?.returning===!1){if(!Number.isSafeInteger(D.count)||D.count<0)throw new Error("insertMany returning:false requires a driver with an affected row count");return D.count}return l(u,D)}),async advisoryXactLock(c){await s("SELECT pg_advisory_xact_lock(hashtextextended($1, 0))",[c])},async lockRows(c,p){let m=[...new Set(p)].sort();if(m.length===0)return;let u=r(c,"lockRows");if(u.singleKey===null)throw new Error(`lockRows(${c}): no single-column primary key \u2014 the lock order needs one`);let w=v(u.singleKey),h=[],b=Q(h),R=m.map(T=>b(ue(u,u.singleKey,T))).join(", ");await s(`SELECT t.${w} FROM ${u.sql} t WHERE t.${w} IN (${R}) ORDER BY t.${w} FOR NO KEY UPDATE`,h)},async lockRowsWhere(c,p,m){let u=ft("lockRowsWhere",c,"mode",m?.mode===void 0?"update":m.mode),w=r(c,"lockRowsWhere");if(w.singleKey===null)throw new Error(`lockRowsWhere(${c}): no single-column primary key \u2014 the lock order needs one`);let h=[],b=de(t,w,p,Q(h),"lockRowsWhere");Ie(b,"lockRowsWhere");let R=v(w.singleKey);await s(`SELECT t.${R} FROM ${w.sql} t WHERE true${b.sql} ORDER BY t.${R} ${u}`,h)},async claim(c,p,m={}){let u=o(c,"claim");U(p,"unique","which key a claim is on");let w=Object.keys(p);if(w.length===0)throw new Error(`claim(${c}): no unique field given. claim takes ownership of a key; with none there is nothing to own \u2014 use insert(${c}, \u2026).`);Ue("claim",c,w,p);for(let O of w){let D=p[O];if(D===null||typeof D=="object"||typeof D=="function")throw new Error(`claim(${c}): the unique field "${O}" is ${D===null?"null":"an object"} \u2014 a key is one value (a string, number, bigint or boolean); NULL never equals a claimed row.`)}let h=Object.keys(m).filter(O=>Object.hasOwn(p,O));if(h.length>0)throw new Error(`claim(${c}): ${h.map(O=>`"${O}"`).join(", ")} is in both the unique fields and extra \u2014 say a key once, in the unique fields.`);let b={...p,...m},R=Object.keys(b);Le(u,"claim",R);let T=await n();try{return await T.savepoint(async O=>{let D=[],A=Xe(u,R,b,Q(D),"claim"),E=await O.unsafe(`INSERT INTO ${u.sql} (${Ee(u,R)}) VALUES (${A}) RETURNING ${H(u)}`,D);if(!E[0])throw new Error(`claim(${c}): the INSERT returned no row \u2014 the write was rejected (an RLS policy, most likely).`);return{inserted:!0,row:d(u,E[0])}})}catch(O){if(!Cs(O))throw O;let D=[],A=Q(D),E=Ge(t,u,p,A,"claim"),$=await s(`SELECT ${H(u,"t")} FROM ${u.sql} t WHERE ${E} LIMIT 1`,D);if(!$[0]){let y=Ke(O);throw new Error(`claim(${c}): a unique violation${y?` (${y})`:""} was caught but no row has these ${w.join(", ")}. Either the violation is of ANOTHER unique constraint \u2014 claim() is the wrong tool for this call \u2014 or the row exists and an RLS policy hides it from this caller.`)}return{inserted:!1,row:d(u,$[0])}}},async put(c,p,m){let u=o(c,"put"),w=m.onConflict;if(w.length===0)throw new Error(`put into ${c}: onConflict needs at least one column`);let h=Object.keys(p);if(h.length===0)throw new Error(`put into ${c}: no columns given`);Le(u,"put",h),U(w,"onConflict","which columns a conflict is on");for(let O of w)ee(u,O,"put","onConflict column");let b=[],R=Xe(u,h,p,Q(b),"put"),T=await s(`INSERT INTO ${u.sql} (${Ee(u,h)}) VALUES (${R}) ${Ye(u,h,w,"update","put")} RETURNING ${H(u)}`,b);if(!T[0])throw new Error(`put into ${c} returned no row \u2014 the write was rejected (an RLS policy, most likely).`);return d(u,T[0])},async update(c,p,m){let u=o(c,"update");if(!u.columns.has("id"))throw new Error(`update(${c}): the table has no "id" column \u2014 update a row by its key with updateMany({ where, set })`);let w=Object.keys(m);if(w.length===0)return g.findById(c,p);for(let O of w)ee(u,O,"update","set column");let h=[],b=Q(h),R=mt(u,w,m,b,"update"),T=await s(`UPDATE ${u.sql} SET ${R} WHERE "id" = ${b(ue(u,"id",p))} RETURNING ${H(u)}`,h);return T[0]?d(u,T[0]):null},async delete(c,p){let m=r(c,"delete");if(!m.columns.has("id"))throw new Error(`delete(${c}): the table has no "id" column \u2014 delete by its key with deleteMany({ where })`);let u=[ue(m,"id",p)];await f(m,()=>s(`DELETE FROM ${m.sql} WHERE "id" = $1`,u))},async updateMany(c,p,m,u){let w=o(c,"updateMany"),h=Object.keys(m);if(h.length===0)throw new Error(`updateMany(${c}): nothing to set. An update with no columns is not a no-op worth pretending happened \u2014 pass the columns to write.`);for(let _ of h)ee(w,_,"updateMany","set column");let b=[],R=Q(b),T=mt(w,h,m,R,"updateMany"),O=de(t,w,p,R,"updateMany");Ie(O,"updateMany");let D=O.sql,A=w.singleKey,E=u?.returning!==!1,$=A===null||Vr(p,A),y=E?`RETURNING ${H(w,"t")}`:"RETURNING 1",x=$?`UPDATE ${w.sql} AS t SET ${T} WHERE true${D} ${y}`:`UPDATE ${w.sql} AS t SET ${T} FROM locked WHERE t.${v(A)} = locked."__pb_lock" ${y}`,N=$?"":`WITH locked AS (SELECT t.${v(A)} AS "__pb_lock" FROM ${w.sql} t WHERE true${D} ORDER BY t.${v(A)} FOR NO KEY UPDATE)`,q=E?`${N} ${x}`.trim():$?`WITH upd AS (${x}) SELECT count(*)::int AS n FROM upd`:`${N}, upd AS (${x}) SELECT count(*)::int AS n FROM upd`,C=await s(q,b);return E?l(w,C):Number(C[0]?.n??0)},async deleteMany(c,p){let m=r(c,"deleteMany"),u=[],w=de(t,m,p,Q(u),"deleteMany");return Ie(w,"deleteMany"),(await f(m,()=>s(`DELETE FROM ${m.sql} AS t WHERE true${w.sql} RETURNING 1`,u))).length},async aggregate(c,p={}){let m=r(c,"aggregate");for(let y of["sum","avg","min","max","groupBy"])U(p[y],y,"which columns an aggregate reads");U(p.count,"count","which counts an aggregate takes");let u=[],w=Q(u),h=[],b=[];for(let y of["sum","avg","min","max"])for(let x of p[y]??[]){if(ee(m,x,"aggregate",`${y} column`),(y==="sum"||y==="avg")&&!Wr(ce(m,x)))throw new Error(`aggregate(${c}): ${y}("${x}") on a column that is not numeric \u2014 "${x}" is ${ce(m,x)}. Only integer, bigint and numeric sum; to count rows, count: true.`);let N=`${y}__${x}`;b.push({fn:y,col:x,alias:N}),h.push(Fr(m,y,x,N))}p.count===!0&&h.push('count(*) AS "_count"');let R=p.count!==null&&typeof p.count=="object"?Object.entries(p.count):[];if(p.count!==void 0&&typeof p.count!="boolean"&&(p.count===null||typeof p.count!="object"||Array.isArray(p.count)||R.length===0))throw new Error(`aggregate(${c}): count is true, or named filters \u2014 { <name>: <filter> }, at least one`);if(R.forEach(([y,x],N)=>{let q=Ge(t,m,x,w,"aggregate","t",0,`count.${y}`);h.push(`count(*) FILTER (WHERE ${q===""?"true":q}) AS ${v(`count__${N}`)}`)}),h.length===0)throw new Error(`aggregate(${c}): no aggregate asked for \u2014 the result would be an empty object. Name sum/avg/min/max columns or count: true.`);let T=p.groupBy??[];for(let y of T)ee(m,y,"aggregate","groupBy column"),xn(m,y,"aggregate","groupBy");let O=T.map(y=>`${ut(m,y,"t")} AS ${v(`g__${y}`)}`),D=de(t,m,p.where??{},w,"aggregate").sql,A=T.length>0?` GROUP BY ${T.map(y=>`t.${v(y)}`).join(", ")}`:"",E=await i(`SELECT ${[...O,...h].join(", ")} FROM ${m.sql} t WHERE true${D}${A}`,u),$=y=>{let x={};for(let N of T)x[N]=y[`g__${N}`];for(let N of b){let q=x[N.fn]??={};q[N.col]=y[N.alias]??null}return p.count===!0&&(x.count=Number(y._count??0)),R.length>0&&(x.count=Object.fromEntries(R.map(([N],q)=>[N,Number(y[`count__${q}`]??0)]))),x};return T.length>0?E.map($):$(E[0]??{})},async count(c,p={}){let m=r(c,"count"),u=[],w=de(t,m,p,Q(u),"count").sql,h=await i(`SELECT count(*) AS n FROM ${m.sql} t WHERE true${w}`,u);return Number(h[0]?.n??0)},async findUnique(c,p,m={}){let u=r(c,"findUnique");fr(c,u.uniqueKeys,p);let w={select:m.select===void 0?void 0:Fe(m.select,[...m.select]),with:m.with,limit:2},h;if(m.lock===void 0)h=await g.findMany(c,p,w);else{let b=pt(t,u,p,{...w,lock:m.lock});h=l(u,await s(b.sql,b.params),m.with)}if(h.length>1)throw new Error(`findUnique(${c}): the database's constraints disagree with the schema; more than one row matched`);return h[0]??null},async findById(c,p){let m=r(c,"findById");if(!m.columns.has("id"))throw new Error(`findById(${c}): the table has no "id" column \u2014 use findUnique({ where: <its key> })`);let u=await i(`SELECT ${H(m)} FROM ${m.sql} WHERE "id" = $1`,[ue(m,"id",p)]);return u[0]?d(m,u[0]):null},async findMany(c,p={},m={}){let u=r(c,"findMany"),w=pt(t,u,p,m),h=m.lock!==void 0;return l(u,await(h?s:i)(w.sql,w.params),m.with)},async search(c,p,m={}){let u=r(c,"search"),w=u.search;if(w===void 0)throw new Error(`search(${c}): the table declares no search \u2014 defineTable(${JSON.stringify(u.name)}, { \u2026, search: { from: [<its text columns>], model } })`);let h=or(c,p,m),b=e.search,R=$=>l(u,$),T=async()=>{let $=gt(t,u,{text:h.text},{where:m.where,limit:h.limit,minScore:h.minScore});return R(await i($.sql,$.params))};if(h.mode==="text")return T();let O=b.embed;if(O===void 0)throw new Error(`search(${c}): no embedder was given, and a search by meaning embeds its query \u2014 createDatabase({ embed }) (the backend's db.embed); mode: "text" searches by word alone`);let D=$=>($===void 0?b.serving.delete(w.key):b.serving.set(w.key,$),$),A=b.serving.get(w.key)??D(et((await i(Zn,[w.key]))[0])),E;for(let $=1;;$++){if(A===void 0){if(h.mode==="vector")throw new Error(`search(${c}): the database holds no vectors for this table \u2014 its schema is migrated before the app serves`);return T()}if(E===void 0||E.of.model!==A.model||E.of.dimensions!==A.dimensions)try{E={of:A,literal:await sr(O,h.text,A)}}catch(k){if(h.mode==="vector")throw k;let S=Date.now();return S-(b.said.get(w.key)??-1/0)>=_s&&(b.said.set(w.key,S),b.log?.(`palgres: search(${c}) answered by word alone: its query could not be embedded (${k instanceof Error?k.message:String(k)})`)),T()}let y=an(A.dimensions,A.metric),x=v(A.types),N=gt(t,u,{...h.mode==="hybrid"?{text:h.text}:{},vector:{table:`${v($e)}.${v(je(w.key,A.gen))}`,literal:E.literal,type:`${x}.${y.type}`,operator:`OPERATOR(${x}.${y.operator})`}},{where:m.where,limit:h.limit,minScore:h.minScore}),q=await n(),[C,_]=await Promise.all([q.unsafe(Zn,[w.key],ht),q.unsafe(N.sql,N.params,lt(N.params)?void 0:ht)]),P=D(et(C[0]));if(P!==void 0&&P.gen===A.gen)return R(_);if($>=3)throw new Error(`search(${c}): the vectors that serve the table changed while it was searched, three times over`);A=P}},async page(c,p={},m={}){let u=r(c,"page");if(e.cursorKey===null)throw new Error("Database.page needs a cursor secret shared by every replica: createDatabase({ cursorSecret })");let w=e.cursorKey,h=Object.create(null);for(let[B,X]of u.columns)h[B]={type:X.type,nullable:X.nullable&&!u.primaryKey.includes(B)};let{order:b,size:R,backward:T,token:O}=$r(h,u.primaryKey,m),D=[],A=Q(D),E=de(t,u,p,A,"page").sql,$=dt(u,m.select===void 0?void 0:Fe(m.select,[...m.select]),"page"),y=rt({table:c,version:t.version,columns:h,order:b,where:E,params:D,select:m.select,with:m.with,identity:e.cursorScope()}),x=O===void 0?void 0:Tr(w,y,O,b.length),N=B=>`t.${v(B)}`,q=x?` AND ${ot(b,x,T,A,N)}`:"",C=x?`EXISTS (SELECT 1 FROM ${u.sql} t WHERE true${E} AND ${ot(b,x,!T,A,N,!0)})`:"false",_="__pb_page_",P=[...u.columns.keys(),...Object.keys(m.with??{})];for(;P.some(B=>B.startsWith(_));)_+="_";let k=`${_}ordinal`,S=`${_}opposite`,M=b.map((B,X)=>`${_}${X}`),L=b.map((B,X)=>`${ce(u,B.column)==="timestamp"?Se("timestamp",N(B.column)):`${N(B.column)}::text`} AS ${v(M[X])}`),I=m.with&&Object.keys(m.with).length?On(t,u,m.with,A,"page"):{select:[],joins:[]},K=b.map(B=>`${N(B.column)} ${B.direction==="asc"!==T?"ASC":"DESC"} NULLS ${B.nulls==="first"!==T?"FIRST":"LAST"}`).join(", "),j=`SELECT ${[$,...I.select,...L,`row_number() OVER (ORDER BY ${K}) AS ${v(k)}`].join(", ")} FROM ${u.sql} t ${I.joins.join(" ")} WHERE true${E}${q} ORDER BY ${K} LIMIT ${R+1}`,W=`SELECT p.*, b.${v(S)} FROM (SELECT ${C} AS ${v(S)}) b LEFT JOIN LATERAL (${j}) p ON true ORDER BY p.${v(k)}`,z=await i(W,D),Y=z[0]?.[S]===!0,V=z.filter(B=>B[k]!==null&&B[k]!==void 0),fe=V.length>R;V=V.slice(0,R),T&&V.reverse();let G=B=>B?Rr(w,y,M.map(X=>B[X]===null?null:String(B[X]))):null,ie={startCursor:G(V[0]),endCursor:G(V.at(-1)),hasNextPage:T?Y:fe,hasPreviousPage:T?fe:Y};for(let B of V)for(let X of[...M,k,S])delete B[X];return{rows:l(u,V,m.with),pageInfo:ie}},async attempt(c){return(await n()).savepoint(m=>c(Ze(()=>Promise.resolve(m),e)))},async txPlan(c){return(await n()).savepoint(async m=>{let u=[];for(let w of c.ops){let h=w.op==="select"||w.op==="delete"?r(w.table,"transaction plan"):o(w.table,"transaction plan"),b=Ms(t,h,w,u),R=w.op==="delete"?t.deferral(h):null;b!==null&&R!==null&&await m.unsafe(R.defer,[]);let T=b===null?[]:l(h,await m.unsafe(b.sql,b.params));b!==null&&R!==null&&await m.unsafe(R.check,[]);let O={rows:T,rows_affected:T.length};u.push(O),Bs(w,O)}return{results:u}})}};return g}function Ls(n,e){let t;return n.op<0||n.op>=e.length?t=`transaction plan: a reference points at operation ${n.op}, but the plan has run ${e.length} (0\u2026${e.length-1}). A reference can only read an EARLIER operation's row.`:e[n.op].rows[0]?t=`transaction plan: operation ${n.op}'s row has no column "${n.field}" (its columns: ${Object.keys(e[n.op].rows[0]).join(", ")}).`:t=`transaction plan: operation ${n.op} returned NO ROW, so "${n.field}" cannot be read. A reference does not guarantee its row exists \u2014 declare the expectation first (\`.expectOne(err)\`).`,Object.assign(new Error(t),{error_code:"tx_ref_unresolved"})}function Et(n,e){if(Mt(n))throw new Error(`${e}: got an imitation of a plan reference ({ $ref: \u2026 }) \u2014 this object was not made by the plan's builder. A reference is built in your code from an earlier operation's row (insert(...).expectOne(err).id); a filter from a request body cannot carry one.`)}function Rt(n,e){let t=e[n.$ref.op]?.rows[0];if(!t||!(n.$ref.field in t))throw Ls(n.$ref,e);return t[n.$ref.field]}function An(n,e,t,r,o,s){return Et(e,`transaction plan (${t})`),Lr(n,t,fn(e)?Rt(e,o):e,r,s)??[Is(n,e,t,r,o)]}function Is(n,e,t,r,o){if(Et(e,`transaction plan (${t})`),fn(e))return r(ue(n,t,Rt(e,o)));if(It(e)){let s=e.$expr;return s.fn==="now"?_e(s,r):`${v(t)} ${s.fn==="inc"?"+":"-"} ${r(ue(n,t,s.by))}`}return r(ue(n,t,e))}function bt(n,e){if(Et(n,"transaction plan filter"),fn(n)){let t=Rt(n,e);if(t==null)throw Object.assign(new Error(`transaction plan: a filter's reference to operation ${n.$ref.op}'s "${n.$ref.field}" is NULL. As a filter value NULL means IS NULL \u2014 every row with no value there, not the one the reference named. Write null in the filter when that is what you mean.`),{error_code:"tx_ref_null"});if(typeof t=="object"&&!Array.isArray(t)&&!Lt(t))throw Object.assign(new Error(`transaction plan: a filter's reference to operation ${n.$ref.op}'s "${n.$ref.field}" is an object. A filter compares a column with a value; an object there would be read as operators. Reference a scalar column.`),{error_code:"tx_ref_object"});return t}if(Array.isArray(n))return Fe(n,n.map(t=>bt(t,e)));if(n!==null&&typeof n=="object"&&!we(n)&&!Ne(n)&&!mn(n)&&!(n instanceof Date)){let t=Fe(n,{});for(let[r,o]of Object.entries(n))t[r]=bt(o,e);return t}return n}function yt(n,e,t,r,o,s){if(t===void 0||Object.keys(t).length===0&&!Ne(t))return{sql:"",conditions:0,resolved:{}};let i=bt(t,o);return{...de(n,e,i,r,s),resolved:i}}function Ms(n,e,t,r){let o=[],s=Q(o),i=`transaction plan ${t.op}`,a=t.op==="insertMany"?[...new Set((t.rows??[]).flatMap(l=>Object.keys(l)))]:Object.keys(t.values??t.set??{});Le(e,i,a);let f;switch(t.op){case"insert":{let l=t.values??{},d=Object.keys(l),g=d.flatMap(c=>An(e,l[c],c,s,r,i));f=d.length?`INSERT INTO ${e.sql} (${Ee(e,d)}) VALUES (${g.join(", ")}) RETURNING ${H(e)}`:`INSERT INTO ${e.sql} DEFAULT VALUES RETURNING ${H(e)}`;break}case"upsert":{let l=t.values??{},d=Object.keys(l),g=t.onConflict??[];if(d.length===0||g.length===0)throw Object.assign(new Error(`put on ${t.table} needs columns and onConflict`),{error_code:"tx_bad_upsert"});U(t.onConflict,"onConflict","which columns a conflict is on");for(let p of g)ee(e,p,i,"onConflict column");let c=d.flatMap(p=>An(e,l[p],p,s,r,i));f=`INSERT INTO ${e.sql} (${Ee(e,d)}) VALUES (${c.join(", ")}) ${Ye(e,d,g,"update",i)} RETURNING ${H(e)}`;break}case"insertMany":{let l=t.rows??[];if(l.length===0)return null;let d=Object.keys(l[0]),g=l.map(m=>`(${d.flatMap(u=>An(e,m[u],u,s,r,i)).join(", ")})`),c=t.onConflict??[];U(t.onConflict,"onConflict","which columns a conflict is on");for(let m of c)ee(e,m,i,"onConflict column");if(t.action==="update"&&c.length===0)throw Object.assign(new Error(`insertMany on ${t.table}: an overwrite needs onConflict columns`),{error_code:"tx_bad_upsert"});let p=t.action!==void 0?` ${Ye(e,d,c,t.action,i)}`:"";f=`INSERT INTO ${e.sql} (${Ee(e,d)}) VALUES ${g.join(", ")}${p} RETURNING ${H(e)}`;break}case"update":{let l=t.set??{},d=Object.keys(l);if(d.length===0)throw new Error(`update ${t.table}: nothing to set`);let g=d.map(m=>{let[u,w]=An(e,l[m],m,s,r,i),h=e.encrypted.get(m)?.lookup;return`${v(m)} = ${u}${h?`, ${v(h)} = ${w}`:""}`}),c=yt(n,e,t.where,s,r,i);Ie(c,i);let p=e.singleKey;f=p===null||Vr(c.resolved,p)?`UPDATE ${e.sql} AS t SET ${g.join(", ")} WHERE true${c.sql} RETURNING ${H(e,"t")}`:`WITH locked AS (SELECT t.${v(p)} AS "__pb_lock" FROM ${e.sql} t WHERE true${c.sql} ORDER BY t.${v(p)} FOR NO KEY UPDATE) UPDATE ${e.sql} AS t SET ${g.join(", ")} FROM locked WHERE t.${v(p)} = locked."__pb_lock" RETURNING ${H(e,"t")}`;break}case"delete":{let l=yt(n,e,t.where,s,r,i);Ie(l,i),f=`DELETE FROM ${e.sql} AS t WHERE true${l.sql} RETURNING ${H(e,"t")}`;break}case"select":{let l="";if(t.limit!==void 0){let g=Number(t.limit);if(!Number.isInteger(g)||g<0)throw new Error(`transaction plan (${t.table}): limit must be an integer, got "${String(t.limit)}"`);l=` LIMIT ${g}`}let d=t.lock==="update"?" FOR UPDATE":"";f=`SELECT ${H(e,"t")} FROM ${e.sql} t WHERE true${yt(n,e,t.where,s,r,i).sql}${l}${d}`;break}default:throw new Error(`unknown operation "${String(t.op)}" in a transaction plan`)}return{sql:f,params:o}}function Bs(n,e){let t=n.guard;if(!t)return;let r=e.rows.length;if(!(t.kind==="one"?r===1:t.kind==="none"?r===0:t.kind==="atLeast"?r>=t.n:r<=t.n))throw Object.assign(new Error(`transaction expectation failed: ${t.kind} (${r} row(s))`),{error_code:"tx_guard_failed",slot:t.slot})}import{AsyncLocalStorage as Jr}from"node:async_hooks";import{randomUUID as js}from"node:crypto";var Pn=new Jr,Hr=()=>({running:new Set}),Ks=n=>String(n?.message??n);function Ws(n){return new Oe(`The transaction was rolled back, not committed: a statement in it failed (${Ks(n)}) and the code went on. One failed statement aborts the whole transaction \u2014 Postgres refuses every later one and answers COMMIT with ROLLBACK. Wrap a write you expect to fail in \`Database.$attempt(async (tx) => \u2026)\` \u2014 it takes a SAVEPOINT, so only that write rolls back \u2014 or use \`Database.public.<t>.put({ data, onConflict: [...] })\` when what you brace for is a duplicate row.`,n)}async function zr(n){for(;n.running.size;)await Promise.allSettled([...n.running])}function Qr(n,e){let t=e.bind;if(e.lockTimeout!==void 0&&(t+=`, set_config('lock_timeout', ${J(e.lockTimeout)}, true)`),e.statementTimeout!==void 0&&(t+=`, set_config('statement_timeout', ${J(e.statementTimeout)}, true)`),!/^select /i.test(t))throw new Error("palgres: the binding statement must be a SELECT list");t+=", pg_catalog.current_setting('transaction_isolation') AS palgres_isolation",e.prepared!==void 0&&(t+=`, pg_catalog.current_setting('palgres.session', true) AS palgres_session, CASE WHEN coalesce(pg_catalog.current_setting('palgres.session', true), '') = '' THEN pg_catalog.set_config('palgres.session', ${J(e.prepared.mark())}, false) END AS palgres_marked, pg_catalog.set_config('plan_cache_mode', ${J(Sr)}, true) AS palgres_plans`);let r=null,o=null,s=null,i=null,a=!1,f=null,l=Hr(),d=!0,g,c=!1,p,m=async()=>!e.control||await e.control.drainCancellation()?!0:(p?.abandon?.(),!1),u,w=!1,h=(q,C,_,P)=>{if(e.prepared===void 0)return _;let k=_?.inline===!0;if(!k&&kr(q))return u===void 0?w=!0:u.forget(),_;if(u===void 0)return e.prepared.count(q,C,k),_;if(P.refused!==void 0)return _;let S=u.run(q,C,k);return S===void 0?_:{..._,prepared:S}},b=()=>{c=!0},R=()=>{if(a)throw new Error("Database transaction has settled; its handle cannot be used again");if(e.control?.check(),e.trace?.check(),Pn.getStore()!==e.scope)throw new Error("Database.$atomic cannot use a handle from another transaction or identity; use its tx argument")},T,O,D=new Set,A=0,E=!1,$=()=>r!==null&&!a&&c&&l.running.size===0&&D.size===0,y=(q,C,_=R,P,k=new Set)=>{let S=()=>{if(_(),O!==P||T?.getStore()!==P)throw new Error("Database connection belongs to another active savepoint; use its tx argument and await it before using the parent handle")};return{unsafe(M,L,I){try{S()}catch(W){return Promise.reject(W)}I?.read!==!0&&(d=!1);let K=(L??[]).map(De),j=()=>{let W=q.unsafe(M,K,h(M,K,I,C)),z=Promise.resolve(e.control?e.control.watch(W):W).catch(Y=>{throw cn(Y)&&(C.refused??={error:Y}),Y});return C.running.add(z),A++,z.catch(()=>{}).finally(()=>{C.running.delete(z),b(),--A===0&&!a&&e.onIdle?.()}),z};return e.trace?e.trace.query(M,j):j()},async savepoint(M){S(),d=!1;let L=Symbol("savepoint"),I=new Set,K=Hr();T??=new Jr,O=L;let j=(async()=>{try{return await q.savepoint(async W=>{let z=!1,Y=()=>{if(_(),z)throw new Error("Database savepoint has settled; its handle cannot be used again")};try{let V=T.run(L,()=>M(y(W,K,Y,L,I))),fe=await(e.control?e.control.race(V):V);if(await zr(K),K.refused)throw K.refused.error;return fe}finally{I.size&&await Promise.allSettled([...I]),z=!0}})}finally{O=P}})();D.add(j),k.add(j);try{return await j}finally{D.delete(j),k.delete(j)}}}},x=async()=>(R(),r||(r=new Promise((q,C)=>{let _=new Promise((P,k)=>{o=P,s=k});_.catch(()=>{}),i=(async()=>{let P=performance.now(),k;try{k=await(e.acquire?e.acquire(e.control?.signal):e.admission.acquire(e.claims,e.control?.signal))}finally{e.trace?.time("queueMs",P)}let S=performance.now(),M,L=e.control!==void 0&&n.cancelBackend!==void 0,I=[];if(e.isolation!==void 0||e.readOnly!==void 0){let ne=e.isolation??"read committed";wn({isolation:ne,readOnly:e.readOnly}),I.push(`SET TRANSACTION ISOLATION LEVEL ${ne.toUpperCase()}${e.readOnly===void 0?"":e.readOnly?" READ ONLY":" READ WRITE"}`)}I.push(L?`WITH backend AS MATERIALIZED (SELECT pid, backend_start::text AS started, xact_start::text AS xact_started FROM pg_catalog.pg_stat_get_activity(pg_catalog.pg_backend_pid())) ${t}, backend.pid, backend.started, backend.xact_started FROM backend`:t);let K=L&&n.cancelOpening!==void 0?`palgres:${js()}`:void 0,j=!1,W=ne=>{c=!0;let F=ne[0];if(typeof F?.palgres_isolation=="string"&&(g=F.palgres_isolation),e.prepared!==void 0&&typeof F?.palgres_session=="string"&&F.palgres_session!==""&&(u=e.prepared.on(F.palgres_session),w&&u.forget()),!L)return;if(!Number.isInteger(F?.pid)||typeof F?.started!="string"||typeof F?.xact_started!="string"){let Te=new Error("Database cancellation cannot identify its own backend");throw l.refused??={error:Te},Te}let oe={pid:F.pid,started:F.started,xactStarted:F.xact_started};j=!0,e.control.bindBackend(()=>n.cancelBackend(oe.pid,oe.started,oe.xactStarted))},z=async()=>{for(let ne=0;ne<400&&!c&&!j;ne++){if(await n.cancelOpening(K))return;await new Promise(F=>setTimeout(F,5))}},Y=k.openWithin,V=!1,fe,G,ie=()=>new ge({retryAfter:1},"Database queue deadline exceeded"),B=Y===void 0?void 0:new Promise((ne,F)=>{G=setTimeout(()=>{c||(V=!0,fe?.abandon?.(),F(ie()))},Y)});B?.catch(()=>{});let X=ne=>n.begin(async F=>{M=performance.now(),e.trace?.time("poolMs",S);let oe=e.trace?performance.now():0;if(e.control?.check(),a)throw new Error("Database transaction closed while waiting for its connection");if(V)throw ie();if(K!==void 0&&!j&&e.control.bindBackend(z),Y!==void 0&&!c){fe=F;try{await F.unsafe("SELECT 1")}catch(Te){throw V?ie():Te}}clearTimeout(G),e.trace?.time("setupMs",oe),ne(),p=F,q(y(F,l)),await _},{sql:I.join("; "),opened:W,tag:K});try{if(e.control?.check(),a)throw new Error("Database transaction closed while waiting for admission");let ne=!1;for(let F=1;;F++)try{let oe=X(()=>{ne=!0});return B===void 0?await oe:(oe.catch(()=>{}),await Promise.race([oe,B]))}catch(oe){let Te=ye(oe);if(ne||a||Te===void 0||F>=(Te==="lost"?yn:bn))throw oe;e.control?.check()}}finally{clearTimeout(G),M!==void 0&&e.trace?.time("connectionMs",M),k.release()}})().catch(P=>{throw C(P),P}),i.catch(()=>{})}),r.then(void 0,()=>{E=!0,a||e.onIdle?.()}),r)),N=q=>f??=(async()=>{if(a=!0,!r)return;await m(),D.size&&await Promise.allSettled([...D]);let C=e.trace?performance.now():0;s(q),await i?.catch(()=>{}),e.trace?.time("rollbackMs",C),e.trace?.rolledBack()})();return{ensure:x,get opened(){return r!==null},get busy(){return r!==null&&!a&&!E&&(!c||A>0)},get failed(){return E},get releasable(){return $()&&d&&l.refused===void 0&&(g==="read committed"||g==="read uncommitted")},async commit(){if(D.size&&await Promise.allSettled([...D]),!r){e.trace?.check(),a=!0;return}await zr(l);try{if(e.trace?.check(),e.control?.checkDeadline(),l.refused)throw Ws(l.refused.error)}catch(C){throw await N(C),C}if(a=!0,!await m()){let C=me(new te(503,"database_unavailable","The database is temporarily unavailable",{retrySafe:!1},1));throw await N(C),C}let q=e.trace?performance.now():0;if(o(),d&&g!==void 0&&g!=="serializable"){i.then(()=>e.trace?.committed(),()=>e.trace?.commitFailed());return}try{await i,e.trace?.committed()}catch(C){throw e.trace?.commitFailed(),C}finally{e.trace?.time("commitMs",q)}},rollback:N}}var Fs="5s",Us="10s",Vs=new Set(["22P02","22007","22008","22003","22001"]),Gr="55s",eo=1,Hs=1e3,nn=new Set,en,zs=new Zr("palgres.release");function Js(n){nn.add(n),en===void 0&&(en=zs.runInAsyncScope(()=>setInterval(()=>{let e=performance.now();for(let t of nn){let r=!0;try{r=t(e)}catch{r=!0}r&&nn.delete(t)}nn.size===0&&(clearInterval(en),en=void 0)},eo)),en.unref?.())}function Qs(n,e){let t=[],r=d=>d!==null&&d.opened&&!d.failed,o=new Set,s,i=!1,a=()=>{for(let d of t)if(r(d.tx)&&d.tx.busy)return!0;for(let d of o)if(d.busy)return!0;return!1},f=Zr.bind(d=>{if(s===void 0||a())return!0;let g=o.size,c=o.size===0;for(let m of t)r(m.tx)&&(g++,m.tx.releasable||(c=!1));if(g===0)return!0;let p=d-s;if(c){if(p<eo)return!1;for(let m of t){let u=m.tx;r(u)&&(m.tx=null,m.lease?.leave(),m.lease=void 0,u.commit().catch(()=>{}))}return s=void 0,!0}return e===void 0||i?!0:p<Hs?!1:(i=!0,e(Math.round(p)),!0)}),l=()=>{a()||(s=performance.now(),Js(f))};return{onIdle:l,surface(d,g){let c={tx:null};t.push(c);let p=()=>{nn.delete(f);let m=c.tx;return c.tx=null,c.lease=void 0,m};return{ensure(){if(s!==void 0&&(s=performance.now()),c.tx===null){if(n())return Promise.reject(new Error("Database transaction has settled; its handle cannot be used again"));c.tx=d(l,m=>g(m).then(u=>(c.lease=u,u)))}return c.tx.ensure()},commit:()=>p()?.commit()??Promise.resolve(),rollback:m=>p()?.rollback(m)??Promise.resolve()}},atomic(d){return o.add(d),()=>{o.delete(d)&&l()}}}}function Gs(n){let e=le(n),t=n?.code,r=s=>e!==void 0&&s.has(e)||typeof t=="string"&&s.has(t),o;if(r(Nt))o=!0;else if(r(Dt))o=!1;else return;return Re(new te(503,"database_unavailable","The database is temporarily unavailable",{retrySafe:o},1),n)}var Me=n=>String(n?.message??n);function Re(n,e){return n.cause=e,me(n)}function Tt(n,e,t){if(typeof n=="object"&&n!==null&&Yr.has(n))return n;let r=Ys(n,e,t);return typeof r=="object"&&r!==null&&Yr.add(r),r}var Yr=new WeakSet,Nn=(n,e,t)=>Object.assign(new Error(n,{cause:e}),{sqlstate:t});function Ys(n,e,t){if(Oe.is(n))return n;let r=le(n);if(r===Z.inFailedTransaction||/current transaction is aborted/i.test(Me(n)))return Nn(`This request cannot write any more: an earlier write in it failed, and a request runs in ONE Postgres transaction, so every statement after the failure is refused. Wrap a write you expect to fail in \`Database.$attempt(async (tx) => \u2026)\` \u2014 it takes a SAVEPOINT, so only that write rolls back \u2014 or use \`Database.public.<t>.put({ data, onConflict: [...] })\` when what you brace for is a duplicate row. (${Me(n)})`,n,Z.inFailedTransaction);if(ve.is(n))return n;if(r===Z.uniqueViolation)return Re(new ve(Ke(n)),n);if(r===Z.serializationFailure)return Re(new jn(r),n);if(r===Z.deadlockDetected)return Re(new Kn(r),n);if(r===Z.queryCancelled)return Re(Object.assign(new te(503,"database_query_cancelled","Database statement was cancelled"),{sqlstate:r}),n);let o=Gs(n);if(o)return o;if(e==="service"&&r===Z.foreignKeyViolation)return Nn(`Database.$asService() hit a foreign key with nothing to point at. It runs in its OWN transaction on its OWN connection, so a row this request wrote through \`Database.*\` is not visible to it until the request commits \u2014 and the request cannot commit until the handler returns. If the row it needs is one this request just created, do both writes on ONE surface. (${Me(n)})`,n,r);if(/lock timeout/i.test(Me(n))){let s;return e==="service"?s=Nn(`Database.$asService() waited too long for a row lock. It runs in its OWN transaction, so a row this request already wrote through Database.* is locked against it until the request commits \u2014 a wait that cannot end. Do that row's work on one surface or the other. (${Me(n)})`,n,r??Z.lockNotAvailable):s=Nn(`Database waited too long for a lock. Another transaction holds it: a concurrent one, or another of this request's own \u2014 Database.*, $asService() and $atomic each run in their OWN transaction, and a row one of them wrote stays locked against the others until it commits, a wait that cannot end while the handler runs. Do that row's work on one surface. (${Me(n)})`,n,r??Z.lockNotAvailable),Re(Object.assign(new te(503,"database_busy","The database waited too long for a lock",{retrySafe:!1},1),{sqlstate:r??Z.lockNotAvailable}),s)}return r!==void 0&&Vs.has(r)?Re(Object.assign(new te(400,"invalid_value","A value is not one its column can take"),{sqlstate:r}),n):r===Z.insufficientPrivilege&&t!==null?Re(Object.assign(new te(t==="anon"?401:403,"permission_denied","The database does not allow this caller to do this"),{sqlstate:r}),n):(r!==void 0&&typeof n=="object"&&n!==null&&!Object.hasOwn(n,"sqlstate")&&Object.defineProperty(n,"sqlstate",{value:r,enumerable:!0,configurable:!0}),n)}function Xs(n,e,t){let r=o=>({unsafe(s,i,a){let f;try{f=o.unsafe(s,i,a)}catch(l){return Promise.reject(Tt(l,e,t))}return Promise.resolve(f).then(Pe,l=>{throw Tt(l,e,t)})},savepoint:s=>o.savepoint(i=>s(r(i))),...o.abandon?{abandon:o.abandon.bind(o)}:{}});return{unsafe:(o,s)=>n.unsafe(o,s),begin:(o,s)=>n.begin(i=>o(r(i)),s).catch(i=>{throw Tt(i,e,t)}),...n.cancelBackend?{cancelBackend:n.cancelBackend.bind(n)}:{},...n.cancelOpening?{cancelOpening:n.cancelOpening.bind(n)}:{}}}var Zs=2,Xr={anon:"anon",authenticated:"authenticated",service:"service"};function ei(n,e){let t=Object.hasOwn(Xr,e.role)?Xr[e.role]:void 0;if(t===void 0)throw new Error(`palgres: a request is anon, authenticated or service, not "${String(e.role)}"`);return n[t]}function $t(n,e,t,r={}){let{signal:o}=r,s=r.diagnostics===void 0?void 0:new kn(r.diagnostics),i=o===void 0?void 0:new qe(void 0,o),a=ei(e.roles,t),f=e.roles.service,l=t.role==="anon"||t.role==="authenticated"?t.role:null,d=t.claims,g=!1,c=!1,p=()=>{c&&ln.committed()},m=k=>{let S;return{cat:e.cat,trace:s,cursorKey:e.cursorKey,cursorScope:()=>S??=Er(k,d),search:e.search,searchable:()=>{c=!0}}},u=m(a),w=m(f),h=new Set,b=null,R=!1,T=0,O=new Set,D=k=>new Promise((S,M)=>{let L=W=>{O.delete(I),clearTimeout(j),k?.removeEventListener("abort",K),W===void 0?S():M(W)},I=()=>L(),K=()=>L(k?.reason??new Error("Database admission cancelled")),j=setTimeout(()=>L(new ge({retryAfter:1},"Database queue deadline exceeded")),e.admission.queueTimeoutMs);O.add(I),k?.addEventListener("abort",K,{once:!0}),k?.aborted&&K()}),A=async k=>{let S;for(;;){for(;h.size===0&&b!==null;)await b;let I=h.size>0;if(I){for(;T>=Zs;)await D(k);T++}let K;try{let j=e.admission.acquire(d,k,{nested:I,returning:!I&&R}).then(W=>{if(I&&h.size===0)return W.release(),null;let z={nested:I,turn:W};return h.add(z),I||(R=!0),z});if(!I){let W=j.then(()=>{},()=>{});b=W,W.then(()=>{b===W&&(b=null)})}K=await j}catch(j){throw I&&E(),j}if(K!==null){S=K;break}E()}let M=!1,L=()=>{if(!M){if(M=!0,h.delete(S),S.nested){E();return}for(let I of h){[S.turn,I.turn]=[I.turn,S.turn],I.nested=!1,S.nested=!0,E();return}}};return{queueMs:S.turn.queueMs,leave:L,release:()=>{L(),S.turn.release()},...S.nested&&e.binding.pooled===!0?{openWithin:e.admission.queueTimeoutMs}:{}}},E=()=>{T--;let k=O.values().next().value;k?.()},$=Qs(()=>g,r.heldIdle),y=(k,S,M={})=>Qr(Xs(n,S,S==="user"?l:null),{bind:He(e.binding,k,d),claims:d,admission:e.admission,acquire:A,trace:s,prepared:e.prepared,...M}),x=(k,S)=>async(M,L={})=>{if(wn(L),g)throw new Error("Database request has settled; it cannot open another transaction");if(Pn.getStore()!==void 0)throw new Error("Nested Database.$atomic is not supported; use tx.$attempt for a savepoint");let I=gn(L.retry),K=L.signal&&o?AbortSignal.any([L.signal,o]):L.signal??o,j=L.timeoutMs!==void 0||K!==void 0?new qe(L.timeoutMs,K):void 0;try{j?.check();for(let W=0;;W++){j?.check();let z=[L.statementTimeoutMs,j?.remainingMs()].filter(G=>G!==void 0),Y=Symbol("atomic transaction"),V=y(k,S,{scope:Y,isolation:L.isolation,readOnly:L.readOnly,control:j,lockTimeout:`${L.lockTimeoutMs??5e3}ms`,statementTimeout:z.length===0?void 0:`${Math.min(...z)}ms`,onIdle:$.onIdle}),fe=$.atomic(V);try{let G=Ze(()=>V.ensure(),S==="user"?u:w),ie=Pn.run(Y,()=>M(G)),B=await(j?j.race(ie):ie);return await V.commit(),p(),B}catch(G){await V.rollback(G);let ie=xe(G)||Oe.is(G)&&xe(G.cause);if(W>=I||!ie)throw G;s?.retry();let B=new Promise(X=>setTimeout(X,Math.min(100,2**W)));await(j?j.race(B):B)}finally{fe()}}}finally{j?.dispose()}},N=$.surface((k,S)=>y(a,"user",{lockTimeout:Us,statementTimeout:Gr,control:i,onIdle:k,acquire:S}),A),q=null,C,_=null,P=()=>{if(_===null){if(g)throw new Error("Database request has settled; it cannot open another transaction");C=o===void 0?void 0:new qe(void 0,o);let k=C,S=$.surface((M,L)=>y(f,"service",{lockTimeout:Fs,statementTimeout:Gr,control:k,onIdle:M,acquire:L}),A);q=S,_=Object.assign(Ze(()=>S.ensure(),w),{atomic:x(f,"service")})}return _};return{client:Object.assign(Ze(()=>N.ensure(),u),{asService:P,atomic:x(a,"user")}),async commit(){g=!0;try{try{s?.check()}catch(k){throw await N.rollback(k),await q?.rollback(k),k}try{await N.commit()}catch(k){throw await q?.rollback(k),k}await q?.commit(),p(),s?.complete("committed"),i?.dispose(),C?.dispose()}catch(k){throw s?.failed(),k}},async rollback(k){g=!0,await N.rollback(k),await q?.rollback(k),i?.dispose(),C?.dispose(),s?.complete("failed")}}}function ni(n){if(n.codec!==void 0&&n.codec in Ae)return Ae[n.codec].tsType;switch(n.type){case"uuid":case"text":case"timestamp":case"date":return"string";case"sql":return n.sqlType!==void 0&&un.has(n.sqlType)?"number":n.sqlType!==void 0&&dn.has(n.sqlType)?"Json":"string";case"integer[]":return"number[]";case"boolean[]":return"boolean[]";case"uuid[]":case"text[]":case"bigint[]":case"numeric[]":case"timestamp[]":case"date[]":return"string[]";case"integer":return"number";case"bigint":case"numeric":return"string";case"boolean":return"boolean";case"jsonb":return"Json";case"enum":{let e=n.enumValues??[];return e.length===0?"string":e.map(t=>JSON.stringify(t)).join(" | ")}case"enum[]":{let e=n.enumValues??[];return e.length===0?"string[]":`(${e.map(t=>JSON.stringify(t)).join(" | ")})[]`}default:{let e=n.type;throw new Error(`env-gen: the column type "${String(e)}" has no TypeScript type \u2014 add a case to baseTsType`)}}}function ti(n){if(n.encrypted!==void 0)return n.encrypted.lookup?"encrypted:lookup":"encrypted";if(n.type==="enum"){let e=[...n.enumValues??[]].sort();return e.length===0?"enum":`enum:${e.join("|")}`}return n.type}function no(n){let e=`Pg<${ni(n)}, ${JSON.stringify(ti(n))}>`;return n.nullable?`${e} | null`:e}function ri(n){return n.nullable===!0||n.defaultRandom===!0||n.defaultNow===!0||n.defaultValue!==void 0||n.defaultSql!==void 0||n.dbAssigned===!0||n.identity!==void 0}function oi(n){return n.identity==="always"||n.generated!==void 0}var tn=n=>/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(n)?n:JSON.stringify(n);function to(n,e,t){let r=Object.entries(n.columns).filter(([,a])=>a._def.ignored!==!0),o=r.map(([a,f])=>`${t} ${tn(a)}: ${no(f._def)};`),s=r.filter(([,a])=>!oi(a._def)).map(([a,f])=>`${t} ${tn(a)}${ri(f._def)?"?":""}: ${no(f._def)};`),i=e.map(a=>`${tn(a.name)}: { to: ${JSON.stringify(a.to)}; kind: ${JSON.stringify(a.kind)}; via: ${JSON.stringify(a.via)} }`).join("; ");return[`${t}${tn(n.name)}: {`,`${t} row: {`,...o,`${t} };`,`${t} insert: {`,...s,`${t} };`,`${t} relations: {${i===""?"":` ${i} `}};`,`${t} uniqueKeys: ${JSON.stringify(Rn(n))};`,...n.search!==void 0?[`${t} searchable: true;`]:[],`${t}};`].join(`
|
|
32
|
+
`)}function si(n){for(let e of n)for(let t of Object.values(e.tables))for(let[r,o]of Object.entries(t.columns)){let s=o._def;if(!(s.transform===void 0||s.codec!==void 0))throw new Be([`table "${be(e.name,t.name)}" column "${r}" declares .transform<T>(): its target type does not exist at runtime, so the generated types would say something the engine contradicts. Declare a named codec instead \u2014 .asNumber() for a JS number, .asDecimal() for the exact string.`])}}var St="// palbase:env:begin",kt="// palbase:env:end",ro=`/**
|
|
33
33
|
* A column's Postgres type, carried in its TypeScript type.
|
|
34
34
|
*
|
|
35
35
|
* __pg is optional, so a row still reads as a plain string or number and is
|
|
@@ -46,22 +46,22 @@ type Pg<T, N extends string> = T & { readonly __pg?: N };
|
|
|
46
46
|
* undefined included: JSON.stringify drops undefined fields, and code that
|
|
47
47
|
* writes { a: undefined } is everywhere \u2014 refusing it would be wrong.
|
|
48
48
|
*/
|
|
49
|
-
type Json = string | number | boolean | null | undefined | Json[] | { [k: string]: Json };`;function
|
|
49
|
+
type Json = string | number | boolean | null | undefined | Json[] | { [k: string]: Json };`;function oo(n,e,t){si(n);let r=Je(n),o=p=>Object.values(p.tables).filter(m=>m.ignored!==!0),s=n.find(p=>p.name==="public"),i=n.filter(p=>p.name!=="public"),a=(s?o(s):[]).map(p=>to(p,r.get(p.name)??[]," ")),f=a.length>0?`
|
|
50
50
|
${a.join(`
|
|
51
51
|
`)}
|
|
52
|
-
`:"",l=i.map(
|
|
53
|
-
${
|
|
52
|
+
`:"",l=i.map(p=>{let m=o(p).map(u=>to(u,r.get(be(p.name,u.name))??[]," "));return` ${tn(p.name)}: {
|
|
53
|
+
${m.join(`
|
|
54
54
|
`)}
|
|
55
|
-
};`}),
|
|
55
|
+
};`}),d=l.length>0?`
|
|
56
56
|
${l.join(`
|
|
57
57
|
`)}
|
|
58
|
-
`:"",
|
|
59
|
-
interface Access {${
|
|
60
|
-
${
|
|
61
|
-
`}}`;return`declare module ${JSON.stringify(
|
|
62
|
-
interface Tables {${
|
|
63
|
-
interface Schemas {${
|
|
64
|
-
}`}function
|
|
58
|
+
`:"",g=t===void 0?void 0:Vn(t," "),c=g===void 0?"":`
|
|
59
|
+
interface Access {${g===""?"":`
|
|
60
|
+
${g}
|
|
61
|
+
`}}`;return`declare module ${JSON.stringify(e)} {
|
|
62
|
+
interface Tables {${f}}
|
|
63
|
+
interface Schemas {${d}}${c}
|
|
64
|
+
}`}function ii(n,e={}){let t=e.module??"palbase/backend/env",r=oo(n,t,e.access);return`// AUTO-GENERATED by Palgres' makeEnvDts from the app's schema files \u2014 DO NOT EDIT.
|
|
65
65
|
// Nothing writes it again on its own: run makeEnvDts again when a schema changes.
|
|
66
66
|
// Augments the ${t} \`Tables\` interface so \`Database.public.*\`
|
|
67
67
|
// is typed with no import and no generic. Schemas other than \`public\` land
|
|
@@ -69,16 +69,16 @@ ${w}
|
|
|
69
69
|
// \`Database.<schema>.<table>\`.
|
|
70
70
|
|
|
71
71
|
${St}
|
|
72
|
-
${
|
|
72
|
+
${ro}
|
|
73
73
|
|
|
74
74
|
${r}
|
|
75
75
|
${kt}
|
|
76
76
|
|
|
77
77
|
export {};
|
|
78
|
-
`}function
|
|
78
|
+
`}function ai(n,e={}){let t=e.module??"palbase/backend/env";return`${St}
|
|
79
79
|
// The app's tables, from its schema files: rows, inserts, unique keys and relations (with, has). Written by
|
|
80
80
|
// palbase db:types \u2014 run it again when a schema changes.
|
|
81
|
-
${
|
|
81
|
+
${ro}
|
|
82
82
|
|
|
83
|
-
${
|
|
84
|
-
${kt}`}function
|
|
83
|
+
${oo(n,t,e.access)}
|
|
84
|
+
${kt}`}function li(n,e){let t=e.tenant,r=e.key??"id",o=(d,g)=>{if(g==null||typeof g!="string"&&typeof g!="number"&&typeof g!="bigint"&&typeof g!="boolean")throw new TypeError(`defineRepository: the ${d} is a string, number, bigint or boolean, not ${g===null?"null":typeof g}`);return g},s=d=>({[t]:o("tenant",d)}),i=(d,g)=>({[t]:o("tenant",d),[r]:o(r,g)}),a=(d,g)=>({...d,[t]:o("tenant",g)}),f=d=>{let g=[t,r].filter(c=>Object.hasOwn(d,c));if(g.length>0)throw new pe({fields:g.map(c=>({field:c,message:"cannot be changed through this update"}))},`defineRepository: the patch carries ${g.join(" and ")}, which an update does not change`);return d};class l{async list(g){return n.findMany({where:s(g)})}async find(g,c){return(await n.findMany({where:i(g,c),limit:1}))[0]??null}async insert(g,c){return n.insert(a(c,g))}async update(g,c,p){let m=await this.updateScoped(g,c,p);if(m===null)throw new Bn(`no row ${r}=${String(c)} where ${String(t)}=${String(g)}`);return m}async updateScoped(g,c,p){return(await n.updateMany({where:i(g,c),set:f(p)}))[0]??null}async delete(g,c){await n.deleteMany({where:i(g,c)})}}return l}function ci(n){return Hn({$col:n},"col")}function ui(n,...e){return Hn({$sql:{text:[...n],values:e}},"sql")}async function di(n,e={}){let t=gn(e.retry),r=0;for(;;)try{return await n()}catch(o){if(r>=t||!xe(o))throw o;r+=1}}async function yl(n){if(n.prepare===!0&&n.binding.pooled===!0)throw new Error("palgres: a pooled binding's connections are a transaction-mode pooler's, another client's each transaction \u2014 nothing stays prepared on them: createDatabase({ prepare: false })");await Gn(n.sql);let e=new Ln;await e.read(i=>n.sql.unsafe(i));let t=n.schemas.some(i=>Object.values(i.tables).some(a=>!a.ignored&&Object.values(a.columns).some(f=>f._def.encrypted!==void 0&&!f._def.ignored))),r=null;if(t||e.size>0){if(n.fields===void 0)throw new Error(`palgres: ${t?"the schema has an .encrypted() column":"a migration is taking a column's encryption on or off"}: the engine needs the project's fields to seal and open it \u2014 createDatabase({ fields })`);r=await xt(n.fields),setInterval(()=>{e.read(a=>n.sql.unsafe(a)).catch(a=>n.log?.(`palgres: which columns are going over could not be read (${a instanceof Error?a.message:String(a)}); kept as last read`))},_n).unref?.()}let o={cat:new Tn(n.schemas,n.binding,r!==null?{cipher:r,sealing:e}:null),binding:n.binding,roles:{...We,...n.roles},admission:cr(n.sql,n.admission),cursorKey:n.cursorSecret?br(n.cursorSecret):null,search:rr(n.embed,n.log),prepared:n.prepare===!1||n.binding.pooled===!0?void 0:new $n},s=n.binding.access!==void 0&&n.binding.accessText!==void 0?Un(n.binding.accessText,n.binding.access):void 0;return{binding:n.binding,request(i,a){let f=$t(n.sql,o,i,a);return{database:Ft(f.client,{...s?{access:s}:{},as:i.role}),client:f.client,commit:()=>f.commit(),rollback:l=>f.rollback(l)}},async reseal(i={}){let a=o.cat.fields;if(a===null||!n.binding.direct)return[];let f=[];for(let{table:l,column:d,encrypted:g}of o.cat.encryptedColumns()){if(a.sealing.get(g.address)!==void 0)continue;let c={table:l.sql,column:d,lookup:g.lookup,address:g.address,direction:"seal"},p=null,m=0;do{let u=$t(n.sql,o,{role:"service",claims:{}});try{let w=await Ot((h,b)=>u.client.query(h,b),c,a.cipher,p,i.batchSize??500);await u.commit(),m+=w.done,p=w.last}catch(w){throw await u.rollback(w),w}}while(p!==null);f.push({address:g.address,resealed:m})}return f}}}export{vo as AccessRefused,Jn as BUN_CLOSE_GRACE_MS,pe as BadRequest,ho as Conflict,We as DEFAULT_ROLES,Kn as DeadlockDetected,he as DriverRefused,go as ENGINE_RAISED,kt as ENV_BLOCK_END,St as ENV_BLOCK_START,po as HTTP_ERROR_BRAND,te as HttpError,bo as MigrationOpen,yo as MigrationRefused,$o as Migrator,Bn as NotFound,Ko as POSTGRES_JS_TYPES,Ro as RowsHeld,Cn as SEALING,_n as SEALING_REFRESH_MS,$e as SEARCH_SCHEMA,lo as SETTLE_MS,Z as SQLSTATE,Be as SchemaError,Ln as Sealing,jn as SerializationFailure,ge as TooManyRequests,Oe as TransactionAborted,Po as TxPlanError,Ao as TxRefError,ve as UniqueViolation,hn as VersionNotMigrated,Eo as VersionStillConnected,Un as accessNames,Vn as accessTypesBlock,uo as adoptionBaseline,Do as ago,Wn as applicationName,Io as bind,He as bindStatement,Vt as binding,Je as buildRelations,er as bunDriver,Qn as cancelBackendThrough,tr as cancelOpeningThrough,io as canonicalType,nr as closeBunPool,ci as col,ye as connectionFailure,Ke as constraintOf,yl as createDatabase,Zo as createSearchWorker,To as cutOff,Co as decrement,li as defineRepository,Dn as digest,fo as drift,so as emptySchema,De as encodeParam,ze as encodePgArray,ai as envBlock,qn as fieldAddress,Mo as forgetUser,Bo as forgetUserIn,qo as increment,Zt as inlineParams,mo as introspect,we as isColRef,Oo as isData,So as isDirect,wo as isEngineRaised,xe as isRetryable,ii as makeEnvDts,xo as markData,me as markEngineRaised,rn as normalize,No as now,co as plan,_o as pooledBinding,Uo as postgresJsDriver,ko as pullSchema,Fo as renewingBunPool,Lo as sayRunning,Fn as searchPath,ui as sqlFragment,le as sqlstateOf,ao as validate,je as vectorTable,Gn as verifyDriver,Mn as versionSchema,di as withRetry};
|
package/dist/testing.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palgres 0.
|
|
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/LOZ6YAC7.js";import{n as Te,p as Ae}from"./chunks/FHL5XTBG.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/M32MCL6M.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.70.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/W6GXJWN3.js";import{n as Te,p as Ae}from"./chunks/V26AHA6W.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/ZEQXUCWB.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
|
@@ -289,16 +289,12 @@ export declare class DriverRefused extends Error {
|
|
|
289
289
|
}
|
|
290
290
|
/** Asks Postgres what it received for each kind of text the engine sends, and refuses a driver that changed it. */
|
|
291
291
|
export declare function verifyDriver(sql: SqlDriver): Promise<void>;
|
|
292
|
-
/** What postgresJsDriver needs of postgres.js: its pool, as `postgres(url, { types: POSTGRES_JS_TYPES })` makes it. */
|
|
292
|
+
/** What postgresJsDriver needs of postgres.js (4+): its pool, as `postgres(url, { types: POSTGRES_JS_TYPES })` makes it. */
|
|
293
293
|
export interface PostgresJs {
|
|
294
294
|
unsafe(text: string, params?: unknown[]): PromiseLike<unknown> & {
|
|
295
295
|
simple(): PromiseLike<unknown>;
|
|
296
296
|
};
|
|
297
297
|
begin<T>(fn: (tx: PostgresJsTx) => Promise<T>): Promise<T>;
|
|
298
|
-
/** Whether it keeps its statements prepared: postgres.js' default, `prepare: false` not. */
|
|
299
|
-
readonly options?: {
|
|
300
|
-
readonly prepare?: boolean;
|
|
301
|
-
};
|
|
302
298
|
}
|
|
303
299
|
interface PostgresJsTx {
|
|
304
300
|
unsafe(text: string, params?: unknown[]): PromiseLike<unknown> & {
|
|
@@ -306,5 +302,20 @@ interface PostgresJsTx {
|
|
|
306
302
|
};
|
|
307
303
|
savepoint<T>(fn: (tx: PostgresJsTx) => Promise<T>): Promise<T>;
|
|
308
304
|
}
|
|
305
|
+
/**
|
|
306
|
+
* postgres.js (4+) as the engine's driver: its transaction runs the opening
|
|
307
|
+
* after its own BEGIN, before the work — a round trip more than Bun's, the
|
|
308
|
+
* same transaction. `control`, a pool of one, is what a cancel goes through.
|
|
309
|
+
*
|
|
310
|
+
* postgres.js sends a statement on a connection whose close it has not read
|
|
311
|
+
* yet, and fails it then (CONNECTION_CLOSED). A transaction whose BEGIN or
|
|
312
|
+
* opening failed so — before the work was handed the transaction — goes on
|
|
313
|
+
* another connection; a statement on its own is a transaction of one, so
|
|
314
|
+
* the same holds for it. Nothing that reached the work is sent again.
|
|
315
|
+
*
|
|
316
|
+
* postgres.js 4 runs transaction control (`BEGIN`/`COMMIT`/`ROLLBACK`/
|
|
317
|
+
* `SAVEPOINT`) as simple queries, refuses a `COMMIT` answered with `ROLLBACK`,
|
|
318
|
+
* and guards writes against a closed connection natively.
|
|
319
|
+
*/
|
|
309
320
|
export declare function postgresJsDriver(pool: PostgresJs, control: PostgresJs): SqlDriver;
|
|
310
321
|
export {};
|