blink 0.1.96 → 0.1.97

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli/index.js CHANGED
@@ -17,6 +17,6 @@ Expecting one of '${n.join(`', '`)}'`);return this._lifeCycleHooks[e]?this._life
17
17
  - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
18
18
  - ${r}`;throw Error(i)}_executeSubCommand(e,t){t=t.slice();let n=!1,s=[`.js`,`.ts`,`.tsx`,`.mjs`,`.cjs`];function c(e,t){let n=i.resolve(e,t);if(a.existsSync(n))return n;if(s.includes(i.extname(t)))return;let r=s.find(e=>a.existsSync(`${n}${e}`));if(r)return`${n}${r}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let u=e._executableFile||`${this._name}-${e._name}`,d=this._executableDir||``;if(this._scriptPath){let e;try{e=a.realpathSync(this._scriptPath)}catch{e=this._scriptPath}d=i.resolve(i.dirname(e),d)}if(d){let t=c(d,u);if(!t&&!e._executableFile&&this._scriptPath){let n=i.basename(this._scriptPath,i.extname(this._scriptPath));n!==this._name&&(t=c(d,`${n}-${e._name}`))}u=t||u}n=s.includes(i.extname(u));let f;o.platform===`win32`?(this._checkForMissingExecutable(u,d,e._name),t.unshift(u),t=g(o.execArgv).concat(t),f=r.spawn(o.execPath,t,{stdio:`inherit`})):n?(t.unshift(u),t=g(o.execArgv).concat(t),f=r.spawn(o.argv[0],t,{stdio:`inherit`})):f=r.spawn(u,t,{stdio:`inherit`}),f.killed||[`SIGUSR1`,`SIGUSR2`,`SIGTERM`,`SIGINT`,`SIGHUP`].forEach(e=>{o.on(e,()=>{f.killed===!1&&f.exitCode===null&&f.kill(e)})});let p=this._exitCallback;f.on(`close`,e=>{e??=1,p?p(new l(e,`commander.executeSubCommandAsync`,`(close)`)):o.exit(e)}),f.on(`error`,t=>{if(t.code===`ENOENT`)this._checkForMissingExecutable(u,d,e._name);else if(t.code===`EACCES`)throw Error(`'${u}' not executable`);if(!p)o.exit(1);else{let e=new l(1,`commander.executeSubCommandAsync`,`(error)`);e.nestedError=t,p(e)}}),this.runningCommand=f}_dispatchSubcommand(e,t,n){let r=this._findCommand(e);r||this.help({error:!0}),r._prepareForParse();let i;return i=this._chainOrCallSubCommandHook(i,r,`preSubcommand`),i=this._chainOrCall(i,()=>{if(r._executableHandler)this._executeSubCommand(r,t.concat(n));else return r._parseCommand(t,n)}),i}_dispatchHelpCommand(e){e||this.help();let t=this._findCommand(e);return t&&!t._executableHandler&&t.help(),this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??`--help`])}_checkNumberOfArguments(){this.registeredArguments.forEach((e,t)=>{e.required&&this.args[t]==null&&this.missingArgument(e.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let e=(e,t,n)=>{let r=t;if(t!==null&&e.parseArg){let i=`error: command-argument value '${t}' is invalid for argument '${e.name()}'.`;r=this._callParseArg(e,t,n,i)}return r};this._checkNumberOfArguments();let t=[];this.registeredArguments.forEach((n,r)=>{let i=n.defaultValue;n.variadic?r<this.args.length?(i=this.args.slice(r),n.parseArg&&(i=i.reduce((t,r)=>e(n,r,t),n.defaultValue))):i===void 0&&(i=[]):r<this.args.length&&(i=this.args[r],n.parseArg&&(i=e(n,i,n.defaultValue))),t[r]=i}),this.processedArgs=t}_chainOrCall(e,t){return e?.then&&typeof e.then==`function`?e.then(()=>t()):t()}_chainOrCallHooks(e,t){let n=e,r=[];return this._getCommandAndAncestors().reverse().filter(e=>e._lifeCycleHooks[t]!==void 0).forEach(e=>{e._lifeCycleHooks[t].forEach(t=>{r.push({hookedCommand:e,callback:t})})}),t===`postAction`&&r.reverse(),r.forEach(e=>{n=this._chainOrCall(n,()=>e.callback(e.hookedCommand,this))}),n}_chainOrCallSubCommandHook(e,t,n){let r=e;return this._lifeCycleHooks[n]!==void 0&&this._lifeCycleHooks[n].forEach(e=>{r=this._chainOrCall(r,()=>e(this,t))}),r}_parseCommand(e,t){let n=this.parseOptions(t);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(n.operands),t=n.unknown,this.args=e.concat(t),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),t);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(t),this._dispatchSubcommand(this._defaultCommandName,e,t);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(n.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let r=()=>{n.unknown.length>0&&this.unknownOption(n.unknown[0])},i=`command:${this.name()}`;if(this._actionHandler){r(),this._processArguments();let n;return n=this._chainOrCallHooks(n,`preAction`),n=this._chainOrCall(n,()=>this._actionHandler(this.processedArgs)),this.parent&&(n=this._chainOrCall(n,()=>{this.parent.emit(i,e,t)})),n=this._chainOrCallHooks(n,`postAction`),n}if(this.parent?.listenerCount(i))r(),this._processArguments(),this.parent.emit(i,e,t);else if(e.length){if(this._findCommand(`*`))return this._dispatchSubcommand(`*`,e,t);this.listenerCount(`command:*`)?this.emit(`command:*`,e,t):this.commands.length?this.unknownCommand():(r(),this._processArguments())}else this.commands.length?(r(),this.help({error:!0})):(r(),this._processArguments())}_findCommand(e){if(e)return this.commands.find(t=>t._name===e||t._aliases.includes(e))}_findOption(e){return this.options.find(t=>t.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(e=>{e.options.forEach(t=>{t.mandatory&&e.getOptionValue(t.attributeName())===void 0&&e.missingMandatoryOptionValue(t)})})}_checkForConflictingLocalOptions(){let e=this.options.filter(e=>{let t=e.attributeName();return this.getOptionValue(t)===void 0?!1:this.getOptionValueSource(t)!==`default`});e.filter(e=>e.conflictsWith.length>0).forEach(t=>{let n=e.find(e=>t.conflictsWith.includes(e.attributeName()));n&&this._conflictingOption(t,n)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let t=[],n=[],r=t;function i(e){return e.length>1&&e[0]===`-`}let a=e=>/^-\d*\.?\d+(e[+-]?\d+)?$/.test(e)?!this._getCommandAndAncestors().some(e=>e.options.map(e=>e.short).some(e=>/^-\d$/.test(e))):!1,o=null,s=null,c=0;for(;c<e.length||s;){let l=s??e[c++];if(s=null,l===`--`){r===n&&r.push(l),r.push(...e.slice(c));break}if(o&&(!i(l)||a(l))){this.emit(`option:${o.name()}`,l);continue}if(o=null,i(l)){let t=this._findOption(l);if(t){if(t.required){let n=e[c++];n===void 0&&this.optionMissingArgument(t),this.emit(`option:${t.name()}`,n)}else if(t.optional){let n=null;c<e.length&&(!i(e[c])||a(e[c]))&&(n=e[c++]),this.emit(`option:${t.name()}`,n)}else this.emit(`option:${t.name()}`);o=t.variadic?t:null;continue}}if(l.length>2&&l[0]===`-`&&l[1]!==`-`){let e=this._findOption(`-${l[1]}`);if(e){e.required||e.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${e.name()}`,l.slice(2)):(this.emit(`option:${e.name()}`),s=`-${l.slice(2)}`);continue}}if(/^--[^=]+=/.test(l)){let e=l.indexOf(`=`),t=this._findOption(l.slice(0,e));if(t&&(t.required||t.optional)){this.emit(`option:${t.name()}`,l.slice(e+1));continue}}if(r===t&&i(l)&&!(this.commands.length===0&&a(l))&&(r=n),(this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&n.length===0){if(this._findCommand(l)){t.push(l),n.push(...e.slice(c));break}else if(this._getHelpCommand()&&l===this._getHelpCommand().name()){t.push(l,...e.slice(c));break}else if(this._defaultCommandName){n.push(l,...e.slice(c));break}}if(this._passThroughOptions){r.push(l,...e.slice(c));break}r.push(l)}return{operands:t,unknown:n}}opts(){if(this._storeOptionsAsProperties){let e={},t=this.options.length;for(let n=0;n<t;n++){let t=this.options[n].attributeName();e[t]=t===this._versionOptionName?this._version:this[t]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,t)=>Object.assign(e,t.opts()),{})}error(e,t){this._outputConfiguration.outputError(`${e}\n`,this._outputConfiguration.writeErr),typeof this._showHelpAfterError==`string`?this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
19
19
  `),this.outputHelp({error:!0}));let n=t||{},r=n.exitCode||1,i=n.code||`commander.error`;this._exit(r,i,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in o.env){let t=e.attributeName();(this.getOptionValue(t)===void 0||[`default`,`config`,`env`].includes(this.getOptionValueSource(t)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,o.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new p(this.options),t=e=>this.getOptionValue(e)!==void 0&&![`default`,`implied`].includes(this.getOptionValueSource(e));this.options.filter(n=>n.implied!==void 0&&t(n.attributeName())&&e.valueFromOption(this.getOptionValue(n.attributeName()),n)).forEach(e=>{Object.keys(e.implied).filter(e=>!t(e)).forEach(t=>{this.setOptionValueWithSource(t,e.implied[t],`implied`)})})}missingArgument(e){let t=`error: missing required argument '${e}'`;this.error(t,{code:`commander.missingArgument`})}optionMissingArgument(e){let t=`error: option '${e.flags}' argument missing`;this.error(t,{code:`commander.optionMissingArgument`})}missingMandatoryOptionValue(e){let t=`error: required option '${e.flags}' not specified`;this.error(t,{code:`commander.missingMandatoryOptionValue`})}_conflictingOption(e,t){let n=e=>{let t=e.attributeName(),n=this.getOptionValue(t),r=this.options.find(e=>e.negate&&t===e.attributeName()),i=this.options.find(e=>!e.negate&&t===e.attributeName());return r&&(r.presetArg===void 0&&n===!1||r.presetArg!==void 0&&n===r.presetArg)?r:i||e},r=e=>{let t=n(e),r=t.attributeName();return this.getOptionValueSource(r)===`env`?`environment variable '${t.envVar}'`:`option '${t.flags}'`},i=`error: ${r(e)} cannot be used with ${r(t)}`;this.error(i,{code:`commander.conflictingOption`})}unknownOption(e){if(this._allowUnknownOption)return;let t=``;if(e.startsWith(`--`)&&this._showSuggestionAfterError){let n=[],r=this;do{let e=r.createHelp().visibleOptions(r).filter(e=>e.long).map(e=>e.long);n=n.concat(e),r=r.parent}while(r&&!r._enablePositionalOptions);t=m(e,n)}let n=`error: unknown option '${e}'${t}`;this.error(n,{code:`commander.unknownOption`})}_excessArguments(e){if(this._allowExcessArguments)return;let t=this.registeredArguments.length,n=t===1?``:`s`,r=`error: too many arguments${this.parent?` for '${this.name()}'`:``}. Expected ${t} argument${n} but got ${e.length}.`;this.error(r,{code:`commander.excessArguments`})}unknownCommand(){let e=this.args[0],t=``;if(this._showSuggestionAfterError){let n=[];this.createHelp().visibleCommands(this).forEach(e=>{n.push(e.name()),e.alias()&&n.push(e.alias())}),t=m(e,n)}let n=`error: unknown command '${e}'${t}`;this.error(n,{code:`commander.unknownCommand`})}version(e,t,n){if(e===void 0)return this._version;this._version=e,t||=`-V, --version`,n||=`output the version number`;let r=this.createOption(t,n);return this._versionOptionName=r.attributeName(),this._registerOption(r),this.on(`option:`+r.name(),()=>{this._outputConfiguration.writeOut(`${e}\n`),this._exit(0,`commander.version`,e)}),this}description(e,t){return e===void 0&&t===void 0?this._description:(this._description=e,t&&(this._argsDescription=t),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let t=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(t=this.commands[this.commands.length-1]),e===t._name)throw Error(`Command alias can't be the same as its name`);let n=this.parent?._findCommand(e);if(n){let t=[n.name()].concat(n.aliases()).join(`|`);throw Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${t}'`)}return t._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(e=>this.alias(e)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let e=this.registeredArguments.map(e=>c(e));return[].concat(this.options.length||this._helpOption!==null?`[options]`:[],this.commands.length?`[command]`:[],this.registeredArguments.length?e:[]).join(` `)}return this._usage=e,this}name(e){return e===void 0?this._name:(this._name=e,this)}helpGroup(e){return e===void 0?this._helpGroupHeading??``:(this._helpGroupHeading=e,this)}commandsGroup(e){return e===void 0?this._defaultCommandGroup??``:(this._defaultCommandGroup=e,this)}optionsGroup(e){return e===void 0?this._defaultOptionGroup??``:(this._defaultOptionGroup=e,this)}_initOptionGroup(e){this._defaultOptionGroup&&!e.helpGroupHeading&&e.helpGroup(this._defaultOptionGroup)}_initCommandGroup(e){this._defaultCommandGroup&&!e.helpGroup()&&e.helpGroup(this._defaultCommandGroup)}nameFromFilename(e){return this._name=i.basename(e,i.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let t=this.createHelp(),n=this._getOutputContext(e);t.prepareContext({error:n.error,helpWidth:n.helpWidth,outputHasColors:n.hasColors});let r=t.formatHelp(this,t);return n.hasColors?r:this._outputConfiguration.stripColor(r)}_getOutputContext(e){e||={};let t=!!e.error,n,r,i;return t?(n=e=>this._outputConfiguration.writeErr(e),r=this._outputConfiguration.getErrHasColors(),i=this._outputConfiguration.getErrHelpWidth()):(n=e=>this._outputConfiguration.writeOut(e),r=this._outputConfiguration.getOutHasColors(),i=this._outputConfiguration.getOutHelpWidth()),{error:t,write:e=>(r||(e=this._outputConfiguration.stripColor(e)),n(e)),hasColors:r,helpWidth:i}}outputHelp(e){let t;typeof e==`function`&&(t=e,e=void 0);let n=this._getOutputContext(e),r={error:n.error,write:n.write,command:this};this._getCommandAndAncestors().reverse().forEach(e=>e.emit(`beforeAllHelp`,r)),this.emit(`beforeHelp`,r);let i=this.helpInformation({error:n.error});if(t&&(i=t(i),typeof i!=`string`&&!Buffer.isBuffer(i)))throw Error(`outputHelp callback must return a string or a Buffer`);n.write(i),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit(`afterHelp`,r),this._getCommandAndAncestors().forEach(e=>e.emit(`afterAllHelp`,r))}helpOption(e,t){return typeof e==`boolean`?(e?(this._helpOption===null&&(this._helpOption=void 0),this._defaultOptionGroup&&this._initOptionGroup(this._getHelpOption())):this._helpOption=null,this):(this._helpOption=this.createOption(e??`-h, --help`,t??`display help for command`),(e||t)&&this._initOptionGroup(this._helpOption),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(e){return this._helpOption=e,this._initOptionGroup(e),this}help(e){this.outputHelp(e);let t=Number(o.exitCode??0);t===0&&e&&typeof e!=`function`&&e.error&&(t=1),this._exit(t,`commander.help`,`(outputHelp)`)}addHelpText(e,t){let n=[`beforeAll`,`before`,`after`,`afterAll`];if(!n.includes(e))throw Error(`Unexpected value for position to addHelpText.
20
- Expecting one of '${n.join(`', '`)}'`);let r=`${e}Help`;return this.on(r,e=>{let n;n=typeof t==`function`?t({error:e.error,command:e.command}):t,n&&e.write(`${n}\n`)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(e=>t.is(e))&&(this.outputHelp(),this._exit(0,`commander.helpDisplayed`,`(outputHelp)`))}};function g(e){return e.map(e=>{if(!e.startsWith(`--inspect`))return e;let t,n=`127.0.0.1`,r=`9229`,i;return(i=e.match(/^(--inspect(-brk)?)$/))===null?(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))===null?(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=i[1],n=i[3],r=i[4]):(t=i[1],/^\d+$/.test(i[3])?r=i[3]:n=i[3]):t=i[1],t&&r!==`0`?`${t}=${n}:${parseInt(r)+1}`:e})}function _(){if(o.env.NO_COLOR||o.env.FORCE_COLOR===`0`||o.env.FORCE_COLOR===`false`)return!1;if(o.env.FORCE_COLOR||o.env.CLICOLOR_FORCE!==void 0)return!0}e.Command=h,e.useColor=_}));const{program:k,createCommand:ie,createArgument:A,createOption:j,CommanderError:ae,InvalidArgumentError:M,InvalidOptionArgumentError:oe,Command:N,Argument:P,Option:se,Help:F}=n(e((e=>{let{Argument:t}=w(),{Command:n}=O(),{CommanderError:r,InvalidArgumentError:i}=C(),{Help:a}=T(),{Option:o}=E();e.program=new n,e.createCommand=e=>new n(e),e.createOption=(e,t)=>new o(e,t),e.createArgument=(e,n)=>new t(e,n),e.Command=n,e.Option=o,e.Argument=t,e.Help=a,e.CommanderError=r,e.InvalidArgumentError=i,e.InvalidOptionArgumentError=i}))(),1).default;var I=`0.1.96`;async function L(e){e||=process.cwd();let t=o(e);await t.build({cwd:e,entry:t.entry,outdir:t.outdir,watch:!1,onStart:()=>{console.log(`Building agent...`)},onResult:e=>{`error`in e&&(console.error(e.error),process.exit(1));for(let t of e.warnings)console.warn(t.message);console.log(`Built agent to ${e.entry}`)}})}var R=n(h(),1),z=n(l(),1),B=n(a(),1);async function V(e,t){e||=process.cwd(),await m(e);let n=await c(),r=new s({authToken:n,fetch:(e,t)=>{let n=new Headers(t?.headers);return n.set(`x-blink-cli-version`,I),fetch(e,{...t,headers:n})}}),a=await i(e,`package.json`);if(!a)throw Error(`package.json not found`);let l=await x(a,`utf-8`),h=JSON.parse(l),g=v(a),C=y(g,`data`,`config.json`),w={};if(te(C)){let e=await x(C,`utf-8`);w=JSON.parse(e)}let T;if(w?.organizationId)try{T=(await r.organizations.get(w.organizationId)).name}catch{w.organizationId=void 0}if(!w?.organizationId){let e=await r.organizations.list();if(e.length===1){let t=e[0];w.organizationId=t.id,T=t.name}else{let t=await f({message:`Which organization should contain this agent?`,options:e.map(e=>({value:e.id,label:e.name}))});if(d(t))return;w.organizationId=t,T=e.find(e=>e.id===t).name}}if(!w.organizationId)throw Error(`Developer error: No organization ID found.`);let E;if(w?.agentId)try{E=(await r.agents.get(w.agentId)).name}catch{w.agentId=void 0}if(!w?.agentId)try{let e=await r.organizations.agents.get({organization_id:w.organizationId,agent_name:h.name});w.agentId=e.id,E=e.name}catch{let e=await r.agents.create({name:h.name,organization_id:w.organizationId});w.agentId=e.id,E=e.name}if(!w.agentId)throw Error(`Developer error: No agent ID found.`);await ne(v(C),{recursive:!0}),await re(C,JSON.stringify({_:`This file can be source controlled. It contains no secrets.`,...w},null,2),`utf-8`);let D=o(g),O=await new Promise((e,t)=>{D.build({cwd:g,entry:D.entry,outdir:D.outdir,watch:!1,onStart:()=>{},onResult:t=>{e(t)}}).catch(t)});if(!O)throw Error(`Failed to build agent`);if(`error`in O)throw Error(O.error.message);let k={},ie=await b(O.outdir);for(let e of ie)k[y(O.outdir,e)]=e;let A=y(e,`README.md`);await H(A)&&(k[A]=`README.md`);let j={},ae=await le(g);for(let e of ae)j[e]=ee(g,e);let M=Object.entries(k),oe=Object.entries(j),N=[...M,...oe],P=N.length,se=0,F=0,L=0,B=Array(P);await ce(N,10,async([e,t],n)=>{let i=(await S(e)).size,a=++se;W(`${z.default.dim(`[${a}/${P}]`)} Uploading ${t} (${U(i)})...`);let o=await x(e),s=await r.files.upload(new File([Buffer.from(o)],t));B[n]={path:t,id:s.id},F+=1,L+=i}),W(`${z.default.dim(`[${F}/${P}]`)} Uploaded files (${U(L)}).`),process.stdout.write(`
20
+ Expecting one of '${n.join(`', '`)}'`);let r=`${e}Help`;return this.on(r,e=>{let n;n=typeof t==`function`?t({error:e.error,command:e.command}):t,n&&e.write(`${n}\n`)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(e=>t.is(e))&&(this.outputHelp(),this._exit(0,`commander.helpDisplayed`,`(outputHelp)`))}};function g(e){return e.map(e=>{if(!e.startsWith(`--inspect`))return e;let t,n=`127.0.0.1`,r=`9229`,i;return(i=e.match(/^(--inspect(-brk)?)$/))===null?(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))===null?(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=i[1],n=i[3],r=i[4]):(t=i[1],/^\d+$/.test(i[3])?r=i[3]:n=i[3]):t=i[1],t&&r!==`0`?`${t}=${n}:${parseInt(r)+1}`:e})}function _(){if(o.env.NO_COLOR||o.env.FORCE_COLOR===`0`||o.env.FORCE_COLOR===`false`)return!1;if(o.env.FORCE_COLOR||o.env.CLICOLOR_FORCE!==void 0)return!0}e.Command=h,e.useColor=_}));const{program:k,createCommand:ie,createArgument:A,createOption:j,CommanderError:ae,InvalidArgumentError:M,InvalidOptionArgumentError:oe,Command:N,Argument:P,Option:se,Help:F}=n(e((e=>{let{Argument:t}=w(),{Command:n}=O(),{CommanderError:r,InvalidArgumentError:i}=C(),{Help:a}=T(),{Option:o}=E();e.program=new n,e.createCommand=e=>new n(e),e.createOption=(e,t)=>new o(e,t),e.createArgument=(e,n)=>new t(e,n),e.Command=n,e.Option=o,e.Argument=t,e.Help=a,e.CommanderError=r,e.InvalidArgumentError=i,e.InvalidOptionArgumentError=i}))(),1).default;var I=`0.1.97`;async function L(e){e||=process.cwd();let t=o(e);await t.build({cwd:e,entry:t.entry,outdir:t.outdir,watch:!1,onStart:()=>{console.log(`Building agent...`)},onResult:e=>{`error`in e&&(console.error(e.error),process.exit(1));for(let t of e.warnings)console.warn(t.message);console.log(`Built agent to ${e.entry}`)}})}var R=n(h(),1),z=n(l(),1),B=n(a(),1);async function V(e,t){e||=process.cwd(),await m(e);let n=await c(),r=new s({authToken:n,fetch:(e,t)=>{let n=new Headers(t?.headers);return n.set(`x-blink-cli-version`,I),fetch(e,{...t,headers:n})}}),a=await i(e,`package.json`);if(!a)throw Error(`package.json not found`);let l=await x(a,`utf-8`),h=JSON.parse(l),g=v(a),C=y(g,`data`,`config.json`),w={};if(te(C)){let e=await x(C,`utf-8`);w=JSON.parse(e)}let T;if(w?.organizationId)try{T=(await r.organizations.get(w.organizationId)).name}catch{w.organizationId=void 0}if(!w?.organizationId){let e=await r.organizations.list();if(e.length===1){let t=e[0];w.organizationId=t.id,T=t.name}else{let t=await f({message:`Which organization should contain this agent?`,options:e.map(e=>({value:e.id,label:e.name}))});if(d(t))return;w.organizationId=t,T=e.find(e=>e.id===t).name}}if(!w.organizationId)throw Error(`Developer error: No organization ID found.`);let E;if(w?.agentId)try{E=(await r.agents.get(w.agentId)).name}catch{w.agentId=void 0}if(!w?.agentId)try{let e=await r.organizations.agents.get({organization_id:w.organizationId,agent_name:h.name});w.agentId=e.id,E=e.name}catch{let e=await r.agents.create({name:h.name,organization_id:w.organizationId});w.agentId=e.id,E=e.name}if(!w.agentId)throw Error(`Developer error: No agent ID found.`);await ne(v(C),{recursive:!0}),await re(C,JSON.stringify({_:`This file can be source controlled. It contains no secrets.`,...w},null,2),`utf-8`);let D=o(g),O=await new Promise((e,t)=>{D.build({cwd:g,entry:D.entry,outdir:D.outdir,watch:!1,onStart:()=>{},onResult:t=>{e(t)}}).catch(t)});if(!O)throw Error(`Failed to build agent`);if(`error`in O)throw Error(O.error.message);let k={},ie=await b(O.outdir);for(let e of ie)k[y(O.outdir,e)]=e;let A=y(e,`README.md`);await H(A)&&(k[A]=`README.md`);let j={},ae=await le(g);for(let e of ae)j[e]=ee(g,e);let M=Object.entries(k),oe=Object.entries(j),N=[...M,...oe],P=N.length,se=0,F=0,L=0,B=Array(P);await ce(N,10,async([e,t],n)=>{let i=(await S(e)).size,a=++se;W(`${z.default.dim(`[${a}/${P}]`)} Uploading ${t} (${U(i)})...`);let o=await x(e),s=await r.files.upload(new File([Buffer.from(o)],t));B[n]={path:t,id:s.id},F+=1,L+=i}),W(`${z.default.dim(`[${F}/${P}]`)} Uploaded files (${U(L)}).`),process.stdout.write(`
21
21
  `);let V=B.filter(Boolean),G=V.slice(0,M.length),ue=V.slice(M.length),K=y(e,`.env.local`),q=[];if(await H(K)){let e=(0,R.parse)(await x(K,`utf-8`));q=Object.keys(e)}let J=[];J=(await r.agents.env.list({agent_id:w.agentId})).map(e=>e.key);let Y=y(e,`.env.production`);if(await H(Y)){let e=(0,R.parse)(await x(Y,`utf-8`)),t=Object.entries(e),n=t.length,i=0;for(let[e,a]of t){let t=await r.agents.env.create({agent_id:w.agentId,key:e,value:a,target:[`production`,`preview`],secret:!0,upsert:!0});J.push(t.key),i+=1,W(`${z.default.dim(`[${i}/${n}]`)} Updating environment variable: ${e} ${z.default.dim(`(.env.production)`)}`)}W(`${z.default.dim(`[${i}/${n}]`)} Updated environment variables! ${z.default.dim(`(.env.production)`)}`),process.stdout.write(`
22
- `)}let X=q.filter(e=>!J.includes(e));if(X.length>0){console.log(`Warning: The following environment variables are set in .env.local but not in .env.production:`);for(let e of X)console.log(`- ${e}`);let e=await p({message:`Do you want to deploy anyway?`});if(e===!1||d(e))return}let Z=await r.agents.deployments.create({agent_id:w.agentId,target:`production`,entrypoint:_(O.entry),output_files:G,source_files:ue,message:t?.message}),Q=`https://blink.so/${T}/${E}/deployments/${Z.number}`;console.log(`Deployed:`,Q);let $=u();$.start(`Waiting for deployment to be live...`);try{for(;;){let e=await r.agents.deployments.get({agent_id:w.agentId,deployment_id:Z.id});if(e.status===`success`){let t=`Deployment successful.`;e.target===`production`&&(t+=` All chats will use this deployment!`),$.stop(t);let n=await r.agents.get(w.agentId);n.request_url&&console.log(`\nSend webhooks from anywhere: ${n.request_url}`);break}if(e.status===`failed`){let t=`Deployment failed.`;e.error_message&&(t+=` ${e.error_message}`),$.stop(t),console.log(`Read logs for details:`,Q);return}await new Promise(e=>setTimeout(e,500))}}catch{$.stop(`Failed to poll for deployment status.`),console.log(`Read logs for details:`,Q);return}}const H=async e=>{try{return await S(e),!0}catch{return!1}};async function ce(e,t,n){let r=Array(e.length),i=0,a=Array(Math.min(t,e.length)).fill(0).map(async()=>{for(;;){let t=i++;if(t>=e.length)break;r[t]=await n(e[t],t)}});return await Promise.all(a),r}function U(e){if(e===0)return`0B`;let t=1024,n=[`B`,`KB`,`MB`,`GB`,`TB`],r=Math.floor(Math.log(e)/Math.log(t)),i=e/t**+r;return`${i.toFixed(i>=100?0:i>=10?1:2)}${n[r]}`}function W(e){if(process.stdout.isTTY)try{process.stdout.clearLine(0),process.stdout.cursorTo(0),process.stdout.write(e);return}catch{}console.log(e)}async function le(e){let t=[],n=(0,B.default)().add([`.git`,`node_modules`,`data`,`.env`,`.env.*`]),r=y(e,`.gitignore`);if(await H(r)){let e=await x(r,`utf-8`);n.add(e)}async function i(r,a=e){let o=await b(r,{withFileTypes:!0});for(let e of o){let o=y(r,e.name),s=ee(a,o);n.ignores(s)||(e.isDirectory()?await i(o,a):e.isFile()&&t.push(o))}}return await i(e),t}if(globalThis.WebSocket||(globalThis.WebSocket=r.default),globalThis.Bun!==void 0){let e=t(`perf_hooks`);e.monitorEventLoopDelay=()=>({enable:()=>{}})}globalThis.crypto||(globalThis.crypto={}),globalThis.crypto.randomUUID||(globalThis.crypto.randomUUID=()=>g()),k.name(`blink`).description(`Blink is a runtime for building and deploying AI agents.`).version(I).action(()=>{k.outputHelp()});const G=e=>async(...t)=>{let{default:n}=await e();return n(...t)};k.command(`init [directory]`).description(`Initialize a new Blink agent.`).action(G(()=>import(`./init-iySs9KUe.js`))),k.command(`dev [directory] [options]`).description(`Start a development server for your agent.`).action(G(()=>import(`./dev-D14ZFqDd.js`))),k.command(`deploy [directory]`).description(`Deploy your agent to the Blink Cloud.`).option(`-m, --message <message>`,`Message for this deployment`).action(V),k.command(`build [directory]`).description(`Build your agent for production.`).action(L),k.command(`telemetry [boolean]`).description(`Enable or disable telemetry.`),k.command(`start [directory]`).description("Starts the Blink runtime in production mode. The agent must be compiled with `blink build` first."),k.command(`run <message...>`).description(`Run your agent programmatically and get the response.`).option(`-d, --directory <directory>`,`Directory to run the agent from (default: current directory)`).option(`-c, --chat <chat>`,`Chat key to use (default: 'default')`).action(G(()=>import(`./run-CzO7B7Wf.js`))),k.command(`connect`,{hidden:!0}).description(`Connect compute to the Blink Cloud.`).action(G(()=>import(`./connect-DXaWCjUL.js`))),k.command(`chat`,{hidden:!0}).description(`Start a Blink chat connected to your machine.`).action(G(()=>import(`./chat-DhLpNFHK.js`))),k.command(`login`,{hidden:!0}).description(`Log in to the Blink Cloud.`).action(G(()=>import(`./login-DTwQcbaT.js`))),k.parse(process.argv);export{};
22
+ `)}let X=q.filter(e=>!J.includes(e));if(X.length>0){console.log(`Warning: The following environment variables are set in .env.local but not in .env.production:`);for(let e of X)console.log(`- ${e}`);let e=await p({message:`Do you want to deploy anyway?`});if(e===!1||d(e))return}let Z=await r.agents.deployments.create({agent_id:w.agentId,target:`production`,entrypoint:_(O.entry),output_files:G,source_files:ue,message:t?.message}),Q=`https://blink.so/${T}/${E}/deployments/${Z.number}`;console.log(`Deployed:`,Q);let $=u();$.start(`Waiting for deployment to be live...`);try{for(;;){let e=await r.agents.deployments.get({agent_id:w.agentId,deployment_id:Z.id});if(e.status===`success`){let t=`Deployment successful.`;e.target===`production`&&(t+=` All chats will use this deployment!`),$.stop(t);let n=await r.agents.get(w.agentId);n.request_url&&console.log(`\nSend webhooks from anywhere: ${n.request_url}`);break}if(e.status===`failed`){let t=`Deployment failed.`;e.error_message&&(t+=` ${e.error_message}`),$.stop(t),console.log(`Read logs for details:`,Q);return}await new Promise(e=>setTimeout(e,500))}}catch{$.stop(`Failed to poll for deployment status.`),console.log(`Read logs for details:`,Q);return}}const H=async e=>{try{return await S(e),!0}catch{return!1}};async function ce(e,t,n){let r=Array(e.length),i=0,a=Array(Math.min(t,e.length)).fill(0).map(async()=>{for(;;){let t=i++;if(t>=e.length)break;r[t]=await n(e[t],t)}});return await Promise.all(a),r}function U(e){if(e===0)return`0B`;let t=1024,n=[`B`,`KB`,`MB`,`GB`,`TB`],r=Math.floor(Math.log(e)/Math.log(t)),i=e/t**+r;return`${i.toFixed(i>=100?0:i>=10?1:2)}${n[r]}`}function W(e){if(process.stdout.isTTY)try{process.stdout.clearLine(0),process.stdout.cursorTo(0),process.stdout.write(e);return}catch{}console.log(e)}async function le(e){let t=[],n=(0,B.default)().add([`.git`,`node_modules`,`data`,`.env`,`.env.*`]),r=y(e,`.gitignore`);if(await H(r)){let e=await x(r,`utf-8`);n.add(e)}async function i(r,a=e){let o=await b(r,{withFileTypes:!0});for(let e of o){let o=y(r,e.name),s=ee(a,o);n.ignores(s)||(e.isDirectory()?await i(o,a):e.isFile()&&t.push(o))}}return await i(e),t}if(globalThis.WebSocket||(globalThis.WebSocket=r.default),globalThis.Bun!==void 0){let e=t(`perf_hooks`);e.monitorEventLoopDelay=()=>({enable:()=>{}})}globalThis.crypto||(globalThis.crypto={}),globalThis.crypto.randomUUID||(globalThis.crypto.randomUUID=()=>g()),k.name(`blink`).description(`Blink is a runtime for building and deploying AI agents.`).version(I).action(()=>{k.outputHelp()});const G=e=>async(...t)=>{let{default:n}=await e();return n(...t)};k.command(`init [directory]`).description(`Initialize a new Blink agent.`).action(G(()=>import(`./init-iySs9KUe.js`))),k.command(`dev [directory] [options]`).description(`Start a development server for your agent.`).action(G(()=>import(`./dev-CGEco9TM.js`))),k.command(`deploy [directory]`).description(`Deploy your agent to the Blink Cloud.`).option(`-m, --message <message>`,`Message for this deployment`).action(V),k.command(`build [directory]`).description(`Build your agent for production.`).action(L),k.command(`telemetry [boolean]`).description(`Enable or disable telemetry.`),k.command(`start [directory]`).description("Starts the Blink runtime in production mode. The agent must be compiled with `blink build` first."),k.command(`run <message...>`).description(`Run your agent programmatically and get the response.`).option(`-d, --directory <directory>`,`Directory to run the agent from (default: current directory)`).option(`-c, --chat <chat>`,`Chat key to use (default: 'default')`).action(G(()=>import(`./run-Djux6Pnc.js`))),k.command(`connect`,{hidden:!0}).description(`Connect compute to the Blink Cloud.`).action(G(()=>import(`./connect-DXaWCjUL.js`))),k.command(`chat`,{hidden:!0}).description(`Start a Blink chat connected to your machine.`).action(G(()=>import(`./chat-DhLpNFHK.js`))),k.command(`login`,{hidden:!0}).description(`Log in to the Blink Cloud.`).action(G(()=>import(`./login-DTwQcbaT.js`))),k.parse(process.argv);export{};
@@ -1 +1 @@
1
- import{__toESM as e}from"./chunk-D9KrCrVq.js";import{getAuthToken as t}from"./auth-DjAEZyZZ.js";import"./dist-BNbSDxaw.js";import"./open-DCYivxgo.js";import{migrateBlinkToData as n,require_main as r}from"./main-BdSSlDIs.js";import{ChatManager as i,Client as a}from"./chat-manager-PrBCvqS6.js";import{spawn as o}from"node:child_process";import{join as s,resolve as c}from"node:path";import{readFile as l}from"node:fs/promises";import{createServer as u}from"node:net";async function d(e){let t=e.env?.PORT??await f(),n=e.env?.HOST??`127.0.0.1`,r=`http://${n}:${t}`,i={...e.env??process.env,PORT:t.toString(),HOST:n},s=o(e.command,e.args,{stdio:`pipe`,env:i});e.signal?.addEventListener(`abort`,()=>{try{s.kill()}catch{}},{once:!0});let c=new AbortController,l=[c.signal];e.signal&&l.push(e.signal);let u=AbortSignal.any(l);s.stdout.on(`data`,t=>{e.onStdout?.(Buffer.from(t).toString(`utf-8`))});let d=``;s.stderr.on(`data`,t=>{c.signal.aborted||(d+=Buffer.from(t).toString(`utf-8`)),e.onStderr?.(Buffer.from(t).toString(`utf-8`))}),s.on(`error`,e=>{c.abort(e)}),s.on(`exit`,(t,n)=>{c.signal.aborted?e.onExit?.(t,n):c.abort()});let p=new a({baseUrl:r}),m=0;for(;!u.aborted;){try{await p.health();break}catch{}if(await new Promise(e=>setTimeout(e,m*5)),m++,m>100)throw Error(`Health endpoint timed out`)}if(u.aborted)throw u.reason;return c.abort(),{client:p,dispose:()=>{s.kill()}}}async function f(){let e=u();return new Promise((t,n)=>{e.listen(0,()=>{let n=e.address().port;t(n)}).on(`error`,e=>{n(e)})}).finally(()=>{e.close()})}var p=e(r(),1);async function m(e,r){let a=c(r?.directory??process.cwd());await n(a);let o=(0,p.parse)(await l(s(a,`.env.local`),`utf-8`)),u=await t(),f=await d({command:`node`,args:[`--experimental-strip-types`,`--no-deprecation`,c(a,`agent.ts`)],env:{...process.env,...o,BLINK_TOKEN:u}}),m=c(r?.directory??process.cwd(),`data`,`chats`),h=r?.chat??`default`,g=new i({chatId:h,chatsDirectory:m});g.setAgent(f.client);try{await g.sendMessage({id:crypto.randomUUID(),created_at:new Date().toISOString(),metadata:void 0,parts:[{type:`text`,text:e.join(` `)}],role:`user`}),await new Promise(e=>{let t=g.subscribe(n=>{(n.status===`idle`||n.status===`error`)&&(t(),e()),n.streamingMessage&&console.log(n.streamingMessage)})});let t=g.getState();t.error&&console.error(`Error:`,t.error)}finally{g.dispose(),f.dispose()}}export{m as default};
1
+ import{__toESM as e}from"./chunk-D9KrCrVq.js";import{getAuthToken as t}from"./auth-DjAEZyZZ.js";import"./dist-BNbSDxaw.js";import"./open-DCYivxgo.js";import{migrateBlinkToData as n,require_main as r}from"./main-BdSSlDIs.js";import{ChatManager as i,Client as a}from"./chat-manager-BuoEwJ6L.js";import{spawn as o}from"node:child_process";import{join as s,resolve as c}from"node:path";import{readFile as l}from"node:fs/promises";import{createServer as u}from"node:net";async function d(e){let t=e.env?.PORT??await f(),n=e.env?.HOST??`127.0.0.1`,r=`http://${n}:${t}`,i={...e.env??process.env,PORT:t.toString(),HOST:n},s=o(e.command,e.args,{stdio:`pipe`,env:i});e.signal?.addEventListener(`abort`,()=>{try{s.kill()}catch{}},{once:!0});let c=new AbortController,l=[c.signal];e.signal&&l.push(e.signal);let u=AbortSignal.any(l);s.stdout.on(`data`,t=>{e.onStdout?.(Buffer.from(t).toString(`utf-8`))});let d=``;s.stderr.on(`data`,t=>{c.signal.aborted||(d+=Buffer.from(t).toString(`utf-8`)),e.onStderr?.(Buffer.from(t).toString(`utf-8`))}),s.on(`error`,e=>{c.abort(e)}),s.on(`exit`,(t,n)=>{c.signal.aborted?e.onExit?.(t,n):c.abort()});let p=new a({baseUrl:r}),m=0;for(;!u.aborted;){try{await p.health();break}catch{}if(await new Promise(e=>setTimeout(e,m*5)),m++,m>100)throw Error(`Health endpoint timed out`)}if(u.aborted)throw u.reason;return c.abort(),{client:p,dispose:()=>{s.kill()}}}async function f(){let e=u();return new Promise((t,n)=>{e.listen(0,()=>{let n=e.address().port;t(n)}).on(`error`,e=>{n(e)})}).finally(()=>{e.close()})}var p=e(r(),1);async function m(e,r){let a=c(r?.directory??process.cwd());await n(a);let o=(0,p.parse)(await l(s(a,`.env.local`),`utf-8`)),u=await t(),f=await d({command:`node`,args:[`--experimental-strip-types`,`--no-deprecation`,c(a,`agent.ts`)],env:{...process.env,...o,BLINK_TOKEN:u}}),m=c(r?.directory??process.cwd(),`data`,`chats`),h=r?.chat??`default`,g=new i({chatId:h,chatsDirectory:m});g.setAgent(f.client);try{await g.sendMessage({id:crypto.randomUUID(),created_at:new Date().toISOString(),metadata:void 0,parts:[{type:`text`,text:e.join(` `)}],role:`user`}),await new Promise(e=>{let t=g.subscribe(n=>{(n.status===`idle`||n.status===`error`)&&(t(),e()),n.streamingMessage&&console.log(n.streamingMessage)})});let t=g.getState();t.error&&console.error(`Error:`,t.error)}finally{g.dispose(),f.dispose()}}export{m as default};
@@ -1,4 +1,4 @@
1
- const e=require(`../chunk-iXuH7AlR.cjs`),t=require(`../index.node-DlfrLUZ3.cjs`);require(`../token-error-BoNG8ooW.cjs`),require(`../esm-0UNjvroT.cjs`);const n=require(`../build-D_HFEWKz.cjs`);let r=require(`zod/v4`);r=e.__toESM(r),require(`zod/v3`);let i=require(`node:fs`);i=e.__toESM(i);let a=require(`node:stream`);a=e.__toESM(a);let o=require(`node:util`);o=e.__toESM(o);let s=require(`http`);s=e.__toESM(s);let c=require(`path`);c=e.__toESM(c);let l=require(`module`);l=e.__toESM(l);let u=require(`fs`);u=e.__toESM(u);let d=require(`node:process`);d=e.__toESM(d);let f=require(`ai`);f=e.__toESM(f);let p=require(`fs/promises`);p=e.__toESM(p);let m=require(`child_process`);m=e.__toESM(m);let h=require(`react`);h=e.__toESM(h);let g=require(`node:path`);g=e.__toESM(g);let _=require(`node:module`);_=e.__toESM(_);let v=require(`zod`);v=e.__toESM(v);let y=require(`node:readline`);y=e.__toESM(y);let b=require(`node:fs/promises`);b=e.__toESM(b);function x(e){let[n,r]=(0,h.useState)(void 0),[i,a]=(0,h.useState)([]),[o,s]=(0,h.useState)(void 0),[c,l]=(0,h.useState)(e.buildResult),[u,d]=(0,h.useState)(e.env),[f,p]=(0,h.useState)(e.apiServerUrl),[g,_]=(0,h.useState)(void 0);return(0,h.useEffect)(()=>{d(e.env),l(e.buildResult),p(e.apiServerUrl)},[e.env,e.buildResult,e.apiServerUrl]),(0,h.useEffect)(()=>{if(!c||`error`in c){r(void 0),a([]),s(void 0);return}let e=new AbortController,n=!1;return s(void 0),(async()=>{let n=await S(),i=(0,m.spawn)(`node`,[`--no-deprecation`,c.entry],{stdio:`pipe`,env:{...process.env,...u,[t.APIServerURLEnvironmentVariable]:f,PORT:n.toString(),HOST:`127.0.0.1`}});e.signal.addEventListener(`abort`,()=>{try{i.kill()}catch{}});let o=!1;i.stdout.on(`data`,e=>{let t=Buffer.from(e).toString(`utf-8`).trim();!o&&t.startsWith(`Agent server listening on`)||(o||console.log(`stdout: ${t}`),t.length&&a(e=>[...e,{level:`log`,message:t}]))}),i.stderr.on(`data`,e=>{o||console.error(`stderr: ${Buffer.from(e).toString(`utf-8`).trim()}`);let t=Buffer.from(e).toString(`utf-8`).trim();t.length&&a(e=>[...e,{level:`error`,message:t}])}),i.on(`error`,t=>{e.abort(t)}),i.on(`exit`,(t,n)=>{e.abort(`Agent exited with code ${t??`unknown`} and signal ${n??`unknown`}. Be sure to call "blink.agent(...).serve()".`)});let s=new t.Client({baseUrl:`http://127.0.0.1:${n}`});for(;!e.signal.aborted;){try{await s.health();break}catch{}await new Promise(e=>setTimeout(e,100))}if(e.signal.aborted)throw e.signal.reason;o=!0;let l=await s.capabilities();_(l),r(s)})().catch(e=>{n||s(e instanceof Error?e:Error(String(e)))}),()=>{n=!0,e.abort()}},[c,u,f]),(0,h.useMemo)(()=>({agent:n,logs:i,error:o,capabilities:g}),[n,i,o,g])}async function S(){let e=(0,s.createServer)();return new Promise((t,n)=>{e.listen(0,()=>{let n=e.address().port;t(n)}).on(`error`,e=>{n(e)})}).finally(()=>{e.close()})}function C(e){let{directory:t,onBuildStart:r,onBuildSuccess:i,onBuildError:a}=typeof e==`string`?{directory:e}:e,o=(0,h.useMemo)(()=>n.resolveConfig(t),[t]),[s,c]=(0,h.useState)(void 0),[l,u]=(0,h.useState)(void 0),[d,f]=(0,h.useState)(`building`),p=(0,h.useRef)(r),m=(0,h.useRef)(i),g=(0,h.useRef)(a);return(0,h.useEffect)(()=>{p.current=r,m.current=i,g.current=a},[r,i,a]),(0,h.useEffect)(()=>{let e=new AbortController;return o.build({cwd:t,entry:o.entry,outdir:o.outdir,watch:!0,dev:!0,signal:e.signal,onStart:()=>{f(`building`),c(void 0),u(void 0),p.current?.()},onResult:e=>{`error`in e?(c(e.error),f(`error`),g.current?.(e.error)):(u(e),f(`success`),m.current?.(e))}}).catch(e=>{console.log(`error`,e),f(`error`),c(e),g.current?.(e)}),()=>{e.abort()}},[t]),(0,h.useMemo)(()=>({error:s,status:d,result:l,entry:o.entry,outdir:o.outdir}),[s,d,l,o.entry,o.outdir])}function w(){return/[<>:"/\\|?*\u0000-\u001F]|[. ]$/g}function T(){return/^(con|prn|aux|nul|com\d|lpt\d)$/i}const E=100,D=/^\.+(\\|\/)|^\.+$/,O=/[. ]+$/,k=/[\p{Control}\p{Format}\p{Zl}\p{Zp}\uFFF0-\uFFFF]/gu,A=/[\p{Control}\p{Format}\p{Zl}\p{Zp}\uFFF0-\uFFFF]/u,j=e=>e===`‍`,M=/([<>:"/\\|?*\u0000-\u001F]){2,}/g,N=/[\t\n\r\u00A0\u1680\u2000-\u200A\u202F\u205F\u3000]+/g;let P;function F(){return P??=new Intl.Segmenter(void 0,{granularity:`grapheme`}),P}function I(e,t={}){if(typeof e!=`string`)throw TypeError(`Expected a string`);let n=t.replacement??`!`;if(w().test(n)||[...n].some(e=>A.test(e)&&!j(e)))throw Error(`Replacement string cannot contain reserved filename characters`);e=e.normalize(`NFC`),e=e.replaceAll(N,` `),n.length>0&&(e=e.replaceAll(M,`$1`)),e=e.replace(O,``),e=e.replace(D,n),e=e.replace(w(),n),e=e.replaceAll(k,e=>j(e)?e:n),e.length===0&&(e=n),e=T().test(e)?e+n:e;let r=typeof t.maxLength==`number`?t.maxLength:100;if(e.length>r){let t=e.lastIndexOf(`.`);if(t===-1)e=ee(e,r);else{let n=e.slice(0,t),i=e.slice(t),a=Math.max(0,r-i.length);e=ee(n,a)+i}}return e}function ee(e,t){if(e.length<=t)return e;let n=0,r=``;for(let{segment:i}of F().segment(e)){let e=n+i.length;if(e>t)break;r+=i,n=e}return r}function L(e){return`${e}.lock`}function R(e){try{return process.kill(e,0),!0}catch(e){return e.code===`EPERM`}}function te(e,t={}){let n=L(e),r=process.pid.toString();try{return i.writeFileSync(n,r,{flag:`wx`}),!0}catch(r){if(r.code!==`EEXIST`)throw r;if(t.stale===0)return!1;let a;try{a=parseInt(i.readFileSync(n,`utf8`),10)}catch{return i.unlinkSync(n),te(e,{...t,stale:0})}if(!R(a))try{return i.unlinkSync(n),te(e,{...t,stale:0})}catch(n){if(n.code===`ENOENT`)return te(e,{...t,stale:0});throw n}return!1}}async function z(e,t={}){let n={stale:!0,retries:0,retryInterval:100,...t},r=g.resolve(e),i=0;for(;i<=n.retries;){if(te(r,n))return()=>B(r);i<n.retries&&await new Promise(e=>setTimeout(e,n.retryInterval)),i++}let a=Error(`Lock file is already being held`);throw a.code=`ELOCKED`,a.file=r,a}function B(e){let t=g.resolve(e),n=L(t);try{if(parseInt(i.readFileSync(n,`utf8`),10)!==process.pid){let e=Error(`Lock is not owned by this process`);throw e.code=`ENOTACQUIRED`,e}i.unlinkSync(n)}catch(e){if(e.code===`ENOENT`){let e=Error(`Lock is not acquired`);throw e.code=`ENOTACQUIRED`,e}throw e}}function V(e){let t=g.resolve(e),n=L(t);try{if(!i.existsSync(n))return{locked:!1};let e=i.readFileSync(n,`utf8`),t=parseInt(e,10);return R(t)?{locked:!0,pid:t}:{locked:!1}}catch(e){return e.code,{locked:!1}}}const ne=e=>{i.mkdirSync(e,{recursive:!0})},re=e=>{try{i.fdatasyncSync(e)}catch{}try{i.closeSync(e)}catch{}},H=e=>{try{let t=i.openSync(e,`r`);try{i.fsyncSync(t)}finally{i.closeSync(t)}}catch{}},ie=(e,t)=>{let n=g.dirname(e);ne(n);let r=g.join(n,`.tmp-`+process.pid+`-`+Math.random().toString(36).slice(2)),a;try{a=i.openSync(r,`w`),i.writeFileSync(a,t,`utf-8`),re(a),a=void 0,i.renameSync(r,e),H(e),H(n)}catch(e){if(a!==void 0)try{i.closeSync(a)}catch{}try{i.rmSync(r,{force:!0})}catch{}throw e}},ae=(e,t)=>{let n=new Map,r,a=e=>{if(i.statSync(e,{throwIfNoEntry:!1}))return JSON.parse(i.readFileSync(e,`utf-8`))},o=(e,t)=>{ie(e,JSON.stringify(t,null,2))},s=async()=>{if(r)throw Error(`Index is already locked`);let t=g.join(e,`index.json`);ne(e),i.existsSync(t)||i.writeFileSync(t,JSON.stringify({ids:{}}),`utf-8`);let n=await z(t,{stale:!0,retries:5,retryInterval:100});return r=()=>Promise.resolve(n()),()=>{n(),r=void 0}},c=async()=>{let t=g.join(e,`index.json`),n=a(t)??{ids:{}};return n.ids||={},n},l=async t=>{let n=g.join(e,`index.json`);o(n,t)},u=async t=>{let n=(await c()).ids[t];if(n)return g.join(e,n)},d=async t=>{let n=(await c()).ids[t];if(!n)return;let r=g.join(e,n);if(i.statSync(r,{throwIfNoEntry:!1}))return JSON.parse(i.readFileSync(r,`utf-8`))},f=async n=>{let r=n[t],i=String(r),a=I(i,{replacement:`_`})+`.json`,u=await s();try{let t=await c();t.ids[i]=a,t.current=i;let r=g.join(e,a);o(r,n),await l(t)}finally{await u()}};return{async get(e){return await d(e)},async list(){if(!i.statSync(e,{throwIfNoEntry:!1}))return[];let t=await c(),n=[];for(let[r,a]of Object.entries(t.ids)){let t=g.join(e,a),o=i.statSync(t,{throwIfNoEntry:!1});if(!o)continue;let s=V(t);n.push({key:r,locked:s.locked,pid:s.pid,mtime:o.mtimeMs})}return n.sort((e,t)=>t.mtime-e.mtime),n},async lock(r,a){if(n.has(r))throw Error(`Key "${r}" is already locked in this process`);let o=await u(r);if(!o){let t=I(r,{replacement:`_`})+`.json`,n=await s();try{let n=await c();n.ids[r]=t;let a=g.join(e,t);ne(e),i.writeFileSync(a,JSON.stringify({}),`utf-8`),await l(n),o=a}finally{await n()}}if(a?.force){let e=V(o);if(e.locked&&e.pid&&e.pid!==process.pid)try{process.kill(e.pid,`SIGTERM`),await new Promise(e=>setTimeout(e,100))}catch(t){t.code!==`ESRCH`&&console.warn(`Failed to kill process ${e.pid}:`,t.message)}}let p=await z(o,{stale:!0,retries:a?.force?10:5,retryInterval:(a?.force,100)});return n.set(r,()=>Promise.resolve(p())),{async get(){let e=await d(r);if(!e)throw Error(`Key ${r} not found`);return e},async set(e){await f(e)},async update(e){let n=await d(r);if(!n||!(t in n))throw Error(`Key ${r} not found`);await f({...n,...e})},async delete(){let t=await s();try{let t=await c(),n=t.ids[r];if(n){delete t.ids[r],t.current===r&&(t.current=void 0),await l(t);let a=g.join(e,n);try{i.rmSync(a,{force:!0}),H(e)}catch{}}}finally{await t()}},async release(){p(),n.delete(r)}}},dispose(){n.clear()}}},U=(e,t)=>{let n=t?.pollInterval??200,r=t?.debounce??50,a=new Set,o,s,c=new Map,l=new Map,u=g.join(e,`index.json`),d=()=>{try{if(!i.statSync(u,{throwIfNoEntry:!1}))return{ids:{}};let e=i.readFileSync(u,`utf-8`);return{ids:JSON.parse(e).ids??{}}}catch{return{ids:{}}}},f=(e,t,n,r)=>{for(let i of a)try{i({key:e,value:t,locked:n,pid:r})}catch(e){console.error(`Error in onChange callback:`,e)}},p=(t,n,r=!1)=>{let a=g.join(e,n);try{let e=i.statSync(a,{throwIfNoEntry:!1}),o=l.get(n);if(!e){o&&(l.delete(n),f(t,void 0,!1));return}let s=e.mtimeMs,c=o?{locked:o.locked,pid:o.pid}:{locked:!1,pid:void 0};if((r||!o)&&(c=V(a)),!o||o.mtime!==s||o.locked!==c.locked||o.pid!==c.pid){let e;e=!o||o.mtime!==s?JSON.parse(i.readFileSync(a,`utf-8`)):o.cachedValue,l.set(n,{mtime:s,key:t,locked:c.locked,pid:c.pid,cachedValue:e}),f(t,e,c.locked,c.pid)}}catch{}},m=()=>{try{let e=d(),t=new Set(Object.keys(e.ids));for(let[t,n]of Object.entries(e.ids))p(t,n,!0);for(let[e,n]of l.entries())t.has(n.key)||(l.delete(e),f(n.key,void 0,!1))}catch{}},h=(e,t,n=!1)=>{let i=c.get(e);i&&clearTimeout(i),c.set(e,setTimeout(()=>{c.delete(e),p(e,t,n)},r))},_=()=>{if(o)return;try{i.mkdirSync(e,{recursive:!0})}catch{}o=i.watch(e,(e,t)=>{if(!t||t.startsWith(`.tmp-`))return;if(t===`index.json`){m();return}if(t.endsWith(`.lock`)){let e=t.replace(`.lock`,``),n=d(),r=Object.keys(n.ids).find(t=>n.ids[t]===e);r&&p(r,e,!0);return}let n=d(),r=Object.keys(n.ids).find(e=>n.ids[e]===t);r&&h(r,t,!1)});let t=()=>{m(),s=setTimeout(t,n)};m(),s=setTimeout(t,n)};return{onChange(e){return a.size===0&&_(),a.add(e),()=>{if(a.delete(e),a.size===0){o&&=(o.close(),void 0),s&&=(clearTimeout(s),void 0);for(let e of c.values())clearTimeout(e);c.clear(),l.clear()}}},dispose(){o&&=(o.close(),void 0),s&&=(clearTimeout(s),void 0);for(let e of c.values())clearTimeout(e);c.clear(),a.clear(),l.clear()}}};async function oe({chatKey:e,agent:t,messages:n,signal:r,shouldContinueStreaming:i=se}){n=[...n];let a=new TransformStream,o=a.writable.getWriter(),s=async()=>{let a;try{let c=await t.chat({messages:n,chat:{key:e}},{signal:r}),l=(0,f.readUIMessageStream)({message:{id:crypto.randomUUID(),role:`assistant`,parts:[],metadata:{}},stream:c,onError:e=>{e instanceof Error&&e.name===`AbortError`||o.abort(e)}});for await(let e of l)o.write(e),a=e;if(a&&i(a)){n.push(a),await s();return}await o.close()}catch(e){if(e?.name===`AbortError`||r?.aborted)return;await o.abort(e)}finally{await o.close()}};return s().catch(e=>{o.abort(e)}),a.readable}const se=e=>{if(e.role!==`assistant`)return!1;let n=e.parts.reduce((e,t,n)=>t.type===`step-start`?n:e,-1),r=e.parts.slice(n+1).filter(f.isToolOrDynamicToolUIPart);return r.length===0||r.some(e=>t.isToolApprovalOutput(e.output)&&e.output.outcome===`pending`)?!1:r.every(e=>e.state.startsWith(`output-`))},ce=(e,t=crypto.randomUUID())=>({created_at:new Date().toISOString(),...e,id:t,metadata:e.metadata});function le(e){return typeof e==`object`&&e?.__blink_internal===!0}var ue=class{chatId;agent;chatStore;serializeMessage;filterMessages;chat;loading=!1;streamingMessage;status=`idle`;queue=[];abortController;isProcessingQueue=!1;listeners=new Set;watcher;disposed=!1;constructor(e){this.chatId=e.chatId,this.chat={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]},this.loading=!0,this.chatStore=ae(e.chatsDirectory,`id`),this.serializeMessage=e.serializeMessage,this.filterMessages=e.filterMessages,this.watcher=U(e.chatsDirectory,{pollInterval:1e3,debounce:50}),this.watcher.onChange(e=>{if(e.key!==this.chatId||this.isProcessingQueue)return;if(!e.value){this.chat={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]},this.status=`idle`,this.streamingMessage=void 0,this.notifyListeners();return}let t=e.value,n=e.value?.error?`error`:`idle`;e.locked&&(n=`streaming`);let r=this.chat.updated_at!==t?.updated_at||this.status!==n;this.chat=t,this.streamingMessage=void 0,this.status=n,r&&this.notifyListeners()}),this.chatStore.get(this.chatId).then(e=>{this.disposed||e&&(this.chat=e)}).catch(e=>{this.chat.error=e instanceof Error?e.message:String(e)}).finally(()=>{this.loading=!1,this.notifyListeners()})}setAgent(e){this.agent=e}getState(){return{id:this.chatId,messages:(this.chat?.messages??[]).filter(e=>!le(e.metadata)),created_at:this.chat?.created_at,updated_at:this.chat?.updated_at,status:this.status,streamingMessage:this.streamingMessage,error:this.chat?.error,loading:this.loading,queuedMessages:this.queue}}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}async upsertMessage(e,t){let n=!1,r;t?r=t:(r=await this.chatStore.lock(this.chatId),n=!0);try{let t=await r.get();(!t.id||!Array.isArray(t.messages))&&(t={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]});let n=e;if(this.serializeMessage){let t=this.serializeMessage(e);if(t===void 0)return;n=t}let i=n.id||crypto.randomUUID(),a=ce(n,i),o=t.messages.find(e=>e.id===a.id)?t.messages.map(e=>e.id===a.id?a:e):[...t.messages,a];this.chat={...t,updated_at:new Date().toISOString(),messages:o},await r.set(this.chat),this.notifyListeners()}finally{n&&await r.release()}}async deleteMessage(e){let t;try{t=await this.chatStore.lock(this.chatId);let n=await t.get();this.chat.messages=n.messages.filter(t=>t.id!==e),this.chat.updated_at=new Date().toISOString(),await t.set(this.chat),this.notifyListeners()}finally{t&&await t.release()}}async sendMessage(e){if(this.status===`streaming`){this.queue.push(e),this.notifyListeners();return}this.queue=[e],await this.processQueue()}async processQueue(){if(!this.agent){this.chat.error=`The agent is not available. Please wait for the build to succeed.`,this.status=`error`,this.queue=[],this.notifyListeners();return}if(this.isProcessingQueue)return;this.isProcessingQueue=!0;let e=new AbortController;this.abortController=e,this.chat.error=void 0;let t;try{for(t=await this.chatStore.lock(this.chatId);this.queue.length>0;){let n=this.queue.shift();if(!n)return;this.status=`streaming`,this.streamingMessage=void 0,await this.upsertMessage(n,t);let r=this.chat.messages;this.filterMessages&&(r=r.filter(this.filterMessages)),r=r.map(e=>({...e,parts:e.parts.map(e=>!(0,f.isToolOrDynamicToolUIPart)(e)||e.input!==``?e:{...e,input:{}})}));let i=await oe({agent:this.agent,chatKey:this.chatId,signal:e.signal,messages:r}),a=async e=>{this.chat.updated_at=new Date().toISOString(),this.chat.messages.push(ce(e)),this.streamingMessage=void 0,await t?.set(this.chat)},o=i.getReader();try{for(;;){let{done:t,value:n}=await o.read();if(t||e.signal.aborted)break;this.streamingMessage&&n.id!==this.streamingMessage.id&&await a(this.streamingMessage),this.streamingMessage=n,this.notifyListeners()}}finally{o.releaseLock()}this.streamingMessage&&await a(this.streamingMessage)}}catch(e){this.chat.error=e instanceof Error?e.message:String(e)}finally{this.isProcessingQueue=!1,this.streamingMessage=void 0,this.chat.error?this.status=`error`:this.status=`idle`,t&&(this.chat.updated_at=new Date().toISOString(),await t.set(this.chat),await t.release(),this.notifyListeners())}}stopStreaming(){this.abortController?.abort(),this.queue.length>0&&setTimeout(()=>{this.processQueue()},100)}clearQueue(){this.queue=[],this.notifyListeners()}async resetChat(){this.abortController?.abort(),this.resetChatState(),this.notifyListeners();let e;try{e=await this.chatStore.lock(this.chatId),await e.delete()}catch{}finally{if(e)try{await e.release()}catch{}}}dispose(){this.disposed=!0,this.watcher.dispose(),this.listeners.clear(),this.abortController?.abort()}resetChatState(){this.chat={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]},this.streamingMessage=void 0,this.status=`idle`,this.queue=[]}notifyListeners(){let e=this.getState();for(let t of this.listeners)t(e)}};function de(e){let{chatId:t,agent:n,chatsDirectory:r,serializeMessage:i,filterMessages:a}=e,o=(0,h.useRef)(null),[s,c]=(0,h.useState)({id:t,messages:[],status:`idle`,loading:!0,queuedMessages:[]});(0,h.useEffect)(()=>{o.current&&o.current.dispose();let e=new ue({chatId:t,chatsDirectory:r,serializeMessage:i,filterMessages:a}),n=e.subscribe(e=>{c(e)});return c(e.getState()),o.current=e,()=>{n(),e.dispose(),o.current=null}},[t,r]),(0,h.useEffect)(()=>{o.current&&o.current.setAgent(n)},[n]);let l=(0,h.useCallback)(async e=>{o.current&&await o.current.sendMessage(e)},[]),u=(0,h.useCallback)(async e=>{o.current&&await o.current.upsertMessage(e)},[]),d=(0,h.useCallback)(()=>{o.current&&o.current.stopStreaming()},[]),f=(0,h.useCallback)(async()=>{o.current&&await o.current.resetChat()},[]),p=(0,h.useCallback)(()=>{o.current&&o.current.clearQueue()},[]),m=(0,h.useCallback)(async e=>{o.current&&await o.current.deleteMessage(e)},[]);return{...s,sendMessage:l,upsertMessage:u,stopStreaming:d,resetChat:f,clearQueue:p,deleteMessage:m}}var fe=Object.getOwnPropertyNames,pe=(e,t)=>function(){return t||(0,e[fe(e)[0]])((t={exports:{}}).exports,t),t.exports},W=(0,_.createRequire)(require(`url`).pathToFileURL(__filename).href);v.z.object({email:v.z.string().email(),password:v.z.string().min(8)}),v.z.object({email:v.z.string().email(),code:v.z.string()}),v.z.object({email:v.z.string().email(),password:v.z.string().min(8)});var me=class{constructor(e,t){this.client=e,this.baseURL=t}async token(e,t={timeout:12e4}){return new Promise((n,r)=>{let i=crypto.randomUUID(),a=this.client.websocket(`/api/auth/token?id=${i}`),o=new URL(`/auth?id=${i}`,this.baseURL),s=setTimeout(()=>{r(Error(`Timeout waiting for the user to authenticate`))},t.timeout);a.onerror=e=>{clearTimeout(s),console.log(`error`,e),r(Error(`Failed to connect to server`))},a.onopen=()=>{e(o.toString(),i)},a.onmessage=e=>{typeof e.data==`string`&&(clearTimeout(s),n(e.data))}})}},he=class extends Error{constructor(e,t){super(e),this.name=`ParseError`,this.type=t.type,this.field=t.field,this.value=t.value,this.line=t.line}};function ge(e){}function _e(e){if(typeof e==`function`)throw TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");let{onEvent:t=ge,onError:n=ge,onRetry:r=ge,onComment:i}=e,a=``,o=!0,s,c=``,l=``;function u(e){let t=o?e.replace(/^\xEF\xBB\xBF/,``):e,[n,r]=G(`${a}${t}`);for(let e of n)d(e);a=r,o=!1}function d(e){if(e===``){p();return}if(e.startsWith(`:`)){i&&i(e.slice(e.startsWith(`: `)?2:1));return}let t=e.indexOf(`:`);if(t!==-1){let n=e.slice(0,t),r=e[t+1]===` `?2:1,i=e.slice(t+r);f(n,i,e);return}f(e,``,e)}function f(e,t,i){switch(e){case`event`:l=t;break;case`data`:c=`${c}${t}
1
+ const e=require(`../chunk-iXuH7AlR.cjs`),t=require(`../index.node-DlfrLUZ3.cjs`);require(`../token-error-BoNG8ooW.cjs`),require(`../esm-0UNjvroT.cjs`);const n=require(`../build-D_HFEWKz.cjs`);let r=require(`zod/v4`);r=e.__toESM(r),require(`zod/v3`);let i=require(`node:fs`);i=e.__toESM(i);let a=require(`node:stream`);a=e.__toESM(a);let o=require(`node:util`);o=e.__toESM(o);let s=require(`http`);s=e.__toESM(s);let c=require(`path`);c=e.__toESM(c);let l=require(`module`);l=e.__toESM(l);let u=require(`fs`);u=e.__toESM(u);let d=require(`node:process`);d=e.__toESM(d);let f=require(`ai`);f=e.__toESM(f);let p=require(`fs/promises`);p=e.__toESM(p);let m=require(`child_process`);m=e.__toESM(m);let h=require(`react`);h=e.__toESM(h);let g=require(`node:path`);g=e.__toESM(g);let _=require(`node:module`);_=e.__toESM(_);let v=require(`zod`);v=e.__toESM(v);let y=require(`node:readline`);y=e.__toESM(y);let b=require(`node:fs/promises`);b=e.__toESM(b);function x(e){let[n,r]=(0,h.useState)(void 0),[i,a]=(0,h.useState)([]),[o,s]=(0,h.useState)(void 0),[c,l]=(0,h.useState)(e.buildResult),[u,d]=(0,h.useState)(e.env),[f,p]=(0,h.useState)(e.apiServerUrl),[g,_]=(0,h.useState)(void 0);return(0,h.useEffect)(()=>{d(e.env),l(e.buildResult),p(e.apiServerUrl)},[e.env,e.buildResult,e.apiServerUrl]),(0,h.useEffect)(()=>{if(!c||`error`in c){r(void 0),a([]),s(void 0);return}let e=new AbortController,n=!1;return s(void 0),(async()=>{let n=await S(),i=(0,m.spawn)(`node`,[`--no-deprecation`,c.entry],{stdio:`pipe`,env:{...process.env,...u,[t.APIServerURLEnvironmentVariable]:f,PORT:n.toString(),HOST:`127.0.0.1`}});e.signal.addEventListener(`abort`,()=>{try{i.kill()}catch{}});let o=!1;i.stdout.on(`data`,e=>{let t=Buffer.from(e).toString(`utf-8`).trim();!o&&t.startsWith(`Agent server listening on`)||(o||console.log(`stdout: ${t}`),t.length&&a(e=>[...e,{level:`log`,message:t}]))}),i.stderr.on(`data`,e=>{o||console.error(`stderr: ${Buffer.from(e).toString(`utf-8`).trim()}`);let t=Buffer.from(e).toString(`utf-8`).trim();t.length&&a(e=>[...e,{level:`error`,message:t}])}),i.on(`error`,t=>{e.abort(t)}),i.on(`exit`,(t,n)=>{e.abort(`Agent exited with code ${t??`unknown`} and signal ${n??`unknown`}. Be sure to call "blink.agent(...).serve()".`)});let s=new t.Client({baseUrl:`http://127.0.0.1:${n}`});for(;!e.signal.aborted;){try{await s.health();break}catch{}await new Promise(e=>setTimeout(e,100))}if(e.signal.aborted)throw e.signal.reason;o=!0;let l=await s.capabilities();_(l),r(s)})().catch(e=>{n||s(e instanceof Error?e:Error(String(e)))}),()=>{n=!0,e.abort()}},[c,u,f]),(0,h.useMemo)(()=>({agent:n,logs:i,error:o,capabilities:g}),[n,i,o,g])}async function S(){let e=(0,s.createServer)();return new Promise((t,n)=>{e.listen(0,()=>{let n=e.address().port;t(n)}).on(`error`,e=>{n(e)})}).finally(()=>{e.close()})}function C(e){let{directory:t,onBuildStart:r,onBuildSuccess:i,onBuildError:a}=typeof e==`string`?{directory:e}:e,o=(0,h.useMemo)(()=>n.resolveConfig(t),[t]),[s,c]=(0,h.useState)(void 0),[l,u]=(0,h.useState)(void 0),[d,f]=(0,h.useState)(`building`),p=(0,h.useRef)(r),m=(0,h.useRef)(i),g=(0,h.useRef)(a);return(0,h.useEffect)(()=>{p.current=r,m.current=i,g.current=a},[r,i,a]),(0,h.useEffect)(()=>{let e=new AbortController;return o.build({cwd:t,entry:o.entry,outdir:o.outdir,watch:!0,dev:!0,signal:e.signal,onStart:()=>{f(`building`),c(void 0),u(void 0),p.current?.()},onResult:e=>{`error`in e?(c(e.error),f(`error`),g.current?.(e.error)):(u(e),f(`success`),m.current?.(e))}}).catch(e=>{console.log(`error`,e),f(`error`),c(e),g.current?.(e)}),()=>{e.abort()}},[t]),(0,h.useMemo)(()=>({error:s,status:d,result:l,entry:o.entry,outdir:o.outdir}),[s,d,l,o.entry,o.outdir])}function w(){return/[<>:"/\\|?*\u0000-\u001F]|[. ]$/g}function T(){return/^(con|prn|aux|nul|com\d|lpt\d)$/i}const E=100,D=/^\.+(\\|\/)|^\.+$/,O=/[. ]+$/,k=/[\p{Control}\p{Format}\p{Zl}\p{Zp}\uFFF0-\uFFFF]/gu,A=/[\p{Control}\p{Format}\p{Zl}\p{Zp}\uFFF0-\uFFFF]/u,j=e=>e===`‍`,M=/([<>:"/\\|?*\u0000-\u001F]){2,}/g,N=/[\t\n\r\u00A0\u1680\u2000-\u200A\u202F\u205F\u3000]+/g;let P;function F(){return P??=new Intl.Segmenter(void 0,{granularity:`grapheme`}),P}function I(e,t={}){if(typeof e!=`string`)throw TypeError(`Expected a string`);let n=t.replacement??`!`;if(w().test(n)||[...n].some(e=>A.test(e)&&!j(e)))throw Error(`Replacement string cannot contain reserved filename characters`);e=e.normalize(`NFC`),e=e.replaceAll(N,` `),n.length>0&&(e=e.replaceAll(M,`$1`)),e=e.replace(O,``),e=e.replace(D,n),e=e.replace(w(),n),e=e.replaceAll(k,e=>j(e)?e:n),e.length===0&&(e=n),e=T().test(e)?e+n:e;let r=typeof t.maxLength==`number`?t.maxLength:100;if(e.length>r){let t=e.lastIndexOf(`.`);if(t===-1)e=ee(e,r);else{let n=e.slice(0,t),i=e.slice(t),a=Math.max(0,r-i.length);e=ee(n,a)+i}}return e}function ee(e,t){if(e.length<=t)return e;let n=0,r=``;for(let{segment:i}of F().segment(e)){let e=n+i.length;if(e>t)break;r+=i,n=e}return r}function L(e){return`${e}.lock`}function R(e){try{return process.kill(e,0),!0}catch(e){return e.code===`EPERM`}}function te(e,t={}){let n=L(e),r=process.pid.toString();try{return i.writeFileSync(n,r,{flag:`wx`}),!0}catch(r){if(r.code!==`EEXIST`)throw r;if(t.stale===0)return!1;let a;try{a=parseInt(i.readFileSync(n,`utf8`),10)}catch{return i.unlinkSync(n),te(e,{...t,stale:0})}if(!R(a))try{return i.unlinkSync(n),te(e,{...t,stale:0})}catch(n){if(n.code===`ENOENT`)return te(e,{...t,stale:0});throw n}return!1}}async function z(e,t={}){let n={stale:!0,retries:0,retryInterval:100,...t},r=g.resolve(e),i=0;for(;i<=n.retries;){if(te(r,n))return()=>B(r);i<n.retries&&await new Promise(e=>setTimeout(e,n.retryInterval)),i++}let a=Error(`Lock file is already being held`);throw a.code=`ELOCKED`,a.file=r,a}function B(e){let t=g.resolve(e),n=L(t);try{if(parseInt(i.readFileSync(n,`utf8`),10)!==process.pid){let e=Error(`Lock is not owned by this process`);throw e.code=`ENOTACQUIRED`,e}i.unlinkSync(n)}catch(e){if(e.code===`ENOENT`){let e=Error(`Lock is not acquired`);throw e.code=`ENOTACQUIRED`,e}throw e}}function V(e){let t=g.resolve(e),n=L(t);try{if(!i.existsSync(n))return{locked:!1};let e=i.readFileSync(n,`utf8`),t=parseInt(e,10);return R(t)?{locked:!0,pid:t}:{locked:!1}}catch(e){return e.code,{locked:!1}}}const ne=e=>{i.mkdirSync(e,{recursive:!0})},re=e=>{try{i.fdatasyncSync(e)}catch{}try{i.closeSync(e)}catch{}},H=e=>{try{let t=i.openSync(e,`r`);try{i.fsyncSync(t)}finally{i.closeSync(t)}}catch{}},ie=(e,t)=>{let n=g.dirname(e);ne(n);let r=g.join(n,`.tmp-`+process.pid+`-`+Math.random().toString(36).slice(2)),a;try{a=i.openSync(r,`w`),i.writeFileSync(a,t,`utf-8`),re(a),a=void 0,i.renameSync(r,e),H(e),H(n)}catch(e){if(a!==void 0)try{i.closeSync(a)}catch{}try{i.rmSync(r,{force:!0})}catch{}throw e}},ae=(e,t)=>{let n=new Map,r,a=e=>{if(i.statSync(e,{throwIfNoEntry:!1}))return JSON.parse(i.readFileSync(e,`utf-8`))},o=(e,t)=>{ie(e,JSON.stringify(t,null,2))},s=async()=>{if(r)throw Error(`Index is already locked`);let t=g.join(e,`index.json`);ne(e),i.existsSync(t)||i.writeFileSync(t,JSON.stringify({ids:{}}),`utf-8`);let n=await z(t,{stale:!0,retries:5,retryInterval:100});return r=()=>Promise.resolve(n()),()=>{n(),r=void 0}},c=async()=>{let t=g.join(e,`index.json`),n=a(t)??{ids:{}};return n.ids||={},n},l=async t=>{let n=g.join(e,`index.json`);o(n,t)},u=async t=>{let n=(await c()).ids[t];if(n)return g.join(e,n)},d=async t=>{let n=(await c()).ids[t];if(!n)return;let r=g.join(e,n);if(i.statSync(r,{throwIfNoEntry:!1}))return JSON.parse(i.readFileSync(r,`utf-8`))},f=async n=>{let r=n[t],i=String(r),a=I(i,{replacement:`_`})+`.json`,u=await s();try{let t=await c();t.ids[i]=a,t.current=i;let r=g.join(e,a);o(r,n),await l(t)}finally{await u()}};return{async get(e){return await d(e)},async list(){if(!i.statSync(e,{throwIfNoEntry:!1}))return[];let t=await c(),n=[];for(let[r,a]of Object.entries(t.ids)){let t=g.join(e,a),o=i.statSync(t,{throwIfNoEntry:!1});if(!o)continue;let s=V(t);n.push({key:r,locked:s.locked,pid:s.pid,mtime:o.mtimeMs})}return n.sort((e,t)=>t.mtime-e.mtime),n},async lock(r,a){if(n.has(r))throw Error(`Key "${r}" is already locked in this process`);let o=await u(r);if(!o){let t=I(r,{replacement:`_`})+`.json`,n=await s();try{let n=await c();n.ids[r]=t;let a=g.join(e,t);ne(e),i.writeFileSync(a,JSON.stringify({}),`utf-8`),await l(n),o=a}finally{await n()}}if(a?.force){let e=V(o);if(e.locked&&e.pid&&e.pid!==process.pid)try{process.kill(e.pid,`SIGTERM`),await new Promise(e=>setTimeout(e,100))}catch(t){t.code!==`ESRCH`&&console.warn(`Failed to kill process ${e.pid}:`,t.message)}}let p=await z(o,{stale:!0,retries:a?.force?10:5,retryInterval:(a?.force,100)});return n.set(r,()=>Promise.resolve(p())),{async get(){let e=await d(r);if(!e)throw Error(`Key ${r} not found`);return e},async set(e){await f(e)},async update(e){let n=await d(r);if(!n||!(t in n))throw Error(`Key ${r} not found`);await f({...n,...e})},async delete(){let t=await s();try{let t=await c(),n=t.ids[r];if(n){delete t.ids[r],t.current===r&&(t.current=void 0),await l(t);let a=g.join(e,n);try{i.rmSync(a,{force:!0}),H(e)}catch{}}}finally{await t()}},async release(){p(),n.delete(r)}}},dispose(){n.clear()}}},U=(e,t)=>{let n=t?.pollInterval??200,r=t?.debounce??50,a=new Set,o,s,c=new Map,l=new Map,u=g.join(e,`index.json`),d=()=>{try{if(!i.statSync(u,{throwIfNoEntry:!1}))return{ids:{}};let e=i.readFileSync(u,`utf-8`);return{ids:JSON.parse(e).ids??{}}}catch{return{ids:{}}}},f=(e,t,n,r)=>{for(let i of a)try{i({key:e,value:t,locked:n,pid:r})}catch(e){console.error(`Error in onChange callback:`,e)}},p=(t,n,r=!1)=>{let a=g.join(e,n);try{let e=i.statSync(a,{throwIfNoEntry:!1}),o=l.get(n);if(!e){o&&(l.delete(n),f(t,void 0,!1));return}let s=e.mtimeMs,c=o?{locked:o.locked,pid:o.pid}:{locked:!1,pid:void 0};if((r||!o)&&(c=V(a)),!o||o.mtime!==s||o.locked!==c.locked||o.pid!==c.pid){let e;e=!o||o.mtime!==s?JSON.parse(i.readFileSync(a,`utf-8`)):o.cachedValue,l.set(n,{mtime:s,key:t,locked:c.locked,pid:c.pid,cachedValue:e}),f(t,e,c.locked,c.pid)}}catch{}},m=()=>{try{let e=d(),t=new Set(Object.keys(e.ids));for(let[t,n]of Object.entries(e.ids))p(t,n,!0);for(let[e,n]of l.entries())t.has(n.key)||(l.delete(e),f(n.key,void 0,!1))}catch{}},h=(e,t,n=!1)=>{let i=c.get(e);i&&clearTimeout(i),c.set(e,setTimeout(()=>{c.delete(e),p(e,t,n)},r))},_=()=>{if(o)return;try{i.mkdirSync(e,{recursive:!0})}catch{}o=i.watch(e,(e,t)=>{if(!t||t.startsWith(`.tmp-`))return;if(t===`index.json`){m();return}if(t.endsWith(`.lock`)){let e=t.replace(`.lock`,``),n=d(),r=Object.keys(n.ids).find(t=>n.ids[t]===e);r&&p(r,e,!0);return}let n=d(),r=Object.keys(n.ids).find(e=>n.ids[e]===t);r&&h(r,t,!1)});let t=()=>{m(),s=setTimeout(t,n)};m(),s=setTimeout(t,n)};return{onChange(e){return a.size===0&&_(),a.add(e),()=>{if(a.delete(e),a.size===0){o&&=(o.close(),void 0),s&&=(clearTimeout(s),void 0);for(let e of c.values())clearTimeout(e);c.clear(),l.clear()}}},dispose(){o&&=(o.close(),void 0),s&&=(clearTimeout(s),void 0);for(let e of c.values())clearTimeout(e);c.clear(),a.clear(),l.clear()}}};async function oe({chatKey:e,agent:t,messages:n,signal:r,shouldContinueStreaming:i=se}){n=[...n];let a=new TransformStream,o=a.writable.getWriter(),s=async()=>{let a;try{let c=await t.chat({messages:n,chat:{key:e}},{signal:r}),l=(0,f.readUIMessageStream)({message:{id:crypto.randomUUID(),role:`assistant`,parts:[],metadata:{}},stream:c,onError:e=>{e instanceof Error&&e.name===`AbortError`||o.abort(e)}});for await(let e of l)o.write(e),a=e;if(a&&i(a)){n.push(a),await s();return}await o.close()}catch(e){if(e?.name===`AbortError`||r?.aborted)return;await o.abort(e)}finally{await o.close()}};return s().catch(e=>{o.abort(e)}),a.readable}const se=e=>{if(e.role!==`assistant`)return!1;let n=e.parts.reduce((e,t,n)=>t.type===`step-start`?n:e,-1),r=e.parts.slice(n+1).filter(f.isToolOrDynamicToolUIPart);return r.length===0||r.some(e=>t.isToolApprovalOutput(e.output)&&e.output.outcome===`pending`)?!1:r.every(e=>e.state.startsWith(`output-`))},ce=(e,t=crypto.randomUUID())=>({created_at:new Date().toISOString(),...e,id:t,metadata:e.metadata});function le(e){return typeof e==`object`&&e?.__blink_internal===!0}var ue=class{chatId;agent;chatStore;serializeMessage;filterMessages;chat;loading=!1;streamingMessage;status=`idle`;queue=[];abortController;isProcessingQueue=!1;listeners=new Set;watcher;disposed=!1;constructor(e){this.chatId=e.chatId,this.chat={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]},this.loading=!0,this.chatStore=ae(e.chatsDirectory,`id`),this.serializeMessage=e.serializeMessage,this.filterMessages=e.filterMessages,this.watcher=U(e.chatsDirectory,{pollInterval:1e3,debounce:50}),this.watcher.onChange(e=>{if(e.key!==this.chatId||this.isProcessingQueue)return;if(!e.value){this.chat={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]},this.status=`idle`,this.streamingMessage=void 0,this.notifyListeners();return}let t=e.value,n=e.value?.error?`error`:`idle`;e.locked&&(n=`streaming`);let r=this.chat.updated_at!==t?.updated_at||this.status!==n;this.chat=t,this.streamingMessage=void 0,this.status=n,r&&this.notifyListeners()}),this.chatStore.get(this.chatId).then(e=>{this.disposed||e&&(this.chat=e)}).catch(e=>{this.chat.error=e instanceof Error?e.message:String(e)}).finally(()=>{this.loading=!1,this.notifyListeners()})}setAgent(e){this.agent=e}getState(){return{id:this.chatId,messages:(this.chat?.messages??[]).filter(e=>!le(e.metadata)),created_at:this.chat?.created_at,updated_at:this.chat?.updated_at,status:this.status,streamingMessage:this.streamingMessage,error:this.chat?.error,loading:this.loading,queuedMessages:this.queue}}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}async upsertMessage(e,t){let n=!1,r;t?r=t:(r=await this.chatStore.lock(this.chatId),n=!0);try{let t=await r.get();(!t.id||!Array.isArray(t.messages))&&(t={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]});let n=e;if(this.serializeMessage){let t=this.serializeMessage(e);if(t===void 0)return;n=t}let i=n.id||crypto.randomUUID(),a=ce(n,i),o=t.messages.find(e=>e.id===a.id)?t.messages.map(e=>e.id===a.id?a:e):[...t.messages,a];this.chat={...t,updated_at:new Date().toISOString(),messages:o},await r.set(this.chat),this.notifyListeners()}finally{n&&await r.release()}}async deleteMessage(e){let t;try{t=await this.chatStore.lock(this.chatId);let n=await t.get();this.chat.messages=n.messages.filter(t=>t.id!==e),this.chat.updated_at=new Date().toISOString(),await t.set(this.chat),this.notifyListeners()}finally{t&&await t.release()}}async sendMessage(e){if(this.status===`streaming`){this.queue.push(e),this.notifyListeners();return}this.queue=[e],await this.processQueueOrRun()}async start(){await this.processQueueOrRun()}async processQueueOrRun(){if(!this.agent){this.chat.error=`The agent is not available. Please wait for the build to succeed.`,this.status=`error`,this.queue=[],this.notifyListeners();return}if(this.isProcessingQueue)return;this.isProcessingQueue=!0;let e=new AbortController;this.abortController=e,this.chat.error=void 0;let t;try{t=await this.chatStore.lock(this.chatId);let n=!0;for(;this.queue.length>0||n;){n=!1;let r=this.queue.shift();this.status=`streaming`,this.streamingMessage=void 0,r&&await this.upsertMessage(r,t);let i=this.chat.messages;this.filterMessages&&(i=i.filter(this.filterMessages)),i=i.map(e=>({...e,parts:e.parts.map(e=>!(0,f.isToolOrDynamicToolUIPart)(e)||e.input!==``?e:{...e,input:{}})}));let a=await oe({agent:this.agent,chatKey:this.chatId,signal:e.signal,messages:i}),o=async e=>{this.chat.updated_at=new Date().toISOString(),this.chat.messages.push(ce(e)),this.streamingMessage=void 0,await t?.set(this.chat)},s=a.getReader();try{for(;;){let{done:t,value:n}=await s.read();if(t||e.signal.aborted)break;this.streamingMessage&&n.id!==this.streamingMessage.id&&await o(this.streamingMessage),this.streamingMessage=n,this.notifyListeners()}}finally{s.releaseLock()}this.streamingMessage&&await o(this.streamingMessage)}}catch(e){this.chat.error=e instanceof Error?e.message:String(e)}finally{this.isProcessingQueue=!1,this.streamingMessage=void 0,this.chat.error?this.status=`error`:this.status=`idle`,t&&(this.chat.updated_at=new Date().toISOString(),await t.set(this.chat),await t.release(),this.notifyListeners())}}stopStreaming(){this.abortController?.abort(),this.queue.length>0&&setTimeout(()=>{this.processQueueOrRun()},100)}clearQueue(){this.queue=[],this.notifyListeners()}async resetChat(){this.abortController?.abort(),this.resetChatState(),this.notifyListeners();let e;try{e=await this.chatStore.lock(this.chatId),await e.delete()}catch{}finally{if(e)try{await e.release()}catch{}}}dispose(){this.disposed=!0,this.watcher.dispose(),this.listeners.clear(),this.abortController?.abort()}resetChatState(){this.chat={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]},this.streamingMessage=void 0,this.status=`idle`,this.queue=[]}notifyListeners(){let e=this.getState();for(let t of this.listeners)t(e)}};function de(e){let{chatId:t,agent:n,chatsDirectory:r,serializeMessage:i,filterMessages:a}=e,o=(0,h.useRef)(null),[s,c]=(0,h.useState)({id:t,messages:[],status:`idle`,loading:!0,queuedMessages:[]});(0,h.useEffect)(()=>{o.current&&o.current.dispose();let e=new ue({chatId:t,chatsDirectory:r,serializeMessage:i,filterMessages:a}),n=e.subscribe(e=>{c(e)});return c(e.getState()),o.current=e,()=>{n(),e.dispose(),o.current=null}},[t,r]),(0,h.useEffect)(()=>{o.current&&o.current.setAgent(n)},[n]);let l=(0,h.useCallback)(async e=>{o.current&&await o.current.sendMessage(e)},[]),u=(0,h.useCallback)(async e=>{o.current&&await o.current.upsertMessage(e)},[]),d=(0,h.useCallback)(()=>{o.current&&o.current.stopStreaming()},[]),f=(0,h.useCallback)(async()=>{o.current&&await o.current.resetChat()},[]),p=(0,h.useCallback)(()=>{o.current&&o.current.clearQueue()},[]),m=(0,h.useCallback)(async e=>{o.current&&await o.current.deleteMessage(e)},[]);return{...s,sendMessage:l,upsertMessage:u,stopStreaming:d,resetChat:f,clearQueue:p,deleteMessage:m}}var fe=Object.getOwnPropertyNames,pe=(e,t)=>function(){return t||(0,e[fe(e)[0]])((t={exports:{}}).exports,t),t.exports},W=(0,_.createRequire)(require(`url`).pathToFileURL(__filename).href);v.z.object({email:v.z.string().email(),password:v.z.string().min(8)}),v.z.object({email:v.z.string().email(),code:v.z.string()}),v.z.object({email:v.z.string().email(),password:v.z.string().min(8)});var me=class{constructor(e,t){this.client=e,this.baseURL=t}async token(e,t={timeout:12e4}){return new Promise((n,r)=>{let i=crypto.randomUUID(),a=this.client.websocket(`/api/auth/token?id=${i}`),o=new URL(`/auth?id=${i}`,this.baseURL),s=setTimeout(()=>{r(Error(`Timeout waiting for the user to authenticate`))},t.timeout);a.onerror=e=>{clearTimeout(s),console.log(`error`,e),r(Error(`Failed to connect to server`))},a.onopen=()=>{e(o.toString(),i)},a.onmessage=e=>{typeof e.data==`string`&&(clearTimeout(s),n(e.data))}})}},he=class extends Error{constructor(e,t){super(e),this.name=`ParseError`,this.type=t.type,this.field=t.field,this.value=t.value,this.line=t.line}};function ge(e){}function _e(e){if(typeof e==`function`)throw TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");let{onEvent:t=ge,onError:n=ge,onRetry:r=ge,onComment:i}=e,a=``,o=!0,s,c=``,l=``;function u(e){let t=o?e.replace(/^\xEF\xBB\xBF/,``):e,[n,r]=G(`${a}${t}`);for(let e of n)d(e);a=r,o=!1}function d(e){if(e===``){p();return}if(e.startsWith(`:`)){i&&i(e.slice(e.startsWith(`: `)?2:1));return}let t=e.indexOf(`:`);if(t!==-1){let n=e.slice(0,t),r=e[t+1]===` `?2:1,i=e.slice(t+r);f(n,i,e);return}f(e,``,e)}function f(e,t,i){switch(e){case`event`:l=t;break;case`data`:c=`${c}${t}
2
2
  `;break;case`id`:s=t.includes(`\0`)?void 0:t;break;case`retry`:/^\d+$/.test(t)?r(parseInt(t,10)):n(new he(`Invalid \`retry\` value: "${t}"`,{type:`invalid-retry`,value:t,line:i}));break;default:n(new he(`Unknown field "${e.length>20?`${e.slice(0,20)}\u2026`:e}"`,{type:`unknown-field`,field:e,value:t,line:i}));break}}function p(){c.length>0&&t({id:s,event:l||void 0,data:c.endsWith(`
3
3
  `)?c.slice(0,-1):c}),s=void 0,c=``,l=``}function m(e={}){a&&e.consume&&d(a),o=!0,s=void 0,c=``,l=``,a=``}return{feed:u,reset:m}}function G(e){let t=[],n=``,r=0;for(;r<e.length;){let i=e.indexOf(`\r`,r),a=e.indexOf(`
4
4
  `,r),o=-1;if(i!==-1&&a!==-1?o=Math.min(i,a):i===-1?a!==-1&&(o=a):o=i===e.length-1?-1:i,o===-1){n=e.slice(r);break}else{let n=e.slice(r,o);t.push(n),r=o+1,e[r-1]===`\r`&&e[r]===`
@@ -125,7 +125,7 @@ ${Ea}${t.trimStart()}`),n=3+(0,o.stripVTControlCharacters)(t.trimStart()).length
125
125
  `);process.stdout.write(Hi.cursor.move(-999,e.length-1)),process.stdout.write(Hi.erase.down(e.length))},g=e=>e.replace(/\.+$/,``),_=e=>{let t=(performance.now()-e)/1e3,n=Math.floor(t/60),r=Math.floor(t%60);return n>0?`[${n}m ${r}s]`:`[${r}s]`},v=(u=``)=>{o=!0,i=ui(),s=g(u),l=performance.now(),process.stdout.write(`${J.default.gray(Y)}
126
126
  `);let d=0,f=0;p(),a=setInterval(()=>{if(r&&s===c)return;h(),c=s;let n=J.default.magenta(t[d]);if(r)process.stdout.write(`${n} ${s}...`);else if(e===`timer`)process.stdout.write(`${n} ${s} ${_(l)}`);else{let e=`.`.repeat(Math.floor(f)).slice(0,3);process.stdout.write(`${n} ${s}${e}`)}d=d+1<t.length?d+1:0,f=f<t.length?f+.125:0},n)},y=(t=``,n=0)=>{o=!1,clearInterval(a),h();let r=n===0?J.default.green(Yi):n===1?J.default.red(qi):J.default.red(Ji);s=g(t??s),e===`timer`?process.stdout.write(`${r} ${s} ${_(l)}
127
127
  `):process.stdout.write(`${r} ${s}
128
- `),m(),i()};return{start:v,stop:y,message:(e=``)=>{s=g(e??s)}}},ka=async(e,t)=>{let n={},r=Object.keys(e);for(let i of r){let r=e[i],a=await r({results:n})?.catch(e=>{throw e});if(typeof t?.onCancel==`function`&&ci(a)){n[i]=`canceled`,t.onCancel({results:n});continue}n[i]=a}return n},Aa=async e=>{for(let t of e){if(t.enabled===!1)continue;let e=Oa();e.start(t.title);let n=await t.task(e.message);e.stop(n||t.title)}};function ja(){let e=Ma();if((0,u.existsSync)(e)){let t=(0,u.readFileSync)(e,`utf8`);return JSON.parse(t).token}}function Ma(){let e=ur(`blink`).dataDirs();if(e.length===0)throw Error(`No suitable data directory for Blink storage found!`);return(0,c.join)(e[0],`auth.json`)}function Na(e){let t=(0,c.join)(e,`data`,`devhook.txt`);if((0,u.mkdirSync)((0,c.dirname)(t),{recursive:!0}),(0,u.existsSync)(t))return(0,u.readFileSync)(t,`utf-8`);let n=crypto.randomUUID();return(0,u.writeFileSync)(t,n),n}const Pa=(e,t)=>e.json({error:t},400),Fa=e=>{let t=e.req.param(`key`);return!t||t===``?{key:t,err:`Key is required`}:t.length>475?{key:t,err:`Key is too long. Max length is 475 characters.`}:{key:t}},Ia=()=>new t.Hono,La=Ia().get(`/:key`,async e=>{let{key:t,err:n}=Fa(e);if(n)return Pa(e,n);let r=await e.env.context.store.get(t);return e.json({value:r},200)}).post(`/:key`,t.validator(`json`,(e,t)=>{let n=e.value;return n?typeof n==`string`?n.length>2e4?Pa(t,`Value is too long. Max length is 20,000 characters.`):{value:n}:Pa(t,`Value must be a string`):Pa(t,`Value is required`)}),async e=>{let{key:t,err:n}=Fa(e);if(n)return Pa(e,n);let{value:r}=e.req.valid(`json`);return await e.env.context.store.set(t,r),e.body(null,204)}).delete(`/:key`,async e=>{let{key:t,err:n}=Fa(e);return n?Pa(e,n):(await e.env.context.store.delete(t),e.body(null,204))}).get(`/`,async e=>{let{cursor:t,limit:n,prefix:r}=e.req.query(),{entries:i,cursor:a}=await e.env.context.store.list(r,{cursor:t?String(t):void 0,limit:n?Number(n):100});return e.json({entries:i,cursor:a})}),Ra=e=>{let t=e.req.param(`key`);return t?t.length>475?{key:t,err:`Key is too long. Max length is 475 characters.`}:{key:t}:{key:t,err:`Key is required`}},za=Ia().basePath(`/:key`).post(`/`,async e=>{let{key:t,err:n}=Ra(e);return n?Pa(e,n):e.json(await e.env.context.chat.ensure(t),200)}).post(`/sendMessages`,t.validator(`json`,(e,t)=>({message:e.message,options:e.options})),async e=>{let{key:t,err:n}=Ra(e);if(n)return Pa(e,n);let{message:r,options:i}=e.req.valid(`json`);try{await e.env.context.chat.message(t,r,i)}catch(t){return Pa(e,t instanceof Error?t.message:`Unknown error`)}return e.body(null,204)}),Ba=Ia().post(`/v1/traces`,async e=>e.env.context.otlp?e.env.context.otlp.traces(e.req.raw):e.body(null,204)),Va=new t.Hono().route(`/kv`,La).route(`/chat`,za).route(`/otlp`,Ba);function Ha(e){let n=(0,g.join)(e.dataDirectory,`chats`),r={},a=(0,g.join)(e.dataDirectory,`storage.json`);i.existsSync(a)&&(r=JSON.parse(i.readFileSync(a,`utf-8`)));let o=new Map,c=t=>{let r=o.get(t);return r||(r=new ue({chatId:t,chatsDirectory:n}),r.setAgent(e.getAgent()),o.set(t,r)),r},l={chat:{async ensure(e){let t=c(e).getState(),n=t.messages.length===0&&!t.created_at;return{key:e,created:n}},async message(e,t,n){let r=c(e),i=ce(t);if(n?.behavior===`append`){await r.upsertMessage(i);return}if(n?.behavior===`interrupt`){await r.sendMessage(i);return}await r.sendMessage(i)}},store:{get(e){return Promise.resolve(r[e])},set(e,t){return r[e]=t,i.writeFileSync(a,JSON.stringify(r),`utf-8`),Promise.resolve()},delete(e){return delete r[e],i.writeFileSync(a,JSON.stringify(r),`utf-8`),Promise.resolve()},list(e,t){let n=Math.min(t?.limit??100,1e3),i=t?.cursor,a=Object.keys(r).filter(t=>t.startsWith(e??``)).sort(),o=0;if(i){let e=a.indexOf(i);e!==-1&&(o=e+1)}let s=a.slice(o,o+n),c=o+n<a.length?s[s.length-1]:void 0;return Promise.resolve({entries:s.map(e=>({key:e})),cursor:c})}}},u=(0,s.createServer)(t.createServerAdapter(e=>Va.fetch(e,{context:l})));u.listen(e.port??0);let d=ae(n,`id`);return{url:`http://127.0.0.1:${u.address().port}`,runtime:l,chatsDirectory:n,getChatManager:c,listChats:()=>d.list(),lockChat:e=>d.lock(e),startChat:e=>{c(e)},stopChat:e=>{o.get(e)?.stopStreaming()},dispose:()=>{for(let e of o.values())e.dispose();o.clear(),d.dispose(),u.close()}}}function Ua({agent:e,capabilities:n,messages:r}){let[i,a]=(0,h.useState)(void 0),[o,s]=(0,h.useState)(!0),[c,l]=(0,h.useState)(void 0),u=(0,h.useRef)(c);(0,h.useEffect)(()=>{u.current=c},[c]);let[d,f]=(0,h.useState)(()=>t.lastUIOptions(r));(0,h.useEffect)(()=>{f(e=>{let n=t.lastUIOptions(r);return JSON.stringify(n)===JSON.stringify(e)?e:n})},[r]);let[p,m]=(0,h.useState)(void 0),g=(0,h.useCallback)((e,t)=>{if(!u.current)return!1;let n=u.current[e];return n?n.values.some(e=>e.id===t):!1},[]),_=(0,h.useCallback)(e=>{m(t=>{let n={...d,...t,...e};for(let[e,t]of Object.entries(n))g(e,t)||delete n[e];for(let[e,t]of Object.entries(u.current??{}))!n[e]&&t.defaultValue!==void 0&&(n[e]=t.defaultValue);return JSON.stringify(n)===JSON.stringify(t)?t:n})},[d,g]);(0,h.useEffect)(()=>{if(!d&&!c){m(void 0);return}_()},[d,c,_]);let v=(0,h.useRef)(void 0),y=(0,h.useRef)(void 0);(0,h.useEffect)(()=>{e!==y.current&&(y.current=e,l(void 0),m(void 0),a(void 0),s(!0),v.current=void 0)},[e]),(0,h.useEffect)(()=>{if(n&&!n.ui||!e){l(void 0),m(void 0),a(void 0),v.current=void 0;return}let t=p?JSON.stringify(p):``;if(v.current===t){s(!1),a(void 0);return}let r=new AbortController;return s(!0),a(void 0),e.ui(p?{selectedOptions:p}:{},{signal:r.signal}).then(e=>{if(!e){l(void 0);return}r.signal.aborted||(l(t=>JSON.stringify(t)===JSON.stringify(e)?t:e),v.current=t)}).catch(e=>{r.signal.aborted||a(e instanceof Error?e:Error(String(e)))}).finally(()=>{s(!1)}),()=>{r.abort()}},[e,n,p]);let b=(0,h.useCallback)((e,t)=>{_({[e]:t})},[_]);return{schema:c,options:p,setOption:b,loading:o,error:i}}function Wa(e){let t=(0,h.useRef)(e.onRequest);(0,h.useEffect)(()=>{t.current=e.onRequest},[e.onRequest]);let n=(0,h.useRef)(e.id??crypto.randomUUID()),[r,i]=(0,h.useState)(`disconnected`);return(0,h.useEffect)(()=>{if(e.disabled){i(`disconnected`);return}let r=!1,a,o,s=!1,c=()=>{if(!(r||s)){if(s=!0,a){try{a.dispose()}catch{}a=void 0}a=new $n({baseURL:`https://blink.so`}).devhook.listen({id:n.current,onRequest:async e=>t.current(e),onConnect:()=>{s=!1,i(`connected`)},onDisconnect:()=>{s=!1,i(`disconnected`),!r&&!o&&(o=setTimeout(()=>{o=void 0,c()},2e3))},onError:e=>{s=!1,i(`error`),!r&&!o&&(o=setTimeout(()=>{o=void 0,c()},2e3))}})}};return c(),()=>{if(r=!0,o&&=(clearTimeout(o),void 0),a){try{a.dispose()}catch{}a=void 0}}},[e.disabled]),{id:n.current,status:r}}var Ga=e.__commonJSMin(((e,t)=>{t.exports={name:`dotenv`,version:`17.2.3`,description:`Loads environment variables from .env file`,main:`lib/main.js`,types:`lib/main.d.ts`,exports:{".":{types:`./lib/main.d.ts`,require:`./lib/main.js`,default:`./lib/main.js`},"./config":`./config.js`,"./config.js":`./config.js`,"./lib/env-options":`./lib/env-options.js`,"./lib/env-options.js":`./lib/env-options.js`,"./lib/cli-options":`./lib/cli-options.js`,"./lib/cli-options.js":`./lib/cli-options.js`,"./package.json":`./package.json`},scripts:{"dts-check":`tsc --project tests/types/tsconfig.json`,lint:`standard`,pretest:`npm run lint && npm run dts-check`,test:`tap run tests/**/*.js --allow-empty-coverage --disable-coverage --timeout=60000`,"test:coverage":`tap run tests/**/*.js --show-full-coverage --timeout=60000 --coverage-report=text --coverage-report=lcov`,prerelease:`npm test`,release:`standard-version`},repository:{type:`git`,url:`git://github.com/motdotla/dotenv.git`},homepage:`https://github.com/motdotla/dotenv#readme`,funding:`https://dotenvx.com`,keywords:[`dotenv`,`env`,`.env`,`environment`,`variables`,`config`,`settings`],readmeFilename:`README.md`,license:`BSD-2-Clause`,devDependencies:{"@types/node":`^18.11.3`,decache:`^4.6.2`,sinon:`^14.0.1`,standard:`^17.0.0`,"standard-version":`^9.5.0`,tap:`^19.2.0`,typescript:`^4.8.4`},engines:{node:`>=12`},browser:{fs:!1}}})),Ka=e.__commonJSMin(((e,t)=>{let n=require(`fs`),r=require(`path`),i=require(`os`),a=require(`crypto`),o=Ga().version,s=[`🔐 encrypt with Dotenvx: https://dotenvx.com`,`🔐 prevent committing .env to code: https://dotenvx.com/precommit`,`🔐 prevent building .env in docker: https://dotenvx.com/prebuild`,`📡 add observability to secrets: https://dotenvx.com/ops`,`👥 sync secrets across teammates & machines: https://dotenvx.com/ops`,`🗂️ backup and recover secrets: https://dotenvx.com/ops`,`✅ audit secrets and track compliance: https://dotenvx.com/ops`,`🔄 add secrets lifecycle management: https://dotenvx.com/ops`,`🔑 add access controls to secrets: https://dotenvx.com/ops`,"🛠️ run anywhere with `dotenvx run -- yourcommand`",`⚙️ specify custom .env file path with { path: '/custom/path/.env' }`,`⚙️ enable debug logging with { debug: true }`,`⚙️ override existing env vars with { override: true }`,`⚙️ suppress all logs with { quiet: true }`,`⚙️ write to custom object with { processEnv: myObject }`,`⚙️ load multiple .env files with { path: ['.env.local', '.env'] }`];function c(){return s[Math.floor(Math.random()*s.length)]}function l(e){return typeof e==`string`?![`false`,`0`,`no`,`off`,``].includes(e.toLowerCase()):!!e}function u(){return process.stdout.isTTY}function d(e){return u()?`\x1b[2m${e}\x1b[0m`:e}let f=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/gm;function p(e){let t={},n=e.toString();n=n.replace(/\r\n?/gm,`
128
+ `),m(),i()};return{start:v,stop:y,message:(e=``)=>{s=g(e??s)}}},ka=async(e,t)=>{let n={},r=Object.keys(e);for(let i of r){let r=e[i],a=await r({results:n})?.catch(e=>{throw e});if(typeof t?.onCancel==`function`&&ci(a)){n[i]=`canceled`,t.onCancel({results:n});continue}n[i]=a}return n},Aa=async e=>{for(let t of e){if(t.enabled===!1)continue;let e=Oa();e.start(t.title);let n=await t.task(e.message);e.stop(n||t.title)}};function ja(){let e=Ma();if((0,u.existsSync)(e)){let t=(0,u.readFileSync)(e,`utf8`);return JSON.parse(t).token}}function Ma(){let e=ur(`blink`).dataDirs();if(e.length===0)throw Error(`No suitable data directory for Blink storage found!`);return(0,c.join)(e[0],`auth.json`)}function Na(e){let t=(0,c.join)(e,`data`,`devhook.txt`);if((0,u.mkdirSync)((0,c.dirname)(t),{recursive:!0}),(0,u.existsSync)(t))return(0,u.readFileSync)(t,`utf-8`);let n=crypto.randomUUID();return(0,u.writeFileSync)(t,n),n}const Pa=(e,t)=>e.json({error:t},400),Fa=e=>{let t=e.req.param(`key`);return!t||t===``?{key:t,err:`Key is required`}:t.length>475?{key:t,err:`Key is too long. Max length is 475 characters.`}:{key:t}},Ia=()=>new t.Hono,La=Ia().get(`/:key`,async e=>{let{key:t,err:n}=Fa(e);if(n)return Pa(e,n);let r=await e.env.context.store.get(t);return e.json({value:r},200)}).post(`/:key`,t.validator(`json`,(e,t)=>{let n=e.value;return n?typeof n==`string`?n.length>2e4?Pa(t,`Value is too long. Max length is 20,000 characters.`):{value:n}:Pa(t,`Value must be a string`):Pa(t,`Value is required`)}),async e=>{let{key:t,err:n}=Fa(e);if(n)return Pa(e,n);let{value:r}=e.req.valid(`json`);return await e.env.context.store.set(t,r),e.body(null,204)}).delete(`/:key`,async e=>{let{key:t,err:n}=Fa(e);return n?Pa(e,n):(await e.env.context.store.delete(t),e.body(null,204))}).get(`/`,async e=>{let{cursor:t,limit:n,prefix:r}=e.req.query(),{entries:i,cursor:a}=await e.env.context.store.list(r,{cursor:t?String(t):void 0,limit:n?Number(n):100});return e.json({entries:i,cursor:a})}),Ra=e=>{let t=e.req.param(`key`);return t?t.length>475?{key:t,err:`Key is too long. Max length is 475 characters.`}:{key:t}:{key:t,err:`Key is required`}},za=Ia().basePath(`/:key`).post(`/`,async e=>{let{key:t,err:n}=Ra(e);return n?Pa(e,n):e.json(await e.env.context.chat.ensure(t),200)}).post(`/sendMessages`,t.validator(`json`,(e,t)=>({message:e.message,options:e.options})),async e=>{let{key:t,err:n}=Ra(e);if(n)return Pa(e,n);let{message:r,options:i}=e.req.valid(`json`);try{await e.env.context.chat.message(t,r,i)}catch(t){return Pa(e,t instanceof Error?t.message:`Unknown error`)}return e.body(null,204)}),Ba=Ia().post(`/v1/traces`,async e=>e.env.context.otlp?e.env.context.otlp.traces(e.req.raw):e.body(null,204)),Va=new t.Hono().route(`/kv`,La).route(`/chat`,za).route(`/otlp`,Ba);function Ha(e){let n=(0,g.join)(e.dataDirectory,`chats`),r={},a=(0,g.join)(e.dataDirectory,`storage.json`);i.existsSync(a)&&(r=JSON.parse(i.readFileSync(a,`utf-8`)));let o=new Map,c=t=>{let r=o.get(t);return r||(r=new ue({chatId:t,chatsDirectory:n}),r.setAgent(e.getAgent()),o.set(t,r)),r},l={chat:{async ensure(e){let t=c(e).getState(),n=t.messages.length===0&&!t.created_at;return{key:e,created:n}},async message(e,t,n){let r=c(e),i=ce(t);if(n?.behavior===`append`){await r.upsertMessage(i);return}if(n?.behavior===`interrupt`){await r.sendMessage(i);return}await r.sendMessage(i)}},store:{get(e){return Promise.resolve(r[e])},set(e,t){return r[e]=t,i.writeFileSync(a,JSON.stringify(r),`utf-8`),Promise.resolve()},delete(e){return delete r[e],i.writeFileSync(a,JSON.stringify(r),`utf-8`),Promise.resolve()},list(e,t){let n=Math.min(t?.limit??100,1e3),i=t?.cursor,a=Object.keys(r).filter(t=>t.startsWith(e??``)).sort(),o=0;if(i){let e=a.indexOf(i);e!==-1&&(o=e+1)}let s=a.slice(o,o+n),c=o+n<a.length?s[s.length-1]:void 0;return Promise.resolve({entries:s.map(e=>({key:e})),cursor:c})}}},u=(0,s.createServer)(t.createServerAdapter(e=>Va.fetch(e,{context:l})));u.listen(e.port??0);let d=ae(n,`id`);return{url:`http://127.0.0.1:${u.address().port}`,runtime:l,chatsDirectory:n,getChatManager:c,listChats:()=>d.list(),lockChat:e=>d.lock(e),startChat:async e=>{await c(e).start()},stopChat:e=>{o.get(e)?.stopStreaming()},dispose:()=>{for(let e of o.values())e.dispose();o.clear(),d.dispose(),u.close()}}}function Ua({agent:e,capabilities:n,messages:r}){let[i,a]=(0,h.useState)(void 0),[o,s]=(0,h.useState)(!0),[c,l]=(0,h.useState)(void 0),u=(0,h.useRef)(c);(0,h.useEffect)(()=>{u.current=c},[c]);let[d,f]=(0,h.useState)(()=>t.lastUIOptions(r));(0,h.useEffect)(()=>{f(e=>{let n=t.lastUIOptions(r);return JSON.stringify(n)===JSON.stringify(e)?e:n})},[r]);let[p,m]=(0,h.useState)(void 0),g=(0,h.useCallback)((e,t)=>{if(!u.current)return!1;let n=u.current[e];return n?n.values.some(e=>e.id===t):!1},[]),_=(0,h.useCallback)(e=>{m(t=>{let n={...d,...t,...e};for(let[e,t]of Object.entries(n))g(e,t)||delete n[e];for(let[e,t]of Object.entries(u.current??{}))!n[e]&&t.defaultValue!==void 0&&(n[e]=t.defaultValue);return JSON.stringify(n)===JSON.stringify(t)?t:n})},[d,g]);(0,h.useEffect)(()=>{if(!d&&!c){m(void 0);return}_()},[d,c,_]);let v=(0,h.useRef)(void 0),y=(0,h.useRef)(void 0);(0,h.useEffect)(()=>{e!==y.current&&(y.current=e,l(void 0),m(void 0),a(void 0),s(!0),v.current=void 0)},[e]),(0,h.useEffect)(()=>{if(n&&!n.ui||!e){l(void 0),m(void 0),a(void 0),v.current=void 0;return}let t=p?JSON.stringify(p):``;if(v.current===t){s(!1),a(void 0);return}let r=new AbortController;return s(!0),a(void 0),e.ui(p?{selectedOptions:p}:{},{signal:r.signal}).then(e=>{if(!e){l(void 0);return}r.signal.aborted||(l(t=>JSON.stringify(t)===JSON.stringify(e)?t:e),v.current=t)}).catch(e=>{r.signal.aborted||a(e instanceof Error?e:Error(String(e)))}).finally(()=>{s(!1)}),()=>{r.abort()}},[e,n,p]);let b=(0,h.useCallback)((e,t)=>{_({[e]:t})},[_]);return{schema:c,options:p,setOption:b,loading:o,error:i}}function Wa(e){let t=(0,h.useRef)(e.onRequest);(0,h.useEffect)(()=>{t.current=e.onRequest},[e.onRequest]);let n=(0,h.useRef)(e.id??crypto.randomUUID()),[r,i]=(0,h.useState)(`disconnected`);return(0,h.useEffect)(()=>{if(e.disabled){i(`disconnected`);return}let r=!1,a,o,s=!1,c=()=>{if(!(r||s)){if(s=!0,a){try{a.dispose()}catch{}a=void 0}a=new $n({baseURL:`https://blink.so`}).devhook.listen({id:n.current,onRequest:async e=>t.current(e),onConnect:()=>{s=!1,i(`connected`)},onDisconnect:()=>{s=!1,i(`disconnected`),!r&&!o&&(o=setTimeout(()=>{o=void 0,c()},2e3))},onError:e=>{s=!1,i(`error`),!r&&!o&&(o=setTimeout(()=>{o=void 0,c()},2e3))}})}};return c(),()=>{if(r=!0,o&&=(clearTimeout(o),void 0),a){try{a.dispose()}catch{}a=void 0}}},[e.disabled]),{id:n.current,status:r}}var Ga=e.__commonJSMin(((e,t)=>{t.exports={name:`dotenv`,version:`17.2.3`,description:`Loads environment variables from .env file`,main:`lib/main.js`,types:`lib/main.d.ts`,exports:{".":{types:`./lib/main.d.ts`,require:`./lib/main.js`,default:`./lib/main.js`},"./config":`./config.js`,"./config.js":`./config.js`,"./lib/env-options":`./lib/env-options.js`,"./lib/env-options.js":`./lib/env-options.js`,"./lib/cli-options":`./lib/cli-options.js`,"./lib/cli-options.js":`./lib/cli-options.js`,"./package.json":`./package.json`},scripts:{"dts-check":`tsc --project tests/types/tsconfig.json`,lint:`standard`,pretest:`npm run lint && npm run dts-check`,test:`tap run tests/**/*.js --allow-empty-coverage --disable-coverage --timeout=60000`,"test:coverage":`tap run tests/**/*.js --show-full-coverage --timeout=60000 --coverage-report=text --coverage-report=lcov`,prerelease:`npm test`,release:`standard-version`},repository:{type:`git`,url:`git://github.com/motdotla/dotenv.git`},homepage:`https://github.com/motdotla/dotenv#readme`,funding:`https://dotenvx.com`,keywords:[`dotenv`,`env`,`.env`,`environment`,`variables`,`config`,`settings`],readmeFilename:`README.md`,license:`BSD-2-Clause`,devDependencies:{"@types/node":`^18.11.3`,decache:`^4.6.2`,sinon:`^14.0.1`,standard:`^17.0.0`,"standard-version":`^9.5.0`,tap:`^19.2.0`,typescript:`^4.8.4`},engines:{node:`>=12`},browser:{fs:!1}}})),Ka=e.__commonJSMin(((e,t)=>{let n=require(`fs`),r=require(`path`),i=require(`os`),a=require(`crypto`),o=Ga().version,s=[`🔐 encrypt with Dotenvx: https://dotenvx.com`,`🔐 prevent committing .env to code: https://dotenvx.com/precommit`,`🔐 prevent building .env in docker: https://dotenvx.com/prebuild`,`📡 add observability to secrets: https://dotenvx.com/ops`,`👥 sync secrets across teammates & machines: https://dotenvx.com/ops`,`🗂️ backup and recover secrets: https://dotenvx.com/ops`,`✅ audit secrets and track compliance: https://dotenvx.com/ops`,`🔄 add secrets lifecycle management: https://dotenvx.com/ops`,`🔑 add access controls to secrets: https://dotenvx.com/ops`,"🛠️ run anywhere with `dotenvx run -- yourcommand`",`⚙️ specify custom .env file path with { path: '/custom/path/.env' }`,`⚙️ enable debug logging with { debug: true }`,`⚙️ override existing env vars with { override: true }`,`⚙️ suppress all logs with { quiet: true }`,`⚙️ write to custom object with { processEnv: myObject }`,`⚙️ load multiple .env files with { path: ['.env.local', '.env'] }`];function c(){return s[Math.floor(Math.random()*s.length)]}function l(e){return typeof e==`string`?![`false`,`0`,`no`,`off`,``].includes(e.toLowerCase()):!!e}function u(){return process.stdout.isTTY}function d(e){return u()?`\x1b[2m${e}\x1b[0m`:e}let f=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/gm;function p(e){let t={},n=e.toString();n=n.replace(/\r\n?/gm,`
129
129
  `);let r;for(;(r=f.exec(n))!=null;){let e=r[1],n=r[2]||``;n=n.trim();let i=n[0];n=n.replace(/^(['"`])([\s\S]*)\1$/gm,`$2`),i===`"`&&(n=n.replace(/\\n/g,`
130
130
  `),n=n.replace(/\\r/g,`\r`)),t[e]=n}return t}function m(e){e||={};let t=b(e);e.path=t;let n=D.configDotenv(e);if(!n.parsed){let e=Error(`MISSING_DATA: Cannot parse ${t} for an unknown reason`);throw e.code=`MISSING_DATA`,e}let r=v(e).split(`,`),i=r.length,a;for(let e=0;e<i;e++)try{let t=r[e].trim(),i=y(n,t);a=D.decrypt(i.ciphertext,i.key);break}catch(t){if(e+1>=i)throw t}return D.parse(a)}function h(e){console.error(`[dotenv@${o}][WARN] ${e}`)}function g(e){console.log(`[dotenv@${o}][DEBUG] ${e}`)}function _(e){console.log(`[dotenv@${o}] ${e}`)}function v(e){return e&&e.DOTENV_KEY&&e.DOTENV_KEY.length>0?e.DOTENV_KEY:process.env.DOTENV_KEY&&process.env.DOTENV_KEY.length>0?process.env.DOTENV_KEY:``}function y(e,t){let n;try{n=new URL(t)}catch(e){if(e.code===`ERR_INVALID_URL`){let e=Error(`INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development`);throw e.code=`INVALID_DOTENV_KEY`,e}throw e}let r=n.password;if(!r){let e=Error(`INVALID_DOTENV_KEY: Missing key part`);throw e.code=`INVALID_DOTENV_KEY`,e}let i=n.searchParams.get(`environment`);if(!i){let e=Error(`INVALID_DOTENV_KEY: Missing environment part`);throw e.code=`INVALID_DOTENV_KEY`,e}let a=`DOTENV_VAULT_${i.toUpperCase()}`,o=e.parsed[a];if(!o){let e=Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${a} in your .env.vault file.`);throw e.code=`NOT_FOUND_DOTENV_ENVIRONMENT`,e}return{ciphertext:o,key:r}}function b(e){let t=null;if(e&&e.path&&e.path.length>0)if(Array.isArray(e.path))for(let r of e.path)n.existsSync(r)&&(t=r.endsWith(`.vault`)?r:`${r}.vault`);else t=e.path.endsWith(`.vault`)?e.path:`${e.path}.vault`;else t=r.resolve(process.cwd(),`.env.vault`);return n.existsSync(t)?t:null}function x(e){return e[0]===`~`?r.join(i.homedir(),e.slice(1)):e}function S(e){let t=l(process.env.DOTENV_CONFIG_DEBUG||e&&e.debug),n=l(process.env.DOTENV_CONFIG_QUIET||e&&e.quiet);(t||!n)&&_(`Loading env from encrypted .env.vault`);let r=D._parseVault(e),i=process.env;return e&&e.processEnv!=null&&(i=e.processEnv),D.populate(i,r,e),{parsed:r}}function C(e){let t=r.resolve(process.cwd(),`.env`),i=`utf8`,a=process.env;e&&e.processEnv!=null&&(a=e.processEnv);let o=l(a.DOTENV_CONFIG_DEBUG||e&&e.debug),s=l(a.DOTENV_CONFIG_QUIET||e&&e.quiet);e&&e.encoding?i=e.encoding:o&&g(`No encoding is specified. UTF-8 is used by default`);let u=[t];if(e&&e.path)if(!Array.isArray(e.path))u=[x(e.path)];else{u=[];for(let t of e.path)u.push(x(t))}let f,p={};for(let t of u)try{let r=D.parse(n.readFileSync(t,{encoding:i}));D.populate(p,r,e)}catch(e){o&&g(`Failed to load ${t} ${e.message}`),f=e}let m=D.populate(a,p,e);if(o=l(a.DOTENV_CONFIG_DEBUG||o),s=l(a.DOTENV_CONFIG_QUIET||s),o||!s){let e=Object.keys(m).length,t=[];for(let e of u)try{let n=r.relative(process.cwd(),e);t.push(n)}catch(t){o&&g(`Failed to load ${e} ${t.message}`),f=t}_(`injecting env (${e}) from ${t.join(`,`)} ${d(`-- tip: ${c()}`)}`)}return f?{parsed:p,error:f}:{parsed:p}}function w(e){if(v(e).length===0)return D.configDotenv(e);let t=b(e);return t?D._configVault(e):(h(`You set DOTENV_KEY but you are missing a .env.vault file at ${t}. Did you forget to build it?`),D.configDotenv(e))}function T(e,t){let n=Buffer.from(t.slice(-64),`hex`),r=Buffer.from(e,`base64`),i=r.subarray(0,12),o=r.subarray(-16);r=r.subarray(12,-16);try{let e=a.createDecipheriv(`aes-256-gcm`,n,i);return e.setAuthTag(o),`${e.update(r)}${e.final()}`}catch(e){let t=e instanceof RangeError,n=e.message===`Invalid key length`,r=e.message===`Unsupported state or unable to authenticate data`;if(t||n){let e=Error(`INVALID_DOTENV_KEY: It must be 64 characters long (or more)`);throw e.code=`INVALID_DOTENV_KEY`,e}else if(r){let e=Error(`DECRYPTION_FAILED: Please check your DOTENV_KEY`);throw e.code=`DECRYPTION_FAILED`,e}else throw e}}function E(e,t,n={}){let r=!!(n&&n.debug),i=!!(n&&n.override),a={};if(typeof t!=`object`){let e=Error(`OBJECT_REQUIRED: Please check the processEnv argument being passed to populate`);throw e.code=`OBJECT_REQUIRED`,e}for(let n of Object.keys(t))Object.prototype.hasOwnProperty.call(e,n)?(i===!0&&(e[n]=t[n],a[n]=t[n]),r&&g(i===!0?`"${n}" is already defined and WAS overwritten`:`"${n}" is already defined and was NOT overwritten`)):(e[n]=t[n],a[n]=t[n]);return a}let D={configDotenv:C,_configVault:S,_parseVault:m,config:w,decrypt:T,parse:p,populate:E};t.exports.configDotenv=D.configDotenv,t.exports._configVault=D._configVault,t.exports._parseVault=D._parseVault,t.exports.config=D.config,t.exports.decrypt=D.decrypt,t.exports.parse=D.parse,t.exports.populate=D.populate,t.exports=D})),qa=e.__toESM(Ka(),1);async function Ja(e,t){let n=e;for(;n!==(0,c.dirname)(n);){let e=(0,c.join)(n,t);try{return await(0,p.stat)(e),e}catch{}n=(0,c.dirname)(n)}}function Ya(e,t=`.env.local`){let[n,r]=(0,h.useState)({});return(0,h.useEffect)(()=>{let n,i=e=>{try{let t=(0,u.readFileSync)(e,`utf-8`),n=(0,qa.parse)(t);r(n)}catch(e){console.error(`Error reading ${t}:`,e),r({})}};return Ja(e,t).then(e=>{if(!e){r({});return}i(e),n=(0,u.watch)(e,{persistent:!1},()=>{i(e)})}),()=>{n&&n.close()}},[e,t]),n}const Xa=(e,t)=>{let n=typeof e==`string`;typeof e==`string`&&(e=t.encode(e));let r=new Uint8Array(1+e.byteLength);return r[0]=n?0:1,r.set(new Uint8Array(e),1),r},Za=(e,t)=>e[0]===0?t.decode(e.subarray(1)):new Uint8Array(e.subarray(1));let Qa=function(e){return e[e.REQUEST=0]=`REQUEST`,e[e.PROXY_INIT=1]=`PROXY_INIT`,e[e.PROXY_BODY=2]=`PROXY_BODY`,e[e.PROXY_WEBSOCKET_MESSAGE=3]=`PROXY_WEBSOCKET_MESSAGE`,e[e.PROXY_WEBSOCKET_CLOSE=4]=`PROXY_WEBSOCKET_CLOSE`,e}({}),$a=function(e){return e[e.RESPONSE=0]=`RESPONSE`,e[e.NOTIFICATION=1]=`NOTIFICATION`,e[e.PROXY_INIT=2]=`PROXY_INIT`,e[e.PROXY_DATA=3]=`PROXY_DATA`,e[e.PROXY_WEBSOCKET_MESSAGE=4]=`PROXY_WEBSOCKET_MESSAGE`,e[e.PROXY_WEBSOCKET_CLOSE=5]=`PROXY_WEBSOCKET_CLOSE`,e}({});const eo={[Qa.REQUEST]:v.z.string(),[Qa.PROXY_INIT]:v.z.object({method:v.z.string(),headers:v.z.record(v.z.string(),v.z.string()),url:v.z.string()}),[Qa.PROXY_BODY]:v.z.instanceof(Uint8Array),[Qa.PROXY_WEBSOCKET_MESSAGE]:v.z.object({type:v.z.enum([`text`,`binary`]),data:v.z.instanceof(Uint8Array)}),[Qa.PROXY_WEBSOCKET_CLOSE]:v.z.object({code:v.z.number().optional(),reason:v.z.string().optional()})},to={[$a.RESPONSE]:v.z.string(),[$a.NOTIFICATION]:v.z.string(),[$a.PROXY_INIT]:v.z.object({status_code:v.z.number(),status_message:v.z.string(),headers:v.z.record(v.z.string(),v.z.string())}),[$a.PROXY_DATA]:v.z.instanceof(Uint8Array),[$a.PROXY_WEBSOCKET_MESSAGE]:v.z.instanceof(Uint8Array),[$a.PROXY_WEBSOCKET_CLOSE]:v.z.object({code:v.z.number(),reason:v.z.string()})},no={[Qa.PROXY_INIT]:{method:v.z.string(),headers:v.z.record(v.z.string(),v.z.string()),url:v.z.string()}},ro={process_execute:v.z.object({command:v.z.string(),args:v.z.array(v.z.string()),env_file:v.z.string().optional(),env:v.z.record(v.z.string(),v.z.string()).optional(),cwd:v.z.string().optional()}),process_send_input:v.z.object({pid:v.z.number(),data:v.z.string()}),process_wait:v.z.object({pid:v.z.number(),output_idle_timeout_ms:v.z.number().optional(),timeout_ms:v.z.number().optional()}),process_list:v.z.object({include_dead:v.z.boolean().optional()}),process_read_plain_output:v.z.object({pid:v.z.number(),start_line:v.z.number().optional(),end_line:v.z.number().optional()}),process_kill:v.z.object({pid:v.z.number(),signal:v.z.string().optional()}),set_env:v.z.object({env:v.z.record(v.z.string(),v.z.string())}),read_file:v.z.object({path:v.z.string(),line_start:v.z.number().optional(),line_end:v.z.number().optional()}),write_file:v.z.object({path:v.z.string(),content:v.z.string(),base64:v.z.boolean().optional(),mode:v.z.number().optional()}),read_directory:v.z.object({path:v.z.string()}),watch_directory:v.z.object({path:v.z.string()}),deploy_static_files:v.z.object({path:v.z.string()})},io=v.z.object({pid:v.z.number(),command:v.z.string(),args:v.z.array(v.z.string()),title:v.z.string().optional(),cwd:v.z.string(),env:v.z.record(v.z.string(),v.z.string()),exit_code:v.z.number().optional(),exit_signal:v.z.number().optional(),duration_ms:v.z.number().optional(),output_total_lines:v.z.number()}),ao=io.extend({ansi_output:v.z.string(),plain_output:v.z.object({lines:v.z.array(v.z.string()),total_lines:v.z.number()})}),oo={process_execute:v.z.object({pid:v.z.number()}),process_send_input:v.z.object({}),process_wait:ao,process_list:v.z.object({processes:v.z.array(io)}),process_read_plain_output:v.z.object({lines:v.z.array(v.z.string()),total_lines:v.z.number(),duration_ms:v.z.number(),exit_code:v.z.number().optional(),exit_signal:v.z.number().optional()}),process_kill:v.z.object({}),set_env:v.z.object({}),read_file:v.z.object({total_lines:v.z.number(),lines_read:v.z.number(),start_line:v.z.number(),content:v.z.string(),mime_type:v.z.string()}),write_file:v.z.object({}),read_directory:v.z.object({entries:v.z.array(v.z.object({name:v.z.string(),type:v.z.enum([`file`,`directory`,`symlink`])}))}),watch_directory:v.z.object({}),deploy_static_files:v.z.object({deployment_id:v.z.string()})},so=v.z.object({type:v.z.enum([`create`,`update`,`delete`]),path:v.z.string()}),co=v.z.object({type:v.z.enum([`context`,`added`,`deleted`]),content:v.z.string(),oldLineNumber:v.z.number().optional(),newLineNumber:v.z.number().optional()}),lo=v.z.object({oldStart:v.z.number(),oldLines:v.z.number(),newStart:v.z.number(),newLines:v.z.number(),lines:v.z.array(co)}),uo=v.z.object({path:v.z.string(),status:v.z.enum([`added`,`modified`,`deleted`,`renamed`,`copied`,`untracked`,`ignored`,`unmerged`,`typechange`]),oldPath:v.z.string().optional(),insertions:v.z.number(),deletions:v.z.number(),chunks:v.z.array(lo)}),fo=v.z.object({totalFiles:v.z.number(),totalInsertions:v.z.number(),totalDeletions:v.z.number(),netChange:v.z.number(),startHash:v.z.string().optional(),currentHash:v.z.string().optional(),timespan:v.z.number(),files:v.z.array(uo)}),po=v.z.object({path:v.z.string(),status:v.z.enum([`added`,`modified`,`deleted`,`renamed`,`copied`,`untracked`,`ignored`,`unmerged`,`typechange`]),staged:v.z.boolean()}),mo=v.z.object({hash:v.z.string(),shortHash:v.z.string(),message:v.z.string(),author:v.z.string(),email:v.z.string(),date:v.z.date(),timestamp:v.z.date(),filesChanged:v.z.number(),insertions:v.z.number(),deletions:v.z.number(),commitDiff:v.z.array(uo).optional()}),ho=v.z.object({files:v.z.array(po),branch:v.z.string(),ahead:v.z.number(),behind:v.z.number(),timestamp:v.z.date(),sessionDiff:fo.optional(),workingDirectoryDiff:fo.optional(),newCommits:v.z.array(mo),currentCommit:v.z.object({hash:v.z.string(),shortHash:v.z.string(),message:v.z.string(),author:v.z.string(),date:v.z.date()}).optional(),diffSkipped:v.z.boolean().optional(),payloadTruncated:v.z.boolean().optional(),estimatedSizeKB:v.z.number().optional()}),go=v.z.object({debounceDelay:v.z.number().optional(),gitStatusInterval:v.z.number().optional(),ignoreDotfiles:v.z.boolean().optional(),ignored:v.z.array(v.z.string()).optional(),watchGit:v.z.boolean().optional(),includeDiffs:v.z.boolean().optional(),maxDiffFiles:v.z.number().optional(),maxPayloadSizeKB:v.z.number().optional(),truncateLargeDiffs:v.z.boolean().optional()}),_o={process_status:v.z.object({status:io}),process_output:v.z.object({pid:v.z.number(),output:v.z.string()}),file_change:v.z.object({changes:v.z.array(so)}),git_status:ho};var vo=class{notificationCallbacks=new Map;disposables=[];requestHandlers=new Map;send;jwt;requestTimeoutMS;constructor({send:e,jwt:t,requestTimeoutMS:n}){this.send=e,this.jwt=t,this.requestTimeoutMS=n}handleMessage(e){if(typeof e!=`string`)return;let t=JSON.parse(e);if(`id`in t){let e=this.requestHandlers.get(t.id);if(!e)return;e(t.payload,t.error)}else if(`type`in t)this.notificationCallbacks.get(t.type)?.forEach(e=>{e(t.payload)});else return}dispose(e){this.disposables.forEach(t=>t.dispose(e))}async request(e,t,n){let r=crypto.randomUUID(),i,a,o=new Promise((e,t)=>{i=e,a=t}),s={dispose:e=>{l();let t=`Client was disposed!`;e&&(t+=` Reason: ${e}`),a(Error(t))}};this.disposables.push(s);let c;this.requestTimeoutMS&&(c=setTimeout(()=>{a(Error(`Request timed out`))},this.requestTimeoutMS));let l=()=>{this.disposables.splice(this.disposables.indexOf(s),1),this.requestHandlers.delete(r),c&&clearTimeout(c)};n?.signal&&n.signal.addEventListener(`abort`,()=>{l(),a(n.signal?.reason)}),this.requestHandlers.set(r,(e,t)=>{if(l(),t)return a(Error(t));i(e)});let u={id:r,type:e,payload:t,jwt:this.jwt};return this.send(JSON.stringify(u)),o}onNotification(e,t){let n=this.notificationCallbacks.get(e)??[];return n.push(t),this.notificationCallbacks.set(e,n),{dispose:()=>{let n=this.notificationCallbacks.get(e)??[],r=n.indexOf(t);r!==-1&&n.splice(r,1)}}}},yo=e.__commonJSMin(((e,t)=>{let n=[`nodebuffer`,`arraybuffer`,`fragments`],r=typeof Blob<`u`;r&&n.push(`blob`),t.exports={BINARY_TYPES:n,EMPTY_BUFFER:Buffer.alloc(0),GUID:`258EAFA5-E914-47DA-95CA-C5AB0DC85B11`,hasBlob:r,kForOnEventAttribute:Symbol(`kIsForOnEventAttribute`),kListener:Symbol(`kListener`),kStatusCode:Symbol(`status-code`),kWebSocket:Symbol(`websocket`),NOOP:()=>{}}})),bo=e.__commonJSMin(((e,t)=>{let{EMPTY_BUFFER:n}=yo(),r=Buffer[Symbol.species];function i(e,t){if(e.length===0)return n;if(e.length===1)return e[0];let i=Buffer.allocUnsafe(t),a=0;for(let t=0;t<e.length;t++){let n=e[t];i.set(n,a),a+=n.length}return a<t?new r(i.buffer,i.byteOffset,a):i}function a(e,t,n,r,i){for(let a=0;a<i;a++)n[r+a]=e[a]^t[a&3]}function o(e,t){for(let n=0;n<e.length;n++)e[n]^=t[n&3]}function s(e){return e.length===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.length)}function c(e){if(c.readOnly=!0,Buffer.isBuffer(e))return e;let t;return e instanceof ArrayBuffer?t=new r(e):ArrayBuffer.isView(e)?t=new r(e.buffer,e.byteOffset,e.byteLength):(t=Buffer.from(e),c.readOnly=!1),t}if(t.exports={concat:i,mask:a,toArrayBuffer:s,toBuffer:c,unmask:o},!process.env.WS_NO_BUFFER_UTIL)try{let e=require(`bufferutil`);t.exports.mask=function(t,n,r,i,o){o<48?a(t,n,r,i,o):e.mask(t,n,r,i,o)},t.exports.unmask=function(t,n){t.length<32?o(t,n):e.unmask(t,n)}}catch{}})),xo=e.__commonJSMin(((e,t)=>{let n=Symbol(`kDone`),r=Symbol(`kRun`);t.exports=class{constructor(e){this[n]=()=>{this.pending--,this[r]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[r]()}[r](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[n])}}}})),So=e.__commonJSMin(((e,t)=>{let n=require(`zlib`),r=bo(),i=xo(),{kStatusCode:a}=yo(),o=Buffer[Symbol.species],s=Buffer.from([0,0,255,255]),c=Symbol(`permessage-deflate`),l=Symbol(`total-length`),u=Symbol(`callback`),d=Symbol(`buffers`),f=Symbol(`error`),p;t.exports=class{constructor(e,t,n){if(this._maxPayload=n|0,this._options=e||{},this._threshold=this._options.threshold===void 0?1024:this._options.threshold,this._isServer=!!t,this._deflate=null,this._inflate=null,this.params=null,!p){let e=this._options.concurrencyLimit===void 0?10:this._options.concurrencyLimit;p=new i(e)}}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??(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(),null),this._deflate){let e=this._deflate[u];this._deflate.close(),this._deflate=null,e&&e(Error(`The deflate stream was closed while data was being processed`))}}acceptAsServer(e){let t=this._options,n=e.find(e=>!(t.serverNoContextTakeover===!1&&e.server_no_context_takeover||e.server_max_window_bits&&(t.serverMaxWindowBits===!1||typeof t.serverMaxWindowBits==`number`&&t.serverMaxWindowBits>e.server_max_window_bits)||typeof t.clientMaxWindowBits==`number`&&!e.client_max_window_bits));if(!n)throw Error(`None of the extension offers can be accepted`);return t.serverNoContextTakeover&&(n.server_no_context_takeover=!0),t.clientNoContextTakeover&&(n.client_no_context_takeover=!0),typeof t.serverMaxWindowBits==`number`&&(n.server_max_window_bits=t.serverMaxWindowBits),typeof t.clientMaxWindowBits==`number`?n.client_max_window_bits=t.clientMaxWindowBits:(n.client_max_window_bits===!0||t.clientMaxWindowBits===!1)&&delete n.client_max_window_bits,n}acceptAsClient(e){let t=e[0];if(this._options.clientNoContextTakeover===!1&&t.client_no_context_takeover)throw Error(`Unexpected parameter "client_no_context_takeover"`);if(!t.client_max_window_bits)typeof this._options.clientMaxWindowBits==`number`&&(t.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits==`number`&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw Error(`Unexpected or invalid parameter "client_max_window_bits"`);return t}normalizeParams(e){return e.forEach(e=>{Object.keys(e).forEach(t=>{let n=e[t];if(n.length>1)throw Error(`Parameter "${t}" must have only a single value`);if(n=n[0],t===`client_max_window_bits`){if(n!==!0){let e=+n;if(!Number.isInteger(e)||e<8||e>15)throw TypeError(`Invalid value for parameter "${t}": ${n}`);n=e}else if(!this._isServer)throw TypeError(`Invalid value for parameter "${t}": ${n}`)}else if(t===`server_max_window_bits`){let e=+n;if(!Number.isInteger(e)||e<8||e>15)throw TypeError(`Invalid value for parameter "${t}": ${n}`);n=e}else if(t===`client_no_context_takeover`||t===`server_no_context_takeover`){if(n!==!0)throw TypeError(`Invalid value for parameter "${t}": ${n}`)}else throw Error(`Unknown parameter "${t}"`);e[t]=n})}),e}decompress(e,t,n){p.add(r=>{this._decompress(e,t,(e,t)=>{r(),n(e,t)})})}compress(e,t,n){p.add(r=>{this._compress(e,t,(e,t)=>{r(),n(e,t)})})}_decompress(e,t,i){let a=this._isServer?`client`:`server`;if(!this._inflate){let e=`${a}_max_window_bits`,t=typeof this.params[e]==`number`?this.params[e]:n.Z_DEFAULT_WINDOWBITS;this._inflate=n.createInflateRaw({...this._options.zlibInflateOptions,windowBits:t}),this._inflate[c]=this,this._inflate[l]=0,this._inflate[d]=[],this._inflate.on(`error`,g),this._inflate.on(`data`,h)}this._inflate[u]=i,this._inflate.write(e),t&&this._inflate.write(s),this._inflate.flush(()=>{let e=this._inflate[f];if(e){this._inflate.close(),this._inflate=null,i(e);return}let n=r.concat(this._inflate[d],this._inflate[l]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[l]=0,this._inflate[d]=[],t&&this.params[`${a}_no_context_takeover`]&&this._inflate.reset()),i(null,n)})}_compress(e,t,i){let a=this._isServer?`server`:`client`;if(!this._deflate){let e=`${a}_max_window_bits`,t=typeof this.params[e]==`number`?this.params[e]:n.Z_DEFAULT_WINDOWBITS;this._deflate=n.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:t}),this._deflate[l]=0,this._deflate[d]=[],this._deflate.on(`data`,m)}this._deflate[u]=i,this._deflate.write(e),this._deflate.flush(n.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let e=r.concat(this._deflate[d],this._deflate[l]);t&&(e=new o(e.buffer,e.byteOffset,e.length-4)),this._deflate[u]=null,this._deflate[l]=0,this._deflate[d]=[],t&&this.params[`${a}_no_context_takeover`]&&this._deflate.reset(),i(null,e)})}};function m(e){this[d].push(e),this[l]+=e.length}function h(e){if(this[l]+=e.length,this[c]._maxPayload<1||this[l]<=this[c]._maxPayload){this[d].push(e);return}this[f]=RangeError(`Max payload size exceeded`),this[f].code=`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`,this[f][a]=1009,this.removeListener(`data`,h),this.reset()}function g(e){if(this[c]._inflate=null,this[f]){this[u](this[f]);return}e[a]=1007,this[u](e)}})),Co=e.__commonJSMin(((e,t)=>{let{isUtf8:n}=require(`buffer`),{hasBlob:r}=yo(),i=[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 a(e){return e>=1e3&&e<=1014&&e!==1004&&e!==1005&&e!==1006||e>=3e3&&e<=4999}function o(e){let t=e.length,n=0;for(;n<t;)if(!(e[n]&128))n++;else if((e[n]&224)==192){if(n+1===t||(e[n+1]&192)!=128||(e[n]&254)==192)return!1;n+=2}else if((e[n]&240)==224){if(n+2>=t||(e[n+1]&192)!=128||(e[n+2]&192)!=128||e[n]===224&&(e[n+1]&224)==128||e[n]===237&&(e[n+1]&224)==160)return!1;n+=3}else if((e[n]&248)==240){if(n+3>=t||(e[n+1]&192)!=128||(e[n+2]&192)!=128||(e[n+3]&192)!=128||e[n]===240&&(e[n+1]&240)==128||e[n]===244&&e[n+1]>143||e[n]>244)return!1;n+=4}else return!1;return!0}function s(e){return r&&typeof e==`object`&&typeof e.arrayBuffer==`function`&&typeof e.type==`string`&&typeof e.stream==`function`&&(e[Symbol.toStringTag]===`Blob`||e[Symbol.toStringTag]===`File`)}if(t.exports={isBlob:s,isValidStatusCode:a,isValidUTF8:o,tokenChars:i},n)t.exports.isValidUTF8=function(e){return e.length<24?o(e):n(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let e=require(`utf-8-validate`);t.exports.isValidUTF8=function(t){return t.length<32?o(t):e(t)}}catch{}})),wo=e.__commonJSMin(((e,t)=>{let{Writable:n}=require(`stream`),r=So(),{BINARY_TYPES:i,EMPTY_BUFFER:a,kStatusCode:o,kWebSocket:s}=yo(),{concat:c,toArrayBuffer:l,unmask:u}=bo(),{isValidStatusCode:d,isValidUTF8:f}=Co(),p=Buffer[Symbol.species];t.exports=class extends n{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents===void 0?!0:e.allowSynchronousEvents,this._binaryType=e.binaryType||i[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[s]=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=0}_write(e,t,n){if(this._opcode===8&&this._state==0)return n();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(n)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let t=this._buffers[0];return this._buffers[0]=new p(t.buffer,t.byteOffset+e,t.length-e),new p(t.buffer,t.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let n=this._buffers[0],r=t.length-e;e>=n.length?t.set(this._buffers.shift(),r):(t.set(new Uint8Array(n.buffer,n.byteOffset,e),r),this._buffers[0]=new p(n.buffer,n.byteOffset+e,n.length-e)),e-=n.length}while(e>0);return t}startLoop(e){this._loop=!0;do switch(this._state){case 0:this.getInfo(e);break;case 1:this.getPayloadLength16(e);break;case 2:this.getPayloadLength64(e);break;case 3:this.getMask();break;case 4:this.getData(e);break;case 5:case 6:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let t=this.consume(2);if(t[0]&48){let t=this.createError(RangeError,`RSV2 and RSV3 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_2_3`);e(t);return}let n=(t[0]&64)==64;if(n&&!this._extensions[r.extensionName]){let t=this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`);e(t);return}if(this._fin=(t[0]&128)==128,this._opcode=t[0]&15,this._payloadLength=t[1]&127,this._opcode===0){if(n){let t=this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`);e(t);return}if(!this._fragmented){let t=this.createError(RangeError,`invalid opcode 0`,!0,1002,`WS_ERR_INVALID_OPCODE`);e(t);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let t=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,`WS_ERR_INVALID_OPCODE`);e(t);return}this._compressed=n}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let t=this.createError(RangeError,`FIN must be set`,!0,1002,`WS_ERR_EXPECTED_FIN`);e(t);return}if(n){let t=this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`);e(t);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let t=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,`WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH`);e(t);return}}else{let t=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,`WS_ERR_INVALID_OPCODE`);e(t);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(t[1]&128)==128,this._isServer){if(!this._masked){let t=this.createError(RangeError,`MASK must be set`,!0,1002,`WS_ERR_EXPECTED_MASK`);e(t);return}}else if(this._masked){let t=this.createError(RangeError,`MASK must be clear`,!0,1002,`WS_ERR_UNEXPECTED_MASK`);e(t);return}this._payloadLength===126?this._state=1:this._payloadLength===127?this._state=2: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 t=this.consume(8),n=t.readUInt32BE(0);if(n>2**21-1){let t=this.createError(RangeError,`Unsupported WebSocket frame: payload length > 2^53 - 1`,!1,1009,`WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH`);e(t);return}this._payloadLength=n*2**32+t.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 t=this.createError(RangeError,`Max payload size exceeded`,!1,1009,`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`);e(t);return}this._masked?this._state=3:this._state=4}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=4}getData(e){let t=a;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}t=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&u(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._compressed){this._state=5,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[r.extensionName].decompress(e,this._fin,(e,n)=>{if(e)return t(e);if(n.length){if(this._messageLength+=n.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let e=this.createError(RangeError,`Max payload size exceeded`,!1,1009,`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`);t(e);return}this._fragments.push(n)}this.dataMessage(t),this._state===0&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=0;return}let t=this._messageLength,n=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let r;r=this._binaryType===`nodebuffer`?c(n,t):this._binaryType===`arraybuffer`?l(c(n,t)):this._binaryType===`blob`?new Blob(n):n,this._allowSynchronousEvents?(this.emit(`message`,r,!0),this._state=0):(this._state=6,setImmediate(()=>{this.emit(`message`,r,!0),this._state=0,this.startLoop(e)}))}else{let r=c(n,t);if(!this._skipUTF8Validation&&!f(r)){let t=this.createError(Error,`invalid UTF-8 sequence`,!0,1007,`WS_ERR_INVALID_UTF8`);e(t);return}this._state===5||this._allowSynchronousEvents?(this.emit(`message`,r,!1),this._state=0):(this._state=6,setImmediate(()=>{this.emit(`message`,r,!1),this._state=0,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit(`conclude`,1005,a),this.end();else{let n=e.readUInt16BE(0);if(!d(n)){let e=this.createError(RangeError,`invalid status code ${n}`,!0,1002,`WS_ERR_INVALID_CLOSE_CODE`);t(e);return}let r=new p(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!f(r)){let e=this.createError(Error,`invalid UTF-8 sequence`,!0,1007,`WS_ERR_INVALID_UTF8`);t(e);return}this._loop=!1,this.emit(`conclude`,n,r),this.end()}this._state=0;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?`ping`:`pong`,e),this._state=0):(this._state=6,setImmediate(()=>{this.emit(this._opcode===9?`ping`:`pong`,e),this._state=0,this.startLoop(t)}))}createError(e,t,n,r,i){this._loop=!1,this._errored=!0;let a=new e(n?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(a,this.createError),a.code=i,a[o]=r,a}}})),To=e.__commonJSMin(((e,t)=>{let{Duplex:n}=require(`stream`),{randomFillSync:r}=require(`crypto`),i=So(),{EMPTY_BUFFER:a,kWebSocket:o,NOOP:s}=yo(),{isBlob:c,isValidStatusCode:l}=Co(),{mask:u,toBuffer:d}=bo(),f=Symbol(`kByteLength`),p=Buffer.alloc(4),m=8*1024,h,g=m;t.exports=class e{constructor(e,t,n){this._extensions=t||{},n&&(this._generateMask=n,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=0,this.onerror=s,this[o]=void 0}static frame(e,t){let n,i=!1,a=2,o=!1;t.mask&&(n=t.maskBuffer||p,t.generateMask?t.generateMask(n):(g===m&&(h===void 0&&(h=Buffer.alloc(m)),r(h,0,m),g=0),n[0]=h[g++],n[1]=h[g++],n[2]=h[g++],n[3]=h[g++]),o=(n[0]|n[1]|n[2]|n[3])===0,a=6);let s;typeof e==`string`?(!t.mask||o)&&t[f]!==void 0?s=t[f]:(e=Buffer.from(e),s=e.length):(s=e.length,i=t.mask&&t.readOnly&&!o);let c=s;s>=65536?(a+=8,c=127):s>125&&(a+=2,c=126);let l=Buffer.allocUnsafe(i?s+a:a);return l[0]=t.fin?t.opcode|128:t.opcode,t.rsv1&&(l[0]|=64),l[1]=c,c===126?l.writeUInt16BE(s,2):c===127&&(l[2]=l[3]=0,l.writeUIntBE(s,4,6)),!t.mask||(l[1]|=128,l[a-4]=n[0],l[a-3]=n[1],l[a-2]=n[2],l[a-1]=n[3],o)?[l,e]:i?(u(e,n,l,a,s),[l]):(u(e,n,e,0,s),[l,e])}close(t,n,r,i){let o;if(t===void 0)o=a;else if(typeof t!=`number`||!l(t))throw TypeError(`First argument must be a valid error code number`);else if(n===void 0||!n.length)o=Buffer.allocUnsafe(2),o.writeUInt16BE(t,0);else{let e=Buffer.byteLength(n);if(e>123)throw RangeError(`The message must not be greater than 123 bytes`);o=Buffer.allocUnsafe(2+e),o.writeUInt16BE(t,0),typeof n==`string`?o.write(n,2):o.set(n,2)}let s={[f]:o.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state===0?this.sendFrame(e.frame(o,s),i):this.enqueue([this.dispatch,o,!1,s,i])}ping(t,n,r){let i,a;if(typeof t==`string`?(i=Buffer.byteLength(t),a=!1):c(t)?(i=t.size,a=!1):(t=d(t),i=t.length,a=d.readOnly),i>125)throw RangeError(`The data size must not be greater than 125 bytes`);let o={[f]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:a,rsv1:!1};c(t)?this._state===0?this.getBlobData(t,!1,o,r):this.enqueue([this.getBlobData,t,!1,o,r]):this._state===0?this.sendFrame(e.frame(t,o),r):this.enqueue([this.dispatch,t,!1,o,r])}pong(t,n,r){let i,a;if(typeof t==`string`?(i=Buffer.byteLength(t),a=!1):c(t)?(i=t.size,a=!1):(t=d(t),i=t.length,a=d.readOnly),i>125)throw RangeError(`The data size must not be greater than 125 bytes`);let o={[f]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:a,rsv1:!1};c(t)?this._state===0?this.getBlobData(t,!1,o,r):this.enqueue([this.getBlobData,t,!1,o,r]):this._state===0?this.sendFrame(e.frame(t,o),r):this.enqueue([this.dispatch,t,!1,o,r])}send(e,t,n){let r=this._extensions[i.extensionName],a=t.binary?2:1,o=t.compress,s,l;typeof e==`string`?(s=Buffer.byteLength(e),l=!1):c(e)?(s=e.size,l=!1):(e=d(e),s=e.length,l=d.readOnly),this._firstFragment?(this._firstFragment=!1,o&&r&&r.params[r._isServer?`server_no_context_takeover`:`client_no_context_takeover`]&&(o=s>=r._threshold),this._compress=o):(o=!1,a=0),t.fin&&(this._firstFragment=!0);let u={[f]:s,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:a,readOnly:l,rsv1:o};c(e)?this._state===0?this.getBlobData(e,this._compress,u,n):this.enqueue([this.getBlobData,e,this._compress,u,n]):this._state===0?this.dispatch(e,this._compress,u,n):this.enqueue([this.dispatch,e,this._compress,u,n])}getBlobData(t,n,r,i){this._bufferedBytes+=r[f],this._state=2,t.arrayBuffer().then(t=>{if(this._socket.destroyed){let e=Error(`The socket was closed while the blob was being read`);process.nextTick(_,this,e,i);return}this._bufferedBytes-=r[f];let a=d(t);n?this.dispatch(a,n,r,i):(this._state=0,this.sendFrame(e.frame(a,r),i),this.dequeue())}).catch(e=>{process.nextTick(v,this,e,i)})}dispatch(t,n,r,a){if(!n){this.sendFrame(e.frame(t,r),a);return}let o=this._extensions[i.extensionName];this._bufferedBytes+=r[f],this._state=1,o.compress(t,r.fin,(t,n)=>{if(this._socket.destroyed){_(this,Error(`The socket was closed while data was being compressed`),a);return}this._bufferedBytes-=r[f],this._state=0,r.readOnly=!1,this.sendFrame(e.frame(n,r),a),this.dequeue()})}dequeue(){for(;this._state===0&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][f],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][f],this._queue.push(e)}sendFrame(e,t){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}};function _(e,t,n){typeof n==`function`&&n(t);for(let n=0;n<e._queue.length;n++){let r=e._queue[n],i=r[r.length-1];typeof i==`function`&&i(t)}}function v(e,t,n){_(e,t,n),e.onerror(t)}})),Eo=e.__commonJSMin(((e,t)=>{let{kForOnEventAttribute:n,kListener:r}=yo(),i=Symbol(`kCode`),a=Symbol(`kData`),o=Symbol(`kError`),s=Symbol(`kMessage`),c=Symbol(`kReason`),l=Symbol(`kTarget`),u=Symbol(`kType`),d=Symbol(`kWasClean`);var f=class{constructor(e){this[l]=null,this[u]=e}get target(){return this[l]}get type(){return this[u]}};Object.defineProperty(f.prototype,`target`,{enumerable:!0}),Object.defineProperty(f.prototype,`type`,{enumerable:!0});var p=class extends f{constructor(e,t={}){super(e),this[i]=t.code===void 0?0:t.code,this[c]=t.reason===void 0?``:t.reason,this[d]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[i]}get reason(){return this[c]}get wasClean(){return this[d]}};Object.defineProperty(p.prototype,`code`,{enumerable:!0}),Object.defineProperty(p.prototype,`reason`,{enumerable:!0}),Object.defineProperty(p.prototype,`wasClean`,{enumerable:!0});var m=class extends f{constructor(e,t={}){super(e),this[o]=t.error===void 0?null:t.error,this[s]=t.message===void 0?``:t.message}get error(){return this[o]}get message(){return this[s]}};Object.defineProperty(m.prototype,`error`,{enumerable:!0}),Object.defineProperty(m.prototype,`message`,{enumerable:!0});var h=class extends f{constructor(e,t={}){super(e),this[a]=t.data===void 0?null:t.data}get data(){return this[a]}};Object.defineProperty(h.prototype,`data`,{enumerable:!0}),t.exports={CloseEvent:p,ErrorEvent:m,Event:f,EventTarget:{addEventListener(e,t,i={}){for(let a of this.listeners(e))if(!i[n]&&a[r]===t&&!a[n])return;let a;if(e===`message`)a=function(e,n){let r=new h(`message`,{data:n?e:e.toString()});r[l]=this,g(t,this,r)};else if(e===`close`)a=function(e,n){let r=new p(`close`,{code:e,reason:n.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});r[l]=this,g(t,this,r)};else if(e===`error`)a=function(e){let n=new m(`error`,{error:e,message:e.message});n[l]=this,g(t,this,n)};else if(e===`open`)a=function(){let e=new f(`open`);e[l]=this,g(t,this,e)};else return;a[n]=!!i[n],a[r]=t,i.once?this.once(e,a):this.on(e,a)},removeEventListener(e,t){for(let i of this.listeners(e))if(i[r]===t&&!i[n]){this.removeListener(e,i);break}}},MessageEvent:h};function g(e,t,n){typeof e==`object`&&e.handleEvent?e.handleEvent.call(e,n):e.call(t,n)}})),Do=e.__commonJSMin(((e,t)=>{let{tokenChars:n}=Co();function r(e,t,n){e[t]===void 0?e[t]=[n]:e[t].push(n)}function i(e){let t=Object.create(null),i=Object.create(null),a=!1,o=!1,s=!1,c,l,u=-1,d=-1,f=-1,p=0;for(;p<e.length;p++)if(d=e.charCodeAt(p),c===void 0)if(f===-1&&n[d]===1)u===-1&&(u=p);else if(p!==0&&(d===32||d===9))f===-1&&u!==-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p);let n=e.slice(u,f);d===44?(r(t,n,i),i=Object.create(null)):c=n,u=f=-1}else throw SyntaxError(`Unexpected character at index ${p}`);else if(l===void 0)if(f===-1&&n[d]===1)u===-1&&(u=p);else if(d===32||d===9)f===-1&&u!==-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p),r(i,e.slice(u,f),!0),d===44&&(r(t,c,i),i=Object.create(null),c=void 0),u=f=-1}else if(d===61&&u!==-1&&f===-1)l=e.slice(u,p),u=f=-1;else throw SyntaxError(`Unexpected character at index ${p}`);else if(o){if(n[d]!==1)throw SyntaxError(`Unexpected character at index ${p}`);u===-1?u=p:a||=!0,o=!1}else if(s)if(n[d]===1)u===-1&&(u=p);else if(d===34&&u!==-1)s=!1,f=p;else if(d===92)o=!0;else throw SyntaxError(`Unexpected character at index ${p}`);else if(d===34&&e.charCodeAt(p-1)===61)s=!0;else if(f===-1&&n[d]===1)u===-1&&(u=p);else if(u!==-1&&(d===32||d===9))f===-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p);let n=e.slice(u,f);a&&=(n=n.replace(/\\/g,``),!1),r(i,l,n),d===44&&(r(t,c,i),i=Object.create(null),c=void 0),l=void 0,u=f=-1}else throw SyntaxError(`Unexpected character at index ${p}`);if(u===-1||s||d===32||d===9)throw SyntaxError(`Unexpected end of input`);f===-1&&(f=p);let m=e.slice(u,f);return c===void 0?r(t,m,i):(l===void 0?r(i,m,!0):a?r(i,l,m.replace(/\\/g,``)):r(i,l,m),r(t,c,i)),t}function a(e){return Object.keys(e).map(t=>{let n=e[t];return Array.isArray(n)||(n=[n]),n.map(e=>[t].concat(Object.keys(e).map(t=>{let n=e[t];return Array.isArray(n)||(n=[n]),n.map(e=>e===!0?t:`${t}=${e}`).join(`; `)})).join(`; `)).join(`, `)}).join(`, `)}t.exports={format:a,parse:i}})),Oo=e.__commonJSMin(((e,t)=>{let n=require(`events`),r=require(`https`),i=require(`http`),a=require(`net`),o=require(`tls`),{randomBytes:s,createHash:c}=require(`crypto`),{Duplex:l,Readable:u}=require(`stream`),{URL:d}=require(`url`),f=So(),p=wo(),m=To(),{isBlob:h}=Co(),{BINARY_TYPES:g,EMPTY_BUFFER:_,GUID:v,kForOnEventAttribute:y,kListener:b,kStatusCode:x,kWebSocket:S,NOOP:C}=yo(),{EventTarget:{addEventListener:w,removeEventListener:T}}=Eo(),{format:E,parse:D}=Do(),{toBuffer:O}=bo(),k=Symbol(`kAborted`),A=[8,13],j=[`CONNECTING`,`OPEN`,`CLOSING`,`CLOSED`],M=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;var N=class e extends n{constructor(t,n,r){super(),this._binaryType=g[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=_,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol=``,this._readyState=e.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,t===null?(this._autoPong=r.autoPong,this._isServer=!0):(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,n===void 0?n=[]:Array.isArray(n)||(typeof n==`object`&&n?(r=n,n=[]):n=[n]),P(this,t,n,r))}get binaryType(){return this._binaryType}set binaryType(e){g.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(t,n,r){let i=new p({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),a=new m(t,this._extensions,r.generateMask);this._receiver=i,this._sender=a,this._socket=t,i[S]=this,a[S]=this,t[S]=this,i.on(`conclude`,te),i.on(`drain`,z),i.on(`error`,B),i.on(`message`,ne),i.on(`ping`,re),i.on(`pong`,H),a.onerror=ae,t.setTimeout&&t.setTimeout(0),t.setNoDelay&&t.setNoDelay(),n.length>0&&t.unshift(n),t.on(`close`,oe),t.on(`data`,se),t.on(`end`,ce),t.on(`error`,le),this._readyState=e.OPEN,this.emit(`open`)}emitClose(){if(!this._socket){this._readyState=e.CLOSED,this.emit(`close`,this._closeCode,this._closeMessage);return}this._extensions[f.extensionName]&&this._extensions[f.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=e.CLOSED,this.emit(`close`,this._closeCode,this._closeMessage)}close(t,n){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){L(this,this._req,`WebSocket was closed before the connection was established`);return}if(this.readyState===e.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=e.CLOSING,this._sender.close(t,n,!this._isServer,e=>{e||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),U(this)}}pause(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!0,this._socket.pause())}ping(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof t==`function`?(r=t,t=n=void 0):typeof n==`function`&&(r=n,n=void 0),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){R(this,t,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(t||_,n,r)}pong(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof t==`function`?(r=t,t=n=void 0):typeof n==`function`&&(r=n,n=void 0),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){R(this,t,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(t||_,n,r)}resume(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof n==`function`&&(r=n,n={}),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){R(this,t,r);return}let i={binary:typeof t!=`string`,mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[f.extensionName]||(i.compress=!1),this._sender.send(t||_,i,r)}terminate(){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){L(this,this._req,`WebSocket was closed before the connection was established`);return}this._socket&&(this._readyState=e.CLOSING,this._socket.destroy())}}};Object.defineProperty(N,`CONNECTING`,{enumerable:!0,value:j.indexOf(`CONNECTING`)}),Object.defineProperty(N.prototype,`CONNECTING`,{enumerable:!0,value:j.indexOf(`CONNECTING`)}),Object.defineProperty(N,`OPEN`,{enumerable:!0,value:j.indexOf(`OPEN`)}),Object.defineProperty(N.prototype,`OPEN`,{enumerable:!0,value:j.indexOf(`OPEN`)}),Object.defineProperty(N,`CLOSING`,{enumerable:!0,value:j.indexOf(`CLOSING`)}),Object.defineProperty(N.prototype,`CLOSING`,{enumerable:!0,value:j.indexOf(`CLOSING`)}),Object.defineProperty(N,`CLOSED`,{enumerable:!0,value:j.indexOf(`CLOSED`)}),Object.defineProperty(N.prototype,`CLOSED`,{enumerable:!0,value:j.indexOf(`CLOSED`)}),[`binaryType`,`bufferedAmount`,`extensions`,`isPaused`,`protocol`,`readyState`,`url`].forEach(e=>{Object.defineProperty(N.prototype,e,{enumerable:!0})}),[`open`,`error`,`close`,`message`].forEach(e=>{Object.defineProperty(N.prototype,`on${e}`,{enumerable:!0,get(){for(let t of this.listeners(e))if(t[y])return t[b];return null},set(t){for(let t of this.listeners(e))if(t[y]){this.removeListener(e,t);break}typeof t==`function`&&this.addEventListener(e,t,{[y]:!0})}})}),N.prototype.addEventListener=w,N.prototype.removeEventListener=T,t.exports=N;function P(e,t,n,a){let o={allowSynchronousEvents:!0,autoPong:!0,protocolVersion:A[1],maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...a,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:`GET`,host:void 0,path:void 0,port:void 0};if(e._autoPong=o.autoPong,!A.includes(o.protocolVersion))throw RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${A.join(`, `)})`);let l;if(t instanceof d)l=t;else try{l=new d(t)}catch{throw SyntaxError(`Invalid URL: ${t}`)}l.protocol===`http:`?l.protocol=`ws:`:l.protocol===`https:`&&(l.protocol=`wss:`),e._url=l.href;let u=l.protocol===`wss:`,p=l.protocol===`ws+unix:`,m;if(l.protocol!==`ws:`&&!u&&!p?m=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:p&&!l.pathname?m=`The URL's pathname is empty`:l.hash&&(m=`The URL contains a fragment identifier`),m){let t=SyntaxError(m);if(e._redirects===0)throw t;F(e,t);return}let h=u?443:80,g=s(16).toString(`base64`),_=u?r.request:i.request,y=new Set,b;if(o.createConnection=o.createConnection||(u?ee:I),o.defaultPort=o.defaultPort||h,o.port=l.port||h,o.host=l.hostname.startsWith(`[`)?l.hostname.slice(1,-1):l.hostname,o.headers={...o.headers,"Sec-WebSocket-Version":o.protocolVersion,"Sec-WebSocket-Key":g,Connection:`Upgrade`,Upgrade:`websocket`},o.path=l.pathname+l.search,o.timeout=o.handshakeTimeout,o.perMessageDeflate&&(b=new f(o.perMessageDeflate===!0?{}:o.perMessageDeflate,!1,o.maxPayload),o.headers[`Sec-WebSocket-Extensions`]=E({[f.extensionName]:b.offer()})),n.length){for(let e of n){if(typeof e!=`string`||!M.test(e)||y.has(e))throw SyntaxError(`An invalid or duplicated subprotocol was specified`);y.add(e)}o.headers[`Sec-WebSocket-Protocol`]=n.join(`,`)}if(o.origin&&(o.protocolVersion<13?o.headers[`Sec-WebSocket-Origin`]=o.origin:o.headers.Origin=o.origin),(l.username||l.password)&&(o.auth=`${l.username}:${l.password}`),p){let e=o.path.split(`:`);o.socketPath=e[0],o.path=e[1]}let x;if(o.followRedirects){if(e._redirects===0){e._originalIpc=p,e._originalSecure=u,e._originalHostOrSocketPath=p?o.socketPath:l.host;let t=a&&a.headers;if(a={...a,headers:{}},t)for(let[e,n]of Object.entries(t))a.headers[e.toLowerCase()]=n}else if(e.listenerCount(`redirect`)===0){let t=p?e._originalIpc?o.socketPath===e._originalHostOrSocketPath:!1:e._originalIpc?!1:l.host===e._originalHostOrSocketPath;(!t||e._originalSecure&&!u)&&(delete o.headers.authorization,delete o.headers.cookie,t||delete o.headers.host,o.auth=void 0)}o.auth&&!a.headers.authorization&&(a.headers.authorization=`Basic `+Buffer.from(o.auth).toString(`base64`)),x=e._req=_(o),e._redirects&&e.emit(`redirect`,e.url,x)}else x=e._req=_(o);o.timeout&&x.on(`timeout`,()=>{L(e,x,`Opening handshake has timed out`)}),x.on(`error`,t=>{x===null||x[k]||(x=e._req=null,F(e,t))}),x.on(`response`,r=>{let i=r.headers.location,s=r.statusCode;if(i&&o.followRedirects&&s>=300&&s<400){if(++e._redirects>o.maxRedirects){L(e,x,`Maximum redirects exceeded`);return}x.abort();let r;try{r=new d(i,t)}catch{let t=SyntaxError(`Invalid URL: ${i}`);F(e,t);return}P(e,r,n,a)}else e.emit(`unexpected-response`,x,r)||L(e,x,`Unexpected server response: ${r.statusCode}`)}),x.on(`upgrade`,(t,n,r)=>{if(e.emit(`upgrade`,t),e.readyState!==N.CONNECTING)return;x=e._req=null;let i=t.headers.upgrade;if(i===void 0||i.toLowerCase()!==`websocket`){L(e,n,`Invalid Upgrade header`);return}let a=c(`sha1`).update(g+v).digest(`base64`);if(t.headers[`sec-websocket-accept`]!==a){L(e,n,`Invalid Sec-WebSocket-Accept header`);return}let s=t.headers[`sec-websocket-protocol`],l;if(s===void 0?y.size&&(l=`Server sent no subprotocol`):y.size?y.has(s)||(l=`Server sent an invalid subprotocol`):l=`Server sent a subprotocol but none was requested`,l){L(e,n,l);return}s&&(e._protocol=s);let u=t.headers[`sec-websocket-extensions`];if(u!==void 0){if(!b){L(e,n,`Server sent a Sec-WebSocket-Extensions header but no extension was requested`);return}let t;try{t=D(u)}catch{L(e,n,`Invalid Sec-WebSocket-Extensions header`);return}let r=Object.keys(t);if(r.length!==1||r[0]!==f.extensionName){L(e,n,`Server indicated an extension that was not requested`);return}try{b.accept(t[f.extensionName])}catch{L(e,n,`Invalid Sec-WebSocket-Extensions header`);return}e._extensions[f.extensionName]=b}e.setSocket(n,r,{allowSynchronousEvents:o.allowSynchronousEvents,generateMask:o.generateMask,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation})}),o.finishRequest?o.finishRequest(x,e):x.end()}function F(e,t){e._readyState=N.CLOSING,e._errorEmitted=!0,e.emit(`error`,t),e.emitClose()}function I(e){return e.path=e.socketPath,a.connect(e)}function ee(e){return e.path=void 0,!e.servername&&e.servername!==``&&(e.servername=a.isIP(e.host)?``:e.host),o.connect(e)}function L(e,t,n){e._readyState=N.CLOSING;let r=Error(n);Error.captureStackTrace(r,L),t.setHeader?(t[k]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(F,e,r)):(t.destroy(r),t.once(`error`,e.emit.bind(e,`error`)),t.once(`close`,e.emitClose.bind(e)))}function R(e,t,n){if(t){let n=h(t)?t.size:O(t).length;e._socket?e._sender._bufferedBytes+=n:e._bufferedAmount+=n}if(n){let t=Error(`WebSocket is not open: readyState ${e.readyState} (${j[e.readyState]})`);process.nextTick(n,t)}}function te(e,t){let n=this[S];n._closeFrameReceived=!0,n._closeMessage=t,n._closeCode=e,n._socket[S]!==void 0&&(n._socket.removeListener(`data`,se),process.nextTick(ie,n._socket),e===1005?n.close():n.close(e,t))}function z(){let e=this[S];e.isPaused||e._socket.resume()}function B(e){let t=this[S];t._socket[S]!==void 0&&(t._socket.removeListener(`data`,se),process.nextTick(ie,t._socket),t.close(e[x])),t._errorEmitted||(t._errorEmitted=!0,t.emit(`error`,e))}function V(){this[S].emitClose()}function ne(e,t){this[S].emit(`message`,e,t)}function re(e){let t=this[S];t._autoPong&&t.pong(e,!this._isServer,C),t.emit(`ping`,e)}function H(e){this[S].emit(`pong`,e)}function ie(e){e.resume()}function ae(e){let t=this[S];t.readyState!==N.CLOSED&&(t.readyState===N.OPEN&&(t._readyState=N.CLOSING,U(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit(`error`,e)))}function U(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),3e4)}function oe(){let e=this[S];this.removeListener(`close`,oe),this.removeListener(`data`,se),this.removeListener(`end`,ce),e._readyState=N.CLOSING;let t;!this._readableState.endEmitted&&!e._closeFrameReceived&&!e._receiver._writableState.errorEmitted&&(t=e._socket.read())!==null&&e._receiver.write(t),e._receiver.end(),this[S]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on(`error`,V),e._receiver.on(`finish`,V))}function se(e){this[S]._receiver.write(e)||this.pause()}function ce(){let e=this[S];e._readyState=N.CLOSING,e._receiver.end(),this.end()}function le(){let e=this[S];this.removeListener(`error`,le),this.on(`error`,C),e&&(e._readyState=N.CLOSING,this.destroy())}})),ko=e.__commonJSMin(((e,t)=>{Oo();let{Duplex:n}=require(`stream`);function r(e){e.emit(`close`)}function i(){!this.destroyed&&this._writableState.finished&&this.destroy()}function a(e){this.removeListener(`error`,a),this.destroy(),this.listenerCount(`error`)===0&&this.emit(`error`,e)}function o(e,t){let o=!0,s=new n({...t,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return e.on(`message`,function(t,n){let r=!n&&s._readableState.objectMode?t.toString():t;s.push(r)||e.pause()}),e.once(`error`,function(e){s.destroyed||(o=!1,s.destroy(e))}),e.once(`close`,function(){s.destroyed||s.push(null)}),s._destroy=function(t,n){if(e.readyState===e.CLOSED){n(t),process.nextTick(r,s);return}let i=!1;e.once(`error`,function(e){i=!0,n(e)}),e.once(`close`,function(){i||n(t),process.nextTick(r,s)}),o&&e.terminate()},s._final=function(t){if(e.readyState===e.CONNECTING){e.once(`open`,function(){s._final(t)});return}e._socket!==null&&(e._socket._writableState.finished?(t(),s._readableState.endEmitted&&s.destroy()):(e._socket.once(`finish`,function(){t()}),e.close()))},s._read=function(){e.isPaused&&e.resume()},s._write=function(t,n,r){if(e.readyState===e.CONNECTING){e.once(`open`,function(){s._write(t,n,r)});return}e.send(t,r)},s.on(`end`,i),s.on(`error`,a),s}t.exports=o})),Ao=e.__commonJSMin(((e,t)=>{let{tokenChars:n}=Co();function r(e){let t=new Set,r=-1,i=-1,a=0;for(;a<e.length;a++){let o=e.charCodeAt(a);if(i===-1&&n[o]===1)r===-1&&(r=a);else if(a!==0&&(o===32||o===9))i===-1&&r!==-1&&(i=a);else if(o===44){if(r===-1)throw SyntaxError(`Unexpected character at index ${a}`);i===-1&&(i=a);let n=e.slice(r,i);if(t.has(n))throw SyntaxError(`The "${n}" subprotocol is duplicated`);t.add(n),r=i=-1}else throw SyntaxError(`Unexpected character at index ${a}`)}if(r===-1||i!==-1)throw SyntaxError(`Unexpected end of input`);let o=e.slice(r,a);if(t.has(o))throw SyntaxError(`The "${o}" subprotocol is duplicated`);return t.add(o),t}t.exports={parse:r}})),jo=e.__commonJSMin(((e,t)=>{let n=require(`events`),r=require(`http`),{Duplex:i}=require(`stream`),{createHash:a}=require(`crypto`),o=Do(),s=So(),c=Ao(),l=Oo(),{GUID:u,kWebSocket:d}=yo(),f=/^[+/0-9A-Za-z]{22}==$/;t.exports=class extends n{constructor(e,t){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:l,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw TypeError(`One and only one of the "port", "server", or "noServer" options must be specified`);if(e.port==null?e.server&&(this._server=e.server):(this._server=r.createServer((e,t)=>{let n=r.STATUS_CODES[426];t.writeHead(426,{"Content-Length":n.length,"Content-Type":`text/plain`}),t.end(n)}),this._server.listen(e.port,e.host,e.backlog,t)),this._server){let e=this.emit.bind(this,`connection`);this._removeListeners=p(this._server,{listening:this.emit.bind(this,`listening`),error:this.emit.bind(this,`error`),upgrade:(t,n,r)=>{this.handleUpgrade(t,n,r,e)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=0}address(){if(this.options.noServer)throw Error(`The server is operating in "noServer" mode`);return this._server?this._server.address():null}close(e){if(this._state===2){e&&this.once(`close`,()=>{e(Error(`The server is not running`))}),process.nextTick(m,this);return}if(e&&this.once(`close`,e),this._state!==1)if(this._state=1,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(m,this);else{let e=this._server;this._removeListeners(),this._removeListeners=this._server=null,e.close(()=>{m(this)})}}shouldHandle(e){if(this.options.path){let t=e.url.indexOf(`?`);if((t===-1?e.url:e.url.slice(0,t))!==this.options.path)return!1}return!0}handleUpgrade(e,t,n,r){t.on(`error`,h);let i=e.headers[`sec-websocket-key`],a=e.headers.upgrade,l=+e.headers[`sec-websocket-version`];if(e.method!==`GET`){_(this,e,t,405,`Invalid HTTP method`);return}if(a===void 0||a.toLowerCase()!==`websocket`){_(this,e,t,400,`Invalid Upgrade header`);return}if(i===void 0||!f.test(i)){_(this,e,t,400,`Missing or invalid Sec-WebSocket-Key header`);return}if(l!==13&&l!==8){_(this,e,t,400,`Missing or invalid Sec-WebSocket-Version header`,{"Sec-WebSocket-Version":`13, 8`});return}if(!this.shouldHandle(e)){g(t,400);return}let u=e.headers[`sec-websocket-protocol`],d=new Set;if(u!==void 0)try{d=c.parse(u)}catch{_(this,e,t,400,`Invalid Sec-WebSocket-Protocol header`);return}let p=e.headers[`sec-websocket-extensions`],m={};if(this.options.perMessageDeflate&&p!==void 0){let n=new s(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let e=o.parse(p);e[s.extensionName]&&(n.accept(e[s.extensionName]),m[s.extensionName]=n)}catch{_(this,e,t,400,`Invalid or unacceptable Sec-WebSocket-Extensions header`);return}}if(this.options.verifyClient){let a={origin:e.headers[`${l===8?`sec-websocket-origin`:`origin`}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(a,(a,o,s,c)=>{if(!a)return g(t,o||401,s,c);this.completeUpgrade(m,i,d,e,t,n,r)});return}if(!this.options.verifyClient(a))return g(t,401)}this.completeUpgrade(m,i,d,e,t,n,r)}completeUpgrade(e,t,n,r,i,c,l){if(!i.readable||!i.writable)return i.destroy();if(i[d])throw Error(`server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration`);if(this._state>0)return g(i,503);let f=[`HTTP/1.1 101 Switching Protocols`,`Upgrade: websocket`,`Connection: Upgrade`,`Sec-WebSocket-Accept: ${a(`sha1`).update(t+u).digest(`base64`)}`],p=new this.options.WebSocket(null,void 0,this.options);if(n.size){let e=this.options.handleProtocols?this.options.handleProtocols(n,r):n.values().next().value;e&&(f.push(`Sec-WebSocket-Protocol: ${e}`),p._protocol=e)}if(e[s.extensionName]){let t=e[s.extensionName].params,n=o.format({[s.extensionName]:[t]});f.push(`Sec-WebSocket-Extensions: ${n}`),p._extensions=e}this.emit(`headers`,f,r),i.write(f.concat(`\r
131
131
  `).join(`\r
@@ -628,4 +628,4 @@ Instead:
628
628
 
629
629
  The agent process can restart at any time, so all important state must be externalized.
630
630
  </technical_knowledge>
631
- `;function hf(e){let[n,r]=(0,h.useState)(void 0),[i,a]=(0,h.useState)(void 0),o=(0,h.useRef)(void 0);return(0,h.useEffect)(()=>{let n=new AbortController;return(async()=>{o.current=pf({directory:e.directory});let i=await gf(),a=o.current.agent.serve({port:i,host:`127.0.0.1`,apiUrl:e.apiServerUrl});n.signal.addEventListener(`abort`,()=>{try{a.close()}catch{}});let s=new t.Client({baseUrl:`http://127.0.0.1:${i}`});for(;!n.signal.aborted;){try{await s.health();break}catch{}await new Promise(e=>setTimeout(e,100))}if(n.signal.aborted)throw n.signal.reason;r(s)})().catch(e=>{a(e instanceof Error?e:Error(String(e)))}),()=>n.abort()},[e.directory,e.apiServerUrl]),(0,h.useMemo)(()=>({client:n,error:i,setUserAgentUrl:e=>{o.current?.setUserAgentUrl(e)}}),[n,i])}async function gf(){let e=(0,s.createServer)();return new Promise((t,n)=>{e.listen(0,()=>{let n=e.address().port;t(n)}).on(`error`,e=>{n(e)})}).finally(()=>{e.close()})}function _f(e){let{directory:n}=e,[r,i]=(0,h.useState)(`run`),a=(0,h.useRef)(`run`);(0,h.useEffect)(()=>{a.current=r},[r]);let o=(0,h.useCallback)(t=>{i(t),e.onModeChange?.(t)},[e.onModeChange]),s=(0,h.useCallback)(()=>{o(r===`run`?`edit`:`run`)},[r,o]),{error:l,status:u,result:d,entry:p}=C({directory:n,onBuildStart:e.onBuildStart,onBuildSuccess:e.onBuildSuccess,onBuildError:e.onBuildError}),m=Ya(n),g=(0,h.useMemo)(()=>{let e=ja();return e?{...m,BLINK_TOKEN:e}:m},[m]),_=(0,h.useRef)(void 0);(0,h.useEffect)(()=>{let t=Object.keys(g);if(t.length===_.current||_.current===void 0){_.current=t.length;return}_.current=t.length,e.onEnvLoaded?.(t)},[g,e.onEnvLoaded]);let v=(0,h.useRef)(void 0),y=(0,h.useMemo)(()=>Ha({port:0,dataDirectory:(0,c.join)(n,`data`),getAgent:()=>v.current}),[n]),{agent:b,logs:S,error:w,capabilities:T}=x({buildResult:d,env:g,apiServerUrl:y.url}),{client:E,error:D,setUserAgentUrl:O}=hf({directory:n,apiServerUrl:y.url}),k=(0,h.useRef)(0);(0,h.useEffect)(()=>{if(S.length===k.current)return;let t=k.current;for(let n of S.slice(t))e.onAgentLog?.(n);k.current=S.length},[S,e.onAgentLog]);let[A,j]=(0,h.useState)(`default`);(0,h.useEffect)(()=>{b&&O(b.baseUrl),r===`run`?b?v.current=b:(v.current=void 0,y.stopChat(A)):r===`edit`&&(E?v.current=E:(v.current=void 0,y.stopChat(A)))},[b,E,r,A,y]);let M=de({chatId:A,agent:r===`run`?b:E,chatsDirectory:y.chatsDirectory,filterMessages:r===`run`?e=>!le(e.metadata):void 0}),[N,P]=(0,h.useState)([]);(0,h.useEffect)(()=>{y.listChats().then(e=>{P(e.map(e=>e.key))})},[y]),(0,h.useEffect)(()=>{A&&!N.includes(A)&&P(e=>[...e,A])},[A,N]);let F=(0,h.useMemo)(()=>Na(n),[n]),I=Wa({id:F,disabled:!T?.request,onRequest:async e=>{if(!b)throw Error(`No agent`);let t=new URL(e.url),n=new URL(b.baseUrl);return n.pathname=t.pathname,n.search=t.search,await fetch(n.toString(),e)}});(0,h.useEffect)(()=>{I.status===`connected`&&e.onDevhookConnected?.(`https://${I.id}.dev.blink.host`)},[I.status,I.id]);let{schema:ee,options:L,error:R,setOption:te}=Ua({agent:v.current,capabilities:T,messages:M.messages}),z=(0,h.useMemo)(()=>{let e=[];return w&&r===`run`&&e.push(w.message),D&&r===`edit`&&e.push(`Edit agent error: ${D.message}`),M.error&&e.push(`Chat error: ${M.error}`),R&&e.push(`Options error: ${R.message}`),e},[w,D,M.error,R,r]);(0,h.useEffect)(()=>{for(let t of z)e.onError?.(t)},[z]),(0,h.useEffect)(()=>{M.upsertMessage({id:crypto.randomUUID(),created_at:new Date().toISOString(),role:`assistant`,parts:[{type:`text`,text:r===`run`?`<run_mode />`:`<edit_mode />`}],metadata:{__blink_internal:!0,type:`mode`,mode:r}}).catch(e=>{console.error(`Error inserting mode delimiter:`,e)})},[r,M.upsertMessage]);let[B,V]=(0,h.useState)(),ne=(0,h.useMemo)(()=>{let e=[...M.messages].reverse().find(e=>!(e.role!==`assistant`||e.metadata&&e.metadata.ephemeral));if(!e||B===e.id)return;let n=e.parts.filter(f.isToolOrDynamicToolUIPart);if(n.length!==0&&n.some(e=>t.isToolApprovalOutput(e.output)&&e.output.outcome===`pending`))return e},[M.messages,B]),re=(0,h.useCallback)(async e=>{if(!ne)return;V(ne.id);let n=await y.lockChat(A);try{let r=await n.get();if(r.messages.length>0){let i=r.messages[r.messages.length-1];if(i&&i.role===`assistant`&&Array.isArray(i.parts)){let a=i.parts.map(n=>(0,f.isToolOrDynamicToolUIPart)(n)&&n.output&&t.isToolApprovalOutput(n.output)&&n.output.outcome===`pending`?{...n,output:{...n.output,outcome:e?`approved`:`rejected`}}:n),o=[...r.messages];o[o.length-1]={...i,parts:a},await n.update({messages:o})}}}finally{await n.release()}y.startChat(A)},[ne,y,A]),H=(0,h.useCallback)(()=>{let e=crypto.randomUUID();j(e),P(t=>[...t,e])},[]),ie=(0,h.useMemo)(()=>{if(ne)return{message:ne,approve:()=>re(!0),reject:()=>re(!1)}},[ne,re]),ae=(0,h.useMemo)(()=>{let e=M.messages;if(e.length!==0)for(let t=e.length-1;t>=0;t--){let n=e[t];if(!n||n.role!==`assistant`||!n.metadata||typeof n.metadata!=`object`||!(`totalUsage`in n.metadata))continue;let r=n.metadata.totalUsage;if(!(!r||typeof r!=`object`)&&!(!(`inputTokens`in r)||!(`outputTokens`in r)||!(`totalTokens`in r)))return{inputTokens:r.inputTokens,outputTokens:r.outputTokens,totalTokens:r.totalTokens,cachedInputTokens:r.cachedInputTokens}}},[M.messages]),U=(0,h.useMemo)(()=>{if(M.status!==`streaming`)return!1;if(!M.streamingMessage)return!0;let e=M.streamingMessage.parts.filter(f.isToolOrDynamicToolUIPart);return e.length>0&&e.every(e=>e.state.startsWith(`output-`))},[M.status,M.streamingMessage]);return{mode:r,setMode:o,toggleMode:s,chat:M,chats:N,switchChat:j,newChat:H,build:{status:u,error:l,entrypoint:p},devhook:{connected:I.status===`connected`,url:I.status===`connected`?`https://${I.id}.dev.blink.host`:void 0},capabilities:T,options:{schema:ee,selected:L,error:R,setOption:te},approval:ie,tokenUsage:ae,server:y,showWaitingPlaceholder:U}}exports.useAgent=x,exports.useBundler=C,exports.useChat=de,exports.useDevMode=_f,exports.useDevhook=Wa,exports.useDotenv=Ya,exports.useEditAgent=hf,exports.useOptions=Ua;
631
+ `;function hf(e){let[n,r]=(0,h.useState)(void 0),[i,a]=(0,h.useState)(void 0),o=(0,h.useRef)(void 0);return(0,h.useEffect)(()=>{let n=new AbortController;return(async()=>{o.current=pf({directory:e.directory});let i=await gf(),a=o.current.agent.serve({port:i,host:`127.0.0.1`,apiUrl:e.apiServerUrl});n.signal.addEventListener(`abort`,()=>{try{a.close()}catch{}});let s=new t.Client({baseUrl:`http://127.0.0.1:${i}`});for(;!n.signal.aborted;){try{await s.health();break}catch{}await new Promise(e=>setTimeout(e,100))}if(n.signal.aborted)throw n.signal.reason;r(s)})().catch(e=>{a(e instanceof Error?e:Error(String(e)))}),()=>n.abort()},[e.directory,e.apiServerUrl]),(0,h.useMemo)(()=>({client:n,error:i,setUserAgentUrl:e=>{o.current?.setUserAgentUrl(e)}}),[n,i])}async function gf(){let e=(0,s.createServer)();return new Promise((t,n)=>{e.listen(0,()=>{let n=e.address().port;t(n)}).on(`error`,e=>{n(e)})}).finally(()=>{e.close()})}function _f(e){let{directory:n}=e,[r,i]=(0,h.useState)(`run`),a=(0,h.useRef)(`run`);(0,h.useEffect)(()=>{a.current=r},[r]);let o=(0,h.useCallback)(t=>{i(t),e.onModeChange?.(t)},[e.onModeChange]),s=(0,h.useCallback)(()=>{o(r===`run`?`edit`:`run`)},[r,o]),{error:l,status:u,result:d,entry:p}=C({directory:n,onBuildStart:e.onBuildStart,onBuildSuccess:e.onBuildSuccess,onBuildError:e.onBuildError}),m=Ya(n),g=(0,h.useMemo)(()=>{let e=ja();return e?{...m,BLINK_TOKEN:e}:m},[m]),_=(0,h.useRef)(void 0);(0,h.useEffect)(()=>{let t=Object.keys(g);if(t.length===_.current||_.current===void 0){_.current=t.length;return}_.current=t.length,e.onEnvLoaded?.(t)},[g,e.onEnvLoaded]);let v=(0,h.useRef)(void 0),y=(0,h.useMemo)(()=>Ha({port:0,dataDirectory:(0,c.join)(n,`data`),getAgent:()=>v.current}),[n]),{agent:b,logs:S,error:w,capabilities:T}=x({buildResult:d,env:g,apiServerUrl:y.url}),{client:E,error:D,setUserAgentUrl:O}=hf({directory:n,apiServerUrl:y.url}),k=(0,h.useRef)(0);(0,h.useEffect)(()=>{if(S.length===k.current)return;let t=k.current;for(let n of S.slice(t))e.onAgentLog?.(n);k.current=S.length},[S,e.onAgentLog]);let[A,j]=(0,h.useState)(`default`);(0,h.useEffect)(()=>{b&&O(b.baseUrl),r===`run`?b?v.current=b:(v.current=void 0,y.stopChat(A)):r===`edit`&&(E?v.current=E:(v.current=void 0,y.stopChat(A)))},[b,E,r,A,y]);let M=de({chatId:A,agent:r===`run`?b:E,chatsDirectory:y.chatsDirectory,filterMessages:r===`run`?e=>!le(e.metadata):void 0}),[N,P]=(0,h.useState)([]);(0,h.useEffect)(()=>{y.listChats().then(e=>{P(e.map(e=>e.key))})},[y]),(0,h.useEffect)(()=>{A&&!N.includes(A)&&P(e=>[...e,A])},[A,N]);let F=(0,h.useMemo)(()=>Na(n),[n]),I=Wa({id:F,disabled:!T?.request,onRequest:async e=>{if(!b)throw Error(`No agent`);let t=new URL(e.url),n=new URL(b.baseUrl);return n.pathname=t.pathname,n.search=t.search,await fetch(n.toString(),e)}});(0,h.useEffect)(()=>{I.status===`connected`&&e.onDevhookConnected?.(`https://${I.id}.dev.blink.host`)},[I.status,I.id]);let{schema:ee,options:L,error:R,setOption:te}=Ua({agent:v.current,capabilities:T,messages:M.messages}),z=(0,h.useMemo)(()=>{let e=[];return w&&r===`run`&&e.push(w.message),D&&r===`edit`&&e.push(`Edit agent error: ${D.message}`),M.error&&e.push(`Chat error: ${M.error}`),R&&e.push(`Options error: ${R.message}`),e},[w,D,M.error,R,r]);(0,h.useEffect)(()=>{for(let t of z)e.onError?.(t)},[z]),(0,h.useEffect)(()=>{M.upsertMessage({id:crypto.randomUUID(),created_at:new Date().toISOString(),role:`assistant`,parts:[{type:`text`,text:r===`run`?`<run_mode />`:`<edit_mode />`}],metadata:{__blink_internal:!0,type:`mode`,mode:r}}).catch(e=>{console.error(`Error inserting mode delimiter:`,e)})},[r,M.upsertMessage]);let[B,V]=(0,h.useState)(),ne=(0,h.useMemo)(()=>{let e=[...M.messages].reverse().find(e=>!(e.role!==`assistant`||e.metadata&&e.metadata.ephemeral));if(!e||B===e.id)return;let n=e.parts.filter(f.isToolOrDynamicToolUIPart);if(n.length!==0&&n.some(e=>t.isToolApprovalOutput(e.output)&&e.output.outcome===`pending`))return e},[M.messages,B]),re=(0,h.useCallback)(async e=>{if(!ne)return;V(ne.id);let n=await y.lockChat(A);try{let r=await n.get();if(r.messages.length>0){let i=r.messages[r.messages.length-1];if(i&&i.role===`assistant`&&Array.isArray(i.parts)){let a=i.parts.map(n=>(0,f.isToolOrDynamicToolUIPart)(n)&&n.output&&t.isToolApprovalOutput(n.output)&&n.output.outcome===`pending`?{...n,output:{...n.output,outcome:e?`approved`:`rejected`}}:n),o=[...r.messages];o[o.length-1]={...i,parts:a},await n.update({messages:o})}}}finally{await n.release()}await y.startChat(A)},[ne,y,A]),H=(0,h.useCallback)(()=>{let e=crypto.randomUUID();j(e),P(t=>[...t,e])},[]),ie=(0,h.useMemo)(()=>{if(ne)return{message:ne,approve:()=>re(!0),reject:()=>re(!1)}},[ne,re]),ae=(0,h.useMemo)(()=>{let e=M.messages;if(e.length!==0)for(let t=e.length-1;t>=0;t--){let n=e[t];if(!n||n.role!==`assistant`||!n.metadata||typeof n.metadata!=`object`||!(`totalUsage`in n.metadata))continue;let r=n.metadata.totalUsage;if(!(!r||typeof r!=`object`)&&!(!(`inputTokens`in r)||!(`outputTokens`in r)||!(`totalTokens`in r)))return{inputTokens:r.inputTokens,outputTokens:r.outputTokens,totalTokens:r.totalTokens,cachedInputTokens:r.cachedInputTokens}}},[M.messages]),U=(0,h.useMemo)(()=>{if(M.status!==`streaming`)return!1;if(!M.streamingMessage)return!0;let e=M.streamingMessage.parts.filter(f.isToolOrDynamicToolUIPart);return e.length>0&&e.every(e=>e.state.startsWith(`output-`))},[M.status,M.streamingMessage]);return{mode:r,setMode:o,toggleMode:s,chat:M,chats:N,switchChat:j,newChat:H,build:{status:u,error:l,entrypoint:p},devhook:{connected:I.status===`connected`,url:I.status===`connected`?`https://${I.id}.dev.blink.host`:void 0},capabilities:T,options:{schema:ee,selected:L,error:R,setOption:te},approval:ie,tokenUsage:ae,server:y,showWaitingPlaceholder:U}}exports.useAgent=x,exports.useBundler=C,exports.useChat=de,exports.useDevMode=_f,exports.useDevhook=Wa,exports.useDotenv=Ya,exports.useEditAgent=hf,exports.useOptions=Ua;
@@ -166,7 +166,8 @@ declare class ChatManager {
166
166
  * Send a message to the agent
167
167
  */
168
168
  sendMessage(message: StoredMessage): Promise<void>;
169
- private processQueue;
169
+ start(): Promise<void>;
170
+ private processQueueOrRun;
170
171
  /**
171
172
  * Stop the current streaming operation
172
173
  */
@@ -236,7 +237,7 @@ declare function createLocalServer(options: CreateLocalServerOptions): {
236
237
  getChatManager: (chatId: string) => ChatManager;
237
238
  listChats: () => Promise<StoreEntry[]>;
238
239
  lockChat: (chatId: string) => Promise<LockedStoreEntry<StoredChat>>;
239
- startChat: (chatId: string) => void;
240
+ startChat: (chatId: string) => Promise<void>;
240
241
  stopChat: (chatId: string) => void;
241
242
  dispose: () => void;
242
243
  };
@@ -166,7 +166,8 @@ declare class ChatManager {
166
166
  * Send a message to the agent
167
167
  */
168
168
  sendMessage(message: StoredMessage): Promise<void>;
169
- private processQueue;
169
+ start(): Promise<void>;
170
+ private processQueueOrRun;
170
171
  /**
171
172
  * Stop the current streaming operation
172
173
  */
@@ -236,7 +237,7 @@ declare function createLocalServer(options: CreateLocalServerOptions): {
236
237
  getChatManager: (chatId: string) => ChatManager;
237
238
  listChats: () => Promise<StoreEntry[]>;
238
239
  lockChat: (chatId: string) => Promise<LockedStoreEntry<StoredChat>>;
239
- startChat: (chatId: string) => void;
240
+ startChat: (chatId: string) => Promise<void>;
240
241
  stopChat: (chatId: string) => void;
241
242
  dispose: () => void;
242
243
  };