@north-light/cli 0.3.736 → 0.3.737

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.
@@ -97,7 +97,7 @@ To prepare for this change:
97
97
  See https://www.postgresql.org/docs/current/libpq-ssl.html for libpq SSL mode definitions.`))}Aet.exports=iB;iB.parse=iB;iB.toClientConfig=get;iB.parseIntoClientConfig=tkn});var mge=Q((bwi,xet)=>{"use strict";var nkn=K("dns"),wet=QF(),Eet=yet().parse,ou=function(t,e,n){return e[t]?e[t]:(n===void 0?n=process.env["PG"+t.toUpperCase()]:n===!1||(n=process.env[n]),n||wet[t])},rkn=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 wet.ssl},oB=function(t){return"'"+(""+t).replace(/\\/g,"\\\\").replace(/'/g,"\\'")+"'"},Yd=function(t,e,n){let r=e[n];r!=null&&t.push(n+"="+oB(r))},hge=class{constructor(e){if(e=typeof e=="string"?Eet(e):e||{},e.connectionString&&(e=Object.assign({},e,Eet(e.connectionString))),this.user=ou("user",e),this.database=ou("database",e),this.database===void 0&&(this.database=this.user),this.port=parseInt(ou("port",e),10),this.host=ou("host",e),Object.defineProperty(this,"password",{configurable:!0,enumerable:!1,writable:!0,value:ou("password",e)}),this.binary=ou("binary",e),this.options=ou("options",e),this.ssl=typeof e.ssl>"u"?rkn():e.ssl,typeof this.ssl=="string"&&this.ssl==="true"&&(this.ssl=!0),this.ssl==="no-verify"&&(this.ssl={rejectUnauthorized:!1}),this.ssl&&this.ssl.key&&Object.defineProperty(this.ssl,"key",{enumerable:!1}),this.sslnegotiation=ou("sslnegotiation",e,"PGSSLNEGOTIATION"),this.sslnegotiation!==void 0&&this.sslnegotiation!=="postgres"&&this.sslnegotiation!=="direct")throw new Error(`Invalid sslnegotiation value: "${this.sslnegotiation}". Valid values are "postgres" and "direct".`);if(this.sslnegotiation==="direct"&&!this.ssl)throw new Error("sslnegotiation=direct requires SSL to be enabled");this.client_encoding=ou("client_encoding",e),this.replication=ou("replication",e),this.isDomainSocket=!(this.host||"").indexOf("/"),this.application_name=ou("application_name",e,"PGAPPNAME"),this.fallback_application_name=ou("fallback_application_name",e,!1),this.statement_timeout=ou("statement_timeout",e,!1),this.lock_timeout=ou("lock_timeout",e,!1),this.idle_in_transaction_session_timeout=ou("idle_in_transaction_session_timeout",e,!1),this.query_timeout=ou("query_timeout",e,!1),e.connectionTimeoutMillis===void 0?this.connect_timeout=process.env.PGCONNECT_TIMEOUT||0:this.connect_timeout=Math.floor(e.connectionTimeoutMillis/1e3),e.keepAlive===!1?this.keepalives=0:e.keepAlive===!0&&(this.keepalives=1),typeof e.keepAliveInitialDelayMillis=="number"&&(this.keepalives_idle=Math.floor(e.keepAliveInitialDelayMillis/1e3))}getLibpqConnectionString(e){let n=[];Yd(n,this,"user"),Yd(n,this,"password"),Yd(n,this,"port"),Yd(n,this,"application_name"),Yd(n,this,"fallback_application_name"),Yd(n,this,"connect_timeout"),Yd(n,this,"options");let r=typeof this.ssl=="object"?this.ssl:this.ssl?{sslmode:this.ssl}:{};if(Yd(n,r,"sslmode"),Yd(n,r,"sslca"),Yd(n,r,"sslkey"),Yd(n,r,"sslcert"),Yd(n,r,"sslrootcert"),Yd(n,this,"sslnegotiation"),this.database&&n.push("dbname="+oB(this.database)),this.replication&&n.push("replication="+oB(this.replication)),this.host&&n.push("host="+oB(this.host)),this.isDomainSocket)return e(null,n.join(" "));this.client_encoding&&n.push("client_encoding="+oB(this.client_encoding)),nkn.lookup(this.host,function(i,o){return i?e(i,null):(n.push("hostaddr="+oB(o)),e(null,n.join(" ")))})}};xet.exports=hge});var gge=Q((Cwi,Cet)=>{"use strict";var ikn=LF(),bet=/^([A-Za-z]+)(?: (\d+))?(?: (\d+))?/,fge=class{constructor(e,n){this.command=null,this.rowCount=null,this.oid=null,this.rows=[],this.fields=[],this._parsers=void 0,this._types=n,this.RowCtor=null,this.rowAsArray=e==="array",this.rowAsArray&&(this.parseRow=this._parseRowAsArray),this._prebuiltEmptyResultObject=null}addCommandComplete(e){let n;e.text?n=bet.exec(e.text):n=bet.exec(e.command),n&&(this.command=n[1],n[3]?(this.oid=parseInt(n[2],10),this.rowCount=parseInt(n[3],10)):n[2]&&(this.rowCount=parseInt(n[2],10)))}_parseRowAsArray(e){let n=new Array(e.length);for(let r=0,i=e.length;r<i;r++){let o=e[r];o!==null?n[r]=this._parsers[r](o):n[r]=null}return n}parseRow(e){let n={...this._prebuiltEmptyResultObject};for(let r=0,i=e.length;r<i;r++){let o=e[r],s=this.fields[r].name;if(o!==null){let a=this.fields[r].format==="binary"?Buffer.from(o):o;n[s]=this._parsers[r](a)}else n[s]=null}return n}addRow(e){this.rows.push(e)}addFields(e){this.fields=e,this.fields.length&&(this._parsers=new Array(e.length));let n=Object.create(null);for(let r=0;r<e.length;r++){let i=e[r];n[i.name]=null,this._types?this._parsers[r]=this._types.getTypeParser(i.dataTypeID,i.format||"text"):this._parsers[r]=ikn.getTypeParser(i.dataTypeID,i.format||"text")}this._prebuiltEmptyResultObject={...n}}};Cet.exports=fge});var ket=Q((Iwi,_et)=>{"use strict";var{EventEmitter:okn}=K("events"),Iet=gge(),vet=GI(),Age=class extends okn{constructor(e,n,r){super(),e=vet.normalizeQueryConfig(e,n,r),this.text=e.text,this.values=e.values,this.rows=e.rows,this.types=e.types,this.name=e.name,this.queryMode=e.queryMode,this.binary=e.binary,this.portal=e.portal||"",this.callback=e.callback,this._rowMode=e.rowMode,process.domain&&e.callback&&(this.callback=process.domain.bind(e.callback)),this._result=new Iet(this._rowMode,this.types),this._results=this._result,this._canceledDueToError=!1}requiresPreparation(){return this.queryMode==="extended"||this.name||this.rows?!0:!this.text||!this.values?!1:this.values.length>0}_checkForMultirow(){this._result.command&&(Array.isArray(this._results)||(this._results=[this._result]),this._result=new Iet(this._rowMode,this._result._types),this._results.push(this._result))}handleRowDescription(e){this._checkForMultirow(),this._result.addFields(e.fields),this._accumulateRows=this.callback||!this.listeners("row").length}handleDataRow(e){let n;if(!this._canceledDueToError){try{n=this._result.parseRow(e.fields)}catch(r){this._canceledDueToError=r;return}this.emit("row",n,this._result),this._accumulateRows&&this._result.addRow(n)}}handleCommandComplete(e,n){this._checkForMultirow(),this._result.addCommandComplete(e),this.rows&&n.sync()}handleEmptyQuery(e){this.rows&&e.sync()}handleError(e,n){if(this._canceledDueToError&&(e=this._canceledDueToError,this._canceledDueToError=!1),this.callback)return this.callback(e);this.emit("error",e)}handleReadyForQuery(e){if(this._canceledDueToError)return this.handleError(this._canceledDueToError,e);if(this.callback)try{this.callback(null,this._results)}catch(n){process.nextTick(()=>{throw n})}this.emit("end",this._results)}submit(e){if(typeof this.text!="string"&&typeof this.name!="string")return new Error("A query must have either text or a name. Supplying neither is unsupported.");let n=e.parsedStatements[this.name]||e.submittedNamedStatements[this.name];if(this.text&&n&&this.text!==n)return new Error(`Prepared statements must be unique - '${this.name}' was used for a different statement`);if(this.values&&!Array.isArray(this.values))return new Error("Query values must be an array");if(this.requiresPreparation()){e.stream.cork&&e.stream.cork();try{this.prepare(e)}finally{e.stream.uncork&&e.stream.uncork()}}else e.query(this.text);return null}hasBeenParsed(e){return this.name&&(e.parsedStatements[this.name]!==void 0||e.submittedNamedStatements[this.name]!==void 0)}handlePortalSuspended(e){this._getRows(e,this.rows)}_getRows(e,n){e.execute({portal:this.portal,rows:n}),n?e.flush():e.sync()}prepare(e){this.hasBeenParsed(e)||(e.parse({text:this.text,name:this.name,types:this.types}),this.name&&(e.submittedNamedStatements[this.name]=this.text));try{e.bind({portal:this.portal,statement:this.name,values:this.values,binary:this.binary,valueMapper:vet.prepareValue})}catch(n){e.close({type:"S",name:this.name}),e.sync(),this.handleError(n,e);return}e.describe({type:"P",name:this.portal||""}),this._getRows(e,this.rows)}handleCopyInResponse(e){e.sendCopyFail("No source stream defined")}handleCopyData(e,n){}};_et.exports=Age});var Dge=Q($n=>{"use strict";Object.defineProperty($n,"__esModule",{value:!0});$n.NoticeMessage=$n.DataRowMessage=$n.CommandCompleteMessage=$n.ReadyForQueryMessage=$n.NotificationResponseMessage=$n.BackendKeyDataMessage=$n.AuthenticationMD5Password=$n.ParameterStatusMessage=$n.ParameterDescriptionMessage=$n.RowDescriptionMessage=$n.Field=$n.CopyResponse=$n.CopyDataMessage=$n.DatabaseError=$n.copyDone=$n.emptyQuery=$n.replicationStart=$n.portalSuspended=$n.noData=$n.closeComplete=$n.bindComplete=$n.parseComplete=void 0;$n.parseComplete={name:"parseComplete",length:5};$n.bindComplete={name:"bindComplete",length:5};$n.closeComplete={name:"closeComplete",length:5};$n.noData={name:"noData",length:5};$n.portalSuspended={name:"portalSuspended",length:5};$n.replicationStart={name:"replicationStart",length:4};$n.emptyQuery={name:"emptyQuery",length:4};$n.copyDone={name:"copyDone",length:4};var yge=class extends Error{constructor(e,n,r){super(e),this.length=n,this.name=r}};$n.DatabaseError=yge;var Ege=class{constructor(e,n){this.length=e,this.chunk=n,this.name="copyData"}};$n.CopyDataMessage=Ege;var wge=class{constructor(e,n,r,i){this.length=e,this.name=n,this.binary=r,this.columnTypes=new Array(i)}};$n.CopyResponse=wge;var xge=class{constructor(e,n,r,i,o,s,a){this.name=e,this.tableID=n,this.columnID=r,this.dataTypeID=i,this.dataTypeSize=o,this.dataTypeModifier=s,this.format=a}};$n.Field=xge;var bge=class{constructor(e,n){this.length=e,this.fieldCount=n,this.name="rowDescription",this.fields=new Array(this.fieldCount)}};$n.RowDescriptionMessage=bge;var Cge=class{constructor(e,n){this.length=e,this.parameterCount=n,this.name="parameterDescription",this.dataTypeIDs=new Array(this.parameterCount)}};$n.ParameterDescriptionMessage=Cge;var Ige=class{constructor(e,n,r){this.length=e,this.parameterName=n,this.parameterValue=r,this.name="parameterStatus"}};$n.ParameterStatusMessage=Ige;var vge=class{constructor(e,n){this.length=e,this.salt=n,this.name="authenticationMD5Password"}};$n.AuthenticationMD5Password=vge;var Sge=class{constructor(e,n,r){this.length=e,this.processID=n,this.secretKey=r,this.name="backendKeyData"}};$n.BackendKeyDataMessage=Sge;var _ge=class{constructor(e,n,r,i){this.length=e,this.processId=n,this.channel=r,this.payload=i,this.name="notification"}};$n.NotificationResponseMessage=_ge;var kge=class{constructor(e,n){this.length=e,this.status=n,this.name="readyForQuery"}};$n.ReadyForQueryMessage=kge;var Tge=class{constructor(e,n){this.length=e,this.text=n,this.name="commandComplete"}};$n.CommandCompleteMessage=Tge;var Rge=class{constructor(e,n){this.length=e,this.fields=n,this.name="dataRow",this.fieldCount=n.length}};$n.DataRowMessage=Rge;var Bge=class{constructor(e,n){this.length=e,this.message=n,this.name="notice"}};$n.NoticeMessage=Bge});var Tet=Q(Q6=>{"use strict";Object.defineProperty(Q6,"__esModule",{value:!0});Q6.Writer=void 0;var Mge=class{constructor(e=256){this.size=e,this.offset=5,this.headerPosition=0,this.buffer=Buffer.allocUnsafe(e)}ensure(e){if(this.buffer.length-this.offset<e){let r=this.buffer,i=r.length+(r.length>>1)+e;this.buffer=Buffer.allocUnsafe(i),r.copy(this.buffer,0,0,this.offset)}}addInt32(e){return this.ensure(4),this.buffer[this.offset++]=e>>>24&255,this.buffer[this.offset++]=e>>>16&255,this.buffer[this.offset++]=e>>>8&255,this.buffer[this.offset++]=e>>>0&255,this}addInt16(e){return this.ensure(2),this.buffer[this.offset++]=e>>>8&255,this.buffer[this.offset++]=e>>>0&255,this}addCString(e){if(!e)this.ensure(1);else{let n=Buffer.byteLength(e);this.ensure(n+1),this.buffer.write(e,this.offset,"utf-8"),this.offset+=n}return this.buffer[this.offset++]=0,this}addString(e=""){let n=Buffer.byteLength(e);return this.ensure(n),this.buffer.write(e,this.offset),this.offset+=n,this}addInt32PrefixedString(e){let n=Buffer.byteLength(e);this.ensure(4+n);let r=this.buffer,i=this.offset;return r[i++]=n>>>24&255,r[i++]=n>>>16&255,r[i++]=n>>>8&255,r[i++]=n>>>0&255,r.write(e,i,"utf-8"),this.offset=i+n,this}add(e){return this.ensure(e.length),e.copy(this.buffer,this.offset),this.offset+=e.length,this}reserveUnsafe(e){let n=this.offset;return this.ensure(e),this.offset+=e,n}join(e){if(e){this.buffer[this.headerPosition]=e;let n=this.offset-(this.headerPosition+1);this.buffer.writeInt32BE(n,this.headerPosition+1)}return this.buffer.slice(e?0:5,this.offset)}flush(e){let n=this.join(e);return this.offset=5,this.headerPosition=0,this.buffer=Buffer.allocUnsafe(this.size),n}clear(){this.offset=5,this.headerPosition=0}};Q6.Writer=Mge});var Det=Q(F6=>{"use strict";Object.defineProperty(F6,"__esModule",{value:!0});F6.serialize=void 0;var Ret=Tet(),Vi=new Ret.Writer,skn=t=>{Vi.addInt16(3).addInt16(0);for(let r of Object.keys(t))Vi.addCString(r).addCString(t[r]);Vi.addCString("client_encoding").addCString("UTF8");let e=Vi.addCString("").flush(),n=e.length+4;return new Ret.Writer().addInt32(n).add(e).flush()},akn=()=>{let t=Buffer.allocUnsafe(8);return t.writeInt32BE(8,0),t.writeInt32BE(80877103,4),t},ckn=t=>Vi.addCString(t).flush(112),ukn=function(t,e){return Vi.addCString(t).addInt32PrefixedString(e),Vi.flush(112)},lkn=function(t){return Vi.addString(t).flush(112)},dkn=t=>Vi.addCString(t).flush(81),Bet=[],pkn=t=>{let e=t.name||"";e.length>63&&(console.error("Warning! Postgres only supports 63 characters for query names."),console.error("You supplied %s (%s)",e,e.length),console.error("This can cause conflicts and silent errors executing queries"));let n=t.types||Bet,r=n.length,i=Vi.addCString(e).addCString(t.text).addInt16(r);for(let o=0;o<r;o++)i.addInt32(n[o]);return Vi.flush(80)},hkn=function(t,e,n){let r=t.length;for(let i=0;i<r;i++){let o=e?e(t[i],i):t[i],s=0;o==null?Vi.addInt32(-1):o instanceof Buffer?(s=1,Vi.addInt32(o.length),Vi.add(o)):Vi.addInt32PrefixedString(o);let a=Vi.buffer;a[n++]=0,a[n++]=s}},mkn=(t={})=>{let e=t.portal||"",n=t.statement||"",r=t.binary||!1,i=t.values||Bet,o=i.length;Vi.addCString(e).addCString(n),Vi.addInt16(o);let s=Vi.reserveUnsafe(o*2);Vi.addInt16(o);try{hkn(i,t.valueMapper,s)}catch(a){throw Vi.clear(),a}return Vi.addInt16(1),Vi.addInt16(r?1:0),Vi.flush(66)},fkn=Buffer.from([69,0,0,0,9,0,0,0,0,0]),gkn=t=>{if(!t||!t.portal&&!t.rows)return fkn;let e=t.portal||"",n=t.rows||0,r=Buffer.byteLength(e),i=4+r+1+4,o=Buffer.allocUnsafe(1+i);return o[0]=69,o.writeInt32BE(i,1),o.write(e,5,"utf-8"),o[r+5]=0,o.writeUInt32BE(n,o.length-4),o},Akn=(t,e)=>{let n=Buffer.allocUnsafe(16);return n.writeInt32BE(16,0),n.writeInt16BE(1234,4),n.writeInt16BE(5678,6),n.writeInt32BE(t,8),n.writeInt32BE(e,12),n},Pge=(t,e)=>{let r=4+Buffer.byteLength(e)+1,i=Buffer.allocUnsafe(1+r);return i[0]=t,i.writeInt32BE(r,1),i.write(e,5,"utf-8"),i[r]=0,i},ykn=Vi.addCString("P").flush(68),Ekn=Vi.addCString("S").flush(68),wkn=t=>t.name?Pge(68,`${t.type}${t.name||""}`):t.type==="P"?ykn:Ekn,xkn=t=>{let e=`${t.type}${t.name||""}`;return Pge(67,e)},bkn=t=>Vi.add(t).flush(100),Ckn=t=>Pge(102,t),O6=t=>Buffer.from([t,0,0,0,4]),Ikn=O6(72),vkn=O6(83),Skn=O6(88),_kn=O6(99),kkn={startup:skn,password:ckn,requestSsl:akn,sendSASLInitialResponseMessage:ukn,sendSCRAMClientFinalMessage:lkn,query:dkn,parse:pkn,bind:mkn,execute:gkn,describe:wkn,close:xkn,flush:()=>Ikn,sync:()=>vkn,end:()=>Skn,copyData:bkn,copyDone:()=>_kn,copyFail:Ckn,cancel:Akn};F6.serialize=kkn});var Met=Q(U6=>{"use strict";Object.defineProperty(U6,"__esModule",{value:!0});U6.BufferReader=void 0;var Nge=class{constructor(e=0){this.offset=e,this.buffer=Buffer.allocUnsafe(0),this.encoding="utf-8"}setBuffer(e,n){this.offset=e,this.buffer=n}int16(){let e=this.buffer.readInt16BE(this.offset);return this.offset+=2,e}byte(){let e=this.buffer[this.offset];return this.offset++,e}int32(){let e=this.buffer.readInt32BE(this.offset);return this.offset+=4,e}uint32(){let e=this.buffer.readUInt32BE(this.offset);return this.offset+=4,e}string(e){let n=this.buffer.toString(this.encoding,this.offset,this.offset+e);return this.offset+=e,n}cstring(){let e=this.offset,n=e;for(;this.buffer[n++];);return this.offset=n,this.buffer.toString(this.encoding,e,n-1)}bytes(e){let n=this.buffer.slice(this.offset,this.offset+e);return this.offset+=e,n}};U6.BufferReader=Nge});var Qet=Q($6=>{"use strict";Object.defineProperty($6,"__esModule",{value:!0});$6.Parser=void 0;var as=Dge(),Tkn=Met(),Qge=1,Rkn=4,Pet=Qge+Rkn,Jd=-1,Lge=Buffer.allocUnsafe(0),Oge=class{constructor(e){if(this.buffer=Lge,this.bufferLength=0,this.bufferOffset=0,this.reader=new Tkn.BufferReader,e?.mode==="binary")throw new Error("Binary mode not supported yet");this.mode=e?.mode||"text"}parse(e,n){this.mergeBuffer(e);let r=this.bufferOffset+this.bufferLength,i=this.bufferOffset;for(;i+Pet<=r;){let o=this.buffer[i],s=this.buffer.readUInt32BE(i+Qge),a=Qge+s;if(a+i<=r){let c=this.handlePacket(i+Pet,o,s,this.buffer);n(c),i+=a}else break}i===r?(this.buffer=Lge,this.bufferLength=0,this.bufferOffset=0):(this.bufferLength=r-i,this.bufferOffset=i)}mergeBuffer(e){if(this.bufferLength>0){let n=this.bufferLength+e.byteLength;if(n+this.bufferOffset>this.buffer.byteLength){let i;if(n<=this.buffer.byteLength&&this.bufferOffset>=this.bufferLength)i=this.buffer;else{let o=this.buffer.byteLength*2;for(;n>=o;)o*=2;i=Buffer.allocUnsafe(o)}this.buffer.copy(i,0,this.bufferOffset,this.bufferOffset+this.bufferLength),this.buffer=i,this.bufferOffset=0}e.copy(this.buffer,this.bufferOffset+this.bufferLength),this.bufferLength=n}else this.buffer=e,this.bufferOffset=0,this.bufferLength=e.byteLength}handlePacket(e,n,r,i){let{reader:o}=this;o.setBuffer(e,i);let s;switch(n){case 50:s=as.bindComplete;break;case 49:s=as.parseComplete;break;case 51:s=as.closeComplete;break;case 110:s=as.noData;break;case 115:s=as.portalSuspended;break;case 99:s=as.copyDone;break;case 87:s=as.replicationStart;break;case 73:s=as.emptyQuery;break;case 68:s=Ukn(o);break;case 67:s=Dkn(o);break;case 90:s=Bkn(o);break;case 65:s=Lkn(o);break;case 82:s=Hkn(o,r);break;case 83:s=$kn(o);break;case 75:s=Wkn(o);break;case 69:s=Net(o,"error");break;case 78:s=Net(o,"notice");break;case 84:s=Qkn(o);break;case 116:s=Fkn(o);break;case 71:s=Pkn(o);break;case 72:s=Nkn(o);break;case 100:s=Mkn(o,r);break;default:return new as.DatabaseError("received invalid response: "+n.toString(16),r,"error")}return o.setBuffer(0,Lge),s.length=r,s}};$6.Parser=Oge;var Bkn=t=>{let e=t.string(1);return new as.ReadyForQueryMessage(Jd,e)},Dkn=t=>{let e=t.cstring();return new as.CommandCompleteMessage(Jd,e)},Mkn=(t,e)=>{let n=t.bytes(e-4);return new as.CopyDataMessage(Jd,n)},Pkn=t=>Let(t,"copyInResponse"),Nkn=t=>Let(t,"copyOutResponse"),Let=(t,e)=>{let n=t.byte()!==0,r=t.int16(),i=new as.CopyResponse(Jd,e,n,r);for(let o=0;o<r;o++)i.columnTypes[o]=t.int16();return i},Lkn=t=>{let e=t.int32(),n=t.cstring(),r=t.cstring();return new as.NotificationResponseMessage(Jd,e,n,r)},Qkn=t=>{let e=t.int16(),n=new as.RowDescriptionMessage(Jd,e);for(let r=0;r<e;r++)n.fields[r]=Okn(t);return n},Okn=t=>{let e=t.cstring(),n=t.uint32(),r=t.int16(),i=t.uint32(),o=t.int16(),s=t.int32(),a=t.int16()===0?"text":"binary";return new as.Field(e,n,r,i,o,s,a)},Fkn=t=>{let e=t.int16(),n=new as.ParameterDescriptionMessage(Jd,e);for(let r=0;r<e;r++)n.dataTypeIDs[r]=t.uint32();return n},Ukn=t=>{let e=t.int16(),n=new Array(e);for(let r=0;r<e;r++){let i=t.int32();n[r]=i===-1?null:t.string(i)}return new as.DataRowMessage(Jd,n)},$kn=t=>{let e=t.cstring(),n=t.cstring();return new as.ParameterStatusMessage(Jd,e,n)},Wkn=t=>{let e=t.int32(),n=t.int32();return new as.BackendKeyDataMessage(Jd,e,n)},Hkn=(t,e)=>{let n=t.int32(),r={name:"authenticationOk",length:e};switch(n){case 0:break;case 3:r.length===8&&(r.name="authenticationCleartextPassword");break;case 5:if(r.length===12){r.name="authenticationMD5Password";let i=t.bytes(4);return new as.AuthenticationMD5Password(Jd,i)}break;case 10:{r.name="authenticationSASL",r.mechanisms=[];let i;do i=t.cstring(),i&&r.mechanisms.push(i);while(i)}break;case 11:r.name="authenticationSASLContinue",r.data=t.string(e-8);break;case 12:r.name="authenticationSASLFinal",r.data=t.string(e-8);break;default:throw new Error("Unknown authenticationOk message type "+n)}return r},Net=(t,e)=>{let n={},r=t.string(1);for(;r!=="\0";)n[r]=t.cstring(),r=t.string(1);let i=n.M,o=e==="notice"?new as.NoticeMessage(Jd,i):new as.DatabaseError(i,Jd,e);return o.severity=n.S,o.code=n.C,o.detail=n.D,o.hint=n.H,o.position=n.P,o.internalPosition=n.p,o.internalQuery=n.q,o.where=n.W,o.schema=n.s,o.table=n.t,o.column=n.c,o.dataType=n.d,o.constraint=n.n,o.file=n.F,o.line=n.L,o.routine=n.R,o}});var Fge=Q(zI=>{"use strict";Object.defineProperty(zI,"__esModule",{value:!0});zI.DatabaseError=zI.serialize=void 0;zI.parse=zkn;var Gkn=Dge();Object.defineProperty(zI,"DatabaseError",{enumerable:!0,get:function(){return Gkn.DatabaseError}});var qkn=Det();Object.defineProperty(zI,"serialize",{enumerable:!0,get:function(){return qkn.serialize}});var jkn=Qet();function zkn(t,e){let n=new jkn.Parser;return t.on("data",r=>n.parse(r,e)),new Promise(r=>t.on("end",()=>r()))}});var Oet=Q(Uge=>{"use strict";Object.defineProperty(Uge,"__esModule",{value:!0});Uge.default={}});var Uet=Q((Dwi,Fet)=>{var{getStream:Vkn,getSecureStream:Kkn}=Zkn();Fet.exports={getStream:Vkn,getSecureStream:Kkn};function Ykn(){function t(n){let r=K("net");return new r.Socket}function e(n){return K("tls").connect(n)}return{getStream:t,getSecureStream:e}}function Jkn(){function t(n){let{CloudflareSocket:r}=Oet();return new r(n)}function e(n){return n.socket.startTls(n),n.socket}return{getStream:t,getSecureStream:e}}function Xkn(){if(typeof navigator=="object"&&navigator!==null&&typeof navigator.userAgent=="string")return navigator.userAgent==="Cloudflare-Workers";if(typeof Response=="function"){let t=new Response(null,{cf:{thing:!0}});if(typeof t.cf=="object"&&t.cf!==null&&t.cf.thing)return!0}return!1}function Zkn(){return Xkn()?Jkn():Ykn()}});var Wge=Q((Mwi,Wet)=>{"use strict";var eTn=K("events").EventEmitter,{parse:tTn,serialize:Ja}=Fge(),$et=Uet(),{getStream:nTn}=$et,rTn=Ja.flush(),iTn=Ja.sync(),oTn=Ja.end(),$ge=class extends eTn{constructor(e){super(),e=e||{},this.stream=e.stream||nTn(e.ssl),typeof this.stream=="function"&&(this.stream=this.stream(e)),this._keepAlive=e.keepAlive,this._keepAliveInitialDelayMillis=e.keepAliveInitialDelayMillis,this.parsedStatements={},this.submittedNamedStatements={},this.ssl=e.ssl||!1,this.sslNegotiation=e.sslNegotiation||"postgres",this._ending=!1,this._emitMessage=!1;let n=this;this.on("newListener",function(r){r==="message"&&(n._emitMessage=!0)})}connect(e,n){let r=this;this._connecting=!0,this.stream.setNoDelay(!0),this.stream.connect(e,n),this.stream.once("connect",function(){r._keepAlive&&r.stream.setKeepAlive(!0,r._keepAliveInitialDelayMillis),r.emit("connect")});let i=function(o){r._ending&&(o.code==="ECONNRESET"||o.code==="EPIPE")||r.emit("error",o)};if(this.stream.on("error",i),this.stream.on("close",function(){r.emit("end")}),!this.ssl)return this.attachListeners(this.stream);if(this.sslNegotiation==="direct")return this.stream.once("connect",function(){r.upgradeToSSL(n,i)});this.stream.once("data",function(o){switch(o.toString("utf8")){case"S":break;case"N":return r.stream.end(),r.emit("error",new Error("The server does not support SSL connections"));default:return r.stream.end(),r.emit("error",new Error("There was an error establishing an SSL connection"))}r.upgradeToSSL(n,i)})}upgradeToSSL(e,n){let r=this,i={socket:r.stream,host:e};r.ssl!==!0&&(Object.assign(i,r.ssl),"key"in r.ssl&&(i.key=r.ssl.key)),r.sslNegotiation==="direct"&&(i.ALPNProtocols=["postgresql"]);let o=K("net");o.isIP&&o.isIP(e)===0&&(i.servername=e);try{r.stream=$et.getSecureStream(i)}catch(s){return r.emit("error",s)}r.attachListeners(r.stream),r.stream.on("error",n),r.emit("sslconnect")}attachListeners(e){tTn(e,n=>{let r=n.name==="error"?"errorMessage":n.name;this._emitMessage&&this.emit("message",n),this.emit(r,n)})}requestSsl(){this.stream.write(Ja.requestSsl())}startup(e){this.stream.write(Ja.startup(e))}cancel(e,n){this._send(Ja.cancel(e,n))}password(e){this._send(Ja.password(e))}sendSASLInitialResponseMessage(e,n){this._send(Ja.sendSASLInitialResponseMessage(e,n))}sendSCRAMClientFinalMessage(e){this._send(Ja.sendSCRAMClientFinalMessage(e))}_send(e){return this.stream.writable?this.stream.write(e):!1}query(e){this._send(Ja.query(e))}parse(e){this._send(Ja.parse(e))}bind(e){this._send(Ja.bind(e))}execute(e){this._send(Ja.execute(e))}flush(){this.stream.writable&&this.stream.write(rTn)}sync(){this._send(iTn)}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(oTn,()=>{this.stream.end()})}close(e){this._send(Ja.close(e))}describe(e){this._send(Ja.describe(e))}sendCopyFromChunk(e){this._send(Ja.copyData(e))}endCopyFrom(){this._send(Ja.copyDone())}sendCopyFail(e){this._send(Ja.copyFail(e))}};Wet.exports=$ge});var jet=Q((Pwi,qet)=>{"use strict";var{Transform:sTn}=K("stream"),{StringDecoder:aTn}=K("string_decoder"),Aw=Symbol("last"),W6=Symbol("decoder");function cTn(t,e,n){let r;if(this.overflow){if(r=this[W6].write(t).split(this.matcher),r.length===1)return n();r.shift(),this.overflow=!1}else this[Aw]+=this[W6].write(t),r=this[Aw].split(this.matcher);this[Aw]=r.pop();for(let i=0;i<r.length;i++)try{Get(this,this.mapper(r[i]))}catch(o){return n(o)}if(this.overflow=this[Aw].length>this.maxLength,this.overflow&&!this.skipOverflow){n(new Error("maximum buffer reached"));return}n()}function uTn(t){if(this[Aw]+=this[W6].end(),this[Aw])try{Get(this,this.mapper(this[Aw]))}catch(e){return t(e)}t()}function Get(t,e){e!==void 0&&t.push(e)}function Het(t){return t}function lTn(t,e,n){switch(t=t||/\r?\n/,e=e||Het,n=n||{},arguments.length){case 1:typeof t=="function"?(e=t,t=/\r?\n/):typeof t=="object"&&!(t instanceof RegExp)&&!t[Symbol.split]&&(n=t,t=/\r?\n/);break;case 2:typeof t=="function"?(n=e,e=t,t=/\r?\n/):typeof e=="object"&&(n=e,e=Het)}n=Object.assign({},n),n.autoDestroy=!0,n.transform=cTn,n.flush=uTn,n.readableObjectMode=!0;let r=new sTn(n);return r[Aw]="",r[W6]=new aTn("utf8"),r.matcher=t,r.mapper=e,r.maxLength=n.maxLength,r.skipOverflow=n.skipOverflow||!1,r.overflow=!1,r._destroy=function(i,o){this._writableState.errorEmitted=!1,o(i)},r}qet.exports=lTn});var Ket=Q((Nwi,q0)=>{"use strict";var zet=K("path"),dTn=K("stream").Stream,pTn=jet(),Vet=K("util"),hTn=5432,H6=process.platform==="win32",FF=process.stderr,mTn=56,fTn=7,gTn=61440,ATn=32768;function yTn(t){return(t&gTn)==ATn}var sB=["host","port","database","user","password"],Hge=sB.length,ETn=sB[Hge-1];function Gge(){var t=FF instanceof dTn&&FF.writable===!0;if(t){var e=Array.prototype.slice.call(arguments).concat(`
98
98
  `);FF.write(Vet.format.apply(Vet,e))}}Object.defineProperty(q0.exports,"isWin",{get:function(){return H6},set:function(t){H6=t}});q0.exports.warnTo=function(t){var e=FF;return FF=t,e};q0.exports.getFileName=function(t){var e=t||process.env,n=e.PGPASSFILE||(H6?zet.join(e.APPDATA||"./","postgresql","pgpass.conf"):zet.join(e.HOME||"./",".pgpass"));return n};q0.exports.usePgPass=function(t,e){return Object.prototype.hasOwnProperty.call(process.env,"PGPASSWORD")?!1:H6?!0:(e=e||"<unkn>",yTn(t.mode)?t.mode&(mTn|fTn)?(Gge('WARNING: password file "%s" has group or world access; permissions should be u=rw (0600) or less',e),!1):!0:(Gge('WARNING: password file "%s" is not a plain file',e),!1))};var wTn=q0.exports.match=function(t,e){return sB.slice(0,-1).reduce(function(n,r,i){return i==1&&Number(t[r]||hTn)===Number(e[r])?n&&!0:n&&(e[r]==="*"||e[r]===t[r])},!0)};q0.exports.getPassword=function(t,e,n){var r,i=e.pipe(pTn());function o(c){var u=xTn(c);u&&bTn(u)&&wTn(t,u)&&(r=u[ETn],i.end())}var s=function(){e.destroy(),n(r)},a=function(c){e.destroy(),Gge("WARNING: error on reading file: %s",c),n(void 0)};e.on("error",a),i.on("data",o).on("end",s).on("error",a)};var xTn=q0.exports.parseLine=function(t){if(t.length<11||t.match(/^\s+#/))return null;for(var e="",n="",r=0,i=0,o=0,s={},a=!1,c=function(l,d,p){var h=t.substring(d,p);Object.hasOwnProperty.call(process.env,"PGPASS_NO_DEESCAPE")||(h=h.replace(/\\([:\\])/g,"$1")),s[sB[l]]=h},u=0;u<t.length-1;u+=1){if(e=t.charAt(u+1),n=t.charAt(u),a=r==Hge-1,a){c(r,i);break}u>=0&&e==":"&&n!=="\\"&&(c(r,i,u+1),i=u+2,r+=1)}return s=Object.keys(s).length===Hge?s:null,s},bTn=q0.exports.isValidEntry=function(t){for(var e={0:function(s){return s.length>0},1:function(s){return s==="*"?!0:(s=Number(s),isFinite(s)&&s>0&&s<9007199254740992&&Math.floor(s)===s)},2:function(s){return s.length>0},3:function(s){return s.length>0},4:function(s){return s.length>0}},n=0;n<sB.length;n+=1){var r=e[n],i=t[sB[n]]||"",o=r(i);if(!o)return!1}return!0}});var Jet=Q((Qwi,qge)=>{"use strict";var Lwi=K("path"),Yet=K("fs"),G6=Ket();qge.exports=function(t,e){var n=G6.getFileName();Yet.stat(n,function(r,i){if(r||!G6.usePgPass(i,n))return e(void 0);var o=Yet.createReadStream(n);G6.getPassword(t,o,e)})};qge.exports.warnTo=G6.warnTo});var ttt=Q((Owi,ett)=>{var CTn=K("events").EventEmitter,Xet=GI(),UF=K("util"),q6=met(),ITn=L6(),vTn=mge(),jge=ket(),STn=QF(),_Tn=Wge(),kTn=uge(),Zet=UF.deprecate(()=>{},"Client.activeQuery is deprecated and will be removed in pg@9.0"),TTn=UF.deprecate(()=>{},"Client.queryQueue is deprecated and will be removed in pg@9.0."),RTn=UF.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."),BTn=UF.deprecate(()=>{},"Passing a custom Promise implementation to the Client/Pool constructor is deprecated and will be removed in pg@9.0."),DTn=UF.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.");function MTn(t,e){if(typeof t=="number")return Number.isFinite(t)?t:e;if(typeof t=="string"&&t.trim()!==""){let n=Number(t);return Number.isFinite(n)?n:e}return e}var j6=class extends CTn{constructor(e){super(),this.connectionParameters=new vTn(e),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 n=e||{};n.Promise&&BTn(),this._Promise=n.Promise||global.Promise,this._types=new ITn(n.types),this._ending=!1,this._ended=!1,this._connecting=!1,this._connected=!1,this._connectionError=!1,this._queryable=!0,this._activeQuery=null,this._txStatus=null,this.enableChannelBinding=!!n.enableChannelBinding,this.scramMaxIterations=MTn(n.scramMaxIterations,q6.DEFAULT_MAX_SCRAM_ITERATIONS),this.connection=n.connection||new _Tn({stream:n.stream,ssl:this.connectionParameters.ssl,sslNegotiation:this.connectionParameters.sslnegotiation,keepAlive:n.keepAlive||!1,keepAliveInitialDelayMillis:n.keepAliveInitialDelayMillis||0,encoding:this.connectionParameters.client_encoding||"utf8"}),this._queryQueue=[],this._sentQueryQueue=[],this.pipeline=!!n.pipeline,this.binary=n.binary||STn.binary,this.processID=null,this.secretKey=null,this.ssl=this.connectionParameters.ssl||!1,this.sslNegotiation=this.connectionParameters.sslnegotiation||"postgres",this.ssl&&this.ssl.key&&Object.defineProperty(this.ssl,"key",{enumerable:!1}),this._connectionTimeoutMillis=n.connectionTimeoutMillis||0}get activeQuery(){return Zet(),this._activeQuery}set activeQuery(e){Zet(),this._activeQuery=e}_getActiveQuery(){return this._activeQuery}_errorAllQueries(e){let n=i=>{process.nextTick(()=>{i.handleError(e,this.connection)})},r=this._getActiveQuery();r&&(n(r),this._activeQuery=null),this._sentQueryQueue.forEach(n),this._sentQueryQueue.length=0,this._queryQueue.forEach(n),this._queryQueue.length=0}_connect(e){let n=this,r=this.connection;if(this._connectionCallback=e,this._connecting||this._connected){let i=new Error("Client has already been connected. You cannot reuse a client.");process.nextTick(()=>{e(i)});return}this._connecting=!0,this._connectionTimeoutMillis>0&&(this.connectionTimeoutHandle=setTimeout(()=>{r._ending=!0,r.stream.destroy(new Error("timeout expired"))},this._connectionTimeoutMillis),this.connectionTimeoutHandle.unref&&this.connectionTimeoutHandle.unref()),this.host&&this.host.indexOf("/")===0?r.connect(this.host+"/.s.PGSQL."+this.port):r.connect(this.port,this.host),r.on("connect",function(){n.ssl?n.sslNegotiation!=="direct"&&r.requestSsl():r.startup(n.getStartupConf())}),r.on("sslconnect",function(){r.startup(n.getStartupConf())}),this._attachListeners(r),r.once("end",()=>{let i=this._ending?new Error("Connection terminated"):new Error("Connection terminated unexpectedly");clearTimeout(this.connectionTimeoutHandle),this._errorAllQueries(i),this._ended=!0,this._ending||(this._connecting&&!this._connectionError?this._connectionCallback?this._connectionCallback(i):this._handleErrorEvent(i):this._connectionError||this._handleErrorEvent(i)),process.nextTick(()=>{this.emit("end")})})}connect(e){if(e){this._connect(e);return}return new this._Promise((n,r)=>{this._connect(i=>{i?r(i):n(this)})})}_attachListeners(e){e.on("authenticationCleartextPassword",this._handleAuthCleartextPassword.bind(this)),e.on("authenticationMD5Password",this._handleAuthMD5Password.bind(this)),e.on("authenticationSASL",this._handleAuthSASL.bind(this)),e.on("authenticationSASLContinue",this._handleAuthSASLContinue.bind(this)),e.on("authenticationSASLFinal",this._handleAuthSASLFinal.bind(this)),e.on("backendKeyData",this._handleBackendKeyData.bind(this)),e.on("error",this._handleErrorEvent.bind(this)),e.on("errorMessage",this._handleErrorMessage.bind(this)),e.on("readyForQuery",this._handleReadyForQuery.bind(this)),e.on("notice",this._handleNotice.bind(this)),e.on("rowDescription",this._handleRowDescription.bind(this)),e.on("dataRow",this._handleDataRow.bind(this)),e.on("portalSuspended",this._handlePortalSuspended.bind(this)),e.on("emptyQuery",this._handleEmptyQuery.bind(this)),e.on("commandComplete",this._handleCommandComplete.bind(this)),e.on("parseComplete",this._handleParseComplete.bind(this)),e.on("copyInResponse",this._handleCopyInResponse.bind(this)),e.on("copyData",this._handleCopyData.bind(this)),e.on("notification",this._handleNotification.bind(this))}_getPassword(e){let n=this.connection;if(typeof this.password=="function")this._Promise.resolve().then(()=>this.password(this.connectionParameters)).then(r=>{if(r!==void 0){if(typeof r!="string"){n.emit("error",new TypeError("Password must be a string"));return}this.connectionParameters.password=this.password=r}else this.connectionParameters.password=this.password=null;e()}).catch(r=>{n.emit("error",r)});else if(this.password!==null)e();else try{Jet()(this.connectionParameters,i=>{i!==void 0&&(RTn(),this.connectionParameters.password=this.password=i),e()})}catch(r){this.emit("error",r)}}_handleAuthCleartextPassword(e){this._getPassword(()=>{this.connection.password(this.password)})}_handleAuthMD5Password(e){this._getPassword(async()=>{try{let n=await kTn.postgresMd5PasswordHash(this.user,this.password,e.salt);this.connection.password(n)}catch(n){this.emit("error",n)}})}_handleAuthSASL(e){this._getPassword(()=>{try{this.saslSession=q6.startSession(e.mechanisms,this.enableChannelBinding&&this.connection.stream,this.scramMaxIterations),this.connection.sendSASLInitialResponseMessage(this.saslSession.mechanism,this.saslSession.response)}catch(n){this.connection.emit("error",n)}})}async _handleAuthSASLContinue(e){try{await q6.continueSession(this.saslSession,this.password,e.data,this.enableChannelBinding&&this.connection.stream),this.connection.sendSCRAMClientFinalMessage(this.saslSession.response)}catch(n){this.connection.emit("error",n)}}_handleAuthSASLFinal(e){try{q6.finalizeSession(this.saslSession,e.data),this.saslSession=null}catch(n){this.connection.emit("error",n)}}_handleBackendKeyData(e){this.processID=e.processID,this.secretKey=e.secretKey}_handleReadyForQuery(e){this._connecting&&(this._connecting=!1,this._connected=!0,clearTimeout(this.connectionTimeoutHandle),this._connectionCallback&&(this._connectionCallback(null,this),this._connectionCallback=null),this.emit("connect"));let n=this._getActiveQuery();this._activeQuery=null,this._txStatus=e?.status??null,this.readyForQuery=!0,n&&n.handleReadyForQuery(this.connection),this._pulseQueryQueue()}_handleErrorWhileConnecting(e){if(!this._connectionError){if(this._connectionError=!0,clearTimeout(this.connectionTimeoutHandle),this._connectionCallback)return this._connectionCallback(e);this.emit("error",e)}}_handleErrorEvent(e){if(this._connecting)return this._handleErrorWhileConnecting(e);this._queryable=!1,this._errorAllQueries(e),this.emit("error",e)}_handleErrorMessage(e){if(this._connecting)return this._handleErrorWhileConnecting(e);let n=this._getActiveQuery();if(!n){this._handleErrorEvent(e);return}this._activeQuery=null,n.name&&delete this.connection.submittedNamedStatements[n.name],n.handleError(e,this.connection)}_handleRowDescription(e){let n=this._getActiveQuery();if(n==null){let r=new Error("Received unexpected rowDescription message from backend.");this._handleErrorEvent(r);return}n.handleRowDescription(e)}_handleDataRow(e){let n=this._getActiveQuery();if(n==null){let r=new Error("Received unexpected dataRow message from backend.");this._handleErrorEvent(r);return}n.handleDataRow(e)}_handlePortalSuspended(e){let n=this._getActiveQuery();if(n==null){let r=new Error("Received unexpected portalSuspended message from backend.");this._handleErrorEvent(r);return}n.handlePortalSuspended(this.connection)}_handleEmptyQuery(e){let n=this._getActiveQuery();if(n==null){let r=new Error("Received unexpected emptyQuery message from backend.");this._handleErrorEvent(r);return}n.handleEmptyQuery(this.connection)}_handleCommandComplete(e){let n=this._getActiveQuery();if(n==null){let r=new Error("Received unexpected commandComplete message from backend.");this._handleErrorEvent(r);return}n.handleCommandComplete(e,this.connection)}_handleParseComplete(){let e=this._getActiveQuery();if(e==null){let n=new Error("Received unexpected parseComplete message from backend.");this._handleErrorEvent(n);return}e.name&&(this.connection.parsedStatements[e.name]=e.text,delete this.connection.submittedNamedStatements[e.name])}_handleCopyInResponse(e){let n=this._getActiveQuery();if(n==null){let r=new Error("Received unexpected copyInResponse message from backend.");this._handleErrorEvent(r);return}n.handleCopyInResponse(this.connection)}_handleCopyData(e){let n=this._getActiveQuery();if(n==null){let r=new Error("Received unexpected copyData message from backend.");this._handleErrorEvent(r);return}n.handleCopyData(e,this.connection)}_handleNotification(e){this.emit("notification",e)}_handleNotice(e){this.emit("notice",e)}getStartupConf(){let e=this.connectionParameters,n={user:e.user,database:e.database},r=e.application_name||e.fallback_application_name;return r&&(n.application_name=r),e.replication&&(n.replication=""+e.replication),e.statement_timeout&&(n.statement_timeout=String(parseInt(e.statement_timeout,10))),e.lock_timeout&&(n.lock_timeout=String(parseInt(e.lock_timeout,10))),e.idle_in_transaction_session_timeout&&(n.idle_in_transaction_session_timeout=String(parseInt(e.idle_in_transaction_session_timeout,10))),e.options&&(n.options=e.options),n}cancel(e,n){if(e.activeQuery===n){let r=this.connection;this.host&&this.host.indexOf("/")===0?r.connect(this.host+"/.s.PGSQL."+this.port):r.connect(this.port,this.host),r.on("connect",function(){r.cancel(e.processID,e.secretKey)})}else e._queryQueue.indexOf(n)!==-1?e._queryQueue.splice(e._queryQueue.indexOf(n),1):e._sentQueryQueue.indexOf(n)!==-1&&(n.callback=()=>{})}setTypeParser(e,n,r){return this._types.setTypeParser(e,n,r)}getTypeParser(e,n){return this._types.getTypeParser(e,n)}escapeIdentifier(e){return Xet.escapeIdentifier(e)}escapeLiteral(e){return Xet.escapeLiteral(e)}_pulseQueryQueue(){if(this.pipeline){this._pulsePipelinedQueryQueue();return}if(this.readyForQuery===!0){this._activeQuery=this._queryQueue.shift();let e=this._getActiveQuery();if(e){this.readyForQuery=!1,this.hasExecuted=!0;let n=e.submit(this.connection);n&&process.nextTick(()=>{e.handleError(n,this.connection),this.readyForQuery=!0,this._pulseQueryQueue()})}else this.hasExecuted&&(this._activeQuery=null,this.emit("drain"))}}_pulsePipelinedQueryQueue(){if(!(!this._connected||!this._queryable)){for(;this._queryQueue.length>0;){let e=this._queryQueue.shift();this.hasExecuted=!0;let n=e.submit(this.connection);if(n){process.nextTick(()=>{e.handleError(n,this.connection)});continue}this._sentQueryQueue.push(e)}this.readyForQuery&&!this._activeQuery&&this._sentQueryQueue.length>0&&(this._activeQuery=this._sentQueryQueue.shift(),this.readyForQuery=!1),!this._activeQuery&&this._sentQueryQueue.length===0&&this._queryQueue.length===0&&this.hasExecuted&&this.emit("drain")}}query(e,n,r){let i,o;if(e==null)throw new TypeError("Client was passed a null or undefined query");if(typeof e.submit=="function")o=i=e,i.callback||(typeof n=="function"?i.callback=n:r&&(i.callback=r));else if(i=new jge(e,n,r),!i.callback)o=new this._Promise((a,c)=>{i.callback=(u,l)=>u?c(u):a(l)}).catch(a=>{throw Error.captureStackTrace(a),a});else if(typeof i.callback!="function")throw new TypeError("callback is not a function");let s=e.query_timeout||this.connectionParameters.query_timeout;if(s){let a=i.callback||(()=>{}),c=setTimeout(()=>{let u=new Error("Query read timeout");process.nextTick(()=>{i.handleError(u,this.connection)}),a(u),i.callback=()=>{};let l=this._queryQueue.indexOf(i);if(l>-1)this._queryQueue.splice(l,1);else if(this.pipeline){this.connection.stream.destroy();return}this._pulseQueryQueue()},s);i.callback=(u,l)=>{clearTimeout(c),a(u,l)}}if(this.binary&&!i.binary&&(i.binary=!0),i._result&&!i._result._types&&(i._result._types=this._types),this.pipeline){let a=typeof e.submit=="function"&&!(i instanceof jge)?"Custom query classes such as pg-cursor and pg-query-stream are":i.rows?"The `rows` option is":null;if(a)return process.nextTick(()=>{i.handleError(new Error(`${a} not supported in pipeline mode`),this.connection)}),o}return this._queryable?this._ending?(process.nextTick(()=>{i.handleError(new Error("Client was closed and is not queryable"),this.connection)}),o):(this._queryQueue.length>0&&!this.pipeline&&DTn(),this._queryQueue.push(i),this._pulseQueryQueue(),o):(process.nextTick(()=>{i.handleError(new Error("Client has encountered a connection error and is not queryable"),this.connection)}),o)}ref(){this.connection.ref()}unref(){this.connection.unref()}getTransactionStatus(){return this._txStatus}end(e){if(this._ending=!0,!this.connection._connecting||this._ended)if(e){e();return}else return this._Promise.resolve();if(this._queryable?this.pipeline&&(this._getActiveQuery()||this._sentQueryQueue.length>0||this._queryQueue.length>0)?this.once("drain",()=>this.connection.end()):this._getActiveQuery()?this.connection.stream.destroy():this.connection.end():this.connection.stream.destroy(),e)this.connection.once("end",e);else return new this._Promise(n=>{this.connection.once("end",n)})}get queryQueue(){return TTn(),this._queryQueue}};j6.Query=jge;ett.exports=j6});var itt=Q((Fwi,rtt)=>{"use strict";var PTn=K("events").EventEmitter,zge=function(){},ntt=(t,e)=>{let n=t.findIndex(e);return n===-1?void 0:t.splice(n,1)[0]},Vge=class{constructor(e,n,r){this.client=e,this.idleListener=n,this.timeoutId=r}},aB=class{constructor(e){this.callback=e}};function NTn(){throw new Error("Release called on client which has already been released to the pool.")}function z6(t,e){if(e)return{callback:e,result:void 0};let n,r,i=function(s,a){s?n(s):r(a)},o=new t(function(s,a){r=s,n=a}).catch(s=>{throw Error.captureStackTrace(s),s});return{callback:i,result:o}}function LTn(t,e){return function n(r){r.client=e,e.removeListener("error",n),e.on("error",()=>{t.log("additional client error after disconnection due to error",r)}),t._remove(e),t.emit("error",r,e)}}var Kge=class extends PTn{constructor(e,n){super(),this.options=Object.assign({},e),e!=null&&"password"in e&&Object.defineProperty(this.options,"password",{configurable:!0,enumerable:!1,writable:!0,value:e.password}),e!=null&&e.ssl&&e.ssl.key&&Object.defineProperty(this.options.ssl,"key",{enumerable:!1}),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||n||Yge().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(e){let n=this.Promise;return typeof n.try=="function"?n.try(e):new n(r=>r(e()))}_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){this.log("pulse queue on ending"),this._idle.length&&this._idle.slice().map(n=>{this._remove(n.client)}),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 e=this._pendingQueue.shift();if(this._idle.length){let n=this._idle.pop();clearTimeout(n.timeoutId);let r=n.client;r.ref&&r.ref();let i=n.idleListener;return this._acquireClient(r,e,i,!1)}if(!this._isFull())return this.newClient(e);throw new Error("unexpected condition")}_remove(e,n){let r=ntt(this._idle,o=>o.client===e);r!==void 0&&clearTimeout(r.timeoutId),this._clients=this._clients.filter(o=>o!==e);let i=this;e.end(()=>{i.emit("remove",e),typeof n=="function"&&n()})}connect(e){if(this.ending){let i=new Error("Cannot use a pool after calling end on the pool");return e?e(i):this.Promise.reject(i)}let n=z6(this.Promise,e),r=n.result;if(this._isFull()||this._idle.length){if(this._idle.length&&process.nextTick(()=>this._pulseQueue()),!this.options.connectionTimeoutMillis)return this._pendingQueue.push(new aB(n.callback)),r;let i=(a,c,u)=>{clearTimeout(s),n.callback(a,c,u)},o=new aB(i),s=setTimeout(()=>{ntt(this._pendingQueue,a=>a.callback===i),o.timedOut=!0,n.callback(new Error("timeout exceeded when trying to connect"))},this.options.connectionTimeoutMillis);return s.unref&&s.unref(),this._pendingQueue.push(o),r}return this.newClient(new aB(n.callback)),r}newClient(e){let n=new this.Client(this.options);this._clients.push(n);let r=LTn(this,n);this.log("checking client timeout");let i,o=!1;this.options.connectionTimeoutMillis&&(i=setTimeout(()=>{n.connection?(this.log("ending client due to timeout"),o=!0,n.connection.stream.destroy()):n.isConnected()||(this.log("ending client due to timeout"),o=!0,n.end())},this.options.connectionTimeoutMillis)),this.log("connecting new client"),n.connect(s=>{if(i&&clearTimeout(i),n.on("error",r),s)this.log("client failed to connect",s),this._clients=this._clients.filter(a=>a!==n),o&&(s=new Error("Connection terminated due to connection timeout",{cause:s})),this._pulseQueue(),e.timedOut||e.callback(s,void 0,zge);else{if(this.log("new client connected"),this.options.onConnect){this._promiseTry(()=>this.options.onConnect(n)).then(()=>{this._afterConnect(n,e,r)},a=>{this._clients=this._clients.filter(c=>c!==n),n.end(()=>{this._pulseQueue(),e.timedOut||e.callback(a,void 0,zge)})});return}return this._afterConnect(n,e,r)}})}_afterConnect(e,n,r){if(this.options.maxLifetimeSeconds!==0){let i=setTimeout(()=>{this.log("ending client due to expired lifetime"),this._expired.add(e),this._idle.findIndex(s=>s.client===e)!==-1&&this._acquireClient(e,new aB((s,a,c)=>c()),r,!1)},this.options.maxLifetimeSeconds*1e3);i.unref(),e.once("end",()=>clearTimeout(i))}return this._acquireClient(e,n,r,!0)}_acquireClient(e,n,r,i){i&&this.emit("connect",e),this.emit("acquire",e),e.release=this._releaseOnce(e,r),e.removeListener("error",r),n.timedOut?i&&this.options.verify?this.options.verify(e,e.release):e.release():i&&this.options.verify?this.options.verify(e,o=>{if(o)return e.release(o),n.callback(o,void 0,zge);n.callback(void 0,e,e.release)}):n.callback(void 0,e,e.release)}_releaseOnce(e,n){let r=!1;return i=>{r&&NTn(),r=!0,this._release(e,n,i)}}_release(e,n,r){if(e.on("error",n),e._poolUseCount=(e._poolUseCount||0)+1,this.emit("release",r,e),r||this.ending||!e._queryable||e._ending||e._poolUseCount>=this.options.maxUses)return e._poolUseCount>=this.options.maxUses&&this.log("remove expended client"),this._remove(e,this._pulseQueue.bind(this));if(this._expired.has(e))return this.log("remove expired client"),this._expired.delete(e),this._remove(e,this._pulseQueue.bind(this));let o;this.options.idleTimeoutMillis&&this._isAboveMin()&&(o=setTimeout(()=>{this._isAboveMin()&&(this.log("remove idle client"),this._remove(e,this._pulseQueue.bind(this)))},this.options.idleTimeoutMillis),this.options.allowExitOnIdle&&o.unref()),this.options.allowExitOnIdle&&e.unref(),this._idle.push(new Vge(e,n,o)),this._pulseQueue()}query(e,n,r){if(typeof e=="function"){let o=z6(this.Promise,e);return setImmediate(function(){return o.callback(new Error("Passing a function as the first parameter to pool.query is not supported"))}),o.result}typeof n=="function"&&(r=n,n=void 0);let i=z6(this.Promise,r);return r=i.callback,this.connect((o,s)=>{if(o)return r(o);let a=!1,c=u=>{a||(a=!0,s.release(u),r(u))};s.once("error",c),this.log("dispatching query");try{s.query(e,n,(u,l)=>{if(this.log("query dispatched"),s.removeListener("error",c),!a)return a=!0,s.release(u),u?r(u):r(void 0,l)})}catch(u){return s.release(u),r(u)}}),i.result}end(e){if(this.log("ending"),this.ending){let r=new Error("Called end on pool more than once");return e?e(r):this.Promise.reject(r)}this.ending=!0;let n=z6(this.Promise,e);return this._endCallback=n.callback,this._pulseQueue(),n.result}get waitingCount(){return this._pendingQueue.length}get idleCount(){return this._idle.length}get expiredCount(){return this._clients.reduce((e,n)=>e+(this._expired.has(n)?1:0),0)}get totalCount(){return this._clients.length}};rtt.exports=Kge});var att=Q((Uwi,stt)=>{"use strict";var ott=K("events").EventEmitter,QTn=K("util"),Jge=GI(),cB=stt.exports=function(t,e,n){ott.call(this),t=Jge.normalizeQueryConfig(t,e,n),this.text=t.text,this.values=t.values,this.name=t.name,this.queryMode=t.queryMode,this.callback=t.callback,this.state="new",this._arrayMode=t.rowMode==="array",this._emitRowEvents=!1,this.on("newListener",function(r){r==="row"&&(this._emitRowEvents=!0)}.bind(this))};QTn.inherits(cB,ott);var OTn={sqlState:"code",statementPosition:"position",messagePrimary:"message",messageDetail:"detail",messageHint:"hint",context:"where",schemaName:"schema",tableName:"table",columnName:"column",dataTypeName:"dataType",constraintName:"constraint",sourceFile:"file",sourceLine:"line",sourceFunction:"routine"};cB.prototype.handleError=function(t){let e=this.native&&this.native.pq.resultErrorFields();if(e)for(let n in e){let r=OTn[n]||n;t[r]=e[n]}this.callback?this.callback(t):this.emit("error",t),this.state="error"};cB.prototype.then=function(t,e){return this._getPromise().then(t,e)};cB.prototype.catch=function(t){return this._getPromise().catch(t)};cB.prototype._getPromise=function(){return this._promise?this._promise:(this._promise=new Promise(function(t,e){this._once("end",t),this._once("error",e)}.bind(this)),this._promise)};cB.prototype.submit=function(t){this.state="running";let e=this;this.native=t.native,t.native.arrayMode=this._arrayMode;let n=function(r,i,o){if(t.native.arrayMode=!1,setImmediate(function(){e.emit("_done")}),r)return e.handleError(r);e._emitRowEvents&&(o.length>1?i.forEach((s,a)=>{s.forEach(c=>{e.emit("row",c,o[a])})}):i.forEach(function(s){e.emit("row",s,o)})),e.state="end",e.emit("end",o),e.callback&&e.callback(null,o)};if(process.domain&&(n=process.domain.bind(n)),this.name){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 r=(this.values||[]).map(Jge.prepareValue);if(t.namedQueries[this.name]!==void 0){if(this.text&&t.namedQueries[this.name]!==this.text){let i=new Error(`Prepared statements must be unique - '${this.name}' was used for a different statement`);return n(i)}return t.native.execute(this.name,r,n)}return t.native.prepare(this.name,this.text,r.length,function(i){return i?n(i):(t.namedQueries[e.name]=e.text,e.native.execute(e.name,r,n))})}else if(this.values){if(!Array.isArray(this.values)){let i=new Error("Query values must be an array");return n(i)}let r=this.values.map(Jge.prepareValue);t.native.query(this.text,r,n)}else this.queryMode==="extended"?t.native.query(this.text,[],n):t.native.query(this.text,n)}});var ptt=Q(($wi,dtt)=>{var FTn=K("util"),ctt;try{ctt=K("pg-native")}catch(t){throw t}var UTn=L6(),utt=K("events").EventEmitter,$Tn=K("util"),WTn=mge(),ltt=att(),HTn=FTn.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."),Dc=dtt.exports=function(t){utt.call(this),t=t||{},this._Promise=t.Promise||global.Promise,this._types=new UTn(t.types),this.native=new ctt({types:this._types}),this._queryQueue=[],this._ending=!1,this._connecting=!1,this._connected=!1,this._queryable=!0,this.pipeline=!!t.pipeline,this._pipelineInFlight=!1;let e=this.connectionParameters=new WTn(t);t.nativeConnectionString&&(e.nativeConnectionString=t.nativeConnectionString),this.user=e.user,Object.defineProperty(this,"password",{configurable:!0,enumerable:!1,writable:!0,value:e.password}),this.database=e.database,this.host=e.host,this.port=e.port,this.namedQueries={}};Dc.Query=ltt;$Tn.inherits(Dc,utt);Dc.prototype._errorAllQueries=function(t){let e=n=>{process.nextTick(()=>{n.native=this.native,n.handleError(t)})};this._hasActiveQuery()&&(e(this._activeQuery),this._activeQuery=null),this._queryQueue.forEach(e),this._queryQueue.length=0};Dc.prototype._connect=function(t){let e=this;if(this._connecting){process.nextTick(()=>t(new Error("Client has already been connected. You cannot reuse a client.")));return}this._connecting=!0,this.connectionParameters.getLibpqConnectionString(function(n,r){if(e.connectionParameters.nativeConnectionString&&(r=e.connectionParameters.nativeConnectionString),n)return t(n);e.native.connect(r,function(i){if(i)return e.native.end(),t(i);e._connected=!0,e.native.on("error",function(o){e._queryable=!1,e._errorAllQueries(o),e.emit("error",o)}),e.native.on("notification",function(o){e.emit("notification",{channel:o.relname,payload:o.extra})}),e.emit("connect"),e._pulseQueryQueue(!0),t(null,this)})})};Dc.prototype.connect=function(t){if(t){this._connect(t);return}return new this._Promise((e,n)=>{this._connect(r=>{r?n(r):e(this)})})};Dc.prototype.query=function(t,e,n){let r,i,o,s,a;if(t==null)throw new TypeError("Client was passed a null or undefined query");if(typeof t.submit=="function")o=t.query_timeout||this.connectionParameters.query_timeout,i=r=t,typeof e=="function"&&(t.callback=e);else if(o=t.query_timeout||this.connectionParameters.query_timeout,r=new ltt(t,e,n),!r.callback){let c,u;i=new this._Promise((l,d)=>{c=l,u=d}).catch(l=>{throw Error.captureStackTrace(l),l}),r.callback=(l,d)=>l?u(l):c(d)}return o&&(a=r.callback||(()=>{}),s=setTimeout(()=>{let c=new Error("Query read timeout");process.nextTick(()=>{r.handleError(c,this.connection)}),a(c),r.callback=()=>{};let u=this._queryQueue.indexOf(r);u>-1&&this._queryQueue.splice(u,1),this._pulseQueryQueue()},o),r.callback=(c,u)=>{clearTimeout(s),a(c,u)}),this._queryable?this._ending?(r.native=this.native,process.nextTick(()=>{r.handleError(new Error("Client was closed and is not queryable"))}),i):(this._queryQueue.length>0&&!this.pipeline&&HTn(),this._queryQueue.push(r),this._pulseQueryQueue(),i):(r.native=this.native,process.nextTick(()=>{r.handleError(new Error("Client has encountered a connection error and is not queryable"))}),i)};Dc.prototype.end=function(t){let e=this;this._ending=!0,this._connecting&&!this._connected&&this.once("connect",()=>{this.end(()=>{})});let n;t||(n=new this._Promise(function(i,o){t=s=>s?o(s):i()}));let r=function(){e.native.end(function(){e._connected=!1,e._errorAllQueries(new Error("Connection terminated")),process.nextTick(()=>{e.emit("end"),t&&t()})})};return this.pipeline&&(this._pipelineInFlight||this._queryQueue.length>0)?this.once("drain",r):r(),n};Dc.prototype._hasActiveQuery=function(){return this._activeQuery&&this._activeQuery.state!=="error"&&this._activeQuery.state!=="end"};Dc.prototype._pulseQueryQueue=function(t){if(!this._connected)return;if(this.pipeline&&!t)return this._pulsePipelinedQueryQueue();if(this._hasActiveQuery())return;let e=this._queryQueue.shift();if(!e){t||this.emit("drain");return}this._activeQuery=e,e.submit(this);let n=this;e.once("_done",function(){n._pulseQueryQueue()})};Dc.prototype._pulsePipelinedQueryQueue=function(){if(!this._connected||this._pipelineInFlight)return;if(this._queryQueue.length===0){this.hasExecuted&&this.emit("drain");return}this._pipelineInFlight=!0;let t=this,e=[],n=[],r=GI();for(;this._queryQueue.length>0;){let i=this._queryQueue.shift();this.hasExecuted=!0,n.push(i);let o=i.values?i.values.map(r.prepareValue):null,s={text:i.text,name:i.name,arrayMode:i._arrayMode};o&&(s.values=o),i.name&&this.namedQueries[i.name]&&(s._alreadyPrepared=!0),e.push(s)}this.native.pipeline(e,function(i,o){if(t._pipelineInFlight=!1,i){t._connected=!1,t._queryable=!1;for(let s=0;s<n.length;s++){let a=n[s];a.native=t.native,a.handleError(i)}t._errorAllQueries(i),t.emit("error",i),t.emit("end");return}for(let s=0;s<n.length;s++){let a=n[s],c=o[s];a.native=t.native,c.err?a.handleError(c.err):(a.name&&(t.namedQueries[a.name]=a.text),a.state="end",a.emit("end",c.result),a.callback&&a.callback(null,c.result)),setImmediate(function(){a.emit("_done")})}t._pulsePipelinedQueryQueue()})};Dc.prototype.cancel=function(t){this._activeQuery===t?this.native.cancel(function(){}):this._queryQueue.indexOf(t)!==-1&&this._queryQueue.splice(this._queryQueue.indexOf(t),1)};Dc.prototype.ref=function(){};Dc.prototype.unref=function(){};Dc.prototype.setTypeParser=function(t,e,n){return this._types.setTypeParser(t,e,n)};Dc.prototype.getTypeParser=function(t,e){return this._types.getTypeParser(t,e)};Dc.prototype.isConnected=function(){return this._connected};Dc.prototype.getTransactionStatus=function(){return this.native.getTransactionStatus()}});var Xge=Q((Wwi,htt)=>{"use strict";htt.exports=ptt()});var Yge=Q((Gwi,V6)=>{"use strict";var GTn=ttt(),qTn=QF(),jTn=Wge(),zTn=gge(),VTn=GI(),KTn=itt(),YTn=L6(),{DatabaseError:JTn}=Fge(),{escapeIdentifier:XTn,escapeLiteral:ZTn}=GI(),eRn=t=>class extends KTn{constructor(n){super(n,t)}},mtt=function(t){this.defaults=qTn,this.Client=t,this.Query=this.Client.Query,this.Pool=eRn(this.Client),this._pools=[],this.Connection=jTn,this.types=LF(),this.DatabaseError=JTn,this.TypeOverrides=YTn,this.escapeIdentifier=XTn,this.escapeLiteral=ZTn,this.Result=zTn,this.utils=VTn},ftt=GTn,gtt=!1;try{gtt=!!process.env.NODE_PG_FORCE_NATIVE}catch{}gtt&&(ftt=Xge());V6.exports=new mtt(ftt);Object.defineProperty(V6.exports,"native",{configurable:!0,enumerable:!1,get(){let t=null;try{t=new mtt(Xge())}catch(e){if(e.code!=="MODULE_NOT_FOUND")throw e}return Object.defineProperty(V6.exports,"native",{value:t}),t}})});var Xd,qwi,jwi,zwi,Vwi,Kwi,Ywi,Jwi,Xwi,Zwi,exi,txi,Att,ytt=y(()=>{Xd=cn(Yge(),1),qwi=Xd.default.Client,jwi=Xd.default.Pool,zwi=Xd.default.Connection,Vwi=Xd.default.types,Kwi=Xd.default.Query,Ywi=Xd.default.DatabaseError,Jwi=Xd.default.escapeIdentifier,Xwi=Xd.default.escapeLiteral,Zwi=Xd.default.Result,exi=Xd.default.TypeOverrides,txi=Xd.default.defaults,Att=Xd.default});var tRn,nRn,Zge,ixi,Ett=y(()=>{"use strict";ytt();tRn=["mail","node","grant","run_event","report","structured_request","queue","spend_limits","environment_image","fault_retry","settings","machine","machine_call","document","review","execution_exit"],nRn=new Set(tRn),Zge=class{dirty=new Map;subscribers=new Set;scheduled;checkIntervalMs;checkTimeoutMs;reconnectMs;constructor(e={}){this.checkIntervalMs=e.checkIntervalMs??3e4,this.checkTimeoutMs=e.checkTimeoutMs??1e4,this.reconnectMs=e.reconnectMs??1e3}async subscribe(e,n={}){let r={listener:e,kinds:new Set(n.kinds??["mail","node"]),onListenStart:n.onListenStart};return this.subscribers.add(r),this.listener!==void 0&&r.onListenStart!==void 0&&queueMicrotask(()=>{this.subscribers.has(r)&&this.callListenStart(r)}),()=>{this.subscribers.delete(r)}}markMail(e){this.mark("mail",e)}markNode(e){this.mark("node",e)}markSignal(e,n){this.mark(e,n)}mark(e,n){let r=`${e}:${n}`;this.dirty.has(r)||this.dirty.set(r,{id:n,kind:e}),this.scheduled??=setImmediate(()=>this.flush())}flush(){this.scheduled=void 0;let e=[...this.dirty.values()];this.dirty.clear();for(let{id:n,kind:r}of e)for(let i of this.subscribers)if(i.kinds.has(r))try{i.listener(n,r)}catch{}}callListenStart(e){try{e.onListenStart?.()}catch{}}async listen(e){this.listener!==void 0||this.listening!==void 0||(this.url=e,this.listening=this.connectListener().finally(()=>{this.listening=void 0}),await this.listening)}listener;listening;url;reconnect;check;async connectListener(){let e=new Att.Client({connectionString:this.url,application_name:`crtr-signal-${process.pid}`,keepAlive:!0});e.on("notification",r=>{let i=r.payload??"",o=i.indexOf(":");if(o<0)return;let s=i.slice(0,o);nRn.has(s)&&this.mark(s,i.slice(o+1))});let n=()=>{this.listener===e&&(this.dropListener(e),this.scheduleReconnect())};e.on("error",n),e.on("end",n);try{await e.connect(),await e.query("LISTEN crtr_signal")}catch(r){throw e.removeAllListeners(),e.on("error",()=>{}),e.end().catch(()=>{}),r}if(this.url===void 0){e.removeAllListeners(),e.on("error",()=>{}),e.end().catch(()=>{});return}this.listener=e,this.startChecks(e,n);for(let r of[...this.subscribers])this.callListenStart(r)}startChecks(e,n){this.stopChecks(),this.check=setInterval(()=>{if(this.listener!==e)return;let r,i=new Promise((o,s)=>{r=setTimeout(()=>s(new Error("listen connection check timed out")),this.checkTimeoutMs)});Promise.race([e.query("SELECT 1"),i]).catch(()=>n()).finally(()=>clearTimeout(r))},this.checkIntervalMs),this.check.unref()}stopChecks(){this.check!==void 0&&clearInterval(this.check),this.check=void 0}dropListener(e){this.listener=void 0,this.stopChecks(),e.removeAllListeners(),e.on("error",()=>{}),e.end().catch(()=>{})}scheduleReconnect(){this.url===void 0||this.reconnect!==void 0||(this.reconnect=setTimeout(()=>{this.reconnect=void 0,this.url!==void 0&&(this.listening=this.connectListener().catch(()=>this.scheduleReconnect()).finally(()=>{this.listening=void 0}))},this.reconnectMs))}close(){this.url=void 0,this.reconnect!==void 0&&clearTimeout(this.reconnect),this.reconnect=void 0,this.stopChecks();let e=this.listener;return this.listener=void 0,this.scheduled!==void 0&&clearImmediate(this.scheduled),this.scheduled=void 0,this.dirty.clear(),this.subscribers.clear(),e===void 0?Promise.resolve():(e.removeAllListeners("notification"),e.removeAllListeners("error"),e.on("error",()=>{}),e.end().catch(()=>{}))}},ixi=new Zge});var wtt=y(()=>{"use strict";RF()});function aRn(t){switch(t){case oRn:return"context-nudge";case rRn:return"bearings";case sRn:return"review-boundary";case iRn:return"situational";default:return}}function tAe(t){return t.replace(/&(?:amp|lt|gt|quot|apos);/g,e=>({"&amp;":"&","&lt;":"<","&gt;":">","&quot;":'"',"&apos;":"'"})[e])}function eAe(t){let e={};K6.lastIndex=0;let n=0;for(;n<t.length&&!/^\s*$/.test(t.slice(n));){K6.lastIndex=n;let r=K6.exec(t);if(r===null)return null;let[,i,o,s]=r;if(i===void 0||Object.hasOwn(e,i))return null;e[i]=tAe(o??s??""),n=K6.lastIndex}return e}function nAe(t){return typeof t.content=="string"?t.content:Array.isArray(t.content)?t.content.filter(e=>typeof e=="object"&&e!==null&&e.type==="text"&&typeof e.text=="string").map(e=>e.text).join(""):""}function cRn(t){let e=[],n=/<from\b([^>]*)>([\s\S]*?)<\/from>/g;for(let r of t.matchAll(n)){let i=eAe(r[1]??"");if(i?.id===void 0)continue;let o=[],s=r[2]??"",a=/<entry\b([^>]*)>([\s\S]*?)<\/entry>/g;for(let u of s.matchAll(a)){let l=eAe(u[1]??"");if(l?.kind===void 0)continue;let d=l.disposition==="human-answer"||l.disposition==="human-canceled"?l.disposition:"report";o.push({kind:l.kind,disposition:d,body:tAe(u[2]??""),...l.ref===void 0?{}:{ref:l.ref}})}let c=i.updates===void 0?Number.NaN:Number(i.updates);e.push({id:i.id,updates:Number.isFinite(c)?c:o.length,finished:i.finished==="true"||o.some(u=>u.kind==="final"),entries:o})}return e}function uRn(t,e,n,r){return{kind:t,facts:e,body:n,senders:r}}function vtt(t){let e=/^<runtime\b([^>]*)>/.exec(t);if(e===null||!t.endsWith("</runtime>"))return null;let n=eAe(e[1]??"");if(n?.kind===void 0)return null;let r=t.slice(e[0].length,-10),{kind:i,...o}=n,s=Object.freeze(o),a=i.includes(":")?tAe(r):r;return uRn(i,s,a,i==="inbox"?cRn(a):[])}function uB(t){let e=nAe(t),n=vtt(e);if(n!==null)return n;if(t.role!=="custom")return null;let r=aRn(t.customType);return r===void 0?null:{kind:r,facts:Object.freeze({}),body:e,senders:[]}}function VI(t){return t.disposition==="human-answer"&&vtt(t.body.trim())===null}var rRn,iRn,oRn,sRn,xtt,btt,Ctt,Itt,K6,KI=y(()=>{"use strict";rRn="crtr-context",iRn="crtr-situational-context",oRn="crtr-context-nudge",sRn="crtr-review-boundary",xtt="Provider credentials were just updated (a new login landed). Your previous turn stopped on a provider authentication failure. Continue from where you left off and retry the work that failed.",btt="The network connection is back online. Your previous turn stopped on a connection error (the network was down). Continue from where you left off and retry the work that failed.",Ctt="Your previous turn stopped on a connection error reaching the model provider. Retrying now: continue from where you left off and retry the work that failed.",Itt="Your previous turn stopped on a provider fault. Continue from where you left off and retry the work that failed.";K6=/\s+([A-Za-z_:][A-Za-z0-9_:.-]*)\s*=\s*(?:"([^"]*)"|'([^']*)')/gy});var Stt=y(()=>{"use strict";KI()});function lRn(){let t=process.env.CRTR_API_URL;if(!(t===void 0||t==="")){if(!/^https?:\/\//.test(t))throw new Error(`CRTR_API_URL must be an http(s) URL: ${t}`);return t}}function TF(){let t=lRn();if(t===void 0)return fw({autostart:!1});let e=xZe();if(e===void 0)throw new Error("broker has no node token for CRTR_API_URL");return new kg({baseUrl:t,headers:{authorization:`Bearer ${e}`}})}function _tt(t,e){return TF().appendNodeLog(t,{record:e,expected_execution_id:dRn()})}function dRn(){let t=OYe();if(t===void 0||t==="")throw new Error("broker launch is missing CRTR_EXECUTION_ID");return t}async function ktt(t,e){return TF().recordNodeFault(t,e)}async function Ttt(t,e={}){return TF().clearNodeFault(t,{...e.link===void 0?{}:{link:e.link},...e.preserveEpisode===void 0?{}:{preserve_episode:e.preserveEpisode}}).then(n=>n.cleared)}var RF=y(()=>{"use strict";T6();bZe();R6();hw();Kfe();Bc();IZe();YI();Ett();wtt();Stt()});function hRn(t,e){Rtt=Rtt.then(async()=>{try{let{appended:n}=await _tt(t,e);n||process.stderr.write(`[broker] log.jsonl refused record: ${e}
99
99
  `)}catch(n){process.stderr.write(`[broker] log.jsonl append failed (${n instanceof Error?n.message:String(n)}): ${e}
100
- `)}})}function $l(t){let e=v6();if(e===void 0)return!1;if(e.component==="broker"&&e.node_id!==void 0&&t.node_id!==void 0&&t.node_id!==e.node_id)throw new TypeError(`broker event target node_id must match bound node_id; received ${t.node_id}`);if(t.level==="debug"&&process.env.CRTR_LOG!=="debug")return!1;let n=MXe({...t,component:e.component,...e.node_id===void 0?{}:{node_id:e.node_id},...e.stream_id===void 0?{}:{stream_id:e.stream_id}}),r=NXe(n);return e.component==="broker"&&e.node_id!==void 0&&(pRn??=BI())?(hRn(e.node_id,r),!0):e.component==="daemon"?SXe(e.path,r):h6(e.path,r)}var pRn,Rtt,YI=y(()=>{"use strict";wfe();PXe();LXe();Ofe();Bc();RF();Rtt=Promise.resolve()});var Btt,Dtt=y(()=>{"use strict";YI();Btt={sandboxUsdPerGbHour:"CRTR_LEDGER_SANDBOX_USD_PER_GB_HOUR",sandboxStandbyS:"CRTR_LEDGER_SANDBOX_STANDBY_S",storageUsdPerGbMonth:"CRTR_LEDGER_STORAGE_USD_PER_GB_MONTH",infraFreeUsdPerMonth:"CRTR_LEDGER_INFRA_FREE_USD_PER_MONTH",takePct:"CRTR_LEDGER_TAKE_PCT",r2Move:"CRTR_LEDGER_R2_MOVE"}});function Y6(t){return t.flatMap(e=>e.path===void 0?[]:[e.path])}var $F=y(()=>{"use strict"});var Mtt=y(()=>{"use strict"});import{createHash as mRn}from"node:crypto";function Ltt(t){return t===void 0?"absent":mRn("sha256").update(JSON.stringify(t)).digest("hex")}function Qtt(t,e){Ntt.set(t,e)}function j0(){let t;try{t=y6()}catch(n){if(n instanceof IF)return Ptt();if(n instanceof CF)return rAe??Ptt();throw n}let e=Ntt.get(t);if(e!==void 0)return e;if(rAe!==void 0)return rAe;throw new iAe(t)}function Ott(t){fRn=t}function Ftt(t){gRn=t}function HF(t){let e=j0().settings[t];return{settings:e===void 0?null:structuredClone(e),revision:Ltt(e)}}function Utt(t){let e=j0().state[t];return e===void 0?{marketplaces:{},plugins:{},activeCanvas:null}:structuredClone(e)}function $tt(){return structuredClone(j0().profiles)}function Wtt(t){let e=j0().profiles.find(n=>n.profileId===t);return e===void 0?null:structuredClone(e)}var WF,iAe,Ntt,Ptt,rAe,fRn,gRn,lB=y(()=>{"use strict";JR();WF=class extends Error{constructor(){super("settings changed since the supplied revision"),this.name="SettingsRevisionConflictError"}},iAe=class extends Error{constructor(e){super(`settings for ${e} are not loaded in this process`),this.name="PersonSettingsNotLoadedError"}},Ntt=new Map;Ptt=()=>({profiles:[],defaults:{},settings:{},state:{},apps:{}});fRn=async()=>{throw new Error("no settings transport installed in this process")}});var Htt=y(()=>{"use strict"});import{chmodSync as Gxi,existsSync as Gtt,mkdirSync as qxi,readFileSync as qtt,rmSync as jxi,writeFileSync as zxi}from"node:fs";import{dirname as Kxi,join as jtt}from"node:path";function yw(){let t=ARn();if(!Gtt(t))return;let e=JSON.parse(qtt(t,"utf8"));if(typeof e.apiUrl!="string"||typeof e.environmentId!="string"||typeof e.runId!="string"||typeof e.directoryUrl!="string")throw new Error(`${t} must hold {apiUrl, environmentId, runId, directoryUrl}`);let n=e.account!==void 0&&typeof e.account?.id=="string"&&typeof e.account.display=="string"?{id:e.account.id,display:e.account.display}:void 0;return{apiUrl:e.apiUrl,environmentId:e.environmentId,runId:e.runId,directoryUrl:e.directoryUrl,...n===void 0?{}:{account:n}}}function ERn(){let t=yRn();if(!Gtt(t))return;let e=JSON.parse(qtt(t,"utf8"));if(typeof e.runId!="string"||typeof e.apiUrl!="string"||typeof e.directoryUrl!="string"||e.state!=="running"&&e.state!=="committed"&&e.state!=="activated"||typeof e.account?.id!="string"||typeof e.account.display!="string")throw new Error(`${t} is not a move record`);return{runId:e.runId,apiUrl:e.apiUrl,directoryUrl:e.directoryUrl,account:{id:e.account.id,display:e.account.display},notify:typeof e.notify=="string"?e.notify:null,state:e.state,notified:e.notified===!0,pid:typeof e.pid=="number"?e.pid:0}}var ARn,yRn,ztt,Vtt,GF=y(()=>{"use strict";Jm();qd();Ol();ru();ARn=()=>jtt(Fl(),"machine.json");yRn=()=>jtt(Fl(),"import","move.json");ztt=()=>ERn()?.state==="committed",Vtt=t=>new os("move_unfinished",`crtr's records are already in your Northlight account, but this computer has not switched over${t===void 0?".":`: ${t}`}`,ji.USAGE,{next:"Run `crtr sys signin` to finish."})});function xRn(t){return t.grantee??"app:terminal"}function bRn(t){if(!Ktt.test(t))throw dw(`invalid profile id: ${t}`,{received:t,next:"Profile ids look like <slug>-<8-hex-chars> (as printed by `crtr profile new`). Pass an exact id or a profile name, not a raw path."})}function J6(t){bRn(t);let e=Wtt(t);if(e===null)throw d6(`profile not found: ${t}`,{received:t});return zXe(xRn(e.manifest),t).dir}function CRn(){return{entries:$tt(),unreadableIds:[]}}function X6(){return CRn().entries}function IRn(t){let e=X6(),n=vRn(e,t,Ytt);return n?{kind:"resolved",entry:n}:{kind:"absent"}}function vRn(t,e,n){if(Ktt.test(e)){let i=t.find(o=>n(o).profileId===e);if(i!==void 0)return i}let r=t.filter(i=>n(i).name===e);if(r.length===1)return r[0];if(r.length>1){let i=r.map(o=>n(o).profileId);throw yXe(`profile name "${e}" matches ${i.length} profiles: ${i.join(", ")}`,{received:e,candidates:i,next:`Re-run with one exact profile id: ${i.join(", ")}.`})}return null}function SRn(t,e,n){let r=t.map(i=>`${n(i).profileId} (${n(i).name})`);return d6(`profile not found: ${e}`,{received:e,available:r,next:r.length>0?`Re-run with one of the profiles on this host: ${r.join(", ")} \u2014 or create one with \`crtr profile new --name <name>\`.`:"No profiles exist on this host yet \u2014 create one with `crtr profile new --name <name>`."})}function Tg(t){let e=IRn(t);if(e.kind==="resolved")return e.entry;throw SRn(X6(),t,Ytt)}var Ktt,Ytt,JI=y(()=>{"use strict";ru();Jm();$F();Ol();lB();qd();Htt();JR();GF();Ktt=/^[a-z0-9]+(?:-[a-z0-9]+)*-[0-9a-f]{8}$/;Ytt=t=>({profileId:t.profileId,name:t.manifest.name})});import{homedir as Jtt}from"node:os";import{existsSync as _Rn,statSync as kRn}from"node:fs";import{join as Z6,resolve as Xtt,dirname as TRn,sep as oAe}from"node:path";function Zd(){return Z6(Fl(),"scope")}function RRn(t,e){if(!_Rn(t)||Ym(t)===Ym(Z6(Jtt(),NI))||Ym(t).startsWith(`${Ym(Tfe())}${oAe}`)&&t.endsWith(`${oAe}home${oAe}${NI}`)||!BI()&&(Ym(t)===Ym(e)||Ym(t)===Ym(b6())))return!1;try{return kRn(t).isDirectory()}catch{return!1}}function BRn(t=process.cwd()){return Ztt(t)[0]??null}function DRn(t,e){let n=[],r=Ym(Jtt()),i=Xtt(t);for(;;){let o=Z6(i,NI);if(RRn(o,e)&&n.push(o),Ym(i)===r)return n;let s=TRn(i);if(s===i)return n;i=s}}function Ztt(t=process.cwd(),e=Fme()||null){return MRn(t,e)}function MRn(t,e){let n=Xtt(t),r=Zd(),i=[n];if(!BI()&&e!==null&&e!=="")try{let{manifest:a}=Tg(e);i.push(...Y6(a.projects))}catch{}let o=new Set,s=[];for(let a of i)for(let c of DRn(a,r))o.has(c)||(o.add(c),s.push(c));return s}function ent(t){return BRn(t)}function z0(t){return t==="builtin"?null:t==="user"?Zd():ent()}function tnt(t){let e=t==="user"?Fl():z0(t);return e?Z6(e,"plugins"):null}var XI=y(()=>{"use strict";Bc();$F();ru();Mtt();qd();JI();Ol();Jm()});import{join as PRn}from"node:path";function NRn(t){return PRn(t,fXe,gXe)}function LRn(t){let e;try{e=UI(t)}catch(n){return{status:"broken",error:n instanceof Error?n.message:String(n)}}return e===null?{status:"absent"}:typeof e!="object"||Array.isArray(e)?{status:"broken",error:"manifest is not a JSON object"}:{status:"ok",manifest:e}}function QRn(t){return LRn(NRn(t))}function nnt(t){let e=QRn(t);return e.status==="ok"?e.manifest:null}var sAe=y(()=>{"use strict";ru();Ol()});import{existsSync as ORn,mkdirSync as FRn,readdirSync as int,rmSync as ont,rmdirSync as URn,statSync as $Rn,unlinkSync as WRn,writeFileSync as HRn}from"node:fs";import{randomUUID as GRn}from"node:crypto";function ant(t){return Math.min(t*2,qRn)}function cnt(t){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,t)}function cAe(t,e){return`${t}/${aAe}${e}`}function uAe(t){try{return int(t).find(e=>e.startsWith(aAe))?.slice(aAe.length)??null}catch{return null}}function unt(t){let e=Number(t.split(".",1)[0]);if(!Number.isSafeInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(n){return n.code==="EPERM"}}function VRn(t){try{return int(t).length===0}catch{return!1}}function KRn(t){try{return Date.now()-$Rn(t).mtimeMs}catch{return 0}}function YRn(t,e){let n=uAe(t);if(n!==null){if(unt(n))return;try{WRn(cAe(t,n))}catch(r){if(r.code==="ENOENT")return;throw r}}else{if(KRn(t)<=e)return;if(!VRn(t)){ont(t,{recursive:!0,force:!0});return}}try{URn(t)}catch(r){let i=r.code;if(i!=="ENOENT"&&i!=="ENOTEMPTY"&&i!=="EEXIST")throw r}}function eV(t){let e=uAe(t);if(e===null)return null;let n=Number(e.split(".",1)[0]);return Number.isSafeInteger(n)&&n>0?n:null}function lnt(t,e){let n=Date.now()+e,r=snt;for(;;){let i=uAe(t);if(i===null||Number(i.split(".",1)[0])===process.pid||!unt(i))return;let o=n-Date.now();if(o<=0)return;cnt(Math.min(r,o)),r=ant(r)}}function rnt(t,e){let n=`${process.pid}.${GRn()}`;try{return FRn(t,{mode:448}),HRn(cAe(t,n),"",{flag:"wx",mode:384}),{path:t,token:n}}catch(r){if(r.code!=="EEXIST")throw r;return YRn(t,e),null}}function ZI(t,e,n={}){let r=n.staleMs??jRn,i=Date.now()+(n.timeoutMs??zRn),o=snt,s=rnt(t,r);for(;s===null;){if(Date.now()>=i)throw n.timeoutError?.()??new Error(`timed out waiting for the exclusive lock: ${t}`);cnt(Math.min(o,Math.max(0,i-Date.now()))),o=ant(o),s=rnt(t,r)}try{return e()}finally{ORn(cAe(s.path,s.token))&&ont(s.path,{recursive:!0,force:!0})}}var aAe,snt,qRn,jRn,zRn,ev=y(()=>{"use strict";aAe="owner.",snt=10,qRn=250,jRn=3e4,zRn=5e3});import{join as JRn}from"node:path";function dnt(t,e){return JRn(t,"tmp",`${e}.swap.lock`)}function pnt(t,e){let n=eV(dnt(t,e));return n!==null&&n!==process.pid}function hnt(t,e){lnt(dnt(t,e),XRn)}var XRn,mnt=y(()=>{"use strict";ev();XRn=2e3});function tV(t,e){let n=t.apps[ZRn];return n===void 0&&e===null?null:{...e??{},plugins:structuredClone(n?.plugins??{}),marketplaces:structuredClone(n?.marketplaces??{})}}var ZRn,lAe=y(()=>{"use strict";Bc();lB();ZRn="app:terminal"});import{join as dAe}from"node:path";function eBn(t,e){let n=t==="user"?pF()?tV(j0(),HF("user").settings):HF("user").settings:UI(dAe(e,c6));return n&&n.plugins&&typeof n.plugins=="object"?n.plugins:{}}function tBn(t,e,n){let r=Object.keys(e);return r.every(i=>n.has(i))?[]:r.filter(i=>!n.has(i)&&pnt(t,i))}function nV(t,e){if(t==="user"&&A6())return[];let n=t!=="user"?dAe(e,"plugins"):tnt("user");if(n===void 0||!_fe(n))return[];let r=eBn(t,e),i=fnt(t,n,r),o=tBn(e,r,new Set(i.map(s=>s.name)));if(o.length===0)return i;for(let s of o)hnt(e,s);return fnt(t,n,r)}function fnt(t,e,n){let r=[];for(let i of kfe(e)){let o=dAe(e,i),s=nnt(o);if(!s)continue;let a=n[i],c=typeof a?.version=="string"?a.version:s.version;r.push({name:i,scope:t,root:o,manifest:s,enabled:typeof a?.enabled=="boolean"?a.enabled:!0,sourceMarketplace:typeof a?.source_marketplace=="string"?a.source_marketplace:void 0,version:c})}return r}var rV=y(()=>{"use strict";ru();Ol();sAe();mnt();JR();lB();lAe();XI()});import{existsSync as nBn,realpathSync as rBn}from"node:fs";import{basename as iBn,dirname as oBn,join as iCi,resolve as gnt}from"node:path";function dB(t){let e=gnt(t),n=e,r=[];for(;!nBn(n);){let i=oBn(n);if(i===n)return e;r.unshift(iBn(n)),n=i}return gnt(rBn(n),...r)}var Ant=y(()=>{"use strict"});function sBn(t){let e=zi.indexOf(t);return`less ${zi.map((r,i)=>i===e?"\u25CF":"\u25CB").map((r,i)=>i===0?r:`${i<=e?"\u2501\u2501\u2501\u2501":"\u2500\u2500\u2500\u2500"}${r}`).join("")} more ${oV[t]}`}function iV(t,e,n){let r=t.indexOf(e),i=r>=0?r:0;return t[(i+n+t.length)%t.length]}function ynt(t,e,n){let r=t.indexOf(e);return r>=0?t[(r+n+t.length)%t.length]:n>=0?t.find(i=>i>e)??t[0]:[...t].reverse().find(i=>i<e)??t[t.length-1]}function tv(t,e){return t==="true"?!0:t==="false"?!1:`${e} must be true or false`}function xnt(t,e){if(!/^\d+$/.test(t))return`${e} must be an integer >= 0`;let n=Number(t);return Number.isSafeInteger(n)?n:`${e} must be an integer >= 0`}function aBn(t,e){let n=xnt(t,e);return typeof n=="string"||n<1?`${e} must be an integer >= 1`:n}function wnt(t,e){let n=t.providerOptions[e];if(n!==void 0)return n;let r={};return t.providerOptions[e]=r,r}function dBn(){let t=[];for(let e of Object.values(bnt))e.surface==="settings"&&("setting"in e?t.push(e.setting):t.push(...Object.values(e.settings)));return t.sort((e,n)=>e.order-n.order)}var oV,Ent,cBn,uBn,qF,bnt,lBn,aCi,pAe=y(()=>{"use strict";ru();oV={replies:"Replies only",summaries:"Messages + summaries",tools:"Tool calls",previews:"Previews",full:"Full"};Ent=[!1,"notify","apply"],cBn=[0,1,6,12,24,48,72,168],uBn=[1,2,3,4,5,6,8,10,12],qF="openai-codex";bnt={schema_version:{surface:"specialized",owner:"internal schema migration"},marketplaces:{surface:"specialized",owner:"Plugins and pkg market commands"},plugins:{surface:"specialized",owner:"Plugins tab and pkg plugin commands"},auto_update:{surface:"settings",settings:{crtr:{key:"auto_update.crtr",label:"crouter updates",description:"Notify about crouter releases, install them automatically, or turn checks off.",valueConstraint:"true|false|notify|apply; true stores notify",applies:"Applies on the next crouter command.",group:"updates",order:70,format:t=>t.auto_update.crtr===!1?"off":t.auto_update.crtr,cycle:(t,e)=>{t.auto_update.crtr=iV(Ent,t.auto_update.crtr,e)},setFromString:(t,e)=>{let n=e==="true"?"notify":e;return n!=="notify"&&n!=="apply"&&n!=="false"?"auto_update.crtr must be notify, apply, or false":(t.auto_update.crtr=n==="false"?!1:n,null)}},content:{key:"auto_update.content",label:"Content updates",description:"Notify about plugin and marketplace updates, apply them automatically, or turn checks off.",valueConstraint:"false|notify|apply",applies:"Applies on the next crouter command.",group:"updates",order:80,format:t=>t.auto_update.content===!1?"off":t.auto_update.content,cycle:(t,e)=>{t.auto_update.content=iV(Ent,t.auto_update.content,e)},setFromString:(t,e)=>e!=="notify"&&e!=="apply"&&e!=="false"?"auto_update.content must be notify, apply, or false":(t.auto_update.content=e==="false"?!1:e,null)},interval_hours:{key:"auto_update.interval_hours",label:"Update interval",description:"Minimum hours between automatic update checks. Zero checks on every command.",valueConstraint:"integer >= 0",applies:"Applies on the next crouter command.",group:"updates",order:90,format:t=>`${t.auto_update.interval_hours}h`,cycle:(t,e)=>{t.auto_update.interval_hours=ynt(cBn,t.auto_update.interval_hours,e)},setFromString:(t,e)=>{let n=xnt(e,"auto_update.interval_hours");return typeof n=="string"?n:(t.auto_update.interval_hours=n,null)}}}},max_panes_per_window:{surface:"settings",setting:{key:"max_panes_per_window",label:"Maximum panes",description:"Maximum human-review panes placed in one tmux window before using another window.",valueConstraint:"integer >= 1",applies:"Applies to the next pane placement.",group:"panes",order:20,format:t=>String(t.max_panes_per_window),cycle:(t,e)=>{t.max_panes_per_window=ynt(uBn,t.max_panes_per_window,e)},setFromString:(t,e)=>{let n=aBn(e,"max_panes_per_window");return typeof n=="string"?n:(t.max_panes_per_window=n,null)}}},auto_open_child_viewers:{surface:"settings",setting:{key:"auto_open_child_viewers",label:"Open child panes",description:"Open each managed child beside its watched parent. Off keeps new children running in the background.",valueConstraint:"true|false",applies:"Applies to the next managed child created; independent roots still open their attended viewer.",group:"panes",order:10,format:t=>t.auto_open_child_viewers?"on":"off",cycle:t=>{t.auto_open_child_viewers=!t.auto_open_child_viewers},setFromString:(t,e)=>{let n=tv(e,"auto_open_child_viewers");return typeof n=="string"?n:(t.auto_open_child_viewers=n,null)}}},brokerThresholds:{surface:"specialized",owner:"Broker limits tab"},lifecycle:{surface:"specialized",owner:"sys config set lifecycle.unattendedParkMs"},completion_bell:{surface:"settings",setting:{key:"completion_bell",label:"Completion bell",description:"Ring a short sound when the node in an attached viewer finishes a turn.",valueConstraint:"true|false",applies:"Applies on the next turn end.",group:"display",order:41,format:t=>t.completion_bell?"on":"off",cycle:t=>{t.completion_bell=!t.completion_bell},setFromString:(t,e)=>{let n=tv(e,"completion_bell");return typeof n=="string"?n:(t.completion_bell=n,null)}}},working_gerunds:{surface:"specialized",owner:"sys config set working_gerunds"},whip_mode:{surface:"settings",setting:{key:"whip_mode",label:"Whip mode",description:"Play the whip animation when you send a prompt and when a viewer opens for an agent with an initial prompt.",valueConstraint:"true|false",applies:"Applies on the next attach.",group:"display",order:39,format:t=>t.whip_mode?"on":"off",cycle:t=>{t.whip_mode=!t.whip_mode},setFromString:(t,e)=>{let n=tv(e,"whip_mode");return typeof n=="string"?n:(t.whip_mode=n,null)}}},page_surface:{surface:"settings",setting:{key:"page_surface",label:"Page human surface",description:"This host reads pages in a browser rather than a terminal. Agents are told the page module runs as written, HTML pages are offered, and document review and live display leave the command tree.",valueConstraint:"true|false",applies:"Applies when human command help is assembled.",group:"display",order:37,format:t=>t.page_surface?"on":"off",cycle:t=>{t.page_surface=!t.page_surface},setFromString:(t,e)=>{let n=tv(e,"page_surface");return typeof n=="string"?n:(t.page_surface=n,null)}}},whip_messages:{surface:"specialized",owner:"sys config set whip_messages"},whip_message_mode:{surface:"settings",setting:{key:"whip_message_mode",label:"Whip message",description:"What the whip action sends: a random line from whip_messages, or the fixed \u201CGo faster\u201D.",valueConstraint:LI.join("|"),applies:"Applies on the next attach.",group:"display",order:40,format:t=>t.whip_message_mode==="go-faster"?"go faster":"random",cycle:(t,e)=>{t.whip_message_mode=iV(LI,t.whip_message_mode,e)},setFromString:(t,e)=>LI.includes(e)?(t.whip_message_mode=e,null):`whip_message_mode must be one of: ${LI.join("|")}`}},mouse_mode_default:{surface:"settings",setting:{key:"mouse_mode_default",label:"Default mouse mode",description:"Initial mouse wheel scrolling for each attached viewer.",valueConstraint:QI.join("|"),applies:"Applies on the next attach.",group:"display",order:38,format:t=>t.mouse_mode_default==="tmux"?"follow tmux":t.mouse_mode_default,cycle:(t,e)=>{t.mouse_mode_default=iV(QI,t.mouse_mode_default,e)},setFromString:(t,e)=>QI.includes(e)?(t.mouse_mode_default=e,null):`mouse_mode_default must be one of: ${QI.join("|")}`}},bash_tool_purpose:{surface:"settings",setting:{key:"bash_tool_purpose",label:"Bash purpose field",description:"Expose the optional purpose label to agents in the bash tool schema. Off removes the field without disabling the bash valve.",valueConstraint:"true|false",applies:"Applies on the next node session.",group:"display",order:25,format:t=>t.bash_tool_purpose?"on":"off",cycle:t=>{t.bash_tool_purpose=!t.bash_tool_purpose},setFromString:(t,e)=>{let n=tv(e,"bash_tool_purpose");return typeof n=="string"?n:(t.bash_tool_purpose=n,null)}}},verbosity:{surface:"settings",setting:{key:"verbosity",label:"Verbosity",description:"How much of a transcript the viewer shows, from one rewritten reply per message to every tool call untruncated. Ctrl+O shows more and Ctrl+Shift+O less in the open viewer only; this sets where every viewer starts.",valueConstraint:zi.join("|"),applies:"Applies on the next attach.",group:"display",order:30,format:t=>t.verbosity,display:t=>sBn(t.verbosity),cycle:(t,e)=>{let n=zi.indexOf(t.verbosity)+e;t.verbosity=zi[Math.max(0,Math.min(zi.length-1,n))]},setFromString:(t,e)=>zi.includes(e)?(t.verbosity=e,null):`verbosity must be one of: ${zi.join("|")}`}},document_port:{surface:"settings",setting:{key:"document_port",label:"Document browser port",description:"Fixed localhost port where crtrd serves editable document pages.",valueConstraint:"1-65535",applies:"Applies after daemon handover and on the next attach.",group:"display",order:37.5,format:t=>String(t.document_port),cycle:(t,e)=>{t.document_port=Math.max(1,Math.min(65535,t.document_port+e))},setFromString:(t,e)=>{let n=Number(e);return!/^\d+$/.test(e)||!Number.isInteger(n)||n<1||n>65535?"document_port must be an integer from 1 to 65535":(t.document_port=n,null)}}},detailed_tool_recaps:{surface:"settings",setting:{key:"detailed_tool_recaps",label:"Detailed tool recaps",description:"Show each document read and edited file in folded tool recaps. Off shows a compact count line instead.",valueConstraint:"true|false",applies:"Applies on the next attach.",group:"display",order:36,format:t=>t.detailed_tool_recaps?"on":"off",cycle:t=>{t.detailed_tool_recaps=!t.detailed_tool_recaps},setFromString:(t,e)=>{let n=tv(e,"detailed_tool_recaps");return typeof n=="string"?n:(t.detailed_tool_recaps=n,null)}}},keybindings:{surface:"specialized",owner:"Keybindings tab"},tmux_passthrough:{surface:"specialized",owner:"Keybindings tab"},providerOptions:{surface:"settings",settings:{"openai-codex.fastMode":{key:`providerOptions.${qF}.fastMode`,label:"Codex fast mode",description:"Serve Codex turns at the ChatGPT priority tier: about 1.5x faster generation for about 2x the credits. Displayed cost does not reflect the premium.",valueConstraint:"true|false",applies:"Applies on each node's next turn.",group:"providers",order:40,format:t=>t.providerOptions[qF]?.fastMode?"on":"off",cycle:t=>{let e=wnt(t,qF);e.fastMode=!e.fastMode},setFromString:(t,e)=>{let n=tv(e,`providerOptions.${qF}.fastMode`);return typeof n=="string"?n:(wnt(t,qF).fastMode=n,null)}}}},modelLadders:{surface:"specialized",owner:"Models tab"},modelRoutes:{surface:"specialized",owner:"Models route declarations"},modelRouting:{surface:"specialized",owner:"Models route declarations"},kinds:{surface:"specialized",owner:"Models tab and kind registry"},page_components:{surface:"specialized",owner:"Page component catalog: product-registered page component kinds"},remoteCanvas:{surface:"specialized",owner:"canvas config commands"},api:{surface:"specialized",owner:"sys connect"},paths:{surface:"specialized",owner:"runtime layout"},store:{surface:"specialized",owner:"daemon conversation store"},runtime:{surface:"specialized",owner:"app-facing listener"},spawnEnv:{surface:"specialized",owner:"spawn environment allow-list"},bin:{surface:"specialized",owner:"bare-binary contributions on every node PATH"},humanActions:{surface:"specialized",owner:"scope-configured human completion actions"}},lBn=Object.keys(bnt);aCi=dBn()});function jF(t){return t.split("-").map(e=>e===""?"":`${e[0].toUpperCase()}${e.slice(1)}`).join("")}function hB(t){try{let e=JSON.stringify(t);return e===void 0?String(t):e}catch{return String(t)}}function pB(t,e,n,r){if(t!==void 0){if(typeof t!="string"||t.trim()==="")throw new Error(`${n}[${r}].${e} must be a non-empty string; received ${hB(t)}`);return t.trim()}}function gAe(t,e="page_components"){if(t===void 0)return[];if(!Array.isArray(t))throw new Error(`${e} must be an array; received ${hB(t)}`);let n=new Set,r=new Set;return t.map((i,o)=>{let s;if(typeof i=="string")s={kind:i.trim()};else if(i!==null&&typeof i=="object"&&!Array.isArray(i)){let u=i,l=Object.keys(u).filter(d=>!["kind","description","useWhen","doc","display"].includes(d));if(l.length>0)throw new Error(`${e}[${o}] has unknown field(s): ${l.join(", ")}`);if(typeof u.kind!="string")throw new Error(`${e}[${o}].kind must be a string; offending entry: ${hB(i)}`);if(u.display!==void 0&&typeof u.display!="boolean")throw new Error(`${e}[${o}].display must be a boolean; offending entry: ${hB(i)}`);s={kind:u.kind.trim(),...pB(u.description,"description",e,o)===void 0?{}:{description:pB(u.description,"description",e,o)},...pB(u.useWhen,"useWhen",e,o)===void 0?{}:{useWhen:pB(u.useWhen,"useWhen",e,o)},...pB(u.doc,"doc",e,o)===void 0?{}:{doc:pB(u.doc,"doc",e,o)},...u.display===!0?{display:!0}:{}}}else throw new Error(`${e}[${o}] must be a string or component object; offending entry: ${hB(i)}`);let a=s.kind;if(!hBn.test(a))throw new Error(`${e}[${o}] has invalid page kind ${hB(a)}; expected /^[a-z][a-z0-9-]{0,63}$/`);if(mBn.has(a)||pBn.includes(a))throw new Error(`${e}[${o}] collides with built-in page kind "${a}"`);if(n.has(a))throw new Error(`${e}[${o}] duplicates page kind "${a}"`);let c=jF(a);if(sV.has(c))throw new Error(`${e}[${o}] kind "${a}" derives JSX tag "${c}", which collides with a built-in page component`);if(r.has(c))throw new Error(`${e}[${o}] kind "${a}" derives JSX tag "${c}", which duplicates another product page component`);return n.add(a),r.add(c),s})}function Int(t){let e=new Map,n=new Map,r=[];for(let i of t)for(let o of i.components){let s=e.get(o.kind);if(s!==void 0)throw new Error(`page component kind "${o.kind}" is registered by both ${s} and ${i.origin}`);let a=jF(o.kind),c=n.get(a);if(c!==void 0)throw new Error(`page component kind "${o.kind}" (${i.origin}) derives JSX tag "${a}", which duplicates kind "${c.kind}" from ${c.origin}`);e.set(o.kind,i.origin),n.set(a,{kind:o.kind,origin:i.origin}),r.push(o)}return r}function vnt(t,e){return e.find(n=>n.kind===t)}var hAe,pBn,hBn,mBn,Cnt,mAe,sV,fAe,zF=y(()=>{"use strict";hAe=["options","text","table","cards","chart"],pBn=["page","step"],hBn=/^[a-z][a-z0-9-]{0,63}$/,mBn=new Set(hAe),Cnt=[{kind:"page",tag:"Page",description:"the page itself: title, subtitle, and every step it contains",useWhen:"use as the single root element every page returns",builtin:!0,structural:!0},{kind:"step",tag:"Step",description:"one step inside a Page",useWhen:"use for each step the user sees and completes in sequence",builtin:!0,structural:!0},{kind:"options",tag:"UserQuestion",description:"known alternatives with single or multiple selection",useWhen:"use when the user picks among known alternatives, optionally with freetext",builtin:!0,structural:!1},{kind:"text",tag:"UserText",description:"writing surface whose answer is the text the user hands back",useWhen:"use when you need prose from the user \u2014 a value they write, or a draft they revise; prose they only read is a plain element",builtin:!0,structural:!1},{kind:"table",tag:"UserTable",description:"rows and columns with optional selection",useWhen:"use when structured records are easiest to compare in rows and columns",builtin:!0,structural:!1},{kind:"cards",tag:"UserCards",description:"visual records with optional selection",useWhen:"use when the user compares or picks richer items than a compact option list can carry",builtin:!0,structural:!1},{kind:"chart",tag:"Chart",description:"line, bar, or area data visualization",useWhen:"use when shape, trend, or magnitude matters more than exact tabular values",builtin:!0,structural:!1}];mAe=Object.fromEntries(Cnt.filter(t=>!t.structural).map(t=>[t.tag,t.kind])),sV=new Set(Cnt.map(t=>t.tag)),fAe=new Set(["Card","CardHeader","CardTitle","CardDescription","CardContent","CardFooter","CardAction","Badge","Button","Separator","Progress","Alert","AlertTitle","AlertDescription","Table","TableHeader","TableBody","TableFooter","TableRow","TableHead","TableCell","TableCaption","Tabs","TabsList","TabsTrigger","TabsContent","Accordion","AccordionItem","AccordionTrigger","AccordionContent"])});import{basename as Rnt,join as Bnt}from"node:path";import{existsSync as gBn,mkdirSync as fCi,statSync as gCi}from"node:fs";function ABn(t){return Bnt(t,c6)}function yBn(t){return Bnt(t,AXe)}function Dnt(t){let e=dB(t),n=dB(Zd());if(e===n)return{key:"user",kind:"user",root:n};if(Rnt(e)===".crouter")return{key:"project",kind:"project",root:e};for(let r of X6()){let i=dB(J6(r.profileId));if(e===i)return{key:`profile:${r.profileId}`,kind:"profile",root:i,profileId:r.profileId}}throw new Error(`settings root is not a recognized owner: ${t}`)}function Mnt(t){if(Rnt(t)===".crouter"){let r;try{r=dB(t)}catch(i){if(i.code==="ENOENT")return null;throw i}if(r!==dB(Zd()))return UI(ABn(t))}let e=Dnt(t).key,n=HF(e).settings;return e==="user"&&pF()?tV(j0(),n):n}function lh(t){let e=EBn[wBn];if(e){if(t!=="user")throw new Error(`broker config snapshot has no ${t} scope`);return e.user}let n=z0(t);return n?xBn(n):l6()}function xBn(t){let e=Mnt(t);return e?VBn(e):l6()}function bBn(t){let e=UI(yBn(t));return{marketplaces:e?.marketplaces??{},plugins:e?.plugins??{},activeCanvas:e?.activeCanvas??null,...e?.last_self_check===void 0?{}:{last_self_check:e.last_self_check}}}function Pnt(t){let e=z0(t);return e?t==="project"?gBn(e)?bBn(e):Efe():Utt(Dnt(e).key):Efe()}function CBn(t){if(t===null||typeof t!="object"||Array.isArray(t))return{};let e={};for(let[n,r]of Object.entries(t))Array.isArray(r)&&r.every(i=>typeof i=="string")&&(e[n]=[...r]);return e}function mB(t){return t===void 0?[...vBn]:Array.isArray(t)?[...new Set(t.filter(e=>typeof e=="string"&&PI.has(e)&&IBn.has(e)))]:[]}function SBn(t,e=yfe()){let n=e;if(t===null||typeof t!="object")return n;let r=t,i={anthropic:{...n.anthropic},openai:{...n.openai},...n.defaultProvider!==void 0?{defaultProvider:n.defaultProvider}:{}};(r.defaultProvider==="anthropic"||r.defaultProvider==="openai")&&(i.defaultProvider=r.defaultProvider);for(let o of["anthropic","openai"]){let s=r[o];if(!(s===null||typeof s!="object"))for(let[a,c]of Object.entries(s))(a==="ultra"||a==="strong"||a==="medium"||a==="light")&&typeof c=="string"&&(i[o][a]=c)}return i}function Nnt(t){return t==="ultra"||t==="strong"||t==="medium"||t==="light"}function AAe(){return Object.create(null)}function aV(t,e,n){Object.defineProperty(t,e,{value:n,writable:!0,enumerable:!0,configurable:!0})}function kBn(t){let e=AAe();for(let[n,r]of Object.entries(t??{}))aV(e,n,r);return e}function VF(t,e){$l({level:"warn",event:"config.model_routes.invalid",fields:{route_id:t,rule:e}})}function TBn(t,e={}){let n=kBn(e);if(t===null||typeof t!="object"||Array.isArray(t))return n;for(let[r,i]of Object.entries(t)){if(r.trim()===""){VF(r,"route id must be a non-empty string");continue}if(i===null||typeof i!="object"||Array.isArray(i)){VF(r,"route must be an object");continue}let o=i,s=n[r],a={...s},c;for(let u of["family","credentialSource","providerId"]){let l=o[u];if(l!==void 0){if(typeof l!="string"||l.trim()===""){c=`${u} must be a non-empty string`;break}a[u]=l}}if(c===void 0&&o.models!==void 0)if(o.models===null||typeof o.models!="object"||Array.isArray(o.models))c="models must be an object";else{let u={...s?.models};for(let[l,d]of Object.entries(o.models)){if(!Nnt(l)){c=`models.${l} is not a model strength`;break}if(typeof d!="string"||d.trim()===""){c=`models.${l} must be a non-empty provider/id ref`;break}let p=d.indexOf("/");if(p<=0||p===d.length-1){c=`models.${l} must be provider/id`;break}u[l]=d}a.models=u}if(c===void 0&&a.models!==void 0&&a.providerId!==void 0){for(let[u,l]of Object.entries(a.models))if(l.slice(0,l.indexOf("/"))!==a.providerId){c=`models.${u} provider prefix must equal providerId`;break}}if(c!==void 0){VF(r,c);continue}aV(n,r,a)}return n}function RBn(t){let e=AAe(),n=AAe();for(let[r,i]of Object.entries(t)){if(i.family===void 0||i.credentialSource===void 0||i.providerId===void 0||i.models===void 0){VF(r,"route must include family, credentialSource, providerId, and models");continue}let o=_Bn.filter(s=>i.models[s]===void 0);if(o.length>0){VF(r,`incomplete route; missing strengths: ${o.join(", ")}`),aV(n,r,{family:i.family,credentialSource:i.credentialSource,providerId:i.providerId,models:i.models});continue}aV(e,r,{family:i.family,credentialSource:i.credentialSource,providerId:i.providerId,models:i.models})}return{complete:e,legacy:n}}function BBn(t,e){if(t===void 0||t===null||typeof t!="object"||Array.isArray(t))return e;let n=t,r=o=>Array.isArray(o)&&o.every(s=>typeof s=="string"&&s.trim()!=="")?[...o]:void 0,i=Array.isArray(n.strengthFallback)&&n.strengthFallback.every(o=>Nnt(o))?[...n.strengthFallback]:void 0;return{...r(n.credentialSourceOrder)!==void 0?{credentialSourceOrder:r(n.credentialSourceOrder)}:{},...r(n.familyOrder)!==void 0?{familyOrder:r(n.familyOrder)}:{},...i!==void 0?{strengthFallback:i}:{}}}function DBn(t){return t!==""&&t.replace(/\*/g,"")===""}function MBn(t,e=[]){let n=t,r=Array.isArray(n?.allow)?n.allow.filter(i=>typeof i=="string"):[];for(let i of r)if(DBn(i))throw new Error(`spawnEnv.allow: "${i}" matches every env var name (inherit-all) \u2014 this is exactly the leak the spawn-env boundary closes. Name the specific vars/prefixes you actually need instead (e.g. "AWS_*", "GIT_ASKPASS").`);return{allow:[...new Set([...e,...r])]}}function PBn(t,e={}){let n={};for(let[r,i]of Object.entries(e))n[r]={...i};if(t!==null&&typeof t=="object")for(let[r,i]of Object.entries(t)){if(i===null||typeof i!="object")continue;let o={...n[r]},s=i.fastMode;typeof s=="boolean"&&(o.fastMode=s),n[r]=o}return n}function LBn(t,e){if(e==="bin"&&NBn.has(t))return`${e}.${t} is reserved by crouter \u2014 pick another bare command name`;if(!Snt.test(t))return`${e}.${t} is not a safe bare command name (expected ${Snt.source})`}function QBn(t){if(t===null||typeof t!="object"||Array.isArray(t))return{};let e={};for(let[n,r]of Object.entries(t))LBn(n,"bin")===void 0&&(typeof r!="string"||r.trim()===""||(e[n]=r));return e}function OBn(t){if(t===null||typeof t!="object"||Array.isArray(t))return[{name:"humanActions",reason:"humanActions must be a JSON object mapping action names to {argv, cwd}",block:!0}];let e=[];for(let[n,r]of Object.entries(t)){let i=[];if(_nt.test(n)||i.push(`action name must match ${_nt.source}`),r===null||typeof r!="object"||Array.isArray(r))i.push("action must be an object with argv and cwd");else{let o=r,s=Object.keys(o).filter(a=>a!=="argv"&&a!=="cwd");s.length>0&&i.push(`action has unsupported field${s.length===1?"":"s"}: ${s.join(", ")}`),(!Array.isArray(o.argv)||o.argv.length===0||!o.argv.every(a=>typeof a=="string"&&a.length>0))&&i.push("argv must be a non-empty array of non-empty strings"),(typeof o.cwd!="string"||o.cwd.length===0)&&i.push("cwd is required and must be a non-empty string")}i.length>0&&e.push({name:n,reason:i.join("; ")})}return e}function FBn(t){if(t===null||typeof t!="object"||Array.isArray(t))return{};let e=new Set(OBn(t).map(r=>r.name)),n={};for(let[r,i]of Object.entries(t)){if(e.has(r))continue;let o=i;n[r]={argv:[...o.argv],cwd:o.cwd}}return n}function UBn(t){if(t===null||typeof t!="object")return null;let e=t,n={};typeof e.whenToUse=="string"&&e.whenToUse.trim()!==""&&(n.whenToUse=e.whenToUse),typeof e.model=="string"&&e.model.trim()!==""&&(n.model=e.model),typeof e.orchestratorModel=="string"&&e.orchestratorModel.trim()!==""&&(n.orchestratorModel=e.orchestratorModel);let r=i=>Array.isArray(i)&&i.every(o=>typeof o=="string");return r(e.tools)&&(n.tools=e.tools),r(e.extensions)&&(n.extensions=e.extensions),r(e.availableTo)&&(n.availableTo=e.availableTo),Object.keys(n).length>0?n:null}function $Bn(t,e=Afe()){let n={...e};if(t!==null&&typeof t=="object")for(let[r,i]of Object.entries(t)){let o=UBn(i);if(o===null)continue;let s=n[r];s!==void 0?n[r]={...s,...o}:o.whenToUse!==void 0&&(n[r]=o)}return n}function uV(){let t=[{origin:"config.json",components:lh("user").page_components}],e=z0("user");if(e!==null){let n=nV("user",e).filter(r=>r.enabled&&r.manifest.page_components!==void 0).sort((r,i)=>r.name.localeCompare(i.name));for(let r of n){let i=`plugin "${r.name}" page_components`;t.push({origin:`plugin "${r.name}"`,components:gAe(r.manifest.page_components,i)})}}return Int(t)}function WBn(t){if(t===null||typeof t!="object")return null;let e=t;if(typeof e.previewEndpoint!="string"||e.previewEndpoint.trim()===""||typeof e.relayTokenRef!="string"||e.relayTokenRef.trim()==="")return null;let n={previewEndpoint:e.previewEndpoint,relayTokenRef:e.relayTokenRef};return typeof e.cpOrigin=="string"&&e.cpOrigin.trim()!==""&&(n.cpOrigin=e.cpOrigin),n}function HBn(t,e=gfe()){let n={...e.targets};if(t!==null&&typeof t=="object"){let r=t;if(r.targets!==null&&typeof r.targets=="object")for(let[i,o]of Object.entries(r.targets)){let s=WBn(o);s!==null&&(n[i]=s)}}return{targets:n}}function knt(t,e){return t===!0?"notify":t===!1?!1:t==="notify"||t==="apply"?t:e}function cV(t,e){return typeof t=="number"&&Number.isSafeInteger(t)&&t>=1?t:e}function GBn(t,e){let n=t!==null&&typeof t=="object"?t:{},r=cV(n.warning,e.warning),i=cV(n.automaticReviveCap,e.automaticReviveCap);return r<=i?{warning:r,automaticReviveCap:i}:{...e}}function qBn(t,e){return{unattendedParkMs:cV((t!==null&&typeof t=="object"?t:{}).unattendedParkMs,e.unattendedParkMs)}}function jBn(t){if(!Array.isArray(t))return[...u6];let e=t.filter(n=>typeof n=="string"&&n.trim()!=="").map(n=>n.trim());return e.length>0?e:[...u6]}function zBn(t,e){if(t===null||typeof t!="object")return{...e};let n=t.tcp;return{tcp:typeof n=="string"?n:e.tcp}}function VBn(t){!Tnt&&t.ledger!==void 0&&(Tnt=!0,$l({level:"warn",event:"config.ledger.ignored",fields:{variables:Object.values(Btt)}}));let e=l6(),n=e.schema_version,r=t.marketplaces===void 0?{}:t.marketplaces,i=t.plugins===void 0?{}:t.plugins,o=t.auto_update,s=o&&typeof o.interval_hours=="number"?o.interval_hours:void 0,a=s!==void 0&&Number.isFinite(s)&&s>=0?s:e.auto_update.interval_hours,c={crtr:knt(o?.crtr,e.auto_update.crtr),content:knt(o?.content,e.auto_update.content),interval_hours:a},u=t.max_panes_per_window,l=cV(u,e.max_panes_per_window),d=typeof t.auto_open_child_viewers=="boolean"?t.auto_open_child_viewers:e.auto_open_child_viewers,p=GBn(t.brokerThresholds,e.brokerThresholds),h=qBn(t.lifecycle,e.lifecycle),m=typeof t.completion_bell=="boolean"?t.completion_bell:e.completion_bell,f=t.working_gerunds===void 0?[...e.working_gerunds]:hXe(t.working_gerunds),g=typeof t.whip_mode=="boolean"?t.whip_mode:e.whip_mode,A=gAe(t.page_components),x=typeof t.page_surface=="boolean"?t.page_surface:e.page_surface,b=jBn(t.whip_messages),v=LI.includes(t.whip_message_mode)?t.whip_message_mode:e.whip_message_mode,S=QI.includes(t.mouse_mode_default)?t.mouse_mode_default:e.mouse_mode_default,_=typeof t.bash_tool_purpose=="boolean"?t.bash_tool_purpose:e.bash_tool_purpose,T=zi.includes(t.verbosity)?t.verbosity:e.verbosity,B=typeof t.detailed_tool_recaps=="boolean"?t.detailed_tool_recaps:e.detailed_tool_recaps,R=Number.isInteger(t.document_port)&&t.document_port>=1&&t.document_port<=65535?t.document_port:e.document_port,P=CBn(t.keybindings),O=mB(t.tmux_passthrough),$=SBn(t.modelLadders),j=PBn(t.providerOptions,e.providerOptions),H=RBn(TBn(t.modelRoutes)),le=H.complete,ee=BBn(t.modelRouting,void 0),ge=$Bn(t.kinds),Ie=HBn(t.remoteCanvas),$e=zBn(t.api,e.api),wt=t.paths;if(wt?.user_files!==void 0&&(typeof wt.user_files!="string"||!wt.user_files.startsWith("/")))throw new Error("paths.user_files must be an absolute path");let Ze=t.store,xt=t.runtime;if(xt?.person_uids!==void 0&&(!Array.isArray(xt.person_uids)||!xt.person_uids.every(et=>Number.isSafeInteger(et)&&et>=0)))throw new Error("runtime.person_uids must be an array of nonnegative integer uids");let re=MBn(t.spawnEnv,e.spawnEnv?.allow),ot=QBn(t.bin),ke=FBn(t.humanActions);return{bin:ot,humanActions:ke,schema_version:n,marketplaces:r,plugins:i,auto_update:c,max_panes_per_window:l,auto_open_child_viewers:d,brokerThresholds:p,lifecycle:h,completion_bell:m,working_gerunds:f,whip_mode:g,page_components:A,page_surface:x,whip_messages:b,whip_message_mode:v,mouse_mode_default:S,bash_tool_purpose:_,verbosity:T,detailed_tool_recaps:B,document_port:R,keybindings:P,tmux_passthrough:O,modelLadders:$,providerOptions:j,...Object.keys(le).length>0?{modelRoutes:le}:{},...Object.keys(H.legacy).length>0?{legacyModelRoutes:H.legacy}:{},...ee!==void 0?{modelRouting:ee}:{},kinds:ge,remoteCanvas:Ie,api:$e,...wt?{paths:wt}:{},...Ze?{store:Ze}:{},...xt?{runtime:xt}:{},spawnEnv:re}}function KBn(t){return Mnt(t)}function Lnt(t){let e=z0(t);return e?KBn(e):null}var EBn,wBn,IBn,vBn,_Bn,Snt,NBn,_nt,Tnt,Vd=y(()=>{"use strict";Bc();ru();o6();qd();YI();Dtt();Ol();XI();rV();JI();Ant();lB();lAe();ev();pAe();a6();zF();EBn=globalThis,wBn=Symbol.for("crtr.broker.config-snapshot");IBn=new Set(Gd.filter(wF).map(t=>t.id)),vBn=Object.freeze(["crtr.attach.scroll.up","crtr.attach.scroll.down","crtr.attach.scroll.page-up","crtr.attach.scroll.page-down","crtr.attach.scroll.live"]);_Bn=["ultra","strong","medium","light"];Snt=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,NBn=new Set(["crtr","crtrd"]);_nt=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;Tnt=!1});var Y0=Q((MIi,nrt)=>{"use strict";var ert=["nodebuffer","arraybuffer","fragments"],trt=typeof Blob<"u";trt&&ert.push("blob");nrt.exports={BINARY_TYPES:ert,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:trt,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var tU=Q((PIi,hV)=>{"use strict";var{EMPTY_BUFFER:W1n}=Y0(),HAe=Buffer[Symbol.species];function H1n(t,e){if(t.length===0)return W1n;if(t.length===1)return t[0];let n=Buffer.allocUnsafe(e),r=0;for(let i=0;i<t.length;i++){let o=t[i];n.set(o,r),r+=o.length}return r<e?new HAe(n.buffer,n.byteOffset,r):n}function rrt(t,e,n,r,i){for(let o=0;o<i;o++)n[r+o]=t[o]^e[o&3]}function irt(t,e){for(let n=0;n<t.length;n++)t[n]^=e[n&3]}function G1n(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function GAe(t){if(GAe.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new HAe(t):ArrayBuffer.isView(t)?e=new HAe(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),GAe.readOnly=!1),e}hV.exports={concat:H1n,mask:rrt,toArrayBuffer:G1n,toBuffer:GAe,unmask:irt};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=K("bufferutil");hV.exports.mask=function(e,n,r,i,o){o<48?rrt(e,n,r,i,o):t.mask(e,n,r,i,o)},hV.exports.unmask=function(e,n){e.length<32?irt(e,n):t.unmask(e,n)}}catch{}});var art=Q((NIi,srt)=>{"use strict";var ort=Symbol("kDone"),qAe=Symbol("kRun"),jAe=class{constructor(e){this[ort]=()=>{this.pending--,this[qAe]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[qAe]()}[qAe](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[ort])}}};srt.exports=jAe});var bB=Q((LIi,drt)=>{"use strict";var nU=K("zlib"),crt=tU(),q1n=art(),{kStatusCode:urt}=Y0(),j1n=Buffer[Symbol.species],z1n=Buffer.from([0,0,255,255]),fV=Symbol("permessage-deflate"),J0=Symbol("total-length"),wB=Symbol("callback"),xw=Symbol("buffers"),xB=Symbol("error"),mV,zAe=class{constructor(e){if(this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!mV){let n=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;mV=new q1n(n)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[wB];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let n=this._options,r=e.find(i=>!(n.serverNoContextTakeover===!1&&i.server_no_context_takeover||i.server_max_window_bits&&(n.serverMaxWindowBits===!1||typeof n.serverMaxWindowBits=="number"&&n.serverMaxWindowBits>i.server_max_window_bits)||typeof n.clientMaxWindowBits=="number"&&!i.client_max_window_bits));if(!r)throw new Error("None of the extension offers can be accepted");return n.serverNoContextTakeover&&(r.server_no_context_takeover=!0),n.clientNoContextTakeover&&(r.client_no_context_takeover=!0),typeof n.serverMaxWindowBits=="number"&&(r.server_max_window_bits=n.serverMaxWindowBits),typeof n.clientMaxWindowBits=="number"?r.client_max_window_bits=n.clientMaxWindowBits:(r.client_max_window_bits===!0||n.clientMaxWindowBits===!1)&&delete r.client_max_window_bits,r}acceptAsClient(e){let n=e[0];if(this._options.clientNoContextTakeover===!1&&n.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!n.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(n.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&n.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return n}normalizeParams(e){return e.forEach(n=>{Object.keys(n).forEach(r=>{let i=n[r];if(i.length>1)throw new Error(`Parameter "${r}" must have only a single value`);if(i=i[0],r==="client_max_window_bits"){if(i!==!0){let o=+i;if(!Number.isInteger(o)||o<8||o>15)throw new TypeError(`Invalid value for parameter "${r}": ${i}`);i=o}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${r}": ${i}`)}else if(r==="server_max_window_bits"){let o=+i;if(!Number.isInteger(o)||o<8||o>15)throw new TypeError(`Invalid value for parameter "${r}": ${i}`);i=o}else if(r==="client_no_context_takeover"||r==="server_no_context_takeover"){if(i!==!0)throw new TypeError(`Invalid value for parameter "${r}": ${i}`)}else throw new Error(`Unknown parameter "${r}"`);n[r]=i})}),e}decompress(e,n,r){mV.add(i=>{this._decompress(e,n,(o,s)=>{i(),r(o,s)})})}compress(e,n,r){mV.add(i=>{this._compress(e,n,(o,s)=>{i(),r(o,s)})})}_decompress(e,n,r){let i=this._isServer?"client":"server";if(!this._inflate){let o=`${i}_max_window_bits`,s=typeof this.params[o]!="number"?nU.Z_DEFAULT_WINDOWBITS:this.params[o];this._inflate=nU.createInflateRaw({...this._options.zlibInflateOptions,windowBits:s}),this._inflate[fV]=this,this._inflate[J0]=0,this._inflate[xw]=[],this._inflate.on("error",K1n),this._inflate.on("data",lrt)}this._inflate[wB]=r,this._inflate.write(e),n&&this._inflate.write(z1n),this._inflate.flush(()=>{let o=this._inflate[xB];if(o){this._inflate.close(),this._inflate=null,r(o);return}let s=crt.concat(this._inflate[xw],this._inflate[J0]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[J0]=0,this._inflate[xw]=[],n&&this.params[`${i}_no_context_takeover`]&&this._inflate.reset()),r(null,s)})}_compress(e,n,r){let i=this._isServer?"server":"client";if(!this._deflate){let o=`${i}_max_window_bits`,s=typeof this.params[o]!="number"?nU.Z_DEFAULT_WINDOWBITS:this.params[o];this._deflate=nU.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:s}),this._deflate[J0]=0,this._deflate[xw]=[],this._deflate.on("data",V1n)}this._deflate[wB]=r,this._deflate.write(e),this._deflate.flush(nU.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let o=crt.concat(this._deflate[xw],this._deflate[J0]);n&&(o=new j1n(o.buffer,o.byteOffset,o.length-4)),this._deflate[wB]=null,this._deflate[J0]=0,this._deflate[xw]=[],n&&this.params[`${i}_no_context_takeover`]&&this._deflate.reset(),r(null,o)})}};drt.exports=zAe;function V1n(t){this[xw].push(t),this[J0]+=t.length}function lrt(t){if(this[J0]+=t.length,this[fV]._maxPayload<1||this[J0]<=this[fV]._maxPayload){this[xw].push(t);return}this[xB]=new RangeError("Max payload size exceeded"),this[xB].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[xB][urt]=1009,this.removeListener("data",lrt),this.reset()}function K1n(t){if(this[fV]._inflate=null,this[xB]){this[wB](this[xB]);return}t[urt]=1007,this[wB](t)}});var CB=Q((QIi,gV)=>{"use strict";var{isUtf8:prt}=K("buffer"),{hasBlob:Y1n}=Y0(),J1n=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function X1n(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function VAe(t){let e=t.length,n=0;for(;n<e;)if((t[n]&128)===0)n++;else if((t[n]&224)===192){if(n+1===e||(t[n+1]&192)!==128||(t[n]&254)===192)return!1;n+=2}else if((t[n]&240)===224){if(n+2>=e||(t[n+1]&192)!==128||(t[n+2]&192)!==128||t[n]===224&&(t[n+1]&224)===128||t[n]===237&&(t[n+1]&224)===160)return!1;n+=3}else if((t[n]&248)===240){if(n+3>=e||(t[n+1]&192)!==128||(t[n+2]&192)!==128||(t[n+3]&192)!==128||t[n]===240&&(t[n+1]&240)===128||t[n]===244&&t[n+1]>143||t[n]>244)return!1;n+=4}else return!1;return!0}function Z1n(t){return Y1n&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}gV.exports={isBlob:Z1n,isValidStatusCode:X1n,isValidUTF8:VAe,tokenChars:J1n};if(prt)gV.exports.isValidUTF8=function(t){return t.length<24?VAe(t):prt(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=K("utf-8-validate");gV.exports.isValidUTF8=function(e){return e.length<32?VAe(e):t(e)}}catch{}});var ZAe=Q((OIi,Ert)=>{"use strict";var{Writable:eDn}=K("stream"),hrt=bB(),{BINARY_TYPES:tDn,EMPTY_BUFFER:mrt,kStatusCode:nDn,kWebSocket:rDn}=Y0(),{concat:KAe,toArrayBuffer:iDn,unmask:oDn}=tU(),{isValidStatusCode:sDn,isValidUTF8:frt}=CB(),AV=Buffer[Symbol.species],ph=0,grt=1,Art=2,yrt=3,YAe=4,JAe=5,yV=6,XAe=class extends eDn{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||tDn[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxBufferedChunks=e.maxBufferedChunks|0,this._maxFragments=e.maxFragments|0,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[rDn]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=ph}_write(e,n,r){if(this._opcode===8&&this._state==ph)return r();if(this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks){r(this.createError(RangeError,"Too many buffered chunks",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS"));return}this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(r)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let r=this._buffers[0];return this._buffers[0]=new AV(r.buffer,r.byteOffset+e,r.length-e),new AV(r.buffer,r.byteOffset,e)}let n=Buffer.allocUnsafe(e);do{let r=this._buffers[0],i=n.length-e;e>=r.length?n.set(this._buffers.shift(),i):(n.set(new Uint8Array(r.buffer,r.byteOffset,e),i),this._buffers[0]=new AV(r.buffer,r.byteOffset+e,r.length-e)),e-=r.length}while(e>0);return n}startLoop(e){this._loop=!0;do switch(this._state){case ph:this.getInfo(e);break;case grt:this.getPayloadLength16(e);break;case Art:this.getPayloadLength64(e);break;case yrt:this.getMask();break;case YAe:this.getData(e);break;case JAe:case yV:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let n=this.consume(2);if((n[0]&48)!==0){let i=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(i);return}let r=(n[0]&64)===64;if(r&&!this._extensions[hrt.extensionName]){let i=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(i);return}if(this._fin=(n[0]&128)===128,this._opcode=n[0]&15,this._payloadLength=n[1]&127,this._opcode===0){if(r){let i=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(i);return}if(!this._fragmented){let i=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(i);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let i=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(i);return}this._compressed=r}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let i=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(i);return}if(r){let i=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(i);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let i=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(i);return}}else{let i=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(i);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(n[1]&128)===128,this._isServer){if(!this._masked){let i=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(i);return}}else if(this._masked){let i=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(i);return}this._payloadLength===126?this._state=grt:this._payloadLength===127?this._state=Art:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let n=this.consume(8),r=n.readUInt32BE(0);if(r>Math.pow(2,21)-1){let i=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(i);return}this._payloadLength=r*Math.pow(2,32)+n.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let n=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(n);return}this._masked?this._state=yrt:this._state=YAe}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=YAe}getData(e){let n=mrt;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}n=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&oDn(n,this._mask)}if(this._opcode>7){this.controlMessage(n,e);return}if(this._compressed){this._state=JAe,this.decompress(n,e);return}if(n.length){if(this._maxFragments>0&&this._fragments.length>=this._maxFragments){let r=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");e(r);return}this._messageLength=this._totalPayloadLength,this._fragments.push(n)}this.dataMessage(e)}decompress(e,n){this._extensions[hrt.extensionName].decompress(e,this._fin,(i,o)=>{if(i)return n(i);if(o.length){if(this._messageLength+=o.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let s=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");n(s);return}if(this._maxFragments>0&&this._fragments.length>=this._maxFragments){let s=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");n(s);return}this._fragments.push(o)}this.dataMessage(n),this._state===ph&&this.startLoop(n)})}dataMessage(e){if(!this._fin){this._state=ph;return}let n=this._messageLength,r=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let i;this._binaryType==="nodebuffer"?i=KAe(r,n):this._binaryType==="arraybuffer"?i=iDn(KAe(r,n)):this._binaryType==="blob"?i=new Blob(r):i=r,this._allowSynchronousEvents?(this.emit("message",i,!0),this._state=ph):(this._state=yV,setImmediate(()=>{this.emit("message",i,!0),this._state=ph,this.startLoop(e)}))}else{let i=KAe(r,n);if(!this._skipUTF8Validation&&!frt(i)){let o=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(o);return}this._state===JAe||this._allowSynchronousEvents?(this.emit("message",i,!1),this._state=ph):(this._state=yV,setImmediate(()=>{this.emit("message",i,!1),this._state=ph,this.startLoop(e)}))}}controlMessage(e,n){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,mrt),this.end();else{let r=e.readUInt16BE(0);if(!sDn(r)){let o=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");n(o);return}let i=new AV(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!frt(i)){let o=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");n(o);return}this._loop=!1,this.emit("conclude",r,i),this.end()}this._state=ph;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=ph):(this._state=yV,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=ph,this.startLoop(n)}))}createError(e,n,r,i,o){this._loop=!1,this._errored=!0;let s=new e(r?`Invalid WebSocket frame: ${n}`:n);return Error.captureStackTrace(s,this.createError),s.code=o,s[nDn]=i,s}};Ert.exports=XAe});var n0e=Q((UIi,brt)=>{"use strict";var{Duplex:FIi}=K("stream"),{randomFillSync:aDn}=K("crypto"),{types:{isUint8Array:cDn}}=K("util"),wrt=bB(),{EMPTY_BUFFER:uDn,kWebSocket:lDn,NOOP:dDn}=Y0(),{isBlob:IB,isValidStatusCode:pDn}=CB(),{mask:xrt,toBuffer:ov}=tU(),hh=Symbol("kByteLength"),hDn=Buffer.alloc(4),EV=8*1024,sv,vB=EV,Xm=0,mDn=1,fDn=2,e0e=class t{constructor(e,n,r){this._extensions=n||{},r&&(this._generateMask=r,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=Xm,this.onerror=dDn,this[lDn]=void 0}static frame(e,n){let r,i=!1,o=2,s=!1;n.mask&&(r=n.maskBuffer||hDn,n.generateMask?n.generateMask(r):(vB===EV&&(sv===void 0&&(sv=Buffer.alloc(EV)),aDn(sv,0,EV),vB=0),r[0]=sv[vB++],r[1]=sv[vB++],r[2]=sv[vB++],r[3]=sv[vB++]),s=(r[0]|r[1]|r[2]|r[3])===0,o=6);let a;typeof e=="string"?(!n.mask||s)&&n[hh]!==void 0?a=n[hh]:(e=Buffer.from(e),a=e.length):(a=e.length,i=n.mask&&n.readOnly&&!s);let c=a;a>=65536?(o+=8,c=127):a>125&&(o+=2,c=126);let u=Buffer.allocUnsafe(i?a+o:o);return u[0]=n.fin?n.opcode|128:n.opcode,n.rsv1&&(u[0]|=64),u[1]=c,c===126?u.writeUInt16BE(a,2):c===127&&(u[2]=u[3]=0,u.writeUIntBE(a,4,6)),n.mask?(u[1]|=128,u[o-4]=r[0],u[o-3]=r[1],u[o-2]=r[2],u[o-1]=r[3],s?[u,e]:i?(xrt(e,r,u,o,a),[u]):(xrt(e,r,e,0,a),[u,e])):[u,e]}close(e,n,r,i){let o;if(e===void 0)o=uDn;else{if(typeof e!="number"||!pDn(e))throw new TypeError("First argument must be a valid error code number");if(n===void 0||!n.length)o=Buffer.allocUnsafe(2),o.writeUInt16BE(e,0);else{let a=Buffer.byteLength(n);if(a>123)throw new RangeError("The message must not be greater than 123 bytes");if(o=Buffer.allocUnsafe(2+a),o.writeUInt16BE(e,0),typeof n=="string")o.write(n,2);else if(cDn(n))o.set(n,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let s={[hh]:o.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==Xm?this.enqueue([this.dispatch,o,!1,s,i]):this.sendFrame(t.frame(o,s),i)}ping(e,n,r){let i,o;if(typeof e=="string"?(i=Buffer.byteLength(e),o=!1):IB(e)?(i=e.size,o=!1):(e=ov(e),i=e.length,o=ov.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");let s={[hh]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:o,rsv1:!1};IB(e)?this._state!==Xm?this.enqueue([this.getBlobData,e,!1,s,r]):this.getBlobData(e,!1,s,r):this._state!==Xm?this.enqueue([this.dispatch,e,!1,s,r]):this.sendFrame(t.frame(e,s),r)}pong(e,n,r){let i,o;if(typeof e=="string"?(i=Buffer.byteLength(e),o=!1):IB(e)?(i=e.size,o=!1):(e=ov(e),i=e.length,o=ov.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");let s={[hh]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:o,rsv1:!1};IB(e)?this._state!==Xm?this.enqueue([this.getBlobData,e,!1,s,r]):this.getBlobData(e,!1,s,r):this._state!==Xm?this.enqueue([this.dispatch,e,!1,s,r]):this.sendFrame(t.frame(e,s),r)}send(e,n,r){let i=this._extensions[wrt.extensionName],o=n.binary?2:1,s=n.compress,a,c;typeof e=="string"?(a=Buffer.byteLength(e),c=!1):IB(e)?(a=e.size,c=!1):(e=ov(e),a=e.length,c=ov.readOnly),this._firstFragment?(this._firstFragment=!1,s&&i&&i.params[i._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(s=a>=i._threshold),this._compress=s):(s=!1,o=0),n.fin&&(this._firstFragment=!0);let u={[hh]:a,fin:n.fin,generateMask:this._generateMask,mask:n.mask,maskBuffer:this._maskBuffer,opcode:o,readOnly:c,rsv1:s};IB(e)?this._state!==Xm?this.enqueue([this.getBlobData,e,this._compress,u,r]):this.getBlobData(e,this._compress,u,r):this._state!==Xm?this.enqueue([this.dispatch,e,this._compress,u,r]):this.dispatch(e,this._compress,u,r)}getBlobData(e,n,r,i){this._bufferedBytes+=r[hh],this._state=fDn,e.arrayBuffer().then(o=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(t0e,this,a,i);return}this._bufferedBytes-=r[hh];let s=ov(o);n?this.dispatch(s,n,r,i):(this._state=Xm,this.sendFrame(t.frame(s,r),i),this.dequeue())}).catch(o=>{process.nextTick(gDn,this,o,i)})}dispatch(e,n,r,i){if(!n){this.sendFrame(t.frame(e,r),i);return}let o=this._extensions[wrt.extensionName];this._bufferedBytes+=r[hh],this._state=mDn,o.compress(e,r.fin,(s,a)=>{if(this._socket.destroyed){let c=new Error("The socket was closed while data was being compressed");t0e(this,c,i);return}this._bufferedBytes-=r[hh],this._state=Xm,r.readOnly=!1,this.sendFrame(t.frame(a,r),i),this.dequeue()})}dequeue(){for(;this._state===Xm&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][hh],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][hh],this._queue.push(e)}sendFrame(e,n){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],n),this._socket.uncork()):this._socket.write(e[0],n)}};brt.exports=e0e;function t0e(t,e,n){typeof n=="function"&&n(e);for(let r=0;r<t._queue.length;r++){let i=t._queue[r],o=i[i.length-1];typeof o=="function"&&o(e)}}function gDn(t,e,n){t0e(t,e,n),t.onerror(e)}});var Brt=Q(($Ii,Rrt)=>{"use strict";var{kForOnEventAttribute:rU,kListener:r0e}=Y0(),Crt=Symbol("kCode"),Irt=Symbol("kData"),vrt=Symbol("kError"),Srt=Symbol("kMessage"),_rt=Symbol("kReason"),SB=Symbol("kTarget"),krt=Symbol("kType"),Trt=Symbol("kWasClean"),X0=class{constructor(e){this[SB]=null,this[krt]=e}get target(){return this[SB]}get type(){return this[krt]}};Object.defineProperty(X0.prototype,"target",{enumerable:!0});Object.defineProperty(X0.prototype,"type",{enumerable:!0});var av=class extends X0{constructor(e,n={}){super(e),this[Crt]=n.code===void 0?0:n.code,this[_rt]=n.reason===void 0?"":n.reason,this[Trt]=n.wasClean===void 0?!1:n.wasClean}get code(){return this[Crt]}get reason(){return this[_rt]}get wasClean(){return this[Trt]}};Object.defineProperty(av.prototype,"code",{enumerable:!0});Object.defineProperty(av.prototype,"reason",{enumerable:!0});Object.defineProperty(av.prototype,"wasClean",{enumerable:!0});var _B=class extends X0{constructor(e,n={}){super(e),this[vrt]=n.error===void 0?null:n.error,this[Srt]=n.message===void 0?"":n.message}get error(){return this[vrt]}get message(){return this[Srt]}};Object.defineProperty(_B.prototype,"error",{enumerable:!0});Object.defineProperty(_B.prototype,"message",{enumerable:!0});var iU=class extends X0{constructor(e,n={}){super(e),this[Irt]=n.data===void 0?null:n.data}get data(){return this[Irt]}};Object.defineProperty(iU.prototype,"data",{enumerable:!0});var ADn={addEventListener(t,e,n={}){for(let i of this.listeners(t))if(!n[rU]&&i[r0e]===e&&!i[rU])return;let r;if(t==="message")r=function(o,s){let a=new iU("message",{data:s?o:o.toString()});a[SB]=this,wV(e,this,a)};else if(t==="close")r=function(o,s){let a=new av("close",{code:o,reason:s.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[SB]=this,wV(e,this,a)};else if(t==="error")r=function(o){let s=new _B("error",{error:o,message:o.message});s[SB]=this,wV(e,this,s)};else if(t==="open")r=function(){let o=new X0("open");o[SB]=this,wV(e,this,o)};else return;r[rU]=!!n[rU],r[r0e]=e,n.once?this.once(t,r):this.on(t,r)},removeEventListener(t,e){for(let n of this.listeners(t))if(n[r0e]===e&&!n[rU]){this.removeListener(t,n);break}}};Rrt.exports={CloseEvent:av,ErrorEvent:_B,Event:X0,EventTarget:ADn,MessageEvent:iU};function wV(t,e,n){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,n):t.call(e,n)}});var xV=Q((WIi,Drt)=>{"use strict";var{tokenChars:oU}=CB();function Dg(t,e,n){t[e]===void 0?t[e]=[n]:t[e].push(n)}function yDn(t){let e=Object.create(null),n=Object.create(null),r=!1,i=!1,o=!1,s,a,c=-1,u=-1,l=-1,d=0;for(;d<t.length;d++)if(u=t.charCodeAt(d),s===void 0)if(l===-1&&oU[u]===1)c===-1&&(c=d);else if(d!==0&&(u===32||u===9))l===-1&&c!==-1&&(l=d);else if(u===59||u===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${d}`);l===-1&&(l=d);let h=t.slice(c,l);u===44?(Dg(e,h,n),n=Object.create(null)):s=h,c=l=-1}else throw new SyntaxError(`Unexpected character at index ${d}`);else if(a===void 0)if(l===-1&&oU[u]===1)c===-1&&(c=d);else if(u===32||u===9)l===-1&&c!==-1&&(l=d);else if(u===59||u===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${d}`);l===-1&&(l=d),Dg(n,t.slice(c,l),!0),u===44&&(Dg(e,s,n),n=Object.create(null),s=void 0),c=l=-1}else if(u===61&&c!==-1&&l===-1)a=t.slice(c,d),c=l=-1;else throw new SyntaxError(`Unexpected character at index ${d}`);else if(i){if(oU[u]!==1)throw new SyntaxError(`Unexpected character at index ${d}`);c===-1?c=d:r||(r=!0),i=!1}else if(o)if(oU[u]===1)c===-1&&(c=d);else if(u===34&&c!==-1)o=!1,l=d;else if(u===92)i=!0;else throw new SyntaxError(`Unexpected character at index ${d}`);else if(u===34&&t.charCodeAt(d-1)===61)o=!0;else if(l===-1&&oU[u]===1)c===-1&&(c=d);else if(c!==-1&&(u===32||u===9))l===-1&&(l=d);else if(u===59||u===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${d}`);l===-1&&(l=d);let h=t.slice(c,l);r&&(h=h.replace(/\\/g,""),r=!1),Dg(n,a,h),u===44&&(Dg(e,s,n),n=Object.create(null),s=void 0),a=void 0,c=l=-1}else throw new SyntaxError(`Unexpected character at index ${d}`);if(c===-1||o||u===32||u===9)throw new SyntaxError("Unexpected end of input");l===-1&&(l=d);let p=t.slice(c,l);return s===void 0?Dg(e,p,n):(a===void 0?Dg(n,p,!0):r?Dg(n,a,p.replace(/\\/g,"")):Dg(n,a,p),Dg(e,s,n)),e}function EDn(t){return Object.keys(t).map(e=>{let n=t[e];return Array.isArray(n)||(n=[n]),n.map(r=>[e].concat(Object.keys(r).map(i=>{let o=r[i];return Array.isArray(o)||(o=[o]),o.map(s=>s===!0?i:`${i}=${s}`).join("; ")})).join("; ")).join(", ")}).join(", ")}Drt.exports={format:EDn,parse:yDn}});var vV=Q((qIi,Grt)=>{"use strict";var wDn=K("events"),xDn=K("https"),bDn=K("http"),Nrt=K("net"),CDn=K("tls"),{randomBytes:IDn,createHash:vDn}=K("crypto"),{Duplex:HIi,Readable:GIi}=K("stream"),{URL:i0e}=K("url"),bw=bB(),SDn=ZAe(),_Dn=n0e(),{isBlob:kDn}=CB(),{BINARY_TYPES:Mrt,CLOSE_TIMEOUT:TDn,EMPTY_BUFFER:bV,GUID:RDn,kForOnEventAttribute:o0e,kListener:BDn,kStatusCode:DDn,kWebSocket:Za,NOOP:Lrt}=Y0(),{EventTarget:{addEventListener:MDn,removeEventListener:PDn}}=Brt(),{format:NDn,parse:LDn}=xV(),{toBuffer:QDn}=tU(),Qrt=Symbol("kAborted"),s0e=[8,13],Z0=["CONNECTING","OPEN","CLOSING","CLOSED"],ODn=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,Go=class t extends wDn{constructor(e,n,r){super(),this._binaryType=Mrt[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=bV,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=t.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,n===void 0?n=[]:Array.isArray(n)||(typeof n=="object"&&n!==null?(r=n,n=[]):n=[n]),Ort(this,e,n,r)):(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Mrt.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,n,r){let i=new SDn({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:r.maxBufferedChunks,maxFragments:r.maxFragments,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),o=new _Dn(e,this._extensions,r.generateMask);this._receiver=i,this._sender=o,this._socket=e,i[Za]=this,o[Za]=this,e[Za]=this,i.on("conclude",$Dn),i.on("drain",WDn),i.on("error",HDn),i.on("message",GDn),i.on("ping",qDn),i.on("pong",jDn),o.onerror=zDn,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),n.length>0&&e.unshift(n),e.on("close",$rt),e.on("data",IV),e.on("end",Wrt),e.on("error",Hrt),this._readyState=t.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[bw.extensionName]&&this._extensions[bw.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,n){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){ep(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===t.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=t.CLOSING,this._sender.close(e,n,!this._isServer,r=>{r||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),Urt(this)}}pause(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,n,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(r=e,e=n=void 0):typeof n=="function"&&(r=n,n=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){a0e(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(e||bV,n,r)}pong(e,n,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(r=e,e=n=void 0):typeof n=="function"&&(r=n,n=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){a0e(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(e||bV,n,r)}resume(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,n,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof n=="function"&&(r=n,n={}),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){a0e(this,e,r);return}let i={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[bw.extensionName]||(i.compress=!1),this._sender.send(e||bV,i,r)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){ep(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(Go,"CONNECTING",{enumerable:!0,value:Z0.indexOf("CONNECTING")});Object.defineProperty(Go.prototype,"CONNECTING",{enumerable:!0,value:Z0.indexOf("CONNECTING")});Object.defineProperty(Go,"OPEN",{enumerable:!0,value:Z0.indexOf("OPEN")});Object.defineProperty(Go.prototype,"OPEN",{enumerable:!0,value:Z0.indexOf("OPEN")});Object.defineProperty(Go,"CLOSING",{enumerable:!0,value:Z0.indexOf("CLOSING")});Object.defineProperty(Go.prototype,"CLOSING",{enumerable:!0,value:Z0.indexOf("CLOSING")});Object.defineProperty(Go,"CLOSED",{enumerable:!0,value:Z0.indexOf("CLOSED")});Object.defineProperty(Go.prototype,"CLOSED",{enumerable:!0,value:Z0.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(Go.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(Go.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[o0e])return e[BDn];return null},set(e){for(let n of this.listeners(t))if(n[o0e]){this.removeListener(t,n);break}typeof e=="function"&&this.addEventListener(t,e,{[o0e]:!0})}})});Go.prototype.addEventListener=MDn;Go.prototype.removeEventListener=PDn;Grt.exports=Go;function Ort(t,e,n,r){let i={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:TDn,protocolVersion:s0e[1],maxBufferedChunks:1048576,maxFragments:131072,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...r,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(t._autoPong=i.autoPong,t._closeTimeout=i.closeTimeout,!s0e.includes(i.protocolVersion))throw new RangeError(`Unsupported protocol version: ${i.protocolVersion} (supported versions: ${s0e.join(", ")})`);let o;if(e instanceof i0e)o=e;else try{o=new i0e(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}o.protocol==="http:"?o.protocol="ws:":o.protocol==="https:"&&(o.protocol="wss:"),t._url=o.href;let s=o.protocol==="wss:",a=o.protocol==="ws+unix:",c;if(o.protocol!=="ws:"&&!s&&!a?c=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:a&&!o.pathname?c="The URL's pathname is empty":o.hash&&(c="The URL contains a fragment identifier"),c){let f=new SyntaxError(c);if(t._redirects===0)throw f;CV(t,f);return}let u=s?443:80,l=IDn(16).toString("base64"),d=s?xDn.request:bDn.request,p=new Set,h;if(i.createConnection=i.createConnection||(s?UDn:FDn),i.defaultPort=i.defaultPort||u,i.port=o.port||u,i.host=o.hostname.startsWith("[")?o.hostname.slice(1,-1):o.hostname,i.headers={...i.headers,"Sec-WebSocket-Version":i.protocolVersion,"Sec-WebSocket-Key":l,Connection:"Upgrade",Upgrade:"websocket"},i.path=o.pathname+o.search,i.timeout=i.handshakeTimeout,i.perMessageDeflate&&(h=new bw({...i.perMessageDeflate,isServer:!1,maxPayload:i.maxPayload}),i.headers["Sec-WebSocket-Extensions"]=NDn({[bw.extensionName]:h.offer()})),n.length){for(let f of n){if(typeof f!="string"||!ODn.test(f)||p.has(f))throw new SyntaxError("An invalid or duplicated subprotocol was specified");p.add(f)}i.headers["Sec-WebSocket-Protocol"]=n.join(",")}if(i.origin&&(i.protocolVersion<13?i.headers["Sec-WebSocket-Origin"]=i.origin:i.headers.Origin=i.origin),(o.username||o.password)&&(i.auth=`${o.username}:${o.password}`),a){let f=i.path.split(":");i.socketPath=f[0],i.path=f[1]}let m;if(i.followRedirects){if(t._redirects===0){t._originalIpc=a,t._originalSecure=s,t._originalHostOrSocketPath=a?i.socketPath:o.host;let f=r&&r.headers;if(r={...r,headers:{}},f)for(let[g,A]of Object.entries(f))r.headers[g.toLowerCase()]=A}else if(t.listenerCount("redirect")===0){let f=a?t._originalIpc?i.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:o.host===t._originalHostOrSocketPath;(!f||t._originalSecure&&!s)&&(delete i.headers.authorization,delete i.headers.cookie,f||delete i.headers.host,i.auth=void 0)}i.auth&&!r.headers.authorization&&(r.headers.authorization="Basic "+Buffer.from(i.auth).toString("base64")),m=t._req=d(i),t._redirects&&t.emit("redirect",t.url,m)}else m=t._req=d(i);i.timeout&&m.on("timeout",()=>{ep(t,m,"Opening handshake has timed out")}),m.on("error",f=>{m===null||m[Qrt]||(m=t._req=null,CV(t,f))}),m.on("response",f=>{let g=f.headers.location,A=f.statusCode;if(g&&i.followRedirects&&A>=300&&A<400){if(++t._redirects>i.maxRedirects){ep(t,m,"Maximum redirects exceeded");return}m.abort();let x;try{x=new i0e(g,e)}catch{let v=new SyntaxError(`Invalid URL: ${g}`);CV(t,v);return}Ort(t,x,n,r)}else t.emit("unexpected-response",m,f)||ep(t,m,`Unexpected server response: ${f.statusCode}`)}),m.on("upgrade",(f,g,A)=>{if(t.emit("upgrade",f),t.readyState!==Go.CONNECTING)return;m=t._req=null;let x=f.headers.upgrade;if(x===void 0||x.toLowerCase()!=="websocket"){ep(t,g,"Invalid Upgrade header");return}let b=vDn("sha1").update(l+RDn).digest("base64");if(f.headers["sec-websocket-accept"]!==b){ep(t,g,"Invalid Sec-WebSocket-Accept header");return}let v=f.headers["sec-websocket-protocol"],S;if(v!==void 0?p.size?p.has(v)||(S="Server sent an invalid subprotocol"):S="Server sent a subprotocol but none was requested":p.size&&(S="Server sent no subprotocol"),S){ep(t,g,S);return}v&&(t._protocol=v);let _=f.headers["sec-websocket-extensions"];if(_!==void 0){if(!h){ep(t,g,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let T;try{T=LDn(_)}catch{ep(t,g,"Invalid Sec-WebSocket-Extensions header");return}let B=Object.keys(T);if(B.length!==1||B[0]!==bw.extensionName){ep(t,g,"Server indicated an extension that was not requested");return}try{h.accept(T[bw.extensionName])}catch{ep(t,g,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[bw.extensionName]=h}t.setSocket(g,A,{allowSynchronousEvents:i.allowSynchronousEvents,generateMask:i.generateMask,maxBufferedChunks:i.maxBufferedChunks,maxFragments:i.maxFragments,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation})}),i.finishRequest?i.finishRequest(m,t):m.end()}function CV(t,e){t._readyState=Go.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function FDn(t){return t.path=t.socketPath,Nrt.connect(t)}function UDn(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=Nrt.isIP(t.host)?"":t.host),CDn.connect(t)}function ep(t,e,n){t._readyState=Go.CLOSING;let r=new Error(n);Error.captureStackTrace(r,ep),e.setHeader?(e[Qrt]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(CV,t,r)):(e.destroy(r),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function a0e(t,e,n){if(e){let r=kDn(e)?e.size:QDn(e).length;t._socket?t._sender._bufferedBytes+=r:t._bufferedAmount+=r}if(n){let r=new Error(`WebSocket is not open: readyState ${t.readyState} (${Z0[t.readyState]})`);process.nextTick(n,r)}}function $Dn(t,e){let n=this[Za];n._closeFrameReceived=!0,n._closeMessage=e,n._closeCode=t,n._socket[Za]!==void 0&&(n._socket.removeListener("data",IV),process.nextTick(Frt,n._socket),t===1005?n.close():n.close(t,e))}function WDn(){let t=this[Za];t.isPaused||t._socket.resume()}function HDn(t){let e=this[Za];e._socket[Za]!==void 0&&(e._socket.removeListener("data",IV),process.nextTick(Frt,e._socket),e.close(t[DDn])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function Prt(){this[Za].emitClose()}function GDn(t,e){this[Za].emit("message",t,e)}function qDn(t){let e=this[Za];e._autoPong&&e.pong(t,!this._isServer,Lrt),e.emit("ping",t)}function jDn(t){this[Za].emit("pong",t)}function Frt(t){t.resume()}function zDn(t){let e=this[Za];e.readyState!==Go.CLOSED&&(e.readyState===Go.OPEN&&(e._readyState=Go.CLOSING,Urt(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function Urt(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function $rt(){let t=this[Za];if(this.removeListener("close",$rt),this.removeListener("data",IV),this.removeListener("end",Wrt),t._readyState=Go.CLOSING,!this._readableState.endEmitted&&!t._closeFrameReceived&&!t._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);t._receiver.write(e)}t._receiver.end(),this[Za]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",Prt),t._receiver.on("finish",Prt))}function IV(t){this[Za]._receiver.write(t)||this.pause()}function Wrt(){let t=this[Za];t._readyState=Go.CLOSING,t._receiver.end(),this.end()}function Hrt(){let t=this[Za];this.removeListener("error",Hrt),this.on("error",Lrt),t&&(t._readyState=Go.CLOSING,this.destroy())}});var Vrt=Q((zIi,zrt)=>{"use strict";var jIi=vV(),{Duplex:VDn}=K("stream");function qrt(t){t.emit("close")}function KDn(){!this.destroyed&&this._writableState.finished&&this.destroy()}function jrt(t){this.removeListener("error",jrt),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function YDn(t,e){let n=!0,r=new VDn({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return t.on("message",function(o,s){let a=!s&&r._readableState.objectMode?o.toString():o;r.push(a)||t.pause()}),t.once("error",function(o){r.destroyed||(n=!1,r.destroy(o))}),t.once("close",function(){r.destroyed||r.push(null)}),r._destroy=function(i,o){if(t.readyState===t.CLOSED){o(i),process.nextTick(qrt,r);return}let s=!1;t.once("error",function(c){s=!0,o(c)}),t.once("close",function(){s||o(i),process.nextTick(qrt,r)}),n&&t.terminate()},r._final=function(i){if(t.readyState===t.CONNECTING){t.once("open",function(){r._final(i)});return}t._socket!==null&&(t._socket._writableState.finished?(i(),r._readableState.endEmitted&&r.destroy()):(t._socket.once("finish",function(){i()}),t.close()))},r._read=function(){t.isPaused&&t.resume()},r._write=function(i,o,s){if(t.readyState===t.CONNECTING){t.once("open",function(){r._write(i,o,s)});return}t.send(i,s)},r.on("end",KDn),r.on("error",jrt),r}zrt.exports=YDn});var c0e=Q((VIi,Krt)=>{"use strict";var{tokenChars:JDn}=CB();function XDn(t){let e=new Set,n=-1,r=-1,i=0;for(i;i<t.length;i++){let s=t.charCodeAt(i);if(r===-1&&JDn[s]===1)n===-1&&(n=i);else if(i!==0&&(s===32||s===9))r===-1&&n!==-1&&(r=i);else if(s===44){if(n===-1)throw new SyntaxError(`Unexpected character at index ${i}`);r===-1&&(r=i);let a=t.slice(n,r);if(e.has(a))throw new SyntaxError(`The "${a}" subprotocol is duplicated`);e.add(a),n=r=-1}else throw new SyntaxError(`Unexpected character at index ${i}`)}if(n===-1||r!==-1)throw new SyntaxError("Unexpected end of input");let o=t.slice(n,i);if(e.has(o))throw new SyntaxError(`The "${o}" subprotocol is duplicated`);return e.add(o),e}Krt.exports={parse:XDn}});var nit=Q((YIi,tit)=>{"use strict";var ZDn=K("events"),SV=K("http"),{Duplex:KIi}=K("stream"),{createHash:eMn}=K("crypto"),Yrt=xV(),cv=bB(),tMn=c0e(),nMn=vV(),{CLOSE_TIMEOUT:rMn,GUID:iMn,kWebSocket:oMn}=Y0(),sMn=/^[+/0-9A-Za-z]{22}==$/,Jrt=0,Xrt=1,eit=2,u0e=class extends ZDn{constructor(e,n){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxBufferedChunks:1024*1024,maxFragments:128*1024,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:rMn,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:nMn,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(e.port!=null?(this._server=SV.createServer((r,i)=>{let o=SV.STATUS_CODES[426];i.writeHead(426,{"Content-Length":o.length,"Content-Type":"text/plain"}),i.end(o)}),this._server.listen(e.port,e.host,e.backlog,n)):e.server&&(this._server=e.server),this._server){let r=this.emit.bind(this,"connection");this._removeListeners=aMn(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(i,o,s)=>{this.handleUpgrade(i,o,s,r)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=Jrt}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(this._state===eit){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(sU,this);return}if(e&&this.once("close",e),this._state!==Xrt)if(this._state=Xrt,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(sU,this):process.nextTick(sU,this);else{let n=this._server;this._removeListeners(),this._removeListeners=this._server=null,n.close(()=>{sU(this)})}}shouldHandle(e){if(this.options.path){let n=e.url.indexOf("?");if((n!==-1?e.url.slice(0,n):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,n,r,i){n.on("error",Zrt);let o=e.headers["sec-websocket-key"],s=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){uv(this,e,n,405,"Invalid HTTP method");return}if(s===void 0||s.toLowerCase()!=="websocket"){uv(this,e,n,400,"Invalid Upgrade header");return}if(o===void 0||!sMn.test(o)){uv(this,e,n,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){uv(this,e,n,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){aU(n,400);return}let c=e.headers["sec-websocket-protocol"],u=new Set;if(c!==void 0)try{u=tMn.parse(c)}catch{uv(this,e,n,400,"Invalid Sec-WebSocket-Protocol header");return}let l=e.headers["sec-websocket-extensions"],d={};if(this.options.perMessageDeflate&&l!==void 0){let p=new cv({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let h=Yrt.parse(l);h[cv.extensionName]&&(p.accept(h[cv.extensionName]),d[cv.extensionName]=p)}catch{uv(this,e,n,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let p={origin:e.headers[`${a===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(p,(h,m,f,g)=>{if(!h)return aU(n,m||401,f,g);this.completeUpgrade(d,o,u,e,n,r,i)});return}if(!this.options.verifyClient(p))return aU(n,401)}this.completeUpgrade(d,o,u,e,n,r,i)}completeUpgrade(e,n,r,i,o,s,a){if(!o.readable||!o.writable)return o.destroy();if(o[oMn])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Jrt)return aU(o,503);let u=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${eMn("sha1").update(n+iMn).digest("base64")}`],l=new this.options.WebSocket(null,void 0,this.options);if(r.size){let d=this.options.handleProtocols?this.options.handleProtocols(r,i):r.values().next().value;d&&(u.push(`Sec-WebSocket-Protocol: ${d}`),l._protocol=d)}if(e[cv.extensionName]){let d=e[cv.extensionName].params,p=Yrt.format({[cv.extensionName]:[d]});u.push(`Sec-WebSocket-Extensions: ${p}`),l._extensions=e}this.emit("headers",u,i),o.write(u.concat(`\r
100
+ `)}})}function $l(t){let e=v6();if(e===void 0)return!1;if(e.component==="broker"&&e.node_id!==void 0&&t.node_id!==void 0&&t.node_id!==e.node_id)throw new TypeError(`broker event target node_id must match bound node_id; received ${t.node_id}`);if(t.level==="debug"&&process.env.CRTR_LOG!=="debug")return!1;let n=MXe({...t,component:e.component,...e.node_id===void 0?{}:{node_id:e.node_id},...e.stream_id===void 0?{}:{stream_id:e.stream_id}}),r=NXe(n);return e.component==="broker"&&e.node_id!==void 0&&(pRn??=BI())?(hRn(e.node_id,r),!0):e.component==="daemon"?SXe(e.path,r):h6(e.path,r)}var pRn,Rtt,YI=y(()=>{"use strict";wfe();PXe();LXe();Ofe();Bc();RF();Rtt=Promise.resolve()});var Btt,Dtt=y(()=>{"use strict";YI();Btt={sandboxUsdPerGbHour:"CRTR_LEDGER_SANDBOX_USD_PER_GB_HOUR",sandboxStandbyS:"CRTR_LEDGER_SANDBOX_STANDBY_S",storageUsdPerGbMonth:"CRTR_LEDGER_STORAGE_USD_PER_GB_MONTH",infraFreeUsdPerMonth:"CRTR_LEDGER_INFRA_FREE_USD_PER_MONTH",takePct:"CRTR_LEDGER_TAKE_PCT",r2Move:"CRTR_LEDGER_R2_MOVE"}});function Y6(t){return t.flatMap(e=>e.path===void 0?[]:[e.path])}var $F=y(()=>{"use strict"});var Mtt=y(()=>{"use strict"});import{createHash as mRn}from"node:crypto";function Ltt(t){return t===void 0?"absent":mRn("sha256").update(JSON.stringify(t)).digest("hex")}function Qtt(t,e){Ntt.set(t,e)}function j0(){let t;try{t=y6()}catch(n){if(n instanceof IF)return Ptt();if(n instanceof CF)return rAe??Ptt();throw n}let e=Ntt.get(t);if(e!==void 0)return e;if(rAe!==void 0)return rAe;throw new iAe(t)}function Ott(t){fRn=t}function Ftt(t){gRn=t}function HF(t){let e=j0().settings[t];return{settings:e===void 0?null:structuredClone(e),revision:Ltt(e)}}function Utt(t){let e=j0().state[t];return e===void 0?{marketplaces:{},plugins:{},activeCanvas:null}:structuredClone(e)}function $tt(){return structuredClone(j0().profiles)}function Wtt(t){let e=j0().profiles.find(n=>n.profileId===t);return e===void 0?null:structuredClone(e)}var WF,iAe,Ntt,Ptt,rAe,fRn,gRn,lB=y(()=>{"use strict";JR();WF=class extends Error{constructor(){super("settings changed since the supplied revision"),this.name="SettingsRevisionConflictError"}},iAe=class extends Error{constructor(e){super(`settings for ${e} are not loaded in this process`),this.name="PersonSettingsNotLoadedError"}},Ntt=new Map;Ptt=()=>({profiles:[],defaults:{},settings:{},state:{},apps:{}});fRn=async()=>{throw new Error("no settings transport installed in this process")}});var Htt=y(()=>{"use strict"});import{chmodSync as Gxi,existsSync as Gtt,mkdirSync as qxi,readFileSync as qtt,rmSync as jxi,writeFileSync as zxi}from"node:fs";import{dirname as Kxi,join as jtt}from"node:path";function yw(){let t=ARn();if(!Gtt(t))return;let e=JSON.parse(qtt(t,"utf8"));if(typeof e.apiUrl!="string"||typeof e.environmentId!="string"||e.runId!==void 0&&typeof e.runId!="string"||typeof e.directoryUrl!="string")throw new Error(`${t} must hold {apiUrl, environmentId, directoryUrl}`);let n=e.account!==void 0&&typeof e.account?.id=="string"&&typeof e.account.display=="string"?{id:e.account.id,display:e.account.display}:void 0;return{apiUrl:e.apiUrl,environmentId:e.environmentId,...e.runId===void 0?{}:{runId:e.runId},directoryUrl:e.directoryUrl,...n===void 0?{}:{account:n}}}function ERn(){let t=yRn();if(!Gtt(t))return;let e=JSON.parse(qtt(t,"utf8"));if(typeof e.runId!="string"||typeof e.apiUrl!="string"||typeof e.directoryUrl!="string"||e.state!=="running"&&e.state!=="committed"&&e.state!=="activated"||typeof e.account?.id!="string"||typeof e.account.display!="string")throw new Error(`${t} is not a move record`);return{runId:e.runId,apiUrl:e.apiUrl,directoryUrl:e.directoryUrl,account:{id:e.account.id,display:e.account.display},notify:typeof e.notify=="string"?e.notify:null,state:e.state,notified:e.notified===!0,pid:typeof e.pid=="number"?e.pid:0}}var ARn,yRn,ztt,Vtt,GF=y(()=>{"use strict";Jm();qd();Ol();ru();ARn=()=>jtt(Fl(),"machine.json");yRn=()=>jtt(Fl(),"import","move.json");ztt=()=>ERn()?.state==="committed",Vtt=t=>new os("move_unfinished",`crtr's records are already in your Northlight account, but this computer has not switched over${t===void 0?".":`: ${t}`}`,ji.USAGE,{next:"Run `crtr sys signin` to finish."})});function xRn(t){return t.grantee??"app:terminal"}function bRn(t){if(!Ktt.test(t))throw dw(`invalid profile id: ${t}`,{received:t,next:"Profile ids look like <slug>-<8-hex-chars> (as printed by `crtr profile new`). Pass an exact id or a profile name, not a raw path."})}function J6(t){bRn(t);let e=Wtt(t);if(e===null)throw d6(`profile not found: ${t}`,{received:t});return zXe(xRn(e.manifest),t).dir}function CRn(){return{entries:$tt(),unreadableIds:[]}}function X6(){return CRn().entries}function IRn(t){let e=X6(),n=vRn(e,t,Ytt);return n?{kind:"resolved",entry:n}:{kind:"absent"}}function vRn(t,e,n){if(Ktt.test(e)){let i=t.find(o=>n(o).profileId===e);if(i!==void 0)return i}let r=t.filter(i=>n(i).name===e);if(r.length===1)return r[0];if(r.length>1){let i=r.map(o=>n(o).profileId);throw yXe(`profile name "${e}" matches ${i.length} profiles: ${i.join(", ")}`,{received:e,candidates:i,next:`Re-run with one exact profile id: ${i.join(", ")}.`})}return null}function SRn(t,e,n){let r=t.map(i=>`${n(i).profileId} (${n(i).name})`);return d6(`profile not found: ${e}`,{received:e,available:r,next:r.length>0?`Re-run with one of the profiles on this host: ${r.join(", ")} \u2014 or create one with \`crtr profile new --name <name>\`.`:"No profiles exist on this host yet \u2014 create one with `crtr profile new --name <name>`."})}function Tg(t){let e=IRn(t);if(e.kind==="resolved")return e.entry;throw SRn(X6(),t,Ytt)}var Ktt,Ytt,JI=y(()=>{"use strict";ru();Jm();$F();Ol();lB();qd();Htt();JR();GF();Ktt=/^[a-z0-9]+(?:-[a-z0-9]+)*-[0-9a-f]{8}$/;Ytt=t=>({profileId:t.profileId,name:t.manifest.name})});import{homedir as Jtt}from"node:os";import{existsSync as _Rn,statSync as kRn}from"node:fs";import{join as Z6,resolve as Xtt,dirname as TRn,sep as oAe}from"node:path";function Zd(){return Z6(Fl(),"scope")}function RRn(t,e){if(!_Rn(t)||Ym(t)===Ym(Z6(Jtt(),NI))||Ym(t).startsWith(`${Ym(Tfe())}${oAe}`)&&t.endsWith(`${oAe}home${oAe}${NI}`)||!BI()&&(Ym(t)===Ym(e)||Ym(t)===Ym(b6())))return!1;try{return kRn(t).isDirectory()}catch{return!1}}function BRn(t=process.cwd()){return Ztt(t)[0]??null}function DRn(t,e){let n=[],r=Ym(Jtt()),i=Xtt(t);for(;;){let o=Z6(i,NI);if(RRn(o,e)&&n.push(o),Ym(i)===r)return n;let s=TRn(i);if(s===i)return n;i=s}}function Ztt(t=process.cwd(),e=Fme()||null){return MRn(t,e)}function MRn(t,e){let n=Xtt(t),r=Zd(),i=[n];if(!BI()&&e!==null&&e!=="")try{let{manifest:a}=Tg(e);i.push(...Y6(a.projects))}catch{}let o=new Set,s=[];for(let a of i)for(let c of DRn(a,r))o.has(c)||(o.add(c),s.push(c));return s}function ent(t){return BRn(t)}function z0(t){return t==="builtin"?null:t==="user"?Zd():ent()}function tnt(t){let e=t==="user"?Fl():z0(t);return e?Z6(e,"plugins"):null}var XI=y(()=>{"use strict";Bc();$F();ru();Mtt();qd();JI();Ol();Jm()});import{join as PRn}from"node:path";function NRn(t){return PRn(t,fXe,gXe)}function LRn(t){let e;try{e=UI(t)}catch(n){return{status:"broken",error:n instanceof Error?n.message:String(n)}}return e===null?{status:"absent"}:typeof e!="object"||Array.isArray(e)?{status:"broken",error:"manifest is not a JSON object"}:{status:"ok",manifest:e}}function QRn(t){return LRn(NRn(t))}function nnt(t){let e=QRn(t);return e.status==="ok"?e.manifest:null}var sAe=y(()=>{"use strict";ru();Ol()});import{existsSync as ORn,mkdirSync as FRn,readdirSync as int,rmSync as ont,rmdirSync as URn,statSync as $Rn,unlinkSync as WRn,writeFileSync as HRn}from"node:fs";import{randomUUID as GRn}from"node:crypto";function ant(t){return Math.min(t*2,qRn)}function cnt(t){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,t)}function cAe(t,e){return`${t}/${aAe}${e}`}function uAe(t){try{return int(t).find(e=>e.startsWith(aAe))?.slice(aAe.length)??null}catch{return null}}function unt(t){let e=Number(t.split(".",1)[0]);if(!Number.isSafeInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(n){return n.code==="EPERM"}}function VRn(t){try{return int(t).length===0}catch{return!1}}function KRn(t){try{return Date.now()-$Rn(t).mtimeMs}catch{return 0}}function YRn(t,e){let n=uAe(t);if(n!==null){if(unt(n))return;try{WRn(cAe(t,n))}catch(r){if(r.code==="ENOENT")return;throw r}}else{if(KRn(t)<=e)return;if(!VRn(t)){ont(t,{recursive:!0,force:!0});return}}try{URn(t)}catch(r){let i=r.code;if(i!=="ENOENT"&&i!=="ENOTEMPTY"&&i!=="EEXIST")throw r}}function eV(t){let e=uAe(t);if(e===null)return null;let n=Number(e.split(".",1)[0]);return Number.isSafeInteger(n)&&n>0?n:null}function lnt(t,e){let n=Date.now()+e,r=snt;for(;;){let i=uAe(t);if(i===null||Number(i.split(".",1)[0])===process.pid||!unt(i))return;let o=n-Date.now();if(o<=0)return;cnt(Math.min(r,o)),r=ant(r)}}function rnt(t,e){let n=`${process.pid}.${GRn()}`;try{return FRn(t,{mode:448}),HRn(cAe(t,n),"",{flag:"wx",mode:384}),{path:t,token:n}}catch(r){if(r.code!=="EEXIST")throw r;return YRn(t,e),null}}function ZI(t,e,n={}){let r=n.staleMs??jRn,i=Date.now()+(n.timeoutMs??zRn),o=snt,s=rnt(t,r);for(;s===null;){if(Date.now()>=i)throw n.timeoutError?.()??new Error(`timed out waiting for the exclusive lock: ${t}`);cnt(Math.min(o,Math.max(0,i-Date.now()))),o=ant(o),s=rnt(t,r)}try{return e()}finally{ORn(cAe(s.path,s.token))&&ont(s.path,{recursive:!0,force:!0})}}var aAe,snt,qRn,jRn,zRn,ev=y(()=>{"use strict";aAe="owner.",snt=10,qRn=250,jRn=3e4,zRn=5e3});import{join as JRn}from"node:path";function dnt(t,e){return JRn(t,"tmp",`${e}.swap.lock`)}function pnt(t,e){let n=eV(dnt(t,e));return n!==null&&n!==process.pid}function hnt(t,e){lnt(dnt(t,e),XRn)}var XRn,mnt=y(()=>{"use strict";ev();XRn=2e3});function tV(t,e){let n=t.apps[ZRn];return n===void 0&&e===null?null:{...e??{},plugins:structuredClone(n?.plugins??{}),marketplaces:structuredClone(n?.marketplaces??{})}}var ZRn,lAe=y(()=>{"use strict";Bc();lB();ZRn="app:terminal"});import{join as dAe}from"node:path";function eBn(t,e){let n=t==="user"?pF()?tV(j0(),HF("user").settings):HF("user").settings:UI(dAe(e,c6));return n&&n.plugins&&typeof n.plugins=="object"?n.plugins:{}}function tBn(t,e,n){let r=Object.keys(e);return r.every(i=>n.has(i))?[]:r.filter(i=>!n.has(i)&&pnt(t,i))}function nV(t,e){if(t==="user"&&A6())return[];let n=t!=="user"?dAe(e,"plugins"):tnt("user");if(n===void 0||!_fe(n))return[];let r=eBn(t,e),i=fnt(t,n,r),o=tBn(e,r,new Set(i.map(s=>s.name)));if(o.length===0)return i;for(let s of o)hnt(e,s);return fnt(t,n,r)}function fnt(t,e,n){let r=[];for(let i of kfe(e)){let o=dAe(e,i),s=nnt(o);if(!s)continue;let a=n[i],c=typeof a?.version=="string"?a.version:s.version;r.push({name:i,scope:t,root:o,manifest:s,enabled:typeof a?.enabled=="boolean"?a.enabled:!0,sourceMarketplace:typeof a?.source_marketplace=="string"?a.source_marketplace:void 0,version:c})}return r}var rV=y(()=>{"use strict";ru();Ol();sAe();mnt();JR();lB();lAe();XI()});import{existsSync as nBn,realpathSync as rBn}from"node:fs";import{basename as iBn,dirname as oBn,join as iCi,resolve as gnt}from"node:path";function dB(t){let e=gnt(t),n=e,r=[];for(;!nBn(n);){let i=oBn(n);if(i===n)return e;r.unshift(iBn(n)),n=i}return gnt(rBn(n),...r)}var Ant=y(()=>{"use strict"});function sBn(t){let e=zi.indexOf(t);return`less ${zi.map((r,i)=>i===e?"\u25CF":"\u25CB").map((r,i)=>i===0?r:`${i<=e?"\u2501\u2501\u2501\u2501":"\u2500\u2500\u2500\u2500"}${r}`).join("")} more ${oV[t]}`}function iV(t,e,n){let r=t.indexOf(e),i=r>=0?r:0;return t[(i+n+t.length)%t.length]}function ynt(t,e,n){let r=t.indexOf(e);return r>=0?t[(r+n+t.length)%t.length]:n>=0?t.find(i=>i>e)??t[0]:[...t].reverse().find(i=>i<e)??t[t.length-1]}function tv(t,e){return t==="true"?!0:t==="false"?!1:`${e} must be true or false`}function xnt(t,e){if(!/^\d+$/.test(t))return`${e} must be an integer >= 0`;let n=Number(t);return Number.isSafeInteger(n)?n:`${e} must be an integer >= 0`}function aBn(t,e){let n=xnt(t,e);return typeof n=="string"||n<1?`${e} must be an integer >= 1`:n}function wnt(t,e){let n=t.providerOptions[e];if(n!==void 0)return n;let r={};return t.providerOptions[e]=r,r}function dBn(){let t=[];for(let e of Object.values(bnt))e.surface==="settings"&&("setting"in e?t.push(e.setting):t.push(...Object.values(e.settings)));return t.sort((e,n)=>e.order-n.order)}var oV,Ent,cBn,uBn,qF,bnt,lBn,aCi,pAe=y(()=>{"use strict";ru();oV={replies:"Replies only",summaries:"Messages + summaries",tools:"Tool calls",previews:"Previews",full:"Full"};Ent=[!1,"notify","apply"],cBn=[0,1,6,12,24,48,72,168],uBn=[1,2,3,4,5,6,8,10,12],qF="openai-codex";bnt={schema_version:{surface:"specialized",owner:"internal schema migration"},marketplaces:{surface:"specialized",owner:"Plugins and pkg market commands"},plugins:{surface:"specialized",owner:"Plugins tab and pkg plugin commands"},auto_update:{surface:"settings",settings:{crtr:{key:"auto_update.crtr",label:"crouter updates",description:"Notify about crouter releases, install them automatically, or turn checks off.",valueConstraint:"true|false|notify|apply; true stores notify",applies:"Applies on the next crouter command.",group:"updates",order:70,format:t=>t.auto_update.crtr===!1?"off":t.auto_update.crtr,cycle:(t,e)=>{t.auto_update.crtr=iV(Ent,t.auto_update.crtr,e)},setFromString:(t,e)=>{let n=e==="true"?"notify":e;return n!=="notify"&&n!=="apply"&&n!=="false"?"auto_update.crtr must be notify, apply, or false":(t.auto_update.crtr=n==="false"?!1:n,null)}},content:{key:"auto_update.content",label:"Content updates",description:"Notify about plugin and marketplace updates, apply them automatically, or turn checks off.",valueConstraint:"false|notify|apply",applies:"Applies on the next crouter command.",group:"updates",order:80,format:t=>t.auto_update.content===!1?"off":t.auto_update.content,cycle:(t,e)=>{t.auto_update.content=iV(Ent,t.auto_update.content,e)},setFromString:(t,e)=>e!=="notify"&&e!=="apply"&&e!=="false"?"auto_update.content must be notify, apply, or false":(t.auto_update.content=e==="false"?!1:e,null)},interval_hours:{key:"auto_update.interval_hours",label:"Update interval",description:"Minimum hours between automatic update checks. Zero checks on every command.",valueConstraint:"integer >= 0",applies:"Applies on the next crouter command.",group:"updates",order:90,format:t=>`${t.auto_update.interval_hours}h`,cycle:(t,e)=>{t.auto_update.interval_hours=ynt(cBn,t.auto_update.interval_hours,e)},setFromString:(t,e)=>{let n=xnt(e,"auto_update.interval_hours");return typeof n=="string"?n:(t.auto_update.interval_hours=n,null)}}}},max_panes_per_window:{surface:"settings",setting:{key:"max_panes_per_window",label:"Maximum panes",description:"Maximum human-review panes placed in one tmux window before using another window.",valueConstraint:"integer >= 1",applies:"Applies to the next pane placement.",group:"panes",order:20,format:t=>String(t.max_panes_per_window),cycle:(t,e)=>{t.max_panes_per_window=ynt(uBn,t.max_panes_per_window,e)},setFromString:(t,e)=>{let n=aBn(e,"max_panes_per_window");return typeof n=="string"?n:(t.max_panes_per_window=n,null)}}},auto_open_child_viewers:{surface:"settings",setting:{key:"auto_open_child_viewers",label:"Open child panes",description:"Open each managed child beside its watched parent. Off keeps new children running in the background.",valueConstraint:"true|false",applies:"Applies to the next managed child created; independent roots still open their attended viewer.",group:"panes",order:10,format:t=>t.auto_open_child_viewers?"on":"off",cycle:t=>{t.auto_open_child_viewers=!t.auto_open_child_viewers},setFromString:(t,e)=>{let n=tv(e,"auto_open_child_viewers");return typeof n=="string"?n:(t.auto_open_child_viewers=n,null)}}},brokerThresholds:{surface:"specialized",owner:"Broker limits tab"},lifecycle:{surface:"specialized",owner:"sys config set lifecycle.unattendedParkMs"},completion_bell:{surface:"settings",setting:{key:"completion_bell",label:"Completion bell",description:"Ring a short sound when the node in an attached viewer finishes a turn.",valueConstraint:"true|false",applies:"Applies on the next turn end.",group:"display",order:41,format:t=>t.completion_bell?"on":"off",cycle:t=>{t.completion_bell=!t.completion_bell},setFromString:(t,e)=>{let n=tv(e,"completion_bell");return typeof n=="string"?n:(t.completion_bell=n,null)}}},working_gerunds:{surface:"specialized",owner:"sys config set working_gerunds"},whip_mode:{surface:"settings",setting:{key:"whip_mode",label:"Whip mode",description:"Play the whip animation when you send a prompt and when a viewer opens for an agent with an initial prompt.",valueConstraint:"true|false",applies:"Applies on the next attach.",group:"display",order:39,format:t=>t.whip_mode?"on":"off",cycle:t=>{t.whip_mode=!t.whip_mode},setFromString:(t,e)=>{let n=tv(e,"whip_mode");return typeof n=="string"?n:(t.whip_mode=n,null)}}},page_surface:{surface:"settings",setting:{key:"page_surface",label:"Page human surface",description:"This host reads pages in a browser rather than a terminal. Agents are told the page module runs as written, HTML pages are offered, and document review and live display leave the command tree.",valueConstraint:"true|false",applies:"Applies when human command help is assembled.",group:"display",order:37,format:t=>t.page_surface?"on":"off",cycle:t=>{t.page_surface=!t.page_surface},setFromString:(t,e)=>{let n=tv(e,"page_surface");return typeof n=="string"?n:(t.page_surface=n,null)}}},whip_messages:{surface:"specialized",owner:"sys config set whip_messages"},whip_message_mode:{surface:"settings",setting:{key:"whip_message_mode",label:"Whip message",description:"What the whip action sends: a random line from whip_messages, or the fixed \u201CGo faster\u201D.",valueConstraint:LI.join("|"),applies:"Applies on the next attach.",group:"display",order:40,format:t=>t.whip_message_mode==="go-faster"?"go faster":"random",cycle:(t,e)=>{t.whip_message_mode=iV(LI,t.whip_message_mode,e)},setFromString:(t,e)=>LI.includes(e)?(t.whip_message_mode=e,null):`whip_message_mode must be one of: ${LI.join("|")}`}},mouse_mode_default:{surface:"settings",setting:{key:"mouse_mode_default",label:"Default mouse mode",description:"Initial mouse wheel scrolling for each attached viewer.",valueConstraint:QI.join("|"),applies:"Applies on the next attach.",group:"display",order:38,format:t=>t.mouse_mode_default==="tmux"?"follow tmux":t.mouse_mode_default,cycle:(t,e)=>{t.mouse_mode_default=iV(QI,t.mouse_mode_default,e)},setFromString:(t,e)=>QI.includes(e)?(t.mouse_mode_default=e,null):`mouse_mode_default must be one of: ${QI.join("|")}`}},bash_tool_purpose:{surface:"settings",setting:{key:"bash_tool_purpose",label:"Bash purpose field",description:"Expose the optional purpose label to agents in the bash tool schema. Off removes the field without disabling the bash valve.",valueConstraint:"true|false",applies:"Applies on the next node session.",group:"display",order:25,format:t=>t.bash_tool_purpose?"on":"off",cycle:t=>{t.bash_tool_purpose=!t.bash_tool_purpose},setFromString:(t,e)=>{let n=tv(e,"bash_tool_purpose");return typeof n=="string"?n:(t.bash_tool_purpose=n,null)}}},verbosity:{surface:"settings",setting:{key:"verbosity",label:"Verbosity",description:"How much of a transcript the viewer shows, from one rewritten reply per message to every tool call untruncated. Ctrl+O shows more and Ctrl+Shift+O less in the open viewer only; this sets where every viewer starts.",valueConstraint:zi.join("|"),applies:"Applies on the next attach.",group:"display",order:30,format:t=>t.verbosity,display:t=>sBn(t.verbosity),cycle:(t,e)=>{let n=zi.indexOf(t.verbosity)+e;t.verbosity=zi[Math.max(0,Math.min(zi.length-1,n))]},setFromString:(t,e)=>zi.includes(e)?(t.verbosity=e,null):`verbosity must be one of: ${zi.join("|")}`}},document_port:{surface:"settings",setting:{key:"document_port",label:"Document browser port",description:"Fixed localhost port where crtrd serves editable document pages.",valueConstraint:"1-65535",applies:"Applies after daemon handover and on the next attach.",group:"display",order:37.5,format:t=>String(t.document_port),cycle:(t,e)=>{t.document_port=Math.max(1,Math.min(65535,t.document_port+e))},setFromString:(t,e)=>{let n=Number(e);return!/^\d+$/.test(e)||!Number.isInteger(n)||n<1||n>65535?"document_port must be an integer from 1 to 65535":(t.document_port=n,null)}}},detailed_tool_recaps:{surface:"settings",setting:{key:"detailed_tool_recaps",label:"Detailed tool recaps",description:"Show each document read and edited file in folded tool recaps. Off shows a compact count line instead.",valueConstraint:"true|false",applies:"Applies on the next attach.",group:"display",order:36,format:t=>t.detailed_tool_recaps?"on":"off",cycle:t=>{t.detailed_tool_recaps=!t.detailed_tool_recaps},setFromString:(t,e)=>{let n=tv(e,"detailed_tool_recaps");return typeof n=="string"?n:(t.detailed_tool_recaps=n,null)}}},keybindings:{surface:"specialized",owner:"Keybindings tab"},tmux_passthrough:{surface:"specialized",owner:"Keybindings tab"},providerOptions:{surface:"settings",settings:{"openai-codex.fastMode":{key:`providerOptions.${qF}.fastMode`,label:"Codex fast mode",description:"Serve Codex turns at the ChatGPT priority tier: about 1.5x faster generation for about 2x the credits. Displayed cost does not reflect the premium.",valueConstraint:"true|false",applies:"Applies on each node's next turn.",group:"providers",order:40,format:t=>t.providerOptions[qF]?.fastMode?"on":"off",cycle:t=>{let e=wnt(t,qF);e.fastMode=!e.fastMode},setFromString:(t,e)=>{let n=tv(e,`providerOptions.${qF}.fastMode`);return typeof n=="string"?n:(wnt(t,qF).fastMode=n,null)}}}},modelLadders:{surface:"specialized",owner:"Models tab"},modelRoutes:{surface:"specialized",owner:"Models route declarations"},modelRouting:{surface:"specialized",owner:"Models route declarations"},kinds:{surface:"specialized",owner:"Models tab and kind registry"},page_components:{surface:"specialized",owner:"Page component catalog: product-registered page component kinds"},remoteCanvas:{surface:"specialized",owner:"canvas config commands"},api:{surface:"specialized",owner:"sys connect"},paths:{surface:"specialized",owner:"runtime layout"},store:{surface:"specialized",owner:"daemon conversation store"},runtime:{surface:"specialized",owner:"app-facing listener"},spawnEnv:{surface:"specialized",owner:"spawn environment allow-list"},bin:{surface:"specialized",owner:"bare-binary contributions on every node PATH"},humanActions:{surface:"specialized",owner:"scope-configured human completion actions"}},lBn=Object.keys(bnt);aCi=dBn()});function jF(t){return t.split("-").map(e=>e===""?"":`${e[0].toUpperCase()}${e.slice(1)}`).join("")}function hB(t){try{let e=JSON.stringify(t);return e===void 0?String(t):e}catch{return String(t)}}function pB(t,e,n,r){if(t!==void 0){if(typeof t!="string"||t.trim()==="")throw new Error(`${n}[${r}].${e} must be a non-empty string; received ${hB(t)}`);return t.trim()}}function gAe(t,e="page_components"){if(t===void 0)return[];if(!Array.isArray(t))throw new Error(`${e} must be an array; received ${hB(t)}`);let n=new Set,r=new Set;return t.map((i,o)=>{let s;if(typeof i=="string")s={kind:i.trim()};else if(i!==null&&typeof i=="object"&&!Array.isArray(i)){let u=i,l=Object.keys(u).filter(d=>!["kind","description","useWhen","doc","display"].includes(d));if(l.length>0)throw new Error(`${e}[${o}] has unknown field(s): ${l.join(", ")}`);if(typeof u.kind!="string")throw new Error(`${e}[${o}].kind must be a string; offending entry: ${hB(i)}`);if(u.display!==void 0&&typeof u.display!="boolean")throw new Error(`${e}[${o}].display must be a boolean; offending entry: ${hB(i)}`);s={kind:u.kind.trim(),...pB(u.description,"description",e,o)===void 0?{}:{description:pB(u.description,"description",e,o)},...pB(u.useWhen,"useWhen",e,o)===void 0?{}:{useWhen:pB(u.useWhen,"useWhen",e,o)},...pB(u.doc,"doc",e,o)===void 0?{}:{doc:pB(u.doc,"doc",e,o)},...u.display===!0?{display:!0}:{}}}else throw new Error(`${e}[${o}] must be a string or component object; offending entry: ${hB(i)}`);let a=s.kind;if(!hBn.test(a))throw new Error(`${e}[${o}] has invalid page kind ${hB(a)}; expected /^[a-z][a-z0-9-]{0,63}$/`);if(mBn.has(a)||pBn.includes(a))throw new Error(`${e}[${o}] collides with built-in page kind "${a}"`);if(n.has(a))throw new Error(`${e}[${o}] duplicates page kind "${a}"`);let c=jF(a);if(sV.has(c))throw new Error(`${e}[${o}] kind "${a}" derives JSX tag "${c}", which collides with a built-in page component`);if(r.has(c))throw new Error(`${e}[${o}] kind "${a}" derives JSX tag "${c}", which duplicates another product page component`);return n.add(a),r.add(c),s})}function Int(t){let e=new Map,n=new Map,r=[];for(let i of t)for(let o of i.components){let s=e.get(o.kind);if(s!==void 0)throw new Error(`page component kind "${o.kind}" is registered by both ${s} and ${i.origin}`);let a=jF(o.kind),c=n.get(a);if(c!==void 0)throw new Error(`page component kind "${o.kind}" (${i.origin}) derives JSX tag "${a}", which duplicates kind "${c.kind}" from ${c.origin}`);e.set(o.kind,i.origin),n.set(a,{kind:o.kind,origin:i.origin}),r.push(o)}return r}function vnt(t,e){return e.find(n=>n.kind===t)}var hAe,pBn,hBn,mBn,Cnt,mAe,sV,fAe,zF=y(()=>{"use strict";hAe=["options","text","table","cards","chart"],pBn=["page","step"],hBn=/^[a-z][a-z0-9-]{0,63}$/,mBn=new Set(hAe),Cnt=[{kind:"page",tag:"Page",description:"the page itself: title, subtitle, and every step it contains",useWhen:"use as the single root element every page returns",builtin:!0,structural:!0},{kind:"step",tag:"Step",description:"one step inside a Page",useWhen:"use for each step the user sees and completes in sequence",builtin:!0,structural:!0},{kind:"options",tag:"UserQuestion",description:"known alternatives with single or multiple selection",useWhen:"use when the user picks among known alternatives, optionally with freetext",builtin:!0,structural:!1},{kind:"text",tag:"UserText",description:"writing surface whose answer is the text the user hands back",useWhen:"use when you need prose from the user \u2014 a value they write, or a draft they revise; prose they only read is a plain element",builtin:!0,structural:!1},{kind:"table",tag:"UserTable",description:"rows and columns with optional selection",useWhen:"use when structured records are easiest to compare in rows and columns",builtin:!0,structural:!1},{kind:"cards",tag:"UserCards",description:"visual records with optional selection",useWhen:"use when the user compares or picks richer items than a compact option list can carry",builtin:!0,structural:!1},{kind:"chart",tag:"Chart",description:"line, bar, or area data visualization",useWhen:"use when shape, trend, or magnitude matters more than exact tabular values",builtin:!0,structural:!1}];mAe=Object.fromEntries(Cnt.filter(t=>!t.structural).map(t=>[t.tag,t.kind])),sV=new Set(Cnt.map(t=>t.tag)),fAe=new Set(["Card","CardHeader","CardTitle","CardDescription","CardContent","CardFooter","CardAction","Badge","Button","Separator","Progress","Alert","AlertTitle","AlertDescription","Table","TableHeader","TableBody","TableFooter","TableRow","TableHead","TableCell","TableCaption","Tabs","TabsList","TabsTrigger","TabsContent","Accordion","AccordionItem","AccordionTrigger","AccordionContent"])});import{basename as Rnt,join as Bnt}from"node:path";import{existsSync as gBn,mkdirSync as fCi,statSync as gCi}from"node:fs";function ABn(t){return Bnt(t,c6)}function yBn(t){return Bnt(t,AXe)}function Dnt(t){let e=dB(t),n=dB(Zd());if(e===n)return{key:"user",kind:"user",root:n};if(Rnt(e)===".crouter")return{key:"project",kind:"project",root:e};for(let r of X6()){let i=dB(J6(r.profileId));if(e===i)return{key:`profile:${r.profileId}`,kind:"profile",root:i,profileId:r.profileId}}throw new Error(`settings root is not a recognized owner: ${t}`)}function Mnt(t){if(Rnt(t)===".crouter"){let r;try{r=dB(t)}catch(i){if(i.code==="ENOENT")return null;throw i}if(r!==dB(Zd()))return UI(ABn(t))}let e=Dnt(t).key,n=HF(e).settings;return e==="user"&&pF()?tV(j0(),n):n}function lh(t){let e=EBn[wBn];if(e){if(t!=="user")throw new Error(`broker config snapshot has no ${t} scope`);return e.user}let n=z0(t);return n?xBn(n):l6()}function xBn(t){let e=Mnt(t);return e?VBn(e):l6()}function bBn(t){let e=UI(yBn(t));return{marketplaces:e?.marketplaces??{},plugins:e?.plugins??{},activeCanvas:e?.activeCanvas??null,...e?.last_self_check===void 0?{}:{last_self_check:e.last_self_check}}}function Pnt(t){let e=z0(t);return e?t==="project"?gBn(e)?bBn(e):Efe():Utt(Dnt(e).key):Efe()}function CBn(t){if(t===null||typeof t!="object"||Array.isArray(t))return{};let e={};for(let[n,r]of Object.entries(t))Array.isArray(r)&&r.every(i=>typeof i=="string")&&(e[n]=[...r]);return e}function mB(t){return t===void 0?[...vBn]:Array.isArray(t)?[...new Set(t.filter(e=>typeof e=="string"&&PI.has(e)&&IBn.has(e)))]:[]}function SBn(t,e=yfe()){let n=e;if(t===null||typeof t!="object")return n;let r=t,i={anthropic:{...n.anthropic},openai:{...n.openai},...n.defaultProvider!==void 0?{defaultProvider:n.defaultProvider}:{}};(r.defaultProvider==="anthropic"||r.defaultProvider==="openai")&&(i.defaultProvider=r.defaultProvider);for(let o of["anthropic","openai"]){let s=r[o];if(!(s===null||typeof s!="object"))for(let[a,c]of Object.entries(s))(a==="ultra"||a==="strong"||a==="medium"||a==="light")&&typeof c=="string"&&(i[o][a]=c)}return i}function Nnt(t){return t==="ultra"||t==="strong"||t==="medium"||t==="light"}function AAe(){return Object.create(null)}function aV(t,e,n){Object.defineProperty(t,e,{value:n,writable:!0,enumerable:!0,configurable:!0})}function kBn(t){let e=AAe();for(let[n,r]of Object.entries(t??{}))aV(e,n,r);return e}function VF(t,e){$l({level:"warn",event:"config.model_routes.invalid",fields:{route_id:t,rule:e}})}function TBn(t,e={}){let n=kBn(e);if(t===null||typeof t!="object"||Array.isArray(t))return n;for(let[r,i]of Object.entries(t)){if(r.trim()===""){VF(r,"route id must be a non-empty string");continue}if(i===null||typeof i!="object"||Array.isArray(i)){VF(r,"route must be an object");continue}let o=i,s=n[r],a={...s},c;for(let u of["family","credentialSource","providerId"]){let l=o[u];if(l!==void 0){if(typeof l!="string"||l.trim()===""){c=`${u} must be a non-empty string`;break}a[u]=l}}if(c===void 0&&o.models!==void 0)if(o.models===null||typeof o.models!="object"||Array.isArray(o.models))c="models must be an object";else{let u={...s?.models};for(let[l,d]of Object.entries(o.models)){if(!Nnt(l)){c=`models.${l} is not a model strength`;break}if(typeof d!="string"||d.trim()===""){c=`models.${l} must be a non-empty provider/id ref`;break}let p=d.indexOf("/");if(p<=0||p===d.length-1){c=`models.${l} must be provider/id`;break}u[l]=d}a.models=u}if(c===void 0&&a.models!==void 0&&a.providerId!==void 0){for(let[u,l]of Object.entries(a.models))if(l.slice(0,l.indexOf("/"))!==a.providerId){c=`models.${u} provider prefix must equal providerId`;break}}if(c!==void 0){VF(r,c);continue}aV(n,r,a)}return n}function RBn(t){let e=AAe(),n=AAe();for(let[r,i]of Object.entries(t)){if(i.family===void 0||i.credentialSource===void 0||i.providerId===void 0||i.models===void 0){VF(r,"route must include family, credentialSource, providerId, and models");continue}let o=_Bn.filter(s=>i.models[s]===void 0);if(o.length>0){VF(r,`incomplete route; missing strengths: ${o.join(", ")}`),aV(n,r,{family:i.family,credentialSource:i.credentialSource,providerId:i.providerId,models:i.models});continue}aV(e,r,{family:i.family,credentialSource:i.credentialSource,providerId:i.providerId,models:i.models})}return{complete:e,legacy:n}}function BBn(t,e){if(t===void 0||t===null||typeof t!="object"||Array.isArray(t))return e;let n=t,r=o=>Array.isArray(o)&&o.every(s=>typeof s=="string"&&s.trim()!=="")?[...o]:void 0,i=Array.isArray(n.strengthFallback)&&n.strengthFallback.every(o=>Nnt(o))?[...n.strengthFallback]:void 0;return{...r(n.credentialSourceOrder)!==void 0?{credentialSourceOrder:r(n.credentialSourceOrder)}:{},...r(n.familyOrder)!==void 0?{familyOrder:r(n.familyOrder)}:{},...i!==void 0?{strengthFallback:i}:{}}}function DBn(t){return t!==""&&t.replace(/\*/g,"")===""}function MBn(t,e=[]){let n=t,r=Array.isArray(n?.allow)?n.allow.filter(i=>typeof i=="string"):[];for(let i of r)if(DBn(i))throw new Error(`spawnEnv.allow: "${i}" matches every env var name (inherit-all) \u2014 this is exactly the leak the spawn-env boundary closes. Name the specific vars/prefixes you actually need instead (e.g. "AWS_*", "GIT_ASKPASS").`);return{allow:[...new Set([...e,...r])]}}function PBn(t,e={}){let n={};for(let[r,i]of Object.entries(e))n[r]={...i};if(t!==null&&typeof t=="object")for(let[r,i]of Object.entries(t)){if(i===null||typeof i!="object")continue;let o={...n[r]},s=i.fastMode;typeof s=="boolean"&&(o.fastMode=s),n[r]=o}return n}function LBn(t,e){if(e==="bin"&&NBn.has(t))return`${e}.${t} is reserved by crouter \u2014 pick another bare command name`;if(!Snt.test(t))return`${e}.${t} is not a safe bare command name (expected ${Snt.source})`}function QBn(t){if(t===null||typeof t!="object"||Array.isArray(t))return{};let e={};for(let[n,r]of Object.entries(t))LBn(n,"bin")===void 0&&(typeof r!="string"||r.trim()===""||(e[n]=r));return e}function OBn(t){if(t===null||typeof t!="object"||Array.isArray(t))return[{name:"humanActions",reason:"humanActions must be a JSON object mapping action names to {argv, cwd}",block:!0}];let e=[];for(let[n,r]of Object.entries(t)){let i=[];if(_nt.test(n)||i.push(`action name must match ${_nt.source}`),r===null||typeof r!="object"||Array.isArray(r))i.push("action must be an object with argv and cwd");else{let o=r,s=Object.keys(o).filter(a=>a!=="argv"&&a!=="cwd");s.length>0&&i.push(`action has unsupported field${s.length===1?"":"s"}: ${s.join(", ")}`),(!Array.isArray(o.argv)||o.argv.length===0||!o.argv.every(a=>typeof a=="string"&&a.length>0))&&i.push("argv must be a non-empty array of non-empty strings"),(typeof o.cwd!="string"||o.cwd.length===0)&&i.push("cwd is required and must be a non-empty string")}i.length>0&&e.push({name:n,reason:i.join("; ")})}return e}function FBn(t){if(t===null||typeof t!="object"||Array.isArray(t))return{};let e=new Set(OBn(t).map(r=>r.name)),n={};for(let[r,i]of Object.entries(t)){if(e.has(r))continue;let o=i;n[r]={argv:[...o.argv],cwd:o.cwd}}return n}function UBn(t){if(t===null||typeof t!="object")return null;let e=t,n={};typeof e.whenToUse=="string"&&e.whenToUse.trim()!==""&&(n.whenToUse=e.whenToUse),typeof e.model=="string"&&e.model.trim()!==""&&(n.model=e.model),typeof e.orchestratorModel=="string"&&e.orchestratorModel.trim()!==""&&(n.orchestratorModel=e.orchestratorModel);let r=i=>Array.isArray(i)&&i.every(o=>typeof o=="string");return r(e.tools)&&(n.tools=e.tools),r(e.extensions)&&(n.extensions=e.extensions),r(e.availableTo)&&(n.availableTo=e.availableTo),Object.keys(n).length>0?n:null}function $Bn(t,e=Afe()){let n={...e};if(t!==null&&typeof t=="object")for(let[r,i]of Object.entries(t)){let o=UBn(i);if(o===null)continue;let s=n[r];s!==void 0?n[r]={...s,...o}:o.whenToUse!==void 0&&(n[r]=o)}return n}function uV(){let t=[{origin:"config.json",components:lh("user").page_components}],e=z0("user");if(e!==null){let n=nV("user",e).filter(r=>r.enabled&&r.manifest.page_components!==void 0).sort((r,i)=>r.name.localeCompare(i.name));for(let r of n){let i=`plugin "${r.name}" page_components`;t.push({origin:`plugin "${r.name}"`,components:gAe(r.manifest.page_components,i)})}}return Int(t)}function WBn(t){if(t===null||typeof t!="object")return null;let e=t;if(typeof e.previewEndpoint!="string"||e.previewEndpoint.trim()===""||typeof e.relayTokenRef!="string"||e.relayTokenRef.trim()==="")return null;let n={previewEndpoint:e.previewEndpoint,relayTokenRef:e.relayTokenRef};return typeof e.cpOrigin=="string"&&e.cpOrigin.trim()!==""&&(n.cpOrigin=e.cpOrigin),n}function HBn(t,e=gfe()){let n={...e.targets};if(t!==null&&typeof t=="object"){let r=t;if(r.targets!==null&&typeof r.targets=="object")for(let[i,o]of Object.entries(r.targets)){let s=WBn(o);s!==null&&(n[i]=s)}}return{targets:n}}function knt(t,e){return t===!0?"notify":t===!1?!1:t==="notify"||t==="apply"?t:e}function cV(t,e){return typeof t=="number"&&Number.isSafeInteger(t)&&t>=1?t:e}function GBn(t,e){let n=t!==null&&typeof t=="object"?t:{},r=cV(n.warning,e.warning),i=cV(n.automaticReviveCap,e.automaticReviveCap);return r<=i?{warning:r,automaticReviveCap:i}:{...e}}function qBn(t,e){return{unattendedParkMs:cV((t!==null&&typeof t=="object"?t:{}).unattendedParkMs,e.unattendedParkMs)}}function jBn(t){if(!Array.isArray(t))return[...u6];let e=t.filter(n=>typeof n=="string"&&n.trim()!=="").map(n=>n.trim());return e.length>0?e:[...u6]}function zBn(t,e){if(t===null||typeof t!="object")return{...e};let n=t.tcp;return{tcp:typeof n=="string"?n:e.tcp}}function VBn(t){!Tnt&&t.ledger!==void 0&&(Tnt=!0,$l({level:"warn",event:"config.ledger.ignored",fields:{variables:Object.values(Btt)}}));let e=l6(),n=e.schema_version,r=t.marketplaces===void 0?{}:t.marketplaces,i=t.plugins===void 0?{}:t.plugins,o=t.auto_update,s=o&&typeof o.interval_hours=="number"?o.interval_hours:void 0,a=s!==void 0&&Number.isFinite(s)&&s>=0?s:e.auto_update.interval_hours,c={crtr:knt(o?.crtr,e.auto_update.crtr),content:knt(o?.content,e.auto_update.content),interval_hours:a},u=t.max_panes_per_window,l=cV(u,e.max_panes_per_window),d=typeof t.auto_open_child_viewers=="boolean"?t.auto_open_child_viewers:e.auto_open_child_viewers,p=GBn(t.brokerThresholds,e.brokerThresholds),h=qBn(t.lifecycle,e.lifecycle),m=typeof t.completion_bell=="boolean"?t.completion_bell:e.completion_bell,f=t.working_gerunds===void 0?[...e.working_gerunds]:hXe(t.working_gerunds),g=typeof t.whip_mode=="boolean"?t.whip_mode:e.whip_mode,A=gAe(t.page_components),x=typeof t.page_surface=="boolean"?t.page_surface:e.page_surface,b=jBn(t.whip_messages),v=LI.includes(t.whip_message_mode)?t.whip_message_mode:e.whip_message_mode,S=QI.includes(t.mouse_mode_default)?t.mouse_mode_default:e.mouse_mode_default,_=typeof t.bash_tool_purpose=="boolean"?t.bash_tool_purpose:e.bash_tool_purpose,T=zi.includes(t.verbosity)?t.verbosity:e.verbosity,B=typeof t.detailed_tool_recaps=="boolean"?t.detailed_tool_recaps:e.detailed_tool_recaps,R=Number.isInteger(t.document_port)&&t.document_port>=1&&t.document_port<=65535?t.document_port:e.document_port,P=CBn(t.keybindings),O=mB(t.tmux_passthrough),$=SBn(t.modelLadders),j=PBn(t.providerOptions,e.providerOptions),H=RBn(TBn(t.modelRoutes)),le=H.complete,ee=BBn(t.modelRouting,void 0),ge=$Bn(t.kinds),Ie=HBn(t.remoteCanvas),$e=zBn(t.api,e.api),wt=t.paths;if(wt?.user_files!==void 0&&(typeof wt.user_files!="string"||!wt.user_files.startsWith("/")))throw new Error("paths.user_files must be an absolute path");let Ze=t.store,xt=t.runtime;if(xt?.person_uids!==void 0&&(!Array.isArray(xt.person_uids)||!xt.person_uids.every(et=>Number.isSafeInteger(et)&&et>=0)))throw new Error("runtime.person_uids must be an array of nonnegative integer uids");let re=MBn(t.spawnEnv,e.spawnEnv?.allow),ot=QBn(t.bin),ke=FBn(t.humanActions);return{bin:ot,humanActions:ke,schema_version:n,marketplaces:r,plugins:i,auto_update:c,max_panes_per_window:l,auto_open_child_viewers:d,brokerThresholds:p,lifecycle:h,completion_bell:m,working_gerunds:f,whip_mode:g,page_components:A,page_surface:x,whip_messages:b,whip_message_mode:v,mouse_mode_default:S,bash_tool_purpose:_,verbosity:T,detailed_tool_recaps:B,document_port:R,keybindings:P,tmux_passthrough:O,modelLadders:$,providerOptions:j,...Object.keys(le).length>0?{modelRoutes:le}:{},...Object.keys(H.legacy).length>0?{legacyModelRoutes:H.legacy}:{},...ee!==void 0?{modelRouting:ee}:{},kinds:ge,remoteCanvas:Ie,api:$e,...wt?{paths:wt}:{},...Ze?{store:Ze}:{},...xt?{runtime:xt}:{},spawnEnv:re}}function KBn(t){return Mnt(t)}function Lnt(t){let e=z0(t);return e?KBn(e):null}var EBn,wBn,IBn,vBn,_Bn,Snt,NBn,_nt,Tnt,Vd=y(()=>{"use strict";Bc();ru();o6();qd();YI();Dtt();Ol();XI();rV();JI();Ant();lB();lAe();ev();pAe();a6();zF();EBn=globalThis,wBn=Symbol.for("crtr.broker.config-snapshot");IBn=new Set(Gd.filter(wF).map(t=>t.id)),vBn=Object.freeze(["crtr.attach.scroll.up","crtr.attach.scroll.down","crtr.attach.scroll.page-up","crtr.attach.scroll.page-down","crtr.attach.scroll.live"]);_Bn=["ultra","strong","medium","light"];Snt=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,NBn=new Set(["crtr","crtrd"]);_nt=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;Tnt=!1});var Y0=Q((MIi,nrt)=>{"use strict";var ert=["nodebuffer","arraybuffer","fragments"],trt=typeof Blob<"u";trt&&ert.push("blob");nrt.exports={BINARY_TYPES:ert,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:trt,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var tU=Q((PIi,hV)=>{"use strict";var{EMPTY_BUFFER:W1n}=Y0(),HAe=Buffer[Symbol.species];function H1n(t,e){if(t.length===0)return W1n;if(t.length===1)return t[0];let n=Buffer.allocUnsafe(e),r=0;for(let i=0;i<t.length;i++){let o=t[i];n.set(o,r),r+=o.length}return r<e?new HAe(n.buffer,n.byteOffset,r):n}function rrt(t,e,n,r,i){for(let o=0;o<i;o++)n[r+o]=t[o]^e[o&3]}function irt(t,e){for(let n=0;n<t.length;n++)t[n]^=e[n&3]}function G1n(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function GAe(t){if(GAe.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new HAe(t):ArrayBuffer.isView(t)?e=new HAe(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),GAe.readOnly=!1),e}hV.exports={concat:H1n,mask:rrt,toArrayBuffer:G1n,toBuffer:GAe,unmask:irt};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=K("bufferutil");hV.exports.mask=function(e,n,r,i,o){o<48?rrt(e,n,r,i,o):t.mask(e,n,r,i,o)},hV.exports.unmask=function(e,n){e.length<32?irt(e,n):t.unmask(e,n)}}catch{}});var art=Q((NIi,srt)=>{"use strict";var ort=Symbol("kDone"),qAe=Symbol("kRun"),jAe=class{constructor(e){this[ort]=()=>{this.pending--,this[qAe]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[qAe]()}[qAe](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[ort])}}};srt.exports=jAe});var bB=Q((LIi,drt)=>{"use strict";var nU=K("zlib"),crt=tU(),q1n=art(),{kStatusCode:urt}=Y0(),j1n=Buffer[Symbol.species],z1n=Buffer.from([0,0,255,255]),fV=Symbol("permessage-deflate"),J0=Symbol("total-length"),wB=Symbol("callback"),xw=Symbol("buffers"),xB=Symbol("error"),mV,zAe=class{constructor(e){if(this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!mV){let n=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;mV=new q1n(n)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[wB];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let n=this._options,r=e.find(i=>!(n.serverNoContextTakeover===!1&&i.server_no_context_takeover||i.server_max_window_bits&&(n.serverMaxWindowBits===!1||typeof n.serverMaxWindowBits=="number"&&n.serverMaxWindowBits>i.server_max_window_bits)||typeof n.clientMaxWindowBits=="number"&&!i.client_max_window_bits));if(!r)throw new Error("None of the extension offers can be accepted");return n.serverNoContextTakeover&&(r.server_no_context_takeover=!0),n.clientNoContextTakeover&&(r.client_no_context_takeover=!0),typeof n.serverMaxWindowBits=="number"&&(r.server_max_window_bits=n.serverMaxWindowBits),typeof n.clientMaxWindowBits=="number"?r.client_max_window_bits=n.clientMaxWindowBits:(r.client_max_window_bits===!0||n.clientMaxWindowBits===!1)&&delete r.client_max_window_bits,r}acceptAsClient(e){let n=e[0];if(this._options.clientNoContextTakeover===!1&&n.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!n.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(n.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&n.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return n}normalizeParams(e){return e.forEach(n=>{Object.keys(n).forEach(r=>{let i=n[r];if(i.length>1)throw new Error(`Parameter "${r}" must have only a single value`);if(i=i[0],r==="client_max_window_bits"){if(i!==!0){let o=+i;if(!Number.isInteger(o)||o<8||o>15)throw new TypeError(`Invalid value for parameter "${r}": ${i}`);i=o}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${r}": ${i}`)}else if(r==="server_max_window_bits"){let o=+i;if(!Number.isInteger(o)||o<8||o>15)throw new TypeError(`Invalid value for parameter "${r}": ${i}`);i=o}else if(r==="client_no_context_takeover"||r==="server_no_context_takeover"){if(i!==!0)throw new TypeError(`Invalid value for parameter "${r}": ${i}`)}else throw new Error(`Unknown parameter "${r}"`);n[r]=i})}),e}decompress(e,n,r){mV.add(i=>{this._decompress(e,n,(o,s)=>{i(),r(o,s)})})}compress(e,n,r){mV.add(i=>{this._compress(e,n,(o,s)=>{i(),r(o,s)})})}_decompress(e,n,r){let i=this._isServer?"client":"server";if(!this._inflate){let o=`${i}_max_window_bits`,s=typeof this.params[o]!="number"?nU.Z_DEFAULT_WINDOWBITS:this.params[o];this._inflate=nU.createInflateRaw({...this._options.zlibInflateOptions,windowBits:s}),this._inflate[fV]=this,this._inflate[J0]=0,this._inflate[xw]=[],this._inflate.on("error",K1n),this._inflate.on("data",lrt)}this._inflate[wB]=r,this._inflate.write(e),n&&this._inflate.write(z1n),this._inflate.flush(()=>{let o=this._inflate[xB];if(o){this._inflate.close(),this._inflate=null,r(o);return}let s=crt.concat(this._inflate[xw],this._inflate[J0]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[J0]=0,this._inflate[xw]=[],n&&this.params[`${i}_no_context_takeover`]&&this._inflate.reset()),r(null,s)})}_compress(e,n,r){let i=this._isServer?"server":"client";if(!this._deflate){let o=`${i}_max_window_bits`,s=typeof this.params[o]!="number"?nU.Z_DEFAULT_WINDOWBITS:this.params[o];this._deflate=nU.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:s}),this._deflate[J0]=0,this._deflate[xw]=[],this._deflate.on("data",V1n)}this._deflate[wB]=r,this._deflate.write(e),this._deflate.flush(nU.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let o=crt.concat(this._deflate[xw],this._deflate[J0]);n&&(o=new j1n(o.buffer,o.byteOffset,o.length-4)),this._deflate[wB]=null,this._deflate[J0]=0,this._deflate[xw]=[],n&&this.params[`${i}_no_context_takeover`]&&this._deflate.reset(),r(null,o)})}};drt.exports=zAe;function V1n(t){this[xw].push(t),this[J0]+=t.length}function lrt(t){if(this[J0]+=t.length,this[fV]._maxPayload<1||this[J0]<=this[fV]._maxPayload){this[xw].push(t);return}this[xB]=new RangeError("Max payload size exceeded"),this[xB].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[xB][urt]=1009,this.removeListener("data",lrt),this.reset()}function K1n(t){if(this[fV]._inflate=null,this[xB]){this[wB](this[xB]);return}t[urt]=1007,this[wB](t)}});var CB=Q((QIi,gV)=>{"use strict";var{isUtf8:prt}=K("buffer"),{hasBlob:Y1n}=Y0(),J1n=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function X1n(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function VAe(t){let e=t.length,n=0;for(;n<e;)if((t[n]&128)===0)n++;else if((t[n]&224)===192){if(n+1===e||(t[n+1]&192)!==128||(t[n]&254)===192)return!1;n+=2}else if((t[n]&240)===224){if(n+2>=e||(t[n+1]&192)!==128||(t[n+2]&192)!==128||t[n]===224&&(t[n+1]&224)===128||t[n]===237&&(t[n+1]&224)===160)return!1;n+=3}else if((t[n]&248)===240){if(n+3>=e||(t[n+1]&192)!==128||(t[n+2]&192)!==128||(t[n+3]&192)!==128||t[n]===240&&(t[n+1]&240)===128||t[n]===244&&t[n+1]>143||t[n]>244)return!1;n+=4}else return!1;return!0}function Z1n(t){return Y1n&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}gV.exports={isBlob:Z1n,isValidStatusCode:X1n,isValidUTF8:VAe,tokenChars:J1n};if(prt)gV.exports.isValidUTF8=function(t){return t.length<24?VAe(t):prt(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=K("utf-8-validate");gV.exports.isValidUTF8=function(e){return e.length<32?VAe(e):t(e)}}catch{}});var ZAe=Q((OIi,Ert)=>{"use strict";var{Writable:eDn}=K("stream"),hrt=bB(),{BINARY_TYPES:tDn,EMPTY_BUFFER:mrt,kStatusCode:nDn,kWebSocket:rDn}=Y0(),{concat:KAe,toArrayBuffer:iDn,unmask:oDn}=tU(),{isValidStatusCode:sDn,isValidUTF8:frt}=CB(),AV=Buffer[Symbol.species],ph=0,grt=1,Art=2,yrt=3,YAe=4,JAe=5,yV=6,XAe=class extends eDn{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||tDn[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxBufferedChunks=e.maxBufferedChunks|0,this._maxFragments=e.maxFragments|0,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[rDn]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=ph}_write(e,n,r){if(this._opcode===8&&this._state==ph)return r();if(this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks){r(this.createError(RangeError,"Too many buffered chunks",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS"));return}this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(r)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let r=this._buffers[0];return this._buffers[0]=new AV(r.buffer,r.byteOffset+e,r.length-e),new AV(r.buffer,r.byteOffset,e)}let n=Buffer.allocUnsafe(e);do{let r=this._buffers[0],i=n.length-e;e>=r.length?n.set(this._buffers.shift(),i):(n.set(new Uint8Array(r.buffer,r.byteOffset,e),i),this._buffers[0]=new AV(r.buffer,r.byteOffset+e,r.length-e)),e-=r.length}while(e>0);return n}startLoop(e){this._loop=!0;do switch(this._state){case ph:this.getInfo(e);break;case grt:this.getPayloadLength16(e);break;case Art:this.getPayloadLength64(e);break;case yrt:this.getMask();break;case YAe:this.getData(e);break;case JAe:case yV:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let n=this.consume(2);if((n[0]&48)!==0){let i=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(i);return}let r=(n[0]&64)===64;if(r&&!this._extensions[hrt.extensionName]){let i=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(i);return}if(this._fin=(n[0]&128)===128,this._opcode=n[0]&15,this._payloadLength=n[1]&127,this._opcode===0){if(r){let i=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(i);return}if(!this._fragmented){let i=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(i);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let i=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(i);return}this._compressed=r}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let i=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(i);return}if(r){let i=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(i);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let i=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(i);return}}else{let i=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(i);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(n[1]&128)===128,this._isServer){if(!this._masked){let i=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(i);return}}else if(this._masked){let i=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(i);return}this._payloadLength===126?this._state=grt:this._payloadLength===127?this._state=Art:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let n=this.consume(8),r=n.readUInt32BE(0);if(r>Math.pow(2,21)-1){let i=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(i);return}this._payloadLength=r*Math.pow(2,32)+n.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let n=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(n);return}this._masked?this._state=yrt:this._state=YAe}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=YAe}getData(e){let n=mrt;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}n=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&oDn(n,this._mask)}if(this._opcode>7){this.controlMessage(n,e);return}if(this._compressed){this._state=JAe,this.decompress(n,e);return}if(n.length){if(this._maxFragments>0&&this._fragments.length>=this._maxFragments){let r=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");e(r);return}this._messageLength=this._totalPayloadLength,this._fragments.push(n)}this.dataMessage(e)}decompress(e,n){this._extensions[hrt.extensionName].decompress(e,this._fin,(i,o)=>{if(i)return n(i);if(o.length){if(this._messageLength+=o.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let s=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");n(s);return}if(this._maxFragments>0&&this._fragments.length>=this._maxFragments){let s=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");n(s);return}this._fragments.push(o)}this.dataMessage(n),this._state===ph&&this.startLoop(n)})}dataMessage(e){if(!this._fin){this._state=ph;return}let n=this._messageLength,r=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let i;this._binaryType==="nodebuffer"?i=KAe(r,n):this._binaryType==="arraybuffer"?i=iDn(KAe(r,n)):this._binaryType==="blob"?i=new Blob(r):i=r,this._allowSynchronousEvents?(this.emit("message",i,!0),this._state=ph):(this._state=yV,setImmediate(()=>{this.emit("message",i,!0),this._state=ph,this.startLoop(e)}))}else{let i=KAe(r,n);if(!this._skipUTF8Validation&&!frt(i)){let o=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(o);return}this._state===JAe||this._allowSynchronousEvents?(this.emit("message",i,!1),this._state=ph):(this._state=yV,setImmediate(()=>{this.emit("message",i,!1),this._state=ph,this.startLoop(e)}))}}controlMessage(e,n){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,mrt),this.end();else{let r=e.readUInt16BE(0);if(!sDn(r)){let o=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");n(o);return}let i=new AV(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!frt(i)){let o=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");n(o);return}this._loop=!1,this.emit("conclude",r,i),this.end()}this._state=ph;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=ph):(this._state=yV,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=ph,this.startLoop(n)}))}createError(e,n,r,i,o){this._loop=!1,this._errored=!0;let s=new e(r?`Invalid WebSocket frame: ${n}`:n);return Error.captureStackTrace(s,this.createError),s.code=o,s[nDn]=i,s}};Ert.exports=XAe});var n0e=Q((UIi,brt)=>{"use strict";var{Duplex:FIi}=K("stream"),{randomFillSync:aDn}=K("crypto"),{types:{isUint8Array:cDn}}=K("util"),wrt=bB(),{EMPTY_BUFFER:uDn,kWebSocket:lDn,NOOP:dDn}=Y0(),{isBlob:IB,isValidStatusCode:pDn}=CB(),{mask:xrt,toBuffer:ov}=tU(),hh=Symbol("kByteLength"),hDn=Buffer.alloc(4),EV=8*1024,sv,vB=EV,Xm=0,mDn=1,fDn=2,e0e=class t{constructor(e,n,r){this._extensions=n||{},r&&(this._generateMask=r,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=Xm,this.onerror=dDn,this[lDn]=void 0}static frame(e,n){let r,i=!1,o=2,s=!1;n.mask&&(r=n.maskBuffer||hDn,n.generateMask?n.generateMask(r):(vB===EV&&(sv===void 0&&(sv=Buffer.alloc(EV)),aDn(sv,0,EV),vB=0),r[0]=sv[vB++],r[1]=sv[vB++],r[2]=sv[vB++],r[3]=sv[vB++]),s=(r[0]|r[1]|r[2]|r[3])===0,o=6);let a;typeof e=="string"?(!n.mask||s)&&n[hh]!==void 0?a=n[hh]:(e=Buffer.from(e),a=e.length):(a=e.length,i=n.mask&&n.readOnly&&!s);let c=a;a>=65536?(o+=8,c=127):a>125&&(o+=2,c=126);let u=Buffer.allocUnsafe(i?a+o:o);return u[0]=n.fin?n.opcode|128:n.opcode,n.rsv1&&(u[0]|=64),u[1]=c,c===126?u.writeUInt16BE(a,2):c===127&&(u[2]=u[3]=0,u.writeUIntBE(a,4,6)),n.mask?(u[1]|=128,u[o-4]=r[0],u[o-3]=r[1],u[o-2]=r[2],u[o-1]=r[3],s?[u,e]:i?(xrt(e,r,u,o,a),[u]):(xrt(e,r,e,0,a),[u,e])):[u,e]}close(e,n,r,i){let o;if(e===void 0)o=uDn;else{if(typeof e!="number"||!pDn(e))throw new TypeError("First argument must be a valid error code number");if(n===void 0||!n.length)o=Buffer.allocUnsafe(2),o.writeUInt16BE(e,0);else{let a=Buffer.byteLength(n);if(a>123)throw new RangeError("The message must not be greater than 123 bytes");if(o=Buffer.allocUnsafe(2+a),o.writeUInt16BE(e,0),typeof n=="string")o.write(n,2);else if(cDn(n))o.set(n,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let s={[hh]:o.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==Xm?this.enqueue([this.dispatch,o,!1,s,i]):this.sendFrame(t.frame(o,s),i)}ping(e,n,r){let i,o;if(typeof e=="string"?(i=Buffer.byteLength(e),o=!1):IB(e)?(i=e.size,o=!1):(e=ov(e),i=e.length,o=ov.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");let s={[hh]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:o,rsv1:!1};IB(e)?this._state!==Xm?this.enqueue([this.getBlobData,e,!1,s,r]):this.getBlobData(e,!1,s,r):this._state!==Xm?this.enqueue([this.dispatch,e,!1,s,r]):this.sendFrame(t.frame(e,s),r)}pong(e,n,r){let i,o;if(typeof e=="string"?(i=Buffer.byteLength(e),o=!1):IB(e)?(i=e.size,o=!1):(e=ov(e),i=e.length,o=ov.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");let s={[hh]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:o,rsv1:!1};IB(e)?this._state!==Xm?this.enqueue([this.getBlobData,e,!1,s,r]):this.getBlobData(e,!1,s,r):this._state!==Xm?this.enqueue([this.dispatch,e,!1,s,r]):this.sendFrame(t.frame(e,s),r)}send(e,n,r){let i=this._extensions[wrt.extensionName],o=n.binary?2:1,s=n.compress,a,c;typeof e=="string"?(a=Buffer.byteLength(e),c=!1):IB(e)?(a=e.size,c=!1):(e=ov(e),a=e.length,c=ov.readOnly),this._firstFragment?(this._firstFragment=!1,s&&i&&i.params[i._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(s=a>=i._threshold),this._compress=s):(s=!1,o=0),n.fin&&(this._firstFragment=!0);let u={[hh]:a,fin:n.fin,generateMask:this._generateMask,mask:n.mask,maskBuffer:this._maskBuffer,opcode:o,readOnly:c,rsv1:s};IB(e)?this._state!==Xm?this.enqueue([this.getBlobData,e,this._compress,u,r]):this.getBlobData(e,this._compress,u,r):this._state!==Xm?this.enqueue([this.dispatch,e,this._compress,u,r]):this.dispatch(e,this._compress,u,r)}getBlobData(e,n,r,i){this._bufferedBytes+=r[hh],this._state=fDn,e.arrayBuffer().then(o=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(t0e,this,a,i);return}this._bufferedBytes-=r[hh];let s=ov(o);n?this.dispatch(s,n,r,i):(this._state=Xm,this.sendFrame(t.frame(s,r),i),this.dequeue())}).catch(o=>{process.nextTick(gDn,this,o,i)})}dispatch(e,n,r,i){if(!n){this.sendFrame(t.frame(e,r),i);return}let o=this._extensions[wrt.extensionName];this._bufferedBytes+=r[hh],this._state=mDn,o.compress(e,r.fin,(s,a)=>{if(this._socket.destroyed){let c=new Error("The socket was closed while data was being compressed");t0e(this,c,i);return}this._bufferedBytes-=r[hh],this._state=Xm,r.readOnly=!1,this.sendFrame(t.frame(a,r),i),this.dequeue()})}dequeue(){for(;this._state===Xm&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][hh],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][hh],this._queue.push(e)}sendFrame(e,n){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],n),this._socket.uncork()):this._socket.write(e[0],n)}};brt.exports=e0e;function t0e(t,e,n){typeof n=="function"&&n(e);for(let r=0;r<t._queue.length;r++){let i=t._queue[r],o=i[i.length-1];typeof o=="function"&&o(e)}}function gDn(t,e,n){t0e(t,e,n),t.onerror(e)}});var Brt=Q(($Ii,Rrt)=>{"use strict";var{kForOnEventAttribute:rU,kListener:r0e}=Y0(),Crt=Symbol("kCode"),Irt=Symbol("kData"),vrt=Symbol("kError"),Srt=Symbol("kMessage"),_rt=Symbol("kReason"),SB=Symbol("kTarget"),krt=Symbol("kType"),Trt=Symbol("kWasClean"),X0=class{constructor(e){this[SB]=null,this[krt]=e}get target(){return this[SB]}get type(){return this[krt]}};Object.defineProperty(X0.prototype,"target",{enumerable:!0});Object.defineProperty(X0.prototype,"type",{enumerable:!0});var av=class extends X0{constructor(e,n={}){super(e),this[Crt]=n.code===void 0?0:n.code,this[_rt]=n.reason===void 0?"":n.reason,this[Trt]=n.wasClean===void 0?!1:n.wasClean}get code(){return this[Crt]}get reason(){return this[_rt]}get wasClean(){return this[Trt]}};Object.defineProperty(av.prototype,"code",{enumerable:!0});Object.defineProperty(av.prototype,"reason",{enumerable:!0});Object.defineProperty(av.prototype,"wasClean",{enumerable:!0});var _B=class extends X0{constructor(e,n={}){super(e),this[vrt]=n.error===void 0?null:n.error,this[Srt]=n.message===void 0?"":n.message}get error(){return this[vrt]}get message(){return this[Srt]}};Object.defineProperty(_B.prototype,"error",{enumerable:!0});Object.defineProperty(_B.prototype,"message",{enumerable:!0});var iU=class extends X0{constructor(e,n={}){super(e),this[Irt]=n.data===void 0?null:n.data}get data(){return this[Irt]}};Object.defineProperty(iU.prototype,"data",{enumerable:!0});var ADn={addEventListener(t,e,n={}){for(let i of this.listeners(t))if(!n[rU]&&i[r0e]===e&&!i[rU])return;let r;if(t==="message")r=function(o,s){let a=new iU("message",{data:s?o:o.toString()});a[SB]=this,wV(e,this,a)};else if(t==="close")r=function(o,s){let a=new av("close",{code:o,reason:s.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[SB]=this,wV(e,this,a)};else if(t==="error")r=function(o){let s=new _B("error",{error:o,message:o.message});s[SB]=this,wV(e,this,s)};else if(t==="open")r=function(){let o=new X0("open");o[SB]=this,wV(e,this,o)};else return;r[rU]=!!n[rU],r[r0e]=e,n.once?this.once(t,r):this.on(t,r)},removeEventListener(t,e){for(let n of this.listeners(t))if(n[r0e]===e&&!n[rU]){this.removeListener(t,n);break}}};Rrt.exports={CloseEvent:av,ErrorEvent:_B,Event:X0,EventTarget:ADn,MessageEvent:iU};function wV(t,e,n){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,n):t.call(e,n)}});var xV=Q((WIi,Drt)=>{"use strict";var{tokenChars:oU}=CB();function Dg(t,e,n){t[e]===void 0?t[e]=[n]:t[e].push(n)}function yDn(t){let e=Object.create(null),n=Object.create(null),r=!1,i=!1,o=!1,s,a,c=-1,u=-1,l=-1,d=0;for(;d<t.length;d++)if(u=t.charCodeAt(d),s===void 0)if(l===-1&&oU[u]===1)c===-1&&(c=d);else if(d!==0&&(u===32||u===9))l===-1&&c!==-1&&(l=d);else if(u===59||u===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${d}`);l===-1&&(l=d);let h=t.slice(c,l);u===44?(Dg(e,h,n),n=Object.create(null)):s=h,c=l=-1}else throw new SyntaxError(`Unexpected character at index ${d}`);else if(a===void 0)if(l===-1&&oU[u]===1)c===-1&&(c=d);else if(u===32||u===9)l===-1&&c!==-1&&(l=d);else if(u===59||u===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${d}`);l===-1&&(l=d),Dg(n,t.slice(c,l),!0),u===44&&(Dg(e,s,n),n=Object.create(null),s=void 0),c=l=-1}else if(u===61&&c!==-1&&l===-1)a=t.slice(c,d),c=l=-1;else throw new SyntaxError(`Unexpected character at index ${d}`);else if(i){if(oU[u]!==1)throw new SyntaxError(`Unexpected character at index ${d}`);c===-1?c=d:r||(r=!0),i=!1}else if(o)if(oU[u]===1)c===-1&&(c=d);else if(u===34&&c!==-1)o=!1,l=d;else if(u===92)i=!0;else throw new SyntaxError(`Unexpected character at index ${d}`);else if(u===34&&t.charCodeAt(d-1)===61)o=!0;else if(l===-1&&oU[u]===1)c===-1&&(c=d);else if(c!==-1&&(u===32||u===9))l===-1&&(l=d);else if(u===59||u===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${d}`);l===-1&&(l=d);let h=t.slice(c,l);r&&(h=h.replace(/\\/g,""),r=!1),Dg(n,a,h),u===44&&(Dg(e,s,n),n=Object.create(null),s=void 0),a=void 0,c=l=-1}else throw new SyntaxError(`Unexpected character at index ${d}`);if(c===-1||o||u===32||u===9)throw new SyntaxError("Unexpected end of input");l===-1&&(l=d);let p=t.slice(c,l);return s===void 0?Dg(e,p,n):(a===void 0?Dg(n,p,!0):r?Dg(n,a,p.replace(/\\/g,"")):Dg(n,a,p),Dg(e,s,n)),e}function EDn(t){return Object.keys(t).map(e=>{let n=t[e];return Array.isArray(n)||(n=[n]),n.map(r=>[e].concat(Object.keys(r).map(i=>{let o=r[i];return Array.isArray(o)||(o=[o]),o.map(s=>s===!0?i:`${i}=${s}`).join("; ")})).join("; ")).join(", ")}).join(", ")}Drt.exports={format:EDn,parse:yDn}});var vV=Q((qIi,Grt)=>{"use strict";var wDn=K("events"),xDn=K("https"),bDn=K("http"),Nrt=K("net"),CDn=K("tls"),{randomBytes:IDn,createHash:vDn}=K("crypto"),{Duplex:HIi,Readable:GIi}=K("stream"),{URL:i0e}=K("url"),bw=bB(),SDn=ZAe(),_Dn=n0e(),{isBlob:kDn}=CB(),{BINARY_TYPES:Mrt,CLOSE_TIMEOUT:TDn,EMPTY_BUFFER:bV,GUID:RDn,kForOnEventAttribute:o0e,kListener:BDn,kStatusCode:DDn,kWebSocket:Za,NOOP:Lrt}=Y0(),{EventTarget:{addEventListener:MDn,removeEventListener:PDn}}=Brt(),{format:NDn,parse:LDn}=xV(),{toBuffer:QDn}=tU(),Qrt=Symbol("kAborted"),s0e=[8,13],Z0=["CONNECTING","OPEN","CLOSING","CLOSED"],ODn=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,Go=class t extends wDn{constructor(e,n,r){super(),this._binaryType=Mrt[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=bV,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=t.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,n===void 0?n=[]:Array.isArray(n)||(typeof n=="object"&&n!==null?(r=n,n=[]):n=[n]),Ort(this,e,n,r)):(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Mrt.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,n,r){let i=new SDn({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:r.maxBufferedChunks,maxFragments:r.maxFragments,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),o=new _Dn(e,this._extensions,r.generateMask);this._receiver=i,this._sender=o,this._socket=e,i[Za]=this,o[Za]=this,e[Za]=this,i.on("conclude",$Dn),i.on("drain",WDn),i.on("error",HDn),i.on("message",GDn),i.on("ping",qDn),i.on("pong",jDn),o.onerror=zDn,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),n.length>0&&e.unshift(n),e.on("close",$rt),e.on("data",IV),e.on("end",Wrt),e.on("error",Hrt),this._readyState=t.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[bw.extensionName]&&this._extensions[bw.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,n){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){ep(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===t.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=t.CLOSING,this._sender.close(e,n,!this._isServer,r=>{r||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),Urt(this)}}pause(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,n,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(r=e,e=n=void 0):typeof n=="function"&&(r=n,n=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){a0e(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(e||bV,n,r)}pong(e,n,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(r=e,e=n=void 0):typeof n=="function"&&(r=n,n=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){a0e(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(e||bV,n,r)}resume(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,n,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof n=="function"&&(r=n,n={}),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){a0e(this,e,r);return}let i={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[bw.extensionName]||(i.compress=!1),this._sender.send(e||bV,i,r)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){ep(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(Go,"CONNECTING",{enumerable:!0,value:Z0.indexOf("CONNECTING")});Object.defineProperty(Go.prototype,"CONNECTING",{enumerable:!0,value:Z0.indexOf("CONNECTING")});Object.defineProperty(Go,"OPEN",{enumerable:!0,value:Z0.indexOf("OPEN")});Object.defineProperty(Go.prototype,"OPEN",{enumerable:!0,value:Z0.indexOf("OPEN")});Object.defineProperty(Go,"CLOSING",{enumerable:!0,value:Z0.indexOf("CLOSING")});Object.defineProperty(Go.prototype,"CLOSING",{enumerable:!0,value:Z0.indexOf("CLOSING")});Object.defineProperty(Go,"CLOSED",{enumerable:!0,value:Z0.indexOf("CLOSED")});Object.defineProperty(Go.prototype,"CLOSED",{enumerable:!0,value:Z0.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(Go.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(Go.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[o0e])return e[BDn];return null},set(e){for(let n of this.listeners(t))if(n[o0e]){this.removeListener(t,n);break}typeof e=="function"&&this.addEventListener(t,e,{[o0e]:!0})}})});Go.prototype.addEventListener=MDn;Go.prototype.removeEventListener=PDn;Grt.exports=Go;function Ort(t,e,n,r){let i={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:TDn,protocolVersion:s0e[1],maxBufferedChunks:1048576,maxFragments:131072,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...r,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(t._autoPong=i.autoPong,t._closeTimeout=i.closeTimeout,!s0e.includes(i.protocolVersion))throw new RangeError(`Unsupported protocol version: ${i.protocolVersion} (supported versions: ${s0e.join(", ")})`);let o;if(e instanceof i0e)o=e;else try{o=new i0e(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}o.protocol==="http:"?o.protocol="ws:":o.protocol==="https:"&&(o.protocol="wss:"),t._url=o.href;let s=o.protocol==="wss:",a=o.protocol==="ws+unix:",c;if(o.protocol!=="ws:"&&!s&&!a?c=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:a&&!o.pathname?c="The URL's pathname is empty":o.hash&&(c="The URL contains a fragment identifier"),c){let f=new SyntaxError(c);if(t._redirects===0)throw f;CV(t,f);return}let u=s?443:80,l=IDn(16).toString("base64"),d=s?xDn.request:bDn.request,p=new Set,h;if(i.createConnection=i.createConnection||(s?UDn:FDn),i.defaultPort=i.defaultPort||u,i.port=o.port||u,i.host=o.hostname.startsWith("[")?o.hostname.slice(1,-1):o.hostname,i.headers={...i.headers,"Sec-WebSocket-Version":i.protocolVersion,"Sec-WebSocket-Key":l,Connection:"Upgrade",Upgrade:"websocket"},i.path=o.pathname+o.search,i.timeout=i.handshakeTimeout,i.perMessageDeflate&&(h=new bw({...i.perMessageDeflate,isServer:!1,maxPayload:i.maxPayload}),i.headers["Sec-WebSocket-Extensions"]=NDn({[bw.extensionName]:h.offer()})),n.length){for(let f of n){if(typeof f!="string"||!ODn.test(f)||p.has(f))throw new SyntaxError("An invalid or duplicated subprotocol was specified");p.add(f)}i.headers["Sec-WebSocket-Protocol"]=n.join(",")}if(i.origin&&(i.protocolVersion<13?i.headers["Sec-WebSocket-Origin"]=i.origin:i.headers.Origin=i.origin),(o.username||o.password)&&(i.auth=`${o.username}:${o.password}`),a){let f=i.path.split(":");i.socketPath=f[0],i.path=f[1]}let m;if(i.followRedirects){if(t._redirects===0){t._originalIpc=a,t._originalSecure=s,t._originalHostOrSocketPath=a?i.socketPath:o.host;let f=r&&r.headers;if(r={...r,headers:{}},f)for(let[g,A]of Object.entries(f))r.headers[g.toLowerCase()]=A}else if(t.listenerCount("redirect")===0){let f=a?t._originalIpc?i.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:o.host===t._originalHostOrSocketPath;(!f||t._originalSecure&&!s)&&(delete i.headers.authorization,delete i.headers.cookie,f||delete i.headers.host,i.auth=void 0)}i.auth&&!r.headers.authorization&&(r.headers.authorization="Basic "+Buffer.from(i.auth).toString("base64")),m=t._req=d(i),t._redirects&&t.emit("redirect",t.url,m)}else m=t._req=d(i);i.timeout&&m.on("timeout",()=>{ep(t,m,"Opening handshake has timed out")}),m.on("error",f=>{m===null||m[Qrt]||(m=t._req=null,CV(t,f))}),m.on("response",f=>{let g=f.headers.location,A=f.statusCode;if(g&&i.followRedirects&&A>=300&&A<400){if(++t._redirects>i.maxRedirects){ep(t,m,"Maximum redirects exceeded");return}m.abort();let x;try{x=new i0e(g,e)}catch{let v=new SyntaxError(`Invalid URL: ${g}`);CV(t,v);return}Ort(t,x,n,r)}else t.emit("unexpected-response",m,f)||ep(t,m,`Unexpected server response: ${f.statusCode}`)}),m.on("upgrade",(f,g,A)=>{if(t.emit("upgrade",f),t.readyState!==Go.CONNECTING)return;m=t._req=null;let x=f.headers.upgrade;if(x===void 0||x.toLowerCase()!=="websocket"){ep(t,g,"Invalid Upgrade header");return}let b=vDn("sha1").update(l+RDn).digest("base64");if(f.headers["sec-websocket-accept"]!==b){ep(t,g,"Invalid Sec-WebSocket-Accept header");return}let v=f.headers["sec-websocket-protocol"],S;if(v!==void 0?p.size?p.has(v)||(S="Server sent an invalid subprotocol"):S="Server sent a subprotocol but none was requested":p.size&&(S="Server sent no subprotocol"),S){ep(t,g,S);return}v&&(t._protocol=v);let _=f.headers["sec-websocket-extensions"];if(_!==void 0){if(!h){ep(t,g,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let T;try{T=LDn(_)}catch{ep(t,g,"Invalid Sec-WebSocket-Extensions header");return}let B=Object.keys(T);if(B.length!==1||B[0]!==bw.extensionName){ep(t,g,"Server indicated an extension that was not requested");return}try{h.accept(T[bw.extensionName])}catch{ep(t,g,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[bw.extensionName]=h}t.setSocket(g,A,{allowSynchronousEvents:i.allowSynchronousEvents,generateMask:i.generateMask,maxBufferedChunks:i.maxBufferedChunks,maxFragments:i.maxFragments,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation})}),i.finishRequest?i.finishRequest(m,t):m.end()}function CV(t,e){t._readyState=Go.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function FDn(t){return t.path=t.socketPath,Nrt.connect(t)}function UDn(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=Nrt.isIP(t.host)?"":t.host),CDn.connect(t)}function ep(t,e,n){t._readyState=Go.CLOSING;let r=new Error(n);Error.captureStackTrace(r,ep),e.setHeader?(e[Qrt]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(CV,t,r)):(e.destroy(r),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function a0e(t,e,n){if(e){let r=kDn(e)?e.size:QDn(e).length;t._socket?t._sender._bufferedBytes+=r:t._bufferedAmount+=r}if(n){let r=new Error(`WebSocket is not open: readyState ${t.readyState} (${Z0[t.readyState]})`);process.nextTick(n,r)}}function $Dn(t,e){let n=this[Za];n._closeFrameReceived=!0,n._closeMessage=e,n._closeCode=t,n._socket[Za]!==void 0&&(n._socket.removeListener("data",IV),process.nextTick(Frt,n._socket),t===1005?n.close():n.close(t,e))}function WDn(){let t=this[Za];t.isPaused||t._socket.resume()}function HDn(t){let e=this[Za];e._socket[Za]!==void 0&&(e._socket.removeListener("data",IV),process.nextTick(Frt,e._socket),e.close(t[DDn])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function Prt(){this[Za].emitClose()}function GDn(t,e){this[Za].emit("message",t,e)}function qDn(t){let e=this[Za];e._autoPong&&e.pong(t,!this._isServer,Lrt),e.emit("ping",t)}function jDn(t){this[Za].emit("pong",t)}function Frt(t){t.resume()}function zDn(t){let e=this[Za];e.readyState!==Go.CLOSED&&(e.readyState===Go.OPEN&&(e._readyState=Go.CLOSING,Urt(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function Urt(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function $rt(){let t=this[Za];if(this.removeListener("close",$rt),this.removeListener("data",IV),this.removeListener("end",Wrt),t._readyState=Go.CLOSING,!this._readableState.endEmitted&&!t._closeFrameReceived&&!t._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);t._receiver.write(e)}t._receiver.end(),this[Za]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",Prt),t._receiver.on("finish",Prt))}function IV(t){this[Za]._receiver.write(t)||this.pause()}function Wrt(){let t=this[Za];t._readyState=Go.CLOSING,t._receiver.end(),this.end()}function Hrt(){let t=this[Za];this.removeListener("error",Hrt),this.on("error",Lrt),t&&(t._readyState=Go.CLOSING,this.destroy())}});var Vrt=Q((zIi,zrt)=>{"use strict";var jIi=vV(),{Duplex:VDn}=K("stream");function qrt(t){t.emit("close")}function KDn(){!this.destroyed&&this._writableState.finished&&this.destroy()}function jrt(t){this.removeListener("error",jrt),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function YDn(t,e){let n=!0,r=new VDn({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return t.on("message",function(o,s){let a=!s&&r._readableState.objectMode?o.toString():o;r.push(a)||t.pause()}),t.once("error",function(o){r.destroyed||(n=!1,r.destroy(o))}),t.once("close",function(){r.destroyed||r.push(null)}),r._destroy=function(i,o){if(t.readyState===t.CLOSED){o(i),process.nextTick(qrt,r);return}let s=!1;t.once("error",function(c){s=!0,o(c)}),t.once("close",function(){s||o(i),process.nextTick(qrt,r)}),n&&t.terminate()},r._final=function(i){if(t.readyState===t.CONNECTING){t.once("open",function(){r._final(i)});return}t._socket!==null&&(t._socket._writableState.finished?(i(),r._readableState.endEmitted&&r.destroy()):(t._socket.once("finish",function(){i()}),t.close()))},r._read=function(){t.isPaused&&t.resume()},r._write=function(i,o,s){if(t.readyState===t.CONNECTING){t.once("open",function(){r._write(i,o,s)});return}t.send(i,s)},r.on("end",KDn),r.on("error",jrt),r}zrt.exports=YDn});var c0e=Q((VIi,Krt)=>{"use strict";var{tokenChars:JDn}=CB();function XDn(t){let e=new Set,n=-1,r=-1,i=0;for(i;i<t.length;i++){let s=t.charCodeAt(i);if(r===-1&&JDn[s]===1)n===-1&&(n=i);else if(i!==0&&(s===32||s===9))r===-1&&n!==-1&&(r=i);else if(s===44){if(n===-1)throw new SyntaxError(`Unexpected character at index ${i}`);r===-1&&(r=i);let a=t.slice(n,r);if(e.has(a))throw new SyntaxError(`The "${a}" subprotocol is duplicated`);e.add(a),n=r=-1}else throw new SyntaxError(`Unexpected character at index ${i}`)}if(n===-1||r!==-1)throw new SyntaxError("Unexpected end of input");let o=t.slice(n,i);if(e.has(o))throw new SyntaxError(`The "${o}" subprotocol is duplicated`);return e.add(o),e}Krt.exports={parse:XDn}});var nit=Q((YIi,tit)=>{"use strict";var ZDn=K("events"),SV=K("http"),{Duplex:KIi}=K("stream"),{createHash:eMn}=K("crypto"),Yrt=xV(),cv=bB(),tMn=c0e(),nMn=vV(),{CLOSE_TIMEOUT:rMn,GUID:iMn,kWebSocket:oMn}=Y0(),sMn=/^[+/0-9A-Za-z]{22}==$/,Jrt=0,Xrt=1,eit=2,u0e=class extends ZDn{constructor(e,n){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxBufferedChunks:1024*1024,maxFragments:128*1024,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:rMn,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:nMn,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(e.port!=null?(this._server=SV.createServer((r,i)=>{let o=SV.STATUS_CODES[426];i.writeHead(426,{"Content-Length":o.length,"Content-Type":"text/plain"}),i.end(o)}),this._server.listen(e.port,e.host,e.backlog,n)):e.server&&(this._server=e.server),this._server){let r=this.emit.bind(this,"connection");this._removeListeners=aMn(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(i,o,s)=>{this.handleUpgrade(i,o,s,r)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=Jrt}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(this._state===eit){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(sU,this);return}if(e&&this.once("close",e),this._state!==Xrt)if(this._state=Xrt,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(sU,this):process.nextTick(sU,this);else{let n=this._server;this._removeListeners(),this._removeListeners=this._server=null,n.close(()=>{sU(this)})}}shouldHandle(e){if(this.options.path){let n=e.url.indexOf("?");if((n!==-1?e.url.slice(0,n):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,n,r,i){n.on("error",Zrt);let o=e.headers["sec-websocket-key"],s=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){uv(this,e,n,405,"Invalid HTTP method");return}if(s===void 0||s.toLowerCase()!=="websocket"){uv(this,e,n,400,"Invalid Upgrade header");return}if(o===void 0||!sMn.test(o)){uv(this,e,n,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){uv(this,e,n,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){aU(n,400);return}let c=e.headers["sec-websocket-protocol"],u=new Set;if(c!==void 0)try{u=tMn.parse(c)}catch{uv(this,e,n,400,"Invalid Sec-WebSocket-Protocol header");return}let l=e.headers["sec-websocket-extensions"],d={};if(this.options.perMessageDeflate&&l!==void 0){let p=new cv({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let h=Yrt.parse(l);h[cv.extensionName]&&(p.accept(h[cv.extensionName]),d[cv.extensionName]=p)}catch{uv(this,e,n,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let p={origin:e.headers[`${a===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(p,(h,m,f,g)=>{if(!h)return aU(n,m||401,f,g);this.completeUpgrade(d,o,u,e,n,r,i)});return}if(!this.options.verifyClient(p))return aU(n,401)}this.completeUpgrade(d,o,u,e,n,r,i)}completeUpgrade(e,n,r,i,o,s,a){if(!o.readable||!o.writable)return o.destroy();if(o[oMn])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Jrt)return aU(o,503);let u=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${eMn("sha1").update(n+iMn).digest("base64")}`],l=new this.options.WebSocket(null,void 0,this.options);if(r.size){let d=this.options.handleProtocols?this.options.handleProtocols(r,i):r.values().next().value;d&&(u.push(`Sec-WebSocket-Protocol: ${d}`),l._protocol=d)}if(e[cv.extensionName]){let d=e[cv.extensionName].params,p=Yrt.format({[cv.extensionName]:[d]});u.push(`Sec-WebSocket-Extensions: ${p}`),l._extensions=e}this.emit("headers",u,i),o.write(u.concat(`\r
101
101
  `).join(`\r
102
102
  `)),o.removeListener("error",Zrt),l.setSocket(o,s,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxBufferedChunks:this.options.maxBufferedChunks,maxFragments:this.options.maxFragments,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(l),l.on("close",()=>{this.clients.delete(l),this._shouldEmitClose&&!this.clients.size&&process.nextTick(sU,this)})),a(l,i)}};tit.exports=u0e;function aMn(t,e){for(let n of Object.keys(e))t.on(n,e[n]);return function(){for(let r of Object.keys(e))t.removeListener(r,e[r])}}function sU(t){t._state=eit,t.emit("close")}function Zrt(){this.destroy()}function aU(t,e,n,r){n=n||SV.STATUS_CODES[e],r={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(n),...r},t.once("finish",t.destroy),t.end(`HTTP/1.1 ${e} ${SV.STATUS_CODES[e]}\r
103
103
  `+Object.keys(r).map(i=>`${i}: ${r[i]}`).join(`\r