palgres 0.66.0 → 0.68.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/index.js CHANGED
@@ -1,19 +1,19 @@
1
- /*! palgres 0.66.0 — Palbase SDK License (see LICENSE) */
2
- import{a as Ae,j as un,k as dn}from"./chunks/LRDQMK6O.js";import{A as Io,B as Lo,C as Mo,D as Bo,E as Ve,F as Ft,G as Ut,H as gn,I as wn,J as Vt,K as Ht,a as No,b as Un,c as Vn,e as It,f as Do,g as qo,h as Pe,i as Fe,j as U,k as Hn,l as ye,m as Ne,n as fn,o as Lt,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 Wt,y as Co,z as _o}from"./chunks/5UVBQYNY.js";import{A as Oo,B as Ct,C as Fn,D as Ao,E as Po,a as xt,b as qn,c as Cn,d as _n,e as po,f as In,g as Ot,h as on,i as Se,j as Ke,k as Ln,l as Pt,m as an,n as ln,o as Mn,p as go,q as wo,r as ho,s as yo,t as So,u as $o,v as ko,w as vo,x as xo,y as We,z as Wn}from"./chunks/BWGT6CBO.js";import{a as _t}from"./chunks/2VBY4HRX.js";import{A as Dt,B as qt,C as ue,D as cn,E as je,a as le,b as At,c as sn,d as Q,j as bo,k as To,l as Z,m as te,n as ge,o as Ro,p as we,q as Bn,r as Eo,s as ve,t as xe,u as Kn,v as jn,w as Oe,x as he,y as ce,z as Nt}from"./chunks/RN23MOOY.js";import{T as se,a as vt,c as Be,d as uo,f as fo,j as mo,k as rn,m as Dn}from"./chunks/NDFZTRRI.js";function Ko(e){return{...e,pooled:!0}}function jo(e){return`SELECT set_config('application_name', ${Q(e.applicationName)}, false)`}function Qt(e,n,t,r){return{...t!==void 0?{access:t}:{},...t!==void 0&&r!==void 0?{accessText:r}:{},version:e,direct:n,searchPath:n?`${le("public")}, ${Ct}, 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 Wo(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=ce(i);if(a!=="42P01"&&a!=="3F000"){if(ue(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 Qt(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=zt.get(e);r||zt.set(e,r=new Map);let o=r.get(n);return o===void 0&&(o=`SELECT set_config('role', ${Q(n)}, true), set_config('search_path', ${Q(e.searchPath)}, true), set_config('application_name', ${Q(e.applicationName)}, ${e.pooled===!0}), set_config('palgres.version', ${Q(String(e.version))}, true), set_config('request.jwt.claims', `,r.set(n,o)),`${o}${Q(JSON.stringify(t))}, true)`}var zt=new WeakMap;async function Fo(e,n,t,r,o="service_role"){let s=Gt(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 Yt(p,s,r);return i?{...l,relationships:await Jt(p,r)}:l})}async function Uo(e,n,t,r){let o=Gt(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 Yt(p,o,r);return i.length>0&&await p.query(`SELECT palgres.defer_keys(${a}, false)`),s?{...l,relationships:await Jt(p,r)}:l})}async function Jt(e,n){let t=await e.query("SELECT access.forget_subject($1)::int AS n",[n]);return Number(t[0].n)}function Gt(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 Yt(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 ${le(s.column)} = NULL WHERE ${le(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 ${le(s.column)} = $1 RETURNING 1) SELECT count(*)::int AS n FROM t`,[t]);r+=Number(i[0].n)}return{deleted:r,detached:o}}function nr(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?Vo(e):e instanceof Uint8Array?`\\x${Buffer.from(e).toString("hex")}`:Array.isArray(e)&&tr(e)?ze(e):JSON.stringify(e)}function tr(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)&&tr(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 Vo(e){if(Number.isNaN(e.getTime()))throw new TypeError("an invalid Date is not a database value");return e.toISOString()}var Ho={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 Xt(e){let n=e;return n.length>0&&Array.isArray(n[n.length-1])?n[n.length-1]:n}var rr=/^[A-Za-z0-9:_-]{1,80}$/;function or(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":Q(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 Zt(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 sr(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&&!rr.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 T=1;;T++){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=qt(R);v&&(e.discard!==void 0?e.discard(i):Promise.resolve(i.close({timeout:0})).catch(()=>{}),a=!1,p=!1);let P=v?"unusable":ue(R);if(c||P===void 0||T>=(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 Zt(w.error)})),g={unsafe(y,T,R){if(w!==void 0)return Promise.reject(Zt(w.error));let v=R?.prepared,P=()=>v===void 0?i.unsafe(y,T):nr(v,A=>i.unsafe(A).simple());if(l)return P();if(m===null&&R?.inline===!0&&v===void 0){let A=or(y,T??[]);if(A!==void 0)return d(A)}return u().then(P)},async savepoint(y){await u();let T=`palgres_sp_${++f}`;await i.unsafe(`SAVEPOINT ${T}`).simple();let R;try{R=await y(g)}catch(v){throw await Promise.resolve(i.unsafe(`ROLLBACK TO SAVEPOINT ${T}; RELEASE SAVEPOINT ${T}`).simple()).catch(()=>{}),v}return await i.unsafe(`RELEASE SAVEPOINT ${T}`).simple(),R},abandon(){c||(c=!0,Promise.resolve(i.close({timeout:0})).catch(()=>{}))}},h=async y=>{let T=await i.unsafe(y).simple();if(p=!1,y==="COMMIT"&&T.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(T){throw await m?.catch(()=>{}),p&&!c&&await h("ROLLBACK").catch(()=>{}),T}if(!p)return y;try{await h("COMMIT")}catch(T){throw p&&await h("ROLLBACK").catch(()=>{}),T}return y}finally{a&&(p&&!c&&await Promise.resolve(i.close()).catch(()=>{}),i.release())}}};if(n!==void 0){let r=sr(n);t.cancelBackend=Jn(r),t.cancelOpening=ar(r)}return t}var Qn=1e3;async function ir(e,n){let t;try{await Promise.race([Promise.resolve(e.close({timeout:n})),new Promise(r=>{t=setTimeout(r,n*1e3+Qn)})])}finally{clearTimeout(t)}}function zo(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([ir(n,a),Promise.race([Promise.all(s.values()),new Promise(l=>{p=setTimeout(l,a*1e3+Qn)})])])}finally{clearTimeout(p)}}}}function ar(e){return async n=>{if(!rr.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.68.0 — Palbase SDK License (see LICENSE) */
2
+ import{a as Ae,j as un,k as dn}from"./chunks/UW7RR3MZ.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/RCW2ILY4.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/NHN34MV5.js";import{a as _t}from"./chunks/TLJINWUH.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/4VEWGTPJ.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/O43AXIWY.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
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 Jn(e){return async(n,t,r)=>{await e.unsafe(`SELECT pg_cancel_backend(pid) FROM pg_stat_activity
4
+ AND usename = session_user AND datname = current_database() AND backend_type = 'client backend'`,[String(t.length),t])).length>0}}function Qn(e){return async(n,t,r)=>{await e.unsafe(`SELECT pg_cancel_backend(pid) FROM pg_stat_activity
5
5
  WHERE pid = $1::integer AND backend_start = $2::timestamptz AND xact_start = $3::timestamptz
6
- AND usename = session_user AND datname = current_database() AND backend_type = 'client backend'`,[String(n),t,r])}}var be=class extends Error{constructor(n){super(`palgres: the driver ${n}. 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(e){let t=(await e.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 be("re-encodes text bound for a jsonb parameter (JSON text became a JSON string)");if(t.b!==!0)throw new be("changes the text bound for a boolean ('true' was not read as true)");if(t.t!==!0)throw new be("changes the text bound for a timestamp (its microseconds did not arrive)");if(Number(t.a)!==2)throw new be("changes the text bound for an array (the literal {1,2} did not arrive)");if(t.y!==!0)throw new be("changes the text bound for a bytea");if((await e.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 be("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")}var Qo=/\bdeallocate\b/i,Jo="SELECT EXISTS (SELECT FROM pg_catalog.pg_prepared_statements WHERE statement = 'commit' AND NOT from_sql) AS palgres_commit_kept",er=()=>new Promise(()=>{});function Go(e,n){let t=a=>Promise.resolve(a).then(p=>p),r=e.options?.prepare!==!1,o=a=>async(p,l)=>{for(let m=1;;m++){let w=!1,c=!1,f,d=y=>f!==void 0?Promise.reject(f.error):t(y()).catch(T=>{throw ue(T)==="lost"&&(f??={error:T}),T}),u=(y,T)=>y.then(R=>f===void 0?R:(T(f.error),er()),R=>f===void 0?Promise.reject(R):(T(R),er())),g=y=>({unsafe:(T,R,v)=>(r&&Qo.test(T)&&(c=!0),v?.prepared===void 0?d(()=>y.unsafe(T,R??[])):nr(v.prepared,P=>d(()=>y.unsafe(P).simple()))),savepoint:T=>new Promise((R,v)=>{if(f!==void 0)return v(f.error);y.savepoint(P=>u(T(g(P)),v)).then(R,v)})}),h=a.begin(y=>u((async()=>{if(l!==void 0)if(r){let R=await d(()=>y.unsafe(`${l.sql}; ${Jo}`).simple());R.at(-1)?.[0]?.palgres_commit_kept!==!0&&(c=!0),l.opened?.(Xt(R.slice(0,-1)))}else{let R=Xt(await d(()=>y.unsafe(l.sql).simple()));l.opened?.(R)}w=!0;let T=await p(g(y));if(c){let[R]=await d(()=>y.unsafe("COMMIT; BEGIN").simple());if(R?.command==="ROLLBACK")throw new Error("palgres: COMMIT was answered with ROLLBACK \u2014 nothing the transaction did was kept")}return T})(),()=>{}));h.catch(y=>{ue(y)==="lost"&&(f??={error:y})});try{return await h}catch(y){let T=ue(y);if(w||T===void 0||m>=(T==="lost"?yn:bn))throw y}}},s=o(e),i=o(n);return{unsafe:(a,p)=>s(l=>Promise.resolve(l.unsafe(a,p))),begin:s,cancelBackend:Jn({unsafe:(a,p)=>i(l=>Promise.resolve(l.unsafe(a,p)))})}}var lr=(e,n)=>({embed:e,serving:new Map,said:new Map,log:n}),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 ${Se}.generations g ON g.table_key = $1 AND g.status = 'active' ORDER BY g.gen DESC LIMIT 1`;function et(e){if(!(e===void 0||e.gen===null||e.gen===void 0||typeof e.types!="string"))return{gen:Number(e.gen),model:String(e.model),dimensions:Number(e.dimensions),metric:e.metric,types:e.types}}var Yo=["hybrid","text","vector"],Yn=(e,n)=>ge(new we({fields:[{field:e,message:n}]},`search: ${e} ${n}`));function cr(e,n,t){if(t===null||typeof t!="object")throw new TypeError(`search(${e}): its options are { limit, where, mode, minScore }`);if(typeof n!="string")throw new TypeError(`search(${e}): the query is the text searched for, not ${n===null?"null":typeof n}`);let r=n.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"||!Yo.includes(o))throw new TypeError(`search(${e}): 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(e,n){if(!Array.isArray(e)||e.length!==n)throw new Error(`the embedder answered ${Array.isArray(e)?`a vector of ${e.length} dimensions`:"no vector"} where ${n} were asked for`);for(let t of e)if(typeof t!="number"||!Number.isFinite(t))throw new Error("the embedder answered a vector that holds what is not a number");return`[${e.join(",")}]`}async function ur(e,n,t){let r=await e({texts:[n],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 dr=100,Xo="2 minutes",Zo=8,es=256,ns=25e4,fr=1e3,ts=15e3,rs=3e4,os=5e3,re=Se,Tn=e=>(e instanceof Error?e.message:String(e)).slice(0,500);function ss(e){let{sql:n,embed:t,log:r}=e,o={...We,...e.roles},s=`SELECT set_config('role', ${Q(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=>n.begin(S=>E(async(b,O=[])=>await S.unsafe(b,O.map(De))),{sql:s}),a=(E,S)=>i(b=>b(E,S)),p=!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 '${Xo}' 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(S=>S.map(b=>({id:String(b.id),table_key:String(b.table_key),gen:Number(b.gen),row_id:String(b.row_id),enqueued_at:String(b.enqueued_at)})));async function m(E,S){let[b]=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,
6
+ AND usename = session_user AND datname = current_database() AND backend_type = 'client backend'`,[String(n),t,r])}}var ye=class extends Error{constructor(n){super(`palgres: the driver ${n}. 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(e){let t=(await e.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 ye("re-encodes text bound for a jsonb parameter (JSON text became a JSON string)");if(t.b!==!0)throw new ye("changes the text bound for a boolean ('true' was not read as true)");if(t.t!==!0)throw new ye("changes the text bound for a timestamp (its microseconds did not arrive)");if(Number(t.a)!==2)throw new ye("changes the text bound for an array (the literal {1,2} did not arrive)");if(t.y!==!0)throw new ye("changes the text bound for a bytea");if((await e.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 ye("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")}var Vo=/\bdeallocate\b/i,Ho="SELECT EXISTS (SELECT FROM pg_catalog.pg_prepared_statements WHERE statement = 'commit' AND NOT from_sql) AS palgres_commit_kept",Yt=()=>new Promise(()=>{});function zo(e,n){let t=a=>Promise.resolve(a).then(p=>p),r=e.options?.prepare!==!1,o=a=>async(p,l)=>{for(let m=1;;m++){let w=!1,c=!1,f,d=y=>f!==void 0?Promise.reject(f.error):t(y()).catch(E=>{throw ce(E)==="lost"&&(f??={error:E}),E}),u=(y,E)=>y.then(R=>f===void 0?R:(E(f.error),Yt()),R=>f===void 0?Promise.reject(R):(E(R),Yt())),g=y=>({unsafe:(E,R,v)=>(r&&Vo.test(E)&&(c=!0),v?.prepared===void 0?d(()=>y.unsafe(E,R??[])):Xt(v.prepared,P=>d(()=>y.unsafe(P).simple()))),savepoint:E=>new Promise((R,v)=>{if(f!==void 0)return v(f.error);y.savepoint(P=>u(E(g(P)),v)).then(R,v)})}),h=a.begin(y=>u((async()=>{if(l!==void 0)if(r){let R=await d(()=>y.unsafe(`${l.sql}; ${Ho}`).simple());R.at(-1)?.[0]?.palgres_commit_kept!==!0&&(c=!0),l.opened?.(Qt(R.slice(0,-1)))}else{let R=Qt(await d(()=>y.unsafe(l.sql).simple()));l.opened?.(R)}w=!0;let E=await p(g(y));if(c){let[R]=await d(()=>y.unsafe("COMMIT; BEGIN").simple());if(R?.command==="ROLLBACK")throw new Error("palgres: COMMIT was answered with ROLLBACK \u2014 nothing the transaction did was kept")}return E})(),()=>{}));h.catch(y=>{ce(y)==="lost"&&(f??={error:y})});try{return await h}catch(y){let E=ce(y);if(w||E===void 0||m>=(E==="lost"?yn:bn))throw y}}},s=o(e),i=o(n);return{unsafe:(a,p)=>s(l=>Promise.resolve(l.unsafe(a,p))),begin:s,cancelBackend:Qn({unsafe:(a,p)=>i(l=>Promise.resolve(l.unsafe(a,p)))})}}var sr=(e,n)=>({embed:e,serving:new Map,said:new Map,log:n}),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(e){if(!(e===void 0||e.gen===null||e.gen===void 0||typeof e.types!="string"))return{gen:Number(e.gen),model:String(e.model),dimensions:Number(e.dimensions),metric:e.metric,types:e.types}}var Jo=["hybrid","text","vector"],Yn=(e,n)=>pe(new ge({fields:[{field:e,message:n}]},`search: ${e} ${n}`));function ir(e,n,t){if(t===null||typeof t!="object")throw new TypeError(`search(${e}): its options are { limit, where, mode, minScore }`);if(typeof n!="string")throw new TypeError(`search(${e}): the query is the text searched for, not ${n===null?"null":typeof n}`);let r=n.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"||!Jo.includes(o))throw new TypeError(`search(${e}): 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(e,n){if(!Array.isArray(e)||e.length!==n)throw new Error(`the embedder answered ${Array.isArray(e)?`a vector of ${e.length} dimensions`:"no vector"} where ${n} were asked for`);for(let t of e)if(typeof t!="number"||!Number.isFinite(t))throw new Error("the embedder answered a vector that holds what is not a number");return`[${e.join(",")}]`}async function ar(e,n,t){let r=await e({texts:[n],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 lr=100,Qo="2 minutes",Go=8,Yo=256,Xo=25e4,cr=1e3,Zo=15e3,es=3e4,ns=5e3,re=$e,En=e=>(e instanceof Error?e.message:String(e)).slice(0,500);function ts(e){let{sql:n,embed:t,log:r}=e,o={...We,...e.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=T=>n.begin($=>T(async(b,O=[])=>await $.unsafe(b,O.map(De))),{sql:s}),a=(T,$)=>i(b=>b(T,$)),p=!0,l=T=>a(`WITH due AS (SELECT id FROM ${re}.queue WHERE next_attempt_at <= now() ORDER BY enqueued_at, id LIMIT ${T} FOR UPDATE SKIP LOCKED)
7
+ UPDATE ${re}.queue q SET next_attempt_at = now() + interval '${Qo}' 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(b=>({id:String(b.id),table_key:String(b.table_key),gen:Number(b.gen),row_id:String(b.row_id),enqueued_at:String(b.enqueued_at)})));async function m(T,$){let[b]=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'`,[E,S]);if(b===void 0||typeof b.types!="string")return;let O=Number(b.dimensions),D=b.metric;return{model:String(b.model),dimensions:O,metric:D,from:b.from_columns.map(String),parent:String(b.parent),pk:le(String(b.pk)),pkType:String(b.pk_type),vectors:`${re}.${le(Ke(E,S))}`,vectorType:`${le(b.types)}.${an(O,D).type}`}}let w="unnest($1::bigint[], $2::timestamptz[]) AS c(id, at) WHERE q.id = c.id AND q.enqueued_at = c.at",c=E=>[E.map(S=>S.id),E.map(S=>S.enqueued_at)],f=E=>a(`DELETE FROM ${re}.queue q USING ${w}`,c(E)),d=async(E,S)=>{E.length!==0&&(r?.(`palgres: search of ${E[0].table_key}: ${E.length} row(s) not embedded, tried again later (${Tn(S)})`),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 ${w}`,[...c(E),Tn(S)]))};async function u(E,S,b,O){let D=[],q=[],C=0;for(let $ of S){let M=Math.ceil($.text.length/4);q.length>0&&(q.length>=es||C+M>ns)&&(D.push(q),q=[],C=0),q.push($),C+=M}q.length>0&&D.push(q);let _=($,M)=>(O.failed+=$.length,d($.map(I=>I.row),M)),N=async $=>{if($.length===0)return;let M=Math.ceil($.length/2);await k($.slice(0,M)),M<$.length&&await k($.slice(M))},k=async $=>{if(O.down)return _($,new Error("the embedder is not answering"));let M,I;try{let L=await t({texts:$.map(j=>j.text),model:E.model,dimensions:E.dimensions,purpose:"document"});if(L===null||typeof L!="object"||!Array.isArray(L.vectors)||L.vectors.length!==$.length)throw new Error(`the embedder answered ${Array.isArray(L?.vectors)?L.vectors.length:"no"} vector(s) for ${$.length} text(s)`);M=L.vectors.map(j=>nt(j,E.dimensions)),I=typeof L.model=="string"&&L.model!==""?L.model:E.model}catch(L){return $.length===1?_($,L):O.answered?N($):(await k([$[0]]),await k([$[$.length-1]]),O.answered?N($.slice(1,-1)):(O.down=!0,_($.slice(1,-1),L)))}O.answered=!0,await b($,I,M)};for(let $ of D)await k($)}async function g(E,S){let b=await m(E[0].table_key,E[0].gen);if(b===void 0)return await f(E),0;let O=new Map((await a(`SELECT p.${b.pk}::text AS id, ${Ln(b.from,"p")} AS text FROM ${b.parent} p WHERE p.${b.pk} = ANY($1::${b.pkType}[])`,[E.map(N=>N.row_id)])).map(N=>[String(N.id),String(N.text??"")])),D=E.filter(N=>!O.has(N.row_id));D.length>0&&await f(D);let q=E.filter(N=>O.has(N.row_id)&&O.get(N.row_id).trim()==="");q.length>0&&await a(`WITH done AS (DELETE FROM ${re}.queue q USING ${w} RETURNING q.row_id) DELETE FROM ${b.vectors} v USING done d WHERE v.id = d.row_id::${b.pkType}`,c(q));let C=E.filter(N=>(O.get(N.row_id)??"").trim()!=="").map(N=>({row:N,text:O.get(N.row_id).slice(0,Xn)})),_=0;return await u(b,C,async(N,k,$)=>{try{let[M]=await a(`WITH done AS (DELETE FROM ${re}.queue q USING ${w} RETURNING q.row_id),
14
+ WHERE g.table_key = $1 AND g.gen = $2::integer AND g.status <> 'retired'`,[T,$]);if(b===void 0||typeof b.types!="string")return;let O=Number(b.dimensions),D=b.metric;return{model:String(b.model),dimensions:O,metric:D,from:b.from_columns.map(String),parent:String(b.parent),pk:ae(String(b.pk)),pkType:String(b.pk_type),vectors:`${re}.${ae(Ke(T,$))}`,vectorType:`${ae(b.types)}.${an(O,D).type}`}}let w="unnest($1::bigint[], $2::timestamptz[]) AS c(id, at) WHERE q.id = c.id AND q.enqueued_at = c.at",c=T=>[T.map($=>$.id),T.map($=>$.enqueued_at)],f=T=>a(`DELETE FROM ${re}.queue q USING ${w}`,c(T)),d=async(T,$)=>{T.length!==0&&(r?.(`palgres: search of ${T[0].table_key}: ${T.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 >= ${Go} THEN 'infinity'::timestamptz ELSE now() + interval '1 minute' * power(4, least(q.attempts, 4)) END
16
+ FROM ${w}`,[...c(T),En($)]))};async function u(T,$,b,O){let D=[],C=[],q=0;for(let S of $){let M=Math.ceil(S.text.length/4);C.length>0&&(C.length>=Yo||q+M>Xo)&&(D.push(C),C=[],q=0),C.push(S),q+=M}C.length>0&&D.push(C);let _=(S,M)=>(O.failed+=S.length,d(S.map(L=>L.row),M)),N=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(O.down)return _(S,new Error("the embedder is not answering"));let M,L;try{let I=await t({texts:S.map(j=>j.text),model:T.model,dimensions:T.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(j=>nt(j,T.dimensions)),L=typeof I.model=="string"&&I.model!==""?I.model:T.model}catch(I){return S.length===1?_(S,I):O.answered?N(S):(await k([S[0]]),await k([S[S.length-1]]),O.answered?N(S.slice(1,-1)):(O.down=!0,_(S.slice(1,-1),I)))}O.answered=!0,await b(S,L,M)};for(let S of D)await k(S)}async function g(T,$){let b=await m(T[0].table_key,T[0].gen);if(b===void 0)return await f(T),0;let O=new Map((await a(`SELECT p.${b.pk}::text AS id, ${In(b.from,"p")} AS text FROM ${b.parent} p WHERE p.${b.pk} = ANY($1::${b.pkType}[])`,[T.map(N=>N.row_id)])).map(N=>[String(N.id),String(N.text??"")])),D=T.filter(N=>!O.has(N.row_id));D.length>0&&await f(D);let C=T.filter(N=>O.has(N.row_id)&&O.get(N.row_id).trim()==="");C.length>0&&await a(`WITH done AS (DELETE FROM ${re}.queue q USING ${w} RETURNING q.row_id) DELETE FROM ${b.vectors} v USING done d WHERE v.id = d.row_id::${b.pkType}`,c(C));let q=T.filter(N=>(O.get(N.row_id)??"").trim()!=="").map(N=>({row:N,text:O.get(N.row_id).slice(0,Xn)})),_=0;return await u(b,q,async(N,k,S)=>{try{let[M]=await a(`WITH done AS (DELETE FROM ${re}.queue q USING ${w} RETURNING q.row_id),
17
17
  there AS (SELECT p.${b.pk}::text AS id FROM ${b.parent} p WHERE p.${b.pk} = ANY($3::${b.pkType}[]) FOR KEY SHARE),
18
18
  written AS (
19
19
  INSERT INTO ${b.vectors} (id, embedding, model)
@@ -21,15 +21,15 @@ import{a as Ae,j as un,k as dn}from"./chunks/LRDQMK6O.js";import{A as Io,B as Lo
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(N.map(I=>I.row)),N.map(I=>I.row.row_id),$,k,N.map(I=>I.row.row_id)]);_+=Number(M?.n??0)}catch(M){S.failed+=N.length,await d(N.map(I=>I.row),M)}},S),_}async function h(E){let S=0,b=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 O of b){let D=String(O.table_key),q=Number(O.gen),C=await m(D,q);if(C===void 0)continue;let[_]=await a(`WITH missing AS (
24
+ SELECT count(*)::int AS n FROM written`,[...c(N.map(L=>L.row)),N.map(L=>L.row.row_id),S,k,N.map(L=>L.row.row_id)]);_+=Number(M?.n??0)}catch(M){$.failed+=N.length,await d(N.map(L=>L.row),M)}},$),_}async function h(T){let $=0,b=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 O of b){let D=String(O.table_key),C=Number(O.gen),q=await m(D,C);if(q===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.${C.pk}::text FROM ${C.parent} p
27
- WHERE btrim(${Ln(C.from,"p")}) <> '' AND NOT EXISTS (SELECT 1 FROM ${C.vectors} v WHERE v.id = p.${C.pk})
26
+ SELECT $1::text, $2::integer, p.${q.pk}::text FROM ${q.parent} p
27
+ WHERE btrim(${In(q.from,"p")}) <> '' AND NOT EXISTS (SELECT 1 FROM ${q.vectors} v WHERE v.id = p.${q.pk})
28
28
  ON CONFLICT ON CONSTRAINT queue_one_pending DO NOTHING RETURNING 1)
29
- SELECT count(*)::int AS n FROM missing`,[D,q]);if(Number(_?.n??0)>0){S+=Number(_.n);continue}let[N]=await a(`SELECT ${re}.promote($1) AS gen`,[D]);N?.gen!==null&&N?.gen!==void 0&&(E.push(D),r?.(`palgres: search of ${D}: every row is embedded again \u2014 generation ${String(N.gen)} serves`))}return S}async function y(E={}){let S=E.timeoutMs===void 0?1/0:Date.now()+E.timeoutMs,b=[],O=0,D=()=>Date.now()<S&&(E.max===void 0||O<E.max)&&!(E.whileRunning===!0&&p);for(;;){for(;D();){let q=await l(E.max===void 0?dr:Math.min(dr,E.max-O));if(q.length===0)break;let C=new Map;for(let k of q){let $=`${k.table_key}\0${k.gen}`,M=C.get($);M?M.push(k):C.set($,[k])}let _={answered:!1,down:!1,failed:0},N=0;for(let k of C.values())try{N+=await g(k,_)}catch($){_.failed+=k.length,await d(k,$).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 T,R,v=!1,P,A=()=>{v=!0,R?.()};return{drain:E=>y(E),kick:A,start(){T===void 0&&(p=!1,P=ln.listen(A),T=(async()=>{await a(`UPDATE ${re}.queue SET attempts = 0, next_attempt_at = now(), last_error = NULL WHERE next_attempt_at = 'infinity'`).catch(S=>r?.(`palgres: the search worker could not read its queue (${Tn(S)})`));let E=fr;for(;!p;){v=!1;let S=!1;try{let b=await y({timeoutMs:rs,whileRunning:!0});S=b.embedded>0||b.promoted.length>0}catch(b){r?.(`palgres: the search worker could not embed (${Tn(b)}); it looks again`)}E=S?fr:Math.min(ts,E*2),!(p||v)&&(await new Promise(b=>{let O=setTimeout(b,E);O.unref?.(),R=()=>{clearTimeout(O),b()}}),R=void 0)}})())},async stop(){if(T===void 0)return;p=!0,P?.(),P=void 0,R?.();let E=T;T=void 0;let S;await Promise.race([E,new Promise(b=>S=setTimeout(b,os))]),clearTimeout(S)}}}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 he({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 he({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 he({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()})}},mr=new WeakMap;function pr(e,n={concurrency:10}){let t=mr.get(e);if(!t)return t=new tt(n),mr.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 is(e){return e.endsWith("_id")?e.slice(0,-3):e}function gr(e){return e.direction==="forward"?`the foreign key "${e.table}.${e.column}"`:`the reverse of "${e.table}.${e.column}"`}function wr(e){return e.direction==="reverse"?'references(() => \u2026, { reverseAs: "\u2026" })':e.def.selfRefColumn!==void 0?'selfReferences("\u2026", { as: "\u2026" })':'references(() => \u2026, { as: "\u2026" })'}function Qe(e){let n=new Map,t=new Map;for(let o of e)for(let s of Object.values(o.tables)){let i=se(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=wr(l),w=wr(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}": ${gr(l)} and ${gr(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=se(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??is(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 as(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 as({columns:n,primaryKey:e.primaryKey,unique:e.unique})}function hr(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 Rr(e){return e.type==="sql"&&typeof e.sqlType=="string"?`sql:${e.sqlType}`:e.type}var En=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=Qe(n);for(let s of n)for(let i of Object.values(s.tables)){let a=se(s.name,i.name);if(i.ignored){this.ignoredTables.add(a);continue}this.tables.set(a,cs(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??=ls(_t([...this.schemas])),this.deferrals.get(`${n.schema}.${n.name}`)??null}};function ls(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 cs(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=qn(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=>us(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 us(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 yr(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 br(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 Tr(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 $e(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 yr(n);case"date":return br(n);case"bigint[]":case"numeric[]":case"uuid[]":case"enum[]":return`${n}::text[]`;case"date[]":return Tr(n,br);case"timestamp[]":return Tr(n,yr)}return null}function Er(e){return e==="jsonb"||e==="sql:json"}import{createCipheriv as ds,createDecipheriv as fs,createHash as Sr,randomBytes as ms}from"node:crypto";var ie=(e,n="page")=>new we({fields:[{field:n,message:e}]},e);function $r(e){return Sr("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 Sr("sha256").update(JSON.stringify(n(e))).digest("base64url")}function kr(e,n){let{iat:t,exp:r,nbf:o,jti:s,...i}=n;return rt({role:e,authorization:i})}function vr(e,n,t){let r=ms(12),o=ds("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 ie("page cursor values are too large; choose shorter ordering columns");return i}function xr(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=fs("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 ie("Invalid cursor for this query or identity; restart from the first page","cursor")}}var ps=new Set(["uuid","text","integer","bigint","boolean","timestamp","numeric","enum"]);function Or(e,n,t){let r=t;if("limit"in r||"offset"in r)throw ie("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 ie("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 ie("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 ie("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 ie(`page order column ${m?.column} is not declared`);if(!ps.has(w.type??""))throw ie(`page cannot order ${m.column}: ${w.type??"unknown"} is not a supported scalar column`);if(a.has(m.column))throw ie(`page order column ${m.column} is repeated`);if(m.direction!==void 0&&m.direction!=="asc"&&m.direction!=="desc")throw ie("page direction must be asc or desc");if(m.nulls!==void 0&&m.nulls!=="first"&&m.nulls!=="last")throw ie("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 gs}from"node:crypto";var ws=16,hs=2,Ar="force_custom_plan",ys=16384,bs=256,Ts=2e3,Rs=256,Es=/^\s*(?:\(\s*)*(?:select|insert|update|delete|merge|values|with|table)\b/i,Ss=/\bdeallocate\b/i,$s=/'\s*(?:now|today|tomorrow|yesterday)\s*'/i;function Pr(e){return Ss.test(e)}function ks(e,n){if(e.length>ys||!Es.test(e)||$s.test(e))return;let t=n?e:e.replace(/;\s*$/,"");if(!t.includes(";")&&!(!n&&t.includes("*")))return t}function Nr(e,n,t){if(!(n.length===0||n.length>bs)){for(let r of n)if(r!==null&&(typeof r!="string"||r.includes("\0")))return;return ks(e,t)}}var vs=0,xs=0,Dr=gs(5).toString("hex"),Sn=class{texts=new Map;sessions=new Map;mark(){return`${Dr}_${++xs}`}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>Rs&&this.sessions.delete(this.sessions.keys().next().value),t}count(n,t,r){Nr(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>Ts&&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=Nr(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<hs||this.size>=ws)return;i=`palgres_${Dr}_${++vs}`,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":Q(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=ce(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 oo}from"node:async_hooks";var Os=5e3,$n=()=>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(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($n()),n))}check(){this.deadline!==void 0&&performance.now()>=this.deadline&&!this.signal.aborted&&this.controller.abort($n()),this.signal.throwIfAborted()}checkDeadline(){if(!(this.deadline===void 0||performance.now()<this.deadline))throw this.signal.aborted||this.controller.abort($n()),$n()}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+Os-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 As}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:As("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`,[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(`
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 Ir=new WeakMap,Lr=new WeakSet;function J(e){let n=t=>`$${e.push(t)}`;return Ir.set(n,e),n}var lt=e=>Lr.has(e);var Mr=e=>`'${e.replace(/'/g,"''")}'`;function de(e,n){let t=e.columns.get(n);return t?Rr(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 fe(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=de(e,n);return s===null||o===null||o===void 0?o:s.endsWith("[]")&&Array.isArray(o)?ze(o):Er(s)?JSON.stringify(o):o}function Br(e,n){return n.flatMap(t=>{let r=e.encrypted.get(t)?.lookup;return r?[t,r]:[t]})}function Te(e,n){return Br(e,n).map(x).join(", ")}function Ps(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 Kr(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 ${Cn} 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 jr(e,n,t,r,o){let s=e.encrypted.get(n);return s===void 0?null:Kr(e,n,s,t,r,o)}function Wr(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),Kr(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 Fr(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 Ie(e,n,t){for(let r of t)ee(e,r,n,"column");Fr(e,n,t)}function ct(e,n,t,r){return Ue(n,e.key,[t],r),zn(n,e.key,[t],r),fe(e,t,r[t])}function ut(e,n,t){let r=`${t?`${x(t)}.`:""}${x(n)}`;return $e(de(e,n),r)??r}function Ur(e,n,t){let r=ut(e,n,t);return $e(de(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=>Ur(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"),Ur(e,r,"t"))).join(", ")}function Vr(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 Ns(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 Ce={gt:">",gte:">=",lt:"<",lte:"<=",neq:"<>"},Ds=[["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(${Ds.filter(([s])=>r.span[s]!==void 0).map(([s,i,a])=>`${i} => ${n(r.span[s])}::${a}`).join(", ")}))`}var qr=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(qr,r))return qr[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 Cr=e=>Ve(e);function _r(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 Hr(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 ge(new we({fields:[{field:n,message:t}]},`${e}: ${n} ${t}`))}function qs(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(qs(t,a),Kt(o,n.key,t),Ne(t)){let{text:l,values:m}=t.$sql,w=Ir.get(r);if(w===void 0)throw new Error("palgres: an sqlFragment was compiled outside binder()");if(Lr.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 T=vn(e,n,h,r,o,s,i,`${a}.${l}[${y}]`);if(T.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`(${T.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(S=>S.name===g);if(y===void 0){let S=n.relations.map(b=>b.name).sort();throw new Error(`${o}(${n.key}): there is no relation has.${g}`+(S.length>0?` (known: ${S.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[T,R]=Hr(e,n,y,o);if(T===null||R===null)throw new Error(`${o}(${n.key}): has.${g} cannot be built \u2014 "${T===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}`),E=`${P}.${x(R)} = ${x(s)}.${x(T)}`;p.push(`EXISTS (SELECT 1 FROM ${v.sql} ${P} WHERE ${E}${A===""?"":` AND ${A}`})`)}continue}ee(n,l,o,"where column");let w=n.encrypted.get(l);if(w!==void 0){p.push(Cs(n,l,w,m,r,o,s,a));continue}let c=`${x(s)}.${x(l)}`,f=de(n,l)?.endsWith("[]")===!0,d=u=>r(fe(n,l,u));if(ye(m)){p.push(`${c} = ${_r(n,m,o,s)}`);continue}if(pn(m)){p.push(`${c} = ${_e(Cr(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"),T=u==="startsWith"?`${y}%`:u==="endsWith"?`%${y}`:`%${y}%`;p.push(`${c} ${u==="icontains"?"ILIKE":"LIKE"} ${r(T)}`);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(ye))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 Ce))throw new Error(`${o}(${n.key}): where.${l}.${u} cannot take now() \u2014 for equality write it bare: { ${l}: now() }`);p.push(`${c} ${Ce[u]} ${_e(Cr(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(ye(g)){if(!(u in Ce))throw new Error(`${o}(${n.key}): where.${l}.${u} cannot take col() \u2014 for equality write it bare: { ${l}: col("\u2026") }`);p.push(`${c} ${Ce[u]} ${_r(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 Ce){if(g===null&&u==="neq"){p.push(`${c} IS NOT NULL`);continue}p.push(`${c} ${Ce[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 Cs(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 }))"))};(ye(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 T=u.map(R=>o(R));return`(${y} OR ${u.length===1?`${p} = ${T[0]}`:`${p} IN (${T.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 me(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 Le(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=Br(e,n),i=Ps(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 Fr(e,o,n),n.map(s=>{let i=e.encrypted.get(s);if(i!==void 0){let[p,l]=Wr(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 Wr(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 _s=new Set(["integer","bigint","numeric"]);function zr(e){return e!==null&&_s.has(e)}function Qr(e,n,t,r){xn(e,t,"aggregate",n);let o=`t.${x(t)}`,s=de(e,t);if(n==="sum"||n==="avg")return`${n}(${o})::text AS ${x(r)}`;let i=s!==null&&!s.endsWith("[]")?$e(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 Is(e,n,t,r=[]){return`json_build_object(${[...n.map(s=>{let i=de(e,s),a=`${t}.${x(s)}`,p=i==="numeric"||i==="bigint"?`${a}::text`:$e(i,a)??a;return`${Mr(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]=Hr(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,T=`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,T,i+1,a),A=P.joins.length?` ${P.joins.join(" ")}`:"",E=Is(g,R,T,P.jsonPairs),S=h.where!==void 0&&h.where!==null?Ge(e,g,h.where,r,o,T,y,`with.${w}.where`):"",b=`${T}.${x(u)} = ${x(s)}.${x(d)}`,O=S===""?b:`${b} AND ${S}`,D=h.limit;at(D,o);let q=f.kind==="many"?D:Math.min(1,D??1),C=Vr(g,h.orderBy,o,T)+at(q,o),_=`wj${y}`;f.kind==="many"?l.push(`LEFT JOIN LATERAL (SELECT coalesce(json_agg(x.o), '[]'::json) AS d FROM (SELECT ${E} AS o FROM ${g.sql} ${T}${A} WHERE ${O}${C}) x) ${x(_)} ON true`):l.push(`LEFT JOIN LATERAL (SELECT ${E} AS d FROM ${g.sql} ${T}${A} WHERE ${O}${C}) ${x(_)} ON true`),p.push(`${x(_)}."d" AS ${x(w)}`),m.push(`${Mr(w)}, ${x(_)}."d"`)}return{select:p,joins:l,jsonPairs:m}}function pt(e,n,t,r){let o=[],s=J(o),i=me(e,n,t,s,"findMany").sql,a=Vr(n,r.orderBy,"findMany"),p=at(r.limit),l=Ns(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=J(o),i=x(n.singleKey),a=me(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 ${Ls(r.limit)}`,params:o}}function Ls(e){if(!Number.isInteger(e)||e<1)throw new Error(`search: limit must be a positive integer (got ${String(e)})`);return e}function Jr(e){return e instanceof Date?e.toISOString():Array.isArray(e)?e.map(Jr):e}function wt(e){if(e===null||typeof e!="object")return e;let n={};for(let[t,r]of Object.entries(e))n[t]=Jr(r);return n}function Ms(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 Je(e,n,t,r){let o=t.map(s=>Ms(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]=Je(e,p,m,a):m&&typeof m=="object"&&(l[s.name]=Je(e,p,[m],a)[0])}}return Pe(o)}var Bs={inline:!0},ht={inline:!0,read:!0},Ks=e=>ce(e)===Z.uniqueViolation||ve.is(e);function Gr(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 js=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:Bs),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)=>Je(t,c,f,d),m=(c,f)=>Je(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`);Ie(d,"insert",u);let g=[],h=Xe(d,u,f,J(g),"insert"),y=await s(`INSERT INTO ${d.sql} (${Te(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(Vt(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 E=g.filter(b=>!(b in f[A])),S=Object.keys(f[A]).filter(b=>!g.includes(b));if(E.length>0||S.length>0)throw new Error(`insertMany(${c}): row ${A} does not have the first row's columns`+(E.length>0?` (missing: ${E.join(", ")})`:"")+(S.length>0?` (extra: ${S.join(", ")})`:"")+". One statement shares the column list: write null for a missing value, or insert differently shaped rows in calls of their own.")}Ie(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=J(h),T=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} (${Te(u,g)}) VALUES ${T.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=J(h),T=d.map(R=>y(fe(u,u.singleKey,R))).join(", ");await s(`SELECT t.${g} FROM ${u.sql} t WHERE t.${g} IN (${T}) 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=me(t,g,f,J(h),"lockRowsWhere");Le(y,"lockRowsWhere");let T=x(g.singleKey);await s(`SELECT t.${T} FROM ${g.sql} t WHERE true${y.sql} ORDER BY t.${T} ${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},T=Object.keys(y);Ie(u,"claim",T);let R=await e();try{return await R.savepoint(async v=>{let P=[],A=Xe(u,T,y,J(P),"claim"),E=await v.unsafe(`INSERT INTO ${u.sql} (${Te(u,T)}) VALUES (${A}) RETURNING ${H(u)}`,P);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:m(u,E[0])}})}catch(v){if(!Ks(v))throw v;let P=[],A=J(P),E=Ge(t,u,f,A,"claim"),S=await s(`SELECT ${H(u,"t")} FROM ${u.sql} t WHERE ${E} LIMIT 1`,P);if(!S[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,S[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`);Ie(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=[],T=Xe(u,h,f,J(y),"put"),R=await s(`INSERT INTO ${u.sql} (${Te(u,h)}) VALUES (${T}) ${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=J(h),T=mt(u,g,d,y,"update"),R=await s(`UPDATE ${u.sql} SET ${T} WHERE "id" = ${y(fe(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=[fe(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=[],T=J(y),R=mt(g,h,d,T,"updateMany"),v=me(t,g,f,T,"updateMany");Le(v,"updateMany");let P=v.sql,A=g.singleKey,E=u?.returning!==!1,S=A===null||Gr(f,A),b=E?`RETURNING ${H(g,"t")}`:"RETURNING 1",O=S?`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=S?"":`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)`,q=E?`${D} ${O}`.trim():S?`WITH upd AS (${O}) SELECT count(*)::int AS n FROM upd`:`${D}, upd AS (${O}) SELECT count(*)::int AS n FROM upd`,C=await s(q,y);return E?l(g,C):Number(C[0]?.n??0)},async deleteMany(c,f){let d=r(c,"deleteMany"),u=[],g=me(t,d,f,J(u),"deleteMany");return Le(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=J(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")&&!zr(de(d,O)))throw new Error(`aggregate(${c}): ${b}("${O}") on a column that is not numeric \u2014 "${O}" is ${de(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(Qr(d,b,O,D))}f.count===!0&&h.push('count(*) AS "_count"');let T=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)||T.length===0))throw new Error(`aggregate(${c}): count is true, or named filters \u2014 { <name>: <filter> }, at least one`);if(T.forEach(([b,O],D)=>{let q=Ge(t,d,O,g,"aggregate","t",0,`count.${b}`);h.push(`count(*) FILTER (WHERE ${q===""?"true":q}) 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=me(t,d,f.where??{},g,"aggregate").sql,A=R.length>0?` GROUP BY ${R.map(b=>`t.${x(b)}`).join(", ")}`:"",E=await i(`SELECT ${[...v,...h].join(", ")} FROM ${d.sql} t WHERE true${P}${A}`,u),S=b=>{let O={};for(let D of R)O[D]=b[`g__${D}`];for(let D of y){let q=O[D.fn]??={};q[D.col]=b[D.alias]??null}return f.count===!0&&(O.count=Number(b._count??0)),T.length>0&&(O.count=Object.fromEntries(T.map(([D],q)=>[D,Number(b[`count__${q}`]??0)]))),O};return R.length>0?E.map(S):S(E[0]??{})},async count(c,f={}){let d=r(c,"count"),u=[],g=me(t,d,f,J(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");hr(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`,[fe(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=cr(c,f,d),y=n.search,T=S=>l(u,S),R=async()=>{let S=gt(t,u,{text:h.text},{where:d.where,limit:h.limit,minScore:h.minScore});return T(await i(S.sql,S.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=S=>(S===void 0?y.serving.delete(g.key):y.serving.set(g.key,S),S),A=y.serving.get(g.key)??P(et((await i(Zn,[g.key]))[0])),E;for(let S=1;;S++){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(E===void 0||E.of.model!==A.model||E.of.dimensions!==A.dimensions)try{E={of:A,literal:await ur(v,h.text,A)}}catch(k){if(h.mode==="vector")throw k;let $=Date.now();return $-(y.said.get(g.key)??-1/0)>=js&&(y.said.set(g.key,$),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(Se)}.${x(Ke(g.key,A.gen))}`,literal:E.literal,type:`${O}.${b.type}`,operator:`OPERATOR(${O}.${b.operator})`}},{where:d.where,limit:h.limit,minScore:h.minScore}),q=await e(),[C,_]=await Promise.all([q.unsafe(Zn,[g.key],ht),q.unsafe(D.sql,D.params,lt(D.params)?void 0:ht)]),N=P(et(C[0]));if(N!==void 0&&N.gen===A.gen)return T(_);if(S>=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:T,backward:R,token:v}=Or(h,u.primaryKey,d),P=[],A=J(P),E=me(t,u,f,A,"page").sql,S=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:E,params:P,select:d.select,with:d.with,identity:n.cursorScope()}),O=v===void 0?void 0:xr(g,b,v,y.length),D=B=>`t.${x(B)}`,q=O?` AND ${ot(y,O,R,A,D)}`:"",C=O?`EXISTS (SELECT 1 FROM ${u.sql} t WHERE true${E} 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`,$=`${_}opposite`,M=y.map((B,X)=>`${_}${X}`),I=y.map((B,X)=>`${de(u,B.column)==="timestamp"?$e("timestamp",D(B.column)):`${D(B.column)}::text`} AS ${x(M[X])}`),L=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 ${[S,...L.select,...I,`row_number() OVER (ORDER BY ${j}) AS ${x(k)}`].join(", ")} FROM ${u.sql} t ${L.joins.join(" ")} WHERE true${E}${q} ORDER BY ${j} LIMIT ${T+1}`,W=`SELECT p.*, b.${x($)} FROM (SELECT ${C} AS ${x($)}) b LEFT JOIN LATERAL (${K}) p ON true ORDER BY p.${x(k)}`,z=await i(W,P),Y=z[0]?.[$]===!0,V=z.filter(B=>B[k]!==null&&B[k]!==void 0),pe=V.length>T;V=V.slice(0,T),R&&V.reverse();let G=B=>B?vr(g,b,M.map(X=>B[X]===null?null:String(B[X]))):null,ae={startCursor:G(V[0]),endCursor:G(V.at(-1)),hasNextPage:R?Y:pe,hasPreviousPage:R?pe:Y};for(let B of V)for(let X of[...M,k,$])delete B[X];return{rows:l(u,V,d.with),pageInfo:ae}},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=Us(t,h,g,u),T=g.op==="delete"?t.deferral(h):null;y!==null&&T!==null&&await d.unsafe(T.defer,[]);let R=y===null?[]:l(h,await d.unsafe(y.sql,y.params));y!==null&&T!==null&&await d.unsafe(T.check,[]);let v={rows:R,rows_affected:R.length};u.push(v),Vs(g,v)}return{results:u}})}};return w}function Ws(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 Tt(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 Ws(e.$ref,n);return t[e.$ref.field]}function An(e,n,t,r,o,s){return Tt(n,`transaction plan (${t})`),jr(e,t,fn(n)?Rt(n,o):n,r,s)??[Fs(e,n,t,r,o)]}function Fs(e,n,t,r,o){if(Tt(n,`transaction plan (${t})`),fn(n))return r(fe(e,t,Rt(n,o)));if(Lt(n)){let s=n.$expr;return s.fn==="now"?_e(s,r):`${x(t)} ${s.fn==="inc"?"+":"-"} ${r(fe(e,t,s.by))}`}return r(fe(e,t,n))}function bt(e,n){if(Tt(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)&&!It(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"&&!ye(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{...me(e,n,i,r,s),resolved:i}}function Us(e,n,t,r){let o=[],s=J(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??{});Ie(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} (${Te(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} (${Te(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} (${Te(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);Le(c,i);let f=n.singleKey;p=f===null||Gr(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);Le(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 Vs(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 Zr}from"node:async_hooks";import{randomUUID as Hs}from"node:crypto";var Pn=new Zr,Yr=()=>({running:new Set}),zs=e=>String(e?.message??e);function Qs(e){return new Oe(`The transaction was rolled back, not committed: a statement in it failed (${zs(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 Xr(e){for(;e.running.size;)await Promise.allSettled([...e.running])}function eo(e,n){let t=n.bind;if(n.lockTimeout!==void 0&&(t+=`, set_config('lock_timeout', ${Q(n.lockTimeout)}, true)`),n.statementTimeout!==void 0&&(t+=`, set_config('statement_timeout', ${Q(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', ${Q(n.prepared.mark())}, false) END AS palgres_marked, pg_catalog.set_config('plan_cache_mode', ${Q(Ar)}, true) AS palgres_plans`);let r=null,o=null,s=null,i=null,a=!1,p=null,l=Yr(),m=!0,w,c=!1,f,d=async()=>!n.control||await n.control.drainCancellation()?!0:(f?.abandon?.(),!1),u,g=!1,h=(q,C,_,N)=>{if(n.prepared===void 0)return _;let k=_?.inline===!0;if(!k&&Pr(q))return u===void 0?g=!0:u.forget(),_;if(u===void 0)return n.prepared.count(q,C,k),_;if(N.refused!==void 0)return _;let $=u.run(q,C,k);return $===void 0?_:{..._,prepared:$}},y=()=>{c=!0},T=()=>{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,E=!1,S=()=>r!==null&&!a&&c&&l.running.size===0&&P.size===0,b=(q,C,_=T,N,k=new Set)=>{let $=()=>{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,I,L){try{$()}catch(W){return Promise.reject(W)}L?.read!==!0&&(m=!1);let j=(I??[]).map(De),K=()=>{let W=q.unsafe(M,j,h(M,j,L,C)),z=Promise.resolve(n.control?n.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),y(),--A===0&&!a&&n.onIdle?.()}),z};return n.trace?n.trace.query(M,K):K()},async savepoint(M){$(),m=!1;let I=Symbol("savepoint"),L=new Set,j=Yr();R??=new Zr,v=I;let K=(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=R.run(I,()=>M(b(W,j,Y,I,L))),pe=await(n.control?n.control.race(V):V);if(await Xr(j),j.refused)throw j.refused.error;return pe}finally{L.size&&await Promise.allSettled([...L]),z=!0}})}finally{v=N}})();P.add(K),k.add(K);try{return await K}finally{P.delete(K),k.delete(K)}}}},O=async()=>(T(),r||(r=new Promise((q,C)=>{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 $=performance.now(),M,I=n.control!==void 0&&e.cancelBackend!==void 0,L=[];if(n.isolation!==void 0||n.readOnly!==void 0){let ne=n.isolation??"read committed";wn({isolation:ne,readOnly:n.readOnly}),L.push(`SET TRANSACTION ISOLATION LEVEL ${ne.toUpperCase()}${n.readOnly===void 0?"":n.readOnly?" READ ONLY":" READ WRITE"}`)}L.push(I?`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=I&&e.cancelOpening!==void 0?`palgres:${Hs()}`: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()),!I)return;if(!Number.isInteger(F?.pid)||typeof F?.started!="string"||typeof F?.xact_started!="string"){let Ee=new Error("Database cancellation cannot identify its own backend");throw l.refused??={error:Ee},Ee}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,pe,G,ae=()=>new he({retryAfter:1},"Database queue deadline exceeded"),B=Y===void 0?void 0:new Promise((ne,F)=>{G=setTimeout(()=>{c||(V=!0,pe?.abandon?.(),F(ae()))},Y)});B?.catch(()=>{});let X=ne=>e.begin(async F=>{M=performance.now(),n.trace?.time("poolMs",$);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 ae();if(j!==void 0&&!K&&n.control.bindBackend(z),Y!==void 0&&!c){pe=F;try{await F.unsafe("SELECT 1")}catch(Ee){throw V?ae():Ee}}clearTimeout(G),n.trace?.time("setupMs",oe),ne(),f=F,q(b(F,l)),await _},{sql:L.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 Ee=ue(oe);if(ne||a||Ee===void 0||F>=(Ee==="lost"?yn:bn))throw oe;n.control?.check()}}finally{clearTimeout(G),M!==void 0&&n.trace?.time("connectionMs",M),k.release()}})().catch(N=>{throw C(N),N}),i.catch(()=>{})}),r.then(void 0,()=>{E=!0,a||n.onIdle?.()}),r)),D=q=>p??=(async()=>{if(a=!0,!r)return;await d(),P.size&&await Promise.allSettled([...P]);let C=n.trace?performance.now():0;s(q),await i?.catch(()=>{}),n.trace?.time("rollbackMs",C),n.trace?.rolledBack()})();return{ensure:O,get opened(){return r!==null},get busy(){return r!==null&&!a&&!E&&(!c||A>0)},get failed(){return E},get releasable(){return S()&&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 Xr(l);try{if(n.trace?.check(),n.control?.checkDeadline(),l.refused)throw Qs(l.refused.error)}catch(C){throw await D(C),C}if(a=!0,!await d()){let C=ge(new te(503,"database_unavailable","The database is temporarily unavailable",{retrySafe:!1},1));throw await D(C),C}let q=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(C){throw n.trace?.commitFailed(),C}finally{n.trace?.time("commitMs",q)}},rollback:D}}var Js="5s",Gs="10s",Ys=new Set(["22P02","22007","22008","22003","22001"]),no="55s",so=1,Xs=1e3,nn=new Set,en,Zs=new oo("palgres.release");function ei(e){nn.add(e),en===void 0&&(en=Zs.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)},so)),en.unref?.())}function ni(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=oo.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<so)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<Xs?!1:(i=!0,n(Math.round(f)),!0)}),l=()=>{a()||(s=performance.now(),ei(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 ti(e){let n=ce(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,ge(e)}function Et(e,n,t){if(typeof e=="object"&&e!==null&&to.has(e))return e;let r=ri(e,n,t);return typeof r=="object"&&r!==null&&to.add(r),r}var to=new WeakSet,Nn=(e,n,t)=>Object.assign(new Error(e,{cause:n}),{sqlstate:t});function ri(e,n,t){if(Oe.is(e))return e;let r=ce(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=ti(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&&Ys.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 oi(e,n,t){let r=o=>({unsafe(s,i,a){let p;try{p=o.unsafe(s,i,a)}catch(l){return Promise.reject(Et(l,n,t))}return Promise.resolve(p).then(Pe,l=>{throw Et(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 Et(i,n,t)}),...e.cancelBackend?{cancelBackend:e.cancelBackend.bind(e)}:{},...e.cancelOpening?{cancelOpening:e.cancelOpening.bind(e)}:{}}}var si=2,ro={anon:"anon",authenticated:"authenticated",service:"service"};function ii(e,n){let t=Object.hasOwn(ro,n.role)?ro[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 St(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 qe(void 0,o),a=ii(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 $;return{cat:n.cat,trace:s,cursorKey:n.cursorKey,cursorScope:()=>$??=kr(k,m),search:n.search,searchable:()=>{c=!0}}},u=d(a),g=d(p),h=new Set,y=null,T=!1,R=0,v=new Set,P=k=>new Promise(($,M)=>{let I=W=>{v.delete(L),clearTimeout(K),k?.removeEventListener("abort",j),W===void 0?$():M(W)},L=()=>I(),j=()=>I(k?.reason??new Error("Database admission cancelled")),K=setTimeout(()=>I(new he({retryAfter:1},"Database queue deadline exceeded")),n.admission.queueTimeoutMs);v.add(L),k?.addEventListener("abort",j,{once:!0}),k?.aborted&&j()}),A=async k=>{let $;for(;;){for(;h.size===0&&y!==null;)await y;let L=h.size>0;if(L){for(;R>=si;)await P(k);R++}let j;try{let K=n.admission.acquire(m,k,{nested:L,returning:!L&&T}).then(W=>{if(L&&h.size===0)return W.release(),null;let z={nested:L,turn:W};return h.add(z),L||(T=!0),z});if(!L){let W=K.then(()=>{},()=>{});y=W,W.then(()=>{y===W&&(y=null)})}j=await K}catch(K){throw L&&E(),K}if(j!==null){$=j;break}E()}let M=!1,I=()=>{if(!M){if(M=!0,h.delete($),$.nested){E();return}for(let L of h){[$.turn,L.turn]=[L.turn,$.turn],L.nested=!1,$.nested=!0,E();return}}};return{queueMs:$.turn.queueMs,leave:I,release:()=>{I(),$.turn.release()},...$.nested&&n.binding.pooled===!0?{openWithin:n.admission.queueTimeoutMs}:{}}},E=()=>{R--;let k=v.values().next().value;k?.()},S=ni(()=>w,r.heldIdle),b=(k,$,M={})=>eo(oi(e,$,$==="user"?l:null),{bind:He(n.binding,k,m),claims:m,admission:n.admission,acquire:A,trace:s,prepared:n.prepared,...M}),O=(k,$)=>async(M,I={})=>{if(wn(I),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 L=gn(I.retry),j=I.signal&&o?AbortSignal.any([I.signal,o]):I.signal??o,K=I.timeoutMs!==void 0||j!==void 0?new qe(I.timeoutMs,j):void 0;try{K?.check();for(let W=0;;W++){K?.check();let z=[I.statementTimeoutMs,K?.remainingMs()].filter(G=>G!==void 0),Y=Symbol("atomic transaction"),V=b(k,$,{scope:Y,isolation:I.isolation,readOnly:I.readOnly,control:K,lockTimeout:`${I.lockTimeoutMs??5e3}ms`,statementTimeout:z.length===0?void 0:`${Math.min(...z)}ms`,onIdle:S.onIdle}),pe=S.atomic(V);try{let G=Ze(()=>V.ensure(),$==="user"?u:g),ae=Pn.run(Y,()=>M(G)),B=await(K?K.race(ae):ae);return await V.commit(),f(),B}catch(G){await V.rollback(G);let ae=xe(G)||Oe.is(G)&&xe(G.cause);if(W>=L||!ae)throw G;s?.retry();let B=new Promise(X=>setTimeout(X,Math.min(100,2**W)));await(K?K.race(B):B)}finally{pe()}}}finally{K?.dispose()}},D=S.surface((k,$)=>b(a,"user",{lockTimeout:Gs,statementTimeout:no,control:i,onIdle:k,acquire:$}),A),q=null,C,_=null,N=()=>{if(_===null){if(w)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,I)=>b(p,"service",{lockTimeout:Js,statementTimeout:no,control:k,onIdle:M,acquire:I}),A);q=$,_=Object.assign(Ze(()=>$.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 q?.rollback(k),k}try{await D.commit()}catch(k){throw await q?.rollback(k),k}await q?.commit(),f(),s?.complete("committed"),i?.dispose(),C?.dispose()}catch(k){throw s?.failed(),k}},async rollback(k){w=!0,await D.rollback(k),await q?.rollback(k),i?.dispose(),C?.dispose(),s?.complete("failed")}}}function ai(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 li(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 io(e){let n=`Pg<${ai(e)}, ${JSON.stringify(li(e))}>`;return e.nullable?`${n} | null`:n}function ci(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 ui(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 ao(e,n,t){let r=Object.entries(e.columns).filter(([,a])=>a._def.ignored!==!0),o=r.map(([a,p])=>`${t} ${tn(a)}: ${io(p._def)};`),s=r.filter(([,a])=>!ui(a._def)).map(([a,p])=>`${t} ${tn(a)}${ci(p._def)?"?":""}: ${io(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 di(e){for(let n of e)for(let t of Object.values(n.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 "${se(n.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 $t="// palbase:env:begin",kt="// palbase:env:end",lo=`/**
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 li(e){for(let n of e)for(let t of Object.values(n.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(n.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",so=`/**
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,10 +46,10 @@ 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 co(e,n,t){di(e);let r=Qe(e),o=f=>Object.values(f.tables).filter(d=>d.ignored!==!0),s=e.find(f=>f.name==="public"),i=e.filter(f=>f.name!=="public"),a=(s?o(s):[]).map(f=>ao(f,r.get(f.name)??[]," ")),p=a.length>0?`
49
+ type Json = string | number | boolean | null | undefined | Json[] | { [k: string]: Json };`;function io(e,n,t){li(e);let r=Je(e),o=f=>Object.values(f.tables).filter(d=>d.ignored!==!0),s=e.find(f=>f.name==="public"),i=e.filter(f=>f.name!=="public"),a=(s?o(s):[]).map(f=>oo(f,r.get(f.name)??[]," ")),p=a.length>0?`
50
50
  ${a.join(`
51
51
  `)}
52
- `:"",l=i.map(f=>{let d=o(f).map(u=>ao(u,r.get(se(f.name,u.name))??[]," "));return` ${tn(f.name)}: {
52
+ `:"",l=i.map(f=>{let d=o(f).map(u=>oo(u,r.get(be(f.name,u.name))??[]," "));return` ${tn(f.name)}: {
53
53
  ${d.join(`
54
54
  `)}
55
55
  };`}),m=l.length>0?`
@@ -61,24 +61,24 @@ ${w}
61
61
  `}}`;return`declare module ${JSON.stringify(n)} {
62
62
  interface Tables {${p}}
63
63
  interface Schemas {${m}}${c}
64
- }`}function fi(e,n={}){let t=n.module??"palbase/backend/env",r=co(e,t,n.access);return`// AUTO-GENERATED by Palgres' makeEnvDts from the app's schema files \u2014 DO NOT EDIT.
64
+ }`}function ci(e,n={}){let t=n.module??"palbase/backend/env",r=io(e,t,n.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
68
68
  // under \`Schemas\` and are reached by name the same way:
69
69
  // \`Database.<schema>.<table>\`.
70
70
 
71
- ${$t}
72
- ${lo}
71
+ ${St}
72
+ ${so}
73
73
 
74
74
  ${r}
75
75
  ${kt}
76
76
 
77
77
  export {};
78
- `}function mi(e,n={}){let t=n.module??"palbase/backend/env";return`${$t}
78
+ `}function ui(e,n={}){let t=n.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
- ${lo}
81
+ ${so}
82
82
 
83
- ${co(e,t,n.access)}
84
- ${kt}`}function pi(e,n){let t=n.tenant,r=n.key??"id",o=(m,w)=>{if(w==null||typeof w!="string"&&typeof w!="number"&&typeof w!="bigint"&&typeof w!="boolean")throw new TypeError(`defineRepository: the ${m} is a string, number, bigint or boolean, not ${w===null?"null":typeof w}`);return w},s=m=>({[t]:o("tenant",m)}),i=(m,w)=>({[t]:o("tenant",m),[r]:o(r,w)}),a=(m,w)=>({...m,[t]:o("tenant",w)}),p=m=>{let w=[t,r].filter(c=>Object.hasOwn(m,c));if(w.length>0)throw new we({fields:w.map(c=>({field:c,message:"cannot be changed through this update"}))},`defineRepository: the patch carries ${w.join(" and ")}, which an update does not change`);return m};class l{async list(w){return e.findMany({where:s(w)})}async find(w,c){return(await e.findMany({where:i(w,c),limit:1}))[0]??null}async insert(w,c){return e.insert(a(c,w))}async update(w,c,f){let d=await this.updateScoped(w,c,f);if(d===null)throw new Bn(`no row ${r}=${String(c)} where ${String(t)}=${String(w)}`);return d}async updateScoped(w,c,f){return(await e.updateMany({where:i(w,c),set:p(f)}))[0]??null}async delete(w,c){await e.deleteMany({where:i(w,c)})}}return l}function gi(e){return Hn({$col:e},"col")}function wi(e,...n){return Hn({$sql:{text:[...e],values:n}},"sql")}async function hi(e,n={}){let t=gn(n.retry),r=0;for(;;)try{return await e()}catch(o){if(r>=t||!xe(o))throw o;r+=1}}function yi(e,n){return{search:(t,r)=>n.search(e,t,r),insert:t=>n.insert(e,t),aggregate:(t=>n.aggregate(e,t)),insertMany:((t,r)=>n.insertMany(e,t,r)),put:t=>n.put(e,t.data,{onConflict:t.onConflict}),update:t=>n.update(e,Wt(e,t.where),t.set),delete:t=>n.delete(e,t),findUnique:(t=>n.findUnique(e,t.where,{select:t.select,lock:t.lock})),findById:t=>n.findById(e,t),page:(t=>{let{where:r,...o}=t??{};return n.page(e,r,o)}),findMany:(t=>{let{where:r,...o}=t??{};return n.findMany(e,r,o)}),updateMany:(t=>n.updateMany(e,t.where,t.set,t.returning===void 0?void 0:{returning:t.returning})),deleteMany:t=>n.deleteMany(e,t.where),count:t=>n.count(e,t?.where)}}function bi(e,n){let t={},r=o=>Object.fromEntries(Object.values(e.tables).map(s=>[s.name,o.table(se(e.name,s.name))]));for(let[o,s]of Object.entries(e.tables))t[o]=yi(se(e.name,s.name),n);return{tables:t,diagnostics:()=>n.diagnostics(),transaction(o){let s=new Ft;return Ut(n,{tables:r(s)},s,o)}}}async function Ol(e){if(e.prepare===!0&&e.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(e.sql);let n=new In;await n.read(i=>e.sql.unsafe(i));let t=e.schemas.some(i=>Object.values(i.tables).some(a=>!a.ignored&&Object.values(a.columns).some(p=>p._def.encrypted!==void 0&&!p._def.ignored))),r=null;if(t||n.size>0){if(e.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(e.fields),setInterval(()=>{n.read(a=>e.sql.unsafe(a)).catch(a=>e.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 En(e.schemas,e.binding,r!==null?{cipher:r,sealing:n}:null),binding:e.binding,roles:{...We,...e.roles},admission:pr(e.sql,e.admission),cursorKey:e.cursorSecret?$r(e.cursorSecret):null,search:lr(e.embed,e.log),prepared:e.prepare===!1||e.binding.pooled===!0?void 0:new Sn},s=e.binding.access!==void 0&&e.binding.accessText!==void 0?Un(e.binding.accessText,e.binding.access):void 0;return{binding:e.binding,request(i,a){let p=St(e.sql,o,i,a);return{database:Ht(p.client,{...s?{access:s}:{},as:i.role}),client:p.client,commit:()=>p.commit(),rollback:l=>p.rollback(l)}},async reseal(i={}){let a=o.cat.fields;if(a===null||!e.binding.direct)return[];let p=[];for(let{table:l,column:m,encrypted:w}of o.cat.encryptedColumns()){if(a.sealing.get(w.address)!==void 0)continue;let c={table:l.sql,column:m,lookup:w.lookup,address:w.address,direction:"seal"},f=null,d=0;do{let u=St(e.sql,o,{role:"service",claims:{}});try{let g=await Ot((h,y)=>u.client.query(h,y),c,a.cipher,f,i.batchSize??500);await u.commit(),d+=g.done,f=g.last}catch(g){throw await u.rollback(g),g}}while(f!==null);p.push({address:w.address,resealed:d})}return p}}}export{No as AccessRefused,Qn as BUN_CLOSE_GRACE_MS,we as BadRequest,Eo as Conflict,We as DEFAULT_ROLES,jn as DeadlockDetected,be as DriverRefused,To as ENGINE_RAISED,kt as ENV_BLOCK_END,$t as ENV_BLOCK_START,bo as HTTP_ERROR_BRAND,te as HttpError,$o as MigrationOpen,So as MigrationRefused,Oo as Migrator,Bn as NotFound,Ho as POSTGRES_JS_TYPES,vo as RowsHeld,Cn as SEALING,_n as SEALING_REFRESH_MS,Se as SEARCH_SCHEMA,po as SETTLE_MS,Z as SQLSTATE,Be as SchemaError,In as Sealing,Kn as SerializationFailure,he as TooManyRequests,Oe as TransactionAborted,_o as TxPlanError,Co as TxRefError,ve as UniqueViolation,hn as VersionNotMigrated,ko as VersionStillConnected,Un as accessNames,Vn as accessTypesBlock,wo as adoptionBaseline,Lo as ago,Wn as applicationName,Wo as bind,He as bindStatement,Qt as binding,Qe as buildRelations,sr as bunDriver,Jn as cancelBackendThrough,ar as cancelOpeningThrough,fo as canonicalType,ir as closeBunPool,gi as col,ue as connectionFailure,je as constraintOf,Ol as createDatabase,ss as createSearchWorker,xo as cutOff,Bo as decrement,pi as defineRepository,Dn as digest,ho as drift,uo as emptySchema,De as encodeParam,ze as encodePgArray,mi as envBlock,qn as fieldAddress,Fo as forgetUser,Uo as forgetUserIn,Mo as increment,or as inlineParams,yo as introspect,ye as isColRef,qo as isData,Ao as isDirect,Ro as isEngineRaised,xe as isRetryable,fi as makeEnvDts,bi as makeTypedDB,Do as markData,ge as markEngineRaised,rn as normalize,Io as now,go as plan,Ko as pooledBinding,Go as postgresJsDriver,Po as pullSchema,zo as renewingBunPool,jo as sayRunning,Fn as searchPath,wi as sqlFragment,ce as sqlstateOf,mo as validate,Ke as vectorTable,Gn as verifyDriver,Mn as versionSchema,hi as withRetry};
83
+ ${io(e,t,n.access)}
84
+ ${kt}`}function di(e,n){let t=n.tenant,r=n.key??"id",o=(m,w)=>{if(w==null||typeof w!="string"&&typeof w!="number"&&typeof w!="bigint"&&typeof w!="boolean")throw new TypeError(`defineRepository: the ${m} is a string, number, bigint or boolean, not ${w===null?"null":typeof w}`);return w},s=m=>({[t]:o("tenant",m)}),i=(m,w)=>({[t]:o("tenant",m),[r]:o(r,w)}),a=(m,w)=>({...m,[t]:o("tenant",w)}),p=m=>{let w=[t,r].filter(c=>Object.hasOwn(m,c));if(w.length>0)throw new ge({fields:w.map(c=>({field:c,message:"cannot be changed through this update"}))},`defineRepository: the patch carries ${w.join(" and ")}, which an update does not change`);return m};class l{async list(w){return e.findMany({where:s(w)})}async find(w,c){return(await e.findMany({where:i(w,c),limit:1}))[0]??null}async insert(w,c){return e.insert(a(c,w))}async update(w,c,f){let d=await this.updateScoped(w,c,f);if(d===null)throw new Bn(`no row ${r}=${String(c)} where ${String(t)}=${String(w)}`);return d}async updateScoped(w,c,f){return(await e.updateMany({where:i(w,c),set:p(f)}))[0]??null}async delete(w,c){await e.deleteMany({where:i(w,c)})}}return l}function fi(e){return Hn({$col:e},"col")}function mi(e,...n){return Hn({$sql:{text:[...e],values:n}},"sql")}async function pi(e,n={}){let t=gn(n.retry),r=0;for(;;)try{return await e()}catch(o){if(r>=t||!xe(o))throw o;r+=1}}async function Rl(e){if(e.prepare===!0&&e.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(e.sql);let n=new Ln;await n.read(i=>e.sql.unsafe(i));let t=e.schemas.some(i=>Object.values(i.tables).some(a=>!a.ignored&&Object.values(a.columns).some(p=>p._def.encrypted!==void 0&&!p._def.ignored))),r=null;if(t||n.size>0){if(e.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(e.fields),setInterval(()=>{n.read(a=>e.sql.unsafe(a)).catch(a=>e.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(e.schemas,e.binding,r!==null?{cipher:r,sealing:n}:null),binding:e.binding,roles:{...We,...e.roles},admission:dr(e.sql,e.admission),cursorKey:e.cursorSecret?Rr(e.cursorSecret):null,search:sr(e.embed,e.log),prepared:e.prepare===!1||e.binding.pooled===!0?void 0:new $n},s=e.binding.access!==void 0&&e.binding.accessText!==void 0?Un(e.binding.accessText,e.binding.access):void 0;return{binding:e.binding,request(i,a){let p=$t(e.sql,o,i,a);return{database:Ft(p.client,{...s?{access:s}:{},as:i.role}),client:p.client,commit:()=>p.commit(),rollback:l=>p.rollback(l)}},async reseal(i={}){let a=o.cat.fields;if(a===null||!e.binding.direct)return[];let p=[];for(let{table:l,column:m,encrypted:w}of o.cat.encryptedColumns()){if(a.sealing.get(w.address)!==void 0)continue;let c={table:l.sql,column:m,lookup:w.lookup,address:w.address,direction:"seal"},f=null,d=0;do{let u=$t(e.sql,o,{role:"service",claims:{}});try{let g=await Ot((h,y)=>u.client.query(h,y),c,a.cipher,f,i.batchSize??500);await u.commit(),d+=g.done,f=g.last}catch(g){throw await u.rollback(g),g}}while(f!==null);p.push({address:w.address,resealed:d})}return p}}}export{Oo as AccessRefused,Jn as BUN_CLOSE_GRACE_MS,ge as BadRequest,bo as Conflict,We as DEFAULT_ROLES,jn as DeadlockDetected,ye as DriverRefused,ho as ENGINE_RAISED,kt as ENV_BLOCK_END,St as ENV_BLOCK_START,wo as HTTP_ERROR_BRAND,te as HttpError,Ro as MigrationOpen,Eo as MigrationRefused,ko as Migrator,Bn as NotFound,Fo as POSTGRES_JS_TYPES,$o as RowsHeld,qn as SEALING,_n as SEALING_REFRESH_MS,$e as SEARCH_SCHEMA,uo as SETTLE_MS,Z as SQLSTATE,Be as SchemaError,Ln as Sealing,Kn as SerializationFailure,we as TooManyRequests,Oe as TransactionAborted,Do as TxPlanError,No as TxRefError,ve as UniqueViolation,hn as VersionNotMigrated,To as VersionStillConnected,Un as accessNames,Vn as accessTypesBlock,mo as adoptionBaseline,qo as ago,Wn as applicationName,Bo as bind,He as bindStatement,Vt as binding,Je as buildRelations,tr as bunDriver,Qn as cancelBackendThrough,or as cancelOpeningThrough,lo as canonicalType,rr as closeBunPool,fi as col,ce as connectionFailure,je as constraintOf,Rl as createDatabase,ts as createSearchWorker,So as cutOff,Lo as decrement,di as defineRepository,Dn as digest,po as drift,ao as emptySchema,De as encodeParam,ze as encodePgArray,ui as envBlock,Cn as fieldAddress,Ko as forgetUser,jo as forgetUserIn,_o as increment,nr as inlineParams,go as introspect,he as isColRef,Po as isData,vo as isDirect,yo as isEngineRaised,xe as isRetryable,ci as makeEnvDts,Ao as markData,pe as markEngineRaised,rn as normalize,Co as now,fo as plan,Io as pooledBinding,zo as postgresJsDriver,xo as pullSchema,Uo as renewingBunPool,Mo as sayRunning,Fn as searchPath,mi as sqlFragment,le as sqlstateOf,co as validate,Ke as vectorTable,Gn as verifyDriver,Mn as versionSchema,pi as withRetry};