blink 0.1.97 → 0.1.99

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.
@@ -19,7 +19,7 @@ export function ${e}(options) {
19
19
  return aiOriginal.${e}(options);
20
20
  }
21
21
  `).join(``)}
22
- `,loader:`js`,resolveDir:i?.resolveDir}})}}}function p(e){return async t=>{let r=await(await import(`esbuild`)).context({entryPoints:[t.entry],outdir:t.outdir,bundle:!0,write:!1,logLevel:`silent`,format:`esm`,platform:`node`,target:`node22`,sourcemap:!1,mainFields:[`module`,`main`],conditions:[`import`,`module`],plugins:[{name:`blink-esm-require-to-import`,setup(e){e.onEnd(t=>{e.initialOptions.format!==`esm`||e.initialOptions.platform!==`node`||t.outputFiles?.forEach(e=>{if(e.path.endsWith(`.js`)||e.path.endsWith(`.mjs`)){let t=Buffer.from(e.contents).toString(`utf-8`),n=new Map,r=RegExp(`\\b__require\\("(node:)?(${o.join(`|`)})"\\)`,`gm`);t=t.replace(r,(e,t,r)=>{let i=`__import_${r.toUpperCase().replace(/-/g,`_`)}`,a=`node:${r}`;return n.set(i,a),i}),n.size>0&&(t=Array.from(n.entries()).map(([e,t])=>`import ${e} from "${t}";`).join(`
22
+ `,loader:`js`,resolveDir:i?.resolveDir}})}}}function p(e){return async t=>{let r=await(await import(`esbuild`)).context({entryPoints:[t.entry],outdir:t.outdir,bundle:!0,write:!1,logLevel:`silent`,format:`esm`,platform:`node`,target:`node22`,sourcemap:!1,mainFields:[`module`,`main`],conditions:[`import`,`module`],plugins:[{name:`blink-esm-require-to-import`,setup(e){e.onEnd(t=>{e.initialOptions.format!==`esm`||e.initialOptions.platform!==`node`||t.outputFiles?.forEach(e=>{if(e.path.endsWith(`.js`)||e.path.endsWith(`.mjs`)){let t=Buffer.from(e.contents).toString(`utf-8`),n=new Map,r=RegExp(`\\b__require\\("(node:)?(${o.join(`|`)})(/[^"]+)?"\\)`,`gm`);t=t.replace(r,(e,t,r,i=``)=>{let a=r+i,o=`__import_${a.toUpperCase().replace(/[/-]/g,`_`)}`,s=`node:${a}`;return n.set(o,s),o}),n.size>0&&(t=Array.from(n.entries()).map(([e,t])=>`import ${e} from "${t}";`).join(`
23
23
  `)+`
24
24
 
25
25
  `+t),e.contents=Buffer.from(t,`utf-8`)}})})}},{name:`blink-dev-server`,setup(e){let i;e.onStart(()=>{t.onStart(),i=performance.now()}),e.onEnd(async e=>{await c(t.outdir,{recursive:!0,force:!0}),await s(t.outdir,{recursive:!0});let a=e.outputFiles?.map(e=>({path:e.path,contents:e.contents}))??[];a.push({path:n.resolve(t.outdir,`package.json`),contents:Buffer.from(JSON.stringify({type:`module`},null,2),`utf-8`)});for(let e of a)await u(e.path,e.contents);e.errors.length>0?t.onResult({error:{message:e.errors.map(e=>`${e.text} (${e.location?.file})`).join(`
package/dist/cli/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{__commonJSMin as e,__require as t,__toESM as n}from"./chunk-D9KrCrVq.js";import{import_websocket as r}from"./wrapper-B0SBsJWP.js";import{findNearestEntry as i,require_ignore as a,resolveConfig as o}from"./ignore-9sH8Tr-1.js";import{Client as s,loginIfNeeded as c,require_source as l}from"./auth-DjAEZyZZ.js";import{Y as u,pD as d,ve as f,ye as p}from"./dist-BNbSDxaw.js";import"./open-DCYivxgo.js";import{migrateBlinkToData as m,require_main as h}from"./main-BdSSlDIs.js";import{randomUUID as g}from"crypto";import{basename as _,dirname as v,join as y,relative as ee}from"node:path";import{existsSync as te}from"node:fs";import{mkdir as ne,readdir as b,writeFile as re}from"fs/promises";import{readFile as x,stat as S}from"node:fs/promises";var C=e((e=>{var t=class extends Error{constructor(e,t,n){super(n),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=t,this.exitCode=e,this.nestedError=void 0}},n=class extends t{constructor(e){super(1,`commander.invalidArgument`,e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};e.CommanderError=t,e.InvalidArgumentError=n})),w=e((e=>{let{InvalidArgumentError:t}=C();var n=class{constructor(e,t){switch(this.description=t||``,this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case`<`:this.required=!0,this._name=e.slice(1,-1);break;case`[`:this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e;break}this._name.endsWith(`...`)&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_collectValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:(t.push(e),t)}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(e,n)=>{if(!this.argChoices.includes(e))throw new t(`Allowed choices are ${this.argChoices.join(`, `)}.`);return this.variadic?this._collectValue(e,n):e},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function r(e){let t=e.name()+(e.variadic===!0?`...`:``);return e.required?`<`+t+`>`:`[`+t+`]`}e.Argument=n,e.humanReadableArgName=r})),T=e((e=>{let{humanReadableArgName:t}=w();var n=class{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(e){this.helpWidth=this.helpWidth??e.helpWidth??80}visibleCommands(e){let t=e.commands.filter(e=>!e._hidden),n=e._getHelpCommand();return n&&!n._hidden&&t.push(n),this.sortSubcommands&&t.sort((e,t)=>e.name().localeCompare(t.name())),t}compareOptions(e,t){let n=e=>e.short?e.short.replace(/^-/,``):e.long.replace(/^--/,``);return n(e).localeCompare(n(t))}visibleOptions(e){let t=e.options.filter(e=>!e.hidden),n=e._getHelpOption();if(n&&!n.hidden){let r=n.short&&e._findOption(n.short),i=n.long&&e._findOption(n.long);!r&&!i?t.push(n):n.long&&!i?t.push(e.createOption(n.long,n.description)):n.short&&!r&&t.push(e.createOption(n.short,n.description))}return this.sortOptions&&t.sort(this.compareOptions),t}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let t=[];for(let n=e.parent;n;n=n.parent){let e=n.options.filter(e=>!e.hidden);t.push(...e)}return this.sortOptions&&t.sort(this.compareOptions),t}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(t=>{t.description=t.description||e._argsDescription[t.name()]||``}),e.registeredArguments.find(e=>e.description)?e.registeredArguments:[]}subcommandTerm(e){let n=e.registeredArguments.map(e=>t(e)).join(` `);return e._name+(e._aliases[0]?`|`+e._aliases[0]:``)+(e.options.length?` [options]`:``)+(n?` `+n:``)}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,t){return t.visibleCommands(e).reduce((e,n)=>Math.max(e,this.displayWidth(t.styleSubcommandTerm(t.subcommandTerm(n)))),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((e,n)=>Math.max(e,this.displayWidth(t.styleOptionTerm(t.optionTerm(n)))),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((e,n)=>Math.max(e,this.displayWidth(t.styleOptionTerm(t.optionTerm(n)))),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((e,n)=>Math.max(e,this.displayWidth(t.styleArgumentTerm(t.argumentTerm(n)))),0)}commandUsage(e){let t=e._name;e._aliases[0]&&(t=t+`|`+e._aliases[0]);let n=``;for(let t=e.parent;t;t=t.parent)n=t.name()+` `+n;return n+t+` `+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(e=>JSON.stringify(e)).join(`, `)}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue==`boolean`)&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&t.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&t.push(`env: ${e.envVar}`),t.length>0){let n=`(${t.join(`, `)})`;return e.description?`${e.description} ${n}`:n}return e.description}argumentDescription(e){let t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(e=>JSON.stringify(e)).join(`, `)}`),e.defaultValue!==void 0&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),t.length>0){let n=`(${t.join(`, `)})`;return e.description?`${e.description} ${n}`:n}return e.description}formatItemList(e,t,n){return t.length===0?[]:[n.styleTitle(e),...t,``]}groupItems(e,t,n){let r=new Map;return e.forEach(e=>{let t=n(e);r.has(t)||r.set(t,[])}),t.forEach(e=>{let t=n(e);r.has(t)||r.set(t,[]),r.get(t).push(e)}),r}formatHelp(e,t){let n=t.padWidth(e,t),r=t.helpWidth??80;function i(e,r){return t.formatItem(e,n,r,t)}let a=[`${t.styleTitle(`Usage:`)} ${t.styleUsage(t.commandUsage(e))}`,``],o=t.commandDescription(e);o.length>0&&(a=a.concat([t.boxWrap(t.styleCommandDescription(o),r),``]));let s=t.visibleArguments(e).map(e=>i(t.styleArgumentTerm(t.argumentTerm(e)),t.styleArgumentDescription(t.argumentDescription(e))));if(a=a.concat(this.formatItemList(`Arguments:`,s,t)),this.groupItems(e.options,t.visibleOptions(e),e=>e.helpGroupHeading??`Options:`).forEach((e,n)=>{let r=e.map(e=>i(t.styleOptionTerm(t.optionTerm(e)),t.styleOptionDescription(t.optionDescription(e))));a=a.concat(this.formatItemList(n,r,t))}),t.showGlobalOptions){let n=t.visibleGlobalOptions(e).map(e=>i(t.styleOptionTerm(t.optionTerm(e)),t.styleOptionDescription(t.optionDescription(e))));a=a.concat(this.formatItemList(`Global Options:`,n,t))}return this.groupItems(e.commands,t.visibleCommands(e),e=>e.helpGroup()||`Commands:`).forEach((e,n)=>{let r=e.map(e=>i(t.styleSubcommandTerm(t.subcommandTerm(e)),t.styleSubcommandDescription(t.subcommandDescription(e))));a=a.concat(this.formatItemList(n,r,t))}),a.join(`
2
+ import{__commonJSMin as e,__require as t,__toESM as n}from"./chunk-D9KrCrVq.js";import{import_websocket as r}from"./wrapper-B0SBsJWP.js";import{findNearestEntry as i,require_ignore as a,resolveConfig as o}from"./ignore-6Nkv6BEs.js";import{Client as s,loginIfNeeded as c,require_source as l}from"./auth-DjAEZyZZ.js";import{Y as u,pD as d,ve as f,ye as p}from"./dist-BNbSDxaw.js";import"./open-DCYivxgo.js";import{migrateBlinkToData as m,require_main as h}from"./main-BdSSlDIs.js";import{randomUUID as g}from"crypto";import{basename as _,dirname as v,join as y,relative as ee}from"node:path";import{existsSync as te}from"node:fs";import{mkdir as ne,readdir as b,writeFile as re}from"fs/promises";import{readFile as x,stat as S}from"node:fs/promises";var C=e((e=>{var t=class extends Error{constructor(e,t,n){super(n),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=t,this.exitCode=e,this.nestedError=void 0}},n=class extends t{constructor(e){super(1,`commander.invalidArgument`,e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};e.CommanderError=t,e.InvalidArgumentError=n})),w=e((e=>{let{InvalidArgumentError:t}=C();var n=class{constructor(e,t){switch(this.description=t||``,this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case`<`:this.required=!0,this._name=e.slice(1,-1);break;case`[`:this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e;break}this._name.endsWith(`...`)&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_collectValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:(t.push(e),t)}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(e,n)=>{if(!this.argChoices.includes(e))throw new t(`Allowed choices are ${this.argChoices.join(`, `)}.`);return this.variadic?this._collectValue(e,n):e},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function r(e){let t=e.name()+(e.variadic===!0?`...`:``);return e.required?`<`+t+`>`:`[`+t+`]`}e.Argument=n,e.humanReadableArgName=r})),T=e((e=>{let{humanReadableArgName:t}=w();var n=class{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(e){this.helpWidth=this.helpWidth??e.helpWidth??80}visibleCommands(e){let t=e.commands.filter(e=>!e._hidden),n=e._getHelpCommand();return n&&!n._hidden&&t.push(n),this.sortSubcommands&&t.sort((e,t)=>e.name().localeCompare(t.name())),t}compareOptions(e,t){let n=e=>e.short?e.short.replace(/^-/,``):e.long.replace(/^--/,``);return n(e).localeCompare(n(t))}visibleOptions(e){let t=e.options.filter(e=>!e.hidden),n=e._getHelpOption();if(n&&!n.hidden){let r=n.short&&e._findOption(n.short),i=n.long&&e._findOption(n.long);!r&&!i?t.push(n):n.long&&!i?t.push(e.createOption(n.long,n.description)):n.short&&!r&&t.push(e.createOption(n.short,n.description))}return this.sortOptions&&t.sort(this.compareOptions),t}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let t=[];for(let n=e.parent;n;n=n.parent){let e=n.options.filter(e=>!e.hidden);t.push(...e)}return this.sortOptions&&t.sort(this.compareOptions),t}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(t=>{t.description=t.description||e._argsDescription[t.name()]||``}),e.registeredArguments.find(e=>e.description)?e.registeredArguments:[]}subcommandTerm(e){let n=e.registeredArguments.map(e=>t(e)).join(` `);return e._name+(e._aliases[0]?`|`+e._aliases[0]:``)+(e.options.length?` [options]`:``)+(n?` `+n:``)}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,t){return t.visibleCommands(e).reduce((e,n)=>Math.max(e,this.displayWidth(t.styleSubcommandTerm(t.subcommandTerm(n)))),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((e,n)=>Math.max(e,this.displayWidth(t.styleOptionTerm(t.optionTerm(n)))),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((e,n)=>Math.max(e,this.displayWidth(t.styleOptionTerm(t.optionTerm(n)))),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((e,n)=>Math.max(e,this.displayWidth(t.styleArgumentTerm(t.argumentTerm(n)))),0)}commandUsage(e){let t=e._name;e._aliases[0]&&(t=t+`|`+e._aliases[0]);let n=``;for(let t=e.parent;t;t=t.parent)n=t.name()+` `+n;return n+t+` `+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(e=>JSON.stringify(e)).join(`, `)}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue==`boolean`)&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&t.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&t.push(`env: ${e.envVar}`),t.length>0){let n=`(${t.join(`, `)})`;return e.description?`${e.description} ${n}`:n}return e.description}argumentDescription(e){let t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(e=>JSON.stringify(e)).join(`, `)}`),e.defaultValue!==void 0&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),t.length>0){let n=`(${t.join(`, `)})`;return e.description?`${e.description} ${n}`:n}return e.description}formatItemList(e,t,n){return t.length===0?[]:[n.styleTitle(e),...t,``]}groupItems(e,t,n){let r=new Map;return e.forEach(e=>{let t=n(e);r.has(t)||r.set(t,[])}),t.forEach(e=>{let t=n(e);r.has(t)||r.set(t,[]),r.get(t).push(e)}),r}formatHelp(e,t){let n=t.padWidth(e,t),r=t.helpWidth??80;function i(e,r){return t.formatItem(e,n,r,t)}let a=[`${t.styleTitle(`Usage:`)} ${t.styleUsage(t.commandUsage(e))}`,``],o=t.commandDescription(e);o.length>0&&(a=a.concat([t.boxWrap(t.styleCommandDescription(o),r),``]));let s=t.visibleArguments(e).map(e=>i(t.styleArgumentTerm(t.argumentTerm(e)),t.styleArgumentDescription(t.argumentDescription(e))));if(a=a.concat(this.formatItemList(`Arguments:`,s,t)),this.groupItems(e.options,t.visibleOptions(e),e=>e.helpGroupHeading??`Options:`).forEach((e,n)=>{let r=e.map(e=>i(t.styleOptionTerm(t.optionTerm(e)),t.styleOptionDescription(t.optionDescription(e))));a=a.concat(this.formatItemList(n,r,t))}),t.showGlobalOptions){let n=t.visibleGlobalOptions(e).map(e=>i(t.styleOptionTerm(t.optionTerm(e)),t.styleOptionDescription(t.optionDescription(e))));a=a.concat(this.formatItemList(`Global Options:`,n,t))}return this.groupItems(e.commands,t.visibleCommands(e),e=>e.helpGroup()||`Commands:`).forEach((e,n)=>{let r=e.map(e=>i(t.styleSubcommandTerm(t.subcommandTerm(e)),t.styleSubcommandDescription(t.subcommandDescription(e))));a=a.concat(this.formatItemList(n,r,t))}),a.join(`
3
3
  `)}displayWidth(e){return r(e).length}styleTitle(e){return e}styleUsage(e){return e.split(` `).map(e=>e===`[options]`?this.styleOptionText(e):e===`[command]`?this.styleSubcommandText(e):e[0]===`[`||e[0]===`<`?this.styleArgumentText(e):this.styleCommandText(e)).join(` `)}styleCommandDescription(e){return this.styleDescriptionText(e)}styleOptionDescription(e){return this.styleDescriptionText(e)}styleSubcommandDescription(e){return this.styleDescriptionText(e)}styleArgumentDescription(e){return this.styleDescriptionText(e)}styleDescriptionText(e){return e}styleOptionTerm(e){return this.styleOptionText(e)}styleSubcommandTerm(e){return e.split(` `).map(e=>e===`[options]`?this.styleOptionText(e):e[0]===`[`||e[0]===`<`?this.styleArgumentText(e):this.styleSubcommandText(e)).join(` `)}styleArgumentTerm(e){return this.styleArgumentText(e)}styleOptionText(e){return e}styleArgumentText(e){return e}styleSubcommandText(e){return e}styleCommandText(e){return e}padWidth(e,t){return Math.max(t.longestOptionTermLength(e,t),t.longestGlobalOptionTermLength(e,t),t.longestSubcommandTermLength(e,t),t.longestArgumentTermLength(e,t))}preformatted(e){return/\n[^\S\r\n]/.test(e)}formatItem(e,t,n,r){let i=` `.repeat(2);if(!n)return i+e;let a=e.padEnd(t+e.length-r.displayWidth(e)),o=(this.helpWidth??80)-t-2-2,s;return s=o<this.minWidthToWrap||r.preformatted(n)?n:r.boxWrap(n,o).replace(/\n/g,`
4
4
  `+` `.repeat(t+2)),i+a+` `.repeat(2)+s.replace(/\n/g,`\n${i}`)}boxWrap(e,t){if(t<this.minWidthToWrap)return e;let n=e.split(/\r\n|\n/),r=/[\s]*[^\s]+/g,i=[];return n.forEach(e=>{let n=e.match(r);if(n===null){i.push(``);return}let a=[n.shift()],o=this.displayWidth(a[0]);n.forEach(e=>{let n=this.displayWidth(e);if(o+n<=t){a.push(e),o+=n;return}i.push(a.join(``));let r=e.trimStart();a=[r],o=this.displayWidth(r)}),i.push(a.join(``))}),i.join(`
5
5
  `)}};function r(e){return e.replace(/\x1b\[\d*(;\d*)*m/g,``)}e.Help=n,e.stripColor=r})),E=e((e=>{let{InvalidArgumentError:t}=C();var n=class{constructor(e,t){this.flags=e,this.description=t||``,this.required=e.includes(`<`),this.optional=e.includes(`[`),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let n=a(e);this.short=n.shortFlag,this.long=n.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith(`--no-`)),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0,this.helpGroupHeading=void 0}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let t=e;return typeof e==`string`&&(t={[e]:!0}),this.implied=Object.assign(this.implied||{},t),this}env(e){return this.envVar=e,this}argParser(e){return this.parseArg=e,this}makeOptionMandatory(e=!0){return this.mandatory=!!e,this}hideHelp(e=!0){return this.hidden=!!e,this}_collectValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:(t.push(e),t)}choices(e){return this.argChoices=e.slice(),this.parseArg=(e,n)=>{if(!this.argChoices.includes(e))throw new t(`Allowed choices are ${this.argChoices.join(`, `)}.`);return this.variadic?this._collectValue(e,n):e},this}name(){return this.long?this.long.replace(/^--/,``):this.short.replace(/^-/,``)}attributeName(){return this.negate?i(this.name().replace(/^no-/,``)):i(this.name())}helpGroup(e){return this.helpGroupHeading=e,this}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},r=class{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach(e=>{e.negate?this.negativeOptions.set(e.attributeName(),e):this.positiveOptions.set(e.attributeName(),e)}),this.negativeOptions.forEach((e,t)=>{this.positiveOptions.has(t)&&this.dualOptions.add(t)})}valueFromOption(e,t){let n=t.attributeName();if(!this.dualOptions.has(n))return!0;let r=this.negativeOptions.get(n).presetArg,i=r===void 0?!1:r;return t.negate===(i===e)}};function i(e){return e.split(`-`).reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function a(e){let t,n,r=/^-[^-]$/,i=/^--[^-]/,a=e.split(/[ |,]+/).concat(`guard`);if(r.test(a[0])&&(t=a.shift()),i.test(a[0])&&(n=a.shift()),!t&&r.test(a[0])&&(t=a.shift()),!t&&i.test(a[0])&&(t=n,n=a.shift()),a[0].startsWith(`-`)){let t=a[0],n=`option creation failed due to '${t}' in option flags '${e}'`;throw/^-[^-][^-]/.test(t)?Error(`${n}
@@ -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.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(`
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.99`;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-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{};
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-w5PyI9S9.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-D8dpOtYY.js`))),k.command(`chat`,{hidden:!0}).description(`Start a Blink chat connected to your machine.`).action(G(()=>import(`./chat-DX_V608z.js`))),k.command(`login`,{hidden:!0}).description(`Log in to the Blink Cloud.`).action(G(()=>import(`./login-DTwQcbaT.js`))),k.parse(process.argv);export{};
@@ -11,6 +11,6 @@ import{import_websocket as e}from"./wrapper-B0SBsJWP.js";import{createRequire as
11
11
  `));let r=e.pax;if(r)for(let e in r)n+=y(` `+e+`=`+r[e]+`
12
12
  `);return t.from(n)},e.decodePax=function(e){let n={};for(;e.length;){let r=0;for(;r<e.length&&e[r]!==32;)r++;let i=parseInt(t.toString(e.subarray(0,r)),10);if(!i)return n;let a=t.toString(e.subarray(r+1,i-1)),o=a.indexOf(`=`);if(o===-1)return n;n[a.slice(0,o)]=a.slice(o+1),e=e.subarray(i)}return n},e.encode=function(e){let i=t.alloc(512),a=e.name,o=``;if(e.typeflag===5&&a[a.length-1]!==`/`&&(a+=`/`),t.byteLength(a)!==a.length)return null;for(;t.byteLength(a)>100;){let e=a.indexOf(`/`);if(e===-1)return null;o+=o?`/`+a.slice(0,e):a.slice(0,e),a=a.slice(e+1)}return t.byteLength(a)>100||t.byteLength(o)>155||e.linkname&&t.byteLength(e.linkname)>100?null:(t.write(i,a),t.write(i,p(e.mode&4095,6),100),t.write(i,p(e.uid,6),108),t.write(i,p(e.gid,6),116),h(e.size,i,124),t.write(i,p(e.mtime.getTime()/1e3|0,11),136),i[156]=48+u(e.type),e.linkname&&t.write(i,e.linkname,157),t.copy(n,i,257),t.copy(r,i,263),e.uname&&t.write(i,e.uname,265),e.gname&&t.write(i,e.gname,297),t.write(i,p(e.devmajor||0,6),329),t.write(i,p(e.devminor||0,6),337),o&&t.write(i,o,345),t.write(i,p(f(i),6),148),i)},e.decode=function(e,t,n){let r=e[156]===0?0:e[156]-48,i=v(e,0,100,t),a=_(e,100,8),c=_(e,108,8),u=_(e,116,8),d=_(e,124,12),p=_(e,136,12),m=l(r),h=e[157]===0?null:v(e,157,100,t),g=v(e,265,32),y=v(e,297,32),b=_(e,329,8),x=_(e,337,8),S=f(e);if(S===256)return null;if(S!==_(e,148,8))throw Error(`Invalid tar header. Maybe the tar is corrupted or it needs to be gunzipped?`);if(o(e))e[345]&&(i=v(e,345,155,t)+`/`+i);else if(!s(e)&&!n)throw Error(`Invalid tar header: unknown format.`);return r===0&&i&&i[i.length-1]===`/`&&(r=5),{name:i,mode:a,uid:c,gid:u,size:d,mtime:new Date(1e3*p),type:m,linkname:h,uname:g,gname:y,devmajor:b,devminor:x,pax:null}};function o(e){return t.equals(n,e.subarray(257,263))}function s(e){return t.equals(i,e.subarray(257,263))&&t.equals(a,e.subarray(263,265))}function c(e,t,n){return typeof e==`number`?(e=~~e,e>=t?t:e>=0||(e+=t,e>=0)?e:0):n}function l(e){switch(e){case 0:return`file`;case 1:return`link`;case 2:return`symlink`;case 3:return`character-device`;case 4:return`block-device`;case 5:return`directory`;case 6:return`fifo`;case 7:return`contiguous-file`;case 72:return`pax-header`;case 55:return`pax-global-header`;case 27:return`gnu-long-link-path`;case 28:case 30:return`gnu-long-path`}return null}function u(e){switch(e){case`file`:return 0;case`link`:return 1;case`symlink`:return 2;case`character-device`:return 3;case`block-device`:return 4;case`directory`:return 5;case`fifo`:return 6;case`contiguous-file`:return 7;case`pax-header`:return 72}return 0}function d(e,t,n,r){for(;n<r;n++)if(e[n]===t)return n;return r}function f(e){let t=256;for(let n=0;n<148;n++)t+=e[n];for(let n=156;n<512;n++)t+=e[n];return t}function p(e,t){return e=e.toString(8),e.length>t?`7777777777777777777`.slice(0,t)+` `:`0000000000000000000`.slice(0,t-e.length)+e+` `}function m(e,t,n){t[n]=128;for(let r=11;r>0;r--)t[n+r]=e&255,e=Math.floor(e/256)}function h(e,n,r){e.toString(8).length>11?m(e,n,r):t.write(n,p(e,11),r)}function g(e){let t;if(e[0]===128)t=!0;else if(e[0]===255)t=!1;else return null;let n=[],r;for(r=e.length-1;r>0;r--){let i=e[r];t?n.push(i):n.push(255-i)}let i=0,a=n.length;for(r=0;r<a;r++)i+=n[r]*256**r;return t?i:-1*i}function _(e,n,r){if(e=e.subarray(n,n+r),n=0,e[n]&128)return g(e);{for(;n<e.length&&e[n]===32;)n++;let r=c(d(e,32,n,e.length),e.length,e.length);for(;n<r&&e[n]===0;)n++;return r===n?0:parseInt(t.toString(e.subarray(n,r)),8)}}function v(e,n,r,i){return t.toString(e.subarray(n,d(e,0,n,n+r)),i)}function y(e){let n=t.byteLength(e),r=Math.floor(Math.log(n)/Math.log(10))+1;return n+r>=10**r&&r++,n+r+e}})}),Wt=O({"../../node_modules/tar-stream/extract.js":((e,t)=>{let{Writable:n,Readable:r,getStreamError:i}=Ht(),a=Lt(),o=Rt(),s=Ut(),c=o.alloc(0);var l=class{constructor(){this.buffered=0,this.shifted=0,this.queue=new a,this._offset=0}push(e){this.buffered+=e.byteLength,this.queue.push(e)}shiftFirst(e){return this._buffered===0?null:this._next(e)}shift(e){if(e>this.buffered)return null;if(e===0)return c;let t=this._next(e);if(e===t.byteLength)return t;let n=[t];for(;(e-=t.byteLength)>0;)t=this._next(e),n.push(t);return o.concat(n)}_next(e){let t=this.queue.peek(),n=t.byteLength-this._offset;if(e>=n){let e=this._offset?t.subarray(this._offset,t.byteLength):t;return this.queue.shift(),this._offset=0,this.buffered-=n,this.shifted+=n,e}return this.buffered-=e,this.shifted+=e,t.subarray(this._offset,this._offset+=e)}},u=class extends r{constructor(e,t,n){super(),this.header=t,this.offset=n,this._parent=e}_read(e){this.header.size===0&&this.push(null),this._parent._stream===this&&this._parent._update(),e(null)}_predestroy(){this._parent.destroy(i(this))}_detach(){this._parent._stream===this&&(this._parent._stream=null,this._parent._missing=p(this.header.size),this._parent._update())}_destroy(e){this._detach(),e(null)}},d=class extends n{constructor(e){super(e),e||={},this._buffer=new l,this._offset=0,this._header=null,this._stream=null,this._missing=0,this._longHeader=!1,this._callback=f,this._locked=!1,this._finished=!1,this._pax=null,this._paxGlobal=null,this._gnuLongPath=null,this._gnuLongLinkPath=null,this._filenameEncoding=e.filenameEncoding||`utf-8`,this._allowUnknownFormat=!!e.allowUnknownFormat,this._unlockBound=this._unlock.bind(this)}_unlock(e){if(this._locked=!1,e){this.destroy(e),this._continueWrite(e);return}this._update()}_consumeHeader(){if(this._locked)return!1;this._offset=this._buffer.shifted;try{this._header=s.decode(this._buffer.shift(512),this._filenameEncoding,this._allowUnknownFormat)}catch(e){return this._continueWrite(e),!1}if(!this._header)return!0;switch(this._header.type){case`gnu-long-path`:case`gnu-long-link-path`:case`pax-global-header`:case`pax-header`:return this._longHeader=!0,this._missing=this._header.size,!0}return this._locked=!0,this._applyLongHeaders(),this._header.size===0||this._header.type===`directory`?(this.emit(`entry`,this._header,this._createStream(),this._unlockBound),!0):(this._stream=this._createStream(),this._missing=this._header.size,this.emit(`entry`,this._header,this._stream,this._unlockBound),!0)}_applyLongHeaders(){this._gnuLongPath&&=(this._header.name=this._gnuLongPath,null),this._gnuLongLinkPath&&=(this._header.linkname=this._gnuLongLinkPath,null),this._pax&&=(this._pax.path&&(this._header.name=this._pax.path),this._pax.linkpath&&(this._header.linkname=this._pax.linkpath),this._pax.size&&(this._header.size=parseInt(this._pax.size,10)),this._header.pax=this._pax,null)}_decodeLongHeader(e){switch(this._header.type){case`gnu-long-path`:this._gnuLongPath=s.decodeLongPath(e,this._filenameEncoding);break;case`gnu-long-link-path`:this._gnuLongLinkPath=s.decodeLongPath(e,this._filenameEncoding);break;case`pax-global-header`:this._paxGlobal=s.decodePax(e);break;case`pax-header`:this._pax=this._paxGlobal===null?s.decodePax(e):Object.assign({},this._paxGlobal,s.decodePax(e));break}}_consumeLongHeader(){this._longHeader=!1,this._missing=p(this._header.size);let e=this._buffer.shift(this._header.size);try{this._decodeLongHeader(e)}catch(e){return this._continueWrite(e),!1}return!0}_consumeStream(){let e=this._buffer.shiftFirst(this._missing);if(e===null)return!1;this._missing-=e.byteLength;let t=this._stream.push(e);return this._missing===0?(this._stream.push(null),t&&this._stream._detach(),t&&this._locked===!1):t}_createStream(){return new u(this,this._header,this._offset)}_update(){for(;this._buffer.buffered>0&&!this.destroying;){if(this._missing>0){if(this._stream!==null){if(this._consumeStream()===!1)return;continue}if(this._longHeader===!0){if(this._missing>this._buffer.buffered)break;if(this._consumeLongHeader()===!1)return!1;continue}let e=this._buffer.shiftFirst(this._missing);e!==null&&(this._missing-=e.byteLength);continue}if(this._buffer.buffered<512)break;if(this._stream!==null||this._consumeHeader()===!1)return}this._continueWrite(null)}_continueWrite(e){let t=this._callback;this._callback=f,t(e)}_write(e,t){this._callback=t,this._buffer.push(e),this._update()}_final(e){this._finished=this._missing===0&&this._buffer.buffered===0,e(this._finished?null:Error(`Unexpected end of data`))}_predestroy(){this._continueWrite(null)}_destroy(e){this._stream&&this._stream.destroy(i(this)),e(null)}[Symbol.asyncIterator](){let e=null,t=null,n=null,r=null,i=null,a=this;return this.on(`entry`,c),this.on(`error`,t=>{e=t}),this.on(`close`,l),{[Symbol.asyncIterator](){return this},next(){return new Promise(s)},return(){return u(null)},throw(e){return u(e)}};function o(e){if(!i)return;let t=i;i=null,t(e)}function s(i,s){if(e)return s(e);if(r){i({value:r,done:!1}),r=null;return}t=i,n=s,o(null),a._finished&&t&&(t({value:void 0,done:!0}),t=n=null)}function c(e,a,o){i=o,a.on(`error`,f),t?(t({value:a,done:!1}),t=n=null):r=a}function l(){o(e),t&&=(e?n(e):t({value:void 0,done:!0}),n=null)}function u(e){return a.destroy(e),o(e),new Promise((t,n)=>{if(a.destroyed)return t({value:void 0,done:!0});a.once(`close`,function(){e?n(e):t({value:void 0,done:!0})})})}}};t.exports=function(e){return new d(e)};function f(){}function p(e){return e&=511,e&&512-e}})}),Gt=O({"../../node_modules/tar-stream/constants.js":((e,t)=>{let n={S_IFMT:61440,S_IFDIR:16384,S_IFCHR:8192,S_IFBLK:24576,S_IFIFO:4096,S_IFLNK:40960};try{t.exports=j(`fs`).constants||n}catch{t.exports=n}})}),Kt=O({"../../node_modules/tar-stream/pack.js":((e,t)=>{let{Readable:n,Writable:r,getStreamError:i}=Ht(),a=Rt(),o=Gt(),s=Ut(),c=a.alloc(1024);var l=class extends r{constructor(e,t,n){super({mapWritable:m,eagerOpen:!0}),this.written=0,this.header=t,this._callback=n,this._linkname=null,this._isLinkname=t.type===`symlink`&&!t.linkname,this._isVoid=t.type!==`file`&&t.type!==`contiguous-file`,this._finished=!1,this._pack=e,this._openCallback=null,this._pack._stream===null?this._pack._stream=this:this._pack._pending.push(this)}_open(e){this._openCallback=e,this._pack._stream===this&&this._continueOpen()}_continuePack(e){if(this._callback===null)return;let t=this._callback;this._callback=null,t(e)}_continueOpen(){this._pack._stream===null&&(this._pack._stream=this);let e=this._openCallback;if(this._openCallback=null,e!==null){if(this._pack.destroying)return e(Error(`pack stream destroyed`));if(this._pack._finalized)return e(Error(`pack stream is already finalized`));this._pack._stream=this,this._isLinkname||this._pack._encode(this.header),this._isVoid&&(this._finish(),this._continuePack(null)),e(null)}}_write(e,t){if(this._isLinkname)return this._linkname=this._linkname?a.concat([this._linkname,e]):e,t(null);if(this._isVoid)return e.byteLength>0?t(Error(`No body allowed for this entry`)):t();if(this.written+=e.byteLength,this._pack.push(e))return t();this._pack._drain=t}_finish(){this._finished||(this._finished=!0,this._isLinkname&&(this.header.linkname=this._linkname?a.toString(this._linkname,`utf-8`):``,this._pack._encode(this.header)),p(this._pack,this.header.size),this._pack._done(this))}_final(e){if(this.written!==this.header.size)return e(Error(`Size mismatch`));this._finish(),e(null)}_getError(){return i(this)||Error(`tar entry destroyed`)}_predestroy(){this._pack.destroy(this._getError())}_destroy(e){this._pack._done(this),this._continuePack(this._finished?null:this._getError()),e()}},u=class extends n{constructor(e){super(e),this._drain=f,this._finalized=!1,this._finalizing=!1,this._pending=[],this._stream=null}entry(e,t,n){if(this._finalized||this.destroying)throw Error(`already finalized or destroyed`);typeof t==`function`&&(n=t,t=null),n||=f,(!e.size||e.type===`symlink`)&&(e.size=0),e.type||=d(e.mode),e.mode||=e.type===`directory`?493:420,e.uid||=0,e.gid||=0,e.mtime||=new Date,typeof t==`string`&&(t=a.from(t));let r=new l(this,e,n);return a.isBuffer(t)?(e.size=t.byteLength,r.write(t),r.end(),r):(r._isVoid,r)}finalize(){if(this._stream||this._pending.length>0){this._finalizing=!0;return}this._finalized||(this._finalized=!0,this.push(c),this.push(null))}_done(e){e===this._stream&&(this._stream=null,this._finalizing&&this.finalize(),this._pending.length&&this._pending.shift()._continueOpen())}_encode(e){if(!e.pax){let t=s.encode(e);if(t){this.push(t);return}}this._encodePax(e)}_encodePax(e){let t=s.encodePax({name:e.name,linkname:e.linkname,pax:e.pax}),n={name:`PaxHeader`,mode:e.mode,uid:e.uid,gid:e.gid,size:t.byteLength,mtime:e.mtime,type:`pax-header`,linkname:e.linkname&&`PaxHeader`,uname:e.uname,gname:e.gname,devmajor:e.devmajor,devminor:e.devminor};this.push(s.encode(n)),this.push(t),p(this,t.byteLength),n.size=e.size,n.type=e.type,this.push(s.encode(n))}_doDrain(){let e=this._drain;this._drain=f,e()}_predestroy(){let e=i(this);for(this._stream&&this._stream.destroy(e);this._pending.length;){let t=this._pending.shift();t.destroy(e),t._continueOpen()}this._doDrain()}_read(e){this._doDrain(),e()}};t.exports=function(e){return new u(e)};function d(e){switch(e&o.S_IFMT){case o.S_IFBLK:return`block-device`;case o.S_IFCHR:return`character-device`;case o.S_IFDIR:return`directory`;case o.S_IFIFO:return`fifo`;case o.S_IFLNK:return`symlink`}return`file`}function f(){}function p(e,t){t&=511,t&&e.push(c.subarray(0,512-t))}function m(e){return a.isBuffer(e)?e:a.from(e)}})}),qt=A(O({"../../node_modules/tar-stream/index.js":(e=>{e.extract=Wt(),e.pack=Kt()})})(),1);const Jt=async(e,t)=>{let{maxBytes:r=50*1024*1024}=t??{};if(!(await o.stat(e)).isDirectory())throw Error(`Path is not a directory: ${e}`);let i=qt.pack(),a=async(e,t=``)=>{let r=await o.readdir(e,{withFileTypes:!0});for(let s of r){let r=`${e}/${s.name}`,c=t?`${t}/${s.name}`:s.name;if(s.isDirectory()){i.entry({name:`${c}/`,type:`directory`}),await a(r,c);continue}if(s.isSymbolicLink?.()){let e=await o.readlink(r);i.entry({name:c,type:`symlink`,linkname:e});continue}if(s.isFile()){let e=await o.stat(r);await new Promise((t,a)=>{let o=n(r),s=i.entry({name:c,size:e.size,mode:e.mode,mtime:e.mtime},e=>{e&&a(e)});o.on(`error`,a),o.on(`data`,e=>s.write(e)),o.on(`end`,()=>{s.end(),t()})});continue}}};(async()=>{try{await a(e),i.finalize()}catch(e){i.destroy(e)}})();let s=i,c=0,l=!1;return new ReadableStream({start(e){s.on(`data`,t=>{if(!l){if(c+=t.length,c>r){l=!0,e.error(Error(`Archive exceeds size limit (${r} bytes). Emitted=${c} bytes.`));try{s.destroy()}catch{}return}e.enqueue(new Uint8Array(t))}}),s.once(`error`,t=>{l||(l=!0,e.error(t instanceof Error?t:Error(String(t))))}),s.once(`end`,()=>{l||(l=!0,e.close())})},cancel(){try{s.destroy()}catch{}}})};var Yt=O({"../../node_modules/dotenv/package.json":((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}}})}),Xt=A(O({"../../node_modules/dotenv/lib/main.js":((e,t)=>{let n=j(`fs`),r=j(`path`),i=j(`os`),a=j(`crypto`),o=Yt().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,`
13
13
  `);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,`
14
- `),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})})(),1);const Zt=(e,t)=>e.length<=t?e:e.slice(e.length-t),Qt=(e,t)=>{if(e.length===0)return{lines:[],truncated:!1};let n=0,r=e.length;for(let i=e.length-1;i>=0;i--){let a=e[i].length;if(n+a>t&&r!==e.length)break;n+=a,r=i}return r===0?{lines:e,truncated:!1}:{lines:e.slice(r),truncated:!0}};var $t=class{multiplexer;notificationStream;decoder=new TextDecoder;encoder=new TextEncoder;processManager;createDeploymentFromTar;proxyOnly;fetchProxyRequest;constructor(e){this.createDeploymentFromTar=e.createDeploymentFromTar,this.proxyOnly=e.proxyOnly,this.fetchProxyRequest=e.fetchProxyRequest,this.multiplexer=new z({send:t=>{e.send(t)}}),this.multiplexer.onStream(e=>{this.handleStream(e)}),this.notificationStream=this.multiplexer.createStream(),this.processManager=new Nt({env:e.env,nodePty:e.nodePty}),this.processManager.onSpawn(e=>{let t=()=>{this.sendNotification({type:`process_status`,payload:{status:this.processManager.status(e.pid)}})};t(),e.terminal.onTitleChange(()=>{t()}),e.onExit(()=>{this.sendNotification({type:`process_status`,payload:{status:this.processManager.status(e.pid)}})}),e.onOutput(t=>{let n=I.getMaxPayloadSize()-1;for(let r=0;r<t.length;r+=n){let i=t.slice(r,r+n);this.sendNotification({type:`process_output`,payload:{pid:e.pid,output:i}})}})})}handleMessage(e){this.multiplexer.handleMessage(e)}handleStream(e){let t=new AbortController;e.onClose(()=>{t.abort()}),e.onData(n=>{let r=n[0],i=n.subarray(1);switch(r){case u.REQUEST:{let n=JSON.parse(this.decoder.decode(i));if(this.proxyOnly){this.sendResponse(e,{id:n.id,error:`This server is in proxy only mode.`});return}this.handleRequest(e,n,t.signal).catch(t=>{this.sendResponse(e,{id:n.id,error:t instanceof Error?t.message:String(t)})});break}case u.PROXY_INIT:{let t=f[u.PROXY_INIT].safeParse(JSON.parse(this.decoder.decode(i)));if(!t.success)throw Error(`Invalid proxy init message`);let n;n=t.data.headers.upgrade===`websocket`?this.handleProxyWebSocket(e,t.data):this.handleProxyRequest(e,t.data),n.catch(t=>{e.error(t.message)});break}}})}async handleProxyWebSocket(t,n){let r=new URL(n.url);r.protocol===`http:`?r.protocol=`ws:`:r.protocol===`https:`&&(r.protocol=`wss:`);let i=new e.default(r.toString(),n.headers[`sec-websocket-protocol`]?n.headers[`sec-websocket-protocol`]:void 0,{headers:n.headers,perMessageDeflate:!1});i.addEventListener(`open`,()=>{t.writeTyped(d.PROXY_INIT,this.encoder.encode(JSON.stringify({status_code:101,status_message:`Switching Protocols`,headers:{}})))}),i.addEventListener(`message`,e=>{t.disposed||t.writeTyped(d.PROXY_WEBSOCKET_MESSAGE,c(e.data,this.encoder))}),i.addEventListener(`close`,e=>{if(t.disposed)return;let n={code:e.code,reason:e.reason};t.writeTyped(d.PROXY_WEBSOCKET_CLOSE,this.encoder.encode(JSON.stringify(n))),t.close()}),i.addEventListener(`error`,e=>{console.log(`err`,e)}),t.onClose(()=>{i.close()}),t.onError(e=>{i.close(1011,e)}),t.onData(e=>{let n=e.subarray(1);switch(e[0]){case u.PROXY_WEBSOCKET_MESSAGE:{let e=l(n,this.decoder);i.send(e);break}case u.PROXY_WEBSOCKET_CLOSE:{let e=f[u.PROXY_WEBSOCKET_CLOSE].safeParse(JSON.parse(this.decoder.decode(n)));if(!e.success)throw Error(`Invalid proxy websocket close message`);try{i.close(e.data.code,e.data.reason)}catch(t){console.error(`Error closing websocket`,t,e.data)}break}default:t.error(`Unexpected message type: ${e[0]}`)}})}async handleProxyRequest(e,t){let n,r;if(t.method!==`GET`&&t.method!==`HEAD`&&t.method!==`OPTIONS`){let e=new TransformStream;n=e.writable.getWriter(),r=e.readable}e.onData(t=>{switch(t[0]){case u.PROXY_BODY:if(n){let e=t.subarray(1);e.length===0?n.close():n.write(e)}break;default:e.error(`Unexpected message type: ${t[0]}`)}});let i={headers:t.headers,method:t.method,body:r},a;a=this.fetchProxyRequest?await this.fetchProxyRequest(t.url,i):await fetch(t.url,i);let o={};a.headers.forEach((e,t)=>{o[t]=e});let s={headers:o,status_code:a.status,status_message:a.statusText};e.writeTyped(d.PROXY_INIT,this.encoder.encode(JSON.stringify(s)));let c=a.headers.get(`content-length`),l=c?parseInt(c):0,f=I.getMaxPayloadSize()-1;if(l>=f){if(!a.body){e.close();return}let t=a.body.getReader();try{for(;;){let{done:n,value:r}=await t.read();if(n)break;if(r){let t=0;for(;t<r.length;){let n=Math.min(f,r.length-t),i=r.subarray(t,t+n);e.writeTyped(d.PROXY_DATA,i),t+=n}}}}finally{t.releaseLock()}}else a.body&&await a.body.pipeTo(new WritableStream({write:t=>{e.writeTyped(d.PROXY_DATA,t)}}));e.close()}async handleRequest(e,t,n){let r=p[t.type].safeParse(t.payload);if(!r.success)throw Error(`Invalid request payload: ${r.error.message}`);switch(t.type){case`process_execute`:{if(t.payload.env_file){let e=await i.readFile(t.payload.env_file,`utf-8`),n=(0,Xt.parse)(e);t.payload.env={...t.payload.env,...n}}let n=await this.processManager.execute(t.payload.command,t.payload.args,{cwd:t.payload.cwd,env:t.payload.env});this.sendResponse(e,{id:t.id,payload:{pid:n.pid}});break}case`process_wait`:this.handleProcessWait(e,t,n);break;case`process_kill`:this.mustGetProcess(t.payload.pid).kill(t.payload.signal),this.sendResponse(e,{id:t.id,payload:{}});break;case`process_list`:this.sendResponse(e,{id:t.id,payload:{processes:this.processManager.list(t.payload.include_dead??!1)}});break;case`process_read_plain_output`:{let n=this.mustGetProcess(t.payload.pid),r=this.processManager.readPlainOutput(t.payload.pid,t.payload.start_line,t.payload.end_line),i=Qt(r.lines,256e3);this.sendResponse(e,{id:t.id,payload:{lines:i.lines,total_lines:r.totalLines,duration_ms:Date.now()-n.startTimeMS,exit_code:n.exitCode,exit_signal:n.exitSignal}});break}case`process_send_input`:this.mustGetProcess(t.payload.pid).sendInput(t.payload.data),this.sendResponse(e,{id:t.id,payload:{}});break;case`set_env`:this.processManager.setEnv(t.payload.env),this.sendResponse(e,{id:t.id,payload:{}});break;case`deploy_static_files`:{if(!this.createDeploymentFromTar)throw Error(`This server does not support static file deployments!`);let n=await Jt(t.payload.path),r=await this.createDeploymentFromTar(n);this.sendResponse(e,{id:t.id,payload:{deployment_id:r}});break}case`read_file`:{let n=await i.readFile(t.payload.path),r=await Et(n);if(!(!r||r?.mime===`text/plain`)){this.sendResponse(e,{id:t.id,payload:{content:n.toString(`base64`),mime_type:r?.mime,total_lines:0,lines_read:0,start_line:0}});break}let a=n.toString(`utf-8`).split(`
14
+ `),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})})(),1);const Zt=(e,t)=>e.length<=t?e:e.slice(e.length-t),Qt=(e,t)=>{if(e.length===0)return{lines:[],truncated:!1};let n=0,r=e.length;for(let i=e.length-1;i>=0;i--){let a=e[i].length;if(n+a>t&&r!==e.length)break;n+=a,r=i}return r===0?{lines:e,truncated:!1}:{lines:e.slice(r),truncated:!0}};var $t=class{multiplexer;notificationStream;decoder=new TextDecoder;encoder=new TextEncoder;processManager;createDeploymentFromTar;proxyOnly;fetchProxyRequest;constructor(e){this.createDeploymentFromTar=e.createDeploymentFromTar,this.proxyOnly=e.proxyOnly,this.fetchProxyRequest=e.fetchProxyRequest,this.multiplexer=new z({send:t=>{e.send(t)}}),this.multiplexer.onStream(e=>{this.handleStream(e)}),this.notificationStream=this.multiplexer.createStream(),this.processManager=new Nt({env:e.env,nodePty:e.nodePty}),this.processManager.onSpawn(e=>{let t=()=>{this.sendNotification({type:`process_status`,payload:{status:this.processManager.status(e.pid)}})};t(),e.terminal.onTitleChange(()=>{t()}),e.onExit(()=>{this.sendNotification({type:`process_status`,payload:{status:this.processManager.status(e.pid)}})}),e.onOutput(t=>{let n=I.getMaxPayloadSize()-1;for(let r=0;r<t.length;r+=n){let i=t.slice(r,r+n);this.sendNotification({type:`process_output`,payload:{pid:e.pid,output:i}})}})})}handleMessage(e){this.multiplexer.handleMessage(e)}handleStream(e){let t=new AbortController;e.onClose(()=>{t.abort()}),e.onData(n=>{let r=n[0],i=n.subarray(1);switch(r){case u.REQUEST:{let n=JSON.parse(this.decoder.decode(i));if(this.proxyOnly){this.sendResponse(e,{id:n.id,error:`This server is in proxy only mode.`});return}this.handleRequest(e,n,t.signal).catch(t=>{this.sendResponse(e,{id:n.id,error:t instanceof Error?t.message:String(t)})});break}case u.PROXY_INIT:{let t=f[u.PROXY_INIT].safeParse(JSON.parse(this.decoder.decode(i)));if(!t.success)throw Error(`Invalid proxy init message`);let n;n=t.data.headers.upgrade===`websocket`?this.handleProxyWebSocket(e,t.data):this.handleProxyRequest(e,t.data),n.catch(t=>{e.error(t.message)});break}}})}async handleProxyWebSocket(t,n){let r=new URL(n.url);r.protocol===`http:`?r.protocol=`ws:`:r.protocol===`https:`&&(r.protocol=`wss:`);let i=new e.default(r.toString(),n.headers[`sec-websocket-protocol`]?n.headers[`sec-websocket-protocol`]:void 0,{headers:n.headers,perMessageDeflate:!1});i.addEventListener(`open`,()=>{t.writeTyped(d.PROXY_INIT,this.encoder.encode(JSON.stringify({status_code:101,status_message:`Switching Protocols`,headers:{}})))}),i.addEventListener(`message`,e=>{t.disposed||t.writeTyped(d.PROXY_WEBSOCKET_MESSAGE,c(e.data,this.encoder))}),i.addEventListener(`close`,e=>{if(t.disposed)return;let n={code:e.code,reason:e.reason};t.writeTyped(d.PROXY_WEBSOCKET_CLOSE,this.encoder.encode(JSON.stringify(n))),t.close()}),i.addEventListener(`error`,e=>{console.log(`err`,e)}),t.onClose(()=>{i.close()}),t.onError(e=>{i.close(1011,e)}),t.onData(e=>{let n=e.subarray(1);switch(e[0]){case u.PROXY_WEBSOCKET_MESSAGE:{let e=l(n,this.decoder);i.send(e);break}case u.PROXY_WEBSOCKET_CLOSE:{let e=f[u.PROXY_WEBSOCKET_CLOSE].safeParse(JSON.parse(this.decoder.decode(n)));if(!e.success)throw Error(`Invalid proxy websocket close message`);try{i.close(e.data.code,e.data.reason)}catch(t){console.error(`Error closing websocket`,t,e.data)}break}default:t.error(`Unexpected message type: ${e[0]}`)}})}async handleProxyRequest(e,t){let n,r;if(t.method!==`GET`&&t.method!==`HEAD`&&t.method!==`OPTIONS`){let e=new TransformStream;n=e.writable.getWriter(),r=e.readable}e.onData(t=>{switch(t[0]){case u.PROXY_BODY:if(n){let e=t.subarray(1);e.length===0?n.close():n.write(e)}break;default:e.error(`Unexpected message type: ${t[0]}`)}});let i={headers:t.headers,method:t.method,body:r,redirect:`manual`},a;a=this.fetchProxyRequest?await this.fetchProxyRequest(t.url,i):await fetch(t.url,i);let o={};a.headers.forEach((e,t)=>{o[t]=e});let s={headers:o,status_code:a.status,status_message:a.statusText};e.writeTyped(d.PROXY_INIT,this.encoder.encode(JSON.stringify(s)));let c=a.headers.get(`content-length`),l=c?parseInt(c):0,f=I.getMaxPayloadSize()-1;if(l>=f){if(!a.body){e.close();return}let t=a.body.getReader();try{for(;;){let{done:n,value:r}=await t.read();if(n)break;if(r){let t=0;for(;t<r.length;){let n=Math.min(f,r.length-t),i=r.subarray(t,t+n);e.writeTyped(d.PROXY_DATA,i),t+=n}}}}finally{t.releaseLock()}}else a.body&&await a.body.pipeTo(new WritableStream({write:t=>{e.writeTyped(d.PROXY_DATA,t)}}));e.close()}async handleRequest(e,t,n){let r=p[t.type].safeParse(t.payload);if(!r.success)throw Error(`Invalid request payload: ${r.error.message}`);switch(t.type){case`process_execute`:{if(t.payload.env_file){let e=await i.readFile(t.payload.env_file,`utf-8`),n=(0,Xt.parse)(e);t.payload.env={...t.payload.env,...n}}let n=await this.processManager.execute(t.payload.command,t.payload.args,{cwd:t.payload.cwd,env:t.payload.env});this.sendResponse(e,{id:t.id,payload:{pid:n.pid}});break}case`process_wait`:this.handleProcessWait(e,t,n);break;case`process_kill`:this.mustGetProcess(t.payload.pid).kill(t.payload.signal),this.sendResponse(e,{id:t.id,payload:{}});break;case`process_list`:this.sendResponse(e,{id:t.id,payload:{processes:this.processManager.list(t.payload.include_dead??!1)}});break;case`process_read_plain_output`:{let n=this.mustGetProcess(t.payload.pid),r=this.processManager.readPlainOutput(t.payload.pid,t.payload.start_line,t.payload.end_line),i=Qt(r.lines,256e3);this.sendResponse(e,{id:t.id,payload:{lines:i.lines,total_lines:r.totalLines,duration_ms:Date.now()-n.startTimeMS,exit_code:n.exitCode,exit_signal:n.exitSignal}});break}case`process_send_input`:this.mustGetProcess(t.payload.pid).sendInput(t.payload.data),this.sendResponse(e,{id:t.id,payload:{}});break;case`set_env`:this.processManager.setEnv(t.payload.env),this.sendResponse(e,{id:t.id,payload:{}});break;case`deploy_static_files`:{if(!this.createDeploymentFromTar)throw Error(`This server does not support static file deployments!`);let n=await Jt(t.payload.path),r=await this.createDeploymentFromTar(n);this.sendResponse(e,{id:t.id,payload:{deployment_id:r}});break}case`read_file`:{let n=await i.readFile(t.payload.path),r=await Et(n);if(!(!r||r?.mime===`text/plain`)){this.sendResponse(e,{id:t.id,payload:{content:n.toString(`base64`),mime_type:r?.mime,total_lines:0,lines_read:0,start_line:0}});break}let a=n.toString(`utf-8`).split(`
15
15
  `),o=Math.max(0,(t.payload.line_start??1)-1),s=Math.min(a.length,t.payload.line_end??a.length),c=a.slice(o,s);this.sendResponse(e,{id:t.id,payload:{content:c.join(`
16
16
  `),mime_type:`text/plain`,total_lines:a.length,lines_read:c.length,start_line:o}});break}case`write_file`:t.payload.base64?await i.writeFile(t.payload.path,Buffer.from(t.payload.content,`base64`)):await i.writeFile(t.payload.path,t.payload.content),typeof t.payload.mode==`number`&&await i.chmod(t.payload.path,t.payload.mode),this.sendResponse(e,{id:t.id,payload:{}});break;case`read_directory`:{let n=await i.readdir(t.payload.path,{withFileTypes:!0});this.sendResponse(e,{id:t.id,payload:{entries:n.map(e=>({name:e.name,type:e.isDirectory()?`directory`:e.isSymbolicLink()?`symlink`:`file`}))}});break}default:throw Error(`Unknown request type: ${t.type}`)}}sendResponse(e,t){e.writeTyped(d.RESPONSE,this.encoder.encode(JSON.stringify(t)))}sendNotification(e){this.notificationStream.write(new Uint8Array([d.NOTIFICATION,...this.encoder.encode(JSON.stringify(e))]))}handleProcessWait(e,t,n){let r=t.payload,i=this.mustGetProcess(r.pid),a,o,s=!1,c,l;typeof r.timeout_ms==`number`&&(l=setTimeout(()=>{u()},r.timeout_ms));let u=()=>{if(s||(s=!0,a&&a.dispose(),o&&o.dispose(),l&&clearTimeout(l),c&&clearTimeout(c),n?.aborted))return;let i=this.processManager.status(r.pid),u=this.processManager.readPlainOutput(i.pid),d=Zt(this.processManager.readANSIOutput(i.pid),64e3),f=Qt(u.lines,256e3);this.sendResponse(e,{id:t.id,payload:{...i,ansi_output:d,plain_output:{lines:f.lines,total_lines:u.totalLines}}})};if(typeof i.exitCode==`number`||typeof i.exitSignal==`number`){u();return}a=i.onOutput(()=>{c&&clearTimeout(c),typeof r.output_idle_timeout_ms==`number`&&(c=setTimeout(()=>{u()},r.output_idle_timeout_ms))}),o=i.onExit(()=>{setTimeout(()=>{u()},10)}),n.addEventListener(`abort`,()=>{u()})}mustGetProcess(e){let t=this.processManager.getProcess(e);if(!t)throw Error(`Process ${e} not found`);return t}};export{z as Multiplexer,$t as Server};
@@ -1 +1 @@
1
- const e=require(`../chunk-iXuH7AlR.cjs`),t=require(`../build-D_HFEWKz.cjs`);exports.buildWithEsbuild=t.buildWithEsbuild,exports.defineConfig=t.defineConfig,exports.resolveConfig=t.resolveConfig,exports.setEsbuildInstance=t.setEsbuildInstance;
1
+ const e=require(`../chunk-iXuH7AlR.cjs`),t=require(`../build-BzoNpizh.cjs`);exports.buildWithEsbuild=t.buildWithEsbuild,exports.defineConfig=t.defineConfig,exports.resolveConfig=t.resolveConfig,exports.setEsbuildInstance=t.setEsbuildInstance;
@@ -1 +1 @@
1
- import{buildWithEsbuild as e,defineConfig as t,resolveConfig as n,setEsbuildInstance as r}from"../build-D_4dvv5-.js";export{e as buildWithEsbuild,t as defineConfig,n as resolveConfig,r as setEsbuildInstance};
1
+ import{buildWithEsbuild as e,defineConfig as t,resolveConfig as n,setEsbuildInstance as r}from"../build-D_L0gFGa.js";export{e as buildWithEsbuild,t as defineConfig,n as resolveConfig,r as setEsbuildInstance};
@@ -19,7 +19,7 @@ export function ${e}(options) {
19
19
  return aiOriginal.${e}(options);
20
20
  }
21
21
  `).join(``)}
22
- `,loader:`js`,resolveDir:i?.resolveDir}})}}}let s;function c(e){s=e}function l(e){return async r=>{let a=await(s??await import(`esbuild`)).context({entryPoints:[r.entry],outdir:r.outdir,bundle:!0,write:!1,logLevel:`silent`,format:`esm`,platform:`node`,target:`node22`,sourcemap:!1,mainFields:[`module`,`main`],conditions:[`import`,`module`],plugins:[{name:`blink-esm-require-to-import`,setup(e){e.onEnd(t=>{e.initialOptions.format!==`esm`||e.initialOptions.platform!==`node`||t.outputFiles?.forEach(e=>{if(e.path.endsWith(`.js`)||e.path.endsWith(`.mjs`)){let t=Buffer.from(e.contents).toString(`utf-8`),r=new Map,i=RegExp(`\\b__require\\("(node:)?(${n.builtinModules.join(`|`)})"\\)`,`gm`);t=t.replace(i,(e,t,n)=>{let i=`__import_${n.toUpperCase().replace(/-/g,`_`)}`,a=`node:${n}`;return r.set(i,a),i}),r.size>0&&(t=Array.from(r.entries()).map(([e,t])=>`import ${e} from "${t}";`).join(`
22
+ `,loader:`js`,resolveDir:i?.resolveDir}})}}}let s;function c(e){s=e}function l(e){return async r=>{let a=await(s??await import(`esbuild`)).context({entryPoints:[r.entry],outdir:r.outdir,bundle:!0,write:!1,logLevel:`silent`,format:`esm`,platform:`node`,target:`node22`,sourcemap:!1,mainFields:[`module`,`main`],conditions:[`import`,`module`],plugins:[{name:`blink-esm-require-to-import`,setup(e){e.onEnd(t=>{e.initialOptions.format!==`esm`||e.initialOptions.platform!==`node`||t.outputFiles?.forEach(e=>{if(e.path.endsWith(`.js`)||e.path.endsWith(`.mjs`)){let t=Buffer.from(e.contents).toString(`utf-8`),r=new Map,i=RegExp(`\\b__require\\("(node:)?(${n.builtinModules.join(`|`)})(/[^"]+)?"\\)`,`gm`);t=t.replace(i,(e,t,n,i=``)=>{let a=n+i,o=`__import_${a.toUpperCase().replace(/[/-]/g,`_`)}`,s=`node:${a}`;return r.set(o,s),o}),r.size>0&&(t=Array.from(r.entries()).map(([e,t])=>`import ${e} from "${t}";`).join(`
23
23
  `)+`
24
24
 
25
25
  `+t),e.contents=Buffer.from(t,`utf-8`)}})})}},{name:`blink-dev-server`,setup(e){let n;e.onStart(()=>{r.onStart(),n=performance.now()}),e.onEnd(async e=>{await(0,i.rm)(r.outdir,{recursive:!0,force:!0}),await(0,i.mkdir)(r.outdir,{recursive:!0});let o=e.outputFiles?.map(e=>({path:e.path,contents:e.contents}))??[];o.push({path:t.default.resolve(r.outdir,`package.json`),contents:Buffer.from(JSON.stringify({type:`module`},null,2),`utf-8`)});for(let e of o)await(0,i.writeFile)(e.path,e.contents);e.errors.length>0?r.onResult({error:{message:e.errors.map(e=>`${e.text} (${e.location?.file})`).join(`
@@ -19,7 +19,7 @@ export function ${e}(options) {
19
19
  return aiOriginal.${e}(options);
20
20
  }
21
21
  `).join(``)}
22
- `,loader:`js`,resolveDir:i?.resolveDir}})}}}let l;function u(e){l=e}function d(e){return async r=>{let s=await(l??await import(`esbuild`)).context({entryPoints:[r.entry],outdir:r.outdir,bundle:!0,write:!1,logLevel:`silent`,format:`esm`,platform:`node`,target:`node22`,sourcemap:!1,mainFields:[`module`,`main`],conditions:[`import`,`module`],plugins:[{name:`blink-esm-require-to-import`,setup(e){e.onEnd(t=>{e.initialOptions.format!==`esm`||e.initialOptions.platform!==`node`||t.outputFiles?.forEach(e=>{if(e.path.endsWith(`.js`)||e.path.endsWith(`.mjs`)){let t=Buffer.from(e.contents).toString(`utf-8`),r=new Map,i=RegExp(`\\b__require\\("(node:)?(${n.join(`|`)})"\\)`,`gm`);t=t.replace(i,(e,t,n)=>{let i=`__import_${n.toUpperCase().replace(/-/g,`_`)}`,a=`node:${n}`;return r.set(i,a),i}),r.size>0&&(t=Array.from(r.entries()).map(([e,t])=>`import ${e} from "${t}";`).join(`
22
+ `,loader:`js`,resolveDir:i?.resolveDir}})}}}let l;function u(e){l=e}function d(e){return async r=>{let s=await(l??await import(`esbuild`)).context({entryPoints:[r.entry],outdir:r.outdir,bundle:!0,write:!1,logLevel:`silent`,format:`esm`,platform:`node`,target:`node22`,sourcemap:!1,mainFields:[`module`,`main`],conditions:[`import`,`module`],plugins:[{name:`blink-esm-require-to-import`,setup(e){e.onEnd(t=>{e.initialOptions.format!==`esm`||e.initialOptions.platform!==`node`||t.outputFiles?.forEach(e=>{if(e.path.endsWith(`.js`)||e.path.endsWith(`.mjs`)){let t=Buffer.from(e.contents).toString(`utf-8`),r=new Map,i=RegExp(`\\b__require\\("(node:)?(${n.join(`|`)})(/[^"]+)?"\\)`,`gm`);t=t.replace(i,(e,t,n,i=``)=>{let a=n+i,o=`__import_${a.toUpperCase().replace(/[/-]/g,`_`)}`,s=`node:${a}`;return r.set(o,s),o}),r.size>0&&(t=Array.from(r.entries()).map(([e,t])=>`import ${e} from "${t}";`).join(`
23
23
  `)+`
24
24
 
25
25
  `+t),e.contents=Buffer.from(t,`utf-8`)}})})}},{name:`blink-dev-server`,setup(e){let n;e.onStart(()=>{r.onStart(),n=performance.now()}),e.onEnd(async e=>{await a(r.outdir,{recursive:!0,force:!0}),await i(r.outdir,{recursive:!0});let c=e.outputFiles?.map(e=>({path:e.path,contents:e.contents}))??[];c.push({path:t.resolve(r.outdir,`package.json`),contents:Buffer.from(JSON.stringify({type:`module`},null,2),`utf-8`)});for(let e of c)await o(e.path,e.contents);e.errors.length>0?r.onResult({error:{message:e.errors.map(e=>`${e.text} (${e.location?.file})`).join(`
@@ -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.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}
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-BzoNpizh.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]===`
@@ -145,7 +145,7 @@ ${Ea}${t.trimStart()}`),n=3+(0,o.stripVTControlCharacters)(t.trimStart()).length
145
145
  `));let r=e.pax;if(r)for(let e in r)n+=y(` `+e+`=`+r[e]+`
146
146
  `);return t.from(n)},e.decodePax=function(e){let n={};for(;e.length;){let r=0;for(;r<e.length&&e[r]!==32;)r++;let i=parseInt(t.toString(e.subarray(0,r)),10);if(!i)return n;let a=t.toString(e.subarray(r+1,i-1)),o=a.indexOf(`=`);if(o===-1)return n;n[a.slice(0,o)]=a.slice(o+1),e=e.subarray(i)}return n},e.encode=function(e){let i=t.alloc(512),a=e.name,o=``;if(e.typeflag===5&&a[a.length-1]!==`/`&&(a+=`/`),t.byteLength(a)!==a.length)return null;for(;t.byteLength(a)>100;){let e=a.indexOf(`/`);if(e===-1)return null;o+=o?`/`+a.slice(0,e):a.slice(0,e),a=a.slice(e+1)}return t.byteLength(a)>100||t.byteLength(o)>155||e.linkname&&t.byteLength(e.linkname)>100?null:(t.write(i,a),t.write(i,p(e.mode&4095,6),100),t.write(i,p(e.uid,6),108),t.write(i,p(e.gid,6),116),h(e.size,i,124),t.write(i,p(e.mtime.getTime()/1e3|0,11),136),i[156]=48+u(e.type),e.linkname&&t.write(i,e.linkname,157),t.copy(n,i,257),t.copy(r,i,263),e.uname&&t.write(i,e.uname,265),e.gname&&t.write(i,e.gname,297),t.write(i,p(e.devmajor||0,6),329),t.write(i,p(e.devminor||0,6),337),o&&t.write(i,o,345),t.write(i,p(f(i),6),148),i)},e.decode=function(e,t,n){let r=e[156]===0?0:e[156]-48,i=v(e,0,100,t),a=_(e,100,8),c=_(e,108,8),u=_(e,116,8),d=_(e,124,12),p=_(e,136,12),m=l(r),h=e[157]===0?null:v(e,157,100,t),g=v(e,265,32),y=v(e,297,32),b=_(e,329,8),x=_(e,337,8),S=f(e);if(S===256)return null;if(S!==_(e,148,8))throw Error(`Invalid tar header. Maybe the tar is corrupted or it needs to be gunzipped?`);if(o(e))e[345]&&(i=v(e,345,155,t)+`/`+i);else if(!s(e)&&!n)throw Error(`Invalid tar header: unknown format.`);return r===0&&i&&i[i.length-1]===`/`&&(r=5),{name:i,mode:a,uid:c,gid:u,size:d,mtime:new Date(1e3*p),type:m,linkname:h,uname:g,gname:y,devmajor:b,devminor:x,pax:null}};function o(e){return t.equals(n,e.subarray(257,263))}function s(e){return t.equals(i,e.subarray(257,263))&&t.equals(a,e.subarray(263,265))}function c(e,t,n){return typeof e==`number`?(e=~~e,e>=t?t:e>=0||(e+=t,e>=0)?e:0):n}function l(e){switch(e){case 0:return`file`;case 1:return`link`;case 2:return`symlink`;case 3:return`character-device`;case 4:return`block-device`;case 5:return`directory`;case 6:return`fifo`;case 7:return`contiguous-file`;case 72:return`pax-header`;case 55:return`pax-global-header`;case 27:return`gnu-long-link-path`;case 28:case 30:return`gnu-long-path`}return null}function u(e){switch(e){case`file`:return 0;case`link`:return 1;case`symlink`:return 2;case`character-device`:return 3;case`block-device`:return 4;case`directory`:return 5;case`fifo`:return 6;case`contiguous-file`:return 7;case`pax-header`:return 72}return 0}function d(e,t,n,r){for(;n<r;n++)if(e[n]===t)return n;return r}function f(e){let t=256;for(let n=0;n<148;n++)t+=e[n];for(let n=156;n<512;n++)t+=e[n];return t}function p(e,t){return e=e.toString(8),e.length>t?`7777777777777777777`.slice(0,t)+` `:`0000000000000000000`.slice(0,t-e.length)+e+` `}function m(e,t,n){t[n]=128;for(let r=11;r>0;r--)t[n+r]=e&255,e=Math.floor(e/256)}function h(e,n,r){e.toString(8).length>11?m(e,n,r):t.write(n,p(e,11),r)}function g(e){let t;if(e[0]===128)t=!0;else if(e[0]===255)t=!1;else return null;let n=[],r;for(r=e.length-1;r>0;r--){let i=e[r];t?n.push(i):n.push(255-i)}let i=0,a=n.length;for(r=0;r<a;r++)i+=n[r]*256**r;return t?i:-1*i}function _(e,n,r){if(e=e.subarray(n,n+r),n=0,e[n]&128)return g(e);{for(;n<e.length&&e[n]===32;)n++;let r=c(d(e,32,n,e.length),e.length,e.length);for(;n<r&&e[n]===0;)n++;return r===n?0:parseInt(t.toString(e.subarray(n,r)),8)}}function v(e,n,r,i){return t.toString(e.subarray(n,d(e,0,n,n+r)),i)}function y(e){let n=t.byteLength(e),r=Math.floor(Math.log(n)/Math.log(10))+1;return n+r>=10**r&&r++,n+r+e}})}),sl=X({"../../node_modules/tar-stream/extract.js":((e,t)=>{let{Writable:n,Readable:r,getStreamError:i}=al(),a=el(),o=tl(),s=ol(),c=o.alloc(0);var l=class{constructor(){this.buffered=0,this.shifted=0,this.queue=new a,this._offset=0}push(e){this.buffered+=e.byteLength,this.queue.push(e)}shiftFirst(e){return this._buffered===0?null:this._next(e)}shift(e){if(e>this.buffered)return null;if(e===0)return c;let t=this._next(e);if(e===t.byteLength)return t;let n=[t];for(;(e-=t.byteLength)>0;)t=this._next(e),n.push(t);return o.concat(n)}_next(e){let t=this.queue.peek(),n=t.byteLength-this._offset;if(e>=n){let e=this._offset?t.subarray(this._offset,t.byteLength):t;return this.queue.shift(),this._offset=0,this.buffered-=n,this.shifted+=n,e}return this.buffered-=e,this.shifted+=e,t.subarray(this._offset,this._offset+=e)}},u=class extends r{constructor(e,t,n){super(),this.header=t,this.offset=n,this._parent=e}_read(e){this.header.size===0&&this.push(null),this._parent._stream===this&&this._parent._update(),e(null)}_predestroy(){this._parent.destroy(i(this))}_detach(){this._parent._stream===this&&(this._parent._stream=null,this._parent._missing=p(this.header.size),this._parent._update())}_destroy(e){this._detach(),e(null)}},d=class extends n{constructor(e){super(e),e||={},this._buffer=new l,this._offset=0,this._header=null,this._stream=null,this._missing=0,this._longHeader=!1,this._callback=f,this._locked=!1,this._finished=!1,this._pax=null,this._paxGlobal=null,this._gnuLongPath=null,this._gnuLongLinkPath=null,this._filenameEncoding=e.filenameEncoding||`utf-8`,this._allowUnknownFormat=!!e.allowUnknownFormat,this._unlockBound=this._unlock.bind(this)}_unlock(e){if(this._locked=!1,e){this.destroy(e),this._continueWrite(e);return}this._update()}_consumeHeader(){if(this._locked)return!1;this._offset=this._buffer.shifted;try{this._header=s.decode(this._buffer.shift(512),this._filenameEncoding,this._allowUnknownFormat)}catch(e){return this._continueWrite(e),!1}if(!this._header)return!0;switch(this._header.type){case`gnu-long-path`:case`gnu-long-link-path`:case`pax-global-header`:case`pax-header`:return this._longHeader=!0,this._missing=this._header.size,!0}return this._locked=!0,this._applyLongHeaders(),this._header.size===0||this._header.type===`directory`?(this.emit(`entry`,this._header,this._createStream(),this._unlockBound),!0):(this._stream=this._createStream(),this._missing=this._header.size,this.emit(`entry`,this._header,this._stream,this._unlockBound),!0)}_applyLongHeaders(){this._gnuLongPath&&=(this._header.name=this._gnuLongPath,null),this._gnuLongLinkPath&&=(this._header.linkname=this._gnuLongLinkPath,null),this._pax&&=(this._pax.path&&(this._header.name=this._pax.path),this._pax.linkpath&&(this._header.linkname=this._pax.linkpath),this._pax.size&&(this._header.size=parseInt(this._pax.size,10)),this._header.pax=this._pax,null)}_decodeLongHeader(e){switch(this._header.type){case`gnu-long-path`:this._gnuLongPath=s.decodeLongPath(e,this._filenameEncoding);break;case`gnu-long-link-path`:this._gnuLongLinkPath=s.decodeLongPath(e,this._filenameEncoding);break;case`pax-global-header`:this._paxGlobal=s.decodePax(e);break;case`pax-header`:this._pax=this._paxGlobal===null?s.decodePax(e):Object.assign({},this._paxGlobal,s.decodePax(e));break}}_consumeLongHeader(){this._longHeader=!1,this._missing=p(this._header.size);let e=this._buffer.shift(this._header.size);try{this._decodeLongHeader(e)}catch(e){return this._continueWrite(e),!1}return!0}_consumeStream(){let e=this._buffer.shiftFirst(this._missing);if(e===null)return!1;this._missing-=e.byteLength;let t=this._stream.push(e);return this._missing===0?(this._stream.push(null),t&&this._stream._detach(),t&&this._locked===!1):t}_createStream(){return new u(this,this._header,this._offset)}_update(){for(;this._buffer.buffered>0&&!this.destroying;){if(this._missing>0){if(this._stream!==null){if(this._consumeStream()===!1)return;continue}if(this._longHeader===!0){if(this._missing>this._buffer.buffered)break;if(this._consumeLongHeader()===!1)return!1;continue}let e=this._buffer.shiftFirst(this._missing);e!==null&&(this._missing-=e.byteLength);continue}if(this._buffer.buffered<512)break;if(this._stream!==null||this._consumeHeader()===!1)return}this._continueWrite(null)}_continueWrite(e){let t=this._callback;this._callback=f,t(e)}_write(e,t){this._callback=t,this._buffer.push(e),this._update()}_final(e){this._finished=this._missing===0&&this._buffer.buffered===0,e(this._finished?null:Error(`Unexpected end of data`))}_predestroy(){this._continueWrite(null)}_destroy(e){this._stream&&this._stream.destroy(i(this)),e(null)}[Symbol.asyncIterator](){let e=null,t=null,n=null,r=null,i=null,a=this;return this.on(`entry`,c),this.on(`error`,t=>{e=t}),this.on(`close`,l),{[Symbol.asyncIterator](){return this},next(){return new Promise(s)},return(){return u(null)},throw(e){return u(e)}};function o(e){if(!i)return;let t=i;i=null,t(e)}function s(i,s){if(e)return s(e);if(r){i({value:r,done:!1}),r=null;return}t=i,n=s,o(null),a._finished&&t&&(t({value:void 0,done:!0}),t=n=null)}function c(e,a,o){i=o,a.on(`error`,f),t?(t({value:a,done:!1}),t=n=null):r=a}function l(){o(e),t&&=(e?n(e):t({value:void 0,done:!0}),n=null)}function u(e){return a.destroy(e),o(e),new Promise((t,n)=>{if(a.destroyed)return t({value:void 0,done:!0});a.once(`close`,function(){e?n(e):t({value:void 0,done:!0})})})}}};t.exports=function(e){return new d(e)};function f(){}function p(e){return e&=511,e&&512-e}})}),cl=X({"../../node_modules/tar-stream/constants.js":((e,t)=>{let n={S_IFMT:61440,S_IFDIR:16384,S_IFCHR:8192,S_IFBLK:24576,S_IFIFO:4096,S_IFLNK:40960};try{t.exports=Go(`fs`).constants||n}catch{t.exports=n}})}),ll=X({"../../node_modules/tar-stream/pack.js":((e,t)=>{let{Readable:n,Writable:r,getStreamError:i}=al(),a=tl(),o=cl(),s=ol(),c=a.alloc(1024);var l=class extends r{constructor(e,t,n){super({mapWritable:m,eagerOpen:!0}),this.written=0,this.header=t,this._callback=n,this._linkname=null,this._isLinkname=t.type===`symlink`&&!t.linkname,this._isVoid=t.type!==`file`&&t.type!==`contiguous-file`,this._finished=!1,this._pack=e,this._openCallback=null,this._pack._stream===null?this._pack._stream=this:this._pack._pending.push(this)}_open(e){this._openCallback=e,this._pack._stream===this&&this._continueOpen()}_continuePack(e){if(this._callback===null)return;let t=this._callback;this._callback=null,t(e)}_continueOpen(){this._pack._stream===null&&(this._pack._stream=this);let e=this._openCallback;if(this._openCallback=null,e!==null){if(this._pack.destroying)return e(Error(`pack stream destroyed`));if(this._pack._finalized)return e(Error(`pack stream is already finalized`));this._pack._stream=this,this._isLinkname||this._pack._encode(this.header),this._isVoid&&(this._finish(),this._continuePack(null)),e(null)}}_write(e,t){if(this._isLinkname)return this._linkname=this._linkname?a.concat([this._linkname,e]):e,t(null);if(this._isVoid)return e.byteLength>0?t(Error(`No body allowed for this entry`)):t();if(this.written+=e.byteLength,this._pack.push(e))return t();this._pack._drain=t}_finish(){this._finished||(this._finished=!0,this._isLinkname&&(this.header.linkname=this._linkname?a.toString(this._linkname,`utf-8`):``,this._pack._encode(this.header)),p(this._pack,this.header.size),this._pack._done(this))}_final(e){if(this.written!==this.header.size)return e(Error(`Size mismatch`));this._finish(),e(null)}_getError(){return i(this)||Error(`tar entry destroyed`)}_predestroy(){this._pack.destroy(this._getError())}_destroy(e){this._pack._done(this),this._continuePack(this._finished?null:this._getError()),e()}},u=class extends n{constructor(e){super(e),this._drain=f,this._finalized=!1,this._finalizing=!1,this._pending=[],this._stream=null}entry(e,t,n){if(this._finalized||this.destroying)throw Error(`already finalized or destroyed`);typeof t==`function`&&(n=t,t=null),n||=f,(!e.size||e.type===`symlink`)&&(e.size=0),e.type||=d(e.mode),e.mode||=e.type===`directory`?493:420,e.uid||=0,e.gid||=0,e.mtime||=new Date,typeof t==`string`&&(t=a.from(t));let r=new l(this,e,n);return a.isBuffer(t)?(e.size=t.byteLength,r.write(t),r.end(),r):(r._isVoid,r)}finalize(){if(this._stream||this._pending.length>0){this._finalizing=!0;return}this._finalized||(this._finalized=!0,this.push(c),this.push(null))}_done(e){e===this._stream&&(this._stream=null,this._finalizing&&this.finalize(),this._pending.length&&this._pending.shift()._continueOpen())}_encode(e){if(!e.pax){let t=s.encode(e);if(t){this.push(t);return}}this._encodePax(e)}_encodePax(e){let t=s.encodePax({name:e.name,linkname:e.linkname,pax:e.pax}),n={name:`PaxHeader`,mode:e.mode,uid:e.uid,gid:e.gid,size:t.byteLength,mtime:e.mtime,type:`pax-header`,linkname:e.linkname&&`PaxHeader`,uname:e.uname,gname:e.gname,devmajor:e.devmajor,devminor:e.devminor};this.push(s.encode(n)),this.push(t),p(this,t.byteLength),n.size=e.size,n.type=e.type,this.push(s.encode(n))}_doDrain(){let e=this._drain;this._drain=f,e()}_predestroy(){let e=i(this);for(this._stream&&this._stream.destroy(e);this._pending.length;){let t=this._pending.shift();t.destroy(e),t._continueOpen()}this._doDrain()}_read(e){this._doDrain(),e()}};t.exports=function(e){return new u(e)};function d(e){switch(e&o.S_IFMT){case o.S_IFBLK:return`block-device`;case o.S_IFCHR:return`character-device`;case o.S_IFDIR:return`directory`;case o.S_IFIFO:return`fifo`;case o.S_IFLNK:return`symlink`}return`file`}function f(){}function p(e,t){t&=511,t&&e.push(c.subarray(0,512-t))}function m(e){return a.isBuffer(e)?e:a.from(e)}})}),ul=Wo(X({"../../node_modules/tar-stream/index.js":(e=>{e.extract=sl(),e.pack=ll()})})(),1);const dl=async(e,t)=>{let{maxBytes:n=50*1024*1024}=t??{};if(!(await b.stat(e)).isDirectory())throw Error(`Path is not a directory: ${e}`);let r=ul.pack(),a=async(e,t=``)=>{let n=await b.readdir(e,{withFileTypes:!0});for(let o of n){let n=`${e}/${o.name}`,s=t?`${t}/${o.name}`:o.name;if(o.isDirectory()){r.entry({name:`${s}/`,type:`directory`}),await a(n,s);continue}if(o.isSymbolicLink?.()){let e=await b.readlink(n);r.entry({name:s,type:`symlink`,linkname:e});continue}if(o.isFile()){let e=await b.stat(n);await new Promise((t,a)=>{let o=(0,i.createReadStream)(n),c=r.entry({name:s,size:e.size,mode:e.mode,mtime:e.mtime},e=>{e&&a(e)});o.on(`error`,a),o.on(`data`,e=>c.write(e)),o.on(`end`,()=>{c.end(),t()})});continue}}};(async()=>{try{await a(e),r.finalize()}catch(e){r.destroy(e)}})();let o=r,s=0,c=!1;return new ReadableStream({start(e){o.on(`data`,t=>{if(!c){if(s+=t.length,s>n){c=!0,e.error(Error(`Archive exceeds size limit (${n} bytes). Emitted=${s} bytes.`));try{o.destroy()}catch{}return}e.enqueue(new Uint8Array(t))}}),o.once(`error`,t=>{c||(c=!0,e.error(t instanceof Error?t:Error(String(t))))}),o.once(`end`,()=>{c||(c=!0,e.close())})},cancel(){try{o.destroy()}catch{}}})};var fl=X({"../../node_modules/dotenv/package.json":((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}}})}),pl=Wo(X({"../../node_modules/dotenv/lib/main.js":((e,t)=>{let n=Go(`fs`),r=Go(`path`),i=Go(`os`),a=Go(`crypto`),o=fl().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,`
147
147
  `);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,`
148
- `),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})})(),1);const ml=(e,t)=>e.length<=t?e:e.slice(e.length-t),hl=(e,t)=>{if(e.length===0)return{lines:[],truncated:!1};let n=0,r=e.length;for(let i=e.length-1;i>=0;i--){let a=e[i].length;if(n+a>t&&r!==e.length)break;n+=a,r=i}return r===0?{lines:e,truncated:!1}:{lines:e.slice(r),truncated:!0}};var gl=class{multiplexer;notificationStream;decoder=new TextDecoder;encoder=new TextEncoder;processManager;createDeploymentFromTar;proxyOnly;fetchProxyRequest;constructor(e){this.createDeploymentFromTar=e.createDeploymentFromTar,this.proxyOnly=e.proxyOnly,this.fetchProxyRequest=e.fetchProxyRequest,this.multiplexer=new $o({send:t=>{e.send(t)}}),this.multiplexer.onStream(e=>{this.handleStream(e)}),this.notificationStream=this.multiplexer.createStream(),this.processManager=new Xc({env:e.env,nodePty:e.nodePty}),this.processManager.onSpawn(e=>{let t=()=>{this.sendNotification({type:`process_status`,payload:{status:this.processManager.status(e.pid)}})};t(),e.terminal.onTitleChange(()=>{t()}),e.onExit(()=>{this.sendNotification({type:`process_status`,payload:{status:this.processManager.status(e.pid)}})}),e.onOutput(t=>{let n=Xo.getMaxPayloadSize()-1;for(let r=0;r<t.length;r+=n){let i=t.slice(r,r+n);this.sendNotification({type:`process_output`,payload:{pid:e.pid,output:i}})}})})}handleMessage(e){this.multiplexer.handleMessage(e)}handleStream(e){let t=new AbortController;e.onClose(()=>{t.abort()}),e.onData(n=>{let r=n[0],i=n.subarray(1);switch(r){case Qa.REQUEST:{let n=JSON.parse(this.decoder.decode(i));if(this.proxyOnly){this.sendResponse(e,{id:n.id,error:`This server is in proxy only mode.`});return}this.handleRequest(e,n,t.signal).catch(t=>{this.sendResponse(e,{id:n.id,error:t instanceof Error?t.message:String(t)})});break}case Qa.PROXY_INIT:{let t=eo[Qa.PROXY_INIT].safeParse(JSON.parse(this.decoder.decode(i)));if(!t.success)throw Error(`Invalid proxy init message`);let n;n=t.data.headers.upgrade===`websocket`?this.handleProxyWebSocket(e,t.data):this.handleProxyRequest(e,t.data),n.catch(t=>{e.error(t.message)});break}}})}async handleProxyWebSocket(e,t){let n=new URL(t.url);n.protocol===`http:`?n.protocol=`ws:`:n.protocol===`https:`&&(n.protocol=`wss:`);let r=new Fo.default(n.toString(),t.headers[`sec-websocket-protocol`]?t.headers[`sec-websocket-protocol`]:void 0,{headers:t.headers,perMessageDeflate:!1});r.addEventListener(`open`,()=>{e.writeTyped($a.PROXY_INIT,this.encoder.encode(JSON.stringify({status_code:101,status_message:`Switching Protocols`,headers:{}})))}),r.addEventListener(`message`,t=>{e.disposed||e.writeTyped($a.PROXY_WEBSOCKET_MESSAGE,Xa(t.data,this.encoder))}),r.addEventListener(`close`,t=>{if(e.disposed)return;let n={code:t.code,reason:t.reason};e.writeTyped($a.PROXY_WEBSOCKET_CLOSE,this.encoder.encode(JSON.stringify(n))),e.close()}),r.addEventListener(`error`,e=>{console.log(`err`,e)}),e.onClose(()=>{r.close()}),e.onError(e=>{r.close(1011,e)}),e.onData(t=>{let n=t.subarray(1);switch(t[0]){case Qa.PROXY_WEBSOCKET_MESSAGE:{let e=Za(n,this.decoder);r.send(e);break}case Qa.PROXY_WEBSOCKET_CLOSE:{let e=eo[Qa.PROXY_WEBSOCKET_CLOSE].safeParse(JSON.parse(this.decoder.decode(n)));if(!e.success)throw Error(`Invalid proxy websocket close message`);try{r.close(e.data.code,e.data.reason)}catch(t){console.error(`Error closing websocket`,t,e.data)}break}default:e.error(`Unexpected message type: ${t[0]}`)}})}async handleProxyRequest(e,t){let n,r;if(t.method!==`GET`&&t.method!==`HEAD`&&t.method!==`OPTIONS`){let e=new TransformStream;n=e.writable.getWriter(),r=e.readable}e.onData(t=>{switch(t[0]){case Qa.PROXY_BODY:if(n){let e=t.subarray(1);e.length===0?n.close():n.write(e)}break;default:e.error(`Unexpected message type: ${t[0]}`)}});let i={headers:t.headers,method:t.method,body:r},a;a=this.fetchProxyRequest?await this.fetchProxyRequest(t.url,i):await fetch(t.url,i);let o={};a.headers.forEach((e,t)=>{o[t]=e});let s={headers:o,status_code:a.status,status_message:a.statusText};e.writeTyped($a.PROXY_INIT,this.encoder.encode(JSON.stringify(s)));let c=a.headers.get(`content-length`),l=c?parseInt(c):0,u=Xo.getMaxPayloadSize()-1;if(l>=u){if(!a.body){e.close();return}let t=a.body.getReader();try{for(;;){let{done:n,value:r}=await t.read();if(n)break;if(r){let t=0;for(;t<r.length;){let n=Math.min(u,r.length-t),i=r.subarray(t,t+n);e.writeTyped($a.PROXY_DATA,i),t+=n}}}}finally{t.releaseLock()}}else a.body&&await a.body.pipeTo(new WritableStream({write:t=>{e.writeTyped($a.PROXY_DATA,t)}}));e.close()}async handleRequest(e,t,n){let r=ro[t.type].safeParse(t.payload);if(!r.success)throw Error(`Invalid request payload: ${r.error.message}`);switch(t.type){case`process_execute`:{if(t.payload.env_file){let e=await p.readFile(t.payload.env_file,`utf-8`),n=(0,pl.parse)(e);t.payload.env={...t.payload.env,...n}}let n=await this.processManager.execute(t.payload.command,t.payload.args,{cwd:t.payload.cwd,env:t.payload.env});this.sendResponse(e,{id:t.id,payload:{pid:n.pid}});break}case`process_wait`:this.handleProcessWait(e,t,n);break;case`process_kill`:this.mustGetProcess(t.payload.pid).kill(t.payload.signal),this.sendResponse(e,{id:t.id,payload:{}});break;case`process_list`:this.sendResponse(e,{id:t.id,payload:{processes:this.processManager.list(t.payload.include_dead??!1)}});break;case`process_read_plain_output`:{let n=this.mustGetProcess(t.payload.pid),r=this.processManager.readPlainOutput(t.payload.pid,t.payload.start_line,t.payload.end_line),i=hl(r.lines,256e3);this.sendResponse(e,{id:t.id,payload:{lines:i.lines,total_lines:r.totalLines,duration_ms:Date.now()-n.startTimeMS,exit_code:n.exitCode,exit_signal:n.exitSignal}});break}case`process_send_input`:this.mustGetProcess(t.payload.pid).sendInput(t.payload.data),this.sendResponse(e,{id:t.id,payload:{}});break;case`set_env`:this.processManager.setEnv(t.payload.env),this.sendResponse(e,{id:t.id,payload:{}});break;case`deploy_static_files`:{if(!this.createDeploymentFromTar)throw Error(`This server does not support static file deployments!`);let n=await dl(t.payload.path),r=await this.createDeploymentFromTar(n);this.sendResponse(e,{id:t.id,payload:{deployment_id:r}});break}case`read_file`:{let n=await p.readFile(t.payload.path),r=await Hc(n);if(!(!r||r?.mime===`text/plain`)){this.sendResponse(e,{id:t.id,payload:{content:n.toString(`base64`),mime_type:r?.mime,total_lines:0,lines_read:0,start_line:0}});break}let i=n.toString(`utf-8`).split(`
148
+ `),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})})(),1);const ml=(e,t)=>e.length<=t?e:e.slice(e.length-t),hl=(e,t)=>{if(e.length===0)return{lines:[],truncated:!1};let n=0,r=e.length;for(let i=e.length-1;i>=0;i--){let a=e[i].length;if(n+a>t&&r!==e.length)break;n+=a,r=i}return r===0?{lines:e,truncated:!1}:{lines:e.slice(r),truncated:!0}};var gl=class{multiplexer;notificationStream;decoder=new TextDecoder;encoder=new TextEncoder;processManager;createDeploymentFromTar;proxyOnly;fetchProxyRequest;constructor(e){this.createDeploymentFromTar=e.createDeploymentFromTar,this.proxyOnly=e.proxyOnly,this.fetchProxyRequest=e.fetchProxyRequest,this.multiplexer=new $o({send:t=>{e.send(t)}}),this.multiplexer.onStream(e=>{this.handleStream(e)}),this.notificationStream=this.multiplexer.createStream(),this.processManager=new Xc({env:e.env,nodePty:e.nodePty}),this.processManager.onSpawn(e=>{let t=()=>{this.sendNotification({type:`process_status`,payload:{status:this.processManager.status(e.pid)}})};t(),e.terminal.onTitleChange(()=>{t()}),e.onExit(()=>{this.sendNotification({type:`process_status`,payload:{status:this.processManager.status(e.pid)}})}),e.onOutput(t=>{let n=Xo.getMaxPayloadSize()-1;for(let r=0;r<t.length;r+=n){let i=t.slice(r,r+n);this.sendNotification({type:`process_output`,payload:{pid:e.pid,output:i}})}})})}handleMessage(e){this.multiplexer.handleMessage(e)}handleStream(e){let t=new AbortController;e.onClose(()=>{t.abort()}),e.onData(n=>{let r=n[0],i=n.subarray(1);switch(r){case Qa.REQUEST:{let n=JSON.parse(this.decoder.decode(i));if(this.proxyOnly){this.sendResponse(e,{id:n.id,error:`This server is in proxy only mode.`});return}this.handleRequest(e,n,t.signal).catch(t=>{this.sendResponse(e,{id:n.id,error:t instanceof Error?t.message:String(t)})});break}case Qa.PROXY_INIT:{let t=eo[Qa.PROXY_INIT].safeParse(JSON.parse(this.decoder.decode(i)));if(!t.success)throw Error(`Invalid proxy init message`);let n;n=t.data.headers.upgrade===`websocket`?this.handleProxyWebSocket(e,t.data):this.handleProxyRequest(e,t.data),n.catch(t=>{e.error(t.message)});break}}})}async handleProxyWebSocket(e,t){let n=new URL(t.url);n.protocol===`http:`?n.protocol=`ws:`:n.protocol===`https:`&&(n.protocol=`wss:`);let r=new Fo.default(n.toString(),t.headers[`sec-websocket-protocol`]?t.headers[`sec-websocket-protocol`]:void 0,{headers:t.headers,perMessageDeflate:!1});r.addEventListener(`open`,()=>{e.writeTyped($a.PROXY_INIT,this.encoder.encode(JSON.stringify({status_code:101,status_message:`Switching Protocols`,headers:{}})))}),r.addEventListener(`message`,t=>{e.disposed||e.writeTyped($a.PROXY_WEBSOCKET_MESSAGE,Xa(t.data,this.encoder))}),r.addEventListener(`close`,t=>{if(e.disposed)return;let n={code:t.code,reason:t.reason};e.writeTyped($a.PROXY_WEBSOCKET_CLOSE,this.encoder.encode(JSON.stringify(n))),e.close()}),r.addEventListener(`error`,e=>{console.log(`err`,e)}),e.onClose(()=>{r.close()}),e.onError(e=>{r.close(1011,e)}),e.onData(t=>{let n=t.subarray(1);switch(t[0]){case Qa.PROXY_WEBSOCKET_MESSAGE:{let e=Za(n,this.decoder);r.send(e);break}case Qa.PROXY_WEBSOCKET_CLOSE:{let e=eo[Qa.PROXY_WEBSOCKET_CLOSE].safeParse(JSON.parse(this.decoder.decode(n)));if(!e.success)throw Error(`Invalid proxy websocket close message`);try{r.close(e.data.code,e.data.reason)}catch(t){console.error(`Error closing websocket`,t,e.data)}break}default:e.error(`Unexpected message type: ${t[0]}`)}})}async handleProxyRequest(e,t){let n,r;if(t.method!==`GET`&&t.method!==`HEAD`&&t.method!==`OPTIONS`){let e=new TransformStream;n=e.writable.getWriter(),r=e.readable}e.onData(t=>{switch(t[0]){case Qa.PROXY_BODY:if(n){let e=t.subarray(1);e.length===0?n.close():n.write(e)}break;default:e.error(`Unexpected message type: ${t[0]}`)}});let i={headers:t.headers,method:t.method,body:r,redirect:`manual`},a;a=this.fetchProxyRequest?await this.fetchProxyRequest(t.url,i):await fetch(t.url,i);let o={};a.headers.forEach((e,t)=>{o[t]=e});let s={headers:o,status_code:a.status,status_message:a.statusText};e.writeTyped($a.PROXY_INIT,this.encoder.encode(JSON.stringify(s)));let c=a.headers.get(`content-length`),l=c?parseInt(c):0,u=Xo.getMaxPayloadSize()-1;if(l>=u){if(!a.body){e.close();return}let t=a.body.getReader();try{for(;;){let{done:n,value:r}=await t.read();if(n)break;if(r){let t=0;for(;t<r.length;){let n=Math.min(u,r.length-t),i=r.subarray(t,t+n);e.writeTyped($a.PROXY_DATA,i),t+=n}}}}finally{t.releaseLock()}}else a.body&&await a.body.pipeTo(new WritableStream({write:t=>{e.writeTyped($a.PROXY_DATA,t)}}));e.close()}async handleRequest(e,t,n){let r=ro[t.type].safeParse(t.payload);if(!r.success)throw Error(`Invalid request payload: ${r.error.message}`);switch(t.type){case`process_execute`:{if(t.payload.env_file){let e=await p.readFile(t.payload.env_file,`utf-8`),n=(0,pl.parse)(e);t.payload.env={...t.payload.env,...n}}let n=await this.processManager.execute(t.payload.command,t.payload.args,{cwd:t.payload.cwd,env:t.payload.env});this.sendResponse(e,{id:t.id,payload:{pid:n.pid}});break}case`process_wait`:this.handleProcessWait(e,t,n);break;case`process_kill`:this.mustGetProcess(t.payload.pid).kill(t.payload.signal),this.sendResponse(e,{id:t.id,payload:{}});break;case`process_list`:this.sendResponse(e,{id:t.id,payload:{processes:this.processManager.list(t.payload.include_dead??!1)}});break;case`process_read_plain_output`:{let n=this.mustGetProcess(t.payload.pid),r=this.processManager.readPlainOutput(t.payload.pid,t.payload.start_line,t.payload.end_line),i=hl(r.lines,256e3);this.sendResponse(e,{id:t.id,payload:{lines:i.lines,total_lines:r.totalLines,duration_ms:Date.now()-n.startTimeMS,exit_code:n.exitCode,exit_signal:n.exitSignal}});break}case`process_send_input`:this.mustGetProcess(t.payload.pid).sendInput(t.payload.data),this.sendResponse(e,{id:t.id,payload:{}});break;case`set_env`:this.processManager.setEnv(t.payload.env),this.sendResponse(e,{id:t.id,payload:{}});break;case`deploy_static_files`:{if(!this.createDeploymentFromTar)throw Error(`This server does not support static file deployments!`);let n=await dl(t.payload.path),r=await this.createDeploymentFromTar(n);this.sendResponse(e,{id:t.id,payload:{deployment_id:r}});break}case`read_file`:{let n=await p.readFile(t.payload.path),r=await Hc(n);if(!(!r||r?.mime===`text/plain`)){this.sendResponse(e,{id:t.id,payload:{content:n.toString(`base64`),mime_type:r?.mime,total_lines:0,lines_read:0,start_line:0}});break}let i=n.toString(`utf-8`).split(`
149
149
  `),a=Math.max(0,(t.payload.line_start??1)-1),o=Math.min(i.length,t.payload.line_end??i.length),s=i.slice(a,o);this.sendResponse(e,{id:t.id,payload:{content:s.join(`
150
150
  `),mime_type:`text/plain`,total_lines:i.length,lines_read:s.length,start_line:a}});break}case`write_file`:t.payload.base64?await p.writeFile(t.payload.path,Buffer.from(t.payload.content,`base64`)):await p.writeFile(t.payload.path,t.payload.content),typeof t.payload.mode==`number`&&await p.chmod(t.payload.path,t.payload.mode),this.sendResponse(e,{id:t.id,payload:{}});break;case`read_directory`:{let n=await p.readdir(t.payload.path,{withFileTypes:!0});this.sendResponse(e,{id:t.id,payload:{entries:n.map(e=>({name:e.name,type:e.isDirectory()?`directory`:e.isSymbolicLink()?`symlink`:`file`}))}});break}default:throw Error(`Unknown request type: ${t.type}`)}}sendResponse(e,t){e.writeTyped($a.RESPONSE,this.encoder.encode(JSON.stringify(t)))}sendNotification(e){this.notificationStream.write(new Uint8Array([$a.NOTIFICATION,...this.encoder.encode(JSON.stringify(e))]))}handleProcessWait(e,t,n){let r=t.payload,i=this.mustGetProcess(r.pid),a,o,s=!1,c,l;typeof r.timeout_ms==`number`&&(l=setTimeout(()=>{u()},r.timeout_ms));let u=()=>{if(s||(s=!0,a&&a.dispose(),o&&o.dispose(),l&&clearTimeout(l),c&&clearTimeout(c),n?.aborted))return;let i=this.processManager.status(r.pid),u=this.processManager.readPlainOutput(i.pid),d=ml(this.processManager.readANSIOutput(i.pid),64e3),f=hl(u.lines,256e3);this.sendResponse(e,{id:t.id,payload:{...i,ansi_output:d,plain_output:{lines:f.lines,total_lines:u.totalLines}}})};if(typeof i.exitCode==`number`||typeof i.exitSignal==`number`){u();return}a=i.onOutput(()=>{c&&clearTimeout(c),typeof r.output_idle_timeout_ms==`number`&&(c=setTimeout(()=>{u()},r.output_idle_timeout_ms))}),o=i.onExit(()=>{setTimeout(()=>{u()},10)}),n.addEventListener(`abort`,()=>{u()})}mustGetProcess(e){let t=this.processManager.getProcess(e);if(!t)throw Error(`Process ${e} not found`);return t}};function _l(e){let t=new TextEncoder,n=new TextDecoder,r=new gl({...e,send:e=>{i.handleMessage(e)}}),i=new $o({send:e=>{r.handleMessage(e)},isClient:!0}),a=i.createStream(),o=new vo({send:e=>{a.writeTyped(0,t.encode(e),!0)}});return a.onData(e=>{let t=e.subarray(1);o.handleMessage(n.decode(t))}),i.onStream(e=>{e.onData(e=>{let t=e.subarray(1);o.handleMessage(n.decode(t))})}),{client:o,server:r}}var vl=class{diff(e,t,n={}){let r;typeof n==`function`?(r=n,n={}):`callback`in n&&(r=n.callback);let i=this.castInput(e,n),a=this.castInput(t,n),o=this.removeEmpty(this.tokenize(i,n)),s=this.removeEmpty(this.tokenize(a,n));return this.diffWithOptionsObj(o,s,n,r)}diffWithOptionsObj(e,t,n,r){let i=e=>{if(e=this.postProcess(e,n),r){setTimeout(function(){r(e)},0);return}else return e},a=t.length,o=e.length,s=1,c=a+o;n.maxEditLength!=null&&(c=Math.min(c,n.maxEditLength));let l=n.timeout??1/0,u=Date.now()+l,d=[{oldPos:-1,lastComponent:void 0}],f=this.extractCommon(d[0],t,e,0,n);if(d[0].oldPos+1>=o&&f+1>=a)return i(this.buildValues(d[0].lastComponent,t,e));let p=-1/0,m=1/0,h=()=>{for(let r=Math.max(p,-s);r<=Math.min(m,s);r+=2){let s,c=d[r-1],l=d[r+1];c&&(d[r-1]=void 0);let u=!1;if(l){let e=l.oldPos-r;u=l&&0<=e&&e<a}let h=c&&c.oldPos+1<o;if(!u&&!h){d[r]=void 0;continue}if(s=!h||u&&c.oldPos<l.oldPos?this.addToPath(l,!0,!1,0,n):this.addToPath(c,!1,!0,1,n),f=this.extractCommon(s,t,e,r,n),s.oldPos+1>=o&&f+1>=a)return i(this.buildValues(s.lastComponent,t,e))||!0;d[r]=s,s.oldPos+1>=o&&(m=Math.min(m,r-1)),f+1>=a&&(p=Math.max(p,r+1))}s++};if(r)(function e(){setTimeout(function(){if(s>c||Date.now()>u)return r(void 0);h()||e()},0)})();else for(;s<=c&&Date.now()<=u;){let e=h();if(e)return e}}addToPath(e,t,n,r,i){let a=e.lastComponent;return a&&!i.oneChangePerToken&&a.added===t&&a.removed===n?{oldPos:e.oldPos+r,lastComponent:{count:a.count+1,added:t,removed:n,previousComponent:a.previousComponent}}:{oldPos:e.oldPos+r,lastComponent:{count:1,added:t,removed:n,previousComponent:a}}}extractCommon(e,t,n,r,i){let a=t.length,o=n.length,s=e.oldPos,c=s-r,l=0;for(;c+1<a&&s+1<o&&this.equals(n[s+1],t[c+1],i);)c++,s++,l++,i.oneChangePerToken&&(e.lastComponent={count:1,previousComponent:e.lastComponent,added:!1,removed:!1});return l&&!i.oneChangePerToken&&(e.lastComponent={count:l,previousComponent:e.lastComponent,added:!1,removed:!1}),e.oldPos=s,c}equals(e,t,n){return n.comparator?n.comparator(e,t):e===t||!!n.ignoreCase&&e.toLowerCase()===t.toLowerCase()}removeEmpty(e){let t=[];for(let n=0;n<e.length;n++)e[n]&&t.push(e[n]);return t}castInput(e,t){return e}tokenize(e,t){return Array.from(e)}join(e){return e.join(``)}postProcess(e,t){return e}get useLongestToken(){return!1}buildValues(e,t,n){let r=[],i;for(;e;)r.push(e),i=e.previousComponent,delete e.previousComponent,e=i;r.reverse();let a=r.length,o=0,s=0,c=0;for(;o<a;o++){let e=r[o];if(e.removed)e.value=this.join(n.slice(c,c+e.count)),c+=e.count;else{if(!e.added&&this.useLongestToken){let r=t.slice(s,s+e.count);r=r.map(function(e,t){let r=n[c+t];return r.length>e.length?r:e}),e.value=this.join(r)}else e.value=this.join(t.slice(s,s+e.count));s+=e.count,e.added||(c+=e.count)}}return r}},yl=class extends vl{};new yl;function bl(e,t){let n;for(n=0;n<e.length&&n<t.length;n++)if(e[n]!=t[n])return e.slice(0,n);return e.slice(0,n)}function xl(e,t){let n;if(!e||!t||e[e.length-1]!=t[t.length-1])return``;for(n=0;n<e.length&&n<t.length;n++)if(e[e.length-(n+1)]!=t[t.length-(n+1)])return e.slice(-n);return e.slice(-n)}function Sl(e,t,n){if(e.slice(0,t.length)!=t)throw Error(`string ${JSON.stringify(e)} doesn't start with prefix ${JSON.stringify(t)}; this is a bug`);return n+e.slice(t.length)}function Cl(e,t,n){if(!t)return e+n;if(e.slice(-t.length)!=t)throw Error(`string ${JSON.stringify(e)} doesn't end with suffix ${JSON.stringify(t)}; this is a bug`);return e.slice(0,-t.length)+n}function wl(e,t){return Sl(e,t,``)}function Tl(e,t){return Cl(e,t,``)}function El(e,t){return t.slice(0,Dl(e,t))}function Dl(e,t){let n=0;e.length>t.length&&(n=e.length-t.length);let r=t.length;e.length<t.length&&(r=e.length);let i=Array(r),a=0;i[0]=0;for(let e=1;e<r;e++){for(t[e]==t[a]?i[e]=i[a]:i[e]=a;a>0&&t[e]!=t[a];)a=i[a];t[e]==t[a]&&a++}a=0;for(let r=n;r<e.length;r++){for(;a>0&&e[r]!=t[a];)a=i[a];e[r]==t[a]&&a++}return a}function Ol(e){let t;for(t=e.length-1;t>=0&&e[t].match(/\s/);t--);return e.substring(t+1)}function kl(e){let t=e.match(/^\s*/);return t?t[0]:``}const Al=`a-zA-Z0-9_\\u{C0}-\\u{FF}\\u{D8}-\\u{F6}\\u{F8}-\\u{2C6}\\u{2C8}-\\u{2D7}\\u{2DE}-\\u{2FF}\\u{1E00}-\\u{1EFF}`,jl=RegExp(`[${Al}]+|\\s+|[^${Al}]`,`ug`);var Ml=class extends vl{equals(e,t,n){return n.ignoreCase&&(e=e.toLowerCase(),t=t.toLowerCase()),e.trim()===t.trim()}tokenize(e,t={}){let n;if(t.intlSegmenter){let r=t.intlSegmenter;if(r.resolvedOptions().granularity!=`word`)throw Error(`The segmenter passed must have a granularity of "word"`);n=Array.from(r.segment(e),e=>e.segment)}else n=e.match(jl)||[];let r=[],i=null;return n.forEach(e=>{/\s/.test(e)?i==null?r.push(e):r.push(r.pop()+e):i!=null&&/\s/.test(i)?r[r.length-1]==i?r.push(r.pop()+e):r.push(i+e):r.push(e),i=e}),r}join(e){return e.map((e,t)=>t==0?e:e.replace(/^\s+/,``)).join(``)}postProcess(e,t){if(!e||t.oneChangePerToken)return e;let n=null,r=null,i=null;return e.forEach(e=>{e.added?r=e:e.removed?i=e:((r||i)&&Nl(n,i,r,e),n=e,r=null,i=null)}),(r||i)&&Nl(n,i,r,null),e}};new Ml;function Nl(e,t,n,r){if(t&&n){let i=kl(t.value),a=Ol(t.value),o=kl(n.value),s=Ol(n.value);if(e){let r=bl(i,o);e.value=Cl(e.value,o,r),t.value=wl(t.value,r),n.value=wl(n.value,r)}if(r){let e=xl(a,s);r.value=Sl(r.value,s,e),t.value=Tl(t.value,e),n.value=Tl(n.value,e)}}else if(n){if(e){let e=kl(n.value);n.value=n.value.substring(e.length)}if(r){let e=kl(r.value);r.value=r.value.substring(e.length)}}else if(e&&r){let n=kl(r.value),i=kl(t.value),a=Ol(t.value),o=bl(n,i);t.value=wl(t.value,o);let s=xl(wl(n,o),a);t.value=Tl(t.value,s),r.value=Sl(r.value,n,s),e.value=Cl(e.value,n,n.slice(0,n.length-s.length))}else if(r){let e=kl(r.value),n=Ol(t.value),i=El(n,e);t.value=Tl(t.value,i)}else if(e){let n=Ol(e.value),r=kl(t.value),i=El(n,r);t.value=wl(t.value,i)}}var Pl=class extends vl{tokenize(e){let t=RegExp(`(\\r?\\n)|[${Al}]+|[^\\S\\n\\r]+|[^${Al}]`,`ug`);return e.match(t)||[]}};new Pl;var Fl=class extends vl{constructor(){super(...arguments),this.tokenize=Rl}equals(e,t,n){return n.ignoreWhitespace?((!n.newlineIsToken||!e.includes(`
151
151
  `))&&(e=e.trim()),(!n.newlineIsToken||!t.includes(`
@@ -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()}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;
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,redirect:`manual`})}});(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:r===`run`?b:E,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;