@qualcomm-ui/mdx-vite 3.8.1 → 3.8.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -1,22 +1,22 @@
1
- import{createRequire as e}from"node:module";e(import.meta.url);import{I as t,M as n,t as r}from"./search-indexer-D3Y9DkgK.js";import{createRequire as e}from"node:module";import{resolve as i}from"node:path";import{writeFileSync as a}from"node:fs";import{cwd as o}from"node:process";import{glob as s}from"glob";import{access as c,mkdir as l,readFile as u,writeFile as d}from"node:fs/promises";import{createHash as f}from"node:crypto";import p,{config as m}from"dotenv";import{setTimeout as h}from"node:timers/promises";import g from"ora";var _=Object.create,v=Object.defineProperty,y=Object.getOwnPropertyDescriptor,b=Object.getOwnPropertyNames,x=Object.getPrototypeOf,S=Object.prototype.hasOwnProperty,__commonJSMin=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),__copyProps=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=b(t),a=0,o=i.length,s;a<o;a++)s=i[a],!S.call(e,s)&&s!==n&&v(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=y(t,s))||r.enumerable});return e},__toESM=(e,t,n)=>(n=e==null?{}:_(x(e)),__copyProps(t||!e||!e.__esModule?v(n,`default`,{value:e,enumerable:!0}):n,e)),C=e(import.meta.url),w=__commonJSMin((e=>{var CommanderError=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}},InvalidArgumentError=class extends CommanderError{constructor(e){super(1,`commander.invalidArgument`,e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};e.CommanderError=CommanderError,e.InvalidArgumentError=InvalidArgumentError})),T=__commonJSMin((e=>{var{InvalidArgumentError:t}=w(),Argument=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 humanReadableArgName(e){let t=e.name()+(e.variadic===!0?`...`:``);return e.required?`<`+t+`>`:`[`+t+`]`}e.Argument=Argument,e.humanReadableArgName=humanReadableArgName})),E=__commonJSMin((e=>{var{humanReadableArgName:t}=T(),Help=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 getSortKey=e=>e.short?e.short.replace(/^-/,``):e.long.replace(/^--/,``);return getSortKey(e).localeCompare(getSortKey(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 callFormatItem(e,r){return t.formatItem(e,n,r,t)}let i=[`${t.styleTitle(`Usage:`)} ${t.styleUsage(t.commandUsage(e))}`,``],a=t.commandDescription(e);a.length>0&&(i=i.concat([t.boxWrap(t.styleCommandDescription(a),r),``]));let o=t.visibleArguments(e).map(e=>callFormatItem(t.styleArgumentTerm(t.argumentTerm(e)),t.styleArgumentDescription(t.argumentDescription(e))));if(i=i.concat(this.formatItemList(`Arguments:`,o,t)),this.groupItems(e.options,t.visibleOptions(e),e=>e.helpGroupHeading??`Options:`).forEach((e,n)=>{let r=e.map(e=>callFormatItem(t.styleOptionTerm(t.optionTerm(e)),t.styleOptionDescription(t.optionDescription(e))));i=i.concat(this.formatItemList(n,r,t))}),t.showGlobalOptions){let n=t.visibleGlobalOptions(e).map(e=>callFormatItem(t.styleOptionTerm(t.optionTerm(e)),t.styleOptionDescription(t.optionDescription(e))));i=i.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=>callFormatItem(t.styleSubcommandTerm(t.subcommandTerm(e)),t.styleSubcommandDescription(t.subcommandDescription(e))));i=i.concat(this.formatItemList(n,r,t))}),i.join(`
2
- `)}displayWidth(e){return stripColor(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,`
1
+ import{I as e,M as t,t as n}from"./search-indexer-Chr-z_vN.js";import{createRequire as r}from"node:module";import{resolve as i}from"node:path";import{writeFileSync as a}from"node:fs";import{cwd as o}from"node:process";import{glob as s}from"glob";import{access as c,mkdir as l,readFile as u,writeFile as d}from"node:fs/promises";import{createHash as f}from"node:crypto";import p,{config as m}from"dotenv";import{setTimeout as h}from"node:timers/promises";import g from"ora";var _=Object.create,v=Object.defineProperty,y=Object.getOwnPropertyDescriptor,b=Object.getOwnPropertyNames,x=Object.getPrototypeOf,S=Object.prototype.hasOwnProperty,C=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),w=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=b(t),a=0,o=i.length,s;a<o;a++)s=i[a],!S.call(e,s)&&s!==n&&v(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=y(t,s))||r.enumerable});return e},T=(e,t,n)=>(n=e==null?{}:_(x(e)),w(t||!e||!e.__esModule?v(n,`default`,{value:e,enumerable:!0}):n,e)),E=r(import.meta.url),D=C((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})),O=C((e=>{var{InvalidArgumentError:t}=D(),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})),k=C((e=>{var{humanReadableArgName:t}=O(),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
+ `)}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,`
3
3
  `+` `.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(`
4
- `)}};function stripColor(e){return e.replace(/\x1b\[\d*(;\d*)*m/g,``)}e.Help=Help,e.stripColor=stripColor})),D=__commonJSMin((e=>{var{InvalidArgumentError:t}=w(),Option=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=splitOptionFlags(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?camelcase(this.name().replace(/^no-/,``)):camelcase(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}},DualOptions=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 camelcase(e){return e.split(`-`).reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function splitOptionFlags(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}
4
+ `)}};function r(e){return e.replace(/\x1b\[\d*(;\d*)*m/g,``)}e.Help=n,e.stripColor=r})),A=C((e=>{var{InvalidArgumentError:t}=D(),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}
5
5
  - a short flag is a single dash and a single character
6
6
  - either use a single dash and a single character (for a short flag)
7
7
  - or use a double dash for a long option (and can have two, like '--ws, --workspace')`):r.test(t)?Error(`${n}
8
8
  - too many short flags`):i.test(t)?Error(`${n}
9
9
  - too many long flags`):Error(`${n}
10
- - unrecognised flag format`)}if(t===void 0&&n===void 0)throw Error(`option creation failed due to no flags found in '${e}'.`);return{shortFlag:t,longFlag:n}}e.Option=Option,e.DualOptions=DualOptions})),O=__commonJSMin((e=>{var t=3;function editDistance(e,n){if(Math.abs(e.length-n.length)>t)return Math.max(e.length,n.length);let r=[];for(let t=0;t<=e.length;t++)r[t]=[t];for(let e=0;e<=n.length;e++)r[0][e]=e;for(let t=1;t<=n.length;t++)for(let i=1;i<=e.length;i++){let a=1;a=e[i-1]===n[t-1]?0:1,r[i][t]=Math.min(r[i-1][t]+1,r[i][t-1]+1,r[i-1][t-1]+a),i>1&&t>1&&e[i-1]===n[t-2]&&e[i-2]===n[t-1]&&(r[i][t]=Math.min(r[i][t],r[i-2][t-2]+1))}return r[e.length][n.length]}function suggestSimilar(e,n){if(!n||n.length===0)return``;n=Array.from(new Set(n));let r=e.startsWith(`--`);r&&(e=e.slice(2),n=n.map(e=>e.slice(2)));let i=[],a=t;return n.forEach(t=>{if(t.length<=1)return;let n=editDistance(e,t),r=Math.max(e.length,t.length);(r-n)/r>.4&&(n<a?(a=n,i=[t]):n===a&&i.push(t))}),i.sort((e,t)=>e.localeCompare(t)),r&&(i=i.map(e=>`--${e}`)),i.length>1?`\n(Did you mean one of ${i.join(`, `)}?)`:i.length===1?`\n(Did you mean ${i[0]}?)`:``}e.suggestSimilar=suggestSimilar})),k=__commonJSMin((e=>{var t=C(`node:events`).EventEmitter,n=C(`node:child_process`),r=C(`node:path`),i=C(`node:fs`),a=C(`node:process`),{Argument:o,humanReadableArgName:s}=T(),{CommanderError:c}=w(),{Help:l,stripColor:u}=E(),{Option:d,DualOptions:f}=D(),{suggestSimilar:p}=O(),m=class Command extends t{constructor(e){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!1,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=e||``,this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description=``,this._summary=``,this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._savedState=null,this._outputConfiguration={writeOut:e=>a.stdout.write(e),writeErr:e=>a.stderr.write(e),outputError:(e,t)=>t(e),getOutHelpWidth:()=>a.stdout.isTTY?a.stdout.columns:void 0,getErrHelpWidth:()=>a.stderr.isTTY?a.stderr.columns:void 0,getOutHasColors:()=>useColor()??(a.stdout.isTTY&&a.stdout.hasColors?.()),getErrHasColors:()=>useColor()??(a.stderr.isTTY&&a.stderr.hasColors?.()),stripColor:e=>u(e)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={},this._helpGroupHeading=void 0,this._defaultCommandGroup=void 0,this._defaultOptionGroup=void 0}copyInheritedSettings(e){return this._outputConfiguration=e._outputConfiguration,this._helpOption=e._helpOption,this._helpCommand=e._helpCommand,this._helpConfiguration=e._helpConfiguration,this._exitCallback=e._exitCallback,this._storeOptionsAsProperties=e._storeOptionsAsProperties,this._combineFlagAndOptionalValue=e._combineFlagAndOptionalValue,this._allowExcessArguments=e._allowExcessArguments,this._enablePositionalOptions=e._enablePositionalOptions,this._showHelpAfterError=e._showHelpAfterError,this._showSuggestionAfterError=e._showSuggestionAfterError,this}_getCommandAndAncestors(){let e=[];for(let t=this;t;t=t.parent)e.push(t);return e}command(e,t,n){let r=t,i=n;typeof r==`object`&&r&&(i=r,r=null),i||={};let[,a,o]=e.match(/([^ ]+) *(.*)/),s=this.createCommand(a);return r&&(s.description(r),s._executableHandler=!0),i.isDefault&&(this._defaultCommandName=s._name),s._hidden=!!(i.noHelp||i.hidden),s._executableFile=i.executableFile||null,o&&s.arguments(o),this._registerCommand(s),s.parent=this,s.copyInheritedSettings(this),r?this:s}createCommand(e){return new Command(e)}createHelp(){return Object.assign(new l,this.configureHelp())}configureHelp(e){return e===void 0?this._helpConfiguration:(this._helpConfiguration=e,this)}configureOutput(e){return e===void 0?this._outputConfiguration:(this._outputConfiguration={...this._outputConfiguration,...e},this)}showHelpAfterError(e=!0){return typeof e!=`string`&&(e=!!e),this._showHelpAfterError=e,this}showSuggestionAfterError(e=!0){return this._showSuggestionAfterError=!!e,this}addCommand(e,t){if(!e._name)throw Error(`Command passed to .addCommand() must have a name
10
+ - unrecognised flag format`)}if(t===void 0&&n===void 0)throw Error(`option creation failed due to no flags found in '${e}'.`);return{shortFlag:t,longFlag:n}}e.Option=n,e.DualOptions=r})),j=C((e=>{var t=3;function n(e,n){if(Math.abs(e.length-n.length)>t)return Math.max(e.length,n.length);let r=[];for(let t=0;t<=e.length;t++)r[t]=[t];for(let e=0;e<=n.length;e++)r[0][e]=e;for(let t=1;t<=n.length;t++)for(let i=1;i<=e.length;i++){let a=1;a=e[i-1]===n[t-1]?0:1,r[i][t]=Math.min(r[i-1][t]+1,r[i][t-1]+1,r[i-1][t-1]+a),i>1&&t>1&&e[i-1]===n[t-2]&&e[i-2]===n[t-1]&&(r[i][t]=Math.min(r[i][t],r[i-2][t-2]+1))}return r[e.length][n.length]}function r(e,r){if(!r||r.length===0)return``;r=Array.from(new Set(r));let i=e.startsWith(`--`);i&&(e=e.slice(2),r=r.map(e=>e.slice(2)));let a=[],o=t;return r.forEach(t=>{if(t.length<=1)return;let r=n(e,t),i=Math.max(e.length,t.length);(i-r)/i>.4&&(r<o?(o=r,a=[t]):r===o&&a.push(t))}),a.sort((e,t)=>e.localeCompare(t)),i&&(a=a.map(e=>`--${e}`)),a.length>1?`\n(Did you mean one of ${a.join(`, `)}?)`:a.length===1?`\n(Did you mean ${a[0]}?)`:``}e.suggestSimilar=r})),M=C((e=>{var t=E(`node:events`).EventEmitter,n=E(`node:child_process`),r=E(`node:path`),i=E(`node:fs`),a=E(`node:process`),{Argument:o,humanReadableArgName:s}=O(),{CommanderError:c}=D(),{Help:l,stripColor:u}=k(),{Option:d,DualOptions:f}=A(),{suggestSimilar:p}=j(),m=class e extends t{constructor(e){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!1,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=e||``,this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description=``,this._summary=``,this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._savedState=null,this._outputConfiguration={writeOut:e=>a.stdout.write(e),writeErr:e=>a.stderr.write(e),outputError:(e,t)=>t(e),getOutHelpWidth:()=>a.stdout.isTTY?a.stdout.columns:void 0,getErrHelpWidth:()=>a.stderr.isTTY?a.stderr.columns:void 0,getOutHasColors:()=>g()??(a.stdout.isTTY&&a.stdout.hasColors?.()),getErrHasColors:()=>g()??(a.stderr.isTTY&&a.stderr.hasColors?.()),stripColor:e=>u(e)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={},this._helpGroupHeading=void 0,this._defaultCommandGroup=void 0,this._defaultOptionGroup=void 0}copyInheritedSettings(e){return this._outputConfiguration=e._outputConfiguration,this._helpOption=e._helpOption,this._helpCommand=e._helpCommand,this._helpConfiguration=e._helpConfiguration,this._exitCallback=e._exitCallback,this._storeOptionsAsProperties=e._storeOptionsAsProperties,this._combineFlagAndOptionalValue=e._combineFlagAndOptionalValue,this._allowExcessArguments=e._allowExcessArguments,this._enablePositionalOptions=e._enablePositionalOptions,this._showHelpAfterError=e._showHelpAfterError,this._showSuggestionAfterError=e._showSuggestionAfterError,this}_getCommandAndAncestors(){let e=[];for(let t=this;t;t=t.parent)e.push(t);return e}command(e,t,n){let r=t,i=n;typeof r==`object`&&r&&(i=r,r=null),i||={};let[,a,o]=e.match(/([^ ]+) *(.*)/),s=this.createCommand(a);return r&&(s.description(r),s._executableHandler=!0),i.isDefault&&(this._defaultCommandName=s._name),s._hidden=!!(i.noHelp||i.hidden),s._executableFile=i.executableFile||null,o&&s.arguments(o),this._registerCommand(s),s.parent=this,s.copyInheritedSettings(this),r?this:s}createCommand(t){return new e(t)}createHelp(){return Object.assign(new l,this.configureHelp())}configureHelp(e){return e===void 0?this._helpConfiguration:(this._helpConfiguration=e,this)}configureOutput(e){return e===void 0?this._outputConfiguration:(this._outputConfiguration={...this._outputConfiguration,...e},this)}showHelpAfterError(e=!0){return typeof e!=`string`&&(e=!!e),this._showHelpAfterError=e,this}showSuggestionAfterError(e=!0){return this._showSuggestionAfterError=!!e,this}addCommand(e,t){if(!e._name)throw Error(`Command passed to .addCommand() must have a name
11
11
  - specify the name in Command constructor or using .name()`);return t||={},t.isDefault&&(this._defaultCommandName=e._name),(t.noHelp||t.hidden)&&(e._hidden=!0),this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,t){return new o(e,t)}argument(e,t,n,r){let i=this.createArgument(e,t);return typeof n==`function`?i.default(r).argParser(n):i.default(n),this.addArgument(i),this}arguments(e){return e.trim().split(/ +/).forEach(e=>{this.argument(e)}),this}addArgument(e){let t=this.registeredArguments.slice(-1)[0];if(t?.variadic)throw Error(`only the last argument can be variadic '${t.name()}'`);if(e.required&&e.defaultValue!==void 0&&e.parseArg===void 0)throw Error(`a default value for a required argument is never used: '${e.name()}'`);return this.registeredArguments.push(e),this}helpCommand(e,t){if(typeof e==`boolean`)return this._addImplicitHelpCommand=e,e&&this._defaultCommandGroup&&this._initCommandGroup(this._getHelpCommand()),this;let[,n,r]=(e??`help [command]`).match(/([^ ]+) *(.*)/),i=t??`display help for command`,a=this.createCommand(n);return a.helpOption(!1),r&&a.arguments(r),i&&a.description(i),this._addImplicitHelpCommand=!0,this._helpCommand=a,(e||t)&&this._initCommandGroup(a),this}addHelpCommand(e,t){return typeof e==`object`?(this._addImplicitHelpCommand=!0,this._helpCommand=e,this._initCommandGroup(e),this):(this.helpCommand(e,t),this)}_getHelpCommand(){return this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand(`help`))?(this._helpCommand===void 0&&this.helpCommand(void 0,void 0),this._helpCommand):null}hook(e,t){let n=[`preSubcommand`,`preAction`,`postAction`];if(!n.includes(e))throw Error(`Unexpected value for event passed to hook : '${e}'.
12
12
  Expecting one of '${n.join(`', '`)}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(t):this._lifeCycleHooks[e]=[t],this}exitOverride(e){return e?this._exitCallback=e:this._exitCallback=e=>{if(e.code!==`commander.executeSubCommandAsync`)throw e},this}_exit(e,t,n){this._exitCallback&&this._exitCallback(new c(e,t,n)),a.exit(e)}action(e){return this._actionHandler=t=>{let n=this.registeredArguments.length,r=t.slice(0,n);return this._storeOptionsAsProperties?r[n]=this:r[n]=this.opts(),r.push(this),e.apply(this,r)},this}createOption(e,t){return new d(e,t)}_callParseArg(e,t,n,r){try{return e.parseArg(t,n)}catch(e){if(e.code===`commander.invalidArgument`){let t=`${r} ${e.message}`;this.error(t,{exitCode:e.exitCode,code:e.code})}throw e}}_registerOption(e){let t=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(t){let n=e.long&&this._findOption(e.long)?e.long:e.short;throw Error(`Cannot add option '${e.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${n}'
13
- - already used by option '${t.flags}'`)}this._initOptionGroup(e),this.options.push(e)}_registerCommand(e){let knownBy=e=>[e.name()].concat(e.aliases()),t=knownBy(e).find(e=>this._findCommand(e));if(t){let n=knownBy(this._findCommand(t)).join(`|`),r=knownBy(e).join(`|`);throw Error(`cannot add command '${r}' as already have command '${n}'`)}this._initCommandGroup(e),this.commands.push(e)}addOption(e){this._registerOption(e);let t=e.name(),n=e.attributeName();if(e.negate){let t=e.long.replace(/^--no-/,`--`);this._findOption(t)||this.setOptionValueWithSource(n,e.defaultValue===void 0?!0:e.defaultValue,`default`)}else e.defaultValue!==void 0&&this.setOptionValueWithSource(n,e.defaultValue,`default`);let handleOptionValue=(t,r,i)=>{t==null&&e.presetArg!==void 0&&(t=e.presetArg);let a=this.getOptionValue(n);t!==null&&e.parseArg?t=this._callParseArg(e,t,a,r):t!==null&&e.variadic&&(t=e._collectValue(t,a)),t??=e.negate?!1:e.isBoolean()||e.optional?!0:``,this.setOptionValueWithSource(n,t,i)};return this.on(`option:`+t,t=>{handleOptionValue(t,`error: option '${e.flags}' argument '${t}' is invalid.`,`cli`)}),e.envVar&&this.on(`optionEnv:`+t,t=>{handleOptionValue(t,`error: option '${e.flags}' value '${t}' from env '${e.envVar}' is invalid.`,`env`)}),this}_optionEx(e,t,n,fn,r){if(typeof t==`object`&&t instanceof d)throw Error(`To add an Option object use addOption() instead of option() or requiredOption()`);let i=this.createOption(t,n);if(i.makeOptionMandatory(!!e.mandatory),typeof fn==`function`)i.default(r).argParser(fn);else if(fn instanceof RegExp){let e=fn;fn=(t,n)=>{let r=e.exec(t);return r?r[0]:n},i.default(r).argParser(fn)}else i.default(fn);return this.addOption(i)}option(e,t,n,r){return this._optionEx({},e,t,n,r)}requiredOption(e,t,n,r){return this._optionEx({mandatory:!0},e,t,n,r)}combineFlagAndOptionalValue(e=!0){return this._combineFlagAndOptionalValue=!!e,this}allowUnknownOption(e=!0){return this._allowUnknownOption=!!e,this}allowExcessArguments(e=!0){return this._allowExcessArguments=!!e,this}enablePositionalOptions(e=!0){return this._enablePositionalOptions=!!e,this}passThroughOptions(e=!0){return this._passThroughOptions=!!e,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(e=!0){if(this.options.length)throw Error(`call .storeOptionsAsProperties() before adding options`);if(Object.keys(this._optionValues).length)throw Error(`call .storeOptionsAsProperties() before setting option values`);return this._storeOptionsAsProperties=!!e,this}getOptionValue(e){return this._storeOptionsAsProperties?this[e]:this._optionValues[e]}setOptionValue(e,t){return this.setOptionValueWithSource(e,t,void 0)}setOptionValueWithSource(e,t,n){return this._storeOptionsAsProperties?this[e]=t:this._optionValues[e]=t,this._optionValueSources[e]=n,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let t;return this._getCommandAndAncestors().forEach(n=>{n.getOptionValueSource(e)!==void 0&&(t=n.getOptionValueSource(e))}),t}_prepareUserArgs(e,t){if(e!==void 0&&!Array.isArray(e))throw Error(`first parameter to parse must be array or undefined`);if(t||={},e===void 0&&t.from===void 0){a.versions?.electron&&(t.from=`electron`);let e=a.execArgv??[];(e.includes(`-e`)||e.includes(`--eval`)||e.includes(`-p`)||e.includes(`--print`))&&(t.from=`eval`)}e===void 0&&(e=a.argv),this.rawArgs=e.slice();let n;switch(t.from){case void 0:case`node`:this._scriptPath=e[1],n=e.slice(2);break;case`electron`:a.defaultApp?(this._scriptPath=e[1],n=e.slice(2)):n=e.slice(1);break;case`user`:n=e.slice(0);break;case`eval`:n=e.slice(1);break;default:throw Error(`unexpected parse option { from: '${t.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||`program`,n}parse(e,t){this._prepareForParse();let n=this._prepareUserArgs(e,t);return this._parseCommand([],n),this}async parseAsync(e,t){this._prepareForParse();let n=this._prepareUserArgs(e,t);return await this._parseCommand([],n),this}_prepareForParse(){this._savedState===null?this.saveStateBeforeParse():this.restoreStateBeforeParse()}saveStateBeforeParse(){this._savedState={_name:this._name,_optionValues:{...this._optionValues},_optionValueSources:{...this._optionValueSources}}}restoreStateBeforeParse(){if(this._storeOptionsAsProperties)throw Error(`Can not call parse again when storeOptionsAsProperties is true.
13
+ - already used by option '${t.flags}'`)}this._initOptionGroup(e),this.options.push(e)}_registerCommand(e){let t=e=>[e.name()].concat(e.aliases()),n=t(e).find(e=>this._findCommand(e));if(n){let r=t(this._findCommand(n)).join(`|`),i=t(e).join(`|`);throw Error(`cannot add command '${i}' as already have command '${r}'`)}this._initCommandGroup(e),this.commands.push(e)}addOption(e){this._registerOption(e);let t=e.name(),n=e.attributeName();if(e.negate){let t=e.long.replace(/^--no-/,`--`);this._findOption(t)||this.setOptionValueWithSource(n,e.defaultValue===void 0?!0:e.defaultValue,`default`)}else e.defaultValue!==void 0&&this.setOptionValueWithSource(n,e.defaultValue,`default`);let r=(t,r,i)=>{t==null&&e.presetArg!==void 0&&(t=e.presetArg);let a=this.getOptionValue(n);t!==null&&e.parseArg?t=this._callParseArg(e,t,a,r):t!==null&&e.variadic&&(t=e._collectValue(t,a)),t??=e.negate?!1:e.isBoolean()||e.optional?!0:``,this.setOptionValueWithSource(n,t,i)};return this.on(`option:`+t,t=>{r(t,`error: option '${e.flags}' argument '${t}' is invalid.`,`cli`)}),e.envVar&&this.on(`optionEnv:`+t,t=>{r(t,`error: option '${e.flags}' value '${t}' from env '${e.envVar}' is invalid.`,`env`)}),this}_optionEx(e,t,n,r,i){if(typeof t==`object`&&t instanceof d)throw Error(`To add an Option object use addOption() instead of option() or requiredOption()`);let a=this.createOption(t,n);if(a.makeOptionMandatory(!!e.mandatory),typeof r==`function`)a.default(i).argParser(r);else if(r instanceof RegExp){let e=r;r=(t,n)=>{let r=e.exec(t);return r?r[0]:n},a.default(i).argParser(r)}else a.default(r);return this.addOption(a)}option(e,t,n,r){return this._optionEx({},e,t,n,r)}requiredOption(e,t,n,r){return this._optionEx({mandatory:!0},e,t,n,r)}combineFlagAndOptionalValue(e=!0){return this._combineFlagAndOptionalValue=!!e,this}allowUnknownOption(e=!0){return this._allowUnknownOption=!!e,this}allowExcessArguments(e=!0){return this._allowExcessArguments=!!e,this}enablePositionalOptions(e=!0){return this._enablePositionalOptions=!!e,this}passThroughOptions(e=!0){return this._passThroughOptions=!!e,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(e=!0){if(this.options.length)throw Error(`call .storeOptionsAsProperties() before adding options`);if(Object.keys(this._optionValues).length)throw Error(`call .storeOptionsAsProperties() before setting option values`);return this._storeOptionsAsProperties=!!e,this}getOptionValue(e){return this._storeOptionsAsProperties?this[e]:this._optionValues[e]}setOptionValue(e,t){return this.setOptionValueWithSource(e,t,void 0)}setOptionValueWithSource(e,t,n){return this._storeOptionsAsProperties?this[e]=t:this._optionValues[e]=t,this._optionValueSources[e]=n,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let t;return this._getCommandAndAncestors().forEach(n=>{n.getOptionValueSource(e)!==void 0&&(t=n.getOptionValueSource(e))}),t}_prepareUserArgs(e,t){if(e!==void 0&&!Array.isArray(e))throw Error(`first parameter to parse must be array or undefined`);if(t||={},e===void 0&&t.from===void 0){a.versions?.electron&&(t.from=`electron`);let e=a.execArgv??[];(e.includes(`-e`)||e.includes(`--eval`)||e.includes(`-p`)||e.includes(`--print`))&&(t.from=`eval`)}e===void 0&&(e=a.argv),this.rawArgs=e.slice();let n;switch(t.from){case void 0:case`node`:this._scriptPath=e[1],n=e.slice(2);break;case`electron`:a.defaultApp?(this._scriptPath=e[1],n=e.slice(2)):n=e.slice(1);break;case`user`:n=e.slice(0);break;case`eval`:n=e.slice(1);break;default:throw Error(`unexpected parse option { from: '${t.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||`program`,n}parse(e,t){this._prepareForParse();let n=this._prepareUserArgs(e,t);return this._parseCommand([],n),this}async parseAsync(e,t){this._prepareForParse();let n=this._prepareUserArgs(e,t);return await this._parseCommand([],n),this}_prepareForParse(){this._savedState===null?this.saveStateBeforeParse():this.restoreStateBeforeParse()}saveStateBeforeParse(){this._savedState={_name:this._name,_optionValues:{...this._optionValues},_optionValueSources:{...this._optionValueSources}}}restoreStateBeforeParse(){if(this._storeOptionsAsProperties)throw Error(`Can not call parse again when storeOptionsAsProperties is true.
14
14
  - either make a new Command for each call to parse, or stop storing options as properties`);this._name=this._savedState._name,this._scriptPath=null,this.rawArgs=[],this._optionValues={...this._savedState._optionValues},this._optionValueSources={...this._savedState._optionValueSources},this.args=[],this.processedArgs=[]}_checkForMissingExecutable(e,t,n){if(i.existsSync(e))return;let r=`'${e}' does not exist
15
15
  - if '${n}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
16
16
  - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
17
- - ${t?`searched for local subcommand relative to directory '${t}'`:`no directory for search for local subcommand, use .executableDir() to supply a custom directory`}`;throw Error(r)}_executeSubCommand(e,t){t=t.slice();let o=!1,s=[`.js`,`.ts`,`.tsx`,`.mjs`,`.cjs`];function findFile(e,t){let n=r.resolve(e,t);if(i.existsSync(n))return n;if(s.includes(r.extname(t)))return;let a=s.find(e=>i.existsSync(`${n}${e}`));if(a)return`${n}${a}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let l=e._executableFile||`${this._name}-${e._name}`,u=this._executableDir||``;if(this._scriptPath){let e;try{e=i.realpathSync(this._scriptPath)}catch{e=this._scriptPath}u=r.resolve(r.dirname(e),u)}if(u){let t=findFile(u,l);if(!t&&!e._executableFile&&this._scriptPath){let n=r.basename(this._scriptPath,r.extname(this._scriptPath));n!==this._name&&(t=findFile(u,`${n}-${e._name}`))}l=t||l}o=s.includes(r.extname(l));let d;a.platform===`win32`?(this._checkForMissingExecutable(l,u,e._name),t.unshift(l),t=incrementNodeInspectorPort(a.execArgv).concat(t),d=n.spawn(a.execPath,t,{stdio:`inherit`})):o?(t.unshift(l),t=incrementNodeInspectorPort(a.execArgv).concat(t),d=n.spawn(a.argv[0],t,{stdio:`inherit`})):d=n.spawn(l,t,{stdio:`inherit`}),d.killed||[`SIGUSR1`,`SIGUSR2`,`SIGTERM`,`SIGINT`,`SIGHUP`].forEach(e=>{a.on(e,()=>{d.killed===!1&&d.exitCode===null&&d.kill(e)})});let f=this._exitCallback;d.on(`close`,e=>{e??=1,f?f(new c(e,`commander.executeSubCommandAsync`,`(close)`)):a.exit(e)}),d.on(`error`,t=>{if(t.code===`ENOENT`)this._checkForMissingExecutable(l,u,e._name);else if(t.code===`EACCES`)throw Error(`'${l}' not executable`);if(!f)a.exit(1);else{let e=new c(1,`commander.executeSubCommandAsync`,`(error)`);e.nestedError=t,f(e)}}),this.runningCommand=d}_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 myParseArg=(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 e=[];this.registeredArguments.forEach((t,n)=>{let r=t.defaultValue;t.variadic?n<this.args.length?(r=this.args.slice(n),t.parseArg&&(r=r.reduce((e,n)=>myParseArg(t,n,e),t.defaultValue))):r===void 0&&(r=[]):n<this.args.length&&(r=this.args[n],t.parseArg&&(r=myParseArg(t,r,t.defaultValue))),e[n]=r}),this.processedArgs=e}_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 checkForUnknownOptions=()=>{n.unknown.length>0&&this.unknownOption(n.unknown[0])},r=`command:${this.name()}`;if(this._actionHandler){checkForUnknownOptions(),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(r,e,t)})),n=this._chainOrCallHooks(n,`postAction`),n}if(this.parent?.listenerCount(r))checkForUnknownOptions(),this._processArguments(),this.parent.emit(r,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():(checkForUnknownOptions(),this._processArguments())}else this.commands.length?(checkForUnknownOptions(),this.help({error:!0})):(checkForUnknownOptions(),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 maybeOption(e){return e.length>1&&e[0]===`-`}let negativeNumberArg=e=>/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(e)?!this._getCommandAndAncestors().some(e=>e.options.map(e=>e.short).some(e=>/^-\d$/.test(e))):!1,i=null,a=null,o=0;for(;o<e.length||a;){let s=a??e[o++];if(a=null,s===`--`){r===n&&r.push(s),r.push(...e.slice(o));break}if(i&&(!maybeOption(s)||negativeNumberArg(s))){this.emit(`option:${i.name()}`,s);continue}if(i=null,maybeOption(s)){let t=this._findOption(s);if(t){if(t.required){let n=e[o++];n===void 0&&this.optionMissingArgument(t),this.emit(`option:${t.name()}`,n)}else if(t.optional){let n=null;o<e.length&&(!maybeOption(e[o])||negativeNumberArg(e[o]))&&(n=e[o++]),this.emit(`option:${t.name()}`,n)}else this.emit(`option:${t.name()}`);i=t.variadic?t:null;continue}}if(s.length>2&&s[0]===`-`&&s[1]!==`-`){let e=this._findOption(`-${s[1]}`);if(e){e.required||e.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${e.name()}`,s.slice(2)):(this.emit(`option:${e.name()}`),a=`-${s.slice(2)}`);continue}}if(/^--[^=]+=/.test(s)){let e=s.indexOf(`=`),t=this._findOption(s.slice(0,e));if(t&&(t.required||t.optional)){this.emit(`option:${t.name()}`,s.slice(e+1));continue}}if(r===t&&maybeOption(s)&&!(this.commands.length===0&&negativeNumberArg(s))&&(r=n),(this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&n.length===0){if(this._findCommand(s)){t.push(s),n.push(...e.slice(o));break}else if(this._getHelpCommand()&&s===this._getHelpCommand().name()){t.push(s,...e.slice(o));break}else if(this._defaultCommandName){n.push(s,...e.slice(o));break}}if(this._passThroughOptions){r.push(s,...e.slice(o));break}r.push(s)}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(`
18
- `),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 a.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()}`,a.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new f(this.options),hasCustomOptionValue=e=>this.getOptionValue(e)!==void 0&&![`default`,`implied`].includes(this.getOptionValueSource(e));this.options.filter(t=>t.implied!==void 0&&hasCustomOptionValue(t.attributeName())&&e.valueFromOption(this.getOptionValue(t.attributeName()),t)).forEach(e=>{Object.keys(e.implied).filter(e=>!hasCustomOptionValue(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 findBestOptionFromValue=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},getErrorMessage=e=>{let t=findBestOptionFromValue(e),n=t.attributeName();return this.getOptionValueSource(n)===`env`?`environment variable '${t.envVar}'`:`option '${t.flags}'`},n=`error: ${getErrorMessage(e)} cannot be used with ${getErrorMessage(t)}`;this.error(n,{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=p(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=p(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=>s(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=r.basename(e,r.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,baseWrite,n,r;return t?(baseWrite=e=>this._outputConfiguration.writeErr(e),n=this._outputConfiguration.getErrHasColors(),r=this._outputConfiguration.getErrHelpWidth()):(baseWrite=e=>this._outputConfiguration.writeOut(e),n=this._outputConfiguration.getOutHasColors(),r=this._outputConfiguration.getOutHelpWidth()),{error:t,write:e=>(n||(e=this._outputConfiguration.stripColor(e)),baseWrite(e)),hasColors:n,helpWidth:r}}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(a.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.
19
- 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 incrementNodeInspectorPort(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 useColor(){if(a.env.NO_COLOR||a.env.FORCE_COLOR===`0`||a.env.FORCE_COLOR===`false`)return!1;if(a.env.FORCE_COLOR||a.env.CLICOLOR_FORCE!==void 0)return!0}e.Command=m,e.useColor=useColor})),A=__commonJSMin((e=>{var{Argument:t}=T(),{Command:n}=k(),{CommanderError:r,InvalidArgumentError:i}=w(),{Help:a}=E(),{Option:o}=D();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})),{program:j,createCommand:M,createArgument:N,createOption:P,CommanderError:F,InvalidArgumentError:I,InvalidOptionArgumentError:L,Command:R,Argument:z,Option:B,Help:V}=__toESM(__commonJSMin(((e,t)=>{var n=A();e=t.exports={},e.program=new n.Command,e.Argument=n.Argument,e.Command=n.Command,e.CommanderError=n.CommanderError,e.Help=n.Help,e.InvalidArgumentError=n.InvalidArgumentError,e.InvalidOptionArgumentError=n.InvalidArgumentError,e.Option=n.Option,e.createCommand=e=>new n.Command(e),e.createOption=(e,t)=>new n.Option(e,t),e.createArgument=(e,t)=>new n.Argument(e,t)}))(),1).default;function addGeneratePageMapCommand(){j.command(`generate-page-map`).description(`Invokes the docs-plugin once to build the site data and writes it to json`).option(`-c, --config-file <configFile>`,`Path to the qui-docs.config.ts config file`).option(`-r, --routes-dir <routesDir>`,`Path to the routes directory`,`src/routes`).option(`-o, --output <output>`,`Output path for the site data json`,`site-data.json`).action(async e=>{try{let a=new n({configFile:e.configFile}).loadConfig(),c=t(i(a.appDirectory,a.pageDirectory)),l=new r({...a,srcDir:t(i(o(),a.appDirectory)),typeDocProps:{}}),u=s.sync([`${c}/**/*.mdx`,`${c}/**/*.tsx`],{absolute:!0,cwd:o()});l.buildIndex(u,!0),await d(i(o(),e.output),JSON.stringify(l.pageMap,null,2),`utf-8`)}catch(e){console.error(`Generate Site Data Error:`,e instanceof Error?e.message:String(e)),process.exit(1)}})}function isErrorResponse(e){return typeof e==`object`&&!!e&&`detail`in e}var FilesApi=class{constructor(e){this.config=e}get headers(){return{Authorization:`Bearer ${this.config.apiKey}`}}get jsonHeaders(){return{...this.headers,"Content-Type":`application/json`}}async handleResponse(e){let t=await e.json();if(isErrorResponse(t))throw Error(t.detail);return t}async upload(e,t,n){let r=new FormData,i;if(e instanceof Blob)i=e;else if(e instanceof ArrayBuffer)i=new Blob([e],{type:`text/markdown; charset=utf-8`});else{let t=new Uint8Array(e).buffer;i=new Blob([t],{type:`text/markdown; charset=utf-8`})}r.append(`file`,i,t),n?.metadata&&r.append(`metadata`,JSON.stringify(n.metadata));let a=new URLSearchParams;n?.process!==void 0&&a.set(`process`,String(n.process)),n?.processInBackground!==void 0&&a.set(`process_in_background`,String(n.processInBackground));let o=`${this.config.baseUrl}/api/v1/files/${a.toString()?`?${a}`:``}`,s=await fetch(o,{body:r,headers:this.headers,method:`POST`});return this.handleResponse(s)}async list(e=!0){let t=new URLSearchParams({content:String(e)}),n=await fetch(`${this.config.baseUrl}/api/v1/files/?${t}`,{headers:this.headers});return this.handleResponse(n)}async search(e,t=!0){let n=new URLSearchParams({content:String(t),filename:e}),r=await fetch(`${this.config.baseUrl}/api/v1/files/search?${n}`,{headers:this.headers});return r.status===404?[]:this.handleResponse(r)}async deleteAll(){let e=await fetch(`${this.config.baseUrl}/api/v1/files/all`,{headers:this.headers,method:`DELETE`});return this.handleResponse(e)}async getById(e){let t=await fetch(`${this.config.baseUrl}/api/v1/files/${e}`,{headers:this.headers});return this.handleResponse(t)}async getProcessStatus(e){let t=await fetch(`${this.config.baseUrl}/api/v1/files/${e}/process/status`,{headers:this.headers});return this.handleResponse(t)}async waitForProcessing(e,t){let n=t?.maxAttempts??120,r=t?.intervalMs??1e3;for(let t=0;t<n;t++){let t=await this.getProcessStatus(e);if(t.status===`completed`||t.status===`failed`)return t;await new Promise(e=>setTimeout(e,r))}throw Error(`File processing timed out after ${n} attempts`)}async getDataContent(e){let t=await fetch(`${this.config.baseUrl}/api/v1/files/${e}/data/content`,{headers:this.headers});return this.handleResponse(t)}async updateDataContent(e,t){let n=await fetch(`${this.config.baseUrl}/api/v1/files/${e}/data/content/update`,{body:JSON.stringify({content:t}),headers:this.jsonHeaders,method:`POST`});return this.handleResponse(n)}async getContent(e,t=!1){let n=new URLSearchParams({attachment:String(t)});return fetch(`${this.config.baseUrl}/api/v1/files/${e}/content?${n}`,{headers:this.headers})}async getContentAsText(e){let t=await this.getContent(e);if(!t.ok){let e=await t.json();throw Error(e.detail||`Failed to get file content`)}return t.text()}async delete(e){let t=await fetch(`${this.config.baseUrl}/api/v1/files/${e}`,{headers:this.headers,method:`DELETE`});return this.handleResponse(t)}},KnowledgeApi=class{constructor(e){this.config=e}get headers(){return{Authorization:`Bearer ${this.config.apiKey}`}}get jsonHeaders(){return{...this.headers,"Content-Type":`application/json`}}async handleResponse(e){let t=await e.json();if(isErrorResponse(t))throw Error(t.detail);return t}async list(){let e=await fetch(`${this.config.baseUrl}/api/v1/knowledge/`,{headers:this.headers});return this.handleResponse(e)}async listWritable(){let e=await fetch(`${this.config.baseUrl}/api/v1/knowledge/list`,{headers:this.headers});return this.handleResponse(e)}async create(e){let t=await fetch(`${this.config.baseUrl}/api/v1/knowledge/create`,{body:JSON.stringify(e),headers:this.jsonHeaders,method:`POST`});return this.handleResponse(t)}async reindex(){let e=await fetch(`${this.config.baseUrl}/api/v1/knowledge/reindex`,{headers:this.jsonHeaders,method:`POST`});return this.handleResponse(e)}async getById(e){let t=await fetch(`${this.config.baseUrl}/api/v1/knowledge/${e}`,{headers:this.headers});return this.handleResponse(t)}async update(e,t){let n=await fetch(`${this.config.baseUrl}/api/v1/knowledge/${e}/update`,{body:JSON.stringify(t),headers:this.jsonHeaders,method:`POST`});return this.handleResponse(n)}async addFile(e,t){let n=await fetch(`${this.config.baseUrl}/api/v1/knowledge/${e}/file/add`,{body:JSON.stringify({file_id:t}),headers:this.jsonHeaders,method:`POST`});return this.handleResponse(n)}async updateFile(e,t){let n=await fetch(`${this.config.baseUrl}/api/v1/knowledge/${e}/file/update`,{body:JSON.stringify({file_id:t}),headers:this.jsonHeaders,method:`POST`});return this.handleResponse(n)}async removeFile(e,t,n=!0){let r=new URLSearchParams({delete_file:String(n)}),i=await fetch(`${this.config.baseUrl}/api/v1/knowledge/${e}/file/remove?${r}`,{body:JSON.stringify({file_id:t}),headers:this.jsonHeaders,method:`POST`});return this.handleResponse(i)}async delete(e){let t=await fetch(`${this.config.baseUrl}/api/v1/knowledge/${e}/delete`,{headers:this.headers,method:`DELETE`});return this.handleResponse(t)}async reset(e){let t=await fetch(`${this.config.baseUrl}/api/v1/knowledge/${e}/reset`,{headers:this.jsonHeaders,method:`POST`});return this.handleResponse(t)}async addFilesBatch(e,t){let n=await fetch(`${this.config.baseUrl}/api/v1/knowledge/${e}/files/batch/add`,{body:JSON.stringify(t.map(e=>({file_id:e}))),headers:this.jsonHeaders,method:`POST`});return this.handleResponse(n)}};function loadEnv(){let e=j.optsWithGlobals();e.env?m({path:e.env,quiet:!0}):m({quiet:!0})}function getConfigFromEnv(){let e=process.env.WEB_UI_URL||process.env.OPEN_WEB_UI_URL,t=process.env.WEB_UI_KEY||process.env.OPEN_WEB_UI_API_KEY,n=process.env.KNOWLEDGE_ID||process.env.OPEN_WEB_UI_KNOWLEDGE_ID;if(!e||!t||!n)throw Error(`WEB_UI_URL, WEB_UI_KEY, and KNOWLEDGE_ID must be set`);return{knowledgeId:n,webUiKey:t,webUiUrl:e}}function addDownloadKnowledgeCommand(){j.command(`download-knowledge`).description(`Download files from an Open Web UI knowledge base`).requiredOption(`-o, --output-dir <outputDir>`,`Folder path`).requiredOption(`-e, --environment <environments>`,`environment to load`).action(async e=>{loadEnv();let t=e.environment;p.config({path:`.env.${t}`}),await l(e.outputDir,{recursive:!0}).catch();let n=getConfigFromEnv(),r={apiKey:n.webUiKey,baseUrl:n.webUiUrl},a=new KnowledgeApi(r),o=new FilesApi(r),s=await a.getById(n.knowledgeId);for(let t of s.files??[]){let n=t.meta?.name;if(n)try{let r=await o.getDataContent(t.id);r?.content&&await d(i(e.outputDir,n),r.content,`utf-8`)}catch{console.warn(`Failed to download ${n}`)}}})}function loadOpenWebUiEnv(e,t){let n=e.envFile??`.env.${e.id}`;m({override:!0,path:n,quiet:!0});let r=process.env.OPEN_WEB_UI_URL??process.env.WEB_UI_URL,i=process.env.OPEN_WEB_UI_API_KEY??process.env.WEB_UI_KEY,a=process.env.OPEN_WEB_UI_KNOWLEDGE_ID??process.env.KNOWLEDGE_ID;if(!r)throw Error(`Missing OPEN_WEB_UI_URL for integration "${t}" (env file: ${n})`);if(!i)throw Error(`Missing OPEN_WEB_UI_API_KEY for integration "${t}" (env file: ${n})`);if(!a)throw Error(`Missing OPEN_WEB_UI_KNOWLEDGE_ID for integration "${t}" (env file: ${n})`);return{apiKey:i,knowledgeId:a,url:r}}function resolveOpenWebUiIntegration(e,t,n){let r=loadOpenWebUiEnv(t,e);return{apiKey:r.apiKey,knowledgeId:r.knowledgeId,name:e,outputPath:n,url:r.url}}function loadOpenWebUiIntegrations(e={}){let t=new n({}).loadConfig().knowledge,r=t?.integrations?.openWebUi;if(!r||r.length===0)return[];let i=t?.outputPath??`public/exports`,a=r;if(e.integrations?.length){let t=new Set(e.integrations);a=r.filter(e=>t.has(e.id))}return a.map(e=>({integration:e,name:e.id,outputPath:i}))}var KnowledgeCleaner=class{constructor(e){let t={apiKey:e.webUiKey,baseUrl:e.webUiUrl};this.filesApi=new FilesApi(t),this.knowledgeApi=new KnowledgeApi(t)}async cleanUpOrphanedFiles(){}};function toKnowledgeFile(e){return{id:e.id,meta:{name:e.meta?.name}}}function calculateFileHash(e){let t=e.normalize(`NFC`).replace(/\r\n/g,`
17
+ - ${t?`searched for local subcommand relative to directory '${t}'`:`no directory for search for local subcommand, use .executableDir() to supply a custom directory`}`;throw Error(r)}_executeSubCommand(e,t){t=t.slice();let o=!1,s=[`.js`,`.ts`,`.tsx`,`.mjs`,`.cjs`];function l(e,t){let n=r.resolve(e,t);if(i.existsSync(n))return n;if(s.includes(r.extname(t)))return;let a=s.find(e=>i.existsSync(`${n}${e}`));if(a)return`${n}${a}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let u=e._executableFile||`${this._name}-${e._name}`,d=this._executableDir||``;if(this._scriptPath){let e;try{e=i.realpathSync(this._scriptPath)}catch{e=this._scriptPath}d=r.resolve(r.dirname(e),d)}if(d){let t=l(d,u);if(!t&&!e._executableFile&&this._scriptPath){let n=r.basename(this._scriptPath,r.extname(this._scriptPath));n!==this._name&&(t=l(d,`${n}-${e._name}`))}u=t||u}o=s.includes(r.extname(u));let f;a.platform===`win32`?(this._checkForMissingExecutable(u,d,e._name),t.unshift(u),t=h(a.execArgv).concat(t),f=n.spawn(a.execPath,t,{stdio:`inherit`})):o?(t.unshift(u),t=h(a.execArgv).concat(t),f=n.spawn(a.argv[0],t,{stdio:`inherit`})):f=n.spawn(u,t,{stdio:`inherit`}),f.killed||[`SIGUSR1`,`SIGUSR2`,`SIGTERM`,`SIGINT`,`SIGHUP`].forEach(e=>{a.on(e,()=>{f.killed===!1&&f.exitCode===null&&f.kill(e)})});let p=this._exitCallback;f.on(`close`,e=>{e??=1,p?p(new c(e,`commander.executeSubCommandAsync`,`(close)`)):a.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)a.exit(1);else{let e=new c(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*\.\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(`
18
+ `),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 a.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()}`,a.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new f(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=p(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=p(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=>s(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=r.basename(e,r.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(a.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.
19
+ 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 h(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 g(){if(a.env.NO_COLOR||a.env.FORCE_COLOR===`0`||a.env.FORCE_COLOR===`false`)return!1;if(a.env.FORCE_COLOR||a.env.CLICOLOR_FORCE!==void 0)return!0}e.Command=m,e.useColor=g})),N=C((e=>{var{Argument:t}=O(),{Command:n}=M(),{CommanderError:r,InvalidArgumentError:i}=D(),{Help:a}=k(),{Option:o}=A();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})),{program:P,createCommand:F,createArgument:I,createOption:ee,CommanderError:te,InvalidArgumentError:ne,InvalidOptionArgumentError:re,Command:ie,Argument:ae,Option:oe,Help:se}=T(C(((e,t)=>{var n=N();e=t.exports={},e.program=new n.Command,e.Argument=n.Argument,e.Command=n.Command,e.CommanderError=n.CommanderError,e.Help=n.Help,e.InvalidArgumentError=n.InvalidArgumentError,e.InvalidOptionArgumentError=n.InvalidArgumentError,e.Option=n.Option,e.createCommand=e=>new n.Command(e),e.createOption=(e,t)=>new n.Option(e,t),e.createArgument=(e,t)=>new n.Argument(e,t)}))(),1).default;async function L(t){if(!t.typeDocProps)return{};try{let n=e(i(o(),t.typeDocProps));return JSON.parse(await u(n,`utf-8`))?.props??{}}catch{return console.debug(`Invalid doc props file. Unable to parse JSON. Please check the file`),{}}}function R(){P.command(`generate-page-map`).description(`Invokes the docs-plugin once to build the site data and writes it to json`).option(`-c, --config-file <configFile>`,`Path to the qui-docs.config.ts config file`).option(`-r, --routes-dir <routesDir>`,`Path to the routes directory`,`src/routes`).option(`-o, --output <output>`,`Output path for the site data json`,`site-data.json`).action(async r=>{try{let a=new t({configFile:r.configFile}).loadConfig(),c=await L(a),l=e(i(a.appDirectory,a.pageDirectory)),u=new n({...a,srcDir:e(i(o(),a.appDirectory)),typeDocProps:c}),f=s.sync([`${l}/**/*.mdx`,`${l}/**/*.tsx`],{absolute:!0,cwd:o()});u.buildIndex(f,!0),await d(i(o(),r.output),JSON.stringify(u.pageMap,null,2),`utf-8`)}catch(e){console.error(`Generate Site Data Error:`,e instanceof Error?e.message:String(e)),process.exit(1)}})}function z(e){return typeof e==`object`&&!!e&&`detail`in e}var B=class{config;constructor(e){this.config=e}get headers(){return{Authorization:`Bearer ${this.config.apiKey}`}}get jsonHeaders(){return{...this.headers,"Content-Type":`application/json`}}async handleResponse(e){let t=await e.json();if(z(t))throw Error(t.detail);return t}async upload(e,t,n){let r=new FormData,i;if(e instanceof Blob)i=e;else if(e instanceof ArrayBuffer)i=new Blob([e],{type:`text/markdown; charset=utf-8`});else{let t=new Uint8Array(e).buffer;i=new Blob([t],{type:`text/markdown; charset=utf-8`})}r.append(`file`,i,t),n?.metadata&&r.append(`metadata`,JSON.stringify(n.metadata));let a=new URLSearchParams;n?.process!==void 0&&a.set(`process`,String(n.process)),n?.processInBackground!==void 0&&a.set(`process_in_background`,String(n.processInBackground));let o=`${this.config.baseUrl}/api/v1/files/${a.toString()?`?${a}`:``}`,s=await fetch(o,{body:r,headers:this.headers,method:`POST`});return this.handleResponse(s)}async list(e=!0){let t=new URLSearchParams({content:String(e)}),n=await fetch(`${this.config.baseUrl}/api/v1/files/?${t}`,{headers:this.headers});return this.handleResponse(n)}async search(e,t=!0){let n=new URLSearchParams({content:String(t),filename:e}),r=await fetch(`${this.config.baseUrl}/api/v1/files/search?${n}`,{headers:this.headers});return r.status===404?[]:this.handleResponse(r)}async deleteAll(){let e=await fetch(`${this.config.baseUrl}/api/v1/files/all`,{headers:this.headers,method:`DELETE`});return this.handleResponse(e)}async getById(e){let t=await fetch(`${this.config.baseUrl}/api/v1/files/${e}`,{headers:this.headers});return this.handleResponse(t)}async getProcessStatus(e){let t=await fetch(`${this.config.baseUrl}/api/v1/files/${e}/process/status`,{headers:this.headers});return this.handleResponse(t)}async waitForProcessing(e,t){let n=t?.maxAttempts??120,r=t?.intervalMs??1e3;for(let t=0;t<n;t++){let t=await this.getProcessStatus(e);if(t.status===`completed`||t.status===`failed`)return t;await new Promise(e=>setTimeout(e,r))}throw Error(`File processing timed out after ${n} attempts`)}async getDataContent(e){let t=await fetch(`${this.config.baseUrl}/api/v1/files/${e}/data/content`,{headers:this.headers});return this.handleResponse(t)}async updateDataContent(e,t){let n=await fetch(`${this.config.baseUrl}/api/v1/files/${e}/data/content/update`,{body:JSON.stringify({content:t}),headers:this.jsonHeaders,method:`POST`});return this.handleResponse(n)}async getContent(e,t=!1){let n=new URLSearchParams({attachment:String(t)});return fetch(`${this.config.baseUrl}/api/v1/files/${e}/content?${n}`,{headers:this.headers})}async getContentAsText(e){let t=await this.getContent(e);if(!t.ok){let e=await t.json();throw Error(e.detail||`Failed to get file content`)}return t.text()}async delete(e){let t=await fetch(`${this.config.baseUrl}/api/v1/files/${e}`,{headers:this.headers,method:`DELETE`});return this.handleResponse(t)}},V=class{config;constructor(e){this.config=e}get headers(){return{Authorization:`Bearer ${this.config.apiKey}`}}get jsonHeaders(){return{...this.headers,"Content-Type":`application/json`}}async handleResponse(e){let t=await e.json();if(z(t))throw Error(t.detail);return t}async list(){let e=await fetch(`${this.config.baseUrl}/api/v1/knowledge/`,{headers:this.headers});return this.handleResponse(e)}async listWritable(){let e=await fetch(`${this.config.baseUrl}/api/v1/knowledge/list`,{headers:this.headers});return this.handleResponse(e)}async create(e){let t=await fetch(`${this.config.baseUrl}/api/v1/knowledge/create`,{body:JSON.stringify(e),headers:this.jsonHeaders,method:`POST`});return this.handleResponse(t)}async reindex(){let e=await fetch(`${this.config.baseUrl}/api/v1/knowledge/reindex`,{headers:this.jsonHeaders,method:`POST`});return this.handleResponse(e)}async getById(e){let t=await fetch(`${this.config.baseUrl}/api/v1/knowledge/${e}`,{headers:this.headers});return this.handleResponse(t)}async update(e,t){let n=await fetch(`${this.config.baseUrl}/api/v1/knowledge/${e}/update`,{body:JSON.stringify(t),headers:this.jsonHeaders,method:`POST`});return this.handleResponse(n)}async addFile(e,t){let n=await fetch(`${this.config.baseUrl}/api/v1/knowledge/${e}/file/add`,{body:JSON.stringify({file_id:t}),headers:this.jsonHeaders,method:`POST`});return this.handleResponse(n)}async updateFile(e,t){let n=await fetch(`${this.config.baseUrl}/api/v1/knowledge/${e}/file/update`,{body:JSON.stringify({file_id:t}),headers:this.jsonHeaders,method:`POST`});return this.handleResponse(n)}async removeFile(e,t,n=!0){let r=new URLSearchParams({delete_file:String(n)}),i=await fetch(`${this.config.baseUrl}/api/v1/knowledge/${e}/file/remove?${r}`,{body:JSON.stringify({file_id:t}),headers:this.jsonHeaders,method:`POST`});return this.handleResponse(i)}async delete(e){let t=await fetch(`${this.config.baseUrl}/api/v1/knowledge/${e}/delete`,{headers:this.headers,method:`DELETE`});return this.handleResponse(t)}async reset(e){let t=await fetch(`${this.config.baseUrl}/api/v1/knowledge/${e}/reset`,{headers:this.jsonHeaders,method:`POST`});return this.handleResponse(t)}async addFilesBatch(e,t){let n=await fetch(`${this.config.baseUrl}/api/v1/knowledge/${e}/files/batch/add`,{body:JSON.stringify(t.map(e=>({file_id:e}))),headers:this.jsonHeaders,method:`POST`});return this.handleResponse(n)}};function H(){let e=P.optsWithGlobals();e.env?m({path:e.env,quiet:!0}):m({quiet:!0})}function U(){let e=process.env.WEB_UI_URL||process.env.OPEN_WEB_UI_URL,t=process.env.WEB_UI_KEY||process.env.OPEN_WEB_UI_API_KEY,n=process.env.KNOWLEDGE_ID||process.env.OPEN_WEB_UI_KNOWLEDGE_ID;if(!e||!t||!n)throw Error(`WEB_UI_URL, WEB_UI_KEY, and KNOWLEDGE_ID must be set`);return{knowledgeId:n,webUiKey:t,webUiUrl:e}}function W(){P.command(`download-knowledge`).description(`Download files from an Open Web UI knowledge base`).requiredOption(`-o, --output-dir <outputDir>`,`Folder path`).requiredOption(`-e, --environment <environments>`,`environment to load`).action(async e=>{H();let t=e.environment;p.config({path:`.env.${t}`}),await l(e.outputDir,{recursive:!0}).catch();let n=U(),r={apiKey:n.webUiKey,baseUrl:n.webUiUrl},a=new V(r),o=new B(r),s=await a.getById(n.knowledgeId);for(let t of s.files??[]){let n=t.meta?.name;if(n)try{let r=await o.getDataContent(t.id);r?.content&&await d(i(e.outputDir,n),r.content,`utf-8`)}catch{console.warn(`Failed to download ${n}`)}}})}function G(e,t){let n=e.envFile??`.env.${e.id}`;m({override:!0,path:n,quiet:!0});let r=process.env.OPEN_WEB_UI_URL??process.env.WEB_UI_URL,i=process.env.OPEN_WEB_UI_API_KEY??process.env.WEB_UI_KEY,a=process.env.OPEN_WEB_UI_KNOWLEDGE_ID??process.env.KNOWLEDGE_ID;if(!r)throw Error(`Missing OPEN_WEB_UI_URL for integration "${t}" (env file: ${n})`);if(!i)throw Error(`Missing OPEN_WEB_UI_API_KEY for integration "${t}" (env file: ${n})`);if(!a)throw Error(`Missing OPEN_WEB_UI_KNOWLEDGE_ID for integration "${t}" (env file: ${n})`);return{apiKey:i,knowledgeId:a,url:r}}function K(e,t,n){let r=G(t,e);return{apiKey:r.apiKey,knowledgeId:r.knowledgeId,name:e,outputPath:n,url:r.url}}function q(e={}){let n=new t({}).loadConfig().knowledge,r=n?.integrations?.openWebUi;if(!r||r.length===0)return[];let i=n?.outputPath??`public/exports`,a=r;if(e.integrations?.length){let t=new Set(e.integrations);a=r.filter(e=>t.has(e.id))}return a.map(e=>({integration:e,name:e.id,outputPath:i}))}var J=class{filesApi;knowledgeApi;constructor(e){let t={apiKey:e.webUiKey,baseUrl:e.webUiUrl};this.filesApi=new B(t),this.knowledgeApi=new V(t)}async cleanUpOrphanedFiles(){}};function Y(e){return{id:e.id,meta:{name:e.meta?.name}}}function X(e){let t=e.normalize(`NFC`).replace(/\r\n/g,`
20
20
  `).replace(/\r/g,`
21
- `).replace(/\n+$/,``);return f(`sha256`).update(t).digest(`hex`)}var Uploader=class{constructor(e){this.fileHashCache=new Map,this.knowledgeFilesCache=null,this.config=e;let t={apiKey:e.webUiKey,baseUrl:e.webUiUrl};this.knowledgeApi=new KnowledgeApi(t),this.filesApi=new FilesApi(t),this.cleaner=new KnowledgeCleaner(e)}async buildHashCache(e){let t=(await Promise.allSettled(e.map(async e=>{try{let t=await this.filesApi.getDataContent(e.id);t?.content&&this.fileHashCache.set(e.id,calculateFileHash(t.content))}catch{}}))).filter(e=>e.status===`rejected`);t.length>0&&console.warn(`Failed to cache ${t.length} file hashes`)}async waitForFileDeletion(e,t,n=15){let r=g(`File changed, deleting ${t}`).start();for(let t=0;t<n;t++){if(this.knowledgeFilesCache=null,!((await this.knowledgeApi.getById(this.config.knowledgeId)).files??[]).some(t=>t.id===e))return this.fileHashCache.delete(e),r.succeed(`File deleted: ${e}`),!0;await h(100*(t+1))}return r.stop(),console.debug(`File ${e} may not have been fully deleted`),!1}async uploadWithRetry(e,t,n=10){for(let r=0;r<n;r++){let i=await this.uploadFile(e,t);if(i.success)return i;if(i.error?.detail?.includes(`Duplicate content detected`)){if(console.warn(`Duplicate content: ${e} is already in knowledge base, skipping`),i.error.fileId)try{console.debug(`Removing duplicate file: ${i.error.fileId}`),await this.filesApi.delete(i.error.fileId),await this.waitForFileDeletion(i.error.fileId,e)}catch(e){console.debug(`Failed to remove duplicate file`,e)}return{skipped:!0,success:!0}}if(r<n-1){let t=100*2**r;console.debug(`Retrying ${e} in ${t}ms (attempt ${r+2}/${n})`),await h(t)}}return console.debug(`Failed to upload ${e}`),{success:!1}}async uploadFiles(e){let t=await this.knowledgeApi.getById(this.config.knowledgeId),n=t.files?.length?t.files.map(toKnowledgeFile):await this.filesApi.list().then(e=>e.filter(e=>e.meta.collection_name===t.id));this.knowledgeFilesCache=n,await this.buildHashCache(this.knowledgeFilesCache);let r=0,i=0,a=0;for(let t of e){let e=await this.uploadWithRetry(t.name,t.contents);e.skipped?r++:e.success?i++:a++}let o=new Set(e.map(e=>e.name)),s=n.filter(e=>e.meta.name&&!o.has(e.meta.name));for(let e of s)try{let t=g(`Removing stale file: ${e.meta.name}`).start();await this.knowledgeApi.removeFile(this.config.knowledgeId,e.id,!0),t.succeed(`Removed stale file: ${e.meta.name}`)}catch(t){console.warn(`Failed to remove stale file ${e.meta.name}:`,t)}r>0&&console.debug(`Skipped uploading ${r} files because their contents did not change`),i>0&&console.debug(`Successfully uploaded ${i} files`),s.length>0&&console.debug(`Removed ${s.length} stale file(s)`),a>0&&console.debug(`Failed to upload ${a} files`)}async uploadFile(e,t){let n=(this.knowledgeFilesCache??[]).find(t=>t.meta.name===e),r=calculateFileHash(t);if(n&&!this.config.force&&this.fileHashCache.get(n.id)===r)return{skipped:!0,success:!0};if(n)try{let r=n.id,i=g(`Updating ${e}`).start();return await this.filesApi.updateDataContent(r,t),await this.knowledgeApi.updateFile(this.config.knowledgeId,r),i.succeed(`Updated ${e}`),{success:!0}}catch(t){return console.warn(`Failed to update existing file ${e}:`,t),{success:!1}}let i=g(`Uploading ${e}`).start(),a=Buffer.from(t,`utf-8`),o;try{let t=await this.filesApi.upload(a,e,{processInBackground:!1});if(o=t.id,!t.id||!t.filename)return i.fail(`Error uploading ${e}`),{error:{fileId:t.id,uploadResponse:t},success:!1};i.text=`Associating ${e} with knowledge base`;let n=await this.knowledgeApi.addFile(this.config.knowledgeId,t.id);return n.name?(i.succeed(`${e} associated with knowledge base`),this.fileHashCache.set(t.id,r),{success:!0}):(i.stop(),{error:{addResponse:n,fileId:t.id},success:!1})}catch(t){return i.fail(`Error uploading ${e}`),{error:{detail:t instanceof Error?t.message:String(t),fileId:o},success:!1}}}async uploadFromPagesJson(e){let t=await u(e,`utf-8`),n=JSON.parse(t).pages.map(e=>({contents:e.content,name:`${e.pageId}.md`}));return this.uploadFiles(n)}async uploadKnowledge(){await this.cleaner.cleanUpOrphanedFiles();let e=i(this.config.knowledgeFilePath),t=e.endsWith(`pages.json`)?e:i(e,`pages.json`);if(!await c(t).then(()=>!0).catch(()=>!1))throw Error(`pages.json not found at ${t}`);return this.uploadFromPagesJson(t)}};function addUploadKnowledgeCommand(){function getUploader(e,t){let n=getConfigFromEnv(),r=e||process.env.KNOWLEDGE_OUTPUT_PATH||`public/exports`;if(!r)throw Error(`KNOWLEDGE_FILE_PATH must be set or provided as the --path option`);return new Uploader({...n,force:t,knowledgeFilePath:r})}j.name(`upload-knowledge`).description(`Upload files to OpenWebUI knowledge base`).command(`upload-knowledge`).option(`-p, --path <path>`,`Path to file or folder relative to script`).option(`--force`,`force upload files, even if their contents have not changed`).option(`-i, --integration <integrations>`,`Comma-separated list of integrations to upload to (default: all)`).action(async e=>{loadEnv();let t=e.integration?.split(`,`).map(e=>e.trim()).filter(Boolean),n=loadOpenWebUiIntegrations({integrations:t});if(n.length===0)return console.log(`No integrations configured, using legacy env vars`),getUploader(e.path,e.force).uploadKnowledge();let r=0,i=0;for(let{integration:t,name:a,outputPath:o}of n){console.log(`\n[${a}] Uploading to OpenWebUI...`);try{let n=resolveOpenWebUiIntegration(a,t,o);await new Uploader({force:e.force,knowledgeFilePath:e.path??n.outputPath,knowledgeId:n.knowledgeId,webUiKey:n.apiKey,webUiUrl:n.url}).uploadKnowledge(),r++,console.log(`[${a}] Upload complete`)}catch(e){i++,console.error(`[${a}] Upload failed:`,e)}}n.length>1&&console.log(`\nUploaded to ${r} integration(s)${i>0?`, ${i} failed`:``}`)}),j.command(`get-knowledge-files`).description(`Get files from OpenWebUI knowledge base`).option(`-p, --path <path>`,`Path to file or folder relative to script`).action(async e=>{loadEnv();let t=getUploader(e.path),n=await t.filesApi.search(`*`);console.debug(`found ${n.length} files`),a(i(t.config.knowledgeFilePath,`files.json`),JSON.stringify(n,null,2),`utf-8`)}),j.command(`clear-knowledge`).description(`Remove all files from the knowledge base collection`).action(async()=>{loadEnv();let e=getConfigFromEnv(),t={apiKey:e.webUiKey,baseUrl:e.webUiUrl},n=new FilesApi(t),r=new KnowledgeApi(t);await new KnowledgeCleaner(e).cleanUpOrphanedFiles();let i=await r.getById(e.knowledgeId),a=i.files??[];if(!i){console.log(`Knowledge base not found`);return}let o=await n.list(!1).then(e=>e.filter(e=>e.meta?.collection_name===i.id));if(o.length===0){console.log(`No files in knowledge base`);return}console.log(`Removing ${o.length} files from knowledge base...`);for(let e of o)a.some(t=>t.id===e.id)?await r.removeFile(i.id,e.id,!0):await n.delete(e.id),console.log(`Removed ${e.id}`);console.log(`Removed ${o.length} files`)})}function setupCli(){j.option(`--env <envFile>`,`relative path to the env file to use`),addUploadKnowledgeCommand(),addDownloadKnowledgeCommand(),addGeneratePageMapCommand(),j.parse()}setupCli();export{};
21
+ `).replace(/\n+$/,``);return f(`sha256`).update(t).digest(`hex`)}var Z=class{config;knowledgeApi;filesApi;fileHashCache=new Map;knowledgeFilesCache=null;cleaner;constructor(e){this.config=e;let t={apiKey:e.webUiKey,baseUrl:e.webUiUrl};this.knowledgeApi=new V(t),this.filesApi=new B(t),this.cleaner=new J(e)}async buildHashCache(e){let t=(await Promise.allSettled(e.map(async e=>{try{let t=await this.filesApi.getDataContent(e.id);t?.content&&this.fileHashCache.set(e.id,X(t.content))}catch{}}))).filter(e=>e.status===`rejected`);t.length>0&&console.warn(`Failed to cache ${t.length} file hashes`)}async waitForFileDeletion(e,t,n=15){let r=g(`File changed, deleting ${t}`).start();for(let t=0;t<n;t++){if(this.knowledgeFilesCache=null,!((await this.knowledgeApi.getById(this.config.knowledgeId)).files??[]).some(t=>t.id===e))return this.fileHashCache.delete(e),r.succeed(`File deleted: ${e}`),!0;await h(100*(t+1))}return r.stop(),console.debug(`File ${e} may not have been fully deleted`),!1}async uploadWithRetry(e,t,n=10){for(let r=0;r<n;r++){let i=await this.uploadFile(e,t);if(i.success)return i;if(i.error?.detail?.includes(`Duplicate content detected`)){if(console.warn(`Duplicate content: ${e} is already in knowledge base, skipping`),i.error.fileId)try{console.debug(`Removing duplicate file: ${i.error.fileId}`),await this.filesApi.delete(i.error.fileId),await this.waitForFileDeletion(i.error.fileId,e)}catch(e){console.debug(`Failed to remove duplicate file`,e)}return{skipped:!0,success:!0}}if(r<n-1){let t=100*2**r;console.debug(`Retrying ${e} in ${t}ms (attempt ${r+2}/${n})`),await h(t)}}return console.debug(`Failed to upload ${e}`),{success:!1}}async uploadFiles(e){let t=await this.knowledgeApi.getById(this.config.knowledgeId),n=t.files?.length?t.files.map(Y):await this.filesApi.list().then(e=>e.filter(e=>e.meta.collection_name===t.id));this.knowledgeFilesCache=n,await this.buildHashCache(this.knowledgeFilesCache);let r=0,i=0,a=0;for(let t of e){let e=await this.uploadWithRetry(t.name,t.contents);e.skipped?r++:e.success?i++:a++}let o=new Set(e.map(e=>e.name)),s=n.filter(e=>e.meta.name&&!o.has(e.meta.name));for(let e of s)try{let t=g(`Removing stale file: ${e.meta.name}`).start();await this.knowledgeApi.removeFile(this.config.knowledgeId,e.id,!0),t.succeed(`Removed stale file: ${e.meta.name}`)}catch(t){console.warn(`Failed to remove stale file ${e.meta.name}:`,t)}r>0&&console.debug(`Skipped uploading ${r} files because their contents did not change`),i>0&&console.debug(`Successfully uploaded ${i} files`),s.length>0&&console.debug(`Removed ${s.length} stale file(s)`),a>0&&console.debug(`Failed to upload ${a} files`)}async uploadFile(e,t){let n=(this.knowledgeFilesCache??[]).find(t=>t.meta.name===e),r=X(t);if(n&&!this.config.force&&this.fileHashCache.get(n.id)===r)return{skipped:!0,success:!0};if(n)try{let r=n.id,i=g(`Updating ${e}`).start();return await this.filesApi.updateDataContent(r,t),await this.knowledgeApi.updateFile(this.config.knowledgeId,r),i.succeed(`Updated ${e}`),{success:!0}}catch(t){return console.warn(`Failed to update existing file ${e}:`,t),{success:!1}}let i=g(`Uploading ${e}`).start(),a=Buffer.from(t,`utf-8`),o;try{let t=await this.filesApi.upload(a,e,{processInBackground:!1});if(o=t.id,!t.id||!t.filename)return i.fail(`Error uploading ${e}`),{error:{fileId:t.id,uploadResponse:t},success:!1};i.text=`Associating ${e} with knowledge base`;let n=await this.knowledgeApi.addFile(this.config.knowledgeId,t.id);return n.name?(i.succeed(`${e} associated with knowledge base`),this.fileHashCache.set(t.id,r),{success:!0}):(i.stop(),{error:{addResponse:n,fileId:t.id},success:!1})}catch(t){return i.fail(`Error uploading ${e}`),{error:{detail:t instanceof Error?t.message:String(t),fileId:o},success:!1}}}async uploadFromPagesJson(e){let t=await u(e,`utf-8`),n=JSON.parse(t).pages.map(e=>({contents:e.content,name:`${e.pageId}.md`}));return this.uploadFiles(n)}async uploadKnowledge(){await this.cleaner.cleanUpOrphanedFiles();let e=i(this.config.knowledgeFilePath),t=e.endsWith(`pages.json`)?e:i(e,`pages.json`);if(!await c(t).then(()=>!0).catch(()=>!1))throw Error(`pages.json not found at ${t}`);return this.uploadFromPagesJson(t)}};function Q(){function e(e,t){let n=U(),r=e||process.env.KNOWLEDGE_OUTPUT_PATH||`public/exports`;if(!r)throw Error(`KNOWLEDGE_FILE_PATH must be set or provided as the --path option`);return new Z({...n,force:t,knowledgeFilePath:r})}P.name(`upload-knowledge`).description(`Upload files to OpenWebUI knowledge base`).command(`upload-knowledge`).option(`-p, --path <path>`,`Path to file or folder relative to script`).option(`--force`,`force upload files, even if their contents have not changed`).option(`-i, --integration <integrations>`,`Comma-separated list of integrations to upload to (default: all)`).action(async t=>{H();let n=t.integration?.split(`,`).map(e=>e.trim()).filter(Boolean),r=q({integrations:n});if(r.length===0)return console.log(`No integrations configured, using legacy env vars`),e(t.path,t.force).uploadKnowledge();let i=0,a=0;for(let{integration:e,name:n,outputPath:o}of r){console.log(`\n[${n}] Uploading to OpenWebUI...`);try{let r=K(n,e,o);await new Z({force:t.force,knowledgeFilePath:t.path??r.outputPath,knowledgeId:r.knowledgeId,webUiKey:r.apiKey,webUiUrl:r.url}).uploadKnowledge(),i++,console.log(`[${n}] Upload complete`)}catch(e){a++,console.error(`[${n}] Upload failed:`,e)}}r.length>1&&console.log(`\nUploaded to ${i} integration(s)${a>0?`, ${a} failed`:``}`)}),P.command(`get-knowledge-files`).description(`Get files from OpenWebUI knowledge base`).option(`-p, --path <path>`,`Path to file or folder relative to script`).action(async t=>{H();let n=e(t.path),r=await n.filesApi.search(`*`);console.debug(`found ${r.length} files`),a(i(n.config.knowledgeFilePath,`files.json`),JSON.stringify(r,null,2),`utf-8`)}),P.command(`clear-knowledge`).description(`Remove all files from the knowledge base collection`).action(async()=>{H();let e=U(),t={apiKey:e.webUiKey,baseUrl:e.webUiUrl},n=new B(t),r=new V(t);await new J(e).cleanUpOrphanedFiles();let i=await r.getById(e.knowledgeId),a=i.files??[];if(!i){console.log(`Knowledge base not found`);return}let o=await n.list(!1).then(e=>e.filter(e=>e.meta?.collection_name===i.id));if(o.length===0){console.log(`No files in knowledge base`);return}console.log(`Removing ${o.length} files from knowledge base...`);for(let e of o)a.some(t=>t.id===e.id)?await r.removeFile(i.id,e.id,!0):await n.delete(e.id),console.log(`Removed ${e.id}`);console.log(`Removed ${o.length} files`)})}function $(){P.option(`--env <envFile>`,`relative path to the env file to use`),Q(),W(),R(),P.parse()}$();export{};
22
22
  //# sourceMappingURL=cli.js.map