@qualcomm-ui/mdx-vite 1.1.0 → 2.0.0

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.map CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../../../../node_modules/.pnpm/commander@14.0.2/node_modules/commander/lib/error.js", "../../../../node_modules/.pnpm/commander@14.0.2/node_modules/commander/lib/argument.js", "../../../../node_modules/.pnpm/commander@14.0.2/node_modules/commander/lib/help.js", "../../../../node_modules/.pnpm/commander@14.0.2/node_modules/commander/lib/option.js", "../../../../node_modules/.pnpm/commander@14.0.2/node_modules/commander/lib/suggestSimilar.js", "../../../../node_modules/.pnpm/commander@14.0.2/node_modules/commander/lib/command.js", "../../../../node_modules/.pnpm/commander@14.0.2/node_modules/commander/index.js", "../../../../node_modules/.pnpm/@commander-js+extra-typings@14.0.0_commander@14.0.2/node_modules/@commander-js/extra-typings/index.js", "../../../../node_modules/.pnpm/@commander-js+extra-typings@14.0.0_commander@14.0.2/node_modules/@commander-js/extra-typings/esm.mjs", "../src/open-web-ui-knowledge/download-knowledge.ts", "../src/open-web-ui-knowledge/common.ts", "../src/open-web-ui-knowledge/generate-knowledge.ts", "../src/docs-plugin/docs-plugin.ts", "../src/docs-plugin/internal/config-loader.ts", "../src/docs-plugin/internal/config-schema.ts", "../src/docs-plugin/internal/zod.ts", "../src/docs-plugin/internal/utils.ts", "../src/docs-plugin/internal/search-indexer.ts", "../src/docs-plugin/internal/services/doc-props/doc-props-indexer.ts", "../src/docs-plugin/internal/services/markdown/markdown-file-reader.ts", "../src/docs-plugin/internal/services/markdown/markdown-indexer.ts", "../src/docs-plugin/rehype/rehype-slug.ts", "../src/docs-plugin/remark/remark-alerts.ts", "../src/docs-plugin/internal/services/markdown/remark-remove-code-blocks.ts", "../src/docs-plugin/internal/services/markdown/remark-remove-jsx.ts", "../src/docs-plugin/internal/services/nav-builder/get-route-meta.ts", "../src/docs-plugin/internal/services/nav-builder/nav-builder.ts", "../src/docs-plugin/internal/services/nav-builder/page-map.ts", "../src/docs-plugin/internal/transform-route-meta-array.ts", "../src/docs-plugin/mdx-plugins.ts", "../src/exports.ts", "../src/docs-plugin/rehype/rehype-sectionize.ts", "../src/docs-plugin/remark/remark-code-tabs.ts", "../src/docs-plugin/remark/remark-self-link-headings.ts", "../src/docs-plugin/remark/remark-spoilers.ts", "../src/open-web-ui-knowledge/load-config-from-env.ts", "../src/open-web-ui-knowledge/upload-knowledge.ts", "../src/react-demo-plugin/generate-lazy-demo-map.ts", "../src/react-demo-plugin/demo-plugin-utils.ts", "../src/cli.ts"],
4
- "sourcesContent": ["/**\n * CommanderError class\n */\nclass CommanderError extends Error {\n /**\n * Constructs the CommanderError class\n * @param {number} exitCode suggested exit code which could be used with process.exit\n * @param {string} code an id string representing the error\n * @param {string} message human-readable description of the error\n */\n constructor(exitCode, code, message) {\n super(message);\n // properly capture stack trace in Node.js\n Error.captureStackTrace(this, this.constructor);\n this.name = this.constructor.name;\n this.code = code;\n this.exitCode = exitCode;\n this.nestedError = undefined;\n }\n}\n\n/**\n * InvalidArgumentError class\n */\nclass InvalidArgumentError extends CommanderError {\n /**\n * Constructs the InvalidArgumentError class\n * @param {string} [message] explanation of why argument is invalid\n */\n constructor(message) {\n super(1, 'commander.invalidArgument', message);\n // properly capture stack trace in Node.js\n Error.captureStackTrace(this, this.constructor);\n this.name = this.constructor.name;\n }\n}\n\nexports.CommanderError = CommanderError;\nexports.InvalidArgumentError = InvalidArgumentError;\n", "const { InvalidArgumentError } = require('./error.js');\n\nclass Argument {\n /**\n * Initialize a new command argument with the given name and description.\n * The default is that the argument is required, and you can explicitly\n * indicate this with <> around the name. Put [] around the name for an optional argument.\n *\n * @param {string} name\n * @param {string} [description]\n */\n\n constructor(name, description) {\n this.description = description || '';\n this.variadic = false;\n this.parseArg = undefined;\n this.defaultValue = undefined;\n this.defaultValueDescription = undefined;\n this.argChoices = undefined;\n\n switch (name[0]) {\n case '<': // e.g. <required>\n this.required = true;\n this._name = name.slice(1, -1);\n break;\n case '[': // e.g. [optional]\n this.required = false;\n this._name = name.slice(1, -1);\n break;\n default:\n this.required = true;\n this._name = name;\n break;\n }\n\n if (this._name.endsWith('...')) {\n this.variadic = true;\n this._name = this._name.slice(0, -3);\n }\n }\n\n /**\n * Return argument name.\n *\n * @return {string}\n */\n\n name() {\n return this._name;\n }\n\n /**\n * @package\n */\n\n _collectValue(value, previous) {\n if (previous === this.defaultValue || !Array.isArray(previous)) {\n return [value];\n }\n\n previous.push(value);\n return previous;\n }\n\n /**\n * Set the default value, and optionally supply the description to be displayed in the help.\n *\n * @param {*} value\n * @param {string} [description]\n * @return {Argument}\n */\n\n default(value, description) {\n this.defaultValue = value;\n this.defaultValueDescription = description;\n return this;\n }\n\n /**\n * Set the custom handler for processing CLI command arguments into argument values.\n *\n * @param {Function} [fn]\n * @return {Argument}\n */\n\n argParser(fn) {\n this.parseArg = fn;\n return this;\n }\n\n /**\n * Only allow argument value to be one of choices.\n *\n * @param {string[]} values\n * @return {Argument}\n */\n\n choices(values) {\n this.argChoices = values.slice();\n this.parseArg = (arg, previous) => {\n if (!this.argChoices.includes(arg)) {\n throw new InvalidArgumentError(\n `Allowed choices are ${this.argChoices.join(', ')}.`,\n );\n }\n if (this.variadic) {\n return this._collectValue(arg, previous);\n }\n return arg;\n };\n return this;\n }\n\n /**\n * Make argument required.\n *\n * @returns {Argument}\n */\n argRequired() {\n this.required = true;\n return this;\n }\n\n /**\n * Make argument optional.\n *\n * @returns {Argument}\n */\n argOptional() {\n this.required = false;\n return this;\n }\n}\n\n/**\n * Takes an argument and returns its human readable equivalent for help usage.\n *\n * @param {Argument} arg\n * @return {string}\n * @private\n */\n\nfunction humanReadableArgName(arg) {\n const nameOutput = arg.name() + (arg.variadic === true ? '...' : '');\n\n return arg.required ? '<' + nameOutput + '>' : '[' + nameOutput + ']';\n}\n\nexports.Argument = Argument;\nexports.humanReadableArgName = humanReadableArgName;\n", "const { humanReadableArgName } = require('./argument.js');\n\n/**\n * TypeScript import types for JSDoc, used by Visual Studio Code IntelliSense and `npm run typescript-checkJS`\n * https://www.typescriptlang.org/docs/handbook/jsdoc-supported-types.html#import-types\n * @typedef { import(\"./argument.js\").Argument } Argument\n * @typedef { import(\"./command.js\").Command } Command\n * @typedef { import(\"./option.js\").Option } Option\n */\n\n// Although this is a class, methods are static in style to allow override using subclass or just functions.\nclass Help {\n constructor() {\n this.helpWidth = undefined;\n this.minWidthToWrap = 40;\n this.sortSubcommands = false;\n this.sortOptions = false;\n this.showGlobalOptions = false;\n }\n\n /**\n * prepareContext is called by Commander after applying overrides from `Command.configureHelp()`\n * and just before calling `formatHelp()`.\n *\n * Commander just uses the helpWidth and the rest is provided for optional use by more complex subclasses.\n *\n * @param {{ error?: boolean, helpWidth?: number, outputHasColors?: boolean }} contextOptions\n */\n prepareContext(contextOptions) {\n this.helpWidth = this.helpWidth ?? contextOptions.helpWidth ?? 80;\n }\n\n /**\n * Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.\n *\n * @param {Command} cmd\n * @returns {Command[]}\n */\n\n visibleCommands(cmd) {\n const visibleCommands = cmd.commands.filter((cmd) => !cmd._hidden);\n const helpCommand = cmd._getHelpCommand();\n if (helpCommand && !helpCommand._hidden) {\n visibleCommands.push(helpCommand);\n }\n if (this.sortSubcommands) {\n visibleCommands.sort((a, b) => {\n // @ts-ignore: because overloaded return type\n return a.name().localeCompare(b.name());\n });\n }\n return visibleCommands;\n }\n\n /**\n * Compare options for sort.\n *\n * @param {Option} a\n * @param {Option} b\n * @returns {number}\n */\n compareOptions(a, b) {\n const getSortKey = (option) => {\n // WYSIWYG for order displayed in help. Short used for comparison if present. No special handling for negated.\n return option.short\n ? option.short.replace(/^-/, '')\n : option.long.replace(/^--/, '');\n };\n return getSortKey(a).localeCompare(getSortKey(b));\n }\n\n /**\n * Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.\n *\n * @param {Command} cmd\n * @returns {Option[]}\n */\n\n visibleOptions(cmd) {\n const visibleOptions = cmd.options.filter((option) => !option.hidden);\n // Built-in help option.\n const helpOption = cmd._getHelpOption();\n if (helpOption && !helpOption.hidden) {\n // Automatically hide conflicting flags. Bit dubious but a historical behaviour that is convenient for single-command programs.\n const removeShort = helpOption.short && cmd._findOption(helpOption.short);\n const removeLong = helpOption.long && cmd._findOption(helpOption.long);\n if (!removeShort && !removeLong) {\n visibleOptions.push(helpOption); // no changes needed\n } else if (helpOption.long && !removeLong) {\n visibleOptions.push(\n cmd.createOption(helpOption.long, helpOption.description),\n );\n } else if (helpOption.short && !removeShort) {\n visibleOptions.push(\n cmd.createOption(helpOption.short, helpOption.description),\n );\n }\n }\n if (this.sortOptions) {\n visibleOptions.sort(this.compareOptions);\n }\n return visibleOptions;\n }\n\n /**\n * Get an array of the visible global options. (Not including help.)\n *\n * @param {Command} cmd\n * @returns {Option[]}\n */\n\n visibleGlobalOptions(cmd) {\n if (!this.showGlobalOptions) return [];\n\n const globalOptions = [];\n for (\n let ancestorCmd = cmd.parent;\n ancestorCmd;\n ancestorCmd = ancestorCmd.parent\n ) {\n const visibleOptions = ancestorCmd.options.filter(\n (option) => !option.hidden,\n );\n globalOptions.push(...visibleOptions);\n }\n if (this.sortOptions) {\n globalOptions.sort(this.compareOptions);\n }\n return globalOptions;\n }\n\n /**\n * Get an array of the arguments if any have a description.\n *\n * @param {Command} cmd\n * @returns {Argument[]}\n */\n\n visibleArguments(cmd) {\n // Side effect! Apply the legacy descriptions before the arguments are displayed.\n if (cmd._argsDescription) {\n cmd.registeredArguments.forEach((argument) => {\n argument.description =\n argument.description || cmd._argsDescription[argument.name()] || '';\n });\n }\n\n // If there are any arguments with a description then return all the arguments.\n if (cmd.registeredArguments.find((argument) => argument.description)) {\n return cmd.registeredArguments;\n }\n return [];\n }\n\n /**\n * Get the command term to show in the list of subcommands.\n *\n * @param {Command} cmd\n * @returns {string}\n */\n\n subcommandTerm(cmd) {\n // Legacy. Ignores custom usage string, and nested commands.\n const args = cmd.registeredArguments\n .map((arg) => humanReadableArgName(arg))\n .join(' ');\n return (\n cmd._name +\n (cmd._aliases[0] ? '|' + cmd._aliases[0] : '') +\n (cmd.options.length ? ' [options]' : '') + // simplistic check for non-help option\n (args ? ' ' + args : '')\n );\n }\n\n /**\n * Get the option term to show in the list of options.\n *\n * @param {Option} option\n * @returns {string}\n */\n\n optionTerm(option) {\n return option.flags;\n }\n\n /**\n * Get the argument term to show in the list of arguments.\n *\n * @param {Argument} argument\n * @returns {string}\n */\n\n argumentTerm(argument) {\n return argument.name();\n }\n\n /**\n * Get the longest command term length.\n *\n * @param {Command} cmd\n * @param {Help} helper\n * @returns {number}\n */\n\n longestSubcommandTermLength(cmd, helper) {\n return helper.visibleCommands(cmd).reduce((max, command) => {\n return Math.max(\n max,\n this.displayWidth(\n helper.styleSubcommandTerm(helper.subcommandTerm(command)),\n ),\n );\n }, 0);\n }\n\n /**\n * Get the longest option term length.\n *\n * @param {Command} cmd\n * @param {Help} helper\n * @returns {number}\n */\n\n longestOptionTermLength(cmd, helper) {\n return helper.visibleOptions(cmd).reduce((max, option) => {\n return Math.max(\n max,\n this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))),\n );\n }, 0);\n }\n\n /**\n * Get the longest global option term length.\n *\n * @param {Command} cmd\n * @param {Help} helper\n * @returns {number}\n */\n\n longestGlobalOptionTermLength(cmd, helper) {\n return helper.visibleGlobalOptions(cmd).reduce((max, option) => {\n return Math.max(\n max,\n this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))),\n );\n }, 0);\n }\n\n /**\n * Get the longest argument term length.\n *\n * @param {Command} cmd\n * @param {Help} helper\n * @returns {number}\n */\n\n longestArgumentTermLength(cmd, helper) {\n return helper.visibleArguments(cmd).reduce((max, argument) => {\n return Math.max(\n max,\n this.displayWidth(\n helper.styleArgumentTerm(helper.argumentTerm(argument)),\n ),\n );\n }, 0);\n }\n\n /**\n * Get the command usage to be displayed at the top of the built-in help.\n *\n * @param {Command} cmd\n * @returns {string}\n */\n\n commandUsage(cmd) {\n // Usage\n let cmdName = cmd._name;\n if (cmd._aliases[0]) {\n cmdName = cmdName + '|' + cmd._aliases[0];\n }\n let ancestorCmdNames = '';\n for (\n let ancestorCmd = cmd.parent;\n ancestorCmd;\n ancestorCmd = ancestorCmd.parent\n ) {\n ancestorCmdNames = ancestorCmd.name() + ' ' + ancestorCmdNames;\n }\n return ancestorCmdNames + cmdName + ' ' + cmd.usage();\n }\n\n /**\n * Get the description for the command.\n *\n * @param {Command} cmd\n * @returns {string}\n */\n\n commandDescription(cmd) {\n // @ts-ignore: because overloaded return type\n return cmd.description();\n }\n\n /**\n * Get the subcommand summary to show in the list of subcommands.\n * (Fallback to description for backwards compatibility.)\n *\n * @param {Command} cmd\n * @returns {string}\n */\n\n subcommandDescription(cmd) {\n // @ts-ignore: because overloaded return type\n return cmd.summary() || cmd.description();\n }\n\n /**\n * Get the option description to show in the list of options.\n *\n * @param {Option} option\n * @return {string}\n */\n\n optionDescription(option) {\n const extraInfo = [];\n\n if (option.argChoices) {\n extraInfo.push(\n // use stringify to match the display of the default value\n `choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(', ')}`,\n );\n }\n if (option.defaultValue !== undefined) {\n // default for boolean and negated more for programmer than end user,\n // but show true/false for boolean option as may be for hand-rolled env or config processing.\n const showDefault =\n option.required ||\n option.optional ||\n (option.isBoolean() && typeof option.defaultValue === 'boolean');\n if (showDefault) {\n extraInfo.push(\n `default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`,\n );\n }\n }\n // preset for boolean and negated are more for programmer than end user\n if (option.presetArg !== undefined && option.optional) {\n extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);\n }\n if (option.envVar !== undefined) {\n extraInfo.push(`env: ${option.envVar}`);\n }\n if (extraInfo.length > 0) {\n const extraDescription = `(${extraInfo.join(', ')})`;\n if (option.description) {\n return `${option.description} ${extraDescription}`;\n }\n return extraDescription;\n }\n\n return option.description;\n }\n\n /**\n * Get the argument description to show in the list of arguments.\n *\n * @param {Argument} argument\n * @return {string}\n */\n\n argumentDescription(argument) {\n const extraInfo = [];\n if (argument.argChoices) {\n extraInfo.push(\n // use stringify to match the display of the default value\n `choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(', ')}`,\n );\n }\n if (argument.defaultValue !== undefined) {\n extraInfo.push(\n `default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`,\n );\n }\n if (extraInfo.length > 0) {\n const extraDescription = `(${extraInfo.join(', ')})`;\n if (argument.description) {\n return `${argument.description} ${extraDescription}`;\n }\n return extraDescription;\n }\n return argument.description;\n }\n\n /**\n * Format a list of items, given a heading and an array of formatted items.\n *\n * @param {string} heading\n * @param {string[]} items\n * @param {Help} helper\n * @returns string[]\n */\n formatItemList(heading, items, helper) {\n if (items.length === 0) return [];\n\n return [helper.styleTitle(heading), ...items, ''];\n }\n\n /**\n * Group items by their help group heading.\n *\n * @param {Command[] | Option[]} unsortedItems\n * @param {Command[] | Option[]} visibleItems\n * @param {Function} getGroup\n * @returns {Map<string, Command[] | Option[]>}\n */\n groupItems(unsortedItems, visibleItems, getGroup) {\n const result = new Map();\n // Add groups in order of appearance in unsortedItems.\n unsortedItems.forEach((item) => {\n const group = getGroup(item);\n if (!result.has(group)) result.set(group, []);\n });\n // Add items in order of appearance in visibleItems.\n visibleItems.forEach((item) => {\n const group = getGroup(item);\n if (!result.has(group)) {\n result.set(group, []);\n }\n result.get(group).push(item);\n });\n return result;\n }\n\n /**\n * Generate the built-in help text.\n *\n * @param {Command} cmd\n * @param {Help} helper\n * @returns {string}\n */\n\n formatHelp(cmd, helper) {\n const termWidth = helper.padWidth(cmd, helper);\n const helpWidth = helper.helpWidth ?? 80; // in case prepareContext() was not called\n\n function callFormatItem(term, description) {\n return helper.formatItem(term, termWidth, description, helper);\n }\n\n // Usage\n let output = [\n `${helper.styleTitle('Usage:')} ${helper.styleUsage(helper.commandUsage(cmd))}`,\n '',\n ];\n\n // Description\n const commandDescription = helper.commandDescription(cmd);\n if (commandDescription.length > 0) {\n output = output.concat([\n helper.boxWrap(\n helper.styleCommandDescription(commandDescription),\n helpWidth,\n ),\n '',\n ]);\n }\n\n // Arguments\n const argumentList = helper.visibleArguments(cmd).map((argument) => {\n return callFormatItem(\n helper.styleArgumentTerm(helper.argumentTerm(argument)),\n helper.styleArgumentDescription(helper.argumentDescription(argument)),\n );\n });\n output = output.concat(\n this.formatItemList('Arguments:', argumentList, helper),\n );\n\n // Options\n const optionGroups = this.groupItems(\n cmd.options,\n helper.visibleOptions(cmd),\n (option) => option.helpGroupHeading ?? 'Options:',\n );\n optionGroups.forEach((options, group) => {\n const optionList = options.map((option) => {\n return callFormatItem(\n helper.styleOptionTerm(helper.optionTerm(option)),\n helper.styleOptionDescription(helper.optionDescription(option)),\n );\n });\n output = output.concat(this.formatItemList(group, optionList, helper));\n });\n\n if (helper.showGlobalOptions) {\n const globalOptionList = helper\n .visibleGlobalOptions(cmd)\n .map((option) => {\n return callFormatItem(\n helper.styleOptionTerm(helper.optionTerm(option)),\n helper.styleOptionDescription(helper.optionDescription(option)),\n );\n });\n output = output.concat(\n this.formatItemList('Global Options:', globalOptionList, helper),\n );\n }\n\n // Commands\n const commandGroups = this.groupItems(\n cmd.commands,\n helper.visibleCommands(cmd),\n (sub) => sub.helpGroup() || 'Commands:',\n );\n commandGroups.forEach((commands, group) => {\n const commandList = commands.map((sub) => {\n return callFormatItem(\n helper.styleSubcommandTerm(helper.subcommandTerm(sub)),\n helper.styleSubcommandDescription(helper.subcommandDescription(sub)),\n );\n });\n output = output.concat(this.formatItemList(group, commandList, helper));\n });\n\n return output.join('\\n');\n }\n\n /**\n * Return display width of string, ignoring ANSI escape sequences. Used in padding and wrapping calculations.\n *\n * @param {string} str\n * @returns {number}\n */\n displayWidth(str) {\n return stripColor(str).length;\n }\n\n /**\n * Style the title for displaying in the help. Called with 'Usage:', 'Options:', etc.\n *\n * @param {string} str\n * @returns {string}\n */\n styleTitle(str) {\n return str;\n }\n\n styleUsage(str) {\n // Usage has lots of parts the user might like to color separately! Assume default usage string which is formed like:\n // command subcommand [options] [command] <foo> [bar]\n return str\n .split(' ')\n .map((word) => {\n if (word === '[options]') return this.styleOptionText(word);\n if (word === '[command]') return this.styleSubcommandText(word);\n if (word[0] === '[' || word[0] === '<')\n return this.styleArgumentText(word);\n return this.styleCommandText(word); // Restrict to initial words?\n })\n .join(' ');\n }\n styleCommandDescription(str) {\n return this.styleDescriptionText(str);\n }\n styleOptionDescription(str) {\n return this.styleDescriptionText(str);\n }\n styleSubcommandDescription(str) {\n return this.styleDescriptionText(str);\n }\n styleArgumentDescription(str) {\n return this.styleDescriptionText(str);\n }\n styleDescriptionText(str) {\n return str;\n }\n styleOptionTerm(str) {\n return this.styleOptionText(str);\n }\n styleSubcommandTerm(str) {\n // This is very like usage with lots of parts! Assume default string which is formed like:\n // subcommand [options] <foo> [bar]\n return str\n .split(' ')\n .map((word) => {\n if (word === '[options]') return this.styleOptionText(word);\n if (word[0] === '[' || word[0] === '<')\n return this.styleArgumentText(word);\n return this.styleSubcommandText(word); // Restrict to initial words?\n })\n .join(' ');\n }\n styleArgumentTerm(str) {\n return this.styleArgumentText(str);\n }\n styleOptionText(str) {\n return str;\n }\n styleArgumentText(str) {\n return str;\n }\n styleSubcommandText(str) {\n return str;\n }\n styleCommandText(str) {\n return str;\n }\n\n /**\n * Calculate the pad width from the maximum term length.\n *\n * @param {Command} cmd\n * @param {Help} helper\n * @returns {number}\n */\n\n padWidth(cmd, helper) {\n return Math.max(\n helper.longestOptionTermLength(cmd, helper),\n helper.longestGlobalOptionTermLength(cmd, helper),\n helper.longestSubcommandTermLength(cmd, helper),\n helper.longestArgumentTermLength(cmd, helper),\n );\n }\n\n /**\n * Detect manually wrapped and indented strings by checking for line break followed by whitespace.\n *\n * @param {string} str\n * @returns {boolean}\n */\n preformatted(str) {\n return /\\n[^\\S\\r\\n]/.test(str);\n }\n\n /**\n * Format the \"item\", which consists of a term and description. Pad the term and wrap the description, indenting the following lines.\n *\n * So \"TTT\", 5, \"DDD DDDD DD DDD\" might be formatted for this.helpWidth=17 like so:\n * TTT DDD DDDD\n * DD DDD\n *\n * @param {string} term\n * @param {number} termWidth\n * @param {string} description\n * @param {Help} helper\n * @returns {string}\n */\n formatItem(term, termWidth, description, helper) {\n const itemIndent = 2;\n const itemIndentStr = ' '.repeat(itemIndent);\n if (!description) return itemIndentStr + term;\n\n // Pad the term out to a consistent width, so descriptions are aligned.\n const paddedTerm = term.padEnd(\n termWidth + term.length - helper.displayWidth(term),\n );\n\n // Format the description.\n const spacerWidth = 2; // between term and description\n const helpWidth = this.helpWidth ?? 80; // in case prepareContext() was not called\n const remainingWidth = helpWidth - termWidth - spacerWidth - itemIndent;\n let formattedDescription;\n if (\n remainingWidth < this.minWidthToWrap ||\n helper.preformatted(description)\n ) {\n formattedDescription = description;\n } else {\n const wrappedDescription = helper.boxWrap(description, remainingWidth);\n formattedDescription = wrappedDescription.replace(\n /\\n/g,\n '\\n' + ' '.repeat(termWidth + spacerWidth),\n );\n }\n\n // Construct and overall indent.\n return (\n itemIndentStr +\n paddedTerm +\n ' '.repeat(spacerWidth) +\n formattedDescription.replace(/\\n/g, `\\n${itemIndentStr}`)\n );\n }\n\n /**\n * Wrap a string at whitespace, preserving existing line breaks.\n * Wrapping is skipped if the width is less than `minWidthToWrap`.\n *\n * @param {string} str\n * @param {number} width\n * @returns {string}\n */\n boxWrap(str, width) {\n if (width < this.minWidthToWrap) return str;\n\n const rawLines = str.split(/\\r\\n|\\n/);\n // split up text by whitespace\n const chunkPattern = /[\\s]*[^\\s]+/g;\n const wrappedLines = [];\n rawLines.forEach((line) => {\n const chunks = line.match(chunkPattern);\n if (chunks === null) {\n wrappedLines.push('');\n return;\n }\n\n let sumChunks = [chunks.shift()];\n let sumWidth = this.displayWidth(sumChunks[0]);\n chunks.forEach((chunk) => {\n const visibleWidth = this.displayWidth(chunk);\n // Accumulate chunks while they fit into width.\n if (sumWidth + visibleWidth <= width) {\n sumChunks.push(chunk);\n sumWidth += visibleWidth;\n return;\n }\n wrappedLines.push(sumChunks.join(''));\n\n const nextChunk = chunk.trimStart(); // trim space at line break\n sumChunks = [nextChunk];\n sumWidth = this.displayWidth(nextChunk);\n });\n wrappedLines.push(sumChunks.join(''));\n });\n\n return wrappedLines.join('\\n');\n }\n}\n\n/**\n * Strip style ANSI escape sequences from the string. In particular, SGR (Select Graphic Rendition) codes.\n *\n * @param {string} str\n * @returns {string}\n * @package\n */\n\nfunction stripColor(str) {\n // eslint-disable-next-line no-control-regex\n const sgrPattern = /\\x1b\\[\\d*(;\\d*)*m/g;\n return str.replace(sgrPattern, '');\n}\n\nexports.Help = Help;\nexports.stripColor = stripColor;\n", "const { InvalidArgumentError } = require('./error.js');\n\nclass Option {\n /**\n * Initialize a new `Option` with the given `flags` and `description`.\n *\n * @param {string} flags\n * @param {string} [description]\n */\n\n constructor(flags, description) {\n this.flags = flags;\n this.description = description || '';\n\n this.required = flags.includes('<'); // A value must be supplied when the option is specified.\n this.optional = flags.includes('['); // A value is optional when the option is specified.\n // variadic test ignores <value,...> et al which might be used to describe custom splitting of single argument\n this.variadic = /\\w\\.\\.\\.[>\\]]$/.test(flags); // The option can take multiple values.\n this.mandatory = false; // The option must have a value after parsing, which usually means it must be specified on command line.\n const optionFlags = splitOptionFlags(flags);\n this.short = optionFlags.shortFlag; // May be a short flag, undefined, or even a long flag (if option has two long flags).\n this.long = optionFlags.longFlag;\n this.negate = false;\n if (this.long) {\n this.negate = this.long.startsWith('--no-');\n }\n this.defaultValue = undefined;\n this.defaultValueDescription = undefined;\n this.presetArg = undefined;\n this.envVar = undefined;\n this.parseArg = undefined;\n this.hidden = false;\n this.argChoices = undefined;\n this.conflictsWith = [];\n this.implied = undefined;\n this.helpGroupHeading = undefined; // soft initialised when option added to command\n }\n\n /**\n * Set the default value, and optionally supply the description to be displayed in the help.\n *\n * @param {*} value\n * @param {string} [description]\n * @return {Option}\n */\n\n default(value, description) {\n this.defaultValue = value;\n this.defaultValueDescription = description;\n return this;\n }\n\n /**\n * Preset to use when option used without option-argument, especially optional but also boolean and negated.\n * The custom processing (parseArg) is called.\n *\n * @example\n * new Option('--color').default('GREYSCALE').preset('RGB');\n * new Option('--donate [amount]').preset('20').argParser(parseFloat);\n *\n * @param {*} arg\n * @return {Option}\n */\n\n preset(arg) {\n this.presetArg = arg;\n return this;\n }\n\n /**\n * Add option name(s) that conflict with this option.\n * An error will be displayed if conflicting options are found during parsing.\n *\n * @example\n * new Option('--rgb').conflicts('cmyk');\n * new Option('--js').conflicts(['ts', 'jsx']);\n *\n * @param {(string | string[])} names\n * @return {Option}\n */\n\n conflicts(names) {\n this.conflictsWith = this.conflictsWith.concat(names);\n return this;\n }\n\n /**\n * Specify implied option values for when this option is set and the implied options are not.\n *\n * The custom processing (parseArg) is not called on the implied values.\n *\n * @example\n * program\n * .addOption(new Option('--log', 'write logging information to file'))\n * .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));\n *\n * @param {object} impliedOptionValues\n * @return {Option}\n */\n implies(impliedOptionValues) {\n let newImplied = impliedOptionValues;\n if (typeof impliedOptionValues === 'string') {\n // string is not documented, but easy mistake and we can do what user probably intended.\n newImplied = { [impliedOptionValues]: true };\n }\n this.implied = Object.assign(this.implied || {}, newImplied);\n return this;\n }\n\n /**\n * Set environment variable to check for option value.\n *\n * An environment variable is only used if when processed the current option value is\n * undefined, or the source of the current value is 'default' or 'config' or 'env'.\n *\n * @param {string} name\n * @return {Option}\n */\n\n env(name) {\n this.envVar = name;\n return this;\n }\n\n /**\n * Set the custom handler for processing CLI option arguments into option values.\n *\n * @param {Function} [fn]\n * @return {Option}\n */\n\n argParser(fn) {\n this.parseArg = fn;\n return this;\n }\n\n /**\n * Whether the option is mandatory and must have a value after parsing.\n *\n * @param {boolean} [mandatory=true]\n * @return {Option}\n */\n\n makeOptionMandatory(mandatory = true) {\n this.mandatory = !!mandatory;\n return this;\n }\n\n /**\n * Hide option in help.\n *\n * @param {boolean} [hide=true]\n * @return {Option}\n */\n\n hideHelp(hide = true) {\n this.hidden = !!hide;\n return this;\n }\n\n /**\n * @package\n */\n\n _collectValue(value, previous) {\n if (previous === this.defaultValue || !Array.isArray(previous)) {\n return [value];\n }\n\n previous.push(value);\n return previous;\n }\n\n /**\n * Only allow option value to be one of choices.\n *\n * @param {string[]} values\n * @return {Option}\n */\n\n choices(values) {\n this.argChoices = values.slice();\n this.parseArg = (arg, previous) => {\n if (!this.argChoices.includes(arg)) {\n throw new InvalidArgumentError(\n `Allowed choices are ${this.argChoices.join(', ')}.`,\n );\n }\n if (this.variadic) {\n return this._collectValue(arg, previous);\n }\n return arg;\n };\n return this;\n }\n\n /**\n * Return option name.\n *\n * @return {string}\n */\n\n name() {\n if (this.long) {\n return this.long.replace(/^--/, '');\n }\n return this.short.replace(/^-/, '');\n }\n\n /**\n * Return option name, in a camelcase format that can be used\n * as an object attribute key.\n *\n * @return {string}\n */\n\n attributeName() {\n if (this.negate) {\n return camelcase(this.name().replace(/^no-/, ''));\n }\n return camelcase(this.name());\n }\n\n /**\n * Set the help group heading.\n *\n * @param {string} heading\n * @return {Option}\n */\n helpGroup(heading) {\n this.helpGroupHeading = heading;\n return this;\n }\n\n /**\n * Check if `arg` matches the short or long flag.\n *\n * @param {string} arg\n * @return {boolean}\n * @package\n */\n\n is(arg) {\n return this.short === arg || this.long === arg;\n }\n\n /**\n * Return whether a boolean option.\n *\n * Options are one of boolean, negated, required argument, or optional argument.\n *\n * @return {boolean}\n * @package\n */\n\n isBoolean() {\n return !this.required && !this.optional && !this.negate;\n }\n}\n\n/**\n * This class is to make it easier to work with dual options, without changing the existing\n * implementation. We support separate dual options for separate positive and negative options,\n * like `--build` and `--no-build`, which share a single option value. This works nicely for some\n * use cases, but is tricky for others where we want separate behaviours despite\n * the single shared option value.\n */\nclass DualOptions {\n /**\n * @param {Option[]} options\n */\n constructor(options) {\n this.positiveOptions = new Map();\n this.negativeOptions = new Map();\n this.dualOptions = new Set();\n options.forEach((option) => {\n if (option.negate) {\n this.negativeOptions.set(option.attributeName(), option);\n } else {\n this.positiveOptions.set(option.attributeName(), option);\n }\n });\n this.negativeOptions.forEach((value, key) => {\n if (this.positiveOptions.has(key)) {\n this.dualOptions.add(key);\n }\n });\n }\n\n /**\n * Did the value come from the option, and not from possible matching dual option?\n *\n * @param {*} value\n * @param {Option} option\n * @returns {boolean}\n */\n valueFromOption(value, option) {\n const optionKey = option.attributeName();\n if (!this.dualOptions.has(optionKey)) return true;\n\n // Use the value to deduce if (probably) came from the option.\n const preset = this.negativeOptions.get(optionKey).presetArg;\n const negativeValue = preset !== undefined ? preset : false;\n return option.negate === (negativeValue === value);\n }\n}\n\n/**\n * Convert string from kebab-case to camelCase.\n *\n * @param {string} str\n * @return {string}\n * @private\n */\n\nfunction camelcase(str) {\n return str.split('-').reduce((str, word) => {\n return str + word[0].toUpperCase() + word.slice(1);\n });\n}\n\n/**\n * Split the short and long flag out of something like '-m,--mixed <value>'\n *\n * @private\n */\n\nfunction splitOptionFlags(flags) {\n let shortFlag;\n let longFlag;\n // short flag, single dash and single character\n const shortFlagExp = /^-[^-]$/;\n // long flag, double dash and at least one character\n const longFlagExp = /^--[^-]/;\n\n const flagParts = flags.split(/[ |,]+/).concat('guard');\n // Normal is short and/or long.\n if (shortFlagExp.test(flagParts[0])) shortFlag = flagParts.shift();\n if (longFlagExp.test(flagParts[0])) longFlag = flagParts.shift();\n // Long then short. Rarely used but fine.\n if (!shortFlag && shortFlagExp.test(flagParts[0]))\n shortFlag = flagParts.shift();\n // Allow two long flags, like '--ws, --workspace'\n // This is the supported way to have a shortish option flag.\n if (!shortFlag && longFlagExp.test(flagParts[0])) {\n shortFlag = longFlag;\n longFlag = flagParts.shift();\n }\n\n // Check for unprocessed flag. Fail noisily rather than silently ignore.\n if (flagParts[0].startsWith('-')) {\n const unsupportedFlag = flagParts[0];\n const baseError = `option creation failed due to '${unsupportedFlag}' in option flags '${flags}'`;\n if (/^-[^-][^-]/.test(unsupportedFlag))\n throw new Error(\n `${baseError}\n- a short flag is a single dash and a single character\n - either use a single dash and a single character (for a short flag)\n - or use a double dash for a long option (and can have two, like '--ws, --workspace')`,\n );\n if (shortFlagExp.test(unsupportedFlag))\n throw new Error(`${baseError}\n- too many short flags`);\n if (longFlagExp.test(unsupportedFlag))\n throw new Error(`${baseError}\n- too many long flags`);\n\n throw new Error(`${baseError}\n- unrecognised flag format`);\n }\n if (shortFlag === undefined && longFlag === undefined)\n throw new Error(\n `option creation failed due to no flags found in '${flags}'.`,\n );\n\n return { shortFlag, longFlag };\n}\n\nexports.Option = Option;\nexports.DualOptions = DualOptions;\n", "const maxDistance = 3;\n\nfunction editDistance(a, b) {\n // https://en.wikipedia.org/wiki/Damerau\u2013Levenshtein_distance\n // Calculating optimal string alignment distance, no substring is edited more than once.\n // (Simple implementation.)\n\n // Quick early exit, return worst case.\n if (Math.abs(a.length - b.length) > maxDistance)\n return Math.max(a.length, b.length);\n\n // distance between prefix substrings of a and b\n const d = [];\n\n // pure deletions turn a into empty string\n for (let i = 0; i <= a.length; i++) {\n d[i] = [i];\n }\n // pure insertions turn empty string into b\n for (let j = 0; j <= b.length; j++) {\n d[0][j] = j;\n }\n\n // fill matrix\n for (let j = 1; j <= b.length; j++) {\n for (let i = 1; i <= a.length; i++) {\n let cost = 1;\n if (a[i - 1] === b[j - 1]) {\n cost = 0;\n } else {\n cost = 1;\n }\n d[i][j] = Math.min(\n d[i - 1][j] + 1, // deletion\n d[i][j - 1] + 1, // insertion\n d[i - 1][j - 1] + cost, // substitution\n );\n // transposition\n if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {\n d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);\n }\n }\n }\n\n return d[a.length][b.length];\n}\n\n/**\n * Find close matches, restricted to same number of edits.\n *\n * @param {string} word\n * @param {string[]} candidates\n * @returns {string}\n */\n\nfunction suggestSimilar(word, candidates) {\n if (!candidates || candidates.length === 0) return '';\n // remove possible duplicates\n candidates = Array.from(new Set(candidates));\n\n const searchingOptions = word.startsWith('--');\n if (searchingOptions) {\n word = word.slice(2);\n candidates = candidates.map((candidate) => candidate.slice(2));\n }\n\n let similar = [];\n let bestDistance = maxDistance;\n const minSimilarity = 0.4;\n candidates.forEach((candidate) => {\n if (candidate.length <= 1) return; // no one character guesses\n\n const distance = editDistance(word, candidate);\n const length = Math.max(word.length, candidate.length);\n const similarity = (length - distance) / length;\n if (similarity > minSimilarity) {\n if (distance < bestDistance) {\n // better edit distance, throw away previous worse matches\n bestDistance = distance;\n similar = [candidate];\n } else if (distance === bestDistance) {\n similar.push(candidate);\n }\n }\n });\n\n similar.sort((a, b) => a.localeCompare(b));\n if (searchingOptions) {\n similar = similar.map((candidate) => `--${candidate}`);\n }\n\n if (similar.length > 1) {\n return `\\n(Did you mean one of ${similar.join(', ')}?)`;\n }\n if (similar.length === 1) {\n return `\\n(Did you mean ${similar[0]}?)`;\n }\n return '';\n}\n\nexports.suggestSimilar = suggestSimilar;\n", "const EventEmitter = require('node:events').EventEmitter;\nconst childProcess = require('node:child_process');\nconst path = require('node:path');\nconst fs = require('node:fs');\nconst process = require('node:process');\n\nconst { Argument, humanReadableArgName } = require('./argument.js');\nconst { CommanderError } = require('./error.js');\nconst { Help, stripColor } = require('./help.js');\nconst { Option, DualOptions } = require('./option.js');\nconst { suggestSimilar } = require('./suggestSimilar');\n\nclass Command extends EventEmitter {\n /**\n * Initialize a new `Command`.\n *\n * @param {string} [name]\n */\n\n constructor(name) {\n super();\n /** @type {Command[]} */\n this.commands = [];\n /** @type {Option[]} */\n this.options = [];\n this.parent = null;\n this._allowUnknownOption = false;\n this._allowExcessArguments = false;\n /** @type {Argument[]} */\n this.registeredArguments = [];\n this._args = this.registeredArguments; // deprecated old name\n /** @type {string[]} */\n this.args = []; // cli args with options removed\n this.rawArgs = [];\n this.processedArgs = []; // like .args but after custom processing and collecting variadic\n this._scriptPath = null;\n this._name = name || '';\n this._optionValues = {};\n this._optionValueSources = {}; // default, env, cli etc\n this._storeOptionsAsProperties = false;\n this._actionHandler = null;\n this._executableHandler = false;\n this._executableFile = null; // custom name for executable\n this._executableDir = null; // custom search directory for subcommands\n this._defaultCommandName = null;\n this._exitCallback = null;\n this._aliases = [];\n this._combineFlagAndOptionalValue = true;\n this._description = '';\n this._summary = '';\n this._argsDescription = undefined; // legacy\n this._enablePositionalOptions = false;\n this._passThroughOptions = false;\n this._lifeCycleHooks = {}; // a hash of arrays\n /** @type {(boolean | string)} */\n this._showHelpAfterError = false;\n this._showSuggestionAfterError = true;\n this._savedState = null; // used in save/restoreStateBeforeParse\n\n // see configureOutput() for docs\n this._outputConfiguration = {\n writeOut: (str) => process.stdout.write(str),\n writeErr: (str) => process.stderr.write(str),\n outputError: (str, write) => write(str),\n getOutHelpWidth: () =>\n process.stdout.isTTY ? process.stdout.columns : undefined,\n getErrHelpWidth: () =>\n process.stderr.isTTY ? process.stderr.columns : undefined,\n getOutHasColors: () =>\n useColor() ?? (process.stdout.isTTY && process.stdout.hasColors?.()),\n getErrHasColors: () =>\n useColor() ?? (process.stderr.isTTY && process.stderr.hasColors?.()),\n stripColor: (str) => stripColor(str),\n };\n\n this._hidden = false;\n /** @type {(Option | null | undefined)} */\n this._helpOption = undefined; // Lazy created on demand. May be null if help option is disabled.\n this._addImplicitHelpCommand = undefined; // undecided whether true or false yet, not inherited\n /** @type {Command} */\n this._helpCommand = undefined; // lazy initialised, inherited\n this._helpConfiguration = {};\n /** @type {string | undefined} */\n this._helpGroupHeading = undefined; // soft initialised when added to parent\n /** @type {string | undefined} */\n this._defaultCommandGroup = undefined;\n /** @type {string | undefined} */\n this._defaultOptionGroup = undefined;\n }\n\n /**\n * Copy settings that are useful to have in common across root command and subcommands.\n *\n * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)\n *\n * @param {Command} sourceCommand\n * @return {Command} `this` command for chaining\n */\n copyInheritedSettings(sourceCommand) {\n this._outputConfiguration = sourceCommand._outputConfiguration;\n this._helpOption = sourceCommand._helpOption;\n this._helpCommand = sourceCommand._helpCommand;\n this._helpConfiguration = sourceCommand._helpConfiguration;\n this._exitCallback = sourceCommand._exitCallback;\n this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;\n this._combineFlagAndOptionalValue =\n sourceCommand._combineFlagAndOptionalValue;\n this._allowExcessArguments = sourceCommand._allowExcessArguments;\n this._enablePositionalOptions = sourceCommand._enablePositionalOptions;\n this._showHelpAfterError = sourceCommand._showHelpAfterError;\n this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;\n\n return this;\n }\n\n /**\n * @returns {Command[]}\n * @private\n */\n\n _getCommandAndAncestors() {\n const result = [];\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n for (let command = this; command; command = command.parent) {\n result.push(command);\n }\n return result;\n }\n\n /**\n * Define a command.\n *\n * There are two styles of command: pay attention to where to put the description.\n *\n * @example\n * // Command implemented using action handler (description is supplied separately to `.command`)\n * program\n * .command('clone <source> [destination]')\n * .description('clone a repository into a newly created directory')\n * .action((source, destination) => {\n * console.log('clone command called');\n * });\n *\n * // Command implemented using separate executable file (description is second parameter to `.command`)\n * program\n * .command('start <service>', 'start named service')\n * .command('stop [service]', 'stop named service, or all if no name supplied');\n *\n * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`\n * @param {(object | string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)\n * @param {object} [execOpts] - configuration options (for executable)\n * @return {Command} returns new command for action handler, or `this` for executable command\n */\n\n command(nameAndArgs, actionOptsOrExecDesc, execOpts) {\n let desc = actionOptsOrExecDesc;\n let opts = execOpts;\n if (typeof desc === 'object' && desc !== null) {\n opts = desc;\n desc = null;\n }\n opts = opts || {};\n const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);\n\n const cmd = this.createCommand(name);\n if (desc) {\n cmd.description(desc);\n cmd._executableHandler = true;\n }\n if (opts.isDefault) this._defaultCommandName = cmd._name;\n cmd._hidden = !!(opts.noHelp || opts.hidden); // noHelp is deprecated old name for hidden\n cmd._executableFile = opts.executableFile || null; // Custom name for executable file, set missing to null to match constructor\n if (args) cmd.arguments(args);\n this._registerCommand(cmd);\n cmd.parent = this;\n cmd.copyInheritedSettings(this);\n\n if (desc) return this;\n return cmd;\n }\n\n /**\n * Factory routine to create a new unattached command.\n *\n * See .command() for creating an attached subcommand, which uses this routine to\n * create the command. You can override createCommand to customise subcommands.\n *\n * @param {string} [name]\n * @return {Command} new command\n */\n\n createCommand(name) {\n return new Command(name);\n }\n\n /**\n * You can customise the help with a subclass of Help by overriding createHelp,\n * or by overriding Help properties using configureHelp().\n *\n * @return {Help}\n */\n\n createHelp() {\n return Object.assign(new Help(), this.configureHelp());\n }\n\n /**\n * You can customise the help by overriding Help properties using configureHelp(),\n * or with a subclass of Help by overriding createHelp().\n *\n * @param {object} [configuration] - configuration options\n * @return {(Command | object)} `this` command for chaining, or stored configuration\n */\n\n configureHelp(configuration) {\n if (configuration === undefined) return this._helpConfiguration;\n\n this._helpConfiguration = configuration;\n return this;\n }\n\n /**\n * The default output goes to stdout and stderr. You can customise this for special\n * applications. You can also customise the display of errors by overriding outputError.\n *\n * The configuration properties are all functions:\n *\n * // change how output being written, defaults to stdout and stderr\n * writeOut(str)\n * writeErr(str)\n * // change how output being written for errors, defaults to writeErr\n * outputError(str, write) // used for displaying errors and not used for displaying help\n * // specify width for wrapping help\n * getOutHelpWidth()\n * getErrHelpWidth()\n * // color support, currently only used with Help\n * getOutHasColors()\n * getErrHasColors()\n * stripColor() // used to remove ANSI escape codes if output does not have colors\n *\n * @param {object} [configuration] - configuration options\n * @return {(Command | object)} `this` command for chaining, or stored configuration\n */\n\n configureOutput(configuration) {\n if (configuration === undefined) return this._outputConfiguration;\n\n this._outputConfiguration = {\n ...this._outputConfiguration,\n ...configuration,\n };\n return this;\n }\n\n /**\n * Display the help or a custom message after an error occurs.\n *\n * @param {(boolean|string)} [displayHelp]\n * @return {Command} `this` command for chaining\n */\n showHelpAfterError(displayHelp = true) {\n if (typeof displayHelp !== 'string') displayHelp = !!displayHelp;\n this._showHelpAfterError = displayHelp;\n return this;\n }\n\n /**\n * Display suggestion of similar commands for unknown commands, or options for unknown options.\n *\n * @param {boolean} [displaySuggestion]\n * @return {Command} `this` command for chaining\n */\n showSuggestionAfterError(displaySuggestion = true) {\n this._showSuggestionAfterError = !!displaySuggestion;\n return this;\n }\n\n /**\n * Add a prepared subcommand.\n *\n * See .command() for creating an attached subcommand which inherits settings from its parent.\n *\n * @param {Command} cmd - new subcommand\n * @param {object} [opts] - configuration options\n * @return {Command} `this` command for chaining\n */\n\n addCommand(cmd, opts) {\n if (!cmd._name) {\n throw new Error(`Command passed to .addCommand() must have a name\n- specify the name in Command constructor or using .name()`);\n }\n\n opts = opts || {};\n if (opts.isDefault) this._defaultCommandName = cmd._name;\n if (opts.noHelp || opts.hidden) cmd._hidden = true; // modifying passed command due to existing implementation\n\n this._registerCommand(cmd);\n cmd.parent = this;\n cmd._checkForBrokenPassThrough();\n\n return this;\n }\n\n /**\n * Factory routine to create a new unattached argument.\n *\n * See .argument() for creating an attached argument, which uses this routine to\n * create the argument. You can override createArgument to return a custom argument.\n *\n * @param {string} name\n * @param {string} [description]\n * @return {Argument} new argument\n */\n\n createArgument(name, description) {\n return new Argument(name, description);\n }\n\n /**\n * Define argument syntax for command.\n *\n * The default is that the argument is required, and you can explicitly\n * indicate this with <> around the name. Put [] around the name for an optional argument.\n *\n * @example\n * program.argument('<input-file>');\n * program.argument('[output-file]');\n *\n * @param {string} name\n * @param {string} [description]\n * @param {(Function|*)} [parseArg] - custom argument processing function or default value\n * @param {*} [defaultValue]\n * @return {Command} `this` command for chaining\n */\n argument(name, description, parseArg, defaultValue) {\n const argument = this.createArgument(name, description);\n if (typeof parseArg === 'function') {\n argument.default(defaultValue).argParser(parseArg);\n } else {\n argument.default(parseArg);\n }\n this.addArgument(argument);\n return this;\n }\n\n /**\n * Define argument syntax for command, adding multiple at once (without descriptions).\n *\n * See also .argument().\n *\n * @example\n * program.arguments('<cmd> [env]');\n *\n * @param {string} names\n * @return {Command} `this` command for chaining\n */\n\n arguments(names) {\n names\n .trim()\n .split(/ +/)\n .forEach((detail) => {\n this.argument(detail);\n });\n return this;\n }\n\n /**\n * Define argument syntax for command, adding a prepared argument.\n *\n * @param {Argument} argument\n * @return {Command} `this` command for chaining\n */\n addArgument(argument) {\n const previousArgument = this.registeredArguments.slice(-1)[0];\n if (previousArgument?.variadic) {\n throw new Error(\n `only the last argument can be variadic '${previousArgument.name()}'`,\n );\n }\n if (\n argument.required &&\n argument.defaultValue !== undefined &&\n argument.parseArg === undefined\n ) {\n throw new Error(\n `a default value for a required argument is never used: '${argument.name()}'`,\n );\n }\n this.registeredArguments.push(argument);\n return this;\n }\n\n /**\n * Customise or override default help command. By default a help command is automatically added if your command has subcommands.\n *\n * @example\n * program.helpCommand('help [cmd]');\n * program.helpCommand('help [cmd]', 'show help');\n * program.helpCommand(false); // suppress default help command\n * program.helpCommand(true); // add help command even if no subcommands\n *\n * @param {string|boolean} enableOrNameAndArgs - enable with custom name and/or arguments, or boolean to override whether added\n * @param {string} [description] - custom description\n * @return {Command} `this` command for chaining\n */\n\n helpCommand(enableOrNameAndArgs, description) {\n if (typeof enableOrNameAndArgs === 'boolean') {\n this._addImplicitHelpCommand = enableOrNameAndArgs;\n if (enableOrNameAndArgs && this._defaultCommandGroup) {\n // make the command to store the group\n this._initCommandGroup(this._getHelpCommand());\n }\n return this;\n }\n\n const nameAndArgs = enableOrNameAndArgs ?? 'help [command]';\n const [, helpName, helpArgs] = nameAndArgs.match(/([^ ]+) *(.*)/);\n const helpDescription = description ?? 'display help for command';\n\n const helpCommand = this.createCommand(helpName);\n helpCommand.helpOption(false);\n if (helpArgs) helpCommand.arguments(helpArgs);\n if (helpDescription) helpCommand.description(helpDescription);\n\n this._addImplicitHelpCommand = true;\n this._helpCommand = helpCommand;\n // init group unless lazy create\n if (enableOrNameAndArgs || description) this._initCommandGroup(helpCommand);\n\n return this;\n }\n\n /**\n * Add prepared custom help command.\n *\n * @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()`\n * @param {string} [deprecatedDescription] - deprecated custom description used with custom name only\n * @return {Command} `this` command for chaining\n */\n addHelpCommand(helpCommand, deprecatedDescription) {\n // If not passed an object, call through to helpCommand for backwards compatibility,\n // as addHelpCommand was originally used like helpCommand is now.\n if (typeof helpCommand !== 'object') {\n this.helpCommand(helpCommand, deprecatedDescription);\n return this;\n }\n\n this._addImplicitHelpCommand = true;\n this._helpCommand = helpCommand;\n this._initCommandGroup(helpCommand);\n return this;\n }\n\n /**\n * Lazy create help command.\n *\n * @return {(Command|null)}\n * @package\n */\n _getHelpCommand() {\n const hasImplicitHelpCommand =\n this._addImplicitHelpCommand ??\n (this.commands.length &&\n !this._actionHandler &&\n !this._findCommand('help'));\n\n if (hasImplicitHelpCommand) {\n if (this._helpCommand === undefined) {\n this.helpCommand(undefined, undefined); // use default name and description\n }\n return this._helpCommand;\n }\n return null;\n }\n\n /**\n * Add hook for life cycle event.\n *\n * @param {string} event\n * @param {Function} listener\n * @return {Command} `this` command for chaining\n */\n\n hook(event, listener) {\n const allowedValues = ['preSubcommand', 'preAction', 'postAction'];\n if (!allowedValues.includes(event)) {\n throw new Error(`Unexpected value for event passed to hook : '${event}'.\nExpecting one of '${allowedValues.join(\"', '\")}'`);\n }\n if (this._lifeCycleHooks[event]) {\n this._lifeCycleHooks[event].push(listener);\n } else {\n this._lifeCycleHooks[event] = [listener];\n }\n return this;\n }\n\n /**\n * Register callback to use as replacement for calling process.exit.\n *\n * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing\n * @return {Command} `this` command for chaining\n */\n\n exitOverride(fn) {\n if (fn) {\n this._exitCallback = fn;\n } else {\n this._exitCallback = (err) => {\n if (err.code !== 'commander.executeSubCommandAsync') {\n throw err;\n } else {\n // Async callback from spawn events, not useful to throw.\n }\n };\n }\n return this;\n }\n\n /**\n * Call process.exit, and _exitCallback if defined.\n *\n * @param {number} exitCode exit code for using with process.exit\n * @param {string} code an id string representing the error\n * @param {string} message human-readable description of the error\n * @return never\n * @private\n */\n\n _exit(exitCode, code, message) {\n if (this._exitCallback) {\n this._exitCallback(new CommanderError(exitCode, code, message));\n // Expecting this line is not reached.\n }\n process.exit(exitCode);\n }\n\n /**\n * Register callback `fn` for the command.\n *\n * @example\n * program\n * .command('serve')\n * .description('start service')\n * .action(function() {\n * // do work here\n * });\n *\n * @param {Function} fn\n * @return {Command} `this` command for chaining\n */\n\n action(fn) {\n const listener = (args) => {\n // The .action callback takes an extra parameter which is the command or options.\n const expectedArgsCount = this.registeredArguments.length;\n const actionArgs = args.slice(0, expectedArgsCount);\n if (this._storeOptionsAsProperties) {\n actionArgs[expectedArgsCount] = this; // backwards compatible \"options\"\n } else {\n actionArgs[expectedArgsCount] = this.opts();\n }\n actionArgs.push(this);\n\n return fn.apply(this, actionArgs);\n };\n this._actionHandler = listener;\n return this;\n }\n\n /**\n * Factory routine to create a new unattached option.\n *\n * See .option() for creating an attached option, which uses this routine to\n * create the option. You can override createOption to return a custom option.\n *\n * @param {string} flags\n * @param {string} [description]\n * @return {Option} new option\n */\n\n createOption(flags, description) {\n return new Option(flags, description);\n }\n\n /**\n * Wrap parseArgs to catch 'commander.invalidArgument'.\n *\n * @param {(Option | Argument)} target\n * @param {string} value\n * @param {*} previous\n * @param {string} invalidArgumentMessage\n * @private\n */\n\n _callParseArg(target, value, previous, invalidArgumentMessage) {\n try {\n return target.parseArg(value, previous);\n } catch (err) {\n if (err.code === 'commander.invalidArgument') {\n const message = `${invalidArgumentMessage} ${err.message}`;\n this.error(message, { exitCode: err.exitCode, code: err.code });\n }\n throw err;\n }\n }\n\n /**\n * Check for option flag conflicts.\n * Register option if no conflicts found, or throw on conflict.\n *\n * @param {Option} option\n * @private\n */\n\n _registerOption(option) {\n const matchingOption =\n (option.short && this._findOption(option.short)) ||\n (option.long && this._findOption(option.long));\n if (matchingOption) {\n const matchingFlag =\n option.long && this._findOption(option.long)\n ? option.long\n : option.short;\n throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'\n- already used by option '${matchingOption.flags}'`);\n }\n\n this._initOptionGroup(option);\n this.options.push(option);\n }\n\n /**\n * Check for command name and alias conflicts with existing commands.\n * Register command if no conflicts found, or throw on conflict.\n *\n * @param {Command} command\n * @private\n */\n\n _registerCommand(command) {\n const knownBy = (cmd) => {\n return [cmd.name()].concat(cmd.aliases());\n };\n\n const alreadyUsed = knownBy(command).find((name) =>\n this._findCommand(name),\n );\n if (alreadyUsed) {\n const existingCmd = knownBy(this._findCommand(alreadyUsed)).join('|');\n const newCmd = knownBy(command).join('|');\n throw new Error(\n `cannot add command '${newCmd}' as already have command '${existingCmd}'`,\n );\n }\n\n this._initCommandGroup(command);\n this.commands.push(command);\n }\n\n /**\n * Add an option.\n *\n * @param {Option} option\n * @return {Command} `this` command for chaining\n */\n addOption(option) {\n this._registerOption(option);\n\n const oname = option.name();\n const name = option.attributeName();\n\n // store default value\n if (option.negate) {\n // --no-foo is special and defaults foo to true, unless a --foo option is already defined\n const positiveLongFlag = option.long.replace(/^--no-/, '--');\n if (!this._findOption(positiveLongFlag)) {\n this.setOptionValueWithSource(\n name,\n option.defaultValue === undefined ? true : option.defaultValue,\n 'default',\n );\n }\n } else if (option.defaultValue !== undefined) {\n this.setOptionValueWithSource(name, option.defaultValue, 'default');\n }\n\n // handler for cli and env supplied values\n const handleOptionValue = (val, invalidValueMessage, valueSource) => {\n // val is null for optional option used without an optional-argument.\n // val is undefined for boolean and negated option.\n if (val == null && option.presetArg !== undefined) {\n val = option.presetArg;\n }\n\n // custom processing\n const oldValue = this.getOptionValue(name);\n if (val !== null && option.parseArg) {\n val = this._callParseArg(option, val, oldValue, invalidValueMessage);\n } else if (val !== null && option.variadic) {\n val = option._collectValue(val, oldValue);\n }\n\n // Fill-in appropriate missing values. Long winded but easy to follow.\n if (val == null) {\n if (option.negate) {\n val = false;\n } else if (option.isBoolean() || option.optional) {\n val = true;\n } else {\n val = ''; // not normal, parseArg might have failed or be a mock function for testing\n }\n }\n this.setOptionValueWithSource(name, val, valueSource);\n };\n\n this.on('option:' + oname, (val) => {\n const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;\n handleOptionValue(val, invalidValueMessage, 'cli');\n });\n\n if (option.envVar) {\n this.on('optionEnv:' + oname, (val) => {\n const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;\n handleOptionValue(val, invalidValueMessage, 'env');\n });\n }\n\n return this;\n }\n\n /**\n * Internal implementation shared by .option() and .requiredOption()\n *\n * @return {Command} `this` command for chaining\n * @private\n */\n _optionEx(config, flags, description, fn, defaultValue) {\n if (typeof flags === 'object' && flags instanceof Option) {\n throw new Error(\n 'To add an Option object use addOption() instead of option() or requiredOption()',\n );\n }\n const option = this.createOption(flags, description);\n option.makeOptionMandatory(!!config.mandatory);\n if (typeof fn === 'function') {\n option.default(defaultValue).argParser(fn);\n } else if (fn instanceof RegExp) {\n // deprecated\n const regex = fn;\n fn = (val, def) => {\n const m = regex.exec(val);\n return m ? m[0] : def;\n };\n option.default(defaultValue).argParser(fn);\n } else {\n option.default(fn);\n }\n\n return this.addOption(option);\n }\n\n /**\n * Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.\n *\n * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required\n * option-argument is indicated by `<>` and an optional option-argument by `[]`.\n *\n * See the README for more details, and see also addOption() and requiredOption().\n *\n * @example\n * program\n * .option('-p, --pepper', 'add pepper')\n * .option('--pt, --pizza-type <TYPE>', 'type of pizza') // required option-argument\n * .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default\n * .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function\n *\n * @param {string} flags\n * @param {string} [description]\n * @param {(Function|*)} [parseArg] - custom option processing function or default value\n * @param {*} [defaultValue]\n * @return {Command} `this` command for chaining\n */\n\n option(flags, description, parseArg, defaultValue) {\n return this._optionEx({}, flags, description, parseArg, defaultValue);\n }\n\n /**\n * Add a required option which must have a value after parsing. This usually means\n * the option must be specified on the command line. (Otherwise the same as .option().)\n *\n * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.\n *\n * @param {string} flags\n * @param {string} [description]\n * @param {(Function|*)} [parseArg] - custom option processing function or default value\n * @param {*} [defaultValue]\n * @return {Command} `this` command for chaining\n */\n\n requiredOption(flags, description, parseArg, defaultValue) {\n return this._optionEx(\n { mandatory: true },\n flags,\n description,\n parseArg,\n defaultValue,\n );\n }\n\n /**\n * Alter parsing of short flags with optional values.\n *\n * @example\n * // for `.option('-f,--flag [value]'):\n * program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour\n * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`\n *\n * @param {boolean} [combine] - if `true` or omitted, an optional value can be specified directly after the flag.\n * @return {Command} `this` command for chaining\n */\n combineFlagAndOptionalValue(combine = true) {\n this._combineFlagAndOptionalValue = !!combine;\n return this;\n }\n\n /**\n * Allow unknown options on the command line.\n *\n * @param {boolean} [allowUnknown] - if `true` or omitted, no error will be thrown for unknown options.\n * @return {Command} `this` command for chaining\n */\n allowUnknownOption(allowUnknown = true) {\n this._allowUnknownOption = !!allowUnknown;\n return this;\n }\n\n /**\n * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.\n *\n * @param {boolean} [allowExcess] - if `true` or omitted, no error will be thrown for excess arguments.\n * @return {Command} `this` command for chaining\n */\n allowExcessArguments(allowExcess = true) {\n this._allowExcessArguments = !!allowExcess;\n return this;\n }\n\n /**\n * Enable positional options. Positional means global options are specified before subcommands which lets\n * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.\n * The default behaviour is non-positional and global options may appear anywhere on the command line.\n *\n * @param {boolean} [positional]\n * @return {Command} `this` command for chaining\n */\n enablePositionalOptions(positional = true) {\n this._enablePositionalOptions = !!positional;\n return this;\n }\n\n /**\n * Pass through options that come after command-arguments rather than treat them as command-options,\n * so actual command-options come before command-arguments. Turning this on for a subcommand requires\n * positional options to have been enabled on the program (parent commands).\n * The default behaviour is non-positional and options may appear before or after command-arguments.\n *\n * @param {boolean} [passThrough] for unknown options.\n * @return {Command} `this` command for chaining\n */\n passThroughOptions(passThrough = true) {\n this._passThroughOptions = !!passThrough;\n this._checkForBrokenPassThrough();\n return this;\n }\n\n /**\n * @private\n */\n\n _checkForBrokenPassThrough() {\n if (\n this.parent &&\n this._passThroughOptions &&\n !this.parent._enablePositionalOptions\n ) {\n throw new Error(\n `passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`,\n );\n }\n }\n\n /**\n * Whether to store option values as properties on command object,\n * or store separately (specify false). In both cases the option values can be accessed using .opts().\n *\n * @param {boolean} [storeAsProperties=true]\n * @return {Command} `this` command for chaining\n */\n\n storeOptionsAsProperties(storeAsProperties = true) {\n if (this.options.length) {\n throw new Error('call .storeOptionsAsProperties() before adding options');\n }\n if (Object.keys(this._optionValues).length) {\n throw new Error(\n 'call .storeOptionsAsProperties() before setting option values',\n );\n }\n this._storeOptionsAsProperties = !!storeAsProperties;\n return this;\n }\n\n /**\n * Retrieve option value.\n *\n * @param {string} key\n * @return {object} value\n */\n\n getOptionValue(key) {\n if (this._storeOptionsAsProperties) {\n return this[key];\n }\n return this._optionValues[key];\n }\n\n /**\n * Store option value.\n *\n * @param {string} key\n * @param {object} value\n * @return {Command} `this` command for chaining\n */\n\n setOptionValue(key, value) {\n return this.setOptionValueWithSource(key, value, undefined);\n }\n\n /**\n * Store option value and where the value came from.\n *\n * @param {string} key\n * @param {object} value\n * @param {string} source - expected values are default/config/env/cli/implied\n * @return {Command} `this` command for chaining\n */\n\n setOptionValueWithSource(key, value, source) {\n if (this._storeOptionsAsProperties) {\n this[key] = value;\n } else {\n this._optionValues[key] = value;\n }\n this._optionValueSources[key] = source;\n return this;\n }\n\n /**\n * Get source of option value.\n * Expected values are default | config | env | cli | implied\n *\n * @param {string} key\n * @return {string}\n */\n\n getOptionValueSource(key) {\n return this._optionValueSources[key];\n }\n\n /**\n * Get source of option value. See also .optsWithGlobals().\n * Expected values are default | config | env | cli | implied\n *\n * @param {string} key\n * @return {string}\n */\n\n getOptionValueSourceWithGlobals(key) {\n // global overwrites local, like optsWithGlobals\n let source;\n this._getCommandAndAncestors().forEach((cmd) => {\n if (cmd.getOptionValueSource(key) !== undefined) {\n source = cmd.getOptionValueSource(key);\n }\n });\n return source;\n }\n\n /**\n * Get user arguments from implied or explicit arguments.\n * Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.\n *\n * @private\n */\n\n _prepareUserArgs(argv, parseOptions) {\n if (argv !== undefined && !Array.isArray(argv)) {\n throw new Error('first parameter to parse must be array or undefined');\n }\n parseOptions = parseOptions || {};\n\n // auto-detect argument conventions if nothing supplied\n if (argv === undefined && parseOptions.from === undefined) {\n if (process.versions?.electron) {\n parseOptions.from = 'electron';\n }\n // check node specific options for scenarios where user CLI args follow executable without scriptname\n const execArgv = process.execArgv ?? [];\n if (\n execArgv.includes('-e') ||\n execArgv.includes('--eval') ||\n execArgv.includes('-p') ||\n execArgv.includes('--print')\n ) {\n parseOptions.from = 'eval'; // internal usage, not documented\n }\n }\n\n // default to using process.argv\n if (argv === undefined) {\n argv = process.argv;\n }\n this.rawArgs = argv.slice();\n\n // extract the user args and scriptPath\n let userArgs;\n switch (parseOptions.from) {\n case undefined:\n case 'node':\n this._scriptPath = argv[1];\n userArgs = argv.slice(2);\n break;\n case 'electron':\n // @ts-ignore: because defaultApp is an unknown property\n if (process.defaultApp) {\n this._scriptPath = argv[1];\n userArgs = argv.slice(2);\n } else {\n userArgs = argv.slice(1);\n }\n break;\n case 'user':\n userArgs = argv.slice(0);\n break;\n case 'eval':\n userArgs = argv.slice(1);\n break;\n default:\n throw new Error(\n `unexpected parse option { from: '${parseOptions.from}' }`,\n );\n }\n\n // Find default name for program from arguments.\n if (!this._name && this._scriptPath)\n this.nameFromFilename(this._scriptPath);\n this._name = this._name || 'program';\n\n return userArgs;\n }\n\n /**\n * Parse `argv`, setting options and invoking commands when defined.\n *\n * Use parseAsync instead of parse if any of your action handlers are async.\n *\n * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!\n *\n * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:\n * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that\n * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged\n * - `'user'`: just user arguments\n *\n * @example\n * program.parse(); // parse process.argv and auto-detect electron and special node flags\n * program.parse(process.argv); // assume argv[0] is app and argv[1] is script\n * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]\n *\n * @param {string[]} [argv] - optional, defaults to process.argv\n * @param {object} [parseOptions] - optionally specify style of options with from: node/user/electron\n * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'\n * @return {Command} `this` command for chaining\n */\n\n parse(argv, parseOptions) {\n this._prepareForParse();\n const userArgs = this._prepareUserArgs(argv, parseOptions);\n this._parseCommand([], userArgs);\n\n return this;\n }\n\n /**\n * Parse `argv`, setting options and invoking commands when defined.\n *\n * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!\n *\n * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:\n * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that\n * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged\n * - `'user'`: just user arguments\n *\n * @example\n * await program.parseAsync(); // parse process.argv and auto-detect electron and special node flags\n * await program.parseAsync(process.argv); // assume argv[0] is app and argv[1] is script\n * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]\n *\n * @param {string[]} [argv]\n * @param {object} [parseOptions]\n * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'\n * @return {Promise}\n */\n\n async parseAsync(argv, parseOptions) {\n this._prepareForParse();\n const userArgs = this._prepareUserArgs(argv, parseOptions);\n await this._parseCommand([], userArgs);\n\n return this;\n }\n\n _prepareForParse() {\n if (this._savedState === null) {\n this.saveStateBeforeParse();\n } else {\n this.restoreStateBeforeParse();\n }\n }\n\n /**\n * Called the first time parse is called to save state and allow a restore before subsequent calls to parse.\n * Not usually called directly, but available for subclasses to save their custom state.\n *\n * This is called in a lazy way. Only commands used in parsing chain will have state saved.\n */\n saveStateBeforeParse() {\n this._savedState = {\n // name is stable if supplied by author, but may be unspecified for root command and deduced during parsing\n _name: this._name,\n // option values before parse have default values (including false for negated options)\n // shallow clones\n _optionValues: { ...this._optionValues },\n _optionValueSources: { ...this._optionValueSources },\n };\n }\n\n /**\n * Restore state before parse for calls after the first.\n * Not usually called directly, but available for subclasses to save their custom state.\n *\n * This is called in a lazy way. Only commands used in parsing chain will have state restored.\n */\n restoreStateBeforeParse() {\n if (this._storeOptionsAsProperties)\n throw new Error(`Can not call parse again when storeOptionsAsProperties is true.\n- either make a new Command for each call to parse, or stop storing options as properties`);\n\n // clear state from _prepareUserArgs\n this._name = this._savedState._name;\n this._scriptPath = null;\n this.rawArgs = [];\n // clear state from setOptionValueWithSource\n this._optionValues = { ...this._savedState._optionValues };\n this._optionValueSources = { ...this._savedState._optionValueSources };\n // clear state from _parseCommand\n this.args = [];\n // clear state from _processArguments\n this.processedArgs = [];\n }\n\n /**\n * Throw if expected executable is missing. Add lots of help for author.\n *\n * @param {string} executableFile\n * @param {string} executableDir\n * @param {string} subcommandName\n */\n _checkForMissingExecutable(executableFile, executableDir, subcommandName) {\n if (fs.existsSync(executableFile)) return;\n\n const executableDirMessage = executableDir\n ? `searched for local subcommand relative to directory '${executableDir}'`\n : 'no directory for search for local subcommand, use .executableDir() to supply a custom directory';\n const executableMissing = `'${executableFile}' does not exist\n - if '${subcommandName}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead\n - if the default executable name is not suitable, use the executableFile option to supply a custom name or path\n - ${executableDirMessage}`;\n throw new Error(executableMissing);\n }\n\n /**\n * Execute a sub-command executable.\n *\n * @private\n */\n\n _executeSubCommand(subcommand, args) {\n args = args.slice();\n let launchWithNode = false; // Use node for source targets so do not need to get permissions correct, and on Windows.\n const sourceExt = ['.js', '.ts', '.tsx', '.mjs', '.cjs'];\n\n function findFile(baseDir, baseName) {\n // Look for specified file\n const localBin = path.resolve(baseDir, baseName);\n if (fs.existsSync(localBin)) return localBin;\n\n // Stop looking if candidate already has an expected extension.\n if (sourceExt.includes(path.extname(baseName))) return undefined;\n\n // Try all the extensions.\n const foundExt = sourceExt.find((ext) =>\n fs.existsSync(`${localBin}${ext}`),\n );\n if (foundExt) return `${localBin}${foundExt}`;\n\n return undefined;\n }\n\n // Not checking for help first. Unlikely to have mandatory and executable, and can't robustly test for help flags in external command.\n this._checkForMissingMandatoryOptions();\n this._checkForConflictingOptions();\n\n // executableFile and executableDir might be full path, or just a name\n let executableFile =\n subcommand._executableFile || `${this._name}-${subcommand._name}`;\n let executableDir = this._executableDir || '';\n if (this._scriptPath) {\n let resolvedScriptPath; // resolve possible symlink for installed npm binary\n try {\n resolvedScriptPath = fs.realpathSync(this._scriptPath);\n } catch {\n resolvedScriptPath = this._scriptPath;\n }\n executableDir = path.resolve(\n path.dirname(resolvedScriptPath),\n executableDir,\n );\n }\n\n // Look for a local file in preference to a command in PATH.\n if (executableDir) {\n let localFile = findFile(executableDir, executableFile);\n\n // Legacy search using prefix of script name instead of command name\n if (!localFile && !subcommand._executableFile && this._scriptPath) {\n const legacyName = path.basename(\n this._scriptPath,\n path.extname(this._scriptPath),\n );\n if (legacyName !== this._name) {\n localFile = findFile(\n executableDir,\n `${legacyName}-${subcommand._name}`,\n );\n }\n }\n executableFile = localFile || executableFile;\n }\n\n launchWithNode = sourceExt.includes(path.extname(executableFile));\n\n let proc;\n if (process.platform !== 'win32') {\n if (launchWithNode) {\n args.unshift(executableFile);\n // add executable arguments to spawn\n args = incrementNodeInspectorPort(process.execArgv).concat(args);\n\n proc = childProcess.spawn(process.argv[0], args, { stdio: 'inherit' });\n } else {\n proc = childProcess.spawn(executableFile, args, { stdio: 'inherit' });\n }\n } else {\n this._checkForMissingExecutable(\n executableFile,\n executableDir,\n subcommand._name,\n );\n args.unshift(executableFile);\n // add executable arguments to spawn\n args = incrementNodeInspectorPort(process.execArgv).concat(args);\n proc = childProcess.spawn(process.execPath, args, { stdio: 'inherit' });\n }\n\n if (!proc.killed) {\n // testing mainly to avoid leak warnings during unit tests with mocked spawn\n const signals = ['SIGUSR1', 'SIGUSR2', 'SIGTERM', 'SIGINT', 'SIGHUP'];\n signals.forEach((signal) => {\n process.on(signal, () => {\n if (proc.killed === false && proc.exitCode === null) {\n // @ts-ignore because signals not typed to known strings\n proc.kill(signal);\n }\n });\n });\n }\n\n // By default terminate process when spawned process terminates.\n const exitCallback = this._exitCallback;\n proc.on('close', (code) => {\n code = code ?? 1; // code is null if spawned process terminated due to a signal\n if (!exitCallback) {\n process.exit(code);\n } else {\n exitCallback(\n new CommanderError(\n code,\n 'commander.executeSubCommandAsync',\n '(close)',\n ),\n );\n }\n });\n proc.on('error', (err) => {\n // @ts-ignore: because err.code is an unknown property\n if (err.code === 'ENOENT') {\n this._checkForMissingExecutable(\n executableFile,\n executableDir,\n subcommand._name,\n );\n // @ts-ignore: because err.code is an unknown property\n } else if (err.code === 'EACCES') {\n throw new Error(`'${executableFile}' not executable`);\n }\n if (!exitCallback) {\n process.exit(1);\n } else {\n const wrappedError = new CommanderError(\n 1,\n 'commander.executeSubCommandAsync',\n '(error)',\n );\n wrappedError.nestedError = err;\n exitCallback(wrappedError);\n }\n });\n\n // Store the reference to the child process\n this.runningCommand = proc;\n }\n\n /**\n * @private\n */\n\n _dispatchSubcommand(commandName, operands, unknown) {\n const subCommand = this._findCommand(commandName);\n if (!subCommand) this.help({ error: true });\n\n subCommand._prepareForParse();\n let promiseChain;\n promiseChain = this._chainOrCallSubCommandHook(\n promiseChain,\n subCommand,\n 'preSubcommand',\n );\n promiseChain = this._chainOrCall(promiseChain, () => {\n if (subCommand._executableHandler) {\n this._executeSubCommand(subCommand, operands.concat(unknown));\n } else {\n return subCommand._parseCommand(operands, unknown);\n }\n });\n return promiseChain;\n }\n\n /**\n * Invoke help directly if possible, or dispatch if necessary.\n * e.g. help foo\n *\n * @private\n */\n\n _dispatchHelpCommand(subcommandName) {\n if (!subcommandName) {\n this.help();\n }\n const subCommand = this._findCommand(subcommandName);\n if (subCommand && !subCommand._executableHandler) {\n subCommand.help();\n }\n\n // Fallback to parsing the help flag to invoke the help.\n return this._dispatchSubcommand(\n subcommandName,\n [],\n [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? '--help'],\n );\n }\n\n /**\n * Check this.args against expected this.registeredArguments.\n *\n * @private\n */\n\n _checkNumberOfArguments() {\n // too few\n this.registeredArguments.forEach((arg, i) => {\n if (arg.required && this.args[i] == null) {\n this.missingArgument(arg.name());\n }\n });\n // too many\n if (\n this.registeredArguments.length > 0 &&\n this.registeredArguments[this.registeredArguments.length - 1].variadic\n ) {\n return;\n }\n if (this.args.length > this.registeredArguments.length) {\n this._excessArguments(this.args);\n }\n }\n\n /**\n * Process this.args using this.registeredArguments and save as this.processedArgs!\n *\n * @private\n */\n\n _processArguments() {\n const myParseArg = (argument, value, previous) => {\n // Extra processing for nice error message on parsing failure.\n let parsedValue = value;\n if (value !== null && argument.parseArg) {\n const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;\n parsedValue = this._callParseArg(\n argument,\n value,\n previous,\n invalidValueMessage,\n );\n }\n return parsedValue;\n };\n\n this._checkNumberOfArguments();\n\n const processedArgs = [];\n this.registeredArguments.forEach((declaredArg, index) => {\n let value = declaredArg.defaultValue;\n if (declaredArg.variadic) {\n // Collect together remaining arguments for passing together as an array.\n if (index < this.args.length) {\n value = this.args.slice(index);\n if (declaredArg.parseArg) {\n value = value.reduce((processed, v) => {\n return myParseArg(declaredArg, v, processed);\n }, declaredArg.defaultValue);\n }\n } else if (value === undefined) {\n value = [];\n }\n } else if (index < this.args.length) {\n value = this.args[index];\n if (declaredArg.parseArg) {\n value = myParseArg(declaredArg, value, declaredArg.defaultValue);\n }\n }\n processedArgs[index] = value;\n });\n this.processedArgs = processedArgs;\n }\n\n /**\n * Once we have a promise we chain, but call synchronously until then.\n *\n * @param {(Promise|undefined)} promise\n * @param {Function} fn\n * @return {(Promise|undefined)}\n * @private\n */\n\n _chainOrCall(promise, fn) {\n // thenable\n if (promise?.then && typeof promise.then === 'function') {\n // already have a promise, chain callback\n return promise.then(() => fn());\n }\n // callback might return a promise\n return fn();\n }\n\n /**\n *\n * @param {(Promise|undefined)} promise\n * @param {string} event\n * @return {(Promise|undefined)}\n * @private\n */\n\n _chainOrCallHooks(promise, event) {\n let result = promise;\n const hooks = [];\n this._getCommandAndAncestors()\n .reverse()\n .filter((cmd) => cmd._lifeCycleHooks[event] !== undefined)\n .forEach((hookedCommand) => {\n hookedCommand._lifeCycleHooks[event].forEach((callback) => {\n hooks.push({ hookedCommand, callback });\n });\n });\n if (event === 'postAction') {\n hooks.reverse();\n }\n\n hooks.forEach((hookDetail) => {\n result = this._chainOrCall(result, () => {\n return hookDetail.callback(hookDetail.hookedCommand, this);\n });\n });\n return result;\n }\n\n /**\n *\n * @param {(Promise|undefined)} promise\n * @param {Command} subCommand\n * @param {string} event\n * @return {(Promise|undefined)}\n * @private\n */\n\n _chainOrCallSubCommandHook(promise, subCommand, event) {\n let result = promise;\n if (this._lifeCycleHooks[event] !== undefined) {\n this._lifeCycleHooks[event].forEach((hook) => {\n result = this._chainOrCall(result, () => {\n return hook(this, subCommand);\n });\n });\n }\n return result;\n }\n\n /**\n * Process arguments in context of this command.\n * Returns action result, in case it is a promise.\n *\n * @private\n */\n\n _parseCommand(operands, unknown) {\n const parsed = this.parseOptions(unknown);\n this._parseOptionsEnv(); // after cli, so parseArg not called on both cli and env\n this._parseOptionsImplied();\n operands = operands.concat(parsed.operands);\n unknown = parsed.unknown;\n this.args = operands.concat(unknown);\n\n if (operands && this._findCommand(operands[0])) {\n return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);\n }\n if (\n this._getHelpCommand() &&\n operands[0] === this._getHelpCommand().name()\n ) {\n return this._dispatchHelpCommand(operands[1]);\n }\n if (this._defaultCommandName) {\n this._outputHelpIfRequested(unknown); // Run the help for default command from parent rather than passing to default command\n return this._dispatchSubcommand(\n this._defaultCommandName,\n operands,\n unknown,\n );\n }\n if (\n this.commands.length &&\n this.args.length === 0 &&\n !this._actionHandler &&\n !this._defaultCommandName\n ) {\n // probably missing subcommand and no handler, user needs help (and exit)\n this.help({ error: true });\n }\n\n this._outputHelpIfRequested(parsed.unknown);\n this._checkForMissingMandatoryOptions();\n this._checkForConflictingOptions();\n\n // We do not always call this check to avoid masking a \"better\" error, like unknown command.\n const checkForUnknownOptions = () => {\n if (parsed.unknown.length > 0) {\n this.unknownOption(parsed.unknown[0]);\n }\n };\n\n const commandEvent = `command:${this.name()}`;\n if (this._actionHandler) {\n checkForUnknownOptions();\n this._processArguments();\n\n let promiseChain;\n promiseChain = this._chainOrCallHooks(promiseChain, 'preAction');\n promiseChain = this._chainOrCall(promiseChain, () =>\n this._actionHandler(this.processedArgs),\n );\n if (this.parent) {\n promiseChain = this._chainOrCall(promiseChain, () => {\n this.parent.emit(commandEvent, operands, unknown); // legacy\n });\n }\n promiseChain = this._chainOrCallHooks(promiseChain, 'postAction');\n return promiseChain;\n }\n if (this.parent?.listenerCount(commandEvent)) {\n checkForUnknownOptions();\n this._processArguments();\n this.parent.emit(commandEvent, operands, unknown); // legacy\n } else if (operands.length) {\n if (this._findCommand('*')) {\n // legacy default command\n return this._dispatchSubcommand('*', operands, unknown);\n }\n if (this.listenerCount('command:*')) {\n // skip option check, emit event for possible misspelling suggestion\n this.emit('command:*', operands, unknown);\n } else if (this.commands.length) {\n this.unknownCommand();\n } else {\n checkForUnknownOptions();\n this._processArguments();\n }\n } else if (this.commands.length) {\n checkForUnknownOptions();\n // This command has subcommands and nothing hooked up at this level, so display help (and exit).\n this.help({ error: true });\n } else {\n checkForUnknownOptions();\n this._processArguments();\n // fall through for caller to handle after calling .parse()\n }\n }\n\n /**\n * Find matching command.\n *\n * @private\n * @return {Command | undefined}\n */\n _findCommand(name) {\n if (!name) return undefined;\n return this.commands.find(\n (cmd) => cmd._name === name || cmd._aliases.includes(name),\n );\n }\n\n /**\n * Return an option matching `arg` if any.\n *\n * @param {string} arg\n * @return {Option}\n * @package\n */\n\n _findOption(arg) {\n return this.options.find((option) => option.is(arg));\n }\n\n /**\n * Display an error message if a mandatory option does not have a value.\n * Called after checking for help flags in leaf subcommand.\n *\n * @private\n */\n\n _checkForMissingMandatoryOptions() {\n // Walk up hierarchy so can call in subcommand after checking for displaying help.\n this._getCommandAndAncestors().forEach((cmd) => {\n cmd.options.forEach((anOption) => {\n if (\n anOption.mandatory &&\n cmd.getOptionValue(anOption.attributeName()) === undefined\n ) {\n cmd.missingMandatoryOptionValue(anOption);\n }\n });\n });\n }\n\n /**\n * Display an error message if conflicting options are used together in this.\n *\n * @private\n */\n _checkForConflictingLocalOptions() {\n const definedNonDefaultOptions = this.options.filter((option) => {\n const optionKey = option.attributeName();\n if (this.getOptionValue(optionKey) === undefined) {\n return false;\n }\n return this.getOptionValueSource(optionKey) !== 'default';\n });\n\n const optionsWithConflicting = definedNonDefaultOptions.filter(\n (option) => option.conflictsWith.length > 0,\n );\n\n optionsWithConflicting.forEach((option) => {\n const conflictingAndDefined = definedNonDefaultOptions.find((defined) =>\n option.conflictsWith.includes(defined.attributeName()),\n );\n if (conflictingAndDefined) {\n this._conflictingOption(option, conflictingAndDefined);\n }\n });\n }\n\n /**\n * Display an error message if conflicting options are used together.\n * Called after checking for help flags in leaf subcommand.\n *\n * @private\n */\n _checkForConflictingOptions() {\n // Walk up hierarchy so can call in subcommand after checking for displaying help.\n this._getCommandAndAncestors().forEach((cmd) => {\n cmd._checkForConflictingLocalOptions();\n });\n }\n\n /**\n * Parse options from `argv` removing known options,\n * and return argv split into operands and unknown arguments.\n *\n * Side effects: modifies command by storing options. Does not reset state if called again.\n *\n * Examples:\n *\n * argv => operands, unknown\n * --known kkk op => [op], []\n * op --known kkk => [op], []\n * sub --unknown uuu op => [sub], [--unknown uuu op]\n * sub -- --unknown uuu op => [sub --unknown uuu op], []\n *\n * @param {string[]} args\n * @return {{operands: string[], unknown: string[]}}\n */\n\n parseOptions(args) {\n const operands = []; // operands, not options or values\n const unknown = []; // first unknown option and remaining unknown args\n let dest = operands;\n\n function maybeOption(arg) {\n return arg.length > 1 && arg[0] === '-';\n }\n\n const negativeNumberArg = (arg) => {\n // return false if not a negative number\n if (!/^-(\\d+|\\d*\\.\\d+)(e[+-]?\\d+)?$/.test(arg)) return false;\n // negative number is ok unless digit used as an option in command hierarchy\n return !this._getCommandAndAncestors().some((cmd) =>\n cmd.options\n .map((opt) => opt.short)\n .some((short) => /^-\\d$/.test(short)),\n );\n };\n\n // parse options\n let activeVariadicOption = null;\n let activeGroup = null; // working through group of short options, like -abc\n let i = 0;\n while (i < args.length || activeGroup) {\n const arg = activeGroup ?? args[i++];\n activeGroup = null;\n\n // literal\n if (arg === '--') {\n if (dest === unknown) dest.push(arg);\n dest.push(...args.slice(i));\n break;\n }\n\n if (\n activeVariadicOption &&\n (!maybeOption(arg) || negativeNumberArg(arg))\n ) {\n this.emit(`option:${activeVariadicOption.name()}`, arg);\n continue;\n }\n activeVariadicOption = null;\n\n if (maybeOption(arg)) {\n const option = this._findOption(arg);\n // recognised option, call listener to assign value with possible custom processing\n if (option) {\n if (option.required) {\n const value = args[i++];\n if (value === undefined) this.optionMissingArgument(option);\n this.emit(`option:${option.name()}`, value);\n } else if (option.optional) {\n let value = null;\n // historical behaviour is optional value is following arg unless an option\n if (\n i < args.length &&\n (!maybeOption(args[i]) || negativeNumberArg(args[i]))\n ) {\n value = args[i++];\n }\n this.emit(`option:${option.name()}`, value);\n } else {\n // boolean flag\n this.emit(`option:${option.name()}`);\n }\n activeVariadicOption = option.variadic ? option : null;\n continue;\n }\n }\n\n // Look for combo options following single dash, eat first one if known.\n if (arg.length > 2 && arg[0] === '-' && arg[1] !== '-') {\n const option = this._findOption(`-${arg[1]}`);\n if (option) {\n if (\n option.required ||\n (option.optional && this._combineFlagAndOptionalValue)\n ) {\n // option with value following in same argument\n this.emit(`option:${option.name()}`, arg.slice(2));\n } else {\n // boolean option\n this.emit(`option:${option.name()}`);\n // remove the processed option and keep processing group\n activeGroup = `-${arg.slice(2)}`;\n }\n continue;\n }\n }\n\n // Look for known long flag with value, like --foo=bar\n if (/^--[^=]+=/.test(arg)) {\n const index = arg.indexOf('=');\n const option = this._findOption(arg.slice(0, index));\n if (option && (option.required || option.optional)) {\n this.emit(`option:${option.name()}`, arg.slice(index + 1));\n continue;\n }\n }\n\n // Not a recognised option by this command.\n // Might be a command-argument, or subcommand option, or unknown option, or help command or option.\n\n // An unknown option means further arguments also classified as unknown so can be reprocessed by subcommands.\n // A negative number in a leaf command is not an unknown option.\n if (\n dest === operands &&\n maybeOption(arg) &&\n !(this.commands.length === 0 && negativeNumberArg(arg))\n ) {\n dest = unknown;\n }\n\n // If using positionalOptions, stop processing our options at subcommand.\n if (\n (this._enablePositionalOptions || this._passThroughOptions) &&\n operands.length === 0 &&\n unknown.length === 0\n ) {\n if (this._findCommand(arg)) {\n operands.push(arg);\n unknown.push(...args.slice(i));\n break;\n } else if (\n this._getHelpCommand() &&\n arg === this._getHelpCommand().name()\n ) {\n operands.push(arg, ...args.slice(i));\n break;\n } else if (this._defaultCommandName) {\n unknown.push(arg, ...args.slice(i));\n break;\n }\n }\n\n // If using passThroughOptions, stop processing options at first command-argument.\n if (this._passThroughOptions) {\n dest.push(arg, ...args.slice(i));\n break;\n }\n\n // add arg\n dest.push(arg);\n }\n\n return { operands, unknown };\n }\n\n /**\n * Return an object containing local option values as key-value pairs.\n *\n * @return {object}\n */\n opts() {\n if (this._storeOptionsAsProperties) {\n // Preserve original behaviour so backwards compatible when still using properties\n const result = {};\n const len = this.options.length;\n\n for (let i = 0; i < len; i++) {\n const key = this.options[i].attributeName();\n result[key] =\n key === this._versionOptionName ? this._version : this[key];\n }\n return result;\n }\n\n return this._optionValues;\n }\n\n /**\n * Return an object containing merged local and global option values as key-value pairs.\n *\n * @return {object}\n */\n optsWithGlobals() {\n // globals overwrite locals\n return this._getCommandAndAncestors().reduce(\n (combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()),\n {},\n );\n }\n\n /**\n * Display error message and exit (or call exitOverride).\n *\n * @param {string} message\n * @param {object} [errorOptions]\n * @param {string} [errorOptions.code] - an id string representing the error\n * @param {number} [errorOptions.exitCode] - used with process.exit\n */\n error(message, errorOptions) {\n // output handling\n this._outputConfiguration.outputError(\n `${message}\\n`,\n this._outputConfiguration.writeErr,\n );\n if (typeof this._showHelpAfterError === 'string') {\n this._outputConfiguration.writeErr(`${this._showHelpAfterError}\\n`);\n } else if (this._showHelpAfterError) {\n this._outputConfiguration.writeErr('\\n');\n this.outputHelp({ error: true });\n }\n\n // exit handling\n const config = errorOptions || {};\n const exitCode = config.exitCode || 1;\n const code = config.code || 'commander.error';\n this._exit(exitCode, code, message);\n }\n\n /**\n * Apply any option related environment variables, if option does\n * not have a value from cli or client code.\n *\n * @private\n */\n _parseOptionsEnv() {\n this.options.forEach((option) => {\n if (option.envVar && option.envVar in process.env) {\n const optionKey = option.attributeName();\n // Priority check. Do not overwrite cli or options from unknown source (client-code).\n if (\n this.getOptionValue(optionKey) === undefined ||\n ['default', 'config', 'env'].includes(\n this.getOptionValueSource(optionKey),\n )\n ) {\n if (option.required || option.optional) {\n // option can take a value\n // keep very simple, optional always takes value\n this.emit(`optionEnv:${option.name()}`, process.env[option.envVar]);\n } else {\n // boolean\n // keep very simple, only care that envVar defined and not the value\n this.emit(`optionEnv:${option.name()}`);\n }\n }\n }\n });\n }\n\n /**\n * Apply any implied option values, if option is undefined or default value.\n *\n * @private\n */\n _parseOptionsImplied() {\n const dualHelper = new DualOptions(this.options);\n const hasCustomOptionValue = (optionKey) => {\n return (\n this.getOptionValue(optionKey) !== undefined &&\n !['default', 'implied'].includes(this.getOptionValueSource(optionKey))\n );\n };\n this.options\n .filter(\n (option) =>\n option.implied !== undefined &&\n hasCustomOptionValue(option.attributeName()) &&\n dualHelper.valueFromOption(\n this.getOptionValue(option.attributeName()),\n option,\n ),\n )\n .forEach((option) => {\n Object.keys(option.implied)\n .filter((impliedKey) => !hasCustomOptionValue(impliedKey))\n .forEach((impliedKey) => {\n this.setOptionValueWithSource(\n impliedKey,\n option.implied[impliedKey],\n 'implied',\n );\n });\n });\n }\n\n /**\n * Argument `name` is missing.\n *\n * @param {string} name\n * @private\n */\n\n missingArgument(name) {\n const message = `error: missing required argument '${name}'`;\n this.error(message, { code: 'commander.missingArgument' });\n }\n\n /**\n * `Option` is missing an argument.\n *\n * @param {Option} option\n * @private\n */\n\n optionMissingArgument(option) {\n const message = `error: option '${option.flags}' argument missing`;\n this.error(message, { code: 'commander.optionMissingArgument' });\n }\n\n /**\n * `Option` does not have a value, and is a mandatory option.\n *\n * @param {Option} option\n * @private\n */\n\n missingMandatoryOptionValue(option) {\n const message = `error: required option '${option.flags}' not specified`;\n this.error(message, { code: 'commander.missingMandatoryOptionValue' });\n }\n\n /**\n * `Option` conflicts with another option.\n *\n * @param {Option} option\n * @param {Option} conflictingOption\n * @private\n */\n _conflictingOption(option, conflictingOption) {\n // The calling code does not know whether a negated option is the source of the\n // value, so do some work to take an educated guess.\n const findBestOptionFromValue = (option) => {\n const optionKey = option.attributeName();\n const optionValue = this.getOptionValue(optionKey);\n const negativeOption = this.options.find(\n (target) => target.negate && optionKey === target.attributeName(),\n );\n const positiveOption = this.options.find(\n (target) => !target.negate && optionKey === target.attributeName(),\n );\n if (\n negativeOption &&\n ((negativeOption.presetArg === undefined && optionValue === false) ||\n (negativeOption.presetArg !== undefined &&\n optionValue === negativeOption.presetArg))\n ) {\n return negativeOption;\n }\n return positiveOption || option;\n };\n\n const getErrorMessage = (option) => {\n const bestOption = findBestOptionFromValue(option);\n const optionKey = bestOption.attributeName();\n const source = this.getOptionValueSource(optionKey);\n if (source === 'env') {\n return `environment variable '${bestOption.envVar}'`;\n }\n return `option '${bestOption.flags}'`;\n };\n\n const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;\n this.error(message, { code: 'commander.conflictingOption' });\n }\n\n /**\n * Unknown option `flag`.\n *\n * @param {string} flag\n * @private\n */\n\n unknownOption(flag) {\n if (this._allowUnknownOption) return;\n let suggestion = '';\n\n if (flag.startsWith('--') && this._showSuggestionAfterError) {\n // Looping to pick up the global options too\n let candidateFlags = [];\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n let command = this;\n do {\n const moreFlags = command\n .createHelp()\n .visibleOptions(command)\n .filter((option) => option.long)\n .map((option) => option.long);\n candidateFlags = candidateFlags.concat(moreFlags);\n command = command.parent;\n } while (command && !command._enablePositionalOptions);\n suggestion = suggestSimilar(flag, candidateFlags);\n }\n\n const message = `error: unknown option '${flag}'${suggestion}`;\n this.error(message, { code: 'commander.unknownOption' });\n }\n\n /**\n * Excess arguments, more than expected.\n *\n * @param {string[]} receivedArgs\n * @private\n */\n\n _excessArguments(receivedArgs) {\n if (this._allowExcessArguments) return;\n\n const expected = this.registeredArguments.length;\n const s = expected === 1 ? '' : 's';\n const forSubcommand = this.parent ? ` for '${this.name()}'` : '';\n const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;\n this.error(message, { code: 'commander.excessArguments' });\n }\n\n /**\n * Unknown command.\n *\n * @private\n */\n\n unknownCommand() {\n const unknownName = this.args[0];\n let suggestion = '';\n\n if (this._showSuggestionAfterError) {\n const candidateNames = [];\n this.createHelp()\n .visibleCommands(this)\n .forEach((command) => {\n candidateNames.push(command.name());\n // just visible alias\n if (command.alias()) candidateNames.push(command.alias());\n });\n suggestion = suggestSimilar(unknownName, candidateNames);\n }\n\n const message = `error: unknown command '${unknownName}'${suggestion}`;\n this.error(message, { code: 'commander.unknownCommand' });\n }\n\n /**\n * Get or set the program version.\n *\n * This method auto-registers the \"-V, --version\" option which will print the version number.\n *\n * You can optionally supply the flags and description to override the defaults.\n *\n * @param {string} [str]\n * @param {string} [flags]\n * @param {string} [description]\n * @return {(this | string | undefined)} `this` command for chaining, or version string if no arguments\n */\n\n version(str, flags, description) {\n if (str === undefined) return this._version;\n this._version = str;\n flags = flags || '-V, --version';\n description = description || 'output the version number';\n const versionOption = this.createOption(flags, description);\n this._versionOptionName = versionOption.attributeName();\n this._registerOption(versionOption);\n\n this.on('option:' + versionOption.name(), () => {\n this._outputConfiguration.writeOut(`${str}\\n`);\n this._exit(0, 'commander.version', str);\n });\n return this;\n }\n\n /**\n * Set the description.\n *\n * @param {string} [str]\n * @param {object} [argsDescription]\n * @return {(string|Command)}\n */\n description(str, argsDescription) {\n if (str === undefined && argsDescription === undefined)\n return this._description;\n this._description = str;\n if (argsDescription) {\n this._argsDescription = argsDescription;\n }\n return this;\n }\n\n /**\n * Set the summary. Used when listed as subcommand of parent.\n *\n * @param {string} [str]\n * @return {(string|Command)}\n */\n summary(str) {\n if (str === undefined) return this._summary;\n this._summary = str;\n return this;\n }\n\n /**\n * Set an alias for the command.\n *\n * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.\n *\n * @param {string} [alias]\n * @return {(string|Command)}\n */\n\n alias(alias) {\n if (alias === undefined) return this._aliases[0]; // just return first, for backwards compatibility\n\n /** @type {Command} */\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n let command = this;\n if (\n this.commands.length !== 0 &&\n this.commands[this.commands.length - 1]._executableHandler\n ) {\n // assume adding alias for last added executable subcommand, rather than this\n command = this.commands[this.commands.length - 1];\n }\n\n if (alias === command._name)\n throw new Error(\"Command alias can't be the same as its name\");\n const matchingCommand = this.parent?._findCommand(alias);\n if (matchingCommand) {\n // c.f. _registerCommand\n const existingCmd = [matchingCommand.name()]\n .concat(matchingCommand.aliases())\n .join('|');\n throw new Error(\n `cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`,\n );\n }\n\n command._aliases.push(alias);\n return this;\n }\n\n /**\n * Set aliases for the command.\n *\n * Only the first alias is shown in the auto-generated help.\n *\n * @param {string[]} [aliases]\n * @return {(string[]|Command)}\n */\n\n aliases(aliases) {\n // Getter for the array of aliases is the main reason for having aliases() in addition to alias().\n if (aliases === undefined) return this._aliases;\n\n aliases.forEach((alias) => this.alias(alias));\n return this;\n }\n\n /**\n * Set / get the command usage `str`.\n *\n * @param {string} [str]\n * @return {(string|Command)}\n */\n\n usage(str) {\n if (str === undefined) {\n if (this._usage) return this._usage;\n\n const args = this.registeredArguments.map((arg) => {\n return humanReadableArgName(arg);\n });\n return []\n .concat(\n this.options.length || this._helpOption !== null ? '[options]' : [],\n this.commands.length ? '[command]' : [],\n this.registeredArguments.length ? args : [],\n )\n .join(' ');\n }\n\n this._usage = str;\n return this;\n }\n\n /**\n * Get or set the name of the command.\n *\n * @param {string} [str]\n * @return {(string|Command)}\n */\n\n name(str) {\n if (str === undefined) return this._name;\n this._name = str;\n return this;\n }\n\n /**\n * Set/get the help group heading for this subcommand in parent command's help.\n *\n * @param {string} [heading]\n * @return {Command | string}\n */\n\n helpGroup(heading) {\n if (heading === undefined) return this._helpGroupHeading ?? '';\n this._helpGroupHeading = heading;\n return this;\n }\n\n /**\n * Set/get the default help group heading for subcommands added to this command.\n * (This does not override a group set directly on the subcommand using .helpGroup().)\n *\n * @example\n * program.commandsGroup('Development Commands:);\n * program.command('watch')...\n * program.command('lint')...\n * ...\n *\n * @param {string} [heading]\n * @returns {Command | string}\n */\n commandsGroup(heading) {\n if (heading === undefined) return this._defaultCommandGroup ?? '';\n this._defaultCommandGroup = heading;\n return this;\n }\n\n /**\n * Set/get the default help group heading for options added to this command.\n * (This does not override a group set directly on the option using .helpGroup().)\n *\n * @example\n * program\n * .optionsGroup('Development Options:')\n * .option('-d, --debug', 'output extra debugging')\n * .option('-p, --profile', 'output profiling information')\n *\n * @param {string} [heading]\n * @returns {Command | string}\n */\n optionsGroup(heading) {\n if (heading === undefined) return this._defaultOptionGroup ?? '';\n this._defaultOptionGroup = heading;\n return this;\n }\n\n /**\n * @param {Option} option\n * @private\n */\n _initOptionGroup(option) {\n if (this._defaultOptionGroup && !option.helpGroupHeading)\n option.helpGroup(this._defaultOptionGroup);\n }\n\n /**\n * @param {Command} cmd\n * @private\n */\n _initCommandGroup(cmd) {\n if (this._defaultCommandGroup && !cmd.helpGroup())\n cmd.helpGroup(this._defaultCommandGroup);\n }\n\n /**\n * Set the name of the command from script filename, such as process.argv[1],\n * or require.main.filename, or __filename.\n *\n * (Used internally and public although not documented in README.)\n *\n * @example\n * program.nameFromFilename(require.main.filename);\n *\n * @param {string} filename\n * @return {Command}\n */\n\n nameFromFilename(filename) {\n this._name = path.basename(filename, path.extname(filename));\n\n return this;\n }\n\n /**\n * Get or set the directory for searching for executable subcommands of this command.\n *\n * @example\n * program.executableDir(__dirname);\n * // or\n * program.executableDir('subcommands');\n *\n * @param {string} [path]\n * @return {(string|null|Command)}\n */\n\n executableDir(path) {\n if (path === undefined) return this._executableDir;\n this._executableDir = path;\n return this;\n }\n\n /**\n * Return program help documentation.\n *\n * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout\n * @return {string}\n */\n\n helpInformation(contextOptions) {\n const helper = this.createHelp();\n const context = this._getOutputContext(contextOptions);\n helper.prepareContext({\n error: context.error,\n helpWidth: context.helpWidth,\n outputHasColors: context.hasColors,\n });\n const text = helper.formatHelp(this, helper);\n if (context.hasColors) return text;\n return this._outputConfiguration.stripColor(text);\n }\n\n /**\n * @typedef HelpContext\n * @type {object}\n * @property {boolean} error\n * @property {number} helpWidth\n * @property {boolean} hasColors\n * @property {function} write - includes stripColor if needed\n *\n * @returns {HelpContext}\n * @private\n */\n\n _getOutputContext(contextOptions) {\n contextOptions = contextOptions || {};\n const error = !!contextOptions.error;\n let baseWrite;\n let hasColors;\n let helpWidth;\n if (error) {\n baseWrite = (str) => this._outputConfiguration.writeErr(str);\n hasColors = this._outputConfiguration.getErrHasColors();\n helpWidth = this._outputConfiguration.getErrHelpWidth();\n } else {\n baseWrite = (str) => this._outputConfiguration.writeOut(str);\n hasColors = this._outputConfiguration.getOutHasColors();\n helpWidth = this._outputConfiguration.getOutHelpWidth();\n }\n const write = (str) => {\n if (!hasColors) str = this._outputConfiguration.stripColor(str);\n return baseWrite(str);\n };\n return { error, write, hasColors, helpWidth };\n }\n\n /**\n * Output help information for this command.\n *\n * Outputs built-in help, and custom text added using `.addHelpText()`.\n *\n * @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout\n */\n\n outputHelp(contextOptions) {\n let deprecatedCallback;\n if (typeof contextOptions === 'function') {\n deprecatedCallback = contextOptions;\n contextOptions = undefined;\n }\n\n const outputContext = this._getOutputContext(contextOptions);\n /** @type {HelpTextEventContext} */\n const eventContext = {\n error: outputContext.error,\n write: outputContext.write,\n command: this,\n };\n\n this._getCommandAndAncestors()\n .reverse()\n .forEach((command) => command.emit('beforeAllHelp', eventContext));\n this.emit('beforeHelp', eventContext);\n\n let helpInformation = this.helpInformation({ error: outputContext.error });\n if (deprecatedCallback) {\n helpInformation = deprecatedCallback(helpInformation);\n if (\n typeof helpInformation !== 'string' &&\n !Buffer.isBuffer(helpInformation)\n ) {\n throw new Error('outputHelp callback must return a string or a Buffer');\n }\n }\n outputContext.write(helpInformation);\n\n if (this._getHelpOption()?.long) {\n this.emit(this._getHelpOption().long); // deprecated\n }\n this.emit('afterHelp', eventContext);\n this._getCommandAndAncestors().forEach((command) =>\n command.emit('afterAllHelp', eventContext),\n );\n }\n\n /**\n * You can pass in flags and a description to customise the built-in help option.\n * Pass in false to disable the built-in help option.\n *\n * @example\n * program.helpOption('-?, --help' 'show help'); // customise\n * program.helpOption(false); // disable\n *\n * @param {(string | boolean)} flags\n * @param {string} [description]\n * @return {Command} `this` command for chaining\n */\n\n helpOption(flags, description) {\n // Support enabling/disabling built-in help option.\n if (typeof flags === 'boolean') {\n if (flags) {\n if (this._helpOption === null) this._helpOption = undefined; // reenable\n if (this._defaultOptionGroup) {\n // make the option to store the group\n this._initOptionGroup(this._getHelpOption());\n }\n } else {\n this._helpOption = null; // disable\n }\n return this;\n }\n\n // Customise flags and description.\n this._helpOption = this.createOption(\n flags ?? '-h, --help',\n description ?? 'display help for command',\n );\n // init group unless lazy create\n if (flags || description) this._initOptionGroup(this._helpOption);\n\n return this;\n }\n\n /**\n * Lazy create help option.\n * Returns null if has been disabled with .helpOption(false).\n *\n * @returns {(Option | null)} the help option\n * @package\n */\n _getHelpOption() {\n // Lazy create help option on demand.\n if (this._helpOption === undefined) {\n this.helpOption(undefined, undefined);\n }\n return this._helpOption;\n }\n\n /**\n * Supply your own option to use for the built-in help option.\n * This is an alternative to using helpOption() to customise the flags and description etc.\n *\n * @param {Option} option\n * @return {Command} `this` command for chaining\n */\n addHelpOption(option) {\n this._helpOption = option;\n this._initOptionGroup(option);\n return this;\n }\n\n /**\n * Output help information and exit.\n *\n * Outputs built-in help, and custom text added using `.addHelpText()`.\n *\n * @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout\n */\n\n help(contextOptions) {\n this.outputHelp(contextOptions);\n let exitCode = Number(process.exitCode ?? 0); // process.exitCode does allow a string or an integer, but we prefer just a number\n if (\n exitCode === 0 &&\n contextOptions &&\n typeof contextOptions !== 'function' &&\n contextOptions.error\n ) {\n exitCode = 1;\n }\n // message: do not have all displayed text available so only passing placeholder.\n this._exit(exitCode, 'commander.help', '(outputHelp)');\n }\n\n /**\n * // Do a little typing to coordinate emit and listener for the help text events.\n * @typedef HelpTextEventContext\n * @type {object}\n * @property {boolean} error\n * @property {Command} command\n * @property {function} write\n */\n\n /**\n * Add additional text to be displayed with the built-in help.\n *\n * Position is 'before' or 'after' to affect just this command,\n * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.\n *\n * @param {string} position - before or after built-in help\n * @param {(string | Function)} text - string to add, or a function returning a string\n * @return {Command} `this` command for chaining\n */\n\n addHelpText(position, text) {\n const allowedValues = ['beforeAll', 'before', 'after', 'afterAll'];\n if (!allowedValues.includes(position)) {\n throw new Error(`Unexpected value for position to addHelpText.\nExpecting one of '${allowedValues.join(\"', '\")}'`);\n }\n\n const helpEvent = `${position}Help`;\n this.on(helpEvent, (/** @type {HelpTextEventContext} */ context) => {\n let helpStr;\n if (typeof text === 'function') {\n helpStr = text({ error: context.error, command: context.command });\n } else {\n helpStr = text;\n }\n // Ignore falsy value when nothing to output.\n if (helpStr) {\n context.write(`${helpStr}\\n`);\n }\n });\n return this;\n }\n\n /**\n * Output help information if help flags specified\n *\n * @param {Array} args - array of options to search for help flags\n * @private\n */\n\n _outputHelpIfRequested(args) {\n const helpOption = this._getHelpOption();\n const helpRequested = helpOption && args.find((arg) => helpOption.is(arg));\n if (helpRequested) {\n this.outputHelp();\n // (Do not have all displayed text available so only passing placeholder.)\n this._exit(0, 'commander.helpDisplayed', '(outputHelp)');\n }\n }\n}\n\n/**\n * Scan arguments and increment port number for inspect calls (to avoid conflicts when spawning new command).\n *\n * @param {string[]} args - array of arguments from node.execArgv\n * @returns {string[]}\n * @private\n */\n\nfunction incrementNodeInspectorPort(args) {\n // Testing for these options:\n // --inspect[=[host:]port]\n // --inspect-brk[=[host:]port]\n // --inspect-port=[host:]port\n return args.map((arg) => {\n if (!arg.startsWith('--inspect')) {\n return arg;\n }\n let debugOption;\n let debugHost = '127.0.0.1';\n let debugPort = '9229';\n let match;\n if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {\n // e.g. --inspect\n debugOption = match[1];\n } else if (\n (match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null\n ) {\n debugOption = match[1];\n if (/^\\d+$/.test(match[3])) {\n // e.g. --inspect=1234\n debugPort = match[3];\n } else {\n // e.g. --inspect=localhost\n debugHost = match[3];\n }\n } else if (\n (match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\\d+)$/)) !== null\n ) {\n // e.g. --inspect=localhost:1234\n debugOption = match[1];\n debugHost = match[3];\n debugPort = match[4];\n }\n\n if (debugOption && debugPort !== '0') {\n return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;\n }\n return arg;\n });\n}\n\n/**\n * @returns {boolean | undefined}\n * @package\n */\nfunction useColor() {\n // Test for common conventions.\n // NB: the observed behaviour is in combination with how author adds color! For example:\n // - we do not test NODE_DISABLE_COLORS, but util:styletext does\n // - we do test NO_COLOR, but Chalk does not\n //\n // References:\n // https://no-color.org\n // https://bixense.com/clicolors/\n // https://github.com/nodejs/node/blob/0a00217a5f67ef4a22384cfc80eb6dd9a917fdc1/lib/internal/tty.js#L109\n // https://github.com/chalk/supports-color/blob/c214314a14bcb174b12b3014b2b0a8de375029ae/index.js#L33\n // (https://force-color.org recent web page from 2023, does not match major javascript implementations)\n\n if (\n process.env.NO_COLOR ||\n process.env.FORCE_COLOR === '0' ||\n process.env.FORCE_COLOR === 'false'\n )\n return false;\n if (process.env.FORCE_COLOR || process.env.CLICOLOR_FORCE !== undefined)\n return true;\n return undefined;\n}\n\nexports.Command = Command;\nexports.useColor = useColor; // exporting for tests\n", "const { Argument } = require('./lib/argument.js');\nconst { Command } = require('./lib/command.js');\nconst { CommanderError, InvalidArgumentError } = require('./lib/error.js');\nconst { Help } = require('./lib/help.js');\nconst { Option } = require('./lib/option.js');\n\nexports.program = new Command();\n\nexports.createCommand = (name) => new Command(name);\nexports.createOption = (flags, description) => new Option(flags, description);\nexports.createArgument = (name, description) => new Argument(name, description);\n\n/**\n * Expose classes\n */\n\nexports.Command = Command;\nexports.Option = Option;\nexports.Argument = Argument;\nexports.Help = Help;\n\nexports.CommanderError = CommanderError;\nexports.InvalidArgumentError = InvalidArgumentError;\nexports.InvalidOptionArgumentError = InvalidArgumentError; // Deprecated\n", "const commander = require('commander');\n\nexports = module.exports = {};\n\n// Return a different global program than commander,\n// and don't also return it as default export.\nexports.program = new commander.Command();\n\n/**\n * Expose classes. The FooT versions are just types, so return Commander original implementations!\n */\n\nexports.Argument = commander.Argument;\nexports.Command = commander.Command;\nexports.CommanderError = commander.CommanderError;\nexports.Help = commander.Help;\nexports.InvalidArgumentError = commander.InvalidArgumentError;\nexports.InvalidOptionArgumentError = commander.InvalidArgumentError; // Deprecated\nexports.Option = commander.Option;\n\nexports.createCommand = (name) => new commander.Command(name);\nexports.createOption = (flags, description) =>\n new commander.Option(flags, description);\nexports.createArgument = (name, description) =>\n new commander.Argument(name, description);\n", "import extraTypingsCommander from './index.js';\n\n// wrapper to provide named exports for ESM.\nexport const {\n program,\n createCommand,\n createArgument,\n createOption,\n CommanderError,\n InvalidArgumentError,\n InvalidOptionArgumentError, // deprecated old name\n Command,\n Argument,\n Option,\n Help,\n} = extraTypingsCommander;\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport {program} from \"@commander-js/extra-typings\"\nimport {mkdir, writeFile} from \"node:fs/promises\"\nimport {resolve} from \"node:path\"\n\nimport {getConfigFromEnv, KnowledgeApi, loadEnv} from \"./common\"\n\nexport function addDownloadKnowledgeCommand() {\n program\n .command(\"download-knowledge\")\n .description(\"Download files from an Open Web UI knowledge base\")\n .requiredOption(\"-o, --output-dir <outputDir>\", \"Folder path\")\n .action(async (opts) => {\n loadEnv()\n\n await mkdir(opts.outputDir, {recursive: true}).catch()\n\n const api = new KnowledgeApi(getConfigFromEnv())\n\n const knowledge = await api.listKnowledgeFiles()\n for (const file of knowledge.files) {\n const data = await api.downloadFile(file.id)\n\n if (data) {\n await writeFile(\n resolve(opts.outputDir, file.meta.name),\n data,\n \"utf-8\",\n )\n }\n }\n })\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport {program} from \"@commander-js/extra-typings\"\nimport {config} from \"dotenv\"\n\nimport type {GlobalCliOpts} from \"./types\"\n\nexport function loadEnv() {\n const options: GlobalCliOpts = program.optsWithGlobals()\n console.debug(options)\n if (options.env) {\n config({path: options.env})\n } else {\n config()\n }\n}\n\nexport interface SharedConfig {\n knowledgeId: string\n webUiKey: string\n webUiUrl: string\n}\n\nexport function getConfigFromEnv(): SharedConfig {\n const openWebUiUrl = process.env.WEB_UI_URL\n const openWebUiKey = process.env.WEB_UI_KEY\n const knowledgeId = process.env.KNOWLEDGE_ID\n\n if (!openWebUiUrl || !openWebUiKey || !knowledgeId) {\n throw new Error(\"WEB_UI_URL, WEB_UI_KEY, and KNOWLEDGE_ID must be set\")\n }\n return {\n knowledgeId,\n webUiKey: openWebUiKey,\n webUiUrl: openWebUiUrl,\n }\n}\n\nexport interface KnowledgeMeta {\n collection_name: string\n content_type: string\n data: Record<string, unknown>\n name: string\n size: number\n}\n\nexport interface KnowledgeResponse {\n files: {id: string; meta: KnowledgeMeta}[]\n}\n\nexport interface ErrorResponse {\n detail: string\n}\n\nexport class KnowledgeApi {\n private readonly config: SharedConfig\n private knowledgeCache: KnowledgeResponse | null = null\n\n constructor(config: SharedConfig) {\n this.config = config\n }\n\n get headers() {\n return {\n Authorization: `Bearer ${this.config.webUiKey}`,\n }\n }\n\n async listKnowledgeFiles() {\n if (this.knowledgeCache) {\n return this.knowledgeCache\n }\n const knowledge: KnowledgeResponse | ErrorResponse = await fetch(\n `${this.config.webUiUrl}/api/v1/knowledge/${this.config.knowledgeId}`,\n {\n headers: {\n ...this.headers,\n Accept: \"application/json\",\n },\n },\n ).then((res) => res.json())\n if (\"detail\" in knowledge) {\n throw new Error(knowledge.detail)\n } else {\n this.knowledgeCache = knowledge\n }\n return this.knowledgeCache\n }\n\n async downloadFile(fileId: string): Promise<string | null> {\n const fileResponse = await fetch(\n `${this.config.webUiUrl}/api/v1/files/${fileId}`,\n {\n headers: {\n ...this.headers,\n Accept: \"application/json\",\n },\n },\n ).then((res) => res.json())\n\n return fileResponse?.data?.content ?? \"\"\n }\n\n async removeKnowledgeFile(id: string) {\n return fetch(\n `${this.config.webUiUrl}/api/v1/knowledge/${this.config.knowledgeId}/file/remove`,\n {\n body: JSON.stringify({file_id: id}),\n headers: {\n ...this.headers,\n \"Content-Type\": \"application/json\",\n },\n method: \"POST\",\n },\n ).then((res) => res.json())\n }\n\n async deleteFile(id: string) {\n return fetch(`${this.config.webUiUrl}/api/v1/files/${id}`, {\n headers: {\n ...this.headers,\n \"Content-Type\": \"application/json\",\n },\n method: \"DELETE\",\n }).then((res) => res.json())\n }\n\n async uploadFile(\n fileBuffer: Buffer,\n name: string,\n ): Promise<{filename?: string; id?: string}> {\n const formData = new FormData()\n formData.append(\"file\", new Blob([fileBuffer as BlobPart]), name)\n formData.append(\"knowledge_id\", this.config.knowledgeId)\n\n return fetch(`${this.config.webUiUrl}/api/v1/files/`, {\n body: formData,\n headers: {\n ...this.headers,\n Accept: \"application/json\",\n },\n method: \"POST\",\n }).then((res) => res.json())\n }\n\n async associateFile(fileId: string): Promise<{name?: string}> {\n return fetch(\n `${this.config.webUiUrl}/api/v1/knowledge/${this.config.knowledgeId}/file/add`,\n {\n body: JSON.stringify({file_id: fileId}),\n headers: {\n ...this.headers,\n \"Content-Type\": \"application/json\",\n },\n method: \"POST\",\n },\n ).then((res) => res.json())\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport {program} from \"@commander-js/extra-typings\"\nimport {kebabCase} from \"change-case\"\nimport {\n access,\n mkdir,\n readdir,\n readFile,\n rm,\n stat,\n writeFile,\n} from \"node:fs/promises\"\nimport {basename, dirname, extname, join, resolve} from \"node:path\"\nimport remarkFrontmatter from \"remark-frontmatter\"\nimport remarkParse from \"remark-parse\"\nimport remarkParseFrontmatter from \"remark-parse-frontmatter\"\nimport remarkStringify from \"remark-stringify\"\nimport {unified} from \"unified\"\n\nimport type {\n QuiComment,\n QuiCommentDisplayPart,\n} from \"@qualcomm-ui/typedoc-common\"\n\nimport {remarkSelfLinkHeadings} from \"../docs-plugin\"\nimport {\n getPathnameFromPathSegments,\n getPathSegmentsFromFileName,\n} from \"../docs-plugin/internal\"\n\nimport {loadEnv} from \"./common\"\nimport {loadKnowledgeConfigFromEnv} from \"./load-config-from-env\"\nimport type {WebUiKnowledgeConfig} from \"./types\"\n\ninterface PageInfo {\n demosFolder?: string\n mdxFile: string\n name: string\n path: string\n url: string | undefined\n}\n\ninterface ProcessedPage {\n content: string\n demoFiles: string[]\n frontmatter: Record<string, string>\n title: string\n}\n\ninterface ImportedModule {\n content: string\n path: string\n}\n\ninterface ComponentProps {\n input?: PropInfo[]\n name: string\n output?: PropInfo[]\n props?: PropInfo[]\n}\n\ninterface DocProps {\n props: Record<string, ComponentProps>\n}\n\ninterface PropInfo {\n comment?: QuiComment\n defaultValue?: string\n name: string\n resolvedType?: {\n baseType?: string\n name?: string\n prettyType?: string\n required?: boolean\n type?: string\n }\n type: string\n}\n\ninterface SimplifiedProp {\n defaultValue?: string\n description: string\n name: string\n propType?: \"input\" | \"output\" | undefined\n required: boolean | undefined\n type: string\n}\n\nasync function exists(dirPath: string): Promise<boolean> {\n return access(dirPath)\n .then(() => true)\n .catch(() => false)\n}\n\nasync function loadDocProps(\n routesFolder: string,\n docPropsPath: string | undefined,\n verbose: boolean | undefined,\n): Promise<DocProps | null> {\n const resolvedDocPropsPath = docPropsPath\n ? (await exists(docPropsPath))\n ? docPropsPath\n : resolve(process.cwd(), docPropsPath)\n : join(dirname(routesFolder), \"doc-props.json\")\n\n if (!(await exists(resolvedDocPropsPath))) {\n if (verbose) {\n console.log(`Doc props file not found at: ${resolvedDocPropsPath}`)\n }\n return null\n }\n\n try {\n const content = await readFile(resolvedDocPropsPath, \"utf-8\")\n const docProps = JSON.parse(content) as DocProps\n if (verbose) {\n console.log(`Loaded doc props from: ${resolvedDocPropsPath}`)\n console.log(`Found ${Object.keys(docProps.props).length} component types`)\n }\n return docProps\n } catch (error) {\n if (verbose) {\n console.log(`Error loading doc props: ${error}`)\n }\n return null\n }\n}\n\nfunction formatComment(comment: QuiComment | null): string {\n if (!comment) {\n return \"\"\n }\n\n const parts: string[] = []\n\n // Format summary\n if (comment.summary && comment.summary.length > 0) {\n const summaryText = formatCommentParts(comment.summary)\n if (summaryText.trim()) {\n parts.push(summaryText.trim())\n }\n }\n\n // Format block tags\n if (comment.blockTags && comment.blockTags.length > 0) {\n for (const blockTag of comment.blockTags) {\n const tagContent = formatCommentParts(blockTag.content)\n if (tagContent.trim()) {\n const tagName = blockTag.tag.replace(\"@\", \"\")\n\n // Skip default tags since they're handled separately\n if (tagName === \"default\" || tagName === \"defaultValue\") {\n continue\n }\n\n // Special handling for other tags\n if (tagName === \"example\") {\n parts.push(`**Example:**\\n\\`\\`\\`\\n${tagContent.trim()}\\n\\`\\`\\``)\n } else {\n parts.push(`**${tagName}:** ${tagContent.trim()}`)\n }\n }\n }\n }\n\n return parts.join(\"\\n\\n\")\n}\n\nfunction formatCommentParts(parts: QuiCommentDisplayPart[]): string {\n return parts\n .map((part) => {\n switch (part.kind) {\n case \"text\":\n return part.text\n case \"code\":\n // Clean up malformed code blocks like \"```ts\\ntrue\\n```\"\n const codeText = part.text\n .replace(/```\\w*\\n?/g, \"\") // Remove opening code blocks with optional language\n .replace(/\\n?```/g, \"\") // Remove closing code blocks\n .trim()\n\n // If it's still multi-line after cleanup, use code block\n if (codeText.includes(\"\\n\")) {\n return `\\`\\`\\`\\n${codeText}\\n\\`\\`\\``\n } else {\n return codeText\n }\n default:\n if (\n \"tag\" in part &&\n part.tag === \"@link\" &&\n typeof part.target === \"string\"\n ) {\n return `[${part.text}](${part.target})`\n }\n return part.text\n }\n })\n .join(\"\")\n .replace(/\\n/g, \" \")\n .replace(/\\s+/g, \" \")\n .trim()\n}\n\nfunction convertPropInfo(\n propInfo: PropInfo,\n isPartial: boolean,\n propType: \"input\" | \"output\" | undefined = undefined,\n): SimplifiedProp {\n return {\n name: propInfo.name,\n type: extractBestType(propInfo),\n ...(propInfo.defaultValue && {\n defaultValue: cleanDefaultValue(propInfo.defaultValue),\n }),\n description: formatComment(propInfo.comment || null),\n propType,\n required: extractRequired(propInfo, isPartial) || undefined,\n }\n}\n\nfunction extractBestType(propInfo: PropInfo): string {\n const type = propInfo.resolvedType?.prettyType || propInfo.type\n\n return cleanType(type.startsWith(\"| \") ? type.substring(2) : type)\n}\n\nfunction extractRequired(propInfo: PropInfo, isPartial: boolean): boolean {\n return Boolean(propInfo.resolvedType?.required && !isPartial)\n}\n\nfunction cleanType(type: string): string {\n return type.replace(/\\n/g, \" \").replace(/\\s+/g, \" \").trim()\n}\n\nfunction cleanDefaultValue(defaultValue: string): string {\n return defaultValue.replace(/^\\n+/, \"\").replace(/\\n+$/, \"\").trim()\n}\n\nasync function scanPages(\n routesFolder: string,\n verbose: boolean | undefined,\n excludePatterns: string[] = [],\n baseUrl: string | undefined,\n): Promise<PageInfo[]> {\n const components: PageInfo[] = []\n\n function shouldExclude(dirPath: string): boolean {\n const dirName = basename(dirPath)\n return excludePatterns.some((pattern) => {\n if (pattern.includes(\"*\")) {\n const regex = new RegExp(`^${pattern.replace(/\\*/g, \".*\")}$`)\n return regex.test(dirName)\n }\n return dirName === pattern\n })\n }\n\n async function scanDirectory(dirPath: string): Promise<void> {\n if (shouldExclude(dirPath)) {\n if (verbose) {\n console.log(`Excluding directory: ${basename(dirPath)}`)\n }\n return\n }\n\n const entries = await readdir(dirPath, {withFileTypes: true})\n const mdxFiles = entries.filter((f) => f.name.endsWith(\".mdx\"))\n\n if (mdxFiles.length > 0) {\n const mdxFile = mdxFiles[0]\n const demosFolder = entries.find((f) => f.name === \"demos\")\n const demosFolderPath = demosFolder\n ? join(dirPath, demosFolder.name)\n : undefined\n\n // TODO: load routing strategy from qui-docs config.\n const segments = getPathSegmentsFromFileName(\n join(dirPath, mdxFile.name),\n routesFolder,\n )\n const url = getPathnameFromPathSegments(segments)\n\n components.push({\n demosFolder: demosFolderPath,\n mdxFile: join(dirPath, mdxFile.name),\n name: segments.at(-1)!,\n path: dirPath,\n url: baseUrl ? new URL(url, baseUrl).toString() : undefined,\n })\n\n if (verbose) {\n console.log(`Found component: ${basename(dirPath)}`)\n console.log(` Demos folder: ${demosFolderPath || \"NOT FOUND\"}`)\n }\n }\n\n for (const entry of entries) {\n const fullPath = join(dirPath, entry.name)\n const stats = await stat(fullPath)\n if (stats.isDirectory()) {\n await scanDirectory(fullPath)\n }\n }\n }\n\n await scanDirectory(routesFolder)\n return components\n}\n\nfunction isPreviewLine(trimmedLine: string): boolean {\n return (\n trimmedLine === \"// preview\" ||\n /^\\{\\s*\\/\\*\\s*preview\\s*\\*\\/\\s*\\}$/.test(trimmedLine) ||\n /^<!--\\s*preview\\s*-->$/.test(trimmedLine)\n )\n}\n\nfunction extractProps(\n props: ComponentProps,\n isPartial: boolean,\n): SimplifiedProp[] {\n const propsInfo: SimplifiedProp[] = []\n\n if (props.props?.length) {\n propsInfo.push(\n ...props.props.map((prop) => convertPropInfo(prop, isPartial)),\n )\n }\n if (props.input?.length) {\n propsInfo.push(\n ...props.input.map((prop) => convertPropInfo(prop, isPartial, \"input\")),\n )\n }\n if (props.output?.length) {\n propsInfo.push(\n ...props.output.map((prop) => convertPropInfo(prop, isPartial, \"output\")),\n )\n }\n\n return propsInfo\n}\n\nfunction removePreviewLines(code: string): string {\n return code\n .split(\"\\n\")\n .filter((line) => !isPreviewLine(line.trim()))\n .join(\"\\n\")\n}\n\nfunction getIntroLines(\n pages: Array<ProcessedPage>,\n projectName?: string,\n description?: string,\n baseUrl?: string,\n) {\n const lines: string[] = []\n\n if (projectName) {\n lines.push(`# ${projectName}`)\n lines.push(\"\")\n }\n\n if (description) {\n lines.push(`> ${description}`)\n lines.push(\"\")\n }\n\n lines.push(\"## Components and Integrations\")\n lines.push(\"\")\n\n for (const page of pages) {\n const url = baseUrl\n ? `${baseUrl}/${kebabCase(page.title)}`\n : `#${kebabCase(page.title)}`\n if (page.title.includes(\"Introduction\")) {\n lines.push(`- [${page.title}](${url}): introduction and getting started`)\n } else if (page.title.includes(\"Tailwind\")) {\n lines.push(\n `- [${page.title}](${url}): integration documentation and examples`,\n )\n } else {\n lines.push(\n `- [${page.title}](${url}): component documentation and examples`,\n )\n }\n }\n\n return lines.join(\"\\n\")\n}\n\nasync function generateLlmsTxt(\n pages: Array<ProcessedPage>,\n projectName?: string,\n description?: string,\n baseUrl?: string,\n): Promise<string> {\n const lines: string[] = [\n getIntroLines(pages, projectName, description, baseUrl),\n ]\n\n lines.push(\"## Documentation Content\")\n lines.push(\"\")\n\n for (const page of pages) {\n lines.push(`# ${page.title}`)\n lines.push(\"\")\n lines.push(page.content)\n lines.push(\"\")\n }\n\n return lines.join(\"\\n\")\n}\n\ninterface ProcessedPage {\n content: string\n demoFiles: string[]\n frontmatter: Record<string, string>\n title: string\n}\n\ninterface ImportedModule {\n content: string\n path: string\n}\n\nfunction extractRelativeImports(content: string): string[] {\n const imports: string[] = []\n const importRegex =\n /^import\\s+(?:{[^}]*}|[\\w*]+|\\*\\s+as\\s+\\w+)?\\s*(?:,\\s*{[^}]*})?\\s*from\\s+[\"'](\\.[^\"']+)[\"']/gm\n let match: RegExpExecArray | null\n while ((match = importRegex.exec(content)) !== null) {\n imports.push(match[1])\n }\n return imports\n}\n\nasync function resolveModulePath(\n importPath: string,\n fromFile: string,\n): Promise<string | null> {\n const fromDir = dirname(fromFile)\n const baseResolved = resolve(fromDir, importPath)\n const extensions = [\".ts\", \".tsx\", \".js\", \".jsx\", \"\"]\n for (const ext of extensions) {\n const fullPath = baseResolved + ext\n if (await exists(fullPath)) {\n return fullPath\n }\n }\n if (await exists(baseResolved)) {\n const indexPath = join(baseResolved, \"index.ts\")\n if (await exists(indexPath)) {\n return indexPath\n }\n }\n return null\n}\n\nasync function collectRelativeImports(\n filePath: string,\n visited: Set<string> = new Set(),\n verbose: boolean | undefined,\n): Promise<ImportedModule[]> {\n const normalizedPath = resolve(filePath)\n if (visited.has(normalizedPath)) {\n return []\n }\n visited.add(normalizedPath)\n const modules: ImportedModule[] = []\n try {\n const content = await readFile(normalizedPath, \"utf-8\")\n const relativeImports = extractRelativeImports(content)\n for (const importPath of relativeImports) {\n const resolvedPath = await resolveModulePath(importPath, normalizedPath)\n if (!resolvedPath) {\n if (verbose) {\n console.log(\n ` Could not resolve import: ${importPath} from ${normalizedPath}`,\n )\n }\n continue\n }\n const importContent = await readFile(resolvedPath, \"utf-8\")\n modules.push({\n content: importContent,\n path: resolvedPath,\n })\n const nestedModules = await collectRelativeImports(\n resolvedPath,\n visited,\n verbose,\n )\n modules.push(...nestedModules)\n }\n } catch (error) {\n if (verbose) {\n console.log(` Error processing ${normalizedPath}: ${error}`)\n }\n }\n return modules\n}\n\nasync function processMdxContent(\n mdxContent: string,\n pageUrl: string | undefined,\n demosFolder: string | undefined,\n docProps: DocProps | null,\n verbose: boolean | undefined,\n): Promise<{content: string; demoFiles: string[]}> {\n let processedContent = mdxContent\n const demoFiles: string[] = []\n\n const lines = processedContent.split(\"\\n\")\n const titleLine = lines.findIndex((line) => line.startsWith(\"# \"))\n processedContent =\n titleLine >= 0 ? lines.slice(titleLine + 1).join(\"\\n\") : processedContent\n if (pageUrl) {\n processedContent = processedContent.replace(\n /\\[([^\\]]+)\\]\\(\\.\\/#([^)]+)\\)/g,\n (_, text, anchor) => `[${text}](${pageUrl}#${anchor})`,\n )\n }\n if (docProps) {\n const typeDocRegex =\n /<TypeDocProps\\s+name=[\"']([^\"']+)[\"'](?:\\s+partial)?[^>]*\\/>/g\n processedContent = processedContent.replace(\n typeDocRegex,\n (match, propsName) => {\n const isPartial = /\\spartial(?:\\s|\\/|>)/.test(match)\n const componentProps = docProps.props[propsName]\n if (!componentProps) {\n if (verbose) {\n console.log(` TypeDocProps not found: ${propsName}`)\n }\n return \"\"\n }\n const propsDoc = extractProps(componentProps, isPartial)\n if (verbose) {\n console.log(\n ` Replaced TypeDocProps ${propsName} with API documentation`,\n )\n }\n return `**Component Props:**\\n\\`\\`\\`json\\n${JSON.stringify(propsDoc, null, 2)}\\n\\`\\`\\`\\n`\n },\n )\n } else {\n processedContent = processedContent.replace(/<TypeDocProps\\s+[^>]*\\/>/g, \"\")\n }\n let demoRegex = /<(?:QdsDemo|CodeDemo)\\s+[^>]*name=\"(\\w+)\"[^>]*\\/>/g\n let demoMatches = Array.from(processedContent.matchAll(demoRegex))\n if (!demoMatches.length) {\n demoRegex = /<(?:QdsDemo|CodeDemo)\\s+[^>]*node=\\{Demo\\.(\\w+)\\}[^>]*\\/>/g\n demoMatches = Array.from(processedContent.matchAll(demoRegex))\n }\n const replacements = await Promise.all(\n demoMatches.map(async (match) => {\n const [fullMatch, demoName] = match\n const kebabName = kebabCase(demoName)\n let filePath = `${kebabName}.tsx`\n if (!demosFolder) {\n if (verbose) {\n console.log(` No demos folder for ${demoName}`)\n }\n return {match: fullMatch, replacement: \"\"}\n }\n let demoFilePath = join(demosFolder, filePath)\n let isAngularDemo = false\n if (!(await exists(demoFilePath))) {\n demoFilePath = join(demosFolder, `${kebabName}.ts`)\n if (await exists(demoFilePath)) {\n isAngularDemo = true\n filePath = `${kebabCase(demoName).replace(\"-component\", \".component\")}.ts`\n demoFilePath = join(demosFolder, filePath)\n } else {\n console.log(` Demo not found ${demoName}`)\n return {match: fullMatch, replacement: \"\"}\n }\n }\n try {\n const demoCode = await readFile(demoFilePath, \"utf-8\")\n const cleanedCode = removePreviewLines(demoCode)\n const codeBlock = `\\`\\`\\`${isAngularDemo ? \"angular-ts\" : \"tsx\"}\\n${cleanedCode}\\`\\`\\``\n if (verbose) {\n console.log(` Replaced demo ${demoName} with source code`)\n }\n demoFiles.push(demoFilePath)\n return {match: fullMatch, replacement: codeBlock}\n } catch (error) {\n if (verbose) {\n console.log(` Error reading demo ${demoName}: ${error}`)\n }\n return {match: fullMatch, replacement: \"\"}\n }\n }),\n )\n for (const {match, replacement} of replacements) {\n processedContent = processedContent.replace(match, replacement)\n }\n processedContent = processedContent.replace(/\\n\\s*\\n\\s*\\n/g, \"\\n\\n\")\n return {content: processedContent, demoFiles}\n}\n\nasync function processComponent(\n component: PageInfo,\n docProps: DocProps | null,\n verbose: boolean | undefined,\n): Promise<ProcessedPage> {\n try {\n const mdxContent = await readFile(component.mdxFile, \"utf-8\")\n if (verbose) {\n console.log(`Processing page: ${component.name}`)\n }\n const processor = unified()\n .use(remarkParse)\n .use(remarkFrontmatter, [\"yaml\"])\n .use(remarkParseFrontmatter)\n .use(remarkSelfLinkHeadings(component.url))\n .use(remarkStringify)\n const parsed = await processor.process(mdxContent)\n const frontmatter = (parsed.data as any)?.frontmatter || {}\n const {content: processedContent, demoFiles} = await processMdxContent(\n String(parsed),\n component.url,\n component.demosFolder,\n docProps,\n verbose,\n )\n const contentWithoutFrontmatter = processedContent.replace(\n /^---[\\s\\S]*?---\\n/,\n \"\",\n )\n const title = frontmatter.title || component.name\n\n return {\n content: contentWithoutFrontmatter.trim(),\n demoFiles,\n frontmatter,\n title,\n }\n } catch (error) {\n console.error(`Error processing component ${component.name}:`, error)\n throw error\n }\n}\n\nasync function generatePerPageExports({\n includeImports,\n metadata,\n outputPath,\n pages,\n pageTitlePrefix,\n processedPages,\n verbose,\n}: {\n includeImports?: boolean\n metadata: string[][]\n outputPath: string\n pages: PageInfo[]\n pageTitlePrefix?: string\n processedPages: ProcessedPage[]\n verbose: boolean | undefined\n}) {\n await mkdir(dirname(outputPath), {recursive: true}).catch()\n const count = processedPages.length\n let totalSize = 0\n await Promise.all(\n processedPages.map(async (processedPage, index) => {\n const page = pages[index]\n const lines: string[] = []\n if (metadata.length || page.url) {\n lines.push(\"---\")\n if (page.url) {\n lines.push(`url: ${page.url}`)\n }\n if (metadata.length) {\n for (const [key, value] of metadata) {\n lines.push(`${key}: ${value}`)\n }\n }\n lines.push(\"---\")\n lines.push(\"\")\n }\n\n lines.push(`# ${processedPage.title}`)\n lines.push(\"\")\n if (processedPage.frontmatter?.title) {\n page.name = processedPage.frontmatter.title\n }\n let content = processedPage.content\n if (pageTitlePrefix) {\n content = content.replace(\n `# ${page.name}`,\n `# ${pageTitlePrefix} ${page.name}`,\n )\n page.name = `${pageTitlePrefix} ${page.name}`\n }\n lines.push(content)\n lines.push(\"\")\n\n if (includeImports && processedPage.demoFiles.length > 0) {\n if (verbose) {\n console.log(\n `Collecting imports for ${page.name} from ${processedPage.demoFiles.length} demo files`,\n )\n }\n\n const allImports: ImportedModule[] = []\n for (const demoFile of processedPage.demoFiles) {\n const imports = await collectRelativeImports(\n demoFile,\n new Set(),\n verbose,\n )\n allImports.push(...imports)\n }\n\n const uniqueImports = Array.from(\n new Map(allImports.map((m) => [m.path, m])).values(),\n )\n\n if (verbose) {\n console.log(\n ` Collected ${uniqueImports.length} unique import modules`,\n )\n }\n\n if (uniqueImports.length > 0) {\n lines.push(\"## Related Source Files\")\n lines.push(\"\")\n for (const importedModule of uniqueImports) {\n const ext = extname(importedModule.path).slice(1)\n lines.push(`### ${basename(importedModule.path)}`)\n lines.push(\"\")\n lines.push(`\\`\\`\\`${ext}`)\n lines.push(importedModule.content)\n lines.push(\"```\")\n lines.push(\"\")\n }\n }\n }\n\n const outfile = `${resolve(outputPath)}/${kebabCase(page.name)}.md`\n await writeFile(outfile, lines.join(\"\\n\"), \"utf-8\")\n const stats = await stat(outfile)\n totalSize += stats.size / 1024\n }),\n )\n console.log(`Generated ${count} component(s) in ${outputPath}`)\n console.log(`Folder size: ${totalSize.toFixed(1)} KB`)\n}\n\nfunction extractMetadata(metadata: string[] | undefined): string[][] {\n return (metadata ?? []).map((current) => {\n const [key, value] = current.split(\"=\")\n return [key, value]\n })\n}\n\nexport async function generate({\n baseUrl,\n clean,\n description,\n docPropsPath,\n exclude,\n includeImports,\n metadata,\n name,\n outputMode,\n outputPath,\n pageTitlePrefix,\n routeDir,\n verbose,\n}: WebUiKnowledgeConfig): Promise<void> {\n const extractedMetadata = extractMetadata(metadata)\n if (verbose) {\n console.log(`Scanning pages in: ${routeDir}`)\n if (exclude?.length) {\n console.log(`Excluding patterns: ${exclude.join(\", \")}`)\n }\n }\n const [docProps, pages] = await Promise.all([\n loadDocProps(routeDir, docPropsPath, verbose),\n scanPages(routeDir, verbose, exclude, baseUrl),\n ])\n if (pages.length === 0) {\n console.log(\"No pages found.\")\n return\n }\n if (verbose) {\n console.log(`Found ${pages.length} page(s)`)\n }\n const processedPages: ProcessedPage[] = []\n for (const page of pages) {\n try {\n const processed = await processComponent(page, docProps, verbose)\n processedPages.push(processed)\n } catch (error) {\n console.error(`Failed to process page: ${page.name}`)\n process.exit(1)\n }\n }\n if (clean) {\n await rm(outputPath, {force: true, recursive: true}).catch()\n }\n if (outputMode === \"aggregated\") {\n const llmsTxtContent = await generateLlmsTxt(\n processedPages,\n name,\n description,\n baseUrl,\n )\n await mkdir(dirname(outputPath), {recursive: true}).catch()\n await writeFile(outputPath, llmsTxtContent, \"utf-8\")\n const outputStats = await stat(outputPath)\n const outputSizeKb = (outputStats.size / 1024).toFixed(1)\n console.log(\n `Generated ${outputPath} with ${pages.length} component(s) at: ${outputPath}`,\n )\n console.log(`File size: ${outputSizeKb} KB`)\n } else {\n await mkdir(outputPath, {recursive: true}).catch()\n await generatePerPageExports({\n includeImports,\n metadata: extractedMetadata,\n outputPath,\n pages,\n pageTitlePrefix,\n processedPages,\n verbose,\n })\n }\n}\n\nexport function addGenerateKnowledgeCommand() {\n program\n .description(\"Generate llms.txt from QUI Docs documentation\")\n .command(\"generate-llms-txt\")\n .option(\"-n, --name <name>\", \"Project name for llms.txt header\")\n .requiredOption(\"-m, --output-mode <outputMode>\")\n .option(\"-o, --outputPath <outputPath>\", \"Output file or directory.\")\n .option(\n \"-d, --description <description>\",\n \"Project description for llms.txt\",\n )\n .option(\"-v, --verbose\", \"Enable verbose logging\", false)\n .option(\n \"--exclude <patterns...>\",\n \"Exclude folder patterns (supports * wildcards)\",\n [],\n )\n .option(\"--base-url <url>\", \"Base URL for component documentation links\")\n .option(\"--metadata <pairs...>\", \"metadata key-value pairs\")\n .option(\"--clean\", \"Clean the output path before generating\")\n .option(\"--include-imports\", \"Include relative import source files\", true)\n .action(async (options) => {\n loadEnv()\n const knowledgeConfig = loadKnowledgeConfigFromEnv({\n ...options,\n outputMode:\n options.outputMode === \"per-page\" ? \"per-page\" : \"aggregated\",\n })\n await generate(knowledgeConfig)\n })\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport chalk from \"chalk\"\nimport chokidar from \"chokidar\"\nimport {glob} from \"glob\"\nimport {readFileSync} from \"node:fs\"\nimport {resolve} from \"node:path\"\nimport prettyMilliseconds from \"pretty-ms\"\nimport type {PluginOption, ViteDevServer} from \"vite\"\n\nimport type {QuiPropTypes} from \"@qualcomm-ui/typedoc-common\"\n\nimport {\n ConfigLoader,\n fixPath,\n type ResolvedQuiDocsConfig,\n SearchIndexer,\n} from \"./internal\"\n\nconst isDev = process.env.NODE_ENV === \"development\"\n\nexport interface QuiDocsPluginOptions {\n /**\n * Path to the qui-docs config file. This is automatically detected if omitted.\n */\n configFile?: string\n\n /**\n * The current working directory.\n *\n * @default process.cwd()\n */\n cwd?: string\n}\n\n/**\n * TODO: adjust when https://github.com/vitejs/vite/discussions/16358 lands.\n */\nclass PluginState {\n buildCount: number = 0\n configFilePath: string = \"\"\n docPropsFilePath: string = \"\"\n indexer!: SearchIndexer\n configLoader: ConfigLoader | null = null\n routesDir!: string\n servers: ViteDevServer[] = []\n timeout: ReturnType<typeof setTimeout> | undefined = undefined\n watching = false\n\n readonly resolvedVirtualModuleId: string\n readonly virtualModuleId = \"@qualcomm-ui/mdx-vite-plugin\"\n private cwd!: string\n\n constructor() {\n this.resolvedVirtualModuleId = `\\0${this.virtualModuleId}`\n }\n\n init(cwd: string) {\n this.cwd = cwd\n }\n\n get docPropsDirectory() {\n if (!this.docPropsFilePath) {\n return \"\"\n }\n return this.docPropsFilePath.substring(\n 0,\n this.docPropsFilePath.lastIndexOf(\"/\"),\n )\n }\n\n private resolveDocProps(): Record<string, QuiPropTypes> {\n if (!this.docPropsFilePath) {\n return {}\n }\n try {\n return JSON.parse(readFileSync(this.docPropsFilePath, \"utf-8\"))?.props\n } catch (e) {\n console.debug(\n \"Invalid doc props file. Unable to parse JSON. Please check the file\",\n )\n return {}\n }\n }\n\n createIndexer(config: ResolvedQuiDocsConfig) {\n this.configFilePath = config.filePath\n this.docPropsFilePath = config.typeDocProps\n ? fixPath(resolve(this.cwd, config.typeDocProps))\n : \"\"\n this.routesDir = fixPath(resolve(config.appDirectory, config.pageDirectory))\n this.indexer = new SearchIndexer({\n ...config,\n srcDir: fixPath(resolve(this.cwd, config.appDirectory)),\n typeDocProps: this.resolveDocProps(),\n })\n }\n\n buildIndex(shouldLog: boolean) {\n const files = glob.sync(\n [`${this.routesDir}/**/*.mdx`, `${this.routesDir}/**/*.tsx`],\n {\n absolute: true,\n cwd: this.cwd,\n },\n )\n\n if (!files.length) {\n return\n }\n\n const startTime = Date.now()\n\n this.indexer.buildIndex(files, shouldLog)\n\n if (isDev && shouldLog) {\n console.debug(\n `${chalk.magenta.bold(`@qualcomm-ui/mdx-vite/docs-plugin:`)} Compiled search index in: ${chalk.blueBright.bold(prettyMilliseconds(Date.now() - startTime))}${state.indexer.cachedFileCount ? chalk.greenBright.bold(` (${state.indexer.cachedFileCount}/${state.indexer.mdxFileCount} files cached)`) : \"\"}`,\n )\n }\n }\n\n /**\n * When the user edits MDX content or modifies the plugin config, we re-index the\n * site. This function handles module invalidation so that virtual file imports\n * are refreshed as expected by the consumer's dev server.\n */\n sendUpdate() {\n for (const server of this.servers) {\n const virtualModule = server.moduleGraph.getModuleById(\n this.resolvedVirtualModuleId,\n )\n if (virtualModule) {\n server.moduleGraph.invalidateModule(virtualModule)\n server.reloadModule(virtualModule)\n }\n }\n }\n\n handleChange(callback?: () => void) {\n // the plugin is activating twice in dev mode. It's mostly harmless, but we\n // prevent logs from emitting twice by flipping a flag\n\n // debounce the change handler to prevent rapid updates from triggering rebuilds\n // in quick succession.\n clearTimeout(this.timeout)\n this.timeout = setTimeout(() => {\n this.buildIndex(true)\n this.sendUpdate()\n callback?.()\n }, 300)\n }\n\n initWatchers(configFile?: string) {\n if (this.watching) {\n return\n }\n this.initConfigWatcher(configFile)\n this.watching = true\n }\n\n private initConfigWatcher(configFile?: string) {\n const paths: string[] = [this.configFilePath]\n if (this.docPropsFilePath) {\n paths.push(this.docPropsFilePath)\n }\n chokidar\n .watch(paths, {\n cwd: this.cwd,\n })\n .on(\"change\", () => {\n console.debug(`qui-docs config changed, reloading plugin`)\n this.configLoader = new ConfigLoader({configFile})\n const resolvedConfig = this.configLoader.loadConfig()\n this.configFilePath = resolvedConfig.filePath\n this.createIndexer(resolvedConfig)\n this.handleChange()\n })\n }\n}\n\nconst state = new PluginState()\n\nexport function quiDocsPlugin(opts?: QuiDocsPluginOptions): PluginOption {\n state.init(fixPath(opts?.cwd ?? process.cwd()))\n\n // https://vitejs.dev/guide/api-plugin#virtual-modules-convention\n\n const configLoader = new ConfigLoader(opts || {})\n const config = configLoader.loadConfig()\n state.createIndexer(config)\n\n return {\n buildStart: async () => {\n state.buildIndex(state.buildCount > 0)\n state.buildCount++\n },\n configureServer: (server) => {\n if (!isDev) {\n return\n }\n state.initWatchers(opts?.configFile)\n server.watcher.on(\"add\", (path: string) => {\n if (path.endsWith(\".mdx\")) {\n state.handleChange(() => {\n server.ws.send({type: \"full-reload\"})\n })\n }\n })\n server.watcher.on(\"unlink\", (path: string) => {\n if (path.endsWith(\".mdx\")) {\n state.handleChange(() => {\n server.ws.send({type: \"full-reload\"})\n })\n }\n })\n state.servers.push(server)\n },\n handleHotUpdate: async ({file: updateFile}) => {\n const file = fixPath(updateFile)\n\n if (\n (!config.hotUpdateIgnore || !config.hotUpdateIgnore.test(file)) &&\n // ignore watched files. We watch for these separately.\n file !== state.configFilePath\n ) {\n if (\n state.docPropsDirectory &&\n file.startsWith(state.docPropsFilePath)\n ) {\n return []\n }\n state.handleChange()\n }\n return []\n },\n load: (id): string | undefined => {\n if (id === state.resolvedVirtualModuleId) {\n return `export const siteData = ${JSON.stringify({navItems: state.indexer.navItems, pageDocProps: state.indexer.pageDocProps, pageMap: state.indexer.pageMap, searchIndex: state.indexer.searchIndex})}`\n }\n return undefined\n },\n name: \"qui-mdx-vite-plugin\",\n resolveId: (id) => {\n if (id === state.virtualModuleId) {\n return state.resolvedVirtualModuleId\n }\n return undefined\n },\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport {type Config, type CosmiconfigResult, cosmiconfigSync} from \"cosmiconfig\"\n\nimport type {QuiDocsConfig} from \"../types\"\n\nimport {configSchema} from \"./config-schema\"\nimport {removeTrailingSlash} from \"./utils\"\n\ninterface LoadedCosmicConfig {\n config: Config\n filepath: string\n isEmpty?: boolean\n}\n\nexport interface ResolvedQuiDocsConfig extends QuiDocsConfig {\n appDirectory: string\n /**\n * full path to the cosmiconfig file.\n */\n filePath: string\n pageDirectory: string\n}\n\nexport interface ConfigLoaderOptions {\n /**\n * Path to the qui-docs config file. This is automatically detected if omitted.\n */\n configFile?: string\n}\n\nexport class ConfigLoader {\n private readonly options: ConfigLoaderOptions\n\n constructor(options: ConfigLoaderOptions) {\n this.options = options\n return this\n }\n\n private getCosmiconfig(): LoadedCosmicConfig {\n const explorer = cosmiconfigSync(\"qui-docs\")\n\n const result: CosmiconfigResult | null = this.options.configFile\n ? explorer.load(this.options.configFile)\n : explorer.search()\n\n if (!result) {\n throw new Error(\n \"Config file not found. Please consult the docs at https://docs.qui.qualcomm.com/guide/page-setup#config\",\n )\n }\n\n return result\n }\n\n private resolveConfigFromCosmiconfig(\n config: CosmiconfigResult,\n ): ResolvedQuiDocsConfig {\n const parsed = configSchema.safeParse(config!.config)\n if (!parsed.success) {\n console.dir(parsed.error.issues, {depth: 10})\n throw new Error(\"Failed to parse config file.\")\n }\n const conf = parsed.data\n return {\n ...conf,\n appDirectory: conf.appDirectory || \"app\",\n filePath: config!.filepath,\n pageDirectory: conf.pageDirectory\n ? removeTrailingSlash(conf.pageDirectory)\n : \"routes\",\n }\n }\n\n loadConfig(): ResolvedQuiDocsConfig {\n const config = this.getCosmiconfig()\n return this.resolveConfigFromCosmiconfig(config)\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport {z, type ZodObject, type ZodSchema} from \"zod\"\n\nimport type {\n NavMeta,\n QuiDocsConfig,\n QuiDocsTypeDocOptions,\n RouteMeta,\n} from \"../types\"\n\nimport {implement} from \"./zod\"\n\nexport const navMetaSchema: ZodObject<{}> = implement<NavMeta>().with({\n id: z.never().optional(),\n sectionTitle: z.string().optional(),\n separator: z.boolean().optional(),\n})\n\nexport const routeMetaSchema: ZodSchema<RouteMeta> =\n implement<RouteMeta>().with({\n children: z.array(z.lazy(() => routeMetaSchema)).optional(),\n expanded: z.boolean().optional(),\n group: z.string().optional(),\n groupOrder: z.string().array().optional(),\n hidden: z.boolean().optional(),\n hideBreadcrumbs: z.boolean().optional(),\n hideFromSearch: z.boolean().optional(),\n hidePageLinks: z.boolean().optional(),\n hideSideNav: z.boolean().optional(),\n hideToc: z.boolean().optional(),\n id: z.string(),\n ignoreRouteMetaOrder: z.boolean().optional(),\n restricted: z.boolean().optional(),\n sectionTitle: z.never().optional(),\n separator: z.never().optional(),\n sideNavTitle: z.string().optional(),\n title: z.string().optional(),\n })\n\nconst typeDocPropsSchema = implement<QuiDocsTypeDocOptions>().with({\n includeInSearchIndex: z.boolean().optional(),\n})\n\nexport const configSchema = implement<QuiDocsConfig>().with({\n appDirectory: z.string().optional(),\n disableCache: z.boolean().optional(),\n headings: z\n .array(\n z.union([\n z.literal(\"h1\"),\n z.literal(\"h2\"),\n z.literal(\"h3\"),\n z.literal(\"h4\"),\n z.literal(\"h5\"),\n z.literal(\"h6\"),\n ]),\n )\n .optional(),\n hotUpdateIgnore: z.instanceof(RegExp).optional(),\n navConfig: z.array(z.union([routeMetaSchema, navMetaSchema])).optional(),\n pageDirectory: z.string().optional(),\n routingStrategy: z\n .union([\n z.literal(\"vite-generouted\"),\n z.function(z.tuple([z.string()]), z.array(z.string())),\n ])\n .optional(),\n typeDocProps: z.string().optional(),\n typeDocPropsOptions: typeDocPropsSchema.optional(),\n})\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport {z} from \"zod\"\n\ntype Implements<Model> = {\n [key in keyof Model]-?: undefined extends Model[key]\n ? null extends Model[key]\n ? z.ZodNullableType<z.ZodOptionalType<z.ZodType<Model[key]>>>\n : z.ZodOptionalType<z.ZodType<Model[key]>>\n : null extends Model[key]\n ? z.ZodNullableType<z.ZodType<Model[key]>>\n : z.ZodType<Model[key]> | z.ZodDefault<z.ZodType<Model[key]>>\n}\n\nexport function implement<Model = never>() {\n return {\n with: <\n Schema extends Implements<Model> & {\n [unknownKey in Exclude<keyof Schema, keyof Model>]: never\n },\n >(\n schema: Schema,\n ) => z.object(schema),\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport {z, type ZodObject} from \"zod\"\n\nimport type {PageFrontmatter} from \"@qualcomm-ui/mdx-common\"\n\nimport {implement} from \"./zod\"\n\nexport const isDefined = (\n value: string | boolean | object | null | undefined | number,\n): boolean => typeof value !== \"undefined\" && value !== null\n\nexport function defined<T>(value: T | null | undefined): value is T {\n return typeof value !== \"undefined\" && value !== null\n}\n\n/**\n * Used to validate the MDX frontmatter and emit warnings for pages that violate the\n * schema.\n */\nexport const frontmatterSchema: ZodObject<{}> =\n implement<PageFrontmatter>().with({\n categories: z.string().array().optional(),\n group: z.string().optional(),\n hidden: z.boolean().optional(),\n hideBreadcrumbs: z.boolean().optional(),\n hideFromSearch: z.boolean().optional(),\n hidePageLinks: z.boolean().optional(),\n hideSideNav: z.boolean().optional(),\n hideToc: z.boolean().optional(),\n id: z.string().optional(),\n restricted: z.boolean().optional(),\n sideNavTitle: z.string().optional(),\n title: z.string(),\n })\n\n/**\n * Winblows fix\n */\nexport function fixPath(str: string): string {\n return str.replaceAll(\"\\\\\", \"/\")\n}\n\n/**\n * Removes the trailing slash from a string.\n */\nexport function removeTrailingSlash(str: string): string {\n return str.endsWith(\"/\") ? str.substring(0, str.length - 1) : str\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport chalk from \"chalk\"\n\nimport type {\n NavItem,\n PageFrontmatter,\n PageMap,\n PageSection,\n} from \"@qualcomm-ui/mdx-common\"\nimport type {QuiPropTypes} from \"@qualcomm-ui/typedoc-common\"\n\nimport type {\n RouteMetaInternal,\n RouteMetaNavInternal,\n SearchIndexerOptions,\n} from \"../types\"\n\nimport {\n DocPropsIndexer,\n filterFileGlob,\n getCategoriesFromPathSegments,\n getPathnameFromPathSegments,\n getPathSegmentsFromFileName,\n getRouteMeta,\n type IndexedPage,\n type IndexedSection,\n MarkdownFileReader,\n MarkdownIndexer,\n NavBuilder,\n} from \"./services\"\nimport {transformRouteMetaArray} from \"./transform-route-meta-array\"\nimport {defined, fixPath} from \"./utils\"\n\nexport class SearchIndexer {\n private readonly docPropsIndexer: DocPropsIndexer\n private readonly markdownIndexer: MarkdownIndexer\n private readonly navBuilder: NavBuilder\n private readonly fileCache: MarkdownFileReader\n private readonly allowedHeadings: Set<string>\n private readonly metaJson: RouteMetaInternal\n private readonly routeMetaNav: Record<string, RouteMetaNavInternal> = {}\n\n get cachedFileCount(): number {\n return this.fileCache.cachedFileCount\n }\n\n get pageDocProps(): Record<string, Record<string, QuiPropTypes>> {\n return this._pageDocProps\n }\n private _pageDocProps: Record<string, Record<string, QuiPropTypes>> = {}\n\n get mdxFileCount(): number {\n return this._mdxFileCount\n }\n private _mdxFileCount: number = 0\n\n get navItems(): NavItem[] {\n return this.navBuilder.navItems\n }\n\n get pageMap(): PageMap {\n return this._pageMap\n }\n private _pageMap: PageMap = {}\n\n get searchIndex(): PageSection[] {\n return this._searchIndex\n }\n private _searchIndex: PageSection[] = []\n\n reset(): void {\n this.fileCache.reset()\n this._pageMap = {}\n this._searchIndex = []\n }\n\n constructor(\n public config: SearchIndexerOptions,\n public logWarnings = true,\n // enable composition by making these classes replaceable\n addons: {\n docPropsIndexer?: DocPropsIndexer\n fileCache?: MarkdownFileReader\n markdownIndexer?: MarkdownIndexer\n navBuilder?: NavBuilder\n } = {},\n ) {\n this.allowedHeadings = new Set<string>(\n Array.from(config?.headings || [\"h2\", \"h3\", \"h4\"]),\n )\n this.metaJson = transformRouteMetaArray(\n this.config.navConfig ?? [],\n this.routeMetaNav,\n )\n\n this.markdownIndexer =\n addons.markdownIndexer || new MarkdownIndexer(this.allowedHeadings)\n this.navBuilder =\n addons.navBuilder || new NavBuilder(this.metaJson, this.routeMetaNav)\n this.docPropsIndexer =\n addons.docPropsIndexer ||\n new DocPropsIndexer(this.config.typeDocProps ?? {})\n this.fileCache =\n addons.fileCache ||\n new MarkdownFileReader(\n process.env.NODE_ENV === \"development\" && !this.config.disableCache,\n )\n }\n\n /**\n * Resolves a page's properties from the combined frontmatter and RouteMeta.\n * RouteMeta properties take precedence.\n */\n private getPageEntry(\n filepath: string,\n frontmatter: Partial<PageFrontmatter>,\n ): PageSection {\n const pagePath = filepath.replace(this.config.srcDir, \"\")\n\n const pathSegments = getPathSegmentsFromFileName(\n pagePath,\n this.config.pageDirectory,\n this.config.routingStrategy,\n )\n\n const pathname = getPathnameFromPathSegments(pathSegments)\n\n const routeMeta =\n getRouteMeta(\n pathSegments.length === 0\n ? frontmatter.id\n ? [frontmatter.id]\n : [\"_index\"]\n : pathSegments,\n this.metaJson,\n ) ?? {}\n\n return {\n categories:\n frontmatter.categories ??\n getCategoriesFromPathSegments(\n pathSegments,\n this.metaJson,\n routeMeta?.title || frontmatter.title || \"\",\n ),\n hidden: defined(routeMeta.hidden) ? routeMeta.hidden : frontmatter.hidden,\n hideBreadcrumbs: defined(routeMeta.hideBreadcrumbs)\n ? routeMeta.hideBreadcrumbs\n : frontmatter.hideBreadcrumbs,\n hideFromSearch: defined(routeMeta.hideFromSearch)\n ? routeMeta.hideFromSearch\n : frontmatter.hideFromSearch,\n hidePageLinks: defined(routeMeta.hidePageLinks)\n ? routeMeta.hidePageLinks\n : frontmatter.hidePageLinks,\n hideSideNav: defined(routeMeta.hideSideNav)\n ? routeMeta.hideSideNav\n : frontmatter.hideSideNav,\n hideToc: defined(routeMeta.hideToc)\n ? routeMeta.hideToc\n : frontmatter.hideToc,\n id: pagePath,\n pathname,\n pathSegments,\n restricted: defined(routeMeta.restricted)\n ? routeMeta.restricted\n : frontmatter.restricted,\n title: defined(routeMeta.title)\n ? routeMeta.title || \"\"\n : frontmatter.title || \"\",\n }\n }\n\n /**\n * Parses an MDX file to extract the site data for the nav items, doc props,\n * breadcrumbs, and search index.\n */\n private compileMdxFile(filepath: string): PageSection[] {\n const {cached, fileContents, frontmatter} =\n this.fileCache.readFile(filepath)\n\n this.docPropsIndexer.reset()\n this.markdownIndexer.reset()\n\n const defaultSection: PageSection = this.getPageEntry(filepath, frontmatter)\n if (!defaultSection.categories.length && defaultSection.title) {\n defaultSection.categories = [defaultSection.title]\n }\n\n if (!defaultSection.hidden) {\n this.navBuilder.add(defaultSection, frontmatter)\n }\n\n this._pageMap[defaultSection.pathname] = defaultSection\n\n let indexedPage: IndexedPage\n\n try {\n indexedPage = cached?.page\n ? cached.page\n : this.markdownIndexer.parseMarkdown(fileContents, frontmatter)\n } catch (error) {\n console.debug(\n `${chalk.yellowBright.bold(\n \"Failed to parse mdx page content.\",\n )} ${chalk.blueBright.bold(filepath)}`,\n )\n\n return [defaultSection]\n }\n\n const {sections, toc} = indexedPage\n\n if (toc.length) {\n this._pageMap[defaultSection.pathname].toc = toc\n }\n\n let docPropSections: IndexedSection[] = []\n let docProps: Record<string, QuiPropTypes> = {}\n\n if (this.config.typeDocProps) {\n docPropSections =\n cached?.pageDocPropSections ||\n (this.docPropsIndexer.build(fileContents, toc) ?? [])\n docProps = cached?.pageDocProps || this.docPropsIndexer.getDocProps()\n }\n\n if (docPropSections.length) {\n this._pageDocProps[defaultSection.pathname] = docProps\n }\n\n this.fileCache.updateCache(filepath, fileContents, {\n frontmatter,\n page: indexedPage,\n pageDocProps: docProps,\n pageDocPropSections: docPropSections,\n })\n\n // omit entries from pages that are explicitly omitted from the index.\n if (frontmatter.hideFromSearch) {\n return [defaultSection]\n }\n\n if (!sections.length && !docPropSections.length) {\n return [defaultSection]\n }\n\n const sectionReturn: PageSection[] = [\n ...this.formatSections(sections, defaultSection, false),\n ]\n\n if (this.config.typeDocPropsOptions?.includeInSearchIndex) {\n sectionReturn.push(\n ...this.formatSections(docPropSections, defaultSection, true),\n )\n }\n\n return sectionReturn\n }\n\n private formatSections(\n sections: IndexedSection[],\n {toc: _toc, ...defaultSection}: PageSection,\n isDocProp: boolean,\n ): PageSection[] {\n return sections.map((section, index): PageSection => {\n const content = section.content.map((c) => c.text.join(\" \")).join(\" \")\n return {\n ...defaultSection,\n content: content || undefined,\n heading: section.heading?.textContent ?? defaultSection.title,\n headingLevel: section.heading?.headingLevel,\n href:\n section.heading &&\n (this.allowedHeadings.has(section.heading.tagName) || isDocProp)\n ? `${defaultSection.pathname}#${section.heading.id}`\n : defaultSection.pathname,\n id: `${defaultSection.id}-${index}${isDocProp ? \"-prop\" : \"\"}`,\n isDocProp: isDocProp || undefined,\n richContent: section.richContent,\n }\n })\n }\n\n private compileTsxFile(filepath: string) {\n const entry = this.getPageEntry(filepath, {})\n\n const routeMeta = getRouteMeta(\n entry.pathSegments.length === 0 ? [\"_index\"] : entry.pathSegments,\n this.metaJson,\n )\n\n if (!routeMeta) {\n return null\n }\n\n if (!entry.hidden) {\n this.navBuilder.add(entry, {}, routeMeta)\n }\n\n this._pageMap[entry.pathname] = entry\n\n return entry\n }\n\n buildIndex(inputFileGlob: string[], logWarnings: boolean = true): void {\n this.logWarnings = logWarnings\n this.fileCache.logWarnings = logWarnings\n // Windows path fix\n const fileGlob = inputFileGlob.map(fixPath)\n this.navBuilder.reset()\n this.reset()\n\n const mdxFileGlob = filterFileGlob(\n fileGlob,\n \"mdx\",\n this.config.srcDir,\n this.config.routingStrategy,\n )\n\n this._mdxFileCount = mdxFileGlob.length\n const mdxIndex = mdxFileGlob.map((file) => this.compileMdxFile(file)).flat()\n\n filterFileGlob(\n fileGlob,\n \"tsx\",\n this.config.srcDir,\n this.config.routingStrategy,\n ).map((file) => this.compileTsxFile(file))\n\n this._searchIndex.push(...mdxIndex.filter((entry) => !entry.hideFromSearch))\n\n this.navBuilder.build()\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport type {MdxJsxAttribute} from \"mdast-util-mdx-jsx\"\nimport remarkMdx from \"remark-mdx\"\nimport remarkParse from \"remark-parse\"\nimport remarkStringify from \"remark-stringify\"\nimport {type Plugin, unified} from \"unified\"\nimport {visit} from \"unist-util-visit\"\n\nimport {\n type PageDocProps,\n type PageHeading,\n type PagePropType,\n UniqueIdService,\n} from \"@qualcomm-ui/mdx-common\"\nimport type {\n QuiPropDeclaration,\n QuiPropTypes,\n} from \"@qualcomm-ui/typedoc-common\"\n\nimport type {IndexedSection} from \"../markdown\"\n\nfunction extractPickPropsRecord(\n node: MdxJsxAttribute,\n): Record<string, string[]> | null {\n if (\n node.name !== \"unionWithPick\" ||\n !node.value ||\n typeof node.value === \"string\"\n ) {\n return null\n }\n\n const estree = node.value.data?.estree\n if (!estree?.body?.[0] || estree.body[0].type !== \"ExpressionStatement\") {\n return null\n }\n\n const expression = estree.body[0].expression\n if (expression.type !== \"ObjectExpression\") {\n return null\n }\n\n const result: Record<string, string[]> = {}\n\n for (const property of expression.properties) {\n if (property.type !== \"Property\" || property.key.type !== \"Identifier\") {\n continue\n }\n\n if (property.value.type !== \"ArrayExpression\") {\n continue\n }\n\n const key = property.key.name\n const values: string[] = []\n\n for (const element of property.value.elements) {\n if (element?.type === \"Literal\" && typeof element.value === \"string\") {\n values.push(element.value)\n }\n }\n\n result[key] = values\n }\n\n return result\n}\n\nconst targetMdxElements: string[] = [\n \"TypeDocProps\",\n \"TypeDocAttributes\",\n \"TypeDocAngularAttributes\",\n]\n\ninterface DocPropEntry {\n name: string\n omitFrom?: string[]\n}\n\nexport class DocPropsIndexer {\n docPropsEntries: DocPropEntry[] = []\n idService: UniqueIdService = new UniqueIdService()\n private readonly props: Record<string, QuiPropTypes>\n private pageDocProps: PageDocProps = {}\n\n constructor(props: Record<string, QuiPropTypes>) {\n this.props = props\n }\n\n reset(): void {\n this.idService.reset()\n this.docPropsEntries = []\n }\n\n private extractNamesFromAttribute(attr: MdxJsxAttribute): string[] {\n if (!attr.value) {\n return []\n }\n\n if (typeof attr.value === \"string\") {\n return [attr.value]\n }\n\n if (attr.value.type === \"mdxJsxAttributeValueExpression\") {\n const estree = attr.value.data?.estree\n if (!estree?.body?.[0] || estree.body[0].type !== \"ExpressionStatement\") {\n return []\n }\n\n const expression = estree.body[0].expression\n\n if (expression.type === \"ArrayExpression\") {\n const names: string[] = []\n for (const element of expression.elements) {\n if (\n element?.type === \"Literal\" &&\n typeof element.value === \"string\"\n ) {\n names.push(element.value)\n }\n }\n return names\n }\n\n // Handle single string expression\n if (\n expression.type === \"Literal\" &&\n typeof expression.value === \"string\"\n ) {\n return [expression.value]\n }\n }\n\n return []\n }\n\n /**\n * Finds all JSX `<TypeDocProps />` nodes on the current page and adds their names\n * to an array. Once all nodes have been collected, we process them into\n * `PageSection` entries for the search index.\n */\n getTypeDocPropsNodes: Plugin = () => {\n return (tree, _file, done) => {\n visit(tree, \"mdxJsxFlowElement\", (node: any) => {\n if (node && \"name\" in node && targetMdxElements.includes(node.name)) {\n const nameAttr = node.attributes?.find(\n (attr: MdxJsxAttribute) => attr.name === \"name\",\n )\n const omitFromAttr = node.attributes?.find(\n (attr: MdxJsxAttribute) => attr.name === \"omitFrom\",\n )\n const omitFrom = omitFromAttr\n ? this.extractNamesFromAttribute(omitFromAttr)\n : undefined\n\n if (nameAttr) {\n const names = this.extractNamesFromAttribute(nameAttr)\n for (const name of names) {\n this.docPropsEntries.push({name, omitFrom})\n if (name.endsWith(\"Props\")) {\n // also index the corresponding component for lookup on this page.\n this.docPropsEntries.push({name: name.slice(0, -5), omitFrom})\n }\n }\n }\n\n const unionWithPickAttr: MdxJsxAttribute = node.attributes?.find(\n (attr: MdxJsxAttribute) => attr.name === \"unionWithPick\",\n )\n if (unionWithPickAttr) {\n try {\n const unionWithPick = extractPickPropsRecord(unionWithPickAttr)\n if (unionWithPick) {\n this.docPropsEntries.push(\n ...Object.keys(unionWithPick).map((entry) => ({\n name: entry,\n omitFrom,\n })),\n )\n }\n } catch (e) {}\n }\n }\n })\n done()\n }\n }\n\n build(fileContents: string, toc: PageHeading[]): IndexedSection[] | null {\n // parse the Markdown into an AST\n unified()\n .use(remarkMdx)\n // find the TypeDocProp nodes\n .use(this.getTypeDocPropsNodes)\n .use(remarkParse)\n .use(remarkStringify)\n .processSync(fileContents)\n\n if (!this.docPropsEntries.length) {\n return null\n }\n\n for (const item of toc) {\n this.idService.add(item.id)\n }\n\n return this.docPropsEntries\n .map((entry): IndexedSection[] => {\n const propTypes = this.props[entry.name]\n if (!propTypes) {\n return []\n }\n\n const omittedProps = new Set<string>(\n (entry.omitFrom ?? [])\n .map((entry) => {\n const propTypes = this.props[entry]\n if (!propTypes) {\n return []\n }\n return [\n propTypes.props,\n propTypes.input,\n propTypes.output,\n propTypes.publicMethods,\n ].reduce((acc: string[], current) => {\n if (current) {\n acc.push(...current.map((prop) => prop.name))\n }\n return acc\n }, [])\n })\n .flat(1)\n .filter(Boolean),\n )\n\n const sections: IndexedSection[] = []\n\n const assembleProps = (\n propsInput: QuiPropDeclaration[] | undefined,\n ): PagePropType[] | undefined => {\n if (!propsInput) {\n return undefined\n }\n const props: PagePropType[] = []\n for (const prop of propsInput) {\n if (omittedProps.has(prop.name)) {\n continue\n }\n const id = this.idService.add(prop.name)\n props.push({...prop, id})\n sections.push(this.assembleProp(prop, id))\n }\n return props\n }\n\n this.pageDocProps[entry.name] = {\n ...this.props[entry.name],\n input: assembleProps(propTypes.input),\n output: assembleProps(propTypes.output),\n props: assembleProps(propTypes.props),\n publicMethods: assembleProps(propTypes.publicMethods),\n }\n return sections\n })\n .flat()\n }\n\n getDocProps(): PageDocProps {\n return this.docPropsEntries.reduce((acc: PageDocProps, entry) => {\n const propTypes = this.pageDocProps[entry.name]\n // TODO: convert code comments to HTML using rehype. Remove markdown-to-jsx\n // in @qualcomm-ui/react-mdx library.\n if (propTypes) {\n acc[entry.name] = propTypes\n }\n return acc\n }, {})\n }\n\n private assembleProp(prop: QuiPropDeclaration, id: string): IndexedSection {\n const name = prop.name\n\n const heading: PageHeading = {\n headingLevel: 4,\n id,\n tagName: \"a\",\n textContent: name,\n }\n\n const comment = prop.comment\n if (!comment) {\n return {content: [], heading, richContent: []}\n }\n\n const content = {\n tagName: \"p\",\n text: [\n comment.summary\n .map((entry) => entry.text.replaceAll(\"\\n\", \" \"))\n .join(\"\"),\n ],\n }\n return {content: [content], heading, richContent: []}\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport chalk from \"chalk\"\nimport {createHash} from \"node:crypto\"\nimport {readFileSync} from \"node:fs\"\nimport remarkFrontmatter from \"remark-frontmatter\"\nimport remarkParse from \"remark-parse\"\nimport remarkParseFrontmatter from \"remark-parse-frontmatter\"\nimport remarkStringify from \"remark-stringify\"\nimport {unified} from \"unified\"\n\nimport type {PageFrontmatter} from \"@qualcomm-ui/mdx-common\"\nimport type {QuiPropTypes} from \"@qualcomm-ui/typedoc-common\"\n\nimport {frontmatterSchema} from \"../../utils\"\n\nimport type {IndexedPage, IndexedSection} from \"./markdown.types\"\n\ninterface PageCache {\n frontmatter: PageFrontmatter\n md5: string\n page: IndexedPage\n pageDocProps: Record<string, QuiPropTypes>\n pageDocPropSections: IndexedSection[]\n}\n\nexport class MarkdownFileReader {\n cachedFileCount = 0\n logWarnings = true\n private mdxCache: Record<string, PageCache> = {}\n\n constructor(public enabled: boolean) {}\n\n private hash(input: string) {\n return createHash(\"md5\").update(input).digest(\"hex\")\n }\n\n reset(): void {\n this.cachedFileCount = 0\n }\n\n private checkCache(\n filepath: string,\n fileContents: string,\n ): Omit<PageCache, \"md5\"> | undefined {\n if (!this.enabled) {\n return\n }\n\n const fileMd5 = this.hash(fileContents)\n const cached = this.mdxCache[filepath]\n\n if (cached?.md5 !== fileMd5) {\n return\n }\n\n this.cachedFileCount++\n\n return {\n frontmatter: cached.frontmatter,\n page: cached.page,\n pageDocProps: cached.pageDocProps,\n pageDocPropSections: cached.pageDocPropSections,\n }\n }\n\n readFile(filepath: string): {\n cached: Omit<PageCache, \"md5\"> | undefined\n fileContents: string\n frontmatter: PageFrontmatter\n } {\n const fileContents = readFileSync(filepath, \"utf-8\")\n\n const cached = this.checkCache(filepath, fileContents)\n\n let file:\n | {data: {frontmatter: PageFrontmatter}}\n | ReturnType<typeof unified.processSync>\n if (cached?.frontmatter) {\n file = {data: {frontmatter: cached.frontmatter}}\n } else {\n // only parse the yaml section because we just need the frontmatter at this\n // stage.\n const yamlSection = fileContents.substring(\n 0,\n fileContents.indexOf(\"\\n---\") + 4,\n )\n file = unified()\n .use(remarkParse)\n .use(remarkFrontmatter, [\"yaml\"])\n .use(remarkParseFrontmatter)\n .use(remarkStringify)\n .processSync(yamlSection)\n }\n\n const frontmatter: PageFrontmatter = (file.data\n .frontmatter as PageFrontmatter) ?? {title: \"\"}\n\n if (!frontmatter.title) {\n const lines = fileContents.split(\"\\n\")\n const fallbackTitle = lines.find((line) => line.startsWith(\"# \"))\n if (fallbackTitle) {\n frontmatter.title = fallbackTitle.substring(2).trim()\n }\n }\n // TODO: permit omitting title from frontmatter if provided in the navConfig\n if (!frontmatter.title && this.logWarnings) {\n console.debug(chalk.red.bold(\"Missing title:\"), filepath)\n }\n\n const parsedFrontmatter = frontmatterSchema.safeParse(frontmatter)\n\n if (!parsedFrontmatter.success) {\n console.debug(\n `${chalk.redBright.bold(\"Invalid frontmatter detected for file\")}: ${filepath}\\n`,\n )\n console.debug(chalk.redBright.bold(\"Please check the following fields:\"))\n parsedFrontmatter.error.issues.map((issue: any) => {\n console.debug(`- ${issue.path.join(\".\")}`)\n })\n }\n\n return {cached, fileContents, frontmatter}\n }\n\n updateCache(\n filepath: string,\n fileContents: string,\n cacheData: Omit<PageCache, \"md5\">,\n ): void {\n if (this.enabled) {\n this.mdxCache[filepath] = {...cacheData, md5: this.hash(fileContents)}\n }\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport type {Element} from \"hast\"\nimport {fromHtml} from \"hast-util-from-html\"\nimport {toText} from \"hast-util-to-text\"\nimport {clone, size} from \"lodash-es\"\nimport rehypeParse from \"rehype-parse\"\nimport rehypeStringify from \"rehype-stringify\"\nimport remarkGfm from \"remark-gfm\"\nimport remarkMdx from \"remark-mdx\"\nimport remarkParse from \"remark-parse\"\nimport remarkRehype from \"remark-rehype\"\nimport {unified} from \"unified\"\n\nimport type {\n PageFrontmatter,\n PageHeading,\n RichContentNode,\n} from \"@qualcomm-ui/mdx-common\"\n\nimport {rehypeSlug} from \"../../../rehype/rehype-slug\"\nimport {remarkAlerts} from \"../../../remark/remark-alerts\"\n\nimport type {IndexedPage, IndexedSection} from \"./markdown.types\"\nimport {remarkRemoveMermaidCodeBlocks} from \"./remark-remove-code-blocks\"\nimport {remarkRemoveJsx} from \"./remark-remove-jsx\"\n\n/**\n * Parses an html string into an AST and builds the search index from the tree.\n */\nexport class MarkdownIndexer {\n private sections: IndexedSection[] = []\n private currentSection!: IndexedSection\n private readonly headingLevels: Set<string>\n\n reset(): void {\n this.sections = []\n this._toc = []\n this.resetSection()\n }\n\n resetSection(): void {\n this.currentSection = {\n content: [],\n heading: null,\n richContent: [],\n }\n }\n\n get toc(): PageHeading[] {\n return this._toc\n }\n private _toc: PageHeading[] = []\n\n constructor(headingLevels: Set<string>) {\n this.resetSection()\n this.headingLevels = headingLevels\n }\n\n private appendTocItem(heading: PageHeading) {\n this._toc.push(heading)\n }\n\n private warn(...data: any[]) {\n if (process.env.DEBUG) {\n console.warn(...data)\n }\n // TODO: remove\n console.warn(...data)\n }\n\n private isHeading(element: Element): boolean {\n return this.headingLevels.has(element.tagName)\n }\n\n private isRootHeading(element: Element) {\n return element.tagName === \"h1\"\n }\n\n /**\n * Parses a heading Element node into the indexed heading data structure.\n */\n private parseHeading(headingElement: Element): PageHeading {\n const id = headingElement.properties.id\n const text = toText(headingElement)\n\n return {\n headingLevel: parseInt(headingElement.tagName.charAt(1)),\n id: id ? `${id}` : \"\",\n tagName: headingElement.tagName,\n textContent: text,\n }\n }\n\n private parseElementNode(element: Element) {\n const isRootHeading = this.isRootHeading(element)\n if (this.isHeading(element) || isRootHeading) {\n const currentSection = this.currentSection\n if (currentSection.heading) {\n // the old section is now done, so we add it and start a new one.\n this.sections.push(clone(this.currentSection))\n this.resetSection()\n }\n const heading = this.parseHeading(element)\n if (!isRootHeading) {\n this.appendTocItem(heading)\n }\n this.currentSection.heading = heading\n return\n }\n\n this.currentSection.richContent.push(element as RichContentNode)\n\n const text = toText(element, {whitespace: \"pre-wrap\"})\n .replaceAll(\"\\n\", \"\\t\")\n .split(\"\\t\")\n .filter(size)\n\n if (text.length) {\n this.currentSection.content.push({\n tagName: element.tagName,\n text,\n })\n }\n }\n\n parseMarkdown(\n fileContents: string | Buffer,\n frontmatter: PageFrontmatter,\n ): IndexedPage {\n const file = unified()\n .use(remarkMdx)\n .use(remarkRemoveJsx)\n .use(remarkRemoveMermaidCodeBlocks)\n .use(remarkParse)\n .use(remarkGfm)\n .use(remarkAlerts)\n .use(remarkRehype)\n .use(rehypeStringify)\n .processSync(fileContents)\n\n let contents = file.toString()\n\n contents = contents.substring(contents.indexOf(\"<h1>\"))\n\n for (const [key, value] of Object.entries(frontmatter)) {\n if (typeof value === \"string\" || typeof value === \"number\") {\n contents = contents.replaceAll(`frontmatter.${key}`, `${value}`)\n }\n }\n\n const htmlAst = unified()\n .data(\"settings\", {fragment: true})\n .use(rehypeParse)\n .use(rehypeStringify)\n .use(rehypeSlug)\n .processSync(contents)\n\n contents = htmlAst.toString()\n\n return this.build(contents)\n }\n\n build(html: string): IndexedPage {\n const tree = fromHtml(html, {fragment: true})\n\n for (const child of tree.children) {\n if (child.type === \"element\") {\n this.parseElementNode(child)\n }\n }\n\n // The parser processes sections in order and only appends the content once a\n // new section is encountered. We manually account for the final section here.\n if (this.currentSection.heading?.textContent) {\n this.sections.push(clone(this.currentSection))\n }\n\n return {\n sections: this.sections,\n toc: this.toc,\n }\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport type {Root} from \"hast\"\nimport {headingRank} from \"hast-util-heading-rank\"\nimport {toString} from \"hast-util-to-string\"\nimport type {Plugin} from \"unified\"\nimport {visit} from \"unist-util-visit\"\n\nexport interface RehypeSlugOptions {\n /**\n * @default ['h2', 'h3', 'h4']\n */\n allowedHeadings?: string[]\n prefix?: string\n}\n\nconst emptyOptions: RehypeSlugOptions = {}\n\n/**\n * Converts heading text to URL-friendly slugs. Converts multi-word and PascalCase\n * text to kebab-case. Lowercases single sentence-case words. Appends counter for\n * duplicate slugs.\n */\nexport const rehypeSlug: Plugin<[RehypeSlugOptions?], Root> = (\n options: RehypeSlugOptions | null | undefined,\n) => {\n const settings = options || emptyOptions\n const prefix = settings.prefix || \"\"\n const allowedHeadings = new Set<string>(\n settings.allowedHeadings || [\"h2\", \"h3\", \"h4\"],\n )\n const seenIds = new Map<string, number>()\n\n function createSlug(text: string): string {\n const cleaned = text\n .replace(/[<>]/g, \"\")\n .replace(/[^\\w\\s-]/g, \"\")\n .trim()\n\n let slug: string\n if (cleaned.includes(\" \")) {\n slug = cleaned\n .toLowerCase()\n .replace(/\\s+/g, \"-\")\n .replace(/^-+|-+$/g, \"\")\n } else if ((cleaned.match(/[A-Z]/g) || []).length >= 2) {\n slug = cleaned\n .replace(/([a-z0-9])([A-Z])/g, \"$1-$2\")\n .replace(/([A-Z]+)([A-Z][a-z])/g, \"$1-$2\")\n .toLowerCase()\n } else {\n slug = cleaned.toLowerCase()\n }\n\n const count = seenIds.get(slug) || 0\n seenIds.set(slug, count + 1)\n return count > 0 ? `${slug}-${count}` : slug\n }\n\n return (tree) => {\n seenIds.clear()\n visit(tree, \"element\", function (node) {\n if (\n headingRank(node) &&\n !node.properties.id &&\n allowedHeadings.has(node.tagName)\n ) {\n node.properties.id = prefix + createSlug(toString(node))\n }\n })\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport type {PhrasingContent, Root} from \"mdast\"\nimport type {Plugin} from \"unified\"\nimport {visit} from \"unist-util-visit\"\n\nconst alertLegacyRegex = /^\\[!(NOTE|TIP|SUCCESS|WARNING|CAUTION)(\\/.*)?\\]/i\n\n/**\n * Alerts are a Markdown extension based on the blockquote syntax that you can use\n * to emphasize critical information. On GitHub, they are displayed with distinctive\n * colors and icons to indicate the significance of the content.\n * https://docs.github.com/en/get-started/writing-on-github/getting-started-with-writing-and-formatting-on-github/basic-writing-and-formatting-syntax#alerts\n */\nexport const remarkAlerts: Plugin<[], Root> = () => {\n return (tree) => {\n visit(tree, \"blockquote\", (node) => {\n let alertType = \"\"\n let title = \"\"\n let isNext = true\n const child = node.children.map((item) => {\n if (isNext && item.type === \"paragraph\") {\n const firstNode = item.children[0]\n const text = firstNode.type === \"text\" ? firstNode.value : \"\"\n const reg = alertLegacyRegex\n const match = text.match(reg)\n if (match) {\n isNext = false\n alertType = match[1].toLocaleLowerCase()\n title = match[2] || alertType.toLocaleUpperCase()\n if (text.includes(\"\\n\")) {\n item.children[0] = {\n type: \"text\",\n value: text.replace(reg, \"\").replace(/^\\n+/, \"\"),\n }\n }\n\n if (!text.includes(\"\\n\")) {\n const itemChild: PhrasingContent[] = []\n item.children.forEach((item: any, idx: number) => {\n if (idx === 0) {\n return\n }\n if (idx === 1 && item.type === \"break\") {\n return\n }\n itemChild.push(item)\n })\n item.children = [...itemChild]\n }\n }\n }\n return item\n })\n\n title = title.replace(/^\\//, \"\")\n\n if (!!alertType) {\n node.data = {\n hName: \"div\",\n hProperties: {\n class: `qui-notification__root`,\n \"data-emphasis\":\n alertToEmphasis[alertType as IconType] || \"neutral\",\n \"data-orientation\": \"vertical\",\n dir: \"auto\",\n },\n }\n node.children = [\n {\n children: [getAlertIcon(alertType as IconType)],\n data: {\n hProperties: {\n class: \"qui-notification__icon\",\n \"data-part\": \"status-icon\",\n \"data-scope\": \"inline-notification\",\n },\n },\n type: \"paragraph\",\n },\n {\n children: [\n {\n type: \"text\",\n value: title,\n },\n ],\n data: {\n hProperties: {\n class: \"qui-notification__label\",\n dir: \"auto\",\n },\n },\n type: \"paragraph\",\n },\n {\n children: child,\n data: {\n hName: \"div\",\n hProperties: {\n class: `qui-notification__description`,\n dir: \"auto\",\n },\n },\n type: \"blockquote\",\n },\n ]\n }\n })\n }\n}\n\nexport function getAlertIcon(type: IconType): PhrasingContent {\n const svgChildren = svgData[type] ?? []\n return {\n children: svgChildren,\n data: {\n hName: \"svg\",\n hProperties: {\n ariaHidden: \"true\",\n class: \"lucide\",\n fill: \"transparent\",\n height: \"20\",\n stroke: \"currentColor\",\n strokeLinecap: \"round\",\n strokeLinejoin: \"round\",\n strokeWidth: \"2\",\n viewBox: \"0 0 24 24\",\n width: \"20\",\n },\n },\n type: \"emphasis\",\n }\n}\n\ntype IconType = \"note\" | \"tip\" | \"success\" | \"warning\" | \"caution\"\n\n/**\n * These SVG children correspond to the lucide icons matching our\n * {@link https://react.qui.qualcomm.com/components/inline-alert | Alert} component.\n */\nconst svgData: Record<IconType, PhrasingContent[]> = {\n caution: [\n {\n children: [],\n data: {\n hName: \"polygon\",\n hProperties: {\n points:\n \"7.86 2 16.14 2 22 7.86 22 16.14 16.14 22 7.86 22 2 16.14 2 7.86 7.86 2\",\n },\n },\n type: \"emphasis\",\n },\n {\n children: [],\n data: {\n hName: \"line\",\n hProperties: {\n x1: \"12\",\n x2: \"12\",\n y1: \"8\",\n y2: \"12\",\n },\n },\n type: \"emphasis\",\n },\n {\n children: [],\n data: {\n hName: \"line\",\n hProperties: {\n x1: \"12\",\n x2: \"12.01\",\n y1: \"16\",\n y2: \"16\",\n },\n },\n type: \"emphasis\",\n },\n ],\n note: [\n {\n children: [],\n data: {\n hName: \"circle\",\n hProperties: {\n cx: \"12\",\n cy: \"12\",\n r: \"10\",\n },\n },\n type: \"emphasis\",\n },\n {\n children: [],\n data: {\n hName: \"path\",\n hProperties: {\n d: \"M12 16v-4\",\n },\n },\n type: \"emphasis\",\n },\n {\n children: [],\n data: {\n hName: \"path\",\n hProperties: {\n d: \"M12 8h.01\",\n },\n },\n type: \"emphasis\",\n },\n ],\n success: [\n {\n children: [],\n data: {\n hName: \"path\",\n hProperties: {\n d: \"M20 6 9 17l-5-5\",\n },\n },\n type: \"emphasis\",\n },\n ],\n tip: [\n {\n children: [],\n data: {\n hName: \"path\",\n hProperties: {\n d: \"M15 14c.2-1 .7-1.7 1.5-2.5 1-.9 1.5-2.2 1.5-3.5A6 6 0 0 0 6 8c0 1 .2 2.2 1.5 3.5.7.7 1.3 1.5 1.5 2.5\",\n },\n },\n type: \"emphasis\",\n },\n {\n children: [],\n data: {\n hName: \"path\",\n hProperties: {\n d: \"M9 18h6\",\n },\n },\n type: \"emphasis\",\n },\n {\n children: [],\n data: {\n hName: \"path\",\n hProperties: {\n d: \"M10 22h4\",\n },\n },\n type: \"emphasis\",\n },\n ],\n warning: [\n {\n children: [],\n data: {\n hName: \"path\",\n hProperties: {\n d: \"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3\",\n },\n },\n type: \"emphasis\",\n },\n {\n children: [],\n data: {\n hName: \"path\",\n hProperties: {\n d: \"M12 9v4\",\n },\n },\n type: \"emphasis\",\n },\n {\n children: [],\n data: {\n hName: \"path\",\n hProperties: {\n d: \"M12 17h.01\",\n },\n },\n type: \"emphasis\",\n },\n ],\n}\n\nconst alertToEmphasis: Record<IconType, string> = {\n caution: \"danger\",\n note: \"neutral\",\n success: \"success\",\n tip: \"info\",\n warning: \"warning\",\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport type {Plugin} from \"unified\"\nimport {remove} from \"unist-util-remove\"\n\nexport const remarkRemoveMermaidCodeBlocks: Plugin = () => {\n return (tree, _file, done) => {\n remove(tree, (node: any) => node.type === \"code\" && node.lang === \"mermaid\")\n done()\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport type {Plugin} from \"unified\"\nimport {remove} from \"unist-util-remove\"\n\nexport const remarkRemoveJsx: Plugin = () => {\n return (tree, _file, done) => {\n remove(tree, \"mdxjsEsm\")\n remove(tree, \"mdxJsxFlowElement\")\n done()\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport type {RouteMetaEntryInternal, RouteMetaInternal} from \"../../../types\"\n\n/**\n * Retrieves the route metadata for a given path based on its path segments.\n */\nexport function getRouteMeta(\n pathSegments: string[],\n metaJson: RouteMetaInternal,\n): RouteMetaEntryInternal | undefined | null {\n const routeMeta = metaJson[pathSegments[0]]\n if (!routeMeta) {\n // backup, fetch using id if provided\n return undefined\n }\n\n if (pathSegments.length === 1) {\n return routeMeta\n }\n\n return pathSegments\n .slice(1)\n .reduce((acc: RouteMetaEntryInternal | undefined | null, segment) => {\n return acc?.children?.[segment]\n }, routeMeta)\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport {capitalCase} from \"change-case\"\nimport {sortBy} from \"lodash-es\"\nimport {v4 as uuidv4} from \"uuid\"\n\nimport type {\n NavItem,\n PageFrontmatter,\n PageSection,\n} from \"@qualcomm-ui/mdx-common\"\n\nimport type {\n NavMeta,\n RouteMetaEntryInternal,\n RouteMetaInternal,\n} from \"../../../types\"\nimport {defined} from \"../../utils\"\n\nimport {getRouteMeta} from \"./get-route-meta\"\n\ninterface InitialRoute {\n pageFrontmatter: Partial<PageFrontmatter>\n pageSection: PageSection\n routeMeta?: RouteMetaEntryInternal\n}\n\n/**\n * Given a flat remix route structure, computes nested navigation items for the QUI\n * side nav.\n */\nexport class NavBuilder {\n private initialRoutes: InitialRoute[] = []\n private flatNavItems: NavItem[] = []\n\n get navItems(): NavItem[] {\n return this._navItems\n }\n private _navItems: NavItem[] = []\n\n private readonly metaJson: RouteMetaInternal\n private readonly navMeta: Record<number, NavMeta>\n\n constructor(metaJson: RouteMetaInternal, navMeta: Record<number, NavMeta>) {\n this.navMeta = navMeta\n this.metaJson = metaJson\n }\n\n add(\n pageSection: PageSection,\n pageFrontmatter: Partial<PageFrontmatter>,\n routeMeta?: RouteMetaEntryInternal,\n ): void {\n this.initialRoutes.push({pageFrontmatter, pageSection, routeMeta})\n }\n\n reset(): void {\n this.initialRoutes = []\n this.flatNavItems = []\n this._navItems = []\n }\n\n /**\n * Sorts nav items. Nav items with an order defined take precedence over nav items\n * without an order. Nav items with the same order are sorted alphabetically by\n * title.\n */\n private navItemSort(a: NavItem, b: NavItem, groupOrder?: string[]) {\n if (a.depth !== b.depth) {\n return a.depth - b.depth\n }\n\n if (a.order && !b.order) {\n return -1\n }\n if (!a.order && b.order) {\n return 1\n } else if (a.order && b.order && a.order !== b.order) {\n return a.order - b.order\n }\n\n if (groupOrder && a.group && b.group) {\n const aIndex = a.group ? groupOrder.indexOf(a.group) : -1\n const bIndex = b.group ? groupOrder.indexOf(b.group) : -1\n\n if (aIndex === bIndex) {\n // continue\n } else if (aIndex !== -1 && bIndex !== -1) {\n return aIndex - bIndex\n } else if (aIndex !== -1) {\n return -1\n } else if (bIndex !== -1) {\n return 1\n }\n }\n\n // group items with the same group\n if (a.group !== b.group) {\n if (!a.group && b.group) {\n return -1\n }\n if (a.group && !b.group) {\n return 1\n }\n if (a.group && b.group) {\n return a.group.localeCompare(b.group)\n }\n }\n\n return a.title.localeCompare(b.title)\n }\n\n resolveSideNavTitle(\n frontmatter: Partial<PageFrontmatter>,\n routeMeta: Partial<RouteMetaEntryInternal>,\n fallback: string,\n ): string {\n return (\n (defined(routeMeta.sideNavTitle)\n ? routeMeta.sideNavTitle || \"\"\n : frontmatter.sideNavTitle || \"\") || fallback\n )\n }\n\n /**\n * Builds a flat list of nav items from the MDX pages and _meta.json. If a page\n * does not exist, it is not added to the side nav (even if it has an entry in\n * _meta.json).\n */\n private buildNavItem({\n pageFrontmatter,\n pageSection: {pathname, pathSegments, title},\n routeMeta: routeMetaParam,\n }: InitialRoute) {\n const id = pageFrontmatter?.id || \"\"\n\n // handle home page (this route does not have path segments)\n if (!pathSegments.length && pathname === \"/\") {\n const routeMeta =\n routeMetaParam || getRouteMeta(id ? [id] : [], this.metaJson)\n if (!routeMeta) {\n return\n }\n\n this.flatNavItems.push({\n depth: 1,\n expanded: routeMeta?.expanded || false,\n id: `/`,\n order: routeMeta?.order,\n pathname,\n pathSegments: [],\n title: this.resolveSideNavTitle(\n pageFrontmatter,\n routeMeta,\n routeMeta?.title || title,\n ),\n })\n }\n\n pathSegments.forEach((segment, index) => {\n const depth = index + 1\n\n // we only add an item if it doesn't already exist, which we determine by\n // comparing the path segments iteratively.\n const navItem = this.flatNavItems.find((item) =>\n pathSegments\n .slice(0, depth)\n .every((value, i) => value === item.pathSegments[i]),\n )\n\n if (!navItem) {\n const isPage = index === pathSegments.length - 1\n const adjustedSegments = pathSegments.slice(0, depth)\n\n const routeMeta =\n getRouteMeta(\n isPage ? pathSegments : adjustedSegments,\n this.metaJson,\n ) ?? {}\n\n this.flatNavItems.push({\n depth,\n expanded: routeMeta?.expanded || false,\n group: isPage\n ? routeMeta.group || pageFrontmatter.group\n : routeMeta.group,\n id: `/${adjustedSegments.join(\"/\")}`,\n items: [],\n order: routeMeta?.order,\n pathname: isPage ? pathname : undefined,\n pathSegments: adjustedSegments,\n title: this.resolveSideNavTitle(\n pageFrontmatter,\n routeMeta,\n routeMeta?.title\n ? routeMeta.title\n : isPage\n ? title\n : capitalCase(segment),\n ),\n })\n }\n })\n }\n\n /**\n * Iterates through a nav item's path segments and ensures that all of its parent\n * elements exist in the recursive structure.\n */\n private ensureParent(navItem: NavItem) {\n const segments = navItem.pathSegments\n let items: NavItem[] = this.navItems\n let item: NavItem | undefined\n let prevItem: NavItem | undefined = undefined\n\n for (let i = 0; i < segments.length - 1; i++) {\n const segment = segments[i]\n item = items?.find((entry) => entry.pathSegments[i] === segment)\n if (item) {\n // point to the found item's children and keep iterating\n items = item.items ?? []\n prevItem = item\n continue\n }\n if (prevItem) {\n const pathSegments = segments.slice(0, i + 1)\n const routeMeta = getRouteMeta(pathSegments, this.metaJson)\n\n items = []\n const base = {\n depth: pathSegments.length,\n id: `/routes/${pathSegments.join(\"/\")}`,\n items,\n pathSegments,\n title: segment,\n }\n const newItem = routeMeta\n ? {\n ...base,\n expanded: routeMeta.expanded,\n order: routeMeta.order,\n restricted: routeMeta.restricted,\n title: routeMeta.title ?? segment,\n }\n : base\n prevItem.items = prevItem.items\n ? [...prevItem.items, newItem]\n : [newItem]\n }\n prevItem = item\n }\n }\n\n /**\n * Deeply inserts a nav item into the array, iterating through parent routes\n * (based on the pathSegments) and adding them if they don't exist.\n *\n * For example, given a leaf node 4 path segments deep, this function will create\n * all parent nav items as nested children of the top-most nav item.\n */\n private nestedInsert(\n item: NavItem,\n pathSegments: string[],\n items: NavItem[],\n ) {\n const segment = pathSegments[0]\n const parentItem = items.find(\n (parent) =>\n parent.pathSegments[parent.pathSegments.length - 1] === segment,\n )\n if (parentItem) {\n this.nestedInsert(item, pathSegments.slice(1), parentItem.items ?? [])\n } else if (pathSegments.length === 1) {\n items.push(item)\n }\n }\n\n private buildNestedNavItems() {\n for (let i = 0; i < this.flatNavItems.length; i++) {\n const navItem = this.flatNavItems[i]\n if (navItem.depth === 1) {\n this.navItems.push(navItem)\n continue\n }\n\n this.ensureParent(navItem)\n this.nestedInsert(navItem, navItem.pathSegments, this.navItems)\n }\n }\n\n private sortNestedNavItems(items: NavItem[], groupOrder?: string[]) {\n items.sort((a, b) => this.navItemSort(a, b, groupOrder))\n items.forEach((item) => {\n if (item.items?.length) {\n const meta = getRouteMeta(item.pathSegments, this.metaJson)\n this.sortNestedNavItems(item.items, meta?.groupOrder)\n }\n })\n }\n\n /**\n * To be called after every mdx page route has been added through the {@link add}\n * function.\n */\n build(): NavItem[] {\n // We need to process parent items first, so we sort by path segment. Routes\n // with shorter path segments will be processed first.\n sortBy(\n this.initialRoutes,\n (item) => item.pageSection.pathSegments.length,\n ).map((r) => this.buildNavItem(r))\n\n this.buildNestedNavItems()\n\n const rootMeta = getRouteMeta([], this.metaJson)\n this.sortNestedNavItems(this.navItems, rootMeta?.groupOrder)\n\n if (this.navMeta) {\n Object.entries(this.navMeta).forEach(([index, value]) => {\n this._navItems.splice(parseInt(index), 0, {\n depth: 1,\n id: uuidv4(),\n pathSegments: [],\n sectionTitle: value.sectionTitle,\n separator: value.separator,\n title: \"\",\n })\n })\n }\n\n this._navItems = this.groupNavItems(this.navItems)\n this._navItems = this.buildSearchMeta(this.navItems, [])\n return this.navItems\n }\n\n private groupNavItems(items: NavItem[]): NavItem[] {\n const result: NavItem[] = []\n const seenGroups = new Set<string>()\n\n for (const item of items) {\n if (item.group && !seenGroups.has(item.group)) {\n seenGroups.add(item.group)\n result.push({\n depth: item.depth,\n group: item.group,\n id: uuidv4(),\n pathSegments: [],\n sectionTitle: item.group,\n title: \"\",\n })\n }\n\n result.push({\n ...item,\n items: item.items ? this.groupNavItems(item.items) : undefined,\n })\n }\n\n return result\n }\n\n /**\n * Walks over the tree and builds search metadata using the nearest sectionTitle.\n */\n private buildSearchMeta(items: NavItem[], meta: string[]): NavItem[] {\n let sectionTitle = \"\"\n const results: NavItem[] = []\n\n for (const ogItem of items) {\n const item = {...ogItem}\n\n if (item.sectionTitle) {\n sectionTitle = item.sectionTitle\n } else if (item.separator) {\n sectionTitle = \"\"\n }\n\n if (!item.separator) {\n const currentMeta = sectionTitle ? [...meta, sectionTitle] : [...meta]\n const nextMeta = [...(item.searchMeta || []), ...currentMeta]\n if (nextMeta.length) {\n item.searchMeta = [...nextMeta]\n }\n\n if (item.items) {\n item.items = this.buildSearchMeta(item.items, currentMeta)\n }\n }\n\n results.push(item)\n }\n\n return results\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport {capitalCase} from \"change-case\"\nimport {join} from \"node:path\"\n\nimport type {RouteMetaInternal, RoutingStrategy} from \"../../../types\"\n\nimport {getRouteMeta} from \"./get-route-meta\"\n\nexport function getPathnameFromPathSegments(segments: string[]) {\n return `/${segments.join(\"/\")}`\n}\n\nexport function getCategoriesFromPathSegments(\n segments: string[],\n metaJson: RouteMetaInternal,\n // the frontmatter title only applies to the last segment.\n frontmatterTitle: string,\n): string[] {\n return segments.reduce((acc: string[], segment, index) => {\n const pathSegments = segments.slice(0, index + 1)\n if (index === segments.length - 1) {\n acc.push(frontmatterTitle)\n return acc\n }\n const meta = getRouteMeta(pathSegments, metaJson)\n if (meta?.title) {\n acc.push(meta.title)\n } else {\n acc.push(pathSegmentToCategory(segment))\n }\n return acc\n }, [])\n}\n\n// fallback for unmatched path segments\nexport function pathSegmentToCategory(segment: string): string {\n // we don't transform words like `a`, `or`, and `and`\n return segment\n .split(\"-\")\n .map((segment) =>\n /\\b(a|an|and|but|or|in|on|at)\\b/.test(segment)\n ? segment\n : capitalCase(segment),\n )\n .join(\" \")\n}\n\nfunction getGeneroutedPathSegments(filePath: string): string[] {\n const extension = filePath.endsWith(\"mdx\") ? \"mdx\" : \"tsx\"\n\n const segments = filePath\n .substring(0, filePath.lastIndexOf(`.${extension}`))\n .split(\"/\")\n\n if (segments[segments.length - 1] === \"index\") {\n return segments.slice(0, segments.length - 1)\n }\n return segments\n}\n\nconst pathSeparatorRegex = /[\\/\\\\.]/\nfunction isPathSeparator(char: string) {\n return pathSeparatorRegex.test(char)\n}\n\nconst indexRouteRegex =\n /((^|[.]|[+]\\/)(index|_index))(\\/[^\\/]+)?$|(\\/_?index\\/)/\n\nfunction getRemixFlatRoutesSegments(\n name: string,\n index: boolean,\n paramPrefixChar: string = \"$\",\n) {\n let routeSegments: string[] = []\n let i = 0\n let routeSegment = \"\"\n let state = \"START\"\n let subState = \"NORMAL\"\n let hasPlus = false\n\n // ignore layout routes\n if (name.endsWith(\"_layout\")) {\n return []\n }\n\n /*\n * name has already been normalized to use / as path separator.\n * replace `+/_.` with `_+/`\n * this supports the ability to specify parent folder will not be a layout.\n * _public+/_.about.tsx => _public_.about.tsx\n */\n if (/\\+\\/_\\./.test(name)) {\n name = name.replace(/\\+\\/_\\./g, \"_+/\")\n }\n\n /*\n * replace `+/` with `.`\n * this supports folders for organizing flat-files convention.\n * _public+/about.tsx => _public.about.tsx\n */\n if (/\\+\\//.test(name)) {\n name = name.replace(/\\+\\//g, \".\")\n hasPlus = true\n }\n const hasFolder = /\\//.test(name)\n // if name has plus folder, but we still have regular folders\n // then treat ending route as flat-folders\n if (\n ((hasPlus && hasFolder) || !hasPlus) &&\n !(name.endsWith(\".route\") || name.endsWith(\".index\"))\n ) {\n // Do not remove segments ending in .route\n // since these would be part of the route directory name\n // docs/readme.route.tsx => docs/readme\n // Remove last segment since this should just be the route filename, and we only\n // want the directory name docs/_layout.tsx => docs\n const last = name.lastIndexOf(\"/\")\n if (last >= 0) {\n name = name.substring(0, last)\n }\n }\n\n const pushRouteSegment = (routeSegment: string) => {\n if (routeSegment) {\n routeSegments.push(routeSegment)\n }\n }\n\n while (i < name.length) {\n const char = name[i]\n switch (state) {\n case \"START\":\n // process existing segment\n if (\n routeSegment.includes(paramPrefixChar) &&\n !(\n routeSegment.startsWith(paramPrefixChar) ||\n routeSegment.startsWith(`(${paramPrefixChar}`)\n )\n ) {\n throw new Error(\n `Route params must start with prefix char ${paramPrefixChar}: ${routeSegment}`,\n )\n }\n if (\n routeSegment.includes(\"(\") &&\n !routeSegment.startsWith(\"(\") &&\n !routeSegment.endsWith(\")\")\n ) {\n throw new Error(\n `Optional routes must start and end with parentheses: ${routeSegment}`,\n )\n }\n pushRouteSegment(routeSegment)\n routeSegment = \"\"\n state = \"PATH\"\n continue // restart without advancing index\n case \"PATH\":\n if (isPathSeparator(char) && subState === \"NORMAL\") {\n state = \"START\"\n break\n } else if (char === \"[\") {\n subState = \"ESCAPE\"\n break\n } else if (char === \"]\") {\n subState = \"NORMAL\"\n break\n }\n routeSegment += char\n break\n }\n i++ // advance to next character\n }\n // process remaining segment\n pushRouteSegment(routeSegment)\n // strip trailing .route segment\n if (\n routeSegments.at(-1) === \"route\" ||\n routeSegments.at(-1) === \"index\" ||\n routeSegments.at(-1) === \"_index\" ||\n routeSegments.at(-1) === \"_route\"\n ) {\n routeSegments = routeSegments.slice(0, -1)\n }\n // if hasPlus, we need to strip the trailing segment if it starts with _\n // and route is not an index route\n // this is to handle layouts in flat-files\n // _public+/_layout.tsx => _public.tsx\n // _public+/index.tsx => _public.index.tsx\n if (!index && hasPlus && routeSegments.at(-1)?.startsWith(\"_\")) {\n routeSegments = routeSegments.slice(0, -1)\n }\n return routeSegments\n}\n\nfunction getRemixHybridRoutesPathSegments(filePath: string): string[] {\n const routeWithoutExtension = filePath.substring(0, filePath.lastIndexOf(\".\"))\n\n return getRemixFlatRoutesSegments(\n routeWithoutExtension,\n indexRouteRegex.test(routeWithoutExtension),\n )\n}\n\nexport function getPathSegmentsFromFileName(\n filePath: string,\n pageDirectory: string,\n strategy?: RoutingStrategy,\n): string[] {\n const filePathWithoutPageDirectory = filePath.substring(\n filePath.indexOf(pageDirectory) + pageDirectory.length + 1,\n )\n if (typeof strategy === \"function\") {\n return strategy(filePathWithoutPageDirectory)\n }\n switch (strategy) {\n case \"vite-generouted\":\n return getGeneroutedPathSegments(filePathWithoutPageDirectory)\n default:\n return getRemixHybridRoutesPathSegments(filePathWithoutPageDirectory)\n }\n}\n\nexport function filterFileGlob(\n fileGlob: string[],\n ext: string,\n srcDir: string,\n router?: RoutingStrategy,\n): string[] {\n if (typeof router === \"string\" && router === \"vite-generouted\") {\n // vite-generouted: filter routes\n const restrictedPattern = /(\\(.*\\))|(\\[.*\\])/\n // pull out the full path before filtering to avoid potential issues with\n // parent directories.\n const relativeGlobs = fileGlob.map((file) => file.replace(srcDir, \"\"))\n return (\n relativeGlobs\n .filter(\n (file) =>\n file.endsWith(`.${ext}`) &&\n !file.includes(\"/_\") &&\n !file.includes(\"/+\"),\n )\n // filter pathless segments\n .map((file) =>\n file\n .split(\"/\")\n .filter((segment) => !restrictedPattern.test(segment))\n .join(\"/\"),\n )\n // restore full path\n .map((file) => join(srcDir, file))\n )\n }\n return fileGlob.filter((file) => file.endsWith(ext) && !file.includes(\"$\"))\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport type {NavConfig, NavMeta, RouteMeta, RouteMetaInternal} from \"../types\"\n\nexport function transformRouteMetaArray(\n meta: NavConfig[],\n routeMetaNav: Record<string, NavMeta>,\n): RouteMetaInternal {\n let ignoringOrder = 0\n return meta.reduce((acc: RouteMetaInternal, item, index) => {\n // strip the nav meta and populate a separate record. This will be used for\n // lookup while building the nav items.\n if (!(\"id\" in item)) {\n if (\"separator\" in item || \"sectionTitle\" in item) {\n // offset the navMeta index by the number of items that will be sorted to\n // the back of the nav order.\n routeMetaNav[index - ignoringOrder] = item\n }\n return acc\n }\n const current = item as RouteMeta\n if (current.ignoreRouteMetaOrder || current.hidden) {\n // items with ignored order are always sorted to the back of the nav order. We\n // need to account for this when splicing in the navMeta entries.\n ignoringOrder++\n }\n acc[current.id] = {\n children: current.children\n ? transformRouteMetaArray(current.children, routeMetaNav)\n : undefined,\n expanded: current.expanded,\n group: current.group,\n groupOrder: current.groupOrder,\n hidden: current.hidden,\n hideBreadcrumbs: current.hideBreadcrumbs,\n hideFromSearch: current.hideFromSearch,\n hidePageLinks: current.hidePageLinks,\n hideSideNav: current.hideSideNav,\n hideToc: current.hideToc,\n order: current.ignoreRouteMetaOrder ? undefined : index + 1,\n restricted: current.restricted,\n title: current.title,\n }\n return acc\n }, {})\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport rehypeShiki, {type RehypeShikiOptions} from \"@shikijs/rehype\"\nimport type {PluggableList} from \"unified\"\n\nimport {quiCustomDarkTheme} from \"@qualcomm-ui/mdx-common\"\n\nimport {\n rehypeMdxCodeProps,\n remarkFrontmatter,\n remarkGfm,\n remarkMdxFrontmatter,\n} from \"../exports\"\n\nimport {ConfigLoader, type ConfigLoaderOptions} from \"./internal\"\nimport {rehypeSectionize, rehypeSlug, type RehypeSlugOptions} from \"./rehype\"\nimport {remarkAlerts, remarkCodeTabs, remarkSpoilers} from \"./remark\"\n\n/**\n * @deprecated migrate to the {@link getRehypePlugins} function\n */\nexport const quiRehypePlugins: PluggableList = [rehypeSectionize, rehypeSlug]\n\nexport interface QuiRehypePluginOptions extends ConfigLoaderOptions {\n rehypeShikiOptions?: Partial<RehypeShikiOptions>\n}\n\n/**\n * Used to retrieve all the rehype plugins required for QUI Docs MDX.\n * These should be passed to the `mdx` vite plugin from\n */\nexport function getRehypePlugins(\n options: QuiRehypePluginOptions = {},\n): PluggableList {\n const config = new ConfigLoader(options).loadConfig()\n return [\n rehypeMdxCodeProps,\n [\n rehypeSlug,\n {allowedHeadings: config.headings} satisfies RehypeSlugOptions,\n ],\n rehypeSectionize,\n [\n rehypeShiki,\n {\n defaultColor: \"light-dark()\",\n themes: {\n dark: quiCustomDarkTheme,\n light: \"github-light-high-contrast\",\n },\n ...options.rehypeShikiOptions,\n } satisfies RehypeShikiOptions,\n ],\n ]\n}\n\n/**\n * @deprecated migrate to the {@link getRemarkPlugins} function\n */\nexport const quiRemarkPlugins: PluggableList = [remarkAlerts, remarkCodeTabs]\n\n/**\n * @returns every remark plugin needed for QUI Docs MDX.\n *\n * @example\n * ```ts\n * // in your vite config\n * plugins: [\n * mdx({\n * providerImportSource: \"@mdx-js/react\",\n * rehypePlugins: [...getRehypePlugins()],\n * remarkPlugins: [...getRemarkPlugins()],\n * }),\n * quiDocsPlugin(),\n * // ... the rest of your plugins\n * ]\n * ```\n */\nexport function getRemarkPlugins(): PluggableList {\n return [\n remarkFrontmatter,\n remarkMdxFrontmatter,\n remarkGfm,\n remarkAlerts,\n remarkCodeTabs,\n remarkSpoilers,\n ]\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport rehypeMdxCodeProps from \"rehype-mdx-code-props\"\nimport remarkFrontmatter from \"remark-frontmatter\"\nimport remarkGfm from \"remark-gfm\"\nimport remarkMdxFrontmatter from \"remark-mdx-frontmatter\"\n\nimport {rehypeSlug} from \"./docs-plugin/rehype/rehype-slug\"\n\n// Re-export these peerDependencies for more convenient imports.\n// Some of these are not included in the bundled JS, so the user must install them\n// separately.\nexport {\n remarkFrontmatter,\n remarkGfm,\n remarkMdxFrontmatter,\n rehypeMdxCodeProps,\n rehypeSlug,\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport type {Element, Root, RootContent} from \"hast\"\nimport {heading} from \"hast-util-heading\"\nimport {headingRank} from \"hast-util-heading-rank\"\nimport type {Properties} from \"hastscript\"\nimport type {Plugin} from \"unified\"\n\nexport type RehypeSectionizeOptions = {\n enableRootSection?: boolean | undefined\n idPropertyName?: string | undefined\n properties?: Properties | undefined\n rankPropertyName?: string | undefined\n}\n\nconst defaultOptions: Required<RehypeSectionizeOptions> = {\n enableRootSection: false,\n idPropertyName: \"ariaLabelledby\",\n properties: {},\n rankPropertyName: \"dataHeadingRank\",\n}\n\nconst wrappingRank = (\n rootContent: RootContent | undefined,\n rankPropertyName: RehypeSectionizeOptions[\"rankPropertyName\"],\n) => {\n if (\n rootContent == null ||\n rankPropertyName == null ||\n !(\"properties\" in rootContent)\n ) {\n throw new Error(\"rootContent and rankPropertyName must have value\")\n }\n\n const rank = rootContent.properties?.[rankPropertyName]\n if (typeof rank !== \"number\") {\n throw new Error(`rankPropertyName(${rankPropertyName}) must be number`)\n }\n\n return rank\n}\n\nconst createElement = (\n rank: number,\n options: Pick<\n RehypeSectionizeOptions,\n \"properties\" | \"rankPropertyName\" | \"idPropertyName\"\n >,\n children: Element[] = [],\n) => {\n const {idPropertyName, properties, rankPropertyName} = options\n\n if (\n properties != null &&\n rankPropertyName != null &&\n rankPropertyName in properties\n ) {\n throw new Error(\n `rankPropertyName(${rankPropertyName}) dataHeadingRank must exist`,\n )\n }\n\n const id = children.at(0)?.properties?.id\n const element: Element = {\n children,\n properties: {\n className: [\"heading\"],\n ...(rankPropertyName ? {[rankPropertyName]: rank} : {}),\n ...(idPropertyName && typeof id === \"string\"\n ? {[idPropertyName]: id}\n : {}),\n ...(properties ? properties : {}),\n },\n tagName: \"section\",\n type: \"element\",\n }\n\n return element\n}\n\nexport const rehypeSectionize: Plugin<[RehypeSectionizeOptions?], Root> = (\n options = defaultOptions,\n) => {\n const {enableRootSection, ...rest} = {\n enableRootSection:\n options.enableRootSection ?? defaultOptions.enableRootSection,\n idPropertyName: options.idPropertyName ?? defaultOptions.idPropertyName,\n properties: options.properties ?? defaultOptions.properties,\n rankPropertyName:\n options.rankPropertyName ?? defaultOptions.rankPropertyName,\n }\n\n return (root) => {\n const rootWrapper = createElement(0, rest)\n\n const wrapperStack: RootContent[] = []\n wrapperStack.push(rootWrapper)\n\n const lastStackItem = () => {\n const last = wrapperStack.at(-1)\n if (last == null || last.type !== \"element\") {\n throw new Error(\"lastStackItem must be Element\")\n }\n return wrapperStack.at(-1) as Element\n }\n\n for (const rootContent of root.children) {\n if (heading(rootContent)) {\n const rank = headingRank(rootContent)\n if (rank == null) {\n throw new Error(\"heading or headingRank is not working\")\n }\n\n if (rank > wrappingRank(lastStackItem(), rest.rankPropertyName)) {\n const childWrapper = createElement(rank, rest, [rootContent])\n lastStackItem().children.push(childWrapper)\n wrapperStack.push(childWrapper)\n } else if (\n rank <= wrappingRank(lastStackItem(), rest.rankPropertyName)\n ) {\n while (rank <= wrappingRank(lastStackItem(), rest.rankPropertyName)) {\n wrapperStack.pop()\n }\n const siblingWrapper = createElement(rank, rest, [rootContent])\n\n lastStackItem().children.push(siblingWrapper)\n wrapperStack.push(siblingWrapper)\n }\n } else {\n if (rootContent.type === \"doctype\") {\n throw new Error(\"must be used in a fragment\")\n }\n lastStackItem().children.push(rootContent as any)\n }\n }\n\n return {\n ...root,\n children: enableRootSection ? [rootWrapper] : rootWrapper.children,\n }\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport type {Code, Parent, Root} from \"mdast\"\nimport type {Plugin} from \"unified\"\nimport {visit} from \"unist-util-visit\"\n\ninterface Tab {\n index: number\n label: string\n meta: string | undefined\n tabsGroup: string\n}\n\nfunction parseTabAttributes(meta: string): {\n label: string | null\n remainingMeta: string\n tabsGroup: string | null\n} {\n if (!meta) {\n return {label: null, remainingMeta: \"\", tabsGroup: null}\n }\n\n const tabsMatch = meta.match(/tabs=[\"']([^\"']+)[\"']|tabs=(\\S+)/)\n const labelMatch = meta.match(/label=[\"']([^\"']+)[\"']|label=(\\S+)/)\n\n const tabsGroup = tabsMatch ? tabsMatch[1] || tabsMatch[2] : null\n const label = labelMatch ? labelMatch[1] || labelMatch[2] : null\n\n // Remove both tabs and label attributes from meta\n const remainingMeta = meta\n .replace(/\\s*tabs=[\"']([^\"']+)[\"']/g, \"\")\n .replace(/\\s*tabs=(\\S+)/g, \"\")\n .replace(/\\s*label=[\"']([^\"']+)[\"']/g, \"\")\n .replace(/\\s*label=(\\S+)/g, \"\")\n .trim()\n\n return {label, remainingMeta, tabsGroup}\n}\n\nfunction findConsecutiveTabs(\n startIndex: number,\n parent: Parent,\n targetTabsGroup: string,\n): Tab[] {\n const tabs: Tab[] = []\n let currentIndex = startIndex\n\n while (currentIndex < parent.children.length) {\n const currentNode = parent.children[currentIndex]\n\n if (!currentNode || currentNode.type !== \"code\") {\n break\n }\n\n const codeNode = currentNode\n\n if (!codeNode.meta) {\n break\n }\n\n const {label, remainingMeta, tabsGroup} = parseTabAttributes(codeNode.meta)\n\n // Only include if it matches the target tabs group and has a label\n if (!tabsGroup || !label || tabsGroup !== targetTabsGroup) {\n break\n }\n\n // Clean the original node's meta NOW\n codeNode.meta = remainingMeta || undefined\n\n tabs.push({\n index: currentIndex,\n label,\n meta: remainingMeta || undefined,\n tabsGroup,\n })\n\n if (remainingMeta && remainingMeta.includes(\"end\")) {\n break\n }\n\n currentIndex++\n }\n\n return tabs\n}\n\nfunction renderTabs(tabs: Tab[], parent: Parent): any[] {\n const tabsContainer = {\n attributes: [],\n children: [] as any[],\n name: \"CodeTabs\",\n type: \"mdxJsxFlowElement\",\n }\n\n tabs.forEach((tab) => {\n const codeNode = parent.children[tab.index] as Code\n\n const tabAttributes = [\n {\n name: \"label\",\n type: \"mdxJsxAttribute\",\n value: tab.label,\n },\n ]\n\n // Add meta to JSX element if it exists\n if (tab.meta) {\n tabAttributes.push({\n name: \"meta\",\n type: \"mdxJsxAttribute\",\n value: tab.meta,\n })\n }\n\n const tabElement = {\n attributes: tabAttributes,\n children: [\n {\n lang: codeNode.lang,\n meta: codeNode.meta, // This is now clean\n type: \"code\",\n value: codeNode.value,\n },\n ],\n name: \"CodeTab\",\n type: \"mdxJsxFlowElement\",\n }\n\n tabsContainer.children.push(tabElement)\n })\n\n return [tabsContainer]\n}\n\n/**\n * Very cool. TODO: document this https://docs.qui.qualcomm.com/guide/markdown\n */\nexport const remarkCodeTabs: Plugin<[], Root> = () => {\n return (tree) => {\n const transformations: Array<{\n endIndex: number\n parent: Parent\n replacement: any[]\n startIndex: number\n }> = []\n\n visit(\n tree,\n \"code\",\n (node: Code, index: number | undefined, parent: Parent | undefined) => {\n if (!node.meta || !parent || index === undefined) {\n return\n }\n\n const {label, tabsGroup} = parseTabAttributes(node.meta)\n if (!tabsGroup || !label) {\n return\n }\n\n const alreadyProcessed = transformations.some(\n (t) =>\n t.parent === parent && index >= t.startIndex && index < t.endIndex,\n )\n\n if (alreadyProcessed) {\n return\n }\n\n const tabs = findConsecutiveTabs(index, parent, tabsGroup)\n\n if (tabs.length > 1) {\n const startIndex = tabs[0].index\n const endIndex = tabs[tabs.length - 1].index + 1\n const newChildren = renderTabs(tabs, parent)\n\n transformations.push({\n endIndex,\n parent,\n replacement: newChildren,\n startIndex,\n })\n }\n },\n )\n\n transformations\n .sort((a, b) => b.startIndex - a.startIndex)\n .forEach((transformation) => {\n transformation.parent.children.splice(\n transformation.startIndex,\n transformation.endIndex - transformation.startIndex,\n ...transformation.replacement,\n )\n })\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport type {Heading, Link, Root} from \"mdast\"\nimport {toString} from \"mdast-util-to-string\"\nimport type {Plugin} from \"unified\"\nimport {visit} from \"unist-util-visit\"\n\nexport interface RemarkSelfLinkOptions {\n /**\n * @default [2, 3, 4]\n */\n allowedLevels?: number[]\n prefix?: string\n}\n\nconst emptyOptions: RemarkSelfLinkOptions = {}\n\nexport function remarkSelfLinkHeadings(\n baseUrl: string = \"\",\n options?: RemarkSelfLinkOptions | null,\n): Plugin<[], Root> {\n if (!baseUrl) {\n return () => {}\n }\n return () => {\n const settings = options || emptyOptions\n const prefix = settings.prefix || \"\"\n const allowedLevels = new Set<number>(settings.allowedLevels || [2, 3, 4])\n const seenIds = new Map<string, number>()\n\n function createSlug(text: string): string {\n const cleaned = text\n .replace(/[<>]/g, \"\")\n .replace(/[^\\w\\s-]/g, \"\")\n .trim()\n\n let slug: string\n if (cleaned.includes(\" \")) {\n slug = cleaned\n .toLowerCase()\n .replace(/\\s+/g, \"-\")\n .replace(/^-+|-+$/g, \"\")\n } else if ((cleaned.match(/[A-Z]/g) || []).length >= 2) {\n slug = cleaned\n .replace(/([a-z0-9])([A-Z])/g, \"$1-$2\")\n .replace(/([A-Z]+)([A-Z][a-z])/g, \"$1-$2\")\n .toLowerCase()\n } else {\n slug = cleaned.toLowerCase()\n }\n\n const count = seenIds.get(slug) || 0\n seenIds.set(slug, count + 1)\n return count > 0 ? `${slug}-${count}` : slug\n }\n\n return (tree) => {\n seenIds.clear()\n visit(tree, \"heading\", (node: Heading) => {\n if (allowedLevels.has(node.depth)) {\n const text = toString(node)\n const slug = prefix + createSlug(text)\n\n const linkNode: Link = {\n children: node.children,\n type: \"link\",\n url: `${baseUrl}#${slug}`,\n }\n\n node.children = [linkNode]\n }\n })\n }\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport type {BlockContent, Root} from \"mdast\"\nimport type {Plugin} from \"unified\"\nimport {visit} from \"unist-util-visit\"\n\ninterface SpoilerOptions {\n defaultSummary?: string\n detailsClassName?: string[]\n summaryClassName?: string[]\n}\n\n/**\n * Transforms spoiler blocks into MDX components.\n *\n * @example\n * ```\n * ::: spoiler Title\n *\n * Content\n *\n * :::\n * ```\n *\n * result:\n *\n * ```jsx\n * <SpoilerRoot>\n * <SpoilerTrigger><p>Title</p></SpoilerTrigger>\n * <SpoilerContent>Content</SpoilerContent>\n * </SpoilerRoot>\n * ```\n */\nexport const remarkSpoilers: Plugin<[SpoilerOptions?], Root> = (\n options = {},\n) => {\n const {\n defaultSummary = \"Open spoiler\",\n detailsClassName = [],\n summaryClassName = [],\n } = options\n\n return (tree) => {\n visit(tree, \"paragraph\", (node, index, parent) => {\n if (!parent || index === undefined) {\n return\n }\n\n const firstChild = node.children[0]\n if (firstChild?.type !== \"text\") {\n return\n }\n\n const match = firstChild.value.match(/^:::\\s*spoiler\\s*(.*)$/)\n if (!match) {\n return\n }\n\n const summary = match[1].trim() || defaultSummary\n let endIndex = index + 1\n const contentNodes: BlockContent[] = []\n\n while (endIndex < parent.children.length) {\n const child = parent.children[endIndex]\n\n if (child.type === \"paragraph\") {\n const firstText = child.children[0]\n if (firstText?.type === \"text\" && firstText.value.trim() === \":::\") {\n break\n }\n }\n\n contentNodes.push(child as BlockContent)\n endIndex++\n }\n\n if (endIndex >= parent.children.length) {\n return\n }\n\n const summaryNode: BlockContent = {\n attributes: summaryClassName.length\n ? [\n {\n name: \"className\",\n type: \"mdxJsxAttribute\",\n value: summaryClassName.join(\" \"),\n },\n ]\n : [],\n children: [\n {\n children: [{type: \"text\", value: summary}],\n type: \"paragraph\",\n },\n ],\n name: \"SpoilerSummary\",\n type: \"mdxJsxFlowElement\",\n }\n\n const contentNode: BlockContent = {\n attributes: [],\n children: contentNodes,\n name: \"SpoilerContent\",\n type: \"mdxJsxFlowElement\",\n }\n\n const detailsNode: BlockContent = {\n attributes: detailsClassName.length\n ? [\n {\n name: \"className\",\n type: \"mdxJsxAttribute\",\n value: detailsClassName.join(\" \"),\n },\n ]\n : [],\n children: [summaryNode, contentNode],\n name: \"SpoilerRoot\",\n type: \"mdxJsxFlowElement\",\n }\n\n parent.children.splice(index, endIndex - index + 1, detailsNode)\n })\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport {existsSync} from \"node:fs\"\nimport {join, resolve} from \"node:path\"\n\nimport {ConfigLoader} from \"../docs-plugin/internal\"\n\nimport type {CliConfig, WebUiKnowledgeConfig} from \"./types\"\n\nexport function loadKnowledgeConfigFromEnv(\n options: CliConfig,\n): WebUiKnowledgeConfig {\n const knowledgeId = process.env.KNOWLEDGE_ID\n const exclude =\n options.exclude || (process.env.FILE_EXCLUDE_PATTERN ?? \"\").split(\",\")\n const outputPath = options.outputPath || process.env.KNOWLEDGE_OUTPUT_PATH\n const prefix = process.env.PAGE_TITLE_PREFIX\n\n if (!knowledgeId) {\n throw new Error(\"Missing required KNOWLEDGE_ID environment variable\")\n }\n\n if (!outputPath) {\n throw new Error(\"Missing required outputPath\")\n }\n\n const configLoader = new ConfigLoader({})\n const resolvedConfig = configLoader.loadConfig()\n\n const routeDir = join(\n resolvedConfig.appDirectory,\n resolvedConfig.pageDirectory,\n )\n\n if (!existsSync(resolve(routeDir))) {\n throw new Error(`Route directory ${routeDir} does not exist`)\n }\n\n return {\n ...options,\n baseUrl: options.baseUrl || process.env.DOCS_SITE_BASE_URL,\n docPropsPath: resolvedConfig.typeDocProps,\n exclude,\n knowledgeId,\n outputPath,\n pageTitlePrefix: prefix,\n routeDir,\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport {program} from \"@commander-js/extra-typings\"\nimport {createHash} from \"node:crypto\"\nimport {\n access,\n mkdir,\n readdir,\n readFile,\n stat,\n writeFile,\n} from \"node:fs/promises\"\nimport {resolve} from \"node:path\"\nimport {setTimeout} from \"node:timers/promises\"\nimport ora from \"ora\"\n\nimport {\n getConfigFromEnv,\n KnowledgeApi,\n loadEnv,\n type SharedConfig,\n} from \"./common\"\n\ninterface Config extends SharedConfig {\n force: boolean\n knowledgeFilePath: string\n}\n\n/**\n * Calculates the MD5 checksum of a file.\n */\nfunction calculateFileHash(fileData: string) {\n const normalized = fileData\n .normalize(\"NFC\") // Normalize Unicode to canonical form\n .replace(/\\r\\n/g, \"\\n\")\n .replace(/\\r/g, \"\\n\")\n .replace(/\\n+$/, \"\") // Remove trailing newline\n return createHash(\"sha256\").update(normalized).digest(\"hex\")\n}\n\nclass Uploader {\n private config: Config\n readonly api: KnowledgeApi\n\n constructor(config: Config) {\n this.config = config\n this.api = new KnowledgeApi(config)\n }\n\n get headers() {\n return {\n Authorization: `Bearer ${this.config.webUiKey}`,\n }\n }\n\n private async uploadDirectory() {\n const fileNames = await readdir(this.config.knowledgeFilePath)\n const files = await Promise.all(\n fileNames.map(async (name) => ({\n contents: await readFile(\n resolve(this.config.knowledgeFilePath, name),\n \"utf-8\",\n ),\n name,\n })),\n )\n const skippedFiles: string[] = []\n let successCount = 0\n let failureCount = 0\n // fill cache\n await this.api.listKnowledgeFiles()\n\n for (const file of files) {\n let result = await this.uploadFile(file.name, file.contents)\n while (!result.success && result.count && result.count < 5) {\n console.debug(\"Failed to upload, retrying with count: \", result.count)\n await setTimeout(100)\n result = await this.uploadFile(file.name, file.contents, result.count)\n }\n if (result.skipped) {\n skippedFiles.push(file.name)\n }\n if (result.success) {\n successCount++\n } else {\n failureCount++\n }\n }\n\n if (skippedFiles.length > 0) {\n console.debug(\n `Skipped uploading ${skippedFiles.length} files because their contents did not change`,\n )\n }\n const uploadCount = successCount - skippedFiles.length\n if (uploadCount) {\n console.debug(`Successfully uploaded ${uploadCount} files`)\n }\n if (failureCount > 0) {\n console.debug(`Failed to upload ${failureCount} files`)\n }\n }\n\n private async uploadFile(\n name: string,\n contents: string,\n count = 0,\n ): Promise<{\n count?: number\n skipped?: boolean\n success: boolean\n }> {\n const knowledge = await this.api.listKnowledgeFiles()\n const knowledgeFile = (knowledge.files ?? []).find(\n (f) => f.meta.name === name,\n )\n\n if (knowledgeFile) {\n console.debug(\"Found existing file:\", knowledgeFile?.meta.name)\n\n const data = await this.api.downloadFile(knowledgeFile.id)\n\n if (!this.config.force && data) {\n if (calculateFileHash(data) === calculateFileHash(contents)) {\n return {skipped: true, success: true}\n }\n\n await mkdir(resolve(process.cwd(), `./temp/diff`), {\n recursive: true,\n }).catch()\n await writeFile(\n resolve(process.cwd(), `./temp/diff/${name}-current.md`),\n contents,\n \"utf-8\",\n )\n await writeFile(\n resolve(process.cwd(), `./temp/diff/${name}-owui.md`),\n data,\n \"utf-8\",\n )\n\n const dataLines = data.split(\"\\n\")\n const contentLines = contents.split(\"\\n\")\n\n if (dataLines.length === contentLines.length) {\n const allLinesMatch = dataLines.every(\n (line, i) => line === contentLines[i],\n )\n if (allLinesMatch) {\n return {skipped: true, success: true}\n }\n }\n }\n }\n\n const fileBuffer = await readFile(\n resolve(this.config.knowledgeFilePath, name),\n )\n\n if (knowledgeFile) {\n await this.api.removeKnowledgeFile(knowledgeFile.id)\n console.log(`Removed existing file: ${name}`)\n }\n\n const spinner = ora(`Uploading ${name}`).start()\n\n const uploadResponse = await this.api.uploadFile(fileBuffer, name)\n\n if (!uploadResponse.id || !uploadResponse.filename) {\n spinner.fail(`Error uploading ${name}, exiting`)\n console.debug(uploadResponse)\n return {success: false}\n }\n\n // give the upload time to register on the backend\n await setTimeout(500)\n\n spinner.text = `Associating ${name} with knowledge base`\n\n const addResponse = await this.api.associateFile(uploadResponse.id)\n\n if (addResponse.name) {\n spinner.succeed(`${name} associated with knowledge base`)\n return {success: true}\n } else {\n spinner.fail(`Failed to associate ${name} with knowledge base`)\n console.debug(addResponse)\n return {count: count + 1, success: false}\n }\n }\n\n async uploadKnowledge() {\n const resolvedPath = resolve(this.config.knowledgeFilePath)\n if (\n !(await access(resolvedPath)\n .then(() => true)\n .catch(() => false))\n ) {\n throw new Error(`File or folder not found at ${resolvedPath}`)\n }\n const stats = await stat(resolvedPath)\n if (stats.isDirectory()) {\n return this.uploadDirectory()\n } else {\n // TODO: add\n }\n }\n}\n\nexport function addUploadKnowledgeCommand() {\n program\n .name(\"upload-knowledge\")\n .description(\"Upload files to OpenWebUI knowledge base\")\n .command(\"upload-knowledge\")\n .option(\"-p, --path <path>\", \"Path to file or folder relative to script\")\n .option(\n \"--force\",\n \"force upload files, even if their contents have not changed\",\n )\n .action(async (options) => {\n loadEnv()\n\n const sharedConfig = getConfigFromEnv()\n\n const knowledgeFilePath =\n options.path || process.env.KNOWLEDGE_OUTPUT_PATH\n\n if (!knowledgeFilePath) {\n throw new Error(\n \"KNOWLEDGE_FILE_PATH must be set or provided as the --path option\",\n )\n }\n\n const uploader = new Uploader({\n ...sharedConfig,\n force: options.force || false,\n knowledgeFilePath,\n })\n\n return uploader.uploadKnowledge()\n })\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport {program} from \"@commander-js/extra-typings\"\nimport {glob} from \"glob\"\nimport {uniqBy} from \"lodash-es\"\nimport {writeFile} from \"node:fs/promises\"\nimport {resolve} from \"node:path\"\n\nimport {dedent} from \"@qualcomm-ui/utils/dedent\"\n\nimport {extractPageId, isDemoFile} from \"./demo-plugin-utils\"\n\ninterface DemoPage {\n pageId: string\n routePath: string\n}\n\nexport interface DemoScanConfig {\n /**\n * @default \"src/routes/**\\/demos/*.tsx\"\n */\n demoPattern?: string\n\n /**\n * The directory where the routes are located. Must be relative to the project\n * root. The demoPattern should start with this directory:\n *\n * @example\n * ```js\n * {\n * demoPattern = \"src/routes/**\\/demos/*.tsx\",\n * routesDir = \"src/routes\",\n * }\n * ```\n */\n routesDir?: string\n}\n\nasync function scanForDemoPages({\n demoPattern = \"src/routes/**/demos/*.tsx\",\n routesDir = \"src/routes\",\n}: DemoScanConfig): Promise<DemoPage[]> {\n const demoFiles = (await glob(demoPattern)).filter((file) => isDemoFile(file))\n\n return uniqBy(\n demoFiles.map((file) => ({\n pageId: extractPageId(file, routesDir),\n routePath: file\n .replace(routesDir, \"\")\n .replace(/\\/demos\\/.*\\.tsx$/, \"\")\n .replace(/\\+/g, \"\"),\n })),\n (page) => page.pageId,\n )\n}\n\nfunction generateLazyDemoLoader(demoPages: DemoPage[]): string {\n const imports = demoPages\n .map(({pageId, routePath}) => {\n return ` \"${routePath}\": () =>\\n import(\"virtual:qui-demo-scope/page:${pageId}\")`\n })\n .sort()\n .join(\",\\n\")\n\n return dedent`\n /* eslint-disable */\n\n // This file is generated automatically. Don't edit it directly.\n\n import type {ReactDemoWithScope} from \"@qualcomm-ui/mdx-common\"\n\n export const lazyDemos: Record<\n string,\n () => Promise<{getDemo(name: string): ReactDemoWithScope | undefined}>\n > = {\n ${imports},\n }\n\n`\n}\n\nasync function generateLazyDemoMap(options: {\n output: string\n routesDir: string\n}) {\n const routesDir = options.routesDir\n const outputPath = resolve(options.output)\n\n console.log(`Scanning for demo pages in: ${routesDir}`)\n\n const demoPages = await scanForDemoPages({routesDir})\n\n console.log(`Found ${demoPages.length} pages with demos`)\n\n const content = generateLazyDemoLoader(demoPages)\n\n await writeFile(outputPath, content, \"utf-8\")\n\n console.log(`\\nGenerated lazy demo loader at: ${outputPath}`)\n}\n\nexport function addGenerateLazyDemoMapCommand() {\n program\n .command(\"generate-lazy-demo-map\")\n .description(\"Scan for pages with demos and generate lazy demo loader\")\n .requiredOption(\n \"-r, --routes-dir <path>\",\n \"Path to the routes directory (e.g., src/routes)\",\n )\n .requiredOption(\n \"-o, --output <path>\",\n \"Output path for the lazy demo loader file\",\n )\n .action(async (options) => {\n try {\n await generateLazyDemoMap(options)\n } catch (error) {\n console.error(\n \"Error:\",\n error instanceof Error ? error.message : String(error),\n )\n process.exit(1)\n }\n })\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport chalk from \"chalk\"\nimport {createHash} from \"node:crypto\"\nimport {existsSync, readFileSync} from \"node:fs\"\nimport {readFile} from \"node:fs/promises\"\nimport {dirname, join, relative, resolve, sep} from \"node:path\"\nimport * as ts from \"typescript\"\n\nimport {pascalCase} from \"@qualcomm-ui/utils/change-case\"\n\nimport {LOG_PREFIX, NODE_BUILTINS, REACT_IMPORTS} from \"./demo-plugin-constants\"\n\ninterface PathAlias {\n pattern: RegExp\n replacement: string\n}\n\nexport interface ImportSpecifier {\n source: string\n specifiers: Array<{\n imported: string\n local: string\n }>\n type: \"thirdParty\"\n}\n\nexport interface RelativeImport {\n resolvedPath: string\n source: string\n specifiers: Array<{\n imported: string\n local: string\n }>\n type: \"relative\"\n}\n\n/**\n * Demo names are created using the PascalCase format of the file name without the\n * extension.\n */\nexport function createDemoName(filePath: string): string {\n const separatorChar = filePath.includes(\"/\") ? \"/\" : \"\\\\\"\n const fileName = filePath.substring(\n filePath.lastIndexOf(separatorChar),\n filePath.lastIndexOf(\".\"),\n )\n if (!fileName) {\n throw new Error(`Failed to create demo name for ${filePath}`)\n }\n return pascalCase(fileName)\n}\n\nexport async function extractFileImports(filePath: string): Promise<{\n relativeImports: RelativeImport[]\n thirdPartyImports: ImportSpecifier[]\n} | null> {\n try {\n const content = await readFile(filePath, \"utf-8\")\n return extractImports(content, filePath)\n } catch (error) {\n console.log(\n `${chalk.magenta.bold(LOG_PREFIX)} ${chalk.yellowBright(\"Failed to parse\")} ${chalk.blueBright.bold(filePath)}:`,\n error,\n )\n return null\n }\n}\n\nfunction mergeImports(\n importMap: Map<string, Set<{imported: string; local: string}>>,\n imports: ImportSpecifier[],\n) {\n for (const {source, specifiers} of imports) {\n if (isNodeBuiltin(source)) {\n continue\n }\n let sourceSpecifiers = importMap.get(source)\n if (!sourceSpecifiers) {\n sourceSpecifiers = new Set()\n importMap.set(source, sourceSpecifiers)\n }\n for (const spec of specifiers) {\n sourceSpecifiers.add(spec)\n }\n }\n}\n\nfunction extractImports(\n code: string,\n fileName: string,\n): {\n relativeImports: RelativeImport[]\n thirdPartyImports: ImportSpecifier[]\n} {\n const sourceFile = ts.createSourceFile(\n fileName,\n code,\n ts.ScriptTarget.Latest,\n true,\n getScriptKind(fileName),\n )\n const thirdPartyImports: ImportSpecifier[] = []\n const relativeImports: RelativeImport[] = []\n\n function visit(node: ts.Node) {\n if (ts.isImportDeclaration(node)) {\n const importSpec = parseImportDeclaration(node, fileName)\n if (importSpec) {\n if (importSpec.type === \"relative\") {\n relativeImports.push(importSpec)\n } else {\n thirdPartyImports.push(importSpec)\n }\n }\n }\n ts.forEachChild(node, visit)\n }\n\n visit(sourceFile)\n return {relativeImports, thirdPartyImports}\n}\n\nexport function getScriptKind(fileName: string): ts.ScriptKind {\n return fileName.endsWith(\".tsx\") || fileName.endsWith(\".jsx\")\n ? ts.ScriptKind.TSX\n : ts.ScriptKind.TS\n}\n\nfunction parseImportDeclaration(\n node: ts.ImportDeclaration,\n fileName: string,\n): ImportSpecifier | RelativeImport | null {\n const moduleSpecifier = node.moduleSpecifier\n if (!ts.isStringLiteral(moduleSpecifier)) {\n return null\n }\n\n const source = moduleSpecifier.text\n if (node.importClause?.isTypeOnly) {\n return null\n }\n\n const specifiers = extractSpecifiers(node.importClause)\n if (specifiers.length === 0) {\n return null\n }\n\n if (isRelativeImport(source)) {\n const resolvedPath = resolveRelativeImport(source, fileName)\n return {\n resolvedPath,\n source,\n specifiers,\n type: \"relative\",\n }\n }\n\n if (isNodeBuiltin(source)) {\n return null\n }\n\n const pathAliases = loadTsConfigPaths(fileName)\n if (isPathAliasImport(source, pathAliases)) {\n const resolvedPath = resolvePathAlias(source, pathAliases)\n if (resolvedPath) {\n return {\n resolvedPath,\n source,\n specifiers,\n type: \"relative\",\n }\n }\n }\n\n return {\n source,\n specifiers,\n type: \"thirdParty\",\n }\n}\n\nfunction extractSpecifiers(\n importClause: ts.ImportClause | undefined,\n): Array<{imported: string; local: string}> {\n if (!importClause) {\n return []\n }\n\n const specifiers: Array<{imported: string; local: string}> = []\n\n if (importClause.name) {\n specifiers.push({imported: \"default\", local: \"default\"})\n }\n\n if (importClause.namedBindings) {\n if (ts.isNamespaceImport(importClause.namedBindings)) {\n specifiers.push({imported: \"*\", local: \"*\"})\n } else if (ts.isNamedImports(importClause.namedBindings)) {\n importClause.namedBindings.elements.forEach((element) => {\n if (!element.isTypeOnly) {\n const imported = element.propertyName\n ? element.propertyName.text\n : element.name.text\n const local = element.name.text\n specifiers.push({imported, local})\n }\n })\n }\n }\n\n return specifiers\n}\n\nfunction resolveRelativeImport(source: string, fromFile: string): string {\n const fromDir = dirname(fromFile)\n const resolved = resolve(fromDir, source)\n\n const extensions = [\".ts\", \".tsx\", \".js\", \".jsx\"]\n for (const ext of extensions) {\n const withExt = resolved + ext\n if (existsSync(withExt)) {\n return withExt\n }\n }\n\n for (const ext of extensions) {\n const indexFile = join(resolved, `index${ext}`)\n if (existsSync(indexFile)) {\n return indexFile\n }\n }\n\n return resolved\n}\n\nexport async function extractAllImports(files: string[]): Promise<{\n importMap: Map<string, Set<{imported: string; local: string}>>\n relativeImports: RelativeImport[]\n}> {\n const importMap = new Map<string, Set<{imported: string; local: string}>>()\n const relativeImports: RelativeImport[] = []\n\n for (const filePath of files) {\n const result = await extractFileImports(filePath)\n if (result) {\n mergeImports(importMap, result.thirdPartyImports)\n relativeImports.push(...result.relativeImports)\n }\n }\n\n return {importMap, relativeImports}\n}\n\nfunction isRelativeImport(source: string): boolean {\n return source.startsWith(\"./\") || source.startsWith(\"../\")\n}\n\nfunction isNodeBuiltin(source: string): boolean {\n return source.startsWith(\"node:\") || NODE_BUILTINS.includes(source)\n}\n\nfunction loadTsConfigPaths(fromFile: string): PathAlias[] {\n let currentDir = dirname(fromFile)\n const pathAliases: PathAlias[] = []\n\n while (currentDir !== dirname(currentDir)) {\n const tsconfigPath = join(currentDir, \"tsconfig.json\")\n if (existsSync(tsconfigPath)) {\n try {\n const configContent = ts.sys.readFile(tsconfigPath)\n if (!configContent) {\n currentDir = dirname(currentDir)\n continue\n }\n\n const parseResult = ts.parseConfigFileTextToJson(\n tsconfigPath,\n configContent,\n )\n if (parseResult.error) {\n currentDir = dirname(currentDir)\n continue\n }\n\n const paths = parseResult.config?.compilerOptions?.paths\n const baseUrl = parseResult.config?.compilerOptions?.baseUrl || \"./\"\n const resolvedBaseUrl = resolve(currentDir, baseUrl)\n\n if (paths) {\n for (const [alias, targets] of Object.entries(paths)) {\n if (Array.isArray(targets) && targets.length > 0) {\n const target = targets[0]\n const pattern = new RegExp(\n `^${alias\n .replace(\"*\", \"(.*)\")\n .replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\")\n .replace(\"\\\\(\\\\*\\\\)\", \"(.*)\")}$`,\n )\n const replacement = resolve(\n resolvedBaseUrl,\n target.replace(\"*\", \"$1\"),\n )\n pathAliases.push({pattern, replacement})\n }\n }\n }\n\n const extendsPath = parseResult.config?.extends\n if (extendsPath) {\n const resolvedExtends = resolve(currentDir, extendsPath)\n const extendedAliases = loadTsConfigPathsFromFile(resolvedExtends)\n pathAliases.push(...extendedAliases)\n }\n\n return pathAliases\n } catch (error) {\n currentDir = dirname(currentDir)\n continue\n }\n }\n currentDir = dirname(currentDir)\n }\n\n return pathAliases\n}\n\nfunction loadTsConfigPathsFromFile(tsconfigPath: string): PathAlias[] {\n const pathAliases: PathAlias[] = []\n const configDir = dirname(tsconfigPath)\n\n try {\n const configContent = ts.sys.readFile(tsconfigPath)\n if (!configContent) {\n return pathAliases\n }\n\n const parseResult = ts.parseConfigFileTextToJson(\n tsconfigPath,\n configContent,\n )\n if (parseResult.error) {\n return pathAliases\n }\n\n const paths = parseResult.config?.compilerOptions?.paths\n const baseUrl = parseResult.config?.compilerOptions?.baseUrl || \"./\"\n const resolvedBaseUrl = resolve(configDir, baseUrl)\n\n if (paths) {\n for (const [alias, targets] of Object.entries(paths)) {\n if (Array.isArray(targets) && targets.length > 0) {\n const target = targets[0]\n const pattern = new RegExp(\n `^${alias\n .replace(\"*\", \"(.*)\")\n .replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\")\n .replace(\"\\\\(\\\\*\\\\)\", \"(.*)\")}$`,\n )\n const replacement = resolve(\n resolvedBaseUrl,\n target.replace(\"*\", \"$1\"),\n )\n pathAliases.push({pattern, replacement})\n }\n }\n }\n\n const extendsPath = parseResult.config?.extends\n if (extendsPath) {\n let resolvedExtends = resolve(configDir, extendsPath)\n if (!resolvedExtends.endsWith(\".json\")) {\n resolvedExtends += \".json\"\n }\n if (existsSync(resolvedExtends)) {\n const extendedAliases = loadTsConfigPathsFromFile(resolvedExtends)\n pathAliases.push(...extendedAliases)\n }\n }\n } catch (error) {\n return pathAliases\n }\n\n return pathAliases\n}\n\nfunction isPathAliasImport(source: string, pathAliases: PathAlias[]): boolean {\n return pathAliases.some((alias) => alias.pattern.test(source))\n}\n\nfunction resolvePathAlias(\n source: string,\n pathAliases: PathAlias[],\n): string | null {\n for (const alias of pathAliases) {\n if (alias.pattern.test(source)) {\n const resolvedPath = source.replace(alias.pattern, alias.replacement)\n const extensions = [\".ts\", \".tsx\", \".js\", \".jsx\"]\n\n for (const ext of extensions) {\n const withExt = resolvedPath + ext\n if (existsSync(withExt)) {\n return withExt\n }\n }\n\n for (const ext of extensions) {\n const indexFile = join(resolvedPath, `index${ext}`)\n if (existsSync(indexFile)) {\n return indexFile\n }\n }\n\n return resolvedPath\n }\n }\n return null\n}\n\nexport function sanitizeSourceName(source: string): string {\n return source\n .replace(/@/g, \"at_\")\n .replace(/\\//g, \"_\")\n .replace(/[^a-zA-Z0-9_]/g, \"_\")\n .replace(/_+/g, \"_\")\n .replace(/^_|_$/g, \"\")\n}\n\nexport function sanitizeIdentifier(str: string): string {\n return str.replace(/[^a-zA-Z0-9]/g, \"_\")\n}\n\nexport function createUniqueModuleName(source: string): string {\n const hash = createHash(\"sha256\").update(source).digest(\"hex\").substring(0, 8)\n const baseName =\n source\n .split(\"/\")\n .pop()\n ?.replace(/[^a-zA-Z0-9]/g, \"_\")\n ?.replace(/^_+|_+$/g, \"\")\n ?.replace(/^(\\d)/, \"_$1\") || \"module\"\n\n return `mod_${baseName}_${hash}`\n}\n\nexport function addReactImports(imports: string[], scopeEntries: string[]) {\n imports.push(`import React from \"react\"`)\n imports.push(`import {\n ${REACT_IMPORTS.join(\", \")}\n } from \"react\"`)\n scopeEntries.push(\"React\", ...REACT_IMPORTS)\n}\n\nexport function addThirdPartyImports(\n importMap: Map<string, Set<{imported: string; local: string}>>,\n imports: string[],\n scopeEntries: string[],\n) {\n const sortedImports = Array.from(importMap.entries()).sort(([a], [b]) =>\n a.localeCompare(b),\n )\n const usedNames = new Set([\"React\", ...REACT_IMPORTS])\n\n for (const [source, specifiers] of sortedImports) {\n const moduleName = createUniqueModuleName(source)\n imports.push(`import * as ${moduleName} from \"${source}\"`)\n addModuleToScope(source, specifiers, moduleName, scopeEntries, usedNames)\n }\n}\n\nexport function addThirdPartyImportsNamespaced(\n importMap: Map<string, Set<{imported: string; local: string}>>,\n imports: string[],\n scopeEntries: string[],\n demoName: string,\n) {\n const sortedImports = Array.from(importMap.entries()).sort(([a], [b]) =>\n a.localeCompare(b),\n )\n const usedNames = new Set([\"React\", ...REACT_IMPORTS])\n\n for (const [source, specifiers] of sortedImports) {\n const moduleName = `${sanitizeIdentifier(demoName)}_${createUniqueModuleName(source)}`\n imports.push(`import * as ${moduleName} from \"${source}\"`)\n addModuleToScope(source, specifiers, moduleName, scopeEntries, usedNames)\n }\n}\n\nexport function addRelativeImportsNamespaced(\n relativeImports: RelativeImport[],\n imports: string[],\n scopeEntries: string[],\n demoName: string,\n) {\n const processedPaths = new Set<string>()\n\n for (const {resolvedPath, specifiers} of relativeImports) {\n if (processedPaths.has(resolvedPath)) {\n continue\n }\n processedPaths.add(resolvedPath)\n\n const moduleName = `${sanitizeIdentifier(demoName)}_${createUniqueModuleName(resolvedPath)}`\n imports.push(`import * as ${moduleName} from \"${resolvedPath}\"`)\n\n for (const {imported, local} of specifiers) {\n if (imported === \"default\") {\n scopeEntries.push(`${local}: ${moduleName}.default`)\n } else if (imported === \"*\") {\n scopeEntries.push(`...${moduleName}`)\n } else {\n scopeEntries.push(`${local}: ${moduleName}.${imported}`)\n }\n }\n }\n}\n\nfunction addModuleToScope(\n source: string,\n specifiers: Set<{imported: string; local: string}>,\n moduleName: string,\n scopeEntries: string[],\n usedNames: Set<string>,\n) {\n const specArray = Array.from(specifiers)\n const hasDefault = specArray.some((spec) => spec.imported === \"default\")\n const hasNamespace = specArray.some((spec) => spec.imported === \"*\")\n const namedImports = specArray.filter(\n (spec) => spec.imported !== \"default\" && spec.imported !== \"*\",\n )\n\n if (hasNamespace) {\n scopeEntries.push(`...${moduleName}`)\n return\n }\n\n const sanitizedSource = sanitizeSourceName(source)\n if (hasDefault) {\n scopeEntries.push(`\"${sanitizedSource}__default\": ${moduleName}.default`)\n }\n\n for (const {imported, local} of namedImports) {\n const sanitizedKey = `${sanitizedSource}__${imported}`\n scopeEntries.push(`\"${sanitizedKey}\": ${moduleName}.${imported}`)\n if (!usedNames.has(local)) {\n scopeEntries.push(`${local}: ${moduleName}.${imported}`)\n usedNames.add(local)\n }\n }\n}\n\nexport function extractPageId(filePath: string, routesDir: string): string {\n const relativePath = relative(routesDir, filePath)\n const pathParts = relativePath.split(sep)\n if (pathParts.includes(\"demos\")) {\n const demosIndex = pathParts.indexOf(\"demos\")\n return pathParts.slice(0, demosIndex).join(sep)\n }\n return dirname(relativePath)\n}\n\nexport function isCssAsset(filePath: string) {\n return filePath.endsWith(\".css\")\n}\n\nexport function isDemoFile(filePath: string): boolean {\n try {\n return (\n filePath.includes(\"/demos/\") &&\n filePath.endsWith(\".tsx\") &&\n // could also be in a comment, probably need to use TS parser\n readFileSync(filePath, \"utf-8\").includes(\"export default\")\n )\n } catch (error) {\n return false\n }\n}\n\nexport function createEmptyScopeModule(): string {\n return \"export const createDemoScope = () => ({})\"\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport {program} from \"@commander-js/extra-typings\"\n\nimport {addDownloadKnowledgeCommand} from \"./open-web-ui-knowledge/download-knowledge\"\nimport {addGenerateKnowledgeCommand} from \"./open-web-ui-knowledge/generate-knowledge\"\nimport {addUploadKnowledgeCommand} from \"./open-web-ui-knowledge/upload-knowledge\"\nimport {addGenerateLazyDemoMapCommand} from \"./react-demo-plugin/generate-lazy-demo-map\"\n\nfunction setupCli() {\n // global options\n program.option(\"--env <envFile>\", \"relative path to the env file to use\")\n\n addGenerateKnowledgeCommand()\n addUploadKnowledgeCommand()\n addDownloadKnowledgeCommand()\n addGenerateLazyDemoMapCommand()\n\n program.parse()\n}\n\nsetupCli()\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAGA,QAAMA,kBAAN,cAA6B,MAAM;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,MAOjC,YAAY,UAAU,MAAM,SAAS;AACnC,cAAM,OAAO;AAEb,cAAM,kBAAkB,MAAM,KAAK,WAAW;AAC9C,aAAK,OAAO,KAAK,YAAY;AAC7B,aAAK,OAAO;AACZ,aAAK,WAAW;AAChB,aAAK,cAAc;AAAA,MACrB;AAAA,IACF;AAKA,QAAMC,wBAAN,cAAmCD,gBAAe;AAAA;AAAA;AAAA;AAAA;AAAA,MAKhD,YAAY,SAAS;AACnB,cAAM,GAAG,6BAA6B,OAAO;AAE7C,cAAM,kBAAkB,MAAM,KAAK,WAAW;AAC9C,aAAK,OAAO,KAAK,YAAY;AAAA,MAC/B;AAAA,IACF;AAEA,YAAQ,iBAAiBA;AACzB,YAAQ,uBAAuBC;AAAA;AAAA;;;ACtC/B;AAAA;AAAA;AAAA,QAAM,EAAE,sBAAAC,sBAAqB,IAAI;AAEjC,QAAMC,YAAN,MAAe;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,MAUb,YAAY,MAAM,aAAa;AAC7B,aAAK,cAAc,eAAe;AAClC,aAAK,WAAW;AAChB,aAAK,WAAW;AAChB,aAAK,eAAe;AACpB,aAAK,0BAA0B;AAC/B,aAAK,aAAa;AAElB,gBAAQ,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ACF,CAAC;AACL;;;AEnHA,SAAS,WAAW;AAElB,UAAQ,OAAO,mBAAmB,sCAAsC;AAExE,8BAA4B;AAC5B,4BAA0B;AAC1B,8BAA4B;AAC5B,gCAA8B;AAE9B,UAAQ,MAAM;AAChB;AAEA,SAAS;",
6
- "names": ["CommanderError", "InvalidArgumentError", "InvalidArgumentError", "Argument", "Help", "cmd", "heading", "InvalidArgumentError", "Option", "heading", "str", "process", "Argument", "CommanderError", "Help", "Option", "Command", "config", "defined", "option", "heading", "path", "Argument", "Command", "CommanderError", "InvalidArgumentError", "Help", "Option", "extraTypingsCommander", "config", "mkdir", "writeFile", "join", "resolve", "remarkFrontmatter", "remarkParse", "remarkParseFrontmatter", "remarkStringify", "unified", "chalk", "readFileSync", "resolve", "z", "z", "z", "z", "config", "chalk", "entry", "propTypes", "heading", "remarkParse", "remarkStringify", "unified", "unified", "remarkParse", "remarkStringify", "remarkMdx", "remarkParse", "unified", "visit", "visit", "item", "remove", "heading", "unified", "remarkMdx", "remarkParse", "capitalCase", "segment", "capitalCase", "state", "routeSegment", "config", "chalk", "readFileSync", "config", "resolve", "chalk", "remarkFrontmatter", "remarkGfm", "headingRank", "visit", "toString", "visit", "emptyOptions", "visit", "join", "resolve", "join", "resolve", "resolve", "join", "unified", "remarkParse", "remarkFrontmatter", "remarkParseFrontmatter", "remarkStringify", "mkdir", "writeFile", "createHash", "access", "mkdir", "readdir", "readFile", "stat", "writeFile", "resolve", "setTimeout", "createHash", "config", "readdir", "readFile", "resolve", "setTimeout", "mkdir", "writeFile", "access", "stat", "glob", "writeFile", "resolve", "chalk", "existsSync", "readFileSync", "dirname", "join", "resolve", "dirname", "readFileSync", "glob", "resolve", "writeFile"]
3
+ "sources": ["../../../../node_modules/.pnpm/commander@14.0.2/node_modules/commander/lib/error.js", "../../../../node_modules/.pnpm/commander@14.0.2/node_modules/commander/lib/argument.js", "../../../../node_modules/.pnpm/commander@14.0.2/node_modules/commander/lib/help.js", "../../../../node_modules/.pnpm/commander@14.0.2/node_modules/commander/lib/option.js", "../../../../node_modules/.pnpm/commander@14.0.2/node_modules/commander/lib/suggestSimilar.js", "../../../../node_modules/.pnpm/commander@14.0.2/node_modules/commander/lib/command.js", "../../../../node_modules/.pnpm/commander@14.0.2/node_modules/commander/index.js", "../../../../node_modules/.pnpm/@commander-js+extra-typings@14.0.0_commander@14.0.2/node_modules/@commander-js/extra-typings/index.js", "../../../../node_modules/.pnpm/@commander-js+extra-typings@14.0.0_commander@14.0.2/node_modules/@commander-js/extra-typings/esm.mjs", "../src/docs-plugin/generate-page-map.ts", "../src/docs-plugin/internal/config-loader.ts", "../src/docs-plugin/internal/config-schema.ts", "../src/docs-plugin/internal/zod.ts", "../src/docs-plugin/internal/utils.ts", "../src/docs-plugin/internal/search-indexer.ts", "../src/docs-plugin/internal/services/doc-props/doc-props-indexer.ts", "../src/docs-plugin/internal/services/markdown/markdown-file-reader.ts", "../src/docs-plugin/internal/services/markdown/markdown-indexer.ts", "../src/docs-plugin/rehype/rehype-slug.ts", "../src/docs-plugin/remark/remark-alerts.ts", "../src/docs-plugin/internal/services/markdown/remark-remove-code-blocks.ts", "../src/docs-plugin/internal/services/markdown/remark-remove-jsx.ts", "../src/docs-plugin/internal/services/nav-builder/get-route-meta.ts", "../src/docs-plugin/internal/services/nav-builder/nav-builder.ts", "../src/docs-plugin/internal/services/nav-builder/page-map.ts", "../src/docs-plugin/internal/transform-route-meta-array.ts", "../src/open-web-ui-knowledge/download-knowledge.ts", "../src/open-web-ui-knowledge/common.ts", "../src/open-web-ui-knowledge/generate-knowledge.ts", "../src/docs-plugin/docs-plugin.ts", "../src/docs-plugin/mdx-plugins.ts", "../src/exports.ts", "../src/docs-plugin/rehype/rehype-sectionize.ts", "../src/docs-plugin/remark/remark-code-tabs.ts", "../src/docs-plugin/remark/remark-self-link-headings.ts", "../src/docs-plugin/remark/remark-spoilers.ts", "../src/open-web-ui-knowledge/load-config-from-env.ts", "../src/open-web-ui-knowledge/upload-knowledge.ts", "../src/react-demo-plugin/generate-lazy-demo-map.ts", "../src/react-demo-plugin/demo-plugin-utils.ts", "../src/cli.ts"],
4
+ "sourcesContent": ["/**\n * CommanderError class\n */\nclass CommanderError extends Error {\n /**\n * Constructs the CommanderError class\n * @param {number} exitCode suggested exit code which could be used with process.exit\n * @param {string} code an id string representing the error\n * @param {string} message human-readable description of the error\n */\n constructor(exitCode, code, message) {\n super(message);\n // properly capture stack trace in Node.js\n Error.captureStackTrace(this, this.constructor);\n this.name = this.constructor.name;\n this.code = code;\n this.exitCode = exitCode;\n this.nestedError = undefined;\n }\n}\n\n/**\n * InvalidArgumentError class\n */\nclass InvalidArgumentError extends CommanderError {\n /**\n * Constructs the InvalidArgumentError class\n * @param {string} [message] explanation of why argument is invalid\n */\n constructor(message) {\n super(1, 'commander.invalidArgument', message);\n // properly capture stack trace in Node.js\n Error.captureStackTrace(this, this.constructor);\n this.name = this.constructor.name;\n }\n}\n\nexports.CommanderError = CommanderError;\nexports.InvalidArgumentError = InvalidArgumentError;\n", "const { InvalidArgumentError } = require('./error.js');\n\nclass Argument {\n /**\n * Initialize a new command argument with the given name and description.\n * The default is that the argument is required, and you can explicitly\n * indicate this with <> around the name. Put [] around the name for an optional argument.\n *\n * @param {string} name\n * @param {string} [description]\n */\n\n constructor(name, description) {\n this.description = description || '';\n this.variadic = false;\n this.parseArg = undefined;\n this.defaultValue = undefined;\n this.defaultValueDescription = undefined;\n this.argChoices = undefined;\n\n switch (name[0]) {\n case '<': // e.g. <required>\n this.required = true;\n this._name = name.slice(1, -1);\n break;\n case '[': // e.g. [optional]\n this.required = false;\n this._name = name.slice(1, -1);\n break;\n default:\n this.required = true;\n this._name = name;\n break;\n }\n\n if (this._name.endsWith('...')) {\n this.variadic = true;\n this._name = this._name.slice(0, -3);\n }\n }\n\n /**\n * Return argument name.\n *\n * @return {string}\n */\n\n name() {\n return this._name;\n }\n\n /**\n * @package\n */\n\n _collectValue(value, previous) {\n if (previous === this.defaultValue || !Array.isArray(previous)) {\n return [value];\n }\n\n previous.push(value);\n return previous;\n }\n\n /**\n * Set the default value, and optionally supply the description to be displayed in the help.\n *\n * @param {*} value\n * @param {string} [description]\n * @return {Argument}\n */\n\n default(value, description) {\n this.defaultValue = value;\n this.defaultValueDescription = description;\n return this;\n }\n\n /**\n * Set the custom handler for processing CLI command arguments into argument values.\n *\n * @param {Function} [fn]\n * @return {Argument}\n */\n\n argParser(fn) {\n this.parseArg = fn;\n return this;\n }\n\n /**\n * Only allow argument value to be one of choices.\n *\n * @param {string[]} values\n * @return {Argument}\n */\n\n choices(values) {\n this.argChoices = values.slice();\n this.parseArg = (arg, previous) => {\n if (!this.argChoices.includes(arg)) {\n throw new InvalidArgumentError(\n `Allowed choices are ${this.argChoices.join(', ')}.`,\n );\n }\n if (this.variadic) {\n return this._collectValue(arg, previous);\n }\n return arg;\n };\n return this;\n }\n\n /**\n * Make argument required.\n *\n * @returns {Argument}\n */\n argRequired() {\n this.required = true;\n return this;\n }\n\n /**\n * Make argument optional.\n *\n * @returns {Argument}\n */\n argOptional() {\n this.required = false;\n return this;\n }\n}\n\n/**\n * Takes an argument and returns its human readable equivalent for help usage.\n *\n * @param {Argument} arg\n * @return {string}\n * @private\n */\n\nfunction humanReadableArgName(arg) {\n const nameOutput = arg.name() + (arg.variadic === true ? '...' : '');\n\n return arg.required ? '<' + nameOutput + '>' : '[' + nameOutput + ']';\n}\n\nexports.Argument = Argument;\nexports.humanReadableArgName = humanReadableArgName;\n", "const { humanReadableArgName } = require('./argument.js');\n\n/**\n * TypeScript import types for JSDoc, used by Visual Studio Code IntelliSense and `npm run typescript-checkJS`\n * https://www.typescriptlang.org/docs/handbook/jsdoc-supported-types.html#import-types\n * @typedef { import(\"./argument.js\").Argument } Argument\n * @typedef { import(\"./command.js\").Command } Command\n * @typedef { import(\"./option.js\").Option } Option\n */\n\n// Although this is a class, methods are static in style to allow override using subclass or just functions.\nclass Help {\n constructor() {\n this.helpWidth = undefined;\n this.minWidthToWrap = 40;\n this.sortSubcommands = false;\n this.sortOptions = false;\n this.showGlobalOptions = false;\n }\n\n /**\n * prepareContext is called by Commander after applying overrides from `Command.configureHelp()`\n * and just before calling `formatHelp()`.\n *\n * Commander just uses the helpWidth and the rest is provided for optional use by more complex subclasses.\n *\n * @param {{ error?: boolean, helpWidth?: number, outputHasColors?: boolean }} contextOptions\n */\n prepareContext(contextOptions) {\n this.helpWidth = this.helpWidth ?? contextOptions.helpWidth ?? 80;\n }\n\n /**\n * Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.\n *\n * @param {Command} cmd\n * @returns {Command[]}\n */\n\n visibleCommands(cmd) {\n const visibleCommands = cmd.commands.filter((cmd) => !cmd._hidden);\n const helpCommand = cmd._getHelpCommand();\n if (helpCommand && !helpCommand._hidden) {\n visibleCommands.push(helpCommand);\n }\n if (this.sortSubcommands) {\n visibleCommands.sort((a, b) => {\n // @ts-ignore: because overloaded return type\n return a.name().localeCompare(b.name());\n });\n }\n return visibleCommands;\n }\n\n /**\n * Compare options for sort.\n *\n * @param {Option} a\n * @param {Option} b\n * @returns {number}\n */\n compareOptions(a, b) {\n const getSortKey = (option) => {\n // WYSIWYG for order displayed in help. Short used for comparison if present. No special handling for negated.\n return option.short\n ? option.short.replace(/^-/, '')\n : option.long.replace(/^--/, '');\n };\n return getSortKey(a).localeCompare(getSortKey(b));\n }\n\n /**\n * Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.\n *\n * @param {Command} cmd\n * @returns {Option[]}\n */\n\n visibleOptions(cmd) {\n const visibleOptions = cmd.options.filter((option) => !option.hidden);\n // Built-in help option.\n const helpOption = cmd._getHelpOption();\n if (helpOption && !helpOption.hidden) {\n // Automatically hide conflicting flags. Bit dubious but a historical behaviour that is convenient for single-command programs.\n const removeShort = helpOption.short && cmd._findOption(helpOption.short);\n const removeLong = helpOption.long && cmd._findOption(helpOption.long);\n if (!removeShort && !removeLong) {\n visibleOptions.push(helpOption); // no changes needed\n } else if (helpOption.long && !removeLong) {\n visibleOptions.push(\n cmd.createOption(helpOption.long, helpOption.description),\n );\n } else if (helpOption.short && !removeShort) {\n visibleOptions.push(\n cmd.createOption(helpOption.short, helpOption.description),\n );\n }\n }\n if (this.sortOptions) {\n visibleOptions.sort(this.compareOptions);\n }\n return visibleOptions;\n }\n\n /**\n * Get an array of the visible global options. (Not including help.)\n *\n * @param {Command} cmd\n * @returns {Option[]}\n */\n\n visibleGlobalOptions(cmd) {\n if (!this.showGlobalOptions) return [];\n\n const globalOptions = [];\n for (\n let ancestorCmd = cmd.parent;\n ancestorCmd;\n ancestorCmd = ancestorCmd.parent\n ) {\n const visibleOptions = ancestorCmd.options.filter(\n (option) => !option.hidden,\n );\n globalOptions.push(...visibleOptions);\n }\n if (this.sortOptions) {\n globalOptions.sort(this.compareOptions);\n }\n return globalOptions;\n }\n\n /**\n * Get an array of the arguments if any have a description.\n *\n * @param {Command} cmd\n * @returns {Argument[]}\n */\n\n visibleArguments(cmd) {\n // Side effect! Apply the legacy descriptions before the arguments are displayed.\n if (cmd._argsDescription) {\n cmd.registeredArguments.forEach((argument) => {\n argument.description =\n argument.description || cmd._argsDescription[argument.name()] || '';\n });\n }\n\n // If there are any arguments with a description then return all the arguments.\n if (cmd.registeredArguments.find((argument) => argument.description)) {\n return cmd.registeredArguments;\n }\n return [];\n }\n\n /**\n * Get the command term to show in the list of subcommands.\n *\n * @param {Command} cmd\n * @returns {string}\n */\n\n subcommandTerm(cmd) {\n // Legacy. Ignores custom usage string, and nested commands.\n const args = cmd.registeredArguments\n .map((arg) => humanReadableArgName(arg))\n .join(' ');\n return (\n cmd._name +\n (cmd._aliases[0] ? '|' + cmd._aliases[0] : '') +\n (cmd.options.length ? ' [options]' : '') + // simplistic check for non-help option\n (args ? ' ' + args : '')\n );\n }\n\n /**\n * Get the option term to show in the list of options.\n *\n * @param {Option} option\n * @returns {string}\n */\n\n optionTerm(option) {\n return option.flags;\n }\n\n /**\n * Get the argument term to show in the list of arguments.\n *\n * @param {Argument} argument\n * @returns {string}\n */\n\n argumentTerm(argument) {\n return argument.name();\n }\n\n /**\n * Get the longest command term length.\n *\n * @param {Command} cmd\n * @param {Help} helper\n * @returns {number}\n */\n\n longestSubcommandTermLength(cmd, helper) {\n return helper.visibleCommands(cmd).reduce((max, command) => {\n return Math.max(\n max,\n this.displayWidth(\n helper.styleSubcommandTerm(helper.subcommandTerm(command)),\n ),\n );\n }, 0);\n }\n\n /**\n * Get the longest option term length.\n *\n * @param {Command} cmd\n * @param {Help} helper\n * @returns {number}\n */\n\n longestOptionTermLength(cmd, helper) {\n return helper.visibleOptions(cmd).reduce((max, option) => {\n return Math.max(\n max,\n this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))),\n );\n }, 0);\n }\n\n /**\n * Get the longest global option term length.\n *\n * @param {Command} cmd\n * @param {Help} helper\n * @returns {number}\n */\n\n longestGlobalOptionTermLength(cmd, helper) {\n return helper.visibleGlobalOptions(cmd).reduce((max, option) => {\n return Math.max(\n max,\n this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))),\n );\n }, 0);\n }\n\n /**\n * Get the longest argument term length.\n *\n * @param {Command} cmd\n * @param {Help} helper\n * @returns {number}\n */\n\n longestArgumentTermLength(cmd, helper) {\n return helper.visibleArguments(cmd).reduce((max, argument) => {\n return Math.max(\n max,\n this.displayWidth(\n helper.styleArgumentTerm(helper.argumentTerm(argument)),\n ),\n );\n }, 0);\n }\n\n /**\n * Get the command usage to be displayed at the top of the built-in help.\n *\n * @param {Command} cmd\n * @returns {string}\n */\n\n commandUsage(cmd) {\n // Usage\n let cmdName = cmd._name;\n if (cmd._aliases[0]) {\n cmdName = cmdName + '|' + cmd._aliases[0];\n }\n let ancestorCmdNames = '';\n for (\n let ancestorCmd = cmd.parent;\n ancestorCmd;\n ancestorCmd = ancestorCmd.parent\n ) {\n ancestorCmdNames = ancestorCmd.name() + ' ' + ancestorCmdNames;\n }\n return ancestorCmdNames + cmdName + ' ' + cmd.usage();\n }\n\n /**\n * Get the description for the command.\n *\n * @param {Command} cmd\n * @returns {string}\n */\n\n commandDescription(cmd) {\n // @ts-ignore: because overloaded return type\n return cmd.description();\n }\n\n /**\n * Get the subcommand summary to show in the list of subcommands.\n * (Fallback to description for backwards compatibility.)\n *\n * @param {Command} cmd\n * @returns {string}\n */\n\n subcommandDescription(cmd) {\n // @ts-ignore: because overloaded return type\n return cmd.summary() || cmd.description();\n }\n\n /**\n * Get the option description to show in the list of options.\n *\n * @param {Option} option\n * @return {string}\n */\n\n optionDescription(option) {\n const extraInfo = [];\n\n if (option.argChoices) {\n extraInfo.push(\n // use stringify to match the display of the default value\n `choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(', ')}`,\n );\n }\n if (option.defaultValue !== undefined) {\n // default for boolean and negated more for programmer than end user,\n // but show true/false for boolean option as may be for hand-rolled env or config processing.\n const showDefault =\n option.required ||\n option.optional ||\n (option.isBoolean() && typeof option.defaultValue === 'boolean');\n if (showDefault) {\n extraInfo.push(\n `default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`,\n );\n }\n }\n // preset for boolean and negated are more for programmer than end user\n if (option.presetArg !== undefined && option.optional) {\n extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);\n }\n if (option.envVar !== undefined) {\n extraInfo.push(`env: ${option.envVar}`);\n }\n if (extraInfo.length > 0) {\n const extraDescription = `(${extraInfo.join(', ')})`;\n if (option.description) {\n return `${option.description} ${extraDescription}`;\n }\n return extraDescription;\n }\n\n return option.description;\n }\n\n /**\n * Get the argument description to show in the list of arguments.\n *\n * @param {Argument} argument\n * @return {string}\n */\n\n argumentDescription(argument) {\n const extraInfo = [];\n if (argument.argChoices) {\n extraInfo.push(\n // use stringify to match the display of the default value\n `choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(', ')}`,\n );\n }\n if (argument.defaultValue !== undefined) {\n extraInfo.push(\n `default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`,\n );\n }\n if (extraInfo.length > 0) {\n const extraDescription = `(${extraInfo.join(', ')})`;\n if (argument.description) {\n return `${argument.description} ${extraDescription}`;\n }\n return extraDescription;\n }\n return argument.description;\n }\n\n /**\n * Format a list of items, given a heading and an array of formatted items.\n *\n * @param {string} heading\n * @param {string[]} items\n * @param {Help} helper\n * @returns string[]\n */\n formatItemList(heading, items, helper) {\n if (items.length === 0) return [];\n\n return [helper.styleTitle(heading), ...items, ''];\n }\n\n /**\n * Group items by their help group heading.\n *\n * @param {Command[] | Option[]} unsortedItems\n * @param {Command[] | Option[]} visibleItems\n * @param {Function} getGroup\n * @returns {Map<string, Command[] | Option[]>}\n */\n groupItems(unsortedItems, visibleItems, getGroup) {\n const result = new Map();\n // Add groups in order of appearance in unsortedItems.\n unsortedItems.forEach((item) => {\n const group = getGroup(item);\n if (!result.has(group)) result.set(group, []);\n });\n // Add items in order of appearance in visibleItems.\n visibleItems.forEach((item) => {\n const group = getGroup(item);\n if (!result.has(group)) {\n result.set(group, []);\n }\n result.get(group).push(item);\n });\n return result;\n }\n\n /**\n * Generate the built-in help text.\n *\n * @param {Command} cmd\n * @param {Help} helper\n * @returns {string}\n */\n\n formatHelp(cmd, helper) {\n const termWidth = helper.padWidth(cmd, helper);\n const helpWidth = helper.helpWidth ?? 80; // in case prepareContext() was not called\n\n function callFormatItem(term, description) {\n return helper.formatItem(term, termWidth, description, helper);\n }\n\n // Usage\n let output = [\n `${helper.styleTitle('Usage:')} ${helper.styleUsage(helper.commandUsage(cmd))}`,\n '',\n ];\n\n // Description\n const commandDescription = helper.commandDescription(cmd);\n if (commandDescription.length > 0) {\n output = output.concat([\n helper.boxWrap(\n helper.styleCommandDescription(commandDescription),\n helpWidth,\n ),\n '',\n ]);\n }\n\n // Arguments\n const argumentList = helper.visibleArguments(cmd).map((argument) => {\n return callFormatItem(\n helper.styleArgumentTerm(helper.argumentTerm(argument)),\n helper.styleArgumentDescription(helper.argumentDescription(argument)),\n );\n });\n output = output.concat(\n this.formatItemList('Arguments:', argumentList, helper),\n );\n\n // Options\n const optionGroups = this.groupItems(\n cmd.options,\n helper.visibleOptions(cmd),\n (option) => option.helpGroupHeading ?? 'Options:',\n );\n optionGroups.forEach((options, group) => {\n const optionList = options.map((option) => {\n return callFormatItem(\n helper.styleOptionTerm(helper.optionTerm(option)),\n helper.styleOptionDescription(helper.optionDescription(option)),\n );\n });\n output = output.concat(this.formatItemList(group, optionList, helper));\n });\n\n if (helper.showGlobalOptions) {\n const globalOptionList = helper\n .visibleGlobalOptions(cmd)\n .map((option) => {\n return callFormatItem(\n helper.styleOptionTerm(helper.optionTerm(option)),\n helper.styleOptionDescription(helper.optionDescription(option)),\n );\n });\n output = output.concat(\n this.formatItemList('Global Options:', globalOptionList, helper),\n );\n }\n\n // Commands\n const commandGroups = this.groupItems(\n cmd.commands,\n helper.visibleCommands(cmd),\n (sub) => sub.helpGroup() || 'Commands:',\n );\n commandGroups.forEach((commands, group) => {\n const commandList = commands.map((sub) => {\n return callFormatItem(\n helper.styleSubcommandTerm(helper.subcommandTerm(sub)),\n helper.styleSubcommandDescription(helper.subcommandDescription(sub)),\n );\n });\n output = output.concat(this.formatItemList(group, commandList, helper));\n });\n\n return output.join('\\n');\n }\n\n /**\n * Return display width of string, ignoring ANSI escape sequences. Used in padding and wrapping calculations.\n *\n * @param {string} str\n * @returns {number}\n */\n displayWidth(str) {\n return stripColor(str).length;\n }\n\n /**\n * Style the title for displaying in the help. Called with 'Usage:', 'Options:', etc.\n *\n * @param {string} str\n * @returns {string}\n */\n styleTitle(str) {\n return str;\n }\n\n styleUsage(str) {\n // Usage has lots of parts the user might like to color separately! Assume default usage string which is formed like:\n // command subcommand [options] [command] <foo> [bar]\n return str\n .split(' ')\n .map((word) => {\n if (word === '[options]') return this.styleOptionText(word);\n if (word === '[command]') return this.styleSubcommandText(word);\n if (word[0] === '[' || word[0] === '<')\n return this.styleArgumentText(word);\n return this.styleCommandText(word); // Restrict to initial words?\n })\n .join(' ');\n }\n styleCommandDescription(str) {\n return this.styleDescriptionText(str);\n }\n styleOptionDescription(str) {\n return this.styleDescriptionText(str);\n }\n styleSubcommandDescription(str) {\n return this.styleDescriptionText(str);\n }\n styleArgumentDescription(str) {\n return this.styleDescriptionText(str);\n }\n styleDescriptionText(str) {\n return str;\n }\n styleOptionTerm(str) {\n return this.styleOptionText(str);\n }\n styleSubcommandTerm(str) {\n // This is very like usage with lots of parts! Assume default string which is formed like:\n // subcommand [options] <foo> [bar]\n return str\n .split(' ')\n .map((word) => {\n if (word === '[options]') return this.styleOptionText(word);\n if (word[0] === '[' || word[0] === '<')\n return this.styleArgumentText(word);\n return this.styleSubcommandText(word); // Restrict to initial words?\n })\n .join(' ');\n }\n styleArgumentTerm(str) {\n return this.styleArgumentText(str);\n }\n styleOptionText(str) {\n return str;\n }\n styleArgumentText(str) {\n return str;\n }\n styleSubcommandText(str) {\n return str;\n }\n styleCommandText(str) {\n return str;\n }\n\n /**\n * Calculate the pad width from the maximum term length.\n *\n * @param {Command} cmd\n * @param {Help} helper\n * @returns {number}\n */\n\n padWidth(cmd, helper) {\n return Math.max(\n helper.longestOptionTermLength(cmd, helper),\n helper.longestGlobalOptionTermLength(cmd, helper),\n helper.longestSubcommandTermLength(cmd, helper),\n helper.longestArgumentTermLength(cmd, helper),\n );\n }\n\n /**\n * Detect manually wrapped and indented strings by checking for line break followed by whitespace.\n *\n * @param {string} str\n * @returns {boolean}\n */\n preformatted(str) {\n return /\\n[^\\S\\r\\n]/.test(str);\n }\n\n /**\n * Format the \"item\", which consists of a term and description. Pad the term and wrap the description, indenting the following lines.\n *\n * So \"TTT\", 5, \"DDD DDDD DD DDD\" might be formatted for this.helpWidth=17 like so:\n * TTT DDD DDDD\n * DD DDD\n *\n * @param {string} term\n * @param {number} termWidth\n * @param {string} description\n * @param {Help} helper\n * @returns {string}\n */\n formatItem(term, termWidth, description, helper) {\n const itemIndent = 2;\n const itemIndentStr = ' '.repeat(itemIndent);\n if (!description) return itemIndentStr + term;\n\n // Pad the term out to a consistent width, so descriptions are aligned.\n const paddedTerm = term.padEnd(\n termWidth + term.length - helper.displayWidth(term),\n );\n\n // Format the description.\n const spacerWidth = 2; // between term and description\n const helpWidth = this.helpWidth ?? 80; // in case prepareContext() was not called\n const remainingWidth = helpWidth - termWidth - spacerWidth - itemIndent;\n let formattedDescription;\n if (\n remainingWidth < this.minWidthToWrap ||\n helper.preformatted(description)\n ) {\n formattedDescription = description;\n } else {\n const wrappedDescription = helper.boxWrap(description, remainingWidth);\n formattedDescription = wrappedDescription.replace(\n /\\n/g,\n '\\n' + ' '.repeat(termWidth + spacerWidth),\n );\n }\n\n // Construct and overall indent.\n return (\n itemIndentStr +\n paddedTerm +\n ' '.repeat(spacerWidth) +\n formattedDescription.replace(/\\n/g, `\\n${itemIndentStr}`)\n );\n }\n\n /**\n * Wrap a string at whitespace, preserving existing line breaks.\n * Wrapping is skipped if the width is less than `minWidthToWrap`.\n *\n * @param {string} str\n * @param {number} width\n * @returns {string}\n */\n boxWrap(str, width) {\n if (width < this.minWidthToWrap) return str;\n\n const rawLines = str.split(/\\r\\n|\\n/);\n // split up text by whitespace\n const chunkPattern = /[\\s]*[^\\s]+/g;\n const wrappedLines = [];\n rawLines.forEach((line) => {\n const chunks = line.match(chunkPattern);\n if (chunks === null) {\n wrappedLines.push('');\n return;\n }\n\n let sumChunks = [chunks.shift()];\n let sumWidth = this.displayWidth(sumChunks[0]);\n chunks.forEach((chunk) => {\n const visibleWidth = this.displayWidth(chunk);\n // Accumulate chunks while they fit into width.\n if (sumWidth + visibleWidth <= width) {\n sumChunks.push(chunk);\n sumWidth += visibleWidth;\n return;\n }\n wrappedLines.push(sumChunks.join(''));\n\n const nextChunk = chunk.trimStart(); // trim space at line break\n sumChunks = [nextChunk];\n sumWidth = this.displayWidth(nextChunk);\n });\n wrappedLines.push(sumChunks.join(''));\n });\n\n return wrappedLines.join('\\n');\n }\n}\n\n/**\n * Strip style ANSI escape sequences from the string. In particular, SGR (Select Graphic Rendition) codes.\n *\n * @param {string} str\n * @returns {string}\n * @package\n */\n\nfunction stripColor(str) {\n // eslint-disable-next-line no-control-regex\n const sgrPattern = /\\x1b\\[\\d*(;\\d*)*m/g;\n return str.replace(sgrPattern, '');\n}\n\nexports.Help = Help;\nexports.stripColor = stripColor;\n", "const { InvalidArgumentError } = require('./error.js');\n\nclass Option {\n /**\n * Initialize a new `Option` with the given `flags` and `description`.\n *\n * @param {string} flags\n * @param {string} [description]\n */\n\n constructor(flags, description) {\n this.flags = flags;\n this.description = description || '';\n\n this.required = flags.includes('<'); // A value must be supplied when the option is specified.\n this.optional = flags.includes('['); // A value is optional when the option is specified.\n // variadic test ignores <value,...> et al which might be used to describe custom splitting of single argument\n this.variadic = /\\w\\.\\.\\.[>\\]]$/.test(flags); // The option can take multiple values.\n this.mandatory = false; // The option must have a value after parsing, which usually means it must be specified on command line.\n const optionFlags = splitOptionFlags(flags);\n this.short = optionFlags.shortFlag; // May be a short flag, undefined, or even a long flag (if option has two long flags).\n this.long = optionFlags.longFlag;\n this.negate = false;\n if (this.long) {\n this.negate = this.long.startsWith('--no-');\n }\n this.defaultValue = undefined;\n this.defaultValueDescription = undefined;\n this.presetArg = undefined;\n this.envVar = undefined;\n this.parseArg = undefined;\n this.hidden = false;\n this.argChoices = undefined;\n this.conflictsWith = [];\n this.implied = undefined;\n this.helpGroupHeading = undefined; // soft initialised when option added to command\n }\n\n /**\n * Set the default value, and optionally supply the description to be displayed in the help.\n *\n * @param {*} value\n * @param {string} [description]\n * @return {Option}\n */\n\n default(value, description) {\n this.defaultValue = value;\n this.defaultValueDescription = description;\n return this;\n }\n\n /**\n * Preset to use when option used without option-argument, especially optional but also boolean and negated.\n * The custom processing (parseArg) is called.\n *\n * @example\n * new Option('--color').default('GREYSCALE').preset('RGB');\n * new Option('--donate [amount]').preset('20').argParser(parseFloat);\n *\n * @param {*} arg\n * @return {Option}\n */\n\n preset(arg) {\n this.presetArg = arg;\n return this;\n }\n\n /**\n * Add option name(s) that conflict with this option.\n * An error will be displayed if conflicting options are found during parsing.\n *\n * @example\n * new Option('--rgb').conflicts('cmyk');\n * new Option('--js').conflicts(['ts', 'jsx']);\n *\n * @param {(string | string[])} names\n * @return {Option}\n */\n\n conflicts(names) {\n this.conflictsWith = this.conflictsWith.concat(names);\n return this;\n }\n\n /**\n * Specify implied option values for when this option is set and the implied options are not.\n *\n * The custom processing (parseArg) is not called on the implied values.\n *\n * @example\n * program\n * .addOption(new Option('--log', 'write logging information to file'))\n * .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));\n *\n * @param {object} impliedOptionValues\n * @return {Option}\n */\n implies(impliedOptionValues) {\n let newImplied = impliedOptionValues;\n if (typeof impliedOptionValues === 'string') {\n // string is not documented, but easy mistake and we can do what user probably intended.\n newImplied = { [impliedOptionValues]: true };\n }\n this.implied = Object.assign(this.implied || {}, newImplied);\n return this;\n }\n\n /**\n * Set environment variable to check for option value.\n *\n * An environment variable is only used if when processed the current option value is\n * undefined, or the source of the current value is 'default' or 'config' or 'env'.\n *\n * @param {string} name\n * @return {Option}\n */\n\n env(name) {\n this.envVar = name;\n return this;\n }\n\n /**\n * Set the custom handler for processing CLI option arguments into option values.\n *\n * @param {Function} [fn]\n * @return {Option}\n */\n\n argParser(fn) {\n this.parseArg = fn;\n return this;\n }\n\n /**\n * Whether the option is mandatory and must have a value after parsing.\n *\n * @param {boolean} [mandatory=true]\n * @return {Option}\n */\n\n makeOptionMandatory(mandatory = true) {\n this.mandatory = !!mandatory;\n return this;\n }\n\n /**\n * Hide option in help.\n *\n * @param {boolean} [hide=true]\n * @return {Option}\n */\n\n hideHelp(hide = true) {\n this.hidden = !!hide;\n return this;\n }\n\n /**\n * @package\n */\n\n _collectValue(value, previous) {\n if (previous === this.defaultValue || !Array.isArray(previous)) {\n return [value];\n }\n\n previous.push(value);\n return previous;\n }\n\n /**\n * Only allow option value to be one of choices.\n *\n * @param {string[]} values\n * @return {Option}\n */\n\n choices(values) {\n this.argChoices = values.slice();\n this.parseArg = (arg, previous) => {\n if (!this.argChoices.includes(arg)) {\n throw new InvalidArgumentError(\n `Allowed choices are ${this.argChoices.join(', ')}.`,\n );\n }\n if (this.variadic) {\n return this._collectValue(arg, previous);\n }\n return arg;\n };\n return this;\n }\n\n /**\n * Return option name.\n *\n * @return {string}\n */\n\n name() {\n if (this.long) {\n return this.long.replace(/^--/, '');\n }\n return this.short.replace(/^-/, '');\n }\n\n /**\n * Return option name, in a camelcase format that can be used\n * as an object attribute key.\n *\n * @return {string}\n */\n\n attributeName() {\n if (this.negate) {\n return camelcase(this.name().replace(/^no-/, ''));\n }\n return camelcase(this.name());\n }\n\n /**\n * Set the help group heading.\n *\n * @param {string} heading\n * @return {Option}\n */\n helpGroup(heading) {\n this.helpGroupHeading = heading;\n return this;\n }\n\n /**\n * Check if `arg` matches the short or long flag.\n *\n * @param {string} arg\n * @return {boolean}\n * @package\n */\n\n is(arg) {\n return this.short === arg || this.long === arg;\n }\n\n /**\n * Return whether a boolean option.\n *\n * Options are one of boolean, negated, required argument, or optional argument.\n *\n * @return {boolean}\n * @package\n */\n\n isBoolean() {\n return !this.required && !this.optional && !this.negate;\n }\n}\n\n/**\n * This class is to make it easier to work with dual options, without changing the existing\n * implementation. We support separate dual options for separate positive and negative options,\n * like `--build` and `--no-build`, which share a single option value. This works nicely for some\n * use cases, but is tricky for others where we want separate behaviours despite\n * the single shared option value.\n */\nclass DualOptions {\n /**\n * @param {Option[]} options\n */\n constructor(options) {\n this.positiveOptions = new Map();\n this.negativeOptions = new Map();\n this.dualOptions = new Set();\n options.forEach((option) => {\n if (option.negate) {\n this.negativeOptions.set(option.attributeName(), option);\n } else {\n this.positiveOptions.set(option.attributeName(), option);\n }\n });\n this.negativeOptions.forEach((value, key) => {\n if (this.positiveOptions.has(key)) {\n this.dualOptions.add(key);\n }\n });\n }\n\n /**\n * Did the value come from the option, and not from possible matching dual option?\n *\n * @param {*} value\n * @param {Option} option\n * @returns {boolean}\n */\n valueFromOption(value, option) {\n const optionKey = option.attributeName();\n if (!this.dualOptions.has(optionKey)) return true;\n\n // Use the value to deduce if (probably) came from the option.\n const preset = this.negativeOptions.get(optionKey).presetArg;\n const negativeValue = preset !== undefined ? preset : false;\n return option.negate === (negativeValue === value);\n }\n}\n\n/**\n * Convert string from kebab-case to camelCase.\n *\n * @param {string} str\n * @return {string}\n * @private\n */\n\nfunction camelcase(str) {\n return str.split('-').reduce((str, word) => {\n return str + word[0].toUpperCase() + word.slice(1);\n });\n}\n\n/**\n * Split the short and long flag out of something like '-m,--mixed <value>'\n *\n * @private\n */\n\nfunction splitOptionFlags(flags) {\n let shortFlag;\n let longFlag;\n // short flag, single dash and single character\n const shortFlagExp = /^-[^-]$/;\n // long flag, double dash and at least one character\n const longFlagExp = /^--[^-]/;\n\n const flagParts = flags.split(/[ |,]+/).concat('guard');\n // Normal is short and/or long.\n if (shortFlagExp.test(flagParts[0])) shortFlag = flagParts.shift();\n if (longFlagExp.test(flagParts[0])) longFlag = flagParts.shift();\n // Long then short. Rarely used but fine.\n if (!shortFlag && shortFlagExp.test(flagParts[0]))\n shortFlag = flagParts.shift();\n // Allow two long flags, like '--ws, --workspace'\n // This is the supported way to have a shortish option flag.\n if (!shortFlag && longFlagExp.test(flagParts[0])) {\n shortFlag = longFlag;\n longFlag = flagParts.shift();\n }\n\n // Check for unprocessed flag. Fail noisily rather than silently ignore.\n if (flagParts[0].startsWith('-')) {\n const unsupportedFlag = flagParts[0];\n const baseError = `option creation failed due to '${unsupportedFlag}' in option flags '${flags}'`;\n if (/^-[^-][^-]/.test(unsupportedFlag))\n throw new Error(\n `${baseError}\n- a short flag is a single dash and a single character\n - either use a single dash and a single character (for a short flag)\n - or use a double dash for a long option (and can have two, like '--ws, --workspace')`,\n );\n if (shortFlagExp.test(unsupportedFlag))\n throw new Error(`${baseError}\n- too many short flags`);\n if (longFlagExp.test(unsupportedFlag))\n throw new Error(`${baseError}\n- too many long flags`);\n\n throw new Error(`${baseError}\n- unrecognised flag format`);\n }\n if (shortFlag === undefined && longFlag === undefined)\n throw new Error(\n `option creation failed due to no flags found in '${flags}'.`,\n );\n\n return { shortFlag, longFlag };\n}\n\nexports.Option = Option;\nexports.DualOptions = DualOptions;\n", "const maxDistance = 3;\n\nfunction editDistance(a, b) {\n // https://en.wikipedia.org/wiki/Damerau\u2013Levenshtein_distance\n // Calculating optimal string alignment distance, no substring is edited more than once.\n // (Simple implementation.)\n\n // Quick early exit, return worst case.\n if (Math.abs(a.length - b.length) > maxDistance)\n return Math.max(a.length, b.length);\n\n // distance between prefix substrings of a and b\n const d = [];\n\n // pure deletions turn a into empty string\n for (let i = 0; i <= a.length; i++) {\n d[i] = [i];\n }\n // pure insertions turn empty string into b\n for (let j = 0; j <= b.length; j++) {\n d[0][j] = j;\n }\n\n // fill matrix\n for (let j = 1; j <= b.length; j++) {\n for (let i = 1; i <= a.length; i++) {\n let cost = 1;\n if (a[i - 1] === b[j - 1]) {\n cost = 0;\n } else {\n cost = 1;\n }\n d[i][j] = Math.min(\n d[i - 1][j] + 1, // deletion\n d[i][j - 1] + 1, // insertion\n d[i - 1][j - 1] + cost, // substitution\n );\n // transposition\n if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {\n d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);\n }\n }\n }\n\n return d[a.length][b.length];\n}\n\n/**\n * Find close matches, restricted to same number of edits.\n *\n * @param {string} word\n * @param {string[]} candidates\n * @returns {string}\n */\n\nfunction suggestSimilar(word, candidates) {\n if (!candidates || candidates.length === 0) return '';\n // remove possible duplicates\n candidates = Array.from(new Set(candidates));\n\n const searchingOptions = word.startsWith('--');\n if (searchingOptions) {\n word = word.slice(2);\n candidates = candidates.map((candidate) => candidate.slice(2));\n }\n\n let similar = [];\n let bestDistance = maxDistance;\n const minSimilarity = 0.4;\n candidates.forEach((candidate) => {\n if (candidate.length <= 1) return; // no one character guesses\n\n const distance = editDistance(word, candidate);\n const length = Math.max(word.length, candidate.length);\n const similarity = (length - distance) / length;\n if (similarity > minSimilarity) {\n if (distance < bestDistance) {\n // better edit distance, throw away previous worse matches\n bestDistance = distance;\n similar = [candidate];\n } else if (distance === bestDistance) {\n similar.push(candidate);\n }\n }\n });\n\n similar.sort((a, b) => a.localeCompare(b));\n if (searchingOptions) {\n similar = similar.map((candidate) => `--${candidate}`);\n }\n\n if (similar.length > 1) {\n return `\\n(Did you mean one of ${similar.join(', ')}?)`;\n }\n if (similar.length === 1) {\n return `\\n(Did you mean ${similar[0]}?)`;\n }\n return '';\n}\n\nexports.suggestSimilar = suggestSimilar;\n", "const EventEmitter = require('node:events').EventEmitter;\nconst childProcess = require('node:child_process');\nconst path = require('node:path');\nconst fs = require('node:fs');\nconst process = require('node:process');\n\nconst { Argument, humanReadableArgName } = require('./argument.js');\nconst { CommanderError } = require('./error.js');\nconst { Help, stripColor } = require('./help.js');\nconst { Option, DualOptions } = require('./option.js');\nconst { suggestSimilar } = require('./suggestSimilar');\n\nclass Command extends EventEmitter {\n /**\n * Initialize a new `Command`.\n *\n * @param {string} [name]\n */\n\n constructor(name) {\n super();\n /** @type {Command[]} */\n this.commands = [];\n /** @type {Option[]} */\n this.options = [];\n this.parent = null;\n this._allowUnknownOption = false;\n this._allowExcessArguments = false;\n /** @type {Argument[]} */\n this.registeredArguments = [];\n this._args = this.registeredArguments; // deprecated old name\n /** @type {string[]} */\n this.args = []; // cli args with options removed\n this.rawArgs = [];\n this.processedArgs = []; // like .args but after custom processing and collecting variadic\n this._scriptPath = null;\n this._name = name || '';\n this._optionValues = {};\n this._optionValueSources = {}; // default, env, cli etc\n this._storeOptionsAsProperties = false;\n this._actionHandler = null;\n this._executableHandler = false;\n this._executableFile = null; // custom name for executable\n this._executableDir = null; // custom search directory for subcommands\n this._defaultCommandName = null;\n this._exitCallback = null;\n this._aliases = [];\n this._combineFlagAndOptionalValue = true;\n this._description = '';\n this._summary = '';\n this._argsDescription = undefined; // legacy\n this._enablePositionalOptions = false;\n this._passThroughOptions = false;\n this._lifeCycleHooks = {}; // a hash of arrays\n /** @type {(boolean | string)} */\n this._showHelpAfterError = false;\n this._showSuggestionAfterError = true;\n this._savedState = null; // used in save/restoreStateBeforeParse\n\n // see configureOutput() for docs\n this._outputConfiguration = {\n writeOut: (str) => process.stdout.write(str),\n writeErr: (str) => process.stderr.write(str),\n outputError: (str, write) => write(str),\n getOutHelpWidth: () =>\n process.stdout.isTTY ? process.stdout.columns : undefined,\n getErrHelpWidth: () =>\n process.stderr.isTTY ? process.stderr.columns : undefined,\n getOutHasColors: () =>\n useColor() ?? (process.stdout.isTTY && process.stdout.hasColors?.()),\n getErrHasColors: () =>\n useColor() ?? (process.stderr.isTTY && process.stderr.hasColors?.()),\n stripColor: (str) => stripColor(str),\n };\n\n this._hidden = false;\n /** @type {(Option | null | undefined)} */\n this._helpOption = undefined; // Lazy created on demand. May be null if help option is disabled.\n this._addImplicitHelpCommand = undefined; // undecided whether true or false yet, not inherited\n /** @type {Command} */\n this._helpCommand = undefined; // lazy initialised, inherited\n this._helpConfiguration = {};\n /** @type {string | undefined} */\n this._helpGroupHeading = undefined; // soft initialised when added to parent\n /** @type {string | undefined} */\n this._defaultCommandGroup = undefined;\n /** @type {string | undefined} */\n this._defaultOptionGroup = undefined;\n }\n\n /**\n * Copy settings that are useful to have in common across root command and subcommands.\n *\n * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)\n *\n * @param {Command} sourceCommand\n * @return {Command} `this` command for chaining\n */\n copyInheritedSettings(sourceCommand) {\n this._outputConfiguration = sourceCommand._outputConfiguration;\n this._helpOption = sourceCommand._helpOption;\n this._helpCommand = sourceCommand._helpCommand;\n this._helpConfiguration = sourceCommand._helpConfiguration;\n this._exitCallback = sourceCommand._exitCallback;\n this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;\n this._combineFlagAndOptionalValue =\n sourceCommand._combineFlagAndOptionalValue;\n this._allowExcessArguments = sourceCommand._allowExcessArguments;\n this._enablePositionalOptions = sourceCommand._enablePositionalOptions;\n this._showHelpAfterError = sourceCommand._showHelpAfterError;\n this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;\n\n return this;\n }\n\n /**\n * @returns {Command[]}\n * @private\n */\n\n _getCommandAndAncestors() {\n const result = [];\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n for (let command = this; command; command = command.parent) {\n result.push(command);\n }\n return result;\n }\n\n /**\n * Define a command.\n *\n * There are two styles of command: pay attention to where to put the description.\n *\n * @example\n * // Command implemented using action handler (description is supplied separately to `.command`)\n * program\n * .command('clone <source> [destination]')\n * .description('clone a repository into a newly created directory')\n * .action((source, destination) => {\n * console.log('clone command called');\n * });\n *\n * // Command implemented using separate executable file (description is second parameter to `.command`)\n * program\n * .command('start <service>', 'start named service')\n * .command('stop [service]', 'stop named service, or all if no name supplied');\n *\n * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`\n * @param {(object | string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)\n * @param {object} [execOpts] - configuration options (for executable)\n * @return {Command} returns new command for action handler, or `this` for executable command\n */\n\n command(nameAndArgs, actionOptsOrExecDesc, execOpts) {\n let desc = actionOptsOrExecDesc;\n let opts = execOpts;\n if (typeof desc === 'object' && desc !== null) {\n opts = desc;\n desc = null;\n }\n opts = opts || {};\n const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);\n\n const cmd = this.createCommand(name);\n if (desc) {\n cmd.description(desc);\n cmd._executableHandler = true;\n }\n if (opts.isDefault) this._defaultCommandName = cmd._name;\n cmd._hidden = !!(opts.noHelp || opts.hidden); // noHelp is deprecated old name for hidden\n cmd._executableFile = opts.executableFile || null; // Custom name for executable file, set missing to null to match constructor\n if (args) cmd.arguments(args);\n this._registerCommand(cmd);\n cmd.parent = this;\n cmd.copyInheritedSettings(this);\n\n if (desc) return this;\n return cmd;\n }\n\n /**\n * Factory routine to create a new unattached command.\n *\n * See .command() for creating an attached subcommand, which uses this routine to\n * create the command. You can override createCommand to customise subcommands.\n *\n * @param {string} [name]\n * @return {Command} new command\n */\n\n createCommand(name) {\n return new Command(name);\n }\n\n /**\n * You can customise the help with a subclass of Help by overriding createHelp,\n * or by overriding Help properties using configureHelp().\n *\n * @return {Help}\n */\n\n createHelp() {\n return Object.assign(new Help(), this.configureHelp());\n }\n\n /**\n * You can customise the help by overriding Help properties using configureHelp(),\n * or with a subclass of Help by overriding createHelp().\n *\n * @param {object} [configuration] - configuration options\n * @return {(Command | object)} `this` command for chaining, or stored configuration\n */\n\n configureHelp(configuration) {\n if (configuration === undefined) return this._helpConfiguration;\n\n this._helpConfiguration = configuration;\n return this;\n }\n\n /**\n * The default output goes to stdout and stderr. You can customise this for special\n * applications. You can also customise the display of errors by overriding outputError.\n *\n * The configuration properties are all functions:\n *\n * // change how output being written, defaults to stdout and stderr\n * writeOut(str)\n * writeErr(str)\n * // change how output being written for errors, defaults to writeErr\n * outputError(str, write) // used for displaying errors and not used for displaying help\n * // specify width for wrapping help\n * getOutHelpWidth()\n * getErrHelpWidth()\n * // color support, currently only used with Help\n * getOutHasColors()\n * getErrHasColors()\n * stripColor() // used to remove ANSI escape codes if output does not have colors\n *\n * @param {object} [configuration] - configuration options\n * @return {(Command | object)} `this` command for chaining, or stored configuration\n */\n\n configureOutput(configuration) {\n if (configuration === undefined) return this._outputConfiguration;\n\n this._outputConfiguration = {\n ...this._outputConfiguration,\n ...configuration,\n };\n return this;\n }\n\n /**\n * Display the help or a custom message after an error occurs.\n *\n * @param {(boolean|string)} [displayHelp]\n * @return {Command} `this` command for chaining\n */\n showHelpAfterError(displayHelp = true) {\n if (typeof displayHelp !== 'string') displayHelp = !!displayHelp;\n this._showHelpAfterError = displayHelp;\n return this;\n }\n\n /**\n * Display suggestion of similar commands for unknown commands, or options for unknown options.\n *\n * @param {boolean} [displaySuggestion]\n * @return {Command} `this` command for chaining\n */\n showSuggestionAfterError(displaySuggestion = true) {\n this._showSuggestionAfterError = !!displaySuggestion;\n return this;\n }\n\n /**\n * Add a prepared subcommand.\n *\n * See .command() for creating an attached subcommand which inherits settings from its parent.\n *\n * @param {Command} cmd - new subcommand\n * @param {object} [opts] - configuration options\n * @return {Command} `this` command for chaining\n */\n\n addCommand(cmd, opts) {\n if (!cmd._name) {\n throw new Error(`Command passed to .addCommand() must have a name\n- specify the name in Command constructor or using .name()`);\n }\n\n opts = opts || {};\n if (opts.isDefault) this._defaultCommandName = cmd._name;\n if (opts.noHelp || opts.hidden) cmd._hidden = true; // modifying passed command due to existing implementation\n\n this._registerCommand(cmd);\n cmd.parent = this;\n cmd._checkForBrokenPassThrough();\n\n return this;\n }\n\n /**\n * Factory routine to create a new unattached argument.\n *\n * See .argument() for creating an attached argument, which uses this routine to\n * create the argument. You can override createArgument to return a custom argument.\n *\n * @param {string} name\n * @param {string} [description]\n * @return {Argument} new argument\n */\n\n createArgument(name, description) {\n return new Argument(name, description);\n }\n\n /**\n * Define argument syntax for command.\n *\n * The default is that the argument is required, and you can explicitly\n * indicate this with <> around the name. Put [] around the name for an optional argument.\n *\n * @example\n * program.argument('<input-file>');\n * program.argument('[output-file]');\n *\n * @param {string} name\n * @param {string} [description]\n * @param {(Function|*)} [parseArg] - custom argument processing function or default value\n * @param {*} [defaultValue]\n * @return {Command} `this` command for chaining\n */\n argument(name, description, parseArg, defaultValue) {\n const argument = this.createArgument(name, description);\n if (typeof parseArg === 'function') {\n argument.default(defaultValue).argParser(parseArg);\n } else {\n argument.default(parseArg);\n }\n this.addArgument(argument);\n return this;\n }\n\n /**\n * Define argument syntax for command, adding multiple at once (without descriptions).\n *\n * See also .argument().\n *\n * @example\n * program.arguments('<cmd> [env]');\n *\n * @param {string} names\n * @return {Command} `this` command for chaining\n */\n\n arguments(names) {\n names\n .trim()\n .split(/ +/)\n .forEach((detail) => {\n this.argument(detail);\n });\n return this;\n }\n\n /**\n * Define argument syntax for command, adding a prepared argument.\n *\n * @param {Argument} argument\n * @return {Command} `this` command for chaining\n */\n addArgument(argument) {\n const previousArgument = this.registeredArguments.slice(-1)[0];\n if (previousArgument?.variadic) {\n throw new Error(\n `only the last argument can be variadic '${previousArgument.name()}'`,\n );\n }\n if (\n argument.required &&\n argument.defaultValue !== undefined &&\n argument.parseArg === undefined\n ) {\n throw new Error(\n `a default value for a required argument is never used: '${argument.name()}'`,\n );\n }\n this.registeredArguments.push(argument);\n return this;\n }\n\n /**\n * Customise or override default help command. By default a help command is automatically added if your command has subcommands.\n *\n * @example\n * program.helpCommand('help [cmd]');\n * program.helpCommand('help [cmd]', 'show help');\n * program.helpCommand(false); // suppress default help command\n * program.helpCommand(true); // add help command even if no subcommands\n *\n * @param {string|boolean} enableOrNameAndArgs - enable with custom name and/or arguments, or boolean to override whether added\n * @param {string} [description] - custom description\n * @return {Command} `this` command for chaining\n */\n\n helpCommand(enableOrNameAndArgs, description) {\n if (typeof enableOrNameAndArgs === 'boolean') {\n this._addImplicitHelpCommand = enableOrNameAndArgs;\n if (enableOrNameAndArgs && this._defaultCommandGroup) {\n // make the command to store the group\n this._initCommandGroup(this._getHelpCommand());\n }\n return this;\n }\n\n const nameAndArgs = enableOrNameAndArgs ?? 'help [command]';\n const [, helpName, helpArgs] = nameAndArgs.match(/([^ ]+) *(.*)/);\n const helpDescription = description ?? 'display help for command';\n\n const helpCommand = this.createCommand(helpName);\n helpCommand.helpOption(false);\n if (helpArgs) helpCommand.arguments(helpArgs);\n if (helpDescription) helpCommand.description(helpDescription);\n\n this._addImplicitHelpCommand = true;\n this._helpCommand = helpCommand;\n // init group unless lazy create\n if (enableOrNameAndArgs || description) this._initCommandGroup(helpCommand);\n\n return this;\n }\n\n /**\n * Add prepared custom help command.\n *\n * @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()`\n * @param {string} [deprecatedDescription] - deprecated custom description used with custom name only\n * @return {Command} `this` command for chaining\n */\n addHelpCommand(helpCommand, deprecatedDescription) {\n // If not passed an object, call through to helpCommand for backwards compatibility,\n // as addHelpCommand was originally used like helpCommand is now.\n if (typeof helpCommand !== 'object') {\n this.helpCommand(helpCommand, deprecatedDescription);\n return this;\n }\n\n this._addImplicitHelpCommand = true;\n this._helpCommand = helpCommand;\n this._initCommandGroup(helpCommand);\n return this;\n }\n\n /**\n * Lazy create help command.\n *\n * @return {(Command|null)}\n * @package\n */\n _getHelpCommand() {\n const hasImplicitHelpCommand =\n this._addImplicitHelpCommand ??\n (this.commands.length &&\n !this._actionHandler &&\n !this._findCommand('help'));\n\n if (hasImplicitHelpCommand) {\n if (this._helpCommand === undefined) {\n this.helpCommand(undefined, undefined); // use default name and description\n }\n return this._helpCommand;\n }\n return null;\n }\n\n /**\n * Add hook for life cycle event.\n *\n * @param {string} event\n * @param {Function} listener\n * @return {Command} `this` command for chaining\n */\n\n hook(event, listener) {\n const allowedValues = ['preSubcommand', 'preAction', 'postAction'];\n if (!allowedValues.includes(event)) {\n throw new Error(`Unexpected value for event passed to hook : '${event}'.\nExpecting one of '${allowedValues.join(\"', '\")}'`);\n }\n if (this._lifeCycleHooks[event]) {\n this._lifeCycleHooks[event].push(listener);\n } else {\n this._lifeCycleHooks[event] = [listener];\n }\n return this;\n }\n\n /**\n * Register callback to use as replacement for calling process.exit.\n *\n * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing\n * @return {Command} `this` command for chaining\n */\n\n exitOverride(fn) {\n if (fn) {\n this._exitCallback = fn;\n } else {\n this._exitCallback = (err) => {\n if (err.code !== 'commander.executeSubCommandAsync') {\n throw err;\n } else {\n // Async callback from spawn events, not useful to throw.\n }\n };\n }\n return this;\n }\n\n /**\n * Call process.exit, and _exitCallback if defined.\n *\n * @param {number} exitCode exit code for using with process.exit\n * @param {string} code an id string representing the error\n * @param {string} message human-readable description of the error\n * @return never\n * @private\n */\n\n _exit(exitCode, code, message) {\n if (this._exitCallback) {\n this._exitCallback(new CommanderError(exitCode, code, message));\n // Expecting this line is not reached.\n }\n process.exit(exitCode);\n }\n\n /**\n * Register callback `fn` for the command.\n *\n * @example\n * program\n * .command('serve')\n * .description('start service')\n * .action(function() {\n * // do work here\n * });\n *\n * @param {Function} fn\n * @return {Command} `this` command for chaining\n */\n\n action(fn) {\n const listener = (args) => {\n // The .action callback takes an extra parameter which is the command or options.\n const expectedArgsCount = this.registeredArguments.length;\n const actionArgs = args.slice(0, expectedArgsCount);\n if (this._storeOptionsAsProperties) {\n actionArgs[expectedArgsCount] = this; // backwards compatible \"options\"\n } else {\n actionArgs[expectedArgsCount] = this.opts();\n }\n actionArgs.push(this);\n\n return fn.apply(this, actionArgs);\n };\n this._actionHandler = listener;\n return this;\n }\n\n /**\n * Factory routine to create a new unattached option.\n *\n * See .option() for creating an attached option, which uses this routine to\n * create the option. You can override createOption to return a custom option.\n *\n * @param {string} flags\n * @param {string} [description]\n * @return {Option} new option\n */\n\n createOption(flags, description) {\n return new Option(flags, description);\n }\n\n /**\n * Wrap parseArgs to catch 'commander.invalidArgument'.\n *\n * @param {(Option | Argument)} target\n * @param {string} value\n * @param {*} previous\n * @param {string} invalidArgumentMessage\n * @private\n */\n\n _callParseArg(target, value, previous, invalidArgumentMessage) {\n try {\n return target.parseArg(value, previous);\n } catch (err) {\n if (err.code === 'commander.invalidArgument') {\n const message = `${invalidArgumentMessage} ${err.message}`;\n this.error(message, { exitCode: err.exitCode, code: err.code });\n }\n throw err;\n }\n }\n\n /**\n * Check for option flag conflicts.\n * Register option if no conflicts found, or throw on conflict.\n *\n * @param {Option} option\n * @private\n */\n\n _registerOption(option) {\n const matchingOption =\n (option.short && this._findOption(option.short)) ||\n (option.long && this._findOption(option.long));\n if (matchingOption) {\n const matchingFlag =\n option.long && this._findOption(option.long)\n ? option.long\n : option.short;\n throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'\n- already used by option '${matchingOption.flags}'`);\n }\n\n this._initOptionGroup(option);\n this.options.push(option);\n }\n\n /**\n * Check for command name and alias conflicts with existing commands.\n * Register command if no conflicts found, or throw on conflict.\n *\n * @param {Command} command\n * @private\n */\n\n _registerCommand(command) {\n const knownBy = (cmd) => {\n return [cmd.name()].concat(cmd.aliases());\n };\n\n const alreadyUsed = knownBy(command).find((name) =>\n this._findCommand(name),\n );\n if (alreadyUsed) {\n const existingCmd = knownBy(this._findCommand(alreadyUsed)).join('|');\n const newCmd = knownBy(command).join('|');\n throw new Error(\n `cannot add command '${newCmd}' as already have command '${existingCmd}'`,\n );\n }\n\n this._initCommandGroup(command);\n this.commands.push(command);\n }\n\n /**\n * Add an option.\n *\n * @param {Option} option\n * @return {Command} `this` command for chaining\n */\n addOption(option) {\n this._registerOption(option);\n\n const oname = option.name();\n const name = option.attributeName();\n\n // store default value\n if (option.negate) {\n // --no-foo is special and defaults foo to true, unless a --foo option is already defined\n const positiveLongFlag = option.long.replace(/^--no-/, '--');\n if (!this._findOption(positiveLongFlag)) {\n this.setOptionValueWithSource(\n name,\n option.defaultValue === undefined ? true : option.defaultValue,\n 'default',\n );\n }\n } else if (option.defaultValue !== undefined) {\n this.setOptionValueWithSource(name, option.defaultValue, 'default');\n }\n\n // handler for cli and env supplied values\n const handleOptionValue = (val, invalidValueMessage, valueSource) => {\n // val is null for optional option used without an optional-argument.\n // val is undefined for boolean and negated option.\n if (val == null && option.presetArg !== undefined) {\n val = option.presetArg;\n }\n\n // custom processing\n const oldValue = this.getOptionValue(name);\n if (val !== null && option.parseArg) {\n val = this._callParseArg(option, val, oldValue, invalidValueMessage);\n } else if (val !== null && option.variadic) {\n val = option._collectValue(val, oldValue);\n }\n\n // Fill-in appropriate missing values. Long winded but easy to follow.\n if (val == null) {\n if (option.negate) {\n val = false;\n } else if (option.isBoolean() || option.optional) {\n val = true;\n } else {\n val = ''; // not normal, parseArg might have failed or be a mock function for testing\n }\n }\n this.setOptionValueWithSource(name, val, valueSource);\n };\n\n this.on('option:' + oname, (val) => {\n const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;\n handleOptionValue(val, invalidValueMessage, 'cli');\n });\n\n if (option.envVar) {\n this.on('optionEnv:' + oname, (val) => {\n const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;\n handleOptionValue(val, invalidValueMessage, 'env');\n });\n }\n\n return this;\n }\n\n /**\n * Internal implementation shared by .option() and .requiredOption()\n *\n * @return {Command} `this` command for chaining\n * @private\n */\n _optionEx(config, flags, description, fn, defaultValue) {\n if (typeof flags === 'object' && flags instanceof Option) {\n throw new Error(\n 'To add an Option object use addOption() instead of option() or requiredOption()',\n );\n }\n const option = this.createOption(flags, description);\n option.makeOptionMandatory(!!config.mandatory);\n if (typeof fn === 'function') {\n option.default(defaultValue).argParser(fn);\n } else if (fn instanceof RegExp) {\n // deprecated\n const regex = fn;\n fn = (val, def) => {\n const m = regex.exec(val);\n return m ? m[0] : def;\n };\n option.default(defaultValue).argParser(fn);\n } else {\n option.default(fn);\n }\n\n return this.addOption(option);\n }\n\n /**\n * Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.\n *\n * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required\n * option-argument is indicated by `<>` and an optional option-argument by `[]`.\n *\n * See the README for more details, and see also addOption() and requiredOption().\n *\n * @example\n * program\n * .option('-p, --pepper', 'add pepper')\n * .option('--pt, --pizza-type <TYPE>', 'type of pizza') // required option-argument\n * .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default\n * .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function\n *\n * @param {string} flags\n * @param {string} [description]\n * @param {(Function|*)} [parseArg] - custom option processing function or default value\n * @param {*} [defaultValue]\n * @return {Command} `this` command for chaining\n */\n\n option(flags, description, parseArg, defaultValue) {\n return this._optionEx({}, flags, description, parseArg, defaultValue);\n }\n\n /**\n * Add a required option which must have a value after parsing. This usually means\n * the option must be specified on the command line. (Otherwise the same as .option().)\n *\n * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.\n *\n * @param {string} flags\n * @param {string} [description]\n * @param {(Function|*)} [parseArg] - custom option processing function or default value\n * @param {*} [defaultValue]\n * @return {Command} `this` command for chaining\n */\n\n requiredOption(flags, description, parseArg, defaultValue) {\n return this._optionEx(\n { mandatory: true },\n flags,\n description,\n parseArg,\n defaultValue,\n );\n }\n\n /**\n * Alter parsing of short flags with optional values.\n *\n * @example\n * // for `.option('-f,--flag [value]'):\n * program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour\n * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`\n *\n * @param {boolean} [combine] - if `true` or omitted, an optional value can be specified directly after the flag.\n * @return {Command} `this` command for chaining\n */\n combineFlagAndOptionalValue(combine = true) {\n this._combineFlagAndOptionalValue = !!combine;\n return this;\n }\n\n /**\n * Allow unknown options on the command line.\n *\n * @param {boolean} [allowUnknown] - if `true` or omitted, no error will be thrown for unknown options.\n * @return {Command} `this` command for chaining\n */\n allowUnknownOption(allowUnknown = true) {\n this._allowUnknownOption = !!allowUnknown;\n return this;\n }\n\n /**\n * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.\n *\n * @param {boolean} [allowExcess] - if `true` or omitted, no error will be thrown for excess arguments.\n * @return {Command} `this` command for chaining\n */\n allowExcessArguments(allowExcess = true) {\n this._allowExcessArguments = !!allowExcess;\n return this;\n }\n\n /**\n * Enable positional options. Positional means global options are specified before subcommands which lets\n * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.\n * The default behaviour is non-positional and global options may appear anywhere on the command line.\n *\n * @param {boolean} [positional]\n * @return {Command} `this` command for chaining\n */\n enablePositionalOptions(positional = true) {\n this._enablePositionalOptions = !!positional;\n return this;\n }\n\n /**\n * Pass through options that come after command-arguments rather than treat them as command-options,\n * so actual command-options come before command-arguments. Turning this on for a subcommand requires\n * positional options to have been enabled on the program (parent commands).\n * The default behaviour is non-positional and options may appear before or after command-arguments.\n *\n * @param {boolean} [passThrough] for unknown options.\n * @return {Command} `this` command for chaining\n */\n passThroughOptions(passThrough = true) {\n this._passThroughOptions = !!passThrough;\n this._checkForBrokenPassThrough();\n return this;\n }\n\n /**\n * @private\n */\n\n _checkForBrokenPassThrough() {\n if (\n this.parent &&\n this._passThroughOptions &&\n !this.parent._enablePositionalOptions\n ) {\n throw new Error(\n `passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`,\n );\n }\n }\n\n /**\n * Whether to store option values as properties on command object,\n * or store separately (specify false). In both cases the option values can be accessed using .opts().\n *\n * @param {boolean} [storeAsProperties=true]\n * @return {Command} `this` command for chaining\n */\n\n storeOptionsAsProperties(storeAsProperties = true) {\n if (this.options.length) {\n throw new Error('call .storeOptionsAsProperties() before adding options');\n }\n if (Object.keys(this._optionValues).length) {\n throw new Error(\n 'call .storeOptionsAsProperties() before setting option values',\n );\n }\n this._storeOptionsAsProperties = !!storeAsProperties;\n return this;\n }\n\n /**\n * Retrieve option value.\n *\n * @param {string} key\n * @return {object} value\n */\n\n getOptionValue(key) {\n if (this._storeOptionsAsProperties) {\n return this[key];\n }\n return this._optionValues[key];\n }\n\n /**\n * Store option value.\n *\n * @param {string} key\n * @param {object} value\n * @return {Command} `this` command for chaining\n */\n\n setOptionValue(key, value) {\n return this.setOptionValueWithSource(key, value, undefined);\n }\n\n /**\n * Store option value and where the value came from.\n *\n * @param {string} key\n * @param {object} value\n * @param {string} source - expected values are default/config/env/cli/implied\n * @return {Command} `this` command for chaining\n */\n\n setOptionValueWithSource(key, value, source) {\n if (this._storeOptionsAsProperties) {\n this[key] = value;\n } else {\n this._optionValues[key] = value;\n }\n this._optionValueSources[key] = source;\n return this;\n }\n\n /**\n * Get source of option value.\n * Expected values are default | config | env | cli | implied\n *\n * @param {string} key\n * @return {string}\n */\n\n getOptionValueSource(key) {\n return this._optionValueSources[key];\n }\n\n /**\n * Get source of option value. See also .optsWithGlobals().\n * Expected values are default | config | env | cli | implied\n *\n * @param {string} key\n * @return {string}\n */\n\n getOptionValueSourceWithGlobals(key) {\n // global overwrites local, like optsWithGlobals\n let source;\n this._getCommandAndAncestors().forEach((cmd) => {\n if (cmd.getOptionValueSource(key) !== undefined) {\n source = cmd.getOptionValueSource(key);\n }\n });\n return source;\n }\n\n /**\n * Get user arguments from implied or explicit arguments.\n * Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.\n *\n * @private\n */\n\n _prepareUserArgs(argv, parseOptions) {\n if (argv !== undefined && !Array.isArray(argv)) {\n throw new Error('first parameter to parse must be array or undefined');\n }\n parseOptions = parseOptions || {};\n\n // auto-detect argument conventions if nothing supplied\n if (argv === undefined && parseOptions.from === undefined) {\n if (process.versions?.electron) {\n parseOptions.from = 'electron';\n }\n // check node specific options for scenarios where user CLI args follow executable without scriptname\n const execArgv = process.execArgv ?? [];\n if (\n execArgv.includes('-e') ||\n execArgv.includes('--eval') ||\n execArgv.includes('-p') ||\n execArgv.includes('--print')\n ) {\n parseOptions.from = 'eval'; // internal usage, not documented\n }\n }\n\n // default to using process.argv\n if (argv === undefined) {\n argv = process.argv;\n }\n this.rawArgs = argv.slice();\n\n // extract the user args and scriptPath\n let userArgs;\n switch (parseOptions.from) {\n case undefined:\n case 'node':\n this._scriptPath = argv[1];\n userArgs = argv.slice(2);\n break;\n case 'electron':\n // @ts-ignore: because defaultApp is an unknown property\n if (process.defaultApp) {\n this._scriptPath = argv[1];\n userArgs = argv.slice(2);\n } else {\n userArgs = argv.slice(1);\n }\n break;\n case 'user':\n userArgs = argv.slice(0);\n break;\n case 'eval':\n userArgs = argv.slice(1);\n break;\n default:\n throw new Error(\n `unexpected parse option { from: '${parseOptions.from}' }`,\n );\n }\n\n // Find default name for program from arguments.\n if (!this._name && this._scriptPath)\n this.nameFromFilename(this._scriptPath);\n this._name = this._name || 'program';\n\n return userArgs;\n }\n\n /**\n * Parse `argv`, setting options and invoking commands when defined.\n *\n * Use parseAsync instead of parse if any of your action handlers are async.\n *\n * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!\n *\n * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:\n * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that\n * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged\n * - `'user'`: just user arguments\n *\n * @example\n * program.parse(); // parse process.argv and auto-detect electron and special node flags\n * program.parse(process.argv); // assume argv[0] is app and argv[1] is script\n * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]\n *\n * @param {string[]} [argv] - optional, defaults to process.argv\n * @param {object} [parseOptions] - optionally specify style of options with from: node/user/electron\n * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'\n * @return {Command} `this` command for chaining\n */\n\n parse(argv, parseOptions) {\n this._prepareForParse();\n const userArgs = this._prepareUserArgs(argv, parseOptions);\n this._parseCommand([], userArgs);\n\n return this;\n }\n\n /**\n * Parse `argv`, setting options and invoking commands when defined.\n *\n * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!\n *\n * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:\n * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that\n * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged\n * - `'user'`: just user arguments\n *\n * @example\n * await program.parseAsync(); // parse process.argv and auto-detect electron and special node flags\n * await program.parseAsync(process.argv); // assume argv[0] is app and argv[1] is script\n * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]\n *\n * @param {string[]} [argv]\n * @param {object} [parseOptions]\n * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'\n * @return {Promise}\n */\n\n async parseAsync(argv, parseOptions) {\n this._prepareForParse();\n const userArgs = this._prepareUserArgs(argv, parseOptions);\n await this._parseCommand([], userArgs);\n\n return this;\n }\n\n _prepareForParse() {\n if (this._savedState === null) {\n this.saveStateBeforeParse();\n } else {\n this.restoreStateBeforeParse();\n }\n }\n\n /**\n * Called the first time parse is called to save state and allow a restore before subsequent calls to parse.\n * Not usually called directly, but available for subclasses to save their custom state.\n *\n * This is called in a lazy way. Only commands used in parsing chain will have state saved.\n */\n saveStateBeforeParse() {\n this._savedState = {\n // name is stable if supplied by author, but may be unspecified for root command and deduced during parsing\n _name: this._name,\n // option values before parse have default values (including false for negated options)\n // shallow clones\n _optionValues: { ...this._optionValues },\n _optionValueSources: { ...this._optionValueSources },\n };\n }\n\n /**\n * Restore state before parse for calls after the first.\n * Not usually called directly, but available for subclasses to save their custom state.\n *\n * This is called in a lazy way. Only commands used in parsing chain will have state restored.\n */\n restoreStateBeforeParse() {\n if (this._storeOptionsAsProperties)\n throw new Error(`Can not call parse again when storeOptionsAsProperties is true.\n- either make a new Command for each call to parse, or stop storing options as properties`);\n\n // clear state from _prepareUserArgs\n this._name = this._savedState._name;\n this._scriptPath = null;\n this.rawArgs = [];\n // clear state from setOptionValueWithSource\n this._optionValues = { ...this._savedState._optionValues };\n this._optionValueSources = { ...this._savedState._optionValueSources };\n // clear state from _parseCommand\n this.args = [];\n // clear state from _processArguments\n this.processedArgs = [];\n }\n\n /**\n * Throw if expected executable is missing. Add lots of help for author.\n *\n * @param {string} executableFile\n * @param {string} executableDir\n * @param {string} subcommandName\n */\n _checkForMissingExecutable(executableFile, executableDir, subcommandName) {\n if (fs.existsSync(executableFile)) return;\n\n const executableDirMessage = executableDir\n ? `searched for local subcommand relative to directory '${executableDir}'`\n : 'no directory for search for local subcommand, use .executableDir() to supply a custom directory';\n const executableMissing = `'${executableFile}' does not exist\n - if '${subcommandName}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead\n - if the default executable name is not suitable, use the executableFile option to supply a custom name or path\n - ${executableDirMessage}`;\n throw new Error(executableMissing);\n }\n\n /**\n * Execute a sub-command executable.\n *\n * @private\n */\n\n _executeSubCommand(subcommand, args) {\n args = args.slice();\n let launchWithNode = false; // Use node for source targets so do not need to get permissions correct, and on Windows.\n const sourceExt = ['.js', '.ts', '.tsx', '.mjs', '.cjs'];\n\n function findFile(baseDir, baseName) {\n // Look for specified file\n const localBin = path.resolve(baseDir, baseName);\n if (fs.existsSync(localBin)) return localBin;\n\n // Stop looking if candidate already has an expected extension.\n if (sourceExt.includes(path.extname(baseName))) return undefined;\n\n // Try all the extensions.\n const foundExt = sourceExt.find((ext) =>\n fs.existsSync(`${localBin}${ext}`),\n );\n if (foundExt) return `${localBin}${foundExt}`;\n\n return undefined;\n }\n\n // Not checking for help first. Unlikely to have mandatory and executable, and can't robustly test for help flags in external command.\n this._checkForMissingMandatoryOptions();\n this._checkForConflictingOptions();\n\n // executableFile and executableDir might be full path, or just a name\n let executableFile =\n subcommand._executableFile || `${this._name}-${subcommand._name}`;\n let executableDir = this._executableDir || '';\n if (this._scriptPath) {\n let resolvedScriptPath; // resolve possible symlink for installed npm binary\n try {\n resolvedScriptPath = fs.realpathSync(this._scriptPath);\n } catch {\n resolvedScriptPath = this._scriptPath;\n }\n executableDir = path.resolve(\n path.dirname(resolvedScriptPath),\n executableDir,\n );\n }\n\n // Look for a local file in preference to a command in PATH.\n if (executableDir) {\n let localFile = findFile(executableDir, executableFile);\n\n // Legacy search using prefix of script name instead of command name\n if (!localFile && !subcommand._executableFile && this._scriptPath) {\n const legacyName = path.basename(\n this._scriptPath,\n path.extname(this._scriptPath),\n );\n if (legacyName !== this._name) {\n localFile = findFile(\n executableDir,\n `${legacyName}-${subcommand._name}`,\n );\n }\n }\n executableFile = localFile || executableFile;\n }\n\n launchWithNode = sourceExt.includes(path.extname(executableFile));\n\n let proc;\n if (process.platform !== 'win32') {\n if (launchWithNode) {\n args.unshift(executableFile);\n // add executable arguments to spawn\n args = incrementNodeInspectorPort(process.execArgv).concat(args);\n\n proc = childProcess.spawn(process.argv[0], args, { stdio: 'inherit' });\n } else {\n proc = childProcess.spawn(executableFile, args, { stdio: 'inherit' });\n }\n } else {\n this._checkForMissingExecutable(\n executableFile,\n executableDir,\n subcommand._name,\n );\n args.unshift(executableFile);\n // add executable arguments to spawn\n args = incrementNodeInspectorPort(process.execArgv).concat(args);\n proc = childProcess.spawn(process.execPath, args, { stdio: 'inherit' });\n }\n\n if (!proc.killed) {\n // testing mainly to avoid leak warnings during unit tests with mocked spawn\n const signals = ['SIGUSR1', 'SIGUSR2', 'SIGTERM', 'SIGINT', 'SIGHUP'];\n signals.forEach((signal) => {\n process.on(signal, () => {\n if (proc.killed === false && proc.exitCode === null) {\n // @ts-ignore because signals not typed to known strings\n proc.kill(signal);\n }\n });\n });\n }\n\n // By default terminate process when spawned process terminates.\n const exitCallback = this._exitCallback;\n proc.on('close', (code) => {\n code = code ?? 1; // code is null if spawned process terminated due to a signal\n if (!exitCallback) {\n process.exit(code);\n } else {\n exitCallback(\n new CommanderError(\n code,\n 'commander.executeSubCommandAsync',\n '(close)',\n ),\n );\n }\n });\n proc.on('error', (err) => {\n // @ts-ignore: because err.code is an unknown property\n if (err.code === 'ENOENT') {\n this._checkForMissingExecutable(\n executableFile,\n executableDir,\n subcommand._name,\n );\n // @ts-ignore: because err.code is an unknown property\n } else if (err.code === 'EACCES') {\n throw new Error(`'${executableFile}' not executable`);\n }\n if (!exitCallback) {\n process.exit(1);\n } else {\n const wrappedError = new CommanderError(\n 1,\n 'commander.executeSubCommandAsync',\n '(error)',\n );\n wrappedError.nestedError = err;\n exitCallback(wrappedError);\n }\n });\n\n // Store the reference to the child process\n this.runningCommand = proc;\n }\n\n /**\n * @private\n */\n\n _dispatchSubcommand(commandName, operands, unknown) {\n const subCommand = this._findCommand(commandName);\n if (!subCommand) this.help({ error: true });\n\n subCommand._prepareForParse();\n let promiseChain;\n promiseChain = this._chainOrCallSubCommandHook(\n promiseChain,\n subCommand,\n 'preSubcommand',\n );\n promiseChain = this._chainOrCall(promiseChain, () => {\n if (subCommand._executableHandler) {\n this._executeSubCommand(subCommand, operands.concat(unknown));\n } else {\n return subCommand._parseCommand(operands, unknown);\n }\n });\n return promiseChain;\n }\n\n /**\n * Invoke help directly if possible, or dispatch if necessary.\n * e.g. help foo\n *\n * @private\n */\n\n _dispatchHelpCommand(subcommandName) {\n if (!subcommandName) {\n this.help();\n }\n const subCommand = this._findCommand(subcommandName);\n if (subCommand && !subCommand._executableHandler) {\n subCommand.help();\n }\n\n // Fallback to parsing the help flag to invoke the help.\n return this._dispatchSubcommand(\n subcommandName,\n [],\n [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? '--help'],\n );\n }\n\n /**\n * Check this.args against expected this.registeredArguments.\n *\n * @private\n */\n\n _checkNumberOfArguments() {\n // too few\n this.registeredArguments.forEach((arg, i) => {\n if (arg.required && this.args[i] == null) {\n this.missingArgument(arg.name());\n }\n });\n // too many\n if (\n this.registeredArguments.length > 0 &&\n this.registeredArguments[this.registeredArguments.length - 1].variadic\n ) {\n return;\n }\n if (this.args.length > this.registeredArguments.length) {\n this._excessArguments(this.args);\n }\n }\n\n /**\n * Process this.args using this.registeredArguments and save as this.processedArgs!\n *\n * @private\n */\n\n _processArguments() {\n const myParseArg = (argument, value, previous) => {\n // Extra processing for nice error message on parsing failure.\n let parsedValue = value;\n if (value !== null && argument.parseArg) {\n const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;\n parsedValue = this._callParseArg(\n argument,\n value,\n previous,\n invalidValueMessage,\n );\n }\n return parsedValue;\n };\n\n this._checkNumberOfArguments();\n\n const processedArgs = [];\n this.registeredArguments.forEach((declaredArg, index) => {\n let value = declaredArg.defaultValue;\n if (declaredArg.variadic) {\n // Collect together remaining arguments for passing together as an array.\n if (index < this.args.length) {\n value = this.args.slice(index);\n if (declaredArg.parseArg) {\n value = value.reduce((processed, v) => {\n return myParseArg(declaredArg, v, processed);\n }, declaredArg.defaultValue);\n }\n } else if (value === undefined) {\n value = [];\n }\n } else if (index < this.args.length) {\n value = this.args[index];\n if (declaredArg.parseArg) {\n value = myParseArg(declaredArg, value, declaredArg.defaultValue);\n }\n }\n processedArgs[index] = value;\n });\n this.processedArgs = processedArgs;\n }\n\n /**\n * Once we have a promise we chain, but call synchronously until then.\n *\n * @param {(Promise|undefined)} promise\n * @param {Function} fn\n * @return {(Promise|undefined)}\n * @private\n */\n\n _chainOrCall(promise, fn) {\n // thenable\n if (promise?.then && typeof promise.then === 'function') {\n // already have a promise, chain callback\n return promise.then(() => fn());\n }\n // callback might return a promise\n return fn();\n }\n\n /**\n *\n * @param {(Promise|undefined)} promise\n * @param {string} event\n * @return {(Promise|undefined)}\n * @private\n */\n\n _chainOrCallHooks(promise, event) {\n let result = promise;\n const hooks = [];\n this._getCommandAndAncestors()\n .reverse()\n .filter((cmd) => cmd._lifeCycleHooks[event] !== undefined)\n .forEach((hookedCommand) => {\n hookedCommand._lifeCycleHooks[event].forEach((callback) => {\n hooks.push({ hookedCommand, callback });\n });\n });\n if (event === 'postAction') {\n hooks.reverse();\n }\n\n hooks.forEach((hookDetail) => {\n result = this._chainOrCall(result, () => {\n return hookDetail.callback(hookDetail.hookedCommand, this);\n });\n });\n return result;\n }\n\n /**\n *\n * @param {(Promise|undefined)} promise\n * @param {Command} subCommand\n * @param {string} event\n * @return {(Promise|undefined)}\n * @private\n */\n\n _chainOrCallSubCommandHook(promise, subCommand, event) {\n let result = promise;\n if (this._lifeCycleHooks[event] !== undefined) {\n this._lifeCycleHooks[event].forEach((hook) => {\n result = this._chainOrCall(result, () => {\n return hook(this, subCommand);\n });\n });\n }\n return result;\n }\n\n /**\n * Process arguments in context of this command.\n * Returns action result, in case it is a promise.\n *\n * @private\n */\n\n _parseCommand(operands, unknown) {\n const parsed = this.parseOptions(unknown);\n this._parseOptionsEnv(); // after cli, so parseArg not called on both cli and env\n this._parseOptionsImplied();\n operands = operands.concat(parsed.operands);\n unknown = parsed.unknown;\n this.args = operands.concat(unknown);\n\n if (operands && this._findCommand(operands[0])) {\n return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);\n }\n if (\n this._getHelpCommand() &&\n operands[0] === this._getHelpCommand().name()\n ) {\n return this._dispatchHelpCommand(operands[1]);\n }\n if (this._defaultCommandName) {\n this._outputHelpIfRequested(unknown); // Run the help for default command from parent rather than passing to default command\n return this._dispatchSubcommand(\n this._defaultCommandName,\n operands,\n unknown,\n );\n }\n if (\n this.commands.length &&\n this.args.length === 0 &&\n !this._actionHandler &&\n !this._defaultCommandName\n ) {\n // probably missing subcommand and no handler, user needs help (and exit)\n this.help({ error: true });\n }\n\n this._outputHelpIfRequested(parsed.unknown);\n this._checkForMissingMandatoryOptions();\n this._checkForConflictingOptions();\n\n // We do not always call this check to avoid masking a \"better\" error, like unknown command.\n const checkForUnknownOptions = () => {\n if (parsed.unknown.length > 0) {\n this.unknownOption(parsed.unknown[0]);\n }\n };\n\n const commandEvent = `command:${this.name()}`;\n if (this._actionHandler) {\n checkForUnknownOptions();\n this._processArguments();\n\n let promiseChain;\n promiseChain = this._chainOrCallHooks(promiseChain, 'preAction');\n promiseChain = this._chainOrCall(promiseChain, () =>\n this._actionHandler(this.processedArgs),\n );\n if (this.parent) {\n promiseChain = this._chainOrCall(promiseChain, () => {\n this.parent.emit(commandEvent, operands, unknown); // legacy\n });\n }\n promiseChain = this._chainOrCallHooks(promiseChain, 'postAction');\n return promiseChain;\n }\n if (this.parent?.listenerCount(commandEvent)) {\n checkForUnknownOptions();\n this._processArguments();\n this.parent.emit(commandEvent, operands, unknown); // legacy\n } else if (operands.length) {\n if (this._findCommand('*')) {\n // legacy default command\n return this._dispatchSubcommand('*', operands, unknown);\n }\n if (this.listenerCount('command:*')) {\n // skip option check, emit event for possible misspelling suggestion\n this.emit('command:*', operands, unknown);\n } else if (this.commands.length) {\n this.unknownCommand();\n } else {\n checkForUnknownOptions();\n this._processArguments();\n }\n } else if (this.commands.length) {\n checkForUnknownOptions();\n // This command has subcommands and nothing hooked up at this level, so display help (and exit).\n this.help({ error: true });\n } else {\n checkForUnknownOptions();\n this._processArguments();\n // fall through for caller to handle after calling .parse()\n }\n }\n\n /**\n * Find matching command.\n *\n * @private\n * @return {Command | undefined}\n */\n _findCommand(name) {\n if (!name) return undefined;\n return this.commands.find(\n (cmd) => cmd._name === name || cmd._aliases.includes(name),\n );\n }\n\n /**\n * Return an option matching `arg` if any.\n *\n * @param {string} arg\n * @return {Option}\n * @package\n */\n\n _findOption(arg) {\n return this.options.find((option) => option.is(arg));\n }\n\n /**\n * Display an error message if a mandatory option does not have a value.\n * Called after checking for help flags in leaf subcommand.\n *\n * @private\n */\n\n _checkForMissingMandatoryOptions() {\n // Walk up hierarchy so can call in subcommand after checking for displaying help.\n this._getCommandAndAncestors().forEach((cmd) => {\n cmd.options.forEach((anOption) => {\n if (\n anOption.mandatory &&\n cmd.getOptionValue(anOption.attributeName()) === undefined\n ) {\n cmd.missingMandatoryOptionValue(anOption);\n }\n });\n });\n }\n\n /**\n * Display an error message if conflicting options are used together in this.\n *\n * @private\n */\n _checkForConflictingLocalOptions() {\n const definedNonDefaultOptions = this.options.filter((option) => {\n const optionKey = option.attributeName();\n if (this.getOptionValue(optionKey) === undefined) {\n return false;\n }\n return this.getOptionValueSource(optionKey) !== 'default';\n });\n\n const optionsWithConflicting = definedNonDefaultOptions.filter(\n (option) => option.conflictsWith.length > 0,\n );\n\n optionsWithConflicting.forEach((option) => {\n const conflictingAndDefined = definedNonDefaultOptions.find((defined) =>\n option.conflictsWith.includes(defined.attributeName()),\n );\n if (conflictingAndDefined) {\n this._conflictingOption(option, conflictingAndDefined);\n }\n });\n }\n\n /**\n * Display an error message if conflicting options are used together.\n * Called after checking for help flags in leaf subcommand.\n *\n * @private\n */\n _checkForConflictingOptions() {\n // Walk up hierarchy so can call in subcommand after checking for displaying help.\n this._getCommandAndAncestors().forEach((cmd) => {\n cmd._checkForConflictingLocalOptions();\n });\n }\n\n /**\n * Parse options from `argv` removing known options,\n * and return argv split into operands and unknown arguments.\n *\n * Side effects: modifies command by storing options. Does not reset state if called again.\n *\n * Examples:\n *\n * argv => operands, unknown\n * --known kkk op => [op], []\n * op --known kkk => [op], []\n * sub --unknown uuu op => [sub], [--unknown uuu op]\n * sub -- --unknown uuu op => [sub --unknown uuu op], []\n *\n * @param {string[]} args\n * @return {{operands: string[], unknown: string[]}}\n */\n\n parseOptions(args) {\n const operands = []; // operands, not options or values\n const unknown = []; // first unknown option and remaining unknown args\n let dest = operands;\n\n function maybeOption(arg) {\n return arg.length > 1 && arg[0] === '-';\n }\n\n const negativeNumberArg = (arg) => {\n // return false if not a negative number\n if (!/^-(\\d+|\\d*\\.\\d+)(e[+-]?\\d+)?$/.test(arg)) return false;\n // negative number is ok unless digit used as an option in command hierarchy\n return !this._getCommandAndAncestors().some((cmd) =>\n cmd.options\n .map((opt) => opt.short)\n .some((short) => /^-\\d$/.test(short)),\n );\n };\n\n // parse options\n let activeVariadicOption = null;\n let activeGroup = null; // working through group of short options, like -abc\n let i = 0;\n while (i < args.length || activeGroup) {\n const arg = activeGroup ?? args[i++];\n activeGroup = null;\n\n // literal\n if (arg === '--') {\n if (dest === unknown) dest.push(arg);\n dest.push(...args.slice(i));\n break;\n }\n\n if (\n activeVariadicOption &&\n (!maybeOption(arg) || negativeNumberArg(arg))\n ) {\n this.emit(`option:${activeVariadicOption.name()}`, arg);\n continue;\n }\n activeVariadicOption = null;\n\n if (maybeOption(arg)) {\n const option = this._findOption(arg);\n // recognised option, call listener to assign value with possible custom processing\n if (option) {\n if (option.required) {\n const value = args[i++];\n if (value === undefined) this.optionMissingArgument(option);\n this.emit(`option:${option.name()}`, value);\n } else if (option.optional) {\n let value = null;\n // historical behaviour is optional value is following arg unless an option\n if (\n i < args.length &&\n (!maybeOption(args[i]) || negativeNumberArg(args[i]))\n ) {\n value = args[i++];\n }\n this.emit(`option:${option.name()}`, value);\n } else {\n // boolean flag\n this.emit(`option:${option.name()}`);\n }\n activeVariadicOption = option.variadic ? option : null;\n continue;\n }\n }\n\n // Look for combo options following single dash, eat first one if known.\n if (arg.length > 2 && arg[0] === '-' && arg[1] !== '-') {\n const option = this._findOption(`-${arg[1]}`);\n if (option) {\n if (\n option.required ||\n (option.optional && this._combineFlagAndOptionalValue)\n ) {\n // option with value following in same argument\n this.emit(`option:${option.name()}`, arg.slice(2));\n } else {\n // boolean option\n this.emit(`option:${option.name()}`);\n // remove the processed option and keep processing group\n activeGroup = `-${arg.slice(2)}`;\n }\n continue;\n }\n }\n\n // Look for known long flag with value, like --foo=bar\n if (/^--[^=]+=/.test(arg)) {\n const index = arg.indexOf('=');\n const option = this._findOption(arg.slice(0, index));\n if (option && (option.required || option.optional)) {\n this.emit(`option:${option.name()}`, arg.slice(index + 1));\n continue;\n }\n }\n\n // Not a recognised option by this command.\n // Might be a command-argument, or subcommand option, or unknown option, or help command or option.\n\n // An unknown option means further arguments also classified as unknown so can be reprocessed by subcommands.\n // A negative number in a leaf command is not an unknown option.\n if (\n dest === operands &&\n maybeOption(arg) &&\n !(this.commands.length === 0 && negativeNumberArg(arg))\n ) {\n dest = unknown;\n }\n\n // If using positionalOptions, stop processing our options at subcommand.\n if (\n (this._enablePositionalOptions || this._passThroughOptions) &&\n operands.length === 0 &&\n unknown.length === 0\n ) {\n if (this._findCommand(arg)) {\n operands.push(arg);\n unknown.push(...args.slice(i));\n break;\n } else if (\n this._getHelpCommand() &&\n arg === this._getHelpCommand().name()\n ) {\n operands.push(arg, ...args.slice(i));\n break;\n } else if (this._defaultCommandName) {\n unknown.push(arg, ...args.slice(i));\n break;\n }\n }\n\n // If using passThroughOptions, stop processing options at first command-argument.\n if (this._passThroughOptions) {\n dest.push(arg, ...args.slice(i));\n break;\n }\n\n // add arg\n dest.push(arg);\n }\n\n return { operands, unknown };\n }\n\n /**\n * Return an object containing local option values as key-value pairs.\n *\n * @return {object}\n */\n opts() {\n if (this._storeOptionsAsProperties) {\n // Preserve original behaviour so backwards compatible when still using properties\n const result = {};\n const len = this.options.length;\n\n for (let i = 0; i < len; i++) {\n const key = this.options[i].attributeName();\n result[key] =\n key === this._versionOptionName ? this._version : this[key];\n }\n return result;\n }\n\n return this._optionValues;\n }\n\n /**\n * Return an object containing merged local and global option values as key-value pairs.\n *\n * @return {object}\n */\n optsWithGlobals() {\n // globals overwrite locals\n return this._getCommandAndAncestors().reduce(\n (combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()),\n {},\n );\n }\n\n /**\n * Display error message and exit (or call exitOverride).\n *\n * @param {string} message\n * @param {object} [errorOptions]\n * @param {string} [errorOptions.code] - an id string representing the error\n * @param {number} [errorOptions.exitCode] - used with process.exit\n */\n error(message, errorOptions) {\n // output handling\n this._outputConfiguration.outputError(\n `${message}\\n`,\n this._outputConfiguration.writeErr,\n );\n if (typeof this._showHelpAfterError === 'string') {\n this._outputConfiguration.writeErr(`${this._showHelpAfterError}\\n`);\n } else if (this._showHelpAfterError) {\n this._outputConfiguration.writeErr('\\n');\n this.outputHelp({ error: true });\n }\n\n // exit handling\n const config = errorOptions || {};\n const exitCode = config.exitCode || 1;\n const code = config.code || 'commander.error';\n this._exit(exitCode, code, message);\n }\n\n /**\n * Apply any option related environment variables, if option does\n * not have a value from cli or client code.\n *\n * @private\n */\n _parseOptionsEnv() {\n this.options.forEach((option) => {\n if (option.envVar && option.envVar in process.env) {\n const optionKey = option.attributeName();\n // Priority check. Do not overwrite cli or options from unknown source (client-code).\n if (\n this.getOptionValue(optionKey) === undefined ||\n ['default', 'config', 'env'].includes(\n this.getOptionValueSource(optionKey),\n )\n ) {\n if (option.required || option.optional) {\n // option can take a value\n // keep very simple, optional always takes value\n this.emit(`optionEnv:${option.name()}`, process.env[option.envVar]);\n } else {\n // boolean\n // keep very simple, only care that envVar defined and not the value\n this.emit(`optionEnv:${option.name()}`);\n }\n }\n }\n });\n }\n\n /**\n * Apply any implied option values, if option is undefined or default value.\n *\n * @private\n */\n _parseOptionsImplied() {\n const dualHelper = new DualOptions(this.options);\n const hasCustomOptionValue = (optionKey) => {\n return (\n this.getOptionValue(optionKey) !== undefined &&\n !['default', 'implied'].includes(this.getOptionValueSource(optionKey))\n );\n };\n this.options\n .filter(\n (option) =>\n option.implied !== undefined &&\n hasCustomOptionValue(option.attributeName()) &&\n dualHelper.valueFromOption(\n this.getOptionValue(option.attributeName()),\n option,\n ),\n )\n .forEach((option) => {\n Object.keys(option.implied)\n .filter((impliedKey) => !hasCustomOptionValue(impliedKey))\n .forEach((impliedKey) => {\n this.setOptionValueWithSource(\n impliedKey,\n option.implied[impliedKey],\n 'implied',\n );\n });\n });\n }\n\n /**\n * Argument `name` is missing.\n *\n * @param {string} name\n * @private\n */\n\n missingArgument(name) {\n const message = `error: missing required argument '${name}'`;\n this.error(message, { code: 'commander.missingArgument' });\n }\n\n /**\n * `Option` is missing an argument.\n *\n * @param {Option} option\n * @private\n */\n\n optionMissingArgument(option) {\n const message = `error: option '${option.flags}' argument missing`;\n this.error(message, { code: 'commander.optionMissingArgument' });\n }\n\n /**\n * `Option` does not have a value, and is a mandatory option.\n *\n * @param {Option} option\n * @private\n */\n\n missingMandatoryOptionValue(option) {\n const message = `error: required option '${option.flags}' not specified`;\n this.error(message, { code: 'commander.missingMandatoryOptionValue' });\n }\n\n /**\n * `Option` conflicts with another option.\n *\n * @param {Option} option\n * @param {Option} conflictingOption\n * @private\n */\n _conflictingOption(option, conflictingOption) {\n // The calling code does not know whether a negated option is the source of the\n // value, so do some work to take an educated guess.\n const findBestOptionFromValue = (option) => {\n const optionKey = option.attributeName();\n const optionValue = this.getOptionValue(optionKey);\n const negativeOption = this.options.find(\n (target) => target.negate && optionKey === target.attributeName(),\n );\n const positiveOption = this.options.find(\n (target) => !target.negate && optionKey === target.attributeName(),\n );\n if (\n negativeOption &&\n ((negativeOption.presetArg === undefined && optionValue === false) ||\n (negativeOption.presetArg !== undefined &&\n optionValue === negativeOption.presetArg))\n ) {\n return negativeOption;\n }\n return positiveOption || option;\n };\n\n const getErrorMessage = (option) => {\n const bestOption = findBestOptionFromValue(option);\n const optionKey = bestOption.attributeName();\n const source = this.getOptionValueSource(optionKey);\n if (source === 'env') {\n return `environment variable '${bestOption.envVar}'`;\n }\n return `option '${bestOption.flags}'`;\n };\n\n const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;\n this.error(message, { code: 'commander.conflictingOption' });\n }\n\n /**\n * Unknown option `flag`.\n *\n * @param {string} flag\n * @private\n */\n\n unknownOption(flag) {\n if (this._allowUnknownOption) return;\n let suggestion = '';\n\n if (flag.startsWith('--') && this._showSuggestionAfterError) {\n // Looping to pick up the global options too\n let candidateFlags = [];\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n let command = this;\n do {\n const moreFlags = command\n .createHelp()\n .visibleOptions(command)\n .filter((option) => option.long)\n .map((option) => option.long);\n candidateFlags = candidateFlags.concat(moreFlags);\n command = command.parent;\n } while (command && !command._enablePositionalOptions);\n suggestion = suggestSimilar(flag, candidateFlags);\n }\n\n const message = `error: unknown option '${flag}'${suggestion}`;\n this.error(message, { code: 'commander.unknownOption' });\n }\n\n /**\n * Excess arguments, more than expected.\n *\n * @param {string[]} receivedArgs\n * @private\n */\n\n _excessArguments(receivedArgs) {\n if (this._allowExcessArguments) return;\n\n const expected = this.registeredArguments.length;\n const s = expected === 1 ? '' : 's';\n const forSubcommand = this.parent ? ` for '${this.name()}'` : '';\n const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;\n this.error(message, { code: 'commander.excessArguments' });\n }\n\n /**\n * Unknown command.\n *\n * @private\n */\n\n unknownCommand() {\n const unknownName = this.args[0];\n let suggestion = '';\n\n if (this._showSuggestionAfterError) {\n const candidateNames = [];\n this.createHelp()\n .visibleCommands(this)\n .forEach((command) => {\n candidateNames.push(command.name());\n // just visible alias\n if (command.alias()) candidateNames.push(command.alias());\n });\n suggestion = suggestSimilar(unknownName, candidateNames);\n }\n\n const message = `error: unknown command '${unknownName}'${suggestion}`;\n this.error(message, { code: 'commander.unknownCommand' });\n }\n\n /**\n * Get or set the program version.\n *\n * This method auto-registers the \"-V, --version\" option which will print the version number.\n *\n * You can optionally supply the flags and description to override the defaults.\n *\n * @param {string} [str]\n * @param {string} [flags]\n * @param {string} [description]\n * @return {(this | string | undefined)} `this` command for chaining, or version string if no arguments\n */\n\n version(str, flags, description) {\n if (str === undefined) return this._version;\n this._version = str;\n flags = flags || '-V, --version';\n description = description || 'output the version number';\n const versionOption = this.createOption(flags, description);\n this._versionOptionName = versionOption.attributeName();\n this._registerOption(versionOption);\n\n this.on('option:' + versionOption.name(), () => {\n this._outputConfiguration.writeOut(`${str}\\n`);\n this._exit(0, 'commander.version', str);\n });\n return this;\n }\n\n /**\n * Set the description.\n *\n * @param {string} [str]\n * @param {object} [argsDescription]\n * @return {(string|Command)}\n */\n description(str, argsDescription) {\n if (str === undefined && argsDescription === undefined)\n return this._description;\n this._description = str;\n if (argsDescription) {\n this._argsDescription = argsDescription;\n }\n return this;\n }\n\n /**\n * Set the summary. Used when listed as subcommand of parent.\n *\n * @param {string} [str]\n * @return {(string|Command)}\n */\n summary(str) {\n if (str === undefined) return this._summary;\n this._summary = str;\n return this;\n }\n\n /**\n * Set an alias for the command.\n *\n * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.\n *\n * @param {string} [alias]\n * @return {(string|Command)}\n */\n\n alias(alias) {\n if (alias === undefined) return this._aliases[0]; // just return first, for backwards compatibility\n\n /** @type {Command} */\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n let command = this;\n if (\n this.commands.length !== 0 &&\n this.commands[this.commands.length - 1]._executableHandler\n ) {\n // assume adding alias for last added executable subcommand, rather than this\n command = this.commands[this.commands.length - 1];\n }\n\n if (alias === command._name)\n throw new Error(\"Command alias can't be the same as its name\");\n const matchingCommand = this.parent?._findCommand(alias);\n if (matchingCommand) {\n // c.f. _registerCommand\n const existingCmd = [matchingCommand.name()]\n .concat(matchingCommand.aliases())\n .join('|');\n throw new Error(\n `cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`,\n );\n }\n\n command._aliases.push(alias);\n return this;\n }\n\n /**\n * Set aliases for the command.\n *\n * Only the first alias is shown in the auto-generated help.\n *\n * @param {string[]} [aliases]\n * @return {(string[]|Command)}\n */\n\n aliases(aliases) {\n // Getter for the array of aliases is the main reason for having aliases() in addition to alias().\n if (aliases === undefined) return this._aliases;\n\n aliases.forEach((alias) => this.alias(alias));\n return this;\n }\n\n /**\n * Set / get the command usage `str`.\n *\n * @param {string} [str]\n * @return {(string|Command)}\n */\n\n usage(str) {\n if (str === undefined) {\n if (this._usage) return this._usage;\n\n const args = this.registeredArguments.map((arg) => {\n return humanReadableArgName(arg);\n });\n return []\n .concat(\n this.options.length || this._helpOption !== null ? '[options]' : [],\n this.commands.length ? '[command]' : [],\n this.registeredArguments.length ? args : [],\n )\n .join(' ');\n }\n\n this._usage = str;\n return this;\n }\n\n /**\n * Get or set the name of the command.\n *\n * @param {string} [str]\n * @return {(string|Command)}\n */\n\n name(str) {\n if (str === undefined) return this._name;\n this._name = str;\n return this;\n }\n\n /**\n * Set/get the help group heading for this subcommand in parent command's help.\n *\n * @param {string} [heading]\n * @return {Command | string}\n */\n\n helpGroup(heading) {\n if (heading === undefined) return this._helpGroupHeading ?? '';\n this._helpGroupHeading = heading;\n return this;\n }\n\n /**\n * Set/get the default help group heading for subcommands added to this command.\n * (This does not override a group set directly on the subcommand using .helpGroup().)\n *\n * @example\n * program.commandsGroup('Development Commands:);\n * program.command('watch')...\n * program.command('lint')...\n * ...\n *\n * @param {string} [heading]\n * @returns {Command | string}\n */\n commandsGroup(heading) {\n if (heading === undefined) return this._defaultCommandGroup ?? '';\n this._defaultCommandGroup = heading;\n return this;\n }\n\n /**\n * Set/get the default help group heading for options added to this command.\n * (This does not override a group set directly on the option using .helpGroup().)\n *\n * @example\n * program\n * .optionsGroup('Development Options:')\n * .option('-d, --debug', 'output extra debugging')\n * .option('-p, --profile', 'output profiling information')\n *\n * @param {string} [heading]\n * @returns {Command | string}\n */\n optionsGroup(heading) {\n if (heading === undefined) return this._defaultOptionGroup ?? '';\n this._defaultOptionGroup = heading;\n return this;\n }\n\n /**\n * @param {Option} option\n * @private\n */\n _initOptionGroup(option) {\n if (this._defaultOptionGroup && !option.helpGroupHeading)\n option.helpGroup(this._defaultOptionGroup);\n }\n\n /**\n * @param {Command} cmd\n * @private\n */\n _initCommandGroup(cmd) {\n if (this._defaultCommandGroup && !cmd.helpGroup())\n cmd.helpGroup(this._defaultCommandGroup);\n }\n\n /**\n * Set the name of the command from script filename, such as process.argv[1],\n * or require.main.filename, or __filename.\n *\n * (Used internally and public although not documented in README.)\n *\n * @example\n * program.nameFromFilename(require.main.filename);\n *\n * @param {string} filename\n * @return {Command}\n */\n\n nameFromFilename(filename) {\n this._name = path.basename(filename, path.extname(filename));\n\n return this;\n }\n\n /**\n * Get or set the directory for searching for executable subcommands of this command.\n *\n * @example\n * program.executableDir(__dirname);\n * // or\n * program.executableDir('subcommands');\n *\n * @param {string} [path]\n * @return {(string|null|Command)}\n */\n\n executableDir(path) {\n if (path === undefined) return this._executableDir;\n this._executableDir = path;\n return this;\n }\n\n /**\n * Return program help documentation.\n *\n * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout\n * @return {string}\n */\n\n helpInformation(contextOptions) {\n const helper = this.createHelp();\n const context = this._getOutputContext(contextOptions);\n helper.prepareContext({\n error: context.error,\n helpWidth: context.helpWidth,\n outputHasColors: context.hasColors,\n });\n const text = helper.formatHelp(this, helper);\n if (context.hasColors) return text;\n return this._outputConfiguration.stripColor(text);\n }\n\n /**\n * @typedef HelpContext\n * @type {object}\n * @property {boolean} error\n * @property {number} helpWidth\n * @property {boolean} hasColors\n * @property {function} write - includes stripColor if needed\n *\n * @returns {HelpContext}\n * @private\n */\n\n _getOutputContext(contextOptions) {\n contextOptions = contextOptions || {};\n const error = !!contextOptions.error;\n let baseWrite;\n let hasColors;\n let helpWidth;\n if (error) {\n baseWrite = (str) => this._outputConfiguration.writeErr(str);\n hasColors = this._outputConfiguration.getErrHasColors();\n helpWidth = this._outputConfiguration.getErrHelpWidth();\n } else {\n baseWrite = (str) => this._outputConfiguration.writeOut(str);\n hasColors = this._outputConfiguration.getOutHasColors();\n helpWidth = this._outputConfiguration.getOutHelpWidth();\n }\n const write = (str) => {\n if (!hasColors) str = this._outputConfiguration.stripColor(str);\n return baseWrite(str);\n };\n return { error, write, hasColors, helpWidth };\n }\n\n /**\n * Output help information for this command.\n *\n * Outputs built-in help, and custom text added using `.addHelpText()`.\n *\n * @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout\n */\n\n outputHelp(contextOptions) {\n let deprecatedCallback;\n if (typeof contextOptions === 'function') {\n deprecatedCallback = contextOptions;\n contextOptions = undefined;\n }\n\n const outputContext = this._getOutputContext(contextOptions);\n /** @type {HelpTextEventContext} */\n const eventContext = {\n error: outputContext.error,\n write: outputContext.write,\n command: this,\n };\n\n this._getCommandAndAncestors()\n .reverse()\n .forEach((command) => command.emit('beforeAllHelp', eventContext));\n this.emit('beforeHelp', eventContext);\n\n let helpInformation = this.helpInformation({ error: outputContext.error });\n if (deprecatedCallback) {\n helpInformation = deprecatedCallback(helpInformation);\n if (\n typeof helpInformation !== 'string' &&\n !Buffer.isBuffer(helpInformation)\n ) {\n throw new Error('outputHelp callback must return a string or a Buffer');\n }\n }\n outputContext.write(helpInformation);\n\n if (this._getHelpOption()?.long) {\n this.emit(this._getHelpOption().long); // deprecated\n }\n this.emit('afterHelp', eventContext);\n this._getCommandAndAncestors().forEach((command) =>\n command.emit('afterAllHelp', eventContext),\n );\n }\n\n /**\n * You can pass in flags and a description to customise the built-in help option.\n * Pass in false to disable the built-in help option.\n *\n * @example\n * program.helpOption('-?, --help' 'show help'); // customise\n * program.helpOption(false); // disable\n *\n * @param {(string | boolean)} flags\n * @param {string} [description]\n * @return {Command} `this` command for chaining\n */\n\n helpOption(flags, description) {\n // Support enabling/disabling built-in help option.\n if (typeof flags === 'boolean') {\n if (flags) {\n if (this._helpOption === null) this._helpOption = undefined; // reenable\n if (this._defaultOptionGroup) {\n // make the option to store the group\n this._initOptionGroup(this._getHelpOption());\n }\n } else {\n this._helpOption = null; // disable\n }\n return this;\n }\n\n // Customise flags and description.\n this._helpOption = this.createOption(\n flags ?? '-h, --help',\n description ?? 'display help for command',\n );\n // init group unless lazy create\n if (flags || description) this._initOptionGroup(this._helpOption);\n\n return this;\n }\n\n /**\n * Lazy create help option.\n * Returns null if has been disabled with .helpOption(false).\n *\n * @returns {(Option | null)} the help option\n * @package\n */\n _getHelpOption() {\n // Lazy create help option on demand.\n if (this._helpOption === undefined) {\n this.helpOption(undefined, undefined);\n }\n return this._helpOption;\n }\n\n /**\n * Supply your own option to use for the built-in help option.\n * This is an alternative to using helpOption() to customise the flags and description etc.\n *\n * @param {Option} option\n * @return {Command} `this` command for chaining\n */\n addHelpOption(option) {\n this._helpOption = option;\n this._initOptionGroup(option);\n return this;\n }\n\n /**\n * Output help information and exit.\n *\n * Outputs built-in help, and custom text added using `.addHelpText()`.\n *\n * @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout\n */\n\n help(contextOptions) {\n this.outputHelp(contextOptions);\n let exitCode = Number(process.exitCode ?? 0); // process.exitCode does allow a string or an integer, but we prefer just a number\n if (\n exitCode === 0 &&\n contextOptions &&\n typeof contextOptions !== 'function' &&\n contextOptions.error\n ) {\n exitCode = 1;\n }\n // message: do not have all displayed text available so only passing placeholder.\n this._exit(exitCode, 'commander.help', '(outputHelp)');\n }\n\n /**\n * // Do a little typing to coordinate emit and listener for the help text events.\n * @typedef HelpTextEventContext\n * @type {object}\n * @property {boolean} error\n * @property {Command} command\n * @property {function} write\n */\n\n /**\n * Add additional text to be displayed with the built-in help.\n *\n * Position is 'before' or 'after' to affect just this command,\n * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.\n *\n * @param {string} position - before or after built-in help\n * @param {(string | Function)} text - string to add, or a function returning a string\n * @return {Command} `this` command for chaining\n */\n\n addHelpText(position, text) {\n const allowedValues = ['beforeAll', 'before', 'after', 'afterAll'];\n if (!allowedValues.includes(position)) {\n throw new Error(`Unexpected value for position to addHelpText.\nExpecting one of '${allowedValues.join(\"', '\")}'`);\n }\n\n const helpEvent = `${position}Help`;\n this.on(helpEvent, (/** @type {HelpTextEventContext} */ context) => {\n let helpStr;\n if (typeof text === 'function') {\n helpStr = text({ error: context.error, command: context.command });\n } else {\n helpStr = text;\n }\n // Ignore falsy value when nothing to output.\n if (helpStr) {\n context.write(`${helpStr}\\n`);\n }\n });\n return this;\n }\n\n /**\n * Output help information if help flags specified\n *\n * @param {Array} args - array of options to search for help flags\n * @private\n */\n\n _outputHelpIfRequested(args) {\n const helpOption = this._getHelpOption();\n const helpRequested = helpOption && args.find((arg) => helpOption.is(arg));\n if (helpRequested) {\n this.outputHelp();\n // (Do not have all displayed text available so only passing placeholder.)\n this._exit(0, 'commander.helpDisplayed', '(outputHelp)');\n }\n }\n}\n\n/**\n * Scan arguments and increment port number for inspect calls (to avoid conflicts when spawning new command).\n *\n * @param {string[]} args - array of arguments from node.execArgv\n * @returns {string[]}\n * @private\n */\n\nfunction incrementNodeInspectorPort(args) {\n // Testing for these options:\n // --inspect[=[host:]port]\n // --inspect-brk[=[host:]port]\n // --inspect-port=[host:]port\n return args.map((arg) => {\n if (!arg.startsWith('--inspect')) {\n return arg;\n }\n let debugOption;\n let debugHost = '127.0.0.1';\n let debugPort = '9229';\n let match;\n if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {\n // e.g. --inspect\n debugOption = match[1];\n } else if (\n (match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null\n ) {\n debugOption = match[1];\n if (/^\\d+$/.test(match[3])) {\n // e.g. --inspect=1234\n debugPort = match[3];\n } else {\n // e.g. --inspect=localhost\n debugHost = match[3];\n }\n } else if (\n (match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\\d+)$/)) !== null\n ) {\n // e.g. --inspect=localhost:1234\n debugOption = match[1];\n debugHost = match[3];\n debugPort = match[4];\n }\n\n if (debugOption && debugPort !== '0') {\n return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;\n }\n return arg;\n });\n}\n\n/**\n * @returns {boolean | undefined}\n * @package\n */\nfunction useColor() {\n // Test for common conventions.\n // NB: the observed behaviour is in combination with how author adds color! For example:\n // - we do not test NODE_DISABLE_COLORS, but util:styletext does\n // - we do test NO_COLOR, but Chalk does not\n //\n // References:\n // https://no-color.org\n // https://bixense.com/clicolors/\n // https://github.com/nodejs/node/blob/0a00217a5f67ef4a22384cfc80eb6dd9a917fdc1/lib/internal/tty.js#L109\n // https://github.com/chalk/supports-color/blob/c214314a14bcb174b12b3014b2b0a8de375029ae/index.js#L33\n // (https://force-color.org recent web page from 2023, does not match major javascript implementations)\n\n if (\n process.env.NO_COLOR ||\n process.env.FORCE_COLOR === '0' ||\n process.env.FORCE_COLOR === 'false'\n )\n return false;\n if (process.env.FORCE_COLOR || process.env.CLICOLOR_FORCE !== undefined)\n return true;\n return undefined;\n}\n\nexports.Command = Command;\nexports.useColor = useColor; // exporting for tests\n", "const { Argument } = require('./lib/argument.js');\nconst { Command } = require('./lib/command.js');\nconst { CommanderError, InvalidArgumentError } = require('./lib/error.js');\nconst { Help } = require('./lib/help.js');\nconst { Option } = require('./lib/option.js');\n\nexports.program = new Command();\n\nexports.createCommand = (name) => new Command(name);\nexports.createOption = (flags, description) => new Option(flags, description);\nexports.createArgument = (name, description) => new Argument(name, description);\n\n/**\n * Expose classes\n */\n\nexports.Command = Command;\nexports.Option = Option;\nexports.Argument = Argument;\nexports.Help = Help;\n\nexports.CommanderError = CommanderError;\nexports.InvalidArgumentError = InvalidArgumentError;\nexports.InvalidOptionArgumentError = InvalidArgumentError; // Deprecated\n", "const commander = require('commander');\n\nexports = module.exports = {};\n\n// Return a different global program than commander,\n// and don't also return it as default export.\nexports.program = new commander.Command();\n\n/**\n * Expose classes. The FooT versions are just types, so return Commander original implementations!\n */\n\nexports.Argument = commander.Argument;\nexports.Command = commander.Command;\nexports.CommanderError = commander.CommanderError;\nexports.Help = commander.Help;\nexports.InvalidArgumentError = commander.InvalidArgumentError;\nexports.InvalidOptionArgumentError = commander.InvalidArgumentError; // Deprecated\nexports.Option = commander.Option;\n\nexports.createCommand = (name) => new commander.Command(name);\nexports.createOption = (flags, description) =>\n new commander.Option(flags, description);\nexports.createArgument = (name, description) =>\n new commander.Argument(name, description);\n", "import extraTypingsCommander from './index.js';\n\n// wrapper to provide named exports for ESM.\nexport const {\n program,\n createCommand,\n createArgument,\n createOption,\n CommanderError,\n InvalidArgumentError,\n InvalidOptionArgumentError, // deprecated old name\n Command,\n Argument,\n Option,\n Help,\n} = extraTypingsCommander;\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport {program} from \"@commander-js/extra-typings\"\nimport {glob} from \"glob\"\nimport {writeFile} from \"node:fs/promises\"\nimport {resolve} from \"node:path\"\nimport {cwd} from \"node:process\"\n\nimport {ConfigLoader, fixPath, SearchIndexer} from \"./internal\"\n\nexport function addGeneratePageMapCommand() {\n program\n .command(\"generate-page-map\")\n .description(\n \"Invokes the docs-plugin once to build the site data and writes it to json\",\n )\n .option(\n \"-c, --config-file <configFile>\",\n \"Path to the qui-docs.config.ts config file\",\n )\n .option(\n \"-r, --routes-dir <routesDir>\",\n \"Path to the routes directory\",\n \"src/routes\",\n )\n .option(\n \"-o, --output <output>\",\n \"Output path for the site data json\",\n \"site-data.json\",\n )\n .action(async (options) => {\n try {\n const configLoader = new ConfigLoader({configFile: options.configFile})\n const resolvedConfig = configLoader.loadConfig()\n const routesDir = fixPath(\n resolve(resolvedConfig.appDirectory, resolvedConfig.pageDirectory),\n )\n const indexer = new SearchIndexer({\n ...resolvedConfig,\n srcDir: fixPath(resolve(cwd(), resolvedConfig.appDirectory)),\n typeDocProps: {},\n })\n const files = glob.sync(\n [`${routesDir}/**/*.mdx`, `${routesDir}/**/*.tsx`],\n {\n absolute: true,\n cwd: cwd(),\n },\n )\n indexer.buildIndex(files, true)\n await writeFile(\n resolve(cwd(), options.output),\n JSON.stringify(indexer.pageMap, null, 2),\n \"utf-8\",\n )\n } catch (error) {\n console.error(\n \"Generate Site Data Error:\",\n error instanceof Error ? error.message : String(error),\n )\n process.exit(1)\n }\n })\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport {type Config, type CosmiconfigResult, cosmiconfigSync} from \"cosmiconfig\"\n\nimport type {QuiDocsConfig} from \"../types\"\n\nimport {configSchema} from \"./config-schema\"\nimport {removeTrailingSlash} from \"./utils\"\n\ninterface LoadedCosmicConfig {\n config: Config\n filepath: string\n isEmpty?: boolean\n}\n\nexport interface ResolvedQuiDocsConfig extends QuiDocsConfig {\n appDirectory: string\n /**\n * full path to the cosmiconfig file.\n */\n filePath: string\n pageDirectory: string\n}\n\nexport interface ConfigLoaderOptions {\n /**\n * Path to the qui-docs config file. This is automatically detected if omitted.\n */\n configFile?: string\n}\n\nexport class ConfigLoader {\n private readonly options: ConfigLoaderOptions\n\n constructor(options: ConfigLoaderOptions) {\n this.options = options\n return this\n }\n\n private getCosmiconfig(): LoadedCosmicConfig {\n const explorer = cosmiconfigSync(\"qui-docs\")\n\n const result: CosmiconfigResult | null = this.options.configFile\n ? explorer.load(this.options.configFile)\n : explorer.search()\n\n if (!result) {\n throw new Error(\n \"Config file not found. Please consult the docs at https://docs.qui.qualcomm.com/guide/page-setup#config\",\n )\n }\n\n return result\n }\n\n private resolveConfigFromCosmiconfig(\n config: CosmiconfigResult,\n ): ResolvedQuiDocsConfig {\n const parsed = configSchema.safeParse(config!.config)\n if (!parsed.success) {\n console.dir(parsed.error.issues, {depth: 10})\n throw new Error(\"Failed to parse config file.\")\n }\n const conf = parsed.data\n return {\n ...conf,\n appDirectory: conf.appDirectory || \"app\",\n filePath: config!.filepath,\n pageDirectory: conf.pageDirectory\n ? removeTrailingSlash(conf.pageDirectory)\n : \"routes\",\n }\n }\n\n loadConfig(): ResolvedQuiDocsConfig {\n const config = this.getCosmiconfig()\n return this.resolveConfigFromCosmiconfig(config)\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport {z, type ZodObject, type ZodSchema} from \"zod\"\n\nimport type {\n NavMeta,\n QuiDocsConfig,\n QuiDocsTypeDocOptions,\n RouteMeta,\n} from \"../types\"\n\nimport {implement} from \"./zod\"\n\nexport const navMetaSchema: ZodObject<{}> = implement<NavMeta>().with({\n id: z.never().optional(),\n sectionTitle: z.string().optional(),\n separator: z.boolean().optional(),\n})\n\nexport const routeMetaSchema: ZodSchema<RouteMeta> =\n implement<RouteMeta>().with({\n children: z.array(z.lazy(() => routeMetaSchema)).optional(),\n expanded: z.boolean().optional(),\n group: z.string().optional(),\n groupOrder: z.string().array().optional(),\n hidden: z.boolean().optional(),\n hideBreadcrumbs: z.boolean().optional(),\n hideFromSearch: z.boolean().optional(),\n hidePageLinks: z.boolean().optional(),\n hideSideNav: z.boolean().optional(),\n hideToc: z.boolean().optional(),\n id: z.string(),\n ignoreRouteMetaOrder: z.boolean().optional(),\n restricted: z.boolean().optional(),\n sectionTitle: z.never().optional(),\n separator: z.never().optional(),\n sideNavTitle: z.string().optional(),\n title: z.string().optional(),\n })\n\nconst typeDocPropsSchema = implement<QuiDocsTypeDocOptions>().with({\n includeInSearchIndex: z.boolean().optional(),\n})\n\nexport const configSchema = implement<QuiDocsConfig>().with({\n appDirectory: z.string().optional(),\n disableCache: z.boolean().optional(),\n headings: z\n .array(\n z.union([\n z.literal(\"h1\"),\n z.literal(\"h2\"),\n z.literal(\"h3\"),\n z.literal(\"h4\"),\n z.literal(\"h5\"),\n z.literal(\"h6\"),\n ]),\n )\n .optional(),\n hotUpdateIgnore: z.instanceof(RegExp).optional(),\n navConfig: z.array(z.union([routeMetaSchema, navMetaSchema])).optional(),\n pageDirectory: z.string().optional(),\n routingStrategy: z\n .union([\n z.literal(\"vite-generouted\"),\n z.function(z.tuple([z.string()]), z.array(z.string())),\n ])\n .optional(),\n typeDocProps: z.string().optional(),\n typeDocPropsOptions: typeDocPropsSchema.optional(),\n})\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport {z} from \"zod\"\n\ntype Implements<Model> = {\n [key in keyof Model]-?: undefined extends Model[key]\n ? null extends Model[key]\n ? z.ZodNullableType<z.ZodOptionalType<z.ZodType<Model[key]>>>\n : z.ZodOptionalType<z.ZodType<Model[key]>>\n : null extends Model[key]\n ? z.ZodNullableType<z.ZodType<Model[key]>>\n : z.ZodType<Model[key]> | z.ZodDefault<z.ZodType<Model[key]>>\n}\n\nexport function implement<Model = never>() {\n return {\n with: <\n Schema extends Implements<Model> & {\n [unknownKey in Exclude<keyof Schema, keyof Model>]: never\n },\n >(\n schema: Schema,\n ) => z.object(schema),\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport {z, type ZodObject} from \"zod\"\n\nimport type {PageFrontmatter} from \"@qualcomm-ui/mdx-common\"\n\nimport {implement} from \"./zod\"\n\nexport const isDefined = (\n value: string | boolean | object | null | undefined | number,\n): boolean => typeof value !== \"undefined\" && value !== null\n\nexport function defined<T>(value: T | null | undefined): value is T {\n return typeof value !== \"undefined\" && value !== null\n}\n\n/**\n * Used to validate the MDX frontmatter and emit warnings for pages that violate the\n * schema.\n */\nexport const frontmatterSchema: ZodObject<{}> =\n implement<PageFrontmatter>().with({\n categories: z.string().array().optional(),\n group: z.string().optional(),\n hidden: z.boolean().optional(),\n hideBreadcrumbs: z.boolean().optional(),\n hideFromSearch: z.boolean().optional(),\n hidePageLinks: z.boolean().optional(),\n hideSideNav: z.boolean().optional(),\n hideToc: z.boolean().optional(),\n id: z.string().optional(),\n restricted: z.boolean().optional(),\n sideNavTitle: z.string().optional(),\n title: z.string(),\n })\n\n/**\n * Winblows fix\n */\nexport function fixPath(str: string): string {\n return str.replaceAll(\"\\\\\", \"/\")\n}\n\n/**\n * Removes the trailing slash from a string.\n */\nexport function removeTrailingSlash(str: string): string {\n return str.endsWith(\"/\") ? str.substring(0, str.length - 1) : str\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport chalk from \"chalk\"\n\nimport type {\n NavItem,\n PageFrontmatter,\n PageMap,\n PageSection,\n} from \"@qualcomm-ui/mdx-common\"\nimport type {QuiPropTypes} from \"@qualcomm-ui/typedoc-common\"\n\nimport type {\n RouteMetaInternal,\n RouteMetaNavInternal,\n SearchIndexerOptions,\n} from \"../types\"\n\nimport {\n DocPropsIndexer,\n filterFileGlob,\n getCategoriesFromPathSegments,\n getPathnameFromPathSegments,\n getPathSegmentsFromFileName,\n getRouteMeta,\n type IndexedPage,\n type IndexedSection,\n MarkdownFileReader,\n MarkdownIndexer,\n NavBuilder,\n} from \"./services\"\nimport {transformRouteMetaArray} from \"./transform-route-meta-array\"\nimport {defined, fixPath} from \"./utils\"\n\nexport class SearchIndexer {\n private readonly docPropsIndexer: DocPropsIndexer\n private readonly markdownIndexer: MarkdownIndexer\n private readonly navBuilder: NavBuilder\n private readonly fileCache: MarkdownFileReader\n private readonly allowedHeadings: Set<string>\n private readonly metaJson: RouteMetaInternal\n private readonly routeMetaNav: Record<string, RouteMetaNavInternal> = {}\n\n get cachedFileCount(): number {\n return this.fileCache.cachedFileCount\n }\n\n get pageDocProps(): Record<string, Record<string, QuiPropTypes>> {\n return this._pageDocProps\n }\n private _pageDocProps: Record<string, Record<string, QuiPropTypes>> = {}\n\n get mdxFileCount(): number {\n return this._mdxFileCount\n }\n private _mdxFileCount: number = 0\n\n get navItems(): NavItem[] {\n return this.navBuilder.navItems\n }\n\n get pageMap(): PageMap {\n return this._pageMap\n }\n private _pageMap: PageMap = {}\n\n get searchIndex(): PageSection[] {\n return this._searchIndex\n }\n private _searchIndex: PageSection[] = []\n\n reset(): void {\n this.fileCache.reset()\n this._pageMap = {}\n this._searchIndex = []\n }\n\n constructor(\n public config: SearchIndexerOptions,\n public logWarnings = true,\n // enable composition by making these classes replaceable\n addons: {\n docPropsIndexer?: DocPropsIndexer\n fileCache?: MarkdownFileReader\n markdownIndexer?: MarkdownIndexer\n navBuilder?: NavBuilder\n } = {},\n ) {\n this.allowedHeadings = new Set<string>(\n Array.from(config?.headings || [\"h2\", \"h3\", \"h4\"]),\n )\n this.metaJson = transformRouteMetaArray(\n this.config.navConfig ?? [],\n this.routeMetaNav,\n )\n\n this.markdownIndexer =\n addons.markdownIndexer || new MarkdownIndexer(this.allowedHeadings)\n this.navBuilder =\n addons.navBuilder || new NavBuilder(this.metaJson, this.routeMetaNav)\n this.docPropsIndexer =\n addons.docPropsIndexer ||\n new DocPropsIndexer(this.config.typeDocProps ?? {})\n this.fileCache =\n addons.fileCache ||\n new MarkdownFileReader(\n process.env.NODE_ENV === \"development\" && !this.config.disableCache,\n )\n }\n\n /**\n * Resolves a page's properties from the combined frontmatter and RouteMeta.\n * RouteMeta properties take precedence.\n */\n private getPageEntry(\n filepath: string,\n frontmatter: Partial<PageFrontmatter>,\n ): PageSection {\n const pagePath = filepath.replace(this.config.srcDir, \"\")\n\n const pathSegments = getPathSegmentsFromFileName(\n pagePath,\n this.config.pageDirectory,\n this.config.routingStrategy,\n )\n\n const pathname = getPathnameFromPathSegments(pathSegments)\n\n const routeMeta =\n getRouteMeta(\n pathSegments.length === 0\n ? frontmatter.id\n ? [frontmatter.id]\n : [\"_index\"]\n : pathSegments,\n this.metaJson,\n ) ?? {}\n\n return {\n categories:\n frontmatter.categories ??\n getCategoriesFromPathSegments(\n pathSegments,\n this.metaJson,\n routeMeta?.title || frontmatter.title || \"\",\n ),\n hidden: defined(routeMeta.hidden) ? routeMeta.hidden : frontmatter.hidden,\n hideBreadcrumbs: defined(routeMeta.hideBreadcrumbs)\n ? routeMeta.hideBreadcrumbs\n : frontmatter.hideBreadcrumbs,\n hideFromSearch: defined(routeMeta.hideFromSearch)\n ? routeMeta.hideFromSearch\n : frontmatter.hideFromSearch,\n hidePageLinks: defined(routeMeta.hidePageLinks)\n ? routeMeta.hidePageLinks\n : frontmatter.hidePageLinks,\n hideSideNav: defined(routeMeta.hideSideNav)\n ? routeMeta.hideSideNav\n : frontmatter.hideSideNav,\n hideToc: defined(routeMeta.hideToc)\n ? routeMeta.hideToc\n : frontmatter.hideToc,\n id: pagePath,\n pathname,\n pathSegments,\n restricted: defined(routeMeta.restricted)\n ? routeMeta.restricted\n : frontmatter.restricted,\n title: defined(routeMeta.title)\n ? routeMeta.title || \"\"\n : frontmatter.title || \"\",\n }\n }\n\n /**\n * Parses an MDX file to extract the site data for the nav items, doc props,\n * breadcrumbs, and search index.\n */\n private compileMdxFile(filepath: string): PageSection[] {\n const {cached, fileContents, frontmatter} =\n this.fileCache.readFile(filepath)\n\n this.docPropsIndexer.reset()\n this.markdownIndexer.reset()\n\n const defaultSection: PageSection = this.getPageEntry(filepath, frontmatter)\n if (!defaultSection.categories.length && defaultSection.title) {\n defaultSection.categories = [defaultSection.title]\n }\n\n if (!defaultSection.hidden) {\n this.navBuilder.add(defaultSection, frontmatter)\n }\n\n this._pageMap[defaultSection.pathname] = defaultSection\n\n let indexedPage: IndexedPage\n\n try {\n indexedPage = cached?.page\n ? cached.page\n : this.markdownIndexer.parseMarkdown(fileContents, frontmatter)\n } catch (error) {\n console.debug(\n `${chalk.yellowBright.bold(\n \"Failed to parse mdx page content.\",\n )} ${chalk.blueBright.bold(filepath)}`,\n )\n\n return [defaultSection]\n }\n\n const {sections, toc} = indexedPage\n\n if (toc.length) {\n this._pageMap[defaultSection.pathname].toc = toc\n }\n\n let docPropSections: IndexedSection[] = []\n let docProps: Record<string, QuiPropTypes> = {}\n\n if (this.config.typeDocProps) {\n docPropSections =\n cached?.pageDocPropSections ||\n (this.docPropsIndexer.build(fileContents, toc) ?? [])\n docProps = cached?.pageDocProps || this.docPropsIndexer.getDocProps()\n }\n\n if (docPropSections.length) {\n this._pageDocProps[defaultSection.pathname] = docProps\n }\n\n this.fileCache.updateCache(filepath, fileContents, {\n frontmatter,\n page: indexedPage,\n pageDocProps: docProps,\n pageDocPropSections: docPropSections,\n })\n\n // omit entries from pages that are explicitly omitted from the index.\n if (frontmatter.hideFromSearch) {\n return [defaultSection]\n }\n\n if (!sections.length && !docPropSections.length) {\n return [defaultSection]\n }\n\n const sectionReturn: PageSection[] = [\n ...this.formatSections(sections, defaultSection, false),\n ]\n\n if (this.config.typeDocPropsOptions?.includeInSearchIndex) {\n sectionReturn.push(\n ...this.formatSections(docPropSections, defaultSection, true),\n )\n }\n\n return sectionReturn\n }\n\n private formatSections(\n sections: IndexedSection[],\n {toc: _toc, ...defaultSection}: PageSection,\n isDocProp: boolean,\n ): PageSection[] {\n return sections.map((section, index): PageSection => {\n const content = section.content.map((c) => c.text.join(\" \")).join(\" \")\n return {\n ...defaultSection,\n content: content || undefined,\n heading: section.heading?.textContent ?? defaultSection.title,\n headingLevel: section.heading?.headingLevel,\n href:\n section.heading &&\n (this.allowedHeadings.has(section.heading.tagName) || isDocProp)\n ? `${defaultSection.pathname}#${section.heading.id}`\n : defaultSection.pathname,\n id: `${defaultSection.id}-${index}${isDocProp ? \"-prop\" : \"\"}`,\n isDocProp: isDocProp || undefined,\n richContent: section.richContent,\n }\n })\n }\n\n private compileTsxFile(filepath: string) {\n const entry = this.getPageEntry(filepath, {})\n\n const routeMeta = getRouteMeta(\n entry.pathSegments.length === 0 ? [\"_index\"] : entry.pathSegments,\n this.metaJson,\n )\n\n if (!routeMeta) {\n return null\n }\n\n if (!entry.hidden) {\n this.navBuilder.add(entry, {}, routeMeta)\n }\n\n this._pageMap[entry.pathname] = entry\n\n return entry\n }\n\n buildIndex(inputFileGlob: string[], logWarnings: boolean = true): void {\n this.logWarnings = logWarnings\n this.fileCache.logWarnings = logWarnings\n // Windows path fix\n const fileGlob = inputFileGlob.map(fixPath)\n this.navBuilder.reset()\n this.reset()\n\n const mdxFileGlob = filterFileGlob(\n fileGlob,\n \"mdx\",\n this.config.srcDir,\n this.config.routingStrategy,\n )\n\n this._mdxFileCount = mdxFileGlob.length\n const mdxIndex = mdxFileGlob.map((file) => this.compileMdxFile(file)).flat()\n\n filterFileGlob(\n fileGlob,\n \"tsx\",\n this.config.srcDir,\n this.config.routingStrategy,\n ).map((file) => this.compileTsxFile(file))\n\n this._searchIndex.push(...mdxIndex.filter((entry) => !entry.hideFromSearch))\n\n this.navBuilder.build()\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport type {MdxJsxAttribute} from \"mdast-util-mdx-jsx\"\nimport remarkMdx from \"remark-mdx\"\nimport remarkParse from \"remark-parse\"\nimport remarkStringify from \"remark-stringify\"\nimport {type Plugin, unified} from \"unified\"\nimport {visit} from \"unist-util-visit\"\n\nimport {\n type PageDocProps,\n type PageHeading,\n type PagePropType,\n UniqueIdService,\n} from \"@qualcomm-ui/mdx-common\"\nimport type {\n QuiPropDeclaration,\n QuiPropTypes,\n} from \"@qualcomm-ui/typedoc-common\"\n\nimport type {IndexedSection} from \"../markdown\"\n\nfunction extractPickPropsRecord(\n node: MdxJsxAttribute,\n): Record<string, string[]> | null {\n if (\n node.name !== \"unionWithPick\" ||\n !node.value ||\n typeof node.value === \"string\"\n ) {\n return null\n }\n\n const estree = node.value.data?.estree\n if (!estree?.body?.[0] || estree.body[0].type !== \"ExpressionStatement\") {\n return null\n }\n\n const expression = estree.body[0].expression\n if (expression.type !== \"ObjectExpression\") {\n return null\n }\n\n const result: Record<string, string[]> = {}\n\n for (const property of expression.properties) {\n if (property.type !== \"Property\" || property.key.type !== \"Identifier\") {\n continue\n }\n\n if (property.value.type !== \"ArrayExpression\") {\n continue\n }\n\n const key = property.key.name\n const values: string[] = []\n\n for (const element of property.value.elements) {\n if (element?.type === \"Literal\" && typeof element.value === \"string\") {\n values.push(element.value)\n }\n }\n\n result[key] = values\n }\n\n return result\n}\n\nconst targetMdxElements: string[] = [\n \"TypeDocProps\",\n \"TypeDocAttributes\",\n \"TypeDocAngularAttributes\",\n]\n\ninterface DocPropEntry {\n name: string\n omitFrom?: string[]\n}\n\nexport class DocPropsIndexer {\n docPropsEntries: DocPropEntry[] = []\n idService: UniqueIdService = new UniqueIdService()\n private readonly props: Record<string, QuiPropTypes>\n private pageDocProps: PageDocProps = {}\n\n constructor(props: Record<string, QuiPropTypes>) {\n this.props = props\n }\n\n reset(): void {\n this.idService.reset()\n this.docPropsEntries = []\n }\n\n private extractNamesFromAttribute(attr: MdxJsxAttribute): string[] {\n if (!attr.value) {\n return []\n }\n\n if (typeof attr.value === \"string\") {\n return [attr.value]\n }\n\n if (attr.value.type === \"mdxJsxAttributeValueExpression\") {\n const estree = attr.value.data?.estree\n if (!estree?.body?.[0] || estree.body[0].type !== \"ExpressionStatement\") {\n return []\n }\n\n const expression = estree.body[0].expression\n\n if (expression.type === \"ArrayExpression\") {\n const names: string[] = []\n for (const element of expression.elements) {\n if (\n element?.type === \"Literal\" &&\n typeof element.value === \"string\"\n ) {\n names.push(element.value)\n }\n }\n return names\n }\n\n // Handle single string expression\n if (\n expression.type === \"Literal\" &&\n typeof expression.value === \"string\"\n ) {\n return [expression.value]\n }\n }\n\n return []\n }\n\n /**\n * Finds all JSX `<TypeDocProps />` nodes on the current page and adds their names\n * to an array. Once all nodes have been collected, we process them into\n * `PageSection` entries for the search index.\n */\n getTypeDocPropsNodes: Plugin = () => {\n return (tree, _file, done) => {\n visit(tree, \"mdxJsxFlowElement\", (node: any) => {\n if (node && \"name\" in node && targetMdxElements.includes(node.name)) {\n const nameAttr = node.attributes?.find(\n (attr: MdxJsxAttribute) => attr.name === \"name\",\n )\n const omitFromAttr = node.attributes?.find(\n (attr: MdxJsxAttribute) => attr.name === \"omitFrom\",\n )\n const omitFrom = omitFromAttr\n ? this.extractNamesFromAttribute(omitFromAttr)\n : undefined\n\n if (nameAttr) {\n const names = this.extractNamesFromAttribute(nameAttr)\n for (const name of names) {\n this.docPropsEntries.push({name, omitFrom})\n if (name.endsWith(\"Props\")) {\n // also index the corresponding component for lookup on this page.\n this.docPropsEntries.push({name: name.slice(0, -5), omitFrom})\n }\n }\n }\n\n const unionWithPickAttr: MdxJsxAttribute = node.attributes?.find(\n (attr: MdxJsxAttribute) => attr.name === \"unionWithPick\",\n )\n if (unionWithPickAttr) {\n try {\n const unionWithPick = extractPickPropsRecord(unionWithPickAttr)\n if (unionWithPick) {\n this.docPropsEntries.push(\n ...Object.keys(unionWithPick).map((entry) => ({\n name: entry,\n omitFrom,\n })),\n )\n }\n } catch (e) {}\n }\n }\n })\n done()\n }\n }\n\n build(fileContents: string, toc: PageHeading[]): IndexedSection[] | null {\n // parse the Markdown into an AST\n unified()\n .use(remarkMdx)\n // find the TypeDocProp nodes\n .use(this.getTypeDocPropsNodes)\n .use(remarkParse)\n .use(remarkStringify)\n .processSync(fileContents)\n\n if (!this.docPropsEntries.length) {\n return null\n }\n\n for (const item of toc) {\n this.idService.add(item.id)\n }\n\n return this.docPropsEntries\n .map((entry): IndexedSection[] => {\n const propTypes = this.props[entry.name]\n if (!propTypes) {\n return []\n }\n\n const omittedProps = new Set<string>(\n (entry.omitFrom ?? [])\n .map((entry) => {\n const propTypes = this.props[entry]\n if (!propTypes) {\n return []\n }\n return [\n propTypes.props,\n propTypes.input,\n propTypes.output,\n propTypes.publicMethods,\n ].reduce((acc: string[], current) => {\n if (current) {\n acc.push(...current.map((prop) => prop.name))\n }\n return acc\n }, [])\n })\n .flat(1)\n .filter(Boolean),\n )\n\n const sections: IndexedSection[] = []\n\n const assembleProps = (\n propsInput: QuiPropDeclaration[] | undefined,\n ): PagePropType[] | undefined => {\n if (!propsInput) {\n return undefined\n }\n const props: PagePropType[] = []\n for (const prop of propsInput) {\n if (omittedProps.has(prop.name)) {\n continue\n }\n const id = this.idService.add(prop.name)\n props.push({...prop, id})\n sections.push(this.assembleProp(prop, id))\n }\n return props\n }\n\n this.pageDocProps[entry.name] = {\n ...this.props[entry.name],\n input: assembleProps(propTypes.input),\n output: assembleProps(propTypes.output),\n props: assembleProps(propTypes.props),\n publicMethods: assembleProps(propTypes.publicMethods),\n }\n return sections\n })\n .flat()\n }\n\n getDocProps(): PageDocProps {\n return this.docPropsEntries.reduce((acc: PageDocProps, entry) => {\n const propTypes = this.pageDocProps[entry.name]\n // TODO: convert code comments to HTML using rehype. Remove markdown-to-jsx\n // in @qualcomm-ui/react-mdx library.\n if (propTypes) {\n acc[entry.name] = propTypes\n }\n return acc\n }, {})\n }\n\n private assembleProp(prop: QuiPropDeclaration, id: string): IndexedSection {\n const name = prop.name\n\n const heading: PageHeading = {\n headingLevel: 4,\n id,\n tagName: \"a\",\n textContent: name,\n }\n\n const comment = prop.comment\n if (!comment) {\n return {content: [], heading, richContent: []}\n }\n\n const content = {\n tagName: \"p\",\n text: [\n comment.summary\n .map((entry) => entry.text.replaceAll(\"\\n\", \" \"))\n .join(\"\"),\n ],\n }\n return {content: [content], heading, richContent: []}\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport chalk from \"chalk\"\nimport {createHash} from \"node:crypto\"\nimport {readFileSync} from \"node:fs\"\nimport remarkFrontmatter from \"remark-frontmatter\"\nimport remarkParse from \"remark-parse\"\nimport remarkParseFrontmatter from \"remark-parse-frontmatter\"\nimport remarkStringify from \"remark-stringify\"\nimport {unified} from \"unified\"\n\nimport type {PageFrontmatter} from \"@qualcomm-ui/mdx-common\"\nimport type {QuiPropTypes} from \"@qualcomm-ui/typedoc-common\"\n\nimport {frontmatterSchema} from \"../../utils\"\n\nimport type {IndexedPage, IndexedSection} from \"./markdown.types\"\n\ninterface PageCache {\n frontmatter: PageFrontmatter\n md5: string\n page: IndexedPage\n pageDocProps: Record<string, QuiPropTypes>\n pageDocPropSections: IndexedSection[]\n}\n\nexport class MarkdownFileReader {\n cachedFileCount = 0\n logWarnings = true\n private mdxCache: Record<string, PageCache> = {}\n\n constructor(public enabled: boolean) {}\n\n private hash(input: string) {\n return createHash(\"md5\").update(input).digest(\"hex\")\n }\n\n reset(): void {\n this.cachedFileCount = 0\n }\n\n private checkCache(\n filepath: string,\n fileContents: string,\n ): Omit<PageCache, \"md5\"> | undefined {\n if (!this.enabled) {\n return\n }\n\n const fileMd5 = this.hash(fileContents)\n const cached = this.mdxCache[filepath]\n\n if (cached?.md5 !== fileMd5) {\n return\n }\n\n this.cachedFileCount++\n\n return {\n frontmatter: cached.frontmatter,\n page: cached.page,\n pageDocProps: cached.pageDocProps,\n pageDocPropSections: cached.pageDocPropSections,\n }\n }\n\n readFile(filepath: string): {\n cached: Omit<PageCache, \"md5\"> | undefined\n fileContents: string\n frontmatter: PageFrontmatter\n } {\n const fileContents = readFileSync(filepath, \"utf-8\")\n\n const cached = this.checkCache(filepath, fileContents)\n\n let file:\n | {data: {frontmatter: PageFrontmatter}}\n | ReturnType<typeof unified.processSync>\n if (cached?.frontmatter) {\n file = {data: {frontmatter: cached.frontmatter}}\n } else {\n // only parse the yaml section because we just need the frontmatter at this\n // stage.\n const yamlSection = fileContents.substring(\n 0,\n fileContents.indexOf(\"\\n---\") + 4,\n )\n file = unified()\n .use(remarkParse)\n .use(remarkFrontmatter, [\"yaml\"])\n .use(remarkParseFrontmatter)\n .use(remarkStringify)\n .processSync(yamlSection)\n }\n\n const frontmatter: PageFrontmatter = (file.data\n .frontmatter as PageFrontmatter) ?? {title: \"\"}\n\n if (!frontmatter.title) {\n const lines = fileContents.split(\"\\n\")\n const fallbackTitle = lines.find((line) => line.startsWith(\"# \"))\n if (fallbackTitle) {\n frontmatter.title = fallbackTitle.substring(2).trim()\n }\n }\n // TODO: permit omitting title from frontmatter if provided in the navConfig\n if (!frontmatter.title && this.logWarnings) {\n console.debug(chalk.red.bold(\"Missing title:\"), filepath)\n }\n\n const parsedFrontmatter = frontmatterSchema.safeParse(frontmatter)\n\n if (!parsedFrontmatter.success) {\n console.debug(\n `${chalk.redBright.bold(\"Invalid frontmatter detected for file\")}: ${filepath}\\n`,\n )\n console.debug(chalk.redBright.bold(\"Please check the following fields:\"))\n parsedFrontmatter.error.issues.map((issue: any) => {\n console.debug(`- ${issue.path.join(\".\")}`)\n })\n }\n\n return {cached, fileContents, frontmatter}\n }\n\n updateCache(\n filepath: string,\n fileContents: string,\n cacheData: Omit<PageCache, \"md5\">,\n ): void {\n if (this.enabled) {\n this.mdxCache[filepath] = {...cacheData, md5: this.hash(fileContents)}\n }\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport type {Element} from \"hast\"\nimport {fromHtml} from \"hast-util-from-html\"\nimport {toText} from \"hast-util-to-text\"\nimport {clone, size} from \"lodash-es\"\nimport rehypeParse from \"rehype-parse\"\nimport rehypeStringify from \"rehype-stringify\"\nimport remarkGfm from \"remark-gfm\"\nimport remarkMdx from \"remark-mdx\"\nimport remarkParse from \"remark-parse\"\nimport remarkRehype from \"remark-rehype\"\nimport {unified} from \"unified\"\n\nimport type {\n PageFrontmatter,\n PageHeading,\n RichContentNode,\n} from \"@qualcomm-ui/mdx-common\"\n\nimport {rehypeSlug} from \"../../../rehype/rehype-slug\"\nimport {remarkAlerts} from \"../../../remark/remark-alerts\"\n\nimport type {IndexedPage, IndexedSection} from \"./markdown.types\"\nimport {remarkRemoveMermaidCodeBlocks} from \"./remark-remove-code-blocks\"\nimport {remarkRemoveJsx} from \"./remark-remove-jsx\"\n\n/**\n * Parses an html string into an AST and builds the search index from the tree.\n */\nexport class MarkdownIndexer {\n private sections: IndexedSection[] = []\n private currentSection!: IndexedSection\n private readonly headingLevels: Set<string>\n\n reset(): void {\n this.sections = []\n this._toc = []\n this.resetSection()\n }\n\n resetSection(): void {\n this.currentSection = {\n content: [],\n heading: null,\n richContent: [],\n }\n }\n\n get toc(): PageHeading[] {\n return this._toc\n }\n private _toc: PageHeading[] = []\n\n constructor(headingLevels: Set<string>) {\n this.resetSection()\n this.headingLevels = headingLevels\n }\n\n private appendTocItem(heading: PageHeading) {\n this._toc.push(heading)\n }\n\n private warn(...data: any[]) {\n if (process.env.DEBUG) {\n console.warn(...data)\n }\n // TODO: remove\n console.warn(...data)\n }\n\n private isHeading(element: Element): boolean {\n return this.headingLevels.has(element.tagName)\n }\n\n private isRootHeading(element: Element) {\n return element.tagName === \"h1\"\n }\n\n /**\n * Parses a heading Element node into the indexed heading data structure.\n */\n private parseHeading(headingElement: Element): PageHeading {\n const id = headingElement.properties.id\n const text = toText(headingElement)\n\n return {\n headingLevel: parseInt(headingElement.tagName.charAt(1)),\n id: id ? `${id}` : \"\",\n tagName: headingElement.tagName,\n textContent: text,\n }\n }\n\n private parseElementNode(element: Element) {\n const isRootHeading = this.isRootHeading(element)\n if (this.isHeading(element) || isRootHeading) {\n const currentSection = this.currentSection\n if (currentSection.heading) {\n // the old section is now done, so we add it and start a new one.\n this.sections.push(clone(this.currentSection))\n this.resetSection()\n }\n const heading = this.parseHeading(element)\n if (!isRootHeading) {\n this.appendTocItem(heading)\n }\n this.currentSection.heading = heading\n return\n }\n\n this.currentSection.richContent.push(element as RichContentNode)\n\n const text = toText(element, {whitespace: \"pre-wrap\"})\n .replaceAll(\"\\n\", \"\\t\")\n .split(\"\\t\")\n .filter(size)\n\n if (text.length) {\n this.currentSection.content.push({\n tagName: element.tagName,\n text,\n })\n }\n }\n\n parseMarkdown(\n fileContents: string | Buffer,\n frontmatter: PageFrontmatter,\n ): IndexedPage {\n const file = unified()\n .use(remarkMdx)\n .use(remarkRemoveJsx)\n .use(remarkRemoveMermaidCodeBlocks)\n .use(remarkParse)\n .use(remarkGfm)\n .use(remarkAlerts)\n .use(remarkRehype)\n .use(rehypeStringify)\n .processSync(fileContents)\n\n let contents = file.toString()\n\n contents = contents.substring(contents.indexOf(\"<h1>\"))\n\n for (const [key, value] of Object.entries(frontmatter)) {\n if (typeof value === \"string\" || typeof value === \"number\") {\n contents = contents.replaceAll(`frontmatter.${key}`, `${value}`)\n }\n }\n\n const htmlAst = unified()\n .data(\"settings\", {fragment: true})\n .use(rehypeParse)\n .use(rehypeStringify)\n .use(rehypeSlug)\n .processSync(contents)\n\n contents = htmlAst.toString()\n\n return this.build(contents)\n }\n\n build(html: string): IndexedPage {\n const tree = fromHtml(html, {fragment: true})\n\n for (const child of tree.children) {\n if (child.type === \"element\") {\n this.parseElementNode(child)\n }\n }\n\n // The parser processes sections in order and only appends the content once a\n // new section is encountered. We manually account for the final section here.\n if (this.currentSection.heading?.textContent) {\n this.sections.push(clone(this.currentSection))\n }\n\n return {\n sections: this.sections,\n toc: this.toc,\n }\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport type {Root} from \"hast\"\nimport {headingRank} from \"hast-util-heading-rank\"\nimport {toString} from \"hast-util-to-string\"\nimport type {Plugin} from \"unified\"\nimport {visit} from \"unist-util-visit\"\n\nexport interface RehypeSlugOptions {\n /**\n * @default ['h2', 'h3', 'h4']\n */\n allowedHeadings?: string[]\n prefix?: string\n}\n\nconst emptyOptions: RehypeSlugOptions = {}\n\n/**\n * Converts heading text to URL-friendly slugs. Converts multi-word and PascalCase\n * text to kebab-case. Lowercases single sentence-case words. Appends counter for\n * duplicate slugs.\n */\nexport const rehypeSlug: Plugin<[RehypeSlugOptions?], Root> = (\n options: RehypeSlugOptions | null | undefined,\n) => {\n const settings = options || emptyOptions\n const prefix = settings.prefix || \"\"\n const allowedHeadings = new Set<string>(\n settings.allowedHeadings || [\"h2\", \"h3\", \"h4\"],\n )\n const seenIds = new Map<string, number>()\n\n function createSlug(text: string): string {\n const cleaned = text\n .replace(/[<>]/g, \"\")\n .replace(/[^\\w\\s-]/g, \"\")\n .trim()\n\n let slug: string\n if (cleaned.includes(\" \")) {\n slug = cleaned\n .toLowerCase()\n .replace(/\\s+/g, \"-\")\n .replace(/^-+|-+$/g, \"\")\n } else if ((cleaned.match(/[A-Z]/g) || []).length >= 2) {\n slug = cleaned\n .replace(/([a-z0-9])([A-Z])/g, \"$1-$2\")\n .replace(/([A-Z]+)([A-Z][a-z])/g, \"$1-$2\")\n .toLowerCase()\n } else {\n slug = cleaned.toLowerCase()\n }\n\n const count = seenIds.get(slug) || 0\n seenIds.set(slug, count + 1)\n return count > 0 ? `${slug}-${count}` : slug\n }\n\n return (tree) => {\n seenIds.clear()\n visit(tree, \"element\", function (node) {\n if (\n headingRank(node) &&\n !node.properties.id &&\n allowedHeadings.has(node.tagName)\n ) {\n node.properties.id = prefix + createSlug(toString(node))\n }\n })\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport type {PhrasingContent, Root} from \"mdast\"\nimport type {Plugin} from \"unified\"\nimport {visit} from \"unist-util-visit\"\n\nconst alertLegacyRegex = /^\\[!(NOTE|TIP|SUCCESS|WARNING|CAUTION)(\\/.*)?\\]/i\n\n/**\n * Alerts are a Markdown extension based on the blockquote syntax that you can use\n * to emphasize critical information. On GitHub, they are displayed with distinctive\n * colors and icons to indicate the significance of the content.\n * https://docs.github.com/en/get-started/writing-on-github/getting-started-with-writing-and-formatting-on-github/basic-writing-and-formatting-syntax#alerts\n */\nexport const remarkAlerts: Plugin<[], Root> = () => {\n return (tree) => {\n visit(tree, \"blockquote\", (node) => {\n let alertType = \"\"\n let title = \"\"\n let isNext = true\n const child = node.children.map((item) => {\n if (isNext && item.type === \"paragraph\") {\n const firstNode = item.children[0]\n const text = firstNode.type === \"text\" ? firstNode.value : \"\"\n const reg = alertLegacyRegex\n const match = text.match(reg)\n if (match) {\n isNext = false\n alertType = match[1].toLocaleLowerCase()\n title = match[2] || alertType.toLocaleUpperCase()\n if (text.includes(\"\\n\")) {\n item.children[0] = {\n type: \"text\",\n value: text.replace(reg, \"\").replace(/^\\n+/, \"\"),\n }\n }\n\n if (!text.includes(\"\\n\")) {\n const itemChild: PhrasingContent[] = []\n item.children.forEach((item: any, idx: number) => {\n if (idx === 0) {\n return\n }\n if (idx === 1 && item.type === \"break\") {\n return\n }\n itemChild.push(item)\n })\n item.children = [...itemChild]\n }\n }\n }\n return item\n })\n\n title = title.replace(/^\\//, \"\")\n\n if (!!alertType) {\n node.data = {\n hName: \"div\",\n hProperties: {\n class: `qui-notification__root`,\n \"data-emphasis\":\n alertToEmphasis[alertType as IconType] || \"neutral\",\n \"data-orientation\": \"vertical\",\n dir: \"auto\",\n },\n }\n node.children = [\n {\n children: [getAlertIcon(alertType as IconType)],\n data: {\n hProperties: {\n class: \"qui-notification__icon\",\n \"data-part\": \"status-icon\",\n \"data-scope\": \"inline-notification\",\n },\n },\n type: \"paragraph\",\n },\n {\n children: [\n {\n type: \"text\",\n value: title,\n },\n ],\n data: {\n hProperties: {\n class: \"qui-notification__label\",\n dir: \"auto\",\n },\n },\n type: \"paragraph\",\n },\n {\n children: child,\n data: {\n hName: \"div\",\n hProperties: {\n class: `qui-notification__description`,\n dir: \"auto\",\n },\n },\n type: \"blockquote\",\n },\n ]\n }\n })\n }\n}\n\nexport function getAlertIcon(type: IconType): PhrasingContent {\n const svgChildren = svgData[type] ?? []\n return {\n children: svgChildren,\n data: {\n hName: \"svg\",\n hProperties: {\n ariaHidden: \"true\",\n class: \"lucide\",\n fill: \"transparent\",\n height: \"20\",\n stroke: \"currentColor\",\n strokeLinecap: \"round\",\n strokeLinejoin: \"round\",\n strokeWidth: \"2\",\n viewBox: \"0 0 24 24\",\n width: \"20\",\n },\n },\n type: \"emphasis\",\n }\n}\n\ntype IconType = \"note\" | \"tip\" | \"success\" | \"warning\" | \"caution\"\n\n/**\n * These SVG children correspond to the lucide icons matching our\n * {@link https://react.qui.qualcomm.com/components/inline-alert | Alert} component.\n */\nconst svgData: Record<IconType, PhrasingContent[]> = {\n caution: [\n {\n children: [],\n data: {\n hName: \"polygon\",\n hProperties: {\n points:\n \"7.86 2 16.14 2 22 7.86 22 16.14 16.14 22 7.86 22 2 16.14 2 7.86 7.86 2\",\n },\n },\n type: \"emphasis\",\n },\n {\n children: [],\n data: {\n hName: \"line\",\n hProperties: {\n x1: \"12\",\n x2: \"12\",\n y1: \"8\",\n y2: \"12\",\n },\n },\n type: \"emphasis\",\n },\n {\n children: [],\n data: {\n hName: \"line\",\n hProperties: {\n x1: \"12\",\n x2: \"12.01\",\n y1: \"16\",\n y2: \"16\",\n },\n },\n type: \"emphasis\",\n },\n ],\n note: [\n {\n children: [],\n data: {\n hName: \"circle\",\n hProperties: {\n cx: \"12\",\n cy: \"12\",\n r: \"10\",\n },\n },\n type: \"emphasis\",\n },\n {\n children: [],\n data: {\n hName: \"path\",\n hProperties: {\n d: \"M12 16v-4\",\n },\n },\n type: \"emphasis\",\n },\n {\n children: [],\n data: {\n hName: \"path\",\n hProperties: {\n d: \"M12 8h.01\",\n },\n },\n type: \"emphasis\",\n },\n ],\n success: [\n {\n children: [],\n data: {\n hName: \"path\",\n hProperties: {\n d: \"M20 6 9 17l-5-5\",\n },\n },\n type: \"emphasis\",\n },\n ],\n tip: [\n {\n children: [],\n data: {\n hName: \"path\",\n hProperties: {\n d: \"M15 14c.2-1 .7-1.7 1.5-2.5 1-.9 1.5-2.2 1.5-3.5A6 6 0 0 0 6 8c0 1 .2 2.2 1.5 3.5.7.7 1.3 1.5 1.5 2.5\",\n },\n },\n type: \"emphasis\",\n },\n {\n children: [],\n data: {\n hName: \"path\",\n hProperties: {\n d: \"M9 18h6\",\n },\n },\n type: \"emphasis\",\n },\n {\n children: [],\n data: {\n hName: \"path\",\n hProperties: {\n d: \"M10 22h4\",\n },\n },\n type: \"emphasis\",\n },\n ],\n warning: [\n {\n children: [],\n data: {\n hName: \"path\",\n hProperties: {\n d: \"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3\",\n },\n },\n type: \"emphasis\",\n },\n {\n children: [],\n data: {\n hName: \"path\",\n hProperties: {\n d: \"M12 9v4\",\n },\n },\n type: \"emphasis\",\n },\n {\n children: [],\n data: {\n hName: \"path\",\n hProperties: {\n d: \"M12 17h.01\",\n },\n },\n type: \"emphasis\",\n },\n ],\n}\n\nconst alertToEmphasis: Record<IconType, string> = {\n caution: \"danger\",\n note: \"neutral\",\n success: \"success\",\n tip: \"info\",\n warning: \"warning\",\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport type {Plugin} from \"unified\"\nimport {remove} from \"unist-util-remove\"\n\nexport const remarkRemoveMermaidCodeBlocks: Plugin = () => {\n return (tree, _file, done) => {\n remove(tree, (node: any) => node.type === \"code\" && node.lang === \"mermaid\")\n done()\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport type {Plugin} from \"unified\"\nimport {remove} from \"unist-util-remove\"\n\nexport const remarkRemoveJsx: Plugin = () => {\n return (tree, _file, done) => {\n remove(tree, \"mdxjsEsm\")\n remove(tree, \"mdxJsxFlowElement\")\n done()\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport type {RouteMetaEntryInternal, RouteMetaInternal} from \"../../../types\"\n\n/**\n * Retrieves the route metadata for a given path based on its path segments.\n */\nexport function getRouteMeta(\n pathSegments: string[],\n metaJson: RouteMetaInternal,\n): RouteMetaEntryInternal | undefined | null {\n const routeMeta = metaJson[pathSegments[0]]\n if (!routeMeta) {\n // backup, fetch using id if provided\n return undefined\n }\n\n if (pathSegments.length === 1) {\n return routeMeta\n }\n\n return pathSegments\n .slice(1)\n .reduce((acc: RouteMetaEntryInternal | undefined | null, segment) => {\n return acc?.children?.[segment]\n }, routeMeta)\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport {capitalCase} from \"change-case\"\nimport {sortBy} from \"lodash-es\"\nimport {v4 as uuidv4} from \"uuid\"\n\nimport type {\n NavItem,\n PageFrontmatter,\n PageSection,\n} from \"@qualcomm-ui/mdx-common\"\n\nimport type {\n NavMeta,\n RouteMetaEntryInternal,\n RouteMetaInternal,\n} from \"../../../types\"\nimport {defined} from \"../../utils\"\n\nimport {getRouteMeta} from \"./get-route-meta\"\n\ninterface InitialRoute {\n pageFrontmatter: Partial<PageFrontmatter>\n pageSection: PageSection\n routeMeta?: RouteMetaEntryInternal\n}\n\n/**\n * Given a flat remix route structure, computes nested navigation items for the QUI\n * side nav.\n */\nexport class NavBuilder {\n private initialRoutes: InitialRoute[] = []\n private flatNavItems: NavItem[] = []\n\n get navItems(): NavItem[] {\n return this._navItems\n }\n private _navItems: NavItem[] = []\n\n private readonly metaJson: RouteMetaInternal\n private readonly navMeta: Record<number, NavMeta>\n\n constructor(metaJson: RouteMetaInternal, navMeta: Record<number, NavMeta>) {\n this.navMeta = navMeta\n this.metaJson = metaJson\n }\n\n add(\n pageSection: PageSection,\n pageFrontmatter: Partial<PageFrontmatter>,\n routeMeta?: RouteMetaEntryInternal,\n ): void {\n this.initialRoutes.push({pageFrontmatter, pageSection, routeMeta})\n }\n\n reset(): void {\n this.initialRoutes = []\n this.flatNavItems = []\n this._navItems = []\n }\n\n /**\n * Sorts nav items. Nav items with an order defined take precedence over nav items\n * without an order. Nav items with the same order are sorted alphabetically by\n * title.\n */\n private navItemSort(a: NavItem, b: NavItem, groupOrder?: string[]) {\n if (a.depth !== b.depth) {\n return a.depth - b.depth\n }\n\n if (a.order && !b.order) {\n return -1\n }\n if (!a.order && b.order) {\n return 1\n } else if (a.order && b.order && a.order !== b.order) {\n return a.order - b.order\n }\n\n if (groupOrder && a.group && b.group) {\n const aIndex = a.group ? groupOrder.indexOf(a.group) : -1\n const bIndex = b.group ? groupOrder.indexOf(b.group) : -1\n\n if (aIndex === bIndex) {\n // continue\n } else if (aIndex !== -1 && bIndex !== -1) {\n return aIndex - bIndex\n } else if (aIndex !== -1) {\n return -1\n } else if (bIndex !== -1) {\n return 1\n }\n }\n\n // group items with the same group\n if (a.group !== b.group) {\n if (!a.group && b.group) {\n return -1\n }\n if (a.group && !b.group) {\n return 1\n }\n if (a.group && b.group) {\n return a.group.localeCompare(b.group)\n }\n }\n\n return a.title.localeCompare(b.title)\n }\n\n resolveSideNavTitle(\n frontmatter: Partial<PageFrontmatter>,\n routeMeta: Partial<RouteMetaEntryInternal>,\n fallback: string,\n ): string {\n return (\n (defined(routeMeta.sideNavTitle)\n ? routeMeta.sideNavTitle || \"\"\n : frontmatter.sideNavTitle || \"\") || fallback\n )\n }\n\n /**\n * Builds a flat list of nav items from the MDX pages and _meta.json. If a page\n * does not exist, it is not added to the side nav (even if it has an entry in\n * _meta.json).\n */\n private buildNavItem({\n pageFrontmatter,\n pageSection: {pathname, pathSegments, title},\n routeMeta: routeMetaParam,\n }: InitialRoute) {\n const id = pageFrontmatter?.id || \"\"\n\n // handle home page (this route does not have path segments)\n if (!pathSegments.length && pathname === \"/\") {\n const routeMeta =\n routeMetaParam || getRouteMeta(id ? [id] : [], this.metaJson)\n if (!routeMeta) {\n return\n }\n\n this.flatNavItems.push({\n depth: 1,\n expanded: routeMeta?.expanded || false,\n id: `/`,\n order: routeMeta?.order,\n pathname,\n pathSegments: [],\n title: this.resolveSideNavTitle(\n pageFrontmatter,\n routeMeta,\n routeMeta?.title || title,\n ),\n })\n }\n\n pathSegments.forEach((segment, index) => {\n const depth = index + 1\n\n // we only add an item if it doesn't already exist, which we determine by\n // comparing the path segments iteratively.\n const navItem = this.flatNavItems.find((item) =>\n pathSegments\n .slice(0, depth)\n .every((value, i) => value === item.pathSegments[i]),\n )\n\n if (!navItem) {\n const isPage = index === pathSegments.length - 1\n const adjustedSegments = pathSegments.slice(0, depth)\n\n const routeMeta =\n getRouteMeta(\n isPage ? pathSegments : adjustedSegments,\n this.metaJson,\n ) ?? {}\n\n this.flatNavItems.push({\n depth,\n expanded: routeMeta?.expanded || false,\n group: isPage\n ? routeMeta.group || pageFrontmatter.group\n : routeMeta.group,\n id: `/${adjustedSegments.join(\"/\")}`,\n items: [],\n order: routeMeta?.order,\n pathname: isPage ? pathname : undefined,\n pathSegments: adjustedSegments,\n title: this.resolveSideNavTitle(\n pageFrontmatter,\n routeMeta,\n routeMeta?.title\n ? routeMeta.title\n : isPage\n ? title\n : capitalCase(segment),\n ),\n })\n }\n })\n }\n\n /**\n * Iterates through a nav item's path segments and ensures that all of its parent\n * elements exist in the recursive structure.\n */\n private ensureParent(navItem: NavItem) {\n const segments = navItem.pathSegments\n let items: NavItem[] = this.navItems\n let item: NavItem | undefined\n let prevItem: NavItem | undefined = undefined\n\n for (let i = 0; i < segments.length - 1; i++) {\n const segment = segments[i]\n item = items?.find((entry) => entry.pathSegments[i] === segment)\n if (item) {\n // point to the found item's children and keep iterating\n items = item.items ?? []\n prevItem = item\n continue\n }\n if (prevItem) {\n const pathSegments = segments.slice(0, i + 1)\n const routeMeta = getRouteMeta(pathSegments, this.metaJson)\n\n items = []\n const base = {\n depth: pathSegments.length,\n id: `/routes/${pathSegments.join(\"/\")}`,\n items,\n pathSegments,\n title: segment,\n }\n const newItem = routeMeta\n ? {\n ...base,\n expanded: routeMeta.expanded,\n order: routeMeta.order,\n restricted: routeMeta.restricted,\n title: routeMeta.title ?? segment,\n }\n : base\n prevItem.items = prevItem.items\n ? [...prevItem.items, newItem]\n : [newItem]\n }\n prevItem = item\n }\n }\n\n /**\n * Deeply inserts a nav item into the array, iterating through parent routes\n * (based on the pathSegments) and adding them if they don't exist.\n *\n * For example, given a leaf node 4 path segments deep, this function will create\n * all parent nav items as nested children of the top-most nav item.\n */\n private nestedInsert(\n item: NavItem,\n pathSegments: string[],\n items: NavItem[],\n ) {\n const segment = pathSegments[0]\n const parentItem = items.find(\n (parent) =>\n parent.pathSegments[parent.pathSegments.length - 1] === segment,\n )\n if (parentItem) {\n this.nestedInsert(item, pathSegments.slice(1), parentItem.items ?? [])\n } else if (pathSegments.length === 1) {\n items.push(item)\n }\n }\n\n private buildNestedNavItems() {\n for (let i = 0; i < this.flatNavItems.length; i++) {\n const navItem = this.flatNavItems[i]\n if (navItem.depth === 1) {\n this.navItems.push(navItem)\n continue\n }\n\n this.ensureParent(navItem)\n this.nestedInsert(navItem, navItem.pathSegments, this.navItems)\n }\n }\n\n private sortNestedNavItems(items: NavItem[], groupOrder?: string[]) {\n items.sort((a, b) => this.navItemSort(a, b, groupOrder))\n items.forEach((item) => {\n if (item.items?.length) {\n const meta = getRouteMeta(item.pathSegments, this.metaJson)\n this.sortNestedNavItems(item.items, meta?.groupOrder)\n }\n })\n }\n\n /**\n * To be called after every mdx page route has been added through the {@link add}\n * function.\n */\n build(): NavItem[] {\n // We need to process parent items first, so we sort by path segment. Routes\n // with shorter path segments will be processed first.\n sortBy(\n this.initialRoutes,\n (item) => item.pageSection.pathSegments.length,\n ).map((r) => this.buildNavItem(r))\n\n this.buildNestedNavItems()\n\n const rootMeta = getRouteMeta([], this.metaJson)\n this.sortNestedNavItems(this.navItems, rootMeta?.groupOrder)\n\n if (this.navMeta) {\n Object.entries(this.navMeta).forEach(([index, value]) => {\n this._navItems.splice(parseInt(index), 0, {\n depth: 1,\n id: uuidv4(),\n pathSegments: [],\n sectionTitle: value.sectionTitle,\n separator: value.separator,\n title: \"\",\n })\n })\n }\n\n this._navItems = this.groupNavItems(this.navItems)\n this._navItems = this.buildSearchMeta(this.navItems, [])\n return this.navItems\n }\n\n private groupNavItems(items: NavItem[]): NavItem[] {\n const result: NavItem[] = []\n const seenGroups = new Set<string>()\n\n for (const item of items) {\n if (item.group && !seenGroups.has(item.group)) {\n seenGroups.add(item.group)\n result.push({\n depth: item.depth,\n group: item.group,\n id: uuidv4(),\n pathSegments: [],\n sectionTitle: item.group,\n title: \"\",\n })\n }\n\n result.push({\n ...item,\n items: item.items ? this.groupNavItems(item.items) : undefined,\n })\n }\n\n return result\n }\n\n /**\n * Walks over the tree and builds search metadata using the nearest sectionTitle.\n */\n private buildSearchMeta(items: NavItem[], meta: string[]): NavItem[] {\n let sectionTitle = \"\"\n const results: NavItem[] = []\n\n for (const ogItem of items) {\n const item = {...ogItem}\n\n if (item.sectionTitle) {\n sectionTitle = item.sectionTitle\n } else if (item.separator) {\n sectionTitle = \"\"\n }\n\n if (!item.separator) {\n const currentMeta = sectionTitle ? [...meta, sectionTitle] : [...meta]\n const nextMeta = [...(item.searchMeta || []), ...currentMeta]\n if (nextMeta.length) {\n item.searchMeta = [...nextMeta]\n }\n\n if (item.items) {\n item.items = this.buildSearchMeta(item.items, currentMeta)\n }\n }\n\n results.push(item)\n }\n\n return results\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport {capitalCase} from \"change-case\"\nimport {join} from \"node:path\"\n\nimport type {RouteMetaInternal, RoutingStrategy} from \"../../../types\"\n\nimport {getRouteMeta} from \"./get-route-meta\"\n\nexport function getPathnameFromPathSegments(segments: string[]) {\n return `/${segments.join(\"/\")}`\n}\n\nexport function getCategoriesFromPathSegments(\n segments: string[],\n metaJson: RouteMetaInternal,\n // the frontmatter title only applies to the last segment.\n frontmatterTitle: string,\n): string[] {\n return segments.reduce((acc: string[], segment, index) => {\n const pathSegments = segments.slice(0, index + 1)\n if (index === segments.length - 1) {\n acc.push(frontmatterTitle)\n return acc\n }\n const meta = getRouteMeta(pathSegments, metaJson)\n if (meta?.title) {\n acc.push(meta.title)\n } else {\n acc.push(pathSegmentToCategory(segment))\n }\n return acc\n }, [])\n}\n\n// fallback for unmatched path segments\nexport function pathSegmentToCategory(segment: string): string {\n // we don't transform words like `a`, `or`, and `and`\n return segment\n .split(\"-\")\n .map((segment) =>\n /\\b(a|an|and|but|or|in|on|at)\\b/.test(segment)\n ? segment\n : capitalCase(segment),\n )\n .join(\" \")\n}\n\nfunction getGeneroutedPathSegments(filePath: string): string[] {\n const extension = filePath.endsWith(\"mdx\") ? \"mdx\" : \"tsx\"\n\n const segments = filePath\n .substring(0, filePath.lastIndexOf(`.${extension}`))\n .split(\"/\")\n\n if (segments[segments.length - 1] === \"index\") {\n return segments.slice(0, segments.length - 1)\n }\n return segments\n}\n\nconst pathSeparatorRegex = /[\\/\\\\.]/\nfunction isPathSeparator(char: string) {\n return pathSeparatorRegex.test(char)\n}\n\nconst indexRouteRegex =\n /((^|[.]|[+]\\/)(index|_index))(\\/[^\\/]+)?$|(\\/_?index\\/)/\n\nfunction getRemixFlatRoutesSegments(\n name: string,\n index: boolean,\n paramPrefixChar: string = \"$\",\n) {\n let routeSegments: string[] = []\n let i = 0\n let routeSegment = \"\"\n let state = \"START\"\n let subState = \"NORMAL\"\n let hasPlus = false\n\n // ignore layout routes\n if (name.endsWith(\"_layout\")) {\n return []\n }\n\n /*\n * name has already been normalized to use / as path separator.\n * replace `+/_.` with `_+/`\n * this supports the ability to specify parent folder will not be a layout.\n * _public+/_.about.tsx => _public_.about.tsx\n */\n if (/\\+\\/_\\./.test(name)) {\n name = name.replace(/\\+\\/_\\./g, \"_+/\")\n }\n\n /*\n * replace `+/` with `.`\n * this supports folders for organizing flat-files convention.\n * _public+/about.tsx => _public.about.tsx\n */\n if (/\\+\\//.test(name)) {\n name = name.replace(/\\+\\//g, \".\")\n hasPlus = true\n }\n const hasFolder = /\\//.test(name)\n // if name has plus folder, but we still have regular folders\n // then treat ending route as flat-folders\n if (\n ((hasPlus && hasFolder) || !hasPlus) &&\n !(name.endsWith(\".route\") || name.endsWith(\".index\"))\n ) {\n // Do not remove segments ending in .route\n // since these would be part of the route directory name\n // docs/readme.route.tsx => docs/readme\n // Remove last segment since this should just be the route filename, and we only\n // want the directory name docs/_layout.tsx => docs\n const last = name.lastIndexOf(\"/\")\n if (last >= 0) {\n name = name.substring(0, last)\n }\n }\n\n const pushRouteSegment = (routeSegment: string) => {\n if (routeSegment) {\n routeSegments.push(routeSegment)\n }\n }\n\n while (i < name.length) {\n const char = name[i]\n switch (state) {\n case \"START\":\n // process existing segment\n if (\n routeSegment.includes(paramPrefixChar) &&\n !(\n routeSegment.startsWith(paramPrefixChar) ||\n routeSegment.startsWith(`(${paramPrefixChar}`)\n )\n ) {\n throw new Error(\n `Route params must start with prefix char ${paramPrefixChar}: ${routeSegment}`,\n )\n }\n if (\n routeSegment.includes(\"(\") &&\n !routeSegment.startsWith(\"(\") &&\n !routeSegment.endsWith(\")\")\n ) {\n throw new Error(\n `Optional routes must start and end with parentheses: ${routeSegment}`,\n )\n }\n pushRouteSegment(routeSegment)\n routeSegment = \"\"\n state = \"PATH\"\n continue // restart without advancing index\n case \"PATH\":\n if (isPathSeparator(char) && subState === \"NORMAL\") {\n state = \"START\"\n break\n } else if (char === \"[\") {\n subState = \"ESCAPE\"\n break\n } else if (char === \"]\") {\n subState = \"NORMAL\"\n break\n }\n routeSegment += char\n break\n }\n i++ // advance to next character\n }\n // process remaining segment\n pushRouteSegment(routeSegment)\n // strip trailing .route segment\n if (\n routeSegments.at(-1) === \"route\" ||\n routeSegments.at(-1) === \"index\" ||\n routeSegments.at(-1) === \"_index\" ||\n routeSegments.at(-1) === \"_route\"\n ) {\n routeSegments = routeSegments.slice(0, -1)\n }\n // if hasPlus, we need to strip the trailing segment if it starts with _\n // and route is not an index route\n // this is to handle layouts in flat-files\n // _public+/_layout.tsx => _public.tsx\n // _public+/index.tsx => _public.index.tsx\n if (!index && hasPlus && routeSegments.at(-1)?.startsWith(\"_\")) {\n routeSegments = routeSegments.slice(0, -1)\n }\n return routeSegments\n}\n\nfunction getRemixHybridRoutesPathSegments(filePath: string): string[] {\n const routeWithoutExtension = filePath.substring(0, filePath.lastIndexOf(\".\"))\n\n return getRemixFlatRoutesSegments(\n routeWithoutExtension,\n indexRouteRegex.test(routeWithoutExtension),\n )\n}\n\nexport function getPathSegmentsFromFileName(\n filePath: string,\n pageDirectory: string,\n strategy?: RoutingStrategy,\n): string[] {\n const filePathWithoutPageDirectory = filePath.substring(\n filePath.indexOf(pageDirectory) + pageDirectory.length + 1,\n )\n if (typeof strategy === \"function\") {\n return strategy(filePathWithoutPageDirectory)\n }\n switch (strategy) {\n case \"vite-generouted\":\n return getGeneroutedPathSegments(filePathWithoutPageDirectory)\n default:\n return getRemixHybridRoutesPathSegments(filePathWithoutPageDirectory)\n }\n}\n\nexport function filterFileGlob(\n fileGlob: string[],\n ext: string,\n srcDir: string,\n router?: RoutingStrategy,\n): string[] {\n if (typeof router === \"string\" && router === \"vite-generouted\") {\n // vite-generouted: filter routes\n const restrictedPattern = /(\\(.*\\))|(\\[.*\\])/\n // pull out the full path before filtering to avoid potential issues with\n // parent directories.\n const relativeGlobs = fileGlob.map((file) => file.replace(srcDir, \"\"))\n return (\n relativeGlobs\n .filter(\n (file) =>\n file.endsWith(`.${ext}`) &&\n !file.includes(\"/_\") &&\n !file.includes(\"/+\"),\n )\n // filter pathless segments\n .map((file) =>\n file\n .split(\"/\")\n .filter((segment) => !restrictedPattern.test(segment))\n .join(\"/\"),\n )\n // restore full path\n .map((file) => join(srcDir, file))\n )\n }\n return fileGlob.filter((file) => file.endsWith(ext) && !file.includes(\"$\"))\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport type {NavConfig, NavMeta, RouteMeta, RouteMetaInternal} from \"../types\"\n\nexport function transformRouteMetaArray(\n meta: NavConfig[],\n routeMetaNav: Record<string, NavMeta>,\n): RouteMetaInternal {\n let ignoringOrder = 0\n return meta.reduce((acc: RouteMetaInternal, item, index) => {\n // strip the nav meta and populate a separate record. This will be used for\n // lookup while building the nav items.\n if (!(\"id\" in item)) {\n if (\"separator\" in item || \"sectionTitle\" in item) {\n // offset the navMeta index by the number of items that will be sorted to\n // the back of the nav order.\n routeMetaNav[index - ignoringOrder] = item\n }\n return acc\n }\n const current = item as RouteMeta\n if (current.ignoreRouteMetaOrder || current.hidden) {\n // items with ignored order are always sorted to the back of the nav order. We\n // need to account for this when splicing in the navMeta entries.\n ignoringOrder++\n }\n acc[current.id] = {\n children: current.children\n ? transformRouteMetaArray(current.children, routeMetaNav)\n : undefined,\n expanded: current.expanded,\n group: current.group,\n groupOrder: current.groupOrder,\n hidden: current.hidden,\n hideBreadcrumbs: current.hideBreadcrumbs,\n hideFromSearch: current.hideFromSearch,\n hidePageLinks: current.hidePageLinks,\n hideSideNav: current.hideSideNav,\n hideToc: current.hideToc,\n order: current.ignoreRouteMetaOrder ? undefined : index + 1,\n restricted: current.restricted,\n title: current.title,\n }\n return acc\n }, {})\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport {program} from \"@commander-js/extra-typings\"\nimport {mkdir, writeFile} from \"node:fs/promises\"\nimport {resolve} from \"node:path\"\n\nimport {getConfigFromEnv, KnowledgeApi, loadEnv} from \"./common\"\n\nexport function addDownloadKnowledgeCommand() {\n program\n .command(\"download-knowledge\")\n .description(\"Download files from an Open Web UI knowledge base\")\n .requiredOption(\"-o, --output-dir <outputDir>\", \"Folder path\")\n .action(async (opts) => {\n loadEnv()\n\n await mkdir(opts.outputDir, {recursive: true}).catch()\n\n const api = new KnowledgeApi(getConfigFromEnv())\n\n const knowledge = await api.listKnowledgeFiles()\n for (const file of knowledge.files) {\n const data = await api.downloadFile(file.id)\n\n if (data) {\n await writeFile(\n resolve(opts.outputDir, file.meta.name),\n data,\n \"utf-8\",\n )\n }\n }\n })\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport {program} from \"@commander-js/extra-typings\"\nimport {config} from \"dotenv\"\n\nimport type {GlobalCliOpts} from \"./types\"\n\nexport function loadEnv() {\n const options: GlobalCliOpts = program.optsWithGlobals()\n console.debug(options)\n if (options.env) {\n config({path: options.env})\n } else {\n config()\n }\n}\n\nexport interface SharedConfig {\n knowledgeId: string\n webUiKey: string\n webUiUrl: string\n}\n\nexport function getConfigFromEnv(): SharedConfig {\n const openWebUiUrl = process.env.WEB_UI_URL\n const openWebUiKey = process.env.WEB_UI_KEY\n const knowledgeId = process.env.KNOWLEDGE_ID\n\n if (!openWebUiUrl || !openWebUiKey || !knowledgeId) {\n throw new Error(\"WEB_UI_URL, WEB_UI_KEY, and KNOWLEDGE_ID must be set\")\n }\n return {\n knowledgeId,\n webUiKey: openWebUiKey,\n webUiUrl: openWebUiUrl,\n }\n}\n\nexport interface KnowledgeMeta {\n collection_name: string\n content_type: string\n data: Record<string, unknown>\n name: string\n size: number\n}\n\nexport interface KnowledgeResponse {\n files: {id: string; meta: KnowledgeMeta}[]\n}\n\nexport interface ErrorResponse {\n detail: string\n}\n\nexport class KnowledgeApi {\n private readonly config: SharedConfig\n private knowledgeCache: KnowledgeResponse | null = null\n\n constructor(config: SharedConfig) {\n this.config = config\n }\n\n get headers() {\n return {\n Authorization: `Bearer ${this.config.webUiKey}`,\n }\n }\n\n async listKnowledgeFiles() {\n if (this.knowledgeCache) {\n return this.knowledgeCache\n }\n const knowledge: KnowledgeResponse | ErrorResponse = await fetch(\n `${this.config.webUiUrl}/api/v1/knowledge/${this.config.knowledgeId}`,\n {\n headers: {\n ...this.headers,\n Accept: \"application/json\",\n },\n },\n ).then((res) => res.json())\n if (\"detail\" in knowledge) {\n throw new Error(knowledge.detail)\n } else {\n this.knowledgeCache = knowledge\n }\n return this.knowledgeCache\n }\n\n async downloadFile(fileId: string): Promise<string | null> {\n const fileResponse = await fetch(\n `${this.config.webUiUrl}/api/v1/files/${fileId}`,\n {\n headers: {\n ...this.headers,\n Accept: \"application/json\",\n },\n },\n ).then((res) => res.json())\n\n return fileResponse?.data?.content ?? \"\"\n }\n\n async removeKnowledgeFile(id: string) {\n return fetch(\n `${this.config.webUiUrl}/api/v1/knowledge/${this.config.knowledgeId}/file/remove`,\n {\n body: JSON.stringify({file_id: id}),\n headers: {\n ...this.headers,\n \"Content-Type\": \"application/json\",\n },\n method: \"POST\",\n },\n ).then((res) => res.json())\n }\n\n async deleteFile(id: string) {\n return fetch(`${this.config.webUiUrl}/api/v1/files/${id}`, {\n headers: {\n ...this.headers,\n \"Content-Type\": \"application/json\",\n },\n method: \"DELETE\",\n }).then((res) => res.json())\n }\n\n async uploadFile(\n fileBuffer: Buffer,\n name: string,\n ): Promise<{filename?: string; id?: string}> {\n const formData = new FormData()\n formData.append(\"file\", new Blob([fileBuffer as BlobPart]), name)\n formData.append(\"knowledge_id\", this.config.knowledgeId)\n\n return fetch(`${this.config.webUiUrl}/api/v1/files/`, {\n body: formData,\n headers: {\n ...this.headers,\n Accept: \"application/json\",\n },\n method: \"POST\",\n }).then((res) => res.json())\n }\n\n async associateFile(fileId: string): Promise<{name?: string}> {\n return fetch(\n `${this.config.webUiUrl}/api/v1/knowledge/${this.config.knowledgeId}/file/add`,\n {\n body: JSON.stringify({file_id: fileId}),\n headers: {\n ...this.headers,\n \"Content-Type\": \"application/json\",\n },\n method: \"POST\",\n },\n ).then((res) => res.json())\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport {program} from \"@commander-js/extra-typings\"\nimport {kebabCase} from \"change-case\"\nimport {\n access,\n mkdir,\n readdir,\n readFile,\n rm,\n stat,\n writeFile,\n} from \"node:fs/promises\"\nimport {basename, dirname, extname, join, resolve} from \"node:path\"\nimport remarkFrontmatter from \"remark-frontmatter\"\nimport remarkParse from \"remark-parse\"\nimport remarkParseFrontmatter from \"remark-parse-frontmatter\"\nimport remarkStringify from \"remark-stringify\"\nimport {unified} from \"unified\"\n\nimport type {\n QuiComment,\n QuiCommentDisplayPart,\n} from \"@qualcomm-ui/typedoc-common\"\n\nimport {remarkSelfLinkHeadings} from \"../docs-plugin\"\nimport {\n getPathnameFromPathSegments,\n getPathSegmentsFromFileName,\n} from \"../docs-plugin/internal\"\n\nimport {loadEnv} from \"./common\"\nimport {loadKnowledgeConfigFromEnv} from \"./load-config-from-env\"\nimport type {WebUiKnowledgeConfig} from \"./types\"\n\ninterface PageInfo {\n demosFolder?: string\n mdxFile: string\n name: string\n path: string\n url: string | undefined\n}\n\ninterface ProcessedPage {\n content: string\n demoFiles: string[]\n frontmatter: Record<string, string>\n title: string\n}\n\ninterface ImportedModule {\n content: string\n path: string\n}\n\ninterface ComponentProps {\n input?: PropInfo[]\n name: string\n output?: PropInfo[]\n props?: PropInfo[]\n}\n\ninterface DocProps {\n props: Record<string, ComponentProps>\n}\n\ninterface PropInfo {\n comment?: QuiComment\n defaultValue?: string\n name: string\n resolvedType?: {\n baseType?: string\n name?: string\n prettyType?: string\n required?: boolean\n type?: string\n }\n type: string\n}\n\ninterface SimplifiedProp {\n defaultValue?: string\n description: string\n name: string\n propType?: \"input\" | \"output\" | undefined\n required: boolean | undefined\n type: string\n}\n\nasync function exists(dirPath: string): Promise<boolean> {\n return access(dirPath)\n .then(() => true)\n .catch(() => false)\n}\n\nasync function loadDocProps(\n routesFolder: string,\n docPropsPath: string | undefined,\n verbose: boolean | undefined,\n): Promise<DocProps | null> {\n const resolvedDocPropsPath = docPropsPath\n ? (await exists(docPropsPath))\n ? docPropsPath\n : resolve(process.cwd(), docPropsPath)\n : join(dirname(routesFolder), \"doc-props.json\")\n\n if (!(await exists(resolvedDocPropsPath))) {\n if (verbose) {\n console.log(`Doc props file not found at: ${resolvedDocPropsPath}`)\n }\n return null\n }\n\n try {\n const content = await readFile(resolvedDocPropsPath, \"utf-8\")\n const docProps = JSON.parse(content) as DocProps\n if (verbose) {\n console.log(`Loaded doc props from: ${resolvedDocPropsPath}`)\n console.log(`Found ${Object.keys(docProps.props).length} component types`)\n }\n return docProps\n } catch (error) {\n if (verbose) {\n console.log(`Error loading doc props: ${error}`)\n }\n return null\n }\n}\n\nfunction formatComment(comment: QuiComment | null): string {\n if (!comment) {\n return \"\"\n }\n\n const parts: string[] = []\n\n // Format summary\n if (comment.summary && comment.summary.length > 0) {\n const summaryText = formatCommentParts(comment.summary)\n if (summaryText.trim()) {\n parts.push(summaryText.trim())\n }\n }\n\n // Format block tags\n if (comment.blockTags && comment.blockTags.length > 0) {\n for (const blockTag of comment.blockTags) {\n const tagContent = formatCommentParts(blockTag.content)\n if (tagContent.trim()) {\n const tagName = blockTag.tag.replace(\"@\", \"\")\n\n // Skip default tags since they're handled separately\n if (tagName === \"default\" || tagName === \"defaultValue\") {\n continue\n }\n\n // Special handling for other tags\n if (tagName === \"example\") {\n parts.push(`**Example:**\\n\\`\\`\\`\\n${tagContent.trim()}\\n\\`\\`\\``)\n } else {\n parts.push(`**${tagName}:** ${tagContent.trim()}`)\n }\n }\n }\n }\n\n return parts.join(\"\\n\\n\")\n}\n\nfunction formatCommentParts(parts: QuiCommentDisplayPart[]): string {\n return parts\n .map((part) => {\n switch (part.kind) {\n case \"text\":\n return part.text\n case \"code\":\n // Clean up malformed code blocks like \"```ts\\ntrue\\n```\"\n const codeText = part.text\n .replace(/```\\w*\\n?/g, \"\") // Remove opening code blocks with optional language\n .replace(/\\n?```/g, \"\") // Remove closing code blocks\n .trim()\n\n // If it's still multi-line after cleanup, use code block\n if (codeText.includes(\"\\n\")) {\n return `\\`\\`\\`\\n${codeText}\\n\\`\\`\\``\n } else {\n return codeText\n }\n default:\n if (\n \"tag\" in part &&\n part.tag === \"@link\" &&\n typeof part.target === \"string\"\n ) {\n return `[${part.text}](${part.target})`\n }\n return part.text\n }\n })\n .join(\"\")\n .replace(/\\n/g, \" \")\n .replace(/\\s+/g, \" \")\n .trim()\n}\n\nfunction convertPropInfo(\n propInfo: PropInfo,\n isPartial: boolean,\n propType: \"input\" | \"output\" | undefined = undefined,\n): SimplifiedProp {\n return {\n name: propInfo.name,\n type: extractBestType(propInfo),\n ...(propInfo.defaultValue && {\n defaultValue: cleanDefaultValue(propInfo.defaultValue),\n }),\n description: formatComment(propInfo.comment || null),\n propType,\n required: extractRequired(propInfo, isPartial) || undefined,\n }\n}\n\nfunction extractBestType(propInfo: PropInfo): string {\n const type = propInfo.resolvedType?.prettyType || propInfo.type\n\n return cleanType(type.startsWith(\"| \") ? type.substring(2) : type)\n}\n\nfunction extractRequired(propInfo: PropInfo, isPartial: boolean): boolean {\n return Boolean(propInfo.resolvedType?.required && !isPartial)\n}\n\nfunction cleanType(type: string): string {\n return type.replace(/\\n/g, \" \").replace(/\\s+/g, \" \").trim()\n}\n\nfunction cleanDefaultValue(defaultValue: string): string {\n return defaultValue.replace(/^\\n+/, \"\").replace(/\\n+$/, \"\").trim()\n}\n\nasync function scanPages(\n routesFolder: string,\n verbose: boolean | undefined,\n excludePatterns: string[] = [],\n baseUrl: string | undefined,\n): Promise<PageInfo[]> {\n const components: PageInfo[] = []\n\n function shouldExclude(dirPath: string): boolean {\n const dirName = basename(dirPath)\n return excludePatterns.some((pattern) => {\n if (pattern.includes(\"*\")) {\n const regex = new RegExp(`^${pattern.replace(/\\*/g, \".*\")}$`)\n return regex.test(dirName)\n }\n return dirName === pattern\n })\n }\n\n async function scanDirectory(dirPath: string): Promise<void> {\n if (shouldExclude(dirPath)) {\n if (verbose) {\n console.log(`Excluding directory: ${basename(dirPath)}`)\n }\n return\n }\n\n const entries = await readdir(dirPath, {withFileTypes: true})\n const mdxFiles = entries.filter((f) => f.name.endsWith(\".mdx\"))\n\n if (mdxFiles.length > 0) {\n const mdxFile = mdxFiles[0]\n const demosFolder = entries.find((f) => f.name === \"demos\")\n const demosFolderPath = demosFolder\n ? join(dirPath, demosFolder.name)\n : undefined\n\n // TODO: load routing strategy from qui-docs config.\n const segments = getPathSegmentsFromFileName(\n join(dirPath, mdxFile.name),\n routesFolder,\n )\n const url = getPathnameFromPathSegments(segments)\n\n components.push({\n demosFolder: demosFolderPath,\n mdxFile: join(dirPath, mdxFile.name),\n name: segments.at(-1)!,\n path: dirPath,\n url: baseUrl ? new URL(url, baseUrl).toString() : undefined,\n })\n\n if (verbose) {\n console.log(`Found component: ${basename(dirPath)}`)\n console.log(` Demos folder: ${demosFolderPath || \"NOT FOUND\"}`)\n }\n }\n\n for (const entry of entries) {\n const fullPath = join(dirPath, entry.name)\n const stats = await stat(fullPath)\n if (stats.isDirectory()) {\n await scanDirectory(fullPath)\n }\n }\n }\n\n await scanDirectory(routesFolder)\n return components\n}\n\nfunction isPreviewLine(trimmedLine: string): boolean {\n return (\n trimmedLine === \"// preview\" ||\n /^\\{\\s*\\/\\*\\s*preview\\s*\\*\\/\\s*\\}$/.test(trimmedLine) ||\n /^<!--\\s*preview\\s*-->$/.test(trimmedLine)\n )\n}\n\nfunction extractProps(\n props: ComponentProps,\n isPartial: boolean,\n): SimplifiedProp[] {\n const propsInfo: SimplifiedProp[] = []\n\n if (props.props?.length) {\n propsInfo.push(\n ...props.props.map((prop) => convertPropInfo(prop, isPartial)),\n )\n }\n if (props.input?.length) {\n propsInfo.push(\n ...props.input.map((prop) => convertPropInfo(prop, isPartial, \"input\")),\n )\n }\n if (props.output?.length) {\n propsInfo.push(\n ...props.output.map((prop) => convertPropInfo(prop, isPartial, \"output\")),\n )\n }\n\n return propsInfo\n}\n\nfunction removePreviewLines(code: string): string {\n return code\n .split(\"\\n\")\n .filter((line) => !isPreviewLine(line.trim()))\n .join(\"\\n\")\n}\n\nfunction getIntroLines(\n pages: Array<ProcessedPage>,\n projectName?: string,\n description?: string,\n baseUrl?: string,\n) {\n const lines: string[] = []\n\n if (projectName) {\n lines.push(`# ${projectName}`)\n lines.push(\"\")\n }\n\n if (description) {\n lines.push(`> ${description}`)\n lines.push(\"\")\n }\n\n lines.push(\"## Components and Integrations\")\n lines.push(\"\")\n\n for (const page of pages) {\n const url = baseUrl\n ? `${baseUrl}/${kebabCase(page.title)}`\n : `#${kebabCase(page.title)}`\n if (page.title.includes(\"Introduction\")) {\n lines.push(`- [${page.title}](${url}): introduction and getting started`)\n } else if (page.title.includes(\"Tailwind\")) {\n lines.push(\n `- [${page.title}](${url}): integration documentation and examples`,\n )\n } else {\n lines.push(\n `- [${page.title}](${url}): component documentation and examples`,\n )\n }\n }\n\n return lines.join(\"\\n\")\n}\n\nasync function generateLlmsTxt(\n pages: Array<ProcessedPage>,\n projectName?: string,\n description?: string,\n baseUrl?: string,\n): Promise<string> {\n const lines: string[] = [\n getIntroLines(pages, projectName, description, baseUrl),\n ]\n\n lines.push(\"## Documentation Content\")\n lines.push(\"\")\n\n for (const page of pages) {\n lines.push(`# ${page.title}`)\n lines.push(\"\")\n lines.push(page.content)\n lines.push(\"\")\n }\n\n return lines.join(\"\\n\")\n}\n\ninterface ProcessedPage {\n content: string\n demoFiles: string[]\n frontmatter: Record<string, string>\n title: string\n}\n\ninterface ImportedModule {\n content: string\n path: string\n}\n\nfunction extractRelativeImports(content: string): string[] {\n const imports: string[] = []\n const importRegex =\n /^import\\s+(?:{[^}]*}|[\\w*]+|\\*\\s+as\\s+\\w+)?\\s*(?:,\\s*{[^}]*})?\\s*from\\s+[\"'](\\.[^\"']+)[\"']/gm\n let match: RegExpExecArray | null\n while ((match = importRegex.exec(content)) !== null) {\n imports.push(match[1])\n }\n return imports\n}\n\nasync function resolveModulePath(\n importPath: string,\n fromFile: string,\n): Promise<string | null> {\n const fromDir = dirname(fromFile)\n const baseResolved = resolve(fromDir, importPath)\n const extensions = [\".ts\", \".tsx\", \".js\", \".jsx\", \"\"]\n for (const ext of extensions) {\n const fullPath = baseResolved + ext\n if (await exists(fullPath)) {\n return fullPath\n }\n }\n if (await exists(baseResolved)) {\n const indexPath = join(baseResolved, \"index.ts\")\n if (await exists(indexPath)) {\n return indexPath\n }\n }\n return null\n}\n\nasync function collectRelativeImports(\n filePath: string,\n visited: Set<string> = new Set(),\n verbose: boolean | undefined,\n): Promise<ImportedModule[]> {\n const normalizedPath = resolve(filePath)\n if (visited.has(normalizedPath)) {\n return []\n }\n visited.add(normalizedPath)\n const modules: ImportedModule[] = []\n try {\n const content = await readFile(normalizedPath, \"utf-8\")\n const relativeImports = extractRelativeImports(content)\n for (const importPath of relativeImports) {\n const resolvedPath = await resolveModulePath(importPath, normalizedPath)\n if (!resolvedPath) {\n if (verbose) {\n console.log(\n ` Could not resolve import: ${importPath} from ${normalizedPath}`,\n )\n }\n continue\n }\n const importContent = await readFile(resolvedPath, \"utf-8\")\n modules.push({\n content: importContent,\n path: resolvedPath,\n })\n const nestedModules = await collectRelativeImports(\n resolvedPath,\n visited,\n verbose,\n )\n modules.push(...nestedModules)\n }\n } catch (error) {\n if (verbose) {\n console.log(` Error processing ${normalizedPath}: ${error}`)\n }\n }\n return modules\n}\n\nasync function processMdxContent(\n mdxContent: string,\n pageUrl: string | undefined,\n demosFolder: string | undefined,\n docProps: DocProps | null,\n verbose: boolean | undefined,\n): Promise<{content: string; demoFiles: string[]}> {\n let processedContent = mdxContent\n const demoFiles: string[] = []\n\n const lines = processedContent.split(\"\\n\")\n const titleLine = lines.findIndex((line) => line.startsWith(\"# \"))\n processedContent =\n titleLine >= 0 ? lines.slice(titleLine + 1).join(\"\\n\") : processedContent\n if (pageUrl) {\n processedContent = processedContent.replace(\n /\\[([^\\]]+)\\]\\(\\.\\/#([^)]+)\\)/g,\n (_, text, anchor) => `[${text}](${pageUrl}#${anchor})`,\n )\n }\n if (docProps) {\n const typeDocRegex =\n /<TypeDocProps\\s+name=[\"']([^\"']+)[\"'](?:\\s+partial)?[^>]*\\/>/g\n processedContent = processedContent.replace(\n typeDocRegex,\n (match, propsName) => {\n const isPartial = /\\spartial(?:\\s|\\/|>)/.test(match)\n const componentProps = docProps.props[propsName]\n if (!componentProps) {\n if (verbose) {\n console.log(` TypeDocProps not found: ${propsName}`)\n }\n return \"\"\n }\n const propsDoc = extractProps(componentProps, isPartial)\n if (verbose) {\n console.log(\n ` Replaced TypeDocProps ${propsName} with API documentation`,\n )\n }\n return `**Component Props:**\\n\\`\\`\\`json\\n${JSON.stringify(propsDoc, null, 2)}\\n\\`\\`\\`\\n`\n },\n )\n } else {\n processedContent = processedContent.replace(/<TypeDocProps\\s+[^>]*\\/>/g, \"\")\n }\n let demoRegex = /<(?:QdsDemo|CodeDemo)\\s+[^>]*name=\"(\\w+)\"[^>]*\\/>/g\n let demoMatches = Array.from(processedContent.matchAll(demoRegex))\n if (!demoMatches.length) {\n demoRegex = /<(?:QdsDemo|CodeDemo)\\s+[^>]*node=\\{Demo\\.(\\w+)\\}[^>]*\\/>/g\n demoMatches = Array.from(processedContent.matchAll(demoRegex))\n }\n const replacements = await Promise.all(\n demoMatches.map(async (match) => {\n const [fullMatch, demoName] = match\n const kebabName = kebabCase(demoName)\n let filePath = `${kebabName}.tsx`\n if (!demosFolder) {\n if (verbose) {\n console.log(` No demos folder for ${demoName}`)\n }\n return {match: fullMatch, replacement: \"\"}\n }\n let demoFilePath = join(demosFolder, filePath)\n let isAngularDemo = false\n if (!(await exists(demoFilePath))) {\n demoFilePath = join(demosFolder, `${kebabName}.ts`)\n if (await exists(demoFilePath)) {\n isAngularDemo = true\n filePath = `${kebabCase(demoName).replace(\"-component\", \".component\")}.ts`\n demoFilePath = join(demosFolder, filePath)\n } else {\n console.log(` Demo not found ${demoName}`)\n return {match: fullMatch, replacement: \"\"}\n }\n }\n try {\n const demoCode = await readFile(demoFilePath, \"utf-8\")\n const cleanedCode = removePreviewLines(demoCode)\n const codeBlock = `\\`\\`\\`${isAngularDemo ? \"angular-ts\" : \"tsx\"}\\n${cleanedCode}\\`\\`\\``\n if (verbose) {\n console.log(` Replaced demo ${demoName} with source code`)\n }\n demoFiles.push(demoFilePath)\n return {match: fullMatch, replacement: codeBlock}\n } catch (error) {\n if (verbose) {\n console.log(` Error reading demo ${demoName}: ${error}`)\n }\n return {match: fullMatch, replacement: \"\"}\n }\n }),\n )\n for (const {match, replacement} of replacements) {\n processedContent = processedContent.replace(match, replacement)\n }\n processedContent = processedContent.replace(/\\n\\s*\\n\\s*\\n/g, \"\\n\\n\")\n return {content: processedContent, demoFiles}\n}\n\nasync function processComponent(\n component: PageInfo,\n docProps: DocProps | null,\n verbose: boolean | undefined,\n): Promise<ProcessedPage> {\n try {\n const mdxContent = await readFile(component.mdxFile, \"utf-8\")\n if (verbose) {\n console.log(`Processing page: ${component.name}`)\n }\n const processor = unified()\n .use(remarkParse)\n .use(remarkFrontmatter, [\"yaml\"])\n .use(remarkParseFrontmatter)\n .use(remarkSelfLinkHeadings(component.url))\n .use(remarkStringify)\n const parsed = await processor.process(mdxContent)\n const frontmatter = (parsed.data as any)?.frontmatter || {}\n const {content: processedContent, demoFiles} = await processMdxContent(\n String(parsed),\n component.url,\n component.demosFolder,\n docProps,\n verbose,\n )\n const contentWithoutFrontmatter = processedContent.replace(\n /^---[\\s\\S]*?---\\n/,\n \"\",\n )\n const title = frontmatter.title || component.name\n\n return {\n content: contentWithoutFrontmatter.trim(),\n demoFiles,\n frontmatter,\n title,\n }\n } catch (error) {\n console.error(`Error processing component ${component.name}:`, error)\n throw error\n }\n}\n\nasync function generatePerPageExports({\n includeImports,\n metadata,\n outputPath,\n pages,\n pageTitlePrefix,\n processedPages,\n verbose,\n}: {\n includeImports?: boolean\n metadata: string[][]\n outputPath: string\n pages: PageInfo[]\n pageTitlePrefix?: string\n processedPages: ProcessedPage[]\n verbose: boolean | undefined\n}) {\n await mkdir(dirname(outputPath), {recursive: true}).catch()\n const count = processedPages.length\n let totalSize = 0\n await Promise.all(\n processedPages.map(async (processedPage, index) => {\n const page = pages[index]\n const lines: string[] = []\n if (metadata.length || page.url) {\n lines.push(\"---\")\n if (page.url) {\n lines.push(`url: ${page.url}`)\n }\n if (metadata.length) {\n for (const [key, value] of metadata) {\n lines.push(`${key}: ${value}`)\n }\n }\n lines.push(\"---\")\n lines.push(\"\")\n }\n\n lines.push(`# ${processedPage.title}`)\n lines.push(\"\")\n if (processedPage.frontmatter?.title) {\n page.name = processedPage.frontmatter.title\n }\n let content = processedPage.content\n if (pageTitlePrefix) {\n content = content.replace(\n `# ${page.name}`,\n `# ${pageTitlePrefix} ${page.name}`,\n )\n page.name = `${pageTitlePrefix} ${page.name}`\n }\n lines.push(content)\n lines.push(\"\")\n\n if (includeImports && processedPage.demoFiles.length > 0) {\n if (verbose) {\n console.log(\n `Collecting imports for ${page.name} from ${processedPage.demoFiles.length} demo files`,\n )\n }\n\n const allImports: ImportedModule[] = []\n for (const demoFile of processedPage.demoFiles) {\n const imports = await collectRelativeImports(\n demoFile,\n new Set(),\n verbose,\n )\n allImports.push(...imports)\n }\n\n const uniqueImports = Array.from(\n new Map(allImports.map((m) => [m.path, m])).values(),\n )\n\n if (verbose) {\n console.log(\n ` Collected ${uniqueImports.length} unique import modules`,\n )\n }\n\n if (uniqueImports.length > 0) {\n lines.push(\"## Related Source Files\")\n lines.push(\"\")\n for (const importedModule of uniqueImports) {\n const ext = extname(importedModule.path).slice(1)\n lines.push(`### ${basename(importedModule.path)}`)\n lines.push(\"\")\n lines.push(`\\`\\`\\`${ext}`)\n lines.push(importedModule.content)\n lines.push(\"```\")\n lines.push(\"\")\n }\n }\n }\n\n const outfile = `${resolve(outputPath)}/${kebabCase(page.name)}.md`\n await writeFile(outfile, lines.join(\"\\n\"), \"utf-8\")\n const stats = await stat(outfile)\n totalSize += stats.size / 1024\n }),\n )\n console.log(`Generated ${count} component(s) in ${outputPath}`)\n console.log(`Folder size: ${totalSize.toFixed(1)} KB`)\n}\n\nfunction extractMetadata(metadata: string[] | undefined): string[][] {\n return (metadata ?? []).map((current) => {\n const [key, value] = current.split(\"=\")\n return [key, value]\n })\n}\n\nexport async function generate({\n baseUrl,\n clean,\n description,\n docPropsPath,\n exclude,\n includeImports,\n metadata,\n name,\n outputMode,\n outputPath,\n pageTitlePrefix,\n routeDir,\n verbose,\n}: WebUiKnowledgeConfig): Promise<void> {\n const extractedMetadata = extractMetadata(metadata)\n if (verbose) {\n console.log(`Scanning pages in: ${routeDir}`)\n if (exclude?.length) {\n console.log(`Excluding patterns: ${exclude.join(\", \")}`)\n }\n }\n const [docProps, pages] = await Promise.all([\n loadDocProps(routeDir, docPropsPath, verbose),\n scanPages(routeDir, verbose, exclude, baseUrl),\n ])\n if (pages.length === 0) {\n console.log(\"No pages found.\")\n return\n }\n if (verbose) {\n console.log(`Found ${pages.length} page(s)`)\n }\n const processedPages: ProcessedPage[] = []\n for (const page of pages) {\n try {\n const processed = await processComponent(page, docProps, verbose)\n processedPages.push(processed)\n } catch (error) {\n console.error(`Failed to process page: ${page.name}`)\n process.exit(1)\n }\n }\n if (clean) {\n await rm(outputPath, {force: true, recursive: true}).catch()\n }\n if (outputMode === \"aggregated\") {\n const llmsTxtContent = await generateLlmsTxt(\n processedPages,\n name,\n description,\n baseUrl,\n )\n await mkdir(dirname(outputPath), {recursive: true}).catch()\n await writeFile(outputPath, llmsTxtContent, \"utf-8\")\n const outputStats = await stat(outputPath)\n const outputSizeKb = (outputStats.size / 1024).toFixed(1)\n console.log(\n `Generated ${outputPath} with ${pages.length} component(s) at: ${outputPath}`,\n )\n console.log(`File size: ${outputSizeKb} KB`)\n } else {\n await mkdir(outputPath, {recursive: true}).catch()\n await generatePerPageExports({\n includeImports,\n metadata: extractedMetadata,\n outputPath,\n pages,\n pageTitlePrefix,\n processedPages,\n verbose,\n })\n }\n}\n\nexport function addGenerateKnowledgeCommand() {\n program\n .description(\"Generate llms.txt from QUI Docs documentation\")\n .command(\"generate-llms-txt\")\n .option(\"-n, --name <name>\", \"Project name for llms.txt header\")\n .requiredOption(\"-m, --output-mode <outputMode>\")\n .option(\"-o, --outputPath <outputPath>\", \"Output file or directory.\")\n .option(\n \"-d, --description <description>\",\n \"Project description for llms.txt\",\n )\n .option(\"-v, --verbose\", \"Enable verbose logging\", false)\n .option(\n \"--exclude <patterns...>\",\n \"Exclude folder patterns (supports * wildcards)\",\n [],\n )\n .option(\"--base-url <url>\", \"Base URL for component documentation links\")\n .option(\"--metadata <pairs...>\", \"metadata key-value pairs\")\n .option(\"--clean\", \"Clean the output path before generating\")\n .option(\"--include-imports\", \"Include relative import source files\", true)\n .action(async (options) => {\n loadEnv()\n const knowledgeConfig = loadKnowledgeConfigFromEnv({\n ...options,\n outputMode:\n options.outputMode === \"per-page\" ? \"per-page\" : \"aggregated\",\n })\n await generate(knowledgeConfig)\n })\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport chalk from \"chalk\"\nimport chokidar from \"chokidar\"\nimport {glob} from \"glob\"\nimport {readFileSync} from \"node:fs\"\nimport {resolve} from \"node:path\"\nimport prettyMilliseconds from \"pretty-ms\"\nimport type {PluginOption, ViteDevServer} from \"vite\"\n\nimport type {QuiPropTypes} from \"@qualcomm-ui/typedoc-common\"\n\nimport {\n ConfigLoader,\n fixPath,\n type ResolvedQuiDocsConfig,\n SearchIndexer,\n} from \"./internal\"\n\nconst isDev = process.env.NODE_ENV === \"development\"\n\ninterface ChangeOptions {\n onComplete?: () => void\n}\n\nexport interface QuiDocsPluginOptions {\n /**\n * Path to the qui-docs config file. This is automatically detected if omitted.\n */\n configFile?: string\n\n /**\n * The current working directory.\n *\n * @default process.cwd()\n */\n cwd?: string\n}\n\nconst VIRTUAL_MODULE_ID = \"\\0@qualcomm-ui/mdx-vite-plugin\"\n\n/**\n * TODO: adjust when https://github.com/vitejs/vite/discussions/16358 lands.\n */\nclass PluginState {\n buildCount: number = 0\n configFilePath: string = \"\"\n docPropsFilePath: string = \"\"\n indexer!: SearchIndexer\n configLoader: ConfigLoader | null = null\n routesDir!: string\n servers: ViteDevServer[] = []\n timeout: ReturnType<typeof setTimeout> | undefined = undefined\n watching = false\n\n private cwd!: string\n\n init(cwd: string) {\n this.cwd = cwd\n }\n\n get docPropsDirectory() {\n if (!this.docPropsFilePath) {\n return \"\"\n }\n return this.docPropsFilePath.substring(\n 0,\n this.docPropsFilePath.lastIndexOf(\"/\"),\n )\n }\n\n private resolveDocProps(): Record<string, QuiPropTypes> {\n if (!this.docPropsFilePath) {\n return {}\n }\n try {\n return JSON.parse(readFileSync(this.docPropsFilePath, \"utf-8\"))?.props\n } catch (e) {\n console.debug(\n \"Invalid doc props file. Unable to parse JSON. Please check the file\",\n )\n return {}\n }\n }\n\n createIndexer(config: ResolvedQuiDocsConfig) {\n this.configFilePath = config.filePath\n this.docPropsFilePath = config.typeDocProps\n ? fixPath(resolve(this.cwd, config.typeDocProps))\n : \"\"\n this.routesDir = fixPath(resolve(config.appDirectory, config.pageDirectory))\n this.indexer = new SearchIndexer({\n ...config,\n srcDir: fixPath(resolve(this.cwd, config.appDirectory)),\n typeDocProps: this.resolveDocProps(),\n })\n }\n\n buildIndex(shouldLog: boolean) {\n const files = glob.sync(\n [`${this.routesDir}/**/*.mdx`, `${this.routesDir}/**/*.tsx`],\n {\n absolute: true,\n cwd: this.cwd,\n },\n )\n\n if (!files.length) {\n return\n }\n\n const startTime = Date.now()\n\n this.indexer.buildIndex(files, shouldLog)\n\n if (isDev && shouldLog) {\n console.debug(\n `${chalk.magenta.bold(`@qualcomm-ui/mdx-vite/docs-plugin:`)} Compiled search index in: ${chalk.blueBright.bold(prettyMilliseconds(Date.now() - startTime))}${state.indexer.cachedFileCount ? chalk.greenBright.bold(` (${state.indexer.cachedFileCount}/${state.indexer.mdxFileCount} files cached)`) : \"\"}`,\n )\n }\n }\n\n /**\n * When the user adds or removes mdx files, we re-index the site. This function\n * handles module invalidation so that virtual file imports are refreshed as\n * expected by the consumer's dev server.\n */\n sendUpdate() {\n for (const server of this.servers) {\n const virtualModule = server.moduleGraph.getModuleById(VIRTUAL_MODULE_ID)\n if (virtualModule) {\n server.moduleGraph.invalidateModule(virtualModule)\n server.reloadModule(virtualModule)\n }\n }\n }\n\n handleChange(opts: ChangeOptions = {}) {\n // the plugin is activating twice in dev mode. It's mostly harmless, but we\n // prevent logs from emitting twice by flipping a flag\n\n // debounce the change handler to prevent rapid updates from triggering rebuilds\n // in quick succession.\n clearTimeout(this.timeout)\n this.timeout = setTimeout(() => {\n this.buildIndex(true)\n this.sendUpdate()\n opts?.onComplete?.()\n }, 300)\n }\n\n initWatchers(configFile?: string) {\n if (this.watching) {\n return\n }\n this.initConfigWatcher(configFile)\n this.watching = true\n }\n\n private initConfigWatcher(configFile?: string) {\n const paths: string[] = [this.configFilePath]\n if (this.docPropsFilePath) {\n paths.push(this.docPropsFilePath)\n }\n chokidar\n .watch(paths, {\n cwd: this.cwd,\n })\n .on(\"change\", () => {\n console.debug(`qui-docs config changed, reloading plugin`)\n this.configLoader = new ConfigLoader({configFile})\n const resolvedConfig = this.configLoader.loadConfig()\n this.configFilePath = resolvedConfig.filePath\n this.createIndexer(resolvedConfig)\n this.handleChange()\n })\n }\n}\n\nconst state = new PluginState()\n\nexport function quiDocsPlugin(opts?: QuiDocsPluginOptions): PluginOption {\n state.init(fixPath(opts?.cwd ?? process.cwd()))\n\n // https://vitejs.dev/guide/api-plugin#virtual-modules-convention\n\n const configLoader = new ConfigLoader(opts || {})\n const config = configLoader.loadConfig()\n state.createIndexer(config)\n\n return {\n buildStart: async () => {\n state.buildIndex(state.buildCount > 0)\n state.buildCount++\n },\n configureServer: (server) => {\n if (!isDev) {\n return\n }\n state.initWatchers(opts?.configFile)\n server.watcher.on(\"add\", (path: string) => {\n if (path.endsWith(\".mdx\")) {\n state.handleChange({\n onComplete: () => {\n server.ws.send({type: \"full-reload\"})\n },\n })\n }\n })\n server.watcher.on(\"unlink\", (path: string) => {\n if (path.endsWith(\".mdx\")) {\n state.handleChange({\n onComplete: () => {\n server.ws.send({type: \"full-reload\"})\n },\n })\n }\n })\n state.servers.push(server)\n },\n handleHotUpdate: async ({file: updateFile, modules, server}) => {\n const file = fixPath(updateFile)\n\n if (\n (!config.hotUpdateIgnore || !config.hotUpdateIgnore.test(file)) &&\n // ignore watched files. We watch for these separately.\n file !== state.configFilePath\n ) {\n if (\n state.docPropsDirectory &&\n file.startsWith(state.docPropsFilePath)\n ) {\n return []\n }\n\n state.buildIndex(true)\n if (updateFile.endsWith(\".mdx\")) {\n // invalidate the plugin module so that the virtual file is refreshed\n const virtualModule =\n server.moduleGraph.getModuleById(VIRTUAL_MODULE_ID)\n if (virtualModule) {\n server.moduleGraph.invalidateModule(virtualModule)\n }\n }\n }\n\n return modules\n },\n load: (id): string | undefined => {\n if (id === VIRTUAL_MODULE_ID) {\n return `export const siteData = ${JSON.stringify({navItems: state.indexer.navItems, pageDocProps: state.indexer.pageDocProps, pageMap: state.indexer.pageMap, searchIndex: state.indexer.searchIndex})}`\n }\n return undefined\n },\n name: \"qui-mdx-vite-plugin\",\n resolveId: (id) => {\n if (id === \"@qualcomm-ui/mdx-vite-plugin\") {\n return VIRTUAL_MODULE_ID\n }\n return undefined\n },\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport rehypeShiki, {type RehypeShikiOptions} from \"@shikijs/rehype\"\nimport type {PluggableList} from \"unified\"\n\nimport {quiCustomDarkTheme} from \"@qualcomm-ui/mdx-common\"\n\nimport {\n rehypeMdxCodeProps,\n remarkFrontmatter,\n remarkGfm,\n remarkMdxFrontmatter,\n} from \"../exports\"\n\nimport {ConfigLoader, type ConfigLoaderOptions} from \"./internal\"\nimport {rehypeSectionize, rehypeSlug, type RehypeSlugOptions} from \"./rehype\"\nimport {remarkAlerts, remarkCodeTabs, remarkSpoilers} from \"./remark\"\n\n/**\n * @deprecated migrate to the {@link getRehypePlugins} function\n */\nexport const quiRehypePlugins: PluggableList = [rehypeSectionize, rehypeSlug]\n\nexport interface QuiRehypePluginOptions extends ConfigLoaderOptions {\n rehypeShikiOptions?: Partial<RehypeShikiOptions>\n}\n\n/**\n * Used to retrieve all the rehype plugins required for QUI Docs MDX.\n * These should be passed to the `mdx` vite plugin from\n */\nexport function getRehypePlugins(\n options: QuiRehypePluginOptions = {},\n): PluggableList {\n const config = new ConfigLoader(options).loadConfig()\n return [\n rehypeMdxCodeProps,\n [\n rehypeSlug,\n {allowedHeadings: config.headings} satisfies RehypeSlugOptions,\n ],\n rehypeSectionize,\n [\n rehypeShiki,\n {\n defaultColor: \"light-dark()\",\n themes: {\n dark: quiCustomDarkTheme,\n light: \"github-light-high-contrast\",\n },\n ...options.rehypeShikiOptions,\n } satisfies RehypeShikiOptions,\n ],\n ]\n}\n\n/**\n * @deprecated migrate to the {@link getRemarkPlugins} function\n */\nexport const quiRemarkPlugins: PluggableList = [remarkAlerts, remarkCodeTabs]\n\n/**\n * @returns every remark plugin needed for QUI Docs MDX.\n *\n * @example\n * ```ts\n * // in your vite config\n * plugins: [\n * mdx({\n * providerImportSource: \"@mdx-js/react\",\n * rehypePlugins: [...getRehypePlugins()],\n * remarkPlugins: [...getRemarkPlugins()],\n * }),\n * quiDocsPlugin(),\n * // ... the rest of your plugins\n * ]\n * ```\n */\nexport function getRemarkPlugins(): PluggableList {\n return [\n remarkFrontmatter,\n remarkMdxFrontmatter,\n remarkGfm,\n remarkAlerts,\n remarkCodeTabs,\n remarkSpoilers,\n ]\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport rehypeMdxCodeProps from \"rehype-mdx-code-props\"\nimport remarkFrontmatter from \"remark-frontmatter\"\nimport remarkGfm from \"remark-gfm\"\nimport remarkMdxFrontmatter from \"remark-mdx-frontmatter\"\n\nimport {rehypeSlug} from \"./docs-plugin/rehype/rehype-slug\"\n\n// Re-export these peerDependencies for more convenient imports.\n// Some of these are not included in the bundled JS, so the user must install them\n// separately.\nexport {\n remarkFrontmatter,\n remarkGfm,\n remarkMdxFrontmatter,\n rehypeMdxCodeProps,\n rehypeSlug,\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport type {Element, Root, RootContent} from \"hast\"\nimport {heading} from \"hast-util-heading\"\nimport {headingRank} from \"hast-util-heading-rank\"\nimport type {Properties} from \"hastscript\"\nimport type {Plugin} from \"unified\"\n\nexport type RehypeSectionizeOptions = {\n enableRootSection?: boolean | undefined\n idPropertyName?: string | undefined\n properties?: Properties | undefined\n rankPropertyName?: string | undefined\n}\n\nconst defaultOptions: Required<RehypeSectionizeOptions> = {\n enableRootSection: false,\n idPropertyName: \"ariaLabelledby\",\n properties: {},\n rankPropertyName: \"dataHeadingRank\",\n}\n\nconst wrappingRank = (\n rootContent: RootContent | undefined,\n rankPropertyName: RehypeSectionizeOptions[\"rankPropertyName\"],\n) => {\n if (\n rootContent == null ||\n rankPropertyName == null ||\n !(\"properties\" in rootContent)\n ) {\n throw new Error(\"rootContent and rankPropertyName must have value\")\n }\n\n const rank = rootContent.properties?.[rankPropertyName]\n if (typeof rank !== \"number\") {\n throw new Error(`rankPropertyName(${rankPropertyName}) must be number`)\n }\n\n return rank\n}\n\nconst createElement = (\n rank: number,\n options: Pick<\n RehypeSectionizeOptions,\n \"properties\" | \"rankPropertyName\" | \"idPropertyName\"\n >,\n children: Element[] = [],\n) => {\n const {idPropertyName, properties, rankPropertyName} = options\n\n if (\n properties != null &&\n rankPropertyName != null &&\n rankPropertyName in properties\n ) {\n throw new Error(\n `rankPropertyName(${rankPropertyName}) dataHeadingRank must exist`,\n )\n }\n\n const id = children.at(0)?.properties?.id\n const element: Element = {\n children,\n properties: {\n className: [\"heading\"],\n ...(rankPropertyName ? {[rankPropertyName]: rank} : {}),\n ...(idPropertyName && typeof id === \"string\"\n ? {[idPropertyName]: id}\n : {}),\n ...(properties ? properties : {}),\n },\n tagName: \"section\",\n type: \"element\",\n }\n\n return element\n}\n\nexport const rehypeSectionize: Plugin<[RehypeSectionizeOptions?], Root> = (\n options = defaultOptions,\n) => {\n const {enableRootSection, ...rest} = {\n enableRootSection:\n options.enableRootSection ?? defaultOptions.enableRootSection,\n idPropertyName: options.idPropertyName ?? defaultOptions.idPropertyName,\n properties: options.properties ?? defaultOptions.properties,\n rankPropertyName:\n options.rankPropertyName ?? defaultOptions.rankPropertyName,\n }\n\n return (root) => {\n const rootWrapper = createElement(0, rest)\n\n const wrapperStack: RootContent[] = []\n wrapperStack.push(rootWrapper)\n\n const lastStackItem = () => {\n const last = wrapperStack.at(-1)\n if (last == null || last.type !== \"element\") {\n throw new Error(\"lastStackItem must be Element\")\n }\n return wrapperStack.at(-1) as Element\n }\n\n for (const rootContent of root.children) {\n if (heading(rootContent)) {\n const rank = headingRank(rootContent)\n if (rank == null) {\n throw new Error(\"heading or headingRank is not working\")\n }\n\n if (rank > wrappingRank(lastStackItem(), rest.rankPropertyName)) {\n const childWrapper = createElement(rank, rest, [rootContent])\n lastStackItem().children.push(childWrapper)\n wrapperStack.push(childWrapper)\n } else if (\n rank <= wrappingRank(lastStackItem(), rest.rankPropertyName)\n ) {\n while (rank <= wrappingRank(lastStackItem(), rest.rankPropertyName)) {\n wrapperStack.pop()\n }\n const siblingWrapper = createElement(rank, rest, [rootContent])\n\n lastStackItem().children.push(siblingWrapper)\n wrapperStack.push(siblingWrapper)\n }\n } else {\n if (rootContent.type === \"doctype\") {\n throw new Error(\"must be used in a fragment\")\n }\n lastStackItem().children.push(rootContent as any)\n }\n }\n\n return {\n ...root,\n children: enableRootSection ? [rootWrapper] : rootWrapper.children,\n }\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport type {Code, Parent, Root} from \"mdast\"\nimport type {Plugin} from \"unified\"\nimport {visit} from \"unist-util-visit\"\n\ninterface Tab {\n index: number\n label: string\n meta: string | undefined\n tabsGroup: string\n}\n\nfunction parseTabAttributes(meta: string): {\n label: string | null\n remainingMeta: string\n tabsGroup: string | null\n} {\n if (!meta) {\n return {label: null, remainingMeta: \"\", tabsGroup: null}\n }\n\n const tabsMatch = meta.match(/tabs=[\"']([^\"']+)[\"']|tabs=(\\S+)/)\n const labelMatch = meta.match(/label=[\"']([^\"']+)[\"']|label=(\\S+)/)\n\n const tabsGroup = tabsMatch ? tabsMatch[1] || tabsMatch[2] : null\n const label = labelMatch ? labelMatch[1] || labelMatch[2] : null\n\n // Remove both tabs and label attributes from meta\n const remainingMeta = meta\n .replace(/\\s*tabs=[\"']([^\"']+)[\"']/g, \"\")\n .replace(/\\s*tabs=(\\S+)/g, \"\")\n .replace(/\\s*label=[\"']([^\"']+)[\"']/g, \"\")\n .replace(/\\s*label=(\\S+)/g, \"\")\n .trim()\n\n return {label, remainingMeta, tabsGroup}\n}\n\nfunction findConsecutiveTabs(\n startIndex: number,\n parent: Parent,\n targetTabsGroup: string,\n): Tab[] {\n const tabs: Tab[] = []\n let currentIndex = startIndex\n\n while (currentIndex < parent.children.length) {\n const currentNode = parent.children[currentIndex]\n\n if (!currentNode || currentNode.type !== \"code\") {\n break\n }\n\n const codeNode = currentNode\n\n if (!codeNode.meta) {\n break\n }\n\n const {label, remainingMeta, tabsGroup} = parseTabAttributes(codeNode.meta)\n\n // Only include if it matches the target tabs group and has a label\n if (!tabsGroup || !label || tabsGroup !== targetTabsGroup) {\n break\n }\n\n // Clean the original node's meta NOW\n codeNode.meta = remainingMeta || undefined\n\n tabs.push({\n index: currentIndex,\n label,\n meta: remainingMeta || undefined,\n tabsGroup,\n })\n\n if (remainingMeta && remainingMeta.includes(\"end\")) {\n break\n }\n\n currentIndex++\n }\n\n return tabs\n}\n\nfunction renderTabs(tabs: Tab[], parent: Parent): any[] {\n const tabsContainer = {\n attributes: [],\n children: [] as any[],\n name: \"CodeTabs\",\n type: \"mdxJsxFlowElement\",\n }\n\n tabs.forEach((tab) => {\n const codeNode = parent.children[tab.index] as Code\n\n const tabAttributes = [\n {\n name: \"label\",\n type: \"mdxJsxAttribute\",\n value: tab.label,\n },\n ]\n\n // Add meta to JSX element if it exists\n if (tab.meta) {\n tabAttributes.push({\n name: \"meta\",\n type: \"mdxJsxAttribute\",\n value: tab.meta,\n })\n }\n\n const tabElement = {\n attributes: tabAttributes,\n children: [\n {\n lang: codeNode.lang,\n meta: codeNode.meta, // This is now clean\n type: \"code\",\n value: codeNode.value,\n },\n ],\n name: \"CodeTab\",\n type: \"mdxJsxFlowElement\",\n }\n\n tabsContainer.children.push(tabElement)\n })\n\n return [tabsContainer]\n}\n\n/**\n * Very cool. TODO: document this https://docs.qui.qualcomm.com/guide/markdown\n */\nexport const remarkCodeTabs: Plugin<[], Root> = () => {\n return (tree) => {\n const transformations: Array<{\n endIndex: number\n parent: Parent\n replacement: any[]\n startIndex: number\n }> = []\n\n visit(\n tree,\n \"code\",\n (node: Code, index: number | undefined, parent: Parent | undefined) => {\n if (!node.meta || !parent || index === undefined) {\n return\n }\n\n const {label, tabsGroup} = parseTabAttributes(node.meta)\n if (!tabsGroup || !label) {\n return\n }\n\n const alreadyProcessed = transformations.some(\n (t) =>\n t.parent === parent && index >= t.startIndex && index < t.endIndex,\n )\n\n if (alreadyProcessed) {\n return\n }\n\n const tabs = findConsecutiveTabs(index, parent, tabsGroup)\n\n if (tabs.length > 1) {\n const startIndex = tabs[0].index\n const endIndex = tabs[tabs.length - 1].index + 1\n const newChildren = renderTabs(tabs, parent)\n\n transformations.push({\n endIndex,\n parent,\n replacement: newChildren,\n startIndex,\n })\n }\n },\n )\n\n transformations\n .sort((a, b) => b.startIndex - a.startIndex)\n .forEach((transformation) => {\n transformation.parent.children.splice(\n transformation.startIndex,\n transformation.endIndex - transformation.startIndex,\n ...transformation.replacement,\n )\n })\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport type {Heading, Link, Root} from \"mdast\"\nimport {toString} from \"mdast-util-to-string\"\nimport type {Plugin} from \"unified\"\nimport {visit} from \"unist-util-visit\"\n\nexport interface RemarkSelfLinkOptions {\n /**\n * @default [2, 3, 4]\n */\n allowedLevels?: number[]\n prefix?: string\n}\n\nconst emptyOptions: RemarkSelfLinkOptions = {}\n\nexport function remarkSelfLinkHeadings(\n baseUrl: string = \"\",\n options?: RemarkSelfLinkOptions | null,\n): Plugin<[], Root> {\n if (!baseUrl) {\n return () => {}\n }\n return () => {\n const settings = options || emptyOptions\n const prefix = settings.prefix || \"\"\n const allowedLevels = new Set<number>(settings.allowedLevels || [2, 3, 4])\n const seenIds = new Map<string, number>()\n\n function createSlug(text: string): string {\n const cleaned = text\n .replace(/[<>]/g, \"\")\n .replace(/[^\\w\\s-]/g, \"\")\n .trim()\n\n let slug: string\n if (cleaned.includes(\" \")) {\n slug = cleaned\n .toLowerCase()\n .replace(/\\s+/g, \"-\")\n .replace(/^-+|-+$/g, \"\")\n } else if ((cleaned.match(/[A-Z]/g) || []).length >= 2) {\n slug = cleaned\n .replace(/([a-z0-9])([A-Z])/g, \"$1-$2\")\n .replace(/([A-Z]+)([A-Z][a-z])/g, \"$1-$2\")\n .toLowerCase()\n } else {\n slug = cleaned.toLowerCase()\n }\n\n const count = seenIds.get(slug) || 0\n seenIds.set(slug, count + 1)\n return count > 0 ? `${slug}-${count}` : slug\n }\n\n return (tree) => {\n seenIds.clear()\n visit(tree, \"heading\", (node: Heading) => {\n if (allowedLevels.has(node.depth)) {\n const text = toString(node)\n const slug = prefix + createSlug(text)\n\n const linkNode: Link = {\n children: node.children,\n type: \"link\",\n url: `${baseUrl}#${slug}`,\n }\n\n node.children = [linkNode]\n }\n })\n }\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport type {BlockContent, Root} from \"mdast\"\nimport type {Plugin} from \"unified\"\nimport {visit} from \"unist-util-visit\"\n\ninterface SpoilerOptions {\n defaultSummary?: string\n detailsClassName?: string[]\n summaryClassName?: string[]\n}\n\n/**\n * Transforms spoiler blocks into MDX components.\n *\n * @example\n * ```\n * ::: spoiler Title\n *\n * Content\n *\n * :::\n * ```\n *\n * result:\n *\n * ```jsx\n * <SpoilerRoot>\n * <SpoilerTrigger><p>Title</p></SpoilerTrigger>\n * <SpoilerContent>Content</SpoilerContent>\n * </SpoilerRoot>\n * ```\n */\nexport const remarkSpoilers: Plugin<[SpoilerOptions?], Root> = (\n options = {},\n) => {\n const {\n defaultSummary = \"Open spoiler\",\n detailsClassName = [],\n summaryClassName = [],\n } = options\n\n return (tree) => {\n visit(tree, \"paragraph\", (node, index, parent) => {\n if (!parent || index === undefined) {\n return\n }\n\n const firstChild = node.children[0]\n if (firstChild?.type !== \"text\") {\n return\n }\n\n const match = firstChild.value.match(/^:::\\s*spoiler\\s*(.*)$/)\n if (!match) {\n return\n }\n\n const summary = match[1].trim() || defaultSummary\n let endIndex = index + 1\n const contentNodes: BlockContent[] = []\n\n while (endIndex < parent.children.length) {\n const child = parent.children[endIndex]\n\n if (child.type === \"paragraph\") {\n const firstText = child.children[0]\n if (firstText?.type === \"text\" && firstText.value.trim() === \":::\") {\n break\n }\n }\n\n contentNodes.push(child as BlockContent)\n endIndex++\n }\n\n if (endIndex >= parent.children.length) {\n return\n }\n\n const summaryNode: BlockContent = {\n attributes: summaryClassName.length\n ? [\n {\n name: \"className\",\n type: \"mdxJsxAttribute\",\n value: summaryClassName.join(\" \"),\n },\n ]\n : [],\n children: [\n {\n children: [{type: \"text\", value: summary}],\n type: \"paragraph\",\n },\n ],\n name: \"SpoilerSummary\",\n type: \"mdxJsxFlowElement\",\n }\n\n const contentNode: BlockContent = {\n attributes: [],\n children: contentNodes,\n name: \"SpoilerContent\",\n type: \"mdxJsxFlowElement\",\n }\n\n const detailsNode: BlockContent = {\n attributes: detailsClassName.length\n ? [\n {\n name: \"className\",\n type: \"mdxJsxAttribute\",\n value: detailsClassName.join(\" \"),\n },\n ]\n : [],\n children: [summaryNode, contentNode],\n name: \"SpoilerRoot\",\n type: \"mdxJsxFlowElement\",\n }\n\n parent.children.splice(index, endIndex - index + 1, detailsNode)\n })\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport {existsSync} from \"node:fs\"\nimport {join, resolve} from \"node:path\"\n\nimport {ConfigLoader} from \"../docs-plugin/internal\"\n\nimport type {CliConfig, WebUiKnowledgeConfig} from \"./types\"\n\nexport function loadKnowledgeConfigFromEnv(\n options: CliConfig,\n): WebUiKnowledgeConfig {\n const knowledgeId = process.env.KNOWLEDGE_ID\n const exclude =\n options.exclude || (process.env.FILE_EXCLUDE_PATTERN ?? \"\").split(\",\")\n const outputPath = options.outputPath || process.env.KNOWLEDGE_OUTPUT_PATH\n const prefix = process.env.PAGE_TITLE_PREFIX\n\n if (!knowledgeId) {\n throw new Error(\"Missing required KNOWLEDGE_ID environment variable\")\n }\n\n if (!outputPath) {\n throw new Error(\"Missing required outputPath\")\n }\n\n const configLoader = new ConfigLoader({})\n const resolvedConfig = configLoader.loadConfig()\n\n const routeDir = join(\n resolvedConfig.appDirectory,\n resolvedConfig.pageDirectory,\n )\n\n if (!existsSync(resolve(routeDir))) {\n throw new Error(`Route directory ${routeDir} does not exist`)\n }\n\n return {\n ...options,\n baseUrl: options.baseUrl || process.env.DOCS_SITE_BASE_URL,\n docPropsPath: resolvedConfig.typeDocProps,\n exclude,\n knowledgeId,\n outputPath,\n pageTitlePrefix: prefix,\n routeDir,\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport {program} from \"@commander-js/extra-typings\"\nimport {createHash} from \"node:crypto\"\nimport {\n access,\n mkdir,\n readdir,\n readFile,\n stat,\n writeFile,\n} from \"node:fs/promises\"\nimport {resolve} from \"node:path\"\nimport {setTimeout} from \"node:timers/promises\"\nimport ora from \"ora\"\n\nimport {\n getConfigFromEnv,\n KnowledgeApi,\n loadEnv,\n type SharedConfig,\n} from \"./common\"\n\ninterface Config extends SharedConfig {\n force: boolean\n knowledgeFilePath: string\n}\n\n/**\n * Calculates the MD5 checksum of a file.\n */\nfunction calculateFileHash(fileData: string) {\n const normalized = fileData\n .normalize(\"NFC\") // Normalize Unicode to canonical form\n .replace(/\\r\\n/g, \"\\n\")\n .replace(/\\r/g, \"\\n\")\n .replace(/\\n+$/, \"\") // Remove trailing newline\n return createHash(\"sha256\").update(normalized).digest(\"hex\")\n}\n\nclass Uploader {\n private config: Config\n readonly api: KnowledgeApi\n\n constructor(config: Config) {\n this.config = config\n this.api = new KnowledgeApi(config)\n }\n\n get headers() {\n return {\n Authorization: `Bearer ${this.config.webUiKey}`,\n }\n }\n\n private async uploadDirectory() {\n const fileNames = await readdir(this.config.knowledgeFilePath)\n const files = await Promise.all(\n fileNames.map(async (name) => ({\n contents: await readFile(\n resolve(this.config.knowledgeFilePath, name),\n \"utf-8\",\n ),\n name,\n })),\n )\n const skippedFiles: string[] = []\n let successCount = 0\n let failureCount = 0\n // fill cache\n await this.api.listKnowledgeFiles()\n\n for (const file of files) {\n let result = await this.uploadFile(file.name, file.contents)\n while (!result.success && result.count && result.count < 5) {\n console.debug(\"Failed to upload, retrying with count: \", result.count)\n await setTimeout(100)\n result = await this.uploadFile(file.name, file.contents, result.count)\n }\n if (result.skipped) {\n skippedFiles.push(file.name)\n }\n if (result.success) {\n successCount++\n } else {\n failureCount++\n }\n }\n\n if (skippedFiles.length > 0) {\n console.debug(\n `Skipped uploading ${skippedFiles.length} files because their contents did not change`,\n )\n }\n const uploadCount = successCount - skippedFiles.length\n if (uploadCount) {\n console.debug(`Successfully uploaded ${uploadCount} files`)\n }\n if (failureCount > 0) {\n console.debug(`Failed to upload ${failureCount} files`)\n }\n }\n\n private async uploadFile(\n name: string,\n contents: string,\n count = 0,\n ): Promise<{\n count?: number\n skipped?: boolean\n success: boolean\n }> {\n const knowledge = await this.api.listKnowledgeFiles()\n const knowledgeFile = (knowledge.files ?? []).find(\n (f) => f.meta.name === name,\n )\n\n if (knowledgeFile) {\n console.debug(\"Found existing file:\", knowledgeFile?.meta.name)\n\n const data = await this.api.downloadFile(knowledgeFile.id)\n\n if (!this.config.force && data) {\n if (calculateFileHash(data) === calculateFileHash(contents)) {\n return {skipped: true, success: true}\n }\n\n await mkdir(resolve(process.cwd(), `./temp/diff`), {\n recursive: true,\n }).catch()\n await writeFile(\n resolve(process.cwd(), `./temp/diff/${name}-current.md`),\n contents,\n \"utf-8\",\n )\n await writeFile(\n resolve(process.cwd(), `./temp/diff/${name}-owui.md`),\n data,\n \"utf-8\",\n )\n\n const dataLines = data.split(\"\\n\")\n const contentLines = contents.split(\"\\n\")\n\n if (dataLines.length === contentLines.length) {\n const allLinesMatch = dataLines.every(\n (line, i) => line === contentLines[i],\n )\n if (allLinesMatch) {\n return {skipped: true, success: true}\n }\n }\n }\n }\n\n const fileBuffer = await readFile(\n resolve(this.config.knowledgeFilePath, name),\n )\n\n if (knowledgeFile) {\n await this.api.removeKnowledgeFile(knowledgeFile.id)\n console.log(`Removed existing file: ${name}`)\n }\n\n const spinner = ora(`Uploading ${name}`).start()\n\n const uploadResponse = await this.api.uploadFile(fileBuffer, name)\n\n if (!uploadResponse.id || !uploadResponse.filename) {\n spinner.fail(`Error uploading ${name}, exiting`)\n console.debug(uploadResponse)\n return {success: false}\n }\n\n // give the upload time to register on the backend\n await setTimeout(500)\n\n spinner.text = `Associating ${name} with knowledge base`\n\n const addResponse = await this.api.associateFile(uploadResponse.id)\n\n if (addResponse.name) {\n spinner.succeed(`${name} associated with knowledge base`)\n return {success: true}\n } else {\n spinner.fail(`Failed to associate ${name} with knowledge base`)\n console.debug(addResponse)\n return {count: count + 1, success: false}\n }\n }\n\n async uploadKnowledge() {\n const resolvedPath = resolve(this.config.knowledgeFilePath)\n if (\n !(await access(resolvedPath)\n .then(() => true)\n .catch(() => false))\n ) {\n throw new Error(`File or folder not found at ${resolvedPath}`)\n }\n const stats = await stat(resolvedPath)\n if (stats.isDirectory()) {\n return this.uploadDirectory()\n } else {\n // TODO: add\n }\n }\n}\n\nexport function addUploadKnowledgeCommand() {\n program\n .name(\"upload-knowledge\")\n .description(\"Upload files to OpenWebUI knowledge base\")\n .command(\"upload-knowledge\")\n .option(\"-p, --path <path>\", \"Path to file or folder relative to script\")\n .option(\n \"--force\",\n \"force upload files, even if their contents have not changed\",\n )\n .action(async (options) => {\n loadEnv()\n\n const sharedConfig = getConfigFromEnv()\n\n const knowledgeFilePath =\n options.path || process.env.KNOWLEDGE_OUTPUT_PATH\n\n if (!knowledgeFilePath) {\n throw new Error(\n \"KNOWLEDGE_FILE_PATH must be set or provided as the --path option\",\n )\n }\n\n const uploader = new Uploader({\n ...sharedConfig,\n force: options.force || false,\n knowledgeFilePath,\n })\n\n return uploader.uploadKnowledge()\n })\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport {program} from \"@commander-js/extra-typings\"\nimport {glob} from \"glob\"\nimport {uniqBy} from \"lodash-es\"\nimport {writeFile} from \"node:fs/promises\"\nimport {resolve} from \"node:path\"\n\nimport {dedent} from \"@qualcomm-ui/utils/dedent\"\n\nimport {extractPageId, isDemoFile} from \"./demo-plugin-utils\"\n\ninterface DemoPage {\n pageId: string\n routePath: string\n}\n\nexport interface DemoScanConfig {\n /**\n * @default \"src/routes/**\\/demos/*.tsx\"\n */\n demoPattern?: string\n\n /**\n * The directory where the routes are located. Must be relative to the project\n * root. The demoPattern should start with this directory:\n *\n * @example\n * ```js\n * {\n * demoPattern = \"src/routes/**\\/demos/*.tsx\",\n * routesDir = \"src/routes\",\n * }\n * ```\n */\n routesDir?: string\n}\n\nasync function scanForDemoPages({\n demoPattern = \"src/routes/**/demos/*.tsx\",\n routesDir = \"src/routes\",\n}: DemoScanConfig): Promise<DemoPage[]> {\n const demoFiles = (await glob(demoPattern)).filter((file) => isDemoFile(file))\n\n return uniqBy(\n demoFiles.map((file) => ({\n pageId: extractPageId(file, routesDir),\n routePath: file\n .replace(routesDir, \"\")\n .replace(/\\/demos\\/.*\\.tsx$/, \"\")\n .replace(/\\+/g, \"\"),\n })),\n (page) => page.pageId,\n )\n}\n\nfunction generateLazyDemoLoader(demoPages: DemoPage[]): string {\n const imports = demoPages\n .map(({pageId, routePath}) => {\n return ` \"${routePath}\": () =>\\n import(\"virtual:qui-demo-scope/page:${pageId}\")`\n })\n .sort()\n .join(\",\\n\")\n\n return dedent`\n /* eslint-disable */\n\n // This file is generated automatically. Don't edit it directly.\n\n import type {ReactDemoWithScope} from \"@qualcomm-ui/mdx-common\"\n\n export const lazyDemos: Record<\n string,\n () => Promise<{getDemo(name: string): ReactDemoWithScope | undefined}>\n > = {\n ${imports},\n }\n\n`\n}\n\nasync function generateLazyDemoMap(options: {\n output: string\n routesDir: string\n}) {\n const routesDir = options.routesDir\n const outputPath = resolve(options.output)\n\n console.log(`Scanning for demo pages in: ${routesDir}`)\n\n const demoPages = await scanForDemoPages({routesDir})\n\n console.log(`Found ${demoPages.length} pages with demos`)\n\n const content = generateLazyDemoLoader(demoPages)\n\n await writeFile(outputPath, content, \"utf-8\")\n\n console.log(`\\nGenerated lazy demo loader at: ${outputPath}`)\n}\n\nexport function addGenerateLazyDemoMapCommand() {\n program\n .command(\"generate-lazy-demo-map\")\n .description(\"Scan for pages with demos and generate lazy demo loader\")\n .requiredOption(\n \"-r, --routes-dir <path>\",\n \"Path to the routes directory (e.g., src/routes)\",\n )\n .requiredOption(\n \"-o, --output <path>\",\n \"Output path for the lazy demo loader file\",\n )\n .action(async (options) => {\n try {\n await generateLazyDemoMap(options)\n } catch (error) {\n console.error(\n \"Error:\",\n error instanceof Error ? error.message : String(error),\n )\n process.exit(1)\n }\n })\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport chalk from \"chalk\"\nimport {existsSync, readFileSync} from \"node:fs\"\nimport {readFile} from \"node:fs/promises\"\nimport {dirname, join, relative, resolve, sep} from \"node:path\"\nimport * as ts from \"typescript\"\n\nimport {pascalCase} from \"@qualcomm-ui/utils/change-case\"\n\nimport {LOG_PREFIX, NODE_BUILTINS} from \"./demo-plugin-constants\"\n\ninterface PathAlias {\n pattern: RegExp\n replacement: string\n}\n\nexport interface ImportSpecifier {\n source: string\n specifiers: Array<{\n imported: string\n local: string\n }>\n type: \"thirdParty\"\n}\n\nexport interface RelativeImport {\n resolvedPath: string\n source: string\n specifiers: Array<{\n imported: string\n local: string\n }>\n type: \"relative\"\n}\n\n/**\n * Demo names are created using the PascalCase format of the file name without the\n * extension.\n */\nexport function createDemoName(filePath: string): string {\n const separatorChar = filePath.includes(\"/\") ? \"/\" : \"\\\\\"\n const fileName = filePath.substring(\n filePath.lastIndexOf(separatorChar),\n filePath.lastIndexOf(\".\"),\n )\n if (!fileName) {\n throw new Error(`Failed to create demo name for ${filePath}`)\n }\n return pascalCase(fileName)\n}\n\nexport async function extractFileImports(filePath: string): Promise<{\n relativeImports: RelativeImport[]\n thirdPartyImports: ImportSpecifier[]\n} | null> {\n try {\n const content = await readFile(filePath, \"utf-8\")\n return extractImports(content, filePath)\n } catch (error) {\n console.log(\n `${chalk.magenta.bold(LOG_PREFIX)} ${chalk.yellowBright(\"Failed to parse\")} ${chalk.blueBright.bold(filePath)}:`,\n error,\n )\n return null\n }\n}\n\nfunction extractImports(\n code: string,\n fileName: string,\n): {\n relativeImports: RelativeImport[]\n thirdPartyImports: ImportSpecifier[]\n} {\n const sourceFile = ts.createSourceFile(\n fileName,\n code,\n ts.ScriptTarget.Latest,\n true,\n getScriptKind(fileName),\n )\n const thirdPartyImports: ImportSpecifier[] = []\n const relativeImports: RelativeImport[] = []\n\n function visit(node: ts.Node) {\n if (ts.isImportDeclaration(node)) {\n const importSpec = parseImportDeclaration(node, fileName)\n if (importSpec) {\n if (importSpec.type === \"relative\") {\n relativeImports.push(importSpec)\n } else {\n thirdPartyImports.push(importSpec)\n }\n }\n }\n ts.forEachChild(node, visit)\n }\n\n visit(sourceFile)\n return {relativeImports, thirdPartyImports}\n}\n\nexport function getScriptKind(fileName: string): ts.ScriptKind {\n return fileName.endsWith(\".tsx\") || fileName.endsWith(\".jsx\")\n ? ts.ScriptKind.TSX\n : ts.ScriptKind.TS\n}\n\nfunction parseImportDeclaration(\n node: ts.ImportDeclaration,\n fileName: string,\n): ImportSpecifier | RelativeImport | null {\n const moduleSpecifier = node.moduleSpecifier\n if (!ts.isStringLiteral(moduleSpecifier)) {\n return null\n }\n\n const source = moduleSpecifier.text\n if (node.importClause?.isTypeOnly) {\n return null\n }\n\n const specifiers = extractSpecifiers(node.importClause)\n if (specifiers.length === 0) {\n return null\n }\n\n if (isRelativeImport(source)) {\n const resolvedPath = resolveRelativeImport(source, fileName)\n return {\n resolvedPath,\n source,\n specifiers,\n type: \"relative\",\n }\n }\n\n if (isNodeBuiltin(source)) {\n return null\n }\n\n const pathAliases = loadTsConfigPaths(fileName)\n if (isPathAliasImport(source, pathAliases)) {\n const resolvedPath = resolvePathAlias(source, pathAliases)\n if (resolvedPath) {\n return {\n resolvedPath,\n source,\n specifiers,\n type: \"relative\",\n }\n }\n }\n\n return {\n source,\n specifiers,\n type: \"thirdParty\",\n }\n}\n\nfunction extractSpecifiers(\n importClause: ts.ImportClause | undefined,\n): Array<{imported: string; local: string}> {\n if (!importClause) {\n return []\n }\n\n const specifiers: Array<{imported: string; local: string}> = []\n\n if (importClause.name) {\n specifiers.push({imported: \"default\", local: \"default\"})\n }\n\n if (importClause.namedBindings) {\n if (ts.isNamespaceImport(importClause.namedBindings)) {\n specifiers.push({imported: \"*\", local: \"*\"})\n } else if (ts.isNamedImports(importClause.namedBindings)) {\n importClause.namedBindings.elements.forEach((element) => {\n if (!element.isTypeOnly) {\n const imported = element.propertyName\n ? element.propertyName.text\n : element.name.text\n const local = element.name.text\n specifiers.push({imported, local})\n }\n })\n }\n }\n\n return specifiers\n}\n\nfunction resolveRelativeImport(source: string, fromFile: string): string {\n const fromDir = dirname(fromFile)\n const resolved = resolve(fromDir, source)\n\n const extensions = [\".ts\", \".tsx\", \".js\", \".jsx\"]\n for (const ext of extensions) {\n const withExt = resolved + ext\n if (existsSync(withExt)) {\n return withExt\n }\n }\n\n for (const ext of extensions) {\n const indexFile = join(resolved, `index${ext}`)\n if (existsSync(indexFile)) {\n return indexFile\n }\n }\n\n return resolved\n}\n\nfunction isRelativeImport(source: string): boolean {\n return source.startsWith(\"./\") || source.startsWith(\"../\")\n}\n\nfunction isNodeBuiltin(source: string): boolean {\n return source.startsWith(\"node:\") || NODE_BUILTINS.includes(source)\n}\n\nfunction loadTsConfigPaths(fromFile: string): PathAlias[] {\n let currentDir = dirname(fromFile)\n const pathAliases: PathAlias[] = []\n\n while (currentDir !== dirname(currentDir)) {\n const tsconfigPath = join(currentDir, \"tsconfig.json\")\n if (existsSync(tsconfigPath)) {\n try {\n const configContent = ts.sys.readFile(tsconfigPath)\n if (!configContent) {\n currentDir = dirname(currentDir)\n continue\n }\n\n const parseResult = ts.parseConfigFileTextToJson(\n tsconfigPath,\n configContent,\n )\n if (parseResult.error) {\n currentDir = dirname(currentDir)\n continue\n }\n\n const paths = parseResult.config?.compilerOptions?.paths\n const baseUrl = parseResult.config?.compilerOptions?.baseUrl || \"./\"\n const resolvedBaseUrl = resolve(currentDir, baseUrl)\n\n if (paths) {\n for (const [alias, targets] of Object.entries(paths)) {\n if (Array.isArray(targets) && targets.length > 0) {\n const target = targets[0]\n const pattern = new RegExp(\n `^${alias\n .replace(\"*\", \"(.*)\")\n .replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\")\n .replace(\"\\\\(\\\\*\\\\)\", \"(.*)\")}$`,\n )\n const replacement = resolve(\n resolvedBaseUrl,\n target.replace(\"*\", \"$1\"),\n )\n pathAliases.push({pattern, replacement})\n }\n }\n }\n\n const extendsPath = parseResult.config?.extends\n if (extendsPath) {\n const resolvedExtends = resolve(currentDir, extendsPath)\n const extendedAliases = loadTsConfigPathsFromFile(resolvedExtends)\n pathAliases.push(...extendedAliases)\n }\n\n return pathAliases\n } catch (error) {\n currentDir = dirname(currentDir)\n continue\n }\n }\n currentDir = dirname(currentDir)\n }\n\n return pathAliases\n}\n\nfunction loadTsConfigPathsFromFile(tsconfigPath: string): PathAlias[] {\n const pathAliases: PathAlias[] = []\n const configDir = dirname(tsconfigPath)\n\n try {\n const configContent = ts.sys.readFile(tsconfigPath)\n if (!configContent) {\n return pathAliases\n }\n\n const parseResult = ts.parseConfigFileTextToJson(\n tsconfigPath,\n configContent,\n )\n if (parseResult.error) {\n return pathAliases\n }\n\n const paths = parseResult.config?.compilerOptions?.paths\n const baseUrl = parseResult.config?.compilerOptions?.baseUrl || \"./\"\n const resolvedBaseUrl = resolve(configDir, baseUrl)\n\n if (paths) {\n for (const [alias, targets] of Object.entries(paths)) {\n if (Array.isArray(targets) && targets.length > 0) {\n const target = targets[0]\n const pattern = new RegExp(\n `^${alias\n .replace(\"*\", \"(.*)\")\n .replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\")\n .replace(\"\\\\(\\\\*\\\\)\", \"(.*)\")}$`,\n )\n const replacement = resolve(\n resolvedBaseUrl,\n target.replace(\"*\", \"$1\"),\n )\n pathAliases.push({pattern, replacement})\n }\n }\n }\n\n const extendsPath = parseResult.config?.extends\n if (extendsPath) {\n let resolvedExtends = resolve(configDir, extendsPath)\n if (!resolvedExtends.endsWith(\".json\")) {\n resolvedExtends += \".json\"\n }\n if (existsSync(resolvedExtends)) {\n const extendedAliases = loadTsConfigPathsFromFile(resolvedExtends)\n pathAliases.push(...extendedAliases)\n }\n }\n } catch (error) {\n return pathAliases\n }\n\n return pathAliases\n}\n\nfunction isPathAliasImport(source: string, pathAliases: PathAlias[]): boolean {\n return pathAliases.some((alias) => alias.pattern.test(source))\n}\n\nfunction resolvePathAlias(\n source: string,\n pathAliases: PathAlias[],\n): string | null {\n for (const alias of pathAliases) {\n if (alias.pattern.test(source)) {\n const resolvedPath = source.replace(alias.pattern, alias.replacement)\n const extensions = [\".ts\", \".tsx\", \".js\", \".jsx\"]\n\n for (const ext of extensions) {\n const withExt = resolvedPath + ext\n if (existsSync(withExt)) {\n return withExt\n }\n }\n\n for (const ext of extensions) {\n const indexFile = join(resolvedPath, `index${ext}`)\n if (existsSync(indexFile)) {\n return indexFile\n }\n }\n\n return resolvedPath\n }\n }\n return null\n}\n\nexport function extractPageId(filePath: string, routesDir: string): string {\n const relativePath = relative(routesDir, filePath)\n const pathParts = relativePath.split(sep)\n if (pathParts.includes(\"demos\")) {\n const demosIndex = pathParts.indexOf(\"demos\")\n return pathParts.slice(0, demosIndex).join(sep)\n }\n return dirname(relativePath)\n}\n\nexport function isCssAsset(filePath: string) {\n return filePath.endsWith(\".css\")\n}\n\nexport function isDemoFile(filePath: string): boolean {\n try {\n return (\n filePath.includes(\"/demos/\") &&\n filePath.endsWith(\".tsx\") &&\n !readFileSync(filePath).includes(\"export default\")\n )\n } catch (error) {\n return false\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport {program} from \"@commander-js/extra-typings\"\n\nimport {addGeneratePageMapCommand} from \"./docs-plugin/generate-page-map\"\nimport {addDownloadKnowledgeCommand} from \"./open-web-ui-knowledge/download-knowledge\"\nimport {addGenerateKnowledgeCommand} from \"./open-web-ui-knowledge/generate-knowledge\"\nimport {addUploadKnowledgeCommand} from \"./open-web-ui-knowledge/upload-knowledge\"\nimport {addGenerateLazyDemoMapCommand} from \"./react-demo-plugin/generate-lazy-demo-map\"\n\nfunction setupCli() {\n // global options\n program.option(\"--env <envFile>\", \"relative path to the env file to use\")\n\n addGenerateKnowledgeCommand()\n addUploadKnowledgeCommand()\n addDownloadKnowledgeCommand()\n addGenerateLazyDemoMapCommand()\n addGeneratePageMapCommand()\n\n program.parse()\n}\n\nsetupCli()\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAGA,QAAMA,kBAAN,cAA6B,MAAM;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,MAOjC,YAAY,UAAU,MAAM,SAAS;AACnC,cAAM,OAAO;AAEb,cAAM,kBAAkB,MAAM,KAAK,WAAW;AAC9C,aAAK,OAAO,KAAK,YAAY;AAC7B,aAAK,OAAO;AACZ,aAAK,WAAW;AAChB,aAAK,cAAc;AAAA,MACrB;AAAA,IACF;AAKA,QAAMC,wBAAN,cAAmCD,gBAAe;AAAA;AAAA;AAAA;AAAA;AAAA,MAKhD,YAAY,SAAS;AACnB,cAAM,GAAG,6BAA6B,OAAO;AAE7C,cAAM,kBAAkB,MA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A,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC,OAAO,OAAO,YAAY;AACzB,QAAI;AACF,YAAM,oBAAoB,OAAO;AAAA,IACnC,SAAS,OAAO;AACd,cAAQ;AAAA,QACN;AAAA,QACA,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAAA,MACvD;AACA,cAAQ,KAAK,CAAC;AAAA,IAChB;AAAA,EACF,CAAC;AACL;;;AElHA,SAAS,WAAW;AAElB,UAAQ,OAAO,mBAAmB,sCAAsC;AAExE,8BAA4B;AAC5B,4BAA0B;AAC1B,8BAA4B;AAC5B,gCAA8B;AAC9B,4BAA0B;AAE1B,UAAQ,MAAM;AAChB;AAEA,SAAS;",
6
+ "names": ["CommanderError", "InvalidArgumentError", "InvalidArgumentError", "Argument", "Help", "cmd", "heading", "InvalidArgumentError", "Option", "heading", "str", "process", "Argument", "CommanderError", "Help", "Option", "Command", "config", "defined", "option", "heading", "path", "Argument", "Command", "CommanderError", "InvalidArgumentError", "Help", "Option", "extraTypingsCommander", "z", "z", "z", "z", "config", "chalk", "entry", "propTypes", "heading", "remarkParse", "remarkStringify", "unified", "unified", "remarkParse", "remarkStringify", "remarkMdx", "remarkParse", "unified", "visit", "visit", "item", "remove", "heading", "unified", "remarkMdx", "remarkParse", "capitalCase", "segment", "capitalCase", "state", "routeSegment", "config", "chalk", "writeFile", "resolve", "config", "writeFile", "resolve", "mkdir", "writeFile", "join", "resolve", "remarkFrontmatter", "remarkParse", "remarkParseFrontmatter", "remarkStringify", "unified", "chalk", "glob", "readFileSync", "resolve", "cwd", "readFileSync", "config", "resolve", "glob", "chalk", "remarkFrontmatter", "remarkGfm", "headingRank", "visit", "toString", "visit", "emptyOptions", "visit", "join", "resolve", "join", "resolve", "resolve", "join", "unified", "remarkParse", "remarkFrontmatter", "remarkParseFrontmatter", "remarkStringify", "mkdir", "writeFile", "createHash", "access", "mkdir", "readdir", "readFile", "stat", "writeFile", "resolve", "setTimeout", "createHash", "config", "readdir", "readFile", "resolve", "setTimeout", "mkdir", "writeFile", "access", "stat", "glob", "writeFile", "resolve", "chalk", "existsSync", "readFileSync", "dirname", "join", "resolve", "dirname", "readFileSync", "glob", "resolve", "writeFile"]
7
7
  }