UNPKG

@electric-sql/pglite

Version:

PGlite is a WASM Postgres build packaged into a TypeScript client library that enables you to run Postgres in the browser, Node.js and Bun, with no need to install any other dependencies. It is only 3.7mb gzipped.

10 lines 458 kB
"use strict";var ys=Object.create;var st=Object.defineProperty;var ws=Object.getOwnPropertyDescriptor;var bs=Object.getOwnPropertyNames;var Cs=Object.getPrototypeOf,Is=Object.prototype.hasOwnProperty;var sa=e=>{throw TypeError(e)};var Ps=(e,t,r)=>t in e?st(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var ot=(e,t)=>()=>(e&&(t=e(e=0)),t);var Be=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Ie=(e,t)=>{for(var r in t)st(e,r,{get:t[r],enumerable:!0})},oa=(e,t,r,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of bs(t))!Is.call(e,s)&&s!==r&&st(e,s,{get:()=>t[s],enumerable:!(a=ws(t,s))||a.enumerable});return e};var V=(e,t,r)=>(r=e!=null?ys(Cs(e)):{},oa(t||!e||!e.__esModule?st(r,"default",{value:e,enumerable:!0}):r,e)),Fs=e=>oa(st({},"__esModule",{value:!0}),e);var oe=(e,t,r)=>Ps(e,typeof t!="symbol"?t+"":t,r),pr=(e,t,r)=>t.has(e)||sa("Cannot "+r);var p=(e,t,r)=>(pr(e,t,"read from private field"),r?r.call(e):t.get(e)),v=(e,t,r)=>t.has(e)?sa("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),S=(e,t,r,a)=>(pr(e,t,"write to private field"),a?a.call(e,r):t.set(e,r),r),h=(e,t,r)=>(pr(e,t,"access private method"),r);var Pe=(e,t,r,a)=>({set _(s){S(e,t,s,r)},get _(){return p(e,t,a)}});var As,I,M=ot(()=>{"use strict";As=()=>typeof document>"u"?new URL(`file:${__filename}`).href:document.currentScript&&document.currentScript.src||new URL("main.js",document.baseURI).href,I=As()});var Ct=Be((Gi,J)=>{"use strict";M();var Na=9007199254740991,za=function(e){return e}();function sn(e){return e===za}function La(e){return typeof e=="string"||Object.prototype.toString.call(e)=="[object String]"}function on(e){return Object.prototype.toString.call(e)=="[object Date]"}function er(e){return e!==null&&typeof e=="object"}function tr(e){return typeof e=="function"}function nn(e){return typeof e=="number"&&e>-1&&e%1==0&&e<=Na}function ln(e){return Object.prototype.toString.call(e)=="[object Array]"}function Oa(e){return er(e)&&!tr(e)&&nn(e.length)}function Br(e){return Object.prototype.toString.call(e)=="[object ArrayBuffer]"}function _n(e,t){return Array.prototype.map.call(e,t)}function mn(e,t){var r=za;return tr(t)&&Array.prototype.every.call(e,function(a,s,o){var n=t(a,s,o);return n&&(r=a),!n}),r}function pn(e){return Object.assign.apply(null,arguments)}function Ba(e){var t,r,a;if(La(e)){for(r=e.length,a=new Uint8Array(r),t=0;t<r;t++)a[t]=e.charCodeAt(t)&255;return a}return Br(e)?new Uint8Array(e):er(e)&&Br(e.buffer)?new Uint8Array(e.buffer):Oa(e)?new Uint8Array(e):er(e)&&tr(e.toString)?Ba(e.toString()):new Uint8Array}J.exports.MAX_SAFE_INTEGER=Na;J.exports.isUndefined=sn;J.exports.isString=La;J.exports.isObject=er;J.exports.isDateTime=on;J.exports.isFunction=tr;J.exports.isArray=ln;J.exports.isArrayLike=Oa;J.exports.isArrayBuffer=Br;J.exports.map=_n;J.exports.find=mn;J.exports.extend=pn;J.exports.toUint8Array=Ba});var It=Be((Xi,Ga)=>{"use strict";M();var Gr="\0";Ga.exports={NULL_CHAR:Gr,TMAGIC:"ustar"+Gr+"00",OLDGNU_MAGIC:"ustar "+Gr,REGTYPE:0,LNKTYPE:1,SYMTYPE:2,CHRTYPE:3,BLKTYPE:4,DIRTYPE:5,FIFOTYPE:6,CONTTYPE:7,TSUID:parseInt("4000",8),TSGID:parseInt("2000",8),TSVTX:parseInt("1000",8),TUREAD:parseInt("0400",8),TUWRITE:parseInt("0200",8),TUEXEC:parseInt("0100",8),TGREAD:parseInt("0040",8),TGWRITE:parseInt("0020",8),TGEXEC:parseInt("0010",8),TOREAD:parseInt("0004",8),TOWRITE:parseInt("0002",8),TOEXEC:parseInt("0001",8),TPERMALL:parseInt("0777",8),TPERMMASK:parseInt("0777",8)}});var Wr=Be((ji,$)=>{"use strict";M();var Ha=Ct(),O=It(),dn=512,Hr=O.TPERMALL,Xa=0,Wa=0,Xr=[["name",100,0,function(e,t){return Pt(e[t[0]],t[1])},function(e,t,r){return De(e.slice(t,t+r[1]))}],["mode",8,100,function(e,t){var r=e[t[0]]||Hr;return r=r&O.TPERMMASK,Ve(r,t[1],Hr)},function(e,t,r){var a=ce(e.slice(t,t+r[1]));return a&=O.TPERMMASK,a}],["uid",8,108,function(e,t){return Ve(e[t[0]],t[1],Xa)},function(e,t,r){return ce(e.slice(t,t+r[1]))}],["gid",8,116,function(e,t){return Ve(e[t[0]],t[1],Wa)},function(e,t,r){return ce(e.slice(t,t+r[1]))}],["size",12,124,function(e,t){return Ve(e.data.length,t[1])},function(e,t,r){return ce(e.slice(t,t+r[1]))}],["modifyTime",12,136,function(e,t){return rr(e[t[0]],t[1])},function(e,t,r){return ar(e.slice(t,t+r[1]))}],["checksum",8,148,function(e,t){return" "},function(e,t,r){return ce(e.slice(t,t+r[1]))}],["type",1,156,function(e,t){return""+(parseInt(e[t[0]],10)||0)%8},function(e,t,r){return(parseInt(String.fromCharCode(e[t]),10)||0)%8}],["linkName",100,157,function(e,t){return""},function(e,t,r){return De(e.slice(t,t+r[1]))}],["ustar",8,257,function(e,t){return O.TMAGIC},function(e,t,r){return un(De(e.slice(t,t+r[1]),!0))},function(e,t){return e[t[0]]==O.TMAGIC||e[t[0]]==O.OLDGNU_MAGIC}],["owner",32,265,function(e,t){return Pt(e[t[0]],t[1])},function(e,t,r){return De(e.slice(t,t+r[1]))}],["group",32,297,function(e,t){return Pt(e[t[0]],t[1])},function(e,t,r){return De(e.slice(t,t+r[1]))}],["majorNumber",8,329,function(e,t){return""},function(e,t,r){return ce(e.slice(t,t+r[1]))}],["minorNumber",8,337,function(e,t){return""},function(e,t,r){return ce(e.slice(t,t+r[1]))}],["prefix",131,345,function(e,t){return Pt(e[t[0]],t[1])},function(e,t,r){return De(e.slice(t,t+r[1]))}],["accessTime",12,476,function(e,t){return rr(e[t[0]],t[1])},function(e,t,r){return ar(e.slice(t,t+r[1]))}],["createTime",12,488,function(e,t){return rr(e[t[0]],t[1])},function(e,t,r){return ar(e.slice(t,t+r[1]))}]],ja=function(e){var t=e[e.length-1];return t[2]+t[1]}(Xr);function un(e){if(e.length==8){var t=e.split("");if(t[5]==O.NULL_CHAR)return(t[6]==" "||t[6]==O.NULL_CHAR)&&(t[6]="0"),(t[7]==" "||t[7]==O.NULL_CHAR)&&(t[7]="0"),t=t.join(""),t==O.TMAGIC?t:e;if(t[7]==O.NULL_CHAR)return t[5]==O.NULL_CHAR&&(t[5]=" "),t[6]==O.NULL_CHAR&&(t[6]=" "),t==O.OLDGNU_MAGIC?t:e}return e}function Pt(e,t){return t-=1,Ha.isUndefined(e)&&(e=""),e=(""+e).substr(0,t),e+O.NULL_CHAR}function Ve(e,t,r){for(r=parseInt(r)||0,t-=1,e=(parseInt(e)||r).toString(8).substr(-t,t);e.length<t;)e="0"+e;return e+O.NULL_CHAR}function rr(e,t){if(Ha.isDateTime(e))e=Math.floor(1*e/1e3);else if(e=parseInt(e,10),isFinite(e)){if(e<=0)return""}else e=Math.floor(1*new Date/1e3);return Ve(e,t,0)}function De(e,t){var r=String.fromCharCode.apply(null,e);if(t)return r;var a=r.indexOf(O.NULL_CHAR);return a>=0?r.substr(0,a):r}function ce(e){var t=String.fromCharCode.apply(null,e);return parseInt(t.replace(/^0+$/g,""),8)||0}function ar(e){return e.length==0||e[0]==0?null:new Date(1e3*ce(e))}function cn(e,t,r){var a=parseInt(t,10)||0,s=Math.min(a+ja,e.length),o=0,n=0,l=0;r&&Xr.every(function(u){return u[0]=="checksum"?(n=a+u[2],l=n+u[1],!1):!0});for(var _=32,m=a;m<s;m++){var d=m>=n&&m<l?_:e[m];o=(o+d)%262144}return o}$.exports.recordSize=dn;$.exports.defaultFileMode=Hr;$.exports.defaultUid=Xa;$.exports.defaultGid=Wa;$.exports.posixHeader=Xr;$.exports.effectiveHeaderSize=ja;$.exports.calculateChecksum=cn;$.exports.formatTarString=Pt;$.exports.formatTarNumber=Ve;$.exports.formatTarDateTime=rr;$.exports.parseTarString=De;$.exports.parseTarNumber=ce;$.exports.parseTarDateTime=ar});var Ya=Be((Ki,Qa)=>{"use strict";M();var gn=It(),sr=Ct(),Se=Wr();function Va(e){return Se.recordSize}function Ka(e){return Math.ceil(e.data.length/Se.recordSize)*Se.recordSize}function fn(e){var t=0;return e.forEach(function(r){t+=Va(r)+Ka(r)}),t+=Se.recordSize*2,new Uint8Array(t)}function hn(e,t,r){r=parseInt(r)||0;var a=r;Se.posixHeader.forEach(function(_){for(var m=_[3](t,_),d=m.length,u=0;u<d;u+=1)e[a+u]=m.charCodeAt(u)&255;a+=_[1]});var s=sr.find(Se.posixHeader,function(_){return _[0]=="checksum"});if(s){var o=Se.calculateChecksum(e,r,!0),n=Se.formatTarNumber(o,s[1]-2)+gn.NULL_CHAR+" ";a=r+s[2];for(var l=0;l<n.length;l+=1)e[a]=n.charCodeAt(l)&255,a++}return r+Va(t)}function xn(e,t,r){return r=parseInt(r,10)||0,e.set(t.data,r),r+Ka(t)}function Mn(e){e=sr.map(e,function(a){return sr.extend({},a,{data:sr.toUint8Array(a.data)})});var t=fn(e),r=0;return e.forEach(function(a){r=hn(t,a,r),r=xn(t,a,r)}),t}Qa.exports.tar=Mn});var $a=Be((Yi,Ja)=>{"use strict";M();var Sn=It(),Vr=Ct(),le=Wr(),vn={extractData:!0,checkHeader:!0,checkChecksum:!0,checkFileSize:!0},En={size:!0,checksum:!0,ustar:!0},jr={unexpectedEndOfFile:"Unexpected end of file.",fileCorrupted:"File is corrupted.",checksumCheckFailed:"Checksum check failed."};function yn(e){return le.recordSize}function wn(e){return Math.ceil(e/le.recordSize)*le.recordSize}function bn(e,t){for(var r=t,a=Math.min(e.length,t+le.recordSize*2),s=r;s<a;s++)if(e[s]!=0)return!1;return!0}function Cn(e,t,r){if(e.length-t<le.recordSize){if(r.checkFileSize)throw new Error(jr.unexpectedEndOfFile);return null}t=parseInt(t)||0;var a={},s=t;if(le.posixHeader.forEach(function(l){a[l[0]]=l[4](e,s,l),s+=l[1]}),a.type!=0&&(a.size=0),r.checkHeader&&le.posixHeader.forEach(function(l){if(Vr.isFunction(l[5])&&!l[5](a,l)){var _=new Error(jr.fileCorrupted);throw _.data={offset:t+l[2],field:l[0]},_}}),r.checkChecksum){var o=le.calculateChecksum(e,t,!0);if(o!=a.checksum){var n=new Error(jr.checksumCheckFailed);throw n.data={offset:t,header:a,checksum:o},n}}return a}function In(e,t,r,a){return a.extractData?r.size<=0?new Uint8Array:e.slice(t,t+r.size):null}function Pn(e,t){var r={};return le.posixHeader.forEach(function(a){var s=a[0];En[s]||(r[s]=e[s])}),r.isOldGNUFormat=e.ustar==Sn.OLDGNU_MAGIC,t&&(r.data=t),r}function Fn(e,t){t=Vr.extend({},vn,t);for(var r=[],a=0,s=e.length;s-a>=le.recordSize;){e=Vr.toUint8Array(e);var o=Cn(e,a,t);if(!o)break;a+=yn(o);var n=In(e,a,o,t);if(r.push(Pn(o,n)),a+=wn(o.size),bn(e,a))break}return r}Ja.exports.untar=Fn});var Kr=Be(($i,Za)=>{"use strict";M();var An=Ct(),kn=It(),Tn=Ya(),Un=$a();An.extend(Za.exports,Tn,Un,kn)});async function Jr(e,t,r="pgdata",a="auto"){let s=zn(e,t),[o,n]=await Ln(s,a),l=r+(n?".tar.gz":".tar"),_=n?"application/x-gzip":"application/x-tar";return typeof File<"u"?new File([o],l,{type:_}):new Blob([o],{type:_})}async function _s(e,t,r){let a=new Uint8Array(await t.arrayBuffer()),s=typeof File<"u"&&t instanceof File?t.name:void 0;(qn.includes(t.type)||s?.endsWith(".tgz")||s?.endsWith(".tar.gz"))&&(a=await is(a));let n;try{n=(0,ne.untar)(a)}catch(l){if(l instanceof Error&&l.message.includes("File is corrupted"))a=await is(a),n=(0,ne.untar)(a);else throw l}for(let l of n){let _=r+l.name,m=_.split("/").slice(0,-1);for(let d=1;d<=m.length;d++){let u=m.slice(0,d).join("/");e.analyzePath(u).exists||e.mkdir(u)}l.type===ne.REGTYPE?(e.writeFile(_,l.data),e.utime(_,ls(l.modifyTime),ls(l.modifyTime))):l.type===ne.DIRTYPE&&e.mkdir(_)}}function Nn(e,t){let r=[],a=s=>{e.readdir(s).forEach(n=>{if(n==="."||n==="..")return;let l=s+"/"+n,_=e.stat(l),m=e.isFile(_.mode)?e.readFile(l,{encoding:"binary"}):new Uint8Array(0);r.push({name:l.substring(t.length),mode:_.mode,size:_.size,type:e.isFile(_.mode)?ne.REGTYPE:ne.DIRTYPE,modifyTime:_.mtime,data:m}),e.isDir(_.mode)&&a(l)})};return a(t),r}function zn(e,t){let r=Nn(e,t);return(0,ne.tar)(r)}async function Ln(e,t="auto"){if(t==="none")return[e,!1];if(typeof CompressionStream<"u")return[await On(e),!0];if(typeof process<"u"&&process.versions&&process.versions.node)return[await Bn(e),!0];if(t==="auto")return[e,!1];throw new Error("Compression not supported in this environment")}async function On(e){let t=new CompressionStream("gzip"),r=t.writable.getWriter(),a=t.readable.getReader();r.write(e),r.close();let s=[];for(;;){let{value:l,done:_}=await a.read();if(_)break;l&&s.push(l)}let o=new Uint8Array(s.reduce((l,_)=>l+_.length,0)),n=0;return s.forEach(l=>{o.set(l,n),n+=l.length}),o}async function Bn(e){let{promisify:t}=await import("util"),{gzip:r}=await import("zlib");return await t(r)(e)}async function is(e){if(typeof CompressionStream<"u")return await Gn(e);if(typeof process<"u"&&process.versions&&process.versions.node)return await Hn(e);throw new Error("Unsupported environment for decompression")}async function Gn(e){let t=new DecompressionStream("gzip"),r=t.writable.getWriter(),a=t.readable.getReader();r.write(e),r.close();let s=[];for(;;){let{value:l,done:_}=await a.read();if(_)break;l&&s.push(l)}let o=new Uint8Array(s.reduce((l,_)=>l+_.length,0)),n=0;return s.forEach(l=>{o.set(l,n),n+=l.length}),o}async function Hn(e){let{promisify:t}=await import("util"),{gunzip:r}=await import("zlib");return await t(r)(e)}function ls(e){return e?typeof e=="number"?e:Math.floor(e.getTime()/1e3):Math.floor(Date.now()/1e3)}var ne,qn,$r=ot(()=>{"use strict";M();ne=V(Kr(),1);qn=["application/x-gtar","application/x-tar+gzip","application/x-gzip","application/gzip"]});var Ut,Q,ve,kt,Tt,Xn,Qe=ot(()=>{"use strict";M();$r();Ut="/tmp/pglite",Q=Ut+"/base",ve=class{constructor(t){this.dataDir=t}async init(t,r){return this.pg=t,{emscriptenOpts:r}}async syncToFs(t){}async initialSyncFs(){}async closeFs(){}async dumpTar(t,r){return Jr(this.pg.Module.FS,Q,t,r)}},kt=class{constructor(t,{debug:r=!1}={}){this.dataDir=t,this.debug=r}async syncToFs(t){}async initialSyncFs(){}async closeFs(){}async dumpTar(t,r){return Jr(this.pg.Module.FS,Q,t,r)}async init(t,r){return this.pg=t,{emscriptenOpts:{...r,preRun:[...r.preRun||[],s=>{let o=Xn(s,this);s.FS.mkdir(Q),s.FS.mount(o,{},Q)}]}}}},Tt={EBADF:8,EBADFD:127,EEXIST:20,EINVAL:28,EISDIR:31,ENODEV:43,ENOENT:44,ENOTDIR:54,ENOTEMPTY:55},Xn=(e,t)=>{let r=e.FS,a=t.debug?console.log:null,s={tryFSOperation(o){try{return o()}catch(n){throw n.code?n.code==="UNKNOWN"?new r.ErrnoError(Tt.EINVAL):new r.ErrnoError(n.code):n}},mount(o){return s.createNode(null,"/",16895,0)},syncfs(o,n,l){},createNode(o,n,l,_){if(!r.isDir(l)&&!r.isFile(l))throw new r.ErrnoError(28);let m=r.createNode(o,n,l);return m.node_ops=s.node_ops,m.stream_ops=s.stream_ops,m},getMode:function(o){return a?.("getMode",o),s.tryFSOperation(()=>t.lstat(o).mode)},realPath:function(o){let n=[];for(;o.parent!==o;)n.push(o.name),o=o.parent;return n.push(o.mount.opts.root),n.reverse(),n.join("/")},node_ops:{getattr(o){a?.("getattr",s.realPath(o));let n=s.realPath(o);return s.tryFSOperation(()=>{let l=t.lstat(n);return{...l,dev:0,ino:o.id,nlink:1,rdev:o.rdev,atime:new Date(l.atime),mtime:new Date(l.mtime),ctime:new Date(l.ctime)}})},setattr(o,n){a?.("setattr",s.realPath(o),n);let l=s.realPath(o);s.tryFSOperation(()=>{n.mode!==void 0&&t.chmod(l,n.mode),n.size!==void 0&&t.truncate(l,n.size),n.timestamp!==void 0&&t.utimes(l,n.timestamp,n.timestamp),n.size!==void 0&&t.truncate(l,n.size)})},lookup(o,n){a?.("lookup",s.realPath(o),n);let l=[s.realPath(o),n].join("/"),_=s.getMode(l);return s.createNode(o,n,_)},mknod(o,n,l,_){a?.("mknod",s.realPath(o),n,l,_);let m=s.createNode(o,n,l,_),d=s.realPath(m);return s.tryFSOperation(()=>(r.isDir(m.mode)?t.mkdir(d,{mode:l}):t.writeFile(d,"",{mode:l}),m))},rename(o,n,l){a?.("rename",s.realPath(o),s.realPath(n),l);let _=s.realPath(o),m=[s.realPath(n),l].join("/");s.tryFSOperation(()=>{t.rename(_,m)}),o.name=l},unlink(o,n){a?.("unlink",s.realPath(o),n);let l=[s.realPath(o),n].join("/");try{t.unlink(l)}catch{}},rmdir(o,n){a?.("rmdir",s.realPath(o),n);let l=[s.realPath(o),n].join("/");return s.tryFSOperation(()=>{t.rmdir(l)})},readdir(o){a?.("readdir",s.realPath(o));let n=s.realPath(o);return s.tryFSOperation(()=>t.readdir(n))},symlink(o,n,l){throw a?.("symlink",s.realPath(o),n,l),new r.ErrnoError(63)},readlink(o){throw a?.("readlink",s.realPath(o)),new r.ErrnoError(63)}},stream_ops:{open(o){a?.("open stream",s.realPath(o.node));let n=s.realPath(o.node);return s.tryFSOperation(()=>{r.isFile(o.node.mode)&&(o.shared.refcount=1,o.nfd=t.open(n))})},close(o){return a?.("close stream",s.realPath(o.node)),s.tryFSOperation(()=>{r.isFile(o.node.mode)&&o.nfd&&--o.shared.refcount===0&&t.close(o.nfd)})},dup(o){a?.("dup stream",s.realPath(o.node)),o.shared.refcount++},read(o,n,l,_,m){return a?.("read stream",s.realPath(o.node),l,_,m),_===0?0:s.tryFSOperation(()=>t.read(o.nfd,n,l,_,m))},write(o,n,l,_,m){return a?.("write stream",s.realPath(o.node),l,_,m),s.tryFSOperation(()=>t.write(o.nfd,n.buffer,l,_,m))},llseek(o,n,l){a?.("llseek stream",s.realPath(o.node),n,l);let _=n;if(l===1?_+=o.position:l===2&&r.isFile(o.node.mode)&&s.tryFSOperation(()=>{let m=t.fstat(o.nfd);_+=m.size}),_<0)throw new r.ErrnoError(28);return _},mmap(o,n,l,_,m){if(a?.("mmap stream",s.realPath(o.node),n,l,_,m),!r.isFile(o.node.mode))throw new r.ErrnoError(Tt.ENODEV);let d=e.mmapAlloc(n);return s.stream_ops.read(o,e.HEAP8,d,n,l),{ptr:d,allocated:!0}},msync(o,n,l,_,m){return a?.("msync stream",s.realPath(o.node),l,_,m),s.stream_ops.write(o,n,0,_,l),0}}};return s}});var ms={};Ie(ms,{NodeFS:()=>Zr});var or,nr,Zr,ps=ot(()=>{"use strict";M();or=V(require("fs"),1),nr=V(require("path"),1);Qe();Zr=class extends ve{constructor(t){super(t),this.rootDir=nr.resolve(t),or.existsSync(nr.join(this.rootDir))||or.mkdirSync(this.rootDir)}async init(t,r){return this.pg=t,{emscriptenOpts:{...r,preRun:[...r.preRun||[],s=>{let o=s.FS.filesystems.NODEFS;s.FS.mkdir(Q),s.FS.mount(o,{root:this.rootDir},Q)}]}}}async closeFs(){this.pg.Module.FS.quit()}}});var cs={};Ie(cs,{OpfsAhpFS:()=>ta});var Wn,jn,ea,Dt,Ze,Ee,qt,B,ge,W,Nt,ye,we,me,E,ds,qe,$e,_e,X,Rt,us,ra,ta,q,gs=ot(()=>{"use strict";M();Qe();Wn="state.txt",jn="data",ea={DIR:16384,FILE:32768},ta=class extends kt{constructor(r,{initialPoolSize:a=1e3,maintainedPoolSize:s=100,debug:o=!1}={}){super(r,{debug:o});v(this,E);v(this,Dt);v(this,Ze);v(this,Ee);v(this,qt);v(this,B);v(this,ge,new Map);v(this,W,new Map);v(this,Nt,0);v(this,ye,new Map);v(this,we,new Map);this.lastCheckpoint=0;this.checkpointInterval=1e3*60;this.poolCounter=0;v(this,me,new Set);this.initialPoolSize=a,this.maintainedPoolSize=s}async init(r,a){return await h(this,E,ds).call(this),super.init(r,a)}async syncToFs(r=!1){await this.maybeCheckpointState(),await this.maintainPool(),r||this.flush()}async closeFs(){for(let r of p(this,W).values())r.close();p(this,B).flush(),p(this,B).close(),this.pg.Module.FS.quit()}async maintainPool(r){r=r||this.maintainedPoolSize;let a=r-this.state.pool.length,s=[];for(let o=0;o<a;o++)s.push(new Promise(async n=>{++this.poolCounter;let l=`${(Date.now()-1704063600).toString(16).padStart(8,"0")}-${this.poolCounter.toString(16).padStart(8,"0")}`,_=await p(this,Ee).getFileHandle(l,{create:!0}),m=await _.createSyncAccessHandle();p(this,ge).set(l,_),p(this,W).set(l,m),h(this,E,$e).call(this,{opp:"createPoolFile",args:[l]}),this.state.pool.push(l),n()}));for(let o=0;o>a;o--)s.push(new Promise(async n=>{let l=this.state.pool.pop();h(this,E,$e).call(this,{opp:"deletePoolFile",args:[l]});let _=p(this,ge).get(l);p(this,W).get(l)?.close(),await p(this,Ee).removeEntry(_.name),p(this,ge).delete(l),p(this,W).delete(l),n()}));await Promise.all(s)}_createPoolFileState(r){this.state.pool.push(r)}_deletePoolFileState(r){let a=this.state.pool.indexOf(r);a>-1&&this.state.pool.splice(a,1)}async maybeCheckpointState(){Date.now()-this.lastCheckpoint>this.checkpointInterval&&await this.checkpointState()}async checkpointState(){let r=new TextEncoder().encode(JSON.stringify(this.state));p(this,B).truncate(0),p(this,B).write(r,{at:0}),p(this,B).flush(),this.lastCheckpoint=Date.now()}flush(){for(let r of p(this,me))try{r.flush()}catch{}p(this,me).clear()}chmod(r,a){h(this,E,qe).call(this,{opp:"chmod",args:[r,a]},()=>{this._chmodState(r,a)})}_chmodState(r,a){let s=h(this,E,X).call(this,r);s.mode=a}close(r){let a=h(this,E,Rt).call(this,r);p(this,ye).delete(r),p(this,we).delete(a)}fstat(r){let a=h(this,E,Rt).call(this,r);return this.lstat(a)}lstat(r){let a=h(this,E,X).call(this,r),s=a.type==="file"?p(this,W).get(a.backingFilename).getSize():0,o=4096;return{dev:0,ino:0,mode:a.mode,nlink:1,uid:0,gid:0,rdev:0,size:s,blksize:o,blocks:Math.ceil(s/o),atime:a.lastModified,mtime:a.lastModified,ctime:a.lastModified}}mkdir(r,a){h(this,E,qe).call(this,{opp:"mkdir",args:[r,a]},()=>{this._mkdirState(r,a)})}_mkdirState(r,a){let s=h(this,E,_e).call(this,r),o=s.pop(),n=[],l=this.state.root;for(let m of s){if(n.push(r),!Object.prototype.hasOwnProperty.call(l.children,m))if(a?.recursive)this.mkdir(n.join("/"));else throw new q("ENOENT","No such file or directory");if(l.children[m].type!=="directory")throw new q("ENOTDIR","Not a directory");l=l.children[m]}if(Object.prototype.hasOwnProperty.call(l.children,o))throw new q("EEXIST","File exists");let _={type:"directory",lastModified:Date.now(),mode:a?.mode||ea.DIR,children:{}};l.children[o]=_}open(r,a,s){if(h(this,E,X).call(this,r).type!=="file")throw new q("EISDIR","Is a directory");let n=h(this,E,us).call(this);return p(this,ye).set(n,r),p(this,we).set(r,n),n}readdir(r){let a=h(this,E,X).call(this,r);if(a.type!=="directory")throw new q("ENOTDIR","Not a directory");return Object.keys(a.children)}read(r,a,s,o,n){let l=h(this,E,Rt).call(this,r),_=h(this,E,X).call(this,l);if(_.type!=="file")throw new q("EISDIR","Is a directory");return p(this,W).get(_.backingFilename).read(new Uint8Array(a.buffer,s,o),{at:n})}rename(r,a){h(this,E,qe).call(this,{opp:"rename",args:[r,a]},()=>{this._renameState(r,a,!0)})}_renameState(r,a,s=!1){let o=h(this,E,_e).call(this,r),n=o.pop(),l=h(this,E,X).call(this,o.join("/"));if(!Object.prototype.hasOwnProperty.call(l.children,n))throw new q("ENOENT","No such file or directory");let _=h(this,E,_e).call(this,a),m=_.pop(),d=h(this,E,X).call(this,_.join("/"));if(s&&Object.prototype.hasOwnProperty.call(d.children,m)){let u=d.children[m];p(this,W).get(u.backingFilename).truncate(0),this.state.pool.push(u.backingFilename)}d.children[m]=l.children[n],delete l.children[n]}rmdir(r){h(this,E,qe).call(this,{opp:"rmdir",args:[r]},()=>{this._rmdirState(r)})}_rmdirState(r){let a=h(this,E,_e).call(this,r),s=a.pop(),o=h(this,E,X).call(this,a.join("/"));if(!Object.prototype.hasOwnProperty.call(o.children,s))throw new q("ENOENT","No such file or directory");let n=o.children[s];if(n.type!=="directory")throw new q("ENOTDIR","Not a directory");if(Object.keys(n.children).length>0)throw new q("ENOTEMPTY","Directory not empty");delete o.children[s]}truncate(r,a=0){let s=h(this,E,X).call(this,r);if(s.type!=="file")throw new q("EISDIR","Is a directory");let o=p(this,W).get(s.backingFilename);if(!o)throw new q("ENOENT","No such file or directory");o.truncate(a),p(this,me).add(o)}unlink(r){h(this,E,qe).call(this,{opp:"unlink",args:[r]},()=>{this._unlinkState(r,!0)})}_unlinkState(r,a=!1){let s=h(this,E,_e).call(this,r),o=s.pop(),n=h(this,E,X).call(this,s.join("/"));if(!Object.prototype.hasOwnProperty.call(n.children,o))throw new q("ENOENT","No such file or directory");let l=n.children[o];if(l.type!=="file")throw new q("EISDIR","Is a directory");if(delete n.children[o],a){let _=p(this,W).get(l.backingFilename);_?.truncate(0),p(this,me).add(_),p(this,we).has(r)&&(p(this,ye).delete(p(this,we).get(r)),p(this,we).delete(r))}this.state.pool.push(l.backingFilename)}utimes(r,a,s){h(this,E,qe).call(this,{opp:"utimes",args:[r,a,s]},()=>{this._utimesState(r,a,s)})}_utimesState(r,a,s){let o=h(this,E,X).call(this,r);o.lastModified=s}writeFile(r,a,s){let o=h(this,E,_e).call(this,r),n=o.pop(),l=h(this,E,X).call(this,o.join("/"));if(Object.prototype.hasOwnProperty.call(l.children,n)){let d=l.children[n];d.lastModified=Date.now(),h(this,E,$e).call(this,{opp:"setLastModified",args:[r,d.lastModified]})}else{if(this.state.pool.length===0)throw new Error("No more file handles available in the pool");let d={type:"file",lastModified:Date.now(),mode:s?.mode||ea.FILE,backingFilename:this.state.pool.pop()};l.children[n]=d,h(this,E,$e).call(this,{opp:"createFileNode",args:[r,d]})}let _=l.children[n],m=p(this,W).get(_.backingFilename);a.length>0&&(m.write(typeof a=="string"?new TextEncoder().encode(a):new Uint8Array(a),{at:0}),r.startsWith("/pg_wal")&&p(this,me).add(m))}_createFileNodeState(r,a){let s=h(this,E,_e).call(this,r),o=s.pop(),n=h(this,E,X).call(this,s.join("/"));n.children[o]=a;let l=this.state.pool.indexOf(a.backingFilename);return l>-1&&this.state.pool.splice(l,1),a}_setLastModifiedState(r,a){let s=h(this,E,X).call(this,r);s.lastModified=a}write(r,a,s,o,n){let l=h(this,E,Rt).call(this,r),_=h(this,E,X).call(this,l);if(_.type!=="file")throw new q("EISDIR","Is a directory");let m=p(this,W).get(_.backingFilename);if(!m)throw new q("EBADF","Bad file descriptor");let d=m.write(new Uint8Array(a,s,o),{at:n});return l.startsWith("/pg_wal")&&p(this,me).add(m),d}};Dt=new WeakMap,Ze=new WeakMap,Ee=new WeakMap,qt=new WeakMap,B=new WeakMap,ge=new WeakMap,W=new WeakMap,Nt=new WeakMap,ye=new WeakMap,we=new WeakMap,me=new WeakMap,E=new WeakSet,ds=async function(){S(this,Dt,await navigator.storage.getDirectory()),S(this,Ze,await h(this,E,ra).call(this,this.dataDir,{create:!0})),S(this,Ee,await h(this,E,ra).call(this,jn,{from:p(this,Ze),create:!0})),S(this,qt,await p(this,Ze).getFileHandle(Wn,{create:!0})),S(this,B,await p(this,qt).createSyncAccessHandle());let r=new ArrayBuffer(p(this,B).getSize());p(this,B).read(r,{at:0});let a,s=new TextDecoder().decode(r).split(` `),o=!1;try{a=JSON.parse(s[0])}catch{a={root:{type:"directory",lastModified:Date.now(),mode:ea.DIR,children:{}},pool:[]},p(this,B).truncate(0),p(this,B).write(new TextEncoder().encode(JSON.stringify(a)),{at:0}),o=!0}this.state=a;let n=s.slice(1).filter(Boolean).map(d=>JSON.parse(d));for(let d of n){let u=`_${d.opp}State`;if(typeof this[u]=="function")try{this[u].bind(this)(...d.args)}catch(c){console.warn("Error applying OPFS AHP WAL entry",d,c)}}let l=[],_=async d=>{if(d.type==="file")try{let u=await p(this,Ee).getFileHandle(d.backingFilename),c=await u.createSyncAccessHandle();p(this,ge).set(d.backingFilename,u),p(this,W).set(d.backingFilename,c)}catch(u){console.error("Error opening file handle for node",d,u)}else for(let u of Object.values(d.children))l.push(_(u))};await _(this.state.root);let m=[];for(let d of this.state.pool)m.push(new Promise(async u=>{p(this,ge).has(d)&&console.warn("File handle already exists for pool file",d);let c=await p(this,Ee).getFileHandle(d),g=await c.createSyncAccessHandle();p(this,ge).set(d,c),p(this,W).set(d,g),u()}));await Promise.all([...l,...m]),await this.maintainPool(o?this.initialPoolSize:this.maintainedPoolSize)},qe=function(r,a){let s=h(this,E,$e).call(this,r);try{a()}catch(o){throw p(this,B).truncate(s),o}},$e=function(r){let a=JSON.stringify(r),s=new TextEncoder().encode(` ${a}`),o=p(this,B).getSize();return p(this,B).write(s,{at:o}),p(this,me).add(p(this,B)),o},_e=function(r){return r.split("/").filter(Boolean)},X=function(r,a){let s=h(this,E,_e).call(this,r),o=a||this.state.root;for(let n of s){if(o.type!=="directory")throw new q("ENOTDIR","Not a directory");if(!Object.prototype.hasOwnProperty.call(o.children,n))throw new q("ENOENT","No such file or directory");o=o.children[n]}return o},Rt=function(r){let a=p(this,ye).get(r);if(!a)throw new q("EBADF","Bad file descriptor");return a},us=function(){let r=++Pe(this,Nt)._;for(;p(this,ye).has(r);)Pe(this,Nt)._++;return r},ra=async function(r,a){let s=h(this,E,_e).call(this,r),o=a?.from||p(this,Dt);for(let n of s)o=await o.getDirectoryHandle(n,{create:a?.create});return o};q=class extends Error{constructor(t,r){super(r),typeof t=="number"?this.code=t:typeof t=="string"&&(this.code=Tt[t])}}});var Kn={};Ie(Kn,{IdbFs:()=>Ye,MemoryFS:()=>Je,Mutex:()=>he,PGlite:()=>aa,formatQuery:()=>ss,messages:()=>yt,parse:()=>br,protocol:()=>Lr,types:()=>wr,uuid:()=>as});module.exports=Fs(Kn);M();M();M();var Jn=new Error("timeout while waiting for mutex to become available"),$n=new Error("mutex already locked"),ks=new Error("request for lock canceled"),Ts=function(e,t,r,a){function s(o){return o instanceof r?o:new r(function(n){n(o)})}return new(r||(r=Promise))(function(o,n){function l(d){try{m(a.next(d))}catch(u){n(u)}}function _(d){try{m(a.throw(d))}catch(u){n(u)}}function m(d){d.done?o(d.value):s(d.value).then(l,_)}m((a=a.apply(e,t||[])).next())})},dr=class{constructor(t,r=ks){this._value=t,this._cancelError=r,this._weightedQueues=[],this._weightedWaiters=[]}acquire(t=1){if(t<=0)throw new Error(`invalid weight ${t}: must be positive`);return new Promise((r,a)=>{this._weightedQueues[t-1]||(this._weightedQueues[t-1]=[]),this._weightedQueues[t-1].push({resolve:r,reject:a}),this._dispatch()})}runExclusive(t,r=1){return Ts(this,void 0,void 0,function*(){let[a,s]=yield this.acquire(r);try{return yield t(a)}finally{s()}})}waitForUnlock(t=1){if(t<=0)throw new Error(`invalid weight ${t}: must be positive`);return new Promise(r=>{this._weightedWaiters[t-1]||(this._weightedWaiters[t-1]=[]),this._weightedWaiters[t-1].push(r),this._dispatch()})}isLocked(){return this._value<=0}getValue(){return this._value}setValue(t){this._value=t,this._dispatch()}release(t=1){if(t<=0)throw new Error(`invalid weight ${t}: must be positive`);this._value+=t,this._dispatch()}cancel(){this._weightedQueues.forEach(t=>t.forEach(r=>r.reject(this._cancelError))),this._weightedQueues=[]}_dispatch(){var t;for(let r=this._value;r>0;r--){let a=(t=this._weightedQueues[r-1])===null||t===void 0?void 0:t.shift();if(!a)continue;let s=this._value,o=r;this._value-=r,r=this._value+1,a.resolve([s,this._newReleaser(o)])}this._drainUnlockWaiters()}_newReleaser(t){let r=!1;return()=>{r||(r=!0,this.release(t))}}_drainUnlockWaiters(){for(let t=this._value;t>0;t--)this._weightedWaiters[t-1]&&(this._weightedWaiters[t-1].forEach(r=>r()),this._weightedWaiters[t-1]=[])}},Us=function(e,t,r,a){function s(o){return o instanceof r?o:new r(function(n){n(o)})}return new(r||(r=Promise))(function(o,n){function l(d){try{m(a.next(d))}catch(u){n(u)}}function _(d){try{m(a.throw(d))}catch(u){n(u)}}function m(d){d.done?o(d.value):s(d.value).then(l,_)}m((a=a.apply(e,t||[])).next())})},he=class{constructor(t){this._semaphore=new dr(1,t)}acquire(){return Us(this,void 0,void 0,function*(){let[,t]=yield this._semaphore.acquire();return t})}runExclusive(t){return this._semaphore.runExclusive(()=>t())}isLocked(){return this._semaphore.isLocked()}waitForUnlock(){return this._semaphore.waitForUnlock()}release(){this._semaphore.isLocked()&&this._semaphore.release()}cancel(){return this._semaphore.cancel()}};M();M();var na={part:"part",container:"container"};function Gt(e,t,...r){let a=e.length-1,s=r.length-1;if(s!==-1){if(s===0){e[a]=e[a]+r[0]+t;return}e[a]=e[a]+r[0],e.push(...r.slice(1,s)),e.push(r[s]+t)}}function Rs(e,...t){let r=[e[0]];r.raw=[e.raw[0]];let a=[];for(let s=0;s<t.length;s++){let o=t[s],n=s+1;if(o?._templateType===na.part){Gt(r,e[n],o.str),Gt(r.raw,e.raw[n],o.str);continue}if(o?._templateType===na.container){Gt(r,e[n],...o.strings),Gt(r.raw,e.raw[n],...o.strings.raw),a.push(...o.values);continue}r.push(e[n]),r.raw.push(e.raw[n]),a.push(o)}return{_templateType:"container",strings:r,values:a}}function ur(e,...t){let{strings:r,values:a}=Rs(e,...t);return{query:[r[0],...a.flatMap((s,o)=>[`$${o+1}`,r[o+1]])].join(""),params:a}}var br={};Ie(br,{parseDescribeStatementResults:()=>it,parseResults:()=>Wt});M();var wr={};Ie(wr,{ABSTIME:()=>Ks,ACLITEM:()=>ro,BIT:()=>no,BOOL:()=>gr,BPCHAR:()=>da,BYTEA:()=>fr,CHAR:()=>Ns,CID:()=>Bs,CIDR:()=>Vs,CIRCLE:()=>Js,DATE:()=>ca,FLOAT4:()=>ma,FLOAT8:()=>pa,GTSVECTOR:()=>yo,INET:()=>to,INT2:()=>ia,INT4:()=>la,INT8:()=>hr,INTERVAL:()=>so,JSON:()=>xr,JSONB:()=>fa,MACADDR:()=>eo,MACADDR8:()=>$s,MONEY:()=>Zs,NUMERIC:()=>lo,OID:()=>_a,PATH:()=>Ws,PG_DEPENDENCIES:()=>So,PG_LSN:()=>xo,PG_NDISTINCT:()=>Mo,PG_NODE_TREE:()=>Hs,POLYGON:()=>js,REFCURSOR:()=>_o,REGCLASS:()=>co,REGCONFIG:()=>wo,REGDICTIONARY:()=>bo,REGNAMESPACE:()=>Co,REGOPER:()=>po,REGOPERATOR:()=>uo,REGPROC:()=>zs,REGPROCEDURE:()=>mo,REGROLE:()=>Io,REGTYPE:()=>go,RELTIME:()=>Qs,SMGR:()=>Xs,TEXT:()=>nt,TID:()=>Ls,TIME:()=>ao,TIMESTAMP:()=>ga,TIMESTAMPTZ:()=>Mr,TIMETZ:()=>oo,TINTERVAL:()=>Ys,TSQUERY:()=>Eo,TSVECTOR:()=>vo,TXID_SNAPSHOT:()=>ho,UUID:()=>fo,VARBIT:()=>io,VARCHAR:()=>ua,XID:()=>Os,XML:()=>Gs,arrayParser:()=>yr,arraySerializer:()=>Xt,parseType:()=>Ht,parsers:()=>vr,serializers:()=>Er,types:()=>ha});M();var Ds=globalThis.JSON.parse,qs=globalThis.JSON.stringify,gr=16,fr=17,Ns=18,hr=20,ia=21,la=23,zs=24,nt=25,_a=26,Ls=27,Os=28,Bs=29,xr=114,Gs=142,Hs=194,Xs=210,Ws=602,js=604,Vs=650,ma=700,pa=701,Ks=702,Qs=703,Ys=704,Js=718,$s=774,Zs=790,eo=829,to=869,ro=1033,da=1042,ua=1043,ca=1082,ao=1083,ga=1114,Mr=1184,so=1186,oo=1266,no=1560,io=1562,lo=1700,_o=1790,mo=2202,po=2203,uo=2204,co=2205,go=2206,fo=2950,ho=2970,xo=3220,Mo=3361,So=3402,vo=3614,Eo=3615,yo=3642,wo=3734,bo=3769,fa=3802,Co=4089,Io=4096,ha={string:{to:nt,from:[nt,ua,da],serialize:e=>{if(typeof e=="string")return e;if(typeof e=="number")return e.toString();throw new Error("Invalid input for string type")},parse:e=>e},number:{to:0,from:[ia,la,_a,ma,pa],serialize:e=>e.toString(),parse:e=>+e},bigint:{to:hr,from:[hr],serialize:e=>e.toString(),parse:e=>{let t=BigInt(e);return t<Number.MIN_SAFE_INTEGER||t>Number.MAX_SAFE_INTEGER?t:Number(t)}},json:{to:xr,from:[xr,fa],serialize:e=>typeof e=="string"?e:qs(e),parse:e=>Ds(e)},boolean:{to:gr,from:[gr],serialize:e=>{if(typeof e!="boolean")throw new Error("Invalid input for boolean type");return e?"t":"f"},parse:e=>e==="t"},date:{to:Mr,from:[ca,ga,Mr],serialize:e=>{if(typeof e=="string")return e;if(typeof e=="number")return new Date(e).toISOString();if(e instanceof Date)return e.toISOString();throw new Error("Invalid input for date type")},parse:e=>new Date(e)},bytea:{to:fr,from:[fr],serialize:e=>{if(!(e instanceof Uint8Array))throw new Error("Invalid input for bytea type");return"\\x"+Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")},parse:e=>{let t=e.slice(2);return Uint8Array.from({length:t.length/2},(r,a)=>parseInt(t.substring(a*2,(a+1)*2),16))}}},Sr=Po(ha),vr=Sr.parsers,Er=Sr.serializers;function Ht(e,t,r){if(e===null)return null;let a=r?.[t]??Sr.parsers[t];return a?a(e,t):e}function Po(e){return Object.keys(e).reduce(({parsers:t,serializers:r},a)=>{let{to:s,from:o,serialize:n,parse:l}=e[a];return r[s]=n,r[a]=n,t[a]=l,Array.isArray(o)?o.forEach(_=>{t[_]=l,r[_]=n}):(t[o]=l,r[o]=n),{parsers:t,serializers:r}},{parsers:{},serializers:{}})}var Fo=/\\/g,Ao=/"/g;function ko(e){return e.replace(Fo,"\\\\").replace(Ao,'\\"')}function Xt(e,t,r){if(Array.isArray(e)===!1)return e;if(!e.length)return"{}";let a=e[0],s=r===1020?";":",";return Array.isArray(a)?`{${e.map(o=>Xt(o,t,r)).join(s)}}`:`{${e.map(o=>(o===void 0&&(o=null),o===null?"null":'"'+ko(t?t(o):o.toString())+'"')).join(s)}}`}var cr={i:0,char:null,str:"",quoted:!1,last:0,p:null};function yr(e,t,r){return cr.i=cr.last=0,xa(cr,e,t,r)[0]}function xa(e,t,r,a){let s=[],o=a===1020?";":",";for(;e.i<t.length;e.i++){if(e.char=t[e.i],e.quoted)e.char==="\\"?e.str+=t[++e.i]:e.char==='"'?(s.push(r?r(e.str):e.str),e.str="",e.quoted=t[e.i+1]==='"',e.last=e.i+2):e.str+=e.char;else if(e.char==='"')e.quoted=!0;else if(e.char==="{")e.last=++e.i,s.push(xa(e,t,r,a));else if(e.char==="}"){e.quoted=!1,e.last<e.i&&s.push(r?r(t.slice(e.last,e.i)):t.slice(e.last,e.i)),e.last=e.i+1;break}else e.char===o&&e.p!=="}"&&e.p!=='"'&&(s.push(r?r(t.slice(e.last,e.i)):t.slice(e.last,e.i)),e.last=e.i+1);e.p=e.char}return e.last<e.i&&s.push(r?r(t.slice(e.last,e.i+1)):t.slice(e.last,e.i+1)),s}function Wt(e,t,r,a){let s=[],o={rows:[],fields:[]},n=0,l={...t,...r?.parsers};return e.forEach(_=>{switch(_.name){case"rowDescription":{let m=_;o.fields=m.fields.map(d=>({name:d.name,dataTypeID:d.dataTypeID}));break}case"dataRow":{if(!o)break;let m=_;r?.rowMode==="array"?o.rows.push(m.fields.map((d,u)=>Ht(d,o.fields[u].dataTypeID,l))):o.rows.push(Object.fromEntries(m.fields.map((d,u)=>[o.fields[u].name,Ht(d,o.fields[u].dataTypeID,l)])));break}case"commandComplete":{n+=To(_),s.push({...o,affectedRows:n,...a?{blob:a}:{}}),o={rows:[],fields:[]};break}}}),s.length===0&&s.push({affectedRows:0,rows:[],fields:[]}),s}function To(e){let t=e.text.split(" ");switch(t[0]){case"INSERT":return parseInt(t[2],10);case"UPDATE":case"DELETE":case"COPY":return parseInt(t[1],10);default:return 0}}function it(e){let t=e.find(r=>r.name==="parameterDescription");return t?t.dataTypeIDs:[]}var Lr={};Ie(Lr,{Parser:()=>Ue,messages:()=>yt,serialize:()=>N});M();M();M();M();function Ge(e){let t=e.length;for(let r=e.length-1;r>=0;r--){let a=e.charCodeAt(r);a>127&&a<=2047?t++:a>2047&&a<=65535&&(t+=2),a>=56320&&a<=57343&&r--}return t}var z,L,Xe,Vt,We,Y,jt,He,Ma,Fe=class{constructor(t=256){this.size=t;v(this,Y);v(this,z);v(this,L,5);v(this,Xe,!1);v(this,Vt,new TextEncoder);v(this,We,0);S(this,z,h(this,Y,jt).call(this,t))}addInt32(t){return h(this,Y,He).call(this,4),p(this,z).setInt32(p(this,L),t,p(this,Xe)),S(this,L,p(this,L)+4),this}addInt16(t){return h(this,Y,He).call(this,2),p(this,z).setInt16(p(this,L),t,p(this,Xe)),S(this,L,p(this,L)+2),this}addCString(t){return t&&this.addString(t),h(this,Y,He).call(this,1),p(this,z).setUint8(p(this,L),0),Pe(this,L)._++,this}addString(t=""){let r=Ge(t);return h(this,Y,He).call(this,r),p(this,Vt).encodeInto(t,new Uint8Array(p(this,z).buffer,p(this,L))),S(this,L,p(this,L)+r),this}add(t){return h(this,Y,He).call(this,t.byteLength),new Uint8Array(p(this,z).buffer).set(new Uint8Array(t),p(this,L)),S(this,L,p(this,L)+t.byteLength),this}flush(t){let r=h(this,Y,Ma).call(this,t);return S(this,L,5),S(this,z,h(this,Y,jt).call(this,this.size)),new Uint8Array(r)}};z=new WeakMap,L=new WeakMap,Xe=new WeakMap,Vt=new WeakMap,We=new WeakMap,Y=new WeakSet,jt=function(t){return new DataView(new ArrayBuffer(t))},He=function(t){if(p(this,z).byteLength-p(this,L)<t){let a=p(this,z).buffer,s=a.byteLength+(a.byteLength>>1)+t;S(this,z,h(this,Y,jt).call(this,s)),new Uint8Array(p(this,z).buffer).set(new Uint8Array(a))}},Ma=function(t){if(t){p(this,z).setUint8(p(this,We),t);let r=p(this,L)-(p(this,We)+1);p(this,z).setInt32(p(this,We)+1,r,p(this,Xe))}return p(this,z).buffer.slice(t?0:5,p(this,L))};var D=new Fe,Uo=e=>{D.addInt16(3).addInt16(0);for(let a of Object.keys(e))D.addCString(a).addCString(e[a]);D.addCString("client_encoding").addCString("UTF8");let t=D.addCString("").flush(),r=t.byteLength+4;return new Fe().addInt32(r).add(t).flush()},Ro=()=>{let e=new DataView(new ArrayBuffer(8));return e.setInt32(0,8,!1),e.setInt32(4,80877103,!1),new Uint8Array(e.buffer)},Do=e=>D.addCString(e).flush(112),qo=(e,t)=>(D.addCString(e).addInt32(Ge(t)).addString(t),D.flush(112)),No=e=>D.addString(e).flush(112),zo=e=>D.addCString(e).flush(81),Lo=[],Oo=e=>{let t=e.name??"";t.length>63&&(console.error("Warning! Postgres only supports 63 characters for query names."),console.error("You supplied %s (%s)",t,t.length),console.error("This can cause conflicts and silent errors executing queries"));let r=D.addCString(t).addCString(e.text).addInt16(e.types?.length??0);return e.types?.forEach(a=>r.addInt32(a)),D.flush(80)},je=new Fe;var Bo=(e,t)=>{for(let r=0;r<e.length;r++){let a=t?t(e[r],r):e[r];if(a===null)D.addInt16(0),je.addInt32(-1);else if(a instanceof ArrayBuffer||ArrayBuffer.isView(a)){let s=ArrayBuffer.isView(a)?a.buffer.slice(a.byteOffset,a.byteOffset+a.byteLength):a;D.addInt16(1),je.addInt32(s.byteLength),je.add(s)}else D.addInt16(0),je.addInt32(Ge(a)),je.addString(a)}},Go=(e={})=>{let t=e.portal??"",r=e.statement??"",a=e.binary??!1,s=e.values??Lo,o=s.length;return D.addCString(t).addCString(r),D.addInt16(o),Bo(s,e.valueMapper),D.addInt16(o),D.add(je.flush()),D.addInt16(a?1:0),D.flush(66)},Ho=new Uint8Array([69,0,0,0,9,0,0,0,0,0]),Xo=e=>{if(!e||!e.portal&&!e.rows)return Ho;let t=e.portal??"",r=e.rows??0,a=Ge(t),s=4+a+1+4,o=new DataView(new ArrayBuffer(1+s));return o.setUint8(0,69),o.setInt32(1,s,!1),new TextEncoder().encodeInto(t,new Uint8Array(o.buffer,5)),o.setUint8(a+5,0),o.setUint32(o.byteLength-4,r,!1),new Uint8Array(o.buffer)},Wo=(e,t)=>{let r=new DataView(new ArrayBuffer(16));return r.setInt32(0,16,!1),r.setInt16(4,1234,!1),r.setInt16(6,5678,!1),r.setInt32(8,e,!1),r.setInt32(12,t,!1),new Uint8Array(r.buffer)},Cr=(e,t)=>{let r=new Fe;return r.addCString(t),r.flush(e)},jo=D.addCString("P").flush(68),Vo=D.addCString("S").flush(68),Ko=e=>e.name?Cr(68,`${e.type}${e.name??""}`):e.type==="P"?jo:Vo,Qo=e=>{let t=`${e.type}${e.name??""}`;return Cr(67,t)},Yo=e=>D.add(e).flush(100),Jo=e=>Cr(102,e),Kt=e=>new Uint8Array([e,0,0,0,4]),$o=Kt(72),Zo=Kt(83),en=Kt(88),tn=Kt(99),N={startup:Uo,password:Do,requestSsl:Ro,sendSASLInitialResponseMessage:qo,sendSCRAMClientFinalMessage:No,query:zo,parse:Oo,bind:Go,execute:Xo,describe:Ko,close:Qo,flush:()=>$o,sync:()=>Zo,end:()=>en,copyData:Yo,copyDone:()=>tn,copyFail:Jo,cancel:Wo};M();var yt={};Ie(yt,{AuthenticationCleartextPassword:()=>_t,AuthenticationMD5Password:()=>mt,AuthenticationOk:()=>lt,AuthenticationSASL:()=>pt,AuthenticationSASLContinue:()=>dt,AuthenticationSASLFinal:()=>ut,BackendKeyDataMessage:()=>St,CommandCompleteMessage:()=>ke,CopyDataMessage:()=>ct,CopyResponse:()=>gt,DataRowMessage:()=>Et,DatabaseError:()=>xe,Field:()=>ft,NoticeMessage:()=>Te,NotificationResponseMessage:()=>Ae,ParameterDescriptionMessage:()=>xt,ParameterStatusMessage:()=>Mt,ReadyForQueryMessage:()=>vt,RowDescriptionMessage:()=>ht,bindComplete:()=>Pr,closeComplete:()=>Fr,copyDone:()=>Rr,emptyQuery:()=>Ur,noData:()=>Ar,parseComplete:()=>Ir,portalSuspended:()=>kr,replicationStart:()=>Tr});M();var Ir={name:"parseComplete",length:5},Pr={name:"bindComplete",length:5},Fr={name:"closeComplete",length:5},Ar={name:"noData",length:5},kr={name:"portalSuspended",length:5},Tr={name:"replicationStart",length:4},Ur={name:"emptyQuery",length:4},Rr={name:"copyDone",length:4},lt=class{constructor(t){this.length=t;this.name="authenticationOk"}},_t=class{constructor(t){this.length=t;this.name="authenticationCleartextPassword"}},mt=class{constructor(t,r){this.length=t;this.salt=r;this.name="authenticationMD5Password"}},pt=class{constructor(t,r){this.length=t;this.mechanisms=r;this.name="authenticationSASL"}},dt=class{constructor(t,r){this.length=t;this.data=r;this.name="authenticationSASLContinue"}},ut=class{constructor(t,r){this.length=t;this.data=r;this.name="authenticationSASLFinal"}},xe=class extends Error{constructor(r,a,s){super(r);this.length=a;this.name=s}},ct=class{constructor(t,r){this.length=t;this.chunk=r;this.name="copyData"}},gt=class{constructor(t,r,a,s){this.length=t;this.name=r;this.binary=a;this.columnTypes=new Array(s)}},ft=class{constructor(t,r,a,s,o,n,l){this.name=t;this.tableID=r;this.columnID=a;this.dataTypeID=s;this.dataTypeSize=o;this.dataTypeModifier=n;this.format=l}},ht=class{constructor(t,r){this.length=t;this.fieldCount=r;this.name="rowDescription";this.fields=new Array(this.fieldCount)}},xt=class{constructor(t,r){this.length=t;this.parameterCount=r;this.name="parameterDescription";this.dataTypeIDs=new Array(this.parameterCount)}},Mt=class{constructor(t,r,a){this.length=t;this.parameterName=r;this.parameterValue=a;this.name="parameterStatus"}},St=class{constructor(t,r,a){this.length=t;this.processID=r;this.secretKey=a;this.name="backendKeyData"}},Ae=class{constructor(t,r,a,s){this.length=t;this.processId=r;this.channel=a;this.payload=s;this.name="notification"}},vt=class{constructor(t,r){this.length=t;this.status=r;this.name="readyForQuery"}},ke=class{constructor(t,r){this.length=t;this.text=r;this.name="commandComplete"}},Et=class{constructor(t,r){this.length=t;this.fields=r;this.name="dataRow";this.fieldCount=r.length}},Te=class{constructor(t,r){this.length=t;this.message=r;this.name="notice"}};M();var Dr={text:0,binary:1};M();var rn=new ArrayBuffer(0),ue,H,Yt,Jt,wt,Qt=class{constructor(t=0){v(this,ue,new DataView(rn));v(this,H);v(this,Yt,"utf-8");v(this,Jt,new TextDecoder(p(this,Yt)));v(this,wt,!1);S(this,H,t)}setBuffer(t,r){S(this,H,t),S(this,ue,new DataView(r))}int16(){let t=p(this,ue).getInt16(p(this,H),p(this,wt));return S(this,H,p(this,H)+2),t}byte(){let t=p(this,ue).getUint8(p(this,H));return Pe(this,H)._++,t}int32(){let t=p(this,ue).getInt32(p(this,H),p(this,wt));return S(this,H,p(this,H)+4),t}string(t){return p(this,Jt).decode(this.bytes(t))}cstring(){let t=p(this,H),r=t;for(;p(this,ue).getUint8(r++)!==0;);let a=this.string(r-t-1);return S(this,H,r),a}bytes(t){let r=p(this,ue).buffer.slice(p(this,H),p(this,H)+t);return S(this,H,p(this,H)+t),new Uint8Array(r)}};ue=new WeakMap,H=new WeakMap,Yt=new WeakMap,Jt=new WeakMap,wt=new WeakMap;var qr=1,an=4,Sa=qr+an,va=new ArrayBuffer(0);var K,ee,te,y,k,Ea,ya,wa,ba,Ca,Ia,Pa,Nr,Fa,Aa,ka,Ta,Ua,Ra,Da,qa,zr,Ue=class{constructor(){v(this,k);v(this,K,new DataView(va));v(this,ee,0);v(this,te,0);v(this,y,new Qt)}parse(t,r){h(this,k,Ea).call(this,ArrayBuffer.isView(t)?t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength):t);let a=p(this,te)+p(this,ee),s=p(this,te);for(;s+Sa<=a;){let o=p(this,K).getUint8(s),n=p(this,K).getUint32(s+qr,!1),l=qr+n;if(l+s<=a){let _=h(this,k,ya).call(this,s+Sa,o,n,p(this,K).buffer);r(_),s+=l}else break}s===a?(S(this,K,new DataView(va)),S(this,ee,0),S(this,te,0)):(S(this,ee,a-s),S(this,te,s))}};K=new WeakMap,ee=new WeakMap,te=new WeakMap,y=new WeakMap,k=new WeakSet,Ea=function(t){if(p(this,ee)>0){let r=p(this,ee)+t.byteLength;if(r+p(this,te)>p(this,K).byteLength){let s;if(r<=p(this,K).byteLength&&p(this,te)>=p(this,ee))s=p(this,K).buffer;else{let o=p(this,K).byteLength*2;for(;r>=o;)o*=2;s=new ArrayBuffer(o)}new Uint8Array(s).set(new Uint8Array(p(this,K).buffer,p(this,te),p(this,ee))),S(this,K,new DataView(s)),S(this,te,0)}new Uint8Array(p(this,K).buffer).set(new Uint8Array(t),p(this,te)+p(this,ee)),S(this,ee,r)}else S(this,K,new DataView(t)),S(this,te,0),S(this,ee,t.byteLength)},ya=function(t,r,a,s){switch(r){case 50:return Pr;case 49:return Ir;case 51:return Fr;case 110:return Ar;case 115:return kr;case 99:return Rr;case 87:return Tr;case 73:return Ur;case 68:return h(this,k,Ua).call(this,t,a,s);case 67:return h(this,k,ba).call(this,t,a,s);case 90:return h(this,k,wa).call(this,t,a,s);case 65:return h(this,k,Fa).call(this,t,a,s);case 82:return h(this,k,qa).call(this,t,a,s);case 83:return h(this,k,Ra).call(this,t,a,s);case 75:return h(this,k,Da).call(this,t,a,s);case 69:return h(this,k,zr).call(this,t,a,s,"error");case 78:return h(this,k,zr).call(this,t,a,s,"notice");case 84:return h(this,k,Aa).call(this,t,a,s);case 116:return h(this,k,Ta).call(this,t,a,s);case 71:return h(this,k,Ia).call(this,t,a,s);case 72:return h(this,k,Pa).call(this,t,a,s);case 100:return h(this,k,Ca).call(this,t,a,s);default:return new xe("received invalid response: "+r.toString(16),a,"error")}},wa=function(t,r,a){p(this,y).setBuffer(t,a);let s=p(this,y).string(1);return new vt(r,s)},ba=function(t,r,a){p(this,y).setBuffer(t,a);let s=p(this,y).cstring();return new ke(r,s)},Ca=function(t,r,a){let s=a.slice(t,t+(r-4));return new ct(r,new Uint8Array(s))},Ia=function(t,r,a){return h(this,k,Nr).call(this,t,r,a,"copyInResponse")},Pa=function(t,r,a){return h(this,k,Nr).call(this,t,r,a,"copyOutResponse")},Nr=function(t,r,a,s){p(this,y).setBuffer(t,a);let o=p(this,y).byte()!==0,n=p(this,y).int16(),l=new gt(r,s,o,n);for(let _=0;_<n;_++)l.columnTypes[_]=p(this,y).int16();return l},Fa=function(t,r,a){p(this,y).setBuffer(t,a);let s=p(this,y).int32(),o=p(this,y).cstring(),n=p(this,y).cstring();return new Ae(r,s,o,n)},Aa=function(t,r,a){p(this,y).setBuffer(t,a);let s=p(this,y).int16(),o=new ht(r,s);for(let n=0;n<s;n++)o.fields[n]=h(this,k,ka).call(this);return o},ka=function(){let t=p(this,y).cstring(),r=p(this,y).int32(),a=p(this,y).int16(),s=p(this,y).int32(),o=p(this,y).int16(),n=p(this,y).int32(),l=p(this,y).int16()===0?Dr.text:Dr.binary;return new ft(t,r,a,s,o,n,l)},Ta=function(t,r,a){p(this,y).setBuffer(t,a);let s=p(this,y).int16(),o=new xt(r,s);for(let n=0;n<s;n++)o.dataTypeIDs[n]=p(this,y).int32();return o},Ua=function(t,r,a){p(this,y).setBuffer(t,a);let s=p(this,y).int16(),o=new Array(s);for(let n=0;n<s;n++){let l=p(this,y).int32();o[n]=l===-1?null:p(this,y).string(l)}return new Et(r,o)},Ra=function(t,r,a){p(this,y).setBuffer(t,a);let s=p(this,y).cstring(),o=p(this,y).cstring();return new Mt(r,s,o)},Da=function(t,r,a){p(this,y).setBuffer(t,a);let s=p(this,y).int32(),o=p(this,y).int32();return new St(r,s,o)},qa=function(t,r,a){p(this,y).setBuffer(t,a);let s=p(this,y).int32();switch(s){case 0:return new lt(r);case 3:return new _t(r);case 5:return new mt(r,p(this,y).bytes(4));case 10:{let o=[];for(;;){let n=p(this,y).cstring();if(n.length===0)return new pt(r,o);o.push(n)}}case 11:return new dt(r,p(this,y).string(r-8));case 12:return new ut(r,p(this,y).string(r-8));default:throw new Error("Unknown authenticationOk message type "+s)}},zr=function(t,r,a,s){p(this,y).setBuffer(t,a);let o={},n=p(this,y).string(1);for(;n!=="\0";)o[n]=p(this,y).cstring(),n=p(this,y).string(1);let l=o.M,_=s==="notice"?new Te(r,l):new xe(l,r,s);return _.severity=o.S,_.code=o.C,_.detail=o.D,_.hint=o.H,_.position=o.P,_.internalPosition=o.p,_.internalQuery=o.q,_.where=o.W,_.schema=o.s,_.table=o.t,_.column=o.c,_.dataType=o.d,_.constraint=o.n,_.file=o.F,_.line=o.L,_.routine=o.R,_};var bt,Me,R,se,$t,Re,Or,Zt=class{constructor(){v(this,R);this.serializers={...Er};this.parsers={...vr};v(this,bt,!1);v(this,Me,!1)}async _initArrayTypes({force:t=!1}={}){if(p(this,bt)&&!t)return;S(this,bt,!0);let r=await this.query(` SELECT b.oid, b.typarray FROM pg_catalog.pg_type a LEFT JOIN pg_catalog.pg_type b ON b.oid = a.typelem WHERE a.typcategory = 'A' GROUP BY b.oid, b.typarray ORDER BY b.oid `);for(let a of r.rows)this.serializers[a.typarray]=s=>Xt(s,this.serializers[a.oid],a.typarray),this.parsers[a.typarray]=s=>yr(s,this.parsers[a.oid],a.typarray)}async refreshArrayTypes(){await this._initArrayTypes({force:!0})}async query(t,r,a){return await this._checkReady(),await this._runExclusiveTransaction(async()=>await h(this,R,$t).call(this,t,r,a))}async sql(t,...r){let{query:a,params:s}=ur(t,...r);return await this.query(a,s)}async exec(t,r){return await this._checkReady(),await this._runExclusiveTransaction(async()=>await h(this,R,Re).call(this,t,r))}async describeQuery(t,r){try{await h(this,R,se).call(this,N.parse({text:t,types:r?.paramTypes}),r);let a=await h(this,R,se).call(this,N.describe({type:"S"}),r),s=a.messages.find(_=>_.name==="parameterDescription"),o=a.messages.find(_=>_.name==="rowDescription"),n=s?.dataTypeIDs.map(_=>({dataTypeID:_,serializer:this.serializers[_]}))??[],l=o?.fields.map(_=>({name:_.name,dataTypeID:_.dataTypeID,parser:this.parsers[_.dataTypeID]}))??[];retur