@north-light/cli 0.3.782 → 0.3.784

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.
Files changed (60) hide show
  1. package/dist/api/contract.d.ts +1 -1
  2. package/dist/api/contract.js +1 -1
  3. package/dist/api/dto/charges.d.ts +3 -3
  4. package/dist/api/dto/charges.js +1 -1
  5. package/dist/builtin-memory/crouter-sdk/release-notes.md +6 -0
  6. package/dist/builtin-memory/internal/marketplaces.md +1 -1
  7. package/dist/builtin-memory/internal/storage-tiers.md +1 -1
  8. package/dist/builtin-pi-packages/pi-crtr-extensions/README.md +3 -3
  9. package/dist/cli.js +2 -8
  10. package/dist/clients/attach/viewer.js +1 -1
  11. package/dist/commands/pkg/account-installs.d.ts +10 -0
  12. package/dist/commands/pkg/account-installs.js +1 -0
  13. package/dist/commands/pkg/plugin-manage.d.ts +4 -0
  14. package/dist/commands/pkg/plugin-manage.js +1 -1
  15. package/dist/commands/sys/doctor.js +1 -1
  16. package/dist/commands/sys/provider-login.js +5 -5
  17. package/dist/commands/sys/setup-core.d.ts +1 -52
  18. package/dist/commands/sys/setup-core.js +6 -6
  19. package/dist/commands/sys/setup-wizard.d.ts +4 -9
  20. package/dist/commands/sys/setup-wizard.js +3 -1
  21. package/dist/commands/sys/setup.js +1 -1
  22. package/dist/commands/sys/signin.js +7 -3
  23. package/dist/core/grants/shadow.js +1 -1
  24. package/dist/core/grants/sync.js +1 -1
  25. package/dist/core/ledger/check.d.ts +6 -2
  26. package/dist/core/ledger/check.js +1 -1
  27. package/dist/core/llm/run.js +2 -2
  28. package/dist/core/runtime/first-run-offer.d.ts +2 -6
  29. package/dist/core/runtime/first-run-offer.js +2 -10
  30. package/dist/core/runtime/front-door.js +8 -9
  31. package/dist/core/runtime/package-health.d.ts +1 -1
  32. package/dist/core/runtime/package-health.js +5 -4
  33. package/dist/core/runtime/provider-credential-gate.d.ts +1 -1
  34. package/dist/core/runtime/provider-credential-gate.js +1 -1
  35. package/dist/core/runtime/runner/machine/executor.d.ts +3 -0
  36. package/dist/core/runtime/runner/machine/executor.js +2 -1
  37. package/dist/core/runtime/start-refusal-notice.d.ts +5 -0
  38. package/dist/core/runtime/start-refusal-notice.js +1 -0
  39. package/dist/core/scoped-state/seed-terminal-defaults.d.ts +2 -0
  40. package/dist/core/scoped-state/seed-terminal-defaults.js +1 -0
  41. package/dist/daemon/cron-run.js +2 -2
  42. package/dist/daemon/fleet.js +5 -5
  43. package/dist/daemon/machine-daemon.js +1 -1
  44. package/dist/daemon/reconcilers/node-lifecycle/freeze-lane.js +1 -1
  45. package/docs/cli/first-session.md +2 -2
  46. package/docs/cli/official-marketplace.md +1 -1
  47. package/docs/sdk/release-notes.md +6 -0
  48. package/package.json +3 -3
  49. package/packages/crouter-api/dist/api/contract.js +1 -1
  50. package/packages/crouter-api/dist/api/dto/charges.js +1 -1
  51. package/packages/crouter-api/package.json +1 -1
  52. package/packages/crouter-identity/package.json +1 -1
  53. package/packages/crouter-plugin/package.json +3 -3
  54. package/runtime.lock.json +14 -14
  55. package/dist/commands/sys/panels/plugin-env-panel.d.ts +0 -19
  56. package/dist/commands/sys/panels/plugin-env-panel.js +0 -2
  57. package/dist/commands/sys/panels/plugins-panel.d.ts +0 -16
  58. package/dist/commands/sys/panels/plugins-panel.js +0 -1
  59. package/dist/core/runtime/front-door-login.d.ts +0 -2
  60. package/dist/core/runtime/front-door-login.js +0 -1
@@ -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.`))}Tet.exports=sB;sB.parse=sB;sB.toClientConfig=ket;sB.parseIntoClientConfig=rTn});var wge=L((Oxi,Met)=>{"use strict";var iTn=Y("dns"),Det=FF(),Bet=Ret().parse,ru=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||Det[t])},oTn=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 Det.ssl},aB=function(t){return"'"+(""+t).replace(/\\/g,"\\\\").replace(/'/g,"\\'")+"'"},Jd=function(t,e,n){let r=e[n];r!=null&&t.push(n+"="+aB(r))},Ege=class{constructor(e){if(e=typeof e=="string"?Bet(e):e||{},e.connectionString&&(e=Object.assign({},e,Bet(e.connectionString))),this.user=ru("user",e),this.database=ru("database",e),this.database===void 0&&(this.database=this.user),this.port=parseInt(ru("port",e),10),this.host=ru("host",e),Object.defineProperty(this,"password",{configurable:!0,enumerable:!1,writable:!0,value:ru("password",e)}),this.binary=ru("binary",e),this.options=ru("options",e),this.ssl=typeof e.ssl>"u"?oTn():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=ru("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=ru("client_encoding",e),this.replication=ru("replication",e),this.isDomainSocket=!(this.host||"").indexOf("/"),this.application_name=ru("application_name",e,"PGAPPNAME"),this.fallback_application_name=ru("fallback_application_name",e,!1),this.statement_timeout=ru("statement_timeout",e,!1),this.lock_timeout=ru("lock_timeout",e,!1),this.idle_in_transaction_session_timeout=ru("idle_in_transaction_session_timeout",e,!1),this.query_timeout=ru("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=[];Jd(n,this,"user"),Jd(n,this,"password"),Jd(n,this,"port"),Jd(n,this,"application_name"),Jd(n,this,"fallback_application_name"),Jd(n,this,"connect_timeout"),Jd(n,this,"options");let r=typeof this.ssl=="object"?this.ssl:this.ssl?{sslmode:this.ssl}:{};if(Jd(n,r,"sslmode"),Jd(n,r,"sslca"),Jd(n,r,"sslkey"),Jd(n,r,"sslcert"),Jd(n,r,"sslrootcert"),Jd(n,this,"sslnegotiation"),this.database&&n.push("dbname="+aB(this.database)),this.replication&&n.push("replication="+aB(this.replication)),this.host&&n.push("host="+aB(this.host)),this.isDomainSocket)return e(null,n.join(" "));this.client_encoding&&n.push("client_encoding="+aB(this.client_encoding)),iTn.lookup(this.host,function(i,o){return i?e(i,null):(n.push("hostaddr="+aB(o)),e(null,n.join(" ")))})}};Met.exports=Ege});var bge=L((Lxi,Net)=>{"use strict";var sTn=QF(),Pet=/^([A-Za-z]+)(?: (\d+))?(?: (\d+))?/,xge=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=Pet.exec(e.text):n=Pet.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]=sTn.getTypeParser(i.dataTypeID,i.format||"text")}this._prebuiltEmptyResultObject={...n}}};Net.exports=xge});var Fet=L((Qxi,Qet)=>{"use strict";var{EventEmitter:aTn}=Y("events"),Oet=bge(),Let=VI(),Cge=class extends aTn{constructor(e,n,r){super(),e=Let.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 Oet(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 Oet(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:Let.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){}};Qet.exports=Cge});var Qge=L(Wn=>{"use strict";Object.defineProperty(Wn,"__esModule",{value:!0});Wn.NoticeMessage=Wn.DataRowMessage=Wn.CommandCompleteMessage=Wn.ReadyForQueryMessage=Wn.NotificationResponseMessage=Wn.BackendKeyDataMessage=Wn.AuthenticationMD5Password=Wn.ParameterStatusMessage=Wn.ParameterDescriptionMessage=Wn.RowDescriptionMessage=Wn.Field=Wn.CopyResponse=Wn.CopyDataMessage=Wn.DatabaseError=Wn.copyDone=Wn.emptyQuery=Wn.replicationStart=Wn.portalSuspended=Wn.noData=Wn.closeComplete=Wn.bindComplete=Wn.parseComplete=void 0;Wn.parseComplete={name:"parseComplete",length:5};Wn.bindComplete={name:"bindComplete",length:5};Wn.closeComplete={name:"closeComplete",length:5};Wn.noData={name:"noData",length:5};Wn.portalSuspended={name:"portalSuspended",length:5};Wn.replicationStart={name:"replicationStart",length:4};Wn.emptyQuery={name:"emptyQuery",length:4};Wn.copyDone={name:"copyDone",length:4};var Ige=class extends Error{constructor(e,n,r){super(e),this.length=n,this.name=r}};Wn.DatabaseError=Ige;var vge=class{constructor(e,n){this.length=e,this.chunk=n,this.name="copyData"}};Wn.CopyDataMessage=vge;var Sge=class{constructor(e,n,r,i){this.length=e,this.name=n,this.binary=r,this.columnTypes=new Array(i)}};Wn.CopyResponse=Sge;var _ge=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}};Wn.Field=_ge;var kge=class{constructor(e,n){this.length=e,this.fieldCount=n,this.name="rowDescription",this.fields=new Array(this.fieldCount)}};Wn.RowDescriptionMessage=kge;var Tge=class{constructor(e,n){this.length=e,this.parameterCount=n,this.name="parameterDescription",this.dataTypeIDs=new Array(this.parameterCount)}};Wn.ParameterDescriptionMessage=Tge;var Rge=class{constructor(e,n,r){this.length=e,this.parameterName=n,this.parameterValue=r,this.name="parameterStatus"}};Wn.ParameterStatusMessage=Rge;var Bge=class{constructor(e,n){this.length=e,this.salt=n,this.name="authenticationMD5Password"}};Wn.AuthenticationMD5Password=Bge;var Dge=class{constructor(e,n,r){this.length=e,this.processID=n,this.secretKey=r,this.name="backendKeyData"}};Wn.BackendKeyDataMessage=Dge;var Mge=class{constructor(e,n,r,i){this.length=e,this.processId=n,this.channel=r,this.payload=i,this.name="notification"}};Wn.NotificationResponseMessage=Mge;var Pge=class{constructor(e,n){this.length=e,this.status=n,this.name="readyForQuery"}};Wn.ReadyForQueryMessage=Pge;var Nge=class{constructor(e,n){this.length=e,this.text=n,this.name="commandComplete"}};Wn.CommandCompleteMessage=Nge;var Oge=class{constructor(e,n){this.length=e,this.fields=n,this.name="dataRow",this.fieldCount=n.length}};Wn.DataRowMessage=Oge;var Lge=class{constructor(e,n){this.length=e,this.message=n,this.name="notice"}};Wn.NoticeMessage=Lge});var Uet=L(H6=>{"use strict";Object.defineProperty(H6,"__esModule",{value:!0});H6.Writer=void 0;var Fge=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}};H6.Writer=Fge});var Het=L(q6=>{"use strict";Object.defineProperty(q6,"__esModule",{value:!0});q6.serialize=void 0;var $et=Uet(),ji=new $et.Writer,cTn=t=>{ji.addInt16(3).addInt16(0);for(let r of Object.keys(t))ji.addCString(r).addCString(t[r]);ji.addCString("client_encoding").addCString("UTF8");let e=ji.addCString("").flush(),n=e.length+4;return new $et.Writer().addInt32(n).add(e).flush()},uTn=()=>{let t=Buffer.allocUnsafe(8);return t.writeInt32BE(8,0),t.writeInt32BE(80877103,4),t},lTn=t=>ji.addCString(t).flush(112),dTn=function(t,e){return ji.addCString(t).addInt32PrefixedString(e),ji.flush(112)},pTn=function(t){return ji.addString(t).flush(112)},hTn=t=>ji.addCString(t).flush(81),Wet=[],mTn=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||Wet,r=n.length,i=ji.addCString(e).addCString(t.text).addInt16(r);for(let o=0;o<r;o++)i.addInt32(n[o]);return ji.flush(80)},fTn=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?ji.addInt32(-1):o instanceof Buffer?(s=1,ji.addInt32(o.length),ji.add(o)):ji.addInt32PrefixedString(o);let a=ji.buffer;a[n++]=0,a[n++]=s}},gTn=(t={})=>{let e=t.portal||"",n=t.statement||"",r=t.binary||!1,i=t.values||Wet,o=i.length;ji.addCString(e).addCString(n),ji.addInt16(o);let s=ji.reserveUnsafe(o*2);ji.addInt16(o);try{fTn(i,t.valueMapper,s)}catch(a){throw ji.clear(),a}return ji.addInt16(1),ji.addInt16(r?1:0),ji.flush(66)},ATn=Buffer.from([69,0,0,0,9,0,0,0,0,0]),yTn=t=>{if(!t||!t.portal&&!t.rows)return ATn;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},ETn=(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},Uge=(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},wTn=ji.addCString("P").flush(68),xTn=ji.addCString("S").flush(68),bTn=t=>t.name?Uge(68,`${t.type}${t.name||""}`):t.type==="P"?wTn:xTn,CTn=t=>{let e=`${t.type}${t.name||""}`;return Uge(67,e)},ITn=t=>ji.add(t).flush(100),vTn=t=>Uge(102,t),G6=t=>Buffer.from([t,0,0,0,4]),STn=G6(72),_Tn=G6(83),kTn=G6(88),TTn=G6(99),RTn={startup:cTn,password:lTn,requestSsl:uTn,sendSASLInitialResponseMessage:dTn,sendSCRAMClientFinalMessage:pTn,query:hTn,parse:mTn,bind:gTn,execute:yTn,describe:bTn,close:CTn,flush:()=>STn,sync:()=>_Tn,end:()=>kTn,copyData:ITn,copyDone:()=>TTn,copyFail:vTn,cancel:ETn};q6.serialize=RTn});var Get=L(j6=>{"use strict";Object.defineProperty(j6,"__esModule",{value:!0});j6.BufferReader=void 0;var $ge=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}};j6.BufferReader=$ge});var Vet=L(z6=>{"use strict";Object.defineProperty(z6,"__esModule",{value:!0});z6.Parser=void 0;var as=Qge(),BTn=Get(),Hge=1,DTn=4,qet=Hge+DTn,Xd=-1,Wge=Buffer.allocUnsafe(0),Gge=class{constructor(e){if(this.buffer=Wge,this.bufferLength=0,this.bufferOffset=0,this.reader=new BTn.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+qet<=r;){let o=this.buffer[i],s=this.buffer.readUInt32BE(i+Hge),a=Hge+s;if(a+i<=r){let c=this.handlePacket(i+qet,o,s,this.buffer);n(c),i+=a}else break}i===r?(this.buffer=Wge,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=WTn(o);break;case 67:s=PTn(o);break;case 90:s=MTn(o);break;case 65:s=QTn(o);break;case 82:s=qTn(o,r);break;case 83:s=HTn(o);break;case 75:s=GTn(o);break;case 69:s=jet(o,"error");break;case 78:s=jet(o,"notice");break;case 84:s=FTn(o);break;case 116:s=$Tn(o);break;case 71:s=OTn(o);break;case 72:s=LTn(o);break;case 100:s=NTn(o,r);break;default:return new as.DatabaseError("received invalid response: "+n.toString(16),r,"error")}return o.setBuffer(0,Wge),s.length=r,s}};z6.Parser=Gge;var MTn=t=>{let e=t.string(1);return new as.ReadyForQueryMessage(Xd,e)},PTn=t=>{let e=t.cstring();return new as.CommandCompleteMessage(Xd,e)},NTn=(t,e)=>{let n=t.bytes(e-4);return new as.CopyDataMessage(Xd,n)},OTn=t=>zet(t,"copyInResponse"),LTn=t=>zet(t,"copyOutResponse"),zet=(t,e)=>{let n=t.byte()!==0,r=t.int16(),i=new as.CopyResponse(Xd,e,n,r);for(let o=0;o<r;o++)i.columnTypes[o]=t.int16();return i},QTn=t=>{let e=t.int32(),n=t.cstring(),r=t.cstring();return new as.NotificationResponseMessage(Xd,e,n,r)},FTn=t=>{let e=t.int16(),n=new as.RowDescriptionMessage(Xd,e);for(let r=0;r<e;r++)n.fields[r]=UTn(t);return n},UTn=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)},$Tn=t=>{let e=t.int16(),n=new as.ParameterDescriptionMessage(Xd,e);for(let r=0;r<e;r++)n.dataTypeIDs[r]=t.uint32();return n},WTn=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(Xd,n)},HTn=t=>{let e=t.cstring(),n=t.cstring();return new as.ParameterStatusMessage(Xd,e,n)},GTn=t=>{let e=t.int32(),n=t.int32();return new as.BackendKeyDataMessage(Xd,e,n)},qTn=(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(Xd,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},jet=(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(Xd,i):new as.DatabaseError(i,Xd,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 qge=L(JI=>{"use strict";Object.defineProperty(JI,"__esModule",{value:!0});JI.DatabaseError=JI.serialize=void 0;JI.parse=KTn;var jTn=Qge();Object.defineProperty(JI,"DatabaseError",{enumerable:!0,get:function(){return jTn.DatabaseError}});var zTn=Het();Object.defineProperty(JI,"serialize",{enumerable:!0,get:function(){return zTn.serialize}});var VTn=Vet();function KTn(t,e){let n=new VTn.Parser;return t.on("data",r=>n.parse(r,e)),new Promise(r=>t.on("end",()=>r()))}});var Ket=L(jge=>{"use strict";Object.defineProperty(jge,"__esModule",{value:!0});jge.default={}});var Jet=L((jxi,Yet)=>{var{getStream:YTn,getSecureStream:JTn}=tRn();Yet.exports={getStream:YTn,getSecureStream:JTn};function XTn(){function t(n){let r=Y("net");return new r.Socket}function e(n){return Y("tls").connect(n)}return{getStream:t,getSecureStream:e}}function ZTn(){function t(n){let{CloudflareSocket:r}=Ket();return new r(n)}function e(n){return n.socket.startTls(n),n.socket}return{getStream:t,getSecureStream:e}}function eRn(){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 tRn(){return eRn()?ZTn():XTn()}});var Vge=L((zxi,Zet)=>{"use strict";var nRn=Y("events").EventEmitter,{parse:rRn,serialize:Ya}=qge(),Xet=Jet(),{getStream:iRn}=Xet,oRn=Ya.flush(),sRn=Ya.sync(),aRn=Ya.end(),zge=class extends nRn{constructor(e){super(),e=e||{},this.stream=e.stream||iRn(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=Y("net");o.isIP&&o.isIP(e)===0&&(i.servername=e);try{r.stream=Xet.getSecureStream(i)}catch(s){return r.emit("error",s)}r.attachListeners(r.stream),r.stream.on("error",n),r.emit("sslconnect")}attachListeners(e){rRn(e,n=>{let r=n.name==="error"?"errorMessage":n.name;this._emitMessage&&this.emit("message",n),this.emit(r,n)})}requestSsl(){this.stream.write(Ya.requestSsl())}startup(e){this.stream.write(Ya.startup(e))}cancel(e,n){this._send(Ya.cancel(e,n))}password(e){this._send(Ya.password(e))}sendSASLInitialResponseMessage(e,n){this._send(Ya.sendSASLInitialResponseMessage(e,n))}sendSCRAMClientFinalMessage(e){this._send(Ya.sendSCRAMClientFinalMessage(e))}_send(e){return this.stream.writable?this.stream.write(e):!1}query(e){this._send(Ya.query(e))}parse(e){this._send(Ya.parse(e))}bind(e){this._send(Ya.bind(e))}execute(e){this._send(Ya.execute(e))}flush(){this.stream.writable&&this.stream.write(oRn)}sync(){this._send(sRn)}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(aRn,()=>{this.stream.end()})}close(e){this._send(Ya.close(e))}describe(e){this._send(Ya.describe(e))}sendCopyFromChunk(e){this._send(Ya.copyData(e))}endCopyFrom(){this._send(Ya.copyDone())}sendCopyFail(e){this._send(Ya.copyFail(e))}};Zet.exports=zge});var rtt=L((Vxi,ntt)=>{"use strict";var{Transform:cRn}=Y("stream"),{StringDecoder:uRn}=Y("string_decoder"),ww=Symbol("last"),V6=Symbol("decoder");function lRn(t,e,n){let r;if(this.overflow){if(r=this[V6].write(t).split(this.matcher),r.length===1)return n();r.shift(),this.overflow=!1}else this[ww]+=this[V6].write(t),r=this[ww].split(this.matcher);this[ww]=r.pop();for(let i=0;i<r.length;i++)try{ttt(this,this.mapper(r[i]))}catch(o){return n(o)}if(this.overflow=this[ww].length>this.maxLength,this.overflow&&!this.skipOverflow){n(new Error("maximum buffer reached"));return}n()}function dRn(t){if(this[ww]+=this[V6].end(),this[ww])try{ttt(this,this.mapper(this[ww]))}catch(e){return t(e)}t()}function ttt(t,e){e!==void 0&&t.push(e)}function ett(t){return t}function pRn(t,e,n){switch(t=t||/\r?\n/,e=e||ett,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=ett)}n=Object.assign({},n),n.autoDestroy=!0,n.transform=lRn,n.flush=dRn,n.readableObjectMode=!0;let r=new cRn(n);return r[ww]="",r[V6]=new uRn("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}ntt.exports=pRn});var stt=L((Kxi,z0)=>{"use strict";var itt=Y("path"),hRn=Y("stream").Stream,mRn=rtt(),ott=Y("util"),fRn=5432,K6=process.platform==="win32",$F=process.stderr,gRn=56,ARn=7,yRn=61440,ERn=32768;function wRn(t){return(t&yRn)==ERn}var cB=["host","port","database","user","password"],Kge=cB.length,xRn=cB[Kge-1];function Yge(){var t=$F instanceof hRn&&$F.writable===!0;if(t){var e=Array.prototype.slice.call(arguments).concat(`
98
98
  `);$F.write(ott.format.apply(ott,e))}}Object.defineProperty(z0.exports,"isWin",{get:function(){return K6},set:function(t){K6=t}});z0.exports.warnTo=function(t){var e=$F;return $F=t,e};z0.exports.getFileName=function(t){var e=t||process.env,n=e.PGPASSFILE||(K6?itt.join(e.APPDATA||"./","postgresql","pgpass.conf"):itt.join(e.HOME||"./",".pgpass"));return n};z0.exports.usePgPass=function(t,e){return Object.prototype.hasOwnProperty.call(process.env,"PGPASSWORD")?!1:K6?!0:(e=e||"<unkn>",wRn(t.mode)?t.mode&(gRn|ARn)?(Yge('WARNING: password file "%s" has group or world access; permissions should be u=rw (0600) or less',e),!1):!0:(Yge('WARNING: password file "%s" is not a plain file',e),!1))};var bRn=z0.exports.match=function(t,e){return cB.slice(0,-1).reduce(function(n,r,i){return i==1&&Number(t[r]||fRn)===Number(e[r])?n&&!0:n&&(e[r]==="*"||e[r]===t[r])},!0)};z0.exports.getPassword=function(t,e,n){var r,i=e.pipe(mRn());function o(c){var u=CRn(c);u&&IRn(u)&&bRn(t,u)&&(r=u[xRn],i.end())}var s=function(){e.destroy(),n(r)},a=function(c){e.destroy(),Yge("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 CRn=z0.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[cB[l]]=h},u=0;u<t.length-1;u+=1){if(e=t.charAt(u+1),n=t.charAt(u),a=r==Kge-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===Kge?s:null,s},IRn=z0.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<cB.length;n+=1){var r=e[n],i=t[cB[n]]||"",o=r(i);if(!o)return!1}return!0}});var ctt=L((Jxi,Jge)=>{"use strict";var Yxi=Y("path"),att=Y("fs"),Y6=stt();Jge.exports=function(t,e){var n=Y6.getFileName();att.stat(n,function(r,i){if(r||!Y6.usePgPass(i,n))return e(void 0);var o=att.createReadStream(n);Y6.getPassword(t,o,e)})};Jge.exports.warnTo=Y6.warnTo});var ptt=L((Xxi,dtt)=>{var vRn=Y("events").EventEmitter,utt=VI(),WF=Y("util"),J6=vet(),SRn=W6(),_Rn=wge(),Xge=Fet(),kRn=FF(),TRn=Vge(),RRn=fge(),ltt=WF.deprecate(()=>{},"Client.activeQuery is deprecated and will be removed in pg@9.0"),BRn=WF.deprecate(()=>{},"Client.queryQueue is deprecated and will be removed in pg@9.0."),DRn=WF.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."),MRn=WF.deprecate(()=>{},"Passing a custom Promise implementation to the Client/Pool constructor is deprecated and will be removed in pg@9.0."),PRn=WF.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 NRn(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 X6=class extends vRn{constructor(e){super(),this.connectionParameters=new _Rn(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&&MRn(),this._Promise=n.Promise||global.Promise,this._types=new SRn(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=NRn(n.scramMaxIterations,J6.DEFAULT_MAX_SCRAM_ITERATIONS),this.connection=n.connection||new TRn({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||kRn.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 ltt(),this._activeQuery}set activeQuery(e){ltt(),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{ctt()(this.connectionParameters,i=>{i!==void 0&&(DRn(),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 RRn.postgresMd5PasswordHash(this.user,this.password,e.salt);this.connection.password(n)}catch(n){this.emit("error",n)}})}_handleAuthSASL(e){this._getPassword(()=>{try{this.saslSession=J6.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 J6.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{J6.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 utt.escapeIdentifier(e)}escapeLiteral(e){return utt.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 Xge(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 Xge)?"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&&PRn(),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 BRn(),this._queryQueue}};X6.Query=Xge;dtt.exports=X6});var ftt=L((Zxi,mtt)=>{"use strict";var ORn=Y("events").EventEmitter,Zge=function(){},htt=(t,e)=>{let n=t.findIndex(e);return n===-1?void 0:t.splice(n,1)[0]},eAe=class{constructor(e,n,r){this.client=e,this.idleListener=n,this.timeoutId=r}},uB=class{constructor(e){this.callback=e}};function LRn(){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 QRn(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 tAe=class extends ORn{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||nAe().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=htt(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 uB(n.callback)),r;let i=(a,c,u)=>{clearTimeout(s),n.callback(a,c,u)},o=new uB(i),s=setTimeout(()=>{htt(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 uB(n.callback)),r}newClient(e){let n=new this.Client(this.options);this._clients.push(n);let r=QRn(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 uB((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&&LRn(),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 eAe(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}};mtt.exports=tAe});var ytt=L((ebi,Att)=>{"use strict";var gtt=Y("events").EventEmitter,FRn=Y("util"),rAe=VI(),lB=Att.exports=function(t,e,n){gtt.call(this),t=rAe.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))};FRn.inherits(lB,gtt);var URn={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"};lB.prototype.handleError=function(t){let e=this.native&&this.native.pq.resultErrorFields();if(e)for(let n in e){let r=URn[n]||n;t[r]=e[n]}this.callback?this.callback(t):this.emit("error",t),this.state="error"};lB.prototype.then=function(t,e){return this._getPromise().then(t,e)};lB.prototype.catch=function(t){return this._getPromise().catch(t)};lB.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)};lB.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(rAe.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(rAe.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 Ctt=L((tbi,btt)=>{var $Rn=Y("util"),Ett;try{Ett=Y("pg-native")}catch(t){throw t}var WRn=W6(),wtt=Y("events").EventEmitter,HRn=Y("util"),GRn=wge(),xtt=ytt(),qRn=$Rn.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."),Bc=btt.exports=function(t){wtt.call(this),t=t||{},this._Promise=t.Promise||global.Promise,this._types=new WRn(t.types),this.native=new Ett({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 GRn(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={}};Bc.Query=xtt;HRn.inherits(Bc,wtt);Bc.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};Bc.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)})})};Bc.prototype.connect=function(t){if(t){this._connect(t);return}return new this._Promise((e,n)=>{this._connect(r=>{r?n(r):e(this)})})};Bc.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 xtt(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&&qRn(),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)};Bc.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};Bc.prototype._hasActiveQuery=function(){return this._activeQuery&&this._activeQuery.state!=="error"&&this._activeQuery.state!=="end"};Bc.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()})};Bc.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=VI();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()})};Bc.prototype.cancel=function(t){this._activeQuery===t?this.native.cancel(function(){}):this._queryQueue.indexOf(t)!==-1&&this._queryQueue.splice(this._queryQueue.indexOf(t),1)};Bc.prototype.ref=function(){};Bc.prototype.unref=function(){};Bc.prototype.setTypeParser=function(t,e,n){return this._types.setTypeParser(t,e,n)};Bc.prototype.getTypeParser=function(t,e){return this._types.getTypeParser(t,e)};Bc.prototype.isConnected=function(){return this._connected};Bc.prototype.getTransactionStatus=function(){return this.native.getTransactionStatus()}});var iAe=L((nbi,Itt)=>{"use strict";Itt.exports=Ctt()});var nAe=L((ibi,eV)=>{"use strict";var jRn=ptt(),zRn=FF(),VRn=Vge(),KRn=bge(),YRn=VI(),JRn=ftt(),XRn=W6(),{DatabaseError:ZRn}=qge(),{escapeIdentifier:eBn,escapeLiteral:tBn}=VI(),nBn=t=>class extends JRn{constructor(n){super(n,t)}},vtt=function(t){this.defaults=zRn,this.Client=t,this.Query=this.Client.Query,this.Pool=nBn(this.Client),this._pools=[],this.Connection=VRn,this.types=QF(),this.DatabaseError=ZRn,this.TypeOverrides=XRn,this.escapeIdentifier=eBn,this.escapeLiteral=tBn,this.Result=KRn,this.utils=YRn},Stt=jRn,_tt=!1;try{_tt=!!process.env.NODE_PG_FORCE_NATIVE}catch{}_tt&&(Stt=iAe());eV.exports=new vtt(Stt);Object.defineProperty(eV.exports,"native",{configurable:!0,enumerable:!1,get(){let t=null;try{t=new vtt(iAe())}catch(e){if(e.code!=="MODULE_NOT_FOUND")throw e}return Object.defineProperty(eV.exports,"native",{value:t}),t}})});var Zd,obi,sbi,abi,cbi,ubi,lbi,dbi,pbi,hbi,mbi,fbi,ktt,Ttt=A(()=>{Zd=cn(nAe(),1),obi=Zd.default.Client,sbi=Zd.default.Pool,abi=Zd.default.Connection,cbi=Zd.default.types,ubi=Zd.default.Query,lbi=Zd.default.DatabaseError,dbi=Zd.default.escapeIdentifier,pbi=Zd.default.escapeLiteral,hbi=Zd.default.Result,mbi=Zd.default.TypeOverrides,fbi=Zd.default.defaults,ktt=Zd.default});var rBn,iBn,oAe,ybi,Rtt=A(()=>{"use strict";Ttt();rBn=["mail","node","grant","run_event","report","structured_request","queue","spend_limits","environment_image","fault_retry","settings","machine","machine_call","document","review","execution_exit"],iBn=new Set(rBn),oAe=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 ktt.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);iBn.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(()=>{}))}},ybi=new oAe});var Btt=A(()=>{"use strict";rB()});function uBn(t){switch(t){case aBn:return"context-nudge";case oBn:return"bearings";case cBn:return"review-boundary";case sBn:return"situational";default:return}}function aAe(t){return t.replace(/&(?:amp|lt|gt|quot|apos);/g,e=>({"&amp;":"&","&lt;":"<","&gt;":">","&quot;":'"',"&apos;":"'"})[e])}function sAe(t){let e={};tV.lastIndex=0;let n=0;for(;n<t.length&&!/^\s*$/.test(t.slice(n));){tV.lastIndex=n;let r=tV.exec(t);if(r===null)return null;let[,i,o,s]=r;if(i===void 0||Object.hasOwn(e,i))return null;e[i]=aAe(o??s??""),n=tV.lastIndex}return e}function cAe(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 lBn(t){let e=[],n=/<from\b([^>]*)>([\s\S]*?)<\/from>/g;for(let r of t.matchAll(n)){let i=sAe(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=sAe(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:aAe(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 dBn(t,e,n,r){return{kind:t,facts:e,body:n,senders:r}}function Ott(t){let e=/^<runtime\b([^>]*)>/.exec(t);if(e===null||!t.endsWith("</runtime>"))return null;let n=sAe(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(":")?aAe(r):r;return dBn(i,s,a,i==="inbox"?lBn(a):[])}function dB(t){let e=cAe(t),n=Ott(e);if(n!==null)return n;if(t.role!=="custom")return null;let r=uBn(t.customType);return r===void 0?null:{kind:r,facts:Object.freeze({}),body:e,senders:[]}}function XI(t){return t.disposition==="human-answer"&&Ott(t.body.trim())===null}var oBn,sBn,aBn,cBn,Dtt,Mtt,Ptt,Ntt,tV,ZI=A(()=>{"use strict";oBn="crtr-context",sBn="crtr-situational-context",aBn="crtr-context-nudge",cBn="crtr-review-boundary",Dtt="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.",Mtt="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.",Ptt="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.",Ntt="Your previous turn stopped on a provider fault. Continue from where you left off and retry the work that failed.";tV=/\s+([A-Za-z_:][A-Za-z0-9_:.-]*)\s*=\s*(?:"([^"]*)"|'([^']*)')/gy});var Ltt=A(()=>{"use strict";ZI()});function pBn(){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 DF(){let t=pBn();if(t===void 0)return yw({autostart:!1});let e=DZe();if(e===void 0)throw new Error("broker has no node token for CRTR_API_URL");return new Rg({baseUrl:t,headers:{authorization:`Bearer ${e}`}})}function Qtt(t,e){return DF().appendNodeLog(t,{record:e,expected_execution_id:hBn()})}function hBn(){let t=YYe();if(t===void 0||t==="")throw new Error("broker launch is missing CRTR_EXECUTION_ID");return t}async function nV(t,e){return DF().recordNodeFault(t,e)}async function rV(t,e={}){return DF().clearNodeFault(t,{...e.link===void 0?{}:{link:e.link},...e.preserveEpisode===void 0?{}:{preserve_episode:e.preserveEpisode}}).then(n=>n.cleared)}var rB=A(()=>{"use strict";M6();MZe();P6();gw();L6();Rc();NZe();ev();Rtt();Btt();Ltt()});function fBn(t,e){Ftt=Ftt.then(async()=>{try{let{appended:n}=await Qtt(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 Gl(t){let e=T6();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=qXe({...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=zXe(n);return e.component==="broker"&&e.node_id!==void 0&&(mBn??=OI())?(fBn(e.node_id,r),!0):e.component==="daemon"?QXe(e.path,r):A6(e.path,r)}var mBn,Ftt,ev=A(()=>{"use strict";kfe();jXe();VXe();jfe();Rc();rB();Ftt=Promise.resolve()});var Utt,$tt=A(()=>{"use strict";ev();Utt={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 iV(t){return t.flatMap(e=>e.path===void 0?[]:[e.path])}var HF=A(()=>{"use strict"});var Wtt=A(()=>{"use strict"});var Htt=A(()=>{"use strict";Ul()});import{createHash as gBn}from"node:crypto";function jtt(t){return t===void 0?"absent":gBn("sha256").update(JSON.stringify(t)).digest("hex")}function ztt(t,e){qtt.set(t,e)}function V0(){let t;try{t=b6()}catch(n){if(n instanceof SF)return Gtt();if(n instanceof vF)return uAe??Gtt();throw n}let e=qtt.get(t);if(e!==void 0)return e;if(uAe!==void 0)return uAe;throw new lAe(t)}function Vtt(t){ABn=t}function Ktt(t){yBn=t}function qF(t){let e=V0().settings[t];return{settings:e===void 0?null:structuredClone(e),revision:jtt(e)}}function Ytt(t){let e=V0().state[t];return e===void 0?{marketplaces:{},plugins:{},activeCanvas:null}:structuredClone(e)}function Jtt(){return structuredClone(V0().profiles)}function Xtt(t){let e=V0().profiles.find(n=>n.profileId===t);return e===void 0?null:structuredClone(e)}var GF,lAe,qtt,Gtt,uAe,ABn,yBn,pB=A(()=>{"use strict";XR();GF=class extends Error{constructor(){super("settings changed since the supplied revision"),this.name="SettingsRevisionConflictError"}},lAe=class extends Error{constructor(e){super(`settings for ${e} are not loaded in this process`),this.name="PersonSettingsNotLoadedError"}},qtt=new Map;Gtt=()=>({profiles:[],defaults:{},settings:{},state:{},apps:{}});ABn=async()=>{throw new Error("no settings transport installed in this process")}});var Ztt=A(()=>{"use strict"});var ent=A(()=>{"use strict";Rc()});var tnt=A(()=>{"use strict"});var nnt=A(()=>{"use strict"});var rnt=A(()=>{"use strict"});var int=A(()=>{"use strict"});var ont=A(()=>{"use strict"});var snt=A(()=>{"use strict"});var ant=A(()=>{"use strict"});var cnt=A(()=>{"use strict"});var unt=A(()=>{"use strict"});var lnt,dAe=A(()=>{"use strict";lnt=["trial_ended","card_required","card_limit","nothing_left","app_limit","team_limit","app_unpaid","account_held"]});var dnt=A(()=>{"use strict"});var pnt=A(()=>{"use strict"});var hnt=A(()=>{"use strict"});var mnt=A(()=>{"use strict"});var fnt=A(()=>{"use strict"});var gnt=A(()=>{"use strict"});var Ant=A(()=>{"use strict"});var ynt=A(()=>{"use strict"});var Ent=A(()=>{"use strict"});var wnt=A(()=>{"use strict"});var xnt=A(()=>{"use strict"});var bnt=A(()=>{"use strict"});var Cnt=A(()=>{"use strict"});var Int=A(()=>{"use strict"});var vnt=A(()=>{"use strict"});var Snt=A(()=>{"use strict"});var _nt=A(()=>{"use strict"});var knt=A(()=>{"use strict"});var Tnt=A(()=>{"use strict"});var Rnt=A(()=>{"use strict"});var Bnt=A(()=>{"use strict"});var Dnt=A(()=>{"use strict"});var Mnt=A(()=>{"use strict"});var Pnt=A(()=>{"use strict"});var Nnt=A(()=>{"use strict"});var Ont=A(()=>{"use strict"});var Lnt=A(()=>{"use strict"});var Qnt=A(()=>{"use strict"});var Fnt=A(()=>{"use strict"});var Unt=A(()=>{"use strict"});var $nt=A(()=>{"use strict"});var Wnt=A(()=>{"use strict"});var Hnt=A(()=>{"use strict"});var Gnt=A(()=>{"use strict"});var tv=A(()=>{"use strict";M6();gw();nnt();Vfe();rnt();int();ont();ZI();Yfe();snt();ant();cnt();unt();dAe();dnt();pnt();hnt();mnt();fnt();gnt();Jfe();Ant();ynt();Ent();wnt();xnt();bnt();Xfe();Cnt();Int();vnt();HF();Snt();_nt();knt();Tnt();Rnt();Bnt();Dnt();Mnt();Pnt();Nnt();Ont();Lnt();Qnt();Fnt();Unt();$nt();Wnt();Hnt();Gnt()});function EBn(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function jF(t,e,n={}){if(t.code==="daemon_restarting")return new na("daemon_restarting",t.message,Go.NETWORK,{next:"crtrd is now on the new generation \u2014 retry the command."});if(t.code==="daemon_unavailable")return new na("daemon_unavailable",t.message,Go.NETWORK,{next:"Start it with `crtr sys daemon start`, then retry."});if(t.code==="northlight_unreachable"){let a=t.details?.next;return new na("northlight_unreachable",t.message,Go.NETWORK,{next:typeof a=="string"&&a!==""?a:"Check this computer's internet connection, then retry."})}if(t.code==="model_sign_in_required"){let a=t.details?.url;return new mh({error:t.code,message:t.message,next:typeof a=="string"?`Ask the person to sign in at ${a}, then retry.`:"Ask the person to sign in to an AI subscription on their Northlight account, then retry.",...typeof a=="string"?{details:{url:a}}:{}},Go.USAGE)}let r=t.details,i=xBn(t,r,n.providerCall===!0);if(t.status===503||n.providerCall===!0&&t.status===504&&i.code!==void 0){let a=i.code??t.code,c={next:i.next??e??"Retry the command; if it persists, inspect the unavailable service named in the error."};return i.details!==void 0&&(c.details=i.details),i.code!==void 0&&(i.field!==void 0&&(c.field=i.field),i.received!==void 0&&(c.received=i.received),i.retryAfterS!==void 0&&(c.retry_after_s=i.retryAfterS)),new na(a,t.message,Go.NETWORK,c)}let o=Array.isArray(r?.violations)?r.violations.map(a=>`${String(a.field)} ${String(a.problem)}${a.received!==void 0?` (received ${JSON.stringify(a.received)})`:""}`):[],s=r&&typeof r.error=="string"&&typeof r.message=="string"&&typeof r.next=="string"?r:{error:i.code??wBn[t.status]??t.code,...i.field!==void 0?{field:i.field}:{},...i.received!==void 0?{received:i.received}:{},...i.retryAfterS!==void 0?{retry_after_s:i.retryAfterS}:{},...i.details!==void 0?{details:i.details}:{},message:o.length>0?`${t.message}: ${o.join("; ")}`:t.message.trim()!==""?t.message:`request refused (HTTP ${t.status}, ${t.code}) with no message`,next:i.next??(r?.outcome==="unknown"?"The change may already be applied: check the current state before repeating it, and do not report it failed.":void 0)??e??(i.retryAfterS!==void 0?`Wait ${i.retryAfterS}s, then retry; do not retry sooner.`:t.status>=500?"This is a crtr bug, not a bad call. Retry; if it persists, report it (the daemon log holds the full cause).":t.status===404&&i.code===void 0?"List nodes with `crtr node inspect list`.":"Inspect the error and adjust the call. See -h for the schema.")};return new mh(s,bBn(s.error,t.status))}function xBn(t,e,n){let r=o=>typeof o=="string"&&/^[a-z][a-z0-9_]*$/.test(o);if(n&&t.origin!==void 0&&t.origin!=="provider"&&r(t.code)){let o={code:t.code};return(t.status===503||t.status===504)&&(o.next=t.retryable===!0?"Retry the command; if it persists, the machine or service named in the error is unavailable.":"Read the error before retrying: the action may already have run."),EBn(t.details)&&(o.details=t.details),t.param!==void 0&&(o.field=t.param),typeof t.retryAfterS=="number"&&(o.retryAfterS=t.retryAfterS),o}if(t.origin!=="provider"||e===void 0||e===null||typeof e!="object")return{};let i={};return typeof e.status=="number"&&r(e.code)&&(i.code=e.code),typeof e.next=="string"&&e.next.trim()!==""&&(i.next=e.next),typeof e.field=="string"&&e.field!==""?i.field=e.field:t.param!==void 0&&(i.field=t.param),e.received!==void 0&&e.received!==null&&(i.received=e.received),typeof t.retryAfterS=="number"&&(i.retryAfterS=t.retryAfterS),i}function bBn(t,e){return t==="not_found"||e===404?Go.NOT_FOUND:t==="ambiguous"?Go.AMBIGUOUS:Go.USAGE}var FIi,mh,wBn,hB=A(()=>{"use strict";Ul();Uu();ent();tnt();tv();FIi=256*1024,mh=class extends na{payload;constructor(e,n=Go.USAGE){super(e.error,e.message,n,{...e}),this.name="InputError",this.payload=e}};wBn={400:"invalid_request",404:"not_found",409:"conflict",422:"unprocessable"}});var oV=A(()=>{"use strict"});import{loadLinuxNative as IBn}from"../../native/linux.js";var GIi,pAe=A(()=>{"use strict";oV();GIi=IBn()});var jnt=A(()=>{"use strict";pAe();oV()});import{join as _Bn}from"node:path";function znt(){return _Bn(lh(),"runtime-client.json")}function kBn(){let t=j0(znt());if(t?.token_sha256===void 0)return null;let{owner:e}=t;if(typeof e!="string"||!/^user:.+/.test(e))throw new Error(`${znt()} was written by join but has a missing or invalid owner`);return t}function Vnt(){return kBn()?.issuer??null}var Knt=A(()=>{"use strict";hB();Ul();dh();Wl();$l();jnt();L6();xw()});import{chmodSync as avi,existsSync as TBn,mkdirSync as cvi,readFileSync as RBn,writeFileSync as lvi}from"node:fs";import{dirname as pvi,join as BBn}from"node:path";function K0(){let t=DBn();if(!TBn(t))return;let e=JSON.parse(RBn(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}}}var DBn,Ynt,zF=A(()=>{"use strict";dh();Knt();DBn=()=>BBn(Kd(),"machine.json");Ynt=()=>K0()===void 0&&Vnt()===null});function PBn(t){return t.grantee??"app:terminal"}function NBn(t){if(!Jnt.test(t))throw q0(`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 sV(t){NBn(t);let e=Xtt(t);if(e===null)throw f6(`profile not found: ${t}`,{received:t});return oZe(PBn(e.manifest),t).dir}function OBn(){return{entries:Jtt(),unreadableIds:[]}}function aV(){return OBn().entries}function LBn(t){let e=aV(),n=QBn(e,t,Xnt);return n?{kind:"resolved",entry:n}:{kind:"absent"}}function QBn(t,e,n){if(Jnt.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 RXe(`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 FBn(t,e,n){let r=t.map(i=>`${n(i).profileId} (${n(i).name})`);return f6(`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 Bg(t){let e=LBn(t);if(e.kind==="resolved")return e.entry;throw FBn(aV(),t,Xnt)}var Jnt,Xnt,nv=A(()=>{"use strict";Htt();Uu();dh();HF();$l();pB();Ul();Ztt();XR();zF();Jnt=/^[a-z0-9]+(?:-[a-z0-9]+)*-[0-9a-f]{8}$/;Xnt=t=>({profileId:t.profileId,name:t.manifest.name})});import{homedir as Znt}from"node:os";import{existsSync as UBn,statSync as $Bn}from"node:fs";import{join as cV,resolve as ert,dirname as WBn,sep as mAe}from"node:path";function ep(){return cV(Kd(),"scope")}function HBn(t,e){if(!UBn(t)||ef(t)===ef(cV(Znt(),UI))||ef(t).startsWith(`${ef(Lfe())}${mAe}`)&&t.endsWith(`${mAe}home${mAe}${UI}`)||!OI()&&(ef(t)===ef(e)||ef(t)===ef(S6())))return!1;try{return $Bn(t).isDirectory()}catch{return!1}}function GBn(t=process.cwd()){return trt(t)[0]??null}function qBn(t,e){let n=[],r=ef(Znt()),i=ert(t);for(;;){let o=cV(i,UI);if(HBn(o,e)&&n.push(o),ef(i)===r)return n;let s=WBn(i);if(s===i)return n;i=s}}function trt(t=process.cwd(),e=zme()||null){return jBn(t,e)}function jBn(t,e){let n=ert(t),r=ep(),i=[n];if(!OI()&&e!==null&&e!=="")try{let{manifest:a}=Bg(e);i.push(...iV(a.projects))}catch{}let o=new Set,s=[];for(let a of i)for(let c of qBn(a,r))o.has(c)||(o.add(c),s.push(c));return s}function nrt(t){return GBn(t)}function Y0(t){return t==="builtin"?null:t==="user"?ep():nrt()}function hAe(t){let e=t==="user"?Kd():Y0(t);return e?cV(e,"plugins"):null}var xw=A(()=>{"use strict";Rc();HF();Uu();Wtt();Ul();nv();$l();dh()});import{join as zBn}from"node:path";function VBn(t){return zBn(t,_Xe,kXe)}function KBn(t){let e;try{e=j0(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 YBn(t){return KBn(VBn(t))}function rrt(t){let e=YBn(t);return e.status==="ok"?e.manifest:null}var fAe=A(()=>{"use strict";Uu();$l()});import{existsSync as irt,mkdirSync as JBn,readdirSync as ort,rmSync as AAe,rmdirSync as XBn,statSync as ZBn,unlinkSync as eDn,writeFileSync as tDn}from"node:fs";import{randomUUID as nDn}from"node:crypto";function EAe(t){return Math.min(t*2,rDn)}function crt(t){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,t)}function iDn(t){return new Promise(e=>setTimeout(e,t))}function lV(t,e){return`${t}/${gAe}${e}`}function wAe(t){try{return ort(t).find(e=>e.startsWith(gAe))?.slice(gAe.length)??null}catch{return null}}function urt(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 oDn(t){try{return ort(t).length===0}catch{return!1}}function sDn(t){try{return Date.now()-ZBn(t).mtimeMs}catch{return 0}}function aDn(t,e){let n=wAe(t);if(n!==null){if(urt(n))return;try{eDn(lV(t,n))}catch(r){if(r.code==="ENOENT")return;throw r}}else{if(sDn(t)<=e)return;if(!oDn(t)){AAe(t,{recursive:!0,force:!0});return}}try{XBn(t)}catch(r){let i=r.code;if(i!=="ENOENT"&&i!=="ENOTEMPTY"&&i!=="EEXIST")throw r}}function dV(t){let e=wAe(t);if(e===null)return null;let n=Number(e.split(".",1)[0]);return Number.isSafeInteger(n)&&n>0?n:null}function lrt(t,e){let n=Date.now()+e,r=yAe;for(;;){let i=wAe(t);if(i===null||Number(i.split(".",1)[0])===process.pid||!urt(i))return;let o=n-Date.now();if(o<=0)return;crt(Math.min(r,o)),r=EAe(r)}}function uV(t,e){let n=`${process.pid}.${nDn()}`;try{return JBn(t,{mode:448}),tDn(lV(t,n),"",{flag:"wx",mode:384}),{path:t,token:n}}catch(r){if(r.code!=="EEXIST")throw r;return aDn(t,e),null}}function rv(t,e,n={}){let r=n.staleMs??srt,i=Date.now()+(n.timeoutMs??art),o=yAe,s=uV(t,r);for(;s===null;){if(Date.now()>=i)throw n.timeoutError?.()??new Error(`timed out waiting for the exclusive lock: ${t}`);crt(Math.min(o,Math.max(0,i-Date.now()))),o=EAe(o),s=uV(t,r)}try{return e()}finally{irt(lV(s.path,s.token))&&AAe(s.path,{recursive:!0,force:!0})}}async function drt(t,e,n={}){let r=n.staleMs??srt,i=Date.now()+(n.timeoutMs??art),o=yAe,s=uV(t,r);for(;s===null;){if(Date.now()>=i)throw n.timeoutError?.()??new Error(`timed out waiting for the exclusive lock: ${t}`);await iDn(Math.min(o,Math.max(0,i-Date.now()))),o=EAe(o),s=uV(t,r)}try{return await e()}finally{irt(lV(s.path,s.token))&&AAe(s.path,{recursive:!0,force:!0})}}var gAe,yAe,rDn,srt,art,bw=A(()=>{"use strict";gAe="owner.",yAe=10,rDn=250,srt=3e4,art=5e3});import{join as cDn}from"node:path";function prt(t,e){return cDn(t,"tmp",`${e}.swap.lock`)}function hrt(t,e){let n=dV(prt(t,e));return n!==null&&n!==process.pid}function mrt(t,e){lrt(prt(t,e),uDn)}var uDn,frt=A(()=>{"use strict";bw();uDn=2e3});function pV(t,e){let n=t.apps[lDn];return n===void 0&&e===null?null:{...e??{},plugins:structuredClone(n?.plugins??{}),marketplaces:structuredClone(n?.marketplaces??{})}}var lDn,xAe=A(()=>{"use strict";Rc();pB();lDn="app:terminal"});import{join as bAe}from"node:path";function dDn(t,e){let n=t==="user"?mF()?pV(V0(),qF("user").settings):qF("user").settings:j0(bAe(e,p6));return n&&n.plugins&&typeof n.plugins=="object"?n.plugins:{}}function pDn(t,e,n){let r=Object.keys(e);return r.every(i=>n.has(i))?[]:r.filter(i=>!n.has(i)&&hrt(t,i))}function hV(t,e){if(t==="user"&&x6())return[];let n=t!=="user"?bAe(e,"plugins"):hAe("user");if(n===void 0||!Nfe(n))return[];let r=dDn(t,e),i=grt(t,n,r),o=pDn(e,r,new Set(i.map(s=>s.name)));if(o.length===0)return i;for(let s of o)mrt(e,s);return grt(t,n,r)}function grt(t,e,n){let r=[];for(let i of Ofe(e)){let o=bAe(e,i),s=rrt(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 mV=A(()=>{"use strict";Uu();$l();fAe();frt();XR();pB();xAe();xw()});import{existsSync as hDn,realpathSync as mDn}from"node:fs";import{basename as fDn,dirname as gDn,join as xSi,resolve as Art}from"node:path";function mB(t){let e=Art(t),n=e,r=[];for(;!hDn(n);){let i=gDn(n);if(i===n)return e;r.unshift(fDn(n)),n=i}return Art(mDn(n),...r)}var yrt=A(()=>{"use strict"});function ADn(t){let e=qi.indexOf(t);return`less ${qi.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 ${gV[t]}`}function fV(t,e,n){let r=t.indexOf(e),i=r>=0?r:0;return t[(i+n+t.length)%t.length]}function Ert(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 iv(t,e){return t==="true"?!0:t==="false"?!1:`${e} must be true or false`}function brt(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 yDn(t,e){let n=brt(t,e);return typeof n=="string"||n<1?`${e} must be an integer >= 1`:n}function xrt(t,e){let n=t.providerOptions[e];if(n!==void 0)return n;let r={};return t.providerOptions[e]=r,r}function bDn(){let t=[];for(let e of Object.values(Crt))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 gV,wrt,EDn,wDn,VF,Crt,xDn,ISi,CAe=A(()=>{"use strict";Uu();gV={replies:"Replies only",summaries:"Messages + summaries",tools:"Tool calls",previews:"Previews",full:"Full"};wrt=[!1,"notify","apply"],EDn=[0,1,6,12,24,48,72,168],wDn=[1,2,3,4,5,6,8,10,12],VF="openai-codex";Crt={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=fV(wrt,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=fV(wrt,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=Ert(EDn,t.auto_update.interval_hours,e)},setFromString:(t,e)=>{let n=brt(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=Ert(wDn,t.max_panes_per_window,e)},setFromString:(t,e)=>{let n=yDn(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=iv(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=iv(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=iv(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=iv(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:$I.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=fV($I,t.whip_message_mode,e)},setFromString:(t,e)=>$I.includes(e)?(t.whip_message_mode=e,null):`whip_message_mode must be one of: ${$I.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:WI.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=fV(WI,t.mouse_mode_default,e)},setFromString:(t,e)=>WI.includes(e)?(t.mouse_mode_default=e,null):`mouse_mode_default must be one of: ${WI.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=iv(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:qi.join("|"),applies:"Applies on the next attach.",group:"display",order:30,format:t=>t.verbosity,display:t=>ADn(t.verbosity),cycle:(t,e)=>{let n=qi.indexOf(t.verbosity)+e;t.verbosity=qi[Math.max(0,Math.min(qi.length-1,n))]},setFromString:(t,e)=>qi.includes(e)?(t.verbosity=e,null):`verbosity must be one of: ${qi.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=iv(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.${VF}.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[VF]?.fastMode?"on":"off",cycle:t=>{let e=xrt(t,VF);e.fastMode=!e.fastMode},setFromString:(t,e)=>{let n=iv(e,`providerOptions.${VF}.fastMode`);return typeof n=="string"?n:(xrt(t,VF).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:"daemon API listener"},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"}},xDn=Object.keys(Crt);ISi=bDn()});function KF(t){return t.split("-").map(e=>e===""?"":`${e[0].toUpperCase()}${e.slice(1)}`).join("")}function gB(t){try{let e=JSON.stringify(t);return e===void 0?String(t):e}catch{return String(t)}}function fB(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 ${gB(t)}`);return t.trim()}}function _Ae(t,e="page_components"){if(t===void 0)return[];if(!Array.isArray(t))throw new Error(`${e} must be an array; received ${gB(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: ${gB(i)}`);if(u.display!==void 0&&typeof u.display!="boolean")throw new Error(`${e}[${o}].display must be a boolean; offending entry: ${gB(i)}`);s={kind:u.kind.trim(),...fB(u.description,"description",e,o)===void 0?{}:{description:fB(u.description,"description",e,o)},...fB(u.useWhen,"useWhen",e,o)===void 0?{}:{useWhen:fB(u.useWhen,"useWhen",e,o)},...fB(u.doc,"doc",e,o)===void 0?{}:{doc:fB(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: ${gB(i)}`);let a=s.kind;if(!IDn.test(a))throw new Error(`${e}[${o}] has invalid page kind ${gB(a)}; expected /^[a-z][a-z0-9-]{0,63}$/`);if(vDn.has(a)||CDn.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=KF(a);if(AV.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 vrt(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=KF(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 Srt(t,e){return e.find(n=>n.kind===t)}var IAe,CDn,IDn,vDn,Irt,vAe,AV,SAe,YF=A(()=>{"use strict";IAe=["options","text","table","cards","chart"],CDn=["page","step"],IDn=/^[a-z][a-z0-9-]{0,63}$/,vDn=new Set(IAe),Irt=[{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}];vAe=Object.fromEntries(Irt.filter(t=>!t.structural).map(t=>[t.tag,t.kind])),AV=new Set(Irt.map(t=>t.tag)),SAe=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 Brt,join as Drt}from"node:path";import{existsSync as _Dn,mkdirSync as DSi,statSync as MSi}from"node:fs";function kDn(t){return Drt(t,p6)}function TDn(t){return Drt(t,TXe)}function Mrt(t){let e=mB(t),n=mB(ep());if(e===n)return{key:"user",kind:"user",root:n};if(Brt(e)===".crouter")return{key:"project",kind:"project",root:e};for(let r of aV()){let i=mB(sV(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 Prt(t){if(Brt(t)===".crouter"){let r;try{r=mB(t)}catch(i){if(i.code==="ENOENT")return null;throw i}if(r!==mB(ep()))return j0(kDn(t))}let e=Mrt(t).key,n=qF(e).settings;return e==="user"&&mF()?pV(V0(),n):n}function ph(t){let e=RDn[BDn];if(e){if(t!=="user")throw new Error(`broker config snapshot has no ${t} scope`);return e.user}let n=Y0(t);return n?DDn(n):m6()}function DDn(t){let e=Prt(t);return e?o1n(e):m6()}function MDn(t){let e=j0(TDn(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 Nrt(t){let e=Y0(t);return e?t==="project"?_Dn(e)?MDn(e):_fe():Ytt(Mrt(e).key):_fe()}function PDn(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 AB(t){return t===void 0?[...ODn]:Array.isArray(t)?[...new Set(t.filter(e=>typeof e=="string"&&FI.has(e)&&NDn.has(e)))]:[]}function LDn(t,e=Sfe()){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 Ort(t){return t==="ultra"||t==="strong"||t==="medium"||t==="light"}function kAe(){return Object.create(null)}function yV(t,e,n){Object.defineProperty(t,e,{value:n,writable:!0,enumerable:!0,configurable:!0})}function FDn(t){let e=kAe();for(let[n,r]of Object.entries(t??{}))yV(e,n,r);return e}function JF(t,e){Gl({level:"warn",event:"config.model_routes.invalid",fields:{route_id:t,rule:e}})}function UDn(t,e={}){let n=FDn(e);if(t===null||typeof t!="object"||Array.isArray(t))return n;for(let[r,i]of Object.entries(t)){if(r.trim()===""){JF(r,"route id must be a non-empty string");continue}if(i===null||typeof i!="object"||Array.isArray(i)){JF(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(!Ort(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){JF(r,c);continue}yV(n,r,a)}return n}function $Dn(t){let e=kAe(),n=kAe();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){JF(r,"route must include family, credentialSource, providerId, and models");continue}let o=QDn.filter(s=>i.models[s]===void 0);if(o.length>0){JF(r,`incomplete route; missing strengths: ${o.join(", ")}`),yV(n,r,{family:i.family,credentialSource:i.credentialSource,providerId:i.providerId,models:i.models});continue}yV(e,r,{family:i.family,credentialSource:i.credentialSource,providerId:i.providerId,models:i.models})}return{complete:e,legacy:n}}function WDn(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=>Ort(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 HDn(t){return t!==""&&t.replace(/\*/g,"")===""}function GDn(t,e=[]){let n=t,r=Array.isArray(n?.allow)?n.allow.filter(i=>typeof i=="string"):[];for(let i of r)if(HDn(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 qDn(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 zDn(t,e){if(e==="bin"&&jDn.has(t))return`${e}.${t} is reserved by crouter \u2014 pick another bare command name`;if(!_rt.test(t))return`${e}.${t} is not a safe bare command name (expected ${_rt.source})`}function VDn(t){if(t===null||typeof t!="object"||Array.isArray(t))return{};let e={};for(let[n,r]of Object.entries(t))zDn(n,"bin")===void 0&&(typeof r!="string"||r.trim()===""||(e[n]=r));return e}function KDn(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(krt.test(n)||i.push(`action name must match ${krt.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 YDn(t){if(t===null||typeof t!="object"||Array.isArray(t))return{};let e=new Set(KDn(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 JDn(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 XDn(t,e=vfe()){let n={...e};if(t!==null&&typeof t=="object")for(let[r,i]of Object.entries(t)){let o=JDn(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 wV(){let t=[{origin:"config.json",components:ph("user").page_components}],e=Y0("user");if(e!==null){let n=hV("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:_Ae(r.manifest.page_components,i)})}}return vrt(t)}function ZDn(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 e1n(t,e=Ife()){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=ZDn(o);s!==null&&(n[i]=s)}}return{targets:n}}function Trt(t,e){return t===!0?"notify":t===!1?!1:t==="notify"||t==="apply"?t:e}function EV(t,e){return typeof t=="number"&&Number.isSafeInteger(t)&&t>=1?t:e}function t1n(t,e){let n=t!==null&&typeof t=="object"?t:{},r=EV(n.warning,e.warning),i=EV(n.automaticReviveCap,e.automaticReviveCap);return r<=i?{warning:r,automaticReviveCap:i}:{...e}}function n1n(t,e){return{unattendedParkMs:EV((t!==null&&typeof t=="object"?t:{}).unattendedParkMs,e.unattendedParkMs)}}function r1n(t){if(!Array.isArray(t))return[...h6];let e=t.filter(n=>typeof n=="string"&&n.trim()!=="").map(n=>n.trim());return e.length>0?e:[...h6]}function i1n(t,e){if(t===null||typeof t!="object")return{...e};let n=t.tcp;return{tcp:typeof n=="string"?n:e.tcp}}function o1n(t){!Rrt&&t.ledger!==void 0&&(Rrt=!0,Gl({level:"warn",event:"config.ledger.ignored",fields:{variables:Object.values(Utt)}}));let e=m6(),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:Trt(o?.crtr,e.auto_update.crtr),content:Trt(o?.content,e.auto_update.content),interval_hours:a},u=t.max_panes_per_window,l=EV(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=t1n(t.brokerThresholds,e.brokerThresholds),h=n1n(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]:vXe(t.working_gerunds),g=typeof t.whip_mode=="boolean"?t.whip_mode:e.whip_mode,y=_Ae(t.page_components),x=typeof t.page_surface=="boolean"?t.page_surface:e.page_surface,b=r1n(t.whip_messages),v=$I.includes(t.whip_message_mode)?t.whip_message_mode:e.whip_message_mode,S=WI.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=qi.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=PDn(t.keybindings),Q=AB(t.tmux_passthrough),$=LDn(t.modelLadders),j=qDn(t.providerOptions,e.providerOptions),W=$Dn(UDn(t.modelRoutes)),de=W.complete,ee=WDn(t.modelRouting,void 0),Ae=XDn(t.kinds),Ie=e1n(t.remoteCanvas),Ue=i1n(t.api,e.api),Et=t.paths;if(Et?.user_files!==void 0&&(typeof Et.user_files!="string"||!Et.user_files.startsWith("/")))throw new Error("paths.user_files must be an absolute path");let Ze=t.store,wt=t.runtime;if(wt?.person_uids!==void 0&&(!Array.isArray(wt.person_uids)||!wt.person_uids.every($t=>Number.isSafeInteger($t)&&$t>=0)))throw new Error("runtime.person_uids must be an array of nonnegative integer uids");let te=GDn(t.spawnEnv,e.spawnEnv?.allow),it=VDn(t.bin),at=YDn(t.humanActions);return{bin:it,humanActions:at,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:y,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:Q,modelLadders:$,providerOptions:j,...Object.keys(de).length>0?{modelRoutes:de}:{},...Object.keys(W.legacy).length>0?{legacyModelRoutes:W.legacy}:{},...ee!==void 0?{modelRouting:ee}:{},kinds:Ae,remoteCanvas:Ie,api:Ue,...Et?{paths:Et}:{},...Ze?{store:Ze}:{},...wt?{runtime:wt}:{},spawnEnv:te}}function s1n(t){return Prt(t)}function Lrt(t){let e=Y0(t);return e?s1n(e):null}var RDn,BDn,NDn,ODn,QDn,_rt,jDn,krt,Rrt,Yd=A(()=>{"use strict";Rc();Uu();u6();Ul();ev();$tt();$l();xw();mV();nv();yrt();pB();xAe();bw();CAe();d6();YF();RDn=globalThis,BDn=Symbol.for("crtr.broker.config-snapshot");NDn=new Set(jd.filter(bF).map(t=>t.id)),ODn=Object.freeze(["crtr.attach.scroll.up","crtr.attach.scroll.down","crtr.attach.scroll.page-up","crtr.attach.scroll.page-down","crtr.attach.scroll.live"]);QDn=["ultra","strong","medium","light"];_rt=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,jDn=new Set(["crtr","crtrd"]);krt=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;Rrt=!1});var Z0=L((Y_i,rit)=>{"use strict";var tit=["nodebuffer","arraybuffer","fragments"],nit=typeof Blob<"u";nit&&tit.push("blob");rit.exports={BINARY_TYPES:tit,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:nit,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var iU=L((J_i,IV)=>{"use strict";var{EMPTY_BUFFER:Z1n}=Z0(),e0e=Buffer[Symbol.species];function eMn(t,e){if(t.length===0)return Z1n;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 e0e(n.buffer,n.byteOffset,r):n}function iit(t,e,n,r,i){for(let o=0;o<i;o++)n[r+o]=t[o]^e[o&3]}function oit(t,e){for(let n=0;n<t.length;n++)t[n]^=e[n&3]}function tMn(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function t0e(t){if(t0e.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new e0e(t):ArrayBuffer.isView(t)?e=new e0e(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),t0e.readOnly=!1),e}IV.exports={concat:eMn,mask:iit,toArrayBuffer:tMn,toBuffer:t0e,unmask:oit};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=Y("bufferutil");IV.exports.mask=function(e,n,r,i,o){o<48?iit(e,n,r,i,o):t.mask(e,n,r,i,o)},IV.exports.unmask=function(e,n){e.length<32?oit(e,n):t.unmask(e,n)}}catch{}});var cit=L((X_i,ait)=>{"use strict";var sit=Symbol("kDone"),n0e=Symbol("kRun"),r0e=class{constructor(e){this[sit]=()=>{this.pending--,this[n0e]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[n0e]()}[n0e](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[sit])}}};ait.exports=r0e});var vB=L((Z_i,pit)=>{"use strict";var oU=Y("zlib"),uit=iU(),nMn=cit(),{kStatusCode:lit}=Z0(),rMn=Buffer[Symbol.species],iMn=Buffer.from([0,0,255,255]),SV=Symbol("permessage-deflate"),ey=Symbol("total-length"),CB=Symbol("callback"),vw=Symbol("buffers"),IB=Symbol("error"),vV,i0e=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,!vV){let n=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;vV=new nMn(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[CB];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){vV.add(i=>{this._decompress(e,n,(o,s)=>{i(),r(o,s)})})}compress(e,n,r){vV.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"?oU.Z_DEFAULT_WINDOWBITS:this.params[o];this._inflate=oU.createInflateRaw({...this._options.zlibInflateOptions,windowBits:s}),this._inflate[SV]=this,this._inflate[ey]=0,this._inflate[vw]=[],this._inflate.on("error",sMn),this._inflate.on("data",dit)}this._inflate[CB]=r,this._inflate.write(e),n&&this._inflate.write(iMn),this._inflate.flush(()=>{let o=this._inflate[IB];if(o){this._inflate.close(),this._inflate=null,r(o);return}let s=uit.concat(this._inflate[vw],this._inflate[ey]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[ey]=0,this._inflate[vw]=[],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"?oU.Z_DEFAULT_WINDOWBITS:this.params[o];this._deflate=oU.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:s}),this._deflate[ey]=0,this._deflate[vw]=[],this._deflate.on("data",oMn)}this._deflate[CB]=r,this._deflate.write(e),this._deflate.flush(oU.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let o=uit.concat(this._deflate[vw],this._deflate[ey]);n&&(o=new rMn(o.buffer,o.byteOffset,o.length-4)),this._deflate[CB]=null,this._deflate[ey]=0,this._deflate[vw]=[],n&&this.params[`${i}_no_context_takeover`]&&this._deflate.reset(),r(null,o)})}};pit.exports=i0e;function oMn(t){this[vw].push(t),this[ey]+=t.length}function dit(t){if(this[ey]+=t.length,this[SV]._maxPayload<1||this[ey]<=this[SV]._maxPayload){this[vw].push(t);return}this[IB]=new RangeError("Max payload size exceeded"),this[IB].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[IB][lit]=1009,this.removeListener("data",dit),this.reset()}function sMn(t){if(this[SV]._inflate=null,this[IB]){this[CB](this[IB]);return}t[lit]=1007,this[CB](t)}});var SB=L((eki,_V)=>{"use strict";var{isUtf8:hit}=Y("buffer"),{hasBlob:aMn}=Z0(),cMn=[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 uMn(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function o0e(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 lMn(t){return aMn&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}_V.exports={isBlob:lMn,isValidStatusCode:uMn,isValidUTF8:o0e,tokenChars:cMn};if(hit)_V.exports.isValidUTF8=function(t){return t.length<24?o0e(t):hit(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=Y("utf-8-validate");_V.exports.isValidUTF8=function(e){return e.length<32?o0e(e):t(e)}}catch{}});var l0e=L((tki,wit)=>{"use strict";var{Writable:dMn}=Y("stream"),mit=vB(),{BINARY_TYPES:pMn,EMPTY_BUFFER:fit,kStatusCode:hMn,kWebSocket:mMn}=Z0(),{concat:s0e,toArrayBuffer:fMn,unmask:gMn}=iU(),{isValidStatusCode:AMn,isValidUTF8:git}=SB(),kV=Buffer[Symbol.species],fh=0,Ait=1,yit=2,Eit=3,a0e=4,c0e=5,TV=6,u0e=class extends dMn{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||pMn[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[mMn]=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=fh}_write(e,n,r){if(this._opcode===8&&this._state==fh)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 kV(r.buffer,r.byteOffset+e,r.length-e),new kV(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 kV(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 fh:this.getInfo(e);break;case Ait:this.getPayloadLength16(e);break;case yit:this.getPayloadLength64(e);break;case Eit:this.getMask();break;case a0e:this.getData(e);break;case c0e:case TV: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[mit.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=Ait:this._payloadLength===127?this._state=yit: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=Eit:this._state=a0e}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=a0e}getData(e){let n=fit;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&&gMn(n,this._mask)}if(this._opcode>7){this.controlMessage(n,e);return}if(this._compressed){this._state=c0e,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[mit.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===fh&&this.startLoop(n)})}dataMessage(e){if(!this._fin){this._state=fh;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=s0e(r,n):this._binaryType==="arraybuffer"?i=fMn(s0e(r,n)):this._binaryType==="blob"?i=new Blob(r):i=r,this._allowSynchronousEvents?(this.emit("message",i,!0),this._state=fh):(this._state=TV,setImmediate(()=>{this.emit("message",i,!0),this._state=fh,this.startLoop(e)}))}else{let i=s0e(r,n);if(!this._skipUTF8Validation&&!git(i)){let o=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(o);return}this._state===c0e||this._allowSynchronousEvents?(this.emit("message",i,!1),this._state=fh):(this._state=TV,setImmediate(()=>{this.emit("message",i,!1),this._state=fh,this.startLoop(e)}))}}controlMessage(e,n){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,fit),this.end();else{let r=e.readUInt16BE(0);if(!AMn(r)){let o=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");n(o);return}let i=new kV(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!git(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=fh;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=fh):(this._state=TV,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=fh,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[hMn]=i,s}};wit.exports=u0e});var h0e=L((rki,Cit)=>{"use strict";var{Duplex:nki}=Y("stream"),{randomFillSync:yMn}=Y("crypto"),{types:{isUint8Array:EMn}}=Y("util"),xit=vB(),{EMPTY_BUFFER:wMn,kWebSocket:xMn,NOOP:bMn}=Z0(),{isBlob:_B,isValidStatusCode:CMn}=SB(),{mask:bit,toBuffer:cv}=iU(),gh=Symbol("kByteLength"),IMn=Buffer.alloc(4),RV=8*1024,uv,kB=RV,tf=0,vMn=1,SMn=2,d0e=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=tf,this.onerror=bMn,this[xMn]=void 0}static frame(e,n){let r,i=!1,o=2,s=!1;n.mask&&(r=n.maskBuffer||IMn,n.generateMask?n.generateMask(r):(kB===RV&&(uv===void 0&&(uv=Buffer.alloc(RV)),yMn(uv,0,RV),kB=0),r[0]=uv[kB++],r[1]=uv[kB++],r[2]=uv[kB++],r[3]=uv[kB++]),s=(r[0]|r[1]|r[2]|r[3])===0,o=6);let a;typeof e=="string"?(!n.mask||s)&&n[gh]!==void 0?a=n[gh]:(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?(bit(e,r,u,o,a),[u]):(bit(e,r,e,0,a),[u,e])):[u,e]}close(e,n,r,i){let o;if(e===void 0)o=wMn;else{if(typeof e!="number"||!CMn(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(EMn(n))o.set(n,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let s={[gh]:o.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==tf?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):_B(e)?(i=e.size,o=!1):(e=cv(e),i=e.length,o=cv.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");let s={[gh]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:o,rsv1:!1};_B(e)?this._state!==tf?this.enqueue([this.getBlobData,e,!1,s,r]):this.getBlobData(e,!1,s,r):this._state!==tf?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):_B(e)?(i=e.size,o=!1):(e=cv(e),i=e.length,o=cv.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");let s={[gh]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:o,rsv1:!1};_B(e)?this._state!==tf?this.enqueue([this.getBlobData,e,!1,s,r]):this.getBlobData(e,!1,s,r):this._state!==tf?this.enqueue([this.dispatch,e,!1,s,r]):this.sendFrame(t.frame(e,s),r)}send(e,n,r){let i=this._extensions[xit.extensionName],o=n.binary?2:1,s=n.compress,a,c;typeof e=="string"?(a=Buffer.byteLength(e),c=!1):_B(e)?(a=e.size,c=!1):(e=cv(e),a=e.length,c=cv.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={[gh]:a,fin:n.fin,generateMask:this._generateMask,mask:n.mask,maskBuffer:this._maskBuffer,opcode:o,readOnly:c,rsv1:s};_B(e)?this._state!==tf?this.enqueue([this.getBlobData,e,this._compress,u,r]):this.getBlobData(e,this._compress,u,r):this._state!==tf?this.enqueue([this.dispatch,e,this._compress,u,r]):this.dispatch(e,this._compress,u,r)}getBlobData(e,n,r,i){this._bufferedBytes+=r[gh],this._state=SMn,e.arrayBuffer().then(o=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(p0e,this,a,i);return}this._bufferedBytes-=r[gh];let s=cv(o);n?this.dispatch(s,n,r,i):(this._state=tf,this.sendFrame(t.frame(s,r),i),this.dequeue())}).catch(o=>{process.nextTick(_Mn,this,o,i)})}dispatch(e,n,r,i){if(!n){this.sendFrame(t.frame(e,r),i);return}let o=this._extensions[xit.extensionName];this._bufferedBytes+=r[gh],this._state=vMn,o.compress(e,r.fin,(s,a)=>{if(this._socket.destroyed){let c=new Error("The socket was closed while data was being compressed");p0e(this,c,i);return}this._bufferedBytes-=r[gh],this._state=tf,r.readOnly=!1,this.sendFrame(t.frame(a,r),i),this.dequeue()})}dequeue(){for(;this._state===tf&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][gh],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][gh],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)}};Cit.exports=d0e;function p0e(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 _Mn(t,e,n){p0e(t,e,n),t.onerror(e)}});var Dit=L((iki,Bit)=>{"use strict";var{kForOnEventAttribute:sU,kListener:m0e}=Z0(),Iit=Symbol("kCode"),vit=Symbol("kData"),Sit=Symbol("kError"),_it=Symbol("kMessage"),kit=Symbol("kReason"),TB=Symbol("kTarget"),Tit=Symbol("kType"),Rit=Symbol("kWasClean"),ty=class{constructor(e){this[TB]=null,this[Tit]=e}get target(){return this[TB]}get type(){return this[Tit]}};Object.defineProperty(ty.prototype,"target",{enumerable:!0});Object.defineProperty(ty.prototype,"type",{enumerable:!0});var lv=class extends ty{constructor(e,n={}){super(e),this[Iit]=n.code===void 0?0:n.code,this[kit]=n.reason===void 0?"":n.reason,this[Rit]=n.wasClean===void 0?!1:n.wasClean}get code(){return this[Iit]}get reason(){return this[kit]}get wasClean(){return this[Rit]}};Object.defineProperty(lv.prototype,"code",{enumerable:!0});Object.defineProperty(lv.prototype,"reason",{enumerable:!0});Object.defineProperty(lv.prototype,"wasClean",{enumerable:!0});var RB=class extends ty{constructor(e,n={}){super(e),this[Sit]=n.error===void 0?null:n.error,this[_it]=n.message===void 0?"":n.message}get error(){return this[Sit]}get message(){return this[_it]}};Object.defineProperty(RB.prototype,"error",{enumerable:!0});Object.defineProperty(RB.prototype,"message",{enumerable:!0});var aU=class extends ty{constructor(e,n={}){super(e),this[vit]=n.data===void 0?null:n.data}get data(){return this[vit]}};Object.defineProperty(aU.prototype,"data",{enumerable:!0});var kMn={addEventListener(t,e,n={}){for(let i of this.listeners(t))if(!n[sU]&&i[m0e]===e&&!i[sU])return;let r;if(t==="message")r=function(o,s){let a=new aU("message",{data:s?o:o.toString()});a[TB]=this,BV(e,this,a)};else if(t==="close")r=function(o,s){let a=new lv("close",{code:o,reason:s.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[TB]=this,BV(e,this,a)};else if(t==="error")r=function(o){let s=new RB("error",{error:o,message:o.message});s[TB]=this,BV(e,this,s)};else if(t==="open")r=function(){let o=new ty("open");o[TB]=this,BV(e,this,o)};else return;r[sU]=!!n[sU],r[m0e]=e,n.once?this.once(t,r):this.on(t,r)},removeEventListener(t,e){for(let n of this.listeners(t))if(n[m0e]===e&&!n[sU]){this.removeListener(t,n);break}}};Bit.exports={CloseEvent:lv,ErrorEvent:RB,Event:ty,EventTarget:kMn,MessageEvent:aU};function BV(t,e,n){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,n):t.call(e,n)}});var DV=L((oki,Mit)=>{"use strict";var{tokenChars:cU}=SB();function Pg(t,e,n){t[e]===void 0?t[e]=[n]:t[e].push(n)}function TMn(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&&cU[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?(Pg(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&&cU[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),Pg(n,t.slice(c,l),!0),u===44&&(Pg(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(cU[u]!==1)throw new SyntaxError(`Unexpected character at index ${d}`);c===-1?c=d:r||(r=!0),i=!1}else if(o)if(cU[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&&cU[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),Pg(n,a,h),u===44&&(Pg(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?Pg(e,p,n):(a===void 0?Pg(n,p,!0):r?Pg(n,a,p.replace(/\\/g,"")):Pg(n,a,p),Pg(e,s,n)),e}function RMn(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(", ")}Mit.exports={format:RMn,parse:TMn}});var OV=L((cki,qit)=>{"use strict";var BMn=Y("events"),DMn=Y("https"),MMn=Y("http"),Oit=Y("net"),PMn=Y("tls"),{randomBytes:NMn,createHash:OMn}=Y("crypto"),{Duplex:ski,Readable:aki}=Y("stream"),{URL:f0e}=Y("url"),Sw=vB(),LMn=l0e(),QMn=h0e(),{isBlob:FMn}=SB(),{BINARY_TYPES:Pit,CLOSE_TIMEOUT:UMn,EMPTY_BUFFER:MV,GUID:$Mn,kForOnEventAttribute:g0e,kListener:WMn,kStatusCode:HMn,kWebSocket:Xa,NOOP:Lit}=Z0(),{EventTarget:{addEventListener:GMn,removeEventListener:qMn}}=Dit(),{format:jMn,parse:zMn}=DV(),{toBuffer:VMn}=iU(),Qit=Symbol("kAborted"),A0e=[8,13],ny=["CONNECTING","OPEN","CLOSING","CLOSED"],KMn=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,qo=class t extends BMn{constructor(e,n,r){super(),this._binaryType=Pit[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=MV,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]),Fit(this,e,n,r)):(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Pit.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 LMn({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 QMn(e,this._extensions,r.generateMask);this._receiver=i,this._sender=o,this._socket=e,i[Xa]=this,o[Xa]=this,e[Xa]=this,i.on("conclude",XMn),i.on("drain",ZMn),i.on("error",ePn),i.on("message",tPn),i.on("ping",nPn),i.on("pong",rPn),o.onerror=iPn,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),n.length>0&&e.unshift(n),e.on("close",Wit),e.on("data",NV),e.on("end",Hit),e.on("error",Git),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[Sw.extensionName]&&this._extensions[Sw.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){tp(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())}),$it(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){y0e(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(e||MV,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){y0e(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(e||MV,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){y0e(this,e,r);return}let i={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[Sw.extensionName]||(i.compress=!1),this._sender.send(e||MV,i,r)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){tp(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(qo,"CONNECTING",{enumerable:!0,value:ny.indexOf("CONNECTING")});Object.defineProperty(qo.prototype,"CONNECTING",{enumerable:!0,value:ny.indexOf("CONNECTING")});Object.defineProperty(qo,"OPEN",{enumerable:!0,value:ny.indexOf("OPEN")});Object.defineProperty(qo.prototype,"OPEN",{enumerable:!0,value:ny.indexOf("OPEN")});Object.defineProperty(qo,"CLOSING",{enumerable:!0,value:ny.indexOf("CLOSING")});Object.defineProperty(qo.prototype,"CLOSING",{enumerable:!0,value:ny.indexOf("CLOSING")});Object.defineProperty(qo,"CLOSED",{enumerable:!0,value:ny.indexOf("CLOSED")});Object.defineProperty(qo.prototype,"CLOSED",{enumerable:!0,value:ny.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(qo.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(qo.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[g0e])return e[WMn];return null},set(e){for(let n of this.listeners(t))if(n[g0e]){this.removeListener(t,n);break}typeof e=="function"&&this.addEventListener(t,e,{[g0e]:!0})}})});qo.prototype.addEventListener=GMn;qo.prototype.removeEventListener=qMn;qit.exports=qo;function Fit(t,e,n,r){let i={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:UMn,protocolVersion:A0e[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,!A0e.includes(i.protocolVersion))throw new RangeError(`Unsupported protocol version: ${i.protocolVersion} (supported versions: ${A0e.join(", ")})`);let o;if(e instanceof f0e)o=e;else try{o=new f0e(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;PV(t,f);return}let u=s?443:80,l=NMn(16).toString("base64"),d=s?DMn.request:MMn.request,p=new Set,h;if(i.createConnection=i.createConnection||(s?JMn:YMn),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 Sw({...i.perMessageDeflate,isServer:!1,maxPayload:i.maxPayload}),i.headers["Sec-WebSocket-Extensions"]=jMn({[Sw.extensionName]:h.offer()})),n.length){for(let f of n){if(typeof f!="string"||!KMn.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,y]of Object.entries(f))r.headers[g.toLowerCase()]=y}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",()=>{tp(t,m,"Opening handshake has timed out")}),m.on("error",f=>{m===null||m[Qit]||(m=t._req=null,PV(t,f))}),m.on("response",f=>{let g=f.headers.location,y=f.statusCode;if(g&&i.followRedirects&&y>=300&&y<400){if(++t._redirects>i.maxRedirects){tp(t,m,"Maximum redirects exceeded");return}m.abort();let x;try{x=new f0e(g,e)}catch{let v=new SyntaxError(`Invalid URL: ${g}`);PV(t,v);return}Fit(t,x,n,r)}else t.emit("unexpected-response",m,f)||tp(t,m,`Unexpected server response: ${f.statusCode}`)}),m.on("upgrade",(f,g,y)=>{if(t.emit("upgrade",f),t.readyState!==qo.CONNECTING)return;m=t._req=null;let x=f.headers.upgrade;if(x===void 0||x.toLowerCase()!=="websocket"){tp(t,g,"Invalid Upgrade header");return}let b=OMn("sha1").update(l+$Mn).digest("base64");if(f.headers["sec-websocket-accept"]!==b){tp(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){tp(t,g,S);return}v&&(t._protocol=v);let _=f.headers["sec-websocket-extensions"];if(_!==void 0){if(!h){tp(t,g,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let T;try{T=zMn(_)}catch{tp(t,g,"Invalid Sec-WebSocket-Extensions header");return}let B=Object.keys(T);if(B.length!==1||B[0]!==Sw.extensionName){tp(t,g,"Server indicated an extension that was not requested");return}try{h.accept(T[Sw.extensionName])}catch{tp(t,g,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[Sw.extensionName]=h}t.setSocket(g,y,{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 PV(t,e){t._readyState=qo.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function YMn(t){return t.path=t.socketPath,Oit.connect(t)}function JMn(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=Oit.isIP(t.host)?"":t.host),PMn.connect(t)}function tp(t,e,n){t._readyState=qo.CLOSING;let r=new Error(n);Error.captureStackTrace(r,tp),e.setHeader?(e[Qit]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(PV,t,r)):(e.destroy(r),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function y0e(t,e,n){if(e){let r=FMn(e)?e.size:VMn(e).length;t._socket?t._sender._bufferedBytes+=r:t._bufferedAmount+=r}if(n){let r=new Error(`WebSocket is not open: readyState ${t.readyState} (${ny[t.readyState]})`);process.nextTick(n,r)}}function XMn(t,e){let n=this[Xa];n._closeFrameReceived=!0,n._closeMessage=e,n._closeCode=t,n._socket[Xa]!==void 0&&(n._socket.removeListener("data",NV),process.nextTick(Uit,n._socket),t===1005?n.close():n.close(t,e))}function ZMn(){let t=this[Xa];t.isPaused||t._socket.resume()}function ePn(t){let e=this[Xa];e._socket[Xa]!==void 0&&(e._socket.removeListener("data",NV),process.nextTick(Uit,e._socket),e.close(t[HMn])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function Nit(){this[Xa].emitClose()}function tPn(t,e){this[Xa].emit("message",t,e)}function nPn(t){let e=this[Xa];e._autoPong&&e.pong(t,!this._isServer,Lit),e.emit("ping",t)}function rPn(t){this[Xa].emit("pong",t)}function Uit(t){t.resume()}function iPn(t){let e=this[Xa];e.readyState!==qo.CLOSED&&(e.readyState===qo.OPEN&&(e._readyState=qo.CLOSING,$it(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function $it(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function Wit(){let t=this[Xa];if(this.removeListener("close",Wit),this.removeListener("data",NV),this.removeListener("end",Hit),t._readyState=qo.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[Xa]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",Nit),t._receiver.on("finish",Nit))}function NV(t){this[Xa]._receiver.write(t)||this.pause()}function Hit(){let t=this[Xa];t._readyState=qo.CLOSING,t._receiver.end(),this.end()}function Git(){let t=this[Xa];this.removeListener("error",Git),this.on("error",Lit),t&&(t._readyState=qo.CLOSING,this.destroy())}});var Kit=L((lki,Vit)=>{"use strict";var uki=OV(),{Duplex:oPn}=Y("stream");function jit(t){t.emit("close")}function sPn(){!this.destroyed&&this._writableState.finished&&this.destroy()}function zit(t){this.removeListener("error",zit),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function aPn(t,e){let n=!0,r=new oPn({...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(jit,r);return}let s=!1;t.once("error",function(c){s=!0,o(c)}),t.once("close",function(){s||o(i),process.nextTick(jit,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",sPn),r.on("error",zit),r}Vit.exports=aPn});var E0e=L((dki,Yit)=>{"use strict";var{tokenChars:cPn}=SB();function uPn(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&&cPn[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}Yit.exports={parse:uPn}});var rot=L((hki,not)=>{"use strict";var lPn=Y("events"),LV=Y("http"),{Duplex:pki}=Y("stream"),{createHash:dPn}=Y("crypto"),Jit=DV(),dv=vB(),pPn=E0e(),hPn=OV(),{CLOSE_TIMEOUT:mPn,GUID:fPn,kWebSocket:gPn}=Z0(),APn=/^[+/0-9A-Za-z]{22}==$/,Xit=0,Zit=1,tot=2,w0e=class extends lPn{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:mPn,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:hPn,...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=LV.createServer((r,i)=>{let o=LV.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=yPn(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=Xit}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===tot){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(uU,this);return}if(e&&this.once("close",e),this._state!==Zit)if(this._state=Zit,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(uU,this):process.nextTick(uU,this);else{let n=this._server;this._removeListeners(),this._removeListeners=this._server=null,n.close(()=>{uU(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",eot);let o=e.headers["sec-websocket-key"],s=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){pv(this,e,n,405,"Invalid HTTP method");return}if(s===void 0||s.toLowerCase()!=="websocket"){pv(this,e,n,400,"Invalid Upgrade header");return}if(o===void 0||!APn.test(o)){pv(this,e,n,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){pv(this,e,n,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){lU(n,400);return}let c=e.headers["sec-websocket-protocol"],u=new Set;if(c!==void 0)try{u=pPn.parse(c)}catch{pv(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 dv({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let h=Jit.parse(l);h[dv.extensionName]&&(p.accept(h[dv.extensionName]),d[dv.extensionName]=p)}catch{pv(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 lU(n,m||401,f,g);this.completeUpgrade(d,o,u,e,n,r,i)});return}if(!this.options.verifyClient(p))return lU(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[gPn])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Xit)return lU(o,503);let u=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${dPn("sha1").update(n+fPn).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[dv.extensionName]){let d=e[dv.extensionName].params,p=Jit.format({[dv.extensionName]:[d]});u.push(`Sec-WebSocket-Extensions: ${p}`),l._extensions=e}this.emit("headers",u,i),o.write(u.concat(`\r
100
+ `)}})}function Gl(t){let e=T6();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=qXe({...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=zXe(n);return e.component==="broker"&&e.node_id!==void 0&&(mBn??=OI())?(fBn(e.node_id,r),!0):e.component==="daemon"?QXe(e.path,r):A6(e.path,r)}var mBn,Ftt,ev=A(()=>{"use strict";kfe();jXe();VXe();jfe();Rc();rB();Ftt=Promise.resolve()});var Utt,$tt=A(()=>{"use strict";ev();Utt={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 iV(t){return t.flatMap(e=>e.path===void 0?[]:[e.path])}var HF=A(()=>{"use strict"});var Wtt=A(()=>{"use strict"});var Htt=A(()=>{"use strict";Ul()});import{createHash as gBn}from"node:crypto";function jtt(t){return t===void 0?"absent":gBn("sha256").update(JSON.stringify(t)).digest("hex")}function ztt(t,e){qtt.set(t,e)}function V0(){let t;try{t=b6()}catch(n){if(n instanceof SF)return Gtt();if(n instanceof vF)return uAe??Gtt();throw n}let e=qtt.get(t);if(e!==void 0)return e;if(uAe!==void 0)return uAe;throw new lAe(t)}function Vtt(t){ABn=t}function Ktt(t){yBn=t}function qF(t){let e=V0().settings[t];return{settings:e===void 0?null:structuredClone(e),revision:jtt(e)}}function Ytt(t){let e=V0().state[t];return e===void 0?{marketplaces:{},plugins:{},activeCanvas:null}:structuredClone(e)}function Jtt(){return structuredClone(V0().profiles)}function Xtt(t){let e=V0().profiles.find(n=>n.profileId===t);return e===void 0?null:structuredClone(e)}var GF,lAe,qtt,Gtt,uAe,ABn,yBn,pB=A(()=>{"use strict";XR();GF=class extends Error{constructor(){super("settings changed since the supplied revision"),this.name="SettingsRevisionConflictError"}},lAe=class extends Error{constructor(e){super(`settings for ${e} are not loaded in this process`),this.name="PersonSettingsNotLoadedError"}},qtt=new Map;Gtt=()=>({profiles:[],defaults:{},settings:{},state:{},apps:{}});ABn=async()=>{throw new Error("no settings transport installed in this process")}});var Ztt=A(()=>{"use strict"});var ent=A(()=>{"use strict";Rc()});var tnt=A(()=>{"use strict"});var nnt=A(()=>{"use strict"});var rnt=A(()=>{"use strict"});var int=A(()=>{"use strict"});var ont=A(()=>{"use strict"});var snt=A(()=>{"use strict"});var ant=A(()=>{"use strict"});var cnt=A(()=>{"use strict"});var unt=A(()=>{"use strict"});var lnt,dAe=A(()=>{"use strict";lnt=["trial_ended","card_required","card_limit","nothing_left","app_limit","team_limit","app_unpaid","account_held","operator_stop","person_limit"]});var dnt=A(()=>{"use strict"});var pnt=A(()=>{"use strict"});var hnt=A(()=>{"use strict"});var mnt=A(()=>{"use strict"});var fnt=A(()=>{"use strict"});var gnt=A(()=>{"use strict"});var Ant=A(()=>{"use strict"});var ynt=A(()=>{"use strict"});var Ent=A(()=>{"use strict"});var wnt=A(()=>{"use strict"});var xnt=A(()=>{"use strict"});var bnt=A(()=>{"use strict"});var Cnt=A(()=>{"use strict"});var Int=A(()=>{"use strict"});var vnt=A(()=>{"use strict"});var Snt=A(()=>{"use strict"});var _nt=A(()=>{"use strict"});var knt=A(()=>{"use strict"});var Tnt=A(()=>{"use strict"});var Rnt=A(()=>{"use strict"});var Bnt=A(()=>{"use strict"});var Dnt=A(()=>{"use strict"});var Mnt=A(()=>{"use strict"});var Pnt=A(()=>{"use strict"});var Nnt=A(()=>{"use strict"});var Ont=A(()=>{"use strict"});var Lnt=A(()=>{"use strict"});var Qnt=A(()=>{"use strict"});var Fnt=A(()=>{"use strict"});var Unt=A(()=>{"use strict"});var $nt=A(()=>{"use strict"});var Wnt=A(()=>{"use strict"});var Hnt=A(()=>{"use strict"});var Gnt=A(()=>{"use strict"});var tv=A(()=>{"use strict";M6();gw();nnt();Vfe();rnt();int();ont();ZI();Yfe();snt();ant();cnt();unt();dAe();dnt();pnt();hnt();mnt();fnt();gnt();Jfe();Ant();ynt();Ent();wnt();xnt();bnt();Xfe();Cnt();Int();vnt();HF();Snt();_nt();knt();Tnt();Rnt();Bnt();Dnt();Mnt();Pnt();Nnt();Ont();Lnt();Qnt();Fnt();Unt();$nt();Wnt();Hnt();Gnt()});function EBn(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function jF(t,e,n={}){if(t.code==="daemon_restarting")return new na("daemon_restarting",t.message,Go.NETWORK,{next:"crtrd is now on the new generation \u2014 retry the command."});if(t.code==="daemon_unavailable")return new na("daemon_unavailable",t.message,Go.NETWORK,{next:"Start it with `crtr sys daemon start`, then retry."});if(t.code==="northlight_unreachable"){let a=t.details?.next;return new na("northlight_unreachable",t.message,Go.NETWORK,{next:typeof a=="string"&&a!==""?a:"Check this computer's internet connection, then retry."})}if(t.code==="model_sign_in_required"){let a=t.details?.url;return new mh({error:t.code,message:t.message,next:typeof a=="string"?`Ask the person to sign in at ${a}, then retry.`:"Ask the person to sign in to an AI subscription on their Northlight account, then retry.",...typeof a=="string"?{details:{url:a}}:{}},Go.USAGE)}let r=t.details,i=xBn(t,r,n.providerCall===!0);if(t.status===503||n.providerCall===!0&&t.status===504&&i.code!==void 0){let a=i.code??t.code,c={next:i.next??e??"Retry the command; if it persists, inspect the unavailable service named in the error."};return i.details!==void 0&&(c.details=i.details),i.code!==void 0&&(i.field!==void 0&&(c.field=i.field),i.received!==void 0&&(c.received=i.received),i.retryAfterS!==void 0&&(c.retry_after_s=i.retryAfterS)),new na(a,t.message,Go.NETWORK,c)}let o=Array.isArray(r?.violations)?r.violations.map(a=>`${String(a.field)} ${String(a.problem)}${a.received!==void 0?` (received ${JSON.stringify(a.received)})`:""}`):[],s=r&&typeof r.error=="string"&&typeof r.message=="string"&&typeof r.next=="string"?r:{error:i.code??wBn[t.status]??t.code,...i.field!==void 0?{field:i.field}:{},...i.received!==void 0?{received:i.received}:{},...i.retryAfterS!==void 0?{retry_after_s:i.retryAfterS}:{},...i.details!==void 0?{details:i.details}:{},message:o.length>0?`${t.message}: ${o.join("; ")}`:t.message.trim()!==""?t.message:`request refused (HTTP ${t.status}, ${t.code}) with no message`,next:i.next??(r?.outcome==="unknown"?"The change may already be applied: check the current state before repeating it, and do not report it failed.":void 0)??e??(i.retryAfterS!==void 0?`Wait ${i.retryAfterS}s, then retry; do not retry sooner.`:t.status>=500?"This is a crtr bug, not a bad call. Retry; if it persists, report it (the daemon log holds the full cause).":t.status===404&&i.code===void 0?"List nodes with `crtr node inspect list`.":"Inspect the error and adjust the call. See -h for the schema.")};return new mh(s,bBn(s.error,t.status))}function xBn(t,e,n){let r=o=>typeof o=="string"&&/^[a-z][a-z0-9_]*$/.test(o);if(n&&t.origin!==void 0&&t.origin!=="provider"&&r(t.code)){let o={code:t.code};return(t.status===503||t.status===504)&&(o.next=t.retryable===!0?"Retry the command; if it persists, the machine or service named in the error is unavailable.":"Read the error before retrying: the action may already have run."),EBn(t.details)&&(o.details=t.details),t.param!==void 0&&(o.field=t.param),typeof t.retryAfterS=="number"&&(o.retryAfterS=t.retryAfterS),o}if(t.origin!=="provider"||e===void 0||e===null||typeof e!="object")return{};let i={};return typeof e.status=="number"&&r(e.code)&&(i.code=e.code),typeof e.next=="string"&&e.next.trim()!==""&&(i.next=e.next),typeof e.field=="string"&&e.field!==""?i.field=e.field:t.param!==void 0&&(i.field=t.param),e.received!==void 0&&e.received!==null&&(i.received=e.received),typeof t.retryAfterS=="number"&&(i.retryAfterS=t.retryAfterS),i}function bBn(t,e){return t==="not_found"||e===404?Go.NOT_FOUND:t==="ambiguous"?Go.AMBIGUOUS:Go.USAGE}var FIi,mh,wBn,hB=A(()=>{"use strict";Ul();Uu();ent();tnt();tv();FIi=256*1024,mh=class extends na{payload;constructor(e,n=Go.USAGE){super(e.error,e.message,n,{...e}),this.name="InputError",this.payload=e}};wBn={400:"invalid_request",404:"not_found",409:"conflict",422:"unprocessable"}});var oV=A(()=>{"use strict"});import{loadLinuxNative as IBn}from"../../native/linux.js";var GIi,pAe=A(()=>{"use strict";oV();GIi=IBn()});var jnt=A(()=>{"use strict";pAe();oV()});import{join as _Bn}from"node:path";function znt(){return _Bn(lh(),"runtime-client.json")}function kBn(){let t=j0(znt());if(t?.token_sha256===void 0)return null;let{owner:e}=t;if(typeof e!="string"||!/^user:.+/.test(e))throw new Error(`${znt()} was written by join but has a missing or invalid owner`);return t}function Vnt(){return kBn()?.issuer??null}var Knt=A(()=>{"use strict";hB();Ul();dh();Wl();$l();jnt();L6();xw()});import{chmodSync as avi,existsSync as TBn,mkdirSync as cvi,readFileSync as RBn,writeFileSync as lvi}from"node:fs";import{dirname as pvi,join as BBn}from"node:path";function K0(){let t=DBn();if(!TBn(t))return;let e=JSON.parse(RBn(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}}}var DBn,Ynt,zF=A(()=>{"use strict";dh();Knt();DBn=()=>BBn(Kd(),"machine.json");Ynt=()=>K0()===void 0&&Vnt()===null});function PBn(t){return t.grantee??"app:terminal"}function NBn(t){if(!Jnt.test(t))throw q0(`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 sV(t){NBn(t);let e=Xtt(t);if(e===null)throw f6(`profile not found: ${t}`,{received:t});return oZe(PBn(e.manifest),t).dir}function OBn(){return{entries:Jtt(),unreadableIds:[]}}function aV(){return OBn().entries}function LBn(t){let e=aV(),n=QBn(e,t,Xnt);return n?{kind:"resolved",entry:n}:{kind:"absent"}}function QBn(t,e,n){if(Jnt.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 RXe(`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 FBn(t,e,n){let r=t.map(i=>`${n(i).profileId} (${n(i).name})`);return f6(`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 Bg(t){let e=LBn(t);if(e.kind==="resolved")return e.entry;throw FBn(aV(),t,Xnt)}var Jnt,Xnt,nv=A(()=>{"use strict";Htt();Uu();dh();HF();$l();pB();Ul();Ztt();XR();zF();Jnt=/^[a-z0-9]+(?:-[a-z0-9]+)*-[0-9a-f]{8}$/;Xnt=t=>({profileId:t.profileId,name:t.manifest.name})});import{homedir as Znt}from"node:os";import{existsSync as UBn,statSync as $Bn}from"node:fs";import{join as cV,resolve as ert,dirname as WBn,sep as mAe}from"node:path";function ep(){return cV(Kd(),"scope")}function HBn(t,e){if(!UBn(t)||ef(t)===ef(cV(Znt(),UI))||ef(t).startsWith(`${ef(Lfe())}${mAe}`)&&t.endsWith(`${mAe}home${mAe}${UI}`)||!OI()&&(ef(t)===ef(e)||ef(t)===ef(S6())))return!1;try{return $Bn(t).isDirectory()}catch{return!1}}function GBn(t=process.cwd()){return trt(t)[0]??null}function qBn(t,e){let n=[],r=ef(Znt()),i=ert(t);for(;;){let o=cV(i,UI);if(HBn(o,e)&&n.push(o),ef(i)===r)return n;let s=WBn(i);if(s===i)return n;i=s}}function trt(t=process.cwd(),e=zme()||null){return jBn(t,e)}function jBn(t,e){let n=ert(t),r=ep(),i=[n];if(!OI()&&e!==null&&e!=="")try{let{manifest:a}=Bg(e);i.push(...iV(a.projects))}catch{}let o=new Set,s=[];for(let a of i)for(let c of qBn(a,r))o.has(c)||(o.add(c),s.push(c));return s}function nrt(t){return GBn(t)}function Y0(t){return t==="builtin"?null:t==="user"?ep():nrt()}function hAe(t){let e=t==="user"?Kd():Y0(t);return e?cV(e,"plugins"):null}var xw=A(()=>{"use strict";Rc();HF();Uu();Wtt();Ul();nv();$l();dh()});import{join as zBn}from"node:path";function VBn(t){return zBn(t,_Xe,kXe)}function KBn(t){let e;try{e=j0(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 YBn(t){return KBn(VBn(t))}function rrt(t){let e=YBn(t);return e.status==="ok"?e.manifest:null}var fAe=A(()=>{"use strict";Uu();$l()});import{existsSync as irt,mkdirSync as JBn,readdirSync as ort,rmSync as AAe,rmdirSync as XBn,statSync as ZBn,unlinkSync as eDn,writeFileSync as tDn}from"node:fs";import{randomUUID as nDn}from"node:crypto";function EAe(t){return Math.min(t*2,rDn)}function crt(t){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,t)}function iDn(t){return new Promise(e=>setTimeout(e,t))}function lV(t,e){return`${t}/${gAe}${e}`}function wAe(t){try{return ort(t).find(e=>e.startsWith(gAe))?.slice(gAe.length)??null}catch{return null}}function urt(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 oDn(t){try{return ort(t).length===0}catch{return!1}}function sDn(t){try{return Date.now()-ZBn(t).mtimeMs}catch{return 0}}function aDn(t,e){let n=wAe(t);if(n!==null){if(urt(n))return;try{eDn(lV(t,n))}catch(r){if(r.code==="ENOENT")return;throw r}}else{if(sDn(t)<=e)return;if(!oDn(t)){AAe(t,{recursive:!0,force:!0});return}}try{XBn(t)}catch(r){let i=r.code;if(i!=="ENOENT"&&i!=="ENOTEMPTY"&&i!=="EEXIST")throw r}}function dV(t){let e=wAe(t);if(e===null)return null;let n=Number(e.split(".",1)[0]);return Number.isSafeInteger(n)&&n>0?n:null}function lrt(t,e){let n=Date.now()+e,r=yAe;for(;;){let i=wAe(t);if(i===null||Number(i.split(".",1)[0])===process.pid||!urt(i))return;let o=n-Date.now();if(o<=0)return;crt(Math.min(r,o)),r=EAe(r)}}function uV(t,e){let n=`${process.pid}.${nDn()}`;try{return JBn(t,{mode:448}),tDn(lV(t,n),"",{flag:"wx",mode:384}),{path:t,token:n}}catch(r){if(r.code!=="EEXIST")throw r;return aDn(t,e),null}}function rv(t,e,n={}){let r=n.staleMs??srt,i=Date.now()+(n.timeoutMs??art),o=yAe,s=uV(t,r);for(;s===null;){if(Date.now()>=i)throw n.timeoutError?.()??new Error(`timed out waiting for the exclusive lock: ${t}`);crt(Math.min(o,Math.max(0,i-Date.now()))),o=EAe(o),s=uV(t,r)}try{return e()}finally{irt(lV(s.path,s.token))&&AAe(s.path,{recursive:!0,force:!0})}}async function drt(t,e,n={}){let r=n.staleMs??srt,i=Date.now()+(n.timeoutMs??art),o=yAe,s=uV(t,r);for(;s===null;){if(Date.now()>=i)throw n.timeoutError?.()??new Error(`timed out waiting for the exclusive lock: ${t}`);await iDn(Math.min(o,Math.max(0,i-Date.now()))),o=EAe(o),s=uV(t,r)}try{return await e()}finally{irt(lV(s.path,s.token))&&AAe(s.path,{recursive:!0,force:!0})}}var gAe,yAe,rDn,srt,art,bw=A(()=>{"use strict";gAe="owner.",yAe=10,rDn=250,srt=3e4,art=5e3});import{join as cDn}from"node:path";function prt(t,e){return cDn(t,"tmp",`${e}.swap.lock`)}function hrt(t,e){let n=dV(prt(t,e));return n!==null&&n!==process.pid}function mrt(t,e){lrt(prt(t,e),uDn)}var uDn,frt=A(()=>{"use strict";bw();uDn=2e3});function pV(t,e){let n=t.apps[lDn];return n===void 0&&e===null?null:{...e??{},plugins:structuredClone(n?.plugins??{}),marketplaces:structuredClone(n?.marketplaces??{})}}var lDn,xAe=A(()=>{"use strict";Rc();pB();lDn="app:terminal"});import{join as bAe}from"node:path";function dDn(t,e){let n=t==="user"?mF()?pV(V0(),qF("user").settings):qF("user").settings:j0(bAe(e,p6));return n&&n.plugins&&typeof n.plugins=="object"?n.plugins:{}}function pDn(t,e,n){let r=Object.keys(e);return r.every(i=>n.has(i))?[]:r.filter(i=>!n.has(i)&&hrt(t,i))}function hV(t,e){if(t==="user"&&x6())return[];let n=t!=="user"?bAe(e,"plugins"):hAe("user");if(n===void 0||!Nfe(n))return[];let r=dDn(t,e),i=grt(t,n,r),o=pDn(e,r,new Set(i.map(s=>s.name)));if(o.length===0)return i;for(let s of o)mrt(e,s);return grt(t,n,r)}function grt(t,e,n){let r=[];for(let i of Ofe(e)){let o=bAe(e,i),s=rrt(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 mV=A(()=>{"use strict";Uu();$l();fAe();frt();XR();pB();xAe();xw()});import{existsSync as hDn,realpathSync as mDn}from"node:fs";import{basename as fDn,dirname as gDn,join as xSi,resolve as Art}from"node:path";function mB(t){let e=Art(t),n=e,r=[];for(;!hDn(n);){let i=gDn(n);if(i===n)return e;r.unshift(fDn(n)),n=i}return Art(mDn(n),...r)}var yrt=A(()=>{"use strict"});function ADn(t){let e=qi.indexOf(t);return`less ${qi.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 ${gV[t]}`}function fV(t,e,n){let r=t.indexOf(e),i=r>=0?r:0;return t[(i+n+t.length)%t.length]}function Ert(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 iv(t,e){return t==="true"?!0:t==="false"?!1:`${e} must be true or false`}function brt(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 yDn(t,e){let n=brt(t,e);return typeof n=="string"||n<1?`${e} must be an integer >= 1`:n}function xrt(t,e){let n=t.providerOptions[e];if(n!==void 0)return n;let r={};return t.providerOptions[e]=r,r}function bDn(){let t=[];for(let e of Object.values(Crt))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 gV,wrt,EDn,wDn,VF,Crt,xDn,ISi,CAe=A(()=>{"use strict";Uu();gV={replies:"Replies only",summaries:"Messages + summaries",tools:"Tool calls",previews:"Previews",full:"Full"};wrt=[!1,"notify","apply"],EDn=[0,1,6,12,24,48,72,168],wDn=[1,2,3,4,5,6,8,10,12],VF="openai-codex";Crt={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=fV(wrt,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=fV(wrt,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=Ert(EDn,t.auto_update.interval_hours,e)},setFromString:(t,e)=>{let n=brt(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=Ert(wDn,t.max_panes_per_window,e)},setFromString:(t,e)=>{let n=yDn(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=iv(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=iv(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=iv(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=iv(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:$I.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=fV($I,t.whip_message_mode,e)},setFromString:(t,e)=>$I.includes(e)?(t.whip_message_mode=e,null):`whip_message_mode must be one of: ${$I.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:WI.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=fV(WI,t.mouse_mode_default,e)},setFromString:(t,e)=>WI.includes(e)?(t.mouse_mode_default=e,null):`mouse_mode_default must be one of: ${WI.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=iv(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:qi.join("|"),applies:"Applies on the next attach.",group:"display",order:30,format:t=>t.verbosity,display:t=>ADn(t.verbosity),cycle:(t,e)=>{let n=qi.indexOf(t.verbosity)+e;t.verbosity=qi[Math.max(0,Math.min(qi.length-1,n))]},setFromString:(t,e)=>qi.includes(e)?(t.verbosity=e,null):`verbosity must be one of: ${qi.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=iv(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.${VF}.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[VF]?.fastMode?"on":"off",cycle:t=>{let e=xrt(t,VF);e.fastMode=!e.fastMode},setFromString:(t,e)=>{let n=iv(e,`providerOptions.${VF}.fastMode`);return typeof n=="string"?n:(xrt(t,VF).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:"daemon API listener"},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"}},xDn=Object.keys(Crt);ISi=bDn()});function KF(t){return t.split("-").map(e=>e===""?"":`${e[0].toUpperCase()}${e.slice(1)}`).join("")}function gB(t){try{let e=JSON.stringify(t);return e===void 0?String(t):e}catch{return String(t)}}function fB(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 ${gB(t)}`);return t.trim()}}function _Ae(t,e="page_components"){if(t===void 0)return[];if(!Array.isArray(t))throw new Error(`${e} must be an array; received ${gB(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: ${gB(i)}`);if(u.display!==void 0&&typeof u.display!="boolean")throw new Error(`${e}[${o}].display must be a boolean; offending entry: ${gB(i)}`);s={kind:u.kind.trim(),...fB(u.description,"description",e,o)===void 0?{}:{description:fB(u.description,"description",e,o)},...fB(u.useWhen,"useWhen",e,o)===void 0?{}:{useWhen:fB(u.useWhen,"useWhen",e,o)},...fB(u.doc,"doc",e,o)===void 0?{}:{doc:fB(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: ${gB(i)}`);let a=s.kind;if(!IDn.test(a))throw new Error(`${e}[${o}] has invalid page kind ${gB(a)}; expected /^[a-z][a-z0-9-]{0,63}$/`);if(vDn.has(a)||CDn.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=KF(a);if(AV.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 vrt(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=KF(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 Srt(t,e){return e.find(n=>n.kind===t)}var IAe,CDn,IDn,vDn,Irt,vAe,AV,SAe,YF=A(()=>{"use strict";IAe=["options","text","table","cards","chart"],CDn=["page","step"],IDn=/^[a-z][a-z0-9-]{0,63}$/,vDn=new Set(IAe),Irt=[{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}];vAe=Object.fromEntries(Irt.filter(t=>!t.structural).map(t=>[t.tag,t.kind])),AV=new Set(Irt.map(t=>t.tag)),SAe=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 Brt,join as Drt}from"node:path";import{existsSync as _Dn,mkdirSync as DSi,statSync as MSi}from"node:fs";function kDn(t){return Drt(t,p6)}function TDn(t){return Drt(t,TXe)}function Mrt(t){let e=mB(t),n=mB(ep());if(e===n)return{key:"user",kind:"user",root:n};if(Brt(e)===".crouter")return{key:"project",kind:"project",root:e};for(let r of aV()){let i=mB(sV(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 Prt(t){if(Brt(t)===".crouter"){let r;try{r=mB(t)}catch(i){if(i.code==="ENOENT")return null;throw i}if(r!==mB(ep()))return j0(kDn(t))}let e=Mrt(t).key,n=qF(e).settings;return e==="user"&&mF()?pV(V0(),n):n}function ph(t){let e=RDn[BDn];if(e){if(t!=="user")throw new Error(`broker config snapshot has no ${t} scope`);return e.user}let n=Y0(t);return n?DDn(n):m6()}function DDn(t){let e=Prt(t);return e?o1n(e):m6()}function MDn(t){let e=j0(TDn(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 Nrt(t){let e=Y0(t);return e?t==="project"?_Dn(e)?MDn(e):_fe():Ytt(Mrt(e).key):_fe()}function PDn(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 AB(t){return t===void 0?[...ODn]:Array.isArray(t)?[...new Set(t.filter(e=>typeof e=="string"&&FI.has(e)&&NDn.has(e)))]:[]}function LDn(t,e=Sfe()){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 Ort(t){return t==="ultra"||t==="strong"||t==="medium"||t==="light"}function kAe(){return Object.create(null)}function yV(t,e,n){Object.defineProperty(t,e,{value:n,writable:!0,enumerable:!0,configurable:!0})}function FDn(t){let e=kAe();for(let[n,r]of Object.entries(t??{}))yV(e,n,r);return e}function JF(t,e){Gl({level:"warn",event:"config.model_routes.invalid",fields:{route_id:t,rule:e}})}function UDn(t,e={}){let n=FDn(e);if(t===null||typeof t!="object"||Array.isArray(t))return n;for(let[r,i]of Object.entries(t)){if(r.trim()===""){JF(r,"route id must be a non-empty string");continue}if(i===null||typeof i!="object"||Array.isArray(i)){JF(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(!Ort(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){JF(r,c);continue}yV(n,r,a)}return n}function $Dn(t){let e=kAe(),n=kAe();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){JF(r,"route must include family, credentialSource, providerId, and models");continue}let o=QDn.filter(s=>i.models[s]===void 0);if(o.length>0){JF(r,`incomplete route; missing strengths: ${o.join(", ")}`),yV(n,r,{family:i.family,credentialSource:i.credentialSource,providerId:i.providerId,models:i.models});continue}yV(e,r,{family:i.family,credentialSource:i.credentialSource,providerId:i.providerId,models:i.models})}return{complete:e,legacy:n}}function WDn(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=>Ort(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 HDn(t){return t!==""&&t.replace(/\*/g,"")===""}function GDn(t,e=[]){let n=t,r=Array.isArray(n?.allow)?n.allow.filter(i=>typeof i=="string"):[];for(let i of r)if(HDn(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 qDn(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 zDn(t,e){if(e==="bin"&&jDn.has(t))return`${e}.${t} is reserved by crouter \u2014 pick another bare command name`;if(!_rt.test(t))return`${e}.${t} is not a safe bare command name (expected ${_rt.source})`}function VDn(t){if(t===null||typeof t!="object"||Array.isArray(t))return{};let e={};for(let[n,r]of Object.entries(t))zDn(n,"bin")===void 0&&(typeof r!="string"||r.trim()===""||(e[n]=r));return e}function KDn(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(krt.test(n)||i.push(`action name must match ${krt.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 YDn(t){if(t===null||typeof t!="object"||Array.isArray(t))return{};let e=new Set(KDn(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 JDn(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 XDn(t,e=vfe()){let n={...e};if(t!==null&&typeof t=="object")for(let[r,i]of Object.entries(t)){let o=JDn(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 wV(){let t=[{origin:"config.json",components:ph("user").page_components}],e=Y0("user");if(e!==null){let n=hV("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:_Ae(r.manifest.page_components,i)})}}return vrt(t)}function ZDn(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 e1n(t,e=Ife()){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=ZDn(o);s!==null&&(n[i]=s)}}return{targets:n}}function Trt(t,e){return t===!0?"notify":t===!1?!1:t==="notify"||t==="apply"?t:e}function EV(t,e){return typeof t=="number"&&Number.isSafeInteger(t)&&t>=1?t:e}function t1n(t,e){let n=t!==null&&typeof t=="object"?t:{},r=EV(n.warning,e.warning),i=EV(n.automaticReviveCap,e.automaticReviveCap);return r<=i?{warning:r,automaticReviveCap:i}:{...e}}function n1n(t,e){return{unattendedParkMs:EV((t!==null&&typeof t=="object"?t:{}).unattendedParkMs,e.unattendedParkMs)}}function r1n(t){if(!Array.isArray(t))return[...h6];let e=t.filter(n=>typeof n=="string"&&n.trim()!=="").map(n=>n.trim());return e.length>0?e:[...h6]}function i1n(t,e){if(t===null||typeof t!="object")return{...e};let n=t.tcp;return{tcp:typeof n=="string"?n:e.tcp}}function o1n(t){!Rrt&&t.ledger!==void 0&&(Rrt=!0,Gl({level:"warn",event:"config.ledger.ignored",fields:{variables:Object.values(Utt)}}));let e=m6(),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:Trt(o?.crtr,e.auto_update.crtr),content:Trt(o?.content,e.auto_update.content),interval_hours:a},u=t.max_panes_per_window,l=EV(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=t1n(t.brokerThresholds,e.brokerThresholds),h=n1n(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]:vXe(t.working_gerunds),g=typeof t.whip_mode=="boolean"?t.whip_mode:e.whip_mode,y=_Ae(t.page_components),x=typeof t.page_surface=="boolean"?t.page_surface:e.page_surface,b=r1n(t.whip_messages),v=$I.includes(t.whip_message_mode)?t.whip_message_mode:e.whip_message_mode,S=WI.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=qi.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=PDn(t.keybindings),Q=AB(t.tmux_passthrough),$=LDn(t.modelLadders),j=qDn(t.providerOptions,e.providerOptions),W=$Dn(UDn(t.modelRoutes)),de=W.complete,ee=WDn(t.modelRouting,void 0),Ae=XDn(t.kinds),Ie=e1n(t.remoteCanvas),Ue=i1n(t.api,e.api),Et=t.paths;if(Et?.user_files!==void 0&&(typeof Et.user_files!="string"||!Et.user_files.startsWith("/")))throw new Error("paths.user_files must be an absolute path");let Ze=t.store,wt=t.runtime;if(wt?.person_uids!==void 0&&(!Array.isArray(wt.person_uids)||!wt.person_uids.every($t=>Number.isSafeInteger($t)&&$t>=0)))throw new Error("runtime.person_uids must be an array of nonnegative integer uids");let te=GDn(t.spawnEnv,e.spawnEnv?.allow),it=VDn(t.bin),at=YDn(t.humanActions);return{bin:it,humanActions:at,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:y,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:Q,modelLadders:$,providerOptions:j,...Object.keys(de).length>0?{modelRoutes:de}:{},...Object.keys(W.legacy).length>0?{legacyModelRoutes:W.legacy}:{},...ee!==void 0?{modelRouting:ee}:{},kinds:Ae,remoteCanvas:Ie,api:Ue,...Et?{paths:Et}:{},...Ze?{store:Ze}:{},...wt?{runtime:wt}:{},spawnEnv:te}}function s1n(t){return Prt(t)}function Lrt(t){let e=Y0(t);return e?s1n(e):null}var RDn,BDn,NDn,ODn,QDn,_rt,jDn,krt,Rrt,Yd=A(()=>{"use strict";Rc();Uu();u6();Ul();ev();$tt();$l();xw();mV();nv();yrt();pB();xAe();bw();CAe();d6();YF();RDn=globalThis,BDn=Symbol.for("crtr.broker.config-snapshot");NDn=new Set(jd.filter(bF).map(t=>t.id)),ODn=Object.freeze(["crtr.attach.scroll.up","crtr.attach.scroll.down","crtr.attach.scroll.page-up","crtr.attach.scroll.page-down","crtr.attach.scroll.live"]);QDn=["ultra","strong","medium","light"];_rt=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,jDn=new Set(["crtr","crtrd"]);krt=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;Rrt=!1});var Z0=L((Y_i,rit)=>{"use strict";var tit=["nodebuffer","arraybuffer","fragments"],nit=typeof Blob<"u";nit&&tit.push("blob");rit.exports={BINARY_TYPES:tit,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:nit,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var iU=L((J_i,IV)=>{"use strict";var{EMPTY_BUFFER:Z1n}=Z0(),e0e=Buffer[Symbol.species];function eMn(t,e){if(t.length===0)return Z1n;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 e0e(n.buffer,n.byteOffset,r):n}function iit(t,e,n,r,i){for(let o=0;o<i;o++)n[r+o]=t[o]^e[o&3]}function oit(t,e){for(let n=0;n<t.length;n++)t[n]^=e[n&3]}function tMn(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function t0e(t){if(t0e.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new e0e(t):ArrayBuffer.isView(t)?e=new e0e(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),t0e.readOnly=!1),e}IV.exports={concat:eMn,mask:iit,toArrayBuffer:tMn,toBuffer:t0e,unmask:oit};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=Y("bufferutil");IV.exports.mask=function(e,n,r,i,o){o<48?iit(e,n,r,i,o):t.mask(e,n,r,i,o)},IV.exports.unmask=function(e,n){e.length<32?oit(e,n):t.unmask(e,n)}}catch{}});var cit=L((X_i,ait)=>{"use strict";var sit=Symbol("kDone"),n0e=Symbol("kRun"),r0e=class{constructor(e){this[sit]=()=>{this.pending--,this[n0e]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[n0e]()}[n0e](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[sit])}}};ait.exports=r0e});var vB=L((Z_i,pit)=>{"use strict";var oU=Y("zlib"),uit=iU(),nMn=cit(),{kStatusCode:lit}=Z0(),rMn=Buffer[Symbol.species],iMn=Buffer.from([0,0,255,255]),SV=Symbol("permessage-deflate"),ey=Symbol("total-length"),CB=Symbol("callback"),vw=Symbol("buffers"),IB=Symbol("error"),vV,i0e=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,!vV){let n=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;vV=new nMn(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[CB];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){vV.add(i=>{this._decompress(e,n,(o,s)=>{i(),r(o,s)})})}compress(e,n,r){vV.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"?oU.Z_DEFAULT_WINDOWBITS:this.params[o];this._inflate=oU.createInflateRaw({...this._options.zlibInflateOptions,windowBits:s}),this._inflate[SV]=this,this._inflate[ey]=0,this._inflate[vw]=[],this._inflate.on("error",sMn),this._inflate.on("data",dit)}this._inflate[CB]=r,this._inflate.write(e),n&&this._inflate.write(iMn),this._inflate.flush(()=>{let o=this._inflate[IB];if(o){this._inflate.close(),this._inflate=null,r(o);return}let s=uit.concat(this._inflate[vw],this._inflate[ey]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[ey]=0,this._inflate[vw]=[],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"?oU.Z_DEFAULT_WINDOWBITS:this.params[o];this._deflate=oU.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:s}),this._deflate[ey]=0,this._deflate[vw]=[],this._deflate.on("data",oMn)}this._deflate[CB]=r,this._deflate.write(e),this._deflate.flush(oU.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let o=uit.concat(this._deflate[vw],this._deflate[ey]);n&&(o=new rMn(o.buffer,o.byteOffset,o.length-4)),this._deflate[CB]=null,this._deflate[ey]=0,this._deflate[vw]=[],n&&this.params[`${i}_no_context_takeover`]&&this._deflate.reset(),r(null,o)})}};pit.exports=i0e;function oMn(t){this[vw].push(t),this[ey]+=t.length}function dit(t){if(this[ey]+=t.length,this[SV]._maxPayload<1||this[ey]<=this[SV]._maxPayload){this[vw].push(t);return}this[IB]=new RangeError("Max payload size exceeded"),this[IB].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[IB][lit]=1009,this.removeListener("data",dit),this.reset()}function sMn(t){if(this[SV]._inflate=null,this[IB]){this[CB](this[IB]);return}t[lit]=1007,this[CB](t)}});var SB=L((eki,_V)=>{"use strict";var{isUtf8:hit}=Y("buffer"),{hasBlob:aMn}=Z0(),cMn=[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 uMn(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function o0e(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 lMn(t){return aMn&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}_V.exports={isBlob:lMn,isValidStatusCode:uMn,isValidUTF8:o0e,tokenChars:cMn};if(hit)_V.exports.isValidUTF8=function(t){return t.length<24?o0e(t):hit(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=Y("utf-8-validate");_V.exports.isValidUTF8=function(e){return e.length<32?o0e(e):t(e)}}catch{}});var l0e=L((tki,wit)=>{"use strict";var{Writable:dMn}=Y("stream"),mit=vB(),{BINARY_TYPES:pMn,EMPTY_BUFFER:fit,kStatusCode:hMn,kWebSocket:mMn}=Z0(),{concat:s0e,toArrayBuffer:fMn,unmask:gMn}=iU(),{isValidStatusCode:AMn,isValidUTF8:git}=SB(),kV=Buffer[Symbol.species],fh=0,Ait=1,yit=2,Eit=3,a0e=4,c0e=5,TV=6,u0e=class extends dMn{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||pMn[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[mMn]=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=fh}_write(e,n,r){if(this._opcode===8&&this._state==fh)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 kV(r.buffer,r.byteOffset+e,r.length-e),new kV(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 kV(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 fh:this.getInfo(e);break;case Ait:this.getPayloadLength16(e);break;case yit:this.getPayloadLength64(e);break;case Eit:this.getMask();break;case a0e:this.getData(e);break;case c0e:case TV: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[mit.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=Ait:this._payloadLength===127?this._state=yit: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=Eit:this._state=a0e}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=a0e}getData(e){let n=fit;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&&gMn(n,this._mask)}if(this._opcode>7){this.controlMessage(n,e);return}if(this._compressed){this._state=c0e,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[mit.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===fh&&this.startLoop(n)})}dataMessage(e){if(!this._fin){this._state=fh;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=s0e(r,n):this._binaryType==="arraybuffer"?i=fMn(s0e(r,n)):this._binaryType==="blob"?i=new Blob(r):i=r,this._allowSynchronousEvents?(this.emit("message",i,!0),this._state=fh):(this._state=TV,setImmediate(()=>{this.emit("message",i,!0),this._state=fh,this.startLoop(e)}))}else{let i=s0e(r,n);if(!this._skipUTF8Validation&&!git(i)){let o=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(o);return}this._state===c0e||this._allowSynchronousEvents?(this.emit("message",i,!1),this._state=fh):(this._state=TV,setImmediate(()=>{this.emit("message",i,!1),this._state=fh,this.startLoop(e)}))}}controlMessage(e,n){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,fit),this.end();else{let r=e.readUInt16BE(0);if(!AMn(r)){let o=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");n(o);return}let i=new kV(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!git(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=fh;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=fh):(this._state=TV,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=fh,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[hMn]=i,s}};wit.exports=u0e});var h0e=L((rki,Cit)=>{"use strict";var{Duplex:nki}=Y("stream"),{randomFillSync:yMn}=Y("crypto"),{types:{isUint8Array:EMn}}=Y("util"),xit=vB(),{EMPTY_BUFFER:wMn,kWebSocket:xMn,NOOP:bMn}=Z0(),{isBlob:_B,isValidStatusCode:CMn}=SB(),{mask:bit,toBuffer:cv}=iU(),gh=Symbol("kByteLength"),IMn=Buffer.alloc(4),RV=8*1024,uv,kB=RV,tf=0,vMn=1,SMn=2,d0e=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=tf,this.onerror=bMn,this[xMn]=void 0}static frame(e,n){let r,i=!1,o=2,s=!1;n.mask&&(r=n.maskBuffer||IMn,n.generateMask?n.generateMask(r):(kB===RV&&(uv===void 0&&(uv=Buffer.alloc(RV)),yMn(uv,0,RV),kB=0),r[0]=uv[kB++],r[1]=uv[kB++],r[2]=uv[kB++],r[3]=uv[kB++]),s=(r[0]|r[1]|r[2]|r[3])===0,o=6);let a;typeof e=="string"?(!n.mask||s)&&n[gh]!==void 0?a=n[gh]:(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?(bit(e,r,u,o,a),[u]):(bit(e,r,e,0,a),[u,e])):[u,e]}close(e,n,r,i){let o;if(e===void 0)o=wMn;else{if(typeof e!="number"||!CMn(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(EMn(n))o.set(n,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let s={[gh]:o.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==tf?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):_B(e)?(i=e.size,o=!1):(e=cv(e),i=e.length,o=cv.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");let s={[gh]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:o,rsv1:!1};_B(e)?this._state!==tf?this.enqueue([this.getBlobData,e,!1,s,r]):this.getBlobData(e,!1,s,r):this._state!==tf?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):_B(e)?(i=e.size,o=!1):(e=cv(e),i=e.length,o=cv.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");let s={[gh]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:o,rsv1:!1};_B(e)?this._state!==tf?this.enqueue([this.getBlobData,e,!1,s,r]):this.getBlobData(e,!1,s,r):this._state!==tf?this.enqueue([this.dispatch,e,!1,s,r]):this.sendFrame(t.frame(e,s),r)}send(e,n,r){let i=this._extensions[xit.extensionName],o=n.binary?2:1,s=n.compress,a,c;typeof e=="string"?(a=Buffer.byteLength(e),c=!1):_B(e)?(a=e.size,c=!1):(e=cv(e),a=e.length,c=cv.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={[gh]:a,fin:n.fin,generateMask:this._generateMask,mask:n.mask,maskBuffer:this._maskBuffer,opcode:o,readOnly:c,rsv1:s};_B(e)?this._state!==tf?this.enqueue([this.getBlobData,e,this._compress,u,r]):this.getBlobData(e,this._compress,u,r):this._state!==tf?this.enqueue([this.dispatch,e,this._compress,u,r]):this.dispatch(e,this._compress,u,r)}getBlobData(e,n,r,i){this._bufferedBytes+=r[gh],this._state=SMn,e.arrayBuffer().then(o=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(p0e,this,a,i);return}this._bufferedBytes-=r[gh];let s=cv(o);n?this.dispatch(s,n,r,i):(this._state=tf,this.sendFrame(t.frame(s,r),i),this.dequeue())}).catch(o=>{process.nextTick(_Mn,this,o,i)})}dispatch(e,n,r,i){if(!n){this.sendFrame(t.frame(e,r),i);return}let o=this._extensions[xit.extensionName];this._bufferedBytes+=r[gh],this._state=vMn,o.compress(e,r.fin,(s,a)=>{if(this._socket.destroyed){let c=new Error("The socket was closed while data was being compressed");p0e(this,c,i);return}this._bufferedBytes-=r[gh],this._state=tf,r.readOnly=!1,this.sendFrame(t.frame(a,r),i),this.dequeue()})}dequeue(){for(;this._state===tf&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][gh],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][gh],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)}};Cit.exports=d0e;function p0e(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 _Mn(t,e,n){p0e(t,e,n),t.onerror(e)}});var Dit=L((iki,Bit)=>{"use strict";var{kForOnEventAttribute:sU,kListener:m0e}=Z0(),Iit=Symbol("kCode"),vit=Symbol("kData"),Sit=Symbol("kError"),_it=Symbol("kMessage"),kit=Symbol("kReason"),TB=Symbol("kTarget"),Tit=Symbol("kType"),Rit=Symbol("kWasClean"),ty=class{constructor(e){this[TB]=null,this[Tit]=e}get target(){return this[TB]}get type(){return this[Tit]}};Object.defineProperty(ty.prototype,"target",{enumerable:!0});Object.defineProperty(ty.prototype,"type",{enumerable:!0});var lv=class extends ty{constructor(e,n={}){super(e),this[Iit]=n.code===void 0?0:n.code,this[kit]=n.reason===void 0?"":n.reason,this[Rit]=n.wasClean===void 0?!1:n.wasClean}get code(){return this[Iit]}get reason(){return this[kit]}get wasClean(){return this[Rit]}};Object.defineProperty(lv.prototype,"code",{enumerable:!0});Object.defineProperty(lv.prototype,"reason",{enumerable:!0});Object.defineProperty(lv.prototype,"wasClean",{enumerable:!0});var RB=class extends ty{constructor(e,n={}){super(e),this[Sit]=n.error===void 0?null:n.error,this[_it]=n.message===void 0?"":n.message}get error(){return this[Sit]}get message(){return this[_it]}};Object.defineProperty(RB.prototype,"error",{enumerable:!0});Object.defineProperty(RB.prototype,"message",{enumerable:!0});var aU=class extends ty{constructor(e,n={}){super(e),this[vit]=n.data===void 0?null:n.data}get data(){return this[vit]}};Object.defineProperty(aU.prototype,"data",{enumerable:!0});var kMn={addEventListener(t,e,n={}){for(let i of this.listeners(t))if(!n[sU]&&i[m0e]===e&&!i[sU])return;let r;if(t==="message")r=function(o,s){let a=new aU("message",{data:s?o:o.toString()});a[TB]=this,BV(e,this,a)};else if(t==="close")r=function(o,s){let a=new lv("close",{code:o,reason:s.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[TB]=this,BV(e,this,a)};else if(t==="error")r=function(o){let s=new RB("error",{error:o,message:o.message});s[TB]=this,BV(e,this,s)};else if(t==="open")r=function(){let o=new ty("open");o[TB]=this,BV(e,this,o)};else return;r[sU]=!!n[sU],r[m0e]=e,n.once?this.once(t,r):this.on(t,r)},removeEventListener(t,e){for(let n of this.listeners(t))if(n[m0e]===e&&!n[sU]){this.removeListener(t,n);break}}};Bit.exports={CloseEvent:lv,ErrorEvent:RB,Event:ty,EventTarget:kMn,MessageEvent:aU};function BV(t,e,n){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,n):t.call(e,n)}});var DV=L((oki,Mit)=>{"use strict";var{tokenChars:cU}=SB();function Pg(t,e,n){t[e]===void 0?t[e]=[n]:t[e].push(n)}function TMn(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&&cU[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?(Pg(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&&cU[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),Pg(n,t.slice(c,l),!0),u===44&&(Pg(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(cU[u]!==1)throw new SyntaxError(`Unexpected character at index ${d}`);c===-1?c=d:r||(r=!0),i=!1}else if(o)if(cU[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&&cU[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),Pg(n,a,h),u===44&&(Pg(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?Pg(e,p,n):(a===void 0?Pg(n,p,!0):r?Pg(n,a,p.replace(/\\/g,"")):Pg(n,a,p),Pg(e,s,n)),e}function RMn(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(", ")}Mit.exports={format:RMn,parse:TMn}});var OV=L((cki,qit)=>{"use strict";var BMn=Y("events"),DMn=Y("https"),MMn=Y("http"),Oit=Y("net"),PMn=Y("tls"),{randomBytes:NMn,createHash:OMn}=Y("crypto"),{Duplex:ski,Readable:aki}=Y("stream"),{URL:f0e}=Y("url"),Sw=vB(),LMn=l0e(),QMn=h0e(),{isBlob:FMn}=SB(),{BINARY_TYPES:Pit,CLOSE_TIMEOUT:UMn,EMPTY_BUFFER:MV,GUID:$Mn,kForOnEventAttribute:g0e,kListener:WMn,kStatusCode:HMn,kWebSocket:Xa,NOOP:Lit}=Z0(),{EventTarget:{addEventListener:GMn,removeEventListener:qMn}}=Dit(),{format:jMn,parse:zMn}=DV(),{toBuffer:VMn}=iU(),Qit=Symbol("kAborted"),A0e=[8,13],ny=["CONNECTING","OPEN","CLOSING","CLOSED"],KMn=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,qo=class t extends BMn{constructor(e,n,r){super(),this._binaryType=Pit[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=MV,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]),Fit(this,e,n,r)):(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Pit.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 LMn({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 QMn(e,this._extensions,r.generateMask);this._receiver=i,this._sender=o,this._socket=e,i[Xa]=this,o[Xa]=this,e[Xa]=this,i.on("conclude",XMn),i.on("drain",ZMn),i.on("error",ePn),i.on("message",tPn),i.on("ping",nPn),i.on("pong",rPn),o.onerror=iPn,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),n.length>0&&e.unshift(n),e.on("close",Wit),e.on("data",NV),e.on("end",Hit),e.on("error",Git),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[Sw.extensionName]&&this._extensions[Sw.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){tp(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())}),$it(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){y0e(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(e||MV,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){y0e(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(e||MV,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){y0e(this,e,r);return}let i={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[Sw.extensionName]||(i.compress=!1),this._sender.send(e||MV,i,r)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){tp(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(qo,"CONNECTING",{enumerable:!0,value:ny.indexOf("CONNECTING")});Object.defineProperty(qo.prototype,"CONNECTING",{enumerable:!0,value:ny.indexOf("CONNECTING")});Object.defineProperty(qo,"OPEN",{enumerable:!0,value:ny.indexOf("OPEN")});Object.defineProperty(qo.prototype,"OPEN",{enumerable:!0,value:ny.indexOf("OPEN")});Object.defineProperty(qo,"CLOSING",{enumerable:!0,value:ny.indexOf("CLOSING")});Object.defineProperty(qo.prototype,"CLOSING",{enumerable:!0,value:ny.indexOf("CLOSING")});Object.defineProperty(qo,"CLOSED",{enumerable:!0,value:ny.indexOf("CLOSED")});Object.defineProperty(qo.prototype,"CLOSED",{enumerable:!0,value:ny.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(qo.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(qo.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[g0e])return e[WMn];return null},set(e){for(let n of this.listeners(t))if(n[g0e]){this.removeListener(t,n);break}typeof e=="function"&&this.addEventListener(t,e,{[g0e]:!0})}})});qo.prototype.addEventListener=GMn;qo.prototype.removeEventListener=qMn;qit.exports=qo;function Fit(t,e,n,r){let i={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:UMn,protocolVersion:A0e[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,!A0e.includes(i.protocolVersion))throw new RangeError(`Unsupported protocol version: ${i.protocolVersion} (supported versions: ${A0e.join(", ")})`);let o;if(e instanceof f0e)o=e;else try{o=new f0e(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;PV(t,f);return}let u=s?443:80,l=NMn(16).toString("base64"),d=s?DMn.request:MMn.request,p=new Set,h;if(i.createConnection=i.createConnection||(s?JMn:YMn),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 Sw({...i.perMessageDeflate,isServer:!1,maxPayload:i.maxPayload}),i.headers["Sec-WebSocket-Extensions"]=jMn({[Sw.extensionName]:h.offer()})),n.length){for(let f of n){if(typeof f!="string"||!KMn.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,y]of Object.entries(f))r.headers[g.toLowerCase()]=y}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",()=>{tp(t,m,"Opening handshake has timed out")}),m.on("error",f=>{m===null||m[Qit]||(m=t._req=null,PV(t,f))}),m.on("response",f=>{let g=f.headers.location,y=f.statusCode;if(g&&i.followRedirects&&y>=300&&y<400){if(++t._redirects>i.maxRedirects){tp(t,m,"Maximum redirects exceeded");return}m.abort();let x;try{x=new f0e(g,e)}catch{let v=new SyntaxError(`Invalid URL: ${g}`);PV(t,v);return}Fit(t,x,n,r)}else t.emit("unexpected-response",m,f)||tp(t,m,`Unexpected server response: ${f.statusCode}`)}),m.on("upgrade",(f,g,y)=>{if(t.emit("upgrade",f),t.readyState!==qo.CONNECTING)return;m=t._req=null;let x=f.headers.upgrade;if(x===void 0||x.toLowerCase()!=="websocket"){tp(t,g,"Invalid Upgrade header");return}let b=OMn("sha1").update(l+$Mn).digest("base64");if(f.headers["sec-websocket-accept"]!==b){tp(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){tp(t,g,S);return}v&&(t._protocol=v);let _=f.headers["sec-websocket-extensions"];if(_!==void 0){if(!h){tp(t,g,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let T;try{T=zMn(_)}catch{tp(t,g,"Invalid Sec-WebSocket-Extensions header");return}let B=Object.keys(T);if(B.length!==1||B[0]!==Sw.extensionName){tp(t,g,"Server indicated an extension that was not requested");return}try{h.accept(T[Sw.extensionName])}catch{tp(t,g,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[Sw.extensionName]=h}t.setSocket(g,y,{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 PV(t,e){t._readyState=qo.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function YMn(t){return t.path=t.socketPath,Oit.connect(t)}function JMn(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=Oit.isIP(t.host)?"":t.host),PMn.connect(t)}function tp(t,e,n){t._readyState=qo.CLOSING;let r=new Error(n);Error.captureStackTrace(r,tp),e.setHeader?(e[Qit]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(PV,t,r)):(e.destroy(r),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function y0e(t,e,n){if(e){let r=FMn(e)?e.size:VMn(e).length;t._socket?t._sender._bufferedBytes+=r:t._bufferedAmount+=r}if(n){let r=new Error(`WebSocket is not open: readyState ${t.readyState} (${ny[t.readyState]})`);process.nextTick(n,r)}}function XMn(t,e){let n=this[Xa];n._closeFrameReceived=!0,n._closeMessage=e,n._closeCode=t,n._socket[Xa]!==void 0&&(n._socket.removeListener("data",NV),process.nextTick(Uit,n._socket),t===1005?n.close():n.close(t,e))}function ZMn(){let t=this[Xa];t.isPaused||t._socket.resume()}function ePn(t){let e=this[Xa];e._socket[Xa]!==void 0&&(e._socket.removeListener("data",NV),process.nextTick(Uit,e._socket),e.close(t[HMn])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function Nit(){this[Xa].emitClose()}function tPn(t,e){this[Xa].emit("message",t,e)}function nPn(t){let e=this[Xa];e._autoPong&&e.pong(t,!this._isServer,Lit),e.emit("ping",t)}function rPn(t){this[Xa].emit("pong",t)}function Uit(t){t.resume()}function iPn(t){let e=this[Xa];e.readyState!==qo.CLOSED&&(e.readyState===qo.OPEN&&(e._readyState=qo.CLOSING,$it(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function $it(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function Wit(){let t=this[Xa];if(this.removeListener("close",Wit),this.removeListener("data",NV),this.removeListener("end",Hit),t._readyState=qo.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[Xa]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",Nit),t._receiver.on("finish",Nit))}function NV(t){this[Xa]._receiver.write(t)||this.pause()}function Hit(){let t=this[Xa];t._readyState=qo.CLOSING,t._receiver.end(),this.end()}function Git(){let t=this[Xa];this.removeListener("error",Git),this.on("error",Lit),t&&(t._readyState=qo.CLOSING,this.destroy())}});var Kit=L((lki,Vit)=>{"use strict";var uki=OV(),{Duplex:oPn}=Y("stream");function jit(t){t.emit("close")}function sPn(){!this.destroyed&&this._writableState.finished&&this.destroy()}function zit(t){this.removeListener("error",zit),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function aPn(t,e){let n=!0,r=new oPn({...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(jit,r);return}let s=!1;t.once("error",function(c){s=!0,o(c)}),t.once("close",function(){s||o(i),process.nextTick(jit,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",sPn),r.on("error",zit),r}Vit.exports=aPn});var E0e=L((dki,Yit)=>{"use strict";var{tokenChars:cPn}=SB();function uPn(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&&cPn[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}Yit.exports={parse:uPn}});var rot=L((hki,not)=>{"use strict";var lPn=Y("events"),LV=Y("http"),{Duplex:pki}=Y("stream"),{createHash:dPn}=Y("crypto"),Jit=DV(),dv=vB(),pPn=E0e(),hPn=OV(),{CLOSE_TIMEOUT:mPn,GUID:fPn,kWebSocket:gPn}=Z0(),APn=/^[+/0-9A-Za-z]{22}==$/,Xit=0,Zit=1,tot=2,w0e=class extends lPn{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:mPn,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:hPn,...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=LV.createServer((r,i)=>{let o=LV.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=yPn(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=Xit}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===tot){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(uU,this);return}if(e&&this.once("close",e),this._state!==Zit)if(this._state=Zit,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(uU,this):process.nextTick(uU,this);else{let n=this._server;this._removeListeners(),this._removeListeners=this._server=null,n.close(()=>{uU(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",eot);let o=e.headers["sec-websocket-key"],s=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){pv(this,e,n,405,"Invalid HTTP method");return}if(s===void 0||s.toLowerCase()!=="websocket"){pv(this,e,n,400,"Invalid Upgrade header");return}if(o===void 0||!APn.test(o)){pv(this,e,n,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){pv(this,e,n,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){lU(n,400);return}let c=e.headers["sec-websocket-protocol"],u=new Set;if(c!==void 0)try{u=pPn.parse(c)}catch{pv(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 dv({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let h=Jit.parse(l);h[dv.extensionName]&&(p.accept(h[dv.extensionName]),d[dv.extensionName]=p)}catch{pv(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 lU(n,m||401,f,g);this.completeUpgrade(d,o,u,e,n,r,i)});return}if(!this.options.verifyClient(p))return lU(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[gPn])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Xit)return lU(o,503);let u=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${dPn("sha1").update(n+fPn).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[dv.extensionName]){let d=e[dv.extensionName].params,p=Jit.format({[dv.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",eot),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(uU,this)})),a(l,i)}};not.exports=w0e;function yPn(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 uU(t){t._state=tot,t.emit("close")}function eot(){this.destroy()}function lU(t,e,n,r){n=n||LV.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} ${LV.STATUS_CODES[e]}\r
103
103
  `+Object.keys(r).map(i=>`${i}: ${r[i]}`).join(`\r