UNPKG

@abw/badger-database

Version:

Javascript database abstraction layer

1 lines 64 kB
import e from"events";import t from"timers";const s="id",r=/:/,i=/^\w+$/,n="*",a="true",o="unknown",l=" ",c="=",u=", ",h="\n",d="",m="'",p='"',b="`",g="(",y=")",f="WITH",w="INSERT",v="SELECT",q="UPDATE",k="DELETE",x="FROM",O="IN",j="NOT IN",R="INTO",A="SET",T="VALUES",C="JOIN",M="LEFT JOIN",E="RIGHT JOIN",I="INNER JOIN",D="FULL JOIN",_="WHERE",P="GROUP BY",L="ORDER BY",V="HAVING",$="LIMIT",S="OFFSET",N="RETURNING",B="AS",F="ON",Q="AND",H="ASC",W="DESC",U="BEGIN",J="ROLLBACK",z="COMMIT";function G(e){return"string"==typeof e}function K(e){return Number.isInteger(e)}function Y(e){return Array.isArray(e)}function X(e){return"function"==typeof e}function Z(e){return"object"==typeof e&&!Y(e)&&!ee(e)}function ee(e){return null===e}function te(e){return!(function(e){return void 0===e}(e)||ee(e))}function se(e){return!te(e)}function re(...e){return e.find((e=>te(e)))}function ie(...e){throw new Error(e.join(""))}function ne(){}function ae(e,t=/,\s*|\s+/){return se(e)?[]:G(e)?e.length?e.split(t):[]:Y(e)?e:[e]}function oe(e,t=!0,s={}){return Z(e)?e:ae(e).reduce(((e,s)=>(e[s]=X(t)?t(s):t,e)),s)}function le(e){if(X(e))return e;if(function(e){return e instanceof RegExp}(e))return t=>e.test(t);if(Z(e))return t=>Boolean(e[t]);if(Y(e)||G(e)){const t=oe(e);return e=>Boolean(t[e])}ie("Invalid selector() specification: "+e)}Intl.DateTimeFormat().resolvedOptions().locale;const ce=(e,t,s={})=>{let r={},i={delete:!1,...s};const n=le(t);return Object.keys(e).map((t=>{if(n(t)){let s=e[t];i.delete&&delete e[t],i.key&&(t=i.key(t)),i.value&&(s=i.value(s)),r[t]=s}})),r},ue=(e,t)=>{const s=e[t];return delete e[t],s},he=e=>Y(e)?e:[e],de=e=>e.match(/^[aeiou]/i)?"an":"a",me={reset:0,bold:1,bright:1,dark:2,black:0,red:1,green:2,yellow:3,blue:4,magenta:5,cyan:6,grey:7,white:8,fg:30,bg:40},pe={fg:e=>`38;2;${e.r};${e.g};${e.b}`,bg:e=>`48;2;${e.r};${e.g};${e.b}`},be=(e,t="fg")=>{const s=(e=>{const t=e.match(/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i);return t?{r:parseInt(t[1],16),g:parseInt(t[2],16),b:parseInt(t[3],16)}:null})(e)||(e=>{const t=ae(e);return 3===t.length?{r:t[0],g:t[1],b:t[2]}:null})(e);return s?((e,t="fg")=>"["+pe[t](e)+"m")(s,t):((e,t="fg")=>{let s=[],r=e.split(/ /,2);const i=r.pop(),n=(t?me[t]:0)+me[i];if(s.push(n),r.length){const e=r.length?r.shift():"dark";s.push(me[e])}return"["+s.join(";")+"m"})(e,t)},ge=(e={})=>{const t=Z(e)?e:{fg:e};let s=[];return t.bg&&s.push(be(t.bg,"bg")),t.fg&&s.push(be(t.fg,"fg")),s.join("")},ye=be("reset",!1),fe=()=>ye,we=e=>(...t)=>ge(e)+t.join("")+ye,ve=e=>Object.entries(e).reduce(((e,[t,s])=>(e[t]=we(s),e)),{}),qe=we("black"),ke=we("red"),xe=we("green"),Oe=we("yellow"),je=we("blue"),Re=we("magenta"),Ae=we("cyan"),Te=we("grey"),Ce=we("white"),Me=we("bright black"),Ee=we("bright red"),Ie=we("bright green"),De=we("bright yellow"),_e=we("bright blue"),Pe=we("bright magenta"),Le=we("bright cyan"),Ve=we("bright grey"),$e=we("bright white"),Se=we("dark black"),Ne=we("dark red"),Be=we("dark green"),Fe=we("dark yellow"),Qe=we("dark blue"),He=we("dark magenta"),We=we("dark cyan"),Ue=we("dark grey"),Je=we("dark white"),ze=(e,t)=>e.replace(/<(\w+)>/g,((s,r)=>{const i=t[r];return se(i)&&ie(`Invalid variable expansion <${r}> in message format: ${e}`),i})),Ge=e=>ie(`No "${e}" specified`),Ke=(e,t)=>ie(`Invalid "${e}" specified: ${t}`),Ye=(e,t)=>ie(`${e} is not implemented in ${t}`),Xe=e=>t=>Ye(t,e),Ze=e=>Xe(`the ${e} base class`);class et extends Error{constructor(e){super(e),this.name=this.constructor.name}}class tt extends Error{constructor(e,t){super(t.message),this.name=this.constructor.name,this.query=e,this.type=t.type,this.code=t.code,this.position=t.position,t.stack&&(this.stack=t.stack)}}class st extends et{}const rt=(e,t)=>{throw new st(`Failed to load "${e}" engine driver module. Have you installed it?\nError: `+t.message)};class it extends et{}class nt extends et{}class at extends et{}class ot extends et{}class lt extends et{}class ct extends et{}function ut(e,t="returned"){throw new it(`${e} rows were ${t} when one was expected`)}const ht=(e,t=Error)=>(s,r)=>{const i=ze(e[s]||ie("Invalid message format: ",s),r);throw new t(i)},dt=ht({unknown:'Unknown "<column>" column in the <table> table',readonly:'The "<column>" column is readonly in the <table> table',fixed:'The "<column>" column is fixed in the <table> table',required:'Missing required column "<column>" for the <table> table',multipleIds:'Multiple columns are marked as "id" in the <table> table',noColumns:'No "columns" specified for the <table> table',invalidColumns:'Invalid "columns" specified for the <table> table: <columns>'},nt),mt=ht({action:"Cannot <action> deleted <table> record #<id>"},ot),pt=e=>{const t=e.columns||dt("noColumns",{table:e.table});return G(t)?bt(t,e):Y(t)?gt(t,e):Z(t)?yt(t,e):dt("invalidColumns",{table:e.table,columns:t})},bt=(e,t)=>gt(ae(e),t),gt=(e,t)=>{let s={};return e.forEach((e=>{const i=e.split(r),n=i.shift();s[n]=ft(n,i,t)})),yt(s,t)},yt=(e,t)=>function(e,t){return Object.keys(e).reduce(((s,r)=>(s[r]=t(e[r],r),s)),{})}(e,((e,s)=>{if(G(e))return ft(s,e.split(r),t);if(Z(e)){const r=e.column||(e.column=s);return e.tableColumn=t.table+"."+r,e}ie(`Invalid "${s}" columns specified in ${t.table} table: ${e}`)})),ft=(e,t,s)=>t.reduce(((e,t)=>{const s=t.split("=",2);return e[s.shift()]=!s.length||s[0],e}),{column:e,tableColumn:s.table+"."+e}),wt=(e,t={})=>{let r=ae(e.keys);const i=Object.keys(t).filter((e=>t[e].id));return i.length>1?dt("multipleIds",{table:e.table}):(0===r.length&&(r=Object.keys(t).filter((e=>t[e].key))),e.id?r.unshift(e.id):i.length?(e.id=i[0],r.unshift(e.id)):0===r.length&&(e.id=s,r.unshift(e.id)),r)},vt=/^(\w+):\/\/(?:(?:(\w+)(?::(\w+))?@)?(\w+)(?::(\d+))?\/)?(\w+)/,qt={engine:1,user:2,password:3,host:4,port:5,database:6},kt={username:"user",pass:"password",hostname:"host",file:"filename",name:"database"},xt=e=>{e.env&&Object.assign(e,Ot(e.env,{prefix:e.envPrefix}));let t=e.database||Ge("database");return G(t)&&(e.database=t=jt(t)),e.engine||=t.engine||Ge("database.engine"),delete t.engine,Object.entries(kt).map((([e,s])=>{te(t[e])&&(t[s]||=ue(t,e))})),e.engineOptions&&Object.assign(t,ue(e,"engineOptions")),e},Ot=(e,t={})=>{const s=t.prefix||"DATABASE",r=s.match(/_$/)?"":"_",i=new RegExp(`^${s}${r}`);return{database:e[s]||ce(e,i,{key:e=>e.replace(i,"").toLowerCase()})}},jt=e=>{let t,s={};return e.match(/^postgres(ql)?:/)?(s.engine="postgres",s.connectionString=e.replace(/^postgres:/,"postgresql:")):(t=e.match(/^sqlite:\/\/(.*)/))?(s.engine="sqlite",s.filename=t[1]):"sqlite:memory"===e?(s.engine="sqlite",s.filename=":memory:"):(t=e.match(vt))?Object.entries(qt).map((([e,r])=>{const i=t[r];te(i)&&(s[e]=i)})):Ke("database",e),s};function Rt(e,t="",s){return e?t?(e,...r)=>console.log("%s"+t+"%s"+e,s?ge(s):"",fe(),...r):console.log.bind(console):ne}function At(e,t,s="",r){e.debug=Rt(t,s,r)}let Tt={database:{debug:!1,prefix:"Database",color:"bright magenta"},engine:{debug:!1,prefix:"Engine",color:"red"},query:{debug:!1,prefix:"Query",color:"cyan"},tables:{debug:!1,prefix:"Tables",color:"blue"},table:{debug:!1,prefix:"Table",color:"bright cyan"},record:{debug:!1,prefix:"Record",color:"green"},builder:{debug:!1,prefix:"Builder",color:"yellow"},transaction:{debug:!1,prefix:"Transaction",color:"bright red"},test:{debug:!1,prefix:"Test",color:"green"}};const Ct=e=>ie(`Invalid debug item "${e}" specified`),Mt=e=>{Object.entries(e).map((([e,t])=>{const s=Tt[e]||Ct(e);!function(e){return"boolean"==typeof e}(t)?Z(t)&&Object.assign(s,t):s.debug=t}))},Et=(e,...t)=>{const s=Tt[e]||Ct(e);return Object.assign({},s,...t)},It=(e,t,...s)=>{const r=Et(t,...s),i=r.debug,n=r.debugPrefix||r.prefix,a=r.debugColor||r.color,o=n.length>14?n+"\n"+"".padEnd(16,"-")+"> ":(n+" ").padEnd(16,"-")+"> ";At(e,i,o,a),e.debugData=function(e,t,s,r=16){return e?(e,i={})=>{console.log("%s"+t+"%s"+e,s?ge(s):"",s?fe():""),Object.entries(i).map((([e,t])=>console.log("%s"+e.padStart(r," ")+":%s",s?ge(s):"",s?fe():"",t)))}:ne}(i,o,a)};const Dt={[O]:O,[j]:j},_t=e=>Dt[e.toUpperCase().replaceAll(/\s+/g," ")],Pt=/^(\w+)\s*([-~=#]>)\s*(\w+)\.(\w+)$/,Lt={"~>":"any","->":"one","=>":"many","#>":"map"},Vt={localKey:"from",local_key:"from",remoteKey:"to",remote_key:"to",orderBy:"order",order_by:"order"},$t=(e,t,s)=>(G(s)?s=St(s):G(s.relation)&&(s={...St(s.relation),...s}),Object.entries(Vt).map((([e,t])=>{te(s[e])&&(s[t]||=ue(s,e))})),s.load||["type","table","to","from"].forEach((r=>{se(s[r])&&ie(`Missing "${r}" in ${t} relation for ${e} table`)})),s.name=`${e}.${t}`,s),St=e=>{let t;return(t=e.match(Pt))?{from:t[1],type:Lt[t[2]]||ie('Invalid type "',t[2],'" specified in relation: ',e),table:t[3],to:t[4]}:ie("Invalid relation string specified: ",e)},Nt=(e,t)=>{const s=t.from,r=t.to;let i=t.where||{};return s&&r&&(i[r]=e.row[s]),i},Bt=e=>e&&e.length?e+l:d,Ft=e=>e&&e.length?l+e:d,Qt=e=>e&&e.length?l+e+l:d,Ht=e=>e&&e.length?"("+e+")":d,Wt=e=>({sql:e});let Ut={},Jt={};const zt=Ze("Builder");class Gt{static generateSQL(e){const t=this.keyword,s=this.joint;return Bt(t)+(Y(e)?e.join(s):e)}constructor(e,...t){this.parent=e,this.args=t,this.messages=this.constructor.messages,this.method=this.constructor.buildMethod,this.slot=this.constructor.contextSlot||this.method,this.initBuilder(...t),It(this,"builder",{debugPrefix:this.method&&`Builder:${this.method}`})}initBuilder(){}async one(e,t){const s=this.sql(),r=this.lookupDatabase(),i=this.allValues(e);return this.debugData("one()",{sql:s,values:i}),r.one(s,i,t)}async any(e,t){const s=this.sql(),r=this.lookupDatabase(),i=this.allValues(e);return this.debugData("any()",{sql:s,values:i}),r.any(s,i,t)}async all(e,t={}){const s=this.sql(),r=this.lookupDatabase(),i=this.allValues(e);return this.debugData("all()",{sql:s,values:i}),r.all(s,i,t)}async run(e,t={}){const s=this.sql(),r=this.lookupDatabase(),i=this.allValues(e);return this.debugData("all()",{sql:s,values:i}),r.run(s,i,{...t,sanitizeResult:!0})}contextValues(){const{setValues:e,whereValues:t,havingValues:s}=this.resolveChain();return{setValues:e,whereValues:t,havingValues:s}}allValues(e=[]){const{setValues:t,whereValues:s,havingValues:r}=this.resolveChain();return X(e)?e(t,s,r):[...t,...s,...r,...e]}setValues(...e){return e.length&&(this.context.setValues=[...this.context.setValues,...e]),this.context.setValues}whereValues(...e){return e.length&&(this.context.whereValues=[...this.context.whereValues,...e]),this.context.whereValues}havingValues(...e){return e.length&&(this.context.havingValues=[...this.context.havingValues,...e]),this.context.havingValues}sql(){const e=this.resolveChain();return Object.entries(Jt).sort(((e,t)=>e[1][1]-t[1][1])).filter((([t])=>e[t])).map((([t,s])=>s[0].generateSQL(e[t],e))).filter((e=>te(e))).join(h)}resolveChain(){return this.context||this.resolve(this.parent?this.parent.resolveChain():{setValues:[],whereValues:[],havingValues:[],placeholder:1})}resolve(e,t={}){const s=this.slot;this.context={...e,...t};const r=this.resolveLink();return r&&r.length&&(this.context[s]=[...this.context[s]||[],...r]),this.context}resolveLink(){return this.args.map((e=>Z(e)&&e.sql?e.sql:this.resolveLinkItem(e))).flat()}resolveLinkItem(e){return G(e)?this.resolveLinkString(e):Y(e)?this.resolveLinkArray(e):X(e)?e(this):Z(e)?this.resolveLinkObject(e):se(e)?this.resolveLinkNothing(e):void ie("Invalid query builder value: ",e)}resolveLinkString(){zt("resolveLinkString()")}resolveLinkArray(){zt("resolveLinkArray()")}resolveLinkObject(){zt("resolveLinkObject()")}resolveLinkNothing(){return[]}lookup(e,t){return this[e]||(this.parent?this.parent.lookup(e):ie(t||`Missing item in query chain: ${e}`))}lookupDatabase(){return this.context.database||this.lookup("database")}lookupTable(){return this.context.table||this.lookup("table")}quote(e){return this.lookupDatabase().quote(e)}quoteTableColumns(e,t,s){const r=e?s?t=>this.quoteTableColumnAs(e,t,s+t):t=>this.quoteTableColumn(e,t):s?e=>this.quoteColumnAs(e,s+e):e=>this.quote(e);return ae(t).map(r)}tableColumn(e,t){return t.match(/\./)?t:`${e}.${t}`}quoteTableColumn(e,t){return this.quote(this.tableColumn(e,t))}quoteTableAs(e,t){return[this.quote(e),this.quote(t)].join(" AS ")}quoteTableColumnAs(e,t,s){return[this.quoteTableColumn(e,t),this.quote(s)].join(" AS ")}quoteColumnAs(e,t){return[this.quote(e),this.quote(t)].join(" AS ")}errorMsg(e,t){const s=this.method||o;return this.error(ze(this.messages?.[e]||ie("Invalid message format: ",e),{method:s,...t}))}toString(){return this.sql()}error(...e){throw new(this.errorType||lt)(e.join(""))}}class Kt extends Gt{static buildMethod="select";static buildOrder=20;static subMethods="select columns from table prefix join where having group groupBy order orderBy limit offset range returning";static keyword=v;static joint=u;static messages={array:'Invalid array with <n> items specified for query builder "<method>" component. Expected [column, alias] or [table, column, alias].',object:'Invalid object with "<keys>" properties specified for query builder "<method>" component. Valid properties are "columns", "column", "table", "prefix" and "as".'};resolveLinkString(e,t,s){return this.quoteTableColumns(t,e,s)}resolveLinkArray(e){return 2===e.length?this.quoteColumnAs(...e):3===e.length?this.quoteTableColumnAs(...e):void this.errorMsg("array",{n:e.length})}resolveLinkObject(e){if(e.column&&e.as)return e.table?this.quoteTableColumnAs(e.table,e.column,e.as):this.quoteColumnAs(e.column,e.as);const t=e.column||e.columns;if(t)return this.resolveLinkString(t,e.table,e.prefix);this.errorMsg("object",{keys:Object.keys(e).sort().join(", ")})}}let Yt=class extends Gt{initBuilder(e){this.database=e}resolve(e){return{database:this.database,...e}}};class Xt extends Gt{static buildMethod="from";static buildOrder=30;static keyword=x;static joint=u;static messages={array:'Invalid array with <n> items specified for query builder "<method>" component. Expected [table, alias].',object:'Invalid object with "<keys>" properties specified for query builder "<method>" component. Valid properties are "tables", "table" and "as".'};initBuilder(...e){const t=e.at(-1);G(t)?this.tableName=ae(t).at(-1):Y(t)&&2===t.length?this.tableName=t[1]:Z(t)&&t.as&&(this.tableName=t.as)}resolve(e){return super.resolve(e,this.tableName?{table:this.tableName}:void 0)}resolveLinkString(e){return ae(e).map((e=>this.quote(e)))}resolveLinkArray(e){return 2===e.length?this.quoteTableAs(...e):this.errorMsg("array",{n:e.length})}resolveLinkObject(e){return e.table?e.as?this.quoteTableAs(e.table,e.as):this.quote(e.table):e.tables?this.resolveLinkString(e.tables):void this.errorMsg("object",{keys:Object.keys(e).sort().join(", ")})}}class Zt extends Gt{static buildMethod="where";static buildOrder=50;static keyword=_;static joint=" AND ";static messages={array:'Invalid array with <n> items specified for query builder "<method>" component. Expected [column, value] or [column, operator, value].',object:'Invalid value array with <n> items specified for query builder "<method>" component. Expected [value] or [operator, value].'};resolveLinkString(e){const t=this.lookupDatabase();return ae(e).map((e=>t.engine.formatWherePlaceholder(e,void 0,this.context.placeholder++)))}resolveLinkArray(e){const t=this.lookupDatabase();if(2===e.length){let s;if(Y(e[1])){const t=_t(e[1][0]);if(t){const s=he(e[1][1]);return this.addValues(...s),this.resolveIn(e[0],t,s)}te(e[1][1])&&this.addValues(e[1][1]),s=[e[1][0],void 0]}else this.addValues(e[1]);return t.engine.formatWherePlaceholder(e[0],s,this.context.placeholder++)}if(3===e.length){const s=_t(e[1]);if(s){const t=he(e[2]);return this.addValues(...t),this.resolveIn(e[0],s,t)}return te(e[2])&&this.addValues(e[2]),t.engine.formatWherePlaceholder(e[0],[e[1],e[2]],this.context.placeholder++)}this.errorMsg("array",{n:e.length})}resolveLinkObject(e){const t=this.lookupDatabase();let s=[];const r=Object.entries(e).map((([e,r])=>{if(Y(r))if(2===r.length){const t=_t(r[0]),i=he(r[1]);if(t)return s.push(...i),this.resolveIn(e,t,i);s.push(r[1])}else 1!==r.length&&this.errorMsg("object",{n:r.length});else{if(ee(r))return t.engine.formatWhereNull(e);s.push(r)}return t.engine.formatWherePlaceholder(e,r,this.context.placeholder++)}));return s.length&&this.addValues(...s),r}resolveIn(e,t,s){const r=this.lookupDatabase(),i=this.context.placeholder;return this.context.placeholder+=s.length,r.engine.formatWhereInPlaceholder(e,t,s,i)}addValues(...e){this.whereValues(...e)}}const es=/^(\w+)\.(\w+)$/,ts=/^(.*?)\s*(<?=>?)\s*(\w+)\.(\w+)(?:\s+as\s+(\w+))?$/,ss={from:1,type:2,table:3,to:4,as:5},rs={default:C,inner:I,"=":C,left:M,"<=":M,right:E,"=>":E,full:D,"<=>":D};class is extends Gt{static buildMethod="simple";static generateSQL(e){const t=this.keyword;return Bt(t)+(Y(e)?e.at(-1):e)}initBuilder(e){this.value=e}resolve(e){return this.context={...e,[this.slot]:this.value},this.context}}let ns=class extends Gt{static buildMethod="table";initBuilder(e){this.tableName=e}resolve(e){return this.context={...e,table:this.tableName},this.context}};const as=(e,t,s={})=>new Proxy(t,{get(r,i){if("toString"===i)return r.toString.bind(r);const n=e[i];if(!n)return Reflect.get(r,i);if(s.valid){let e=Boolean(s.valid[i]);if(!e&&n.validFor&&(e=Boolean(oe(n.validFor)[s.keyword])),!e)throw new lt(`${i}() is not a valid builder method for ${de(s.keyword)} ${s.keyword} query.`)}return((...s)=>{const r=new n(t,...s),i=n.subMethods;return i?as(e,r,{valid:ce(e,i),keyword:n.keyword}):as(e,r)}).bind(r)}}),os=e=>{const t=e.contextSlot||e.buildMethod,s=e.buildOrder;[e.buildMethod,...ae(e.buildAlias)].forEach((t=>Ut[t]=e)),t&&te(s)&&(Jt[t]=[e,s])},ls=(...e)=>e.forEach(os);ls(class extends Gt{static buildMethod="after";static buildOrder=100},class extends Gt{static buildMethod="before";static buildOrder=0},class extends Kt{static buildMethod="columns";static contextSlot="select";initBuilder(){}resolveLinkString(e,t=this.lookupTable(),s=this.context.prefix){return super.resolveLinkString(e,t,s)}resolveLinkArray(e){const t=this.lookupTable();return 2===e.length?this.quoteTableColumnAs(t,...e):3===e.length?this.quoteTableColumnAs(...e):void this.errorMsg("array",{n:e.length})}resolveLinkObject(e){const t=this.lookupTable();if(e.column&&e.as)return this.quoteTableColumnAs(e.table||t,e.column,e.as);const s=e.column||e.columns;if(s)return this.resolveLinkString(s,e.table||t,e.prefix||this.context.prefix);this.errorMsg("object",{keys:Object.keys(e).sort().join(", ")})}},class extends Gt{static buildMethod="delete";static buildOrder=19;static subMethods="from join where order order_by limit returning";static keyword=k;static joint=u;static messages={object:'Invalid object with "<keys>" properties specified for query builder "<method>" component. Valid properties are "columns", "column", "table" and "prefix".'};static generateSQL(e){const t=this.keyword,s=this.joint;return e&&e.length?Bt(t)+(Y(e)?e.join(s):e):t}resolveLink(){if(this.args.length)return super.resolveLink();this.context.delete=[]}resolveLinkString(e,t,s){return this.quoteTableColumns(t,e,s)}resolveLinkObject(e){const t=e.column||e.columns;if(t)return this.resolveLinkString(t,e.table,e.prefix);this.errorMsg("object",{keys:Object.keys(e).sort().join(", ")})}},Xt,class extends Gt{static buildMethod="group";static buildAlias="groupBy";static buildOrder=60;static keyword=P;static joint=u;static messages={array:'Invalid array with <n> items specified for query builder "<method>" component. Expected [column].',object:'Invalid object with "<keys>" properties specified for query builder "<method>" component. Valid properties are "columns" and "column".'};resolveLinkString(e){return ae(e).map((e=>this.quote(e)))}resolveLinkArray(e){if(1===e.length)return this.quote(e[0]);this.errorMsg("array",{n:e.length})}resolveLinkObject(e){return e.column?this.quote(e.column):e.columns?this.resolveLinkString(e.columns):void this.errorMsg("object",{keys:Object.keys(e).sort().join(", ")})}},class extends Zt{static buildMethod="having";static buildOrder=70;static keyword=V;addValues(...e){this.havingValues(...e)}},class extends Gt{static buildMethod="insert";static buildOrder=17;static subMethods="into join values returning";static keyword=w;static joint=u;static messages={object:'Invalid object with "<keys>" properties specified for query builder "<method>" component. Valid properties are "columns" and "column".'};static generateSQL(){return this.keyword}resolveLink(){if(this.args.length)return super.resolveLink();this.context.insert=[]}resolveLinkString(e){return this.quoteTableColumns(void 0,e)}resolveLinkArray(e){return this.quoteTableColumns(void 0,e)}resolveLinkObject(e){const t=e.column||e.columns;if(t)return this.resolveLinkString(t,e.table);this.errorMsg("object",{keys:Object.keys(e).sort().join(", ")})}},class extends Gt{static buildMethod="into";static buildOrder=29;static keyword=R;static joint=u;static generateSQL(e,t){const s=this.keyword,r=this.joint,i=t.database,n=t.insert||[];let a=t.placeholder;return Bt(s)+(Y(e)?e.join(r):e)+(n.length?Ft(Ht(n.join(u))):d)+(n.length?h+Bt(T)+Ht(n.map((()=>i.engine.formatPlaceholder(a++))).join(u)):d)}initBuilder(...e){1===e.length&&G(e[0])&&(this.tableName=e[0])}resolve(e){return super.resolve(e,this.tableName?{table:this.tableName}:void 0)}resolveLinkString(e){return[this.quote(e)]}},class extends Gt{static buildMethod="join";static buildOrder=40;static keyword=d;static joint=h;static messages={type:'Invalid join type "<joinType>" specified for query builder "<method>" component. Valid types are "left", "right", "inner" and "full".',string:'Invalid join string "<join>" specified for query builder "<method>" component. Expected "from=table.to".',object:'Invalid object with "<keys>" properties specified for query builder "<method>" component. Valid properties are "type", "table", "from" and "to".',array:'Invalid array with <n> items specified for query builder "<method>" component. Expected [type, from, table, to], [from, table, to] or [from, table.to].'};resolveLinkString(e){let t=e.match(ts),s={};if(t)return Object.entries(ss).map((([e,r])=>s[e]=t[r])),this.resolveLinkObject(s);this.errorMsg("string",{join:e})}resolveLinkArray(e){if(4===e.length){const[t,s,r,i]=e;return this.resolveLinkObject({type:t,from:s,table:r,to:i})}if(3===e.length){const[t,s,r]=e;return this.resolveLinkObject({from:t,table:s,to:r})}if(2===e.length){const t=e[1].match(es);if(t){const s=e[0],[,r,i]=t;return this.resolveLinkObject({from:s,table:r,to:i})}}this.errorMsg("array",{n:e.length})}resolveLinkObject(e){const t=rs[e.type||"default"]||this.errorMsg("type",{joinType:e.type});if(e.table&&e.from&&e.to)return e.as?this.constructJoinAs(t,e.from,e.table,e.as,this.tableColumn(e.as,e.to)):this.constructJoin(t,e.from,e.table,this.tableColumn(e.table,e.to));if(e.from&&e.to){const s=e.to.match(es);if(s)return e.as?this.constructJoinAs(t,e.from,s[1],e.as,this.tableColumn(e.as,s[2])):this.constructJoin(t,e.from,s[1],this.tableColumn(s[1],s[2]))}this.errorMsg("object",{keys:Object.keys(e).sort().join(", ")})}constructJoin(e,t,s,r){return Bt(e)+this.quote(s)+Qt(F)+this.quote(t)+Qt(c)+this.quote(r)}constructJoinAs(e,t,s,r,i){return Bt(e)+this.quote(s)+Qt("AS")+this.quote(r)+Qt(F)+this.quote(t)+Qt(c)+this.quote(i)}},class extends is{static buildMethod="limit";static buildOrder=90;static keyword=$;initBuilder(e){this.value=e}},class extends is{static buildMethod="offset";static buildOrder=95;static keyword=S;initBuilder(e){this.value=e}},class extends Gt{static buildMethod="order";static buildAlias="orderBy";static buildOrder=80;static keyword=L;static joint=u;static messages={array:'Invalid array with <n> items specified for query builder "<method>" component. Expected [column, direction] or [column].',object:'Invalid object with "<keys>" properties specified for query builder "<method>" component. Valid properties are "columns", "column", "direction", "dir", "asc" and "desc".'};resolveLinkString(e,t){return ae(e).map((e=>this.constructOrder(e))).join(", ")+(t?l+t:"")}resolveLinkArray(e){if(2===e.length||1===e.length)return this.constructOrder(...e);this.errorMsg("array",{n:e.length})}resolveLinkObject(e){const t=e.direction||e.dir||e.desc&&W||e.asc&&"ASC";return e.column?this.constructOrder(e.column,t):e.columns?this.resolveLinkString(e.columns,t):void this.errorMsg("object",{keys:Object.keys(e).sort().join(", ")})}constructOrder(e,t){return this.quote(e)+(t?l+t:"")}},class extends Gt{static buildMethod="prefix";initBuilder(e){this.prefix=e}resolve(e){return this.context={...e,prefix:this.prefix},this.context}},class extends Gt{static buildMethod="range";static messages={arg:'Invalid argument specified for query builder "<method>" component. Expected (from, to), (from) or object.',args:'Invalid arguments with <n> items specified for query builder "<method>" component. Expected (from, to), (from) or object.',object:'Invalid object with "<keys>" properties specified for query builder "<method>" component. Valid properties are "from", "to", "limit" and "offset".'};initBuilder(...e){if(2===e.length)this.args=this.twoNumberArgs(...e);else if(1===e.length){const t=e[0];K(t)?this.args=this.oneNumberArg(t):Z(t)?this.args=this.objectArgs(t):this.errorMsg("arg")}else this.errorMsg("args",{n:e.length})}twoNumberArgs(e,t){return{offset:e,limit:t-e+1}}oneNumberArg(e){return{offset:e}}objectArgs(e){return e.from&&e.to?this.twoNumberArgs(e.from,e.to):e.from?this.oneNumberArg(e.from):e.to?{limit:e.to+1}:e.limit||e.offset?{limit:e.limit,offset:e.offset}:void this.errorMsg("object",{keys:Object.keys(e).sort().join(", ")})}resolve(e){return this.context={...e,...this.args},this.context}},class extends Kt{static buildMethod="returning";static buildOrder=96;static keyword=N},Kt,class extends Zt{static buildMethod="set";static buildOrder=45;static keyword="SET";static joint=u;static messages={array:'Invalid array with <n> items specified for query builder "<method>" component. Expected [column, value].',object:'Invalid value array with <n> items specified for query builder "<method>" component. Expected [value] or [operator, value].'};addValues(...e){this.setValues(...e)}resolveLinkObject(e){const t=this.lookupDatabase();let s=[];const r=Object.entries(e).map((([e,r])=>(s.push(r),t.engine.formatWherePlaceholder(e,"",this.context.placeholder++))));return s.length&&this.addValues(...s),r}resolveLinkArray(e){if(2==e.length)return this.addValues(e[1]),this.lookupDatabase().engine.formatSetPlaceholder(e[0],this.context.placeholder++);this.errorMsg("array",{n:e.length})}},ns,class extends Xt{static buildMethod="update";static buildOrder=18;static subMethods="join set where order order_by limit returning";static keyword=q;static joint=u},class extends Gt{static buildMethod="values";static buildOrder=0;resolveLinkItem(e){return K(e)||function(e){return function(e){return"number"==typeof e}(e)&&!K(e)}(e)?this.resolveLinkString(e):super.resolveLinkItem(e)}resolveLinkString(e){return this.setValues(e),[]}resolveLinkArray(e){return e.forEach((e=>{this.setValues(e)})),[]}},Zt);const cs=e=>as(Ut,new Yt(void 0,e)),us=e=>as(Ut,new ns(void 0,e));class hs{constructor(e,t,s={}){if(this.engine=e||Ge("engine"),this.setValues=s.setValues||[],this.whereValues=s.whereValues||[],this.havingValues=s.havingValues||[],this.transact=s.transact,G(t))this.query=t;else if(t instanceof Gt){this.query=t.sql();const e=t.contextValues();Object.keys(e).forEach((t=>this[t]=[...e[t],...this[t]]))}else ie("Invalid query type: ",t);It(this,"query",this.config)}sql(){return this.query}run(...e){const t=this.sql(),[s,r]=this.queryArgs(e);return this.debugData("run()",{sql:t,values:s,options:r}),this.engine.run(t,s,r)}one(...e){const t=this.sql(),[s,r]=this.queryArgs(e);return this.debugData("one()",{sql:t,values:s,options:r}),this.engine.one(t,s,r)}any(...e){const t=this.sql(),[s,r]=this.queryArgs(e);return this.debugData("any()",{sql:t,values:s,options:r}),this.engine.any(t,s,r)}all(...e){const t=this.sql(),[s,r]=this.queryArgs(e);return this.debugData("all()",{sql:t,values:s,options:r}),this.engine.all(t,s,r)}queryArgs(e){const t=Y(e[0])?e.shift():[],s=e.length?e.shift():{};return[this.allValues(t),this.transact?{...s,transact:this.transact}:s]}allValues(e=[]){const t=this.whereValues,s=this.havingValues;return X(e)?e(t,s):[...t,...s,...e]}toString(){return this.sql()}}const ds=e=>G(e)||e instanceof Gt,ms=(e,t,s=16)=>{let r=e=e.trim(),i=0,n=[];for(;;){let e=!1;if(r=r.replace(/<(\w+?)>/g,((s,r)=>(e=!0,n.push(r),t.fragment(r)))),!e)break;++i>=s&&ie("Maximum SQL expansion limit (maxDepth=",s,") exceeded: ",n.join(" -> "))}return r};class ps{constructor(e,t={}){this.engine=e||Ge("engine"),this.transact=t.transact}query(e){this.debugData("query()",{source:e});const t=this.queries[e]||this.database&&this.database.query(e)||ie("Invalid named query specified: ",e);return X(t)?t(this):t}fragment(e){return this.debugData("fragment()",{name:e}),this.fragments[e]||this.database&&this.database.fragment(e)||ie("Invalid query fragment in SQL expansion: <",e,">")}buildQuery(e,t={}){return t.transact||=this.transact,this.debugData("buildQuery()",{source:e,config:t}),new hs(this.engine,G(e)?this.expandQuery(e):e,t)}expandQuery(e,t){return this.debugData("expandQuery()",{source:e}),e.match(i)?this.expandNamedQuery(e,t):ms(e,this)}expandNamedQuery(e){this.debugData("expandNamedQuery()",{name:e});const t=this.query(e);return G(t)?ms(t,this):t}sql(e,t){return this.debugData("sql()",{name:e,config:t}),this.buildQuery(e,t).sql()}async run(e,t,s){return this.debugData("run()",{query:e,params:t,options:s}),this.buildQuery(e).run(t,s)}async one(e,t,s){return this.debugData("one()",{query:e,params:t,options:s}),this.loadedOne(await this.buildQuery(e).one(t,s),s)}async any(e,t,s){return this.debugData("any()",{query:e,params:t,options:s}),this.loadedAny(await this.buildQuery(e).any(t,s),s)}async all(e,t,s){return this.debugData("all()",{query:e,params:t,options:s}),this.loadedAll(await this.buildQuery(e).all(t,s),s)}loadedOne(e){return e}loadedAny(e){return e}loadedAll(e){return e}}const bs={one:async(e,t={})=>{const s=Nt(e,t),r=await e.database.table(t.table);return await r.oneRecord(s)},any:async(e,t={})=>{const s=Nt(e,t),r=await e.database.table(t.table);return await r.anyRecord(s)},many:async(e,t={})=>{const s=Nt(e,t),r=t.order,i=r?{order:r}:{},n=await e.database.table(t.table);return await n.allRecords(s,i)},map:async(e,t={})=>{const s=Nt(e,t),r=t.key||e.table.id,i=t.value,n=await e.database.table(t.table);return(await n.allRecords(s)).reduce(((e,s)=>(e[s[r]]=t.value?s[i]:s,e)),{})}};class gs{constructor(e,t,s={}){this.table=e,this.database=e.database,this.row=t,this.relations={},this.config=s,It(this,"record",{debugPrefix:`Record:${this.table.table}`},s)}async update(e,t={}){this.debugData("update()",{set:e}),this.assertNotDeleted("update");const s=this.table.identity(this.row),r=await this.table.updateOne(e,s,{...t,reload:!0});return Object.assign(this.row,r),this}async delete(){this.debugData("delete()"),this.assertNotDeleted("delete");const e=this.table.identity(this.row);return await this.table.delete(e),this.deleted=!0,this}assertNotDeleted(e){this.deleted&&mt("action",{action:e,table:this.table.table,id:this.table.keys.map((e=>this.row[e])).join("/")})}async relation(e){return this.debug("relation(%s)",e),this.relations[e]||=await this.initRelation(e)}async initRelation(e){this.debug("initRelation(%s)",e);const t=this.table.table,s=$t(t,e,this.table.relations[e]||ie(`Invalid "${e}" relation specified for ${t} table`));if(s.load)return await s.load(this);const r=bs[s.type]||ie(`Invalid "${s.type}" relation type specified for ${e} relation in ${t} table`);return await r(this,s)}}const ys=e=>new Proxy(e,{get:(e,t)=>Reflect.has(e,t)?Reflect.get(e,t):Reflect.has(e.row,t)?Reflect.get(e.row,t):Reflect.has(e.table.relations,t)?e.relation(t):Reflect.get(e,t)}),fs={insertRow:"insertOneRow",insertRows:"insertAllRows",insertRecord:"insertOneRecord",insertRecords:"insertAllRecords",update:"updateAll",updateRow:"updateOneRow",fetch:"fetchAll",fetchRecord:"fetchOneRecord",fetchRecords:"fetchAllRecords"};class ws extends ps{constructor(e,t){var s,r;super(e.engine,t),this.config=this.configure(t)||t,this.database=e||ie("No database specified"),this.table=t.table,this.columns=pt(t),this.readonly=Object.keys(this.columns).filter((e=>this.columns[e].readonly)),this.required=Object.keys(this.columns).filter((e=>this.columns[e].required)),this.keys=wt(t,this.columns),this.id=t.id,this.recordClass=t.recordClass||gs,this.recordConfig=t.recordConfig,this.queries=t.queries||{},this.fragments=this.prepareFragments(t),this.relations=t.relations||{},this.build=cs(this.database),s=this,r=fs,Object.entries(r).map((([e,t])=>s[e]=s[t]||ie(`Invalid alias "${e}" references non-existent method "${t}"`))),It(this,"table",{debugPrefix:`Table:${this.table}`},t)}configure(e){return e}prepareFragments(e){const t=this.database.quote.bind(this.database),s=e.fragments||={};return s.table=t(this.table),s.columns=Object.values(this.columns).map((e=>t(e.tableColumn))).join(", "),s}async insert(e,t){return Y(e)?this.insertAll(e,t):this.insertOne(e,t)}async prepareInsert(e,t){const[s,r]=await this.validateInsert(e,t),i=this.engine.returning?{table:this.table,columns:this.keys}:void 0;this.checkRequiredColumns(e);const n=this.build.insert(s).into(this.table).values(r).returning(i);return this.debugData("prepareInsert()",{data:e,sql:n.sql()}),n}async validateInsert(e,t){return this.checkWritableColumns(e,t)}async insertOne(e,t={}){const s=await this.prepareInsert(e,t).then((e=>e.run(void 0,{keys:this.keys})));return this.inserted(e,s,t)}async insertAll(e,t){this.debugData("insertAll()",{data:e,options:t});let s=[];for(const r of e)s.push(await this.insertOne(r,t));return s}async insertOneRow(e,t){return this.debugData("insertOneRow()",{data:e,options:t}),this.insertOne(e,this.withReloadOption(t))}async insertAllRows(e,t){return this.debugData("insertAllRows()",{data:e,options:t}),this.insertAll(e,this.withReloadOption(t))}async insertOneRecord(e,t){return this.debugData("insertOneRecord()",{data:e,options:t}),this.insertOne(e,this.withRecordOption(t))}async insertAllRecords(e,t){return this.debugData("insertAllRecords()",{data:e,options:t}),this.insertAll(e,this.withRecordOption(t))}async inserted(e,t,s={}){return s.reload||s.record?this.insertReload(e,t,s):t}async insertReload(e,t,s={}){const r={};return this.keys.map((s=>r[s]=re(t[s],e[s]))),s.record?this.oneRecord(r):this.oneRow(r)}async prepareUpdate(e,t,s){const[r,i]=await this.validateUpdate(e,t,s),n=this.build.update(this.table).set(r).where(i),a=n.sql();return this.debugData("prepareUpdate()",{where:t,sql:a}),n}async validateUpdate(e,t,s){const[,,r]=this.checkUpdatableColumns(e,s),[,,i]=this.checkWhereColumns(t,s);return[r,i]}async updateOne(e,t,s={}){this.debugData("updateOne()",{set:e,where:t,options:s});const r=await this.prepareUpdate(e,t,s).then((e=>e.run()));return 1===r.changes?this.updated(e,t,r,s):ut(r.changes,"updated")}async updateAny(e,t,s={}){this.debugData("updateAny()",{set:e,where:t,options:s});const r=await this.prepareUpdate(e,t,s).then((e=>e.run()));return r.changes>1?ut(r.changes,"updated"):1===r.changes?this.updated(e,t,r,s):s.reload?void 0:r}async updateAll(e,t,s={}){this.debugData("updateAllRows()",{set:e,where:t,options:s});const r=await this.prepareUpdate(e,t,s).then((e=>e.run()));return s.reload?ie("Cannot reload multiple updated rows"):r}async updateOneRow(e,t,s){return this.debugData("updateOneRow()",{set:e,where:t,options:s}),this.updateOne(e,t,this.withReloadOption(s))}async updateAnyRow(e,t,s){return this.debugData("updateAnyRow()",{set:e,where:t,options:s}),this.updateAny(e,t,this.withReloadOption(s))}async updated(e,t,s,r){return r.reload?this.updateReload(e,t,r):s}async updateReload(e,t,s){const r={};return Object.keys(t).map((s=>r[s]=re(e[s],t[s]))),this.oneRow(r,s)}async delete(e,t){this.debugData("delete()",{where:e});const s=await this.validateDelete(e,t),r=this.build.delete().from(this.table).where(s),i=r.sql();this.debugData("delete()",{where:e,sql:i});const n=await r.run();return this.deleted(e,n,t)}async validateDelete(e,t){const[,,s]=this.checkWhereColumns(e,t);return s}async deleted(e,t){return t}prepareFetch(e,t){const s=this.table,r=t.columns||Object.keys(this.columns);this.checkColumnNames(r);const[,,i]=this.checkWhereColumns(e,t),n=this.select({table:s,columns:r}).where(i).order(t.orderBy||t.order),a=n.sql();return this.debugData("prepareFetch()",{where:e,sql:a}),n}async fetchOne(e,t={}){this.debugData("fetchOne()",{where:e,options:t});const s=await this.prepareFetch(e,t).one();return this.loadedOne(s,t)}async fetchAny(e,t={}){this.debugData("fetchAny()",{where:e,options:t});const s=await this.prepareFetch(e,t).any();return s?this.loadedOne(s,t):void 0}async fetchAll(e,t={}){this.debugData("fetchAllRows()",{where:e,options:t});const s=await this.prepareFetch(e,t).all();return this.loadedAll(s,t)}async fetchOneRecord(e,t){return this.debugData("fetchOneRecord()",{where:e,options:t}),this.fetchOne(e,this.withRecordOption(t))}async fetchAnyRecord(e,t){return this.debugData("fetchAnyRecord()",{where:e,options:t}),this.fetchAny(e,this.withRecordOption(t))}async fetchAllRecords(e,t){return this.debugData("fetchAllRecords()",{where:e,options:t}),this.fetchAll(e,this.withRecordOption(t))}async oneRow(e,...t){return this.debugData("oneRow()",{query:e,args:t}),ds(e)?this.one(e,...t):this.fetchOne(e,...t)}async anyRow(e,...t){return this.debugData("anyRow()",{query:e,...t}),ds(e)?this.any(e,...t):this.fetchAny(e,...t)}async allRows(e,...t){return this.debugData("allRows()",{query:e,...t}),ds(e)?this.all(e,...t):this.fetchAll(e,...t)}async oneRecord(e,...t){return this.debugData("oneRecord()",{query:e,args:t}),ds(e)?this.one(e,t[0],this.withRecordOption(t[1])):this.fetchOne(e,this.withRecordOption(t[0]))}async anyRecord(e,...t){return this.debugData("anyRecord()",{query:e,args:t}),ds(e)?this.any(e,t[0],this.withRecordOption(t[1])):this.fetchAny(e,this.withRecordOption(t[0]))}async allRecords(e,...t){return this.debugData("allRecords()",{query:e,args:t}),ds(e)?this.all(e,t[0],this.withRecordOption(t[1])):this.fetchAll(e,this.withRecordOption(t[0]))}loaded(e,t={}){return t.record?this.record(e):e}loadedOne(e,t={}){return this.loaded(e,t)}loadedAny(e,t={}){return e?this.loaded(e,t):void 0}loadedAll(e,t={}){return Promise.all(e.map((e=>this.loaded(e,t))))}withReloadOption(e={}){return{...e,reload:!0}}withRecordOption(e={}){return{...e,record:!0}}checkColumnNames(e){const t=this.table;ae(e).forEach((e=>this.columns[e]||dt("unknown",{column:e,table:t})))}checkColumns(e={},t={},s=[],r=[]){this.debugData("checkColumns()",{data:e,options:t});const i=this.table;let n={};return Object.keys(e).forEach((a=>{const o=this.columns[a];o?(t.writable&&o.readonly&&dt("readonly",{column:a,table:i}),t.fixed&&o.fixed&&dt("fixed",{column:a,table:i}),s.push(o.column),r.push(e[a]),n[o.column]=e[a]):t.pick||dt("unknown",{column:a,table:i})})),this.debugData("checkColumns()",{cols:s,vals:r}),[s,r,n]}checkWritableColumns(e,t={}){return this.checkColumns(e,{...t,writable:!0})}checkUpdatableColumns(e,t={}){return this.checkColumns(e,{...t,writable:!0,fixed:!0})}checkWhereColumns(e,t){return this.checkColumns(e,t)}checkRequiredColumns(e){const t=this.table;this.required.forEach((s=>{se(e[s])&&dt("required",{column:s,table:t})}))}select(...e){return 0===e.length&&e.push({table:this.table,columns:Object.keys(this.columns)}),this.build.select(...e).from(this.table)}newRecord(e){return ys(new this.recordClass(this,e,this.recordConfig))}record(e){return this.debugData("record()",{row:e}),Promise.resolve(this.newRecord(e))}records(e){return this.debugData("records()",{rows:e}),Promise.resolve(e.map((e=>this.newRecord(e))))}tableFragments(){return this.tableFragments}identity(e){return this.keys.reduce(((t,s)=>(t[s]=e[s],t)),{})}}class vs{constructor(e={}){this.tables=e,It(this,"tables")}async table(e){const t=this.tables[e];return X(t)&&X(t.constructor)?{tableClass:t}:t}}class qs{constructor(e,t={}){this.engine=e||Ge("engine"),this.completed=!1,this.autoCommit=t.autoCommit,this.autoRollback=t.autoRollback,It(this,"transaction",t)}async run(e,t){this.debug("run()");const s=this.commit.bind(this),r=this.rollback.bind(this);try{await this.acquire(),await this.begin(),await t(e,s,r),this.debug("code complete"),this.completed||(this.autoCommit?(this.debug("autoCommit"),await this.commit()):this.autoRollback?(this.debug("autoRollback"),await this.rollback()):this.fail("Transaction was not committed or rolled back"))}catch(e){throw this.completed||(this.debug("caught error, rolling back transaction"),await this.rollback()),e}finally{await this.release()}}async acquire(){this.debug("acquire()"),this.connection&&this.fail("Transaction has already acquired a connection"),this.connection=await this.engine.acquire()}async release(){this.debug("release()"),this.connection||this.fail("Transaction does not have a connection to release"),await this.engine.release(this.connection),delete this.connection}async begin(){this.debug("begin()"),this.engine.begin(this)}async commit(){this.debug("commit()"),this.complete("commit"),await this.engine.commit(this)}async rollback(){this.debug("rollback()"),this.complete("rollback"),await this.engine.rollback(this)}complete(e){if(this.completed)throw new ct(`Cannot ${e} transaction - ${this.completed}() has already been called`);this.completed=e}fail(...e){throw new ct(e.join(""))}}function ks(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}const xs=e=>{if("object"==typeof e){const t=()=>e;return t.__proxy__=!0,new Proxy(t,Os)}return"function"==typeof e?new Proxy(e,Os):e},Os={construct:(e,t)=>(e.__proxy__&&(e=e()),xs(Reflect.construct(e,t))),get:(e,t,s)=>(e.__proxy__&&(e=e()),"then"!==t&&"catch"!==t&&"function"==typeof e.then?xs(e.then((e=>js(e,t,s)))):xs(js(e,t,s))),apply:(e,t,s)=>(e.__proxy__&&(e=e()),"function"==typeof e.then?xs(e.then((e=>Reflect.apply(e,t,s)))):xs(Reflect.apply(e,t,s)))},js=(e,t,s)=>{const r="object"==typeof e?Reflect.get(e,t,s):e[t];return"function"==typeof r&&"function"==typeof r.bind?Object.assign(r.bind(e),r):r};var Rs=ks(xs);const As=e=>new Proxy(e,{get:(e,t)=>"then"===t?Reflect.get(e,t):e.table(t)});var Ts={exports:{}},Cs={},Ms={},Es={};Object.defineProperty(Es,"__esModule",{value:!0});class Is extends Error{}Es.TimeoutError=Is;var Ds={},_s={};Object.defineProperty(_s,"__esModule",{value:!0});_s.PromiseInspection=class{constructor(e){this._value=e.value,this._error=e.error}value(){return this._value}reason(){return this._error}isRejected(){return!!this._error}isFulfilled(){return!!this._value}},Object.defineProperty(Ds,"__esModule",{value:!0});const Ps=_s;function Ls(e){return"number"==typeof e&&e===Math.round(e)&&e>0}Ds.defer=function(){let e=null,t=null;return{promise:new Promise(((s,r)=>{e=s,t=r})),resolve:e,reject:t}},Ds.now=function(){return Date.now()},Ds.duration=function(e,t){return Math.abs(t-e)},Ds.checkOptionalTime=function(e){return void 0===e||Ls(e)},Ds.checkRequiredTime=Ls,Ds.delay=function(e){return new Promise((t=>setTimeout(t,e)))},Ds.reflect=function(e){return e.then((e=>new Ps.PromiseInspection({value:e}))).catch((e=>new Ps.PromiseInspection({error:e})))},Ds.tryPromise=function(e){try{const t=e();return Promise.resolve(t)}catch(e){return Promise.reject(e)}},Object.defineProperty(Ms,"__esModule",{value:!0});const Vs=Es,$s=Ds;Ms.PendingOperation=class{constructor(e){var t,s;this.timeoutMillis=e,this.deferred=$s.defer(),this.possibleTimeoutCause=null,this.isRejected=!1,this.promise=(t=this.deferred.promise,s=e,new Promise(((e,r)=>{const i=setTimeout((()=>r(new Vs.TimeoutError)),s);t.then((t=>{clearTimeout(i),e(t)})).catch((e=>{clearTimeout(i),r(e)}))}))).catch((e=>(e instanceof Vs.TimeoutError&&(e=this.possibleTimeoutCause?new Vs.TimeoutError(this.possibleTimeoutCause.message):new Vs.TimeoutError("operation timed out for an unknown reason")),this.isRejected=!0,Promise.reject(e))))}abort(){this.reject(new Error("aborted"))}reject(e){this.deferred.reject(e)}resolve(e){this.deferred.resolve(e)}};var Ss={};Object.defineProperty(Ss,"__esModule",{value:!0});const Ns=Ds;class Bs{constructor(e){this.resource=e,this.resource=e,this.timestamp=Ns.now(),this.deferred=Ns.defer()}get promise(){return this.deferred.promise}resolve(){return this.deferred.resolve(void 0),new Bs(this.resource)}}Ss.Resource=Bs,Object.defineProperty(Cs,"__esModule",{value:!0});const Fs=Ms,Qs=Ss,Hs=Ds,Ws=e,Us=t;function Js(e,t){const s=e.indexOf(t);return-1!==s&&(e.splice(s,1),!0)}Cs.Pool=class{constructor(e){if(this.destroyed=!1,this.emitter=new Ws.EventEmitter,!(e=e||{}).create)throw new Error("Tarn: opt.create function most be provided");if(!e.destroy)throw new Error("Tarn: opt.destroy function most be provided");if("number"!=typeof e.min||e.min<0||e.min!==Math.round(e.min))throw new Error("Tarn: opt.min must be an integer >= 0");if("number"!=typeof e.max||e.max<=0||e.max!==Math.round(e.max))throw new Error("Tarn: opt.max must be an integer > 0");if(e.min>e.max)throw new Error("Tarn: opt.max is smaller than opt.min");if(!Hs.checkOptionalTime(e.acquireTimeoutMillis))throw new Error("Tarn: invalid opt.acquireTimeoutMillis "+JSON.stringify(e.acquireTimeoutMillis));if(!Hs.checkOptionalTime(e.createTimeoutMillis))throw new Error("Tarn: invalid opt.createTimeoutMillis "+JSON.stringify(e.createTimeoutMillis));if(!Hs.checkOptionalTime(e.destroyTimeoutMillis))throw new Error("Tarn: invalid opt.destroyTimeoutMillis "+JSON.stringify(e.destroyTimeoutMillis));if(!Hs.checkOptionalTime(e.idleTimeoutMillis))throw new Error("Tarn: invalid opt.idleTimeoutMillis "+JSON.stringify(e.idleTimeoutMillis));if(!Hs.checkOptionalTime(e.reapIntervalMillis))throw new Error("Tarn: invalid opt.reapIntervalMillis "+JSON.stringify(e.reapIntervalMillis));if(!Hs.checkOptionalTime(e.createRetryIntervalMillis))throw new Error("Tarn: invalid opt.createRetryIntervalMillis "+JSON.stringify(e.createRetryIntervalMillis));const t={create:!0,validate:!0,destroy:!0,log:!0,min:!0,max:!0,acquireTimeoutMillis:!0,createTimeoutMillis:!0,destroyTimeoutMillis:!0,idleTimeoutMillis:!0,reapIntervalMillis:!0,createRetryIntervalMillis:!0,propagateCreateError:!0};for(const s of Object.keys(e))if(!t[s])throw new Error(`Tarn: unsupported option opt.${s}`);this.creator=e.create,this.destroyer=e.destroy,this.validate="function"==typeof e.validate?e.validate:()=>!0,this.log=e.log||(()=>{}),this.acquireTimeoutMillis=e.acquireTimeoutMillis||3e4,this.createTimeoutMillis=e.createTimeoutMillis||3e4,this.destroyTimeoutMillis=e.destroyTimeoutMillis||5e3,this.idleTimeoutMillis=e.idleTimeoutMillis||3e4,this.reapIntervalMillis=e.reapIntervalMillis||1e3,this.createRetryIntervalMillis=e.createRetryIntervalMillis||200,this.propagateCreateError=!!e.propagateCreateError,this.min=e.min,this.max=e.max,this.used=[],this.free=[],this.pendingCreates=[],this.pendingAcquires=[],this.pendingDestroys=[],this.pendingValidations=[],this.destroyed=!1,this.interval=null,this.eventId=1}numUsed(){return this.used.length}numFree(){return this.free.length}numPendingAcquires(){return this.pendingAcquires.length}numPendingValidations(){return this.pendingValidations.length}numPendingCreates(){return this.pendingCreates.length}acquire(){const e=this.eventId++;this._executeEventHandlers("acquireRequest",e);const t=new Fs.PendingOperation(this.acquireTimeoutMillis);return this.pendingAcquires.push(t),t.promise=t.promise.then((t=>(this._executeEventHandlers("acquireSuccess",e,t),t))).catch((s=>(this._executeEventHandlers("acquireFail",e,s),Js(this.pendingAcquires,t),Promise.reject(s)))),this._tryAcquireOrCreate(),t}release(e){this._executeEventHandlers("release",e);for(let t=0,s=this.used.length;t<s;++t){const s=this.used[t];if(s.resource===e)return this.used.splice(t,1),this.free.push(s.resolve()),this._tryAcquireOrCreate(),!0}return!1}isEmpty(){return 0===[this.numFree(),this.numUsed(),this.numPendingAcquires(),this.numPendingValidations(),this.numPendingCreates()].reduce(((e,t)=>e+t))}check(){const e=Hs.now(),t=[],s=this.min-this.used.length,r=this.free.length-s;let i=0;this.free.forEach((s=>{Hs.duration(e,s.timestamp)>=this.idleTimeoutMillis&&i<r?(i++,this._destroy(s.resource)):t.push(s)})),this.free=t,this.isEmpty()&&this._stopReaping()}destroy(){const e=this.eventId++;return this._executeEventHandlers("poolDestroyRequest",e),this._stopReaping(),this.destroyed=!0,Hs.reflect(Promise.all(this.pendingCreates.map((e=>Hs.reflect(e.promise)))).then((()=>new Promise(((e,t)=>{if(0===this.numPendingValidations())return void e();const s=setInterval((()=>{0===this.numPendingValidations()&&(Us.clearInterval(s),e())}),100)})))).then((()=>Promise.all(this.used.map((e=>Hs.reflect(e.promise)))))).then((()=>Promise.all(this.pendingAcquires.map((e=>(e.abort(),Hs.reflect(e.promise))))))).then((()=>Promise.all(this.free.map((e=>Hs.reflect(this._destroy(e.resource))))))).then((()=>Promise.all(this.pendingDestroys.map((e=>e.promise))))).then((()=>{this.free=[],this.pendingAcquires=[]}))).then((t=>(this._executeEventHandlers("poolDestroySuccess",e),this.emitter.removeAllListeners(),t)))}on(e,t){this.emitter.on(e,t)}removeListener(e,t){this.emitter.removeListener(e,t)}removeAllListeners(e){this.emitter.removeAllListeners(e)}_tryAcquireOrCreate(){this.destroyed||(this._hasFreeResources()?this._doAcquire():this._shouldCreateMoreResources()&&this._doCreate())}_hasFreeResources(){return this.free.length>0}_doAcquire(){for(;this._canAcquire();){const e=this.pendingAcquires.shift(),t=this.free.pop();if(void 0===t||void 0===e){const e="this.free was empty while trying to acquire resource";throw this.log(`Tarn: ${e}`,"warn"),new Error(`Internal error, should never happen. ${e}`)}this.pendingValidations.push(e),this.used.push(t);const s=new Fs.PendingOperation(this.acquireTimeoutMillis);e.promise.catch((e=>{s.abort()})),s.promise.catch((e=>(this.log("Tarn: resource validator threw an exception "+e.stack,"warn"),!1))).then((s=>{try{s&&!e.isRejected?(this._star