@ckirg/corelib-cloud 0.1.22
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +252 -0
- package/dist/aws/RequestUnlimited-EKXQGSQT.mjs +2 -0
- package/dist/aws/bun-GK5CEVAU.mjs +2 -0
- package/dist/aws/chunk-27GDSGEE.mjs +2 -0
- package/dist/aws/chunk-F2KTMAO3.mjs +6 -0
- package/dist/aws/chunk-QCE23AKJ.mjs +8 -0
- package/dist/aws/chunk-STPKE4A5.mjs +24 -0
- package/dist/aws/chunk-V3XZ4XYN.mjs +2 -0
- package/dist/aws/chunk-VULBPPPP.mjs +2 -0
- package/dist/aws/chunk-Y7RZHZ53.mjs +2 -0
- package/dist/aws/cloudflare-BDB3FS4Y.mjs +2 -0
- package/dist/aws/deno-AIUOFIXG.mjs +2 -0
- package/dist/aws/dist-VV3A6A7N.mjs +118 -0
- package/dist/aws/gcp-ZEEIATV7.mjs +438 -0
- package/dist/aws/handler.mjs +63 -0
- package/dist/aws/lambda-S3DVSSBV.mjs +3 -0
- package/dist/aws/node-A7ZN443L.mjs +2 -0
- package/dist/aws/node-RM2WPPZL.mjs +8 -0
- package/dist/aws/src-W4SC2UPB.mjs +23 -0
- package/dist/aws/utils-KMHFLZAJ.mjs +2 -0
- package/dist/cloudflare/RequestUnlimited-QCOTVU4G.js +1 -0
- package/dist/cloudflare/bun-O4EJPGLH.js +1 -0
- package/dist/cloudflare/chunk-DGDAVQYC.js +1 -0
- package/dist/cloudflare/chunk-EQSCULS7.js +2 -0
- package/dist/cloudflare/chunk-O3XYZ4KS.js +1 -0
- package/dist/cloudflare/chunk-PVAE643M.js +1 -0
- package/dist/cloudflare/chunk-QPTGW2LL.js +1 -0
- package/dist/cloudflare/cloudflare-I5A4OJEG.js +1 -0
- package/dist/cloudflare/deno-KE6IVNNU.js +1 -0
- package/dist/cloudflare/dist-GZV6T6K3.js +117 -0
- package/dist/cloudflare/gcp-MNKOPDML.js +1 -0
- package/dist/cloudflare/lambda-PLZQW4BF.js +1 -0
- package/dist/cloudflare/node-DRV76TUB.js +1 -0
- package/dist/cloudflare/utils-7K7MHQMD.js +1 -0
- package/dist/cloudflare/worker.js +62 -0
- package/dist/cloudrun/RequestUnlimited-YQAPYTOH.js +2 -0
- package/dist/cloudrun/bun-BONNABBU.js +2 -0
- package/dist/cloudrun/chunk-5B5BV7SP.js +8 -0
- package/dist/cloudrun/chunk-5CIUNKHO.js +2 -0
- package/dist/cloudrun/chunk-CFQMQATE.js +24 -0
- package/dist/cloudrun/chunk-FYZPEVAA.js +2 -0
- package/dist/cloudrun/chunk-GB4XIPDS.js +6 -0
- package/dist/cloudrun/chunk-JUVTJQ7I.js +2 -0
- package/dist/cloudrun/chunk-ZXZVHMQF.js +2 -0
- package/dist/cloudrun/cloudflare-Q3ZW7CDF.js +2 -0
- package/dist/cloudrun/deno-CPTVGH3A.js +2 -0
- package/dist/cloudrun/dist-VT4HJLSH.js +118 -0
- package/dist/cloudrun/gcp-W76U73T6.js +438 -0
- package/dist/cloudrun/lambda-NKM4QA4M.js +3 -0
- package/dist/cloudrun/node-LVHXMIYI.js +8 -0
- package/dist/cloudrun/node-SKMPZMFE.js +2 -0
- package/dist/cloudrun/server.js +67 -0
- package/dist/cloudrun/src-2WWXNWVC.js +23 -0
- package/dist/cloudrun/utils-SDRX3ZUT.js +2 -0
- package/package.json +52 -0
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import { createRequire } from 'module'; const require = createRequire(import.meta.url);
|
|
2
|
+
import{c as E,d as A}from"./chunk-STPKE4A5.mjs";import"./chunk-V3XZ4XYN.mjs";import{a as H,c as s,e as D,h as i}from"./chunk-VULBPPPP.mjs";var O=s(v=>{"use strict";i();Object.defineProperty(v,"__esModule",{value:!0});v.GlobalContextStorageProvider=void 0;var S=Symbol.for("aws.lambda.runtime.context");v.GlobalContextStorageProvider={getContext:()=>global[S],setContext:e=>global[S]=e,updateContext:e=>{let t=v.GlobalContextStorageProvider.getContext();global[S]={...t,...e}}}});var w=s(b=>{"use strict";i();var V=b&&b.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(b,"__esModule",{value:!0});b.formatLevel=void 0;var Y=V(E()),K=e=>{var t;return typeof e=="string"?e.toLocaleUpperCase():typeof e=="number"?(t=Y.default.levels.labels[e])===null||t===void 0?void 0:t.toLocaleUpperCase():e};b.formatLevel=K});var N=s(q=>{"use strict";i();Object.defineProperty(q,"__esModule",{value:!0});q.CloudwatchLogFormatter=void 0;var Q=w(),h=class{format(t){let{awsRequestId:r,level:o,msg:a}=t,f=new Date().toISOString(),_=Q.formatLevel(o);return`${f}${r?` ${r}`:""} ${_} ${a} ${JSON.stringify(t)}`}};q.CloudwatchLogFormatter=h});var $=s(y=>{"use strict";i();Object.defineProperty(y,"__esModule",{value:!0});y.PinoLogFormatter=void 0;var R=class{format(t){return JSON.stringify(t)}};y.PinoLogFormatter=R});var F=s(L=>{"use strict";i();Object.defineProperty(L,"__esModule",{value:!0});L.StructuredLogFormatter=void 0;var k=w(),j=class{format({awsRequestId:t,level:r,...o}){return JSON.stringify({timestamp:new Date().toISOString(),level:k.formatLevel(r),requestId:t,message:o})}};L.StructuredLogFormatter=j});var M=s(d=>{"use strict";i();var ee=d&&d.__createBinding||(Object.create?(function(e,t,r,o){o===void 0&&(o=r),Object.defineProperty(e,o,{enumerable:!0,get:function(){return t[r]}})}):(function(e,t,r,o){o===void 0&&(o=r),e[o]=t[r]})),I=d&&d.__exportStar||function(e,t){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r)&&ee(t,e,r)};Object.defineProperty(d,"__esModule",{value:!0});I(N(),d);I($(),d);I(F(),d)});var G=s(C=>{"use strict";i();Object.defineProperty(C,"__esModule",{value:!0});C.pinoLambdaDestination=void 0;var te=H("stream"),re=O(),oe=M(),ie=(e={})=>new te.Writable({defaultEncoding:"utf8",write(r,o,a){let f=e.storageProvider||re.GlobalContextStorageProvider,_=e.formatter||new oe.CloudwatchLogFormatter,l=JSON.parse(r),m=f.getContext()||{},g=_.format({...m,...l});g=g.replace(/\n/,"\r"),g+=`
|
|
3
|
+
`,e.streamWriter?e.streamWriter(g):process.stdout.write(g),a()}});C.pinoLambdaDestination=ie});var J=s(P=>{"use strict";i();Object.defineProperty(P,"__esModule",{value:!0});P.lambdaRequestTracker=void 0;var ae=O(),B="_X_AMZN_TRACE_ID",T="x-correlation-",W=`${T}id`,ne=`${T}trace-id`,se=(e={})=>(t,r)=>{var o;let a={awsRequestId:r.awsRequestId},f=(o=t.requestContext)===null||o===void 0?void 0:o.requestId;if(f&&(a.apiRequestId=f),t.headers)for(let[l,m]of Object.entries(t.headers))l.toLowerCase().startsWith(T)&&(a[l]=m);if(process.env[B]&&(a[ne]=process.env[B]),a[W]||(a[W]=r.awsRequestId),e.requestMixin){let l=e.requestMixin(t,r);for(let m in l)a[m]=l[m]}let _=e.storageProvider||ae.GlobalContextStorageProvider;_&&_.setContext(a)};P.lambdaRequestTracker=se});var X=s(U=>{"use strict";i();Object.defineProperty(U,"__esModule",{value:!0})});var Z=s(n=>{"use strict";i();var ue=n&&n.__createBinding||(Object.create?(function(e,t,r,o){o===void 0&&(o=r),Object.defineProperty(e,o,{enumerable:!0,get:function(){return t[r]}})}):(function(e,t,r,o){o===void 0&&(o=r),e[o]=t[r]})),p=n&&n.__exportStar||function(e,t){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r)&&ue(t,e,r)};Object.defineProperty(n,"__esModule",{value:!0});p(O(),n);p(G(),n);p(M(),n);p(J(),n);p(X(),n)});i();var x=D(E(),1),z=D(Z(),1);function ce(){let e=z.default,t=typeof e=="function"?e:e.default||e.pinoLambda,r;if(typeof t=="function")try{r=t()}catch{console.warn("pino-lambda destination creation failed, using default")}let o=(0,x.default)({level:process.env.LOG_LEVEL||"info",timestamp:x.default.stdTimeFunctions.isoTime,redact:["password","secret","token","authorization"]},r);return new A(o)}export{ce as default};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { createRequire } from 'module'; const require = createRequire(import.meta.url);
|
|
2
|
+
import{a as g}from"./chunk-F2KTMAO3.mjs";import"./chunk-27GDSGEE.mjs";import{c as p,d as i}from"./chunk-STPKE4A5.mjs";import"./chunk-V3XZ4XYN.mjs";import{e as s,h as n}from"./chunk-VULBPPPP.mjs";n();var o=s(p(),1),a=s(g(),1);import{Writable as d}from"stream";var f=process.env.LOG_PRETTY==="true"||process.env.NODE_ENV!=="production"&&process.env.LOG_PRETTY!=="false",e=process.env.LOG_LEVEL||"info",m=new d({write(t,v,c){let r=globalThis.__wsLogWrite;r&&r(typeof t=="string"?t:t.toString("utf8")),c()}}),l=o.default.multistream([{level:e,stream:f?(0,a.default)({colorize:!0,translateTime:"SYS:standard",ignore:"pid,hostname"}):process.stdout},{level:e,stream:m}]),u=(0,o.default)({level:e,redact:["password","secret","token","authorization","apiKey"]},l),L=new i(u),S=L;export{S as default};
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { createRequire } from 'module'; const require = createRequire(import.meta.url);
|
|
2
|
+
import{a as E,c as q,e as G,g as h,h as l}from"./chunk-VULBPPPP.mjs";var Us=q(F=>{"use strict";l();var Ii=F&&F.__createBinding||(Object.create?(function(t,e,r,s){s===void 0&&(s=r);var n=Object.getOwnPropertyDescriptor(e,r);(!n||("get"in n?!e.__esModule:n.writable||n.configurable))&&(n={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,s,n)}):(function(t,e,r,s){s===void 0&&(s=r),t[s]=e[r]})),qi=F&&F.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),Ns=F&&F.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Ii(e,t,r);return qi(e,t),e};Object.defineProperty(F,"__esModule",{value:!0});F.load=F.currentTarget=void 0;var Oi=Ns(E("path")),vi=Ns(E("fs"));function Li(){let t=null;switch(process.platform){case"android":switch(process.arch){case"arm":return"android-arm-eabi";case"arm64":return"android-arm64"}t="Android";break;case"win32":switch(process.arch){case"x64":return"win32-x64-msvc";case"arm64":return"win32-arm64-msvc";case"ia32":return"win32-ia32-msvc"}t="Windows";break;case"darwin":switch(process.arch){case"x64":return"darwin-x64";case"arm64":return"darwin-arm64"}t="macOS";break;case"linux":switch(process.arch){case"x64":case"arm64":return ki()?`linux-${process.arch}-gnu`:`linux-${process.arch}-musl`;case"arm":return"linux-arm-gnueabihf"}t="Linux";break;case"freebsd":if(process.arch==="x64")return"freebsd-x64";t="FreeBSD";break}throw t?new Error(`Neon: unsupported ${t} architecture: ${process.arch}`):new Error(`Neon: unsupported system: ${process.platform}`)}F.currentTarget=Li;function ki(){let t=process.report?.getReport();if(typeof t!="object"||!t||!("header"in t))return!1;let e=t.header;return typeof e=="object"&&!!e&&"glibcVersionRuntime"in e}function Ai(t){let e=Oi.join(t,"index.node");return vi.existsSync(e)?E(e):null}F.load=Ai});var Ds=q((Du,Ms)=>{"use strict";l();var Bs=()=>process.platform==="linux",gr=null,Pi=()=>(gr||(gr=Bs()&&process.report?process.report.getReport():{}),gr);Ms.exports={isLinux:Bs,getReport:Pi}});var $s=q((ju,js)=>{"use strict";l();var Fs=E("fs"),Ni="/usr/bin/ldd",Ui=t=>Fs.readFileSync(t,"utf-8"),Bi=t=>new Promise((e,r)=>{Fs.readFile(t,"utf-8",(s,n)=>{s?r(s):e(n)})});js.exports={LDD_PATH:Ni,readFileSync:Ui,readFile:Bi}});var an=q((Wu,on)=>{"use strict";l();var Vs=E("child_process"),{isLinux:Fe,getReport:Gs}=Ds(),{LDD_PATH:Bt,readFile:Hs,readFileSync:zs}=$s(),Y,J,Qs="getconf GNU_LIBC_VERSION 2>&1 || true; ldd --version 2>&1 || true",ue="",Ks=()=>ue||new Promise(t=>{Vs.exec(Qs,(e,r)=>{ue=e?" ":r,t(ue)})}),Ys=()=>{if(!ue)try{ue=Vs.execSync(Qs,{encoding:"utf8"})}catch{ue=" "}return ue},X="glibc",Js=/GLIBC\s(\d+\.\d+)/,Se="musl",Mi=X.toUpperCase(),Di=Se.toLowerCase(),Fi=t=>t.includes("libc.musl-")||t.includes("ld-musl-"),Zs=()=>{let t=Gs();return t.header&&t.header.glibcVersionRuntime?X:Array.isArray(t.sharedObjects)&&t.sharedObjects.some(Fi)?Se:null},Xs=t=>{let[e,r]=t.split(/[\r\n]+/);return e&&e.includes(X)?X:r&&r.includes(Se)?Se:null},en=t=>t.includes(Di)?Se:t.includes(Mi)?X:null,ji=async()=>{if(Y!==void 0)return Y;Y=null;try{let t=await Hs(Bt);Y=en(t)}catch{}return Y},$i=()=>{if(Y!==void 0)return Y;Y=null;try{let t=zs(Bt);Y=en(t)}catch{}return Y},tn=async()=>{let t=null;if(Fe()&&(t=await ji(),t||(t=Zs()),!t)){let e=await Ks();t=Xs(e)}return t},rn=()=>{let t=null;if(Fe()&&(t=$i(),t||(t=Zs()),!t)){let e=Ys();t=Xs(e)}return t},Wi=async()=>Fe()&&await tn()!==X,Vi=()=>Fe()&&rn()!==X,Gi=async()=>{if(J!==void 0)return J;J=null;try{let e=(await Hs(Bt)).match(Js);e&&(J=e[1])}catch{}return J},Hi=()=>{if(J!==void 0)return J;J=null;try{let e=zs(Bt).match(Js);e&&(J=e[1])}catch{}return J},sn=()=>{let t=Gs();return t.header&&t.header.glibcVersionRuntime?t.header.glibcVersionRuntime:null},Ws=t=>t.trim().split(/\s+/)[1],nn=t=>{let[e,r,s]=t.split(/[\r\n]+/);return e&&e.includes(X)?Ws(e):r&&s&&r.includes(Se)?Ws(s):null},zi=async()=>{let t=null;if(Fe()&&(t=await Gi(),t||(t=sn()),!t)){let e=await Ks();t=nn(e)}return t},Qi=()=>{let t=null;if(Fe()&&(t=Hi(),t||(t=sn()),!t)){let e=Ys();t=nn(e)}return t};on.exports={GLIBC:X,MUSL:Se,family:tn,familySync:rn,isNonGlibcLinux:Wi,isNonGlibcLinuxSync:Vi,version:zi,versionSync:Qi}});var ln=q((Gu,cn)=>{"use strict";l();var Ki={ALLOW:0,DENY:1};cn.exports=Ki});var hn=q((zu,un)=>{"use strict";l();var xr={value:"SqliteError",writable:!0,enumerable:!1,configurable:!0};function Ee(t,e,r){if(new.target!==Ee)return new Ee(t,e);if(typeof e!="string")throw new TypeError("Expected second argument to be a string");Error.call(this,t),xr.value=""+t,Object.defineProperty(this,"message",xr),Error.captureStackTrace(this,Ee),this.code=e,this.rawCode=r}Object.setPrototypeOf(Ee,Error);Object.setPrototypeOf(Ee.prototype,Error.prototype);Object.defineProperty(Ee.prototype,"name",xr);un.exports=Ee});var _n=q((Ku,Mt)=>{"use strict";l();var{load:Yi,currentTarget:Ji}=Us(),{familySync:fn,GLIBC:Zi,MUSL:Xi}=an();function ea(){if(process.env.LIBSQL_JS_DEV)return Yi(h);let t=Ji();if(fn()==Zi)switch(t){case"linux-x64-musl":t="linux-x64-gnu";break;case"linux-arm64-musl":t="linux-arm64-gnu";break}return t==="linux-arm-gnueabihf"&&fn()==Xi&&(t="linux-arm-musleabihf"),E(`@libsql/${t}`)}var{databaseOpen:ta,databaseOpenWithSync:ra,databaseInTransaction:sa,databaseInterrupt:na,databaseClose:oa,databaseSyncSync:ia,databaseSyncUntilSync:aa,databaseExecSync:ca,databasePrepareSync:la,databaseDefaultSafeIntegers:ua,databaseAuthorizer:ha,databaseLoadExtension:fa,databaseMaxWriteReplicationIndex:da,statementRaw:pa,statementIsReader:ma,statementGet:dn,statementRun:pn,statementInterrupt:ya,statementRowsSync:mn,statementColumns:_a,statementSafeIntegers:ba,rowsNext:wa}=ea(),ga=ln(),yn=hn();function je(t){return t.libsqlError?new yn(t.message,t.code,t.rawCode):t}var Sr=class{constructor(e,r){let s=r?.encryptionCipher??"aes256cbc";if(r&&r.syncUrl){var n="";r.syncAuth?(console.warn("Warning: The `syncAuth` option is deprecated, please use `authToken` option instead."),n=r.syncAuth):r.authToken&&(n=r.authToken);let i=r?.encryptionKey??"",a=r?.syncPeriod??0,c=r?.readYourWrites??!0,u=r?.offline??!1,d=r?.remoteEncryptionKey??"";this.db=ra(e,r.syncUrl,n,s,i,a,c,u,d)}else{let i=r?.authToken??"",a=r?.encryptionKey??"",c=r?.timeout??0,u=r?.remoteEncryptionKey??"";this.db=ta(e,i,s,a,c,u)}this.memory=e===":memory:",this.readonly=!1,this.name="",this.open=!0;let o=this.db;Object.defineProperties(this,{inTransaction:{get(){return sa(o)}}})}sync(){return ia.call(this.db)}syncUntil(e){return aa.call(this.db,e)}prepare(e){try{let r=la.call(this.db,e);return new Er(r)}catch(r){throw je(r)}}transaction(e){if(typeof e!="function")throw new TypeError("Expected first argument to be a function");let r=this,s=o=>(...i)=>{r.exec("BEGIN "+o);try{let a=e(...i);return r.exec("COMMIT"),a}catch(a){throw r.exec("ROLLBACK"),a}},n={default:{value:s("")},deferred:{value:s("DEFERRED")},immediate:{value:s("IMMEDIATE")},exclusive:{value:s("EXCLUSIVE")},database:{value:this,enumerable:!0}};return Object.defineProperties(n.default.value,n),Object.defineProperties(n.deferred.value,n),Object.defineProperties(n.immediate.value,n),Object.defineProperties(n.exclusive.value,n),n.default.value}pragma(e,r){if(r==null&&(r={}),typeof e!="string")throw new TypeError("Expected first argument to be a string");if(typeof r!="object")throw new TypeError("Expected second argument to be an options object");let s=r.simple,n=this.prepare(`PRAGMA ${e}`,this,!0);return s?n.pluck().get():n.all()}backup(e,r){throw new Error("not implemented")}serialize(e){throw new Error("not implemented")}function(e,r,s){throw r==null&&(r={}),typeof r=="function"&&(s=r,r={}),typeof e!="string"?new TypeError("Expected first argument to be a string"):typeof s!="function"?new TypeError("Expected last argument to be a function"):typeof r!="object"?new TypeError("Expected second argument to be an options object"):e?new Error("not implemented"):new TypeError("User-defined function name cannot be an empty string")}aggregate(e,r){throw typeof e!="string"?new TypeError("Expected first argument to be a string"):typeof r!="object"||r===null?new TypeError("Expected second argument to be an options object"):e?new Error("not implemented"):new TypeError("User-defined function name cannot be an empty string")}table(e,r){throw typeof e!="string"?new TypeError("Expected first argument to be a string"):e?new Error("not implemented"):new TypeError("Virtual table module name cannot be an empty string")}authorizer(e){ha.call(this.db,e)}loadExtension(...e){fa.call(this.db,...e)}maxWriteReplicationIndex(){return da.call(this.db)}exec(e){try{ca.call(this.db,e)}catch(r){throw je(r)}}interrupt(){na.call(this.db)}close(){oa.call(this.db),this.open=!1}defaultSafeIntegers(e){return ua.call(this.db,e??!0),this}unsafeMode(...e){throw new Error("not implemented")}},Er=class{constructor(e){this.stmt=e,this.pluckMode=!1}raw(e){return pa.call(this.stmt,e??!0),this}pluck(e){return this.pluckMode=e??!0,this}get reader(){return ma.call(this.stmt)}run(...e){try{return e.length==1&&typeof e[0]=="object"?pn.call(this.stmt,e[0]):pn.call(this.stmt,e.flat())}catch(r){throw je(r)}}get(...e){try{return e.length==1&&typeof e[0]=="object"?dn.call(this.stmt,e[0]):dn.call(this.stmt,e.flat())}catch(r){throw je(r)}}iterate(...e){var r=void 0;return e.length==1&&typeof e[0]=="object"?r=mn.call(this.stmt,e[0]):r=mn.call(this.stmt,e.flat()),{nextRows:Array(100),nextRowIndex:100,next(){try{this.nextRowIndex===100&&(wa.call(r,this.nextRows),this.nextRowIndex=0);let n=this.nextRows[this.nextRowIndex];return this.nextRows[this.nextRowIndex]=void 0,n?(this.nextRowIndex++,{value:n,done:!1}):{done:!0}}catch(n){throw je(n)}},[Symbol.iterator](){return this}}}all(...e){try{let r=[];for(let s of this.iterate(...e))this.pluckMode?r.push(s[Object.keys(s)[0]]):r.push(s);return r}catch(r){throw je(r)}}interrupt(){ya.call(this.stmt)}columns(){return _a.call(this.stmt)}safeIntegers(e){return ba.call(this.stmt,e??!0),this}};Mt.exports=Sr;Mt.exports.Authorization=ga;Mt.exports.SqliteError=yn});var ee=q((oh,Rn)=>{"use strict";l();var En=["nodebuffer","arraybuffer","fragments"],Cn=typeof Blob<"u";Cn&&En.push("blob");Rn.exports={BINARY_TYPES:En,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Cn,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var yt=q((ah,Dt)=>{"use strict";l();var{EMPTY_BUFFER:Oa}=ee(),Tr=Buffer[Symbol.species];function va(t,e){if(t.length===0)return Oa;if(t.length===1)return t[0];let r=Buffer.allocUnsafe(e),s=0;for(let n=0;n<t.length;n++){let o=t[n];r.set(o,s),s+=o.length}return s<e?new Tr(r.buffer,r.byteOffset,s):r}function Tn(t,e,r,s,n){for(let o=0;o<n;o++)r[s+o]=t[o]^e[o&3]}function In(t,e){for(let r=0;r<t.length;r++)t[r]^=e[r&3]}function La(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function Ir(t){if(Ir.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new Tr(t):ArrayBuffer.isView(t)?e=new Tr(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),Ir.readOnly=!1),e}Dt.exports={concat:va,mask:Tn,toArrayBuffer:La,toBuffer:Ir,unmask:In};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=E("bufferutil");Dt.exports.mask=function(e,r,s,n,o){o<48?Tn(e,r,s,n,o):t.mask(e,r,s,n,o)},Dt.exports.unmask=function(e,r){e.length<32?In(e,r):t.unmask(e,r)}}catch{}});var vn=q((lh,On)=>{"use strict";l();var qn=Symbol("kDone"),qr=Symbol("kRun"),Or=class{constructor(e){this[qn]=()=>{this.pending--,this[qr]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[qr]()}[qr](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[qn])}}};On.exports=Or});var Ve=q((hh,Pn)=>{"use strict";l();var _t=E("zlib"),Ln=yt(),ka=vn(),{kStatusCode:kn}=ee(),Aa=Buffer[Symbol.species],Pa=Buffer.from([0,0,255,255]),jt=Symbol("permessage-deflate"),te=Symbol("total-length"),$e=Symbol("callback"),he=Symbol("buffers"),We=Symbol("error"),Ft,vr=class{constructor(e){if(this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!Ft){let r=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Ft=new ka(r)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[$e];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let r=this._options,s=e.find(n=>!(r.serverNoContextTakeover===!1&&n.server_no_context_takeover||n.server_max_window_bits&&(r.serverMaxWindowBits===!1||typeof r.serverMaxWindowBits=="number"&&r.serverMaxWindowBits>n.server_max_window_bits)||typeof r.clientMaxWindowBits=="number"&&!n.client_max_window_bits));if(!s)throw new Error("None of the extension offers can be accepted");return r.serverNoContextTakeover&&(s.server_no_context_takeover=!0),r.clientNoContextTakeover&&(s.client_no_context_takeover=!0),typeof r.serverMaxWindowBits=="number"&&(s.server_max_window_bits=r.serverMaxWindowBits),typeof r.clientMaxWindowBits=="number"?s.client_max_window_bits=r.clientMaxWindowBits:(s.client_max_window_bits===!0||r.clientMaxWindowBits===!1)&&delete s.client_max_window_bits,s}acceptAsClient(e){let r=e[0];if(this._options.clientNoContextTakeover===!1&&r.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!r.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(r.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&r.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return r}normalizeParams(e){return e.forEach(r=>{Object.keys(r).forEach(s=>{let n=r[s];if(n.length>1)throw new Error(`Parameter "${s}" must have only a single value`);if(n=n[0],s==="client_max_window_bits"){if(n!==!0){let o=+n;if(!Number.isInteger(o)||o<8||o>15)throw new TypeError(`Invalid value for parameter "${s}": ${n}`);n=o}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${s}": ${n}`)}else if(s==="server_max_window_bits"){let o=+n;if(!Number.isInteger(o)||o<8||o>15)throw new TypeError(`Invalid value for parameter "${s}": ${n}`);n=o}else if(s==="client_no_context_takeover"||s==="server_no_context_takeover"){if(n!==!0)throw new TypeError(`Invalid value for parameter "${s}": ${n}`)}else throw new Error(`Unknown parameter "${s}"`);r[s]=n})}),e}decompress(e,r,s){Ft.add(n=>{this._decompress(e,r,(o,i)=>{n(),s(o,i)})})}compress(e,r,s){Ft.add(n=>{this._compress(e,r,(o,i)=>{n(),s(o,i)})})}_decompress(e,r,s){let n=this._isServer?"client":"server";if(!this._inflate){let o=`${n}_max_window_bits`,i=typeof this.params[o]!="number"?_t.Z_DEFAULT_WINDOWBITS:this.params[o];this._inflate=_t.createInflateRaw({...this._options.zlibInflateOptions,windowBits:i}),this._inflate[jt]=this,this._inflate[te]=0,this._inflate[he]=[],this._inflate.on("error",Ua),this._inflate.on("data",An)}this._inflate[$e]=s,this._inflate.write(e),r&&this._inflate.write(Pa),this._inflate.flush(()=>{let o=this._inflate[We];if(o){this._inflate.close(),this._inflate=null,s(o);return}let i=Ln.concat(this._inflate[he],this._inflate[te]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[te]=0,this._inflate[he]=[],r&&this.params[`${n}_no_context_takeover`]&&this._inflate.reset()),s(null,i)})}_compress(e,r,s){let n=this._isServer?"server":"client";if(!this._deflate){let o=`${n}_max_window_bits`,i=typeof this.params[o]!="number"?_t.Z_DEFAULT_WINDOWBITS:this.params[o];this._deflate=_t.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:i}),this._deflate[te]=0,this._deflate[he]=[],this._deflate.on("data",Na)}this._deflate[$e]=s,this._deflate.write(e),this._deflate.flush(_t.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let o=Ln.concat(this._deflate[he],this._deflate[te]);r&&(o=new Aa(o.buffer,o.byteOffset,o.length-4)),this._deflate[$e]=null,this._deflate[te]=0,this._deflate[he]=[],r&&this.params[`${n}_no_context_takeover`]&&this._deflate.reset(),s(null,o)})}};Pn.exports=vr;function Na(t){this[he].push(t),this[te]+=t.length}function An(t){if(this[te]+=t.length,this[jt]._maxPayload<1||this[te]<=this[jt]._maxPayload){this[he].push(t);return}this[We]=new RangeError("Max payload size exceeded"),this[We].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[We][kn]=1009,this.removeListener("data",An),this.reset()}function Ua(t){if(this[jt]._inflate=null,this[We]){this[$e](this[We]);return}t[kn]=1007,this[$e](t)}});var Ge=q((dh,$t)=>{"use strict";l();var{isUtf8:Nn}=E("buffer"),{hasBlob:Ba}=ee(),Ma=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function Da(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function Lr(t){let e=t.length,r=0;for(;r<e;)if((t[r]&128)===0)r++;else if((t[r]&224)===192){if(r+1===e||(t[r+1]&192)!==128||(t[r]&254)===192)return!1;r+=2}else if((t[r]&240)===224){if(r+2>=e||(t[r+1]&192)!==128||(t[r+2]&192)!==128||t[r]===224&&(t[r+1]&224)===128||t[r]===237&&(t[r+1]&224)===160)return!1;r+=3}else if((t[r]&248)===240){if(r+3>=e||(t[r+1]&192)!==128||(t[r+2]&192)!==128||(t[r+3]&192)!==128||t[r]===240&&(t[r+1]&240)===128||t[r]===244&&t[r+1]>143||t[r]>244)return!1;r+=4}else return!1;return!0}function Fa(t){return Ba&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}$t.exports={isBlob:Fa,isValidStatusCode:Da,isValidUTF8:Lr,tokenChars:Ma};if(Nn)$t.exports.isValidUTF8=function(t){return t.length<24?Lr(t):Nn(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=E("utf-8-validate");$t.exports.isValidUTF8=function(e){return e.length<32?Lr(e):t(e)}}catch{}});var Ur=q((mh,$n)=>{"use strict";l();var{Writable:ja}=E("stream"),Un=Ve(),{BINARY_TYPES:$a,EMPTY_BUFFER:Bn,kStatusCode:Wa,kWebSocket:Va}=ee(),{concat:kr,toArrayBuffer:Ga,unmask:Ha}=yt(),{isValidStatusCode:za,isValidUTF8:Mn}=Ge(),Wt=Buffer[Symbol.species],j=0,Dn=1,Fn=2,jn=3,Ar=4,Pr=5,Vt=6,Nr=class extends ja{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||$a[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxBufferedChunks=e.maxBufferedChunks|0,this._maxFragments=e.maxFragments|0,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[Va]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=j}_write(e,r,s){if(this._opcode===8&&this._state==j)return s();if(this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks){s(this.createError(RangeError,"Too many buffered chunks",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS"));return}this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(s)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let s=this._buffers[0];return this._buffers[0]=new Wt(s.buffer,s.byteOffset+e,s.length-e),new Wt(s.buffer,s.byteOffset,e)}let r=Buffer.allocUnsafe(e);do{let s=this._buffers[0],n=r.length-e;e>=s.length?r.set(this._buffers.shift(),n):(r.set(new Uint8Array(s.buffer,s.byteOffset,e),n),this._buffers[0]=new Wt(s.buffer,s.byteOffset+e,s.length-e)),e-=s.length}while(e>0);return r}startLoop(e){this._loop=!0;do switch(this._state){case j:this.getInfo(e);break;case Dn:this.getPayloadLength16(e);break;case Fn:this.getPayloadLength64(e);break;case jn:this.getMask();break;case Ar:this.getData(e);break;case Pr:case Vt:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let r=this.consume(2);if((r[0]&48)!==0){let n=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(n);return}let s=(r[0]&64)===64;if(s&&!this._extensions[Un.extensionName]){let n=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(n);return}if(this._fin=(r[0]&128)===128,this._opcode=r[0]&15,this._payloadLength=r[1]&127,this._opcode===0){if(s){let n=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(n);return}if(!this._fragmented){let n=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(n);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let n=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(n);return}this._compressed=s}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let n=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(n);return}if(s){let n=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(n);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let n=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(n);return}}else{let n=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(n);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(r[1]&128)===128,this._isServer){if(!this._masked){let n=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(n);return}}else if(this._masked){let n=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(n);return}this._payloadLength===126?this._state=Dn:this._payloadLength===127?this._state=Fn:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let r=this.consume(8),s=r.readUInt32BE(0);if(s>Math.pow(2,21)-1){let n=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(n);return}this._payloadLength=s*Math.pow(2,32)+r.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let r=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(r);return}this._masked?this._state=jn:this._state=Ar}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Ar}getData(e){let r=Bn;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}r=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&Ha(r,this._mask)}if(this._opcode>7){this.controlMessage(r,e);return}if(this._compressed){this._state=Pr,this.decompress(r,e);return}if(r.length){if(this._maxFragments>0&&this._fragments.length>=this._maxFragments){let s=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");e(s);return}this._messageLength=this._totalPayloadLength,this._fragments.push(r)}this.dataMessage(e)}decompress(e,r){this._extensions[Un.extensionName].decompress(e,this._fin,(n,o)=>{if(n)return r(n);if(o.length){if(this._messageLength+=o.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let i=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");r(i);return}if(this._maxFragments>0&&this._fragments.length>=this._maxFragments){let i=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");r(i);return}this._fragments.push(o)}this.dataMessage(r),this._state===j&&this.startLoop(r)})}dataMessage(e){if(!this._fin){this._state=j;return}let r=this._messageLength,s=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let n;this._binaryType==="nodebuffer"?n=kr(s,r):this._binaryType==="arraybuffer"?n=Ga(kr(s,r)):this._binaryType==="blob"?n=new Blob(s):n=s,this._allowSynchronousEvents?(this.emit("message",n,!0),this._state=j):(this._state=Vt,setImmediate(()=>{this.emit("message",n,!0),this._state=j,this.startLoop(e)}))}else{let n=kr(s,r);if(!this._skipUTF8Validation&&!Mn(n)){let o=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(o);return}this._state===Pr||this._allowSynchronousEvents?(this.emit("message",n,!1),this._state=j):(this._state=Vt,setImmediate(()=>{this.emit("message",n,!1),this._state=j,this.startLoop(e)}))}}controlMessage(e,r){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,Bn),this.end();else{let s=e.readUInt16BE(0);if(!za(s)){let o=this.createError(RangeError,`invalid status code ${s}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");r(o);return}let n=new Wt(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Mn(n)){let o=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");r(o);return}this._loop=!1,this.emit("conclude",s,n),this.end()}this._state=j;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=j):(this._state=Vt,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=j,this.startLoop(r)}))}createError(e,r,s,n,o){this._loop=!1,this._errored=!0;let i=new e(s?`Invalid WebSocket frame: ${r}`:r);return Error.captureStackTrace(i,this.createError),i.code=o,i[Wa]=n,i}};$n.exports=Nr});var Dr=q((bh,Gn)=>{"use strict";l();var{Duplex:_h}=E("stream"),{randomFillSync:Qa}=E("crypto"),{types:{isUint8Array:Ka}}=E("util"),Wn=Ve(),{EMPTY_BUFFER:Ya,kWebSocket:Ja,NOOP:Za}=ee(),{isBlob:He,isValidStatusCode:Xa}=Ge(),{mask:Vn,toBuffer:Ce}=yt(),$=Symbol("kByteLength"),ec=Buffer.alloc(4),Gt=8*1024,Re,ze=Gt,H=0,tc=1,rc=2,Br=class t{constructor(e,r,s){this._extensions=r||{},s&&(this._generateMask=s,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=H,this.onerror=Za,this[Ja]=void 0}static frame(e,r){let s,n=!1,o=2,i=!1;r.mask&&(s=r.maskBuffer||ec,r.generateMask?r.generateMask(s):(ze===Gt&&(Re===void 0&&(Re=Buffer.alloc(Gt)),Qa(Re,0,Gt),ze=0),s[0]=Re[ze++],s[1]=Re[ze++],s[2]=Re[ze++],s[3]=Re[ze++]),i=(s[0]|s[1]|s[2]|s[3])===0,o=6);let a;typeof e=="string"?(!r.mask||i)&&r[$]!==void 0?a=r[$]:(e=Buffer.from(e),a=e.length):(a=e.length,n=r.mask&&r.readOnly&&!i);let c=a;a>=65536?(o+=8,c=127):a>125&&(o+=2,c=126);let u=Buffer.allocUnsafe(n?a+o:o);return u[0]=r.fin?r.opcode|128:r.opcode,r.rsv1&&(u[0]|=64),u[1]=c,c===126?u.writeUInt16BE(a,2):c===127&&(u[2]=u[3]=0,u.writeUIntBE(a,4,6)),r.mask?(u[1]|=128,u[o-4]=s[0],u[o-3]=s[1],u[o-2]=s[2],u[o-1]=s[3],i?[u,e]:n?(Vn(e,s,u,o,a),[u]):(Vn(e,s,e,0,a),[u,e])):[u,e]}close(e,r,s,n){let o;if(e===void 0)o=Ya;else{if(typeof e!="number"||!Xa(e))throw new TypeError("First argument must be a valid error code number");if(r===void 0||!r.length)o=Buffer.allocUnsafe(2),o.writeUInt16BE(e,0);else{let a=Buffer.byteLength(r);if(a>123)throw new RangeError("The message must not be greater than 123 bytes");if(o=Buffer.allocUnsafe(2+a),o.writeUInt16BE(e,0),typeof r=="string")o.write(r,2);else if(Ka(r))o.set(r,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let i={[$]:o.length,fin:!0,generateMask:this._generateMask,mask:s,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==H?this.enqueue([this.dispatch,o,!1,i,n]):this.sendFrame(t.frame(o,i),n)}ping(e,r,s){let n,o;if(typeof e=="string"?(n=Buffer.byteLength(e),o=!1):He(e)?(n=e.size,o=!1):(e=Ce(e),n=e.length,o=Ce.readOnly),n>125)throw new RangeError("The data size must not be greater than 125 bytes");let i={[$]:n,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:9,readOnly:o,rsv1:!1};He(e)?this._state!==H?this.enqueue([this.getBlobData,e,!1,i,s]):this.getBlobData(e,!1,i,s):this._state!==H?this.enqueue([this.dispatch,e,!1,i,s]):this.sendFrame(t.frame(e,i),s)}pong(e,r,s){let n,o;if(typeof e=="string"?(n=Buffer.byteLength(e),o=!1):He(e)?(n=e.size,o=!1):(e=Ce(e),n=e.length,o=Ce.readOnly),n>125)throw new RangeError("The data size must not be greater than 125 bytes");let i={[$]:n,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:10,readOnly:o,rsv1:!1};He(e)?this._state!==H?this.enqueue([this.getBlobData,e,!1,i,s]):this.getBlobData(e,!1,i,s):this._state!==H?this.enqueue([this.dispatch,e,!1,i,s]):this.sendFrame(t.frame(e,i),s)}send(e,r,s){let n=this._extensions[Wn.extensionName],o=r.binary?2:1,i=r.compress,a,c;typeof e=="string"?(a=Buffer.byteLength(e),c=!1):He(e)?(a=e.size,c=!1):(e=Ce(e),a=e.length,c=Ce.readOnly),this._firstFragment?(this._firstFragment=!1,i&&n&&n.params[n._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(i=a>=n._threshold),this._compress=i):(i=!1,o=0),r.fin&&(this._firstFragment=!0);let u={[$]:a,fin:r.fin,generateMask:this._generateMask,mask:r.mask,maskBuffer:this._maskBuffer,opcode:o,readOnly:c,rsv1:i};He(e)?this._state!==H?this.enqueue([this.getBlobData,e,this._compress,u,s]):this.getBlobData(e,this._compress,u,s):this._state!==H?this.enqueue([this.dispatch,e,this._compress,u,s]):this.dispatch(e,this._compress,u,s)}getBlobData(e,r,s,n){this._bufferedBytes+=s[$],this._state=rc,e.arrayBuffer().then(o=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(Mr,this,a,n);return}this._bufferedBytes-=s[$];let i=Ce(o);r?this.dispatch(i,r,s,n):(this._state=H,this.sendFrame(t.frame(i,s),n),this.dequeue())}).catch(o=>{process.nextTick(sc,this,o,n)})}dispatch(e,r,s,n){if(!r){this.sendFrame(t.frame(e,s),n);return}let o=this._extensions[Wn.extensionName];this._bufferedBytes+=s[$],this._state=tc,o.compress(e,s.fin,(i,a)=>{if(this._socket.destroyed){let c=new Error("The socket was closed while data was being compressed");Mr(this,c,n);return}this._bufferedBytes-=s[$],this._state=H,s.readOnly=!1,this.sendFrame(t.frame(a,s),n),this.dequeue()})}dequeue(){for(;this._state===H&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][$],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][$],this._queue.push(e)}sendFrame(e,r){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],r),this._socket.uncork()):this._socket.write(e[0],r)}};Gn.exports=Br;function Mr(t,e,r){typeof r=="function"&&r(e);for(let s=0;s<t._queue.length;s++){let n=t._queue[s],o=n[n.length-1];typeof o=="function"&&o(e)}}function sc(t,e,r){Mr(t,e,r),t.onerror(e)}});var eo=q((gh,Xn)=>{"use strict";l();var{kForOnEventAttribute:bt,kListener:Fr}=ee(),Hn=Symbol("kCode"),zn=Symbol("kData"),Qn=Symbol("kError"),Kn=Symbol("kMessage"),Yn=Symbol("kReason"),Qe=Symbol("kTarget"),Jn=Symbol("kType"),Zn=Symbol("kWasClean"),re=class{constructor(e){this[Qe]=null,this[Jn]=e}get target(){return this[Qe]}get type(){return this[Jn]}};Object.defineProperty(re.prototype,"target",{enumerable:!0});Object.defineProperty(re.prototype,"type",{enumerable:!0});var Te=class extends re{constructor(e,r={}){super(e),this[Hn]=r.code===void 0?0:r.code,this[Yn]=r.reason===void 0?"":r.reason,this[Zn]=r.wasClean===void 0?!1:r.wasClean}get code(){return this[Hn]}get reason(){return this[Yn]}get wasClean(){return this[Zn]}};Object.defineProperty(Te.prototype,"code",{enumerable:!0});Object.defineProperty(Te.prototype,"reason",{enumerable:!0});Object.defineProperty(Te.prototype,"wasClean",{enumerable:!0});var Ke=class extends re{constructor(e,r={}){super(e),this[Qn]=r.error===void 0?null:r.error,this[Kn]=r.message===void 0?"":r.message}get error(){return this[Qn]}get message(){return this[Kn]}};Object.defineProperty(Ke.prototype,"error",{enumerable:!0});Object.defineProperty(Ke.prototype,"message",{enumerable:!0});var wt=class extends re{constructor(e,r={}){super(e),this[zn]=r.data===void 0?null:r.data}get data(){return this[zn]}};Object.defineProperty(wt.prototype,"data",{enumerable:!0});var nc={addEventListener(t,e,r={}){for(let n of this.listeners(t))if(!r[bt]&&n[Fr]===e&&!n[bt])return;let s;if(t==="message")s=function(o,i){let a=new wt("message",{data:i?o:o.toString()});a[Qe]=this,Ht(e,this,a)};else if(t==="close")s=function(o,i){let a=new Te("close",{code:o,reason:i.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[Qe]=this,Ht(e,this,a)};else if(t==="error")s=function(o){let i=new Ke("error",{error:o,message:o.message});i[Qe]=this,Ht(e,this,i)};else if(t==="open")s=function(){let o=new re("open");o[Qe]=this,Ht(e,this,o)};else return;s[bt]=!!r[bt],s[Fr]=e,r.once?this.once(t,s):this.on(t,s)},removeEventListener(t,e){for(let r of this.listeners(t))if(r[Fr]===e&&!r[bt]){this.removeListener(t,r);break}}};Xn.exports={CloseEvent:Te,ErrorEvent:Ke,Event:re,EventTarget:nc,MessageEvent:wt};function Ht(t,e,r){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,r):t.call(e,r)}});var zt=q((Sh,to)=>{"use strict";l();var{tokenChars:gt}=Ge();function Z(t,e,r){t[e]===void 0?t[e]=[r]:t[e].push(r)}function oc(t){let e=Object.create(null),r=Object.create(null),s=!1,n=!1,o=!1,i,a,c=-1,u=-1,d=-1,p=0;for(;p<t.length;p++)if(u=t.charCodeAt(p),i===void 0)if(d===-1&>[u]===1)c===-1&&(c=p);else if(p!==0&&(u===32||u===9))d===-1&&c!==-1&&(d=p);else if(u===59||u===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${p}`);d===-1&&(d=p);let g=t.slice(c,d);u===44?(Z(e,g,r),r=Object.create(null)):i=g,c=d=-1}else throw new SyntaxError(`Unexpected character at index ${p}`);else if(a===void 0)if(d===-1&>[u]===1)c===-1&&(c=p);else if(u===32||u===9)d===-1&&c!==-1&&(d=p);else if(u===59||u===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${p}`);d===-1&&(d=p),Z(r,t.slice(c,d),!0),u===44&&(Z(e,i,r),r=Object.create(null),i=void 0),c=d=-1}else if(u===61&&c!==-1&&d===-1)a=t.slice(c,p),c=d=-1;else throw new SyntaxError(`Unexpected character at index ${p}`);else if(n){if(gt[u]!==1)throw new SyntaxError(`Unexpected character at index ${p}`);c===-1?c=p:s||(s=!0),n=!1}else if(o)if(gt[u]===1)c===-1&&(c=p);else if(u===34&&c!==-1)o=!1,d=p;else if(u===92)n=!0;else throw new SyntaxError(`Unexpected character at index ${p}`);else if(u===34&&t.charCodeAt(p-1)===61)o=!0;else if(d===-1&>[u]===1)c===-1&&(c=p);else if(c!==-1&&(u===32||u===9))d===-1&&(d=p);else if(u===59||u===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${p}`);d===-1&&(d=p);let g=t.slice(c,d);s&&(g=g.replace(/\\/g,""),s=!1),Z(r,a,g),u===44&&(Z(e,i,r),r=Object.create(null),i=void 0),a=void 0,c=d=-1}else throw new SyntaxError(`Unexpected character at index ${p}`);if(c===-1||o||u===32||u===9)throw new SyntaxError("Unexpected end of input");d===-1&&(d=p);let w=t.slice(c,d);return i===void 0?Z(e,w,r):(a===void 0?Z(r,w,!0):s?Z(r,a,w.replace(/\\/g,"")):Z(r,a,w),Z(e,i,r)),e}function ic(t){return Object.keys(t).map(e=>{let r=t[e];return Array.isArray(r)||(r=[r]),r.map(s=>[e].concat(Object.keys(s).map(n=>{let o=s[n];return Array.isArray(o)||(o=[o]),o.map(i=>i===!0?n:`${n}=${i}`).join("; ")})).join("; ")).join(", ")}).join(", ")}to.exports={format:ic,parse:oc}});var Jt=q((Th,po)=>{"use strict";l();var ac=E("events"),cc=E("https"),lc=E("http"),no=E("net"),uc=E("tls"),{randomBytes:hc,createHash:fc}=E("crypto"),{Duplex:Ch,Readable:Rh}=E("stream"),{URL:jr}=E("url"),fe=Ve(),dc=Ur(),pc=Dr(),{isBlob:mc}=Ge(),{BINARY_TYPES:ro,CLOSE_TIMEOUT:yc,EMPTY_BUFFER:Qt,GUID:_c,kForOnEventAttribute:$r,kListener:bc,kStatusCode:wc,kWebSocket:k,NOOP:oo}=ee(),{EventTarget:{addEventListener:gc,removeEventListener:xc}}=eo(),{format:Sc,parse:Ec}=zt(),{toBuffer:Cc}=yt(),io=Symbol("kAborted"),Wr=[8,13],se=["CONNECTING","OPEN","CLOSING","CLOSED"],Rc=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,R=class t extends ac{constructor(e,r,s){super(),this._binaryType=ro[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Qt,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=t.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,r===void 0?r=[]:Array.isArray(r)||(typeof r=="object"&&r!==null?(s=r,r=[]):r=[r]),ao(this,e,r,s)):(this._autoPong=s.autoPong,this._closeTimeout=s.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){ro.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,r,s){let n=new dc({allowSynchronousEvents:s.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:s.maxBufferedChunks,maxFragments:s.maxFragments,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation}),o=new pc(e,this._extensions,s.generateMask);this._receiver=n,this._sender=o,this._socket=e,n[k]=this,o[k]=this,e[k]=this,n.on("conclude",qc),n.on("drain",Oc),n.on("error",vc),n.on("message",Lc),n.on("ping",kc),n.on("pong",Ac),o.onerror=Pc,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),r.length>0&&e.unshift(r),e.on("close",uo),e.on("data",Yt),e.on("end",ho),e.on("error",fo),this._readyState=t.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[fe.extensionName]&&this._extensions[fe.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,r){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){B(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===t.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=t.CLOSING,this._sender.close(e,r,!this._isServer,s=>{s||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),lo(this)}}pause(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,r,s){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(s=e,e=r=void 0):typeof r=="function"&&(s=r,r=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Vr(this,e,s);return}r===void 0&&(r=!this._isServer),this._sender.ping(e||Qt,r,s)}pong(e,r,s){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(s=e,e=r=void 0):typeof r=="function"&&(s=r,r=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Vr(this,e,s);return}r===void 0&&(r=!this._isServer),this._sender.pong(e||Qt,r,s)}resume(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,r,s){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof r=="function"&&(s=r,r={}),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Vr(this,e,s);return}let n={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...r};this._extensions[fe.extensionName]||(n.compress=!1),this._sender.send(e||Qt,n,s)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){B(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(R,"CONNECTING",{enumerable:!0,value:se.indexOf("CONNECTING")});Object.defineProperty(R.prototype,"CONNECTING",{enumerable:!0,value:se.indexOf("CONNECTING")});Object.defineProperty(R,"OPEN",{enumerable:!0,value:se.indexOf("OPEN")});Object.defineProperty(R.prototype,"OPEN",{enumerable:!0,value:se.indexOf("OPEN")});Object.defineProperty(R,"CLOSING",{enumerable:!0,value:se.indexOf("CLOSING")});Object.defineProperty(R.prototype,"CLOSING",{enumerable:!0,value:se.indexOf("CLOSING")});Object.defineProperty(R,"CLOSED",{enumerable:!0,value:se.indexOf("CLOSED")});Object.defineProperty(R.prototype,"CLOSED",{enumerable:!0,value:se.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(R.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(R.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[$r])return e[bc];return null},set(e){for(let r of this.listeners(t))if(r[$r]){this.removeListener(t,r);break}typeof e=="function"&&this.addEventListener(t,e,{[$r]:!0})}})});R.prototype.addEventListener=gc;R.prototype.removeEventListener=xc;po.exports=R;function ao(t,e,r,s){let n={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:yc,protocolVersion:Wr[1],maxBufferedChunks:1048576,maxFragments:131072,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...s,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(t._autoPong=n.autoPong,t._closeTimeout=n.closeTimeout,!Wr.includes(n.protocolVersion))throw new RangeError(`Unsupported protocol version: ${n.protocolVersion} (supported versions: ${Wr.join(", ")})`);let o;if(e instanceof jr)o=e;else try{o=new jr(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}o.protocol==="http:"?o.protocol="ws:":o.protocol==="https:"&&(o.protocol="wss:"),t._url=o.href;let i=o.protocol==="wss:",a=o.protocol==="ws+unix:",c;if(o.protocol!=="ws:"&&!i&&!a?c=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:a&&!o.pathname?c="The URL's pathname is empty":o.hash&&(c="The URL contains a fragment identifier"),c){let m=new SyntaxError(c);if(t._redirects===0)throw m;Kt(t,m);return}let u=i?443:80,d=hc(16).toString("base64"),p=i?cc.request:lc.request,w=new Set,g;if(n.createConnection=n.createConnection||(i?Ic:Tc),n.defaultPort=n.defaultPort||u,n.port=o.port||u,n.host=o.hostname.startsWith("[")?o.hostname.slice(1,-1):o.hostname,n.headers={...n.headers,"Sec-WebSocket-Version":n.protocolVersion,"Sec-WebSocket-Key":d,Connection:"Upgrade",Upgrade:"websocket"},n.path=o.pathname+o.search,n.timeout=n.handshakeTimeout,n.perMessageDeflate&&(g=new fe({...n.perMessageDeflate,isServer:!1,maxPayload:n.maxPayload}),n.headers["Sec-WebSocket-Extensions"]=Sc({[fe.extensionName]:g.offer()})),r.length){for(let m of r){if(typeof m!="string"||!Rc.test(m)||w.has(m))throw new SyntaxError("An invalid or duplicated subprotocol was specified");w.add(m)}n.headers["Sec-WebSocket-Protocol"]=r.join(",")}if(n.origin&&(n.protocolVersion<13?n.headers["Sec-WebSocket-Origin"]=n.origin:n.headers.Origin=n.origin),(o.username||o.password)&&(n.auth=`${o.username}:${o.password}`),a){let m=n.path.split(":");n.socketPath=m[0],n.path=m[1]}let b;if(n.followRedirects){if(t._redirects===0){t._originalIpc=a,t._originalSecure=i,t._originalHostOrSocketPath=a?n.socketPath:o.host;let m=s&&s.headers;if(s={...s,headers:{}},m)for(let[C,D]of Object.entries(m))s.headers[C.toLowerCase()]=D}else if(t.listenerCount("redirect")===0){let m=a?t._originalIpc?n.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:o.host===t._originalHostOrSocketPath;(!m||t._originalSecure&&!i)&&(delete n.headers.authorization,delete n.headers.cookie,m||delete n.headers.host,n.auth=void 0)}n.auth&&!s.headers.authorization&&(s.headers.authorization="Basic "+Buffer.from(n.auth).toString("base64")),b=t._req=p(n),t._redirects&&t.emit("redirect",t.url,b)}else b=t._req=p(n);n.timeout&&b.on("timeout",()=>{B(t,b,"Opening handshake has timed out")}),b.on("error",m=>{b===null||b[io]||(b=t._req=null,Kt(t,m))}),b.on("response",m=>{let C=m.headers.location,D=m.statusCode;if(C&&n.followRedirects&&D>=300&&D<400){if(++t._redirects>n.maxRedirects){B(t,b,"Maximum redirects exceeded");return}b.abort();let we;try{we=new jr(C,e)}catch{let Ue=new SyntaxError(`Invalid URL: ${C}`);Kt(t,Ue);return}ao(t,we,r,s)}else t.emit("unexpected-response",b,m)||B(t,b,`Unexpected server response: ${m.statusCode}`)}),b.on("upgrade",(m,C,D)=>{if(t.emit("upgrade",m),t.readyState!==R.CONNECTING)return;b=t._req=null;let we=m.headers.upgrade;if(we===void 0||we.toLowerCase()!=="websocket"){B(t,C,"Invalid Upgrade header");return}let hs=fc("sha1").update(d+_c).digest("base64");if(m.headers["sec-websocket-accept"]!==hs){B(t,C,"Invalid Sec-WebSocket-Accept header");return}let Ue=m.headers["sec-websocket-protocol"],ht;if(Ue!==void 0?w.size?w.has(Ue)||(ht="Server sent an invalid subprotocol"):ht="Server sent a subprotocol but none was requested":w.size&&(ht="Server sent no subprotocol"),ht){B(t,C,ht);return}Ue&&(t._protocol=Ue);let fs=m.headers["sec-websocket-extensions"];if(fs!==void 0){if(!g){B(t,C,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let pr;try{pr=Ec(fs)}catch{B(t,C,"Invalid Sec-WebSocket-Extensions header");return}let ds=Object.keys(pr);if(ds.length!==1||ds[0]!==fe.extensionName){B(t,C,"Server indicated an extension that was not requested");return}try{g.accept(pr[fe.extensionName])}catch{B(t,C,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[fe.extensionName]=g}t.setSocket(C,D,{allowSynchronousEvents:n.allowSynchronousEvents,generateMask:n.generateMask,maxBufferedChunks:n.maxBufferedChunks,maxFragments:n.maxFragments,maxPayload:n.maxPayload,skipUTF8Validation:n.skipUTF8Validation})}),n.finishRequest?n.finishRequest(b,t):b.end()}function Kt(t,e){t._readyState=R.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function Tc(t){return t.path=t.socketPath,no.connect(t)}function Ic(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=no.isIP(t.host)?"":t.host),uc.connect(t)}function B(t,e,r){t._readyState=R.CLOSING;let s=new Error(r);Error.captureStackTrace(s,B),e.setHeader?(e[io]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Kt,t,s)):(e.destroy(s),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function Vr(t,e,r){if(e){let s=mc(e)?e.size:Cc(e).length;t._socket?t._sender._bufferedBytes+=s:t._bufferedAmount+=s}if(r){let s=new Error(`WebSocket is not open: readyState ${t.readyState} (${se[t.readyState]})`);process.nextTick(r,s)}}function qc(t,e){let r=this[k];r._closeFrameReceived=!0,r._closeMessage=e,r._closeCode=t,r._socket[k]!==void 0&&(r._socket.removeListener("data",Yt),process.nextTick(co,r._socket),t===1005?r.close():r.close(t,e))}function Oc(){let t=this[k];t.isPaused||t._socket.resume()}function vc(t){let e=this[k];e._socket[k]!==void 0&&(e._socket.removeListener("data",Yt),process.nextTick(co,e._socket),e.close(t[wc])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function so(){this[k].emitClose()}function Lc(t,e){this[k].emit("message",t,e)}function kc(t){let e=this[k];e._autoPong&&e.pong(t,!this._isServer,oo),e.emit("ping",t)}function Ac(t){this[k].emit("pong",t)}function co(t){t.resume()}function Pc(t){let e=this[k];e.readyState!==R.CLOSED&&(e.readyState===R.OPEN&&(e._readyState=R.CLOSING,lo(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function lo(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function uo(){let t=this[k];if(this.removeListener("close",uo),this.removeListener("data",Yt),this.removeListener("end",ho),t._readyState=R.CLOSING,!this._readableState.endEmitted&&!t._closeFrameReceived&&!t._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);t._receiver.write(e)}t._receiver.end(),this[k]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",so),t._receiver.on("finish",so))}function Yt(t){this[k]._receiver.write(t)||this.pause()}function ho(){let t=this[k];t._readyState=R.CLOSING,t._receiver.end(),this.end()}function fo(){let t=this[k];this.removeListener("error",fo),this.on("error",oo),t&&(t._readyState=R.CLOSING,this.destroy())}});var bo=q((Oh,_o)=>{"use strict";l();var qh=Jt(),{Duplex:Nc}=E("stream");function mo(t){t.emit("close")}function Uc(){!this.destroyed&&this._writableState.finished&&this.destroy()}function yo(t){this.removeListener("error",yo),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function Bc(t,e){let r=!0,s=new Nc({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return t.on("message",function(o,i){let a=!i&&s._readableState.objectMode?o.toString():o;s.push(a)||t.pause()}),t.once("error",function(o){s.destroyed||(r=!1,s.destroy(o))}),t.once("close",function(){s.destroyed||s.push(null)}),s._destroy=function(n,o){if(t.readyState===t.CLOSED){o(n),process.nextTick(mo,s);return}let i=!1;t.once("error",function(c){i=!0,o(c)}),t.once("close",function(){i||o(n),process.nextTick(mo,s)}),r&&t.terminate()},s._final=function(n){if(t.readyState===t.CONNECTING){t.once("open",function(){s._final(n)});return}t._socket!==null&&(t._socket._writableState.finished?(n(),s._readableState.endEmitted&&s.destroy()):(t._socket.once("finish",function(){n()}),t.close()))},s._read=function(){t.isPaused&&t.resume()},s._write=function(n,o,i){if(t.readyState===t.CONNECTING){t.once("open",function(){s._write(n,o,i)});return}t.send(n,i)},s.on("end",Uc),s.on("error",yo),s}_o.exports=Bc});var Gr=q((Lh,wo)=>{"use strict";l();var{tokenChars:Mc}=Ge();function Dc(t){let e=new Set,r=-1,s=-1,n=0;for(n;n<t.length;n++){let i=t.charCodeAt(n);if(s===-1&&Mc[i]===1)r===-1&&(r=n);else if(n!==0&&(i===32||i===9))s===-1&&r!==-1&&(s=n);else if(i===44){if(r===-1)throw new SyntaxError(`Unexpected character at index ${n}`);s===-1&&(s=n);let a=t.slice(r,s);if(e.has(a))throw new SyntaxError(`The "${a}" subprotocol is duplicated`);e.add(a),r=s=-1}else throw new SyntaxError(`Unexpected character at index ${n}`)}if(r===-1||s!==-1)throw new SyntaxError("Unexpected end of input");let o=t.slice(r,n);if(e.has(o))throw new SyntaxError(`The "${o}" subprotocol is duplicated`);return e.add(o),e}wo.exports={parse:Dc}});var To=q((Ph,Ro)=>{"use strict";l();var Fc=E("events"),Zt=E("http"),{Duplex:Ah}=E("stream"),{createHash:jc}=E("crypto"),go=zt(),Ie=Ve(),$c=Gr(),Wc=Jt(),{CLOSE_TIMEOUT:Vc,GUID:Gc,kWebSocket:Hc}=ee(),zc=/^[+/0-9A-Za-z]{22}==$/,xo=0,So=1,Co=2,Hr=class extends Fc{constructor(e,r){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxBufferedChunks:1024*1024,maxFragments:128*1024,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:Vc,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:Wc,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(e.port!=null?(this._server=Zt.createServer((s,n)=>{let o=Zt.STATUS_CODES[426];n.writeHead(426,{"Content-Length":o.length,"Content-Type":"text/plain"}),n.end(o)}),this._server.listen(e.port,e.host,e.backlog,r)):e.server&&(this._server=e.server),this._server){let s=this.emit.bind(this,"connection");this._removeListeners=Qc(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(n,o,i)=>{this.handleUpgrade(n,o,i,s)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=xo}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(this._state===Co){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(xt,this);return}if(e&&this.once("close",e),this._state!==So)if(this._state=So,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(xt,this):process.nextTick(xt,this);else{let r=this._server;this._removeListeners(),this._removeListeners=this._server=null,r.close(()=>{xt(this)})}}shouldHandle(e){if(this.options.path){let r=e.url.indexOf("?");if((r!==-1?e.url.slice(0,r):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,r,s,n){r.on("error",Eo);let o=e.headers["sec-websocket-key"],i=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){qe(this,e,r,405,"Invalid HTTP method");return}if(i===void 0||i.toLowerCase()!=="websocket"){qe(this,e,r,400,"Invalid Upgrade header");return}if(o===void 0||!zc.test(o)){qe(this,e,r,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){qe(this,e,r,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){St(r,400);return}let c=e.headers["sec-websocket-protocol"],u=new Set;if(c!==void 0)try{u=$c.parse(c)}catch{qe(this,e,r,400,"Invalid Sec-WebSocket-Protocol header");return}let d=e.headers["sec-websocket-extensions"],p={};if(this.options.perMessageDeflate&&d!==void 0){let w=new Ie({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let g=go.parse(d);g[Ie.extensionName]&&(w.accept(g[Ie.extensionName]),p[Ie.extensionName]=w)}catch{qe(this,e,r,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let w={origin:e.headers[`${a===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(w,(g,b,m,C)=>{if(!g)return St(r,b||401,m,C);this.completeUpgrade(p,o,u,e,r,s,n)});return}if(!this.options.verifyClient(w))return St(r,401)}this.completeUpgrade(p,o,u,e,r,s,n)}completeUpgrade(e,r,s,n,o,i,a){if(!o.readable||!o.writable)return o.destroy();if(o[Hc])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>xo)return St(o,503);let u=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${jc("sha1").update(r+Gc).digest("base64")}`],d=new this.options.WebSocket(null,void 0,this.options);if(s.size){let p=this.options.handleProtocols?this.options.handleProtocols(s,n):s.values().next().value;p&&(u.push(`Sec-WebSocket-Protocol: ${p}`),d._protocol=p)}if(e[Ie.extensionName]){let p=e[Ie.extensionName].params,w=go.format({[Ie.extensionName]:[p]});u.push(`Sec-WebSocket-Extensions: ${w}`),d._extensions=e}this.emit("headers",u,n),o.write(u.concat(`\r
|
|
3
|
+
`).join(`\r
|
|
4
|
+
`)),o.removeListener("error",Eo),d.setSocket(o,i,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxBufferedChunks:this.options.maxBufferedChunks,maxFragments:this.options.maxFragments,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(d),d.on("close",()=>{this.clients.delete(d),this._shouldEmitClose&&!this.clients.size&&process.nextTick(xt,this)})),a(d,n)}};Ro.exports=Hr;function Qc(t,e){for(let r of Object.keys(e))t.on(r,e[r]);return function(){for(let s of Object.keys(e))t.removeListener(s,e[s])}}function xt(t){t._state=Co,t.emit("close")}function Eo(){this.destroy()}function St(t,e,r,s){r=r||Zt.STATUS_CODES[e],s={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(r),...s},t.once("finish",t.destroy),t.end(`HTTP/1.1 ${e} ${Zt.STATUS_CODES[e]}\r
|
|
5
|
+
`+Object.keys(s).map(n=>`${n}: ${s[n]}`).join(`\r
|
|
6
|
+
`)+`\r
|
|
7
|
+
\r
|
|
8
|
+
`+r)}function qe(t,e,r,s,n,o){if(t.listenerCount("wsClientError")){let i=new Error(n);Error.captureStackTrace(i,qe),t.emit("wsClientError",i,r,e)}else St(r,s,n,o)}});var is=q((Sm,ei)=>{"use strict";l();function _u(t){var e=0,r=[];function s(){e--,e<t&&n()}function n(){var c=r.shift();a.queue=r.length,c&&i(c.fn).then(c.resolve).catch(c.reject)}function o(c){return new Promise(function(u,d){r.push({fn:c,resolve:u,reject:d}),a.queue=r.length})}function i(c){e++;try{return Promise.resolve(c()).then(function(u){return s(),u},function(u){throw s(),u})}catch(u){return s(),Promise.reject(u)}}var a=function(c){return e>=t?o(c):i(c)};return a}function bu(t,e){var r=!1,s=this;return Promise.all(t.map(function(){var n=arguments;return s(function(){if(!r)return e.apply(void 0,n).catch(function(o){throw r=!0,o})})}))}function Xo(t){return t.queue=0,t.map=bu,t}ei.exports=function(t){return Xo(t?_u(t):function(e){return e()})}});l();l();l();var _=class extends Error{code;extendedCode;rawCode;constructor(e,r,s,n,o){r!==void 0&&(e=`${r}: ${e}`),super(e,{cause:o}),this.code=r,this.extendedCode=s,this.rawCode=n,this.name="LibsqlError"}},L=class extends _{statementIndex;constructor(e,r,s,n,o,i){super(e,s,n,o,i),this.statementIndex=r,this.name="LibsqlBatchError"}};l();function ps(t){let e=ci.exec(t);if(e===null)throw new _(`The URL '${t}' is not in a valid format`,"URL_INVALID");let r=e.groups,s=r.scheme,n=r.authority!==void 0?li(r.authority):void 0,o=ge(r.path),i=r.query!==void 0?hi(r.query):void 0,a=r.fragment!==void 0?ge(r.fragment):void 0;return{scheme:s,authority:n,path:o,query:i,fragment:a}}var ci=(()=>{let t="(?<scheme>[A-Za-z][A-Za-z.+-]*)",e="(?<authority>[^/?#]*)",r="(?<path>[^?#]*)",s="(?<query>[^#]*)",n="(?<fragment>.*)";return new RegExp(`^${t}:(//${e})?${r}(\\?${s})?(#${n})?$`,"su")})();function li(t){let e=ui.exec(t);if(e===null)throw new _("The authority part of the URL is not in a valid format","URL_INVALID");let r=e.groups,s=ge(r.host_br??r.host),n=r.port?parseInt(r.port,10):void 0,o=r.username!==void 0?{username:ge(r.username),password:r.password!==void 0?ge(r.password):void 0}:void 0;return{host:s,port:n,userinfo:o}}var ui=new RegExp("^((?<username>[^:]*)(:(?<password>.*))?@)?((?<host>[^:\\[\\]]*)|(\\[(?<host_br>[^\\[\\]]*)\\]))(:(?<port>[0-9]*))?$","su");function hi(t){let e=t.split("&"),r=[];for(let s of e){if(s==="")continue;let n,o,i=s.indexOf("=");i<0?(n=s,o=""):(n=s.substring(0,i),o=s.substring(i+1)),r.push({key:ge(n.replaceAll("+"," ")),value:ge(o.replaceAll("+"," "))})}return{pairs:r}}function ge(t){try{return decodeURIComponent(t)}catch(e){throw e instanceof URIError?new _(`URL component has invalid percent encoding: ${e}`,"URL_INVALID",void 0,void 0,e):e}}function ft(t,e,r){if(e===void 0)throw new _(`URL with scheme ${JSON.stringify(t+":")} requires authority (the "//" part)`,"URL_INVALID");let s=`${t}:`,n=fi(e.host),o=di(e.port),a=`//${pi(e.userinfo)}${n}${o}`,c=r.split("/").map(encodeURIComponent).join("/");return c!==""&&!c.startsWith("/")&&(c="/"+c),new URL(`${s}${a}${c}`)}function fi(t){return t.includes(":")?`[${encodeURI(t)}]`:encodeURI(t)}function di(t){return t!==void 0?`:${t}`:""}function pi(t){if(t===void 0)return"";let e=encodeURIComponent(t.username),r=t.password!==void 0?`:${encodeURIComponent(t.password)}`:"";return`${e}${r}@`}l();l();var gs="3.7.8",mi=gs,Me=typeof Buffer=="function",ms=typeof TextDecoder=="function"?new TextDecoder:void 0,ys=typeof TextEncoder=="function"?new TextEncoder:void 0,yi="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",dt=Array.prototype.slice.call(yi),Nt=(t=>{let e={};return t.forEach((r,s)=>e[r]=s),e})(dt),_i=/^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/,P=String.fromCharCode.bind(String),_s=typeof Uint8Array.from=="function"?Uint8Array.from.bind(Uint8Array):t=>new Uint8Array(Array.prototype.slice.call(t,0)),xs=t=>t.replace(/=/g,"").replace(/[+\/]/g,e=>e=="+"?"-":"_"),Ss=t=>t.replace(/[^A-Za-z0-9\+\/]/g,""),Es=t=>{let e,r,s,n,o="",i=t.length%3;for(let a=0;a<t.length;){if((r=t.charCodeAt(a++))>255||(s=t.charCodeAt(a++))>255||(n=t.charCodeAt(a++))>255)throw new TypeError("invalid character found");e=r<<16|s<<8|n,o+=dt[e>>18&63]+dt[e>>12&63]+dt[e>>6&63]+dt[e&63]}return i?o.slice(0,i-3)+"===".substring(i):o},br=typeof btoa=="function"?t=>btoa(t):Me?t=>Buffer.from(t,"binary").toString("base64"):Es,yr=Me?t=>Buffer.from(t).toString("base64"):t=>{let r=[];for(let s=0,n=t.length;s<n;s+=4096)r.push(P.apply(null,t.subarray(s,s+4096)));return br(r.join(""))},Ut=(t,e=!1)=>e?xs(yr(t)):yr(t),bi=t=>{if(t.length<2){var e=t.charCodeAt(0);return e<128?t:e<2048?P(192|e>>>6)+P(128|e&63):P(224|e>>>12&15)+P(128|e>>>6&63)+P(128|e&63)}else{var e=65536+(t.charCodeAt(0)-55296)*1024+(t.charCodeAt(1)-56320);return P(240|e>>>18&7)+P(128|e>>>12&63)+P(128|e>>>6&63)+P(128|e&63)}},wi=/[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g,Cs=t=>t.replace(wi,bi),bs=Me?t=>Buffer.from(t,"utf8").toString("base64"):ys?t=>yr(ys.encode(t)):t=>br(Cs(t)),Be=(t,e=!1)=>e?xs(bs(t)):bs(t),ws=t=>Be(t,!0),gi=/[\xC0-\xDF][\x80-\xBF]|[\xE0-\xEF][\x80-\xBF]{2}|[\xF0-\xF7][\x80-\xBF]{3}/g,xi=t=>{switch(t.length){case 4:var e=(7&t.charCodeAt(0))<<18|(63&t.charCodeAt(1))<<12|(63&t.charCodeAt(2))<<6|63&t.charCodeAt(3),r=e-65536;return P((r>>>10)+55296)+P((r&1023)+56320);case 3:return P((15&t.charCodeAt(0))<<12|(63&t.charCodeAt(1))<<6|63&t.charCodeAt(2));default:return P((31&t.charCodeAt(0))<<6|63&t.charCodeAt(1))}},Rs=t=>t.replace(gi,xi),Ts=t=>{if(t=t.replace(/\s+/g,""),!_i.test(t))throw new TypeError("malformed base64.");t+="==".slice(2-(t.length&3));let e,r,s,n=[];for(let o=0;o<t.length;)e=Nt[t.charAt(o++)]<<18|Nt[t.charAt(o++)]<<12|(r=Nt[t.charAt(o++)])<<6|(s=Nt[t.charAt(o++)]),r===64?n.push(P(e>>16&255)):s===64?n.push(P(e>>16&255,e>>8&255)):n.push(P(e>>16&255,e>>8&255,e&255));return n.join("")},wr=typeof atob=="function"?t=>atob(Ss(t)):Me?t=>Buffer.from(t,"base64").toString("binary"):Ts,Is=Me?t=>_s(Buffer.from(t,"base64")):t=>_s(wr(t).split("").map(e=>e.charCodeAt(0))),qs=t=>Is(Os(t)),Si=Me?t=>Buffer.from(t,"base64").toString("utf8"):ms?t=>ms.decode(Is(t)):t=>Rs(wr(t)),Os=t=>Ss(t.replace(/[-_]/g,e=>e=="-"?"+":"/")),_r=t=>Si(Os(t)),Ei=t=>{if(typeof t!="string")return!1;let e=t.replace(/\s+/g,"").replace(/={0,2}$/,"");return!/[^\s0-9a-zA-Z\+/]/.test(e)||!/[^\s0-9a-zA-Z\-_]/.test(e)},vs=t=>({value:t,enumerable:!1,writable:!0,configurable:!0}),Ls=function(){let t=(e,r)=>Object.defineProperty(String.prototype,e,vs(r));t("fromBase64",function(){return _r(this)}),t("toBase64",function(e){return Be(this,e)}),t("toBase64URI",function(){return Be(this,!0)}),t("toBase64URL",function(){return Be(this,!0)}),t("toUint8Array",function(){return qs(this)})},ks=function(){let t=(e,r)=>Object.defineProperty(Uint8Array.prototype,e,vs(r));t("toBase64",function(e){return Ut(this,e)}),t("toBase64URI",function(){return Ut(this,!0)}),t("toBase64URL",function(){return Ut(this,!0)})},Ci=()=>{Ls(),ks()},De={version:gs,VERSION:mi,atob:wr,atobPolyfill:Ts,btoa:br,btoaPolyfill:Es,fromBase64:_r,toBase64:Be,encode:Be,encodeURI:ws,encodeURL:ws,utob:Cs,btou:Rs,decode:_r,isValid:Ei,fromUint8Array:Ut,toUint8Array:qs,extendString:Ls,extendUint8Array:ks,extendBuiltins:Ci};var K="https://github.com/libsql/libsql-client-ts#supported-urls";function le(t){if(t==="write")return"BEGIN IMMEDIATE";if(t==="read")return"BEGIN TRANSACTION READONLY";if(t==="deferred")return"BEGIN DEFERRED";throw RangeError('Unknown transaction mode, supported values are "write", "read" and "deferred"')}var xe=class{columns;columnTypes;rows;rowsAffected;lastInsertRowid;constructor(e,r,s,n,o){this.columns=e,this.columnTypes=r,this.rows=s,this.rowsAffected=n,this.lastInsertRowid=o}toJSON(){return{columns:this.columns,columnTypes:this.columnTypes,rows:this.rows.map(Ri),rowsAffected:this.rowsAffected,lastInsertRowid:this.lastInsertRowid!==void 0?""+this.lastInsertRowid:null}}};function Ri(t){return Array.prototype.map.call(t,Ti)}function Ti(t){return typeof t=="bigint"?""+t:t instanceof ArrayBuffer?De.fromUint8Array(new Uint8Array(t)):t}var As=":memory:";function Ps(t){return t.scheme==="file"&&(t.path===":memory:"||t.path.startsWith(":memory:?"))}function pt(t,e){if(typeof t!="object")throw new TypeError(`Expected client configuration as object, got ${typeof t}`);let{url:r,authToken:s,tls:n,intMode:o,concurrency:i}=t;i=Math.max(0,i||20),o??="number";let a=[];r===As&&(r="file::memory:");let c=ps(r),u=c.scheme.toLowerCase(),d=u==="file"&&c.path===As&&c.authority===void 0,p;d?p={cache:{values:["shared","private"],update:(m,C)=>a.push(`${m}=${C}`)}}:p={tls:{values:["0","1"],update:(m,C)=>n=C==="1"},authToken:{update:(m,C)=>s=C}};for(let{key:m,value:C}of c.query?.pairs??[]){if(!Object.hasOwn(p,m))throw new _(`Unsupported URL query parameter ${JSON.stringify(m)}`,"URL_PARAM_NOT_SUPPORTED");let D=p[m];if(D.values!==void 0&&!D.values.includes(C))throw new _(`Unknown value for the "${m}" query argument: ${JSON.stringify(C)}. Supported values are: [${D.values.map(we=>'"'+we+'"').join(", ")}]`,"URL_INVALID");D.update!==void 0&&D?.update(m,C)}let w=a.length===0?"":`?${a.join("&")}`,g=c.path+w,b;if(u==="libsql")if(n===!1){if(c.authority?.port===void 0)throw new _('A "libsql:" URL with ?tls=0 must specify an explicit port',"URL_INVALID");b=e?"http":"ws"}else b=e?"https":"wss";else b=u;if(b==="http"||b==="ws"?n??=!1:n??=!0,b!=="http"&&b!=="ws"&&b!=="https"&&b!=="wss"&&b!=="file")throw new _(`The client supports only "libsql:", "wss:", "ws:", "https:", "http:" and "file:" URLs, got ${JSON.stringify(c.scheme+":")}. For more information, please read ${K}`,"URL_SCHEME_NOT_SUPPORTED");if(o!=="number"&&o!=="bigint"&&o!=="string")throw new TypeError(`Invalid value for intMode, expected "number", "bigint" or "string", got ${JSON.stringify(o)}`);if(c.fragment!==void 0)throw new _(`URL fragments are not supported: ${JSON.stringify("#"+c.fragment)}`,"URL_INVALID");return d?{scheme:"file",tls:!1,path:g,intMode:o,concurrency:i,syncUrl:t.syncUrl,syncInterval:t.syncInterval,readYourWrites:t.readYourWrites,offline:t.offline,fetch:t.fetch,authToken:void 0,encryptionKey:void 0,remoteEncryptionKey:void 0,authority:void 0}:{scheme:b,tls:n,authority:c.authority,path:g,authToken:s,intMode:o,concurrency:i,encryptionKey:t.encryptionKey,remoteEncryptionKey:t.remoteEncryptionKey,syncUrl:t.syncUrl,syncInterval:t.syncInterval,readYourWrites:t.readYourWrites,offline:t.offline,fetch:t.fetch}}l();var mt=G(_n(),1);import{Buffer as wn}from"buffer";function gn(t){if(t.scheme!=="file")throw new _(`URL scheme ${JSON.stringify(t.scheme+":")} is not supported by the local sqlite3 client. For more information, please read ${K}`,"URL_SCHEME_NOT_SUPPORTED");let e=t.authority;if(e!==void 0){let i=e.host.toLowerCase();if(i!==""&&i!=="localhost")throw new _(`Invalid host in file URL: ${JSON.stringify(e.host)}. A "file:" URL with an absolute path should start with one slash ("file:/absolute/path.db") or with three slashes ("file:///absolute/path.db"). For more information, please read ${K}`,"URL_INVALID");if(e.port!==void 0)throw new _("File URL cannot have a port","URL_INVALID");if(e.userinfo!==void 0)throw new _("File URL cannot have username and password","URL_INVALID")}let r=Ps(t);if(r&&t.syncUrl)throw new _(`Embedded replica must use file for local db but URI with in-memory mode were provided instead: ${t.path}`,"URL_INVALID");let s=t.path;r&&(s=`${t.scheme}:${t.path}`);let n={authToken:t.authToken,encryptionKey:t.encryptionKey,remoteEncryptionKey:t.remoteEncryptionKey,syncUrl:t.syncUrl,syncPeriod:t.syncInterval,readYourWrites:t.readYourWrites,offline:t.offline},o=new mt.default(s,n);return v(o,"SELECT 1 AS checkThatTheDatabaseCanBeOpened",t.intMode),new Cr(s,n,o,t.intMode)}var Cr=class{#e;#t;#r;#s;closed;protocol;constructor(e,r,s,n){this.#e=e,this.#t=r,this.#r=s,this.#s=n,this.closed=!1,this.protocol="file"}async execute(e,r){let s;return typeof e=="string"?s={sql:e,args:r||[]}:s=e,this.#n(),v(this.#o(),s,this.#s)}async batch(e,r="deferred"){this.#n();let s=this.#o();try{v(s,le(r),this.#s);let n=[];for(let o=0;o<e.length;o++)try{if(!s.inTransaction)throw new L("The transaction has been rolled back",o,"TRANSACTION_CLOSED");let i=e[o],a=Array.isArray(i)?{sql:i[0],args:i[1]||[]}:i;n.push(v(s,a,this.#s))}catch(i){throw i instanceof L?i:i instanceof _?new L(i.message,o,i.code,i.extendedCode,i.rawCode,i.cause instanceof Error?i.cause:void 0):i}return v(s,"COMMIT",this.#s),n}finally{s.inTransaction&&v(s,"ROLLBACK",this.#s)}}async migrate(e){this.#n();let r=this.#o();try{v(r,"PRAGMA foreign_keys=off",this.#s),v(r,le("deferred"),this.#s);let s=[];for(let n=0;n<e.length;n++)try{if(!r.inTransaction)throw new L("The transaction has been rolled back",n,"TRANSACTION_CLOSED");s.push(v(r,e[n],this.#s))}catch(o){throw o instanceof L?o:o instanceof _?new L(o.message,n,o.code,o.extendedCode,o.rawCode,o.cause instanceof Error?o.cause:void 0):o}return v(r,"COMMIT",this.#s),s}finally{r.inTransaction&&v(r,"ROLLBACK",this.#s),v(r,"PRAGMA foreign_keys=on",this.#s)}}async transaction(e="write"){let r=this.#o();return v(r,le(e),this.#s),this.#r=null,new Rr(r,this.#s)}async executeMultiple(e){this.#n();let r=this.#o();try{return xn(r,e)}finally{r.inTransaction&&v(r,"ROLLBACK",this.#s)}}async sync(){this.#n();let e=await this.#o().sync();return{frames_synced:e.frames_synced,frame_no:e.frame_no}}async reconnect(){try{!this.closed&&this.#r!==null&&this.#r.close()}finally{this.#r=new mt.default(this.#e,this.#t),this.closed=!1}}close(){this.closed=!0,this.#r!==null&&(this.#r.close(),this.#r=null)}#n(){if(this.closed)throw new _("The client is closed","CLIENT_CLOSED")}#o(){return this.#r===null&&(this.#r=new mt.default(this.#e,this.#t)),this.#r}},Rr=class{#e;#t;constructor(e,r){this.#e=e,this.#t=r}async execute(e,r){let s;return typeof e=="string"?s={sql:e,args:r||[]}:s=e,this.#r(),v(this.#e,s,this.#t)}async batch(e){let r=[];for(let s=0;s<e.length;s++)try{this.#r();let n=e[s],o=Array.isArray(n)?{sql:n[0],args:n[1]||[]}:n;r.push(v(this.#e,o,this.#t))}catch(n){throw n instanceof L?n:n instanceof _?new L(n.message,s,n.code,n.extendedCode,n.rawCode,n.cause instanceof Error?n.cause:void 0):n}return r}async executeMultiple(e){return this.#r(),xn(this.#e,e)}async rollback(){this.#e.open&&(this.#r(),v(this.#e,"ROLLBACK",this.#t))}async commit(){this.#r(),v(this.#e,"COMMIT",this.#t)}close(){this.#e.inTransaction&&v(this.#e,"ROLLBACK",this.#t)}get closed(){return!this.#e.inTransaction}#r(){if(this.closed)throw new _("The transaction is closed","TRANSACTION_CLOSED")}};function v(t,e,r){let s,n;if(typeof e=="string")s=e,n=[];else if(s=e.sql,Array.isArray(e.args))n=e.args.map(o=>bn(o,r));else{n={};for(let o in e.args){let i=o[0]==="@"||o[0]==="$"||o[0]===":"?o.substring(1):o;n[i]=bn(e.args[o],r)}}try{let o=t.prepare(s);o.safeIntegers(!0);let i=!0;try{o.raw(!0)}catch{i=!1}if(i){let a=Array.from(o.columns().map(w=>w.name)),c=Array.from(o.columns().map(w=>w.type??"")),u=o.all(n).map(w=>xa(w,a,r)),d=0,p=void 0;return new xe(a,c,u,d,p)}else{let a=o.run(n),c=a.changes,u=BigInt(a.lastInsertRowid);return new xe([],[],[],c,u)}}catch(o){throw Sn(o)}}function xa(t,e,r){let s={};Object.defineProperty(s,"length",{value:t.length});for(let n=0;n<t.length;++n){let o=Sa(t[n],r);Object.defineProperty(s,n,{value:o});let i=e[n];Object.hasOwn(s,i)||Object.defineProperty(s,i,{value:o,enumerable:!0,configurable:!0,writable:!0})}return s}function Sa(t,e){if(typeof t=="bigint")if(e==="number"){if(t<Ea||t>Ca)throw new RangeError("Received integer which cannot be safely represented as a JavaScript number");return Number(t)}else{if(e==="bigint")return t;if(e==="string")return""+t;throw new Error("Invalid value for IntMode")}else if(t instanceof wn)return t.buffer;return t}var Ea=-9007199254740991n,Ca=9007199254740991n;function bn(t,e){if(typeof t=="number"){if(!Number.isFinite(t))throw new RangeError("Only finite numbers (not Infinity or NaN) can be passed as arguments");return t}else if(typeof t=="bigint"){if(t<Ra||t>Ta)throw new RangeError("bigint is too large to be represented as a 64-bit integer and passed as argument");return t}else if(typeof t=="boolean")switch(e){case"bigint":return t?1n:0n;case"string":return t?"1":"0";default:return t?1:0}else{if(t instanceof ArrayBuffer)return wn.from(t);if(t instanceof Date)return t.valueOf();if(t===void 0)throw new TypeError("undefined cannot be passed as argument to the database");return t}}var Ra=-9223372036854775808n,Ta=9223372036854775807n;function xn(t,e){try{t.exec(e)}catch(r){throw Sn(r)}}function Sn(t){if(t instanceof mt.default.SqliteError){let e=t.code,r=Ia(t.rawCode);return new _(t.message,r,e,t.rawCode,t)}return t}function Ia(t){if(t===void 0)return"SQLITE_UNKNOWN";let e=t&255;return qa[e]??`SQLITE_UNKNOWN_${e.toString()}`}var qa={1:"SQLITE_ERROR",2:"SQLITE_INTERNAL",3:"SQLITE_PERM",4:"SQLITE_ABORT",5:"SQLITE_BUSY",6:"SQLITE_LOCKED",7:"SQLITE_NOMEM",8:"SQLITE_READONLY",9:"SQLITE_INTERRUPT",10:"SQLITE_IOERR",11:"SQLITE_CORRUPT",12:"SQLITE_NOTFOUND",13:"SQLITE_FULL",14:"SQLITE_CANTOPEN",15:"SQLITE_PROTOCOL",16:"SQLITE_EMPTY",17:"SQLITE_SCHEMA",18:"SQLITE_TOOBIG",19:"SQLITE_CONSTRAINT",20:"SQLITE_MISMATCH",21:"SQLITE_MISUSE",22:"SQLITE_NOLFS",23:"SQLITE_AUTH",24:"SQLITE_FORMAT",25:"SQLITE_RANGE",26:"SQLITE_NOTADB",27:"SQLITE_NOTICE",28:"SQLITE_WARNING"};l();l();l();l();var Kc=G(bo(),1),Yc=G(zt(),1),Jc=G(Ve(),1),Zc=G(Ur(),1),Xc=G(Dr(),1),el=G(Gr(),1),Ye=G(Jt(),1),tl=G(To(),1);l();l();var Oe=class{constructor(){this.intMode="number"}intMode};l();l();l();var x=class extends Error{constructor(e){super(e),this.name="ClientError"}},y=class extends x{constructor(e){super(e),this.name="ProtoError"}},Je=class extends x{code;proto;constructor(e,r){super(e),this.name="ResponseError",this.code=r.code,this.proto=r,this.stack=void 0}},I=class extends x{constructor(e,r){r!==void 0?(super(`${e}: ${r}`),this.cause=r):super(e),this.name="ClosedError"}},Ze=class extends x{constructor(e){super(e),this.name="WebSocketUnsupportedError"}},ve=class extends x{constructor(e){super(e),this.name="WebSocketError"}},de=class extends x{status;constructor(e,r){super(e),this.status=r,this.name="HttpServerError"}};var W=class extends x{constructor(e){super(e),this.name="ProtocolVersionError"}},N=class extends x{constructor(e){super(e),this.name="InternalError"}},z=class extends x{constructor(e){super(e),this.name="MisuseError"}};function U(t){if(typeof t=="string")return t;throw Xe(t,"string")}function M(t){if(t!=null){if(typeof t=="string")return t;throw Xe(t,"string or null")}}function ne(t){if(typeof t=="number")return t;throw Xe(t,"number")}function pe(t){if(typeof t=="boolean")return t;throw Xe(t,"boolean")}function Et(t){if(Array.isArray(t))return t;throw Xe(t,"array")}function O(t){if(t!==null&&typeof t=="object"&&!Array.isArray(t))return t;throw Xe(t,"object")}function Q(t,e){return Et(t).map(r=>e(O(r)))}function Xe(t,e){if(t===void 0)return new y(`Expected ${e}, but the property was missing`);let r=typeof t;return t===null?r="null":Array.isArray(t)&&(r="array"),new y(`Expected ${e}, received ${r}`)}function Le(t,e){return e(O(t))}l();var zr=class{#e;#t;constructor(e){this.#e=e,this.#t=!1}begin(){this.#e.push("{"),this.#t=!0}end(){this.#e.push("}"),this.#t=!1}#r(e){this.#t?(this.#e.push('"'),this.#t=!1):this.#e.push(',"'),this.#e.push(e),this.#e.push('":')}string(e,r){this.#r(e),this.#e.push(JSON.stringify(r))}stringRaw(e,r){this.#r(e),this.#e.push('"'),this.#e.push(r),this.#e.push('"')}number(e,r){this.#r(e),this.#e.push(""+r)}boolean(e,r){this.#r(e),this.#e.push(r?"true":"false")}object(e,r,s){this.#r(e),this.begin(),s(this,r),this.end()}arrayObjects(e,r,s){this.#r(e),this.#e.push("[");for(let n=0;n<r.length;++n)n!==0&&this.#e.push(","),this.begin(),s(this,r[n]),this.end();this.#e.push("]")}};function Ct(t,e){let r=[],s=new zr(r);return s.begin(),e(s,t),s.end(),r.join("")}l();l();var Qr=class{#e;#t;#r;constructor(e){this.#e=e,this.#t=new DataView(e.buffer,e.byteOffset,e.byteLength),this.#r=0}varint(){let e=0;for(let r=0;;r+=7){let s=this.#e[this.#r++];if(e|=(s&127)<<r,!(s&128))break}return e}varintBig(){let e=0n;for(let r=0n;;r+=7n){let s=this.#e[this.#r++];if(e|=BigInt(s&127)<<r,!(s&128))break}return e}bytes(e){let r=new Uint8Array(this.#e.buffer,this.#e.byteOffset+this.#r,e);return this.#r+=e,r}double(){let e=this.#t.getFloat64(this.#r,!0);return this.#r+=8,e}skipVarint(){for(;this.#e[this.#r++]&128;);}skip(e){this.#r+=e}eof(){return this.#r>=this.#e.byteLength}},Kr=class{#e;#t;constructor(e){this.#e=e,this.#t=-1}setup(e){this.#t=e}#r(e){if(this.#t!==e)throw new y(`Expected wire type ${e}, got ${this.#t}`);this.#t=-1}bytes(){this.#r(2);let e=this.#e.varint();return this.#e.bytes(e)}string(){return new TextDecoder().decode(this.bytes())}message(e){return me(this.bytes(),e)}int32(){return this.#r(0),this.#e.varint()}uint32(){return this.int32()}bool(){return this.int32()!==0}uint64(){return this.#r(0),this.#e.varintBig()}sint64(){let e=this.uint64();return e>>1n^-(e&1n)}double(){return this.#r(1),this.#e.double()}maybeSkip(){if(!(this.#t<0)){if(this.#t===0)this.#e.skipVarint();else if(this.#t===1)this.#e.skip(8);else if(this.#t===2){let e=this.#e.varint();this.#e.skip(e)}else if(this.#t===5)this.#e.skip(4);else throw new y(`Unexpected wire type ${this.#t}`);this.#t=-1}}};function me(t,e){let r=new Qr(t),s=new Kr(r),n=e.default();for(;!r.eof();){let o=r.varint(),i=o>>3,a=o&7;s.setup(a);let c=e[i];if(c!==void 0){let u=c(s,n);u!==void 0&&(n=u)}s.maybeSkip()}return n}l();var Yr=class t{#e;#t;#r;#s;constructor(){this.#e=new ArrayBuffer(256),this.#t=new Uint8Array(this.#e),this.#r=new DataView(this.#e),this.#s=0}#n(e){if(this.#s+e<=this.#e.byteLength)return;let r=this.#e.byteLength;for(;r<this.#s+e;)r*=2;let s=new ArrayBuffer(r),n=new Uint8Array(s),o=new DataView(s);n.set(new Uint8Array(this.#e,0,this.#s)),this.#e=s,this.#t=n,this.#r=o}#o(e){this.#n(5),e=0|e;do{let r=e&127;e>>>=7,r|=e?128:0,this.#t[this.#s++]=r}while(e)}#i(e){this.#n(10),e=e&0xffffffffffffffffn;do{let r=Number(e&0x7fn);e>>=7n,r|=e?128:0,this.#t[this.#s++]=r}while(e)}#a(e,r){this.#o(e<<3|r)}bytes(e,r){this.#a(e,2),this.#o(r.byteLength),this.#n(r.byteLength),this.#t.set(r,this.#s),this.#s+=r.byteLength}string(e,r){this.bytes(e,new TextEncoder().encode(r))}message(e,r,s){let n=new t;s(n,r),this.bytes(e,n.data())}int32(e,r){this.#a(e,0),this.#o(r)}uint32(e,r){this.int32(e,r)}bool(e,r){this.int32(e,r?1:0)}sint64(e,r){this.#a(e,0),this.#i(r<<1n^r>>63n)}double(e,r){this.#a(e,1),this.#n(8),this.#r.setFloat64(this.#s,r,!0),this.#s+=8}data(){return new Uint8Array(this.#e,0,this.#s)}};function Rt(t,e){let r=new Yr;return e(r,t),r.data()}l();var oe=class{#e;#t;constructor(){this.#e=new Set,this.#t=new Set}alloc(){for(let r of this.#t)return this.#t.delete(r),this.#e.add(r),this.#e.has(this.#e.size-1)||this.#t.add(this.#e.size-1),r;let e=this.#e.size;return this.#e.add(e),e}free(e){if(!this.#e.delete(e))throw new N("Freeing an id that is not allocated");this.#t.delete(this.#e.size),e<this.#e.size&&this.#t.add(e)}};l();l();l();function S(t,e){throw new N(e)}function tt(t){if(t===null)return null;if(typeof t=="string")return t;if(typeof t=="number"){if(!Number.isFinite(t))throw new RangeError("Only finite numbers (not Infinity or NaN) can be passed as arguments");return t}else if(typeof t=="bigint"){if(t<nl||t>ol)throw new RangeError("This bigint value is too large to be represented as a 64-bit integer and passed as argument");return t}else{if(typeof t=="boolean")return t?1n:0n;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(t instanceof Uint8Array)return t;if(t instanceof Date)return+t.valueOf();if(typeof t=="object")return""+t.toString();throw new TypeError("Unsupported type of value")}}var nl=-9223372036854775808n,ol=9223372036854775807n;function Jr(t,e){if(t===null)return null;if(typeof t=="number")return t;if(typeof t=="string")return t;if(typeof t=="bigint")if(e==="number"){let r=Number(t);if(!Number.isSafeInteger(r))throw new RangeError("Received integer which is too large to be safely represented as a JavaScript number");return r}else{if(e==="bigint")return t;if(e==="string")return""+t;throw new z("Invalid value for IntMode")}else{if(t instanceof Uint8Array)return t.slice().buffer;throw t===void 0?new y("Received unrecognized type of Value"):S(t,"Impossible type of Value")}}function ke(t){return{affectedRowCount:t.affectedRowCount,lastInsertRowid:t.lastInsertRowid,columnNames:t.cols.map(e=>e.name),columnDecltypes:t.cols.map(e=>e.decltype)}}function rr(t,e){let r=ke(t),s=t.rows.map(n=>Io(r.columnNames,n,e));return{...r,rows:s}}function sr(t,e){let r=ke(t),s;return t.rows.length>0&&(s=Io(r.columnNames,t.rows[0],e)),{...r,row:s}}function nr(t,e){let r=ke(t),s;return t.rows.length>0&&r.columnNames.length>0&&(s=Jr(t.rows[0][0],e)),{...r,value:s}}function Io(t,e,r){let s={};Object.defineProperty(s,"length",{value:e.length});for(let n=0;n<e.length;++n){let o=Jr(e[n],r);Object.defineProperty(s,n,{value:o});let i=t[n];i!==void 0&&!Object.hasOwn(s,i)&&Object.defineProperty(s,i,{value:o,enumerable:!0,configurable:!0,writable:!0})}return s}function ie(t){return new Je(t.message,t)}l();var ye=class{#e;#t;#r;constructor(e,r){this.#e=e,this.#t=r,this.#r=void 0}_getSqlId(e){if(this.#e!==e)throw new z("Attempted to use SQL text opened with other object");if(this.#r!==void 0)throw new I("SQL text is closed",this.#r);return this.#t}close(){this._setClosed(new x("SQL text was manually closed"))}_setClosed(e){this.#r===void 0&&(this.#r=e,this.#e._closeSql(this.#t))}get closed(){return this.#r!==void 0}};function Tt(t,e){return e instanceof ye?{sqlId:e._getSqlId(t)}:{sql:""+e}}l();l();var ae=class{#e;#t;constructor(){this.#e=[],this.#t=[]}get length(){return this.#e.length+this.#t.length}push(e){this.#e.push(e)}shift(){return this.#t.length===0&&this.#e.length>0&&(this.#t=this.#e.reverse(),this.#e=[]),this.#t.pop()}first(){return this.#t.length!==0?this.#t[this.#t.length-1]:this.#e[0]}};l();l();l();var rt=class{sql;_args;_namedArgs;constructor(e){this.sql=e,this._args=[],this._namedArgs=new Map}bindIndexes(e){this._args.length=0;for(let r of e)this._args.push(tt(r));return this}bindIndex(e,r){if(e!==(e|0)||e<=0)throw new RangeError("Index of a positional argument must be positive integer");for(;this._args.length<e;)this._args.push(null);return this._args[e-1]=tt(r),this}bindName(e,r){return this._namedArgs.set(e,tt(r)),this}unbindAll(){return this._args.length=0,this._namedArgs.clear(),this}};function or(t,e,r){let s,n=[],o=[];if(e instanceof rt){s=e.sql,n=e._args;for(let[c,u]of e._namedArgs.entries())o.push({name:c,value:u})}else Array.isArray(e)?(s=e[0],Array.isArray(e[1])?n=e[1].map(c=>tt(c)):o=Object.entries(e[1]).map(([c,u])=>({name:c,value:tt(u)}))):s=e;let{sql:i,sqlId:a}=Tt(t,s);return{sql:i,sqlId:a,args:n,namedArgs:o,wantRows:r}}var It=class{_stream;#e;_steps;#t;constructor(e,r){this._stream=e,this.#e=r,this._steps=[],this.#t=!1}step(){return new ir(this)}execute(){if(this.#t)throw new z("This batch has already been executed");this.#t=!0;let e={steps:this._steps.map(r=>r.proto)};return this.#e?al(this._stream,this._steps,e):il(this._stream,this._steps,e)}};function il(t,e,r){return t._batch(r).then(s=>{for(let n=0;n<e.length;++n){let o=s.stepResults.get(n),i=s.stepErrors.get(n);e[n].callback(o,i)}})}async function al(t,e,r){let s=await t._openCursor(r);try{let n=0,o,i=[];for(;;){let a=await s.next();if(a===void 0)break;if(a.type==="step_begin"){if(a.step<n||a.step>=e.length)throw new y("Server produced StepBeginEntry for unexpected step");if(o!==void 0)throw new y("Server produced StepBeginEntry before terminating previous step");for(let c=n;c<a.step;++c)e[c].callback(void 0,void 0);n=a.step+1,o=a,i=[]}else if(a.type==="step_end"){if(o===void 0)throw new y("Server produced StepEndEntry but no step is active");let c={cols:o.cols,rows:i,affectedRowCount:a.affectedRowCount,lastInsertRowid:a.lastInsertRowid};e[o.step].callback(c,void 0),o=void 0,i=[]}else if(a.type==="step_error"){if(o===void 0){if(a.step>=e.length)throw new y("Server produced StepErrorEntry for unexpected step");for(let c=n;c<a.step;++c)e[c].callback(void 0,void 0)}else{if(a.step!==o.step)throw new y("Server produced StepErrorEntry for unexpected step");o=void 0,i=[]}e[a.step].callback(void 0,a.error),n=a.step+1}else if(a.type==="row"){if(o===void 0)throw new y("Server produced RowEntry but no step is active");i.push(a.row)}else throw a.type==="error"?ie(a.error):a.type==="none"?new y("Server produced unrecognized CursorEntry"):S(a,"Impossible CursorEntry")}if(o!==void 0)throw new y("Server closed Cursor before terminating active step");for(let a=n;a<e.length;++a)e[a].callback(void 0,void 0)}finally{s.close()}}var ir=class{_batch;#e;_index;constructor(e){this._batch=e,this.#e=[],this._index=void 0}condition(e){return this.#e.push(e._proto),this}query(e){return this.#t(e,!0,rr)}queryRow(e){return this.#t(e,!0,sr)}queryValue(e){return this.#t(e,!0,nr)}run(e){return this.#t(e,!1,ke)}#t(e,r,s){if(this._index!==void 0)throw new z("This BatchStep has already been added to the batch");let n=or(this._batch._stream._sqlOwner(),e,r),o;this.#e.length===0?o=void 0:this.#e.length===1?o=this.#e[0]:o={type:"and",conds:this.#e.slice()};let i={stmt:n,condition:o};return new Promise((a,c)=>{let u=(d,p)=>{d!==void 0&&p!==void 0?c(new y("Server returned both result and error")):p!==void 0?c(ie(p)):a(d!==void 0?s(d,this._batch._stream.intMode):void 0)};this._index=this._batch._steps.length,this._batch._steps.push({proto:i,callback:u})})}},A=class t{_batch;_proto;constructor(e,r){this._batch=e,this._proto=r}static ok(e){return new t(e._batch,{type:"ok",step:qo(e)})}static error(e){return new t(e._batch,{type:"error",step:qo(e)})}static not(e){return new t(e._batch,{type:"not",cond:e._proto})}static and(e,r){for(let s of r)Oo(e,s);return new t(e,{type:"and",conds:r.map(s=>s._proto)})}static or(e,r){for(let s of r)Oo(e,s);return new t(e,{type:"or",conds:r.map(s=>s._proto)})}static isAutocommit(e){return e._stream.client()._ensureVersion(3,"BatchCond.isAutocommit()"),new t(e,{type:"is_autocommit"})}};function qo(t){if(t._index===void 0)throw new z("Cannot add a condition referencing a step that has not been added to the batch");return t._index}function Oo(t,e){if(e._batch!==t)throw new z("Cannot mix BatchCond objects for different Batch objects")}l();function vo(t){return{paramNames:t.params.map(e=>e.name),columns:t.cols,isExplain:t.isExplain,isReadonly:t.isReadonly}}var Ae=class{constructor(e){this.intMode=e}query(e){return this.#e(e,!0,rr)}queryRow(e){return this.#e(e,!0,sr)}queryValue(e){return this.#e(e,!0,nr)}run(e){return this.#e(e,!1,ke)}#e(e,r,s){let n=or(this._sqlOwner(),e,r);return this._execute(n).then(o=>s(o,this.intMode))}batch(e=!1){return new It(this,e)}describe(e){let r=Tt(this._sqlOwner(),e);return this._describe(r).then(vo)}sequence(e){let r=Tt(this._sqlOwner(),e);return this._sequence(r)}intMode};l();l();var st=class{};var cl=1e3,ll=10,ar=class extends st{#e;#t;#r;#s;#n;#o;#i;constructor(e,r,s){super(),this.#e=e,this.#t=r,this.#r=s,this.#s=new ae,this.#n=new ae,this.#o=void 0,this.#i=!1}async next(){for(;;){if(this.#o!==void 0)throw new I("Cursor is closed",this.#o);for(;!this.#i&&this.#n.length<ll;)this.#n.push(this.#a());let e=this.#s.shift();if(this.#i||e!==void 0)return e;await this.#n.shift().then(r=>{if(r!==void 0){for(let s of r.entries)this.#s.push(s);this.#i||=r.done}})}}#a(){return this.#t._sendCursorRequest(this,{type:"fetch_cursor",cursorId:this.#r,maxCount:cl}).then(e=>e,e=>{this._setClosed(e)})}_setClosed(e){this.#o===void 0&&(this.#o=e,this.#t._sendCursorRequest(this,{type:"close_cursor",cursorId:this.#r}).catch(()=>{}),this.#t._cursorClosed(this))}close(){this._setClosed(new x("Cursor was manually closed"))}get closed(){return this.#o!==void 0}};var qt=class t extends Ae{#e;#t;#r;#s;#n;#o;static open(e){let r=e._streamIdAlloc.alloc(),s=new t(e,r),n=()=>{},o=a=>s.#u(a),i={type:"open_stream",streamId:r};return e._sendRequest(i,{responseCallback:n,errorCallback:o}),s}constructor(e,r){super(e.intMode),this.#e=e,this.#t=r,this.#r=new ae,this.#s=void 0,this.#n=!1,this.#o=void 0}client(){return this.#e}_sqlOwner(){return this.#e}_execute(e){return this.#i({type:"execute",streamId:this.#t,stmt:e}).then(r=>r.result)}_batch(e){return this.#i({type:"batch",streamId:this.#t,batch:e}).then(r=>r.result)}_describe(e){return this.#e._ensureVersion(2,"describe()"),this.#i({type:"describe",streamId:this.#t,sql:e.sql,sqlId:e.sqlId}).then(r=>r.result)}_sequence(e){return this.#e._ensureVersion(2,"sequence()"),this.#i({type:"sequence",streamId:this.#t,sql:e.sql,sqlId:e.sqlId}).then(r=>{})}getAutocommit(){return this.#e._ensureVersion(3,"getAutocommit()"),this.#i({type:"get_autocommit",streamId:this.#t}).then(e=>e.isAutocommit)}#i(e){return new Promise((r,s)=>{this.#a({type:"request",request:e,responseCallback:r,errorCallback:s})})}_openCursor(e){return this.#e._ensureVersion(3,"cursor"),new Promise((r,s)=>{this.#a({type:"cursor",batch:e,cursorCallback:r,errorCallback:s})})}_sendCursorRequest(e,r){if(e!==this.#s)throw new N("Cursor not associated with the stream attempted to execute a request");return new Promise((s,n)=>{this.#o!==void 0?n(new I("Stream is closed",this.#o)):this.#e._sendRequest(r,{responseCallback:s,errorCallback:n})})}_cursorClosed(e){if(e!==this.#s)throw new N("Cursor was closed, but it was not associated with the stream");this.#s=void 0,this.#c()}#a(e){this.#o!==void 0?e.errorCallback(new I("Stream is closed",this.#o)):this.#n?e.errorCallback(new I("Stream is closing",void 0)):(this.#r.push(e),this.#c())}#c(){for(;;){let e=this.#r.first();if(e===void 0&&this.#s===void 0&&this.#n){this.#u(new x("Stream was gracefully closed"));break}else if(e?.type==="request"&&this.#s===void 0){let{request:r,responseCallback:s,errorCallback:n}=e;this.#r.shift(),this.#e._sendRequest(r,{responseCallback:s,errorCallback:n})}else if(e?.type==="cursor"&&this.#s===void 0){let{batch:r,cursorCallback:s}=e;this.#r.shift();let n=this.#e._cursorIdAlloc.alloc(),o=new ar(this.#e,this,n),i={type:"open_cursor",streamId:this.#t,cursorId:n,batch:r},a=()=>{},c=u=>o._setClosed(u);this.#e._sendRequest(i,{responseCallback:a,errorCallback:c}),this.#s=o,s(o)}else break}}#u(e){if(this.#o!==void 0)return;for(this.#o=e,this.#s!==void 0&&this.#s._setClosed(e);;){let o=this.#r.shift();if(o!==void 0)o.errorCallback(e);else break}let r={type:"close_stream",streamId:this.#t},s=()=>this.#e._streamIdAlloc.free(this.#t),n=()=>{};this.#e._sendRequest(r,{responseCallback:s,errorCallback:n})}close(){this.#u(new x("Stream was manually closed"))}closeGracefully(){this.#n=!0,this.#c()}get closed(){return this.#o!==void 0||this.#n}};l();l();function Ot(t,e){e.sql!==void 0&&t.string("sql",e.sql),e.sqlId!==void 0&&t.number("sql_id",e.sqlId),t.arrayObjects("args",e.args,Lo),t.arrayObjects("named_args",e.namedArgs,ul),t.boolean("want_rows",e.wantRows)}function ul(t,e){t.string("name",e.name),t.object("value",e.value,Lo)}function nt(t,e){t.arrayObjects("steps",e.steps,hl)}function hl(t,e){e.condition!==void 0&&t.object("condition",e.condition,Zr),t.object("stmt",e.stmt,Ot)}function Zr(t,e){if(t.stringRaw("type",e.type),e.type==="ok"||e.type==="error")t.number("step",e.step);else if(e.type==="not")t.object("cond",e.cond,Zr);else if(e.type==="and"||e.type==="or")t.arrayObjects("conds",e.conds,Zr);else if(e.type!=="is_autocommit")throw S(e,"Impossible type of BatchCond")}function Lo(t,e){if(e===null)t.stringRaw("type","null");else if(typeof e=="bigint")t.stringRaw("type","integer"),t.stringRaw("value",""+e);else if(typeof e=="number")t.stringRaw("type","float"),t.number("value",e);else if(typeof e=="string")t.stringRaw("type","text"),t.string("value",e);else if(e instanceof Uint8Array)t.stringRaw("type","blob"),t.stringRaw("base64",De.fromUint8Array(e));else if(e!==void 0)throw S(e,"Impossible type of Value")}function ko(t,e){if(t.stringRaw("type",e.type),e.type==="hello")e.jwt!==void 0&&t.string("jwt",e.jwt);else if(e.type==="request")t.number("request_id",e.requestId),t.object("request",e.request,fl);else throw S(e,"Impossible type of ClientMsg")}function fl(t,e){if(t.stringRaw("type",e.type),e.type==="open_stream")t.number("stream_id",e.streamId);else if(e.type==="close_stream")t.number("stream_id",e.streamId);else if(e.type==="execute")t.number("stream_id",e.streamId),t.object("stmt",e.stmt,Ot);else if(e.type==="batch")t.number("stream_id",e.streamId),t.object("batch",e.batch,nt);else if(e.type==="open_cursor")t.number("stream_id",e.streamId),t.number("cursor_id",e.cursorId),t.object("batch",e.batch,nt);else if(e.type==="close_cursor")t.number("cursor_id",e.cursorId);else if(e.type==="fetch_cursor")t.number("cursor_id",e.cursorId),t.number("max_count",e.maxCount);else if(e.type==="sequence")t.number("stream_id",e.streamId),e.sql!==void 0&&t.string("sql",e.sql),e.sqlId!==void 0&&t.number("sql_id",e.sqlId);else if(e.type==="describe")t.number("stream_id",e.streamId),e.sql!==void 0&&t.string("sql",e.sql),e.sqlId!==void 0&&t.number("sql_id",e.sqlId);else if(e.type==="store_sql")t.number("sql_id",e.sqlId),t.string("sql",e.sql);else if(e.type==="close_sql")t.number("sql_id",e.sqlId);else if(e.type==="get_autocommit")t.number("stream_id",e.streamId);else throw S(e,"Impossible type of Request")}l();l();function vt(t,e){e.sql!==void 0&&t.string(1,e.sql),e.sqlId!==void 0&&t.int32(2,e.sqlId);for(let r of e.args)t.message(3,r,Po);for(let r of e.namedArgs)t.message(4,r,dl);t.bool(5,e.wantRows)}function dl(t,e){t.string(1,e.name),t.message(2,e.value,Po)}function ot(t,e){for(let r of e.steps)t.message(1,r,pl)}function pl(t,e){e.condition!==void 0&&t.message(1,e.condition,Xr),t.message(2,e.stmt,vt)}function Xr(t,e){if(e.type==="ok")t.uint32(1,e.step);else if(e.type==="error")t.uint32(2,e.step);else if(e.type==="not")t.message(3,e.cond,Xr);else if(e.type==="and")t.message(4,e.conds,Ao);else if(e.type==="or")t.message(5,e.conds,Ao);else if(e.type==="is_autocommit")t.message(6,void 0,No);else throw S(e,"Impossible type of BatchCond")}function Ao(t,e){for(let r of e)t.message(1,r,Xr)}function Po(t,e){if(e===null)t.message(1,void 0,No);else if(typeof e=="bigint")t.sint64(2,e);else if(typeof e=="number")t.double(3,e);else if(typeof e=="string")t.string(4,e);else if(e instanceof Uint8Array)t.bytes(5,e);else if(e!==void 0)throw S(e,"Impossible type of Value")}function No(t,e){}function Uo(t,e){if(e.type==="hello")t.message(1,e,ml);else if(e.type==="request")t.message(2,e,yl);else throw S(e,"Impossible type of ClientMsg")}function ml(t,e){e.jwt!==void 0&&t.string(1,e.jwt)}function yl(t,e){t.int32(1,e.requestId);let r=e.request;if(r.type==="open_stream")t.message(2,r,_l);else if(r.type==="close_stream")t.message(3,r,bl);else if(r.type==="execute")t.message(4,r,wl);else if(r.type==="batch")t.message(5,r,gl);else if(r.type==="open_cursor")t.message(6,r,xl);else if(r.type==="close_cursor")t.message(7,r,Sl);else if(r.type==="fetch_cursor")t.message(8,r,El);else if(r.type==="sequence")t.message(9,r,Cl);else if(r.type==="describe")t.message(10,r,Rl);else if(r.type==="store_sql")t.message(11,r,Tl);else if(r.type==="close_sql")t.message(12,r,Il);else if(r.type==="get_autocommit")t.message(13,r,ql);else throw S(r,"Impossible type of Request")}function _l(t,e){t.int32(1,e.streamId)}function bl(t,e){t.int32(1,e.streamId)}function wl(t,e){t.int32(1,e.streamId),t.message(2,e.stmt,vt)}function gl(t,e){t.int32(1,e.streamId),t.message(2,e.batch,ot)}function xl(t,e){t.int32(1,e.streamId),t.int32(2,e.cursorId),t.message(3,e.batch,ot)}function Sl(t,e){t.int32(1,e.cursorId)}function El(t,e){t.int32(1,e.cursorId),t.uint32(2,e.maxCount)}function Cl(t,e){t.int32(1,e.streamId),e.sql!==void 0&&t.string(2,e.sql),e.sqlId!==void 0&&t.int32(3,e.sqlId)}function Rl(t,e){t.int32(1,e.streamId),e.sql!==void 0&&t.string(2,e.sql),e.sqlId!==void 0&&t.int32(3,e.sqlId)}function Tl(t,e){t.int32(1,e.sqlId),t.string(2,e.sql)}function Il(t,e){t.int32(1,e.sqlId)}function ql(t,e){t.int32(1,e.streamId)}l();l();function _e(t){let e=U(t.message),r=M(t.code);return{message:e,code:r}}function Lt(t){let e=Q(t.cols,Bo),r=Et(t.rows).map(i=>Q(i,Mo)),s=ne(t.affected_row_count),n=M(t.last_insert_rowid),o=n!==void 0?BigInt(n):void 0;return{cols:e,rows:r,affectedRowCount:s,lastInsertRowid:o}}function Bo(t){let e=M(t.name),r=M(t.decltype);return{name:e,decltype:r}}function cr(t){let e=new Map;Et(t.step_results).forEach((s,n)=>{s!==null&&e.set(n,Lt(O(s)))});let r=new Map;return Et(t.step_errors).forEach((s,n)=>{s!==null&&r.set(n,_e(O(s)))}),{stepResults:e,stepErrors:r}}function lr(t){let e=U(t.type);if(e==="step_begin"){let r=ne(t.step),s=Q(t.cols,Bo);return{type:"step_begin",step:r,cols:s}}else if(e==="step_end"){let r=ne(t.affected_row_count),s=M(t.last_insert_rowid),n=s!==void 0?BigInt(s):void 0;return{type:"step_end",affectedRowCount:r,lastInsertRowid:n}}else if(e==="step_error"){let r=ne(t.step),s=_e(O(t.error));return{type:"step_error",step:r,error:s}}else{if(e==="row")return{type:"row",row:Q(t.row,Mo)};if(e==="error")return{type:"error",error:_e(O(t.error))};throw new y("Unexpected type of CursorEntry")}}function ur(t){let e=Q(t.params,Ol),r=Q(t.cols,vl),s=pe(t.is_explain),n=pe(t.is_readonly);return{params:e,cols:r,isExplain:s,isReadonly:n}}function Ol(t){return{name:M(t.name)}}function vl(t){let e=U(t.name),r=M(t.decltype);return{name:e,decltype:r}}function Mo(t){let e=U(t.type);if(e==="null")return null;if(e==="integer"){let r=U(t.value);return BigInt(r)}else{if(e==="float")return ne(t.value);if(e==="text")return U(t.value);if(e==="blob")return De.toUint8Array(U(t.base64));throw new y("Unexpected type of Value")}}function Do(t){let e=U(t.type);if(e==="hello_ok")return{type:"hello_ok"};if(e==="hello_error")return{type:"hello_error",error:_e(O(t.error))};if(e==="response_ok"){let r=ne(t.request_id),s=Ll(O(t.response));return{type:"response_ok",requestId:r,response:s}}else if(e==="response_error"){let r=ne(t.request_id),s=_e(O(t.error));return{type:"response_error",requestId:r,error:s}}else throw new y("Unexpected type of ServerMsg")}function Ll(t){let e=U(t.type);if(e==="open_stream")return{type:"open_stream"};if(e==="close_stream")return{type:"close_stream"};if(e==="execute")return{type:"execute",result:Lt(O(t.result))};if(e==="batch")return{type:"batch",result:cr(O(t.result))};if(e==="open_cursor")return{type:"open_cursor"};if(e==="close_cursor")return{type:"close_cursor"};if(e==="fetch_cursor"){let r=Q(t.entries,lr),s=pe(t.done);return{type:"fetch_cursor",entries:r,done:s}}else{if(e==="sequence")return{type:"sequence"};if(e==="describe")return{type:"describe",result:ur(O(t.result))};if(e==="store_sql")return{type:"store_sql"};if(e==="close_sql")return{type:"close_sql"};if(e==="get_autocommit")return{type:"get_autocommit",isAutocommit:pe(t.is_autocommit)};throw new y("Unexpected type of Response")}}l();l();var V={default(){return{message:"",code:void 0}},1(t,e){e.message=t.string()},2(t,e){e.code=t.string()}},be={default(){return{cols:[],rows:[],affectedRowCount:0,lastInsertRowid:void 0}},1(t,e){e.cols.push(t.message(Fo))},2(t,e){e.rows.push(t.message(jo))},3(t,e){e.affectedRowCount=Number(t.uint64())},4(t,e){e.lastInsertRowid=t.sint64()}},Fo={default(){return{name:void 0,decltype:void 0}},1(t,e){e.name=t.string()},2(t,e){e.decltype=t.string()}},jo={default(){return[]},1(t,e){e.push(t.message(Dl))}},it={default(){return{stepResults:new Map,stepErrors:new Map}},1(t,e){let[r,s]=t.message(kl);e.stepResults.set(r,s)},2(t,e){let[r,s]=t.message(Al);e.stepErrors.set(r,s)}},kl={default(){return[0,be.default()]},1(t,e){e[0]=t.uint32()},2(t,e){e[1]=t.message(be)}},Al={default(){return[0,V.default()]},1(t,e){e[0]=t.uint32()},2(t,e){e[1]=t.message(V)}},hr={default(){return{type:"none"}},1(t){return t.message(Pl)},2(t){return t.message(Nl)},3(t){return t.message(Ul)},4(t){return{type:"row",row:t.message(jo)}},5(t){return{type:"error",error:t.message(V)}}},Pl={default(){return{type:"step_begin",step:0,cols:[]}},1(t,e){e.step=t.uint32()},2(t,e){e.cols.push(t.message(Fo))}},Nl={default(){return{type:"step_end",affectedRowCount:0,lastInsertRowid:void 0}},1(t,e){e.affectedRowCount=t.uint32()},2(t,e){e.lastInsertRowid=t.uint64()}},Ul={default(){return{type:"step_error",step:0,error:V.default()}},1(t,e){e.step=t.uint32()},2(t,e){e.error=t.message(V)}},at={default(){return{params:[],cols:[],isExplain:!1,isReadonly:!1}},1(t,e){e.params.push(t.message(Bl))},2(t,e){e.cols.push(t.message(Ml))},3(t,e){e.isExplain=t.bool()},4(t,e){e.isReadonly=t.bool()}},Bl={default(){return{name:void 0}},1(t,e){e.name=t.string()}},Ml={default(){return{name:"",decltype:void 0}},1(t,e){e.name=t.string()},2(t,e){e.decltype=t.string()}},Dl={default(){},1(t){return null},2(t){return t.sint64()},3(t){return t.double()},4(t){return t.string()},5(t){return t.bytes()}};var $o={default(){return{type:"none"}},1(t){return{type:"hello_ok"}},2(t){return t.message(Fl)},3(t){return t.message($l)},4(t){return t.message(jl)}},Fl={default(){return{type:"hello_error",error:V.default()}},1(t,e){e.error=t.message(V)}},jl={default(){return{type:"response_error",requestId:0,error:V.default()}},1(t,e){e.requestId=t.int32()},2(t,e){e.error=t.message(V)}},$l={default(){return{type:"response_ok",requestId:0,response:{type:"none"}}},1(t,e){e.requestId=t.int32()},2(t,e){e.response={type:"open_stream"}},3(t,e){e.response={type:"close_stream"}},4(t,e){e.response=t.message(Wl)},5(t,e){e.response=t.message(Vl)},6(t,e){e.response={type:"open_cursor"}},7(t,e){e.response={type:"close_cursor"}},8(t,e){e.response=t.message(Gl)},9(t,e){e.response={type:"sequence"}},10(t,e){e.response=t.message(Hl)},11(t,e){e.response={type:"store_sql"}},12(t,e){e.response={type:"close_sql"}},13(t,e){e.response=t.message(zl)}},Wl={default(){return{type:"execute",result:be.default()}},1(t,e){e.result=t.message(be)}},Vl={default(){return{type:"batch",result:it.default()}},1(t,e){e.result=t.message(it)}},Gl={default(){return{type:"fetch_cursor",entries:[],done:!1}},1(t,e){e.entries.push(t.message(hr))},2(t,e){e.done=t.bool()}},Hl={default(){return{type:"describe",result:at.default()}},1(t,e){e.result=t.message(at)}},zl={default(){return{type:"get_autocommit",isAutocommit:!1}},1(t,e){e.isAutocommit=t.bool()}};var Wo=new Map([["hrana2",{version:2,encoding:"json"}],["hrana1",{version:1,encoding:"json"}]]),es=new Map([["hrana3-protobuf",{version:3,encoding:"protobuf"}],["hrana3",{version:3,encoding:"json"}],["hrana2",{version:2,encoding:"json"}],["hrana1",{version:1,encoding:"json"}]]),kt=class extends Oe{#e;#t;#r;#s;#n;#o;#i;#a;#c;_streamIdAlloc;_cursorIdAlloc;#u;constructor(e,r){super(),this.#e=e,this.#t=[],this.#r=!1,this.#s=void 0,this.#n=!1,this.#o=void 0,this.#i=!1,this.#a=new Map,this.#c=new oe,this._streamIdAlloc=new oe,this._cursorIdAlloc=new oe,this.#u=new oe,this.#e.binaryType="arraybuffer",this.#e.addEventListener("open",()=>this.#h()),this.#e.addEventListener("close",s=>this.#m(s)),this.#e.addEventListener("error",s=>this.#f(s)),this.#e.addEventListener("message",s=>this.#y(s)),this.#d({type:"hello",jwt:r})}#d(e){if(this.#s!==void 0)throw new N("Trying to send a message on a closed client");if(this.#r)this.#p(e);else{let r=()=>this.#p(e),s=()=>{};this.#t.push({openCallback:r,errorCallback:s})}}#h(){let e=this.#e.protocol;if(e===void 0){this.#l(new x("The `WebSocket.protocol` property is undefined. This most likely means that the WebSocket implementation provided by the environment is broken. If you are using Miniflare 2, please update to Miniflare 3, which fixes this problem."));return}else if(e==="")this.#o={version:1,encoding:"json"};else if(this.#o=es.get(e),this.#o===void 0){this.#l(new y(`Unrecognized WebSocket subprotocol: ${JSON.stringify(e)}`));return}for(let r of this.#t)r.openCallback();this.#t.length=0,this.#r=!0}#p(e){let r=this.#o.encoding;if(r==="json"){let s=Ct(e,ko);this.#e.send(s)}else if(r==="protobuf"){let s=Rt(e,Uo);this.#e.send(s)}else throw S(r,"Impossible encoding")}getVersion(){return new Promise((e,r)=>{if(this.#i=!0,this.#s!==void 0)r(this.#s);else if(this.#r)e(this.#o.version);else{let s=()=>e(this.#o.version);this.#t.push({openCallback:s,errorCallback:r})}})}_ensureVersion(e,r){if(this.#o===void 0||!this.#i)throw new W(`${r} is supported only on protocol version ${e} and higher, but the version supported by the WebSocket server is not yet known. Use Client.getVersion() to wait until the version is available.`);if(this.#o.version<e)throw new W(`${r} is supported on protocol version ${e} and higher, but the WebSocket server only supports version ${this.#o.version}`)}_sendRequest(e,r){if(this.#s!==void 0){r.errorCallback(new I("Client is closed",this.#s));return}let s=this.#c.alloc();this.#a.set(s,{...r,type:e.type}),this.#d({type:"request",requestId:s,request:e})}#f(e){let s=e.message??"WebSocket was closed due to an error";this.#l(new ve(s))}#m(e){let r=`WebSocket was closed with code ${e.code}`;e.reason&&(r+=`: ${e.reason}`),this.#l(new ve(r))}#l(e){if(this.#s===void 0){this.#s=e;for(let r of this.#t)r.errorCallback(e);this.#t.length=0;for(let[r,s]of this.#a.entries())s.errorCallback(e),this.#c.free(r);this.#a.clear(),this.#e.close()}}#y(e){if(this.#s===void 0)try{let r,s=this.#o.encoding;if(s==="json"){if(typeof e.data!="string"){this.#e.close(3003,"Only text messages are accepted with JSON encoding"),this.#l(new y("Received non-text message from server with JSON encoding"));return}r=Le(JSON.parse(e.data),Do)}else if(s==="protobuf"){if(!(e.data instanceof ArrayBuffer)){this.#e.close(3003,"Only binary messages are accepted with Protobuf encoding"),this.#l(new y("Received non-binary message from server with Protobuf encoding"));return}r=me(new Uint8Array(e.data),$o)}else throw S(s,"Impossible encoding");this.#_(r)}catch(r){this.#e.close(3007,"Could not handle message"),this.#l(r)}}#_(e){if(e.type==="none")throw new y("Received an unrecognized ServerMsg");if(e.type==="hello_ok"||e.type==="hello_error"){if(this.#n)throw new y("Received a duplicated hello response");if(this.#n=!0,e.type==="hello_error")throw ie(e.error);return}else if(!this.#n)throw new y("Received a non-hello message before a hello response");if(e.type==="response_ok"){let r=e.requestId,s=this.#a.get(r);if(this.#a.delete(r),s===void 0)throw new y("Received unexpected OK response");this.#c.free(r);try{if(s.type!==e.response.type)throw console.dir({responseState:s,msg:e}),new y("Received unexpected type of response");s.responseCallback(e.response)}catch(n){throw s.errorCallback(n),n}}else if(e.type==="response_error"){let r=e.requestId,s=this.#a.get(r);if(this.#a.delete(r),s===void 0)throw new y("Received unexpected error response");this.#c.free(r),s.errorCallback(ie(e.error))}else throw S(e,"Impossible ServerMsg type")}openStream(){return qt.open(this)}storeSql(e){this._ensureVersion(2,"storeSql()");let r=this.#u.alloc(),s=new ye(this,r),n=()=>{},o=a=>s._setClosed(a),i={type:"store_sql",sqlId:r,sql:e};return this._sendRequest(i,{responseCallback:n,errorCallback:o}),s}_closeSql(e){if(this.#s!==void 0)return;let r=()=>this.#u.free(e),s=o=>this.#l(o),n={type:"close_sql",sqlId:e};this._sendRequest(n,{responseCallback:r,errorCallback:s})}close(){this.#l(new x("Client was manually closed"))}get closed(){return this.#s!==void 0}};l();l();l();var Pe;if(typeof queueMicrotask<"u")Pe=queueMicrotask;else{let t=Promise.resolve();Pe=e=>{t.then(e)}}l();l();var fr=class{#e;#t;#r;constructor(e){this.#e=new Uint8Array(new ArrayBuffer(e)),this.#t=0,this.#r=0}get length(){return this.#r-this.#t}data(){return this.#e.slice(this.#t,this.#r)}push(e){this.#s(e.byteLength),this.#e.set(e,this.#r),this.#r+=e.byteLength}#s(e){if(this.#r+e<=this.#e.byteLength)return;let r=this.#r-this.#t;if(r+e<=this.#e.byteLength&&2*this.#r>=this.#e.byteLength)this.#e.copyWithin(0,this.#t,this.#r);else{let s=this.#e.byteLength;do s*=2;while(r+e>s);let n=new Uint8Array(new ArrayBuffer(s));n.set(this.#e.slice(this.#t,this.#r),0),this.#e=n}this.#r=r,this.#t=0}shift(e){this.#t+=e}};l();function Vo(t){let e=M(t.baton),r=M(t.base_url),s=Q(t.results,Ql);return{baton:e,baseUrl:r,results:s}}function Ql(t){let e=U(t.type);if(e==="ok")return{type:"ok",response:Kl(O(t.response))};if(e==="error")return{type:"error",error:_e(O(t.error))};throw new y("Unexpected type of StreamResult")}function Kl(t){let e=U(t.type);if(e==="close")return{type:"close"};if(e==="execute")return{type:"execute",result:Lt(O(t.result))};if(e==="batch")return{type:"batch",result:cr(O(t.result))};if(e==="sequence")return{type:"sequence"};if(e==="describe")return{type:"describe",result:ur(O(t.result))};if(e==="store_sql")return{type:"store_sql"};if(e==="close_sql")return{type:"close_sql"};if(e==="get_autocommit")return{type:"get_autocommit",isAutocommit:pe(t.is_autocommit)};throw new y("Unexpected type of StreamResponse")}function Go(t){let e=M(t.baton),r=M(t.base_url);return{baton:e,baseUrl:r}}l();var Ho={default(){return{baton:void 0,baseUrl:void 0,results:[]}},1(t,e){e.baton=t.string()},2(t,e){e.baseUrl=t.string()},3(t,e){e.results.push(t.message(Yl))}},Yl={default(){return{type:"none"}},1(t){return{type:"ok",response:t.message(Jl)}},2(t){return{type:"error",error:t.message(V)}}},Jl={default(){return{type:"none"}},1(t){return{type:"close"}},2(t){return t.message(Zl)},3(t){return t.message(Xl)},4(t){return{type:"sequence"}},5(t){return t.message(eu)},6(t){return{type:"store_sql"}},7(t){return{type:"close_sql"}},8(t){return t.message(tu)}},Zl={default(){return{type:"execute",result:be.default()}},1(t,e){e.result=t.message(be)}},Xl={default(){return{type:"batch",result:it.default()}},1(t,e){e.result=t.message(it)}},eu={default(){return{type:"describe",result:at.default()}},1(t,e){e.result=t.message(at)}},tu={default(){return{type:"get_autocommit",isAutocommit:!1}},1(t,e){e.isAutocommit=t.bool()}},zo={default(){return{baton:void 0,baseUrl:void 0}},1(t,e){e.baton=t.string()},2(t,e){e.baseUrl=t.string()}};var dr=class extends st{#e;#t;#r;#s;#n;#o;constructor(e,r){super(),this.#e=e,this.#t=r,this.#r=void 0,this.#s=new fr(16*1024),this.#n=void 0,this.#o=!1}async open(e){if(e.body===null)throw new y("No response body for cursor request");this.#r=e.body[Symbol.asyncIterator]();let r=await this.#i(Go,zo);if(r===void 0)throw new y("Empty response to cursor request");return r}next(){return this.#i(lr,hr)}close(){this._setClosed(new x("Cursor was manually closed"))}_setClosed(e){this.#n===void 0&&(this.#n=e,this.#e._cursorClosed(this),this.#r!==void 0&&this.#r.return())}get closed(){return this.#n!==void 0}async#i(e,r){for(;;){if(this.#o)return;if(this.#n!==void 0)throw new I("Cursor is closed",this.#n);if(this.#t==="json"){let o=this.#a();if(o!==void 0){let i=new TextDecoder().decode(o),a=JSON.parse(i);return Le(a,e)}}else if(this.#t==="protobuf"){let o=this.#c();if(o!==void 0)return me(o,r)}else throw S(this.#t,"Impossible encoding");if(this.#r===void 0)throw new N("Attempted to read from HTTP cursor before it was opened");let{value:s,done:n}=await this.#r.next();if(n&&this.#s.length===0)this.#o=!0;else{if(n)throw new y("Unexpected end of cursor stream");this.#s.push(s)}}}#a(){let e=this.#s.data(),s=e.indexOf(10);if(s<0)return;let n=e.slice(0,s);return this.#s.shift(s+1),n}#c(){let e=this.#s.data(),r=0,s=0;for(;;){if(s>=e.byteLength)return;let o=e[s];if(r|=(o&127)<<7*s,s+=1,!(o&128))break}if(e.byteLength<s+r)return;let n=e.slice(s,s+r);return this.#s.shift(s+r),n}};l();function Qo(t,e){e.baton!==void 0&&t.string("baton",e.baton),t.arrayObjects("requests",e.requests,ru)}function ru(t,e){if(t.stringRaw("type",e.type),e.type!=="close"){if(e.type==="execute")t.object("stmt",e.stmt,Ot);else if(e.type==="batch")t.object("batch",e.batch,nt);else if(e.type==="sequence")e.sql!==void 0&&t.string("sql",e.sql),e.sqlId!==void 0&&t.number("sql_id",e.sqlId);else if(e.type==="describe")e.sql!==void 0&&t.string("sql",e.sql),e.sqlId!==void 0&&t.number("sql_id",e.sqlId);else if(e.type==="store_sql")t.number("sql_id",e.sqlId),t.string("sql",e.sql);else if(e.type==="close_sql")t.number("sql_id",e.sqlId);else if(e.type!=="get_autocommit")throw S(e,"Impossible type of StreamRequest")}}function Ko(t,e){e.baton!==void 0&&t.string("baton",e.baton),t.object("batch",e.batch,nt)}l();function Yo(t,e){e.baton!==void 0&&t.string(1,e.baton);for(let r of e.requests)t.message(2,r,su)}function su(t,e){if(e.type==="close")t.message(1,e,nu);else if(e.type==="execute")t.message(2,e,ou);else if(e.type==="batch")t.message(3,e,iu);else if(e.type==="sequence")t.message(4,e,au);else if(e.type==="describe")t.message(5,e,cu);else if(e.type==="store_sql")t.message(6,e,lu);else if(e.type==="close_sql")t.message(7,e,uu);else if(e.type==="get_autocommit")t.message(8,e,hu);else throw S(e,"Impossible type of StreamRequest")}function nu(t,e){}function ou(t,e){t.message(1,e.stmt,vt)}function iu(t,e){t.message(1,e.batch,ot)}function au(t,e){e.sql!==void 0&&t.string(1,e.sql),e.sqlId!==void 0&&t.int32(2,e.sqlId)}function cu(t,e){e.sql!==void 0&&t.string(1,e.sql),e.sqlId!==void 0&&t.int32(2,e.sqlId)}function lu(t,e){t.int32(1,e.sqlId),t.string(2,e.sql)}function uu(t,e){t.int32(1,e.sqlId)}function hu(t,e){}function Jo(t,e){e.baton!==void 0&&t.string(1,e.baton),t.message(2,e.batch,ot)}var At=class extends Ae{#e;#t;#r;#s;#n;#o;#i;#a;#c;#u;#d;#h;#p;constructor(e,r,s,n,o){super(e.intMode),this.#e=e,this.#t=r.toString(),this.#r=s,this.#s=n,this.#n=o,this.#o=void 0,this.#i=new ae,this.#a=!1,this.#u=!1,this.#d=!1,this.#h=void 0,this.#p=new oe}client(){return this.#e}_sqlOwner(){return this}storeSql(e){let r=this.#p.alloc();return this.#f({type:"store_sql",sqlId:r,sql:e}).then(()=>{},s=>this._setClosed(s)),new ye(this,r)}_closeSql(e){this.#h===void 0&&this.#f({type:"close_sql",sqlId:e}).then(()=>this.#p.free(e),r=>this._setClosed(r))}_execute(e){return this.#f({type:"execute",stmt:e}).then(r=>r.result)}_batch(e){return this.#f({type:"batch",batch:e}).then(r=>r.result)}_describe(e){return this.#f({type:"describe",sql:e.sql,sqlId:e.sqlId}).then(r=>r.result)}_sequence(e){return this.#f({type:"sequence",sql:e.sql,sqlId:e.sqlId}).then(r=>{})}getAutocommit(){return this.#e._ensureVersion(3,"getAutocommit()"),this.#f({type:"get_autocommit"}).then(e=>e.isAutocommit)}#f(e){return new Promise((r,s)=>{this.#m({type:"pipeline",request:e,responseCallback:r,errorCallback:s})})}_openCursor(e){return new Promise((r,s)=>{this.#m({type:"cursor",batch:e,cursorCallback:r,errorCallback:s})})}_cursorClosed(e){if(e!==this.#c)throw new N("Cursor was closed, but it was not associated with the stream");this.#c=void 0,Pe(()=>this.#l())}close(){this._setClosed(new x("Stream was manually closed"))}closeGracefully(){this.#u=!0,Pe(()=>this.#l())}get closed(){return this.#h!==void 0||this.#u}_setClosed(e){if(this.#h===void 0){for(this.#h=e,this.#c!==void 0&&this.#c._setClosed(e),this.#e._streamClosed(this);;){let r=this.#i.shift();if(r!==void 0)r.errorCallback(e);else break}(this.#o!==void 0||this.#a)&&!this.#d&&(this.#i.push({type:"pipeline",request:{type:"close"},responseCallback:()=>{},errorCallback:()=>{}}),this.#d=!0,Pe(()=>this.#l()))}}#m(e){if(this.#h!==void 0)throw new I("Stream is closed",this.#h);if(this.#u)throw new I("Stream is closing",void 0);this.#i.push(e),Pe(()=>this.#l())}#l(){if(this.#a||this.#c!==void 0)return;if(this.#u&&this.#i.length===0){this._setClosed(new x("Stream was gracefully closed"));return}let e=this.#e._endpoint;if(e===void 0){this.#e._endpointPromise.then(()=>this.#l(),s=>this._setClosed(s));return}let r=this.#i.shift();if(r!==void 0)if(r.type==="pipeline"){let s=[r];for(;;){let n=this.#i.first();if(n!==void 0&&n.type==="pipeline")s.push(n),this.#i.shift();else if(n===void 0&&this.#u&&!this.#d){s.push({type:"pipeline",request:{type:"close"},responseCallback:()=>{},errorCallback:()=>{}}),this.#d=!0;break}else break}this.#y(e,s)}else if(r.type==="cursor")this.#_(e,r);else throw S(r,"Impossible type of QueueEntry")}#y(e,r){this.#b(()=>this.#g(r,e),s=>du(s,e.encoding),s=>s.baton,s=>s.baseUrl,s=>fu(r,s),s=>r.forEach(n=>n.errorCallback(s)))}#_(e,r){let s=new dr(this,e.encoding);this.#c=s,this.#b(()=>this.#x(r,e),n=>s.open(n),n=>n.baton,n=>n.baseUrl,n=>r.cursorCallback(s),n=>r.errorCallback(n))}#b(e,r,s,n,o,i){let a;try{let c=e(),u=this.#s;a=u(c)}catch(c){a=Promise.reject(c)}this.#a=!0,a.then(c=>c.ok?r(c):pu(c).then(u=>{throw u})).then(c=>{this.#o=s(c),this.#t=n(c)??this.#t,o(c)}).catch(c=>{this._setClosed(c),i(c)}).finally(()=>{this.#a=!1,this.#l()})}#g(e,r){return this.#w(new URL(r.pipelinePath,this.#t),{baton:this.#o,requests:e.map(s=>s.request)},r.encoding,Qo,Yo)}#x(e,r){if(r.cursorPath===void 0)throw new W(`Cursors are supported only on protocol version 3 and higher, but the HTTP server only supports version ${r.version}.`);return this.#w(new URL(r.cursorPath,this.#t),{baton:this.#o,batch:e.batch},r.encoding,Ko,Jo)}#w(e,r,s,n,o){let i,a;if(s==="json")i=Ct(r,n),a="application/json";else if(s==="protobuf")i=Rt(r,o),a="application/x-protobuf";else throw S(s,"Impossible encoding");let c=new Headers;return c.set("content-type",a),this.#r!==void 0&&c.set("authorization",`Bearer ${this.#r}`),this.#n!==void 0&&c.set("x-turso-encryption-key",this.#n),new Request(e.toString(),{method:"POST",headers:c,body:i})}};function fu(t,e){if(e.results.length!==t.length)throw new y("Server returned unexpected number of pipeline results");for(let r=0;r<t.length;++r){let s=e.results[r],n=t[r];if(s.type==="ok"){if(s.response.type!==n.request.type)throw new y("Received unexpected type of response");n.responseCallback(s.response)}else if(s.type==="error")n.errorCallback(ie(s.error));else throw s.type==="none"?new y("Received unrecognized type of StreamResult"):S(s,"Received impossible type of StreamResult")}}async function du(t,e){if(e==="json"){let r=await t.json();return Le(r,Vo)}if(e==="protobuf"){let r=await t.arrayBuffer();return me(new Uint8Array(r),Ho)}throw await t.body?.cancel(),S(e,"Impossible encoding")}async function pu(t){let e=t.headers.get("content-type")??"text/plain",r=`Server returned HTTP status ${t.status}`;if(e==="application/json"){let s=await t.json();return"message"in s?ie(s):new de(r,t.status)}if(e==="text/plain"){let s=(await t.text()).trim();return s!==""&&(r+=`: ${s}`),new de(r,t.status)}return await t.body?.cancel(),new de(r,t.status)}var mu=[{versionPath:"v3-protobuf",pipelinePath:"v3-protobuf/pipeline",cursorPath:"v3-protobuf/cursor",version:3,encoding:"protobuf"}],ts={versionPath:"v2",pipelinePath:"v2/pipeline",cursorPath:void 0,version:2,encoding:"json"},Pt=class extends Oe{#e;#t;#r;#s;#n;#o;_endpointPromise;_endpoint;constructor(e,r,s,n,o=2){super(),this.#e=e,this.#t=r,this.#r=s??globalThis.fetch,this.#s=n,this.#n=void 0,this.#o=new Set,o==3?(this._endpointPromise=yu(this.#r,this.#e),this._endpointPromise.then(i=>this._endpoint=i,i=>this.#i(i))):(this._endpointPromise=Promise.resolve(ts),this._endpointPromise.then(i=>this._endpoint=i,i=>this.#i(i)))}async getVersion(){return this._endpoint!==void 0?this._endpoint.version:(await this._endpointPromise).version}_ensureVersion(e,r){if(!(e<=ts.version)){if(this._endpoint===void 0)throw new W(`${r} is supported only on protocol version ${e} and higher, but the version supported by the HTTP server is not yet known. Use Client.getVersion() to wait until the version is available.`);if(this._endpoint.version<e)throw new W(`${r} is supported only on protocol version ${e} and higher, but the HTTP server only supports version ${this._endpoint.version}.`)}}openStream(){if(this.#n!==void 0)throw new I("Client is closed",this.#n);let e=new At(this,this.#e,this.#t,this.#r,this.#s);return this.#o.add(e),e}_streamClosed(e){this.#o.delete(e)}close(){this.#i(new x("Client was manually closed"))}get closed(){return this.#n!==void 0}#i(e){if(this.#n===void 0){this.#n=e;for(let r of Array.from(this.#o))r._setClosed(new I("Client was closed",e))}}};async function yu(t,e){let r=t;for(let s of mu){let n=new URL(s.versionPath,e),o=new Request(n.toString(),{method:"GET"}),i=await r(o);if(await i.arrayBuffer(),i.ok)return s}return ts}l();function rs(t,e,r=2){if(typeof Ye.default>"u")throw new Ze("WebSockets are not supported in this environment");var s=void 0;r==3?s=Array.from(es.keys()):s=Array.from(Wo.keys());let n=new Ye.default(t,s);return new kt(n,e)}function ss(t,e,r,s,n=2){return new Pt(t instanceof URL?t:new URL(t),e,r,s,n)}l();var ct=class{#e;#t;#r;constructor(e,r){this.#e=e,this.#t=r,this.#r=void 0}execute(e){return this.batch([e]).then(r=>r[0])}async batch(e){let r=this._getStream();if(r.closed)throw new _("Cannot execute statements because the transaction is closed","TRANSACTION_CLOSED");try{let s=e.map(ce),n;if(this.#r===void 0){this._getSqlCache().apply(s);let i=r.batch(this.#t>=3),a=i.step(),c=a.run(le(this.#e)),u=a;n=s.map(d=>{let p=i.step().condition(A.ok(u));this.#t>=3&&p.condition(A.not(A.isAutocommit(i)));let w=p.query(d);return w.catch(()=>{}),u=p,w}),this.#r=i.execute().then(()=>c).then(()=>{});try{await this.#r}catch(d){throw this.close(),d}}else{this.#t<3&&await this.#r,this._getSqlCache().apply(s);let i=r.batch(this.#t>=3),a;n=s.map(c=>{let u=i.step();a!==void 0&&u.condition(A.ok(a)),this.#t>=3&&u.condition(A.not(A.isAutocommit(i)));let d=u.query(c);return d.catch(()=>{}),a=u,d}),await i.execute()}let o=[];for(let i=0;i<n.length;i++)try{let a=await n[i];if(a===void 0)throw new L("Statement in a transaction was not executed, probably because the transaction has been rolled back",i,"TRANSACTION_CLOSED");o.push(ut(a))}catch(a){if(a instanceof L)throw a;let c=T(a);throw c instanceof _?new L(c.message,i,c.code,c.extendedCode,c.rawCode,c.cause instanceof Error?c.cause:void 0):c}return o}catch(s){throw T(s)}}async executeMultiple(e){let r=this._getStream();if(r.closed)throw new _("Cannot execute statements because the transaction is closed","TRANSACTION_CLOSED");try{if(this.#r===void 0){this.#r=r.run(le(this.#e)).then(()=>{});try{await this.#r}catch(s){throw this.close(),s}}else await this.#r;await r.sequence(e)}catch(s){throw T(s)}}async rollback(){try{let e=this._getStream();if(e.closed||this.#r===void 0)return;let r=e.run("ROLLBACK").catch(s=>{throw T(s)});e.closeGracefully(),await r}catch(e){throw T(e)}finally{this.close()}}async commit(){try{let e=this._getStream();if(e.closed)throw new _("Cannot commit the transaction because it is already closed","TRANSACTION_CLOSED");if(this.#r!==void 0)await this.#r;else return;let r=e.run("COMMIT").catch(s=>{throw T(s)});e.closeGracefully(),await r}catch(e){throw T(e)}finally{this.close()}}};async function lt(t,e,r,s,n=!1){n&&r.step().run("PRAGMA foreign_keys=off");let o=r.step(),i=o.run(le(t)),a=o,c=s.map(g=>{let b=r.step().condition(A.ok(a));e>=3&&b.condition(A.not(A.isAutocommit(r)));let m=b.query(g);return a=b,m}),u=r.step().condition(A.ok(a));e>=3&&u.condition(A.not(A.isAutocommit(r)));let d=u.run("COMMIT");r.step().condition(A.not(A.ok(u))).run("ROLLBACK").catch(g=>{}),n&&r.step().run("PRAGMA foreign_keys=on"),await r.execute();let w=[];await i;for(let g=0;g<c.length;g++)try{let b=await c[g];if(b===void 0)throw new L("Statement in a batch was not executed, probably because the transaction has been rolled back",g,"TRANSACTION_CLOSED");w.push(ut(b))}catch(b){if(b instanceof L)throw b;let m=T(b);throw m instanceof _?new L(m.message,g,m.code,m.extendedCode,m.rawCode,m.cause instanceof Error?m.cause:void 0):m}return await d,w}function ce(t){let e,r;Array.isArray(t)?[e,r]=t:typeof t=="string"?e=t:(e=t.sql,r=t.args);let s=new rt(e);if(r)if(Array.isArray(r))s.bindIndexes(r);else for(let[n,o]of Object.entries(r))s.bindName(n,o);return s}function ut(t){let e=t.columnNames.map(i=>i??""),r=t.columnDecltypes.map(i=>i??""),s=t.rows,n=t.affectedRowCount,o=t.lastInsertRowid!==void 0?t.lastInsertRowid:void 0;return new xe(e,r,s,n,o)}function T(t){if(t instanceof x){let e=Zo(t);return new _(t.message,e,void 0,void 0,t)}return t}function Zo(t){return t instanceof Je&&t.code!==void 0?t.code:t instanceof y?"HRANA_PROTO_ERROR":t instanceof I?t.cause instanceof x?Zo(t.cause):"HRANA_CLOSED_ERROR":t instanceof ve?"HRANA_WEBSOCKET_ERROR":t instanceof de?"SERVER_ERROR":t instanceof W?"PROTOCOL_VERSION_ERROR":t instanceof N?"INTERNAL_ERROR":"UNKNOWN"}l();var Ne=class{#e;#t;capacity;constructor(e,r){this.#e=e,this.#t=new os,this.capacity=r}apply(e){if(this.capacity<=0)return;let r=new Set;for(let s of e){if(typeof s.sql!="string")continue;let n=s.sql;if(n.length>=5e3)continue;let o=this.#t.get(n);if(o===void 0){for(;this.#t.size+1>this.capacity;){let[i,a]=this.#t.peekLru();if(r.has(a))break;a.close(),this.#t.delete(i)}this.#t.size+1<=this.capacity&&(o=this.#e.storeSql(n),this.#t.set(n,o))}o!==void 0&&(s.sql=o,r.add(o))}}},os=class{#e;constructor(){this.#e=new Map}get(e){let r=this.#e.get(e);return r!==void 0&&(this.#e.delete(e),this.#e.set(e,r)),r}set(e,r){this.#e.set(e,r)}peekLru(){for(let e of this.#e.entries())return e}delete(e){this.#e.delete(e)}get size(){return this.#e.size}};var ri=G(is(),1);function si(t){if(t.scheme!=="wss"&&t.scheme!=="ws")throw new _(`The WebSocket client supports only "libsql:", "wss:" and "ws:" URLs, got ${JSON.stringify(t.scheme+":")}. For more information, please read ${K}`,"URL_SCHEME_NOT_SUPPORTED");if(t.encryptionKey!==void 0)throw new _("Encryption key is not supported by the remote client.","ENCRYPTION_KEY_NOT_SUPPORTED");if(t.scheme==="ws"&&t.tls)throw new _('A "ws:" URL cannot opt into TLS by using ?tls=1',"URL_INVALID");if(t.scheme==="wss"&&!t.tls)throw new _('A "wss:" URL cannot opt out of TLS by using ?tls=0',"URL_INVALID");let e=ft(t.scheme,t.authority,t.path),r;try{r=rs(e,t.authToken)}catch(s){if(s instanceof Ze){let n=t.scheme==="wss"?"https":"http",o=ft(n,t.authority,t.path);throw new _(`This environment does not support WebSockets, please switch to the HTTP client by using a "${n}:" URL (${JSON.stringify(o)}). For more information, please read ${K}`,"WEBSOCKETS_NOT_SUPPORTED")}throw T(s)}return new as(r,e,t.authToken,t.intMode,t.concurrency)}var wu=60*1e3,ti=100,as=class{#e;#t;#r;#s;#n;closed;protocol;#o;#i;constructor(e,r,s,n,o){this.#e=r,this.#t=s,this.#r=n,this.#s=this.#c(e),this.#n=void 0,this.closed=!1,this.protocol="ws",this.#i=(0,ri.default)(o)}async limit(e){return this.#i(e)}async execute(e,r){let s;return typeof e=="string"?s={sql:e,args:r||[]}:s=e,this.limit(async()=>{let n=await this.#a();try{let o=ce(s);n.conn.sqlCache.apply([o]);let i=n.stream.query(o);n.stream.closeGracefully();let a=await i;return ut(a)}catch(o){throw T(o)}finally{this._closeStream(n)}})}async batch(e,r="deferred"){return this.limit(async()=>{let s=await this.#a();try{let o=e.map(d=>Array.isArray(d)?{sql:d[0],args:d[1]||[]}:d).map(ce),i=await s.conn.client.getVersion();s.conn.sqlCache.apply(o);let a=s.stream.batch(i>=3);return await lt(r,i,a,o)}catch(n){throw T(n)}finally{this._closeStream(s)}})}async migrate(e){return this.limit(async()=>{let r=await this.#a();try{let s=e.map(ce),n=await r.conn.client.getVersion(),o=r.stream.batch(n>=3);return await lt("deferred",n,o,s,!0)}catch(s){throw T(s)}finally{this._closeStream(r)}})}async transaction(e="write"){return this.limit(async()=>{let r=await this.#a();try{let s=await r.conn.client.getVersion();return new cs(this,r,e,s)}catch(s){throw this._closeStream(r),T(s)}})}async executeMultiple(e){return this.limit(async()=>{let r=await this.#a();try{let s=r.stream.sequence(e);r.stream.closeGracefully(),await s}catch(s){throw T(s)}finally{this._closeStream(r)}})}sync(){throw new _("sync not supported in ws mode","SYNC_NOT_SUPPORTED")}async#a(){if(this.closed)throw new _("The client is closed","CLIENT_CLOSED");if(new Date().valueOf()-this.#s.openTime.valueOf()>wu&&this.#n===void 0){let n=this.#c();this.#n=n,n.client.getVersion().then(o=>{this.#s!==n&&this.#s.streamStates.size===0&&this.#s.client.close(),this.#s=n,this.#n=void 0},o=>{this.#n=void 0})}if(this.#s.client.closed)try{this.#n!==void 0?this.#s=this.#n:this.#s=this.#c()}catch(n){throw T(n)}let s=this.#s;try{s.useSqlCache===void 0&&(s.useSqlCache=await s.client.getVersion()>=2,s.useSqlCache&&(s.sqlCache.capacity=ti));let n=s.client.openStream();n.intMode=this.#r;let o={conn:s,stream:n};return s.streamStates.add(o),o}catch(n){throw T(n)}}#c(e){try{return e??=rs(this.#e,this.#t),{client:e,useSqlCache:void 0,sqlCache:new Ne(e,0),openTime:new Date,streamStates:new Set}}catch(r){throw T(r)}}async reconnect(){try{for(let s of Array.from(this.#s.streamStates))try{s.stream.close()}catch{}this.#s.client.close()}catch{}if(this.#n){try{this.#n.client.close()}catch{}this.#n=void 0}let e=this.#c(),r=await e.client.getVersion();e.useSqlCache=r>=2,e.useSqlCache&&(e.sqlCache.capacity=ti),this.#s=e,this.closed=!1}_closeStream(e){e.stream.close();let r=e.conn;r.streamStates.delete(e),r.streamStates.size===0&&r!==this.#s&&r.client.close()}close(){if(this.#s.client.close(),this.closed=!0,this.#n){try{this.#n.client.close()}catch{}this.#n=void 0}this.closed=!0}},cs=class extends ct{#e;#t;constructor(e,r,s,n){super(s,n),this.#e=e,this.#t=r}_getStream(){return this.#t.stream}_getSqlCache(){return this.#t.conn.sqlCache}close(){this.#e._closeStream(this.#t)}get closed(){return this.#t.stream.closed}};l();var ni=G(is(),1);function oi(t){if(t.scheme!=="https"&&t.scheme!=="http")throw new _(`The HTTP client supports only "libsql:", "https:" and "http:" URLs, got ${JSON.stringify(t.scheme+":")}. For more information, please read ${K}`,"URL_SCHEME_NOT_SUPPORTED");if(t.encryptionKey!==void 0)throw new _("Encryption key is not supported by the remote client.","ENCRYPTION_KEY_NOT_SUPPORTED");if(t.scheme==="http"&&t.tls)throw new _('A "http:" URL cannot opt into TLS by using ?tls=1',"URL_INVALID");if(t.scheme==="https"&&!t.tls)throw new _('A "https:" URL cannot opt out of TLS by using ?tls=0',"URL_INVALID");let e=ft(t.scheme,t.authority,t.path);return new ls(e,t.authToken,t.intMode,t.fetch,t.concurrency,t.remoteEncryptionKey)}var ii=30,ls=class{#e;protocol;#t;#r;#s;#n;#o;#i;#a;constructor(e,r,s,n,o,i){this.#t=e,this.#o=r,this.#r=s,this.#s=n,this.#n=o,this.#i=i,this.#e=ss(this.#t,this.#o,this.#s,i),this.#e.intMode=this.#r,this.protocol="http",this.#a=(0,ni.default)(this.#n)}async limit(e){return this.#a(e)}async execute(e,r){let s;return typeof e=="string"?s={sql:e,args:r||[]}:s=e,this.limit(async()=>{try{let n=ce(s),o,i=this.#e.openStream();try{o=i.query(n)}finally{i.closeGracefully()}let a=await o;return ut(a)}catch(n){throw T(n)}})}async batch(e,r="deferred"){return this.limit(async()=>{try{let n=e.map(u=>Array.isArray(u)?{sql:u[0],args:u[1]||[]}:u).map(ce),o=await this.#e.getVersion(),i,a=this.#e.openStream();try{new Ne(a,ii).apply(n);let d=a.batch(!1);i=lt(r,o,d,n)}finally{a.closeGracefully()}return await i}catch(s){throw T(s)}})}async migrate(e){return this.limit(async()=>{try{let r=e.map(ce),s=await this.#e.getVersion(),n,o=this.#e.openStream();try{let a=o.batch(!1);n=lt("deferred",s,a,r,!0)}finally{o.closeGracefully()}return await n}catch(r){throw T(r)}})}async transaction(e="write"){return this.limit(async()=>{try{let r=await this.#e.getVersion();return new us(this.#e.openStream(),e,r)}catch(r){throw T(r)}})}async executeMultiple(e){return this.limit(async()=>{try{let r,s=this.#e.openStream();try{r=s.sequence(e)}finally{s.closeGracefully()}await r}catch(r){throw T(r)}})}sync(){throw new _("sync not supported in http mode","SYNC_NOT_SUPPORTED")}close(){this.#e.close()}async reconnect(){try{this.closed||this.#e.close()}finally{this.#e=ss(this.#t,this.#o,this.#s,this.#i),this.#e.intMode=this.#r}}get closed(){return this.#e.closed}},us=class extends ct{#e;#t;constructor(e,r,s){super(r,s),this.#e=e,this.#t=new Ne(e,ii)}_getStream(){return this.#e}_getSqlCache(){return this.#t}close(){this.#e.close()}get closed(){return this.#e.closed}};function Hm(t){return gu(pt(t,!0))}function gu(t){return t.scheme==="wss"||t.scheme==="ws"?si(t):t.scheme==="https"||t.scheme==="http"?oi(t):gn(t)}export{L as LibsqlBatchError,_ as LibsqlError,Hm as createClient};
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { createRequire } from 'module'; const require = createRequire(import.meta.url);
|
|
2
|
+
import{h as Q}from"./chunk-VULBPPPP.mjs";Q();import dn from"os";import pn from"fs";Q();Q();var He=new Map,st=new Map,at=Symbol("OriginError"),Te={},re=class extends Promise{constructor(r,n,a,i,u={}){let o,c;super((d,j)=>{o=d,c=j}),this.tagged=Array.isArray(r.raw),this.strings=r,this.args=n,this.handler=a,this.canceller=i,this.options=u,this.state=null,this.statement=null,this.resolve=d=>(this.active=!1,o(d)),this.reject=d=>(this.active=!1,c(d)),this.active=!1,this.cancelled=null,this.executed=!1,this.signature="",this[at]=this.handler.debug?new Error:this.tagged&&Qr(this.strings)}get origin(){return(this.handler.debug?this[at].stack:this.tagged&&st.has(this.strings)?st.get(this.strings):st.set(this.strings,this[at].stack).get(this.strings))||""}static get[Symbol.species](){return Promise}cancel(){return this.canceller&&(this.canceller(this),this.canceller=null)}simple(){return this.options.simple=!0,this.options.prepare=!1,this}async readable(){return this.simple(),this.streaming=!0,this}async writable(){return this.simple(),this.streaming=!0,this}cursor(r=1,n){if(this.options.simple=!1,typeof r=="function"&&(n=r,r=1),this.cursorRows=r,typeof n=="function")return this.cursorFn=n,this;let a;return{[Symbol.asyncIterator]:()=>({next:()=>{if(this.executed&&!this.active)return{done:!0};a&&a();let i=new Promise((u,o)=>{this.cursorFn=c=>(u({value:c,done:!1}),new Promise(d=>a=d)),this.resolve=()=>(this.active=!1,u({done:!0})),this.reject=c=>(this.active=!1,o(c))});return this.execute(),i},return(){return a&&a(Te),{done:!0}}})}}describe(){return this.options.simple=!1,this.onlyDescribe=this.options.prepare=!0,this}stream(){throw new Error(".stream has been renamed to .forEach")}forEach(r){return this.forEachFn=r,this.handle(),this}raw(){return this.isRaw=!0,this}values(){return this.isRaw="values",this}async handle(){!this.executed&&(this.executed=!0)&&await 1&&this.handler(this)}execute(){return this.handle(),this}then(){return this.handle(),super.then.apply(this,arguments)}catch(){return this.handle(),super.catch.apply(this,arguments)}finally(){return this.handle(),super.finally.apply(this,arguments)}};function Qr(e){if(He.has(e))return He.get(e);let r=Error.stackTraceLimit;return Error.stackTraceLimit=4,He.set(e,new Error),Error.stackTraceLimit=r,He.get(e)}Q();var _e=class extends Error{constructor(r){super(r.message),this.name=this.constructor.name,Object.assign(this,r)}},z={connection:Nt,postgres:Ut,generic:jt,notSupported:Rt};function Nt(e,r,n){let{host:a,port:i}=n||r,u=Object.assign(new Error("write "+e+" "+(r.path||a+":"+i)),{code:e,errno:e,address:r.path||a},r.path?{}:{port:i});return Error.captureStackTrace(u,Nt),u}function Ut(e){let r=new _e(e);return Error.captureStackTrace(r,Ut),r}function jt(e,r){let n=Object.assign(new Error(e+": "+r),{code:e});return Error.captureStackTrace(n,jt),n}function Rt(e){let r=Object.assign(new Error(e+" (B) is not supported"),{code:"MESSAGE_NOT_SUPPORTED",name:e});return Error.captureStackTrace(r,Rt),r}var Hr={string:{to:25,from:null,serialize:e=>""+e},number:{to:0,from:[21,23,26,700,701],serialize:e=>""+e,parse:e=>+e},json:{to:114,from:[114,3802],serialize:e=>JSON.stringify(e),parse:e=>JSON.parse(e)},boolean:{to:16,from:16,serialize:e=>e===!0?"t":"f",parse:e=>e==="t"},date:{to:1184,from:[1082,1114,1184],serialize:e=>(e instanceof Date?e:new Date(e)).toISOString(),parse:e=>new Date(e)},bytea:{to:17,from:17,serialize:e=>"\\x"+Buffer.from(e).toString("hex"),parse:e=>Buffer.from(e.slice(2),"hex")}},ke=class{then(){ot()}catch(){ot()}finally(){ot()}},Ie=class extends ke{constructor(r){super(),this.value=We(r)}},ie=class extends ke{constructor(r,n,a){super(),this.value=r,this.type=n,this.array=a}},Fe=class extends ke{constructor(r,n){super(),this.first=r,this.rest=n}build(r,n,a,i){let u=Kr.map(([o,c])=>({fn:c,i:r.search(o)})).sort((o,c)=>o.i-c.i).pop();return u.i===-1?ft(this.first,i):u.fn(this.first,this.rest,n,a,i)}};function Ye(e,r,n,a){let i=e instanceof ie?e.value:e;if(i===void 0&&(e instanceof ie?e.value=a.transform.undefined:i=e=a.transform.undefined,i===void 0))throw z.generic("UNDEFINED_VALUE","Undefined values are not allowed");return"$"+n.push(e instanceof ie?(r.push(e.value),e.array?e.array[e.type||Ve(e.value)]||e.type||Lt(e.value):e.type):(r.push(e),Ve(e)))}var kt=zt(Hr);function lt(e,r,n,a,i,u){for(let o=1;o<e.strings.length;o++)r+=ut(r,n,a,i,u)+e.strings[o],n=e.args[o];return r}function ut(e,r,n,a,i){return r instanceof Fe?r.build(e,n,a,i):r instanceof re?ct(r,n,a,i):r instanceof Ie?r.value:r&&r[0]instanceof re?r.reduce((u,o)=>u+" "+ct(o,n,a,i),""):Ye(r,n,a,i)}function ct(e,r,n,a){return e.fragment=!0,lt(e,e.strings[0],e.args[0],r,n,a)}function Ft(e,r,n,a,i){return e.map(u=>"("+a.map(o=>ut("values",u[o],r,n,i)).join(",")+")").join(",")}function Dt(e,r,n,a,i){let u=Array.isArray(e[0]),o=r.length?r.flat():Object.keys(u?e[0]:e);return Ft(u?e:[e],n,a,o,i)}function Ke(e,r,n,a,i){if(typeof e=="string"&&(e=[e].concat(r)),Array.isArray(e))return ft(e,i);let u;return(r.length?r.flat():Object.keys(e)).map(c=>(u=e[c],(u instanceof re?ct(u,n,a,i):u instanceof Ie?u.value:Ye(u,n,a,i))+" as "+We(i.transform.column.to?i.transform.column.to(c):c))).join(",")}var Kr=Object.entries({values:Dt,in:(...e)=>{let r=Dt(...e);return r==="()"?"(null)":r},select:Ke,as:Ke,returning:Ke,"\\(":Ke,update(e,r,n,a,i){return(r.length?r.flat():Object.keys(e)).map(u=>We(i.transform.column.to?i.transform.column.to(u):u)+"="+ut("values",e[u],n,a,i))},insert(e,r,n,a,i){let u=r.length?r.flat():Object.keys(Array.isArray(e)?e[0]:e);return"("+ft(u,i)+")values"+Ft(Array.isArray(e)?e:[e],n,a,u,i)}}).map(([e,r])=>[new RegExp("((?:^|[\\s(])"+e+"(?:$|[\\s(]))(?![\\s\\S]*\\1)","i"),r]);function ot(){throw z.generic("NOT_TAGGED_CALL","Query not called as a tagged template literal")}var Vr=kt.serializers,Yr=kt.parsers;function Lt(e){return Array.isArray(e)?Lt(e[0]):typeof e=="string"?1009:0}var Mt=function(e){let r=zt(e||{});return{serializers:Object.assign({},Vr,r.serializers),parsers:Object.assign({},Yr,r.parsers)}};function zt(e){return Object.keys(e).reduce((r,n)=>(e[n].from&&[].concat(e[n].from).forEach(a=>r.parsers[a]=e[n].parse),e[n].serialize&&(r.serializers[e[n].to]=e[n].serialize,e[n].from&&[].concat(e[n].from).forEach(a=>r.serializers[a]=e[n].serialize)),r),{parsers:{},serializers:{}})}function ft(e,{transform:{column:r}}){return e.map(n=>We(r.to?r.to(n):n)).join(",")}var We=function(r){return'"'+r.replace(/"/g,'""').replace(/\./g,'"."')+'"'},Ve=function e(r){return r instanceof ie?r.type:r instanceof Date?1184:r instanceof Uint8Array?17:r===!0||r===!1?16:typeof r=="bigint"?20:Array.isArray(r)?e(r[0]):0},Wr=/\\/g,Xr=/"/g;function Jr(e){return e.replace(Wr,"\\\\").replace(Xr,'\\"')}var $t=function e(r,n,a,i){if(Array.isArray(r)===!1)return r;if(!r.length)return"{}";let u=r[0],o=i===1020?";":",";return Array.isArray(u)&&!u.type?"{"+r.map(c=>e(c,n,a,i)).join(o)+"}":"{"+r.map(c=>{if(c===void 0&&(c=a.transform.undefined,c===void 0))throw z.generic("UNDEFINED_VALUE","Undefined values are not allowed");return c===null?"null":'"'+Jr(n?n(c.type?c.value:c):""+c)+'"'}).join(o)+"}"},it={i:0,char:null,str:"",quoted:!1,last:0},Gt=function(r,n,a){return it.i=it.last=0,Qt(it,r,n,a)};function Qt(e,r,n,a){let i=[],u=a===1020?";":",";for(;e.i<r.length;e.i++){if(e.char=r[e.i],e.quoted)e.char==="\\"?e.str+=r[++e.i]:e.char==='"'?(i.push(n?n(e.str):e.str),e.str="",e.quoted=r[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,i.push(Qt(e,r,n,a));else if(e.char==="}"){e.quoted=!1,e.last<e.i&&i.push(n?n(r.slice(e.last,e.i)):r.slice(e.last,e.i)),e.last=e.i+1;break}else e.char===u&&e.p!=="}"&&e.p!=='"'&&(i.push(n?n(r.slice(e.last,e.i)):r.slice(e.last,e.i)),e.last=e.i+1);e.p=e.char}return e.last<e.i&&i.push(n?n(r.slice(e.last,e.i+1)):r.slice(e.last,e.i+1)),i}var Se=e=>{let r=e[0];for(let n=1;n<e.length;n++)r+=e[n]==="_"?e[++n].toUpperCase():e[n];return r},ve=e=>{let r=e[0].toUpperCase();for(let n=1;n<e.length;n++)r+=e[n]==="_"?e[++n].toUpperCase():e[n];return r},Ae=e=>e.replace(/_/g,"-"),Le=e=>e.replace(/([A-Z])/g,"_$1").toLowerCase(),Me=e=>(e.slice(0,1)+e.slice(1).replace(/([A-Z])/g,"_$1")).toLowerCase(),ze=e=>e.replace(/-/g,"_");function mt(e){return function r(n,a){return typeof n=="object"&&n!==null&&(a.type===114||a.type===3802)?Array.isArray(n)?n.map(i=>r(i,a)):Object.entries(n).reduce((i,[u,o])=>Object.assign(i,{[e(u)]:r(o,a)}),{}):n}}Se.column={from:Se};Se.value={from:mt(Se)};Le.column={to:Le};var dt={...Se};dt.column.to=Le;ve.column={from:ve};ve.value={from:mt(ve)};Me.column={to:Me};var pt={...ve};pt.column.to=Me;Ae.column={from:Ae};Ae.value={from:mt(Ae)};ze.column={to:ze};var ht={...Ae};ht.column.to=ze;Q();import Ht from"net";import en from"tls";import $e from"crypto";import gt from"stream";import{performance as Kt}from"perf_hooks";Q();var we=class extends Array{constructor(){super(),Object.defineProperties(this,{count:{value:null,writable:!0},state:{value:null,writable:!0},command:{value:null,writable:!0},columns:{value:null,writable:!0},statement:{value:null,writable:!0}})}static get[Symbol.species](){return Array}};Q();var ne=Zr;function Zr(e=[]){let r=e.slice(),n=0;return{get length(){return r.length-n},remove:a=>{let i=r.indexOf(a);return i===-1?null:(r.splice(i,1),a)},push:a=>(r.push(a),a),shift:()=>{let a=r[n++];return n===r.length?(n=0,r=[]):r[n-1]=void 0,a}}}Q();var X=Buffer.allocUnsafe(256),qr="BCcDdEFfHPpQSX".split("").reduce((e,r)=>{let n=r.charCodeAt(0);return e[r]=()=>(X[0]=n,B.i=5,B),e},{}),B=Object.assign(xr,qr,{N:"\0",i:0,inc(e){return B.i+=e,B},str(e){let r=Buffer.byteLength(e);return Xe(r),B.i+=X.write(e,B.i,r,"utf8"),B},i16(e){return Xe(2),X.writeUInt16BE(e,B.i),B.i+=2,B},i32(e,r){return r||r===0?(X.writeUInt32BE(e,r),B):(Xe(4),X.writeUInt32BE(e,B.i),B.i+=4,B)},z(e){return Xe(e),X.fill(0,B.i,B.i+e),B.i+=e,B},raw(e){return X=Buffer.concat([X.subarray(0,B.i),e]),B.i=X.length,B},end(e=1){X.writeUInt32BE(B.i-e,e);let r=X.subarray(0,B.i);return B.i=0,X=Buffer.allocUnsafe(256),r}}),p=B;function Xe(e){if(X.length-B.i<e){let r=X,n=r.length;X=Buffer.allocUnsafe(n+(n>>1)+e),r.copy(X)}}function xr(){return B.i=0,B}var wt=Wt,tn=1,be=p().S().end(),Vt=p().H().end(),rn=p().i32(8).i32(80877103).end(8),nn=Buffer.concat([p().E().str(p.N).i32(0).end(),be]),sn=p().D().str("S").str(p.N).end(),Ne=()=>{},an=new Set(["FetchPreparedStatement","RevalidateCachedQuery","transformAssignedExpr"]),on={83:"severity_local",86:"severity",67:"code",77:"message",68:"detail",72:"hint",80:"position",112:"internal_position",113:"internal_query",87:"where",115:"schema_name",116:"table_name",99:"column_name",100:"data type_name",110:"constraint_name",70:"file",76:"line",82:"routine"};function Wt(e,r={},{onopen:n=Ne,onend:a=Ne,onclose:i=Ne}={}){let{sslnegotiation:u,ssl:o,max:c,user:d,host:j,port:C,database:P,parsers:b,transform:E,onnotice:R,onnotify:g,onparameter:H,max_pipeline:N,keep_alive:oe,backoff:se,target_session_attrs:ee}=e,S=ne(),he=tn++,le={pid:null,secret:null},Oe=yt(rt,e.idle_timeout),Ee=yt(rt,e.max_lifetime),v=yt(rr,e.connect_timeout),m=null,ue,x=null,A=new we,J=Buffer.alloc(0),Pe=e.fetch_types,fe={},l={},y=Math.random().toString(36).slice(2),U=1,$=0,L=0,w=0,O=0,k=0,F=0,G=0,Z=null,T=null,me=!1,ce=null,ge=null,V=null,D=null,I=null,te=null,Ge=null,et=null,f=null,Ue=null,Y={queue:r.closed,idleTimer:Oe,connect(t){V=t,Pt()},terminate:De,execute:je,cancel:qt,end:rt,count:0,id:he};return r.closed&&r.closed.push(Y),Y;async function Zt(){let t;try{t=e.socket?await Promise.resolve(e.socket(e)):new Ht.Socket}catch(s){Ce(s);return}return t.on("error",Ce),t.on("close",Bt),t.on("drain",At),t}async function qt({pid:t,secret:s},h,_){try{ue=p().i32(16).i32(80877102).i32(t).i32(s).end(16),await Ot(),m.once("error",_),m.once("close",h)}catch(M){_(M)}}function je(t){if(me)return Re(t,z.connection("CONNECTION_DESTROYED",e));if(I)return Re(t,z.generic("COPY_IN_PROGRESS","You cannot execute queries during copy"));if(!t.cancelled)try{return t.state=le,f?S.push(t):(f=t,f.active=!0),tr(t),K(xt(t))&&!t.describeFirst&&!t.cursorFn&&S.length<N&&(!t.options.onexecute||t.options.onexecute(Y))}catch(s){return S.length===0&&K(be),ae(s),!0}}function xt(t){if(t.parameters.length>=65534)throw z.generic("MAX_PARAMETERS_EXCEEDED","Max number of parameters (65534) exceeded");return t.options.simple?p().Q().str(t.statement.string+p.N).end():t.describeFirst?Buffer.concat([_t(t),Vt]):t.prepare?t.prepared?Qe(t):Buffer.concat([_t(t),Qe(t)]):er(t)}function _t(t){return Buffer.concat([Tt(t.statement.string,t.parameters,t.statement.types,t.statement.name),zr("S",t.statement.name)])}function Qe(t){return Buffer.concat([Mr(t.parameters,t.statement.types,t.statement.name,t.cursorName),t.cursorFn?It("",t.cursorRows):nn])}function er(t){return Buffer.concat([Tt(t.statement.string,t.parameters,t.statement.types),sn,Qe(t)])}function tr(t){let s=[],h=[],_=lt(t,t.strings[0],t.args[0],s,h,e);!t.tagged&&t.args.forEach(M=>Ye(M,s,h,e)),t.prepare=e.prepare&&("prepare"in t.options?t.options.prepare:!0),t.string=_,t.signature=t.prepare&&h+_,t.onlyDescribe&&delete l[t.signature],t.parameters=t.parameters||s,t.prepared=t.prepare&&t.signature in l,t.describeFirst=t.onlyDescribe||s.length&&!t.prepared,t.statement=t.prepared?l[t.signature]:{string:_,types:h,name:t.prepare?y+U++:""},typeof e.debug=="function"&&e.debug(he,_,s,h)}function K(t,s){return te=te?Buffer.concat([te,t]):Buffer.from(t),s||te.length>=1024?St(s):(T===null&&(T=setImmediate(St)),!0)}function St(t){let s=m.write(te,t);return T!==null&&clearImmediate(T),te=T=null,s}function rr(){ae(z.connection("CONNECT_TIMEOUT",e,m)),m.destroy()}async function vt(){if(u!=="direct"&&(K(rn),!await new Promise(h=>m.once("data",_=>h(_[0]===83)))&&o==="prefer"))return Be();let t={socket:m,servername:Ht.isIP(m.host)?void 0:m.host};u==="direct"&&(t.ALPNProtocols=["postgresql"]),o==="require"||o==="allow"||o==="prefer"?t.rejectUnauthorized=!1:typeof o=="object"&&Object.assign(t,o),m.removeAllListeners(),m=en.connect(t),m.on("secureConnect",Be),m.on("error",Ce),m.on("close",Bt),m.on("drain",At)}function At(){!f&&n(Y)}function tt(t){if(!(ce&&(ce.push(t),L-=t.length,L>0)))for(J=ce?Buffer.concat(ce,k-L):J.length===0?t:Buffer.concat([J,t],J.length+t.length);J.length>4;){if(k=J.readUInt32BE(1),k>=J.length){L=k-J.length,ce=[J];break}try{nr(J.subarray(0,k+1))}catch(s){f&&(f.cursorFn||f.describeFirst)&&K(be),ae(s)}J=J.subarray(k+1),L=0,ce=null}}async function Ot(){if(me=!1,fe={},m||(m=await Zt()),!!m){if(v.start(),e.socket)return o?vt():Be();if(m.on("connect",o?vt:Be),e.path)return m.connect(e.path);m.ssl=o,m.connect(C[w],j[w]),m.host=j[w],m.port=C[w],w=(w+1)%C.length}}function Pt(){setTimeout(Ot,$?Math.max(0,$+F-Kt.now()):0)}function Be(){try{l={},Pe=e.fetch_types,y=Math.random().toString(36).slice(2),U=1,Ee.start(),m.on("data",tt),oe&&m.setKeepAlive&&m.setKeepAlive(!0,1e3*oe);let t=Gr();K(t)}catch(t){Ce(t)}}function Ce(t){if(!(Y.queue===r.connecting&&e.host[O+1]))for(ae(t);S.length;)Re(S.shift(),t)}function ae(t){I&&(I.destroy(t),I=null),f&&Re(f,t),V&&(Re(V,t),V=null)}function Re(t,s){if(t.reserve)return t.reject(s);(!s||typeof s!="object")&&(s=new Error(s)),"query"in s||"parameters"in s||Object.defineProperties(s,{stack:{value:s.stack+t.origin.replace(/.*\n/,`
|
|
3
|
+
`),enumerable:e.debug},query:{value:t.string,enumerable:e.debug},parameters:{value:t.parameters,enumerable:e.debug},args:{value:t.args,enumerable:e.debug},types:{value:t.statement&&t.statement.types,enumerable:e.debug}}),t.reject(s)}function rt(){return D||(!Y.reserved&&a(Y),!Y.reserved&&!V&&!f&&S.length===0?(De(),new Promise(t=>m&&m.readyState!=="closed"?m.once("close",t):t())):D=new Promise(t=>Ge=t))}function De(){me=!0,(I||f||V||S.length)&&Ce(z.connection("CONNECTION_DESTROYED",e)),clearImmediate(T),m&&(m.removeListener("data",tt),m.removeListener("connect",Be),m.readyState==="open"&&m.end(p().X().end())),Ge&&(Ge(),D=Ge=null)}async function Bt(t){if(J=Buffer.alloc(0),L=0,ce=null,clearImmediate(T),m.removeListener("data",tt),m.removeListener("connect",Be),Oe.cancel(),Ee.cancel(),v.cancel(),m.removeAllListeners(),m=null,V)return Pt();!t&&(f||S.length)&&Ce(z.connection("CONNECTION_CLOSED",e,m)),$=Kt.now(),t&&e.shared.retries++,F=(typeof se=="function"?se(e.shared.retries):se)*1e3,i(Y,z.connection("CONNECTION_CLOSED",e,m))}function nr(t,s=t[0]){(s===68?sr:s===100?Nr:s===65?Or:s===83?ar:s===90?or:s===67?ir:s===50?Ct:s===49?cr:s===116?lr:s===84?ur:s===82?fr:s===110?yr:s===75?wr:s===69?vr:s===115?Pr:s===51?Br:s===71?Cr:s===78?jr:s===72?Tr:s===99?Ur:s===73?Rr:s===86?Dr:s===118?kr:s===87?Ir:Fr)(t)}function sr(t){let s=7,h,_,M,W=f.isRaw?new Array(f.statement.columns.length):{};for(let q=0;q<f.statement.columns.length;q++)_=f.statement.columns[q],h=t.readInt32BE(s),s+=4,M=h===-1?null:f.isRaw===!0?t.subarray(s,s+=h):_.parser===void 0?t.toString("utf8",s,s+=h):_.parser.array===!0?_.parser(t.toString("utf8",s+1,s+=h)):_.parser(t.toString("utf8",s,s+=h)),f.isRaw?W[q]=f.isRaw===!0?M:E.value.from?E.value.from(M,_):M:W[_.name]=E.value.from?E.value.from(M,_):M;f.forEachFn?f.forEachFn(E.row.from?E.row.from(W):W,A):A[G++]=E.row.from?E.row.from(W):W}function ar(t){let[s,h]=t.toString("utf8",5,t.length-1).split(p.N);fe[s]=h,e.parameters[s]!==h&&(e.parameters[s]=h,H&&H(s,h))}function or(t){if(f?x?f.retried?ae(f.retried):f.prepared&&an.has(x.routine)?Ar(f,x):ae(x):f.resolve(ge||A):x&&ae(x),f=ge=x=null,A=new we,v.cancel(),V){if(ee){if(!fe.in_hot_standby||!fe.default_transaction_read_only)return Sr();if(_r(ee,fe))return De()}if(Pe)return V.reserve&&(V=null),br();V&&!V.reserve&&je(V),e.shared.retries=O=0,V=null;return}for(;S.length&&(f=S.shift())&&(f.active=!0,f.cancelled);)Wt(e).cancel(f.state,f.cancelled.resolve,f.cancelled.reject);f||(Y.reserved?!Y.reserved.release&&t[5]===73?D?De():(Y.reserved=null,n(Y)):Y.reserved():D?De():n(Y))}function ir(t){G=0;for(let s=t.length-1;s>0;s--)if(t[s]===32&&t[s+1]<58&&A.count===null&&(A.count=+t.toString("utf8",s+1,t.length-1)),t[s-1]>=65){A.command=t.toString("utf8",5,s),A.state=le;break}if(Ue&&(Ue(),Ue=null),A.command==="BEGIN"&&c!==1&&!Y.reserved)return ae(z.generic("UNSAFE_TRANSACTION","Only use sql.begin, sql.reserved or max: 1"));if(f.options.simple)return Ct();f.cursorFn&&(A.count&&f.cursorFn(A),K(be))}function cr(){f.parsing=!1}function Ct(){!A.statement&&(A.statement=f.statement),A.columns=f.statement.columns}function lr(t){let s=t.readUInt16BE(5);for(let h=0;h<s;++h)!f.statement.types[h]&&(f.statement.types[h]=t.readUInt32BE(7+h*4));f.prepare&&(l[f.signature]=f.statement),f.describeFirst&&!f.onlyDescribe&&(K(Qe(f)),f.describeFirst=!1)}function ur(t){A.command&&(ge=ge||[A],ge.push(A=new we),A.count=null,f.statement.columns=null);let s=t.readUInt16BE(5),h=7,_;f.statement.columns=Array(s);for(let M=0;M<s;++M){for(_=h;t[h++]!==0;);let W=t.readUInt32BE(h),q=t.readUInt16BE(h+4),ye=t.readUInt32BE(h+6);f.statement.columns[M]={name:E.column.from?E.column.from(t.toString("utf8",_,h-1)):t.toString("utf8",_,h-1),parser:b[ye],table:W,number:q,type:ye},h+=18}if(A.statement=f.statement,f.onlyDescribe)return f.resolve(f.statement),K(be)}async function fr(t,s=t.readUInt32BE(5)){(s===3?mr:s===5?dr:s===10?pr:s===11?hr:s===12?gr:s!==0?Lr:Ne)(t,s)}async function mr(){let t=await nt();K(p().p().str(t).z(1).end())}async function dr(t){let s="md5"+await Yt(Buffer.concat([Buffer.from(await Yt(await nt()+d)),t.subarray(9)]));K(p().p().str(s).z(1).end())}async function pr(){et=(await $e.randomBytes(18)).toString("base64"),p().p().str("SCRAM-SHA-256"+p.N);let t=p.i;K(p.inc(4).str("n,,n=*,r="+et).i32(p.i-t-4,t).end())}async function hr(t){let s=t.toString("utf8",9).split(",").reduce((q,ye)=>(q[ye[0]]=ye.slice(2),q),{}),h=await $e.pbkdf2Sync(await nt(),Buffer.from(s.s,"base64"),parseInt(s.i),32,"sha256"),_=await Ze(h,"Client Key"),M="n=*,r="+et+",r="+s.r+",s="+s.s+",i="+s.i+",c=biws,r="+s.r;Z=(await Ze(await Ze(h,"Server Key"),M)).toString("base64");let W="c=biws,r="+s.r+",p="+ln(_,Buffer.from(await Ze(await cn(_),M))).toString("base64");K(p().p().str(W).end())}function gr(t){t.toString("utf8",9).split(p.N,1)[0].slice(2)!==Z&&(ae(z.generic("SASL_SIGNATURE_MISMATCH","The server did not return the correct signature")),m.destroy())}function nt(){return Promise.resolve(typeof e.pass=="function"?e.pass():e.pass)}function yr(){if(A.statement=f.statement,A.statement.columns=[],f.onlyDescribe)return f.resolve(f.statement),K(be)}function wr(t){le.pid=t.readUInt32BE(5),le.secret=t.readUInt32BE(9)}async function br(){Pe=!1,(await new re([`
|
|
4
|
+
select b.oid, b.typarray
|
|
5
|
+
from pg_catalog.pg_type a
|
|
6
|
+
left join pg_catalog.pg_type b on b.oid = a.typelem
|
|
7
|
+
where a.typcategory = 'A'
|
|
8
|
+
group by b.oid, b.typarray
|
|
9
|
+
order by b.oid
|
|
10
|
+
`],[],je)).forEach(({oid:s,typarray:h})=>Er(s,h))}function Er(t,s){if(e.parsers[s]&&e.serializers[s])return;let h=e.parsers[t];e.shared.typeArrayMap[t]=s,e.parsers[s]=_=>Gt(_,h,s),e.parsers[s].array=!0,e.serializers[s]=_=>$t(_,e.serializers[t],e,s)}function _r(t,s){return t==="read-write"&&s.default_transaction_read_only==="on"||t==="read-only"&&s.default_transaction_read_only==="off"||t==="primary"&&s.in_hot_standby==="on"||t==="standby"&&s.in_hot_standby==="off"||t==="prefer-standby"&&s.in_hot_standby==="off"&&e.host[O]}function Sr(){let t=new re([`
|
|
11
|
+
show transaction_read_only;
|
|
12
|
+
select pg_catalog.pg_is_in_recovery()
|
|
13
|
+
`],[],je,null,{simple:!0});t.resolve=([[s],[h]])=>{fe.default_transaction_read_only=s.transaction_read_only,fe.in_hot_standby=h.pg_is_in_recovery?"on":"off"},t.execute()}function vr(t){f?((f.cursorFn||f.describeFirst)&&K(be),x=z.postgres(Je(t))):ae(z.postgres(Je(t)))}function Ar(t,s){delete l[t.signature],t.retried=s,je(t)}function Or(t){if(!g)return;let s=9;for(;t[s++]!==0;);g(t.toString("utf8",9,s-1),t.toString("utf8",s,t.length-1))}async function Pr(){try{let t=await Promise.resolve(f.cursorFn(A));G=0,t===Te?K($r(f.portal)):(A=new we,K(It("",f.cursorRows)))}catch(t){K(be),f.reject(t)}}function Br(){A.count&&f.cursorFn(A),f.resolve(A)}function Cr(){I=new gt.Writable({autoDestroy:!0,write(t,s,h){m.write(p().d().raw(t).end(),h)},destroy(t,s){s(t),m.write(p().f().str(t+p.N).end()),I=null},final(t){m.write(p().c().end()),Ue=t,I=null}}),f.resolve(I)}function Tr(){I=new gt.Readable({read(){m.resume()}}),f.resolve(I)}function Ir(){I=new gt.Duplex({autoDestroy:!0,read(){m.resume()},write(t,s,h){m.write(p().d().raw(t).end(),h)},destroy(t,s){s(t),m.write(p().f().str(t+p.N).end()),I=null},final(t){m.write(p().c().end()),Ue=t}}),f.resolve(I)}function Nr(t){I&&(I.push(t.subarray(5))||m.pause())}function Ur(){I&&I.push(null),I=null}function jr(t){R?R(Je(t)):console.log(Je(t))}function Rr(){}function Dr(){ae(z.notSupported("FunctionCallResponse"))}function kr(){ae(z.notSupported("NegotiateProtocolVersion"))}function Fr(t){console.error("Postgres.js : Unknown Message:",t[0])}function Lr(t,s){console.error("Postgres.js : Unknown Auth:",s)}function Mr(t,s,h="",_=""){let M,W;return p().B().str(_+p.N).str(h+p.N).i16(0).i16(t.length),t.forEach((q,ye)=>{if(q===null)return p.i32(4294967295);W=s[ye],t[ye]=q=W in e.serializers?e.serializers[W](q):""+q,M=p.i,p.inc(4).str(q).i32(p.i-M-4,M)}),p.i16(0),p.end()}function Tt(t,s,h,_=""){return p().P().str(_+p.N).str(t+p.N).i16(s.length),s.forEach((M,W)=>p.i32(h[W]||0)),p.end()}function zr(t,s=""){return p().D().str(t).str(s+p.N).end()}function It(t="",s=0){return Buffer.concat([p().E().str(t+p.N).i32(s).end(),Vt])}function $r(t=""){return Buffer.concat([p().C().str("P").str(t+p.N).end(),p().S().end()])}function Gr(){return ue||p().inc(4).i16(3).z(2).str(Object.entries(Object.assign({user:d,database:P,client_encoding:"UTF8"},e.connection)).filter(([,t])=>t).map(([t,s])=>t+p.N+s).join(p.N)).z(2).end(0)}}function Je(e){let r={},n=5;for(let a=5;a<e.length-1;a++)e[a]===0&&(r[on[e[n]]]=e.toString("utf8",n+1,a),n=a+1);return r}function Yt(e){return $e.createHash("md5").update(e).digest("hex")}function Ze(e,r){return $e.createHmac("sha256",e).update(r).digest()}function cn(e){return $e.createHash("sha256").update(e).digest()}function ln(e,r){let n=Math.max(e.length,r.length),a=Buffer.allocUnsafe(n);for(let i=0;i<n;i++)a[i]=e[i]^r[i];return a}function yt(e,r){if(r=typeof r=="function"?r():r,!r)return{cancel:Ne,start:Ne};let n;return{cancel(){n&&(clearTimeout(n),n=null)},start(){n&&clearTimeout(n),n=setTimeout(a,r*1e3,arguments)}};function a(i){e.apply(null,i),n=null}}Q();var Xt=()=>{};function bt(e,r){let n=new Map,a="postgresjs_"+Math.random().toString(36).slice(2),i={},u,o,c=!1,d=P.sql=e({...r,transform:{column:{},value:{},row:{}},max:1,fetch_types:!1,idle_timeout:null,max_lifetime:null,connection:{...r.connection,replication:"database"},onclose:async function(){c||(o=null,i.pid=i.secret=void 0,b(await E(d,a,r.publications)),n.forEach(g=>g.forEach(({onsubscribe:H})=>H())))},no_subscribe:!0}),j=d.end,C=d.close;return d.end=async()=>(c=!0,o&&await new Promise(g=>(o.once("close",g),o.end())),j()),d.close=async()=>(o&&await new Promise(g=>(o.once("close",g),o.end())),C()),P;async function P(g,H,N=Xt,oe=Xt){g=mn(g),u||(u=E(d,a,r.publications));let se={fn:H,onsubscribe:N},ee=n.has(g)?n.get(g).add(se):n.set(g,new Set([se])).get(g),S=()=>{ee.delete(se),ee.size===0&&n.delete(g)};return u.then(he=>(b(he),N(),o&&o.on("error",oe),{unsubscribe:S,state:i,sql:d}))}function b(g){o=g.stream,i.pid=g.state.pid,i.secret=g.state.secret}async function E(g,H,N){if(!N)throw new Error("Missing publication names");let oe=await g.unsafe(`CREATE_REPLICATION_SLOT ${H} TEMPORARY LOGICAL pgoutput NOEXPORT_SNAPSHOT`),[se]=oe,ee=await g.unsafe(`START_REPLICATION SLOT ${H} LOGICAL ${se.consistent_point} (proto_version '1', publication_names '${N}')`).writable(),S={lsn:Buffer.concat(se.consistent_point.split("/").map(v=>Buffer.from(("00000000"+v).slice(-8),"hex")))};return ee.on("data",le),ee.on("error",he),ee.on("close",g.close),{stream:ee,state:oe.state};function he(v){console.error("Unexpected error during logical streaming - reconnecting",v)}function le(v){v[0]===119?fn(v.subarray(25),S,g.options.parsers,Oe,r.transform):v[0]===107&&v[17]&&(S.lsn=v.subarray(1,9),Ee())}function Oe(v,m){let ue=m.relation.schema+"."+m.relation.table;R("*",v,m),R("*:"+ue,v,m),m.relation.keys.length&&R("*:"+ue+"="+m.relation.keys.map(x=>v[x.name]),v,m),R(m.command,v,m),R(m.command+":"+ue,v,m),m.relation.keys.length&&R(m.command+":"+ue+"="+m.relation.keys.map(x=>v[x.name]),v,m)}function Ee(){let v=Buffer.alloc(34);v[0]=114,v.fill(S.lsn,1),v.writeBigInt64BE(BigInt(Date.now()-Date.UTC(2e3,0,1))*BigInt(1e3),25),ee.write(v)}}function R(g,H,N){n.has(g)&&n.get(g).forEach(({fn:oe})=>oe(H,N,g))}}function un(e){return new Date(Date.UTC(2e3,0,1)+Number(e/BigInt(1e3)))}function fn(e,r,n,a,i){let u=(o,[c,d])=>(o[c.charCodeAt(0)]=d,o);Object.entries({R:o=>{let c=1,d=r[o.readUInt32BE(c)]={schema:o.toString("utf8",c+=4,c=o.indexOf(0,c))||"pg_catalog",table:o.toString("utf8",c+1,c=o.indexOf(0,c+1)),columns:Array(o.readUInt16BE(c+=2)),keys:[]};c+=2;let j=0,C;for(;c<o.length;)C=d.columns[j++]={key:o[c++],name:i.column.from?i.column.from(o.toString("utf8",c,c=o.indexOf(0,c))):o.toString("utf8",c,c=o.indexOf(0,c)),type:o.readUInt32BE(c+=1),parser:n[o.readUInt32BE(c)],atttypmod:o.readUInt32BE(c+=4)},C.key&&d.keys.push(C),c+=4},Y:()=>{},O:()=>{},B:o=>{r.date=un(o.readBigInt64BE(9)),r.lsn=o.subarray(1,9)},I:o=>{let c=1,d=r[o.readUInt32BE(c)],{row:j}=qe(o,d.columns,c+=7,i);a(j,{command:"insert",relation:d})},D:o=>{let c=1,d=r[o.readUInt32BE(c)];c+=4;let j=o[c]===75;a(j||o[c]===79?qe(o,d.columns,c+=3,i).row:null,{command:"delete",relation:d,key:j})},U:o=>{let c=1,d=r[o.readUInt32BE(c)];c+=4;let j=o[c]===75,C=j||o[c]===79?qe(o,d.columns,c+=3,i):null;C&&(c=C.i);let{row:P}=qe(o,d.columns,c+3,i);a(P,{command:"update",relation:d,key:j,old:C&&C.row})},T:()=>{},C:()=>{}}).reduce(u,{})[e[0]](e)}function qe(e,r,n,a){let i,u,o,c=a.raw?new Array(r.length):{};for(let d=0;d<r.length;d++)i=e[n++],u=r[d],o=i===110?null:i===117?void 0:u.parser===void 0?e.toString("utf8",n+4,n+=4+e.readUInt32BE(n)):u.parser.array===!0?u.parser(e.toString("utf8",n+5,n+=4+e.readUInt32BE(n))):u.parser(e.toString("utf8",n+4,n+=4+e.readUInt32BE(n))),a.raw?c[d]=a.raw===!0?o:a.value.from?a.value.from(o,u):o:c[u.name]=a.value.from?a.value.from(o,u):o;return{i:n,row:a.row.from?a.row.from(c):c}}function mn(e){let r=e.match(/^(\*|insert|update|delete)?:?([^.]+?\.?[^=]+)?=?(.+)?/i)||[];if(!r)throw new Error("Malformed subscribe pattern: "+e);let[,n,a,i]=r;return(n||"*")+(a?":"+(a.indexOf(".")===-1?"public."+a:a):"")+(i?"="+i:"")}Q();import Jt from"stream";function Et(e,r,n=393216){return new Promise(async(a,i)=>{await e.begin(async u=>{let o;!r&&([{oid:r}]=await u`select lo_creat(-1) as oid`);let[{fd:c}]=await u`select lo_open(${r}, ${n}) as fd`,d={writable:C,readable:j,close:()=>u`select lo_close(${c})`.then(o),tell:()=>u`select lo_tell64(${c})`,read:P=>u`select loread(${c}, ${P}) as data`,write:P=>u`select lowrite(${c}, ${P})`,truncate:P=>u`select lo_truncate64(${c}, ${P})`,seek:(P,b=0)=>u`select lo_lseek64(${c}, ${P}, ${b})`,size:()=>u`
|
|
14
|
+
select
|
|
15
|
+
lo_lseek64(${c}, location, 0) as position,
|
|
16
|
+
seek.size
|
|
17
|
+
from (
|
|
18
|
+
select
|
|
19
|
+
lo_lseek64($1, 0, 2) as size,
|
|
20
|
+
tell.location
|
|
21
|
+
from (select lo_tell64($1) as location) tell
|
|
22
|
+
) seek
|
|
23
|
+
`};return a(d),new Promise(async P=>o=P);async function j({highWaterMark:P=2048*8,start:b=0,end:E=1/0}={}){let R=E-b;return b&&await d.seek(b),new Jt.Readable({highWaterMark:P,async read(g){let H=g>R?g-R:g;R-=g;let[{data:N}]=await d.read(H);this.push(N),N.length<g&&this.push(null)}})}async function C({highWaterMark:P=2048*8,start:b=0}={}){return b&&await d.seek(b),new Jt.Writable({highWaterMark:P,write(E,R,g){d.write(E).then(()=>g(),g)}})}}).catch(i)})}Object.assign(xe,{PostgresError:_e,toPascal:ve,pascal:pt,toCamel:Se,camel:dt,toKebab:Ae,kebab:ht,fromPascal:Me,fromCamel:Le,fromKebab:ze,BigInt:{to:20,from:[20],parse:e=>BigInt(e),serialize:e=>e.toString()}});var ls=xe;function xe(e,r){let n=hn(e,r),a=n.no_subscribe||bt(xe,{...n}),i=!1,u=ne(),o=ne(),c=ne(),d=ne(),j=ne(),C=ne(),P=ne(),b=ne(),E={connecting:o,reserved:c,closed:d,ended:j,open:C,busy:P,full:b},R=[...Array(n.max)].map(()=>wt(n,E,{onopen:Pe,onend:J,onclose:fe})),g=H(Oe);return Object.assign(g,{get parameters(){return n.parameters},largeObject:Et.bind(null,g),subscribe:a,CLOSE:Te,END:Te,PostgresError:_e,options:n,reserve:se,listen:N,begin:ee,close:ue,end:m}),g;function H(l){return l.debug=n.debug,Object.entries(n.types).reduce((w,[O,k])=>(w[O]=F=>new ie(F,k.to),w),y),Object.assign(U,{types:y,typed:y,unsafe:$,notify:oe,array:le,json:he,file:L}),U;function y(w,O){return new ie(w,O)}function U(w,...O){return w&&Array.isArray(w.raw)?new re(w,O,l,v):typeof w=="string"&&!O.length?new Ie(n.transform.column.to?n.transform.column.to(w):w):new Fe(w,O)}function $(w,O=[],k={}){return arguments.length===2&&!Array.isArray(O)&&(k=O,O=[]),new re([w],O,l,v,{prepare:!1,...k,simple:"simple"in k?k.simple:O.length===0})}function L(w,O=[],k={}){return arguments.length===2&&!Array.isArray(O)&&(k=O,O=[]),new re([],O,G=>{pn.readFile(w,"utf8",(Z,T)=>{if(Z)return G.reject(Z);G.strings=[T],l(G)})},v,{...k,simple:"simple"in k?k.simple:O.length===0})}}async function N(l,y,U){let $={fn:y,onlisten:U},L=N.sql||(N.sql=xe({...n,max:1,idle_timeout:null,max_lifetime:null,fetch_types:!1,onclose(){Object.entries(N.channels).forEach(([G,{listeners:Z}])=>{delete N.channels[G],Promise.all(Z.map(T=>N(G,T.fn,T.onlisten).catch(()=>{})))})},onnotify(G,Z){G in N.channels&&N.channels[G].listeners.forEach(T=>T.fn(Z))}})),w=N.channels||(N.channels={});if(l in w){w[l].listeners.push($);let G=await w[l].result;return $.onlisten&&$.onlisten(),{state:G.state,unlisten:F}}w[l]={result:L`listen ${L.unsafe('"'+l.replace(/"/g,'""')+'"')}`,listeners:[$]};let k=await w[l].result;return $.onlisten&&$.onlisten(),{state:k.state,unlisten:F};async function F(){if(l in w&&(w[l].listeners=w[l].listeners.filter(G=>G!==$),!w[l].listeners.length))return delete w[l],L`unlisten ${L.unsafe('"'+l.replace(/"/g,'""')+'"')}`}}async function oe(l,y){return await g`select pg_notify(${l}, ${""+y})`}async function se(){let l=ne(),y=C.length?C.shift():await new Promise((L,w)=>{let O={reserve:L,reject:w};u.push(O),d.length&&A(d.shift(),O)});S(y,c),y.reserved=()=>l.length?y.execute(l.shift()):S(y,c),y.reserved.release=!0;let U=H($);return U.release=()=>{y.reserved=null,Pe(y)},U;function $(L){y.queue===b?l.push(L):y.execute(L)||S(y,b)}}async function ee(l,y){!y&&(y=l,l="");let U=ne(),$=0,L,w=null;try{return await g.unsafe("begin "+l.replace(/[^a-z ]/ig,""),[],{onexecute:k}).execute(),await Promise.race([O(L,y),new Promise((F,G)=>L.onclose=G)])}catch(F){throw F}async function O(F,G,Z){let T=H(V);T.savepoint=ge,T.prepare=D=>w=D.replace(/[^a-z0-9$-_. ]/gi);let me,ce;Z&&await T`savepoint ${T(Z)}`;try{if(ce=await new Promise((D,I)=>{let te=G(T);Promise.resolve(Array.isArray(te)?Promise.all(te):te).then(D,I)}),me)throw me}catch(D){throw await(Z?T`rollback to ${T(Z)}`:T`rollback`),D instanceof _e&&D.code==="25P02"&&me||D}return Z||(w?await T`prepare transaction '${T.unsafe(w)}'`:await T`commit`),ce;function ge(D,I){return D&&Array.isArray(D.raw)?ge(te=>te.apply(te,arguments)):(arguments.length===1&&(I=D,D=null),O(F,I,"s"+$+++(D?"_"+D:"")))}function V(D){D.catch(I=>me||(me=I)),F.queue===b?U.push(D):F.execute(D)||S(F,b)}}function k(F){L=F,S(F,c),F.reserved=()=>U.length?F.execute(U.shift()):S(F,c)}}function S(l,y){return l.queue.remove(l),y.push(l),l.queue=y,y===C?l.idleTimer.start():l.idleTimer.cancel(),l}function he(l){return new ie(l,3802)}function le(l,y){return Array.isArray(l)?new ie(l,y||(l.length?Ve(l)||25:0),n.shared.typeArrayMap):le(Array.from(arguments))}function Oe(l){if(i)return l.reject(z.connection("CONNECTION_ENDED",n,n));if(C.length)return Ee(C.shift(),l);if(d.length)return A(d.shift(),l);P.length?Ee(P.shift(),l):u.push(l)}function Ee(l,y){return l.execute(y)?S(l,P):S(l,b)}function v(l){return new Promise((y,U)=>{l.state?l.active?wt(n).cancel(l.state,y,U):l.cancelled={resolve:y,reject:U}:(u.remove(l),l.cancelled=!0,l.reject(z.generic("57014","canceling statement due to user request")),y())})}async function m({timeout:l=null}={}){if(i)return i;await 1;let y;return i=Promise.race([new Promise(U=>l!==null&&(y=setTimeout(x,l*1e3,U))),Promise.all(R.map(U=>U.end()).concat(N.sql?N.sql.end({timeout:0}):[],a.sql?a.sql.end({timeout:0}):[]))]).then(()=>clearTimeout(y))}async function ue(){await Promise.all(R.map(l=>l.end()))}async function x(l){for(await Promise.all(R.map(y=>y.terminate()));u.length;)u.shift().reject(z.connection("CONNECTION_DESTROYED",n));l()}function A(l,y){return S(l,o),l.connect(y),l}function J(l){S(l,j)}function Pe(l){if(u.length===0)return S(l,C);let y=Math.ceil(u.length/(o.length+1)),U=!0;for(;U&&u.length&&y-- >0;){let $=u.shift();if($.reserve)return $.reserve(l);U=l.execute($)}U?S(l,P):S(l,b)}function fe(l,y){S(l,d),l.reserved=null,l.onclose&&(l.onclose(y),l.onclose=null),n.onclose&&n.onclose(l.id),u.length&&A(l,u.shift())}}function hn(e,r){if(e&&e.shared)return e;let n=process.env,a=(!e||typeof e=="string"?r:e)||{},{url:i,multihost:u}=En(e),o=[...i.searchParams].reduce((b,[E,R])=>(b[E]=R,b),{}),c=a.hostname||a.host||u||i.hostname||n.PGHOST||"localhost",d=a.port||i.port||n.PGPORT||5432,j=a.user||a.username||i.username||n.PGUSERNAME||n.PGUSER||_n();a.no_prepare&&(a.prepare=!1),o.sslmode&&(o.ssl=o.sslmode,delete o.sslmode),"timeout"in a&&(console.log("The timeout option is deprecated, use idle_timeout instead"),a.idle_timeout=a.timeout),o.sslrootcert==="system"&&(o.ssl="verify-full");let C=["idle_timeout","connect_timeout","max_lifetime","max_pipeline","backoff","keep_alive"],P={max:globalThis.Cloudflare?3:10,ssl:!1,sslnegotiation:null,idle_timeout:null,connect_timeout:30,max_lifetime:wn,max_pipeline:100,backoff:yn,keep_alive:60,prepare:!0,debug:!1,fetch_types:!0,publications:"alltables",target_session_attrs:null};return{host:Array.isArray(c)?c:c.split(",").map(b=>b.split(":")[0]),port:Array.isArray(d)?d:c.split(",").map(b=>parseInt(b.split(":")[1]||d)),path:a.path||c.indexOf("/")>-1&&c+"/.s.PGSQL."+d,database:a.database||a.db||(i.pathname||"").slice(1)||n.PGDATABASE||j,user:j,pass:a.pass||a.password||i.password||n.PGPASSWORD||"",...Object.entries(P).reduce((b,[E,R])=>{let g=E in a?a[E]:E in o?o[E]==="disable"||o[E]==="false"?!1:o[E]:n["PG"+E.toUpperCase()]||R;return b[E]=typeof g=="string"&&C.includes(E)?+g:g,b},{}),connection:{application_name:n.PGAPPNAME||"postgres.js",...a.connection,...Object.entries(o).reduce((b,[E,R])=>(E in P||(b[E]=R),b),{})},types:a.types||{},target_session_attrs:gn(a,i,n),onnotice:a.onnotice,onnotify:a.onnotify,onclose:a.onclose,onparameter:a.onparameter,socket:a.socket,transform:bn(a.transform||{undefined:void 0}),parameters:{},shared:{retries:0,typeArrayMap:{}},...Mt(a.types)}}function gn(e,r,n){let a=e.target_session_attrs||r.searchParams.get("target_session_attrs")||n.PGTARGETSESSIONATTRS;if(!a||["read-write","read-only","primary","standby","prefer-standby"].includes(a))return a;throw new Error("target_session_attrs "+a+" is not supported")}function yn(e){return(.5+Math.random()/2)*Math.min(3**e/100,20)}function wn(){return 60*(30+Math.random()*30)}function bn(e){return{undefined:e.undefined,column:{from:typeof e.column=="function"?e.column:e.column&&e.column.from,to:e.column&&e.column.to},value:{from:typeof e.value=="function"?e.value:e.value&&e.value.from,to:e.value&&e.value.to},row:{from:typeof e.row=="function"?e.row:e.row&&e.row.from,to:e.row&&e.row.to}}}function En(e){if(!e||typeof e!="string")return{url:{searchParams:new Map}};let r=e;r=r.slice(r.indexOf("://")+3).split(/[?/]/)[0],r=decodeURIComponent(r.slice(r.indexOf("@")+1));let n=new URL(e.replace(r,r.split(",")[0]));return{url:{username:decodeURIComponent(n.username),password:decodeURIComponent(n.password),host:n.host,hostname:n.hostname,port:n.port,pathname:n.pathname,searchParams:n.searchParams},multihost:r.indexOf(",")>-1&&r}}function _n(){try{return dn.userInfo().username}catch{return process.env.USERNAME||process.env.USER||process.env.LOGNAME}}export{ls as default};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { createRequire } from 'module'; const require = createRequire(import.meta.url);
|
|
2
|
+
import{b as d,c as e,d as f,e as g,f as h,g as i,h as j,i as k,j as l,k as m,l as n,m as o,n as p,o as q}from"./chunk-Y7RZHZ53.mjs";import{a,b,c}from"./chunk-V3XZ4XYN.mjs";import"./chunk-VULBPPPP.mjs";export{c as SysInfo,g as Utils,a as detectRuntime,k as existsSync,i as getAllEnv,l as getCwd,m as getDirname,h as getEnv,o as getMode,n as getPlatform,f as getRequire,b as getSysInfo,p as getTempDir,d as includeExcludeCron,e as nextCid,j as readTextFileSync,q as sleep};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a,b,c,d,e,f,g,h,i,j}from"./chunk-EQSCULS7.js";import"./chunk-QPTGW2LL.js";import"./chunk-DGDAVQYC.js";import"./chunk-PVAE643M.js";export{g as DEFAULT_REQUEST_OPTIONS,d as MAX_BACKOFF_LIMIT_MS,a as MAX_RETRY_LIMIT,c as MAX_TIMEOUT_MS,b as MIN_TIMEOUT_MS,j as RequestUnlimited,e as clampNumber,h as endPoint,i as endPoints,f as fullJitterDelay};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as r}from"./chunk-O3XYZ4KS.js";import"./chunk-DGDAVQYC.js";import"./chunk-PVAE643M.js";import{Writable as i}from"stream";import s from"pino";import a from"pino-pretty";var c=process.env.LOG_PRETTY==="true"||process.env.NODE_ENV!=="production"&&process.env.LOG_PRETTY!=="false",e=process.env.LOG_LEVEL||"info",p=new i({write(t,m,n){let o=globalThis.__wsLogWrite;o&&o(typeof t=="string"?t:t.toString("utf8")),n()}}),g=s.multistream([{level:e,stream:c?a({colorize:!0,translateTime:"SYS:standard",ignore:"pid,hostname"}):process.stdout},{level:e,stream:p}]),d=s({level:e,redact:["password","secret","token","authorization","apiKey"]},g),f=new r(d),w=f;export{w as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var t;function f(){try{if(typeof process<"u"&&process.env&&process.env.RUNTIME){let e=process.env.RUNTIME.toLowerCase();if(["node","bun","deno","cloudflare","aws-lambda","gcp-cloudrun"].includes(e))return e}}catch{}try{if(typeof globalThis<"u"&&(globalThis.cloudflare||globalThis.caches||globalThis.WebSocketPair||globalThis.__CFW__)||typeof process<"u"&&process.env&&process.env.PLATFORM==="cloudflare")return"cloudflare"}catch{}try{if(typeof process<"u"&&process.env&&process.env.AWS_LAMBDA_FUNCTION_NAME)return"aws-lambda"}catch{}try{if(typeof process<"u"&&process.env&&(process.env.K_SERVICE||process.env.K_REVISION||process.env.GOOGLE_CLOUD_PROJECT))return"gcp-cloudrun"}catch{}return typeof Bun<"u"?"bun":typeof Deno<"u"&&Deno.version&&Deno.version.deno?"deno":"node"}function s(){return t!==void 0||(t=f()),t}var c,o,m=()=>{if(!o){let e=s();if(c&&typeof import.meta<"u"&&import.meta.url)try{o=c(import.meta.url)}catch{}!o&&typeof globalThis.require=="function"&&(o=globalThis.require),o||(o=n=>{throw new Error(`require("${n}") is not available in this runtime (${e}).`)})}return o};function a(e){let n={},r=["KEY","SECRET","PASSWORD","TOKEN","AUTH","CREDENTIAL","APIKEY","PRIVATE","CERT","KEYSTORE"];for(let[u,i]of Object.entries(e)){if(i===void 0)continue;let d=u.toUpperCase(),l=r.some(p=>d.includes(p));n[u]=l?"[REDACTED]":i}return n}function y(e){let n=m()("node:os"),r=typeof process.memoryUsage=="function"?process.memoryUsage():{};return{runtime:e,os:process.platform,arch:process.arch,pid:process.pid,ppid:process.ppid??null,cwd:process.cwd(),uptime:process.uptime(),osVersion:n.release?.()??null,loadAvg:n.loadavg?.()??[0,0,0],memory:{rss:r.rss??null,heapTotal:r.heapTotal??null,heapUsed:r.heapUsed??null,external:r.external??null},env:a({...process.env})}}function R(){let e=typeof Deno<"u"?Deno:null,n=e&&typeof e.systemMemoryInfo=="function"?e.systemMemoryInfo():{};return{runtime:"deno",os:e?.build?.os??"unknown",arch:e?.build?.arch??"unknown",pid:e?.pid??null,ppid:e?.ppid??null,cwd:e?.cwd?.()??"",uptime:typeof performance<"u"?performance.now()/1e3:0,osVersion:e?.osRelease?.()??null,loadAvg:e?.loadavg?.()??[0,0,0],memory:{rss:n.total??null,heapTotal:null,heapUsed:null,external:null},env:a(e?.env?.toObject()??{})}}function g(){return{runtime:"unknown",os:"unknown",arch:"unknown",pid:null,ppid:null,cwd:"",uptime:0,osVersion:null,loadAvg:[0,0,0],memory:{rss:null,heapTotal:null,heapUsed:null,external:null},env:{}}}function _(){let e=s();switch(e){case"node":case"bun":return y(e);case"deno":return R();default:return g()}}var T={get:_};export{s as a,_ as b,T as c};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{a as h,c as O,d as S,g as A,h as b,i as C,j,k as L,l as z,m as P}from"./chunk-QPTGW2LL.js";import{a as T}from"./chunk-DGDAVQYC.js";var d={defaultMerge:Symbol("deepmerge-ts: default merge"),skip:Symbol("deepmerge-ts: skip")},Pe={defaultMerge:d.defaultMerge};function Q(t,e){return e}function G(t,e){return t.filter(r=>r!==void 0)}var D;(function(t){t[t.NOT=0]="NOT",t[t.RECORD=1]="RECORD",t[t.ARRAY=2]="ARRAY",t[t.SET=3]="SET",t[t.MAP=4]="MAP",t[t.OTHER=5]="OTHER"})(D||(D={}));function q(t){return typeof t!="object"||t===null?0:Array.isArray(t)?2:te(t)?1:t instanceof Set?3:t instanceof Map?4:5}function Z(t){let e=new Set;for(let r of t)for(let n of[...Object.keys(r),...Object.getOwnPropertySymbols(r)])e.add(n);return e}function ee(t,e){return typeof t=="object"&&Object.prototype.propertyIsEnumerable.call(t,e)}function N(t){let e=0,r=t[0]?.[Symbol.iterator]();return{[Symbol.iterator](){return{next(){do{if(r===void 0)return{done:!0,value:void 0};let n=r.next();if(n.done===!0){e+=1,r=t[e]?.[Symbol.iterator]();continue}return{done:!1,value:n.value}}while(!0)}}}}}var U=["[object Object]","[object Module]"];function te(t){if(!U.includes(Object.prototype.toString.call(t)))return!1;let{constructor:e}=t;if(e===void 0)return!0;let r=e.prototype;return!(r===null||typeof r!="object"||!U.includes(Object.prototype.toString.call(r))||!r.hasOwnProperty("isPrototypeOf"))}function re(t,e,r){let n={};for(let i of Z(t)){let o=[];for(let a of t)ee(a,i)&&o.push(a[i]);if(o.length===0)continue;let s=e.metaDataUpdater(r,{key:i,parents:t}),c=W(o,e,s);c!==d.skip&&(i==="__proto__"?Object.defineProperty(n,i,{value:c,configurable:!0,enumerable:!0,writable:!0}):n[i]=c)}return n}function ne(t){return t.flat()}function ie(t){return new Set(N(t))}function oe(t){return new Map(N(t))}function se(t){return t.at(-1)}var k={mergeRecords:re,mergeArrays:ne,mergeSets:ie,mergeMaps:oe,mergeOthers:se};function M(t,e){let r=ae(t,n);function n(...i){return W(i,r,e)}return n}function ae(t,e){return{defaultMergeFunctions:k,mergeFunctions:{...k,...Object.fromEntries(Object.entries(t).filter(([r,n])=>Object.hasOwn(k,r)).map(([r,n])=>n===!1?[r,k.mergeOthers]:[r,n]))},metaDataUpdater:t.metaDataUpdater??Q,deepmerge:e,useImplicitDefaultMerging:t.enableImplicitDefaultMerging??!1,filterValues:t.filterValues===!1?void 0:t.filterValues??G,actions:d}}function W(t,e,r){let n=e.filterValues?.(t,r)??t;if(n.length===0)return;if(n.length===1)return _(n,e,r);let i=q(n[0]);if(i!==0&&i!==5){for(let o=1;o<n.length;o++)if(q(n[o])!==i)return _(n,e,r)}switch(i){case 1:return ce(n,e,r);case 2:return ue(n,e,r);case 3:return fe(n,e,r);case 4:return le(n,e,r);default:return _(n,e,r)}}function ce(t,e,r){let n=e.mergeFunctions.mergeRecords(t,e,r);return n===d.defaultMerge||e.useImplicitDefaultMerging&&n===void 0&&e.mergeFunctions.mergeRecords!==e.defaultMergeFunctions.mergeRecords?e.defaultMergeFunctions.mergeRecords(t,e,r):n}function ue(t,e,r){let n=e.mergeFunctions.mergeArrays(t,e,r);return n===d.defaultMerge||e.useImplicitDefaultMerging&&n===void 0&&e.mergeFunctions.mergeArrays!==e.defaultMergeFunctions.mergeArrays?e.defaultMergeFunctions.mergeArrays(t):n}function fe(t,e,r){let n=e.mergeFunctions.mergeSets(t,e,r);return n===d.defaultMerge||e.useImplicitDefaultMerging&&n===void 0&&e.mergeFunctions.mergeSets!==e.defaultMergeFunctions.mergeSets?e.defaultMergeFunctions.mergeSets(t):n}function le(t,e,r){let n=e.mergeFunctions.mergeMaps(t,e,r);return n===d.defaultMerge||e.useImplicitDefaultMerging&&n===void 0&&e.mergeFunctions.mergeMaps!==e.defaultMergeFunctions.mergeMaps?e.defaultMergeFunctions.mergeMaps(t):n}function _(t,e,r){let n=e.mergeFunctions.mergeOthers(t,e,r);return n===d.defaultMerge||e.useImplicitDefaultMerging&&n===void 0&&e.mergeFunctions.mergeOthers!==e.defaultMergeFunctions.mergeOthers?e.defaultMergeFunctions.mergeOthers(t):n}import Re,{HTTPError as J}from"ky";import{serializeError as H}from"serialize-error";import{EventEmitter as de}from"events";import{serializeError as me}from"serialize-error";var I={markets:{chromeVersion:"146",nasdaq:{statusEndpoint:"https://api.nasdaq.com/api/market-info",monitor:{liveIntervalSec:10,closedIntervalSec:3600,warnIntervalSec:60},symbols:{nasdaqListedUrl:"https://www.nasdaqtrader.com/dynamic/symdir/nasdaqlisted.txt",otherListedUrl:"https://www.nasdaqtrader.com/dynamic/symdir/otherlisted.txt",initialBackoffMs:1e3,maxRetryBackoffMs:36e5,maxFetchRetries:10},quotes:{concurrencyLimit:5}}},retrieve:{timeout:5e4,retry:{limit:5,backoffLimit:3e3}}};async function V(t){let{getEnv:e}=await import("./utils-7K7MHQMD.js"),r=(await import("crypto")).default,n=e("CORELIB_AES_PASSWORD");if(!n)throw new Error("Decryption failed: CORELIB_AES_PASSWORD environment variable is not set.");let i=t.split(`
|
|
2
|
+
`).map(u=>u.trim()).filter(Boolean);if(i.length<2)throw new Error("Invalid .enc file format. Expected IV on line 1 and Ciphertext on line 2.");let o=Buffer.from(i[0],"base64"),s=Buffer.from(i[1],"base64"),c=Buffer.from(n,"hex"),a=r.createDecipheriv("aes-256-cbc",c,o),f=a.update(s);return f=Buffer.concat([f,a.final()]),JSON.parse(f.toString("utf8"))}var E=M({mergeArrays:!1}),pe=t=>!t.split(/[.-]/).some(e=>e==="__proto__"||e==="constructor"||e==="prototype");function y(t,e){for(let r of Object.keys(t))r in e||delete t[r];for(let r of Object.keys(e)){let n=e[r];n&&typeof n=="object"&&!Array.isArray(n)?((!t[r]||typeof t[r]!="object"||Array.isArray(t[r]))&&(t[r]={}),y(t[r],n)):t[r]=n}}function he(t,e,r,n){let i=t;for(;;){if(r(e.join(i,"pnpm-workspace.yaml")))return e.basename(i);let o=e.join(i,"package.json");if(r(o))try{if(JSON.parse(n(o)).workspaces)return e.basename(i)}catch{}let s=e.dirname(i);if(s===i)break;i=s}return e.basename(t)}var p=class t extends de{static instance;_config={};_defaultsPath;static _logger=h.child({section:"ConfigManager"});_initPromise=null;_isInitialized=!1;_mutationChain=Promise.resolve();_inFlightTempConfig=null;static _prematureWarnEmitted=!1;constructor(){super();let e=L(),r=e;try{let{join:n}=S()("node:path");r=n(e,"ConfigManager.json")}catch{r=`${e}/ConfigManager.json`}this._defaultsPath=r,y(this._config,I),globalThis.sysconfig=this._config}static getInstance(){return t.instance||(t.instance=new t),t.instance}get(e){!this._isInitialized&&!t._prematureWarnEmitted&&P()!=="production"&&(t._prematureWarnEmitted=!0,t._logger.warn(`ConfigManager.get("${e}") called before initialize() resolved; returning seeded default`));let r=e.split("."),n=this._config;for(let i of r){if(n===null||typeof n!="object"||!(i in n))return;n=n[i]}return n}static get(e){return t.getInstance().get(e)}initialize(e){return this._initPromise?this._initPromise:(this._initPromise=this._enqueue(()=>this.runInitSequence(e)).then(()=>{this._isInitialized=!0,this._initPromise=null},r=>{throw this._initPromise=null,r}),this._initPromise)}async runInitSequence(e){t._logger.trace("initialize: start");let r=e??(typeof process<"u"&&Array.isArray(process.argv)?process.argv.slice(2):[]),n,i={};for(let s=0;s<r.length;s++){let c=r[s];if(c==="-C"||c==="--config"){s+1<r.length&&!r[s+1].startsWith("-")&&(n=r[++s]);continue}if(c.startsWith("--config=")){n=c.slice(9);continue}if(!c.startsWith("--"))continue;let a=c.slice(2);if(a===""||a.startsWith("="))continue;let f,u=a.indexOf("=");u>-1?(f=a.slice(u+1),a=a.slice(0,u)):s+1<r.length&&!r[s+1].startsWith("-")?f=r[++s]:f=!0,i[a]=f}t._logger.trace("initialize: resolved",{hasConfigPath:n!=null,overrideCount:Object.keys(i).length});let o={};this._inFlightTempConfig=o;try{if(this.loadDefaults(o),n){let s=await this.fetchExternalConfig(n);this.processHierarchy(s,o)}this.applyEnvOverrides(o),this.applyCliOverrides(i,o),y(this._config,o),t._logger.trace("initialize: committed",{keys:Object.keys(this._config??{}).length}),this.emit("initialized",this._config)}finally{this._inFlightTempConfig=null}}_enqueue(e){let r=this._mutationChain.then(e,e);return this._mutationChain=r.then(()=>{},()=>{}),r}getConfig(){return this._config}get isInitialized(){return this._isInitialized}whenReady(){return this._isInitialized?Promise.resolve():this._initPromise??Promise.resolve()}loadExternalConfig(e){return this._enqueue(()=>this.loadExternalConfigInner(e))}async loadExternalConfigInner(e){try{let r=await this.fetchExternalConfig(e),n=structuredClone(this._config);this._inFlightTempConfig=n;try{this.processHierarchy(r,n),this.applyEnvOverrides(n),y(this._config,n),this.emit("configLoaded",this._config)}finally{this._inFlightTempConfig=null}}catch(r){throw this.logError(`Failed to load external config dynamically from ${e}`,r),r}}loadDefaults(e){let r={...I};if(C(this._defaultsPath))try{r=JSON.parse(b(this._defaultsPath))}catch(n){this.logError("Failed to load defaults",n)}y(e,r)}async fetchExternalConfig(e){t._logger.trace("external config",{source:e.startsWith("http")?"http":"file"});let r;if(e.startsWith("http")){let{endPoint:o}=await import("./RequestUnlimited-QCOTVU4G.js"),s=await o(e);if(s.status==="error")throw new Error("Failed to fetch external config");r=s.value.body}else r=b(e);let n=e.toLowerCase();if(n.endsWith(".enc")){t._logger.trace("decrypting .enc config");let o=this.validateConfigObject(await V(r),e);return t._logger.trace("decryption ok"),o}let i=await import("./dist-GZV6T6K3.js");return n.endsWith(".yaml")||n.endsWith(".yml")?this.validateConfigObject(i.parseYAML(r),e):n.endsWith(".toml")?this.validateConfigObject(i.parseTOML(r),e):n.endsWith(".json5")?this.validateConfigObject(i.parseJSON5(r),e):n.endsWith(".jsonc")?this.validateConfigObject(i.parseJSONC(r),e):n.endsWith(".ini")?this.validateConfigObject(i.parseINI(r),e):this.validateConfigObject(i.parseJSON(r),e)}validateConfigObject(e,r){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`Config from "${r}" must be a JSON object, got ${Array.isArray(e)?"array":typeof e}`);return e}processHierarchy(e,r){if(!e)return;let n=this.getAppName(),i=z(),o=P(),s=e.commonAll||{},c=Object.keys(e).find(u=>u.toLowerCase()===n.toLowerCase()),a=c?e[c]:null;if(a){a.common&&(s=E(s,a.common));let u=a[i];if(u){let m=u[o];m&&(s=E(s,m))}}let f=E(r,s);y(r,f)}applyEnvOverrides(e){let r="CORELIB_",n=A();Object.keys(n).forEach(i=>{if(i.startsWith(r)){let o=i.slice(r.length).toLowerCase().replace(/_/g,".");t._logger.trace("env override",{key:o});let s=this.parseValue(n[i]);this.setPath(e,o,s)}})}applyCliOverrides(e,r){Object.keys(e).forEach(n=>{if(n==="config")return;if(!pe(n)){t._logger.warn(`Dropped unsafe CLI override key "${n}" (prototype-pollution guard)`);return}let i=n.replace(/-/g,".");t._logger.trace("cli override",{key:i});let o=this.parseValue(e[n]);this.setPath(r,i,o)})}updateValue(e,r){this.setPath(this._config,e,r),this._inFlightTempConfig!==null&&this.setPath(this._inFlightTempConfig,e,r),this.emit("change",{path:e,value:r}),this.emit(`change:${e}`,r)}setPath(e,r,n){let i=r.split("."),o=e;for(;i.length>1;){let s=i.shift();(!(s in o)||typeof o[s]!="object"||o[s]===null)&&(o[s]={}),o=o[s]}o[i[0]]=n}parseValue(e){if(typeof e!="string")return e;if(e.startsWith("[")&&e.endsWith("]")||e.startsWith("{")&&e.endsWith("}"))try{return JSON.parse(e)}catch(r){return this.logError("Failed to parse complex JSON from CLI/Env flag",r),e}return e.toLowerCase()==="true"?!0:e.toLowerCase()==="false"?!1:!Number.isNaN(Number(e))&&e.trim()!==""?Number(e):e}getAppName(){try{let e=T();if(e==="node"||e==="bun"||typeof import.meta<"u"&&import.meta.url&&import.meta.url.startsWith("file:")){let r=S()("node:path");return he(j(),r,n=>C(n),n=>b(n))}return"edge-app"}catch(e){return this.logError("Failed to get app name from cwd. Falling back to default-app",e),"default-app"}}logError(e,r){let n=r?me(r):void 0;t._logger.error(e,{error:n})}toJsonString(){return JSON.stringify(this._config)}toBuffer(){return Buffer.from(this.toJsonString())}__resetForTests(){this._initPromise=null,this._isInitialized=!1,this._inFlightTempConfig=null,this._mutationChain=Promise.resolve(),t._prematureWarnEmitted=!1}};import{serializeError as ye}from"serialize-error";var we=h.child({section:"RequestResponseSerialize"});async function F(t){if(!t)return null;let e={};t.headers.forEach((i,o)=>{e[o.toLowerCase()]=i});let r,n=t.headers.get("content-type")||"";try{if(t.bodyUsed)r="[Body already consumed]";else{let i=await t.clone().text();if(n.includes("application/json"))try{r=JSON.parse(i)}catch{r=i}else r=i}}catch(i){we.warn("Failed to read response body",{status:t.status,url:t.url,bodyUsed:t.bodyUsed,error:ye(i)}),r="[Error reading body]"}return{ok:t.ok,status:t.status,statusText:t.statusText,headers:e,url:t.url,redirected:t.redirected,type:t.type,body:r}}var l=h.child({section:"RequestUnlimited"}),be=M({mergeArrays:!1}),ke=10,Me=1e3,ve=12e4,Oe=6e4;function x(t,e,r,n){return typeof t!="number"||!Number.isFinite(t)?n:Math.min(r,Math.max(e,t))}function $(t){try{let e=t instanceof URL?t:new URL(t instanceof Request?t.url:t);return`${e.origin}${e.pathname}`}catch{return"[unparseable url]"}}function Se(t,e){let r=Math.min(e,300*2**(t-1)),n=Math.round(Math.random()*r);return l.trace("retry delay computed",{attempt:t,base:r,cap:e,delayMs:n}),n}var R={timeout:5e4,throwHttpErrors:!0,retry:{limit:5,methods:["get","post","put","delete","patch"],backoffLimit:3e3,shouldRetry:({error:t,retryCount:e})=>{if(t instanceof J&&t.response){let r=t.response.status;if(r===429&&e<=5)return l.trace("retry decision",{status:r,willRetry:!0}),!0;if(r>=400&&r<500)return l.trace("retry decision: skip",{status:r,willRetry:!1}),!1;let n=r>=500;return l.trace(n?"retry decision":"retry decision: skip",{status:r,willRetry:n}),n}return l.trace("retry decision",{willRetry:!0}),!0}},method:"get",headers:{"content-type":"application/json",accept:"application/json"},hooks:{beforeRetry:[]}};function B(t){let e={};for(let r in t)Object.hasOwn(t,r)&&t[r]!==void 0&&(e[r.toLowerCase()]=t[r]);return e}async function K(t,e={}){let r=B(R.headers||{}),n=e.headers?B(e.headers):{},{headers:i,hooks:o,...s}=e,c=x(p.get("retrieve.timeout"),Me,ve,5e4),a=x(p.get("retrieve.retry.limit"),0,ke,5),f=x(p.get("retrieve.retry.backoffLimit"),0,Oe,3e3),u=O(),m=performance.now();l.trace("endPoint: request",{cid:u,url:$(t),timeout:c,retryLimit:a,backoffLimit:f});let Y=R.retry,X=be(R,{timeout:c,retry:{...Y,limit:a,backoffLimit:f,delay:g=>Se(g,f)}},s,{headers:{...r,...n},hooks:{beforeRetry:[...R.hooks?.beforeRetry||[],async({retryCount:g})=>{l.trace("endPoint: retry",{cid:u,retryCount:g,durationMs:performance.now()-m})},...o?.beforeRetry||[]]}});try{let g=await Re(t,X),w=await F(g);return l.trace("endPoint: ok",{cid:u,durationMs:performance.now()-m,url:$(t),status:g.status}),{status:"success",value:w}}catch(g){if(g instanceof J||g.response){let v=await F(g.response);return l.trace("endPoint: error",{cid:u,durationMs:performance.now()-m,status:v?.status,errorMsg:"HTTP error"}),l.warn("HTTP Error",{cid:u,status:v?.status,url:t.toString()}),{status:"error",reason:v}}let w=H(g);return l.trace("endPoint: error",{cid:u,durationMs:performance.now()-m,errorMsg:w?.message??"internal/network error"}),l.error("Internal/Network Error",{cid:u,error:w}),{status:"error",reason:w}}}async function Ce(t,e={}){let r=O(),n=performance.now();l.trace("endPoints: batch",{cid:r,count:t.length});let i=t.map(a=>K(a,e)),s=(await Promise.allSettled(i)).map(a=>a.status==="fulfilled"?a.value:{status:"error",reason:H(a.reason)}),c=s.filter(a=>a.status==="success").length;return l.trace("endPoints: done",{cid:r,durationMs:performance.now()-n,ok:c,failed:s.length-c}),s}var Qe={defaults:R,endPoint:K,endPoints:Ce};export{ke as a,Me as b,ve as c,Oe as d,x as e,Se as f,R as g,K as h,Ce as i,Qe as j,p as k};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{c as n}from"./chunk-DGDAVQYC.js";var s=5e3,r=class i{pinoInstance;state;context;telemetryCache=null;constructor(e,t={telemetryEnabled:!1},o={}){this.pinoInstance=e,this.state=t,this.context=o}getTelemetry(){if(!this.state.telemetryEnabled)return;let e=Date.now();return(!this.telemetryCache||e>=this.telemetryCache.expiresAt)&&(this.telemetryCache={value:n.get(),expiresAt:e+s}),this.telemetryCache.value}validate(e,t){if(typeof e!="string")throw new Error("Logger requires string message first, optional object second");if(t!==void 0&&(typeof t!="object"||t===null||Array.isArray(t)))throw new Error("Logger requires string message first, optional object second")}trace(e,t){this.validate(e,t),this.pinoInstance.trace({...this.context,...t,telemetry:this.getTelemetry()},e)}debug(e,t){this.validate(e,t),this.pinoInstance.debug({...this.context,...t,telemetry:this.getTelemetry()},e)}info(e,t){this.validate(e,t),this.pinoInstance.info({...this.context,...t,telemetry:this.getTelemetry()},e)}warn(e,t){this.validate(e,t),this.pinoInstance.warn({...this.context,...t,telemetry:this.getTelemetry()},e)}error(e,t){this.validate(e,t),this.pinoInstance.error({...this.context,...t,telemetry:this.getTelemetry()},e)}fatal(e,t){this.validate(e,t),this.pinoInstance.fatal({...this.context,...t,telemetry:this.getTelemetry()},e)}child(e){return new i(this.pinoInstance,this.state,{...this.context,...e})}setTelemetry(e){if(e!=="on"&&e!=="off")throw new Error("setTelemetry accepts only 'on' or 'off'");this.state.telemetryEnabled=e==="on"}get level(){return this.pinoInstance.level}set level(e){this.pinoInstance.level=e}get levelVal(){return this.pinoInstance.levelVal}bindings(){return{...this.context}}silent(){this.pinoInstance.level="silent"}flush(e){typeof this.pinoInstance.flush=="function"?this.pinoInstance.flush(e):e?.()}};export{r as a};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var h=Object.create;var e=Object.defineProperty;var i=Object.getOwnPropertyDescriptor;var j=Object.getOwnPropertyNames;var k=Object.getPrototypeOf,l=Object.prototype.hasOwnProperty;var m=(a,b)=>()=>(a&&(b=a(a=0)),b);var n=(a,b)=>()=>(b||a((b={exports:{}}).exports,b),b.exports),o=(a,b)=>{for(var c in b)e(a,c,{get:b[c],enumerable:!0})},g=(a,b,c,f)=>{if(b&&typeof b=="object"||typeof b=="function")for(let d of j(b))!l.call(a,d)&&d!==c&&e(a,d,{get:()=>b[d],enumerable:!(f=i(b,d))||f.enumerable});return a};var p=(a,b,c)=>(c=a!=null?h(k(a)):{},g(b||!a||!a.__esModule?e(c,"default",{value:a,enumerable:!0}):c,a)),q=a=>g(e({},"__esModule",{value:!0}),a);export{m as a,n as b,o as c,p as d,q as e};
|