@hasna/assistants 1.1.129 → 1.1.130
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +4 -4
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1012,7 +1012,7 @@ To prepare for this change:
|
|
|
1012
1012
|
- If you want libpq compatibility now, use 'uselibpqcompat=true&sslmode=${sslmode}'
|
|
1013
1013
|
|
|
1014
1014
|
See https://www.postgresql.org/docs/current/libpq-ssl.html for libpq SSL mode definitions.`)}module.exports=parse2,parse2.parse=parse2,parse2.toClientConfig=toClientConfig,parse2.parseIntoClientConfig=parseIntoClientConfig}),require_connection_parameters=__commonJS2((exports,module)=>{var dns=__require2("dns"),defaults2=require_defaults2(),parse2=require_pg_connection_string().parse,val=function(key,config,envVar){if(config[key])return config[key];if(envVar===void 0)envVar=process.env["PG"+key.toUpperCase()];else if(envVar===!1);else envVar=process.env[envVar];return envVar||defaults2[key]},readSSLConfigFromEnvironment=function(){switch(process.env.PGSSLMODE){case"disable":return!1;case"prefer":case"require":case"verify-ca":case"verify-full":return!0;case"no-verify":return{rejectUnauthorized:!1}}return defaults2.ssl},quoteParamValue=function(value){return"'"+(""+value).replace(/\\/g,"\\\\").replace(/'/g,"\\'")+"'"},add=function(params,config,paramName){let value=config[paramName];if(value!==void 0&&value!==null)params.push(paramName+"="+quoteParamValue(value))};class ConnectionParameters{constructor(config){if(config=typeof config==="string"?parse2(config):config||{},config.connectionString)config=Object.assign({},config,parse2(config.connectionString));if(this.user=val("user",config),this.database=val("database",config),this.database===void 0)this.database=this.user;if(this.port=parseInt(val("port",config),10),this.host=val("host",config),Object.defineProperty(this,"password",{configurable:!0,enumerable:!1,writable:!0,value:val("password",config)}),this.binary=val("binary",config),this.options=val("options",config),this.ssl=typeof config.ssl>"u"?readSSLConfigFromEnvironment():config.ssl,typeof this.ssl==="string"){if(this.ssl==="true")this.ssl=!0}if(this.ssl==="no-verify")this.ssl={rejectUnauthorized:!1};if(this.ssl&&this.ssl.key)Object.defineProperty(this.ssl,"key",{enumerable:!1});if(this.client_encoding=val("client_encoding",config),this.replication=val("replication",config),this.isDomainSocket=!(this.host||"").indexOf("/"),this.application_name=val("application_name",config,"PGAPPNAME"),this.fallback_application_name=val("fallback_application_name",config,!1),this.statement_timeout=val("statement_timeout",config,!1),this.lock_timeout=val("lock_timeout",config,!1),this.idle_in_transaction_session_timeout=val("idle_in_transaction_session_timeout",config,!1),this.query_timeout=val("query_timeout",config,!1),config.connectionTimeoutMillis===void 0)this.connect_timeout=process.env.PGCONNECT_TIMEOUT||0;else this.connect_timeout=Math.floor(config.connectionTimeoutMillis/1000);if(config.keepAlive===!1)this.keepalives=0;else if(config.keepAlive===!0)this.keepalives=1;if(typeof config.keepAliveInitialDelayMillis==="number")this.keepalives_idle=Math.floor(config.keepAliveInitialDelayMillis/1000)}getLibpqConnectionString(cb){let params=[];add(params,this,"user"),add(params,this,"password"),add(params,this,"port"),add(params,this,"application_name"),add(params,this,"fallback_application_name"),add(params,this,"connect_timeout"),add(params,this,"options");let ssl=typeof this.ssl==="object"?this.ssl:this.ssl?{sslmode:this.ssl}:{};if(add(params,ssl,"sslmode"),add(params,ssl,"sslca"),add(params,ssl,"sslkey"),add(params,ssl,"sslcert"),add(params,ssl,"sslrootcert"),this.database)params.push("dbname="+quoteParamValue(this.database));if(this.replication)params.push("replication="+quoteParamValue(this.replication));if(this.host)params.push("host="+quoteParamValue(this.host));if(this.isDomainSocket)return cb(null,params.join(" "));if(this.client_encoding)params.push("client_encoding="+quoteParamValue(this.client_encoding));dns.lookup(this.host,function(err,address){if(err)return cb(err,null);return params.push("hostaddr="+quoteParamValue(address)),cb(null,params.join(" "))})}}module.exports=ConnectionParameters}),require_result=__commonJS2((exports,module)=>{var types3=require_pg_types(),matchRegexp=/^([A-Za-z]+)(?: (\d+))?(?: (\d+))?/;class Result{constructor(rowMode,types22){if(this.command=null,this.rowCount=null,this.oid=null,this.rows=[],this.fields=[],this._parsers=void 0,this._types=types22,this.RowCtor=null,this.rowAsArray=rowMode==="array",this.rowAsArray)this.parseRow=this._parseRowAsArray;this._prebuiltEmptyResultObject=null}addCommandComplete(msg){let match;if(msg.text)match=matchRegexp.exec(msg.text);else match=matchRegexp.exec(msg.command);if(match){if(this.command=match[1],match[3])this.oid=parseInt(match[2],10),this.rowCount=parseInt(match[3],10);else if(match[2])this.rowCount=parseInt(match[2],10)}}_parseRowAsArray(rowData){let row=Array(rowData.length);for(let i=0,len=rowData.length;i<len;i++){let rawValue=rowData[i];if(rawValue!==null)row[i]=this._parsers[i](rawValue);else row[i]=null}return row}parseRow(rowData){let row={...this._prebuiltEmptyResultObject};for(let i=0,len=rowData.length;i<len;i++){let rawValue=rowData[i],field=this.fields[i].name;if(rawValue!==null){let v=this.fields[i].format==="binary"?Buffer.from(rawValue):rawValue;row[field]=this._parsers[i](v)}else row[field]=null}return row}addRow(row){this.rows.push(row)}addFields(fieldDescriptions){if(this.fields=fieldDescriptions,this.fields.length)this._parsers=Array(fieldDescriptions.length);let row={};for(let i=0;i<fieldDescriptions.length;i++){let desc=fieldDescriptions[i];if(row[desc.name]=null,this._types)this._parsers[i]=this._types.getTypeParser(desc.dataTypeID,desc.format||"text");else this._parsers[i]=types3.getTypeParser(desc.dataTypeID,desc.format||"text")}this._prebuiltEmptyResultObject={...row}}}module.exports=Result}),require_query=__commonJS2((exports,module)=>{var{EventEmitter}=__require2("events"),Result=require_result(),utils2=require_utils2();class Query extends EventEmitter{constructor(config,values2,callback){super();if(config=utils2.normalizeQueryConfig(config,values2,callback),this.text=config.text,this.values=config.values,this.rows=config.rows,this.types=config.types,this.name=config.name,this.queryMode=config.queryMode,this.binary=config.binary,this.portal=config.portal||"",this.callback=config.callback,this._rowMode=config.rowMode,process.domain&&config.callback)this.callback=process.domain.bind(config.callback);this._result=new Result(this._rowMode,this.types),this._results=this._result,this._canceledDueToError=!1}requiresPreparation(){if(this.queryMode==="extended")return!0;if(this.name)return!0;if(this.rows)return!0;if(!this.text)return!1;if(!this.values)return!1;return this.values.length>0}_checkForMultirow(){if(this._result.command){if(!Array.isArray(this._results))this._results=[this._result];this._result=new Result(this._rowMode,this._result._types),this._results.push(this._result)}}handleRowDescription(msg){this._checkForMultirow(),this._result.addFields(msg.fields),this._accumulateRows=this.callback||!this.listeners("row").length}handleDataRow(msg){let row;if(this._canceledDueToError)return;try{row=this._result.parseRow(msg.fields)}catch(err){this._canceledDueToError=err;return}if(this.emit("row",row,this._result),this._accumulateRows)this._result.addRow(row)}handleCommandComplete(msg,connection){if(this._checkForMultirow(),this._result.addCommandComplete(msg),this.rows)connection.sync()}handleEmptyQuery(connection){if(this.rows)connection.sync()}handleError(err,connection){if(this._canceledDueToError)err=this._canceledDueToError,this._canceledDueToError=!1;if(this.callback)return this.callback(err);this.emit("error",err)}handleReadyForQuery(con){if(this._canceledDueToError)return this.handleError(this._canceledDueToError,con);if(this.callback)try{this.callback(null,this._results)}catch(err){process.nextTick(()=>{throw err})}this.emit("end",this._results)}submit(connection){if(typeof this.text!=="string"&&typeof this.name!=="string")return Error("A query must have either text or a name. Supplying neither is unsupported.");let previous=connection.parsedStatements[this.name];if(this.text&&previous&&this.text!==previous)return Error(`Prepared statements must be unique - '${this.name}' was used for a different statement`);if(this.values&&!Array.isArray(this.values))return Error("Query values must be an array");if(this.requiresPreparation()){connection.stream.cork&&connection.stream.cork();try{this.prepare(connection)}finally{connection.stream.uncork&&connection.stream.uncork()}}else connection.query(this.text);return null}hasBeenParsed(connection){return this.name&&connection.parsedStatements[this.name]}handlePortalSuspended(connection){this._getRows(connection,this.rows)}_getRows(connection,rows){if(connection.execute({portal:this.portal,rows}),!rows)connection.sync();else connection.flush()}prepare(connection){if(!this.hasBeenParsed(connection))connection.parse({text:this.text,name:this.name,types:this.types});try{connection.bind({portal:this.portal,statement:this.name,values:this.values,binary:this.binary,valueMapper:utils2.prepareValue})}catch(err){this.handleError(err,connection);return}connection.describe({type:"P",name:this.portal||""}),this._getRows(connection,this.rows)}handleCopyInResponse(connection){connection.sendCopyFail("No source stream defined")}handleCopyData(msg,connection){}}module.exports=Query}),require_messages=__commonJS2((exports)=>{Object.defineProperty(exports,"__esModule",{value:!0}),exports.NoticeMessage=exports.DataRowMessage=exports.CommandCompleteMessage=exports.ReadyForQueryMessage=exports.NotificationResponseMessage=exports.BackendKeyDataMessage=exports.AuthenticationMD5Password=exports.ParameterStatusMessage=exports.ParameterDescriptionMessage=exports.RowDescriptionMessage=exports.Field=exports.CopyResponse=exports.CopyDataMessage=exports.DatabaseError=exports.copyDone=exports.emptyQuery=exports.replicationStart=exports.portalSuspended=exports.noData=exports.closeComplete=exports.bindComplete=exports.parseComplete=void 0,exports.parseComplete={name:"parseComplete",length:5},exports.bindComplete={name:"bindComplete",length:5},exports.closeComplete={name:"closeComplete",length:5},exports.noData={name:"noData",length:5},exports.portalSuspended={name:"portalSuspended",length:5},exports.replicationStart={name:"replicationStart",length:4},exports.emptyQuery={name:"emptyQuery",length:4},exports.copyDone={name:"copyDone",length:4};class DatabaseError extends Error{constructor(message,length,name){super(message);this.length=length,this.name=name}}exports.DatabaseError=DatabaseError;class CopyDataMessage{constructor(length,chunk){this.length=length,this.chunk=chunk,this.name="copyData"}}exports.CopyDataMessage=CopyDataMessage;class CopyResponse{constructor(length,name,binary,columnCount){this.length=length,this.name=name,this.binary=binary,this.columnTypes=Array(columnCount)}}exports.CopyResponse=CopyResponse;class Field{constructor(name,tableID,columnID,dataTypeID,dataTypeSize,dataTypeModifier,format){this.name=name,this.tableID=tableID,this.columnID=columnID,this.dataTypeID=dataTypeID,this.dataTypeSize=dataTypeSize,this.dataTypeModifier=dataTypeModifier,this.format=format}}exports.Field=Field;class RowDescriptionMessage{constructor(length,fieldCount){this.length=length,this.fieldCount=fieldCount,this.name="rowDescription",this.fields=Array(this.fieldCount)}}exports.RowDescriptionMessage=RowDescriptionMessage;class ParameterDescriptionMessage{constructor(length,parameterCount){this.length=length,this.parameterCount=parameterCount,this.name="parameterDescription",this.dataTypeIDs=Array(this.parameterCount)}}exports.ParameterDescriptionMessage=ParameterDescriptionMessage;class ParameterStatusMessage{constructor(length,parameterName,parameterValue){this.length=length,this.parameterName=parameterName,this.parameterValue=parameterValue,this.name="parameterStatus"}}exports.ParameterStatusMessage=ParameterStatusMessage;class AuthenticationMD5Password{constructor(length,salt){this.length=length,this.salt=salt,this.name="authenticationMD5Password"}}exports.AuthenticationMD5Password=AuthenticationMD5Password;class BackendKeyDataMessage{constructor(length,processID,secretKey){this.length=length,this.processID=processID,this.secretKey=secretKey,this.name="backendKeyData"}}exports.BackendKeyDataMessage=BackendKeyDataMessage;class NotificationResponseMessage{constructor(length,processId,channel,payload){this.length=length,this.processId=processId,this.channel=channel,this.payload=payload,this.name="notification"}}exports.NotificationResponseMessage=NotificationResponseMessage;class ReadyForQueryMessage{constructor(length,status){this.length=length,this.status=status,this.name="readyForQuery"}}exports.ReadyForQueryMessage=ReadyForQueryMessage;class CommandCompleteMessage{constructor(length,text){this.length=length,this.text=text,this.name="commandComplete"}}exports.CommandCompleteMessage=CommandCompleteMessage;class DataRowMessage{constructor(length,fields){this.length=length,this.fields=fields,this.name="dataRow",this.fieldCount=fields.length}}exports.DataRowMessage=DataRowMessage;class NoticeMessage{constructor(length,message){this.length=length,this.message=message,this.name="notice"}}exports.NoticeMessage=NoticeMessage}),require_buffer_writer=__commonJS2((exports)=>{Object.defineProperty(exports,"__esModule",{value:!0}),exports.Writer=void 0;class Writer{constructor(size=256){this.size=size,this.offset=5,this.headerPosition=0,this.buffer=Buffer.allocUnsafe(size)}ensure(size){if(this.buffer.length-this.offset<size){let oldBuffer=this.buffer,newSize=oldBuffer.length+(oldBuffer.length>>1)+size;this.buffer=Buffer.allocUnsafe(newSize),oldBuffer.copy(this.buffer)}}addInt32(num){return this.ensure(4),this.buffer[this.offset++]=num>>>24&255,this.buffer[this.offset++]=num>>>16&255,this.buffer[this.offset++]=num>>>8&255,this.buffer[this.offset++]=num>>>0&255,this}addInt16(num){return this.ensure(2),this.buffer[this.offset++]=num>>>8&255,this.buffer[this.offset++]=num>>>0&255,this}addCString(string){if(!string)this.ensure(1);else{let len=Buffer.byteLength(string);this.ensure(len+1),this.buffer.write(string,this.offset,"utf-8"),this.offset+=len}return this.buffer[this.offset++]=0,this}addString(string=""){let len=Buffer.byteLength(string);return this.ensure(len),this.buffer.write(string,this.offset),this.offset+=len,this}add(otherBuffer){return this.ensure(otherBuffer.length),otherBuffer.copy(this.buffer,this.offset),this.offset+=otherBuffer.length,this}join(code){if(code){this.buffer[this.headerPosition]=code;let length=this.offset-(this.headerPosition+1);this.buffer.writeInt32BE(length,this.headerPosition+1)}return this.buffer.slice(code?0:5,this.offset)}flush(code){let result=this.join(code);return this.offset=5,this.headerPosition=0,this.buffer=Buffer.allocUnsafe(this.size),result}}exports.Writer=Writer}),require_serializer=__commonJS2((exports)=>{Object.defineProperty(exports,"__esModule",{value:!0}),exports.serialize=void 0;var buffer_writer_1=require_buffer_writer(),writer=new buffer_writer_1.Writer,startup=(opts)=>{writer.addInt16(3).addInt16(0);for(let key of Object.keys(opts))writer.addCString(key).addCString(opts[key]);writer.addCString("client_encoding").addCString("UTF8");let bodyBuffer=writer.addCString("").flush(),length=bodyBuffer.length+4;return new buffer_writer_1.Writer().addInt32(length).add(bodyBuffer).flush()},requestSsl=()=>{let response=Buffer.allocUnsafe(8);return response.writeInt32BE(8,0),response.writeInt32BE(80877103,4),response},password=(password2)=>{return writer.addCString(password2).flush(112)},sendSASLInitialResponseMessage=function(mechanism,initialResponse){return writer.addCString(mechanism).addInt32(Buffer.byteLength(initialResponse)).addString(initialResponse),writer.flush(112)},sendSCRAMClientFinalMessage=function(additionalData){return writer.addString(additionalData).flush(112)},query=(text)=>{return writer.addCString(text).flush(81)},emptyArray=[],parse2=(query2)=>{let name=query2.name||"";if(name.length>63)console.error("Warning! Postgres only supports 63 characters for query names."),console.error("You supplied %s (%s)",name,name.length),console.error("This can cause conflicts and silent errors executing queries");let types3=query2.types||emptyArray,len=types3.length,buffer=writer.addCString(name).addCString(query2.text).addInt16(len);for(let i=0;i<len;i++)buffer.addInt32(types3[i]);return writer.flush(80)},paramWriter=new buffer_writer_1.Writer,writeValues=function(values2,valueMapper){for(let i=0;i<values2.length;i++){let mappedVal=valueMapper?valueMapper(values2[i],i):values2[i];if(mappedVal==null)writer.addInt16(0),paramWriter.addInt32(-1);else if(mappedVal instanceof Buffer)writer.addInt16(1),paramWriter.addInt32(mappedVal.length),paramWriter.add(mappedVal);else writer.addInt16(0),paramWriter.addInt32(Buffer.byteLength(mappedVal)),paramWriter.addString(mappedVal)}},bind=(config={})=>{let portal=config.portal||"",statement=config.statement||"",binary=config.binary||!1,values2=config.values||emptyArray,len=values2.length;return writer.addCString(portal).addCString(statement),writer.addInt16(len),writeValues(values2,config.valueMapper),writer.addInt16(len),writer.add(paramWriter.flush()),writer.addInt16(1),writer.addInt16(binary?1:0),writer.flush(66)},emptyExecute=Buffer.from([69,0,0,0,9,0,0,0,0,0]),execute=(config)=>{if(!config||!config.portal&&!config.rows)return emptyExecute;let portal=config.portal||"",rows=config.rows||0,portalLength=Buffer.byteLength(portal),len=4+portalLength+1+4,buff=Buffer.allocUnsafe(1+len);return buff[0]=69,buff.writeInt32BE(len,1),buff.write(portal,5,"utf-8"),buff[portalLength+5]=0,buff.writeUInt32BE(rows,buff.length-4),buff},cancel=(processID,secretKey)=>{let buffer=Buffer.allocUnsafe(16);return buffer.writeInt32BE(16,0),buffer.writeInt16BE(1234,4),buffer.writeInt16BE(5678,6),buffer.writeInt32BE(processID,8),buffer.writeInt32BE(secretKey,12),buffer},cstringMessage=(code,string)=>{let len=4+Buffer.byteLength(string)+1,buffer=Buffer.allocUnsafe(1+len);return buffer[0]=code,buffer.writeInt32BE(len,1),buffer.write(string,5,"utf-8"),buffer[len]=0,buffer},emptyDescribePortal=writer.addCString("P").flush(68),emptyDescribeStatement=writer.addCString("S").flush(68),describe=(msg)=>{return msg.name?cstringMessage(68,`${msg.type}${msg.name||""}`):msg.type==="P"?emptyDescribePortal:emptyDescribeStatement},close=(msg)=>{let text=`${msg.type}${msg.name||""}`;return cstringMessage(67,text)},copyData=(chunk)=>{return writer.add(chunk).flush(100)},copyFail=(message)=>{return cstringMessage(102,message)},codeOnlyBuffer=(code)=>Buffer.from([code,0,0,0,4]),flushBuffer=codeOnlyBuffer(72),syncBuffer=codeOnlyBuffer(83),endBuffer=codeOnlyBuffer(88),copyDoneBuffer=codeOnlyBuffer(99),serialize={startup,password,requestSsl,sendSASLInitialResponseMessage,sendSCRAMClientFinalMessage,query,parse:parse2,bind,execute,describe,close,flush:()=>flushBuffer,sync:()=>syncBuffer,end:()=>endBuffer,copyData,copyDone:()=>copyDoneBuffer,copyFail,cancel};exports.serialize=serialize}),require_buffer_reader=__commonJS2((exports)=>{Object.defineProperty(exports,"__esModule",{value:!0}),exports.BufferReader=void 0;class BufferReader{constructor(offset=0){this.offset=offset,this.buffer=Buffer.allocUnsafe(0),this.encoding="utf-8"}setBuffer(offset,buffer){this.offset=offset,this.buffer=buffer}int16(){let result=this.buffer.readInt16BE(this.offset);return this.offset+=2,result}byte(){let result=this.buffer[this.offset];return this.offset++,result}int32(){let result=this.buffer.readInt32BE(this.offset);return this.offset+=4,result}uint32(){let result=this.buffer.readUInt32BE(this.offset);return this.offset+=4,result}string(length){let result=this.buffer.toString(this.encoding,this.offset,this.offset+length);return this.offset+=length,result}cstring(){let start=this.offset,end=start;while(this.buffer[end++]!==0);return this.offset=end,this.buffer.toString(this.encoding,start,end-1)}bytes(length){let result=this.buffer.slice(this.offset,this.offset+length);return this.offset+=length,result}}exports.BufferReader=BufferReader}),require_parser=__commonJS2((exports)=>{Object.defineProperty(exports,"__esModule",{value:!0}),exports.Parser=void 0;var messages_1=require_messages(),buffer_reader_1=require_buffer_reader(),CODE_LENGTH=1,LEN_LENGTH=4,HEADER_LENGTH=CODE_LENGTH+LEN_LENGTH,LATEINIT_LENGTH=-1,emptyBuffer=Buffer.allocUnsafe(0);class Parser{constructor(opts){if(this.buffer=emptyBuffer,this.bufferLength=0,this.bufferOffset=0,this.reader=new buffer_reader_1.BufferReader,(opts===null||opts===void 0?void 0:opts.mode)==="binary")throw Error("Binary mode not supported yet");this.mode=(opts===null||opts===void 0?void 0:opts.mode)||"text"}parse(buffer,callback){this.mergeBuffer(buffer);let bufferFullLength=this.bufferOffset+this.bufferLength,offset=this.bufferOffset;while(offset+HEADER_LENGTH<=bufferFullLength){let code=this.buffer[offset],length=this.buffer.readUInt32BE(offset+CODE_LENGTH),fullMessageLength=CODE_LENGTH+length;if(fullMessageLength+offset<=bufferFullLength){let message=this.handlePacket(offset+HEADER_LENGTH,code,length,this.buffer);callback(message),offset+=fullMessageLength}else break}if(offset===bufferFullLength)this.buffer=emptyBuffer,this.bufferLength=0,this.bufferOffset=0;else this.bufferLength=bufferFullLength-offset,this.bufferOffset=offset}mergeBuffer(buffer){if(this.bufferLength>0){let newLength=this.bufferLength+buffer.byteLength;if(newLength+this.bufferOffset>this.buffer.byteLength){let newBuffer;if(newLength<=this.buffer.byteLength&&this.bufferOffset>=this.bufferLength)newBuffer=this.buffer;else{let newBufferLength=this.buffer.byteLength*2;while(newLength>=newBufferLength)newBufferLength*=2;newBuffer=Buffer.allocUnsafe(newBufferLength)}this.buffer.copy(newBuffer,0,this.bufferOffset,this.bufferOffset+this.bufferLength),this.buffer=newBuffer,this.bufferOffset=0}buffer.copy(this.buffer,this.bufferOffset+this.bufferLength),this.bufferLength=newLength}else this.buffer=buffer,this.bufferOffset=0,this.bufferLength=buffer.byteLength}handlePacket(offset,code,length,bytes){let{reader}=this;reader.setBuffer(offset,bytes);let message;switch(code){case 50:message=messages_1.bindComplete;break;case 49:message=messages_1.parseComplete;break;case 51:message=messages_1.closeComplete;break;case 110:message=messages_1.noData;break;case 115:message=messages_1.portalSuspended;break;case 99:message=messages_1.copyDone;break;case 87:message=messages_1.replicationStart;break;case 73:message=messages_1.emptyQuery;break;case 68:message=parseDataRowMessage(reader);break;case 67:message=parseCommandCompleteMessage(reader);break;case 90:message=parseReadyForQueryMessage(reader);break;case 65:message=parseNotificationMessage(reader);break;case 82:message=parseAuthenticationResponse(reader,length);break;case 83:message=parseParameterStatusMessage(reader);break;case 75:message=parseBackendKeyData(reader);break;case 69:message=parseErrorMessage(reader,"error");break;case 78:message=parseErrorMessage(reader,"notice");break;case 84:message=parseRowDescriptionMessage(reader);break;case 116:message=parseParameterDescriptionMessage(reader);break;case 71:message=parseCopyInMessage(reader);break;case 72:message=parseCopyOutMessage(reader);break;case 100:message=parseCopyData(reader,length);break;default:return new messages_1.DatabaseError("received invalid response: "+code.toString(16),length,"error")}return reader.setBuffer(0,emptyBuffer),message.length=length,message}}exports.Parser=Parser;var parseReadyForQueryMessage=(reader)=>{let status=reader.string(1);return new messages_1.ReadyForQueryMessage(LATEINIT_LENGTH,status)},parseCommandCompleteMessage=(reader)=>{let text=reader.cstring();return new messages_1.CommandCompleteMessage(LATEINIT_LENGTH,text)},parseCopyData=(reader,length)=>{let chunk=reader.bytes(length-4);return new messages_1.CopyDataMessage(LATEINIT_LENGTH,chunk)},parseCopyInMessage=(reader)=>parseCopyMessage(reader,"copyInResponse"),parseCopyOutMessage=(reader)=>parseCopyMessage(reader,"copyOutResponse"),parseCopyMessage=(reader,messageName)=>{let isBinary=reader.byte()!==0,columnCount=reader.int16(),message=new messages_1.CopyResponse(LATEINIT_LENGTH,messageName,isBinary,columnCount);for(let i=0;i<columnCount;i++)message.columnTypes[i]=reader.int16();return message},parseNotificationMessage=(reader)=>{let processId=reader.int32(),channel=reader.cstring(),payload=reader.cstring();return new messages_1.NotificationResponseMessage(LATEINIT_LENGTH,processId,channel,payload)},parseRowDescriptionMessage=(reader)=>{let fieldCount=reader.int16(),message=new messages_1.RowDescriptionMessage(LATEINIT_LENGTH,fieldCount);for(let i=0;i<fieldCount;i++)message.fields[i]=parseField2(reader);return message},parseField2=(reader)=>{let name=reader.cstring(),tableID=reader.uint32(),columnID=reader.int16(),dataTypeID=reader.uint32(),dataTypeSize=reader.int16(),dataTypeModifier=reader.int32(),mode=reader.int16()===0?"text":"binary";return new messages_1.Field(name,tableID,columnID,dataTypeID,dataTypeSize,dataTypeModifier,mode)},parseParameterDescriptionMessage=(reader)=>{let parameterCount=reader.int16(),message=new messages_1.ParameterDescriptionMessage(LATEINIT_LENGTH,parameterCount);for(let i=0;i<parameterCount;i++)message.dataTypeIDs[i]=reader.int32();return message},parseDataRowMessage=(reader)=>{let fieldCount=reader.int16(),fields=Array(fieldCount);for(let i=0;i<fieldCount;i++){let len=reader.int32();fields[i]=len===-1?null:reader.string(len)}return new messages_1.DataRowMessage(LATEINIT_LENGTH,fields)},parseParameterStatusMessage=(reader)=>{let name=reader.cstring(),value=reader.cstring();return new messages_1.ParameterStatusMessage(LATEINIT_LENGTH,name,value)},parseBackendKeyData=(reader)=>{let processID=reader.int32(),secretKey=reader.int32();return new messages_1.BackendKeyDataMessage(LATEINIT_LENGTH,processID,secretKey)},parseAuthenticationResponse=(reader,length)=>{let code=reader.int32(),message={name:"authenticationOk",length};switch(code){case 0:break;case 3:if(message.length===8)message.name="authenticationCleartextPassword";break;case 5:if(message.length===12){message.name="authenticationMD5Password";let salt=reader.bytes(4);return new messages_1.AuthenticationMD5Password(LATEINIT_LENGTH,salt)}break;case 10:{message.name="authenticationSASL",message.mechanisms=[];let mechanism;do if(mechanism=reader.cstring(),mechanism)message.mechanisms.push(mechanism);while(mechanism)}break;case 11:message.name="authenticationSASLContinue",message.data=reader.string(length-8);break;case 12:message.name="authenticationSASLFinal",message.data=reader.string(length-8);break;default:throw Error("Unknown authenticationOk message type "+code)}return message},parseErrorMessage=(reader,name)=>{let fields={},fieldType=reader.string(1);while(fieldType!=="\x00")fields[fieldType]=reader.cstring(),fieldType=reader.string(1);let messageValue=fields.M,message=name==="notice"?new messages_1.NoticeMessage(LATEINIT_LENGTH,messageValue):new messages_1.DatabaseError(messageValue,LATEINIT_LENGTH,name);return message.severity=fields.S,message.code=fields.C,message.detail=fields.D,message.hint=fields.H,message.position=fields.P,message.internalPosition=fields.p,message.internalQuery=fields.q,message.where=fields.W,message.schema=fields.s,message.table=fields.t,message.column=fields.c,message.dataType=fields.d,message.constraint=fields.n,message.file=fields.F,message.line=fields.L,message.routine=fields.R,message}}),require_dist=__commonJS2((exports)=>{Object.defineProperty(exports,"__esModule",{value:!0}),exports.DatabaseError=exports.serialize=exports.parse=void 0;var messages_1=require_messages();Object.defineProperty(exports,"DatabaseError",{enumerable:!0,get:function(){return messages_1.DatabaseError}});var serializer_1=require_serializer();Object.defineProperty(exports,"serialize",{enumerable:!0,get:function(){return serializer_1.serialize}});var parser_1=require_parser();function parse2(stream,callback){let parser=new parser_1.Parser;return stream.on("data",(buffer)=>parser.parse(buffer,callback)),new Promise((resolve6)=>stream.on("end",()=>resolve6()))}exports.parse=parse2}),require_empty=__commonJS2((exports)=>{Object.defineProperty(exports,"__esModule",{value:!0}),exports.default={}}),require_stream=__commonJS2((exports,module)=>{var{getStream,getSecureStream}=getStreamFuncs();module.exports={getStream,getSecureStream};function getNodejsStreamFuncs(){function getStream2(ssl){return new(__require2("net")).Socket}function getSecureStream2(options2){return __require2("tls").connect(options2)}return{getStream:getStream2,getSecureStream:getSecureStream2}}function getCloudflareStreamFuncs(){function getStream2(ssl){let{CloudflareSocket}=require_empty();return new CloudflareSocket(ssl)}function getSecureStream2(options2){return options2.socket.startTls(options2),options2.socket}return{getStream:getStream2,getSecureStream:getSecureStream2}}function isCloudflareRuntime(){if(typeof navigator==="object"&&navigator!==null&&typeof navigator.userAgent==="string")return navigator.userAgent==="Cloudflare-Workers";if(typeof Response==="function"){let resp=new Response(null,{cf:{thing:!0}});if(typeof resp.cf==="object"&&resp.cf!==null&&resp.cf.thing)return!0}return!1}function getStreamFuncs(){if(isCloudflareRuntime())return getCloudflareStreamFuncs();return getNodejsStreamFuncs()}}),require_connection=__commonJS2((exports,module)=>{var EventEmitter=__require2("events").EventEmitter,{parse:parse2,serialize}=require_dist(),{getStream,getSecureStream}=require_stream(),flushBuffer=serialize.flush(),syncBuffer=serialize.sync(),endBuffer=serialize.end();class Connection extends EventEmitter{constructor(config){super();if(config=config||{},this.stream=config.stream||getStream(config.ssl),typeof this.stream==="function")this.stream=this.stream(config);this._keepAlive=config.keepAlive,this._keepAliveInitialDelayMillis=config.keepAliveInitialDelayMillis,this.parsedStatements={},this.ssl=config.ssl||!1,this._ending=!1,this._emitMessage=!1;let self2=this;this.on("newListener",function(eventName){if(eventName==="message")self2._emitMessage=!0})}connect(port,host){let self2=this;this._connecting=!0,this.stream.setNoDelay(!0),this.stream.connect(port,host),this.stream.once("connect",function(){if(self2._keepAlive)self2.stream.setKeepAlive(!0,self2._keepAliveInitialDelayMillis);self2.emit("connect")});let reportStreamError=function(error2){if(self2._ending&&(error2.code==="ECONNRESET"||error2.code==="EPIPE"))return;self2.emit("error",error2)};if(this.stream.on("error",reportStreamError),this.stream.on("close",function(){self2.emit("end")}),!this.ssl)return this.attachListeners(this.stream);this.stream.once("data",function(buffer){switch(buffer.toString("utf8")){case"S":break;case"N":return self2.stream.end(),self2.emit("error",Error("The server does not support SSL connections"));default:return self2.stream.end(),self2.emit("error",Error("There was an error establishing an SSL connection"))}let options2={socket:self2.stream};if(self2.ssl!==!0){if(Object.assign(options2,self2.ssl),"key"in self2.ssl)options2.key=self2.ssl.key}let net=__require2("net");if(net.isIP&&net.isIP(host)===0)options2.servername=host;try{self2.stream=getSecureStream(options2)}catch(err){return self2.emit("error",err)}self2.attachListeners(self2.stream),self2.stream.on("error",reportStreamError),self2.emit("sslconnect")})}attachListeners(stream){parse2(stream,(msg)=>{let eventName=msg.name==="error"?"errorMessage":msg.name;if(this._emitMessage)this.emit("message",msg);this.emit(eventName,msg)})}requestSsl(){this.stream.write(serialize.requestSsl())}startup(config){this.stream.write(serialize.startup(config))}cancel(processID,secretKey){this._send(serialize.cancel(processID,secretKey))}password(password){this._send(serialize.password(password))}sendSASLInitialResponseMessage(mechanism,initialResponse){this._send(serialize.sendSASLInitialResponseMessage(mechanism,initialResponse))}sendSCRAMClientFinalMessage(additionalData){this._send(serialize.sendSCRAMClientFinalMessage(additionalData))}_send(buffer){if(!this.stream.writable)return!1;return this.stream.write(buffer)}query(text){this._send(serialize.query(text))}parse(query){this._send(serialize.parse(query))}bind(config){this._send(serialize.bind(config))}execute(config){this._send(serialize.execute(config))}flush(){if(this.stream.writable)this.stream.write(flushBuffer)}sync(){this._ending=!0,this._send(syncBuffer)}ref(){this.stream.ref()}unref(){this.stream.unref()}end(){if(this._ending=!0,!this._connecting||!this.stream.writable){this.stream.end();return}return this.stream.write(endBuffer,()=>{this.stream.end()})}close(msg){this._send(serialize.close(msg))}describe(msg){this._send(serialize.describe(msg))}sendCopyFromChunk(chunk){this._send(serialize.copyData(chunk))}endCopyFrom(){this._send(serialize.copyDone())}sendCopyFail(msg){this._send(serialize.copyFail(msg))}}module.exports=Connection}),require_split2=__commonJS2((exports,module)=>{var{Transform}=__require2("stream"),{StringDecoder}=__require2("string_decoder"),kLast=Symbol("last"),kDecoder=Symbol("decoder");function transform(chunk,enc,cb){let list;if(this.overflow){if(list=this[kDecoder].write(chunk).split(this.matcher),list.length===1)return cb();list.shift(),this.overflow=!1}else this[kLast]+=this[kDecoder].write(chunk),list=this[kLast].split(this.matcher);this[kLast]=list.pop();for(let i=0;i<list.length;i++)try{push(this,this.mapper(list[i]))}catch(error2){return cb(error2)}if(this.overflow=this[kLast].length>this.maxLength,this.overflow&&!this.skipOverflow){cb(Error("maximum buffer reached"));return}cb()}function flush(cb){if(this[kLast]+=this[kDecoder].end(),this[kLast])try{push(this,this.mapper(this[kLast]))}catch(error2){return cb(error2)}cb()}function push(self2,val){if(val!==void 0)self2.push(val)}function noop2(incoming){return incoming}function split(matcher,mapper,options2){switch(matcher=matcher||/\r?\n/,mapper=mapper||noop2,options2=options2||{},arguments.length){case 1:if(typeof matcher==="function")mapper=matcher,matcher=/\r?\n/;else if(typeof matcher==="object"&&!(matcher instanceof RegExp)&&!matcher[Symbol.split])options2=matcher,matcher=/\r?\n/;break;case 2:if(typeof matcher==="function")options2=mapper,mapper=matcher,matcher=/\r?\n/;else if(typeof mapper==="object")options2=mapper,mapper=noop2}options2=Object.assign({},options2),options2.autoDestroy=!0,options2.transform=transform,options2.flush=flush,options2.readableObjectMode=!0;let stream=new Transform(options2);return stream[kLast]="",stream[kDecoder]=new StringDecoder("utf8"),stream.matcher=matcher,stream.mapper=mapper,stream.maxLength=options2.maxLength,stream.skipOverflow=options2.skipOverflow||!1,stream.overflow=!1,stream._destroy=function(err,cb){this._writableState.errorEmitted=!1,cb(err)},stream}module.exports=split}),require_helper=__commonJS2((exports,module)=>{var path2=__require2("path"),Stream2=__require2("stream").Stream,split=require_split2(),util=__require2("util"),defaultPort=5432,isWin=process.platform==="win32",warnStream=process.stderr,S_IRWXG=56,S_IRWXO=7,S_IFMT=61440,S_IFREG=32768;function isRegFile(mode){return(mode&S_IFMT)==S_IFREG}var fieldNames=["host","port","database","user","password"],nrOfFields=fieldNames.length,passKey=fieldNames[nrOfFields-1];function warn(){var isWritable=warnStream instanceof Stream2&&warnStream.writable===!0;if(isWritable){var args=Array.prototype.slice.call(arguments).concat(`
|
|
1015
|
-
`);warnStream.write(util.format.apply(util,args))}}Object.defineProperty(exports,"isWin",{get:function(){return isWin},set:function(val){isWin=val}}),exports.warnTo=function(stream){var old=warnStream;return warnStream=stream,old},exports.getFileName=function(rawEnv){var env2=rawEnv||process.env,file=env2.PGPASSFILE||(isWin?path2.join(env2.APPDATA||"./","postgresql","pgpass.conf"):path2.join(env2.HOME||"./",".pgpass"));return file},exports.usePgPass=function(stats,fname){if(Object.prototype.hasOwnProperty.call(process.env,"PGPASSWORD"))return!1;if(isWin)return!0;if(fname=fname||"<unkn>",!isRegFile(stats.mode))return warn('WARNING: password file "%s" is not a plain file',fname),!1;if(stats.mode&(S_IRWXG|S_IRWXO))return warn('WARNING: password file "%s" has group or world access; permissions should be u=rw (0600) or less',fname),!1;return!0};var matcher=exports.match=function(connInfo,entry){return fieldNames.slice(0,-1).reduce(function(prev,field,idx){if(idx==1){if(Number(connInfo[field]||defaultPort)===Number(entry[field]))return prev&&!0}return prev&&(entry[field]==="*"||entry[field]===connInfo[field])},!0)};exports.getPassword=function(connInfo,stream,cb){var pass,lineStream=stream.pipe(split());function onLine(line){var entry=parseLine(line);if(entry&&isValidEntry(entry)&&matcher(connInfo,entry))pass=entry[passKey],lineStream.end()}var onEnd=function(){stream.destroy(),cb(pass)},onErr=function(err){stream.destroy(),warn("WARNING: error on reading file: %s",err),cb(void 0)};stream.on("error",onErr),lineStream.on("data",onLine).on("end",onEnd).on("error",onErr)};var parseLine=exports.parseLine=function(line){if(line.length<11||line.match(/^\s+#/))return null;var curChar="",prevChar="",fieldIdx=0,startIdx=0,endIdx=0,obj={},isLastField=!1,addToObj=function(idx,i0,i1){var field=line.substring(i0,i1);if(!Object.hasOwnProperty.call(process.env,"PGPASS_NO_DEESCAPE"))field=field.replace(/\\([:\\])/g,"$1");obj[fieldNames[idx]]=field};for(var i=0;i<line.length-1;i+=1){if(curChar=line.charAt(i+1),prevChar=line.charAt(i),isLastField=fieldIdx==nrOfFields-1,isLastField){addToObj(fieldIdx,startIdx);break}if(i>=0&&curChar==":"&&prevChar!=="\\")addToObj(fieldIdx,startIdx,i+1),startIdx=i+2,fieldIdx+=1}return obj=Object.keys(obj).length===nrOfFields?obj:null,obj},isValidEntry=exports.isValidEntry=function(entry){var rules={0:function(x){return x.length>0},1:function(x){if(x==="*")return!0;return x=Number(x),isFinite(x)&&x>0&&x<9007199254740992&&Math.floor(x)===x},2:function(x){return x.length>0},3:function(x){return x.length>0},4:function(x){return x.length>0}};for(var idx=0;idx<fieldNames.length;idx+=1){var rule=rules[idx],value=entry[fieldNames[idx]]||"",res=rule(value);if(!res)return!1}return!0}}),require_lib=__commonJS2((exports,module)=>{var path2=__require2("path"),fs=__require2("fs"),helper=require_helper();module.exports=function(connInfo,cb){var file=helper.getFileName();fs.stat(file,function(err,stat2){if(err||!helper.usePgPass(stat2,file))return cb(void 0);var st=fs.createReadStream(file);helper.getPassword(connInfo,st,cb)})},module.exports.warnTo=helper.warnTo}),require_client=__commonJS2((exports,module)=>{var EventEmitter=__require2("events").EventEmitter,utils2=require_utils2(),nodeUtils=__require2("util"),sasl=require_sasl(),TypeOverrides=require_type_overrides(),ConnectionParameters=require_connection_parameters(),Query=require_query(),defaults2=require_defaults2(),Connection=require_connection(),crypto2=require_utils22(),activeQueryDeprecationNotice=nodeUtils.deprecate(()=>{},"Client.activeQuery is deprecated and will be removed in pg@9.0"),queryQueueDeprecationNotice=nodeUtils.deprecate(()=>{},"Client.queryQueue is deprecated and will be removed in pg@9.0."),pgPassDeprecationNotice=nodeUtils.deprecate(()=>{},"pgpass support is deprecated and will be removed in pg@9.0. You can provide an async function as the password property to the Client/Pool constructor that returns a password instead. Within this function you can call the pgpass module in your own code."),byoPromiseDeprecationNotice=nodeUtils.deprecate(()=>{},"Passing a custom Promise implementation to the Client/Pool constructor is deprecated and will be removed in pg@9.0."),queryQueueLengthDeprecationNotice=nodeUtils.deprecate(()=>{},"Calling client.query() when the client is already executing a query is deprecated and will be removed in pg@9.0. Use async/await or an external async flow control mechanism instead.");class Client2 extends EventEmitter{constructor(config){super();this.connectionParameters=new ConnectionParameters(config),this.user=this.connectionParameters.user,this.database=this.connectionParameters.database,this.port=this.connectionParameters.port,this.host=this.connectionParameters.host,Object.defineProperty(this,"password",{configurable:!0,enumerable:!1,writable:!0,value:this.connectionParameters.password}),this.replication=this.connectionParameters.replication;let c=config||{};if(c.Promise)byoPromiseDeprecationNotice();if(this._Promise=c.Promise||global.Promise,this._types=new TypeOverrides(c.types),this._ending=!1,this._ended=!1,this._connecting=!1,this._connected=!1,this._connectionError=!1,this._queryable=!0,this._activeQuery=null,this.enableChannelBinding=Boolean(c.enableChannelBinding),this.connection=c.connection||new Connection({stream:c.stream,ssl:this.connectionParameters.ssl,keepAlive:c.keepAlive||!1,keepAliveInitialDelayMillis:c.keepAliveInitialDelayMillis||0,encoding:this.connectionParameters.client_encoding||"utf8"}),this._queryQueue=[],this.binary=c.binary||defaults2.binary,this.processID=null,this.secretKey=null,this.ssl=this.connectionParameters.ssl||!1,this.ssl&&this.ssl.key)Object.defineProperty(this.ssl,"key",{enumerable:!1});this._connectionTimeoutMillis=c.connectionTimeoutMillis||0}get activeQuery(){return activeQueryDeprecationNotice(),this._activeQuery}set activeQuery(val){activeQueryDeprecationNotice(),this._activeQuery=val}_getActiveQuery(){return this._activeQuery}_errorAllQueries(err){let enqueueError=(query)=>{process.nextTick(()=>{query.handleError(err,this.connection)})},activeQuery=this._getActiveQuery();if(activeQuery)enqueueError(activeQuery),this._activeQuery=null;this._queryQueue.forEach(enqueueError),this._queryQueue.length=0}_connect(callback){let self2=this,con=this.connection;if(this._connectionCallback=callback,this._connecting||this._connected){let err=Error("Client has already been connected. You cannot reuse a client.");process.nextTick(()=>{callback(err)});return}if(this._connecting=!0,this._connectionTimeoutMillis>0){if(this.connectionTimeoutHandle=setTimeout(()=>{con._ending=!0,con.stream.destroy(Error("timeout expired"))},this._connectionTimeoutMillis),this.connectionTimeoutHandle.unref)this.connectionTimeoutHandle.unref()}if(this.host&&this.host.indexOf("/")===0)con.connect(this.host+"/.s.PGSQL."+this.port);else con.connect(this.port,this.host);con.on("connect",function(){if(self2.ssl)con.requestSsl();else con.startup(self2.getStartupConf())}),con.on("sslconnect",function(){con.startup(self2.getStartupConf())}),this._attachListeners(con),con.once("end",()=>{let error2=this._ending?Error("Connection terminated"):Error("Connection terminated unexpectedly");if(clearTimeout(this.connectionTimeoutHandle),this._errorAllQueries(error2),this._ended=!0,!this._ending){if(this._connecting&&!this._connectionError)if(this._connectionCallback)this._connectionCallback(error2);else this._handleErrorEvent(error2);else if(!this._connectionError)this._handleErrorEvent(error2)}process.nextTick(()=>{this.emit("end")})})}connect(callback){if(callback){this._connect(callback);return}return new this._Promise((resolve6,reject)=>{this._connect((error2)=>{if(error2)reject(error2);else resolve6(this)})})}_attachListeners(con){con.on("authenticationCleartextPassword",this._handleAuthCleartextPassword.bind(this)),con.on("authenticationMD5Password",this._handleAuthMD5Password.bind(this)),con.on("authenticationSASL",this._handleAuthSASL.bind(this)),con.on("authenticationSASLContinue",this._handleAuthSASLContinue.bind(this)),con.on("authenticationSASLFinal",this._handleAuthSASLFinal.bind(this)),con.on("backendKeyData",this._handleBackendKeyData.bind(this)),con.on("error",this._handleErrorEvent.bind(this)),con.on("errorMessage",this._handleErrorMessage.bind(this)),con.on("readyForQuery",this._handleReadyForQuery.bind(this)),con.on("notice",this._handleNotice.bind(this)),con.on("rowDescription",this._handleRowDescription.bind(this)),con.on("dataRow",this._handleDataRow.bind(this)),con.on("portalSuspended",this._handlePortalSuspended.bind(this)),con.on("emptyQuery",this._handleEmptyQuery.bind(this)),con.on("commandComplete",this._handleCommandComplete.bind(this)),con.on("parseComplete",this._handleParseComplete.bind(this)),con.on("copyInResponse",this._handleCopyInResponse.bind(this)),con.on("copyData",this._handleCopyData.bind(this)),con.on("notification",this._handleNotification.bind(this))}_getPassword(cb){let con=this.connection;if(typeof this.password==="function")this._Promise.resolve().then(()=>this.password(this.connectionParameters)).then((pass)=>{if(pass!==void 0){if(typeof pass!=="string"){con.emit("error",TypeError("Password must be a string"));return}this.connectionParameters.password=this.password=pass}else this.connectionParameters.password=this.password=null;cb()}).catch((err)=>{con.emit("error",err)});else if(this.password!==null)cb();else try{require_lib()(this.connectionParameters,(pass)=>{if(pass!==void 0)pgPassDeprecationNotice(),this.connectionParameters.password=this.password=pass;cb()})}catch(e){this.emit("error",e)}}_handleAuthCleartextPassword(msg){this._getPassword(()=>{this.connection.password(this.password)})}_handleAuthMD5Password(msg){this._getPassword(async()=>{try{let hashedPassword=await crypto2.postgresMd5PasswordHash(this.user,this.password,msg.salt);this.connection.password(hashedPassword)}catch(e){this.emit("error",e)}})}_handleAuthSASL(msg){this._getPassword(()=>{try{this.saslSession=sasl.startSession(msg.mechanisms,this.enableChannelBinding&&this.connection.stream),this.connection.sendSASLInitialResponseMessage(this.saslSession.mechanism,this.saslSession.response)}catch(err){this.connection.emit("error",err)}})}async _handleAuthSASLContinue(msg){try{await sasl.continueSession(this.saslSession,this.password,msg.data,this.enableChannelBinding&&this.connection.stream),this.connection.sendSCRAMClientFinalMessage(this.saslSession.response)}catch(err){this.connection.emit("error",err)}}_handleAuthSASLFinal(msg){try{sasl.finalizeSession(this.saslSession,msg.data),this.saslSession=null}catch(err){this.connection.emit("error",err)}}_handleBackendKeyData(msg){this.processID=msg.processID,this.secretKey=msg.secretKey}_handleReadyForQuery(msg){if(this._connecting){if(this._connecting=!1,this._connected=!0,clearTimeout(this.connectionTimeoutHandle),this._connectionCallback)this._connectionCallback(null,this),this._connectionCallback=null;this.emit("connect")}let activeQuery=this._getActiveQuery();if(this._activeQuery=null,this.readyForQuery=!0,activeQuery)activeQuery.handleReadyForQuery(this.connection);this._pulseQueryQueue()}_handleErrorWhileConnecting(err){if(this._connectionError)return;if(this._connectionError=!0,clearTimeout(this.connectionTimeoutHandle),this._connectionCallback)return this._connectionCallback(err);this.emit("error",err)}_handleErrorEvent(err){if(this._connecting)return this._handleErrorWhileConnecting(err);this._queryable=!1,this._errorAllQueries(err),this.emit("error",err)}_handleErrorMessage(msg){if(this._connecting)return this._handleErrorWhileConnecting(msg);let activeQuery=this._getActiveQuery();if(!activeQuery){this._handleErrorEvent(msg);return}this._activeQuery=null,activeQuery.handleError(msg,this.connection)}_handleRowDescription(msg){let activeQuery=this._getActiveQuery();if(activeQuery==null){let error2=Error("Received unexpected rowDescription message from backend.");this._handleErrorEvent(error2);return}activeQuery.handleRowDescription(msg)}_handleDataRow(msg){let activeQuery=this._getActiveQuery();if(activeQuery==null){let error2=Error("Received unexpected dataRow message from backend.");this._handleErrorEvent(error2);return}activeQuery.handleDataRow(msg)}_handlePortalSuspended(msg){let activeQuery=this._getActiveQuery();if(activeQuery==null){let error2=Error("Received unexpected portalSuspended message from backend.");this._handleErrorEvent(error2);return}activeQuery.handlePortalSuspended(this.connection)}_handleEmptyQuery(msg){let activeQuery=this._getActiveQuery();if(activeQuery==null){let error2=Error("Received unexpected emptyQuery message from backend.");this._handleErrorEvent(error2);return}activeQuery.handleEmptyQuery(this.connection)}_handleCommandComplete(msg){let activeQuery=this._getActiveQuery();if(activeQuery==null){let error2=Error("Received unexpected commandComplete message from backend.");this._handleErrorEvent(error2);return}activeQuery.handleCommandComplete(msg,this.connection)}_handleParseComplete(){let activeQuery=this._getActiveQuery();if(activeQuery==null){let error2=Error("Received unexpected parseComplete message from backend.");this._handleErrorEvent(error2);return}if(activeQuery.name)this.connection.parsedStatements[activeQuery.name]=activeQuery.text}_handleCopyInResponse(msg){let activeQuery=this._getActiveQuery();if(activeQuery==null){let error2=Error("Received unexpected copyInResponse message from backend.");this._handleErrorEvent(error2);return}activeQuery.handleCopyInResponse(this.connection)}_handleCopyData(msg){let activeQuery=this._getActiveQuery();if(activeQuery==null){let error2=Error("Received unexpected copyData message from backend.");this._handleErrorEvent(error2);return}activeQuery.handleCopyData(msg,this.connection)}_handleNotification(msg){this.emit("notification",msg)}_handleNotice(msg){this.emit("notice",msg)}getStartupConf(){let params=this.connectionParameters,data={user:params.user,database:params.database},appName=params.application_name||params.fallback_application_name;if(appName)data.application_name=appName;if(params.replication)data.replication=""+params.replication;if(params.statement_timeout)data.statement_timeout=String(parseInt(params.statement_timeout,10));if(params.lock_timeout)data.lock_timeout=String(parseInt(params.lock_timeout,10));if(params.idle_in_transaction_session_timeout)data.idle_in_transaction_session_timeout=String(parseInt(params.idle_in_transaction_session_timeout,10));if(params.options)data.options=params.options;return data}cancel(client,query){if(client.activeQuery===query){let con=this.connection;if(this.host&&this.host.indexOf("/")===0)con.connect(this.host+"/.s.PGSQL."+this.port);else con.connect(this.port,this.host);con.on("connect",function(){con.cancel(client.processID,client.secretKey)})}else if(client._queryQueue.indexOf(query)!==-1)client._queryQueue.splice(client._queryQueue.indexOf(query),1)}setTypeParser(oid,format,parseFn){return this._types.setTypeParser(oid,format,parseFn)}getTypeParser(oid,format){return this._types.getTypeParser(oid,format)}escapeIdentifier(str3){return utils2.escapeIdentifier(str3)}escapeLiteral(str3){return utils2.escapeLiteral(str3)}_pulseQueryQueue(){if(this.readyForQuery===!0){this._activeQuery=this._queryQueue.shift();let activeQuery=this._getActiveQuery();if(activeQuery){this.readyForQuery=!1,this.hasExecuted=!0;let queryError=activeQuery.submit(this.connection);if(queryError)process.nextTick(()=>{activeQuery.handleError(queryError,this.connection),this.readyForQuery=!0,this._pulseQueryQueue()})}else if(this.hasExecuted)this._activeQuery=null,this.emit("drain")}}query(config,values2,callback){let query,result,readTimeout,readTimeoutTimer,queryCallback;if(config===null||config===void 0)throw TypeError("Client was passed a null or undefined query");else if(typeof config.submit==="function"){if(readTimeout=config.query_timeout||this.connectionParameters.query_timeout,result=query=config,!query.callback){if(typeof values2==="function")query.callback=values2;else if(callback)query.callback=callback}}else if(readTimeout=config.query_timeout||this.connectionParameters.query_timeout,query=new Query(config,values2,callback),!query.callback)result=new this._Promise((resolve6,reject)=>{query.callback=(err,res)=>err?reject(err):resolve6(res)}).catch((err)=>{throw Error.captureStackTrace(err),err});if(readTimeout)queryCallback=query.callback||(()=>{}),readTimeoutTimer=setTimeout(()=>{let error2=Error("Query read timeout");process.nextTick(()=>{query.handleError(error2,this.connection)}),queryCallback(error2),query.callback=()=>{};let index=this._queryQueue.indexOf(query);if(index>-1)this._queryQueue.splice(index,1);this._pulseQueryQueue()},readTimeout),query.callback=(err,res)=>{clearTimeout(readTimeoutTimer),queryCallback(err,res)};if(this.binary&&!query.binary)query.binary=!0;if(query._result&&!query._result._types)query._result._types=this._types;if(!this._queryable)return process.nextTick(()=>{query.handleError(Error("Client has encountered a connection error and is not queryable"),this.connection)}),result;if(this._ending)return process.nextTick(()=>{query.handleError(Error("Client was closed and is not queryable"),this.connection)}),result;if(this._queryQueue.length>0)queryQueueLengthDeprecationNotice();return this._queryQueue.push(query),this._pulseQueryQueue(),result}ref(){this.connection.ref()}unref(){this.connection.unref()}end(cb){if(this._ending=!0,!this.connection._connecting||this._ended)if(cb)cb();else return this._Promise.resolve();if(this._getActiveQuery()||!this._queryable)this.connection.stream.destroy();else this.connection.end();if(cb)this.connection.once("end",cb);else return new this._Promise((resolve6)=>{this.connection.once("end",resolve6)})}get queryQueue(){return queryQueueDeprecationNotice(),this._queryQueue}}Client2.Query=Query,module.exports=Client2}),require_pg_pool=__commonJS2((exports,module)=>{var EventEmitter=__require2("events").EventEmitter,NOOP=function(){},removeWhere=(list,predicate)=>{let i=list.findIndex(predicate);return i===-1?void 0:list.splice(i,1)[0]};class IdleItem{constructor(client,idleListener,timeoutId){this.client=client,this.idleListener=idleListener,this.timeoutId=timeoutId}}class PendingItem{constructor(callback){this.callback=callback}}function throwOnDoubleRelease(){throw Error("Release called on client which has already been released to the pool.")}function promisify(Promise2,callback){if(callback)return{callback,result:void 0};let rej,res,cb=function(err,client){err?rej(err):res(client)},result=new Promise2(function(resolve6,reject){res=resolve6,rej=reject}).catch((err)=>{throw Error.captureStackTrace(err),err});return{callback:cb,result}}function makeIdleListener(pool,client){return function idleListener(err){err.client=client,client.removeListener("error",idleListener),client.on("error",()=>{pool.log("additional client error after disconnection due to error",err)}),pool._remove(client),pool.emit("error",err,client)}}class Pool extends EventEmitter{constructor(options2,Client2){super();if(this.options=Object.assign({},options2),options2!=null&&"password"in options2)Object.defineProperty(this.options,"password",{configurable:!0,enumerable:!1,writable:!0,value:options2.password});if(options2!=null&&options2.ssl&&options2.ssl.key)Object.defineProperty(this.options.ssl,"key",{enumerable:!1});if(this.options.max=this.options.max||this.options.poolSize||10,this.options.min=this.options.min||0,this.options.maxUses=this.options.maxUses||1/0,this.options.allowExitOnIdle=this.options.allowExitOnIdle||!1,this.options.maxLifetimeSeconds=this.options.maxLifetimeSeconds||0,this.log=this.options.log||function(){},this.Client=this.options.Client||Client2||require_lib2().Client,this.Promise=this.options.Promise||global.Promise,typeof this.options.idleTimeoutMillis>"u")this.options.idleTimeoutMillis=1e4;this._clients=[],this._idle=[],this._expired=new WeakSet,this._pendingQueue=[],this._endCallback=void 0,this.ending=!1,this.ended=!1}_promiseTry(f){let Promise2=this.Promise;if(typeof Promise2.try==="function")return Promise2.try(f);return new Promise2((resolve6)=>resolve6(f()))}_isFull(){return this._clients.length>=this.options.max}_isAboveMin(){return this._clients.length>this.options.min}_pulseQueue(){if(this.log("pulse queue"),this.ended){this.log("pulse queue ended");return}if(this.ending){if(this.log("pulse queue on ending"),this._idle.length)this._idle.slice().map((item)=>{this._remove(item.client)});if(!this._clients.length)this.ended=!0,this._endCallback();return}if(!this._pendingQueue.length){this.log("no queued requests");return}if(!this._idle.length&&this._isFull())return;let pendingItem=this._pendingQueue.shift();if(this._idle.length){let idleItem=this._idle.pop();clearTimeout(idleItem.timeoutId);let client=idleItem.client;client.ref&&client.ref();let idleListener=idleItem.idleListener;return this._acquireClient(client,pendingItem,idleListener,!1)}if(!this._isFull())return this.newClient(pendingItem);throw Error("unexpected condition")}_remove(client,callback){let removed=removeWhere(this._idle,(item)=>item.client===client);if(removed!==void 0)clearTimeout(removed.timeoutId);this._clients=this._clients.filter((c)=>c!==client);let context=this;client.end(()=>{if(context.emit("remove",client),typeof callback==="function")callback()})}connect(cb){if(this.ending){let err=Error("Cannot use a pool after calling end on the pool");return cb?cb(err):this.Promise.reject(err)}let response=promisify(this.Promise,cb),result=response.result;if(this._isFull()||this._idle.length){if(this._idle.length)process.nextTick(()=>this._pulseQueue());if(!this.options.connectionTimeoutMillis)return this._pendingQueue.push(new PendingItem(response.callback)),result;let queueCallback=(err,res,done)=>{clearTimeout(tid),response.callback(err,res,done)},pendingItem=new PendingItem(queueCallback),tid=setTimeout(()=>{removeWhere(this._pendingQueue,(i)=>i.callback===queueCallback),pendingItem.timedOut=!0,response.callback(Error("timeout exceeded when trying to connect"))},this.options.connectionTimeoutMillis);if(tid.unref)tid.unref();return this._pendingQueue.push(pendingItem),result}return this.newClient(new PendingItem(response.callback)),result}newClient(pendingItem){let client=new this.Client(this.options);this._clients.push(client);let idleListener=makeIdleListener(this,client);this.log("checking client timeout");let tid,timeoutHit=!1;if(this.options.connectionTimeoutMillis)tid=setTimeout(()=>{if(client.connection)this.log("ending client due to timeout"),timeoutHit=!0,client.connection.stream.destroy();else if(!client.isConnected())this.log("ending client due to timeout"),timeoutHit=!0,client.end()},this.options.connectionTimeoutMillis);this.log("connecting new client"),client.connect((err)=>{if(tid)clearTimeout(tid);if(client.on("error",idleListener),err){if(this.log("client failed to connect",err),this._clients=this._clients.filter((c)=>c!==client),timeoutHit)err=Error("Connection terminated due to connection timeout",{cause:err});if(this._pulseQueue(),!pendingItem.timedOut)pendingItem.callback(err,void 0,NOOP)}else{if(this.log("new client connected"),this.options.onConnect){this._promiseTry(()=>this.options.onConnect(client)).then(()=>{this._afterConnect(client,pendingItem,idleListener)},(hookErr)=>{this._clients=this._clients.filter((c)=>c!==client),client.end(()=>{if(this._pulseQueue(),!pendingItem.timedOut)pendingItem.callback(hookErr,void 0,NOOP)})});return}return this._afterConnect(client,pendingItem,idleListener)}})}_afterConnect(client,pendingItem,idleListener){if(this.options.maxLifetimeSeconds!==0){let maxLifetimeTimeout=setTimeout(()=>{if(this.log("ending client due to expired lifetime"),this._expired.add(client),this._idle.findIndex((idleItem)=>idleItem.client===client)!==-1)this._acquireClient(client,new PendingItem((err,client2,clientRelease)=>clientRelease()),idleListener,!1)},this.options.maxLifetimeSeconds*1000);maxLifetimeTimeout.unref(),client.once("end",()=>clearTimeout(maxLifetimeTimeout))}return this._acquireClient(client,pendingItem,idleListener,!0)}_acquireClient(client,pendingItem,idleListener,isNew){if(isNew)this.emit("connect",client);if(this.emit("acquire",client),client.release=this._releaseOnce(client,idleListener),client.removeListener("error",idleListener),!pendingItem.timedOut)if(isNew&&this.options.verify)this.options.verify(client,(err)=>{if(err)return client.release(err),pendingItem.callback(err,void 0,NOOP);pendingItem.callback(void 0,client,client.release)});else pendingItem.callback(void 0,client,client.release);else if(isNew&&this.options.verify)this.options.verify(client,client.release);else client.release()}_releaseOnce(client,idleListener){let released=!1;return(err)=>{if(released)throwOnDoubleRelease();released=!0,this._release(client,idleListener,err)}}_release(client,idleListener,err){if(client.on("error",idleListener),client._poolUseCount=(client._poolUseCount||0)+1,this.emit("release",err,client),err||this.ending||!client._queryable||client._ending||client._poolUseCount>=this.options.maxUses){if(client._poolUseCount>=this.options.maxUses)this.log("remove expended client");return this._remove(client,this._pulseQueue.bind(this))}if(this._expired.has(client))return this.log("remove expired client"),this._expired.delete(client),this._remove(client,this._pulseQueue.bind(this));let tid;if(this.options.idleTimeoutMillis&&this._isAboveMin()){if(tid=setTimeout(()=>{if(this._isAboveMin())this.log("remove idle client"),this._remove(client,this._pulseQueue.bind(this))},this.options.idleTimeoutMillis),this.options.allowExitOnIdle)tid.unref()}if(this.options.allowExitOnIdle)client.unref();this._idle.push(new IdleItem(client,idleListener,tid)),this._pulseQueue()}query(text,values2,cb){if(typeof text==="function"){let response2=promisify(this.Promise,text);return setImmediate(function(){return response2.callback(Error("Passing a function as the first parameter to pool.query is not supported"))}),response2.result}if(typeof values2==="function")cb=values2,values2=void 0;let response=promisify(this.Promise,cb);return cb=response.callback,this.connect((err,client)=>{if(err)return cb(err);let clientReleased=!1,onError=(err2)=>{if(clientReleased)return;clientReleased=!0,client.release(err2),cb(err2)};client.once("error",onError),this.log("dispatching query");try{client.query(text,values2,(err2,res)=>{if(this.log("query dispatched"),client.removeListener("error",onError),clientReleased)return;if(clientReleased=!0,client.release(err2),err2)return cb(err2);return cb(void 0,res)})}catch(err2){return client.release(err2),cb(err2)}}),response.result}end(cb){if(this.log("ending"),this.ending){let err=Error("Called end on pool more than once");return cb?cb(err):this.Promise.reject(err)}this.ending=!0;let promised=promisify(this.Promise,cb);return this._endCallback=promised.callback,this._pulseQueue(),promised.result}get waitingCount(){return this._pendingQueue.length}get idleCount(){return this._idle.length}get expiredCount(){return this._clients.reduce((acc,client)=>acc+(this._expired.has(client)?1:0),0)}get totalCount(){return this._clients.length}}module.exports=Pool}),require_query2=__commonJS2((exports,module)=>{var EventEmitter=__require2("events").EventEmitter,util=__require2("util"),utils2=require_utils2(),NativeQuery=module.exports=function(config,values2,callback){EventEmitter.call(this),config=utils2.normalizeQueryConfig(config,values2,callback),this.text=config.text,this.values=config.values,this.name=config.name,this.queryMode=config.queryMode,this.callback=config.callback,this.state="new",this._arrayMode=config.rowMode==="array",this._emitRowEvents=!1,this.on("newListener",function(event){if(event==="row")this._emitRowEvents=!0}.bind(this))};util.inherits(NativeQuery,EventEmitter);var errorFieldMap={sqlState:"code",statementPosition:"position",messagePrimary:"message",context:"where",schemaName:"schema",tableName:"table",columnName:"column",dataTypeName:"dataType",constraintName:"constraint",sourceFile:"file",sourceLine:"line",sourceFunction:"routine"};NativeQuery.prototype.handleError=function(err){let fields=this.native.pq.resultErrorFields();if(fields)for(let key in fields){let normalizedFieldName=errorFieldMap[key]||key;err[normalizedFieldName]=fields[key]}if(this.callback)this.callback(err);else this.emit("error",err);this.state="error"},NativeQuery.prototype.then=function(onSuccess,onFailure){return this._getPromise().then(onSuccess,onFailure)},NativeQuery.prototype.catch=function(callback){return this._getPromise().catch(callback)},NativeQuery.prototype._getPromise=function(){if(this._promise)return this._promise;return this._promise=new Promise(function(resolve6,reject){this._once("end",resolve6),this._once("error",reject)}.bind(this)),this._promise},NativeQuery.prototype.submit=function(client){this.state="running";let self2=this;this.native=client.native,client.native.arrayMode=this._arrayMode;let after=function(err,rows,results){if(client.native.arrayMode=!1,setImmediate(function(){self2.emit("_done")}),err)return self2.handleError(err);if(self2._emitRowEvents)if(results.length>1)rows.forEach((rowOfRows,i)=>{rowOfRows.forEach((row)=>{self2.emit("row",row,results[i])})});else rows.forEach(function(row){self2.emit("row",row,results)});if(self2.state="end",self2.emit("end",results),self2.callback)self2.callback(null,results)};if(process.domain)after=process.domain.bind(after);if(this.name){if(this.name.length>63)console.error("Warning! Postgres only supports 63 characters for query names."),console.error("You supplied %s (%s)",this.name,this.name.length),console.error("This can cause conflicts and silent errors executing queries");let values2=(this.values||[]).map(utils2.prepareValue);if(client.namedQueries[this.name]){if(this.text&&client.namedQueries[this.name]!==this.text){let err=Error(`Prepared statements must be unique - '${this.name}' was used for a different statement`);return after(err)}return client.native.execute(this.name,values2,after)}return client.native.prepare(this.name,this.text,values2.length,function(err){if(err)return after(err);return client.namedQueries[self2.name]=self2.text,self2.native.execute(self2.name,values2,after)})}else if(this.values){if(!Array.isArray(this.values)){let err=Error("Query values must be an array");return after(err)}let vals=this.values.map(utils2.prepareValue);client.native.query(this.text,vals,after)}else if(this.queryMode==="extended")client.native.query(this.text,[],after);else client.native.query(this.text,after)}}),require_client2=__commonJS2((exports,module)=>{var nodeUtils=__require2("util"),Native;try{Native=(()=>{throw Error("Cannot require module pg-native")})()}catch(e){throw e}var TypeOverrides=require_type_overrides(),EventEmitter=__require2("events").EventEmitter,util=__require2("util"),ConnectionParameters=require_connection_parameters(),NativeQuery=require_query2(),queryQueueLengthDeprecationNotice=nodeUtils.deprecate(()=>{},"Calling client.query() when the client is already executing a query is deprecated and will be removed in pg@9.0. Use async/await or an external async flow control mechanism instead."),Client2=module.exports=function(config){EventEmitter.call(this),config=config||{},this._Promise=config.Promise||global.Promise,this._types=new TypeOverrides(config.types),this.native=new Native({types:this._types}),this._queryQueue=[],this._ending=!1,this._connecting=!1,this._connected=!1,this._queryable=!0;let cp=this.connectionParameters=new ConnectionParameters(config);if(config.nativeConnectionString)cp.nativeConnectionString=config.nativeConnectionString;this.user=cp.user,Object.defineProperty(this,"password",{configurable:!0,enumerable:!1,writable:!0,value:cp.password}),this.database=cp.database,this.host=cp.host,this.port=cp.port,this.namedQueries={}};Client2.Query=NativeQuery,util.inherits(Client2,EventEmitter),Client2.prototype._errorAllQueries=function(err){let enqueueError=(query)=>{process.nextTick(()=>{query.native=this.native,query.handleError(err)})};if(this._hasActiveQuery())enqueueError(this._activeQuery),this._activeQuery=null;this._queryQueue.forEach(enqueueError),this._queryQueue.length=0},Client2.prototype._connect=function(cb){let self2=this;if(this._connecting){process.nextTick(()=>cb(Error("Client has already been connected. You cannot reuse a client.")));return}this._connecting=!0,this.connectionParameters.getLibpqConnectionString(function(err,conString){if(self2.connectionParameters.nativeConnectionString)conString=self2.connectionParameters.nativeConnectionString;if(err)return cb(err);self2.native.connect(conString,function(err2){if(err2)return self2.native.end(),cb(err2);self2._connected=!0,self2.native.on("error",function(err3){self2._queryable=!1,self2._errorAllQueries(err3),self2.emit("error",err3)}),self2.native.on("notification",function(msg){self2.emit("notification",{channel:msg.relname,payload:msg.extra})}),self2.emit("connect"),self2._pulseQueryQueue(!0),cb(null,this)})})},Client2.prototype.connect=function(callback){if(callback){this._connect(callback);return}return new this._Promise((resolve6,reject)=>{this._connect((error2)=>{if(error2)reject(error2);else resolve6(this)})})},Client2.prototype.query=function(config,values2,callback){let query,result,readTimeout,readTimeoutTimer,queryCallback;if(config===null||config===void 0)throw TypeError("Client was passed a null or undefined query");else if(typeof config.submit==="function"){if(readTimeout=config.query_timeout||this.connectionParameters.query_timeout,result=query=config,typeof values2==="function")config.callback=values2}else if(readTimeout=config.query_timeout||this.connectionParameters.query_timeout,query=new NativeQuery(config,values2,callback),!query.callback){let resolveOut,rejectOut;result=new this._Promise((resolve6,reject)=>{resolveOut=resolve6,rejectOut=reject}).catch((err)=>{throw Error.captureStackTrace(err),err}),query.callback=(err,res)=>err?rejectOut(err):resolveOut(res)}if(readTimeout)queryCallback=query.callback||(()=>{}),readTimeoutTimer=setTimeout(()=>{let error2=Error("Query read timeout");process.nextTick(()=>{query.handleError(error2,this.connection)}),queryCallback(error2),query.callback=()=>{};let index=this._queryQueue.indexOf(query);if(index>-1)this._queryQueue.splice(index,1);this._pulseQueryQueue()},readTimeout),query.callback=(err,res)=>{clearTimeout(readTimeoutTimer),queryCallback(err,res)};if(!this._queryable)return query.native=this.native,process.nextTick(()=>{query.handleError(Error("Client has encountered a connection error and is not queryable"))}),result;if(this._ending)return query.native=this.native,process.nextTick(()=>{query.handleError(Error("Client was closed and is not queryable"))}),result;if(this._queryQueue.length>0)queryQueueLengthDeprecationNotice();return this._queryQueue.push(query),this._pulseQueryQueue(),result},Client2.prototype.end=function(cb){let self2=this;if(this._ending=!0,!this._connected)this.once("connect",this.end.bind(this,cb));let result;if(!cb)result=new this._Promise(function(resolve6,reject){cb=(err)=>err?reject(err):resolve6()});return this.native.end(function(){self2._connected=!1,self2._errorAllQueries(Error("Connection terminated")),process.nextTick(()=>{if(self2.emit("end"),cb)cb()})}),result},Client2.prototype._hasActiveQuery=function(){return this._activeQuery&&this._activeQuery.state!=="error"&&this._activeQuery.state!=="end"},Client2.prototype._pulseQueryQueue=function(initialConnection){if(!this._connected)return;if(this._hasActiveQuery())return;let query=this._queryQueue.shift();if(!query){if(!initialConnection)this.emit("drain");return}this._activeQuery=query,query.submit(this);let self2=this;query.once("_done",function(){self2._pulseQueryQueue()})},Client2.prototype.cancel=function(query){if(this._activeQuery===query)this.native.cancel(function(){});else if(this._queryQueue.indexOf(query)!==-1)this._queryQueue.splice(this._queryQueue.indexOf(query),1)},Client2.prototype.ref=function(){},Client2.prototype.unref=function(){},Client2.prototype.setTypeParser=function(oid,format,parseFn){return this._types.setTypeParser(oid,format,parseFn)},Client2.prototype.getTypeParser=function(oid,format){return this._types.getTypeParser(oid,format)},Client2.prototype.isConnected=function(){return this._connected}}),require_lib2=__commonJS2((exports,module)=>{var Client2=require_client(),defaults2=require_defaults2(),Connection=require_connection(),Result=require_result(),utils2=require_utils2(),Pool=require_pg_pool(),TypeOverrides=require_type_overrides(),{DatabaseError}=require_dist(),{escapeIdentifier,escapeLiteral}=require_utils2(),poolFactory=(Client22)=>{return class extends Pool{constructor(options2){super(options2,Client22)}}},PG=function(clientConstructor2){this.defaults=defaults2,this.Client=clientConstructor2,this.Query=this.Client.Query,this.Pool=poolFactory(this.Client),this._pools=[],this.Connection=Connection,this.types=require_pg_types(),this.DatabaseError=DatabaseError,this.TypeOverrides=TypeOverrides,this.escapeIdentifier=escapeIdentifier,this.escapeLiteral=escapeLiteral,this.Result=Result,this.utils=utils2},clientConstructor=Client2,forceNative=!1;try{forceNative=!!process.env.NODE_PG_FORCE_NATIVE}catch{}if(forceNative)clientConstructor=require_client2();module.exports=new PG(clientConstructor),Object.defineProperty(module.exports,"native",{configurable:!0,enumerable:!1,get(){let native=null;try{native=new PG(require_client2())}catch(err){if(err.code!=="MODULE_NOT_FOUND")throw err}return Object.defineProperty(module.exports,"native",{value:native}),native}})}),init_esm=__esm2(()=>{import_lib=__toESM2(require_lib2(),1),Client2=import_lib.default.Client,Pool=import_lib.default.Pool,Connection=import_lib.default.Connection,types3=import_lib.default.types,Query=import_lib.default.Query,DatabaseError=import_lib.default.DatabaseError,escapeIdentifier=import_lib.default.escapeIdentifier,escapeLiteral=import_lib.default.escapeLiteral,Result=import_lib.default.Result,TypeOverrides=import_lib.default.TypeOverrides,defaults2=import_lib.default.defaults,esm_default=import_lib.default});init_adapter=__esm2(()=>{init_esm()}),init_util=__esm2(()=>{(function(util2){util2.assertEqual=(_)=>{};function assertIs(_arg){}util2.assertIs=assertIs;function assertNever3(_x){throw Error()}util2.assertNever=assertNever3,util2.arrayToEnum=(items)=>{let obj={};for(let item of items)obj[item]=item;return obj},util2.getValidEnumValues=(obj)=>{let validKeys=util2.objectKeys(obj).filter((k)=>typeof obj[obj[k]]!=="number"),filtered={};for(let k of validKeys)filtered[k]=obj[k];return util2.objectValues(filtered)},util2.objectValues=(obj)=>{return util2.objectKeys(obj).map(function(e){return obj[e]})},util2.objectKeys=typeof Object.keys==="function"?(obj)=>Object.keys(obj):(object)=>{let keys=[];for(let key in object)if(Object.prototype.hasOwnProperty.call(object,key))keys.push(key);return keys},util2.find=(arr,checker)=>{for(let item of arr)if(checker(item))return item;return},util2.isInteger=typeof Number.isInteger==="function"?(val)=>Number.isInteger(val):(val)=>typeof val==="number"&&Number.isFinite(val)&&Math.floor(val)===val;function joinValues(array,separator=" | "){return array.map((val)=>typeof val==="string"?`'${val}'`:val).join(separator)}util2.joinValues=joinValues,util2.jsonStringifyReplacer=(_,value)=>{if(typeof value==="bigint")return value.toString();return value}})(util||(util={})),function(objectUtil2){objectUtil2.mergeShapes=(first,second)=>{return{...first,...second}}}(objectUtil||(objectUtil={})),ZodParsedType=util.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"])}),init_ZodError=__esm2(()=>{init_util(),ZodIssueCode=util.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),ZodError=class ZodError2 extends Error{get errors(){return this.issues}constructor(issues){super();this.issues=[],this.addIssue=(sub)=>{this.issues=[...this.issues,sub]},this.addIssues=(subs=[])=>{this.issues=[...this.issues,...subs]};let actualProto=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,actualProto);else this.__proto__=actualProto;this.name="ZodError",this.issues=issues}format(_mapper){let mapper=_mapper||function(issue){return issue.message},fieldErrors={_errors:[]},processError=(error2)=>{for(let issue of error2.issues)if(issue.code==="invalid_union")issue.unionErrors.map(processError);else if(issue.code==="invalid_return_type")processError(issue.returnTypeError);else if(issue.code==="invalid_arguments")processError(issue.argumentsError);else if(issue.path.length===0)fieldErrors._errors.push(mapper(issue));else{let curr=fieldErrors,i=0;while(i<issue.path.length){let el=issue.path[i];if(i!==issue.path.length-1)curr[el]=curr[el]||{_errors:[]};else curr[el]=curr[el]||{_errors:[]},curr[el]._errors.push(mapper(issue));curr=curr[el],i++}}};return processError(this),fieldErrors}static assert(value){if(!(value instanceof ZodError2))throw Error(`Not a ZodError: ${value}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,util.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(mapper=(issue)=>issue.message){let fieldErrors={},formErrors=[];for(let sub of this.issues)if(sub.path.length>0){let firstEl=sub.path[0];fieldErrors[firstEl]=fieldErrors[firstEl]||[],fieldErrors[firstEl].push(mapper(sub))}else formErrors.push(mapper(sub));return{formErrors,fieldErrors}}get formErrors(){return this.flatten()}},ZodError.create=(issues)=>{return new ZodError(issues)}}),init_en=__esm2(()=>{init_ZodError(),init_util(),en_default=errorMap});init_errors2=__esm2(()=>{init_en(),overrideErrorMap=en_default});init_parseUtil=__esm2(()=>{init_errors2(),init_en(),EMPTY_PATH=[],INVALID=Object.freeze({status:"aborted"})}),init_errorUtil=__esm2(()=>{(function(errorUtil2){errorUtil2.errToObj=(message)=>typeof message==="string"?{message}:message||{},errorUtil2.toString=(message)=>typeof message==="string"?message:message?.message})(errorUtil||(errorUtil={}))});init_types3=__esm2(()=>{init_ZodError(),init_errors2(),init_errorUtil(),init_parseUtil(),init_util(),cuidRegex=/^c[^\s-]{8,}$/i,cuid2Regex=/^[0-9a-z]+$/,ulidRegex=/^[0-9A-HJKMNP-TV-Z]{26}$/i,uuidRegex=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,nanoidRegex=/^[a-z0-9_-]{21}$/i,jwtRegex=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,durationRegex=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,emailRegex=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,ipv4Regex=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4CidrRegex=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6Regex=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,ipv6CidrRegex=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64Regex=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64urlRegex=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,dateRegex=new RegExp(`^${dateRegexSource}$`),ZodString=class ZodString2 extends ZodType{_parse(input){if(this._def.coerce)input.data=String(input.data);if(this._getType(input)!==ZodParsedType.string){let ctx2=this._getOrReturnCtx(input);return addIssueToContext(ctx2,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.string,received:ctx2.parsedType}),INVALID}let status=new ParseStatus,ctx=void 0;for(let check of this._def.checks)if(check.kind==="min"){if(input.data.length<check.value)ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{code:ZodIssueCode.too_small,minimum:check.value,type:"string",inclusive:!0,exact:!1,message:check.message}),status.dirty()}else if(check.kind==="max"){if(input.data.length>check.value)ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{code:ZodIssueCode.too_big,maximum:check.value,type:"string",inclusive:!0,exact:!1,message:check.message}),status.dirty()}else if(check.kind==="length"){let tooBig=input.data.length>check.value,tooSmall=input.data.length<check.value;if(tooBig||tooSmall){if(ctx=this._getOrReturnCtx(input,ctx),tooBig)addIssueToContext(ctx,{code:ZodIssueCode.too_big,maximum:check.value,type:"string",inclusive:!0,exact:!0,message:check.message});else if(tooSmall)addIssueToContext(ctx,{code:ZodIssueCode.too_small,minimum:check.value,type:"string",inclusive:!0,exact:!0,message:check.message});status.dirty()}}else if(check.kind==="email"){if(!emailRegex.test(input.data))ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{validation:"email",code:ZodIssueCode.invalid_string,message:check.message}),status.dirty()}else if(check.kind==="emoji"){if(!emojiRegex)emojiRegex=new RegExp(_emojiRegex,"u");if(!emojiRegex.test(input.data))ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{validation:"emoji",code:ZodIssueCode.invalid_string,message:check.message}),status.dirty()}else if(check.kind==="uuid"){if(!uuidRegex.test(input.data))ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{validation:"uuid",code:ZodIssueCode.invalid_string,message:check.message}),status.dirty()}else if(check.kind==="nanoid"){if(!nanoidRegex.test(input.data))ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{validation:"nanoid",code:ZodIssueCode.invalid_string,message:check.message}),status.dirty()}else if(check.kind==="cuid"){if(!cuidRegex.test(input.data))ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{validation:"cuid",code:ZodIssueCode.invalid_string,message:check.message}),status.dirty()}else if(check.kind==="cuid2"){if(!cuid2Regex.test(input.data))ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{validation:"cuid2",code:ZodIssueCode.invalid_string,message:check.message}),status.dirty()}else if(check.kind==="ulid"){if(!ulidRegex.test(input.data))ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{validation:"ulid",code:ZodIssueCode.invalid_string,message:check.message}),status.dirty()}else if(check.kind==="url")try{new URL(input.data)}catch{ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{validation:"url",code:ZodIssueCode.invalid_string,message:check.message}),status.dirty()}else if(check.kind==="regex"){if(check.regex.lastIndex=0,!check.regex.test(input.data))ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{validation:"regex",code:ZodIssueCode.invalid_string,message:check.message}),status.dirty()}else if(check.kind==="trim")input.data=input.data.trim();else if(check.kind==="includes"){if(!input.data.includes(check.value,check.position))ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{code:ZodIssueCode.invalid_string,validation:{includes:check.value,position:check.position},message:check.message}),status.dirty()}else if(check.kind==="toLowerCase")input.data=input.data.toLowerCase();else if(check.kind==="toUpperCase")input.data=input.data.toUpperCase();else if(check.kind==="startsWith"){if(!input.data.startsWith(check.value))ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{code:ZodIssueCode.invalid_string,validation:{startsWith:check.value},message:check.message}),status.dirty()}else if(check.kind==="endsWith"){if(!input.data.endsWith(check.value))ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{code:ZodIssueCode.invalid_string,validation:{endsWith:check.value},message:check.message}),status.dirty()}else if(check.kind==="datetime"){if(!datetimeRegex(check).test(input.data))ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{code:ZodIssueCode.invalid_string,validation:"datetime",message:check.message}),status.dirty()}else if(check.kind==="date"){if(!dateRegex.test(input.data))ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{code:ZodIssueCode.invalid_string,validation:"date",message:check.message}),status.dirty()}else if(check.kind==="time"){if(!timeRegex(check).test(input.data))ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{code:ZodIssueCode.invalid_string,validation:"time",message:check.message}),status.dirty()}else if(check.kind==="duration"){if(!durationRegex.test(input.data))ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{validation:"duration",code:ZodIssueCode.invalid_string,message:check.message}),status.dirty()}else if(check.kind==="ip"){if(!isValidIP(input.data,check.version))ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{validation:"ip",code:ZodIssueCode.invalid_string,message:check.message}),status.dirty()}else if(check.kind==="jwt"){if(!isValidJWT(input.data,check.alg))ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{validation:"jwt",code:ZodIssueCode.invalid_string,message:check.message}),status.dirty()}else if(check.kind==="cidr"){if(!isValidCidr(input.data,check.version))ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{validation:"cidr",code:ZodIssueCode.invalid_string,message:check.message}),status.dirty()}else if(check.kind==="base64"){if(!base64Regex.test(input.data))ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{validation:"base64",code:ZodIssueCode.invalid_string,message:check.message}),status.dirty()}else if(check.kind==="base64url"){if(!base64urlRegex.test(input.data))ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{validation:"base64url",code:ZodIssueCode.invalid_string,message:check.message}),status.dirty()}else util.assertNever(check);return{status:status.value,value:input.data}}_regex(regex,validation,message){return this.refinement((data)=>regex.test(data),{validation,code:ZodIssueCode.invalid_string,...errorUtil.errToObj(message)})}_addCheck(check){return new ZodString2({...this._def,checks:[...this._def.checks,check]})}email(message){return this._addCheck({kind:"email",...errorUtil.errToObj(message)})}url(message){return this._addCheck({kind:"url",...errorUtil.errToObj(message)})}emoji(message){return this._addCheck({kind:"emoji",...errorUtil.errToObj(message)})}uuid(message){return this._addCheck({kind:"uuid",...errorUtil.errToObj(message)})}nanoid(message){return this._addCheck({kind:"nanoid",...errorUtil.errToObj(message)})}cuid(message){return this._addCheck({kind:"cuid",...errorUtil.errToObj(message)})}cuid2(message){return this._addCheck({kind:"cuid2",...errorUtil.errToObj(message)})}ulid(message){return this._addCheck({kind:"ulid",...errorUtil.errToObj(message)})}base64(message){return this._addCheck({kind:"base64",...errorUtil.errToObj(message)})}base64url(message){return this._addCheck({kind:"base64url",...errorUtil.errToObj(message)})}jwt(options2){return this._addCheck({kind:"jwt",...errorUtil.errToObj(options2)})}ip(options2){return this._addCheck({kind:"ip",...errorUtil.errToObj(options2)})}cidr(options2){return this._addCheck({kind:"cidr",...errorUtil.errToObj(options2)})}datetime(options2){if(typeof options2==="string")return this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:options2});return this._addCheck({kind:"datetime",precision:typeof options2?.precision>"u"?null:options2?.precision,offset:options2?.offset??!1,local:options2?.local??!1,...errorUtil.errToObj(options2?.message)})}date(message){return this._addCheck({kind:"date",message})}time(options2){if(typeof options2==="string")return this._addCheck({kind:"time",precision:null,message:options2});return this._addCheck({kind:"time",precision:typeof options2?.precision>"u"?null:options2?.precision,...errorUtil.errToObj(options2?.message)})}duration(message){return this._addCheck({kind:"duration",...errorUtil.errToObj(message)})}regex(regex,message){return this._addCheck({kind:"regex",regex,...errorUtil.errToObj(message)})}includes(value,options2){return this._addCheck({kind:"includes",value,position:options2?.position,...errorUtil.errToObj(options2?.message)})}startsWith(value,message){return this._addCheck({kind:"startsWith",value,...errorUtil.errToObj(message)})}endsWith(value,message){return this._addCheck({kind:"endsWith",value,...errorUtil.errToObj(message)})}min(minLength,message){return this._addCheck({kind:"min",value:minLength,...errorUtil.errToObj(message)})}max(maxLength,message){return this._addCheck({kind:"max",value:maxLength,...errorUtil.errToObj(message)})}length(len,message){return this._addCheck({kind:"length",value:len,...errorUtil.errToObj(message)})}nonempty(message){return this.min(1,errorUtil.errToObj(message))}trim(){return new ZodString2({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new ZodString2({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new ZodString2({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find((ch)=>ch.kind==="datetime")}get isDate(){return!!this._def.checks.find((ch)=>ch.kind==="date")}get isTime(){return!!this._def.checks.find((ch)=>ch.kind==="time")}get isDuration(){return!!this._def.checks.find((ch)=>ch.kind==="duration")}get isEmail(){return!!this._def.checks.find((ch)=>ch.kind==="email")}get isURL(){return!!this._def.checks.find((ch)=>ch.kind==="url")}get isEmoji(){return!!this._def.checks.find((ch)=>ch.kind==="emoji")}get isUUID(){return!!this._def.checks.find((ch)=>ch.kind==="uuid")}get isNANOID(){return!!this._def.checks.find((ch)=>ch.kind==="nanoid")}get isCUID(){return!!this._def.checks.find((ch)=>ch.kind==="cuid")}get isCUID2(){return!!this._def.checks.find((ch)=>ch.kind==="cuid2")}get isULID(){return!!this._def.checks.find((ch)=>ch.kind==="ulid")}get isIP(){return!!this._def.checks.find((ch)=>ch.kind==="ip")}get isCIDR(){return!!this._def.checks.find((ch)=>ch.kind==="cidr")}get isBase64(){return!!this._def.checks.find((ch)=>ch.kind==="base64")}get isBase64url(){return!!this._def.checks.find((ch)=>ch.kind==="base64url")}get minLength(){let min=null;for(let ch of this._def.checks)if(ch.kind==="min"){if(min===null||ch.value>min)min=ch.value}return min}get maxLength(){let max=null;for(let ch of this._def.checks)if(ch.kind==="max"){if(max===null||ch.value<max)max=ch.value}return max}},ZodString.create=(params)=>{return new ZodString({checks:[],typeName:ZodFirstPartyTypeKind.ZodString,coerce:params?.coerce??!1,...processCreateParams(params)})},ZodNumber=class ZodNumber2 extends ZodType{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(input){if(this._def.coerce)input.data=Number(input.data);if(this._getType(input)!==ZodParsedType.number){let ctx2=this._getOrReturnCtx(input);return addIssueToContext(ctx2,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.number,received:ctx2.parsedType}),INVALID}let ctx=void 0,status=new ParseStatus;for(let check of this._def.checks)if(check.kind==="int"){if(!util.isInteger(input.data))ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:"integer",received:"float",message:check.message}),status.dirty()}else if(check.kind==="min"){if(check.inclusive?input.data<check.value:input.data<=check.value)ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{code:ZodIssueCode.too_small,minimum:check.value,type:"number",inclusive:check.inclusive,exact:!1,message:check.message}),status.dirty()}else if(check.kind==="max"){if(check.inclusive?input.data>check.value:input.data>=check.value)ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{code:ZodIssueCode.too_big,maximum:check.value,type:"number",inclusive:check.inclusive,exact:!1,message:check.message}),status.dirty()}else if(check.kind==="multipleOf"){if(floatSafeRemainder(input.data,check.value)!==0)ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{code:ZodIssueCode.not_multiple_of,multipleOf:check.value,message:check.message}),status.dirty()}else if(check.kind==="finite"){if(!Number.isFinite(input.data))ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{code:ZodIssueCode.not_finite,message:check.message}),status.dirty()}else util.assertNever(check);return{status:status.value,value:input.data}}gte(value,message){return this.setLimit("min",value,!0,errorUtil.toString(message))}gt(value,message){return this.setLimit("min",value,!1,errorUtil.toString(message))}lte(value,message){return this.setLimit("max",value,!0,errorUtil.toString(message))}lt(value,message){return this.setLimit("max",value,!1,errorUtil.toString(message))}setLimit(kind,value,inclusive,message){return new ZodNumber2({...this._def,checks:[...this._def.checks,{kind,value,inclusive,message:errorUtil.toString(message)}]})}_addCheck(check){return new ZodNumber2({...this._def,checks:[...this._def.checks,check]})}int(message){return this._addCheck({kind:"int",message:errorUtil.toString(message)})}positive(message){return this._addCheck({kind:"min",value:0,inclusive:!1,message:errorUtil.toString(message)})}negative(message){return this._addCheck({kind:"max",value:0,inclusive:!1,message:errorUtil.toString(message)})}nonpositive(message){return this._addCheck({kind:"max",value:0,inclusive:!0,message:errorUtil.toString(message)})}nonnegative(message){return this._addCheck({kind:"min",value:0,inclusive:!0,message:errorUtil.toString(message)})}multipleOf(value,message){return this._addCheck({kind:"multipleOf",value,message:errorUtil.toString(message)})}finite(message){return this._addCheck({kind:"finite",message:errorUtil.toString(message)})}safe(message){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:errorUtil.toString(message)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:errorUtil.toString(message)})}get minValue(){let min=null;for(let ch of this._def.checks)if(ch.kind==="min"){if(min===null||ch.value>min)min=ch.value}return min}get maxValue(){let max=null;for(let ch of this._def.checks)if(ch.kind==="max"){if(max===null||ch.value<max)max=ch.value}return max}get isInt(){return!!this._def.checks.find((ch)=>ch.kind==="int"||ch.kind==="multipleOf"&&util.isInteger(ch.value))}get isFinite(){let max=null,min=null;for(let ch of this._def.checks)if(ch.kind==="finite"||ch.kind==="int"||ch.kind==="multipleOf")return!0;else if(ch.kind==="min"){if(min===null||ch.value>min)min=ch.value}else if(ch.kind==="max"){if(max===null||ch.value<max)max=ch.value}return Number.isFinite(min)&&Number.isFinite(max)}},ZodNumber.create=(params)=>{return new ZodNumber({checks:[],typeName:ZodFirstPartyTypeKind.ZodNumber,coerce:params?.coerce||!1,...processCreateParams(params)})},ZodBigInt=class ZodBigInt2 extends ZodType{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse(input){if(this._def.coerce)try{input.data=BigInt(input.data)}catch{return this._getInvalidInput(input)}if(this._getType(input)!==ZodParsedType.bigint)return this._getInvalidInput(input);let ctx=void 0,status=new ParseStatus;for(let check of this._def.checks)if(check.kind==="min"){if(check.inclusive?input.data<check.value:input.data<=check.value)ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{code:ZodIssueCode.too_small,type:"bigint",minimum:check.value,inclusive:check.inclusive,message:check.message}),status.dirty()}else if(check.kind==="max"){if(check.inclusive?input.data>check.value:input.data>=check.value)ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{code:ZodIssueCode.too_big,type:"bigint",maximum:check.value,inclusive:check.inclusive,message:check.message}),status.dirty()}else if(check.kind==="multipleOf"){if(input.data%check.value!==BigInt(0))ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{code:ZodIssueCode.not_multiple_of,multipleOf:check.value,message:check.message}),status.dirty()}else util.assertNever(check);return{status:status.value,value:input.data}}_getInvalidInput(input){let ctx=this._getOrReturnCtx(input);return addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.bigint,received:ctx.parsedType}),INVALID}gte(value,message){return this.setLimit("min",value,!0,errorUtil.toString(message))}gt(value,message){return this.setLimit("min",value,!1,errorUtil.toString(message))}lte(value,message){return this.setLimit("max",value,!0,errorUtil.toString(message))}lt(value,message){return this.setLimit("max",value,!1,errorUtil.toString(message))}setLimit(kind,value,inclusive,message){return new ZodBigInt2({...this._def,checks:[...this._def.checks,{kind,value,inclusive,message:errorUtil.toString(message)}]})}_addCheck(check){return new ZodBigInt2({...this._def,checks:[...this._def.checks,check]})}positive(message){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:errorUtil.toString(message)})}negative(message){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:errorUtil.toString(message)})}nonpositive(message){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:errorUtil.toString(message)})}nonnegative(message){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:errorUtil.toString(message)})}multipleOf(value,message){return this._addCheck({kind:"multipleOf",value,message:errorUtil.toString(message)})}get minValue(){let min=null;for(let ch of this._def.checks)if(ch.kind==="min"){if(min===null||ch.value>min)min=ch.value}return min}get maxValue(){let max=null;for(let ch of this._def.checks)if(ch.kind==="max"){if(max===null||ch.value<max)max=ch.value}return max}},ZodBigInt.create=(params)=>{return new ZodBigInt({checks:[],typeName:ZodFirstPartyTypeKind.ZodBigInt,coerce:params?.coerce??!1,...processCreateParams(params)})},ZodBoolean=class extends ZodType{_parse(input){if(this._def.coerce)input.data=Boolean(input.data);if(this._getType(input)!==ZodParsedType.boolean){let ctx=this._getOrReturnCtx(input);return addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.boolean,received:ctx.parsedType}),INVALID}return OK(input.data)}},ZodBoolean.create=(params)=>{return new ZodBoolean({typeName:ZodFirstPartyTypeKind.ZodBoolean,coerce:params?.coerce||!1,...processCreateParams(params)})},ZodDate=class ZodDate2 extends ZodType{_parse(input){if(this._def.coerce)input.data=new Date(input.data);if(this._getType(input)!==ZodParsedType.date){let ctx2=this._getOrReturnCtx(input);return addIssueToContext(ctx2,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.date,received:ctx2.parsedType}),INVALID}if(Number.isNaN(input.data.getTime())){let ctx2=this._getOrReturnCtx(input);return addIssueToContext(ctx2,{code:ZodIssueCode.invalid_date}),INVALID}let status=new ParseStatus,ctx=void 0;for(let check of this._def.checks)if(check.kind==="min"){if(input.data.getTime()<check.value)ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{code:ZodIssueCode.too_small,message:check.message,inclusive:!0,exact:!1,minimum:check.value,type:"date"}),status.dirty()}else if(check.kind==="max"){if(input.data.getTime()>check.value)ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{code:ZodIssueCode.too_big,message:check.message,inclusive:!0,exact:!1,maximum:check.value,type:"date"}),status.dirty()}else util.assertNever(check);return{status:status.value,value:new Date(input.data.getTime())}}_addCheck(check){return new ZodDate2({...this._def,checks:[...this._def.checks,check]})}min(minDate,message){return this._addCheck({kind:"min",value:minDate.getTime(),message:errorUtil.toString(message)})}max(maxDate,message){return this._addCheck({kind:"max",value:maxDate.getTime(),message:errorUtil.toString(message)})}get minDate(){let min=null;for(let ch of this._def.checks)if(ch.kind==="min"){if(min===null||ch.value>min)min=ch.value}return min!=null?new Date(min):null}get maxDate(){let max=null;for(let ch of this._def.checks)if(ch.kind==="max"){if(max===null||ch.value<max)max=ch.value}return max!=null?new Date(max):null}},ZodDate.create=(params)=>{return new ZodDate({checks:[],coerce:params?.coerce||!1,typeName:ZodFirstPartyTypeKind.ZodDate,...processCreateParams(params)})},ZodSymbol=class extends ZodType{_parse(input){if(this._getType(input)!==ZodParsedType.symbol){let ctx=this._getOrReturnCtx(input);return addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.symbol,received:ctx.parsedType}),INVALID}return OK(input.data)}},ZodSymbol.create=(params)=>{return new ZodSymbol({typeName:ZodFirstPartyTypeKind.ZodSymbol,...processCreateParams(params)})},ZodUndefined=class extends ZodType{_parse(input){if(this._getType(input)!==ZodParsedType.undefined){let ctx=this._getOrReturnCtx(input);return addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.undefined,received:ctx.parsedType}),INVALID}return OK(input.data)}},ZodUndefined.create=(params)=>{return new ZodUndefined({typeName:ZodFirstPartyTypeKind.ZodUndefined,...processCreateParams(params)})},ZodNull=class extends ZodType{_parse(input){if(this._getType(input)!==ZodParsedType.null){let ctx=this._getOrReturnCtx(input);return addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.null,received:ctx.parsedType}),INVALID}return OK(input.data)}},ZodNull.create=(params)=>{return new ZodNull({typeName:ZodFirstPartyTypeKind.ZodNull,...processCreateParams(params)})},ZodAny=class extends ZodType{constructor(){super(...arguments);this._any=!0}_parse(input){return OK(input.data)}},ZodAny.create=(params)=>{return new ZodAny({typeName:ZodFirstPartyTypeKind.ZodAny,...processCreateParams(params)})},ZodUnknown=class extends ZodType{constructor(){super(...arguments);this._unknown=!0}_parse(input){return OK(input.data)}},ZodUnknown.create=(params)=>{return new ZodUnknown({typeName:ZodFirstPartyTypeKind.ZodUnknown,...processCreateParams(params)})},ZodNever=class extends ZodType{_parse(input){let ctx=this._getOrReturnCtx(input);return addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.never,received:ctx.parsedType}),INVALID}},ZodNever.create=(params)=>{return new ZodNever({typeName:ZodFirstPartyTypeKind.ZodNever,...processCreateParams(params)})},ZodVoid=class extends ZodType{_parse(input){if(this._getType(input)!==ZodParsedType.undefined){let ctx=this._getOrReturnCtx(input);return addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.void,received:ctx.parsedType}),INVALID}return OK(input.data)}},ZodVoid.create=(params)=>{return new ZodVoid({typeName:ZodFirstPartyTypeKind.ZodVoid,...processCreateParams(params)})},ZodArray=class ZodArray2 extends ZodType{_parse(input){let{ctx,status}=this._processInputParams(input),def=this._def;if(ctx.parsedType!==ZodParsedType.array)return addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.array,received:ctx.parsedType}),INVALID;if(def.exactLength!==null){let tooBig=ctx.data.length>def.exactLength.value,tooSmall=ctx.data.length<def.exactLength.value;if(tooBig||tooSmall)addIssueToContext(ctx,{code:tooBig?ZodIssueCode.too_big:ZodIssueCode.too_small,minimum:tooSmall?def.exactLength.value:void 0,maximum:tooBig?def.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:def.exactLength.message}),status.dirty()}if(def.minLength!==null){if(ctx.data.length<def.minLength.value)addIssueToContext(ctx,{code:ZodIssueCode.too_small,minimum:def.minLength.value,type:"array",inclusive:!0,exact:!1,message:def.minLength.message}),status.dirty()}if(def.maxLength!==null){if(ctx.data.length>def.maxLength.value)addIssueToContext(ctx,{code:ZodIssueCode.too_big,maximum:def.maxLength.value,type:"array",inclusive:!0,exact:!1,message:def.maxLength.message}),status.dirty()}if(ctx.common.async)return Promise.all([...ctx.data].map((item,i)=>{return def.type._parseAsync(new ParseInputLazyPath(ctx,item,ctx.path,i))})).then((result2)=>{return ParseStatus.mergeArray(status,result2)});let result=[...ctx.data].map((item,i)=>{return def.type._parseSync(new ParseInputLazyPath(ctx,item,ctx.path,i))});return ParseStatus.mergeArray(status,result)}get element(){return this._def.type}min(minLength,message){return new ZodArray2({...this._def,minLength:{value:minLength,message:errorUtil.toString(message)}})}max(maxLength,message){return new ZodArray2({...this._def,maxLength:{value:maxLength,message:errorUtil.toString(message)}})}length(len,message){return new ZodArray2({...this._def,exactLength:{value:len,message:errorUtil.toString(message)}})}nonempty(message){return this.min(1,message)}},ZodArray.create=(schema,params)=>{return new ZodArray({type:schema,minLength:null,maxLength:null,exactLength:null,typeName:ZodFirstPartyTypeKind.ZodArray,...processCreateParams(params)})},ZodObject=class ZodObject2 extends ZodType{constructor(){super(...arguments);this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let shape=this._def.shape(),keys=util.objectKeys(shape);return this._cached={shape,keys},this._cached}_parse(input){if(this._getType(input)!==ZodParsedType.object){let ctx2=this._getOrReturnCtx(input);return addIssueToContext(ctx2,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:ctx2.parsedType}),INVALID}let{status,ctx}=this._processInputParams(input),{shape,keys:shapeKeys}=this._getCached(),extraKeys=[];if(!(this._def.catchall instanceof ZodNever&&this._def.unknownKeys==="strip")){for(let key in ctx.data)if(!shapeKeys.includes(key))extraKeys.push(key)}let pairs=[];for(let key of shapeKeys){let keyValidator=shape[key],value=ctx.data[key];pairs.push({key:{status:"valid",value:key},value:keyValidator._parse(new ParseInputLazyPath(ctx,value,ctx.path,key)),alwaysSet:key in ctx.data})}if(this._def.catchall instanceof ZodNever){let unknownKeys=this._def.unknownKeys;if(unknownKeys==="passthrough")for(let key of extraKeys)pairs.push({key:{status:"valid",value:key},value:{status:"valid",value:ctx.data[key]}});else if(unknownKeys==="strict"){if(extraKeys.length>0)addIssueToContext(ctx,{code:ZodIssueCode.unrecognized_keys,keys:extraKeys}),status.dirty()}else if(unknownKeys==="strip");else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let catchall=this._def.catchall;for(let key of extraKeys){let value=ctx.data[key];pairs.push({key:{status:"valid",value:key},value:catchall._parse(new ParseInputLazyPath(ctx,value,ctx.path,key)),alwaysSet:key in ctx.data})}}if(ctx.common.async)return Promise.resolve().then(async()=>{let syncPairs=[];for(let pair of pairs){let key=await pair.key,value=await pair.value;syncPairs.push({key,value,alwaysSet:pair.alwaysSet})}return syncPairs}).then((syncPairs)=>{return ParseStatus.mergeObjectSync(status,syncPairs)});else return ParseStatus.mergeObjectSync(status,pairs)}get shape(){return this._def.shape()}strict(message){return errorUtil.errToObj,new ZodObject2({...this._def,unknownKeys:"strict",...message!==void 0?{errorMap:(issue,ctx)=>{let defaultError=this._def.errorMap?.(issue,ctx).message??ctx.defaultError;if(issue.code==="unrecognized_keys")return{message:errorUtil.errToObj(message).message??defaultError};return{message:defaultError}}}:{}})}strip(){return new ZodObject2({...this._def,unknownKeys:"strip"})}passthrough(){return new ZodObject2({...this._def,unknownKeys:"passthrough"})}extend(augmentation){return new ZodObject2({...this._def,shape:()=>({...this._def.shape(),...augmentation})})}merge(merging){return new ZodObject2({unknownKeys:merging._def.unknownKeys,catchall:merging._def.catchall,shape:()=>({...this._def.shape(),...merging._def.shape()}),typeName:ZodFirstPartyTypeKind.ZodObject})}setKey(key,schema){return this.augment({[key]:schema})}catchall(index){return new ZodObject2({...this._def,catchall:index})}pick(mask){let shape={};for(let key of util.objectKeys(mask))if(mask[key]&&this.shape[key])shape[key]=this.shape[key];return new ZodObject2({...this._def,shape:()=>shape})}omit(mask){let shape={};for(let key of util.objectKeys(this.shape))if(!mask[key])shape[key]=this.shape[key];return new ZodObject2({...this._def,shape:()=>shape})}deepPartial(){return deepPartialify(this)}partial(mask){let newShape={};for(let key of util.objectKeys(this.shape)){let fieldSchema=this.shape[key];if(mask&&!mask[key])newShape[key]=fieldSchema;else newShape[key]=fieldSchema.optional()}return new ZodObject2({...this._def,shape:()=>newShape})}required(mask){let newShape={};for(let key of util.objectKeys(this.shape))if(mask&&!mask[key])newShape[key]=this.shape[key];else{let newField=this.shape[key];while(newField instanceof ZodOptional)newField=newField._def.innerType;newShape[key]=newField}return new ZodObject2({...this._def,shape:()=>newShape})}keyof(){return createZodEnum(util.objectKeys(this.shape))}},ZodObject.create=(shape,params)=>{return new ZodObject({shape:()=>shape,unknownKeys:"strip",catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(params)})},ZodObject.strictCreate=(shape,params)=>{return new ZodObject({shape:()=>shape,unknownKeys:"strict",catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(params)})},ZodObject.lazycreate=(shape,params)=>{return new ZodObject({shape,unknownKeys:"strip",catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(params)})},ZodUnion=class extends ZodType{_parse(input){let{ctx}=this._processInputParams(input),options2=this._def.options;function handleResults(results){for(let result of results)if(result.result.status==="valid")return result.result;for(let result of results)if(result.result.status==="dirty")return ctx.common.issues.push(...result.ctx.common.issues),result.result;let unionErrors=results.map((result)=>new ZodError(result.ctx.common.issues));return addIssueToContext(ctx,{code:ZodIssueCode.invalid_union,unionErrors}),INVALID}if(ctx.common.async)return Promise.all(options2.map(async(option)=>{let childCtx={...ctx,common:{...ctx.common,issues:[]},parent:null};return{result:await option._parseAsync({data:ctx.data,path:ctx.path,parent:childCtx}),ctx:childCtx}})).then(handleResults);else{let dirty=void 0,issues=[];for(let option of options2){let childCtx={...ctx,common:{...ctx.common,issues:[]},parent:null},result=option._parseSync({data:ctx.data,path:ctx.path,parent:childCtx});if(result.status==="valid")return result;else if(result.status==="dirty"&&!dirty)dirty={result,ctx:childCtx};if(childCtx.common.issues.length)issues.push(childCtx.common.issues)}if(dirty)return ctx.common.issues.push(...dirty.ctx.common.issues),dirty.result;let unionErrors=issues.map((issues2)=>new ZodError(issues2));return addIssueToContext(ctx,{code:ZodIssueCode.invalid_union,unionErrors}),INVALID}}get options(){return this._def.options}},ZodUnion.create=(types22,params)=>{return new ZodUnion({options:types22,typeName:ZodFirstPartyTypeKind.ZodUnion,...processCreateParams(params)})},ZodDiscriminatedUnion=class ZodDiscriminatedUnion2 extends ZodType{_parse(input){let{ctx}=this._processInputParams(input);if(ctx.parsedType!==ZodParsedType.object)return addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:ctx.parsedType}),INVALID;let discriminator=this.discriminator,discriminatorValue=ctx.data[discriminator],option=this.optionsMap.get(discriminatorValue);if(!option)return addIssueToContext(ctx,{code:ZodIssueCode.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[discriminator]}),INVALID;if(ctx.common.async)return option._parseAsync({data:ctx.data,path:ctx.path,parent:ctx});else return option._parseSync({data:ctx.data,path:ctx.path,parent:ctx})}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(discriminator,options2,params){let optionsMap=new Map;for(let type of options2){let discriminatorValues=getDiscriminator(type.shape[discriminator]);if(!discriminatorValues.length)throw Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`);for(let value of discriminatorValues){if(optionsMap.has(value))throw Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);optionsMap.set(value,type)}}return new ZodDiscriminatedUnion2({typeName:ZodFirstPartyTypeKind.ZodDiscriminatedUnion,discriminator,options:options2,optionsMap,...processCreateParams(params)})}},ZodIntersection=class extends ZodType{_parse(input){let{status,ctx}=this._processInputParams(input),handleParsed=(parsedLeft,parsedRight)=>{if(isAborted(parsedLeft)||isAborted(parsedRight))return INVALID;let merged=mergeValues(parsedLeft.value,parsedRight.value);if(!merged.valid)return addIssueToContext(ctx,{code:ZodIssueCode.invalid_intersection_types}),INVALID;if(isDirty(parsedLeft)||isDirty(parsedRight))status.dirty();return{status:status.value,value:merged.data}};if(ctx.common.async)return Promise.all([this._def.left._parseAsync({data:ctx.data,path:ctx.path,parent:ctx}),this._def.right._parseAsync({data:ctx.data,path:ctx.path,parent:ctx})]).then(([left,right])=>handleParsed(left,right));else return handleParsed(this._def.left._parseSync({data:ctx.data,path:ctx.path,parent:ctx}),this._def.right._parseSync({data:ctx.data,path:ctx.path,parent:ctx}))}},ZodIntersection.create=(left,right,params)=>{return new ZodIntersection({left,right,typeName:ZodFirstPartyTypeKind.ZodIntersection,...processCreateParams(params)})},ZodTuple=class ZodTuple2 extends ZodType{_parse(input){let{status,ctx}=this._processInputParams(input);if(ctx.parsedType!==ZodParsedType.array)return addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.array,received:ctx.parsedType}),INVALID;if(ctx.data.length<this._def.items.length)return addIssueToContext(ctx,{code:ZodIssueCode.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),INVALID;if(!this._def.rest&&ctx.data.length>this._def.items.length)addIssueToContext(ctx,{code:ZodIssueCode.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),status.dirty();let items=[...ctx.data].map((item,itemIndex)=>{let schema=this._def.items[itemIndex]||this._def.rest;if(!schema)return null;return schema._parse(new ParseInputLazyPath(ctx,item,ctx.path,itemIndex))}).filter((x)=>!!x);if(ctx.common.async)return Promise.all(items).then((results)=>{return ParseStatus.mergeArray(status,results)});else return ParseStatus.mergeArray(status,items)}get items(){return this._def.items}rest(rest){return new ZodTuple2({...this._def,rest})}},ZodTuple.create=(schemas,params)=>{if(!Array.isArray(schemas))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new ZodTuple({items:schemas,typeName:ZodFirstPartyTypeKind.ZodTuple,rest:null,...processCreateParams(params)})},ZodRecord=class ZodRecord2 extends ZodType{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(input){let{status,ctx}=this._processInputParams(input);if(ctx.parsedType!==ZodParsedType.object)return addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:ctx.parsedType}),INVALID;let pairs=[],keyType=this._def.keyType,valueType=this._def.valueType;for(let key in ctx.data)pairs.push({key:keyType._parse(new ParseInputLazyPath(ctx,key,ctx.path,key)),value:valueType._parse(new ParseInputLazyPath(ctx,ctx.data[key],ctx.path,key)),alwaysSet:key in ctx.data});if(ctx.common.async)return ParseStatus.mergeObjectAsync(status,pairs);else return ParseStatus.mergeObjectSync(status,pairs)}get element(){return this._def.valueType}static create(first,second,third){if(second instanceof ZodType)return new ZodRecord2({keyType:first,valueType:second,typeName:ZodFirstPartyTypeKind.ZodRecord,...processCreateParams(third)});return new ZodRecord2({keyType:ZodString.create(),valueType:first,typeName:ZodFirstPartyTypeKind.ZodRecord,...processCreateParams(second)})}},ZodMap=class extends ZodType{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(input){let{status,ctx}=this._processInputParams(input);if(ctx.parsedType!==ZodParsedType.map)return addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.map,received:ctx.parsedType}),INVALID;let keyType=this._def.keyType,valueType=this._def.valueType,pairs=[...ctx.data.entries()].map(([key,value],index)=>{return{key:keyType._parse(new ParseInputLazyPath(ctx,key,ctx.path,[index,"key"])),value:valueType._parse(new ParseInputLazyPath(ctx,value,ctx.path,[index,"value"]))}});if(ctx.common.async){let finalMap=new Map;return Promise.resolve().then(async()=>{for(let pair of pairs){let key=await pair.key,value=await pair.value;if(key.status==="aborted"||value.status==="aborted")return INVALID;if(key.status==="dirty"||value.status==="dirty")status.dirty();finalMap.set(key.value,value.value)}return{status:status.value,value:finalMap}})}else{let finalMap=new Map;for(let pair of pairs){let{key,value}=pair;if(key.status==="aborted"||value.status==="aborted")return INVALID;if(key.status==="dirty"||value.status==="dirty")status.dirty();finalMap.set(key.value,value.value)}return{status:status.value,value:finalMap}}}},ZodMap.create=(keyType,valueType,params)=>{return new ZodMap({valueType,keyType,typeName:ZodFirstPartyTypeKind.ZodMap,...processCreateParams(params)})},ZodSet=class ZodSet2 extends ZodType{_parse(input){let{status,ctx}=this._processInputParams(input);if(ctx.parsedType!==ZodParsedType.set)return addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.set,received:ctx.parsedType}),INVALID;let def=this._def;if(def.minSize!==null){if(ctx.data.size<def.minSize.value)addIssueToContext(ctx,{code:ZodIssueCode.too_small,minimum:def.minSize.value,type:"set",inclusive:!0,exact:!1,message:def.minSize.message}),status.dirty()}if(def.maxSize!==null){if(ctx.data.size>def.maxSize.value)addIssueToContext(ctx,{code:ZodIssueCode.too_big,maximum:def.maxSize.value,type:"set",inclusive:!0,exact:!1,message:def.maxSize.message}),status.dirty()}let valueType=this._def.valueType;function finalizeSet(elements2){let parsedSet=new Set;for(let element of elements2){if(element.status==="aborted")return INVALID;if(element.status==="dirty")status.dirty();parsedSet.add(element.value)}return{status:status.value,value:parsedSet}}let elements=[...ctx.data.values()].map((item,i)=>valueType._parse(new ParseInputLazyPath(ctx,item,ctx.path,i)));if(ctx.common.async)return Promise.all(elements).then((elements2)=>finalizeSet(elements2));else return finalizeSet(elements)}min(minSize,message){return new ZodSet2({...this._def,minSize:{value:minSize,message:errorUtil.toString(message)}})}max(maxSize,message){return new ZodSet2({...this._def,maxSize:{value:maxSize,message:errorUtil.toString(message)}})}size(size,message){return this.min(size,message).max(size,message)}nonempty(message){return this.min(1,message)}},ZodSet.create=(valueType,params)=>{return new ZodSet({valueType,minSize:null,maxSize:null,typeName:ZodFirstPartyTypeKind.ZodSet,...processCreateParams(params)})},ZodFunction=class ZodFunction2 extends ZodType{constructor(){super(...arguments);this.validate=this.implement}_parse(input){let{ctx}=this._processInputParams(input);if(ctx.parsedType!==ZodParsedType.function)return addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.function,received:ctx.parsedType}),INVALID;function makeArgsIssue(args,error2){return makeIssue({data:args,path:ctx.path,errorMaps:[ctx.common.contextualErrorMap,ctx.schemaErrorMap,getErrorMap(),en_default].filter((x)=>!!x),issueData:{code:ZodIssueCode.invalid_arguments,argumentsError:error2}})}function makeReturnsIssue(returns,error2){return makeIssue({data:returns,path:ctx.path,errorMaps:[ctx.common.contextualErrorMap,ctx.schemaErrorMap,getErrorMap(),en_default].filter((x)=>!!x),issueData:{code:ZodIssueCode.invalid_return_type,returnTypeError:error2}})}let params={errorMap:ctx.common.contextualErrorMap},fn=ctx.data;if(this._def.returns instanceof ZodPromise){let me=this;return OK(async function(...args){let error2=new ZodError([]),parsedArgs=await me._def.args.parseAsync(args,params).catch((e)=>{throw error2.addIssue(makeArgsIssue(args,e)),error2}),result=await Reflect.apply(fn,this,parsedArgs);return await me._def.returns._def.type.parseAsync(result,params).catch((e)=>{throw error2.addIssue(makeReturnsIssue(result,e)),error2})})}else{let me=this;return OK(function(...args){let parsedArgs=me._def.args.safeParse(args,params);if(!parsedArgs.success)throw new ZodError([makeArgsIssue(args,parsedArgs.error)]);let result=Reflect.apply(fn,this,parsedArgs.data),parsedReturns=me._def.returns.safeParse(result,params);if(!parsedReturns.success)throw new ZodError([makeReturnsIssue(result,parsedReturns.error)]);return parsedReturns.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...items){return new ZodFunction2({...this._def,args:ZodTuple.create(items).rest(ZodUnknown.create())})}returns(returnType){return new ZodFunction2({...this._def,returns:returnType})}implement(func){return this.parse(func)}strictImplement(func){return this.parse(func)}static create(args,returns,params){return new ZodFunction2({args:args?args:ZodTuple.create([]).rest(ZodUnknown.create()),returns:returns||ZodUnknown.create(),typeName:ZodFirstPartyTypeKind.ZodFunction,...processCreateParams(params)})}},ZodLazy=class extends ZodType{get schema(){return this._def.getter()}_parse(input){let{ctx}=this._processInputParams(input);return this._def.getter()._parse({data:ctx.data,path:ctx.path,parent:ctx})}},ZodLazy.create=(getter,params)=>{return new ZodLazy({getter,typeName:ZodFirstPartyTypeKind.ZodLazy,...processCreateParams(params)})},ZodLiteral=class extends ZodType{_parse(input){if(input.data!==this._def.value){let ctx=this._getOrReturnCtx(input);return addIssueToContext(ctx,{received:ctx.data,code:ZodIssueCode.invalid_literal,expected:this._def.value}),INVALID}return{status:"valid",value:input.data}}get value(){return this._def.value}},ZodLiteral.create=(value,params)=>{return new ZodLiteral({value,typeName:ZodFirstPartyTypeKind.ZodLiteral,...processCreateParams(params)})},ZodEnum=class ZodEnum2 extends ZodType{_parse(input){if(typeof input.data!=="string"){let ctx=this._getOrReturnCtx(input),expectedValues=this._def.values;return addIssueToContext(ctx,{expected:util.joinValues(expectedValues),received:ctx.parsedType,code:ZodIssueCode.invalid_type}),INVALID}if(!this._cache)this._cache=new Set(this._def.values);if(!this._cache.has(input.data)){let ctx=this._getOrReturnCtx(input),expectedValues=this._def.values;return addIssueToContext(ctx,{received:ctx.data,code:ZodIssueCode.invalid_enum_value,options:expectedValues}),INVALID}return OK(input.data)}get options(){return this._def.values}get enum(){let enumValues={};for(let val of this._def.values)enumValues[val]=val;return enumValues}get Values(){let enumValues={};for(let val of this._def.values)enumValues[val]=val;return enumValues}get Enum(){let enumValues={};for(let val of this._def.values)enumValues[val]=val;return enumValues}extract(values2,newDef=this._def){return ZodEnum2.create(values2,{...this._def,...newDef})}exclude(values2,newDef=this._def){return ZodEnum2.create(this.options.filter((opt)=>!values2.includes(opt)),{...this._def,...newDef})}},ZodEnum.create=createZodEnum,ZodNativeEnum=class extends ZodType{_parse(input){let nativeEnumValues=util.getValidEnumValues(this._def.values),ctx=this._getOrReturnCtx(input);if(ctx.parsedType!==ZodParsedType.string&&ctx.parsedType!==ZodParsedType.number){let expectedValues=util.objectValues(nativeEnumValues);return addIssueToContext(ctx,{expected:util.joinValues(expectedValues),received:ctx.parsedType,code:ZodIssueCode.invalid_type}),INVALID}if(!this._cache)this._cache=new Set(util.getValidEnumValues(this._def.values));if(!this._cache.has(input.data)){let expectedValues=util.objectValues(nativeEnumValues);return addIssueToContext(ctx,{received:ctx.data,code:ZodIssueCode.invalid_enum_value,options:expectedValues}),INVALID}return OK(input.data)}get enum(){return this._def.values}},ZodNativeEnum.create=(values2,params)=>{return new ZodNativeEnum({values:values2,typeName:ZodFirstPartyTypeKind.ZodNativeEnum,...processCreateParams(params)})},ZodPromise=class extends ZodType{unwrap(){return this._def.type}_parse(input){let{ctx}=this._processInputParams(input);if(ctx.parsedType!==ZodParsedType.promise&&ctx.common.async===!1)return addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.promise,received:ctx.parsedType}),INVALID;let promisified=ctx.parsedType===ZodParsedType.promise?ctx.data:Promise.resolve(ctx.data);return OK(promisified.then((data)=>{return this._def.type.parseAsync(data,{path:ctx.path,errorMap:ctx.common.contextualErrorMap})}))}},ZodPromise.create=(schema,params)=>{return new ZodPromise({type:schema,typeName:ZodFirstPartyTypeKind.ZodPromise,...processCreateParams(params)})},ZodEffects=class extends ZodType{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ZodFirstPartyTypeKind.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(input){let{status,ctx}=this._processInputParams(input),effect=this._def.effect||null,checkCtx={addIssue:(arg)=>{if(addIssueToContext(ctx,arg),arg.fatal)status.abort();else status.dirty()},get path(){return ctx.path}};if(checkCtx.addIssue=checkCtx.addIssue.bind(checkCtx),effect.type==="preprocess"){let processed=effect.transform(ctx.data,checkCtx);if(ctx.common.async)return Promise.resolve(processed).then(async(processed2)=>{if(status.value==="aborted")return INVALID;let result=await this._def.schema._parseAsync({data:processed2,path:ctx.path,parent:ctx});if(result.status==="aborted")return INVALID;if(result.status==="dirty")return DIRTY(result.value);if(status.value==="dirty")return DIRTY(result.value);return result});else{if(status.value==="aborted")return INVALID;let result=this._def.schema._parseSync({data:processed,path:ctx.path,parent:ctx});if(result.status==="aborted")return INVALID;if(result.status==="dirty")return DIRTY(result.value);if(status.value==="dirty")return DIRTY(result.value);return result}}if(effect.type==="refinement"){let executeRefinement=(acc)=>{let result=effect.refinement(acc,checkCtx);if(ctx.common.async)return Promise.resolve(result);if(result instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return acc};if(ctx.common.async===!1){let inner=this._def.schema._parseSync({data:ctx.data,path:ctx.path,parent:ctx});if(inner.status==="aborted")return INVALID;if(inner.status==="dirty")status.dirty();return executeRefinement(inner.value),{status:status.value,value:inner.value}}else return this._def.schema._parseAsync({data:ctx.data,path:ctx.path,parent:ctx}).then((inner)=>{if(inner.status==="aborted")return INVALID;if(inner.status==="dirty")status.dirty();return executeRefinement(inner.value).then(()=>{return{status:status.value,value:inner.value}})})}if(effect.type==="transform")if(ctx.common.async===!1){let base=this._def.schema._parseSync({data:ctx.data,path:ctx.path,parent:ctx});if(!isValid(base))return INVALID;let result=effect.transform(base.value,checkCtx);if(result instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:status.value,value:result}}else return this._def.schema._parseAsync({data:ctx.data,path:ctx.path,parent:ctx}).then((base)=>{if(!isValid(base))return INVALID;return Promise.resolve(effect.transform(base.value,checkCtx)).then((result)=>({status:status.value,value:result}))});util.assertNever(effect)}},ZodEffects.create=(schema,effect,params)=>{return new ZodEffects({schema,typeName:ZodFirstPartyTypeKind.ZodEffects,effect,...processCreateParams(params)})},ZodEffects.createWithPreprocess=(preprocess,schema,params)=>{return new ZodEffects({schema,effect:{type:"preprocess",transform:preprocess},typeName:ZodFirstPartyTypeKind.ZodEffects,...processCreateParams(params)})},ZodOptional=class extends ZodType{_parse(input){if(this._getType(input)===ZodParsedType.undefined)return OK(void 0);return this._def.innerType._parse(input)}unwrap(){return this._def.innerType}},ZodOptional.create=(type,params)=>{return new ZodOptional({innerType:type,typeName:ZodFirstPartyTypeKind.ZodOptional,...processCreateParams(params)})},ZodNullable=class extends ZodType{_parse(input){if(this._getType(input)===ZodParsedType.null)return OK(null);return this._def.innerType._parse(input)}unwrap(){return this._def.innerType}},ZodNullable.create=(type,params)=>{return new ZodNullable({innerType:type,typeName:ZodFirstPartyTypeKind.ZodNullable,...processCreateParams(params)})},ZodDefault=class extends ZodType{_parse(input){let{ctx}=this._processInputParams(input),data=ctx.data;if(ctx.parsedType===ZodParsedType.undefined)data=this._def.defaultValue();return this._def.innerType._parse({data,path:ctx.path,parent:ctx})}removeDefault(){return this._def.innerType}},ZodDefault.create=(type,params)=>{return new ZodDefault({innerType:type,typeName:ZodFirstPartyTypeKind.ZodDefault,defaultValue:typeof params.default==="function"?params.default:()=>params.default,...processCreateParams(params)})},ZodCatch=class extends ZodType{_parse(input){let{ctx}=this._processInputParams(input),newCtx={...ctx,common:{...ctx.common,issues:[]}},result=this._def.innerType._parse({data:newCtx.data,path:newCtx.path,parent:{...newCtx}});if(isAsync(result))return result.then((result2)=>{return{status:"valid",value:result2.status==="valid"?result2.value:this._def.catchValue({get error(){return new ZodError(newCtx.common.issues)},input:newCtx.data})}});else return{status:"valid",value:result.status==="valid"?result.value:this._def.catchValue({get error(){return new ZodError(newCtx.common.issues)},input:newCtx.data})}}removeCatch(){return this._def.innerType}},ZodCatch.create=(type,params)=>{return new ZodCatch({innerType:type,typeName:ZodFirstPartyTypeKind.ZodCatch,catchValue:typeof params.catch==="function"?params.catch:()=>params.catch,...processCreateParams(params)})},ZodNaN=class extends ZodType{_parse(input){if(this._getType(input)!==ZodParsedType.nan){let ctx=this._getOrReturnCtx(input);return addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.nan,received:ctx.parsedType}),INVALID}return{status:"valid",value:input.data}}},ZodNaN.create=(params)=>{return new ZodNaN({typeName:ZodFirstPartyTypeKind.ZodNaN,...processCreateParams(params)})},BRAND=Symbol("zod_brand"),ZodBranded=class extends ZodType{_parse(input){let{ctx}=this._processInputParams(input),data=ctx.data;return this._def.type._parse({data,path:ctx.path,parent:ctx})}unwrap(){return this._def.type}},ZodPipeline=class ZodPipeline2 extends ZodType{_parse(input){let{status,ctx}=this._processInputParams(input);if(ctx.common.async)return(async()=>{let inResult=await this._def.in._parseAsync({data:ctx.data,path:ctx.path,parent:ctx});if(inResult.status==="aborted")return INVALID;if(inResult.status==="dirty")return status.dirty(),DIRTY(inResult.value);else return this._def.out._parseAsync({data:inResult.value,path:ctx.path,parent:ctx})})();else{let inResult=this._def.in._parseSync({data:ctx.data,path:ctx.path,parent:ctx});if(inResult.status==="aborted")return INVALID;if(inResult.status==="dirty")return status.dirty(),{status:"dirty",value:inResult.value};else return this._def.out._parseSync({data:inResult.value,path:ctx.path,parent:ctx})}}static create(a,b){return new ZodPipeline2({in:a,out:b,typeName:ZodFirstPartyTypeKind.ZodPipeline})}},ZodReadonly=class extends ZodType{_parse(input){let result=this._def.innerType._parse(input),freeze=(data)=>{if(isValid(data))data.value=Object.freeze(data.value);return data};return isAsync(result)?result.then((data)=>freeze(data)):freeze(result)}unwrap(){return this._def.innerType}},ZodReadonly.create=(type,params)=>{return new ZodReadonly({innerType:type,typeName:ZodFirstPartyTypeKind.ZodReadonly,...processCreateParams(params)})},late={object:ZodObject.lazycreate},function(ZodFirstPartyTypeKind2){ZodFirstPartyTypeKind2.ZodString="ZodString",ZodFirstPartyTypeKind2.ZodNumber="ZodNumber",ZodFirstPartyTypeKind2.ZodNaN="ZodNaN",ZodFirstPartyTypeKind2.ZodBigInt="ZodBigInt",ZodFirstPartyTypeKind2.ZodBoolean="ZodBoolean",ZodFirstPartyTypeKind2.ZodDate="ZodDate",ZodFirstPartyTypeKind2.ZodSymbol="ZodSymbol",ZodFirstPartyTypeKind2.ZodUndefined="ZodUndefined",ZodFirstPartyTypeKind2.ZodNull="ZodNull",ZodFirstPartyTypeKind2.ZodAny="ZodAny",ZodFirstPartyTypeKind2.ZodUnknown="ZodUnknown",ZodFirstPartyTypeKind2.ZodNever="ZodNever",ZodFirstPartyTypeKind2.ZodVoid="ZodVoid",ZodFirstPartyTypeKind2.ZodArray="ZodArray",ZodFirstPartyTypeKind2.ZodObject="ZodObject",ZodFirstPartyTypeKind2.ZodUnion="ZodUnion",ZodFirstPartyTypeKind2.ZodDiscriminatedUnion="ZodDiscriminatedUnion",ZodFirstPartyTypeKind2.ZodIntersection="ZodIntersection",ZodFirstPartyTypeKind2.ZodTuple="ZodTuple",ZodFirstPartyTypeKind2.ZodRecord="ZodRecord",ZodFirstPartyTypeKind2.ZodMap="ZodMap",ZodFirstPartyTypeKind2.ZodSet="ZodSet",ZodFirstPartyTypeKind2.ZodFunction="ZodFunction",ZodFirstPartyTypeKind2.ZodLazy="ZodLazy",ZodFirstPartyTypeKind2.ZodLiteral="ZodLiteral",ZodFirstPartyTypeKind2.ZodEnum="ZodEnum",ZodFirstPartyTypeKind2.ZodEffects="ZodEffects",ZodFirstPartyTypeKind2.ZodNativeEnum="ZodNativeEnum",ZodFirstPartyTypeKind2.ZodOptional="ZodOptional",ZodFirstPartyTypeKind2.ZodNullable="ZodNullable",ZodFirstPartyTypeKind2.ZodDefault="ZodDefault",ZodFirstPartyTypeKind2.ZodCatch="ZodCatch",ZodFirstPartyTypeKind2.ZodPromise="ZodPromise",ZodFirstPartyTypeKind2.ZodBranded="ZodBranded",ZodFirstPartyTypeKind2.ZodPipeline="ZodPipeline",ZodFirstPartyTypeKind2.ZodReadonly="ZodReadonly"}(ZodFirstPartyTypeKind||(ZodFirstPartyTypeKind={})),stringType=ZodString.create,numberType=ZodNumber.create,nanType=ZodNaN.create,bigIntType=ZodBigInt.create,booleanType=ZodBoolean.create,dateType=ZodDate.create,symbolType=ZodSymbol.create,undefinedType=ZodUndefined.create,nullType=ZodNull.create,anyType=ZodAny.create,unknownType=ZodUnknown.create,neverType=ZodNever.create,voidType=ZodVoid.create,arrayType=ZodArray.create,objectType=ZodObject.create,strictObjectType=ZodObject.strictCreate,unionType=ZodUnion.create,discriminatedUnionType=ZodDiscriminatedUnion.create,intersectionType=ZodIntersection.create,tupleType=ZodTuple.create,recordType=ZodRecord.create,mapType=ZodMap.create,setType=ZodSet.create,functionType=ZodFunction.create,lazyType=ZodLazy.create,literalType=ZodLiteral.create,enumType=ZodEnum.create,nativeEnumType=ZodNativeEnum.create,promiseType=ZodPromise.create,effectsType=ZodEffects.create,optionalType=ZodOptional.create,nullableType=ZodNullable.create,preprocessType=ZodEffects.createWithPreprocess,pipelineType=ZodPipeline.create,coerce={string:(arg)=>ZodString.create({...arg,coerce:!0}),number:(arg)=>ZodNumber.create({...arg,coerce:!0}),boolean:(arg)=>ZodBoolean.create({...arg,coerce:!0}),bigint:(arg)=>ZodBigInt.create({...arg,coerce:!0}),date:(arg)=>ZodDate.create({...arg,coerce:!0})},NEVER=INVALID}),exports_external={};__export2(exports_external,{void:()=>voidType,util:()=>util,unknown:()=>unknownType,union:()=>unionType,undefined:()=>undefinedType,tuple:()=>tupleType,transformer:()=>effectsType,symbol:()=>symbolType,string:()=>stringType,strictObject:()=>strictObjectType,setErrorMap:()=>setErrorMap,set:()=>setType,record:()=>recordType,quotelessJson:()=>quotelessJson,promise:()=>promiseType,preprocess:()=>preprocessType,pipeline:()=>pipelineType,ostring:()=>ostring,optional:()=>optionalType,onumber:()=>onumber,oboolean:()=>oboolean,objectUtil:()=>objectUtil,object:()=>objectType,number:()=>numberType,nullable:()=>nullableType,null:()=>nullType,never:()=>neverType,nativeEnum:()=>nativeEnumType,nan:()=>nanType,map:()=>mapType,makeIssue:()=>makeIssue,literal:()=>literalType,lazy:()=>lazyType,late:()=>late,isValid:()=>isValid,isDirty:()=>isDirty,isAsync:()=>isAsync,isAborted:()=>isAborted,intersection:()=>intersectionType,instanceof:()=>instanceOfType,getParsedType:()=>getParsedType,getErrorMap:()=>getErrorMap,function:()=>functionType,enum:()=>enumType,effect:()=>effectsType,discriminatedUnion:()=>discriminatedUnionType,defaultErrorMap:()=>en_default,datetimeRegex:()=>datetimeRegex,date:()=>dateType,custom:()=>custom,coerce:()=>coerce,boolean:()=>booleanType,bigint:()=>bigIntType,array:()=>arrayType,any:()=>anyType,addIssueToContext:()=>addIssueToContext,ZodVoid:()=>ZodVoid,ZodUnknown:()=>ZodUnknown,ZodUnion:()=>ZodUnion,ZodUndefined:()=>ZodUndefined,ZodType:()=>ZodType,ZodTuple:()=>ZodTuple,ZodTransformer:()=>ZodEffects,ZodSymbol:()=>ZodSymbol,ZodString:()=>ZodString,ZodSet:()=>ZodSet,ZodSchema:()=>ZodType,ZodRecord:()=>ZodRecord,ZodReadonly:()=>ZodReadonly,ZodPromise:()=>ZodPromise,ZodPipeline:()=>ZodPipeline,ZodParsedType:()=>ZodParsedType,ZodOptional:()=>ZodOptional,ZodObject:()=>ZodObject,ZodNumber:()=>ZodNumber,ZodNullable:()=>ZodNullable,ZodNull:()=>ZodNull,ZodNever:()=>ZodNever,ZodNativeEnum:()=>ZodNativeEnum,ZodNaN:()=>ZodNaN,ZodMap:()=>ZodMap,ZodLiteral:()=>ZodLiteral,ZodLazy:()=>ZodLazy,ZodIssueCode:()=>ZodIssueCode,ZodIntersection:()=>ZodIntersection,ZodFunction:()=>ZodFunction,ZodFirstPartyTypeKind:()=>ZodFirstPartyTypeKind,ZodError:()=>ZodError,ZodEnum:()=>ZodEnum,ZodEffects:()=>ZodEffects,ZodDiscriminatedUnion:()=>ZodDiscriminatedUnion,ZodDefault:()=>ZodDefault,ZodDate:()=>ZodDate,ZodCatch:()=>ZodCatch,ZodBranded:()=>ZodBranded,ZodBoolean:()=>ZodBoolean,ZodBigInt:()=>ZodBigInt,ZodArray:()=>ZodArray,ZodAny:()=>ZodAny,Schema:()=>ZodType,ParseStatus:()=>ParseStatus,OK:()=>OK,NEVER:()=>NEVER,INVALID:()=>INVALID,EMPTY_PATH:()=>EMPTY_PATH,DIRTY:()=>DIRTY,BRAND:()=>BRAND});init_external=__esm2(()=>{init_errors2(),init_parseUtil(),init_typeAliases(),init_util(),init_types3(),init_ZodError()}),init_zod=__esm2(()=>{init_external(),init_external()});init_dotfile=__esm2(()=>{HASNA_DIR=join18(homedir10(),".hasna")}),exports_config2={};__export2(exports_config2,{saveCloudConfig:()=>saveCloudConfig,getConnectionString:()=>getConnectionString,getConfigPath:()=>getConfigPath3,getConfigDir:()=>getConfigDir2,getCloudConfig:()=>getCloudConfig,createDatabase:()=>createDatabase,CloudConfigSchema:()=>CloudConfigSchema});init_config3=__esm2(()=>{init_zod(),init_adapter(),init_dotfile(),CloudConfigSchema=exports_external.object({rds:exports_external.object({host:exports_external.string().default(""),port:exports_external.number().default(5432),username:exports_external.string().default(""),password_env:exports_external.string().default("HASNA_RDS_PASSWORD"),ssl:exports_external.boolean().default(!0)}).default({}),mode:exports_external.enum(["local","cloud","hybrid"]).default("hybrid"),auto_sync_interval_minutes:exports_external.number().default(0),feedback_endpoint:exports_external.string().default("https://feedback.hasna.com/api/v1/feedback"),sync:exports_external.object({schedule_minutes:exports_external.number().default(0)}).default({})}),CONFIG_DIR=join22(homedir22(),".hasna","cloud"),CONFIG_PATH=join22(CONFIG_DIR,"config.json")}),exports_discover={};__export2(exports_discover,{isSyncExcludedTable:()=>isSyncExcludedTable,getServiceDbPath:()=>getServiceDbPath,discoverSyncableServices:()=>discoverSyncableServices,discoverServices:()=>discoverServices,SYNC_EXCLUDED_TABLE_PATTERNS:()=>SYNC_EXCLUDED_TABLE_PATTERNS,KNOWN_PG_SERVICES:()=>KNOWN_PG_SERVICES});init_discover=__esm2(()=>{KNOWN_PG_SERVICES=["assistants","attachments","brains","configs","connectors","contacts","context","conversations","crawl","deployment","economy","emails","files","hooks","implementations","logs","mcps","mementos","microservices","predictor","prompts","recordings","researcher","sandboxes","search","secrets","sessions","signatures","skills","telephony","terminal","testers","tickets","todos","wallets"],SYNC_EXCLUDED_TABLE_PATTERNS=[/^sqlite_/,/_fts$/,/_fts_/,/^_sync_/,/^_pg_migrations$/]});init_adapter();init_config3();init_config3();init_dotfile();init_adapter();init_config3();init_discover();AUTO_SYNC_CONFIG_PATH=join42(homedir42(),".hasna","cloud","config.json"),DEFAULT_AUTO_SYNC_CONFIG={auto_sync_on_start:!0,auto_sync_on_stop:!0};cleanupHandlers=[];init_config3();init_adapter();init_dotfile();init_config3();CONFIG_DIR2=join62(homedir52(),".hasna","cloud");init_adapter();init_config3();init_discover();init_zod();init_config3();init_dotfile();init_adapter();init_config3();init_dotfile();init_adapter()});import{join as join19}from"path";import{mkdirSync as mkdirSync11,writeFileSync as writeFileSync7}from"fs";function normalizeTags(value){if(Array.isArray(value)){let tags=value.map((t)=>String(t).trim()).filter(Boolean);return tags.length>0?tags:void 0}if(typeof value==="string"){let tags=value.split(",").map((t)=>t.trim()).filter(Boolean);return tags.length>0?tags:void 0}return}function resolveFeedbackDir(cwd){let baseCwd=cwd&&cwd.trim().length>0?cwd:process.cwd();return join19(getProjectDataDir(baseCwd),"feedback")}function saveFeedbackEntry(entry,cwd){let feedbackDir=resolveFeedbackDir(cwd);mkdirSync11(feedbackDir,{recursive:!0});let path2=join19(feedbackDir,`${entry.id}.json`);return writeFileSync7(path2,JSON.stringify(entry,null,2)),{path:path2}}function buildEntry(input,overrides){let typeValue=String(input.type||"feedback").toLowerCase(),type=typeValue==="bug"||typeValue==="feature"?typeValue:"feedback",title=String(input.title||"Feedback").trim()||"Feedback",description=String(input.description||input.message||"").trim(),steps=String(input.steps||"").trim(),expected=String(input.expected||"").trim(),actual=String(input.actual||"").trim(),tags=normalizeTags(input.tags),metadata=input.metadata&&typeof input.metadata==="object"?input.metadata:void 0,source=typeof input.source==="string"?input.source:void 0;return{id:generateId(),createdAt:new Date().toISOString(),type,title,description,steps:steps||void 0,expected:expected||void 0,actual:actual||void 0,tags,metadata,source,...overrides}}var FeedbackTool;var init_feedback=__esm(async()=>{init_src2();await init_config();FeedbackTool=class FeedbackTool{static tool={name:"submit_feedback",description:"Submit product feedback and save it locally. Use for bugs, feature requests, or general feedback.",parameters:{type:"object",properties:{type:{type:"string",description:"Feedback type: bug, feature, or feedback",enum:["bug","feature","feedback"],default:"feedback"},title:{type:"string",description:"Short summary title"},description:{type:"string",description:"Detailed description of the feedback"},steps:{type:"string",description:"Steps to reproduce (for bugs)"},expected:{type:"string",description:"Expected behavior (for bugs)"},actual:{type:"string",description:"Actual behavior (for bugs)"},tags:{type:"array",description:"Optional tags",items:{type:"string",description:"Tag"}},metadata:{type:"object",description:"Optional metadata (key-value)"},source:{type:"string",description:"Source of feedback (optional)"}},required:["title","description"]}};static executor=async(input)=>{try{let entry=buildEntry(input,{source:input.source||"tool"}),{path:path2}=saveFeedbackEntry(entry,typeof input.cwd==="string"?input.cwd:void 0);try{let{sendFeedback:sendFeedback2}=await Promise.resolve().then(() => (init_dist(),exports_dist));await sendFeedback2({service:"open-assistants",version:"1.1.129",message:`[${entry.type}] ${entry.title}: ${entry.description}`})}catch{}return`Feedback saved locally.
|
|
1015
|
+
`);warnStream.write(util.format.apply(util,args))}}Object.defineProperty(exports,"isWin",{get:function(){return isWin},set:function(val){isWin=val}}),exports.warnTo=function(stream){var old=warnStream;return warnStream=stream,old},exports.getFileName=function(rawEnv){var env2=rawEnv||process.env,file=env2.PGPASSFILE||(isWin?path2.join(env2.APPDATA||"./","postgresql","pgpass.conf"):path2.join(env2.HOME||"./",".pgpass"));return file},exports.usePgPass=function(stats,fname){if(Object.prototype.hasOwnProperty.call(process.env,"PGPASSWORD"))return!1;if(isWin)return!0;if(fname=fname||"<unkn>",!isRegFile(stats.mode))return warn('WARNING: password file "%s" is not a plain file',fname),!1;if(stats.mode&(S_IRWXG|S_IRWXO))return warn('WARNING: password file "%s" has group or world access; permissions should be u=rw (0600) or less',fname),!1;return!0};var matcher=exports.match=function(connInfo,entry){return fieldNames.slice(0,-1).reduce(function(prev,field,idx){if(idx==1){if(Number(connInfo[field]||defaultPort)===Number(entry[field]))return prev&&!0}return prev&&(entry[field]==="*"||entry[field]===connInfo[field])},!0)};exports.getPassword=function(connInfo,stream,cb){var pass,lineStream=stream.pipe(split());function onLine(line){var entry=parseLine(line);if(entry&&isValidEntry(entry)&&matcher(connInfo,entry))pass=entry[passKey],lineStream.end()}var onEnd=function(){stream.destroy(),cb(pass)},onErr=function(err){stream.destroy(),warn("WARNING: error on reading file: %s",err),cb(void 0)};stream.on("error",onErr),lineStream.on("data",onLine).on("end",onEnd).on("error",onErr)};var parseLine=exports.parseLine=function(line){if(line.length<11||line.match(/^\s+#/))return null;var curChar="",prevChar="",fieldIdx=0,startIdx=0,endIdx=0,obj={},isLastField=!1,addToObj=function(idx,i0,i1){var field=line.substring(i0,i1);if(!Object.hasOwnProperty.call(process.env,"PGPASS_NO_DEESCAPE"))field=field.replace(/\\([:\\])/g,"$1");obj[fieldNames[idx]]=field};for(var i=0;i<line.length-1;i+=1){if(curChar=line.charAt(i+1),prevChar=line.charAt(i),isLastField=fieldIdx==nrOfFields-1,isLastField){addToObj(fieldIdx,startIdx);break}if(i>=0&&curChar==":"&&prevChar!=="\\")addToObj(fieldIdx,startIdx,i+1),startIdx=i+2,fieldIdx+=1}return obj=Object.keys(obj).length===nrOfFields?obj:null,obj},isValidEntry=exports.isValidEntry=function(entry){var rules={0:function(x){return x.length>0},1:function(x){if(x==="*")return!0;return x=Number(x),isFinite(x)&&x>0&&x<9007199254740992&&Math.floor(x)===x},2:function(x){return x.length>0},3:function(x){return x.length>0},4:function(x){return x.length>0}};for(var idx=0;idx<fieldNames.length;idx+=1){var rule=rules[idx],value=entry[fieldNames[idx]]||"",res=rule(value);if(!res)return!1}return!0}}),require_lib=__commonJS2((exports,module)=>{var path2=__require2("path"),fs=__require2("fs"),helper=require_helper();module.exports=function(connInfo,cb){var file=helper.getFileName();fs.stat(file,function(err,stat2){if(err||!helper.usePgPass(stat2,file))return cb(void 0);var st=fs.createReadStream(file);helper.getPassword(connInfo,st,cb)})},module.exports.warnTo=helper.warnTo}),require_client=__commonJS2((exports,module)=>{var EventEmitter=__require2("events").EventEmitter,utils2=require_utils2(),nodeUtils=__require2("util"),sasl=require_sasl(),TypeOverrides=require_type_overrides(),ConnectionParameters=require_connection_parameters(),Query=require_query(),defaults2=require_defaults2(),Connection=require_connection(),crypto2=require_utils22(),activeQueryDeprecationNotice=nodeUtils.deprecate(()=>{},"Client.activeQuery is deprecated and will be removed in pg@9.0"),queryQueueDeprecationNotice=nodeUtils.deprecate(()=>{},"Client.queryQueue is deprecated and will be removed in pg@9.0."),pgPassDeprecationNotice=nodeUtils.deprecate(()=>{},"pgpass support is deprecated and will be removed in pg@9.0. You can provide an async function as the password property to the Client/Pool constructor that returns a password instead. Within this function you can call the pgpass module in your own code."),byoPromiseDeprecationNotice=nodeUtils.deprecate(()=>{},"Passing a custom Promise implementation to the Client/Pool constructor is deprecated and will be removed in pg@9.0."),queryQueueLengthDeprecationNotice=nodeUtils.deprecate(()=>{},"Calling client.query() when the client is already executing a query is deprecated and will be removed in pg@9.0. Use async/await or an external async flow control mechanism instead.");class Client2 extends EventEmitter{constructor(config){super();this.connectionParameters=new ConnectionParameters(config),this.user=this.connectionParameters.user,this.database=this.connectionParameters.database,this.port=this.connectionParameters.port,this.host=this.connectionParameters.host,Object.defineProperty(this,"password",{configurable:!0,enumerable:!1,writable:!0,value:this.connectionParameters.password}),this.replication=this.connectionParameters.replication;let c=config||{};if(c.Promise)byoPromiseDeprecationNotice();if(this._Promise=c.Promise||global.Promise,this._types=new TypeOverrides(c.types),this._ending=!1,this._ended=!1,this._connecting=!1,this._connected=!1,this._connectionError=!1,this._queryable=!0,this._activeQuery=null,this.enableChannelBinding=Boolean(c.enableChannelBinding),this.connection=c.connection||new Connection({stream:c.stream,ssl:this.connectionParameters.ssl,keepAlive:c.keepAlive||!1,keepAliveInitialDelayMillis:c.keepAliveInitialDelayMillis||0,encoding:this.connectionParameters.client_encoding||"utf8"}),this._queryQueue=[],this.binary=c.binary||defaults2.binary,this.processID=null,this.secretKey=null,this.ssl=this.connectionParameters.ssl||!1,this.ssl&&this.ssl.key)Object.defineProperty(this.ssl,"key",{enumerable:!1});this._connectionTimeoutMillis=c.connectionTimeoutMillis||0}get activeQuery(){return activeQueryDeprecationNotice(),this._activeQuery}set activeQuery(val){activeQueryDeprecationNotice(),this._activeQuery=val}_getActiveQuery(){return this._activeQuery}_errorAllQueries(err){let enqueueError=(query)=>{process.nextTick(()=>{query.handleError(err,this.connection)})},activeQuery=this._getActiveQuery();if(activeQuery)enqueueError(activeQuery),this._activeQuery=null;this._queryQueue.forEach(enqueueError),this._queryQueue.length=0}_connect(callback){let self2=this,con=this.connection;if(this._connectionCallback=callback,this._connecting||this._connected){let err=Error("Client has already been connected. You cannot reuse a client.");process.nextTick(()=>{callback(err)});return}if(this._connecting=!0,this._connectionTimeoutMillis>0){if(this.connectionTimeoutHandle=setTimeout(()=>{con._ending=!0,con.stream.destroy(Error("timeout expired"))},this._connectionTimeoutMillis),this.connectionTimeoutHandle.unref)this.connectionTimeoutHandle.unref()}if(this.host&&this.host.indexOf("/")===0)con.connect(this.host+"/.s.PGSQL."+this.port);else con.connect(this.port,this.host);con.on("connect",function(){if(self2.ssl)con.requestSsl();else con.startup(self2.getStartupConf())}),con.on("sslconnect",function(){con.startup(self2.getStartupConf())}),this._attachListeners(con),con.once("end",()=>{let error2=this._ending?Error("Connection terminated"):Error("Connection terminated unexpectedly");if(clearTimeout(this.connectionTimeoutHandle),this._errorAllQueries(error2),this._ended=!0,!this._ending){if(this._connecting&&!this._connectionError)if(this._connectionCallback)this._connectionCallback(error2);else this._handleErrorEvent(error2);else if(!this._connectionError)this._handleErrorEvent(error2)}process.nextTick(()=>{this.emit("end")})})}connect(callback){if(callback){this._connect(callback);return}return new this._Promise((resolve6,reject)=>{this._connect((error2)=>{if(error2)reject(error2);else resolve6(this)})})}_attachListeners(con){con.on("authenticationCleartextPassword",this._handleAuthCleartextPassword.bind(this)),con.on("authenticationMD5Password",this._handleAuthMD5Password.bind(this)),con.on("authenticationSASL",this._handleAuthSASL.bind(this)),con.on("authenticationSASLContinue",this._handleAuthSASLContinue.bind(this)),con.on("authenticationSASLFinal",this._handleAuthSASLFinal.bind(this)),con.on("backendKeyData",this._handleBackendKeyData.bind(this)),con.on("error",this._handleErrorEvent.bind(this)),con.on("errorMessage",this._handleErrorMessage.bind(this)),con.on("readyForQuery",this._handleReadyForQuery.bind(this)),con.on("notice",this._handleNotice.bind(this)),con.on("rowDescription",this._handleRowDescription.bind(this)),con.on("dataRow",this._handleDataRow.bind(this)),con.on("portalSuspended",this._handlePortalSuspended.bind(this)),con.on("emptyQuery",this._handleEmptyQuery.bind(this)),con.on("commandComplete",this._handleCommandComplete.bind(this)),con.on("parseComplete",this._handleParseComplete.bind(this)),con.on("copyInResponse",this._handleCopyInResponse.bind(this)),con.on("copyData",this._handleCopyData.bind(this)),con.on("notification",this._handleNotification.bind(this))}_getPassword(cb){let con=this.connection;if(typeof this.password==="function")this._Promise.resolve().then(()=>this.password(this.connectionParameters)).then((pass)=>{if(pass!==void 0){if(typeof pass!=="string"){con.emit("error",TypeError("Password must be a string"));return}this.connectionParameters.password=this.password=pass}else this.connectionParameters.password=this.password=null;cb()}).catch((err)=>{con.emit("error",err)});else if(this.password!==null)cb();else try{require_lib()(this.connectionParameters,(pass)=>{if(pass!==void 0)pgPassDeprecationNotice(),this.connectionParameters.password=this.password=pass;cb()})}catch(e){this.emit("error",e)}}_handleAuthCleartextPassword(msg){this._getPassword(()=>{this.connection.password(this.password)})}_handleAuthMD5Password(msg){this._getPassword(async()=>{try{let hashedPassword=await crypto2.postgresMd5PasswordHash(this.user,this.password,msg.salt);this.connection.password(hashedPassword)}catch(e){this.emit("error",e)}})}_handleAuthSASL(msg){this._getPassword(()=>{try{this.saslSession=sasl.startSession(msg.mechanisms,this.enableChannelBinding&&this.connection.stream),this.connection.sendSASLInitialResponseMessage(this.saslSession.mechanism,this.saslSession.response)}catch(err){this.connection.emit("error",err)}})}async _handleAuthSASLContinue(msg){try{await sasl.continueSession(this.saslSession,this.password,msg.data,this.enableChannelBinding&&this.connection.stream),this.connection.sendSCRAMClientFinalMessage(this.saslSession.response)}catch(err){this.connection.emit("error",err)}}_handleAuthSASLFinal(msg){try{sasl.finalizeSession(this.saslSession,msg.data),this.saslSession=null}catch(err){this.connection.emit("error",err)}}_handleBackendKeyData(msg){this.processID=msg.processID,this.secretKey=msg.secretKey}_handleReadyForQuery(msg){if(this._connecting){if(this._connecting=!1,this._connected=!0,clearTimeout(this.connectionTimeoutHandle),this._connectionCallback)this._connectionCallback(null,this),this._connectionCallback=null;this.emit("connect")}let activeQuery=this._getActiveQuery();if(this._activeQuery=null,this.readyForQuery=!0,activeQuery)activeQuery.handleReadyForQuery(this.connection);this._pulseQueryQueue()}_handleErrorWhileConnecting(err){if(this._connectionError)return;if(this._connectionError=!0,clearTimeout(this.connectionTimeoutHandle),this._connectionCallback)return this._connectionCallback(err);this.emit("error",err)}_handleErrorEvent(err){if(this._connecting)return this._handleErrorWhileConnecting(err);this._queryable=!1,this._errorAllQueries(err),this.emit("error",err)}_handleErrorMessage(msg){if(this._connecting)return this._handleErrorWhileConnecting(msg);let activeQuery=this._getActiveQuery();if(!activeQuery){this._handleErrorEvent(msg);return}this._activeQuery=null,activeQuery.handleError(msg,this.connection)}_handleRowDescription(msg){let activeQuery=this._getActiveQuery();if(activeQuery==null){let error2=Error("Received unexpected rowDescription message from backend.");this._handleErrorEvent(error2);return}activeQuery.handleRowDescription(msg)}_handleDataRow(msg){let activeQuery=this._getActiveQuery();if(activeQuery==null){let error2=Error("Received unexpected dataRow message from backend.");this._handleErrorEvent(error2);return}activeQuery.handleDataRow(msg)}_handlePortalSuspended(msg){let activeQuery=this._getActiveQuery();if(activeQuery==null){let error2=Error("Received unexpected portalSuspended message from backend.");this._handleErrorEvent(error2);return}activeQuery.handlePortalSuspended(this.connection)}_handleEmptyQuery(msg){let activeQuery=this._getActiveQuery();if(activeQuery==null){let error2=Error("Received unexpected emptyQuery message from backend.");this._handleErrorEvent(error2);return}activeQuery.handleEmptyQuery(this.connection)}_handleCommandComplete(msg){let activeQuery=this._getActiveQuery();if(activeQuery==null){let error2=Error("Received unexpected commandComplete message from backend.");this._handleErrorEvent(error2);return}activeQuery.handleCommandComplete(msg,this.connection)}_handleParseComplete(){let activeQuery=this._getActiveQuery();if(activeQuery==null){let error2=Error("Received unexpected parseComplete message from backend.");this._handleErrorEvent(error2);return}if(activeQuery.name)this.connection.parsedStatements[activeQuery.name]=activeQuery.text}_handleCopyInResponse(msg){let activeQuery=this._getActiveQuery();if(activeQuery==null){let error2=Error("Received unexpected copyInResponse message from backend.");this._handleErrorEvent(error2);return}activeQuery.handleCopyInResponse(this.connection)}_handleCopyData(msg){let activeQuery=this._getActiveQuery();if(activeQuery==null){let error2=Error("Received unexpected copyData message from backend.");this._handleErrorEvent(error2);return}activeQuery.handleCopyData(msg,this.connection)}_handleNotification(msg){this.emit("notification",msg)}_handleNotice(msg){this.emit("notice",msg)}getStartupConf(){let params=this.connectionParameters,data={user:params.user,database:params.database},appName=params.application_name||params.fallback_application_name;if(appName)data.application_name=appName;if(params.replication)data.replication=""+params.replication;if(params.statement_timeout)data.statement_timeout=String(parseInt(params.statement_timeout,10));if(params.lock_timeout)data.lock_timeout=String(parseInt(params.lock_timeout,10));if(params.idle_in_transaction_session_timeout)data.idle_in_transaction_session_timeout=String(parseInt(params.idle_in_transaction_session_timeout,10));if(params.options)data.options=params.options;return data}cancel(client,query){if(client.activeQuery===query){let con=this.connection;if(this.host&&this.host.indexOf("/")===0)con.connect(this.host+"/.s.PGSQL."+this.port);else con.connect(this.port,this.host);con.on("connect",function(){con.cancel(client.processID,client.secretKey)})}else if(client._queryQueue.indexOf(query)!==-1)client._queryQueue.splice(client._queryQueue.indexOf(query),1)}setTypeParser(oid,format,parseFn){return this._types.setTypeParser(oid,format,parseFn)}getTypeParser(oid,format){return this._types.getTypeParser(oid,format)}escapeIdentifier(str3){return utils2.escapeIdentifier(str3)}escapeLiteral(str3){return utils2.escapeLiteral(str3)}_pulseQueryQueue(){if(this.readyForQuery===!0){this._activeQuery=this._queryQueue.shift();let activeQuery=this._getActiveQuery();if(activeQuery){this.readyForQuery=!1,this.hasExecuted=!0;let queryError=activeQuery.submit(this.connection);if(queryError)process.nextTick(()=>{activeQuery.handleError(queryError,this.connection),this.readyForQuery=!0,this._pulseQueryQueue()})}else if(this.hasExecuted)this._activeQuery=null,this.emit("drain")}}query(config,values2,callback){let query,result,readTimeout,readTimeoutTimer,queryCallback;if(config===null||config===void 0)throw TypeError("Client was passed a null or undefined query");else if(typeof config.submit==="function"){if(readTimeout=config.query_timeout||this.connectionParameters.query_timeout,result=query=config,!query.callback){if(typeof values2==="function")query.callback=values2;else if(callback)query.callback=callback}}else if(readTimeout=config.query_timeout||this.connectionParameters.query_timeout,query=new Query(config,values2,callback),!query.callback)result=new this._Promise((resolve6,reject)=>{query.callback=(err,res)=>err?reject(err):resolve6(res)}).catch((err)=>{throw Error.captureStackTrace(err),err});if(readTimeout)queryCallback=query.callback||(()=>{}),readTimeoutTimer=setTimeout(()=>{let error2=Error("Query read timeout");process.nextTick(()=>{query.handleError(error2,this.connection)}),queryCallback(error2),query.callback=()=>{};let index=this._queryQueue.indexOf(query);if(index>-1)this._queryQueue.splice(index,1);this._pulseQueryQueue()},readTimeout),query.callback=(err,res)=>{clearTimeout(readTimeoutTimer),queryCallback(err,res)};if(this.binary&&!query.binary)query.binary=!0;if(query._result&&!query._result._types)query._result._types=this._types;if(!this._queryable)return process.nextTick(()=>{query.handleError(Error("Client has encountered a connection error and is not queryable"),this.connection)}),result;if(this._ending)return process.nextTick(()=>{query.handleError(Error("Client was closed and is not queryable"),this.connection)}),result;if(this._queryQueue.length>0)queryQueueLengthDeprecationNotice();return this._queryQueue.push(query),this._pulseQueryQueue(),result}ref(){this.connection.ref()}unref(){this.connection.unref()}end(cb){if(this._ending=!0,!this.connection._connecting||this._ended)if(cb)cb();else return this._Promise.resolve();if(this._getActiveQuery()||!this._queryable)this.connection.stream.destroy();else this.connection.end();if(cb)this.connection.once("end",cb);else return new this._Promise((resolve6)=>{this.connection.once("end",resolve6)})}get queryQueue(){return queryQueueDeprecationNotice(),this._queryQueue}}Client2.Query=Query,module.exports=Client2}),require_pg_pool=__commonJS2((exports,module)=>{var EventEmitter=__require2("events").EventEmitter,NOOP=function(){},removeWhere=(list,predicate)=>{let i=list.findIndex(predicate);return i===-1?void 0:list.splice(i,1)[0]};class IdleItem{constructor(client,idleListener,timeoutId){this.client=client,this.idleListener=idleListener,this.timeoutId=timeoutId}}class PendingItem{constructor(callback){this.callback=callback}}function throwOnDoubleRelease(){throw Error("Release called on client which has already been released to the pool.")}function promisify(Promise2,callback){if(callback)return{callback,result:void 0};let rej,res,cb=function(err,client){err?rej(err):res(client)},result=new Promise2(function(resolve6,reject){res=resolve6,rej=reject}).catch((err)=>{throw Error.captureStackTrace(err),err});return{callback:cb,result}}function makeIdleListener(pool,client){return function idleListener(err){err.client=client,client.removeListener("error",idleListener),client.on("error",()=>{pool.log("additional client error after disconnection due to error",err)}),pool._remove(client),pool.emit("error",err,client)}}class Pool extends EventEmitter{constructor(options2,Client2){super();if(this.options=Object.assign({},options2),options2!=null&&"password"in options2)Object.defineProperty(this.options,"password",{configurable:!0,enumerable:!1,writable:!0,value:options2.password});if(options2!=null&&options2.ssl&&options2.ssl.key)Object.defineProperty(this.options.ssl,"key",{enumerable:!1});if(this.options.max=this.options.max||this.options.poolSize||10,this.options.min=this.options.min||0,this.options.maxUses=this.options.maxUses||1/0,this.options.allowExitOnIdle=this.options.allowExitOnIdle||!1,this.options.maxLifetimeSeconds=this.options.maxLifetimeSeconds||0,this.log=this.options.log||function(){},this.Client=this.options.Client||Client2||require_lib2().Client,this.Promise=this.options.Promise||global.Promise,typeof this.options.idleTimeoutMillis>"u")this.options.idleTimeoutMillis=1e4;this._clients=[],this._idle=[],this._expired=new WeakSet,this._pendingQueue=[],this._endCallback=void 0,this.ending=!1,this.ended=!1}_promiseTry(f){let Promise2=this.Promise;if(typeof Promise2.try==="function")return Promise2.try(f);return new Promise2((resolve6)=>resolve6(f()))}_isFull(){return this._clients.length>=this.options.max}_isAboveMin(){return this._clients.length>this.options.min}_pulseQueue(){if(this.log("pulse queue"),this.ended){this.log("pulse queue ended");return}if(this.ending){if(this.log("pulse queue on ending"),this._idle.length)this._idle.slice().map((item)=>{this._remove(item.client)});if(!this._clients.length)this.ended=!0,this._endCallback();return}if(!this._pendingQueue.length){this.log("no queued requests");return}if(!this._idle.length&&this._isFull())return;let pendingItem=this._pendingQueue.shift();if(this._idle.length){let idleItem=this._idle.pop();clearTimeout(idleItem.timeoutId);let client=idleItem.client;client.ref&&client.ref();let idleListener=idleItem.idleListener;return this._acquireClient(client,pendingItem,idleListener,!1)}if(!this._isFull())return this.newClient(pendingItem);throw Error("unexpected condition")}_remove(client,callback){let removed=removeWhere(this._idle,(item)=>item.client===client);if(removed!==void 0)clearTimeout(removed.timeoutId);this._clients=this._clients.filter((c)=>c!==client);let context=this;client.end(()=>{if(context.emit("remove",client),typeof callback==="function")callback()})}connect(cb){if(this.ending){let err=Error("Cannot use a pool after calling end on the pool");return cb?cb(err):this.Promise.reject(err)}let response=promisify(this.Promise,cb),result=response.result;if(this._isFull()||this._idle.length){if(this._idle.length)process.nextTick(()=>this._pulseQueue());if(!this.options.connectionTimeoutMillis)return this._pendingQueue.push(new PendingItem(response.callback)),result;let queueCallback=(err,res,done)=>{clearTimeout(tid),response.callback(err,res,done)},pendingItem=new PendingItem(queueCallback),tid=setTimeout(()=>{removeWhere(this._pendingQueue,(i)=>i.callback===queueCallback),pendingItem.timedOut=!0,response.callback(Error("timeout exceeded when trying to connect"))},this.options.connectionTimeoutMillis);if(tid.unref)tid.unref();return this._pendingQueue.push(pendingItem),result}return this.newClient(new PendingItem(response.callback)),result}newClient(pendingItem){let client=new this.Client(this.options);this._clients.push(client);let idleListener=makeIdleListener(this,client);this.log("checking client timeout");let tid,timeoutHit=!1;if(this.options.connectionTimeoutMillis)tid=setTimeout(()=>{if(client.connection)this.log("ending client due to timeout"),timeoutHit=!0,client.connection.stream.destroy();else if(!client.isConnected())this.log("ending client due to timeout"),timeoutHit=!0,client.end()},this.options.connectionTimeoutMillis);this.log("connecting new client"),client.connect((err)=>{if(tid)clearTimeout(tid);if(client.on("error",idleListener),err){if(this.log("client failed to connect",err),this._clients=this._clients.filter((c)=>c!==client),timeoutHit)err=Error("Connection terminated due to connection timeout",{cause:err});if(this._pulseQueue(),!pendingItem.timedOut)pendingItem.callback(err,void 0,NOOP)}else{if(this.log("new client connected"),this.options.onConnect){this._promiseTry(()=>this.options.onConnect(client)).then(()=>{this._afterConnect(client,pendingItem,idleListener)},(hookErr)=>{this._clients=this._clients.filter((c)=>c!==client),client.end(()=>{if(this._pulseQueue(),!pendingItem.timedOut)pendingItem.callback(hookErr,void 0,NOOP)})});return}return this._afterConnect(client,pendingItem,idleListener)}})}_afterConnect(client,pendingItem,idleListener){if(this.options.maxLifetimeSeconds!==0){let maxLifetimeTimeout=setTimeout(()=>{if(this.log("ending client due to expired lifetime"),this._expired.add(client),this._idle.findIndex((idleItem)=>idleItem.client===client)!==-1)this._acquireClient(client,new PendingItem((err,client2,clientRelease)=>clientRelease()),idleListener,!1)},this.options.maxLifetimeSeconds*1000);maxLifetimeTimeout.unref(),client.once("end",()=>clearTimeout(maxLifetimeTimeout))}return this._acquireClient(client,pendingItem,idleListener,!0)}_acquireClient(client,pendingItem,idleListener,isNew){if(isNew)this.emit("connect",client);if(this.emit("acquire",client),client.release=this._releaseOnce(client,idleListener),client.removeListener("error",idleListener),!pendingItem.timedOut)if(isNew&&this.options.verify)this.options.verify(client,(err)=>{if(err)return client.release(err),pendingItem.callback(err,void 0,NOOP);pendingItem.callback(void 0,client,client.release)});else pendingItem.callback(void 0,client,client.release);else if(isNew&&this.options.verify)this.options.verify(client,client.release);else client.release()}_releaseOnce(client,idleListener){let released=!1;return(err)=>{if(released)throwOnDoubleRelease();released=!0,this._release(client,idleListener,err)}}_release(client,idleListener,err){if(client.on("error",idleListener),client._poolUseCount=(client._poolUseCount||0)+1,this.emit("release",err,client),err||this.ending||!client._queryable||client._ending||client._poolUseCount>=this.options.maxUses){if(client._poolUseCount>=this.options.maxUses)this.log("remove expended client");return this._remove(client,this._pulseQueue.bind(this))}if(this._expired.has(client))return this.log("remove expired client"),this._expired.delete(client),this._remove(client,this._pulseQueue.bind(this));let tid;if(this.options.idleTimeoutMillis&&this._isAboveMin()){if(tid=setTimeout(()=>{if(this._isAboveMin())this.log("remove idle client"),this._remove(client,this._pulseQueue.bind(this))},this.options.idleTimeoutMillis),this.options.allowExitOnIdle)tid.unref()}if(this.options.allowExitOnIdle)client.unref();this._idle.push(new IdleItem(client,idleListener,tid)),this._pulseQueue()}query(text,values2,cb){if(typeof text==="function"){let response2=promisify(this.Promise,text);return setImmediate(function(){return response2.callback(Error("Passing a function as the first parameter to pool.query is not supported"))}),response2.result}if(typeof values2==="function")cb=values2,values2=void 0;let response=promisify(this.Promise,cb);return cb=response.callback,this.connect((err,client)=>{if(err)return cb(err);let clientReleased=!1,onError=(err2)=>{if(clientReleased)return;clientReleased=!0,client.release(err2),cb(err2)};client.once("error",onError),this.log("dispatching query");try{client.query(text,values2,(err2,res)=>{if(this.log("query dispatched"),client.removeListener("error",onError),clientReleased)return;if(clientReleased=!0,client.release(err2),err2)return cb(err2);return cb(void 0,res)})}catch(err2){return client.release(err2),cb(err2)}}),response.result}end(cb){if(this.log("ending"),this.ending){let err=Error("Called end on pool more than once");return cb?cb(err):this.Promise.reject(err)}this.ending=!0;let promised=promisify(this.Promise,cb);return this._endCallback=promised.callback,this._pulseQueue(),promised.result}get waitingCount(){return this._pendingQueue.length}get idleCount(){return this._idle.length}get expiredCount(){return this._clients.reduce((acc,client)=>acc+(this._expired.has(client)?1:0),0)}get totalCount(){return this._clients.length}}module.exports=Pool}),require_query2=__commonJS2((exports,module)=>{var EventEmitter=__require2("events").EventEmitter,util=__require2("util"),utils2=require_utils2(),NativeQuery=module.exports=function(config,values2,callback){EventEmitter.call(this),config=utils2.normalizeQueryConfig(config,values2,callback),this.text=config.text,this.values=config.values,this.name=config.name,this.queryMode=config.queryMode,this.callback=config.callback,this.state="new",this._arrayMode=config.rowMode==="array",this._emitRowEvents=!1,this.on("newListener",function(event){if(event==="row")this._emitRowEvents=!0}.bind(this))};util.inherits(NativeQuery,EventEmitter);var errorFieldMap={sqlState:"code",statementPosition:"position",messagePrimary:"message",context:"where",schemaName:"schema",tableName:"table",columnName:"column",dataTypeName:"dataType",constraintName:"constraint",sourceFile:"file",sourceLine:"line",sourceFunction:"routine"};NativeQuery.prototype.handleError=function(err){let fields=this.native.pq.resultErrorFields();if(fields)for(let key in fields){let normalizedFieldName=errorFieldMap[key]||key;err[normalizedFieldName]=fields[key]}if(this.callback)this.callback(err);else this.emit("error",err);this.state="error"},NativeQuery.prototype.then=function(onSuccess,onFailure){return this._getPromise().then(onSuccess,onFailure)},NativeQuery.prototype.catch=function(callback){return this._getPromise().catch(callback)},NativeQuery.prototype._getPromise=function(){if(this._promise)return this._promise;return this._promise=new Promise(function(resolve6,reject){this._once("end",resolve6),this._once("error",reject)}.bind(this)),this._promise},NativeQuery.prototype.submit=function(client){this.state="running";let self2=this;this.native=client.native,client.native.arrayMode=this._arrayMode;let after=function(err,rows,results){if(client.native.arrayMode=!1,setImmediate(function(){self2.emit("_done")}),err)return self2.handleError(err);if(self2._emitRowEvents)if(results.length>1)rows.forEach((rowOfRows,i)=>{rowOfRows.forEach((row)=>{self2.emit("row",row,results[i])})});else rows.forEach(function(row){self2.emit("row",row,results)});if(self2.state="end",self2.emit("end",results),self2.callback)self2.callback(null,results)};if(process.domain)after=process.domain.bind(after);if(this.name){if(this.name.length>63)console.error("Warning! Postgres only supports 63 characters for query names."),console.error("You supplied %s (%s)",this.name,this.name.length),console.error("This can cause conflicts and silent errors executing queries");let values2=(this.values||[]).map(utils2.prepareValue);if(client.namedQueries[this.name]){if(this.text&&client.namedQueries[this.name]!==this.text){let err=Error(`Prepared statements must be unique - '${this.name}' was used for a different statement`);return after(err)}return client.native.execute(this.name,values2,after)}return client.native.prepare(this.name,this.text,values2.length,function(err){if(err)return after(err);return client.namedQueries[self2.name]=self2.text,self2.native.execute(self2.name,values2,after)})}else if(this.values){if(!Array.isArray(this.values)){let err=Error("Query values must be an array");return after(err)}let vals=this.values.map(utils2.prepareValue);client.native.query(this.text,vals,after)}else if(this.queryMode==="extended")client.native.query(this.text,[],after);else client.native.query(this.text,after)}}),require_client2=__commonJS2((exports,module)=>{var nodeUtils=__require2("util"),Native;try{Native=(()=>{throw Error("Cannot require module pg-native")})()}catch(e){throw e}var TypeOverrides=require_type_overrides(),EventEmitter=__require2("events").EventEmitter,util=__require2("util"),ConnectionParameters=require_connection_parameters(),NativeQuery=require_query2(),queryQueueLengthDeprecationNotice=nodeUtils.deprecate(()=>{},"Calling client.query() when the client is already executing a query is deprecated and will be removed in pg@9.0. Use async/await or an external async flow control mechanism instead."),Client2=module.exports=function(config){EventEmitter.call(this),config=config||{},this._Promise=config.Promise||global.Promise,this._types=new TypeOverrides(config.types),this.native=new Native({types:this._types}),this._queryQueue=[],this._ending=!1,this._connecting=!1,this._connected=!1,this._queryable=!0;let cp=this.connectionParameters=new ConnectionParameters(config);if(config.nativeConnectionString)cp.nativeConnectionString=config.nativeConnectionString;this.user=cp.user,Object.defineProperty(this,"password",{configurable:!0,enumerable:!1,writable:!0,value:cp.password}),this.database=cp.database,this.host=cp.host,this.port=cp.port,this.namedQueries={}};Client2.Query=NativeQuery,util.inherits(Client2,EventEmitter),Client2.prototype._errorAllQueries=function(err){let enqueueError=(query)=>{process.nextTick(()=>{query.native=this.native,query.handleError(err)})};if(this._hasActiveQuery())enqueueError(this._activeQuery),this._activeQuery=null;this._queryQueue.forEach(enqueueError),this._queryQueue.length=0},Client2.prototype._connect=function(cb){let self2=this;if(this._connecting){process.nextTick(()=>cb(Error("Client has already been connected. You cannot reuse a client.")));return}this._connecting=!0,this.connectionParameters.getLibpqConnectionString(function(err,conString){if(self2.connectionParameters.nativeConnectionString)conString=self2.connectionParameters.nativeConnectionString;if(err)return cb(err);self2.native.connect(conString,function(err2){if(err2)return self2.native.end(),cb(err2);self2._connected=!0,self2.native.on("error",function(err3){self2._queryable=!1,self2._errorAllQueries(err3),self2.emit("error",err3)}),self2.native.on("notification",function(msg){self2.emit("notification",{channel:msg.relname,payload:msg.extra})}),self2.emit("connect"),self2._pulseQueryQueue(!0),cb(null,this)})})},Client2.prototype.connect=function(callback){if(callback){this._connect(callback);return}return new this._Promise((resolve6,reject)=>{this._connect((error2)=>{if(error2)reject(error2);else resolve6(this)})})},Client2.prototype.query=function(config,values2,callback){let query,result,readTimeout,readTimeoutTimer,queryCallback;if(config===null||config===void 0)throw TypeError("Client was passed a null or undefined query");else if(typeof config.submit==="function"){if(readTimeout=config.query_timeout||this.connectionParameters.query_timeout,result=query=config,typeof values2==="function")config.callback=values2}else if(readTimeout=config.query_timeout||this.connectionParameters.query_timeout,query=new NativeQuery(config,values2,callback),!query.callback){let resolveOut,rejectOut;result=new this._Promise((resolve6,reject)=>{resolveOut=resolve6,rejectOut=reject}).catch((err)=>{throw Error.captureStackTrace(err),err}),query.callback=(err,res)=>err?rejectOut(err):resolveOut(res)}if(readTimeout)queryCallback=query.callback||(()=>{}),readTimeoutTimer=setTimeout(()=>{let error2=Error("Query read timeout");process.nextTick(()=>{query.handleError(error2,this.connection)}),queryCallback(error2),query.callback=()=>{};let index=this._queryQueue.indexOf(query);if(index>-1)this._queryQueue.splice(index,1);this._pulseQueryQueue()},readTimeout),query.callback=(err,res)=>{clearTimeout(readTimeoutTimer),queryCallback(err,res)};if(!this._queryable)return query.native=this.native,process.nextTick(()=>{query.handleError(Error("Client has encountered a connection error and is not queryable"))}),result;if(this._ending)return query.native=this.native,process.nextTick(()=>{query.handleError(Error("Client was closed and is not queryable"))}),result;if(this._queryQueue.length>0)queryQueueLengthDeprecationNotice();return this._queryQueue.push(query),this._pulseQueryQueue(),result},Client2.prototype.end=function(cb){let self2=this;if(this._ending=!0,!this._connected)this.once("connect",this.end.bind(this,cb));let result;if(!cb)result=new this._Promise(function(resolve6,reject){cb=(err)=>err?reject(err):resolve6()});return this.native.end(function(){self2._connected=!1,self2._errorAllQueries(Error("Connection terminated")),process.nextTick(()=>{if(self2.emit("end"),cb)cb()})}),result},Client2.prototype._hasActiveQuery=function(){return this._activeQuery&&this._activeQuery.state!=="error"&&this._activeQuery.state!=="end"},Client2.prototype._pulseQueryQueue=function(initialConnection){if(!this._connected)return;if(this._hasActiveQuery())return;let query=this._queryQueue.shift();if(!query){if(!initialConnection)this.emit("drain");return}this._activeQuery=query,query.submit(this);let self2=this;query.once("_done",function(){self2._pulseQueryQueue()})},Client2.prototype.cancel=function(query){if(this._activeQuery===query)this.native.cancel(function(){});else if(this._queryQueue.indexOf(query)!==-1)this._queryQueue.splice(this._queryQueue.indexOf(query),1)},Client2.prototype.ref=function(){},Client2.prototype.unref=function(){},Client2.prototype.setTypeParser=function(oid,format,parseFn){return this._types.setTypeParser(oid,format,parseFn)},Client2.prototype.getTypeParser=function(oid,format){return this._types.getTypeParser(oid,format)},Client2.prototype.isConnected=function(){return this._connected}}),require_lib2=__commonJS2((exports,module)=>{var Client2=require_client(),defaults2=require_defaults2(),Connection=require_connection(),Result=require_result(),utils2=require_utils2(),Pool=require_pg_pool(),TypeOverrides=require_type_overrides(),{DatabaseError}=require_dist(),{escapeIdentifier,escapeLiteral}=require_utils2(),poolFactory=(Client22)=>{return class extends Pool{constructor(options2){super(options2,Client22)}}},PG=function(clientConstructor2){this.defaults=defaults2,this.Client=clientConstructor2,this.Query=this.Client.Query,this.Pool=poolFactory(this.Client),this._pools=[],this.Connection=Connection,this.types=require_pg_types(),this.DatabaseError=DatabaseError,this.TypeOverrides=TypeOverrides,this.escapeIdentifier=escapeIdentifier,this.escapeLiteral=escapeLiteral,this.Result=Result,this.utils=utils2},clientConstructor=Client2,forceNative=!1;try{forceNative=!!process.env.NODE_PG_FORCE_NATIVE}catch{}if(forceNative)clientConstructor=require_client2();module.exports=new PG(clientConstructor),Object.defineProperty(module.exports,"native",{configurable:!0,enumerable:!1,get(){let native=null;try{native=new PG(require_client2())}catch(err){if(err.code!=="MODULE_NOT_FOUND")throw err}return Object.defineProperty(module.exports,"native",{value:native}),native}})}),init_esm=__esm2(()=>{import_lib=__toESM2(require_lib2(),1),Client2=import_lib.default.Client,Pool=import_lib.default.Pool,Connection=import_lib.default.Connection,types3=import_lib.default.types,Query=import_lib.default.Query,DatabaseError=import_lib.default.DatabaseError,escapeIdentifier=import_lib.default.escapeIdentifier,escapeLiteral=import_lib.default.escapeLiteral,Result=import_lib.default.Result,TypeOverrides=import_lib.default.TypeOverrides,defaults2=import_lib.default.defaults,esm_default=import_lib.default});init_adapter=__esm2(()=>{init_esm()}),init_util=__esm2(()=>{(function(util2){util2.assertEqual=(_)=>{};function assertIs(_arg){}util2.assertIs=assertIs;function assertNever3(_x){throw Error()}util2.assertNever=assertNever3,util2.arrayToEnum=(items)=>{let obj={};for(let item of items)obj[item]=item;return obj},util2.getValidEnumValues=(obj)=>{let validKeys=util2.objectKeys(obj).filter((k)=>typeof obj[obj[k]]!=="number"),filtered={};for(let k of validKeys)filtered[k]=obj[k];return util2.objectValues(filtered)},util2.objectValues=(obj)=>{return util2.objectKeys(obj).map(function(e){return obj[e]})},util2.objectKeys=typeof Object.keys==="function"?(obj)=>Object.keys(obj):(object)=>{let keys=[];for(let key in object)if(Object.prototype.hasOwnProperty.call(object,key))keys.push(key);return keys},util2.find=(arr,checker)=>{for(let item of arr)if(checker(item))return item;return},util2.isInteger=typeof Number.isInteger==="function"?(val)=>Number.isInteger(val):(val)=>typeof val==="number"&&Number.isFinite(val)&&Math.floor(val)===val;function joinValues(array,separator=" | "){return array.map((val)=>typeof val==="string"?`'${val}'`:val).join(separator)}util2.joinValues=joinValues,util2.jsonStringifyReplacer=(_,value)=>{if(typeof value==="bigint")return value.toString();return value}})(util||(util={})),function(objectUtil2){objectUtil2.mergeShapes=(first,second)=>{return{...first,...second}}}(objectUtil||(objectUtil={})),ZodParsedType=util.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"])}),init_ZodError=__esm2(()=>{init_util(),ZodIssueCode=util.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),ZodError=class ZodError2 extends Error{get errors(){return this.issues}constructor(issues){super();this.issues=[],this.addIssue=(sub)=>{this.issues=[...this.issues,sub]},this.addIssues=(subs=[])=>{this.issues=[...this.issues,...subs]};let actualProto=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,actualProto);else this.__proto__=actualProto;this.name="ZodError",this.issues=issues}format(_mapper){let mapper=_mapper||function(issue){return issue.message},fieldErrors={_errors:[]},processError=(error2)=>{for(let issue of error2.issues)if(issue.code==="invalid_union")issue.unionErrors.map(processError);else if(issue.code==="invalid_return_type")processError(issue.returnTypeError);else if(issue.code==="invalid_arguments")processError(issue.argumentsError);else if(issue.path.length===0)fieldErrors._errors.push(mapper(issue));else{let curr=fieldErrors,i=0;while(i<issue.path.length){let el=issue.path[i];if(i!==issue.path.length-1)curr[el]=curr[el]||{_errors:[]};else curr[el]=curr[el]||{_errors:[]},curr[el]._errors.push(mapper(issue));curr=curr[el],i++}}};return processError(this),fieldErrors}static assert(value){if(!(value instanceof ZodError2))throw Error(`Not a ZodError: ${value}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,util.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(mapper=(issue)=>issue.message){let fieldErrors={},formErrors=[];for(let sub of this.issues)if(sub.path.length>0){let firstEl=sub.path[0];fieldErrors[firstEl]=fieldErrors[firstEl]||[],fieldErrors[firstEl].push(mapper(sub))}else formErrors.push(mapper(sub));return{formErrors,fieldErrors}}get formErrors(){return this.flatten()}},ZodError.create=(issues)=>{return new ZodError(issues)}}),init_en=__esm2(()=>{init_ZodError(),init_util(),en_default=errorMap});init_errors2=__esm2(()=>{init_en(),overrideErrorMap=en_default});init_parseUtil=__esm2(()=>{init_errors2(),init_en(),EMPTY_PATH=[],INVALID=Object.freeze({status:"aborted"})}),init_errorUtil=__esm2(()=>{(function(errorUtil2){errorUtil2.errToObj=(message)=>typeof message==="string"?{message}:message||{},errorUtil2.toString=(message)=>typeof message==="string"?message:message?.message})(errorUtil||(errorUtil={}))});init_types3=__esm2(()=>{init_ZodError(),init_errors2(),init_errorUtil(),init_parseUtil(),init_util(),cuidRegex=/^c[^\s-]{8,}$/i,cuid2Regex=/^[0-9a-z]+$/,ulidRegex=/^[0-9A-HJKMNP-TV-Z]{26}$/i,uuidRegex=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,nanoidRegex=/^[a-z0-9_-]{21}$/i,jwtRegex=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,durationRegex=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,emailRegex=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,ipv4Regex=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4CidrRegex=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6Regex=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,ipv6CidrRegex=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64Regex=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64urlRegex=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,dateRegex=new RegExp(`^${dateRegexSource}$`),ZodString=class ZodString2 extends ZodType{_parse(input){if(this._def.coerce)input.data=String(input.data);if(this._getType(input)!==ZodParsedType.string){let ctx2=this._getOrReturnCtx(input);return addIssueToContext(ctx2,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.string,received:ctx2.parsedType}),INVALID}let status=new ParseStatus,ctx=void 0;for(let check of this._def.checks)if(check.kind==="min"){if(input.data.length<check.value)ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{code:ZodIssueCode.too_small,minimum:check.value,type:"string",inclusive:!0,exact:!1,message:check.message}),status.dirty()}else if(check.kind==="max"){if(input.data.length>check.value)ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{code:ZodIssueCode.too_big,maximum:check.value,type:"string",inclusive:!0,exact:!1,message:check.message}),status.dirty()}else if(check.kind==="length"){let tooBig=input.data.length>check.value,tooSmall=input.data.length<check.value;if(tooBig||tooSmall){if(ctx=this._getOrReturnCtx(input,ctx),tooBig)addIssueToContext(ctx,{code:ZodIssueCode.too_big,maximum:check.value,type:"string",inclusive:!0,exact:!0,message:check.message});else if(tooSmall)addIssueToContext(ctx,{code:ZodIssueCode.too_small,minimum:check.value,type:"string",inclusive:!0,exact:!0,message:check.message});status.dirty()}}else if(check.kind==="email"){if(!emailRegex.test(input.data))ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{validation:"email",code:ZodIssueCode.invalid_string,message:check.message}),status.dirty()}else if(check.kind==="emoji"){if(!emojiRegex)emojiRegex=new RegExp(_emojiRegex,"u");if(!emojiRegex.test(input.data))ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{validation:"emoji",code:ZodIssueCode.invalid_string,message:check.message}),status.dirty()}else if(check.kind==="uuid"){if(!uuidRegex.test(input.data))ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{validation:"uuid",code:ZodIssueCode.invalid_string,message:check.message}),status.dirty()}else if(check.kind==="nanoid"){if(!nanoidRegex.test(input.data))ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{validation:"nanoid",code:ZodIssueCode.invalid_string,message:check.message}),status.dirty()}else if(check.kind==="cuid"){if(!cuidRegex.test(input.data))ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{validation:"cuid",code:ZodIssueCode.invalid_string,message:check.message}),status.dirty()}else if(check.kind==="cuid2"){if(!cuid2Regex.test(input.data))ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{validation:"cuid2",code:ZodIssueCode.invalid_string,message:check.message}),status.dirty()}else if(check.kind==="ulid"){if(!ulidRegex.test(input.data))ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{validation:"ulid",code:ZodIssueCode.invalid_string,message:check.message}),status.dirty()}else if(check.kind==="url")try{new URL(input.data)}catch{ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{validation:"url",code:ZodIssueCode.invalid_string,message:check.message}),status.dirty()}else if(check.kind==="regex"){if(check.regex.lastIndex=0,!check.regex.test(input.data))ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{validation:"regex",code:ZodIssueCode.invalid_string,message:check.message}),status.dirty()}else if(check.kind==="trim")input.data=input.data.trim();else if(check.kind==="includes"){if(!input.data.includes(check.value,check.position))ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{code:ZodIssueCode.invalid_string,validation:{includes:check.value,position:check.position},message:check.message}),status.dirty()}else if(check.kind==="toLowerCase")input.data=input.data.toLowerCase();else if(check.kind==="toUpperCase")input.data=input.data.toUpperCase();else if(check.kind==="startsWith"){if(!input.data.startsWith(check.value))ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{code:ZodIssueCode.invalid_string,validation:{startsWith:check.value},message:check.message}),status.dirty()}else if(check.kind==="endsWith"){if(!input.data.endsWith(check.value))ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{code:ZodIssueCode.invalid_string,validation:{endsWith:check.value},message:check.message}),status.dirty()}else if(check.kind==="datetime"){if(!datetimeRegex(check).test(input.data))ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{code:ZodIssueCode.invalid_string,validation:"datetime",message:check.message}),status.dirty()}else if(check.kind==="date"){if(!dateRegex.test(input.data))ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{code:ZodIssueCode.invalid_string,validation:"date",message:check.message}),status.dirty()}else if(check.kind==="time"){if(!timeRegex(check).test(input.data))ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{code:ZodIssueCode.invalid_string,validation:"time",message:check.message}),status.dirty()}else if(check.kind==="duration"){if(!durationRegex.test(input.data))ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{validation:"duration",code:ZodIssueCode.invalid_string,message:check.message}),status.dirty()}else if(check.kind==="ip"){if(!isValidIP(input.data,check.version))ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{validation:"ip",code:ZodIssueCode.invalid_string,message:check.message}),status.dirty()}else if(check.kind==="jwt"){if(!isValidJWT(input.data,check.alg))ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{validation:"jwt",code:ZodIssueCode.invalid_string,message:check.message}),status.dirty()}else if(check.kind==="cidr"){if(!isValidCidr(input.data,check.version))ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{validation:"cidr",code:ZodIssueCode.invalid_string,message:check.message}),status.dirty()}else if(check.kind==="base64"){if(!base64Regex.test(input.data))ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{validation:"base64",code:ZodIssueCode.invalid_string,message:check.message}),status.dirty()}else if(check.kind==="base64url"){if(!base64urlRegex.test(input.data))ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{validation:"base64url",code:ZodIssueCode.invalid_string,message:check.message}),status.dirty()}else util.assertNever(check);return{status:status.value,value:input.data}}_regex(regex,validation,message){return this.refinement((data)=>regex.test(data),{validation,code:ZodIssueCode.invalid_string,...errorUtil.errToObj(message)})}_addCheck(check){return new ZodString2({...this._def,checks:[...this._def.checks,check]})}email(message){return this._addCheck({kind:"email",...errorUtil.errToObj(message)})}url(message){return this._addCheck({kind:"url",...errorUtil.errToObj(message)})}emoji(message){return this._addCheck({kind:"emoji",...errorUtil.errToObj(message)})}uuid(message){return this._addCheck({kind:"uuid",...errorUtil.errToObj(message)})}nanoid(message){return this._addCheck({kind:"nanoid",...errorUtil.errToObj(message)})}cuid(message){return this._addCheck({kind:"cuid",...errorUtil.errToObj(message)})}cuid2(message){return this._addCheck({kind:"cuid2",...errorUtil.errToObj(message)})}ulid(message){return this._addCheck({kind:"ulid",...errorUtil.errToObj(message)})}base64(message){return this._addCheck({kind:"base64",...errorUtil.errToObj(message)})}base64url(message){return this._addCheck({kind:"base64url",...errorUtil.errToObj(message)})}jwt(options2){return this._addCheck({kind:"jwt",...errorUtil.errToObj(options2)})}ip(options2){return this._addCheck({kind:"ip",...errorUtil.errToObj(options2)})}cidr(options2){return this._addCheck({kind:"cidr",...errorUtil.errToObj(options2)})}datetime(options2){if(typeof options2==="string")return this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:options2});return this._addCheck({kind:"datetime",precision:typeof options2?.precision>"u"?null:options2?.precision,offset:options2?.offset??!1,local:options2?.local??!1,...errorUtil.errToObj(options2?.message)})}date(message){return this._addCheck({kind:"date",message})}time(options2){if(typeof options2==="string")return this._addCheck({kind:"time",precision:null,message:options2});return this._addCheck({kind:"time",precision:typeof options2?.precision>"u"?null:options2?.precision,...errorUtil.errToObj(options2?.message)})}duration(message){return this._addCheck({kind:"duration",...errorUtil.errToObj(message)})}regex(regex,message){return this._addCheck({kind:"regex",regex,...errorUtil.errToObj(message)})}includes(value,options2){return this._addCheck({kind:"includes",value,position:options2?.position,...errorUtil.errToObj(options2?.message)})}startsWith(value,message){return this._addCheck({kind:"startsWith",value,...errorUtil.errToObj(message)})}endsWith(value,message){return this._addCheck({kind:"endsWith",value,...errorUtil.errToObj(message)})}min(minLength,message){return this._addCheck({kind:"min",value:minLength,...errorUtil.errToObj(message)})}max(maxLength,message){return this._addCheck({kind:"max",value:maxLength,...errorUtil.errToObj(message)})}length(len,message){return this._addCheck({kind:"length",value:len,...errorUtil.errToObj(message)})}nonempty(message){return this.min(1,errorUtil.errToObj(message))}trim(){return new ZodString2({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new ZodString2({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new ZodString2({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find((ch)=>ch.kind==="datetime")}get isDate(){return!!this._def.checks.find((ch)=>ch.kind==="date")}get isTime(){return!!this._def.checks.find((ch)=>ch.kind==="time")}get isDuration(){return!!this._def.checks.find((ch)=>ch.kind==="duration")}get isEmail(){return!!this._def.checks.find((ch)=>ch.kind==="email")}get isURL(){return!!this._def.checks.find((ch)=>ch.kind==="url")}get isEmoji(){return!!this._def.checks.find((ch)=>ch.kind==="emoji")}get isUUID(){return!!this._def.checks.find((ch)=>ch.kind==="uuid")}get isNANOID(){return!!this._def.checks.find((ch)=>ch.kind==="nanoid")}get isCUID(){return!!this._def.checks.find((ch)=>ch.kind==="cuid")}get isCUID2(){return!!this._def.checks.find((ch)=>ch.kind==="cuid2")}get isULID(){return!!this._def.checks.find((ch)=>ch.kind==="ulid")}get isIP(){return!!this._def.checks.find((ch)=>ch.kind==="ip")}get isCIDR(){return!!this._def.checks.find((ch)=>ch.kind==="cidr")}get isBase64(){return!!this._def.checks.find((ch)=>ch.kind==="base64")}get isBase64url(){return!!this._def.checks.find((ch)=>ch.kind==="base64url")}get minLength(){let min=null;for(let ch of this._def.checks)if(ch.kind==="min"){if(min===null||ch.value>min)min=ch.value}return min}get maxLength(){let max=null;for(let ch of this._def.checks)if(ch.kind==="max"){if(max===null||ch.value<max)max=ch.value}return max}},ZodString.create=(params)=>{return new ZodString({checks:[],typeName:ZodFirstPartyTypeKind.ZodString,coerce:params?.coerce??!1,...processCreateParams(params)})},ZodNumber=class ZodNumber2 extends ZodType{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(input){if(this._def.coerce)input.data=Number(input.data);if(this._getType(input)!==ZodParsedType.number){let ctx2=this._getOrReturnCtx(input);return addIssueToContext(ctx2,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.number,received:ctx2.parsedType}),INVALID}let ctx=void 0,status=new ParseStatus;for(let check of this._def.checks)if(check.kind==="int"){if(!util.isInteger(input.data))ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:"integer",received:"float",message:check.message}),status.dirty()}else if(check.kind==="min"){if(check.inclusive?input.data<check.value:input.data<=check.value)ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{code:ZodIssueCode.too_small,minimum:check.value,type:"number",inclusive:check.inclusive,exact:!1,message:check.message}),status.dirty()}else if(check.kind==="max"){if(check.inclusive?input.data>check.value:input.data>=check.value)ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{code:ZodIssueCode.too_big,maximum:check.value,type:"number",inclusive:check.inclusive,exact:!1,message:check.message}),status.dirty()}else if(check.kind==="multipleOf"){if(floatSafeRemainder(input.data,check.value)!==0)ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{code:ZodIssueCode.not_multiple_of,multipleOf:check.value,message:check.message}),status.dirty()}else if(check.kind==="finite"){if(!Number.isFinite(input.data))ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{code:ZodIssueCode.not_finite,message:check.message}),status.dirty()}else util.assertNever(check);return{status:status.value,value:input.data}}gte(value,message){return this.setLimit("min",value,!0,errorUtil.toString(message))}gt(value,message){return this.setLimit("min",value,!1,errorUtil.toString(message))}lte(value,message){return this.setLimit("max",value,!0,errorUtil.toString(message))}lt(value,message){return this.setLimit("max",value,!1,errorUtil.toString(message))}setLimit(kind,value,inclusive,message){return new ZodNumber2({...this._def,checks:[...this._def.checks,{kind,value,inclusive,message:errorUtil.toString(message)}]})}_addCheck(check){return new ZodNumber2({...this._def,checks:[...this._def.checks,check]})}int(message){return this._addCheck({kind:"int",message:errorUtil.toString(message)})}positive(message){return this._addCheck({kind:"min",value:0,inclusive:!1,message:errorUtil.toString(message)})}negative(message){return this._addCheck({kind:"max",value:0,inclusive:!1,message:errorUtil.toString(message)})}nonpositive(message){return this._addCheck({kind:"max",value:0,inclusive:!0,message:errorUtil.toString(message)})}nonnegative(message){return this._addCheck({kind:"min",value:0,inclusive:!0,message:errorUtil.toString(message)})}multipleOf(value,message){return this._addCheck({kind:"multipleOf",value,message:errorUtil.toString(message)})}finite(message){return this._addCheck({kind:"finite",message:errorUtil.toString(message)})}safe(message){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:errorUtil.toString(message)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:errorUtil.toString(message)})}get minValue(){let min=null;for(let ch of this._def.checks)if(ch.kind==="min"){if(min===null||ch.value>min)min=ch.value}return min}get maxValue(){let max=null;for(let ch of this._def.checks)if(ch.kind==="max"){if(max===null||ch.value<max)max=ch.value}return max}get isInt(){return!!this._def.checks.find((ch)=>ch.kind==="int"||ch.kind==="multipleOf"&&util.isInteger(ch.value))}get isFinite(){let max=null,min=null;for(let ch of this._def.checks)if(ch.kind==="finite"||ch.kind==="int"||ch.kind==="multipleOf")return!0;else if(ch.kind==="min"){if(min===null||ch.value>min)min=ch.value}else if(ch.kind==="max"){if(max===null||ch.value<max)max=ch.value}return Number.isFinite(min)&&Number.isFinite(max)}},ZodNumber.create=(params)=>{return new ZodNumber({checks:[],typeName:ZodFirstPartyTypeKind.ZodNumber,coerce:params?.coerce||!1,...processCreateParams(params)})},ZodBigInt=class ZodBigInt2 extends ZodType{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse(input){if(this._def.coerce)try{input.data=BigInt(input.data)}catch{return this._getInvalidInput(input)}if(this._getType(input)!==ZodParsedType.bigint)return this._getInvalidInput(input);let ctx=void 0,status=new ParseStatus;for(let check of this._def.checks)if(check.kind==="min"){if(check.inclusive?input.data<check.value:input.data<=check.value)ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{code:ZodIssueCode.too_small,type:"bigint",minimum:check.value,inclusive:check.inclusive,message:check.message}),status.dirty()}else if(check.kind==="max"){if(check.inclusive?input.data>check.value:input.data>=check.value)ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{code:ZodIssueCode.too_big,type:"bigint",maximum:check.value,inclusive:check.inclusive,message:check.message}),status.dirty()}else if(check.kind==="multipleOf"){if(input.data%check.value!==BigInt(0))ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{code:ZodIssueCode.not_multiple_of,multipleOf:check.value,message:check.message}),status.dirty()}else util.assertNever(check);return{status:status.value,value:input.data}}_getInvalidInput(input){let ctx=this._getOrReturnCtx(input);return addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.bigint,received:ctx.parsedType}),INVALID}gte(value,message){return this.setLimit("min",value,!0,errorUtil.toString(message))}gt(value,message){return this.setLimit("min",value,!1,errorUtil.toString(message))}lte(value,message){return this.setLimit("max",value,!0,errorUtil.toString(message))}lt(value,message){return this.setLimit("max",value,!1,errorUtil.toString(message))}setLimit(kind,value,inclusive,message){return new ZodBigInt2({...this._def,checks:[...this._def.checks,{kind,value,inclusive,message:errorUtil.toString(message)}]})}_addCheck(check){return new ZodBigInt2({...this._def,checks:[...this._def.checks,check]})}positive(message){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:errorUtil.toString(message)})}negative(message){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:errorUtil.toString(message)})}nonpositive(message){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:errorUtil.toString(message)})}nonnegative(message){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:errorUtil.toString(message)})}multipleOf(value,message){return this._addCheck({kind:"multipleOf",value,message:errorUtil.toString(message)})}get minValue(){let min=null;for(let ch of this._def.checks)if(ch.kind==="min"){if(min===null||ch.value>min)min=ch.value}return min}get maxValue(){let max=null;for(let ch of this._def.checks)if(ch.kind==="max"){if(max===null||ch.value<max)max=ch.value}return max}},ZodBigInt.create=(params)=>{return new ZodBigInt({checks:[],typeName:ZodFirstPartyTypeKind.ZodBigInt,coerce:params?.coerce??!1,...processCreateParams(params)})},ZodBoolean=class extends ZodType{_parse(input){if(this._def.coerce)input.data=Boolean(input.data);if(this._getType(input)!==ZodParsedType.boolean){let ctx=this._getOrReturnCtx(input);return addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.boolean,received:ctx.parsedType}),INVALID}return OK(input.data)}},ZodBoolean.create=(params)=>{return new ZodBoolean({typeName:ZodFirstPartyTypeKind.ZodBoolean,coerce:params?.coerce||!1,...processCreateParams(params)})},ZodDate=class ZodDate2 extends ZodType{_parse(input){if(this._def.coerce)input.data=new Date(input.data);if(this._getType(input)!==ZodParsedType.date){let ctx2=this._getOrReturnCtx(input);return addIssueToContext(ctx2,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.date,received:ctx2.parsedType}),INVALID}if(Number.isNaN(input.data.getTime())){let ctx2=this._getOrReturnCtx(input);return addIssueToContext(ctx2,{code:ZodIssueCode.invalid_date}),INVALID}let status=new ParseStatus,ctx=void 0;for(let check of this._def.checks)if(check.kind==="min"){if(input.data.getTime()<check.value)ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{code:ZodIssueCode.too_small,message:check.message,inclusive:!0,exact:!1,minimum:check.value,type:"date"}),status.dirty()}else if(check.kind==="max"){if(input.data.getTime()>check.value)ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{code:ZodIssueCode.too_big,message:check.message,inclusive:!0,exact:!1,maximum:check.value,type:"date"}),status.dirty()}else util.assertNever(check);return{status:status.value,value:new Date(input.data.getTime())}}_addCheck(check){return new ZodDate2({...this._def,checks:[...this._def.checks,check]})}min(minDate,message){return this._addCheck({kind:"min",value:minDate.getTime(),message:errorUtil.toString(message)})}max(maxDate,message){return this._addCheck({kind:"max",value:maxDate.getTime(),message:errorUtil.toString(message)})}get minDate(){let min=null;for(let ch of this._def.checks)if(ch.kind==="min"){if(min===null||ch.value>min)min=ch.value}return min!=null?new Date(min):null}get maxDate(){let max=null;for(let ch of this._def.checks)if(ch.kind==="max"){if(max===null||ch.value<max)max=ch.value}return max!=null?new Date(max):null}},ZodDate.create=(params)=>{return new ZodDate({checks:[],coerce:params?.coerce||!1,typeName:ZodFirstPartyTypeKind.ZodDate,...processCreateParams(params)})},ZodSymbol=class extends ZodType{_parse(input){if(this._getType(input)!==ZodParsedType.symbol){let ctx=this._getOrReturnCtx(input);return addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.symbol,received:ctx.parsedType}),INVALID}return OK(input.data)}},ZodSymbol.create=(params)=>{return new ZodSymbol({typeName:ZodFirstPartyTypeKind.ZodSymbol,...processCreateParams(params)})},ZodUndefined=class extends ZodType{_parse(input){if(this._getType(input)!==ZodParsedType.undefined){let ctx=this._getOrReturnCtx(input);return addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.undefined,received:ctx.parsedType}),INVALID}return OK(input.data)}},ZodUndefined.create=(params)=>{return new ZodUndefined({typeName:ZodFirstPartyTypeKind.ZodUndefined,...processCreateParams(params)})},ZodNull=class extends ZodType{_parse(input){if(this._getType(input)!==ZodParsedType.null){let ctx=this._getOrReturnCtx(input);return addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.null,received:ctx.parsedType}),INVALID}return OK(input.data)}},ZodNull.create=(params)=>{return new ZodNull({typeName:ZodFirstPartyTypeKind.ZodNull,...processCreateParams(params)})},ZodAny=class extends ZodType{constructor(){super(...arguments);this._any=!0}_parse(input){return OK(input.data)}},ZodAny.create=(params)=>{return new ZodAny({typeName:ZodFirstPartyTypeKind.ZodAny,...processCreateParams(params)})},ZodUnknown=class extends ZodType{constructor(){super(...arguments);this._unknown=!0}_parse(input){return OK(input.data)}},ZodUnknown.create=(params)=>{return new ZodUnknown({typeName:ZodFirstPartyTypeKind.ZodUnknown,...processCreateParams(params)})},ZodNever=class extends ZodType{_parse(input){let ctx=this._getOrReturnCtx(input);return addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.never,received:ctx.parsedType}),INVALID}},ZodNever.create=(params)=>{return new ZodNever({typeName:ZodFirstPartyTypeKind.ZodNever,...processCreateParams(params)})},ZodVoid=class extends ZodType{_parse(input){if(this._getType(input)!==ZodParsedType.undefined){let ctx=this._getOrReturnCtx(input);return addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.void,received:ctx.parsedType}),INVALID}return OK(input.data)}},ZodVoid.create=(params)=>{return new ZodVoid({typeName:ZodFirstPartyTypeKind.ZodVoid,...processCreateParams(params)})},ZodArray=class ZodArray2 extends ZodType{_parse(input){let{ctx,status}=this._processInputParams(input),def=this._def;if(ctx.parsedType!==ZodParsedType.array)return addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.array,received:ctx.parsedType}),INVALID;if(def.exactLength!==null){let tooBig=ctx.data.length>def.exactLength.value,tooSmall=ctx.data.length<def.exactLength.value;if(tooBig||tooSmall)addIssueToContext(ctx,{code:tooBig?ZodIssueCode.too_big:ZodIssueCode.too_small,minimum:tooSmall?def.exactLength.value:void 0,maximum:tooBig?def.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:def.exactLength.message}),status.dirty()}if(def.minLength!==null){if(ctx.data.length<def.minLength.value)addIssueToContext(ctx,{code:ZodIssueCode.too_small,minimum:def.minLength.value,type:"array",inclusive:!0,exact:!1,message:def.minLength.message}),status.dirty()}if(def.maxLength!==null){if(ctx.data.length>def.maxLength.value)addIssueToContext(ctx,{code:ZodIssueCode.too_big,maximum:def.maxLength.value,type:"array",inclusive:!0,exact:!1,message:def.maxLength.message}),status.dirty()}if(ctx.common.async)return Promise.all([...ctx.data].map((item,i)=>{return def.type._parseAsync(new ParseInputLazyPath(ctx,item,ctx.path,i))})).then((result2)=>{return ParseStatus.mergeArray(status,result2)});let result=[...ctx.data].map((item,i)=>{return def.type._parseSync(new ParseInputLazyPath(ctx,item,ctx.path,i))});return ParseStatus.mergeArray(status,result)}get element(){return this._def.type}min(minLength,message){return new ZodArray2({...this._def,minLength:{value:minLength,message:errorUtil.toString(message)}})}max(maxLength,message){return new ZodArray2({...this._def,maxLength:{value:maxLength,message:errorUtil.toString(message)}})}length(len,message){return new ZodArray2({...this._def,exactLength:{value:len,message:errorUtil.toString(message)}})}nonempty(message){return this.min(1,message)}},ZodArray.create=(schema,params)=>{return new ZodArray({type:schema,minLength:null,maxLength:null,exactLength:null,typeName:ZodFirstPartyTypeKind.ZodArray,...processCreateParams(params)})},ZodObject=class ZodObject2 extends ZodType{constructor(){super(...arguments);this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let shape=this._def.shape(),keys=util.objectKeys(shape);return this._cached={shape,keys},this._cached}_parse(input){if(this._getType(input)!==ZodParsedType.object){let ctx2=this._getOrReturnCtx(input);return addIssueToContext(ctx2,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:ctx2.parsedType}),INVALID}let{status,ctx}=this._processInputParams(input),{shape,keys:shapeKeys}=this._getCached(),extraKeys=[];if(!(this._def.catchall instanceof ZodNever&&this._def.unknownKeys==="strip")){for(let key in ctx.data)if(!shapeKeys.includes(key))extraKeys.push(key)}let pairs=[];for(let key of shapeKeys){let keyValidator=shape[key],value=ctx.data[key];pairs.push({key:{status:"valid",value:key},value:keyValidator._parse(new ParseInputLazyPath(ctx,value,ctx.path,key)),alwaysSet:key in ctx.data})}if(this._def.catchall instanceof ZodNever){let unknownKeys=this._def.unknownKeys;if(unknownKeys==="passthrough")for(let key of extraKeys)pairs.push({key:{status:"valid",value:key},value:{status:"valid",value:ctx.data[key]}});else if(unknownKeys==="strict"){if(extraKeys.length>0)addIssueToContext(ctx,{code:ZodIssueCode.unrecognized_keys,keys:extraKeys}),status.dirty()}else if(unknownKeys==="strip");else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let catchall=this._def.catchall;for(let key of extraKeys){let value=ctx.data[key];pairs.push({key:{status:"valid",value:key},value:catchall._parse(new ParseInputLazyPath(ctx,value,ctx.path,key)),alwaysSet:key in ctx.data})}}if(ctx.common.async)return Promise.resolve().then(async()=>{let syncPairs=[];for(let pair of pairs){let key=await pair.key,value=await pair.value;syncPairs.push({key,value,alwaysSet:pair.alwaysSet})}return syncPairs}).then((syncPairs)=>{return ParseStatus.mergeObjectSync(status,syncPairs)});else return ParseStatus.mergeObjectSync(status,pairs)}get shape(){return this._def.shape()}strict(message){return errorUtil.errToObj,new ZodObject2({...this._def,unknownKeys:"strict",...message!==void 0?{errorMap:(issue,ctx)=>{let defaultError=this._def.errorMap?.(issue,ctx).message??ctx.defaultError;if(issue.code==="unrecognized_keys")return{message:errorUtil.errToObj(message).message??defaultError};return{message:defaultError}}}:{}})}strip(){return new ZodObject2({...this._def,unknownKeys:"strip"})}passthrough(){return new ZodObject2({...this._def,unknownKeys:"passthrough"})}extend(augmentation){return new ZodObject2({...this._def,shape:()=>({...this._def.shape(),...augmentation})})}merge(merging){return new ZodObject2({unknownKeys:merging._def.unknownKeys,catchall:merging._def.catchall,shape:()=>({...this._def.shape(),...merging._def.shape()}),typeName:ZodFirstPartyTypeKind.ZodObject})}setKey(key,schema){return this.augment({[key]:schema})}catchall(index){return new ZodObject2({...this._def,catchall:index})}pick(mask){let shape={};for(let key of util.objectKeys(mask))if(mask[key]&&this.shape[key])shape[key]=this.shape[key];return new ZodObject2({...this._def,shape:()=>shape})}omit(mask){let shape={};for(let key of util.objectKeys(this.shape))if(!mask[key])shape[key]=this.shape[key];return new ZodObject2({...this._def,shape:()=>shape})}deepPartial(){return deepPartialify(this)}partial(mask){let newShape={};for(let key of util.objectKeys(this.shape)){let fieldSchema=this.shape[key];if(mask&&!mask[key])newShape[key]=fieldSchema;else newShape[key]=fieldSchema.optional()}return new ZodObject2({...this._def,shape:()=>newShape})}required(mask){let newShape={};for(let key of util.objectKeys(this.shape))if(mask&&!mask[key])newShape[key]=this.shape[key];else{let newField=this.shape[key];while(newField instanceof ZodOptional)newField=newField._def.innerType;newShape[key]=newField}return new ZodObject2({...this._def,shape:()=>newShape})}keyof(){return createZodEnum(util.objectKeys(this.shape))}},ZodObject.create=(shape,params)=>{return new ZodObject({shape:()=>shape,unknownKeys:"strip",catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(params)})},ZodObject.strictCreate=(shape,params)=>{return new ZodObject({shape:()=>shape,unknownKeys:"strict",catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(params)})},ZodObject.lazycreate=(shape,params)=>{return new ZodObject({shape,unknownKeys:"strip",catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(params)})},ZodUnion=class extends ZodType{_parse(input){let{ctx}=this._processInputParams(input),options2=this._def.options;function handleResults(results){for(let result of results)if(result.result.status==="valid")return result.result;for(let result of results)if(result.result.status==="dirty")return ctx.common.issues.push(...result.ctx.common.issues),result.result;let unionErrors=results.map((result)=>new ZodError(result.ctx.common.issues));return addIssueToContext(ctx,{code:ZodIssueCode.invalid_union,unionErrors}),INVALID}if(ctx.common.async)return Promise.all(options2.map(async(option)=>{let childCtx={...ctx,common:{...ctx.common,issues:[]},parent:null};return{result:await option._parseAsync({data:ctx.data,path:ctx.path,parent:childCtx}),ctx:childCtx}})).then(handleResults);else{let dirty=void 0,issues=[];for(let option of options2){let childCtx={...ctx,common:{...ctx.common,issues:[]},parent:null},result=option._parseSync({data:ctx.data,path:ctx.path,parent:childCtx});if(result.status==="valid")return result;else if(result.status==="dirty"&&!dirty)dirty={result,ctx:childCtx};if(childCtx.common.issues.length)issues.push(childCtx.common.issues)}if(dirty)return ctx.common.issues.push(...dirty.ctx.common.issues),dirty.result;let unionErrors=issues.map((issues2)=>new ZodError(issues2));return addIssueToContext(ctx,{code:ZodIssueCode.invalid_union,unionErrors}),INVALID}}get options(){return this._def.options}},ZodUnion.create=(types22,params)=>{return new ZodUnion({options:types22,typeName:ZodFirstPartyTypeKind.ZodUnion,...processCreateParams(params)})},ZodDiscriminatedUnion=class ZodDiscriminatedUnion2 extends ZodType{_parse(input){let{ctx}=this._processInputParams(input);if(ctx.parsedType!==ZodParsedType.object)return addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:ctx.parsedType}),INVALID;let discriminator=this.discriminator,discriminatorValue=ctx.data[discriminator],option=this.optionsMap.get(discriminatorValue);if(!option)return addIssueToContext(ctx,{code:ZodIssueCode.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[discriminator]}),INVALID;if(ctx.common.async)return option._parseAsync({data:ctx.data,path:ctx.path,parent:ctx});else return option._parseSync({data:ctx.data,path:ctx.path,parent:ctx})}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(discriminator,options2,params){let optionsMap=new Map;for(let type of options2){let discriminatorValues=getDiscriminator(type.shape[discriminator]);if(!discriminatorValues.length)throw Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`);for(let value of discriminatorValues){if(optionsMap.has(value))throw Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);optionsMap.set(value,type)}}return new ZodDiscriminatedUnion2({typeName:ZodFirstPartyTypeKind.ZodDiscriminatedUnion,discriminator,options:options2,optionsMap,...processCreateParams(params)})}},ZodIntersection=class extends ZodType{_parse(input){let{status,ctx}=this._processInputParams(input),handleParsed=(parsedLeft,parsedRight)=>{if(isAborted(parsedLeft)||isAborted(parsedRight))return INVALID;let merged=mergeValues(parsedLeft.value,parsedRight.value);if(!merged.valid)return addIssueToContext(ctx,{code:ZodIssueCode.invalid_intersection_types}),INVALID;if(isDirty(parsedLeft)||isDirty(parsedRight))status.dirty();return{status:status.value,value:merged.data}};if(ctx.common.async)return Promise.all([this._def.left._parseAsync({data:ctx.data,path:ctx.path,parent:ctx}),this._def.right._parseAsync({data:ctx.data,path:ctx.path,parent:ctx})]).then(([left,right])=>handleParsed(left,right));else return handleParsed(this._def.left._parseSync({data:ctx.data,path:ctx.path,parent:ctx}),this._def.right._parseSync({data:ctx.data,path:ctx.path,parent:ctx}))}},ZodIntersection.create=(left,right,params)=>{return new ZodIntersection({left,right,typeName:ZodFirstPartyTypeKind.ZodIntersection,...processCreateParams(params)})},ZodTuple=class ZodTuple2 extends ZodType{_parse(input){let{status,ctx}=this._processInputParams(input);if(ctx.parsedType!==ZodParsedType.array)return addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.array,received:ctx.parsedType}),INVALID;if(ctx.data.length<this._def.items.length)return addIssueToContext(ctx,{code:ZodIssueCode.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),INVALID;if(!this._def.rest&&ctx.data.length>this._def.items.length)addIssueToContext(ctx,{code:ZodIssueCode.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),status.dirty();let items=[...ctx.data].map((item,itemIndex)=>{let schema=this._def.items[itemIndex]||this._def.rest;if(!schema)return null;return schema._parse(new ParseInputLazyPath(ctx,item,ctx.path,itemIndex))}).filter((x)=>!!x);if(ctx.common.async)return Promise.all(items).then((results)=>{return ParseStatus.mergeArray(status,results)});else return ParseStatus.mergeArray(status,items)}get items(){return this._def.items}rest(rest){return new ZodTuple2({...this._def,rest})}},ZodTuple.create=(schemas,params)=>{if(!Array.isArray(schemas))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new ZodTuple({items:schemas,typeName:ZodFirstPartyTypeKind.ZodTuple,rest:null,...processCreateParams(params)})},ZodRecord=class ZodRecord2 extends ZodType{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(input){let{status,ctx}=this._processInputParams(input);if(ctx.parsedType!==ZodParsedType.object)return addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:ctx.parsedType}),INVALID;let pairs=[],keyType=this._def.keyType,valueType=this._def.valueType;for(let key in ctx.data)pairs.push({key:keyType._parse(new ParseInputLazyPath(ctx,key,ctx.path,key)),value:valueType._parse(new ParseInputLazyPath(ctx,ctx.data[key],ctx.path,key)),alwaysSet:key in ctx.data});if(ctx.common.async)return ParseStatus.mergeObjectAsync(status,pairs);else return ParseStatus.mergeObjectSync(status,pairs)}get element(){return this._def.valueType}static create(first,second,third){if(second instanceof ZodType)return new ZodRecord2({keyType:first,valueType:second,typeName:ZodFirstPartyTypeKind.ZodRecord,...processCreateParams(third)});return new ZodRecord2({keyType:ZodString.create(),valueType:first,typeName:ZodFirstPartyTypeKind.ZodRecord,...processCreateParams(second)})}},ZodMap=class extends ZodType{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(input){let{status,ctx}=this._processInputParams(input);if(ctx.parsedType!==ZodParsedType.map)return addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.map,received:ctx.parsedType}),INVALID;let keyType=this._def.keyType,valueType=this._def.valueType,pairs=[...ctx.data.entries()].map(([key,value],index)=>{return{key:keyType._parse(new ParseInputLazyPath(ctx,key,ctx.path,[index,"key"])),value:valueType._parse(new ParseInputLazyPath(ctx,value,ctx.path,[index,"value"]))}});if(ctx.common.async){let finalMap=new Map;return Promise.resolve().then(async()=>{for(let pair of pairs){let key=await pair.key,value=await pair.value;if(key.status==="aborted"||value.status==="aborted")return INVALID;if(key.status==="dirty"||value.status==="dirty")status.dirty();finalMap.set(key.value,value.value)}return{status:status.value,value:finalMap}})}else{let finalMap=new Map;for(let pair of pairs){let{key,value}=pair;if(key.status==="aborted"||value.status==="aborted")return INVALID;if(key.status==="dirty"||value.status==="dirty")status.dirty();finalMap.set(key.value,value.value)}return{status:status.value,value:finalMap}}}},ZodMap.create=(keyType,valueType,params)=>{return new ZodMap({valueType,keyType,typeName:ZodFirstPartyTypeKind.ZodMap,...processCreateParams(params)})},ZodSet=class ZodSet2 extends ZodType{_parse(input){let{status,ctx}=this._processInputParams(input);if(ctx.parsedType!==ZodParsedType.set)return addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.set,received:ctx.parsedType}),INVALID;let def=this._def;if(def.minSize!==null){if(ctx.data.size<def.minSize.value)addIssueToContext(ctx,{code:ZodIssueCode.too_small,minimum:def.minSize.value,type:"set",inclusive:!0,exact:!1,message:def.minSize.message}),status.dirty()}if(def.maxSize!==null){if(ctx.data.size>def.maxSize.value)addIssueToContext(ctx,{code:ZodIssueCode.too_big,maximum:def.maxSize.value,type:"set",inclusive:!0,exact:!1,message:def.maxSize.message}),status.dirty()}let valueType=this._def.valueType;function finalizeSet(elements2){let parsedSet=new Set;for(let element of elements2){if(element.status==="aborted")return INVALID;if(element.status==="dirty")status.dirty();parsedSet.add(element.value)}return{status:status.value,value:parsedSet}}let elements=[...ctx.data.values()].map((item,i)=>valueType._parse(new ParseInputLazyPath(ctx,item,ctx.path,i)));if(ctx.common.async)return Promise.all(elements).then((elements2)=>finalizeSet(elements2));else return finalizeSet(elements)}min(minSize,message){return new ZodSet2({...this._def,minSize:{value:minSize,message:errorUtil.toString(message)}})}max(maxSize,message){return new ZodSet2({...this._def,maxSize:{value:maxSize,message:errorUtil.toString(message)}})}size(size,message){return this.min(size,message).max(size,message)}nonempty(message){return this.min(1,message)}},ZodSet.create=(valueType,params)=>{return new ZodSet({valueType,minSize:null,maxSize:null,typeName:ZodFirstPartyTypeKind.ZodSet,...processCreateParams(params)})},ZodFunction=class ZodFunction2 extends ZodType{constructor(){super(...arguments);this.validate=this.implement}_parse(input){let{ctx}=this._processInputParams(input);if(ctx.parsedType!==ZodParsedType.function)return addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.function,received:ctx.parsedType}),INVALID;function makeArgsIssue(args,error2){return makeIssue({data:args,path:ctx.path,errorMaps:[ctx.common.contextualErrorMap,ctx.schemaErrorMap,getErrorMap(),en_default].filter((x)=>!!x),issueData:{code:ZodIssueCode.invalid_arguments,argumentsError:error2}})}function makeReturnsIssue(returns,error2){return makeIssue({data:returns,path:ctx.path,errorMaps:[ctx.common.contextualErrorMap,ctx.schemaErrorMap,getErrorMap(),en_default].filter((x)=>!!x),issueData:{code:ZodIssueCode.invalid_return_type,returnTypeError:error2}})}let params={errorMap:ctx.common.contextualErrorMap},fn=ctx.data;if(this._def.returns instanceof ZodPromise){let me=this;return OK(async function(...args){let error2=new ZodError([]),parsedArgs=await me._def.args.parseAsync(args,params).catch((e)=>{throw error2.addIssue(makeArgsIssue(args,e)),error2}),result=await Reflect.apply(fn,this,parsedArgs);return await me._def.returns._def.type.parseAsync(result,params).catch((e)=>{throw error2.addIssue(makeReturnsIssue(result,e)),error2})})}else{let me=this;return OK(function(...args){let parsedArgs=me._def.args.safeParse(args,params);if(!parsedArgs.success)throw new ZodError([makeArgsIssue(args,parsedArgs.error)]);let result=Reflect.apply(fn,this,parsedArgs.data),parsedReturns=me._def.returns.safeParse(result,params);if(!parsedReturns.success)throw new ZodError([makeReturnsIssue(result,parsedReturns.error)]);return parsedReturns.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...items){return new ZodFunction2({...this._def,args:ZodTuple.create(items).rest(ZodUnknown.create())})}returns(returnType){return new ZodFunction2({...this._def,returns:returnType})}implement(func){return this.parse(func)}strictImplement(func){return this.parse(func)}static create(args,returns,params){return new ZodFunction2({args:args?args:ZodTuple.create([]).rest(ZodUnknown.create()),returns:returns||ZodUnknown.create(),typeName:ZodFirstPartyTypeKind.ZodFunction,...processCreateParams(params)})}},ZodLazy=class extends ZodType{get schema(){return this._def.getter()}_parse(input){let{ctx}=this._processInputParams(input);return this._def.getter()._parse({data:ctx.data,path:ctx.path,parent:ctx})}},ZodLazy.create=(getter,params)=>{return new ZodLazy({getter,typeName:ZodFirstPartyTypeKind.ZodLazy,...processCreateParams(params)})},ZodLiteral=class extends ZodType{_parse(input){if(input.data!==this._def.value){let ctx=this._getOrReturnCtx(input);return addIssueToContext(ctx,{received:ctx.data,code:ZodIssueCode.invalid_literal,expected:this._def.value}),INVALID}return{status:"valid",value:input.data}}get value(){return this._def.value}},ZodLiteral.create=(value,params)=>{return new ZodLiteral({value,typeName:ZodFirstPartyTypeKind.ZodLiteral,...processCreateParams(params)})},ZodEnum=class ZodEnum2 extends ZodType{_parse(input){if(typeof input.data!=="string"){let ctx=this._getOrReturnCtx(input),expectedValues=this._def.values;return addIssueToContext(ctx,{expected:util.joinValues(expectedValues),received:ctx.parsedType,code:ZodIssueCode.invalid_type}),INVALID}if(!this._cache)this._cache=new Set(this._def.values);if(!this._cache.has(input.data)){let ctx=this._getOrReturnCtx(input),expectedValues=this._def.values;return addIssueToContext(ctx,{received:ctx.data,code:ZodIssueCode.invalid_enum_value,options:expectedValues}),INVALID}return OK(input.data)}get options(){return this._def.values}get enum(){let enumValues={};for(let val of this._def.values)enumValues[val]=val;return enumValues}get Values(){let enumValues={};for(let val of this._def.values)enumValues[val]=val;return enumValues}get Enum(){let enumValues={};for(let val of this._def.values)enumValues[val]=val;return enumValues}extract(values2,newDef=this._def){return ZodEnum2.create(values2,{...this._def,...newDef})}exclude(values2,newDef=this._def){return ZodEnum2.create(this.options.filter((opt)=>!values2.includes(opt)),{...this._def,...newDef})}},ZodEnum.create=createZodEnum,ZodNativeEnum=class extends ZodType{_parse(input){let nativeEnumValues=util.getValidEnumValues(this._def.values),ctx=this._getOrReturnCtx(input);if(ctx.parsedType!==ZodParsedType.string&&ctx.parsedType!==ZodParsedType.number){let expectedValues=util.objectValues(nativeEnumValues);return addIssueToContext(ctx,{expected:util.joinValues(expectedValues),received:ctx.parsedType,code:ZodIssueCode.invalid_type}),INVALID}if(!this._cache)this._cache=new Set(util.getValidEnumValues(this._def.values));if(!this._cache.has(input.data)){let expectedValues=util.objectValues(nativeEnumValues);return addIssueToContext(ctx,{received:ctx.data,code:ZodIssueCode.invalid_enum_value,options:expectedValues}),INVALID}return OK(input.data)}get enum(){return this._def.values}},ZodNativeEnum.create=(values2,params)=>{return new ZodNativeEnum({values:values2,typeName:ZodFirstPartyTypeKind.ZodNativeEnum,...processCreateParams(params)})},ZodPromise=class extends ZodType{unwrap(){return this._def.type}_parse(input){let{ctx}=this._processInputParams(input);if(ctx.parsedType!==ZodParsedType.promise&&ctx.common.async===!1)return addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.promise,received:ctx.parsedType}),INVALID;let promisified=ctx.parsedType===ZodParsedType.promise?ctx.data:Promise.resolve(ctx.data);return OK(promisified.then((data)=>{return this._def.type.parseAsync(data,{path:ctx.path,errorMap:ctx.common.contextualErrorMap})}))}},ZodPromise.create=(schema,params)=>{return new ZodPromise({type:schema,typeName:ZodFirstPartyTypeKind.ZodPromise,...processCreateParams(params)})},ZodEffects=class extends ZodType{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ZodFirstPartyTypeKind.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(input){let{status,ctx}=this._processInputParams(input),effect=this._def.effect||null,checkCtx={addIssue:(arg)=>{if(addIssueToContext(ctx,arg),arg.fatal)status.abort();else status.dirty()},get path(){return ctx.path}};if(checkCtx.addIssue=checkCtx.addIssue.bind(checkCtx),effect.type==="preprocess"){let processed=effect.transform(ctx.data,checkCtx);if(ctx.common.async)return Promise.resolve(processed).then(async(processed2)=>{if(status.value==="aborted")return INVALID;let result=await this._def.schema._parseAsync({data:processed2,path:ctx.path,parent:ctx});if(result.status==="aborted")return INVALID;if(result.status==="dirty")return DIRTY(result.value);if(status.value==="dirty")return DIRTY(result.value);return result});else{if(status.value==="aborted")return INVALID;let result=this._def.schema._parseSync({data:processed,path:ctx.path,parent:ctx});if(result.status==="aborted")return INVALID;if(result.status==="dirty")return DIRTY(result.value);if(status.value==="dirty")return DIRTY(result.value);return result}}if(effect.type==="refinement"){let executeRefinement=(acc)=>{let result=effect.refinement(acc,checkCtx);if(ctx.common.async)return Promise.resolve(result);if(result instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return acc};if(ctx.common.async===!1){let inner=this._def.schema._parseSync({data:ctx.data,path:ctx.path,parent:ctx});if(inner.status==="aborted")return INVALID;if(inner.status==="dirty")status.dirty();return executeRefinement(inner.value),{status:status.value,value:inner.value}}else return this._def.schema._parseAsync({data:ctx.data,path:ctx.path,parent:ctx}).then((inner)=>{if(inner.status==="aborted")return INVALID;if(inner.status==="dirty")status.dirty();return executeRefinement(inner.value).then(()=>{return{status:status.value,value:inner.value}})})}if(effect.type==="transform")if(ctx.common.async===!1){let base=this._def.schema._parseSync({data:ctx.data,path:ctx.path,parent:ctx});if(!isValid(base))return INVALID;let result=effect.transform(base.value,checkCtx);if(result instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:status.value,value:result}}else return this._def.schema._parseAsync({data:ctx.data,path:ctx.path,parent:ctx}).then((base)=>{if(!isValid(base))return INVALID;return Promise.resolve(effect.transform(base.value,checkCtx)).then((result)=>({status:status.value,value:result}))});util.assertNever(effect)}},ZodEffects.create=(schema,effect,params)=>{return new ZodEffects({schema,typeName:ZodFirstPartyTypeKind.ZodEffects,effect,...processCreateParams(params)})},ZodEffects.createWithPreprocess=(preprocess,schema,params)=>{return new ZodEffects({schema,effect:{type:"preprocess",transform:preprocess},typeName:ZodFirstPartyTypeKind.ZodEffects,...processCreateParams(params)})},ZodOptional=class extends ZodType{_parse(input){if(this._getType(input)===ZodParsedType.undefined)return OK(void 0);return this._def.innerType._parse(input)}unwrap(){return this._def.innerType}},ZodOptional.create=(type,params)=>{return new ZodOptional({innerType:type,typeName:ZodFirstPartyTypeKind.ZodOptional,...processCreateParams(params)})},ZodNullable=class extends ZodType{_parse(input){if(this._getType(input)===ZodParsedType.null)return OK(null);return this._def.innerType._parse(input)}unwrap(){return this._def.innerType}},ZodNullable.create=(type,params)=>{return new ZodNullable({innerType:type,typeName:ZodFirstPartyTypeKind.ZodNullable,...processCreateParams(params)})},ZodDefault=class extends ZodType{_parse(input){let{ctx}=this._processInputParams(input),data=ctx.data;if(ctx.parsedType===ZodParsedType.undefined)data=this._def.defaultValue();return this._def.innerType._parse({data,path:ctx.path,parent:ctx})}removeDefault(){return this._def.innerType}},ZodDefault.create=(type,params)=>{return new ZodDefault({innerType:type,typeName:ZodFirstPartyTypeKind.ZodDefault,defaultValue:typeof params.default==="function"?params.default:()=>params.default,...processCreateParams(params)})},ZodCatch=class extends ZodType{_parse(input){let{ctx}=this._processInputParams(input),newCtx={...ctx,common:{...ctx.common,issues:[]}},result=this._def.innerType._parse({data:newCtx.data,path:newCtx.path,parent:{...newCtx}});if(isAsync(result))return result.then((result2)=>{return{status:"valid",value:result2.status==="valid"?result2.value:this._def.catchValue({get error(){return new ZodError(newCtx.common.issues)},input:newCtx.data})}});else return{status:"valid",value:result.status==="valid"?result.value:this._def.catchValue({get error(){return new ZodError(newCtx.common.issues)},input:newCtx.data})}}removeCatch(){return this._def.innerType}},ZodCatch.create=(type,params)=>{return new ZodCatch({innerType:type,typeName:ZodFirstPartyTypeKind.ZodCatch,catchValue:typeof params.catch==="function"?params.catch:()=>params.catch,...processCreateParams(params)})},ZodNaN=class extends ZodType{_parse(input){if(this._getType(input)!==ZodParsedType.nan){let ctx=this._getOrReturnCtx(input);return addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.nan,received:ctx.parsedType}),INVALID}return{status:"valid",value:input.data}}},ZodNaN.create=(params)=>{return new ZodNaN({typeName:ZodFirstPartyTypeKind.ZodNaN,...processCreateParams(params)})},BRAND=Symbol("zod_brand"),ZodBranded=class extends ZodType{_parse(input){let{ctx}=this._processInputParams(input),data=ctx.data;return this._def.type._parse({data,path:ctx.path,parent:ctx})}unwrap(){return this._def.type}},ZodPipeline=class ZodPipeline2 extends ZodType{_parse(input){let{status,ctx}=this._processInputParams(input);if(ctx.common.async)return(async()=>{let inResult=await this._def.in._parseAsync({data:ctx.data,path:ctx.path,parent:ctx});if(inResult.status==="aborted")return INVALID;if(inResult.status==="dirty")return status.dirty(),DIRTY(inResult.value);else return this._def.out._parseAsync({data:inResult.value,path:ctx.path,parent:ctx})})();else{let inResult=this._def.in._parseSync({data:ctx.data,path:ctx.path,parent:ctx});if(inResult.status==="aborted")return INVALID;if(inResult.status==="dirty")return status.dirty(),{status:"dirty",value:inResult.value};else return this._def.out._parseSync({data:inResult.value,path:ctx.path,parent:ctx})}}static create(a,b){return new ZodPipeline2({in:a,out:b,typeName:ZodFirstPartyTypeKind.ZodPipeline})}},ZodReadonly=class extends ZodType{_parse(input){let result=this._def.innerType._parse(input),freeze=(data)=>{if(isValid(data))data.value=Object.freeze(data.value);return data};return isAsync(result)?result.then((data)=>freeze(data)):freeze(result)}unwrap(){return this._def.innerType}},ZodReadonly.create=(type,params)=>{return new ZodReadonly({innerType:type,typeName:ZodFirstPartyTypeKind.ZodReadonly,...processCreateParams(params)})},late={object:ZodObject.lazycreate},function(ZodFirstPartyTypeKind2){ZodFirstPartyTypeKind2.ZodString="ZodString",ZodFirstPartyTypeKind2.ZodNumber="ZodNumber",ZodFirstPartyTypeKind2.ZodNaN="ZodNaN",ZodFirstPartyTypeKind2.ZodBigInt="ZodBigInt",ZodFirstPartyTypeKind2.ZodBoolean="ZodBoolean",ZodFirstPartyTypeKind2.ZodDate="ZodDate",ZodFirstPartyTypeKind2.ZodSymbol="ZodSymbol",ZodFirstPartyTypeKind2.ZodUndefined="ZodUndefined",ZodFirstPartyTypeKind2.ZodNull="ZodNull",ZodFirstPartyTypeKind2.ZodAny="ZodAny",ZodFirstPartyTypeKind2.ZodUnknown="ZodUnknown",ZodFirstPartyTypeKind2.ZodNever="ZodNever",ZodFirstPartyTypeKind2.ZodVoid="ZodVoid",ZodFirstPartyTypeKind2.ZodArray="ZodArray",ZodFirstPartyTypeKind2.ZodObject="ZodObject",ZodFirstPartyTypeKind2.ZodUnion="ZodUnion",ZodFirstPartyTypeKind2.ZodDiscriminatedUnion="ZodDiscriminatedUnion",ZodFirstPartyTypeKind2.ZodIntersection="ZodIntersection",ZodFirstPartyTypeKind2.ZodTuple="ZodTuple",ZodFirstPartyTypeKind2.ZodRecord="ZodRecord",ZodFirstPartyTypeKind2.ZodMap="ZodMap",ZodFirstPartyTypeKind2.ZodSet="ZodSet",ZodFirstPartyTypeKind2.ZodFunction="ZodFunction",ZodFirstPartyTypeKind2.ZodLazy="ZodLazy",ZodFirstPartyTypeKind2.ZodLiteral="ZodLiteral",ZodFirstPartyTypeKind2.ZodEnum="ZodEnum",ZodFirstPartyTypeKind2.ZodEffects="ZodEffects",ZodFirstPartyTypeKind2.ZodNativeEnum="ZodNativeEnum",ZodFirstPartyTypeKind2.ZodOptional="ZodOptional",ZodFirstPartyTypeKind2.ZodNullable="ZodNullable",ZodFirstPartyTypeKind2.ZodDefault="ZodDefault",ZodFirstPartyTypeKind2.ZodCatch="ZodCatch",ZodFirstPartyTypeKind2.ZodPromise="ZodPromise",ZodFirstPartyTypeKind2.ZodBranded="ZodBranded",ZodFirstPartyTypeKind2.ZodPipeline="ZodPipeline",ZodFirstPartyTypeKind2.ZodReadonly="ZodReadonly"}(ZodFirstPartyTypeKind||(ZodFirstPartyTypeKind={})),stringType=ZodString.create,numberType=ZodNumber.create,nanType=ZodNaN.create,bigIntType=ZodBigInt.create,booleanType=ZodBoolean.create,dateType=ZodDate.create,symbolType=ZodSymbol.create,undefinedType=ZodUndefined.create,nullType=ZodNull.create,anyType=ZodAny.create,unknownType=ZodUnknown.create,neverType=ZodNever.create,voidType=ZodVoid.create,arrayType=ZodArray.create,objectType=ZodObject.create,strictObjectType=ZodObject.strictCreate,unionType=ZodUnion.create,discriminatedUnionType=ZodDiscriminatedUnion.create,intersectionType=ZodIntersection.create,tupleType=ZodTuple.create,recordType=ZodRecord.create,mapType=ZodMap.create,setType=ZodSet.create,functionType=ZodFunction.create,lazyType=ZodLazy.create,literalType=ZodLiteral.create,enumType=ZodEnum.create,nativeEnumType=ZodNativeEnum.create,promiseType=ZodPromise.create,effectsType=ZodEffects.create,optionalType=ZodOptional.create,nullableType=ZodNullable.create,preprocessType=ZodEffects.createWithPreprocess,pipelineType=ZodPipeline.create,coerce={string:(arg)=>ZodString.create({...arg,coerce:!0}),number:(arg)=>ZodNumber.create({...arg,coerce:!0}),boolean:(arg)=>ZodBoolean.create({...arg,coerce:!0}),bigint:(arg)=>ZodBigInt.create({...arg,coerce:!0}),date:(arg)=>ZodDate.create({...arg,coerce:!0})},NEVER=INVALID}),exports_external={};__export2(exports_external,{void:()=>voidType,util:()=>util,unknown:()=>unknownType,union:()=>unionType,undefined:()=>undefinedType,tuple:()=>tupleType,transformer:()=>effectsType,symbol:()=>symbolType,string:()=>stringType,strictObject:()=>strictObjectType,setErrorMap:()=>setErrorMap,set:()=>setType,record:()=>recordType,quotelessJson:()=>quotelessJson,promise:()=>promiseType,preprocess:()=>preprocessType,pipeline:()=>pipelineType,ostring:()=>ostring,optional:()=>optionalType,onumber:()=>onumber,oboolean:()=>oboolean,objectUtil:()=>objectUtil,object:()=>objectType,number:()=>numberType,nullable:()=>nullableType,null:()=>nullType,never:()=>neverType,nativeEnum:()=>nativeEnumType,nan:()=>nanType,map:()=>mapType,makeIssue:()=>makeIssue,literal:()=>literalType,lazy:()=>lazyType,late:()=>late,isValid:()=>isValid,isDirty:()=>isDirty,isAsync:()=>isAsync,isAborted:()=>isAborted,intersection:()=>intersectionType,instanceof:()=>instanceOfType,getParsedType:()=>getParsedType,getErrorMap:()=>getErrorMap,function:()=>functionType,enum:()=>enumType,effect:()=>effectsType,discriminatedUnion:()=>discriminatedUnionType,defaultErrorMap:()=>en_default,datetimeRegex:()=>datetimeRegex,date:()=>dateType,custom:()=>custom,coerce:()=>coerce,boolean:()=>booleanType,bigint:()=>bigIntType,array:()=>arrayType,any:()=>anyType,addIssueToContext:()=>addIssueToContext,ZodVoid:()=>ZodVoid,ZodUnknown:()=>ZodUnknown,ZodUnion:()=>ZodUnion,ZodUndefined:()=>ZodUndefined,ZodType:()=>ZodType,ZodTuple:()=>ZodTuple,ZodTransformer:()=>ZodEffects,ZodSymbol:()=>ZodSymbol,ZodString:()=>ZodString,ZodSet:()=>ZodSet,ZodSchema:()=>ZodType,ZodRecord:()=>ZodRecord,ZodReadonly:()=>ZodReadonly,ZodPromise:()=>ZodPromise,ZodPipeline:()=>ZodPipeline,ZodParsedType:()=>ZodParsedType,ZodOptional:()=>ZodOptional,ZodObject:()=>ZodObject,ZodNumber:()=>ZodNumber,ZodNullable:()=>ZodNullable,ZodNull:()=>ZodNull,ZodNever:()=>ZodNever,ZodNativeEnum:()=>ZodNativeEnum,ZodNaN:()=>ZodNaN,ZodMap:()=>ZodMap,ZodLiteral:()=>ZodLiteral,ZodLazy:()=>ZodLazy,ZodIssueCode:()=>ZodIssueCode,ZodIntersection:()=>ZodIntersection,ZodFunction:()=>ZodFunction,ZodFirstPartyTypeKind:()=>ZodFirstPartyTypeKind,ZodError:()=>ZodError,ZodEnum:()=>ZodEnum,ZodEffects:()=>ZodEffects,ZodDiscriminatedUnion:()=>ZodDiscriminatedUnion,ZodDefault:()=>ZodDefault,ZodDate:()=>ZodDate,ZodCatch:()=>ZodCatch,ZodBranded:()=>ZodBranded,ZodBoolean:()=>ZodBoolean,ZodBigInt:()=>ZodBigInt,ZodArray:()=>ZodArray,ZodAny:()=>ZodAny,Schema:()=>ZodType,ParseStatus:()=>ParseStatus,OK:()=>OK,NEVER:()=>NEVER,INVALID:()=>INVALID,EMPTY_PATH:()=>EMPTY_PATH,DIRTY:()=>DIRTY,BRAND:()=>BRAND});init_external=__esm2(()=>{init_errors2(),init_parseUtil(),init_typeAliases(),init_util(),init_types3(),init_ZodError()}),init_zod=__esm2(()=>{init_external(),init_external()});init_dotfile=__esm2(()=>{HASNA_DIR=join18(homedir10(),".hasna")}),exports_config2={};__export2(exports_config2,{saveCloudConfig:()=>saveCloudConfig,getConnectionString:()=>getConnectionString,getConfigPath:()=>getConfigPath3,getConfigDir:()=>getConfigDir2,getCloudConfig:()=>getCloudConfig,createDatabase:()=>createDatabase,CloudConfigSchema:()=>CloudConfigSchema});init_config3=__esm2(()=>{init_zod(),init_adapter(),init_dotfile(),CloudConfigSchema=exports_external.object({rds:exports_external.object({host:exports_external.string().default(""),port:exports_external.number().default(5432),username:exports_external.string().default(""),password_env:exports_external.string().default("HASNA_RDS_PASSWORD"),ssl:exports_external.boolean().default(!0)}).default({}),mode:exports_external.enum(["local","cloud","hybrid"]).default("hybrid"),auto_sync_interval_minutes:exports_external.number().default(0),feedback_endpoint:exports_external.string().default("https://feedback.hasna.com/api/v1/feedback"),sync:exports_external.object({schedule_minutes:exports_external.number().default(0)}).default({})}),CONFIG_DIR=join22(homedir22(),".hasna","cloud"),CONFIG_PATH=join22(CONFIG_DIR,"config.json")}),exports_discover={};__export2(exports_discover,{isSyncExcludedTable:()=>isSyncExcludedTable,getServiceDbPath:()=>getServiceDbPath,discoverSyncableServices:()=>discoverSyncableServices,discoverServices:()=>discoverServices,SYNC_EXCLUDED_TABLE_PATTERNS:()=>SYNC_EXCLUDED_TABLE_PATTERNS,KNOWN_PG_SERVICES:()=>KNOWN_PG_SERVICES});init_discover=__esm2(()=>{KNOWN_PG_SERVICES=["assistants","attachments","brains","configs","connectors","contacts","context","conversations","crawl","deployment","economy","emails","files","hooks","implementations","logs","mcps","mementos","microservices","predictor","prompts","recordings","researcher","sandboxes","search","secrets","sessions","signatures","skills","telephony","terminal","testers","tickets","todos","wallets"],SYNC_EXCLUDED_TABLE_PATTERNS=[/^sqlite_/,/_fts$/,/_fts_/,/^_sync_/,/^_pg_migrations$/]});init_adapter();init_config3();init_config3();init_dotfile();init_adapter();init_config3();init_discover();AUTO_SYNC_CONFIG_PATH=join42(homedir42(),".hasna","cloud","config.json"),DEFAULT_AUTO_SYNC_CONFIG={auto_sync_on_start:!0,auto_sync_on_stop:!0};cleanupHandlers=[];init_config3();init_adapter();init_dotfile();init_config3();CONFIG_DIR2=join62(homedir52(),".hasna","cloud");init_adapter();init_config3();init_discover();init_zod();init_config3();init_dotfile();init_adapter();init_config3();init_dotfile();init_adapter()});import{join as join19}from"path";import{mkdirSync as mkdirSync11,writeFileSync as writeFileSync7}from"fs";function normalizeTags(value){if(Array.isArray(value)){let tags=value.map((t)=>String(t).trim()).filter(Boolean);return tags.length>0?tags:void 0}if(typeof value==="string"){let tags=value.split(",").map((t)=>t.trim()).filter(Boolean);return tags.length>0?tags:void 0}return}function resolveFeedbackDir(cwd){let baseCwd=cwd&&cwd.trim().length>0?cwd:process.cwd();return join19(getProjectDataDir(baseCwd),"feedback")}function saveFeedbackEntry(entry,cwd){let feedbackDir=resolveFeedbackDir(cwd);mkdirSync11(feedbackDir,{recursive:!0});let path2=join19(feedbackDir,`${entry.id}.json`);return writeFileSync7(path2,JSON.stringify(entry,null,2)),{path:path2}}function buildEntry(input,overrides){let typeValue=String(input.type||"feedback").toLowerCase(),type=typeValue==="bug"||typeValue==="feature"?typeValue:"feedback",title=String(input.title||"Feedback").trim()||"Feedback",description=String(input.description||input.message||"").trim(),steps=String(input.steps||"").trim(),expected=String(input.expected||"").trim(),actual=String(input.actual||"").trim(),tags=normalizeTags(input.tags),metadata=input.metadata&&typeof input.metadata==="object"?input.metadata:void 0,source=typeof input.source==="string"?input.source:void 0;return{id:generateId(),createdAt:new Date().toISOString(),type,title,description,steps:steps||void 0,expected:expected||void 0,actual:actual||void 0,tags,metadata,source,...overrides}}var FeedbackTool;var init_feedback=__esm(async()=>{init_src2();await init_config();FeedbackTool=class FeedbackTool{static tool={name:"submit_feedback",description:"Submit product feedback and save it locally. Use for bugs, feature requests, or general feedback.",parameters:{type:"object",properties:{type:{type:"string",description:"Feedback type: bug, feature, or feedback",enum:["bug","feature","feedback"],default:"feedback"},title:{type:"string",description:"Short summary title"},description:{type:"string",description:"Detailed description of the feedback"},steps:{type:"string",description:"Steps to reproduce (for bugs)"},expected:{type:"string",description:"Expected behavior (for bugs)"},actual:{type:"string",description:"Actual behavior (for bugs)"},tags:{type:"array",description:"Optional tags",items:{type:"string",description:"Tag"}},metadata:{type:"object",description:"Optional metadata (key-value)"},source:{type:"string",description:"Source of feedback (optional)"}},required:["title","description"]}};static executor=async(input)=>{try{let entry=buildEntry(input,{source:input.source||"tool"}),{path:path2}=saveFeedbackEntry(entry,typeof input.cwd==="string"?input.cwd:void 0);try{let{sendFeedback:sendFeedback2}=await Promise.resolve().then(() => (init_dist(),exports_dist));await sendFeedback2({service:"open-assistants",version:"1.1.130",message:`[${entry.type}] ${entry.title}: ${entry.description}`})}catch{}return`Feedback saved locally.
|
|
1016
1016
|
ID: ${entry.id}
|
|
1017
1017
|
Path: ${path2}`}catch(error2){return`Error: ${error2 instanceof Error?error2.message:String(error2)}`}}}});function getDb4(){return getDatabase()}function rowToSchedule(row){if(row.data)return JSON.parse(row.data);return{id:row.id,command:row.command,schedule:JSON.parse(row.schedule),status:row.status,createdBy:"user",sessionId:row.session_id??void 0,nextRunAt:row.next_run_at??void 0,lastRunAt:row.last_run_at??void 0,createdAt:Number(row.created_at)||Date.now(),updatedAt:Number(row.updated_at)||Date.now()}}async function listSchedules(cwd,options2){let schedules=getDb4().query("SELECT * FROM schedules WHERE project_path = ?").all(cwd).map(rowToSchedule);if(options2?.sessionId&&!options2?.global)return schedules.filter((s)=>s.sessionId===options2.sessionId||!s.sessionId);return schedules}async function saveSchedule(cwd,schedule){let scheduleJson=JSON.stringify(schedule.schedule),data=JSON.stringify(schedule);getDb4().prepare(`INSERT OR REPLACE INTO schedules (id, project_path, command, schedule, status, session_id, next_run_at, last_run_at, run_count, max_runs, created_at, updated_at, data)
|
|
1018
1018
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(schedule.id,cwd,schedule.command,scheduleJson,schedule.status,schedule.sessionId??null,schedule.nextRunAt??null,schedule.lastRunAt??null,0,null,String(schedule.createdAt),String(schedule.updatedAt),data)}async function getSchedule(cwd,id){let row=getDb4().query("SELECT * FROM schedules WHERE id = ?").get(id);if(!row)return null;return rowToSchedule(row)}async function deleteSchedule(cwd,id){return getDb4().prepare("DELETE FROM schedules WHERE id = ?").run(id).changes>0}function computeNextRun2(schedule,fromTime){let timezone=schedule.schedule.timezone,validTimezone=timezone&&isValidTimeZone(timezone)?timezone:void 0;if(schedule.schedule.kind==="once"){if(!schedule.schedule.at)return;let next=parseScheduledTime(schedule.schedule.at,validTimezone);if(!next||next<=fromTime)return;return next}if(schedule.schedule.kind==="cron"){if(!schedule.schedule.cron)return;return getNextCronRun(schedule.schedule.cron,fromTime,validTimezone)}if(schedule.schedule.kind==="random")return computeRandomNextRun(schedule.schedule,fromTime);if(schedule.schedule.kind==="interval")return computeIntervalNextRun(schedule.schedule,fromTime);return}function computeRandomNextRun(schedule,fromTime){let{minInterval,maxInterval,unit="minutes"}=schedule;if(!minInterval||!maxInterval||minInterval<=0||maxInterval<=0)return;if(minInterval>maxInterval)return;let multiplier=unit==="seconds"?1000:unit==="hours"?3600000:60000,minMs=minInterval*multiplier,maxMs=maxInterval*multiplier,randomDelay=Math.floor(Math.random()*(maxMs-minMs+1))+minMs;return fromTime+randomDelay}function computeIntervalNextRun(schedule,fromTime){let{interval,unit="minutes"}=schedule;if(!interval||interval<=0)return;let intervalMs=interval*(unit==="seconds"?1000:unit==="hours"?3600000:60000);return fromTime+intervalMs}async function getDueSchedules(cwd,nowTime){return getDb4().query("SELECT * FROM schedules WHERE project_path = ? AND status = 'active' AND next_run_at IS NOT NULL AND next_run_at <= ?").all(cwd,nowTime).map(rowToSchedule).filter((s)=>Number.isFinite(s.nextRunAt))}async function updateSchedule(cwd,id,updater,_options){let d=getDb4();return d.transaction(()=>{let row=d.query("SELECT * FROM schedules WHERE id = ?").get(id);if(!row)return null;let schedule=rowToSchedule(row),updated=updater(schedule),scheduleJson=JSON.stringify(updated.schedule),data=JSON.stringify(updated);return d.prepare("UPDATE schedules SET command = ?, schedule = ?, status = ?, session_id = ?, next_run_at = ?, last_run_at = ?, run_count = ?, max_runs = ?, updated_at = ?, data = ? WHERE id = ?").run(updated.command,scheduleJson,updated.status,updated.sessionId??null,updated.nextRunAt??null,updated.lastRunAt??null,0,null,String(updated.updatedAt),data,id),updated})}async function readSchedule(cwd,id){return getSchedule(cwd,id)}function isValidTimeZone(timeZone){try{return new Intl.DateTimeFormat("en-US",{timeZone}),!0}catch{return!1}}function parseScheduledTime(value,timeZone){if(!value)return;if(!timeZone||hasTimeZoneOffset(value)){let ts=Date.parse(value);return Number.isFinite(ts)?ts:void 0}if(!isValidTimeZone(timeZone))return;let parsed=parseDateTime(value);if(!parsed)return;let utcGuess=Date.UTC(parsed.year,parsed.month-1,parsed.day,parsed.hour,parsed.minute,parsed.second),offset=getTimeZoneOffsetMs(new Date(utcGuess),timeZone);return utcGuess-offset}function parseDateTime(value){let match=value.trim().match(/^(\d{4})-(\d{2})-(\d{2})(?:[T ](\d{2}):(\d{2})(?::(\d{2}))?)?$/);if(!match)return null;let year=Number(match[1]),month=Number(match[2]),day=Number(match[3]),hour=Number(match[4]??"0"),minute=Number(match[5]??"0"),second=Number(match[6]??"0");if(!Number.isFinite(year)||!Number.isFinite(month)||!Number.isFinite(day)||!Number.isFinite(hour)||!Number.isFinite(minute)||!Number.isFinite(second))return null;if(month<1||month>12||day<1||day>31||hour<0||hour>23||minute<0||minute>59||second<0||second>59)return null;return{year,month,day,hour,minute,second}}function hasTimeZoneOffset(value){return/[zZ]|[+-]\d{2}:\d{2}$/.test(value)}function getTimeZoneOffsetMs(date,timeZone){let parts=new Intl.DateTimeFormat("en-US",{timeZone,hour12:!1,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit"}).formatToParts(date),lookup=new Map(parts.map((part)=>[part.type,part.value])),year=Number(lookup.get("year")),month=Number(lookup.get("month")),day=Number(lookup.get("day")),hour=Number(lookup.get("hour")),minute=Number(lookup.get("minute")),second=Number(lookup.get("second"));return Date.UTC(year,month-1,day,hour,minute,second)-date.getTime()}var init_store3=__esm(async()=>{await init_database()});function createSchedulerExecutor(getContext){return async(input)=>{let ctx=getContext(),action=String(input.action||""),cwd=input.cwd||ctx.cwd||process.cwd(),now2=Date.now(),isGlobal=input.global===!0;if(action==="list"){let schedules=await listSchedules(cwd,{sessionId:ctx.sessionId,global:isGlobal});if(schedules.length===0)return"No schedules found.";return schedules.sort((a,b)=>(a.nextRunAt||0)-(b.nextRunAt||0)).map((s)=>{let next=s.nextRunAt?new Date(s.nextRunAt).toISOString():"n/a",scheduleInfo="";if(s.schedule.kind==="interval"&&s.schedule.interval)scheduleInfo=` (every ${s.schedule.interval} ${s.schedule.unit||"minutes"})`;else if(s.schedule.kind==="random"&&s.schedule.minInterval&&s.schedule.maxInterval)scheduleInfo=` (random: ${s.schedule.minInterval}-${s.schedule.maxInterval} ${s.schedule.unit||"minutes"})`;else if(s.schedule.kind==="cron"&&s.schedule.cron)scheduleInfo=` (cron: ${s.schedule.cron})`;let scope=s.sessionId?" [session]":" [global]";return`- ${s.id} [${s.status}]${scope} ${s.command}${scheduleInfo} (next: ${next})`}).join(`
|
|
@@ -1190,7 +1190,7 @@ Use /help to see available commands.
|
|
|
1190
1190
|
`).map((o)=>`${indent2}${o}`),`${indent2}\`\`\``];processedLines.push(fenced.join(`
|
|
1191
1191
|
`))}else processedLines.push(line)}return processedLines.join(`
|
|
1192
1192
|
`)}async executeShell(command,cwd){let validation=validateBashCommand(command);if(!validation.valid)return getSecurityLogger().log({eventType:"blocked_command",severity:validation.severity||"high",details:{tool:"custom_command",command,reason:validation.reason||"Command blocked by security policy"},sessionId:"custom-command"}),`Error: ${validation.reason||"Command blocked by security policy"}`;try{let runtime=getRuntime(),timeoutMs=5000,isWindows=process.platform==="win32",shellBinary=isWindows?"cmd":runtime.which("bash")||"sh",shellArgs=isWindows?["/c",command]:["-lc",command],proc=runtime.spawn([shellBinary,...shellArgs],{cwd,stdin:"ignore",stdout:"pipe",stderr:"pipe"}),timedOut=!1,timer=setTimeout(()=>{timedOut=!0,proc.kill()},5000),[stdout,stderr]=await Promise.all([proc.stdout?new Response(proc.stdout).text():"",proc.stderr?new Response(proc.stderr).text():""]),exitCode=await proc.exited;if(clearTimeout(timer),timedOut)return`Error: command timed out after ${Math.round(5)}s.`;if(exitCode!==0&&stderr){let truncatedStderr=stderr.length>MAX_SHELL_OUTPUT_LENGTH?`${stderr.slice(0,MAX_SHELL_OUTPUT_LENGTH)}...(truncated)`:stderr;return`Error (exit ${exitCode}):
|
|
1193
|
-
${truncatedStderr}`}let trimmedOutput=stdout.trim();if(trimmedOutput.length>MAX_SHELL_OUTPUT_LENGTH)return`${trimmedOutput.slice(0,MAX_SHELL_OUTPUT_LENGTH)}...(output truncated at ${MAX_SHELL_OUTPUT_LENGTH} bytes)`;return trimmedOutput||"(no output)"}catch(error2){return`Error: ${error2 instanceof Error?error2.message:String(error2)}`}}getSuggestions(partial){if(!partial.startsWith("/"))return[];let name=partial.slice(1).toLowerCase();return this.loader.findMatching(name)}}var MAX_SHELL_OUTPUT_LENGTH=65536;var init_executor4=__esm(async()=>{init_bash_validator();await __promiseAll([init_runtime(),init_logger()])});function resolveAuthTimeout(resolve11){resolve11({exitCode:1,stdout:{toString:()=>"{}"}})}function splitArgs(input){let args=[],current="",quote=null,escaped=!1;for(let i=0;i<input.length;i+=1){let char=input[i];if(quote){if(escaped){current+=char,escaped=!1;continue}if(char==="\\"){escaped=!0;continue}if(char===quote){quote=null;continue}current+=char;continue}if(char==='"'||char==="'"){quote=char;continue}if(char===" "||char==="\t"){if(current)args.push(current),current="";continue}current+=char}if(current)args.push(current);return args}function singleLine2(value2){return value2.replace(/[\r\n]+/g," ").replace(/\s+/g," ").trim()}function formatAge(ms){let seconds=Math.floor(ms/1000);if(seconds<60)return`${seconds}s`;let minutes=Math.floor(seconds/60);if(minutes<60)return`${minutes}m`;let hours=Math.floor(minutes/60);if(hours<24)return`${hours}h`;return`${Math.floor(hours/24)}d`}function createTokenUsage(){return{inputTokens:0,outputTokens:0,totalTokens:0,maxContextTokens:200000}}var VERSION2="1.1.
|
|
1193
|
+
${truncatedStderr}`}let trimmedOutput=stdout.trim();if(trimmedOutput.length>MAX_SHELL_OUTPUT_LENGTH)return`${trimmedOutput.slice(0,MAX_SHELL_OUTPUT_LENGTH)}...(output truncated at ${MAX_SHELL_OUTPUT_LENGTH} bytes)`;return trimmedOutput||"(no output)"}catch(error2){return`Error: ${error2 instanceof Error?error2.message:String(error2)}`}}getSuggestions(partial){if(!partial.startsWith("/"))return[];let name=partial.slice(1).toLowerCase();return this.loader.findMatching(name)}}var MAX_SHELL_OUTPUT_LENGTH=65536;var init_executor4=__esm(async()=>{init_bash_validator();await __promiseAll([init_runtime(),init_logger()])});function resolveAuthTimeout(resolve11){resolve11({exitCode:1,stdout:{toString:()=>"{}"}})}function splitArgs(input){let args=[],current="",quote=null,escaped=!1;for(let i=0;i<input.length;i+=1){let char=input[i];if(quote){if(escaped){current+=char,escaped=!1;continue}if(char==="\\"){escaped=!0;continue}if(char===quote){quote=null;continue}current+=char;continue}if(char==='"'||char==="'"){quote=char;continue}if(char===" "||char==="\t"){if(current)args.push(current),current="";continue}current+=char}if(current)args.push(current);return args}function singleLine2(value2){return value2.replace(/[\r\n]+/g," ").replace(/\s+/g," ").trim()}function formatAge(ms){let seconds=Math.floor(ms/1000);if(seconds<60)return`${seconds}s`;let minutes=Math.floor(seconds/60);if(minutes<60)return`${minutes}m`;let hours=Math.floor(minutes/60);if(hours<24)return`${hours}h`;return`${Math.floor(hours/24)}d`}function createTokenUsage(){return{inputTokens:0,outputTokens:0,totalTokens:0,maxContextTokens:200000}}var VERSION2="1.1.130";function aboutCommand(){return{name:"about",description:"About Hasna and Assistants",builtin:!0,selfHandled:!0,content:"",handler:async(_args,context)=>{let message=`
|
|
1194
1194
|
**About Hasna**
|
|
1195
1195
|
|
|
1196
1196
|
`;return message+=`Hasna is on a mission to make AI more useful to everyone.
|
|
@@ -22618,7 +22618,7 @@ Interactive Mode:
|
|
|
22618
22618
|
- Press Ctrl+C to exit
|
|
22619
22619
|
`),exit3(0);return}if(options2.print!==null){if(!options2.print.trim()){print("Error: Prompt is required with -p/--print flag"),exit3(1);return}if(options2.temperature!==null)process.env.ASSISTANTS_TEMPERATURE=String(options2.temperature);if(options2.noMemory)process.env.ASSISTANTS_NO_MEMORY="1";await runHeadless2({prompt:options2.print,cwd:options2.cwd,outputFormat:options2.outputFormat,allowedTools:options2.allowedTools.length>0?options2.allowedTools:void 0,systemPrompt:options2.systemPrompt||void 0,jsonSchema:options2.jsonSchema||void 0,continue:options2.continue,resume:options2.resume,cwdProvided:options2.cwdProvided,timeoutMs:options2.headlessTimeoutMs,temperature:options2.temperature,costLimit:options2.costLimit,noMemory:options2.noMemory})}}setRuntime(bunRuntime);var _worktreeCleanup=null,_renderer=null;function cleanup(){if(_worktreeCleanup)_worktreeCleanup();closeDatabase()}process.on("SIGINT",()=>{if(_renderer&&!_renderer.isDestroyed){_renderer.destroy();return}cleanup(),process.exit(0)});process.on("SIGTERM",()=>{if(_renderer&&!_renderer.isDestroyed){_renderer.destroy();return}cleanup(),process.exit(0)});process.on("uncaughtException",(error55)=>{if(process.stderr.write(`Uncaught exception: ${error55}
|
|
22620
22620
|
`),_renderer&&!_renderer.isDestroyed){_renderer.destroy();return}cleanup(),process.exit(1)});process.on("unhandledRejection",(reason)=>{if(process.stderr.write(`Unhandled rejection: ${reason}
|
|
22621
|
-
`),_renderer&&!_renderer.isDestroyed){_renderer.destroy();return}cleanup(),process.exit(1)});var VERSION7="1.1.
|
|
22621
|
+
`),_renderer&&!_renderer.isDestroyed){_renderer.destroy();return}cleanup(),process.exit(1)});var VERSION7="1.1.130",SYNC_START="\x1B[?2026h",SYNC_END="\x1B[?2026l";function enableSynchronizedOutput(){let originalWrite=process.stdout.write.bind(process.stdout),buffer="",flushScheduled=!1;function flush(){if(flushScheduled=!1,!buffer)return;let output=buffer;buffer="",originalWrite(SYNC_START+output+SYNC_END)}return process.stdout.write=function(chunk,encodingOrCallback,callback){let raw2=typeof chunk==="string"?chunk:chunk.toString(),safe2=sanitizeTerminalOutput(raw2);if(buffer+=safe2,!flushScheduled)flushScheduled=!0,queueMicrotask(flush);if(typeof encodingOrCallback==="function")encodingOrCallback();else if(callback)callback();return!0},()=>{flush(),process.stdout.write=originalWrite}}var subcommand=process.argv[2];if(subcommand==="autocomplete"){let shell=(process.argv[3]||"zsh").toLowerCase(),subcommands=["mcp","doctor","serve","report","config","sessions","search","autocomplete","feedback","brains"],flags=["--help","-h","--version","-v","--print","-p","--output-format","--allowed-tools","--system-prompt","--json-schema","--headless-timeout-ms","--continue","-c","--resume","-r","--cwd","--worktree","--permission-mode","--temperature","--cost-limit","--no-memory"];if(shell==="zsh")console.log(`# assistants zsh completion
|
|
22622
22622
|
# Add to ~/.zshrc: source <(assistants autocomplete zsh)
|
|
22623
22623
|
|
|
22624
22624
|
_assistants() {
|
|
@@ -22757,4 +22757,4 @@ Interactive Mode:
|
|
|
22757
22757
|
- Press Ctrl+C to exit
|
|
22758
22758
|
`),process.exit(0);var activeWorktree=null;if(options2.worktree!==null)try{let worktreeName=typeof options2.worktree==="string"?options2.worktree:void 0;activeWorktree=createWorktree(options2.cwd,worktreeName),options2.cwd=activeWorktree.path,console.log(`Worktree created: ${activeWorktree.path}`)}catch(error55){console.error(`Error creating worktree: ${error55 instanceof Error?error55.message:error55}`),process.exit(1)}function cleanupWorktree(){if(activeWorktree){if(removeWorktree(activeWorktree.path))console.log(`Worktree cleaned up: ${activeWorktree.path}`);else console.log(`Worktree retained (has changes): ${activeWorktree.path}`);activeWorktree=null}}_worktreeCleanup=cleanupWorktree;if(options2.print!==null){if(!options2.print.trim())console.error("Error: Prompt is required with -p/--print flag"),process.exit(1);runHeadless({prompt:options2.print,cwd:options2.cwd,outputFormat:options2.outputFormat,allowedTools:options2.allowedTools.length>0?options2.allowedTools:void 0,systemPrompt:options2.systemPrompt||void 0,jsonSchema:options2.jsonSchema||void 0,continue:options2.continue,resume:options2.resume,cwdProvided:options2.cwdProvided,timeoutMs:options2.headlessTimeoutMs,permissionMode:options2.permissionMode??void 0}).then((result)=>{cleanup(),process.exit(result.success?0:1)}).catch((error55)=>{cleanup(),console.error("Error:",error55.message),process.exit(1)})}else{let disableSyncOutput=process.env.ASSISTANTS_NO_SYNC!=="1"?enableSynchronizedOutput():()=>{},appElement=import_jsx_dev_runtime2.jsxDEV(App,{cwd:options2.cwd,version:VERSION7,permissionMode:options2.permissionMode??void 0},void 0,!1,void 0,this),renderer=await createCliRenderer({exitOnCtrlC:!1,useAlternateScreen:!1,exitSignals:[]});_renderer=renderer,setupThemeDefaults(renderer),createRoot(renderer).render(appElement),renderer.on("destroy",()=>{disableSyncOutput();let stats=getExitStats();if(stats)printExitSummary(stats);cleanup(),process.exit(0)})}export{parseArgs,main2 as main};
|
|
22759
22759
|
|
|
22760
|
-
//# debugId=
|
|
22760
|
+
//# debugId=5F5B6BC3AA6B426864756E2164756E21
|